1!function(){try{var e="u">typeof window?window:"u">typeof global?global:"u">typeof globalThis?globalThis:"u">typeof self?self:{},t=(new e.Error).stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="87afa073-607b-4fba-9f26-d34a4b8c2c89",e._sentryDebugIdIdentifier="sentry-dbid-87afa073-607b-4fba-9f26-d34a4b8c2c89")}catch(e){}}(),(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[986,2602,9325],{2532:(e,t,a)=>{"use strict";a.d(t,{Lo:()=>f,SnapModeProvider:()=>h,WA:()=>p,h3:()=>u});var r=a(95155),n=a(12115);let i=(0,n.createContext)(void 0),s="autoShorts_magnetModeEnabled",o="autoShorts_gridModeEnabled",l="autoShorts_gridIntervalSeconds",d="autoShorts_gridAutoEnabled",c="autoShorts_overlapPolicy",u=[1/30,.05,.1,.25,.5,1,2,5];function p(e){let t=Number.isFinite(e)&&e>0?e:1;for(let e of u)if(e*t>=16)return e;return u[u.length-1]}function m(e){if(!Number.isFinite(e)||e<=0)return 1;let t=u[0],a=Math.abs(e-t);for(let r of u){let n=Math.abs(e-r);n<a&&(t=r,a=n)}return t}function h({children:e}){let[t,a]=(0,n.useState)(()=>{try{let e=localStorage.getItem(s);if(null!==e)return"true"===e;let t=localStorage.getItem("autoShorts_snapModeEnabled");return null===t||"true"===t}catch{return!0}}),[u,p]=(0,n.useState)(()=>{try{let e=localStorage.getItem(o);return null!==e&&"true"===e}catch{return!1}}),[f,g]=(0,n.useState)(()=>{try{let e=localStorage.getItem(l);if(null===e)return 1;let t=Number(e);return m(t)}catch{return 1}}),[x,b]=(0,n.useState)(()=>{try{let e=localStorage.getItem(d);if(null!==e)return"true"===e;return null===localStorage.getItem(l)}catch{return!0}});(0,n.useEffect)(()=>{try{localStorage.setItem(s,String(t))}catch(e){console.warn("[SnapMode] Failed to persist magnet mode to localStorage:",e)}},[t]),(0,n.useEffect)(()=>{try{localStorage.setItem(o,String(u))}catch(e){console.warn("[SnapMode] Failed to persist grid mode to localStorage:",e)}},[u]),(0,n.useEffect)(()=>{try{localStorage.setItem(l,String(f))}catch(e){console.warn("[SnapMode] Failed to persist grid interval to localStorage:",e)}},[f]);
1let[y,v]=(0,n.useState)(()=>{try{let e=localStorage.getItem(c);return"stay"===e?"stay":"bump"}catch{return"bump"}});return(0,n.useEffect)(()=>{try{localStorage.setItem(d,String(x))}catch(e){console.warn("[SnapMode] Failed to persist auto grid to localStorage:",e)}},[x]),(0,n.useEffect)(()=>{try{localStorage.setItem(c,y)}catch(e){console.warn("[SnapMode] Failed to persist overlap policy to localStorage:",e)}},[y]),(0,r.jsx)(i.Provider,{value:{isMagnetEnabled:t,isGridEnabled:u,gridIntervalSeconds:f,isGridAuto:x,overlapPolicy:y,toggleMagnetMode:()=>{a(e=>{let t=!e;return console.log(`[SnapMode] Magnet: ${e?"ON":"OFF"} â ${t?"ON":"OFF"}`),t})},toggleGridMode:()=>{p(e=>{let t=!e;return console.log(`[SnapMode] Grid: ${e?"ON":"OFF"} â ${t?"ON":"OFF"}`),t})},setGridIntervalSeconds:e=>{b(!1),g(t=>{let a=m(e);return a===t?t:a})},setGridAuto:e=>{b(e)},setOverlapPolicy:e=>{v("stay"===e?"stay":"bump")}},children:e})}function f(){let e=(0,n.useContext)(i);if(void 0===e)throw Error("useSnapMode must be used within a SnapModeProvider");return e}},7372:(e,t,a)=>{"use strict";a.d(t,{eg:()=>n,fU:()=>r});let r=e=>{if(isNaN(e)||e<0)return"0:00.00";let t=Math.floor(e/60),a=Math.floor(e%60),r=Math.floor(e%1*100);return`${t}:${a.toString().padStart(2,"0")}.${r.toString().padStart(2,"0")}`},n=e=>{if(isNaN(e)||e<0)return"0:00";let t=Math.floor(e/60),a=Math.floor(e%60);return`${t}:${a.toString().padStart(2,"0")}`}},20986:(e,t,a)=>{"use strict";a.d(t,{A:()=>dI});var r=a(95155);let n="ai-editor-rail-collapsed";var i=a(12115),s=a(33616),o=a(19544),l=a(7831),d=a(79683),c=a(30441),u=a(10615),p=a(47650),m=a(95660),h=a(64962),f=a(94890),g=a(11012),x=a(92571);function b({handleIds:e,filenames:t,onComplete:a,onDismiss:n}){let[s,o]=(0,i.useState)(!1),[l,d]=(0,i.useState)(!1),[c,y]=(0,i.useState)(null),[v,w]=(0,i.useState)(null);(0,i.useEffect)(()=>{o(!0)},[]);let k=(0,i.useCallback)(async()=>{d(!0),w(null);try{let t=await (0,u.mO)(e);y(t),setTimeout(()=>{a(t)},1e3)}catch(e){console.error("[PermissionRestoreModal] Error requesting permissions:",e),w(e instanceof Error?e.message:"Could not read the saved file permissions.")}finally{d(!1)}},[e,a]),S=c?.filter(e=>"granted"===e.permission).length??0,j=c?.filter(e=>"denied"===e.permission).length??0;return s?(0,p.createPortal)((0,r.jsx)("div",{className:"fixed inset-0 z-[9999] flex items-center justify-center bg-black/60 backdrop-blur-sm",children:(0,r.jsxs)("div",{className:"bg-slate-800 border border-slate-700 rounded-xl shadow-2xl max-w-md w-full mx-4 overflow-hidden",children:[(0,r.jsx)("div",{className:"px-6 py-4 border-b border-slate-700 bg-slate-800/50",children:(0,r.jsxs)("div",{className:"flex items-center gap-3",children:[(0,r.jsx)("div",{className:"p-2 bg-emerald-500/20 rounded-lg",children:(0,r.jsx)(m.A,{className:"h-5 w-5 text-emerald-400"})}),(0,r.jsxs)("div",{children:[(0,r.jsx)("h2",{className:"text-lg font-semibold text-white",children:"Restore File Access"}),(0,r.jsxs)("p",{className:"text-sm text-slate-400",children:[e.length," file",1!==e.length?"s":""," need permission"]})]})]})}),(0,r.jsx)("div",{className:"px-6 py-4",children:c?(0,r.jsxs)("div",{className:"space-y-3",children:[S>0&&(0,r.jsxs)("div",{className:"flex items-center gap-2 text-emerald-400",children:[(0,r.jsx)(h.A,{className:"h-4 w-4"}),(0,r.jsxs)("span",{children:[S," file",1!==S?"s":""," accessible"]})]}),j>0&&(0,r.jsxs)("div",{className:"flex items-center gap-2 text-red-400",children:[(0,r.jsx)(f.A,{className:"h-4 w-4"}),(0,r.jsxs)("span",{children:[j," file",1!==j?"s":""," denied - use Relink to restore"]})]})]}):(0,r.jsxs)("div",{className:"space-y-3",children:[(0,r.jsx)("p",{className:"text-slate-300 text-sm",children:"This project uses local files that need your permission to access:"}),(0,r.jsx)("div",{className:"max-h-40 overflow-y-auto bg-slate-900/50 rounded-lg p-3 space-y-1",children:t.map((t,a)=>(0,r.jsxs)("div",{className:"text-sm text-slate-400 truncate flex items-center gap-2",children:[(0,r.jsx)("span",{className:"text-slate-500",children:"â¢"}),t]},e[a]))}),(0,r.jsxs)("div",{className:"flex items-start gap-2 text-amber-400 text-xs bg-amber-500/10 rounded-lg p-3",children:[(0,r.jsx)(g.A,{className:"h-4 w-4 flex-shrink-0 mt-0.5"}),(0,r.jsx)("span",{children:'Click "Grant Access" to allow this app to read your files. You may see a browser permission dialog.'})]}),v&&(0,r.jsxs)("div",{className:"flex items-start gap-2 text-red-400 text-xs bg-red-500/10 rounded-lg p-3","data-testid":"permission-restore-error",children:[(0,r.jsx)(f.A,{className:"h-4 w-4 flex-shrink-0 mt-0.5"}),(0,r.jsxs)("span",{children:["Couldn't restore file access: ",v,". You can retry, or close this and use Relink to reconnect your files."]})]})]})}),(0,r.jsxs)("div",{className:"px-6 py-4 border-t border-slate-700 bg-slate-800/50 flex justify-end gap-3",children:[!c&&v&&(0,r.jsx)("button",{onClick:()=>a([]),disabled:l,className:"px-4 py-2 text-slate-400 hover:text-white transition-colors disabled:opacity-50","data-testid":"permission-restore-close",children:"Close"}),!c&&!v&&n&&(0,r.jsx)("button",{onClick:n,disabled:l,className:"px-4 py-2 text-slate-400 hover:text-white transition-colors disabled:opacity-50",children:"Skip for now"}),!c&&(0,r.jsx)("button",{onClick:k,disabled:l,className:"flex items-center gap-2 px-4 py-2 bg-emerald-600 hover:bg-emerald-700 disabled:bg-emerald-800 text-white rounded-lg transition-colors","data-testid":"grant-access-button",children:l?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(x.A,{className:"h-4 w-4 animate-spin"}),(0,r.jsx)("span",{children:"Requesting..."})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(m.A,{className:"h-4 w-4"}),(0,r.jsx)("span",{children:v?"Retry":"Grant Access"})]})})]})]})}),document.body):null}var y=a(52481),v=a(12458),w=a(68802),k=a(86272),S=a(40554);function j(e){return e?"handle"===e.type&&e.handleId?`handle:${e.handleId}`:"blob"===e.type&&e.blobId?`blob:${e.blobId}`:"r2"===e.type&&e.storageKey?`r2:${e.storageKey}`:null:null}function I(e){return!!e&&e.includes(".r2.cloudflarestorage.com")&&e.includes("X-Amz-Signature=")}function N(e){if(!I(e))return!1;let t=function(e){try{let t=new URL(e),a=t.searchParams.get("X-Amz-Date"),r=t.searchParams.get("X-Amz-Expires");if(!a||!r)return null;let n=a.match(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/);if(!n)return null;let i=Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3]),Number(n[4]),Number(n[5]),Number(n[6])),s=Number.parseInt(r,10);if(!Number.isFinite(s))return null;return i+1e3*s}catch{return null}}(e);return null===t||t-Date.now()>6e4}function C(e,t,a,r,n){let[s,o]=(0,i.useState)(null),[l,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(!1),[p,m]=(0,i.useState)(null),h=(0,i.useRef)(null),f=(0,i.useRef)(null),g=(0,i.useRef)(null),x=(0,i.useRef)(null);(0,i.useEffect)(()=>()=>{g.current&&URL.revokeObjectURL(g.current),x.current&&URL.revokeObjectURL(x.current)},[]),(0,i.useEffect)(()=>{let t=j(n),r=t||a||e||null;if(!r||h.current===r)return;if(e?.startsWith("blob:")&&!t){o(e),h.current=e;return}let i=!1;return(async()=>{u(!0),m(null);
1try{if(N(e)){i||(o(e),h.current=r);return}let t=await (0,S.resolveMediaUrl)(e||void 0,a||void 0,n||void 0);if(t.startsWith("/api/v1/storage/")||t.startsWith("/api/storage/"))for(let e=0;e<=2;e++){if(i)return;try{let a=await (0,S.authenticatedMediaFetch)(t);if(a.ok){let e=await a.blob();g.current&&URL.revokeObjectURL(g.current);let t=URL.createObjectURL(e);g.current=t,i||(o(t),h.current=r);return}e<2&&await new Promise(t=>setTimeout(t,1e3*(e+1)))}catch{e<2&&await new Promise(t=>setTimeout(t,1e3*(e+1)))}}i||(o(t),h.current=r)}catch(t){if(!i){console.error("[useAuthorizedSceneMedia] Error authorizing media URL:",t),m(t instanceof Error?t.message:"Failed to authorize media URL");let a=e?.includes("/api/"),r=e?.startsWith("local://");a||r||o(e||null)}}finally{i||u(!1)}})(),()=>{i=!0}},[e,a,n]),(0,i.useEffect)(()=>{if(!t&&!r||f.current===(t||r||null))return;let e=!1;return(async()=>{try{if(N(t)){e||(d(t),f.current=t||r||null);return}let a=await (0,S.resolveMediaUrl)(t||void 0,r||void 0);if(a.startsWith("/api/v1/storage/")||a.startsWith("/api/storage/"))try{let n=await (0,S.authenticatedMediaFetch)(a);if(n.ok){let a=await n.blob();x.current&&URL.revokeObjectURL(x.current);let i=URL.createObjectURL(a);x.current=i,e||(d(i),f.current=t||r||null);return}}catch{}e||(d(a),f.current=t||r||null)}catch(a){!e&&(console.error("[useAuthorizedSceneMedia] Error authorizing thumbnail URL:",a),t?.includes("/api/")||d(t||null))}})(),()=>{e=!0}},[t,r]);let b=j(n),y=!!b||!!a||I(e)||e?.includes("/api/v1/storage/")||e?.includes("/api/storage/"),v=e?.startsWith("blob:")&&!b;return{authorizedMediaUrl:v?e:y?s||"":s||e||"",authorizedThumbnailUrl:r||I(t)||t?.includes("/api/v1/storage/")||t?.includes("/api/storage/")?l||void 0:l||t||void 0,isLoading:y&&!s&&!v,error:p}}var M=a(82758);function _(e){return!!e&&(e.includes("/api/v1/storage/")||e.includes("/api/storage/"))}var A=a(28607);let E=(0,a(1934).v)((e,t)=>({hoveredMediaKey:null,setHoveredMediaKey:a=>{t().hoveredMediaKey!==a&&e({hoveredMediaKey:a})},clearHoveredMediaKey:()=>{null!==t().hoveredMediaKey&&e({hoveredMediaKey:null})}}));var T=a(59351),$=a(8121);function P(e,t,a){let r=e.resultMediaKey||e.storageKey||null;return r&&t?r===t:!!a&&!!e.displayUrl&&e.displayUrl===a}var D=a(33711),R=a.n(D);function z(e){return!!e&&!e.startsWith("r2://")&&!e.startsWith("local://")&&!e.startsWith("localBlob://")}function L({thumbnailUrl:e,videoUrl:t,trimStart:a,fallbackContent:n,index:s=0,onDimensionsLoaded:o}){let[l,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(null),[p,m]=(0,i.useState)(!1),[h,f]=(0,i.useState)(null),g=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(!(t&&(t.includes("/api/v1/storage/")||t.includes("/api/storage/"))&&!h&&!g.current))return;g.current=!0;let e=!1;return(async()=>{try{let a=A.default.getInstance(),r=await a.getLocalUrl(t,"video");!e&&r?.startsWith("blob:")&&f(r)}catch(e){console.warn("[VideoThumbnail] Failed to download video for thumbnail:",e)}})(),()=>{e=!0}},[t,h]);let x=h||t;return((0,i.useEffect)(()=>{if(e&&!l||c||p||!x||x.includes("/api/v1/storage/")||x.includes("/api/storage/"))return;let t=!1,r=null,n=null,i=null,d=()=>{r&&(r.removeEventListener("loadeddata",g),r.removeEventListener("seeked",h),r.removeEventListener("error",f),r.src="",r.load(),r=null)},h=()=>{if(!t&&r){if(0===r.videoWidth){m(!0),d();return}o&&r.videoWidth>0&&r.videoHeight>0&&o(r.videoWidth,r.videoHeight);try{let e=document.createElement("canvas");e.width=r.videoWidth,e.height=r.videoHeight;let a=e.getContext("2d");if(a){a.drawImage(r,0,0);let n=e.toDataURL("image/jpeg",.7);t||u(n)}}catch{t||m(!0)}d()}},f=()=>{t||m(!0),d()},g=()=>{!t&&r&&(r.currentTime=a||.1)};return i=setTimeout(()=>{t||((r=document.createElement("video")).crossOrigin="anonymous",r.muted=!0,r.playsInl
1ine=!0,r.preload="metadata",r.addEventListener("loadeddata",g),r.addEventListener("seeked",h),r.addEventListener("error",f),r.src=x,n=setTimeout(()=>{t||c||(m(!0),d())},1e4))},s<5?0:(s-4)*100),()=>{t=!0,i&&clearTimeout(i),n&&clearTimeout(n),d()}},[e,l,c,p,x,a,s]),e&&!l)?(0,r.jsx)("img",{src:e,alt:"Scene preview",className:"w-full h-full object-cover",onError:()=>d(!0)}):c?(0,r.jsx)("img",{src:c,alt:"Scene preview",className:"w-full h-full object-cover"}):!p&&t?(0,r.jsx)("div",{className:"w-full h-full flex items-center justify-center bg-slate-800/50",children:(0,r.jsx)("div",{className:"w-4 h-4 border-2 border-slate-500 border-t-transparent rounded-full animate-spin"})}):(0,r.jsx)(r.Fragment,{children:n})}let F=({scene:e,index:t,mediaKey:a,sceneNumber:n=null,isSelected:s=!1,isArchived:o=!1,showMediaOverlays:l=!0,historyViewIndex:d,onHistoryNav:c,onClick:u,onDoubleClick:p,onDelete:m,onDragStart:h,onAnimate:f,animateStatus:g})=>{var x;let b,y,v,[w,S]=(0,i.useState)(!1),[j,I]=(0,i.useState)(!1),[N,A]=(0,i.useState)(null),D=E(i.useCallback(e=>e.hoveredMediaKey===a,[a])),F=s||D,O=e.generationHistory??[],B=e.media?.storageKey,W=e.media?.url||e.media?.storedUrl,{currentInHistory:U,totalGenerations:K,activeHistoryIdx:V,hasMultipleVersions:H}=(x=!!e.media?.url,y=(b=O.some(e=>P(e,B,W)))?O.length:O.length+ +!!x,{currentInHistory:b,totalGenerations:y,activeHistoryIdx:O.findIndex(e=>P(e,B,W)),hasMultipleVersions:y>1}),q="number"==typeof d&&d<O.length,Y=q?O[d]:null,G="number"==typeof d?d+1:U&&V>=0?V+1:K,X=i.useCallback((e,t)=>{A({width:e,height:t})},[]),{sceneBlobUrls:J}=(0,M.L)(),Z=q&&Y?.displayUrl?Y.displayUrl:e.media?.url||e.media?.storedUrl,Q=q?null:e.media?.thumbnailUrl,{authorizedMediaUrl:ee,authorizedThumbnailUrl:et,isLoading:ea}=C(Z,Q,q?Y?.resultMediaKey??void 0:e.media?.storageKey,void 0,q?void 0:e.media?.assetRef),er=Q&&!_(Q)&&z(Q)?Q:null,en=et||er,ei=Z&&!_(Z)&&z(Z)?Z:null,es=ee||J?.[e.id]||ei,eo=e.media?.type==="video",[el,ed]=(0,i.useState)(()=>new Set),ec=eo?[]:[en,es].filter(e=>!!e),eu=ec.find(e=>!el.has(e))??null,ep=ec.length>0&&null===eu,em=e.media?.trim?e.media.trim.end-e.media.trim.start:e.media?.duration||0,eh=(0,r.jsxs)("div",{className:"w-full h-full flex flex-col items-center justify-center bg-slate-800/40",children:[(0,r.jsx)("span",{className:"text-slate-500 text-2xl",children:eo?"\uD83C\uDFAC":"\uD83D\uDDBCï¸"}),(0,r.jsxs)("span",{className:"text-slate-500 text-[10px] mt-1",children:["Scene ",t+1]})]});return(0,r.jsxs)("div",{className:` 2 relative cursor-pointer rounded-md group 3 transition-all duration-150 ease-out 4 ${F?"ring-2 ring-amber-400/80 scale-[1.02]":"hover:ring-1 hover:ring-slate-600"} 5 ${o?"opacity-80":""} 6 ${j?"opacity-50 ring-2 ring-amber-300/70":""} 7 `,onClick:u,onDoubleClick:p,onMouseEnter:()=>S(!0),onMouseLeave:()=>S(!1),onContextMenu:e=>e.preventDefault(),"data-touch-drag":!0,"data-media-scene-id":e.id,draggable:!0,onDragStart:t=>{I(!0);let a=e.isLoading||e.media?.status==="uploading",r=e.media?.trim?.start??0,n=Math.max(1,(e.media?.trim?.end??e.media?.duration??(a?5:10))-r),i={type:"mediabin-scene",sceneId:e.id,scene:e,duration:n},s=JSON.stringify(i);t.dataTransfer.setData("application/json",s),t.dataTransfer.effectAllowed="copy",(0,$.SP)(i),(0,T.q)(t),h?.(e,t)},onDragEnd:()=>{I(!1),(0,$.Xr)()},"data-scene-id":e.id,"data-index":t,"data-archived":o,"data-marquee-id":e.id,"data-no-marquee":!0,children:[H&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{"aria-hidden":!0,"data-testid":"media-bin-deck-layer",className:"pointer-events-none absolute inset-0 rounded-md bg-slate-800 ring-1 ring-slate-600/50 transition-transform duration-200 ease-out translate-x-[1px] translate-y-[1px] group-hover:translate-x-[4px] group-hover:translate-y-[2px] group-hover:rotate-[2.5deg]"}),(0,r.jsx)("div",{"aria-hidden":!0,"data-testid":"media-bin-deck-layer",className:"pointer-events-none absolute inset-0 rounded-md bg-slate-800/80 ring-1 ring-slate-600/40 transition-transform duration-200 ease-out -translate-x-[1px] translate-y-[1px] group-hover:-translate-x-[4px] group-hover:translate-y-[2px] group-hover:-rotate-[2.5deg]"})]}),(0,r.jsxs)("div",{className:`${R().thumbnail} relative z-10 w-full aspect-[9/16] overflow-hidden rounded-md bg-slate-900`,children:[eo?(0,r.jsx)(L,{thumbnailUrl:en,videoUrl:es,trimStart:e.media?.trim?.start,index:t,fallbackContent:eh,onDimensionsLoaded:X}):eu?(0,r.jsx)("img",{src:eu,alt:`Scene ${t+1}`,className:"w-full h-full object-cover",onError:()=>ed(e=>{let t=new Set(e);return t.add(eu),t}),onLoad:e=>{let t=e.currentTarget;
7t.naturalWidth>0&&t.naturalHeight>0&&X(t.naturalWidth,t.naturalHeight)}}):!ep&&(ea||Z&&!ee)?(0,r.jsx)("div",{className:"w-full h-full flex items-center justify-center bg-slate-800/50",children:(0,r.jsx)("div",{className:"w-4 h-4 border-2 border-slate-500 border-t-transparent rounded-full animate-spin"})}):eh,l&&eo&&em>0&&(0,r.jsx)("div",{className:"absolute bottom-1 right-1 px-1.5 py-0.5 bg-black/80 text-white text-[10px] font-medium rounded",children:function(e){if(!e||e<=0)return"0:00";let t=Math.floor(e/60),a=Math.floor(e%60);return`${t}:${a.toString().padStart(2,"0")}`}(em)}),(0,r.jsxs)("div",{className:"absolute top-1 left-1 z-20 flex items-center gap-1",children:["number"==typeof n&&(0,r.jsx)("div",{"data-testid":"media-bin-scene-number",className:"rounded-full border border-white/15 bg-black/65 px-1.5 py-0.5 text-[9px] font-semibold text-white/90 backdrop-blur-sm",title:`Scene ${n}`,children:n}),l&&((v=function(e,t){if(!e||!t)return null;let a=Math.min(e,t);return a>=2160?"4K":a>=1440?"1440p":a>=1080?"1080p":a>=720?"720p":a>=480?"480p":a>=360?"360p":`${a}p`}(e.media?.mediaOriginalWidth||e.media?.width||N?.width,e.media?.mediaOriginalHeight||e.media?.height||N?.height))?(0,r.jsx)("div",{className:"px-1.5 py-0.5 bg-black/70 text-white text-[9px] font-medium rounded",children:v}):null)]}),o&&(0,r.jsx)("div",{className:"absolute bottom-1 left-1 px-1 py-0.5 bg-amber-500/80 text-white text-[8px] font-medium rounded",children:"archived"}),g?.phase==="starting"||g?.phase==="generating"?(0,r.jsxs)("div",{className:"absolute bottom-1 right-1 z-20 flex items-center gap-1 rounded-full bg-black/75 px-2 py-1 backdrop-blur-sm","data-testid":"media-bin-animate-progress",children:[(0,r.jsx)("span",{className:"h-2.5 w-2.5 animate-spin rounded-full border border-sky-300/40 border-t-sky-300"}),(0,r.jsx)("span",{className:"text-[9px] font-medium text-sky-100",children:"number"==typeof g.progress&&g.progress>0?`${Math.round(g.progress)}%`:"Animating"})]}):g?.phase==="failed"?(0,r.jsx)("div",{className:"absolute bottom-1 right-1 z-20 rounded-full bg-red-500/85 px-2 py-1 text-[9px] font-semibold text-white",title:g.error,"data-testid":"media-bin-animate-failed",children:"Animate failed"}):f?(0,r.jsxs)("button",{type:"button",onClick:e=>{e.stopPropagation(),f()},onDoubleClick:e=>e.stopPropagation(),draggable:!1,className:`${R().animatePill} z-20 rounded-full border border-white/15 bg-black/65 font-semibold text-white/90 backdrop-blur-sm transition-colors hover:bg-black/85 hover:text-white`,"aria-label":"Animate",title:"Animate this photo into a video clip","data-testid":"media-bin-animate-pill",children:[(0,r.jsx)(k.A,{className:R().animateIcon,"aria-hidden":!0}),(0,r.jsx)("span",{className:R().animateLabel,children:"Animate"})]}):null,m&&(0,r.jsx)("button",{onClick:m,className:` 8 absolute top-1 right-1 w-5 h-5 9 bg-red-500/80 hover:bg-red-500 10 text-white text-xs font-bold 11 rounded-full flex items-center justify-center 12 transition-opacity duration-150 13 ${w||s?"opacity-100":"opacity-0"} 14 `,title:"Remove from Media Bin",children:"\xd7"}),H&&c&&(0,r.jsxs)("div",{className:"absolute inset-x-0 bottom-1 z-20 flex items-center justify-center gap-1",children:[(0,r.jsx)("button",{type:"button",onClick:t=>{t.stopPropagation();let a=V>=0?V:K-1,r=Math.max(0,(d??a)-1);c(e.id,r)},disabled:G<=1,className:"flex h-4 w-4 items-center justify-center rounded-full bg-black/60 text-[8px] text-white/80 backdrop-blur-sm transition-colors hover:bg-black/80 disabled:opacity-30",children:(0,r.jsx)("svg",{className:"h-2 w-2",viewBox:"0 0 12 12",fill:"currentColor",children:(0,r.jsx)("path",{d:"M8 1L3 6l5 5"})})}),(0,r.jsxs)("span",{className:"text-[8px] text-white/80 bg-black/50 px-1 rounded-full backdrop-blur-sm",children:[G,"/",K]}),(0,r.jsx)("button",{type:"button",onClick:t=>{t.stopPropagation();let a=V>=0?V:K-1,r=(d??a)+1;c(e.id,r>=K?null:r)},disabled:G>=K,className:"flex h-4 w-4 items-center justify-center rounded-full bg-black/60 text-[8px] text-white/80 backdrop-blur-sm transition-colors hover:bg-black/80 disabled:opacity-30",children:(0,r.jsx)("svg",{className:"h-2 w-2",viewBox:"0 0 12 12",fill:"
14currentColor",children:(0,r.jsx)("path",{d:"M4 1l5 5-5 5"})})})]}),F&&(0,r.jsx)("div",{className:"absolute inset-0 border-2 border-amber-400/70 rounded-md pointer-events-none"})]})]})};var O=a(14648),B=a(78780),W=a(76721);let U=[{key:"media",label:"Media Bin"},{key:"effects",label:"Effects"},{key:"transitions",label:"Transitions"},{key:"voiceover",label:"Voiceover"},{key:"music",label:"Music"},{key:"sfx",label:"Sound FX"},{key:"captions",label:"Captions"}];function K({activePanel:e,onSelectPanel:t,hideMediaTab:a=!1,highlightedPanels:n=[]}){let s=(0,i.useRef)(null),[o,l]=(0,i.useState)(!1),[d,c]=(0,i.useState)(!1),u=(0,i.useMemo)(()=>new Set(n),[n]),p=()=>{let e=s.current;if(!e)return;let t=e.scrollWidth-e.clientWidth,a=e.lastElementChild,r=Math.max(12,.5*(a?.getBoundingClientRect().width??0));l(e.scrollLeft>4),c(t>r&&e.scrollLeft<t-4)};(0,i.useEffect)(()=>{let e=s.current;if(!e)return;p();let t=()=>p();e.addEventListener("scroll",t);let a=new ResizeObserver(p);return a.observe(e),()=>{e.removeEventListener("scroll",t),a.disconnect()}},[]);let m=(0,i.useMemo)(()=>o,[o]),h=(0,i.useMemo)(()=>d,[d]);return(0,r.jsxs)("div",{className:"relative flex items-center w-full rounded-[8px] p-0.5 bg-black/40 ring-1 ring-inset ring-white/[0.05] shadow-[inset_0_1px_2px_rgba(0,0,0,0.45)]","data-side-panel-tabs":!0,children:[m&&(0,r.jsx)("button",{onClick:()=>{let e=s.current;e&&e.scrollBy({left:-Math.max(120,.7*e.clientWidth),behavior:"smooth"})},className:"absolute left-0.5 top-1/2 -translate-y-1/2 z-10 h-6 w-6 rounded-[6px] bg-[#0a0e18]/95 text-slate-400 ring-1 ring-inset ring-white/[0.06] hover:text-slate-100 transition-colors","aria-label":"Scroll tabs left",children:(0,r.jsx)(B.A,{size:14,className:"mx-auto"})}),h&&(0,r.jsx)("button",{onClick:()=>{let e=s.current;e&&e.scrollBy({left:Math.max(120,.7*e.clientWidth),behavior:"smooth"})},className:"absolute right-0.5 top-1/2 -translate-y-1/2 z-10 h-6 w-6 rounded-[6px] bg-[#0a0e18]/95 text-slate-400 ring-1 ring-inset ring-white/[0.06] hover:text-slate-100 transition-colors","aria-label":"Scroll tabs right",children:(0,r.jsx)(W.A,{size:14,className:"mx-auto"})}),(0,r.jsx)("div",{ref:s,className:`flex items-center gap-0.5 w-full overflow-x-auto scrollbar-hidden ${m?"pl-7":"pl-0"} ${h?"pr-7":"pr-0"}`,children:U.filter(({key:e})=>!(a&&"media"===e)).map(({key:a,label:n})=>{let i=e===a,s=u.has(a);return(0,r.jsx)("button",{onClick:()=>t(a),className:`flex items-center px-1.5 py-1.5 rounded-[6px] text-[10px] font-medium whitespace-nowrap transition-colors duration-150 ${i?"bg-amber-400/[0.1] text-amber-200 ring-1 ring-inset ring-amber-400/25
14shadow-[0_0_10px_-3px_rgba(251,191,36,0.4)]":s?"text-amber-300 bg-amber-500/10 ring-1 ring-inset ring-amber-500/40":"text-slate-500 hover:text-slate-200 hover:bg-white/[0.06]"}`,"aria-pressed":i,"data-side-panel-tab":a,children:n},a)})})]})}var V=a(83132),H=a(9005),q=a(19805),Y=a(91161),G=a(3983),X=a(18391);let J=new Set;function Z(e,t,a){J.has(e)||(J.add(e),void 0!==a?console.warn(t,a):console.warn(t))}let Q=new Set;function ee(e){try{let t=`${e.source}|${e.mediaId??e.url??"unknown"}`;if(Q.has(t))return;Q.add(t);let r=e.error,n=r&&"string"==typeof r.name&&r.name?r.name:null!=e.error?typeof e.error:null;Promise.resolve().then(a.bind(a,96412)).then(({trackEvent:t})=>{var a;return t("media_decoration_fetch_failed",{source:e.source,url_kind:(a=e.url)?a.startsWith("blob:")?"blob":a.includes("/api/v1/storage/")||a.includes("/api/storage/")?"proxy":a.startsWith("r2://")||/^https?:\/\//i.test(a)?"signed_r2":"unknown":"unknown",error_name:n,media_id:e.mediaId??null})}).catch(()=>{})}catch{}}var et=a(12532),ea=a(65957);function er(e,t){if(!Array.isArray(e)||0===e.length)return[];let a=e[0]??[],r=Math.abs((a?.length??0)-t);for(let n of e){let e=Math.abs((n?.length??0)-t);e<r&&Array.isArray(n)&&n.length>0&&(a=n,r=e)}return a}function en(e){let t=Array.isArray(e.waveform.peakPyramid)?e.waveform.peakPyramid.filter(e=>Array.isArray(e)&&e.length>0):[],a=Array.isArray(e.waveform.minPeakPyramid)?e.waveform.minPeakPyramid.filter(e=>Array.isArray(e)&&e.length>0):[],r=Array.isArray(e.waveform.maxPeakPyramid)?e.waveform.maxPeakPyramid.filter(e=>Array.isArray(e)&&e.length>0):[],n=a.length>0&&a.length===r.length;return{peakPyramid:t.length>0?t:[[0]],...n?{minPeakPyramid:a,maxPeakPyramid:r}:{},duration:e.duration}}let ei=new Map,es=new Set,eo=({audioUrl:e,storageKey:t,assetRef:a,persistedAudioAnalysis:n,analysisSource:s,onPersistAudioAnalysisArtifact:o,totalDuration:l,audioStartTime:d,audioDuration:c,currentTime:u,color:p,className:m="",isDraggable:h=!1,isDragging:f=!1,inOffset:g=0,waveformMode:x="off",onLoadComplete:b,volume:y=1,showClipping:v=!1,fadeInDuration:w=0,fadeOutDuration:k=0,fadeEnvelopeStart:j,fadeEnvelopeDuration:I,liveTimelineStart:N,liveTimelineDuration:C,liveTimeOffset:M=0})=>{let _=(0,i.useRef)(null),A=(0,i.useRef)(null),E=(0,i.useRef)(null),[T,$]=(0,i.useState)(null),[P,D]=(0,i.useState)(!1),[R,z]=(0,i.useState)(null),[L,F]=(0,i.useState)(0),O=async(e,r)=>{let n=null;try{let i,s=await (0,S.resolveMediaUrl)(e,t,a),o=await (0,S.authenticatedMediaFetch)(s);if(!o.ok)throw Error(`Failed to fetch audio: ${o.status}`);let l=await o.arrayBuffer();n=new(window.AudioContext||window.webkitAudioContext);try{i=await n.decodeAudioData(l)}catch(e){throw es.add(r),(0,X.Bp)(s),e}let d=i.getChannelData(0),c=i.duration,u=Math.floor(d.length/300),p=[];for(let e=0;e<300;e++){let t=e*u,a=Math.min(t+u,d.length),r=0;for(let e=t;e<a;e++){let t=Math.abs(d[e]);t>r&&(r=t)}p.push(r)}let m=Math.max(...p);console.log(`[RealWaveform] Generated waveform: ${p.length} peaks, maxPeak: ${m.toFixed(3)}, duration: ${c.toFixed(2)}s`);let h={peakPyramid:[p],duration:c};return ei.set(r,h),h}catch(a){throw Z(`legacy-waveform:${r}`,"[RealWaveform] Error generating legacy waveform:",a),ee({source:"waveform",url:e,mediaId:t??r,error:a}),a}finally{n&&n.close()}},B=async e=>{var r;let i,l={...s??{},storageKey:s?.storageKey??t,sourceFingerprintHint:s?.sourceFingerprintHint??(0,et.z)(a)??void 0},d=(0,et.U)(e,l),c=d||e;if(ei.has(c))return console.log(`[RealWaveform] Using cached waveform for ${c.slice(0,50)}...`),ei.get(c);if(es.has(c)||(0,X.kA)(e))throw Error("Source has no decodable audio (cached result)");let u=d?(r=n?.audioArtifacts,(i=r?.[d])?en(i):null):null;if(u)return ei.set(c,u),u;try{D(!0),z(null);let r=await (0,ea.fY)({audioUrl:e,storageKey:t,assetRef:a,descriptor:l,persistedArtifacts:n?.audioArtifacts,onArtifactReady:o}),i=en(r);return ei.set(c,i),i}catch(t){return Z(`worker-analysis:${c}`,"[RealWaveform] Worker analysis unavailable, using legacy decode fallback",{error:t instanceof Error?t.message:String(t)}),O(e,c)}finally{D(!1)}};(0,i.useEffect)(()=>{if(!e)return void b?.(!1);let t=!1;return(async()=>{try{let a=await B(e);if(!t){$(a);let e=a?.peakPyramid?.[0],t=e?.length?Math.max(...e):0;b?.(t>5e-5)}}catch(e){t||(z(e instanceof Error?e.message:"Failed to load waveform"),$(null),b?.(!1))}})(),()=>{t=!0}},[e]);let W=(0,i.useMemo)(()=>
14{if(!T||l<=0)return null;let e=c||T.duration,t=d/l*100,a=e/l*100;return console.log(`[RealWaveform] Layout: start=${t.toFixed(1)}%, width=${a.toFixed(1)}%, duration=${e.toFixed(2)}s/${l.toFixed(2)}s`),{left:`${t}%`,width:`${Math.min(a,100-t)}%`,actualDuration:e}},[T,l,d,c]);(0,i.useEffect)(()=>{let e=_.current;if(!e||!T||!W)return;let t=e.getBoundingClientRect();if(t.width<=0||t.height<=0)return;let a=window.devicePixelRatio||1,r=Math.min(1,16384/(t.width*a),16384/(t.height*a)),n=e=>{e.width=Math.max(1,Math.round(t.width*a*r)),e.height=Math.max(1,Math.round(t.height*a*r));let n=e.getContext("2d");return n?(n.scale(a*r,a*r),n.clearRect(0,0,t.width,t.height),n):null},i=n(e);if(!i)return;let s=A.current,o=null;s&&(o=n(s));let l=Math.max(64,Math.min(4096,Math.round(t.width/3))),d=er(T.peakPyramid,l),u=T.duration;if(0===d.length)return;let m=T.minPeakPyramid?er(T.minPeakPyramid,l):[],h=T.maxPeakPyramid?er(T.maxPeakPyramid,l):[],f=m.length===d.length&&h.length===d.length&&d.length>0,b=c||u-g,S=u>0?g/u:0,N=u>0?Math.min(1,(g+b)/u):1,C=Math.floor(S*d.length),M=Math.ceil(N*d.length),E=d.slice(C,M);if(0===E.length)return;let $=(e,t,a,r,n)=>{let i=1-n;return i*i*i*e+3*i*i*n*t+3*i*n*n*a+n*n*n*r},P=j??g,D=Math.max(0,I??b),R=Math.max(0,Math.min(D,w)),z=Math.max(0,Math.min(Math.max(0,D-R),k)),L=P+D,F=Math.max(1,d.length-1),O=e=>{let t=1;return R>0&&e>=P&&e<=P+R&&(t=Math.min(t,$(0,0,1,1,(e-P)/R))),z>0&&e>=L-z&&e<=L&&(t=Math.min(t,$(0,0,1,1,(L-e)/z))),Math.max(0,Math.min(1,t))},B=E.map((e,t)=>{let a=Math.min(d.length-1,C+t);return e*O(u>0?a/F*u:0)}),U=e=>{let t=Math.min(d.length-1,C+e);return O(u>0?t/F*u:0)},K=f?h.slice(C,M).map((e,t)=>Math.max(0,e)*U(t)):B,V=f?m.slice(C,M).map((e,t)=>Math.min(0,e)*U(t)):B.map(e=>-e),H=t.width,q=t.height,Y=q/2,G=.45*q*y,X=(e,t,a,r)=>{if(t.length<2)return;e.save(),r&&(e.shadowColor=p,e.shadowBlur=8,e.shadowOffsetX=0,e.shadowOffsetY=0),e.fillStyle=a,e.beginPath(),e.moveTo(0,Y);let n=H/(t.length-1);for(let a=0;a<t.length;a++){let r=a*n,i=Y-t[a]*G;if(0===a)e.lineTo(r,i);else{let s=(a-1)*n,o=Y-t[a-1]*G,l=(s+r)/2;e.quadraticCurveTo(l,o,(l+r)/2,(o+i)/2),e.quadraticCurveTo(r,i,r,i)}}e.lineTo(H,Y),e.closePath(),e.fill(),e.restore()},J=(e,t)=>{let a=e.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(a)return`rgba(${a[1]}, ${a[2]}, ${a[3]}, ${t})`;if(e.startsWith("#")){let a=e.slice(1),r=parseInt(a.slice(0,2),16),n=parseInt(a.slice(2,4),16),i=parseInt(a.slice(4,6),16);return`rgba(${r}, ${n}, ${i}, ${t})`}return e},Z=(e,t,a,r,n)=>{if(t.length<2)return;e.save(),n&&(e.shadowColor=p,e.shadowBlur=10,e.shadowOffsetX=0,e.shadowOffsetY=0),e.fillStyle=a,e.fillRect(0,0,H,q),e.shadowBlur=0,e.globalCompositeOperation="destination-out",e.fillStyle=r;let i=H/(t.length-1);e.beginPath(),e.moveTo(0,Y);for(let a=0;a<t.length;a++){let r=a*i,n=Y-t[a]*G;if(0===a)e.lineTo(r,n);else{let s=(a-1)*i,o=Y-t[a-1]*G,l=(s+r)/2;e.quadraticCurveTo(l,o,(l+r)/2,(o+n)/2),e.quadraticCurveTo(r,n,r,n)}}e.lineTo(H,Y),e.closePath(),e.fill(),e.beginPath(),e.moveTo(0,Y);for(let a=0;a<t.length;a++){let r=a*i,n=Y+t[a]*G;if(0===a)e.lineTo(r,n);else{let s=(a-1)*i,o=Y+t[a-1]*G,l=(s+r)/2;e.quadraticCurveTo(l,o,(l+r)/2,(o+n)/2),e.quadraticCurveTo(r,n,r,n)}}e.lineTo(H,Y),e.closePath(),e.fill(),e.restore()},Q="neon"===x;if("inverted"===x){let e=J(p,.7);Z(i,B,J(p,.3),"rgba(0,0,0,1)",!1),o&&Z(o,B,e,"rgba(0,0,0,1)",!0)}else if(v){let e=1/y,t=1.25/y,a=J(p,.7);X(i,B,a,!1),X(i,B.map(e=>-e),a,!1);let r=H/(B.length-1),n=Math.max(1,.6*r);for(let a=0;a<B.length;a++){let s=B[a],o=a*r-n/2,l=Math.min(s,e)*G,d=Math.min(Math.max(0,s-e),t-e)*G,c=Math.max(0,s-t)*G;if(d>.5&&(i.fillStyle="rgba(251, 191, 36, 0.95)",i.fillRect(o,Y-l-d,n,d),i.fillRect(o,Y+l,n,d)),c>.5){i.fillStyle="rgba(239, 68, 68, 1.0)";let e=l+d;i.fillRect(o,Y-e-c,n,c),i.fillRect(o,Y+e,n,c)}}}else{let e=J(p,.7),t=J(p,Q?.35:.25);X(i,K,t,!1),X(i,V,t,!1),o&&(X(o,K,e,Q),X(o,V,e,Q))}},[T,W,p,g,c,x,y,v,w,k,j,I,L]);let U=W?.actualDuration??0,K=(0,i.useMemo)(()=>v||U<=0?0:Math.min(100,Math.max(0,u-d)/U*100),[v,U,u,d]);return((0,i.useEffect)(()=>{E.current&&(E.current.style.clipPath=`inset(0 ${100-K}% 0 0)`)},[K]),(0,i.useEffect)(()=>
14{if(void 0===N||void 0===C||v||U<=0)return;let e=-1;return(0,G.G)(t=>{let a=Math.min(100,Math.max(0,(Math.max(0,Math.max(0,Math.min(C,t-N))+M)-d)/U*100));!(e>=0&&.02>Math.abs(a-e))&&(e=a,E.current&&(E.current.style.clipPath=`inset(0 ${100-a}% 0 0)`))})},[N,C,M,d,U,v]),(0,i.useEffect)(()=>{let e=_.current;if(!e||"u"<typeof ResizeObserver)return;let t=0,a=new ResizeObserver(()=>{cancelAnimationFrame(t),t=requestAnimationFrame(()=>F(e=>e+1))});return a.observe(e),()=>{cancelAnimationFrame(t),a.disconnect()}},[T]),R)?null:P?(0,r.jsxs)("div",{className:`flex items-center justify-center text-white text-xs ${m}`,children:[(0,r.jsx)("div",{className:"w-3 h-3 border border-white/30 border-t-white rounded-full animate-spin mr-1"}),"Loading..."]}):T&&W?(0,r.jsxs)("div",{className:`absolute top-0 bottom-0 ${m}`,style:{left:W.left,width:W.width},children:[(0,r.jsx)("canvas",{ref:_,className:"w-full h-full",style:{display:"block"}}),(0,r.jsx)("div",{ref:E,className:"pointer-events-none absolute inset-0",style:{clipPath:`inset(0 ${100-K}% 0 0)`},children:(0,r.jsx)("canvas",{ref:A,className:"w-full h-full",style:{display:"block"}})})]}):null};function el(){let e=(0,i.useMemo)(()=>Array.from({length:80},(e,t)=>Math.max(.1,Math.min(1,.6*Math.sin(t/80*Math.PI)+.3+(.15*Math.sin(.5*t)+.1*Math.cos(.3*t))))),[]);return(0,r.jsx)("div",{className:"w-full h-full bg-slate-800/60 relative overflow-hidden",children:(0,r.jsxs)("svg",{className:"w-full h-full",viewBox:"0 0 100 20",preserveAspectRatio:"none",children:[e.map((t,a)=>(0,r.jsx)("rect",{x:a*(100/e.length),y:10-8*t,width:.8,height:16*t,fill:"rgba(100, 180, 255, 0.5)",rx:.2},a)),(0,r.jsx)("line",{x1:"0",y1:"10",x2:"100",y2:"10",stroke:"rgba(100, 180, 255, 0.2)",strokeWidth:"0.3"})]})})}function ed(e){let t=e.media?.assetRef,a=t?.type==="r2"&&t.storageKey?`asset:r2:${t.storageKey}`:t?.type==="handle"&&t.handleId?`asset:handle:${t.handleId}`:t?.type==="blob"&&t.blobId?`asset:blob:${t.blobId}`:null,r=e.media?.url;return e.media?.storageKey||e.media?.storedUrl||a||e.media?.originalUrl||(r&&!r.startsWith("blob:")?r:void 0)||e.id}let ec="touch-drag-move",eu="touch-drag-end";function ep(e,t,a=!0){let r=(0,i.useRef)(t);r.current=t,(0,i.useEffect)(()=>{if(!a)return;let t=e.current;if(!t)return;let n=null,i=0,s=0,o=!1,l=null,d=null;function c(){l&&(l.remove(),l=null)}let u=e=>{if(!o)return;e.preventDefault();let t=e.touches[0];l&&(l.style.left=`${t.clientX-28}px`,l.style.top=`${t.clientY-28}px`),document.dispatchEvent(new CustomEvent(ec,{detail:{clientX:t.clientX,clientY:t.clientY,data:d}}))},p=e=>{if(document.removeEventListener("touchmove",u),document.removeEventListener("touchend",p),document.removeEventListener("touchcancel",p),!o)return;let t=e.changedTouches[0];document.dispatchEvent(new CustomEvent(eu,{detail:{clientX:t.clientX,clientY:t.clientY,data:d}})),c(),o=!1,d=null},m=e=>{let t=e.target.closest("[data-touch-drag]");if(!t)return;let a=r.current(t);if(!a)return;let c=e.touches[0];i=c.clientX,s=c.clientY,d=a,n=setTimeout(()=>{n=null,o=!0,navigator.vibrate&&navigator.vibrate(50);let e="transition"===a.type?"#f59e0b":"effect"===a.type?"#38bdf8":"#a78bfa";(l=document.createElement("div")).style.cssText=`position:fixed;left:${i-28}px;top:${s-28}px;z-index:10000;pointer-events:none;background:rgba(15,23,42,0.95);border:2px solid ${e};border-radius:12px;padding:6px 10px;display:flex;align-items:center;gap:6px;box-shadow:0 8px 32px rgba(0,0,0,0.5);font-family:system-ui;transform:scale(1.05)`,l.innerHTML=`<span style="font-size:18px">${a.icon}</span><span style="font-size:11px;color:#e2e8f0;font-weight:500;white-space:nowrap">${a.label}</span>`,document.body.appendChild(l),document.addEventListener("touchmove",u,{passive:!1}),document.addEventListener("touchend",p),document.addEventListener("touchcancel",p),document.dispatchEvent(new CustomEvent("touch-drag-start",{detail:{clientX:i,clientY:s,data:a}}))},350)},h=e=>{if(o||!n)return;let t=e.touches[0],a=t.clientX-i,r=t.clientY-s;Math.sqrt(a*a+r*r)>10&&(clearTimeout(n),n=null)},f=()=>{n&&(clearTimeout(n),n=null)},g=e=>{let t=e.target;t?.closest("[data-touch-drag]")&&e.preventDefault()};return t.addEventListener("touchstart",m,{passive:!0}),t.addEventListener("touchmove",h,{passive:!0}),t.addEventListener("touchend",f,{passive:!0}),t.addEventListener("contextmenu",g),()=>{n&&clearTimeout(n),t.removeEventListener("touchstart",m),t.removeEventListener("touchmove",h),t.removeEventListener("touchend",f),t.removeEventListener("contextmenu",g),document.removeEventListener("touchmove",u),document.removeEventListener("touchend",p),document.removeEventListener("touchcancel",p),c()}},[e,a])}var em=a(27903);function eh(e){let t=e.isLoading||e.media?.status==="uploading",a=e.media?.trim?.start??0;return Math.max(1,(e.media?.trim?.end??e.media?.duration??(t?5:10))-a)}var ef=a(94392),eg=a(94213),ex=a(7978),eb=a(34378),ey=a(96412);function ev(e){let t=e?.media;if(!t)return null;let a=t.storageKey||(t.storedUrl?(0,ex.L)(t.storedUrl):null)||(t.url?(0,ex.L)(t.url):null);return a?(0,ex.$n)(a):null}function ew(e){let t=e.media;if(t?.trim){let e=t.trim.end-t.trim.start;if(Number.isFinite(e)&&e>0)return e}return"number"==typeof t?.duration&&t.duration>0?t.duration:5}var ek=a(64542),eS=a(50864),ej=a(41833),eI=a(82571);function eN({scenes:e}){let{currentProject:t,getLatestProjectState:a,updateCoreProjectState:n}=(0,s.By)(),o=(0,i.useRef)(null),l=(0,i.useRef)(e);(0,i.useLayoutEffect)(()=>{l.current=e},[e]);let[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),[m,h]=(0,i.useState)(""),f=t?.textStory;
14if(!f||1!==f.version||!f.ready)return null;let g=async()=>{let e=a();if(!e?.textStory||!d||u)return;p(!0),h("");let t=[],r=[];try{let i=[];for(let a of(0,ek.FV)(d)){let n=d.clips[a.key];if(!n||!l.current.some(e=>e.id===n.sceneId)||n.fingerprint===a.fingerprint)continue;let s=await (0,eS.kI)(e,d,a,e=>{t.push(e),r.push(a.key)});i.push({frame:a,media:s.media})}let s=a();if(s?.id!==e.id||JSON.stringify(s.textStory?.messages)!==JSON.stringify(e.textStory.messages))throw Error("The conversation changed while saving. Close this dialog and reopen it to use the latest version.");let c={...s,scenes:l.current},u=(0,ek.lR)(c,d,i);t.length&&(0,eI.g_)(t),await (0,eS.Oo)(u).saveProject(u),r.forEach(t=>(0,eS.rR)(e.id,t)),ej.n.getState().pushAction({type:"UPDATE_TEXT_STORY",description:"Edit conversation",previousState:{scenes:c.scenes,textStory:c.textStory},newState:{scenes:u.scenes,textStory:u.textStory}}),n(u),y.zC.getState().syncFromScenes(u.scenes),o.current?.close()}catch(n){if(t.length){(0,eI.g_)(t);try{let n=a(),i=n?.id===e.id?{...n,scenes:l.current}:await (0,eS.Oo)(e).getProject(e.id);i&&(await (0,eS.Oo)(i).saveProject({...i,scenes:i.scenes.filter(e=>!t.includes(e.id))}),r.forEach(t=>(0,eS.rR)(e.id,t)))}catch{}}h(n instanceof Error?n.message:"Could not save the conversation. Please try again.")}finally{p(!1)}};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",className:"mt-2 rounded-lg border border-white/15 px-3 py-1.5 text-xs font-semibold text-cyan-200 hover:bg-white/5",onClick:()=>{c({...f,messages:f.messages.map(e=>({...e})),clips:{...f.clips}}),h(""),o.current?.showModal()},children:"Edit conversation"}),(0,r.jsxs)("dialog",{ref:o,"aria-labelledby":"text-story-edit-title",onCancel:e=>{u&&e.preventDefault()},className:"max-h-[85dvh] w-[min(560px,calc(100vw-32px))] rounded-2xl border border-white/15 bg-slate-950 p-6 text-white backdrop:bg-black/70",children:[(0,r.jsx)("h2",{id:"text-story-edit-title",className:"text-lg font-semibold",children:"Edit conversation"}),(0,r.jsx)("p",{className:"mt-2 text-sm text-slate-400",children:"Updates the chat images. Your clip lengths, positions, and removed typing pauses stay as you set them."}),(0,r.jsxs)("form",{className:"mt-5 space-y-4",onSubmit:e=>{e.preventDefault(),g()},children:[d?.messages.map((e,t)=>(0,r.jsxs)("label",{className:"block text-sm text-slate-300",children:["Message ",t+1," \xb7 ",e.sender,(0,r.jsx)("textarea",{required:!0,maxLength:2e3,disabled:u,value:e.text,onChange:t=>{let a=t.target.value;c(t=>t?{...t,messages:t.messages.map(t=>t.id===e.id?{...t,text:a}:t)}:t)},rows:3,className:"mt-1 w-full rounded-lg border border-white/15 bg-white/5 p-3 text-white"})]},e.id)),m&&(0,r.jsx)("p",{role:"alert",className:"text-sm text-amber-200",children:m}),(0,r.jsxs)("div",{className:"sticky bottom-0 flex justify-end gap-2 bg-slate-950 pt-3",children:[(0,r.jsx)("button",{type:"button",disabled:u,onClick:()=>o.current?.close(),className:"rounded-lg border border-white/15 px-4 py-2 text-sm",children:"Cancel"}),(0,r.jsx)("button",{type:"submit",disabled:u||d?.messages.some(e=>!e.text.trim()),className:"rounded-lg bg-white px-4 py-2 text-sm font-semibold text-slate-950 disabled:opacity-50",children:u?"Updating imagesâ¦":"Update images"})]})]})]})]})}let eC="mediaBinCardSize",eM=({audio:e,isSelected:t,showOverlays:a,onClick:n})=>{let s,o,[l,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(null),p=e.inOffset??0,m=e.outOffset??null,h=e.duration??0,f=null!==m?Math.max(0,m-p):h,g=h>0?h:1,x=h>0?h:9999,b=!!(e.url||e.storageKey||e.assetRef),y=e.assetRef?.type==="handle"||e.assetRef?.type==="blob"?e.assetRef.filename:void 0,v=e.url||e.storageKey||y||e.id;return(0,r.jsx)("div",{className:`relative cursor-pointer overflow-hidden rounded-md transition-all duration-150 ease-out 15 ${t?"ring-2 ring-amber-400/80 scale-[1.02]":"hover:ring-1 hover:ring-slate-600"} 16 ${l?"opacity-50 ring-2 ring-amber-300/70":""}`,onClick:n,title:e.text||"Audio",onContextMenu:e=>e.preventDefault(),"data-touch-drag":!0,"data-media-audio-id":e.id,"data-no-marquee":!0,draggable:!0,onDragStart:t=>{d(!0);let a=Math.max(.25,f),r={type:"mediabin-audio",audioId:e.id,audio:e,duration:a},n=JSON.stringify(r);t.dataTransfer.setData("application/json",n),t.dataTransfer.effectAllowed="copy",(0,$.SP)(r),(0,T.q)(t)},onDragEnd:()=>{d(!1),(0,$.Xr)()},children:(0,r.jsxs)("div",{className:"relative w-full aspect-[9/16] bg-slate-900/80",children:[(0,r.jsx)("div",{className:`absolute inset-0 pointer-events-none transition-opacity duration-200 ${c?"opacity-0":"opacity-50"}`,children:(0,r.jsx)(el,{})}),b?(0,r.jsx)(eo,{audioUrl:v,storageKey:e.storageKey,assetRef:e.assetRef,totalDuration:g,audioStartTime:0,audioDuration:h||null,currentTime:x,color:t?"#60a5fa":"#94a3b8",waveformMode:"off",className:"pointer-events-none",onLoadComplete:e=>u(e)}):(0,r.jsx)("div",{className:"absolute inset-0 flex items-center justify-center",children:(0,r.jsx)(V.A,{className:"w-6 h-6 text-slate-400/60"})}),a&&f>0&&(0,r.jsx)("div",{className:"absolute bottom-1 right-1 px-1.5 py-0.5 bg-black/80 text-white text-[10px] font-medium rounded",children:(s=Math.floor(f/60),o=Math.floor(f%60),`${s}:${o.toString().padStart(2,"0")}`)}),a&&(0,r.jsx)("div",{className:"absolute bottom-0 left-0 right-6 bg-gradient-to-t from-black/80 to-transparent p-1",children:(0,r.jsx)("span",{className:"text-[8px] text-white truncate block",children:e.text||"Audio"})})]})})},e_=({onPickFiles:e,prominent:t=!1,fullWidth:a=!1,className:n=""})=>{let s=(0,i.useRef)(null);return(0,r.jsxs)("div",{className:n,children:[(0,r.jsx)("input",{ref:s,t
16ype:"file",accept:"video/*,image/*,audio/*",multiple:!0,onChange:t=>{let a=t.target.files?Array.from(t.target.files):[];a.length>0&&e(a),t.target.value=""},className:"sr-only",tabIndex:-1,"data-testid":"media-bin-file-input"}),t?(0,r.jsxs)("button",{type:"button",onClick:()=>s.current?.click(),className:`group relative flex items-center gap-2 px-4 py-2 rounded-lg text-xs font-medium tracking-wide transition-all duration-300 bg-white/[0.06] hover:bg-white/[0.10] text-slate-200 hover:text-white border border-slate-500/30 hover:border-slate-400/50 animate-[importPulse_3s_ease-in-out_infinite] ${a?"w-full justify-center py-2.5":""}`,"data-testid":"media-bin-file-picker",children:[(0,r.jsx)(m.A,{className:"h-4 w-4 text-slate-400 group-hover:text-slate-200 transition-colors"}),(0,r.jsx)("span",{children:"Import Media"})]}):(0,r.jsxs)("button",{type:"button",onClick:()=>s.current?.click(),className:"flex items-center gap-1 px-2 py-1 bg-slate-900/60 hover:bg-slate-800/70 text-slate-300 hover:text-amber-300 text-[11px] rounded-md transition-colors border border-slate-800/50 hover:border-amber-500/30","data-testid":"media-bin-file-picker",children:[(0,r.jsx)(m.A,{className:"h-3 w-3"}),(0,r.jsx)("span",{children:"Import"})]})]})},eA=({scenes:e,projectId:t,onSceneSelect:a,onSceneDoubleClick:n,selectedSceneId:o=null,onFilesImported:l,onPickFiles:d,audioBlocks:u,overlayMode:p=!1,onAddUrls:m,onMediaVersionSwap:h,onCloseOverlay:f,onAnimateScene:g,animateStatusBySceneId:x})=>{let{currentProject:b}=(0,s.By)(),y=(0,i.useMemo)(()=>u||(b?.audio||b?.voiceovers||[]).filter(e=>"audio"===e.type),[u,b?.audio,b?.voiceovers]),v=b?.mode==="local"||!!l,k=t||b?.id,S=(0,O.w)(e=>e.activeProjectId),j=(0,O.w)(e=>
16e.archivedByProject),I=(0,O.w)(e=>e.setActiveProject),N=(0,O.w)(e=>e.removeArchivedScene),C=(0,w.O)(e=>e.activeSidePanel),M=(0,w.O)(e=>e.setActiveSidePanel),_=(0,w.O)(e=>e.rememberScenePanel);(0,i.useEffect)(()=>{k&&I(k)},[k,I]);let A=S&&j[S]||[],E=(0,i.useCallback)(e=>ed(e),[]),P=(0,i.useMemo)(()=>{let t=new Set,a=[];for(let r of e.map((e,t)=>({scene:e,arrayIndex:t})).sort((e,t)=>{let a="number"==typeof e.scene.timelineStart&&Number.isFinite(e.scene.timelineStart)?e.scene.timelineStart:null,r="number"==typeof t.scene.timelineStart&&Number.isFinite(t.scene.timelineStart)?t.scene.timelineStart:null;return null!==a&&null!==r&&a!==r?a-r:null===a&&null!==r?1:null!==a&&null===r?-1:e.arrayIndex-t.arrayIndex}).map(e=>e.scene)){let e=E(r);t.has(e)||(t.add(e),a.push(r))}for(let e of A){let r=E(e);t.has(r)||(t.add(r),a.push(e))}return a},[e,A,E]),[D,R]=(0,i.useState)(null),z=o??D,[L,B]=(0,i.useState)(null),{containerRef:W,onPointerDown:U,onClickCapture:V,marqueeClientRect:G,isMarqueeActive:X,selectedIds:J,setSelectedIds:Z,clearSelection:Q}=(0,em.qj)({scrollMode:"container"});(0,i.useEffect)(()=>{X&&(R(null),B(null))},[X]),(0,i.useEffect)(()=>{if(0===J.size)return;let e=e=>{"Escape"===e.key&&Q()};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[J.size,Q]);let ee=(0,i.useCallback)(e=>{M(e),z&&_(z,e)},[z,_,M]),[et,ea]=(0,i.useState)(()=>{{let e=localStorage.getItem(eC);if(e){let t=parseInt(e,10);if(t>=25&&t<=150)return t}}return 60}),er=(0,i.useRef)(null),en=(0,i.useRef)(null),[ei,es]=(0,i.useState)(280),eo=(0,i.useCallback)(e=>{en.current=e,W.current=e},[W]);(0,i.useEffect)(()=>{let e=er.current;if(!e)return;let t=new ResizeObserver(e=>{for(let t of e)es(t.contentRect.width)});return t.observe(e),()=>t.disconnect()},[]);let el=Math.max(1,Math.floor((ei-16+6)/(et+6))),ec=et>=70,eu=(0,i.useCallback)(e=>{let t=parseInt(e.target.value,10);ea(t),localStorage.setItem(eC,String(t))},[]),ef=(0,i.useCallback)((e,t,r)=>{if(r&&(r.metaKey||r.ctrlKey)){Z(t=>{let a=new Set(t);return 0===a.size&&D&&D!==e&&a.add(D),a.has(e)?a.delete(e):a.add(e),a}),R(null);return}Q(),R(t=>t===e?null:e),a?.(e,t)},[Q,D,a,Z]),eg=(0,i.useCallback)((e,t)=>{let a;if(!J.has(e.id)){J.size>0&&Q();return}let r=(a=P.filter(e=>J.has(e.id))).length<2?null:{type:"mediabin-scenes",sceneIds:a.map(e=>e.id),scenes:a,duration:a.reduce((e,t)=>e+eh(t),0)};r&&(t.dataTransfer.setData("application/json",JSON.stringify(r)),(0,$.SP)(r),(0,T.q)(t,.94,{badgeText:String(r.scenes.length)}))},[P,Q,J]),ex=(0,i.useCallback)(e=>{if(V(e),e.defaultPrevented||0===J.size)return;let t=e.target;t?.closest("[data-marquee-id], [data-no-marquee], button, a, input")||Q()},[Q,J.size,V]),eb=(0,i.useCallback)((e,t)=>{n?.(e,t)},[n]),ey=(0,i.useCallback)(t=>{let a=E(t);return e.some(e=>E(e)===a)},[e,E]),ew=(0,i.useCallback)(e=>!ey(e),[ey]),ek=(0,i.useMemo)(()=>{let e=new Map,t=0;for(let a of P)ey(a)&&(t+=1,e.set(a.id,t));return e},[P,ey]),eS=(0,i.useCallback)((e,t)=>{if(t?.stopPropagation(),ew(e)){let t=E(e);A.filter(e=>E(e)===t).forEach(e=>N(e.id)),D===e.id&&R(null)}},[ew,E,A,N,D]),ej=P.length+y.length,eI=(0,i.useMemo)(()=>new Map(P.map(e=>[e.id,e])),[P]),eA=(0,i.useMemo)(()=>new Map(y.map(e=>[e.id,e])),[y]),[eE,eT]=(0,i.useState)({}),e$=(0,i.useCallback)((e,t)=>{eT(a=>({...a,[e]:t??void 0})),"number"==typeof t&&h&&h(e,t)},[h]);return(ep(en,e=>{let t=e.getAttribute("data-media-scene-id");if(t){let e=eI.get(t);if(!e)return null;let a=e.isLoading||e.media?.status==="uploading",r=e.media?.trim?.start??0,n=Math.max(1,(e.media?.trim?.end??e.media?.duration??(a?5:10))-r);return{type:"mediabin-scene",payload:{type:"mediabin-scene",sceneId:e.id,scene:e,duration:n},icon:e.media?.type==="video"?"\uD83C\uDFAC":"\uD83D\uDDBCï¸",label:`Scene ${null!=e.sequenceIndex?e.sequenceIndex+1:""}`.trim()}}let a=e.getAttribute("data-media-audio-id");if(a){let e=eA.get(a);if(!e)return null;let t=e.inOffset??0,r=e.outOffset??null,n=e.duration??0,i=null!==r?Math.max(.25,r-t):Math.max(.25,n);return{type:"mediabin-audio",payload:{type:"mediabin-audio",audioId:e.id,audio:e,duration:i},icon:"\uD83C\uDFB5",label:e.text||"Audio"}}return null},ej>0),0===ej)?(0,r.jsxs)("div",{className:"flex flex-col h-full bg-slate-950 pl-4 pr-3 pt-3 pb-4 border-r border-white/[0.06]",children:[(0,r.jsx)("style",{children:` 17 @keyframes importPulse { 18 0%, 100% { border-color: rgba(100,116,139,0.30); box-shadow: 0 0 0 rgba(148,163,184,0); } 19 50% { border-color: rgba(148,163,184,0.45); box-shadow: 0 0 12px rgba(148,163,184,0.08); } 20 } 21 @keyframes arrowBounce { 22 0%, 100% { transform: translateY(0); opacity: 0.45; } 23 50% { transform: translateY(5px); opacity: 0.85; } 24 } 25 `}),(0,r.jsx)("div",{className:"flex flex-col gap-2 mb-3",children:(0,r.jsxs)("div",{className:"flex items-start gap-2 min-w-0",children:[(0,r.jsx)("div",{className:"min-w-0 flex-1",children:(0,r.jsx)(K,{activePanel:C,onSelectPanel:ee,hideMediaTab:p&&"media"===C})}),p&&f&&(0,r.jsxs)("button",{type:"button",onClick:f,"data-testid":"media-bin-overlay-close",className:"ml-auto inline-flex shrink-0 items-center gap-1 rounded-lg bg-white/[0.1] px-2.5 py-1.5 text-[11px] font-semibold text-slate-100 ring-1 ring-white/15 transition-colors hover:bg-white/[0.16]",children:["Close",(0,r.jsx)(H.A,{className:"h-3.5 w-3.5"})]})]})}),(0,r.jsxs)("div",{className:"flex-1 flex flex-col items-center justify-center gap-3 px-4 -mt-4",children:[(0,r.jsx)("p",{className:"text-slate-400 text-sm tracking-wide uppercase text-center",children:"Get started"}),(0,r.jsx)(q.A,{className:"h-5 w-5 text-emerald-400",style:{animation:"arrowBounce 2s ease-in-out infinite"}}),v&&k&&l?(0,r.jsx)(c.aG,{projectId:k,onFilesImported:l,prominent:!0}):d?(0,r.jsx)(e_,{onPickFiles:d,prominent:!0}):(0,r.jsx)("p",{className:"text-slate-600 text-xs text-center",children:"Drag and drop files here to add media"}),p&&m&&(0,r.jsxs)("button",{type:"button",onClick:m,className:"inline-flex items-center gap-2 rounded-lg border border-slate-700/70 bg-slate-900/80 px-4 py-2 text-xs font-medium text-slate-200 transition-colors hover:border-sky-500/45 hover:bg-slate-800/80 hover:text-white",children:[(0,r.jsx)(Y.A,{className:"h-4 w-4 text-sky-300"}),(0,r.jsx)("span",{children:"Add URLs"})]}),(0,r.jsx)("p",{className:"text-slate-600 text-[11px] text-center mt-1",children:"or drag files anywhere on this page"})]})]}):(0,r.jsxs)("div",{ref:er,className:"flex flex-col h-full bg-slate-950 overflow-hidden border-r border-white/[0.06]",children:[(0,r.jsxs)("div",{className:"pl-4 pr-3 py-2.5 border-b border-white/[0.06]",style:{background:"linear-gradient(180deg, rgba(13,18,32,0.92) 0%, rgba(9,13,23,0.95) 100%)"},children:[(0,r.jsxs)("div",{className:"flex items-start gap-2 min-w-0",children:[(0,r.jsx)("div",{className:"min-w-0 flex-1",children:(0,r.jsx)(K,{activePanel:C,onSelectPanel:ee,hideMediaTab:p&&"media"===C})}),p&&f&&(0,r.jsxs)("button",{type:"button",onClick:f,"data-testid":"media-bin-overlay-close",className:"ml-auto inline-flex shrink-0 items-center gap-1 rounded-lg bg-white/[0.1] px-2.5 py-1.5 text-[11px] font-semibold text-slate-100 ring-1 ring-white/15 transition-colors hover:bg-white/[0.16]",children:["Close",(0,r.jsx)(H.A,{className:"h-3.5 w-3.5"})]})]}),(0,r.jsx)(eN,{scenes:e}),(0,r.jsxs)("div",{className:"mt-2.5 flex items-center gap-3",children:[!p&&v&&k&&l&&(0,r.jsx)(c.aG,{projectId:k,onFilesImported:l,className:"shrink-0"}
25),!p&&!(v&&k&&l)&&d&&(0,r.jsx)(e_,{onPickFiles:d,className:"shrink-0"}),p&&m&&(0,r.jsxs)("button",{type:"button",onClick:m,className:"inline-flex shrink-0 items-center gap-1.5 rounded-md border border-slate-800/70 bg-slate-900/70 px-2 py-1 text-[11px] text-slate-300 transition-colors hover:border-sky-500/35 hover:text-sky-100",children:[(0,r.jsx)(Y.A,{className:"h-3 w-3 text-sky-300"}),(0,r.jsx)("span",{children:"Add URLs"})]}),J.size>0&&(0,r.jsxs)("div",{"data-testid":"media-bin-selected-count",className:"flex shrink-0 items-center gap-1 rounded-full border border-amber-400/40 bg-amber-500/10 px-2 py-0.5 text-[11px] font-medium text-amber-200",children:[(0,r.jsxs)("span",{children:[J.size," selected"]}),(0,r.jsx)("button",{type:"button",onClick:Q,className:"text-amber-300/80 transition-colors hover:text-amber-100",title:"Clear selection","aria-label":"Clear selection",children:(0,r.jsx)(H.A,{className:"h-3 w-3"})})]}),(0,r.jsx)("input",{type:"range",min:25,max:150,value:et,onChange:eu,className:"flex-none w-24 h-1 bg-slate-700/40 rounded-full appearance-none cursor-pointer opacity-60 hover:opacity-90 transition-opacity ml-auto\n [&::-webkit-slider-thumb]:appearance-none\n [&::-webkit-slider-thumb]:w-2.5\n [&::-webkit-slider-thumb]:h-2.5\n [&::-webkit-slider-thumb]:rounded-full\n [&::-webkit-slider-thumb]:bg-amber-500/80\n [&::-webkit-slider-thumb]:hover:bg-amber-400\n [&::-webkit-slider-thumb]:cursor-pointer\n [&::-moz-range-thumb]:w-2.5\n [&::-moz-range-thumb]:h-2.5\n [&::-moz-range-thumb]:rounded-full\n [&::-moz-range-thumb]:bg-amber-500/80\n [&::-moz-range-thumb]:border-0\n [&::-moz-range-thumb]:cursor-pointer",title:`Card size: ${et}px`})]})]}),p&&(v&&k&&l||d)&&(0,r.jsxs)("div",{className:"flex-shrink-0 px-3 pt-2.5",children:[(0,r.jsx)("style",{children:` 26 @keyframes importPulse { 27 0%, 100% { border-color: rgba(100,116,139,0.30); box-shadow: 0 0 0 rgba(148,163,184,0); } 28 50% { border-color: rgba(148,163,184,0.45); box-shadow: 0 0 12px rgba(148,163,184,0.08); } 29 } 30 `}),v&&k&&l?(0,r.jsx)(c.aG,{projectId:k,onFilesImported:l,prominent:!0,fullWidth:!0}):d?(0,r.jsx)(e_,{onPickFiles:d,prominent:!0,fullWidth:!0}):null]}),(0,r.jsx)("div",{ref:eo,onPointerDown:U,onClickCapture:ex,className:`overflow-y-auto pl-4 pr-2.5 py-2.5 flex-1 min-h-0 ${p?"":"max-h-[calc(80vh-60px)]"} 31 [scrollbar-width:thin] 32 [scrollbar-color:rgba(51,65,85,0.4)_transparent] 33 [&::-webkit-scrollbar]:w-1 34 [&::-webkit-scrollbar-track]:bg-transparent 35 [&::-webkit-scrollbar-thumb]:bg-slate-700/40 36 [&::-webkit-scrollbar-thumb]:rounded-full 37 [&::-webkit-scrollbar-thumb:hover]:bg-slate-600/50`,children:(0,r.jsxs)("div",{className:"grid gap-1.5",style:{gridTemplateColumns:`repeat(${el}, 1fr)`},children:[P.map((e,t)=>{let a=ew(e),n=E(e);return(0,r.jsx)(F,{scene:e,index:t,mediaKey:n,sceneNumber:ek.get(e.id)??null,isSelected:z===e.id||J.has(e.id),isArchived:a,showMediaOverlays:ec,historyViewIndex:eE[e.id],onHistoryNav:e.generationHistory?.length?e$:void 0,onClick:a=>{B(null),ef(e.id,t,a)},onDoubleClick:()=>eb(e.id,t),onDelete:a?t=>eS(e,t):void 0,onDragStart:eg,onAnimate:g&&!Object.values(b?.textStory?.clips??{}).some(t=>t.sceneId===e.id)&&e?.media&&"image"===e.media.type&&(e.media.status??"ready")==="ready"&&null!==ev(e)?()=>g(e.id):void 0,animateStatus:x?.[e.id]},e.id)}),y.map(e=>(0,r.jsx)(eM,{audio:e,isSelected:L===e.id,showOverlays:ec,onClick:()=>{R(null),Q(),B(t=>t===e.id?null:e.id)}},e.id))]})}),G&&G.width>0&&G.height>0&&(0,r.jsx)("div",{"aria-hidden":!0,"data-testid":"media-bin-marquee-rect",className:"pointer-events-none fixed z-50 rounded-sm border border-amber-400/70 bg-amber-400/10",style:{left:G.left,top:G.top,width:G.width,height:G.height}})]})};function eE(e,t){let{min:a,max:r}=function(e){let t=void 0===e?window.innerWidth:e;if("number"!=typeof t||!Number.isFinite(t)||t<=0)return{min:280,max:600};let a=Math.min(600,Math.max(240,t-Math.min(600,Math.max(440,Math.floor(.45*t)))-320));return{min:Math.min(280,a),max:a}}(t);return Math.min(r,Math.max(a,"number"==typeof e&&Number.isFinite(e)?e:452))}function eT({scenes:e,projectId:t,onSceneSelect:a,onFilesImported:n,onPickFiles:o,audioBlocks:l,timelineHeight:d,setTimelineHeight:c,overlayMode:u=!1,overlayViewportWidth:p,overlayTopPx:m,onAddUrls:h,onMediaVersionSwap:f,onCloseOverlay:g,onAnimateScene:x,animateStatusBySceneId:b}){let{currentProject:y,setMediaBinWidth:v}=(0,s.By)(),k=(0,w.O)(e=>e.activeSidePanel),S=y?.mediaBinWidth,[j,I]=i.useState(eE(S,null)),[N,C]=i.useState(!1),M=i.useRef(!1),_=i.useRef({x:0,width:0}),A=i.useRef(j);i.useEffect(()=>{if(M.current)return;let e=eE(S);I(e),A.current=e},[S]),i.useEffect(()=>{if(u)return;let e=()=>{if(N||M.current)return;let e=eE(S??A.current);1>Math.abs(e-A.current)||(I(e),A.current=e)};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[u,N,S]),i.useEffect(()=>{let e=e=>{let t=e.detail?.width;if(void 0===t)return;M.current=!0;let a=eE(t);I(a),A.current=a},t=()=>
37{M.current=!1,v(A.current)};return window.addEventListener("media-bin-resize",e),window.addEventListener("media-bin-resize-end",t),()=>{window.removeEventListener("media-bin-resize",e),window.removeEventListener("media-bin-resize-end",t)}},[v]),i.useEffect(()=>{if(u||y?.masterPreviewLocked)return;let e=e=>{let{leftEdge:t}=e.detail,a=eE(t);I(a),A.current=a,v(a)};return window.addEventListener("preview-left-edge-resize",e),()=>{window.removeEventListener("preview-left-edge-resize",e)}},[u,y?.masterPreviewLocked,v]),i.useEffect(()=>{if(u)return;let e=()=>{if(!y?.masterPreviewLocked||N||M.current)return;let e=document.querySelector("[data-master-preview]");if(!e)return;let t=eE(Math.round(e.getBoundingClientRect().left));1>Math.abs(t-A.current)||(I(t),A.current=t,v(t))};return window.addEventListener("master-preview:layout",e),()=>{window.removeEventListener("master-preview:layout",e)}},[y?.masterPreviewLocked,N,u,v]),i.useEffect(()=>{let e=()=>{let e=document.querySelector("[data-master-timeline]");if(e){let t=Math.round(e.getBoundingClientRect().height);for(let e of["[data-media-bin-container]","[data-ai-rail-container]"]){let a=document.querySelector(e);if(!a)continue;let r=a.style.bottom;r&&r.endsWith("px")&&parseInt(r,10)>0&&(a.style.bottom=`${t}px`)}c(e=>e===t?e:t)}};e();let t=document.querySelector("[data-master-timeline]");if(t){let a=new ResizeObserver(e);return a.observe(t),()=>a.disconnect()}let a=setInterval(e,500);return()=>clearInterval(a)},[c]),i.useEffect(()=>{if(!N)return;let e=e=>{let t=e.clientX-_.current.x,a=eE(_.current.width+t);I(a),A.current=a,window.dispatchEvent(new CustomEvent("media-bin-right-edge-resize",{detail:{rightEdge:a}}))},t=()=>{C(!1),v(A.current),window.dispatchEvent(new Event("media-bin-resize-end"))};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",t),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",t)}},[N,v]);let E=u?Math.max(196,(p||j)-16):j,T=m??104;return(0,r.jsxs)("div",{"data-media-bin-container":!0,className:`fixed overflow-hidden ${u?"z-[65] rounded-2xl shadow-[0_18px_48px_rgba(2,6,23,0.55)]":"top-10 left-0 z-40"}`,style:{width:E,maxWidth:u?"calc(100vw - 16px)":void 0,top:u?T:void 0,left:u?8:void 0,height:u?`calc(100dvh - ${T}px - ${d+8}px)`:void 0,bottom:u?void 0:d},children:[(0,r.jsx)("div",{className:"h-full",style:"media"!==k?{visibility:"hidden"}:void 0,children:(0,r.jsx)(eA,{scenes:e,projectId:t,onSceneSelect:e=>a(e),onFilesImported:n,onPickFiles:o,audioBlocks:l,overlayMode:u,onAddUrls:h,onMediaVersionSwap:f,onCloseOverlay:g,onAnimateScene:x,animateStatusBySceneId:b})}),!u&&(0,r.jsx)("div",{className:`absolute top-0 right-0 w-3 h-full cursor-ew-resize transition-colors ${N?"bg-blue-500/40":"hover:bg-blue-500/20"}`,onMouseDown:e=>{e.preventDefault(),e.stopPropagation(),C(!0),_.current={x:e.clientX,width:j}}})]})}var e$=a(40612),eP=a(85373),eD=a(48543),eR=a(75252),ez=a(49804);let eL=` 38@keyframes fcpw-backdrop { from { opacity: 0; } to { opacity: 1; } } 39@keyframes fcpw-pop { from { opacity: 0; transform: translateY(18px) scale(0.94); } to { opacity: 1; transform: translateY(0) scale(1); } } 40@keyframes fcpw-rise { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: none; } } 41@keyframes fcpw-ring { to { transform: rotate(360deg); } } 42@keyframes fcpw-aurora { 43 0% { transform: translate3d(-16%, -12%, 0) scale(1); opacity: .75; } 44 50% { transform: translate3d(14%, 10%, 0) scale(1.25); opacity: 1; } 45 100% { transform: translate3d(-16%, -12%, 0) scale(1); opacity: .75; } 46} 47@keyframes fcpw-shine { 0% { transform: translateX(-140%) skewX(-18deg); } 45% { transform: translateX(240%) skewX(-18deg); } 100% { transform: translateX(240%) skewX(-18deg); } } 48@keyframes fcpw-glow { 49 0%, 100% { box-shadow: 0 0 22px rgba(251,191,36,.30), 0 8px 30px rgba(251,191,36,.18), inset 0 1px 0 rgba(255,255,255,.35); } 50 50% { box-shadow: 0 0 46px rgba(251,191,36,.55), 0 12px 44px rgba(251,191,36,.32), inset 0 1px 0 rgba(255,255,255,.35); } 51} 52@keyframes fcpw-goldtext { 0% { background-position: 0% 50%; } 100% { background-position: 200% 50%; } } 53.fcpw-backdrop { animation: fcpw-backdrop .35s ease-out both; } 54.fcpw-card { animation: fcpw-pop .55s cubic-bezier(.16, 1, .3, 1) both; } 55.fcpw-ring { animation: fcpw-ring 7s linear infinite; } 56.fcpw-aurora { animation: fcpw-aurora 9s ease-in-out infinite; }
57.fcpw-shine { animation: fcpw-shine 2.6s cubic-bezier(.4, 0, .2, 1) 1.1s infinite; } 58.fcpw-glow { animation: fcpw-glow 2.4s ease-in-out infinite; } 59.fcpw-goldtext { 60 background: linear-gradient(100deg, #fff 0%, #ffe9b3 28%, #fbbf24 46%, #fff6dd 62%, #fff 80%); 61 background-size: 200% auto; 62 -webkit-background-clip: text; 63 background-clip: text; 64 color: transparent; 65 animation: fcpw-goldtext 5s linear infinite; 66} 67.fcpw-rise { animation: fcpw-rise .5s cubic-bezier(.16, 1, .3, 1) both; } 68.fcpw-cta:hover { transform: translateY(-1px); filter: brightness(1.07); } 69.fcpw-cta { transition: transform .18s ease, filter .18s ease; } 70@media (prefers-reduced-motion: reduce) { 71 .fcpw-backdrop, .fcpw-card, .fcpw-ring, .fcpw-aurora, .fcpw-shine, .fcpw-glow, .fcpw-goldtext, .fcpw-rise { animation: none !important; } 72} 73`,eF="var(--font-outfit), ui-sans-serif, system-ui, sans-serif",eO=[{icon:eD.A,text:"Animate any photo into cinematic motion"},{icon:k.A,text:"1,000 AI credits every week"},{icon:eR.A,text:"Premium voices + the AI editor"}];function eB({kind:e,onClose:t}){let a=(0,i.useRef)(!1),n="credits"===e?"/billing?from=animate-photo":"/pricing?from=animate-photo",s="credits"===e?"Get credits":"Upgrade to Pro";(0,i.useEffect)(()=>{a.current||(a.current=!0,(0,ey.trackEvent)("editor_animate_upgrade_modal_shown",{kind:e}))},[e]),(0,i.useEffect)(()=>{let a=a=>{"Escape"===a.key&&((0,ey.trackEvent)("editor_animate_upgrade_modal_dismissed",{kind:e,via:"escape"}),t())};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[e,t]);let o=a=>{(0,ey.trackEvent)("editor_animate_upgrade_modal_dismissed",{kind:e,via:a}),t()},l=(0,r.jsxs)("div",{className:"fcpw-backdrop fixed inset-0 z-[9999] flex items-center justify-center bg-black/75 p-4 backdrop-blur-md",onClick:e=>{e.target===e.currentTarget&&o("backdrop")},role:"dialog","aria-modal":"true","aria-label":"credits"===e?"Out of AI credits":"Animation is a Pro feature","data-testid":"animate-upgrade-modal",children:[(0,r.jsx)("style",{children:eL}),(0,r.jsxs)("div",{className:"fcpw-card relative w-full max-w-[26rem] overflow-hidden rounded-[26px] p-[1.5px] shadow-[0_40px_120px_rgba(0,0,0,0.75)]",children:[(0,r.jsx)("div",{"aria-hidden":!0,className:"fcpw-ring absolute inset-[-150%]",style:{background:"conic-gradient(from 0deg, rgba(251,191,36,0) 0deg, rgba(251,191,36,0.08) 40deg, rgba(251,191,36,0.75) 78deg, rgba(255,236,179,1) 92deg, rgba(251,191,36,0.75) 106deg, rgba(251,191,36,0.08) 150deg, rgba(251,191,36,0) 200deg, rgba(251,191,36,0) 360deg)"}}),(0,r.jsxs)("div",{className:"relative overflow-hidden rounded-[24.5px] bg-[#0f0d0a]",children:[(0,r.jsx)("div",{"aria-hidden":!0,className:"fcpw-aurora pointer-events-none absolute -top-24 left-1/2 h-64 w-[26rem] -translate-x-1/2 rounded-full blur-3xl",style:{background:"radial-gradient(closest-side, rgba(251,191,36,0.22), rgba(217,119,6,0.10) 55%, transparent 75%)"}}),(0,r.jsx)("div",{"aria-hidden":!0,className:"pointer-events-none absolute -bottom-28 -right-20 h-56 w-56 rounded-full blur-3xl",style:{background:"radial-gradient(closest-side, rgba(180,83,9,0.16), transparent 70%)"}}),(0,r.jsx)("div",{"aria-hidden":!0,className:"pointer-events-none absolute inset-0 opacity-[0.05] mix-blend-overlay",style:{backgroundImage:"url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='140' height='140'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2'/%3E%3C/filter%3E%3Crect width='140' height='140' filter='url(%23n)' opacity='0.5'/%3E%3C/svg%3E\")"}}),(0,r.jsxs)("div",{className:"relative px-7 pb-7 pt-6",children:[(0,r.jsxs)("div",{className:"flex items-start justify-between",children:[(0,r.jsxs)("div",{className:"fcpw-rise flex items-center gap-2.5",style:{animationDelay:".08s"},children:[(0,r.jsx)("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-gradient-to-br from-amber-300 to-amber-600 shadow-[0_2px_12px_rgba(251,191,36,0.45)]",children:(0,r.jsx)(eD.A,{className:"h-4 w-4 text-[#231703]"})}),(0,r.jsx)("span",{className:"text-[10px] font-bold uppercase tracking-[0.28em] text-amber-200/90",style:{fontFamily:eF},children:"FrameCompose Pro"})]}),(0,r.jsx)("button",{type:"button",onClick:()=>o("close-button"),className:"rounded-md p-1 text-[#7a736a] transition-colors hover:bg-white/[0.07] hover:text-white","aria-label":"Close","data-testid":"animate-upgrade-close",children:(0,r.jsx)("svg",{className:"h-4 w-4",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",children:(0,r.jsx)("path",{d:"M3.5 3.5l9 9M12.5 3.5l-9 9"})})})]}),"credits"===e?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("h2",{className:"fcpw-goldtext fcpw-rise mt-5 text-[27px] font-extrabold leading-[1.08] tracking-tight",style:{fontFamily:eF,animationDelay:".14s"},children:"Youâre out of AI credits"}),(0,r.jsx)("p",{className:"fcpw-rise mt-2.5 text-[13.5px] leading-relaxed text-[#b3aca2]",style:{animationDelay:".2s"},children:"This animation needs more credits than you have left this week. Top up a pack, or wait for your weekly reset."})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("h2",{className:"fcpw-goldtext fcpw-rise mt-5 text-[29px] font-extrabold leading-[1.06] tracking-tight",style:{fontFamily:eF,animationDelay:".14s"},children:["Bring this photo",(0,r.jsx)("br",{}),"to life"]}),(0,r.jsx)("p",{className:"fcpw-rise mt-2.5 text-[13.5px] leading-relaxed text-[#b3aca2]",style:{animationDelay:".2s"}
73,children:"Photo animation is a Pro feature. Unlock it and you also get:"}),(0,r.jsx)("ul",{className:"mt-4 flex flex-col gap-2",children:eO.map((e,t)=>(0,r.jsxs)("li",{className:"fcpw-rise flex items-center gap-3 rounded-xl border border-amber-200/[0.08] bg-white/[0.03] px-3.5 py-2.5 text-[13px] font-medium text-[#e6e0d7]",style:{animationDelay:`${.26+.07*t}s`},children:[(0,r.jsx)("span",{className:"flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md bg-amber-400/15 ring-1 ring-inset ring-amber-300/25",children:(0,r.jsx)(e.icon,{className:"h-3.5 w-3.5 text-amber-300"})}),e.text]},e.text))})]}),(0,r.jsxs)("div",{className:"fcpw-rise mt-6 flex flex-col gap-2",style:{animationDelay:".42s"},children:[(0,r.jsxs)("a",{href:n,onClick:()=>(0,ey.trackEvent)("editor_animate_upgrade_modal_cta_clicked",{kind:e,destination:n}),className:"fcpw-cta fcpw-glow group relative inline-flex w-full items-center justify-center gap-2.5 overflow-hidden rounded-2xl px-5 py-4",style:{background:"linear-gradient(180deg, #ffd980 0%, #fbbf24 38%, #ee9d0b 100%)"},"data-testid":"animate-upgrade-cta",children:[(0,r.jsx)("span",{"aria-hidden":!0,className:"fcpw-shine pointer-events-none absolute inset-y-0 left-0 w-1/3",style:{background:"linear-gradient(105deg, transparent 0%, rgba(255,255,255,0.75) 50%, transparent 100%)"}}),(0,r.jsx)(ez.A,{className:"h-[19px] w-[19px] text-[#2a1c03]",fill:"#2a1c03"}),(0,r.jsx)("span",{className:"text-[17px] font-extrabold tracking-tight text-[#2a1c03]",style:{fontFamily:eF},children:s})]}),(0,r.jsx)("button",{type:"button",onClick:()=>o("not-now"),className:"inline-flex w-full items-center justify-center rounded-xl px-4 py-2.5 text-[12.5px] font-medium text-[#8f887e] transition-colors hover:bg-white/[0.05] hover:text-white","data-testid":"animate-upgrade-dismiss",children:"Not now"})]}),(0,r.jsx)("p",{className:"fcpw-rise mt-2 text-center text-[10.5px] text-[#6b6459]",style:{animationDelay:".5s"},children:"Your photo is untouched. Your project is saved."})]})]})]})]});return"u"<typeof document?null:(0,p.createPortal)(l,document.body)}let eW=function({scene:e,project:t,videoQualityTier:a,onConfirm:n,onCancel:s}){let[o,l]=(0,i.useState)(null),d=(0,i.useRef)(!0);(0,i.useEffect)(()=>(d.current=!0,()=>{d.current=!1}),[]);let c=e.media,{authorizedMediaUrl:u,authorizedThumbnailUrl:p}=C(c?.url||c?.storedUrl,c?.thumbnailUrl,c?.storageKey,void 0,c?.assetRef),m=p||u||c?.thumbnailUrl||c?.url||"",h=function(e,t){let a=t?.facelessStoryboard?.plan;if(!a||!Array.isArray(a.scenes))return null;let r=(0,ef.nh)(e.id,{projectScenes:t?.scenes,planScenes:a.scenes,liveSyncSceneMap:new Map,detachedPlanSceneIds:new Set(t?.facelessStoryboard?.detachedPlanSceneIds??[])});return r?a.scenes.find(e=>e.id===r)??null:null}(e,t),f=t?.facelessSettings?.blueprintSettings?.animation?.imageGuidanceDefault,g=(0,eP.vT)(f)?f:"choose_per_scene",x=a??t?.facelessSettings?.videoQualityTier??"720p";return o?(0,r.jsx)(eB,{kind:o,onClose:()=>{l(null),s()}}):(0,r.jsx)(e$.h,{imageUrl:m,narrationText:h?.narrationText??"",animationPrompt:h?.animationPrompt,animationPromptSource:h?.animationPromptSource,sceneDuration:ew(e),durationSource:"manual",defaultVideoModelKey:t?.facelessSettings?.videoModel,videoQualityTier:x,imageGuidanceDefault:g,onConfirm:(e,t,a,r,i,s)=>{(async()=>{let r=await n(e,t,a,i,s);r?.blocked&&d.current&&l(r.blocked)})()},onCancel:s})};var eU=a(85389),eK=a(80324),eV=a(88587);function eH({isOpen:e,isSubmitting:t,errorMessage:a,defaultDownloadSource:n="media",onClose:s,onSubmit:o}){let{voices:l,isLoading:d}=(0,eU.f)(),[c,u]=(0,i.useState)(!1),[m,h]=(0,i.useState)("rarehistoricalphotos"),[f,b]=(0,i.useState)(12),[y,v]=(0,i.useState)("top"),[w,S]=(0,i.useState)("week"),[j,I]=(0,i.useState)(!0),[N,C]=(0,i.useState)(20),[M,_]=(0,i.useState)(!0),[A,E]=(0,i.useState)(!0),[T,$]=(0,i.useState)("auto"),[P,D]=(0,i.useState)(n),[R,z]=(0,i.useState)(null);(0,i.useEffect)(()=>{u(!0)},[]),(0,i.useEffect)(()=>{e?D(n):z(null)},[n,e]);let L=(0,i.useMemo)(()=>l.filter(e=>!!(e.voice_id&&e.name)),[l]);if(!c||!e)return null;let F=async e=>{e.preventDefault();let t=m.trim().replace(/^https?:\/\/(www\.)?reddit\.com\/r\//i,"").replace(/^r\//i,"").replace(/\/.*$/,"").trim();t?(z(null),await o({subreddit:t,limit:f,sort:y,time_range:w,include_short_videos:j,max_video_duration_seconds:N,generate_voiceovers:M,generate_captions:M&&A,voice_id:M&&"auto"!==T?T:void 0,summary_style:"rare-photo-short",download_source_override:P})):z("Enter a subreddit to import from.")},O="w-full rounded-lg border border-white/[0.07] bg-white/[0.03] px-3 py-2.5 text-sm text-white/90 outline-none transition-colors duration-150 placeholder:text-white/20 focu
73s:border-emerald-400/40 focus:bg-white/[0.05]",B=`${O} disabled:cursor-not-allowed disabled:opacity-40`,W="text-[11px] font-semibold uppercase tracking-[0.18em] text-white/30";return(0,p.createPortal)((0,r.jsx)("div",{className:"fixed inset-0 z-[9998] flex items-center justify-center bg-black/80 backdrop-blur-md",children:(0,r.jsxs)("div",{className:"relative mx-4 w-full max-w-3xl overflow-hidden rounded-2xl border border-white/[0.07] bg-[#0a0f1e] shadow-[0_32px_80px_rgba(0,0,0,0.6)]",children:[(0,r.jsx)("div",{className:"pointer-events-none absolute -top-24 left-1/2 h-48 w-[400px] -translate-x-1/2 rounded-full bg-emerald-500/[0.06] blur-[80px]"}),(0,r.jsxs)("div",{className:"relative flex items-start justify-between border-b border-white/[0.06] px-6 py-5",children:[(0,r.jsxs)("div",{className:"space-y-2.5",children:[(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-emerald-400/15 bg-emerald-400/[0.06] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.2em] text-emerald-300/70",children:[(0,r.jsx)(k.A,{className:"h-3 w-3"}),"Reddit Photo Short"]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("h2",{className:"text-lg font-semibold tracking-tight text-white",children:"Import a ready-made Reddit batch"}),(0,r.jsx)("p",{className:"mt-1 max-w-xl text-[13px] leading-5 text-white/35",children:"Pull in image posts and short Reddit videos, write one-line voiceovers, and build a vertical sequence with captions and motion already applied."})]})]}),(0,r.jsx)("button",{type:"button",onClick:s,disabled:t,className:"rounded-lg p-1.5 text-white/25 transition-colors duration-150 hover:bg-white/[0.06] hover:text-white/60 disabled:cursor-not-allowed disabled:opacity-50","aria-label":"Close Reddit photo short importer",children:(0,r.jsx)(H.A,{className:"h-4 w-4"})})]}),(0,r.jsxs)("form",{onSubmit:F,className:"space-y-5 px-6 py-5",children:[(0,r.jsxs)("div",{className:"grid gap-3 md:grid-cols-2",children:[(0,r.jsxs)("label",{className:"space-y-1.5",children:[(0,r.jsx)("span",{className:W,children:"Subreddit"}),(0,r.jsx)("input",{value:m,onChange:e=>h(e.target.value),placeholder:"rarehistoricalphotos",className:O})]}),(0,r.jsxs)("label",{className:"space-y-1.5",children:[(0,r.jsx)("span",{className:W,children:"Post Count"}),(0,r.jsx)("input",{type:"number",min:1,max:20,value:f,onChange:e=>b(Math.min(20,Math.max(1,Number(e.target.value)||1))),className:O})]}),(0,r.jsxs)("label",{className:"space-y-1.5",children:[(0,r.jsx)("span",{className:W,children:"Sort"}),(0,r.jsxs)("select",{value:y,onChange:e=>v(e.target.value),className:O,children:[(0,r.jsx)("option",{value:"top",children:"Top"}),(0,r.jsx)("option",{value:"hot",children:"Hot"}),(0,r.jsx)("option",{value:"new",children:"New"}),(0,r.jsx)("option",{value:"rising",children:"Rising"})]})]}),(0,r.jsxs)("label",{className:"space-y-1.5",children:[(0,r.jsx)("span",{className:W,children:"Time Range"}),(0,r.jsxs)("select",{value:w,onChange:e=>S(e.target.value),disabled:"top"!==y,className:B,children:[(0,r.jsx)("option",{value:"hour",children:"Hour"}),(0,r.jsx)("option",{value:"day",children:"Day"}),(0,r.jsx)("option",{value:"week",children:"Week"}),(0,r.jsx)("option",{value:"month",children:"Month"}),(0,r.jsx)("option",{value:"year",children:"Year"}),(0,r.jsx)("option",{value:"all",children:"All"})]})]})]}),(0,r.jsxs)("div",{className:"grid gap-3 lg:grid-cols-[1.2fr_0.8fr]",children:[(0,r.jsxs)("div",{className:"rounded-xl border border-white/[0.05] bg-white/[0.015] p-4",children:[(0,r.jsxs)("div",{className:"mb-3",children:[(0,r.jsx)("h3",{className:"text-sm font-semibold text-white/80",children:"Media Filters"}),(0,r.jsx)("p",{className:"mt-0.5 text-[12px] leading-4 text-white/25",children:"Keep the batch focused on photo-first content and short clips."})]}),(0,r.jsxs)("label",{className:"flex items-start gap-3 rounded-lg border border-white/[0.05] bg-white/[0.02] p-3 transition-colors duration-150 hover:bg-white/[0.04]",children:[(0,r.jsx)("input",{type:"checkbox",checked:j,onChange:e=>I(e.target.checked),className:"mt-0.5 h-4 w-4 rounded border-white/20 bg-transparent text-emerald-500 accent-emerald-500"}),(0,r.jsxs)("span",{className:"space-y-0.5",children:[(0,r.jsx)("span",{className:"block text-sm font-medium text-white/80",children:"Include short Reddit videos"}),(0,r.jsx)("span",{className:"block text-[12px] text-white/30",children:"Pull in Reddit-hosted videos alongside still images."})]})]}),(0,r.jsxs)("label",{className:"mt-3 block space-y-1.5",children:[(0,r.jsx)("span",{className:W,children:"Max Video Length"}),(0,r.jsx)("input",{type:"number",min:3,max:120,value:N,onChange:e=>C(Math.min(120,Math.max(3,Number(e.target.value)||3))),disabled:!j,className:B})]}),(0,r.jsxs)("label",{className:"mt-3 block space-y-1.5",children:[(0,r.jsx)("span",{className:W,children:"Reddit Download Mode"}),(0,r.jsxs)("select",{value:P,onChange:e=>D(e.target.value),className:O,children:[(0,r.jsx)("option",{value:"media",children:"Media URL"}),(0,r.jsx)("option",{value:"page",children:"Post page"})]})]})]}),(0,r.jsxs)("div",{className:"rounded-xl border border-white/[0.05] bg-white/[0.015] p-4",children:[(0,r.jsx)("h3",{className:"text-sm font-semibold text-white/80",children:"Voice and Captions"}),(0,r.jsx)("p",{className:"mt-0.5 text-[12px] leading-4 text-white/25",children:"Voiceovers drive the scene timing. Captions are generated from the final audio."}),(0,r.jsxs)("label",{className:"mt-3 flex items-start gap-3 rounded-lg border border-white/[0.05] bg-white/[0.02] p-3 transition-colors duration-150 hover:bg-white/[0.04]",children:[(0,r.jsx)("input",{type:"checkbox",checked:M,onChange:e=>{let t=e.target.checked;_(t),t||E(!1)}
73,className:"mt-0.5 h-4 w-4 rounded border-white/20 bg-transparent text-emerald-500 accent-emerald-500"}),(0,r.jsxs)("span",{className:"space-y-0.5",children:[(0,r.jsx)("span",{className:"block text-sm font-medium text-white/80",children:"Generate voiceovers"}),(0,r.jsx)("span",{className:"block text-[12px] text-white/30",children:"Write a one-line narration for each scene and synthesize it automatically."})]})]}),(0,r.jsxs)("label",{className:"mt-2 flex items-start gap-3 rounded-lg border border-white/[0.05] bg-white/[0.02] p-3 transition-colors duration-150 hover:bg-white/[0.04]",children:[(0,r.jsx)("input",{type:"checkbox",checked:A,onChange:e=>E(e.target.checked),disabled:!M,className:"mt-0.5 h-4 w-4 rounded border-white/20 bg-transparent text-emerald-500 accent-emerald-500 disabled:cursor-not-allowed"}),(0,r.jsxs)("span",{className:"space-y-0.5",children:[(0,r.jsx)("span",{className:"block text-sm font-medium text-white/80",children:"Generate captions"}),(0,r.jsx)("span",{className:"block text-[12px] text-white/30",children:"Build timed caption blocks from the generated voiceover audio."})]})]}),(0,r.jsxs)("label",{className:"mt-3 block space-y-1.5",children:[(0,r.jsx)("span",{className:W,children:"Voice"}),(0,r.jsxs)("select",{value:T,onChange:e=>{let t=e.target.value;eV.Wt&&"auto"!==t&&"elevenlabs"===(0,eK.BY)(t,L.find(e=>e.voice_id===t)?.name)||$(t)},disabled:!M,className:B,children:[(0,r.jsx)("option",{value:"auto",children:"Auto-select on the server"}),L.map(e=>{let t=eV.Wt&&"elevenlabs"===(0,eK.BY)(e.voice_id,e.name);return(0,r.jsx)("option",{value:e.voice_id,disabled:t,children:t?`${e.name} (Coming Soon)`:e.name},e.voice_id)})]}),(0,r.jsx)("p",{className:"text-[11px] text-white/20",children:d?"Loading available voices...":`${L.length} voices available.`})]})]})]}),(R||a)&&(0,r.jsxs)("div",{className:"flex items-start gap-2.5 rounded-lg border border-rose-500/15 bg-rose-500/[0.06] px-4 py-2.5 text-[13px] leading-5 text-rose-200/70",children:[(0,r.jsx)(g.A,{className:"mt-0.5 h-4 w-4 flex-shrink-0 text-rose-400/60"}),(0,r.jsx)("span",{children:R||a})]}),(0,r.jsxs)("div",{className:"flex items-start gap-2.5 rounded-lg border border-amber-500/10 bg-amber-500/[0.04] px-4 py-2.5 text-[12px] leading-5 text-amber-200/50",children:[(0,r.jsx)(g.A,{className:"mt-0.5 h-3.5 w-3.5 flex-shrink-0 text-amber-400/40"}),(0,r.jsx)("span",{children:"Gallery posts import all images as separate scenes. Each post generates one voiceover for the primary image."})]}),(0,r.jsxs)("div",{className:"flex items-center justify-end gap-2.5 border-t border-white/[0.05] pt-4",children:[(0,r.jsx)("button",{type:"button",onClick:s,disabled:t,className:"rounded-lg border border-white/[0.08] bg-transparent px-4 py-2 text-sm font-medium text-white/40 transition-colors duration-150 hover:border-white/15 hover:text-white/60 disabled:cursor-not-allowed disabled:opacity-50",children:"Cancel"}),(0,r.jsxs)("button",{type:"submit",disabled:t,className:"inline-flex items-center gap-2 rounded-lg bg-white px-5 py-2 text-sm font-semibold text-zinc-900 shadow-[0_1px_8px_rgba(255,255,255,0.1)] transition-all duration-200 hover:bg-zinc-100 hover:shadow-[0_2px_14px_rgba(255,255,255,0.16)] disabled:cursor-not-allowed disabled:opacity-50",children:[t?(0,r.jsx)(x.A,{className:"h-4 w-4 animate-spin"}):(0,r.jsx)(k.A,{className:"h-4 w-4"}),(0,r.jsx)("span",{children:t?"Importing...":"Build Short"})]})]})]})]})}),document.body)}var eq=a(69203),eY=a(1275);let eG=[{key:"rights",title:"I own this content or have permission from the rights holder to import and use it.",detail:"Do not import Reddit media just because it is publicly visible."},{key:"export",title:"I understand FrameCompose does not assume I have export, publishing, or commercial rights to Reddit content.",detail:"Public and commercial use may require separate rights or platform approval."},{key:"personal",title:"I will use this Reddit import flow only for internal review, testing, or personal experimentation unless my broader rights are confirmed.",detail:"This is the conservative posture reflected in the current legal constraints memo."},{key:"removal",title:"I understand imported Reddit content may need to be removed if rights, platform rules, or deleti
73on requests require it.",detail:"Long-term retention and downstream use should be treated cautiously."}];function eX({isOpen:e,onAccept:t,onClose:a}){let[n,s]=(0,i.useState)(!1),[o,l]=(0,i.useState)({rights:!1,export:!1,personal:!1,removal:!1});(0,i.useEffect)(()=>{s(!0)},[]),(0,i.useEffect)(()=>{e||l({rights:!1,export:!1,personal:!1,removal:!1})},[e]);let d=(0,i.useMemo)(()=>eG.every(e=>o[e.key]),[o]),c=(0,i.useMemo)(()=>eG.filter(e=>o[e.key]).length,[o]);return n&&e?(0,p.createPortal)((0,r.jsx)("div",{className:"fixed inset-0 z-[9999] flex items-center justify-center bg-black/80 backdrop-blur-md",children:(0,r.jsxs)("div",{className:"relative mx-4 w-full max-w-2xl overflow-hidden rounded-2xl border border-white/[0.07] bg-[#0a0f1e] shadow-[0_32px_80px_rgba(0,0,0,0.6)]",children:[(0,r.jsx)("div",{className:"pointer-events-none absolute -top-20 left-1/2 h-44 w-[360px] -translate-x-1/2 rounded-full bg-amber-500/[0.05] blur-[80px]"}),(0,r.jsxs)("div",{className:"relative border-b border-white/[0.06] px-6 py-5",children:[(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-amber-400/15 bg-amber-400/[0.06] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.2em] text-amber-300/70",children:[(0,r.jsx)(eq.A,{className:"h-3 w-3"}),"Reddit Usage Confirmation"]}),(0,r.jsx)("h2",{className:"mt-3 text-lg font-semibold tracking-tight text-white",children:"Confirm rights before importing Reddit content"}),(0,r.jsx)("p",{className:"mt-1.5 max-w-xl text-[13px] leading-5 text-white/35",children:"Based on the current Reddit legal-constraints review, this workflow should be treated as conservative and prototype-only unless your rights and use case are clearly covered."})]}),(0,r.jsxs)("div",{className:"space-y-4 px-6 py-5",children:[(0,r.jsxs)("div",{className:"rounded-xl border border-amber-500/10 bg-amber-500/[0.04] px-4 py-3 text-[13px] leading-5 text-amber-200/50",children:["Importing Reddit content for review is lower risk than exporting or commercially publishing it. Public, commercial, and derivative-use rights should not be assumed.",(0,r.jsx)("span",{className:"mt-1 block text-[11px] text-amber-200/30",children:"This is a product guardrail, not legal advice."})]}),(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsxs)("label",{className:`mb-1 flex cursor-pointer items-center gap-2.5 rounded-xl border p-3 transition-colors duration-150 ${d?"border-sky-400/20 bg-sky-400/[0.04]":"border-white/[0.05] bg-white/[0.015] hover:bg-white/[0.03]"}`,children:[(0,r.jsx)("input",{type:"checkbox",checked:d,onChange:()=>{let e=!d;l({rights:e,export:e,personal:e,removal:e})},className:"h-4 w-4 rounded border-white/20 bg-transparent text-sky-500 accent-sky-500"}),(0,r.jsx)("span",{className:"text-[13px] font-medium text-white/50",children:d?"Uncheck all":`Check all (${c}/${eG.length})`})]}),eG.map(e=>(0,r.jsxs)("label",{className:`flex cursor-pointer items-start gap-3 rounded-xl border p-3.5 transition-colors duration-150 ${o[e.key]?"border-sky-400/20 bg-sky-400/[0.04]":"border-white/[0.05] bg-white/[0.015] hover:bg-white/[0.03]"}`,children:[(0,r.jsx)("input",{type:"checkbox",checked:o[e.key],onChange:()=>{let t;return t=e.key,l(e=>({...e,[t]:!e[t]}))},className:"mt-0.5 h-4 w-4 rounded border-white/20 bg-transparent text-sky-500 accent-sky-500"}),(0,r.jsxs)("span",{className:"space-y-0.5",children:[(0,r.jsx)("span",{className:"block text-[13px] font-medium leading-5 text-white/75",children:e.title}),(0,r.jsx)("span",{className:"block text-[11px] leading-4 text-white/25",children:e.detail})]})]},e.key))]}),(0,r.jsxs)("div",{className:"flex items-center justify-between rounded-xl border border-white/[0.05] bg-white/[0.015] px-3.5 py-2.5",children:[(0,r.jsx)("span",{className:"text-[11px] text-white/25",children:"Shared quota risk, unclear commercial rights, no assumed export license"}),(0,r.jsxs)("a",{href:"https://redditinc.com/policies/data-api-terms",target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-[11px] font-medium text-sky-300/60 transition-colors hover:text-sky-300/80",children:["Terms",(0,r.jsx)(eY.A,{className:"h-3 w-3"})]})]})]}),(0,r.jsxs)("div",{className:"flex items-center justify-end gap-2.5 border-t border-white/[0.05] px-6 py-4",children:[(0,r.jsx)("button",{type:"button",onClick:a,className:"rounded-lg border border-white/[0.08] bg-transparent px-4 py-2 text-sm font-medium text-white/40 transition-colors duration-150 hover:border-white/15 hover:text-white/60",children:"Cancel"}),(0,r.jsxs)("button",{type:"button",onClick:t,disabled:!d,className:"inline-flex items-center gap-2 rounded-lg bg-white px-5 py-2 text-sm font-semibold text-zinc-900 shadow-[0_1px_8px_rgba(255,255,255,0.1)] transition-all duration-200 hover:bg-zinc-100 hover:shadow-[0_2px_14px_rgba(255,255,255,0.16)] disabled:cursor-not-allowed disabled:opacity-40",children:[(0,r.jsx)(h.A,{className:"h-4 w-4"}),"Continue to Reddit import"]}
73)]})]})}),document.body):null}var eJ=a(20032),eZ=a(9756);function eQ(e){return(e.split("/").pop()||"file").replace(/^file-/,"")}function e0(e,t,a){if(!e||!t||e.id!==t)return e;let r=e.scenes.find(e=>e.id===a);return r&&r.media?.status==="uploading"?{...e,scenes:e.scenes.map(e=>e===r?{...e,isLoading:!1,media:{...e.media,status:"ready"}}:e)}:e}var e1=a(14539);let e5=16/9,e2={width:702,height:395},e4=({projectId:e,timelineHeight:t,compactViewport:a=!1,compactTopInset:n=0})=>{(0,l.C)("ResizableMasterPreview");let{currentProject:o,updateMasterPreviewSize:c,updateMasterPreviewLocked:u}=(0,s.By)(),p=o?.id,m=o?.masterPreviewLocked===!0,h=d.Wg.MASTER_PREVIEW_FULLSCREEN_DOUBLE_CLICK,f=o?.masterPreviewSize??e2,[g,x]=(0,i.useState)(f),[b,y]=(0,i.useState)({x:0,y:40}),[v,w]=(0,i.useState)(!1),[k,S]=(0,i.useState)(!1),[j,I]=(0,i.useState)(!1),[N,C]=(0,i.useState)({x:0,y:0}),[M,_]=(0,i.useState)(null),[A,E]=(0,i.useState)({x:0,y:0,width:0,height:0,startX:0,startY:0}),[T,$]=(0,i.useState)(!1),P=(0,i.useRef)(!0),[D,R]=(0,i.useState)({size:{width:702,height:395},position:{x:20,y:40}}),[z,L]=(0,i.useState)(0),F=(0,i.useRef)(g),O=(0,i.useRef)(b),B=(0,i.useRef)(!1),W=(0,i.useRef)(!1),U=(0,i.useRef)(!1),K=(0,i.useRef)(40),V=((0,i.useRef)(!1),(0,i.useRef)(o?.id)),H=(0,i.useRef)(o?.masterPreviewSize??null),q=(0,i.useRef)(!1);(0,i.useEffect)(()=>{!p||m||u(!0)},[p,m,u]);let Y=(0,i.useCallback)(()=>{let e=document.querySelector("[data-project-header]"),t=e?Math.round(e.getBoundingClientRect().height):40;return K.current=t,t},[]),G=(0,i.useCallback)(()=>{if(a)return window.innerWidth-8;let e=document.querySelector("[data-ai-rail-container]");return e?Math.max(280,Math.round(e.getBoundingClientRect().left)):window.innerWidth},[a]),X=(0,i.useCallback)(()=>{let e=Math.max(Y(),40)+(a?n>0?n:8:0),r=Math.max(280/e5,(void 0!==t?window.innerHeight-Math.max(0,t)-8*!!a:window.innerHeight-20-8*!!a)-e),i=Math.max(280,.74*Math.max(280,Math.min(2400,Math.max(280,G()-0),r*e5)));return{width:i,height:i/e5}},[n,a,G,Y,t]),J=(0,i.useCallback)(()=>{if(a)return 8;let e=document.querySelector("[data-media-bin-container]");return e?Math.round(e.getBoundingClientRect().right):0},[a]),Z=(0,i.useCallback)(()=>{let e=Math.max(K.current,40)+(a?n>0?n:8:0),r=J(),i=void 0!==t?window.innerHeight-Math.max(0,t)-8*!!a:window.innerHeight-20-8*!!a;return{minX:r,minY:e,maxRight:G(),maxBottom:i}},[n,a,G,J,t]),Q=(0,i.useCallback)(()=>{let e=Math.max(Y(),40)+(a?n>0?n:8:0),r=J(),i=Math.max(r+1,G()),s=document.querySelector("[data-master-timeline]"),o=s?Math.round(s.getBoundingClientRect().height):Math.max(0,t??0),l=Math.max(e+1,window.innerHeight-Math.max(0,o)-8*!!a);return{left:r,right:i,top:e,bottom:l}},[n,a,Y,J,G,t]),ee=(0,i.useCallback)((e,t)=>{window.dispatchEvent(new CustomEvent("preview-right-edge-resize",{detail:{rightEdge:e+t}})),window.dispatchEvent(new CustomEvent("preview-left-edge-resize",{detail:{leftEdge:e}}))},[]),et=(0,i.useCallback)(e=>{window.dispatchEvent(new CustomEvent("preview-vertical-resize",{detail:{bottomEdge:e}}))},[]),ea=(0,i.useCallback)((e,t)=>{let r=J(),n=Math.min(window.innerWidth-0,t.maxRight),i=t.maxBottom,s=e.x,o=e.y,l=[{distance:Math.abs(s-r),targetX:r},{distance:Math.abs(s+e.width-n),targetX:n-e.width}];if(!a){let t=document.querySelector("[data-media-bin-container]");if(t){let a=Math.round(t.getBoundingClientRect().right);l.push({distance:Math.abs(s-a),targetX:a},{distance:Math.abs(s+e.width-a),targetX:a-e.width})}let a=document.querySelector("[data-ai-rail-container]");if(a){let t=Math.round(a.getBoundingClientRect().left);l.push({distance:Math.abs(s+e.width-t),targetX:t-e.width},{distance:Math.abs(s-t),targetX:t})}}let d=l.reduce((e,t)=>t.distance<e.distance?t:e);d.distance<=18&&(s=Math.max(r,Math.min(n-e.width,d.targetX)));let c=Math.abs(o-t.minY),u=Math.abs(o+e.height-i);return(c<=18||u<=18)&&(o=c<=u?t.minY:i-e.height),{...e,x:s,y:o}},[a,J]);(0,i.useEffect)(()=>{F.current=g},[g]),(0,i.useEffect)(()=>{O.current=b},[b]),(0,i.useEffect)(()=>{B.current=v},[v]),(0,i.useEffect)(()=>{W.current=k},[k]),(0,i.useEffect)(()=>{Y()},[Y]),(0,i.useEffect)(()=>{o?.masterPreviewSize},[o?.masterPreviewSize,k,v,T,!0]);let er=(0,i.useCallback)(e=>{if(!c||T)return;let t={width:Math.round(e.width),height:Math.round(e.height)},a=H.current;a&&a.width===t.width&&a.height===t.height||(H.current=t,c(t))},[c,T]),en=(0,i.useCallback)(()=>
73{if(!P.current||T||!es.current)return;let{left:e,right:t,top:a,bottom:r}=Q(),n=Math.max(1,t-e),i=Math.max(1,r-a),s=F.current,o=O.current;if(!(Math.abs(s.width-n)>=1||Math.abs(s.height-i)>=1||Math.abs(o.x-e)>=1||Math.abs(o.y-a)>=1))return;let l=es.current;l.style.transition="none",l.style.left=`${e}px`,l.style.top=`${a}px`,l.style.width=`${n}px`,l.style.height=`${i}px`,F.current={width:n,height:i},O.current={x:e,y:a},x({width:n,height:i}),y({x:e,y:a}),er({width:n,height:i}),ee(e,n)},[T,Q,er,ee]);(0,i.useEffect)(()=>{if(!P.current||T)return;let e=()=>{en()};return window.addEventListener("ai-rail-left-edge-resize",e),window.addEventListener("ai-rail-resize-end",e),()=>{window.removeEventListener("ai-rail-left-edge-resize",e),window.removeEventListener("ai-rail-resize-end",e)}},[!0,T,en]),(0,i.useEffect)(()=>{if(!P.current||T)return;let e=()=>{en()};return window.addEventListener("media-bin-right-edge-resize",e),window.addEventListener("media-bin-resize-end",e),()=>{window.removeEventListener("media-bin-right-edge-resize",e),window.removeEventListener("media-bin-resize-end",e)}},[!0,T,en]);let ei=(0,i.useCallback)(e=>{let t=G()-e;return{x:Math.max(J(),t),y:40}},[G,J]);(0,i.useEffect)(()=>{if(!o){H.current=null,V.current=void 0;return}if(V.current===o.id)return;V.current=o.id;let e=o.masterPreviewSize??X();x(e),H.current=o.masterPreviewSize?{width:Math.round(o.masterPreviewSize.width),height:Math.round(o.masterPreviewSize.height)}:null,y(ei(e.width))},[o,ei,X]);let es=(0,i.useRef)(null);(0,i.useEffect)(()=>{P.current&&!T&&en()},[p,n,a,T,t,en]),(0,i.useEffect)(()=>{},[g.width,g.height,Z,ei,Y,!0]),(0,i.useEffect)(()=>{},[b.x,b.y,g.width,g.height,T,v,k,Z,Y,!0]),(0,i.useEffect)(()=>{let e=document.querySelector("[data-master-timeline]");if(!e)return;let t=new ResizeObserver(()=>{if(!es.current||T||B.current||W.current)return;let t=e.getBoundingClientRect(),a=window.innerHeight-Math.max(0,t.height),r=O.current,n=F.current,i=P.current,s=r.y+n.height;if(i)return void en();if(!i&&s<=a+3)return;let o=Math.max(1,a-r.y),l=n.width,d=r.x;l=Math.max(280,(o=Math.max(280/e5,Math.min(n.height,a-r.y)))*e5);let c=r.x+n.width,u=J();d=Math.max(u,c-l);let p=G()-d-0;if(l>p&&p>280&&(o=(l=p)/e5,d=Math.max(u,c-l)),1>Math.abs(o-n.height)&&1>Math.abs(l-n.width)&&1>Math.abs(d-r.x))return;let m=es.current;m.style.transition="none",m.style.width=`${l}px`,m.style.height=`${o}px`,m.style.left=`${d}px`,F.current={width:l,height:o},O.current={...O.current,x:d},ee(d,l),x({width:l,height:o}),y(e=>1>Math.abs(e.x-d)?e:{...e,x:d})});return t.observe(e),()=>{t.disconnect()}},[T,J,G,ee,en]);let eo=(0,i.useCallback)(e=>{if(P.current)return;let t=e.target;if(t.closest(".resize-handle")||t.closest("button")||t.closest('input[type="range"]')||t.closest(".group-hover\\:opacity-100")||t.closest("[data-master-timeline]")||k)return;let a=e.currentTarget.getBoundingClientRect(),r=e.clientX-a.left,n=e.clientY-a.top;r<10||r>a.width-10||n<10||n>a.height-10||_({clientX:e.clientX,clientY:e.clientY,offsetX:e.clientX-b.x,offsetY:e.clientY-b.y})},[b,k]),[el,ed]=(0,i.useState)(""),ec=((0,i.useCallback)((e,t)=>{if(e.stopPropagation(),S(!0),ed(t),U.current=!1,E({x:e.clientX,y:e.clientY,width:g.width,height:g.height,startX:b.x,startY:b.y}),["w","nw","sw"].includes(t)){let e=document.querySelector("[data-media-bin-container]");if(e){let t=Math.round(e.getBoundingClientRect().right);q.current=20>Math.abs(b.x-t)}else q.current=!1}else q.current=!1;e.preventDefault()},[g.width,g.height,b.x,b.y]),(0,i.useCallback)(()=>{if(!h)return;let e=es.current;e&&(T?(document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen?document.webkitExitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.msExitFullscreen&&document.msExitFullscreen(),x(D.size),y(D.position),$(!1)):(R({size:g,position:b}),e.requestFullscreen?e.requestFullscreen():e.webkitRequestFullscreen?e.webkitRequestFullscreen():e.mozRequestFullScreen?e.mozRequestFullScreen():e.msRequestFullscreen&&e.msRequestFullscreen(),x({width:window.screen.width,height:window.screen.height}),y({x:0,y:0}),$(!0)))},[h,T,D,g,b])),eu=(0,i.useCallback)(e=>{if(e.stopPropagation(),!h)return;let t=Date.now(),a=t-z;a<300&&a>0&&ec(),L(t)},[h,z,ec]);return(0,i.useEffect)(()=>{let e=()=>{!(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)&&T&&(x(D.size),y(D.position),$(!1))};return document.addEventListener("fullscreenchange",e),document.addEventListener("webkitfullscreenchange",e),document.addEventListener("mozfullscreenchange",e),document.addEventListener("MSFullscreenChange",e),()=>{document.removeEventListener("fullscreenchange",e),document.removeEventListener("webkitfullscreenchange",e),document.removeEventListener("mozfullscreenchange",e),document.removeEventListener("MSFullscreenChange",e)}},[T,D]),(0,i.useCallback)(e=>{e.stopPropagation();let t=Y(),{minY:a,maxRight:r,maxBottom:n}=Z();if(10>Math.abs(g.width-280)){let e,i,s=window.innerWidth-0,o=n-t,l=Math.min(s,2400),d=l/e5;d<=o?(e=l,i=d):e=(i=o)*e5;let c=Math.min((window.innerWidth-e)/2,null!=r?r-e:1/0),u=Math.max(a,t+(o-i)/2),p={width:e,height:i};x(p),y({x:c,y:u}),U.current=!1,er(p)}else{let e={width:280,height:280/e5};x(e),U.current=!1,er(e)}},[g.width,er,Z,Y]),(0,i.useEffect)(()=>{let e=e=>{if(M&&!v&&!k){let t=e.clientX-M.clientX,a=e.clientY-M.clientY;(Math.abs(t)>5||Math.abs(a)>5)&&(w(!0),C({x:M.offsetX,y:M.offsetY}),_(null));return}if(v&&!k){let t=e.clientX-N.x,a=e.clientY-N.y,r=a+F.current.height;{let{minY:e,maxBottom:n}=Z(),i=document.querySelector("[data-ai-rail-container]"),s=i?Math.round(i.getBoundingClientRect().width):0,o=s>0?Math.min(s,320):0,l=Math.max(200,window.innerWidth-o-g.width-0),d=Math.max(e,n-g.height),c={x:Math.max(200,Math.min(l,t)),y:Math.max(e,Math.min(d,a)),width:g.width,height:g.height},u={x:Math.max(200,Math.min(l,c.x)),y:Math.max(e,Math.min(d,c.y))};if(P.current)et(Math.max(e+F.current.height,r)),ee(u.x,F.current.width);else{let e=document.querySelector("[data-media-bin-container]"),t=e?Math.round(e.getBoundingClientRect().right):200,a=i?Math.round(i.getBoundingClientRect().left):window.innerWidth,s=u.x+F.current.width;u.x<=t+1&&window.dispatchEvent(new CustomEvent("preview-left-edge-resize",{detail:{leftEdge:u.x}})),s>=a-1&&window.dispatchEvent(new CustomEvent("preview-right-edge-resize",{detail:{rightEdge:s}})),r>=n-1&&et(Math.max(n-1,r))}y(u)}}if(k){let t=e.clientX-A.x,a=e.clientY-A.y,r=A.width,n=A.height,i=A.startX,s=A.startY;switch(el){case"se":n=(r=Math.max(280,Math.min(2400,A.width+t)))/e5;break;case"sw":n=(r=Math.max(280,Math.min(2400,A.width-t)))/e5,i=A.startX+(A.width-r);break;case"ne":n=(r=Math.max(280,Math.min(2400,A.width+t)))/e5,s=A.startY+(A.height-n);break;case"nw":n=(r=Math.max(280,Math.min(2400,A.width-t)))/e5,i=A.startX+(A.width-r),s=A.startY+(A.height-n);break;case"e":n=(r=Math.max(280,Math.min(2400,A.width+t)))/e5,s=A.startY+(A.height-n)/2;break;case"w":n=(r=Math.max(280,Math.min(2400,A.width-t)))/e5,i=A.startX+(A.width-r),s=A.startY+(A.height-n)/2;break;case"n":n=(r=Math.min(2400,r=(n=Math.max(280/e5,A.height-a))*e5))/e5,i=A.startX+(A.width-r)/2,s=A.startY+(A.height-n);break;case"s":n=(r=Math.min(2400,r=(n=Math.max(280/e5,A.height+a))*e5))/e5,i=A.startX+(A.width-r)/2}{let{minX:e,minY:t,maxRight:a,maxBottom:o}=Z(),l=q.current?200:e,d=Math.min(window.innerWidth-r-0,null!=a?a-r:1/0),c=Math.max(t,o-n);i=Math.max(l,Math.min(d,i)),s=Math.max(t,Math.min(c,s));let u=(null!=a?Math.min(window.innerWidth,a):window.innerWidth)-i-0,p=o-s;if(r>u||n>p){let e=Math.min(r,u),t=Math.min(n,p);e/e5<=t?(r=e,n=e/e5):(n=t,r=t*e5)}if(!q.current){let e=ea({x:i,y:s,width:r,height:n},{minY:t,maxRight:a,maxBottom:o});i=e.x,s=e.y;let d=Math.min(window.innerWidth-r-0,null!=a?a-r:1/0),c=Math.max(t,o-n);i=Math.max(l,Math.min(d,i)),s=Math.max(t,Math.min(c,s))}}(Math.abs(r-g.width)>8||Math.abs(n-g.height)>8||Math.abs(i-b.x)>4||Math.abs(s-b.y)>4)&&(x({width:r,height:n}),y({x:i,y:s}),U.current=!0,ee(i,r),et(s+n))}},t=null,a=null,r=r=>{a={clientX:r.clientX,clientY:r.clientY,altKey:r.altKey,ctrlKey:r.ctrlKey,metaKey:r.metaKey,shiftKey:r.shiftKey},null===t&&(t=window.requestAnimationFrame(()=>{t=null;let r=a;a=null,r&&e(r)}))},n=()=>{let r;null!==t&&(window.cancelAnimationFrame(t),t=null),r=a,a=null,r&&e(r),_(null),w(!1),S(!1),ed(""),q.current=!1,k&&U.current&&(er(F.current),U.current=!1)};if(v||k||M)return document.addEventListener("mousemove",r),document.addEventListener("mouseup",n),()=>{null!==t&&(window.cancelAnimationFrame(t),t=null),a=null,document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",n)}},[v,k,M,N,A,el,g.width,g.height,b.x,b.y,er,Z,ea,ee,et]),(0,i.useEffect)(()=>{window.dispatchEvent(new CustomEvent("master-preview:layout")),T||ee(b.x,g.width)},[b.x,b.y,g.width,g.height,T,!0,ee]),(0,r.jsxs)("div",{ref:es,"data-master-preview":!0,
73className:`${T?"fixed inset-0 w-full h-full bg-black":"fixed"} select-none ${T?"z-[9999]":"z-[35]"}`,style:T?{}:{left:`${b.x}px`,top:`${b.y}px`,width:`${g.width}px`,height:`${g.height}px`,transition:"none"},onMouseDown:eo,children:[(0,r.jsx)("div",{className:"w-full h-full relative",onClick:eu,children:(0,r.jsx)(e1.A,{projectId:e,className:"w-full h-full",showDebugInfo:j,onToggleDebugInfo:()=>I(!j)})}),!1]})};var e3=a(98500),e8=a.n(e3),e6=a(54921),e9=a(65408),e7=a(8962),te=a(59189),tt=a(15330),ta=a(66763),tr=a(65738),tn=a(12363),ti=a(80167),ts=a(15688),to=a(41189),tl=a(57804),td=a(90467),tc=a(90710),tu=a(5736),tp=a(40852),tm=a(9383);let th=new Set(["apply_scene_effect"]);function tf(e){if(!e.safeToApply||0===e.operations.length||!e.operations.every(e=>th.has(e.kind)))return null;let t=function(e){let t=new Set;for(let a of e.operations){if("string"==typeof a?.sceneId&&a.sceneId.trim()&&t.add(a.sceneId),Array.isArray(a?.sceneIds))for(let e of a.sceneIds)"string"==typeof e&&e.trim()&&t.add(e);if(a?.scope?.type==="scene_ids"&&Array.isArray(a.scope.sceneIds))for(let e of a.scope.sceneIds)"string"==typeof e&&e.trim()&&t.add(e)}return Array.from(t)}(e);return t.length>1?null:1===t.length?t[0]:e.resolvedSceneTarget?.sceneId&&"low"!==e.resolvedSceneTarget.confidence?e.resolvedSceneTarget.sceneId:null}function tg(e){return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}function tx(e){return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}function tb(e){return!!e&&"object"==typeof e&&"string"==typeof e.id}function ty(e,t){if(!t)return e.map(e=>({...e,status:"unapplied"}));let a=e.findIndex(e=>e.id===t);return a<0?e.map(e=>({...e,status:"unapplied"})):e.map((e,t)=>({...e,status:t<=a?"applied":"unapplied"}))}function tv(e,t){if(0===e.length)return null;let a=e[e.length-1];if(t!==a.id)return null;let r=e.length>1?e[e.length-2]:null,n=r?.id??null;return{checkpoints:ty(e,n),activeCheckpointId:n,projectSnapshot:tg(a.beforeProject)}}function tw(e,t,a={}){let r=a.maxCheckpoints??20,n=a.maxBytes??15e5,i=r>0?e.slice(-r):[...e],s={version:1,baseProject:i.length?tg(i[0].beforeProject):null,activeCheckpointId:null===t?null:t&&i.some(e=>e.id===t)?t:i.length?i[i.length-1].id:null,checkpoints:i.map(e=>({id:e.id,planId:e.planId,planSummary:e.planSummary,messageId:e.messageId,createdAt:e.createdAt,afterProject:tg(e.afterProject),autoApplied:e.autoApplied,targetSceneLabel:e.targetSceneLabel??null,receipts:tx(e.receipts)}))};for(;s.checkpoints.length>0&&function(e){try{return JSON.stringify(e).length}catch{return Number.MAX_SAFE_INTEGER}}(s)>n;){let e=s.checkpoints.shift();if(!e)break;s.baseProject=tg(e.afterProject),s.activeCheckpointId&&!s.checkpoints.some(e=>e.id===s.activeCheckpointId)&&(s.activeCheckpointId=s.checkpoints.length?s.checkpoints[s.checkpoints.length-1].id:null)}return 0===s.checkpoints.length&&(s.baseProject=null,s.activeCheckpointId=null),s}var tk=a(15439),tS=a(96330),tj=a(84422);function tI(e,t){if(!e.prompt?.trim())throw Error("Describe the shot before generating.");let a=e.durationTarget??5;if(!Number.isFinite(a)||a<1||a>60)throw Error("Choose a generation duration between 1 and 60 seconds.");let r=(e.videoModel??t.facelessSettings?.videoModel??"pixverse-v4.5").trim().toLowerCase();if(!tS.L4.some(e=>e.value===r))throw Error(`Video model "${r}" is unavailable. Choose a model before generating.`);let n=e.videoQualityTier??t.facelessSettings?.videoQualityTier??"360p";if(!tj.QR.some(e=>e.id===n))throw Error("Choose one of the available video quality levels.");if(!0===e.generateAudio)throw Error("Native generated audio needs the Video Studio confirmation. Existing audio will not be replaced here.");let i=e.referenceSceneIds??[];if(!Array.isArray(i)||i.length>4||i.some(e=>"string"!=typeof e||!e)||new Set(i).size!==i.length)throw Error("Choose up to 4 distinct reference images.");let s=i.map(e=>{let a=t.scenes.find(t=>t.id===e);if(!a)throw Error("A reference image was removed. Review the plan before generating.");if(a.isLoading||a.media?.status&&"ready"!==a.media.status||a.media?.type!=="image")throw Error("Use a completed image as a generation reference. Video restyling is a separate tool.");let r=a.media,n=r.storage_key,i=r.storageKey||n||(r.assetRef?.type==="r2"?r.assetRef.storageKey:void 0)||(0,ex.L)(r.url||""),s=i?(0,ex.$n)(i):r.url;if(!s||!i&&!/^https?:\/\//i.test(s))throw Error("The reference image is still local. Finish its upload before generating.");return{sceneId:a.id,type:"image",url:s,...i?{storageKey:i}:{},source:a.source?.platform==="ai-generation"?"generated":"uploaded",label:(a.text||"Reference image").slice(0,120)}});if(s.length>1&&!r.startsWith("seedance-2.")&&"vidu-q2"!==r)throw Error("This model cannot use multiple reference images. Choose a compatible model or one image.");let o=e.imageGuidanceMode??("vidu-q2"===r?"reference":"first_frame");
73if("first_frame"!==o&&"reference"!==o)throw Error("Choose how the reference image should guide the shot.");let l=(0,eP.NC)(r,o,!1);if(s.length&&e.imageGuidanceMode&&l!==o)throw Error("This model does not support that image guidance. Review the reference role.");let d=(0,tk.nU)(r);return{videoModel:r,videoProvider:d,videoQualityTier:n,imageGuidanceMode:l,references:s,estimatedCredits:(0,tj.Tz)(n,a,d,r)}}function tN(e,t){let a=[];return e?.operations.forEach((e,r)=>{if("generate_scene_visual"===e.kind)try{a.push({operationIndex:r,spec:tI(e,t),error:null})}catch(e){a.push({operationIndex:r,spec:null,error:e instanceof Error?e.message:"Review this generation request."})}}),{entries:a,blocked:a.some(e=>null!==e.error),estimatedCredits:a.reduce((e,t)=>e+(t.spec?.estimatedCredits??0),0)}}var tC=a(46e3),tM=a(21690),t_=a(74698);let tA=new Set(t_.EFFECTS.map(e=>e.type)),tE=new Set(t_.TRANSITIONS.map(e=>e.type)),tT={"transform.userzoom":"userZoom",userzoom:"userZoom",zoom:"userZoom","transform.panx":"panX",panx:"panX","transform.pany":"panY",pany:"panY","transform.rotation":"rotation",rotation:"rotation"},t$={userZoom:{min:tM.D,max:tM.h},panX:{min:-1,max:1},panY:{min:-1,max:1},rotation:{min:-180,max:180}};var tP=a(89325),tD=a(26527),tR=a(25261),tz=a(63557);async function tL(e,t){let a=(0,tC.Wn)(t);if("local"!==e.mode&&e.id&&a)try{let r=await (0,tz.FP)(e.id,a,t.id);if(r.success&&r.data?.status==="ready"&&Array.isArray(r.data.segments))return r.data.segments.map(e=>({start:e.start,end:e.end,text:e.text,words:e.words?.map(e=>({word:e.word,start:e.start,end:e.end}))}))}catch{}let r=await (0,tD.N4)(t,{projectId:"local"!==e.mode?e.id:void 0});if(!r)throw Error("Scene media is unavailable for transcription.");let n=await (0,tz.TZ)(r);if(!n.success||!n.data?.success)throw Error(n.error?.message||n.data?.error_message||"Failed to analyze scene media for captions.");return(n.data.segments??[]).map(e=>({start:e.start,end:e.end,text:e.text,words:e.words?.map(e=>({word:e.word,start:e.start,end:e.end}))}))}function tF(e,t,a,r,n){let i=Math.max(0,n?.trimStart??0),s="number"==typeof n?.sceneDuration&&Number.isFinite(n.sceneDuration)&&n.sceneDuration>0?n.sceneDuration:1/0,o=i+s,l=r.filter(e=>e.end>i&&e.start<o),d=0===l.length&&r.length>0,c=[];for(let n of d?r:l){let r=d?Math.max(0,n.start):Math.max(0,n.start-i),l=(d?n.end:Math.min(s,n.end-i))-r;if(l<=0)continue;let u=Math.max(.05,l),p=d?n.start:Math.max(n.start,i);c.push({id:`caption-${(0,v.generateId)()}`,start:t+r,duration:u,inOffset:0,outOffset:u,fullDuration:u,trackId:a,sceneId:e,captionText:n.text,captionWords:n.words?.filter(e=>d?e.end>0:e.end>i&&e.start<o).map(e=>({word:e.word,start:Math.max(0,e.start-p),end:Math.min(u,e.end-p)})),source:"auto"})}return c}var tO=a(55116),tB=a(53029);function tW(e,t,a){if(!e)return;let r={};for(let[n,i]of Object.entries(e)){if(!i||!Array.isArray(i.keyframes)||0===i.keyframes.length)continue;let e=function(e,t,a){if(!Array.isArray(e.keyframes)||0===e.keyframes.length||!Number.isFinite(t)||!Number.isFinite(a))return;let r=a-t;if(r<=1e-6)return;let n=[...e.keyframes].sort((e,t)=>e.time-t.time),i=n[0].time,s=n[n.length-1].time,o=n[0].value,l=t>i+1e-6,d=a<s-1e-6,c=n.filter(e=>{let r=l?e.time>t+1e-6:e.time>=t-1e-6,n=d?e.time<a-1e-6:e.time<=a+1e-6;return r&&n}).map(e=>t>1e-6?{...e,id:(0,v.generateId)(),time:e.time-t}:{...e}),u=[];return l&&u.push({id:(0,v.generateId)(),time:0,value:(0,tB.W6)(e,t,o)}),u.push(...c),d&&u.push({id:(0,v.generateId)(),time:r,value:(0,tB.W6)(e,a,o)}),0===u.length&&u.push({id:(0,v.generateId)(),time:0,value:(0,tB.W6)(e,t,o)}),{...e,keyframes:u}}(i,t,a);e&&(r[n]=e)}return Object.keys(r).length>0?r:void 0}function tU(e){var t,a;let r=Math.max(0,e.segmentMediaStart-e.previousTrimStart),n=Math.max(r,e.segmentMediaEnd-e.previousTrimStart);return{automation:tW(e.automation,r,n),effects:(t=e.effects,a={assignNewIds:!e.isFirstSegment},t&&0!==t.length?t.map(e=>{let t=a.assignNewIds?(0,v.generateId)():e.id;if(!e.automation)return{...e,id:t};let i=tW(e.automation,r,n);return{...e,id:t,automation:i??{}}}):t)}}function tK(e){return e?e.map(e=>({...e})):null}function tV(e){return e.map(e=>
73e.word).join(" ").trim()}function tH(e){return e?e.map(e=>({...e})):e}function tq(e){return{...e,captionBox:e.captionBox?{...e.captionBox}:e.captionBox,captionStyle:e.captionStyle?{...e.captionStyle}:e.captionStyle,captionHighlightStyle:e.captionHighlightStyle?{...e.captionHighlightStyle}:e.captionHighlightStyle,captionWords:tK(e.captionWords),captionCues:tH(e.captionCues)}}function tY(e){return{id:e.id,sourceCaptionId:e.sourceCaptionId,start:e.start,duration:e.duration,inOffset:e.inOffset,outOffset:e.outOffset,fullDuration:e.fullDuration,trackId:e.trackId,sceneId:e.sceneId,captionText:e.captionText,captionBox:e.captionBox?{...e.captionBox}:e.captionBox,captionStyle:e.captionStyle?{...e.captionStyle}:e.captionStyle,captionHighlightEnabled:e.captionHighlightEnabled,captionHighlightStyle:e.captionHighlightStyle?{...e.captionHighlightStyle}:e.captionHighlightStyle,captionWords:tK(e.captionWords)??void 0,captionCues:tH(e.captionCues)??void 0,captionDisplayMode:e.captionDisplayMode,captionDisplayWindowSize:e.captionDisplayWindowSize,alignmentProvider:e.alignmentProvider,source:e.source??"auto"}}function tG(e,t,a,r,n){let i=!1;return{captions:e.flatMap(e=>{if(e.sceneId!==t||e.start+e.duration<=r+.05)return[e];if(e.start>=r-.05)return i=!0,[{...e,sceneId:a}];let s=r-e.start,o=function(e,t,a,r){let n,i;if(t<=.05||e.duration-t<=.05)return null;let s=e.captionWords?.filter(e=>e.word?.trim())??[];if(0===s.length)return null;let o=s.filter(e=>(e.start+e.end)/2<t).map(e=>({...e,end:Math.min(e.end,t)})).filter(e=>e.end>e.start),l=s.filter(e=>(e.start+e.end)/2>=t).map(e=>({...e,start:Math.max(0,e.start-t),end:Math.max(0,e.end-t)})).filter(e=>e.end>e.start);if(0===o.length||0===l.length)return null;let d=e.duration-t;e.captionCues&&e.captionCues.length>0&&(n=e.captionCues.filter(e=>e.start<t).map(e=>({...e,end:Math.min(e.end,t)})),i=e.captionCues.filter(e=>e.end>t).map(e=>({...e,start:Math.max(0,e.start-t),end:Math.max(0,e.end-t),wordStartIndex:Math.max(0,e.wordStartIndex-o.length),wordEndIndex:Math.max(0,e.wordEndIndex-o.length)})));let c=a(),u=a();return{left:{...e,id:c,sourceCaptionId:c,duration:t,outOffset:e.inOffset+t,fullDuration:t,captionWords:o,captionCues:n,captionText:tV(o)},right:{...e,id:u,sourceCaptionId:u,sceneId:r,start:e.start+t,duration:d,inOffset:0,outOffset:d,fullDuration:d,captionWords:l,captionCues:i,captionText:tV(l)}}}(e,s,n,a);if(o)return i=!0,[o.left,o.right];let l=e.captionWords?.filter(e=>e.word?.trim())??[];return(l.length>0?l.every(e=>(e.start+e.end)/2>=s):e.start+e.duration/2>=r)?(i=!0,[{...e,sceneId:a}]):[e]}),changed:i}}function tX(e,t,a){let r=e.start,n=e.start+e.duration,i=Math.max(r,t),s=Math.min(n,a);if(s-i<.05)return{kind:"outside"};let o=i-r;if(o<.001&&n-s<.001)return{kind:"unchanged"};let l=s-i,d=e.captionWords??null,c=!d||0===d.length||d.every(t=>t.start>=-.001&&t.end<=e.duration+.001),u=d?c?d:d.map(e=>({...e,start:e.start-r,end:e.end-r})):null,p=u?u.map(e=>{let t=Math.max(0,e.start-o),a=Math.max(t,e.end-o);return{...e,start:t,end:Math.max(t,Math.min(l,a))}}).filter(e=>e.start<l&&e.end>e.start):null,m=u?u.filter(e=>e.end-o<=0).length:0,h=e.captionCues,f=h?h.map(e=>({...e,start:Math.max(0,e.start-o),end:Math.min(l,e.end-o),wordStartIndex:Math.max(0,e.wordStartIndex-m),wordEndIndex:Math.max(0,e.wordEndIndex-m)})).filter(e=>e.end>e.start+.001):h,g=p&&d&&p.length!==d.length?tV(p):e.captionText;return{kind:"capped",next:{...e,start:i,duration:l,inOffset:0,outOffset:l,fullDuration:l,captionWords:p??e.captionWords,...void 0!==h?{captionCues:f}:{},captionText:g}}}function tJ(e,t,a,r){let n=!1;return{blocks:e.flatMap(e=>{if("caption"!==e.type||e.sceneId!==t)return[e];let i=tX(e,a,r);return"outside"===i.kind?(n=!0,[]):"unchanged"===i.kind?[e]:(n=!0,[i.next])}),changed:n}}function tZ(e,t,a){let r=t+Math.max(0,a);return(0,tD.CR)(e).some(e=>{if((e.type??"voiceover")!=="voiceover")return!1;let a=e.inOffset??0,n=Math.max(0,(e.outOffset??e.duration??0)-a);if(n<=tD.pF)return!1;let i=e.start;return i+n>t+tD.pF&&i<r-tD.pF})}function tQ(e,t,a,r){var n,i,s;let o;if(a.startShifted){let n=e.scenes.find(e=>e.id===t);
73n&&(n.timelineStart=a.timelineStart),r?.sceneStartMap?.set(t,a.timelineStart)}let l=(n=e.captionBlocks??[],i=a.captionWindow.start,s=a.captionWindow.end,o=!1,{captions:n.flatMap(e=>{if(e.sceneId!==t)return[e];let a=tX(e,i,s);return"outside"===a.kind?(o=!0,[]):"unchanged"===a.kind?[e]:(o=!0,[a.next])}),changed:o});return l.changed&&(e.captionBlocks=l.captions,r?.captionSyncSceneIds?.add(t)),{captionsChanged:l.changed}}function t0(e,t,a,r,n,i,s,o){if(i<=0&&s<=0)return{applied:!1,nextTrimStart:n.start,nextTrimEnd:n.end};let l=e.scenes.findIndex(e=>e.id===t);if(l<0)return{applied:!1,nextTrimStart:n.start,nextTrimEnd:n.end};let d=e.scenes[l];if(!d.media)return{applied:!1,nextTrimStart:n.start,nextTrimEnd:n.end};let c=(0,tO.AQ)({sceneStart:a,prevTrim:n,mediaDuration:null,requestedTrim:{start:n.start+i,end:(n.end??r)-s},mode:"clamp"});return c.applied?(d.media.trim={start:c.trim.start,end:c.trim.end},tQ(e,t,c,o),{applied:!0,nextTrimStart:c.trim.start,nextTrimEnd:c.trim.end}):{applied:!1,nextTrimStart:n.start,nextTrimEnd:n.end}}function t1(e,t){if(t)for(let a of e)t.sceneStartMap?.set(a.id,a.timelineStart??0),t.sceneTrackMap?.set(a.id,Number(a.trackId??1))}function t5(e,t,a,r,n,i){let s=e.scenes.findIndex(e=>e.id===t);if(s<0)return{applied:!1,splitInsertedScenes:0,usedEdgeTrim:!1,usedInternalSplit:!1,hadRemovableRanges:!1,hadInternalRanges:!1,skippedInternalDueToCaptions:!1,skippedInternalDueToVoiceover:!1,skippedForSafety:!0,speechProtectedWindows:0};let o=e.scenes[s];if(!o.media)return{applied:!1,splitInsertedScenes:0,usedEdgeTrim:!1,usedInternalSplit:!1,hadRemovableRanges:!1,hadInternalRanges:!1,skippedInternalDueToCaptions:!1,skippedInternalDueToVoiceover:!1,skippedForSafety:!0,speechProtectedWindows:0};let l=(0,tC.bo)(o),d=o.media.trim??{start:0,end:o.media.duration??l},c=(0,tD.CN)(n,d.start,d.end,r);if(!c||0===c.removalRanges.length)return{applied:!1,splitInsertedScenes:0,usedEdgeTrim:!1,usedInternalSplit:!1,hadRemovableRanges:!1,hadInternalRanges:!1,skippedInternalDueToCaptions:!1,skippedInternalDueToVoiceover:!1,skippedForSafety:!1,speechProtectedWindows:c?.speechProtectedWindows??0};let u=c.internalRanges.length>0,p=(e.captionBlocks??[]).some(e=>e.sceneId===t),m=tZ(e,a,l),h=u&&(p||m)?c.removalRanges.filter(e=>e.start<=d.start+tD.pF||e.end>=d.end-tD.pF):c.removalRanges;if(0===h.length)return{applied:!1,splitInsertedScenes:0,usedEdgeTrim:!1,usedInternalSplit:!1,hadRemovableRanges:!0,hadInternalRanges:u,skippedInternalDueToCaptions:u&&p,skippedInternalDueToVoiceover:u&&m,skippedForSafety:!1,speechProtectedWindows:c.speechProtectedWindows};let f=(0,tD.IV)(d.start,d.end,h,r.minKeepSeconds);if(0===f.length)return{applied:!1,splitInsertedScenes:0,usedEdgeTrim:!1,usedInternalSplit:!1,hadRemovableRanges:!0,hadInternalRanges:u,skippedInternalDueToCaptions:!1,skippedInternalDueToVoiceover:!1,skippedForSafety:!0,speechProtectedWindows:c.speechProtectedWindows};if(1===f.length){let r=f[0],n=Math.max(0,r.start-d.start),s=Math.max(0,d.end-r.end),o=t0(e,t,a,l,d,n,s,i);return{applied:o.applied,splitInsertedScenes:0,usedEdgeTrim:o.applied,usedInternalSplit:!1,hadRemovableRanges:!0,hadInternalRanges:u,skippedInternalDueToCaptions:!1,skippedInternalDueToVoiceover:!1,skippedForSafety:!1,speechProtectedWindows:c.speechProtectedWindows}}if(p||m||f.length>r.maxKeepSegments)return{applied:!1,splitInsertedScenes:0,usedEdgeTrim:!1,usedInternalSplit:!1,hadRemovableRanges:!0,hadInternalRanges:u,skippedInternalDueToCaptions:p,skippedInternalDueToVoiceover:m,skippedForSafety:!p&&!m,speechProtectedWindows:c.speechProtectedWindows};let g=a,x=f.map((e,t)=>{let a=Math.max(.1,e.end-e.start),r=g;g+=a;let n=tU({automation:o.automation,effects:o.effects,previousTrimStart:d.start,segmentMediaStart:e.start,segmentMediaEnd:e.end,isFirstSegment:0===t});return{...o,id:0===t?o.id:(0,tC.w0)(o.id,e,t),timelineStart:r,trackId:o.trackId??1,transition:t<f.length-1?void 0:o.transition,automation:n.automation,effects:n.effects,media:{...o.media,trim:{start:e.start,end:e.end}}}});return e.scenes.splice(s,1,...x),t1(x,i),{applied:!0,splitInsertedScenes:Math.max(0,x.length-1),usedEdgeTrim:!1,usedInternalSplit:!0,hadRemovableRanges:!0,hadInternalRanges:u,skippedInternalDueToCaptions:!1,skippedInternalDueToVoiceover:!1,skippedForSafety:!1,speechProtectedWindows:c.speechProtectedWindows}}function t2(e,t,a,r,n,i){let s=e.scenes.findIndex(e=>e.id===t);if(s<0)return{applied:!1,splitInsertedScenes:0,usedEdgeTrim:!1,usedInternalSplit:!1,hadSpeechRanges:!1,skippedInternalDueToCaptions:!1,skippedInternalDueToVoiceover:!1,skippedForSafety:!1};let o=e.scenes[s];if(!o.media)return{applied:!1,splitInsertedScenes:0,usedEdgeTrim:!1,usedInternalSplit:!1,hadSpeechRanges:!1,skippedInternalDueToCaptions:!1,skippedInternalDueToVoiceover:!1,skippedForSafety:!1};let l=(0,tC.bo)(o),d=o.media.trim??{start:0,end:o.media.duration??l},c=(0,tD.qI)(n,d.start,d.end,r);if(0===c.length)return{applied:!1,splitInsertedScenes:0,usedEdgeTrim:!1,usedInternalSplit:!1,hadSpeechRanges:!1,skippedInternalDueToCaptions:!1,skippedInternalDueToVoiceover:!1,skippedForSafety:!1};if(1===c.length){let r=c[0],n=Math.max(0,r.start-d.start),s=Math.max(0,d.end-r.end),o=t0(e,t,a,l,d,n,s,i);return{applied:o.applied,splitInsertedScenes:0,usedEdgeTrim:o.applied,usedInternalSplit:!1,hadSpeechRanges:!0,skippedInternalDueToCaptions:!1,skippedInternalDueToVoiceover:!1,skippedForSafety:!1}}let u=(e.captionBlocks??[]).some(e=>e.sceneId===t),p=tZ(e,a,l);if(u||p||c.length>r.maxKeepSegments)return{applied:!1,splitInsertedScenes:0,usedEdgeTrim:!1,usedInternalSplit:!1,hadSpeechRanges:!0,skippedInternalDueToCaptions:u,skippedInternalDueToVoiceover:p,skippedForSafety:!u&&!p};let m=a,h=c.map((e,t)=>{let a=Math.max(.1,e.end-e.start),r=m;m+=a;let n=tU({automation:o.automation,effects:o.effects,previousTrimStart:d.start,segmentMediaStart:e.start,segmentMediaEnd:e.end,isFirstSegment:0===t});return{...o,id:0===t?o.id:(0,tC.w0)(o.id,e,t,"speech"),timelineStart:r,trackId:o.trackId??1,transition:t<c.length-1?void 0:o.transition,automation:n.automation,effects:n.effects,media:{...o.media,trim:{start:e.start,end:e.end}}}});
73return e.scenes.splice(s,1,...h),t1(h,i),{applied:!0,splitInsertedScenes:Math.max(0,h.length-1),usedEdgeTrim:!1,usedInternalSplit:!0,hadSpeechRanges:!0,skippedInternalDueToCaptions:!1,skippedInternalDueToVoiceover:!1,skippedForSafety:!1}}function t4(e){let{audioBlocks:t,originalSceneId:a,rightSceneId:r,splitAbsoluteTime:n,nextId:i,now:s}=e;return t.some(e=>e.sourceSceneId===a)?{blocks:t.flatMap(e=>{if(e.sourceSceneId!==a)return[e];let t=e.start??0,o=e.inOffset??0,l=e.duration||5,d="number"==typeof e.outOffset?e.outOffset:l,c=n-t;if(c>=Math.max(0,d-o)-.05)return[e];if(c<=.05)return[{...e,sourceSceneId:r,updatedAt:s}];let u=Math.min(o+c,d),p={...e,id:i(),outOffset:u,updatedAt:s},m={...e,id:i(),start:n,inOffset:u,sourceSceneId:r,createdAt:s,updatedAt:s};return console.log("[SPLIT_DIAG] Audio split:",{audioId:e.id,audioStart:t,positionInAudio:c,sourceCut:u,left:{start:p.start,inOffset:p.inOffset,outOffset:p.outOffset},right:{start:m.start,inOffset:m.inOffset,outOffset:m.outOffset}}),[p,m]}),hadLinkedAudio:!0}:{blocks:t,hadLinkedAudio:!1}}let t3=new Set(["trim_clip","move_clip","duplicate_clip","split_clip","remove_segments","delete_clip"]);var t8=a(53498);function t6(e){return(0,eV.S0)("speechify",e).voiceId}async function t9(e){let t=t6(e.preferredVoiceId),a=e.requestId??(0,tP.q7)("ai-runtime"),r=await (0,t8.generateGeminiVoiceover)({projectId:e.project.id,isLocalProject:"local"===e.project.mode,text:e.narrationText,voiceId:t,voiceoverId:e.voiceoverId,timeoutMs:36e4}),n=Date.now(),i=Number.isFinite(r.durationSeconds)&&r.durationSeconds>0?r.durationSeconds:e.requestedDuration;return{voiceover:{id:e.voiceoverId,type:"voiceover",url:r.persistenceUrl,storageKey:r.storageKey,assetRef:r.assetRef,start:e.startSeconds,duration:i,trackId:e.trackId,inOffset:0,outOffset:i,volume:e.volume,text:e.narrationText,settings:{voiceId:t},status:"ready",generatedAt:n,createdAt:n,updatedAt:n},voiceId:t,requestId:a}}async function t7(e){let t=window.__AI_EDITOR_GENERATE_VOICEOVER__;if("function"==typeof t){let a=await t(e);if(!a||"object"!=typeof a||!a.voiceover)throw Error("Voiceover panel generation returned no voiceover.");return a}let a=Date.now()+6e3;for(;Date.now()<a;){let t=window.__AI_EDITOR_GENERATE_VOICEOVER__;if("function"==typeof t){let a=await t(e);if(!a||"object"!=typeof a||!a.voiceover)throw Error("Voiceover panel generation returned no voiceover.");return a}await new Promise(e=>{setTimeout(e,50)})}return null}function ae(e){window.__AI_EDITOR_VOICEOVER_STATUS__=e;let t=()=>window.dispatchEvent(new CustomEvent("ai-editor:voiceover-status",{detail:e}));"function"==typeof window.requestAnimationFrame?window.requestAnimationFrame(t):t()}a(28086),a(41463);let at={userZoom:1,panX:0,panY:0,rotation:0},aa={userZoom:{min:tM.D,max:tM.h},panX:{min:-1,max:1},panY:{min:-1,max:1},rotation:{min:-180,max:180}},ar={subtle:.6,normal:1,strong:1.5};function an(e){return{propertyId:"userZoom",points:e,interpolation:"smooth"}}function ai(e,t){let a=[{at:0,value:0}],r=e;for(let e=1;e<=t;e+=1)a.push({at:e/(t+1),value:e%2==1?r:-r}),r*=.75;return a.push({at:1,value:0}),a}let as={ken_burns:{id:"ken_burns",label:"Ken Burns",defaultDuration:"full_scene",variants:[[an([{at:0,value:1},{at:1,value:1.12}]),{propertyId:"panX",interpolation:"smooth",points:[{at:0,value:0},{at:1,value:.06}]},{propertyId:"panY",interpolation:"smooth",points:[{at:0,value:0},{at:1,value:.04}]}],[an([{at:0,value:1.12},{at:1,value:1}]),{propertyId:"panX",interpolation:"smooth",points:[{at:0,value:.06},{at:1,value:0}]},{propertyId:"panY",interpolation:"smooth",points:[{at:0,value:-.04},{at:1,value:0}]}]]},punch_in:{id:"punch_in",label:"Punch In",defaultDuration:.2,variants:[[an([{at:0,value:1},{at:1,value:1.18}])]]},pop_in:{id:"pop_in",label:"Pop In",defaultDuration:.5,variants:[[an([{at:0,value:.6},{at:.7,value:1.06},{at:1,value:1}])]]},slide_in_left:{id:"slide_in_left",label:"Slide In From Left",defaultDuration:.5,variants:[[{propertyId:"panX",interpolation:"smooth",points:[{at:0,value:-.6},{at:1,value:0}]}]]},slide_in_right:{id:"slide_in_right",label:"Slide In From Right",defaultDuration:.5,variants:[[{propertyId:"panX",interpolation:"smooth",points:[{at:0,value:.6},{at:1,value:0}]}]]}
73,shake:{id:"shake",label:"Shake",defaultDuration:.6,variants:[[{propertyId:"panX",interpolation:"linear",points:ai(.035,8)},{propertyId:"panY",interpolation:"linear",points:ai(.018,8).map(e=>({...e,value:-e.value}))}]]},zoom_in:{id:"zoom_in",label:"Zoom In",defaultDuration:"full_scene",variants:[[an([{at:0,value:1},{at:1,value:1.15}])]]},zoom_out:{id:"zoom_out",label:"Zoom Out",defaultDuration:"full_scene",variants:[[an([{at:0,value:1.15},{at:1,value:1}])]]},pan_left:{id:"pan_left",label:"Pan Left",defaultDuration:"full_scene",variants:[[{propertyId:"panX",interpolation:"smooth",points:[{at:0,value:0},{at:1,value:-.35}]}]]},pan_right:{id:"pan_right",label:"Pan Right",defaultDuration:"full_scene",variants:[[{propertyId:"panX",interpolation:"smooth",points:[{at:0,value:0},{at:1,value:.35}]}]]},pan_up:{id:"pan_up",label:"Pan Up",defaultDuration:"full_scene",variants:[[{propertyId:"panY",interpolation:"smooth",points:[{at:0,value:0},{at:1,value:.3}]}]]},pan_down:{id:"pan_down",label:"Pan Down",defaultDuration:"full_scene",variants:[[{propertyId:"panY",interpolation:"smooth",points:[{at:0,value:0},{at:1,value:-.3}]}]]},rotate_left:{id:"rotate_left",label:"Rotate Left",defaultDuration:"full_scene",variants:[[{propertyId:"rotation",interpolation:"smooth",points:[{at:0,value:0},{at:1,value:-8}]}]]},rotate_right:{id:"rotate_right",label:"Rotate Right",defaultDuration:"full_scene",variants:[[{propertyId:"rotation",interpolation:"smooth",points:[{at:0,value:0},{at:1,value:8}]}]]}},ao={punchy:{segmentBeats:1,minSegmentSeconds:.35,fallbackSegmentSeconds:.7},balanced:{segmentBeats:2,minSegmentSeconds:.5,fallbackSegmentSeconds:1.4},cinematic:{segmentBeats:4,minSegmentSeconds:.9,fallbackSegmentSeconds:2.8}},al={punchy:null,balanced:{type:"CROSSFADE",duration:.3,enabled:!0},cinematic:{type:"CROSSFADE",duration:.6,enabled:!0}};function ad(e){let t=Number(e);return Number.isFinite(t)?t:null}function ac(e,t){if(!t)return null;let a=e.media?.storageKey,r=e.media?.storedUrl??e.media?.url,n=Object.values(t).filter(e=>e&&"visual_shots_v1"===e.kind);if(0===n.length)return null;let i=e=>0===e.length?null:e.reduce((e,t)=>(t.analyzedAt??0)>(e.analyzedAt??0)?t:e),s=i(n.filter(t=>t.sourceSceneId===e.id));if(s)return s;if(a){let e=i(n.filter(e=>e.storageKey===a));if(e)return e}if(r){let e=i(n.filter(e=>e.mediaUrl===r));if(e)return e}return null}function au(e){return"string"==typeof e&&(e.startsWith("http://")||e.startsWith("https://"))}async function ap(e,t,a){let r,n,i,s,o,l,d,{workingProject:c}=a,u=(n=ao[r="punchy"===e.style||"cinematic"===e.style||"balanced"===e.style?e.style:"balanced"],i=Math.min(120,Math.max(5,ad(e.targetDurationSeconds)??20)),s=Math.min(16,Math.max(1,Math.round(ad(e.segmentBeats)??n.segmentBeats))),o=Math.max(.2,ad(e.minSegmentSeconds)??n.minSegmentSeconds),l=Math.min(80,Math.max(2,Math.round(ad(e.maxSegments)??40))),d="explicit_track"===e.beatSourceMode||"auto_music"===e.beatSourceMode||"scene_audio"===e.beatSourceMode?e.beatSourceMode:"auto_music",{style:r,targetDurationSeconds:i,segmentBeats:s,minSegmentSeconds:o,maxSegments:l,useShotBoundaries:!1!==e.useShotBoundaries,beatSourceMode:d}),p=[],m=a.resolveSceneIds(e),h=["sceneId","sceneIds","sceneNumber","sceneNumbers","blockId"].some(t=>null!=e[t]&&""!==e[t]);if(0===m.length&&(h||e.scope&&"all"!==e.scope.type))return{operationIndex:t,kind:"create_montage",success:!1,summary:"The requested montage scenes are no longer available.",error:"Select the scenes to include or explicitly request the whole project. No other scenes were edited."};let f=m.length>0?m:c.scenes.filter(e=>!e.isAudioBlock).map(e=>e.id),g=new Set((c.captionBlocks??[]).map(e=>e.sceneId)),x=[],b=0,y=0,v=0;for(let e of f){let t=c.scenes.find(t=>t.id===e);if(t){if(!t.media||!t.media.url){b+=1;continue}if("video"!==t.media.type){y+=1;continue}if(g.has(e)){v+=1;continue}x.push(t)}}if(b>0&&p.push(`Skipped ${b} scene(s) without media.`),y>0&&p.push(`Skipped ${y} non-video scene(s); montage v1 cuts video scenes only.`),v>0&&p.push(`Skipped ${v} caption-bearing scene(s) because ripple-safe caption re-timing is not enabled for montage; remove captions or target caption-free scenes to include them.`),0===x.length)return{operationIndex:t,kind:"create_montage",success:!1,summary:"No usable video scenes were available for the montage.",error:"Montage needs at least one caption-free video scene with media.",warning:p.length>0?p.join(" "):void 0};let w=c.aiAnalysis?.audioArtifacts,k=null,S="style cadence",j=async e=>{let t=(0,tD.sV)(e,w,{preferServerDownbeat:!0});if(t)return t;try{let t=await (0,tD.WA)(c,e,w);if(t.artifact){var a;return a=t.artifact,c.aiAnalysis={...c.aiAnalysis??{},audioArtifacts:{...c.aiAnalysis?.audioArtifacts??{},[a.sourceFingerprint]:a}},w=c.aiAnalysis.audioArtifacts,t.artifact}}catch{}return null};if("string"==typeof e.audioBlockId&&e.audioBlockId.trim())(k=await j(e.audioBlockId))?S=`audio block ${e.audioBlockId}`:p.push(`Requested beat source ${e.audioBlockId} had no usable rhythm analysis; used ${u.style} cadence instead.`);else if("auto_music"===u.beatSourceMode){let e=(0,tD.wV)(c,w);
73e?(k=await j(e))?S=`auto-selected music (${e})`:p.push("Auto-selected music could not be analyzed; montage used style cadence instead of beats."):p.push("No music source was detected; montage used style cadence instead of beats.")}let I=ao[u.style].fallbackSegmentSeconds,N=I;k&&(N=function(e,t,a){let r=e.filter(e=>Number.isFinite(e)).sort((e,t)=>e-t);if(r.length<2)return a;let n=[];for(let e=1;e<r.length;e+=1){let t=r[e]-r[e-1];t>.001&&n.push(t)}return 0===n.length?a:(n.sort((e,t)=>e-t),Math.min(8,Math.max(.3,n[Math.floor(n.length/2)]*Math.max(1,t))))}((0,tD.y9)(k,{minSegmentSeconds:u.minSegmentSeconds,maxCuts:u.maxSegments,subdivision:"beat",distribution:"dense",anchor:"cinematic"===u.style?"bar":"beat",beatStartSeconds:0,beatSourceMode:u.beatSourceMode}).markerTimes,u.segmentBeats,I));let C={...c.aiAnalysis?.visualArtifacts??{}},M=0,_=0,A=0;if(u.useShotBoundaries&&a.requestShotAnalysis){for(let e of x){if(_>=4)break;if(ac(e,C))continue;let t=e.media?.storedUrl??e.media?.url,r=e.media?.storageKey;if(!r&&!au(t)){A+=1;continue}_+=1;try{let n=await a.requestShotAnalysis(c.id,{sceneId:e.id,mediaUrl:au(t)?t:void 0,storageKey:r});n&&(C[n.sourceFingerprint]=n)}catch{}}Object.keys(C).length>0&&(c.aiAnalysis={...c.aiAnalysis??{},visualArtifacts:C})}let E=function(e,t){let a=Math.max(1,Math.ceil(Math.min(t.maxSegments,Math.max(2,Math.ceil(t.targetDurationSeconds/Math.max(.1,t.segmentSeconds))))/Math.max(1,e.length))),r=e.map(e=>(function(e,t){if(e.length<=t)return e;if(t<=1)return[e[0]];let a=e.length-1,r=new Set;for(let e=0;e<t;e+=1)r.add(Math.round(e*a/(t-1)));return[...r].sort((e,t)=>e-t).map(t=>e[t])})(function(e,t,a){let r=e.trimEnd-e.trimStart;if(r<a)return[];let n=(e.shotBoundaries??[]).filter(t=>Number.isFinite(t)&&t>=e.trimStart-.001&&t<e.trimEnd-a).sort((e,t)=>e-t),i=[];if(n.length>0){for(let r of(0,tC.Am)([e.trimStart,...n])){let n=Math.min(r+t,e.trimEnd);n-r>=a&&i.push({start:r,end:n,fromShotBoundary:r!==e.trimStart})}return i}let s=Math.max(1,Math.floor(r/t)),o=r/s;for(let r=0;r<s;r+=1){let n=e.trimStart+r*o,s=Math.min(n+t,e.trimEnd);s-n>=a&&i.push({start:n,end:s,fromShotBoundary:!1})}return i}(e,t.segmentSeconds,t.minSegmentSeconds),a)),n=e.map(()=>0),i=[],s=0,o=!1;for(;!o&&s<t.targetDurationSeconds&&i.length<t.maxSegments;){o=!0;for(let a=0;a<e.length&&!(s>=t.targetDurationSeconds)&&!(i.length>=t.maxSegments);a+=1){let t=r[a],l=n[a];if(l>=t.length)continue;n[a]=l+1,o=!1;let d=t[l];i.push({sceneId:e[a].sceneId,start:d.start,end:d.end,fromShotBoundary:d.fromShotBoundary}),s+=d.end-d.start}}return i}(x.map(e=>{let t=e.media?.duration??(0,tC.bo)(e),a=e.media?.trim??{start:0,end:t},r=u.useShotBoundaries?ac(e,C):null;return r&&r.boundaries.length>0&&(M+=1),{sceneId:e.id,trimStart:a.start,trimEnd:a.end,shotBoundaries:r?.boundaries}}),{segmentSeconds:N,minSegmentSeconds:u.minSegmentSeconds,targetDurationSeconds:u.targetDurationSeconds,maxSegments:u.maxSegments});if(E.length<2)return{operationIndex:t,kind:"create_montage",success:!1,summary:"Not enough usable footage to build a montage.",error:"Montage segment selection produced fewer than two segments with the current duration and safety limits.",warning:p.length>0?p.join(" "):void 0};let T=new Set(x.map(e=>e.id)),$=new Map(x.map(e=>[e.id,e])),P=c.scenes.findIndex(e=>T.has(e.id)),D=Math.min(...x.map(e=>a.sceneStartMap.get(e.id)??e.timelineStart??0)),R=Math.max(...x.map(e=>(a.sceneStartMap.get(e.id)??e.timelineStart??0)+(0,tC.bo)(e))),z=$.get(E[0].sceneId)?.trackId??1,L=(0,tC.yw)(),F=c.scenes.filter(e=>{if(e.isAudioBlock||T.has(e.id)||(e.trackId??1)!==z)return!1;let t=a.sceneStartMap.get(e.id)??e.timelineStart??0;return t+(0,tC.Ip)(e,L)>D+.001&&t<R-.001});if(F.length>0)return{operationIndex:t,kind:"create_montage",success:!1,summary:"The montage targets are not contiguous on their track.",error:`${F.length} other scene(s) sit between the montage targets on track ${z}. Include them in the montage scope, or move them off the target range first, so the montage does not overlap them.`,warning:p.length>0?p.join(" "):void 0};let O=al[u.style],B=new Set,W=D,U=E.map((e,t)=>{let a=$.get(e.sceneId),r=!B.has(e.sceneId);B.add(e.sceneId);let n=Math.max(.1,e.end-e.start),i=W;W+=n;let s=t===E.length-1,o=a.media?.trim?.start??0,l=tU({automation:a.automation,effects:a.effects,previousTrimStart:o,segmentMediaStart:e.start,segmentMediaEnd:e.end,isFirstSegment:r});return{...a,id:r?a.id:(0,tC.w0)(a.id,{start:e.start,end:e.end},t,"montage"),timelineStart:i,trackId:a.trackId??z,transition:!s&&O?{...O}:void 0,automation:l.automation,effects:l.effects,media:{...a.media,trim:{start:e.start,end:e.end}}}}),K=W-D,V=K-(R-D),H=c.scenes.filter(e=>!T.has(e.id)),q=Math.max(0,Math.min(P,H.length));for(let e of(H.splice(q,0,...U),c.scenes=H,T))U.some(t=>t.id===e)||a.sceneStartMap.delete(e);for(let e of U)a.sceneStartMap.set(e.id,e.timelineStart??D);let Y=new Set;if(Math.abs(V)>.001){for(let e of c.scenes){if(e.isAudioBlock||U.some(t=>t.id===e.id)||(e.trackId??1)!==z)continue;let t=a.sceneStartMap.get(e.id)??e.timelineStart??0;t>=R-.001&&(e.timelineStart=Math.max(0,t+V),a.sceneStartMap.set(e.id,e.timelineStart),Y.add(e.id))}if(Y.size>0&&Array.isArray(c.captionBlocks))for(let e of(c.captionBlocks=c.captionBlocks.map(e=>Y.has(e.sceneId)?{...e,start:Math.max(0,e.start+V)}:e),Y))a.captionSyncSceneIds?.add(e)}let G=k?`beat-synced to ${S} (~${N.toFixed(2)}
73s per cut)`:`${u.style} cadence (~${N.toFixed(2)}s per cut)`,X=M>0?` Shot boundaries guided cut points for ${M} scene(s).`:" Segments were sampled across the footage as jump cuts.",J=O?` Added ${O.type.toLowerCase()} transitions (${O.duration.toFixed(1)}s) between segments.`:" Hard cuts between segments (punchy style).";return A>0&&p.push(`${A} scene(s) use local-only media the server cannot fetch, so shot detection was skipped for them; upload the media (or import from a URL) to enable visual cut-point analysis.`),0===M&&u.useShotBoundaries&&p.push("No shot-boundary analysis was available; cut points were sampled evenly across each scene."),k||p.push("Cuts follow the style cadence; add a music track and re-run the montage for beat-synced cutting."),p.push("Scene audio was left unchanged; ask to mute scenes or adjust volume if the montage should be music-only."),{operationIndex:t,kind:"create_montage",success:!0,summary:`Built a ${K.toFixed(1)}s ${u.style} montage from ${B.size} scene(s) using ${E.length} segments, ${G}.${X}${J}`+(Y.size>0?` Shifted ${Y.size} downstream scene(s) by ${V.toFixed(2)}s.`:""),warning:p.length>0?p.join(" "):void 0}}function am(e){return{success:!1,error:e,removedSeconds:0,segmentCount:0,keptSceneIds:[],audioTimelineUpdates:[],captionSyncSceneIds:[]}}function ah(e){let{audioBlocks:t,timelineCuts:a,sceneWindow:r,removedSeconds:n}=e,i=e=>{let t=0;for(let r of a)t+=Math.max(0,Math.min(r.end,e)-r.start);return Math.max(0,e-t)},s=[],o=0,l=[];for(let e of t){if((e.type??"voiceover")!=="voiceover"){s.push(e);continue}let t=e.inOffset??0,d=Math.max(0,(e.outOffset??e.duration??0)-t),c=e.start,u=c+d;if(c>=r.end-.001){if(n>.001){let t=Math.max(0,c-n);s.push({...e,start:t,updatedAt:Date.now()}),l.push({id:e.id,start:t})}else s.push(e);continue}if(u<=r.start+.001){s.push(e);continue}let p=[],m=c;for(let e of a){let t=Math.max(e.start,c),a=Math.min(e.end,u);a<=t||(t-m>=.05&&p.push({start:m,end:t}),m=Math.max(m,a))}if(u-m>=.05&&p.push({start:m,end:u}),1===p.length&&p[0].start===c&&p[0].end===u){let t=i(c);Math.abs(t-c)>.001?(s.push({...e,start:t,updatedAt:Date.now()}),l.push({id:e.id,start:t})):s.push(e);continue}if(0===p.length){o+=1;continue}o+=1,p.forEach((a,r)=>{s.push({...e,id:`${e.id}-cut-${r+1}`,start:i(a.start),inOffset:t+(a.start-c),outOffset:t+(a.end-c),audioFadeInDuration:0===r?e.audioFadeInDuration:0,audioFadeOutDuration:r===p.length-1?e.audioFadeOutDuration:0,updatedAt:Date.now()})})}return{blocks:s,slicedCount:o,repositionedExistingIds:l}}var af=a(97152);let ag=new Set(["analyze_beats","create_action_edit"]);function ax(e){let{workingProject:t,sceneStartMap:a,sceneTrackMap:r,resolved:n,splitTime:i}=e;if(!n.scene.media)return{error:"Split requires media on the target scene."};let s=(0,tC.TJ)(n.scene,n.sceneDuration),o=(0,tO.Y2)({sceneStart:n.sceneStart,sceneDuration:n.sceneDuration,prevTrim:s,mediaDuration:n.scene.media.duration??null,splitAtAbsolute:i});if(!o.applied)return{error:`Split time ${i.toFixed(2)}s is outside clip bounds.`};let l=(0,tC.w0)(n.scene.id,{start:o.splitMediaTime,end:o.right.trim.end},1,"clip"),d=tU({automation:n.scene.automation,effects:n.scene.effects,previousTrimStart:s.start,segmentMediaStart:o.left.trim.start,segmentMediaEnd:o.left.trim.end,isFirstSegment:!0}),c=tU({automation:n.scene.automation,effects:n.scene.effects,previousTrimStart:s.start,segmentMediaStart:o.right.trim.start,segmentMediaEnd:o.right.trim.end,isFirstSegment:!1}),u={...n.scene,id:n.scene.id,timelineStart:o.left.timelineStart,transition:void 0,automation:d.automation,effects:d.effects,media:{...n.scene.media,trim:{...o.left.trim}}},p={...n.scene,id:l,timelineStart:o.right.timelineStart,transition:n.scene.transition,automation:c.automation,effects:c.effects,media:{...n.scene.media,trim:{...o.right.trim}}};t.scenes.splice(n.sceneIndex,1,u,p),a.set(u.id,u.timelineStart??o.left.timelineStart),a.set(p.id,p.timelineStart??o.right.timelineStart),r.set(u.id,Number(u.trackId??1)),r.set(p.id,Number(p.trackId??1));let m=Math.round(1e3*i),h=0,f=tG(t.captionBlocks??[],n.sceneId,l,i,()=>`${n.sceneId}-caption-split-${m}-${h+=1}`);f.changed&&(t.captionBlocks=f.captions,e.captionSyncSceneIds?.add(n.sceneId),e.captionSyncSceneIds?.add(l));let g=t4({audioBlocks:Array.isArray(t.audio)?t.audio:Array.isArray(t.voiceovers)?t.voiceovers:[],originalSceneId:n.sceneId,rightSceneId:l,splitAbsoluteTime:i,nextId:v.generateId,now:Date.now()});return g.hadLinkedAudio&&(t.audio=g.blocks,t.voiceovers=g.blocks),t.scenes=t.scenes.map((e,t)=>({...e,sequenceIndex:t})),{firstScene:u,secondScene:p}}async function ab(e){var t,a,r;let n,i,s,o,l=e.plan,c=(0,tC.BL)(e.currentProject),u=(0,tC.BL)(e.currentProject),p=[],m=(0,tC.TQ)(),h=(0,tC.yw)(),f=(0,tC.mf)(u),g=(0,tC.me)(u),x=(t=[...l.operations],o=e=>(0,tC.ky)(e,u,m),t.map(e=>{let t=null,a=()=>(t||(t={...e}),t),r=e=>{if("string"!=typeof e&&"number"!=typeof e)return null;let t=o(e);return t&&t!==e?t:null};if((e.scope?.type==="scene_ids"||(0,tC.LG)(e.scope))&&Array.isArray(e.scope.sceneIds)){let t=e.scope.sceneIds.map(e=>r(e)??e);("scene_ids"!==e.scope.type||t.some((t,a)=>
73t!==e.scope.sceneIds[a]))&&(a().scope={...e.scope,type:"scene_ids",sceneIds:t})}let n=r(e.sceneId);if(n&&(a().sceneId=n),Array.isArray(e.sceneIds)){let t=e.sceneIds.map(e=>r(e)??e);t.some((t,a)=>t!==e.sceneIds[a])&&(a().sceneIds=t)}if(void 0!==e.sceneNumber){let t=o(e.sceneNumber);if(t){let e=a();"string"==typeof e.sceneId&&e.sceneId||(e.sceneId=t),delete e.sceneNumber}}if(Array.isArray(e.sceneNumbers)){let t=e.sceneNumbers.map(e=>o(e)).filter(e=>!!e);if(t.length===e.sceneNumbers.length&&t.length>0){let e=a(),r=Array.isArray(e.sceneIds)?e.sceneIds:[];e.sceneIds=[...r,...t.filter(e=>!r.includes(e))],delete e.sceneNumbers}}if(t3.has(e.kind)){let t=r(e.blockId);t&&(a().blockId=t)}return t??e})),b=[],k=[],S=new Set,j=[],I={sceneStartMap:m,sceneTrackMap:f,captionSyncSceneIds:S};for(let t=0;t<x.length&&!n;t+=1){let o=x[t];try{if(!d.Wg.AI_EDITOR_ADVANCED_ENABLED&&ag.has(o.kind)){p.push({operationIndex:t,kind:o.kind,success:!1,summary:"Advanced operation is currently disabled.",warning:"Enable advanced AI editor flag to apply this operation."});continue}switch(o.kind){case"trim_clip":{let e=(0,tC.Uj)(o,u,m,h);if(!e){p.push({operationIndex:t,kind:o.kind,success:!1,summary:`Clip ${o.blockId} was not found.`,error:"Cannot trim a missing clip."}),n=`Operation ${o.kind} failed: Clip ${o.blockId} was not found.`;break}if(!e.scene.media){p.push({operationIndex:t,kind:o.kind,success:!1,summary:`Scene ${e.sceneId} has no media to trim.`,error:"Trim requires media on the target scene."}),n=`Operation ${o.kind} failed: Scene ${e.sceneId} has no media.`;break}let a=Number(o.newIn),r=Number(o.newOut);if(!Number.isFinite(a)||!Number.isFinite(r)){p.push({operationIndex:t,kind:o.kind,success:!1,summary:"Trim values were invalid.",error:"newIn/newOut must be valid numbers."}),n=`Operation ${o.kind} failed: invalid trim range.`;break}let i=Math.max(e.scene.media.duration??0,e.scene.media.trim?.end??0),s="image"===e.scene.media.type?(0,tC.TJ)(e.scene,e.sceneDuration):e.scene.media.trim??{start:0,end:i>0?i:Math.max(0,r)},l=(0,tO.AQ)({sceneStart:e.sceneStart,prevTrim:s,mediaDuration:i>0?i:null,requestedTrim:{start:a,end:r},mode:"clamp"});if(!l.applied){p.push({operationIndex:t,kind:o.kind,success:!1,summary:"Trim range would collapse clip duration.",error:"Trim range must keep at least 0.1s."}),n=`Operation ${o.kind} failed: trim range too small.`;break}u.scenes[e.sceneIndex]={...e.scene,media:{...e.scene.media,trim:{start:l.trim.start,end:l.trim.end}}},tQ(u,e.sceneId,l,I),p.push({operationIndex:t,kind:o.kind,success:!0,summary:`Trimmed clip ${e.sceneId} to ${l.trim.start.toFixed(2)}s-${l.trim.end.toFixed(2)}s.`,warning:l.clamped?"Trim range was clamped to available media bounds.":void 0});break}case"move_clip":{let e=(0,tC.Uj)(o,u,m,h);if(!e){p.push({operationIndex:t,kind:o.kind,success:!1,summary:`Clip ${o.blockId} was not found.`,error:"Cannot move a missing clip."}),n=`Operation ${o.kind} failed: Clip ${o.blockId} was not found.`;break}let a=[o.newStart,o.start,o.timelineStart,o.newStartSeconds],r=null;for(let e of a){let t=Number(e);if(Number.isFinite(t)){r=t;break}}let i=e=>{if("number"==typeof e&&Number.isFinite(e))return Math.max(0,Math.trunc(e));if("string"!=typeof e)return null;let t=e.trim().toLowerCase();if(!t)return null;let a=Number(t);if(Number.isFinite(a))return Math.max(0,Math.trunc(a));let r=t.match(/-?\d+/);if(r){let e=Number(r[0]);if(Number.isFinite(e))return Math.max(0,Math.trunc(e))}let n={zero:0,one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10};for(let[e,a]of Object.entries(n))if(t.includes(e))return a;return null},s=e=>{if("string"!=typeof e)return null;let t=e.toLowerCase().match(/\btrack(?:\s+id)?\s*(?:to|on|onto|=|is)?\s*([a-z0-9_-]+)\b/);return t?i(t[1]):null},d=o.scope&&"object"==typeof o.scope?o.scope:null,c=[o.newTrackId,o.trackId,o.targetTrackId,o.newTrack,o.track,d?.trackId,d?.targetTrackId,d?.track],x=null;for(let e of c){let t=i(e);if(null!==t){x=t;break}}if(null===x&&(x=s(`${l.assistantMessage??""} ${l.summary??""}`)),null===r&&null===x){p.push({operationIndex:t,kind:o.kind,success:!1,summary:"Move operation was missing both start and track targets.",error:"Provide newStart, or a valid track target."}),n=`Operation ${o.kind} failed: missing move target.`;break}let b=null===r?e.sceneStart:Math.max(0,r),y=e.sceneStart,v=b-y,w=x??e.scene.trackId;
73u.scenes[e.sceneIndex]={...e.scene,timelineStart:b,trackId:w},m.set(e.sceneId,b),"number"==typeof w&&f.set(e.sceneId,w);let k=null!==r&&Math.abs(v)>tD.pF,j=w!==e.scene.trackId;if(k||j){let t=j?(0,tC.bG)(e.sceneId,f):null;u.captionBlocks=(u.captionBlocks??[]).map(a=>a.sceneId!==e.sceneId?a:{...a,...k?{start:Math.max(0,a.start+v)}:{},...null!==t?{trackId:t}:{}}),j&&g.set(e.sceneId,t),S.add(e.sceneId)}let I=k&&j?`Moved clip ${e.sceneId} to ${b.toFixed(2)}s on track ${w}.`:j?`Moved clip ${e.sceneId} to track ${w}.`:`Moved clip ${e.sceneId} to ${b.toFixed(2)}s.`;p.push({operationIndex:t,kind:o.kind,success:!0,summary:I,sceneId:e.sceneId,beforeTimelineStart:y,afterTimelineStart:b,beforeTrackId:Number(e.scene.trackId??1),afterTrackId:Number(w??e.scene.trackId??1),warning:null!==r&&b!==r?"Start time was clamped to timeline minimum (0s).":void 0});break}case"duplicate_clip":{let a=function(e){let{operation:t,operationIndex:a,workingProject:r,selectedSceneIds:n,sceneStartMap:i,sceneTrackMap:s,sceneBlockDurationMap:o,captionSyncSceneIds:l}=e,d=["scope","sceneId","sceneIds","sceneNumber","sceneNumbers"].some(e=>null!=t[e]),c=!d&&t.blockId?(0,tC.Zx)(t,r):null,u=!d&&t.blockId?c?[c]:[]:(0,tC.K1)(t,r,n);if(0===u.length)return{operationIndex:a,kind:t.kind,success:!1,summary:"Duplicate operation did not resolve any target scenes.",error:"Specify a scene or selected scene scope to duplicate."};let p=null;for(let e of[t.newStart,t.start,t.timelineStart]){if(null==e||""===String(e).trim())continue;let t=Number(e);if(Number.isFinite(t)){p=Math.max(0,t);break}}let m=Number(t.newTrackId),h=null!=t.newTrackId&&""!==String(t.newTrackId).trim()&&Number.isFinite(m),f=Date.now(),g=[...r.captionBlocks??[]],x=[],b=0;for(let e of u){let t=r.scenes.find(t=>t.id===e);if(!t)continue;let a=i.get(t.id)??t.timelineStart??0,n=Number(s.get(t.id)??t.trackId??1),d=h?Math.max(0,Math.trunc(m)):Math.max(0,Math.trunc(n)),c=null!==p?p:r.scenes.reduce((e,t)=>Number(s.get(t.id)??t.trackId??1)!==d?e:Math.max(e,(i.get(t.id)??t.timelineStart??0)+(0,tC.Ip)(t,o)),0),u=(0,tC.BL)({...r,scenes:[t]}).scenes[0],y=(0,tC.Jy)(t.id,b),v=(0,tC.Ip)(t,o);u.id=y,u.timelineStart=c,u.trackId=d,u.media&&0>=(0,tC.bo)(t)&&v>0&&(u.media.trim={start:0,end:v}),r.scenes.push(u),i.set(y,c),s.set(y,d),v>0&&o.set(y,v),x.push(y),b+=1;let w=c-a,k=g.filter(e=>e.sceneId===t.id).map((e,t)=>{let a=e.captionWords??[],r=0===a.length||a.every(t=>t.start>=-.001&&t.end<=e.duration+.001);return{...e,id:`${e.id}-duplicate-${f}-${b}-${t}`,sceneId:y,start:Math.max(0,e.start+w),captionWords:r?e.captionWords:e.captionWords?.map(e=>({...e,start:Math.max(0,e.start+w),end:Math.max(0,e.end+w)}))}});k.length>0&&(r.captionBlocks=[...r.captionBlocks??[],...k],l.add(y))}return 0===b?{operationIndex:a,kind:t.kind,success:!1,summary:"Duplicate operation targets were not found.",error:"Could not find any source scenes to duplicate."}:{operationIndex:a,kind:t.kind,success:!0,summary:1===b?`Duplicated clip ${u[0]} at ${(i.get(x[0])??0).toFixed(2)}s.`:`Duplicated ${b} clips.`}}({operation:o,operationIndex:t,workingProject:u,selectedSceneIds:e.selectedSceneIds,sceneStartMap:m,sceneTrackMap:f,sceneBlockDurationMap:h,captionSyncSceneIds:S});p.push(a),a.success||(n=`Operation ${o.kind} failed: ${a.error}`);break}case"split_clip":{let e,a=(0,tC.Uj)(o,u,m,h);if(!a){p.push({operationIndex:t,kind:o.kind,success:!1,summary:`Clip ${o.blockId} was not found.`,error:"Cannot split a missing clip."}),n=`Operation ${o.kind} failed: Clip ${o.blockId} was not found.`;break}if(!a.scene.media){p.push({operationIndex:t,kind:o.kind,success:!1,summary:`Scene ${a.sceneId} has no media to split.`,error:"Split requires media on the target scene."}),n=`Operation ${o.kind} failed: Scene ${a.sceneId} has no media.`;break}let r=o.parts,i="number"==typeof r&&Number.isFinite(r)?Math.round(r):null;if(null!==i&&i>=2){let e=Math.min(i,24),r=a.sceneDuration/e;if(r<.1){p.push({operationIndex:t,kind:o.kind,success:!1,summary:`Cannot split ${a.sceneDuration.toFixed(2)}s into ${e} parts.`,error:"Each part would be shorter than 0.1s."}),n=`Operation ${o.kind} failed: parts too short.`;break}let s=null;for(let t=e-1;t>=1;t-=1){let e=a.sceneStart+r*t,n=(0,tC.Uj)({blockId:a.sceneId},u,m,h);if(!n){s=`Scene ${a.sceneId} disappeared mid-split.`;break}let i=ax({workingProject:u,sceneStartMap:m,sceneTrackMap:f,captionSyncSceneIds:S,resolved:n,splitTime:e});if("error"in i){s=i.error;break}}if(s){p.push({operationIndex:t,kind:o.kind,success:!1,summary:`Equal-parts split of ${a.sceneId} failed.`,error:s}),n=`Operation ${o.kind} failed: ${s}`;break}p.push({operationIndex:t,kind:o.kind,success:!0,summary:`Split clip ${a.sceneId} into ${e} equal parts (~${r.toFixed(2)}s each).`,warning:i>e?`Part count was capped at ${e}.`:void 0});break}let s=a.sceneStart+a.sceneDuration/2,l=null;for(let t of[o.splitTime,o.time,o.at,o.position]){if(null!==l)break;if("number"==typeof t&&Number.isFinite(t)){l=t;break}if("string"!=typeof t)continue;let r=t.trim().toLowerCase();if(!r)continue;if(/^(mid|middle|midpoint|center|centre|half|halfway)$/.test(r)){l=s,e="Planner sent a semantic split target; runtime used the clip midpoint.";break}let n=r.match(/^(-?\d+(?:\.\d+)?)%$/);if(n){let t=Number(n[1]);if(Number.isFinite(t)){l=a.sceneStart+a.sceneDuration*(t/100),e="Planner sent a percentage split target;
73 runtime resolved it to timeline time.";break}}let i=Number(r);if(Number.isFinite(i)){l=i,e="Planner sent splitTime as a string; runtime coerced it to a number.";break}}null===l&&(l=s,e="Planner omitted numeric splitTime; runtime defaulted to midpoint.");let d=ax({workingProject:u,sceneStartMap:m,sceneTrackMap:f,captionSyncSceneIds:S,resolved:a,splitTime:l});if("error"in d){p.push({operationIndex:t,kind:o.kind,success:!1,summary:`Split time ${l.toFixed(2)}s is outside clip bounds.`,error:"Split must happen strictly inside the clip duration."}),n=`Operation ${o.kind} failed: split time outside clip bounds.`;break}p.push({operationIndex:t,kind:o.kind,success:!0,summary:`Split clip ${a.sceneId} at ${l.toFixed(2)}s into two scenes.`,warning:e});break}case"remove_segments":{let e=(0,tC.Uj)(o,u,m,h);if(!e){p.push({operationIndex:t,kind:o.kind,success:!1,summary:`Clip ${o.blockId} was not found.`,error:"Cannot remove segments from a missing clip."});break}let a=function(e){let{workingProject:t,op:a,resolved:r,sceneStartMap:n,sceneTrackMap:i}=e,{scene:s,sceneId:o,sceneIndex:l,sceneStart:d,sceneDuration:c}=r;if(!s.media)return am("remove_segments requires media on the target scene.");if(!Array.isArray(a.segments)||0===a.segments.length)return am("remove_segments requires at least one segment.");let u=function(e,t){let a=[];for(let r of e){let e=Math.max(0,Math.min(Number(r?.start),t)),n=Math.max(0,Math.min(Number(r?.end),t));Number.isFinite(e)&&Number.isFinite(n)&&(n-e<=.001||a.push({start:e,end:n}))}a.sort((e,t)=>e.start-t.start||e.end-t.end);let r=[];for(let e of a){let t=r[r.length-1];t&&e.start<=t.end+.001?t.end=Math.max(t.end,e.end):r.push({...e})}return r}(a.segments,c);if(0===u.length)return am("No usable segments fell inside the scene bounds.");let p=function(e,t){let a=[],r=0;for(let t of e)t.start-r>=.05&&a.push({start:r,end:t.start}),r=Math.max(r,t.end);return t-r>=.05&&a.push({start:r,end:t}),a}(u,c),m=p.reduce((e,t)=>e+(t.end-t.start),0);if(0===p.length||m<.5)return am(`Removing ${u.length} segment(s) would leave under 0.5s of media.`);let h=Math.max(0,c-m),f=s.media.trim??{start:0,end:s.media.duration??c},g=[],x=0;for(let e of p)g.push(x),x+=e.end-e.start;let b=Number(s.trackId??i.get(o)??1),y=p.map((e,t)=>{let a={start:f.start+e.start,end:f.start+e.end},r=tU({automation:s.automation,effects:s.effects,previousTrimStart:f.start,segmentMediaStart:a.start,segmentMediaEnd:a.end,isFirstSegment:0===t});return{...s,id:0===t?s.id:(0,tC.w0)(s.id,a,t,"cutout"),timelineStart:d+g[t],trackId:s.trackId??b,transition:t<p.length-1?void 0:s.transition,automation:r.automation,effects:r.effects,media:{...s.media,trim:a}}}),v=y.map(e=>e.id);for(let e of(t.scenes.splice(l,1,...y),y))n.set(e.id,e.timelineStart??d),i.set(e.id,Number(e.trackId??b));let w=new Set,k=[],S=!1;for(let e of t.captionBlocks??[]){if(e.sceneId!==o){k.push(e);continue}S=!0,k.push(...function(e){let{caption:t,sceneStart:a,keeps:r,packedOffsets:n,keptSceneIds:i}=e,s=t.start-a,o=s+t.duration,l=(t.captionWords??[]).filter(e=>e.word?.trim()),d=0===l.length||l.every(e=>e.start>=-.001&&e.end<=t.duration+.001),c=l.map(e=>({word:e.word,start:d?s+e.start:e.start-a,end:d?s+e.end:e.end-a})),u=[];for(let e=0;e<r.length;e+=1){let d=r[e],p=Math.max(s,d.start),m=Math.min(o,d.end);if(m-p<.05)continue;let h=c.filter(e=>{let t=(e.start+e.end)/2;return t>=p&&t<m}).map(e=>{let t=Math.max(0,e.start-p),a=Math.min(m-p,Math.max(t,e.end-p));return{word:e.word,start:t,end:a}}).filter(e=>e.end>e.start);if(l.length>0&&0===h.length)continue;let f=m-p,g=a+n[e]+(p-d.start),x=h.length>0?h.map(e=>e.word).join(" ").trim():t.captionText;u.push({...t,id:0===u.length?t.id:`${t.id}-cut-${e}`,sourceCaptionId:0===u.length?t.sourceCaptionId:void 0,sceneId:i[e],start:g,duration:f,inOffset:0,outOffset:f,fullDuration:f,captionWords:l.length>0?h:t.captionWords,captionCues:void 0,captionText:x})}return u}({caption:e,sceneStart:d,keeps:p,packedOffsets:g,keptSceneIds:v}))}if(t.captionBlocks=k,S)for(let e of(w.add(o),v))w.add(e);let j=d+c,I=u.map(e=>({start:d+e.start,end:d+e.end})),N=ah({audioBlocks:t.audio??[],timelineCuts:I,sceneWindow:{start:d,end:j},removedSeconds:h});t.audio=N.blocks,Array.isArray(t.voiceovers)&&t.voiceovers.length>0&&(t.voiceovers=ah({audioBlocks:t.voiceovers,timelineCuts:I,sceneWindow:{start:d,end:j},removedSeconds:h}).blocks);let C=new Set;if(h>.001){for(let e of t.scenes){if(v.includes(e.id)||Number(e.trackId??i.get(e.id)??1)!==b)continue;let t=n.get(e.id)??e.timelineStart;"number"!=typeof t||t<j-.001||(e.timelineStart=Math.max(0,t-h),n.set(e.id,e.timelineStart),C.add(e.id))}if(C.size>0)for(let e of(t.captionBlocks=(t.captionBlocks??[]).map(e=>C.has(e.sceneId)?{...e,start:Math.max(0,e.start-h)}:e),C))w.add(e)}let M=(a.removedLabels??[]).filter(e=>"string"==typeof e&&e),_=M.length>0?` (${M.slice(0,6).join(", ")})`:"",A="filler_words"===a.reason?"filler words":"pauses"===a.reason?"pauses":"segments",E=C.size>0?` ${C.size} later scene(s) shifted left to close the gap.`:"",T=N.slicedCount>0?` ${N.slicedCount} voiceover track(s) were cut in step with the scene.`:"";return{success:!0,removedSeconds:h,segmentCount:u.length,keptSceneIds:v,audioTimelineUpdates:N.repositionedExistingIds,captionSyncSceneIds:Array.from(w),summary:`Removed ${h.toFixed(2)}s of ${A}${_} from scene ${o} across ${u.length} cut(s), leaving ${p.length} segment(s).`+T+E,warning:p.length>8?`The scene was split into ${p.length} segments; consider previewing before further edits.`:void 0}}({workingProject:u,op:o,resolved:e,sceneStartMap:m,sceneTrackMap:f});if(a.success)for(let e of(b.push(...a.audioTimelineUpdates),a.captionSyncSceneIds))S.add(e);if(!a.success){p.push({operationIndex:t,kind:o.kind,success:!1,summary:`Could not remove segments from scene ${e.sceneId}.`,error:a.error});break}p.push({operationIndex:t,kind:o.kind,success:!0,summary:a.summary??`Removed segments from scene ${e.sceneId}.`,warning:a.warning,sceneId:e.sceneId});break}case"delete_clip":{let e=(0,tC.Uj)(o,u,m,h);if(!e){p.push({operationIndex:t,kind:o.kind,success:!1,summary:`Clip ${o.blockId} was not found.`,error:"Cannot delete a missing clip."}),n=`Operation ${o.kind} failed: Clip ${o.blockId} was not found.`;break}u.scenes.splice(e.sceneIndex,1),m.delete(e.sceneId),f.delete(e.sceneId),u.captionBlocks=(u.captionBlocks??[]).filter(t=>t.sceneId!==e.sceneId),S.add(e.sceneId);let a=new Set([e.sceneId]),r=e=>Array.isArray(e)&&0!==e.length?e.filter(e=>
73!a.has(e?.sourceSceneId)&&!a.has(e?.sceneId)&&!a.has(e?.id)):e;u.audio=r(u.audio)??u.audio,u.voiceovers=r(u.voiceovers)??u.voiceovers,j.push(e.sceneId),Array.isArray(u.aiAnalysis?.silenceRanges)&&(u.aiAnalysis={...u.aiAnalysis??{},silenceRanges:u.aiAnalysis.silenceRanges.filter(t=>t.sceneId!==e.sceneId)}),p.push({operationIndex:t,kind:o.kind,success:!0,summary:`Deleted clip ${e.sceneId}.`,warning:'Later scenes keep their positions, so the deleted clip leaves a gap. Ask to "snap the scenes together" to close it.'});break}case"add_audio_item":{let e="string"==typeof o.url?o.url.trim():"",a=Number(o.start),r=Number.isFinite(a)?Math.max(0,a):0,i=function(e,t){for(let a of[e.text,e.script,e.label,t.assistantMessage,t.summary])if("string"==typeof a&&a.trim().length>0)return a.trim();return""}(o,l),s=!e&&i.length>0&&(void 0===o.voiceProvider||"speechify"===o.voiceProvider||"kokoro"===o.voiceProvider||"gemini"===o.voiceProvider),d=function(e,t){let a=Number(e);return Number.isFinite(a)&&a>0?a:Math.max(1,Math.ceil(Math.max(12,t.trim().length)/15))}(o.duration,i),c="number"==typeof o.trackId&&Number.isFinite(o.trackId)?Math.max(0,Math.trunc(o.trackId)):s?2:3,m="number"==typeof o.volume&&Number.isFinite(o.volume)?Math.min(2,Math.max(0,o.volume)):1,h=null,f=null;if(s){try{w.O.getState().setActiveSidePanel("voiceover")}catch{}let e="string"==typeof o.voiceId&&o.voiceId.trim().length>0?o.voiceId.trim():void 0,a=t6(e),s=(0,tP.q7)("ai-runtime");f=s,ae({phase:"start",text:i,voiceId:a});try{let e=await t7({requestId:s,source:"ai-editor",text:i,voiceId:a,provider:"speechify",startSeconds:r,trackId:c,volume:m,skipProjectPersist:!0});if(e)h=e.voiceover,f=e.requestId,(0,tP.Fz)("ai_voiceover_panel_used",{requestId:e.requestId,traceSource:"ai-runtime",projectId:u.id,projectMode:"local"===u.mode?"local":"cloud",voiceoverId:h.id,finalUrl:h.url??null,storageKey:h.storageKey??null,assetRef:h.assetRef??null}),ae({phase:"success",text:i,voiceId:e.voiceId});else{(0,tP.Fz)("ai_voiceover_panel_unavailable",{requestId:s,traceSource:"ai-runtime",projectId:u.id,projectMode:"local"===u.mode?"local":"cloud",textLength:i.length,voiceId:a});let e=`audio-${(0,v.generateId)()}`,t=await t9({project:u,narrationText:i,requestedDuration:d,preferredVoiceId:a,voiceoverId:e,startSeconds:r,trackId:c,volume:m,requestId:s});h=t.voiceover,f=t.requestId,(0,tP.Fz)("ai_voiceover_panel_fallback",{requestId:t.requestId,traceSource:"ai-runtime",projectId:u.id,projectMode:"local"===u.mode?"local":"cloud",voiceoverId:h.id}),ae({phase:"success",text:i,voiceId:t.voiceId})}}catch(a){let e=a instanceof Error?[a.message,a.stack].filter(Boolean).join(" | "):"Unable to generate voiceover.";(0,tP.Fz)("ai_voiceover_error",{requestId:f,traceSource:"ai-runtime",projectId:u.id,projectMode:"local"===u.mode?"local":"cloud",textLength:i.length,error:e}),ae({phase:"error",text:i,error:e}),p.push({operationIndex:t,kind:o.kind,success:!1,summary:"Voiceover generation failed.",error:e}),n=`Operation ${o.kind} failed: voiceover generation failed.`;break}}if(!h&&(!e||!Number.isFinite(d)||d<=0)){p.push({operationIndex:t,kind:o.kind,success:!1,summary:"Audio item payload was invalid.",error:"Expected a playable url (or synth-ready narration text) and positive duration."}),n=`Operation ${o.kind} failed: invalid audio payload.`;break}let g=d,x=!1;if(!h&&e&&!("number"==typeof o.duration&&Number.isFinite(o.duration)&&o.duration>0)){let t=await function(e,t=4e3){return"function"!=typeof Audio?Promise.resolve(null):new Promise(a=>{let r=!1,n=new Audio,i=e=>{if(!r){r=!0,clearTimeout(s),n.removeAttribute("src");try{n.load()}catch{}a(e)}},s=setTimeout(()=>i(null),t);n.preload="metadata",n.onloadedmetadata=()=>{let e=n.duration;i(Number.isFinite(e)&&e>0?e:null)},n.onerror=()=>i(null);try{n.src=e}catch{i(null)}})}(e);null!==t?g=t:x=!0}if(!h){let t=Date.now();h={id:`audio-${(0,v.generateId)()}`,type:"audio",url:e,start:r,duration:g,trackId:c,inOffset:0,outOffset:g,volume:m,text:i||("string"==typeof o.label&&o.label.trim().length>0?o.label.trim():"AI Audio"),status:"ready",createdAt:t,updatedAt:t}}(0,tC.im)(u,h),(0,tP.Fz)("ai_audio_block_inserted",{requestId:f,traceSource:"ai-runtime",projectId:u.id,projectMode:"local"===u.mode?"local":"cloud",audio
73BlockId:h.id,type:h.type,finalUrl:h.url??null,storageKey:h.storageKey??null,durationSeconds:h.duration??null,startSeconds:h.start,trackId:h.trackId}),p.push({operationIndex:t,kind:o.kind,success:!0,summary:"voiceover"===h.type?`Generated voiceover ${h.id} at ${h.start.toFixed(2)}s.`:`Added audio item ${h.id} at ${h.start.toFixed(2)}s.`,warning:x?`Audio duration metadata could not be read; used an estimated ${g.toFixed(1)}s block length.`:void 0});break}case"update_audio_timing":{let e="string"==typeof o.blockId?o.blockId.trim():"",a=Number(o.start);if(!e||!Number.isFinite(a)){p.push({operationIndex:t,kind:o.kind,success:!1,summary:"Audio timing payload was invalid.",error:"Expected blockId and numeric start."}),n=`Operation ${o.kind} failed: invalid audio timing payload.`;break}let r=(0,tD.CR)(u).find(t=>t?.id===e);if(!r){p.push({operationIndex:t,kind:o.kind,success:!1,summary:`Audio item ${e} was not found.`,error:"Cannot update timing for missing audio item."}),n=`Operation ${o.kind} failed: Audio item ${e} not found.`;break}let i="number"==typeof o.duration&&Number.isFinite(o.duration)&&o.duration>0?o.duration:void 0,s=r.inOffset??0,l=void 0!==i?s+i:r.outOffset,d=Math.max(0,a),c={start:d,...void 0!==i?{outOffset:l}:{},updatedAt:Date.now()},m=t=>Array.isArray(t)&&0!==t.length?t.map(t=>t.id===e?{...t,...c}:t):t;u.audio=m(u.audio)??u.audio,u.voiceovers=m(u.voiceovers)??u.voiceovers,b.push({id:e,start:d,...void 0!==i?{duration:i,outOffset:l}:{}}),p.push({operationIndex:t,kind:o.kind,success:!0,summary:`Updated audio timing for ${e} (start ${Math.max(0,a).toFixed(2)}s${void 0!==i?`, duration ${i.toFixed(2)}s`:""}).`});break}case"set_volume":{let a="number"==typeof o.volume&&Number.isFinite(o.volume)?Math.min(2,Math.max(0,o.volume)):"number"==typeof o.volumePercent&&Number.isFinite(o.volumePercent)?Math.min(2,Math.max(0,o.volumePercent/100)):null,r="number"==typeof o.delta&&Number.isFinite(o.delta)?o.delta:null,i="set"===o.mode||"delta"===o.mode?o.mode:null!==r?"delta":"set";if("set"===i&&null===a||"delta"===i&&null===r){p.push({operationIndex:t,kind:o.kind,success:!1,summary:"Volume payload was invalid.",error:"Expected set_volume to include either volume/volumePercent or delta."}),n=`Operation ${o.kind} failed: invalid volume payload.`;break}let s=(0,tC.K1)(o,u,e.selectedSceneIds),l=(0,tD.V5)(o.scope,u,e.selectedSceneIds,s),d=new Set(s),c=new Set(l),m=new Map,h=new Map,f=0;u.scenes=u.scenes.map(e=>{if(!d.has(e.id))return e;let t="number"==typeof e.volume&&Number.isFinite(e.volume)?e.volume:1,n="delta"===i?Math.min(2,Math.max(0,t+(r??0))):a;f+=1;let s=n<=0||"set"!==i&&(!e.muted||!(n>0))&&e.muted;return m.set(e.id,{volume:n,muted:!!s}),{...e,volume:n,muted:s}});let g=0,x=e=>Array.isArray(e)&&0!==e.length?e.map(e=>{let t="string"==typeof e?.id?e.id:null;if(!t||!c.has(t))return e;let n="number"==typeof e.volume&&Number.isFinite(e.volume)?e.volume:1,s="delta"===i?Math.min(2,Math.max(0,n+(r??0))):a;return g+=1,h.set(t,s),{...e,volume:s,updatedAt:Date.now()}}):e;u.audio=x(u.audio)??u.audio,u.voiceovers=x(u.voiceovers)??u.voiceovers;let b=f+g;if(b<=0){p.push({operationIndex:t,kind:o.kind,success:!1,summary:"No scenes or audio blocks matched the requested volume scope.",error:"Try selecting scenes or targeting a track that contains media."}),n=`Operation ${o.kind} failed: no target blocks for scope.`;break}k.push({sceneVolumes:m,audioVolumes:h});let y="delta"===i?`Adjusted volume by ${Math.round(100*r)}% across ${b} item(s).`:`Set volume to ${Math.round(100*a)}% across ${b} item(s).`;p.push({operationIndex:t,kind:o.kind,success:!0,summary:y});break}case"analyze_beats":{let e=u.aiAnalysis?.audioArtifacts,a="string"==typeof o.audioBlockId&&o.audioBlockId.trim().length>0?o.audioBlockId.trim():null;if(a||(a=(0,tD.wV)(u,e)??u.audio?.find(e=>"error"!==e.status)?.id??null),!a){p.push({operationIndex:t,kind:o.kind,success:!1,summary:"No audio source was available for beat analysis.",error:"Add or select an audio block before running analyze_beats."});break}let r=await (0,tD.WA)(u,a,e),n=r.artifact;if(!n){p.push({operationIndex:t,kind:o.kind,success:!1,summary:`Beat analysis was unavailable for audio block ${a}.`,warning:r.serverFallbackWarning??"Could not compute rhythm markers from the selected audio source."});break}r.artifact&&(u.aiAnalysis={...u.aiAnalysis??{},audioArtifacts:{...u.aiAnalysis?.audioArtifacts??{},[r.artifact.sourceFingerprint]:r.artifact}},e=u.aiAnalysis.audioArtifacts);let i=n.rhythm,s=(Array.isArray(i?.barTimes)&&i.barTimes.length>0?i.barTimes:Array.isArray(i?.downbeatTimes)&&i.downbeatTimes.length>0?i.downbeatTimes:Array.isArray(i?.beatTimes)?i.beatTimes:[]).map(e=>(0,tD.bF)(e)).filter(e=>Number.isFinite(e));u.aiAnalysis={...u.aiAnalysis??{},...e?{audioArtifacts:e}:{},beats:{sourceAudioBlockId:a,markers:s,onsets:Array.isArray(i?.onsetTimes)?i.onsetTimes:void 0,tempo:"number"==typeof i?.tempoBpm?i.tempoBpm:void 0,analyzedAt:Date.now(),version:i?.source??"runtime_beat_analysis"}},p.push({operationIndex:t,kind:o.kind,success:!0,summary:`Analyzed beats for ${a} (${s.length} marker${1===s.length?"":"s"}).`});break}case"create_action_edit":{let e=o.style??"balanced",a="punchy"===e?{distribution:"dense",subdivision:"half_beat",minSegmentSeconds:.2,targetCutCount:12,maxCuts:16}:"cinematic"===e?{distribution:"distributed",subdivision:"beat",minSegmentSeconds:.5,targetCutCount:6,maxCuts:8}:{distribution:"distributed",subdivision:"beat",minSegmentSeconds:.35,targetCutCount:8,maxCuts:10},r={kind:"cut_on_beat",scope:o.scope,distribution:a.distribution,subdivision:a.subdivision,minSegmentSeconds:a.minSegmentSeconds,targetCutCount:a.targetCutCount,maxCuts:a.maxCuts,anchor:"punchy"===e?"beat":"bar",beatSourceMode:"auto_music"};x.splice(t+1,0,r),p.push({operationIndex:t,kind:o.kind,success:!0,summary:`Queued ${e} action-edit pass using beat-synced cut planning.`});break}case"trim_scene":{let e=u.scenes.findIndex(e=>e.id===o.sceneId);if(e<0){p.push({operationIndex:t,kind:o.kind,success:!1,summary:`Scene ${o.sceneId} was not found.`,error:"Cannot trim a missing scene."}),n=`Operation ${o.kind} failed: Scene ${o.sceneId} was not found.`;break}let a=Number(o.trimStartBySeconds??0),r=Number(o.trimEndBySeconds??0);if(!Number.isFinite(a)||!Number.isFinite(r)){p.push({operationIndex:t,kind:o.kind,success:!1,summary:`Trim values for scene ${o.sceneId} were invalid.`,error:"trimStartBySeconds/trimEndBySeconds must be valid numbers."}),n=`Operation ${o.kind}
73 failed: invalid trim payload.`;break}if(a<=tD.pF&&r<=tD.pF){p.push({operationIndex:t,kind:o.kind,success:!1,summary:`Scene ${o.sceneId} did not include a trim amount.`,error:"trim_scene requires a positive trimStartBySeconds or trimEndBySeconds value."}),n=`Operation ${o.kind} failed: missing trim amount.`;break}let i=u.scenes[e],s=m.get(i.id)??i.timelineStart??0,l=(0,tC.Ip)(i,h),{scene:d,appliedSeconds:c}=function(e,t,a,r){if(!e.media)throw Error(`Scene ${e.id} has no media to trim.`);let n=(0,tC.Ip)(e,r),i=Math.max(0,t),s=i+Math.max(0,a),o=Math.min(Math.max(0,n-.1),s),l=s>0?Math.min(i,o):0,d=Math.max(0,o-l),c=(0,tC.TJ)(e,n),u=Math.max(0,c.start+l),p=Math.max(u+.1,c.end-d);return{scene:{...e,media:{...e.media,trim:{start:u,end:p}}},appliedSeconds:{start:l,end:d}}}(i,a,r,h);if(c.start<=tD.pF&&c.end<=tD.pF){p.push({operationIndex:t,kind:o.kind,success:!1,summary:`Scene ${o.sceneId} could not be trimmed with the requested values.`,error:"Trim operation resolved to zero applied seconds."}),n=`Operation ${o.kind} failed: zero trim applied.`;break}let f=(0,tC.TJ)(i,l),g=(0,tO.AQ)({sceneStart:s,prevTrim:f,mediaDuration:null,requestedTrim:d.media?.trim??f,mode:"clamp"});if(!g.applied){p.push({operationIndex:t,kind:o.kind,success:!1,summary:`Scene ${o.sceneId} could not be trimmed with the requested values.`,error:g.reason}),n=`Operation ${o.kind} failed: ${g.reason}`;break}u.scenes[e]=d,tQ(u,o.sceneId,g,I),p.push({operationIndex:t,kind:o.kind,success:!0,summary:`Trimmed scene ${o.sceneId} by ${c.start.toFixed(2)}s from the start${c.end>0?` and ${c.end.toFixed(2)}s from the end`:""}.`,warning:c.start!==a||c.end!==r?"Requested trim exceeded scene duration and was clamped to keep at least 0.1s of media.":void 0});break}case"generate_captions":{let a=(0,tC.K1)(o,u,e.selectedSceneIds);if(0===a.length){p.push({operationIndex:t,kind:o.kind,success:!1,summary:"Could not tell which scenes to caption.",error:'No target scene resolved. Name the scene (e.g. "scene 1") or select it, then try again.'});break}let r=new Map(o.captionsByScene?.map(e=>[e.sceneId,e.segments])??[]),i=(u.captionBlocks??[]).filter(e=>!o.replaceExisting||!a.includes(e.sceneId)),s=[],l=[];for(let e of a){let t=u.scenes.find(t=>t.id===e);if(!t)continue;let a=m.get(e)??t.timelineStart??0,n=(0,tC.bG)(e,f,g.get(e)??Number(t.trackId??1)),o=r.get(e)??[];if(0===o.length)try{o=await tL(u,t)}catch(t){s.push(e+(t instanceof Error?`: ${t.message}`:""));continue}if(0===o.length){l.push(e);continue}i.push(...tF(e,a,n,o,{trimStart:t.media?.trim?.start??0,sceneDuration:(0,tC.bo)(t)}))}for(let e of(u.captionBlocks=i,a))S.add(e);p.push({operationIndex:t,kind:o.kind,success:0===s.length,summary:l.length>0&&0===s.length?`Generated captions for ${a.length-l.length} scene(s).`:s.length>0?`Caption generation failed for ${s.length} scene(s).`:`Generated captions for ${a.length} scene(s).`,warning:l.length>0?`No speech segments were detected for ${l.length} scene(s).`:void 0,error:s.length>0?s.join("; "):void 0}),s.length>0&&(n=`Caption generation failed for ${s.length} scene(s).`);break}case"replace_captions":{let a=(0,tC.K1)(o,u,e.selectedSceneIds),r=new Map(o.captionsByScene.map(e=>[e.sceneId,e.segments])),n=(u.captionBlocks??[]).filter(e=>!a.includes(e.sceneId));for(let e of a){let t=u.scenes.find(t=>t.id===e),a=m.get(e)??t?.timelineStart??0,i=(0,tC.bG)(e,f,g.get(e)??Number(t?.trackId??1)),s=r.get(e)??[];n.push(...tF(e,a,i,s,t?{trimStart:t.media?.trim?.start??0,sceneDuration:(0,tC.bo)(t)}:void 0))}for(let e of(u.captionBlocks=n,a))S.add(e);p.push({operationIndex:t,kind:o.kind,success:!0,summary:`Replaced captions for ${a.length} scene(s).`});break}case"style_captions":{let a=new Set((0,tC.K1)(o,u,e.selectedSceneIds)),r=o.scope?.type==="track"?o.scope.trackId:void 0,n=0;u.captionBlocks=(u.captionBlocks??[]).map(e=>{let t=0===a.size||a.has(e.sceneId),i=void 0===r||Number(e.trackId)===Number(r);return t&&i?(n+=1,S.add(e.sceneId),{...e,captionStyle:{...e.captionStyle??{},...void 0!==o.style.fontSize?{fontSize:o.style.fontSize}:{},...void 0!==o.style.fontFamily?{fontFamily:o.style.fontFamily}:{},...void 0!==o.style.color?{color:o.style.color}:{},...void 0!==o.style.backgroundColor?{backgroundColor:o.style.backgroundColor}:{},...void 0!==o.style.textAlign?{textAlign:o.style.textAlign}:{},...void 0!==o.style.outlineColor?{outlineColor:o.style.outlineColor}:{},...void 0!==o.style.outlineWidth?{outlineWidth:o.style.outlineWidth}:{},...void 0!==o.style.animationPreset?{animationPreset:o.style.animationPreset}:{}},captionHighlightEnabled:void 0!==o.style.highlightEnabled?o.style.highlightEnabled:e.captionHighlightEnabled,captionHighlightStyle:o.style.highlightStyle?{...e.captionHighlightStyle??{},...o.style.highlightStyle}:e.captionHighlightStyle}):e}),p.push({operationIndex:t,kind:o.kind,success:!0,summary:`Styled ${n} caption block(s).`});break}case"apply_scene_effect":{let a=function(e){let t=e?.effect;if(t&&"object"==typeof t&&"string"==typeof t.type){if(tA.has(t.type))return t;let e=t.type.toUpperCase().replace(/[\s/\-]+/g,"_").replace(/_+/g,"_");
73if(tA.has(e))return{...t,type:e}}let a="string"==typeof t?t:t&&"object"==typeof t&&"string"==typeof t.name?t.name:t&&"object"==typeof t&&"string"==typeof t.preset?t.preset:"string"==typeof e?.type?e.type:"string"==typeof e?.effectType?e.effectType:"string"==typeof e?.effect_name?e.effect_name:"string"==typeof e?.name?e.name:null;if(!a)return null;let r=a.toUpperCase().replace(/[\s/\-]+/g,"_").replace(/_+/g,"_");return tA.has(r)?{type:r,params:e?.params&&"object"==typeof e.params?e.params:e?.effectParams&&"object"==typeof e.effectParams?e.effectParams:{},enabled:"boolean"!=typeof e?.enabled||e.enabled}:null}(o);if(!a){p.push({operationIndex:t,kind:o.kind,success:!1,summary:"Scene effect operation was missing effect details.",error:"Expected an effect payload with a valid type."}),n="AI effect plan did not include a valid effect payload.";break}let r=(0,tC.K1)(o,u,e.selectedSceneIds);if(0===r.length){p.push({operationIndex:t,kind:o.kind,success:!1,summary:"Scene effect operation did not resolve any matching scenes.",error:"Expected at least one valid target scene for this effect apply."}),n="AI effect plan did not resolve any target scenes.";break}let i=0;if(u.scenes=u.scenes.map(e=>r.includes(e.id)?(i+=1,function(e,t,a){let r=(e.effects??[]).filter(e=>!!(e&&"string"==typeof e.type));if("remove"===a)return{...e,effects:r.filter(e=>e.type!==t.type)};let n={id:`effect-${(0,v.generateId)()}`,type:t.type,params:t.params??{},enabled:t.enabled??!0};if("replace"===a)return{...e,effects:[n]};let i=r.findIndex(e=>e.type===t.type);if(i>=0){let a=[...r];return a[i]={...a[i],params:t.params??a[i].params,enabled:t.enabled??a[i].enabled},{...e,effects:a}}return{...e,effects:[...r,n]}}(e,a,o.mode??"append")):e),0===i){p.push({operationIndex:t,kind:o.kind,success:!1,summary:"Scene effect operation did not update any scenes.",error:"Resolved scene targets were not found during apply."}),n="AI effect apply updated zero scenes.";break}p.push({operationIndex:t,kind:o.kind,success:!0,summary:`Updated effects on ${i} scene(s).`});break}case"apply_transition":{let a,{sceneIds:r,usedResolvedTargetFallback:i}=function(e,t,a,r){let n=(0,tC.K1)(e,t,a),i=["sceneId","sceneIds","sceneNumber","sceneNumbers","blockId"].some(t=>null!=e[t]&&!("string"==typeof e[t]&&!String(e[t]).trim())),s=(0,tC.LG)(e.scope)||e.scope?.type==="scene_ids"||e.scope?.type==="track";if(n.length>0||i||s)return{sceneIds:n,usedResolvedTargetFallback:!1};let o=r?(0,tC.Zx)(r,t):null;return{sceneIds:o?[o]:[],usedResolvedTargetFallback:!!o}}(o,u,e.selectedSceneIds,l.resolvedSceneTarget);if(0===r.length){p.push({operationIndex:t,kind:o.kind,success:!1,summary:"Transition operation did not resolve any matching scenes.",error:"No scene targets were resolved from operation scope or plan target."}),n="AI transition apply did not resolve any target scenes.";break}let s=o.mode??"set",d="remove"===s?null:function(e){let t=e?.transition,a=function(e){if("string"!=typeof e)return null;let t=e.trim();if(!t)return null;let a=t.toUpperCase().replace(/[\s/\-]+/g,"_").replace(/_+/g,"_"),r={CROSS_FADE:"CROSSFADE",CROSS_DISSOLVE:"CROSSFADE",DISSOLVE:"CROSSFADE",BLUR_FADE:"BLUR_TRANSITION",GLITCH:"GLITCH_TRANSITION",SWIRL:"SWIRL_TRANSITION",KALEIDOSCOPE:"KALEIDOSCOPE_TRANSITION"}[a]??a;return tE.has(r)?r:null}(t&&"object"==typeof t&&"string"==typeof t.type?t.type:"string"==typeof t?t:"string"==typeof e?.transitionType?e.transitionType:"string"==typeof e?.type?e.type:"string"==typeof e?.name?e.name:null);if(!a)return null;let r=(0,t_.getTransitionDefinition)(a),n=Number(r?.defaultDuration??.5),i=Math.max(.05,t&&"object"==typeof t&&Number.isFinite(t.duration)?Number(t.duration):Number.isFinite(e?.duration)?Number(e.duration):Number.isFinite(e?.transitionDuration)?Number(e.transitionDuration):n),s=t&&"object"==typeof t&&t.params&&"object"==typeof t.params?t.params:e?.params&&"object"==typeof e.params?e.params:e?.transitionParams&&"object"==typeof e.transitionParams?e.transitionParams:{},o=r?.defaultParams&&Object.keys(r.defaultParams).length>0?{...r.defaultParams,...s}:s;return{type:a,duration:i,params:o,enabled:t&&"object"==typeof t&&"boolean"==typeof t.enabled?t.enabled:"boolean"!=typeof e?.enabled||e.enabled}}(o);if("remove"!==s&&!d){p.push({operationIndex:t,kind:o.kind,success:!1,summary:"Transition payload was invali
73d.",error:"Transition type was missing or unsupported."}),n="AI transition apply failed: invalid transition payload.";break}if("remove"!==s){let e=e=>{let t=u.scenes.find(t=>t.id===e);if(!t)return!1;let a=Number(f.get(e)??t.trackId??1),r=m.get(e)??t.timelineStart??0;return u.scenes.some(t=>t.id!==e&&Number(f.get(t.id)??t.trackId??1)===a&&(m.get(t.id)??t.timelineStart??0)>r+tD.pF)},n=r.filter(t=>!e(t));if(n.length>0&&(r=r.filter(t=>e(t)),a=`Skipped ${n.length} scene(s) with no following scene on their track (an outgoing transition has nothing to blend into).`),0===r.length){p.push({operationIndex:t,kind:o.kind,success:!1,summary:"The targeted scene is the last on its track, so an outgoing transition would never render.",error:"Target an earlier scene, or add a scene after this one first."});break}}let c=(0,tC.dw)(u,m),h=r.map(e=>c.get(e)??0).filter(e=>e>0).sort((e,t)=>e-t),g=1===h.length?`scene ${h[0]}`:h.length>1?`scenes ${h.join(", ")}`:`${r.length} scene(s)`,x=1===h.length&&h[0]<c.size?`between scene ${h[0]} and scene ${h[0]+1}`:null,b=0;if(u.scenes=u.scenes.map(e=>r.includes(e.id)?(b+=1,"remove"===s)?{...e,transition:void 0}:{...e,transition:d}:e),0===b){p.push({operationIndex:t,kind:o.kind,success:!1,summary:"Transition operation did not update any scenes.",error:"Resolved scene targets were not found during apply."}),n="AI transition apply updated zero scenes.";break}p.push({operationIndex:t,kind:o.kind,success:!0,summary:"remove"===s?`Removed transitions from ${g}.`:x?`Set ${d.type} transition (${d.duration.toFixed(1)}s) ${x}.`:`Set ${d.type} transition (${d.duration.toFixed(1)}s) on ${g}.`,warning:[i?"Scope resolved empty; runtime used the plan target scene fallback.":null,a??null].filter(Boolean).join(" ")||void 0});break}case"cut_silence":{let a=(0,tC.K1)(o,u,e.selectedSceneIds),r=Math.max(.1,o.minGapSeconds??.4),n=(0,tD.up)(o),i=u.aiAnalysis?.audioArtifacts,s=0,l=0,d=0,c=0,h=0,f=0,g=0,x=0,b=0,y=0,v=0,w=0,k=0,S=0,j=0,N=0;for(let e of a){let t=u.scenes.findIndex(t=>t.id===e);if(t<0)continue;let a=u.scenes[t];if(!a.media){w+=1,l+=1;continue}let o=m.get(e)??a.timelineStart??0,p=(0,tC.bo)(a),C=a.media.trim??{start:0,end:a.media.duration??p},M=(u.captionBlocks??[]).filter(t=>t.sceneId===e).sort((e,t)=>e.start-t.start),_=0,A=0,E=!1,T=!1,$=(0,tD.NG)(a,i);if(!$){let e=await (0,tD.tm)(a,i);e.artifact?($=e.artifact,u.aiAnalysis={...u.aiAnalysis??{},audioArtifacts:{...u.aiAnalysis?.audioArtifacts??{},[e.artifact.sourceFingerprint]:e.artifact}},i=u.aiAnalysis.audioArtifacts,h+=1):e.unavailableReason&&(T=!0,l+=1)}let P=!!$&&Array.isArray($.speech?.activeRanges)&&$.speech.activeRanges.length>0;if($&&P){let e=(0,tD.nA)($,C.start,C.end,r);_=e.leadingSilence>r?e.leadingSilence:0,A=e.trailingSilence>r?e.trailingSilence:0,E=e.hasInternalGaps,d+=1}else if(M.length>0){let e=M[0],t=M[M.length-1],a=o+p,n=Math.max(0,e.start-o),i=Math.max(0,a-(t.start+t.duration));_=n>r?n:0,A=i>r?i:0;for(let e=0;e<M.length-1;e+=1){let t=M[e];if(M[e+1].start-(t.start+t.duration)>r){E=!0;break}}c+=1}if(0===_&&0===A){if($){let t=t5(u,e,o,n,$,I);if(v+=t.speechProtectedWindows,t.applied){s+=1,f+=1,g+=t.splitInsertedScenes;continue}t.skippedInternalDueToCaptions&&(x+=1,l+=1),t.skippedInternalDueToVoiceover&&(b+=1,l+=1),t.skippedForSafety&&(y+=1,l+=1)}else if(0===M.length){k+=1,T&&(N+=1),l+=1;continue}E?j+=1:S+=1,l+=1;continue}t0(u,e,o,p,C,_,A,I).applied&&(E&&(l+=1),s+=1)}let C=d>0&&c>0?` (${d} artifact-backed${h>0?`, ${h} on-demand`:""}, ${c} caption-fallback)`:d>0?` (artifact-backed${h>0?`; ${h} on-demand`:""})`:c>0?" (caption-fallback)":"",M=f>0?` ${f} scene(s) used low-loudness fallback${g>0?` with ${g} inserted split segment(s)`:""}.`:"",_=[];w>0&&_.push(`Skipped ${w} scene(s) without media.`),k>0&&_.push(`No usable analysis or caption timing was available for ${k} scene(s).`),N>0&&_.push(`On-demand analysis was unavailable and caption fallback was unavailable for ${N} scene(s).`),S>0&&_.push(`No leading/trailing silence above threshold was detected for ${S} scene(s).`),j>0&&_.push(`Only internal silent gaps were detected for ${j} scene(s); internal-gap ripple editing is not implemented yet.`),x>0&&_.push(`Skipped internal quiet-range cleanup for ${x} scene(s) because captions are present and ripple-safe caption rebasing is not enabled.`),b>0&&_.push(`Skipped internal quiet-range cleanup for ${b} scene(s) because a separate narration voiceover overlaps them and would go out of sync â use 'remove ...' phrasing instead.`),y>0&&_.push(`Skipped quiet-range cleanup for ${y} scene(s) because the detected keep ranges were too short or too fragmented for a safe deterministic cut.`),v>0&&_.push(`Speech protection kept ${v} low-loudness windows from being removed.`),p.push({operationIndex:t,kind:o.kind,success:!0,summary:s>0?`Applied silence/dead-air cleanup to ${s} scene(s)${C}.${M}`:`No silence/dead-air cleanup was applied to 0 scene(s)${C}.`,warning:_.length>0?_.join(" "):l>0?"Some scenes could not be trimmed in this pass.":void 0});break}case"set_keyframes":{let a=function(e){let t,a,{operation:r,operationIndex:n,workingProject:i,selectedSceneIds:s}
73=e,o=(0,tC.K1)(r,i,s),l=["sceneId","sceneIds","sceneNumber","sceneNumbers","scope","blockId"].some(e=>{let t=r[e];return null!=t&&!("string"==typeof t&&!t.trim())});if(0!==o.length||l||0===(o=s.filter(e=>i.scenes.some(t=>t.id===e))).length&&1===i.scenes.length&&(o=[i.scenes[0].id]),0===o.length)return{operationIndex:n,kind:r.kind,success:!1,summary:l?"The requested animation target is no longer available.":"Could not tell which scene to keyframe.",error:l?"The requested scene or track was not found. Select a current scene and request the edit again.":'No target scene resolved. Name the scene (e.g. "scene 1") or select it, then try again.'};for(let e of o){let n=i.scenes.findIndex(t=>t.id===e);if(n<0)continue;let s=function(e,t,a){let r=tT[String(t??"").trim().toLowerCase()];if(!r)return{scene:e,applied:!1,error:`Unsupported keyframe target "${t}". Use transform.userZoom, transform.panX, transform.panY, or transform.rotation.`};let n=t$[r],i=(Array.isArray(a)?a:[]).filter(e=>e&&Number.isFinite(e.time)&&e.time>=0&&Number.isFinite(e.value)).map(e=>({id:(0,v.generateId)(),time:e.time,value:Math.max(n.min,Math.min(n.max,e.value))})).sort((e,t)=>e.time-t.time);if(0===i.length)return{scene:e,applied:!1,property:r,error:"No usable keyframes were provided (each needs a non-negative time and numeric value)."};let s=(Array.isArray(a)?a:[]).some(e=>e?.easing&&"linear"!==e.easing);return{scene:{...e,automation:{...e.automation??{},[r]:{propertyId:r,interpolation:s?"smooth":"linear",keyframes:i}}},applied:!0,property:r}}(i.scenes[n],r.target,r.keyframes);if(!s.applied){a=s.error;break}i.scenes[n]=s.scene,t=s.property}return a||!t?{operationIndex:n,kind:r.kind,success:!1,summary:`Could not animate ${r.target}.`,error:a??"No resolvable scenes to keyframe.",sceneId:o[0]}:{operationIndex:n,kind:r.kind,success:!0,summary:`Animated ${t} on ${o.length} scene(s) with ${r.keyframes.length} keyframe(s).`,sceneId:o[0]}}({operation:o,operationIndex:t,workingProject:u,selectedSceneIds:e.selectedSceneIds});p.push(a),a.success||(n=`Operation ${o.kind} failed: ${a.error}`);break}case"apply_animation":{let i,s=(0,tC.K1)(o,u,e.selectedSceneIds);if(0===s.length){p.push({operationIndex:t,kind:o.kind,success:!1,summary:"No target scenes were found for the animation.",error:"Animation requires at least one resolvable scene."}),n=`Operation ${o.kind} failed: no target scenes resolved.`;break}if(a=o.preset,"string"!=typeof a||!(a in as)){p.push({operationIndex:t,kind:o.kind,success:!1,summary:`Unknown animation preset "${o.preset}".`,error:`Supported presets: ${Object.keys(as).join(", ")}.`}),n=`Operation ${o.kind} failed: unknown preset "${o.preset}".`;break}let l=as[o.preset],d=(r=o.intensity,"subtle"===r||"strong"===r||"normal"===r?r:"normal"),c=[],m=0;for(let e=0;e<s.length;e+=1){let t=s[e],a=u.scenes.findIndex(e=>e.id===t);if(a<0){c.push(`${t} (missing)`);continue}let r=u.scenes[a],n=function(e){let t=as[e.presetId];if(!t)return{error:`Unknown animation preset "${e.presetId}".`};let a=Number.isFinite(e.sceneDurationSeconds)?Math.max(0,e.sceneDurationSeconds):0;if(a<=.05)return{error:"Scene is too short to animate."};let r=("number"==typeof e.durationSeconds&&Number.isFinite(e.durationSeconds)?Math.max(.1,e.durationSeconds):void 0)??("full_scene"===t.defaultDuration?a:t.defaultDuration),n=Math.min(a,Math.max(.1,r)),i=ar[e.intensity??"normal"],s=t.variants.length>1?Math.abs(Math.trunc(e.sceneOrdinal??0))%t.variants.length:0,o=t.variants[s],l={};for(let e of o){let t=e.points.map(t=>({id:(0,v.generateId)(),time:Number((t.at*n).toFixed(4)),value:Number((function(e,t,a){let r=at[e];return function(e,t){let{min:a,max:r}=aa[e];return Math.max(a,Math.min(r,t))}(e,r+(t-r)*a)})(e.propertyId,t.value,i).toFixed(4))}));l[e.propertyId]={propertyId:e.propertyId,interpolation:e.interpolation,keyframes:t}}return{curves:l,durationSeconds:n,affectedProperties:o.map(e=>e.propertyId)}}({presetId:o.preset,sceneDurationSeconds:(0,tC.Ip)(r,h),durationSeconds:o.durationSeconds,intensity:d,sceneOrdinal:e});if("error"in n){c.push(`${t} (${n.error})`);continue}u.scenes[a]=function(e,t){let a={...e.automation??{}};for(let[e,r]of Object.entries(t))r&&(a[e]=r);return{...e,automation:a}}(r,n.curves),i=n.durationSeconds,m+=1}if(0===m){p.push({operationIndex:t,kind:o.kind,success:!1,summary:`No scenes could be animated with ${l.label}.`,error:c.length>0?`Skipped: ${c.join("; ")}`:void 0}),n=`Operation ${o.kind} failed: no scenes could be animated.`;break}let f="full_scene"===l.defaultDuration&&"number"!=typeof o.durationSeconds?"across each scene":`over ~${(i??0).toFixed(1)}s`;p.push({operationIndex:t,kind:o.kind,success:!0,summary:`Applied ${l.label} (${d}) to ${m}
73 scene(s) ${f}.`,warning:c.length>0?`Skipped ${c.length} scene(s): ${c.join("; ")}`:void 0,sceneId:s[0]});break}case"duck_audio":{let e=(0,tR.jw)(o),a=(0,tR.U2)(u,o,tD.X4);if(0===a.length){p.push({operationIndex:t,kind:o.kind,success:!1,summary:"No music tracks were found to duck.",error:"Add a music block first (or name the audio block/track that should duck)."}),n=`Operation ${o.kind} failed: no music blocks resolved.`;break}let r=new Set(a.map(e=>"string"==typeof e?.id?e.id:null).filter(e=>!!e)),i=(0,tR.lt)(u),s=u.aiAnalysis?.audioArtifacts,l=0;for(let e of u.scenes.filter(e=>e.media?.type==="video"&&!0!==e.muted&&("number"!=typeof e.volume||e.volume>.001))){let t=(0,tD.NG)(e,s);if(!t){let a=await (0,tD.tm)(e,s);a.artifact&&(t=a.artifact,u.aiAnalysis={...u.aiAnalysis??{},audioArtifacts:{...u.aiAnalysis?.audioArtifacts??{},[a.artifact.sourceFingerprint]:a.artifact}},s=u.aiAnalysis.audioArtifacts)}if(!t){l+=1;continue}let a=m.get(e.id)??e.timelineStart??0;i.push(...(0,tR.fu)(e,t,a))}if(0===i.length){p.push({operationIndex:t,kind:o.kind,success:!1,summary:"No narration or speech was found to duck under.",error:l>0?"No voiceover blocks exist and speech analysis was unavailable for the scene audio.":"Add a voiceover (or scenes with spoken audio) before ducking the music."}),n=`Operation ${o.kind} failed: no speech to duck under.`;break}let d=0,c=0,h=0,f=t=>Array.isArray(t)&&0!==t.length?t.map(t=>{let a="string"==typeof t?.id?t.id:null;if(!a||!r.has(a))return t;let n=Number.isFinite(t?.start)?Number(t.start):0,s=(0,tR.JK)(t),o="number"==typeof t?.volume&&Number.isFinite(t.volume)?t.volume:1,l=(0,tR.Fj)({blockStartSeconds:n,blockDurationSeconds:s,baseVolume:o,speechRanges:i,settings:e});return l.curve?(t?.automation?.volume&&(h+=1),d+=1,c+=l.duckedSections,{...t,automation:{...t.automation??{},volume:l.curve},updatedAt:Date.now()}):t}):t;if(u.audio=f(u.audio)??u.audio,u.voiceovers=f(u.voiceovers)??u.voiceovers,0===d){p.push({operationIndex:t,kind:o.kind,success:!1,summary:"The speech does not overlap the music, so there was nothing to duck.",error:"The music block(s) play outside the narrated sections."}),n=`Operation ${o.kind} failed: speech does not overlap the music.`;break}let g=[];h>0&&g.push(`Replaced the existing volume automation on ${h} music block(s).`),l>0&&g.push(`Speech analysis was unavailable for ${l} scene(s); their speech is not ducked.`),p.push({operationIndex:t,kind:o.kind,success:!0,summary:`Ducked ${d} music block(s) by ${Math.abs(e.duckDb).toFixed(0)} dB under ${c} speech section(s).`,warning:g.length>0?g.join(" "):void 0});break}case"cut_quiet_sections":{let a=(0,tC.K1)(o,u,e.selectedSceneIds),r=(0,tD.up)(o),n=u.aiAnalysis?.audioArtifacts,i=0,s=0,l=0,d=0,c=0,h=0,f=0,g=0,x=0,b=0;for(let e of a){let t=u.scenes.find(t=>t.id===e);if(!t?.media){d+=1;continue}let a=m.get(e)??t.timelineStart??0,o=(0,tD.NG)(t,n);if(!o){let e=await (0,tD.tm)(t,n);e.artifact&&(o=e.artifact,u.aiAnalysis={...u.aiAnalysis??{},audioArtifacts:{...u.aiAnalysis?.audioArtifacts??{},[e.artifact.sourceFingerprint]:e.artifact}},n=u.aiAnalysis.audioArtifacts,l+=1)}if(!o){c+=1;continue}let p=t5(u,e,a,r,o,I);if(b+=p.speechProtectedWindows,p.applied){i+=1,s+=p.splitInsertedScenes;continue}p.skippedInternalDueToCaptions?f+=1:p.skippedInternalDueToVoiceover?g+=1:p.skippedForSafety||p.hadRemovableRanges?x+=1:h+=1}let y=[];d>0&&y.push(`Skipped ${d} scene(s) without media.`),c>0&&y.push(`No loudness analysis was available for ${c} scene(s).`),h>0&&y.push(`No quiet ranges met threshold (${r.quietThresholdDb.toFixed(1)} dB) and minimum duration (${r.minQuietSeconds.toFixed(2)}s) for ${h} scene(s).`),f>0&&y.push(`Skipped internal quiet-range cuts for ${f} scene(s) because captions are present and ripple-safe caption rebasing is not enabled.`),g>0&&y.push(`Skipped internal quiet-range cuts for ${g} scene(s) because a separate narration voiceover overlaps them and would go out of sync â use 'remove ...' phrasing instead.`),x>0&&y.push(`Skipped quiet-section cuts for ${x} scene(s) because safe deterministic keep ranges could not be produced.`),b>0&&y.push(`Speech protection kept ${b} low-loudness windows from being removed.`);let v=l>0?` (${l} on-demand artifact)`:"";p.push({operationIndex:t,kind:o.kind,success:!0,summary:i>0?`Applied quiet-section cleanup to ${i} scene(s)${s>0?` with ${s} inserted split segment(s)`:""}${v}.`:`No quiet-section cleanup was applied to 0 scene(s)${v}.`,warning:y.length>0?y.join(" "):void 0});break}case"isolate_speech":{let a=(0,tC.K1)(o,u,e.selectedSceneIds),r=(0,tD.sM)(o),n=u.aiAnalysis?.audioArtifacts,i=0,s=0,l=0,d=0,c=0,h=0,f=0,g=0,x=0,b=0,y=0;for(let e of a){let t=u.scenes.find(t=>
73t.id===e);if(!t?.media){h+=1;continue}let a=m.get(e)??t.timelineStart??0,o=(0,tD.NG)(t,n);if(!o){let e=await (0,tD.tm)(t,n);e.artifact&&(o=e.artifact,u.aiAnalysis={...u.aiAnalysis??{},audioArtifacts:{...u.aiAnalysis?.audioArtifacts??{},[e.artifact.sourceFingerprint]:e.artifact}},n=u.aiAnalysis.audioArtifacts,l+=1)}if(!o){f+=1;continue}let p=t2(u,e,a,r,o,I);if(p.applied){i+=1,s+=p.splitInsertedScenes;continue}if(p.hadSpeechRanges)p.skippedInternalDueToCaptions?x+=1:p.skippedInternalDueToVoiceover?b+=1:(p.skippedForSafety,y+=1);else{let n=(0,tC.bo)(t),l=t.media.trim??{start:0,end:t.media.duration??n},p=(u.captionBlocks??[]).filter(t=>t.sceneId===e).map(e=>{let t=e.start-a,r=t+e.duration;return{start:Math.max(l.start,t),end:Math.min(l.end,r)}}).filter(e=>e.end-e.start>tD.pF),m=!1,h=p;if(0===h.length)try{m=(h=(await tL(u,t)).map(e=>({start:Math.max(l.start,e.start),end:Math.min(l.end,e.end)})).filter(e=>e.end-e.start>tD.pF)).length>0}catch{h=[]}if(h.length>0){let t={...o,speech:{provider:o.speech?.provider??"energy_threshold",activeRanges:h,silenceRanges:o.speech?.silenceRanges??[]}},n=t2(u,e,a,r,t,I);if(n.applied){i+=1,s+=n.splitInsertedScenes,m?c+=1:d+=1;continue}n.skippedInternalDueToCaptions?x+=1:n.skippedInternalDueToVoiceover?b+=1:n.skippedForSafety?y+=1:g+=1;continue}g+=1}}let v=[];h>0&&v.push(`Skipped ${h} scene(s) without media.`),f>0&&v.push(`No speech analysis was available for ${f} scene(s), including on-demand retries.`),g>0&&v.push(`No speech segments were detected for ${g} scene(s).`),x>0&&v.push(`Skipped internal speech isolation for ${x} scene(s) because captions are present and ripple-safe caption rebasing is not enabled.`),b>0&&v.push(`Skipped internal speech isolation for ${b} scene(s) because a separate narration voiceover overlaps them and would go out of sync â use 'remove ...' phrasing instead.`),y>0&&v.push(`Skipped speech isolation for ${y} scene(s) because the detected speech fragments were too short or too fragmented for a safe deterministic cut.`);let w=l>0?` (${l} on-demand artifact)`:"",k=d>0||c>0?` Speech fallback applied on ${d+c} scene(s)${d>0?` (${d} caption-range`:""}${c>0?`${d>0?", ":" ("}${c} transcript`:""}${d>0||c>0?")":""}.`:"";p.push({operationIndex:t,kind:o.kind,success:!0,summary:i>0?`Applied speech isolation to ${i} scene(s)${s>0?` with ${s} inserted split segment(s)`:""}${w}.${k}`:`No speech isolation was applied to 0 scene(s)${w}.`,warning:v.length>0?v.join(" "):void 0});break}case"cut_on_beat":{let a=(0,tC.K1)(o,u,e.selectedSceneIds),r=(0,tD.hW)(o),n=u.aiAnalysis?.audioArtifacts,i=0,s=0,l=0,d=0,c=0,h=0,g=0,x=0,b=0,y=0,v=0,w=new Set,k=[],S=!1,j=r.anchor,I=null,N=null,C=r.beatSourceMode,M="scene audio",_=async(e,t)=>{let a=(0,tD.sV)(e,n,{preferServerDownbeat:!0}),r=!!a&&!(0,tD.o$)(a);if(!(0,tD.r2)(u,e,a))return a;let i=await (0,tD.WA)(u,e,n);return i.artifact?(a="server"===i.analysisPath?i.artifact:a??i.artifact,u.aiAnalysis={...u.aiAnalysis??{},audioArtifacts:{...u.aiAnalysis?.audioArtifacts??{},[i.artifact.sourceFingerprint]:i.artifact}},n=u.aiAnalysis.audioArtifacts,d+=1,"server"===i.analysisPath?(c+=1,"upload"===i.serverTransport&&k.push(`Server-side downbeat analysis used uploaded local audio bytes for ${t}.`),r&&k.push(`Requested music source ${t} was upgraded from client artifact to server downbeat artifact.`)):(h+=1,i.serverFallbackWarning&&k.push(i.serverFallbackWarning),r&&k.push(`Server downbeat unavailable, reused client-side rhythm artifact for ${t}.`)),a):r&&a?(k.push(`Server downbeat unavailable, reused client-side rhythm artifact for ${t}.`),i.serverFallbackWarning&&k.push(i.serverFallbackWarning),a):null};if("string"==typeof o.audioBlockId&&o.audioBlockId.trim())C="explicit_track",M=`audio block ${o.audioBlockId}`,(I=await _(o.audioBlockId,M))?N=o.audioBlockId.trim():(k.push(`Requested beat source ${M} was unavailable, so runtime fell back to scene audio markers.`),C="scene_audio");else if("auto_music"===r.beatSourceMode){let e=(0,tD.wV)(u,n);e?(M=`auto music block ${e}`,(I=await _(e,M))?N=e:(k.push(`Auto-selected music source ${M} could not be analyzed, so runtime fell back to scene audio markers.`),C="scene_audio")):(k.push("No clear music source was detected, so runtime used scene audio beat markers."),C="scene_audio")}else C="scene_audio";for(let e of a){let t,a=u.scenes.findIndex(t=>t.id===e);if(a<0)continue;let o=u.scenes[a];if(!o.media){g+=1;continue}let d=m.get(e)??o.timelineStart??0,c=(0,tC.bo)(o),p=o.media.trim??{start:0,end:o.media.duration??c},h=(0,tD.NG)(o,n);if(!h){let e=await (0,tD.tm)(o,n);e.artifact&&(h=e.artifact,u.aiAnalysis={...u.aiAnalysis??{},audioArtifacts:{...u.aiAnalysis?.audioArtifacts??{},[e.artifact.sourceFingerprint]:e.artifact}},n=u.aiAnalysis.audioArtifacts,l+=1)}let k="scene_audio"===C?h:I??h;
73if(!k){x+=1;continue}let M=(0,tD.y9)(k,r);if(M.warnings.forEach(e=>w.add(e)),M.anchorModeUsed!==r.anchor&&(S=!0,j=M.anchorModeUsed),!(Array.isArray(M.markerTimes)&&M.markerTimes.length>0)){b+=1;continue}let _=!(M.sourceStartSeconds>tD.pF)&&"scene_audio"!==C&&k===I&&N?(0,tD.Ir)(u,N):null;if(_){let e=Number.isFinite(Number(_.start))?Number(_.start):0,a=Number.isFinite(Number(_.inOffset))?Number(_.inOffset):0;t=M.markerTimes.filter(e=>e>=M.sourceStartSeconds-tD.pF).map(t=>{let r=e+(t-a);return p.start+(r-d)}).filter(e=>e>p.start+tD.pF&&e<p.end-tD.pF)}else t=k.sourceSceneId!==o.id||M.sourceStartSeconds>tD.pF?M.markerTimes.filter(e=>e>=M.sourceStartSeconds-tD.pF).map(e=>p.start+(e-M.sourceStartSeconds)).filter(e=>e>p.start+tD.pF&&e<p.end-tD.pF):M.markerTimes;let A=(0,tD.ji)(p.start,p.end,t,r);if(A.length<=1){v+=1;continue}if((u.captionBlocks??[]).some(t=>t.sceneId===e)){y+=1;continue}let E=d,T=A.map((e,t)=>{let a=Math.max(.1,e.end-e.start),r=E;E+=a;let n=tU({automation:o.automation,effects:o.effects,previousTrimStart:p.start,segmentMediaStart:e.start,segmentMediaEnd:e.end,isFirstSegment:0===t});return{...o,id:0===t?o.id:(0,tC.w0)(o.id,e,t,"beat"),timelineStart:r,trackId:o.trackId??1,transition:t<A.length-1?void 0:o.transition,automation:n.automation,effects:n.effects,media:{...o.media,trim:{start:e.start,end:e.end}}}});for(let e of(u.scenes.splice(a,1,...T),T))m.set(e.id,e.timelineStart??d),f.set(e.id,Number(e.trackId??1));i+=1,s+=Math.max(0,T.length-1)}let A=[];g>0&&A.push(`Skipped ${g} scene(s) without media.`),x>0&&A.push(`No rhythm analysis was available for ${x} scene(s), including on-demand retries.`),b>0&&A.push(`No beat markers were available for ${b} scene(s).`),y>0&&A.push(`Skipped beat-synced internal splits for ${y} scene(s) because captions are present and ripple-safe caption rebasing is not enabled.`),v>0&&A.push(`Skipped beat-synced cuts for ${v} scene(s) because safe beat-aligned segments could not be produced with the current min segment and max cut limits.`),w.size>0&&A.push(...Array.from(w)),k.length>0&&A.push(...k);let E=[];l>0&&E.push(`${l} on-demand scene artifact`),d>0&&E.push(`${d} on-demand beat-source artifact`),c>0&&E.push(`${c} server-side beat-source artifact`),h>0&&E.push(`${h} client-side beat-source artifact`);let T=E.length>0?` (${E.join(", ")})`:"",$="scene_audio"===C?"client-side rhythm analysis":(0,tD.pm)(I);p.push({operationIndex:t,kind:o.kind,success:!0,summary:i>0?`Applied beat-synced cuts to ${i} scene(s)${s>0?` with ${s} inserted split segment(s)`:""} using ${"scene_audio"===C?"scene audio":M} with ${r.distribution} distribution and ${r.anchor.replace("_","-")} anchor${S?` (fell back to ${j.replace("_","-")})`:""} via ${$}${T}.`:`No beat-synced cuts were applied to 0 scene(s)${T}.`,warning:A.length>0?A.join(" "):void 0});break}case"create_montage":{let a=await ap(o,t,{workingProject:u,selectedSceneIds:e.selectedSceneIds,sceneStartMap:m,captionSyncSceneIds:S,resolveSceneIds:t=>(0,tC.K1)(t,u,e.selectedSceneIds),requestShotAnalysis:async(e,t)=>{let a=await (0,af.gW)(e,t);return a.success&&a.data?.status==="ready"&&a.data.artifact?a.data.artifact:null}});p.push(a),a.success||(n=a.error??"Montage could not be created.");break}case"generate_scene_visual":{let e=function(e,t,a,r,n){let i,s=tI(e,t),o=e.durationTarget??5,l=e.aspectRatio??t.aspectRatio??"9:16";if(!["9:16","16:9","1:1","4:3","3:4","21:9"].includes(l))throw Error("Choose a supported video aspect ratio.");let d=0,c=(0,tC.yw)();for(let e of t.scenes.filter(e=>!e.isAudioBlock)){let t=a.get(e.id)??e.timelineStart??0,r=(0,tC.Ip)(e,c)||5;(!i||t+r>d)&&(i=e,d=t+r)}let u=`gen-${r}-${n}`;return{scene:{id:u,url:"",text:e.prompt.trim().slice(0,120),media:{type:"video",status:"generating",url:"",duration:o},generation:{provider:s.videoProvider,model:s.videoModel,mode:s.references.length?"image-to-video":"text-to-video",prompt:e.prompt,quality:s.videoQualityTier,referenceSceneIds:e.referenceSceneIds,imageGuidanceMode:s.imageGuidanceMode},source:{platform:"ai-generation"},createdAt:Date.now(),timelineStart:Math.max(0,d),trackId:i?.trackId??1,muted:!0}
73,request:{sceneId:u,prompt:e.prompt,aspectRatio:l,durationTarget:o,generation:s,idempotencyKey:`ai-editor:${t.id}:${r}:${n}`}}}(o,u,m,l.id,t),a=u.scenes.find(t=>t.id===e.scene.id);if(a){if(a.generation?.prompt!==o.prompt||a.generation?.model!==e.request.generation.videoModel)throw Error("This generation step already has different settings. Request a new plan.");p.push({operationIndex:t,kind:o.kind,success:!0,sceneId:a.id,summary:"This generation step already exists; no second job was requested."});break}u.scenes.push(e.scene),m.set(e.scene.id,e.scene.timelineStart??0),f.set(e.scene.id,Number(e.scene.trackId??1)),i||(i=[]),i.push(e.request),p.push({operationIndex:t,kind:o.kind,success:!0,sceneId:e.scene.id,summary:"Queued a new video clip. Original media and audio are unchanged."});break}case"regenerate_scene_visual":case"regenerate_scene_voiceover":{let a=(0,tC.K1)(o,u,e.selectedSceneIds).filter(e=>u.scenes.some(t=>t.id===e&&!t.isAudioBlock));if(0===a.length){p.push({operationIndex:t,kind:o.kind,success:!1,summary:"No matching scenes found to regenerate.",error:"No matching scenes found to regenerate."});break}let r="regenerate_scene_visual"===o.kind?"scene_visual":"scene_voiceover";for(let e of(s||(s=[]),a))s.push({type:r,sceneId:e});let n="scene_visual"===r?"visuals":"voiceover";p.push({operationIndex:t,kind:o.kind,success:!0,sceneId:1===a.length?a[0]:void 0,summary:`Queued ${n} regeneration for ${a.length} scene${1===a.length?"":"s"}.`});break}case"regenerate_voiceover_beat":{let e=o.blockId??"",a=(0,tD.CR)(u).find(t=>t?.id===e);if(!e||!a){p.push({operationIndex:t,kind:o.kind,success:!1,summary:"Voiceover beat not found.",error:`No audio block with id "${e}" exists in this project.`});break}if(!(a.text??"").trim()){p.push({operationIndex:t,kind:o.kind,success:!1,summary:"Voiceover beat has no script to re-render.",error:"The target audio block has no narration text."});break}s||(s=[]),s.push({type:"voiceover_beat",blockId:e}),p.push({operationIndex:t,kind:o.kind,success:!0,summary:"Queued voiceover beat re-render with the same script and voice."});break}default:p.push({operationIndex:t,kind:o.kind,success:!1,summary:`Operation ${o.kind} is not ready in this runtime pass.`,warning:"Plan was preserved. No destructive fallback was applied."})}}catch(e){p.push({operationIndex:t,kind:o.kind,success:!1,summary:`Operation ${o.kind} failed.`,error:e instanceof Error?e.message:"Unknown runtime error"}),n=e instanceof Error?e.message:"Unknown runtime error"}}let N={...l,operations:x};if(n)return{success:!1,receipts:p,restorePoint:c,executedPlan:N,error:`${n} No changes were applied.`};u.updatedAt=Date.now(),e.updateProject(u),j.length>0&&(0,eI.g_)(j);let C=y.zC.getState(),M={blocks:C.blocks,duration:C.duration,trackMeta:C.trackMeta};if(b.length>0){let e=y.zC.getState();for(let t of b)e.updateBlock(t.id,{start:t.start,...void 0!==t.duration?{duration:t.duration}:{},...void 0!==t.outOffset?{outOffset:t.outOffset}:{}})}if(k.length>0){let e=y.zC.getState();for(let t of k)for(let a of e.blocks){if("scene"===a.type){let r=t.sceneVolumes.get(a.sceneId);if(!r)continue;e.setBlockVolume(a.id,r.volume),e.setBlockMuted(a.id,r.muted);continue}if("audio"!==a.type&&"voiceover"!==a.type)continue;let r=t.audioVolumes.get(a.id)??t.audioVolumes.get(a.sceneId);void 0!==r&&(e.setBlockVolume(a.id,r),e.setBlockMuted(a.id,r<=0))}}S.size>0&&function(e,t){let a=y.zC.getState();for(let r of e){let e=t.filter(e=>e.sceneId===r);a.replaceCaptionBlocksForScene(r,e)}}(Array.from(S),u.captionBlocks??[]);let _=p.some(e=>!e.success);try{return await e.saveProject(u),{success:!_,receipts:p,restorePoint:c,updatedProject:u,executedPlan:N,error:_?"One or more plan operations could not be applied.":void 0,pendingGenerations:i,pendingRegenerations:s}}catch(t){return e.updateProject(c),y.zC.setState({blocks:M.blocks,duration:M.duration,trackMeta:M.trackMeta}),j.length>0&&(0,eI.s8)(j),{success:!1,receipts:p,restorePoint:c,executedPlan:N,error:t instanceof Error?t.message:"Failed to persist AI changes"}}}var ay=a(81715),av=a(14436),aw=a(84677),ak=a(65729),aS=a(98665),aj=a(20502);function aI(e){let t=new Map(e.map(e=>[e.id,e])),a=y.zC.getState(),r=!1,n=a.blocks.map(e=>{if("voiceover"!==e.type&&"audio"!==e.type)return e;let a=t.get(e.id);return!a||"number"!=typeof a.start||1e-6>Math.abs(e.start-a.start)?e:(r=!0,{...e,start:a.start})});r&&a.setBlocks(n)}function aN(e,t){return[...e.filter(e=>"caption"!==e.type),...t.map(e=>({...e,type:"caption"}))]}function aC(e,t){let a={...e??{}};return t?a.editorTail=t:delete a.editorTail,a}async function aM({currentProject:e,snapshot:t,updateProject:a,saveProject:r,isProjectCurrent:n,getCurrentProject:i}){if(t.id!==e.id||!n())throw Error("This AI checkpoint belongs to a different project.");let s={...t,masterTimelineZoomLevel:e.masterTimelineZoomLevel,masterTimelineViewportStart:e.masterTimelineViewportStart,masterTimelineLoopRegion:e.masterTimelineLoopRegion,masterPreviewSize:e.masterPreviewSize,masterPreviewLocked:e.masterPreviewLocked},o=new Set(s.scenes.map(e=>e.id)),l=new Set((0,eI.no)()),d=[...o].filter(e=>l.has(e)),c=e.scenes.filter(e=>!o.has(e.id)).map(e=>e.id),u=c.filter(e=>!l.has(e)),p=y.zC.getState(),m={blocks:p.blocks,duration:p.duration,trackMeta:p.trackMeta},h=i(),f=p;try{(0,eI.s8)([...o]),(0,eI.g_)(c),a(s),aI((s.audio?.length?s.audio:s.voiceovers)??[]),h=i(),f=y.zC.getState(),await r(s)}catch(r){let t=y.zC.getState();throw n()&&i()===h&&t.blocks===f.blocks&&t.trackMeta===f.trackMeta&&((0,eI.s8)(u),(0,eI.g_)(d),a(e),y.zC.setState(m)),r}}function a_({plan:e,review:t,onChange:a}){if(!t.entries.length)return null;let n=(t,r)=>a({...e,safeToApply:!1,operations:e.operations.map((e,a)=>a===t?{...e,...r}:e)});return(0,r.jsxs)("div",{className:"mt-2 space-y-2 rounded border border-white/10 p-2","data-testid":"ai-generation-review",children:[(0,r.jsx)("p",{children:"New generated clips are appended. Other listed edits are applied separately."}),t.entries.map(({operationIndex:t,spec:a,error:i})=>{let s=e.operations[t];return(0,r.jsxs)("div",{className:"space-y-1",children:[(0,r.jsxs)("p",{children:["Step ",t+1,": ",s.durationTarget??5,"s video"]}),(0,r.jsxs)("label",{className:"block",children:["Model",(0,r.jsxs)("select",{"aria-label":`Generation model for step ${t+1}`,value:s.videoModel??a?.videoModel??"",onChange:e=>n(t,{videoModel:e.target.value}),className:"ml-2 max-w-full rounded bg-zinc-900 p-1",children:[!a&&!s.videoModel&&(0,r.jsx)("option",{value:"",children:"Choose a model"}),tS.L4.map(({value:e,label:t})=>(0,r.jsx)("option",{value:e,children:t},e))]})]}),(0,r.jsxs)("label",{className:"block",children:["Quality",(0,r.jsx)("select",{"aria-label":`Generation quality for step ${t+1}`,value:s.videoQualityTier??a?.videoQualityTier??"360p",onChange:e=>n(t,{videoQualityTier:e.target.value}
73),className:"ml-2 rounded bg-zinc-900 p-1",children:tj.QR.map(({id:e})=>(0,r.jsx)("option",{value:e,children:e},e))})]}),a?.references.length?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("p",{children:["Reference images: ",a.references.map(e=>e.label).join(", ")]}),(0,r.jsx)("p",{children:"reference"===a.imageGuidanceMode?"Use their appearance; the opening may be restaged.":"Keep the first reference as the opening frame."})]}):!i&&(0,r.jsx)("p",{children:"Text-to-video: no source image will be sent."}),i&&(0,r.jsx)("p",{role:"alert",className:"text-amber-300",children:i})]},t)}),!t.blocked&&(0,r.jsxs)("p",{"data-testid":"ai-generation-credit-estimate",children:["Estimated generation cost: ",t.estimatedCredits," credits. Apply confirms these settings."]})]})}var aA=a(31084);function aE(e,t,a){let r=e=>{if(e.id!==t)return e;let r=!1,n=e.scenes.map(e=>e.id!==a.id||e.media?.status!=="generating"||e.generationJobId&&e.generationJobId!==a.generationJobId||e.generation?.prompt!==a.generation?.prompt||e.generationJobId===a.generationJobId&&a.media?.status==="generating"?e:(r=!0,{...e,url:a.url,media:{...a.media,trim:e.media.trim},generation:a.generation,generationJobId:a.generationJobId}));return r?{...e,scenes:n}:e},n=!1,i=e.map(e=>{let t=r(e.beforeProject),a=r(e.afterProject);return t===e.beforeProject&&a===e.afterProject?e:(n=!0,{...e,beforeProject:t,afterProject:a})});return n?i:e}let aT={segments:[],text:""};var a$=a(42818),aP=a(41823);function aD(e){return e.startsWith("mkt-transcript-")||e.startsWith("mkt-brand-")}function aR(e,t){return Math.min(e.start+e.duration,t.end)-Math.max(e.start,t.start)}function az(e,t,a=[]){return e.filter(e=>{if(!aD(e.id))return!1;let r=aR(e,t);return!(r<=.05)&&a.every(t=>r>=aR(e,t)-.05)})}function aL(e,t){return t.filter(t=>"voiceover"===t.type&&t.id!==e).map(e=>({start:e.start,end:e.start+Math.max(.1,e.duration)}))}function aF(e,t,a){let r=Math.round(100*Math.min(Math.max(0,Number.isFinite(t)?t:e.audioStart),"number"==typeof a&&Number.isFinite(a)&&a>e.footprintSeconds?Math.max(0,a-e.footprintSeconds):1/0))/100,n=r-e.audioStart;return{start:r,captionUpdates:e.captions.map(e=>({id:e.id,start:Math.max(0,Math.round((e.start+n)*100)/100)}))}}function aO(e){let t=e.trim();if(!t)return null;let a=t.match(/^(\d+):([0-5]?\d(?:\.\d+)?)$/);if(a)return 60*parseInt(a[1],10)+parseFloat(a[2]);if(!/^\d+(\.\d+)?$/.test(t))return null;let r=Number(t);return Number.isFinite(r)?r:null}function aB(e){let t=Math.round(10*(Number.isFinite(e)&&e>0?e:0)),a=Math.floor(t/600),r=t-600*a,n=Math.floor(r/10),i=r%10;return`${a}:${n.toString().padStart(2,"0")}${i>0?`.${i}`:""}`}var aW=a(60977);function aU({startSeconds:e,disabled:t,dragScaleSecondsPerPixel:a,onBegin:n,onPreview:s,onCommit:o,onCancel:l}){let[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(""),[m,h]=(0,i.useState)(!1),f=(0,i.useRef)(null),g=(0,i.useRef)(null),x=(0,i.useCallback)(()=>{f.current=null,h(!1),c(!1)},[]);(0,i.useEffect)(()=>{d&&(g.current?.focus(),g.current?.select())},[d]);let b=()=>{let t=aO(u);if(null===t||.005>Math.abs(t-e)){l(),x();return}o(t),x()},y=(0,i.useCallback)(()=>{l(),x()},[l,x]);return((0,i.useEffect)(()=>{if(!m)return;let e=e=>{"Escape"===e.key&&y()};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[m,y]),d)?(0,r.jsxs)("span",{className:"inline-flex items-center gap-1",children:[(0,r.jsx)("input",{ref:g,value:u,onChange:e=>p(e.target.value),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),b()):"Escape"===e.key&&(e.preventDefault(),y())},onBlur:()=>{f.current||b()},spellCheck:!1,"aria-label":"Beat start time",className:`w-14 rounded-md border px-1 py-0.5 text-[10px] font-medium tabular-nums outline-none transition-colors ${m?"border-emerald-400/60 bg-emerald-500/10 text-emerald-200":"border-emerald-500/40 bg-black/40 text-emerald-200 focus:border-emerald-400/70"}`}),(0,r.jsx)("button",{type:"button",onPointerDown:a=>{if(t)return;a.preventDefault();let r=aO(u)??e;f.current={pointerId:a.pointerId,startX:a.clientX,baseSeconds:r,lastAppliedSeconds:r,moved:!1};try{a.currentTarget.setPointerCapture(a.pointerId)}catch{}h(!0)},onPointerMove:e=>{let t=f.current;if(!t||e.pointerId!==t.pointerId)return;let r=s(Math.max(0,t.baseSeconds+(e.clientX-t.startX)*a));t.lastAppliedSeconds=r,t.moved=!0,p(aB(r))},onPointerUp:e=>{let t=f.current;if(t&&e.pointerId===t.pointerId){if(!t.moved){f.current=null,h(!1),g.current?.focus();return}o(t.lastAppliedSeconds),x()}},onPointerCancel:()=>{f.current&&y()},title:"Drag to move this beat and its captions on the timeline",className:`inline-flex h-5 w-6 shrink-0 touch-none items-center justify-center rounded-md border transition-colors ${m?"curs
73or-grabbing border-emerald-300/70 bg-emerald-400/30 text-emerald-100":"cursor-grab border-emerald-500/40 bg-emerald-500/15 text-emerald-300 hover:bg-emerald-500/25"}`,children:(0,r.jsx)(aW.A,{className:"h-3 w-3"})})]}):(0,r.jsx)("button",{type:"button",onClick:()=>{t||(n(),p(aB(e)),c(!0))},disabled:t,title:"Click to retime this beat - type a time or drag the green handle",className:"rounded px-0.5 text-[10px] font-medium tabular-nums text-zinc-600 transition-colors hover:bg-emerald-500/10 hover:text-emerald-300 disabled:opacity-50",children:aB(e)})}var aK=a(60234);function aV(e){return"object"==typeof e&&null!==e}var aH=a(50680),aq=a(65780),aY=a(51011);function aG({sceneCount:e,progress:t,onReveal:a,onCancel:n}){let s=!!a&&null!==t,o=(0,i.useRef)(!1),l="number"==typeof t?.percent?Math.max(0,Math.min(100,t.percent)):null,d=t?.eyebrow?.trim()||null,c=t?.title?.trim()||null,u=d===aY.n;if((0,i.useEffect)(()=>{!s||o.current||window.innerWidth>900||(o.current=!0,(0,ey.trackEvent)("faceless_watch_video_bar_seen",{scene_count:e,stage_eyebrow:d,stage_title:c,percent:null===l?void 0:Math.round(l)}))},[s,e,d,c,l]),!s)return null;let p=(()=>{let e=t?.title?.trim()??"";if(!e)return null;let a=t?.eyebrow?.trim()??"";return/^[a-z]/.test(e)&&a?`${a} ${e}`:e})();return(0,r.jsxs)("div",{className:"relative hidden w-full shrink-0 items-stretch overflow-hidden border-t border-[#2a2520] bg-[#141210] max-[900px]:flex",children:[(0,r.jsxs)("button",{type:"button",onClick:()=>{(0,ey.trackEvent)("faceless_watch_video_bar_clicked",{scene_count:e,stage_eyebrow:d,stage_title:c,percent:null===l?void 0:Math.round(l)}),a?.()},"data-testid":"faceless-mobile-watch-bar","aria-label":u?"Show the scenes to review the failed generation and retry":"Show the video preview and timeline - generation keeps running",className:"relative flex min-w-0 flex-1 items-center gap-3 px-4 py-2.5 text-left transition-colors active:bg-[#1b1815]",children:[null!==l&&!u&&(0,r.jsx)("span",{"aria-hidden":!0,className:"absolute inset-y-0 left-0 bg-[#c8a87c]/[0.07] transition-[width] duration-700",style:{width:`${l}%`}}),(0,r.jsx)("span",{className:`relative flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border ${u?"border-amber-500/30 bg-amber-500/[0.08]":"border-[#c8a87c]/20 bg-[#c8a87c]/[0.08]"}`,children:u?(0,r.jsx)(g.A,{"aria-hidden":!0,className:"h-4 w-4 text-amber-300"}):(0,r.jsx)("span",{className:"h-4 w-4 animate-spin rounded-full border-2 border-[#c8a87c]/25 border-t-[#f0d3a1]"})}),(0,r.jsxs)("span",{className:"relative min-w-0 flex-1",children:[(0,r.jsx)("span",{className:"block truncate text-[13px] font-semibold text-[#f1ece4]",children:u?"Generation hit a problem":"Watch your video build"}),(0,r.jsx)("span",{"aria-live":"polite",className:"block truncate text-[10.5px] leading-4 text-[#8a8580]",children:u?"No scenes were created. Tap to review and retry.":p??"Generation keeps running while you watch"})]}),null!==l&&!u&&(0,r.jsxs)("span",{className:"relative shrink-0 font-mono text-[11px] font-semibold tabular-nums text-[#f0d3a1]",children:[Math.round(l),"%"]}),(0,r.jsxs)("span",{className:"relative inline-flex shrink-0 items-center gap-1 rounded-md bg-white/[0.08] px-2 py-1 text-[10px] font-semibold text-[#f1ece4] ring-1 ring-white/10",children:["Show",(0,r.jsx)(tn.A,{className:"h-3 w-3"})]})]}),!u&&(0,r.jsx)("button",{type:"button",onClick:()=>{((0,ey.trackEvent)("faceless_generation_cancel_clicked",{source:"mobile_watch_bar",scene_count:e,stage_eyebrow:d,stage_title:c,percent:null===l?void 0:Math.round(l)}),n)?n():window.dispatchEvent(new CustomEvent("faceless:cancel-generation"))},"data-testid":"faceless-mobile-cancel-generation","aria-label":"Cancel generation",title:"Cancel generation",className:"relative m-2 ml-0 inline-flex w-9 shrink-0 items-center justify-center rounded-lg border border-red-400/25 bg-red-500/[0.08] text-red-200 transition-colors active:bg-red-500/20",children:(0,r.jsx)(H.A,{"aria-hidden":!0,className:"h-4 w-4"})})]})}function aX({sceneCount:e,progress:t,...a}){return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"flex-1 overflow-y-auto scrollbar-hidden","data-ai-rail-scroll-viewport":!0,children:(0,r.jsx)(aq.WP,{...a}
73)}),(0,r.jsx)(aG,{sceneCount:e,progress:t,onReveal:a.onMinimizePanel})]})}function aJ({activeTab:e,onSelect:t,editorActive:a,fullscreen:n=!1}){let s=(0,i.useRef)([]),o=[{key:"generate",label:"Video Studio",beta:!1,soon:!1},{key:"editor",label:"AI Editor",beta:!1,soon:!a},{key:"influencer",label:"Influencer",beta:!1,soon:!1},{key:"marketing",label:"Marketing Studio",beta:!0,soon:!1}];return(0,r.jsx)("div",{role:"tablist","aria-label":"AI workspace mode",className:`mt-2 flex overflow-x-auto rounded-lg border border-white/[0.07] bg-[#0f0f16] p-0.5 ${n?"mx-auto w-full max-w-3xl":""}`,children:o.map((a,n)=>(0,r.jsxs)("button",{ref:e=>{s.current[n]=e},type:"button",role:"tab","aria-selected":e===a.key,tabIndex:e===a.key?0:-1,"data-testid":`ai-workspace-tab-${a.key}`,onClick:()=>t(a.key),onKeyDown:e=>{let a="ArrowRight"===e.key?(n+1)%o.length:"ArrowLeft"===e.key?(n+o.length-1)%o.length:"Home"===e.key?0:"End"===e.key?o.length-1:null;null!==a&&(e.preventDefault(),s.current[a]?.focus(),t(o[a].key))},className:`min-w-0 flex-1 rounded-md px-1.5 py-2 text-center text-[10px] font-medium leading-tight transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-violet-300 ${e===a.key?"bg-white/10 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,children:[a.label,a.beta&&(0,r.jsx)("sup",{"aria-label":`${a.label} is in beta`,className:"ml-0.5 text-[7px] font-bold uppercase text-red-400",children:"Beta"}),a.soon&&(0,r.jsx)("sup",{"aria-label":`${a.label} is coming soon`,className:"ml-0.5 text-[7px] font-bold uppercase text-amber-300",children:"Soon"})]},a.key))})}var aZ=a(73321),aQ=a(88359),a0=a(2125),a1=a(54631),a5=a(78864),a2=a(8531),a4=a(92575);async function a3(e,t){let a=await (0,a4.fetchAPI)(e,t);if(a.error||!a.success)throw Error(a.error?.message||"Could not save creator details. Please try again.");let r=a.data;if(!r)throw Error("No creator details returned. Please try again.");return"object"==typeof r&&"data"in r?r.data:r}var a8=a(38038),a6=a(50046),a9=a(12304),a7=a(80503),re=a(81852),rt=a(64700),ra=a(80054);let rr="w-full min-w-0 rounded-lg border border-white/10 bg-black/20 px-3 py-2 text-xs text-zinc-100 outline-none placeholder:text-zinc-600 focus:border-violet-400/60 focus:ring-1 focus:ring-violet-400/30",rn="mb-1.5 block text-[11px] font-medium text-zinc-400";function ri({draft:e,profile:t,character:a,settings:n,change:i,disabled:s}){let o=n.find(t=>t.id===e.settingId);return(0,r.jsxs)("fieldset",{disabled:s,className:"min-w-0 space-y-4 disabled:opacity-60",children:[(0,r.jsx)("legend",{className:"mb-3 text-sm font-semibold text-zinc-100",children:"Your next video"}),(0,r.jsx)("div",{className:"grid gap-2",role:"group","aria-label":"Video format",children:re.L7.map(t=>(0,r.jsxs)("button",{type:"button","aria-pressed":e.format===t.id,onClick:()=>i({format:t.id}),"data-testid":`influencer-format-${t.id}`,className:`rounded-lg border px-3 py-2.5 text-left transition-colors ${e.format===t.id?"border-violet-400/50 bg-violet-400/10":"border-white/10 hover:bg-white/5"}`,children:[(0,r.jsx)("span",{className:"block text-xs font-medium text-zinc-200",children:t.label}),(0,r.jsx)("span",{className:"mt-1 block text-[11px] leading-4 text-zinc-500",children:t.description})]},t.id))}),(0,r.jsxs)("label",{className:"block",children:[(0,r.jsx)("span",{className:rn,children:"What is this video about?"}),(0,r.jsx)("textarea",{className:rr,rows:4,maxLength:4e3,value:e.brief,"data-testid":"influencer-brief",placeholder:"An idea, a story, a useful tipâ¦",onChange:e=>i({brief:e.target.value})})]}),!e.brief.trim()&&(0,r.jsx)("div",{className:"flex flex-wrap gap-1.5","aria-label":"Video idea starters",children:(0,re.pU)(t.niche).map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>i({brief:e.brief}),className:"rounded-full border border-white/10 px-2.5 py-1 text-[10px] text-zinc-400 hover:border-violet-400/40 hover:text-violet-200",children:e.label},e.label))}),(0,r.jsxs)("div",{className:"grid grid-cols-2 gap-3",children:[(0,r.jsxs)("label",{children:[(0,r.jsx)("span",{className:rn,children:"Length"}),(0,r.jsx)("select",{className:rr,value:e.durationSeconds,onChange:e=>i({durationSeconds:Number(e.target.value)}),children:[15,30,60].map(e=>(0,r.jsxs)("option",{value:e,children:[e," seconds"]},e))})]}),(0,r.jsxs)("label",{children:[(0,r.jsx)("span",{className:rn,children:"Outfit"}),(0,r.jsxs)("select",{className:rr,value:e.outfitId??"",onChange:e=>i({outfitId:e.target.value||null}),children:[(0,r.jsx)("option",{value:"",children:"Signature look"}),(a.outfits??[]).map(e=>(0,r.jsx)("option",{value:e.id,children:e.name},e.id))]})]})]}),(0,r.jsxs)("label",{className:"block",children:[(0,r.jsx)("span",{className:rn,children:"Saved setting"}),(0,r.jsxs)("select",{className:rr,value:e.settingId??"",onChange:e=>i({settingId:e.target.value||null,locationId:null}),children:[(0,r.jsx)("option",{value:"",children:"Let the brief set the scene"}),n.map(e=>(0,r.jsx)("option",{value:e.id,children:e.name},e.id))]})]}),!!o?.locations?.length&&(0,r.jsxs)("label",{className:"block",children:[(0,r.jsxs)("span",{className:rn,children:["Location within ",o.name]}),(0,r.jsxs)("select",{className:rr,value:e.locationId??"",onChange:e=>i({locationId:e.target.value||null}),children:[(0,r.jsx)("option",{value:"",children:"Choose scenes from this setting"}),o.locations.map(e=>(0,r.jsx)("option",{value:e.id,children:e.name},e.id))]})]}),"product"===e.format&&(0,r.jsxs)("div",{className:"space-y-3 rounded-lg border border-white/10 p-3",children:[(0,r.jsxs)("label",{className:"block",children:[(0,r.jsx)("span",{className:rn,children:"Product name"}),(0,r.jsx)("input",{className:rr,maxLength:120,value:e.productName,onChange:e=>i({productName:e.target.value})})]}),(0,r.jsxs)("label",{className:"block",children:[(0,r.jsx)("span",{className:rn,children:"Product facts to include"}),(0,r.jsx)("textarea",{className:rr,maxLength:1200,rows:3,value:e.productFacts,placeholder:"What it does, what to demonstrate, and the call to action.",onChange:e=>i({productFacts:e.target.value})})]})]})]})}function rs(e){let{data:t,status:a}=(0,e6.wV)();if("loading"===a)return(0,r.jsx)("p",{className:"p-4 text-xs text-zinc-400",children:"Loading your workspaceâ¦"});if("authenticated"!==a)return(0,r.jsxs)("div",{className:"space-y-3 p-5","data-testid":"influencer-sign-in",children:[(0,r.jsx)(aQ.A,{className:"h-7 w-7 text-violet-300"}),(0,r.jsx)("h2",{className:"text-base font-semibold text-zinc-100",children:"Meet your next creator"}),(0,r.jsx)("p",{className:"text-xs leading-5 text-zinc-400",children:"Create a character once, then make talking videos, lifestyle stories and product videos with them."}),(0,r.jsx)("button",{type:"button",className:"rounded-lg bg-violet-400/15 px-4 py-2 text-xs text-violet-200",onClick:()=>void(0,e6.Jv)(void 0,{callbackUrl:window.location.href}),children:"Sign in to choose your character"})]});let n=t?.user?.id??t?.user?.email??"authenticated";return(0,r.jsx)(ro,{...e},`${n}:${e.project.id}`)}function ro({project:e,onUpdateProject:t,onSaveProject:a,children:n,fullscreen:s,generationBusy:o}){let l=(0,aZ.useRouter)(),{entitlements:d}=(0,ay.G)(),{voices:c}=(0,eU.f)(),{draft:u,change:p,save:m,saveError:h}=function(e,t,a){let[r,n]=(0,i.useState)(()=>(0,re.sy)(e.influencerStudio)),[s,o]=(0,i.useState)(null),l=(0,i.useRef)(e);l.current=e;let d=(0,i.useRef)(r),c=(0,i.useRef)(null),u=(0,i.useRef)(!0),p=(0,i.useRef)({onUpdateProject:t,onSaveProject:a});p.current={onUpdateProject:t,onSaveProject:a};let m=(0,i.useCallback)(async()=>{c.current&&clearTimeout(c.current),c.current=null;try{await p.current.onSaveProject({...l.current,influencerStudio:d.current}),u.current&&o(null)}catch(e){throw u.current&&o("Your draft could not be saved. Try saving again."),e}},[]),h=(0,i.useCallback)((e,t)=>{let a=(0,re.sy)({...d.current,...e});d.current=a,n(a);let r={...l.current,...t,influencerStudio:a,updatedAt:Date.now()};
73return l.current=r,p.current.onUpdateProject(r),c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{m().catch(()=>void 0)},600),a},[m]);return(0,i.useEffect)(()=>(u.current=!0,()=>{u.current=!1,c.current&&(clearTimeout(c.current),c.current=null,p.current.onSaveProject().catch(()=>void 0))}),[m]),{draft:r,change:h,save:m,saveError:s}}(e,t,a),[f,g]=(0,i.useState)([]),[b,y]=(0,i.useState)([]),[w,k]=(0,i.useState)({}),[S,j]=(0,i.useState)({}),[I,N]=(0,i.useState)(!0),[C,M]=(0,i.useState)(null),[_,A]=(0,i.useState)(null),[E,T]=(0,i.useState)(!1),[$,P]=(0,i.useState)(!1),[D,R]=(0,i.useState)(0),[z,L]=(0,i.useState)(!1),F=(0,i.useRef)(!1),O=(0,i.useRef)(!0),[B,W]=(0,i.useState)(null),[U,K]=(0,i.useState)(null),V=(0,i.useRef)(null),H=f.find(e=>e.id===u.characterId)??null,q=(0,re.i2)(H?S[H.id]??w[H.id]:null),Y=!!(H&&S[H.id]),G=(0,re.z0)(e);(0,i.useEffect)(()=>(O.current=!0,()=>{O.current=!1}),[]),(0,i.useEffect)(()=>{let e=!1;return N(!0),M(null),T(!1),(0,a5.tl)().then(t=>{if(!e){if(t.error)throw Error("Could not load your characters.");g(t.data?.characters??[])}}).catch(()=>{e||M("Could not load your characters. Try again.")}).finally(()=>{e||N(!1)}),a3("/influencers/profiles",{method:"GET"}).then(t=>{e||(k(Object.fromEntries(t.profiles.map(e=>[e.characterId,(0,re.i2)(e)]))),T(!0),A(null))}).catch(()=>{e||A("Saved creator details are unavailable. Retry to load them.")}),(0,a2.IY)().then(t=>{e||t.error||y(t.data?.settings??[])}).catch(()=>void 0),()=>{e=!0}},[D]);let X=e=>{g(t=>[...t.filter(t=>t.id!==e.id),e]);let t=(0,re.i2)(w[e.id]);p({characterId:e.id,seed:null,...e.id!==u.characterId?{outfitId:null,format:t.defaultFormat,durationSeconds:t.defaultDurationSeconds}:{}}),P(!1),W(null),K(null)},J=async()=>{if(!H||!E)return;let e=H.id,t={...q,defaultFormat:u.format,defaultDurationSeconds:u.durationSeconds},a=await a3(`/influencers/profiles/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(t)});O.current&&(k(t=>({...t,[e]:(0,re.i2)(a)})),j(t=>{let a={...t};return delete a[e],a}),K("Creator details and format defaults saved."))},Z=async e=>{if(!F.current){F.current=!0,L(!0),W(null);try{await e()}catch(e){O.current&&W(e instanceof Error?e.message:"Something went wrong. Please try again.")}finally{F.current=!1,O.current&&L(!1)}}};return"studio"===u.stage?(0,r.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col","data-testid":"influencer-studio-ready",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2 border-b border-white/5 px-3 py-2",children:[(0,r.jsxs)("span",{className:"min-w-0 truncate text-[11px] text-violet-200",children:[u.seed?.character.name??"Current video"," \xb7 ",u.durationSeconds,"s"]}),(0,r.jsx)("button",{type:"button",disabled:z||o,onClick:()=>p({stage:"setup"}),className:"text-[11px] text-zinc-400 hover:text-zinc-100 disabled:opacity-40",children:"Creator setup"})]}),(B||h)&&(0,r.jsxs)("div",{role:"alert",className:"mx-3 my-2 rounded-lg border border-amber-400/25 bg-amber-400/5 p-3 text-xs text-amber-200",children:[B||h,h&&(0,r.jsx)("button",{type:"button",onClick:()=>void Z(m),className:"ml-2 underline",children:"Save again"})]}),u.seed&&e.influencerStudio?.seed?.id!==u.seed.id?(0,r.jsxs)("p",{role:"status",className:"flex items-center gap-2 p-4 text-xs text-zinc-400",children:[(0,r.jsx)(x.A,{size:13,className:"animate-spin"}),"Opening your prepared videoâ¦"]}):n]}):(0,r.jsx)("div",{className:"flex-1 overflow-y-auto scrollbar-hidden","data-ai-rail-scroll-viewport":!0,"data-testid":"influencer-studio-panel",children:(0,r.jsxs)("div",{className:`space-y-4 p-3 pb-6 ${s?"mx-auto w-full max-w-3xl":""}`,children:[(0,r.jsxs)("div",{className:"rounded-xl border border-violet-400/15 bg-violet-400/[0.04] p-4",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 text-violet-200",children:[(0,r.jsx)(aQ.A,{size:16}),(0,r.jsx)("h2",{className:"text-sm font-semibold",children:"One character. Your next video."})]}),(0,r.jsx)("p",{className:"mt-2 text-[11px] leading-5 text-zinc-400",children:"Keep their look and personality. Choose what they make next."})]}),(B||h)&&(0,r.jsxs)("div",{role:"alert",className:"rounded-lg border border-amber-400/25 bg-amber-400/5 p-3 text-xs text-amber-200",children:[B||h,h&&(0,r.jsx)("button",{type:"button",onClick:()=>void Z(m),className:"ml-2 underline",children:"Save again"})]}),!I&&(E||_)?C?(0,r.jsxs)("div",{role:"alert",className:"text-xs text-amber-200",children:[C,(0,r.jsx)("button",{className:"ml-2 underline",onClick:()=>R(e=>e+1),children:"Retry"})]}):(0,r.jsxs)(r.Fragment,{children:[H?(0,r.jsxs)("div",{className:"flex items-start gap-3 rounded-xl border border-white/10 p-3",children:[(0,a5.l_)(H)&&(0,r.jsx)("img",{src:(0,ex.$n)((0,a5.l_)(H)),alt:H.name,className:"h-24 w-16 rounded-lg object-cover object-top"}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsx)("h3",{className:"truncate text-sm font-semibold text-zinc-100",children:H.name}),(0,r.jsx)("p",{className:"mt-1 line-clamp-2 text-[11px] leading-4 text-zinc-500",children:H.personality||H.identityCard||"Your saved character"}),H.voice?.description&&(0,r.jsxs)("p",{className:"mt-1 text-[10px] text-zinc-500",children:["Voice: ",H.voice.description]}),(0,r.jsxs)("button",{type:"button",disabled:z||G,onClick:()=>P(e=>!e),className:"mt-2 text-[11px] text-violet-300 disabled:opacity-40",children:["Change or edit character ",(0,r.jsx)(tn.A,{size:11,className:"inline"})]})]})]}):(0,r.jsxs)("div",{className:"space-y-2",children:[u.characterId&&(0,r.jsx)("p",{className:"text-xs text-amber-200",children:"This character is no longer in your library. Choose another."}),f.length>0&&(0,r.jsxs)("label",{className:"block text-xs text-zinc-400",children:["Choose your character",(0,r.jsxs)("select",{"aria-label":"Choose your character",className:`${rr} mt-2`,value:"",onChange:e=>{let t=f.find(t=>
73t.id===e.target.value);t&&X(t)},children:[(0,r.jsx)("option",{value:"",children:"Select a saved character"}),f.map(e=>(0,r.jsx)("option",{value:e.id,children:e.name},e.id))]})]}),(0,r.jsxs)("button",{type:"button",onClick:()=>P(e=>!e),className:"flex w-full items-center justify-center gap-2 rounded-lg border border-dashed border-violet-300/25 p-3 text-xs text-violet-200",children:[(0,r.jsx)(a0.A,{size:14}),"Create or choose a character"]})]}),$&&(0,r.jsx)("div",{className:"rounded-xl border border-white/10 p-3","data-testid":"influencer-character-library",children:(0,r.jsx)(a1.p,{activeCharacterId:u.characterId,onApplyCharacter:X,onRemoveCharacterFromProject:()=>p({characterId:null,outfitId:null,seed:null}),isPaidTier:d.features.canUseAiEditor,onUpgradeRequired:W})}),G?(0,r.jsxs)("div",{className:"space-y-3 rounded-xl border border-white/10 p-3",children:[(0,r.jsx)("h3",{className:"text-sm text-zinc-200",children:"This project already has a video"}),(0,r.jsx)("p",{className:"text-xs leading-5 text-zinc-500",children:"Continue editing it, or start a fresh project with the same character. Your current scenes stay untouched."}),(0,r.jsx)("button",{type:"button",onClick:()=>p({stage:"studio",seed:u.seed}),className:"block w-full rounded-lg bg-white/5 p-2 text-xs text-zinc-200 disabled:opacity-40",children:"Continue video"}),(0,r.jsx)("button",{type:"button",disabled:z||o,onClick:()=>void Z(async()=>{await m();let t={...u,brief:"",stage:"setup",seed:null},a={title:`${H?.name??u.seed?.character.name??"Influencer"} â new video`,aspectRatio:e.aspectRatio,aiWorkspaceTab:"influencer",influencerStudio:t},r=await (0,a9.createProject)(a);if(r.error||!r.data?.id)throw Error("Could not create the new video. Please try again.");O.current&&l.push(`/projects/${r.data.id}`)}),className:"block w-full rounded-lg bg-violet-400/15 p-2 text-xs text-violet-200 disabled:opacity-40",children:"New video with this character"})]}):H&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("details",{className:"rounded-xl border border-white/10 p-3",children:[(0,r.jsxs)("summary",{className:"cursor-pointer text-xs font-medium text-zinc-300",children:["Creator details"," ",(0,r.jsx)("span",{className:"font-normal text-zinc-500",children:"\xb7 reused across videos"})]}),_&&(0,r.jsxs)("p",{role:"alert",className:"mt-2 text-xs text-amber-200",children:[_,(0,r.jsx)("button",{className:"ml-2 underline",onClick:()=>R(e=>e+1),children:"Retry"})]}),(0,r.jsxs)("fieldset",{disabled:z||!E,className:"mt-3 space-y-3 disabled:opacity-50",children:[[["niche","Niche","For example: home cooking",160],["audience","Audience","Who are they speaking to?",240],["tone","Speaking style","For example: warm, funny and direct",300],["contentPillars","Regular topics","What do they usually cover?",500]].map(([e,t,a,n])=>(0,r.jsxs)("label",{className:"block text-[11px] text-zinc-400",children:[t,(0,r.jsx)("input",{className:`${rr} mt-1.5`,value:q[e],placeholder:a,maxLength:n,onChange:t=>{var a;return a=t.target.value,void(H&&(j(t=>({...t,[H.id]:{...q,[e]:a}})),K(null)))}})]},e)),(0,r.jsx)("button",{type:"button",onClick:()=>void Z(J),className:"rounded-lg border border-white/10 px-3 py-2 text-[11px] text-zinc-300",children:"Save creator details"}),(0,r.jsx)("p",{role:"status",className:"text-[10px] text-zinc-500",children:U||(Y?"Unsaved creator details":"Saving also remembers the format and length selected below.")})]})]}),(0,r.jsx)(ri,{draft:u,profile:q,character:H,settings:b,change:p,disabled:z}),"product"===u.format&&(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between",children:[(0,r.jsx)("span",{className:"text-[11px] text-zinc-400",children:"Product photos \xb7 up to 3"}),(0,r.jsx)("button",{type:"button",onClick:()=>void Z(async()=>{let e=await a8.h.getProductProfile();if(O.current){if(!e.name&&!e.images.length)throw Error("No saved product yet. Add a name and photos here.");p({productName:e.name??"",productFacts:e.description??"",productImages:e.images.filter(e=>e.storageKey).slice(0,3).map(e=>({storageKey:e.storageKey,url:(0,ex.$n)(e.storageKey)}))})}}),disabled:z,className:"text-[10px] text-violet-300",children:"Use saved product"})]}),(0,r.jsx)("div",{className:"flex flex-wrap gap-2",children:u.productImages.map((e,t)=>(0,r.jsxs)("div",{className:"relative",children:[(0,r.jsx)("img",{src:(0,ex.$n)(e.storageKey),alt:`Product reference ${t+1}`,className:"h-16 w-16 rounded-lg object-cover"}),(0,r.jsx)("button",{type:"button","aria-label":`Remove product photo ${t+1}`,disabled:z,onClick:()=>p({productImages:u.productImages.filter((e,a)=>a!==t)}),className:"absolute right-0 top-0 rounded bg-black/80 px-1 text-white",children:"\xd7"})]},e.storageKey))}),(0,r.jsx)("input",{ref:V,hidden:!0,type:"file",multiple:!0,accept:"image/jpeg,image/png,image/webp",onChange:t=>{let a;a=t.target.files,Z(async()=>{let t=Array.from(a??[]).slice(0,3-u.productImages.length),r=[...u.productImages];for(let a of t){if(!["image/jpeg","image/png","image/webp"].includes(a.type)||a.size>0xa00000)throw Error("Use JPG, PNG or WebP product photos under 10 MB.");let t=await (0,a6.P)(a,e.id);if(t.error||!t.storageKey)throw Error("Could not upload the product photo. Please try again.");if(!O.current)return;r.push({storageKey:t.storageKey,url:(0,ex.$n)(t.storageKey)}),p({productImages:[...r]})}}),t.target.value=""}}),(0,r.jsx)("button",{type:"button",disabled:z||u.productImages.length>=3,onClick:()=>V.current?.click(),className:"rounded-lg border border-dashed border-white/15 px-3 py-2 text-[11px] text-zinc-400 disabled:opacity-40",children:"Add product photos"})]}),(0,r.jsxs)("button",{type:"button",onClick:()=>void Z(async()=>{let t;if(!H||G||o)return;let a=b.find(e=>e.id===u.settingId);if(u.settingId&&!a)throw Error("Choose an available setting first.");let r=a?(0,a7.YU)(a):null;if(a){let e=await (0,a2.wX)(a.id);if(e.error||!(r=(0,a7.B6)(e.data)))throw Error("Could not attach the setting. Please try again.")}if(Y&&E&&await J(),!O.current)return;let n=function(e,t,a,r,n,i,s){let o=(0,a5.l_)(a);if(!o)throw Error("Add a portrait to this character first.");if(!e.brief.trim())throw Error("Add an idea for this video.");if("product"===e.format&&!e.productName.trim())throw Error("Add the product name.");let l=a.outfits?.find(t=>
73t.id===e.outfitId);if(e.outfitId&&!l)throw Error("That outfit is no longer available. Choose another outfit.");let d=l?{...l,source:"preset"}:null,c=(0,ra.l3)(a,r),u=(0,rt.s$)([],a,d);if("product"===e.format){let t=[...new Map(i.map(e=>[e.storageKey,e])).values()].slice(0,3);u.push(...t.map((t,a)=>({id:`influencer-product-${a}`,kind:"style_or_props",role:"prop",enabled:!0,label:`${e.productName} reference ${a+1}`,prompt:`Keep ${e.productName} identical to this reference. ${e.productFacts}`,promptSource:"edited",userDescription:e.productName,asset:{id:`influencer-product-${a}`,type:"image",source:"uploaded",status:"ready",storageKey:t.storageKey,url:(0,ex.$n)(t.storageKey),label:e.productName}})))}let p=n?.areas.find(t=>t.id===e.locationId);if(e.locationId&&!p)throw Error("That location is no longer available. Choose another location.");return{id:s,prompt:(0,re.ad)(e,t,a,n,p),format:e.format,durationSeconds:e.durationSeconds,character:{id:a.id,name:a.name,identityCard:a.identityCard,personality:t.tone.trim()||a.personality,role:"main",heroKey:o,faceKey:(0,a5.Ay)(a),selectedOutfit:d,voice:c?{provider:c.provider,voiceId:c.voiceId}:null,voiceName:c?.label??null,soulId:"ready"===a.soulIdStatus?a.soulId:null},referenceContent:{enabled:!0,basePrompt:u[0]?.prompt??a.name,slots:u},world:n}}(u,q,H,c,r,u.productImages,(0,v.generateId)());p({seed:n,stage:"studio"},(t=e.facelessSettings,{facelessStoryboard:{...e.facelessStoryboard,storyPrompt:n.prompt,selectedTemplate:"custom"},facelessSettings:{...t,selectedTemplate:"custom",promptInputModeOverride:"idea",audioMode:"talking"===n.format?"characters":"voiceover",voiceSource:"app",visualMode:"talking"===n.format?"image":"video",imageModel:"gpt-image-2.5-flare",imageQuality:"low",..."talking"!==n.format?{videoModel:"seedance-2.5",videoProvider:"seedance"}:{},lengthMode:"auto",targetDurationSec:n.durationSeconds,useReferenceImage:!0,blueprintSettings:{...t?.blueprintSettings,voice:{...t?.blueprintSettings?.voice,...n.character.voice,enabled:!0}}}})),await m()}),disabled:z||o||!u.brief.trim()||!(0,a5.l_)(H)||"product"===u.format&&!u.productName.trim(),"data-testid":"influencer-prepare",className:"flex w-full items-center justify-center gap-2 rounded-xl bg-violet-400/15 px-4 py-3 text-sm font-semibold text-violet-100 ring-1 ring-violet-400/30 hover:bg-violet-400/25 disabled:cursor-not-allowed disabled:opacity-40",children:[z?(0,r.jsx)(x.A,{size:15,className:"animate-spin"}):(0,r.jsx)(td.A,{size:15}),"Prepare video"]}),(0,r.jsx)("p",{className:"text-center text-[10px] leading-4 text-zinc-500",children:"No generation credits spent yet. Review your setup and costs in the Studio before generating."})]})]}):(0,r.jsxs)("p",{role:"status",className:"flex items-center gap-2 p-2 text-xs text-zinc-400",children:[(0,r.jsx)(x.A,{size:13,className:"animate-spin"}),"Loading your charactersâ¦"]})]})})}var rl=a(88193),rd=a(94778);function rc(){let{entitlements:e}=(0,ay.G)(),t=e.features.canUseAiEditor,[a,n]=(0,i.useState)(null),[s,o]=(0,i.useState)(null);(0,i.useEffect)(()=>{n((0,rd.gQ)().character)},[]);let l=(0,i.useCallback)(e=>{let t=(0,rd.gQ)(),a=e&&t.clip?.characterId===e.id?t.clip:null;(0,rd.FW)({...t,character:e,clip:a}),n(e)},[]),d=(0,i.useCallback)(e=>{let t=(0,rd.Su)({id:e.id,name:e.name,heroKey:(0,a5.l_)(e),voice:e.voice??null});t?(o(null),l(t),(0,ey.trackEvent)("marketing_presenter_character_selected",{character_id:t.id,has_voice:!!t.geminiVoiceId,surface:"editor-rail"})):o("This character has no portrait yet - generate one below first.")},[l]);return(0,r.jsxs)("div",{className:"space-y-4","data-testid":"rail-product-studio",children:[(0,r.jsxs)("div",{className:"rounded-xl border border-white/[0.06] bg-[#0f0f16] p-3.5",children:[(0,r.jsxs)("div",{className:"flex items-stretch gap-2.5",children:[a?(0,r.jsx)("img",{src:(0,ex.$n)(a.heroKey),alt:a.name,className:"w-16 shrink-0 self-stretch rounded-lg border border-white/[0.08] object-cover object-top"}):(0,r.jsx)("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center self-start rounded-lg border border-white/[0.08] bg-white/[0.04] text-emerald-300/90",children:(0,r.jsx)(rl.A,{className:"h-4 w-4"})}),(0,r.jsxs)("div",{className:"min-w-0",children:[(0,r.jsx)("h3",{className:"text-[13px] font-semibold text-zinc-100",children:a?`${a.name} presents your product`:"Pick a presenter"}),(0,r.jsx)("p",{className:"mt-1 text-[11px] leading-5 text-zinc-500",children:a?"Record a demo and they open the video on camera with a lipsynced intro, then the demo rolls.":"Choose a character below (same library as Video Studio). They open your next recording on camera and narrate it."}),a&&(0,r.jsx)("button",{type:"button",onClick:()=>l(null),className:"mt-1 text-[11px] font-medium text-zinc-500 hover:text-zinc-300",children:"Clear selection"})]})]}),s&&(0,r.jsx)("p",{className:"mt-2 rounded-lg border border-amber-400/25 bg-amber-400/10 px-2.5 py-1.5 text-[11px] text-amber-100",children:s}),(0,r.jsxs)(e8(),{href:"/record?marketing=1&hook=character-presenter&aspect=9:16",onClick:()=>(0,ey.trackEvent)("marketing_presenter_record_clicked",{has_presenter:!!a,surface:"editor-rail"}),className:"group mt-3 flex w-full items-center justify-center gap-2 rounded-lg border border-emerald-400/30 bg-emerald-400/10 px-4 py-2.5 text-sm font-semibold text-emerald-100 transition-colors hover:border-emerald-400/50 hover:bg-emerald-400/20","data-testid":"rail-presenter-record-cta",children:[a?`Record with ${a.name}`:"Record product demo",(0,r.jsx)(td.A,{className:"h-3.5 w-3.5 transition-transform group-hover:translate-x-0.5"})]})]}),(0,r.jsx)("div",{className:"rounded-xl border border-white/[0.06] bg-[#0f0f16] p-3","data-testid":"rail-product-studio-characters",children:(0,r.jsx)(a1.p,{activeCharacterId:a?.id??null,onApplyCharacter:d,onRemoveCharacterFromProject:()=>l(null),onUpgradeRequired:e=>o(e),isPaidTier:t})})]})}var ru=a(59370);function rp({collapsed:e,compact:t,onToggleCollapsed:a,hasPlan:n,statusClassName:i,progress:s,children:o}){return(0,r.jsxs)(r.Fragment,{children:[e&&!t&&(0,r.jsxs)("button",{type:"button",onClick:a,title:s?`${s.title} - open panel`:n?"A plan is waiting for review - open AI panel":"Open AI panel","aria-label":"Open AI panel",className:"group relative h-full w-full border-l border-white/[0.06] bg-[#0c0c11] flex flex-col items-center pt-3 gap-3 transition-colors hover:bg-white/[0.03]",children:[n&&(0,r.jsx)("span",{className:"absolute inset-y-0 left-0 w-[2px] bg-amber-400/80"}),(0,r.jsx)("span",{className:"p-1.5 rounded text-zinc-500 transition-colors group-hover:bg-white/[0.06] group-hover:text-zinc-300",children:(0,r.jsx)(B.A,{className:"h-3.5 w-3.5"})}),(0,r.jsx)(tc.A,{size:14,className:n?"text-amber-400":i}
73),(0,r.jsxs)("span",{"aria-hidden":!0,className:"flex flex-col items-center text-[9px] font-bold leading-[10px] tracking-widest text-zinc-500 transition-colors group-hover:text-zinc-300",children:[(0,r.jsx)("span",{children:"A"}),(0,r.jsx)("span",{children:"I"})]}),s&&(0,r.jsxs)("span",{className:"flex flex-col items-center gap-1.5","data-testid":"ai-rail-collapsed-progress",children:[(0,r.jsx)("span",{className:"h-2.5 w-2.5 animate-spin rounded-full border-2 border-[#c8a87c]/25 border-t-[#f0d3a1]"}),"number"==typeof s.percent&&(0,r.jsxs)("span",{className:"font-mono text-[9px] font-semibold tabular-nums text-[#f0d3a1]",children:[Math.round(s.percent),"%"]})]})]}),(0,r.jsx)("div",{"data-testid":"ai-rail-body","aria-hidden":e,className:"h-full w-full min-h-0 min-w-0 flex-col border-l border-white/[0.06] bg-[#0c0c11] text-zinc-100",style:{display:e?"none":"flex"},children:o})]})}function rm(e){return"editor"===e||"influencer"===e||"marketing"===e?e:"generate"}function rh(e){return"editor"===e&&d.Wg.AI_EDITOR_ACTIVE?"editor":"marketing"===e?"marketing":"generate"}function rf(e){let t=e=>Array.isArray(e)&&e.some(e=>e?.type==="voiceover"&&"string"==typeof e.id&&e.id.startsWith("marketing-vo"));return!!(e&&(t(e.audio)||t(e.voiceovers)))}function rg(e){let t="number"==typeof e.inOffset&&"number"==typeof e.outOffset?e.outOffset-e.inOffset:0;return Number.isFinite(t)&&t>.05?t:"number"==typeof e.duration&&e.duration>0?e.duration:.1}function rx(){return y.zC.getState().blocks.filter(e=>"caption"===e.type).map(e=>({id:e.id,sourceCaptionId:e.sourceCaptionId,start:e.start,duration:e.duration,inOffset:e.inOffset,outOffset:e.outOffset,fullDuration:e.fullDuration,trackId:e.trackId,sceneId:e.sceneId,captionText:e.captionText,captionBox:e.captionBox,captionStyle:e.captionStyle,captionHighlightEnabled:e.captionHighlightEnabled,captionHighlightStyle:e.captionHighlightStyle,captionWords:e.captionWords??void 0,captionCues:e.captionCues??void 0,captionDisplayMode:e.captionDisplayMode,captionDisplayWindowSize:e.captionDisplayWindowSize,alignmentProvider:e.alignmentProvider,source:e.source??"auto"}))}async function rb(e,t,a,r){try{let n=y.zC.getState(),i=n.blocks.filter(e=>"caption"===e.type),s=rg(e),o=az(i,{start:e.start,end:e.start+Math.max(.1,s)},aL(e.id,n.blocks)),l="pending"===e.status||"error"===e.status,d=0===o.length&&l&&!!r?.sceneId;if(0===o.length&&!d)return null;let c={startSeconds:t.block.start,desiredStartSeconds:t.block.start,playableSeconds:Math.max(.4,rg(t.block)),take:t.take};try{[c]=await (0,a$.Di)([c],a)}catch{}let u=function(e){let t=e.oldCaptions.find(e=>e.sceneId),a=t?.sceneId?{sceneId:t.sceneId,trackId:t.trackId}:e.fallbackAnchor?.sceneId?{sceneId:e.fallbackAnchor.sceneId,trackId:e.fallbackAnchor.trackId??aP.YW}:null;if(!a)return null;let r=e.clip.startSeconds+Math.max(.4,e.clip.playableSeconds),n=Number.isFinite(e.timelineDurationSeconds)&&e.timelineDurationSeconds>=r?e.timelineDurationSeconds:r+1,i=e.allCaptionBlocks.filter(e=>{var t;return(t=e.id).startsWith("mkt-hook")||t.startsWith("mkt-cta")}).map(e=>({start:e.start,end:e.start+e.duration}));return(0,aP.BG)([e.clip],{sceneId:a.sceneId,durationSeconds:n,trackId:a.trackId,productName:null,reservedWindows:i,...e.orientation?{orientation:e.orientation}:{}})}({clip:{startSeconds:c.startSeconds,playableSeconds:c.playableSeconds,take:{script:c.take.script,durationSeconds:c.take.durationSeconds},...c.wordTimings?{wordTimings:c.wordTimings}:{}},oldCaptions:o,allCaptionBlocks:i,timelineDurationSeconds:n.duration,...d&&r?{fallbackAnchor:{sceneId:r.sceneId},orientation:r.orientation}:{}});if(!u||0===u.length)return null;return d&&a("Beat captions built fresh (interrupted handoff - none existed to replace)",{blocks:u.length}),{removeIds:o.map(e=>e.id),add:u}}catch(e){return a("Beat caption rebuild skipped",e?.message),null}}let ry="ai-editor-chat",rv="ai-editor-checkpoints",rw="ai-editor-planning-mode",rk=2/30,rS=new Set(["trim_clip","move_clip","duplicate_clip","split_clip","remove_segments","delete_clip","add_audio_item","update_audio_timing","set_volume","trim_scene","generate_captions","replace_captions","style_captions","apply_scene_effect","apply_transition","cut_silence","cut_quiet_sections","isolate_speech","analyze_beats","create_montage","create_action_edit","cut_on_beat","set_keyframes","apply_animation","duck_audio","generate_scene_visual","regenerate_scene_visual","regenerate_scene_voiceover","regenerate_voiceover_beat"]),rj=new Set(["analyze_beats","create_action_edit"]);function rI(e){return!(!rS.has(e)||!d.Wg.AI_EDITOR_ADVANCED_ENABLED&&rj.has(e))}function rN(e){if(!rI(e.kind))return{executable:!1};if("trim_scene"===e.kind){let t=e=>"number"==typeof e&&Number.isFinite(e)?e:0,a=t(e.trimStartBySeconds),r=t(e.trimEndBySeconds);if(a<=1e-4&&r<=1e-4)return{executable:!1,reason:"needs a trim amount. Tell me how many seconds to trim from the start or end."}}return{executable:!0}}let rC={scene_visual:"faceless:regenerate-scene-by-nle",scene_voiceover:"faceless:regenerate-voiceover-by-nle"},rM=[{value:"auto_apply",label:"Auto-apply"},{value:"preview_first",label:"Preview first"}],r_=[{value:"",label:"Auto (recommended)"},{value:"gpt-5.5",label:"Highest quality â gpt-5.5"},{value:"gpt-5.4",label:"Balanced â gpt-5.4"},{value:"gpt-5.4-mini",label:"Fast â gpt-5.4-mini"},{value:"gpt-5.4-nano",label:"Fastest â gpt-5.4-nano"},{value:"gpt-4.1-mini",label:"Compact â gpt-4.1-mini"}],rA=["Paste one content URL per line.","Add captions after importing your clips.","Generate a voiceover once scenes are imported."],r
73E="Generate a video of a unicorn galloping across Mars.",rT={queued:"bg-zinc-500",thinking:"bg-blue-400",planning:"bg-blue-400",planned:"bg-blue-500",applying:"bg-blue-400",applied:"bg-blue-500",failed:"bg-red-400"};function r$(e,t){let a=t?.sceneLabel;if("done"===e.outcome)return{stage:"applied",text:a?`Voiceover on ${a} re-rendered.`:"Voiceover beat re-rendered and captions rebuilt."};let r=a?`The voiceover on ${a}`:"The voiceover beat";return"skipped"===e.outcome?{stage:"failed",text:`${r} was not re-rendered â ${e.reason??"the regeneration was skipped"}.`}:{stage:"failed",text:`${r} failed to re-render${e.reason?` (${e.reason})`:""} â see the beat card to retry.`}}let rP={trim_clip:{icon:"cut",verb:"Trim clip"},trim_scene:{icon:"cut",verb:"Trim"},move_clip:{icon:"motion",verb:"Move clip"},duplicate_clip:{icon:"motion",verb:"Duplicate clip"},split_clip:{icon:"cut",verb:"Split clip"},remove_segments:{icon:"cut",verb:"Remove segments"},delete_clip:{icon:"cut",verb:"Delete clip"},add_audio_item:{icon:"audio",verb:"Add audio"},update_audio_timing:{icon:"audio",verb:"Retime audio"},set_volume:{icon:"audio",verb:"Set volume"},duck_audio:{icon:"audio",verb:"Duck music under speech"},generate_captions:{icon:"captions",verb:"Generate captions"},replace_captions:{icon:"captions",verb:"Replace captions"},style_captions:{icon:"captions",verb:"Restyle captions"},apply_scene_effect:{icon:"effect",verb:"Apply effect"},apply_transition:{icon:"transition",verb:"Add transition"},set_keyframes:{icon:"motion",verb:"Animate"},apply_animation:{icon:"motion",verb:"Animate"},cut_silence:{icon:"cut",verb:"Cut silence"},cut_quiet_sections:{icon:"cut",verb:"Cut quiet sections"},isolate_speech:{icon:"voice",verb:"Keep speech only"},analyze_beats:{icon:"audio",verb:"Analyze beats"},cut_on_beat:{icon:"cut",verb:"Cut on the beat"},create_montage:{icon:"visual",verb:"Create montage"},create_action_edit:{icon:"visual",verb:"Create action edit"},generate_scene_visual:{icon:"visual",verb:"Generate scene visual"},regenerate_scene_visual:{icon:"visual",verb:"Regenerate scene visual"},regenerate_scene_voiceover:{icon:"voice",verb:"Regenerate voiceover"},regenerate_voiceover_beat:{icon:"voice",verb:"Redo voiceover beat"},unsupported:{icon:"other",verb:"Unsupported step"}};function rD(e){return e.replace(/[_-]+/g," ").trim().toLowerCase()}function rR(e,t){let a="string"==typeof e.kind?e.kind:"unsupported",r=rP[a]??{icon:"other",verb:rD(a).replace(/^./,e=>e.toUpperCase())},n=r.verb;if("apply_scene_effect"===a){let t="string"==typeof e.effect?.type?e.effect.type:e.parameterName;"string"==typeof t&&t&&(n=`Apply ${rD(t)}`)}else"apply_transition"===a&&"string"==typeof e.transition?.type&&(n=`Add ${rD(e.transition.type)} transition`);let i=e=>{let a=t.get(e);return"number"==typeof a?`Scene ${a}`:"a scene"},s=null;if("string"==typeof e.sceneId&&e.sceneId)s=i(e.sceneId);else if(rW(e.scope)){let t=e.scope;"scene_ids"===t.type&&Array.isArray(t.sceneIds)&&t.sceneIds.length>0?s=1===t.sceneIds.length&&"string"==typeof t.sceneIds[0]?i(t.sceneIds[0]):`${t.sceneIds.length} scenes`:"track"===t.type?s="number"==typeof t.trackId?`Track ${t.trackId}`:"one track":"all"===t.type?s="whole video":"selected"===t.type&&(s="selected scenes")}return{icon:r.icon,verb:n,target:s}}let rz={explicit:"you named it",selected:"you had it selected",context_last_scene:"your last edited scene",context_same_effect:"continuing your earlier edit",context_same_family:"like your earlier edit"},rL=/^Effect '(.+?)' matched '(.+?)' with (\d+)% confidence\./;function rF(e,t){let a=[],r=e.resolvedSceneTarget;if(r&&"number"==typeof r.sceneNumber&&r.sceneNumber>0){let e=rz[r.resolution];a.push(e?`Target: scene ${r.sceneNumber} (${e})`:`Target: scene ${r.sceneNumber}`)}for(let t of e.warnings??[]){if("string"!=typeof t)continue;let e=t.match(rL);if(e){a.push(`Effect: ${e[2]} (${e[3]}% match)`);break}}return 0===a.length?null:(a.push(t?.autoApplied?"auto-applied â safe single-scene edit":e.safeToApply?"preview first":"preview â creative/multi-scene edit"),a.join(" \xb7 "))}function rO(e){if(!e)return null;let t=e.trim();return t?t.length<=14?t:`${t.slice(0,8)}...${t.slice(-4)}`:null}let rB=/^(?:please\s+)?(?:can\s+you\s+)?(?:undo|revert|un-do)(?:\s+(?:that|this|it|last|the\s+last(?:\s+(?:edit|change|thing))?|my\s+last\s+(?:edit|change)|the\s+previous\s+(?:edit|change)))?(?:\s*,?\s*please)?\s*[.!?]*$/i;function rW(e){return"object"==typeof e&&null!==e}function rU(e){let t=e.planJson;if(!rW(t)||"string"!=typeof t.id||"string"!=typeof t.assistantMessage||"string"!=typeof t.summary||!Array.isArray(t.operations)||!Array.isArray(t.warnings)||"boolean"!=typeof t.safeToApply)return null;let a=rW(t.estimatedImpact)?{scenesTouched:"number"==typeof t.estimatedImpact.scenesTouched?t.estimatedImpact.scenesTouched:0,blocksTouched:"number"==typeof t.estimatedImpact.blocksTouched?t.estimatedImpact.blocksTouched:0,estimatedDurationDeltaSeconds:"number"==typeof t.estimatedImpact.estimatedDurationDeltaSeconds?t.estimatedImpact.estimatedDurationDeltaSeconds:0}:{scenesTouched:0,blocksTouched:0,estimatedDurationDeltaSeconds:0},r=rW(t.resolvedSceneTarget)?{sceneId:"string"==typeof t.resolvedSceneTarget.sceneId?t.resolvedSceneTarget.sceneId:void 0,sceneNumber:"number"==typeof t.resolvedSceneTarget.sceneNumber?t.resolvedSceneTarget.sceneNumber:void 0,resolution:"string"==typeof t.resolvedSceneTarget.resolution?t.resolvedSceneTarget.resolution:void 0,confidence:"string"==typeof t.resolvedSceneTarget.confidence?t.resolvedSceneTarget.confidence:void 0}:null;return{id:t.id,assistantMessage:t.assistantMessage,summary:t.summary,operations:t.operations,warnings:t.warnings.filter(e=>"string"==typeof e),estimatedImpact:a,safeToApply:t.safeToApply,resolvedSceneTarget:r&&r.sceneId&&r.resolution&&r.confidence?{sceneId:r.sce
73neId,sceneNumber:r.sceneNumber,resolution:r.resolution,confidence:r.confidence}:void 0}}function rK(e){let t=e.filter(e=>!e.isAudioBlock).sort((e,t)=>(e.timelineStart??0)-(t.timelineStart??0));return{orderedScenes:t,numberById:new Map(t.map((e,t)=>[e.id,t+1]))}}let rV=new Set(["apply_scene_effect","apply_transition","trim_scene","set_keyframes"]);function rH(e,{messageId:t,receipts:a,status:r,mode:n,requestId:i,idempotencyKey:s,idempotencyReplay:o}){let l=Date.now();return{id:e.id,messageId:t,planId:e.id,requestId:i,idempotencyKey:s,idempotencyReplay:o??null,planJson:e,receiptsJson:a??[],resolvedTargetJson:e.resolvedSceneTarget?e.resolvedSceneTarget:null,status:r,mode:n,createdAt:l,updatedAt:l}}var rq=a(55420),rY=a(76960),rG=a(84614),rX=a(61491),rJ=a(28617),rZ=a(24650),rQ=a(39979);function r0(){return(0,r.jsxs)("span",{"aria-hidden":!0,className:"inline-flex",children:[(0,r.jsx)("span",{className:"animate-pulse",children:"."}),(0,r.jsx)("span",{className:"animate-pulse",style:{animationDelay:"0.25s"},children:"."}),(0,r.jsx)("span",{className:"animate-pulse",style:{animationDelay:"0.5s"},children:"."})]})}let r1=[{label:"Trim scene 1",prompt:"Trim the first two seconds of scene 1"},{label:"Caption every scene",prompt:"Add captions to every scene"},{label:"Voice scene 1",prompt:"Generate a voiceover for scene 1"},{label:"Slow zoom on scene 1",prompt:"Apply a slow zoom to scene 1"}];function r5({fullscreen:e,onPickPrompt:t}){return(0,r.jsxs)("div",{"data-testid":"ai-rail-empty-state",className:"pt-1",children:[(0,r.jsx)("p",{className:`font-semibold text-zinc-100 ${e?"text-[15px]":"text-[13px]"}`,children:"Try an edit"}),(0,r.jsx)("div",{className:"mt-2 flex flex-wrap gap-1.5",children:r1.map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>t(e.prompt),"data-testid":"ai-rail-capability-card",title:e.prompt,className:"rounded-md border border-white/[0.07] bg-white/[0.02] px-2.5 py-1.5 text-[11px] text-zinc-300 transition-colors hover:border-blue-400/30 hover:bg-blue-500/[0.06] hover:text-blue-100",children:e.label},e.label))}),(0,r.jsx)("p",{className:"mt-2.5 text-[10px] leading-4 text-zinc-600",children:"Review changes before applying them."})]})}function r2({chips:e,disabled:t,onPick:a}){return 0===e.length?null:(0,r.jsx)("div",{"data-testid":"ai-composer-chip-bar",className:"mb-1.5 flex items-center gap-1.5 overflow-x-auto pb-0.5 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:e.map(e=>(0,r.jsx)("button",{type:"button",disabled:t,onClick:()=>a(e),"data-testid":`ai-chip-${e.slug}`,title:e.prompt,className:"shrink-0 whitespace-nowrap rounded-full border border-white/[0.1] bg-white/[0.03] px-2.5 py-1 text-[11px] text-zinc-400 transition-colors hover:border-white/[0.22] hover:bg-white/[0.07] hover:text-zinc-200 disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-white/[0.1] disabled:hover:bg-white/[0.03] disabled:hover:text-zinc-400",children:e.label},e.slug))})}function r4({text:e}){return e?(0,r.jsx)("p",{"data-testid":"ai-plan-resolution-line",title:e,className:"mt-1 truncate text-[10px] leading-4 text-zinc-500",children:e}):null}let r3={cut:rq.A,captions:rY.A,audio:rG.A,effect:rX.A,transition:rJ.A,motion:rZ.A,visual:rQ.A,voice:ts.A,other:k.A};function r8({operations:e,sceneNumberById:t}){if(0===e.length)return null;let a=e.slice(0,6);return(0,r.jsxs)("ol",{className:"mt-2 space-y-1","data-testid":"ai-plan-step-list",children:[a.map((e,a)=>{let n=rR(e,t),i=r3[n.icon];return(0,r.jsxs)("li",{className:"flex min-w-0 items-center gap-1.5 text-[11px] text-zinc-300",children:[(0,r.jsx)(i,{size:11,className:"shrink-0 text-amber-300/80"}),(0,r.jsxs)("span",{className:"min-w-0 truncate",children:[n.verb,n.target&&(0,r.jsxs)("span",{className:"text-zinc-500",children:[" \xb7 ",n.target]})]})]},`${e.kind}-${a}`)}),e.length>6&&(0,r.jsxs)("li",{className:"pl-[17px] text-[10px] text-zinc-500",children:["+",e.length-6," more steps"]})]})}function r6({label:e,planSummary:t,statusText:a,isLatest:n,isActive:i,autoApplied:s,targetSceneLabel:o,resolutionText:l,applying:d,showUndoRestore:c,onUnapply:u,onReapply:p,onUndoRestore:m,onRestore:h}){let f="inline-flex h-7 items-center rounded-md border border-amber-500/30 bg-amber-500/15 px-2.5 text-[11px] font-medium text-amber-300 transition-colors hover:bg-amber-500/25 disabled:opacity-50";return(0,r.jsxs)("div",{className:`rounded-md border p-2 text-[11px] ${n?"border-amber-500/15 bg-amber-500/[0.03]":"border-zinc-600/25 bg-zinc-600/[0.04]"}`,children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,r.jsx)("span",{className:`text-[10px] font-semibold uppercase tracking-wide ${n?"text-amber-400":"text-zinc-400"}`,children:e}),(0,r.jsx)("span",{className:i?n?"text-amber-400":"text-blue-400":"text-zinc-500",children:i?"active":a})]}),(0,r.jsx)("div",{className:"mt-1 text-[11px] text-zinc-300",children:t}),(0,r.jsx)(r4,{text:l}),(0,r.jsxs)("div",{className:"mt-1 text-[10px] text-zinc-500",children:[s?"auto-applied":"manual apply",o?` \xb7 ${o}`:""]}),(0,r.jsx)("div",{className:"mt-2 flex gap-2",children:n?(0,r.jsx)("button",{type:"button",onClick:i?u:p,disabled:d,className:f,children:i?"Unapply":"Reapply"}):c?(0,r.jsx)("button",{type:"button",onClick:m,disabled:d,className:f,children:"Undo restore"}):(0,r.jsx)("button",{type:"button",onClick:h,disabled:d,className:"inline-flex h-7 items-center rounded-md border border-white/[0.08] px-2.5 text-[11px] text-zinc-400 transition-colors hover:bg-white/[0.06] hover:text-zinc-200 disabled:opacity-50",children:"Restore to here"})})]})}function r9({entries:e,summaryText:t,detailsOpen:a,onToggleDetails:n}){let i=e.length>0?e[e.length-1]:null;return(0,r.jsxs)("div",{className:"rounded-md border border-white/[0.08] bg-[#111119] px-3 py-2","data-testid":"ai-execution-feed",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,r.jsxs)("div",{className:"flex min-w-0 items-center gap-1.5 text-[11px] text-zinc-300",children:[i&&(0,r.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${rT[i.stage]}`}),(0,r.jsx)("span",{className:"min-w-0 truncate",children:t})]}),(0,r.jsxs)("button",{type:"button",onClick:n,className:"flex shrink-0 items-center gap-0.5 text-[10px] text-zinc-500 transition-colors hover:text-zinc-300","aria-label":a?"Hide execution details":"Show execution details","aria-expanded":a,children:[(0,r.jsx)(W.A,{size:10,
73className:`transition-transform ${a?"rotate-90":""}`}),"Details"]})]}),a&&(0,r.jsx)("div",{className:"mt-1.5 space-y-1",children:e.length>0?e.slice(-8).map(e=>(0,r.jsxs)("div",{className:"flex min-w-0 items-start gap-1.5 text-[10px] leading-relaxed",children:[(0,r.jsx)("span",{className:`mt-[4px] h-1.5 w-1.5 shrink-0 rounded-full ${rT[e.stage]}`}),(0,r.jsx)("span",{className:"min-w-[52px] shrink-0 uppercase text-zinc-500",children:e.stage}),(0,r.jsx)("span",{className:"min-w-0 break-words text-zinc-300",children:e.text})]},e.id)):(0,r.jsx)("div",{className:"text-[10px] text-zinc-500",children:"Waiting for the next AI request."})})]})}function r7({planningMode:e,onChangePlanningMode:t,plannerModel:a,onChangePlannerModel:n,onClose:s,fullscreen:o}){let[l,d]=(0,i.useState)(""!==a);return(0,r.jsx)("div",{className:"border-b border-white/[0.06] bg-[#0e0e14] px-3 py-3",children:(0,r.jsxs)("div",{className:o?"mx-auto w-full max-w-3xl":"",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,r.jsx)("span",{className:"text-[10px] font-semibold uppercase tracking-[0.16em] text-zinc-400",children:"AI settings"}),(0,r.jsx)("button",{type:"button",onClick:s,"aria-label":"Close AI settings",className:"rounded p-1 text-zinc-500 transition-colors hover:bg-white/[0.06] hover:text-zinc-300",children:(0,r.jsx)(H.A,{size:12})})]}),(0,r.jsx)("div",{role:"radiogroup","aria-label":"Planning mode",className:"mt-2 flex rounded-lg border border-white/[0.07] bg-[#0f0f16] p-0.5",children:rM.map(a=>{let n=e===a.value;return(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":n,onClick:()=>
73t(a.value),className:`flex-1 rounded-md px-2.5 py-1.5 text-center text-[11px] font-medium transition-colors ${n?"bg-white/10 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,children:a.label},a.value)})}),(0,r.jsx)("p",{className:"mt-1.5 text-[11px] leading-4 text-zinc-500",children:"preview_first"===e?"Every plan shows a preview; nothing changes until you click Apply. Changes take effect immediately.":"Safe plans are auto-applied immediately (checkpoints let you unapply); plans with unresolved warnings still show a preview first. Changes take effect immediately."}),(0,r.jsxs)("button",{type:"button",onClick:()=>d(e=>!e),"aria-expanded":l,className:"mt-3 flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wide text-zinc-500 transition-colors hover:text-zinc-300",children:[(0,r.jsx)(W.A,{size:10,className:`transition-transform ${l?"rotate-90":""}`}),"Advanced"]}),l&&(0,r.jsxs)("div",{className:"mt-2",children:[(0,r.jsx)("label",{htmlFor:"ai-rail-planner-model",className:"mb-1.5 block text-[10px] uppercase tracking-wide text-zinc-400",children:"Planner model (this session)"}),(0,r.jsxs)("div",{className:"relative",children:[(0,r.jsx)("select",{id:"ai-rail-planner-model",value:a,onChange:e=>n(e.target.value),className:"w-full appearance-none rounded-md border border-white/[0.08] bg-[#16161e] px-2.5 py-1.5 pr-8 text-xs text-zinc-200 focus:border-white/20 focus:outline-none",children:r_.map(e=>(0,r.jsx)("option",{value:e.value,children:e.label},e.value||"default"))}),(0,r.jsx)(tn.A,{size:12,className:"pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-zinc-500"})]})]})]})})}function ne({message:e,canRetry:t,onRetry:a,onDismiss:n}){return(0,r.jsx)("div",{className:"border-t border-red-500/20 bg-red-500/[0.06] px-3 py-2.5","data-testid":"ai-rail-error-card",children:(0,r.jsxs)("div",{className:"flex items-start gap-2",children:[(0,r.jsx)(g.A,{size:13,className:"mt-px shrink-0 text-red-400"}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsx)("p",{className:"text-[11px] font-semibold text-red-200",children:"Something went wrong"}),(0,r.jsx)("p",{className:"mt-0.5 break-words text-[11px] leading-4 text-red-300/85",children:e})]}),(0,r.jsxs)("div",{className:"flex shrink-0 items-center gap-1",children:[t&&(0,r.jsx)("button",{type:"button",onClick:a,"data-testid":"ai-rail-error-retry",className:"inline-flex h-6 items-center rounded-md border border-red-400/30 bg-red-400/10 px-2 text-[10px] font-medium text-red-200 transition-colors hover:bg-red-400/20",children:"Try again"}),(0,r.jsx)("button",{type:"button",onClick:n,"aria-label":"Dismiss error",className:"rounded p-1 text-red-300/70 transition-colors hover:bg-red-400/10 hover:text-red-200",children:(0,r.jsx)(H.A,{size:11})})]})]})})}function nt({onCancel:e,onConfirm:t}){return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button","aria-label":"Dismiss clear chat confirmation",tabIndex:-1,onClick:e,className:"fixed inset-0 z-30 cursor-default bg-transparent"}),(0,r.jsxs)("div",{role:"dialog","aria-label":"Clear this conversation?",className:"absolute right-0 top-full z-40 mt-1.5 w-60 rounded-lg border border-white/[0.12] bg-[#16161e] p-3 shadow-xl shadow-black/50",children:[(0,r.jsx)("p",{className:"text-[12px] font-semibold text-zinc-100",children:"Clear this conversation?"}),(0,r.jsx)("p",{className:"mt-1 text-[11px] leading-4 text-zinc-400",children:"Plans and restore points go too."}),(0,r.jsxs)("div",{className:"mt-2.5 flex justify-end gap-1.5",children:[(0,r.jsx)("button",{type:"button",onClick:e,className:"inline-flex h-7 items-center rounded-md border border-white/[0.08] px-2.5 text-[11px] text-zinc-400 transition-colors hover:bg-white/[0.06] hover:text-zinc-200",children:"Cancel"}),(0,r.jsxs)("button",{type:"button",onClick:t,"data-testid":"ai-rail-clear-chat-confirm",className:"inline-flex h-7 items-center gap-1 rounded-md bg-red-500/90 px-2.5 text-[11px] font-semibold text-white transition-colors hover:bg-red-500",children:[(0,r.jsx)(tr.A,{size:11}),"Clear"]})]})]})]})}var na=a(14929);let nr=[{icon:rq.A,title:"Natural language cuts and trims",description:"Ask the AI to cut pauses, tighten scene pacing, or reorder story beats."},{icon:na.A,title:"Instant caption styling and animations",description:"Apply dynamic caption themes, keyword highlights, and motion styles in one prompt."},{icon:rG.A,title:"Intelligent audio mixing",description:"Auto-duck music behind speech and generate matching sound effects automatically."}],nn=({fullscreen:e=!1,onSwitchToStudio:t})=>(0,r.jsx)("div",{"data-testid":"ai-editor-coming-soon-panel",className:"flex-1 overflow-y-auto px-4 py-6 scrollbar-hidden","data-ai-rail-scroll-viewport":!0,children:(0,r.jsxs)("div",{className:`space-y-6 ${e?"mx-auto max-w-xl py-8":"max-w-md mx-auto"}`,children:[(0,r.jsxs)("div",{className:"text-center space-y-3",children:[(0,r.jsxs)("div",{className:"inline-flex items-center gap-1.5 rounded-full border border-amber-400/30 bg-amber-500/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-wider text-amber-300",children:[(0,r.jsx)(k.A,{className:"h-3.5 w-3.5 text-amber-400 animate-pulse"}),(0,r.jsx)("span",{children:"Coming Soon"})]}),(0,r.jsx)("h2",{className:"text-xl font-bold tracking-tight text-zinc-100",children:"AI Video E
73ditor"}),(0,r.jsx)("p",{className:"text-xs leading-relaxed text-zinc-400",children:"Edit your video timeline using natural chat prompts. We are fine-tuning the editing engine to make script, scene, and audio adjustments seamless and reliable."})]}),(0,r.jsxs)("div",{className:"space-y-2.5",children:[(0,r.jsx)("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-zinc-400 px-1",children:"What is coming to AI Editor"}),(0,r.jsx)("div",{className:"space-y-2",children:nr.map(e=>{let t=e.icon;return(0,r.jsxs)("div",{className:"flex items-start gap-3 rounded-xl border border-white/[0.06] bg-white/[0.02] p-3 text-left transition hover:border-white/[0.10] hover:bg-white/[0.04]",children:[(0,r.jsx)("div",{className:"mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-amber-500/20 bg-amber-500/10 text-amber-400",children:(0,r.jsx)(t,{className:"h-3.5 w-3.5"})}),(0,r.jsxs)("div",{className:"space-y-0.5 min-w-0",children:[(0,r.jsx)("p",{className:"text-xs font-semibold text-zinc-200",children:e.title}),(0,r.jsx)("p",{className:"text-[11px] leading-relaxed text-zinc-400",children:e.description})]})]},e.title)})})]}),(0,r.jsxs)("div",{className:"rounded-2xl border border-amber-500/20 bg-gradient-to-b from-amber-500/[0.08] via-amber-500/[0.03] to-transparent p-4 text-center shadow-lg shadow-black/20",children:[(0,r.jsx)("div",{className:"mx-auto flex h-10 w-10 items-center justify-center rounded-xl border border-amber-500/30 bg-amber-500/15 text-amber-300",children:(0,r.jsx)(rQ.A,{className:"h-5 w-5"})}),(0,r.jsx)("h3",{className:"mt-2.5 text-sm font-bold text-zinc-100",children:"Ready to create videos now?"}),(0,r.jsx)("p",{className:"mt-1 text-xs leading-relaxed text-zinc-300",children:"Video Studio is ready to turn scripts, topics, and Reddit stories into full videos with characters, voiceovers, and captions."}),(0,r.jsxs)("button",{type:"button",onClick:t,"data-testid":"ai-editor-switch-to-studio-button",className:"mt-4 inline-flex w-full items-center justify-center gap-2 rounded-xl bg-gradient-to-r from-amber-500 to-amber-600 px-4 py-2.5 text-xs font-semibold text-slate-950 shadow-md shadow-amber-500/20 transition hover:brightness-110 active:scale-[0.98]",children:[(0,r.jsx)(k.A,{className:"h-3.5 w-3.5 text-slate-950"}),(0,r.jsx)("span",{children:"Create with Video Studio"}),(0,r.jsx)(td.A,{className:"h-3.5 w-3.5 text-slate-950"})]})]})]})});function ni(e){let t=e.audio??[];if(!t.some(e=>e.id.startsWith("marketing-music-")))return e;let a=(0,tR.lt)(e),r=y.zC.getState(),n=t.map(e=>{if(!e.id.startsWith("marketing-music-"))return e;let t=(0,tR.Fj)({blockStartSeconds:e.start,blockDurationSeconds:"number"==typeof e.duration&&e.duration>0?e.duration:Math.max(0,(e.outOffset??0)-(e.inOffset??0)),baseVolume:e.volume,speechRanges:a,settings:{duckDb:tR.D9,attackSeconds:tR.Xh,releaseSeconds:tR.w_}}),n=t.curve?{volume:t.curve}:void 0;return(0,aK.Sl)(n)===(0,aK.Sl)(e.automation)?e:(r.updateBlock(e.id,{automation:n}),{...e,automation:n})});return{...e,audio:n,...Array.isArray(e.voiceovers)&&e.voiceovers.length>0?{voiceovers:e.voiceovers.map(e=>n.find(t=>t.id===e.id)??e)}:{}}}function ns({project:e,launchMode:t,studioMode:a,collapsed:n,compact:s=!1,disableCollapse:o=!1,isInterestingContentCompilationFlow:l=!1,onSubmitInterestingCompilationUrls:c,interestingImporting:u=!1,interestingImportProgress:p=null,interestingImportErrors:m=[],interestingImportNotice:h=null,onToggleCollapsed:f,fullscreen:b=!1,onToggleFullscreen:S,updateProject:j,saveProject:I,addVoiceover:N}){var C;let M,_,A,E,{status:T}=(0,e6.wV)(),{entitlements:$}=(0,ay.G)(),P=(0,ej.n)(e=>
73e.pushAction),D=(0,ru.e)(e=>e.progress),R=(0,i.useMemo)(()=>(e?.scenes??[]).filter(e=>!0!==e.facelessPlaceholder).length,[e?.scenes]),z=$.features.canUseAiEditor,L="authenticated"===T,F=$.freeTierAiPromptLimit,O=$.freeTierAiPromptsRemaining,B=z||L&&(null===O||O>0),[W,U]=(0,i.useState)([]),[K,V]=(0,i.useState)(""),[H,Y]=(0,i.useState)("idle"),[G,X]=(0,i.useState)(null),[J,Z]=(0,i.useState)(null),[Q,ee]=(0,i.useState)(null),[et,ea]=(0,i.useState)([]),[er,en]=(0,i.useState)([]),[ei,es]=(0,i.useState)(null),[eo,el]=(0,i.useState)(!1),[ed,ec]=(0,i.useState)([]),eu=(0,i.useRef)([]),ep=(0,i.useCallback)(e=>{eu.current=e,ec(e)},[]),[em,eh]=(0,i.useState)(null),[ef,ex]=(0,i.useState)(!1),[eb,ev]=(0,i.useState)(!1),[ew,ek]=(0,i.useState)(!1),eS=(0,w.O)(e=>e.setActiveSidePanel),eN=(0,i.useCallback)((e,t,a)=>{t&&y.zC.getState().setSelectedSceneId(t),window.__effectsPanelOpenMode=a??"add",eS("effects")},[eS]),eC=(0,i.useCallback)((e,t)=>{t&&y.zC.getState().setSelectedSceneId(t),eS("captions"),window.__facelessStudioTargetPlanSceneId=e,window.__facelessStudioTargetNleSceneId=t},[eS]),eM=(0,i.useCallback)((e,t)=>{t&&y.zC.getState().setSelectedSceneId(t),eS("voiceover"),window.__facelessStudioTargetPlanSceneId=e,window.__facelessStudioTargetNleSceneId=t},[eS]);(0,i.useEffect)(()=>{let e=()=>{window.__facelessStudioTargetPlanSceneId=void 0,window.__facelessStudioTargetNleSceneId=void 0},t=w.O.getState().activeSidePanel,a=w.O.subscribe(a=>{a.activeSidePanel!==t&&(t=a.activeSidePanel,e())});return()=>{a(),e()}},[]);let e_=(0,i.useCallback)((e,t)=>{t&&y.zC.getState().setSelectedSceneId(t),eS("transitions")},[eS]),[eA,eE]=(0,i.useState)(e.aiWorkspaceTab?rm(e.aiWorkspaceTab):rf(e)?"marketing":rh(a)),eT=(0,ru.e)(e=>e.setStudioGenerateSurfaceOpen);(0,i.useEffect)(()=>(eT(("generate"===eA||"influencer"===eA&&e.influencerStudio?.stage==="studio")&&!n&&!o),()=>eT(!1)),[eA,e.influencerStudio?.stage,n,o,eT]);let[e$,eP]=(0,i.useState)("auto_apply"),[eR,ez]=(0,i.useState)(""),[eL,eF]=(0,i.useState)(null),[eO,eB]=(0,i.useState)(null),[eW,eU]=(0,i.useState)(!1),[eK,eV]=(0,i.useState)(!1),eH=(0,i.useRef)(null),eq=(0,i.useRef)(null),eY=(0,i.useRef)(null),eG=(0,i.useRef)(!1),eX=(0,i.useRef)(""),eJ=(0,i.useRef)(""),eZ=(0,i.useRef)(!0),eQ=(0,i.useRef)(!0),e0=(0,i.useRef)(null),e1=(0,i.useRef)([]),e5=(0,i.useRef)(0),e2=(0,i.useRef)(null),e4=(0,i.useRef)([]),e3=(0,i.useRef)(new Map),[th,tk]=(0,i.useState)(null),[tj,tI]=(0,i.useState)({}),tC=(0,i.useRef)(null),[tM,t_]=(0,i.useState)(null),tA=(0,i.useRef)(!1),tE=(0,i.useRef)(e),tT=(0,i.useRef)(null),t$=(0,i.useRef)(0);(0,i.useEffect)(()=>(tA.current=!1,()=>{tA.current=!0}),[]),(0,i.useLayoutEffect)(()=>{tE.current=e},[e]);let tP=(0,i.useMemo)(()=>rf(e),[e.audio,e.voiceovers]),tD=(0,i.useRef)(!1),[tR,tz]=(0,i.useState)(()=>rf(e)?"website":"product");(0,i.useEffect)(()=>{tP&&!tD.current&&tz("website")},[tP]);let tL=(0,i.useCallback)(e=>{tD.current=!0,tz(e)},[]);(0,i.useEffect)(()=>{e.aiWorkspaceTab?eE(rm(e.aiWorkspaceTab)):tP?eE("marketing"):eE(rh(a))},[e.aiWorkspaceTab,a,tP]);let tF=(0,i.useMemo)(()=>(function(e){if(!e)return aT;let t=new Set,a=[],r=e=>{if(Array.isArray(e))for(let r of e){if(!r||"object"!=typeof r||"voiceover"!==r.type)continue;let e="string"==typeof r.text?r.text.trim():"";if(!e)continue;let n="string"==typeof r.id&&r.id?r.id:"";if(n){if(t.has(n))continue;t.add(n)}let i="number"==typeof r.start&&Number.isFinite(r.start)?Math.max(0,r.start):0;a.push({id:n||`vo-${a.length}`,startSeconds:i,text:e,status:r.status})}};return(r(e.audio),r(e.voiceovers),0===a.length)?aT:(a.sort((e,t)=>e.startSeconds-t.startSeconds||e.id.localeCompare(t.id)),{segments:a,text:a.map(e=>e.text).join("\n\n")})})(e),[e.audio,e.voiceovers]),[tO,tB]=(0,i.useState)(null),tW=(0,i.useRef)(null),[tU,tK]=(0,i.useState)({}),tV=(0,i.useRef)(null),tH=(0,y.zC)(e=>e.duration),tq=(0,i.useMemo)(()=>Math.max(.02,Math.min(.25,(tH>0?tH:60)/400)),[tH]),tY=(0,i.useCallback)((e,t,a)=>{tK(r=>{if(t===a){if(!(e in r))return r;let t={...r};return delete t[e],t}return{...r,[e]:t}})},[]),tG=(0,i.useCallback)(e=>{let t=(tE.current.audio??[]).find(t=>
73t.id===e),a=t?{start:t.start,footprintSeconds:rg(t)}:void 0;tV.current=function(e,t,a){let r=t.find(t=>t.id===e&&("voiceover"===t.type||"audio"===t.type)),n=r?.start??a?.start,i=r?.duration??a?.footprintSeconds;if("number"!=typeof n||!Number.isFinite(n))return null;let s="number"==typeof i&&Number.isFinite(i)&&i>0?i:.1,o=az(t.filter(e=>"caption"===e.type),{start:n,end:n+s},aL(e,t)).map(e=>({id:e.id,start:e.start}));return{blockId:e,audioStart:n,footprintSeconds:s,captions:o}}(e,y.zC.getState().blocks,a)},[]),tX=(0,i.useCallback)((e,t)=>{tV.current?.blockId!==e&&tG(e);let a=tV.current;if(!a)return t;let r=y.zC.getState(),n=aF(a,t,r.duration);for(let t of(r.updateBlock(e,{start:n.start}),n.captionUpdates))r.updateBlock(t.id,{start:t.start});return n.start},[tG]),tJ=(0,i.useCallback)((e,t)=>{tV.current?.blockId!==e&&tG(e);let a=tV.current;if(tV.current=null,!a)return;let r=y.zC.getState(),n=aF(a,t,r.duration);for(let t of(r.updateBlock(e,{start:n.start}),n.captionUpdates))r.updateBlock(t.id,{start:t.start});let i=tE.current,s=Date.now(),o=t=>t.id===e?{...t,start:n.start,updatedAt:s}:t,l=rx(),d=ni({...i,audio:(i.audio??[]).map(o),...Array.isArray(i.voiceovers)&&i.voiceovers.length>0?{voiceovers:i.voiceovers.map(o)}:{},captionBlocks:l,updatedAt:s});if(tE.current=d,j(d),I(d),Math.abs(n.start-a.audioStart)>.004){let t=new Map(a.captions.map(e=>[e.id,e.start])),r=l.map(e=>{let a=t.get(e.id);return"number"==typeof a?{...e,start:a}:e});P({type:"MOVE_BLOCK",previousState:{scenes:i.scenes??[],audio:i.audio??[],captionBlocks:r,affectedAudioId:e},newState:{scenes:d.scenes??[],audio:d.audio??[],captionBlocks:l,affectedAudioId:e}}),(0,ey.trackEvent)("marketing_voiceover_beat_moved",{projectId:i.id,fromSeconds:Math.round(100*a.audioStart)/100,toSeconds:n.start,movedCaptions:n.captionUpdates.length})}},[tG,P,I,j]),tZ=(0,i.useCallback)(e=>{let t=tV.current;if(tV.current=null,!t||t.blockId!==e)return;let a=y.zC.getState();for(let r of(a.updateBlock(e,{start:t.audioStart}),t.captions))a.updateBlock(r.id,{start:r.start})},[]),tQ=(0,i.useRef)(!1);(0,i.useEffect)(()=>{"faceless"!==a||tQ.current||"loading"!==T&&(tQ.current=!0,(0,ey.trackEvent)("faceless_editor_mode_opened",{projectId:e.id,source:window.location.search,authenticated:"authenticated"===T}))},[a,e.id,T]);let t0=e=>{0!==e.length&&en(t=>[...t,...e.map(e=>({id:`feed-${(0,v.generateId)()}`,stage:e.stage,text:e.text,createdAt:Date.now()}))].slice(-40))},t1=(0,i.useMemo)(()=>0===ed.length?null:ed[ed.length-1],[ed]),t5=(0,i.useMemo)(()=>{let e=new Map;for(let t of ed){if(!t.messageId)continue;let a=e.get(t.messageId)??[];a.push(t),e.set(t.messageId,a)}return e},[ed]),t2=(0,i.useMemo)(()=>new Set(W.map(e=>e.id)),[W]),t4=(0,i.useMemo)(()=>ed.filter(e=>!e.messageId||!t2.has(e.messageId)),[ed,t2]),t3=("string"==typeof e.user_id?e.user_id.trim():"")||"anonymous",t8=(0,i.useMemo)(()=>`${ry}:${t3}:${e.id}`,[t3,e.id]),t6=(0,i.useMemo)(()=>`${ry}:${e.id}`,[e.id]),t9=(0,i.useMemo)(()=>`${rv}:${t3}:${e.id}`,[t3,e.id]),t7=(0,i.useMemo)(()=>`${rv}:${e.id}`,[e.id]),ae=(0,i.useMemo)(()=>`${rw}:${t3}`,[t3]),at=(0,i.useCallback)(e=>{let t=e.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return 0===t.length?null:t.every(e=>(e=>{try{let t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}})(e))?Array.from(new Set(t)):null},[]),aa="ai-generated-video"===t,ar=(0,i.useMemo)(()=>{let e=K.trim();return c&&at(e)?null:(0,aH.$C)(e)},[K,c,at]),an=K.trim().length>0&&!ar&&"thinking"!==H&&"applying"!==H&&!u,ai=l?"Describe your edit or paste content URLs.":"Describe your video and press Enter to generate.",as=l?rA[0]:aa?"Describe the video you wish to be generated.":"Describe an editâ¦",ao=G?G.operations.filter(e=>rN(e).executable).length:0,al=ao>0,ad=!!G&&ao===G.operations.length,ac=(0,i.useMemo)(()=>tN(G,e),[G,e]),au=al&&!ac.blocked&&"applying"!==H,ap=ac.blocked?"Review generation settings":ac.entries.length?`Apply and generate (~${ac.estimatedCredits} credits)`:al?ad?G?.safeToApply?"Apply":"Apply (reviewed)":"Apply executable steps":"Not executable",am=!!(window.SpeechRecognition||window.webkitSpeechRecognition);(0,i.useEffect)(()=>{let e=eq.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[K]);let ah=(0,i.useMemo)(()=>
73rK(e.scenes),[e.scenes]),ag=(0,i.useMemo)(()=>{var e;let t;return G?(e=ah.numberById,t=[],G.operations.forEach((a,r)=>{let n=rN(a);if(n.executable||!n.reason)return;let i=rR(a,e),s=i.target?`${i.verb}, ${i.target}`:i.verb;t.push(`Step ${r+1} (${s}) ${n.reason}`)}),t):[]},[G,ah]),ax=(0,y.zC)(e=>{let t=!1,a=!1,r=!1,n=[];for(let i of e.blocks)"audio"===i.type?t=!0:"voiceover"===i.type?a=!0:"caption"===i.type&&(i.sceneId&&n.push(i.sceneId),Array.isArray(i.captionWords)&&i.captionWords.length>0&&(r=!0));return`${+!!t}|${+!!a}|${+!!r}|${Array.from(new Set(n)).sort().join(",")}`}),aS=(0,i.useMemo)(()=>(function(e,t){let a=e.scenes??[],r=t?.blocks,n=a.some(e=>!!e.media?.url&&e.media?.type==="video"),i=r?r.filter(e=>"caption"===e.type):e.captionBlocks??[],s=i.some(e=>Array.isArray(e.captionWords)&&e.captionWords.length>0),o=new Set(i.map(e=>e.sceneId).filter(e=>"string"==typeof e&&e.length>0)),l=a.some(e=>!o.has(e.id)),d=[...e.audio??[],...e.voiceovers??[]],c=r?r.some(e=>"audio"===e.type):d.some(e=>"audio"===e.type),u=r?r.some(e=>"voiceover"===e.type):d.some(e=>"voiceover"===e.type),p=[];if(n&&p.push({slug:"remove-silence",label:"Remove silence",prompt:"Remove silences in this video"}),s&&p.push({slug:"tighten-pauses",label:"Tighten pauses",prompt:"Tighten the long pauses"}),a.length>0&&p.push(l?{slug:"add-captions",label:"Add captions",prompt:"Add captions to every scene"}:{slug:"restyle-captions",label:"Restyle captions",prompt:"Restyle the captions"}),c&&p.push({slug:"cut-on-beat",label:"Cut on beat",prompt:"Cut on the beat"}),c&&(u||n)&&p.push({slug:"duck-music",label:"Duck music",prompt:"Duck the music under speech"}),s&&p.push({slug:"emphasis-zooms",label:"Emphasis zooms",prompt:"add emphasis zooms"}),!(a.length>0||c||u))return[];let m=p.slice(0,5);return m.push({slug:"edit-for-tiktok",label:"Edit for TikTok",prompt:"edit this for TikTok"}),m})(e,y.zC.getState()),[e.scenes,e.audio,e.voiceovers,e.captionBlocks,ax]),aj="thinking"===H||"applying"===H||u,aI=(0,i.useMemo)(()=>{for(let e=W.length-1;e>=0;e-=1)if("user"===W[e].role)return W[e].content;return null},[W]),aN=(0,i.useCallback)(e=>{V(e),eU(!1),eq.current?.focus()},[]),aC=(0,i.useCallback)(()=>{aI&&V(aI),eF(null),eq.current?.focus()},[aI]),aP=t=>{L&&(0,af.Nh)(e.id,t).then(a=>{a.success||console.warn("[AI-EDITOR] failed to persist artifact",{projectId:e.id,artifactId:t.id,error:a.error?.message})})},aR=(t,a)=>{L&&(0,af.o3)(e.id,{activeCheckpointId:a,checkpoints:t.map(e=>({id:e.id,planId:e.planId,planSummary:e.planSummary,messageId:e.messageId,createdAt:e.createdAt,beforeProject:tg(e.beforeProject),afterProject:tg(e.afterProject),status:e.status,autoApplied:e.autoApplied,targetSceneLabel:e.targetSceneLabel??null,receipts:tx(e.receipts)}))}).then(a=>{a.success||console.warn("[AI-EDITOR] failed to persist checkpoints",{projectId:e.id,checkpointCount:t.length,error:a.error?.message})})},aO=()=>{e5.current+=1,tC.current=null,t_(null)};(0,i.useEffect)(()=>{e1.current=W},[W]),(0,i.useEffect)(()=>{eZ.current=!0;let t=e2.current,a=null!==t&&t.userScope===t3&&t.id!==e.id&&t.title===e.title&&e1.current.length>0;try{let t=localStorage.getItem(t8),r=t?null:localStorage.getItem(t6),n=t??r;if(!n){if(a){let e=e1.current.slice(-120);U(e),e1.current=e,localStorage.setItem(t8,JSON.stringify(e))}else U([]),e1.current=[];e2.current={id:e.id,title:e.title,userScope:t3};return}let i=JSON.parse(n),s=Array.isArray(i)?i.slice(-120):[];U(s),e1.current=s,localStorage.setItem(t8,JSON.stringify(s)),r&&localStorage.removeItem(t6),e2.current={id:e.id,title:e.title,userScope:t3}}catch{U([]),e1.current=[],e2.current={id:e.id,title:e.title,userScope:t3}}},[t8,t6,e.id,e.title,t3]),(0,i.useEffect)(()=>{if(eZ.current){eZ.current=!1;return}try{localStorage.setItem(t8,JSON.stringify(W.slice(-120)))}catch{}},[W,t8]),(0,i.useEffect)(()=>{eQ.current=!0;try{let e=localStorage.getItem(t9),t=e?null:localStorage.getItem(t7),a=e??t;if(!a){ep([]),eh(null),e0.current=null;return}let r=JSON.parse(a),n=function(e){if(!e||"object"!=typeof e)return{checkpoints:[],activeCheckpointId:null};let t=Array.isArray(e.checkpoints)?e.checkpoints:[],a=[];for(let e of t)e&&"object"==typeof e&&"string"==typeof e.id&&"string"==typeof e.planId&&"string"==typeof e.planSummary&&"number"==typeof e.createdAt&&tb(e.afterProject)&&a.push({id:e.id,planId:e.planId,planSummary:e.planSummary,messageId:"string"==typeof e.messageId?e.messageId:void 0,createdAt:e.createdAt,afterProject:tg(e.afterProject),autoApplied:!!e.autoApplied,targetSceneLabel:null===e.targetSceneLabel||"string"==typeof e.targetSceneLabel?e.targetSceneLabel:null,receipts:Array.isArray(e.receipts)?tx(e.receipts):[]});let r=tb(e.baseProject)?tg(e.baseProject):null,n=a.map(e=>{let t=r?tg(r):tg(e.afterProject),a=tg(e.afterProject);return r=a,{id:e.id,planId:e.planId,planSummary:e.planSummary,messageId:e.messageId,createdAt:e.createdAt,beforeProject:t,afterProject:a,status:"applied",autoApplied:e.autoApplied,targetSceneLabel:e.targetSceneLabel??null,receipts:tx(e.receipts)}}),i=Object.prototype.hasOwnProperty.call(e,"activeCheckpointId"),s=null===e.activeCheckpointId?null:"string"==typeof e.activeCheckpointId?e.activeCheckpointId:null;return("string"!=typeof s||n.some(e=>e.id===s))&&i||(s=n.length?n[n.length-1].id:null),{checkpoints:ty(n,s),activeCheckpointId:s}}(r);ep(n.checkpoints),eh(n.activeCheckpointId),e0.current=n.activeCheckpointId,t&&localStorage.removeItem(t7)}catch{ep([]),eh(null),e0.current=null}},[t9,t7,e.id]),(0,i.useEffect)(()=>
73{if(!L)return;let t=!1;return(async()=>{let a=e5.current,r=await (0,af.i4)(e.id);if(!r.success||!r.data||t)return;if(e5.current!==a)return console.warn("[AI-EDITOR] skipping stale history hydrate due to local changes",{projectId:e.id});let n=(r.data.messages??[]).filter(e=>!!e&&("user"===e.role||"assistant"===e.role||"system"===e.role)&&"string"==typeof e.id&&"string"==typeof e.content&&"number"==typeof e.createdAt).slice(-120),i=function(e,t){if(!Array.isArray(e))return{checkpoints:[],activeCheckpointId:null};let a=[];for(let t of e)t&&"object"==typeof t&&"string"==typeof t.id&&"string"==typeof t.planId&&"string"==typeof t.planSummary&&"number"==typeof t.createdAt&&tb(t.beforeProject)&&tb(t.afterProject)&&a.push({id:t.id,planId:t.planId,planSummary:t.planSummary,messageId:"string"==typeof t.messageId?t.messageId:void 0,createdAt:t.createdAt,beforeProject:tg(t.beforeProject),afterProject:tg(t.afterProject),status:"unapplied"===t.status?"unapplied":"applied",autoApplied:!!t.autoApplied,targetSceneLabel:null===t.targetSceneLabel||"string"==typeof t.targetSceneLabel?t.targetSceneLabel:null,receipts:Array.isArray(t.receipts)?tx(t.receipts):[]});let r="string"==typeof t?t:null;if(r&&!a.some(e=>e.id===r)&&(r=null),!r){let e=[...a].reverse().find(e=>"applied"===e.status);r=e?.id??null}return{checkpoints:ty(a,r),activeCheckpointId:r}}(r.data.checkpoints??[],r.data.activeCheckpointId??null),s=e=>Number.isFinite(e.updatedAt)?e.updatedAt:e.createdAt,o=(r.data.artifacts??[]).filter(e=>!!e&&"string"==typeof e.id&&"string"==typeof e.status&&"number"==typeof e.createdAt&&"number"==typeof e.updatedAt&&rW(e.planJson)&&Array.isArray(e.receiptsJson)).sort((e,t)=>s(e)-s(t)),l=o.length>0?o[o.length-1]:null,d=l&&"planned"===l.status?l:null,c=d?rU(d):null;c&&!n.some(e=>e.id===d?.messageId)&&(c=null);let u=[...o].reverse().find(e=>Array.isArray(e.receiptsJson)&&e.receiptsJson.length>0),p=[...o].reverse().find(e=>"string"==typeof e.requestId||"string"==typeof e.idempotencyKey),m=u?u.receiptsJson.map(e=>{if(!rW(e))return null;let t="string"==typeof e.summary?e.summary:"";if(!t)return null;let a=!0===e.success?"OK":"SKIP",r="string"==typeof e.warning?e.warning:"",n="string"==typeof e.error?e.error:"",i=r||n;return i?`${a}: ${t} (${i})`:`${a}: ${t}`}).filter(e=>!!e):[],h=function(e){let t=[];for(let a of e){if("applied"!==a.status||!Array.isArray(a.receiptsJson))continue;let e=rU(a);if(e)for(let r of a.receiptsJson){if(!rW(r)||!0!==r.success||"number"!=typeof r.operationIndex||"string"!=typeof r.kind)continue;let n=e.operations[r.operationIndex];if(!n)continue;let i="string"==typeof n.sceneId?n.sceneId:Array.isArray(n.scope?.sceneIds)&&"string"==typeof n.scope.sceneIds[0]?n.scope.sceneIds[0]:e.resolvedSceneTarget?.sceneId;if(!i)continue;let s="number"==typeof n.sceneNumber?n.sceneNumber:e.resolvedSceneTarget?.sceneId===i?e.resolvedSceneTarget?.sceneNumber:void 0;t.push({sceneId:i,sceneNumber:"number"==typeof s?s:void 0,effectType:rW(n.effect)&&"string"==typeof n.effect.type?n.effect.type:void 0,parameterName:"string"==typeof n.parameterName?n.parameterName:void 0,operationKind:r.kind,timestamp:"number"==typeof r.timestamp?r.timestamp:Number.isFinite(a.updatedAt)?a.updatedAt:a.createdAt})}}return t}(o),f=new Map(i.checkpoints.map(e=>[e.planId,e.autoApplied])),g={};for(let e of o){if("applied"!==e.status)continue;let t=rU(e);if(!t)continue;let a=rF(t,{autoApplied:f.get(t.id)??!1});a&&(g[t.id]=a)}if(!(n.length>0||o.length>0||i.checkpoints.length>0||null!==i.activeCheckpointId)&&e1.current.length>0)return console.warn("[AI-EDITOR] preserving local chat history because backend history is empty",{projectId:e.id,localMessageCount:e1.current.length});eZ.current=!0,eQ.current=!0,U(n),ep(i.checkpoints),eh(i.activeCheckpointId),e0.current=i.activeCheckpointId,tI(g),ea(m),es(m.length>0?m[m.length-1]:null),el(!1),tk(null),ee(null),X(c),Z(c?d?.messageId??null:null),eB(p?{requestId:p.requestId,idempotencyKey:p.idempotencyKey,idempotencyReplay:!!p.idempotencyReplay}:null),en([]),Y(c?"planning":"idle"),e4.current=h,e3.current=new Map,c&&d&&e3.current.set(c.id,{requestId:d.requestId,idempotencyKey:d.idempotencyKey,idempotencyReplay:!!d.idempotencyReplay});try{localStorage.setItem(t8,JSON.stringify(n)),localStorage.removeItem(t6);let e=tw(i.checkpoints,i.activeCheckpointId,{maxCheckpoints:20,maxBytes:15e5});localStorage.setItem(t9,JSON.stringify(e)),localStorage.removeItem(t7)}catch{}})(),()=>{t=!0}}
73,[L,e.id,t8,t9,t6,t7]),(0,i.useEffect)(()=>{if(eQ.current){eQ.current=!1;return}try{let e=tw(ed,em,{maxCheckpoints:20,maxBytes:15e5});localStorage.setItem(t9,JSON.stringify(e))}catch{}},[ed,em,t9]),(0,i.useEffect)(()=>{try{let e=localStorage.getItem(ae),t=e?null:localStorage.getItem(rw),a=e??t;eP("preview_first"===a?"preview_first":"auto_apply"),t&&(localStorage.setItem(ae,t),localStorage.removeItem(rw))}catch{eP("auto_apply")}},[ae]),(0,i.useEffect)(()=>{B&&eU(!1)},[B]),(0,i.useEffect)(()=>{eH.current&&(eH.current.scrollTop=eH.current.scrollHeight)},[W,G,et,ed]),(0,i.useEffect)(()=>{e0.current=em},[em]),(0,i.useEffect)(()=>()=>{if(eG.current=!1,eY.current)try{eY.current.stop()}catch{}},[]);let aB=(t,a)=>{aO(),U(e=>{let a=[...e,t].slice(-120);try{localStorage.setItem(t8,JSON.stringify(a))}catch{}return a}),a?.persist!==!1&&L&&(0,af.SK)(e.id,t).then(a=>{a.success||console.warn("[AI-EDITOR] failed to persist chat message",{projectId:e.id,messageId:t.id,error:a.error?.message})})},aW=(0,i.useCallback)(async(e,t)=>{let a={...tE.current,...t,aiWorkspaceTab:e,updatedAt:Date.now()};tE.current=a,j(a),await I(a)},[I,j]),aK=(0,i.useCallback)(e=>{eE(e),aW(e)},[aW]);(0,i.useEffect)(()=>{let e=e=>{let t=e.detail;t&&(t.handled=!0),aK("generate")};return window.addEventListener("faceless:open-generate-tab",e),()=>window.removeEventListener("faceless:open-generate-tab",e)},[aK]);let aq=(0,i.useCallback)(async e=>{let t,a=tE.current,r=a.audio??[],n=r.find(t=>t.id===e);if(!n)return{outcome:"skipped",reason:"its voiceover block no longer exists"};if(tW.current)return{outcome:"skipped",reason:"another regeneration was running"};let i=tU[e],s=(n.text??"").trim(),o="string"==typeof i?i.trim():null,l=null!==o&&o.length>0&&o!==s,d=l?o:s;if(!d)return{outcome:"skipped",reason:"it has no script text to speak"};let c=(e,t)=>console.warn(`[MarketingâRegen] ${e}`,t??""),u=(t,a)=>{if(a){let e=y.zC.getState();for(let t of a.removeIds)e.removeCaptionBlock(t);a.add.length>0&&e.addCaptionBlocks(a.add.map(e=>({...e,type:"caption"})))}let r=tE.current,n=ni({...r,audio:(r.audio??[]).map(a=>a.id===e?t:a),...a?{captionBlocks:rx()}:{},updatedAt:Date.now()});tE.current=n,j(n),I(n)};if(l){let a=r.filter(t=>t.id!==e&&"voiceover"===t.type&&(t.text??"").trim().length>0&&"number"==typeof t.start&&t.start>n.start+.01).map(e=>e.start),i=y.zC.getState().duration,s=a.length>0?Math.min(...a):i>n.start+1?i:null;null!==s&&(t=Math.max(1,s-n.start-.2))}let p=(a.captionBlocks??[]).some(e=>aD(e.id)),m=a.scenes?.[0]?.id,h=!p&&m?{sceneId:m,orientation:"9:16"===a.aspectRatio?"portrait":"landscape"}:null;tW.current=e,tB(e);try{let r=await (0,a$.WU)({block:n,projectId:a.id,isLocalProject:"local"===a.mode,...l?{text:d,maxPlayableSeconds:t}:{},log:c});if(r){let t=await rb(n,r,c,h),i=tE.current;u(r.block,t);let s=tE.current;return P({type:"MOVE_BLOCK",previousState:{scenes:i.scenes??[],audio:i.audio??[],...i.captionBlocks?{captionBlocks:i.captionBlocks}:{},affectedAudioId:e},newState:{scenes:s.scenes??[],audio:s.audio??[],...s.captionBlocks?{captionBlocks:s.captionBlocks}:{},affectedAudioId:e}}),tK(t=>{if(!(e in t))return t;let a={...t};return delete a[e],a}),(0,ey.trackEvent)("marketing_voiceover_beat_regenerated",{projectId:a.id,outcome:"success",textEdited:l,captionsRebuilt:!!t}),{outcome:"done"}}return u({...n,...l?{text:d}:{},status:"error",isLoading:!1,errorMessage:"Voiceover generation failed. Try again.",updatedAt:Date.now()}),(0,ey.trackEvent)("marketing_voiceover_beat_regenerated",{projectId:a.id,outcome:"failed",textEdited:l}),{outcome:"failed",reason:"voiceover generation failed"}}catch(e){return u({...n,...l?{text:d}:{},status:"error",isLoading:!1,errorMessage:e?.message??"Voiceover generation failed. Try again.",updatedAt:Date.now()}),{outcome:"failed",reason:e?.message??"voiceover generation failed"}}finally{tW.current=null,tB(null)}},[tU,P,I,j]),aY=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(("marketing"===a||tP)&&!aY.current){if(e.aiWorkspaceTab){aY.current=!0;return}aY.current=!0,eE("marketing"),aW("marketing")}},[a,tP,e.aiWorkspaceTab,aW]);let aG=(0,i.useRef)(null);(0,i.useEffect)(()=>
73{if("authenticated"!==T||aG.current===e.id)return;let t=(e.audio??[]).filter(e=>"voiceover"===e.type&&"string"==typeof e.id&&e.id.startsWith("marketing-vo")&&("pending"===e.status||"error"===e.status)&&(e.text??"").trim().length>0).sort((e,t)=>(e.start??0)-(t.start??0));0!==t.length&&(aG.current=e.id,console.warn("[MarketingâResume] Resuming interrupted voiceover generation",{projectId:e.id,beats:t.length}),(0,ey.trackEvent)("marketing_voiceover_auto_resume",{projectId:e.id,beats:t.length}),(async()=>{for(let e of t)await aq(e.id)})())},[T,e.id,e.audio,aq]),(0,i.useCallback)((e,t)=>{V(e),eU(!1),eE("editor"),t&&(tE.current=t,j(t)),aW("editor",t)},[aW,j]);let aZ=async()=>{await aQ(K)},aQ=async t=>{let a,r,n,i=t.trim();if(!i)return;let s=at(i);if(s&&c){aB({id:`user-${(0,v.generateId)()}`,role:"user",content:i,createdAt:Date.now()}),V(""),eU(!1),eF(null),en([]),es(null),el(!1),Y("applying"),t0([{stage:"queued",text:`Queued URL import for ${s.length} URL${1===s.length?"":"s"}.`}]);try{await c(s.join("\n")),t0([{stage:"applied",text:`Submitted ${s.length} URL${1===s.length?"":"s"} for scene import.`}]),Y("idle")}catch(t){let e=t instanceof Error?t.message:"Failed to submit URL import.";eF(e),Y("failed"),t0([{stage:"failed",text:`Reddit import failed: ${e}`}])}return}let o=(0,aH.$C)(i);if(o){V(t),eF(o),eU(!1),Y("idle");return}if(!B){(0,ey.trackEvent)("feature_gate_hit",{feature:"ai_editor_prompt_submit",gate:L?"free_prompts_exhausted":"authentication_required",projectId:e.id,limit:F,remaining:O}),eU(!0),eF(null),Y("idle");return}if(rB.test(i.trim())){aB({id:`user-${(0,v.generateId)()}`,role:"user",content:i,createdAt:Date.now()}),V(""),eU(!1),eF(null),en([]),es(null),(0,ey.trackEvent)("ai_editor_chat_undo",{projectId:e.id});let t=tv(ed,em);if(!t||!t1){aB({id:`assistant-${(0,v.generateId)()}`,role:"assistant",content:0===ed.length?"There are no AI edits to undo yet.":"The latest AI edit is already undone. Use the checkpoint history below a message to restore an earlier state.",createdAt:Date.now()}),Y("idle");return}let a=await a9(t.projectSnapshot,t.checkpoints,t.activeCheckpointId,`Unapplied: ${t1.planSummary}`);aB({id:`assistant-${(0,v.generateId)()}`,role:"assistant",content:a?`Undid the last AI edit: ${t1.planSummary}`:"I could not undo the last edit. Try restoring from the checkpoint history instead.",createdAt:Date.now()});return}eU(!1),aB({id:`user-${(0,v.generateId)()}`,role:"user",content:i,createdAt:Date.now()}),V(""),eF(null),en([]),es(null),el(!1);let l=(a=i.trim())?Math.max(1,a.split(/\b(?:and then|then|also)\b/gi).map(e=>e.trim()).filter(Boolean).length):1,u=function(e,t){let a=y.zC.getState(),r=a.blocks,n=r.filter(e=>"scene"===e.type),i=r.filter(e=>"caption"===e.type),s=r.filter(e=>"audio"===e.type||"voiceover"===e.type),o=Array.from(new Set(r.map(e=>Number(e.trackId)))).sort((e,t)=>e-t),l=new Map(n.map(e=>[e.sceneId,e.start])),{orderedScenes:c}=rK(e.scenes.map(e=>{let t=l.get(e.id)??e.timelineStart;return t===e.timelineStart?e:{...e,timelineStart:t}}));return{project:{id:e.id,title:e.title,aspectRatio:e.aspectRatio,duration:a.duration,sceneCount:c.length,audioBlockCount:s.length,captionBlockCount:i.length},editHistory:t?.slice(-20),scenes:c.map(e=>({id:e.id,text:e.text||"",timelineStart:e.timelineStart,trackId:e.trackId,duration:e.media?.trim?Math.max(0,e.media.trim.end-e.media.trim.start):e.media?.duration,hasMedia:!!e.media?.url,mediaType:e.media?.type,effects:(e.effects??[]).filter(e=>!!e?.type).map(e=>({type:e.type,enabled:e.enabled,params:e.params}))})),audioBlocks:s.map(e=>({id:e.id,type:e.type,trackId:Number(e.trackId),start:e.start,duration:e.duration,label:e.label})),captionBlocks:i.map(e=>({id:e.id,sceneId:e.sceneId,trackId:Number(e.trackId),start:e.start,duration:e.duration,text:e.captionText,words:Array.isArray(e.captionWords)?e.captionWords.slice(0,800).map(e=>({word:e.word,start:e.start,end:e.end})):void 0})),selectedSceneIds:a.selectedSceneIds,selectedBlockIds:a.selectedAudioBlockIds,playheadTime:a.projectTime,tracks:o.map(e=>{let t=a.trackSettings.get(e)??{muted:!1,locked:!1,visible:!0},n=a.trackMeta.get(e);
73return{trackId:e,label:function(e,t){if(0===e)return"Background";if(1===e)return"Main";let a=t.filter(t=>Number(t.trackId)===e),r=a.some(e=>"voiceover"===e.type),n=a.some(e=>"audio"===e.type);return r&&!n?"Voiceover":3===e&&n?"Music":`Track ${e}`}(e,r),type:n?.type==="caption"?"caption":e<=1?"video":"audio",visible:t.visible,locked:t.locked,muted:t.muted}}),sceneEntryMap:n.map(e=>({sceneId:e.sceneId,blockId:e.id,trackId:Number(e.trackId),start:e.start,duration:e.duration})),capabilities:{generation:{models:tS.L4.map(({value:e,label:t})=>({key:e,label:t})),defaultVideoModel:e.facelessSettings?.videoModel??"pixverse-v4.5",defaultVideoQualityTier:e.facelessSettings?.videoQualityTier??"360p",imageReferences:e.scenes.filter(e=>e.media?.type==="image"&&!e.isLoading).slice(0,64).map(e=>({sceneId:e.id,label:(e.text||"Image").slice(0,120)})),maxImageReferences:4,nativeAudio:!1},aiEditorEnabled:d.Wg.AI_EDITOR_ENABLED,advancedEnabled:d.Wg.AI_EDITOR_ADVANCED_ENABLED,supportsMicDictation:!!(window.SpeechRecognition||window.webkitSpeechRecognition)},aiAnalysis:function(e){if(!e||!aV(e))return;let t={};if(aV(e.beats)){let a=Array.isArray(e.beats.markers)?e.beats.markers:[],r=Array.isArray(e.beats.onsets)?e.beats.onsets:[];t.beats={sourceAudioBlockId:e.beats.sourceAudioBlockId,tempo:e.beats.tempo,markerCount:a.length,onsetCount:r.length,analyzedAt:e.beats.analyzedAt,version:e.beats.version}}if(Array.isArray(e.silenceRanges)&&e.silenceRanges.length>0&&(t.silenceRangesSummary=e.silenceRanges.slice(0,20).map(e=>{let t=Array.isArray(e?.ranges)?e.ranges:[],a=t.filter(e=>aV(e)&&"number"==typeof e.start&&"number"==typeof e.end).slice(0,3).map(e=>({start:e.start,end:e.end})),r=t.reduce((e,t)=>aV(t)&&"number"==typeof t.start&&"number"==typeof t.end?e+Math.max(0,t.end-t.start):e,0);return{sceneId:e.sceneId,rangeCount:t.length,totalSilenceSeconds:Number(r.toFixed(3)),preview:a}})),aV(e.sceneMetrics)){let a=Object.keys(e.sceneMetrics);t.sceneMetricsSummary={sceneCount:a.length,sceneIds:a.slice(0,20)}}if(aV(e.montageCandidates)){let a=Object.keys(e.montageCandidates);t.montageCandidatesSummary={candidateCount:a.length,sceneIds:a.slice(0,20)}}aV(e.audioArtifacts)&&(t.audioArtifactsSummary=Object.entries(e.audioArtifacts).slice(0,20).flatMap(([e,t])=>{if(!aV(t))return[];let a=aV(t.waveform)?t.waveform:null,r=aV(t.loudness)?t.loudness:null,n=aV(t.speech)?t.speech:null,i=aV(t.rhythm)?t.rhythm:null,s=Array.isArray(a?.peakPyramid)?a.peakPyramid:[],o=Array.isArray(r?.rms)?r.rms:[],l=Array.isArray(n?.activeRanges)?n.activeRanges:[],d=Array.isArray(n?.silenceRanges)?n.silenceRanges:[],c=Array.isArray(i?.beatTimes)?i.beatTimes:[],u=Array.isArray(i?.onsetTimes)?i.onsetTimes:[],p=Array.isArray(i?.downbeatTimes)?i.downbeatTimes:[],m=Array.isArray(i?.barTimes)?i.barTimes:[],h=Array.isArray(i?.kickOnsetTimes)?i.kickOnsetTimes:[];return[{artifactId:e,sourceType:t.sourceType,sourceSceneId:t.sourceSceneId,sourceAudioBlockId:t.sourceAudioBlockId,duration:t.duration,sampleRate:t.sampleRate,channelCount:t.channelCount,analyzedAt:t.analyzedAt,version:t.version,waveformLevels:s.length,rmsBucketCount:o.length,speechRangeCount:l.length,silenceRangeCount:d.length,rhythmBeatCount:c.length,rhythmOnsetCount:u.length,rhythmDownbeatCount:p.length,rhythmBarCount:m.length,rhythmKickCount:h.length,rhythmTempoBpm:"number"==typeof i?.tempoBpm?i.tempoBpm:void 0,rhythmEntryTime:"number"==typeof i?.entryTime?i.entryTime:void 0,rhythmConfidence:"number"==typeof i?.confidence?i.confidence:void 0}]}));let a=new Set(["beats","silenceRanges","sceneMetrics","montageCandidates","audioArtifacts"]),r=Object.keys(e).filter(e=>!a.has(e));return r.length>0&&(t.availableKeys=r.slice(0,20)),Object.keys(t).length>0?t:void 0}(e.aiAnalysis)}}(e,e4.current);(0,ey.trackEvent)("ai_editor_prompt_submitted",{projectId:e.id,promptLength:i.length,clauseCount:l,sceneCount:u.scenes.length,audioCount:u.audioBlocks.length,captionCount:u.captionBlocks.length});let p=`ai-chat-${e.id}-${Date.now().toString(36)}-${(0,v.generateId)()}`;t0([{stage:"queued",text:l>1?`Queued request with ${l} prompt clauses.`:"Queued request."},{stage:"thinking",text:l>1?`Analyzing ${l} prompt clauses...`:"Analyzing prompt..."}]),Y("thinking");let m=(r=W.filter(e=>e.content.trim().length>0&&!function(e){if("assistant"!==e.role)return!1;let t=e.content.toLowerCase();return t.includes("i could not plan that edit")||t.includes("planning request failed")||t.includes("unauthorized")||t.includes("redirecting to sign-in")||t.includes("context window of this model")}(e)),n=i.trim().toLowerCase(),(r.length>0&&n&&r[r.length-1]?.role==="user"&&r[r.length-1]?.content.trim().toLowerCase()===n?r.slice(0,-1):r).slice(-5));console.warn("[AI-EDITOR] plan request",{projectId:e.id,promptLength:i.length,sceneCount:u.scenes.length,audioCount:u.audioBlocks.length,captionCount:u.captionBlocks.length,planningMessageCount:m.length,aiAnalysisKeys:u.aiAnalysis?Object.keys(u.aiAnalysis):[]});let h=new AbortController;tT.current=h;let f=++t$.current,g=await (0,af.ji)(e.id,{prompt:i,snapshot:u,messages:m,idempotencyKey:p,...eR?{model:eR}:{}},{signal:h.signal});if(t$.current!==f)return;if(tT.current===h&&(tT.current=null),g.error?.error_code===af.tJ){t0([{stage:"failed",text:"Stopped before a plan came back."}]),Y("idle");return}let x=g.data?.requestId??g.requestId,b=rO(x);if(!g.success||!g.data){let a=g.error?.message||"Failed to request AI plan.";if(g.error?.status_code===422&&V(e=>e||t),g.error?.error_code==="free_tier_limit_reached"){(0,av.g)(),(0,ey.trackEvent)("feature_gate_hit",{feature:"ai_editor_prompt_submit",gate:"free_prompts_exhausted",projectId:e.id,limit:F,remaining:0}),eU(!0),Y("idle"),t0([{stage:"failed",text:"Today's free AI edits are used up."}]),aB({id:`assistant-${(0,v.generateId)()}`,role:"assistant",content:a,createdAt:Date.now()});return}eF(a),Y("failed"),(0,ey.trackEvent)("ai_editor_prompt_failed",{projectId:e.id,promptLength:i.length,clauseCount:l,requestId:x,errorCode:g.error?.error_code,statusCode:g.error?.status_code,message:a?String(a).slice(0,200):void 0}),eB({requestId:x,idempotencyKey:p,idempotencyReplay:!1}),t0([{stage:"failed",text:b?`Plan failed (${b}): ${a}`:`Plan failed: ${a}`}]),aB({id:`assistant-${(0,v.generateId)()}`,role:"assistant",content:`I could not plan that edit: ${a}`,createdAt:Date.now()});return}let w=g.data.plan;(0,ey.trackEvent)("ai_editor_prompt_succeeded",{projectId:e.id,promptLength:i.length,clauseCount:l,planId:w.id,operationCount:w.operations.length,safeToApply:w.safeToApply,sceneCount:u.scenes.length,audioCount:u.audioBlocks.length,captionCount:u.captionBlocks.length,planKind:w.operations.some(e=>rN(e).executable)?"executable":"guidance",idempotencyReplay:!!g.data.idempotencyReplay}),e.id,w.id,w.operations.map(e=>e.kind),w.operations.length;let k={requestId:x,idempotencyKey:g.data.idempotencyKey??p,idempotencyReplay:!!g.data.idempotencyReplay,prompt:i};eB(k),e3.current.set(w.id,k),t0([{stage:"planning",text:l>1?`Planner assembled ${l} clauses.`:"Planner assembled plan."},{stage:"planned",text:k.idempotencyReplay?`Plan ready with ${w.operations.length} operations (idempotency replay).`:`Plan ready with ${w.operations.length} operations.`}]),(0,av.g)();let S=`assistant-${(0,v.generateId)()}`;if(aB({id:S,role:"assistant",content:g.data.assistantMessage,createdAt:Date.now()}),console.warn("[AI-EDITOR] plan response",{projectId:e.id,planId:g.data.planId,safeToApply:g.data.plan.safeToApply,operationCount:g.data.plan.operations.length,warningCount:g.data.plan.warnings.length}),aP(rH(w,{messageId:S,status:"planned",mode:e$,requestId:k.requestId,idempotencyKey:k.idempotencyKey,idempotencyReplay:k.idempotencyReplay})),!w.operations.some(e=>rI(e.kind))){t0([{stage:"planned",text:"No edit to apply - the planner answered with guid
73ance instead."}]),X(null),Z(null),ee(null),tk(null),Y("idle");return}if("preview_first"===e$||!w.safeToApply){t0([{stage:"planned",text:"preview_first"===e$?"Preview-first mode: review the plan, then click Apply.":"Plan needs review before applying - check the preview warnings."}]),X(w),Z(S),ee(null),tk(null),Y("planning");return}let j=w,I=w.operations.filter(e=>rN(e).executable);if(0===I.length){t0([{stage:"planned",text:"No step in this plan can run yet (unsupported or missing details), so nothing was auto-applied. Review the preview instead."}]),X(w),Z(S),ee(null),tk(null),Y("planning");return}if(I.length!==w.operations.length){let e=w.operations.length-I.length;j={...w,operations:I,warnings:[...w.warnings,`Skipped ${e} step(s) that cannot run yet during auto-apply.`]},t0([{stage:"planned",text:`Skipping ${e} operation(s) that are not available yet; applying the rest.`}])}let N=tf(j)??j.resolvedSceneTarget?.sceneId??null,C=null;if(N){console.warn("[AI-EDITOR] auto-apply target",{projectId:e.id,planId:g.data.planId,targetScene:N});let t=y.zC.getState(),a=t.blocks.find(e=>"scene"===e.type&&e.sceneId===N);if(a){let e=Math.max(0,a.duration??0),r=Math.min(rk,e>0?Math.max(0,e/2):rk),n=Math.max(a.start,Math.min(a.start+r,a.start+Math.max(0,e-.001)));t.setProjectTime(n)}await function(e=300){return new Promise("function"!=typeof window.requestAnimationFrame?t=>setTimeout(t,Math.min(e,50)):t=>{let a=!1,r=()=>{a||(a=!0,clearTimeout(n),t())},n=setTimeout(r,e);window.requestAnimationFrame(()=>{window.requestAnimationFrame(r)})})}(300);let r=rK(tE.current.scenes).numberById.get(N);C=r?`Scene ${r}`:null,tk(r?`Scene ${r}`:N.slice(0,8))}else tk(null);X(null),Z(null),ee(null),await a0(j,{messageId:S,autoApplied:!0,targetSceneLabel:C,requestMeta:k})},a0=async(t,a)=>{var r;aO(),console.warn("[AI-EDITOR] apply start",{projectId:e.id,planId:t.id,operationCount:t.operations.length}),es(null),el(!1);let n=a?.requestMeta??e3.current.get(t.id);n&&eB(n),t0([{stage:"applying",text:`Applying ${t.operations.length} operation${1===t.operations.length?"":"s"}...`},...t.operations.slice(0,8).map((e,a)=>({stage:"applying",text:`Queued op ${a+1}/${t.operations.length}: ${e.kind}`})),...t.operations.length>8?[{stage:"applying",text:`...and ${t.operations.length-8} more operations`}]:[]]),Y("applying"),eF(null);let i=y.zC.getState(),s=await ab({plan:t,promptText:n?.prompt,currentProject:tE.current,selectedSceneIds:i.selectedSceneIds,selectedBlockIds:i.selectedAudioBlockIds,updateProject:j,saveProject:I,addVoiceover:N}),o=s.executedPlan??t,l=s.receipts.map(e=>{let t=e.success?"OK":"SKIP",a=e.warning||e.error;return a?`${t}: ${e.summary} (${a})`:`${t}: ${e.summary}`}),d=s.receipts.filter(e=>e.success),c=s.receipts.filter(e=>!e.success),u=!s.success&&!!s.updatedProject,p=(()=>{if(!u)return null;let e=c.map(e=>e.warning||e.error||e.summary).filter(Boolean).slice(0,3).join("; ");return`Applied ${d.length} of ${s.receipts.length} steps â the rest failed${e?`: ${e}`:"."}`})(),m=[...d].reverse()[0]??[...s.receipts].reverse()[0]??null,h=m?m.summary:null,f=m?.warning||m?.error||null;if(p?es(p):h&&es(s.success?d.length<=1?`Applied: ${h}`:`Applied ${d.length}/${s.receipts.length} steps. Last: ${h}`:f?`Failed: ${h} (${f})`:`Failed: ${h}`),ea(l),t0(s.receipts.map(e=>{let a=e.warning||e.error,r=a?`${e.summary} (${a})`:e.summary;return{stage:e.success?"applied":"failed",text:`Op ${e.operationIndex+1}/${t.operations.length} ${e.kind}: ${r}`}})),!s.success&&!s.updatedProject)return console.error("[AI-EDITOR] apply failed",{projectId:e.id,planId:t.id,receipts:s.receipts.length,error:s.error}),(0,ey.trackEvent)("ai_editor_apply_failed",{projectId:e.id,planId:t.id,operationCount:t.operations.length,receiptCount:s.receipts.length,error:(s.error||"").slice(0,300),receipt_errors:s.receipts.map(e=>e.error).filter(e=>!!e).join("; ").slice(0,300),autoApplied:!!a?.autoApplied}),(0,af._L)(e.id,t.id,"apply_failed").then(e=>{e.success&&e.data?.refunded&&((0,av.g)(),t0([{stage:"failed",text:"This attempt was not charged."}]))}).catch(()=>{}),aP(rH(o,{messageId:a?.messageId,receipts:s.receipts,status:"failed",mode:e$,requestId:n?.requestId,idempotencyKey:n?.idempotencyKey,idempotencyReplay:n?.idempotencyReplay})),Y("failed"),eF(s.error||"AI apply failed during save/restore."),el(!0),t0([{stage:"failed",text:s.error||"Apply failed during save/restore."}]),a?.autoApplied&&(X(t),Z(a.messageId??null)),!1;let g=s.restorePoint?.scenes?structuredClone(s.restorePoint.scenes):null,x=s.updatedProject?.scenes?structuredClone(s.updatedProject.scenes):null;g&&x&&d.length>0&&function(e,t){if(!e||!t||e===t)return!1;if(e.length!==t.length)return!0;try{return JSON.stringify(e)!==JSON.stringify(t)}catch{return!0}}(g,x)&&P({type:"REORDER_SCENES",previousState:{scenes:g},newState:{scenes:x}});let b=`ai-edit-group-${Date.now()}-${(0,v.generateId)()}`,w=s.updatedProject??tE.current;if(tE.current.id!==w.id)return!1;
73for(let e of(tE.current=w,d)){let t=o.operations[e.operationIndex];if(!t)continue;let a=e.sceneId??t.sceneId??t.scope?.sceneIds?.[0]??o.resolvedSceneTarget?.sceneId;if(!a)continue;let r=w.scenes.findIndex(e=>e.id===a);e4.current.push({sceneId:a,sceneNumber:r>=0?r+1:void 0,effectType:t.effect?.type,parameterName:"string"==typeof t.parameterName?t.parameterName:void 0,operationKind:e.kind,timestamp:Date.now(),groupId:b,beforeTimelineStart:"number"==typeof e.beforeTimelineStart?e.beforeTimelineStart:void 0,afterTimelineStart:"number"==typeof e.afterTimelineStart?e.afterTimelineStart:void 0,beforeTrackId:"number"==typeof e.beforeTrackId?e.beforeTrackId:void 0,afterTrackId:"number"==typeof e.afterTrackId?e.afterTrackId:void 0})}console.warn("[AI-EDITOR] apply complete",{projectId:e.id,planId:t.id,receipts:s.receipts.length,partialCommit:u}),aP(rH(o,{messageId:a?.messageId,receipts:s.receipts,status:"applied",mode:e$,requestId:n?.requestId,idempotencyKey:n?.idempotencyKey,idempotencyReplay:n?.idempotencyReplay}));let k=rF(o,{autoApplied:a?.autoApplied??!1});k&&tI(e=>({...e,[o.id]:k}));let S={id:(r={id:`ai-checkpoint-${(0,v.generateId)()}`,plan:o,beforeProject:s.restorePoint,afterProject:w,receipts:s.receipts,messageId:a?.messageId,autoApplied:a?.autoApplied,targetSceneLabel:a?.targetSceneLabel??null}).id,planId:r.plan.id,planSummary:r.plan.summary,messageId:r.messageId,createdAt:r.createdAt??Date.now(),beforeProject:tg(r.beforeProject),afterProject:tg(r.afterProject),status:"applied",autoApplied:!!r.autoApplied,targetSceneLabel:r.targetSceneLabel??null,receipts:tx(r.receipts)},C=function(e,t,a){let r=e;if(t){let a=e.findIndex(e=>e.id===t);a>=0&&a<e.length-1&&(r=e.slice(0,a+1))}else r=[];return{checkpoints:[...ty(r,r.length?r[r.length-1].id:null),{...a,status:"applied"}],activeCheckpointId:a.id}}(ed,e0.current,S);if(ep(C.checkpoints),eh(C.activeCheckpointId),e0.current=C.activeCheckpointId,aR(C.checkpoints,C.activeCheckpointId),(0,ey.trackEvent)("ai_editor_apply_succeeded",{projectId:e.id,planId:t.id,operationCount:t.operations.length,successfulReceipts:d.length,failedReceipts:c.length,partialCommit:u}),Y("applied"),eF(p),el(u),t0([u?{stage:"failed",text:p??`Applied ${d.length} of ${s.receipts.length} steps â the rest failed.`}:{stage:"applied",text:`Apply complete (${d.length}/${s.receipts.length} successful).`}]),s.pendingGenerations&&s.pendingGenerations.length>0)for(let e of s.pendingGenerations)e.sceneId,e.aspectRatio,e.durationTarget,a2(e.sceneId,e.prompt,e.aspectRatio,e.durationTarget,w,e);return s.pendingRegenerations&&s.pendingRegenerations.length>0&&a8(s.pendingRegenerations,w),!0},a1=async(e,t)=>{let a=tE.current,r=a.scenes.find(t=>t.id===e);if(!r)return;if((r.media?.url??"").trim()||(r.url??"").trim()){let t={...a,scenes:a.scenes.map(t=>t.id===e?{...t,media:t.media?{...t.media,status:"ready"}:t.media,updatedAt:Date.now()}:t),updatedAt:Date.now()};tE.current=t,j(t);try{await I(t)}catch{}return}let n=new Set([e]);(0,eI.g_)([e]);let i={...a,scenes:a.scenes.filter(e=>!n.has(e.id)),updatedAt:Date.now()};tE.current=i,j(i);try{await I(i)}catch{}Array.from(n)},a5=(C={project:e,projectRef:tE,updateProject:j,saveProject:I,onSceneUpdated:(e,t)=>{if(tE.current.id!==e)return;let a=aE(eu.current,e,t);a!==eu.current&&(e5.current+=1,ep(a),aR(a,e0.current)),(0,av.g)()},onFailed:async(e,t)=>{await a1(e,t),t0([{stage:"failed",text:t}])},onMessage:(e,t)=>t0([{stage:e,text:t}])},(M=(0,i.useRef)(C)).current=C,_=(0,i.useRef)(new Map),A=(0,i.useRef)(!0),(0,i.useEffect)(()=>(A.current=!0,()=>{for(let e of(A.current=!1,_.current.values()))e.cancelled=!0;_.current.clear()}),[]),E=async(e,t)=>{let a=M.current.projectRef.current,r=a.scenes.find(t=>t.id===e.scene_id);if(!A.current||a.id!==e.project_id||r?.media?.status!=="generating")return;let n=r.generationJobId||void 0;if(t&&t!==n)return;let i=t??n,s=`${e.project_id}:${e.scene_id}`,o=_.current.get(s);if(o&&!o.cancelled&&!o.settled&&i===o.jobId)return;o&&(o.cancelled=!0);let l={projectId:e.project_id,sceneId:e.scene_id,jobId:i,cancelled:!1};_.current.set(s,l);let d=()=>M.current.projectRef.current.scenes.find(e=>e.id===l.sceneId),c=()=>A.current&&!l.cancelled&&_.current.get(s)===l&&M.current.projectRef.current.id===l.projectId&&d()?.media?.status==="generating"&&(!l.jobId||d()?.generationJobId===l.jobId),u=async e=>{if(!A.current||l.cancelled||M.current.projectRef.current.id!==l.projectId)return;let t=M.current,a={...t.projectRef.current,scenes:t.projectRef.current.scenes.map(t=>
73t.id===e.id?e:t),updatedAt:Date.now()};t.projectRef.current=a,t.updateProject(a),t.onSceneUpdated(a.id,e),await t.saveProject(a)};try{if(!c())return;if(!l.jobId){let t=await (0,aA.qZ)(e);if(!c())return;if(!t.success&&t.error?.message?.toLowerCase().includes("project not found")&&(await M.current.saveProject(M.current.projectRef.current),!c()||(t=await (0,aA.qZ)(e),!c())))return;if(!t.success||!t.data?.jobId)return void await M.current.onFailed(l.sceneId,t.error?.message??"Generation job creation failed.");let a=d(),r=t.data.jobId,n={...a,generationJobId:r,generation:{...a.generation,generation_job_id:r},updatedAt:Date.now()};l.jobId=r;try{await u(n)}catch{c()&&M.current.onMessage("failed","The generation job started, but saving its progress failed. No second job was created.")}}if(!c()||!l.jobId)return;let t=await (0,eg.Ar)(l.jobId,void 0,()=>!c(),{jobType:"scene_video"});if(!c())return;if(t.jobId!==l.jobId)throw Error("Generation returned a different job. No media was attached.");if("completed"===t.status||"ready"===t.status){let e=function(e,t,a){let r=e.scenes.find(e=>e.id===t);if(!r||r.media?.status!=="generating"||r.generationJobId!==a.jobId||"ready"!==a.status&&"completed"!==a.status)return null;let n=a.resultMediaKey||void 0,i=n?`r2://${n}`:a.resultUrl;if(!i)throw Error("Generation completed without playable media.");let s=a.resultDuration??r.media.duration;if(!Number.isFinite(s)||!s||s<=0)throw Error("Generation completed without a valid media duration.");return{...r,url:i,media:{...r.media,type:"video",url:i,status:"ready",duration:s,...a.resultWidth?{width:a.resultWidth}:{},...a.resultHeight?{height:a.resultHeight}:{},...n?{storageKey:n,isStorageBacked:!0,assetRef:{type:"r2",storageKey:n}}:{}},generation:{...r.generation,generation_job_id:a.jobId,duration_returned:s,generated_at:new Date().toISOString()},generationJobId:a.jobId,updatedAt:Date.now()}}(M.current.projectRef.current,l.sceneId,t);if(!e)return;l.completing=!0;try{await u(e),A.current&&!l.cancelled&&M.current.projectRef.current.id===l.projectId&&M.current.onMessage("applied","Generated clip added and saved.")}catch{A.current&&!l.cancelled&&M.current.projectRef.current.id===l.projectId&&M.current.onMessage("failed","The generated clip is available, but saving failed. Save again; do not generate it again.")}}else"failed"===t.status||"cancelled"===t.status?await M.current.onFailed(l.sceneId,t.error??"Generation did not complete."):M.current.onMessage("failed",t.error??"Could not confirm generation yet. Reopen the project to check the same job without generating again.")}catch(e){c()&&M.current.onMessage("failed",e instanceof Error?e.message:"Could not verify generation.")}finally{l.settled=!0}},(0,i.useEffect)(()=>{for(let[e,t]of _.current){let a=C.project.scenes.find(e=>e.id===t.sceneId);(t.projectId!==C.project.id||!a||a.media?.status!=="generating"||t.jobId&&a.generationJobId!==t.jobId)&&(t.completing&&t.projectId===C.project.id&&a?.media?.status==="ready"&&a.generationJobId===t.jobId||(t.cancelled=!0),_.current.delete(e))}for(let e of C.project.scenes){if(!e.id.startsWith("gen-")||e.media?.status!=="generating"||!e.generationJobId)continue;let t=`${C.project.id}:${e.id}`;_.current.has(t)||E({project_id:C.project.id,scene_id:e.id,prompt:e.generation?.prompt??"",aspect_ratio:C.project.aspectRatio,duration_target:e.media.duration??5,project_mode:"local"===C.project.mode?"local":"cloud"},e.generationJobId)}},[C.project.id,C.project.scenes]),{start:E});(0,i.useEffect)(()=>{let t=ed;for(let a of e.scenes)a.id.startsWith("gen-")&&a.generationJobId&&(t=aE(t,e.id,a));t!==ed&&(ep(t),aR(t,e0.current))},[e.id,e.scenes,ed]);let a2=async(e,t,a,r,n,i)=>{if(tA.current||tE.current.id!==n.id)return;let s=i?function(e,t){let{generation:a}=e,{references:r}=a;return{project_id:t.id,project_mode:"local"===t.mode?"local":"cloud",scene_id:e.sceneId,idempotency_key:e.idempotencyKey,prompt:e.prompt,aspect_ratio:e.aspectRatio,duration_target:e.durationTarget,job_type:"scene_video",videoModel:a.videoModel,videoProvider:a.videoProvider,videoQualityTier:a.videoQualityTier,generateAudio:!1,...r.length?{referenceImageUrl:r[0].url,referenceAssets:r.map(({sceneId:e,...t})=>t),imageGuidanceMode:a.imageGuidanceMode}:{}}}(i,n):{project_id:n.id,scene_id:e,project_mode:"local"===n.mode?"local":"cloud",prompt:t,aspect_ratio:a,duration_target:r,idempotency_key:`ai-editor-regen:${n.id}:${e}:${(0,v.generateId)()}`};await a5.start(s)},a4=async(e,t)=>{for(let a=0;a<40;a+=1){let a={nleSceneId:t};
73if(window.dispatchEvent(new CustomEvent(e,{detail:a})),a.handled)return!0;await new Promise(e=>setTimeout(e,200))}return!1},a3=(e,t)=>rK(e.scenes).numberById.get(t)??null,a8=async(t,a)=>{let r=t.filter(e=>"voiceover_beat"===e.type),n=t.filter(e=>"voiceover_beat"!==e.type);for(let e of r){let t;if("voiceover_beat"===e.type){t0([{stage:"applying",text:"Re-rendering marketing voiceover beatâ¦"}]);try{t=await aq(e.blockId)}catch(e){t={outcome:"failed",reason:e instanceof Error?e.message:"unknown error"}}t0([r$(t)])}}if(0===n.length)return;let i=e=>e.source?.platform==="faceless-generator"||!!e.facelessPlanSceneId,s=[];for(let t of n){let a=tE.current.scenes.find(e=>e.id===t.sceneId);if(!a)continue;let r=a3(tE.current,a.id),n=r?`scene ${r}`:"that scene";if("scene_visual"===t.type){let r=a.source?.platform==="ai-generation"&&"string"==typeof a.generation?.prompt?a.generation.prompt.trim():"";if(r){t0([{stage:"applying",text:`Re-rendering AI-generated ${n} from its stored promptâ¦`}]);let t={...tE.current,scenes:tE.current.scenes.map(e=>e.id===a.id?{...e,media:e.media?{...e.media,status:"generating"}:e.media,updatedAt:Date.now()}:e),updatedAt:Date.now()};j(t),a2(a.id,r,e.aspectRatio??"9:16",a.media?.duration??5,t);continue}if(!i(a)){t0([{stage:"failed",text:`${n[0].toUpperCase()}${n.slice(1)}'s media wasn't AI-generated, so there's no stored prompt to re-render. Try "generate a new scene of â¦" instead.`}]);continue}s.push(t);continue}if(i(a)){s.push(t);continue}let o=(tE.current.audio??[]).find(e=>"voiceover"===e.type&&(e.text??"").trim().length>0&&(e.sourceSceneId===a.id||"number"==typeof e.start&&"number"==typeof a.timelineStart&&e.start>=a.timelineStart-.25&&e.start<a.timelineStart+((a.media?.trim?.end??a.media?.duration??5)-(a.media?.trim?.start??0))));o?(t0([{stage:"applying",text:`Re-rendering the voiceover on ${n}â¦`}]),t0([r$(await aq(o.id),{sceneLabel:n})])):t0([{stage:"failed",text:`${n[0].toUpperCase()}${n.slice(1)} has no AI voiceover to regenerate.`}])}if(0!==s.length)for(let e of(eE("generate"),s)){let t="scene_visual"===e.type?"visuals":"voiceover",a=a3(tE.current,e.
73sceneId),r=a?`scene ${a}`:"a scene";await a4(rC[e.type],e.sceneId)?t0([{stage:"applying",text:`Regenerating ${t} for ${r} in the Video Studioâ¦`}]):t0([{stage:"failed",text:`The Video Studio didn't pick up the ${t} regeneration for ${r}. Open the Generate tab and use that scene's Regenerate action instead.`}])}},a6=async()=>{var e;if(!G)return;let t=tN(G,tE.current);if(t.blocked||JSON.stringify(t)!==JSON.stringify(ac))return void eF("Generation settings or source images changed. Review the current estimate before applying.");let a={...G,operations:G.operations.map((e,a)=>{if("generate_scene_visual"!==e.kind)return e;let r=t.entries.find(e=>e.operationIndex===a)?.spec;return r?{...e,videoModel:r.videoModel,videoQualityTier:r.videoQualityTier,imageGuidanceMode:r.imageGuidanceMode}:e})},r=a.operations.filter(e=>rN(e).executable);if(0===r.length)return;if(r.length!==a.operations.length){let e=a.operations.length-r.length;a={...a,operations:r,warnings:[...a.warnings,`Skipped ${e} step(s) that cannot run yet during manual apply.`]}}let n=a.resolvedSceneTarget?.sceneId;Q&&n&&Q!==n&&(a={...e=a,operations:e.operations.map(e=>{if(!rV.has(e.kind)||!(e.sceneId===n||e.scope?.type==="scene_ids"&&e.scope?.sceneIds?.includes(n)))return e;let t={...e};return t.sceneId===n&&(t.sceneId=Q),t.scope?.type==="scene_ids"&&(t.scope={...t.scope,sceneIds:t.scope.sceneIds.map(e=>e===n?Q:e)}),t})});let i=Q??a.resolvedSceneTarget?.sceneId??tf(a),s=i?ah.numberById.get(i)??0:0;await a0(a,{messageId:J??void 0,autoApplied:!1,targetSceneLabel:s>0?`Scene ${s}`:null})&&(X(null),Z(null))},a9=async(t,a,r,n)=>{aO();let i=tE.current,s=y.zC.getState().projectTime;window.__AI_REAPPLY_TRACE__={active:!0,startedAtMs:Date.now(),captureUntilMs:Date.now()+2e3,lockProjectTime:s,projectId:e.id,nextActiveCheckpointId:r,actionLabel:n},Y("applying"),eF(null);try{if(await aM({currentProject:i,snapshot:t,updateProject:e=>{tE.current=e,j(e)},saveProject:I,getCurrentProject:()=>tE.current,isProjectCurrent:()=>tE.current.id===i.id}),tE.current.id!==i.id)return!1;return ep(a),eh(r),e0.current=r,aR(a,r),ea([n]),es(n),el(!1),X(null),Z(null),tk(null),Y("idle"),y.zC.getState().setProjectTime(s),!0}catch(e){if(tE.current.id!==i.id)return!1;return Y("failed"),eF(e instanceof Error?e.message:"Failed to restore AI checkpoint."),!1}},a7=async()=>{if(!t1)return;let e=tv(ed,em);e&&await a9(e.projectSnapshot,e.checkpoints,e.activeCheckpointId,`Unapplied: ${t1.planSummary}`)},re=async()=>{if(!t1)return;let e=function(e){if(0===e.length)return null;let t=e[e.length-1];return{checkpoints:ty(e,t.id),activeCheckpointId:t.id,projectSnapshot:tg(t.afterProject)}}(ed);e&&await a9(e.projectSnapshot,e.checkpoints,e.activeCheckpointId,`Reapplied: ${t1.planSummary}`)},rt=async t=>{let a,r=ed.find(e=>e.id===t);if(!r)return;let n=(a=ed.find(e=>e.id===t))?{checkpoints:ty(ed,t),activeCheckpointId:t,projectSnapshot:tg(a.afterProject)}:null;if(!n)return;let i={project:structuredClone(e),checkpoints:structuredClone(ed),activeCheckpointId:em,targetCheckpointId:t};await a9(n.projectSnapshot,n.checkpoints,n.activeCheckpointId,`Restored to: ${r.planSummary}`)&&(tC.current=i,t_(t))},ra=async()=>{let e=tC.current;e&&(tC.current=null,t_(null),await a9(e.project,e.checkpoints,e.activeCheckpointId,"Undid restore"))},rr=()=>{aO(),X(null),Z(null),ee(null),tk(null),ea([]),es(null),el(!1),Y("idle")},rn="thinking"===H?"Thinking":"planning"===H?"Preparing plan":"applying"===H?G?.operations.some(e=>"generate_captions"===e.kind)?"Generating captions":"Applying edit":null,ri=!!(t1&&t1.id===em),ro=tM?"Undo restore":ri?"Undo":t1?"Reapply":"Undo",rl=tM?"Undo the most recent restore action":ri?"Undo latest AI edit":t1?"Reapply latest AI edit":"No AI edits to undo",rd=(!!tM||!!t1)&&"applying"!==H,rS=rO(eO?.requestId??null),rj=er.length>0?er[er.length-1]:null,rM=ei??rj?.text??(rS?"Waiting for the next AI request.":"No recent execution activity."),r_=(0,r.jsx)(aX,{onOpenSceneEffects:eN,onOpenSceneCaptions:eC,onOpenSceneVoiceover:eM,onOpenSceneTransition:e_,liveProject:e,onUpdateProject:j,onSaveProject:I,onMinimizePanel:o?void 0:f,sceneCount:R,progress:D});return(0,r.jsxs)(rp,{collapsed:n,compact:s,onToggleCollapsed:f,hasPlan:!!G,statusClassName:{idle:"text-zinc-500",thinking:"text-blue-400",planning:"text-blue-400",applying:"text-blue-400",applied:"text-blue-400",failed:"text-red-400"}[H],progress:D,children:[(0,r.jsxs)("div",{className:"absolute top-3 right-3 z-10 flex items-center gap-1 max-[900px]:hidden",children:[S&&(0,r.jsx)("button",{type:"button",onClick:S,title:b?"Exit full screen":"Full screen","data-testid":"ai-rail-fullscreen-toggle",className:"p-1.5 rounded text-zinc-500 transition-colors hover:bg-white/[0.06] hover:text-zinc-300",children:b?(0,r.jsx)(e9.A,{className:"h-3.5 w-3.5"}):(0,r.jsx)(e7.A,{className:"h-3.5 w-3.5"})}),!o&&(0,r.jsx)("button",{type:"button",onClick:f,title:"Minimize panel",className:"p-1.5 rounded text-zinc-500 transition-colors hover:bg-white/[0.06] hover:text-zinc-300",children:(0,r.jsx)(te.A,{className:"h-3.5 w-3.5"})})]}),(0,r.jsxs)("div",{className:"px-3 pt-2.5 pb-2 border-b border-white/[0.06] max-[900px]:px-4 max-[900px]:pt-4",children:[(0,r.jsxs)("div",{className:`flex items-center justify-between gap-2 ${b?"mx-auto w-full max-w-3xl":""}`,children:[(0,r.jsxs)("span",{className:"flex min-w-0 items-center gap-1.5",children:[(0,r.jsx)("span",{className:`text-[12px] font-semibold uppercase tracking-[0.18em] transition-colors duration-300 ${"generate"===eA?"text-amber-200":"marketing"===eA?"text-cyan-200":"text-zinc-200"}`,children:"generate"===eA?"Video Studio":"marketing"===eA?"Marketing Studio":"influencer"===eA?"AI Influencer":"AI Editor"}),"marketing"===eA&&(0,r.jsx)("span",{"data-testid":"marketing-studio-beta-badge",title:"The Marketing Studio is in beta - some tools are still rough around the edges",className:"shrink-0 rounded-full border border-red-400/40 bg-red-500/10 px-1.5 py-px text-[8px] font-bold uppercase tracking-[0.14em] text-red-300",children:"Beta"}),"editor"===eA&&!d.Wg.AI_EDITOR_ACTIVE&&(0,r.jsx)("span",{"data-testid":"ai-editor-soon-badge",title:"The AI Editor is coming soon",className:"shrink-0 rounded-full border border-amber-400/40 bg-amber-500/10 px-1.5 py-px text-[8px] font-bold uppercase tracking-[0.14em] text-amber-300",children:"Soon"})]}),(0,r.jsxs)("div",{className:`flex items-center gap-0.5 max-[900px]:mr-0 ${"editor"===eA&&d.Wg.AI_EDITOR_ACTIVE&&!o?S?"mr-16":"mr-9":"editor"===eA&&d.Wg.AI_EDITOR_ACTIVE&&S?"mr-9":""}`,children:["editor"===eA&&d.Wg.AI_EDITOR_ACTIVE&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",onClick:tM?ra:ri?a7:re,disabled:!rd,className:"mr-1 inline-flex items-center gap-1 rounded-md bg-white/[0.06] px-2 py-1 text-[10px] font-medium uppercase tracking-wide text-zinc-300 transition-colors hover:bg-white/[0.10] disabled:cursor-not-allowed disabled:opacity-40",title:rl,children:[(0,r.jsx)(tt.A,{size:11}),ro]}),(0,r.jsx)("button",{type:"button",className:"p-1.5 rounded hover:bg-white/[0.06] text-zinc-500 hover:text-zinc-300 transition-colors",onClick:()=>ev(e=>!e),title:"AI settings",children:(0,r.jsx)(ta.A,{size:13})}),(0,r.jsxs)("span",{className:"relative",children:[(0,r.jsx)("button",{type:"button",className:`p-1.5 rounded transition-colors hover:bg-white/[0.06] hover:text-zinc-300 ${ew?"bg-white/[0.06] text-zinc-300":"text-zinc-500"}`,onClick:()=>ek(e=>!e),title:"Clear chat","data-testid":"ai-rail-clear-chat",children:(0,r.jsx)(tr.A,{size:13})}),ew&&(0,r.jsx)(nt,{onCancel:()=>ek(!1),onConfirm:()=>{ek(!1),aO(),t$.current+=1;let t=tT.current;t&&(tT.current=null,t.abort()),U([]),X(null),Z(null),ee(null),tk(null),ea([]),en([]),es(null),el(!1),ep([]),eh(null),e0.current=null,tI({}),Y("idle"),eF(null),eB(null),e4.current=[],e3.current.clear(),tC.current=null,t_(null);try{localStorage.removeItem(t8),localStorage.removeItem(t9),localStorage.removeItem(t6),localStorage.removeItem(t7)}catch{}L&&(0,af.Kg)(e.id).then(t=>{t.success||console.warn("[AI-EDITOR] failed to clear backend history",{projectId:e.id,error:t.error?.message})})}})]})]}),!o&&(0,r.jsxs)("button",{type:"button",onClick:f,"data-testid":"ai-rail-mobile-minimize",className:"hidden shrink-0 items-center gap-1 rounded-lg bg-white/[0.1] px-2.5 py-1.5 text-[11px] font-semibold text-zinc-100 ring-1 ring-white/15 transition-colors hover:bg-white/[0.16] max-[900px]:inline-flex",children:["Minimize",(0,r.jsx)(tn.A,{className:"h-3.5 w-3.5"})]})]})]}),(0,r.jsx)(aJ,{activeTab:eA,onSelect:aK,editorActive:d.Wg.AI_EDITOR_ACTIVE,fullscreen:b})]}),"generate"===eA?r_:"influencer"===eA?(0,r.jsx)(rs,{project:e,onUpdateProject:j,onSaveProject:I,fullscreen:b,generationBusy:!!D,children:r_}):"marketing"===eA?(0,r.jsx)("div",{className:"flex-1 overflow-y-auto scrollbar-hidden","data-ai-rail-scroll-viewport":!0,children:(0,r.jsxs)("div",{className:`space-y-4 p-3 pb-5 ${b?"mx-auto w-full max-w-3xl":""}`,children:[(0,r.jsx)("div",{role:"tablist","aria-label":"Marketing studio section",className:"flex rounded-lg border border-white/[0.07] bg-[#0f0f16] p-0.5",children:[{key:"product",label:"Product studio"},{key:"website",label:"Website studio"}].map(e=>
73{let t=tR===e.key;return(0,r.jsx)("button",{type:"button",role:"tab","aria-selected":t,onClick:()=>tL(e.key),"data-testid":`marketing-section-${e.key}`,className:`flex-1 rounded-md px-2.5 py-1 text-center text-[10px] font-medium transition-colors ${t?"bg-white/10 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,children:e.label},e.key)})}),"product"===tR?(0,r.jsx)(rc,{}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"rounded-xl border border-white/[0.06] bg-[#0f0f16] p-3.5",children:(0,r.jsxs)("div",{className:"flex items-start gap-2.5",children:[(0,r.jsx)("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-white/[0.08] bg-white/[0.04] text-cyan-300/90",children:(0,r.jsx)(ti.A,{className:"h-4 w-4"})}),(0,r.jsxs)("div",{className:"min-w-0",children:[(0,r.jsx)("h3",{className:"text-[13px] font-semibold text-zinc-100",children:"Marketing Studio"}),(0,r.jsx)("p",{className:"mt-1 text-[11px] leading-5 text-zinc-500",children:tF.segments.length>0?"Your recording, auto-edited. The voiceover script is below.":"Turn a screen recording into an auto-edited product demo."})]})]})}),tF.segments.length>0?(0,r.jsxs)("div",{className:"rounded-xl border border-white/[0.06] bg-[#0f0f16] p-3.5",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,r.jsxs)("p",{className:"flex items-center gap-2 text-[10px] font-semibold uppercase tracking-[0.16em] text-zinc-500",children:[(0,r.jsx)(ts.A,{className:"h-3.5 w-3.5 text-zinc-500"}),"Voiceover script"]}),(0,r.jsxs)("span",{className:"text-[10px] tabular-nums text-zinc-600",children:[tF.segments.length," ",1===tF.segments.length?"beat":"beats"]})]}),(0,r.jsx)("div",{className:"mt-3 space-y-2",children:tF.segments.map(e=>{let t="error"===e.status,a="ready"!==e.status&&!t,n=tO===e.id,i=tU[e.id]??e.text,s="string"==typeof tU[e.id]&&tU[e.id].trim().length>0&&tU[e.id].trim()!==e.text.trim(),o=Math.min(8,Math.max(2,Math.ceil(i.length/46)+(i.match(/\n/g)?.length??0)));return(0,r.jsxs)("div",{className:`rounded-lg border px-2.5 py-2 ${t?"border-red-500/30 bg-red-500/[0.06]":a?"border-amber-500/25 bg-amber-500/[0.05]":"border-white/[0.05] bg-white/[0.02]"}`,children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,r.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,r.jsx)(aU,{startSeconds:e.startSeconds,disabled:null!==tO,dragScaleSecondsPerPixel:tq,onBegin:()=>tG(e.id),onPreview:t=>tX(e.id,t),onCommit:t=>tJ(e.id,t),onCancel:()=>tZ(e.id)}),t&&(0,r.jsxs)("span",{className:"inline-flex items-center gap-1 rounded-full border border-red-500/30 bg-red-500/10 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-red-300",children:[(0,r.jsx)(g.A,{className:"h-2.5 w-2.5"}),"Failed"]}),a&&(0,r.jsx)("span",{className:"inline-flex items-center gap-1 rounded-full border border-amber-500/30 bg-amber-500/10 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-amber-300",children:"Not generated"}),s&&(0,r.jsx)("span",{className:"inline-flex items-center gap-1 rounded-full border border-emerald-500/30 bg-emerald-500/10 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-emerald-300",children:"Edited"})]}),(0,r.jsxs)("button",{type:"button",onClick:()=>void aq(e.id),disabled:null!==tO,className:`inline-flex shrink-0 items-center gap-1 rounded-md border px-1.5 py-0.5 text-[10px] font-medium transition-colors disabled:opacity-50 ${t?"border-red-500/30 bg-red-500/10 text-red-200 hover:bg-red-500/20":a?"border-amber-500/30 bg-amber-500/10 text-amber-200 hover:bg-amber-500/20":s?"border-emerald-500/40 bg-emerald-500/10 text-emerald-200 hover:bg-emerald-500/20":"border-white/[0.08] bg-white/[0.04] text-zinc-300 hover:bg-white/[0.08]"}`,title:t?"Retry this failed voiceover beat":a?"Generate this voiceover beat":s?"Regenerate this beatâs voiceover and captions from your edited text":"Redo this voiceover beat (voiceover + captions)",children:[n?(0,r.jsx)(x.A,{className:"h-3 w-3 animate-spin"}):(0,r.jsx)(to.A,{className:"h-3 w-3"}),n?"Generating":t?"Retry":a?"Generate":"Redo"]})]}),(0,r.jsx)("textarea",{value:i,onChange:t=>tY(e.id,t.target.value,e.text),disabled:n,rows:o,spellCheck:!1,"aria-label":"Beat script",className:`mt-1 w-full resize-none rounded-md border border-transparent bg-transparent px-1 py-0.5 text-[12px] leading-5 outline-none transition-colors focus:border-white/[0.12] focus:bg-white/[0.03] disabled:opacity-60 ${t?"text-red-100/80":a?"text-amber-100/80":"text-zinc-300"}`})]},e.id)})}),(0,r.jsx)("p",{className:"mt-3 text-[11px] leading-4 text-zinc-500",children:"Click a beat's time to type a new start - or drag the green handle to slide the narration and its captions along the timeline together. Edit a beat's text and hit Redo to re-render that beat's voiceover and captions."})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)(e8(),{href:"/record",className:"group flex w-full items-center justify-center gap-2 rounded-lg border border-white/[0.12] bg-white/[0.10] px-4 py-3 text-sm font-semibold text-zinc-100 transition-colors hover:border-white/[0.18] hover:bg-white/[0.16]",children:[(0,r.jsx)(tl.A,{className:"h-4 w-4"}),"Create Marketing Video",(0,r.jsx)(td.A,{className:"h-3.5 w-3.5 transition-transform group-hover:translate-x-0.5"})]}),(0,r.jsxs)("div",{className:"rounded-xl border border-white/[0.06] bg-[#0f0f16] p-3.5",children:[(0,r.jsxs)("p",{className:"flex items-center gap-2 text-[10px] font-semibold uppercase tracking-[0.16em] text-zinc-500",children:[(0,r.jsx)(eD.A,{className:"h-3.5 w-3.5 text-zinc-500"}),"How it works"]}),(0,r.jsx)("ol",{className:"mt-3",children:["Record a product flow.","Polish on the timeline with captions, zoom and voiceover.","Export, then schedule posts to your socials."].map((e,t,a)=>(0,r.jsxs)("li",{className:"relative flex gap-2.5 pb-3 last:pb-0",children:[t<a.length-1&&(0,r.jsx)("span",{className:"absolute left-[9px] top-[18px] h-full w-px bg-white/[0.08]"}),(0,r.jsx)("span",{className:"relative z-10 flex h-[18px] w-[18px] shrink-0 items-center justify-center rounded-full border border-white/[0.10] bg-white/[0.05] text-[10px] font-semibold text-zinc-300",children:t+1}),(0,r.jsx)("span",{className:"pt-px text-[11px] leading-4 text-zinc-400",children:e})]},e))})]})]})]})]})}):d.Wg.AI_EDITOR_ACTIVE?(0,r.jsxs)(r.Fragment,{children:[eb&&(0,r.jsx)(r7,{planningMode:e$,onChangePlanningMode:e=>{eP(e);try{localStorage.setItem(ae,e),localStorage.removeItem(rw)}catch{eF("Could not store AI settings in this browser session.")}},plannerModel:eR,onChangePlannerModel:ez,onClose:()=>ev(!1),fullscreen:b}),(0,r.jsxs)("div",{ref:eH,"data-ai-rail-scroll-viewport":!0,className:`flex-1 overflow-y-auto px-3 py-3 space-y-2.5 ${b?"mx-auto w-full max-w-3xl":""} 74 [overflow-wrap:anywhere] 75 [scrollbar-width:thin] 76 [scrollbar-color:rgba(51,65,85,0.4)_transparent] 77 [&::-webkit-scrollbar]:w-1 78 [&::-webkit-scrollbar-track]:bg-transparent 79 [&::-webkit-scrollbar-thumb]:bg-slate-700/40 80 [&::-webkit-scrollbar-thumb]:rounded-full 81 [&::-webkit-scrollbar-thumb:hover]:bg-slate-600/50`,children:[0===W.length&&(aa||l?(0,r.jsx)("div",{className:"text-xs text-zinc-500 leading-relaxed",children:"Describe an edit and review the plan before applying."}):(0,r.jsx)(r5,{fullscreen:b,onPickPrompt:aN})),W.map(e=>{let t,a,n,i,s,o=t5.get(e.id)??[],l="user"===e.role,d=function(e){if(!Number.isFinite(e)||e<=0)return null;try{return new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return null}}(e.createdAt);return(0,r.jsx)("div",{className:`flex ${l?"justify-end":"justify-start"}`,children:(0,r.jsxs)("div",{title:d??void 0,className:`group rounded-lg px-3 py-2 leading-relaxed max-w-[88%] ${b?"text-[13px]":"text-xs"} ${l?"bg-white/[0.08] text-zinc-100":"assistant"===e.role?"border border-white/[0.07] bg-[#15151f] text-zinc-300":"bg-[#12121a]/60 text-zinc-500"}`,children:[!l&&(0,r.jsxs)("div",{className:"mb-1 flex items-center gap-1.5 text-[9px] font-medium uppercase tracking-widest text-zinc-500",children:[(0,r.jsx)(tc.A,{size:10,
81className:"assistant"===e.role?"text-blue-400/80":"text-zinc-600"}),(0,r.jsx)("span",{children:e.role}),d&&(0,r.jsx)("span",{className:"ml-auto normal-case tracking-normal text-zinc-600 opacity-0 transition-opacity group-hover:opacity-100",children:d})]}),(0,r.jsx)("div",{className:"whitespace-pre-wrap break-words",children:e.content}),G&&J===e.id&&(t=G.resolvedSceneTarget,a=G.operations.some(e=>rV.has(e.kind)),i=(n=Q??t?.sceneId)?ah.numberById.get(n):void 0,s=rF(G,{autoApplied:!1}),(0,r.jsxs)("div",{className:"mt-2 rounded-md border border-amber-500/15 bg-amber-500/[0.03] p-2 text-[11px]",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,r.jsx)("span",{className:"text-[10px] text-amber-400 font-semibold uppercase tracking-wide",children:"Plan Preview"}),(0,r.jsx)("span",{className:"text-zinc-500",children:1===G.operations.length?"1 step":`${G.operations.length} steps`})]}),(0,r.jsx)(r4,{text:s}),(0,r.jsx)(r8,{operations:G.operations,sceneNumberById:ah.numberById}),(0,r.jsx)(a_,{plan:G,review:ac,onChange:X}),a&&i&&(0,r.jsxs)("div",{className:"mt-1.5 flex items-center gap-2",children:[(0,r.jsx)("span",{className:"text-zinc-400",children:"Target:"}),(0,r.jsx)("select",{value:n??"",onChange:e=>ee(e.target.value||null),className:"rounded-md bg-[#16161e] border border-white/[0.08] px-1.5 py-0.5 text-[11px] text-zinc-200 focus:outline-none",children:ah.orderedScenes.map(e=>(0,r.jsxs)("option",{value:e.id,children:["Scene ",ah.numberById.get(e.id),e.id===t?.sceneId?" (original)":""]},e.id))}),t&&!Q&&(0,r.jsx)("span",{className:"text-[10px] text-zinc-500 italic",children:{explicit:"from prompt",context_same_effect:"continued from prior edit",context_same_family:"inferred from similar effect",context_last_scene:"last edited scene",selected:"currently selected"}[t.resolution]??t.resolution}),Q&&Q!==t?.sceneId&&(0,r.jsx)("span",{className:"text-[10px] text-amber-400 italic",children:"overridden"})]}),G.warnings.length>0&&(0,r.jsx)("ul",{className:"mt-1.5 space-y-0.5 text-amber-400",children:G.warnings.slice(0,3).map((e,t)=>(0,r.jsxs)("li",{children:["- ",e]},`${e}-${t}`))}),ag.length>0&&(0,r.jsx)("ul",{className:"mt-1.5 space-y-0.5 text-amber-300","data-testid":"ai-rail-blocked-step-notes",children:ag.map((e,t)=>(0,r.jsxs)("li",{children:["- ",e]},`${e}-${t}`))}),al&&!G.safeToApply&&(0,r.jsx)("p",{className:"mt-1.5 text-[10px] text-amber-300",children:"Plan is preview-only; review warnings, then apply manually if it matches intent."}),(0,r.jsxs)("div",{className:"mt-2.5 flex justify-end gap-2",children:[(0,r.jsx)("button",{type:"button",onClick:rr,className:"inline-flex h-8 items-center rounded-md border border-white/[0.08] px-3 text-[12px] text-zinc-400 transition-colors hover:bg-white/[0.06] hover:text-zinc-200",children:"Cancel"}),(0,r.jsx)("button",{type:"button",onClick:a6,disabled:!au,"data-testid":"ai-rail-apply-plan",className:"inline-flex h-8 items-center rounded-md bg-amber-500 px-3 text-[12px] font-semibold text-[#1c1204] transition-colors hover:bg-amber-400 disabled:cursor-not-allowed disabled:opacity-50",children:ap})]})]})),o.length>0&&!(G&&J===e.id)&&(0,r.jsx)("div",{className:"mt-2 space-y-1.5",children:o.map((e,t)=>{let a=t1?.id===e.id;return(0,r.jsx)(r6,{label:a?"Applied edit":o.length>1?`Checkpoint ${t+1}`:"Checkpoint",planSummary:e.planSummary,statusText:e.status,isLatest:a,isActive:e.id===em,autoApplied:e.autoApplied,targetSceneLabel:e.targetSceneLabel,resolutionText:tj[e.planId]??null,applying:"applying"===H,showUndoRestore:tM===e.id,onUnapply:a7,onReapply:re,onUndoRestore:ra,onRestore:()=>rt(e.id)},e.id)})})]})},e.id)}),t4.length>0&&(0,r.jsx)("div",{className:"space-y-1.5",children:t4.map(e=>{let t=t1?.id===e.id;return(0,r.jsx)(r6,{label:t?"Applied edit":"Checkpoint",planSummary:e.planSummary,statusText:e.status,isLatest:t,isActive:e.id===em,autoApplied:e.autoApplied,targetSceneLabel:e.targetSceneLabel,resolutionText:tj[e.planId]??null,applying:"applying"===H,showUndoRestore:tM===e.id,onUnapply:a7,onReapply:re,onUndoRestore:ra,onRestore:()=>rt(e.id)},e.id)})}),rn&&(0,r.jsxs)("div",{className:`rounded-lg border border-white/[0.07] bg-[#15151f] px-3 py-2 leading-relaxed text-zinc-300 ${b?"text-[13px]":"text-xs"}`,children:[(0,r.jsxs)("div",{className:"mb-1 flex items-center gap-1.5 uppercase tracking-widest text-[9px] font-medium text-zinc-500",children:[(0,r.jsx)(tc.A,{size:10,
81className:"text-blue-400/80"}),"assistant"]}),(0,r.jsxs)("div",{className:"flex items-center gap-2 text-zinc-300",children:[(0,r.jsx)(x.A,{size:12,className:"animate-spin text-blue-400"}),(0,r.jsxs)("span",{children:[rn,(0,r.jsx)(r0,{})]})]})]}),(er.length>0||rS)&&(0,r.jsx)(r9,{entries:er,summaryText:rM,detailsOpen:eo,onToggleDetails:()=>el(e=>!e)}),th&&!G&&(0,r.jsx)("div",{className:`rounded-md p-2.5 ${"failed"===H?"border border-red-500/40 bg-red-500/5":"border border-blue-500/25 bg-blue-500/[0.06]"}`,children:(0,r.jsx)("div",{className:`text-[11px] font-medium flex items-center gap-1.5 ${"failed"===H?"text-red-300":"text-blue-300"}`,children:"applying"===H?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(x.A,{size:10,className:"animate-spin"})," Applying to"," ",th,"â¦"]}):"failed"===H?(0,r.jsxs)(r.Fragment,{children:["Failed to apply to ",th]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(k.A,{size:10})," Applied to ",th]})})})]})]}):(0,r.jsx)(nn,{fullscreen:b,onSwitchToStudio:()=>aK("generate")}),eW&&!z&&(0,r.jsxs)("div",{className:"px-3 py-2.5 text-[11px] border-t border-amber-500/25 bg-amber-500/[0.08] text-amber-200",children:[(0,r.jsxs)("div",{className:"flex items-center gap-1.5 font-medium",children:[(0,r.jsx)(tu.A,{size:11}),(0,r.jsx)("span",{children:L?null!=F?`You've used today's ${F} free AI edits`:"Credits required to send AI requests":"AI Editor is a Pro feature"})]}),(0,r.jsx)("p",{className:"mt-1 text-amber-100/80",children:L?`Buy 1,000 credits to keep editing now, or upgrade to Pro for 1,000 credits every week.${null!=F?" Your free edits come back tomorrow.":""}`:"Sign in or create an account to continue and see upgrade options for the AI editor."}),(0,r.jsxs)("div",{className:"mt-2 flex flex-wrap gap-2",children:[L&&(0,r.jsxs)("button",{type:"button",onClick:()=>{(0,ey.trackEvent)("credit_checkout_started",{source:"ai_editor_paywall",credits:ak.y5.credits}),(0,aw.KS)(ak.y5.credits).then(e=>{window.location.assign(e.url)}).catch(()=>{(0,ey.trackEvent)("credit_checkout_failed",{source:"ai_editor_paywall",credits:ak.y5.credits})})},className:"inline-flex items-center rounded-md border border-emerald-300/40 bg-emerald-300/15 px-2.5 py-1 text-[11px] font-medium text-emerald-100 transition hover:bg-emerald-300/25",children:["Continue with ",ak.y5.credits.toLocaleString()," credits for"," ",(0,ak.wE)(ak.y5.usd)]}),(0,r.jsx)("button",{type:"button",onClick:()=>{if(L)return void window.location.assign("/pricing");let e=window.location.href;(0,e6.Jv)(void 0,{callbackUrl:e})},className:"inline-flex items-center rounded-md border border-amber-300/40 bg-amber-300/15 px-2.5 py-1 text-[11px] font-medium text-amber-100 transition hover:bg-amber-300/25",children:L?"Upgrade to Pro":"Sign in to continue"})]})]}),eL&&(0,r.jsx)(ne,{message:eL,canRetry:!!aI,onRetry:aC,onDismiss:()=>eF(null)}),"editor"===eA&&d.Wg.AI_EDITOR_ACTIVE&&(0,r.jsxs)("div",{className:`border-t border-white/[0.06] p-2.5 ${b?"px-[max(0.625rem,calc(50%_-_24rem))]":""}`,children:[0===W.length&&0===K.trim().length&&(aa||l)&&(0,r.jsxs)("div",{className:"mb-1.5 p-0",children:[(0,r.jsx)("p",{className:aa?"text-[13px] font-semibold text-zinc-100":"text-[11px] font-medium text-zinc-200",children:ai}),aa?(0,r.jsxs)("button",{type:"button",onClick:()=>aN(rE),className:"mt-2 flex w-full flex-col items-start gap-2 rounded-lg border border-blue-500/25 bg-blue-500/[0.08] px-3 py-3 text-left text-[13px] font-semibold text-zinc-100 cursor-pointer transition hover:bg-blue-500/[0.13] hover:border-blue-400/35",children:[(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5 text-[12px] uppercase tracking-wide text-blue-300",children:[(0,r.jsx)(q.A,{size:12,className:"text-blue-400 animate-bounce"}),"Start here"]}),(0,r.jsxs)("span",{className:"block max-w-full whitespace-normal break-words text-[12px] text-zinc-300",children:["Example: ",rE]})]}):l?(0,r.jsx)("ul",{className:"mt-1 space-y-0.5 text-[10px] leading-4 text-zinc-500",children:rA.map(e=>(0,r.jsx)("li",{children:e},e))}):null]}),l&&(0,r.jsxs)("div",{className:"mb-2 space-y-2",children:[h&&(0,r.jsx)("div",{className:"rounded-md border border-zinc-600/25 bg-zinc-600/[0.06] px-2.5 py-2 text-[11px] leading-5 text-zinc-200 break-all",children:h}),p&&(0,r.jsx)("div",{className:"rounded-md border border-sky-500/20 bg-sky-500/[0.07] px-2.5 py-2 text-[11px] leading-5 text-sky-100/90 break-all",children:p.activeUrl?`Importing ${p.completed+1} of ${p.total}: ${p.activeUrl}`:`Imported ${p.completed} of ${p.total} URLs.`}),m.length>0&&(0,r.jsxs)("div",{className:"rounded-md border border-amber-500/20 bg-amber-500/[0.08] px-2.5 py-2 text-[11px] leading-5 text-amber-100/90 break-all",children:[(0,r.jsx)("div",{className:"font-medium text-amber-100",children:"Some URLs were skipped or failed:"}),(0,r.jsx)("div",{className:"mt-1 flex flex-col gap-0.5",children:m.slice(0,4).map(e=>(0,r.jsx)("span",{children:e},e))})]})]}),!aa&&!l&&(0,r.jsx)(r2,{chips:aS,disabled:aj,onPick:e=>{aj||(V(e.prompt),eU(!1),aQ(e.prompt))}}),(0,r.jsx)("textarea",{ref:eq,value:K,"aria-invalid":!!ar,"aria-describedby":ar?"ai-rail-prompt-limit-message":void 0,onChange:e=>{V(e.target.value),eU(!1)},onFocus:()=>eV(!0),onBlur:()=>eV(!1),onKeyDown:e=>{"Enter"===e.key&&!e.shiftKey&&(e.preventDefault(),an&&aZ())},placeholder:as,className:`w-full min-h-[64px] max-h-[200px] resize-none overflow-x-hidden overflow-y-auto break-words rounded-md bg-[#16161e] border border-white/[0.08] px-2.5 py-2 text-zinc-200 placeholder:text-zinc-600 focus:outline-none focus:border-white/20 ${b?"text-[13px]":"text-xs"} 82 [scrollbar-width:thin] 83 [scrollbar-color:rgba(51,65,85,0.4)_transparent] 84 [&::-webkit-scrollbar]:w-1 85 [&::-webkit-scrollbar-track]:bg-transparent 86 [&::-webkit-scrollbar-thumb]:bg-slate-700/40 87 [&::-webkit-scrollbar-thumb]:rounded-full 88 [&::-webkit-scrollbar-thumb:hover]:bg-slate-600/50`}),ar&&(0,r.jsx)("p",{id:"ai-rail-prompt-limit-message","data-testid":"ai-rail-prompt-limit",role:"status",className:"mt-1 text-[10px] text-amber-300",children:ar}),(0,r.jsxs)("div",{className:"mt-2 flex justify-between items-center gap-2",children:[(0,r.jsxs)("button",{type:"button",onClick:()=>
88{if(!am)return;if(ef){eG.current=!1;try{eY.current?.stop()}catch{}ex(!1);return}let e=window.SpeechRecognition||window.webkitSpeechRecognition;if(!e)return;let t=K.trim();eX.current=t?`${t} `:"",eJ.current="",eG.current=!0;let a=new e;a.lang="en-US",a.interimResults=!0,a.continuous=!0,a.onresult=e=>{let t="";for(let a=e.resultIndex;a<e.results.length;a+=1){let r=e.results[a],n=(r?.[0]?.transcript??"").trim();n&&(r.isFinal?eJ.current=eJ.current?`${eJ.current} ${n}`:n:t+=t?` ${n}`:n)}let a=[eJ.current,t].filter(Boolean).join(" ");V(`${eX.current}${a}`),eU(!1)},a.onerror=e=>{let t=e?.error;t&&"no-speech"!==t&&"aborted"!==t&&(eG.current=!1,ex(!1))},a.onend=()=>{if(eG.current)try{a.start();return}catch{}ex(!1)},eY.current=a;try{a.start(),ex(!0)}catch{eG.current=!1,ex(!1)}},disabled:!am,className:`px-2.5 py-1.5 rounded-md text-xs flex items-center gap-1.5 transition-colors ${am?ef?"bg-red-500/15 hover:bg-red-500/25 text-red-400":"bg-white/[0.06] hover:bg-white/[0.10] text-zinc-400":"bg-white/[0.03] text-zinc-600 cursor-not-allowed"}`,title:am?"Dictate into composer":"Speech dictation not supported",children:[ef?(0,r.jsx)(x.A,{size:12,className:"animate-spin"}):(0,r.jsx)(ts.A,{size:12}),ef?"Listeningâ¦":"Mic"]}),eK&&(0,r.jsx)("span",{"aria-hidden":!0,className:"select-none text-[10px] text-zinc-600",children:"â send \xb7 â§â newline"}),"thinking"===H?(0,r.jsxs)("button",{type:"button",onClick:()=>{let e=tT.current;e&&(tT.current=null,e.abort())},"data-testid":"ai-rail-stop-planning",title:"Stop waiting for this plan",className:"px-3 py-1.5 rounded-md bg-red-500/15 hover:bg-red-500/25 text-red-300 text-xs font-medium flex items-center gap-1.5 transition-colors",children:[(0,r.jsx)(tp.A,{size:11}),"Stop"]}):(0,r.jsxs)("button",{type:"button",onClick:aZ,disabled:!an,"data-testid":"ai-rail-send",className:"inline-flex h-8 items-center gap-1.5 rounded-md bg-blue-600 px-3 text-xs font-semibold text-white transition-colors hover:bg-blue-500 disabled:cursor-not-allowed disabled:bg-white/[0.06] disabled:text-zinc-600",children:[(0,r.jsx)(tm.A,{size:12}),"Send"]})]}),!z&&L&&null!==O&&null!==F&&(0,r.jsxs)("p",{"data-testid":"ai-rail-free-prompts-remaining",className:"mt-1.5 text-right text-[10px] text-zinc-500",children:[O," of ",F," free AI prompts left today"]})]})]})}var no=a(40598),nl=a(86347),nd=a(43882),nc=a(52821),nu=a(38897),np=a(12165);function nm({nodes:e,totalMemoryMB:t,lastUpdateMs:a,snapshotId:n}){return 0===e.length?null:(0,r.jsxs)("div",{className:"bg-white/5 rounded-md",children:[(0,r.jsxs)("div",{className:"flex justify-between items-center px-2 py-1",children:[(0,r.jsx)("span",{className:"text-white/50 text-[10px] font-semibold",children:"BUFFER DISTRIBUTION"}),(0,r.jsxs)("span",{className:"text-white/30 text-[10px]",children:[Math.round(t),"MB (",e.length," nodes)",void 0!==n&&(0,r.jsxs)("span",{className:"ml-1 text-white/20",title:`Snapshot #${n}`,children:["#",n]}),a>0&&(0,r.jsx)("span",{className:"ml-1 text-white/20",title:"Stats age (ms since last refresh)",children:600>Math.round(performance.now()-a)?"â":"â"})]})]}),(0,r.jsx)("div",{className:"text-[10px] font-mono pb-1",children:e.map(e=>{var t,a;let{behindMs:n,aheadMs:i}=(a=e).isActive&&0!==a.bufferedFrames?{behindMs:Math.max(0,a.localTimeSec>a.bufferRangeStart?(a.localTimeSec-a.bufferRangeStart)*1e3:0),aheadMs:Math.max(0,a.bufferRangeEnd>a.localTimeSec?(a.bufferRangeEnd-a.localTimeSec)*1e3:0)}:{behindMs:0,aheadMs:0},s=e.bufferRangeEnd-e.bufferRangeStart;return(0,r.jsxs)("div",{className:`py-0.5 px-2 ${e.isActive?"bg-green-800/60":""}`,children:[(0,r.jsxs)("div",{className:"flex justify-between items-center",children:[(0,r.jsxs)("span",{className:"text-white/70",children:["#",e.instanceId," ",(0,r.jsxs)("span",{className:e.isActive?"text-green-300 font-bold":"text-white/40",children:["S",e.sceneIndex]}),e.isActive&&(0,r.jsx)("span",{className:"text-green-400 ml-1",children:"â¶"})]}),(0,r.jsxs)("span",{className:"flex items-center gap-1",children:[(0,r.jsxs)("span",{className:`w-10 text-right ${e.isActive?"text-green-200":"text-white"}`,children:[e.bufferedFrames,"f"]}),(0,r.jsxs)("span",{className:"text-white/40 w-10 text-right",children:[e.bufferedSeconds.toFixed(1),"s"]}),(0,r.jsx)("span",{className:`px-1 rounded text-[9px] w-10 text-center ${"hot"===e.lifecycleState?"bg-red-600/50 text-red-200":"warm"===e.lifecycleState?"bg-yellow-600/50 text-yellow-200":"cold"===e.lifecycleState?"bg-blue-600/50 text-blue-200":"bg-gray-600/50"}`,children:e.lifecycleState.toUpperCase()}),e.isUsingWorker&&(0,r.jsx)("span",{className:"text-purple-300",children:"â"})]})]}),e.isActive&&e.bufferedFrames>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"flex justify-between items-center text-[9px] text-white/40 mt-0.5 pl-4",children:[(0,r.jsxs)("span",{children:[(0,r.jsxs)("span",{className:"text-white/60",children:["@",e.localTimeSec.toFixed(2),"s"]}),(0,r.jsx)("span",{className:"text-white/30 mx-1",children:"|"}),(0,r.jsxs)("span",{className:"text-white/50",children:[e.bufferRangeStart.toFixed(2),"s"]}),(0,r.jsx)("span",{className:"text-white/30",children:"â"}),(0,r.jsxs)("span",{className:"text-white/50",children:[e.bufferRangeEnd.toFixed(2),"s"]})]}),(0,r.jsxs)("span",{className:"flex items-center gap-1",children:[(0,r.jsxs)("span",{className:e.framesBehind>0?"text-orange-300":"text-white/30",children:["â",e.framesBehind]}),(0,r.jsx)("span",{className:e.coversPlayhead?"text-green-400":"text-red-400",children:e.coversPlayhead?"â":"â"}),(0,r.jsxs)("span",{className:e.framesAhead>0?"text-cyan-300":"text-white/30",children:[e.framesAhead,"â¶"]})]})]}),(0,r.jsxs)("div",{className:"flex justify-between items-center text-[8px] text-white/30 pl-4",children:[(0,r.jsx)("span",{className:"text-white/40",children:s>0?`${(1e3*s).toFixed(0)}ms total`:""}),(0,r.jsxs)("span",{className:"flex items-center gap-1",children:[(0,r.jsxs)("span",{className:n>0?"text-orange-400/70":"text-white/20",children:["â",n.toFixed(0),"ms"]}),(0,r.jsx)("span",{className:"text-white/20",children:"|"}),(0,r.jsxs)("span",{className:i>0?"text-cyan-400/70":"text-white/20",children:[i.toFixed(0),"msâ¶"]})]})]})]}),!e.isActive&&e.bufferedFrames>0&&(0,r.jsxs)("div",{className:"flex justify-between items-center text-[9px] text-white/30 mt-0.5 pl-4",children:[(0,r.jsxs)("span",{children:[(0,r.jsxs)("span",{className:"text-white/40",children:[e.bufferRangeStart.toFixed(2),"s"]}),(0,r.jsx)("span",{className:"text-white/20",children:"â"}),(0,r.jsxs)("span",{className:"text-white/40",children:[e.bufferRangeEnd.toFixed(2),"s"]})]}),(0,r.jsx)("span",{className:e.distanceFromPlayhead>0?"text-cyan-400/60":"text-orange-400/60",children:0===(t=e.distanceFromPlayhead)?"â":t>0?`+${t.toFixed(1)}s`:`${t.toFixed(1)}s`})]}),e.isActive&&e.bufferedFrames>0&&!e.coversPlayhead&&(0,r.jsxs)("div",{className:"text-[9px] text-red-400 pl-4 mt-0.5",children:["â ï¸ No frames near playhead! Nearest: ",e.nearestFrameMs.toFixed(0),"ms away"]}),e.isActive&&0===e.bufferedFrames&&(0,r.jsx)("div",{className:"text-[9px] text-yellow-400 pl-4 mt-0.5",children:"â³ Buffer empty - waiting for frames"})]},e.instanceId)})})]})}function nh({position:e,onClose:t}){return(0,r.jsxs)("div",{className:"fixed bg-gray-900/95 rounded-lg p-3 border border-blue-500/50 text-[10px] text-white/90 shadow-xl z-[10001] max-w-[280px]",style:{to
88p:e?e.y:"auto",bottom:e?"auto":16,left:e?e.x+385:"auto",right:e?"auto":-270},children:[(0,r.jsxs)("div",{className:"flex justify-between items-center mb-2",children:[(0,r.jsx)("span",{className:"font-bold text-blue-300",children:"\uD83D\uDCD6 Panel Guide"}),(0,r.jsx)("button",{onClick:t,className:"text-white/50 hover:text-white text-sm",children:"â"})]}),(0,r.jsx)("div",{className:"font-mono text-[9px] leading-relaxed",children:np.$D.trim().split("\n").map((e,t)=>e.startsWith("**")&&e.endsWith("**")?(0,r.jsx)("div",{className:"font-bold text-blue-200 mt-2 mb-0.5 text-[10px]",children:e.replace(/\*\*/g,"")},t):e.startsWith("â¢")?(0,r.jsx)("div",{className:"pl-2 text-white/70",children:e},t):e.startsWith("â")||e.startsWith("â")?(0,r.jsx)("div",{className:"text-white/50 pl-1",children:e},t):(0,r.jsx)("div",{className:"text-white/80",children:e},t))})]})}function nf({snapshots:e,onClose:t,onClear:a}){let[n,s]=(0,i.useState)(!1),{logsEnabled:o}=(0,nc.u)(),l=window.__PLAYWRIGHT_TEST_MODE__,d=o||l;if(0===e.length)return null;let c=e[e.length-1],u=Math.max(0,c.timestamp-(e[0]?.timestamp??0)),p=c?.droppedFrames??0,m=e.length>0?e.reduce((e,t)=>e+(t.dropRate??0),0)/e.length:0,h=e.filter(e=>e.healthTransition).length,f=e.filter(e=>e.inputEvent).length,g=e.filter(e=>(e.lifecycleMismatchCount??0)>0).length;return(0,r.jsxs)("div",{className:"fixed bg-gray-900/98 rounded-lg p-3 border-2 border-red-500/70 text-[10px] text-white/90 shadow-2xl z-[10002]",style:{to
88p:"50%",left:"50%",transform:"translate(-50%, -50%)",maxWidth:"95vw",maxHeight:"85vh",minWidth:"800px"},children:[(0,r.jsxs)("div",{className:"flex justify-between items-center mb-2",children:[(0,r.jsxs)("span",{className:"font-bold text-red-300",children:["\uD83C\uDFAC Recording (",e.length," snapshots, ",(u/1e3).toFixed(1),"s)"]}),(0,r.jsxs)("div",{className:"flex gap-2 items-center",children:[(0,r.jsx)("button",{onClick:()=>s(!n),className:`px-2 py-0.5 rounded text-[9px] ${n?"bg-blue-600 text-white":"bg-white/10 hover:bg-white/20 text-white/70"}`,title:"Toggle between extended and compact format",children:n?"\uD83D\uDCCA Compact":"\uD83D\uDCCA Extended"}),(0,r.jsx)("button",{"data-testid":"webcodecs-copy-recording",onClick:()=>{if(!d)return;let t=n?(0,np.EC)(e):(0,np.ks)(e);navigator.clipboard.writeText(t).then(()=>{alert("Recording copied to clipboard!")})},className:`px-2 py-0.5 rounded text-[9px] ${d?"text-green-400 hover:text-green-300 bg-green-900/50":"text-slate-500 bg-slate-800/60 cursor-not-allowed"}`,children:"\uD83D\uDCCB Copy"}),(0,r.jsx)("button",{"data-testid":"webcodecs-clear-recording",onClick:a,className:"text-orange-400 hover:text-orange-300 bg-orange-900/50 px-2 py-0.5 rounded text-[9px]",children:"\uD83D\uDDD1 Clear"}),(0,r.jsx)("button",{onClick:t,className:"text-white/50 hover:text-white text-sm",children:"â"})]})]}),(0,r.jsxs)("div",{className:"flex gap-4 text-[9px] mb-2 pb-2 border-b border-white/10",children:[(0,r.jsxs)("span",{className:"text-white/50",children:["Snapshots: ",(0,r.jsx)("span",{className:"text-white/80 font-mono",children:e.length})]}),(0,r.jsxs)("span",{className:"text-white/50",children:["Drops:"," ",(0,r.jsx)("span",{className:`font-mono ${p>10?"text-red-400":"text-white/80"}`,children:p})]}),(0,r.jsxs)("span",{className:"text-white/50",children:["Avg Drop%:"," ",(0,r.jsxs)("span",{className:`font-mono ${m>5?"text-red-400":m>1?"text-yellow-400":"text-green-400"}`,children:[m.toFixed(1),"%"]})]}),(0,r.jsxs)("span",{className:"text-white/50",children:["Health Changes:"," ",(0,r.jsx)("span",{className:`font-mono ${h>0?"text-yellow-400":"text-white/80"}`,children:h})]}),(0,r.jsxs)("span",{className:"text-white/50",children:["Input Events: ",(0,r.jsx)("span",{className:"text-cyan-400 font-mono",children:f})]}),g>0&&(0,r.jsxs)("span",{className:"text-white/50",children:["Lifecycle Mismatches:"," ",(0,r.jsx)("span",{className:"text-orange-400 font-mono",children:g})]})]}),(0,r.jsxs)("details",{className:"text-[8px] text-white/40 mb-2",children:[(0,r.jsx)("summary",{className:"cursor-pointer hover:text-white/60",children:"\uD83D\uDCD6 Legend (click to expand)"}),(0,r.jsxs)("div",{className:"mt-1 pl-2 grid grid-cols-2 gap-x-4 gap-y-0.5",children:[(0,r.jsx)("span",{children:"SNAP = Monotonic snapshot ID"}),(0,r.jsx)("span",{children:"VC_T = VideoContext time (seconds)"}),(0,r.jsx)("span",{children:"âBEHIND = Frames before playhead"}),(0,r.jsx)("span",{children:"AHEADâ¶ = Frames after playhead"}),(0,r.jsx)("span",{children:"COVERS = â has frame / â gap"}),(0,r.jsx)("span",{children:"BUF_MS = Buffer ms (behind/ahead)"}),(0,r.jsx)("span",{children:"HOT/W/COLD = Lifecycle counts"}),(0,r.jsx)("span",{children:"RDR/DRP = Rendered/Dropped frames"}),(0,r.jsx)("span",{children:"DEC (m/w) = Decoder count (main/worker)"}),(0,r.jsx)("span",{children:"â = Worker decode enabled"})]})]}),(0,r.jsx)("div",{className:"font-mono text-[8px] overflow-auto bg-black/30 rounded p-2",style:{maxHeight:"calc(85vh - 180px)"},children:d?(0,r.jsx)("pre",{className:"whitespace-pre","data-testid":"webcodecs-recording-content",children:n?(0,np.EC)(e):(0,np.ks)(e)}):(0,r.jsx)("div",{className:"text-slate-400 text-xs",children:"Logs are disabled. Enable verbose logs in the WebCodecs panel to view/copy recording output."})})]})}var ng=a(12255),nx=a(47687);function nb(){var e;let{logsEnabled:t,toggleLogsEnabled:n}=(0,nc.u)(),s=window.__PLAYWRIGHT_TEST_MODE__,o=t||s,l=!o,[c,u]=(0,i.useState)(null),[p,m]=(0,i.useState)(()=>{try{let e=localStorage.getItem(np.ro);return null===e||"true"===e}catch{return!0}}),[h,f]=(0,i.useState)(!1),[g,x]=(0,i.useState)(null),[b,y]=(0,i.useState)(null),[v,w]=(0,i.useState)(null),[k,S]=(0,i.useState)([]),[j,I]=(0,i.useState)(null),[N,C]=(0,i.useState)(null),[M,_]=(0,i.useState)(0),[A,E]=(0,i.useState)(null),[T,$]=(0,i.useState)(0),[P,D]=(0,i.useState)(null),[R,z]=(0,i.useState)(null),[L,F]=(0,i.useState)(null),[O,B]=(0,i.useState)(null),[W,U]=(0,i.useState)(!1),[K,V]=(0,i.useState)(!1),[H,q]=(0,i.useState)(null),[Y,G]=(0,i.useState)(!1),X=(0,i.useRef)({x:0,y:0}),J=(0,i.useRef)(null),[Z,Q]=(0,i.useState)(null),[ee,et]=(0,i.useState)(null),ea=(0,i.useRef)({y:0,height:0,positionY:0,minHeight:0}),[er,en]=(0,i.useState)(()=>{try{let e=localStorage.getItem(np.uG);return null===e||"true"===e}catch{return!0}}),[ei,es]=(0,i.useState)(!1),[eo,el]=(0,i.useState)([]),ed=(0,i.useRef)([]),[ec,eu]=(0,i.useState)(!1),ep=(0,i.useRef)(0),em=(0,i.useRef)(null),eh=(0,i.useRef)(null),ef=(0,i.useRef)(null);eh.current=A,ef.current=g;let eg=(0,i.useRef)(null),ex=(0,i.useRef)([]),[eb,ey]=(0,i.useState)(null),[ev,ew]=(0,i.useState)(null),[ek,eS]=(0,i.useState)(null),[ej,eI]=(0,i.useState)("IDLE"),[eN,eC]=(0,i.useState)("NORMAL"),[eM,e_]=(0,i.useState)(!1),[eA,eE]=(0,i.useState)(null),[eT,e$]=(0,i.useState)({active:!1,summary:"none"}),[eP,eD]=(0,i.useState)(null),[eR,ez]=(0,i.useState)(null),[eL,eF]=(0,i.useState)(null);(0,i.useEffect)(()=>{!o&&(ei&&es(!1),ec&&eu(!1),eo.length>0&&(ed.current=[],el([])))},[o,ei,ec,eo.length]),(0,i.useEffect)(()=>
88{if(s)return window.__RESET_WEBCODECS_RECORDING_BUFFER__=()=>{ed.current=[],el([]),ep.current=performance.now()},()=>{window.__RESET_WEBCODECS_RECORDING_BUFFER__&&delete window.__RESET_WEBCODECS_RECORDING_BUFFER__}},[s]);let[eO,eB]=(0,i.useState)(()=>nx.WebCodecsVideoNode.fastScrubGlobalEnabled),[eW,eU]=(0,i.useState)(!1),[eK,eV]=(0,i.useState)(0);(0,i.useEffect)(()=>{nl.f.setEnabled(!0)},[]),(0,i.useEffect)(()=>{nx.WebCodecsVideoNode.loadFastScrubSetting(),eB(nx.WebCodecsVideoNode.fastScrubGlobalEnabled)},[]),(0,i.useEffect)(()=>{try{let e=localStorage.getItem(np.AQ);e&&q(JSON.parse(e));let t=localStorage.getItem(np.Eh);if(t){let e=parseInt(t,10);!isNaN(e)&&e>0&&Q(e)}let a=localStorage.getItem(np.Jm);if(null!==a){let e="true"===a;V(e),window.__FLAGS_OVERRIDE__=window.__FLAGS_OVERRIDE__||{},window.__FLAGS_OVERRIDE__.USE_DECODE_WORKER=e}else V(d.Wg.USE_DECODE_WORKER)}catch{}},[]),(0,i.useEffect)(()=>{if(H)try{localStorage.setItem(np.AQ,JSON.stringify(H))}catch{}},[H]),(0,i.useEffect)(()=>{if(null!==Z)try{localStorage.setItem(np.Eh,String(Math.round(Z)))}catch{}},[Z]),(0,i.useEffect)(()=>{try{localStorage.setItem(np.ro,String(p))}catch{}},[p]),(0,i.useEffect)(()=>{try{localStorage.setItem(np.uG,String(er))}catch{}},[er]);let eH=(0,i.useCallback)(e=>{let t=e.target;if(t.closest("button")||t.closest("[data-resize-handle]")||!J.current)return;let a=J.current.getBoundingClientRect();if(H)X.current={x:e.clientX-a.left,y:e.clientY-a.top};else{let t=a.left,r=a.top;q({x:t,y:r}),X.current={x:e.clientX-t,y:e.clientY-r}}G(!0),e.preventDefault()},[H]),eq=(0,i.useCallback)(()=>{let e=!K;V(e);try{localStorage.setItem(np.Jm,String(e))}catch{}window.__FLAGS_OVERRIDE__=window.__FLAGS_OVERRIDE__||{},window.__FLAGS_OVERRIDE__.USE_DECODE_WORKER=e,console.log(`[WebCodecsDiagnostic] Worker decode ${e?"ENABLED":"DISABLED"} - reload page for full effect`)},[K]),eY=(0,i.useCallback)(()=>{let e=!eO;nx.WebCodecsVideoNode.setFastScrubEnabled(e),eB(e),console.log(`[WebCodecsDiagnostic] FastScrub ${e?"ENABLED":"DISABLED"} - immediate effect`)},[eO]);(0,i.useEffect)(()=>{if(!Y)return;let e=e=>{q({x:e.clientX-X.current.x,y:e.clientY-X.current.y})},t=()=>G(!1);return document.addEventListener("mousemove",e),document.addEventListener("mouseup",t),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",t)}},[Y]);let eG=(0,i.useCallback)((e,t)=>{if(!J.current)return;e.stopPropagation(),e.preventDefault();let a=J.current.getBoundingClientRect(),r=J.current.querySelector("[data-panel-header]"),n=r?r.getBoundingClientRect().height:0;ea.current={y:e.clientY,height:a.height,positionY:H?.y??a.top,minHeight:n+8},en(!1),et(t)},[H]);if((0,i.useEffect)(()=>{if(!ee)return;let e=e=>{let t;if(!J.current)return;let a=e.clientY-ea.current.y,r=window.innerHeight-e1;if("bottom"===ee)t=ea.current.height+a;else{let e=ea.current.positionY+a,n=Math.max(e1,r-ea.current.minHeight),i=Math.min(Math.max(e1,e),n),s=i-ea.current.positionY;t=ea.current.height-s,q({x:H?.x??J.current.getBoundingClientRect().left,y:i})}let n=Math.max(0,ea.current.minHeight),i="top"===ee?Math.min(Math.max(e1,ea.current.positionY+a),Math.max(e1,r-n)):J.current.getBoundingClientRect().top;Q(t=Math.min(Math.max(n,r-i),Math.max(n,t)))},t=()=>et(null);return document.addEventListener("mousemove",e),document.addEventListener("mouseup",t),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",t)}},[ee,H]),(0,i.useEffect)(()=>{if(!o||ei)return;let e=setInterval(()=>{if(!Y&&!ee)try{let e=window.__WEBCODECS_PROOF__;e&&u({...e});let t=window.masterVC,a=window.__WEBCODECS_NODES__||[],r="function"==typeof t?.getOutputRendererStats?t.getOutputRendererStats():null,n=Array.isArray(r?.sceneDiagnostics)?r.sceneDiagnostics:[],i=a.length>0?a:n.map((e,t)=>{let a=Number.isFinite(e?.sourceOffset)?e.sourceOffset:0,r=Number.isFinite(e?.duration)?e.duration:0,n=Number.isFinite(e?.vcStart)?e.vcStart:0,i=Number.isFinite(e?.vcEnd)?e.vcEnd:n+r,s=!!e?.hasUploadedFrame,o=("string"==typeof e?.lifecycle?e.lifecycle:"cold").toLowerCase(),l=a+Math.max(0,r);return{node:{instanceId:e?.id||`webgpu-scene-${t}`,m_startTime:n,m_stopTime:i,m_startOffset:a,_lifecycleState:o,_useWorkerForDecode:!1,fps:30,fastScrubMode:!1,scrubVelocity:0,buffer:{getStats:()=>({totalCount:+!!s,estimatedMemoryMB:0}),getDetailedStats:e=>{let t=Math.max(0,e/1e6);return{framesBehind:0,framesAhead:+!!s,coversPlayhead:s&&t>=a-.05&&t<=l+.05,oldestTimeSec:a,newestTimeSec:s?Math.max(a,Math.min(l,t)):a,nearestFrameDistanceMs:s?0:1/0}}}}}});if(!e&&r?.mode==="native-webgpu"){let e=Number.isFinite(r?.frameCount)?r.frameCount:0;u({decoderInstancesCreated:i.length,totalDecodeCallsAllTime:e,decodeCallsThisSession:e,lastDecodeTimestamp:e>0?Date.now():null,errors:Number.isFinite(r?.failedCopies)?r.failedCopies:0,errorLog:[]}
88)}let s=t?.state??-1,o=t?.currentTime??0;if(t){let e=-1;i.forEach((t,a)=>{let r=t.node;r&&void 0!==r.m_startTime&&void 0!==r.m_stopTime&&o>=r.m_startTime&&o<r.m_stopTime&&(e=a)}),y({state:nu.nE[s]??"UNKNOWN",stateNum:s,currentTime:o,duration:t.duration??0,activeSceneIndex:e+1,totalScenes:i.length})}let l=0,d=0,c=0;i.forEach(e=>{let t=e.node?._lifecycleState??"unknown";"hot"===t?l++:"warm"===t?d++:"cold"===t&&c++}),w({hot:l,warm:d,cold:c,total:i.length});let p=i.map(e=>({entry:e,node:e.node,startTime:e.node?.m_startTime??1/0,stopTime:e.node?.m_stopTime??1/0})).filter(e=>null!=e.node);p.sort((e,t)=>e.startTime-t.startTime);let m=[],h=0;if(p.forEach((e,t)=>{let a=e.node,r=e.startTime,n=e.stopTime,i=a.buffer?.getStats?.()??{totalCount:0,estimatedMemoryMB:0},s=a.fps??30;h+=i.estimatedMemoryMB??0;let l=o>=r&&o<n,d=a.m_startOffset??0,c=l?Math.max(0,o-r+d):0,u=Math.round(1e6*c),p=l?a.buffer?.getDetailedStats?.(u):null,f=o<r?r-o:o>=n?o-n:0;m.push({instanceId:a.instanceId??t,sceneIndex:t+1,startTime:r,stopTime:n,lifecycleState:a._lifecycleState??"unknown",bufferedFrames:i.totalCount??0,bufferedSeconds:(i.totalCount??0)/s,isUsingWorker:a._useWorkerForDecode??!1,internalPlaying:a.internalPlaying??!1,isActive:l,framesAhead:l?p?.framesAhead??0:-1,framesBehind:l?p?.framesBehind??0:-1,localTimeSec:c,bufferRangeStart:p?.oldestTimeSec??0,bufferRangeEnd:p?.newestTimeSec??0,coversPlayhead:!!l&&(p?.coversPlayhead??!1),nearestFrameMs:l?p?.nearestFrameDistanceMs??1/0:1/0,distanceFromPlayhead:f})}),np.Mo){let e=m.find(e=>e.isActive);console.log("[BufferDist] t=",o.toFixed(2),"active=S"+(e?.sceneIndex??"?"),"state="+(e?.lifecycleState??"?"),"frames="+(e?.bufferedFrames??0),"nodes:",m.map(e=>`S${e.sceneIndex}:${e.bufferedFrames}f/${e.lifecycleState}`).join(" "))}m.sort((e,t)=>t.bufferedFrames-e.bufferedFrames),S(m),_(h),$(performance.now());let f=0===s,g=2===s,b=0,v=0,k=0,j=0;i.forEach(e=>{let t=e.node;if(!t)return;let a=t.internalPlaying??!1,r=t.buffer?.getStats?.()?.totalCount??0,n=t._useWorkerForDecode??!1,i=t._lifecycleState??"unknown";a&&!f&&!g&&b++,a&&0===r&&v++,n&&!f&&k++,"hot"===i&&r<5&&r>0&&j++}),I({pumpWhileVcPaused:b,playingWithEmptyBuffer:v,workerDuringScrubbing:k,hotWithLowBuffer:j});let N=nl.f.snapshot(),M=N.players?.master,A=(M?.renderedExact??0)+(M?.renderedApprox??0),T=M?.dropped??0,P=M?.reused??0,R=A+T;C({rendered:A,dropped:T,reused:P,dropPercent:R>0?T/R*100:0,rollingDropped:N.rollingWindow?.droppedInWindow??0,rollingRendered:N.rollingWindow?.renderedInWindow??0,rollingDropRate:N.rollingWindow?.dropRate??0,lastLatencyMs:N.startupLatency?.lastMs??null,avgLatencyMs:N.startupLatency?.avgMs??null,latencySampleCount:N.startupLatency?.sampleCount??0});let L=Date.now(),O=eg.current;if(O){let e=A-O.rendered,t=T-O.dropped,a=P-O.reused;if(e<0||t<0||a<0)ex.current=[],E(null);else{ex.current.push({ts:L,rendered:e,dropped:t,reused:a}),ex.current=ex.current.filter(e=>L-e.ts<=np.qH);let r=ex.current.reduce((e,t)=>e+t.rendered,0),n=ex.current.reduce((e,t)=>e+t.dropped+t.reused,0),i=0===s&&r<=0&&n>=np.CT;E(i?{windowMs:np.qH,rendered:Math.max(0,r),drops:n}:null)}}else ex.current=[];eg.current={rendered:A,dropped:T,reused:P,timestamp:L};let W=no.B.getSnapshot();if(W.enabled){let e=0,t=0,a=0,r=0;Object.entries(W.categories).forEach(([n,i])=>{try{let s=no.B.getRateForCategory(n);n.startsWith("main-thread/")?(e+=i.totalDecodes??0,t+=s??0):n.startsWith("worker/")&&(a+=i.totalDecodes??0,r+=s??0)}catch{}}),x({mainThread:{total:e,rate:t},worker:{total:a,rate:r}})}let K=(0,np.WH)(),V=(0,np.UV)();D(K),z(V);let H=0===s&&ex.current.length>0&&0>=ex.current.reduce((e,t)=>e+t.rendered,0)&&ex.current.reduce((e,t)=>e+t.dropped+t.reused,0)>=np.CT;F((0,np.S8)(K,V,H)),U((0,np.tn)()),B((0,np.Tk)());let q=(0,np.BZ)();eF(window.__SYSTEM_METRICS_LATEST__||null),q&&(ew(q.global.startupTiming),eS({activeFrames:q.global.activeFrames,activeBufferDurationMs:q.global.activeBufferDurationMs,peakActiveFrames:q.global.peakActiveFrames,peakActiveBufferDurationMs:q.global.peakActiveBufferDurationMs,peakActiveDecoders:q.global.peakActiveDecoders,registryEvictionCount:q.global.registryEvictionCount,registryDeniedCount:q.global.registryDeniedCount}
88),eI(q.global.playbackMode),eC(q.global.qualityMode),e_(q.global.experimentalBudgetsEnabled),eE({lookahead:q.global.budgetLookaheadFrames,history:q.global.budgetHistoryFrames,bubble:q.global.budgetBubbleSize,inflight:q.global.budgetMaxInflightDecodes,maxPPS:q.global.budgetMaxPresentsPerSec}),e$({active:q.global.qualityAdjustmentsActive,summary:q.global.qualityAdjustmentsSummary}),eD({total:q.global.jankAttributionTotal,severe:q.global.jankAttributionSevere,lastAttribution:q.global.lastJankAttribution,lastAgeMs:q.global.lastJankAgeMs}),ez({total:q.global.blackFrameFramesTotal,scrub:q.global.blackFrameFramesWhileScrubbing,firstCrossScene:q.global.blackFrameFramesFirstCrossSceneScrub,transitions:q.global.blackFrameFirstCrossSceneTransitions,resolved:q.global.blackFrameFirstCrossSceneResolved,held:q.global.heldFrameSuppressions,heldScrub:q.global.heldFrameSuppressionsWhileScrubbing,pendingPair:q.global.blackFrameFirstCrossScenePendingPair,p95LatencyMs:q.global.blackFrameFirstCrossSceneP95LatencyMs,reasonsTop:q.global.blackFrameReasonsTop}),eB(nx.WebCodecsVideoNode.fastScrubGlobalEnabled),eU(q.global.fastScrubActive??!1),eV(q.global.scrubVelocity??0)),eb&&ey(null)}catch(e){console.error("[WebCodecsDiagnostic] Polling error:",e),ey(e instanceof Error?e.message:"Unknown error")}},500);return()=>clearInterval(e)},[o,eb,Y,ee,ei]),(0,i.useEffect)(()=>{if(!ei||!o)return;let e=()=>{let e=eh.current,t=ef.current,a=(0,np.BZ)({visualStall:e?{drops:e.drops}:null,decodeRates:t?{mainRate:t.mainThread.rate,workerRate:t.worker.rate}:void 0});if(!a)return;let{global:r,nodes:n}=a,i=(0,np.vb)(a),s=(0,np.XL)(),o=em.current;em.current=null,"BROKEN"===r.vcState?o="BROKEN(4)":"STALLED"===r.vcState&&(o="STALLED");let l={timestamp:performance.now()-ep.current,vcTime:r.vcTimeSec,vcState:r.vcState,activeSceneIndex:r.activeSceneIndex,activeNodeId:i?.nodeId??null,activeNodeFrames:i?.totalFrames??0,activeNodeFramesAhead:i?.framesAhead??0,activeNodeFramesBehind:i?.framesBehind??0,activeNodeCoversPlayhead:i?.coversPlayhead??!1,hotCount:r.hotCount,coldCount:r.coldCount,warmCount:r.warmCount,errorCount:r.errorCount,event:o||void 0,diagnosticsMode:r.diagnosticsMode,blackFrameFramesTotal:r.blackFrameFramesTotal,blackFrameFramesWhileScrubbing:r.blackFrameFramesWhileScrubbing,blackFrameFramesFirstCrossSceneScrub:r.blackFrameFramesFirstCrossSceneScrub,blackFrameFirstCrossSceneTransitions:r.blackFrameFirstCrossSceneTransitions,blackFrameFirstCrossSceneResolved:r.blackFrameFirstCrossSceneResolved,blackFrameFirstCrossScenePendingPair:r.blackFrameFirstCrossScenePendingPair,blackFrameFirstCrossSceneLastLatencyMs:r.blackFrameFirstCrossSceneLastLatencyMs,blackFrameFirstCrossSceneP95LatencyMs:r.blackFrameFirstCrossSceneP95LatencyMs,blackFrameReasonsTop:r.blackFrameReasonsTop,heldFrameSuppressions:r.heldFrameSuppressions,heldFrameSuppressionsWhileScrubbing:r.heldFrameSuppressionsWhileScrubbing,snapshotId:r.snapshotId,bufferBehindMs:i?.bufferBehindMs??0,bufferAheadMs:i?.bufferAheadMs??0,bufferDurationMs:i?.bufferDurationMs??0,bufferStartSec:i?.bufferStartTimeSec??0,bufferEndSec:i?.bufferEndTimeSec??0,playheadSec:i?.playheadTimeSec??0,renderedFrames:r.renderedFrames,droppedFrames:r.droppedFrames,reusedFrames:r.reusedFrames,dropRate:r.dropRate,mainDecoders:r.mainDecoders,workerDecoders:r.workerDecoders,workerOn:r.workerOn,health:r.health,healthTransition:r.healthTransition??void 0,lifecycleMismatchCount:r.lifecycleMismatchCount,inputEvent:s??void 0,canvasFps:r.canvasFps,rafDeltaAvgMs:r.rafDeltaAvgMs,rafDeltaMaxMs:r.rafDeltaMaxMs,rafDeltaP95Ms:r.rafDeltaP95Ms,rafDeltaP99Ms:r.rafDeltaP99Ms,jankCount:r.jankCount,severeJankCount:r.severeJankCount,totalJankEvents:r.totalJankEvents,totalSevereJankEvents:r.totalSevereJankEvents,startupPendingId:r.startupTiming.pendingId,startupPendingType:r.startupTiming.pendingType,startupPendingAgeMs:r.startupTiming.pendingAgeMs,startupPendingStatus:r.startupTiming.pendingStatus,lastPlayToFirstFrameMs:r.startupTiming.lastPlayToFirstFrameMs,lastPlayToStableMs:r.startupTiming.lastPlayToStableMs,lastSeekToFirstFrameMs:r.startupTiming.lastSeekToFirstFrameMs,activeFrames:r.activeFrames,activeBufferDurationMs:r.activeBufferDurationMs,peakActiveFrames:r.peakActiveFrames,peakActiveBufferDurationMs:r.peakActiveBufferDurationMs,peakActiveDecoders:r.peakActiveDecoders,registryActiveCount:r.registryActiveCount,registryEvictionCount:r.registryEvictionCount,registryDeniedCount:r.registryDeniedCount,vcDriftMs:r.vcDriftMs,latenessAvgMs:r.latenessAvgMs,latenessMaxMs:r.latenessMaxMs,lastPresentGapMs:r.lastPresentGapMs,lastPresentFrameTimestampSec:r.lastPresentFrameTimestampSec,lastPresentPlayheadSec:r.lastPresentPlayheadSec,stageDemuxed:r.stageCounters.demuxed,stageDecoded:r.stageCounters.decoded,stageScheduled:r.stageCounters.scheduled,stagePresented:r.stageCounters.presented,dropAtCanvas:r.
88stageCounters.dropAtCanvas,longTaskCount:r.longTaskCount,longTaskMaxMs:r.longTaskMaxMs,playbackMode:r.playbackMode,qualityMode:r.qualityMode,experimentalBudgetsEnabled:r.experimentalBudgetsEnabled,budgetBubbleSize:r.budgetBubbleSize,fastScrubEnabled:r.fastScrubEnabled,fastScrubActive:r.fastScrubActive,scrubVelocity:r.scrubVelocity,fastScrubEntryThreshold:r.fastScrubEntryThreshold,fastScrubExitThreshold:r.fastScrubExitThreshold,systemMetrics:window.__SYSTEM_METRICS_LATEST__||null};ed.current.push(l)};e();let t=setInterval(e,100);return()=>clearInterval(t)},[ei,o]),(0,i.useEffect)(()=>{if(!ei||!o)return;let e=e=>{if("Space"===e.code){em.current="SPACE_KEY";try{let{markSpaceToggleEvent:e}=a(1017);e()}catch{}}};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[ei,o]),!c)return o?(0,r.jsxs)("div",{className:"fixed bg-yellow-900/90 text-yellow-100 p-3 rounded-lg shadow-xl border-2 border-yellow-600 z-[9999] max-w-md text-sm",style:H?{left:H.x,top:H.y}:{top:72,left:16},children:[(0,r.jsx)("div",{className:"font-bold mb-1",children:"â ï¸ WebCodecs Diagnostic"}),(0,r.jsx)("div",{className:"text-xs",children:"Waiting for WebCodecs initialization..."})]}):(0,r.jsxs)("div",{className:"fixed bg-slate-900/90 text-slate-200 p-3 rounded-lg shadow-xl border-2 border-slate-600 z-[9999] max-w-md text-sm",style:H?{left:H.x,top:H.y}:{top:72,left:16},children:[(0,r.jsx)("div",{className:"font-bold mb-1",children:"⸠Logs Disabled"}),(0,r.jsx)("div",{className:"text-xs",children:"WebCodecs panel is paused. Enable logs to resume."})]});let eX=c.totalDecodeCallsAllTime>0,eJ=c.lastDecodeTimestamp?Date.now()-c.lastDecodeTimestamp:null,eZ=null!==eJ&&eJ<1e3,eQ="SCRUB"===ej||eK>.5?"SCRUB":b?.state==="PLAYING"?"PLAYBACK":"OTHER",e0="SCRUB"===eQ?"bg-blue-600 text-white":"PLAYBACK"===eQ?"bg-red-600 text-white":"bg-gray-600 text-white/80",e1=16,e5=window.innerHeight,e2=250+55*Math.max(k.length,4),e4=Math.max(160,e5-(H?.y??72)-e1),e3=Math.min(er?Math.max(e2,470):470,500),e8=Math.min(null!==Z?Z:e3,e4),e6=H?{left:H.x,top:H.y}:{top:72,left:16};e6.height=`${e8}px`,e6.maxHeight=`calc(100vh - ${e1}px)`;let e9=Math.max(4,Math.floor(Math.max(0,e8-250)/55)),e7=k.slice(0,e9),te=j&&(j.pumpWhileVcPaused>0||j.playingWithEmptyBuffer>0||j.hotWithLowBuffer>0),tt=L?.status==="error"?"bg-red-900/60 border-red-500/50":L?.status==="recovered"?"bg-amber-900/50 border-amber-500/40":L?.status==="warning"||A?"bg-amber-900/40 border-amber-500/30":"bg-white/5 border-white/10",ta=(e,t)=>"number"==typeof e&&Number.isFinite(e)?`${e.toFixed(1)}${t}`:" - ",tr=Number.isFinite(eL?.packagePowerWatts)?eL?.packagePowerWatts??null:Number.isFinite(eL?.cpuPowerWatts)||Number.isFinite(eL?.gpuPowerWatts)||Number.isFinite(eL?.anePowerWatts)?(eL?.cpuPowerWatts??0)+(eL?.gpuPowerWatts??0)+(eL?.anePowerWatts??0):null,tn=Number.isFinite(tr)||Number.isFinite(eL?.cpuPowerWatts)||Number.isFinite(eL?.gpuPowerWatts),ti=P&&(e=P.lastReason)?e.length>60?`${e.slice(0,60)}â¦`:e:null,ts=P&&null!=P.lastNodeId?`node #${P.lastNodeId}`:null;return(0,r.jsxs)("div",{ref:J,className:`fixed rounded-lg shadow-xl border-2 z-[9999] select-none cursor-move overflow-hidden flex flex-col ${eX?eZ?"bg-green-900/90 border-green-400":"bg-green-900/70 border-green-600":"bg-red-900/90 border-red-400"}`,style:{...e6,width:"380px",fontSize:"11px"},onMouseDown:eH,children:[(0,r.jsx)("div",{"data-resize-handle":"top",className:"absolute top-0 left-0 right-0 h-2 cursor-ns-resize hover:bg-white/20 transition-colors",onMouseDown:e=>eG(e,"top"),style:{zIndex:10001}}),(0,r.jsxs)("div",{"data-panel-header":!0,className:"flex flex-col border-b border-white/20 pt-2 flex-shrink-0",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between px-2 py-1",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("div",{className:`w-2 h-2 rounded-full ${eZ?"bg-green-400 animate-pulse":eX?"bg-green-600":"bg-red-400"}`}),(0,r.jsx)("span",{className:"font-bold text-white text-xs",children:eX?"â
WebCodecs":"â WebCodecs"}),b&&(0,r.jsx)("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-mono ${"PLAYING"===b.state?"bg-green-600":"PAUSED"===b.state?"bg-yellow-600":"STALLED"===b.state?"bg-orange-600":"bg-gray-600"}`,children:b.state})]}),(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("button",{"data-testid":"webcodecs-logs-toggle",className:`px-2 py-0.5 rounded text-[10px] font-semibold transition-colors ${t?"bg-emerald-600 text-white hover:bg-emerald-500":"bg-slate-700 text-slate-200 hover:bg-slate-600"}`,onClick:e=>{e.stopPropagation(),n()},title:t?"Disable verbose logs":"Enable verbose logs",children:t?"Logs On":"Logs Off"}),(0,r.jsx)("button",{"data-testid":"webcodecs-record-button",disabled:l,className:`px-2 py-0.5 rounded text-[10px] font-semibold transition-colors ${l?"bg-slate-700 text-slate-300 cursor-not-allowed":ei?"bg-red-600 text-white animate-pulse":eo.length>0?"bg-orange-500 text-white hover:bg-orange-400":"bg-red-700 text-white hover:bg-red-600"}`,onClick:e=>{e.stopPropagation(),l||(ei?(es(!1),el(ed.current.slice()),eu(!0)):eo.length>0?eu(!0):(ed.current=[],el([]),ep.current=performance.now(),em.current="RECORD_START",(0,np.de)(),(0,nd.Nk)(),es(!0)))}
88,title:l?"Enable verbose logs using the Logs toggle to record":ei?"Stop recording":eo.length>0?"View recording":"Start recording timeline",children:ei?"â¹ Stop":eo.length>0?`ð ${eo.length}`:"⺠Rec"}),(0,r.jsx)("button",{className:"text-white/70 hover:text-white px-2 text-xs",onClick:e=>{e.stopPropagation(),m(!p)},children:p?"â¼":"â²"})]})]}),L&&(0,r.jsxs)("div",{className:"flex items-center justify-between px-2 py-1 bg-black/20 text-[9px]",children:[(0,r.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,r.jsx)("span",{className:`px-1.5 py-0.5 rounded font-bold ${"ok"===L.status?"bg-green-700 text-green-100":"recovered"===L.status?"bg-amber-500 text-black":"error"===L.status?"bg-red-600 text-white":"warning"===L.status?"bg-yellow-600 text-black":"bg-gray-600 text-white/70"}`,children:"ok"===L.status?"OK":"recovered"===L.status?"RECOVERED":"error"===L.status?"BROKEN":"warning"===L.status?"WARN":" - "}),L.error5Total>0&&(0,r.jsxs)("span",{className:"text-white/60 font-mono",children:[(0,r.jsx)("span",{className:"text-white/80",children:L.error5Total}),(0,r.jsx)("span",{className:"text-white/40",children:" err"}),L.error5Recovered>0&&(0,r.jsxs)("span",{className:"text-green-400",children:[" ",L.error5Recovered,"â"]}),L.error5Unrecovered>0&&(0,r.jsxs)("span",{className:"text-red-400",children:[" ",L.error5Unrecovered,"â"]})]}),L.hasVisualStall&&(0,r.jsx)("span",{className:"text-amber-300",children:"â ï¸ stall"})]}),(0,r.jsxs)("div",{className:"flex items-center gap-1 text-white/60 font-mono",children:[(0,r.jsx)("span",{className:"text-white/40",children:"dec:"}),(0,r.jsx)("span",{className:`${L.activeDecoders>50?"text-yellow-300":L.activeDecoders>100?"text-red-300":"text-white/80"}`,children:L.activeDecoders}),(0,r.jsxs)("span",{className:"text-white/30",children:["/",L.maxDecoders]}),L.softLimitExceeded>0&&(0,r.jsx)("span",{className:"text-yellow-400 ml-0.5",children:"â "})]})]})]}),!o&&(0,r.jsx)("div",{className:"px-2 py-1 text-[10px] text-slate-300 bg-slate-900/60 border-b border-white/10",children:"Logs disabled. Panel is frozen until you re-enable verbose logs with the Logs toggle."}),p&&(0,r.jsxs)("div",{className:"px-2 pb-2 space-y-1 text-white/90 flex-1 min-h-0 overflow-y-auto",children:[eb&&(0,r.jsx)("div",{className:"bg-orange-800/70 rounded p-1 text-[10px] border border-orange-500",children:(0,r.jsxs)("span",{className:"text-orange-200",children:["â ï¸ ",eb]})}),(P?.lastReason||A||R&&R.softLimitExceededCount>0)&&(0,r.jsxs)("div",{className:`rounded p-1.5 border text-[10px] space-y-0.5 ${tt}`,children:[P?.lastReason&&(0,r.jsxs)("div",{className:"flex items-start gap-1",children:[(0,r.jsx)("span",{className:"text-white/50 shrink-0",children:"Last:"}),(0,r.jsxs)("span",{className:`font-mono text-[9px] ${P.unrecoveredCount>0?"text-red-300":"text-white/60"}`,children:[ts&&(0,r.jsxs)("span",{className:"text-white/70",children:[ts," "]}),ti||" - "]})]}),A&&(0,r.jsxs)("div",{className:"text-amber-200 flex items-start gap-1",children:[(0,r.jsx)("span",{className:"shrink-0",children:"â ï¸"}),(0,r.jsxs)("span",{className:"text-white/80",children:["VC PLAYING but 0 frames in ",(A.windowMs/1e3).toFixed(1),"s",(0,r.jsxs)("span",{className:"text-white/50",children:[" (",A.drops," drops)"]})]})]}),R&&(R.softLimitExceededCount>0||R.activeCount>30)&&(0,r.jsxs)("div",{className:"flex justify-between items-center",children:[(0,r.jsx)("span",{className:"text-white/50",children:"Decoders"}),(0,r.jsxs)("span",{className:"font-mono text-white/80",children:[(0,r.jsxs)("span",{className:"text-purple-300",children:[R.byType.worker,"w"]}),(0,r.jsx)("span",{className:"text-white/40",children:" / "}),(0,r.jsxs)("span",{className:"text-white/70",children:[R.byType.mainThread,"m"]}),R.softLimitExceededCount>0&&(0,r.jsxs)("span",{className:"text-yellow-400 ml-1",children:["â limit\xd7",R.softLimitExceededCount]})]})]})]}),b&&(0,r.jsxs)("div",{className:"bg-white/5 rounded px-2 py-1 flex justify-between items-center",children:[(0,r.jsxs)("span",{className:"text-white/60",children:["t=",(0,r.jsxs)("span",{className:"font-mono text-white",children:[b.currentTime.toFixed(2),"s"]}),(0,r.jsxs)("span",{className:"text-white/40",children:["/",b.duration.toFixed(1),"s"]})]}),b.activeSceneIndex>0&&(0,r.jsxs)("span",{className:"text-white/60",children:["Scene ",(0,r.jsx)("span",{className:"font-mono text-white",children:b.activeSceneIndex}),(0,r.jsxs)("span",{className:"text-white/40",children:["/",b.totalScenes]})]})]}),(s||eL)&&(0,r.jsxs)("div",{className:"bg-cyan-900/25 rounded p-1.5 border border-cyan-500/30 text-[10px] space-y-0.5",children:[(0,r.jsxs)("div",{className:"flex justify-between items-center",children:[(0,r.jsx)("span",{className:"text-cyan-200 font-semibold",children:"â¡ LIVE POWER METRICS"}),eL?.timestamp!==void 0&&(0,r.jsxs)("span",{className:"text-cyan-100/70 font-mono",children:["sys@",(eL.timestamp/1e3).toFixed(1),"s"]})]}),eL?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"flex justify-between font-mono text-white/80",children:[(0,r.jsxs)("span",{children:["source ",eL.gpuMetricsSource??" - "," \xb7 C:",ta(tr,"W")," CPU:",ta(eL.cpuPowerWatts,"W")," GPU:",ta(eL.gpuPowerWatts,"W")]}),(0,r.jsxs)("span",{children:["pw/all/other ",ta(eL.playwrightChromeCpu,"%"),"/",ta(eL.allChromeCpu,"%"),"/",ta(eL.otherChromeCpu,"%")]})]}),!tn&&(0,r.jsx)("div",{className:"font-mono text-yellow-200",children:"No wattage sample yet (requires Playwright system metrics collector / powermetrics)."}),(0,r.jsxs)("div",{className:"flex justify-between font-mono text-white/60",children:[(0,r.jsxs)("span",{children:["therm"," ",eL.thermalPressure??(Number.isFinite(eL.fanRpm)?`${Math.round(eL.fanRpm??0)}rpm`:" - ")]}),(0,r.jsxs)("span",{children:["CPU/GPU/SoC ",ta(eL.cpuTempC,"C"),"/",ta(eL.gpuTempC,"C"),"/",ta(eL.socTempC,"C")]})]})]}):(0,r.jsx)("div",{className:"font-mono text-white/60",children:"Waiting for Playwright system metrics collectorâ¦"})]}),te&&(0,r.jsxs)("div",{className:"bg-red-900/60 rounded p-1.5 border border-red-500/50 text-[10px] space-y-0.5",children:[(0,r.jsx)("div",{className:"font-bold text-red-200 text-[10px]",children:"â ï¸ ANOMALIES"}),j.pumpWhileVcPaused>0&&(0,r.jsxs)("div",{className:"text-red-200",children:["⢠Pump while VC paused (",j.pumpWhileVcPaused,")"]}),j.playingWithEmptyBuffer>0&&(0,r.jsxs)("div",{className:"text-red-200",children:["⢠Playing w/ empty buffer (",j.playingWithEmptyBuffer,")"]}),j.hotWithLowBuffer>0&&(0,r.jsxs)("div",{className:"text-yellow-200",children:["⢠HOT w/ low buffer (",j.hotWithLowBuffer,")"]})]}),eR&&(eR.total>0||eR.held>0||eR.transitions>0||!!eR.pendingPair)&&(0,r.jsxs)("div",{className:"bg-orange-900/50 rounded p-1.5 border border-orange-500/40 text-[10px] space-y-0.5",children:[(0,r.jsx)("div",{className:"font-bold text-orange-200 text-[10px]",children:"\uD83D\uDDA4 NO PRESENTABLE FRAME"}),(0,r.jsxs)("div",{className:"flex justify-between",children:[(0,r.jsx)("span",{className:"text-white/70",children:"total/scrub/first"}),(0,r.jsxs)("span",{className:"font-mono text-orange-100",children:[eR.total,"/",eR.scrub,"/",eR.firstCrossScene]})]}),(0,r.jsxs)("div",{className:"flex justify-between",children:[(0,r.jsx)("span",{className:"text-white/70",children:"first-xscene trans/res"}),(0,r.jsxs)("span",{className:"font-mono text-orange-100",children:[eR.transitions,"/",eR.resolved]})]}),eR.held>0&&(0,r.jsxs)("div",{className:"flex justify-between",children:[(0,r.jsx)("span",{className:"text-white/70",children:"held suppressions"}),(0,r.jsxs)("span",{className:"font-mono text-emerald-200",children:[eR.held,"/",eR.heldScrub]})]}),null!==eR.p95LatencyMs&&(0,r.jsxs)("div",{className:"flex justify-between",children:[(0,r.jsx)("span",{className:"text-white/70",children:"first-xscene p95"}),(0,r.jsxs)("span",{className:"font-mono text-orange-100",children:[eR.p95LatencyMs.toFixed(0),"ms"]})]}),eR.pendingPair&&(0,r.jsxs)("div",{className:"text-yellow-200",children:["⢠pending first-xscene: ",eR.pendingPair]}
88),eR.reasonsTop.length>0&&(0,r.jsxs)("div",{className:"text-white/70",children:["⢠reasons: ",eR.reasonsTop.join(", ")]})]}),v&&v.total>0&&(0,r.jsx)("div",{className:"bg-white/5 rounded px-2 py-1",children:(0,r.jsxs)("div",{className:"flex justify-between items-center",children:[(0,r.jsx)("span",{className:"text-white/50 text-[10px] font-semibold",children:"LIFECYCLE"}),(0,r.jsxs)("div",{className:"flex gap-2 font-mono text-[10px]",children:[(0,r.jsxs)("span",{className:"text-red-400",children:["\uD83D\uDD25",v.hot]}),(0,r.jsxs)("span",{className:"text-yellow-400",children:["â³",v.warm]}),(0,r.jsxs)("span",{className:"text-blue-400",children:["âï¸",v.cold]}),(0,r.jsxs)("span",{className:"text-white/30",children:["(",v.total,")"]})]})]})}),W&&O&&(0,r.jsxs)("div",{className:"bg-purple-900/30 rounded px-2 py-1 border border-purple-500/30",children:[(0,r.jsxs)("div",{className:"flex justify-between items-center",children:[(0,r.jsx)("span",{className:"text-purple-300 text-[10px] font-semibold",children:"\uD83C\uDFB0 REGISTRY"}),(0,r.jsxs)("span",{className:"font-mono text-[10px]",children:[(0,r.jsx)("span",{className:"text-white",children:O.activeCount}),(0,r.jsxs)("span",{className:"text-white/40",children:["/",O.hardLimit]}),(0,r.jsxs)("span",{className:"text-white/30 ml-1",children:["(",O.availableSlots," free)"]})]})]}),(0,r.jsxs)("div",{className:"flex justify-between text-[10px] mt-0.5",children:[(0,r.jsxs)("span",{className:"text-white/50",children:["req=",(0,r.jsx)("span",{className:"font-mono text-white/70",children:O.requestCount}),O.evictionCount>0&&(0,r.jsxs)("span",{className:"text-yellow-300 ml-1",children:["evict=",O.evictionCount]}),O.deniedCount>0&&(0,r.jsxs)("span",{className:"text-red-300 ml-1",children:["denied=",O.deniedCount]})]}),(0,r.jsxs)("span",{className:"font-mono text-white/50",children:["m=",O.byPlayerType.master]})]}),(0,r.jsxs)("div",{className:"flex justify-between text-[9px] mt-0.5 text-white/40",children:[(0,r.jsxs)("span",{children:["CRIT=",O.byPriority[0]??0," HI=",O.byPriority[1]??0," ","NORM=",O.byPriority[2]??0," LOW=",O.byPriority[3]??0]}),(0,r.jsxs)("span",{children:["LRU=",O.lruQueueLength]})]})]}),N&&(0,r.jsxs)("div",{className:"bg-white/5 rounded px-2 py-1 space-y-0.5",children:[(0,r.jsx)("div",{className:"text-white/50 text-[10px] font-semibold",children:"FRAMES"}),(0,r.jsxs)("div",{className:"flex justify-between text-[10px]",children:[(0,r.jsxs)("span",{className:"text-white/60",children:["rendered=",(0,r.jsx)("span",{className:"font-mono text-white",children:N.rendered})," ","dropped=",(0,r.jsx)("span",{className:`font-mono ${N.dropped>0?"text-red-300":"text-white"}`,children:N.dropped}),N.reused>0&&(0,r.jsxs)("span",{className:"text-yellow-300",children:[" reused=",N.reused]})]}),(0,r.jsxs)("span",{className:`font-mono ${N.dropPercent>5?"text-red-300":N.dropPercent>1?"text-yellow-300":"text-green-300"}`,children:[N.dropPercent.toFixed(1),"% drop"]})]}),(N.rollingRendered>0||N.rollingDropped>0)&&(0,r.jsxs)("div",{className:"flex justify-between text-[10px] text-white/50",children:[(0,r.jsxs)("span",{children:["last 5s: ",N.rollingRendered,"â ",N.rollingDropped,"â"]}),(0,r.jsxs)("span",{className:N.rollingDropRate>5?"text-red-300":"text-white/50",children:["(",N.rollingDropRate.toFixed(1),"%)"]})]})]}),N&&N.latencySampleCount>0&&(0,r.jsx)("div",{className:"bg-white/5 rounded px-2 py-1",children:(0,r.jsxs)("div",{className:"flex justify-between items-center text-[10px]",children:[(0,r.jsx)("span",{className:"text-white/50 font-semibold",children:"START LATENCY"}),(0,r.jsxs)("span",{className:"font-mono",children:[(0,r.jsxs)("span",{className:`${(N.lastLatencyMs??0)>300?"text-red-300":(N.lastLatencyMs??0)>100?"text-yellow-300":"text-green-300"}`,children:["last=",N.lastLatencyMs?.toFixed(0)??" - ","ms"]}),(0,r.jsxs)("span",{className:"text-white/50 ml-2",children:["avg=",N.avgLatencyMs?.toFixed(0)??" - ","ms"]}),(0,r.jsxs)("span",{className:"text-white/30 ml-1",children:["(n=",N.latencySampleCount,")"]})]})]})}),ev&&(0,r.jsxs)("div",{className:"bg-white/5 rounded px-2 py-1",children:[(0,r.jsxs)("div",{className:"flex justify-between items-center text-[10px]",children:[(0,r.jsx)("span",{className:"text-white/50 font-semibold",children:"INTERACTION"}),(0,r.jsx)("span",{className:"font-mono text-white/70",children:"PENDING"===ev.pendingStatus&&ev.pendingType?(0,r.jsxs)("span",{className:"text-cyan-300",children:[ev.pendingType.toLowerCase(),"â¦",(ev.pen
88dingAgeMs??0).toFixed(0),"ms"]}):(0,r.jsx)("span",{className:"text-white/40",children:"idle"})})]}),(0,r.jsxs)("div",{className:"flex justify-between items-center text-[10px] mt-0.5 font-mono text-white/80",children:[(0,r.jsxs)("span",{children:["seekâ1st=",ev.lastSeekToFirstFrameMs?.toFixed(0)??" - ","ms"]}),(0,r.jsxs)("span",{children:["playâ1st=",ev.lastPlayToFirstFrameMs?.toFixed(0)??" - ","ms"]}),(0,r.jsxs)("span",{children:["playâsmooth=",ev.lastPlayToStableMs?.toFixed(0)??" - ","ms"]})]})]}),(0,r.jsx)(nm,{nodes:er?k:e7,totalMemoryMB:M,lastUpdateMs:T}),(0,r.jsxs)("div",{className:"bg-white/5 rounded px-2 py-1",children:[(0,r.jsxs)("div",{className:"flex justify-between items-center text-[10px]",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:"text-white/50 font-semibold",children:"DECODE"}),(0,r.jsxs)("button",{onClick:eq,className:`px-1 py-0.5 rounded text-[9px] transition-colors ${K?"bg-purple-600 hover:bg-purple-500 text-white":"bg-gray-600/70 hover:bg-gray-500 text-white/80"}`,title:K?"Click to disable worker":"Click to enable worker",children:["Worker ",K?"ON":"OFF"]})]}),(0,r.jsxs)("span",{className:"font-mono text-white/70",children:["main=",(0,r.jsx)("span",{className:"text-white",children:g?.mainThread.total.toLocaleString()??0}),g&&g.worker.total>0&&(0,r.jsxs)("span",{className:"text-purple-300 ml-1",children:["worker=",g.worker.total.toLocaleString()]})]})]}),g&&(g.mainThread.rate>0||g.worker.rate>0)&&(0,r.jsx)("div",{className:"flex justify-end text-[10px] mt-0.5",children:(0,r.jsxs)("span",{className:"font-mono text-white/50",children:[g.mainThread.rate>0&&(0,r.jsxs)("span",{className:g.mainThread.rate>100?"text-yellow-300":"",children:[g.mainThread.rate.toFixed(0),"/s"]}),g.worker.rate>0&&(0,r.jsxs)("span",{className:"text-purple-300 ml-1",children:["+",g.worker.rate.toFixed(0),"/s"]})]})})]}),(0,r.jsxs)("div",{className:"bg-cyan-900/30 rounded px-2 py-1 border border-cyan-500/30",children:[(0,r.jsxs)("div",{className:"flex justify-between items-center text-[10px]",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:"text-cyan-300 text-[10px] font-semibold",children:"\uD83C\uDF9Bï¸ MODE"}),(0,r.jsxs)("button",{"data-testid":"webcodecs-toggle-exp","data-exp-enabled":eM,onClick:()=>{let e=!eM;ng.g.setExperimentalBudgetsEnabled(e),e_(e)},className:`px-1 py-0.5 rounded text-[9px] transition-colors ${eM?"bg-cyan-600 hover:bg-cyan-500 text-white":"bg-gray-600/70 hover:bg-gray-500 text-white/80"}`,title:eM?"Disable experimental budgets":"Enable experimental budgets",children:["Exp ",eM?"ON":"OFF"]}),(0,r.jsxs)("button",{"data-testid":"webcodecs-toggle-quality","data-quality-mode":eN,onClick:()=>{eC(ng.g.toggleQualityMode())},className:`px-1 py-0.5 rounded text-[9px] transition-colors ${eT.active?"bg-orange-500 hover:bg-orange-400 text-white animate-pulse":"LOW"===eN?"bg-orange-600 hover:bg-orange-500 text-white":"bg-gray-600/70 hover:bg-gray-500 text-white/80"}`,title:eT.active?`LOW quality ACTIVE: ${eT.summary}`:"LOW"===eN?"LOW quality (will apply during SCRUB)":"Switch to LOW quality (reduces jank during scrub)",children:["Q:",eN,eT.active?"â¡":""]})]}),(0,r.jsx)("span",{className:`font-mono text-[10px] px-1.5 py-0.5 rounded ${e0}`,title:"Current interaction phase for quick visual validation",children:"PLAYBACK"===eQ?"PLAY":eQ})]}),eM&&eA&&(0,r.jsxs)("div",{className:"flex justify-between text-[9px] mt-0.5 text-white/60 font-mono",children:[(0,r.jsxs)("span",{children:["bubble=",eA.bubble,"f"]}),(0,r.jsxs)("span",{children:["â©",eA.history,"f / âª",eA.lookahead,"f"]}),(0,r.jsxs)("span",{children:["inf=",eA.inflight,eA.maxPPS>0?` ${eA.maxPPS}fps`:""]})]}),eT.active&&(0,r.jsxs)("div",{className:"text-[9px] mt-0.5 text-orange-300 font-mono bg-orange-900/30 rounded px-1 py-0.5",children:["â¡ LOW applied: ",eT.summary]})]}),(0,r.jsxs)("div",{className:`rounded px-2 py-1 border ${eW?"bg-yellow-900/40 border-yellow-500/40":"bg-white/5 border-white/10"}`,children:[(0,r.jsxs)("div",{className:"flex justify-between items-center text-[10px]",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:"text-white/50 font-semibold",children:"\uD83C\uDFC3 SCRUB"}),(0,r.jsxs)("button",{"data-testid":"webcodecs-toggle-fast-scrub","data-fast-scrub-enabled":eO,onClick:eY,className:`px-1 py-0.5 rounded text-[9px] transition-colors ${eO?"bg-green-600 hover:bg-green-500 text-white":"bg-gray-600/70 hover:bg-gray-500 text-white/80"}`,title:eO?"Disable fast scrub optimization":"Enable fast scrub optimization",children:["Fast ",eO?"ON":"OFF"]})]}),(0,r.jsxs)("div",{className:"flex items-center gap-2 font-mono",children:[(0,r.jsx)("span",{className:`px-1.5 py-0.5 rounded ${eW?"bg-yellow-600 text-black animate-pulse":"bg-gray-600/50 text-white/60"}`,children:eW?"â¡ FAST":"NORM"}),eK>0&&(0,r.jsxs)("span",{className:`text-[10px] ${eK>nx.WebCodecsVideoNode.fastScrubEntryThreshold?"text-yellow-300":"text-white/60"}`,children:[eK.toFixed(1),"\xd7"]})]})]}),(eW||eK>.5)&&(0,r.jsxs)("div",{className:"text-[9px] mt-0.5 text-white/50 font-mono",children:["entryâ¥",nx.WebCodecsVideoNode.fastScrubEntryThreshold,"\xd7 / exitâ¤",nx.WebCodecsVideoNode.fastScrubExitThreshold,"\xd7"]})]}),eP&&(eP.total>0||eP.severe>0)&&(0,r.jsxs)("div",{className:"bg-red-900/30 rounded px-2 py-1 border border-red-500/30",children:[(0,r.jsxs)("div",{className:"flex justify-between items-center text-[10px]",children:[(0,r.jsx)("span",{className:"text-red-300 font-semibold",children:"â¡ JANK"}),(0,r.jsxs)("span",{className:"font-mono text-white/70",children:[eP.total,"\xd7 (>50ms)",eP.severe>0&&(0,r.jsxs)("span",{className:"text-red-400 ml-1",children:[eP.severe,"\xd7 severe"]})]})]}),eP.lastAttribution&&(0,r.jsx)("div",{className:"text-[9px] mt-0.5 text-white/60 font-mono truncate",title:eP.lastAttribution,children:eP.lastAttribution.length>60?eP.lastAttribution.slice(0,60)+"...":eP.lastAttribution})]}
88),ek&&(0,r.jsxs)("div",{className:"bg-white/5 rounded px-2 py-1",children:[(0,r.jsxs)("div",{className:"flex justify-between items-center text-[10px]",children:[(0,r.jsx)("span",{className:"text-white/50 font-semibold",children:"PRESSURE"}),(0,r.jsxs)("span",{className:"font-mono text-white/60",children:["peak dec=",ek.peakActiveDecoders,ek.registryEvictionCount>0&&(0,r.jsxs)("span",{className:"text-yellow-300 ml-2",children:["evict=",ek.registryEvictionCount]}),ek.registryDeniedCount>0&&(0,r.jsxs)("span",{className:"text-red-300 ml-2",children:["deny=",ek.registryDeniedCount]})]})]}),(0,r.jsxs)("div",{className:"flex justify-between items-center text-[10px] mt-0.5 font-mono text-white/80",children:[(0,r.jsxs)("span",{children:["active frames=",ek.activeFrames,(0,r.jsxs)("span",{className:"text-white/40",children:[" (peak ",ek.peakActiveFrames,")"]})]}),(0,r.jsxs)("span",{children:["buf=",Math.round(ek.activeBufferDurationMs),"ms",(0,r.jsxs)("span",{className:"text-white/40",children:[" ","(peak ",Math.round(ek.peakActiveBufferDurationMs),"ms)"]})]})]})]}),(0,r.jsxs)("div",{className:"flex justify-between text-[10px] px-1 text-white/40",children:[(0,r.jsxs)("span",{children:[c.decoderInstancesCreated," decoders"]}),c.errors>0&&(0,r.jsxs)("span",{className:"text-red-300",children:[c.errors," errors"]})]}),(0,r.jsxs)("div",{className:"flex justify-center gap-1 pt-1 border-t border-white/10",children:[(0,r.jsx)("button",{className:"text-[9px] bg-white/10 hover:bg-white/20 px-1.5 py-0.5 rounded",onClick:()=>{window.__WEBCODECS_PROOF__?.reset?.(),no.B.reset(),nl.f.reset(),(0,nd.Nk)(),(0,np.de)(),eg.current=null,ex.current=[],E(null),ew(null),eS(null)},children:"Reset"}),(0,r.jsx)("button",{className:"text-[9px] bg-white/10 hover:bg-white/20 px-1.5 py-0.5 rounded",onClick:()=>q(null),children:"Pos"}),(0,r.jsx)("button",{className:"text-[9px] bg-white/10 hover:bg-white/20 px-1.5 py-0.5 rounded",onClick:()=>{no.B.printSummary(),console.log("[FrameMetrics]",nl.f.snapshot())},children:"Log"}),(0,r.jsx)("button",{className:`text-[9px] px-1.5 py-0.5 rounded ${er?"bg-green-600":"bg-white/10 hover:bg-white/20"}`,onClick:()=>en(!er),title:er?"Click to allow manual resize":"Click to expand all nodes",children:"Nodes"}),(0,r.jsx)("button",{className:`text-[9px] px-1.5 py-0.5 rounded ${h?"bg-blue-600":"bg-white/10 hover:bg-white/20"}`,onClick:()=>f(!h),children:"â Info"})]})]}),h&&(0,r.jsx)(nh,{position:H,onClose:()=>f(!1)}),ec&&eo.length>0&&(0,r.jsx)(nf,{snapshots:eo,onClose:()=>eu(!1),onClear:()=>{ed.current=[],el([]),eu(!1)}}),(0,r.jsx)("div",{"data-resize-handle":"bottom",className:"absolute bottom-0 left-0 right-0 h-2 cursor-ns-resize hover:bg-white/20 transition-colors",onMouseDown:e=>eG(e,"bottom"),style:{zIndex:10001}})]})}var ny=a(89959),nv=a(55766),nw=a(73246),nk=a(68051),nS=a(2532),nj=a(87364),nI=a(66609),nN=a(76496);function nC(e,t){let a=[...e.keyframes].sort((e,t)=>e.time-t.time),r=(0,tB.W6)(e,t,a[0]?.value??0),n={id:(0,nN.$C)(),time:t,value:r},i=a.filter(e=>e.time<t).concat(n),s=[{...n,id:(0,nN.$C)(),time:0}].concat(a.filter(e=>e.time>t).map(e=>({...e,id:(0,nN.$C)(),time:e.time-t})));return[{...e,keyframes:i},{...e,keyframes:s}]}function nM(e,t,a,r){return!(a>0)||(e+Math.max(0,t))*a>=r.startPixels-r.marginPixels&&e*a<=r.endPixels+r.marginPixels}var n_=a(85618),nA=a(19707),nE=a(86210),nT=a(95697),n$=a(64577),nP=a(65377),nD=a(37058),nR=a(11036),nz=a(92298);let nL=({label:e,value:t,defaultValue:a,min:n,max:s,step:o,onChange:l,onCommit:d,formatValue:c})=>{let[u,p]=(0,i.useState)(t),m=(0,i.useRef)(!1),h=(0,i.useRef)(t),f=(0,i.useRef)(null);(0,i.useEffect)(()=>{m.current||p(t),h.current=t},[t]),(0,i.useEffect)(()=>()=>{null!==f.current&&cancelAnimationFrame(f.current)},[]);let g=m.current?u:t,x=Math.abs(g-a)>o,b=(0,i.useCallback)(e=>{null!==f.current&&(cancelAnimationFrame(f.current),f.current=null),h.current=e,l(e)},[l]),y=(0,i.useCallback)(e=>{h.current=e,null===f.current&&(f.current=requestAnimationFrame(()=>{f.current=null,l(h.current)}))},[l]),v=(0,i.useCallback)(e=>c?c(e):.01>Math.abs(e)?"0":o>=1?Math.round(e).toString():o>=.1?e.toFixed(1):e.toFixed(2),[c,o]),w=(0,i.useCallback)(e=>{e.stopPropagation(),m.current=!1,p(a),b(a),d?.(a)},[a,b,d]),k=(0,i.useCallback)(e=>{let t=e[0];"number"!=typeof t||Number.isNaN(t)||(m.current=!0,p(t),y(t))},[y]),S=(0,i.useCallback)(e=>{let t=e[0],a="number"!=typeof t||Number.isNaN(t)?u:t;m.current=!1,p(a),b(a),d?.(a)},[b,u,d]);return(0,r.jsxs)("div",{className:"group flex items-center gap-2 h-5",children:[(0,r.jsx)("span",{className:"text-[10px] text-slate-500
88w-16 shrink-0 truncate",children:e}),(0,r.jsxs)(nR.bL,{className:"relative flex-1 flex items-center select-none touch-none h-3",value:[g],min:n,max:s,step:o,onDoubleClick:w,onValueChange:k,onValueCommit:S,children:[(0,r.jsx)(nR.CC,{className:"relative h-[3px] w-full grow rounded-full bg-slate-800",children:(0,r.jsx)(nR.Q6,{className:"absolute h-full rounded-full bg-slate-600"})}),(0,r.jsx)(nR.zi,{className:"block w-[7px] h-[7px] rounded-full bg-slate-300 hover:bg-white focus-visible:outline-none cursor-grab active:cursor-grabbing transition-colors"})]}),(0,r.jsx)("span",{className:`text-[10px] font-mono tabular-nums w-8 text-right shrink-0 ${x?"text-slate-300":"text-slate-600"}`,children:v(g)}),(0,r.jsx)("button",{onClick:w,className:`p-0.5 rounded transition-colors shrink-0 w-4 h-4 flex items-center justify-center ${x?"text-slate-600 hover:text-slate-300 opacity-0 group-hover:opacity-100":"text-transparent opacity-0 pointer-events-none"}`,title:"Reset to default",tabIndex:x?0:-1,"aria-hidden":!x,children:(0,r.jsx)(nz.A,{size:9})})]})},nF=new Set(["fx-AAF_VIDEO_FLIP","fx-BARREL_DISTORT","fx-BLEACH_BYPASS","fx-BLOOM","fx-BRIGHTNESS_CONTRAST","fx-BULGE_PINCH","fx-CANVAS_BLUR","fx-CANVAS_BLUR_2","fx-CANVAS_BLUR_3","fx-CANVAS_BLUR_4","fx-CARTOON","fx-CHROMATIC_ABERRATION","fx-COLOR_SPLASH","fx-CROSS_PROCESS","fx-DITHER","fx-DOT_SCREEN","fx-EDGE_DETECT","fx-EMBOSS","fx-EXPOSURE","fx-FISHEYE","fx-GAMMA","fx-GAUSSIAN_BLUR","fx-GLITCH","fx-GLITCH_BLOCKS","fx-HEXAGONAL_PIXELATE","fx-HORIZONTAL_BLUR","fx-HUE_SATURATION","fx-INVERT","fx-KALEIDOSCOPE","fx-LENS_DISTORTION","fx-LEVELS","fx-LIGHT_LEAK","fx-MIRROR","fx-MONOCHROME","fx-NIGHT_VISION","fx-OIL_PAINTING","fx-OLD_FILM","fx-PIXELATE","fx-POSTERIZE","fx-RADIAL_BLUR","fx-SCANLINES","fx-SEPIA","fx-SHAKE","fx-SHARPEN","fx-SKETCH","fx-SOLARIZE","fx-SPLIT_TONE","fx-SWIRL","fx-TEMPERATURE","fx-THERMAL","fx-THRESHOLD","fx-TILT_SHIFT","fx-TINT","fx-VERTICAL_BLUR","fx-VHS","fx-VIBRANCE","fx-VIGNETTE","fx-VINTAGE","fx-WAVE","fx-ZOOM_BLUR","tr-ADDITIVE_DISSOLVE","tr-BARN_DOOR","tr-BLUR_TRANSITION","tr-BOUNCE","tr-BOX_WIPE","tr-CHECKERBOARD","tr-CLOCK_WIPE","tr-COLOR_PHASE","tr-CROSSFADE","tr-CROSS_ZOOM","tr-CRT_SWITCH","tr-CUBE","tr-DIAGONAL_WIPE","tr-DIAMOND_WIPE","tr-DIRECTIONAL_WARP","tr-DOORWAY","tr-DREAMFADE","tr-FADE_TO_BLACK","tr-FADE_TO_WHITE","tr-FILM_BURN","tr-FLASH","tr-FLIP","tr-GLITCH_TRANSITION","tr-HEART_WIPE","tr-HORIZONTAL_WIPE","tr-INK_SPLASH","tr-IRIS_WIPE","tr-KALEIDOSCOPE_TRANSITION","tr-LIGHT_LEAK","tr-LIGHT_RAYS","tr-LIQUID_MELT","tr-LUMINANCE_DISSOLVE","tr-MORPH","tr-MOSAIC","tr-PAGE_PEEL","tr-PAPER_TEAR","tr-PINWHEEL","tr-PIXELATE_DISSOLVE","tr-PIXEL_SORT","tr-PRISM_SHIFT","tr-PUSH_DOWN","tr-PUSH_LEFT","tr-PUSH_RIGHT","tr-PUSH_UP","tr-RADIAL","tr-RANDOM_DISSOLVE","tr-RGB_SPLIT","tr-RIPPLE_DISSOLVE","tr-ROTATE","tr-SHATTER","tr-SLIDE_LEFT","tr-SLIDE_RIGHT","tr-SPIN_BLUR","tr-SQUEEZE","tr-STAR_WIPE","tr-STATIC_DISSOLVE","tr-SWIRL_TRANSITION","tr-TO_COLOR_AND_BACK","tr-VENETIAN_BLINDS","tr-VERTICAL_WIPE","tr-VHS_REWIND","tr-WATER_DROP","tr-WHIP_PAN","tr-WIND","tr-ZOOM","tr-ZOOM_PUNCH","vfx-anamorphic-streaks","vfx-arcane-runes","vfx-asteroid-field","vfx-bird-flock","vfx-blizzard","vfx-bokeh-dream","vfx-butterflies","vfx-camera-flashes","vfx-candlelight-flicker","vfx-cctv-overlay","vfx-click-ripple","vfx-confetti-burst","vfx-constellation-lines","vfx-crt-scanlines","vfx-dandelion-seeds","vfx-data-stream","vfx-device-frame","vfx-disco-lights","vfx-drifting-mist","vfx-dust-motes","vfx-electric-sparks","vfx-energy-orbs","vfx-falling-ash","vfx-falling-feathers","vfx-falling-leaves","vfx-film-burn","vfx-film-grain","vfx-film-scratches","vfx-fireflies","vfx-fireworks","vfx-floating-bubbles","vfx-floating-embers","vfx-floating-hearts","vfx-floating-petals","vfx-frost-vignette","vfx-gentle-snow","vfx-glitch-vhs","vfx-god-rays","vfx-golden-glitter","vfx-ground-fog","vfx-halftone-pop","vfx-heartbeat-vignette","vfx-heat-haze","vfx-hologram-flicker","vfx-hud-grid","vfx-impact-flash","vfx-incense-smoke","vfx-ink-bleed","vfx-keystroke-pill","vfx-lens-flare","vfx-light-leak","vfx-light-sweep","vfx-lightning-arc","vfx-magic-bloom","vfx-magic-ripple","vfx-matrix-rain","vfx-money-rain","vfx-nebula-drift","vfx-neon-pulse","vfx-northern-lights","vfx-orbiting-rings","vfx-pixel-stars","vfx-plexus-network","vfx-police-lights","vfx-pollen-drift","vfx-portal-vortex","vfx-power-aura","vfx-rain","vfx-rain-on-glass","vfx-rain-ripples","vfx-rainbow-shimmer","vfx-rising-lanterns","vfx-sandstorm","vfx-scan-bars","vfx-screen-cursor","vfx-sea-mist","vfx-searchlight-sweep","vfx-shooting-stars","vfx-smoke-bomb","vfx-soft-smoke","vfx-sparkle-burst","vfx-sparkler-trails","vfx-speed-lines","vfx-spirit-wisps","vfx-star-warp","vfx-starburst-glint","vfx-stardust-trail","vfx-steam-rising","vfx-storybook-god-rays","vfx-thunderstorm","vfx-tv-static","vfx-twinkling-stars","vfx-underwater-caustics","vfx-vignette-pulse","vfx-will-o-wisp","vfx-wind-wisps"]);function nO(e,t){let a=`${e}-${t}`;return nF.has(a)?`/effect-previews/${a}.webp`:null}function nB(){let e=document.querySelector("[data-media-bin-container]"),t=window.innerWidth<900;if(e){let a=e.getBoundingClientRect();if(t){let e=window.innerWidth-16;return{position:"fixed",left:8,top:a.top,width:e,height:a.height,zIndex:67}}return{position:"fixed",left:a.left,top:a.top,width:a.width,height:a.height,zIndex:67}}let a=document.querySelector("[data-master-timeline]"),r=a?a.getBoundingClientRect().top:window.innerHeight-200,n=t?window.innerWidth-16:360;return{position:"fixed",left:t?8:16,top:64,width:n,height:Math.max(200,r-64-8),zIndex:67}}let nW=e=>
88{let[t,a]=(0,i.useState)(()=>nB()),r=(0,i.useRef)(null);return(0,i.useLayoutEffect)(()=>{if(!e)return;a(nB());let t=()=>{null!=r.current&&cancelAnimationFrame(r.current),r.current=requestAnimationFrame(()=>a(nB()))};window.addEventListener("resize",t);let n=null;if("ResizeObserver"in window){n=new ResizeObserver(t);let e=document.querySelector("[data-media-bin-container]");e&&n.observe(e);let a=document.querySelector("[data-master-timeline]");a&&n.observe(a)}return()=>{null!=r.current&&cancelAnimationFrame(r.current),window.removeEventListener("resize",t),n?.disconnect()}},[e]),t};function nU(e){let[t,a]=(0,i.useState)(!1),r=(0,i.useRef)({x:0,width:452}),n=(0,i.useCallback)(t=>{t.preventDefault(),t.stopPropagation();let n=e.current?.getBoundingClientRect().width??452;r.current={x:t.clientX,width:n},a(!0)},[e]);return(0,i.useEffect)(()=>{if(!t)return;let e=e=>{let t=e.clientX-r.current.x,a=eE(r.current.width+t);window.dispatchEvent(new CustomEvent("media-bin-resize",{detail:{width:a}})),window.dispatchEvent(new CustomEvent("media-bin-right-edge-resize",{detail:{rightEdge:a}}))},n=()=>{a(!1),window.dispatchEvent(new Event("media-bin-resize-end"))};return document.body.style.cursor="ew-resize",window.addEventListener("mousemove",e),window.addEventListener("mouseup",n),()=>{document.body.style.cursor="",window.removeEventListener("mousemove",e),window.removeEventListener("mouseup",n)}},[t]),{isResizing:t,onResizeHandleMouseDown:n}}var nK=a(41968);let nV={"sparkle-glimmer":"â¨","wind-wisps":"\uD83C\uDF2Cï¸","magic-bloom":"\uD83C\uDF38",fireflies:"\uD83D\uDD25","storybook-god-rays":"âï¸","magic-ripple":"\uD83C\uDF00","spirit-wisps":"\uD83D\uDC7B","lightning-arc":"â¡","bokeh-dream":"\uD83D\uDCAB","soft-smoke":"\uD83C\uDF2Bï¸","starburst-glint":"\uD83D\uDCA5","northern-lights":"\uD83C\uDF0C","gentle-snow":"âï¸","confetti-burst":"\uD83C\uDF8A","rising-lanterns":"\uD83C\uDFEE","light-leak":"\uD83D\uDD06","floating-bubbles":"\uD83E\uDEE7","matrix-rain":"\uD83D\uDC9A","shooting-stars":"\uD83C\uDF20","ink-bleed":"\uD83D\uDD8Bï¸","floating-petals":"\uD83C\uDF3A","underwater-caustics":"\uD83C\uDF0A",fireworks:"\uD83C\uDF86","glitch-vhs":"\uD83D\uDCFA","twinkling-stars":"â",rain:"\uD83C\uDF27ï¸","falling-leaves":"\uD83C\uDF42","floating-embers":"\uD83D\uDFE0","dust-motes":"\uD83D\uDCA8","dandelion-seeds":"\uD83C\uDF3C",sandstorm:"\uD83C\uDFDCï¸","lens-flare":"\uD83D\uDCF8","heat-haze":"\uD83C\uDF21ï¸","vignette-pulse":"\uD83C\uDFAC","candlelight-flicker":"\uD83D\uDD6Fï¸","stardust-trail":"\uD83C\uDF1F","arcane-runes":"\uD83D\uDD2E","portal-vortex":"\uD83D\uDD73ï¸","will-o-wisp":"\uD83E\uDDDA","money-rain":"\uD83D\uDCB8","power-aura":"\uD83D\uDCAA","sparkler-trails":"\uD83C\uDF87","impact-flash":"\uD83D\uDCA2","film-grain":"\uD83C\uDF9Eï¸","crt-scanlines":"\uD83D\uDDA5ï¸","hud-grid":"\uD83C\uDFAF","hologram-flicker":"\uD83D\uDEF8","ground-fog":"\uD83C\uDF01","rain-on-glass":"\uD83E\uDE9F","steam-rising":"â¨ï¸","anamorphic-streaks":"\uD83C\uDFA5","speed-lines":"\uD83D\uDCA8","light-sweep":"\uD83C\uDF1F","film-burn":"\uD83D\uDD25",thunderstorm:"âï¸","falling-ash":"\uD83C\uDF0B","star-warp":"\uD83D\uDE80","rain-ripples":"\uD83D\uDCA7","frost-vignette":"âï¸","nebula-drift":"\uD83C\uDF0C","pollen-drift":"\uD83C\uDF3C","sea-mist":"\uD83C\uDF0A","film-scratches":"\uD83C\uDF9Eï¸",blizzard:"\uD83C\uDF28ï¸","drifting-mist":"\uD83C\uDF2Bï¸","police-lights":"\uD83D\uDEA8","searchlight-sweep":"\uD83D\uDD26","cctv-overlay":"\uD83D\uDCF9","tv-static":"\uD83D\uDCE1","god-rays":"\uD83C\uDF05","incense-smoke":"\uD83E\uDE94",butterflies:"\uD83E\uDD8B","falling-feathers":"\uD83E\uDEB6","bird-flock":"\uD83D\uDD4Aï¸","asteroid-field":"âï¸","rainbow-shimmer"
88:"\uD83C\uDF08","heartbeat-vignette":"â¤ï¸","electric-sparks":"â¡","energy-orbs":"\uD83D\uDD35","camera-flashes":"\uD83D\uDCF8","smoke-bomb":"\uD83D\uDCA8","neon-pulse":"\uD83D\uDFE3","floating-hearts":"\uD83D\uDC95","golden-glitter":"â¨","disco-lights":"\uD83E\uDEA9","pixel-stars":"\uD83D\uDC7E","halftone-pop":"\uD83D\uDCA5","plexus-network":"\uD83D\uDD78ï¸","scan-bars":"\uD83D\uDCF6","orbiting-rings":"\uD83E\uDE90","constellation-lines":"\uD83C\uDF0C","data-stream":"\uD83D\uDCA0"},nH=new Set(["light","color","stylize","blur","distort","transform"]),nq=[{id:"all",label:"All",Icon:n_.A},{id:"vfx",label:"VFX",Icon:k.A},{id:"filters",label:"Filters",Icon:rQ.A},{id:"classic",label:"Classic",Icon:nA.A},{id:"background",label:"Backdrop",Icon:nE.A},{id:"favorites",label:"Favourites",Icon:nT.A}],nY={light:"from-amber-400/[0.32] via-orange-500/[0.10]",color:"from-fuchsia-400/[0.30] via-pink-500/[0.10]",stylize:"from-violet-400/[0.30] via-purple-500/[0.10]",blur:"from-sky-400/[0.30] via-cyan-500/[0.10]",distort:"from-emerald-400/[0.28] via-teal-500/[0.10]",transform:"from-zinc-300/[0.22] via-slate-400/[0.10]",background:"from-blue-400/[0.30] via-indigo-500/[0.10]",vfx:"from-indigo-400/[0.30] via-violet-500/[0.10]","vfx-filter":"from-cyan-400/[0.26] via-blue-500/[0.10]"},nG=({icon:e,name:t,artClass:a,previewUrl:n,applied:i,disabled:s,comingSoon:o=!1,favorite:l=!1,onToggleFavorite:d,onClick:c,title:u,dragProps:p})=>(0,r.jsxs)("div",{...p,role:"button","aria-pressed":i,title:u,onClick:c,className:`group relative flex select-none flex-col overflow-hidden rounded-md border transition-all duration-150 89 ${i?"border-amber-400/50 bg-amber-400/[0.06] shadow-[0_0_12px_-4px_rgba(251,191,36,0.35)]":"border-white/[0.06] bg-white/[0.02] hover:border-white/[0.16] hover:bg-white/[0.05]"} 90 ${s?"cursor-not-allowed opacity-40":"cursor-pointer"} 91 `,children:[(0,r.jsxs)("div",{className:`relative aspect-[16/9] w-full overflow-hidden bg-gradient-to-br to-transparent ${a}`,children:[n?(0,r.jsx)("img",{src:n,alt:"",loading:"lazy",decoding:"async",draggable:!1,className:"absolute inset-0 h-full w-full object-cover transition-transform duration-200 group-hover:scale-[1.06]"}):(0,r.jsx)("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_72%_130%,rgba(2,6,23,0.6),transparent_62%)]"}),!n&&(0,r.jsx)("span",{className:"absolute inset-0 flex items-center justify-center text-[16px] leading-none drop-shadow-[0_2px_6px_rgba(0,0,0,0.5)] transition-transform duration-200 group-hover:scale-110",children:e}),i&&(0,r.jsx)("span",{className:"absolute left-0.5 top-0.5 flex h-3.5 w-3.5 items-center justify-center rounded-full bg-amber-400 text-slate-950 shadow-sm",children:(0,r.jsx)(n$.A,{size:8,strokeWidth:3.5})}),d&&(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),d()},className:`absolute right-0 top-0 rounded p-[3px] transition-all ${l?"text-amber-300":"text-slate-300/80 opacity-0 hover:text-amber-200 group-hover:opacity-100"}`,title:l?"Remove from favourites":"Add to favourites",children:(0,r.jsx)(nT.A,{size:10,className:l?"fill-amber-300":""})}),o&&(0,r.jsx)("span",{className:"absolute inset-x-0 bottom-0 bg-slate-950/75 py-px text-center text-[7px] font-semibold uppercase tracking-[0.12em] text-amber-300/90 backdrop-blur-sm",children:"Soon"})]}),(0,r.jsx)("div",{className:`truncate px-1 pb-1 pt-0.5 text-center text-[9px] font-medium leading-tight ${i?"text-amber-100":"text-slate-300"}`,children:t})]}),nX=({label:e,count:t})=>(0,r.jsxs)("div",{className:"sticky top-0 z-[1] flex items-center gap-2 bg-slate-950/95 px-3 pb-1.5 pt-2.5 backdrop-blur-sm",children:[(0,r.jsx)("span",{className:"whitespace-nowrap text-[9px] font-semibold uppercase tracking-[0.16em] text-slate-500",children:e}),"number"==typeof t&&(0,r.jsx)("span",{className:"rounded-full bg-white/[0.06] px-1.5 py-px text-[8px] font-medium tabular-nums text-slate-500",children:t}),(0,r.jsx)("div",{className:"h-px flex-1 bg-white/[0.06]"})]}),nJ=({applies:e,children:t})=>(0,r.jsx)("div",{className:e?"":"opacity-40 pointer-events-none select-none",title:e?void 0:"This control has no effect on the selected VFX","aria-disabled":!e,children:t});function nZ(e,t){e&&window.dispatchEvent(new CustomEvent("faceless-studio:effects-change",{detail:{sceneId:e,effects:t}}))}let nQ=({isOpen:e,onClose:t,activePanel:a,onSelectPanel:n,highlightedPanelTabs:s,isKeyframeParameterPickerActive:o=!1,selectedKeyframeParameterKey:l=null,onSelectKeyframeParameter:d,selectedSceneTimelineStart:c=null,selectedSceneId:u,selectedSceneBrightnessSpot:m=null,currentEffects:h,sceneDurationSec:f=0,onApplyEffect:g,onRemoveEffect:x,onUpdateEffect:b,projectFilterPresetId:k=null,projectFilterMixed:S=!1,projectSceneCount:j=0,projectFilterEffect:I=null,onApplyFilterToAllScenes:N,onUpdateProjectFilterParams:C})=>{let M,_,A,[E,T]=(0,i.useState)("all"),[$,P]=(0,i.useState)("all"),[D,R]=(0,i.useState)("library"),[z,L]=(0,i.useState)(null),[F,O]=(0,i.useState)(!1),[B,U]=(0,i.useState)(""),[V,q]=(0,i.useState)(()=>{try{let e=window.localStorage.getItem("timeline.effects.favorites.v1");if(!e)return[];let t=JSON.parse(e);if(!Array.isArray(t))return[];return Array.from(new Set(t.filter(e=>"string"==typeof e)))}catch{return[]}}),Y=nW(e),G=(0,i.useRef)(null),X=(0,i.useRef)(null),{isResizing:J,onResizeHandleMouseDown:Z}=nU(G),Q=(0,i.useMemo)(()=>new Set(V),[V]),ee=(0,y.zC)(e=>e.setSelectedCanvasEffect),et=(0,w.O)(e=>e.effectInspectRequest),ea=(0,w.O)(e=>e.clearEffectInspectRequest),er=(0,i.useRef)(null),en=(0,i.useCallback)(e=>{u&&e&&(0,nK.De)(e)&&ee({sceneId:u,effectId:e.id})},[u,ee]),ei=(0,y.zC)(t=>e&&Number.isFinite(c)?Math.max(0,t.projectTime-c):null),es=(0,i.useMemo)(()=>{let e=new Set;for(let t of(0,nK.CW)(h)){let a="number"==typeof t.params?.preset?t.params.preset:null;null!=a&&e.add(a)}return e},[h]),eo=(0,i.useMemo)(()=>I?(0,nK.mb)(I):null,[I]),[el,ed]=(0,i.useState)(!1),ec=(0,i.useRef)(null);(0,i.useEffect)(()=>
91{if(!e||!0===window.__facelessApplyToAllScenes)return;let t=null;try{t=`${u??""}|${JSON.stringify(h)}`}catch{t=null}(null===t||ec.current!==t)&&(ec.current=t,nZ(u,h))},[e,u,h]),(0,i.useEffect)(()=>{if(!e)return;let t=window.__effectsPanelOpenMode;if(delete window.__effectsPanelOpenMode,"inspect"===t){R("applied"),ed(!1);let e=h[0];e&&L(e.id)}else"add"===t&&(R("library"),L(null),ed(!0))},[e,u]),(0,i.useEffect)(()=>{e&&o&&R("applied")},[e,o]),ep(X,e=>{let t=e.getAttribute("data-effect-type"),a=e.getAttribute("data-drag-icon"),r=e.getAttribute("data-drag-label");return t?{type:"effect",payload:{effectType:t},icon:a||"",label:r||""}:null},e),(0,i.useEffect)(()=>{if(!e||0===h.length)return;let t=er.current;if(t){if(h.some(e=>e.id===t))return;er.current=null}let a=h.find(e=>{if(e.type===nK.de)return!0;let t=t_.EFFECTS.find(t=>t.type===e.type);return t?.paramRanges&&Object.keys(t.paramRanges).length>0});a&&L(a.id)},[e,h]),(0,i.useEffect)(()=>{if(!e||!et||(ea(),et.sceneId!==u))return;let t=h.find(e=>e.id===et.effectId);t&&(er.current=t.id,R("applied"),ed(!1),L(t.id),en(t))},[e,et,u,h,ea,en]),(0,i.useEffect)(()=>{try{window.localStorage.setItem("timeline.effects.favorites.v1",JSON.stringify(V))}catch{}},[V]);let eu=(0,i.useMemo)(()=>{let e,t=B.trim().length>0;if(e="favorites"===E?t_.EFFECTS.filter(e=>Q.has(e.type)):t?t_.EFFECTS.filter(e=>"vfx"!==e.category):"all"===E?t_.EFFECTS.filter(e=>"vfx"!==e.category):"background"===E?(0,t_.getEffectsByCategory)("background"):"classic"===E?"all"===$?t_.EFFECTS.filter(e=>nH.has(e.category)):(0,t_.getEffectsByCategory)($):[],t){let t=B.toLowerCase().trim();e=e.filter(e=>e.name.toLowerCase().includes(t)||e.description.toLowerCase().includes(t)||e.type.toLowerCase().includes(t))}return e},[E,$,B,Q]),em=(0,i.useMemo)(()=>t_.EFFECT_CATEGORIES.filter(e=>nH.has(e.id)),[]),eh=(0,i.useMemo)(()=>nK.PY.filter(e=>(0,nK.Vq)(e.key)),[]),ef=(0,i.useMemo)(()=>{let e=B.toLowerCase().trim(),t=nK.PY.filter(t=>!e||t.name.toLowerCase().includes(e)||t.key.toLowerCase().includes(e));return{regular:t.filter(e=>!(0,nK.Vq)(e.key)),filters:t.filter(e=>(0,nK.Vq)(e.key))}},[B]),eg=B.trim().length>0,ex="vfx"===E||"all"===E||eg&&"favorites"!==E,eb=ex||"filters"===E,ey="vfx"!==E&&"filters"!==E||eg,ev=!!N&&j>0,ew=S?"mixed":null!=k?String(k):"",ek=(0,i.useCallback)(e=>{q(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},[]),eS=(0,i.useCallback)(e=>{if(!u||e.comingSoon)return;let t=h.find(t=>t.type===e.type);if(t)nZ(u,h.filter(e=>e.id!==t.id)),x(u,t.id),z===t.id&&L(null);else{let t=e.createEffect?e.createEffect():{id:(0,v.generateId)(),type:e.type,params:{...e.defaultParams},enabled:!0};nZ(u,[...h.filter(e=>e.type!==t.type),t]),g(u,t),ed(!1),!e.createEffect&&e.paramRanges&&Object.keys(e.paramRanges).length>0&&L(t.id)}},[u,h,g,x,z]),ej=(0,i.useCallback)(e=>{if(!u)return;let t=(0,nK.CW)(h).find(t=>("number"==typeof t.params?.preset?t.params.preset:null)===e);if(t){nZ(u,h.filter(e=>e.id!==t.id)),x(u,t.id),z===t.id&&L(null);return}let a=(0,nK.E3)(e)?.key,r=(0,nK.bT)(a)?m:null,n=(0,nK.cH)(e,1,r),i=(0,nK.Vq)(a)?n:{...n,laneRow:function(e){let t=-1;for(let a of(0,nK.CW)(e)){let e="number"==typeof a.params?.preset?a.params.preset:null,r=null!=e?(0,nK.E3)(e)?.key:null;(0,nK.Vq)(r)||(t=Math.max(t,Math.max(0,Math.round(a.laneRow??0))))}return t+1}(h)};nZ(u,[...h,i]),g(u,i),ed(!1),L(i.id),en(i);let s=r?`anchored@(${r.x.toFixed(2)},${r.y.toFixed(2)})`:(0,nK.bT)(a)?"no-brightest-spotâcenter":"center",o=`[VFX-USER-CHANGE] Scene ${u.slice(0,8)}: user added "${e}" ${s}`;console.log(o),fetch("/api/debug-log",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tag:"VFX-USER-CHANGE",message:o})}).catch(()=>{})},[u,h,z,m,g,x,en]),eI=(0,i.useCallback)(e=>h.some(t=>t.type===e&&t.enabled),[h]),eN=(0,i.useCallback)((e,t,a)=>{u&&(nZ(u,h.map(r=>r.id===e?{...r,params:{...r.params,[t]:a}}:r)),b(u,e,{[t]:a},{persist:!1}))},[u,h,b]),eC=(0,i.useCallback)((e,t,a)=>{u&&(nZ(u,h.map(r=>r.id===e?{...r,params:{...r.params,[t]:a}}:r)),b(u,e,{[t]:a},{persist:!0}))},[u,h,b]),eM=(0,i.useCallback)((e,t,a,r)=>{u&&(nZ(u,h.map(r=>r.id===e?{...r,params:{...r.params,[t]:a}}:r)),b(u,e,{[t]:a},{persist:r}))},[u,h,b]),e_=(0,i.useCallback)((e,t)=>{let a="number"==typeof t.preset.defaultProceduralParams?.glowStrength?t.preset.defaultProceduralParams.glowStrength:.72;eM(e,"glowStrength",t.glowStrength>1e-4?0:Math.max(.08,a),!0)},[eM]),eA=(0,i.useCallback)((e,t,a)=>{C?.({[e]:t},a)},[C]);if(!e)return null;let eE=u?h.length:0,eT=null!=k||S,e$=eE+(ev&&eT?1:0),eP=e=>{let t=es.has(e.id),a=nV[e.key]??"â¨",n=e.name.replace(/\s*\(Animated\)\s
91*$/i,""),i=(0,nK.Vq)(e.key);return(0,r.jsx)(nG,{icon:a,name:n,artClass:nY[i?"vfx-filter":"vfx"],previewUrl:e.proceduralStyle?nO("vfx",e.proceduralStyle):null,applied:t,disabled:!u,title:n,onClick:()=>ej(e.id)},e.id)},eD=(0,r.jsxs)("div",{"data-effects-panel":!0,ref:G,className:"bg-slate-950/95 border border-white/[0.08] rounded-xl shadow-[0_24px_60px_-16px_rgba(0,0,0,0.85),0_0_0_1px_rgba(0,0,0,0.4)] flex flex-col overflow-hidden backdrop-blur-xl",style:Y,children:[(0,r.jsx)("div",{onMouseDown:Z,className:`absolute top-0 right-0 h-full w-2 cursor-ew-resize transition-colors z-10 ${J?"bg-amber-400/20":"hover:bg-amber-400/10"}`}),(0,r.jsxs)("div",{className:"flex items-center justify-between gap-1.5 px-2 py-1.5 border-b border-white/[0.06] bg-gradient-to-b from-slate-900/60 to-slate-950/40",children:[(0,r.jsx)(K,{activePanel:a,onSelectPanel:n,highlightedPanels:s}),(0,r.jsx)("button",{onClick:t,className:"p-1.5 rounded-md text-slate-500 hover:text-slate-200 hover:bg-white/[0.06] transition-colors",title:"Close panel",children:(0,r.jsx)(H.A,{size:13})})]}),(0,r.jsxs)("div",{className:"space-y-1.5 border-b border-white/[0.06] bg-slate-950/60 px-2.5 pb-2 pt-2",children:[(0,r.jsx)("div",{className:"grid grid-cols-2 gap-0.5 rounded-lg border border-white/[0.05] bg-white/[0.03] p-0.5",children:[{id:"library",label:"Library",Icon:n_.A},{id:"applied",label:"Applied",Icon:nA.A}].map(({id:e,label:t,Icon:a})=>{let n=D===e;return(0,r.jsxs)("button",{onClick:()=>R(e),className:`flex h-7 items-center justify-center gap-1.5 rounded-md text-[10.5px] font-medium transition-all duration-150 ${n?"bg-slate-800 text-amber-200 shadow-[inset_0_1px_0_rgba(255,255,255,0.05)] ring-1 ring-white/[0.07]":"text-slate-500 hover:bg-white/[0.04] hover:text-slate-300"}`,"aria-pressed":n,children:[(0,r.jsx)(a,{size:12,className:n?"text-amber-300/80":""}),t,"applied"===e&&e$>0&&(0,r.jsx)("span",{className:`rounded-full px-1.5 py-px text-[8px] font-semibold tabular-nums leading-none ${n?"bg-amber-400/15 text-amber-200":"bg-white/[0.06] text-slate-400"}`,children:e$})]},e)})}),"library"===D&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"relative",children:[(0,r.jsx)(nP.A,{size:13,className:"pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-slate-500"}),(0,r.jsx)("input",{type:"text",value:B,onChange:e=>U(e.target.value),placeholder:"Search effectsâ¦",className:"h-8 w-full rounded-lg border border-white/[0.07] bg-white/[0.04] pl-8 pr-7 text-[11px]\n text-slate-200 placeholder:text-slate-500/80\n transition-all focus:border-amber-400/40 focus:bg-white/[0.06] focus:outline-none focus:ring-2 focus:ring-amber-400/10"}),B&&(0,r.jsx)("button",{onClick:()=>U(""),className:"absolute right-1.5 top-1/2 -translate-y-1/2 rounded p-1 text-slate-500 transition-colors hover:bg-white/[0.06] hover:text-slate-200",title:"Clear search",children:(0,r.jsx)(H.A,{size:11})})]}),(0,r.jsx)("div",{className:"flex items-center gap-0.5 rounded-lg border border-white/[0.05] bg-white/[0.03] p-0.5",children:nq.map(({id:e,label:t,Icon:a})=>{let n=E===e,i="favorites"===e;return(0,r.jsxs)("button",{onClick:()=>T(e),className:`flex h-7 min-w-0 items-center justify-center gap-1 rounded-md text-[10px] font-medium transition-all duration-150 92 ${i?"w-9 shrink-0":"flex-1 px-1"} 93 ${n?"bg-slate-800 text-amber-200 shadow-[inset_0_1px_0_rgba(255,255,255,0.05)] ring-1 ring-white/[0.07]":"text-slate-500 hover:bg-white/[0.04] hover:text-slate-300"}`,"aria-pressed":n,title:t,children:[(0,r.jsx)(a,{size:12,className:`shrink-0 ${n?i?"fill-amber-300 text-amber-300":"text-amber-300/80":""}`}),!i&&(0,r.jsx)("span",{className:"truncate",children:t}),i&&V.length>0&&(0,r.jsx)("span",{className:"text-[8px] tabular-nums leading-none",children:V.length})]},e)})}),"classic"===E&&(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-1 pt-0.5",children:[(0,r.jsx)("button",{onClick:()=>P("all"),className:`whitespace-nowrap rounded-full px-2 py-[3px] text-[9.5px] font-medium transition-colors ${"all"===$?"bg-amber-400/15 text-amber-200 ring-1 ring-amber-400/30":"text-slate-500 ring-1 ring-white/[0.06] hover:bg-white/[0.04] hover:text-slate-300"}`,children:"All"}),em.map(e=>(0,r.jsxs)("button",{onClick:()=>P(e.id),className:`flex items-center gap-1 whitespace-nowrap rounded-full px-2 py-[3px] text-[9.5px] font-medium transition-colors ${$===e.id?"bg-amber-400/15 text-amber-200 ring-1 ring-amber-400/30":"text-slate-500 ring-1 ring-white/[0.06] hover:bg-white/[0.04] hover:text-slate-300"}
93`,children:[(0,r.jsx)("span",{"aria-hidden":!0,className:"text-[10px]",children:e.icon}),e.name]},e.id))]})]})]}),"applied"===D&&ev&&(M=null!=k&&!S&&!!eo&&!!C,(0,r.jsx)("div",{className:"border-b border-white/[0.06] bg-slate-950/50 px-2.5 py-2",children:(0,r.jsxs)("div",{className:`rounded-lg border transition-colors ${eT?"border-amber-400/20 bg-amber-400/[0.04]":"border-white/[0.06] bg-white/[0.02]"}`,children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2 px-2.5 py-2",children:[M?(0,r.jsxs)("button",{type:"button",onClick:()=>O(e=>!e),className:"group flex min-w-0 items-center gap-2 text-left",title:F?"Hide filter controls":"Show filter controls",children:[(0,r.jsx)("span",{className:`flex h-6 w-6 shrink-0 items-center justify-center rounded-md ${eT?"bg-amber-400/15 text-amber-300":"bg-white/[0.05] text-slate-400"}`,children:(0,r.jsx)(rQ.A,{size:12})}),(0,r.jsxs)("div",{className:"min-w-0",children:[(0,r.jsxs)("div",{className:"flex items-center gap-1.5 text-[11px] font-medium text-slate-200",children:[(0,r.jsx)("span",{className:"truncate",children:"Project filter"}),(0,r.jsx)(W.A,{size:11,className:`shrink-0 text-slate-500 transition-transform group-hover:text-slate-300 ${F?"rotate-90":""}`})]}),(0,r.jsx)("div",{className:"text-[9px] leading-tight text-slate-500",children:`All ${j} scene${1===j?"":"s"} \xb7 click to adjust`})]})]}):(0,r.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,r.jsx)("span",{className:`flex h-6 w-6 shrink-0 items-center justify-center rounded-md ${eT?"bg-amber-400/15 text-amber-300":"bg-white/[0.05] text-slate-400"}`,children:(0,r.jsx)(rQ.A,{size:12})}),(0,r.jsxs)("div",{className:"min-w-0",children:[(0,r.jsx)("div",{className:"text-[11px] font-medium text-slate-200",children:"Project filter"}),(0,r.jsx)("div",{className:"truncate text-[9px] leading-tight text-slate-500",children:S?"Scenes differ - pick one to unify":`Applies to all ${j} scene${1===j?"":"s"}`})]})]}),(0,r.jsxs)("select",{value:ew,onChange:e=>{let t=e.target.value;"mixed"!==t&&N?.(""===t?null:Number(t))},title:"Apply a whole-video filter to every scene, or choose None to remove it",className:"max-w-[150px] shrink-0 cursor-pointer rounded-md border border-white/[0.08] bg-slate-900/80 px-2 py-1.5 text-[11px] text-slate-200 outline-none transition-colors hover:border-white/[0.14] focus:border-amber-400/40 focus:ring-1 focus:ring-amber-400/20",children:[S&&(0,r.jsx)("option",{value:"mixed",children:"Mixed"}),(0,r.jsx)("option",{value:"",children:"None"}),eh.map(e=>(0,r.jsx)("option",{value:String(e.id),children:`${nV[e.key]??"â¨"}
93 ${e.name.replace(/\s*\(Animated\)\s*$/i,"")}`},e.id))]})]}),M&&F&&eo&&(0,r.jsx)("div",{className:"px-2.5 pb-2.5",children:(0,r.jsxs)("div",{className:"space-y-0.5 border-t border-white/[0.05] pt-2",children:[(0,r.jsx)(nL,{label:"Opacity",value:eo.opacity??eo.preset.defaultOpacity??.45,defaultValue:eo.preset.defaultOpacity??.45,min:0,max:1,step:.01,onChange:e=>eA("opacity",e,!1),onCommit:e=>eA("opacity",e,!0)}),"procedural-canvas"===eo.preset.renderMode&&(_=eo.preset.proceduralStyle,A=e=>(0,nK.k0)(_,e),(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(nJ,{applies:A("glowStrength"),children:(0,r.jsx)(nL,{label:"Glow",value:eo.glowStrength,defaultValue:eo.preset.defaultProceduralParams?.glowStrength??eo.glowStrength,min:0,max:1.5,step:.01,onChange:e=>eA("glowStrength",e,!1),onCommit:e=>eA("glowStrength",e,!0)})}),(0,r.jsx)(nJ,{applies:A("fieldSpread"),children:(0,r.jsx)(nL,{label:"Field Spread",value:eo.fieldSpread,defaultValue:eo.preset.defaultProceduralParams?.fieldSpread??eo.fieldSpread,min:0,max:1,step:.01,onChange:e=>eA("fieldSpread",e,!1),onCommit:e=>eA("fieldSpread",e,!0)})}),(0,r.jsx)(nJ,{applies:A("radiusNorm"),children:(0,r.jsx)(nL,{label:"Spread",value:eo.radiusNorm,defaultValue:eo.preset.defaultProceduralParams?.radiusNorm??eo.radiusNorm,min:.05,max:.65,step:.01,onChange:e=>eA("radiusNorm",e,!1),onCommit:e=>eA("radiusNorm",e,!0)})}),(0,r.jsx)(nJ,{applies:A("particleCount"),children:(0,r.jsx)(nL,{label:"Density",value:eo.particleCount,defaultValue:eo.preset.defaultProceduralParams?.particleCount??eo.particleCount,min:16,max:220,step:1,onChange:e=>eA("particleCount",e,!1),onCommit:e=>eA("particleCount",e,!0)})}),(0,r.jsx)(nJ,{applies:A("speed"),children:(0,r.jsx)(nL,{label:"Speed",value:eo.speed,defaultValue:eo.preset.defaultProceduralParams?.speed??eo.speed,min:.1,max:3.2,step:.01,onChange:e=>eA("speed",e,!1),onCommit:e=>eA("speed",e,!0)})}),(0,r.jsx)(nJ,{applies:A("sparkleSize"),children:(0,r.jsx)(nL,{label:"Size",value:eo.sparkleSize,defaultValue:eo.preset.defaultProceduralParams?.sparkleSize??eo.sparkleSize,min:.35,max:12,step:.05,onChange:e=>eA("sparkleSize",e,!1),onCommit:e=>eA("sparkleSize",e,!0)})})]}))]})})]})})),"library"===D&&!u&&(0,r.jsxs)("div",{className:"mx-2.5 mt-2.5 flex items-center gap-2.5 rounded-lg border border-amber-400/20 bg-amber-400/[0.06] px-3 py-2.5 text-[11px] text-amber-200/90",children:[(0,r.jsxs)("span",{className:"relative flex h-1.5 w-1.5 shrink-0",children:[(0,r.jsx)("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-amber-300/60"}),(0,r.jsx)("span",{className:"relative inline-flex h-1.5 w-1.5 rounded-full bg-amber-300"})]}),"Select a scene to apply effects"]}),"applied"===D&&(!u||0===h.length)&&(0,r.jsxs)("div",{className:"flex flex-1 flex-col items-center justify-center gap-2.5 px-6 py-10 text-center",children:[(0,r.jsx)(nA.A,{size:18,className:"text-slate-600"}),(0,r.jsx)("p",{className:"max-w-[230px] text-[11px] leading-relaxed text-slate-500",children:u?"No effects on this scene yet.":"Select a scene to see and manage its effects."}),u&&(0,r.jsx)("button",{onClick:()=>R("library"),className:"rounded-md border border-amber-400/30 bg-amber-400/10 px-2.5 py-1.5 text-[10px] font-medium text-amber-200 transition-colors hover:bg-amber-400/15",children:"Browse the library"})]}),"applied"===D&&u&&h.length>0&&(0,r.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col",children:[(0,r.jsx)("div",{className:"select-none bg-gradient-to-b from-slate-900/50 to-transparent px-3 py-2",children:(0,r.jsxs)("div",{className:"flex items-center justify-between",children:[(0,r.jsxs)("span",{className:"flex items-center gap-1.5 text-[9px] font-semibold uppercase tracking-[0.16em] text-slate-400",children:["Effect stack",(0,r.jsx)("span",{className:"rounded-full bg-amber-400/15 px-1.5 py-px text-[8px] font-semibold tabular-nums tracking-normal text-amber-200",children:h.length})]}),(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),nZ(u,[]),h.forEach(e=>x(u,e.id)),L(null)},className:"rounded px-1.5 py-0.5 text-[9px] font-medium uppercase tracking-wide text-slate-500 transition-colors hover:bg-rose-500/10 hover:text-rose-300",children:"Clear all"})]})}),(0,r.jsx)("div",{className:"flex-1 overflow-y-auto scrollbar-hidden px-2 pb-2 space-y-1",children:h.map(e=>
93{let t=t_.EFFECTS.find(t=>t.type===e.type);if(!t)return null;let a=e.type===nK.de,n=a||t.paramRanges&&Object.keys(t.paramRanges).length>0,i=z===e.id,s=a?nY.vfx:nY[t.category]??nY.vfx,c=a?nV[(0,nK.E3)("number"==typeof e.params?.preset?e.params.preset:-1)?.key??""]??t.icon:t.icon;return(0,r.jsxs)("div",{className:`rounded-lg border transition-colors ${i?"border-amber-400/25 bg-white/[0.03]":"border-white/[0.05] bg-white/[0.02] hover:border-white/[0.1] hover:bg-white/[0.04]"}`,children:[(0,r.jsxs)("div",{onClick:()=>{n&&(i||en(e),L(t=>t===e.id?null:e.id))},className:`group flex items-center gap-2 px-1.5 py-1.5 ${n?"cursor-pointer":"cursor-default"}`,children:[(0,r.jsx)("span",{className:`flex h-6 w-6 shrink-0 items-center justify-center rounded-md border border-white/[0.06] bg-gradient-to-br to-transparent text-[13px] leading-none ${s}`,children:c}),(0,r.jsx)("span",{className:"flex-1 truncate text-[11px] font-medium text-slate-200",children:a?function(e,t){if(e.type!==nK.de)return t;let a="number"==typeof e.params?.preset?e.params.preset:null,r=null==a?void 0:(0,nK.E3)(a);
93return r?.name?.replace(/\s*\(Animated\)\s*$/i,"")??t}(e,t.name):t.name}),(0,r.jsx)("div",{className:"flex w-6 items-center justify-center",children:n&&(0,r.jsx)("button",{onClick:t=>{t.stopPropagation(),i||en(e),L(i?null:e.id)},className:`rounded p-1 transition-colors ${i?"bg-amber-400/10 text-amber-300":"text-slate-500 hover:text-slate-200"}`,title:"Adjust parameters",children:(0,r.jsx)(W.A,{size:13,className:`transition-transform ${i?"rotate-90":""}`})})}),(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),ek(t.type)},className:`rounded p-1 transition-colors ${Q.has(t.type)?"text-amber-300 hover:text-amber-200":"text-slate-600 hover:text-slate-300"}`,title:Q.has(t.type)?"Remove from favorites":"Add to favorites",children:(0,r.jsx)(nT.A,{size:12,className:Q.has(t.type)?"fill-amber-300":""})}),(0,r.jsx)("button",{onClick:t=>{t.stopPropagation(),nZ(u,h.filter(t=>t.id!==e.id)),x(u,e.id),z===e.id&&L(null)},className:"rounded p-1 text-slate-600 transition-colors hover:bg-rose-500/10 hover:text-rose-300",title:"Remove effect",children:(0,r.jsx)(tr.A,{size:12})})]}),i&&a&&(()=>{let t,a,n=(0,nK.mb)(e);if(!n)return null;let i=e.id;return(0,r.jsxs)("div",{className:"mx-2 mb-2 space-y-0.5 border-t border-white/[0.05] pt-1.5",children:[(0,r.jsx)(nL,{label:"Opacity",value:n.opacity??.45,defaultValue:n.preset.defaultOpacity??.45,min:0,max:1,step:.01,onChange:e=>eM(i,"opacity",e,!1),onCommit:e=>eM(i,"opacity",e,!0)}),"procedural-canvas"===n.preset.renderMode&&(t=n.preset.proceduralStyle,a=e=>(0,nK.k0)(t,e),(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(nJ,{applies:a("glowStrength"),children:(0,r.jsx)(nL,{label:"Glow",value:n.glowStrength,defaultValue:n.preset.defaultProceduralParams?.glowStrength??n.glowStrength,min:0,max:1.5,step:.01,onChange:e=>eM(i,"glowStrength",e,!1),onCommit:e=>eM(i,"glowStrength",e,!0)})}),(0,r.jsx)(nJ,{applies:a("fieldSpread"),children:(0,r.jsx)(nL,{label:"Field Spread",value:n.fieldSpread,defaultValue:n.preset.defaultProceduralParams?.fieldSpread??n.fieldSpread,min:0,max:1,step:.01,onChange:e=>eM(i,"fieldSpread",e,!1),onCommit:e=>eM(i,"fieldSpread",e,!0)})}),(0,r.jsx)(nJ,{applies:a("centerX"),children:(0,r.jsx)(nL,{label:"Center X",value:n.centerX,defaultValue:n.preset.defaultProceduralParams?.centerX??n.centerX,min:0,max:1,step:.01,onChange:e=>eM(i,"centerX",e,!1),onCommit:e=>eM(i,"centerX",e,!0)})}),(0,r.jsx)(nJ,{applies:a("centerY"),children:(0,r.jsx)(nL,{label:"Center Y",value:n.centerY,defaultValue:n.preset.defaultProceduralParams?.centerY??n.centerY,min:0,max:1,step:.01,onChange:e=>eM(i,"centerY",e,!1),onCommit:e=>eM(i,"centerY",e,!0)})}),(0,r.jsx)(nJ,{applies:a("radiusNorm"),children:(0,r.jsx)(nL,{label:"Spread",value:n.radiusNorm,defaultValue:n.preset.defaultProceduralParams?.radiusNorm??n.radiusNorm,min:.05,max:.65,step:.01,onChange:e=>eM(i,"radiusNorm",e,!1),onCommit:e=>eM(i,"radiusNorm",e,!0)})}),(0,r.jsx)(nJ,{applies:a("particleCount"),children:(0,r.jsx)(nL,{label:"Density",value:n.particleCount,defaultValue:n.preset.defaultProceduralParams?.particleCount??n.particleCount,min:16,max:220,step:1,onChange:e=>eM(i,"particleCount",e,!1),onCommit:e=>eM(i,"particleCount",e,!0)})}),(0,r.jsx)(nJ,{applies:a("speed"),children:(0,r.jsx)(nL,{label:"Speed",value:n.speed,defaultValue:n.preset.defaultProceduralParams?.speed??n.speed,min:.1,max:3.2,step:.01,onChange:e=>eM(i,"speed",e,!1),onCommit:e=>eM(i,"speed",e,!0)})}),(0,r.jsx)(nJ,{applies:a("sparkleSize"),children:(0,r.jsx)(nL,{label:"Size",value:n.sparkleSize,defaultValue:n.preset.defaultProceduralParams?.sparkleSize??n.sparkleSize,min:.35,max:12,step:.05,onChange:e=>eM(i,"sparkleSize",e,!1),onCommit:e=>eM(i,"sparkleSize",e,!0)})}),(0,r.jsx)(nJ,{applies:a("seed"),children:(0,r.jsx)(nL,{label:"Seed",value:n.seed,defaultValue:n.preset.defaultProceduralParams?.seed??n.seed,min:0,max:9999,step:1,onChange:e=>eM(i,"seed",e,!1),onCommit:e=>eM(i,"seed",e,!0)})}),(0,r.jsx)(nJ,{applies:a("glowStrength"),children:(0,r.jsxs)("div",{className:"flex items-center gap-2 h-5",children:[(0,r.jsx)("span",{className:"text-[10px] text-slate-500",children:"Glow Layer"}),(0,r.jsx)("button",{type:"button",onClick:()=>e_(i,n),className:`px-1.5 py-px rounded text-[9px] font-medium transition-colors ${n.glowStrength>1e-4?"bg-amber-500/15 text-amber-200":"text-slate-500 hover:text-slate-300"}`,children:n.glowStrength>1e-4?"On":"Off"})]})})]}))]})}
93)(),i&&n&&!a&&(0,r.jsx)("div",{className:"mx-2 mb-2 space-y-0.5 border-t border-white/[0.05] pt-1.5",children:Object.entries(t.paramRanges).map(([a,n])=>{let i=e.params?.[a]??t.defaultParams[a],s=e.automation?.[a],c=s&&null!=ei?(0,tB.W6)(s,ei,i):i,p=t.defaultParams[a],m=t.paramLabels?.[a]||a,h=u?`scene:${u}:effect:${e.id}:${a}`:null,f=null!==h&&l===h,g=!!(h&&(o||f));return(0,r.jsxs)("div",{className:"flex items-start gap-1.5",children:[g?(0,r.jsx)("button",{type:"button",className:`mt-[3px] flex h-4 w-4 shrink-0 items-center justify-center rounded border transition-colors ${f?"border-amber-300 bg-amber-400/20 text-amber-200":"border-slate-600 text-slate-500 hover:border-amber-400/70 hover:text-amber-200"}`,onClick:t=>{t.stopPropagation(),h&&u&&d?.({key:h,panel:"effects",sceneId:u,effectId:e.id,paramName:a,label:m,min:n.min,max:n.max,step:n.step,defaultValue:p})},title:f?"Selected for keyframe automation":"Select parameter for keyframe automation","aria-label":f?"Selected for keyframe automation":"Select parameter for keyframe automation",children:f?(0,r.jsx)(n$.A,{size:10,strokeWidth:3}):null}):null,(0,r.jsx)("div",{className:"min-w-0 flex-1",children:(0,r.jsx)(nL,{label:m,value:c,defaultValue:p,min:n.min,max:n.max,step:n.step,onChange:t=>eN(e.id,a,t),onCommit:t=>eC(e.id,a,t)})})]},a)})})]},e.id)})})]}),"library"===D&&el&&u&&(0,r.jsxs)("div",{className:"flex items-center justify-center gap-2 px-3 py-2 text-[11px] font-medium text-amber-300/80",children:[(0,r.jsx)("span",{children:"Pick an effect from the library below"}),(0,r.jsx)("svg",{className:"h-3 w-3 animate-bounce",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M8 3v10M4 9l4 4 4-4"})})]}),(0,r.jsx)("div",{ref:X,className:`flex-1 overflow-y-auto pb-2 scrollbar-hidden${"library"===D?"":" hidden"}`,children:(0,r.jsxs)(r.Fragment,{children:[ex&&ef.regular.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(nX,{label:"Regular VFX",count:ef.regular.length}),(0,r.jsx)("div",{className:"grid gap-1.5 px-2.5 pt-0.5 [grid-template-columns:repeat(auto-fill,minmax(64px,1fr))]",children:ef.regular.map(eP)})]}),eb&&ef.filters.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(nX,{label:"Filters",count:ef.filters.length}),(0,r.jsx)("div",{className:"grid gap-1.5 px-2.5 pt-0.5 [grid-template-columns:repeat(auto-fill,minmax(64px,1fr))]",children:ef.filters.map(eP)})]}),ey&&eu.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(nX,{label:ex?"Classic & Backgroun
93d":"classic"===E?"all"===$?"Classic effects":`${em.find(e=>e.id===$)?.name??"Classic"} effects`:"background"===E?"Background effects":"favorites"===E?"Favourites":"Effects",count:eu.length}),(0,r.jsx)("div",{className:"grid gap-1.5 px-2.5 pt-0.5 [grid-template-columns:repeat(auto-fill,minmax(64px,1fr))]",children:eu.map(e=>{let t=eI(e.type),a=!!e.comingSoon,n=!!u&&!a;return(0,r.jsx)(nG,{icon:e.icon,name:e.name,artClass:nY[e.category]??nY.vfx,previewUrl:nO("fx",e.type),applied:t,disabled:!n,comingSoon:a,favorite:Q.has(e.type),onToggleFavorite:()=>ek(e.type),title:`${e.name} - ${e.description}`,onClick:()=>{n&&eS(e)},dragProps:{"data-touch-drag":!0,"data-effect-type":e.type,"data-drag-icon":e.icon,"data-drag-label":e.name,draggable:!a,onDragStart:t=>{if(a)return void t.preventDefault();t.dataTransfer.setData("application/x-effect-type",e.type),t.dataTransfer.effectAllowed="copy";let r=document.createElement("div");r.innerHTML=`<span style="font-size:24px">${e.icon}</span>`,r.style.cssText="position:absolute;top:-1000px;background:#0f172a;padding:8px;border-radius:8px;border:1px solid #fbbf24",document.body.appendChild(r),t.dataTransfer.setDragImage(r,20,20),setTimeout(()=>document.body.removeChild(r),0)}}},e.type)})})]}),(!ey||0===eu.length)&&(!ex||0===ef.regular.length)&&(!eb||0===ef.filters.length)&&(0,r.jsxs)("div",{className:"flex flex-col items-center gap-2 px-4 py-10 text-center",children:["favorites"!==E||eg?(0,r.jsx)(nD.A,{size:18,className:"text-slate-600"}):(0,r.jsx)(nT.A,{size:18,className:"text-slate-600"}),(0,r.jsx)("p",{className:"max-w-[220px] text-[11px] leading-relaxed text-slate-500",children:eg?"No effects match your search.":"favorites"===E?"No favourite effects yet. Star any effect to pin it here.":"No effects available."})]})]})}),(0,r.jsx)("div",{className:"border-t border-white/[0.06] bg-slate-950/80 px-3 py-1.5",children:(0,r.jsx)("p",{className:"text-center text-[9px] text-slate-600",children:"library"===D?"Click to apply \xb7 Drag onto a scene \xb7 Adjust in Applied":"Click an effect to adjust its parameters"})})]});return"u"<typeof document?eD:(0,p.createPortal)(eD,document.body)};var n0=a(52920);function n1(e,t){e&&window.dispatchEvent(new CustomEvent("faceless-studio:transition-change",{detail:{sceneId:e,transition:t}}))}let n5={fade:"from-amber-400/[0.32] via-orange-500/[0.10]",wipe:"from-sky-400/[0.30] via-cyan-500/[0.10]",dissolve:"from-fuchsia-400/[0.30] via-pink-500/[0.10]",slide:"from-emerald-400/[0.28] via-teal-500/[0.10]","3d":"from-violet-400/[0.30] via-purple-500/[0.10]",special:"from-rose-400/[0.28] via-red-500/[0.10]",vfx:"from-indigo-400/[0.34] via-blue-500/[0.12]"};function n2(e){return Math.max(0,Math.min(1,e))}function n4(e){if(!Array.isArray(e)||e.length<3)return"#1a3da6";let[t,a,r]=e,n=e=>Math.round(255*n2(Number.isFinite(e)?e:0)).toString(16).padStart(2,"0");return`#${n(t)}${n(a)}${n(r)}`}let n3=({isOpen:e,onClose:t,activePanel:a,onSelectPanel:n,highlightedPanelTabs:s,isKeyframeParameterPickerActive:o=!1,selectedKeyframeParameterKey:l=null,onSelectKeyframeParameter:d,selectedSceneId:c,currentTransition:u,onApplyTransition:m,onResolveFallbackSceneId:h,onRemoveTransition:f,onUpdateTransition:g,onDurationPreview:x,onDurationPreviewEnd:b})=>{let y,v,[k,S]=(0,i.useState)("all"),[j,I]=(0,i.useState)(""),[N,C]=(0,i.useState)(()=>{try{let e=window.localStorage.getItem("timeline.transitions.favorites.v1");if(!e)return[];let t=JSON.parse(e);if(!Array.isArray(t))return[];return Array.from(new Set(t.filter(e=>"string"==typeof e)))}catch{return[]}}),M=nW(e),_=(0,i.useRef)(null),A=(0,i.useRef)(null),E=(0,i.useRef)(null),{isResizing:T,onResizeHandleMouseDown:$}=nU(_),P=c??"__NO_SCENE__",D=(0,w.O)((0,i.useCallback)(e=>e.transitionListScrollPerScene[P]??0,[P])),R=(0,w.O)(e=>e.rememberTransitionListScroll),z=(0,i.useMemo)(()=>new Set(N),[N]);ep(A,e=>{let t=e.getAttribute("data-transition-type"),a=e.getAttribute("data-drag-icon"),r=e.getAttribute("data-drag-label");return t?{type:"transition",payload:{transitionType:t},icon:a||"",label:r||""}:null},e),(0,i.useEffect)(()=>{try{window.localStorage.setItem("timeline.transitions.favorites.v1",JSON.stringify(N))}catch{}},[N]);let[L,F]=(0,i.useState)(null),O=(0,i.useRef)(!1),B=(0,i.useMemo)(()=>{let e="all"===k?t_.TRANSITIONS:"favorites"===k?t_.TRANSITIONS.filter(e=>z.has(e.type)):(0,t_.getTransitionsByCategory)(k);if(j.trim()){let t=j.toLowerCase().trim();e=e.filter(e=>e.name.toLowerCase().includes(t)||e.description.toLowerCase().includes(t)||e.type.toLowerCase().includes(t))}return e},[k,j,z]),W=(0,i.useCallback)(e=>{C(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},[]);(0,i.useEffect)(()=>
93{if(!e){E.current=null;return}E.current!==P&&A.current&&(E.current=P,requestAnimationFrame(()=>{A.current&&(A.current.scrollTop=D)}))},[e,P,D]);let U=(0,i.useCallback)(e=>{R(P,e.currentTarget.scrollTop)},[R,P]),[V,q]=(0,i.useState)(!1),Y=(0,i.useRef)(null),G=(0,i.useCallback)(()=>{q(!0),Y.current&&clearTimeout(Y.current),Y.current=setTimeout(()=>q(!1),3e3)},[]);(0,i.useEffect)(()=>()=>{Y.current&&clearTimeout(Y.current)},[]);let X=(0,i.useCallback)(e=>{let t=()=>({type:e.type,duration:e.defaultDuration,params:{...e.defaultParams},enabled:!0});if(!c){let e=h?.()??null;if(!e)return void G();let a=t();return n1(e,a),void m(e,a)}if(u?.type===e.type&&u?.enabled){n1(c,void 0),f(c);return}let a=t();n1(c,a),m(c,a)},[c,u,m,f,h,G]),J=(0,i.useCallback)(e=>{O.current=!0,F(e),c&&x&&x(c,e)},[c,x]),Z=(0,i.useCallback)(e=>{c&&u&&(O.current=!1,F(null),b?.(),n1(c,{...u,duration:e}),g(c,{duration:e}))},[c,u,g,b]);(0,i.useCallback)(e=>{c&&u&&(F(null),n1(c,{...u,duration:e}),g(c,{duration:e}))},[c,u,g]);let Q=u?t_.TRANSITIONS.find(e=>e.type===u.type):null,ee=(0,i.useMemo)(()=>{if(!Q||!u)return"#1a3da6";let e=u.params?.color;if(Array.isArray(e))return n4(e);let t=Q.defaultParams?.color;return n4(Array.isArray(t)?t:void 0)},[u,Q]),et=(0,i.useCallback)((e,t)=>{if(!c||!u)return;let a=u.params?.color,r=function(e,t=1){let a=e.replace("#","").trim();if(6!==a.length)return[.1,.24,.65,t];let r=parseInt(a.slice(0,2),16)/255,n=parseInt(a.slice(2,4),16)/255,i=parseInt(a.slice(4,6),16)/255;return[n2(r),n2(n),n2(i),n2(t)]}(e,Array.isArray(a)&&a.length>3&&"number"==typeof a[3]?a[3]:1);n1(c,{...u,params:{...u.params,color:r}}),g(c,{params:{...u.params,color:r}},{persist:t})},[u,g,c]);if(!e)return null;let ea=(0,r.jsxs)("div",{"data-transitions-panel":!0,ref:_,className:"bg-slate-950/95 border border-white/[0.08] rounded-xl shadow-[0_24px_60px_-16px_rgba(0,0,0,0.85),0_0_0_1px_rgba(0,0,0,0.4)] flex flex-col overflow-hidden backdrop-blur-xl",style:M,children:[(0,r.jsx)("div",{onMouseDown:$,className:`absolute top-0 right-0 h-full w-2 cursor-ew-resize transition-colors z-10 ${T?"bg-amber-400/20":"hover:bg-amber-400/10"}`}),(0,r.jsxs)("div",{className:"flex items-center justify-between gap-1.5 px-2 py-1.5 border-b border-white/[0.06] bg-gradient-to-b from-slate-900/60 to-slate-950/40 flex-shrink-0",children:[(0,r.jsx)(K,{activePanel:a,onSelectPanel:n,highlightedPanels:s}),(0,r.jsx)("button",{onClick:t,className:"p-1.5 rounded-md text-slate-500 hover:text-slate-200 hover:bg-white/[0.06] transition-colors",title:"Close panel",children:(0,r.jsx)(H.A,{size:13})})]}),(0,r.jsxs)("div",{className:"space-y-1.5 border-b border-white/[0.06] bg-slate-950/60 px-2.5 pb-2 pt-2",children:[(0,r.jsxs)("div",{className:"relative",children:[(0,r.jsx)(nP.A,{size:13,className:"pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-slate-500"}),(0,r.jsx)("input",{type:"text",value:j,onChange:e=>I(e.target.value),placeholder:"Search transitionsâ¦",className:"h-8 w-full rounded-lg border border-white/[0.07] bg-white/[0.04] pl-8 pr-7 text-[11px]\n text-slate-200 placeholder:text-slate-500/80\n transition-all focus:border-amber-400/40 focus:bg-white/[0.06] focus:outline-none focus:ring-2 focus:ring-amber-400/10"}),j&&(0,r.jsx)("button",{onClick:()=>I(""),className:"absolute right-1.5 top-1/2 -translate-y-1/2 rounded p-1 text-slate-500 transition-colors hover:bg-white/[0.06] hover:text-slate-200",title:"Clear search",children:(0,r.jsx)(H.A,{size:11})})]}),(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-1",children:[(0,r.jsx)("button",{onClick:()=>S("all"),className:`whitespace-nowrap rounded-full px-2 py-[3px] text-[9.5px] font-medium transition-colors ${"all"===k?"bg-amber-400/15 text-amber-200 ring-1 ring-amber-400/30":"text-slate-500 ring-1 ring-white/[0.06] hover:bg-white/[0.04] hover:text-slate-300"}`,children:"All"}),t_.TRANSITION_CATEGORIES.map(e=>(0,r.jsxs)("button",{onClick:()=>S(e.id),className:`flex items-center gap-1 whitespace-nowrap rounded-full px-2 py-[3px] text-[9.5px] font-medium transition-colors ${k===e.id?"bg-amber-400/15 text-amber-200 ring-1 ring-amber-400/30":"text-slate-500 ring-1 ring-white/[0.06] hover:bg-white/[0.04] hover:text-slate-300"}
93`,children:[(0,r.jsx)("span",{"aria-hidden":!0,className:"text-[10px]",children:e.icon}),e.name]},e.id)),(0,r.jsxs)("button",{onClick:()=>S("favorites"),className:`flex items-center gap-1 whitespace-nowrap rounded-full px-2 py-[3px] text-[9.5px] font-medium transition-colors ${"favorites"===k?"bg-amber-400/15 text-amber-200 ring-1 ring-amber-400/30":"text-slate-500 ring-1 ring-white/[0.06] hover:bg-white/[0.04] hover:text-slate-300"}`,children:[(0,r.jsx)(nT.A,{size:9,className:"favorites"===k?"fill-amber-300 text-amber-300":""}),N.length>0?N.length:""]})]})]}),!c&&(0,r.jsxs)("div",{"data-testid":"transitions-panel-hint",className:`mx-2.5 mt-2.5 flex items-center gap-2.5 rounded-lg border px-3 py-2.5 text-[11px] transition-colors ${V?"animate-pulse border-amber-400/60 bg-amber-400/[0.14] text-amber-100":"border-amber-400/20 bg-amber-400/[0.06] text-amber-200/90"}`,children:[(0,r.jsxs)("span",{className:"relative flex h-1.5 w-1.5 shrink-0",children:[(0,r.jsx)("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-amber-300/60"}),(0,r.jsx)("span",{className:"relative inline-flex h-1.5 w-1.5 rounded-full bg-amber-300"})]}),V?"A transition blends two clips. Add or split clips on the timeline first, then tap to apply.":"Tap to apply to a clip, or drag into the gap between scenes"]}),(0,r.jsxs)("div",{ref:A,onScroll:U,className:"flex-1 overflow-y-auto pb-2 scrollbar-hidden",children:["favorites"===k&&0===B.length&&!j.trim()&&(0,r.jsxs)("div",{className:"flex flex-col items-center gap-2 px-4 py-10 text-center",children:[(0,r.jsx)(nT.A,{size:18,className:"text-slate-600"}),(0,r.jsx)("p",{className:"max-w-[220px] text-[11px] leading-relaxed text-slate-500",children:"No favourite transitions yet. Star any transition to pin it here."})]}),0===B.length&&j.trim()&&(0,r.jsxs)("div",{className:"flex flex-col items-center gap-2 px-4 py-10 text-center",children:[(0,r.jsx)(nP.A,{size:18,className:"text-slate-600"}),(0,r.jsx)("p",{className:"max-w-[220px] text-[11px] leading-relaxed text-slate-500",children:"No transitions match your search."})]}),(0,r.jsx)("div",{className:"grid gap-1.5 px-2.5 pt-2 [grid-template-columns:repeat(auto-fill,minmax(64px,1fr))]",children:B.map(e=>{let t=u?.type===e.type&&u?.enabled,a=z.has(e.type),n=n5[e.category]??n5.fade,i=nO("tr",e.type);return(0,r.jsxs)("div",{"data-touch-drag":!0,"data-transition-type":e.type,"data-drag-icon":e.icon,"data-drag-label":e.name,draggable:!0,role:"button","aria-pressed":t,title:`${e.name} - ${e.description}`,onDragStart:t=>{t.dataTransfer.setData("application/x-transition-type",e.type),t.dataTransfer.effectAllowed="copy";let a=document.createElement("div");a.innerHTML=`<span style="font-size: 24px;">${e.icon}</span>`,a.style.cssText="position: absolute; top: -1000px; background: #0f172a; padding: 8px; border-radius: 8px; border: 1px solid #fbbf24;",document.body.appendChild(a),t.dataTransfer.setDragImage(a,20,20),setTimeout(()=>document.body.removeChild(a),0)},onClick:()=>{X(e)},className:`group relative flex select-none flex-col overflow-hidden rounded-md border transition-all duration-150 94 ${t?"border-amber-400/50 bg-amber-400/[0.06] shadow-[0_0_12px_-4px_rgba(251,191,36,0.35)]":"border-white/[0.06] bg-white/[0.02] hover:border-white/[0.16] hover:bg-white/[0.05]"} 95 ${c?"cursor-pointer":"cursor-grab active:cursor-grabbing"} 96 `,children:[(0,r.jsxs)("div",{className:`relative aspect-[16/9] w-full overflow-hidden bg-gradient-to-br to-transparent ${n}`,children:[i?(0,r.jsx)("img",{src:i,alt:"",loading:"lazy",decoding:"async",draggable:!1,className:"absolute inset-0 h-full w-full object-cover transition-transform duration-200 group-hover:scale-[1.06]"}):(0,r.jsx)("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_72%_130%,rgba(2,6,23,0.6),transparent_62%)]"}),!i&&(0,r.jsx)("span",{className:"absolute inset-0 flex items-center justify-center text-[16px] leading-none drop-shadow-[0_2px_6px_rgba(0,0,0,0.5)] transition-transform duration-200 group-hover:scale-110",children:e.icon}),t&&(0,r.jsx)("span",{className:"absolute left-0.5 top-0.5 flex h-3.5 w-3.5 items-center justify-center rounded-full bg-amber-400 text-slate-950 shadow-sm",children:(0,r.jsx)(n$.A,{size:8,strokeWidth:3.5})}),(0,r.jsx)("button",{onMouseDown:e=>e.stopPropagation(),onClick:t=>{t.stopPropagation(),W(e.type)}
96,draggable:!1,className:`absolute right-0 top-0 rounded p-[3px] transition-all ${a?"text-amber-300":"text-slate-300/80 opacity-0 hover:text-amber-200 group-hover:opacity-100"}`,title:a?"Remove from favourites":"Add to favourites",children:(0,r.jsx)(nT.A,{size:10,className:a?"fill-amber-300":""})}),(0,r.jsxs)("span",{className:"absolute bottom-0.5 right-0.5 rounded bg-slate-950/70 px-1 py-px text-[7.5px] font-medium tabular-nums text-slate-300/90 backdrop-blur-sm",children:[e.defaultDuration,"s"]})]}),(0,r.jsx)("div",{className:`truncate px-1 pb-1 pt-0.5 text-center text-[9px] font-medium leading-tight ${t?"text-amber-100":"text-slate-300"}`,children:e.name})]},e.type)})})]}),u&&Q&&c&&(0,r.jsx)("div",{className:"border-t border-white/[0.06] p-2 bg-slate-950/80",children:(0,r.jsxs)("div",{className:"px-2.5 py-2.5 rounded-lg bg-amber-400/[0.04] border border-amber-400/20 space-y-2.5",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:`flex h-6 w-6 shrink-0 items-center justify-center rounded-md border border-white/[0.06] bg-gradient-to-br to-transparent text-[13px] leading-none ${n5[Q.category]??n5.fade}`,children:Q.icon}),(0,r.jsx)("span",{className:"text-[11px] font-medium text-slate-200",children:Q.name})]}),(0,r.jsxs)("div",{className:"flex items-center gap-0.5",children:[(0,r.jsx)("button",{onClick:()=>W(u.type),className:`p-1 rounded-md transition-all duration-150 ${z.has(u.type)?"text-amber-300 hover:text-amber-200":"text-white/20 hover:text-white/50 hover:bg-white/[0.04]"}`,title:z.has(u.type)?"Remove from favorites":"Add to favorites",children:(0,r.jsx)(nT.A,{size:13,className:z.has(u.type)?"fill-amber-300":""})}),(0,r.jsx)("button",{onClick:()=>{n1(c,void 0),f(c)},className:"p-1 rounded-md text-white/20 hover:text-rose-300 hover:bg-rose-500/[0.08] transition-all duration-150",children:(0,r.jsx)(tr.A,{size:13})})]})]}),(v=null!==(y=c?`scene:${c}:transition:duration`:null)&&l===y,(0,r.jsxs)("div",{className:"flex items-start gap-1.5",children:[y&&(o||v)?(0,r.jsx)("button",{type:"button",className:`mt-[3px] flex h-4 w-4 shrink-0 items-center justify-center rounded-[4px] border transition-all duration-150 ${v?"border-amber-400/50 bg-amber-400/15 text-amber-200":"border-white/[0.1] text-white/25 hover:border-amber-400/40 hover:text-amber-200"}`,onClick:e=>{e.stopPropagation(),y&&c&&d?.({key:y,panel:"transitions",sceneId:c,paramName:"duration",label:"Duration",min:.1,max:2,step:.05,defaultValue:Q.defaultDuration})},title:v?"Selected for keyframe automation":"Select parameter for keyframe automation","aria-label":v?"Selected for keyframe automation":"Select parameter for keyframe automation",children:v?(0,r.jsx)(n$.A,{size:10,strokeWidth:3}):null}):null,(0,r.jsx)("div",{className:"min-w-0 flex-1",children:(0,r.jsx)(nL,{label:"Duration",value:L??u.duration,defaultValue:Q.defaultDuration,min:.1,max:2,step:.05,onChange:J,onCommit:Z,formatValue:e=>`${e.toFixed(2)}s`})})]})),Q.paramRanges&&Object.keys(Q.paramRanges).length>0&&(0,r.jsx)("div",{className:"pt-2 border-t border-white/[0.04] space-y-0.5",children:Object.entries(Q.paramRanges).map(([e,t])=>{if("mix"===e||"progress"===e)return null;let a=u.params?.[e]??Q.defaultParams[e],n=Q.defaultParams[e],i=Q.paramLabels?.[e]||e,s=c?`scene:${c}:transition:param:${e}`:null,p=null!==s&&l===s;return(0,r.jsxs)("div",{className:"flex items-start gap-1.5",children:[s&&(o||p)?(0,r.jsx)("button",{type:"button",className:`mt-[3px] flex h-4 w-4 shrink-0 items-center justify-center rounded-[4px] border transition-all duration-150 ${p?"border-amber-400/50 bg-amber-400/15 text-amber-200":"border-white/[0.1] text-white/25 hover:border-amber-400/40 hover:text-amber-200"}`,onClick:a=>{a.stopPropagation(),s&&c&&d?.({key:s,panel:"transitions",sceneId:c,paramName:e,label:i,min:t.min,max:t.max,step:t.step,defaultValue:n})},title:p?"Selected for keyframe automation":"Select parameter for keyframe automation","aria-label":p?"Selected for keyframe automation":"Select parameter for keyframe automation",children:p?(0,r.jsx)(n$.A,{size:10,strokeWidth:3}):null}):null,(0,r.jsx)("div",{className:"min-w-0 flex-1",children:(0,r.jsx)(nL,{label:i,value:a,defaultValue:n,min:t.min,max:t.max,step:t.step,onChange:t=>{n1(c,{...u,params:{...u.params,[e]:t}}),g(c,{params:{...u.params,[e]:t}},{persist:!1})},onCommit:t=>{n1(c,{...u,params:{...u.params,[e]:t}}),g(c,{params:{...u.params,[e]:t}},{persist:!0})}})})]},e)})}),c&&Array.isArray(u.params?.color)&&(0,r.jsx)("div",{className:"pt-2 border-t border-white/[0.04]",children:(0,r.jsxs)("div",{className:"flex items-center gap-2.5",children:[(0,r.jsxs)("span",{className:"text-[10px] text-white/30 w-14 shrink-0 flex items-center gap-1",children:[(0,r.jsx)(n0.A,{size:10}),"Color"]}),(0,r.jsx)("input",{type:"color",value:ee,onChange:e=>et(e.target.value,!1),onBlur:e=>et(e.target.value,!0),className:"h-5 w-8 cursor-pointer rounded-md border border-white/[0.08] bg-[#0a0e1a] p-0","aria-label":"Dip to color"}),(0,r.jsx)("span",{className:"text-[10px] text-white/25 font-mono uppercase",children:ee})]})})]})}),(0,r.jsx)("div",{className:"border-t border-white/[0.06] bg-slate-950/80 px-3 py-1.5",children:(0,r.jsx)("p",{className:"text-center text-[9px] text-slate-600",children:"Tap to apply to a clip \xb7 Drag between scenes"})})]});return"u"<typeof document?ea:(0,p.createPortal)(ea,document.body)};var n8=a(12651),n6=a(34026),n9=a(69072),n7=a(79267),ie=a(36619),it=a(50825);let ia=e=>e?e.replace(/\[removed\]/g,"").replace(/\[deleted\]/g,"").replace(/^Post by u\/[^:]+:\s*/i,"").trim():"";var ir=a(84209),ii=a(92602);let is=null,io=async()=>(is||(is=await a.e(5391).then(a.bind(a,45391))),is),il=null,id=async()=>(il||(il=await a.e(8013).then(a.bind(a,58013))),il),ic=e=>"supertonic"===e?id():io(),iu="voiceover_panel_gemini_api_key",ip={"gemini-2.5-flash":.036,"gemini-3.1-flash":.036,elevenlabs:.15,speechify:.01},im=(e,t)=>e<=0||t<=0?0:Math.max(1,Math.ceil(t/1e3*e/.005*1.5)),ih=e=>e<=0?"0":e<10?Number(e.toFixed(1)).toString():String(Math.round(e)),ig=e=>ih(e/.005*1.5),ix=({isOpen:e,onClose:t,activePanel:n,onSelectPanel:o,projectId:l,addVoiceover:d,selectedSceneId:c,selectedSceneText:u,selectedSceneStart:m})=>{let h,f=nW(e),g=(0,i.useRef)(null),{isResizing:b,onResizeHandleMouseDown:w}=nU(g),S=!1;try{let{currentProject:e}=(0,s.By)();h=e?.id,S=e?.mode==="local"}catch{h=void 0,S=!1}let j=l||h,{voices:I,isLoading:N,selectedVoiceId:C,setSelectedVoiceId:M}=(0,eU.f)(),[_,A]=(0,i.useState)(""),E=(0,i.useRef)(""),[T,$]=(0,i.useState)(!1),[P,D]=(0,i.useState)(null),[R,z]=(0,i.useState)(null),[L,F]=(0,i.useState)(!1),O
96=(0,i.useRef)(null),[B,W]=(0,i.useState)(0),[U,V]=(0,i.useState)(!1),[q,Y]=(0,i.useState)("cpu"),[G,X]=(0,i.useState)("cpu"),[J,Z]=(0,i.useState)(!1);(0,i.useEffect)(()=>{Y((0,ii.yH)("tts_device_kokoro","cpu")),X((0,ii.yH)("tts_device_supertonic","cpu")),Z((0,ii.cF)())},[]);let Q=(0,i.useCallback)(async(e,t)=>{if("gpu"!==t||(0,ii.cF)()){"supertonic"===e?X(t):Y(t);try{let a=await ic(e);a.setDevice?.(t)}catch(e){console.warn("[VoiceoverPanel] Failed to set device:",e)}}},[]),ee=(0,i.useRef)(null),[et,ea]=(0,i.useState)(null),[er,en]=(0,i.useState)(!1),ei=(0,i.useRef)(""),[es,eo]=(0,i.useState)(()=>C?.startsWith("sp_")?"speechify":C?.startsWith("st_")?eV.x3?"speechify":"supertonic":C?.match(/^(af_|am_|bf_|bm_)/)?eV.x3?"speechify":"kokoro":C&&!C.startsWith("gemini_")?eV.Wt?"speechify":"elevenlabs":C?.startsWith("gemini_")?"gemini":"speechify");(0,i.useEffect)(()=>{eV.x3&&C&&(0,eV.Kz)(C)&&(eo("speechify"),M(eV.SA))},[C,M]);let[el,ed]=(0,i.useState)({stability:.5,similarity_boost:.75,style:0,speaker_boost:!1,speed:1}),[ec,eu]=(0,i.useState)(""),[ep,em]=(0,i.useState)(ir._6);(0,i.useEffect)(()=>{let e=window.localStorage.getItem(iu);e&&eu(e)},[]),(0,i.useEffect)(()=>{ec.trim().length>0?window.localStorage.setItem(iu,ec.trim()):window.localStorage.removeItem(iu)},[ec]);let eh=(0,i.useCallback)((t={})=>{if(!e)return;let a=window.__facelessStudioTargetPlanSceneId,r=window.__facelessStudioTargetNleSceneId,n=c||r;if(!n&&!a)return;let i=t.settings??el,s=t.provider??es,o=t.voiceId??C,l=I.find(e=>e.voice_id===o),d=e=>"speechify"===s?eb(e):"kokoro"===s?ef(e):"gemini"===s?eg(e):"supertonic"===s?ex(e):!eb(e)&&!ef(e)&&!eg(e)&&!ex(e),u=!!l&&d(l),p=I.find(d),m=u?o:p?.voice_id??o;window.dispatchEvent(new CustomEvent("faceless-studio:voice-settings-change",{detail:{sceneId:n,planSceneId:a,provider:s,voiceId:m,speed:i.speed,stability:i.stability,similarityBoost:i.similarity_boost,style:i.style,speakerBoost:i.speaker_boost}}))},[e,c,C,el,es,I]),ef=e=>e.voice_id.match(/^(af_|am_|bf_|bm_)/)||e.name.includes("(Kokoro)"),eg=e=>e.voice_id.startsWith("gemini_")||e.name.includes("(Google)"),ex=e=>e.voice_id.startsWith("st_")||e.name.includes("(Supertonic)"),eb=e=>e.voice_id.startsWith("sp_")||e.name.includes("(Speechify)"),ey=I.filter(e=>"speechify"===es?eb(e):"kokoro"===es?ef(e):"gemini"===es?eg(e):"supertonic"===es?ex(e):!eb(e)&&!ef(e)&&!eg(e)&&!ex(e)),ev=(0,i.useMemo)(()=>"string"==typeof u?ia(u):"",[u]);(0,i.useEffect)(()=>{!e||ev&&A(e=>0!==e.trim().length&&e!==E.current||e===ev?e:(E.current=ev,ev))},[e,c,ev]),(0,i.useEffect)(()=>{if(!e)return;let t=e=>{let t=e.detail??{};if("string"!=typeof t.text)return;let a=window.__facelessStudioTargetPlanSceneId;if(a){if(t.planSceneId!==a)return;A(t.text),E.current=t.text;return}A(e=>0!==e.trim().length&&e!==E.current||e===t.text?e:(E.current=t.text,t.text))};return window.addEventListener("faceless-studio:narration-text-change",t),()=>{window.removeEventListener("faceless-studio:narration-text-change",t)}},[e]),(0,i.useEffect)(()=>{if(("kokoro"===es||"supertonic"===es)&&e){let e,t=!1;return ic(es).then(a=>{!t&&(e=a.onLoadProgress(e=>{W(e),V(e>0&&e<100)}),V(a.isTTSLoading()),W(a.getLoadProgress()),a.isTTSLoaded()||a.isTTSLoading()||a.preloadTTS())}),()=>{t=!0,e&&e()}}},[es,e]),(0,i.useEffect)(()=>{ey.length>0&&(ey.some(e=>e.voice_id===C)||M(ey[0].voice_id))},[es,ey,C,M]),(0,i.useEffect)(()=>{let e=e=>{if(e&&"object"==typeof e){if("start"===e.phase){eo("gemini"),"string"==typeof e.text&&e.text.trim().length>0&&A(e.text),"string"==typeof e.voiceId&&e.voiceId.trim().length>0&&M(e.voiceId.trim()),D(null),$(!0);return}if("success"===e.phase){"string"==typeof e.text&&e.text.trim().length>0&&A(e.text),"string"==typeof e.voiceId&&e.voiceId.trim().length>0&&M(e.voiceId.trim()),$(!1);return}"error"===e.phase&&("string"==typeof e.text&&e.text.trim().length>0&&A(e.text),D(e.error||"AI voiceover generation failed."),$(!1))}},t=t=>{e(t.detail)};window.addEventListener("ai-editor:voiceover-status",t);let a=window.__AI_EDITOR_VOICEOVER_STATUS__;return a&&e(a),()=>{window.removeEventListener("ai-editor:voiceover-status",t)}},[M]),(0,i.useEffect)(()=>
96{if(!e){ei.current="";return}let t=window.__facelessStudioTargetPlanSceneId,a=window.__facelessStudioTargetVoiceSettings;if(!t||!a||eV.Wt&&"elevenlabs"===a.provider)return;let r="kokoro"===a.provider||"gemini"===a.provider||"elevenlabs"===a.provider||"supertonic"===a.provider?a.provider:null,n="string"==typeof a.voiceId&&a.voiceId.trim().length>0?a.voiceId.trim():null,i=`${t}:${r??""}:${n??""}`;ei.current!==i&&(ei.current=i,r&&eo(r),n&&M(n),ed(e=>({...e,..."number"==typeof a.speed?{speed:a.speed}:{},..."number"==typeof a.stability?{stability:a.stability}:{},..."number"==typeof a.similarityBoost?{similarity_boost:a.similarityBoost}:{},..."number"==typeof a.style?{style:a.style}:{},..."boolean"==typeof a.speakerBoost?{speaker_boost:a.speakerBoost}:{}})))},[e,M]);let ew=(e,t)=>{ed(a=>{let r={...a,[e]:t};return eh({settings:r}),r})},ek=(0,i.useCallback)(async()=>{let e=ey.find(e=>e.voice_id===C);if(!e)return;if(et===e.voice_id){ee.current?.pause(),ea(null);return}let t=(e,t)=>{ee.current&&ee.current.pause();let a=new Audio(e);ee.current=a,ea(t),a.onended=()=>ea(null),a.onerror=()=>ea(null),a.play().catch(()=>ea(null))};if(e.preview_url)return void t(e.preview_url,e.voice_id);en(!0);try{let{fetchVoiceSampleUrl:r}=await Promise.resolve().then(a.bind(a,12282)),n=await r(e);n&&t(n,e.voice_id)}catch(e){console.warn("[VoiceoverPanel] Failed to load voice sample:",e)}finally{en(!1)}},[ey,C,et]),eS=(0,i.useCallback)(async e=>{let t=("string"==typeof e?.text?e.text:_).trim(),a="string"==typeof e?.voiceId&&e.voiceId.trim().length>0?e.voiceId.trim():C,r=e?.provider??es,n="kokoro"===r||"supertonic"===r||!!(a&&(0,eV.Kz)(a)),i=eV.x3&&n?"speechify":r,s=eV.x3&&n?eV.SA:a,o="string"==typeof e?.requestId&&e.requestId.trim().length>0?e.requestId.trim():(0,tP.q7)(e?.source==="ai-editor"?"ai-runtime":"voiceover-panel"),u=Math.ceil(t.length/15),p=y.zC.getState(),f=!!c&&(p.selectedSceneId===c||p.selectedSceneIds.includes(c)||[p.selectedAudioBlockId,...p.selectedAudioBlockIds].some(e=>!!e&&p.blocks.some(t=>t.id===e&&t.sceneId===c))),g=f?p.blocks.find(e=>"scene"===e.type&&e.sceneId===c)?.start:void 0,x=e?.source==="ai-editor"||f?0:((e,t,a)=>{let r=Math.max(.001,a),n=Number.isFinite(t)?Math.max(0,t):0;for(let t of e.filter(e=>"voiceover"===e.type&&Number.isFinite(e.start)&&Number.isFinite(e.duration)&&e.duration>0).map(e=>({start:Math.max(0,e.start),end:Math.max(0,e.start)+e.duration})).sort((e,t)=>e.start-t.start||e.end-t.end))if(!(t.end<=n+.001)){if(n+r<=t.start+.001)break;n=t.end}return n})(p.blocks,p.projectTime,u),b="number"==typeof e?.startSeconds&&Number.isFinite(e.startSeconds)?Math.max(0,e.startSeconds):"number"==typeof g&&Number.isFinite(g)?Math.max(0,g):f&&"number"==typeof m&&Number.isFinite(m)?Math.max(0,m):x,w="number"==typeof e?.trackId&&Number.isFinite(e.trackId)?Math.max(0,Math.trunc(e.trackId)):2,k="number"==typeof e?.volume&&Number.isFinite(e.volume)?Math.min(2,Math.max(0,e.volume)):1;if(console.log("[VoiceoverPanel] Generate clicked:",{text:t,voiceId:s,projectId:j,provider:i}),!t||!s)return console.log("[VoiceoverPanel] Missing text or voiceId"),null;t!==_&&A(t),i!==es&&eo(i),s!==C&&M(s),D(null),$(!0);try{let a,r,n,p=null,m=f?c??void 0:void 0,g={voiceId:s,stability:el.stability,similarityBoost:el.similarity_boost,style:el.style,speakerBoost:el.speaker_boost,speed:el.speed};(0,tP.Fz)("manual_generate_click",{requestId:o,traceSource:e?.source==="ai-editor"?"ai-runtime":"voiceover-panel",projectId:j??null,projectMode:S?"local":"cloud",provider:i,textLength:t.length,selectedVoiceId:s});let x="kokoro"===i||"supertonic"===i||"gemini"!==i&&"elevenlabs"!==i&&(ef({voice_id:s,name:""})||ex({voice_id:s,name:""})),y="supertonic"===i||ex({voice_id:s,name:""})?"supertonic":"kokoro";if(x){if(console.log(`[VoiceoverPanel] Using browser TTS (${y}), isLocalProject:`,S),!j)return D("No project selected. Please open a project first."),console.log("[VoiceoverPanel] No project found for Kokoro upload"),null;let i=`standalone-vo-${(0,v.generateId)()}`,l=await (0,tP.createProjectKokoroVoiceover)({projectId:j,isLocalProject:S,text:t,voiceId:s,generationId:`${y}-vo-${(0,v.generateId)()}`,voiceoverId:i,durationSeconds:u,startSeconds:b,trackId:w,volume:k,settings:g,requestId:o,traceSource:e?.source==="ai-editor"?"ai-runtime":"voiceover-panel",engine:y});a=l.playbackUrl,r=l.persistenceUrl,n=l.storageKey,p={...l.voiceover,sourceSce
96neId:l.voiceover.sourceSceneId??m},console.log("[VoiceoverPanel] Kokoro generation complete:",{playbackUrl:a,persistenceUrl:r,storageKey:n}),(0,tP.Fz)("manual_generate_complete",{requestId:o,traceSource:e?.source==="ai-editor"?"ai-runtime":"voiceover-panel",projectId:j,projectMode:S?"local":"cloud",provider:y,finalUrl:r,storageKey:n??null,durationSeconds:p.duration})}else if("gemini"===i||"speechify"===i||eg({voice_id:s,name:""})||eb({voice_id:s,name:""})){console.log("[VoiceoverPanel] Using server TTS, voice:",s);let e=await (0,tz.generateFreeVoiceAudio)({text:t,voice_id:s,speed:el.speed,apiKey:ec.trim()||void 0,projectId:j??void 0,model:ep});if(e.error||!e.blob)return D(e.error||"Voice generation returned no audio"),null;let i=URL.createObjectURL(e.blob);if(a=i,j&&!S){let a=await (0,tz.uploadBrowserAudio)(e.blob,j,`gemini-vo-${(0,v.generateId)()}`,t);a.url?(r=a.url,n=a.storageKey):r=i}else r=i;console.log("[VoiceoverPanel] Gemini generation complete:",{blobSize:e.blob.size,persistenceUrl:r?.slice(0,50)})}else{if(!j)return D("No project selected. Please open a project first."),console.log("[VoiceoverPanel] No project found:",{propProjectId:l,contextProjectId:h}),null;let e=`standalone-vo-${(0,v.generateId)()}`,i={text:t,voice_id:s,project_id:j,scene_id:e,stability:el.stability,similarity_boost:el.similarity_boost,style:el.style,use_speaker_boost:el.speaker_boost,output_format:"mp3_44100_128"};console.log("[VoiceoverPanel] Using API TTS:",i);let o=await (0,tz.Qq)(i);if(o.error)throw Error(o.error.message);if(!o.audio?.src)throw Error("No audio URL in response");a=o.audio.src,r=o.url||o.audio.src,n=o.storageKey,console.log("[VoiceoverPanel] API TTS generated, playbackUrl:",a?.slice(0,50),"persistenceUrl:",r?.slice(0,50),"storageKey:",n)}console.log("[VoiceoverPanel] Audio generated successfully"),z(a);let I={id:`standalone-vo-${(0,v.generateId)()}`,type:"voiceover",url:r,storageKey:n||void 0,start:b,duration:u,trackId:w,inOffset:0,outOffset:u,volume:k,text:t,sourceSceneId:m,settings:g,status:"ready",generatedAt:Date.now(),createdAt:Date.now(),updatedAt:Date.now()},N=p??I;if(e?.skipProjectPersist)console.log("[VoiceoverPanel] skipProjectPersist set - returning voiceover without saving:",N.id);else if(d)try{console.log("[DEBUG-AUDIO] About to call addVoiceover:",{id:N.id,url:N.url,storageKey:N.storageKey,status:N.status,duration:N.duration,type:N.type}),(0,tP.Fz)("manual_add_voiceover_start",{requestId:o,traceSource:e?.source==="ai-editor"?"ai-runtime":"voiceover-panel",projectId:j??null,projectMode:S?"local":"cloud",voiceoverId:N.id,finalUrl:N.url??null,storageKey:N.storageKey??null,durationSeconds:N.duration??null}),await d(N),console.log("[DEBUG-AUDIO] addVoiceover completed successfully:",N.id),(0,tP.Fz)("manual_add_voiceover_success",{requestId:o,traceSource:e?.source==="ai-editor"?"ai-runtime":"voiceover-panel",projectId:j??null,projectMode:S?"local":"cloud",voiceoverId:N.id,finalUrl:N.url??null,storageKey:N.storageKey??null}),console.log("[VoiceoverPanel] Voiceover persisted to project timeline:",N.id)}catch(t){console.error("[DEBUG-AUDIO] addVoiceover FAILED:",t),(0,tP.Fz)("manual_add_voiceover_error",{requestId:o,traceSource:e?.source==="ai-editor"?"ai-runtime":"voiceover-panel",projectId:j??null,projectMode:S?"local":"cloud",voiceoverId:N.id,error:t instanceof Error?t.message:String(t)}),console.error("[VoiceoverPanel] Error persisting voiceover:",t)}else console.warn("[VoiceoverPanel] addVoiceover not provided - voiceover will not appear on timeline");return setTimeout(()=>{O.current&&(O.current.src=a,O.current.load(),O.current.play().then(()=>F(!0)).catch(e=>console.error("[VoiceoverPanel] Autoplay error:",e)))},100),{requestId:o,provider:i,voiceId:s,playbackUrl:a,persistenceUrl:r,storageKey:n??void 0,voiceover:N}}catch(e){throw console.error("[VoiceoverPanel] Error generating voiceover:",e),D(e instanceof Error?e.message:"Failed to generate voiceover"),e}finally{$(!1)}},[d,h,ec,ep,S,l,j,C,c,m,M,el.similarity_boost,el.speaker_boost,el.stability,el.style,el.speed,es,_]);(0,i.useEffect)(()=>(window.__AI_EDITOR_GENERATE_VOICEOVER__=eS,()=>{window.__AI_EDITOR_GENERATE_VOICEOVER__===eS&&delete window.__AI_EDITOR_GENERATE_VOICEOVER__}),[eS]);let ej=ec.trim().length>0,eI="elevenlabs"===es?ip.elevenlabs:"speechify"===es?ip.speechify:"gemini"!==es||ej?0:ip["gemini-3.1-flash"===ep?"gemini-3.1-flash":"gemini-2.5-flash"],eN=eI>0&&_.length>0?ih(im(eI,_.length)):null;if(!e)return null;let eC=(0,r.jsxs)("div",{"data-voiceover-panel":!0,ref:g,className:"bg-slate-950/95 border border-white/[0.08] rounded-xl shadow-[0_24px_60px_-16px_rgba(0,0,0,0.85),0_0_0_1px_rgba(0,0,0,0.4)] flex flex-col overflow-hidden backdrop-blur-xl",style:f,children:[(0,r.jsx)("div",{onMouseDown:w,className:`absolute top-0 right-0 h-full w-2 cursor-ew-resize transition-colors z-10 ${b?"bg-amber-400/20":"hover:bg-amber-400/10"}`}),(0,r.jsxs)("div",{className:"flex items-center justify-between gap-1.5 px-2 py-1.5 border-b border-white/[0.06] bg-gradient-to-b from-slate-900/60 to-slate-950/40 flex-shrink-0",children:[(0,r.jsx)(K,{activePanel:n,onSelectPanel:o}),(0,r.jsx)("button",{onClick:t,className:"p-1.5 rounded-md text-slate-500 hover:text-slate-200 hover:bg-white/[0.06] transition-colors",title:"Close panel",children:(0,r.jsx)(H.A,{size:13})})]}),(0,r.jsxs)("div",{className:"flex-1 overflow-y-auto p-2.5 space-y-2.5 scrollbar-hidden",children:[(0,r.jsxs)("div",{className:"rounded-xl border border-white/[0.05] bg-white/[0.02] p-2.5 space-y-2",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("label",{className:"text-[9px] font-semibold uppercase tracking-[0.14em] text-slate-500 mb-1.5 block",children:"Provider"}),(0,r.jsx)("div",{className:`grid gap-1.5 ${eV.x3?"grid-cols-3":"grid-cols-5"}`,children:[{key:"speechify",name:"Speechify",badge:"Best",Icon:nT.A,pro:!1,best:!0},{key:"gemini",name:"Google",badge:"",Icon:k.A,pro:!1,best:!1},...!eV.x3?[{key:"kokoro",name:"Kokoro",badge:"Free \xb7 Local",Icon:n8.A,pro:!1,best:!1},{key:"supertonic",name:"Supertonic",badge:"Free \xb7 Local",Icon:n6.A,pro:!1,best:!1}]:[],{key:"elevenlabs",name:"ElevenLabs",badge:"Pro",Icon:n9.A,pro:!0,best:!1}].map(({key:e,name:t,badge:a,Icon:n,pro:i,best:s})=>{let o=es===e,l="elevenlabs"===e&&eV.Wt;return(0,r.jsxs)("button",{type:"button",disabled:l,title:l?"ElevenLabs voices are coming soon":s?"Our pick - best-quality narration with consistent takes":void 0,onClick:()=>{l||(eo(e),eh({provider:e}))},className:`flex flex-col items-center gap-0.5 rounded-md border px-1 py-1.5 transition-colors ${l?"curs
96or-not-allowed border-white/[0.06] bg-white/[0.02] text-slate-500 opacity-60":o?"border-amber-400/50 bg-amber-400/[0.08] text-amber-50":"border-white/[0.06] bg-white/[0.02] text-slate-300 hover:border-white/[0.14] hover:bg-white/[0.05]"}`,children:[(0,r.jsx)(n,{size:13,className:l?"text-slate-500":s?"text-emerald-300":i?"text-amber-300":o?"text-amber-300/80":"text-slate-400"}),(0,r.jsx)("span",{className:"max-w-full truncate text-[10px] font-semibold leading-tight",children:t}),(l||a)&&(0,r.jsx)("span",{className:`rounded px-1 text-[7px] font-semibold uppercase tracking-wide leading-tight ${l?"bg-white/[0.06] text-slate-400":s?"bg-emerald-500/15 text-emerald-300":i?"bg-amber-500/15 text-amber-300/90":"text-slate-500"}`,children:l?"Coming Soon":a})]},e)})})]}),(0,r.jsxs)("div",{className:"flex items-end gap-2",children:[(0,r.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,r.jsx)("label",{className:"text-[9px] font-semibold uppercase tracking-[0.14em] text-slate-500 mb-1.5 block",children:"Voice"}),(0,r.jsx)("select",{value:C,onChange:e=>{M(e.target.value),eh({voiceId:e.target.value})},className:"w-full px-2 py-[5px] bg-white/[0.04] border border-white/[0.07] rounded-md text-[11px] text-slate-200\n focus:outline-none focus:border-amber-400/40 focus:ring-1 focus:ring-amber-400/20 transition-colors",disabled:N||0===ey.length,children:N?(0,r.jsx)("option",{children:"Loading..."}):0===ey.length?(0,r.jsx)("option",{children:"No voices"}):ey.map(e=>(0,r.jsx)("option",{value:e.voice_id,children:e.name},e.voice_id))})]}),(0,r.jsxs)("button",{type:"button",onClick:ek,disabled:er||!C,className:`flex items-center gap-1 px-2 py-[5px] rounded-md border text-[10px] font-medium transition-colors shrink-0 ${et===C?"border-amber-400/50 bg-amber-400/10 text-amber-200":er?"border-white/[0.07] bg-white/[0.03] text-slate-500 cursor-wait":"border-white/[0.07] bg-white/[0.03] text-slate-400 hover:border-amber-400/40 hover:text-amber-200"}`,title:et===C?"Stop sample":"Play sample",children:[er?(0,r.jsx)(x.A,{size:10,className:"animate-spin"}):et===C?(0,r.jsx)(n7.A,{size:10}):(0,r.jsx)(ie.A,{size:10}),er?"Wait":et===C?"Stop":"Sample"]})]}),("kokoro"===es||"supertonic"===es)&&(0,r.jsxs)("div",{className:"space-y-1.5",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,r.jsx)("span",{className:"text-[9px] font-semibold uppercase tracking-[0.14em] text-slate-500",children:"Device"}),(0,r.jsx)("div",{className:"inline-flex rounded-md border border-white/[0.06] bg-white/[0.03] p-0.5",children:["cpu","gpu"].map(e=>{let t=("supertonic"===es?G:q)===e,a="gpu"===e&&!J;return(0,r.jsx)("button",{type:"button",disabled:a,onClick:()=>Q(es,e),title:a?"WebGPU not available in this browser":void 0,className:`rounded px-2 py-0.5 text-[10px] font-medium transition-all ${t?"bg-slate-800 text-amber-200 ring-1 ring-white/[0.07]":a?"cursor-not-allowed text-slate-600":"text-slate-400 hover:text-slate-200"}`,children:"cpu"===e?"CPU":"GPU"},e)})})]}),!U&&100===B&&(0,r.jsxs)("div",{className:"text-[9px] text-slate-400 flex items-center gap-1.5",children:[(0,r.jsx)("span",{className:"w-1.5 h-1.5 bg-emerald-400 rounded-full shrink-0"}),"supertonic"===es?"Supertonic":"Kokoro"," model ready - runs locally in your browser"]}),U&&(0,r.jsxs)("div",{className:"p-2 bg-white/[0.02] border border-white/[0.06] rounded-md",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 text-[10px] text-slate-300 mb-1",children:[(0,r.jsx)(it.A,{size:10,className:"animate-pulse text-slate-400"}),(0,r.jsxs)("span",{children:["Loading ","supertonic"===es?"Supertonic":"Kokoro"," model (",B,"%)"]})]}),(0,r.jsx)("div",{className:"h-1 bg-slate-800 rounded overflow-hidden",children:(0,r.jsx)("div",{className:"h-full bg-amber-400 transition-all duration-300",style:{width:`${B}%`}})}),(0,r.jsxs)("p",{className:"text-[9px] text-slate-500 mt-1",children:["First-time download (","supertonic"===es?"~99MB":"~86MB",")"]})]}),!U&&B<100&&(0,r.jsxs)("div",{className:"text-[9px] text-slate-400 flex items-center gap-1.5",children:[(0,r.jsx)(k.A,{size:9,className:"text-slate-500 shrink-0"}),"supertonic"===es?"Supertonic - free, local, on-device voice synthesis":"Kokoro - free browser-based voice synthesis"]})]}),"elevenlabs"===es&&(0,r.jsxs)("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-2 py-1.5",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-1.5",children:[(0,r.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,r.jsx)(n9.A,{size:11,className:"text-amber-300 shrink-0"}),(0,r.jsx)("span",{className:"text-[10px] font-semibold text-amber-100",children:"ElevenLabs \xb7 Pro"})]}),(0,r.jsxs)("span",{className:"rounded bg-amber-500/20 px-1.5 py-0.5 text-[9px] font-semibold text-amber-100",children:[ig(ip.elevenlabs)," cr / 1k chars"]})]}),(0,r.jsx)("p",{className:"mt-1 text-[9px] leading-snug text-amber-200/80",children:"Highe
96st-quality premium voices - the most credit-intensive option (~4\xd7 the Google voices)."}),_.length>0&&(0,r.jsxs)("p",{className:"mt-1 text-[9px] font-medium text-amber-100/90",children:["â ",ih(im(ip.elevenlabs,_.length))," ","credits for this script (",_.length," chars)"]})]}),"speechify"===es&&(0,r.jsxs)("div",{className:"rounded-md border border-emerald-500/20 bg-emerald-500/[0.05] px-2 py-1.5","data-testid":"voiceover-speechify-our-pick",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-1.5",children:[(0,r.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,r.jsx)(nT.A,{size:11,className:"text-emerald-300 shrink-0"}),(0,r.jsx)("span",{className:"text-[10px] font-semibold text-emerald-100",children:"Speechify \xb7 Our pick"})]}),(0,r.jsxs)("span",{className:"rounded bg-emerald-500/20 px-1.5 py-0.5 text-[9px] font-semibold text-emerald-100",children:[ig(ip.speechify)," cr / 1k chars"]})]}),(0,r.jsx)("p",{className:"mt-1 text-[9px] leading-snug text-emerald-200/80",children:"Best-quality narration with consistent takes - the voice we recommend for every video."}),_.length>0&&(0,r.jsxs)("p",{className:"mt-1 text-[9px] font-medium text-emerald-100/90",children:["â"," ",ih(im(ip.speechify,_.length))," ","credits for this script (",_.length," chars)"]})]}),"gemini"===es&&(0,r.jsxs)("div",{className:"space-y-1.5",children:[(0,r.jsxs)("div",{className:"text-[9px] text-slate-400 flex items-center gap-1.5",children:[(0,r.jsx)(k.A,{size:9,className:"text-slate-500 shrink-0"}),"Google - cloud voice generation (BYOK supported)"]}),ej&&(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{className:"mb-1 flex items-center justify-between",children:[(0,r.jsx)("label",{className:"text-[9px] font-semibold uppercase tracking-[0.14em] text-slate-500 block",children:"Model"}),(0,r.jsx)("span",{className:"text-[9px] text-slate-500",children:"gemini-2.5-flash"===ep?"Free with your API key \xb7 default":"Best quality \xb7 free with your API key"})]}),(0,r.jsx)("div",{className:"inline-flex w-full rounded-md border border-white/[0.06] bg-white/[0.03] p-0.5",children:[{key:"gemini-2.5-flash",label:"2.5 Flash",pro:!1,free:!0},{key:"gemini-3.1-flash",label:"3.1 Flash",pro:!0,free:!1}].map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>em(e.key),className:`flex flex-1 items-center justify-center gap-1 rounded px-2 py-0.5 text-[10px] font-medium transition-all ${ep===e.key?"bg-slate-800 text-amber-200 ring-1 ring-white/[0.07]":"text-slate-400 hover:text-slate-200"}`,children:[e.label,e.pro&&(0,r.jsx)("span",{className:"rounded bg-amber-500/20 px-1 text-[7px] font-semibold uppercase leading-tight text-amber-200",children:"Pro"}),e.free&&ej&&(0,r.jsx)("span",{className:"rounded bg-emerald-500/15 px-1 text-[7px] font-semibold uppercase leading-tight text-emerald-300",children:"Free"})]},e.key))})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("label",{className:"text-[9px] font-semibold uppercase tracking-[0.14em] text-slate-500 mb-1 block",children:"Google API Key (Optional)"}),(0,r.jsx)("input",{type:"password",value:ec,onChange:e=>eu(e.target.value),placeholder:"Paste your Gemini API key (AIza...)",className:"w-full px-2 py-1.5 bg-white/[0.04] border border-white/[0.07] rounded-md text-[11px] text-slate-200\n placeholder:text-slate-500 focus:outline-none focus:border-amber-400/40 focus:ring-1 focus:ring-amber-400/20 transition-colors"}),(0,r.jsx)("p",{className:"mt-1 text-[9px] text-slate-500",children:"Stored locally in this browser. If left empty, server key is used (if available)."})]})]})]}),"elevenlabs"===es&&(0,r.jsxs)("div",{className:"rounded-xl border border-white/[0.05] bg-white/[0.02] p-2.5 space-y-1.5",children:[(0,r.jsx)("span",{className:"text-[9px] font-semibold uppercase tracking-[0.14em] text-slate-500 block",children:"Voice Settings"}),(0,r.jsx)(nL,{label:"Speed",value:el.speed,defaultValue:1,min:.7,max:1.2,step:.01,onChange:e=>ew("speed",e),onCommit:e=>ew("speed",e)}),(0,r.jsx)(nL,{label:"Stability",value:el.stability,defaultValue:.5,min:0,max:1,step:.01,onChange:e=>ew("stability",e),onCommit:e=>ew("stability",e)}),(0,r.jsx)(nL,{label:"Similarity",value:el.similarity_boost,defaultValue:.75,min:0,max:1,step:.
9601,onChange:e=>ew("similarity_boost",e),onCommit:e=>ew("similarity_boost",e)}),(0,r.jsx)(nL,{label:"Style",value:el.style,defaultValue:0,min:0,max:1,step:.01,onChange:e=>ew("style",e),onCommit:e=>ew("style",e)}),(0,r.jsxs)("div",{className:"flex items-center gap-2 pt-0.5",children:[(0,r.jsx)("label",{className:"text-[10px] text-slate-400",children:"Speaker Boost"}),(0,r.jsx)("button",{onClick:()=>ew("speaker_boost",!el.speaker_boost),className:`relative inline-flex h-4 w-7 items-center rounded-full transition-colors ${el.speaker_boost?"bg-amber-500/60":"bg-slate-700"}`,children:(0,r.jsx)("span",{className:`inline-block h-2.5 w-2.5 transform rounded-full bg-white transition-transform ${el.speaker_boost?"translate-x-3.5":"translate-x-0.5"}`})})]})]}),(0,r.jsxs)("div",{className:"rounded-xl border border-white/[0.05] bg-white/[0.02] p-2.5",children:[(0,r.jsx)("label",{className:"text-[9px] font-semibold uppercase tracking-[0.14em] text-slate-500 mb-1.5 block",children:"Voiceover Text"}),(0,r.jsx)("textarea",{value:_,onChange:e=>{let t=e.target.value;A(t);let a=window.__facelessStudioTargetPlanSceneId,r=window.__facelessStudioTargetNleSceneId;(a||r||c)&&window.dispatchEvent(new CustomEvent("faceless-studio:voiceover-text-change",{detail:{planSceneId:a,sceneId:c||r,text:t}}))},placeholder:"Enter text to convert to speech...",className:"w-full h-20 px-2 py-1.5 bg-white/[0.04] border border-white/[0.07] rounded-md text-xs text-slate-200\n placeholder:text-slate-500 resize-none\n focus:outline-none focus:border-amber-400/40 focus:ring-1 focus:ring-amber-400/20 transition-colors"}),(0,r.jsxs)("div",{className:"flex justify-between items-center mt-1",children:[(0,r.jsxs)("span",{className:"text-[9px] text-slate-500",children:[_.length," chars",eN&&` \xb7 â ${eN} credits`]}),(0,r.jsxs)("button",{onClick:()=>{eS({source:"manual"})},disabled:!_.trim()||!C||T,className:`flex items-center gap-1 px-2.5 py-1 rounded-md text-[10px] font-medium transition-colors border ${!_.trim()||!C||T?"bg-white/[0.02] text-slate-500 border-white/[0.05] cursor-not-allowed":"bg-amber-400/10 text-amber-200 border-amber-400/30 hover:bg-amber-400/15"}`,children:[T&&(0,r.jsx)(x.A,{size:10,className:"animate-spin"}),T?"Generating...":"Generate"]})]}),P&&(0,r.jsx)("div",{className:"mt-1.5 px-2 py-1 bg-rose-900/40 border border-rose-800/50 rounded text-[10px] text-rose-200",children:P}),R&&(0,r.jsxs)("div",{className:"mt-2 flex items-center gap-2 p-1.5 bg-white/[0.02] rounded-md border border-white/[0.06]",children:[(0,r.jsx)("button",{onClick:()=>{O.current&&R&&(L?O.current.pause():O.current.play().catch(console.error),F(!L))},className:"p-1.5 rounded-md bg-slate-800 text-slate-100 hover:bg-slate-700 transition-colors",children:L?(0,r.jsx)(n7.A,{size:12}):(0,r.jsx)(ie.A,{size:12})}),(0,r.jsx)("div",{className:"flex-1",children:(0,r.jsxs)("div",{className:"flex items-center gap-1.5 text-[9px] text-slate-400",children:[(0,r.jsx)(rG.A,{size:10}),(0,r.jsx)("span",{children:"Generated Audio"})]})}),(0,r.jsx)("audio",{ref:O,src:R,onEnded:()=>{F(!1)},crossOrigin:"anonymous",className:"hidden"})]})]})]}),(0,r.jsx)("div",{className:"px-3 py-1.5 border-t border-white/[0.06] bg-slate-950/80 flex-shrink-0",children:(0,r.jsx)("p",{className:"text-center text-[9px] text-slate-600",children:"Settings apply to new voiceovers"})})]});return"u"<typeof document?eC:(0,p.createPortal)(eC,document.body)};var ib=a(99314),iy=a(34779),iv=a(73689);let iw=[30,60,90],ik=/^[0-9a-f]{24}$/i;async function iS(e){var t;let a=e.prompt.trim();if(!a)throw Error("Describe the track first (mood, genre, instruments).");let r=await (0,aA.qZ)({idempotencyKey:`music-${(0,v.generateId)()}`,project_id:e.projectId,scene_id:"music-track",project_mode:ik.test(e.projectId)?"cloud":"local",prompt:a,job_type:"music_track",duration_target:Number.isFinite(t=e.durationSeconds)?Math.round(Math.max(30,Math.min(90,t))):60});if(!r.success||!r.data?.jobId)throw Error(r.error?.message||"Could not start the music generation.");return{jobId:r.data.jobId,creditsCharged:r.data.creditsCharged??0}}async function ij(e,t){let a=Date.now();for(;;){let r=await (0,aA.eb)(e),n=r.success?r.data:null;if(n){if(t?.(n.progress??0),"completed"===n.status)return n;if("failed"===n.status)throw Error(n.error||"Music generation failed - credits were refunded.")}if(Date.now()-a>
9678e4)throw Error("Music generation is taking longer than expected - if it finishes it will appear in your tracks, otherwise the credits are refunded automatically.");await new Promise(e=>globalThis.setTimeout(e,4e3))}}let iI=e=>{let t=Math.floor(e/60),a=Math.floor(e%60);return`${t}:${a.toString().padStart(2,"0")}`},iN=({isOpen:e,onClose:t,activePanel:a,onSelectPanel:n,projectId:s,addVoiceover:o})=>{let l=nW(e),d=(0,i.useRef)(null),{isResizing:c,onResizeHandleMouseDown:u}=nU(d),[m,h]=(0,i.useState)([]),[f,g]=(0,i.useState)([]),[b,y]=(0,i.useState)(!1),[w,S]=(0,i.useState)(null),[j,I]=(0,i.useState)(null),[N,C]=(0,i.useState)(""),M=(0,i.useRef)(null),[_,A]=(0,i.useState)(null),[E,T]=(0,i.useState)(null),[$,P]=(0,i.useState)(!1),[D,R]=(0,i.useState)(null),[z,L]=(0,i.useState)(null),[F,O]=(0,i.useState)(null),[B,W]=(0,i.useState)(null),[U,q]=(0,i.useState)(!1),[Y,G]=(0,i.useState)(!1),[X,J]=(0,i.useState)(""),[Z,Q]=(0,i.useState)(60),[ee,et]=(0,i.useState)(!1),[ea,er]=(0,i.useState)(0),[en,ei]=(0,i.useState)(null),[es,eo]=(0,i.useState)([]),el=Math.ceil(60),ed=(0,i.useRef)(new Map),ec=(0,i.useRef)(null);(0,i.useEffect)(()=>{ec.current?.scrollTo({top:0})},[j,N]),(0,i.useEffect)(()=>{if(!e)return;let t=!1;return y(!0),S(null),iv.Q.listTracks({mood:j??void 0,q:N.trim()||void 0}).then(e=>{!t&&(h(e.tracks),e.moods.length>0&&g(e.moods))}).catch(e=>{t||(console.error("[MusicPanel] Failed to load catalog:",e),S(e instanceof Error?e.message:"Failed to load music catalog"))}).finally(()=>{t||y(!1)}),()=>{t=!0}},[e,j,N]),(0,i.useEffect)(()=>{if(!e)return;let t=!1;return iv.Q.listGenerated().then(e=>{t||eo(e.tracks)}).catch(e=>{console.warn("[MusicPanel] Failed to load generated tracks:",e)}),()=>{t=!0}},[e]),(0,i.useEffect)(()=>{!e&&M.current&&(M.current.pause(),A(null),T(null))},[e]),(0,i.useEffect)(()=>()=>{M.current?.pause()},[]);let eu=(0,i.useRef)(0),ep=(0,i.useCallback)(e=>{if(_===e.track_id||E===e.track_id){eu.current+=1,M.current?.pause(),A(null),T(null);return}M.current||(M.current=new Audio,M.current.crossOrigin="anonymous",M.current.preload="auto");let t=M.current,a=++eu.current;t.pause(),t.src=e.url,t.currentTime=0,t.volume=.8,t.onended=()=>{eu.current===a&&A(null)},t.onerror=()=>{eu.current===a&&(A(null),T(null))},A(null),T(e.track_id),t.play().then(()=>{eu.current===a&&(T(null),A(e.track_id))}).catch(e=>{eu.current===a&&(console.warn("[MusicPanel] Preview failed:",e),T(null),A(null))})},[_,E]),em=(0,i.useCallback)(async e=>{if(!o)return void console.warn("[MusicPanel] addVoiceover not provided - cannot add to timeline");O(e.track_id),S(null);try{let t=Date.now(),a=Math.max(1,e.duration_sec),r={id:`music-${e.track_id}-${(0,v.generateId)()}`,type:"audio",url:e.url,storageKey:e.storage_key,start:0,duration:a,trackId:3,inOffset:0,outOffset:a,volume:.35,text:`${e.title} - ${e.artist}`,status:"ready",createdAt:t,updatedAt:t};await o(r),W(e),q(!1)}catch(e){console.error("[MusicPanel] Failed to add track:",e),S(e instanceof Error?e.message:"Failed to add track to timeline")}finally{O(null)}},[o]),eh=(0,i.useCallback)(async()=>{P(!0),S(null);try{let e=await iv.Q.suggest({style:j??void 0,moods:j?[j]:void 0,seed:s||"editor",limit:1}),t=e.tracks[0];if(!t)return void S("No suggestion available - the catalog may be empty.");R(t.track_id),L(e.reason);let a=ed.current.get(t.track_id);a?.scrollIntoView({behavior:"smooth",block:"center"}),ep(t)}catch(e){console.error("[MusicPanel] AI pick failed:",e),S(e instanceof Error?e.message:"AI pick failed")}finally{P(!1)}},[j,s,ep]),ef=(0,i.useCallback)(()=>{B?.attribution_text&&navigator.clipboard.writeText(B.attribution_text).then(()=>q(!0)).catch(()=>q(!1))},[B]),eg=(0,i.useCallback)(async()=>{if(!ee){if(!s)return void ei("Open a project first - generated tracks are stored with it.");if(!X.trim())return void ei("Describe the track first (mood, genre, instruments).");et(!0),ei(null),er(0);try{let{jobId:e}=await iS({projectId:s,prompt:X,durationSeconds:Z});await ij(e,er);let t=await iv.Q.listGenerated();eo(t.tracks),J("")}catch(e){console.error("[MusicPanel] Music generation failed:",e),ei(e instanceof Error?e.message:"Music generation failed")}finally{et(!1)}}},[X,Z,ee,s]),ex=(0,i.useMemo)(()=>f.slice(0,10),[f]);if(!e)return null;let eb=(0,r.jsxs)("div",{"data-music-panel":!0,ref:d,className:"bg-slate-950/95 border border-white/[0.08] rounded-xl shadow-[0_24px_60px_-16px_rgba(0,0,0,0.85),0_0_0_1px_rgba(0,0,0,0.4)] flex flex-col overflow-hidden backdrop-blur-xl",style:l,children:[(0,r.jsx)("div",{onMouseDown:u,className:`absolute top-0 right-0 h-full w-2 cursor-ew-resize transition-colors z-10 ${c?"bg-amber-400/20":"hover:bg-amber-400/10"}`}),(0,r.jsxs)("div",{className:"flex items-center justify-between gap-1.5 px-2 py-1.5 border-b border-white/[0.06] bg-gradient-to-b from-slate-900/60 to-slate-950/40 flex-shrink-0",children:[(0,r.jsx)(K,{activePanel:a,onSelectPanel:n}),(0,r.jsx)("button",{onClick:t,className:"p-1.5 rounded-md text-slate-500 hover:text-slate-200 hover:bg-white/[0.06] transition-colors",title:"Close panel",children:(0,r.jsx)(H.A,{size:13})})]}),(0,r.jsxs)("div",{className:"px-2.5 pt-2.5 pb-1.5 space-y-2 flex-shrink-0",children:[(0,r.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,r.jsxs)("div",{className:"relative flex-1 min-w-0",children:[(0,r.jsx)(nP.A,{size:11,className:"absolute left-2 top-1/2 -translate-y-1/2 text-slate-500 pointer-events-none"}),(0,r.jsx)("input",{type:"text",value:N,onChange:e=>C(e.target.value),placeholder:"Search tracks, moods, genres...",className:"w-full pl-7 pr-2 py-1.5 bg-slate-900/70 border border-slate-700/60 rounded-md text-[11px] text-slate-200\n placeholder:text-slate-500 focus:outline-none focus:border-sky-400/40 focu
96s:ring-1 focus:ring-sky-400/20 transition-colors"})]}),(0,r.jsxs)("button",{type:"button",onClick:eh,disabled:$||b,title:"Let the AI pick a track for this project",className:`flex shrink-0 items-center gap-1 px-2 py-1.5 rounded-md border text-[10px] font-medium transition-colors ${$?"border-slate-700/60 bg-slate-900/70 text-slate-500 cursor-wait":"border-violet-500/40 bg-violet-500/10 text-violet-200 hover:bg-violet-500/20"}`,children:[$?(0,r.jsx)(x.A,{size:10,className:"animate-spin"}):(0,r.jsx)(k.A,{size:10}),"AI pick"]})]}),ex.length>0&&(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-1",children:[(0,r.jsx)("button",{type:"button",onClick:()=>I(null),className:`px-1.5 py-0.5 rounded text-[9px] font-medium transition-colors ${null===j?"bg-amber-500/20 text-amber-200 ring-1 ring-amber-500/40":"bg-slate-900/70 text-slate-400 hover:text-slate-200"}`,children:"All"}),ex.map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>I(t=>t===e?null:e),className:`px-1.5 py-0.5 rounded text-[9px] font-medium capitalize transition-colors ${j===e?"bg-amber-500/20 text-amber-200 ring-1 ring-amber-500/40":"bg-slate-900/70 text-slate-400 hover:text-slate-200"}`,children:e},e)),(0,r.jsx)("span",{className:"ml-auto pl-1 text-[9px] tabular-nums text-slate-500",children:b?"â¦":`${m.length} track${1===m.length?"":"s"}`})]}),z&&D&&(0,r.jsxs)("div",{className:"px-2 py-1 bg-violet-500/10 border border-violet-500/25 rounded text-[9px] text-violet-200/90 leading-snug",children:[(0,r.jsx)(k.A,{size:9,className:"inline mr-1 -mt-0.5"}),z]}),(0,r.jsxs)("div",{className:"rounded-md border border-slate-800/60 bg-slate-900/40",children:[(0,r.jsxs)("button",{type:"button",onClick:()=>G(e=>!e),className:"flex w-full items-center justify-between px-2 py-1.5 text-[10px] font-medium text-slate-300 hover:text-white transition-colors","data-testid":"music-generate-toggle",children:[(0,r.jsxs)("span",{className:"flex items-center gap-1",children:[(0,r.jsx)(k.A,{size:10,className:"text-amber-300"}),"Generate a custom track"]}),(0,r.jsx)("span",{className:"text-[9px] text-slate-500",children:Y?"Hide":"New"})]}),Y&&(0,r.jsxs)("div",{className:"px-2 pb-2 space-y-1.5",children:[(0,r.jsx)("input",{type:"text",value:X,onChange:e=>J(e.target.value),placeholder:"Mood & genre, e.g. dark ambient tension, slow pulse",disabled:ee,className:"w-full px-2 py-1.5 bg-slate-900/70 border border-slate-700/60 rounded-md text-[11px] text-slate-200\n placeholder:text-slate-500 focus:outline-none focus:border-amber-400/40 focus:ring-1 focus:ring-amber-400/20 transition-colors disabled:opacity-60","data-testid":"music-generate-prompt"}),(0,r.jsxs)("div",{className:"flex items-center gap-1",children:[iw.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>Q(e),disabled:ee,className:`px-1.5 py-0.5 rounded text-[9px] font-medium transition-colors ${Z===e?"bg-amber-500/20 text-amber-200 ring-1 ring-amber-500/40":"bg-slate-900/70 text-slate-400 hover:text-slate-200"}`,children:[e,"s"]},e)),(0,r.jsx)("button",{type:"button",onClick:()=>void eg(),disabled:ee,className:`ml-auto flex items-center gap-1 px-2 py-1 rounded-md border text-[10px] font-medium transition-colors ${ee?"border-slate-700/60 bg-slate-900/70 text-slate-500 cursor-wait":"border-amber-500/40 bg-amber-500/10 text-amber-200 hover:bg-amber-500/20"}`,"data-testid":"music-generate-submit",children:ee?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(x.A,{size:10,className:"animate-spin"}),ea>0?`${ea}%`:"Generatingâ¦"]}):(0,r.jsxs)(r.Fragment,{children:["Generate \xb7 ",el," cr"]})})]}),(0,r.jsxs)("p",{className:"text-[8px] leading-snug text-slate-500",children:["~30-90s instrumental via Stable Audio 2.5. Costs ",el," credits; failed generations are refunded automatically. Commercial use OK."]}),en&&(0,r.jsx)("p",{className:"px-1.5 py-1 bg-rose-900/40 border border-rose-800/50 rounded text-[9px] text-rose-200",children:en})]})]})]}),(0,r.jsxs)("div",{ref:ec,className:`flex-1 overflow-y-auto px-2.5 pb-2 space-y-1 scrollbar-hidden transition-opacity ${b&&m.length>0?"opacity-40 pointer-events-none":""}`,children:[b&&0===m.length&&(0,r.jsxs)("div",{className:"flex items-center justify-center gap-2 py-8 text-slate-500 text-[11px]",children:[(0,r.jsx)(x.A,{size:12,className:"animate-spin"}
96),"Loading catalog..."]}),!b&&0===m.length&&!w&&(0,r.jsxs)("div",{className:"flex flex-col items-center justify-center gap-2 py-8 text-center",children:[(0,r.jsx)(V.A,{size:18,className:"text-slate-600"}),(0,r.jsx)("p",{className:"text-[11px] text-slate-500",children:"No tracks match - try another mood or search."})]}),w&&(0,r.jsx)("div",{className:"px-2 py-1.5 bg-rose-900/40 border border-rose-800/50 rounded text-[10px] text-rose-200",children:w}),es.length>0&&(0,r.jsxs)("div",{className:"space-y-1","data-testid":"music-generated-section",children:[(0,r.jsx)("p",{className:"pt-1 text-[9px] font-semibold uppercase tracking-wide text-slate-500",children:"Your generated tracks"}),es.map(e=>{let t=_===e.track_id,a=E===e.track_id,n=F===e.track_id,i=B?.track_id===e.track_id;return(0,r.jsxs)("div",{className:"group flex items-center gap-2 px-2 py-1.5 rounded-md border border-amber-500/20 bg-amber-500/[0.04] hover:bg-amber-500/[0.08] transition-colors",children:[(0,r.jsx)("button",{type:"button",onClick:()=>ep(e),className:`p-1.5 rounded-md shrink-0 transition-colors ${t||a?"bg-sky-500/20 text-sky-300":"bg-slate-800/80 text-slate-300 hover:bg-slate-700 hover:text-white"}`,title:a?"Loadingâ¦":t?"Stop preview":"Preview",children:a?(0,r.jsx)(x.A,{size:11,className:"animate-spin"}):t?(0,r.jsx)(n7.A,{size:11}):(0,r.jsx)(ie.A,{size:11})}),(0,r.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,r.jsxs)("div",{className:"flex items-center gap-1",children:[(0,r.jsx)(k.A,{size:9,className:"text-amber-300 shrink-0"}),(0,r.jsx)("span",{className:"text-[11px] text-slate-200 font-medium truncate",children:e.title})]}),(0,r.jsxs)("div",{className:"flex items-center gap-1.5 text-[9px] text-slate-500",children:[(0,r.jsx)("span",{children:iI(e.duration_sec)}),(0,r.jsx)("span",{children:"\xb7"}),(0,r.jsx)("span",{className:"truncate text-emerald-400/80",children:"Yours - commercial OK"})]})]}),(0,r.jsxs)("button",{type:"button",onClick:()=>em(e),disabled:n||!o,className:`flex items-center gap-1 px-2 py-1 rounded-md border text-[10px] font-medium shrink-0 transition-colors ${i?"border-emerald-500/40 bg-emerald-500/10 text-emerald-300":n?"border-slate-700/60 bg-slate-900/70 text-slate-500 cursor-wait":"border-slate-700/60 bg-slate-900/70 text-slate-300 hover:border-sky-400/40 hover:text-sky-200 opacity-0 group-hover:opacity-100 focus:opacity-100"}`,style:i?{opacity:1}:void 0,title:"Add to timeline as music bed",children:[n?(0,r.jsx)(x.A,{size:10,className:"animate-spin"}):i?(0,r.jsx)(n$.A,{size:10}):(0,r.jsx)(a0.A,{size:10}),i?"Added":"Add"]})]},e.track_id)}),(0,r.jsx)("p",{className:"pt-0.5 text-[9px] font-semibold uppercase tracking-wide text-slate-500",children:"Library"})]}),m.map(e=>{let t,a=_===e.track_id,n=E===e.track_id,i=D===e.track_id,s=F===e.track_id,l=B?.track_id===e.track_id;return(0,r.jsxs)("div",{ref:t=>{t?ed.current.set(e.track_id,t):ed.current.delete(e.track_id)},className:`group flex items-center gap-2 px-2 py-1.5 rounded-md border transition-colors ${i?"border-violet-500/40 bg-violet-500/10":"border-slate-800/60 bg-slate-900/50 hover:bg-slate-900/90"}`,children:[(0,r.jsx)("button",{type:"button",onClick:()=>ep(e),className:`p-1.5 rounded-md shrink-0 transition-colors ${a||n?"bg-sky-500/20 text-sky-300":"bg-slate-800/80 text-slate-300 hover:bg-slate-700 hover:text-white"}`,title:n?"Loading⦠(click to cancel)":a?"Stop preview":"Preview",children:n?(0,r.jsx)(x.A,{size:11,className:"animate-spin"}):a?(0,r.jsx)(n7.A,{size:11}):(0,r.jsx)(ie.A,{size:11})}),(0,r.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,r.jsxs)("div",{className:"flex items-center gap-1",children:[(0,r.jsx)("span",{className:"text-[11px] text-slate-200 font-medium truncate",children:e.title}),i&&(0,r.jsx)(k.A,{size:9,className:"text-violet-300 shrink-0"})]}),(0,r.jsxs)("div",{className:"flex items-center gap-1.5 text-[9px] text-slate-500",children:[(0,r.jsx)("span",{className:"truncate",children:e.artist}),(0,r.jsx)("span",{children:"\xb7"}),(0,r.jsx)("span",{children:iI(e.duration_sec)}),(0,r.jsx)("span",{children:"\xb7"}),(0,r.jsx)("span",{className:"truncate text-emerald-400/80",children:(t=(e.license||"").toUpperCase()).startsWith("
96CC0")||t.startsWith("PUBLIC")?"Free":"Free \xb7 needs attribution"})]})]}),(0,r.jsxs)("button",{type:"button",onClick:()=>em(e),disabled:s||!o,className:`flex items-center gap-1 px-2 py-1 rounded-md border text-[10px] font-medium shrink-0 transition-colors ${l?"border-emerald-500/40 bg-emerald-500/10 text-emerald-300":s?"border-slate-700/60 bg-slate-900/70 text-slate-500 cursor-wait":"border-slate-700/60 bg-slate-900/70 text-slate-300 hover:border-sky-400/40 hover:text-sky-200 opacity-0 group-hover:opacity-100 focus:opacity-100"}`,style:l?{opacity:1}:void 0,title:"Add to timeline as music bed",children:[s?(0,r.jsx)(x.A,{size:10,className:"animate-spin"}):l?(0,r.jsx)(n$.A,{size:10}):(0,r.jsx)(a0.A,{size:10}),l?"Added":"Add"]})]},e.track_id)})]}),(0,r.jsx)("div",{className:"px-2.5 py-2 border-t border-slate-800/70 bg-slate-950/70 flex-shrink-0",children:B?B.attribution_text?(0,r.jsxs)("div",{className:"space-y-1",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,r.jsx)("span",{className:"text-[9px] font-semibold text-amber-200/90 uppercase tracking-wide",children:"Credit required (CC-BY)"}),(0,r.jsxs)("button",{type:"button",onClick:ef,className:"flex items-center gap-1 px-1.5 py-0.5 rounded border border-slate-700/60 text-[9px] text-slate-300 hover:text-white hover:border-slate-500 transition-colors",children:[U?(0,r.jsx)(n$.A,{size:9}):(0,r.jsx)(ib.A,{size:9}),U?"Copied":"Copy credit"]})]}),(0,r.jsx)("p",{className:"text-[9px] text-slate-400 leading-snug whitespace-pre-line",children:B.attribution_text}),(0,r.jsx)("p",{className:"text-[8px] text-slate-600",children:"Paste this into your video description when you publish."})]}):(0,r.jsxs)("div",{className:"flex items-center gap-1.5 text-[9px] text-emerald-300/90",children:[(0,r.jsx)(iy.A,{size:10}),B.title," added - no attribution required."]}):(0,r.jsx)("p",{className:"text-[9px] text-slate-500",children:"All tracks are free for commercial use. CC-BY tracks show a copyable credit line here after you add them."})})]});return"u"<typeof document?eb:(0,p.createPortal)(eb,document.body)};var iC=a(56395),iM=a(78912),i_=a(18613);let iA={"whoosh-transition":"Whooshes","riser-hook":"Risers & Hooks","impact-boom":"Impacts & Booms","pop-click-ui":"Pops & Clicks","notification-game":"Dings & Rewards","glitch-digital":"Glitch & Digital","cinematic-tension":"Tension","human-crowd":"Crowd & Human","nature-ambience":"Ambience","comedy-meme":"Comedy"},iE=e=>iA[e]??e.replace(/-/g," ").replace(/\b\w/g,e=>e.toUpperCase()),iT=({isOpen:e,onClose:t,activePanel:a,onSelectPanel:n,projectId:s,addVoiceover:o,resolveTrackId:l})=>{let d=nW(e),c=(0,i.useRef)(null),{isResizing:u,onResizeHandleMouseDown:m}=nU(c),[h,f]=(0,i.useState)([]),[g,b]=(0,i.useState)([]),[w,k]=(0,i.useState)(!1),[S,j]=(0,i.useState)(null),[I,N]=(0,i.useState)(null),[C,M]=(0,i.useState)(""),_=(0,i.useRef)(null),[A,E]=(0,i.useState)(null),[T,$]=(0,i.useState)(null),[P,D]=(0,i.useState)(null),[R,z]=(0,i.useState)(null),L=(0,i.useRef)(null);(0,i.useEffect)(()=>{L.current?.scrollTo({top:0})},[I,C]),(0,i.useEffect)(()=>{if(!e)return;let t=!1;return k(!0),j(null),i_.a.listEffects({category:I??void 0,q:C.trim()||void 0}).then(e=>{!t&&(f(e.effects),e.categories.length>0&&b(e.categories))}).catch(e=>{t||(console.error("[SfxPanel] Failed to load catalog:",e),j(e instanceof Error?e.message:"Failed to load sound effects"))}).finally(()=>{t||k(!1)}),()=>{t=!0}},[e,I,C]),(0,i.useEffect)(()=>{!e&&_.current&&(_.current.pause(),E(null),$(null))},[e]),(0,i.useEffect)(()=>()=>{_.current?.pause()},[]);let F=(0,i.useRef)(0),O=(0,i.useCallback)(e=>{if(A===e.sfx_id||T===e.sfx_id){F.current+=1,_.current?.pause(),E(null),$(null);return}_.current||(_.current=new Audio,_.current.crossOrigin="anonymous",_.current.preload="auto");let t=_.current,a=++F.current;t.pause(),t.src=e.url,t.currentTime=0,t.volume=.85,t.onended=()=>{F.current===a&&E(null)},t.onerror=()=>{F.current===a&&(E(null),$(null))},E(null),$(e.sfx_id),t.play().then(()=>{F.current===a&&($(null),E(e.sfx_id))}).catch(e=>{F.current===a&&(console.warn("[SfxPanel] Preview failed:",e),$(null),E(null))})},[A,T]),B=(0,i.useCallback)(async e=>{if(!o)return void console.warn("[SfxPanel] addVoiceover not provided - cannot add to timeline");D(e.sfx_id),j(null);try{let t=Date.now(),a=Math.max(.2,e.duration_sec),r=y.zC.getState().projectTime??0,n=Math.max(0,Math.round(1e3*r)/1e3),i=l?l(n,a):4,s={id:`sfx-${e.sfx_id}-${(0,v.generateId)()}`,type:"audio",url:e.url,storageKey:e.storage_key,start:n,duration:a,trackId:i,inOffset:0,outOffset:a,volume:e.default_volume,text:e.name,status:"ready",createdAt:t,updatedAt:t};await o(s),z(e)}catch(e){console.error("[SfxPanel] Failed to add effect:",e),j(e instanceof Error?e.message:"Failed to add sound effect")}finally{D(null)}},[o,l]),W=(0,i.useMemo)(()=>g.slice(0,10),[g]);if(!e)return null;let U=(0,r.jsxs)("div",{"data-sfx-panel":!0,ref:c,className:"bg-slate-950/95 border border-white/[0.08] rounded-xl shadow-[0_24px_60px_-16px_rgba(0,0,0,0.85),0_0_0_1px_rgba(0,0,0,0.4)] flex flex-col overflow-hidden backdrop-blur-xl",style:d,children:[(0,r.jsx)("div",{onMouseDown:m,className:`absolute top-0 right-0 h-full w-2 cursor-ew-resize transition-colors z-10 ${u?"bg-amber-400/20":"hover:bg-amber-400/10"}`}),(0,r.jsxs)("div",{className:"flex items-center justify-between gap-1.5 px-2 py-1.5 border-b border-white/[0.06] bg-gradient-to-b from-slate-900/60 to-slate-950/40 flex-shrink-0",children:[(0,r.jsx)(K,{activePanel:a,onSelectPanel:n}),(0,r.jsx)("button",{onClick:t,className:"p-1.5 rounded-md text-slate-500 hover:text-slate-200 hover:bg-white/[0.06] transition-colors",title:"Close panel",children:(0,r.jsx)(H.A,{size:13})})]}),(0,r.jsxs)("div",{className:"px-2.5 pt-2.5 pb-1.5 space-y-2 flex-shrink-0",children:[(0,r.jsxs)("div",{className:"relative",children:[(0,r.jsx)(nP.A,{size:11,className:"absolute left-2 top-1/2 -translate-y-1/2 text-slate-500 pointer-events-none"}),(0,r.jsx)("input",{type:"text",value:C,onChange:e=>M(e.target.value),placeholder:"Search whoosh, boom, riser, ding...",className:"w-full pl-7 pr-2 py-1.5 bg-slate-900/70 border border-slate-700/60 rounded-md text-[11px] text-slate-200\n placeholder:text-slate-500 focus:outline-none focus:border-sky-400/40 focu
96s:ring-1 focus:ring-sky-400/20 transition-colors","data-testid":"sfx-search-input"})]}),W.length>0&&(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-1",children:[(0,r.jsx)("button",{type:"button",onClick:()=>N(null),className:`px-1.5 py-0.5 rounded text-[9px] font-medium transition-colors ${null===I?"bg-amber-500/20 text-amber-200 ring-1 ring-amber-500/40":"bg-slate-900/70 text-slate-400 hover:text-slate-200"}`,children:"All"}),W.map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>N(t=>t===e?null:e),className:`px-1.5 py-0.5 rounded text-[9px] font-medium transition-colors ${I===e?"bg-amber-500/20 text-amber-200 ring-1 ring-amber-500/40":"bg-slate-900/70 text-slate-400 hover:text-slate-200"}`,children:iE(e)},e)),(0,r.jsx)("span",{className:"ml-auto pl-1 text-[9px] tabular-nums text-slate-500",children:w?"â¦":`${h.length} effect${1===h.length?"":"s"}`})]})]}),(0,r.jsxs)("div",{ref:L,className:`flex-1 overflow-y-auto px-2.5 pb-2 space-y-1 scrollbar-hidden transition-opacity ${w&&h.length>0?"opacity-40 pointer-events-none":""}`,children:[w&&0===h.length&&(0,r.jsxs)("div",{className:"flex items-center justify-center gap-2 py-8 text-slate-500 text-[11px]",children:[(0,r.jsx)(x.A,{size:12,className:"animate-spin"}),"Loading sound effects..."]}),!w&&0===h.length&&!S&&(0,r.jsxs)("div",{className:"flex flex-col items-center justify-center gap-2 py-8 text-center",children:[(0,r.jsx)(iC.A,{size:18,className:"text-slate-600"}),(0,r.jsx)("p",{className:"text-[11px] text-slate-500",children:"No effects match - try another category or search."})]}),S&&(0,r.jsx)("div",{className:"px-2 py-1.5 bg-rose-900/40 border border-rose-800/50 rounded text-[10px] text-rose-200",children:S}),h.map(e=>{let t,a=A===e.sfx_id,n=T===e.sfx_id,i=P===e.sfx_id,s=R?.sfx_id===e.sfx_id;return(0,r.jsxs)("div",{className:"group flex items-center gap-2 px-2 py-1.5 rounded-md border border-slate-800/60 bg-slate-900/50 hover:bg-slate-900/90 transition-colors","data-testid":"sfx-effect-row",children:[(0,r.jsx)("button",{type:"button",onClick:()=>O(e),className:`p-1.5 rounded-md shrink-0 transition-colors ${a||n?"bg-sky-500/20 text-sky-300":"bg-slate-800/80 text-slate-300 hover:bg-slate-700 hover:text-white"}`,title:n?"Loadingâ¦":a?"Stop preview":"Preview",children:n?(0,r.jsx)(x.A,{size:11,className:"animate-spin"}):a?(0,r.jsx)(n7.A,{size:11}):(0,r.jsx)(ie.A,{size:11})}),(0,r.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,r.jsxs)("div",{className:"flex items-center gap-1",children:[(0,r.jsx)("span",{className:"text-[11px] text-slate-200 font-medium truncate",children:e.name}),e.loopable&&(0,r.jsx)(iM.A,{size:8,className:"text-slate-500 shrink-0","aria-label":"Loopable"})]}),(0,r.jsxs)("div",{className:"flex items-center gap-1.5 text-[9px] text-slate-500",children:[(0,r.jsx)("span",{className:"truncate",children:iE(e.category)}),(0,r.jsx)("span",{children:"\xb7"}),(0,r.jsx)("span",{className:"tabular-nums",children:(t=e.duration_sec)>=10?`${Math.round(t)}s`:`${t.toFixed(1)}s`})]})]}),(0,r.jsxs)("button",{type:"button",onClick:()=>B(e),disabled:i||!o,className:`flex items-center gap-1 px-2 py-1 rounded-md border text-[10px] font-medium shrink-0 transition-colors ${s?"border-emerald-500/40 bg-emerald-500/10 text-emerald-300":i?"border-slate-700/60 bg-slate-900/70 text-slate-500 cursor-wait":"border-slate-700/60 bg-slate-900/70 text-slate-300 hover:border-sky-400/40 hover:text-sky-200 opacity-0 group-hover:opacity-100 focus:opacity-100"}`,style:s?{opacity:1}:void 0,title:"Add to timeline at the playhead",children:[i?(0,r.jsx)(x.A,{size:10,className:"animate-spin"}):s?(0,r.jsx)(n$.A,{size:10}):(0,r.jsx)(a0.A,{size:10}),s?"Added":"Add"]})]},e.sfx_id)})]}),(0,r.jsx)("div",{className:"px-2.5 py-2 border-t border-slate-800/70 bg-slate-950/70 flex-shrink-0",children:R?(0,r.jsxs)("p",{className:"text-[9px] text-emerald-300/90",children:[R.name," added at the playhead - drag it anywhere, trim it, or adjust its volume like any audio block."]}):(0,r.jsx)("p",{className:"text-[9px] text-slate-500",children:'Effects drop at the playhead and mix under your voiceover. All are commercial-use, no credit needed. Tip: the AI editor can place these too - try "add a whoosh at every scene transition".'})})]});return"u"<typeof document?U:(0,p.createPortal)(U,document.body)};var i$=a(79754),iP=a(82749),iD=a(35484),iR=a(33618),iz=a(9e4),iL=a(92918),iF=a(15746);let iO=[{value:"Impact, sans-serif",label:"Impact"},{value:"Inter, sans-serif",label:"Inter"},{value:"Outfit, sans-serif",label:"Outfit"},{value:"Bebas Neue, sans-serif",label:"Bebas Neue"},{value:"Oswald, sans-serif",label:"Oswald"},{value:"Montserrat, sans-serif",label:"Montserrat"},{value:"Poppins, sans-serif",label:"Poppins"},{value:"Roboto, sans-serif",label:"Roboto"},{value:"Open Sans, sans-serif",label:"Open Sans"},{value:"Permanent Marker, cursive",label:"Permanent Marker"},{value:"Playfair Display, serif",label:"Playfair Display"},{value:"Georgia, serif",label:"Georgia"},{value:"Trebuchet MS, sans-serif",label:"Trebuchet MS"},{value:"Verdana, sans-serif",label:"Verdana"},{value:"Courier New, monospace",label:"Courier New"}],iB=["#ffffff","#e2e8f0","#cbd5e1","#94a3b8","#000000","#1e293b","#374151","#6b7280","#fef08a","#facc15","#eab308","#f59e0b","#f43f5e","#ef4444","#dc2626","#f97316","#ea580c","#22c55e","#10b981","#06b6d4","#0ea5e9","#3b82f6","#6366f1","#8b5cf6","#a855f7","#e
96c4899"],iW=[{value:"none",label:"None"},{value:"pop",label:"Pop"},{value:"bounce",label:"Bounce"},{value:"fade_up",label:"Fade Up"},{value:"karaoke_pulse",label:"Karaoke Pulse"},{value:"swoop",label:"Swoop In"},{value:"title_zoom",label:"Title Zoom (in + out)"}];iF.O6.map(e=>({value:e,label:iF.es[e].label}));let iU={textColor:"#fbbf24",outlineColor:"#000000",outlineWidth:0,backgroundColor:"#fbbf24",backgroundOpacity:.22,backgroundPadding:5,keywordEmphasisEnabled:!1,keywordColor:"#fbbf24",keywordGlow:!1};function iK(e){return e?{...e}:void 0}function iV(e){return Math.max(0,Math.min(255,Math.round(e))).toString(16).padStart(2,"0")}function iH(e){if(!e||"transparent"===e)return{backgroundColor:"#000000",backgroundOpacity:0};let t=e.match(/^#([0-9a-f]{6})([0-9a-f]{2})?$/i);if(t){let[,e,a]=t;return{backgroundColor:`#${e}`,backgroundOpacity:a?parseInt(a,16)/255:1}}let a=e.match(/^rgba?\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)(?:\s*,\s*([0-9.]+))?\s*\)$/i);if(a){let[,e,t,r,n]=a;return{backgroundColor:`#${iV(Number(e))}${iV(Number(t))}${iV(Number(r))}`,backgroundOpacity:null==n?1:Math.max(0,Math.min(1,Number(n)))}}return{backgroundColor:"#000000",backgroundOpacity:0}}function iq(e){return{fontSize:e.fontSize,fontFamily:e.fontFamily,fontWeight:e.fontWeight,color:e.textColor,backgroundColor:`${e.backgroundColor}${Math.round(255*e.backgroundOpacity).toString(16).padStart(2,"0")}`,textAlign:e.textAlign,outlineColor:e.outlineColor,outlineWidth:e.outlineWidth,animationPreset:e.animationPreset}}function iY(e){let t=iH(e.backgroundColor);return{fontSize:e.fontSize,fontFamily:e.fontFamily,fontWeight:e.fontWeight,textAlign:e.textAlign,backgroundColor:t.backgroundColor,backgroundOpacity:t.backgroundOpacity,textColor:e.color,outlineColor:e.outlineColor,outlineWidth:e.outlineWidth,animationPreset:e.animationPreset}}function iG(e=iF.nG){return iY(iF.es[e]?.style||iF.zl)}function iX(e){return{color:e.textColor,outlineColor:e.outlineColor,outlineWidth:e.outlineWidth,backgroundColor:e.backgroundColor,backgroundOpacity:e.backgroundOpacity,backgroundPadding:e.backgroundPadding,keywordEmphasisEnabled:e.keywordEmphasisEnabled,keywordColor:e.keywordColor,keywordGlow:e.keywordGlow}}function iJ(e,t){return e.fontSize===t.fontSize&&e.fontFamily===t.fontFamily&&e.fontWeight===t.fontWeight&&e.textAlign===t.textAlign&&e.backgroundColor===t.backgroundColor&&e.backgroundOpacity===t.backgroundOpacity&&e.textColor===t.textColor&&e.animationPreset===t.animationPreset}var iZ=a(91842),iQ=a(12497),i0=a(83421);function i1(e){return e.audio?.extracted?.storage_key?e.audio.extracted.storage_key:e.audio?.extracted?.storageKey?e.audio.extracted.storageKey:e.audio?.extracted?.r2_key?e.audio.extracted.r2_key:e.audio?.extracted_video_audio?.storage_key?e.audio.extracted_video_audio.storage_key:e.audio?.extracted_video_audio?.storageKey?e.audio.extracted_video_audio.storageKey:e.media?.storage_key?e.media.storage_key:e.media?.storageKey?e.media.storageKey:e.audio?.storageKey?e.audio.storageKey:e.audio?.storage_key?e.audio.storage_key:null}function i5(e){return e.success&&e.data?.success!==!1}function i2(e){return e.data?.success===!1&&e.data.message?e.data.message:e.error?.message||"Failed to queue transcription"}let i4=[{label:"Faces",emojis:["\uD83D\uDE00","\uD83D\uDE01","\uD83D\uDE02","\uD83E\uDD23","\uD83D\uDE0A","\uD83D\uDE0D","\uD83E\uDD70","\uD83D\uDE18","\uD83D\uDE0E","\uD83E\uDD73","\uD83E\uDD14","\uD83E\uDD2F","\uD83D\uDE2D","\uD83D\uDE21","\uD83D\uDE34","\uD83D\uDE33","\uD83E\uDD7A","\uD83D\uDC40"]},{label:"Hands",emojis:["\uD83D\uDC4D","\uD83D\uDC4E","\uD83D\uDC4F","\uD83D\uDE4C","\uD83D\uDE4F","\uD83D\uDCAA","\uD83E\uDD1D","âï¸","\uD83E\uDD1F","\uD83D\uDC4C","\uD83D\uDD25","â¨"]},{label:"Hearts",emojis:["â¤ï¸","\uD83E\uDE77","\uD83E\uDDE1","\uD83D\uDC9B","\uD83D\uDC9A","\uD83E\uDE75","\uD83D\uDC99","\uD83D\uDC9C","\uD83E\uDD0D","\uD83D\uDDA4","\uD83D\uDC94","\uD83D\uDC95"]},{label:"Symbols",emojis:["â
","â","â ï¸","â","\uD83C\uDF1F","\uD83D\uDCAF","\uD83C\uDFAF","\uD83D\uDEA8","â","â","\uD83D\uDCA5","\uD83C\uDF89"]},{label:"Objects",emojis:["\uD83C\uDFB5","\uD83C\uDFA4","\uD83C\uDFAC","\uD83D\uDCF1","\uD83D\uDCBB","\uD83D\uDCF7","\uD83C\uDFAE","\uD83E\uDDE0","\uD83D\uDCA1","\uD83D\uDED2","\uD83C\uDF7F","â"]}
96];function i3({onBeforeOpen:e,onEmojiSelect:t}){let a=(0,i.useRef)(null),n=(0,i.useRef)(null),[s,o]=(0,i.useState)(!1),[l,d]=(0,i.useState)(""),c=(0,i.useMemo)(()=>{let e;return(e=l.trim().toLowerCase())?i4.map(t=>({...t,emojis:t.emojis.filter(a=>`${t.label} ${a}`.toLowerCase().includes(e))})).filter(e=>e.emojis.length>0):[...i4]},[l]),u=(0,i.useCallback)(()=>{o(!1),d("")},[]);return(0,i.useEffect)(()=>{if(!s)return;let e=e=>{let t=e.target;n.current?.contains(t)||a.current?.contains(t)||u()};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[s,u]),(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{ref:a,type:"button",onMouseDown:e=>e.preventDefault(),onClick:()=>{s?u():(e(),o(!0))},className:"absolute top-1.5 right-1.5 flex h-5 w-5 items-center justify-center rounded-md border border-white/[0.08] bg-[#0a0e1a]/90 text-[11px] transition-all duration-150 hover:border-amber-500/30 hover:text-amber-200",title:"Open emoji picker",children:"\uD83D\uDE42"}),s&&(0,r.jsxs)("div",{ref:n,className:"absolute right-0 top-full z-30 mt-2 w-[320px] overflow-hidden rounded-xl border border-white/[0.08] bg-[#0a0e1a] shadow-[0_12px_32px_rgba(0,0,0,0.55)]",children:[(0,r.jsx)("div",{className:"border-b border-white/[0.06] p-2",children:(0,r.jsx)("input",{type:"text",value:l,onChange:e=>d(e.target.value),placeholder:"Search emojis...",className:"w-full rounded-lg border border-white/[0.06] bg-white/[0.03] px-2.5 py-1.5 text-xs text-white/85 placeholder:text-white/25 focus:outline-none focus:border-amber-500/25"})}),(0,r.jsx)("div",{className:"max-h-[320px] overflow-y-auto p-2 scrollbar-hidden",children:c.length>0?(0,r.jsx)("div",{className:"space-y-3",children:c.map(e=>(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:"mb-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-white/30",children:e.label}),(0,r.jsx)("div",{className:"grid grid-cols-6 gap-1",children:e.emojis.map(a=>(0,r.jsx)("button",{type:"button",onMouseDown:e=>e.preventDefault(),onClick:()=>{t(a),u()},className:"flex h-10 items-center justify-center rounded-lg border border-transparent bg-white/[0.03] text-xl transition-all duration-150 hover:border-amber-500/25 hover:bg-white/[0.06]",title:`${e.label} ${a}`,children:a},`${e.label}-${a}`))})]},e.label))}):(0,r.jsx)("div",{className:"py-6 text-center text-xs text-white/25",children:"No emojis found."})})]})]})}var i8=a(31935),i6=a(32827),i9=a(68588);function i7({style:e,highlightStyle:t,highlightEnabled:a,captionDisplayMode:n,captionDisplayWindowSize:s,selectionCount:o,applyScope:l,applyTargetsCount:d,panelRef:c,toggleHighlightEnabled:u,updateSelectedCaptionStyle:p,updateSelectedHighlightStyle:m,updateCaptionDisplayMode:h,updateCaptionDisplayWindowSize:f,setApplyScope:g,applyToScope:x}){let b,y,v,w,k,[S,j]=(0,i.useState)("main"),[I,N]=(0,i.useState)("fill"),[C,M]=(0,i.useState)(!1),_=(0,i.useRef)(null),[A,E]=(0,i.useState)(!1),[T,$]=(0,i.useState)(!0),P=(0,i.useRef)(null),D="highlight"===S?{textColor:t.textColor,outlineColor:t.outlineColor,outlineWidth:t.outlineWidth}:{textColor:e.textColor,outlineColor:e.outlineColor,outlineWidth:e.outlineWidth},R=(0,i.useCallback)(e=>{"highlight"===S?m(e):p(e)},[S,p,m]);return(0,i.useEffect)(()=>{if(!C)return;let e=e=>{_.current&&!_.current.contains(e.target)&&M(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[C]),(0,i.useEffect)(()=>{if(!A)return;let e=e=>{P.current&&!P.current.contains(e.target)&&E(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[A]),(0,r.jsxs)("div",{className:"rounded-xl border border-white/[0.05] bg-white/[0.02] p-2.5 space-y-2.5",children:[(0,r.jsx)("span",{className:"text-[9px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Fine-tune"}),(0,r.jsxs)("div",{className:"flex items-center gap-1 rounded-md bg-white/[0.02] border border-white/[0.04] p-0.5",children:[(0,r.jsx)("button",{onClick:()=>j("main"),className:`flex-1 px-2 py-1 rounded-[5px] text-[10px] font-medium transition-colors duration-150 ${"main"===S?"bg-white/[0.07] text-white/90":"text-white/40 hover:text-white/65"}`,children:"Main"}),(0,r.jsx)("button",{onClick:()=>j("highlight"),className:`flex-1 px-2 py-1 rounded-[5px] text-[10px] font-medium transition-colors duration-150 ${"highlight"===S?"bg-amber-500/[0.14] text-amber-200/90":"text-white/40 hover:text-white/65"}`,children:"Highlight"}),(0,r.jsx)("button",{onClick:u,className:`relative w-7 h-3.5 rounded-full transition-colors duration-200 flex-shrink-0 ml-0.5 ${a?"bg-emerald-500/80":"bg-white/[0.08]"}`,title:a?"Disable word highlighting":"Enable word highlighting",children:(0,r.jsx)("span",{className:`absolute top-0.5 left-0.5 w-2.5 h-2.5 rounded-full bg-white shadow-sm transition-transform duration-200 ${a?"translate-x-3.5":""}`})})]}),a&&(0,r.jsxs)("div",{className:"space-y-2 rounded-md border border-white/[0.04] bg-white/[0.02] p-2",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,r.jsxs)("div",{className:"min-w-0",children:[(0,r.jsx)("span",{className:"text-[10px] font-semibold text-white/75",children:"Keyword pop"}),(0,r.jsx)("p",{className:"text-[9px] leading-tight text-white/35",children:"Auto-color the important words"})]}),(0,r.jsx)("button",{onClick:()=>m({keywordEmphasisEnabled:!t.keywordEmphasisEnabled}),className:`relative ml-0.5 h-3.5 w-7 flex-shrink-0 rounded-full transition-colors duration-200 ${t.keywordEmphasisEnabled?"bg-emerald-500/80":"bg-white/[0.08]"}`,title:t.keywordEmphasisEnabled?"Disable keyword emphasis":"Enable keyword emphasis",children:(0,r.jsx)("span",{className:`absolute left-0.5 top-0.5 h-2.5 w-2.5 rounded-full bg-white shadow-sm transition-transform duration-200 ${t.keywordEmphasisEnabled?"translate-x-3.5":""}`})})]}),t.keywordEmphasisEnabled&&(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,r.jsxs)("label",{className:"flex items-center gap-1.5",children:[(0,r.jsx)("span",{className:"text-[9px] font-medium uppercase tracking-[0.1em] text-white/30",children:"Color"}),(0,r.jsx)("input",{type:"color",value:t.keywordColor,onChange:e=>m({keywordColor:e.target.value}),className:"h-5 w-7 cursor-pointer rounded border border-white/[0.08] bg-transparent p-0",title:"Keyword color"})]}),(0,r.jsxs)("button",{onClick:()=>m({keywordGlow:!t.keywordGlow}),className:`rounded px-2 py-1 text-[10px] font-medium transition-colors ${t.keywordGlow?"bg-emerald-500/15 text-emerald-200":"bg-white/[0.04] text-white/45 hover:text-white/70"}`,title:"Toggle a soft glow behind emphasized words",children:["Glow ",t.keywordGlow?"on":"off"]})]})]}),(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{className:"mb-1.5 flex items-center justify-between gap-2",children:[(0,r.jsx)("span",{className:"text-[9px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Display"}),"block"!==n&&(0,r.jsx)("select",{value:s,onChange:e=>f(Number(e.target.value)),disabled:0===o,className:"h-5 rounded border border-white/[0.06] bg-white/[0.03] px-1.5 text-[10px] text-white/65 focus:outline-none focus:border-white/[0.12] disabled:opacity-40",children:[1,2,3].map(e=>(0,r.jsx)("option",{value:e,children:"line"===n?`${e} line${1===e?"":"s"}`:"word"===n?`${e} word${1===e?"":"s"}`:`${e} group${1===e?"":"s"}`},e))})]}
96),(0,r.jsx)("div",{className:"grid grid-cols-5 gap-0.5 rounded-md bg-white/[0.02] p-0.5 border border-white/[0.04]",children:[{value:"block",label:"Block"},{value:"phrase",label:"Phrase"},{value:"shorts",label:"Shorts"},{value:"line",label:"Line"},{value:"word",label:"Word"}].map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>h(e.value),disabled:0===o,className:`rounded px-1.5 py-1 text-[10px] font-medium transition-colors duration-150 disabled:cursor-not-allowed disabled:opacity-40 ${n===e.value?"bg-white/[0.08] text-white/85":"text-white/35 hover:text-white/65"}`,children:e.label},e.value))})]}),(y=[{id:"fill",label:(b="main"===S?{color:e.backgroundColor,setColor:e=>p({backgroundColor:e}),opacity:e.backgroundOpacity,setOpacity:e=>p({backgroundOpacity:e}),label:"Background"}:{color:t.backgroundColor,setColor:e=>m({backgroundColor:e}),opacity:t.backgroundOpacity,setOpacity:e=>m({backgroundOpacity:e}),padding:t.backgroundPadding,setPadding:e=>m({backgroundPadding:e}),label:"Word BG"}).label},{id:"text",label:"Text"},{id:"outline",label:"Outline"}],v="fill"===I?b.color:"text"===I?D.textColor:D.outlineColor,w=e=>{"fill"===I?b.setColor(e):"text"===I?R({textColor:e}):R({outlineColor:e})},k="flex-1 h-1 rounded-full appearance-none cursor-pointer bg-white/[0.06] [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-2.5 [&::-webkit-slider-thumb]:h-2.5 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-white/90 [&::-webkit-slider-thumb]:transition-transform [&::-webkit-slider-thumb]:hover:scale-110 [&::-moz-range-thumb]:appearance-none [&::-moz-range-thumb]:w-2.5 [&::-moz-range-thumb]:h-2.5 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-white/90 [&::-moz-range-thumb]:border-0",(0,r.jsxs)("div",{className:"space-y-2.5",children:["main"===S&&(0,r.jsxs)("label",{className:"flex flex-col gap-1 min-w-0",children:[(0,r.jsx)("span",{className:"text-[9px] uppercase tracking-[0.1em] text-white/30 font-medium",children:"Motion"}),(0,r.jsx)("select",{value:e.animationPreset,onChange:e=>p({animationPreset:e.target.value}),className:"w-full rounded-md border border-white/[0.06] bg-white/[0.03] px-2 py-1.5 text-[11px] text-white/80 focus:outline-none focus:border-white/[0.12]",children:iW.map(e=>(0,r.jsx)("option",{value:e.value,children:e.label},e.value))})]}),(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsx)("div",{className:"flex items-center gap-0.5 rounded-md bg-white/[0.02] border border-white/[0.04] p-0.5",children:y.map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>N(e.id),className:`flex-1 px-2 py-1 rounded-[5px] text-[10px] font-medium transition-colors duration-150 ${I===e.id?"bg-white/[0.07] text-white/85":"text-white/40 hover:text-white/65"}`,children:e.label},e.id))}),(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-1",children:[iB.map(e=>{let t=v.toLowerCase()===e.toLowerCase();return(0,r.jsx)("button",{type:"button",onClick:()=>w(e),className:`w-4 h-4 rounded-[3px] transition-all duration-150 ${t?"ring-1 ring-white/60 ring-offset-1 ring-offset-[#0a0e1a] scale-105":"ring-1 ring-white/[0.08] hover:ring-white/30"}`,style:{backgroundColor:e},title:e},e)}),(0,r.jsxs)("label",{className:"relative w-4 h-4 rounded-[3px] cursor-pointer flex items-center justify-center ring-1 ring-white/[0.12] hover:ring-white/30 transition-all duration-150 bg-gradient-to-br from-white/[0.04] to-white/[0.01]",title:"Custom color",children:[(0,r.jsx)("input",{type:"color",value:v,onChange:e=>w(e.target.value),className:"absolute inset-0 opacity-0 w-full h-full cursor-pointer"}),(0,r.jsx)(a0.A,{size:9,className:"text-white/45"})]})]}),"fill"===I&&(0,r.jsxs)("div",{className:"flex items-center gap-2 pt-0.5",children:[(0,r.jsx)("span",{className:"text-[9px] uppercase tracking-[0.1em] text-white/30 font-medium w-12 flex-shrink-0",children:"Opacity"}),(0,r.jsx)("input",{type:"range",min:"0",max:"1",step:"0.05",value:b.opacity,onChange:e=>b.setOpacity(parseFloat(e.target.value)),className:k}),(0,r.jsxs)("span",{className:"text-[10px] text-white/45 tabular-nums w-9 text-right flex-shrink-0",children:[Math.round(100*b.opacity),"%"]})]}),"fill"===I&&"highlight"===S&&b.setPadding&&(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:"text-[9px] uppercase tracking-[0.1em] text-white/30 font-medium w-12 flex-shrink-0",children:"Padding"}),(0,r.jsx)("input",{type:"range",min:"0",max:"12",step:"1",value:b.padding??0,onChange:e=>b.setPadding(parseInt(e.target.value,10)),className:k}),(0,r.jsx)("span",{className:"text-[10px] text-white/45 tabular-nums w-9 text-right flex-shrink-0",children:b.padding??0})]}),"outline"===I&&(0,r.jsxs)("div",{className:"flex items-center gap-2 pt-0.5",children:[(0,r.jsx)("span",{className:"text-[9px] uppercase tracking-[0.1em] text-white/30 font-medium w-12 flex-shrink-0",children:"Width"}),(0,r.jsx)("input",{type:"range",min:"0",max:"8",step:"0.5",value:D.outlineWidth,onChange:e=>R({outlineWidth:parseFloat(e.target.value)}),className:k}),(0,r.jsxs)("span",{className:"text-[10px] text-white/45 tabular-nums w-9 text-right flex-shrink-0",children:[D.outlineWidth,"px"]})]})]}),(0,r.jsxs)("div",{className:"flex gap-2 items-end",children:[(0,r.jsxs)("div",{className:"flex-1 min-w-0 relative",ref:_,children:[(0,r.jsx)("span",{className:"block mb-1 text-[9px] uppercase tracking-[0.1em] text-white/30 font-medium",children:"Font"}),(0,r.jsxs)("button",{type:"button",onClick:()=>M(e=>!e),className:"w-full flex items-center justify-between px-2 py-1.5 bg-white/[0.03] border border-white/[0.06] rounded-md text-[11px] text-white/80 hover:border-white/[0.12] transition-colors duration-150 text-left",children:[(0,r.jsx)("span",{style:{fontFamily:(0,iR.c)(e.fontFamily)},className:"truncate",children:iO.find(t=>t.value===e.fontFamily)?.label||"Select font"}
96),(0,r.jsx)(tn.A,{size:10,className:`text-white/30 transition-transform duration-150 flex-shrink-0 ml-1 ${C?"rotate-180":""}`})]}),C&&(0,r.jsx)("div",{className:"absolute z-50 top-full left-0 right-0 mt-1 max-h-96 overflow-y-auto rounded-lg bg-[#0a0e1a] border border-white/[0.08] shadow-[0_12px_36px_rgba(0,0,0,0.6)] scrollbar-hidden",children:iO.map(t=>{let a=e.fontFamily===t.value;return(0,r.jsx)("button",{type:"button",onClick:()=>{p({fontFamily:t.value}),M(!1)},className:`w-full text-left px-2.5 py-1.5 text-[12px] transition-colors duration-100 ${a?"bg-white/[0.06] text-white/90":"text-white/60 hover:bg-white/[0.04] hover:text-white/85"}`,style:{fontFamily:(0,iR.c)(t.value)},children:t.label},t.value)})})]}),(0,r.jsxs)("div",{className:"flex-shrink-0",children:[(0,r.jsx)("span",{className:"block mb-1 text-[9px] uppercase tracking-[0.1em] text-white/30 font-medium",children:"Align"}),(0,r.jsx)("div",{className:"flex bg-white/[0.02] rounded-md p-0.5 border border-white/[0.05]",children:["left","center","right"].map(t=>{let a="left"===t?i8.A:"center"===t?i6.A:i9.A;return(0,r.jsx)("button",{onClick:()=>p({textAlign:t}),className:`p-1.5 rounded-[5px] transition-colors duration-150 ${e.textAlign===t?"bg-white/[0.08] text-white/85":"text-white/30 hover:text-white/60"}`,children:(0,r.jsx)(a,{size:11})},t)})})]})]}),(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("span",{className:"text-[9px] uppercase tracking-[0.1em] text-white/30 font-medium w-12 flex-shrink-0",children:"Size"}),(0,r.jsx)("input",{type:"range",min:"12",max:"72",step:"2",value:e.fontSize,onChange:e=>p({fontSize:parseInt(e.target.value,10)}),className:k}),(0,r.jsxs)("span",{className:"text-[10px] text-white/45 tabular-nums w-9 text-right flex-shrink-0",children:[e.fontSize,"px"]})]})]})),(0,r.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,r.jsxs)("div",{className:"relative flex-1 min-w-0",ref:P,children:[(0,r.jsxs)("button",{type:"button",onClick:()=>{if(!A&&P.current&&c.current){let e=P.current.getBoundingClientRect();$(c.current.getBoundingClientRect().bottom-e.bottom<120)}E(e=>!e)},className:"flex items-center gap-1 w-full px-2.5 py-1.5 rounded-lg bg-white/[0.03] border border-white/[0.05] text-[10px] text-white/40 font-medium hover:text-white/60 hover:border-white/[0.08] transition-all duration-150",children:[(0,r.jsx)("span",{className:"truncate",children:"scene"===l?"Entire scene":"track"===l?"Entire track":"Entire project"}),(0,r.jsx)(tn.A,{size:9,className:`text-white/25 transition-transform duration-150 flex-shrink-0 ml-auto ${A?"rotate-180":""}`})]}),A&&(0,r.jsx)("div",{className:`absolute left-0 z-20 rounded-xl border border-white/[0.08] bg-[#0a0e1a] shadow-[0_8px_24px_rgba(0,0,0,0.5)] py-1 min-w-[150px] ${T?"bottom-full mb-1":"top-full mt-1"}`,children:["scene","track","project"].map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>{g(e),E(!1)},className:`w-full text-left px-3 py-1.5 text-[10px] transition-all duration-150 ${l===e?"text-amber-300/90 bg-amber-500/[0.08]":"text-white/55 hover:bg-white/[0.04]"}`,children:"scene"===e?"Entire scene":"track"===e?"Entire track":"Entire project"},e))})]}),(0,r.jsx)("button",{type:"button",onClick:x,disabled:0===d,className:`flex-shrink-0 rounded-lg px-3 py-1.5 text-[10px] font-medium transition-all duration-150 ${0===d?"bg-white/[0.03] text-white/20 cursor-not-allowed":"bg-amber-500/[0.08] text-amber-200/90 border border-amber-500/[0.15] hover:bg-amber-500/[0.14]"}`,children:"Apply"})]})]})}let se=({isOpen:e,onClose:t,activePanel:n,onSelectPanel:o,projectId:l,selectedSceneId:d,selectedSceneText:c})=>{let u,m,h,f=nW(e),g=(0,i.useRef)(null),b=(0,i.useRef)(null),v=(0,i.useRef)({start:0,end:0}),w=(0,i.useRef)(""),k=(0,i.useRef)(null),{isResizing:S,onResizeHandleMouseDown:j}=nU(g),I=[];try{let{currentProject:e}=(0,s.By)();u=e?.id,m=e?.mode,I=e?.scenes??[]}catch{u=void 0,m=void 0}let N=l||u,C="local"===m,{entitlements:_}=(0,ay.G)(),A=_.features.canUsePremiumAiFeatures;try{h=(0,M.L)().triggerCaptionReload}catch{h=void 0}let E=(0,y.zC)(e=>e.blocks),T=(0,y.zC)(e=>e.projectTime),$=(0,y.zC)(e=>e.addCaptionBlock),P=(0,y.zC)(e=>e.addCaptionBlocks),D=(0,y.zC)(e=>e.updateBlock),R=(0,y.zC)(e=>e.clearCaptionBlocksForScene),z=(0,y.zC)(e=>e.selectedAudioBlockId),L=(0,y.zC)(e=>e.selectedAudioBlockIds),F=(0,y.zC)(e=>e.setSelectedAudioBlockId),O=(0,y.zC)(e=>e.selectedSceneId),B=(0,y.zC)(e=>e.ensureCaptionTrack),W=(0,i.useMemo)(()=>E.filter(e=>"caption"===e.type).length,[E]),U=(0,i.useMemo)(()=>E.filter(e=>"caption"===e.type&&e.captionText).sort((e,t)=>
96e.start-t.start).map(e=>e.captionText).join(" "),[E]),V=(0,i.useMemo)(()=>E.filter(e=>"caption"===e.type),[E]),q=(0,i.useMemo)(()=>{let e=new Map;return E.forEach(t=>{"caption"===t.type&&t.sceneId&&e.set(t.sceneId,(e.get(t.sceneId)||0)+1)}),e},[E]),[Y,G]=(0,i.useState)(""),[X,J]=(0,i.useState)(()=>iG()),[Z,Q]=(0,i.useState)(iF.nG),[ee,et]=(0,i.useState)(iU),[ea,er]=(0,i.useState)(!1),[en,ei]=(0,i.useState)(iz._g),[es,eo]=(0,i.useState)(iz.HB),[el,ed]=(0,i.useState)(iL.K5),[ec,eu]=(0,i.useState)([]),ep=(0,i.useRef)([]),[em,eh]=(0,i.useState)(""),[ef,eg]=(0,i.useState)("free"),[ex,eb]=(0,i.useState)(!1),[ey,ev]=(0,i.useState)(null),[ew,ek]=(0,i.useState)(!1),[eS,ej]=(0,i.useState)(null),[eI,eN]=(0,i.useState)(null),eC=(0,i.useMemo)(()=>{let e=L.length>0?L:z?[z]:[];if(0===e.length)return[];let t=new Map(V.map(e=>[e.id,e]));return e.map(e=>t.get(e)).filter(e=>!!e)},[V,z,L]),eM=(0,i.useMemo)(()=>eC.map(e=>e.id),[eC]),e_=em||O||null,eA=(0,i.useMemo)(()=>eC.length>0||!e_?null:V.filter(e=>e.sceneId===e_).sort((e,t)=>e.start-t.start)[0]??null,[eC.length,e_,V]),eE=(0,i.useMemo)(()=>eC[0]||eA||null,[eC,eA]),eT=eE?.sceneId??null,e$=eE?.trackId??null,eP=(0,i.useMemo)(()=>"u">typeof Intl&&"Segmenter"in Intl?[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(Y)].length:Array.from(Y).length,[Y]),eD=(0,i.useMemo)(()=>null==e$?[]:V.filter(e=>e.trackId===e$),[V,e$]),eR=(0,i.useMemo)(()=>null==eT?[]:V.filter(e=>e.sceneId===eT),[V,eT]),[ez,eL]=(0,i.useState)("scene"),eF=(0,i.useMemo)(()=>{let e;return eE?{id:eE.id,captionText:eE.captionText||"",style:(e=iH(eE.captionStyle?.backgroundColor),{fontSize:eE.captionStyle?.fontSize||iF.zl.fontSize,fontFamily:eE.captionStyle?.fontFamily||iF.zl.fontFamily,fontWeight:eE.captionStyle?.fontWeight||500,textAlign:eE.captionStyle?.textAlign||iF.zl.textAlign,backgroundColor:e.backgroundColor,backgroundOpacity:e.backgroundOpacity,textColor:eE.captionStyle?.color||iF.zl.color,outlineColor:eE.captionStyle?.outlineColor||iF.zl.outlineColor,outlineWidth:eE.captionStyle?.outlineWidth??iF.zl.outlineWidth,animationPreset:eE.captionStyle?.animationPreset||iF.zl.animationPreset}),highlight:{textColor:eE.captionHighlightStyle?.color||"#fbbf24",outlineColor:eE.captionHighlightStyle?.outlineColor||"#000000",outlineWidth:eE.captionHighlightStyle?.outlineWidth??0,backgroundColor:eE.captionHighlightStyle?.backgroundColor||"#fbbf24",backgroundOpacity:eE.captionHighlightStyle?.backgroundOpacity??0,backgroundPadding:eE.captionHighlightStyle?.backgroundPadding??4,keywordEmphasisEnabled:eE.captionHighlightStyle?.keywordEmphasisEnabled??!1,keywordColor:eE.captionHighlightStyle?.keywordColor||eE.captionHighlightStyle?.color||"#fbbf24",keywordGlow:eE.captionHighlightStyle?.keywordGlow??!1},highlightEnabled:eE.captionHighlightEnabled??!1,displayMode:(0,iz.$S)(eE.captionDisplayMode),displayWindowSize:(0,iz.j$)(eE.captionDisplayWindowSize),punctuationMode:eE.captionPunctuationMode??iL.K5}:null},[eE]);(0,i.useEffect)(()=>{if(!eF){k.current=null;return}let e=k.current!==eF.id;k.current=eF.id;let t="u">typeof document&&document.activeElement===b.current,a=iF.O6.find(e=>iJ(iG(e),eF.style));if(a&&Q(a),e){G(eF.captionText),J(eF.style),et(eF.highlight),er(eF.highlightEnabled),ei(eF.displayMode),eo(eF.displayWindowSize),ed(eF.punctuationMode);return}t||Y===eF.captionText||G(eF.captionText),J(e=>iJ(e,eF.style)?e:eF.style),ei(eF.displayMode),eo(eF.displayWindowSize),ed(eF.punctuationMode)},[Y,eF]);let eO=(0,i.useCallback)(t=>{J(a=>{let r={...a,...t},n=iq(r),i=window.__facelessStudioTargetPlanSceneId,s=window.__facelessStudioTargetNleSceneId,o=eE?.sceneId||em||d||O||s||"";return e&&(o||i)&&window.dispatchEvent(new CustomEvent("faceless-studio:caption-settings-change",{detail:{sceneId:o,planSceneId:i,captionStyle:n,highlightEnabled:ea,displayMode:en,displayWindowSize:es}})),eM.forEach(e=>{D(e,{captionStyle:{...n}})}),r})},[en,es,ea,e,eE,eM,em,d,O,D]),eB=(0,i.useCallback)(t=>{et(a=>{let r={...a,...t},n=iX(r);eM.forEach(e=>{D(e,{captionHighlightStyle:{...n}})});let i=window.__facelessStudioTargetPlanSceneId,s=window.__facelessStudioTargetNleSceneId,o=eE?.sceneId||em||d||O||s||"";return e&&(o||i)&&window.dispatchEvent(new CustomEvent("faceless-studio:caption-settings-change",{detail:{sceneId:o,planSceneId:i,captionHighlightStyle:n,highlightEnabled:ea}})),r})},[ea,e,eE,eM,em,d,O,D]),eW=window.__facelessStudioTargetPlanSceneId,eU=window.__facelessStudioTargetNleSceneId,eK=eE?.sceneId||em||d||O||eU||"",eV=(0,i.useRef)(null),eH=(0,i.useCallback)((t={},a)=>
96{if(!e||!eK&&!eW)return;let r={sceneId:eK,planSceneId:eW,captionStyle:t.captionStyle??iq(X),highlightEnabled:t.captionHighlightEnabled??ea,captionHighlightStyle:t.captionHighlightStyle??iX(ee),displayMode:t.captionDisplayMode??en,displayWindowSize:t.captionDisplayWindowSize??es},n=null;try{n=JSON.stringify(r)}catch{n=null}a?.onlyIfChanged&&null!==n&&eV.current===n||(eV.current=n,window.dispatchEvent(new CustomEvent("faceless-studio:caption-settings-change",{detail:r})))},[en,es,ea,ee,e,eW,eK,X]);(0,i.useEffect)(()=>{!0!==window.__facelessApplyToAllScenes&&eH({},{onlyIfChanged:!0})},[eH]);let eq=(0,i.useCallback)(()=>{let e=!ea;er(e),eH({captionHighlightEnabled:e}),eC.forEach(t=>{let a={captionHighlightEnabled:e};e&&!t.captionHighlightStyle&&(a.captionHighlightStyle=iX(ee)),D(t.id,a)})},[eH,ea,eC,ee,D]),eY=(0,i.useCallback)(e=>{ei(e),eH({captionDisplayMode:e}),eC.forEach(t=>{D(t.id,{captionDisplayMode:e,captionDisplayWindowSize:es})})},[es,eH,eC,D]),eG=(0,i.useCallback)(e=>{ed(e),eC.forEach(t=>{D(t.id,{captionPunctuationMode:e})})},[eC,D]),eX=(0,i.useCallback)(e=>{let t=(0,iz.j$)(e);eo(t),eH({captionDisplayWindowSize:t}),eC.forEach(e=>{D(e.id,{captionDisplayMode:en,captionDisplayWindowSize:t})})},[en,eH,eC,D]),eJ=(0,i.useCallback)(e=>{if(Q(e.nearestTextPresetId),eO(iY(e.style)),e.highlightStyle&&eB({textColor:e.highlightStyle.color,outlineColor:e.highlightStyle.outlineColor,outlineWidth:e.highlightStyle.outlineWidth,backgroundColor:e.highlightStyle.backgroundColor,backgroundOpacity:e.highlightStyle.backgroundOpacity,backgroundPadding:e.highlightStyle.backgroundPadding,keywordEmphasisEnabled:e.highlightStyle.keywordEmphasisEnabled??!1,keywordColor:e.highlightStyle.keywordColor??e.highlightStyle.color,keywordGlow:e.highlightStyle.keywordGlow??!1}),ea!==e.highlightEnabled&&eq(),eY(e.displayMode),eX(e.displayWindowSize),e.captionBox){let t={...e.captionBox};eM.forEach(e=>{D(e,{captionBox:{...t}})})}},[ea,eM,eq,D,eY,eX,eO,eB]),eZ=(0,i.useCallback)(e=>{let t=iq(X);return(0,iZ.Pm)({name:e,style:{fontSize:X.fontSize,fontFamily:X.fontFamily,fontWeight:X.fontWeight,textAlign:X.textAlign,color:X.textColor,backgroundColor:t.backgroundColor,outlineColor:X.outlineColor,outlineWidth:X.outlineWidth,animationPreset:X.animationPreset},highlightEnabled:ea,highlightStyle:{color:ee.textColor,outlineColor:ee.outlineColor,outlineWidth:ee.outlineWidth,backgroundColor:ee.backgroundColor,backgroundOpacity:ee.backgroundOpacity,backgroundPadding:ee.backgroundPadding,keywordEmphasisEnabled:ee.keywordEmphasisEnabled,keywordColor:ee.keywordColor,keywordGlow:ee.keywordGlow},displayMode:en,displayWindowSize:es,...eE?.captionBox?{captionBox:{...eE.captionBox}}:{}})},[en,es,ea,ee,eE,X]),eQ=(0,i.useCallback)(e=>{G(e),eE&&D(eE.id,{captionText:e})},[eE,D]),e0=(0,i.useCallback)(()=>{let e=b.current;e&&(v.current={start:e.selectionStart??0,end:e.selectionEnd??e.selectionStart??0})},[]),e1=(0,i.useCallback)(e=>{let t=b.current,a=t?.selectionStart??v.current.start??Y.length,r=t?.selectionEnd??v.current.end??Y.length,n=`${Y.slice(0,a)}${e}${Y.slice(r)}`,i=a+e.length;eQ(n),window.requestAnimationFrame(()=>{let e=b.current;e&&(e.focus(),e.setSelectionRange(i,i),v.current={start:i,end:i})})},[Y,eQ]),e5=(0,i.useMemo)(()=>"scene"===ez?eR:"track"===ez?eD:V,[ez,eR,eD,V]),e2="scene"===ez?"scene":"track"===ez?"track":"project",e4=(0,i.useCallback)(()=>{if(0===e5.length)return;let e=iq(X),t=eE?.captionBox?iK(eE.captionBox):void 0;e5.forEach(a=>{let r={captionStyle:{...e}};t&&(r.captionBox=iK(t)),D(a.id,r)});let a=t?"style + position":"style";ej(`Applied ${a} to ${e5.length} block${1===e5.length?"":"s"} (${e2})`),setTimeout(()=>ej(null),3e3)},[e5,e2,X,eE,D]),e3=(0,i.useCallback)(()=>{if(!Y.trim())return;let e=E.find(e=>"scene"===e.type&&T>
96=e.start&&T<e.start+e.duration),t=e?.sceneId||"__manual__",a=B(e?.trackId??1),r=`caption-manual-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;$({id:r,sceneId:t,start:T,duration:3,inOffset:0,outOffset:0,fullDuration:3,trackId:a,captionText:Y.trim(),captionBox:{x:.06,y:.76,width:.88,height:.14},captionStyle:iq(X),captionDisplayMode:en,captionDisplayWindowSize:es,source:"manual",sourceCaptionId:r}),G(""),ej("Caption added to timeline"),setTimeout(()=>ej(null),3e3)},[en,es,Y,X,T,E,$,B]),e8=(0,i.useMemo)(()=>{var e;let t,a;return e=I,t=new Set,a=[],e.forEach(e=>{t.has(e.id)||(t.add(e.id),a.push({sceneId:e.id,sceneNumber:a.length+1,label:e.title||e.text?.slice(0,30)||`Scene ${a.length+1}`,storageKey:i1(e)}))}),a},[I,I.length]),e6=(0,i.useMemo)(()=>{let e,t;return e=E.filter(e=>"scene"===e.type&&!e.sceneId.startsWith("__track0")).sort((e,t)=>e.start-t.start),t=new Map,e.forEach(e=>{let a=e.scene?.id||e.sceneId;if(!a||t.has(a))return;let r=t.size+1,n=e.scene?.title||e.scene?.text?.slice(0,30)||`Scene ${r}`;t.set(a,{sceneId:a,sceneNumber:r,label:n,storageKey:i1(e.scene||{})})}),Array.from(t.values())},[E]),e9=e8.length>0?e8:e6,e7=(0,i.useMemo)(()=>{var e;let t;return e=e8.length>0?e8.length:e6.length,t=[],E.forEach(a=>{("voiceover"===a.type||"audio"===a.type)&&(a.audioStorageKey||a.audioUrl)&&t.push({sceneId:a.id,sceneNumber:e+t.length+1,label:a.label||("voiceover"===a.type?"Voiceover":"Audio"),storageKey:a.audioStorageKey||a.audioUrl||""})}),t},[E,e8.length,e6.length]),te=(0,i.useMemo)(()=>[...e9,...e7],[e9,e7]),tt=(0,i.useMemo)(()=>te.map(e=>`${e.sceneId}\u0000${e.storageKey}\u0000${e.label}`).join("\x01"),[te]),ta=(0,i.useMemo)(()=>te,[tt]),tr=(0,i.useMemo)(()=>{let e=new Map;return E.forEach(t=>{("voiceover"===t.type||"audio"===t.type)&&t.audioStorageKey&&t.sceneId&&!e.has(t.sceneId)&&e.set(t.sceneId,t.audioStorageKey)}),e},[E]),ti=(0,i.useMemo)(()=>{let e=new Map,t=new Map(ec.map(e=>[e.sceneId,e.storageKey]));return ta.forEach(a=>{let r=E.find(e=>"scene"===e.type&&e.sceneId===a.sceneId&&!e.sceneId.startsWith("__track0"))||null,n=I.find(e=>e.id===a.sceneId)||r?.scene||null,i=t.get(a.sceneId)||a.storageKey||r?.audioStorageKey||i1(r?.scene||{})||tr.get(a.sceneId)||null;e.set(a.sceneId,!!n?.media?.url||!!i)}),e},[E,ta,ec,I,tr]),ts=(0,i.useCallback)(e=>ti.get(e.sceneId)??!1,[ti]),to=(0,i.useMemo)(()=>{let e=I.some(e=>{let t=e.media?.url||"",a=e.media?.assetRef?.type;return"blob"===a||"handle"===a||t.startsWith("blob:")||t.startsWith("localBlob://")||t.startsWith("file:")}),t=E.some(e=>{if("scene"!==e.type||e.sceneId.startsWith("__track0"))return!1;let t=e.scene?.media,a=t?.url||"",r=t?.assetRef?.type;return"blob"===r||"handle"===r||a.startsWith("blob:")||a.startsWith("localBlob://")||a.startsWith("file:")});return e||t},[I,E]),tl=(0,i0.Ak)(N),td=C||to||!tl,tc=E.some(e=>("voiceover"===e.type||"audio"===e.type)&&(e.audioStorageKey||e.audioUrl)),tu=td||A||tc,tp=A&&!td,tm="pro"===ef&&tp?"premium":"standard",th="premium"===tm?tp:tu,tf=(0,i.useCallback)(()=>"pro"===ef&&td?"Pro Auto Transcribe is cloud-only. Local projects use browser Free Auto Transcribe.":"premium"!==tm||tp?"No transcribable audio found. Add a voiceover or audio block to enable transcription.":"Pro Auto Transcribe requires Pro access. Free Auto Transcribe is less accurate than Pro.",[ef,tm,tp,td]),tg="pro"===ef&&!td&&!A;(0,i.useEffect)(()=>{td&&"pro"===ef&&eg("free")},[ef,td]),(0,i.useEffect)(()=>{if(!e)return;let t=`captions-panel-state:${N||"default"}`;try{let e=window.localStorage.getItem(t);if(!e)return;let a=JSON.parse(e);"string"==typeof a.selectedSceneId&&a.selectedSceneId.trim().length>0&&eh(a.selectedSceneId)}catch(e){console.warn("[CaptionsPanel] Failed to restore persisted panel state:",e)}},[e,N]),(0,i.useEffect)(()=>{let e=`captions-panel-state:${N||"default"}`;try{window.localStorage.setItem(e,JSON.stringify({selectedSceneId:em||void 0}))}catch(e){console.warn("[CaptionsPanel] Failed to persist panel state:",e)}},[em,N]),(0,i.useEffect)(()=>{if(!e)return;let t=ta.map(e=>({...e,status:"unknown",segmentCount:0}));eu(t),eh(e=>e&&0!==t.length?t.some(t=>t.sceneId===e)?e:"":e)},[e,ta]),(0,i.useEffect)(()=>{ep.current=ec},[ec]),(0,i.useEffect)(()=>{!em||0!==ta.length&&(ta.some(e=>e.sceneId===em)||eh(""))},[ta,em]);let tx=(0,i.useCallback)(async()=>
96{if(0===ta.length)return;let e=new Map(ep.current.map(e=>[e.sceneId,e])),t=ta.map(t=>({sceneId:t.sceneId,sceneNumber:t.sceneNumber,label:t.label,storageKey:e.get(t.sceneId)?.storageKey||t.storageKey,status:"unknown",segmentCount:0}));if(td){let e=y.zC.getState().blocks;eu(t.map(t=>{if(!t.storageKey)return{...t,status:"none"};let a=e.some(e=>e.sceneId===t.sceneId&&"caption"===e.type);return{...t,status:a?"ready":"unknown"}}));return}A?N&&(eu(t.map(e=>({...e,status:e.storageKey?"checking":"none"}))),eu(await Promise.all(t.map(async e=>{if(!e.storageKey)return{...e,status:"none"};try{let t=await (0,tz.FP)(N,e.storageKey);if(t.success&&t.data){let a=t.data.status;return{...e,status:"ready"===a?"ready":"pending"===a?"pending":"processing"===a?"processing":"error"===a?"error":"none",segmentCount:t.data.segments?.length??0}}return{...e,status:"error"}}catch{return{...e,status:"error"}}})))):eu(t.map(e=>({...e,status:e.storageKey?"unknown":"none"})))},[A,N,ta,td]);(0,i.useEffect)(()=>{e&&N&&ta.length>0&&tx()},[e,N,ta.length,tx]),(0,i.useEffect)(()=>{let e=null;z&&ta.some(e=>e.sceneId===z)&&(e=z),e||(e=d||O),!e||ta.some(t=>t.sceneId===e)&&eh(e)},[d,O,z,ta]);let tb=(0,i.useRef)(void 0),ty=(0,i.useCallback)(async()=>{if(!th)return void ev(tf());if(!N)return void ev("No project selected.");let e=ec.filter(e=>ts(e)),t=e.filter(e=>"ready"!==e.status&&"pending"!==e.status&&"processing"!==e.status);if(0===t.length&&e.length>0)return void ej("All scenes already have captions");if(0===e.length)return void ev("No scenes with media found.");eb(!0),ev(null),ej(null);let a=0,r=0,n=!1;if(td&&tb.current)for(let e of t)try{eu(t=>t.map(t=>t.sceneId===e.sceneId?{...t,status:"processing"}:t)),await tb.current(e)?(a++,eu(t=>t.map(t=>t.sceneId===e.sceneId?{...t,status:"ready"}:t))):(r++,eu(t=>t.map(t=>t.sceneId===e.sceneId?{...t,status:"error"}:t)))}catch{r++,eu(t=>t.map(t=>t.sceneId===e.sceneId?{...t,status:"error"}:t))}else for(let e of t){let t=async()=>!!tb.current&&!!await tb.current(e)&&(a++,n=!0,eu(t=>t.map(t=>t.sceneId===e.sceneId?{...t,status:"ready"}:t)),!0);try{eu(t=>t.map(t=>t.sceneId===e.sceneId?{...t,status:"processing"}:t));let i=await (0,tz.YZ)(N,{storage_key:e.storageKey,scene_id:e.sceneId,model:tm});if(i5(i)){a++;let t=i.data?.status,r="already_ready"===t;eu(t=>t.map(t=>t.sceneId===e.sceneId?{...t,status:r?"ready":"pending"}:t)),r&&(n=!0)}else{if(await t())continue;r++,eu(t=>t.map(t=>t.sceneId===e.sceneId?{...t,status:"error"}:t)),ev(i2(i))}}catch{if(await t())continue;r++,eu(t=>t.map(t=>t.sceneId===e.sceneId?{...t,status:"error"}:t))}}eb(!1),a>0&&(td?(ej(`Generated captions for ${a} scene${a>1?"s":""}`),h?.()):(ej(n?`Transcription ready for ${a} scene${a>1?"s":""}`:`Queued ${a} scene${a>1?"s":""} for transcription`),h?.(),n?tx():setTimeout(()=>tx(),5e3))),r>0&&ev(`${r} scene${r>1?"s":""} failed`)},[th,tf,N,ec,ts,tm,td,h,tx]),tv=(0,i.useCallback)(async e=>{if(!th)return ev(tf()),!1;if(!N||!e.storageKey)return!1;eu(t=>t.map(t=>t.sceneId===e.sceneId?{...t,status:"processing"}:t));let t=async()=>!!tb.current&&!!await tb.current(e)&&(eu(t=>t.map(t=>t.sceneId===e.sceneId?{...t,status:"ready"}:t)),ej(`Transcription ready locally for "${e.label}"`),h?.({sceneId:e.sceneId,storageKey:e.storageKey??void 0}),tx(),eN(e),!0);try{let a=await (0,tz.YZ)(N,{storage_key:e.storageKey,scene_id:e.sceneId,force:!0,model:tm});if(i5(a)){let t=a.data?.status,r="already_ready"===t;return eu(t=>t.map(t=>t.sceneId===e.sceneId?{...t,status:r?"ready":"pending"}:t)),ej(r?`Transcription ready for "${e.label}"`:`Queued "${e.label}" for transcription`),h?.({sceneId:e.sceneId,storageKey:e.storageKey??void 0}),r?tx():setTimeout(()=>tx(),5e3),eN(e),!0}if(await t())return!0;return eu(t=>t.map(t=>t.sceneId===e.sceneId?{...t,status:"error"}:t)),ev(i2(a)),!1}catch{if(await t())return!0;return eu(t=>t.map(t=>t.sceneId===e.sceneId?{...t,status:"error"}:t)),!1}},[th,tf,N,tm,h,tx]),tw=(0,i.useMemo)(()=>ta.find(e=>e.sceneId===em)||null,[ta,em]),tk=(0,i.useMemo)(()=>ec.find(e=>e.sceneId===em)||null,[ec,em]),tS=(0,i.useMemo)(()=>E.find(e=>"scene"===e.type&&e.sceneId===em&&!e.sceneId.startsWith("__track0"))||null,[E,em]),tj=tk?.storageKey||tw?.storageKey||tS?.audioStorageKey||i1(tS?.scene||{})||(em?tr.get(em):void 0)||null,tI=(0,i.useMemo)(()=>I.find(e=>
96e.id===em)||tS?.scene||null,[I,tS?.scene,em]),tN=(0,i.useMemo)(()=>{if(em===d&&"string"==typeof c)return ia(c);let e=tI?.text;return"string"==typeof e?ia(e):""},[em,d,tI,c]);(0,i.useEffect)(()=>{!e||eE||eC.length>0||tN&&G(e=>0!==e.trim().length&&e!==w.current||e===tN?e:(w.current=tN,tN))},[e,eE,eC.length,em,tN]);let tC=(0,i.useCallback)(e=>{let t=E.find(t=>"scene"===t.type&&t.sceneId===e.sceneId&&!t.sceneId.startsWith("__track0"))||null,a=I.find(t=>t.id===e.sceneId)||t?.scene||null,r=a?.media?.assetRef||(t?.scene?.media?.assetRef??null),n=ec.find(t=>t.sceneId===e.sceneId)?.storageKey||e.storageKey||t?.audioStorageKey||i1(t?.scene||{})||tr.get(e.sceneId)||null;return{sceneBlock:t,sceneSource:a,mediaAssetRef:r,resolvedStorageKey:n}},[E,ec,I,tr]),tM=(0,i.useCallback)(async(e,t)=>{let r=e?.media?.url;if(!r)return null;if(r.startsWith("localBlob://")){let{resolveLocalBlobUrl:e}=await Promise.resolve().then(a.bind(a,32701));return e(r)}if(r.startsWith("blob:")||r.startsWith("data:")||r.startsWith("file:"))return r;if(t)try{let{resolveMediaUrl:e}=await Promise.resolve().then(a.bind(a,40554));return await e(r,void 0,t)||r}catch(e){console.warn("[CaptionsPanel] Failed to resolve media URL from assetRef:",e)}return r},[]),t_=(0,i.useCallback)(async(e,t,r)=>{if(!t?.media?.url)return null;let n=await tM(t,r);if(!n)return null;let{authenticatedMediaFetch:i}=await Promise.resolve().then(a.bind(a,40554)),s=await i(n);if(!s.ok)throw Error(`Could not read scene media (${s.status})`);let o=await s.blob(),l=o.type||("image"===t.media.type?"image/jpeg":"video/mp4"),d="image"===t.media.type?"jpg":l.includes("webm")?"webm":l.includes("quicktime")?"mov":l.includes("ogg")?"ogg":"mp4";return new File([o],`scene-${e.sceneId}.${d}`,{type:l})},[tM]),tA=(0,i.useCallback)(async(e,t,r)=>{if(!N)return null;try{let n=await t_(e,t,r);if(!n)return null;ej(`Uploading Scene ${e.sceneNumber} media...`);let{uploadViaBackend:i}=await Promise.resolve().then(a.bind(a,9756)),s=await i(N,e.sceneId,n),o=s.data?.storage_key;if(!s.success||!s.data?.success||!o)throw Error(s.error?.message||"Upload failed");return eu(t=>t.map(t=>t.sceneId===e.sceneId?{...t,storageKey:o}:t)),ej(`Scene ${e.sceneNumber} uploaded for transcription`),o}catch(e){return console.error("[CaptionsPanel] Local media upload for transcription failed:",e),null}},[t_,N]),tE=(0,i.useCallback)((e,t,a,r="faster-whisper",n)=>{if(!t)return!1;let i=e.sceneId,{captionBlocks:s,usedUntrimmedFallback:o}
96=function(e){let{sceneId:t,sceneStart:a,sceneDuration:r,sceneTrimStart:n,captionTrackId:i,segments:s,alignmentProvider:o,generationTag:l}=e,d=n+r,c=iX(iU),u=s.filter(e=>e.end>n&&e.start<d),p=0===u.length&&s.length>0;return{captionBlocks:(p?s:u).map(e=>{let s,u,m=p?Math.max(0,e.start):Math.max(0,e.start-n),h=(p?e.end:Math.min(r,e.end-n))-m;if(h<=0)return null;let f=(s=Math.round(1e3*e.start),u=Math.round(1e3*e.end),l?`caption-${t}-${l}-${s}-${u}`:`caption-${t}-${s}-${u}`),g=p?e.start:Math.max(e.start,n),x=e.words?.filter(e=>p?e.end>0:e.end>n&&e.start<d).map(e=>({word:e.word,start:Math.max(0,e.start-g),end:Math.min(h,e.end-g)}))||null,b=Array.isArray(x)&&x.length>0;return{id:f,sceneId:t,start:a+m,duration:h,inOffset:0,outOffset:0,fullDuration:h,trackId:i,captionText:e.text,captionWords:x,captionHighlightEnabled:!1,captionHighlightStyle:b?c:void 0,alignmentProvider:o,captionBox:{x:.06,y:.76,width:.88,height:.14},captionStyle:{fontSize:iF.zl.fontSize,fontFamily:iF.zl.fontFamily,fontWeight:iF.zl.fontWeight,color:iF.zl.color,backgroundColor:iF.zl.backgroundColor,textAlign:iF.zl.textAlign,outlineColor:iF.zl.outlineColor,outlineWidth:iF.zl.outlineWidth,animationPreset:iF.zl.animationPreset},captionPunctuationMode:iL.K5,source:"auto",sourceCaptionId:f}}).filter(e=>null!==e),usedUntrimmedFallback:p}}({sceneId:i,sceneStart:t.start,sceneDuration:t.duration,sceneTrimStart:t.inOffset||0,captionTrackId:B(t.trackId),segments:a,alignmentProvider:r,generationTag:n});if(o&&console.warn("[CaptionsPanel] No segments matched scene trim range; falling back to untrimmed segment mapping."),R(i),s.length>0&&P(s),eu(e=>e.map(e=>e.sceneId===i?{...e,status:"ready",segmentCount:s.length}:e)),s.length>0){let e=s[0];F(e.id),G(e.captionText||"")}return ej(s.length>0?`Replaced captions for Scene ${e.sceneNumber} (${s.length} blocks)`:`No speech segments found for Scene ${e.sceneNumber}`),!0},[R,P,F,B]),tT=(0,i.useCallback)(async e=>{let{sceneBlock:t,sceneSource:r,mediaAssetRef:n,resolvedStorageKey:i}=tC(e),s=E.find(t=>t.id===e.sceneId&&("voiceover"===t.type||"audio"===t.type));if(s&&"voiceover"===s.type&&s.label&&s.duration>0){let t=s.label.split(/\s+/).map(e=>e.trim()).filter(Boolean);if(t.length>3){let a=s.duration/t.length,r=[{start:0,end:s.duration,text:s.label,words:t.map((e,r)=>({word:e,start:r*a,end:r===t.length-1?s.duration:(r+1)*a,probability:1}))}];return tE(e,s,r,"text-distribution",Date.now().toString(36))}}try{let i=null;if(s&&!r){let{resolveMediaUrl:t,authenticatedMediaFetch:r}=await Promise.resolve().then(a.bind(a,40554)),n=s.audioUrl||"";if(s.audioStorageKey&&(n=await t(s.audioUrl,s.audioStorageKey)),!n)return ev(`No audio source found for ${e.label||`Scene ${e.sceneNumber}`}.`),!1;let o=await r(n);if(!o.ok)return ev(`Could not load audio for ${e.label||`Scene ${e.sceneNumber}`} (${o.status}).`),!1;let l=await o.blob(),d=l.type||"audio/mpeg",c=d.includes("wav")?"wav":d.includes("ogg")?"ogg":"mp3";i=new File([l],`audio-${e.sceneId}.${c}`,{type:d})}else{if(!r)return ev(`No audio source found for ${e.label||`Scene ${e.sceneNumber}`}.`),!1;i=await t_(e,r,n)}if(!i)return ev(`Could not read ${e.label||`Scene ${e.sceneNumber}`} media file.`),!1;eu(t=>t.map(t=>t.sceneId===e.sceneId?{...t,status:"processing"}:t)),ej(`Preparing Scene ${e.sceneNumber} for browser transcription...`);let{transcribeCaptionFileLocallyInBrowser:o}=await a.e(8305).then(a.bind(a,48305)),l=await o(i,{onProgress:t=>{if("decoding_audio"===t.stage)return void ej(`Decoding Scene ${e.sceneNumber} audio in browser...`);if("loading_runtime"===t.stage||"loading_model"===t.stage){let e="number"==typeof t.progress?` (${t.progress}%)`:"";ej(`Loading local model${e}...`);return}"transcribing"===t.stage&&ej(`Transcribing Scene ${e.sceneNumber} in browser...`)}});if(!l.success)return ev(l.errorMessage||`Browser transcription failed for Scene ${e.sceneNumber}.`),!1;let d=l.segments||[],c=Date.now().toString(36);return tE(e,t||s||null,d,"faster-whisper",c)}catch(t){return console.error("[CaptionsPanel] Local transcription failed:",t),ev(t instanceof Error?t.message:`Failed to analyze Scene ${e.sceneNumber}`),!1}},[tE,E,t_,tC]);tb.current=tT;let t$=(0,i.useCallback)(async e=>{if(console.log("[CaptionsPanel] handleGenerateScene called:",{sceneId:e.sceneId,label:e.label,storageKey:e.storageKey,canUseSelectedTranscribeMode:th,shouldUseLocalCaptionFlow:td}),!th){console.warn("[CaptionsPanel] canUseSelectedTranscribeMode=false, blocked"),ev(tf());return}ev(null),eb(!0);try{let t=E.some(t=>t.id===e.sceneId&&("voiceover"===t.type||"audio"===t.type)&&t.audioStorageKey);if(td||t){console.log("[CaptionsPanel] Using LOCAL caption flow for:",e.sceneId,{isAudioBlockEntry:t,shouldUseLocalCaptionFlow:td});let a=await tT(e);console.log("[CaptionsPanel] Local flow result:",a),a&&eN({...e,status:"ready"});return}let{sceneSource:a,mediaAssetRef:r,resolvedStorageKey:n}=tC(e),i=n;if(i||(i=await tA(e,a,r)),!i)return void ev(`${e.label||`Scene ${e.sceneNumber}`} has no analyzable storage key yet.`);await tv({...e,storageKey:i})}finally{eb(!1)}},[E,th,tT,tf,tC,tv,td,tA]),tP=(0,i.useCallback)(async()=>
96{if(console.log("[CaptionsPanel] handleGenerateSelected:",{selectedSceneInfo:tw,selectedSceneResolvedStorageKey:tj,selectedSceneStatusInfo:tk}),!tw)return void ev("Select a scene first.");let e={sceneId:tw.sceneId,sceneNumber:tw.sceneNumber,label:tw.label,storageKey:tj,status:tk?.status??"unknown",segmentCount:tk?.segmentCount??0};await t$(e)},[t$,tw,tj,tk]),tD=(0,i.useRef)(null),tR=(0,i.useRef)(null),[tL,tF]=(0,i.useState)(null);if((0,i.useEffect)(()=>{let e=window;return e.__FACELESS_REGENERATE_SCENE_CAPTIONS__=e=>new Promise(t=>{if(!e)return void t();let a=!1,r=()=>{a||(a=!0,t())};tR.current=r,tD.current=e,eh(e),tF(e),window.setTimeout(()=>{tD.current===e&&(tD.current=null,tF(t=>t===e?null:t)),r()},9e3)}),()=>{e.__FACELESS_REGENERATE_SCENE_CAPTIONS__&&delete e.__FACELESS_REGENERATE_SCENE_CAPTIONS__}},[]),(0,i.useEffect)(()=>{if(!tL||em!==tL||!tw||tw.sceneId!==tL)return;tF(null),tD.current=null;let e=tR.current;tR.current=null,Promise.resolve(tP()).finally(()=>e?.())},[tL,em,tw,tP]),(0,i.useEffect)(()=>{0!==ec.length&&eu(e=>{let t=!1,a=e.map(e=>{let a=q.get(e.sceneId)||0,r="pending"===e.status||"processing"===e.status||"checking"===e.status?e.status:a>0?"ready":"error"===e.status?"error":"none";return e.segmentCount===a&&e.status===r?e:(t=!0,{...e,status:r,segmentCount:a})});return t?a:e})},[q,ec.length]),!e)return null;let tO=ec.filter(e=>ts(e)).length,tB=ex||tk?.status==="pending"||tk?.status==="processing",tW=(0,r.jsxs)("div",{"data-captions-panel":!0,ref:g,className:"bg-slate-950/95 border border-white/[0.08] rounded-xl shadow-[0_24px_60px_-16px_rgba(0,0,0,0.85),0_0_0_1px_rgba(0,0,0,0.4)] flex flex-col overflow-hidden backdrop-blur-xl",style:f,children:[(0,r.jsx)("div",{onMouseDown:j,className:`absolute top-0 right-0 h-full w-2 cursor-ew-resize transition-colors z-10 ${S?"bg-amber-400/20":"hover:bg-amber-400/10"}`}),(0,r.jsxs)("div",{className:"flex items-center justify-between gap-1.5 px-2 py-1.5 border-b border-white/[0.06] bg-gradient-to-b from-slate-900/60 to-slate-950/40 flex-shrink-0",children:[(0,r.jsx)(K,{activePanel:n,onSelectPanel:o}),(0,r.jsx)("button",{onClick:t,className:"p-1.5 rounded-md text-slate-500 hover:text-slate-200 hover:bg-white/[0.06] transition-colors",title:"Close panel",children:(0,r.jsx)(H.A,{size:13})})]}),(0,r.jsxs)("div",{className:"flex-1 overflow-y-auto p-2.5 flex flex-col gap-2.5 scrollbar-hidden",children:[eI&&(0,r.jsxs)("button",{onClick:()=>void t$(eI),disabled:ex,className:`order-2 w-full flex items-center justify-center gap-2 px-3 py-2.5 text-[11px] font-medium rounded-lg transition-all duration-150 ${ex?"bg-white/[0.03] text-white/25 cursor-not-allowed":"bg-amber-500/[0.06] text-amber-200/80 hover:bg-amber-500/[0.12] border border-amber-500/[0.12]"}`,children:[(0,r.jsx)(iP.A,{size:12}),`Regenerate Scene ${eI.sceneNumber}`]}),(0,r.jsxs)("div",{className:"order-3 rounded-xl border border-white/[0.05] bg-white/[0.02] p-2.5",children:[(0,r.jsx)("span",{className:"mb-1.5 block text-[9px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Caption Styles"}),(0,r.jsx)(iQ.U,{variant:"editor",onApply:eJ,buildCurrentPack:eZ})]}),(0,r.jsxs)("div",{className:"order-4 flex flex-col gap-2.5",children:[(0,r.jsx)("div",{className:"rounded-xl border border-white/[0.05] bg-white/[0.02] p-2.5",children:(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{className:"flex items-center justify-between mb-1.5",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("label",{className:"text-[9px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Caption Text"}),(0,r.jsxs)("div",{className:"flex items-center gap-1",children:[(0,r.jsx)("span",{className:"text-[9px] text-white/25",children:"Punctuation"}),(0,r.jsx)("div",{className:"flex gap-px rounded bg-white/[0.03] p-px",children:[{value:"creator",label:"Min"},{value:"original",label:"Full"}].map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>eG(e.value),disabled:0===eC.length,className:`rounded px-1 py-0 text-[9px] font-medium transition-colors duration-150 disabled:cursor-not-allowed disabled:opacity-40 ${el===e.value?"bg-white/[0.08] text-white/70":"text-white/25 hover:text-white/50"}`,children:e.label},e.value))})]})]}),(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[eC.length>1&&(0,r.jsx)("span",{className:"text-[9px] text-amber-300/70",children:`${eC.length} selected - style edits apply to all`}),!eE&&Y.trim()&&(0,r.jsxs)("button",{type:"button",onClick:e3,className:"flex items-center gap-1 px-1.5 py-0.5 rounded-md text-[9px] font-medium bg-emerald-500/[0.08] text-emerald-300/80 border border-emerald-500/[0.15] hover:bg-emerald-500/[0.14] transition-all duration-150",children:[(0,r.jsx)(a0.A,{size:9}),"Add at ",T.toFixed(1),"s"]}),(0,r.jsx)("span",{className:"text-[9px] text-white/20 tabular-nums",children:eP})]})]}),(0,r.jsxs)("div",{className:"relative",children:[(0,r.jsx)("textarea",{ref:b,value:Y,onChange:e=>eQ(e.target.value),onClick:e0,onKeyUp:e0,onSelect:e0,onKeyDown:e=>
96{(e.metaKey||e.ctrlKey)&&("z"===e.key.toLowerCase()||"y"===e.key.toLowerCase())&&e.stopPropagation()},placeholder:eC.length>1?"Edit primary selected caption...":eE?"Edit selected caption...":"Enter caption text...",className:"w-full h-16 px-2.5 py-2 pr-8 bg-white/[0.03] border border-white/[0.06] rounded-lg text-xs text-white/85\n placeholder:text-white/20 resize-none scrollbar-hidden\n focus:outline-none focus:border-amber-500/25 focus:bg-white/[0.05] transition-all duration-150",style:{fontFamily:(0,iR.c)(X.fontFamily)}}),!eE&&tN&&(0,r.jsx)("div",{className:"mt-1 text-[9px] text-white/25",children:"Prefilled from the selected scene text."}),(0,r.jsx)(i3,{onBeforeOpen:e0,onEmojiSelect:e1})]})]})}),(0,r.jsx)(i7,{style:X,highlightStyle:ee,highlightEnabled:ea,captionDisplayMode:en,captionDisplayWindowSize:es,selectionCount:eC.length,applyScope:ez,applyTargetsCount:e5.length,panelRef:g,toggleHighlightEnabled:eq,updateSelectedCaptionStyle:eO,updateSelectedHighlightStyle:eB,updateCaptionDisplayMode:eY,updateCaptionDisplayWindowSize:eX,setApplyScope:eL,applyToScope:e4})]}),(0,r.jsxs)("div",{className:"order-1 rounded-xl border border-white/[0.05] bg-white/[0.02] p-2.5 space-y-2.5",children:[tg&&(0,r.jsx)("div",{className:"rounded-lg border border-amber-500/15 bg-amber-950/20 px-3 py-2 text-[10px] text-amber-200/80 leading-relaxed",children:"Cloud transcription requires Pro. Local projects can transcribe for free."}),(0,r.jsxs)("div",{className:"space-y-3",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between",children:[(0,r.jsx)("span",{className:"text-[9px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Generate Captions"}),(0,r.jsx)("button",{onClick:tx,className:"p-1 rounded text-white/20 hover:text-white/50 transition-colors",title:"Refresh status",children:(0,r.jsx)(iP.A,{size:10})})]}),(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,r.jsxs)("div",{className:"flex w-[104px] flex-shrink-0 rounded-md bg-white/[0.02] p-0.5",children:[(0,r.jsx)("button",{type:"button",onClick:()=>{eg("free"),ev(null)},className:`flex-1 rounded-[5px] px-2 py-1.5 text-[10px] font-medium text-center transition-all duration-150 ${"free"===ef?"bg-white/[0.08] text-white/85 shadow-sm":"text-white/30 hover:text-white/55"}`,children:"Standard"}),(0,r.jsx)("button",{type:"button",onClick:()=>{tp?(eg("pro"),ev(null)):ev(td?"Pro transcription is cloud-only. Local projects use standard.":"Pro transcription requires Pro access.")},className:`flex-1 rounded-[5px] px-2 py-1.5 text-[10px] font-medium text-center transition-all duration-150 ${"pro"===ef?"bg-white/[0.08] text-white/85 shadow-sm":"text-white/30 hover:text-white/55"} ${!tp?"opacity-50":""}`,children:"Pro"})]}),(0,r.jsxs)("select",{value:em,onChange:e=>{eh(e.target.value),ev(null)},className:"flex-1 min-w-0 px-2 py-1.5 bg-white/[0.03] border border-white/[0.06] rounded-lg text-[10px] text-white/80\n focus:outline-none focus:border-white/[0.12] transition-colors",children:[(0,r.jsx)("option",{value:"",children:"Select source..."}),e9.length>0&&(0,r.jsx)("optgroup",{label:"Scenes",children:e9.map(e=>(0,r.jsx)("option",{value:e.sceneId,children:`Scene ${e.sceneNumber}: ${e.label}${ts(e)?"":" (No media)"}`},e.sceneId))}),e7.length>0&&(0,r.jsx)("optgroup",{label:"Audio",children:e7.map(e=>(0,r.jsx)("option",{value:e.sceneId,children:`${e.label}${e.storageKey?"":" (No media)"}`},e.sceneId))})]})]}),(0,r.jsxs)("div",{className:"grid grid-cols-2 gap-1.5",children:[(0,r.jsxs)("button",{onClick:tP,disabled:!th||tB,className:`flex w-full items-center justify-center gap-1.5 px-2.5 py-1.5 text-[10px] font-medium rounded-lg transition-all duration-150 ${th&&!tB?"bg-white/[0.05] text-white/80 border border-white/[0.08] hover:bg-white/[0.08] hover:border-white/[0.12]":"bg-white/[0.02] text-white/20 border border-white/[0.04] cursor-not-allowed"}`,children:[tB&&(0,r.jsx)(x.A,{size:11,className:"animate-spin"}),"Transcribe Scene"]}),(0,r.jsxs)("button",{onClick:ty,disabled:ex||0===tO||!th,className:`flex w-full items-center justify-center gap-1.5 px-2.5 py-1.5 text-[10px] font-medium rounded-lg transition-all duration-150 ${ex?"bg-white/[0.03] text-white/30 border border-white/[0.05] curs
96or-wait":0===tO||!th?"bg-white/[0.02] text-white/20 border border-white/[0.04] cursor-not-allowed":"bg-emerald-500/[0.08] text-emerald-200/90 border border-emerald-500/[0.15] hover:bg-emerald-500/[0.12]"}`,children:[ex&&(0,r.jsx)(x.A,{size:11,className:"animate-spin"}),"Transcribe All"]})]})]})]}),ey&&(0,r.jsxs)("div",{className:"flex items-start gap-2 px-3 py-2 bg-red-950/20 border border-red-500/12 rounded-lg text-[10px] text-red-300/80 leading-relaxed",children:[(0,r.jsx)(iD.A,{size:11,className:"flex-shrink-0 mt-px"}),(0,r.jsx)("span",{children:ey})]})]}),eS&&(0,r.jsxs)("div",{className:"order-5 flex items-center gap-2 px-3 py-2 bg-emerald-500/6 border border-emerald-500/12 rounded-lg text-[10px] text-emerald-300/80",children:[(0,r.jsx)(n$.A,{size:11}),eS]})]}),U&&(0,r.jsxs)("div",{className:"px-3 py-2 border-t border-white/[0.04]",children:[(0,r.jsxs)("button",{onClick:()=>ek(e=>!e),className:"flex items-center gap-1.5 text-[10px] font-medium text-white/50 hover:text-white/75 transition-colors",children:[(0,r.jsx)(tn.A,{size:11,className:`transition-transform duration-150 ${ew?"rotate-0":"-rotate-90"}`}),"Show Full Transcript"]}),ew&&(0,r.jsx)("div",{className:"mt-2 max-h-[200px] overflow-y-auto rounded-lg border border-white/[0.06] bg-white/[0.02] px-3 py-2",children:(0,r.jsx)("p",{className:"text-[10px] text-white/70 leading-relaxed whitespace-pre-wrap select-all",children:U})})]}),(0,r.jsx)("div",{className:"px-3 py-1.5 border-t border-white/[0.06] bg-slate-950/80 flex-shrink-0 flex items-center justify-between",children:(0,r.jsx)("p",{className:"text-[9px] text-slate-600 tabular-nums",children:W>0?`${W} on timeline`:"No captions"})})]});return"u"<typeof document?tW:(0,p.createPortal)(tW,document.body)};
96var st=a(1017),sa=a(83604),sr=a(82751);function sn(){return(0,r.jsx)("svg",{width:"7",height:"7",viewBox:"0 0 7 7",fill:"none","aria-hidden":"true",className:"flex-shrink-0",children:(0,r.jsx)("rect",{x:"3.5",y:"0.5",width:"4.24",height:"4.24",rx:"0.6",transform:"rotate(45 3.5 0.5)",fill:"currentColor",opacity:"0.7"})})}function si({top:e,width:t,height:a,label:n,collapsed:i=!1,hideHeader:s=!1,chromeless:o=!1,onHeaderClick:l,headerContent:d,children:c}){return(0,r.jsxs)("div",{className:"absolute left-0 overflow-hidden rounded-[4px]",style:{top:e,width:t,height:a,...o?{background:"rgba(7, 10, 18, 0.3)"}:{background:"linear-gradient(180deg, rgba(9,13,23,0.82) 0%, rgba(5,8,15,0.9) 100%)",boxShadow:"inset 0 0 0 1px rgba(148,163,184,0.09), inset 0 2px 4px rgba(0,0,0,0.35)"}},"data-automation-child-lane":!0,children:[!s&&(0,r.jsxs)("div",{className:`absolute left-0 right-0 top-0 flex items-center ${n?"px-2.5":"px-1"}`,style:{height:sr.n_},onMouseDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),children:[n?(0,r.jsxs)("div",{className:"inline-flex items-center gap-1.5 text-[#d8c8a8]/75",children:[(0,r.jsx)(sn,{}),l?(0,r.jsx)("button",{type:"button",className:"inline-flex items-center gap-1 text-[9px] font-semibold uppercase tracking-[0.1em] text-slate-400 transition-colors hover:text-[#e8dcc8]",onClick:l,children:(0,r.jsx)("span",{children:n})}):(0,r.jsx)("span",{className:"text-[9px] font-semibold uppercase tracking-[0.1em] text-slate-400",children:n})]}):null,d?(0,r.jsx)("div",{className:`${n?"ml-2":"ml-0"} flex min-w-0 items-center gap-1`,children:d}):null]}),!i&&c]})}function ss(e,t,a){let r=so(e,t,a);return r?Math.max(0,r.snappedTime):Math.max(0,e)}function so(e,t,a){let{enableMagnet:r,enableGrid:n,isMagnetEnabled:i,isGridEnabled:s,blockDuration:o,gridIntervalSeconds:l=aj.lI,magnetThresholdSeconds:d=aj.t0}=a,c=null;if(r&&i&&t.length){for(let a of t){let t=Math.abs(e-a),r={snappedTime:a,distance:t,source:"magnet",snappedTo:a,alignment:"start"};if((!c||r.distance<c.distance)&&(c=r),void 0!==o){let t=Math.abs(e+o-a),r={snappedTime:a-o,distance:t,source:"magnet",snappedTo:a,alignment:"end"};(!c||r.distance<c.distance)&&(c=r)}}if(c&&c.distance<=d)return c}if(n&&s&&l>0){let t=Math.round(e/l)*l,a=Math.abs(e-t);return{snappedTime:t,distance:a,source:"grid",snappedTo:t,alignment:"grid"}}return null}function sl(e){return Math.max(aj.vS,Math.min(aj.Sj,e))}function sd(e){let t=e.inOffset??0,a=e.outOffset;return"number"==typeof a&&a>t?Math.max(.25,a-t):Math.max(.25,e.duration??5)}function sc(e,t,a,r,n,i="scene"===t?1:2){let s=Math.max(0,r),o=r=>e.some(e=>!e.sceneId?.startsWith("__track0")&&(e.trackId||1)===r&&"audio"===t==("voiceover"===e.type||"audio"===e.type)&&"caption"!==e.type&&a<e.start+e.duration-.001&&a+s>e.start+.001),l=Math.max(i,Math.floor(n||i));for(;o(l);)l+=1;return l}function su(e,t,a=!1,r){let n=e.trackId??1,i=e.start+e.duration,s=!1,o=!1;return t.forEach(t=>{t.id===e.id||!a&&(t.trackId??1)!==n||r&&(r.has(t.id)||r.has(t.sceneId))||(Math.abs(t.start+t.duration-e.start)<aj.B_&&(s=!0),Math.abs(i-t.start)<aj.B_&&(o=!0))}),{left:s,right:o}}function sp(e,t,a=!1,r){let n=e.trackId??1,i=e.start+e.duration,s=!1,o=!1;return t.forEach(t=>{if(t.id===e.id||!a&&(t.trackId??1)!==n||r&&(r.has(t.id)||r.has(t.sceneId)))return;let l=t.start+t.duration;(Math.abs(l-e.start)<aj.B_||Math.abs(t.start-e.start)<aj.B_)&&(s=!0),(Math.abs(i-t.start)<aj.B_||Math.abs(i-l)<aj.B_)&&(o=!0)}),{left:s,right:o}}function sm(e,t,a,r=0){return Math.max(e*t+200+r,a)}let sh=(e,t,a)=>Math.max(t,Math.min(a,e)),sf=e=>Math.round(100*e)/100;function sg({trackId:e,top:t,width:a,height:n,rowCount:s,rowHeight:o,zoomLevel:l,collapsed:d,blocks:c,snapPoints:u,isMagnetEnabled:p,isGridEnabled:m,gridIntervalSeconds:h,onChangeTiming:f,onSelectEffect:g,onRowHeightChange:x}){let b=(0,i.useRef)(null),[y,v]=(0,i.useState)(null),[w,k]=(0,i.useState)(!1),S=(0,i.useRef)(null),j=(0,i.useCallback)(t=>{if(!x)return;t.preventDefault(),t.stopPropagation(),k(!0);let a=t.clientY,r=Math.max(1,s),n=document.body.style.cursor,i=document.body.style.userSelect;document.body.style.cursor="ns-resize",document.body.style.userSelect="none";let l=t=>{t.preventDefault();let n=o+(t.clientY-a)/r;null!=S.current&&cancelAnimationFrame(S.current),S.current=requestAnimationFrame(()=>{S.current=null,x(e,n)})},d=()=>{k(!1),null!=S.current&&cancelAnimationFrame(S.current),document.body.style.cursor=n,document.body.style.userSelect=i,document.removeEventListener("mousemove",l,!0),document.removeEventListener("mouseup",d,!0)};document.addEventListener("mousemove",l,!0),document.addEventListener("mouseup",d,!0)},[x,o,s,e]),I=(0,i.useCallback)((e,t)=>{let a=so(e,u,{enableMagnet:!0,enableGrid:!0,isMagnetEnabled:p,isGridEnabled:m,blockDuration:t,gridIntervalSeconds:h});return a?Math.max(0,a.snappedTime):Math.max(0,e)},[u,p,m,h]),N=(0,i.useCallback)((e,t,a)=>{let r=b.current;if(!r||l<=0)return;let{block:n}=r,i=Math.max(0,n.sceneDurationSec),d=(e-r.startX)/l,c=r.initStartOffset,u=r.initDuration;if("move"===r.mode)c=sh(I(n.sceneStartSec+r.initStartOffset+d,r.initDuration)-n.sceneStartSec,0,Math.max(0,i-r.initDuration));else if("start"===r.mode){let e=sh(I(n.sceneStartSec+r.initStartOffset+d,void 0)-n.sceneStartSec,0,r.initStartOffset+r.initDuration-aj.sr);c=e,u=r.initStartOffset+r.initDuration-e}else u=sh(I(n.sceneStartSec+r.initStartOffset+r.initDuration+d,void 0)-n.sceneStartSec,r.initStartOffset+aj.sr,i)-r.initStartOffset;let p=r.initLaneRow;if("move"===r.mode){let e=Math.round((t-r.startY)/o);p=sh(r.initLaneRow+e,0,Math.max(0,s))}let m=sf(c),h=sf(u);if(a){v(null);let e=m<=.05&&m+h>=i-.05;f(n.sceneId,n.effectId,e?{startOffset:null,duration:null,laneRow:p}:{startOffset:m,duration:h,laneRow:p},!0)}else v({effectId:n.effectId,startOffset:m,duration:h,laneRow:p})},[l,s,o,I,f]),C=(0,i.useCallback)((e,t)=>a=>{if(e.windowable){a.preventDefault(),a.stopPropagation(),b.current={mode:t,pointerId:a.pointerId,startX:a.clientX,startY:a.clientY,initStartOffset:e.startOffsetSec,initDuration:e.durationSec,initLaneRow:e.laneRow,block:e};try{a.target.setPointerCapture?.(a.pointerId)}catch{}}},[]),M=(0,i.useCallback)(e=>{b.current&&b.current.pointerId===e.pointerId&&N(e.clientX,e.clientY,!1)},[N]),_=(0,i.useCallback)(e=>{let t=b.current;t&&t.pointerId===e.pointerId&&(Math.abs(e.clientX-t.startX)>3||Math.abs(e.clientY-t.startY)>3?N(e.clientX,e.clientY,!0):g(t.block.sceneId,t.block.effectId,t.block),b.current=null)},[N,g]);return(0,r.jsxs)(si,{top:t,width:a,height:n,label:"",hideHeader:!0,chromeless:!0,collapsed:d,children:[(0,r.jsx)("div",{className:"absolute inset-0",onPointerMove:M,onPointerUp:_,onPointerCancel:_,children:c.map(e=>{let t=y&&y.effectId===e.effectId?y:null,a=t?t.startOffset:e.startOffsetSec,n=t?t.duration:e.durationSec,i=t?t.laneRow:e.laneRow,s=(e.sceneStartSec+a)*l,d=Math.max(6,n*l),c=i*o+1,u=d>=34;return e.isLoading?(0,r.jsxs)("div",{"data-testid":"effects-lane-loading-block",className:"pointer-events-none absolute flex select-none items-center justify-center overflow-hidden rounded-[4px] bg-[#0b0d1c]/85",style:{left:s,width:d,top:c,height:o-2,zIndex:5,boxSh
96adow:"inset 0 0 0 1px rgba(129,140,248,0.14)"},"aria-label":"Loading effects",children:[(0,r.jsx)("div",{"aria-hidden":!0,className:"gen-conveyor absolute inset-0",style:{"--gen-stripe":"rgba(129,140,248,0.07)"}}),u&&(0,r.jsxs)("div",{className:"relative flex max-w-full items-center gap-1.5 rounded-md border border-indigo-400/20 bg-black/50 px-1.5 py-[2px]",children:[(0,r.jsxs)("span",{className:"gen-dots text-indigo-300","aria-hidden":!0,children:[(0,r.jsx)("span",{}),(0,r.jsx)("span",{}),(0,r.jsx)("span",{})]}),(0,r.jsx)("span",{className:"truncate font-mono text-[8px] font-semibold uppercase tracking-[0.16em] text-indigo-200/90",children:"Loading effects"})]})]},e.effectId):(0,r.jsxs)("div",{className:"group/fx absolute flex select-none touch-none items-stretch overflow-hidden rounded-[4px] text-[9px] leading-none transition-[box-shadow,filter] duration-150",style:{left:s,width:d,top:c,height:o-2,zIndex:e.isFilter?1:10+i,background:e.isFilter?"linear-gradient(180deg, rgba(148,163,184,0.09) 0%, rgba(12,15,25,0.88) 55%, rgba(8,10,17,0.94) 100%)":"linear-gradient(180deg, rgba(129,140,248,0.14) 0%, rgba(13,15,28,0.88) 55%, rgba(9,10,20,0.94) 100%)",boxShadow:"inset 0 0 0 1px rgba(255,255,255,0.05), 0 1px 2px rgba(0,0,0,0.3)"},title:`${e.label}${e.isFilter?" \xb7 filter (whole scene)":""}`,children:[(0,r.jsx)("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-[1.5px]",style:{background:e.isFilter?"#94a3b8":"#a5b4fc",opacity:e.isFilter?.35:.55},"aria-hidden":"true"}),(0,r.jsx)("div",{className:"pointer-events-none absolute inset-0 bg-white/0 transition-colors duration-150 group-hover/fx:bg-white/[0.06]"}),e.windowable&&(0,r.jsx)("div",{onPointerDown:C(e,"start"),className:"relative z-10 flex w-1.5 shrink-0 cursor-ew-resize items-center justify-center",title:"Trim start",children:(0,r.jsx)("div",{className:"h-[60%] w-[2px] rounded-full bg-white/0 transition-colors duration-150 group-hover/fx:bg-white/80"})}),(0,r.jsx)("div",{onPointerDown:e.windowable?C(e,"move"):void 0,onClick:()=>g(e.sceneId,e.effectId,e),className:`relative z-10 flex min-w-0 flex-1 items-center px-1.5 ${e.windowable?"cursor-grab active:cursor-grabbing":"cursor-pointer"}`,children:u&&(0,r.jsx)("span",{className:`truncate text-[10px] font-medium tracking-wide ${e.isFilter?"text-slate-200/80":"text-indigo-100/90"}`,style:{textShadow:"0 1px 2px rgba(0,0,0,0.55)"},children:e.label})}),e.windowable&&(0,r.jsx)("div",{onPointerDown:C(e,"end"),className:"relative z-10 flex w-1.5 shrink-0 cursor-ew-resize items-center justify-center",title:"Trim end",children:(0,r.jsx)("div",{className:"h-[60%] w-[2px] rounded-full bg-white/0 transition-colors duration-150 group-hover/fx:bg-white/80"})})]},e.effectId)})}),x&&(0,r.jsx)("div",{className:`absolute left-0 right-0 bottom-0 h-2 cursor-ns-resize z-40 ${w?"bg-indigo-400/20":"hover:bg-indigo-400/[0.12]"}`,onPointerDown:e=>e.stopPropagation(),onMouseDown:j,onClick:e=>e.stopPropagation(),title:"Drag to resize the FX lane",children:(0,r.jsx)("div",{className:`absolute left-0 right-0 bottom-0 h-px transition-colors ${w?"bg-indigo-400/80":"bg-slate-500/30"}`})})]})}function sx(e,t){if(!e||!t.audioUrl)return null;let a=(0,et.U)(t.audioUrl,{sourceType:"voiceover"===t.type?"voiceover":"project_audio",sourceSceneId:t.scene?.id,sourceAudioBlockId:t.id,storageKey:t.audioStorageKey,sourceFingerprintHint:(0,et.z)(t.scene?.audio?.assetRef)??void 0}),r=a?e[a]:void 0;if(r?.rhythm?.beatTimes?.length)return r;for(let a of Object.values(e))if(a.sourceAudioBlockId===t.id&&a.rhythm?.beatTimes?.length)return a;return null}function sb(e,t){let a=Math.max(0,t.inOffset||0),r=Math.max(0,t.start),n=Math.max(0,t.duration),i=[];for(let t of e){if(!Number.isFinite(t))continue;let e=t-a;e<0||e>n||i.push(r+e)}return i}let sy=1/30;var sv=a(92714);function sw(e){if(e.type!==nK.de)return!1;let t="number"==typeof e.params?.preset?e.params.preset:null,a=null!=t?(0,nK.E3)(t)?.key:null;return(0,nK.Vq)(a)}let sk={muted:!1,locked:!1,visible:!0},sS=e=>Math.max(aj.ol,Math.min(aj.Uu,e)),sj=e=>Math.max(sr.SU,Math.min(sr.O$,e));function sI(e,t,a=new Map){let r={};return e.forEach((e,n)=>{let i=t.get(n),s=a.get(n);r[n.toString()]=void 0===i?{...e}:{...e,height:sS(i)},void 0!==s&&(r[n.toString()]={...r[n.toString()],automationLaneHeight:sj(s)})}),t.forEach((e,t)=>{let a=t.toString(),n=sS(e);if(!r[a]){r[a]={...sk,height:n};return}r[a]={...r[a],height:n}}),a.forEach((e,t)=>{let a=t.toString(),n=sj(e);if(!r[a]){r[a]={...sk,automationLaneHeight:n};return}r[a]={...r[a],automationLaneHeight:n}}),r}var sN=a(57396);function sC(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}function sM(e,t,a,r){if(!e||0===e.length)return e;let n=t-a;return e.map(e=>{let t=e.start+n,a=e.end+n,i=Math.max(0,Math.min(r,t)),s=Math.max(i,Math.min(r,a));return{...e,start:i,end:s}}).filter(e=>e.end>e.start+.005)}var s_=a(51601),sA=a(44158);function sE(e){let{scenes:t,originalSceneId:a,newScene:r}=e,n=t.findIndex(e=>e.id===a),i=[...t];i.splice(n+1,0,r);let s=i.map((e,t)=>({...e,sequenceIndex:t}));return{type:"ADD_SCENE",previousState:{scenes:[...t],affectedSceneId:r.id},newState:{scenes:s,affectedSceneId:r.id}}}function sT(e){return e&&e.start!==e.end?{start:Math.min(e.start,e.end),end:Math.max(e.start,e.end)}:null}function s$(e,t){return!e&&!t||!!e&&!!t&&e.start===t.start&&e.end===t.end}function sP(e,t){let a=Math.max(0,Math.min(1,e/100)).toFixed(4);return"in"===t?`M 0 1 C 0.4 1 0.6 ${a} 1 ${a}`:`M 0 ${a} C 0.4 ${a} 0.6 1 1 1`}let sD=(e,t)=>{let a=new Date().toISOString().split("T")[1].slice(0,12);console.log(`[SCENE-FLOW] [${a}] TIMELINE: ${e}`,t?JSON.stringify(t,null,0):"")},sR=["zoom_in","zoom_out","pan_right","pan_left","pan_up","pan_down","pan_up_right","pan_up_left","pan_down_right","pan_down_left","rotate_right","rotate_left"],sz={zoom_in:{id:"zoom_in",label:"Zoom In",valueRanges:[{propertyId:"userZoom",startValue:1,endValue:1.15}]},zoom_out:{id:"zoom_out",label:"Zoom Out",valueRanges:[{propertyId:"userZoom",startValue:1.15,endValue:1}]}
96,pan_right:{id:"pan_right",label:"Pan Right",valueRanges:[{propertyId:"panX",startValue:0,endValue:.35}]},pan_left:{id:"pan_left",label:"Pan Left",valueRanges:[{propertyId:"panX",startValue:0,endValue:-.35}]},pan_up:{id:"pan_up",label:"Pan Up",valueRanges:[{propertyId:"panY",startValue:0,endValue:.3}]},pan_down:{id:"pan_down",label:"Pan Down",valueRanges:[{propertyId:"panY",startValue:0,endValue:-.3}]},pan_up_right:{id:"pan_up_right",label:"Pan Up Right",valueRanges:[{propertyId:"panX",startValue:0,endValue:.3},{propertyId:"panY",startValue:0,endValue:.25}]},pan_up_left:{id:"pan_up_left",label:"Pan Up Left",valueRanges:[{propertyId:"panX",startValue:0,endValue:-.3},{propertyId:"panY",startValue:0,endValue:.25}]},pan_down_right:{id:"pan_down_right",label:"Pan Down Right",valueRanges:[{propertyId:"panX",startValue:0,endValue:.3},{propertyId:"panY",startValue:0,endValue:-.25}]},pan_down_left:{id:"pan_down_left",label:"Pan Down Left",valueRanges:[{propertyId:"panX",startValue:0,endValue:-.3},{propertyId:"panY",startValue:0,endValue:-.25}]},rotate_right:{id:"rotate_right",label:"Rotate Right",valueRanges:[{propertyId:"rotation",startValue:0,endValue:8}]},rotate_left:{id:"rotate_left",label:"Rotate Left",valueRanges:[{propertyId:"rotation",startValue:0,endValue:-8}]}};var sL=a(91313);let sF={"9:16":{width:1080,height:1920},"16:9":{width:1920,height:1080},"1:1":{width:1080,height:1080},"4:5":{width:1080,height:1350}};function sO(e){return"number"==typeof e&&Number.isFinite(e)}var sB=a(35717);let sW=(e,t,a)=>Math.max(t,Math.min(a,e)),sU=(e,t)=>({valueToY:(a,r)=>{let n;return(1-((n=t-e)<=0?0:sW((a-e)/n,0,1)))*Math.max(1,r)},yToValue:(a,r)=>{var n;let i;return n=1-sW(a/Math.max(1,r),0,1),(i=t-e)<=0?e:e+sW(n,0,1)*i}}),sK=sU(0,2),sV=sU(-1,1),sH=sU(tM.D,tM.h),sq=sU(-180,180),sY={volume:{id:"volume",label:"Volume",min:0,max:2,defaultValue:1,ownerTypes:["scene","audio"],formatValue:e=>`${Math.round(100*sW(e,0,2))}%`,valueToY:sK.valueToY,yToValue:sK.yToValue,clampValue:e=>sW(e,0,2)},userZoom:{id:"userZoom",label:"Zoom",min:tM.D,max:tM.h,defaultValue:1,ownerTypes:["scene"],formatValue:e=>`${sW(e,tM.D,tM.h).toFixed(2)}x`,valueToY:sH.valueToY,yToValue:sH.yToValue,clampValue:e=>sW(e,tM.D,tM.h)},panX:{id:"panX",label:"Pan X",min:-1,max:1,defaultValue:0,ownerTypes:["scene"],formatValue:e=>sW(e,-1,1).toFixed(2),valueToY:sV.valueToY,yToValue:sV.yToValue,clampValue:e=>sW(e,-1,1)},panY:{id:"panY",label:"Pan Y",min:-1,max:1,defaultValue:0,ownerTypes:["scene"],formatValue:e=>sW(e,-1,1).toFixed(2),valueToY:sV.valueToY,yToValue:sV.yToValue,clampValue:e=>sW(e,-1,1)},rotation:{id:"rotation",label:"Rotation",min:-180,max:180,defaultValue:0,ownerTypes:["scene"],formatValue:e=>`${Math.round(sW(e,-180,180))}deg`,valueToY:sq.valueToY,yToValue:sq.yToValue,clampValue:e=>sW(e,-180,180)}},sG=["volume","userZoom","panX","panY","rotation"],sX=e=>sY[e]??sY.volume,sJ=e=>Object.prototype.hasOwnProperty.call(sY,e),sZ=e=>Math.max(16,e-sr.n_-6),sQ=(e,t)=>`${e}:${t}`,s0=(e,t,a,r,n)=>{let i=Number.isFinite(a)?a:0,s=Number.isFinite(r)&&r>i?r:i+1,o=sW(n,i,s),l=s-i;return{id:e,label:t,min:i,max:s,defaultValue:o,ownerTypes:["scene"],formatValue:e=>sW(e,i,s).toFixed(2),valueToY:(e,t)=>(1-(l>0?(sW(e,i,s)-i)/l:0))*Math.max(1,t),yToValue:(e,t)=>i+(1-sW(e/Math.max(1,t),0,1))*l,clampValue:e=>sW(e,i,s)}};function s1(e){let{blocks:t,customAutomationPropertyDefinitions:a,trackId:r}=e,n=new Set,i=t.filter(e=>Number(e.trackId??1)===r),s=new Set(i.filter(e=>"scene"===e.type&&!e.sceneId.startsWith("__track0")).map(e=>e.sceneId));for(let e of i){let t=e.automation;if("scene"===e.type&&!e.sceneId.startsWith("__track0")){let a=e.scene?.automation;for(let e of["userZoom","panX","panY","rotation","volume"]){let r=t?.[e]??a?.[e];r?.keyframes?.length&&n.add(e)}continue}("voiceover"===e.type||"audio"===e.type)&&t?.volume?.keyframes?.length&&n.add("volume")}for(let[e,t]of Object.entries(a))s.has(t.binding.sceneId)&&n.add(e);return n}function s5(e){return Array.from(new Set((e?.propertyIds?.length?e.propertyIds:e?.propertyId?[e.propertyId]:[]).filter(Boolean)))}function s2(e,t){return{expanded:e?.expanded??!1,propertyId:t,propertyIds:Array.from(new Set([...s5(e),t]))}}function s4(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]}function s3(e){let{transitionType:t,definition:a,minDuration:r,maxDuration:n}=e;return{type:t,duration:Math.max(r,Math.min(n,a.defaultDuration??n)),params:{...a.defaultParams},enabled:!0}}function s8(e,t,a,r=1/0){let n=null,i=1/0;for(let r of e){let e=Math.abs(t-r.seamTime*a);e<i&&(i=e,n=r)}return n&&i<r?n:null}var s6=a(84958),s9=a(39092),s7=a.n(s9),oe=a(94187),ot=a(83451),oa=a(38426),or=a(77031),on=a(9083),oi=a(19391),os=a(60976),oo=a(94088),ol=a(7372),od=a(61285);let oc=({isActive:e,onToggle:t,onDisable:a})=>(0,r.jsxs)("div",{className:"flex shrink-0 items-center gap-px rounded-[7px] bg-black/40 p-0.5 ring-1 ring-inset ring-white/[0.05] shadow-[inset_0_1px_2px_rgba(0,0,0,0.45)]",children:[(0,r.jsx)("button",{onClick:a,className:`flex items-center justify-center rounded-[5px] p-1.5 transition-all duration-150 ${!e?"bg-sky-4
9600/[0.12] text-sky-300 ring-1 ring-inset ring-sky-400/30 shadow-[0_0_10px_-2px_rgba(56,189,248,0.45)]":"text-slate-400 hover:bg-white/[0.07] hover:text-slate-100"}`,title:"Select tool (Esc)","aria-label":"Select tool","aria-pressed":!e,children:(0,r.jsx)(od.A,{size:15})}),(0,r.jsx)("button",{onClick:t,className:`flex items-center justify-center rounded-[5px] p-1.5 transition-all duration-150 ${e?"bg-rose-400/[0.14] text-rose-300 ring-1 ring-inset ring-rose-400/35 shadow-[0_0_10px_-2px_rgba(251,113,133,0.5)]":"text-slate-400 hover:bg-white/[0.07] hover:text-slate-100"}`,title:e?"Splice mode on: click a scene to cut it (Esc to exit)":"Enable splice mode (S)","aria-label":"Toggle splice mode","aria-pressed":e,children:(0,r.jsx)(rq.A,{size:15})})]});function ou({className:e,onSeekToTime:t}){let a=(0,y.zC)(e=>(0,ol.fU)(e.projectTime)),[n,s]=(0,i.useState)(!1),[o,l]=(0,i.useState)(""),d=(0,i.useRef)(null),c=(0,i.useCallback)(()=>{t&&(l((0,ol.fU)(y.zC.getState().projectTime)),s(!0))},[t]);(0,i.useEffect)(()=>{n&&requestAnimationFrame(()=>{d.current?.focus(),d.current?.select()})},[n]);let u=(0,i.useCallback)(()=>{let e=function(e){let t=e.trim();if(!t)return null;let a=!1,r=1,n=t;n.startsWith("+")?(a=!0,n=n.slice(1)):n.startsWith("-")&&(a=!0,r=-1,n=n.slice(1));let i=n.split(":");if(i.length>3||i.some(e=>""===e||!/^\d+(\.\d+)?$/.test(e)))return null;let s=0;for(let e of i)s=60*s+parseFloat(e);return Number.isFinite(s)?{seconds:r*s,relative:a}:null}(o);e&&t&&t((e.relative?y.zC.getState().projectTime:0)+e.seconds),s(!1)},[o,t]);return n?(0,r.jsx)("input",{ref:d,type:"text",value:o,onChange:e=>l(e.target.value),onBlur:u,onKeyDown:e=>{e.stopPropagation(),"Enter"===e.key?(e.preventDefault(),u()):"Escape"===e.key&&(e.preventDefault(),s(!1))},className:`${e} w-[64px] bg-transparent text-sky-200 caret-sky-300 outline-none selection:bg-sky-500/40`,spellCheck:!1,autoComplete:"off","data-testid":"timecode-input"}):(0,r.jsx)("span",{className:`${e} ${t?"cursor-text hover:text-sky-200 transition-colors":""}`,onClick:c,title:t?"Click to type a time (e.g. 1:30, 90, +5)":void 0,"data-testid":"timecode-display",children:a})}function op(e){return 1e-4>Math.abs(e-1/30)?"1f":e<1?`${Math.round(1e3*e)}ms`:Number.isInteger(e)?`${e.toFixed(0)}s`:`${e.toFixed(2)}s`}let om="shrink-0 flex items-center gap-px rounded-[7px] p-0.5 bg-black/40 ring-1 ring-inset ring-white/[0.05] shadow-[inset_0_1px_2px_rgba(0,0,0,0.45)]",oh="rounded-[5px] transition-all duration-150 flex items-center justify-center text-slate-400 hover:text-slate-100 hover:bg-white/[0.07]",of="bg-amber-400/[0.12] text-amber-300 ring-1 ring-inset ring-amber-400/30 shadow-[0_0_10px_-2px_rgba(251,191,36,0.45)] hover:bg-amber-400/[0.16] hover:text-amber-200";function og({isPlaying:e,onTogglePlay:t,duration:a,isRestartModeEnabled:n,onToggleRestartMode:s,loopRegion:o,onClearLoopRegion:l,isMagnetEnabled:d,isGridEnabled:c,gridIntervalSeconds:u,isGridAuto:m=!1,onToggleMagnetMode:h,onToggleGridMode:f,onSetGridIntervalSeconds:g,onSetGridAuto:x,overlapPolicy:b="bump",onSetOverlapPolicy:y,showTrack0:v,onToggleTrack0:w,canUndo:k,canRedo:S,onUndo:j,onRedo:I,isSpliceMode:N,onToggleSpliceMode:C,onDisableSpliceMode:M,waveformMode:_,onCycleWaveformMode:A,zoomLevel:E,onZoomIn:T,onZoomOut:$,onScrollLeft:P,onScrollRight:D,isCollapsed:R,onToggleCollapse:z,compactViewport:L=!1,onSeekToTime:F,onAddMarker:O,onRippleDelete:U,onDuplicateSelected:K,hasSelection:V=!1,hasSceneSelection:q=!1}){let{isDevMode:Y}=(0,nc.u)(),[G,X]=(0,i.useState)(!1),J=(0,i.useRef)(null),Z=(0,i.useRef)(null),Q=(0,i.useRef)(null),ee=(0,i.useRef)(!1),et=(0,i.useRef)(!1),ea=(0,i.useMemo)(()=>m?`Auto \xb7 ${op(u)}`:op(u),[u,m]),er=(0,i.useMemo)(()=>m?`Auto\xb7${op(u)}`:op(u),[u,m]),[en,ei]=(0,i.useState)(null),es=(0,i.useCallback)(()=>{let e=J.current?.getBoundingClientRect();e&&(ei({left:Math.max(8,Math.min(e.left,window.innerWidth-224-8)),bottom:window.innerHeight-e.top+10}),X(!0))},[]),eo=()=>{null!==Q.current&&(window.clearTimeout(Q.current),Q.current=null)},el=()=>{eo()},ed=(0,i.useCallback)(e=>{et.current||(et.current=!0,g(e),c||f(),X(!1))},[g,c,f]);(0,i.useEffect)(()=>{G&&(et.current=!1)},[G]),(0,i.useEffect)(()=>
96{if(!G)return;let e=e=>{let t=e.target;Z.current?.contains(t)||J.current?.contains(t)||X(!1)},t=e=>{"Escape"===e.key&&X(!1)},a=e=>{let t=document.elementFromPoint(e.clientX,e.clientY);if(t){let e=t.closest("[data-grid-interval]");if(e){let t=e.getAttribute("data-grid-interval");if(t){let e=Number(t);isNaN(e)||ed(e)}}}};return document.addEventListener("mousedown",e),document.addEventListener("keydown",t),document.addEventListener("pointerup",a),document.addEventListener("mouseup",a),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",t),document.removeEventListener("pointerup",a),document.removeEventListener("mouseup",a)}},[G,ed]),(0,i.useEffect)(()=>()=>{null!==Q.current&&(window.clearTimeout(Q.current),Q.current=null)},[]);let ec=L?"p-1":"p-1.5",eu=L?14:15;return(0,r.jsxs)("div",{className:`relative flex items-center border-b border-white/[0.06] ${L?"h-10 gap-0.5 overflow-x-auto px-1.5 justify-start timeline-scroll-hidden":"h-11 px-3 justify-between"}`,style:{background:"linear-gradient(180deg, rgba(13,18,32,0.92) 0%, rgba(6,9,17,0.96) 100%)",backdropFilter:"blur(8px)",...L?{touchAction:"pan-x",overscrollBehaviorX:"contain"}:void 0},children:[(0,r.jsx)("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-px",style:{background:"linear-gradient(90deg, transparent 0%, rgba(148,163,184,0.16) 18%, rgba(148,163,184,0.16) 82%, transparent 100%)"},"aria-hidden":"true"}),(0,r.jsxs)("div",{className:`flex items-center ${L?"shrink-0 gap-1 pr-0.5":"min-w-0 gap-2"}`,style:L?{touchAction:"pan-x",overscrollBehaviorX:"contain"}:void 0,children:[(0,r.jsx)("button",{onClick:t,className:`group shrink-0 rounded-[7px] text-slate-100 transition-all duration-150 flex items-center justify-center ring-1 ring-inset ${L?"h-7 w-7":"h-8 w-8"} ${e?"ring-sky-400/40 shadow-[0_0_14px_-2px_rgba(56,189,248,0.5)]":"ring-white/10 hover:ring-sky-400/30 hover:shadow-[0_0_12px_-3px_rgba(56,189,248,0.4)]"}`,style:{background:e?"linear-gradient(180deg, rgba(14,42,68,0.95) 0%, rgba(7,21,38,0.98) 100%)":"linear-gradient(180deg, rgba(40,50,70,0.85) 0%, rgba(17,23,38,0.95) 100%)",boxShadow:"inset 0 1px 0 rgba(255,255,255,0.08)"},title:e?"Pause":"Play",children:e?(0,r.jsx)(n7.A,{size:L?14:15,className:"text-sky-300"}):(0,r.jsx)(ie.A,{size:L?14:15,className:"translate-x-px text-slate-200 transition-colors group-hover:text-sky-200",fill:"currentColor",strokeWidth:0})}),(0,r.jsxs)("div",{className:`shrink-0 flex items-baseline rounded-[7px] bg-black/45 ring-1 ring-inset ring-white/[0.06] shadow-[inset_0_1px_3px_rgba(0,0,0,0.5)] ${L?"px-2 py-[3px]":"px-2.5 py-1"}`,children:[(0,r.jsx)(ou,{className:`font-mono font-semibold tracking-tight text-slate-50 tabular-nums ${L?"text-xs":"text-[13px]"}`,onSeekToTime:F}),(0,r.jsx)("span",{className:"mx-1 select-none text-[10px] text-slate-600",children:"/"}),(0,r.jsx)("span",{className:`font-mono text-slate-500 tabular-nums ${L?"text-[10px]":"text-[11px]"}`,children:(0,ol.fU)(a)})]}),!L&&(0,r.jsxs)("button",{"data-waveform-mode-toggle":!0,onClick:A,className:`relative shrink-0 p-1.5 rounded-[7px] transition-all duration-200 flex items-center ring-1 ring-inset 97 ${"off"===_?"bg-black/30 ring-white/[0.05] hover:bg-white/[0.06]":"neon"===_?"bg-black/40 ring-sky-400/25 shadow-[0_0_12px_-2px_rgba(56,189,248,0.4)]":"ring-fuchsia-400/30 shadow-[0_0_12px_-2px_rgba(217,70,239,0.45)]"}`,style:"inverted"===_?{backgroundImage:"linear-gradient(90deg, rgba(236,72,153,0.55) 0%, rgba(168,85,247,0.55) 40%, rgba(34,211,238,0.55) 60%, rgba(236,72,153,0.55) 100%)",backgroundSize:"200% 200%",animation:"lavaShift 120s ease-in-out infinite"}:void 0,title:"off"===_?"Waveforms: Standard (click for neon)":"neon"===_?"Waveforms: Neon (click for inverted)":"Waveforms: Inverted neon (click to disable)",children:[(0,r.jsx)(oe.A,{size:15,className:"off"===_?"text-slate-400":"neon"===_?"text-transparent bg-clip-text":"text-black drop-shadow-[0_0_3px_rgba(0,0,0,0.75)]",style:"neon"===_?{stroke:"url(#neon-rainbow-gradient)"}:void 0}),"inverted"===_&&(0,r.jsx)(s7(),{id:"d81cb8000659648f",children:"@keyframes lavaShift{0%{background-position:0%50%}50%{background-position:100%50%}
97100%{background-position:0%50%}}"}),"neon"===_&&(0,r.jsx)("svg",{width:"0",height:"0",className:"absolute",children:(0,r.jsx)("defs",{children:(0,r.jsxs)("linearGradient",{id:"neon-rainbow-gradient",x1:"0%",y1:"0%",x2:"100%",y2:"0%",children:[(0,r.jsx)("stop",{offset:"0%",stopColor:"#FF0099"}),(0,r.jsx)("stop",{offset:"25%",stopColor:"#DF19FB"}),(0,r.jsx)("stop",{offset:"50%",stopColor:"#12B8FF"}),(0,r.jsx)("stop",{offset:"75%",stopColor:"#00FF85"}),(0,r.jsx)("stop",{offset:"100%",stopColor:"#FFE62D"})]})})})]}),!L&&(0,r.jsx)("div",{className:"mx-0.5 h-5 w-px shrink-0",style:{background:"linear-gradient(180deg, transparent 0%, rgba(148,163,184,0.18) 50%, transparent 100%)"}}),(0,r.jsx)(oc,{isActive:N,onToggle:C,onDisable:M}),(0,r.jsxs)("div",{className:om,children:[(0,r.jsx)("button",{onClick:s,className:`${ec} ${oh} ${n?of:""}`,title:n?"Restart mode enabled - scenes will loop":"Restart mode disabled - continuous playback",children:(0,r.jsx)(iM.A,{size:eu})}),o&&(0,r.jsx)("button",{onClick:l,className:`${ec} ${oh} ${of}`,title:`Clear loop region (${(0,ol.fU)(o.start)} - ${(0,ol.fU)(o.end)}) - Press Escape`,children:(0,r.jsx)(H.A,{size:eu})})]}),(0,r.jsxs)("div",{className:om,children:[(0,r.jsx)("button",{onClick:h,className:`${ec} ${oh} ${d?"bg-sky-400/[0.12] text-sky-300 ring-1 ring-inset ring-sky-400/30 shadow-[0_0_10px_-2px_rgba(56,189,248,0.45)] hover:bg-sky-400/[0.16] hover:text-sky-200":""}`,title:d?"Magnet snap enabled (snaps to other scenes)":"Magnet snap disabled",children:(0,r.jsx)(ot.A,{size:eu})}),(0,r.jsxs)("div",{className:"relative",children:[(0,r.jsxs)("button",{ref:J,onPointerDown:e=>{0!==e.button||G||(eo(),ee.current=!1,Q.current=window.setTimeout(()=>{ee.current=!0,es()},300))},onPointerUp:el,onPointerLeave:el,onPointerCancel:el,onClick:()=>{if(ee.current){ee.current=!1;return}G?X(!1):f()},onContextMenu:e=>{e.preventDefault(),es(),ee.current=!0},className:`relative ${ec} ${oh} ${c?"bg-teal-400/[0.12] text-teal-300 ring-1 ring-inset ring-teal-400/30 shadow-[0_0_10px_-2px_rgba(45,212,191,0.45)] hover:bg-teal-400/[0.16] hover:text-teal-200":""} ${L&&c?"gap-1":""}`,title:`${c?"Grid snap enabled":"Grid snap disabled"} (${ea}) - Hold to change increment`,children:[(0,r.jsx)(oa.A,{size:eu}),c&&(L?(0,r.jsx)("span",{className:"font-mono text-[8px] font-semibold leading-none text-teal-300/90",children:er}):(0,r.jsx)("span",{className:"absolute -right-1.5 -top-1.5 whitespace-nowrap rounded-[4px] border border-teal-400/40 bg-[#041112] px-1 py-px font-mono text-[8px] font-semibold leading-none text-teal-300 shadow-[0_2px_6px_rgba(0,0,0,0.6)]",children:ea}))]}),G&&en&&"u">typeof document&&(0,p.createPortal)((0,r.jsxs)("div",{ref:Z,className:"fixed z-[9999] w-[224px] select-none rounded-[10px] border border-white/[0.08] p-2 shadow-[0_20px_50px_rgba(0,0,0,0.65),inset_0_1px_0_rgba(255,255,255,0.05)]",style:{left:en.left,bottom:en.bottom,background:"linear-gradient(180deg, rgba(15,20,34,0.98) 0%, rgba(7,10,18,0.99) 100%)",backdropFilter:"blur(12px)"},children:[(0,r.jsxs)("div",{className:"flex items-center justify-between px-1 pb-2",children:[(0,r.jsx)("p",{className:"text-[9px] font-semibold uppercase tracking-[0.14em] text-slate-400",children:"Grid Step"}),(0,r.jsx)("span",{className:"font-mono text-[9px] text-teal-400/80",children:ea})]}),x&&(0,r.jsx)("button",{"data-testid":"grid-auto-toggle",onClick:()=>{x(!m),c||f(),X(!1)},className:`mb-1 w-full rounded-[6px] px-1.5 py-1.5 text-center font-mono text-[11px] transition-all duration-100 ${m?"bg-teal-400/15 text-teal-200 ring-1 ring-inset ring-teal-400/40 shadow-[0_0_10px_-2px_rgba(45,212,191,0.4)]":"text-slate-400 ring-1 ring-inset ring-white/[0.05] hover:bg-white/[0.06] hover:text-slate-200"}`,title:"Grid follows the zoom - snap targets always sit â¥16px apart on screen",children:"Auto (follows zoom)"}),(0,r.jsx)("div",{className:"grid grid-cols-4 gap-1",children:nS.h3.map(e=>{let t=!m&&1e-4>Math.abs(e-u);return(0,r.jsx)("button",{"data-grid-interval":e,onClick:()=>ed(e),className:`rounded-[6px] px-1.5 py-1.5 text-center font-mono text-[11px] tabular-nums transition-all duration-100 ${t?"bg-teal-400/15 text-teal-200 ring-1 ring-inset ring-teal-400/40 shadow-[0_0_10px_-2px_rgba(45,212,191,0.4)]":"text-slate-400 ring-1 ring-inset ring-white/[0.05] hover:bg-white/[0.06] hover:text-slate-200"}`,title:`Snap every ${op(e)}`,children:op(e)},e)})})]}),document.body)]}),y&&(0,r.jsx)("button",{"data-testid":"overlap-policy-toggle",onClick:()=>y("bump"===b?"stay":"bump"),className:`${ec} ${oh} ${"stay"===b?"bg-violet-400/[0.12] text-violet-300 ring-1 ring-inset ring-violet-400/30 shadow-[0_0_10px_-2px_rgba(167,139,250,0.45)] hover:bg-violet-400/[0.16] hover:text-violet-200":""}`,title:"stay"===b?"On overlap: stay on track - dragged clips slide flush against neighbors (click for bump mode)":"On overlap: bump - dragged clips hop to a free adjacent track (click for stay-on-track mode)",children:(0,r.jsx)(or.A,{size:eu})})]}),(0,r.jsxs)("div",{className:om,children:[(0,r.jsx)("button",{onClick:O,className:`${ec} ${oh}`,title:"Add marker at playhead (M)",children:(0,r.jsx)(on.A,{size:eu})}),(0,r.jsx)("button",{onClick:U,disabled:!V,className:`${ec} rounded-[5px] transition-all duration-150 flex items-center justify-center ${V?"text-slate-400 hover:text-rose-300 hover:bg-rose-400/[0.12]":"text-slate-700 cursor-not-allowed"}`,title:V?"Ripple delete selected - remove and close the gap (Shift+Delete)":"Ripple delete - select a clip first (Shift+Delete)",children:(0,r.jsx)(oi.A,{size:eu})}),(0,r.jsx)("button",{onClick:K,disabled:!q,className:`${ec} rounded-[5px] transition-all duration-150 flex items-center justify-center ${q?"text-slate-400 hover:text-slate-100 hover:bg-white/[0.07]":"text-slate-700 cursor-not-allowed"}`,title:q?"Duplicate selected scene (âD)":"Duplicate - select a scene first (âD)",children:(0,r.jsx)(ib.A,{size:eu})})]}),(0,r.jsxs)("div",{className:om,children:[(0,r.jsx)("button",{onClick:j,disabled:!k,className:`${ec} rounded-[5px] transition-all duration-150 flex items-center justify-center ${k?"text-slate-400 hover:text-slate-100 hover:bg-white/[0.07]":"text-slate-700 cursor-not-allowed"}`,title:"Undo (Ctrl+Z)",children:(0,r.jsx)(tt.A,{size:eu})}),(0,r.jsx)("button",{onClick:I,disabled:!S,className:`${ec} rounded-[5px] transition-all duration-150 flex items-center justify-center ${S?"text-slate-400 hover:text-slate-100 hover:bg-white/[0.07]":"text-slate-700 cursor-not-allowed"}`,title:"Redo (Ctrl+Shift+Z)",children:(0,r.jsx)(os.A,{size:eu})})]})]}),Y&&(0,r.jsx)("button",{onClick:w,className:`${ec} ${oh} ring-1 ring-inset ${v?of:"bg-black/30 ring-white/[0.05]"}`,title:v?"Hide Track 0 (background)":"Show Track 0 (background)",children:(0,r.jsx)(nA.A,{size:eu})}),(0,r.jsxs)("div",{className:`flex shrink-0 items-center ${L?"gap-0.5":"ml-1 gap-1"}`,children:[(0,r.jsx)("button",{onClick:z,className:`${ec} ${oh}`,title:R?"Expand timeline":"Collapse timeline",children:R?(0,r.jsx)(oo.A,{size:eu}):(0,r.jsx)(tn.A,{size:eu})}),(0,r.jsxs)("div",{className:`${om} ${L?"gap-px p-px":""}`,children:[!L&&(0,r.jsx)("button",{onClick:P,className:`p-1.5 ${oh}`,title:"Scroll left",children:(0,r.jsx)(B.A,{size:15})}),(0,r.jsx)("button",{onClick:$,className:`${ec} ${oh}`,title:"Zoom out",children:(0,r.jsx)(ny.A,{size:eu})}),!L&&(0,r.jsxs)("span",{className:"w-14 select-none text-center font-mono text-[10px] tabular-nums text-slate-500",children:[Math.round(E),(0,r.jsx)("span",{className:"text-slate-600",children:"px/s"})]}),(0,r.jsx)("button",{onClick:T,className:`${ec} ${oh}`,title:"Zoom in",children:(0,r.jsx)(nv.A,{size:eu})}),!L&&(0,r.jsx)("button",{onClick:D,className:`p-1.5 ${oh}`,title:"Scroll right",children:(0,r.jsx)(W.A,{size:15})})]})]})]})}var ox=a(39832),ob=a(28980),oy=a(47391),ov=a(25182),ow=a(89034),ok=a(36565);function oS({label:e,anchorRef:t}){let[a,n]=(0,i.useState)(null);return((0,i.useEffect)(()=>{let e=t.current;if(!e)return;let a=()=>{let t=e.getBoundingClientRect();n({x:t.left+t.width/2,y:t.top})},r=()=>n(null);return e.addEventListener("mouseenter",a),e.addEventListener("mouseleave",r),()=>{e.removeEventListener("mouseenter",a),e.removeEventListener("mouseleave",r)}},[t]),a)?(0,p.createPortal)((0,r.jsx)("div",{className:"fixed pointer-events-none z-[9999] -translate-x-1/2 whitespace-nowrap rounded-sm border border-slate-700/60 bg-slate-950/95 px-2 py-1 text-[9px] font-medium text-slate-300 shadow-lg backdrop-blur-sm",style:{left:a.x,top:a.y-6,transform:"translate(-50%, -100%)"},children:e}),document.body):null}function oj({children:e,label:t,className:a,onClick:n,style:s,disabled:o=!1}){let l=(0,i.useRef)(null);return(0,r.jsxs)("div",{ref:l,className:"relative",children:[(0,r.jsx)("button",{className:a,onClick:n,title:t,style:s,disabled:o,children:e}),(0,r.jsx)(oS,{label:t,anchorRef:l})]})}function oI({active:e=!1}){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M2.25 9.75L6.75 5.25L11.75 7.75",stroke:"currentColor",strokeWidth:e?1.7:1.5,strokeLinecap:"round",strokeLinejoin:"round",opacity:e?.95:.82}),(0,r.jsx)("rect",{x:"1.25",y:"8.75",width:"2",height:"2",rx:"0.3",transform:"rotate(45 2.25 9.75)",fill:"currentColor",opacity:e?1:.88}),(0,r.jsx)("rect",{x:"5.55",y:"4.05",width:"2.4",height:"2.4",rx:"0.35",transform:"rotate(45 6.75 5.25)",fill:"currentColor",opacity:e?1:.96}),(0,r.jsx)("rect",{x:"10.75",y:"6.75",width:"2",height:"2",rx:"0.3",transform:"rotate(45 11.75 7.75)",fill:"currentColor",opacity:e?1:.88})]})}function oN(e,t,a){return t?"rgb(252 211 77)":a?"rgb(244 114 182)":aj.si[e%aj.si.length]}
97function oC(e,t){return e.match(/\d+/)?.[0]??String(t)}function oM({cursor:e,onStart:t,onDrag:a,onEnd:r,onCancel:n}){let[s,o]=(0,i.useState)(!1),l=(0,i.useRef)(null),d=(0,i.useRef)(null),c=(0,i.useCallback)(()=>{let e=d.current;e&&(document.body.style.cursor=e.cursor,document.body.style.userSelect=e.userSelect,d.current=null)},[]),u=(0,i.useCallback)((e,t)=>{let a=l.current;if(a&&a.pointerId===e.pointerId){e.preventDefault(),e.stopPropagation(),t?r(e.clientX-a.startX,e.clientY-a.startY):n?.();try{a.target.releasePointerCapture?.(a.pointerId)}catch{}l.current=null,c(),o(!1)}},[n,r,c]),p=(0,i.useCallback)(a=>{if(!l.current&&!1!==a.isPrimary&&("mouse"!==a.pointerType||0===a.button)){a.preventDefault(),a.stopPropagation(),t?.(),l.current={pointerId:a.pointerId,startX:a.clientX,startY:a.clientY,target:a.currentTarget},d.current={cursor:document.body.style.cursor,userSelect:document.body.style.userSelect},document.body.style.cursor=e,document.body.style.userSelect="none",o(!0);try{a.currentTarget.setPointerCapture?.(a.pointerId)}catch{}}},[e,t]),m=(0,i.useCallback)(e=>{let t=l.current;t&&t.pointerId===e.pointerId&&(e.preventDefault(),e.stopPropagation(),a(e.clientX-t.startX,e.clientY-t.startY))},[a]);return(0,i.useEffect)(()=>()=>{n?.(),l.current=null,c()},[n,c]),{isResizing:s,pointerHandlers:{onPointerDown:p,onPointerMove:m,onPointerUp:e=>u(e,!0),onPointerCancel:e=>u(e,!1)}}}function o_({trackId:e,getRowHeight:t,getRowCount:a,onChange:n}){let s=(0,i.useRef)(null),o=(0,i.useRef)(0),l=(0,i.useRef)(1),d=(0,i.useCallback)(()=>{null!=s.current&&(cancelAnimationFrame(s.current),s.current=null)},[]),c=(0,i.useCallback)((t,a)=>{let r=o.current-t/l.current;(d(),a)?n(e,r):s.current=requestAnimationFrame(()=>{s.current=null,n(e,r)})},[d,n,e]),{isResizing:u,pointerHandlers:p}=oM({cursor:"ns-resize",onStart:()=>{o.current=t(),l.current=Math.max(1,a())},onDrag:(e,t)=>c(t,!1),onEnd:(e,t)=>c(t,!0),onCancel:d});return(0,r.jsx)("div",{"data-testid":`effects-lane-resize-${e}`,className:`absolute left-0 right-0 top-0 z-40 h-2 -translate-y-1/2 cursor-ns-resize touch-none pointer-coarse:h-6 ${u?"bg-blue-500/25":"hover:bg-blue-400/15"}`,...p,onClick:e=>e.stopPropagation(),title:"Drag to resize the effects lane (drag up to enlarge, down to shrink)",children:(0,r.jsx)("div",{className:`absolute left-0 right-0 h-px transition-colors ${u?"bg-blue-400":"bg-slate-700/50 hover:bg-blue-400/45"}`,style:{top:"50%"}})})}function oA({trackId:e,trackLabel:t,isTrack0:a=!1,isCaption:n=!1,settings:s,onToggleMute:o,onToggleLock:l,onToggleVisible:d,onToggleSolo:c,isEffectivelyMuted:u=!1,onRowContextMenu:p,showLabels:m,height:h,showButtons:f,onHeightChange:g,isFirstTrack:x,canToggleAutomation:b=!1,isAutomationExpanded:y=!1,onToggleAutomation:v,onDeleteTrack:w,showInlineDelete:k=!1,onSelectCaptions:S}){let j="p-1 rounded transition-colors focus:outline-none focus:ring-1 focus:ring-slate-500",I=oN(e,a,n);oC(t,e);let N=(0,i.useRef)(h),C=(0,i.useRef)(null),M=(0,i.useCallback)(()=>{null!=C.current&&(cancelAnimationFrame(C.current),C.current=null)},[]),_=(0,i.useCallback)((t,a)=>{var r;let n=(r=N.current,Math.max(aj.ol,Math.min(aj.Uu,r-t)));(M(),a)?g(e,n):C.current=requestAnimationFrame(()=>{C.current=null,g(e,n)})},[M,g,e]),{isResizing:A,pointerHandlers:E}=oM({cursor:"ns-resize",onStart:()=>{N.current=h},onDrag:(e,t)=>_(t,!1),onEnd:(e,t)=>_(t,!0),onCancel:M});return(0,r.jsxs)("div",{className:`group/track relative flex items-center ${f?"justify-between px-1.5":"justify-center"}`,style:{height:h,flexShrink:0,background:a?"linear-gradient(180deg, rgba(69,49,18,0.28) 0%, rgba(41,30,12,0.3) 100%)":"linear-gradient(180deg, rgba(15,21,35,0.92) 0%, rgba(10,14,24,0.94) 100%)"},onContextMenu:p,children:[(0,r.jsx)("div",{className:"pointer-events-none absolute bottom-[3px] left-0 top-[3px] w-[2.5px] rounded-r-full",style:{background:`linear-gradient(180deg, ${I}e6 0%, ${I}59 100%)`,boxShadow:`0 0 5px ${I}66`},"aria-hidden":"true"}),(0,r.jsx)("div",{"data-testid":`track-height-resize-${e}`,className:`absolute left-0 right-0 top-0 z-40 h-2 cursor-ns-resize touch-none pointer-coarse:h-6 ${x?"":"-translate-y-1/2"} ${A?"bg-blue-500/30":"hover:bg-blue-400/20"}`,...E,title:"Drag to resize track height",children:(0,r.jsx)("div",{className:`absolute left-0 right-0 h-px transition-all ${A?"bg-blue-400":a?"bg-amber-700/30":"bg-slate-700/50 hover:bg-blue-400/50"}
97`,style:{top:x?0:"50%"}})}),w&&k&&(0,r.jsx)("button",{type:"button",className:"absolute left-0.5 z-50 flex h-3.5 w-3.5 items-center justify-center rounded-sm bg-slate-800/85 text-slate-400 opacity-0 shadow-sm transition-opacity pointer-events-none hover:bg-red-500/30 hover:text-red-300 group-hover/track:opacity-100 group-hover/track:pointer-events-auto focus:opacity-100 focus:pointer-events-auto focus:outline-none",style:{top:Math.max(9,Math.round((h-14)/2))},title:"Delete track","aria-label":"Delete track",onMouseDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),w()},children:(0,r.jsx)(H.A,{size:10,strokeWidth:2.5})}),(0,r.jsx)("div",{className:`flex-shrink-0 text-center text-[10px] font-mono font-semibold ${f?"w-7":"w-full"} ${S?"cursor-pointer hover:opacity-100":""}`,style:{color:I,opacity:.7},onClick:S?e=>{e.stopPropagation(),S()}:void 0,onMouseDown:S?e=>e.stopPropagation():void 0,title:S?"Select all captions on this track":void 0,role:S?"button":void 0,children:t}),f&&(0,r.jsxs)("div",{className:"flex items-center gap-0.5",onClick:e=>e.stopPropagation(),children:[b?(0,r.jsx)(oj,{label:y?"Hide keyframe track":"Show keyframe track",className:`inline-flex items-center justify-center rounded-sm px-1 py-0.5 transition-all duration-150 focus:outline-none focus:ring-1 focus:ring-slate-400/40 ${y?"bg-slate-700/45 ring-1 ring-slate-500/30 hover:bg-slate-700/55":"hover:bg-slate-700/40"}`,style:{color:I,opacity:y?1:.82,boxShadow:y?"0 0 6px rgba(15, 23, 42, 0.22)":void 0},onClick:()=>v?.(),children:(0,r.jsx)(oI,{active:y})}):(0,r.jsx)("div",{className:"w-6 flex-shrink-0","aria-hidden":"true"}),(0,r.jsx)(oj,{label:s.muted?"Unmute track":u?"Muted by solo on another track":"Mute track",className:`${j} ${s.muted?"bg-red-500/30 text-red-400 hover:bg-red-500/40":u?"text-red-400/50 hover:bg-slate-700/50 hover:text-red-300/70":"text-slate-400 hover:bg-slate-700/50 hover:text-slate-200"}`,onClick:o,children:s.muted||u?(0,r.jsx)(ob.A,{size:14}):(0,r.jsx)(rG.A,{size:14})}),c&&(0,r.jsx)(oj,{label:s.solo?"Unsolo track":"Solo track (mute all others)",className:`${j} ${s.solo?"bg-emerald-500/25 text-emerald-300 hover:bg-emerald-500/35 shadow-[0_0_8px_-2px_rgba(52,211,153,0.55)] ring-1 ring-inset ring-emerald-400/30":"text-slate-400 hover:bg-slate-700/50 hover:text-slate-200"}`,onClick:c,children:(0,r.jsx)("span",{className:"flex h-3.5 w-3.5 items-center justify-center font-mono text-[10px] font-bold leading-none",children:"S"})}),(0,r.jsx)(oj,{label:s.locked?"Unlock track":"Lock track",className:`${j} ${s.locked?"bg-amber-500/30 text-amber-400 hover:bg-amber-500/40":"text-slate-400 hover:bg-slate-700/50 hover:text-slate-200"}`,onClick:l,children:s.locked?(0,r.jsx)(tu.A,{size:14}):(0,r.jsx)(oy.A,{size:14})}),m&&(0,r.jsx)(oj,{label:s.visible?"Hide track":"Show track",className:`${j} ${!s.visible?"bg-slate-500/30 text-slate-500 hover:bg-slate-500/40":"text-slate-400 hover:bg-slate-700/50 hover:text-slate-200"}`,onClick:d,children:s.visible?(0,r.jsx)(ov.A,{size:14}):(0,r.jsx)(ow.A,{size:14})})]}),(0,r.jsx)("div",{className:`pointer-events-none absolute bottom-0 left-0 right-0 h-px ${a?"bg-amber-700/30":"bg-slate-700/50"}`})]})}function oE({position:e,deleteLabel:t,onDelete:a,onClose:n}){let s=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=e=>{s.current&&!s.current.contains(e.target)&&n()},t=e=>{"Escape"===e.key&&n()};return document.addEventListener("mousedown",e,!0),document.addEventListener("keydown",t,!0),()=>{document.removeEventListener("mousedown",e,!0),document.removeEventListener("keydown",t,!0)}},[n]),(0,p.createPortal)((0,r.jsx)("div",{ref:s,className:"fixed z-[9999] min-w-[140px] py-1 bg-slate-800 border border-slate-600/60 rounded-md shadow-xl",style:{left:e.x,top:e.y},children:(0,r.jsxs)("button",{className:"flex items-center gap-2 w-full px-3 py-1.5 text-xs text-red-400 hover:bg-red-500/15 transition-colors",onClick:()=>{a(),n()},children:[(0,r.jsx)(tr.A,{size:13}),t]})}),document.body)}let oT=(0,i.forwardRef)(({showTrack0:e,visibleTrackCount:t,rulerHeight:a,getTrackHeight:n,getAutomationLaneHeight:s,getTrackEffectsLaneTotalHeight:o,getTrackEffectsLaneRowHeight:l,getTrackEffectsLaneRowCount:d,onEffectsLaneRowHeightChange:c,onClickToSeekZero:u,onHoverSeekZero:p,onDeleteTrack:m,canTrackUseAutomation:h,isTrackAutomationExpanded:f,getTrackAutomationLaneCount:g,onToggleTrackAutomation:x,onAddTrackAutomationLane:b,onRemoveTrackAutomationLane:v,onSelectTrackCaptions:w},k)=>{let S=(0,y.zC)(e=>e.trackControlsPanelWidth),j=(0,y.zC)(e=>e.setTrackControlsPanelWidth),I=(0,y.zC)(e=>e.getTrackSettings),N=(0,y.zC)(e=>e.getTrackMeta);(0,y.zC)(e=>e.trackMeta);let C=(0,y.zC)(e=>e.blocks),M=(0,y.zC)(e=>e.toggleTrackMuted),_=(0,y.zC)(e=>e.toggleTrackLocked),A=(0,y.zC)(e=>e.toggleTrackVisible),E=(0,y.zC)(e=>e.toggleTrackSolo),T=(0,y.zC)(e=>e.setTrackHeight),$=(0,y.zC)(e=>e.trackSettings),[P,D]=(0,i.useState)(null),R=(0,i.useMemo)(()=>{for(let e of $.values())if(e.solo)return!0;return!1},[$]),z=(0,i.useRef)(S),L=(0,i.useRef)(null),F=(0,i.useRef)(null),O=(0,i.useMemo)(()=>{let e=new Map;for(let t of C){let a=Number(t.trackId??1);"caption"!==t.type?e.set(a,!0):e.has(a)||e.set(a,!1)}return e},[C]),B=(0,i.useCallback)(e=>"caption"===N(e).type&&!0!==O.get(e),[N,O]),W=S>=70,U=S>=100,K=S>=100,V=(0,i.useCallback)(()=>{null!=L.current&&(cancelAnimationFrame(L.current),L.current=null),F.current=null},[]),H=(0,i.useCallback)((e,t)=>{let a=z.current+e;if(t){V(),j(a);return}F.current=a,null==L.current&&(L.current=requestAnimationFrame(()=>{L.current=null,null!=F.current&&(j(F.current),F.current=null)}))},[V,j]),{isResizing:q,pointerHandlers:Y}
97=oM({cursor:"ew-resize",onStart:()=>{z.current=S},onDrag:e=>H(e,!1),onEnd:e=>H(e,!0),onCancel:V});(0,i.useEffect)(()=>()=>{V()},[V]);let G=[],X=[];for(let a=0;a<t;a++)X.push(e?a:a+1);let J=[...X].sort((e,t)=>{if(e===t)return 0;if(0===e||0===t)return 0===e?-1:1;let a=N(e),r=N(t),n=B(e),i=B(t),s=n?Math.max(1,a.parentTrackId??e):e,o=i?Math.max(1,r.parentTrackId??t):t;return s!==o?s-o:n!==i?n?1:-1:e-t}),Z=new Map,Q=1;return J.forEach(e=>{0===e||B(e)||(Z.set(e,Q),Q+=1)}),J.forEach(e=>{let t=0===e,a=N(e),r=B(e),n=a.parentTrackId??e,i=Z.get(n)??n,s=Z.get(e)??e,o=t?"BG":r?`C${i}`:`T${s}`;G.push({id:e,label:o,isTrack0:t,isCaption:r})}),(0,r.jsxs)("div",{className:"flex-shrink-0 flex flex-col min-h-0 relative select-none border-r border-white/[0.06]",style:{width:S,background:"linear-gradient(180deg, rgba(11,16,28,0.97) 0%, rgba(7,10,18,0.98) 100%)"},onMouseEnter:p,onMouseMove:p,children:[(0,r.jsx)("div",{className:"flex-shrink-0 flex items-center justify-center border-b border-white/[0.07] text-[9px] font-semibold text-slate-500 uppercase tracking-[0.14em]",style:{height:a,background:"linear-gradient(180deg, rgba(8,11,19,0.85) 0%, rgba(4,6,12,0.92) 100%)"},children:U?"Tracks":""}),(0,r.jsx)("div",{ref:k,className:"flex-1 flex flex-col overflow-y-auto overflow-x-hidden timeline-scroll-hidden",style:{scrollbarWidth:"none",msOverflowStyle:"none"},onClick:u,children:G.map((e,t)=>{let a,u=I(e.id),p=n(e.id),y=h?.(e.id)??!1,k=f?.(e.id)??!1,S=k?Math.max(1,g?.(e.id)??1):0,j=s?.(e.id)??sr.N0,N=oN(e.id,e.isTrack0,e.isCaption),C=oC(e.label,e.id);return(0,r.jsxs)(i.Fragment,{children:[(0,r.jsx)(oA,{trackId:e.id,trackLabel:e.label,isTrack0:e.isTrack0,isCaption:e.isCaption,settings:u,onToggleMute:()=>M(e.id),onToggleLock:()=>_(e.id),onToggleVisible:()=>A(e.id),onToggleSolo:e.isCaption?void 0:()=>E(e.id),isEffectivelyMuted:R&&!e.isCaption&&!u.solo,onRowContextMenu:m&&!e.isTrack0?t=>{t.preventDefault(),D({kind:"track",trackId:e.id,x:t.clientX,y:t.clientY})}:void 0,showLabels:U,showButtons:W,height:p,onHeightChange:T,isFirstTrack:0===t,canToggleAutomation:y,isAutomationExpanded:k,onToggleAutomation:y&&x?()=>x(e.id):void 0,onDeleteTrack:m&&!e.isTrack0?()=>m(e.id):void 0,showInlineDelete:K,onSelectCaptions:e.isCaption&&w?()=>w(e.id):void 0}),k&&Array.from({length:S}).map((t,a)=>(0,r.jsxs)("div",{className:`relative flex items-center border-b border-white/[0.05] ${W?"justify-between px-1.5":"justify-center"}`,style:{height:j+sr.ko,background:"linear-gradient(180deg, rgba(10,14,24,0.85) 0%, rgba(7,10,18,0.9) 100%)"},onContextMenu:t=>{v&&(t.preventDefault(),t.stopPropagation(),D({kind:"automation",trackId:e.id,laneIndex:a,x:t.clientX,y:t.clientY}))},children:[(0,r.jsx)("div",{className:`flex-shrink-0 text-center text-[10px] font-mono font-semibold ${W?"w-7":"w-full"}`,style:{color:N,opacity:.72},children:(0,r.jsx)("span",{className:"leading-none tabular-nums",children:C})}),W&&(0,r.jsxs)("div",{className:"flex items-center gap-0.5",children:[(0,r.jsx)("div",{className:"p-1 rounded-sm text-sky-300/85",children:(0,r.jsx)(oI,{active:!0})}),(0,r.jsx)(oj,{label:"Add keyframe lane",className:"p-1 rounded transition-colors focus:outline-none focus:ring-1 focus:ring-slate-500 text-slate-400 hover:bg-slate-700/50 hover:text-slate-200",onClick:()=>b?.(e.id),children:(0,r.jsx)(a0.A,{size:12})}),(0,r.jsx)(oj,{label:"Minimize keyframe track",className:"p-1 rounded transition-colors focus:outline-none focus:ring-1 focus:ring-slate-500 text-slate-400 hover:bg-slate-700/50 hover:text-slate-200 disabled:opacity-40 disabled:hover:bg-transparent",onClick:()=>x?.(e.id),disabled:!x,children:(0,r.jsx)(ok.A,{size:12})}),U&&(0,r.jsx)("div",{className:"w-6 flex-shrink-0","aria-hidden":"true"})]})]},`automation-track-${e.id}-lane-${a}`)),(a=o?.(e.id)??0)<=0?null:(0,r.jsxs)("div",{className:`relative flex items-center justify-center gap-1 border-b border-white/[0.05] ${W?"px-1.5":""}`,style:{height:a,background:"linear-gradient(180deg, rgba(10,14,24,0.85) 0%, rgba(7,10,18,0.9) 100%)"},children:[(0,r.jsx)("span",{className:"text-[9px] font-mono font-semibold tracking-[0.08em]",style:{color:"#a5b4fc",opacity:.78},children:"FX"}),c&&l&&d&&(0,r.jsx)(o_,{trackId:e.id,getRowHeight:()=>l(e.id),getRowCount:()=>d(e.id),onChange:c})]},`effects-track-${e.id}`)]},e.id)})}),(0,r.jsx)("div",{"data-testid":"track-controls-width-resize",className:`absolute right-0 z-50 h-full w-1.5 translate-x-1/2 cursor-ew-resize touch-none pointer-coarse:w-6 ${q?"bg-blue-500/20":"bg-transparent hover:bg-blue-400/10"}
97`,style:{top:a},...Y,title:"Drag to resize panel width",children:(0,r.jsx)("div",{className:`absolute left-1/2 top-0 h-full -translate-x-1/2 transition-colors ${q?"bg-blue-400 w-0.5":"bg-slate-600 w-px hover:bg-blue-400 hover:w-0.5"}`})}),P&&("track"===P.kind&&m||"automation"===P.kind&&v)&&(0,r.jsx)(oE,{position:{x:P.x,y:P.y},deleteLabel:"track"===P.kind?"Delete track":"Delete keyframe track",onDelete:()=>{"track"===P.kind?m?.(P.trackId):v?.(P.trackId,P.laneIndex)},onClose:()=>D(null)})]})});oT.displayName="TrackControlsPanel";var o$=a(86202),oP=a(89514);function oD({block:e,position:t,onClose:a,onVolumeChange:n,onMuteToggle:s,onFadeSlopeChange:o,onFlattenAudio:l,flattenAudioBlockIds:d=[],onExtractAudio:c,onApplyMotionPreset:u,onAutoReframe:m,autoReframeStatus:h="idle",autoReframeError:f,onDuplicateScene:g,onDeleteScene:b,onRippleDeleteScene:y,selectedSceneCount:v=1,currentVolume:w,currentMuted:k,showExtractAudio:S}){let j=(0,i.useCallback)(e=>Math.max(0,Math.min(200,Math.round(e))),[]),I=(0,i.useRef)(null),N=(0,i.useRef)(null),C=(0,i.useRef)(!1),[M,_]=(0,i.useState)(j(100*w)),[A,E]=(0,i.useState)(String(j(100*w))),T=(0,i.useRef)(j(100*w)||100);(0,i.useEffect)(()=>{let e=j(100*w);_(e),E(String(e)),e>0&&(T.current=e)},[j,w]);let $=(0,i.useCallback)(t=>{let a=j(t);_(a),E(String(a)),n(e.id,a/100)},[e.id,j,n]);(0,i.useEffect)(()=>{let e=e=>{I.current&&!I.current.contains(e.target)&&a()},t=e=>{"Escape"===e.key&&a()};return document.addEventListener("mousedown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",t)}},[a]);let P=(0,i.useRef)({x:t.x,y:t.y});(0,i.useEffect)(()=>{if(I.current){let e=I.current.getBoundingClientRect(),a=window.innerWidth,r=window.innerHeight,n=t.x,i=t.y;t.x+e.width>a&&(n=a-e.width-10),t.y+e.height>r&&(i=r-e.height-10),P.current={x:Math.max(10,n),y:Math.max(10,i)},I.current.style.left=`${P.current.x}px`,I.current.style.top=`${P.current.y}px`}},[t]);let D=(0,i.useCallback)(e=>{$(parseInt(e.target.value,10))},[$]),R=(0,i.useCallback)(()=>{M>0?(T.current=M,$(0)):$(T.current||100)},[$,M]),z=(0,i.useCallback)(()=>{let e=Number(A);Number.isFinite(e)?$(e):E(String(M))},[$,M,A]),L=(0,i.useCallback)(e=>{if("Enter"===e.key){e.preventDefault(),z(),e.currentTarget.blur();return}"Escape"===e.key&&(e.preventDefault(),E(String(M)),e.currentTarget.blur())},[z,M]),F=(0,i.useCallback)(()=>{C.current||(C.current=!0,console.warn("[SceneContextMenu] Extract audio requested for scene:",e.sceneId),c(e.id),a())},[e.id,e.sceneId,c,a]);(0,i.useEffect)(()=>{C.current=!1},[e.id,t.x,t.y]),(0,i.useEffect)(()=>{let e=N.current;if(!e||!S)return;let t=e=>{e.preventDefault(),e.stopPropagation(),"stopImmediatePropagation"in e&&e.stopImmediatePropagation(),F()};return e.addEventListener("pointerdown",t,{capture:!0}),e.addEventListener("mousedown",t,{capture:!0}),e.addEventListener("click",t,{capture:!0}),()=>{e.removeEventListener("pointerdown",t,{capture:!0}),e.removeEventListener("mousedown",t,{capture:!0}),e.removeEventListener("click",t,{capture:!0})}},[F,S]);let O=(0,i.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),F()},[F]),B=(0,i.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),F()},[F]),W=(0,i.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),F()},[F]),U=(0,i.useCallback)(e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),e.stopPropagation(),F())},[F]),K=(0,i.useCallback)(()=>{console.log("[SceneContextMenu] Duplicating scene:",e.sceneId),g?.(e.sceneId),a()}
97,[e.sceneId,g,a]),V=(0,i.useCallback)(()=>{"scene"===e.type&&(b?.(e.sceneId),a())},[e.type,e.sceneId,b,a]),q=(0,i.useCallback)(()=>{"scene"===e.type&&(y?.(e.sceneId),a())},[e.type,e.sceneId,y,a]),Y=(0,i.useCallback)(t=>{"scene"===e.type&&(u?.(e,t),a())},[e,u,a]),G=(0,i.useCallback)(()=>{"scene"===e.type&&"running"!==h&&m?.(e)},[h,e,m]),X="scene"===e.type&&v>1,J="scene"===e.type&&!e.sceneId.startsWith("__track0"),Z=(e.audioFadeInDuration??0)>0||(e.audioFadeOutDuration??0)>0,Q=e.audioFadeInSlope??e.audioFadeOutSlope??.5,ee=[{label:"Gentle",slope:.2,hint:"Eases in late - long soft tail"},{label:"Normal",slope:.5,hint:"Classic smooth S-curve (default)"},{label:"Punchy",slope:.8,hint:"Jumps up fast - snappy edges"}],et=ee.reduce((e,t)=>Math.abs(t.slope-Q)<Math.abs(e-Q)?t.slope:e,ee[0].slope),ea=!!m&&"scene"===e.type&&!e.sceneId.startsWith("__track0")&&e.scene?.media?.type==="video",er=M/100,en=er>0?20*Math.log10(er):-1/0,ei=er>0?`${en>=0?"+":""}${en.toFixed(1)} dB`:"-â dB",es=M>100?"text-amber-400":0===M?"text-red-400":"text-slate-300";return"u"<typeof document?null:(0,p.createPortal)((0,r.jsxs)("div",{ref:I,className:"fixed z-[9999] min-w-[200px] bg-slate-800 border border-slate-600 rounded-lg shadow-2xl overflow-hidden",style:{left:t.x,top:t.y},onClick:e=>e.stopPropagation(),onContextMenu:e=>e.preventDefault(),children:[(0,r.jsxs)("div",{className:"flex items-center justify-between px-3 py-2 bg-slate-900 border-b border-slate-700",children:[(0,r.jsx)("span",{className:"text-xs font-medium text-slate-300 truncate max-w-[140px]",children:e.scene?.text||`Scene ${e.sceneId.substring(0,8)}`}),(0,r.jsx)("button",{onClick:a,className:"p-0.5 rounded hover:bg-slate-700 text-slate-400 hover:text-slate-200 transition-colors",children:(0,r.jsx)(H.A,{size:14})})]}),(0,r.jsxs)("div",{className:"px-3 py-3 border-b border-slate-700",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between mb-3",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("button",{onClick:R,className:`p-1.5 rounded transition-colors ${0===M?"bg-red-500/20 text-red-400 hover:bg-red-500/30":"bg-slate-700/50 text-slate-300 hover:bg-slate-700"}`,title:0===M?"Unmute":"Mute",children:0===M?(0,r.jsx)(ob.A,{size:16}):(0,r.jsx)(rG.A,{size:16})}),(0,r.jsx)("span",{className:"text-xs text-slate-400",children:"Volume"})]}),(0,r.jsxs)("div",{className:"text-right w-[82px]",children:[(0,r.jsxs)("div",{className:"flex items-center justify-end gap-1",children:[(0,r.jsx)("input",{type:"text",inputMode:"numeric",value:A,onChange:e=>{E(e.target.value.replace(/[^0-9]/g,"").slice(0,3))},onBlur:z,onKeyDown:L,className:`w-[52px] rounded border border-slate-600 bg-slate-900 px-1.5 py-0.5 text-right text-sm font-mono font-medium focus:border-blue-500 focus:outline-none ${es}`,"aria-label":"Scene volume percentage"}),(0,r.jsx)("span",{className:"text-xs text-slate-400",children:"%"})]}),(0,r.jsx)("div",{className:"text-xs font-mono text-slate-500",children:ei})]})]}),(0,r.jsxs)("div",{className:"relative h-4",children:[(0,r.jsx)("div",{className:"absolute left-0 right-0 top-1/2 -translate-y-1/2 h-1.5 rounded-full bg-slate-700"}),(0,r.jsx)("div",{className:"absolute left-0 top-1/2 -translate-y-1/2 h-1.5 rounded-l-full pointer-events-none",style:{width:`${M/200*100}%`,backgroundColor:M>100?"#f59e0b":"#3b82f6",borderRadius:M>=200?"9999px":"9999px 0 0 9999px"}}),(0,r.jsx)("div",{className:"absolute w-0.5 h-3 bg-slate-500 top-1/2 -translate-y-1/2",style:{left:"50%"},title:"100% (normal volume)"}),(0,r.jsx)("input",{type:"range",min:"0",max:"200",value:M,onChange:D,className:"absolute inset-0 w-full h-full appearance-none bg-transparent cursor-pointer z-10\n [&::-webkit-slider-runnable-track]:bg-transparent\n [&::-webkit-slider-runnable-track]:h-full\n [&::-webkit-slider-thumb]:appearance-none\n [&::-webkit-slider-thumb]:w-4\n [&::-webkit-slider-thumb]:h-4\n [&::-webkit-slider-thumb]:rounded-full\n [&::-webkit-slider-thumb]:bg-white\n [&::-webkit-slider-thumb]:shadow-md\n [&::-webkit-slider-thumb]:cursor-grab\n [&::-webkit-slider-thumb]:active:cursor-grabbing\n [&::-webkit-slider-thumb]:hover:bg-blue-100\n [&::-webkit-slider-thumb]:mt-[2px]\n [&::-moz-range-track]:bg-transparent\n [&::-moz-range-track]:h-full\n [&::-moz-range-thumb]:appearance-none\n [&::-moz-range-thumb]:w-4\n [&::-moz-range-thumb]:h-4\n [&::-moz-range-thumb]:rounded-full\n [&::-moz-range-thumb]:bg-white\n [&::-moz-range-thumb]:border-0\n [&::-moz-range-thumb]:shadow-md\n [&::-moz-range-thumb]:cursor-grab"})]}),(0,r.jsxs)("div",{className:"flex justify-between text-[10px] text-slate-500 mt-1",children:[(0,r.jsx)("span",{children:"0%"}),(0,r.jsx)("span",{children:"100%"}),(0,r.jsx)("span",{children:"200%"})]})]}),!!o&&Z&&(0,r.jsxs)("div",{className:"px-3 py-3 border-b border-slate-700","data-testid":"fade-curve-section",children:[(0,r.jsxs)("div",{className:"mb-2",children:[(0,r.jsx)("div",{className:"text-xs text-slate-300 font-medium",children:"Fade curve"}),(0,r.jsx)("div",{className:"text-[11px] text-slate-500",children:"Shape of this block's fade in/out - preview and export match."})]}),(0,r.jsx)("div",{className:"grid grid-cols-3 gap-1.5",children:ee.map(t=>{let a=t.slope===et;return(0,r.jsx)("button",{type:"button","data-testid":`fade-curve-${t.label.toLowerCase()}`,onClick:()=>o?.(e.id,t.slope),title:t.hint,className:`rounded border px-2 py-1.5 text-center text-xs transition-colors ${a?"border-sky-500/60 bg-sky-500/15 text-sky-100":"border-slate-600/70 bg-slate-900/70 text-slate-200 hover:border-sky-500/50 hover:bg-slate-700/60 hover:text-sky-100"}`,children:t.label},t.label)})})]}),J&&(0,r.jsxs)("div",{className:"px-3 py-3 border-b border-slate-700",children:[(0,r.jsxs)("div",{className:"mb-2",children:[(0,r.jsx)("div",{className:"text-xs text-slate-300 font-medium",children:"Motion Presets"}),(0,r.jsx)("div",{className:"text-[11px] text-slate-500",children:"Writes keyframes across the current clip."})]}),(0,r.jsx)("div",{className:"grid grid-cols-2 gap-1.5",children:sR.map(e=>{let t=sz[e];return(0,r.jsx)("button",{type:"button",onClick:()=>Y(t.id),className:"rounded border border-slate-600/70 bg-slate-900/70 px-2 py-1.5 text-left text-xs text-slate-200 transition-colors hover:border-sky-500/50 hover:bg-slate-700/60 hover:text-sky-100",children:t.label},t.id)})})]}),ea&&(0,r.jsxs)("div",{className:"border-b border-slate-700",children:[(0,r.jsxs)("button",{type:"button","data-testid":"auto-reframe-scene",onClick:G,disabled:"running"===h,className:`w-full px-3 py-2.5 flex items-center gap-2 text-left text-sm transition-colors ${"running"===h?"text-slate-500 cursor-wait":"text-slate-300 hover:bg-slate-700/50"}`,title:"Detect the subject (face) and keyframe zoom/pan so the crop follows them",children:["running"===h?(0,r.jsx)(x.A,{size:16,className:"text-sky-400 animate-spin"}):(0,r.jsx)(o$.A,{size:16,className:"text-sky-400"}),(0,r.jsx)("span",{children:"running"===h?"Analyzing subjectâ¦":"AI Reframe (follow subject)"})]}),"error"===h&&f&&(0,r.jsx)("div",{className:"px-3 pb-2 text-[11px] text-red-400",children:f})]}),"scene"===e.type&&g&&(0,r.jsxs)("button",{onClick:K,className:"w-full px-3 py-2.5 flex items-center gap-2 text-left text-sm text-slate-300 hover:bg-slate-700/50 transition-colors border-b border-slate-700",children:[(0,r.jsx)(ib.A,{size:16,className:"text-slate-400"}),(0,r.jsx)("span",{children:X?"Duplicate scenes":"Duplicate Scene"})]}),l&&d.length>=2&&(0,r.jsxs)("button",{type:"button","data-testid":"flatten-audio-blocks",onClick:()=>{l(d),a()},className:"w-full px-3 py-2.5 flex items-center gap-2 text-left text-sm text-slate-300 hover:bg-slate-700/50 transition-colors border-b border-slate-700",title:"Render the selected audio blocks (volume, fades, automation baked in) into a single clip",children:[(0,r.jsx)(oP.A,{size:16,className:"text-slate-400"}),(0,r.jsxs)("span",{children:["Flatten ",d.length," audio blocks"]})]}),S&&(0,r.jsxs)("button",{ref:N,type:"button","data-testid":"extract-audio-to-track",onPointerDownCapture:B,onMouseDown:O,onClick:W,onKeyDown:U,className:"relative z-[10001] pointer-events-auto w-full px-3 py-2.5 flex items-center gap-2 text-left text-sm text-slate-300 hover:bg-slate-700/50 transition-colors",children:[(0,r.jsx)(rq.A,{size:16,className:"text-slate-400"}),(0,r.jsx)("span",{children:"Extract Audio to Track"})]}),"scene"===e.type&&(0,r.jsxs)("button",{onClick:V,className:"w-full px-3 py-2.5 flex items-center gap-2 text-left text-sm text-red-300 hover:bg-red-500/15 transition-colors border-t border-slate-700",children:[(0,r.jsx)(tr.A,{size:16,className:"text-red-400"}),(0,r.jsx)("span",{children:X?"Delete scenes":"Delete Scene"})]}),"scene"===e.type&&y&&(0,r.jsxs)("button",{onClick:q,className:"w-full px-3 py-2.5 flex items-center gap-2 text-left text-sm text-red-300 hover:bg-red-500/15 transition-colors border-t border-slate-700/60",title:"Delete and shift everything after it left to close the gap (Shift+Delete)",children:[(0,r.jsx)(oi.A,{size:16,className:"text-red-400"}),(0,r.jsx)("span",{children:X?"Ripple delete scenes":"Ripple Delete"}),(0,r.jsx)("span",{className:"ml-auto text-[10px] font-mono text-slate-500",children:"â§â«"})]})]}),document.body)}function oR({visibleRulerTicks:e,zoomLevel:t,rulerHeight:a,onMouseDown:n,markers:i,onMarkerMouseDown:s,onMarkerDoubleClick:o,onMarkerContextMenu:l,children:d}){return(0,r.jsxs)("div",{className:"absolute top-0 left-0 flex w-full cursor-text select-none items-end border-b border-white/[0.07] text-xs","data-testid":"master-timeline-ruler",style:{height:a,background:"linear-gradient(180deg, rgba(8,11,19,0.85) 0%, rgba(4,6,12,0.92) 100%)"},onMouseDown:n,children:[e.map(({time:e,isMajor:a})=>{let n=e*t;return a?(0,r.jsxs)("div",{className:"pointer-events-none absolute flex h-full flex-col justify-end",style:{left:n},children:[(0,r.jsx)("div",{className:"absolute top-0 h-full w-px",style:{background:"linear-gradient(180deg, rgba(148,163,184,0.12) 0%, rgba(148,163,184,0.45) 100%)"}}),(0,r.jsx)("span",{className:"pb-0.5 pl-1.5 font-mono text-[9px] font-medium tracking-tight text-slate-400 tabular-nums",children:(0,ol.eg)(e)})]},`major-${e}`):(0,r.jsx)("div",{className:"pointer-events-none absolute bottom-0 w-px bg-slate-500/25",style:{left:n,height:"30%"}},`minor-${e}`)}),(i??[]).map(e=>{let a=e.color??"#38bdf8",n=e.time*t;return(0,r.jsxs)("div",{"data-testid":`timeline-marker-${e.id}`,className:"group absolute top-0 z-20 h-full cursor-pointer",style:{left:n-5.5,width:11},title:e.label?e.label:(0,ol.eg)(e.time),onMouseDown:t=>{t.stopPropagation(),s?.(e,t)},onDoubleClick:t=>{t.stopPropagation(),o?.(e,t)},onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),l?.(e,t)},children:[(0,r.jsx)("div",{className:"pointer-events-none absolute top-[9px] bottom-0 left-1/2 w-px -translate-x-1/2 opacity-70 transition-opacity group-hover:opacity-100",style:{background:`linear-gradient(180deg, ${a} 0%, transparent 100%)`}}),(0,r.jsxs)("svg",{className:"pointer-events-none absolute top-[1px] left-1/2 -translate-x-1/2 transition-transform duration-100 group-hover:scale-110",width:"11",height:"11",viewBox:"0 0 11 11",style:{filter:`drop-shadow(0 0 4px ${a}66) drop-shadow(0 1px 2px rgba(0,0,0,0.6))`},children:[(0,r.jsx)("path",{d:"M1.5 0.5 H9.5 Q10.5 0.5 10.5 1.5 V5.5 Q10.5 6.5 9.5 6.5 H7 L5.5 10 L4 6.5 H1.5 Q0.5 6.5 0.5 5.5 V1.5 Q0.5 0.5 1.5 0.5 Z",fill:a,fillOpacity:"0.92",stroke:"rgba(2,6,12,0.85)",strokeWidth:"0.75"}),(0,r.jsx)("path",{d:"M2 1.4 H9 Q9.6 1.4 9.6 2 V2.6 H1.4 V2 Q1.4 1.4 2 1.4 Z",fill:"rgba(255,255,255,0.35)"})]}),e.label?(0,r.jsx)("div",{className:"pointer-events-none absolute top-[12px] left-1/2 hidden -translate-x-1/2 whitespace-nowrap rounded border border-white/10 bg-slate-950/95 px-1 py-[1px] font-mono text-[8px] leading-none text-slate-200 shadow-[0_2px_8px_rgba(0,0,0,0.5)] group-hover:block",children:e.label}):null]},e.id)}),d]})}function oz({selectionBox:e}){return e?.active?(0,r.jsx)("div",{className:"absolute border border-blue-400/60 bg-blue-500/10 pointer-events-none z-20",style:{left:Math.min(e.startX,e.currentX),top:Math.min(e.startY,e.currentY),width:Math.abs(e.currentX-e.startX),height:Math.abs(e.currentY-e.startY)}}):null}function oL({preview:e,zoomLevel:t,getTrackLayout:a}){if(!e)return null;let n=a(e.trackId);return(0,r.jsx)("div",{className:"absolute rounded-sm pointer-events-none",style:{left:e.start*t,top:n.top+2,width:e.duration*t,height:n.height-4,backgroundColor:"rgba(96, 165, 250, 0.3)",zIndex:50}})}function oF({preview:e,zoomLevel:t,getTrackLayout:a}){if(!e)return null;let n=a(e.trackId),i="caption"===e.kind,s="audio"===e.kind,o=Math.max(e.duration*t,i?30:18);return(0,r.jsx)("div",{className:"absolute rounded-sm pointer-events-none",style:{left:e.start*t,top:n.top+(i?4:2),width:o,height:Math.max(8,n.height-(i?8:4)),zIndex:50,...i?{background:"linear-gradient(180deg, rgba(92, 23, 53, 0.92) 0%, rgba(74, 19, 44, 0.92) 100%)",border:"1px solid rgba(244, 114, 182, 0.78)",boxShadow:"0 8px 22px rgba(76, 5, 25, 0.24), 0 0 0 1px rgba(244, 114, 182, 0.18)"}:s?{background:"linear-gradient(180deg, rgba(30, 64, 175, 0.4) 0%, rgba(30, 41, 59,
970.94) 100%)",border:"1px solid rgba(96, 165, 250, 0.68)",borderLeft:"2px solid rgba(2, 6, 23, 0.9)",boxShadow:"0 8px 22px rgba(15, 23, 42, 0.24)"}:{background:"linear-gradient(180deg, rgba(30, 41, 59, 0.92) 0%, rgba(15, 23, 42, 0.95) 100%)",border:"1px solid rgba(148, 163, 184, 0.52)",borderLeft:"2px solid rgba(2, 6, 23, 0.9)",boxShadow:"0 8px 22px rgba(15, 23, 42, 0.24)"}}})}function oO({loopRegion:e,zoomLevel:t}){return e?(0,r.jsxs)("div",{className:"absolute top-0 h-full pointer-events-none z-10",style:{left:e.start*t,width:(e.end-e.start)*t},children:[(0,r.jsx)("div",{className:"absolute inset-0 bg-amber-400/5"}),(0,r.jsx)("div",{className:"absolute left-0 top-0 w-px h-full bg-amber-400/20"}),(0,r.jsx)("div",{className:"absolute right-0 top-0 w-px h-full bg-amber-400/20"})]}):null}function oB({captionBlock:e,anchorBlock:t,audioSource:a,persistedAudioAnalysis:n,onPersistAudioAnalysisArtifact:s,zoomLevel:o,trackTop:l,trackHeight:d,guideExtendToY:c=null,waveformMode:u,onCaptionBlockChange:p,onCaptionBlockCommit:m}){let h=(0,y.zC)(e=>e.projectTime),[f,g]=(0,i.useState)(null),x=(0,i.useRef)(null),b=Math.max(t.duration*o,72),v=Math.max(d+14,64),w=Math.max(l-8,0),k=Math.max(t.duration,.001),S=Math.max(0,e.start-t.start),j=Math.max(e.duration/k*100,2),I=Math.max(0,Math.min(100,S/k*100)),N=Math.max(0,Math.min(100-I,j)),C=Math.max(0,Math.min(100,(h-t.start)/k*100)),M=e.captionWords??[],_=M.length>0,A=null!=c?Math.max(0,c-w-v):0,E=_&&A>4,T=(0,iR.c)(e.captionStyle?.fontFamily),$=Math.max(4,Math.min(12,Math.round(6*Math.sqrt(o/20)))),P=$+6,D=Math.min(3,Math.max(1,Math.floor(v/(P+4)))),R=v/(D+1),z=Math.max(0,Math.min(k,h-t.start)),L=(0,i.useCallback)((t,a)=>{if(a.preventDefault(),a.stopPropagation(),!_)return;let r=(0,aS.zr)(e);x.current=r,g({wordIndex:t,startClientX:a.clientX,initialCaptionBlock:r})},[e,_]);return(0,i.useEffect)(()=>{if(!f)return;let e=e=>{let a=(e.clientX-f.startClientX)/o,r=function(e,t,a,r,n){let i=e.captionWords?.map(e=>({...e}))||[],s=i[t];if(!s)return(0,aS.zr)(e);let o=e.start,l=Math.max(s.end-s.start,.04),d=Math.min(.72,Math.max(.04,.16+.028*Array.from(s.word.replace(/\s+/g,"")).length)),c=(0===t||t===i.length-1)&&l>.9&&l>2.25*d?d:l,u=o+s.start+a,p=Math.max(r,r+n-c),m=Math.min(Math.max(u,r),p)-o;i[t]={...s,start:m,end:m+c};let h=1/0,f=-1/0;
97for(let e of i)h=Math.min(h,e.start),f=Math.max(f,e.end);if(!Number.isFinite(h)||!Number.isFinite(f))return(0,aS.zr)(e);let g=Math.max(f-h,.04),x=i.map(e=>({...e,start:e.start-h,end:e.end-h})),b=function(e,t){if(!e||0===e.length||0===t.length)return e;let a=t.length-1;return e.map(e=>{let r=Math.max(0,Math.min(e.wordStartIndex,a)),n=Math.max(r,Math.min(e.wordEndIndex,a)),i=1/0,s=-1/0;for(let e=r;e<=n;e+=1)i=Math.min(i,t[e].start),s=Math.max(s,t[e].end);return Number.isFinite(i)&&Number.isFinite(s)?{...e,start:i,end:s}:{...e}})}(e.captionCues,x);return{...(0,aS.zr)(e),start:o+h,duration:g,inOffset:0,outOffset:g,fullDuration:g,captionWords:x,captionCues:b}}(f.initialCaptionBlock,f.wordIndex,a,t.start,k);x.current=r,p(r)},a=()=>{let e=x.current||(0,aS.zr)(f.initialCaptionBlock);m(f.initialCaptionBlock,e),x.current=null,g(null)};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",a),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",a)}},[p,m,t.start,k,f,o]),(0,r.jsxs)("div",{"data-caption-timing-overlay":!0,className:"absolute",style:{left:t.start*o,top:w,width:b,height:v,zIndex:70},onMouseDown:e=>e.stopPropagation(),children:[(0,r.jsxs)("div",{className:"absolute inset-0 overflow-hidden rounded-md border border-pink-300/60 bg-slate-950/88 shadow-[0_18px_40px_rgba(15,23,42,0.55)]",children:[a&&(0,r.jsx)(eo,{audioUrl:a.url,storageKey:a.storageKey,assetRef:a.assetRef,persistedAudioAnalysis:n,analysisSource:a.analysisSource,onPersistAudioAnalysisArtifact:s,totalDuration:k,audioStartTime:a.startInScene,audioDuration:a.duration,currentTime:z,liveTimelineStart:t.start,liveTimelineDuration:k,liveTimeOffset:0,color:"#f472b6",inOffset:a.inOffset,waveformMode:u,volume:a.volume}),(0,r.jsx)("div",{className:"absolute inset-y-[3px] rounded-md border border-pink-300/90 bg-pink-500/10 shadow-[0_0_0_1px_rgba(244,114,182,0.2)]",style:{left:`${I}
97%`,width:`${N}%`}}),(0,r.jsx)("div",{className:"absolute top-0 bottom-0 w-px bg-sky-300/90 shadow-[0_0_8px_rgba(125,211,252,0.65)]",style:{left:`${C}%`}}),_?M.map((e,t)=>{let a=(S+e.start)/k*100,n=Math.max((e.end-e.start)/k*100,2.4),i=f?.wordIndex===t,s=t%D;return(0,r.jsxs)("div",{className:"absolute top-0 bottom-0",style:{left:`${a}%`,width:`${n}%`},children:[(0,r.jsx)("div",{className:`absolute top-0 bottom-0 left-0 w-px ${i?"bg-pink-300/90 shadow-[0_0_6px_rgba(244,114,182,0.6)]":"bg-pink-100/25"}`}),(0,r.jsx)("button",{type:"button",className:`absolute left-0 whitespace-nowrap rounded border px-0.5 font-bold leading-tight transition-colors ${i?"cursor-grabbing":"cursor-grab"} border-white/20 bg-transparent text-white hover:border-white/40 hover:bg-white/5`,style:{fontFamily:T,fontSize:`${$}px`,top:`${R*(s+1)-P/2}px`,paddingTop:"1px",paddingBottom:"1px",textShadow:"-1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000"},onMouseDown:e=>L(t,e),title:`Drag "${e.word}" to retime it`,children:e.word})]},`${e.word}-${t}`)}):(0,r.jsx)("div",{className:"absolute inset-0 flex items-center justify-center px-4 text-center text-[10px] text-slate-300/85",children:"This caption has no word timings to drag. Generate word-level timings first, then reopen timing edit."})]}),E&&(0,r.jsx)("div",{className:"pointer-events-none absolute left-0 right-0",style:{to
97p:v,height:A},"aria-hidden":"true",children:M.map((e,t)=>{let a=(S+e.start)/k*100;if(a<0||a>100)return null;let n=Math.max((e.end-e.start)/k*100,.5),i=f?.wordIndex===t;return(0,r.jsxs)("div",{className:"absolute top-0 bottom-0",style:{left:`${a}%`,width:`${n}%`},children:[i&&(0,r.jsx)("div",{className:"absolute inset-0 rounded-b-sm border-x border-pink-300/50 bg-pink-400/10"}),(0,r.jsx)("div",{className:`absolute top-0 bottom-0 left-0 w-px ${i?"bg-pink-300/90 shadow-[0_0_6px_rgba(244,114,182,0.6)]":"bg-pink-200/20"}`})]},`guide-${e.word}-${t}`)})})]})}function oW({nleSceneId:e,blockType:t,small:a}){let n=e=>{e.stopPropagation()},i=a=>{window.dispatchEvent(new CustomEvent(a,{detail:{nleSceneId:e,blockType:t}}))},s=a?"h-4 w-4":"h-5 w-5",o=a?9:11;return(0,r.jsxs)("div",{className:"pointer-events-none absolute inset-0 z-40 opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:[(0,r.jsx)("button",{type:"button",title:"Cancel","aria-label":"Cancel generation",onMouseDown:n,onPointerDown:n,onClick:e=>{n(e),i("faceless:cancel-scene-by-nle")},className:`pointer-events-auto absolute left-1 top-1 flex ${s} items-center justify-center rounded-full bg-black/55 text-white/85 ring-1 ring-white/15 backdrop-blur-sm transition-colors hover:bg-red-500/85 hover:text-white`,children:(0,r.jsx)(H.A,{size:o,strokeWidth:2.75})}),(0,r.jsx)("button",{type:"button",title:"Regenerate","aria-label":"Regenerate",onMouseDown:n,onPointerDown:n,onClick:e=>{n(e),i("faceless:regenerate-scene-by-nle")},className:`pointer-events-auto absolute right-1 top-1 flex ${s} items-center justify-center rounded-full bg-black/55 text-[#e8dcc8] ring-1 ring-[#c8a87c]/40 backdrop-blur-sm transition-colors hover:bg-[#c8a87c] hover:text-[#1a1816]`,children:(0,r.jsx)(to.A,{size:o,strokeWidth:2.75})})]})}function oU({visible:e}){return(0,r.jsx)("svg",{width:"9",height:"9",viewBox:"0 0 10 10",fill:"none","aria-hidden":"true",className:`shrink-0 ${e?"opacity-100":"opacity-0"}`,children:(0,r.jsx)("path",{d:"M1.5 5.5L4 8L8.5 2.5",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round"})})}let oK="flex w-full items-center gap-1.5 px-2 py-[4.5px] text-left text-[10.5px] leading-none transition-colors hover:bg-white/[0.07]";function oV({triggerLabel:e,currentPropertyId:t,activeSentinelLabel:a=null,disabled:n=!1,propertyOptions:s,onSelectProperty:o,onPickEffectParameter:l,onPickTransitionParameter:d,motionPresetOptions:c=[],onApplyMotionPreset:u}){let m=(0,i.useRef)(null),h=(0,i.useRef)(null),[f,g]=(0,i.useState)(null),x=null!==f,b=(0,i.useCallback)(()=>g(null),[]),y=(0,i.useCallback)(()=>{n||g(e=>{if(e)return null;let t=m.current?.getBoundingClientRect();return t?{left:t.left,top:t.bottom+4,triggerTop:t.top}:null})},[n]);(0,i.useLayoutEffect)(()=>{if(!x||!h.current||!f)return;let e=h.current.offsetWidth,t=h.current.offsetHeight,a=window.innerWidth,r=window.innerHeight,n=f.top;if(n+t>r-8){let e=f.triggerTop-4-t;n=e>=8?e:Math.max(8,r-8-t)}let i=f.left;i+e>a-8&&(i=Math.max(8,a-8-e)),(n!==f.top||i!==f.left)&&g({...f,top:n,left:i})},[x,f]),(0,i.useEffect)(()=>{if(!x)return;let e=e=>{let t=e.target;!t||h.current?.contains(t)||m.current?.contains(t)||b()},t=e=>{"Escape"===e.key&&b()},a=e=>{e.target instanceof Node&&h.current?.contains(e.target)||b()};return document.addEventListener("mousedown",e,!0),document.addEventListener("touchstart",e,!0),document.addEventListener("keydown",t,!0),window.addEventListener("scroll",a,!0),window.addEventListener("resize",a),()=>{document.removeEventListener("mousedown",e,!0),document.removeEventListener("touchstart",e,!0),document.removeEventListener("keydown",t,!0),window.removeEventListener("scroll",a,!0),window.removeEventListener("resize",a)}},[b,x]);let v=(0,i.useCallback)(e=>{b(),e()},[b]),w=!!(l||d),k=c.length>0&&!!u;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{ref:m,type:"button","data-lane-property-trigger":!0,className:`inline-flex h-full min-w-0 cursor-pointer items-center gap-0.5 rounded-[3px] px-1 text-[9px] font-semibold tracking-wide outline-none transition-colors disabled:cursor-default disabled:opacity-40 ${x?"text-[#e8dcc8]":"text-slate-300 hover:text-[#e8dcc8]"}
97`,onClick:y,disabled:n,title:"Choose what this keyframe lane controls",children:[(0,r.jsx)("span",{className:"max-w-[180px] truncate",children:e}),(0,r.jsx)("svg",{width:"7",height:"7",viewBox:"0 0 8 8",fill:"none","aria-hidden":"true",className:`shrink-0 text-current opacity-70 transition-transform ${x?"rotate-180":""}`,children:(0,r.jsx)("path",{d:"M1.5 3L4 5.5L6.5 3",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})]}),x&&(0,p.createPortal)((0,r.jsxs)("div",{ref:h,"data-lane-property-menu":!0,role:"menu",className:"custom-scrollbar fixed z-[9999] max-h-[min(460px,72vh)] min-w-[176px] overflow-y-auto rounded-lg border border-slate-700/70 bg-[#0e1524]/[0.98] py-1 text-slate-200 shadow-[0_16px_40px_rgba(0,0,0,0.55)] backdrop-blur-sm",style:{left:f.left,top:f.top},onMouseDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),children:[a&&(0,r.jsxs)("div",{className:`${oK} cursor-default text-[#e8dcc8]`,children:[(0,r.jsx)("span",{className:"text-[#d8c8a8]",children:(0,r.jsx)(oU,{visible:!0})}),(0,r.jsx)("span",{className:"truncate",children:a})]}),s.map(e=>{let a=e.id===t;return(0,r.jsxs)("button",{type:"button",role:"menuitem",className:`${oK} ${a?"text-[#e8dcc8]":"text-slate-200"}`,onClick:()=>v(()=>o(e.id)),children:[(0,r.jsx)("span",{className:a?"text-[#d8c8a8]":"text-[#d8c8a8]/75",children:(0,r.jsx)(oU,{visible:e.active||a})}),(0,r.jsx)("span",{className:"truncate",children:e.label})]},e.id)}),w&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"mx-2 my-1 h-px bg-slate-700/50","aria-hidden":"true"}),l&&(0,r.jsxs)("button",{type:"button",role:"menuitem",className:`${oK} text-slate-300`,onClick:()=>v(l),children:[(0,r.jsx)(oU,{visible:!1}),(0,r.jsx)("span",{className:"truncate",children:"Effect parameter..."})]}),d&&(0,r.jsxs)("button",{type:"button",role:"menuitem",className:`${oK} text-slate-300`,onClick:()=>v(d),children:[(0,r.jsx)(oU,{visible:!1}),(0,r.jsx)("span",{className:"truncate",children:"Transition parameter..."})]})]}),k&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"mx-2 my-1 h-px bg-slate-700/50","aria-hidden":"true"}),(0,r.jsx)("div",{className:"px-2 pb-1 pt-1.5 text-[8px] font-semibold uppercase tracking-[0.14em] text-slate-500",children:"Motion presets"}),c.map(e=>(0,r.jsxs)("button",{type:"button",role:"menuitem",className:`${oK} text-slate-300`,onClick:()=>v(()=>u?.(e.id)),children:[(0,r.jsx)(oU,{visible:!1}),(0,r.jsx)("span",{className:"truncate",children:e.label})]},e.id))]})]}),document.body)]})}let oH=(e,t,a)=>Math.max(t,Math.min(a,e)),oq=e=>`${e.segmentId}:${e.keyframeId}`,oY=e=>{let t=new Map;for(let a of e)t.set(oq(a),a);return Array.from(t.values())};function oG({width:e,height:t,zoomLevel:a,property:n,segments:s,readOnly:o=!1,onCurve
97Change:l,onEditTransactionStart:d,onEditTransactionCommit:c}){let u=(0,i.useRef)(null),[p,m]=(0,i.useState)([]),[h,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),b=(0,i.useMemo)(()=>s.map(e=>({...e,curve:(0,tB.w)(e.curve)})),[s]),y=(0,i.useMemo)(()=>new Map(b.map(e=>[e.id,e])),[b]),w=Math.max(4,t-2),k=(0,i.useMemo)(()=>new Set(p.map(e=>oq(e))),[p]);(0,i.useEffect)(()=>{if(0===p.length)return;let e=p.filter(e=>{let t=y.get(e.segmentId);return t?.curve?.keyframes.some(t=>t.id===e.keyframeId)});e.length!==p.length&&m(e)},[y,p]);let S=(0,i.useCallback)(e=>{let t=u.current?.getBoundingClientRect();return t?{x:oH(e.clientX-t.left,0,t.width),y:oH(e.clientY-t.top,0,t.height)}:{x:0,y:0}},[]),j=(0,i.useCallback)(e=>b.find(t=>{let r=t.startTime*a,n=t.endTime*a;return e>=r&&e<=n}),[b,a]),I=(0,i.useMemo)(()=>b.flatMap(e=>(e.curve?.keyframes??[]).map(t=>({segmentId:e.id,keyframeId:t.id,x:e.startTime*a+t.time*a,y:n.valueToY(n.clampValue(t.value),w)}))),[w,b,n,a]),N=(0,i.useCallback)((e,t,a,r)=>I.filter(n=>n.x>=e&&n.x<=t&&n.y>=a&&n.y<=r).map(e=>({segmentId:e.segmentId,keyframeId:e.keyframeId})),[I]),C=(0,i.useCallback)((e,t,a,r,i=!1)=>{let s=Math.max(0,e.endTime-e.startTime),o=(0,tB.w)(e.curve)??{propertyId:n.id,interpolation:"linear",keyframes:[]},d=oH(a,0,s),c=n.clampValue(r),u=o.keyframes.map(e=>e.id===t?{...e,time:d,value:c}:e),p=i?u:(0,tB.N5)(u);l(e.id,{propertyId:n.id,interpolation:o.interpolation??"linear",keyframes:p})},[l,n]),M=(0,i.useCallback)((e,t,a)=>{d?.();let r=oH(t,0,Math.max(0,e.endTime-e.startTime)),i=n.clampValue(a),s=`keyframe-${(0,v.generateId)()}`,o=(0,tB.w)(e.curve)??{propertyId:n.id,interpolation:"linear",keyframes:[]},u={propertyId:n.id,interpolation:o.interpolation??"linear",keyframes:(0,tB.N5)([...o.keyframes,{id:s,time:r,value:i}])};l(e.id,u),m([{segmentId:e.id,keyframeId:s}]),c?.()},[l,c,d,n]),_=(0,i.useCallback)(()=>{if(0===p.length||o)return;let e=new Map;for(let t of p)e.has(t.segmentId)||e.set(t.segmentId,new Set),e.get(t.segmentId)?.add(t.keyframeId);for(let[t,a]of(d?.(),e)){let e=y.get(t);if(!e?.curve)continue;let r=e.curve.keyframes.filter(e=>!a.has(e.id));if(0===r.length){l(e.id,void 0);continue}l(e.id,{propertyId:n.id,interpolation:e.curve.interpolation??"linear",keyframes:(0,tB.N5)(r)})}m([]),c?.()},[l,c,d,n.id,o,y,p]);(0,i.useEffect)(()=>{if(0===p.length)return;let e=e=>{("Delete"===e.key||"Backspace"===e.key)&&(e.preventDefault(),_())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[_,p.length]);let A=(0,i.useCallback)((e,t,r)=>{let n=Math.max(0,e.endTime-e.startTime),i=(0,tB.w)(e.curve);if(!i)return oH(r,0,n);let s=sr.Ne/Math.max(a,1),o=[0,n];for(let e of i.keyframes)e.id!==t&&o.push(e.time);let l=oH(r,0,n);for(let e of o)if(Math.abs(e-l)<=s){l=e;break}return oH(l,0,n)},[a]);(0,i.useEffect)(()=>{if(!h||o)return;let e=e=>{if(!u.current||"number"==typeof h.pointerId&&0===e.buttons)return;let t=y.get(h.segmentId);if(!t?.curve)return;let{x:r,y:i}=S(e),s=(r-t.startTime*a)/Math.max(a,1),o=A(t,h.keyframeId,s),l=n.yToValue(i,w);C(t,h.keyframeId,o,l)},t=()=>{f(null),c?.()};return window.addEventListener("mousemove",e),window.addEventListener("mouseup",t),()=>{window.removeEventListener("mousemove",e),window.removeEventListener("mouseup",t)}},[h,S,A,w,n,o,y,C,a,c]);let E=(0,i.useCallback)(e=>{if(o)return;let{x:t,y:r}=S(e),i=j(t);if(!i)return;let s=(t-i.startTime*a)/Math.max(a,1);M(i,s,n.yToValue(r,w))},[M,j,S,w,n,o,a]),T=(0,i.useCallback)(e=>{if(o||0!==e.button)return;let t=e.target;if(t?.closest("[data-keyframe-hit]"))return;let{x:a,y:r}=S(e),n=!1,i=a,s=r,l=e=>{let{x:t,y:o}=S(e);i=t,s=o,!n&&(Math.abs(i-a)>4||Math.abs(s-r)>4)&&(n=!0),n&&(x({startX:a,startY:r,currentX:i,currentY:s,active:!0}),m(oY(N(Math.min(a,i),Math.max(a,i),Math.min(r,s),Math.max(r,s)))))},d=()=>{n||m([]),x(null),document.removeEventListener("mousemove",l),document.removeEventListener("mouseup",d)};document.addEventListener("mousemove",l),document.addEventListener("mouseup",d)},[S,N,o]),$=Math.max(e,1),P=Math.max(t,1);return(0,r.jsxs)("div",{ref:u,"data-automation-keyframe-editor":!0,className:"absolute left-0 right-0 bottom-0 top-0 overflow-hidden",style:{width:e,height:t},onMouseDown:T,onDoubleClick:E,children:[(0,r.jsxs)("svg",{className:"absolute inset-0 h-full w-full",viewBox:`0 0 ${$} ${P}`,children:[(0,r.jsxs)("defs",{children:[(0,r.jsxs)("linearGradient",{id:"curve-gradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[(0,r.jsx)("stop",{offset:"0%",stopColor:"rgba(232, 220, 200, 0.16)"}),(0,r.jsx)("stop",{offset:"55%",stopColor:"rgba(232, 220, 200, 0.05)"}),(0,r.jsx)("stop",{offset:"100%",stopColor:"rgba(232, 220, 200, 0)"})]}),(0,r.jsxs)("linearGradient",{id:"curve-stroke-gradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[(0,r.jsx)("stop",{offset:"0%",stopColor:"rgba(245, 236, 218, 0.95)"}),(0,r.jsx)("stop",{offset:"100%",stopColor:"rgba(208, 184, 148, 0.8)"})]}),(0,r.jsxs)("filter",{id:"curve-glow",children:[(0,r.jsx)("feGaussianBlur",{stdDeviation:"1.6",result:"blur"}),(0,r.jsxs)("feMerge",{children:[(0,r.jsx)("feMergeNode",{in:"blur"}),(0,r.jsx)("feMergeNode",{in:"SourceGraphic"})]})]})]}),[.25,.5,.75].map(e=>{let t=w*e;return(0,r.jsx)("line",{x1:0,y1:t,x2:$,y2:t,stroke:.5===e?"rgba(148, 163,
97184, 0.14)":"rgba(148, 163, 184, 0.07)",strokeWidth:"1",strokeDasharray:.5===e?"2 4":void 0},`grid-${e}`)}),b.map(e=>{let i=e.startTime*a,s=Math.max(0,(e.endTime-e.startTime)*a),o=(e=>{let t=[...e].sort((e,t)=>e-t),a=[];for(let e of t)(0===a.length||Math.abs(e-a[a.length-1])>1e-5)&&a.push(e);return a})([0,Math.max(0,e.endTime-e.startTime),...(e.curve?.keyframes??[]).map(e=>e.time)]).map(t=>{let r=i+t*a,s=(0,tB.W6)(e.curve,t,e.fallbackValue);return{x:r,y:n.valueToY(n.clampValue(s),w)}}),l=o.map((e,t)=>`${0===t?"M":"L"} ${e.x.toFixed(2)} ${e.y.toFixed(2)}`).join(" "),d=o.length>0?`${l} L ${o[o.length-1].x.toFixed(2)} ${P} L ${o[0].x.toFixed(2)} ${P} Z`:"";return(0,r.jsxs)("g",{children:[(0,r.jsx)("rect",{x:i,y:0,width:s,height:t,fill:"rgba(148, 163, 184, 0.035)"}),(0,r.jsx)("line",{x1:i,y1:0,x2:i,y2:t,stroke:"rgba(148, 163, 184, 0.18)",strokeWidth:"1"}),(0,r.jsx)("line",{x1:i+s,y1:0,x2:i+s,y2:t,stroke:"rgba(148, 163, 184, 0.18)",strokeWidth:"1"}),d.length>0&&(0,r.jsx)("path",{d:d,fill:"url(#curve-gradient)"}),l.length>0&&(0,r.jsx)("path",{d:l,fill:"none",stroke:"url(#curve-stroke-gradient)",strokeWidth:sr.y9,strokeLinecap:"round",strokeLinejoin:"round",filter:"url(#curve-glow)"})]},e.id)}),b.flatMap(e=>(e.curve?.keyframes??[]).map(t=>{let i=e.startTime*a+t.time*a,s=n.valueToY(n.clampValue(t.value),w),o=k.has(oq({segmentId:e.id,keyframeId:t.id})),l=sr.oA+.5*!!o;return(0,r.jsxs)("g",{children:[o&&(0,r.jsx)("rect",{x:i-l-2,y:s-l-2,width:(l+2)*2,height:(l+2)*2,rx:"1",transform:`rotate(45 ${i} ${s})`,fill:"none",stroke:"rgba(251, 191, 36, 0.45)",strokeWidth:"1"}),(0,r.jsx)("rect",{x:i-l,y:s-l,width:2*l,height:2*l,rx:"0.75",transform:`rotate(45 ${i} ${s})`,fill:o?"#fbbf24":"#0b1220",stroke:o?"rgba(254, 243, 199, 0.95)":"rgba(240, 228, 205, 0.85)",strokeWidth:"1",style:{filter:o?"drop-shadow(0 0 3px rgba(251, 191, 36, 0.55))":"drop-shadow(0 1px 1.5px rgba(0, 0, 0, 0.55))"}})]},`${e.id}-${t.id}`)}))]}),b.flatMap(e=>(e.curve?.keyframes??[]).map(t=>{let i=e.startTime*a+t.time*a,s=n.valueToY(n.clampValue(t.value),w),l=2*sr.oA+sr.Ne;return(0,r.jsx)("button",{type:"button","data-keyframe-hit":!0,className:"absolute -translate-x-1/2 -translate-y-1/2",style:{left:i,top:s,width:l,height:l,background:"transparent",cursor:o?"default":"grab",zIndex:2},onMouseDown:a=>{a.preventDefault(),a.stopPropagation();let r={segmentId:e.id,keyframeId:t.id},n=a.shiftKey||a.metaKey||a.ctrlKey;m(e=>{if(!n)return[r];let t=oq(r);return e.some(e=>oq(e)===t)?e.filter(e=>oq(e)!==t):oY([...e,r])}),o||(d?.(),f({segmentId:e.id,keyframeId:t.id,pointerId:a.button}))},title:`${n.label}: ${n.formatValue(t.value)} @ ${t.time.toFixed(2)}s`},`hit-${e.id}-${t.id}`)})),g?.active&&(0,r.jsx)("div",{className:"absolute border border-[#c8a87c]/55 bg-[#c8a87c]/10 pointer-events-none",style:{left:Math.min(g.startX,g.currentX),top:Math.min(g.startY,g.currentY),width:Math.abs(g.currentX-g.startX),height:Math.abs(g.currentY-g.startY),zIndex:8}})]})}function oX({trackId:e,top:t,width:a,height:n,propertyId:s,property:o,availableProperties:l,activePropertyIds:d=[],segments:c,zoomLevel:u,collapsed:p=!1,readOnly:m=!1,onPropertyChange:h,onPickEffectParameter:f,onPickTransitionParameter:g,motionPresetOptions:x=[],motionPresetActiveLabelOverride:b,onApplyMotionPreset:y,onSegmentCurveChange:v,onAutomationEditStart:w,onAutomationEditCommit:k,onLaneHeightChange:S}){let j=sZ(n),I=sr.n_+1,N=(0,i.useMemo)(()=>c.filter(e=>e.endTime>e.startTime&&Number.isFinite(e.startTime)),[c]),C=(0,i.useMemo)(()=>N.reduce((e,t)=>e+(t.curve?.keyframes.length??0),0),[N]),M=(0,i.useMemo)(()=>new Set(["userZoom","panX","panY","rotation"]),[]),_=(0,i.useMemo)(()=>new Set(d),[d]),A=(0,i.useMemo)(()=>l.filter(e=>!M.has(e.id)),[l,M]),E=(0,i.useMemo)(()=>{let e=[...A];return e.sort((e,t)=>{let a=_.has(e.id);return a!==_.has(t.id)?a?-1:1:"volume"===e.id&&"volume"!==t.id?-1:"volume"===t.id&&"volume"!==e.id?1:e.label.localeCompare(t.label)}),e},[_,A]),T=M.has(s),$=(0,i.useMemo)(()=>M.has(s)&&(b||o.label)||"Motion preset curve",[M,b,o.label,s]),P=(0,i.useMemo)(()=>E.map(e=>({id:e.id,label:e.label,active:_.has(e.id)})),[_,E]),D=(0,i.useCallback)(t=>{(T||t!==s)&&h(e,t,s)},[T,h,s,e]),[R,z]=(0,i.useState)(!1),L=(0,i.useRef)(0),F=(0,i.useRef)(n),O=(0,i.useRef)(null),B=(0,i.useCallback)(e=>{if(!S)return;e.preventDefault(),e.stopPropagation(),z(!0),L.current=e.clientY,F.current=n;let t=document.body.style.cursor,a=document.body.style.userSelect;document.body.style.cursor="ns-resize",document.body.style.userSelect="none";let r=e=>{e.preventDefault();let t=e.clientY-L.current,a=Math.max(sr.SU,Math.min(sr.O$,F.current-t));null!=O.current&&cancelAnimationFrame(O.current),O.current=requestAnimationFrame(()=>{O.current=null,S(a)})},i=()=>{z(!1),null!=O.current&&cancelAnimationFrame(O.current),document.body.style.cursor=t,document.body.style.userSelect=a,document.removeEventListener("mousemove",r,!0),document.removeEventListener("mouseup",i,!0)};document.addEventListener("mousemove",r,!0),document.addEventListener("mouseup",i,!0)},[n,S]);return(0,r.jsxs)(si,{top:t,width:a,height:n,label:"",collapsed:p,headerContent:(0,r.jsxs)("div",{className:"inline-flex h-[15px] max-w-full items-center gap-0.5 rounded-[4px] pl-1.5 pr-0.5",style:{background:"rgba(10, 15, 27, 0.85)",boxShadow:"inset 0 0 0 1px rgba(148, 163,
97184, 0.14)"},children:[(0,r.jsx)("svg",{width:"6",height:"6",viewBox:"0 0 7 7",fill:"none","aria-hidden":"true",className:"shrink-0 text-[#d8c8a8]/70",children:(0,r.jsx)("rect",{x:"3.5",y:"0.5",width:"4.24",height:"4.24",rx:"0.6",transform:"rotate(45 3.5 0.5)",fill:"currentColor"})}),(0,r.jsx)(oV,{triggerLabel:T?$:o.label,currentPropertyId:T?null:s,activeSentinelLabel:T?$:null,disabled:m||0===E.length&&0===x.length,propertyOptions:P,onSelectProperty:D,onPickEffectParameter:f,onPickTransitionParameter:g,motionPresetOptions:x,onApplyMotionPreset:y}),C>0&&(0,r.jsx)("span",{className:"mr-0.5 rounded-[3px] px-1 py-px font-mono text-[8px] font-semibold leading-none tabular-nums text-[#d8c8a8]/70",style:{background:"rgba(200, 168, 124, 0.10)"},title:`${C} keyframe${1===C?"":"s"}`,children:C})]}),children:[(0,r.jsx)("div",{className:"absolute left-0 right-0",style:{top:I,height:j},children:(0,r.jsx)(oG,{width:a,height:j,zoomLevel:u,property:o,segments:N,readOnly:m,onCurveChange:v,onEditTransactionStart:w,onEditTransactionCommit:k})}),S&&(0,r.jsx)("div",{className:`absolute left-0 right-0 top-0 h-[5px] cursor-ns-resize z-30 ${R?"bg-sky-500/25":"hover:bg-sky-400/15"}`,style:{marginTop:-3},onMouseDown:B,title:"Drag to resize keyframe lane height",children:(0,r.jsx)("div",{className:`absolute left-0 right-0 top-[2px] h-px transition-colors ${R?"bg-sky-400/60":"bg-slate-600/40 hover:bg-sky-400/40"}`})})]})}var oJ=a(85331);function oZ({orderedVisibleTrackIds:e,blocks:t,scenes:a,timelineWidth:n,zoomLevel:s,customAutomationPropertyDefinitions:o,motionPresetDropdownOptions:l,motionPresetLabelsByTrackProperty:d,isTrackLocked:c,getTrackAutomationPropertyOptions:u,getTrackAutomationState:p,getTrackAutomationLayout:m,buildTrackAutomationSegments:h,handleTrackAutomationPropertyChange:f,handleTrackParameterPickerRequest:g,handleTrackAutomationPresetSelect:x,updateSegmentAutomationCurve:b,beginAutomationUndoTransaction:y,commitAutomationUndoTransaction:v,setAutomationLaneHeight:w}){let k=new Map((a??[]).map(e=>[e.id,e]));return(0,r.jsx)(r.Fragment,{children:e.flatMap(e=>{let a=u(e),S=p(e);if(!S.expanded)return[];let j=m(e);if(j.laneHeight<=0||j.laneCount<=0)return[];let I=Array.from(new Set(j.propertyIds.length>0?j.propertyIds:S.propertyId?[S.propertyId]:[])).filter(e=>a.includes(e)||!!o[e]);if(0===I.length){let e=a[0];if(!e)return[];I.push(e)}let N=a.map(e=>o[e]??sX(e)).filter((e,t,a)=>a.findIndex(t=>t.id===e.id)===t),C=Array.from(new Set([...s1({blocks:t,customAutomationPropertyDefinitions:o,trackId:e}),...I])),M=t.filter(t=>{if("scene"!==t.type||Number(t.trackId??1)!==e||!(t.duration>0))return!1;let a=k.get(t.sceneId);return(0,oJ.K3)(a)&&a?.facelessPlaceholderHints?.willDeliverZoom===!0}
97);return I.map((t,a)=>{let u=o[t]??sX(t),p=h(e,t),m=j.laneTop+a*(j.laneHeight+sr.ko),k="userZoom"===t&&M.length>0?(0,r.jsx)(r.Fragment,{children:M.map(t=>{let a=Math.max(6,t.duration*s),n=m+sr.n_+1,i=sZ(j.laneHeight);return(0,r.jsxs)("div",{"data-testid":"automation-lane-loading-block",className:"pointer-events-none absolute flex select-none items-center justify-center overflow-hidden rounded-[4px] bg-[#071019]/85",style:{left:t.start*s,width:a,top:n,height:Math.max(0,i-2),zIndex:30,boxShadow:"inset 0 0 0 1px rgba(56,189,248,0.14)"},"aria-label":"Loading keyframes",children:[(0,r.jsx)("div",{"aria-hidden":!0,className:"gen-conveyor absolute inset-0",style:{"--gen-stripe":"rgba(56,189,248,0.06)"}}),a>=34&&(0,r.jsxs)("div",{className:"relative flex max-w-full items-center gap-1.5 rounded-md border border-sky-400/20 bg-black/50 px-1.5 py-[2px]",children:[(0,r.jsxs)("span",{className:"gen-dots text-sky-300","aria-hidden":!0,children:[(0,r.jsx)("span",{}),(0,r.jsx)("span",{}),(0,r.jsx)("span",{})]}),(0,r.jsx)("span",{className:"truncate font-mono text-[8px] font-semibold uppercase tracking-[0.16em] text-sky-200/90",children:"Loading keyframes"})]})]},`automation-zoom-loading-${e}-${t.id}`)})}):null;return(0,r.jsxs)(i.Fragment,{children:[(0,r.jsx)(oX,{trackId:e,top:m,width:n,height:j.laneHeight,propertyId:t,property:u,availableProperties:N,activePropertyIds:C,segments:p,zoomLevel:s,readOnly:c(e),onPropertyChange:f,onPickEffectParameter:()=>g(e,p,"effects"),onPickTransitionParameter:()=>g(e,p,"transitions"),motionPresetOptions:l,motionPresetActiveLabelOverride:d[sQ(e,t)],onApplyMotionPreset:t=>x(e,t),onSegmentCurveChange:(e,a)=>{let r=p.find(t=>t.id===e);r&&b(r,t,a)},onAutomationEditStart:y,onAutomationEditCommit:v,onLaneHeightChange:t=>{w(e,t)}}),k]},`automation-lane-${e}-${t}-${a}`)})})})}function oQ({controller:e}){let t,{pendingTrackDelete:a,cancelTrackDelete:n,confirmTrackDelete:s}=e,o=(0,i.useRef)(null);if((0,i.useEffect)(()=>{if(!a)return;o.current=document.activeElement;let e=e=>{if("Backspace"===e.key||"Delete"===e.key){e.preventDefault(),e.stopImmediatePropagation();return}"Escape"===e.key&&(e.preventDefault(),e.stopImmediatePropagation(),n())};return document.addEventListener("keydown",e,!0),()=>{document.removeEventListener("keydown",e,!0),o.current?.focus()}},[n,a]),!a||"u"<typeof document)return null;let l=(t=[],a.sceneCount>0&&t.push(`${a.sceneCount} scene${1===a.sceneCount?"":"s"}`),a.otherCount>0&&t.push(`${a.otherCount} other block${1===a.otherCount?"":"s"}`),t.join(" and "));return(0,p.createPortal)((0,r.jsx)("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center bg-black/75 px-4 backdrop-blur-sm",role:"presentation","data-testid":"delete-track-confirmation-backdrop",onMouseDown:e=>{e.target===e.currentTarget&&n()},children:(0,r.jsxs)("div",{role:"dialog","aria-modal":"true","aria-labelledby":"delete-track-confirmation-title","aria-describedby":"delete-track-confirmation-description","data-testid":"delete-track-confirmation-dialog",className:"w-full max-w-md rounded-2xl border border-red-400/20 bg-[#111722] p-5 shadow-[0_24px_80px_rgba(0,0,0,0.7)]",onMouseDown:e=>e.stopPropagation(),children:[(0,r.jsxs)("div",{className:"mb-4 flex items-start gap-3",children:[(0,r.jsx)("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-full border border-red-400/25 bg-red-500/10 text-lg text-red-300",children:"!"}),(0,r.jsxs)("div",{children:[(0,r.jsx)("h2",{id:"delete-track-confirmation-title",className:"text-base font-semibold text-slate-100",children:"Delete this track?"}),(0,r.jsxs)("p",{id:"delete-track-confirmation-description",className:"mt-1 text-sm leading-5 text-slate-400",children:["This track contains ",l,"."]})]})]}),a.sceneCount>0?(0,r.jsx)("div",{className:"mb-5 rounded-xl border border-red-400/20 bg-red-500/[0.07] px-3.5 py-3 text-sm leading-5 text-red-100/90",children:"Deleting it will also remove any voiceover, captions, effects and keyframes attached to those scenes, even when they appear on other lanes."}):null,(0,r.jsxs)("div",{className:"flex justify-end gap-2.5",children:[(0,r.jsx)("button",{type:"button",autoFocus:!0,className:"rounded-lg border border-slate-600/70 bg-slate-800 px-4 py-2 text-sm font-medium text-slate-200 transition-colors hover:bg-slate-700 focus:outline-none focus:ring-2 focus:ring-slate-400/50",onClick:n,children:"Cancel"}),(0,r.jsx)("button",{type:"button",className:"rounded-lg border border-red-400/30 bg-red-600 px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-red-500 focus:outline-none focus:ring-2 focus:ring-red-400/60",onClick:s,children:"Delete track"})]})]})}),document.body)}function o0(e,t,a){if(!(a>0))return 0;let r=(e-t)/a;return r<=0?0:r>=1?1:r}function o1(e,t,a){let r=(0,i.useRef)(a);r.current=a,(0,i.useEffect)(()=>{let a=-1;return(0,G.G)(n=>{let i=o0(n,e,t);a>=0&&5e-4>Math.abs(i-a)||(a=i,r.current(i))})},[e,t])}function o5({zoomLevel:e}){let t=(0,y.zC)(e=>e.projectTime);return(0,r.jsx)(ox.PZ,{position:t*e})}function o2(e,t){return(0,y.zC)(a=>o0(a.projectTime,e,t))}
97function o4({start:e,duration:t,offset:a=0,children:r}){return r((0,y.zC)(r=>Math.max(0,Math.min(t,r.projectTime-e))+a))}function o3({start:e,duration:t,color:a}){let n=100*o2(e,t),s=(0,i.useRef)(null),o=(0,i.useRef)(null);return o1(e,t,e=>{let t=100*e;s.current&&(s.current.style.width=`${t}%`),o.current&&(o.current.style.left=`${t}%`,o.current.style.width=`${100-t}%`)}),(0,r.jsxs)("div",{className:"absolute inset-0 pointer-events-none",style:{borderRadius:3},children:[(0,r.jsx)("div",{ref:s,className:"absolute top-0 left-0 h-full",style:{width:`${n}%`,backgroundColor:a,opacity:.22}}),(0,r.jsx)("div",{ref:o,className:"absolute top-0 h-full",style:{left:`${n}%`,width:`${100-n}%`,backgroundColor:a,opacity:.06}})]})}function o8({start:e,duration:t,zoomLevel:a,rawBlockWidth:n,blockChromePadding:s,color:o}){let l=o2(e,t),d=(0,i.useRef)(null),c=(0,i.useRef)(null),u=e=>{let r=n-2*s,i=Math.max(0,e*t*a-s);return r>0?Math.min(100,i/r*100):0},p=u(l);return o1(e,t,e=>{let t=u(e);d.current&&(d.current.style.width=`${t}%`),c.current&&(c.current.style.left=`${t}%`,c.current.style.width=`${100-t}%`)}),(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{ref:d,className:"absolute top-0 left-0 h-full",style:{width:`${p}%`,backgroundColor:o,opacity:.65,filter:"blur(0.15px)"}}),(0,r.jsx)("div",{ref:c,className:"absolute top-0 h-full",style:{left:`${p}%`,width:`${100-p}%`,backgroundColor:o,opacity:.2}})]})}function o6({start:e,duration:t,color:a}){let n=100*o2(e,t),s=(0,i.useRef)(null),o=(0,i.useRef)(null);return o1(e,t,e=>{let t=100*e;s.current&&(s.current.style.width=`${t}%`),o.current&&(o.current.style.left=`${t}%`,o.current.style.width=`${100-t}%`)}),(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{ref:s,className:"absolute top-0 left-0 h-full",style:{width:`${n}%`,backgroundColor:a,opacity:.65}}),(0,r.jsx)("div",{ref:o,className:"absolute top-0 h-full",style:{left:`${n}%`,width:`${100-n}%`,backgroundColor:a,opacity:.2}})]})}function o9({blockStart:e,blockDuration:t,blockWidthPx:a,words:n,availableRows:s,segmentHeight:o,fontSize:l,textColor:d,fontFamily:c}){let u=(0,y.zC)(t=>{if(!n||0===n.length)return -1;let a=-1,r=-1/0;for(let i=0;i<n.length;i++){let s=e+n[i].start,o=e+n[i].end;t.projectTime>=s&&t.projectTime<o&&s>=r&&(a=i,r=s)}return a}),p=(0,i.useRef)(null),m=(0,i.useRef)(n);m.current=n;let h=(0,i.useRef)(d);h.current=d,(0,i.useEffect)(()=>{let t=null;return(0,G.G)(a=>{let r=m.current;if(!r||0===r.length)return;let n=-1,i=-1/0;for(let t=0;t<r.length;t++){let s=e+r[t].start,o=e+r[t].end;a>=s&&a<o&&s>=i&&(n=t,i=s)}if(n===t)return;t=n;let s=p.current;s&&s.querySelectorAll("[data-word-idx]").forEach(e=>{let t=Number(e.dataset.wordIdx)===n;
97e.style.color=t?"#f0e0c0":h.current,e.style.fontWeight=t?"700":"500"})})},[e]);let f=(0,i.useMemo)(()=>(function(e,t,a,r,n){let i=new Set,s=Array(Math.max(1,r)).fill(-1/0),o=.62*n;for(let n=0;n<e.length;n++){let l=e[n];if(!(t>0))break;let d=l.start/t;if(d<0||d>1)continue;let c=n%Math.max(1,r),u=d*a;if(u<s[c]+4)continue;let p=Math.max(6,l.word.length*o);s[c]=u+p,i.add(n)}return i})(n,t,a,s,l),[n,t,a,s,l]);return(0,r.jsx)("div",{ref:p,className:"absolute inset-0 pointer-events-none overflow-hidden",children:n.map((a,n)=>{if(!f.has(n))return null;let i=a.start/t*100,p=n%s,m=e+a.start,h=e+a.end,g=n===u;return(0,r.jsx)("span",{"data-word-idx":n,className:"absolute font-medium whitespace-nowrap overflow-visible",style:{left:`${i}%`,top:o*(p+1)-l/2,color:g?"#f0e0c0":d,fontFamily:c,fontWeight:g?700:500,fontSize:`${l}px`,lineHeight:"1"},title:`"${a.word}" @${m.toFixed(2)}s-${h.toFixed(2)}s`,children:a.word},n)})})}function o7({markerEditState:e,marker:t,onClose:a,onRename:n,onSetColor:i,onRemove:s}){return"u"<typeof document?null:(0,p.createPortal)((0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"fixed inset-0 z-[9998]",onMouseDown:a}),(0,r.jsxs)("div",{className:"fixed z-[9999] w-48 rounded-lg border border-white/10 bg-[#0a0e18]/98 p-2 shadow-[0_12px_40px_rgba(0,0,0,0.65)] backdrop-blur-md",style:{left:Math.min(e.x,window.innerWidth-200),top:Math.max(10,e.y-110)},onMouseDown:e=>e.stopPropagation(),children:[(0,r.jsxs)("div",{className:"mb-1.5 flex items-center justify-between",children:[(0,r.jsx)("span",{className:"text-[9px] font-semibold uppercase tracking-[0.14em] text-slate-500",children:"Marker"}),(0,r.jsx)("button",{className:"rounded px-1 py-[1px] text-[9px] font-medium text-red-300/80 transition-colors hover:bg-red-500/15 hover:text-red-200",onClick:()=>s(t.id),children:"Delete"})]}
97),(0,r.jsx)("input",{autoFocus:!0,type:"text",defaultValue:t.label??"",placeholder:"Marker name",className:"mb-2 w-full rounded-md border border-white/10 bg-slate-950/80 px-2 py-1 text-[11px] text-slate-100 placeholder-slate-600 outline-none focus:border-sky-500/50",onKeyDown:e=>{e.stopPropagation(),"Enter"===e.key&&(n(t.id,e.target.value),a()),"Escape"===e.key&&a()},onBlur:e=>n(t.id,e.target.value)}),(0,r.jsx)("div",{className:"flex items-center justify-between gap-1",children:y.Q4.map(e=>(0,r.jsx)("button",{className:"h-4 w-4 rounded-full border transition-transform hover:scale-110",style:{background:e,borderColor:(t.color??"#38bdf8")===e?"rgba(255,255,255,0.9)":"rgba(255,255,255,0.15)",boxShadow:(t.color??"#38bdf8")===e?`0 0 6px ${e}aa`:"none"},onClick:()=>i(t.id,e)},e))})]})]}),document.body)}let le=(e,t)=>{let a=e.media?.trim?e.media.trim.end-e.media.trim.start:e.media?.duration||0;return a>0?a:t?.duration??0},lt=()=>({armed:null,expansionTrack:null});function la(e){return Math.max(.35,e??1)}function lr({indicator:e}){return!e||"u"<typeof document?null:(0,p.createPortal)((0,r.jsx)("div",{className:"fixed pointer-events-none z-[9999]",style:{left:e.x,top:e.y},children:(0,r.jsxs)("div",{className:"px-1.5 py-[2px] rounded bg-slate-950/90 border border-slate-700/70 text-[9px] leading-none font-mono text-slate-100 shadow-[0_2px_8px_rgba(0,0,0,0.45)] flex items-baseline gap-1",style:e.pulseNonce?{animation:"volumeIndicatorPulse 820ms ease-out 1"}:void 0,children:[(0,r.jsxs)("span",{children:[Math.round(100*e.volume),"%"]}),(0,r.jsx)("span",{className:"text-[8px] text-slate-400",children:function(e){if(e<=0)return"-âdB";let t=20*Math.log10(e);return`${t>=0?"+":""}${t.toFixed(1)}dB`}(e.volume)})]},e.pulseNonce??"drag-indicator")}),document.body)}function ln({indicator:e}){return!e||"u"<typeof document?null:(0,p.createPortal)((0,r.jsx)("div",{className:"fixed pointer-events-none z-[9999]",style:{left:e.x,top:e.y},children:(0,r.jsxs)("div",{className:"px-1 py-[1px] rounded bg-slate-950/90 border border-slate-700/70 text-[9px] leading-none font-mono text-slate-100 shadow-[0_2px_8px_rgba(0,0,0,0.45)]",children:["in"===e.edge?"Fade in":"Fade out"," ",e.seconds.toFixed(2),"s"]})}),document.body)}function li({side:e,animatedColors:t}){let a=t?{className:"fill-amber-400 group-hover:fill-amber-300 transition-colors"}:{fill:"#fbbf24",fillOpacity:.7};return(0,r.jsxs)("svg",{className:"start"===e?"absolute left-0 top-0":"absolute right-0 top-0",width:"8",height:"24",viewBox:"0 0 8 24",fill:"none",children:[(0,r.jsx)("rect",{x:5*("start"!==e),y:"0",width:"3",height:"24",rx:"1",...a}),(0,r.jsx)("rect",{x:"0",y:"0",width:"8",height:"3",rx:"1",...a})]})}function ls({loopRegion:e,loopDragState:t,zoomLevel:a,onClearLoopRegion:n,onLoopEdgeMouseDown:i}){return(0,r.jsxs)(r.Fragment,{children:[t?.active&&(0,r.jsxs)("div",{className:"absolute top-0 h-full pointer-events-none",style:{left:Math.min(t.startTime,t.currentTime)*a,width:Math.abs(t.currentTime-t.startTime)*a},children:[(0,r.jsx)("div",{className:"absolute inset-0 bg-amber-400/10"}),(0,r.jsx)("div",{className:"absolute top-0 left-[6px] right-[6px] h-[2px] bg-amber-400/60"}),(0,r.jsx)(li,{side:"start",animatedColors:!1}),(0,r.jsx)(li,{side:"end",animatedColors:!1})]}),e&&!t?.active&&(0,r.jsxs)("div",{className:"absolute top-0 h-full",style:{left:e.start*a,width:(e.end-e.start)*a},children:[(0,r.jsx)("div",{className:"absolute inset-0 bg-amber-400/8 cursor-pointer",onDoubleClick:e=>{e.stopPropagation(),n()},title:"Double-click to remove loop"}),(0,r.jsx)("div",{className:"absolute top-0 left-[6px] right-[6px] h-[2px] bg-amber-400/80 pointer-events-none"}),(0,r.jsx)("div",{className:"absolute left-0 top-0 w-4 h-full cursor-ew-resize group z-10",onMouseDown:e=>i(e,"start"),onDoubleClick:e=>{e.stopPropagation(),n()},title:"Drag to resize loop start, double-click to remove loop",children:(0,r.jsx)(li,{side:"start",animatedColors:!0})}),(0,r.jsx)("div",{className:"absolute right-0 top-0 w-4 h-full cursor-ew-resize group z-10",onMouseDown:e=>i(e,"end"),onDoubleClick:e=>{e.stopPropagation(),n()},title:"Drag to resize loop end, double-click to remove loop",children:(0,r.jsx)(li,{side:"end",animatedColors:!0})})]})]})}function lo({blocks:e,zoomLevel:t,trimHandleWidth:n,selectedTransitionKey:i,draggingTransition:s,panelDraggingDuration:o,getTrackContentLayout:l,setDraggingTransition:d,setSelectedTransitionKey:c,setSelectedTransitionSceneId:u,setSelectedSceneIds:p,setSelectedAudioBlockIds:m,setActiveSidePanel:h,rememberSceneSidePanel:f,setPanelOpenForSceneId:g,handleRemoveTransition:x,clearSelectedTransition:b,handleApplyTransition:y,handleUpdateTransition:v}){let w=[],k=new Map;
97return e.forEach(e=>{let t=e.trackId??1;k.has(t)||k.set(t,[]),k.get(t).push(e)}),k.forEach(e=>{let t=[...e].sort((e,t)=>e.start-t.start);for(let e=0;e<t.length-1;e++){let a=t[e],r=t[e+1];.1>Math.abs(r.start-(a.start+a.duration))&&a.scene?.transition?.enabled&&w.push({fromBlock:a,toBlock:r,transition:a.scene.transition,key:`transition-${a.id}-${r.id}`})}}),(0,r.jsx)(r.Fragment,{children:w.map(({fromBlock:e,transition:w,key:k})=>{let{top:S,height:j}=l(e.trackId??1),I=s?.key===k?s.duration:o?.sceneId===e.sceneId?o.duration:w.duration,N=e.start+e.duration,C=I*t,M=i===k;return(0,r.jsxs)("div",{"data-transition-block":!0,className:"absolute z-30 cursor-pointer group",style:{left:N*t-C/2,top:S,width:C,height:j},onClick:t=>{t.stopPropagation(),c(k),u(e.sceneId),p([e.sceneId]),m([]),h("transitions"),f(e.sceneId,"transitions"),g(e.sceneId)},onDoubleClick:t=>{t.stopPropagation(),x(e.sceneId),b()},onDragOver:e=>{e.dataTransfer.types.includes("application/x-transition-type")&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},onDrop:t=>{let r=t.dataTransfer.getData("application/x-transition-type");r&&(t.preventDefault(),t.stopPropagation(),Promise.resolve().then(a.bind(a,74698)).then(({getTransitionDefinition:t})=>{let a=t(r);if(!a)return;let n=Math.max(aj.Cy,Math.min(aj.u1,w.duration||a.defaultDuration||aj.u1));y(e.sceneId,{type:r,duration:n,params:{...a.defaultParams},enabled:!0}),c(k),u(e.sceneId),p([e.sceneId]),m([]),h("transitions"),f(e.sceneId,"transitions"),g(e.sceneId)}))},title:`${w.type.replace(/_/g," ")} (${I.toFixed(1)}s) - Click to edit, double-click to remove`,children:[(0,r.jsxs)("div",{className:`absolute inset-0 overflow-hidden rounded-[3px] transition-all duration-100 ${M?"ring-1 ring-white/40 shadow-[0_0_12px_rgba(255,255,255,0.18)]":"ring-1 ring-white/[0.08]"}`,style:{background:M?"linear-gradient(90deg, rgba(255,255,255,0.10) 0%, rgba(255,255,255,0.18) 50%, rgba(255,255,255,0.10) 100%)":"linear-gradient(90deg, rgba(255,255,255,0.04) 0%, rgba(255,255,255,0.10) 50%, rgba(255,255,255,0.04) 100%)",backdropFilter:"blur(1.5px)"},children:[(0,r.jsx)("div",{className:"absolute inset-0 bg-white/0 group-hover:bg-white/[0.06] transition-colors duration-150"}),(0,r.jsxs)("svg",{className:"absolute inset-0 h-full w-full text-white/45 transition-colors group-hover:text-white/70",viewBox:"0 0 100 100",preserveAspectRatio:"none","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M0 100 L100 0",stroke:"currentColor",strokeWidth:"1.2",vectorEffect:"non-scaling-stroke",fill:"none"}),(0,r.jsx)("path",{d:"M0 0 L100 100",stroke:"currentColor",strokeWidth:"1.2",vectorEffect:"non-scaling-stroke",fill:"none"})]}),(0,r.jsx)("div",{className:"absolute left-1/2 top-0 bottom-0 w-px bg-white/25 group-hover:bg-white/40 transition-colors"}),(0,r.jsx)("div",{className:"absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:(0,r.jsxs)("span",{className:"rounded-[4px] bg-black/55 px-1.5 py-0.5 font-mono text-[9px] font-medium text-white/85 tabular-nums backdrop-blur-sm ring-1 ring-white/15",children:[I.toFixed(1),"s"]})})]}),(0,r.jsx)("div",{className:"absolute left-0 top-0 h-full cursor-ew-resize opacity-0 group-hover:opacity-100 transition-opacity hover:bg-white/10",style:{width:n},onMouseDown:a=>{a.stopPropagation(),c(k),u(e.sceneId),p([]),m([]);let r=a.clientX,n=w.duration,i=n,s=e=>{d({key:k,duration:i=Math.max(aj.Cy,Math.min(aj.u1,n+(r-e.clientX)/t))})},o=()=>{document.removeEventListener("mousemove",s),document.removeEventListener("mouseup",o),d(null),i!==n&&v(e.sceneId,{duration:i})};document.addEventListener("mousemove",s),document.addEventListener("mouseup",o)}}),(0,r.jsx)("div",{className:"absolute right-0 top-0 h-full cursor-ew-resize opacity-0 group-hover:opacity-100 transition-opacity hover:bg-white/10",style:{width:n},onMouseDown:a=>{a.stopPropagation(),c(k),u(e.sceneId),p([]),m([]);let r=a.clientX,n=w.duration,i=n,s=e=>{d({key:k,duration:i=Math.max(aj.Cy,Math.min(aj.u1,n+(e.clientX-r)/t))})},o=()=>{document.removeEventListener("mousemove",s),document.removeEventListener("mouseup",o),d(null),i!==n&&v(e.sceneId,{duration:i})};document.addEventListener("mousemove",s),document.addEventListener("mouseup",o)}})]},k)})})}function ll(e){let{blockStart:t,blockDuration:a,isInDraggedSelection:r,isCurrentlyDragging:n,externalFlushEdges:i,pulseEdges:s,draggedEdgePositions:o,tolerance:l}=e,d=!r&&n&&o.some(e=>Math.abs(e-t)<l),c=!r&&n&&o.some(e=>Math.abs(e-(t+a))<l);return{seamLeftAligned:d,seamRightAligned:c,showLeftFlush:r&&n&&i.left||d||s.left,showRightFlush:r&&n&&i.right||c||s.right}}let ld=["#c8a87c","#a8a39e","#b08f74","#8a9b8e","#a8927c"];function lc({captionBlocks:e,blocks:t,zoomLevel:a,trimHandleWidth:n,captionBlockFontSize:i,selectedAudioBlockIds:s,draggingId:o,timingEditCaptionId:l,initialSelectionBlocks:d,dragSelectionBlockIds:c,flushPulseEdges:u,draggedEdgePositions:p,sceneBlocksForCaptionMarkers:m,sceneNumberBySceneId:h,getTrackLayout:f,isTrackLocked:g,isTrackVisible:x,handleAudioBlockClick:b,handleCaptionTimingEditToggle:y,handleBlockMouseDown:v,handleTrimMouseDown:w}){return(0,r.jsx)(r.Fragment,{children:e.map(e=>{var k;let S,j,I,{rawCaptionWidth:N,captionHitWidth:C,captionHitOffset:M,showSceneBoundaryLabels:_}=(j=Math.max(S=e.duration*a,18),{rawCaptionWidth:S,captionHitWidth:j,captionHitOffset:(j-S)/2,showSceneBoundaryLabels:S>=120}),{top:A,height:E}=f(e.trackId),T=E-8,$=s.includes(e.id),P=o===e.id,D=l===e.id,R=g(e.trackId),z=!x(e.trackId),L=sp(e,t,!0,c.size>0?c:void 0),F=u.get(e.id)||{left:!1,right:!1},O=!!o&&(e.id===o||!!d?.has(e.id)),{showLeftFlush:B,showRightFlush:W}=ll({blockStart:e.start,blockDuration:e.duration,isInDraggedSelection:O,isCurrentlyDragging:!!o,externalFlushEdges:L,pulseEdges:F,draggedEdgePositions:p,tolerance:aj.B_}),{captionNeonColor:U,bgGradient:K,borderColor:V,textColor:H}
97=(k=e.trackId,{captionNeonColor:I=ld[k%ld.length],bgGradient:$?`linear-gradient(180deg, ${I}26 0%, rgba(10,12,18,0.95) 52%, rgba(7,9,15,0.98) 100%)`:`linear-gradient(180deg, ${I}18 0%, rgba(9,11,17,0.95) 52%, rgba(6,8,14,0.98) 100%)`,borderColor:$?`${I}aa`:"rgba(255,255,255,0.07)",textColor:"rgba(236, 230, 223, 0.88)"}),q=(0,iR.c)(e.captionStyle?.fontFamily),Y=function(e,t,a){let r=e.start,n=e.start+e.duration;if(e.duration<=0)return[];let i=[];return t.forEach((t,s)=>{let o=t.start,l=t.start+t.duration;if(l<=r||o>=n)return;let d=`S${a?.get(t.sceneId)??s+1}`;o>r&&o<n&&i.push({sceneId:t.sceneId,kind:"start",time:o,pct:(o-r)/e.duration*100,label:d}),l>r&&l<n&&i.push({sceneId:t.sceneId,kind:"end",time:l,pct:(l-r)/e.duration*100,label:d})}),i.sort((e,t)=>e.time-t.time||("end"===e.kind?-1:1)).filter((e,t,a)=>{let r=a[t-1];return!r||Math.abs(r.time-e.time)>.01})}(e,m,h);return(0,r.jsx)("div",{"data-caption-block":!0,"data-timing-edit-active":D?"true":void 0,className:`absolute group select-none ${R?"opacity-60":""}${z?" opacity-30":""}`,style:{left:e.start*a-M,top:A+4,width:C,height:T,cursor:P?"grabbing":R?"not-allowed":D?"ew-resize":"grab",transform:P?"translateY(-1px)":"translateY(0px)",zIndex:P?50:1},onClick:t=>{b(e.id,t)},onDoubleClick:t=>y(e,t),onMouseDown:t=>v(t,e),children:(0,r.jsxs)("div",{className:`absolute top-0 overflow-hidden ${P?"transition-none":"transition-[box-shadow,background-color,border-color] duration-75 ease-out"} ${D?"ring-1 ring-[#c8a87c]/65 ring-offset-1 ring-offset-[#0c0c0e]":""}`,style:{left:M,width:Math.max(N,1),height:T,borderRadius:5,background:K,border:`1px solid ${V}`,boxShadow:$?`0 0 0 1px ${U}30, 0 0 18px ${U}38, inset 0 1px 0 rgba(255,255,255,0.08)`:"inset 0 1px 0 rgba(255,255,255,0.045), 0 1px 3px rgba(0,0,0,0.4)"},children:[(0,r.jsx)("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-[1.5px] z-10",style:{background:U,opacity:$?.9:.5,boxShadow:$?`0 0 6px ${U}aa`:"none"},"aria-hidden":"true"}),e.isLoading&&(0,r.jsx)(oW,{nleSceneId:e.sceneId,blockType:"caption",small:!0}),e.isLoading?(0,r.jsxs)("div",{className:"absolute inset-0 flex items-center justify-center overflow-hidden rounded bg-[#141210]/85",children:[(0,r.jsx)("div",{"aria-hidden":!0,className:"gen-conveyor absolute inset-0",style:{"--gen-stripe":"rgba(200,168,124,0.07)"}}),(0,r.jsxs)("div",{className:"relative flex max-w-full items-center gap-1.5 rounded-md border border-[#c8a87c]/25 bg-black/50 px-1.5 py-[2px]",children:[(0,r.jsxs)("span",{className:"gen-dots text-[#e3c893]","aria-hidden":!0,children:[(0,r.jsx)("span",{}),(0,r.jsx)("span",{}),(0,r.jsx)("span",{})]}),(0,r.jsx)("span",{className:"truncate font-mono text-[8px] font-semibold uppercase tracking-[0.16em] text-[#d8c8a8]",children:"Generating captions"})]})]}):(0,r.jsxs)(r.Fragment,{children:[B&&(0,r.jsx)("div",{className:"absolute left-0 top-0 w-px h-full pointer-events-none z-20",style:{background:"#ef4444",animation:F.left?"flushPulse 0.2s ease-out forwards":"none",boxShadow:"0 0 6px rgba(239, 68, 68, 0.9), 0 0 12px rgba(239, 68, 68, 0.5)"}}),W&&(0,r.jsx)("div",{className:"absolute right-0 top-0 w-px h-full pointer-events-none z-20",style:{background:"#ef4444",animation:F.right?"flushPulse 0.2s ease-out forwards":"none",boxShadow:"0 0 6px rgba(239, 68, 68, 0.9), 0 0 12px rgba(239, 68, 68, 0.5)"}}),Y.map(t=>(0,r.jsxs)("div",{className:"absolute top-0 h-full pointer-events-none z-10",style:{left:`${t.pct}%`,width:0},title:`${t.label} ${"start"===t.kind?"starts":"ends"} at ${t.time.toFixed(2)}s`,children:[(0,r.jsx)("div",{className:"absolute top-0 h-full w-px",style:{background:"start"===t.kind?"rgba(232, 220, 200, 0.75)":"rgba(200, 168, 124, 0.7)",boxShadow:"start"===t.kind?"0 0 5px rgba(232, 220, 200, 0.35)":"0 0 5px rgba(200, 168, 124, 0.32)"}}),_&&(0,r.jsx)("div",{className:"absolute top-0 rounded-b-sm px-1 py-0.5 text-[8px] font-semibold leading-none",style:{left:"start"===t.kind?2:void 0,right:"end"===t.kind?2:void 0,color:"start"===t.kind?"rgba(236, 230, 223, 0.95)":"rgba(220, 195, 162, 0.95)",background:"rgba(20, 18, 16, 0.85)",border:"start"===t.kind?"1px solid rgba(232, 220, 200, 0.32)":"1px solid rgba(200, 168, 124, 0.32)"},children:t.label})]},`${e.id}-${t.sceneId}-${t.kind}-${t.time}`)),!D&&(()=>{let t="caption"===e.type&&(e.captionWords?.length??0)>0,a=Math.min(3,Math.max(1,Math.floor(T/(i+6)))),n=T/(a+1);if(t){let t=e.captionWords;return(0,r.jsx)(o9,{blockStart:e.start,blockDuration:e.duration,blockWidthPx:Math.max(N,1),words:t,availableRows:a,segmentHeight:n,fontSize:i,textColor:H,fontFamily:q})}let s=(e.captionText||"Caption").split(/\s+/),o=Math.max(1,Math.ceil(s.length/a));return(0,r.jsx)("div",{className:"absolute inset-0 pointer-events-none overflow-hidden px-1",children:Array.from({length:Math.min(a,Math.ceil(s.length/o))},(e,t)=>{let a=s.slice(t*o,(t+1)*o);return(0,r.jsx)("div",{className:"absolute left-1 right-1 font-medium whitespace-nowrap overflow-hidden",style:{to
97p:n*(t+1)-i/2,color:H,fontFamily:q,fontSize:`${i}px`,lineHeight:"1",textOverflow:"ellipsis"},children:a.join(" ")},t)})})})(),!D&&(0,r.jsxs)(r.Fragment,{children:[R&&(0,r.jsx)("div",{className:"absolute top-0.5 right-1 z-10 p-0.5 bg-amber-500/80 rounded-sm",title:"Track is locked",children:(0,r.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",className:"text-amber-900",children:[(0,r.jsx)("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"})]})}),(0,r.jsxs)("div",{className:"absolute top-0 left-0 h-full cursor-ew-resize opacity-0 group-hover:opacity-100 transition-opacity z-10",style:{width:n},onMouseDown:t=>w(t,e,"start"),children:[(0,r.jsx)("div",{className:"h-full w-full bg-gradient-to-r from-[#e8dcc8]/40 via-[#e8dcc8]/12 to-transparent"}),(0,r.jsx)("div",{className:"absolute left-[3px] top-1/2 h-[38%] w-[2px] -translate-y-1/2 rounded-full bg-[#f0e4cd]/85 shadow-[0_0_4px_rgba(232,220,200,0.55)]"})]}),(0,r.jsxs)("div",{className:"absolute top-0 right-0 h-full cursor-ew-resize opacity-0 group-hover:opacity-100 transition-opacity z-10",style:{width:n},onMouseDown:t=>w(t,e,"end"),children:[(0,r.jsx)("div",{className:"h-full w-full bg-gradient-to-l from-[#e8dcc8]/40 via-[#e8dcc8]/12 to-transparent"}),(0,r.jsx)("div",{className:"absolute right-[3px] top-1/2 h-[38%] w-[2px] -translate-y-1/2 rounded-full bg-[#f0e4cd]/85 shadow-[0_0_4px_rgba(232,220,200,0.55)]"})]})]})]})]})},e.id)})})}function lu(e,t){let a=Math.max(0,Math.min(2,e.volume??1)),r=Math.max(0,Math.min(t,e.audioFadeInDuration??0)),n=Math.max(0,Math.min(t-r,e.audioFadeOutDuration??0));return{sceneVolume:a,sceneVolumeLinePercent:`${(1-a/2)*100}%`,sceneVolumeLineY:Math.max(0,Math.min(100,(1-a/2)*100)),sceneFadeInDuration:r,sceneFadeOutDuration:n,sceneFadeInPercent:t>0?r/t*100:0,sceneFadeOutPercent:t>0?n/t*100:0}}function lp({inFlight:e,onRegenerate:t}){let a=e=>{e.stopPropagation()};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"pointer-events-none absolute inset-0 z-30 rounded-[5px] ring-1 ring-inset ring-amber-400/60","data-testid":"timeline-voiceover-stale-indicator","aria-hidden":"true"}),(0,r.jsx)("span",{className:"pointer-events-none absolute right-1 top-1 z-30 h-[5px] w-[5px] rounded-full bg-amber-400 shadow-[0_0_4px_rgba(251,191,36,0.85)] transition-opacity duration-150 group-hover:opacity-0","aria-hidden":"true"}),(0,r.jsx)("div",{className:"pointer-events-none absolute inset-0 z-40 opacity-0 transition-opacity duration-150 group-hover:opacity-100",children:(0,r.jsxs)("button",{type:"button","data-testid":"timeline-voiceover-regenerate",title:"Voice changed since this was generated. Regenerate voiceover + captions.","aria-label":"Regenerate voiceover",disabled:e,onMouseDown:a,onPointerDown:a,onClick:r=>{a(r),e||t()},className:"pointer-events-auto absolute right-1 top-1 flex h-4 items-center gap-1 rounded-full bg-black/55 px-1.5 text-[8px] font-semibold uppercase tracking-[0.08em] text-[#e8dcc8] ring-1 ring-[#c8a87c]/40 backdrop-blur-sm transition-colors hover:bg-[#c8a87c] hover:text-[#1a1816] disabled:cursor-default disabled:opacity-60 disabled:hover:bg-black/55 disabled:hover:text-[#e8dcc8]",children:[(0,r.jsx)(to.A,{size:9,strokeWidth:2.75,className:e?"animate-spin":void 0}),"Regenerate"]})})]})}function lm({audioBlocks:e,blocks:t,zoomLevel:a,trimHandleWidth:n,waveformMode:i,blockCullingViewport:s,localTrimPreview:l,selectedAudioBlockIds:d,draggingId:c,initialSelectionBlocks:u,dragSelectionBlockIds:p,flushPulseEdges:m,draggedEdgePositions:h,sceneNumberBySceneId:f,blocksWithWaveform:g,setBlocksWithWaveform:x,activeVolumeDragBlockId:b,activeAudioFadeDragBlockId:y,contextMenuBlockId:v,persistedAudioAnalysis:w,persistAudioAnalysisArtifact:k,getTrackContentLayout:S,isTrackLocked:j,isTrackVisible:I,isTrackMuted:N,handleAudioBlockClick:C,handleBlockMouseDown:M,handleSceneContextMenu:_,handleVolumeLineMouseDown:A,handleVolumeLineDoubleClick:E,handleAudioFadeHandleMouseDown:T,handleAudioFadeHandleDoubleClick:$,handleTrimMouseDown:P,staleVoiceoverBlocks:D,onRegenerateVoiceoverBlock:R}){return(0,r.jsx)(r.Fragment,{children:e.filter(e=>
97e.id===c||e.id===l?.id||d.includes(e.id)||nM(e.start,e.duration,a,s)).map(e=>{let s,z,L,F,O,B,W,U,K=l&&l.id===e.id,V=K?l.start:e.start,H=K?l.duration:e.duration,q=K?l.inOffset:e.inOffset||0,{rawBlockWidth:Y,blockWidth:G,blockHitOffset:X,hideTrimHandles:J,showAudioLabel:Z}=(z=Math.max(s=H*a,18),{rawBlockWidth:s,blockWidth:z,blockHitOffset:(z-s)/2,hideTrimHandles:s<20,showAudioLabel:z>=60}),{top:Q,height:ee}=S(e.trackId),et=d.includes(e.id),ea=c===e.id,er=j(e.trackId),en=!I(e.trackId),ei=N(e.trackId),es=e.muted??!1,el=ei||es,{audioVolume:ed,audioVolumeLinePercent:ec,audioVolumeLineY:eu,audioFadeInDuration:ep,audioFadeOutDuration:em,audioFadeInPercent:eh,audioFadeOutPercent:ef,showAudioFadeHandles:eg}={audioVolume:(L=lu(e,H)).sceneVolume,audioVolumeLinePercent:L.sceneVolumeLinePercent,audioVolumeLineY:L.sceneVolumeLineY,audioFadeInDuration:L.sceneFadeInDuration,audioFadeOutDuration:L.sceneFadeOutDuration,audioFadeInPercent:L.sceneFadeInPercent,audioFadeOutPercent:L.sceneFadeOutPercent,audioFadeOutStartPercent:Math.max(L.sceneFadeInPercent,100-L.sceneFadeOutPercent),showAudioFadeHandles:Y>=26},ex=y===e.id,eb=su(e,t),ey=sp(e,t,!0,p.size>0?p:void 0),ev=m.get(e.id)||{left:!1,right:!1},ew=!!c&&(e.id===c||!!u?.has(e.id)),{showLeftFlush:ek,showRightFlush:eS}=ll({blockStart:e.start,blockDuration:e.duration,isInDraggedSelection:ew,isCurrentlyDragging:!!c,externalFlushEdges:ey,pulseEdges:ev,draggedEdgePositions:h,tolerance:aj.B_}),ej=aj.si[e.trackId%aj.si.length],eI="off"!==i&&et,eN="neon"===i,eC=eN&&eb.left,eM=eN&&eb.right,{audioBannerHoverLabel:e_,audioBannerRestingLabel:eA}=(B=(O=(F=e.sceneId??e.sourceSceneId)?f.get(F):void 0)?`Scene ${O}`:e.label||"Audio",{audioLinkedSceneId:F,audioSceneNumber:O,audioBannerLabel:B,audioBannerHoverLabel:B,audioBannerRestingLabel:B.length>10?`${B.slice(0,8).trimEnd()}â¦`:B});return(0,r.jsx)("div",{"data-audio-block":!0,className:`absolute group select-none ${er?"opacity-60":""}${en?" opacity-30":""}`,style:{left:V*a-X,top:Q,width:G,height:ee,cursor:er?"not-allowed":"default",transform:ea?"translateY(-1px)":"translateY(0px)",zIndex:ea?50:1},onClick:t=>{C(e.id,t)},onMouseDown:t=>M(t,e),onContextMenu:t=>_(e,t),children:(0,r.jsxs)("div",{className:`absolute top-0 overflow-hidden ${ea?"transition-none":"transition-[box-shadow,background-color,border-color] duration-75 ease-out"}`,style:{left:X,width:Math.max(Y,1),height:ee,borderRadius:5,background:et?`linear-gradient(180deg, ${ej}22 0%, rgba(10,13,20,0.95) 52%, rgba(7,10,17,0.98) 100%)`:`linear-gradient(180deg, ${ej}16 0%, rgba(9,12,19,0.95) 52%, rgba(6,9,16,0.98) 100%)`,border:et?`1px solid ${eI?ej:`${ej}aa`}`:"1px solid rgba(255,255,255,0.07)",boxShadow:et?`0 0 0 1px ${ej}30, 0 0 18px ${ej}38, inset 0 1px 0 rgba(255,255,255,0.08)`:"inset 0 1px 0 rgba(255,255,255,0.045), 0 1px 3px rgba(0,0,0,0.4)",...eI&&{borderStyle:"solid",borderColor:ej,borderWidth:2,borderLeftWidth:2*!eC,borderRightWidth:2*!eM}},children:[(0,r.jsx)("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-[1.5px] z-10",style:{background:ej,opacity:et?.95:.55,boxShadow:et?`0 0 6px ${ej}aa`:"none"},"aria-hidden":"true"}),e.isLoading&&!e.id.startsWith("faceless-ph-music-")&&(0,r.jsx)(oW,{nleSceneId:e.sceneId,blockType:e.type,small:!0}),!e.isLoading&&"voiceover"===e.type&&R&&D?.has(e.id)&&(0,r.jsx)(lp,{inFlight:D.get(e.id)?.inFlight,onRegenerate:()=>R(e.id)}),e.isLoading?(0,r.jsxs)("div",{className:"absolute inset-0 flex items-center justify-center overflow-hidden rounded bg-[#071019]/85",children:[(0,r.jsx)("div",{"aria-hidden":!0,className:"gen-conveyor absolute inset-0",style:{"--gen-stripe":"rgba(56,189,248,0.06)"}}),(0,r.jsxs)("div",{className:"relative flex max-w-full items-center gap-1.5 rounded-md border border-sky-400/20 bg-black/50 px-1.5 py-[2px]",children:[(0,r.jsxs)("span",{className:"gen-dots text-sky-300","aria-hidden":!0,children:[(0,r.jsx)("span",{}),(0,r.jsx)("span",{}),(0,r.jsx)("span",{})]}),(0,r.jsx)("span",{className:"truncate font-mono text-[8px] font-semibold uppercase tracking-[0.16em] text-sky-200/90",children:"voiceover"===e.type?"Generating voiceover":e.id.startsWith("faceless-ph-music-")?"Loading music":"Generating audio"})]})]}):(0,o.LN)()?(0,r.jsx)("div",{className:"absolute inset-0 flex items-center justify-center",children:(0,r.jsx)("span",{className:"text-[10px] text-slate-400 truncate px-2",children:e.label||"Audio"})}):(0,r.jsxs)(r.Fragment,{children:[ek&&(0,r.jsx)("div",{className:"absolute left-0 top-0 w-px h-full pointer-events-none z-20",style:{background:"#ef4444",animation:ev.left?"flushPulse 0.2s ease-out forwards":"none",boxShadow:"0 0 6px rgba(239, 68, 68, 0.9), 0 0 12px rgba(239, 68, 68, 0.5)"}}),eS&&(0,r.jsx)("div",{className:"absolute right-0 top-0 w-px h-full pointer-events-none z-20",style:{background:"#ef4444",animation:ev.right?"flushPulse 0.2s ease-out forwards":"none",boxShadow:"0 0 6px rgba(239, 68, 68, 0.9), 0 0 12px rgba(239, 68, 68, 0.5)"}}),"audio"===e.type&&(()=>{let t=sx(w?.audioArtifacts,e);if(!t?.rhythm?.beatTimes?.length)return null;let n=function(e,t,a=12){if(e.length<2||!(t>0))return e;let r=1,n=(e[e.length-1]-e[0])/(e.length-1);for(;n*r*t<a&&r<e.length;)r*=2;if(1===r)return e;if(n*r*t<a)return[];let i=[];for(let t=0;t<e.length;t+=r)i.push(e[t]);return i}(sb(t.rhythm.beatTimes,{...e,start:V,duration:H,inOffset:q}),a);return 0===n.length?null:(0,r.jsx)("div",{className:"pointer-events-none absolute inset-0 overflow-hidden","data-testid":"audio-block-beat-ticks",children:n.map(e=>(0,r.jsx)("div",{className:"absolute bottom-0 w-px",style:{left:(e-V)*a,height:"28%",backgroundColor:"rgba(255,255,255,0.28)"}},e))})})(),!(0,o.U4)()&&(W=g.has(e.id),U=aj.si[e.trackId%aj.si.length],(0,r.jsxs)("div",{className:`absolute inset-0 overflow-hidden pointer-events-none ${el?"bg-red-900/25":""}`,children:["off"!==i&&!W&&(0,r.jsx)(o6,{start:V,duration:H,color:U}),(0,r.jsx)("div",{style:{position:"absolute",top:0,left:-(q*a),width:(e.fullDuration||H)*a,height:"100%",opacity:el?.3:1},children:(0,r.jsx)(o4,{start:V,duration:H,offset:q,children:t=>(0,r.jsx)(eo,{audioUrl:e.audioUrl,storageKey:e.audioStorageKey,assetRef:e.scene?.audio?.assetRef,persistedAudioAnalysis:w,analysisSource:{sourceType:"voiceover"===e.type?"voiceover":"project_audio",sourceSce
97neId:e.scene?.id,sourceAudioBlockId:e.id,storageKey:e.audioStorageKey},onPersistAudioAnalysisArtifact:k,totalDuration:e.fullDuration||e.duration,audioDuration:e.fullDuration||e.duration,audioStartTime:0,currentTime:Math.max(0,t),liveTimelineStart:V,liveTimelineDuration:H,liveTimeOffset:q,color:el?"#ef4444":"off"!==i?aj.si[e.trackId%aj.si.length]:et||ea?"#60a5fa":"#94a3b8",waveformMode:el?"off":i,inOffset:0,volume:e.volume??1,fadeInDuration:ep,fadeOutDuration:em,fadeEnvelopeStart:q,fadeEnvelopeDuration:H,showClipping:v===e.id,onLoadComplete:t=>{x(a=>{let r=new Set(a);return t?r.add(e.id):r.delete(e.id),r})}})})}),el&&(0,r.jsx)("div",{className:"absolute top-1 right-1 z-10 p-0.5 bg-red-500/80 rounded-sm",title:ei?"Track muted":"Block muted",children:(0,r.jsx)(ob.A,{size:10,className:"text-white"})})]})),ee>=24&&(0,r.jsxs)("div",{className:`absolute z-20 transition-opacity duration-150 ${b===e.id||ex?"opacity-100":"opacity-[0.25] group-hover:opacity-100"}`,style:{top:0,left:n,right:n,bottom:0},children:[eh>.5&&(0,r.jsx)("svg",{className:"absolute pointer-events-none",style:{left:0,top:0,width:`${eh}%`,height:"100%"},viewBox:"0 0 1 1",preserveAspectRatio:"none",children:(0,r.jsx)("path",{d:sP(eu,"in"),fill:"none",stroke:b===e.id?"rgba(250, 204, 21, 0.78)":"rgba(148, 163, 184, 0.55)",strokeWidth:"1",strokeLinecap:"round",style:{vectorEffect:"non-scaling-stroke"}})}),ef>.5&&(0,r.jsx)("svg",{className:"absolute pointer-events-none",style:{right:0,top:0,width:`${ef}%`,height:"100%"},viewBox:"0 0 1 1",preserveAspectRatio:"none",children:(0,r.jsx)("path",{d:sP(eu,"out"),fill:"none",stroke:b===e.id?"rgba(250, 204, 21, 0.78)":"rgba(148, 163, 184, 0.55)",strokeWidth:"1",strokeLinecap:"round",style:{vectorEffect:"non-scaling-stroke"}})}),(0,r.jsx)("div",{className:`${er?"cursor-not-allowed":"cursor-ns-resize"} absolute left-0 right-0`,style:{top:ec,height:8,transform:"translateY(-50%)"},onMouseDown:t=>A(t,e),onDoubleClick:t=>E(t,e),title:`${Math.round(100*ed)}% volume (double-click to reset)`,children:(0,r.jsx)("div",{className:"absolute top-1/2 -translate-y-1/2",style:{left:`${eh}%`,right:`${ef}%`,borderTop:`0.5px solid ${b===e.id?"rgba(250, 204, 21, 0.78)":"rgba(148, 163, 184, 0.55)"}`,boxShadow:b===e.id?"0 0 4px rgba(250, 204, 21, 0.28)":"0 0 1px rgba(15, 23, 42, 0.45)"}})}),eg&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:`${er?"cursor-not-allowed":"cursor-ew-resize"} absolute top-0 bottom-0 w-3 -translate-x-1/2`,style:{left:`${eh}%`},onMouseDown:t=>T(t,e,"in"),onDoubleClick:t=>$(t,e,"in"),title:`Fade in ${ep.toFixed(2)}s (drag left/right)`,children:(0,r.jsx)("div",{className:"absolute w-[0.5px] bg-slate-200/40",style:{left:"50%",top:ec,height:Math.min(20,.3*ee),transform:"translate(-50%, -50%)"}})}),(0,r.jsx)("div",{className:`${er?"cursor-not-allowed":"cursor-ew-resize"} absolute top-0 bottom-0 w-3 -translate-x-1/2`,style:{left:`${100-ef}%`},onMouseDown:t=>T(t,e,"out"),onDoubleClick:t=>$(t,e,"out"),title:`Fade out ${em.toFixed(2)}s (drag left/right)`,children:(0,r.jsx)("div",{className:"absolute w-[0.5px] bg-slate-200/40",style:{left:"50%",top:ec,height:Math.min(20,.3*ee),transform:"translate(-50%, -50%)"}})})]})]}),Z&&(0,r.jsx)("div",{className:"absolute flex items-center justify-between gap-1 pointer-events-none",style:{top:2,left:Math.max(5,n+2),right:Math.max(5,n+2),height:14,zIndex:12},children:(0,r.jsx)("div",{className:"min-w-0 relative flex-1",children:(0,r.jsxs)("div",{className:"relative inline-block w-full align-baseline text-[9px]",children:[(0,r.jsxs)("div",{className:"inline-flex max-w-full items-center gap-1 truncate rounded-[4px] px-1 py-px text-[9px] font-semibold tracking-wide text-white/90 group-hover:opacity-0 transition-opacity duration-150",style:{background:"rgba(4,8,16,0.78)",textShadow:"0 1px 2px rgba(0,0,0,0.7)",boxShadow:"inset 0 0 0 1px rgba(255,255,255,0.09)"},children:[(0,r.jsx)("span",{className:"h-[5px] w-[5px] shrink-0 rounded-full",style:{background:ej,boxShadow:`0 0 4px ${ej}aa`},"aria-hidden":"true"}),(0,r.jsx)("span",{className:"truncate",children:eA})]}),(0,r.jsxs)("div",{className:"absolute left-0 top-0 inline-flex max-w-full items-center gap-1 truncate text-[9px] font-semibold tracking-wide text-white/90 opacity-0 group-hover:opacity-100 transition-opacity duration-150 rounded-[4px] px-1 py-px",style:{zIndex:20,background:"rgba(4,8,16,0.78)",textShadow:"0 1px 2px rgba(0,0,0,0.7)",boxShadow:"inset 0 0 0 1px rgba(255,255,255,0.09)"},children:[(0,r.jsx)("span",{className:"h-[5px] w-[5px] shrink-0 rounded-full",style:{background:ej,boxSh
97adow:`0 0 4px ${ej}aa`},"aria-hidden":"true"}),(0,r.jsx)("span",{className:"truncate",children:e_})]})]})})}),er&&(0,r.jsx)("div",{className:"absolute top-0.5 right-1 z-10 p-0.5 bg-amber-500/80 rounded-sm",title:"Track is locked",children:(0,r.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",className:"text-amber-900",children:[(0,r.jsx)("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"})]})}),!J&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"absolute top-0 left-0 h-full cursor-ew-resize opacity-0 group-hover:opacity-100 transition-opacity z-30",style:{width:n},onMouseDown:t=>P(t,e,"start"),children:[(0,r.jsx)("div",{className:"h-full w-full bg-gradient-to-r from-sky-300/40 via-sky-300/12 to-transparent"}),(0,r.jsx)("div",{className:"absolute left-[3px] top-1/2 h-[38%] w-[2px] -translate-y-1/2 rounded-full bg-sky-100/85 shadow-[0_0_4px_rgba(125,211,252,0.6)]"})]}),(0,r.jsxs)("div",{className:"absolute top-0 right-0 h-full cursor-ew-resize opacity-0 group-hover:opacity-100 transition-opacity z-30",style:{width:n},onMouseDown:t=>P(t,e,"end"),children:[(0,r.jsx)("div",{className:"h-full w-full bg-gradient-to-l from-sky-300/40 via-sky-300/12 to-transparent"}),(0,r.jsx)("div",{className:"absolute right-[3px] top-1/2 h-[38%] w-[2px] -translate-y-1/2 rounded-full bg-sky-100/85 shadow-[0_0_4px_rgba(125,211,252,0.6)]"})]})]})]})]})},e.id)})})}var lh=a(10100),lf=a(25369),lg=a(10108),lx=a(20616);let lb=new Set;function ly(e){return e?e.startsWith("blob:")?"blob":e.startsWith("data:")?"data":e.includes("/api/v1/storage/")||e.includes("/api/storage/")?"proxy":e.startsWith("r2://")?"r2":e.startsWith("http")?"http":"other":"empty"}function lv(e,t,r){let n=`${e}:${t}`;lb.has(n)||(lb.add(n),Promise.resolve().then(a.bind(a,96412)).then(({trackEvent:t})=>t("filmstrip_render_failed",{stage:e,...r})).catch(()=>{}))}let lw="strips";function lk(){return"u">typeof indexedDB}let lS=null;function lj(){return lS||(lS=new Promise((e,t)=>{let a=indexedDB.open("filmstrip-strips-v1",1);a.onupgradeneeded=()=>{let e=a.result;e.objectStoreNames.contains(lw)||e.createObjectStore(lw,{keyPath:"key"})},a.onsuccess=()=>e(a.result),a.onerror=()=>t(a.error??Error("IndexedDB open failed")),a.onblocked=()=>t(Error("IndexedDB open blocked"))})).catch(()=>{lS=null}),lS}function lI(e){return new Promise((t,a)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>a(e.error??Error("IndexedDB request failed"))})}async function lN(e){if(!lk())return null;try{let t=(await lj()).transaction(lw,"readonly"),a=await lI(t.objectStore(lw).get(e));if(!a||!Array.isArray(a.frames)||0===a.frames.length)return null;return lC(e),a}catch{return null}}async function lC(e){try{let t=(await lj()).transaction(lw,"readwrite").objectStore(lw),a=await lI(t.get(e));a&&(a.lastUsedAt=Date.now(),t.put(a))}catch{}}async function lM(e){if(lk())try{let t=e.frames.reduce((e,t)=>e+t.blob.size,0),a={...e,bytes:t,savedAt:Date.now(),lastUsedAt:Date.now()},r=(await lj()).transaction(lw,"readwrite");r.objectStore(lw).put(a),await new Promise((e,t)=>{r.oncomplete=()=>e(),r.onerror=()=>t(r.error??Error("IndexedDB write failed")),r.onabort=()=>t(r.error??Error("IndexedDB write aborted"))}),lA()}catch{}}async function l_(e){if(lk())try{(await lj()).transaction(lw,"readwrite").objectStore(lw).delete(e)}catch{}}async function lA(e=0xc800000){if(lk())try{let t=await lj(),a=t.transaction(lw,"readonly"),r=(await lI(a.objectStore(lw).getAll())).map(e=>({key:e.key,bytes:e.bytes,lastUsedAt:e.lastUsedAt})),n=r.reduce((e,t)=>e+t.bytes,0),i=function(e,t,a=0xc800000){if(t<=a)return[];let r=[...e].sort((e,t)=>e.lastUsedAt-t.lastUsedAt),n=[],i=t;for(let e of r){if(i<=a)break;n.push(e.key),i-=e.bytes}return n}(r,n,e);if(0===i.length)return;let s=t.transaction(lw,"readwrite").objectStore(lw);for(let e of i)s.delete(e)}catch{}}async function lE(e){try{if("u"<typeof OffscreenCanvas)return null;let t=new OffscreenCanvas(e.width,e.height),a=t.getContext("2d");if(!a)return null;return a.drawImage(e,0,0),await t.convertToBlob({type:"image/webp",quality:.75})}catch{return null}}async function lT(e){let t=ly(e);if("proxy"!==t&&"http"!==t)return null;try{let t=new AbortController,a=setTimeout(()=>t.abort(),2500),r={};try{r=(0,S.Wu)(e,await (0,S.getMediaAuthToken)())}catch{}let n=await fetch(e,{...r,headers:{...r.headers,Range:"bytes=0-0"},signal:t.signal});clearTimeout(a);try{n.body?.cancel()}catch{}return n.status}catch{return"probe_failed"}}function l$(e){let t=0;for(let a of e)t+=a.bitmap.width*a.bitmap.height*4;return t}class lP{constructor(e=3,t=1){this.active={immediate:0,background:0},this.queues={immediate:[],background:[]}
97,this.maxImmediate=e,this.maxBackground=t}run(e,t){return new Promise((a,r)=>{let n="immediate"===e?this.maxImmediate:this.maxBackground,i=()=>{this.active[e]+=1,t().then(a).catch(r).finally(()=>{this.active[e]=Math.max(0,this.active[e]-1);let t=this.queues[e].shift();t&&t()})};this.active[e]<n?i():this.queues[e].push(i)})}getActiveCount(e){return this.active[e]}}class lD{touch(e){e.lastUsedAt=Date.now()}async acquirePooledMedia(e,t){let a=this.mediaPool.get(e);if(a)return a.lastUsedAt=Date.now(),{pooled:a,reused:!0};let r=await (0,S.getMediaAuthToken)(),n=(0,S.Wu)(t,r),i=new lh.pd({source:new lf.Ts(t,{requestInit:n}),formats:lg.XE});await i.ready;let s=await i.getPrimaryVideoTrack();if(!s){try{i.dispose()}catch{}throw Error("No video track found")}let[o,l,d]=await Promise.all([s.computeDuration(),s.getDisplayWidth(),s.getDisplayHeight()]),c=Math.max(1,Math.round(128*(l/d||1))),u={input:i,canvasSink:new lx.Yy(s,{width:c,height:128,fit:"cover",poolSize:2}),duration:o,width:l,height:d,lastUsedAt:Date.now(),chain:Promise.resolve(),busy:0};return this.mediaPool.set(e,u),this.evictPooledMedia(),{pooled:u,reused:!1}}invalidatePooledMedia(e){let t=this.mediaPool.get(e);if(t){this.mediaPool.delete(e);try{t.input.dispose()}catch{}}}evictPooledMedia(){if(!(this.mediaPool.size<=4))for(let[e]of Array.from(this.mediaPool.entries()).filter(([,e])=>0===e.busy).sort((e,t)=>e[1].lastUsedAt-t[1].lastUsedAt)){if(this.mediaPool.size<=4)break;this.invalidatePooledMedia(e)}}async runOnPooledMedia(e,t){let a;e.busy+=1;let r=e.chain;e.chain=new Promise(e=>{a=e});try{return await r,await t()}finally{a(),e.busy=Math.max(0,e.busy-1),e.lastUsedAt=Date.now()}}getFrames(e){let t=this.cache.get(e);return!t||t.loading?null:(this.touch(t),t.frames)}getTimestamps(e){let t=this.cache.get(e);return!t||t.loading?null:(this.touch(t),t.timestamps)}getFrameAtTime(e,t){let a=this.cache.get(e);if(!a||a.loading||0===a.frames.length)return null;this.touch(a);let r=a.timestamps,n=0,i=r.length;for(;n<i;){let e=n+i>>1;r[e]<t?n=e+1:i=e}let s=Math.min(r.length-1,n),o=Math.max(0,s-1),l=Math.abs(r[o]-t)<=Math.abs(r[s]-t)?o:s;return a.frames[l].bitmap}findCoveringUpgrade(e,t,a,r){let n=null,i=1/0;for(let[o,l]of this.cache){var s;l.upgrade&&!l.loading&&0!==l.frames.length&&(s=l.upgrade,s.baseKey===e&&s.rangeStart<=t+.001&&s.rangeEnd>=a-.001&&s.intervalSec<=r+.001&&l.upgrade.intervalSec<i&&(i=l.upgrade.intervalSec,n=o))}return n}getUpgradeFrames(e,t,a,r,n){if(t){let e=this.getFrames(t);if(e&&e.length>0)return e}let i=this.findCoveringUpgrade(e,a,r,n);return i?this.getFrames(i):null}isLoading(e){let t=this.cache.get(e);return t?.loading??this.loadingPromises.has(e)}isCached(e){let t=this.cache.get(e);return void 0!==t&&!t.loading&&t.frames.length>0}async extractFrames(e,t,a){let r=t||e;if(this.isCached(e)||a?.upgradeMeta&&this.findCoveringUpgrade(a.upgradeMeta.baseKey,a.upgradeMeta.rangeStart,a.upgradeMeta.rangeEnd,a.upgradeMeta.intervalSec))return;let n=this.loadingPromises.get(e);if(n)return n;let i=this.scheduler.run(a?.priority??"immediate",()=>this.doExtractFrames(e,r,a));this.loadingPromises.set(e,i);try{await i}finally{this.loadingPromises.delete(e)}}async doExtractFrames(e,t,a){let r=a?.intervalSec??1,n=a?.maxFrames??100,i=a?.onProgress,s=a?.storageKey,o=t;try{let e=await (0,S.resolveMediaUrl)(t,s);e&&(o=e)}catch(e){console.warn("[FilmstripFrameCache] Failed to resolve media URL",e)}let l=o.includes("/api/v1/storage/")||o.includes("/api/storage/");if(!o){lv("extraction",e,{reason:"Signed media URL not available",url_kind:ly(t),has_storage_key:!!s});let a=this.cache.get(e);a&&(a.loading=!1,a.error="Signed media URL not available");return}if(l&&!s){console.error("[PROXY-URL-TRIPWIRE]",{cacheKey:e,finalFetchUrl:o}),console.trace("[PROXY-URL-TRACE]"),lv("extraction",e,{reason:"Proxy media URL blocked",url_kind:"proxy",has_storage_key:!1});let t=this.cache.get(e);t&&(t.loading=!1,t.error="Proxy media URL blocked");return}l&&s&&Z(`filmstrip-proxy-fallback:${e}`,"[FilmstripFrameCache] Using proxy media URL fallback for extraction",{cacheKey:e}),this.disposeEntry(e),this.cache.set(e,{url:e,frames:[],timestamps:[],duration:0,width:0,height:0,loading:!0,error:null,bytes:0,lastUsedAt:Date.now(),upgrade:a?.upgradeMeta});let d=a?.upgradeMeta||a?.startSec!==void 0||a?.endSec!==void 0?null:`${e}|i${r.toFixed(3)}|n${n}|h128`;if(d&&await this.hydratePersistedStrip(e,d))return;let c=a?.upgradeMeta?.baseKey??e,u=[],p=async t=>{let{pooled:s}=await this.acquirePooledMedia(c,t);await this.runOnPooledMedia(s,async()=>{let t=this.cache.get(e);if(!t)return;t.duration=s.duration,t.width=s.width,t.height=s.height;let o=Math.max(0,Math.min(a?.startSec??0,s.duration)),l=Math.max(0,Math.max(o,Math.min(a?.endSec??s.duration,s.duration))-o);if(l<=0)return;let d=Math.max(1,Math.min(n,Math.ceil(l/Math.max(r,.01)))),c=[];for(let e=0;e<d;e++){let t=(e+.5)/d;c.push(o+t*l)}let p=0;
97for await(let e of s.canvasSink.canvasesAtTimestamps(c)){if(p+=1,!e){i&&i(p/c.length);continue}let t=await createImageBitmap(e.canvas);u.push({timestamp:e.timestamp,bitmap:t}),i&&i(p/c.length)}})},m=this.mediaPool.has(c);try{try{await p(o)}catch(a){if(this.invalidatePooledMedia(c),!m)throw a;for(let e of u.splice(0))try{e.bitmap.close()}catch{}let e=o;try{let a=await (0,S.resolveMediaUrl)(t,s);a&&(e=a)}catch{}await p(e)}let a=this.cache.get(e);if(!a)return;a.frames=u,a.timestamps=u.map(e=>e.timestamp),a.bytes=l$(u),a.lastUsedAt=Date.now(),a.loading=!1,this.totalBytes+=a.bytes,this.enforceBudget(),d&&u.length>0&&this.persistBaseStrip(d,a),console.log(`[FilmstripFrameCache] â
Extracted ${u.length} frames for ${e} (fetch: ${o.slice(0,80)}...)`)}catch(n){console.error("[FilmstripFrameCache] Extraction error:",n);let t=await lT(o);lv("extraction",e,{reason:"string"==typeof n?.message?n.message.slice(0,160):"unknown",url_kind:ly(o),has_storage_key:!!s,had_pooled_pipeline:m,frames_extracted:u.length,is_upgrade:!!a?.upgradeMeta,probe_status:t}),ee({source:"filmstrip",url:o,mediaId:s??e,error:n});let r=this.cache.get(e);r&&(r.frames=u,r.timestamps=u.map(e=>e.timestamp),r.bytes=l$(u),this.totalBytes+=r.bytes,r.loading=!1,r.error=n.message)}}async hydratePersistedStrip(e,t){let a=await lN(t);if(!a)return!1;let r=[];try{for(let e of a.frames){let t=await createImageBitmap(e.blob);r.push({timestamp:e.timestamp,bitmap:t})}}catch{for(let e of r)try{e.bitmap.close()}catch{}return l_(t),!1}let n=this.cache.get(e);if(!n){for(let e of r)e.bitmap.close();return!1}return n.frames=r,n.timestamps=r.map(e=>e.timestamp),n.duration=a.duration,n.width=a.width,n.height=a.height,n.bytes=l$(r),n.lastUsedAt=Date.now(),n.loading=!1,this.totalBytes+=n.bytes,this.enforceBudget(),console.log(`[FilmstripFrameCache] â»ï¸ Hydrated ${r.length} frames for ${e} from IndexedDB`),!0}async persistBaseStrip(e,t){try{let a=[];for(let e of t.frames){let t=await lE(e.bitmap);t&&a.push({timestamp:e.timestamp,blob:t})}if(0===a.length)return;await lM({key:e,duration:t.duration,width:t.width,height:t.height,frames:a})}catch{}}disposeEntry(e){let t=this.cache.get(e);if(t){for(let e of t.frames)try{e.bitmap.close()}catch{}this.totalBytes=Math.max(0,this.totalBytes-t.bytes),this.cache.delete(e)}}enforceBudget(){if(this.totalBytes<=0xa000000)return;let e=Date.now(),t=[];for(let[e,a]of this.cache)t.push({key:e,bytes:a.bytes,lastUsedAt:a.lastUsedAt,isUpgrade:!!a.upgrade,loading:a.loading});let a=function(e,t,a,r=1500){if(t<=0xa000000)return[];let n=e.filter(e=>!e.loading&&a-e.lastUsedAt>r).sort((e,t)=>e.isUpgrade!==t.isUpgrade?e.isUpgrade?-1:1:e.lastUsedAt-t.lastUsedAt),i=[],s=t;for(let e of n){if(s<=0xa000000)break;i.push(e.key),s-=e.bytes}return i}(t,this.totalBytes,e);for(let e of a)this.disposeEntry(e);a.length>0&&console.log(`[FilmstripFrameCache] Evicted ${a.length} strips (${Math.round(this.totalBytes/1048576)}MB in pool)`)}clearCache(e){this.disposeEntry(e)}clearAll(){for(let e of Array.from(this.cache.keys()))this.disposeEntry(e);for(let e of Array.from(this.mediaPool.keys()))this.invalidatePooledMedia(e)}getStats(){let e=0;for(let t of this.cache.values())e+=t.frames.length;return{urls:this.cache.size,totalFrames:e,totalBytes:this.totalBytes}}constructor(){this.cache=new Map,this.loadingPromises=new Map,this.scheduler=new lP,this.totalBytes=0,this.mediaPool=new Map}}let lR=new lD,lz=(e,t,a=0,r=e.length)=>{let n=a,i=r;for(;n<i;){let a=n+i>>1;e[a]<t?n=a+1:i=a}return n},lL=(e,t,a,r)=>{if(t>=a)return -1;let n=Math.min(a-1,lz(e,r,t,a)),i=Math.max(t,n-1);return Math.abs(e[i]-r)<=Math.abs(e[n]-r)?i:n};function lF(e,t,a,r){if(0===e.length||r<=0)return[];let n=t+Math.max(0,a),i=Math.min(r,e.length),s=Math.max(0,lz(e,t)-1),o=Math.min(e.length,lz(e,n)+1);for(s>=o&&(s=0,o=e.length);o-s<i;){let t=s>0,a=o<e.length;if(!t&&!a||(t&&(s-=1),o-s>=i))break;a&&(o+=1)}let l=o-s;if(l<=0)return[];if(l<r)return Array.from({length:r},(e,t)=>s+Math.min(l-1,Math.floor((t+.5)/r*l)));let d=[],c=s-1;for(let n=0;n<r;n++){let i=lL(e,s,o,t+(n+.5)/r*a),l=Math.max(c+1,Math.min(o-(r-n-1)-1,i));d.push(l),c=l}return d}let lO=i.memo(function({bitmap:e}){let t=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let a=t.current;if(!a||!e||0===e.width)return;a.width=e.width,a.height=e.height;let r=a.getContext("2d");r&&r.drawImage(e,0,0)},[e]),(0,r.jsx)("canvas",{ref:t,className:"w-full h-full"})}),lB=[{id:"max",minPxPerSec:96,densityMultiplier:4,minFrames:72,maxFrames:180},{id:"high",minPxPerSec:48,densityMultiplier:3,minFrames:48,maxFrames:120},{id:"medium",minPxPerSec:24,densityMultiplier:2,minFrames:24,maxFrames:72}],lW=(e,t,a)=>{let r=Math.max(1,e.width),n=Math.max(0,Math.min(t,e.start)),i=Math.max(0,Math.min(e.duration,Math.max(0,t-n))),s=Math.max(1,2*Math.round(Math.max(1,Math.floor(r/72))/2)),o=Math.min(60,Math.max(6,s)),l=t>0?Math.max(.25,t/o):1,d=t>0?r/t:0,c=Math.min(t,n+i),u=t>0?Math.max(0,Math.floor(n/t*s)):0,p=t>0?Math.max(u,Math.min(s-1,Math.ceil(c/t*s)-1)):s-1,m=i>0?Math.max(1,p-u+1):0,h=lB.find(e=>d>=e.minPxPerSec)??null,f=h&&m>0?Math.max(h.minFrames,Math.min(h.maxFrames,12*Math.ceil(Math.max(m+2,m*h.densityMultiplier)/12))):0,g=f>0&&i>0?Math.max(.08,i/f):0,x=Math.max(.5,2*g),b=Math.max(.25,2*g),y=f>0?Math.max(0,Math.floor(n/b)*b-x):0,v=f>0?Math.min(t,Math.ceil(c/b)*b+x):0,w=a&&h&&f>0&&v>y?`${a}::filmstrip-upgrade:${h.id}:${f}:${y.toFixed(2)}-${v.toFixed(2)}`:"";return{width:r,visibleRangeStart:n,visibleRangeDuration:i,visibleRangeEnd:c,frameCount:s,targetFrameCount:o,intervalSec:l,pixelsPerSecond:d,visibleCellStart:u,visibleCellEnd:p,visibleCellCount:m,upgradeTier:h,upgradeFrameCount:f,upgradeIntervalSec:g,upgradeRangeStart:y,upgradeRangeEnd:v,upgradeCacheKey:w}},lU=i.memo(({mediaUrl:e,width:t,duration:n,inOffset:s,isVideo:l,blobUrl:d,thumbnailUrl:c,sceneTitle:u,isLoading:p=!1,storageKey:m,assetRef:h,visibleRangeStart:f,visibleRangeDuration:g})=>{let x=(0,i.useRef)(null),[b,v]=(0,i.useState)(!1),[,w]=(0,i.useState)(0),k=(0,y.zC)(e=>e.isPlaying),[j,I]=(0,i.useState)(!1),[N,M]=(0,i.useState)(()=>new Set),_=(e,t)=>
97{lv("image_load",e,{reason:t,url_kind:ly(e)}),e.startsWith("blob:")&&Promise.resolve().then(a.bind(a,32701)).then(({discardDeadBlobUrl:t})=>t(e)).catch(()=>{}),M(t=>{if(t.has(e))return t;let a=new Set(t);return a.add(e),a})},A=(0,i.useRef)(void 0),E=(0,i.useRef)(void 0),T=e=>!!e&&(e.includes("/api/v1/storage/")||e.includes("/api/storage/")||e.startsWith("r2://")),$=e=>e&&!T(e)?e:"",P=$(d),D=$(e),R=$(c),z=m||(e?(0,S.extractStorageKeyFromUrl)(e)??void 0:void 0),L=P||e||D,F=z||e||P||"",O=[R,D,P].some(e=>e&&!N.has(e)),B=!l&&!O&&!!(z||h||c||e),{authorizedMediaUrl:W}=C(B?c||e:void 0,void 0,B?z:void 0,void 0,B?h:void 0),U=(e,t=!1)=>(0,r.jsxs)("div",{ref:x,className:"absolute inset-0 overflow-hidden bg-[#050a14]",children:[(0,r.jsx)("div",{className:"absolute inset-0 z-10 pointer-events-none bg-[linear-gradient(180deg,rgba(5,10,24,0.18)_0%,rgba(5,10,24,0.04)_48%,rgba(5,10,24,0.22)_100%)]"}),(0,r.jsx)("div",{className:"absolute inset-x-0 top-0 z-10 h-[36%] pointer-events-none bg-gradient-to-b from-black/20 to-transparent"}),(0,r.jsx)("div",{className:"absolute inset-x-0 bottom-0 z-10 h-[28%] pointer-events-none bg-gradient-to-t from-[#050a14]/50 to-transparent"}),(0,r.jsx)("div",{className:"relative z-0 w-full h-full flex",style:t?{filter:"brightness(0.88) saturate(1.08) contrast(1.06)"}:void 0,children:e})]}),K=Math.max(0,Math.min(n,f??s)),V=Math.max(0,Math.min(g??Math.max(0,n-K),n-K)),H=(0,i.useRef)(null),q=(0,i.useRef)({width:Math.max(1,Math.round(t)),start:K,duration:V}),[Y,G]=(0,i.useState)(()=>q.current),[X,J]=(0,i.useState)(()=>q.current),Z=(0,i.useRef)(()=>{});Z.current=()=>{H.current&&clearTimeout(H.current),H.current=setTimeout(()=>{let e=q.current;G(t=>1>Math.abs(t.width-e.width)&&.01>Math.abs(t.start-e.start)&&.01>Math.abs(t.duration-e.duration)?t:{...e})},200)},(0,i.useEffect)(()=>{let e=x.current;if(!e)return;let t=new ResizeObserver(([e])=>{let t=Math.round(e.contentRect.width);t<1||(q.current={...q.current,width:t},Z.current())});return t.observe(e),()=>{t.disconnect(),H.current&&clearTimeout(H.current)}},[]),(0,i.useEffect)(()=>{q.current={...q.current,start:K,duration:V},Z.current()},[K,V]);let Q=(0,i.useMemo)(()=>lW(Y,n,F),[Y,n,F]),ee=(0,i.useMemo)(()=>lW(X,n,F),[X,n,F]),et=!!F&&lR.isCached(F),ea=!!F&&lR.isLoading(F),er=!!Q.upgradeCacheKey&&lR.isCached(Q.upgradeCacheKey),en=!!Q.upgradeCacheKey&&lR.isLoading(Q.upgradeCacheKey),ei=F?lR.getFrames(F):null,es=F?lR.getTimestamps(F):null,eo=ee.upgradeCacheKey?lR.getUpgradeFrames(F,ee.upgradeCacheKey,ee.visibleRangeStart,ee.visibleRangeEnd,1.25*ee.upgradeIntervalSec):null,el=(0,i.useMemo)(()=>eo?.map(e=>e.timestamp)??null,[eo]),ed=(0,i.useMemo)(()=>!es||ee.visibleCellCount<=0||ee.visibleRangeDuration<=0?null:lF(es,ee.visibleRangeStart,ee.visibleRangeDuration,ee.visibleCellCount),[es,ee.visibleCellCount,ee.visibleRangeStart,ee.visibleRangeDuration]),ec=(0,i.useMemo)(()=>ed?.map(e=>ei?.[e]?.bitmap??null)??null,[ei,ed]),eu=(0,i.useMemo)(()=>!el||ee.visibleCellCount<=0||ee.visibleRangeDuration<=0?null:lF(el,ee.visibleRangeStart,ee.visibleRangeDuration,ee.visibleCellCount),[el,ee.visibleCellCount,ee.visibleRangeStart,ee.visibleRangeDuration]),ep=(0,i.useMemo)(()=>eu?.map(e=>eo?.[e]?.bitmap??null)??null,[eu,eo]),em=!Q.upgradeCacheKey||er||!!lR.findCoveringUpgrade(F,Q.visibleRangeStart,Q.visibleRangeEnd,1.25*Q.upgradeIntervalSec);(0,i.useEffect)(()=>{1>Math.abs(X.width-Y.width)&&.01>Math.abs(X.start-Y.start)&&.01>Math.abs(X.duration-Y.duration)||(et?em&&J({...Y}):J({...Y}))},[X,Y,et,em]),(0,i.useEffect)(()=>{let e=x.current;if(!e)return;let t=new IntersectionObserver(([e])=>I(e.isIntersecting),{rootMargin:"200px 0px"});return t.observe(e),()=>t.disconnect()},[]),(0,i.useEffect)(()=>{void 0!==E.current&&E.current!==F&&(v(!1),A.current=void 0,J({...q.current})),E.current=F},[F]),(0,i.useEffect)(()=>{if(k||!j||!l||!F||et||ea)return;let e=!!P&&P.startsWith("blob:");if(!(L||z)||p&&!e&&!z)return;let t=L||void 0,a=A.current?.startsWith("blob:")??!1;if(b){if(!e||a)return;console.warn("[Filmstrip] blobUrl arrived - retrying extraction")}(!(L&&T(L))||z)&&(v(!0),A.current=t,lR.extractFrames(F,L||void 0,{intervalSec:Q.intervalSec,maxFrames:Q.targetFrameCount,storageKey:z}).then(()=>{w(e=>e+1)}).catch(()=>{}))},[k,j,F,L,d,z,l,p,et,ea,b,Q.intervalSec,Q.targetFrameCount,P]),(0,i.useEffect)(()=>
97{if(k||!j||!l||!F||!Q.upgradeCacheKey||!et||er||en||Q.visibleRangeDuration<=0||Q.upgradeFrameCount<=0||Q.upgradeIntervalSec<=0)return;let e=!!P&&P.startsWith("blob:");(L||z)&&(!p||e||z)&&(!(L&&T(L))||z)&&lR.extractFrames(Q.upgradeCacheKey,L||void 0,{intervalSec:Q.upgradeIntervalSec,maxFrames:Q.upgradeFrameCount,storageKey:z,startSec:Q.upgradeRangeStart,endSec:Q.upgradeRangeEnd,priority:"background",upgradeMeta:{baseKey:F,rangeStart:Q.upgradeRangeStart,rangeEnd:Q.upgradeRangeEnd,intervalSec:Q.upgradeIntervalSec}}).then(()=>{w(e=>e+1)}).catch(()=>{})},[k,j,l,F,Q.upgradeCacheKey,et,er,en,Q.visibleRangeDuration,Q.upgradeFrameCount,Q.upgradeIntervalSec,Q.upgradeRangeStart,Q.upgradeRangeEnd,L,z,p,P]);let eh=(0,i.useMemo)(()=>et?Array.from({length:ee.frameCount}).map((e,t)=>{let a=s+(t+.5)/ee.frameCount*n,i=t>=ee.visibleCellStart&&t<=ee.visibleCellEnd?t-ee.visibleCellStart:-1,o=(i>=0?ep?.[i]:null)||(i>=0?ec?.[i]:null)||lR.getFrameAtTime(F,a);return(0,r.jsx)("div",{className:"relative overflow-hidden border-r border-sky-100/10 last:border-r-0",style:{width:`${100/ee.frameCount}%`,height:"100%"},children:o?(0,r.jsx)(lO,{bitmap:o}):(0,r.jsx)("div",{className:"w-full h-full bg-slate-800"})},t)}):null,[et,ee,ec,ep,F,s,n]);if(p)return U((0,r.jsx)("div",{className:"w-full h-full bg-gradient-to-r from-slate-700 via-slate-600 to-slate-700 flex items-center justify-center",children:(0,r.jsx)("span",{className:"text-[10px] text-white/40 truncate px-1",children:u})}));if(!l){let e=[R,D,P,W].find(e=>e&&!N.has(e))||"";return U((0,r.jsx)(r.Fragment,{children:Array.from({length:ee.frameCount}).map((t,n)=>(0,r.jsx)("div",{className:"relative overflow-hidden border-r border-sky-100/10 last:border-r-0",style:{width:`${100/ee.frameCount}%`,height:"100%"},children:e?(0,r.jsx)("img",{src:e,className:"w-full h-full object-cover brightness-[0.86] saturate-[1.08] contrast-[1.06]",alt:"",loading:"lazy",draggable:!1,onError:()=>_(e,"image"),onLoad:()=>{if(0!==N.size){var t;let r;t={stage:"image_load",url_kind:ly(e),failed_candidates:N.size},r=`recovery:${e}`,lb.has(r)||(lb.add(r),Promise.resolve().then(a.bind(a,96412)).then(({trackEvent:e})=>e("filmstrip_render_recovered",t)).catch(()=>{}))}}}):(0,r.jsx)("div",{className:"w-full h-full bg-slate-700"})},n))}))}if(!et){let e=!L||T(L),t=R&&!N.has(R)?R:"",a=!t&&!(0,o.Jy)()&&!e;return U((0,r.jsxs)(r.Fragment,{children:[a&&(0,r.jsx)("video",{src:L+"#t=0.1",className:"absolute inset-0 w-full h-full object-cover brightness-[0.84] saturate-[1.06] contrast-[1.04]",muted:!0,preload:"metadata",playsInline:!0,style:{pointerEvents:"none"}}),Array.from({length:ee.frameCount}).map((e,n)=>(0,r.jsx)("div",{className:"relative overflow-hidden border-r border-sky-100/10 last:border-r-0",style:{width:`${100/ee.frameCount}%`,height:"100%"},children:t?(0,r.jsx)("img",{src:t,className:"w-full h-full object-cover brightness-[0.84] saturate-[1.06] contrast-[1.04]",alt:"",loading:"lazy",draggable:!1,onError:()=>_(t,"poster_thumbnail")}):a?null:(0,r.jsx)("div",{className:"w-full h-full bg-slate-800 flex items-center justify-center text-slate-600 text-[8px]",children:"\uD83C\uDFAC"})},n))]}))}return U(eh,!0)},(e,t)=>e.width!==t.width&&e.mediaUrl===t.mediaUrl&&e.duration===t.duration&&e.inOffset===t.inOffset&&e.isVideo===t.isVideo&&e.blobUrl===t.blobUrl&&e.thumbnailUrl===t.thumbnailUrl&&e.sceneTitle===t.sceneTitle&&e.isLoading===t.isLoading&&e.storageKey===t.storageKey&&e.assetRef===t.assetRef&&e.visibleRangeStart===t.visibleRangeStart&&e.visibleRangeDuration===t.visibleRangeDuration);function lK(e,t){let a=e.inOffset,r=e.inOffset+e.duration,n=()=>{window.removeEventListener("touchend",n),window.removeEventListener("touchcancel",n),setTimeout(()=>{let n=y.zC.getState().blocks.find(t=>t.id===e.id);if(!n)return;let i="start"===t?n.inOffset-a:n.inOffset+n.duration-r;(0,ey.trackEvent)("timeline_mobile_trim_used",{via:"handle",direction:"start"===t?"in":"out",delta_ms:Math.round(1e3*i)})},0)};window.addEventListener("touchend",n),window.addEventListener("touchcancel",n)}function lV({blocks:e,showTrack0:t,zoomLevel:n,trimHandleWidth:i,waveformMode:s,blockCullingViewport:l,visibleRange:d,localTrimPreview:c,selectedSceneIds:u,draggingId:p,trimmingId:m,initialSelectionBlocks:h,dragSelectionBlockIds:f,flushPulseEdges:g,draggedEdgePositions:x,sceneNumberBySceneId:b,sceneBlobUrls:y,localGeneratingIds:v,facelessGeneratingNleIds:w,touchHighlightedSceneId:k,splitRegenerateNleSceneId:S,setSplitRegenerateNleSceneId:j,blocksWithWaveform:I,blocksWithoutWaveform:N,setBlocksWithWaveform:C,setBlocksWithoutWaveform:M,activeVolumeDragBlockId:_,activeAudioFadeDragBlockId:A,contextMenuBlockId:E,persistedAudioAnalysis:T,persistAudioAnalysisArtifact:$,setHoveredMediaKey:P,clearHoveredMediaKey:D,getTrackContentLayout:R,isTrackLocked:z,isTrackVisible:L,isTrackMuted:F,handleSceneClick:O,handleBlockMouseDown:B,handleBlockTouchStart:W,handleBlockTouchMove:U,handleBlockTouchEnd:K,handleSceneContextMenu:V,handleApplyEffect:H,handleVolumeLineMouseDown:q,handleVolumeLineDoubleClick:Y,handleAudioFadeHandleMouseDown:G,handleAudioFadeHandleDoubleClick:X,handleTrimMouseDown:J,handleTrimTouchStart:Z}){return(0,r.jsx)(r.Fragment,{children:e.filter(e=>("scene"===e.type||void 0===e.type)&&e.scene&&(t||(e.trackId??1)!==0)&&(e.id===p||e.id===c?.id||h?.has(e.sceneId)||u.includes(e.sceneId)||nM(e.start,e.duration,n,l))).map((t,l)=>{var Q;let ee,et,ea,er,en,ei,es,ec,eu,ep,em,eh,ef,eg,ex,eb,ey,ev,ew,ek,eS,ej=t.scene,eI=c&&c.id===t.id,eN=eI?c.start:t.start,eC=eI?c.duration:t.duration,{rawBlockWidth:eM,blockHitWidth:e_,blockHitOffset:eA,hideTrimHandles:eE,showSceneLabel:eT,showSceneLockIndicator:e$}=(et=Math.max(ee=Math.max(eC*n,1),18),{rawBlockWidth:ee,blockHitWidth:et,blockHitOffset:(et-ee)/2,hideTrimHandles:ee<20,showSceneLabel:ee>=34,showSceneLockIndicator:ee>=22}),eP=ej.media?.thumbnailUrl||ej.media?.storedUrl,eD=ej.media?.url||ej.media?.storedUrl,eR=ej.media?.type==="video",{sceneHasAudioSource:ez,showSceneVolumeLine:eL,showSceneFadeHandles:eF}=function(e){let{scene:t,rawBlockWidth:a,blockId:r,blocksWithoutWaveform:n}=e,i=t.media?.type==="video",s=!!(t.audio?.persistentUrl||t.audio?.audio_url||t.audio?.storageKey||t.audio?.storage_key||t.audio?.assetRef||t.audio?.audio_base64),o=!!(i||s),l=!s&&n.has(r),d=o&&!l;return{hasExplicitSceneAudioSource:s,sceneHasAudioSource:o,sceneKnownNoAudio:l,showSceneVolumeLine:d,showSceneFadeHandles:d&&a>=26}}({scene:ej,rawBlockWidth:eM,blockId:t.id,blocksWithoutWaveform:N}),eO=u.includes(t.sceneId),eB=y?.[ej.id],eW=ej.media?.storageKey||ej.media?.storage_key,eU=eB||ej.audio?.persistentUrl||ej.audio?.audio_url||eD,eK=ej.audio?.storageKey||ej.audio?.storage_key,eV=ej.audio?.assetRef,eH=ej.media?.status==="generating"||v.has(ej.id)||w.has(ej.id),eq=!0===ej.facelessBlocked,eY=eq&&!0===ej.facelessUpgradeRequired,eG=eq&&!eY&&!0===ej.facelessInterrupted,eX=ej.isLoading||eH||eq||ej.media?.status==="uploading"&&!ej.media?.url&&!ej.media?.storageKey,eJ=t.trackId??1,eZ=F(eJ),eQ=t.muted??!1,e0=eZ||eQ,e1=!L(eJ),{top:e5,height:e2}=R(eJ),e4=z(eJ),{sceneVolume:e3,sceneVolumeLinePercent:e8,sceneVolumeLineY:e6,sceneFadeInDuration:e9,sceneFadeOutDuration:e7,sceneFadeInPercent:te,sceneFadeOutPercent:tt}=lu(t,eC),ta=A===t.id,tr=b.get(t.sceneId)??l+1,tn=((e,t)=>{let a=e.title?.trim?.();if(a)return a;let r=e.media?.originalUrl||e.media?.storedUrl||e.media?.url||e.audio?.audio_url;return r?.split("/").pop()?.split("?")[0]?.trim()||`Scene ${t+1}`})(ej,tr-1),{blockChromePadding:ti,audioHeightPx:ts,audioTop:to,audioVisiblePx:tl,audioEffectivelyHidden:td,vizHeaderH:tc,vizFilmTop:tu,vizFilmH:tp}=function(e){let{blockHeight:t,showSceneVolumeLine:a}=e,r=Math.max(2,Math.min(4,.03*t)),n=Math.max(2,Math.min(3,.02*t)),i=t-2*r-12-2*n,s=Math.max(14,Math.min(58,.64*i)),o=Math.max(a?16:10,i-s),l=r+12+n,d=l+s+n,c=Math.max(0,t-d),u=Math.min(1,Math.max(0,(16-c)/8)),p=12-Math.round(12*u),m=r+p+(p>0?n:0),h=Math.max(4,t-m-r);return{blockChromePadding:r,blockSectionGap:n,headerHeightPx:12,filmstripHeightPx:s,audioHeightPx:o,filmstripTop:l,audioTop:d,audioVisiblePx:c,headerCollapseFraction:u,audioEffectivelyHidden:c<=8,vizHeaderH:p,vizFilmTop:m,vizFilmH:s+(h-s)*u}}({blockHeight:e2,showSceneVolumeLine:eL}),tm=Math.max(ti+4,i+2),th=ti+17,tf=eq&&eT&&e2>=th+26,tg=!!p&&(t.id===p||!!h?.has(t.sceneId)),tx=su(t,e),tb=sp(t,e,!0,f.size>0?f:void 0),ty=g.get(t.id)||{left:!1,right:!1},{showLeftFlush:tv,showRightFlush:tw}=ll({blockStart:t.start,blockDuration:t.duration,isInDraggedSelection:tg,isCurrentlyDragging:!!p,externalFlushEdges:tb,pulseEdges:ty,draggedEdgePositions:x,tolerance:aj.B_}),tk=t.sceneId.startsWith("__track0")?null:ed(ej),tS=aj.si[eJ%aj.si.length],tj="off"!==s&&eO,tI="neon"===s,tN=tI&&tx.left,tC=tI&&tx.right;return(0,r.jsxs)("div",{"data-scene-block":!0,"data-scene-id":t.sceneId,className:`absolute group select-none ${e4?"opacity-60":""}${e1?" opacity-30":""}${k===t.sceneId?" ring-2 ring-sky-400/70":""}
97`,style:{left:eN*n-eA,top:e5,width:e_,height:e2,cursor:eX?"wait":e4?"not-allowed":"default",...tg&&{transform:"translateY(-1px)",filter:"saturate(1.08)"},zIndex:tg?60:eO?5:1},onClick:e=>!eX&&O(t.sceneId,e),onMouseDown:e=>!eX&&B(e,t),onTouchStart:e=>!eX&&W(e,t),onTouchMove:e=>!eX&&U(e,t),onTouchEnd:()=>K(t),onTouchCancel:()=>K(t),onMouseEnter:()=>{!tk||p||m||P(tk)},onMouseLeave:e=>{if(!tk)return;let t=e.relatedTarget;t instanceof Element&&t.closest("[data-scene-block]")||D()},onContextMenu:e=>!eX&&V(t,e),onDragOver:e=>{e.dataTransfer.types.includes("application/x-effect-type")&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},onDrop:e=>{e.preventDefault();let r=e.dataTransfer.getData("application/x-effect-type");r&&Promise.resolve().then(a.bind(a,74698)).then(({getEffectDefinition:e})=>{let n=e(r);n&&(n.createEffect?H(t.sceneId,n.createEffect()):Promise.resolve().then(a.bind(a,12458)).then(({generateId:e})=>{H(t.sceneId,{id:e(),type:r,params:{...n.defaultParams},enabled:!0})}))})},children:[(0,r.jsx)("div",{className:"absolute top-0 overflow-hidden",style:{left:eA,width:eM,height:e2,cursor:eX?"wait":e4?"not-allowed":"default",borderRadius:5,background:eX?"linear-gradient(180deg, rgba(22,28,40,0.94) 0%, rgba(9,13,22,0.96) 100%)":"inverted"===s?`linear-gradient(180deg, ${tS}0c 0%, ${tS}08 100%)`:"linear-gradient(180deg, rgba(6,10,18,0.97) 0%, rgba(4,8,16,0.98) 100%)",border:eO?`1px solid ${tj?`${tS}88`:"rgba(96, 165, 250, 0.65)"}`:"1px solid rgba(255, 255, 255, 0.07)",boxShadow:eO?`0 0 0 1px ${tj?`${tS}30`:"rgba(96,165,250,0.22)"}, 0 0 18px ${tj?`${tS}38`:"rgba(37, 99, 235, 0.32)"}, inset 0 1px 0 rgba(255,255,255,0.08)`:"inset 0 1px 0 rgba(255,255,255,0.04), 0 1px 3px rgba(0,0,0,0.4)",...tj&&{borderLeftColor:tN?"rgba(71, 85, 105, 0.18)":tS,borderRightColor:tC?"rgba(71, 85, 105, 0.18)":tS}},children:(0,o.LN)()?(0,r.jsx)("div",{className:"absolute inset-0 flex items-center justify-center",children:(0,r.jsx)("span",{className:"text-[9px] text-slate-400 truncate px-2",children:ej.title||`Scene ${tr}`})}):(0,r.jsxs)(r.Fragment,{children:[tv&&(0,r.jsx)("div",{className:"absolute left-0 top-0 w-px h-full pointer-events-none z-20",style:{background:"#ef4444",animation:ty.left?"flushPulse 0.2s ease-out forwards":"none",boxShadow:"0 0 6px rgba(239, 68, 68, 0.9), 0 0 12px rgba(239, 68, 68, 0.5)"}}),tw&&(0,r.jsx)("div",{className:"absolute right-0 top-0 w-px h-full pointer-events-none z-20",style:{background:"#ef4444",animation:ty.right?"flushPulse 0.2s ease-out forwards":"none",boxShadow:"0 0 6px rgba(239, 68, 68, 0.9), 0 0 12px rgba(239, 68, 68, 0.5)"}}),"inverted"===s&&(0,r.jsx)(o3,{start:eN,duration:eC,color:tS}),tc>0&&"inverted"!==s&&(0,r.jsx)("div",{className:"absolute inset-x-0 top-0 pointer-events-none",style:{height:tc+ti+4,background:"linear-gradient(180deg, rgba(0,0,0,0.55) 0%, rgba(0,0,0,0.2) 70%, transparent 100%)"}}),!td&&"inverted"!==s&&(0,r.jsx)("div",{className:"absolute inset-x-0 bottom-0 pointer-events-none",style:{height:Math.max(14,ts+ti),background:"linear-gradient(180deg, transparent 0%, rgba(5,10,20,0.5) 50%, rgba(5,10,20,0.75) 100%)"}}),eX&&!eH&&eY&&(0,r.jsx)("a",{href:"/pricing?from=free-limit","data-testid":"scene-block-upgrade",title:"Daily free limit reached. Upgrade to Pro to generate this scene.",className:`absolute inset-0 z-10 flex cursor-pointer overflow-hidden bg-violet-950/40 ${tf?"items-start":"items-center justify-center"}`,children:(0,r.jsxs)("div",{className:"relative flex max-w-full items-center gap-1.5 rounded-md border border-violet-400/40 bg-violet-950/70 px-2 py-[3px] backdrop-blur-sm",style:tf?{marginTop:th,marginLeft:tm,maxWidth:`calc(100% - ${tm+4}px)`}:void 0,children:[(0,r.jsxs)("svg",{className:"h-2.5 w-2.5 shrink-0 text-violet-300",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[(0,r.jsx)("rect",{x:"3",y:"7",width:"10",height:"6.5",rx:"1.5"}),(0,r.jsx)("path",{d:"M5.5 7V5.5a2.5 2.5 0 0 1 5 0V7"})]}),(0,r.jsx)("span",{className:"truncate font-mono text-[8px] font-semibold uppercase tracking-[0.18em] text-violet-200",children:"Upgrade to generate"})]})}),eX&&!eH&&!eY&&(0,r.jsxs)("div",{className:`absolute inset-0 z-10 flex overflow-hidden ${eG?"bg-sky-950/40":eq?"bg-amber-950/40":"bg-[#05080f]/60"} ${tf?"items-start":"items-center justify-center"}`,"data-testid":eG?"scene-block-interrupted":eq?"scene-block-blocked":void 0,title:eG?"Generation was interrupted before this scene started. Open its card in Video Studio and press Resume to continue."
97:eq?"This scene failed to generate. Open its card in Video Studio to retry, redirect the wording, or switch model.":void 0,children:[!eq&&(0,r.jsx)("div",{"aria-hidden":!0,className:"gen-conveyor absolute inset-0",style:{"--gen-stripe":"rgba(255,255,255,0.035)"}}),(0,r.jsxs)("div",{className:`relative flex max-w-full items-center gap-1.5 rounded-md border px-2 py-[3px] backdrop-blur-sm ${eG?"border-sky-400/40 bg-sky-950/70":eq?"border-amber-500/40 bg-amber-950/70":"border-white/[0.09] bg-black/55"}`,style:tf?{marginTop:th,marginLeft:tm,maxWidth:`calc(100% - ${tm+4}px)`}:void 0,children:[eG?(0,r.jsx)("svg",{className:"h-2.5 w-2.5 shrink-0 text-sky-300",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:(0,r.jsx)("path",{d:"M5 3.5v9l7.5-4.5L5 3.5z"})}):eq?(0,r.jsxs)("svg",{className:"h-2.5 w-2.5 shrink-0 text-amber-400",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":!0,children:[(0,r.jsx)("path",{d:"M8 2.5l6 10.5H2L8 2.5z"}),(0,r.jsx)("path",{d:"M8 7v3M8 11.8v.2"})]}):(0,r.jsxs)("span",{className:"gen-dots text-sky-300","aria-hidden":!0,children:[(0,r.jsx)("span",{}),(0,r.jsx)("span",{}),(0,r.jsx)("span",{})]}),(0,r.jsx)("span",{className:`truncate font-mono text-[8px] font-semibold uppercase tracking-[0.18em] ${eG?"text-sky-200":eq?"text-amber-300":"text-zinc-300"}`,children:eG?tf?"Interrupted, resume in Studio":`Scene ${tr} interrupted, resume in Studio`:eq?tf?"Scene failed":`Scene ${tr} failed`:"Uploading"})]})]}),e$&&e4&&!eX&&(0,r.jsx)("div",{className:"absolute top-1 right-1 z-10 p-0.5 bg-amber-500/80 rounded-sm",title:"Track is locked",children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",className:"text-amber-900",children:[(0,r.jsx)("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"})]})}),!(0,o.Vp)()&&(0,r.jsxs)("div",{className:"absolute left-0 pointer-events-none overflow-hidden",style:{top:tu,left:ti,width:Math.max(0,eM-2*ti),height:tp,borderRadius:0},children:[(ea=eI?c.inOffset:t.inOffset,er=d.startPixels/n,en=d.endPixels/n,ei=Math.max(eN,er),es=Math.max(0,Math.min(eN+eC,en)-ei),ec=ea+Math.max(0,ei-eN),ep=(eu=eR?ej.media?.duration||t.duration+t.inOffset:Math.max(ej.media?.duration||0,eC+ea))*n,(0,r.jsx)("div",{style:{position:"absolute",top:0,left:-(ea*n),width:ep,height:"100%"},children:(0,r.jsx)(lU,{mediaUrl:eD||"",width:ep,duration:eu,inOffset:0,isVideo:eR,blobUrl:eB,thumbnailUrl:eP,sceneTitle:ej.title||`Scene ${tr}`,isLoading:eX,storageKey:eW,assetRef:ej.media?.assetRef,visibleRangeStart:ec,visibleRangeDuration:es})})),(0,r.jsx)("div",{className:"absolute inset-x-0 top-0 pointer-events-none",style:{height:"40%",background:"linear-gradient(180deg, rgba(3,7,18,0.15) 0%, transparent 100%)"}})]}),eH&&(0,r.jsxs)("div",{className:"pointer-events-none absolute inset-0 z-10 flex items-center justify-center overflow-hidden",style:{background:"rgba(4,8,18,0.78)"},children:[(0,r.jsx)("div",{"aria-hidden":!0,className:"gen-conveyor absolute inset-0",style:{"--gen-stripe":"rgba(18,184,255,0.05)"}}),(0,r.jsx)("span",{"aria-hidden":!0,className:"absolute inset-x-0 top-0 h-[2px] overflow-hidden",children:(0,r.jsx)("span",{className:"gen-sheen",style:{"--gen-sheen-grad":"linear-gradient(90deg, transparent, rgba(18,184,255,0.85), transparent)"}})}),(0,r.jsxs)("div",{className:"relative flex max-w-full items-center gap-1.5 rounded-md border border-[#12B8FF]/25 bg-black/60 px-2 py-[3px] backdrop-blur-sm",children:[(0,r.jsxs)("span",{className:"gen-dots text-[#7cd6ff]","aria-hidden":!0,children:[(0,r.jsx)("span",{}),(0,r.jsx)("span",{}),(0,r.jsx)("span",{})]}),(0,r.jsx)("span",{className:"truncate font-mono text-[8px] font-semibold uppercase tracking-[0.18em] text-[#bfe9ff]",children:"Generating visuals"})]})]}),!(0,o.U4)()&&(em=I.has(t.id),eh=aj.si[eJ%aj.si.length],(0,r.jsxs)("div",{className:`absolute overflow-hidden pointer-events-none ${e0?"bg-red-950/30":""}`,style:{left:ti,top:to,width:Math.max(0,eM-2*ti),height:ts,borderRadius:0,opacity:Math.min(1,tl/14),background:e0?"linear-gradient(180deg, rgba(69,10,10,0.35) 0%, rgba(31,12,16,0.5) 100%)":"inverted"===s?"transparent":"linear-gradient(180deg, rgba(7,14,28,0.85) 0%, rgba(5,10,22,0.92) 100%)"},children:["off"!==s&&!em&&(0,r.jsx)(o8,{start:eN,duration:eC,zoomLevel:n,rawBlockWidth:eM,blockChromePadding:ti,color:eh}),eX?(0,r.jsx)(el,{}):ez?(ef=eI?c.inOffset:t.inOffset,ex=(eg=ej.media?.duration||ej.audio?.duration||t.duration+t.inOffset)*n,eb=ti/n,(0,r.jsx)("div",{style:{position:"absolute",top:0,left:-(ef*n),width:ex,height:"100%",opacity:e0?.3:1},children:(0,r.jsx)(o4,{start:eN,duration:eC,offset:ef-eb,children:e=>(0,r.jsx)(eo,{audioUrl:eU||"",storageKey:eK,assetRef:eV,persistedAudioAnalysis:T,analysisSource:{sourceType:"scene_audio",sourceSce
97neId:ej.id,sourceAudioBlockId:t.id,storageKey:eK},onPersistAudioAnalysisArtifact:$,totalDuration:eg,audioDuration:eg,audioStartTime:0,currentTime:Math.max(0,e),liveTimelineStart:eN,liveTimelineDuration:eC,liveTimeOffset:ef-eb,color:e0?"#ef4444":"off"!==s?aj.si[eJ%aj.si.length]:eO||t.id===p?"#60a5fa":"#94a3b8",inOffset:0,waveformMode:e0?"off":s,volume:t.volume??1,fadeInDuration:e9,fadeOutDuration:e7,fadeEnvelopeStart:ef,fadeEnvelopeDuration:eC,showClipping:E===t.id,onLoadComplete:e=>{C(a=>{let r=new Set(a);return e?r.add(t.id):r.delete(t.id),r}),M(a=>{let r=new Set(a);return e?r.delete(t.id):r.add(t.id),r})}})})})):null,e0&&(0,r.jsx)("div",{className:"absolute top-1 right-1 z-10 p-0.5 bg-red-500/80 rounded-sm",title:eZ?"Track muted":"Block muted",children:(0,r.jsx)(ob.A,{size:10,className:"text-white"})})]})),eL&&ts>=24&&(0,r.jsxs)("div",{className:`absolute bottom-0 z-20 transition-opacity duration-150 ${_===t.id||ta?"opacity-100":"opacity-[0.25] group-hover:opacity-100"}`,style:{left:ti+i,width:Math.max(0,eM-(ti+i)*2),top:to,height:ts,opacity:Math.min(1,tl/14)},children:[te>.5&&(0,r.jsx)("svg",{className:"absolute pointer-events-none",style:{left:0,top:0,width:`${te}%`,height:"100%"},viewBox:"0 0 1 1",preserveAspectRatio:"none",children:(0,r.jsx)("path",{d:sP(e6,"in"),fill:"none",stroke:_===t.id?"rgba(250, 204, 21, 0.78)":"rgba(148, 163, 184, 0.55)",strokeWidth:"1",strokeLinecap:"round",style:{vectorEffect:"non-scaling-stroke"}})}),tt>.5&&(0,r.jsx)("svg",{className:"absolute pointer-events-none",style:{right:0,top:0,width:`${tt}%`,height:"100%"},viewBox:"0 0 1 1",preserveAspectRatio:"none",children:(0,r.jsx)("path",{d:sP(e6,"out"),fill:"none",stroke:_===t.id?"rgba(250, 204, 21, 0.78)":"rgba(148, 163, 184, 0.55)",strokeWidth:"1",strokeLinecap:"round",style:{vectorEffect:"non-scaling-stroke"}})}),(0,r.jsx)("div",{className:`${e4?"cursor-not-allowed":"cursor-ns-resize"} absolute left-0 right-0`,style:{top:e8,height:8,transform:"translateY(-50%)"},onMouseDown:e=>q(e,t),onDoubleClick:e=>Y(e,t),title:`${Math.round(100*e3)}% volume (double-click to reset)`,children:(0,r.jsx)("div",{className:"absolute top-1/2 -translate-y-1/2",style:{left:`${te}%`,right:`${tt}%`,borderTop:`0.5px solid ${_===t.id?"rgba(250, 204, 21, 0.78)":"rgba(148, 163, 184, 0.55)"}`,boxShadow:_===t.id?"0 0 4px rgba(250, 204, 21, 0.28)":"0 0 1px rgba(15, 23, 42, 0.45)"}})}),eF&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:`${e4?"cursor-not-allowed":"cursor-ew-resize"} absolute top-0 bottom-0 w-3 -translate-x-1/2 ${ta?"":"opacity-0 group-hover:opacity-100"} transition-opacity duration-150`,style:{left:`${te}%`},onMouseDown:e=>G(e,t,"in"),onDoubleClick:e=>X(e,t,"in"),title:`Fade in ${e9.toFixed(2)}s (drag left/right)`,children:(0,r.jsx)("div",{className:"absolute w-[0.5px] bg-slate-200/40",style:{left:"50%",top:e8,height:Math.min(20,.3*ts),transform:"translate(-50%, -50%)"}})}),(0,r.jsx)("div",{className:`${e4?"cursor-not-allowed":"cursor-ew-resize"} absolute top-0 bottom-0 w-3 -translate-x-1/2 ${ta?"":"opacity-0 group-hover:opacity-100"} transition-opacity duration-150`,style:{left:`${100-tt}%`},onMouseDown:e=>G(e,t,"out"),onDoubleClick:e=>X(e,t,"out"),title:`Fade out ${e7.toFixed(2)}s (drag left/right)`,children:(0,r.jsx)("div",{className:"absolute w-[0.5px] bg-slate-200/40",style:{left:"50%",top:e8,height:Math.min(20,.3*ts),transform:"translate(-50%, -50%)"}})})]})]}),eT&&!(eq&&!tf)&&(0,r.jsx)("div",{className:"absolute flex items-center justify-between gap-1 pointer-events-none",style:{top:ti+(tc>0?0:1),left:Math.max(ti+4,i+2),right:Math.max(ti+4,i+2),height:Math.max(14,tc),zIndex:tc>0&&!eq?void 0:12},children:(0,r.jsx)("div",{className:"min-w-0 relative flex-1",children:(0,r.jsxs)("div",{className:"relative inline-block w-full align-baseline text-[9px]",children:[(0,r.jsxs)("div",{className:`inline-flex max-w-full items-center gap-1 truncate rounded-[4px] px-1 py-px text-[9px] font-semibold tracking-wide group-hover:opacity-0 transition-opacity duration-150 ${"inverted"===s?"text-black/90":"text-white/90"}`,style:{background:"inverted"===s?`${tS}60`:"rgba(4,8,16,0.78)",..."inverted"!==s&&{textShadow:"0 1px 2px rgba(0,0,0,0.7)",boxShadow:"inset 0 0 0 1px rgba(255,255,255,0.09)"}},children:["inverted"!==s&&(0,r.jsx)("span",{className:"h-[5px] w-[5px] shrink-0 rounded-full",style:{background:tS,boxShadow:`0 0 4px ${tS}aa`},"aria-hidden":"true"}),(0,r.jsxs)("span",{className:"truncate",children:["Scene ",tr]})]}),(0,r.jsxs)("div",{className:`absolute left-0 top-0 inline-flex max-w-full items-center gap-1 truncate text-[9px] font-semibold tracking-wide opacity-0 group-hover:opacity-100 transition-opacity duration-150 rounded-[4px] px-1 py-px ${"inverted"===s?"text-black/90":"text-white/90"}`,style:{zIndex:20,background:"inverted"===s?`${tS}60`:"rgba(4,8,16,0.78)",..."inverted"!==s&&{textShadow:"0 1px 2px rgba(0,0,0,0.7)",boxShadow:"inset 0 0 0 1px rgba(255,255,255,0.09)"}},children:["inverted"!==s&&(0,r.jsx)("span",{className:"h-[5px] w-[5px] shrink-0 rounded-full",style:{background:tS,boxShadow:`0 0 4px ${tS}aa`},"aria-hidden":"true"}),(0,r.jsx)("span",{className:"truncate",children:ej.facelessPlanSceneId?`Scene ${tr}`:tn})]})]})})}),!eE&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:`absolute top-0 left-0 h-full cursor-ew-resize opacity-0 group-hover:opacity-100 ${eO?"pointer-coarse:opacity-100 ":""}transition-opacity z-10`,style:{width:i},onMouseDown:e=>J(e,t,"start"),onTouchStart:e=>{e4||lK(t,"start"),Z(e,t,"start")},children:[(0,r.jsx)("div",{className:"h-full w-full bg-gradient-to-r from-sky-300/40 via-sky-300/12 to-transparent"}),(0,r.jsx)("div",{className:"absolute left-[3px] top-1/2 h-[38%] w-[2px] -translate-y-1/2 roun
97ded-full bg-sky-100/85 shadow-[0_0_4px_rgba(125,211,252,0.6)]"})]}),(0,r.jsxs)("div",{className:`absolute top-0 right-0 h-full cursor-ew-resize opacity-0 group-hover:opacity-100 ${eO?"pointer-coarse:opacity-100 ":""}transition-opacity z-10`,style:{width:i},onMouseDown:e=>J(e,t,"end"),onTouchStart:e=>{e4||lK(t,"end"),Z(e,t,"end")},children:[(0,r.jsx)("div",{className:"h-full w-full bg-gradient-to-l from-sky-300/40 via-sky-300/12 to-transparent"}),(0,r.jsx)("div",{className:"absolute right-[3px] top-1/2 h-[38%] w-[2px] -translate-y-1/2 rounded-full bg-sky-100/85 shadow-[0_0_4px_rgba(125,211,252,0.6)]"})]})]}),S===t.sceneId&&(0,r.jsxs)("div",{className:"absolute inset-0 z-30 flex items-center justify-center",style:{borderRadius:5,background:"rgba(0,0,0,0.55)",backdropFilter:"blur(2px)"},onClick:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),children:[(0,r.jsx)("button",{type:"button",className:"rounded-full bg-[#c8a87c] px-3 py-1 text-[10px] font-semibold text-[#1a1816] shadow-[0_0_12px_rgba(200,168,124,0.5)] animate-pulse hover:bg-[#d4b88c] transition-all",onClick:e=>{e.stopPropagation(),window.dispatchEvent(new CustomEvent("timeline:regenerate-split-scene",{detail:{nleSceneId:t.sceneId}}))},children:"Regenerate"}),(0,r.jsx)("button",{type:"button",className:"absolute top-1 right-1 flex h-4 w-4 items-center justify-center rounded-full bg-white/10 text-white/60 hover:bg-white/20 hover:text-white transition-all",onClick:e=>{e.stopPropagation(),j(null)},title:"Dismiss",children:(0,r.jsx)("span",{className:"text-[10px] leading-none",children:"\xd7"})})]}),eH&&S!==t.sceneId&&(0,r.jsx)(oW,{nleSceneId:t.sceneId,blockType:"scene"})]})}),!eE&&eO&&(ey=(Q={rawBlockWidth:eM,visualHandleWidthPx:i}).targetWidthPx??32,ev=Q.narrowBlockPx??72,ek=Math.max(0,Math.min((ew=Math.max(0,Q.rawBlockWidth))<ev?Q.visualHandleWidthPx:ey/2,ew/2)),eS={outerOffsetPx:-(ey-ek),widthPx:ey,inwardPx:ek},(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{"data-trim-touch-target":"start",className:"absolute top-0 h-full z-20 hidden pointer-coarse:block touch-none",style:{left:eA+eS.outerOffsetPx,width:eS.widthPx},onTouchStart:e=>{e4||lK(t,"start"),Z(e,t,"start")}}),(0,r.jsx)("div",{"data-trim-touch-target":"end",className:"absolute top-0 h-full z-20 hidden pointer-coarse:block touch-none",style:{right:eA+eS.outerOffsetPx,width:eS.widthPx},onTouchStart:e=>{e4||lK(t,"end"),Z(e,t,"end")}})]}))]},t.id)})})}var lH=a(66713),lq=a(95713),lY=a(21764);let lG=new Set(["queued","processing","pending","polling","generating"]);async function lX(e,t){for(let a=0;a<40;a+=1){let a={...t,handled:!1};if(window.dispatchEvent(new CustomEvent(e,{detail:a})),a.handled)return!0;await new Promise(e=>setTimeout(e,200))}return!1}async function lJ(e){window.dispatchEvent(new CustomEvent("faceless:open-studio-panel")),await lX("faceless:open-generate-tab",{}),await lX("faceless:focus-plan-scene",{planSceneId:e})}async function lZ(e){return window.dispatchEvent(new CustomEvent("faceless:open-studio-panel")),await lX("faceless:open-generate-tab",{}),lX("faceless:regenerate-scene",{planSceneId:e})}function lQ(e,t){return Math.min(Math.max(Math.min(e,3)*t,120),280)}let l0=e=>{e.stopPropagation()};function l1({ghost:e,zoomLevel:t}){let[a,n]=(0,i.useState)("idle"),s=(0,aZ.usePathname)(),{entitlements:o}=(0,ay.G)(),l=null!=o.freeTierImageLimit&&null!=o.freeTierImagesRemaining&&o.freeTierImagesRemaining<=0,d=(0,lH.W9)("/pricing?from=free-limit",(0,lH.b$)(s)),c=(0,i.useRef)(null),u=()=>{null!=c.current&&(window.clearTimeout(c.current),c.current=null)};if((0,i.useEffect)(()=>u,[]),(0,i.useEffect)(()=>((0,ey.trackEvent)("timeline_ghost_shown",{plan_scene_id:e.planSceneId,scene_number:e.sceneNumber,left_seconds:e.leftSeconds,estimated_seconds:e.estimatedSeconds,variant:l?"upgrade":"add"}),(0,s_.Lu)({location:"PendingSceneGhostLayer",message:"ghost:shown",data:{scene:e.sceneNumber,left:e.leftSeconds}}),()=>{(0,s_.Lu)({location:"PendingSceneGhostLayer",message:"ghost:hidden",data:{scene:e.sceneNumber}})}),[]),l)return(0,r.jsx)("a",{"data-testid":"timeline-add-next-scene","data-state":"idle","data-variant":"upgrade",href:d,onMouseDown:l0,onPointerDown:l0,onClick:t=>{t.stopPropagation(),(0,ey.trackEvent)("timeline_ghost_upgrade_clicked",{plan_scene_id:e.planSceneId,scene_number:e.sceneNumber}),(0,s_.Lu)({location:"PendingSceneGhostLayer",message:"ghost:upgrade-clicked",data:{scene:e.sceneNumber}})},title:`Daily free limit reached. Upgrade to Pro to generate Scene ${e.sceneNumber}.`,className:"group absolute z-40 flex cursor-pointer flex-col items-center justify-center gap-1 rounded-md border border-dashed border-orange-400/60 bg-orange-400/[0.10] px-2 text-center transition-colors hover:border-orange-400/80 hover:bg-orange-400/[0.16]",style:{left:e.leftSeconds*t+8,top:0,height:"100%",width:lQ(e.estimatedSeconds,t)},children:(0,r.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,r.jsx)(ez.A,{"aria-hidden":"true",className:"h-4 w-4 shrink-0 text-orange-300 transition-colors group-hover:text-orange-200"}),(0,r.jsx)("span",{className:"text-[11px] font-semibold text-orange-300/90 transition-colors group-hover:text-orange-200",children:"Upgrade"})]})});let p="armed"===a?`Tap again to generate Scene ${e.sceneNumber} (uses credits).`:"starting"===a?`Starting Scene ${e.sceneNumber}...`:"unhandled"===a?`Scene ${e.sceneNumber} didn't start. Tap to retry, or generate it from its card in the Video Studio panel.`:`Scene ${e.sceneNumber} from your storyboard has not been generated yet. Tap once to review it in the Video Studio, tap again to generate it right here.`;return(0,r.jsx)("button",{type:"button","data-testid":"timeline-add-next-scene","data-state":a,"data-variant":"add","aria-disabled":"starting"===a,onMouseDown:l0,onPointerDown:l0,onClick:t=>{if(l0(t),"starting"!==a){if("armed"===a){u(),n("starting"),(0,ey.trackEvent)("timeline_ghost_generate_confirmed",{plan_scene_id:e.planSceneId,scene_number:e.sceneNumber}),(0,s_.Lu)({location:"PendingSceneGhostLayer",message:"ghost:generate-confirmed",data:{scene:e.sceneNumber}}),lZ(e.planSceneId).then(t=>{t||((0,ey.trackEvent)("timeline_ghost_generate_unhandled",{plan_scene_id:e.planSceneId,scene_number:e.sceneNumber}),(0,s_.Lu)({location:"PendingSceneGhostLayer",message:"ghost:generate-unhandled",data:{scene:e.sceneNumber}}),n("unhandled"),u(),c.current=window.setTimeout(()=>{c.current=null,n("idle")},8e3))});return}n("armed"),(0,ey.trackEvent)("timeline_ghost_armed",{plan_scene_id:e.planSceneId,scene_number:e.sceneNumber}),(0,s_.Lu)({location:"PendingSceneGhostLayer",message:"ghost:armed",data:{scene:e.sceneNumber}}),u(),c.current=window.setTimeout(()=>{c.current=null,(0,s_.Lu)({location:"PendingSceneGhostLayer",message:"ghost:disarmed-timeout",data:{scene:e.sceneNumber}}),n("idle")},6e3),lJ(e.planSceneId)}},title:p,className:`group absolute z-40 flex flex-col items-center justify-center gap-1 rounded-md px-2 text-center transition-colors ${"armed"===a?"cursor-pointer border border-emerald-400/90 bg-emerald-400/[0.16] hover:bg-emerald-400/[0.22]":"starting"===a?"cursor-default border border-emerald-400/60 bg-emerald-400/[0.10]":"unhandled"===a?"cursor-pointer border border-amber-400/80 bg-amber-400/[0.12] hover:bg-amber-400/[0.18]":"cursor-pointer border border-dashed border-emerald-400/60 bg-emerald-400/[0.10] hover:border-emerald-400/80 hover:bg-emerald-400/[0.16]"}`,style:{left:e.leftSeconds*t+8,top:0,height:"100%",width:lQ(e.estimatedSeconds,t)},children:"starting"===a?(0,r.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,r.jsx)(x.A,{"aria-hidden":"true",className:"h-4 w-4 shrink-0 animate-spin text-emerald-300"}),(0,r.jsxs)("span",{className:"text-[11px] font-semibold leading-tight text-emerald-200",children:["Starting Scene ",e.sceneNumber,"..."]}
97)]}):"armed"===a?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,r.jsx)(k.A,{"aria-hidden":"true",className:"h-4 w-4 shrink-0 text-emerald-200"}),(0,r.jsxs)("span",{className:"text-[11px] font-semibold leading-tight text-emerald-100",children:["Generate Scene ",e.sceneNumber,"?"]})]}),(0,r.jsx)("span",{className:"text-center text-[10px] leading-tight text-emerald-300/90",children:"Tap again to confirm"})]}):"unhandled"===a?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,r.jsx)(g.A,{"aria-hidden":"true",className:"h-4 w-4 shrink-0 text-amber-300"}),(0,r.jsxs)("span",{className:"text-[11px] font-semibold leading-tight text-amber-200",children:["Couldnât start Scene ",e.sceneNumber]})]}),(0,r.jsx)("span",{className:"text-center text-[10px] leading-tight text-amber-300/90",children:"Tap to retry"})]}):(0,r.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,r.jsx)(a0.A,{"aria-hidden":"true",className:"h-4 w-4 shrink-0 text-emerald-300 transition-colors group-hover:text-emerald-200"}),(0,r.jsxs)("span",{className:"text-[11px] font-semibold text-emerald-300/80 transition-colors group-hover:text-emerald-200",children:["Add Scene ",e.sceneNumber]})]})})}let l5=[];function l2(){let e,t,n,l,d,c=(0,o.vr)(),u=(0,i.useRef)(null),p=(0,i.useRef)(null),{updateSceneMedia:m,currentProject:h,getLatestProjectState:f,setMasterTimelineZoomLevel:g,setMasterTimelineViewportStart:x,setMasterTimelineLoopRegion:b,setTrackSettings:k,setTrackControlsPanelWidth:S,setWaveformMode:j,reorderScenes:I,duplicateScene:N,duplicateScenes:C,updateCoreProjectState:_,saveCurrentProject:A,addVoiceover:T,updateVoiceover:P,removeVoiceover:D,updateSceneVolume:R,updateSceneAutomation:z}=(0,s.By)(),L=(0,i.useCallback)(e=>{if(!_||!f)return;let t=f();if(!t)return;let a=t.aiAnalysis?.audioArtifacts?.[e.sourceFingerprint];a&&a.analyzedAt>=e.analyzedAt||_({...t,aiAnalysis:(0,ea.Eb)(t.aiAnalysis,e),updatedAt:Date.now()})},[f,_]),{isReady:F,trimScene:U,reorderScenes:K,moveClip:V,getEntryIdForScene:H}=(0,nj.Gn)(),q=(0,y.zC)(e=>e.blocks),Y=(0,y.zC)(e=>e.setBlocks),[G,X]=(0,i.useState)(new Set);(0,i.useEffect)(()=>{let e=e=>{let t=e.detail?.nleSceneId;t&&X(e=>{let a=new Set(e);return a.add(t),a})},t=e=>{let t=e.detail?.nleSceneId;t&&X(e=>{if(!e.has(t))return e;let a=new Set(e);return a.delete(t),a})};return window.addEventListener("faceless:scene-generating",e),window.addEventListener("faceless:scene-generated",t),()=>{window.removeEventListener("faceless:scene-generating",e),window.removeEventListener("faceless:scene-generated",t)}},[]);let J=(0,i.useMemo)(()=>(function(e){let{sceneJobs:t,scenes:a}=e,r=new Set;if(!t?.length)return r;let n=new Map;for(let e of a??[])e.facelessPlanSceneId&&n.set(e.facelessPlanSceneId,e.id);for(let e of t)if(e.status&&lG.has(e.status)){let t=e.sceneId?n.get(e.sceneId):void 0;t&&r.add(t)}return r})({sceneJobs:h?.facelessStoryboard?.sceneJobs,scenes:h?.scenes}),[h?.facelessStoryboard,h?.scenes]),Z=(0,i.useMemo)(()=>(function(e,t){if(!e?.facelessStoryboard)return null;let a=(0,lq.I)(e);if(0===a.length)return null;let r=e.facelessStoryboard.plan,n=Array.isArray(r?.scenes)?r.scenes:[];if(0===n.length||!r||(e.facelessStoryboard.sceneJobs??[]).some(e=>!!e.status&&lG.has(e.status))||(e.scenes??[]).some(e=>!0===e.facelessPlaceholder)||t.some(e=>!0===e.isLoading))return null;let i=new Set(a.map(e=>e.planSceneId)),s=null;for(let e=0;e<n.length;e+=1){let t=n[e],a="string"==typeof t.id?t.id:null;if(!a||!i.has(a))continue;let r="number"==typeof t.index?t.index:e;(!s||r<s.sceneNumber-1)&&(s={planSceneId:a,sceneNumber:r+1,planScene:t})}if(!s)return null;let o="string"==typeof s.planScene.narrationText?s.planScene.narrationText:"",l=s.planScene.estimatedDuration,d="number"==typeof l&&Number.isFinite(l)&&l>0?l:o.trim()?(0,lY.fW)(o):oJ.v9,c=0,u=new Set;for(let t of e.scenes??[]){if(!0===t.facelessPlaceholder)continue;let e="number"==typeof t.timelineStart?t.timelineStart:null,a=t.media?.duration,r="number"==typeof a&&Number.isFinite(a)&&a>0?a:null;if(null===e||null===r)continue;"string"==typeof t.id&&u.add(t.id);let n=e+r;n>c&&(c=n)}for(let e of t){if("scene"!==e.type||"string"==typeof e.id&&u.has(e.id))continue;let t=e.start+e.duration;t>c&&(c=t)}return{planSceneId:s.planSceneId,sceneNumber:s.sceneNumber,estimatedSeconds:d,leftSeconds:c}})(h,q),[h,q]),Q=(0,i.useMemo)(()=>q.filter(e=>("voiceover"===e.type||"audio"===e.type)&&void 0!==e.type),[q]),{staleVoiceoverBlocks:ee,regenerateVoiceoverBlock:et}
97=function(e){let[t,a]=(0,i.useState)(new Set),r=e?.audio??e?.voiceovers,n=e?.scenes,s=e?.facelessSettings?.blueprintSettings?.voice,o=e?.facelessStoryboard?.plan,l=(0,i.useMemo)(()=>{let e=new Map;if(!r?.length||!n?.length||s?.enabled===!1||!o?.scenes?.length)return e;let t={provider:s?.provider,voiceId:s?.voiceId,speed:"number"==typeof s?.speed?s.speed:1};for(let a of(0,s6.jc)({planScenes:o.scenes,projectScenes:n,projectAudio:r,blueprintVoice:t}))e.set(a.blockId,{nleSceneId:a.nleSceneId});return e},[r,n,s,o]);return(0,i.useEffect)(()=>{a(e=>{if(0===e.size)return e;let t=new Set;for(let e of l.values())t.add(e.nleSceneId);let a=new Set;for(let r of e)t.has(r)&&a.add(r);return a.size===e.size?e:a})},[l]),{staleVoiceoverBlocks:(0,i.useMemo)(()=>{let e=new Map;for(let[a,r]of l)e.set(a,{nleSceneId:r.nleSceneId,inFlight:t.has(r.nleSceneId)});return e},[l,t]),regenerateVoiceoverBlock:(0,i.useCallback)(e=>{let t=l.get(e);if(!t)return;let{nleSceneId:r}=t,n=!1;a(e=>{if(e.has(r))return n=!0,e;let t=new Set(e);return t.add(r),t}),n||(async()=>{for(let e=0;e<40;e+=1){let e={nleSceneId:r};if(window.dispatchEvent(new CustomEvent("faceless:regenerate-voiceover-by-nle",{detail:e})),e.handled)return;await new Promise(e=>setTimeout(e,200))}console.warn("[useStaleVoiceoverBlocks] voiceover regeneration not handled (studio not mounted?)",{nleSceneId:r}),nI.toast.error("Could not start voiceover regeneration. Open the Generate tab and retry."),a(e=>{if(!e.has(r))return e;let t=new Set(e);return t.delete(r),t})})()},[l]),inFlightSceneIds:t}}(h),er=(0,i.useMemo)(()=>q.filter(e=>"caption"===e.type),[q]),en=(0,i.useMemo)(()=>q.filter(e=>("scene"===e.type||void 0===e.type)&&e.scene).sort((e,t)=>e.start-t.start),[q]),ei=(0,y.zC)(e=>e.removeAudioBlock),es=(0,y.zC)(e=>e.getBlocksOnTrack),eo=(0,y.zC)(e=>e.removeTrackAndShift),el=(0,y.zC)(e=>e.addCaptionBlock),ed=(0,y.zC)(e=>e.removeCaptionBlock),ep=(0,y.zC)(e=>e.duration),em=(0,y.zC)(e=>e.isPlaying),ef=(0,y.zC)(e=>e.updateBlock),eg=(0,y.zC)(e=>e.selectedSceneId),ex=(0,y.zC)(e=>e.selectedSceneIds),eb=(0,y.zC)(e=>e.setSelectedSceneIds),ev=(0,y.zC)(e=>e.selectedAudioBlockId),ew=(0,y.zC)(e=>e.selectedAudioBlockIds),ek=(0,y.zC)(e=>e.setSelectedAudioBlockId),eS=(0,y.zC)(e=>e.setSelectedAudioBlockIds),eN=(0,y.zC)(e=>e.setEditingCaptionBox),eC=(0,y.zC)(e=>e.loopRegion),eM=(0,y.zC)(e=>e.setLoopRegion),e_=(0,y.zC)(e=>e.clearLoopRegion),eA=(0,y.zC)(e=>e.markers),eE=(0,y.zC)(e=>e.isTrackMuted),eT=(0,y.zC)(e=>e.isTrackLocked),e$=(0,y.zC)(e=>e.isTrackVisible),eP=(0,y.zC)(e=>e.isTrackCaption),eD=(0,y.zC)(e=>e.trackMeta),eR=(0,y.zC)(e=>e.setIsTrimScrubbing),ez=(0,y.zC)(e=>e.splitRegenerateNleSceneId),eL=(0,y.zC)(e=>e.setSplitRegenerateNleSceneId),eF=(0,y.zC)(e=>e.setBlockVolume),eO=(0,y.zC)(e=>e.setBlockMuted),eB=(0,y.zC)(e=>e.setBlockAudioFadeDurations),eW=(0,y.zC)(e=>e.setBlockAudioFadeSlopes),{sceneBlobUrls:eU}=(0,M.L)(),eK=(0,y.zC)(e=>e.setProjectTime),eV=(0,y.zC)(e=>e.setIsPlaying),eH=E(e=>e.setHoveredMediaKey),eq=E(e=>e.clearHoveredMediaKey),{isRestartModeEnabled:eY,toggleRestartMode:eG}=(0,nk.A)(),{isMagnetEnabled:eX,isGridEnabled:eJ,gridIntervalSeconds:eZ,isGridAuto:eQ,overlapPolicy:e0,toggleMagnetMode:e1,toggleGridMode:e5,setGridIntervalSeconds:e2,setGridAuto:e4,setOverlapPolicy:e3}=(0,nS.Lo)(),{pushAction:e8,undo:e6,redo:e9,canUndo:te,canRedo:tt}=(0,ej.n)(),ta=(0,i.useRef)(!1),tr=(0,i.useRef)(0),tn=(0,i.useRef)(1),ti=(0,i.useRef)(null),ts=(0,i.useRef)(lt()),to=(0,i.useRef)(null),tl=(0,i.useRef)(null),td=(0,i.useRef)(!1),tc=(0,i.useRef)(null),tu=(0,i.useRef)(new Map),tp=(0,i.useRef)(null),tm=(0,i.useCallback)(()=>{if(!ta.current){ta.current=!0,(0,st.markScrubEvent)(),eR(!0),Promise.resolve().then(a.bind(a,47687)).then(({WebCodecsVideoNode:e})=>{e.setGlobalScrubActive(!0)});try{(0,sa.HH)().deactivatePlaybackMode()}catch{}}},[eR]),th=(0,i.useCallback)(()=>{ta.current&&(ta.current=!1,(0,st.markScrubEndEvent)(),eR(!1),Promise.resolve().then(a.bind(a,47687)).then(({WebCodecsVideoNode:e})=>{e.setGlobalScrubActive(!1)}))},[eR]),[tf,tg]=(0,i.useState)(0),[tx,tb]=(0,i.useState)(1e3),[ty,tv]=(0,i.useState)(0),{maxTimelinePanelHeight:tw,showTrack0:tk,setShowTrack0:tS,timelineCollapsed:tj,toggleTimelineCollapse:tI}=function(){let[e,t]=(0,i.useState)(()=>Math.max(aj.E0,window.innerHeight-40)),[a,r]=(0,i.useState)(!1),[n,s]=(0,i.useState)(()=>{try{return"true"===localStorage.getItem("master-timeline-collapsed")}catch{return!1}}),o=(0,i.useCallback)(()=>{s(e=>{let t=!e;try{localStorage.setItem("master-timeline-collapsed",String(t))}catch{}return t})},[]);return(0,i.useEffect)(()=>{let e=()=>{let e=document.querySelector("[data-project-header]"),a=e?Math.round(e.getBoundingClientRect().height):40;t(Math.max(aj.E0,window.innerHeight-a))};e();let a=document.querySelector("[data-project-header]"),r=a?new ResizeObserver(e):null;return a&&r&&r.observe(a),window.addEventListener("resize",e),()=>{window.removeEventListener("resize",e),r?.disconnect()}},[]),{maxTimelinePanelHeight:e,showTrack0:a,setShowTrack0:r,timelineCollapsed:n,toggleTimelineCollapse:o}}(),tN=(0,i.useMemo)(()=>(function(e){let{blocks:t,showTrack0:a,facelessStoryboard:r}=e,n=new Map,i=r?.plan?.scenes,s=new Map;Array.isArray(i)&&i.length&&[...i].sort((e,t)=>
97(e.index??0)-(t.index??0)).forEach((e,t)=>{"string"==typeof e?.id&&s.set(e.id,t+1)});let o=t.filter(e=>("scene"===e.type||void 0===e.type)&&e.scene&&(a||(e.trackId??1)!==0)).slice().sort((e,t)=>e.start-t.start);if(s.size>0){let e=r?.timelineStartOffsetSeconds,t="number"==typeof e&&Number.isFinite(e)&&e>0?o.filter(t=>!t.scene?.facelessPlanSceneId&&t.start<e):[],a=new Set(t.map(e=>e.sceneId));t.forEach((e,t)=>n.set(e.sceneId,t+1));let i=t.length,l=i+s.size;o.forEach(e=>{if(a.has(e.sceneId))return;let t=e.scene?.facelessPlanSceneId,r=t?s.get(t):void 0;null!=r?n.set(e.sceneId,i+r):(l+=1,n.set(e.sceneId,l))})}else o.forEach((e,t)=>n.set(e.sceneId,t+1));return n})({blocks:q,showTrack0:tk,facelessStoryboard:h?.facelessStoryboard}),[q,tk,h?.facelessStoryboard]),[tC,tA]=(0,i.useState)({}),tE=(0,i.useCallback)((e,t)=>{let a=[...(h?.scenes??[]).map(e=>({id:e.id,trackId:e.trackId,timelineStart:e.timelineStart,media:e.media})),...(h?.audio??[]).map(e=>({id:e.id,trackId:e.trackId,start:e.start,duration:(e.outOffset??e.duration??0)-(e.inOffset??0)})),...(h?.captionBlocks??[]).map(e=>({id:e.id,trackId:e.trackId,start:e.start,duration:e.duration}))];return(0,i$.Ll)(a,e,Math.max(.2,t),3)},[h?.scenes,h?.audio,h?.captionBlocks]),[tT,t$]=(0,i.useState)(null),[tP,tR]=(0,i.useState)(null),tz=(0,i.useCallback)(()=>{t$(null),tR(null)},[]),[tL,tF]=(0,i.useState)(h?.waveformMode||"off"),[tB,tW]=(0,i.useState)(new Set),[tU,tK]=(0,i.useState)(new Set);(0,i.useEffect)(()=>{h?.waveformMode&&tF(h.waveformMode)},[h?.waveformMode]);let tX=(0,i.useCallback)(()=>{tF(e=>{let t="off"===e?"neon":"neon"===e?"inverted":"off";return j&&j(t),t})},[j]),[tZ,tQ]=(0,i.useState)(null),t0=(0,i.useRef)(null),t1=(0,i.useRef)(0),[t5,t2]=(0,i.useState)(null),[t3,t8]=(0,i.useState)(null),[t6,t9]=(0,i.useState)(null),[t7,ae]=(0,i.useState)(0),[at,aa]=(0,i.useState)(0),[ar,an]=(0,i.useState)(null),[ai,as]=(0,i.useState)(null),[ao,al]=(0,i.useState)(null),ad=(0,i.useRef)(!1);(0,i.useEffect)(()=>{(0,sA.CO)(()=>y.zC.getState().blocks)},[]);let ac=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(!t5&&!t3)return ac.current=window.setTimeout(()=>{ac.current=null,(0,sA.XX)("settle_watch",y.zC.getState().blocks,{projectId:h?.id??null,generationActive:J.size>0,getBlocks:()=>y.zC.getState().blocks})},2e3),()=>{null!=ac.current&&(window.clearTimeout(ac.current),ac.current=null)}},[q,t5,t3,h?.id,J]);let au=(0,i.useRef)(!1),[ap,am]=(0,i.useState)(null),[ah,af]=(0,i.useState)(null),[ag,ax]=(0,i.useState)(null),[ab,ay]=(0,i.useState)(!1),av=(0,i.useRef)(null),aw=(0,i.useRef)(null),[ak,aM]=(0,i.useState)(new Map),[a_,aA]=(0,i.useState)(null),[aE,aT]=(0,i.useState)(null),[a$,aP]=(0,i.useState)(null),[aD,aR]=(0,i.useState)(null),az=(0,i.useMemo)(()=>{let e,t;return e=[],t=new Map,q.forEach(e=>{let a=e.trackId??1;t.has(a)||t.set(a,[]),t.get(a).push(e)}),t.forEach(t=>{let a=[...t].sort((e,t)=>e.start-t.start);for(let t=0;t<a.length-1;t++){let r=a[t],n=a[t+1];if(.1>Math.abs(n.start-(r.start+r.duration))&&!r.scene?.transition?.enabled){let t=r.start+r.duration;e.push({sceneId:r.sceneId,seamTime:t,trackId:r.trackId??1,fromBlockId:r.id,toBlockId:n.id,key:`seam-${r.id}-${n.id}`})}}}),e},[q]),{zoomLevel:aL,handleZoomIn:aF,handleZoomOut:aO,setZoomFromExternal:aB,zoomToRange:aW}=function({containerRef:e,initialZoom:t=aj.aM,viewportWidth:a,onZoomChange:r,onCommittedScrollLeft:n}){let[s,o]=(0,i.useState)(t),l=(0,i.useRef)(null),d=(0,i.useRef)(s),c=(0,i.useRef)(s),u=(0,i.useRef)(null),p=(0,i.useRef)(null),m=(0,i.useRef)(null),h=(0,i.useRef)(r);h.current=r;let f=(0,i.useRef)(n);f.current=n,(0,i.useEffect)(()=>()=>{m.current&&clearTimeout(m.current),null!==p.current&&cancelAnimationFrame(p.current)},[]),(0,i.useLayoutEffect)(()=>{null!==l.current&&e.current&&(e.current.scrollLeft=l.current,l.current=null)},[s,e]);let g=(0,i.useCallback)(t=>{d.current=t,null===p.current&&(p.current=requestAnimationFrame(()=>{p.current=null;let t=d.current;if(t===c.current){let t=l.current;l.current=null,null!==t&&e.current&&(e.current.scrollLeft=t,f.current?.(t));return}null!==l.current&&f.current?.(l.current),c.current=t,o(t)}))},[e]),x=(0,i.useCallback)(e=>{m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{h.current?.(e)},300)},[]),b=(0,i.useCallback)((t,r)=>{let n=e.current,i=y.zC.getState().projectTime;if(!n){l.current=Math.max(0,i*r-a/2);return}let s=i*t-(l.current??n.scrollLeft);s>=0&&s<=a?l.current=Math.max(0,i*r-s):l.current=Math.max(0,i*r-a/2)},[e,a]),v=(0,i.useCallback)(()=>{let e=d.current,t=Math.min(e*aj.sj,aj.nD);t!==e&&(b(e,t),g(t),x(t))},[g,b,x]),w=(0,i.useCallback)(()=>{let e=d.current,t=Math.max(e/aj.sj,aj.DQ);t!==e&&(b(e,t),g(t),x(t))},[g,b,x]);return(0,i.useEffect)(()=>{let t=e.current;if(!t)return;let a=e=>{if(!(e.ctrlKey||e.metaKey))return;e.preventDefault();let a=-e.deltaY;if(0===a)return;let r=d.current,n=Math.max(Math.min(.008*Math.abs(e.deltaY),.25),.012),i=Math.min(Math.max(r*(a>0?1+n:1/(1+n)),aj.DQ),aj.nD);if(i===r)return;let s=y.zC.getState().projectTime,o=l.current??t.scrollLeft,c=t.clientWidth,u=s*r-o;u>=0&&u<=c?l.current=Math.max(0,s*i-u):l.current=Math.max(0,Math.max(0,(o+c/2)/Math.max(r,.001))*i-c/2),g(i),x(i)};return t.addEventListener("wheel",a,{passive:!1}),()=>t.removeEventListener("wheel",a)},[e,g,x]),(0,i.useEffect)(()=>{let t=e.current;if(!t)return;let a=(e,t)=>Math.hypot(e.clientX-t.clientX,e.clientY-t.clientY),r=(e,t)=>(e.clientX+t.clientX)/2,n=e=>{if(2!==e.touches.length)return;let n=e.touches[0],i=e.touches[1],s=a(n,i);if(s<8)return;let o=t.getBoundingClientRect(),c=r(n,i)-o.left,p=Math.max(0,((l.current??t.scrollLeft)+c)/Math.max(d.current,.001));u.current={startDistance:s,startZoom:d.current,anchorTime:p},e.preventDefault()},i=e=>{let n=u.current;if(!n||2!==e.touches.length)return;let i=e.touches[0],s=e.touches[1],o=a(i,s);if(o<8||n.startDistance<8)return;let c=o/n.startDistance,p=Math.min(Math.max(n.startZoom*c,aj.DQ),aj.nD);if(.01>Math.abs(p-d.current))return;let m=t.getBoundingClientRect(),h=r(i,s)-m.left;l.current=Math.max(0,n.anchorTime*p-h),g(p),x(p),e.preventDefault()},s=()=>{u.current=null};return t.addEventListener("touchstart",n,{passive:!1}),t.addEventListener("touchmove",i,{passive:!1}),t.addEventListener("touchend",s),t.addEventListener("touchcancel",s),()=>{t.removeEventListener("touchstart",n),t.removeEventListener("touchmove",i),t.removeEventListener("touchend",s),t.removeEventListener("touchcancel",s),u.current=null}},[e,g,x]),{zoomLevel:s,handleZoomIn:v,handleZoomOut:w,setZoomFromExternal:(0,i.useCallback)(e=>{e>0&&Math.abs(e-d.current)>.01&&(d.current=e,c.current=e,o(e))},[]),zoomToRange:(0,i.useCallback)((e,t,r=48)=>{let n=t-e;if(!(n>0)||!(a>0))return;let i=Math.min(Math.max(Math.max(64,a-2*r)/n,aj.DQ),aj.nD);l.current=Math.max(0,(e+n/2)*i-a/2),g(i),x(i)},[g,x,a])}}({containerRef:u,initialZoom:h?.masterTimelineZoomLevel||aj.aM,viewportWidth:tx,onZoomChange:g,onCommittedScrollLeft:tg}),aU=eQ?(0,nS.WA)(aL):eZ;!function({currentProject:e,containerRef:t,zoomLevel:a,duration:r,viewportWidth:n,scrollLeft:s,setScrollLeft:o,setZoomFromExternal:l,setMasterTimelineViewportStart:d,setMasterTimelineLoopRegion:c,loopRegion:u,setLoopRegion:p,clearLoopRegion:m}){(0,i.useEffect)(()=>{e?.masterTimelineZoomLevel&&e.masterTimelineZoomLevel>0&&l(e.masterTimelineZoomLevel)},[e?.masterTimelineZoomLevel,l]);let h=(0,i.useRef)(null);(0,i.useEffect)(()=>{let a=e?.id;if(!a)return;if(e?.masterTimelineZoomLevel&&e.masterTimelineZoomLevel>0){h.current=a;return}
97if(h.current===a||!(r>0))return;let i=t.current?.clientWidth||n;if(!(i>0))return;let s=Math.min(aj.nD,Math.max(aj.DQ,i/(1.25*r)));h.current=a,l(s)},[e?.id,e?.masterTimelineZoomLevel,r,n,t,l]),(0,i.useEffect)(()=>{let e=e=>{let a=e.detail?.durationSeconds;if("number"!=typeof a||!Number.isFinite(a)||a<=0)return;let i=Math.max(a,r||0),s=t.current?.clientWidth||n;s>0&&i>0&&(l(Math.min(aj.nD,Math.max(aj.DQ,aj.WO,s/(1.25*i)))),t.current&&(t.current.scrollLeft=0))};return window.addEventListener("faceless:fit-timeline",e),()=>window.removeEventListener("faceless:fit-timeline",e)},[r,n,t,l]);let f=(0,i.useRef)(null),g=(0,i.useRef)(null);(0,i.useEffect)(()=>{f.current=null},[e?.id]),(0,i.useEffect)(()=>{if(!e?.id)return;let t=sT(e.masterTimelineLoopRegion);s$(y.zC.getState().loopRegion,t)||(t?p(t):m())},[e?.id,e?.masterTimelineLoopRegion?.start,e?.masterTimelineLoopRegion?.end,p,m]);let x=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(e?.id&&c)return x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{let t=sT(u);s$(t,sT(e.masterTimelineLoopRegion))||c(t)},500),()=>{x.current&&clearTimeout(x.current)}},[u,e?.id,e?.masterTimelineLoopRegion?.start,e?.masterTimelineLoopRegion?.end,c]);let b=sm(r,a,n);(0,i.useLayoutEffect)(()=>{if(!e?.id||f.current===e.id)return;let n=t.current;if(!n||a<=0)return;let i=e.masterTimelineViewportStart;if(null==i||!Number.isFinite(i)||i<0||r>0&&i>r+10){f.current=e.id;return}let s=Math.max(0,i*a),l=Math.max(0,n.scrollWidth-n.clientWidth);if(s>0&&l<=0)return;let d=Math.min(s,l);Math.abs(n.scrollLeft-d)>1&&(n.scrollLeft=d),o(n.scrollLeft),f.current=e.id},[e?.id,e?.masterTimelineViewportStart,r,a,b,n,t,o]),(0,i.useEffect)(()=>{if(!e?.id||!d||a<=0)return;let t=s/a,n=r>0?r+10:t,i=Math.max(0,Math.min(t,n)),o=e.masterTimelineViewportStart;if(!("number"==typeof o&&Number.isFinite(o)&&.05>Math.abs(o-i)))return g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{d(i)},400),()=>{g.current&&clearTimeout(g.current)}},[s,a,r,e?.id,e?.masterTimelineViewportStart,d])}({currentProject:h,containerRef:u,zoomLevel:aL,duration:ep,viewportWidth:tx,scrollLeft:tf,setScrollLeft:tg,setZoomFromExternal:aB,setMasterTimelineViewportStart:x,setMasterTimelineLoopRegion:b,loopRegion:eC,setLoopRegion:eM,clearLoopRegion:e_});let aK=(0,y.zC)(e=>e.getTrackHeight),aV=(0,y.zC)(e=>e.setTrackHeight),aH=(0,y.zC)(e=>e.setTrackHeightsBatch),aq=(0,y.zC)(e=>e.trackHeights),aY=(0,y.zC)(e=>e.getAutomationLaneHeight),aG=(0,y.zC)(e=>e.setAutomationLaneHeight),aX=(0,y.zC)(e=>e.setAutomationLaneHeightsBatch),aJ=(0,y.zC)(e=>e.automationLaneHeights),aZ=(0,y.zC)(e=>e.getEffectsLaneRowHeight),aQ=(0,y.zC)(e=>e.setEffectsLaneRowHeight),a0=(0,y.zC)(e=>e.effectsLaneRowHeights);!function({currentProject:e,setTrackSettings:t,setTrackControlsPanelWidth:a}){let r=(0,y.zC)(e=>e.trackSettings),n=(0,y.zC)(e=>e.trackControlsPanelWidth),s=(0,y.zC)(e=>e.setTrackControlsPanelWidth);(0,i.useEffect)(()=>{var t;let a,r,n,{settings:i,heights:s,automationLaneHeights:o}=(t=e?.trackSettings,a=new Map,r=new Map,n=new Map,t&&Object.entries(t).forEach(([e,t])=>{let i=parseInt(e,10);Number.isFinite(i)&&(a.set(i,{muted:t.muted,locked:t.locked,visible:t.visible,...void 0!==t.solo?{solo:t.solo}:{}}),"number"==typeof t.height&&Number.isFinite(t.height)&&r.set(i,sS(t.height)),"number"==typeof t.automationLaneHeight&&Number.isFinite(t.automationLaneHeight)&&n.set(i,sj(t.automationLaneHeight)))}),{settings:a,heights:r,automationLaneHeights:n});JSON.stringify(Array.from(y.zC.getState().trackSettings.entries()))!==JSON.stringify(Array.from(i.entries()))&&y.zC.setState({trackSettings:i}),JSON.stringify(Array.from(y.zC.getState().trackHeights.entries()))!==JSON.stringify(Array.from(s.entries()))&&y.zC.setState({trackHeights:s}),JSON.stringify(Array.from(y.zC.getState().automationLaneHeights.entries()))!==JSON.stringify(Array.from(o.entries()))&&y.zC.setState({automationLaneHeights:o})},[e?.id,e?.trackSettings]);let o=(0,i.useRef)({});(0,i.useEffect)(()=>{let t=e?.id,a=e?.trackControlsPanelWidth;if(!t)return;let r=o.current,n=r.projectId!==t,i=r.width!==a;(n||i)&&(o.current={projectId:t,width:a},void 0!==a&&a>0&&s(a))},[e?.id,e?.trackControlsPanelWidth,s]);let l=(0,i.useRef)(null);(0,i.useEffect)(()=>
97{if(e?.id&&t)return l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{let a=sI(r,y.zC.getState().trackHeights,y.zC.getState().automationLaneHeights),n=e.trackSettings||{};JSON.stringify(a)!==JSON.stringify(n)&&t(a)},500),()=>{l.current&&clearTimeout(l.current)}},[r,e?.id,t,e?.trackSettings]);let d=(0,i.useRef)(null),c=(0,i.useRef)(0),u=(0,i.useRef)(0);(0,i.useEffect)(()=>{if(!e?.id||!t)return;let a=y.zC.subscribe(a=>{let r=a.trackHeights,n=a.automationLaneHeights;if(r.size===c.current&&n.size===u.current){let t=!1;if(r.forEach((a,r)=>{let n=e.trackSettings?.[r.toString()];n?.height!==a&&(t=!0)}),t||n.forEach((a,r)=>{let n=e.trackSettings?.[r.toString()];n?.automationLaneHeight!==a&&(t=!0)}),!t)return}c.current=r.size,u.current=n.size,d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{let a=sI(y.zC.getState().trackSettings,y.zC.getState().trackHeights,y.zC.getState().automationLaneHeights),r=e.trackSettings||{};JSON.stringify(a)!==JSON.stringify(r)&&t(a)},500)});return()=>{a(),d.current&&clearTimeout(d.current)}},[e?.id,e?.trackSettings,t]);let p=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(e?.id&&a)return p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{n!==e.trackControlsPanelWidth&&a(n)},500),()=>{p.current&&clearTimeout(p.current)}},[n,e?.id,e?.trackControlsPanelWidth,a])}({currentProject:h,setTrackSettings:k,setTrackControlsPanelWidth:S});let{isSpliceMode:a1,toggleSpliceMode:a5,attemptSpliceAtTime:a2,disableSpliceMode:a4}=function({blocks:e,currentProject:t,pushAction:a,updateCoreProjectState:r,saveCurrentProject:n,setSelectedSceneIds:s,setSelectedAudioBlockId:o,log:l}){let[d,c]=(0,i.useState)(!1),u=(0,i.useCallback)((i,d)=>{if(!t)return!1;let c=function(e,t,a){if("caption"!==e.type)return null;let r=t-e.start;if(r<=.05||e.duration-r<=.05)return null;let n=e.captionWords?.filter(e=>e.word?.trim())??[];if(0===n.length)return null;let i=n.filter(e=>(e.start+e.end)/2<r).map(e=>({...e,end:Math.min(e.end,r)})).filter(e=>e.end>e.start),s=n.filter(e=>(e.start+e.end)/2>=r).map(e=>({...e,start:Math.max(0,e.start-r),end:Math.max(0,e.end-r)})).filter(e=>e.end>e.start);if(0===i.length||0===s.length)return null;let o=e.duration-r,l=tq(e),d=tq(e),c=tH(e.captionCues),u=tH(e.captionCues);return e.captionCues&&e.captionCues.length>0&&(c=e.captionCues.filter(e=>e.start<r).map(e=>({...e,end:Math.min(e.end,r)})),u=e.captionCues.filter(e=>e.end>r).map(e=>({...e,start:Math.max(0,e.start-r),end:Math.max(0,e.end-r),wordStartIndex:Math.max(0,e.wordStartIndex-i.length),wordEndIndex:Math.max(0,e.wordEndIndex-i.length)}))),l.id=a(),l.duration=r,l.inOffset=0,l.outOffset=r,l.fullDuration=r,l.captionWords=i,l.captionCues=c,l.captionText=tV(i),l.sourceCaptionId=l.id,d.id=a(),d.start=e.start+r,d.duration=o,d.inOffset=0,d.outOffset=o,d.fullDuration=o,d.captionWords=s,d.captionCues=u,d.captionText=tV(s),d.sourceCaptionId=d.id,{left:l,right:d}}(i,d,nN.$C);if(!c)return l?.("SPLIT_CAPTION_SKIPPED",{blockId:i.id,targetTime:d}),!1;let u=t.captionBlocks??[],p=e.flatMap(e=>e.id===i.id?[c.left,c.right]:[e]),m=p.filter(e=>"caption"===e.type).map(tY);return a({type:"SPLIT_CAPTION",previousState:{scenes:[...t.scenes??[]],captionBlocks:u,affectedCaptionId:i.id},newState:{scenes:[...t.scenes??[]],captionBlocks:m,affectedCaptionId:c.right.id}}),y.zC.getState().setBlocks(p),r({...t,captionBlocks:m,updatedAt:Date.now()}),n&&n(),o?.(c.right.id),s([]),l?.("SPLIT_CAPTION",{captionId:i.id,newCaptionIds:[c.left.id,c.right.id],targetTime:d,leftText:c.left.captionText,rightText:c.right.captionText}),!0},[e,t,l,a,n,o,s,r]),p=(0,i.useCallback)((e,i)=>{if(!t?.scenes||!e.scene)return!1;if(e.scene.isLoading||e.scene.media?.status==="uploading")return l?.("SPLIT_SKIPPED_LOADING",{sceneId:e.sceneId}),!1;let o=e.scene.media;if(!o)return l?.("SPLIT_SKIPPED_NO_MEDIA",{sceneId:e.sceneId}),!1;let d=o.duration??e.outOffset??e.inOffset+e.duration;if(!d||d<=0)return l?.("SPLIT_SKIPPED_NO_DURATION",{sceneId:e.sceneId}),!1;let c=i-e.start,u=(0,tO.Y2)({sceneStart:e.start,sceneDuration:e.duration,prevTrim:{start:e.inOffset,end:e.inOffset+e.duration},mediaDuration:d,splitAtAbsolute:i});if(!u.applied)return l?.("SPLIT_SKIPPED_EDGE",{sceneId:e.sceneId,positionInBlock:c,reason:u.reason}),!1;let p=u.left.trim.end-u.left.trim.start,m=u.right.trim.end-u.right.trim.start;
97console.log("[SPLIT_DIAG] Input:",{targetTime:i,"block.start":e.start,"block.duration":e.duration,"block.inOffset":e.inOffset,"block.outOffset":e.outOffset,positionInBlock:c,splitPoint:u.splitMediaTime,mediaDuration:d,leftDuration:p,rightDuration:m});let h=Date.now(),f=e.scene,g=f.id,x=(0,nN.$C)(),{left:b,right:v}=function(e,t){if(!e)return{left:void 0,right:void 0};let a={},r={};for(let[n,i]of Object.entries(e)){if(!i||!i.keyframes?.length)continue;let[e,s]=nC(i,t);a[n]=e,r[n]=s}return{left:Object.keys(a).length?a:void 0,right:Object.keys(r).length?r:void 0}}(f.automation,c),{left:w,right:k}=function(e,t){if(!e?.length)return{left:e,right:e};let a=[],r=[];for(let n of e){if(!n.automation){a.push({...n}),r.push({...n,id:(0,nN.$C)()});continue}let e={},i={};for(let[a,r]of Object.entries(n.automation)){if(!r||!r.keyframes?.length)continue;let[n,s]=nC(r,t);e[a]=n,i[a]=s}a.push({...n,automation:e}),r.push({...n,id:(0,nN.$C)(),automation:i})}return{left:a,right:r}}(f.effects,c),S={...f,updatedAt:h,timelineStart:u.left.timelineStart,trackId:e.trackId,automation:b,effects:w,transition:void 0,media:{...o,trim:{...u.left.trim}}},j={...f,id:x,createdAt:h,updatedAt:h,timelineStart:u.right.timelineStart,trackId:e.trackId,automation:v,effects:k,media:{...o,trim:{...u.right.trim}}},I=t.scenes.reduce((e,t)=>(t.id===g?e.push(S,j):e.push(t),e),[]).map((e,t)=>({...e,sequenceIndex:t})),N=e.start+c,C=t.audio||t.voiceovers||[],M=t4({audioBlocks:C,originalSceneId:g,rightSceneId:x,splitAbsoluteTime:N,nextId:nN.$C,now:h}),_=M.hadLinkedAudio,A=M.blocks,E=t.captionBlocks??[],T=tG(E,g,x,N,nN.$C),$=T.captions;T.changed&&console.log("[SPLIT_DIAG] Captions:",{before:E.length,after:$.length,leftSceneCaptions:$.filter(e=>e.sceneId===g).length,rightSceneCaptions:$.filter(e=>e.sceneId===x).length,splitAbsoluteTime:N}),a({type:"SPLIT_SCENE",previousState:{scenes:[...t.scenes],audio:[...C],captionBlocks:[...E],affectedSceneId:g},newState:{scenes:I,audio:A,captionBlocks:$,affectedSceneId:x}}),r({...t,scenes:I,audio:A,voiceovers:A,captionBlocks:$,updatedAt:Date.now()});let P=y.zC.getState();if(P.syncFromScenes(I),P.syncAudioFromProject(A),T.changed){let e=y.zC.getState();e.setBlocks(aN(e.blocks,$))}return n&&n(),s([x]),window.dispatchEvent(new CustomEvent("timeline:scene-split",{detail:{originalNleSceneId:g,rightNleSceneId:x,splitOffset:c,leftCaptionText:T.changed?$.find(e=>e.sceneId===g)?.captionText??"":void 0,rightCaptionText:T.changed?$.find(e=>e.sceneId===x)?.captionText??"":void 0}})),l?.("SPLIT_SCENE",{sceneId:g,newSceneIds:[g,x],splitPoint:u.splitMediaTime,leftTrim:[u.left.trim.start,u.left.trim.end],rightTrim:[u.right.trim.start,u.right.trim.end],targetTime:i,splitAudio:_,splitCaption:T.changed}),!0},[t,l,a,n,s,r]),m=(0,i.useCallback)((e,i)=>{let d=t?.audio||t?.voiceovers;if(!d)return l?.("SPLIT_AUDIO_SKIPPED_NO_AUDIO",{blockId:e.id}),!1;let c=d.find(t=>t.id===e.id);if(!c)return l?.("SPLIT_AUDIO_SKIPPED_NOT_FOUND",{blockId:e.id}),!1;let u=c.duration||e.fullDuration||5;if(!u||u<=0)return l?.("SPLIT_AUDIO_SKIPPED_NO_DURATION",{blockId:e.id}),!1;let p=i-e.start;if(p<=.05||e.duration-p<=.05)return l?.("SPLIT_AUDIO_SKIPPED_EDGE",{blockId:e.id,positionInBlock:p}),!1;let m=(c.inOffset??0)+p,h=e=>Math.max(0,Math.min(e,u)),f=h(c.inOffset??0),g=h(m),x=h(m),b=h(c.outOffset??u),y=g-f,v=b-x;if(y<=.05||v<=.05)return l?.("SPLIT_AUDIO_SKIPPED_TOO_SMALL",{blockId:e.id,leftDuration:y,rightDuration:v}),!1;let w=Date.now(),k=e.start,S=e.start+y,j={...c,id:(0,nN.$C)(),start:k,inOffset:f,outOffset:g,duration:u,createdAt:w,updatedAt:w},I={...c,id:(0,nN.$C)(),start:S,inOffset:x,outOffset:b,duration:u,createdAt:w,updatedAt:w},N=d.reduce((e,t)=>(t.id===c.id?e.push(j,I):e.push(t),e),[]);return a({type:"SPLIT_AUDIO",previousState:{scenes:[...t.scenes??[]],audio:[...d],affectedAudioId:c.id},newState:{scenes:[...t.scenes??[]],audio:N,affectedAudioId:I.id}}),r({...t,audio:N,voiceovers:N,updatedAt:Date.now()}),n&&n(),o?.(I.id),s([]),l?.("SPLIT_AUDIO",{audioId:c.id,newAudioIds:[j.id,I.id],splitPoint:m,leftTrim:[f,g],rightTrim:[x,b],targetTime:i}),!0},[t,l,a,n,o,s,r]),h=(0,i.useCallback)((a,r)=>
97{let n;if(!t)return!1;let i=e.filter(e=>!e.sceneId.startsWith("__track0"));if(!(n=r?i.find(e=>e.id===r):i.find(e=>a>=e.start&&a<=e.start+e.duration)))return l?.("SPLIT_SKIPPED_NO_BLOCK",{targetTime:a.toFixed(3),targetBlockId:r}),!1;let s=n.type;return"caption"===n.type?u(n,a):"voiceover"===s||"audio"===s||"music"===s?m(n,a):n.scene?p(n,a):(l?.("SPLIT_SKIPPED_NO_SCENE",{blockId:n.id}),!1)},[e,t,l,m,u,p]),f=(0,i.useCallback)(()=>{let t=e.some(e=>!e.sceneId.startsWith("__track0"));if(!d&&!t){(0,ey.trackEvent)("timeline_tool_blocked",{tool:"splice",reason:"no_blocks"}),(0,nI.toast)("Nothing to cut yet",{description:"The timeline is empty. Add media or generate scenes first, then use the scissors to split a clip."});return}c(e=>!e)},[e,d]);return{isSpliceMode:d,toggleSpliceMode:f,attemptSpliceAtTime:h,disableSpliceMode:()=>c(!1)}}({blocks:q,currentProject:h,pushAction:e8,updateCoreProjectState:_,saveCurrentProject:A,setSelectedSceneIds:eb,setSelectedAudioBlockId:ek,log:sD}),{lastPanelPerScene:a3,rememberPanelForScene:a8,handleApplyEffect:a6,handleRemoveEffect:a9,handleUpdateEffect:a7,handleUpdateEffectTiming:re,applyProjectFilter:rt,updateProjectFilterParams:ra,handleApplyTransition:rr,handleRemoveTransition:rn,handleUpdateTransition:ri,deleteScenesByIds:rs,handleDeleteSelected:ro,handleDeleteSceneById:rl,handleRippleDeleteSelected:rd,handleRippleDeleteSceneById:rc}=function({currentProject:e,selectedSceneIds:t,selectedSceneId:a,pushAction:r,updateCoreProjectState:n,saveCurrentProject:s,setSelectedSceneIds:o,setSelectedAudioBlockIds:l}){let d=(0,i.useRef)(e);d.current=e;let[c,u]=(0,i.useState)(new Map),p=(0,i.useCallback)((e,t)=>{e&&u(a=>new Map(a).set(e,t))},[]),m=(0,i.useCallback)((e,t)=>{let a=d.current;if(!a?.scenes||!n)return;let i=a.scenes.map(a=>{if(a.id!==e)return a;let r=a.effects||[];(0,sv.L3)(t.type)&&(r=r.filter(e=>!(0,sv.L3)(e.type)));let n=t.type===nK.de?r.findIndex(e=>e.id===t.id):r.findIndex(e=>e.type===t.type);if(n>=0){let e=[...r];return e[n]=t,{...a,effects:e}}return{...a,effects:[...r,t]}}),o={...a,scenes:i,updatedAt:Date.now()};n(o),s?.(o),r({type:"ADD_EFFECT",previousState:{scenes:a.scenes,affectedSceneId:e},newState:{scenes:i,affectedSceneId:e}}),u(t=>new Map(t).set(e,"effects"))},[n,s,r]),h=(0,i.useCallback)((e,t)=>{let a=d.current;if(!a?.scenes||!n)return;let i=y.zC.getState();i.selectedCanvasEffect?.effectId===t&&i.setSelectedCanvasEffect(null);let o=a.scenes.map(a=>a.id!==e?a:{...a,effects:(a.effects||[]).filter(e=>e.id!==t)}),l={...a,scenes:o,updatedAt:Date.now()};n(l),s?.(l),r({type:"REMOVE_EFFECT",previousState:{scenes:a.scenes,affectedSceneId:e},newState:{scenes:o,affectedSceneId:e}}),u(t=>new Map(t).set(e,"effects"))},[n,s,r]),f=(0,i.useCallback)((e,t,a,r={})=>{let i=d.current;if(!i?.scenes||!n)return;let o=i.scenes.map(r=>r.id!==e?r:{...r,effects:(r.effects||[]).map(e=>e.id===t?{...e,params:{...e.params,...a}}:e)}),l={...i,scenes:o,updatedAt:Date.now()};n(l),!1!==r.persist&&s?.(l),u(t=>new Map(t).set(e,"effects"))},[n,s]),g=(0,i.useCallback)((e,t,a,i={})=>{let o=d.current;if(!o?.scenes||!n)return;let l=o.scenes,c=!1,p=l.map(r=>r.id!==e?r:{...r,effects:(r.effects||[]).map(e=>{if(e.id!==t)return e;let r={...e};return"startOffset"in a&&(r.startOffset=null!=a.startOffset&&Number.isFinite(a.startOffset)?Math.max(0,a.startOffset):void 0),"duration"in a&&(r.duration=null!=a.duration&&Number.isFinite(a.duration)?Math.max(0,a.duration):void 0),"number"==typeof a.laneRow&&Number.isFinite(a.laneRow)&&(r.laneRow=Math.max(0,Math.round(a.laneRow))),(r.startOffset!==e.startOffset||r.duration!==e.duration||r.laneRow!==e.laneRow)&&(c=!0),r})}),m={...o,scenes:p,updatedAt:Date.now()};n(m),!1!==i.persist&&(s?.(m),c&&r({type:"UPDATE_EFFECT_TIMING",previousState:{scenes:l,affectedSceneId:e},newState:{scenes:p,affectedSceneId:e}})),u(t=>new Map(t).set(e,"effects"))},[n,s,r]),x=(0,i.useCallback)(e=>{let t=d.current;if(!t?.scenes||!n)return;let a=null!=e?(0,nK.E3)(e):void 0;if(null!=e&&(!a||!(0,nK.Vq)(a.key)))return;let i=t.scenes.map(t=>{let a=(t.effects||[]).filter(e=>!sw(e)),r=null!=e?[...a,(0,nK.cH)(e,1,null)]:a;return{...t,effects:r}}),o={...t,scenes:i,updatedAt:Date.now()};n(o),s?.(o),r({type:"ADD_EFFECT",previousState:{scenes:t.scenes,affectedSceneId:t.scenes[0]?.id},newState:{scenes:i,affectedSceneId:i[0]?.id}}),window.dispatchEvent(new CustomEvent("faceless-studio:project-filter-change",{detail:{presetId:e??null,presetKey:a?.key??null}}))},[n,s,r]),b=(0,i.useCallback)((e,t)=>{let a=d.current;if(!a?.scenes||!n)return;let r=a.scenes.map(t=>{let a=(t.effects||[]).find(e=>sw(e));return a?{...t,effects:(t.effects||[]).map(t=>
97t.id===a.id?{...t,params:{...t.params,...e}}:t)}:t}),i={...a,scenes:r,updatedAt:Date.now()};n(i),t&&s?.(i)},[n,s]),v=(0,i.useCallback)((e,t)=>{let a=d.current;if(!a?.scenes||!n)return;let i=a.scenes.find(t=>t.id===e),o=i?.transition,l=a.scenes.map(a=>a.id!==e?a:{...a,transition:t});n({...a,scenes:l,updatedAt:Date.now()}),s?.(),r({type:"ADD_TRANSITION",previousState:{scenes:a.scenes,affectedSceneId:e,transition:o},newState:{scenes:l,affectedSceneId:e,transition:t}}),u(t=>new Map(t).set(e,"transitions"))},[n,s,r]),w=(0,i.useCallback)(e=>{let t=d.current;if(!t?.scenes||!n)return;let a=t.scenes.find(t=>t.id===e),i=a?.transition,o=t.scenes.map(t=>{if(t.id!==e)return t;let{transition:a,...r}=t;return r});n({...t,scenes:o,updatedAt:Date.now()}),s?.(),r({type:"REMOVE_TRANSITION",previousState:{scenes:t.scenes,affectedSceneId:e,transition:i},newState:{scenes:o,affectedSceneId:e}}),u(t=>new Map(t).set(e,"transitions"))},[n,s,r]),k=(0,i.useCallback)((e,t,a={})=>{let r=d.current;if(!r?.scenes||!n)return;let i=r.scenes.map(a=>a.id===e&&a.transition?{...a,transition:{...a.transition,...t}}:a);n({...r,scenes:i,updatedAt:Date.now()}),!1!==a.persist&&s?.(),u(t=>new Map(t).set(e,"transitions"))},[n,s]),S=(0,i.useCallback)(async(e,t)=>{let a=d.current;if(!e.length||!a?.scenes)return null;
97(0,eI.g_)(e),console.log("[useSceneOperations] Marked scenes as recently deleted:",e);let{archiveScene:i,setActiveProject:c}=O.w.getState();a.id&&(c(a.id),e.forEach(e=>{let t=a.scenes?.find(t=>t.id===e);t&&(i(t,"useSceneOperations.handleDeleteSelected"),console.log("[useSceneOperations] Scene archived to MediaBin before deletion:",e))}));let u=new Set(e),p=a.audio??[],m=a.captionBlocks??[],h={sceneIds:e,planSceneIdsBySceneId:{}};window.dispatchEvent(new CustomEvent("faceless:scene-deleted",{detail:h}));let f=Array.from(new Set([...a.facelessStoryboard?.detachedPlanSceneIds??[],...Object.values(h.planSceneIdsBySceneId),...e.map(e=>{let t=a.scenes?.find(t=>t.id===e);return t?.facelessPlanSceneId}).filter(e=>"string"==typeof e&&e.trim().length>0)])),g=new Set(f),x=e=>{let t=a.scenes?.find(t=>t.id===e),r=t?.facelessPlanSceneId;if("string"==typeof r&&r.trim().length>0)return r;let n=h.planSceneIdsBySceneId[e];return"string"==typeof n&&n.trim().length>0?n:void 0},b={...a.facelessStoryboard?.detachedSceneBundles??{}};for(let t of e){let e=a.scenes?.find(e=>e.id===t);if(!e)continue;let r=x(t);
97r&&(b[r]={nleSceneId:t,scene:e,audio:p.filter(e=>e.sourceSceneId===t),captions:m.filter(e=>e.sceneId===t)})}let v=Object.fromEntries(Object.entries(b).filter(([e])=>g.has(e))),w=p.filter(e=>u.has(e.sourceSceneId)||u.has(e.sceneId)||u.has(e.id)),k=new Set(w.map(e=>e.id)),S=a.scenes.filter(t=>!e.includes(t.id)),j=p.filter(e=>!w.some(t=>t.id===e.id)),I=m.filter(e=>!u.has(e.sceneId)),N=null;if(t?.ripple){let e=y.zC.getState().blocks.filter(e=>"scene"===e.type&&u.has(e.sceneId)).map(e=>({start:e.start,end:e.start+e.duration})).sort((e,t)=>e.start-t.start),t=[];for(let a of e){let e=t[t.length-1];e&&a.start<=e.end+1e-6?e.end=Math.max(e.end,a.end):t.push({...a})}t.length>0&&(N=e=>{let a=0;for(let r of t)e>=r.end-1e-6&&(a+=r.end-r.start);return a},S=S.map(e=>{let t=e.timelineStart??0,a=N(t);return a>0?{...e,timelineStart:Math.max(0,t-a),updatedAt:Date.now()}:e}),j=j.map(e=>{let t=e.start??0,a=N(t);return a>0?{...e,start:Math.max(0,t-a)}:e}),I=I.map(e=>{let t=e.start??0,a=N(t);return a>0?{...e,start:Math.max(0,t-a)}:e}))}r({type:"REMOVE_SCENE",previousState:{scenes:[...a.scenes],audio:p,captionBlocks:m,affectedSceneId:e[0]},newState:{scenes:S,audio:j,captionBlocks:I,affectedSceneId:e[0]}});let C={...a,scenes:S,audio:j,captionBlocks:I,facelessStoryboard:f.length>0?{...a.facelessStoryboard??{},detachedPlanSceneIds:f,detachedSceneBundles:v}:a.facelessStoryboard,updatedAt:Date.now()};n(C);let M=y.zC.getState();if(M.setBlocks(M.blocks.filter(e=>!(u.has(e.sceneId)||k.has(e.id))).map(e=>{if(!N||e.sceneId.startsWith("__track0"))return e;let t=N(e.start);return t>0?{...e,start:Math.max(0,e.start-t)}:e})),s)try{await s(C)}catch(e){console.error("[MasterTimeline] Error saving after batch delete:",e)}return o([]),l?.([]),C},[r,o,l,n,s]),j=(0,i.useCallback)(async()=>{let e=t.length?t:a?[a]:[];e.length&&await S(e)},[S,t,a]),I=(0,i.useCallback)(async()=>{let e=t.length?t:a?[a]:[];e.length&&await S(e,{ripple:!0})},[S,t,a]),N=(0,i.useCallback)(e=>{e&&S([e],{ripple:!0})},[S]),C=(0,i.useCallback)(e=>{e&&S([e])},[S]);return{lastPanelPerScene:c,rememberPanelForScene:p,handleApplyEffect:m,handleRemoveEffect:h,handleUpdateEffect:f,handleUpdateEffectTiming:g,applyProjectFilter:x,updateProjectFilterParams:b,handleApplyTransition:v,handleRemoveTransition:w,handleUpdateTransition:k,deleteScenesByIds:S,handleDeleteSelected:j,handleDeleteSceneById:C,handleRippleDeleteSelected:I,handleRippleDeleteSceneById:N}}({currentProject:h,selectedSceneIds:ex,selectedSceneId:eg,pushAction:e8,updateCoreProjectState:_,saveCurrentProject:A,setSelectedSceneIds:eb,setSelectedAudioBlockIds:eS}),ru=(0,y.zC)(e=>e.selectedCanvasEffect),rp=(0,y.zC)(e=>e.setSelectedCanvasEffect),rm=(0,i.useRef)(!1),rh=(0,i.useRef)(null),rf=`${ex.join(",")}|${ew.join(",")}`;(0,i.useEffect)(()=>{if(rm.current){rm.current=!1;return}rp(null)},[rf]);let rg=(0,i.useCallback)(()=>{ru&&(a9(ru.sceneId,ru.effectId),rp(null),eb([]))},[ru,a9,eb]),rx=(0,i.useRef)(()=>{}),{activeSidePanel:rb,setActiveSidePanel:ry,isEffectsPanelOpen:rv,isTransitionsPanelOpen:rw,isVoiceoverPanelOpen:rk,isMusicPanelOpen:rS,isSfxPanelOpen:rj,isCaptionsPanelOpen:rI,setPanelOpenForSceneId:rN,rememberSceneSidePanel:rC,handleSelectSidePanel:rM,handleSceneClick:r_,handleAudioBlockClick:rA,handleCaptionTemplateDrop:rE,selectedSceneForPanel:rT,selectedSceneDurationForPanel:r$,selectedSceneForTextPanels:rP,projectVfxFilter:rD}=function({blocks:e,currentProject:t,selectedSceneIds:a,selectedSceneId:r,selectedAudioBlockIds:n,selectedAudioBlockId:s,setSelectedSceneIds:o,setSelectedAudioBlockIds:l,clearSelectedTransition:d,draggedDuringInteractionRef:c,timingEditCaptionId:u,setTimingEditCaptionId:p,lastPanelPerScene:m,rememberPanelForScene:h,onDeactivateKeyframeParameterPicker:f}){let g=(0,w.O)(e=>e.activeSidePanel),x=(0,w.O)(e=>e.setActiveSidePanel),b=(0,w.O)(e=>e.lastPanelPerScene),y=(0,w.O)(e=>e.rememberScenePanel),v="effects"===g,k="transitions"===g,S="voiceover"===g,j="music"===g,I="sfx"===g,N="captions"===g,[C,M]=(0,i.useState)(null),_=(0,i.useCallback)((e,t)=>{e&&(h(e,t),y(e,t))},[h,y]),A=(0,i.useCallback)(e=>{let t=a[0]||r;(x(e),"effects"!==e&&"transitions"!==e&&f(),t&&_(t,e),"effects"===e||"transitions"===e)?M(t??null):M(null)},[f,_,r,a,x]),E=(0,i.useCallback)((e,r)=>{if(r.stopPropagation(),c.current){c.current=!1;return}if(d(),r.metaKey||r.ctrlKey)o(s4(a,e)),l(n);else{u&&p(null);
97let a=function(e){let{sceneId:t,scenes:a,activeSidePanel:r,isEffectsPanelOpen:n,isTransitionsPanelOpen:i,panelOpenForSceneId:s,lastPanelPerScene:o,rememberedScenePanels:l}=e;if(s===t&&(n||i))return{kind:"close-panel"};if("captions"===r||"effects"===r||"transitions"===r||"voiceover"===r)return{kind:"sticky",panel:r,panelOpenForSceneId:"effects"===r||"transitions"===r?t:null};let d=a?.find(e=>e.id===t);if(!d)return{kind:"none"};let c=(d.effects?.filter(e=>e.enabled).length??0)>0,u=a?.findIndex(e=>e.id===t)??-1,p=u>0?a?.[u-1]:null,m=!!(d.transition?.enabled||p?.transition?.enabled);if(c||m){let e=o.get(t)||l[t];return{kind:"auto-open",panel:"effects"===e&&c?"effects":"transitions"===e&&m?"transitions":c?"effects":"transitions",panelOpenForSceneId:t}}let h=o.get(t)||l[t];return h&&"media"!==h?{kind:"restore-remembered",panel:h}:{kind:"none"}}({sceneId:e,scenes:t?.scenes,activeSidePanel:g,isEffectsPanelOpen:v,isTransitionsPanelOpen:k,panelOpenForSceneId:C,lastPanelPerScene:m,rememberedScenePanels:b});if("close-panel"===a.kind){x("media"),M(null);return}o([e]),l([]),"sticky"===a.kind?(_(e,a.panel),M(a.panelOpenForSceneId)):"auto-open"===a.kind?(M(a.panelOpenForSceneId),x(a.panel),_(e,a.panel)):"restore-remembered"===a.kind&&(x(a.panel),_(e,a.panel),M(null))}},[a,n,o,l,t?.scenes,m,d,g,v,k,C,x,_,b,u,c,p]),T=(0,i.useCallback)((t,a)=>{if(a.stopPropagation(),c.current){c.current=!1;return}d();let r=e.find(e=>e.id===t)||null,i=r?.type==="caption"?"captions":r?.type==="voiceover"?"voiceover":r?.type==="audio"&&/^(music-|marketing-music-|faceless-ph-music-)/.test(r.id)?"music":null;if(a.metaKey||a.ctrlKey){let e=n.includes(t);l(s4(n,t)),i&&!e&&(x(i),r?.sceneId&&"music"!==i&&_(r.sceneId,i));return}o([]),l([t]),(r?.type!=="caption"||u!==t)&&p(null),i&&(x(i),r?.sceneId&&"music"!==i&&_(r.sceneId,i))},[e,n,x,_,d,o,l,u,c,p]);(0,i.useEffect)(()=>{0===n.length||e.some(e=>"caption"===e.type&&n.includes(e.id))&&x("captions")},[n,e,x]),(0,i.useEffect)(()=>{if("effects"!==g&&"transitions"!==g)return;let e=e=>{let t=e.target;t.closest("[data-effects-panel]")||t.closest("[data-transitions-panel]")||t.closest("[data-voiceover-panel]")||t.closest("[data-captions-panel]")||t.closest("[data-master-caption-overlay]")||t.closest("[data-caption-box-overlay]")||t.closest("[data-caption-inline-editor]")||t.closest("[data-effect-anchor-overlay]")||t.closest("[data-caption-block]")||t.closest("[data-scene-block]")||t.closest("[data-effects-button]")||t.closest("[data-transitions-button]")||t.closest("[data-voiceover-button]")||t.closest("[data-captions-button]")||t.closest("[data-media-bin-button]")||t.closest("[data-side-panel-tabs]")||t.closest("[data-automation-keyframe-editor]")||t.closest("[data-automation-child-lane]")||(x("media"),M(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[g,x,M]);let $=(0,i.useCallback)(t=>{o([]),l([t]),x("captions");let a=e.find(e=>e.id===t);a?.sceneId&&_(a.sceneId,"captions")},[e,x,l,o,_]),P=(0,i.useMemo)(()=>(function(e){let{scenes:t,selectedSceneIds:a,selectedSceneId:r}=e,n=a[0]||r;return n&&t&&t.find(e=>e.id===n)||null})({scenes:t?.scenes,selectedSceneIds:a,selectedSceneId:r}),[a,r,t?.scenes]),D=(0,i.useMemo)(()=>(function(e){let{blocks:t,selectedScene:a}=e,r=a?.id;if(!r)return 0;let n=t.find(e=>"scene"===e.type&&e.sceneId===r);return n?.duration??a?.media?.duration??0})({blocks:e,selectedScene:P}),[e,P]),R=(0,i.useMemo)(()=>(function(e){let{scenes:t,selectedSceneForPanel:a,selectedAudioBlockIds:r,selectedAudioBlockId:n,blocks:i}=e;if(!t?.length)return null;if(a)return a;let s=r[0]||n;if(s){let e=i.find(e=>e.id===s)?.sceneId;if(e){let a=t.find(t=>t.id===e);if(a)return a}}let o=t.filter(e=>!e.facelessPlaceholder);return o.find(e=>e.text?.trim())||o[0]||null})({scenes:t?.scenes,selectedSceneForPanel:P,selectedAudioBlockIds:n,selectedAudioBlockId:s,blocks:e}),[t?.scenes,P,s,n,e]);return{activeSidePanel:g,setActiveSidePanel:x,isEffectsPanelOpen:v,isTransitionsPanelOpen:k,isVoiceoverPanelOpen:S,isMusicPanelOpen:j,isSfxPanelOpen:I,isCaptionsPanelOpen:N,panelOpenForSceneId:C,setPanelOpenForSceneId:M,rememberSceneSidePanel:_,handleSelectSidePanel:A,handleSceneClick:E,handleAudioBlockClick:T,handleCaptionTemplateDrop:$,selectedSceneForPanel:P,selectedSceneDurationForPanel:D,selectedSceneForTextPanels:R,project
97VfxFilter:(0,i.useMemo)(()=>(function(e){let t=e?.filter(e=>!e.facelessPlaceholder);if(!t||0===t.length)return{presetId:null,mixed:!1,sceneCount:0,effect:null};let a=null,r=Array.from(new Set(t.map(e=>{let t=(0,nK.CW)(e.effects).find(e=>{let t="number"==typeof e.params?.preset?e.params.preset:null;return(0,nK.Vq)(null!=t?(0,nK.E3)(t)?.key:null)});return t&&!a&&(a=t),t&&"number"==typeof t.params?.preset?t.params.preset:null}))),n=1===r.length?r[0]:null;return{presetId:n,mixed:r.length>1,sceneCount:t.length,effect:null!=n?a:null}})(t?.scenes),[t?.scenes])}}({blocks:q,currentProject:h,selectedSceneIds:ex,selectedSceneId:eg,selectedAudioBlockIds:ew,selectedAudioBlockId:ev,setSelectedSceneIds:eb,setSelectedAudioBlockIds:eS,clearSelectedTransition:tz,draggedDuringInteractionRef:ad,timingEditCaptionId:t6,setTimingEditCaptionId:t9,lastPanelPerScene:a3,rememberPanelForScene:a8,onDeactivateKeyframeParameterPicker:(0,i.useCallback)(()=>{rx.current()},[])}),{trackAutomationState:rR,motionPresetLabelsByTrackProperty:rz,customAutomationPropertyDefinitions:rL,motionPresetDropdownOptions:rF,isKeyframeParameterPickerActive:rO,setIsKeyframeParameterPickerActive:rB,selectedKeyframeParameterKey:rW,setActiveKeyframePickerTrackId:rU,highlightedParameterPanels:rK,handleTrackParameterPickerRequest:rV,handleSelectKeyframePanelParameter:rH,getTrackAutomationPropertyOptions:rq,getTrackAutomationState:rY,toggleTrackAutomationLane:rG,addTrackAutomationLane:rX,removeTrackAutomationLane:rJ,handleTrackAutomationPropertyChange:rZ,buildTrackAutomationSegments:rQ,updateSegmentAutomationCurve:r0,beginAutomationUndoTransaction:r1,commitAutomationUndoTransaction:r5,handleContextMenuApplyMotionPreset:r2,handleTrackAutomationPresetSelect:r4,handleContextMenuAutoReframe:r3,autoReframeBySceneId:r8}=function({blocks:e,currentProject:t,getLatestProjectState:a,updateBlock:r,updateSceneAutomation:n,updateCoreProjectState:s,saveCurrentProject:o,updateVoiceover:l,pushAction:d,selectedSceneIds:c,selectedSceneId:u,setSelectedSceneIds:p,setSelectedAudioBlockIds:m,setActiveSidePanel:h,setPanelOpenForSceneId:f,rememberSceneSidePanel:g,setContextMenuState:x}){let[b,y]=(0,i.useState)({}),[w,k]=(0,i.useState)({}),[S,j]=(0,i.useState)(!1),[I,N]=(0,i.useState)(null),[C,M]=(0,i.useState)({}),[_,A]=(0,i.useState)(null),E=(0,i.useMemo)(()=>S?["effects","transitions"]:[],[S]),T=(0,i.useMemo)(()=>new Map(t_.EFFECTS.map(e=>[e.type,e])),[]),$=(0,i.useMemo)(()=>new Map(t_.TRANSITIONS.map(e=>[e.type,e])),[]),P=(0,i.useMemo)(()=>sR.map(e=>({id:e,label:sz[e].label})),[]);(0,i.useEffect)(()=>{if(!t?.scenes?.length)return;let e=function(e){let{scenes:t,audioItems:a,getEffectDefinition:r,getTransitionDefinition:n}=e,i={},s={},o={},l=["userZoom","panX","panY","rotation","volume"];for(let e of t){let t=Number(e.trackId??1),a=e.automation??{};for(let e of l){let r=a[e];if(r?.keyframes?.length&&(s[t]??=e,"userZoom"===e)){let a=o[t]??=[];a.includes(e)||a.push(e)}}for(let a of e.effects??[]){let n=a.automation??{},o=r(a.type);for(let[r,l]of Object.entries(n)){if(!l?.keyframes?.length)continue;let n=`scene:${e.id}:effect:${a.id}:${r}`,d=o?.paramRanges?.[r],c=o?.defaultParams?.[r],u="number"==typeof c?c:"number"==typeof a.params?.[r]?a.params[r]:0,p=o?.paramLabels?.[r]??r;i[n]={...s0(n,p,d?.min??-1,d?.max??1,u),binding:{panel:"effects",sceneId:e.id,effectId:a.id,paramName:r}},s[t]??=n}}if(!e.transition?.enabled)continue;let d=e.transition.automation??{},c=n(e.transition.type);for(let[a,r]of Object.entries(d)){if(!r?.keyframes?.length)continue;let n="duration"===a?`scene:${e.id}:transition:duration`:`scene:${e.id}:transition:param:${a}`,o="duration"===a?{min:aj.Cy,max:aj.u1}:c?.paramRanges?.[a],l="duration"===a?e.transition.duration:c?.defaultParams?.[a]??e.transition.params?.[a],d="number"==typeof l?l:0,u="duration"===a?"Duration":c?.paramLabels?.[a]??a;i[n]={...s0(n,u,o?.min??0,o?.max??1,d),binding:{panel:"transitions",sceneId:e.id,paramName:a}},s[t]??=n}}for(let e of a){let t=Number(e?.trackId??1),a=e.automation?.volume;if(a?.keyframes?.length){let a=String(e.id??"");if(a.startsWith("music-")||a.startsWith("marketing-music-"))continue;s[t]??="volume"}}return{hydratedCustomDefinitions:i,preferredTrackProperty:s,preferredTransformProperties:o}}({scenes:t.scenes,audioItems:t.audio||t.voiceovers||[],getEffectDefinition:e=>T.get(e),getTransitionDefinition:e=>$.get(e)});Object.keys(e.hydratedCustomDefinitions).length>0&&M(t=>({...e.hydratedCustomDefinitions,...t})),y(t=>(function(e,t){let{preferredTrackProperty:a,preferredTransformProperties:r}=t,n=!1,i={...e};for(let[e,t]of Object.entries(a)){let a=Number(e),s=r[a]?.length>0?r[a]:[t],o=i[a];if(!o){i[a]={expanded:!0,propertyId:s[0]??t,propertyIds:[...s]},n=!0;continue}let l=s5(o),d=!1;for(let e of s)l.includes(e)||(l.push(e),d=!0);d&&(i[a]={expanded:!0,propertyId:s[0]??t,propertyIds:l},n=!0)}return n?i:e})(t,e))}
97,[t?.audio,t?.scenes,t?.voiceovers,T,$]);let D=(0,i.useCallback)((e,i)=>{if("scene"!==e.type||e.sceneId.startsWith("__track0"))return;let s=a?.()??t,o=s?.scenes?.find(t=>t.id===e.sceneId)??e.scene;if(!o)return;let l=function(e,t,a){var r,n;let i={...e??{}};for(let[e,s]of Object.entries((r=t,n=a,Object.fromEntries(sz[r].valueRanges.map(e=>{var t,a,r;let i;return[e.propertyId,(t=e.propertyId,a=e.startValue,r=e.endValue,i=Math.max(.001,n),{propertyId:t,interpolation:"linear",keyframes:[{id:(0,v.generateId)(),time:0,value:a},{id:(0,v.generateId)(),time:i,value:r}]})]})))))s&&(i[e]=s);return i}(o.automation,i,Math.max(.001,e.duration)),d={...o,automation:l,updatedAt:Date.now()};r(e.id,{scene:d,automation:l}),n?.(e.sceneId,l);let c=sz[i].valueRanges.map(e=>e.propertyId),u=c[0],p=sz[i].label;if(c.length>0){let t=Number(e.trackId??1);k(e=>{let a={...e};for(let e of c)a[sQ(t,e)]=p;return a})}u&&y(t=>({...t,[e.trackId]:s2(t[e.trackId],u)}))},[t,a,k,y,r,n]),[R,z]=(0,i.useState)({}),L=(0,i.useCallback)(async e=>{if("scene"!==e.type||e.sceneId.startsWith("__track0"))return;let i=e.sceneId,s=a?.()??t,o=s?.scenes?.find(e=>e.id===i)??e.scene;if(!o||o.media?.type!=="video")return void z(e=>({...e,[i]:{status:"error",message:"Only video scenes can be reframed."}}));z(e=>({...e,[i]:{status:"running"}}));let l=e=>{z(t=>({...t,[i]:{status:"error",message:e}}))};try{let t=await (0,tD.N4)(o);if(!t)return void l("Scene media is unavailable for analysis.");let a=await (0,sB.T)(t);if(!a.success||!a.data?.success||"ready"!==a.data.status)return void l(a.error?.message||a.data?.error_message||"Subject analysis failed. Try again.");let d=a.data,c=d.source_width||o.media?.width||0,u=d.source_height||o.media?.height||0,p=sF[s?.aspectRatio??"9:16"]??sF["9:16"],m=function(e){let t,a,{keyframes:r,sourceWidth:n,sourceHeight:i,canvasWidth:s,canvasHeight:o,clipDurationSec:l,trimStartSec:d=0,existingAutomation:c}=e;if(!sO(n)||!sO(i)||!sO(s)||!sO(o)||n<=0||i<=0||s<=0||o<=0||!sO(l)||l<=0)return null;let u=(t=(0,sL.Ud)(n,i,s,o),a=Math.min(t.scaleX,t.scaleY),!Number.isFinite(a)||a<=0?1:1/a);if(u<1.12)return null;let p=Math.min(u,tM.h),m=(0,sL.Ud)(n,i,s,o),h=(r??[]).filter(e=>sO(e?.time)&&sO(e?.x)&&sO(e?.y)).map(e=>({time:e.time-d,x:Math.max(0,Math.min(1,e.x)),y:Math.max(0,Math.min(1,e.y))})).filter(e=>e.time>=-.5&&e.time<=l+.5).map(e=>({...e,time:Math.max(0,Math.min(l,e.time))})).sort((e,t)=>e.time-t.time);if(0===h.length)return null;let f=[];for(let e of h){let t=f[f.length-1];t&&1e-4>Math.abs(t.time-e.time)?f[f.length-1]=e:f.push(e)}f[0].time>1e-4&&f.unshift({...f[0],time:0}),f[f.length-1].time<l-1e-4&&f.push({...f[f.length-1],time:l});let g=[],x=[];for(let e of f){let t=(0,sL.xu)({sourceX:e.x,sourceY:e.y,fit:m,zoom:p,edgeMarginUv:.01});g.push({id:(0,v.generateId)(),time:e.time,value:t.panX}),x.push({id:(0,v.generateId)(),time:e.time,value:t.panY})}let b={propertyId:"userZoom",interpolation:"linear",keyframes:[{id:(0,v.generateId)(),time:0,value:p},{id:(0,v.generateId)(),time:l,value:p}]};return{automation:{...c??{},userZoom:b,panX:{propertyId:"panX",interpolation:"smooth",keyframes:g},panY:{propertyId:"panY",interpolation:"smooth",keyframes:x}},coverZoom:p}}({keyframes:d.keyframes??[],sourceWidth:c,sourceHeight:u,canvasWidth:p.width,canvasHeight:p.height,clipDurationSec:Math.max(.001,e.duration),trimStartSec:o.media?.trim?.start??0,existingAutomation:o.automation});if(!m)return void l("This media already fills the canvas - nothing to reframe.");let h={...o,automation:m.automation,updatedAt:Date.now()};r(e.id,{scene:h,automation:m.automation}),n?.(i,m.automation);let f=Number(e.trackId??1);k(e=>{let t={...e};for(let e of["userZoom","panX","panY"])t[sQ(f,e)]="AI Reframe";return t}),y(t=>({...t,[e.trackId]:s2(t[e.trackId],"panX")})),z(e=>{let t={...e};return delete t[i],t}),x(null),sD(`[AutoReframe] applied: scene=${i} coverZoom=${m.coverZoom.toFixed(3)} keyframes=${m.automation.panX?.keyframes.length??0} detectionRate=${d.detection_rate??"n/a"}`)}catch(e){console.error("[MasterTimeline] Auto-reframe failed:",e),l(e instanceof Error?e.message:"Unexpected error during analysis.")}},[t,a,x,k,y,r,n]),F=(0,i.useCallback)(t=>(function(e){let{blocks:t,customAutomationPropertyDefinitions:a,trackId:r}=e,n=t.filter(e=>Number(e.trackId??1)===r),i=n.filter(e=>"scene"===e.type&&!e.sceneId.startsWith("__track0")).map(e=>e.sceneId),s=Object.entries(a).filter(([,e])=>i.includes(e.binding.sceneId)).map(([e])=>e),o=n.some(e=>"scene"===e.type&&!e.sceneId.startsWith("__track0")),l=n.some(e=>"voiceover"===e.type||"audio"===e.type),d=sG.filter(e=>{let t=sX(e);return o&&t.ownerTypes.includes("scene")||l&&t.ownerTypes.includes("audio")}),c=s1({blocks:t,customAutomationPropertyDefinitions:a,trackId:r}),u=Array.from(new Set([...d,...s])).sort((e,t)=>
97{let a=c.has(e);return a===c.has(t)?0:a?-1:1});return u.length>0?u:[]})({blocks:e,customAutomationPropertyDefinitions:C,trackId:t}),[e,C]),O=(0,i.useCallback)(e=>(function(e){let{existingState:t,options:a,customAutomationPropertyDefinitions:r}=e,n=a[0]??"volume",i=[n];if(!t||0===a.length)return{expanded:!1,propertyId:n,propertyIds:i};let s=Array.from(new Set((t.propertyIds?.length?t.propertyIds:[t.propertyId]).filter(e=>a.includes(e)||!!r[e])));return 0===s.length&&s.push(n),{...t,propertyId:s[0]??n,propertyIds:s}})({existingState:b[e],options:F(e),customAutomationPropertyDefinitions:C}),[C,F,b]),B=(0,i.useCallback)(e=>{if(0===F(e).length)return;let t=O(e),a=!t.expanded;y(r=>({...r,[e]:{expanded:a,propertyId:t.propertyId,propertyIds:t.propertyIds?.length?t.propertyIds:[t.propertyId]}}))},[F,O,y]),W=(0,i.useCallback)(e=>{var t;let a,r,n,i,s=F(e);if(0===s.length)return;let o=(t=O(e),a=s5(t),r=s[0]??"volume",n=s.find(e=>!a.includes(e))??a[a.length-1]??r,{expanded:!0,propertyId:(i=[...a,n])[0]??r,propertyIds:i});y(t=>({...t,[e]:o}))},[F,O]),U=(0,i.useCallback)((t,a)=>(function(e){let{blocks:t,customAutomationPropertyDefinitions:a,trackId:r,propertyId:n}=e,i=t.filter(e=>Number(e.trackId??1)===r),s=a[n];if(s){let{binding:e}=s;for(let t of i){if("scene"!==t.type||t.sceneId.startsWith("__track0")||t.sceneId!==e.sceneId)continue;if("effects"===e.panel){let a=t.scene?.effects?.find(t=>t.id===e.effectId),r=a?.automation?.[e.paramName];if(r?.keyframes?.length)return!0;continue}let a=t.scene?.transition,r=a?.automation?.[e.paramName];if(r?.keyframes?.length)return!0}return!1}if(!sJ(n))return!1;for(let e of i){let t=e.automation,a=e.scene?.automation;if("volume"===n){let e=t?.volume??a?.volume;if(e?.keyframes?.length)return!0;continue}if("scene"!==e.type||e.sceneId.startsWith("__track0"))continue;let r=t?.[n]??a?.[n];if(r?.keyframes?.length)return!0}return!1})({blocks:e,customAutomationPropertyDefinitions:C,trackId:t,propertyId:a}),[e,C]),K=(0,i.useCallback)((e,t,a)=>{sJ(t)&&N(null),y(r=>({...r,[e]:function(e){let{existing:t,propertyId:a,currentPropertyId:r,hasCurve:n}=e,i=s5(t);if(0===i.length)return{expanded:t?.expanded??!0,propertyId:a,propertyIds:[a]};let s=r??t?.propertyId??i[0],o=s?i.indexOf(s):-1,l=null!=s&&n(s),d=[...i],c=d.includes(a);o>=0&&!l?c?d.splice(o,1):d[o]=a:c||d.push(a);let u=Array.from(new Set(d.filter(Boolean)));return 0===u.length&&u.push(a),{expanded:t?.expanded??!0,propertyId:u[0]??a,propertyIds:u}}({existing:r[e],propertyId:t,currentPropertyId:a,hasCurve:t=>U(e,t)})}))},[U]),V=(0,i.useCallback)((e,t,a)=>{let r=t.find(e=>"scene"===e.ownerType)?.ownerId??c[0]??u??null;if(h(a),j(!0),A(e),N(null),r){p([r]),m([]),f(r),g(r,a);return}f(null)},[g,u,c,h,f,m,p]),H=(0,i.useCallback)(t=>{let a=_??e.find(e=>"scene"===e.type&&e.sceneId===t.sceneId)?.trackId??null;if(null==a)return void N(e=>e===t.key?null:t.key);let r={...s0(t.key,t.label,t.min,t.max,t.defaultValue),binding:{panel:t.panel,sceneId:t.sceneId,effectId:t.effectId,paramName:t.paramName}};M(e=>({...e,[t.key]:r})),y(e=>{var r,n;let i,s;return{...e,[a]:(r=e[a],n=t.key,s=(i=s5(r)).includes(n)?i:[...i,n],{expanded:r?.expanded??!0,propertyId:s[0]??n,propertyIds:s})}}),N(t.key),j(!1),A(null)},[_,e]),q=(0,i.useCallback)((t,a)=>(function(e){let{blocks:t,customAutomationPropertyDefinitions:a,trackId:r,propertyId:n}=e,i=[...t].filter(e=>Number(e.trackId??1)===r).sort((e,t)=>e.start-t.start),s=[],o=a[n];if(o){let{binding:e}=o;for(let t of i){let a=Math.max(0,t.duration);if(a<=0||"scene"!==t.type||t.sceneId.startsWith("__track0")||t.sceneId!==e.sceneId)continue;if("effects"===e.panel){let i=t.scene?.effects?.find(t=>t.id===e.effectId);if(!i||!i.enabled)continue;let l=i.params?.[e.paramName],d="number"==typeof l?l:o.defaultValue;s.push({id:`${r}:${n}:effect:${t.sceneId}:${i.id}:${t.id}`,ownerId:t.sceneId,ownerType:"scene",blockId:t.id,target:{type:"effect",effectId:i.id,paramName:e.paramName},startTime:t.start,endTime:t.start+a,fallbackValue:d,curve:i.automation?.[e.paramName]});continue}let i=t.scene?.transition;if(!i?.enabled)continue;let l=i.params?.[e.paramName],d="number"==typeof l?l:o.defaultValue;s.push({id:`${r}:${n}:transition:${t.sceneId}:${e.paramName}:${t.id}`,ownerId:t.sceneId,ownerType:"scene",blockId:t.id,target:{type:"transition",paramName:e.paramName},startTime:t.start,endTime:t.start+a,fallbackValue:d,curve:i.automation?.[e.paramName]})}return s}if(!sJ(n))return s;for(let e of i){let t=Math.max(0,e.duration);if(t<=0)continue;let a=e.scene?.automation,i=e.automation;if("volume"===n){if("scene"===e.type&&!e.sceneId.startsWith("__track0")){s.push({id:`${r}:${n}:scene:${e.sceneId}:${e.id}`,ownerId:e.sceneId,ownerType:"scene",blockId:e.id,target:{type:"core",propertyId:n},startTime:e.start,endTime:e.start+t,fallbackValue:e.volume??e.scene?.volume??1,curve:i?.volume??a?.volume});continue}("voiceover"===e.type||"audio"===e.type)&&s.push({id:`${r}:${n}:audio:${e.id}`,ownerId:e.id,ownerType:"audio",blockId:e.id,target:{type:"core",propertyId:n},startTime:e.start,endTime:e.start+t,fallbackValue:e.volume??1,curve:i?.volume});continue}if("scene"!==e.type||e.sceneId.startsWith("__track0"))continue;let o="userZoom"===n?e.scene?.transform?.userZoom??1:"panX"===n?e.scene?.transform?.panX??0:"panY"===n?e.scene?.transform?.panY??0:e.scene?.transform?.rotation??0;s.push({id:`${r}:${n}:scene:${e.sceneId}:${e.id}`,ownerId:e.sceneId,ownerType:"scene",blockId:e.id,target:{type:"core",propertyId:n},startTime:e.start,endTime:e.start+t,fallbackValue:o,curve:i?.[n]??a?.[n]})}return s})({blocks:e,customAutomationPropertyDefinitions:C,trackId:t,propertyId:a}),[e,C]),Y=(0,i.useCallback)((a,i,d)=>
97{let c=function(e,t){if(e&&0!==e.keyframes.length)return{...e,propertyId:t,interpolation:"smooth"===e.interpolation?"smooth":"linear"}}(d,i),u=()=>t?.scenes?.find(e=>e.id===a.ownerId)??e.find(e=>e.sceneId===a.ownerId)?.scene,p=e=>{if(t?.scenes&&s){let r=t.scenes.map(t=>t.id===a.ownerId?{...t,...e,updatedAt:Date.now()}:t);s({...t,scenes:r,updatedAt:Date.now()}),o?.()}};if("scene"===a.ownerType&&"effect"===a.target.type){let e=a.target,t=u();if(!t)return;let n=function(e){let{sourceEffects:t,effectId:a,paramName:r,normalizedCurve:n,fallbackValue:i}=e;return t.map(e=>{if(e.id!==a)return e;let t={...e.automation??{}};n?t[r]=n:delete t[r];let s={...e.params??{}};n||(s[r]=i);let o=Object.keys(t).length>0?t:void 0;return{...e,params:s,automation:o}})}({sourceEffects:t.effects??[],effectId:e.effectId,paramName:e.paramName,normalizedCurve:c,fallbackValue:a.fallbackValue});r(a.blockId,{scene:{...t,effects:n}}),p({effects:n});return}if("scene"===a.ownerType&&"transition"===a.target.type){let e=a.target,t=u(),n=t?.transition;if(!t||!n)return;let i=function(e){let{sourceTransition:t,paramName:a,normalizedCurve:r,fallbackValue:n}=e,i={...t.automation??{}};r?i[a]=r:delete i[a];let s={...t.params??{}};r||(s[a]=n);let o=Object.keys(i).length>0?i:void 0;return{...t,params:s,automation:o}}({sourceTransition:n,paramName:e.paramName,normalizedCurve:c,fallbackValue:a.fallbackValue});r(a.blockId,{scene:{...t,transition:i}}),p({transition:i});return}if("scene"===a.ownerType){let e="core"===a.target.type?a.target.propertyId:"volume",{nextSceneAutomation:t,blockPatch:i}=function(e){let{sourceScene:t,corePropertyId:a,normalizedCurve:r,fallbackValue:n}=e,i=e.now??Date.now(),s={...t?.automation??{}};r?s[a]=r:delete s[a];let o=Object.keys(s).length>0?s:void 0,l=!r,d=t?.transform!=null?{...t.transform}:void 0;l&&d&&("userZoom"===a&&(d.userZoom=n),"panX"===a&&(d.panX=n),"panY"===a&&(d.panY=n),"rotation"===a&&(d.rotation=n));let c=null!=t?{...t,...l&&"volume"===a?{volume:n}:{},...d?{transform:d}:{},automation:o,updatedAt:i}:void 0;return{nextSceneAutomation:o,nextScene:c,blockPatch:{...l&&"volume"===a?{volume:n}:{},automation:o,...c?{scene:c}:{}}}}({sourceScene:u(),corePropertyId:e,normalizedCurve:c,fallbackValue:a.fallbackValue});r(a.blockId,i),n&&n(a.ownerId,t);return}let{patch:m}=function(e){let{sourceAudio:t,normalizedCurve:a,fallbackValue:r}=e,n={...t?.automation??{}};a?n.volume=a:delete n.volume;let i=Object.keys(n).length>0?n:void 0;return{patch:{...a?{}:{volume:r},automation:i}}}({sourceAudio:t?.audio?.find(e=>e.id===a.ownerId)??t?.voiceovers?.find(e=>e.id===a.ownerId),normalizedCurve:c,fallbackValue:a.fallbackValue});r(a.blockId,{...m}),l&&l(a.ownerId,{...m})},[e,t,t?.audio,t?.scenes,t?.voiceovers,o,r,s,n,l]),{beginAutomationUndoTransaction:G,commitAutomationUndoTransaction:X}=function({getLatestProjectState:e,currentProject:t,pushAction:a}){let r=(0,i.useRef)(null),n=(0,i.useCallback)(e=>e&&0!==e.length?e.map(e=>JSON.parse(JSON.stringify(e))):[],[]);return{beginAutomationUndoTransaction:(0,i.useCallback)(()=>{if(r.current)return;let a=e?.()??t;a?.scenes&&(r.current=n(a.scenes))},[n,t,e]),commitAutomationUndoTransaction:(0,i.useCallback)(()=>{let i=r.current;if(!i)return;r.current=null;let s=()=>{let r=e?.()??t,s=r?.scenes;if(!s)return;let o=n(s);JSON.stringify(i)!==JSON.stringify(o)&&a({type:"UPDATE_SCENE_AUTOMATION",previousState:{scenes:i},newState:{scenes:o}})};"function"==typeof window.requestAnimationFrame?window.requestAnimationFrame(()=>{window.requestAnimationFrame(s)}):s()},[n,t,e,a])}}({getLatestProjectState:a,currentProject:t,pushAction:d}),J=(0,i.useCallback)((e,t)=>{let a=q(e,t).filter(e=>!!e.curve);if(0!==a.length){for(let e of(G(),a))Y(e,t,void 0);X()}},[G,q,X,Y]),Z=(0,i.useCallback)((e,t)=>{let a=s5(O(e));if(0===a.length)return;let r="number"==typeof t&&t>=0&&t<a.length?t:a.length-1,n=a[r];n&&(J(e,n),k(t=>{let a=sQ(e,n);if(!(a in t))return t;let r={...t};return delete r[a],r}));let i=a.filter((e,t)=>t!==r);y(t=>({...t,[e]:{expanded:i.length>0,propertyId:i[0]??a[0],propertyIds:i.length>0?i:[a[0]]}}))},[J,O,k]),Q=(0,i.useCallback)((t,a)=>{let r=[...e].filter(e=>Number(e.trackId??1)===t&&"scene"===e.type&&!e.sceneId.startsWith("__track0")).sort((e,t)=>
97e.start-t.start);if(!r.length)return;let n=c.length?c:u?[u]:[];D(r.find(e=>n.includes(e.sceneId))??r[0],a)},[e,D,u,c]);return{trackAutomationState:b,motionPresetLabelsByTrackProperty:w,customAutomationPropertyDefinitions:C,motionPresetDropdownOptions:P,isKeyframeParameterPickerActive:S,setIsKeyframeParameterPickerActive:j,selectedKeyframeParameterKey:I,activeKeyframePickerTrackId:_,setActiveKeyframePickerTrackId:A,highlightedParameterPanels:E,handleTrackParameterPickerRequest:V,handleSelectKeyframePanelParameter:H,getTrackAutomationPropertyOptions:F,getTrackAutomationState:O,trackPropertyHasAutomationCurve:U,toggleTrackAutomationLane:B,addTrackAutomationLane:W,removeTrackAutomationLane:Z,handleTrackAutomationPropertyChange:K,buildTrackAutomationSegments:q,updateSegmentAutomationCurve:Y,beginAutomationUndoTransaction:G,commitAutomationUndoTransaction:X,handleContextMenuApplyMotionPreset:D,handleTrackAutomationPresetSelect:Q,handleContextMenuAutoReframe:L,autoReframeBySceneId:R}}({blocks:q,currentProject:h,getLatestProjectState:f,updateBlock:ef,updateSceneAutomation:z,updateCoreProjectState:_,saveCurrentProject:A,updateVoiceover:P,pushAction:e8,selectedSceneIds:ex,selectedSceneId:eg,setSelectedSceneIds:eb,setSelectedAudioBlockIds:eS,setActiveSidePanel:ry,setPanelOpenForSceneId:rN,rememberSceneSidePanel:rC,setContextMenuState:tQ});rx.current=()=>{rB(!1),rU(null)};let{handleUndo:r6,handleRedo:r9}=function({undo:e,redo:t,currentProject:a,blocks:r,setBlocks:n,addCaptionBlock:s,removeCaptionBlock:o,addVoiceover:l,removeAudioBlock:d,removeVoiceover:c,updateVoiceover:u,updateCoreProjectState:p,saveCurrentProject:m}){let h=(0,i.useCallback)(e=>{n(r.some(t=>t.id===e.id)?r.map(t=>t.id===e.id?(0,aS.zr)(e):t):[...r,(0,aS.zr)(e)])},[r,n]),f=(0,i.useCallback)(e=>{n(aN(r,e));let t={...a,captionBlocks:e,updatedAt:Date.now()};p(t),m?.(t)},[r,a,m,n,p]),g=(0,i.useCallback)(e=>{let t=y.zC.getState();t.setBlocks(aN(t.blocks,e))},[]);return{handleUndo:(0,i.useCallback)(()=>{let t=e();if(!t||!a)return;if("UPDATE_TEXT_STORY"===t.type){let e={...a,scenes:t.previousState.scenes,textStory:t.previousState.textStory,updatedAt:Date.now()};p(e),y.zC.getState().syncFromScenes(e.scenes),m?.(e);return}if("ADD_CAPTION_BLOCK"===t.type){let e=t.newState.captionBlock||t.previousState.captionBlock;e&&(o(e.id),m?.());return}if("ADD_AUDIO_BLOCK"===t.type){let e=t.newState.audioBlock||t.previousState.audioBlock;e&&(d(e.id),c?.(e.id));return}if("REMOVE_CAPTION_BLOCK"===t.type){let e=t.previousState.captionBlocks?t.previousState.captionBlocks:t.previousState.captionBlock?[t.previousState.captionBlock]:[],n=t.previousState.hiddenCaptionBlockIds||[];for(let t of e)t&&!r.some(e=>e.id===t.id)&&s(t);let i={...a,hiddenCaptionBlockIds:n,updatedAt:Date.now()};p(i),m?.(i);return}if("REMOVE_AUDIO_BLOCK"===t.type){let e=t.previousState.audioBlock;e&&l&&(console.log("[MasterTimeline] Undoing REMOVE_AUDIO_BLOCK - restoring:",e.id),l(e));return}if("UPDATE_CAPTION_BLOCK"===t.type){let e=t.previousState.captionBlocks;if(e&&e.length>0){for(let t of e)t&&h(t);m?.();return}let a=t.previousState.captionBlock;a&&(h(a),m?.());return}if("REMOVE_TRANSITION"===t.type||"ADD_TRANSITION"===t.type||"ADD_EFFECT"===t.type||"REMOVE_EFFECT"===t.type||"UPDATE_EFFECT_TIMING"===t.type){let e=t.previousState.scenes;e&&p&&(p({...a,scenes:e,updatedAt:Date.now()}),m?.());return}if("REMOVE_SCENE"===t.type&&t.previousState.scenes){let e=t.previousState.scenes,r=t.previousState.audio,n=t.previousState.captionBlocks;(0,eI.s8)(e.map(e=>e.id));let i=new Set(e.map(e=>e.facelessPlanSceneId).filter(e=>"string"==typeof e&&e.trim().length>0)),s=a?.facelessStoryboard?.detachedPlanSceneIds,o=Array.isArray(s)?s.filter(e=>!i.has(e)):s,l={...a,scenes:e,...r?{audio:r,voiceovers:r}:{},...n?{captionBlocks:n}:{},...a?.facelessStoryboard?{facelessStoryboard:{...a.facelessStoryboard,detachedPlanSceneIds:o}}:{},updatedAt:Date.now()};p(l),m?.(l);let d=y.zC.getState();d.syncFromScenes(e),r&&(d.syncAudioFromProject(r),aI(r)),n&&g(n);return}if("ADD_SCENE"===t.type&&t.previousState.scenes){let e=t.previousState.scenes,r=t.previousState.audio,n=t.previousState.captionBlocks,i={...a,scenes:e,...r?{audio:r,voiceovers:r}:{},...n?{captionBlocks:n}:{},updatedAt:Date.now()};p(i),m?.(i);let s=y.zC.getState();s.syncFromScenes(e),r&&(s.syncAudioFromProject(r),aI(r)),n&&g(n);return}if("SPLIT_SCENE"===t.type&&t.previousState.scenes){let e={...a,scenes:t.previousState.scenes,...t.previousState.audio?{audio:t.previousState.audio,voiceovers:t.previousState.audio}:{}
97,...t.previousState.captionBlocks?{captionBlocks:t.previousState.captionBlocks}:{},updatedAt:Date.now()};p(e),m?.(e);let r=y.zC.getState();r.syncFromScenes(e.scenes),e.audio&&r.syncAudioFromProject(e.audio),t.previousState.captionBlocks&&g(t.previousState.captionBlocks);return}if("SPLIT_AUDIO"===t.type&&t.previousState.audio){let e={...a,scenes:t.previousState.scenes,audio:t.previousState.audio,voiceovers:t.previousState.audio,updatedAt:Date.now()};p(e),m?.(e);let r=y.zC.getState();t.previousState.scenes&&r.syncFromScenes(t.previousState.scenes),r.syncAudioFromProject(t.previousState.audio);return}if("SPLIT_CAPTION"===t.type&&t.previousState.captionBlocks)return void f(t.previousState.captionBlocks);if("TRIM_SCENE"===t.type&&t.previousState.scenes){let e=t.previousState.affectedSceneId,i=t.previousState.scenes;if(e){let t=i.find(t=>t.id===e);if(t){let a=t.media?.trim?.start??0,i=t.media?.trim?.end??t.media?.duration??10,s=Math.max(aj.o6,i-a);n(r.map(r=>r.sceneId!==e||"scene"!==r.type?r:{...r,start:t.timelineStart??r.start,duration:s,inOffset:a,outOffset:i}))}}t.previousState.captionBlocks&&g(t.previousState.captionBlocks),p({...a,scenes:i,updatedAt:Date.now()}),m?.();return}if("REPLACE_VOICEOVER"===t.type&&t.previousState.audio){let e=t.previousState.audio,r=t.previousState.captionBlocks,n=t.previousState.scenes?.length?t.previousState.scenes:null,i=Object.prototype.hasOwnProperty.call(t.previousState,"facelessEditorTail"),s={...a,audio:e,voiceovers:e,...n?{scenes:n}:{},...r?{captionBlocks:r}:{},...i?{facelessStoryboard:aC(a.facelessStoryboard,t.previousState.facelessEditorTail)}:{},updatedAt:Date.now()};p(s),m?.(s);let o=y.zC.getState();n&&o.syncFromScenes(n),o.syncAudioFromProject(e),aI(e),r&&g(r);return}if("MOVE_BLOCK"===t.type&&!t.previousState.blockPositions&&t.previousState.audio){let e=t.previousState.audio,r=t.previousState.captionBlocks,n={...a,audio:e,voiceovers:e,...r?{captionBlocks:r}:{},updatedAt:Date.now()};p(n),m?.(n),y.zC.getState().syncAudioFromProject(e),aI(e),r&&g(r);return}if("MOVE_BLOCK"===t.type&&t.previousState.blockPositions){let e=t.previousState.blockPositions.filter(e=>!e.sceneId.startsWith("__track0")),i=new Set((t.previousState.scenes||[]).map(e=>e.id)),s=new Set(r.filter(e=>"caption"===e.type).map(e=>e.id)),o=e.filter(e=>i.has(e.sceneId)),l=e.filter(e=>!i.has(e.sceneId)),d=l.filter(e=>s.has(e.id)),c=l.filter(e=>!s.has(e.id));if(n(r.map(t=>{if(t.sceneId.startsWith("__track0"))return t;let a=e.find(e=>e.id===t.id);return a?{...t,start:a.start,trackId:a.trackId}:t})),t.previousState.scenes&&o.length>0){let e=t.previousState.scenes.map(e=>{let t=o.find(t=>t.sceneId===e.id);return t?{...e,timelineStart:t.start,trackId:t.trackId}:e});p({...a,scenes:e,updatedAt:Date.now()}),m?.()}if(u&&c.length>0)for(let e of c)u(e.id,{start:e.start,trackId:e.trackId});d.length>0&&m?.();return}let i=t.previousState.scenes;i&&p&&(p({...a,scenes:i,updatedAt:Date.now()}),m?.())},[e,a,s,l,o,d,c,u,p,m,r,n,h,f,g]),handleRedo:(0,i.useCallback)(()=>{let e=t();if(!e||!a)return;if("UPDATE_TEXT_STORY"===e.type){let t={...a,scenes:e.newState.scenes,textStory:e.newState.textStory,updatedAt:Date.now()};p(t),y.zC.getState().syncFromScenes(t.scenes),m?.(t);return}if("ADD_CAPTION_BLOCK"===e.type){let t=e.newState.captionBlock||e.previousState.captionBlock;t&&!r.some(e=>e.id===t.id)&&(s(t),m?.());return}if("ADD_AUDIO_BLOCK"===e.type){let t=e.newState.audioBlock||e.previousState.audioBlock;t&&l&&l(t);return}if("REMOVE_CAPTION_BLOCK"===e.type){let t=e.newState.captionBlocks?e.newState.captionBlocks:e.newState.captionBlock||e.previousState.captionBlock?[e.newState.captionBlock||e.previousState.captionBlock]:[],r=e.newState.hiddenCaptionBlockIds||[];for(let e of t)e&&o(e.id);let n={...a,hiddenCaptionBlockIds:r,updatedAt:Date.now()};p(n),m?.(n);return}if("REMOVE_AUDIO_BLOCK"===e.type){let t=e.previousState.audioBlock;t&&c&&(console.log("[MasterTimeline] Redoing REMOVE_AUDIO_BLOCK - deleting:",t.id),d(t.id),c(t.id));return}if("UPDATE_CAPTION_BLOCK"===e.type){let t=e.newState.captionBlocks;if(t&&t.length>0){for(let e of t)e&&h(e);m?.();return}let a=e.newState.captionBlock;a&&(h(a),m?.());return}if("REMOVE_TRANSITION"===e.type||"ADD_TRANSITION"===e.type||"ADD_EFFECT"===e.type||"REMOVE_
97EFFECT"===e.type||"UPDATE_EFFECT_TIMING"===e.type){let t=e.newState.scenes;t&&p&&(p({...a,scenes:t,updatedAt:Date.now()}),m?.());return}if("REMOVE_SCENE"===e.type&&e.newState.scenes){let t=e.newState.scenes,r=e.newState.audio,n=e.newState.captionBlocks,i=e.previousState.scenes||[],s=new Set(t.map(e=>e.id)),o=i.filter(e=>!s.has(e.id));(0,eI.g_)(o.map(e=>e.id));let l=o.map(e=>e.facelessPlanSceneId).filter(e=>"string"==typeof e&&e.trim().length>0),d=a?.facelessStoryboard?.detachedPlanSceneIds,c=l.length>0?Array.from(new Set([...Array.isArray(d)?d:[],...l])):d,u={...a,scenes:t,...r?{audio:r,voiceovers:r}:{},...n?{captionBlocks:n}:{},...a?.facelessStoryboard?{facelessStoryboard:{...a.facelessStoryboard,detachedPlanSceneIds:c}}:{},updatedAt:Date.now()};p(u),m?.(u);let h=y.zC.getState();h.syncFromScenes(t),r&&(h.syncAudioFromProject(r),aI(r)),n&&g(n);return}if("ADD_SCENE"===e.type&&e.newState.scenes){let t=e.newState.scenes,r=e.newState.audio,n=e.newState.captionBlocks,i={...a,scenes:t,...r?{audio:r,voiceovers:r}:{},...n?{captionBlocks:n}:{},updatedAt:Date.now()};p(i),m?.(i);let s=y.zC.getState();s.syncFromScenes(t),r&&(s.syncAudioFromProject(r),aI(r)),n&&g(n);return}if("SPLIT_SCENE"===e.type&&e.newState.scenes){let t={...a,scenes:e.newState.scenes,...e.newState.audio?{audio:e.newState.audio,voiceovers:e.newState.audio}:{},...e.newState.captionBlocks?{captionBlocks:e.newState.captionBlocks}:{},updatedAt:Date.now()};p(t),m?.(t);let r=y.zC.getState();r.syncFromScenes(t.scenes),t.audio&&r.syncAudioFromProject(t.audio),e.newState.captionBlocks&&g(e.newState.captionBlocks);return}if("SPLIT_AUDIO"===e.type&&e.newState.audio){let t={...a,scenes:e.newState.scenes,audio:e.newState.audio,voiceovers:e.newState.audio,updatedAt:Date.now()};p(t),m?.(t);let r=y.zC.getState();e.newState.scenes&&r.syncFromScenes(e.newState.scenes),r.syncAudioFromProject(e.newState.audio);return}if("SPLIT_CAPTION"===e.type&&e.newState.captionBlocks)return void f(e.newState.captionBlocks);if("TRIM_SCENE"===e.type&&e.newState.scenes){let t=e.newState.affectedSceneId,i=e.newState.scenes;if(t){let e=i.find(e=>e.id===t);if(e){let a=e.media?.trim?.start??0,i=e.media?.trim?.end??e.media?.duration??10,s=Math.max(aj.o6,i-a);n(r.map(r=>r.sceneId!==t||"scene"!==r.type?r:{...r,start:e.timelineStart??r.start,duration:s,inOffset:a,outOffset:i}))}}e.newState.captionBlocks&&g(e.newState.captionBlocks),p({...a,scenes:i,updatedAt:Date.now()}),m?.();return}if("REPLACE_VOICEOVER"===e.type&&e.newState.audio){let t=e.newState.audio,r=e.newState.captionBlocks,n=e.newState.scenes?.length?e.newState.scenes:null,i=Object.prototype.hasOwnProperty.call(e.newState,"facelessEditorTail"),s={...a,audio:t,voiceovers:t,...n?{scenes:n}:{},...r?{captionBlocks:r}:{},...i?{facelessStoryboard:aC(a.facelessStoryboard,e.newState.facelessEditorTail)}:{},updatedAt:Date.now()};p(s),m?.(s);let o=y.zC.getState();n&&o.syncFromScenes(n),o.syncAudioFromProject(t),aI(t),r&&g(r);return}if("MOVE_BLOCK"===e.type&&!e.newState.blockPositions&&e.newState.audio){let t=e.newState.audio,r=e.newState.captionBlocks,n={...a,audio:t,voiceovers:t,...r?{captionBlocks:r}:{},updatedAt:Date.now()};p(n),m?.(n),y.zC.getState().syncAudioFromProject(t),aI(t),r&&g(r);return}if("MOVE_BLOCK"===e.type&&e.newState.blockPositions){let t=e.newState.blockPositions,i=new Set((e.newState.scenes||[]).map(e=>e.id)),s=new Set(r.filter(e=>"caption"===e.type).map(e=>e.id)),o=t.filter(e=>i.has(e.sceneId)),l=t.filter(e=>!i.has(e.sceneId)),d=l.filter(e=>s.has(e.id)),c=l.filter(e=>!s.has(e.id));if(n(r.map(e=>{let a=t.find(t=>t.id===e.id);return a?{...e,start:a.start,trackId:a.trackId}:e})),e.newState.scenes&&o.length>0){let t=e.newState.scenes.map(e=>{let t=o.find(t=>t.sceneId===e.id);return t?{...e,timelineStart:t.start,trackId:t.trackId}:e});p({...a,scenes:t,updatedAt:Date.now()}),m?.()}if(u&&c.length>0)for(let e of c)u(e.id,{start:e.start,trackId:e.trackId});d.length>0&&m?.();return}let i=e.newState.scenes;i&&p&&(p({...a,scenes:i,updatedAt:Date.now()}),m?.())},[t,a,s,l,o,d,c,u,p,m,r,n,h,f,g])}}({undo:e6,redo:e9,currentProject:h,blocks:q,setBlocks:Y,addCaptionBlock:el,removeCaptionBlock:ed,addVoiceover:T,removeAudioBlock:ei,removeVoiceover:D,updateVoiceover:P,updateCoreProjectState:_,saveCurrentProject:A}),{handleDeleteAudioBlock:r7,handleClearAllSelection:ne}=function({currentProject:e,selectedAudioBlockId:t,selectedAudioBlockIds:a,blocks:r,audioBlocks:n,pushAction:s,removeCaptionBlock:o,setSelectedAudioBlockIds:l,updateCoreProjectState:d,saveCurrentProject:c,removeAudioBlock:u,removeVoiceover:p,setSelectedSceneIds:m,timelineLog:h}){let f=(0,i.useCallback)(t=>{if(!e)return;let a=e.hiddenCaptionBlockIds||[];if(a.includes(t.id))return void o(t.id);let r=[...a,t.id];
97s({type:"REMOVE_CAPTION_BLOCK",previousState:{scenes:[...e.scenes],captionBlocks:[t],hiddenCaptionBlockIds:a},newState:{scenes:[...e.scenes],captionBlocks:[t],hiddenCaptionBlockIds:r}}),o(t.id);let n={...e,hiddenCaptionBlockIds:r,updatedAt:Date.now()};d(n),c?.(n)},[e,s,o,d,c]);return{handleDeleteCaptionBlock:f,handleDeleteAudioBlock:(0,i.useCallback)(async()=>{let i=a.length?a:t?[t]:[];if(!i.length||!e)return;let m=[],f=[];for(let e of i){let t=r.find(t=>t.id===e);t?.type==="caption"?m.push(t):f.push(e)}if(m.length>0){let t=e.hiddenCaptionBlockIds||[],a=m.filter(e=>t.includes(e.id)),r=m.filter(e=>!t.includes(e.id));for(let e of a)o(e.id);if(r.length>0){let a=[...t,...r.map(e=>e.id)];for(let n of(s({type:"REMOVE_CAPTION_BLOCK",previousState:{scenes:[...e.scenes],captionBlocks:r,hiddenCaptionBlockIds:t},newState:{scenes:[...e.scenes],captionBlocks:r,hiddenCaptionBlockIds:a}}),r))o(n.id);let n={...e,hiddenCaptionBlockIds:a,updatedAt:Date.now()};d(n),c?.(n)}}for(let t of f){let a=n.find(e=>e.id===t),r=e.audio?.find(e=>e.id===t)||e.voiceovers?.find(e=>e.id===t);if(h("DELETE_AUDIO_BLOCK",{audioBlockId:t,type:a?.type}),r&&s({type:"REMOVE_AUDIO_BLOCK",previousState:{scenes:[...e.sce
97nes],audioBlock:{...r}},newState:{scenes:[...e.scenes],audioBlock:void 0}}),u(t),p)try{await p(t)}catch(e){console.error("[MasterTimeline] Failed to persist audio block deletion:",e)}}l([])},[a,t,e,r,n,h,s,o,u,l,p,d,c]),handleClearAllSelection:(0,i.useCallback)(()=>{m([]),l([])},[m,l])}}({currentProject:h,selectedAudioBlockId:ev,selectedAudioBlockIds:ew,blocks:q,audioBlocks:Q,pushAction:e8,removeCaptionBlock:ed,setSelectedAudioBlockIds:eS,updateCoreProjectState:_,saveCurrentProject:A,removeAudioBlock:ei,removeVoiceover:D,setSelectedSceneIds:eb,timelineLog:sD}),nt=(0,i.useCallback)(()=>{let e=ex.length>0?ex:eg?[eg]:[];if(e.length>0){let t=q.filter(t=>"scene"===t.type&&e.includes(t.sceneId));t.length>0&&eM({start:Math.min(...t.map(e=>e.start)),end:Math.max(...t.map(e=>e.start+e.duration))})}eG()},[q,eg,ex,eM,eG]),na=(0,i.useCallback)(()=>{let e=ex.length>0?ex:eg?[eg]:[],t=ew.length>0?ew:ev?[ev]:[],a=q.filter(a=>"scene"===a.type&&e.includes(a.sceneId)||t.includes(a.id));0===a.length||aW(Math.min(...a.map(e=>e.start)),Math.max(...a.map(e=>e.start+e.duration)))},[q,eg,ex,ev,ew,aW]),nr=(0,i.useCallback)(()=>{ep>0&&aW(0,ep)},[ep,aW]),nn=ex.length>0||!!eg||ew.length>0||!!ev;(0,i.useEffect)(()=>{q.length!==tr.current&&(sD("RENDER_BLOCKS_CHANGED",{prevCount:tr.current,newCount:q.length,duration:ep.toFixed(2),blockIds:q.map(e=>e.sceneId.substring(0,8)),loadingBlocks:q.filter(e=>e.scene?.isLoading||e.scene?.media?.status==="uploading"&&!e.scene?.media?.url&&!e.scene?.media?.storageKey).length}),tr.current=q.length)},[q,ep]),(0,i.useEffect)(()=>{!t6||er.some(e=>e.id===t6)||t9(null)},[er,t6]),(0,i.useEffect)(()=>{if(!t6)return;let e=e=>{"Escape"===e.key&&t9(null)},t=e=>{let t=e.target;t.closest("[data-caption-timing-overlay]")||t.closest("[data-timing-edit-active]")||t9(null)};return document.addEventListener("keydown",e),document.addEventListener("mousedown",t),()=>{document.removeEventListener("keydown",e),document.removeEventListener("mousedown",t)}},[t6]),(0,i.useEffect)(()=>{if(!tP)return;let e=e=>{let t=e.target;if(!t||"INPUT"!==t.tagName&&"TEXTAREA"!==t.tagName&&!t.isContentEditable){if("Escape"===e.key){e.preventDefault(),tz();return}("Backspace"===e.key||"Delete"===e.key)&&(e.preventDefault(),rn(tP),tz())}};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tP,rn,tz]),(0,i.useEffect)(()=>{if(!tP)return;let e=h?.scenes?.find(e=>e.id===tP);e?.transition?.enabled||tz()},[h?.scenes,tP,tz]);let ni=(0,i.useCallback)(()=>{let e=t0.current;e?.timer&&clearTimeout(e.timer),t0.current=null},[]),ns=(0,i.useCallback)((e,t,a)=>{let r=function(e){let{blockRect:t,isSceneBlock:a,clientX:r,viewportWidth:n,viewportHeight:i}=e,s=a?520:330,o=t.right+8,l=t.top;return o+220>n&&(o=t.left-220-8),o<0&&(o=Math.max(8,r)),l+s>i&&(l=Math.max(8,i-s-8)),{x:o,y:l}}({blockRect:t.getBoundingClientRect(),isSceneBlock:"scene"===e.type,clientX:a,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight});tQ({block:e,position:r})},[]),no=(0,i.useCallback)((e,t)=>{t.preventDefault(),t.stopPropagation();let a=Date.now();t0.current||a<t1.current||ns(e,t.currentTarget,t.clientX)},[ns]),nl=(0,i.useCallback)(()=>{tQ(null)},[]),{activeVolumeDragBlockId:nd,activeAudioFadeDragBlockId:nc,volumeDragIndicator:nu,audioFadeDragIndicator:np,handleContextMenuVolumeChange:nm,handleContextMenuMuteToggle:nh,handleContextMenuFadeSlopeChange:nf,handleVolumeLineMouseDown:ng,handleVolumeLineDoubleClick:nx,handleAudioFadeHandleMouseDown:nb,handleAudioFadeHandleDoubleClick:nM,handleExtractAudio:n_,handleFlattenAudioBlocks:nA}=function({blocks:e,isTrackLocked:t,setBlockVolume:r,setBlockMuted:n,setBlockAudioFadeDurations:s,setBlockAudioFadeSlopes:o,updateSceneVolume:l,updateVoiceover:d,saveCurrentProject:c,updateCoreProjectState:u,getLatestProjectState:p}){let[m,h]=(0,i.useState)(null),[f,g]=(0,i.useState)(null),[x,b]=(0,i.useState)(null),[y,w]=(0,i.useState)(null),k=(0,i.useRef)(null);(0,i.useEffect)(()=>()=>{k.current&&clearTimeout(k.current)},[]);let S=(0,i.useCallback)((t,a)=>{r(t,a);let n=e.find(e=>e.id===t);n?.sceneId&&l&&l(n.sceneId,a)},[r,e,l]),j=(0,i.useCallback)((t,a)=>{n(t,a);let r=e.find(e=>e.id===t);if(r?.sceneId&&l){let e=r.volume??1;l(r.sceneId,e,a)}},[n,e,l]),I=(0,i.useCallback)((e,t,a)=>{let r=Math.max(0,e),n=Math.max(0,Math.min(r,t)),i=Math.max(0,Math.min(Math.max(0,r-n),a));return{fadeInDuration:n,fadeOutDuration:i}},[]),N=(0,i.useCallback)(async(e,t,a)=>{if(!p||!u||!c)return;let r=p();
97if(!r||!Array.isArray(r.scenes))return;let n=r.scenes.map(r=>r.id===e?{...r,audioFadeInDuration:t,audioFadeOutDuration:a,updatedAt:Date.now()}:r),i={...r,scenes:n,updatedAt:Date.now()};u(i),await Promise.resolve(c(i))},[p,c,u]),C=(0,i.useCallback)(async(e,t,a)=>{"scene"!==e.type||e.sceneId.startsWith("__track0")?("voiceover"===e.type||"audio"===e.type)&&d&&await Promise.resolve(d(e.id,{audioFadeInDuration:t,audioFadeOutDuration:a})):await N(e.sceneId,t,a)},[N,d]),M=(0,i.useCallback)(async(e,t,a)=>{if(!p||!u||!c)return;let r=p();if(!r||!Array.isArray(r.scenes))return;let n=r.scenes.map(r=>r.id===e?{...r,audioFadeInSlope:t,audioFadeOutSlope:a,updatedAt:Date.now()}:r),i={...r,scenes:n,updatedAt:Date.now()};u(i),await Promise.resolve(c(i))},[p,c,u]),_=(0,i.useCallback)((a,r)=>{let n=e.find(e=>e.id===a);if(!n||t(n.trackId||1))return;let i=Math.max(0,Math.min(1,r));(o?.(a,i,i),"scene"!==n.type||n.sceneId.startsWith("__track0"))?("voiceover"===n.type||"audio"===n.type)&&d&&Promise.resolve(d(n.id,{audioFadeInSlope:i,audioFadeOutSlope:i})):M(n.sceneId,i,i)},[e,t,M,o,d]),A=(0,i.useCallback)((e,a)=>{if(e.detail>1||(e.stopPropagation(),e.preventDefault(),t(a.trackId||1)))return;let n=e.currentTarget,i=n.parentElement,s=i?.getBoundingClientRect()??n.getBoundingClientRect();if(s.height<=0)return;let o=e=>Math.max(0,Math.min(2,e)),c=a.volume??1,u=c,p=c,m=e.clientX,f=e.clientY,g=null,x=(e,t,n=!1)=>{var i;let l=o(2*((s.bottom-t)/s.height));n?u=l:u+=(l-u)*.38,(Math.abs((c=o(u))-p)>=.004||n)&&(p=c,r(a.id,c)),i=c,b({x:Math.max(10,Math.min(window.innerWidth-56,e+14)),y:Math.max(10,Math.min(window.innerHeight-26,t-18)),volume:i})};h(a.id),x(e.clientX,e.clientY,!0);let y=()=>{g=null,x(m,f)},v=e=>{m=e.clientX,f=e.clientY,null===g&&(g=requestAnimationFrame(y))},w=()=>{(null!==g&&(cancelAnimationFrame(g),g=null),x(m,f,!0),document.removeEventListener("mousemove",v),document.removeEventListener("mouseup",w),h(null),b(null),"scene"===a.type&&l&&!a.sceneId.startsWith("__track0"))?l(a.sceneId,c,a.muted):("voiceover"===a.type||"audio"===a.type)&&d&&d(a.id,{volume:c})};document.addEventListener("mousemove",v),document.addEventListener("mouseup",w)},[t,r,l,d]),E=(0,i.useCallback)((e,a)=>{e.stopPropagation(),e.preventDefault(),t(a.trackId||1)||(h(null),r(a.id,1),(b({x:Math.max(10,Math.min(window.innerWidth-56,e.clientX+14)),y:Math.max(10,Math.min(window.innerHeight-26,e.clientY-18)),volume:1,pulseNonce:Date.now()}),k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{b(null),k.current=null},820),"scene"===a.type&&l&&!a.sceneId.startsWith("__track0"))?l(a.sceneId,1,a.muted):("voiceover"===a.type||"audio"===a.type)&&d&&d(a.id,{volume:1}))},[t,r,l,d]),T=(0,i.useCallback)((e,a,r)=>{if(e.detail>1||(e.stopPropagation(),e.preventDefault(),t(a.trackId||1)))return;let n=e.currentTarget.parentElement,i=n?.getBoundingClientRect();if(!i||i.width<=0)return;let o=Math.max(0,a.duration),l=Math.max(0,a.audioFadeInDuration??0),d=Math.max(0,a.audioFadeOutDuration??0),c=e=>e/i.width*o,u=l,p=d,m=e.clientX,h=e.clientY,f=null,x=(e,t,a)=>{w({x:Math.max(10,Math.min(window.innerWidth-86,e+14)),y:Math.max(10,Math.min(window.innerHeight-26,t-18)),seconds:a,edge:r})},b=(e,t)=>{if("in"===r){let a=I(o,c(e-i.left),p);u=a.fadeInDuration,p=a.fadeOutDuration,x(e,t,u)}else{let a=c(i.right-e),r=I(o,u,a);u=r.fadeInDuration,x(e,t,p=r.fadeOutDuration)}s(a.id,u,p)};g(a.id),b(e.clientX,e.clientY);let y=()=>{f=null,b(m,h)},v=e=>{m=e.clientX,h=e.clientY,null===f&&(f=requestAnimationFrame(y))},k=()=>{null!==f&&(cancelAnimationFrame(f),f=null),b(m,h),document.removeEventListener("mousemove",v),document.removeEventListener("mouseup",k),g(null),w(null),C(a,u,p)};document.addEventListener("mousemove",v),document.addEventListener("mouseup",k)},[I,t,C,s]),$=(0,i.useCallback)((e,a,r)=>{if(e.stopPropagation(),e.preventDefault(),t(a.trackId||1))return;let n="in"===r?0:Math.max(0,a.audioFadeInDuration??0),i="out"===r?0:Math.max(0,a.audioFadeOutDuration??0),o=I(a.duration,n,i);s(a.id,o.fadeInDuration,o.fadeOutDuration),C(a,o.fadeInDuration,o.fadeOutDuration)},[I,t,C,s]);return{activeVolumeDragBlockId:m,activeAudioFadeDragBlockId:f,volumeDragIndicator:x,audioFadeDragIndicator:y,handleContextMenuVolumeChange:S,handleContextMenuMuteToggle:j,handleContextMenuFadeSlopeChange:_,handleVolumeLineMouseDown:A,handleVolumeLineDoubleClick:E,handleAudioFadeHandleMouseDown:T,handleAudioFadeHandleDoubleClick:$,handleExtractAudio:(0,i.useCallback)(async t=>{console.warn("[EXTRACT-AUDIO] Handler fired for blockId:",t);let a=e.find(e=>e.id===t);if(!a?.sceneId){console.error("[EXTRACT-AUDIO] Block not found:",t),nI.toast.error("Could not find the selected video scene.");return}let i=a.sceneId;console.warn("[EXTRACT-AUDIO] Calling backend for scene:",i);let s=p?.()?.id;if(!s)return void nI.toast.error("No project loaded.");try{nI.toast.info("Extracting audio from videoâ¦");let e=await (0,sN.R)(s,i);if(console.warn("[EXTRACT-AUDIO] Backend response:",e),!e.success||!e.audio_block){let t=e.message||"Unknown error";console.error("[EXTRACT-AUDIO] Failed:",t),nI.toast.error(t);return}let t=e.audio_block;if(console.warn("[EXTRACT-AUDIO] Success! Audio block:",t),r(a.id,0),n(a.id,!0),p&&u&&c){let e=p();
97if(e){let a=Array.isArray(e.scenes)?e.scenes.map(e=>e.id===i?{...e,volume:0,muted:!0,updatedAt:Date.now()}:e):e.scenes,r={id:t.id,type:"audio",url:t.url,storageKey:t.storage_key,duration:t.duration,start:t.start,trackId:t.trackId,text:t.label,volume:1,status:"ready",sourceSceneId:i,inOffset:0,outOffset:t.duration,createdAt:Date.now(),updatedAt:Date.now()},n=(Array.isArray(e.audio)?e.audio:[]).filter(e=>e.id!==r.id&&("audio"!==e.type||e.sourceSceneId!==i||e.storageKey!==r.storageKey)),s={...e,scenes:a,audio:[...n,r],updatedAt:Date.now()};u(s),await Promise.resolve(c(s)),nI.toast.success("Audio extracted to a new track.");return}}l&&await Promise.resolve(l(i,0,!0)),nI.toast.success("Audio extracted. Refresh the timeline if it does not appear immediately.")}catch(e){console.error("[EXTRACT-AUDIO] Unexpected error:",e),nI.toast.error(e instanceof Error?e.message:"Failed to extract audio")}},[e,r,n,p,u,c,l]),handleFlattenAudioBlocks:(0,i.useCallback)(async r=>{let n=e.filter(e=>r.includes(e.id));if(n.length<2)return void nI.toast.error("Select at least two audio blocks to flatten.");if(n.some(e=>t(e.trackId||1)))return void nI.toast.error("Unlock the track before flattening its audio.");if(!p||!u||!c)return void nI.toast.error("Project state is not available.");let i=p();if(!i?.id)return void nI.toast.error("No project loaded.");try{nI.toast.info(`Flattening ${n.length} audio blocksâ¦`);let{renderAudioBlocksToWav:e}=await a.e(833).then(a.bind(a,10833)),{blob:t,rangeStart:r,rangeDuration:s}=await e(n),{uploadAudioFile:o}=await Promise.resolve().then(a.bind(a,9756)),l=await o(i.id,new File([t],`flattened-${Date.now()}.wav`,{type:"audio/wav"}),{probeDuration:!1});if(!l.success||!l.url)throw Error(l.errorMessage||"The flattened audio upload failed.");let d=new Set(n.map(e=>e.id)),p=n.reduce((e,t)=>Math.min(e,t.trackId||2),n[0].trackId||2),m=Date.now(),h={id:`flattened-${(0,v.generateId)()}`,type:"audio",url:l.url,storageKey:l.storageKey,start:r,duration:s,trackId:p,inOffset:0,outOffset:s,volume:1,text:`Flattened audio (${n.length} clips)`,status:"ready",generatedAt:m,createdAt:m,updatedAt:m},f=Array.isArray(i.audio)?i.audio:[],g=Array.isArray(i.voiceovers)?i.voiceovers:[],x=[...(f.length>0?f:g).filter(e=>!d.has(e.id)),h],b={...i,audio:x,voiceovers:x,updatedAt:m};u(b),await Promise.resolve(c(b)),nI.toast.success(`Flattened ${n.length} blocks into one clip.`)}catch(e){console.error("[FLATTEN-AUDIO] Failed:",e),nI.toast.error(e instanceof Error?e.message:"Failed to flatten audio blocks.")}},[e,p,t,c,u])}}({blocks:q,isTrackLocked:eT,setBlockVolume:eF,setBlockMuted:eO,setBlockAudioFadeDurations:eB,setBlockAudioFadeSlopes:eW,updateSceneVolume:R,updateVoiceover:P,saveCurrentProject:A,updateCoreProjectState:_,getLatestProjectState:f}),nE=(0,i.useCallback)(async e=>{let t=ex.length>1&&ex.includes(e)?ex:[e],a=h?.scenes?.filter(e=>t.includes(e.id)).map(e=>e.id)??t;try{let e=f?.()?.scenes??h?.scenes??[],t=C(a);t&&t.newScenes.length>0&&e.length>0&&e8({type:"ADD_SCENE",previousState:{scenes:e,affectedSceneId:t.newScenes[0].id},newState:{scenes:t.updatedScenes,affectedSceneId:t.newScenes[0].id}})}catch(e){console.error("[MasterTimeline] Failed to duplicate scenes from context menu:",a,e)}},[ex,h?.scenes,C,f,e8]),nT=(0,i.useCallback)(e=>{ex.length>1&&ex.includes(e)?ro():rl(e)},[ex,ro,rl]),n$=(0,i.useCallback)(e=>{ex.length>1&&ex.includes(e)?rd():rc(e)},[ex,rd,rc]),nP=(0,i.useCallback)(e=>ex.length>1&&ex.includes(e)?ex.length:1,[ex]),nD=(0,i.useCallback)(async e=>{let t,a,r=es(e).filter(e=>"scene"===e.type).map(e=>e.sceneId),n=r.length>0?await rs(r):null;eo(e);let i=n??f?.()??h;if(!i)return;let s=(t=(i.scenes??[]).map(t=>{let a=t.trackId??1;return a>e?{...t,trackId:a-1}:t}),a=(i.audio??i.voiceovers??[]).filter(t=>(t.trackId??2)!==e).map(t=>{let a=t.trackId??2;return a>e?{...t,trackId:a-1}:t}),{...i,scenes:t,audio:a,voiceovers:a,updatedAt:Date.now()});_(s);try{await A?.(s)}catch(e){console.error("[MasterTimeline] Failed to persist track delete:",e)}},[es,rs,eo,f,h,_,A]),nR=function({getBlocksOnTrack:e,executeTrackDelete:t}){let[a,r]=(0,i.useState)(null),n=(0,i.useCallback)(a=>{let n=e(a);if(0===n.length)return void t(a);let i=n.filter(e=>"scene"===e.type).length;r({trackId:a,sceneCount:i,otherCount:n.length-i})},[t,e]),s=(0,i.useCallback)(()=>r(null),[]),o=(0,i.useCallback)(()=>
97{if(!a)return;let{trackId:e}=a;r(null),t(e)},[t,a]);return{pendingTrackDelete:a,requestTrackDelete:n,cancelTrackDelete:s,confirmTrackDelete:o}}({getBlocksOnTrack:es,executeTrackDelete:nD}),nz=(0,i.useMemo)(()=>q.length?Math.max(1,...q.map(e=>e.trackId||1)):1,[q]),nL=(0,i.useMemo)(()=>{let e=t5?Math.max(nz,tn.current):nz,t=ag?.trackId??0;return Math.min(aj.Sj,Math.max(1,e,ap??0,t))},[t5,nz,ap,ag]),nF=tk?nL+1:nL,nO=(0,i.useMemo)(()=>(function(e){let t=new Map;for(let a of e){let e=Number(a.trackId??1);"caption"!==a.type?t.set(e,!0):t.has(e)||t.set(e,!1)}return t})(q),[q]),nB=(0,i.useCallback)(e=>{let t;return t=eD.get(e),t?.type==="caption"&&!0!==nO.get(e)},[eD,nO]),nW=(0,i.useMemo)(()=>(function(e){let{visibleTrackCount:t,showTrack0:a,trackMeta:r,isCaptionOnlyTrack:n}=e,i=[];for(let e=0;e<t;e++)i.push(a?e:e+1);return i.sort((e,t)=>{if(e===t)return 0;if(0===e||0===t)return 0===e?-1:1;let a=r.get(e),i=r.get(t),s=n(e),o=n(t),l=s?Math.max(1,a?.parentTrackId??e):e,d=o?Math.max(1,i?.parentTrackId??t):t;return l!==d?l-d:s!==o?s?1:-1:e-t})})({visibleTrackCount:nF,showTrack0:tk,trackMeta:eD,isCaptionOnlyTrack:nB}),[nF,tk,eD,nB]),nU=(0,i.useRef)(nF),nV=(0,i.useMemo)(()=>(function(e){let{orderedVisibleTrackIds:t,blocks:a,scenes:r,effectsLaneCollapsed:n,effectsLaneRowHeights:i}=e,s=new Map,o=new Map((r||[]).map(e=>[e.id,e]));for(let e of t){if(0===e){s.set(e,{laneBlocks:[],rowCount:1,hasEffects:!1,collapsed:!1,totalHeight:0,rowHeight:aj.LQ});continue}let t=a.filter(t=>"scene"===t.type&&Number(t.trackId??1)===e),r=[],l=-1,d=!1;for(let e of t){let t=o.get(e.sceneId);if(!t)continue;let a=(0,nK.CW)(t.effects).filter(e=>!1!==e.enabled),n=Math.max(0,e.duration);if(0===a.length&&(0,oJ.K3)(t)&&t.facelessPlaceholderHints?.willDeliverFx===!0&&n>0){l=Math.max(l,0),r.push({effectId:`faceless-ph-fx-${e.sceneId}`,sceneId:e.sceneId,label:"Loading effects",sceneStartSec:e.start,sceneDurationSec:n,startOffsetSec:0,durationSec:n,isFullScene:!0,windowable:!1,isFilter:!1,isLoading:!0,momentRow:0});continue}for(let t of a){let a="number"==typeof t.params?.preset?t.params.preset:null,i=null!=a?(0,nK.E3)(a):void 0,s=(0,nK.Vq)(i?.key),o=null==t.startOffset&&null==t.duration,c=Math.max(0,Math.min(n,t.startOffset??0)),u=o?n:Math.max(.1,Math.min(t.duration??n-c,n-c)),p=s?null:Math.max(0,Math.round(t.laneRow??0));s?d=!0:l=Math.max(l,p),r.push({effectId:t.id,sceneId:e.sceneId,label:i?.name?.replace(/\s*\(Animated\)\s
97*$/i,"")??"VFX",sceneStartSec:e.start,sceneDurationSec:n,startOffsetSec:c,durationSec:u,isFullScene:o,windowable:!0,isFilter:s,momentRow:p})}}let c=l>=0?l+1:0,u=r.map(({momentRow:e,...t})=>({...t,laneRow:t.isFilter?c:e})),p=u.length>0,m=Math.max(1,c+ +!!d),h=!0===n[e],f=i.get(e)??aj.LQ,g=p?h?aj.dP+aj.w_:aj.dP+m*f+aj.yk:0;s.set(e,{laneBlocks:u,rowCount:m,hasEffects:p,collapsed:h,totalHeight:g,rowHeight:f})}return s})({orderedVisibleTrackIds:nW,blocks:q,scenes:h?.scenes,effectsLaneCollapsed:tC,effectsLaneRowHeights:a0}),[nW,q,h?.scenes,tC,a0]),{layout:nH,totalContentHeight:nq}=(0,i.useMemo)(()=>(function(e){let{orderedVisibleTrackIds:t,getTrackHeight:a,getAutomationLaneHeight:r,trackAutomationState:n,getEffectsLaneTotalHeight:i,minimumTotalContentHeight:s=0}=e,o=new Map,l=0;for(let e of t){let t=a(e);o.set(e,{top:l,height:t}),l+=t;let s=n[e];s?.expanded===!0&&(l+=Math.max(1,s?.propertyIds?.length??+!!s?.propertyId)*(sr.ko+r(e))),l+=i(e)}let d=Math.max(0,s-l),c=t[t.length-1],u=o.get(c);return d>0&&u&&(o.set(c,{...u,height:u.height+d}),l+=d),{layout:o,totalContentHeight:l}})({orderedVisibleTrackIds:nW,getTrackHeight:aK,getAutomationLaneHeight:aY,trackAutomationState:rR,getEffectsLaneTotalHeight:e=>nV.get(e)?.totalHeight??0,minimumTotalContentHeight:tx<=900?Math.max(0,ty-aj.Dm):0}),[nW,aK,aY,aq,rR,aJ,nV,ty,tx]),nY=Math.max(nq,aj.ol),nG=tj?aj.E0:nY+aj.E0+aj.Dm,nX=tj?aj.E0:Math.min(nG,tw),nJ=(0,i.useRef)(null),nZ=(0,i.useRef)(nX);nZ.current=nX;let n0=t5&&td.current&&tl.current?Math.max(0,nq-tl.current.totalContentHeight):0,n1=t5&&null!==nJ.current?nJ.current+n0:nX,n5=(0,i.useCallback)((e,t=aj.ol)=>{let a=function(e){let{desiredTotalHeight:t,minLaneHeight:a,orderedVisibleTrackIds:r,getTrackHeight:n,getAutomationLaneHeight:i,trackAutomationState:s,getEffectsLaneInfo:o}=e;if(!Number.isFinite(t))return null;let l=[...r];if(0===l.length)return null;let d=l.map(e=>({kind:"track",trackId:e,weight:1,start:n(e),min:a,max:aj.Uu})),c=[],u=[],p=0,m=0;for(let e of l){let t=o(e);t?.hasEffects&&(t.collapsed?m+=t.totalHeight:(m+=aj.dP+aj.yk,u.push({kind:"effects",trackId:e,weight:t.rowCount,start:t.rowHeight,min:Math.min(aj.GX,t.rowHeight),max:aj.s4})));let a=s[e];if(a?.expanded!==!0)continue;let r=Math.max(1,a.propertyIds?.length??+!!a.propertyId);p+=r*sr.ko,c.push({kind:"automation",trackId:e,weight:r,start:i(e),min:sr.SU,max:sr.O$})}let h=[...d,...c,...u],f=h.reduce((e,t)=>e+t.weight*t.start,0);if(f<=0)return null;let g=Math.max(h.reduce((e,t)=>e+t.weight*t.min,0),Math.min(h.reduce((e,t)=>e+t.weight*t.max,0),t-p-m));if(.5>Math.abs(g-f))return null;let x=h.map(e=>e.start),b=new Set,y=g;for(let e=0;e<=h.length;e++){let e=[],t=0;for(let a=0;a<h.length;a++)b.has(a)||(e.push(a),t+=h[a].weight*h[a].start);if(0===e.length||t<=0)break;let a=y/t,r=!1;for(let t of e){let e=h[t],n=e.start*a;n<=e.min?(n=e.min,b.add(t),r=!0):n>=e.max&&(n=e.max,b.add(t),r=!0),x[t]=n}if(!r)break;let n=0;for(let e of b)n+=h[e].weight*x[e];y=g-n}let v={trackUpdates:[],automationUpdates:[],effectsRowHeightUpdates:[]};for(let e=0;e<h.length;e++){let t=h[e];"track"===t.kind?v.trackUpdates.push([t.trackId,x[e]]):"automation"===t.kind?v.automationUpdates.push([t.trackId,x[e]]):v.effectsRowHeightUpdates.push([t.trackId,x[e]])}return v}({desiredTotalHeight:e,minLaneHeight:t,orderedVisibleTrackIds:nW,getTrackHeight:aK,getAutomationLaneHeight:aY,trackAutomationState:rR,getEffectsLaneInfo:e=>nV.get(e)});if(a){for(let[e,t]of a.effectsRowHeightUpdates)aQ(e,t);a.trackUpdates.length&&aH(a.trackUpdates),a.automationUpdates.length&&aX(a.automationUpdates)}},[nW,aK,aY,aH,aX,aQ,rR,nV]);(0,i.useEffect)(()=>{if(t5)return;if(nF<=nU.current){nU.current=nF;return}let e=nq-(nF-nU.current)*aj.h2;e>0&&n5(e),nU.current=nF},[t5,nF,nq,n5]),(0,i.useEffect)(()=>{if(!t5)return;let e=tl.current;!e||td.current||nF<=e.visibleTrackCount||(td.current=!0,n5(e.totalContentHeight),nU.current=nF)},[t5,nF,n5]),(0,i.useEffect)(()=>{if(tj)return;let e=null,t=null,a=()=>{if(e=null,null==t)return;let a=Math.min(aj.ol,20),r=aj.E0+aj.Dm+Math.max(1,nF)*a;n5(Math.max(a,Math.min(aj.E0+aj.Dm+Math.max(1,nF)*aj.Uu,Math.max(r,window.innerHeight-t))-aj.E0-aj.Dm),a),t=null},r=r=>{let n=r.detail?.bottomEdge;Number.isFinite(n)&&(t=n,null==e&&(e=(0,o.EP)(a)))};return window.addEventListener("preview-vertical-resize",r),()=>{null!=e&&cancelAnimationFrame(e),window.removeEventListener("preview-vertical-resize",r)}},[tj,nF,n5]);let n2=(0,i.useCallback)(e=>nH.get(e)||{top:0,height:aj.h2},[nH]),n4=(0,i.useCallback)(e=>n2(e).height,[n2]),n8=(0,i.useCallback)(e=>{let t=n2(e),a=rY(e),r=s5(a),n=a.expanded?Math.max(1,r.length):0;if(0===n)return{top:t.top,parentHeight:t.height,laneTop:t.top+t.height,laneHeight:0,laneCount:0,propertyIds:[],exp
97anded:!1};let i=t.height,s=Math.max(0,aY(e)),o=t.top+i+sr.ko;return{top:t.top,parentHeight:i,laneTop:o,laneHeight:s,laneCount:n,propertyIds:r,expanded:!0}},[rY,n2,aY,aJ]),n6=(0,i.useCallback)(e=>{let t=n8(e);return{top:t.top,height:t.parentHeight}},[n8]),n9=(0,i.useCallback)(e=>{let t=nV.get(e);if(!t||!t.hasEffects)return{top:0,height:0,rowCount:0,rowHeight:aj.LQ,collapsed:!1,hasEffects:!1,laneBlocks:[]};let a=n8(e),r=a.laneCount>0?a.laneCount*(a.laneHeight+sr.ko):0;return{top:a.top+a.parentHeight+r+aj.dP,height:t.collapsed?aj.w_:t.rowCount*t.rowHeight+aj.yk,rowCount:t.rowCount,rowHeight:t.rowHeight,collapsed:t.collapsed,hasEffects:!0,laneBlocks:t.laneBlocks}},[nV,n8]),n7=(0,i.useCallback)((e,t,a,r)=>{re(e,t,a,{persist:r})},[re]),ie=(0,i.useCallback)((e,t,a)=>{if((1!==ex.length||ex[0]!==e)&&(rm.current=!0),rp({sceneId:e,effectId:t}),eb([e]),ry("effects"),w.O.getState().requestEffectInspect(e,t),rN(e),rC(e,"effects"),a){let e=a.sceneStartSec+a.startOffsetSec,t=e+a.durationSec,r=y.zC.getState().projectTime;(r<e||r>t)&&rh.current?.(Math.min(e+.05,t),!0)}},[ex,eb,ry,rN,rC]),it=(0,i.useCallback)(e=>{tA(t=>({...t,[e]:!t[e]}))},[]),ia=(0,i.useCallback)(e=>nV.get(e)?.totalHeight??0,[nV]),ir=(0,i.useCallback)(e=>!0===tC[e],[tC]),ii=(0,i.useCallback)(e=>{let t=u.current;if(!t)return null;let a=e-t.getBoundingClientRect().top-aj.Dm+t.scrollTop,r=nW[0]??+!tk,n=nW[nW.length-1]??(tk?nF-1:nF);return function(e){let{localY:t,totalContentHeight:a,orderedVisibleTrackIds:r,getTrackLayout:n,firstTrack:i,lastTrack:s,maxNumericVisibleTrack:o,maxAutoExpandTrack:l,clampTrackId:d,expandState:c}=e,u=null!==c.expansionTrack&&o>=c.expansionTrack?c.expansionTrack:null;if(o<l||null!==u){let e;if(t>=(null!==u?Math.min(n(u).top,a):a)-(e=n(null!==u?r.filter(e=>0!==e&&e<u).pop()??s:s).height,Math.min(aj.Uj,Math.max(8,Math.floor(e/3))))){if(null===c.armed&&(c.armed=!1),c.armed){let e=u??d(o+1);return c.expansionTrack=e,e}}else c.armed=!0}if(t<=0)return i;if(t>=a)return s;for(let e of r){let{top:a,height:r}=n(e);if(t>=a&&t<a+r)return e}return s}({localY:a,totalContentHeight:nq,orderedVisibleTrackIds:nW,getTrackLayout:n2,firstTrack:r,lastTrack:n,maxNumericVisibleTrack:tk?nF-1:nF,maxAutoExpandTrack:to.current??aj.Sj,clampTrackId:sl,expandState:ts.current})},[n2,nW,tk,nq,nF]),is=(0,i.useMemo)(()=>t6&&er.find(e=>e.id===t6)||null,[er,t6]),io=(0,i.useMemo)(()=>{if(!is)return null;let e=q.find(e=>"scene"===e.type&&e.sceneId===is.sceneId&&!!e.scene)||q.find(e=>("voiceover"===e.type||"audio"===e.type)&&e.id===is.sceneId)||null;if(!e)return null;let t=function(e){let{anchorBlock:t,blocks:a,blobUrl:r}=e,n=Math.max(t.duration,.001),i="voiceover"===t.type||"audio"===t.type,s=t.scene;if(s){let e,a,o,l,d,c,u,p=(e=s.media?.url||s.media?.storedUrl||null,a=s.audio?.persistentUrl||s.audio?.audio_url||null,o=s.audio?.storageKey||s.audio?.storage_key||void 0,l=s.audio?.assetRef,d=s.media?.type==="video"&&(r||e)||null,c=s.media?.type==="video"&&(s.media?.storageKey||s.media?.storage_key)||void 0,u=s.media?.type==="video"?s.media?.assetRef:void 0,{sceneAudioUrl:a||d,sceneAudioStorageKey:a?o:c,sceneAudioAssetRef:a?l:u});if(p.sceneAudioUrl)return{url:p.sceneAudioUrl,storageKey:p.sceneAudioStorageKey,assetRef:p.sceneAudioAssetRef,startInScene:0,duration:n,inOffset:t.inOffset,volume:la(t.volume),analysisSource:{sourceType:i?"voiceover"===t.type?"voiceover":"project_audio":"scene_audio",sourceSceneId:s.id,sourceAudioBlockId:t.id,storageKey:p.sceneAudioStorageKey}}}let o=t.start,l=o+n,d=e=>Math.min(e.start+e.duration,l)-Math.max(e.start,o),c=a.filter(e=>("voiceover"===e.type||"audio"===e.type)&&!!e.audioUrl&&!e.isLoading&&e.id!==t.id),u=c.filter(e=>e.sceneId===t.sceneId),p=u.length?u:c.filter(e=>"voiceover"===e.type&&d(e)>.01);if(0===p.length)return null;let m=[...p].sort((e,t)=>+("voiceover"!==e.type)!=+("voiceover"!==t.type)?("voiceover"!==e.type)-("voiceover"!==t.type):d(t)-d(e))[0],h=Math.max(m.start,o),f=Math.min(m.start+m.duration,l)-h;return f<=.01?null:{url:m.audioUrl,storageKey:m.audioStorageKey,assetRef:m.scene?.audio?.assetRef,startInScene:h-o,duration:f,inOffset:m.inOffset+(h-m.start),volume:la(m.volume),analysisSource:{sourceType:"voiceover"===m.type?"voiceover":"project_audio",sourceSce
97neId:m.scene?.id,sourceAudioBlockId:m.id,storageKey:m.audioStorageKey}}}({anchorBlock:e,blocks:q,blobUrl:e.scene?eU?.[e.scene.id]:null}),{top:a,height:r}=n6(is.trackId),n=t?.analysisSource.sourceAudioBlockId,i=(n?q.find(e=>e.id===n&&("voiceover"===e.type||"audio"===e.type)):null)??null;if(!i){let t=e.start,a=t+Math.max(e.duration,.001),r=e=>Math.min(e.start+e.duration,a)-Math.max(e.start,t),n=q.filter(e=>"voiceover"===e.type||"audio"===e.type),s=n.filter(e=>e.sceneId===is.sceneId);i=[...s.length?s:n.filter(e=>"voiceover"===e.type&&r(e)>.01)].sort((e,t)=>+("voiceover"!==e.type)!=+("voiceover"!==t.type)?("voiceover"!==e.type)-("voiceover"!==t.type):r(t)-r(e))[0]??null}let s=null;if(i){let e=n6(i.trackId);e.top>a&&(s=e.top+e.height)}return{captionBlock:is,anchorBlock:e,audioSource:t,trackTop:a,trackHeight:r,wordGuideExtendToY:s}},[q,n6,eU,is]),il=(0,i.useCallback)(()=>{if(!h?.scenes?.length)return;let e=function(e){let{blocks:t,scenes:a}=e,r=e.now??Date.now();if(!a.length)return null;let n=a.map(e=>e.id),i=new Map(n.map((e,t)=>[e,t])),s=t.filter(e=>!e.sceneId.startsWith("__track0")&&"scene"===e.type),o=new Map(s.map(e=>[e.sceneId,e])),l=t.filter(e=>"scene"!==e.type&&void 0!==e.type),d=t.find(e=>e.sceneId.startsWith("__track0")),c=[...s].sort((e,t)=>e.start===t.start?(i.get(e.sceneId)??0)-(i.get(t.sceneId)??0):e.start-t.start).map(e=>e.sceneId);if(c.length!==n.length)return null;let u=c.some((e,t)=>e!==n[t]),p=c.map(e=>{let t=a.find(t=>t.id===e),n=o.get(e);return{...t,timelineStart:n?.start??t.timelineStart??0,trackId:n?.trackId??t.trackId??1,updatedAt:r}}),m=new Map(a.map(e=>[e.id,e])),h=e=>{let t=m.get(e.id);return!t||t.timelineStart!==e.timelineStart||t.trackId!==e.trackId},f=p.some(h);if(!u&&!f)return null;let g=p.map(e=>{let t=o.get(e.id),a=le(e,t);return{...t,start:e.timelineStart??0,duration:a,trackId:e.trackId??1}}),x=p.reduce((e,t)=>Math.max(e,(t.timelineStart??0)+le(t,o.get(t.id))),0),b=d?{...d,duration:x,outOffset:x,fullDuration:x}:null,y=[...b?[b]:[],...g,...l],v=y.length!==t.length||y.some((e,a)=>{let r=t[a];return!r||r.id!==e.id||Math.abs(r.start-e.start)>.001||r.trackId!==e.trackId||Math.abs(r.duration-e.duration)>.001});return{sortedSceneIds:c,updatedScenes:p,allBlocks:y,blocksChanged:v,hasChangedOrder:u,hasPositionChanges:f,scenesWithPositionChanges:f?p.filter(h):[]}}({blocks:q,scenes:h.scenes});if(!e)return;let{sortedSceneIds:t,updatedScenes:a,allBlocks:r,blocksChanged:n,hasChangedOrder:i,hasPositionChanges:s,scenesWithPositionChanges:o}=e;console.log("[MasterTimeline] Gap-preserving reorder - new timeline positions:",a.map(e=>({id:e.id.slice(0,8),timelineStart:e.timelineStart?.toFixed(2),duration:(e.media?.trim?e.media.trim.end-e.media.trim.start:e.media?.duration||0).toFixed(2)}))),n&&Y(r),requestAnimationFrame(()=>{if(F&&s&&V&&H)for(let e of o){let t=H(e.id);if(t)try{V(t,e.timelineStart??0,e.trackId??1)}catch{}}if(_&&A){let e={...h,scenes:a,updatedAt:Date.now()};_(e),A(e)}else i&&(F&&K?K(t):I&&I(t))})},[q,h,I,e8,_,A,F,K,Y,V,H]),id=(0,i.useCallback)(()=>u.current?.scrollBy({left:-aj.HL,behavior:"smooth"}),[]),ic=(0,i.useCallback)(()=>u.current?.scrollBy({left:aj.HL,behavior:"smooth"}),[]),iu=(0,i.useCallback)(e=>{let t=e.currentTarget.scrollTop;p.current&&(p.current.scrollTop=t)},[]);(0,i.useEffect)(()=>{let e=u.current;if(!e)return;let t=()=>{tg(e.scrollLeft),tb(e.clientWidth),tv(e.clientHeight)};t(),e.addEventListener("scroll",t);let a=new ResizeObserver(t);return a.observe(e),()=>{e.removeEventListener("scroll",t),a.disconnect()}},[]);let{majorInterval:ip,minorDivisions:im}=(0,i.useMemo)(()=>(function(e){let t=130/e;for(let[e,a,r]of[[.25,.25,5],[.5,.5,5],[1,1,4],[2,2,4],[5,5,5],[10,10,5],[15,15,3],[30,30,6],[60,60,6],[120,120,4],[300,300,5],[600,600,5]])if(t<=e)return{majorInterval:a,minorDivisions:r};return{majorInterval:60*Math.ceil(t/60),minorDivisions:6}})(aL),[aL]),ih=ip/im,ig=(0,i.useMemo)(()=>sm(ep,aL,tx,Z?8+lQ(Z.estimatedSeconds,aL):0),[ep,aL,tx,Z]),ib=(0,i.useMemo)(()=>(function(e,t,a=200){return{startPixels:Math.max(0,e-a),endPixels:e+t+a}})(tf,tx),[tf,tx]),iy=(0,i.useMemo)(()=>{var e,t;let a;return e=ib.startPixels,a=Math.max(0,(t=ib.endPixels)-e),{startPixels:e,endPixels:t,marginPixels:Math.max(400,a)}},[ib]),iv=(0,i.useMemo)(()=>(function(e,t,a,r,n,i){if(e<=0||i<=0)return[];let s=Math.floor(Math.max(0,a/t)/i),o=Math.ceil(r/t/i),l=[];for(let e=s;e<=o;e++){let t=e*i,a=.001>Math.abs(t%n)||.001>Math.abs(t%n-n);l.push({time:t,isMajor:a})}return l})(ep,aL,ib.startPixels,ib.endPixels,ip,ih),[ep,aL,ib,ip,ih]),iw=(0,i.useMemo)(()=>Math.max(3,Math.min(8,Math.round(aL/100*8))),[aL]),ik=(0,i.useMemo)(()=>Math.max(3,Math.min(10,Math.round(5*Math.sqrt(aL/20)))),[aL]),iS=(0,i.useMemo)(()=>{let e=new Set;if(t5)if(ao&&ao.size>
970)ao.forEach(t=>{e.add(t.id),"scene"===t.type&&t.sceneId&&e.add(t.sceneId)});else{let t=q.find(e=>e.id===t5);t&&(e.add(t.id),"scene"===t.type&&t.sceneId&&e.add(t.sceneId))}return e},[t5,ao,q]),ij=(0,i.useMemo)(()=>{if(!t5||0===iS.size)return[];let e=[];return q.forEach(t=>{(iS.has(t.id)||iS.has(t.sceneId))&&(e.push(t.start),e.push(t.start+t.duration))}),e},[t5,iS,q]),{selectionBox:iI,scheduleScrub:iC,handleTimelineMouseDown:iM,handleTimelineTouchStart:i_,handleTimelineMouseMove:iA,handleTrackControlsHover:iE}=function({containerRef:e,zoomLevel:t,rulerHeight:a,setCurrentTime:r,draggingId:n,trimmingId:s,isPlaying:l,isSpliceMode:d,attemptSpliceAtTime:c,blocks:u,getTrackLayout:p,setSelectedSceneIds:m,setSelectedAudioBlockIds:h,isGridEnabled:f,isMagnetEnabled:g,gridIntervalSeconds:x}){let[b,y]=(0,i.useState)(null),v=(0,i.useRef)(null),w=(0,i.useRef)(null),k=(0,i.useRef)(!1),S=(0,i.useRef)(null),j=(0,i.useCallback)(()=>{k.current||(k.current=!0,(0,st.markScrubEvent)())},[]),I=(0,i.useCallback)(()=>{null!==S.current&&(window.clearTimeout(S.current),S.current=null),S.current=window.setTimeout(()=>{S.current=null,k.current&&(k.current=!1,(0,st.markScrubEndEvent)())},180)},[]),N=(0,i.useCallback)(()=>{null!==w.current&&(r(w.current,!0),w.current=null),v.current=null},[r]),C=(0,i.useCallback)((e,t=!1)=>{(0,o.B)(e,e=>{w.current=e,null===v.current&&((0,o.qW)()||(0,o.Cz)()?N():v.current=(0,o.EP)(N))},t),I()},[N,I]),M=(0,i.useCallback)((e,a,r,n)=>{let i=u.filter(e=>!e.sceneId.startsWith("__track0")).filter(i=>{let s=i.start*t,o=s+i.duration*t,{top:l,height:d}=p(i.trackId??1),c=l+2;return o>=e&&s<=a&&c+d-4>=r&&c<=n}),s=i.filter(e=>"scene"===e.type).map(e=>e.sceneId),o=i.filter(e=>"scene"!==e.type).map(e=>e.id);m(s),h(o)},[u,p,h,m,t]),_=(0,i.useCallback)(r=>{let i=r.target;if(i?.closest("[data-automation-keyframe-editor]"))return;if(d){let a=e.current?.getBoundingClientRect();if(!a)return;c(Math.max(0,(r.clientX-a.left+(e.current?.scrollLeft||0))/t));return}if(n||s)return;let o=e.current?.getBoundingClientRect();if(!o)return;let l=r.clientX-o.left+(e.current?.scrollLeft||0),u=r.clientY-o.top+(e.current?.scrollTop||0)-a,p=!1,b=l,v=u;y({startX:l,currentX:l,startY:u,currentY:u,active:!1});let w=r=>{let n=r.clientX-o.left+(e.current?.scrollLeft||0),i=r.clientY-o.top+(e.current?.scrollTop||0)-a;if(!p&&(Math.abs(n-l)>4||Math.abs(i-u)>4)&&(p=!0),p)b=n,v=i,y({startX:l,currentX:n,startY:u,currentY:i,active:!0});else{j();let e=Math.max(0,n/t);f&&(e=ss(e,[],{enableMagnet:!1,enableGrid:!0,isMagnetEnabled:g,isGridEnabled:f,gridIntervalSeconds:x})),C(e)}},k=a=>{let r=a.clientX-o.left+(e.current?.scrollLeft||0);if(p)M(Math.min(l,b),Math.max(l,b),Math.min(u,v),Math.max(u,v));else{m([]),h([]),j();let e=Math.max(0,r/t);f&&(e=ss(e,[],{enableMagnet:!1,enableGrid:!0,isMagnetEnabled:g,isGridEnabled:f,gridIntervalSeconds:x})),C(e)}I(),y(null),document.removeEventListener("mousemove",w),document.removeEventListener("mouseup",k)};document.addEventListener("mousemove",w),document.addEventListener("mouseup",k)},[d,e,c,t,n,s,a,f,g,x,C,u,p,m,h,M]),A=(0,i.useCallback)(t=>{if(d||n||s||1!==t.touches.length)return;let r=t.target;if(r?.closest("[data-scene-block]")||r?.closest("[data-audio-block]")||r?.closest("[data-caption-block]")||r?.closest("[data-automation-keyframe-editor]"))return;let i=e.current?.getBoundingClientRect();if(!i)return;let o=t.touches[0],l=o.clientX-i.left+(e.current?.scrollLeft||0),c=o.clientY-i.top+(e.current?.scrollTop||0)-a,u=!1,p=!1,m=l,h=c,f=null,g=()=>{null!==f&&(window.clearTimeout(f),f=null)};f=window.setTimeout(()=>{u=!0,y({startX:l,currentX:l,startY:c,currentY:c,active:!1})},220);let x=t=>{if(!t.touches.length)return;let r=t.touches[0],n=r.clientX-i.left+(e.current?.scrollLeft||0),s=r.clientY-i.top+(e.current?.scrollTop||0)-a;if(m=n,h=s,!u){(Math.abs(n-l)>8||Math.abs(s-c)>8)&&g();return}!p&&(Math.abs(n-l)>4||Math.abs(s-c)>4)&&(p=!0),p&&(t.preventDefault(),y({startX:l,currentX:n,startY:c,currentY:s,active:!0}))},b=()=>{g(),document.removeEventListener("touchmove",x),document.removeEventListener("touchend",v),document.removeEventListener("touchcancel",w),u&&p&&M(Math.min(l,m),Math.max(l,m),Math.min(c,h),Math.max(c,h)),y(null)},v=()=>{b()},w=()=>{b()};document.addEventListener("touchmove",x,{passive:!1}),document.addEventListener("touchend",v),document.addEventListener("touchcancel",w)},[d,n,s,e,a,220,8,M]),E=(0,i.useCallback)(a=>{if(n||s||l||b?.active)return;let r=e.current?.getBoundingClientRect();if(!r)return;let i=a.clientX-r.left+(e.current?.scrollLeft||0);j(),C(Math.max(0,i/t))},[n,s,l,b?.active,e,j,C,t]),T=(0,i.useCallback)(()=>{n||s||l||b?.active||C(0)},[n,s,l,b?.active,C]);return(0,i.useEffect)(()=>()=>{null!==v.current&&cancelAnimationFrame(v.current),null!==S.current&&window.clearTimeout(S.current)},[]),{selectionBox:b,scheduleScrub:C,handleTimelineMouseDown:_,handleTimelineTouchStart:A,handleTimelineMouseMove:E,handleTrackControlsHover:T}}({containerRef:u,zoomLevel:aL,rulerHeight:aj.Dm,setCurrentTime:eK,draggingId:t5,trimmingId:t3,isPlaying:em,isSpliceMode:a1,attemptSpliceAtTime:a2,blocks:q,getTrackLayout:n2,setSelectedSceneIds:eb,setSelectedAudioBlockIds:eS,isGridEnabled:eJ,isMagnetEnabled:eX,gridIntervalSeconds:aU});rh.current=iC;let{nudgePlayhead:iP,seekToTime:iD,jumpToStart:iR,jumpToEnd:iz,jumpToPrevEdit:iL,jumpToNextEdit:iF,addMarkerAtPlayhead:iO,removeMarker:iB,renameMarker:iW,setMarkerColor:iU,handleMarkerMouseDown:iK,handleMarkerDoubleClick:iV,handleMarkerContextMenu:iH,markerEditState:iq,closeMarkerEdit:iY,nudgeSelectedBlocks:iG,trimSelectedBlockToPlayhead:iX}=function({currentProject:e,blocks:t,selectedSceneIds:a,selectedSceneId:r,selectedAudioBlockIds:n,selectedAudioBlockId:s,pushAction:o,updateCoreProjectState:l,saveCurrentProject:d,updateVoiceover:c,scheduleScrub:u,isTrackLocked:p,zoomLevel:m}){let h=(0,i.useRef)(e);h.current=e;let f=(0,i.useRef)(t);f.current=t;let[g,x]=(0,i.useState)(null),b=(0,i.useCallback)(e=>{let t=y.zC.getState();
97u(Math.max(0,Math.min(t.duration,t.projectTime+e)))},[u]),v=(0,i.useCallback)(e=>{u(Math.max(0,Math.min(y.zC.getState().duration,e)))},[u]),w=(0,i.useCallback)(()=>u(0),[u]),k=(0,i.useCallback)(()=>{u(Math.max(0,y.zC.getState().duration))},[u]),S=(0,i.useCallback)(()=>{let e=y.zC.getState(),t=new Set([0]);for(let a of(e.duration>0&&t.add(e.duration),e.blocks))a.sceneId?.startsWith("__track0")||(t.add(a.start),t.add(a.start+a.duration));for(let a of e.markers)t.add(a.time);return Array.from(t).sort((e,t)=>e-t)},[]),j=(0,i.useCallback)(()=>{let e=y.zC.getState(),t=[...S()].reverse().find(t=>t<e.projectTime-.001);void 0!==t&&u(t)},[S,u]),I=(0,i.useCallback)(()=>{let e=y.zC.getState(),t=S().find(t=>t>e.projectTime+.001);void 0!==t&&u(t)},[S,u]),N=(0,i.useCallback)(()=>{let e=y.zC.getState(),t=e.markers.find(t=>.05>Math.abs(t.time-e.projectTime));t?e.removeMarker(t.id):e.addMarker({time:e.projectTime}),d?.()},[d]),C=(0,i.useCallback)(e=>{y.zC.getState().removeMarker(e),x(t=>t?.markerId===e?null:t),d?.()},[d]),M=(0,i.useCallback)((e,t)=>{y.zC.getState().updateMarker(e,{label:t.trim()||void 0}),d?.()},[d]),_=(0,i.useCallback)((e,t)=>{y.zC.getState().updateMarker(e,{color:t}),d?.()},[d]),A=(0,i.useCallback)((e,t)=>{if(0!==t.button)return;t.preventDefault();let a=t.clientX,r=e.time,n=!1,i=t=>{let i=t.clientX-a;if(!n&&3>Math.abs(i))return;n=!0;let s=Math.max(0,r+i/m);y.zC.getState().updateMarker(e.id,{time:s})},s=()=>{document.removeEventListener("mousemove",i),document.removeEventListener("mouseup",s),n?d?.():u(Math.max(0,r))};document.addEventListener("mousemove",i),document.addEventListener("mouseup",s)},[m,u,d]),E=(0,i.useCallback)((e,t)=>{x({markerId:e.id,x:t.clientX,y:t.clientY})},[]),T=(0,i.useCallback)(e=>{C(e.id)},[C]),$=(0,i.useCallback)(()=>x(null),[]),P=(0,i.useCallback)(()=>{let e=f.current,t=new Set(a.length>0?a:r?[r]:[]),i=new Set(n.length>0?n:s?[s]:[]);return e.filter(e=>!(e.sceneId?.startsWith("__track0")||p(e.trackId))&&("scene"===e.type?t.has(e.sceneId):i.has(e.id)))},[a,r,n,s,p]),D=(0,i.useCallback)((e,t)=>{let a=h.current;if(!a)return;let r=y.zC.getState(),n=new Map(e.map(e=>[e.id,e]));r.setBlocks(r.blocks.map(e=>{let t=n.get(e.id);return t?{...e,start:t.start,trackId:t.trackId}:e}));let i=new Set((a.scenes??[]).map(e=>e.id)),s=e.filter(e=>i.has(e.sceneId)),u=a.scenes??[];if(s.length>0){let e=new Map(s.map(e=>[e.sceneId,e]));u=(a.scenes??[]).map(t=>{let a=e.get(t.id);return a?{...t,timelineStart:a.start,trackId:a.trackId,updatedAt:Date.now()}:t}),l?.({...a,scenes:u,updatedAt:Date.now()})}let p=new Set(r.blocks.filter(e=>"caption"===e.type).map(e=>e.id)),m=e.filter(e=>!i.has(e.sceneId)&&!p.has(e.id));if(c)for(let e of m)c(e.id,{start:e.start,trackId:e.trackId});d?.(),o({type:"MOVE_BLOCK",previousState:{blockPositions:t,scenes:a.scenes??[]},newState:{blockPositions:e,scenes:u}})},[o,d,l,c]);return{nudgePlayhead:b,seekToTime:v,jumpToStart:w,jumpToEnd:k,jumpToPrevEdit:j,jumpToNextEdit:I,addMarkerAtPlayhead:N,removeMarker:C,renameMarker:M,setMarkerColor:_,handleMarkerMouseDown:A,handleMarkerDoubleClick:E,handleMarkerContextMenu:T,markerEditState:g,closeMarkerEdit:$,nudgeSelectedBlocks:(0,i.useCallback)(e=>{let t=P();if(0===t.length)return;let a=Math.max(e,-Math.min(...t.map(e=>e.start)));if(1e-9>Math.abs(a))return;let r=t.map(e=>({id:e.id,sceneId:e.sceneId,start:e.start,trackId:e.trackId}));D(r.map(e=>({...e,start:Math.max(0,e.start+a)})),r)},[P,D]),trimSelectedBlockToPlayhead:(0,i.useCallback)(e=>{let t=h.current,a=y.zC.getState(),r=a.projectTime,n=P().find(e=>r>e.start&&r<e.start+e.duration)??null;if(!n||!t)return;let i=n.start,s=n.duration,u=n.inOffset,p=n.outOffset;if("in"===e){let e=r-n.start;if(n.duration-e<.1)return;i=r,s=n.duration-e,u=n.inOffset+e}else{let e=r-n.start;if(e<.1)return;s=e,p=n.inOffset+e}if("caption"===n.type){let e=(0,aS.zr)(n),r=(0,aS.zr)({...n,start:i,duration:s,inOffset:0,outOffset:s,fullDuration:s,captionWords:sM(n.captionWords,n.start,i,s)});a.updateBlock(n.id,{start:r.start,duration:r.duration,inOffset:0,outOffset:r.outOffset,fullDuration:r.fullDuration,captionWords:r.captionWords}),(0,aS.hA)(e,r)||o({type:"UPDATE_CAPTION_BLOCK",previousState:{scenes:[...t.scenes??[]],captionBlock:e},newState:{scenes:[...t.scenes??[]],captionBlock:r}}),d?.();return}
97let m="scene"===n.type?(t.scenes??[]).find(e=>e.id===n.sceneId):void 0,f="scene"===n.type?(0,tO.AQ)({sceneStart:n.start,prevTrim:{start:n.inOffset,end:n.outOffset},mediaDuration:m?.media?.type==="image"?null:m?.media?.duration??null,requestedTrim:{start:u,end:p},minDuration:.1,mode:"reject"}):null;if(!f||f.applied)if(a.updateBlock(n.id,{start:i,duration:s,inOffset:u,outOffset:p}),"scene"===n.type&&f?.applied){let e=[...t.scenes??[]],a=(t.scenes??[]).map(e=>e.id!==n.sceneId?e:{...e,timelineStart:f.timelineStart,media:e.media?{...e.media,trim:{start:f.trim.start,end:f.trim.end}}:e.media,updatedAt:Date.now()}),r=y.zC.getState(),i=r.blocks.filter(e=>"caption"===e.type).map(aS.zr),s=tJ(r.blocks,n.sceneId,f.captionWindow.start,f.captionWindow.end);s.changed&&r.setBlocks(s.blocks);let c=s.changed?s.blocks.filter(e=>"caption"===e.type).map(aS.zr):i;o({type:"TRIM_SCENE",previousState:{scenes:e,affectedSceneId:n.sceneId,...s.changed&&{captionBlocks:i}},newState:{scenes:a,affectedSceneId:n.sceneId,...s.changed&&{captionBlocks:c}}}),l?.({...t,scenes:a,updatedAt:Date.now()}),d?.()}else("voiceover"===n.type||"audio"===n.type)&&c?.(n.id,{start:i,duration:s,inOffset:u,outOffset:p}),d?.()},[P,o,d,l,c])}}({currentProject:h,blocks:q,selectedSceneIds:ex,selectedSceneId:eg,selectedAudioBlockIds:ew,selectedAudioBlockId:ev,pushAction:e8,updateCoreProjectState:_,saveCurrentProject:A,updateVoiceover:P,scheduleScrub:iC,isTrackLocked:eT,zoomLevel:aL}),iJ=(0,i.useCallback)(()=>{ex.length>0||eg?rd():r7()},[ex,eg,rd,r7]),iZ=(0,i.useCallback)(()=>{let e=ex[0]||eg;e&&nE(e)},[ex,eg,nE]);!function({selectedSceneId:e,selectedSceneIds:t,selectedAudioBlockId:a,selectedAudioBlockIds:r,selectedEffect:n,blocks:s,loopRegion:o,isSpliceMode:l,onDelete:d,onDeleteEffect:c,onDeleteAudioBlock:u,onUndo:p,onRedo:m,onClearSelection:h,onDisableSpliceMode:f,onToggleSpliceMode:g,onClearLoopRegion:x,onSetLoopRegion:b,onRippleDelete:y,onDuplicate:v,onAddMarker:w,onNudgePlayhead:k,onJumpToStart:S,onJumpToEnd:j,onNudgeSelectedBlocks:I,onTrimToPlayhead:N,onJumpToPrevEdit:C,onJumpToNextEdit:M,onZoomToSelection:_,onZoomToFit:A}){(0,i.useEffect)(()=>{let i=i=>{let E=i.target;if("INPUT"===E.tagName||"TEXTAREA"===E.tagName||E.isContentEditable)return;let T=t.length>0||!!e||r.length>0||!!a;if(i.shiftKey&&("Backspace"===i.key||"Delete"===i.key)&&T&&y){i.preventDefault(),y();return}if("Backspace"===i.key||"Delete"===i.key){if(n&&c){i.preventDefault(),c();return}if(t.length>0||e){i.preventDefault(),d();return}if(r.length>0||a){i.preventDefault(),u();return}}let $=i.key.toLowerCase();if((i.ctrlKey||i.metaKey)&&"z"===$&&!i.shiftKey){i.preventDefault(),p();return}if((i.ctrlKey||i.metaKey)&&("z"===$&&i.shiftKey||"y"===$)){i.preventDefault(),m();return}if((i.ctrlKey||i.metaKey)&&("d"===i.key||"D"===i.key)){T&&v&&(i.preventDefault(),v());return}if(!i.ctrlKey&&!i.metaKey&&!i.altKey){if("ArrowLeft"===i.key||"ArrowRight"===i.key){if(k){i.preventDefault();let e=i.shiftKey?1:sy;k("ArrowLeft"===i.key?-e:e)}return}if("ArrowUp"===i.key||"ArrowDown"===i.key){let e="ArrowUp"===i.key?C:M;e&&(i.preventDefault(),e());return}if("Home"===i.key){S&&(i.preventDefault(),S());return}if("End"===i.key){j&&(i.preventDefault(),j());return}if(","===i.key||"<"===i.key||"."===i.key||">"===i.key){if(T&&I){i.preventDefault();let e=i.shiftKey?1:sy;I(","===i.key||"<"===i.key?-e:e)}return}if("["===i.key||"]"===i.key){T&&N&&(i.preventDefault(),N("["===i.key?"in":"out"));return}if("m"===i.key||"M"===i.key){w&&!i.shiftKey&&(i.preventDefault(),w());return}if("Escape"===i.key){if(i.preventDefault(),l)return void f();if(o)return void x();if(r.length>0||a||t.length>0||e)return void h()}if("l"===i.key||"L"===i.key){if(i.preventDefault(),o)return void x();let a=t.length>0?t:e?[e]:[];if(0===a.length)return;let r=s.filter(e=>a.includes(e.sceneId));if(0===r.length)return;return void b({start:Math.min(...r.map(e=>e.start)),end:Math.max(...r.map(e=>e.start+e.duration))})}if("c"===i.key||"C"===i.key){i.preventDefault(),g();return}if(("z"===i.key||"Z"===i.key)&&!i.ctrlKey&&!i.metaKey&&!i.altKey){if(i.shiftKey){A&&(i.preventDefault(),A());return}T&&_?(i.preventDefault(),_()):A&&(i.preventDefault(),A());return}}};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[e,t,a,r,n,s,o,l,d,c,u,p,m,h,f,g,x,b,y,v,w,k,S,j,I,N,C,M,_,A])}({selectedSceneId:eg,selectedSceneIds:ex,selectedAudioBlockId:ev,selectedAudioBlockIds:ew,selectedEffect:ru,blocks:q,loopRegion:eC,isSpliceMode:a1,onDelete:ro,onDeleteEffect:rg,onDeleteAudioBlock:r7,onUndo:r6,onRedo:r9,onClearSelection:ne,onDisableSpliceMode:a4,onToggleSpliceMode:a5,onClearLoopRegion:e_,onSetLoopRegion:eM,onRippleDelete:iJ,onDuplicate:iZ,onAddMarker:iO,onNudgePlayhead:iP,onJumpToStart:iR,onJumpToEnd:iz,onNudgeSelectedBlocks:iG,onTrimToPlayhead:iX,onJumpToPrevEdit:iL,onJumpToNextEdit:iF,onZoomToSelection:na,onZoomToFit:nr});let iQ=(0,i.useRef)([]);(0,i.useEffect)(()=>{iQ.current=function(e,t,a){if(!t||!(a>0))return[];let r=[];for(let n of e){if("audio"!==n.type)continue;let e=sx(t,n);if(!e?.rhythm?.beatTimes?.length)continue;let i=sb(e.rhythm.beatTimes,n);i.length>=2&&(i[i.length-1]-i[0])/(i.length-1)*a<12||r.push(...i)}return r}(q,h?.aiAnalysis?.audioArtifacts,aL)},[q,h?.aiAnalysis?.audioArtifacts,aL]);let{computeDragDelta:i0}=function({zoomLevel:e,isMagnetEnabled:t,isGridEnabled:a,gridIntervalSeconds:r,dragSnapLockRef:n,getExtraSnapPoints:s}){return{computeDragDelta:(0,i.useCallback)(({deltaSeconds:i,blocks:o,draggingId:l,activeSelection:d,targetTrack:c,activeInitialBlocks:u})=>{let p=i;if(t||a){let c=y.zC.getState(),m=function(e,t,a=[],r=[]){let n=new Set([0]);
97for(let i of(e.forEach(e=>{e.id===t||a.includes(e.sceneId)||a.includes(e.id)||(n.add(e.start),n.add(e.start+e.duration))}),r))Number.isFinite(i)&&i>=0&&n.add(i);return Array.from(n)}(o,l,d,[c.projectTime,...c.markers.map(e=>e.time),...s?.()??[]]),h=Array.from(u.values()),f=Math.min(...h.map(e=>e.start)),g=Math.max(...h.map(e=>e.start+e.duration)),x=f+i,b=g+i,v=aj.yA/Math.max(e,1),w=v*aj.D3,k=n.current,S=!1;if(k){let e="magnet"===k.source&&t||"grid"===k.source&&a,r=Math.abs(i-k.snappedDelta);e&&r<=w?(p=k.snappedDelta,S=!0):n.current=null}if(!S){let e=!1;if(t&&m.length){let t=1/0,a=i,r="start",s=x;for(let e of m){let n=Math.abs(x-e);n<t&&(t=n,a=e-f,r="start",s=e);let i=Math.abs(b-e);i<t&&(t=i,a=e-g,r="end",s=e)}t<=v&&(p=a,e=!0,n.current={snappedDelta:a,snappedTo:s,source:"magnet",alignment:r})}if(!e&&a){let t=Math.round(x/r)*r,a=t-f;p=a,e=!0,n.current={snappedDelta:a,snappedTo:t,source:"grid",alignment:"grid"}}e||(n.current=null)}}else n.current=null;let m=Math.min(...Array.from(u.values()).map(e=>e.start));return m+p<0&&(p=-m),p},[e,t,a,r,n,s])}}({zoomLevel:aL,isMagnetEnabled:eX,isGridEnabled:eJ,gridIntervalSeconds:aU,dragSnapLockRef:tc,getExtraSnapPoints:(0,i.useCallback)(()=>iQ.current,[])}),{computeTrimPreview:i1}=function({zoomLevel:e,isMagnetEnabled:t,isGridEnabled:a,gridIntervalSeconds:r}){return{computeTrimPreview:(0,i.useCallback)(({initialBlockState:e,side:t,deltaSeconds:a,blocks:r})=>{let n="scene"===e.type&&e.scene,i="caption"===e.type,s=n&&e.scene?.media?.type==="image",o=i||s?1/0:n?e.scene?.media?.duration||e.fullDuration||e.duration:e.fullDuration||e.duration;if("start"===t){let t=e.start+a;t=Math.min(t,e.start+e.duration-aj.o6),s||i||(t=Math.max(t,e.start-e.inOffset));let r=(t=Math.max(t,0))-e.start,n=e.duration-r,o=i?sM(e.captionWords,e.start,t,n):void 0;return{previewUpdate:{start:t,duration:n,inOffset:s||i?0:e.inOffset+r,outOffset:i?n:e.outOffset,captionWords:o},scrubTarget:t}}let l=e.start+e.duration+a-e.start;l=Math.max(aj.o6,l),s||i||(l=Math.min(l,o-e.inOffset));let d=i?sM(e.captionWords,e.start,e.start,l):void 0;return{previewUpdate:{start:e.start,duration:l,inOffset:e.inOffset,outOffset:s||i?l:e.inOffset+l,captionWords:d},scrubTarget:Math.max(0,e.start+l-1/30)}},[])}}({zoomLevel:aL,isMagnetEnabled:eX,isGridEnabled:eJ,gridIntervalSeconds:aU}),{attachPointerLifecycle:i5}={attachPointerLifecycle:(0,i.useCallback)((e,t)=>{let a=null,r=null,n=(e,t,a)=>({clientX:e,clientY:t,altKey:a?.altKey??!1,ctrlKey:a?.ctrlKey??!1,metaKey:a?.metaKey??!1,shiftKey:a?.shiftKey??!1}),i=()=>
97{if(!r)return;let t=r;r=null,e(t)},s=e=>{r=n(e.clientX,e.clientY,e),null===a&&(a=window.requestAnimationFrame(()=>{a=null,i()}))},o=e=>{s(e)},l=e=>{null!==a&&(window.cancelAnimationFrame(a),a=null),i(),t(e)},d=e=>{if(!e.touches.length)return;let t=e.touches[0];s(n(t.clientX,t.clientY)),e.preventDefault()},c=e=>{let t=e.changedTouches[0];t&&l(n(t.clientX,t.clientY))};return document.addEventListener("mousemove",o),document.addEventListener("mouseup",l),document.addEventListener("touchmove",d,{passive:!1}),document.addEventListener("touchend",c),document.addEventListener("touchcancel",c),()=>{null!==a&&(window.cancelAnimationFrame(a),a=null),r=null,document.removeEventListener("mousemove",o),document.removeEventListener("mouseup",l),document.removeEventListener("touchmove",d),document.removeEventListener("touchend",c),document.removeEventListener("touchcancel",c)}},[])},{commitDragAndTrim:i2}=function({blocks:e,draggingId:t,trimmingId:a,initialBlockState:r,initialSelectionBlocks:n,localTrimPreview:s,dragShadowPreview:o,currentProject:l,compositionEditsReady:d,trimScene:c,updateSceneMedia:u,updateVoiceover:p,duplicateScene:m,reorderScenesFromBlocks:h,scheduleScrub:f,pushAction:g,updateBlock:x,setDragShadowPreview:b,setFlushPulseEdges:v,updateCoreProjectState:w,saveCurrentProject:k,dragStartBlockPositionsRef:S,prevFrameFlushEdgesRef:j,flushPulseTimeoutRef:I,lastTrimPreviewRef:N,preTrimScenesRef:C}){return{commitDragAndTrim:(0,i.useCallback)(i=>{if(i.altKey&&t&&r?.type==="scene"&&m){let a=r.sceneId;if(a&&!a.startsWith("__track0")){let i=e.find(e=>e.id===t),s=i?.start??r.start,o=i?.trackId??r.trackId??1;console.log("[MasterTimeline] Option+drag: Duplicating scene:",a,"Original pos:",r.start,"track:",r.trackId,"Dragged pos:",s,"track:",o),x(t,{start:r.start,trackId:r.trackId||1}),n&&n.forEach(e=>{e.id===t||e.sceneId?.startsWith("__track0")||x(e.id,{start:e.start,trackId:e.trackId||1})});let d=l?.scenes?[...l.scenes]:[];Promise.resolve(m(a,void 0,void 0,{timelineStart:s,trackId:o})).then(e=>{e&&d.length>0&&g(sE({scenes:d,originalSceneId:a,newScene:e}))}),b(null);return}}if(a&&s&&x(s.id,{start:s.start,duration:s.duration,inOffset:s.inOffset,outOffset:s.outOffset}),a&&r){let t=s?{...e.find(e=>e.id===a.id),...s}:e.find(e=>e.id===a.id);if(t){if("scene"===t.type&&N.current.delete(t.sceneId),"scene"===t.type&&l?.scenes&&!t.sceneId.startsWith("__track0")){let e="start"===a.side;e&&f(t.start,!0);let n=C.current??[...l.scenes],i=n.find(e=>e.id===t.sceneId),s=l.scenes.find(e=>e.id===t.sceneId);if(s){let o=i?.media?.trim||{start:0,end:i?.media?.duration||s.media?.duration||10},p=(0,tO.AQ)({sceneStart:r.start,prevTrim:o,mediaDuration:(i??s)?.media?.type==="image"?null:(i??s)?.media?.duration??null,requestedTrim:{start:t.inOffset,end:t.inOffset+t.duration},mode:"clamp"});if(!p.applied)return void console.warn("[MasterTimeline] Trim commit rejected by edit kernel:",p.reason);let m=e&&p.startShifted,h=p.trim;(0,ey.trackEvent)("timeline_scene_trimmed",{projectId:l?.id,side:a.side,trimmedDurationSec:Math.round((h.end-h.start)*100)/100});let f=l.scenes.map(e=>e.id===t.sceneId?{...e,media:{...e.media,trim:h},...m&&{timelineStart:p.timelineStart},updatedAt:Date.now()}:e),x=y.zC.getState(),b=x.blocks.filter(e=>"caption"===e.type).map(aS.zr),v=tJ(x.blocks,t.sceneId,p.captionWindow.start,p.captionWindow.end);v.changed&&x.setBlocks(v.blocks);let S=v.changed?v.blocks.filter(e=>"caption"===e.type).map(aS.zr):b;if(g({type:"TRIM_SCENE",previousState:{scenes:n,affectedSceneId:t.sceneId,affectedSceneData:{media:{...i?.media||s.media,trim:o}},...v.changed&&{captionBlocks:b}},newState:{scenes:f,affectedSceneId:t.sceneId,affectedSceneData:{media:{...s.media,trim:h},...m&&{timelineStart:p.timelineStart}},...v.changed&&{captionBlocks:S}}}),e){let e={...l,scenes:f,updatedAt:Date.now()};w&&w(e),k&&k(e)}else d&&c?(console.log("[MasterTimeline] Using composition edit pipeline for trim"),c(t.sceneId,h.start,h.end)):(console.warn("[MasterTimeline] â ï¸ CompositionEdits not ready - using legacy updateSceneMedia. This bypasses the composition edit pipeline and should be investigated if seen frequently."),u(t.sceneId,{trim:{start:h.start,end:h.end}})),v.changed&&k?.()}}else if(("voiceover"===t.type||"audio"===t.type)&&p)p(t.id,{start:t.start,inOffset:t.inOffset,outOffset:t.outOffset}),console.log(`[MasterTimeline] Persisted audio block ${t.id} trim: in=${t.inOffset}, out=${t.outOffset}`);else if("caption"===t.type){let e=(0,aS.zr)(r),a=(0,aS.zr)({...t,fullDuration:t.duration,outOffset:t.duration});(0,aS.hA)(e,a)||(g({type:"UPDATE_CAPTION_BLOCK",previousState:{scenes:l?.scenes?[...l.sce
97nes]:[],captionBlock:e},newState:{scenes:l?.scenes?[...l.scenes]:[],captionBlock:a}}),k?.())}}}if(t){o&&o.blockId===t&&(x(t,{trackId:o.trackId}),console.log(`[MasterTimeline] Collision detected - moving block to track ${o.trackId}`));let a=S.current,r=new Map;e.forEach(e=>{r.set(e.id,{start:e.start,trackId:e.trackId||1})});let i=!1;if(a)for(let[e,t]of a){let a=r.get(e);if(a&&(Math.abs(a.start-t.start)>.01||a.trackId!==t.trackId)){i=!0;break}}if(i&&a&&l?.scenes){let t=[],r=[],n=!1,i=!1;for(let[s,o]of a){let a=e.find(e=>e.id===s);if(a){if(!(Math.abs(a.start-o.start)>.01||(a.trackId||1)!==o.trackId))continue;t.push({id:s,sceneId:"scene"===a.type?a.sceneId:a.id,start:o.start,trackId:o.trackId}),r.push({id:s,sceneId:"scene"===a.type?a.sceneId:a.id,start:a.start,trackId:a.trackId||1}),"scene"===a.type?n=!0:"caption"===a.type?i=!0:("voiceover"===a.type||"audio"===a.type)&&p&&(p(s,{start:a.start,trackId:a.trackId}),console.log(`[MasterTimeline] Persisted audio block ${s} position: ${a.start}s, track: ${a.trackId}`))}}if(0===t.length||0===r.length){S.current=null,b(null),j.current=null;return}n&&h(),i&&k?.();let s=n?[...l.scenes]:[];requestAnimationFrame(()=>{let e=n?s.map(e=>{let t=r.find(t=>t.sceneId===e.id);return t?{...e,timelineStart:t.start,trackId:t.trackId}:e}):[];g({type:"MOVE_BLOCK",previousState:{scenes:s,blockPositions:t},newState:{scenes:e,blockPositions:r}})})}S.current=null,b(null),(0,s_.Lu)({location:"useBlockDragCommit",message:"drag committed",data:{leader:t?t.slice(0,8):null}}),(0,sA.i5)("drag_commit",y.zC.getState().blocks,{projectId:l?.id??null,getBlocks:()=>y.zC.getState().blocks});let s=[...e],d=j.current;j.current=null,requestAnimationFrame(()=>{let e=new Set;if(n&&n.size>0)n.forEach(t=>{e.add(t.id),"scene"===t.type&&t.sceneId&&e.add(t.sceneId)});else if(t){let a=s.find(e=>e.id===t);a&&(e.add(a.id),"scene"===a.type&&a.sceneId&&e.add(a.sceneId))}let a=new Map,r=new Set;s.forEach(t=>{if(!(e.has(t.id)||e.has(t.sceneId)))return;let n=sp(t,s,!0,e),i=d?.get(t.id)||{left:!1,right:!1},o=n.left&&!i.left,l=n.right&&!i.right;(o||l)&&(a.set(t.id,{left:o,right:l}),r.add(t.id))}),r.size>0&&(I.current&&clearTimeout(I.current),v(a),I.current=setTimeout(()=>{v(new Map)},aj.Be))})}},[e,t,a,r,n,s,o,l,d,c,u,p,m,h,f,g,x,b,v,w,k,S,j,I,N,C])}}({blocks:q,draggingId:t5,trimmingId:t3,initialBlockState:ar,initialSelectionBlocks:ao,localTrimPreview:ai,dragShadowPreview:ag,currentProject:h,compositionEditsReady:F,trimScene:U,updateSceneMedia:m,updateVoiceover:P,duplicateScene:N,reorderScenesFromBlocks:il,scheduleScrub:iC,pushAction:e8,updateBlock:ef,setDragShadowPreview:ax,setFlushPulseEdges:aM,updateCoreProjectState:_,saveCurrentProject:A,dragStartBlockPositionsRef:ti,prevFrameFlushEdgesRef:aw,flushPulseTimeoutRef:av,lastTrimPreviewRef:tu,preTrimScenesRef:tp}),{attachDragAndTrimLifecycle:i4}=function({attachPointerLifecycle:e,commitDragAndTrim:t,finalizeInteraction:a}){let r=(0,i.useCallback)(e=>{try{t(e)}finally{requestAnimationFrame(()=>a())}},[t,a]);return{attachDragAndTrimLifecycle:(0,i.useCallback)(t=>e(t,r),[e,r])}}({attachPointerLifecycle:i5,commitDragAndTrim:i2,finalizeInteraction:(0,i.useCallback)(()=>{let e=tl.current;if(td.current&&e){let t=y.zC.getState();if(t.blocks.reduce((e,t)=>t.sceneId.startsWith("__track0")?e:Math.max(e,t.trackId||1),1)<=e.highestTrackUsed){let a=new Map(e.trackHeights),r=Array.from(t.trackHeights.keys()).map(e=>[e,a.get(e)??aj.h2]);for(let[t,a]of(r.length&&aH(r),e.automationLaneHeights.length&&aX(e.automationLaneHeights),e.effectsLaneRowHeights))aQ(t,a);nU.current=e.visibleTrackCount}}tl.current=null,td.current=!1,t2(null),t8(null),an(null),al(null),am(null),as(null),ay(!1),ad.current=!1,th(),ts.current=lt(),to.current=null,tc.current=null,nJ.current=null,af(null),tp.current=null},[th,aH,aX,aQ])}),i3=(e,t)=>{let a;if(e.stopPropagation(),eT(t.trackId||1))return void console.log("[MasterTimeline] Block drag prevented - track is locked:",t.trackId);if(a1){let a=u.current?.getBoundingClientRect();if(!a)return;a2(Math.max(0,(e.clientX-a.left+(u.current?.scrollLeft||0))/aL),t.id);return}if(e.metaKey||e.ctrlKey)return;tz();let r=function(e){let{block:t,selectedSceneIds:a,selectedAudioBlockIds:r}=e;return("scene"===t.type?a.includes(t.sceneId):r.includes(t.id))?{nextSelectedSceneIds:a,nextSelectedAudioBlockIds:r,selectionChanged:!1}:"scene"===t.type?{nextSelectedSceneIds:[t.sceneId],nextSelectedAudioBlockIds:[],selectionChanged:!0}:{nextSelectedSceneIds:[],nextSelectedAudioBlockIds:[t.id],selectionChanged:!0}}({block:t,selectedSceneIds:ex,selectedAudioBlockIds:ew});r.selectionChanged&&(eb(r.nextSelectedSceneIds),eS(r.nextSelectedAudioBlockIds));let n=function(e){let{blocks:t,selectedSceneIds:a,selectedAudioBlockIds:r}=e,n=new Map;
97return a.forEach(e=>{let a=t.find(t=>t.sceneId===e&&"scene"===t.type);a&&n.set(e,{...a})}),r.forEach(e=>{let a=t.find(t=>t.id===e&&"scene"!==t.type);a&&n.set(a.id,{...a})}),n}({blocks:q,selectedSceneIds:r.nextSelectedSceneIds,selectedAudioBlockIds:r.nextSelectedAudioBlockIds});al(n),tn.current=nz,ts.current=lt(),to.current=sl(nz+1),tc.current=null;{let e=y.zC.getState();tl.current={totalContentHeight:nq,visibleTrackCount:nF,highestTrackUsed:nz,trackHeights:Array.from(e.trackHeights.entries()),automationLaneHeights:Array.from(e.automationLaneHeights.entries()),effectsLaneRowHeights:Array.from(e.effectsLaneRowHeights.entries())},td.current=!1}nJ.current=nZ.current,t2(t.id),ae(e.clientX),aa(e.clientY),am(t.trackId||1),an({...t}),a=new Map,n.forEach(e=>{e.sceneId.startsWith("__track0")||a.set(e.id,{start:e.start,trackId:e.trackId||1})}),ti.current=a;let i=new Map;q.forEach(e=>{let t=sp(e,q,!0);i.set(e.id,t)}),aw.current=i},i8=(e,t,a)=>{(e.stopPropagation(),e.preventDefault(),tz(),eT(t.trackId||1))?console.log("[MasterTimeline] Block trim prevented - track is locked:",t.trackId):(t8({id:t.id,side:a}),au.current=!1,ae(e.clientX),an({...t}),"scene"===t.type&&h?.scenes&&(tp.current=h.scenes.map(e=>({...e,media:{...e.media}}))),"scene"!==t.type?(eb([]),eS([t.id])):t.sceneId.startsWith("__track0")||tm())},i6=e=>{let t=e.touches[0]??e.changedTouches[0];return{clientX:t?.clientX??0,clientY:t?.clientY??0,altKey:!1,ctrlKey:!1,metaKey:!1,shiftKey:!1,stopPropagation:()=>e.stopPropagation(),preventDefault:()=>e.preventDefault(),currentTarget:e.currentTarget,target:e.target}};(0,i.useEffect)(()=>()=>{ni()},[ni]),(0,i.useEffect)(()=>{if(t5||t3)return i4(e=>{let t=e.clientX-t7,a=e.clientY-at,r=t/aL;if(t5&&ar){(Math.abs(t)>4||Math.abs(a)>4)&&(ad.current=!0),ay(e.altKey&&"scene"===ar.type);let n="scene"!==ar.type,i=ar.trackId||1,s="caption"===ar.type&&t6===ar.id?i:ii(e.clientY),o=s?sl(s):sl(i),l=o-i,d=to.current??aj.Sj;o>tn.current&&(tn.current=o),tn.current>d&&(tn.current=d),am(o);let c=ao&&ao.size>0?Array.from(ao.keys()):n?[ar.id]:ex.length?ex:[ar.sceneId],u=ao&&ao.size>0?ao:new Map(n?[[ar.id,ar]]:[[ar.sceneId,ar]]),p=n?u.get(ar.id)||ar:u.get(ar.sceneId)||ar,m=Array.from(u.values()),h=m.length>1,f=function(e,t,a,r=aj.Sj){if(0===e.length)return 0;let n=e.some(e=>e.isCaption),i=e.some(e=>!e.isCaption);if(n&&i)return 0;let s=Math.round(t);for(let t of e){let e=t.trackId||1;s=Math.max(1-e,Math.min(s,r-e))}return e.every(e=>a((e.trackId||1)+s)===e.isCaption)?s:0}(m.map(e=>({trackId:e.trackId||1,isCaption:"caption"===e.type})),l,eP),g=i0({deltaSeconds:r,blocks:q,draggingId:t5,activeSelection:c,targetTrack:o,activeInitialBlocks:u}),x=tc.current;af(x?.source==="magnet"?x.snappedTo:null);let b="stay"===e0&&!h&&"caption"!==ar.type;if(b){let e=sl((p.trackId||1)+f),t=function(e,t,a,r,n=[]){let i=Math.max(0,t.duration),s=e.filter(e=>!(e.id===t.id||e.sceneId?.startsWith("__track0")||n.includes(e.id)||n.includes(e.sceneId))&&(e.trackId||1)===r&&("voiceover"===t.type||"audio"===t.type)==("voiceover"===e.type||"audio"===e.type)&&"caption"!==e.type&&"caption"!==t.type).map(e=>({start:e.start,end:e.start+e.duration})).sort((e,t)=>e.start-t.start),o=e=>s.some(t=>e<t.end-.001&&e+i>t.start+.001),l=Math.max(0,t.start+a);if(!o(l))return Math.max(-t.start,a);let d=[];for(let e of s){let t=e.start-i;t>=0&&!o(t)&&d.push(t),o(e.end)||d.push(e.end)}if(0===d.length)return null;let c=d[0],u=Math.abs(d[0]-l);for(let e of d){let t=Math.abs(e-l);t<u&&(c=e,u=t)}return c-t.start}(q,p,g,e,c);null===t?(g=0,f=0):g=t}if(n||h||b)ax(null);else{let e=Math.max(0,p.start+g),t=e+p.duration,a=a=>q.some(r=>{if(r.id===p.id||r.sceneId.startsWith("__track0")||"scene"!==r.type||c.includes(r.sceneId)||r.trackId!==a)return!1;let n=r.start;return e<r.start+r.duration-.01&&t>n+.01}),r=o;if(a(o)){let e=sl(o+1);if(e===o||a(e)){let e=sl(o-1);e===o||0===e||a(e)||(r=e)}else r=e}r!==o?ax({blockId:p.id,start:e,duration:p.duration,trackId:r}):ax(null)}if(c.forEach(e=>{let t=u.get(e);if(!t)return;let a=sl((t.trackId||1)+f);a<1&&!t.sceneId?.startsWith("__track0")&&(a=1),ef(t.id,{start:Math.max(0,t.start+g),trackId:a})}),aw.current){let e=new Map(aw.current);q.forEach(t=>{let a=sp(t,q,!0),r=e.get(t.id)||{left:!1,right:!1};
97r.left&&!a.left&&e.set(t.id,{...r,left:!1}),r.right&&!a.right&&e.set(t.id,{...r,right:!1})}),aw.current=e}}else if(t3&&ar){let e="scene"===ar.type&&ar.scene,{previewUpdate:t,scrubTarget:a}=i1({initialBlockState:ar,side:t3.side,deltaSeconds:r,blocks:q});if(as({id:t3.id,...t}),ef(t3.id,t),!au.current&&e){let e=ar.scene?.media?.type==="video",a="end"===t3.side?r>.2:r<-.2,n=.01>Math.abs(t.duration-ar.duration);e&&a&&n&&(au.current=!0,nI.toast.info("This clip is at its full length - a video can't be stretched past its source footage. You can shorten it, or slow it down / regenerate it to make it longer.",{id:"trim-source-cap-hint",duration:5e3}))}if(e&&(iC(a),h?.scenes&&_)){let e=ar.sceneId,a=t.inOffset,r=t.inOffset+t.duration,n=t.start,i=tu.current.get(e),s=1/60;if(!i||Math.abs(i.inOffset-a)>s||Math.abs(i.outOffset-r)>s||Math.abs(i.start-n)>s){tu.current.set(e,{inOffset:a,outOffset:r,start:n});let t=h.scenes.map(t=>t.id===e?{...t,media:{...t.media,trim:{start:a,end:r}},timelineStart:n,updatedAt:Date.now()}:t);_({...h,scenes:t,updatedAt:Date.now()})}}}})},[t5,t3,t7,at,ar,ef,q,aL,ex,ao,iC,i0,i1,h,t6,_,ii,i4,e0]),(0,i.useEffect)(()=>()=>{av.current&&clearTimeout(av.current)},[]);let i9=(0,i.useCallback)((e,t)=>
97{t.preventDefault(),t.stopPropagation(),eb([]),eS([e.id]),ry("captions"),rC(e.sceneId,"captions"),t9(t=>t===e.id?null:e.id)},[ry,eS,eb,rC]),i7=(0,i.useCallback)(e=>{ef(e.id,{start:e.start,duration:e.duration,inOffset:e.inOffset,outOffset:e.outOffset,fullDuration:e.fullDuration,captionWords:e.captionWords?e.captionWords.map(e=>({...e})):e.captionWords,captionCues:e.captionCues?e.captionCues.map(e=>({...e})):e.captionCues})},[ef]),sn=(0,i.useCallback)((e,t)=>{let a=(0,aS.zr)(e),r=(0,aS.zr)(t);(0,aS.hA)(a,r)||(e8({type:"UPDATE_CAPTION_BLOCK",previousState:{scenes:h?.scenes?[...h.scenes]:[],captionBlock:a},newState:{scenes:h?.scenes?[...h.scenes]:[],captionBlock:r}}),A?.())},[h?.scenes,e8,A]),{handleLoopEdgeMouseDown:si,handleRulerMouseDown:so,loopDragState:su}=function({loopRegion:e,setLoopRegion:t,clearLoopRegion:a,containerRef:r,zoomLevel:n,scheduleScrub:s}){let[o,l]=(0,i.useState)(null),[d,c]=(0,i.useState)(null);return{handleLoopEdgeMouseDown:(0,i.useCallback)((a,i)=>{if(a.stopPropagation(),a.preventDefault(),!e)return;let s=r.current?.getBoundingClientRect();if(!s)return;let o={...e};c({edge:i,originalRegion:o});let l=e=>{let a=Math.max(0,(e.clientX-s.left+(r.current?.scrollLeft||0))/n);"start"===i?t({start:Math.max(0,Math.min(a,o.end-.5)),end:o.end}):t({start:o.start,end:Math.max(a,o.start+.5)})},d=()=>{c(null),document.removeEventListener("mousemove",l),document.removeEventListener("mouseup",d)};document.addEventListener("mousemove",l),document.addEventListener("mouseup",d)},[e,r,n,t]),handleRulerMouseDown:(0,i.useCallback)(e=>{e.stopPropagation();let i=r.current?.getBoundingClientRect();if(!i)return;let o=Math.max(0,(e.clientX-i.left+(r.current?.scrollLeft||0))/n),d=!1,c=o;l({startTime:o,currentTime:o,active:!1});let u=e=>{let t=e.clientX-i.left+(r.current?.scrollLeft||0),s=Math.max(0,t/n);!d&&Math.abs(t-o*n)>4&&(d=!0,a()),d&&(c=s,l({startTime:o,currentTime:s,active:!0}))},p=()=>{if(d){let e=Math.min(o,c),a=Math.max(o,c);a-e>=.5&&t({start:e,end:a})}else s(o);l(null),document.removeEventListener("mousemove",u),document.removeEventListener("mouseup",p)};document.addEventListener("mousemove",u),document.addEventListener("mouseup",p)},[r,n,a,t,s]),loopDragState:o,loopResizeState:d}}({loopRegion:eC,setLoopRegion:eM,clearLoopRegion:e_,containerRef:u,zoomLevel:aL,scheduleScrub:iC}),{externalDragPreview:sh,handleExternalDragOver:sf,handleExternalDragLeave:sk,handleExternalDrop:sP}=function({containerRef:e,zoomLevel:t,currentProject:a,getTrackIdFromClientY:r,duplicateScene:n,updateCoreProjectState:s,saveCurrentProject:o,pushAction:l,addCaptionBlock:d,onCaptionBlockDropped:c}){let[u,p]=(0,i.useState)(null),m=(0,i.useCallback)(a=>{let r=e.current?.getBoundingClientRect();if(!r)return 0;let n=e.current?.scrollLeft||0;return Math.max(0,(a-r.left+n)/t)},[e,t]),h=(0,i.useCallback)(e=>sl(r(e)??1),[r]),f=(0,i.useCallback)(e=>{let t=(0,$.Ag)();if(!e.dataTransfer.types.includes("application/json")&&!t)return;e.preventDefault(),e.dataTransfer.dropEffect="copy";let a=m(e.clientX),r=h(e.clientY),n=r,i=5,s="scene",o=sC(e.dataTransfer.getData("application/json"))??t;if(o){if("caption-template"===o.type&&o.caption){let e=o.caption;n=sl(Math.max(2,r)),i=Math.max(.25,Number(e.duration)||3),s="caption"}else if("mediabin-audio"===o.type&&o.audio){n=sl(Math.max(2,r));let e=Number(o.duration);i=Number.isFinite(e)&&e>0?Math.max(.25,e):sd(o.audio),s="audio"}else if("mediabin-scene"===o.type&&o.scene){n=sl(Math.max(1,r));let e=Number(o.duration);i=Number.isFinite(e)&&e>0?Math.max(1,e):eh(o.scene),s="scene"}else if("mediabin-scenes"===o.type&&Array.isArray(o.scenes)){n=sl(Math.max(1,r));let e=Number(o.duration);i=Number.isFinite(e)&&e>0?Math.max(1,e):o.scenes.reduce((e,t)=>e+eh(t),0),s="scene"}else if("faceless-scene-bundle"===o.type&&o.scene){n=sl(Math.max(1,r));let e=Number(o.duration);i=Number.isFinite(e)&&e>0?Math.max(1,e):eh(o.scene),s="scene"}}p({sceneId:"preview",start:a,duration:i,trackId:n,kind:s})},[m,h]);return{externalDragPreview:u,handleExternalDragOver:f,handleExternalDragLeave:(0,i.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||p(null)},[]),handleExternalDrop:(0,i.useCallback)(async e=>{e.preventDefault(),p(null);let t=sC(e.dataTransfer.getData("application/json"))??(0,$.Ag)();if(!t)return void(0,$.Xr)();e.stopPropagation();try{let r=m(e.clientX),i=h(e.clientY);if("caption-template"===t.type&&t.caption){let e=t.caption;if(!d)return void console.warn("[MasterTimeline] Cannot drop caption - addCaptionBlock is unavailable");let n=Math.max(.25,Number(e.duration)||3),s=`caption-${(0,v.generateId)()}`,u=e.sourceCaptionId||e.id,p={id:s,sceneId:e.sceneId||"__manual__",start:r,duration:n,inOffset:0,outOffset:0,fullDuration:n,trackId:sl(Math.max(2,i)),captionText:e.captionText,captionBox:e.captionBox,captionStyle:e.captionStyle,captionWords:e.captionWords,captionDisplayMode:e.captionDisplayMode,captionDisplayWindowSize:e.captionDisplayWindowSize,alignmentProvider:e.alignmentProvider,source:e.source||"auto",sourceCaptionId:u};d(p),l?.({type:"ADD_CAPTION_BLOCK",previousState:{scenes:[...a?.scenes||[]],captionBlock:p},newState:{scenes:[...a?.scenes||[]],captionBlock:p}}),await o?.(),c?.(s);return}if("faceless-scene-bundle"===t.type&&t.scene){let e=t.scene;if(a&&s&&o){let n=sc(y.zC.getState().blocks,"scene",r,eh(e),sl(Math.max(1,i))),d=a.scenes?.some(t=>t.id===e.id),c=d?(0,v.generateId)():e.id,u=e.timelineStart??0,p=e.trackId??1,m=Date.now(),h={...JSON.parse(JSON.stringify(e)),id:c,timelineStart:r,trackId:n,createdAt:d?m:e.createdAt??m,updatedAt:m},f=(e,t)=>sl(n+((e??p+t)-p)),g=Array.isArray(t.audio)?t.audio:[],x=Array.isArray(t.captions)?t.captions:[],b=g.map(e=>({...JSON.parse(JSON.stringify(e)),id:d?`audio-${(0,v.generateId)()}
97`:e.id,sourceSceneId:c,start:r+((e.start??u)-u),trackId:f(e.trackId,1),updatedAt:m})),w=x.map(e=>({...JSON.parse(JSON.stringify(e)),id:d?`caption-${(0,v.generateId)()}`:e.id,sceneId:c,start:r+((e.start??u)-u),trackId:f(e.trackId,2)})),k=[...a.scenes||[],h],S=[...a.audio||[],...b],j=[...a.captionBlocks||[],...w],I=(a.facelessStoryboard?.detachedPlanSceneIds??[]).filter(e=>e!==t.planSceneId),{[t.planSceneId]:N,...C}=a.facelessStoryboard?.detachedSceneBundles??{},M={...a,scenes:k,audio:S,captionBlocks:j,facelessStoryboard:{...a.facelessStoryboard??{},detachedPlanSceneIds:I,detachedSceneBundles:C},updatedAt:m};(0,eI.s8)([e.id,c]),l?.({type:"ADD_SCENE",previousState:{scenes:[...a.scenes||[]],audio:[...a.audio||[]],captionBlocks:[...a.captionBlocks||[]],affectedSceneId:c},newState:{scenes:k,audio:S,captionBlocks:j,affectedSceneId:c}}),s(M),await o(M),window.dispatchEvent(new CustomEvent("faceless:scene-bundle-dropped",{detail:{planSceneId:t.planSceneId,nleSceneId:c,hasAudio:b.some(e=>e?.isLoading!==!0)}}))}else console.warn("[MasterTimeline] Cannot drop Faceless scene bundle - no project or required functions available");return}if("mediabin-scenes"===t.type&&Array.isArray(t.scenes)&&t.scenes.length>0){if(a&&s&&o){let e=Date.now(),n=t.scenes.reduce((e,t)=>e+eh(t),0),d=sc(y.zC.getState().blocks,"scene",r,n,sl(Math.max(1,i))),c=r,u=t.scenes.map(t=>{let a={...JSON.parse(JSON.stringify(t)),id:(0,v.generateId)(),createdAt:e,updatedAt:e,timelineStart:c,trackId:d};return c+=eh(t),a}),p=[...a.scenes||[],...u],m={...a,scenes:p,updatedAt:e};l?.({type:"ADD_SCENE",previousState:{scenes:[...a.scenes||[]],affectedSceneId:u[0].id},newState:{scenes:p,affectedSceneId:u[0].id}}),s(m),await o(m)}else console.warn("[MasterTimeline] Cannot drop scenes - no project or required functions available");return}if("mediabin-scene"===t.type&&t.scene){let e=t.scene,d=sc(y.zC.getState().blocks,"scene",r,eh(e),sl(Math.max(1,i)));if(a?.scenes?.some(t=>t.id===e.id)&&n){let t=await n(e.id,void 0,void 0,{timelineStart:r,trackId:d});if(t){let r=a.scenes.findIndex(t=>t.id===e.id),n=[...a.scenes];n.splice(r+1,0,t);let i=n.map((e,t)=>({...e,sequenceIndex:t}));l?.({type:"ADD_SCENE",previousState:{scenes:[...a.scenes],affectedSceneId:t.id},newState:{scenes:i,affectedSceneId:t.id}})}return}if(a&&s&&o){let t={...JSON.parse(JSON.stringify(e)),id:(0,v.generateId)(),createdAt:Date.now(),updatedAt:Date.now(),timelineStart:r,trackId:d},n=[...a.scenes||[],t],i={...a,scenes:n,updatedAt:Date.now()};l?.({type:"ADD_SCENE",previousState:{scenes:[...a.scenes||[]],affectedSceneId:t.id},newState:{scenes:n,affectedSceneId:t.id}}),s(i),await o(i);return}console.warn("[MasterTimeline] Cannot drop scene - no project or required functions available");return}if("mediabin-audio"===t.type&&t.audio){let e=t.audio;if(a&&s&&o){let t={...JSON.parse(JSON.stringify(e)),id:`audio-${(0,v.generateId)()}`,start:r,trackId:sc(y.zC.getState().blocks,"audio",r,sd(e),sl(Math.max(2,i))),status:e.status||"ready",createdAt:Date.now(),updatedAt:Date.now()},n=[...a.audio||a.voiceovers||[],t],d={...a,audio:n,voiceovers:n,updatedAt:Date.now()};l?.({type:"ADD_AUDIO_BLOCK",previousState:{scenes:[...a.scenes||[]],audioBlock:t},newState:{scenes:[...a.scenes||[]],audioBlock:t}}),s(d),await o(d)}else console.warn("[MasterTimeline] Cannot drop audio - no project or required functions available")}}catch(e){console.error("[MasterTimeline] Failed to process MediaBin drop:",e)}finally{(0,$.Xr)()}},[d,a,n,m,h,c,l,o,s])}}({containerRef:u,zoomLevel:aL,currentProject:h,getTrackIdFromClientY:ii,duplicateScene:N,updateCoreProjectState:_,saveCurrentProject:A,pushAction:e8,addCaptionBlock:el,onCaptionBlockDropped:rE}),sW=(0,i.useCallback)(e=>{if(!e.dataTransfer.types.includes("application/x-transition-type"))return!1;e.preventDefault(),e.dataTransfer.dropEffect="copy";let t=u.current;if(!t||0===az.length)return aP(null),!0;let a=t.getBoundingClientRect(),r=s8(az,e.clientX-a.left+t.scrollLeft,aL,200);return aP(r?r.key:null),!0},[u,az,aL]),sU=(0,i.useCallback)(e=>{u.current?.contains(e.relatedTarget)||aP(null)},[u]),sK=(0,i.useCallback)(e=>{let t=e.dataTransfer.getData("application/x-transition-type");if(!t)return!1;e.preventDefault(),e.stopPropagation();let r=az.find(e=>e.key===a$);return r&&Promise.resolve().then(a.bind(a,74698)).then(({getTransitionDefinition:e})=>{let a=e(t);a&&rr(r.sceneId,s3({transitionType:t,definition:a,minDuration:aj.Cy,maxDuration:aj.u1}))}),aP(null),!0},[az,a$,rr]),sV=(0,i.useCallback)(()=>{let e=y.zC.getState().projectTime,t=q.filter(e=>"scene"===e.type);if(0===t.length)return null;let a=(()=>{let a=null;for(let r of az){let n=t.find(e=>e.id===r.fromBlockId);if(!n?.sceneId)continue;let i=Math.abs(r.seamTime-e);(!a||i<a.distance)&&(a={sceneId:n.sceneId,distance:i})}return a?.sceneId??null})()??(()=>{let a=new Map;for(let e of t){let t=e.trackId??1;a.has(t)||a.set(t,[]),a.get(t).push(e)}let r=[...a.values()].map(e=>[...e].sort((e,t)=>
97e.start-t.start)).filter(e=>e.length>=2);if(0===r.length)return null;let n=r.find(t=>t.some(t=>e>=t.start&&e<t.start+(t.duration??0)))??r[0],i=n.find(t=>e>=t.start&&e<t.start+(t.duration??0)),s=i&&i!==n[n.length-1]?i:n[n.length-2];return s?.sceneId??null})();return a?(eb([a]),a):null},[q,az,eb]),sH=(0,i.useCallback)(e=>{sW(e)||sf(e)},[sW,sf]),sq=(0,i.useCallback)(e=>{sU(e),sk(e),e.currentTarget.contains(e.relatedTarget)||(ts.current=lt())},[sU,sk]),sY=(0,i.useCallback)(e=>{try{if(sK(e))return;sP(e)}finally{ts.current=lt()}},[sK,sP]);(0,ox.Oi)(aL),function({containerRef:e,zoomLevel:t,transitionDropSeams:r,currentProject:n,getTrackIdFromClientY:s,handleApplyTransition:o,handleApplyEffect:l,duplicateScene:d,updateCoreProjectState:c,saveCurrentProject:u,pushAction:p,setHighlightedSeamKey:m,setTouchHighlightedSceneId:h}){let f=(0,i.useRef)(r);f.current=r;let g=(0,i.useRef)(t);g.current=t;let x=(0,i.useRef)(o);x.current=o;let b=(0,i.useRef)(l);b.current=l;let w=(0,i.useRef)(n);w.current=n;let k=(0,i.useRef)(d);k.current=d;let S=(0,i.useRef)(c);S.current=c;let j=(0,i.useRef)(u);j.current=u;let I=(0,i.useRef)(p);I.current=p;let N=(0,i.useRef)(s);N.current=s,(0,i.useEffect)(()=>{function t(t){let a=e.current;if(!a)return null;let r=t-a.getBoundingClientRect().left+a.scrollLeft;return s8(f.current,r,g.current,200)}function r(e,t){let a=document.elementFromPoint(e,t);if(!a)return null;let r=a.closest("[data-scene-id]");return r?.getAttribute("data-scene-id")||null}function n(t,a){let r=e.current;return r?{dropTime:Math.max(0,(t-r.getBoundingClientRect().left+r.scrollLeft)/g.current),targetTrack:sl(N.current(a)??1)}:{dropTime:0,targetTrack:sl(1)}}function i(e){let{clientX:a,clientY:n,data:i}=e.detail;if("transition"===i.type){let e=t(a);m(e?e.key:null)}else"effect"===i.type?h(r(a,n)):("mediabin-scene"===i.type||"mediabin-audio"===i.type)&&h(r(a,n))}function s(e){let{clientX:i,clientY:s,data:o}=e.detail;(async()=>{if("transition"===o.type){let e=t(i);if(e){let t=o.payload.transitionType;Promise.resolve().then(a.bind(a,74698)).then(({getTransitionDefinition:a})=>{let r=a(t);r&&x.current(e.sceneId,s3({transitionType:t,definition:r,minDuration:aj.Cy,maxDuration:aj.u1}))})}m(null);return}if("effect"===o.type){let e=r(i,s);if(e){let t=o.payload.effectType;Promise.resolve().then(a.bind(a,74698)).then(({getEffectDefinition:a})=>{let r=a(t);if(r){let a=r.createEffect?r.createEffect():{id:(0,v.generateId)(),type:t,params:{...r.defaultParams},enabled:!0};b.current(e,a)}})}h(null);return}if("mediabin-scene"===o.type){let e=o.payload.scene;if(!e)return h(null);let{dropTime:t,targetTrack:a}=n(i,s),r=w.current,l=k.current,d=S.current,c=j.current,u=I.current,p=sc(y.zC.getState().blocks,"scene",t,eh(e),sl(Math.max(1,a)));if(r?.scenes?.some(t=>t.id===e.id)&&l){let a=await l(e.id,void 0,void 0,{timelineStart:t,trackId:p});a&&r?.scenes&&u&&u(sE({scenes:r.scenes,originalSceneId:e.id,newScene:a})),h(null);return}if(r&&d&&c){let{updatedProject:a,undoAction:n}=function(e){let{droppedScene:t,project:a,dropTime:r,targetTrack:n}=e,i=e.now??Date.now(),s={...JSON.parse(JSON.stringify(t)),id:e.newSceneId??(0,v.generateId)(),createdAt:i,updatedAt:i,timelineStart:r,trackId:n},o=[...a.scenes||[],s];return{newScene:s,updatedProject:{...a,scenes:o,updatedAt:i}
97,undoAction:{type:"ADD_SCENE",previousState:{scenes:[...a.scenes||[]],affectedSceneId:s.id},newState:{scenes:o,affectedSceneId:s.id}}}}({droppedScene:e,project:r,dropTime:t,targetTrack:p});u?.(n),d(a),await c(a)}return h(null)}if("mediabin-audio"===o.type){let e=o.payload.audio;if(!e)return h(null);let{dropTime:t,targetTrack:a}=n(i,s),r=w.current,l=S.current,d=j.current,c=I.current,u=sc(y.zC.getState().blocks,"audio",t,sd(e),sl(Math.max(2,a)));if(r&&l&&d){let{updatedProject:a,undoAction:n}=function(e){let{droppedAudio:t,project:a,dropTime:r,targetTrack:n}=e,i=e.now??Date.now(),s={...JSON.parse(JSON.stringify(t)),id:e.newAudioId??`audio-${(0,v.generateId)()}`,start:r,trackId:n,status:t.status||"ready",createdAt:i,updatedAt:i},o=[...a.audio||a.voiceovers||[],s];return{newAudio:s,updatedProject:{...a,audio:o,voiceovers:o,updatedAt:i},undoAction:{type:"ADD_AUDIO_BLOCK",previousState:{scenes:[...a.scenes||[]],audioBlock:s},newState:{scenes:[...a.scenes||[]],audioBlock:s}}}}({droppedAudio:e,project:r,dropTime:t,targetTrack:u});c?.(n),l(a),await d(a)}h(null)}})()}return document.addEventListener(ec,i),document.addEventListener(eu,s),()=>{document.removeEventListener(ec,i),document.removeEventListener(eu,s)}},[])}({containerRef:u,zoomLevel:aL,transitionDropSeams:az,currentProject:h,getTrackIdFromClientY:ii,handleApplyTransition:rr,handleApplyEffect:a6,duplicateScene:N,updateCoreProjectState:_,saveCurrentProject:A,pushAction:e8,setHighlightedSeamKey:aP,setTouchHighlightedSceneId:aR});let sZ=(0,r.jsx)(lr,{indicator:nu}),s9=(0,r.jsx)(ln,{indicator:np});return c?(0,r.jsxs)("div",{className:"w-full bg-slate-950/95 border-t border-slate-800/80 shadow-[0_-20px_60px_rgba(0,0,0,0.55)] backdrop-blur-sm flex flex-col select-none relative",style:{height:n1},children:[(0,r.jsx)("style",{children:` 98 @keyframes volumeIndicatorPulse { 0% { opacity: 0.7; transform: scale(0.95); } 22% { opacity: 1; transform: scale(1.02); } 100% { opacity: 0; transform: scale(1.03); } } 99 .timeline-scroll-hidden { scrollbar-width: none; } 100 .timeline-scroll-hidden::-webkit-scrollbar { display: none; } 101 `}),(0,r.jsx)("div",{className:"h-11 bg-slate-950/70 flex items-center px-4 border-b border-slate-800/70 justify-end backdrop-blur-sm",children:(0,r.jsxs)("div",{className:"flex items-center gap-1 bg-slate-900/50 rounded-lg p-0.5 border border-slate-700/50",children:[(0,r.jsx)("button",{onClick:id,className:"p-1.5 rounded-md text-slate-400 hover:text-slate-200 hover:bg-slate-700/50 transition-all duration-150",title:"Scroll left",children:(0,r.jsx)(B.A,{size:15})}),(0,r.jsx)("button",{onClick:aO,className:"p-1.5 rounded-md text-slate-400 hover:text-slate-200 hover:bg-slate-700/50 transition-all duration-150",title:"Zoom out",children:(0,r.jsx)(ny.A,{size:15})}),(0,r.jsxs)("span",{className:"text-[11px] text-slate-500 w-14 text-center font-mono tabular-nums",children:[Math.round(aL),"px/s"]}),(0,r.jsx)("button",{onClick:aF,className:"p-1.5 rounded-md text-slate-400 hover:text-slate-200 hover:bg-slate-700/50 transition-all duration-150",title:"Zoom in",children:(0,r.jsx)(nv.A,{size:15})}),(0,r.jsx)("button",{onClick:nn?na:nr,className:"p-1.5 rounded-md text-slate-400 hover:text-slate-200 hover:bg-slate-700/50 transition-all duration-150",title:nn?"Zoom to selection (Z) - Shift+Z fits the whole project":"Zoom to fit the whole project (Z)","data-testid":"timeline-zoom-to-fit",children:(0,r.jsx)(e7.A,{size:15})}),(0,r.jsx)("button",{onClick:ic,className:"p-1.5 rounded-md text-slate-400 hover:text-slate-200 hover:bg-slate-700/50 transition-all duration-150",title:"Scroll right",children:(0,r.jsx)(W.A,{size:15})})]})}),(0,r.jsx)("div",{className:"flex-1 flex min-h-0 overflow-hidden",children:(0,r.jsx)("div",{ref:u,className:"flex-1 min-h-0 relative overflow-x-auto overflow-y-auto bg-slate-900/60 timeline-scroll-hidden",style:{scrollbarWidth:"none",msOverflowStyle:"none"},"data-testid":"master-timeline-container",onMouseDown:iM,onTouchStart:i_,onMouseMove:iA,onMouseLeave:eq,onScroll:iu,onDragOver:sH,onDragLeave:sq,onDrop:sY,children:(0,r.jsxs)("div",{className:"relative",style:{width:ig,minHeight:nY+aj.Dm},children:[(0,r.jsx)(oR,{visibleRulerTicks:iv,zoomLevel:aL,rulerHeight:aj.Dm,onMouseDown:so,markers:eA}),(0,r.jsx)("div",{className:"absolute left-0 w-full",style:{height:nY,top:aj.Dm},children:q.filter(e=>e.scene&&(tk||(e.trackId??1)!==0)).map(e=>{let{top:t,height:a}=n6(e.trackId??1),n=Math.max(4,a);return(0,r.jsx)("div",{"data-scene-block":!0,className:"absolute bg-slate-800/60 border border-slate-700/60 pointer-events-none",style:{left:e.start*aL,top:t,width:e.duration*aL,height:n}},e.id)})}),(0,r.jsx)(o5,{zoomLevel:aL})]})})}),sZ,s9]}):(0,r.jsxs)("div",{className:"w-full border-t border-white/[0.07] shadow-[0_-20px_60px_rgba(0,0,0,0.55)] backdrop-blur-sm flex flex-col select-none relative",style:{height:n1,background:"linear-gradient(180deg, rgba(7,10,18,0.97) 0%, rgba(3,5,10,0.99) 100%)"},onDragOver:sH,onDragLeave:sq,onDrop:sY,children:[(0,r.jsx)("style",{children:` 102 @keyframes flushPulse { 0% { opacity: 1; box-shadow: 0 0 8px rgba(239, 68, 68, 1), 0 0 16px rgba(239, 68, 68, 0.7); } 100% { opacity: 0; box-shadow: 0 0 0px rgba(239, 68, 68, 0), 0 0 0px rgba(239, 68, 68, 0); } } 103 @keyframes volumeIndicatorPulse { 0% { opacity: 0.7; transform: scale(0.95); } 22% { opacity: 1; transform: scale(1.02); } 100% { opacity: 0; transform: scale(1.03); } } 104 .timeline-scroll-hidden { scrollbar-width: none; } 105 .timeline-scroll-hidden::-webkit-scrollbar { display: none; } 106 `}),sZ,s9,(0,r.jsx)("div",{className:"absolute left-0 right-0 cursor-ns-resize z-30 flex items-center justify-center hover:bg-sky-500/10 transition-colors",style:{to
106p:-6,height:12},onDoubleClick:tI,onMouseDown:tj?void 0:e=>{e.preventDefault(),e.stopPropagation();let t=e.clientY;if(!nW.length||nq<=0)return;let a=null,r=t,n=document.body.style.cursor,i=document.body.style.userSelect;document.body.style.cursor="ns-resize",document.body.style.userSelect="none";let s=()=>{a=null;let e=r-t;n5(Math.max(aj.ol,nq-e),aj.ol)},l=e=>{r=e.clientY,null==a&&(a=(0,o.EP)(s))},d=()=>{null!=a&&cancelAnimationFrame(a),document.body.style.cursor=n,document.body.style.userSelect=i,document.removeEventListener("mousemove",l),document.removeEventListener("mouseup",d)};document.addEventListener("mousemove",l),document.addEventListener("mouseup",d)}}),(0,r.jsx)(og,{isPlaying:em,onTogglePlay:()=>eV(!em),duration:ep,isRestartModeEnabled:eY,onToggleRestartMode:nt,loopRegion:eC,onClearLoopRegion:e_,isMagnetEnabled:eX,isGridEnabled:eJ,gridIntervalSeconds:aU,isGridAuto:eQ,onToggleMagnetMode:e1,onToggleGridMode:e5,onSetGridIntervalSeconds:e2,onSetGridAuto:e4,overlapPolicy:e0,onSetOverlapPolicy:e3,showTrack0:tk,onToggleTrack0:()=>tS(!tk),canUndo:te(),canRedo:tt(),onUndo:r6,onRedo:r9,isSpliceMode:a1,onToggleSpliceMode:a5,onDisableSpliceMode:a4,waveformMode:tL,onCycleWaveformMode:tX,zoomLevel:aL,onZoomIn:aF,onZoomOut:aO,onScrollLeft:id,onScrollRight:ic,isCollapsed:tj,onToggleCollapse:tI,compactViewport:tx<=900,onSeekToTime:iD,onAddMarker:iO,onRippleDelete:iJ,onDuplicateSelected:iZ,hasSelection:ex.length>0||!!eg||ew.length>0||!!ev,hasSceneSelection:ex.length>0||!!eg}),(0,r.jsxs)("div",{className:"flex-1 flex min-h-0 overflow-hidden",style:{height:tj?0:void 0,display:tj?"none":void 0},children:[(0,r.jsx)(oT,{showTrack0:tk,visibleTrackCount:nF,rulerHeight:aj.Dm,getTrackHeight:n4,getAutomationLaneHeight:aY,getTrackEffectsLaneTotalHeight:ia,isTrackEffectsLaneCollapsed:ir,onToggleTrackEffectsLane:it,getTrackEffectsLaneRowHeight:aZ,getTrackEffectsLaneRowCount:e=>nV.get(e)?.rowCount??1,onEffectsLaneRowHeightChange:aQ,onClickToSeekZero:()=>iC(0),onHoverSeekZero:iE,canTrackUseAutomation:e=>0!==e&&rq(e).length>0,isTrackAutomationExpanded:e=>0!==e&&rY(e).expanded,getTrackAutomationLaneCount:e=>{if(0===e)return 0;let t=rY(e);return t.expanded?Math.max(1,s5(t).length):0},onToggleTrackAutomation:e=>{0===e||0!==rq(e).length&&rG(e)},onAddTrackAutomationLane:e=>{0===e||0!==rq(e).length&&rX(e)},onRemoveTrackAutomationLane:(e,t)=>{0!==e&&rJ(e,t)},onDeleteTrack:e=>{nR.requestTrackDelete(e)},onSelectTrackCaptions:e=>{let t=es(e).filter(e=>"caption"===e.type).map(e=>e.id);0!==t.length&&(eb([]),eS(t),eN(!0),ry("captions"))},ref:p}),(0,r.jsx)("div",{ref:u,className:"flex-1 min-h-0 relative overflow-x-auto overflow-y-auto bg-slate-900/60 timeline-scroll-hidden",style:{scrollbarWidth:"none",msOverflowStyle:"none",touchAction:tx<=900?"pan-x pan-y":void 0,overscrollBehaviorX:tx<=900?"contain":void 0},"data-testid":"master-timeline-container",onMouseDown:iM,onTouchStart:i_,onMouseMove:iA,onMouseLeave:eq,onScroll:iu,onDragOver:sH,onDragLeave:sq,onDrop:sY,children:(0,r.jsxs)("div",{className:"relative",style:{width:ig,minHeight:nq+aj.Dm},children:[(0,r.jsx)(oR,{visibleRulerTicks:iv,zoomLevel:aL,rulerHeight:aj.Dm,onMouseDown:so,markers:eA,onMarkerMouseDown:iK,onMarkerDoubleClick:iV,onMarkerContextMenu:iH,children:(0,r.jsx)(ls,{loopRegion:eC,loopDragState:su,zoomLevel:aL,onClearLoopRegion:e_,onLoopEdgeMouseDown:si})}),t5&&(e=new Map,(t=q.filter(e=>"scene"===e.type&&!e.sceneId.startsWith("__track0"))).forEach(a=>{let r=iS.has(a.id)||iS.has(a.sceneId),n=a.start,i=a.start+a.duration,s=a.trackId??1;t.forEach(t=>{if(t.id===a.id)return;let o=iS.has(t.id)||iS.has(t.sceneId);if(!r&&!o||r&&o)return;let l=t.start,d=t.start+t.duration,c=s!==(t.trackId??1);if(.1>Math.abs(i-l)){let t=Math.round(100*i)/100;e.set(t,e.get(t)||c)}if(.1>Math.abs(n-d)){let t=Math.round(100*n)/100;e.set(t,e.get(t)||c)}})}),Array.from(e.entries()).map(([e,t])=>({time:e,isCrossTrack:t}))).map(({time:e,isCrossTrack:t})=>(0,r.jsx)("div",{className:"absolute pointer-events-none",style:{left:e*aL,top:0,width:1,height:aj.Dm+nY,backgroundColor:t?"rgba(239, 68, 68, 0.9)":"rgba(34, 197, 94, 0.9)",boxShadow:t?"0 0 4px rgba(239, 68, 68, 0.6)":"none",zIndex:100}},`flush-line-${e}`)),(0,r.jsxs)("div",{className:"absolute left-0 w-full",style:{height:nq,top:aj.Dm},children:[nW.map(e=>{let t=0===e,{top:a,height:n}=n2(e),s=ap===e;return(0,r.jsxs)(i.Fragment,{children:[(0,r.jsx)("div",{className:`absolute h-px ${t?"bg-amber-500/30":"bg-white/[0.06]"}
106`,style:{top:a+n,left:ib.startPixels,width:ib.endPixels-ib.startPixels}}),(0,r.jsx)("div",{className:"absolute left-0 w-full h-[6px] cursor-ns-resize z-30",style:{top:a-3},onMouseDown:t=>{t.preventDefault(),t.stopPropagation();let a=t.clientY,r=document.body.style.cursor,i=document.body.style.userSelect;document.body.style.cursor="ns-resize",document.body.style.userSelect="none";let s=null,o=t=>{t.preventDefault();let r=t.clientY-a,i=Math.max(aj.ol,Math.min(aj.Uu,n-r));null!=s&&cancelAnimationFrame(s),s=requestAnimationFrame(()=>{s=null,aV(e,i)})},l=()=>{null!=s&&cancelAnimationFrame(s),document.body.style.cursor=r,document.body.style.userSelect=i,document.removeEventListener("mousemove",o,!0),document.removeEventListener("mouseup",l,!0)};document.addEventListener("mousemove",o,!0),document.addEventListener("mouseup",l,!0)}}),(0,r.jsx)("div",{className:`absolute left-0 w-full transition-colors pointer-events-none ${t?"bg-amber-950/10":""} ${s?"bg-sky-400/[0.07]":""}`,style:{top:a,height:n}})]},`track-${e}`)}),(0,r.jsx)(oZ,{orderedVisibleTrackIds:nW,blocks:q,scenes:h?.scenes,timelineWidth:ig,zoomLevel:aL,customAutomationPropertyDefinitions:rL,motionPresetDropdownOptions:rF,motionPresetLabelsByTrackProperty:rz,isTrackLocked:eT,getTrackAutomationPropertyOptions:rq,getTrackAutomationState:rY,getTrackAutomationLayout:n8,buildTrackAutomationSegments:rQ,handleTrackAutomationPropertyChange:rZ,handleTrackParameterPickerRequest:rV,handleTrackAutomationPresetSelect:r4,updateSegmentAutomationCurve:r0,beginAutomationUndoTransaction:r1,commitAutomationUndoTransaction:r5,setAutomationLaneHeight:aG}),nW.map(e=>{if(0===e)return null;let t=n9(e);if(!t.hasEffects)return null;let a=new Set([0]);return t.laneBlocks.forEach(e=>{a.add(e.sceneStartSec),a.add(e.sceneStartSec+e.sceneDurationSec),a.add(e.sceneStartSec+e.startOffsetSec),a.add(e.sceneStartSec+e.startOffsetSec+e.durationSec)}),(0,r.jsx)(sg,{trackId:e,top:t.top,width:ig,height:t.height,rowCount:t.rowCount,rowHeight:t.rowHeight,zoomLevel:aL,collapsed:t.collapsed,blocks:t.laneBlocks,snapPoints:Array.from(a),isMagnetEnabled:eX,isGridEnabled:eJ,gridIntervalSeconds:aU,onChangeTiming:n7,onSelectEffect:ie,onRowHeightChange:aQ},`effects-lane-${e}`)}),(0,r.jsx)(oO,{loopRegion:eC,zoomLevel:aL}),(0,r.jsx)(oz,{selectionBox:iI}),(0,r.jsx)(oL,{preview:ag,zoomLevel:aL,getTrackLayout:n6}),null!==ah&&(0,r.jsx)("div",{className:"absolute top-0 bottom-0 pointer-events-none",style:{left:ah*aL,width:1,background:"rgba(96, 165, 250, 0.7)",boxShadow:"0 0 6px rgba(96, 165, 250, 0.5)",zIndex:50}}),(0,r.jsx)(oF,{preview:sh,zoomLevel:aL,getTrackLayout:n6}),Z&&(0,r.jsx)(l1,{ghost:Z,zoomLevel:aL},Z.planSceneId),ab&&ar&&(n=n6(ar.trackId||1),(0,r.jsx)("div",{className:"absolute pointer-events-none",style:{left:ar.start*aL,top:n.top+2,width:ar.duration*aL,height:n.height-4,backgroundColor:"rgba(96, 165, 250, 0.3)",zIndex:45}})),!(0,o.QA)()&&(0,r.jsx)(lV,{blocks:q,showTrack0:tk,zoomLevel:aL,trimHandleWidth:iw,waveformMode:tL,blockCullingViewport:iy,visibleRange:ib,localTrimPreview:ai,selectedSceneIds:ex,draggingId:t5,trimmingId:t3,initialSelectionBlocks:ao,dragSelectionBlockIds:iS,flushPulseEdges:ak,draggedEdgePositions:ij,sceneNumberBySceneId:tN,sceneBlobUrls:eU,localGeneratingIds:G,facelessGeneratingNleIds:J,touchHighlightedSceneId:aD,splitRegenerateNleSceneId:ez,setSplitRegenerateNleSceneId:eL,blocksWithWaveform:tB,blocksWithoutWaveform:tU,setBlocksWithWaveform:tW,setBlocksWithoutWaveform:tK,activeVolumeDragBlockId:nd,activeAudioFadeDragBlockId:nc,contextMenuBlockId:tZ?.block.id??null,persistedAudioAnalysis:h?.aiAnalysis,persistAudioAnalysisArtifact:L,setHoveredMediaKey:eH,clearHoveredMediaKey:eq,getTrackContentLayout:n6,isTrackLocked:eT,isTrackVisible:e$,isTrackMuted:eE,handleSceneClick:r_,handleBlockMouseDown:i3,handleBlockTouchStart:(e,t)=>{if(!e.touches.length)return;let a=e.touches[0];i3(i6(e),t);let r=e.currentTarget;ni();let n={blockId:t.id,sceneId:t.sceneId,block:t,originElement:r,startX:a.clientX,startY:a.clientY,lastX:a.clientX,lastY:a.clientY,movedOffScene:!1,opened:!1,timer:null};n.timer=setTimeout(()=>{let e=t0.current;e&&e.blockId===t.id&&!e.movedOffScene&&(e.opened=!0,e.timer=null,t1.current=Date.now()+aj.kV,t2(null),al(null),an(null),ns(e.block,e.originElement,e.lastX))},aj.WV),t0.current=n,e.preventDefault()},handleBlockTouchMove:(e,t)=>
106{let a=t0.current;if(!a||a.blockId!==t.id||!e.touches.length)return;let r=e.touches[0];a.lastX=r.clientX,a.lastY=r.clientY;let n=r.clientX-a.startX,i=r.clientY-a.startY;!a.opened&&Math.sqrt(n*n+i*i)>aj.Sx&&a.timer&&(clearTimeout(a.timer),a.timer=null);let s=document.elementFromPoint(r.clientX,r.clientY);(s instanceof HTMLElement&&s.closest("[data-scene-id]")?.getAttribute("data-scene-id")||null)!==a.sceneId&&(a.movedOffScene=!0,a.timer&&(clearTimeout(a.timer),a.timer=null),a.opened&&tQ(e=>e?.block.id===a.blockId?null:e))},handleBlockTouchEnd:e=>{let t=t0.current;t&&t.blockId===e.id&&ni()},handleSceneContextMenu:no,handleApplyEffect:a6,handleVolumeLineMouseDown:ng,handleVolumeLineDoubleClick:nx,handleAudioFadeHandleMouseDown:nb,handleAudioFadeHandleDoubleClick:nM,handleTrimMouseDown:i8,handleTrimTouchStart:(e,t,a)=>{e.touches.length&&(i8(i6(e),t,a),e.preventDefault())}}),!(0,o.QA)()&&(0,r.jsx)(lm,{audioBlocks:Q,blocks:q,zoomLevel:aL,trimHandleWidth:iw,waveformMode:tL,blockCullingViewport:iy,localTrimPreview:ai,selectedAudioBlockIds:ew,draggingId:t5,initialSelectionBlocks:ao,dragSelectionBlockIds:iS,flushPulseEdges:ak,draggedEdgePositions:ij,sceneNumberBySceneId:tN,blocksWithWaveform:tB,setBlocksWithWaveform:tW,activeVolumeDragBlockId:nd,activeAudioFadeDragBlockId:nc,contextMenuBlockId:tZ?.block.id??null,persistedAudioAnalysis:h?.aiAnalysis,persistAudioAnalysisArtifact:L,getTrackContentLayout:n6,isTrackLocked:eT,isTrackVisible:e$,isTrackMuted:eE,handleAudioBlockClick:rA,handleBlockMouseDown:i3,handleSceneContextMenu:no,handleVolumeLineMouseDown:ng,handleVolumeLineDoubleClick:nx,handleAudioFadeHandleMouseDown:nb,handleAudioFadeHandleDoubleClick:nM,handleTrimMouseDown:i8,staleVoiceoverBlocks:ee,onRegenerateVoiceoverBlock:et}),io&&(0,r.jsx)(oB,{captionBlock:io.captionBlock,anchorBlock:io.anchorBlock,audioSource:io.audioSource,persistedAudioAnalysis:h?.aiAnalysis,onPersistAudioAnalysisArtifact:L,zoomLevel:aL,trackTop:io.trackTop,trackHeight:io.trackHeight,guideExtendToY:io.wordGuideExtendToY,waveformMode:tL,onCaptionBlockChange:i7,onCaptionBlockCommit:sn}),!(0,o.QA)()&&(0,r.jsx)(lc,{captionBlocks:er,blocks:q,zoomLevel:aL,trimHandleWidth:iw,captionBlockFontSize:ik,selectedAudioBlockIds:ew,draggingId:t5,timingEditCaptionId:t6,initialSelectionBlocks:ao,dragSelectionBlockIds:iS,flushPulseEdges:ak,draggedEdgePositions:ij,sceneBlocksForCaptionMarkers:en,sceneNumberBySceneId:tN,getTrackLayout:n2,isTrackLocked:eT,isTrackVisible:e$,handleAudioBlockClick:rA,handleCaptionTimingEditToggle:i9,handleBlockMouseDown:i3,handleTrimMouseDown:i8}),!(0,o.QA)()&&(0,r.jsx)(lo,{blocks:q,zoomLevel:aL,trimHandleWidth:iw,selectedTransitionKey:tT,draggingTransition:a_,panelDraggingDuration:aE,getTrackContentLayout:n6,setDraggingTransition:aA,setSelectedTransitionKey:t$,setSelectedTransitionSceneId:tR,setSelectedSceneIds:eb,setSelectedAudioBlockIds:eS,setActiveSidePanel:ry,rememberSceneSidePanel:rC,setPanelOpenForSceneId:rN,handleRemoveTransition:rn,clearSelectedTransition:tz,handleApplyTransition:rr,handleUpdateTransition:ri}),a$&&az.map(e=>{if(e.key!==a$)return null;let{top:t,height:a}=n2(e.trackId);return(0,r.jsx)("div",{className:"absolute pointer-events-none",style:{left:e.seamTime*aL-40,top:t,width:80,height:a,zIndex:50},children:(0,r.jsx)("div",{className:"absolute inset-0 border border-dashed border-white/40 bg-white/[0.1] backdrop-blur-sm rounded-sm flex items-center justify-center",children:(0,r.jsxs)("div",{className:"flex flex-col items-center gap-0.5",children:[(0,r.jsx)(nw.A,{size:14,className:"text-white/60"}),(0,r.jsx)("span",{className:"text-[9px] text-white/50 font-medium",children:"Drop here"})]})})},e.key)})]}),(0,r.jsx)(o5,{zoomLevel:aL})]})})]}),(0,r.jsx)(nQ,{isOpen:rv,onClose:()=>rM("media"),activePanel:rb,onSelectPanel:rM,highlightedPanelTabs:rK,isKeyframeParameterPickerActive:rO,selectedKeyframeParameterKey:rW,onSelectKeyframeParameter:rH,selectedSceneTimelineStart:rT?.timelineStart??null,selectedSceneId:rT?.id||null,selectedSceneBrightnessSpot:Number.isFinite(rT?.media?.brightnessSpotX)&&Number.isFinite(rT?.media?.brightnessSpotY)?{x:rT.media.brightnessSpotX,y:rT.media.brightnessSpotY}:null,currentEffects:rT?.effects||l5,sceneDurationSec:r$,onApplyEffect:a6,onRemoveEffect:a9,onUpdateEffect:a7,onUpdateEffectTiming:re,projectFilterPresetId:rD.presetId,projectFilterMixed:rD.mixed,projectSceneCount:rD.sceneCount,projectFilterEffect:rD.effect,onApplyFilterToAllScenes:rt,onUpdateProjectFilterParams:ra}),(0,r.jsx)(n3,{isOpen:rw,onClose:()=>rM("media"),activePanel:rb,onSelectPanel:rM,highlightedPanelTabs:rK,isKeyframeParameterPickerActive:rO,selectedKeyframeParameterKey:rW,onSelectKeyframeParameter:rH,selectedSceneId:rT?.id||null,currentTransition:rT?.transition,onApplyTransition:rr,onResolveFallbackSceneId:sV,onRemoveTransition:rn,onUpdateTransition:ri,onDurationPreview:(e,t)=>aT({sceneId:e,duration:t}),onDurationPreviewEnd:()=>aT(null)}),(0,r.jsx)(ix,{isOpen:rk,onClose:()=>rM("media"),activePanel:rb,onSelectPanel:rM,projectId:h?.id,addVoiceover:T,selectedSceneId:rP?.id??null,selectedSceneText:rP?.text??"",selectedSceneStart:rP?.timelineStart??null}),(0,r.jsx)(iN,{isOpen:rS,onClose:()=>rM("media"),activePanel:rb,onSelectPanel:rM,projectId:h?.id,addVoiceover:T}),(0,r.jsx)(iT,{isOpen:rj,onClose:()=>rM("media"),activePanel:rb,onSelectPanel:rM,projectId:h?.id,addVoiceover:T,resolveTrackId:tE}),(0,r.jsx)(se,{isOpen:rI,onClose:()=>rM("media"),activePanel:rb,onSelectPanel:rM,projectId:h?.id,selectedSceneId:rP?.id??null,selectedSceneText:rP?.text??""}),iq&&((l=eA.find(e=>e.id===iq.markerId))?(0,r.jsx)(o7,{markerEditState:iq,marker:l,onClose:iY,onRename:iW,onSetColor:iU,onRemove:iB}):null),(0,r.jsx)(oQ,{controller:nR}),tZ&&(0,r.jsx)(oD,{block:tZ.block,position:tZ.position,onClose:nl,onVolumeChange:nm,onMuteToggle:nh,onFadeSlopeChange:nf,onFlattenAudio:e=>void nA(e),flattenAudioBlockIds:("voiceover"===tZ.block.type||"audio"===tZ.block.type)&&ew.length>=2&&ew.includes(tZ.block.id)?ew:[],onExtractAudio:n_,onApplyMotionPreset:r2,onAutoReframe:e=>void r3(e),autoReframeStatus:"scene"===tZ.block.type?r8[tZ.block.sceneId]?.status??"idle":"idle",autoReframeError:"scene"===tZ.block.type?(d=r8[tZ.block.sceneId],d?.status==="error"?d.message:void 0):void 0,onDuplicateScene:nE,onDeleteScene:nT,onRippleDeleteScene:n$,selectedSceneCount:"scene"===tZ.block.type?nP(tZ.block.sceneId):1,currentVolume:tZ.block.volume??1,currentMuted:tZ.block.muted??!1,showExtractAudio:"scene"===tZ.block.type&&tZ.block.scene?.media?.type==="video"})]})}var l4=a(54896);let l3=e=>[`live-cap-${e}`,`restored-cap-${e}`,`faceless-ph-cap-${e}`],l8=e=>"number"==typeof e&&Number.isFinite(e),l6=e=>{let t=l8(e.start)?e.start:0,a=l8(e.outOffset)?e.outOffset:l8(e.duration)?e.duration:void 0;if(void 0===a)return null;let r=a-(l8(e.inOffset)?e.inOffset:0);return r>0?{start:t,duration:r}:null};function l9(e,t){return Math.min(e.start+e.duration,t.start+t.duration)-Math.max(e.start,t.start)}function l7(e){let t=e.filter(e=>e.duration>0).map(e=>({...e,resolvedTrack:Math.max(1,Math.floor(Number(e.trackId??1))||1)}
106)),a=[];for(let e=0;e<32;e+=1){let e=function(e){for(let t=0;t<e.length;t+=1)for(let a=t+1;a<e.length;a+=1){let r=e[t],n=e[a];if(r.sceneId!==n.sceneId&&r.resolvedTrack===n.resolvedTrack&&r.isSettled&&n.isSettled&&l9(r,n)>.025)return[r,n]}return null}(t);if(!e)break;let[r,n]=e,i="a"==(r.isFaceless!==n.isFaceless?r.isFaceless?"a":"b":r.start!==n.start?r.start>n.start?"a":"b":r.order>n.order?"a":"b")?r:n,s=i.resolvedTrack+1,o=e=>t.some(t=>t!==i&&t.resolvedTrack===e&&l9(t,i)>.025);for(;o(s);)s+=1;a.push({sceneId:i.sceneId,fromTrackId:i.resolvedTrack,toTrackId:s}),i.resolvedTrack=s}return a}let de=(e,t)=>{let a=new Date().toISOString().split("T")[1].slice(0,12);console.log(`[SCENE-FLOW] [${a}] SYNC: ${e}`,t?JSON.stringify(t,null,0):"")},dt=e=>null!=e.storeSceneTrackId&&Number.isFinite(e.storeSceneTrackId)?Number(e.storeSceneTrackId):null!=e.projectSceneTrackId&&Number.isFinite(e.projectSceneTrackId)?Number(e.projectSceneTrackId):null!=e.metaParentTrackId&&Number.isFinite(e.metaParentTrackId)?Number(e.metaParentTrackId):Math.max(1,(e.layers[0]??2)-1),da=(e,t)=>Array.isArray(e)&&e.length>0?e:Array.isArray(t)&&t.length>0?t:[],dr=({audioBlocks:e})=>{let t=(0,s.By)(),{currentProject:a}=t,r=(0,y.zC)(e=>e.syncFromScenes),n=(0,y.zC)(e=>e.syncVoiceoversFromProject),o=(0,y.zC)(e=>e.replaceCaptionBlocksForScene),l=(0,y.zC)(e=>e.ensureStackedCaptionTracks),d=(0,y.zC)(e=>e.resetProjectTransientState),c=(0,y.zC)(e=>e.blocks.filter(e=>"scene"===e.type).map(e=>`${e.id}:${!0===e.isLoading?"loading":"settled"}`).sort().join("|")),u=(0,i.useRef)(0),p=(0,i.useRef)(""),m=(0,i.useRef)(0),h=(0,i.useRef)(""),f=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=a?.id??null;e&&(f.current!==e&&(de("PROJECT_CHANGED_RESET_TIMELINE_STORE",{previousProjectId:(f.current??"none").substring(0,8),nextProjectId:e.substring(0,8)}),d(),u.current=0,p.current="",m.current=0,h.current=""),f.current=e)},[a?.id,d]),(0,i.useEffect)(()=>{if(a?.scenes){let e=a.scenes.map(e=>e.id).join(","),t=a.scenes.length;(t!==u.current||e!==p.current)&&(de("SCENES_CHANGED",{prevCount:u.current,newCount:t,sceneIds:a.scenes.map(e=>e.id.substring(0,8)),loadingScenes:a.scenes.filter(e=>e.isLoading||e.media?.status==="uploading").length,projectId:a.id?.substring(0,8)}),u.current=t,p.current=e),r(a.scenes)}else u.current>0&&(de("SCENES_CLEARED",{prevCount:u.current}),u.current=0,p.current="")},[a?.scenes,r]),(0,i.useEffect)(()=>{let t=Array.isArray(e)&&e.length>0?e:da(a?.audio,a?.voiceovers),r=t.map(e=>`${e.id}:${e.start??0}:${e.trackId??""}:${e.inOffset??""}:${e.outOffset??""}:${e.url??""}:${e.status??""}:${e.volume??""}:${e.muted??""}:${e.audioFadeInDuration??""}:${e.audioFadeOutDuration??""}:${e.audio_fade_in_duration??""}:${e.audio_fade_out_duration??""}:${e.audioFadeInSlope??""}:${e.audioFadeOutSlope??""}:${e.audio_fade_in_slope??""}:${e.audio_fade_out_slope??""}:${(0,aK.Sl)(e.automation)}`).join("|"),i=t.length;(i!==m.current||r!==h.current)&&(i>0?de("AUDIO_CHANGED",{prevCount:m.current,newCount:i,audioIds:t.map(e=>e.id.substring(0,15)),projectId:a?.id?.substring(0,8)}):m.current>0&&de("AUDIO_CLEARED",{prevCount:m.current}),m.current=i,h.current=r,n(t))},[e,a?.id,a?.audio,a?.voiceovers,n]);let g=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=a?.id;if(!e||g.current===e)return;g.current=e;let t=Array.isArray(a?.timelineMarkers)?a.timelineMarkers:[];y.zC.getState().setMarkers(t),window.__AUTOSHORTS_MARKERS_HYDRATED_PROJECT__=e,t.length>0&&de("MARKERS_RESTORED",{count:t.length,projectId:e.substring(0,8)})},[a?.id,a?.timelineMarkers]),(0,i.useEffect)(()=>{let e=a?.id,t=a?.captionBlocks,r=new Set(a?.hiddenCaptionBlockIds??[]);if(!e||!t||0===t.length)return;let n=y.zC.getState(),i=n.blocks,s=t.filter(e=>!r.has(e.id)),d=new Map;for(let e of s){let t=e.sceneId??"",a=Number(e.trackId??2),r=d.get(t)??[];r.includes(a)||r.push(a),d.set(t,r)}let c=new Map,u=new Map;for(let[e,t]of d){t.sort((e,t)=>e-t);let r=i.find(t=>t.sceneId===e&&"scene"===t.type),s=(a?.scenes??[]).find(t=>t.id===e),o=t.map(e=>n.trackMeta.get(e)).find(e=>e?.type==="caption"&&Number.isFinite(e.parentTrackId))?.parentTrackId,d=dt({layers:t,storeSceneTrackId:null!=r?Number(r.trackId??1):null,projectSceneTrackId:null!=s?Number(s.trackId??1):null,metaParentTrackId:o??null});u.set(e,d);let p=l(d,t.length),m=new Map;t.forEach((e,t)=>{m.set(e,p[t]??p[p.length-1])}),c.set(e,m)}let p=s.map(e=>{let t=e.sceneId??"",a=Number(e.trackId??2),r=c.get(t)?.get(a)??Math.max(2,a);return r!==e.trackId&&de("CAPTION_TRACK_REASSIGNED",{captionId:e.id.substring(0,15),savedTrack:e.trackId,resolvedTrack:r,parentTrack:u.get(t)}),{id:e.id,type:"caption",sourceCaptionId:e.sourceCaptionId,start:e.start,duration:e.duration,inOffset:e.inOffset,outOffset:e.outOffset,fullDuration:e.fullDuration,trackId:r,sceneId:e.sceneId,captionText:e.captionText,captionBox:e.captionBox,captionStyle:e.captionStyle,captionHighlightEnabled:e.captionHighlightEnabled,captionHighlightStyle:e.captionHighlightStyle,captionWords:e.captionWords,captionCues:e.captionCues,captionDisplayMode:e.captionDisplayMode,captionDisplayWindowSize:e.captionDisplayWindowSize,captionPunctuationMode:e.captionPunctuationMode,alignmentProvider:e.alignmentProvider,source:e.source,...e.isLoading?{isLoading:!0}:{}}}),m=i.filter(e=>"caption"===e.type),h=new Map(m.map(e=>[e.id,e])),f=e=>JSON.stringify({id:e.id,sourceCaptionId:e.sourceCaptionId,start:e.start,duration:e.duration,inOffset:e.inOffset,outOffset:e.outOffset,fullDuration:e.fullDuration,trackId:e.trackId,sceneId:e.sceneId,captionText:e.captionText,captionBox:e.captionBox,captionStyle:e.captionStyle,captionHighlightEnabled:e.captionHighlightEnabled,captionHighlightStyle:e.captionHighlightStyle,captionWords:e.captionWords,captionCues:e.captionCues,captionDisplayMode:e.captionDisplayMode,captionDisplayWindowSize:e.captionDisplayWindowSize,captionPunctuationMode:e.captionPunctuationMode,alignmentProvider:e.alignmentProvider,source:e.source});if((p.length!==m.length||p.some(e=>{let t=h.get(e.id);return!t||f(t)!==f(e)}))&&p.length>0){let t=p.filter(e=>{let t=s.find(t=>
106t.id===e.id);return t&&t.trackId!==e.trackId}).length;de("CAPTIONS_RESTORED",{count:p.length,projectId:e.substring(0,8),reassigned:t});let a=new Map;for(let e of p){let t=a.get(e.sceneId)??[];t.push(e),a.set(e.sceneId,t)}for(let[e,t]of a)o(e,t)}},[a?.id,a?.captionBlocks,a?.hiddenCaptionBlockIds,o,l]);let x=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=a?.id;!a||!e||x.current===e||Array.isArray(a.scenes)&&Array.isArray(a.captionBlocks)&&(x.current=e,(0,sA.i5)("project_load",y.zC.getState().blocks,{projectId:e,getBlocks:()=>y.zC.getState().blocks}))},[a]);let b=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=a?.id;if(!a||!e||!Array.isArray(a.scenes)||!Array.isArray(a.captionBlocks))return;let r=y.zC.getState().blocks.filter(e=>"scene"===e.type&&!e.sceneId?.startsWith("__track0")),n=new Map(a.scenes.map(e=>[e.id,e])),i=r.map((e,t)=>{let a=n.get(e.sceneId),r=a?.media?.status;return{sceneId:e.sceneId,trackId:e.trackId,start:e.start,duration:e.duration,isSettled:!!a&&!0!==e.isLoading&&!0!==a.facelessPlaceholder&&"generating"!==r&&"uploading"!==r,isFaceless:!!a&&(0,i$._e)(a),order:t}}),s=da(a.audio,a.voiceovers).map((e,t)=>({sceneId:e.id,trackId:e.trackId??2,start:Number.isFinite(e.start)?e.start:0,duration:sd(e),isSettled:!0!==e.isLoading&&"pending"!==e.status&&"processing"!==e.status,isFaceless:!1,order:t}));if(i.some(e=>!e.isSettled)||s.some(e=>!e.isSettled))return;let o=[e,...i.map(e=>`scene:${e.sceneId}:${e.trackId??1}:${e.start}:${e.duration}:${e.isSettled}`),...s.map(e=>`audio:${e.sceneId}:${e.trackId??2}:${e.start}:${e.duration}:${e.isSettled}`)].join("|");if(b.current===o)return;b.current=o;let l=l7(i),d=l7(s);if(0===l.length&&0===d.length)return;let c=new Map(l.map(e=>[e.sceneId,e.toTrackId])),u=new Map(d.map(e=>[e.sceneId,e.toTrackId])),p=Date.now(),m=a.scenes.map(e=>c.has(e.id)?{...e,trackId:c.get(e.id),updatedAt:p}:e),h=e=>e?.map(e=>u.has(e.id)?{...e,trackId:u.get(e.id),updatedAt:p}:e),f={...a,scenes:m,...Array.isArray(a.audio)?{audio:h(a.audio)}:{},...Array.isArray(a.voiceovers)?{voiceovers:h(a.voiceovers)}:{},updatedAt:p},g=[...l,...d];de("TIMELINE_OVERLAP_REPAIRED",{projectId:e.substring(0,8),moves:g.map(e=>`${e.sceneId.slice(0,8)}:${e.fromTrackId}->${e.toTrackId}`)}),(0,ey.trackEvent)("timeline_overlap_repaired",{project_id:e,moved_count:g.length,scene_moved_count:l.length,audio_moved_count:d.length,moves:g.map(e=>({from:e.fromTrackId,to:e.toTrackId}))}),t.updateCoreProjectState?.(f),t.saveCurrentProject?.(f)},[a,c]);let v=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=a?.id;if(!a||!e||v.current===e||!Array.isArray(a.scenes)||!Array.isArray(a.captionBlocks))return;v.current=e;let r=y.zC.getState(),n=r.blocks.filter(e=>"caption"===e.type),i=da(a.audio,a.voiceovers),s=!!a.captionsAutoRestoredAt,d=s&&0===a.captionBlocks.length&&0===n.length,c=function(e,t,a,r={}){let n=a??[];if(r.markerPresent&&n.length>0||!Array.isArray(e)||0===e.length)return[];let i=new Set(r.hiddenCaptionBlockIds??[]),s=new Set(n.map(e=>e.sceneId).filter(e=>!!e)),o=new Set(n.map(e=>e.id)),l=n.find(e=>l8(e.trackId))?.trackId??3,d=new Map;for(let e of t??[])"voiceover"!==e.type||e.isLoading||e.id.startsWith("faceless-ph-vo-")||(void 0===e.status||"ready"===e.status)&&e.sourceSceneId&&!d.has(e.sourceSceneId)&&d.set(e.sourceSceneId,e);let c=[],u=iF.es[iF.nG]?.style;for(let t of e){if(!t?.id)continue;let e=(t.text??"").trim();if(!e||s.has(t.id)||l3(t.id).some(e=>o.has(e))||l3(t.id).some(e=>i.has(e)))continue;let a=d.get(t.id),r=a?l6(a):null;if(!r){if(!t.audio?.elevenlabs_voiceover||!l8(t.timelineStart)||!l8(t.duration)||t.duration<=0)continue;r={start:t.timelineStart,duration:t.duration}}let n=(0,eV._z)(e,r.duration);c.push({id:`restored-cap-${t.id}`,sourceCaptionId:void 0,start:r.start,duration:r.duration,inOffset:0,outOffset:r.duration,fullDuration:r.duration,trackId:l,sceneId:t.id,captionText:e,captionWords:n,captionCues:n?(0,l4.R)(e,n,{punctuationPolicy:"creator"}):void 0,source:"auto",captionBox:{x:.06,y:.76,width:.88,height:.14},captionStyle:u?{fontSize:u.fontSize,fontFamily:u.fontFamily,fontWeight:u.fontWeight,color:u.color,backgroundColor:u.backgroundColor,textAlign:"center",outlineColor:u.outlineColor,outlineWidth:u.outlineWidth,animationPreset:u.animationPreset}:void 0,captionHighlightEnabled:!0,captionHighlightStyle:{color:"#fb923c",outlineColor:"#000000",outlineWidth:0,backgroundColor:"#fb923c",backgroundOpacity:0,backgroundPadding:4},captionDisplayMode:"phrase",captionDisplayWindowSize:1,alignmentProvider:void 0})}return c}(a.scenes,i,[...a.captionBlocks,...n],{markerPresent:s,hiddenCaptionBlockIds:a.hiddenCaptionBlockIds});if(0===c.length){d&&de("FACELESS_CAPTIONS_RESTORE_EMPTY_RERUN",{projectId:e.substring(0,8)});return}for(let e of c){let t=r.blocks.find(t=>t.sceneId===e.sceneId&&"scene"===t.type),n=(a.scenes??[]).find(t=>
106t.id===e.sceneId),i=l(dt({layers:[e.trackId],storeSceneTrackId:null!=t?Number(t.trackId??1):null,projectSceneTrackId:null!=n?Number(n.trackId??1):null,metaParentTrackId:null}),1)[0]??e.trackId;o(e.sceneId,[{...e,type:"caption",trackId:i}])}de("FACELESS_CAPTIONS_AUTO_RESTORED",{count:c.length,projectId:e.substring(0,8),damagedRerun:d}),(0,ey.trackEvent)("faceless_captions_restored",{project_id:e,restored_count:c.length,damaged_rerun:d});let u={...a,captionBlocks:[...a.captionBlocks,...c],captionsAutoRestoredAt:new Date().toISOString(),updatedAt:Date.now()};t.updateCoreProjectState?.(u),t.saveCurrentProject?.(u)},[a,o,l]),null};var dn=a(43173);function di(e){if(!e)return;let t=e.message;return"string"!=typeof t&&(t=t&&"object"==typeof t&&"message"in t?String(t.message||"Request failed"):"Request failed"),{...e,message:t}}async function ds(e,t){var a,r;let n=await (0,dn.ff)(`/projects/${e}/reddit-photo-short/import`,{method:"POST",body:JSON.stringify(t)},12e4);if(!n.success||n.error)return{...n,error:di(n.error)};let i=(r=a=n.data)&&"object"==typeof r&&"data"in r?a:{success:!0,data:a};return!1===i.success||i.error?{success:!1,data:null,error:di(i.error)||{status_code:500,message:i.message||"Failed to import Reddit photo short"},message:i.message,timing:n.timing,connectionInfo:n.connectionInfo}:{success:!0,data:i.data,message:i.message,timing:n.timing,connectionInfo:n.connectionInfo}}var dl=a(1007);function dd(...e){let t=new Map;for(let a of e)for(let e of a??[])t.set(e.id,e);return[...t.values()].map(e=>({id:e.id,type:e.type,trackId:e.trackId,start:e.start,duration:sd(e),sceneId:e.sourceSceneId}))}function dc(e,t){let a=Math.max(.25,t.duration),r=sc(e,"audio",t.start,a,t.preferredTrack??2);return e.push({id:t.id,type:"audio",trackId:r,start:t.start,duration:a}),r}var du=a(67705),dp=a(31774);function dm(e){return!Number.isFinite(e)||e<=0?288:Math.max(248,Math.min(328,Math.round(.36*e)))}var dh=a(83870),df=a.n(dh);let dg="inline-flex h-8 min-w-0 items-center gap-1.5 rounded-full border px-3 text-[12px] font-semibold tracking-[-0.01em] transition-[background-color,border-color,color] duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400/60";function dx({mediaLabel:e,mediaOpen:t,showMedia:a,studioLabel:n,studioOpen:i,showStudio:s,studioBusy:o=!1,studioNeedsAttention:l=!1,onToggleMedia:d,onToggleStudio:c}){return(0,r.jsxs)("div",{"data-testid":"mobile-editor-subheader","data-mobile-editor-subheader":!0,className:"absolute inset-x-0 top-0 z-[100] flex items-center justify-between gap-2 bg-[#02060d] px-2",style:{height:40},children:[a?(0,r.jsxs)("button",{type:"button",className:`${dg} max-w-[48%] ${t?"border-slate-400/80 bg-slate-900 text-white":"border-slate-600/80 bg-slate-950 text-slate-100 hover:border-slate-400 hover:bg-slate-900"}`,onClick:d,"aria-label":t?`Close ${e}`:`Open ${e}`,"aria-expanded":t,"data-testid":"mobile-media-bin-chip",children:[(0,r.jsx)("span",{className:"truncate",children:e}),t?(0,r.jsx)(B.A,{"aria-hidden":!0,className:"h-3.5 w-3.5 shrink-0 opacity-75"}):(0,r.jsx)(W.A,{"aria-hidden":!0,className:"h-3.5 w-3.5 shrink-0 opacity-75"})]}):(0,r.jsx)("span",{}),s?(0,r.jsxs)("button",{type:"button",className:`${dg} relative isolate max-w-[52%] overflow-hidden ${l?"border-amber-300/60 bg-slate-900 text-amber-50":i?"border-sky-300/60 bg-slate-900 text-white":"border-sky-400/45 bg-slate-950 text-sky-100 hover:border-sky-300/65 hover:bg-slate-900 hover:text-white"}`,onClick:c,"aria-label":i?`Close ${n}`:l?"Storyboard ready - open Video Studio":`Open ${n}`,"aria-expanded":i,"data-testid":"mobile-ai-panel-chip",children:[!i&&(0,r.jsx)("span",{"aria-hidden":!0,"data-testid":"mobile-video-studio-shimmer",className:df().studioShimmer}),o?(0,r.jsx)("span",{"aria-hidden":!0,className:"relative z-[1] h-2 w-2 shrink-0 animate-pulse rounded-full bg-sky-300 shadow-[0_0_8px_rgba(125,211,252,0.9)] motion-reduce:animate-none"}):null,(0,r.jsx)("span",{className:"relative z-[1] truncate",children:i?"Editor":l?"Finish video":n}),i?(0,r.jsx)(W.A,{"aria-hidden":!0,className:"relative z-[1] h-3.5 w-3.5 shrink-0 opacity-75"}
106):(0,r.jsx)(B.A,{"aria-hidden":!0,className:"relative z-[1] h-3.5 w-3.5 shrink-0 opacity-75"})]}):null]})}let db="project-export-mode",dy="[SCENE-FLOW]",dv=(e,t)=>{let a=new Date().toISOString().split("T")[1].slice(0,12);console.log(`${dy} [${a}] ${e}`,t?JSON.stringify(t,null,0):"")},dw=(e,t)=>{let a=new Date().toISOString().split("T")[1].slice(0,12);console.error(`${dy} [${a}] â ${e}`,t?JSON.stringify(t,null,0):"")},dk="ai-editor-rail-width-v2",dS="reddit-legal-ack-session-v1";function dj(e){return e<=900||"desktop"!==(0,eJ.fP)().deviceClass}function dI({projectId:e,preloadedProject:t,initialProjectName:p,templatePreset:m,intakeMode:h,launchMode:f,studioMode:g}){let w=m===dl._b&&"reddit-urls"===h,[k]=(0,i.useState)(()=>{if(g)return g;if(!t)return;let e=!!t.facelessStoryboard,a=(t.scenes?.length??0)===0&&(t.audio?.length??0)===0;return e||a?"faceless":void 0}),{isDevMode:S}=(0,nc.u)(),{currentProject:j,addScene:I,setCurrentProject:N,error:C,saveCurrentProject:M,isLoading:_,createProject:A,loadProject:E,updateCoreProjectState:T,uiMode:$,setMode:P,setProjectAspectRatio:D,toggleLetterboxing:R,refreshProjects:z,addVoiceover:L,getLatestProjectState:F}=(0,s.By)(),{entitlements:O,isLoading:B}=(0,ay.G)(),W=!B&&O.isAdmin,[U,K]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=()=>{if(!W)return void K(!1);try{K("true"===localStorage.getItem("fc_record_mode"))}catch{K(!1)}};e();let t=e=>{"fc_record_mode"===e.key&&K(W&&"true"===e.newValue)},a=t=>{"boolean"==typeof t.detail?.enabled?K(W&&t.detail.enabled):e()};return window.addEventListener("storage",t),window.addEventListener("fc-record-mode-change",a),()=>{window.removeEventListener("storage",t),window.removeEventListener("fc-record-mode-change",a)}},[W]);let[V,q]=(0,i.useState)(()=>{try{let e=localStorage.getItem("reddit-download-source");return"page"===e||"media"===e?e:"media"}catch{return"media"}}),[Y,G]=(0,i.useState)(!1),[X,J]=(0,i.useState)(!1),[Z,Q]=(0,i.useState)(null),[ee,et]=(0,i.useState)(null),[ea,er]=(0,i.useState)(""),[en,ei]=(0,i.useState)([]),[es,eo]=(0,i.useState)(null),[el,ed]=(0,i.useState)(!1),[ec,eu]=(0,i.useState)(w),[ep,em]=(0,i.useState)(!1),[eh,ek]=(0,i.useState)(!1),[eS,ej]=(0,i.useState)(null),[eI,eN]=(0,i.useState)(null),[eC,eM]=(0,i.useState)(null),[,e_]=(0,i.useState)(null),[eA,eE]=(0,i.useState)(t||null),[e$,eP]=(0,i.useState)([]),[eD,eR]=(0,i.useState)(0);(0,i.useEffect)(()=>{if(0===e$.length)return;let e=e=>{e.preventDefault()};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[e$.length]),(0,i.useEffect)(()=>{let e;if(0===e$.length)return;let t=e=>{(0,ey.trackEvent)("media_import_abandoned",{project_id:(eA||j)?.id,file_count:e$.length,files_done:eD,files_in_flight:Math.max(0,e$.length-eD),trigger:e},{transport:"sendBeacon"})},a=()=>t("pagehide");return window.addEventListener("pagehide",a),"desktop"!==(0,eJ.fP)().deviceClass&&(e=()=>{"hidden"===document.visibilityState&&t("visibility_hidden")},document.addEventListener("visibilitychange",e)),()=>{window.removeEventListener("pagehide",a),e&&document.removeEventListener("visibilitychange",e)}},[e$.length,eD]);let[eL,eF]=(0,i.useState)(null),[eO,eB]=(0,i.useState)(!0),[,eU]=(0,i.useState)(null),[,eK]=(0,i.useState)({isChecked:!1,isAvailable:!1}),[eV,eq]=(0,i.useState)(!1);(0,l.C)("ProjectWorkspace");let eY=(0,o.vr)(),eG=(0,i.useMemo)(()=>{let e=new URLSearchParams(window.location.search);return{hideMediaBin:e.has("hideMediaBin"),hideTimeline:e.has("hideTimeline"),hidePreview:e.has("hidePreview")}},[]),e1=S||!0===window.__PLAYWRIGHT_TEST_MODE__,[e5,e2]=(0,i.useState)(()=>dj(window.innerWidth)?dm(window.innerHeight):200),e3=(0,i.useRef)(null),[e8,e6]=(0,i.useState)(()=>{let e="faceless"===k?Math.min(600,Math.max(440,Math.floor(.45*window.innerWidth))):440;try{let e=localStorage.getItem(dk),t=null===e?NaN:Number(e);if(!Number.isFinite(t)){let e=localStorage.getItem("ai-editor-rail-width"),a=null===e?NaN:Number(e);Number.isFinite(a)&&440!==a&&(t=a)}if(Number.isFinite(t)){let e=Math.max(200,Math.floor(.5*window.innerWidth));return Math.min(900,e,Math.max(200,t))}}catch{}return e}),[e9,e7]=(0,i.useState)(()=>(function(e){if(e.textStory)return!0;
106if(e.compilation)return!1;if(e.compact)return!0;if(e.studioMode)return!1;try{return"1"===localStorage.getItem(n)}catch{return!1}})({textStory:!!t?.textStory?.ready,compilation:w,compact:dj(window.innerWidth),studioMode:k})),[te,tt]=(0,i.useState)(!1),[ta,tr]=(0,i.useState)(!1),tn=(0,i.useRef)({x:0,width:0}),ti=d.Wg.AI_EDITOR_ENABLED,[ts,to]=(0,i.useState)(()=>window.innerWidth),[tl,td]=(0,i.useState)(()=>window.innerHeight),[tc,tu]=(0,i.useState)(()=>dj(window.innerWidth)),[tp,tm]=(0,i.useState)(()=>"mobile"===(0,eJ.fP)().deviceClass),[th,tf]=(0,i.useState)(!1),tg=(0,ru.e)(e=>e.progress),tx=(0,ru.e)(e=>e.pendingSceneRun),tb=ti?e9?44:e8:0,ty=tc?0:tb,tv=tc&&ts>0?Math.min(ty,Math.max(280,Math.floor(.88*ts))):ty,tw=tc&&"faceless"===k,tk=tw&&!e9,tS=tp&&"faceless"===k,tj=tc?dm(tl):0,tI=function(e,t,a){if(a){let a,r={width:Math.max(0,e>=700?Math.round(.75*e):e-32),top:a=Math.max(101,Math.round(.15*t)),height:`calc(100dvh - ${a+48}px)`};return{...r,width:`${r.width}px`}}let r=93;return{width:"min(640px, calc(100dvw - 32px))",top:r,height:`calc(100dvh - ${r+48}px)`}}
106(ts,tl,tp),tN=tl-85-e5-8,tC=0===tl||tN>=320,tM=tC?0===tl?76:Math.max(0,Math.min(76,tN-320)):0,t_=Math.max(93,85+(tM<48?0:tM)),tA=tw?tI.width:"calc(100vw - 16px)",tE=tw?tI.height:`calc(100dvh - ${t_}px - ${e5+8}px)`,tT=(0,i.useRef)(tc),t$=(0,i.useRef)(!!tg),tP=!tc&&ta&&!e9,{containerRef:tD,isOverTimeline:tR}=function({enabled:e}){let t=(0,i.useRef)(null),[a,r]=(0,i.useState)(!1),n=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let i=()=>{null!==n.current&&(window.cancelAnimationFrame(n.current),n.current=null)};if(!e){i(),r(!1);return}let s=e=>{let s=t.current;if(!(s&&s.contains(e.target))){i(),r(!1);return}a||(i(),n.current=window.requestAnimationFrame(()=>{n.current=null;let e=t.current;r(!!(e&&Array.from(e.querySelectorAll("[data-ai-rail-scroll-viewport]")).some(e=>e.clientHeight>0&&e.scrollHeight>e.clientHeight+1)))}))};return document.addEventListener("mousedown",s,!0),()=>{document.removeEventListener("mousedown",s,!0),i()}},[e,a]),{containerRef:t,isOverTimeline:a}}({enabled:!tc&&ti&&!e9&&!tP});(0,i.useEffect)(()=>{if(!tk)return;let e=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=e}},[tk]),(0,i.useEffect)(()=>{let e=!!tg,t=e&&!t$.current;t$.current=e,t&&tS&&(tf(!1),e7(!0))},[tg,tS]),(0,i.useEffect)(()=>{if(!tP)return;let e=e=>{"Escape"===e.key&&tr(!1)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tP]),(0,i.useEffect)(()=>{let e=window.$crisp;e&&"function"==typeof e.push&&e.push(["do","chat:hide"])},[]),(0,i.useEffect)(()=>()=>{let e=window.$crisp;e&&"function"==typeof e.push&&e.push(["do","chat:show"])},[]);let tz=(0,y.zC)(e=>e.syncFromScenes),tL=(0,y.zC)(e=>e.isPlaying),tF=(0,y.zC)(e=>e.setIsPlaying),tO=(0,i.useRef)(!1),tB=(0,i.useRef)(0),tW=(0,i.useRef)(`workspace-${Math.random().toString(36).substring(2,7)}`),tU=(0,i.useRef)(!1),tK=(0,i.useRef)(!1),tV=(0,i.useRef)(null),tH="string"==typeof C?C:C?.message,[tq,tY]=(0,i.useState)(null);(0,i.useEffect)(()=>{try{localStorage.setItem("reddit-download-source",V)}catch{}},[V]),(0,i.useEffect)(()=>{try{"1"===sessionStorage.getItem(dS)&&em(!0)}catch{}},[]),(0,i.useEffect)(()=>{let e=()=>{let e=window.innerWidth,t=dj(e);to(e),td(window.innerHeight),tu(t),tm("mobile"===(0,eJ.fP)().deviceClass),t||tf(!1)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),(0,i.useEffect)(()=>{tc&&!tT.current&&(e7(!w),tf(!1)),tT.current=tc},[tc,w]),(0,i.useEffect)(()=>{let e=e3.current;if(!e)return;let t=()=>{let t=Math.round(e.getBoundingClientRect().height);e2(e=>e===t?e:t)};t();let a=new ResizeObserver(t);return a.observe(e),()=>a.disconnect()},[tk,tS,tC,eV,tj]),(0,i.useEffect)(()=>{let e=!0,t=async()=>{if("visible"!==document.visibilityState)return;let t=await (0,dn.Bp)();e&&eK({isChecked:!0,isAvailable:t.success})};t();let a=setInterval(t,3e5),r=()=>{"visible"===document.visibilityState&&t()};return document.addEventListener("visibilitychange",r),()=>{e=!1,clearInterval(a),document.removeEventListener("visibilitychange",r)}},[]),(0,i.useEffect)(()=>{let e=e=>{let{active:t}=e.detail||{},a=!!t;eq(a),a&&tF(!1)};return window.addEventListener(db,e),()=>{window.removeEventListener(db,e)}},[tL,tF]),(0,i.useEffect)(()=>{},[]),(0,i.useEffect)(()=>{tB.current+=1,console.log(`[${tW.current}] ProjectWorkspace mounted (count: ${tB.current})`,{projectId:e,preloadedProject:t?t.id:null,localProject:eA?eA.id:null,currentProject:j?j.id:null}),"organization"===$&&P("voice-enabled");let a=setTimeout(()=>{eO&&(console.warn(`[${tW.current}] Safety timeout reached. Forcing loading state to false.`),eB(!1),eA||j||eU("Failed to load project after timeout"))},15e3);return tK.current?(console.log(`[${tW.current}] Project is already loading, skipping initialization`),()=>{clearTimeout(a)}):j&&(!e||j.id===e)?(console.log(`[${tW.current}] Current project in context matches needed project:`,j.id),eA!==j&&eE(j),eO&&eB(!1),()=>{clearTimeout(a)}):t&&(!e||t.id===e)?(console.log(`[${tW.current}] Using preloaded project:`,t.id),eA?.id!==t.id&&eE(t),eO&&eB(!1),j&&j.id===t.id||(console.log(`[${tW.current}] Setting context current project to match preloaded:`,t.id),N(t.id)),()=>{clearTimeout(a)}
106):(e&&!tO.current&&E?(tO.current=!0,tK.current=!0,console.log(`[${tW.current}] Loading project via API:`,e),eB(!0),E(e).then(t=>{if(console.log(`[${tW.current}] Successfully loaded project ${e}`),tK.current=!1,!t)throw Error(`Project ${e} failed to load`);eE(t),eB(!1),j&&j.id===e||(console.log(`[${tW.current}] Setting current project ID:`,e),N(e))}).catch(t=>{console.error(`[${tW.current}] Failed to load project ${e}:`,t),eU(`Failed to load project: ${t instanceof Error?t.message:"Unknown error"}`),eB(!1),tK.current=!1})):e||t||j||tU.current||!p?e||t||j||tU.current||(console.log(`[${tW.current}] No project info, creating new project`),tU.current=!0,eB(!1)):(console.log(`[${tW.current}] Creating new project with name: ${p}`),tU.current=!0,A?(eB(!0),A(p,"").then(e=>{if(!e)throw Error("Failed to create project");console.log(`[${tW.current}] Successfully created new project:`,e.id),eE(e),eB(!1)}).catch(e=>{console.error(`[${tW.current}] Failed to create project:`,e),eU(`Failed to create project: ${e instanceof Error?e.message:"Unknown error"}`),eB(!1),tU.current=!1})):(console.error(`[${tW.current}] Cannot create project: createProject function not available`),eU("Cannot create project: app not initialized properly"),eB(!1))),()=>{clearTimeout(a)})},[e,t,j,E,N,$,P,eA,eO,p,A]);let tG=eA||j,tX=(0,i.useCallback)(e=>{let t=F(),a=e0(t,tG?.id,e);a!==t&&T(a),eE(t=>e0(t,tG?.id,e))},[tG?.id,F,T]);!function({projectId:e,isCloudProject:t,scenes:r,setUploadingFiles:n,setUploadDoneCount:s,onSceneUploaded:o}){let l=(0,i.useRef)(new Set),d=(0,i.useRef)(!0);(0,i.useEffect)(()=>(d.current=!0,()=>{d.current=!1}),[]),(0,i.useEffect)(()=>{e&&t&&Array.isArray(r)&&(l.current.has(e)||(l.current.add(e),(async()=>{let t=[];try{let{listRecoverableMediaForProject:n}=await a.e(6886).then(a.bind(a,94505)),i=await n(e);if(0===i.length)return;let s=new Map(i.map(e=>[e.storageKey,e])),o=Date.now();t=r.flatMap(e=>{if(e?.media?.status!=="uploading")return[];let t=e.media?.storageKey,a=t?s.get(t):void 0;if(!a)return[];let r="number"==typeof e.createdAt?e.createdAt:0;return r&&o-r<12e4?[]:[{sceneId:e.id,entry:a,isVideo:(e.media?.type??"video")==="video"}]})}catch{return}if(0===t.length)return;(0,ey.trackEvent)("media_import_resume_started",{project_id:e,scene_count:t.length,total_bytes:t.reduce((e,t)=>e+t.entry.size,0)}),Promise.resolve().then(a.bind(a,66609)).then(({toast:e})=>e.info(1===t.length?"Finishing an interrupted upload":`Finishing ${t.length} interrupted uploads`,{description:"Your files were kept on this device. Uploading them to the cloud now, no need to import them again.",duration:8e3})).catch(()=>{}),d.current&&(n(t.map(e=>({name:eQ(e.entry.storageKey),progress:0}))),s(0));let i=0;for(let r of t){let t=t=>{(0,ey.trackEvent)("media_import_resume_scene_failed",{project_id:e,scene_id:r.sceneId,stage:t})};try{let n=await (0,eZ.Z8)(e,r.sceneId);if(!n.success||!n.data){t("resume_session");continue}let s=n.data,l=new File([r.entry.blob],eQ(s.object_key),{type:r.entry.mimeType||"application/octet-stream"}),c=await (0,eZ.uploadSceneFile)(e,s,l);if(!c.success){t("upload");continue}let u=c.durationSeconds;if(!u&&r.isVideo)try{let{extractVideoMetadata:e}=await a.e(2246).then(a.bind(a,82246)),t=await e(l);t?.duration&&Number.isFinite(t.duration)&&t.duration>0&&(u=t.duration)}catch{}let p=await (0,eZ.finalizeUpload)(s.finalize_url,{durationSeconds:u});if(!p.success||!p.data?.success){t("finalize");continue}i+=1,d.current&&o(r.sceneId)}catch{t("unexpected")}finally{d.current&&s(e=>e+1)}}(0,ey.trackEvent)("media_import_resume_completed",{project_id:e,succeeded:i,failed:t.length-i}),d.current&&(n([]),s(0)),Promise.resolve().then(a.bind(a,66609)).then(({toast:e})=>{i===t.length?e.success(1===i?"Interrupted upload finished":`${i} interrupted uploads finished`):e.warning(`${i} of ${t.length} interrupted uploads finished`,{description:"The rest will be retried next time you open this project. Keep this page open to give uploads time to finish.",duration:1e4})}).catch(()=>{})})()))},[e,t,r,n,s,o])}({projectId:tG?.id,isCloudProject:!!(tG&&"local"!==tG.mode),scenes:tG?.sce
106nes,setUploadingFiles:eP,setUploadDoneCount:eR,onSceneUploaded:tX}),(0,l.X)("ResizableMasterPreview",{hidePreview:eG.hidePreview,isProjectExportMode:eV,isContextLoading:_,localLoading:eO,hasEffectiveProject:!!tG,effectiveProjectId:tG?.id??null,uiMode:$});let tJ=m===dl._b&&"reddit-urls"===h,tZ=tJ?dl._b:void 0,tQ=(0,i.useMemo)(()=>tJ?(0,dl.mR)(tG?.template):void 0,[tG?.template,tJ]);(0,i.useEffect)(()=>{if(!tJ||!tG||!tQ)return;let e=tG.scenes.map(e=>{let t=(0,dl.dT)({title:e.title,sourceText:e.script?.sourceText||e.text||e.title||"",existingScript:e.script,templateSettings:tQ}),a=t.voiceoverText||t.rewrittenText||t.sourceText||e.text;return JSON.stringify(e.script??null)===JSON.stringify(t)&&e.text===a?e:{...e,text:a,script:t,updatedAt:Date.now()}}),t=e.some((e,t)=>e!==tG.scenes[t]),a=JSON.stringify(tG.template??null)!==JSON.stringify(tQ),r=null==tG.aiWorkspaceTab;if(!t&&!a&&!r)return;let n={...tG,scenes:e,template:tQ,aiWorkspaceTab:tG.aiWorkspaceTab??"generate",updatedAt:Date.now()};eE(n),T(n),M(n)},[tG,tQ,tJ,M,T]),(0,i.useEffect)(()=>{if(!tJ||!tG?.id||"9:16"===tG.aspectRatio&&!1===tG.showLetterboxing)return;let e=!1;return(async()=>{try{"9:16"!==tG.aspectRatio&&D&&await D("9:16"),!e&&!1!==tG.showLetterboxing&&R&&await R(!1)}catch(e){console.error("[ProjectWorkspace] Failed to apply guided project defaults:",e)}})(),()=>{e=!0}},[tG?.id,tG?.aspectRatio,tG?.showLetterboxing,tJ,D,R]),(0,i.useEffect)(()=>{tJ&&(eu(!1),e7(!1),tc&&tf(!1))},[tG?.id,tc,tJ]),(0,i.useEffect)(()=>{tJ&&e9&&e7(!1)},[e9,tJ]),(0,i.useEffect)(()=>{let e=()=>{tf(!1),eu(!1),e7(!1)};return window.addEventListener("faceless:open-studio-panel",e),()=>window.removeEventListener("faceless:open-studio-panel",e)},[]);let{showPermissionModal:t0,handlesNeedingPermission:t1,dismissModal:t5,onPermissionsRestored:t2,recheckPermissions:t4}=function(e){let[t,a]=(0,i.useState)(!1),[r,n]=(0,i.useState)([]),[s,o]=(0,i.useState)([]),[l,d]=(0,i.useState)(!1),[c,p]=(0,i.useState)(!1),m=(0,i.useCallback)(async()=>{if(!e||"local"!==e.mode){n([]),o([]),d(!1);return}let t=function(e){if(!e||"local"!==e.mode)return[];let t=[],a=new Set;for(let r of e.scenes||[]){let e=r.media?.assetRef;e?.type==="handle"&&e.handleId&&!a.has(e.handleId)&&(a.add(e.handleId),t.push({handleId:e.handleId,filename:e.filename,sceneId:r.id}))}return t}(e);if(0===t.length){n([]),o([]),d(!1);return}a(!0),console.log(`[useLocalAssetPermissions] Checking ${t.length} handles for project ${e.id}`);try{let a=await (0,u.OP)(e.id);o(a);let r=t.filter(e=>{let t=a.find(t=>t.handleId===e.handleId);return!t||"granted"!==t.permission});n(r),r.length>0&&(console.log(`[useLocalAssetPermissions] ${r.length} handles need permission`),d(!0))}catch(e){console.error("[useLocalAssetPermissions] Error checking permissions:",e)}finally{a(!1),p(!0)}},[e]);(0,i.useEffect)(()=>{e?.id&&"local"===e.mode&&!c?m():e&&"local"===e.mode||(n([]),o([]),d(!1),p(!1))},[e?.id,e?.mode,c,m]);let h=(0,i.useCallback)(()=>{d(!1)},[]),f=(0,i.useCallback)(e=>{o(e);let t=r.filter(t=>{let a=e.find(e=>e.handleId===t.handleId);return!a||"granted"!==a.permission});n(t),d(!1),console.log(`[useLocalAssetPermissions] Permissions restored. ${t.length} still need access.`)},[r]);return{isChecking:t,handlesNeedingPermission:r,permissionResults:s,showPermissionModal:l,dismissModal:h,onPermissionsRestored:f,recheckPermissions:(0,i.useCallback)(()=>{p(!1)},[])}}(tG),t3=(0,i.useCallback)(async e=>{if((t2(e),tG&&"local"===tG.mode)&&e.some(e=>"granted"===e.permission))try{let e=JSON.parse(JSON.stringify(tG)),{project:t}=await (0,u.ZS)(e),a=new Map,r=await Promise.all((t.scenes||[]).map(async e=>{let r=e.media?.assetRef;if(r?.type!=="handle"||!r.handleId||!e.media)return e;let n=a.get(r.handleId);if(n)return{...e,media:{...e.media,url:n.blobUrl,assetRef:n.assetRef}};try{let n=await (0,u.UY)(r.handleId);if(!n)return e;let i=await n.handle.getFile(),s=await (0,u.D_)(t.id,i),o=URL.createObjectURL(i),l={type:"blob",blobId:s.id,filename:s.filename,size:s.size,lastModified:s.lastModified,mimeType:s.mimeType};return a.set(r.handleId,{assetRef:l,blobUrl:o}),{...e,media:{...e.media,url:o,assetRef:l}}}catch(t){return console.warn(`[ProjectWorkspace] Failed migrating handle ${r.handleId} to blob asset:`,t),e}})),n={...t,scenes:r,updatedAt:Date.now()};T(n),eE(n),a.size>0&&(await u.Kn.saveProject(n),t4())}catch(e){console.error("[ProjectWorkspace] Failed to rehydrate local media after permission restore:",e)}},[tG,t2,t4,T]);(0,i.useEffect)(()=>{tG?.scenes&&tz(tG.scenes)},[tG?.scenes,tz]),(0,i.useEffect)(()=>
106{if(ti)try{localStorage.setItem(dk,String(e8)),localStorage.setItem(n,e9?"1":"0")}catch{}},[ti,e8,e9]),(0,i.useEffect)(()=>{if(!ti)return;let e=document.querySelector("[data-ai-rail-container]"),t=e?.getBoundingClientRect();t&&(window.dispatchEvent(new CustomEvent("ai-rail-left-edge-resize",{detail:{leftEdge:Math.round(t.left)}})),window.dispatchEvent(new Event("ai-rail-resize-end"))),window.dispatchEvent(new Event("resize"))},[ti,ty]),(0,i.useEffect)(()=>{if(!te||e9)return;let e=e=>{let t=tn.current.x-e.clientX,a=Math.min(900,Math.max(200,tn.current.width+t));e6(a);let r=window.innerWidth-a;window.dispatchEvent(new CustomEvent("ai-rail-left-edge-resize",{detail:{leftEdge:r}}))},t=()=>{tt(!1),window.dispatchEvent(new Event("ai-rail-resize-end"))};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",t),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",t)}},[200,e9,te]),(0,i.useEffect)(()=>{let e=e=>{var t;" "===e.key&&(t=document.activeElement,t?.closest('button, input, select, textarea, [contenteditable="true"], [contenteditable=""], [contenteditable="plaintext-only"], [role="button"], [role="textbox"], [role="slider"], dialog, [role="dialog"], [aria-modal="true"]')||(e.preventDefault(),e.stopPropagation(),tF(!tL),console.log(`[Keyboard] Spacebar pressed - toggling play/pause: ${!tL}`)))};return window.addEventListener("keydown",e,{capture:!0}),()=>{window.removeEventListener("keydown",e,{capture:!0})}},[tL,tF]),(0,i.useEffect)(()=>{e&&(!j||j.id!==e)&&E&&N&&(eA&&eA.id===e?(console.log(`[Sync Effect] Project ${e}
106 found in local state, setting as current.`),N(e)):(console.log(`[Sync Effect] Project ${e} not current/local, attempting load.`),tK.current||(tK.current=!0,E(e).then(()=>{console.log(`[Sync Effect] Successfully loaded ${e}`)}).catch(t=>{console.error(`[Sync Effect] Error loading project ${e}: ${t}`),eU(`Failed sync load: ${t instanceof Error?t.message:"Unknown error"}`)}).finally(()=>{tK.current=!1}))))},[e,j,E,N,eA,eU]),(0,i.useEffect)(()=>{j&&eE(e=>e===j||e&&e.id===j.id&&e.scenes===j.scenes&&e.audio===j.audio&&e.voiceovers===j.voiceovers&&e.title===j.title&&e.updatedAt===j.updatedAt?e:(console.log(`Current project updated in context, syncing to local state: ${j.id} (${j.scenes.length} scenes)`),j))},[j]);let t8=(0,i.useCallback)(async()=>{if(tG&&(!j||j.id!==tG.id)&&N)if(console.log(`Synchronizing project state before adding scene: ${tG.id}`),e&&E&&(!j||j.id!==e)){console.log(`Loading project ${e} before adding scene`);try{await E(e),console.log(`Successfully loaded project ${e} for adding scene`)}catch(t){return console.error(`Failed to load project ${e} for adding scene:`,t),{projectId:null,error:`Failed to load project: ${t instanceof Error?t.message:"Unknown error"}`}}}else N(tG.id),await new Promise(e=>setTimeout(e,100));let t=tG?.id||j?.id;return t?{projectId:t,error:null}:{projectId:null,error:"No active project to add scene to"}},[tG,j,N,e,E]),t6=(0,i.useCallback)(async e=>{if(!I)return;let t=e??ea;"string"==typeof e&&er(e);let a=Array.from(new Set(t.split(/\r?\n/).map(e=>e.trim()).filter(Boolean))),r=e=>{try{let t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}},n=a.filter(e=>r(e)),i=a.filter(e=>!r(e));if(0===n.length)return void ei(["Paste one or more valid URLs, one per line."]);ed(!0),ei(i.map(e=>`Skipped invalid URL: ${e}`)),eo({completed:0,total:n.length,activeUrl:n[0]||null}),e_(null),Q(null),et(null);let{projectId:s,error:o}=await t8();if(!s){ei(e=>[o||"No active project to add scene to.",...e]),ed(!1),eo(null);return}let l=i.map(e=>`Skipped invalid URL: ${e}`),d=[];try{for(let e=0;e<n.length;e+=1){let t=n[e];eo({completed:e,total:n.length,activeUrl:t});try{let e=/(?:reddit\.com|redd\.it)/i.test(t),a=tZ?{applyTemplatePreset:tZ,templateSettings:tQ}:{},r=e?{...a,redditImportMode:"guided-url-batch"}:a;await I(t,Object.keys(r).length>0?r:void 0)}catch(e){d.push(t),l.push(`${t}: ${e instanceof Error?e.message:"Failed to import scene"}`)}e<n.length-1&&await new Promise(e=>setTimeout(e,250))}eo({completed:n.length,total:n.length,activeUrl:null});try{let e=await E(s);e&&eE(e)}catch(e){console.error("[ProjectWorkspace] Failed to refresh project after guided import:",e)}let e=n.length-d.length;e>0&&et(`Imported ${e} ${1===e?"scene":"scenes"} from URL${1===e?"":"s"}.`),ei(l),er(d.join("\n"))}finally{ed(!1)}},[I,t8,tZ,tQ,ea,E]),t9=(0,i.useCallback)(async e=>{let t=e.trim();if(!t)return void ei(["Paste one or more valid URLs, one per line."]);if(er(t),ei([]),t.split(/\r?\n/).map(e=>e.trim()).some(e=>/(?:reddit\.com|redd\.it)/i.test(e))&&!ep){ej("composer"),eN(null),eM(t),ek(!0);return}await t6(t)},[ep,t6]),t7=(0,i.useCallback)(e=>{"guided"===e?eu(e=>{let t=!e;return t&&e7(!0),t}):(Q(null),et(null),G(!0))},[]),ae=(0,i.useCallback)(async e=>{if(!tG?.id)return void Q("No active project is available for import.");if("local"===tG.mode)return void Q("Reddit photo short import is only available for cloud projects.");J(!0),Q(null),et(null),q(e.download_source_override||"media");try{let t=tQ?.voiceoverSettings,a=t?.mode==="specific"?t.voiceId:t?.mode==="random-free"?"random-free":void 0,r=await ds(tG.id,{...e,voice_id:e.voice_id||a});if(!r.success||r.error||!r.data)throw Error("string"==typeof r.error?.message?r.error.message:"Failed to import Reddit photo short");let n=E?await E(tG.id):null;n&&(eE(n),T(n)),z&&await z();let i=r.data,s=[`Imported ${i.added_scene_count} scenes from r/${i.subreddit}`];i.added_audio_count>0&&s.push(`${i.added_audio_count} voiceovers`),i.added_caption_count>0&&s.push(`${i.added_caption_count} captions`),i.skipped_posts.length>0&&s.push(`${i.skipped_posts.length} skipped`),i.warnings.length>0&&s.push(`${i.warnings.length} warnings`),et(s.join(" ⢠")),G(!1)}catch(e){Q(e instanceof Error?e.message:"Failed to import Reddit photo short")}finally{J(!1)}},[tG,tQ,E,z,T]),at=(0,i.useCallback)(()=>{try{sessionStorage.setItem(dS,"1")}catch{}try{localStorage.setItem("reddit-legal-ack-v1",JSON.stringify({accepted:!0,acceptedAt:Date.now(),version:1}))}catch{}em(!0),ek(!1),ej(null),eN(null),eM(null),"guided"===eS?t6():"composer"===eS&&eC?t6(eC):"batch"===eS&&eI&&ae(eI)},[eC,eI,eS,t6,ae]),aa=(0,i.useCallback)(async e=>{if(!ep){ej("batch"),eN(e),ek(!0);return}await ae(e)},[ep,ae]),ar=()=>`temp-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,an=(0,i.useCallback)(async e=>{if(!tG?.id||"local"!==tG.mode)return void(0,ey.trackEvent)("local_file_import_timeline_apply_failed",{reason:"invalid_project_state",importedCount:e.length,hasProject:!!tG?.id,projectMode:tG?.mode??null});console.log(`[ProjectWorkspace] Imported ${e.length} files for local project`);let t=tG.scenes?.length??0,a=tG.voiceovers?.length??0,r=e.filter(e=>(0,c.L8)(e.mimeType,e.filename)),n=e.filter(e=>!(0,c.L8)(e.mimeType,e.filename));(0,ey.trackEvent)("local_file_import_timeline_apply_started",{projectId:tG.id,importedCount:e.length,mediaCount:n.length,audioCount:r.length,sceneCountBefore:t,voiceoverCountBefore:a}),console.log(`[ProjectWorkspace] Separated: ${n.length} media, ${r.length} audio`);let i=[];for(let e of n){let t=ar(),a=e.mimeType.startsWith("video/")?"video":"image",{metadata:r,blobUrl:n}=e,s=r.duration??("image"===a?5:10),o=r.width,l=r.height,d={id:t,url:`local://${e.filename}`,text:e.filename,media:{type:a,url:n,assetRef:e.assetRef,width:o,height:l,duration:s,trim:{start:0,end:s}},source:{platform:"local",author:"",subreddit:""},createdAt:Date.now(),isLoading:!1};i.push(d),console.log(`[ProjectWorkspace] Created scene for ${e.filename}:`,{handleId:e.handleId,duration:s,width:o,height:l,blobUrl:n.substring(0,50)})}let s=[],o=dd(tG.audio,tG.voiceovers);for(let e of r){let{metadata:t,blobUrl:a}=e,r=t.duration??10,n=`audio-${(0,v.generateId)()}`,i=dc(o,{id:n,start:0,duration:r}),l={id:n,type:"audio",url:a,assetRef:e.assetRef,start:0,duration:r,trackId:i,inOffset:0,outOffset:r,volume:1,text:e.filename,sourceSce
106neId:void 0,status:"ready",generatedAt:Date.now(),createdAt:Date.now(),updatedAt:Date.now()};s.push(l),console.log(`[ProjectWorkspace] Created audio block for ${e.filename}:`,{handleId:e.handleId,duration:r,blobUrl:a.substring(0,50)})}let l={...tG,scenes:[...tG.scenes||[],...i],voiceovers:[...tG.voiceovers||[],...s],updatedAt:Date.now()};try{T(l),eE(l),await u.Kn.saveProject(l),(0,ey.trackEvent)("local_file_import_timeline_apply_succeeded",{projectId:tG.id,importedCount:e.length,mediaCount:n.length,audioCount:r.length,scenesAdded:i.length,voiceoversAdded:s.length,sceneCountBefore:t,sceneCountAfter:l.scenes.length,voiceoverCountBefore:a,voiceoverCountAfter:l.voiceovers?.length??0,videoSceneCount:i.filter(e=>e.media?.type==="video").length,imageSceneCount:i.filter(e=>e.media?.type==="image").length,fallbackDurationCount:n.filter(e=>"number"!=typeof e.metadata.duration).length,missingDimensionCount:n.filter(e=>"number"!=typeof e.metadata.width||"number"!=typeof e.metadata.height).length})}catch(t){throw(0,ey.trackEvent)("local_file_import_timeline_apply_failed",{projectId:tG.id,reason:"save_or_state_update_exception",importedCount:e.length,mediaCount:n.length,audioCount:r.length,scenesAdded:i.length,voiceoversAdded:s.length,errorName:t instanceof Error?t.name:"UnknownError",errorMessage:t instanceof Error?t.message.slice(0,240):String(t)}),t}},[tG,T]),ai=(0,i.useCallback)(async(e,t=!1)=>{if(!tG?.id||"local"!==tG.mode)return{successCount:0,failedCount:e.length};console.log(`[ProjectWorkspace] Dropped ${e.length} files for local project (audioOnly=${t})`);let a=[],r=[],n=dd(tG.audio,tG.voiceovers),i=0;for(let t of(eF(null),e))try{let e,s=(0,c.L8)(t.type,t.name),o=t.type.startsWith("video/");if(e=s?await (0,c.Z2)(t):o?await (0,c.sb)(t):await (0,c.ME)(t),o&&(0,c.ai)(e)){console.warn(`[ProjectWorkspace] Rejecting undecodable dropped video: ${t.name}`),i+=1;let a=(0,c.HT)();(0,ey.trackEvent)("local_file_import_file_undecodable",{projectId:tG.id,source:"drag_drop",mimeType:t.type||"unknown",sizeBytes:t.size,durationSeconds:e.duration,browser:a.browser,locale:a.locale,isSafari:a.isSafari});continue}let l=await (0,u.D_)(tG.id,t),d=URL.createObjectURL(t),p={type:"blob",blobId:l.id,filename:l.filename,size:l.size,lastModified:l.lastModified,mimeType:l.mimeType};if(s){let a=e.duration??10,i=`audio-${(0,v.generateId)()}`,s=dc(n,{id:i,start:0,duration:a}),o={id:i,type:"audio",url:d,assetRef:p,start:0,duration:a,trackId:s,inOffset:0,outOffset:a,volume:1,text:t.name,sourceSceneId:void 0,status:"ready",generatedAt:Date.now(),createdAt:Date.now(),updatedAt:Date.now()};r.push(o),console.log(`[ProjectWorkspace] Created audio block for dropped file: ${t.name}`)}else{let r=ar(),n=o?"video":"image",i=e.duration??("image"===n?5:10),s={id:r,url:`local://${t.name}`,text:t.name,media:{type:n,url:d,assetRef:p,width:e.width,height:e.height,duration:i,trim:{start:0,end:i}},source:{platform:"local",author:"",subreddit:""},createdAt:Date.now(),isLoading:!1};a.push(s),console.log(`[ProjectWorkspace] Created scene for dropped file: ${t.name}`)}}catch(e){console.error(`[ProjectWorkspace] Failed to process dropped file ${t.name}:`,e)}finally{eR(e=>e+1)}if(i>0&&eF((0,c.ND)(i,(0,c.HT)().locale)),a.length>0||r.length>0){let e={...tG,scenes:[...tG.scenes||[],...a],voiceovers:[...tG.voiceovers||[],...r],updatedAt:Date.now()};T(e),eE(e),M&&M()}let s=a.length+r.length;return{successCount:s,failedCount:e.length-s}},[tG,T,M]),as=async(e,t)=>{let r=t||ar(),n=r,i=null,s=()=>{eE(e=>e?{...e,scenes:e.scenes?.filter(e=>e.id!==r&&e.id!==n)||[]}:e)},o=async t=>{s();let{toast:r}=await Promise.resolve().then(a.bind(a,66609));r.error(`"${e.name}" needs a bigger upload limit`,{description:t,duration:12e3,action:{label:"Upgrade",onClick:()=>{window.location.href="/pricing?from=upload-limit"}}})},l=async(t,r)=>{if(s(),i&&tG?.id)try{let{deleteScene:e}=await Promise.resolve().then(a.bind(a,12304));await e(tG.id,i)}catch(e){console.warn("[handleVideoFileAdd] Server-side scene cleanup failed:",e)}eU(`Upload failed for "${e.name}" (${t})${r?`: ${r}`:""}`);let{toast:n}=await Promise.resolve().then(a.bind(a,66609));n.error(`Could not import "${e.name}"`,{description:r||"The upload failed. Please try again.",duration:1e4})};try{if(!tG?.id)return null;if("local"===tG.mode){console.warn('[handleVideoFileAdd] Use "Import Files" for local projects'),eU('Use the "Import Files" button for local projects to persist files across sessions.');let{toast:e}=await Promise.resolve().then(a.bind(a,66609));return e.error('Use the "Import Files" button for local projects',{description:"Files dropped here would not persist across sessions.",duration:1e4}),null}let{resolveUploadGate:t}=await a.e(4538).then(a.bind(a,84538)),s=t(e.size,{isPaidTier:B?null:O.features.canUseAiEditor,maxUploadFileBytes:O.maxUploadFileBytes,paidMaxUploadFileBytes:O.paidMaxUploadFileBytes});if(!s.allowed){if((0,ey.trackEvent)("media_import_file_too_large",{project_id:tG.id,file_size_bytes:e.size,file_type:e.type||"unknown",gate_reason:s.reason,cap_bytes:s.capBytes}),"free_cap"===s.reason)return await o(s.message),null;return await l("too large",s.message),null}let d=URL.createObjectURL(e),{trace:c,traceError:u}=await Promise.all([a.e(1453),a.e(2826),a.e(9304),a.e(4715),a.e(1464)]).then(a.bind(a,41464));c("dnd","start",{projectId:tG.id,name:e.name,size:e.size,type:e.type,sceneId:r}),c("dnd","local_preview_blob",{localUrl:d});let{createUploadSession:p,finalizeUpload:m,uploadSceneFile:h}=await Promise.resolve().then(a.bind(a,9756)),f=await p({project_id:tG.id,filename:e.name,size_bytes:e.size,content_type:e.type||"application/octet-stream"});if(!f.success||!f.data){if(u("dnd","preflight:error",f.error,{}),f.error?.error_code==="free_tier_limit_reached"&&f.error?.message)return await o(f.error.message),null;return await l("preparing upload",f.error?.message),null}let g=f.data;i=g.scene_id,n=g.scene_id,c("dnd","preflight:ok",{sceneId:g.scene_id,objectKey:g.object_key}),eE(e=>e?{...e,scenes:e.scenes?.map(e=>e.id===r?{...e,id:g.scene_id,media:{...e.media,url:d}}:e)||[]}
106:e),c("dnd","pending_scene:updated",{oldId:r,newId:g.scene_id});let x=await h(tG.id,g,e);if(!x.success)return u("dnd","upload:error",x.errorMessage,{}),await l("uploading",x.errorMessage),null;c("dnd","upload:ok",{sceneId:g.scene_id,usedFallback:x.usedFallback});let b=x.durationSeconds;if(!b&&(e.type||"").startsWith("video"))try{let{extractVideoMetadata:t}=await a.e(2246).then(a.bind(a,82246)),r=await t(e);r?.duration&&Number.isFinite(r.duration)&&r.duration>0&&(b=r.duration)}catch{}let y=await m(g.finalize_url,{durationSeconds:b});if(!y.success||!y.data?.success){u("dnd","finalize:error",y.error,{}),eU(`"${e.name}" uploaded but could not be finalized${y.error?.message?`: ${y.error.message}`:""}. Try refreshing the page.`);let{toast:t}=await Promise.resolve().then(a.bind(a,66609));return t.warning(`"${e.name}" uploaded but could not be finalized`,{description:"Try refreshing the page.",duration:1e4}),null}return c("dnd","finalize:ok",{sceneId:g.scene_id}),g.scene_id}catch(t){let{traceError:e}=await Promise.all([a.e(1453),a.e(2826),a.e(9304),a.e(4715),a.e(1464)]).then(a.bind(a,41464));return e("dnd","exception",t,{}),await l("unexpected error",t instanceof Error?t.message:void 0),null}},ao=async e=>{if(!tG?.id||0===e.length)return{successCount:0,failedCount:e.length};let{trace:t}=await Promise.all([a.e(1453),a.e(2826),a.e(9304),a.e(4715),a.e(1464)]).then(a.bind(a,41464));t("dnd","multi_start",{count:e.length}),window.__AUTOSHORTS_UPLOADING__=!0,dv("MULTI_ADD_START",{fileCount:e.length,projectId:tG.id,existingScenes:tG.scenes?.length||0,isMasterOnlyMode:tG.isMasterOnlyMode,viewMode:tG.viewMode});let{extractMultipleVideoMetadata:r}=await a.e(2246).then(a.bind(a,82246)),n=r(e),i=e.map((e,t)=>{let a=ar(),r=URL.createObjectURL(e);return dv("PLACEHOLDER_CREATED",{tempId:a,fileName:e.name,index:t}),{id:a,title:e.name.replace(/\.[^/.]+$/,""),url:r,text:"",media:{type:e.type.startsWith("image/")?"image":e.type.startsWith("video/")?"video":["jpg","jpeg","png","gif","webp","bmp","avif","heic","heif"].includes(e.name.toLowerCase().split(".").pop()||"")?"image":"video",status:"uploading",url:r,originalUrl:r,isStorageBacked:!1,fileSize:e.size,contentType:e.type||"application/octet-stream",duration:5},source:{platform:"upload"},createdAt:Date.now()+t,isLoading:!0,_file:e,_tempId:a}});eE(e=>{if(!e)return e;let t=(e.scenes?.length||0)+i.length;return dv("LOCAL_STATE_UPDATING",{prevSceneCount:e.scenes?.length||0,addingCount:i.length,newTotal:t,prevIsMasterOnlyMode:e.isMasterOnlyMode,prevViewMode:e.viewMode}
106),{...e,scenes:[...e.scenes||[],...i.map(({_file:e,_tempId:t,...a})=>a)],isMasterOnlyMode:e.isMasterOnlyMode,viewMode:e.viewMode}}),t("dnd","placeholders_added",{count:i.length}),n.then(e=>{eE(t=>{if(!t)return t;let a=!1,r=t.scenes?.map(t=>{let r=i.findIndex(e=>e._tempId===t.id||e.id===t.id);if(r>=0&&e[r]){let n=e[r];return a=!0,dv("METADATA_EXTRACTED",{sceneId:t.id,duration:n.duration,dimensions:`${n.width}x${n.height}`}),{...t,media:{...t.media,duration:n.duration,width:n.width,height:n.height}}}return t});return a?{...t,scenes:r}:t})}),dv("UPLOADS_STARTING",{count:i.length,pool:4});let s=Array(i.length).fill(null),o=0,l=Array.from({length:Math.min(4,i.length)},async()=>{for(;;){let e=o++;if(e>=i.length)break;let t=i[e];dv("UPLOAD_INDIVIDUAL_START",{index:e,tempId:t._tempId,fileName:t._file.name});try{let a=await as(t._file,t._tempId);s[e]=a,dv("UPLOAD_INDIVIDUAL_COMPLETE",{index:e,tempId:t._tempId,finalSceneId:a})}catch(a){dw("UPLOAD_INDIVIDUAL_REJECTED",{index:e,tempId:t._tempId,error:String(a)})}finally{eR(e=>e+1)}}});await Promise.all(l);let d=s.filter(Boolean).length,c=i.length-d;t("dnd","multi_complete",{successCount:d,totalCount:e.length}),dv("UPLOADS_ALL_COMPLETE",{successCount:d,failedCount:c,totalCount:e.length}),window.__AUTOSHORTS_UPLOADING__=!1;let u=tG.isMasterOnlyMode,p=tG.viewMode;dv("REFRESH_STARTING",{viewModeBeforeRefresh:u,viewTypeBeforeRefresh:p,currentSceneCount:tG.scenes?.length||0});try{await z();let{fetchAPI:e}=await Promise.resolve().then(a.bind(a,63557)),{transformBackendProject:r}=await Promise.resolve().then(a.bind(a,60668)),n=await e(`/projects/${tG.id}`,{method:"GET"});if(n.success&&n.data){let e=n.data.data?n.data.data:n.data,i=r(e),s=(0,du.I)(i,"function"==typeof F?F():null,{isMasterOnlyMode:u,viewMode:p});dv("SERVER_PROJECT_RECEIVED",{serverSceneCount:i.scenes?.length,serverIsMasterOnlyMode:i.isMasterOnlyMode,serverViewMode:i.viewMode,preservedIsMasterOnlyMode:s.isMasterOnlyMode,preservedViewMode:s.viewMode}),eE(s),t("dnd","project:authoritative_refreshed",{scenes:i.scenes?.length});try{"function"==typeof N&&N(s.id);try{"function"==typeof T&&(T(s),dv("CORE_STATE_UPDATED",{sceneCount:s.scenes?.length,isMasterOnlyMode:s.isMasterOnlyMode}))}catch{}"function"==typeof M&&(await M(s),t("dnd","project:saved"),dv("PROJECT_SAVED"))}catch(t){let{traceError:e}=await Promise.all([a.e(1453),a.e(2826),a.e(9304),a.e(4715),a.e(1464)]).then(a.bind(a,41464));e("dnd","project:persist_error",t,{}),dw("PERSIST_ERROR",{error:String(t)})}}else{var m;let e;m={success:n.success,hasData:!!n.data},e=new Date().toISOString().split("T")[1].slice(0,12),console.warn(`${dy} [${e}] â ï¸ SERVER_RESPONSE_FAILED`,m?JSON.stringify(m,null,0):"")}}catch(t){let{traceError:e}=await Promise.all([a.e(1453),a.e(2826),a.e(9304),a.e(4715),a.e(1464)]).then(a.bind(a,41464));e("dnd","project:refresh_error",t,{}),dw("REFRESH_ERROR",{error:String(t)})}return dv("MULTI_ADD_COMPLETE",{finalSceneCount:tG.scenes?.length||0,isMasterOnlyMode:tG.isMasterOnlyMode}),{successCount:d,failedCount:c}},al=async e=>{if(console.log("[AUDIO] handleAudioFilesAdd called with",e.length,"files"),!tG?.id||0===e.length)return console.log("[AUDIO] Early return - no project or no files"),{successCount:0,failedCount:e.length};let{trace:t}=await Promise.all([a.e(1453),a.e(2826),a.e(9304),a.e(4715),a.e(1464)]).then(a.bind(a,41464));t("dnd","audio_start",{count:e.length}),dv("AUDIO_ADD_START",{fileCount:e.length,projectId:tG.id});let{uploadAudioFile:r}=await Promise.resolve().then(a.bind(a,9756)),{resolveUploadGate:n}=await a.e(4538).then(a.bind(a,84538)),i=async(e,t)=>{let{toast:r}=await Promise.resolve().then(a.bind(a,66609));r.error(`"${e}" needs a bigger upload limit`,{description:t,duration:12e3,action:{label:"Upgrade",onClick:()=>{window.location.href="/pricing?from=upload-limit"}}})},s=0,o=dd(tG.audio,tG.voiceovers);for(let t of e)try{console.log("[AUDIO] Uploading file:",t.name,t.size,"bytes"),dv("AUDIO_UPLOAD_START",{filename:t.name,size:t.size});let e=n(t.size,{isPaidTier:B?null:O.features.canUseAiEditor,maxUploadFileBytes:O.maxUploadFileBytes,paidMaxUploadFileBytes:O.paidMaxUploadFileBytes});if(!e.allowed){if((0,ey.trackEvent)("media_import_file_too_large",{project_id:tG.id,file_size_bytes:t.size,file_type:t.type||"unknown",gate_reason:e.reason,cap_bytes:e.capBytes}),"free_cap"===e.reason){await i(t.name,e.message);continue}throw Error(e.message)}let a=await r(tG.id,t);if(!a.success||!a.url){if("free_tier_limit_reached"===a.errorCode&&a.errorMessage){await i(t.name,a.errorMessage);continue}throw Error(a.errorMessage||"The audio upload failed.")}console.log("[AUDIO] Upload result:",a),dv("AUDIO_UPLOAD_OK",{url:a.url,duration:a.durationSeconds,usedFallback:a.usedFallback});let l=a.durationSeconds||Math.max(5,t.size/2e4),d=`audio-${(0,v.generateId)()}`,c=dc(o,{id:d,start:0,duration:l}),u={id:d,type:"audio",storageKey:a.storageKey,url:a.url,start:0,duration:l,trackId:c,inOffset:0,outOffset:l,volume:1,text:t.name,sourceSce
106neId:void 0,status:"ready",generatedAt:Date.now(),createdAt:Date.now(),updatedAt:Date.now()};L&&(await L(u),dv("AUDIO_PERSISTED",{id:d,start:0,duration:l})),s+=1}catch(r){dw("AUDIO_UPLOAD_FAILED",{filename:t.name,error:String(r)}),console.error(`Failed to upload audio file ${t.name}:`,r);let{toast:e}=await Promise.resolve().then(a.bind(a,66609));e.error(`Could not import "${t.name}"`,{description:r instanceof Error?r.message:"The upload failed. Please try again.",duration:1e4})}finally{eR(e=>e+1)}return dv("AUDIO_ADD_COMPLETE",{count:e.length}),{successCount:s,failedCount:e.length-s}},ad=async e=>{let t=Date.now(),r=e.reduce((e,t)=>e+(t.size||0),0),n={project_id:tG?.id,mode:tG?.mode==="local"?"local":"cloud",file_count:e.length,total_bytes:r};try{if(!tG?.id||0===e.length)return;(0,ey.trackEvent)("media_import_started",n);let{mediaFiles:r,audioFiles:i,unsupportedFiles:s}=(0,dp.d)(e);if(s.length>0){let{toast:e}=await Promise.resolve().then(a.bind(a,66609));e.error(1===s.length?"Unsupported file type":`${s.length} unsupported files`,{description:"Choose video, image, or audio files. Supported files in this selection will still be imported."})}let o=[...r,...i];o.length>0&&(eR(0),eP(o.map(e=>({name:e.name,progress:0}))));let l=0,d=s.length;if("local"===tG.mode){if(o.length>0){let e=await ai(o);l+=e.successCount,d+=e.failedCount}}else{if(r.length>0){let e=await ao(r);l+=e.successCount,d+=e.failedCount}if(i.length>0){await new Promise(e=>setTimeout(e,100));let e=await al(i);l+=e.successCount,d+=e.failedCount}}eP([]),eR(0);let c={...n,media_file_count:r.length,audio_file_count:i.length,unsupported_file_count:s.length,success_count:l,failed_count:d,duration_ms:Date.now()-t};0===l&&d>0?(0,ey.trackEvent)("media_import_failed",{...c,error:s.length===e.length?"unsupported_file_type":"all_files_failed"}):(0,ey.trackEvent)("media_import_completed",c)}catch(r){eP([]),eR(0),console.error("[IMPORT] Exception:",r),(0,ey.trackEvent)("media_import_failed",{...n,duration_ms:Date.now()-t,error:r instanceof Error?r.message.slice(0,200):"unknown"});let{traceError:e}=await Promise.all([a.e(1453),a.e(2826),a.e(9304),a.e(4715),a.e(1464)]).then(a.bind(a,41464));e("dnd","exception",r,{})}},ac=(0,i.useCallback)((e,t)=>{if(!tG)return;let r=tG.scenes.find(t=>t.id===e);if(!r?.media||!r.generationHistory)return;let n=[...r.generationHistory],i=r.media.storageKey,s=i?(0,ex.$n)(i):r.media.url||r.media.storedUrl||"";s&&!n.some(e=>e.resultMediaKey===i&&e.displayUrl===s)&&n.push({displayUrl:s,resultUrl:r.media.url,resultMediaKey:i??null,jobType:"video"===r.media.type?"scene_video":"scene_image",timestamp:Date.now()});let o=n[t];if(!o)return;let l=o.resultMediaKey?(0,ex.$n)(o.resultMediaKey):o.displayUrl,d={...r,media:{...r.media,url:l,storedUrl:l,storageKey:o.resultMediaKey??void 0,type:"scene_video"===o.jobType?"video":"image"},generationHistory:n},c={...tG,scenes:tG.scenes.map(t=>t.id===e?d:t),updatedAt:Date.now()};if(eE(c),T(c),M(c),o.resultMediaKey&&window.dispatchEvent(new CustomEvent("faceless:media-version-swap",{detail:{nleSceneId:e,resultMediaKey:o.resultMediaKey}})),o.resultMediaKey){let t=o.resultMediaKey;(async()=>{try{let{authenticatedMediaFetch:r}=await Promise.resolve().then(a.bind(a,40554)),n=await r(l);if(!n.ok)return;let i=URL.createObjectURL(await n.blob());eE(a=>{let r=a??c,n=r.scenes.find(t=>t.id===e);if(!n?.media||n.media.storageKey!==t)return URL.revokeObjectURL(i),a;let s={...r,scenes:r.scenes.map(t=>t.id===e?{...t,media:{...t.media,url:i}}:t)};return T(s),s})}catch{}})()}},[tG,T,M]),au=function({project:e,commitProject:t,videoQualityTier:r="720p"}){let[n,s]=(0,i.useState)({}),[o,l]=(0,i.useState)(null),d=(0,i.useRef)(e),c=(0,i.useRef)(t),u=(0,i.useRef)(n);(0,i.useEffect)(()=>{d.current=e,c.current=t,u.current=n});let p=(0,i.useRef)(!0);(0,i.useEffect)(()=>(p.current=!0,()=>{p.current=!1}),[]);let m=(0,i.useRef)(new Set),h=(0,i.useRef)(new Map),f=(0,i.useRef)(!1),g=(0,i.useCallback)((e,t)=>{s(a=>{let r={...a};return null===t?delete r[e]:r[e]=t,r})},[]),x=(0,i.useCallback)(e=>{let t=h.current,a=t.get(e);a&&clearTimeout(a),t.set(e,setTimeout(()=>{t.delete(e),s(t=>{if(t[e]?.phase!=="failed")return t;let a={...t};return delete a[e],a})},12e3))},[s]);(0,i.useEffect)(()=>{let e=h.current;return()=>
106{e.forEach(e=>clearTimeout(e)),e.clear()}},[]);let b=(0,i.useCallback)((e,t)=>{let a=d.current;if(!a||!a.scenes.find(t=>t.id===e))return!1;let r={...a,scenes:a.scenes.map(a=>a.id===e?t(a):a),updatedAt:Date.now()};return c.current(r),!0},[]),y=(0,i.useCallback)((e,t,a)=>{b(e,e=>e.media&&"generating"===e.media.status?{...e,media:{...e.media,status:"ready"},generationJobId:void 0}:e),g(e,{phase:"failed",error:t}),x(e),(0,ey.trackEvent)("editor_animate_photo_failed",{provider:a.provider??null,model:a.model??null,reason:a.reason})},[b,x,g]),v=(0,i.useCallback)(async(e,t,r,n)=>{let i=r.resultMediaKey??null;if(!i)return void y(e,"The animation finished without a stored clip. Please try again.",{provider:n.provider,model:n.model,reason:"missing_result_key"});let s=(0,ex.$n)(i),o=s;try{let{authenticatedMediaFetch:e}=await Promise.resolve().then(a.bind(a,40554)),t=await e(s);t.ok&&(o=URL.createObjectURL(await t.blob()))}catch{}let l=b(e,e=>{if(e.media?.storageKey===i)return e;let a=function(e){let t=[...e.generationHistory??[]],a=e.media;if(!a)return t;let r=a.storageKey??null,n=r?(0,ex.$n)(r):a.storedUrl||a.url||"";return n&&!t.some(e=>e.resultMediaKey===r&&e.displayUrl===n)&&t.push({displayUrl:n,resultUrl:a.url,resultMediaKey:r,jobType:"video"===a.type?"scene_video":"scene_image",timestamp:Date.now()}),t}(e);return{...e,media:{...e.media??{type:"image",url:""},type:"video",status:"ready",url:o,storedUrl:s,storageKey:i,assetRef:{type:"r2",storageKey:i},duration:r.resultDuration??n.durationTarget,...r.resultWidth?{width:r.resultWidth}:{},...r.resultHeight?{height:r.resultHeight}:{},contentType:"video/mp4",isStorageBacked:!0,hasNativeAudio:!1,trim:void 0},generationHistory:a,generationJobId:void 0,generation:{provider:n.provider,mode:"image-to-video",prompt:n.prompt,duration_returned:r.resultDuration??void 0,generation_job_id:t,generated_at:new Date().toISOString()}}});g(e,null),(0,ey.trackEvent)("editor_animate_photo_completed",{provider:n.provider,model:n.model,duration_target:n.durationTarget,result_duration:r.resultDuration??null,scene_still_in_project:l})},[b,y,g]),w=(0,i.useCallback)(async(e,t,a)=>{if(!m.current.has(t)){m.current.add(t);try{let r=await (0,eg.Ar)(t,t=>{p.current&&"completed"!==t.status&&"ready"!==t.status&&g(e,{phase:"generating",progress:t.progress??null})},()=>!p.current,{jobType:"scene_video"});if(r.cancelled)return;if(("completed"===r.status||"ready"===r.status)&&r.resultMediaKey)await v(e,t,r,a);else y(e,r.sessionExpired?"Your session expired. Sign in again, then retry.":r.pollTimedOut?"The animation is taking unusually long. It may still finish; reload to check.":r.error||"The animation failed. Credits for failed runs are refunded.",{provider:a.provider,model:a.model,reason:r.pollTimedOut?"poll_timeout":r.sessionExpired?"session_expired":"job_failed"})}finally{m.current.delete(t)}}},[y,v,g]),k=(0,i.useCallback)(e=>{let t=u.current[e]?.phase;"starting"!==t&&"generating"!==t&&((0,ey.trackEvent)("editor_animate_photo_opened",{}),l(e))},[l]),S=(0,i.useCallback)(()=>l(null),[]),j=(0,i.useCallback)(async(e,t,a,n="first_frame",i="edited")=>{let s=d.current;if(!o||!s)return l(null),{blocked:null};let p=s.scenes.find(e=>e.id===o);if(!p)return l(null),{blocked:null};let m=u.current[o]?.phase;if("starting"===m||"generating"===m)return l(null),{blocked:null};if(f.current)return{blocked:null};f.current=!0;let h=function(e,t,a,r){let n=e.facelessStoryboard,i=n?.plan;if(!n||!i||!Array.isArray(i.scenes))return e;let s=(0,ef.nh)(t,{projectScenes:e.scenes,planScenes:i.scenes,liveSyncSceneMap:new Map,detachedPlanSceneIds:new Set(n.detachedPlanSceneIds??[])});if(!s)return e;let o=i.scenes.find(e=>e.id===s);return o&&(o.animationPrompt!==a||o.animationPromptSource!==r)?{...e,facelessStoryboard:{...n,plan:{...i,scenes:i.scenes.map(e=>e.id===s?{...e,animationPrompt:a,animationPromptSource:r}:e)}},updatedAt:Date.now()}:e}(s,o,e,i);h!==s&&(s=h,d.current=h,c.current(h));let y=null,v=5;try{let d=ev(p);if(!d)return l(null),g(o,{phase:"failed",error:"This photo has not finished uploading yet. Try again in a moment."}),x(o),{blocked:null};v=Math.min((0,eb.CP)(a),Math.max(5,Math.ceil(ew(p)))),g(o,{phase:"starting"}),(0,ey.trackEvent)("editor_animate_photo_started",{provider:t,model:a,duration_target:v,quality_tier:r,image_guidance_mode:n,animation_prompt_source:i});let c=await (0,eg.Dv)(s.id,o,e,s.aspectRatio||"9:16",v,t,a,d,r,void 0,void 0,void 0,void 0,n);if(!c.jobId){g(o,{phase:"failed",error:c.sessionExpired?"Your session expired. Sign in again, then retry.":c.upgradeRequired?"Video generation needs a Pro plan or a credit pack.":c.limitReached?"Generation limit reached for now. Try again later.":c.error||"Could not start the animation. Please try again."}),x(o),(0,ey.trackEvent)("editor_animate_photo_failed",{provider:t,model:a,reason:c.upgradeRequired?"upgrade_required":c.sessionExpired?"session_expired":c.limitReached?"limit_reached":"create_failed"});let e=c.upgradeRequired||c.limitReached?"credit_limit_reached"===c.errorCode?"credits":"pro":null;if(e)return{blocked:e};return l(null),{blocked:null}}l(null);let u=c.jobId;y=u,b(o,e=>({...e,media:e.media?{...e.media,status:"generating"}:e.media,generationJobId:u})),g(o,{phase:"generating"})}finally{f.current=!1}return null===y||await w(o,y,{provider:t,model:a,prompt:e,durationTarget:v}),{blocked:null}},[b,w,x,g,o,r]),I=e?.id??null,N=e?.scenes.length??0,C=(0,i.useRef)(null);return(0,i.useEffect)(()=>
106{if(!I||C.current===I)return;let e=d.current;if(e&&0!==e.scenes.length)for(let t of(C.current=I,e.scenes)){let e=t.generationJobId;e&&t.media?.status==="generating"&&t.media?.type==="image"&&(u.current[t.id]||(g(t.id,{phase:"generating"}),w(t.id,e,{provider:"unknown",model:"unknown",prompt:"",durationTarget:Math.min(15,Math.max(5,Math.ceil(ew(t))))})))}},[w,I,N,g]),{animateTargetScene:(0,i.useMemo)(()=>o?e?.scenes.find(e=>e.id===o)??null:null,[e?.scenes,o]),openAnimateDialog:k,closeAnimateDialog:S,handleAnimateConfirm:j,animateStatusBySceneId:n}}({project:tG,commitProject:(0,i.useCallback)(e=>{eE(e),T(e),M(e)},[T,M])});if(_&&!tG)return(0,r.jsxs)("div",{className:"flex justify-center items-center py-12 bg-white dark:bg-gray-900",children:[(0,r.jsx)(x.A,{className:"h-8 w-8 text-blue-500 animate-spin"}),(0,r.jsx)("span",{className:"ml-2 text-lg text-gray-600",children:"Loading project..."})]});if(!tG)return(0,r.jsx)("div",{className:"text-center p-8",children:(0,r.jsx)("p",{className:"text-gray-500",children:"No project data available."})});let ap="faceless"===k?"Video Studio":"AI Studio";return(0,r.jsx)(nj.$W,{children:(0,r.jsxs)("div",{"data-testid":"project-workspace","data-workspace-layout":tc?"compact":"desktop","data-phone-workspace-layout":tp?"true":"false","data-device-class":(0,eJ.fP)().deviceClass,className:"relative h-full min-h-0 bg-slate-900",onDragOver:e=>{e.preventDefault()},onDrop:async e=>{e.preventDefault(),e.dataTransfer?.files&&0!==e.dataTransfer.files.length&&await ad(Array.from(e.dataTransfer.files))},children:[(0,r.jsx)(dr,{audioBlocks:j&&tG&&j.id===tG.id?tG.audio&&tG.audio.length>0?tG.audio:tG.voiceovers:void 0}),!eY&&tH&&tq!==tH&&(0,r.jsxs)("div",{className:"fixed left-1/2 top-12 z-[130] flex w-max max-w-[min(92vw,560px)] -translate-x-1/2 items-start gap-3 rounded-md border border-red-500/40 bg-slate-950/95 px-4 py-2.5 text-sm text-red-200 shadow-[0_12px_32px_rgba(2,6,23,0.6)]",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1",children:tH}),(0,r.jsx)("button",{type:"button","aria-label":"Dismiss error",onClick:()=>tY(tH),className:"shrink-0 rounded p-0.5 text-red-300/80 transition-colors hover:bg-red-500/15 hover:text-red-100",children:(0,r.jsx)(H.A,{size:14})})]}),!eY&&eL&&(0,r.jsxs)("div",{className:"fixed left-1/2 top-12 z-[130] flex w-max max-w-[min(92vw,560px)] -translate-x-1/2 items-start gap-3 rounded-md border border-amber-500/40 bg-slate-950/95 px-4 py-2.5 text-sm text-amber-100 shadow-[0_12px_32px_rgba(2,6,23,0.6)]",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1",children:eL}),(0,r.jsx)("button",{type:"button","aria-label":"Dismiss codec error",onClick:()=>eF(null),className:"shrink-0 rounded p-0.5 text-amber-300/80 transition-colors hover:bg-amber-500/15 hover:text-amber-100",children:(0,r.jsx)(H.A,{size:14})})]}),!eY&&Z&&(0,r.jsx)("div",{className:"sticky top-0 z-40 mx-4 mt-2 rounded-md border border-rose-500/40 bg-rose-500/10 px-3 py-2 text-sm text-rose-100",children:Z}),!eY&&ee&&(0,r.jsx)("div",{className:"sticky top-0 z-40 mx-4 mt-2 rounded-md border border-emerald-500/30 bg-emerald-500/10 px-3 py-2 text-sm text-emerald-100",children:ee}),!eY&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{type:"file",ref:tV,onChange:async e=>{console.log("[E2E File Input] onChange triggered, files:",e.target.files?.length);let t=e.target.files;if(t&&t.length>0){let e=Array.from(t).filter(e=>e.type.startsWith("video/")||e.type.startsWith("image/"));console.log("[E2E File Input] Media files to add:",e.length),e.length>0&&await ao(e)}e.target.value=""},accept:"video/*,image/*",multiple:!0,className:"sr-only",style:{position:"absolute",left:"-9999px",opacity:0},"data-testid":"add-video-file-input"}),(0,r.jsx)("button",{type:"button",onClick:()=>tV.current?.click(),className:"sr-only","data-testid":"add-video-button","aria-hidden":"true",children:"Add Video"})]}),!eG.hidePreview&&!eV&&(0,r.jsx)(e4,{projectId:tG.id,timelineHeight:e5,compactViewport:tc,compactTopInset:40}),tc&&!eV&&(0,r.jsx)(dx,{mediaLabel:"Project Media",mediaOpen:th,showMedia:d.Wg.MEDIA_BIN_ENABLED&&!eG.hideMediaBin,studioLabel:ap,studioOpen:!e9,showStudio:ti,studioBusy:!!tg,studioNeedsAttention:!!tx,onToggleMedia:()=>{tf(e=>{let t=!e;return t&&e7(!0),t})},onToggleStudio:()=>{tf(!1),eu(!1),e7(e=>!e)}}
106),null,tc&&!eV&&!tk&&(d.Wg.MEDIA_BIN_ENABLED&&!eG.hideMediaBin&&th||ti&&!e9)&&(0,r.jsx)("button",{type:"button",className:"fixed inset-x-0 z-[60]",style:{top:85,bottom:e5},onClick:()=>{tf(!1),e7(!0)},"aria-label":"Close mobile editor drawers"}),tk&&!eV&&(0,r.jsx)("button",{type:"button",className:"fixed inset-x-0 bottom-0 z-[85]",style:{top:85},onClick:()=>e7(!0),"aria-label":"Show the editor","data-testid":tS?"phone-editor-switch-backdrop":"tablet-editor-switch-backdrop"}),!eY&&tJ&&!tc&&tG?.id&&"local"!==tG.mode&&!eV&&!U&&(0,r.jsxs)("button",{type:"button",className:"absolute z-[66] inline-flex items-center gap-2 rounded-full border border-emerald-500/35 bg-slate-950/90 px-3 py-1.5 text-xs font-semibold text-emerald-100 shadow-[0_12px_28px_rgba(2,6,23,0.35)] transition-colors hover:border-emerald-400/50 hover:bg-slate-900",style:{top:14,right:ti&&!e9?ty+18:16},onClick:()=>t7("batch"),disabled:X,children:[X?(0,r.jsx)(x.A,{className:"h-3.5 w-3.5 animate-spin"}):(0,r.jsx)(ez.A,{className:"h-3.5 w-3.5"}),(0,r.jsx)("span",{children:X?"Importing...":"Reddit Batch"})]}),d.Wg.MEDIA_BIN_ENABLED&&!eG.hideMediaBin&&!eV&&(!tc||th)&&(0,r.jsx)(eT,{scenes:tG.scenes.filter(e=>!e.facelessPlaceholder),projectId:tG.id,onSceneSelect:e=>{let t,a=(t=0,tG.scenes.map(e=>{let a=t,r=e.media?.trim?e.media.trim.end-e.media.trim.start:e.media?.duration||10;return t+=r,{id:e.id,start:a}})).find(t=>t.id===e);a&&y.zC.getState().setProjectTime(a.start)},onFilesImported:"local"===tG.mode?an:void 0,onPickFiles:ad,audioBlocks:tG.voiceovers?.filter(e=>"audio"===e.type),timelineHeight:e5,setTimelineHeight:e2,overlayMode:tc,overlayViewportWidth:ts,overlayTopPx:t_,onAddUrls:()=>t7("guided"),onMediaVersionSwap:ac,onCloseOverlay:tc?()=>tf(!1):void 0,onAnimateScene:au.openAnimateDialog,animateStatusBySceneId:au.animateStatusBySceneId}),au.animateTargetScene&&(0,r.jsx)(eW,{scene:au.animateTargetScene,project:tG,onConfirm:au.handleAnimateConfirm,onCancel:au.closeAnimateDialog}),!eY&&(0,r.jsx)("div",{className:"px-4 py-3 bg-transparent h-full min-h-0 overflow-y-auto",style:{scrollPaddingBottom:"13rem",paddingRight:ti&&!tc?ty+12:void 0},children:e$.length>0&&(0,r.jsxs)("div",{className:"fixed top-20 left-1/2 -translate-x-1/2 z-50 bg-slate-800 border border-teal-500/50 rounded-lg px-6 py-3 shadow-xl animate-in fade-in slide-in-from-top-2 duration-200","data-testid":"upload-progress-indicator",children:[(0,r.jsxs)("div",{className:"flex items-center gap-3",children:[(0,r.jsx)("div",{className:"w-5 h-5 border-2 border-teal-400 border-t-transparent rounded-full animate-spin"}),(0,r.jsx)("div",{className:"text-white font-medium",children:1===e$.length?`Uploading ${e$[0].name}...`:`Uploading files... ${Math.min(eD,e$.length)} of ${e$.length} done`})]}),e$.length>1&&(0,r.jsx)("div",{className:"mt-2 h-1.5 w-full overflow-hidden rounded-full bg-slate-700",children:(0,r.jsx)("div",{className:"h-full bg-teal-400 transition-[width] duration-300",style:{width:`${Math.round(Math.min(eD,e$.length)/e$.length*100)}%`}})})]})}),ti&&!eV&&(0,r.jsxs)("div",{ref:tD,"data-ai-rail-container":!tc||!e9||void 0,className:`fixed overflow-hidden ${tc?tw?"z-[90] rounded-2xl shadow-[0_22px_64px_rgba(2,6,23,0.72)] ring-1 ring-white/[0.1]":"z-[70] rounded-2xl shadow-[0_18px_48px_rgba(2,6,23,0.55)]":`top-10 right-0 ${tP?"z-[125]":tR?"z-[55]":"z-[45]"}`}`,style:{display:tc&&e9?"none":void 0,width:tc?tA:tP?"100vw":tv,maxWidth:tc?tw?"100dvw":"calc(100vw - 16px)":void 0,top:tc?tw?tI.top:t_:void 0,right:tc?tw?16:8:0,left:!tc&&tP?0:void 0,height:tc?tE:void 0,bottom:tc?void 0:tP||tR?0:e5},children:[!e9&&!tc&&!tP&&(0,r.jsx)("div",{className:`absolute top-0 left-0 w-3 h-full cursor-ew-resize transition-colors ${te?"bg-cyan-500/40":"hover:bg-cyan-500/20"}`,onMouseDown:e=>{e.preventDefault(),e.stopPropagation(),tt(!0),tn.current={x:e.clientX,width:e8}}}
106),(0,r.jsx)(ns,{project:tG,launchMode:f,studioMode:k,collapsed:e9,compact:tc,disableCollapse:tJ,isInterestingContentCompilationFlow:tJ,onSubmitInterestingCompilationUrls:t9,interestingImporting:el,interestingImportProgress:es,interestingImportErrors:en,interestingImportNotice:ee,fullscreen:tP,onToggleFullscreen:tc?void 0:()=>tr(e=>!e),onToggleCollapsed:()=>e7(e=>{if(tJ)return!1;let t=!e;return t?tr(!1):(eu(!1),tc&&tf(!1)),t}),updateProject:T,saveProject:M,addVoiceover:L})]}),e1&&!eV&&(0,r.jsx)(nb,{}),!eG.hideTimeline&&!eV&&(0,r.jsx)("div",{ref:e3,className:`fixed bottom-0 left-0 right-0 z-50 ${tc?"[&>div]:min-h-[inherit]":""}`,style:{minHeight:tj>0?tj:void 0},"data-master-timeline":!0,"data-mobile-default-height":tj>0?tj:void 0,children:(0,r.jsx)(l2,{})}),t0&&t1.length>0&&(0,r.jsx)(b,{handleIds:t1.map(e=>e.handleId),filenames:t1.map(e=>e.filename),onComplete:t3,onDismiss:t5}),(0,r.jsx)(eH,{isOpen:Y,isSubmitting:X,errorMessage:Z,defaultDownloadSource:V,onClose:()=>{X||(Q(null),G(!1))},onSubmit:aa}),(0,r.jsx)(eX,{isOpen:eh,onClose:()=>{ek(!1),ej(null),eN(null),eM(null)},onAccept:at})]})})}},27903:(e,t,a)=>{"use strict";a.d(t,{qj:()=>n});var r=a(12115);function n({itemSelector:e="[data-marquee-id]",disabled:t=!1,scrollMode:a="window"}={}){let i=(0,r.useRef)(null),[s,o]=(0,r.useState)(()=>new Set),[l,d]=(0,r.useState)(null),c=(0,r.useRef)(null),u=(0,r.useRef)(null),p=(0,r.useRef)(new Set),m=(0,r.useRef)(!1),h=(0,r.useRef)(!1),f=(0,r.useRef)(null),g=(0,r.useRef)(s);(0,r.useEffect)(()=>{g.current=s},[s]);let x=(0,r.useCallback)((e,t)=>{if("container"===a){let a=i.current;if(!a)return{x:e,y:t};let r=a.getBoundingClientRect();return{x:e-r.left+a.scrollLeft,y:t-r.top+a.scrollTop}}return{x:e+window.scrollX,y:t+window.scrollY}},[a]),b=(0,r.useCallback)(()=>{let t=i.current;if(!t)return[];let a=t.querySelectorAll(e),r=[];return a.forEach(e=>{let t=e.dataset.marqueeId;if(!t)return;let a=e.getBoundingClientRect(),n=x(a.left,a.top);r.push({id:t,rect:{left:n.x,top:n.y,width:a.width,height:a.height}})}),r},[e,x]),y=(0,r.useCallback)(()=>{let e=c.current,t=u.current;if(!e||!t)return;let a=x(t.x,t.y),r={left:Math.min(e.x,a.x),top:Math.min(e.y,a.y),width:Math.abs(e.x-a.x),height:Math.abs(e.y-a.y)};d(r);let n=function(e,t,a=new Set){let r=new Set(a);for(let a of e){var n;n=a.rect,n.left<t.left+t.width&&n.left+n.width>t.left&&n.top<t.top+t.height&&n.top+n.height>t.top&&r.add(a.id)}return r}(b(),r,p.current);!function(e,t){if(e.size!==t.size)return!1;for(let a of e)if(!t.has(a))return!1;return!0}(n,g.current)&&o(n)},[b,x]),v=(0,r.useCallback)(()=>{null!==f.current&&(cancelAnimationFrame(f.current),f.current=null)},[]),w=(0,r.useCallback)(()=>{v();let e=()=>{if(!m.current)return;let t=u.current;if(t){let e=0;if("container"===a){let a=i.current;if(a){let r=a.getBoundingClientRect(),n=Math.min(72,Math.max(16,r.height/4));t.y<r.top+n?e=-Math.ceil((r.top+n-t.y)/n*22):t.y>r.bottom-n&&(e=Math.ceil((t.y-(r.bottom-n))/n*22)),0!==e&&(a.scrollBy(0,e),y())}}else t.y<72?e=-Math.ceil((72-t.y)/72*22):t.y>window.innerHeight-72&&(e=Math.ceil((t.y-(window.innerHeight-72))/72*22)),0!==e&&(window.scrollBy(0,e),y())}f.current=requestAnimationFrame(e)};f.current=requestAnimationFrame(e)},[a,v,y]),k=(0,r.useCallback)(e=>{let t=m.current;m.current=!1,c.current=null,u.current=null,v(),d(null),document.body.style.userSelect="",t&&(h.current=!0,e&&o(new Set(p.current)))},[v]);(0,r.useEffect)(()=>()=>{v(),document.body.style.userSelect=""},[v]),(0,r.useEffect)(()=>{t&&m.current&&k(!0)},[t,k]);let S=(0,r.useCallback)(e=>{if(t||"mouse"!==e.pointerType||0!==e.button)return;let a=e.target;if(a?.closest("button, a, input, textarea, select, [data-no-marquee]"))return;c.current=x(e.clientX,e.clientY),u.current={x:e.clientX,y:e.clientY},p.current=e.shiftKey||e.metaKey||e.ctrlKey?new Set(g.current):new Set;let r=e=>{if(u.current={x:e.clientX,y:e.clientY},!m.current){let t=c.current;if(!t)return;let a=x(e.clientX,e.clientY);if(6>Math.hypot(a.x-t.x,a.y-t.y))return;m.current=!0,document.body.style.userSelect="none",w()}e.preventDefault(),y()},n=()=>{m.current&&y()},i=e=>{"Escape"===e.key&&m.current&&(e.stopPropagation(),o(!0))},s=()=>o(!1),o=e=>{window.removeEventListener("pointermove",r),window.removeEventListener("pointerup",s),window.removeEventListener("pointercancel",s),window.removeEventListener("scroll",n,!0),window.removeEventListener("keydown",i,!0),k(e)};window.addEventListener("pointermove",r),window.addEventListener("pointerup",s),window.addEventListener("pointercancel",s),window.addEventListener("scroll",n,!0),window.addEventListener("keydown",i,!0)},[t,k,w,x,y]),j=(0,r.useCallback)(e=>{h.current&&(h.current=!1,e.preventDefault(),e.stopPropagation())},[]),I=(0,r.useCallback)(()=>
106{p.current=new Set,o(new Set)},[]),N=(0,r.useCallback)(e=>{o(t=>{let a=new Set(t);return a.has(e)?a.delete(e):a.add(e),a})},[]),C=null;if(l)if("container"===a){let e=i.current;if(e){var M,_;let t,a,r=e.getBoundingClientRect();M={left:l.left+r.left-e.scrollLeft,top:l.top+r.top-e.scrollTop,width:l.width,height:l.height},_={left:r.left,top:r.top,width:r.width,height:r.height},t=Math.max(M.left,_.left),a=Math.max(M.top,_.top),C={left:t,top:a,width:Math.max(0,Math.min(M.left+M.width,_.left+_.width)-t),height:Math.max(0,Math.min(M.top+M.height,_.top+_.height)-a)}}}else C={left:l.left-window.scrollX,top:l.top-window.scrollY,width:l.width,height:l.height};return{containerRef:i,onPointerDown:S,onClickCapture:j,marqueeClientRect:C,isMarqueeActive:null!==l,selectedIds:s,setSelectedIds:o,toggleSelected:N,clearSelection:I}}},33711:e=>{e.exports={thumbnail:"MediaBinCard_thumbnail__QDT9O",animatePill:"MediaBinCard_animatePill__eDRY_",animateIcon:"MediaBinCard_animateIcon__A26TO",animateLabel:"MediaBinCard_animateLabel__Tko5E"}},50864:(e,t,a)=>{"use strict";a.d(t,{Oo:()=>l,RZ:()=>p,kI:()=>u,rR:()=>c});var r=a(10615),n=a(9756),i=a(7978),s=a(90801),o=a(64542);let l=e=>"local"===e.mode?r.Kn:r.aK,d=new Map;function c(e,t){let a=`text-story-upload:${e}:${t}`;d.delete(a);try{sessionStorage.removeItem(a)}catch{d.set(a,null)}}async function u(e,t,a,o){let l=new File([await (0,s.gs)(t,a)],`chat-${a.key.replace(":","-")}.png`,{type:"image/png"}),c={type:"image",width:s.Fv,height:s.CF,duration:a.duration,trim:{start:0,end:a.duration}};if("local"===e.mode){let t=await (0,r.D_)(e.id,l);return{sceneId:`chat-${crypto.randomUUID()}`,media:{...c,url:"",assetRef:{type:"blob",blobId:t.id,filename:t.filename,size:t.size,lastModified:t.lastModified,mimeType:t.mimeType}}}}let u=`text-story-upload:${e.id}:${a.key}`,p=d.get(u);if(void 0===p)try{p=JSON.parse(sessionStorage.getItem(u)??"null")}catch{}let m=p?.fingerprint===a.fingerprint?p.plan:void 0;if(!m?.scene_id||!m.object_key||!m.finalize_url){let t=await (0,n.createUploadSession)({project_id:e.id,filename:l.name,size_bytes:l.size,content_type:l.type});if(!t.success||!t.data)throw Error(t.error?.message||"Could not prepare chat image storage.");m=t.data;let r={fingerprint:a.fingerprint,plan:m};try{sessionStorage.setItem(u,JSON.stringify(r))}catch{}}d.set(u,{fingerprint:a.fingerprint,plan:m}),o?.(m.scene_id);let h=await (0,n.uploadSceneFile)(e.id,m,l);if(!h.success)throw Error(h.errorMessage||"Could not save a chat image.");let f=await (0,n.finalizeUpload)(m.finalize_url,{durationSeconds:a.duration});if(!f.success||!f.data?.success)throw Error(f.error?.message||"Could not finish saving a chat image.");let g=(0,i.$n)(m.object_key);return{sceneId:m.scene_id,media:{...c,url:g,storageKey:m.object_key,isStorageBacked:!0,contentType:"image/png",fileSize:l.size}}}async function p(e,t,a,r){if(e.textStory?.ready)return e;let n=e.textStory??(0,o.qd)(t,r),i=l(e),s={...e,title:e.textStory?e.title:`${n.contactName} â Text story`,aspectRatio:"9:16",textStory:n,aiWorkspaceTab:"generate"};await i.saveProject(s);let d=(0,o.FV)(n),p=0;for(let e=0;e<d.length;e++){let t=d[e],r=s.scenes.find(e=>e.id===s.textStory?.clips[t.key]?.sceneId);if(r?.media&&s.textStory?.clips[t.key]?.fingerprint===t.fingerprint){p=(r.timelineStart??p)+((r.media.trim?.end??r.media.duration??t.duration)-(r.media.trim?.start??0)),a(e+1,d.length);continue}let o=await u(s,n,t),l={id:o.sceneId,title:"typing"===t.kind?t.label:`Message ${t.visibleCount}`,url:o.media.url||`local://${t.key}.png`,text:t.label,media:o.media,createdAt:Date.now(),timelineStart:p,trackId:1,source:{platform:"local",author:"",subreddit:""},isLoading:!1};s={...s,scenes:[...s.scenes.filter(e=>e.id!==o.sceneId),l],textStory:{...s.textStory,clips:{...s.textStory.clips,[t.key]:{sceneId:l.id,fingerprint:t.fingerprint}}},updatedAt:Date.now()},await i.saveProject(s),"local"!==s.mode&&c(s.id,t.key),p+=t.duration,a(e+1,d.length)}return s={...s,textStory:{...s.textStory,ready:!0}},await i.saveProject(s),s}},64542:(e,t,a)=>{"use strict";a.d(t,{FV:()=>s,lR:()=>o,qd:()=>i});var r=a(27614),n=a(38234);function i(e,t){let a=(0,r.K)(e);if(!a)throw Error("Write at least three messages between two people.");
106return{...a,version:1,clips:{},...t?{theme:(0,n.ON)(t)}:{},messages:a.messages.map(e=>({...e,id:crypto.randomUUID()}))}}function s(e){return e.messages.flatMap((t,a)=>{let r=r=>{let i="typing"===r,s=i?a:a+1,o=i?t.side:void 0;return{key:`${t.id}:${r}`,kind:r,visibleCount:s,typingSide:o,duration:i?Math.min(3,Math.max(.7,.035*t.text.length)):Math.max(2,.4*t.text.split(/\s+/).length+.7),label:i?`${t.sender} is typingâ¦`:`${t.sender}: ${t.text}`,fingerprint:JSON.stringify([e.contactName,e.messages.slice(0,s).map(e=>[e.side,e.text]),o??null,...e.theme?[(0,n.ON)(e.theme)]:[]])}};return 0===a?[r("message")]:[r("typing"),r("message")]})}function o(e,t,a){let r=new Map(a.map(e=>[t.clips[e.frame.key]?.sceneId,e])),n={...t.clips},i=e.scenes.map(e=>{let t=r.get(e.id);return t?(n[t.frame.key]={sceneId:e.id,fingerprint:t.frame.fingerprint},{...e,text:t.frame.label,media:{...e.media,...t.media,duration:e.media?.duration,trim:e.media?.trim}}):e});return{...e,scenes:i,textStory:{...t,clips:n},updatedAt:Date.now()}}},65729:(e,t,a)=>{"use strict";a.d(t,{AT:()=>s,Fy:()=>i,LQ:()=>n,RI:()=>r,wE:()=>l,y5:()=>o});let r=[{credits:500,usd:5.99,name:"Starter Pack",tagline:"Try AI, no subscription."},{credits:1e3,usd:9.99,name:"Creator Pack",tagline:"1,000 credits. One payment."},{credits:5e3,usd:35,name:"Credit Pack",tagline:"One-time credits, no subscription."},{credits:1e4,usd:60,name:"Credit Pack",tagline:"One-time credits, no subscription."}],n=0,i=1,s=r[0],o=r[1];function l(e){let t=Number.isInteger(e)?e.toFixed(0):e.toFixed(2);return`$${t} USD`}},66713:(e,t,a)=>{"use strict";a.d(t,{Nz:()=>i,W9:()=>s,b$:()=>n});let r="https://framecompose.invalid";function n(e){if(!e)return null;let t=e.trim();if(!t.startsWith("/")||t.startsWith("//")||t.includes("\\")||t.length>2048||/[\u0000-\u001f\u007f]/.test(t))return null;try{let e=new URL(t,r);if(e.origin!==r)return null;return`${e.pathname}${e.search}${e.hash}`}catch{return null}}function i(){return n(`${window.location.pathname}${window.location.search}${window.location.hash}`)}function s(e,t){let a=n(t);if(!a)return e;let i=new URL(e,r);return i.searchParams.set("returnTo",a),`${i.pathname}${i.search}${i.hash}`}},83870:e=>{e.exports={studioShimmer:"MobileEditorSubheader_studioShimmer__hjiCi","studio-attention-sweep":"MobileEditorSubheader_studio-attention-sweep__zONyT"}},84677:(e,t,a)=>{"use strict";a.d(t,{KS:()=>h,M2:()=>v,M6:()=>g,Vt:()=>y,_F:()=>x,du:()=>f,fw:()=>m,ye:()=>w});var r=a(66713);let n="We couldn't open checkout right now. Please try again in a moment.",i="We couldn't open billing settings right now. Please try again in a moment.",s="Please sign in again to continue.";function o(e,t){return 401===t?s:("customer-portal"===e||"change-plan"===e)&&404===t?"You don't have a subscription to manage yet. Choose a plan to get started.":"create-checkout-session"===e&&409===t?"You already have an active subscription on this account. Manage or change your plan from the Billing page instead.":"customer-portal"===e?i:n}let l=[1200,3e3];async function d(e,t){for(let a=0;;a+=1){let r=null;try{r=await fetch(`/api/billing/${e}`,{...t,credentials:"include",headers:{"Content-Type":"application/json",...t.headers||{}}})}catch{r=null}if(r&&429!==r.status){let t=null,a=await r.text();if(a)try{t=JSON.parse(a)}catch{t=null}if(!r.ok)throw Error(o(e,r.status));return t||{}}let n=l[a];if(void 0===n)throw Error(o(e,r?.status??0));await new Promise(e=>setTimeout(e,n))}}function c(e){return e?"data"in e&&e.data?e.data:e:{}}
106function u(e){return null===e?null:(0,r.b$)(e)??(0,r.Nz)()}function p(){return"function"==typeof globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`checkout-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`}async function m(e,t){let a=u(t),r=p(),i=await d("create-checkout-session",{method:"POST",body:JSON.stringify({plan:e,idempotency_key:r,...a?{return_to:a}:{}})});if(!i||!("success"in i)||!i.success)throw Error(n);let s=c(i.data);if(!s.url)throw Error(n);return s}async function h(e=1e3,t){let a=u(t),r=p(),i=await d("create-credit-checkout-session",{method:"POST",body:JSON.stringify({credits:e,idempotency_key:r,...a?{return_to:a}:{}})});if(!i||!("success"in i)||!i.success)throw Error(n);let s=c(i.data);if(!s.url)throw Error(n);return s}async function f(){let e=await d("customer-portal",{method:"POST"});if(!e||!("success"in e)||!e.success)throw Error(i);let t=c(e.data);if(!t.url)throw Error(i);return t}async function g(e,t){let a=u(t),r=await d("change-plan",{method:"POST",body:JSON.stringify({plan:e,...a?{return_to:a}:{}})});if(!r||!("success"in r)||!r.success)throw Error(i);let n=c(r.data);if(!n.url)throw Error(i);return n}async function x(){let e=await fetch("/api/billing/plans",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw Error("Failed to load subscription plans.");let t=await e.json().catch(()=>null),a=(t&&"data"in t?t.data:t)??[];return Array.isArray(a)?a.filter(e=>e&&("pro"===e.plan||"studio"===e.plan||"max"===e.plan)).map(e=>({plan:e.plan,priceUsd:Number(e.price_usd??e.priceUsd??0),weeklyCredits:Number(e.weekly_credits??e.weeklyCredits??0),available:!!e.available})):[]}async function b(e,t){var a;let r,n=await fetch(`/api/billing/${e}`,{method:t,credentials:"include",headers:{"Content-Type":"application/json"}}),i=null,o=await n.text();if(o)try{i=JSON.parse(o)}catch{i=null}if(!n.ok){if(401===n.status)throw Error(s);if(404===n.status)throw Error("You don't have an active subscription to manage.");throw Error((i&&"string"==typeof i.message?i.message:null)||"We couldn't update your subscription right now. Please try again in a moment.")}return{hasSubscription:!!((r=((a=i)&&"data"in a?a.data:a)??{}).has_subscription??r.hasSubscription),tier:"string"==typeof r.tier?r.tier:null,status:"string"==typeof r.status?r.status:null,cancelAtPeriodEnd:!!(r.cancel_at_period_end??r.cancelAtPeriodEnd),currentPeriodEnd:"string"==typeof(r.current_period_end??r.currentPeriodEnd)?r.current_period_end??r.currentPeriodEnd:null}}async function y(){return b("subscription","GET")}async function v(){return b("cancel-subscription","POST")}async function w(){return b("reactivate-subscription","POST")}},89325:(e,t,a)=>{"use strict";a.d(t,{q7:()=>m,createProjectKokoroVoiceover:()=>I,Fz:()=>h});var r=a(96412),n=a(63557),i=a(21764);let s=[256,512,1024];var o=a(32701);let l="kokoro-voiceover",d={},c=Promise.resolve();function u(e,t){if("string"==typeof t&&(t.startsWith("gemini_")||t.startsWith("sp_")))throw Error(`Voice "${t}" is a cloud voice and cannot run on the local TTS engines. Map it to a Supertonic or Kokoro voice before calling local generation.`);return e||("string"==typeof t&&t.startsWith("st_")?"supertonic":"kokoro")}function p(e){let t="string"==typeof e&&e.trim()?e.trim():l,a=Date.now().toString(36),r=Math.random().toString(36).slice(2,8);return`${t}-${a}-${r}`}function m(e){return p(e)}function h(e,t){console.info("[KOKORO-VOICEOVER]",{phase:e,...t})}function f(e){return new Promise(t=>{setTimeout(t,e)})}function g(){return new Promise(e=>{"function"==typeof window.requestAnimationFrame?window.requestAnimationFrame(()=>e()):setTimeout(e,0)})}async function x(e,t,a){let r=c,n=()=>{};c=new Promise(e=>{n=e}),await r.catch(()=>void 0),h("generation_queue_start",{requestId:e,traceSource:t});try{return await g(),await a()}finally{await g(),n(),h("generation_queue_end",{requestId:e,traceSource:t})}}function b(e){return"u"<typeof URL||"function"!=typeof URL.createObjectURL?null:URL.createObjectURL(e)}async function y(e){let t=window.AudioContext||window.webkitAudioContext||void 0;if("function"!=typeof t)return{status:"unsupported"};let a=new t;try{let t=await a.decodeAudioData(e.slice(0));
106return{status:"decoded",audioBuffer:t}}catch{return{status:"decode_failed"}}finally{try{await a.close()}catch{}}}async function v(e){let t=d[e];return t||(t="supertonic"===e?await Promise.all([a.e(8013),a.e(5139)]).then(a.bind(a,58013)):await a.e(7772).then(a.bind(a,45391)),d[e]=t),t}async function w(e){if(!("function"==typeof e.isTTSLoaded&&e.isTTSLoaded())){if("function"==typeof e.loadTTS){if(await e.loadTTS(),"function"==typeof e.isTTSLoaded&&!e.isTTSLoaded())throw Error("Kokoro model did not report ready after load.");return}if("function"==typeof e.isTTSLoading&&"function"==typeof e.isTTSLoaded&&e.isTTSLoading()){let t=Date.now()+9e4;for(;Date.now()<t;){if(e.isTTSLoaded())return;await f(200)}throw Error("Timed out waiting for Kokoro model to load.")}}}async function k(e,t="Kokoro",a={}){let r={blobMimeType:"string"==typeof e?.type&&e.type.trim().length>0?e.type:"application/octet-stream",blobSize:e?.size??0,decodeStatus:"unsupported"};if(!(e instanceof Blob)||e.size<512)return{error:`Generated ${t} audio blob was too small (${e.size} bytes).`,diagnostics:r};let n="string"==typeof e.type?e.type.toLowerCase():"",i=0===n.length||n.includes("wav")||n.includes("wave"),o=null;try{o=await e.arrayBuffer()}catch{o=null}let l=null,d=o?function(e){if(e.byteLength<44)return null;let t=new DataView(e),a=e=>String.fromCharCode(t.getUint8(e),t.getUint8(e+1),t.getUint8(e+2),t.getUint8(e+3));if("RIFF"!==a(0)||"WAVE"!==a(8))return null;let r=0,n=0,i=0,s=0,o=-1,l=0,d=12;for(;d+8<=e.byteLength;){let c=a(d),u=t.getUint32(d+4,!0),p=d+8;"fmt "===c&&p+16<=e.byteLength?(r=t.getUint16(p,!0),n=t.getUint16(p+2,!0),i=t.getUint32(p+4,!0),s=t.getUint16(p+14,!0)):"data"===c&&(o=p,l=Math.min(u,e.byteLength-p)),d=p+u+u%2}if(o<0||l<=0||n<1||i<=0)return null;let c=1===r&&16===s,u=3===r&&32===s;if(!c&&!u)return null;let p=s/8*n,m=Math.floor(l/p);if(m<=0)return null;let h=new Float32Array(m);for(let e=0;e<m;e+=1){let a=o+e*p;h[e]=c?t.getInt16(a,!0)/32768:t.getFloat32(a,!0)}return{samples:h,sampleRate:i,durationSeconds:m/i}}(o):null;if(d){let e=function(e,t={}){let a=t.lags??s,r={},n=0,i=null;for(let t of a){let a=function(e,t){let a=e.length-t;if(t<=0||a<3*t)return 0;let r=0;for(let t=0;t<e.length;t+=1)r+=e[t];r/=e.length;let n=0,i=0,s=0;for(let o=0;o<a;o+=1){let a=e[o]-r,l=e[o+t]-r;n+=a*l,i+=a*a,s+=l*l}let o=Math.sqrt(i*s);return!Number.isFinite(o)||o<=1e-12?0:n/o}(e,t);r[t]=a,a>n&&(n=a,i=t)}let o="number"==typeof t.durationSeconds&&Number.isFinite(t.durationSeconds)&&t.durationSeconds>0&&"number"==typeof t.expectedDurationSeconds&&Number.isFinite(t.expectedDurationSeconds)&&t.expectedDurationSeconds>0?t.durationSeconds/t.expectedDurationSeconds:null,l=null!==o&&o>=1.4;return{corrupted:n>=.5||l&&n>=.25,maxCorrelation:n,bestLag:i,correlationByLag:r,durationRatio:o,durationSuspect:l}}(d.samples,{durationSeconds:d.durationSeconds,expectedDurationSeconds:a.expectedDurationSeconds});r.stutterCorrelation=e.maxCorrelation,null!==e.durationRatio&&(r.stutterDurationRatio=e.durationRatio),e.corrupted&&(r.stutterDetected=!0,l=`Generated ${t} audio contains duplicated sample blocks (stutter corr=${e.maxCorrelation.toFixed(2)} at lag ${e.bestLag}`+(null!==e.durationRatio?`, duration ${e.durationRatio.toFixed(2)}x expected`:"")+").")}let c=o?await y(o):{status:"decode_failed"};if(r.decodeStatus=c.status,"decode_failed"===c.status&&i)return{error:`Generated ${t} audio blob could not be decoded.`,diagnostics:r};if("unsupported"===c.status||"decode_failed"===c.status)return{error:l,diagnostics:r};let u=c.audioBuffer;if(r.decodedDurationSeconds=u.duration,u.duration<=.08)return{error:`Generated ${t} audio duration was too short (${u.duration.toFixed(3)}s).`,diagnostics:r};let p=function(e){if(!e.numberOfChannels||!e.length)return 0;let t=e.getChannelData(0);if(!t.length)return 0;let a=Math.max(1,Math.floor(t.length/12e3)),r=0,n=0;for(let e=0;e<t.length;e+=a){let a=t[e]??0;r+=a*a,n+=1}return n?Math.sqrt(r/n):0}(u);return(r.rms=p,p<=15e-5)?{error:`Generated ${t} audio appeared silent (rms=${p.toExponential(2)}).`,diagnostics:r}:{error:l,diagnostics:r}}async function S(e,t,a,n){let s=null,o={blobMimeType:"application/octet-stream",blobSize:0,decodeStatus:"unsupported"},l="supertonic"===(n.engine??u(void 0,a))?"Supertonic":"Kokoro",d=(0,i.fW)(t),c=0,p=null,m=null,g=(e,t)=>{0!==c&&(0,r.trackEvent)("voiceover_stutter_detected",{voice_id:a,engine:l.toLowerCase(),detections:c,attempts:t,retry_outcome:e,stutter_correlation:p,duration_ratio:m,expected_duration_seconds:d,trace_source:n.traceS
106ource})};for(let r=1;r<=3;r+=1){let i=await e.generateSpeech(t,a),u=await k(i,l,{expectedDurationSeconds:d});if(s=u.error,o=u.diagnostics,u.diagnostics.stutterDetected&&(c+=1,p=u.diagnostics.stutterCorrelation??null,m=u.diagnostics.stutterDurationRatio??null),h("generation_attempt",{requestId:n.requestId,traceSource:n.traceSource,attempt:r,projectMode:n.projectMode,textLength:t.length,voiceId:a,blobMimeType:o.blobMimeType,blobSize:o.blobSize,decodeStatus:o.decodeStatus,decodedDurationSeconds:o.decodedDurationSeconds,rms:o.rms,stutterCorrelation:o.stutterCorrelation,stutterDurationRatio:o.stutterDurationRatio,validationError:s}),!s)return g("retry_clean",r),{audioBlob:i,diagnostics:{...o,attempts:r}};r<3&&await f(300*r)}throw g("exhausted",3),Error(s??`Generated ${l} audio blob was empty.`)}async function j(e){var t,a;let r,i,s=e.text.trim();if(!s)throw Error("Text cannot be empty for Kokoro generation.");let d=(t=e.requestId,a=e.traceSource,"string"==typeof t&&t.trim()?t.trim():p(a)),c="string"==typeof e.traceSource&&e.traceSource.trim()?e.traceSource.trim():l,m=u(e.engine,e.voiceId),f=e.isLocalProject?"local":"cloud";h("generation_start",{requestId:d,traceSource:c,engine:m,projectId:e.projectId??null,projectMode:f,textLength:s.length,voiceId:e.voiceId,generationId:e.voiceoverId});let g=await x(d,c,async()=>{let t=await v(m);return h("model_wait_start",{requestId:d,traceSource:c,projectMode:f,voiceId:e.voiceId}),await w(t),h("model_ready",{requestId:d,traceSource:c,projectMode:f,voiceId:e.voiceId}),S(t,s,e.voiceId,{requestId:d,traceSource:c,projectMode:f,engine:m})}),y=g.audioBlob,k="",j="";if(e.isLocalProject&&e.projectId){let{localUrl:t,blobId:a}=await (0,o.storeLocalAudioBlob)(e.projectId,y,e.voiceoverId);k=b(y)??t,j=t,r=a,i="local_blob",h("persist_local",{requestId:d,traceSource:c,projectId:e.projectId,projectMode:f,localUrl:t,storageKey:r})}else if(e.projectId){h("upload_start",{requestId:d,traceSource:c,projectId:e.projectId,projectMode:f,blobMimeType:g.diagnostics.blobMimeType,blobSize:g.diagnostics.blobSize,durationSeconds:e.durationSeconds});let t=await (0,n.uploadBrowserAudio)(y,e.projectId,e.voiceoverId,s,e.durationSeconds);if(!t.error&&t.url)k=t.url,j=t.url,r=t.storageKey??void 0,i="cloud_upload",h("upload_success",{requestId:d,traceSource:c,projectId:e.projectId,projectMode:f,persistenceUrl:j,storageKey:r});else{let a=b(y);if(!a)throw Error("Kokoro fallback URL generation is unavailable in this environment.");j=k=a,i="object_url_fallback",h("upload_fallback",{requestId:d,traceSource:c,projectId:e.projectId,projectMode:f,uploadError:t.error?.message??null,fallbackUrl:j})}}else{let e=b(y);if(!e)throw Error("Kokoro URL generation is unavailable without a project id.");j=k=e,i="object_url_fallback",h("persist_without_project",{requestId:d,traceSource:c,projectId:null,projectMode:f,persistenceUrl:j})}let I={...g.diagnostics,persistenceStrategy:i};return h("generation_complete",{requestId:d,traceSource:c,projectId:e.projectId??null,projectMode:f,voiceId:e.voiceId,playbackUrl:k,persistenceUrl:j,storageKey:r??null,diagnostics:I}),{requestId:d,voiceId:e.voiceId,audioBlob:y,playbackUrl:k,persistenceUrl:j,storageKey:r,diagnostics:I}}async function I(e){let t=await j({projectId:e.projectId,isLocalProject:e.isLocalProject,text:e.text,voiceId:e.voiceId,voiceoverId:e.generationId,durationSeconds:e.durationSeconds,requestId:e.requestId,traceSource:e.traceSource,engine:e.engine}),a=Date.now(),r="number"==typeof t.diagnostics.decodedDurationSeconds&&Number.isFinite(t.diagnostics.decodedDurationSeconds)&&t.diagnostics.decodedDurationSeconds>0?t.diagnostics.decodedDurationSeconds:e.durationSeconds,n={id:e.voiceoverId,type:"voiceover",url:t.persistenceUrl,storageKey:e.isLocalProject?void 0:t.storageKey,assetRef:e.isLocalProject&&t.storageKey?{type:"blob",blobId:t.storageKey,filename:`${e.voiceoverId}.wav`,size:t.audioBlob.size,lastModified:a,mimeType:t.audioBlob.type||"audio/wav"}:void 0,start:Math.max(0,e.startSeconds??0),duration:r,trackId:Math.max(0,e.trackId??2),inOffset:0,outOffset:r,volume:"number"==typeof e.volume&&Number.isFinite(e.volume)?Math.min(2,Math.max(0,e.volume)):1,text:e.text.trim(),settings:{...e.settings??{},voiceId:t.voiceId},status:"ready",generatedAt:a,createdAt:a,updatedAt:a};return h("voiceover_block_prepared",{requestId:t.requestId,traceSource:e.traceSource??l,projectId:e.projectId??null,projectMode:e.isLocalProject?"local":"cloud",voiceoverId:n.id,generationId:e.generationId,durationSeconds:n.duration,finalUrl:n.url??null,storageKey:n.storageKey??null,assetRef:n.assetRef??null}),{...t,voiceover:n}}},90801:(e,t,a)=>{"use strict";a.d(t,{CF:()=>i,Fv:()=>n,XR:()=>s,gs:()=>o});var r=a(38234);let n=1080,i=1920;function s(e,t,a={}){e.width=n,e.height=i;let o=e.getContext("2d");if(!o)throw Error("Canvas rendering is unavailable");let l=(0,r.ON)(a.theme??t.theme),d=!a.theme&&!t.theme,c=e=>`${e}px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,u=t.messages.slice(0,a.visibleCount??t.messages.length).map(e=>{let t,r=36;do{if(o.font=c(r),t=function(e,t){let a=[];for(let r of t.split("\n")){let t="";
106for(let n of r.split(/\s+/).filter(Boolean))for(let r of(t&&e.measureText(`${t} ${n}`).width>696&&(a.push(t),t=""),Array.from((t?" ":"")+n)))t&&e.measureText(t+r).width>696&&(a.push(t),t=""),t+=r;a.push(t)}return a}(o,e.text),a.fullHeight||t.length*r*1.34+36<=1380)break;r-=2}while(r>12);return{message:e,size:r,lines:t,width:Math.max(220,Math.min(760,Math.max(...t.map(e=>o.measureText(e).width))+64)),height:Math.max(84,t.length*r*1.34+36)}});a.typingSide&&u.push({message:{side:a.typingSide,sender:"",text:""},size:36,lines:[],width:180,height:84});let p=u.reduce((e,t)=>e+t.height+20,0);a.fullHeight&&(e.height=Math.max(1350,285+p+80)),o.fillStyle=l.background,o.fillRect(0,0,e.width,e.height),o.fillStyle=l.header,o.fillRect(0,0,e.width,210),o.fillStyle=d?"#636366":l.incoming,o.beginPath(),o.arc(540,75,44,0,2*Math.PI),o.fill(),o.fillStyle=d?"#ffffff":(0,r.c_)(l.incoming),o.font=`700 ${c(38)}`,o.textAlign="center",o.textBaseline="middle",o.fillText((t.contactName[0]??"?").toUpperCase(),540,77),o.fillStyle=(0,r.c_)(l.header),o.font=`600 ${c(30)}`,o.fillText(t.contactName,540,154),o.textAlign="left",o.textBaseline="alphabetic";let m=0,h=p;for(;m<u.length-1&&h>e.height-365;)h-=u[m].height+20,m+=1;let f=285;u.slice(m).forEach((e,t,a)=>{let n="me"===e.message.side,i=n?1008-e.width:72,s=t===a.length-1,u=n?d&&!s?"#0866bf":l.outgoing:l.incoming;if(o.fillStyle=u,!function(e,t,a,r,n,i=34){e.beginPath(),e.moveTo(t+i,a),e.lineTo(t+r-i,a),e.quadraticCurveTo(t+r,a,t+r,a+i),e.lineTo(t+r,a+n-i),e.quadraticCurveTo(t+r,a+n,t+r-i,a+n),e.lineTo(t+i,a+n),e.quadraticCurveTo(t,a+n,t,a+n-i),e.lineTo(t,a+i),e.quadraticCurveTo(t,a,t+i,a),e.closePath(),e.fill()}(o,i,f,e.width,e.height),o.fillStyle=d?s?"#f5f5f7":"#c3c3c8":(0,r.c_)(u),o.font=c(e.size),0===e.lines.length)for(let e=0;e<3;e++)o.beginPath(),o.arc(i+54+36*e,f+42,10,0,2*Math.PI),o.fill();else e.lines.forEach((t,a)=>o.fillText(t,i+32,f+e.size+14+a*e.size*1.34));f+=e.height+20})}async function o(e,t={}){let a=document.createElement("canvas");return s(a,e,t),new Promise((e,t)=>a.toBlob(a=>a?e(a):t(Error("PNG export failed")),"image/png"))}},92602:(e,t,a)=>{"use strict";function r(){if("u"<typeof ReadableStream||"u"<typeof Symbol||void 0===Symbol.asyncIterator)return"unavailable";let e=ReadableStream.prototype;if("function"==typeof e[Symbol.asyncIterator])return"native";if("function"!=typeof e.getReader)return"unavailable";try{return Object.defineProperty(ReadableStream.prototype,Symbol.asyncIterator,{value:function(){let e=this.getReader(),t=!1,a=!1,r=()=>{a||(a=!0,e.releaseLock())};return{async next(){if(t)return{done:!0,value:void 0};try{let a=await e.read();if(a.done)return t=!0,r(),{done:!0,value:void 0};return{done:!1,value:a.value}}catch(e){throw t=!0,r(),e}},async return(a){if(!t){t=!0;try{await e.cancel()}finally{r()}}return{done:!0,value:a}},async throw(a){if(!t){t=!0;try{await e.cancel(a)}finally{r()}}throw a},[Symbol.asyncIterator](){return this}}},configurable:!0,writable:!0}),"polyfilled"}catch{return"unavailable"}}a.d(t,{Tk:()=>c,W3:()=>r,cF:()=>s,dx:()=>o,hd:()=>l,oR:()=>p,yH:()=>d});let n="https://cdn.jsdelivr.net/npm/[email protected]/dist/",i=`${n}ort.all.min.js`;function s(){return"u">typeof navigator&&"gpu"in navigator}async function o(){if(!s())return{supported:!1,shaderF16:!1};try{let e=await navigator.gpu.requestAdapter();if(!e)return{supported:!1,shaderF16:!1};let t=e.features?.has?.("shader-f16")===!0;return{supported:!0,shaderF16:t}}catch{return{supported:!1,shaderF16:!1}}}function l(e){return"gpu"===e&&s()?"webgpu":"wasm"}function d(e,t="cpu"){try{let t=window.localStorage.getItem(e);if("cpu"===t||"gpu"===t)return t}catch{}return t}function c(e,t){try{window.localStorage.setItem(e,t)}catch{}}let u=null;async function p(){await (u||("u"<typeof document?Promise.resolve():u=new Promise((e,t)=>{let a=document.querySelector(`script[src="${i}"]`);if(a)return void("true"===a.getAttribute("data-ort-loaded")?e():(a.addEventListener("load",()=>e(),{once:!0}),a.addEventListener("error",()=>t(Error("Failed to load ONNX runtime script")),{once:!0})));let r=document.createElement("script");r.src=i,r.async=!0,r.setAttribute("data-ort-script","true"),r.onload=()=>{r.setAttribute("data-ort-loaded","true"),e()},r.onerror=()=>t(Error("Failed to load ONNX runtime script")),document.head.appendChild(r)})));let e=globalThis.ort;if(!e)throw Error("onnxruntime-web global (ort) was not found after loading the CDN script");try{var t,a;e.env?.wasm&&(e.env.wasm.wasmPaths=n,e.env.wasm.numThreads=(t="u">typeof self&&!0===self.crossOriginIsolated,a="u">typeof navigator?navigator.hardwareConcurrency:void 0,t?Math.min(4,Math.max(1,"number"==typeof a&&Number.isFinite(a)?Math.floor(a):1)):1),e.env.wasm.proxy=!1)}catch{}return e}},95713:(e,t,a)=>{"use strict";function r(e){let t=e?.facelessStoryboard?.plan,a=Array.isArray(t?.scenes)?t.scenes:[];if(0===a.length)return[];let r=new Set(e?.facelessStoryboard?.detachedPlanSceneIds??[]),n=new Set;for(let t of e?.scenes??[])t.facelessPlanSceneId&&!t.facelessPlaceholder&&n.add(t.facelessPlanSceneId);
106if(0===n.size&&(e?.scenes??[]).some(e=>e.source?.platform==="faceless-generator"&&!e.facelessPlaceholder))return[];let i=[];for(let e of a){let t="string"==typeof e.id?e.id:null;if(!t||r.has(t)||n.has(t))continue;let a="string"==typeof e.narrationText?e.narrationText:"";i.push({planSceneId:t,narrationPreview:a.split(/\s+/).slice(0,8).join(" "),isRankCard:!0===e.isRankCard})}return i}function n(e){let t=e.length,a=e.map(e=>e.narrationPreview).filter(Boolean).slice(0,2).map(e=>`"${e}â¦"`).join(", ");return`${t} ${1===t?"scene":"scenes"} from your Video Studio plan ${1===t?"is":"are"} missing from the timeline${a?` (${a})`:""} - usually because generation failed. Exporting now would leave frozen or black gaps in the video. Open the Studio to regenerate the failed scenes (try a different image model if one keeps declining), or delete them from the plan, then export again.`}a.d(t,{I:()=>r,Q:()=>n})}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.