1import{c as ha,j as e,X as os,L as Je,D as aa,C as xa,F as qt,a as Ir,S as as,u as pa,q as Yo,d as Rs,s as Bs,v as fa,O as bl,Q as wl,T as vl,V as Gr,aB as yl,t as jl}from"./index-B0cTFD4s.js";import{r as n,i as Nl,h as _l,d as kl,L as Sr}from"./router-BvNiAcqA.js";import{u as js}from"./useQuery-CwHyibto.js";import{k as fo,m as Sl,b as Jo,n as Ml,f as Cl,g as mr,o as oa,q as El,u as Rl,a as $l,i as Tl,t as Fl,v as Al,w as Yr,j as Il,x as Ll,y as Dl,e as Pl,z as lr,A as Ol,B as Ul,C as Vn,D as Gn,r as Yn,E as zl,F as Bl,G as Wl,H as Hl,I as ql,d as mo,J as Vl,K as Gl,L as Yl}from"./narrativeApi-BeIEiIbn.js";import{C as ia,H as Jl,a as go,I as Jr,B as Xl,b as bo,p as Kl,d as Zl}from"./BridgeBadge-Cza0aXMZ.js";import{A as Tr,f as Ql,a as wo,u as ec,V as tc}from"./uploadWithProgress-DPIR_lRH.js";import{M as sc,m as rc}from"./MusicBedPicker-B4YEVYxq.js";import{M as wr}from"./maximize-2-nfwPVS5w.js";import{R as Ar}from"./rotate-ccw-Bb3RUMmK.js";import{M as Ws}from"./music-CMLcx6K_.js";import{M as Jn}from"./minus-CV80Rx-e.js";import{P as Hs}from"./plus-BHN4nwWB.js";import{G as nc}from"./gauge--cLQadVd.js";import{P as ac}from"./PreRenderApprovalCard-DXYYpnYL.js";import{a as Gs,A as Vs,S as Mr,V as ma,b as oc,I as qs,u as vr,i as Ns,s as ln,P as ic}from"./index-46Wq5223.js";import{R as lc,O as vo}from"./ReframedAsset-B1EDYQOF.js";import{e as cc}from"./publishQueue-bdFuhfqi.js";import{R as cn}from"./refresh-cw-k2tYyOAG.js";import{S as dc}from"./shuffle-B0Yx69lr.js";import{S as uc}from"./send-BTgF3tZL.js";import{S as gr}from"./scissors-CqA5taLM.js";import{T as Xo}from"./trash-2-C3hfL2UI.js";import{P as hc}from"./pencil-CoNi1RzT.js";import{P as _s}from"./play-CIwHwlPC.js";import{I as $s}from"./image-EtJcywam.js";import{M as xc}from"./mic-C4mutK2Z.js";import{L as pc}from"./languages-BmEBD1wx.js";import{u as fc}from"./resumableUpload-DnXZmAA7.js";import{a as mc}from"./audioExtract-CDpZJN99.js";import{U as gc}from"./upload-gNxY4UoN.js";import{C as Ko}from"./crop-IWn9PSJx.js";import{Z as Zo}from"./zoom-out-_cxr6xlp.js";import{Z as Qo}from"./zoom-in-DO6ArSg-.js";import{P as la}from"./pause-PZq9Dma3.js";import{S as bc}from"./search-lw11B4IW.js";import{C as yo}from"./cloud-upload-BphtLxOk.js";import{M as wc}from"./minimize-2-sX2kDcRE.js";import{A as vc}from"./index-DtTjESH9.js";import{g as Cr}from"./proxy-_ndGpe3j.js";import{B as ei,D as yc}from"./brollStyles-BUMzZRV2.js";import{C as Xn}from"./chevron-left-CzvR3Mam.js";import{L as cr}from"./layout-grid-Dn48f7L0.js";import{F as jo}from"./file-text-D2QosKHb.js";import{C as No}from"./captions-PqSiw54S.js";import{V as jc}from"./volume-2-B85ZnKHq.js";import{T as _o}from"./triangle-alert-CRH383iB.js";import"./power-Z3dxv99P.js";import"./copy-4Sc5CU5R.js";import"./lock-BOosGLvN.js";import"./index-RF0-oCdM.js";/** 2 * @license lucide-react v0.451.0 - ISC 3 * 4 * This source code is licensed under the ISC license. 5 * See the LICENSE file in the root directory of this source tree. 6 */const Nc=ha("CirclePlay",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polygon",{points:"10 8 16 12 10 16 10 8",key:"1cimsy"}]]);/** 7 * @license lucide-react v0.451.0 - ISC 8 * 9 * This source code is licensed under the ISC license. 10 * See the LICENSE file in the root directory of this source tree. 11 */const _c=ha("Magnet",[["path",{d:"m6 15-4-4 6.75-6.77a7.79 7.79 0 0 1 11 11L13 22l-4-4 6.39-6.36a2.14 2.14 0 0 0-3-3L6 15",key:"1i3lhw"}],["path",{d:"m5 8 4 4",key:"j6kj7e"}],["path",{d:"m12 15 4 4",key:"lnac28"}]]);/** 12 * @license lucide-react v0.451.0 - ISC 13 * 14 * This source code is licensed under the ISC license. 15 * See the LICENSE file in the root directory of this source tree. 16 */const kc=ha("MoveHorizontal",[["path",{d:"m18 8 4 4-4 4",key:"1ak13k"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}]]),dn=s=>Math.max(0,Math.min(1,s)),ti=s=>Math.max(1,Math.min(5,s));function si(s){const i={width:"100%",height:"100%",objectFit:"cover"};if(!s)return i;const c=dn(s.x??.5)*100,u=dn(s.y??.5)*100;return{...i,objectPosition:`${c}% ${u}%`,transform:`scale(${ti(s.scale??1)})`,transformOrigin:`${c}% ${u}%`}}const Kn=s=>s.scale<=1.001&&Math.abs(s.x-.5)<.005&&Math.abs(s.y-.5)<.005;function Sc({assetUrl:s,boxAR:i,crop:c,indexLabel:u,onChange:p,onClose:m}){const[v,_]=n.useState({scale:(c==null?void 0:c.scale)??1,x:(c==null?void 0:c.x)??.5,y:(c==null?void 0:c.y)??.5}),O=n.useRef(v),Q=n.useRef(null),q=n.useRef(null),F=n.useRef(null),E=W=>{F.current&&clearTimeout(F.current),F.current=setTimeout(()=>p(Kn(W)?void 0:W),300)},w=W=>{F.current&&(clearTimeout(F.current),F.current=null),p(Kn(W)?void 0:W)},H=(W,S=!1)=>{const A={scale:ti(W.scale),x:dn(W.x),y:dn(W.y)};O.current=A,_(A),S?w(A):E(A)};n.useEffect(()=>{const W=S=>{S.key==="Escape"&&m()};return window.addEventListener("keydown",W),()=>{if(window.removeEventListener("keydown",W),F.current){clearTimeout(F.current);const S=O.current;p(Kn(S)?void 0:S)}}},[]);const B=W=>{const S=q.current,A=Q.current;if(!S||!A)return;const k=A.getBoundingClientRect(),xe=(W.clientX-S.sx)/k.width,Le=(W.clientY-S.sy)/k.height;H({scale:O.current.scale,x:S.ox-xe,y:S.oy-Le})},K=()=>{q.current=null,window.removeEventListener("pointermove",B),window.removeEventListener("pointerup",K),w(O.current)},h=W=>{W.preventDefault(),q.current={ox:v.x,oy:v.y,sx:W.clientX,sy:W.clientY},window.addEventListener("pointermove",B),window.addEventListener("pointerup",K)},V=W=>{W.preventDefault(),H({...v,scale:v.scale+(W.deltaY<0?.12:-.12)}
16)},ee=()=>{const W={scale:1,x:.5,y:.5};O.current=W,_(W),w(W)},se=Math.round(v.scale*100);return e.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/80 backdrop-blur-sm p-6",onClick:m,children:e.jsxs("div",{className:"relative flex flex-col gap-3 max-w-[92vw]",onClick:W=>W.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wr,{className:"w-4 h-4 text-cyan-300"}),e.jsxs("span",{className:"text-sm font-bold text-white",children:["Teaser image",u?` · ${u}`:""]}),e.jsx("span",{className:"text-[11px] text-white/40",children:"drag to pan · scroll or slider to zoom"}),e.jsx("button",{onClick:m,title:"Done",className:"ml-auto w-7 h-7 rounded-lg bg-white/8 border border-white/15 text-white/60 hover:text-white flex items-center justify-center",children:e.jsx(os,{className:"w-4 h-4"})})]}),e.jsx("div",{ref:Q,onPointerDown:h,onWheel:V,className:"relative overflow-hidden rounded-2xl border-[3px] border-white/90 bg-black shadow-2xl cursor-grab active:cursor-grabbing select-none mx-auto",style:{aspectRatio:String(i),height:"min(70vh, 560px)",maxWidth:"92vw"},children:e.jsx("img",{src:s,alt:"",draggable:!1,style:si(v)})}),e.jsxs("div",{className:"flex items-center gap-3 px-1",children:[e.jsxs("span",{className:"text-[11px] font-bold text-white/55 w-12",children:[se,"%"]}),e.jsx("input",{type:"range",min:1,max:4,step:.02,value:v.scale,onChange:W=>H({...v,scale:parseFloat(W.target.value)}),onPointerUp:()=>w(v),className:"flex-1 accent-cyan-400"}),e.jsxs("button",{onClick:ee,className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-white/8 border border-white/15 text-white/60 hover:text-white text-[11px] font-bold",children:[e.jsx(Ar,{className:"w-3 h-3"})," Reset"]})]})]})})}const ko=.25,Mc=s=>`${Math.floor(s/60)}:${String(Math.floor(s%60)).padStart(2,"0")}.${String(Math.round(s%1*10))}`;function So(s,i,c){var m,v;const u=((m=s.transcript[0])==null?void 0:m.start_sec)??0,p=_=>Math.max(0,+(u+i+(_-u)*c).toFixed(3));return{transcript:s.transcript.map(_=>({..._,start_sec:p(_.start_sec),end_sec:p(_.end_sec)})),words:(v=s.words)==null?void 0:v.map(_=>({..._,start:p(_.start),end:p(_.end)}))}}function Cc({transcript:s,words:i,onApply:c,onSeek:u,onSaveAndRerender:p,onReset:m,rerendering:v,dirty:_,lyricsEnabled:O,onToggleLyrics:Q}){const[q,F]=n.useState(0),[E,w]=n.useState(1),[H,B]=n.useState("0"),[K,h]=n.useState("1"),V=$=>Math.max(-30,Math.min(30,Math.round($*100)/100)),ee=$=>Math.max(.5,Math.min(1.8,Math.round($*100)/100)),se=n.useRef({transcript:s,words:i}),W=n.useRef(s);n.useEffect(()=>{s!==W.current&&(se.current={transcript:s.map($=>({...$})),words:i==null?void 0:i.map($=>({...$}))},W.current=s,F(0),w(1),B("0"),h("1"))},[s,i]);const S=n.useRef({timer:null,pending:null}),A=()=>{const $=S.current.pending;if(S.current.pending=null,!$)return;const te=So(se.current,$.off,$.str);W.current=te.transcript,c(te.transcript,te.words)},k=($,te)=>{S.current.pending={off:$,str:te},S.current.timer==null&&(A(),S.current.timer=setTimeout(()=>{S.current.timer=null,S.current.pending!=null&&A()},90))};n.useEffect(()=>()=>{S.current.timer&&clearTimeout(S.current.timer)},[]);const xe=($,te)=>{const ue=V($);F(ue),te&&B(String(ue)),k(ue,E)},Le=($,te)=>{const ue=ee($);w(ue),te&&h(String(ue)),k(q,ue)},qe=($,te)=>{var Oe;const ue=se.current,st=ue.transcript[$];if(!st)return;const be=+(te*ko/(E||1)).toFixed(4),Ce=st.start_sec,he=st.end_sec;ue.transcript=ue.transcript.map((Ee,L)=>L===$?{...Ee,start_sec:Math.max(0,+(Ee.start_sec+be).toFixed(3)),end_sec:+(Ee.end_sec+be).toFixed(3)}:Ee),ue.words=(Oe=ue.words)==null?void 0:Oe.map(Ee=>{const L=(Ee.start+Ee.end)/2;return L>=Ce-.001&&L<=he+.001?{...Ee,start:Math.max(0,+(Ee.start+be).toFixed(3)),end:Math.max(0,+(Ee.end+be).toFixed(3))}:Ee});const Qe=So(ue,q,E);W.current=Qe.transcript,c(Qe.transcript,Qe.words)},fe=()=>{F(0),w(1),B("0"),h("1"),m()},Ae="w-7 h-7 flex items-center justify-center rounded-md bg-white/8 border border-white/15 text-white/70 hover:text-white hover:bg-white/15 transition-colors shrink-0",R="w-16 text-center font-mono bg-white/5 border border-white/15 rounded px-1 py-0.5 text-[12px] focus:outline-none focus:border-white/40";return e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ws,{className:"w-4 h-4 text-pink-300"}),e.jsx("h2",{className:"text-sm font-bold text-white",children:"Caption timing"}),e.jsxs("button",{onClick:()=>Q(!O),title:O?"Turn off lyrics â next render has no captions":"Turn on lyrics â captions bake into the render",className:`ml-2 flex items-center gap-1.5 px-2 py-0.5 rounded-md border text-[10px] font-bold transition-colors ${O?"bg-pink-500/20 border-pink-400/40 text-pink-200 hover:bg-pink-500/30":"bg-white/[0.04] border-white/15 text-white/40 hover:text-white/70"}`,children:[e.jsx("span",{className:`relative w-6 h-3 rounded-full border transition-colors ${O?"bg-pink-400/80 border-pink-300/50":"bg-white/15 border-white/20"}`,children:e.jsx("span",{className:`absolute top-px w-2 h-2 rounded-full bg-white shadow transition-all ${O?"left-[12px]":"left-px"}`})}),O?"Lyrics on":"Lyrics off"]}),_&&e.jsxs("button",{onClick:fe,title:"Undo all manual timing and restore the original lyric sync",className:"ml-auto flex items-center gap-1 px-2 py-0.5 rounded-md bg-white/8 border border-white/15 text-white/55 hover:text-white text-[10px] font-bold transition-colors",children:[e.jsx(Ar,{className:"w-3 h-3"})," Reset"]})]}),e.jsxs("p",{className:"text-[11px] text-white/40 leading-snug",children:["Lyrics use the song's pacing. ",e.jsx("span",{className:"text-white/60",children:"1)"})," Set ",e.jsx("span",{className:"text-pink-300 font-semibold",children:"Anchor"})," so line 1 lands on the first sung word. ",e.jsx("span",{className:"text-white/60",children:"2)"})," If the end drifts, adjust ",e.jsx("span",{className:"text-cyan-300 font-semibold",children:"Speed"})," until the last line matches. Then re-render."]}),e.jsxs("div",{className:"flex flex-col gap-1.5 rounded-lg bg-white/[0.03] border border-white/10 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[11px] font-bold text-white/70",children:"Anchor (line 1)"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>xe(q-.1,!0),title:"â0.1s",className:Ae,children:e.jsx(Jn,{className:"w-3 h-3"})}),e.jsx("input",{type:"number",step:.01,min:-30,max:30,value:H,onChange:$=>{B($.target.value);const te=parseFloat($.target.value);Number.isFinite(te)&&xe(te,!1)},onBlur:()=>B(String(q)),className:`${R} text-pink-300`}),e.jsx("span",{className:"text-white/40 text-[10px]",children:"s"}),e.jsx("button",{onClick:()=>xe(q+.1,!0),title:"+0.1s",className:Ae,children:e.jsx(Hs,{className:"w-3 h-3"})})]})]}),e.jsx("input",{type:"range",min:-30,max:30,step:.01,value:q,onChange:$=>xe(parseFloat($.target.value),!0),className:"w-full accent-pink-400"}),e.jsxs("div",{className:"flex justify-between text-[9px] text-white/30 font-mono",children:[e.jsx("span",{children:"â30s (earlier)"}),e.jsx("span",{children:"0"}),e.jsx("span",{children:"+30s (later)"})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5 rounded-lg bg-white/[0.03] border border-white/10 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-[11px] font-bold text-white/70 flex items-center gap-1.5",children:[e.jsx(nc,{className:"w-3.5 h-3.5 text-cyan-300"})," Speed (spacing)"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>Le(E-.1,!0),title:"â0.1Ã",className:Ae,children:e.jsx(Jn,{className:"w-3 h-3"})}),e.jsx("input",{type:"number",step:.01,min:.5,max:1.8,value:K,onChange:$=>{h($.target.value);const te=parseFloat($.target.value);Number.isFinite(te)&&Le(te,!1)},onBlur:()=>h(String(E)),className:`${R} text-cyan-300`}),e.jsx("span",{className:"text-white/40 text-[10px]",children:"Ã"}),e.jsx("button",{onClick:()=>Le(E+.1,!0),title:"+0.1Ã",className:Ae,children:e.jsx(Hs,{className:"w-3 h-3"})})]})]}),e.jsx("input",{type:"range",min:.5,max:1.8,step:.01,value:E,onChange:$=>Le(parseFloat($.target.value),!0),className:"w-full accent-cyan-400"}),e.jsxs("div",{className:"flex justify-between text-[9px] text-white/30 font-mono",children:[e.jsx("span",{children:"0.5à (faster)"}),e.jsx("span",{children:"1Ã"}),e.jsx("span",{children:"1.8à (slower)"})]})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("span",{className:"text-[10px] font-black text-white/40 uppercase tracking-widest",children:["Per-line nudge (±",ko,"s)"]}),e.jsx("div",{className:"flex flex-col gap-1 max-h-[38vh] overflow-y-auto thin-scroll pr-1",children:s.map(($,te)=>e.jsxs("div",{className:"flex items-center gap-2 rounded-lg bg-white/[0.03] border border-white/[0.06] px-2 py-1.5",children:[e.jsx("button",{onClick:()=>u($.start_sec),title:"Seek preview here",className:"font-mono text-[10px] text-cyan-300 hover:text-cyan-100 shrink-0 w-12 text-left",children:Mc($.start_sec)}),e.jsx("span",{className:"flex-1 text-[11px] text-white/75 truncate",title:$.text,children:$.text}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx("button",{onClick:()=>qe(te,-1),title:"Earlier",className:"w-6 h-6 flex items-center justify-center rounded-md bg-white/8 border border-white/15 text-white/60 hover:text-white transition-colors",children:e.jsx(Jn,{className:"w-3 h-3"})}),e.jsx("button",{onClick:()=>qe(te,1),title:"Later",className:"w-6 h-6 flex items-center justify-center rounded-md bg-white/8 border border-white/15 text-white/60 hover:text-white transition-colors",children:e.jsx(Hs,{className:"w-3 h-3"})})]})]},te))})]}),e.jsxs("button",{onClick:p,disabled:v,title:"Persist the adjusted caption timing and render the final video",className:"flex items-center justify-center gap-1.5 py-2 rounded-lg bg-gradient-to-r from-pink-600 to-violet-600 hover:from-pink-500 hover:to-violet-500 disabled:opacity-40 disabled:cursor-not-allowed text-white text-xs font-bold transition-all",children:[v?e.jsx(Je,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Ws,{className:"w-3.5 h-3.5"}),"Save & re-render"]})]})}const Ec=2.4;function ga(s,i){const c=(i||[]).filter(v=>v.end>v.start&&v.start<s).map(v=>({start:Math.max(0,v.start),end:Math.min(s,v.end)})).sort((v,_)=>v.start-_.start),u=[];let p=0,m=0;for(const v of c)v.start>
16p+.001&&(u.push({os:p,oe:v.start,co:m}),m+=v.start-p),p=Math.max(p,v.end);return p<s-.001&&(u.push({os:p,oe:s,co:m}),m+=s-p),{kept:u,compressedDur:m}}function ca(s){return i=>{for(const u of s){if(i>=u.os-.001&&i<=u.oe+.001)return u.co+(i-u.os);if(i<u.os)return u.co}const c=s[s.length-1];return c?c.co+(c.oe-c.os):0}}function Mo(s,i){return(s||[]).some(c=>i>c.start+.001&&i<c.end-.001)}function Rc(s,i){if(s!=null&&s.length)return s;const c=[];for(const u of i??[]){const p=u.text.trim().split(/\s+/).filter(Boolean),m=Math.max(.001,u.end_sec-u.start_sec);p.forEach((v,_)=>c.push({word:v,start:u.start_sec+_/p.length*m,end:u.start_sec+(_+1)/p.length*m}))}return c}function ri(s,i){let c=s;for(const u of i||[])c=Math.max(c,(u.start_sec||0)+(u.dur_sec||0));return c}function ni(s,i){return ga(s,i||[]).compressedDur}function $c(s,i,c){const{kept:u}=ga(s,i||[]);return ca(u)(c)}const Fr={width:"100%",height:"100%",objectFit:"cover"},ai="'Arial Black', Inter, 'Segoe UI', Impact, sans-serif",oi="#ffe14d";function Tc(s,i){const c=s.map(m=>({s:m.start_sec,e:m.start_sec+m.dur_sec})).sort((m,v)=>m.s-v.s),u=[];let p=0;for(const m of c)m.s>p&&u.push({start:p,end:Math.min(m.s,i)}),p=Math.max(p,m.e);return p<i&&u.push({start:p,end:i}),u}function Fc(s){return s&&(s.type==="zoom_in"||s.type==="zoom_out")?{...s,start_scale:Math.max(1,s.start_scale??1),end_scale:Math.max(1,s.end_scale??1.1)}:s&&(s.type==="pan_left"||s.type==="pan_right")?s:{type:"ken_burns",crop_hint:"center",start_scale:Math.max(1.05,(s==null?void 0:s.start_scale)??1),end_scale:Math.max(1.12,(s==null?void 0:s.end_scale)??1.12)}}function Zn(s,i,c,u){const p=Math.min(1,u/c),m=Math.min(1,c/u),v=Q=>Math.max(0,Math.min(1,Q)),_=p<.999?v((s-p/2)/(1-p)):.5,O=m<.999?v((i-m/2)/(1-m)):.5;return{x:_*100,y:O*100}}function Ac({motion:s,photoSrc:i,videoSrc:c,startFromF:u,endAtF:p,volume:m,forceStill:v}){const _=vr(),{durationInFrames:O,fps:Q,width:q,height:F}=Gs(),E=Math.max(1,O-1),w=Math.max(1,E-Math.round((s.hold_sec??0)*Q)),H=Math.min(w-1,Math.max(0,Math.round((s.hold_start_sec??0)*Q))),B={extrapolateLeft:"clamp",extrapolateRight:"clamp"},K=F>0?q/F:9/16,[h,V]=n.useState(0),ee=Math.max(1,s.start_scale??1),se=Math.max(ee,s.end_scale??ee),W=Ns(_,[H,w],[ee,se],B),S=typeof s.focus_to_x=="number"&&typeof s.focus_to_y=="number",A=S?Ns(_,[H,w],[s.focus_x,s.focus_to_x],B):s.focus_x??.5,k=S?Ns(_,[H,w],[s.focus_y,s.focus_to_y],B):s.focus_y??.5;let xe;if(h>0){const fe=Math.min(1,h/K),Ae=F*W/fe,R=Ae*h,$=q/2-A*R,te=F/2-k*Ae;xe={position:"absolute",width:R,height:Ae,left:$,top:te,maxWidth:"none"}}else xe={width:"100%",height:"100%",objectFit:"cover"};const Le=fe=>{const Ae=fe.currentTarget;Ae.naturalWidth&&Ae.naturalHeight&&V(Ae.naturalWidth/Ae.naturalHeight)},qe=fe=>{const Ae=fe.currentTarget;Ae.videoWidth&&Ae.videoHeight&&V(Ae.videoWidth/Ae.videoHeight)};return e.jsx(Vs,{style:{overflow:"hidden"},children:c?v?e.jsx(qs,{src:un(c,+(u/Q).toFixed(2)),style:xe,onLoad:Le,onError:fe=>{fe.currentTarget.style.visibility="hidden"}}):e.jsxs(e.Fragment,{children:[e.jsx(qs,{src:un(c,+(u/Q).toFixed(2)),style:xe,onLoad:Le,onError:fe=>{fe.currentTarget.style.visibility="hidden"}}),e.jsx(ma,{src:c,startFrom:u,endAt:p,muted:m==null,...m!=null?{volume:m}:{},style:{...xe,position:"absolute"},onError:()=>{},onLoadedMetadata:qe})]}):e.jsx(qs,{src:i,style:xe,onLoad:Le,onError:fe=>{fe.currentTarget.style.visibility="hidden"}})})}const un=(s,i)=>`/v1/assembly/thumb?kind=video&url=${encodeURIComponent(s)}${i?`&t=${i.toFixed(2)}`:""}`,Ic=s=>/\.mov(\?|$)/i.test(s);function ii({src:s,style:i,startFromF:c,endAtF:u,volume:p,onAR:m,forceStill:v}){const{fps:_}=Gs(),[O,Q]=n.useState(!1),[q,F]=n.useState(!1),[E,w]=n.useState(null),H=+(c/_).toFixed(2);if(v)return e.jsx(Vs,{children:!q&&e.jsx(qs,{src:un(s,H),style:i,onError:()=>F(!0),onLoad:h=>{const V=h.currentTarget;V.naturalWidth&&V.naturalHeight&&(m==null||m(V.naturalWidth/V.naturalHeight))}})});const B=E?E.from:c,K=E?E.to:u;return e.jsxs(Vs,{children:[!q&&e.jsx(qs,{src:un(s,H),style:i,onError:()=>F(!0),onLoad:h=>{const V=h.currentTarget;
16V.naturalWidth&&V.naturalHeight&&(m==null||m(V.naturalWidth/V.naturalHeight))}}),!O&&e.jsx(ma,{src:s,...p!=null?{volume:p}:{muted:!0},startFrom:B,endAt:K,style:{...i,position:"absolute",inset:0},onError:()=>Q(!0),onLoadedMetadata:h=>{const V=h.currentTarget;V.videoWidth&&V.videoHeight&&(m==null||m(V.videoWidth/V.videoHeight));const ee=Math.round((V.duration||0)*_);ee>1&&c>=ee-1&&w({from:0,to:Math.min(Math.max(1,u-c),ee)})}})]})}function Lc({motion:s,photoSrc:i,videoSrc:c,startFromF:u,endAtF:p,forceStill:m}){const v=vr(),{durationInFrames:_,fps:O,width:Q,height:q}=Gs(),F=Math.max(1,_-1),E=Math.max(1,F-Math.round((s.hold_sec??0)*O)),w=Math.min(E-1,Math.max(0,Math.round((s.hold_start_sec??0)*O))),H={extrapolateLeft:"clamp",extrapolateRight:"clamp"},B=q>0?Q/q:9/16,[K,h]=n.useState(0),V=fe=>Math.max(0,Math.min(100,fe)),ee=typeof s.focus_x=="number"&&typeof s.focus_y=="number",se=ee&&typeof s.focus_to_x=="number"&&typeof s.focus_to_y=="number";let W,S,A,k;if(se){if(K>0){const fe=Zn(s.focus_x,s.focus_y,K,B),Ae=Zn(s.focus_to_x,s.focus_to_y,K,B);W=fe.x,S=Ae.x,A=fe.y,k=Ae.y}else W=V(s.focus_x*100),S=V(s.focus_to_x*100),A=V(s.focus_y*100),k=V(s.focus_to_y*100);s.type==="pan_left"&&W<S&&([W,S]=[S,W],[A,k]=[k,A])}else if(ee){const fe=K>0?Zn(s.focus_x,s.focus_y,K,B):{x:V(s.focus_x*100),y:V(s.focus_y*100)};[W,S]=s.type==="pan_left"?[V(fe.x+14),V(fe.x-14)]:[V(fe.x-14),V(fe.x+14)],A=k=fe.y}else[W,S]=s.type==="pan_left"?[88,12]:[12,88],A=k=50;const xe=Ns(v,[w,E],[W,S],H),Le=Ns(v,[w,E],[A,k],H),qe={width:"100%",height:"100%",objectFit:"cover",objectPosition:`${xe}% ${Le}%`};return e.jsx(Vs,{style:{overflow:"hidden"},children:c?e.jsx(ii,{src:c,forceStill:m,startFromF:u,endAtF:p,style:qe,onAR:h}):e.jsx(qs,{src:i,style:qe,onError:fe=>{fe.currentTarget.style.visibility="hidden"},onLoad:fe=>{const Ae=fe.currentTarget;Ae.naturalWidth&&Ae.naturalHeight&&h(Ae.naturalWidth/Ae.naturalHeight)}})})}function Dc({transcript:s,width:i,arollRanges:c,faceRanges:u=[],posRanges:p=[]}){const m=vr(),{fps:v}=Gs(),_=m/v,O=s.find(k=>_>=k.start_sec&&_<k.end_sec);if(!O)return null;const Q=(O.text||"").trim().split(/\s+/).filter(Boolean);if(!Q.length)return null;const q=Math.max(.001,O.end_sec-O.start_sec),F=Math.min(Q.length-1,Math.floor((_-O.start_sec)/q*Q.length)),E=3,w=Math.floor(F/E),H=Q.slice(w*E,w*E+E),B=F-w*E,K=Math.round((O.start_sec+w*E/Q.length*q)*v),h=ln({frame:Math.max(0,m-K),fps:v,config:{damping:12,stiffness:200,mass:.4},durationInFrames:8}),V=Math.round(i*.082),ee=Math.max(2,Math.round(i*.007)),se=c.some(k=>_>=k.start&&_<k.end),W=u.some(k=>_>=k.start&&_<k.end),S=p.find(k=>_>=k.start&&_<k.end),A=S?S.pos==="top"?22:S.pos==="bottom"?80:50:se||W?74:58;return e.jsx("div",{style:{position:"absolute",left:0,right:0,top:`${A}%`,display:"flex",flexWrap:"wrap",justifyContent:"center",alignItems:"baseline",gap:`${Math.round(i*.009)}px ${Math.round(i*.022)}px`,padding:`0 ${Math.round(i*.06)}px`,transform:`translateY(-50%) scale(${.88+h*.12})`,transformOrigin:"center center",opacity:.2+h*.8},children:H.map((k,xe)=>e.jsx("span",{style:{fontFamily:"Inter, system-ui, sans-serif",fontWeight:900,fontSize:xe===B?Math.round(V*1.1):V,lineHeight:1.05,textTransform:"uppercase",letterSpacing:"-0.01em",color:xe===B?oi:"#fff",WebkitTextStroke:`${ee}px #000`,paintOrder:"stroke fill",textShadow:"0 3px 14px rgba(0,0,0,0.55)",display:"inline-block"},children:k},`${w}-${xe}`))})}function Pc({text:s}){const i=vr(),{fps:c}=Gs(),u=ln({frame:i,fps:c,config:{damping:11,stiffness:130,mass:.6}}),p=Ns(u,[0,1],[.35,1]),m=Ns(u,[0,1],[-7,-3]);let v=s;const _=s.match(/^(\$?)(\d[\d,]*(?:\.\d+)?)(%?.*)$/s);if(_){const O=parseFloat(_[2].replace(/,/g,"")),Q=(_[2].split(".")[1]||"").length,q=ln({frame:i,fps:c,config:{damping:200,stiffness:55,mass:1}}),F=O*q;v=_[1]+(Q>0?F.toFixed(Q):Math.round(F).toLocaleString("en-US"))+_[3]}return e.jsx(Vs,{style:{alignItems:"center",justifyContent:"center"},children:e.jsx("div",{style:{transform:`scale(${p}) rotate(${m}deg)`,fontFamily:ai,fontWeight:900,fontSize:104,color:oi,textTransform:"uppercase",textShadow:"0 5px 0 #c0392b, 0 10px 24px rgba(0,0,0,.6)",WebkitTextStroke:"3px #7a1f12",lineHeight:.95},children:v})})}const Oc=/\.(mov|mp4|m4v|webm|mkv|avi|qt)(\?|$)/i;function li(s){var c;return s?((c=s.items)!=null&&c.length?s.items.map(u=>({url:u.thumbnail_url||u.url,crop:u.crop})):(s.image_urls??[]).map(u=>({url:u,crop:void 0}))).filter(u=>!!u.url&&!Oc.test((u.url||"").split("?")[0])):[]}function Uc(s){return li(s).map(i=>i.url)}function zc(s){if(!s)return Fr;const i=Math.max(0,Math.min(1,s.x??.5))*100,c=Math.max(0,Math.min(1,s.y??.5))*100,u=Math.max(1,s.scale??1);return{...Fr,objectPosition:`${i}% ${c}%`,transform:`scale(${u})`,transformOrigin:`${i}% ${c}%`}}function Bc({teaser:s}){var F,E;const i=vr(),{fps:c}
16=Gs(),u=li(s),p=Math.max(1,Math.round(s.dur_sec*c)),m=Math.max(1,Math.round(p/Math.max(1,u.length))),v=Math.min(u.length-1,Math.floor(i/m)),_=ln({frame:i-v*m,fps:c,config:{damping:200,stiffness:260,mass:.3}}),O=Ns(i,[0,4,p-4,p],[0,1,1,0],{extrapolateLeft:"clamp",extrapolateRight:"clamp"}),Q=typeof s.pos_x=="number"?s.pos_x:.5,q=typeof s.pos_y=="number"?s.pos_y:.47;return e.jsx(Vs,{style:{alignItems:"center",justifyContent:"center",opacity:O},children:e.jsx("div",{style:{position:"absolute",top:`${q*100}%`,left:`${Q*100}%`,transform:`translate(-50%, -50%) scale(${.9+.1*_})`,width:"66%",height:"35%",borderRadius:22,border:"5px solid rgba(255,255,255,.95)",boxShadow:"0 14px 38px rgba(0,0,0,.55)",overflow:"hidden",background:"#000"},children:e.jsx(qs,{src:(F=u[v])==null?void 0:F.url,style:zc((E=u[v])==null?void 0:E.crop),onError:w=>{w.currentTarget.style.visibility="hidden"}})})})}function Wc({label:s,width:i}){const c=vr(),{fps:u,durationInFrames:p}=Gs(),m=c/u,v=p/u,_=Ns(m,[0,.45],[0,1],{extrapolateLeft:"clamp",extrapolateRight:"clamp",easing:E=>1-Math.pow(1-E,3)}),O=Ns(m,[v-.4,v],[1,0],{extrapolateLeft:"clamp",extrapolateRight:"clamp"}),Q=Math.min(_,O),q=Math.round(i*.052),F=Math.round(i*.04);return e.jsx(Vs,{style:{alignItems:"center",justifyContent:"flex-start",paddingTop:"12%",opacity:Q},children:e.jsxs("div",{style:{maxWidth:"82%",padding:`${F*.7}px ${F}px`,borderRadius:Math.round(i*.05),transform:`translateY(${(1-_)*26}px) scale(${.95+.05*_})`,background:"linear-gradient(135deg, rgba(255,255,255,.22), rgba(255,255,255,.07))",border:"1.5px solid rgba(255,255,255,.42)",boxShadow:"0 24px 70px rgba(0,0,0,.5), inset 0 1px 0 rgba(255,255,255,.6)",backdropFilter:"blur(22px)",WebkitBackdropFilter:"blur(22px)",textAlign:"center"},children:[e.jsx("div",{style:{fontFamily:ai,fontWeight:900,fontSize:q,lineHeight:1.1,color:"#fff",textTransform:"uppercase",letterSpacing:"0.01em",textShadow:"0 2px 10px rgba(0,0,0,.45)"},children:s}),e.jsx("div",{style:{height:Math.max(4,Math.round(i*.008)),borderRadius:6,marginTop:F*.45,width:`${72*_}%`,marginLeft:"auto",marginRight:"auto",background:"linear-gradient(90deg,#ff5a5f,#ffb05a)"}})]})})}const Hc=({arollUrl:s,audioUrl:i,muteAroll:c,arollDur:u,brolls:p,transcript:m,words:v,removedRanges:_=[],hook:O,pops:Q,teaser:q,sections:F,h264Urls:E,width:w})=>{const H=n.useMemo(()=>new Set(E??[]),[E]),B=R=>Ic(R)&&!H.has(R),K=R=>H.has(R)?"h":"r",{fps:h,durationInFrames:V}=Gs(),[ee,se]=n.useState(!0);n.useEffect(()=>{se(!0)},[s]);const W=ri(u,p),{kept:S}=ga(W,_),A=ca(S),k=p.map(R=>{const $=A(R.start_sec),te=A(R.start_sec+R.dur_sec);return{b:R,s:$,dur:te-$}}).filter(R=>R.dur>.05);if(!s&&k.length){const R=A(W),$=[...k].sort((te,ue)=>te.s-ue.s);$[0].s>.001&&($[0].s=0);for(let te=0;te<$.length;te++){const ue=te+1<$.length?$[te+1].s:R;ue-$[te].s>$[te].dur&&($[te].dur=ue-$[te].s)}}const xe=Tc(k.map(R=>({...R.b,start_sec:R.s,dur_sec:R.dur})),ca(S)(W)),Le=k.filter(({b:R})=>{var $,te;return typeof(($=R.motion)==null?void 0:$.focus_x)=="number"&&typeof((te=R.motion)==null?void 0:te.focus_y)=="number"}).map(({s:R,dur:$})=>({start:R,end:R+$})),qe=k.filter(({b:R})=>R.caption_pos==="top"||R.caption_pos==="mid"||R.caption_pos==="bottom").map(({b:R,s:$,dur:te})=>({start:$,end:$+te,pos:R.caption_pos})),fe=(()=>{const $=Rc(v,m).filter(be=>!Mo(_,(be.start+be.end)/2)).map(be=>({word:be.word,start:A(be.start),end:A(be.end)})),te=[];let ue=[];const st=()=>{ue.length&&(te.push({start_sec:ue[0].start,end_sec:ue[ue.length-1].end,text:ue.map(be=>be.word).join(" ")}),ue=[])};for(let be=0;be<$.length;be++){ue.push($[be]);const Ce=$[be+1];((Ce?Ce.start-$[be].end:1/0)>.4||ue.length>=5||!Ce)&&st()}return te})(),Ae=(Q??[]).filter(R=>!Mo(_,R.from_sec)).map(R=>({...R,from_sec:A(R.from_sec)}));return e.jsxs(Vs,{style:{backgroundColor:"black"},children:[s&&S.map((R,$)=>e.jsxs(Mr,{from:Math.round(R.co*h),durationInFrames:Math.max(1,Math.round((R.oe-R.os)*h)),children:[ee&&e.jsx(ma,{src:s,startFrom:Math.round(R.os*h),endAt:Math.round(R.oe*h),style:Fr,muted:!0,onError:()=>se(!1)}),!c&&e.jsx(oc,{src:i||s,startFrom:Math.round(R.os*h),endAt:Math.round(R.oe*h)})]},`aroll${$}-${K(s)}`)),k.map(({b:R,s:$,dur:te})=>{var dt;const ue=((dt=R.asset_window)==null?void 0:dt.start)??0,st=Math.round(ue*h),be=Math.round((ue+te)*h),Ce=R.motion??null,he=typeof(Ce==null?void 0:Ce.focus_x)=="number"&&typeof(Ce==null?void 0:Ce.focus_y)=="number",Qe=he&&typeof(Ce==null?void 0:Ce.focus_to_x)=="number"&&typeof(Ce==null?void 0:Ce.focus_to_y)=="number",Oe=he?Ce:Fc(R.motion),Ee=Qe||(Oe.type==="pan_left"||Oe.type==="pan_right")&&!he,L=he&&!Qe,pe=R.audio?Math.min(1,Math.max(0,R.audio.gain??1)):void 0,we=R.type==="broll_video"?R.asset_url:void 0,Ge=R.type==="broll_video"&&B(R.asset_url),et=Ee?e.jsx(Lc,{motion:Oe,photoSrc:R.type==="broll_photo"?R.asset_url:void 0,videoSrc:we,forceStill:Ge,startFromF:st,endAtF:be}):L?e.jsx(Ac,{motion:Oe,photoSrc:R.type==="broll_photo"?R.asset_url:void 0,videoSrc:we,forceStill:Ge,startFromF:st,endAtF:be,volume:pe}):e.jsx(lc,{motion:Oe,children:R.type==="broll_photo"?e.jsx(qs,{src:R.asset_url,style:Fr,onError:Xe=>{Xe.currentTarget.style.visibility="hidden"}}):e.jsx(ii,{src:we,forceStill:Ge,startFromF:st,endAtF:be,style:Fr,volume:pe})});return e.jsx(Mr,{from:Math.round($*h),durationInFrames:Math.max(1,Math.round(te*h)),name:R.id,children:et},R.id)}),q&&Uc(q).length>=2&&e.jsx(Mr,{from:Math.round(A(q.from_sec)*h),durationInFrames:Math.max(1,Math.round(q.dur_sec*h)),children:e.jsx(Bc,{teaser:q})}),Ae.map((R,$)=>e.jsx(Mr,{from:Math.round(R.from_sec*h),durationInFrames:27,children:e.jsx(Pc,{text:R.text})},`pop${$}`)),(F??[]).filter(R=>(R.label||"").trim()).map((R,$)=>{const te=A(Math.max(R.at_sec,.15));return e.jsx(Mr,{from:Math.round(te*h),durationInFrames:Math.max(1,Math.round(Ec*h)),name:`section:${R.label}`,children:e.jsx(Wc,{label:R.label,width:w})},`sec${$}`)}),fe.length>0&&e.jsx(Dc,{transcript:fe,width:w,arollRanges:xe,faceRanges:Le,posRanges:qe})]})};function Co(s){const i=Math.max(0,Math.round(s/1e3));if(i<60)return`~${i}s remaining`;const c=Math.floor(i/60),u=i%60;return`~${c}m ${String(u).padStart(2,"0")}s remaining`}function qc(s){const i=Math.max(0,Math.round(s/1e3));return`${Math.floor(i/60)}:${String(i%60).padStart(2,"0")} elapsed`}function Vc({arollUrl:s,h264Urls:i,audioUrl:c,arollDur:u,videoDurSec:p,brolls:m,transcript:v,words:_,removedRanges:O,hook:Q,pops:q,teaser:F,sections:E,outputFormat:w,playerRef:H,finalVideoRef:B,canUndo:K,onUndo:h,onRerender:V,rerendering:ee,renderElapsedMs:se=0,renderEtaMs:W=0,renderProgress:S=null,render
16Stage:A,hasEdits:k,status:xe,finals:Le,finalMeta:qe,finalView:fe,onSelectFinal:Ae,onCancelRender:R,onRemixVariant:$,renderOnLocal:te=!1,onToggleRenderOnLocal:ue,bridgeAvailable:st=!1,showChapterTitles:be,onToggleChapterTitles:Ce,musicUrl:he,replaceArollAudio:Qe,musicOffsetSec:Oe=0,musicVolume:Ee,sideBySide:L=!1,finalInTray:pe=!1,fill:we=!1}){var ie;const Ge=n.useRef(!1),[et,dt]=n.useState(!1),[Xe,at]=n.useState(0),[Ye,gt]=n.useState(!1),[Ke,tt]=n.useState("preview");n.useEffect(()=>{if(u<=0)return;let G=0,oe=0;const Pe=()=>{const $e=H.current;if($e&&!Ge.current){Ge.current=!0;try{$e.seekTo(1)}catch{}oe=window.setTimeout(()=>gt(!0),900)}else $e||(G=requestAnimationFrame(Pe))};return Pe(),()=>{cancelAnimationFrame(G),clearTimeout(oe)}},[u,H]),n.useEffect(()=>{const G=oe=>{if(oe.code!=="Space"&&oe.key!==" ")return;const Pe=oe.target,$e=Pe==null?void 0:Pe.tagName;if($e==="INPUT"||$e==="TEXTAREA"||$e==="SELECT"||Pe!=null&&Pe.isContentEditable)return;const Te=H.current;if(Te){oe.preventDefault();try{Te.isPlaying()?Te.pause():Te.play()}catch{}}};return document.addEventListener("keydown",G),()=>document.removeEventListener("keydown",G)},[H]);const ut=n.useRef(null),ht=n.useRef(typeof Ee=="number"?Ee:.5);ht.current=typeof Ee=="number"?Ee:.5;const Ve=()=>{var G,oe;try{return!!((oe=(G=H.current)==null?void 0:G.isMuted)!=null&&oe.call(G))}catch{return!1}},D=()=>{var G,oe;try{const Pe=(oe=(G=H.current)==null?void 0:G.getVolume)==null?void 0:oe.call(G);return typeof Pe=="number"?Pe:1}catch{return 1}};n.useEffect(()=>{const G=H.current,oe=ut.current;if(!G||!oe||!he)return;const Pe=()=>{const Wt=Math.max(0,Math.min(1,ht.current));oe.volume=Wt*D(),oe.muted=Wt<=.001||Ve()};Pe();const $e=()=>Pe(),Te=Wt=>Wt/30,ae=(Wt=!1)=>{try{const is=Math.max(0,Te(G.getCurrentFrame())-(Oe||0));(Wt||Math.abs(oe.currentTime-is)>.35)&&(oe.currentTime=is)}catch{}},it=()=>{ae(!0),oe.play().catch(()=>{})},Lt=()=>oe.pause(),St=()=>ae(!0),Vt=()=>{oe.paused||ae(!1)},kt=()=>{oe.pause(),oe.currentTime=0};G.addEventListener("play",it),G.addEventListener("pause",Lt),G.addEventListener("seeked",St),G.addEventListener("frameupdate",Vt),G.addEventListener("ended",kt);try{G.addEventListener("mutechange",$e)}catch{}try{G.addEventListener("volumechange",$e)}catch{}try{G.isPlaying()&&it()}catch{}return()=>{G.removeEventListener("play",it),G.removeEventListener("pause",Lt),G.removeEventListener("seeked",St),G.removeEventListener("frameupdate",Vt),G.removeEventListener("ended",kt);try{G.removeEventListener("mutechange",$e)}catch{}try{G.removeEventListener("volumechange",$e)}catch{}oe.pause()}},[he,H,u,Qe,Oe]),n.useEffect(()=>{const G=ut.current;if(!G)return;const oe=typeof Ee=="number"?Math.max(0,Math.min(1,Ee)):.5;G.volume=oe*D(),G.muted=oe<=.001||Ve()},[Ee,he]);const z=Le.length+(ee?1:0),ye=ee?z-1:-1,je=Math.max(0,Math.min(fe,Math.max(0,z-1))),Z=ee&&je===ye,ke=Z?null:Le[je]??null,Ie=vo[w]??vo["9x16"];n.useEffect(()=>{dt(!1),at(0)},[ke]);const Ue=(()=>{const G=Object.entries(qe||{}).filter(([,Te])=>(Te==null?void 0:Te.createdAt)&&(Te==null?void 0:Te.renderId)),oe=new Map;for(const[Te,ae]of G){const it=oe.get(ae.renderId);it?it.urls.push(Te):oe.set(ae.renderId,{urls:[Te],createdAt:ae.createdAt})}const Pe=[...oe.values()].sort((Te,ae)=>new Date(Te.createdAt).getTime()-new Date(ae.createdAt).getTime()),$e=new Map;return Pe.forEach(({urls:Te},ae)=>{Te.forEach(it=>$e.set(it,ae+1))}),$e})(),ot=new Set(Object.values(qe||{}).map(G=>G==null?void 0:G.renderId).filter(Boolean)).size,jt=ot+(ee?1:0),lt=Z?jt:ke&&Ue.has(ke)?Ue.get(ke):null,vt=ot>0&<!=null,xt=ni(p??ri(u,m),O),Nt=Math.max(1,Math.round(xt*30)),bt=typeof S=="number"&&S>.051,Mt=W>0?se/W:0,wt=Mt>1,yt=bt?Math.min(99,S*100):W>0?Math.min(99,wt?90+(1-Math.exp(-(se-W)/W))*9:Mt*90):0,x=bt&&S>.12&&se>3e4?se*(1-S)/S:null,P=x!=null?Co(x):wt?qc(se):Co(W-se);return e.jsxs("div",{className:`flex gap-4 overflow-y-auto thin-scroll ${we?"p-2 flex-col items-center w-full h-full min-h-0":"p-4"} ${pe?"flex-col items-center w-full h-full min-h-0":L?"flex-row items-start justify-center":we?"":"flex-col items-center shrink-0"}`,style:{width:pe||L||we?void 0:400},children:[pe&&e.jsxs("div",{className:"flex w-full shrink-0 items-center gap-1 rounded-lg border border-white/10 bg-white/[0.03] p-0.5 text-[11px] font-black",children:[e.jsx("button",{onClick:()=>tt("preview"),className:`flex-1 rounded-md px-2 py-1 transition-colors ${Ke==="preview"?"bg-white/15 text-white":"text-white/50 hover:text-white"}`,children:"Preview"}),e.jsxs("button",{onClick:()=>{z>0&&tt("final")},disabled:z===0,className:`flex-1 rounded-md px-2 py-1 transition-colors ${Ke==="final"?"bg-white/15 text-white":"text-white/50 hover:text-white disabled:opacity-30"}`,children:["Final render",z>0?` (${z})`:""]})]}),(!pe||Ke==="preview")&&e.jsxs("div",{className:L&&!pe?"flex w-[400px] max-w-full flex-col items-center gap-3 shrink-0":"contents",children:[e.jsxs("div",{className:`flex flex-col items-center gap-2 ${pe||we?"flex-1 min-h-0 w-full":"w-full"}`,children:[e.jsx("span",{className:"text-[10px] font-black text-white/40 uppercase tracking-widest self-start shrink-0",children:"Preview (in-browser)"}),e.jsxs("div",{className:`relative rounded-xl overflow-hidden border border-white/10 bg-black ${pe||we?"min-h-0 flex-1":""}`,style:{height:pe||we?void 0:"clamp(200px, 58vh, 600px)",maxHeight:pe||we?"100%":void 0,aspectRatio:`${Ie.width} / ${Ie.height}`,maxWidth:"100%"},children:[u>0?e.jsx(ic,{ref:H,component:Hc,inputProps:{arollUrl:s,h264Urls:i,audioUrl:c,muteAroll:Qe,arollDur:u,brolls:m,transcript:v,words:_,removedRanges:O,hook:Q,pops:q,teaser:F,sections:be?E:void 0,width:Ie.width},durationInFrames:Nt,compositionWidth:Ie.width,compositionHeight:Ie.height,fps:30,controls:!0,numberOfSharedAudioTags:0,pauseWhenBuffering:!0,style:{width:"100%",height:"100%"}}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Je,{className:"w-5 h-5 animate-spin text-white/40"})}),s&&!Ye&&u>0&&e.jsxs(e.Fragment,{children:[e.jsx("video",{src:`${s}
16#t=0.1`,preload:"metadata",muted:!0,playsInline:!0,className:"absolute inset-0 w-full h-full object-cover pointer-events-none transition-opacity duration-300",style:{opacity:Ye?0:1}}),e.jsx("img",{src:`/v1/assembly/thumb?kind=video&url=${encodeURIComponent(s)}`,alt:"","aria-hidden":!0,className:"absolute inset-0 w-full h-full object-cover pointer-events-none transition-opacity duration-300",style:{opacity:Ye?0:1},onError:G=>{G.currentTarget.style.visibility="hidden"}})]})]}),he&&e.jsx("audio",{ref:ut,src:he,preload:"auto",className:"hidden"})]}),E&&E.length>0&&Ce&&e.jsxs("label",{className:"flex items-center gap-2 w-full px-1 cursor-pointer select-none",title:"Show animated story-arc chapter titles in the preview and bake them into the final render",children:[e.jsx("input",{type:"checkbox",className:"accent-cyan-400 w-3.5 h-3.5",checked:!!be,onChange:G=>Ce(G.target.checked)}),e.jsxs("span",{className:"text-[11px] text-white/60",children:["Story-arc chapter titles ",e.jsxs("span",{className:"text-white/35",children:["· ",E.length," sections · shown in preview & baked on render"]})]})]}),e.jsxs("div",{className:"flex gap-2 w-full",children:[e.jsxs("button",{onClick:h,disabled:!K,className:"flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg bg-white/8 border border-white/15 text-white/60 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed text-xs font-bold transition-colors",children:[e.jsx(Ar,{className:"w-3.5 h-3.5"})," Undo"]}),ee?e.jsxs("button",{onClick:R,title:"Stop waiting on this render and go back to your latest one",className:"flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg bg-red-600/20 border border-red-500/40 text-red-200 hover:bg-red-600/30 text-xs font-bold transition-all",children:[e.jsx(os,{className:"w-3.5 h-3.5"})," Cancel render"]}):e.jsxs("button",{onClick:V,title:"Render the authoritative video from your current edits",className:"flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg bg-gradient-to-r from-cyan-600 to-violet-600 hover:from-cyan-500 hover:to-violet-500 text-white text-xs font-bold transition-all",children:[e.jsx(cn,{className:"w-3.5 h-3.5"})," Re-render with changes"]})]}),!ee&&ue&&(st?e.jsxs("div",{className:"flex w-full items-center gap-1.5 px-1 text-[11px] font-semibold text-emerald-300",title:"Your ViralSpin connector is running â re-renders run on your own machine (free & faster, no cloud queue).",children:[e.jsx("span",{className:"shrink-0",children:"â¡"})," Renders on your machine ",e.jsx("span",{className:"text-white/45 font-normal",children:"· free & faster, no cloud queue"})]}):e.jsxs("a",{href:ia,download:!0,title:"Download the ViralSpin connector to render on your own machine â free, no cloud queue.",className:"flex w-full items-center gap-1.5 px-1 text-[11px] font-semibold text-cyan-300/90 hover:text-cyan-200",children:[e.jsx(aa,{className:"w-3.5 h-3.5 shrink-0"})," Render on your machine (free, no queue) â get the connector â"]})),!ee&&$&&e.jsxs("button",{onClick:$,title:"Shuffle the B-roll order within each story-arc chapter and render a new variant â same clips, different sequence",className:"w-full flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-lg bg-violet-500/15 border border-violet-500/30 text-violet-200 hover:bg-violet-500/25 text-[11px] font-bold transition-colors",children:[e.jsx(dc,{className:"w-3.5 h-3.5"})," Remix Variant"]}),!ee&&xe&&e.jsx("p",{className:"text-[11px] text-white/45 text-center min-h-[16px]",children:xe})]}),(!pe||Ke==="final")&&e.jsx("div",{className:pe?"flex w-full flex-1 min-h-0 flex-col items-center overflow-y-auto thin-scroll":L?"flex w-[400px] max-w-full flex-col gap-2 shrink-0":"contents",children:e.jsx("div",{className:pe?"w-full max-w-[420px]":"contents",children:z>0&&e.jsxs("div",{className:"w-full flex flex-col gap-2 mt-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-[10px] font-black uppercase tracking-widest text-green-300/70",children:[Z?"Renderingâ¦":"Final render",!Z&&ke&&((ie=qe==null?void 0:qe[ke])==null?void 0:ie.createdAt)&&e.jsxs("span",{className:"ml-1.5 normal-case font-medium tracking-normal text-white/45",children:["· ",new Date(qe[ke].createdAt).toLocaleStr
16ing(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})]})]}),z>1&&e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-white/50",children:[e.jsx("button",{onClick:()=>Ae(Math.max(0,je-1)),disabled:je<=0,title:"Previous render",className:"px-1.5 py-0.5 rounded bg-white/8 border border-white/15 disabled:opacity-30 hover:text-white",children:"â¹"}),e.jsx("span",{className:"font-mono tabular-nums",children:vt?`${lt}/${jt}`:`${je+1}/${z}`}),e.jsx("button",{onClick:()=>Ae(Math.min(z-1,je+1)),disabled:je>=z-1,title:"Next render",className:"px-1.5 py-0.5 rounded bg-white/8 border border-white/15 disabled:opacity-30 hover:text-white",children:"âº"})]})]}),Z?e.jsxs("div",{className:"w-full flex flex-col gap-1.5 rounded-lg border border-white/10 bg-white/[0.02] p-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-[11px]",children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-white/70 font-semibold",children:[e.jsx(Je,{className:"w-3 h-3 animate-spin text-cyan-300"}),A||"Rendering","â¦"]}),e.jsxs("span",{className:"text-white/40 font-mono",children:[bt?`${Math.round(yt)}% · `:"",P]})]}),e.jsx("div",{className:"w-full h-1.5 rounded-full bg-white/10 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-cyan-500 to-violet-500 transition-all duration-500 ease-linear",style:{width:`${Math.max(4,yt)}%`}})}),e.jsxs("p",{className:"text-[10px] text-white/30 text-center",children:["Cached clips are reused â no credits spent. ",Le.length>0?"â¹ back to view your previous render.":""]})]}):ke?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative mx-auto",style:{height:"clamp(200px, 58vh, 600px)",maxWidth:"100%",aspectRatio:`${Ie.width} / ${Ie.height}`},children:[e.jsx("video",{ref:B,src:ke,controls:!0,playsInline:!0,preload:"metadata",onLoadedData:()=>dt(!0),onError:()=>{Xe<12&&window.setTimeout(()=>at(G=>G+1),4e3)},className:`h-full w-full rounded-lg border border-white/10 bg-black object-contain transition-opacity duration-300 ${et?"opacity-100":"opacity-0"}`},`${ke}#${Xe}`),et?null:e.jsxs("div",{className:"pointer-events-none absolute inset-0 flex flex-col items-center justify-center gap-2 rounded-lg border border-white/10 bg-black/85 text-center",children:[e.jsx(Je,{className:"h-6 w-6 animate-spin text-cyan-300"}),e.jsx("span",{className:"text-[12px] font-semibold text-white/70",children:"Finalizing your renderâ¦"}),e.jsxs("span",{className:"text-[10px] text-white/40",children:["Render's done â fetching the file",Xe>0?` (retry ${Xe})`:""]})]})]}),e.jsxs("button",{onClick:()=>{try{const G=(v??[]).map(oe=>oe.text).join(" ").trim();cc({title:"From Swap & Refine",videoUrl:ke,transcript:G,ratio:w,source:"Swap & Refine"})}catch{}window.open("/publish?from=swap-refine","_blank","noopener,noreferrer")},className:"flex items-center justify-center gap-2 py-2 rounded-lg bg-gradient-to-r from-cyan-600 to-violet-600 hover:from-cyan-500 hover:to-violet-500 text-white font-bold text-xs transition-all",children:[e.jsx(uc,{className:"w-3.5 h-3.5"})," Send to Publish"]}),e.jsxs("a",{href:ke,download:!0,target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-center gap-2 py-1.5 rounded-lg bg-green-600/20 border border-green-500/30 text-green-300 font-bold text-xs hover:bg-green-600/30 transition-colors",children:[e.jsx(aa,{className:"w-3.5 h-3.5"})," Download"]})]}):null]})})})]})}const Qn=["#22d3ee","#a78bfa","#f472b6","#34d399","#fbbf24","#60a5fa","#fb7185","#f59e0b","#4ade80","#c084fc","#2dd4bf","#fca5a5"];function br(s){const i=(s||"").trim();if(!i)return Qn[0];let c=2166136261;for(let u=0;u<i.length;u++)c^=i.charCodeAt(u),c=Math.imul(c,16777619);return Qn[Math.abs(c)%Qn.length]}function da(s){return s.asset_id||s.asset_url||s.url||""}const Gc=.5,Eo=["#22d3ee","#a78bfa","#f472b6","#34d399","#fbbf24","#60a5fa","#fb7185","#c084fc"],Zs=116,an=Math.round(Zs*16/9),ua=8,Qs=3,Xr=Zs*Qs+ua*(Qs-1)+12,dr=an+26;function on(s,i=.1){return s&&!s.includes("#")?`${s}#t=${i}`:s}function ea(s){return`/v1/assembly/thumb?kind=video&url=${encodeURIComponent(s)}`}const Kr=s=>{s.currentTarget.style.visibility="hidden"};function Ro({atSec:s,onSeek:i,onInsertPoint:c,onDropBroll:u}){return e.jsxs("button",{onClick:()=>{i(s),c==null||c(s)},title:"Add a B-roll clip here",onDragOver:p=>p.preventDefault(),onDrop:p=>{p.preventDefault();const m=p.dataTransfer.getData("application/x-broll-source");if(m&&u)try{u(s,JSON.parse(m))}catch{}},className:"w-full flex flex-col items-center justify-center gap-1 rounded-lg border-2 border-dashed border-white/15 text-white/30 transition-colors hover:border-white/40 hover:text-white/55",style:{aspectRatio:"9/16"},children:[e.jsx(Hs,{className:"w-5 h-5"}),e.jsx("span",{className:"text-[8px] font-bold uppercase tracking-wider",children:"Add clip"})]})}const $o={en:"English",es:"Spanish",fr:"French",de:"German",it:"Italian",pt:"Portuguese",ko:"Korean",ja:"Japanese",zh:"Chinese",ar:"Arabic",ru:"Russian",nl:"Dutch"},Yc=[{code:"en",label:"English"},{code:"es",label:"Spanish"},{code:"fr",label:"French"},{code:"de",label:"German"},{code:"it",label:"Italian"},{code:"pt",label:"Portuguese"},{code:"ko",label:"Korean"},{code:"ja",label:"Japanese"},{code:"zh",label:"Chinese"},{code:"ar",label:"Arabic"}];
16function Jc({detectedLang:s,onTranslate:i}){const[c,u]=n.useState(!1);return e.jsxs("div",{className:"ml-auto relative",children:[e.jsxs("button",{onClick:()=>u(p=>!p),className:"flex items-center gap-1 px-2 py-0.5 rounded-md bg-violet-500/20 hover:bg-violet-500/35 border border-violet-400/30 text-violet-300 text-[10px] font-bold transition-colors",children:[e.jsx(pc,{className:"w-3 h-3"})," Translate ",e.jsx(Ir,{className:"w-3 h-3"})]}),c&&e.jsx("div",{className:"absolute right-0 top-full mt-1 z-[60] min-w-[150px] rounded-lg border border-white/15 bg-[#16161d] py-1 shadow-2xl",children:Yc.filter(p=>p.code!==s).map(p=>e.jsx("button",{onClick:()=>{i(p.code),u(!1)},className:"w-full text-left px-3 py-1.5 text-[11px] text-white/70 hover:text-white hover:bg-white/[0.08] transition-colors",children:p.label},p.code))})]})}function Xc({voiceId:s,onVoiceChange:i,canPreview:c,playingId:u,onPlay:p}){const[m,v]=n.useState(!1),_=Tr.find(O=>O.id===s)??Tr[0];return e.jsxs("div",{className:"relative",children:[e.jsxs("button",{onClick:()=>v(O=>!O),className:"flex items-center gap-1 px-2 py-0.5 rounded-md bg-emerald-500/20 hover:bg-emerald-500/35 border border-emerald-400/30 text-emerald-300 text-[10px] font-bold transition-colors whitespace-nowrap",children:[e.jsx(xc,{className:"w-3 h-3"})," ",_.name," ",e.jsx(Ir,{className:"w-3 h-3"})]}),m&&e.jsxs("div",{className:"absolute right-0 top-full mt-1 z-[60] w-[244px] max-h-[300px] overflow-y-auto thin-scroll rounded-lg border border-white/15 bg-[#16161d] py-1 shadow-2xl",children:[e.jsx("div",{className:"px-2.5 pt-1 pb-1.5 text-[8px] font-bold text-white/30 uppercase tracking-widest",children:"â¶ hears this voice read your transcript"}),Tr.map(O=>e.jsxs("div",{className:`w-full px-2 py-1.5 flex items-center gap-2 transition-colors ${O.id===s?"bg-emerald-500/15":"hover:bg-white/[0.07]"}`,children:[c&&e.jsx("button",{onClick:Q=>{Q.stopPropagation(),p(O.id)},title:`Hear ${O.name} read the transcript`,className:"shrink-0 w-6 h-6 rounded-full flex items-center justify-center bg-emerald-500/20 border border-emerald-400/40 text-emerald-300 hover:bg-emerald-500/35 transition-colors",children:u===O.id?e.jsx(Je,{className:"w-3 h-3 animate-spin"}):e.jsx(_s,{className:"w-3 h-3 translate-x-px"})}),e.jsxs("button",{onClick:()=>{i(O.id),v(!1)},className:"flex-1 min-w-0 text-left",children:[e.jsx("div",{className:`text-[11px] font-semibold truncate ${O.id===s?"text-emerald-200":"text-white/80"}`,children:O.name}),e.jsx("div",{className:"text-[9px] text-white/40 truncate",children:O.vibe})]})]},O.id))]})]})}const Er="application/x-viralspin-broll",ur="application/x-viralspin-card";function Zr(s,i){const c=s.find(u=>u.id===i);return br(c?da(c):i)}function hr(s){const i=Math.floor(s);return`${Math.floor(i/60)}:${String(i%60).padStart(2,"0")}`}function Kc(s,i){if(i!=null&&i.length)return i;const c=[];for(const u of s){const p=u.text.trim().split(/\s+/).filter(Boolean),m=Math.max(.001,u.end_sec-u.start_sec);p.forEach((v,_)=>c.push({word:v,start:u.start_sec+_/p.length*m,end:u.start_sec+(_+1)/p.length*m}))}return c}function Zc({phrases:s,storedWords:i,brolls:c,removedRanges:u=[],selectedId:p,onSelect:m,onSeek:v,onChange:_,onCommit:O,onRestoreCut:Q,onRemoveWords:q,onInsertPoint:F,onDropBroll:E,onReplaceBroll:w,onRotateBroll:H,onReorderBroll:B,onMoveBroll:K,sectionsLocked:h=!0,onToggleSectionsLock:V,onBlockedMove:ee,arcSections:se,magnetSections:W,onToggleMagnet:S,onAddCard:A,onRenameSection:k,onDeleteSection:xe,onAddSection:Le,locate:qe,detectedLanguage:fe,onTranslate:Ae,translatedFromLang:R,onRevertTranslation:$,suggestedPool:te,onAddSuggested:ue,voiceId:st,onVoiceChange:be,onPreviewVoice:Ce,onEditPhrases:he}){var gs,Ds;const Qe=n.useRef(null),Oe=n.useRef(null),Ee=n.useRef(null),L=n.useRef(!1),pe=n.useRef(new Map),we=n.useRef(new Map),[,Ge]=n.useReducer(d=>d+1,0),[et,dt]=n.useState(0),Xe=n.useRef({}),at=n.useRef(null),Ye=n.useRef(null),gt=n.useRef(null),[Ke,tt]=n.useState(null),[ut,ht]=n.useState(null),[Ve,D]=n.useState(null),z=n.useRef(null),[ye,je]=n.useState(null),[Z,ke]=n.useState(!1),[Ie,Ue]=n.useState(null),ot=n.useRef(null),jt=n.useRef(0),[lt,vt]=n.useState(null),xt=n.useRef(null),Nt=n.useRef(new Map),[bt,Mt]=n.useState(null),[wt,yt]=n.useState(null),x=async(d,y=0)=>{var U;if(!Ce||!d)return;const j=`${d}:${y}`;try{(U=xt.current)==null||U.pause()}catch{}if(bt===j){Mt(null);return}try{let I=Nt.current.get(j);if(!I){Mt(j);const re=await Ce(d,y);I=`data:${re.mime};base64,${re.audio_base64}`,Nt.current.set(j,I)}const le=new Audio(I);xt.current=le,le.onended=()=>Mt(re=>re===j?null:re),Mt(j),await le.play()}catch{Mt(null)}},P=bt&&bt.endsWith(":0")?bt.slice(0,-2):null,[ie,G]=n.useState(!1),[oe,Pe]=n.useState([]),$e=()=>{Pe(s.map(d=>d.text)),G(!0)},Te=(d,y)=>{Pe(j=>{const U=j.slice();return U[d]=y,he==null||he(s.map((I,le)=>({...I,text:U[le]??I.text}))),U})},ae=n.useMemo(()=>Kc(s,i),[s,i]),it=d=>u.some(y=>d.start>=y.start-.05&&d.end<=y.end+.05),Lt=n.useMemo(()=>{const d=ae.map(()=>null);for(const y of c)for(let j=0;j<ae.length;j++){const U=ae[j];y.start_sec<U.end-.001&&y.start_sec+y.dur_sec>
16U.start+.001&&!d[j]&&(d[j]=y.id)}return d},[ae,c]),St=n.useMemo(()=>{const d={};for(const y of c){let j=-1,U=-1;for(let I=0;I<ae.length;I++){const le=ae[I];y.start_sec<le.end-.001&&y.start_sec+y.dur_sec>le.start+.001&&(j<0&&(j=I),U=I)}j>=0&&(d[y.id]={first:j,last:U})}return d},[ae,c]),Vt=n.useMemo(()=>c.filter(d=>St[d.id]).sort((d,y)=>St[d.id].first-St[y.id].first),[c,St]),kt=n.useMemo(()=>c.filter(d=>d.dur_sec>.05).sort((d,y)=>d.start_sec-y.start_sec),[c]);n.useLayoutEffect(()=>{var j;let d=!1;pe.current.forEach((U,I)=>{const le=U.offsetTop;Xe.current[I]!==le&&(Xe.current[I]=le,d=!0)});const y=((j=Qe.current)==null?void 0:j.offsetHeight)??0;y&&Math.abs(y-et)>1&&dt(y),d&&Ge()});const Wt=d=>{if(L.current){L.current=!1;return}const y=d==="strip"?Oe.current:Ee.current,j=d==="strip"?Ee.current:Oe.current;y&&j&&j.scrollTop!==y.scrollTop&&(L.current=!0,j.scrollTop=y.scrollTop)};n.useEffect(()=>{qe&&Dt(qe.id)},[qe==null?void 0:qe.nonce]);const is=(d,y)=>{var U;const j=(U=document.elementFromPoint(d,y))==null?void 0:U.closest("[data-wi]");return j?parseInt(j.dataset.wi,10):-1},Dt=d=>{const y=Zr(c,d),j=St[d];if(j&&Qe.current){const I=Qe.current.querySelector(`[data-wi="${j.first}"]`);I==null||I.scrollIntoView({block:"center",behavior:"smooth"});for(let le=j.first;le<=j.last;le++){const re=Qe.current.querySelector(`[data-wi="${le}"]`);re==null||re.animate([{backgroundColor:y,color:"#0b0b0f"},{backgroundColor:y,color:"#0b0b0f",offset:.55},{}],{duration:1100,easing:"ease-out"})}}const U=we.current.get(d);U==null||U.animate([{boxShadow:`0 0 0 0 ${y}00`,transform:"scale(1)"},{boxShadow:`0 0 22px 5px ${y}`,transform:"scale(1.06)",offset:.3},{boxShadow:`0 0 0 0 ${y}00`,transform:"scale(1)"}],{duration:1100,easing:"ease-out"})},Ts=d=>{const y=at.current;if(!y)return;const j=is(d.clientX,d.clientY);if(j<0||j>=ae.length)return;const U=c.find(I=>I.id===y.id);if(U)if(y.mode==="start"){const I=U.start_sec+U.dur_sec,le=ae[j].start;if(le<I-.15)_(y.id,{start_sec:+le.toFixed(3),dur_sec:+(I-le).toFixed(3)});else{const re=ae[j].end;_(y.id,{start_sec:+le.toFixed(3),dur_sec:+Math.max(.2,re-le).toFixed(3)})}}else{const I=ae[j].end;if(I>U.start_sec+.15)_(y.id,{dur_sec:+(I-U.start_sec).toFixed(3)});else{const le=ae[j].start;_(y.id,{start_sec:+le.toFixed(3),dur_sec:+Math.max(.2,I-le).toFixed(3)})}}},Ft=()=>{at.current&&(at.current=null,window.removeEventListener("pointermove",Ts),window.removeEventListener("pointerup",Ft),O())},Fs=(d,y,j)=>{j.stopPropagation(),j.preventDefault(),m(d),at.current={id:d,mode:y},window.addEventListener("pointermove",Ts),window.addEventListener("pointerup",Ft)},Gt=d=>{const y=Ye.current;if(!y)return;const j=is(d.clientX,d.clientY);j>=0&&j!==y.anchor&&(y.moved=!0,tt({anchor:y.anchor,focus:j}))},At=()=>{const d=Ye.current;if(Ye.current=null,window.removeEventListener("pointermove",Gt),window.removeEventListener("pointerup",At),!d||d.moved)return;const y=d.anchor;if(gt.current===y)tt({anchor:y,focus:y});else{v(ae[y].start),yt(y);const j=Lt[y];j?(m(j),Dt(j)):F==null||F(ae[y].start),tt(null),gt.current=y}},ss=(d,y)=>{y.button===0&&(Ye.current={anchor:d,moved:!1},window.addEventListener("pointermove",Gt),window.addEventListener("pointerup",At))},$t=Ke?{lo:Math.min(Ke.anchor,Ke.focus),hi:Math.max(Ke.anchor,Ke.focus)}:null;if(!ae.length){const d=c.length>0,y=se&&se.length>0;if(d||y){const j=se??[],U=new Map;for(const ge of c){let Y=0;for(let o=0;o<j.length;o++)j[o].at_sec<=ge.start_sec+.001&&(Y=o);U.has(Y)||U.set(Y,[]),U.get(Y).push(ge)}const I=j.length?c.filter(ge=>ge.start_sec<j[0].at_sec-.001):[],le=({b:ge})=>{const Y=br(da(ge)),o=p===ge.id;return e.jsxs("button",{onClick:()=>{m(ge.id),v(ge.start_sec)},className:"relative rounded-lg overflow-hidden w-full",style:{aspectRatio:"9/16"},children:[e.jsx("div",{className:"absolute inset-0 rounded-lg pointer-events-none z-10",style:{border:`2px solid ${Y}`,boxShadow:o?`0 0 0 2px #fff4, 0 0 0 4px ${Y}`:void 0}}),ge.type==="broll_video"?e.jsx("img",{src:ea(ge.asset_url),className:"w-full h-full object-cover",alt:"",loading:"lazy",onError:Kr}):e.jsx("img",{src:ge.asset_url,className:"w-full h-full object-cover",alt:"",loading:"lazy",onError:Kr}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 px-1 py-0.5 bg-gradient-to-t from-black/70 to-transparent",children:e.jsxs("span",{className:"text-[9px] text-white/60",children:[ge.dur_sec.toFixed(1),"s"]})})]})},re=({label:ge,atSec:Y,secIdx:o,color:b})=>{const g=U.get(o)??[],J=j.map((We,ft)=>ft).filter(We=>(U.get(We)??[]).length===0),X=J.indexOf(o),ve=Math.max(1,J.length),Be=(te==null?void 0:te.length)??0,Se=g.length===0&&Be>0?(te??[]).slice(Math.floor(X*Be/ve),Math.floor((X+1)*Be/ve)).slice(0,3):[];return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{backgroundColor:b}}),e.jsx("span",{className:"text-[10px] font-black text-white/45 uppercase tracking-widest truncate",children:ge}),e.jsxs("span",{className:"text-[10px] text-white/20 ml-auto shrink-0",children:[Y.toFixed(1),"s"]})]}),g.length>0?e.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[g.map(We=>e.jsx(le,{b:We},We.id)),e.jsx(Ro,{atSec:Y,onSeek:v,onInsertPoint:F,onDropBroll:E})]}):Se.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[9px] font-bold text-white/28 uppercase tracking-widest mb-1.5",children:"Detected scenes"}),e.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[Se.map((We,ft)=>e.jsxs("button",{onClick:()=>
16ue==null?void 0:ue(We.url,We.kind,Y),title:"Click to add this scene",className:"relative w-full rounded-lg overflow-hidden group outline-none",style:{aspectRatio:"9/16",border:"2px solid rgba(255,255,255,0.12)"},children:[We.kind==="video"?e.jsx("img",{src:ea(We.url),alt:"",draggable:!1,loading:"lazy",onError:Kr,className:"w-full h-full object-cover",style:{pointerEvents:"none"}}):e.jsx("img",{src:We.url,alt:"",draggable:!1,className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(Hs,{className:"w-5 h-5 text-white"})})]},ft)),e.jsx(Ro,{atSec:Y,onSeek:v,onInsertPoint:F,onDropBroll:E})]})]}):e.jsx("button",{onClick:()=>{v(Y),F==null||F(Y)},className:"w-full py-3 border border-dashed border-white/10 rounded-lg text-[10px] text-white/25 hover:border-white/30 hover:text-white/45 transition-colors",onDragOver:We=>We.preventDefault(),onDrop:We=>{We.preventDefault();const ft=We.dataTransfer.getData("application/x-broll-source");if(ft&&E)try{const Ps=JSON.parse(ft);E(Y,Ps)}catch{}},children:"+ Drop or click to add B-roll"})]})},Re=["#22d3ee","#a78bfa","#f472b6","#34d399","#fbbf24","#60a5fa","#fb7185","#c084fc"];return e.jsxs("div",{className:"flex flex-col gap-5 p-4 overflow-y-auto h-full",children:[I.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-black text-white/35 uppercase tracking-widest mb-2",children:"Intro"}),e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:I.map(ge=>e.jsx(le,{b:ge},ge.id))})]}),j.length>0?j.map((ge,Y)=>e.jsx(re,{label:ge.label,atSec:ge.at_sec,secIdx:Y,color:Re[Y%Re.length]},ge.at_sec)):d&&e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:c.map(ge=>e.jsx(le,{b:ge},ge.id))}),e.jsx("p",{className:"text-[10px] text-white/20 text-center pt-1",children:"No spoken audio · drag from B-roll panel to swap clips"})]})}return e.jsx("p",{className:"text-xs text-white/30 p-4 text-center",children:'No transcript â click "Re-transcribe audio" to transcribe.'})}const ms=new Map;se!=null&&se.length&&[...se].sort((y,j)=>y.at_sec-j.at_sec).forEach((y,j)=>{if(j===0)return;const U=ae.findIndex(I=>I.start>=y.at_sec-.15);U>=0&&ms.set(U,{label:y.label,atSec:y.at_sec,color:Eo[j%Eo.length]})});const Yt=[];for(let d=0;d<ae.length;d++){const y=ae[d],j=ms.get(d);if(j&&Yt.push(e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,margin:"14px 0 4px",userSelect:"none",pointerEvents:"none",width:"100%"},children:[e.jsx("span",{style:{width:6,height:6,borderRadius:"50%",backgroundColor:j.color,flexShrink:0,display:"inline-block"}}),e.jsx("span",{style:{fontSize:10,fontWeight:900,textTransform:"uppercase",letterSpacing:"0.1em",color:j.color},children:j.label}),e.jsx("span",{style:{flex:1,height:1,background:`${j.color}35`,display:"inline-block"}}),e.jsx("span",{style:{fontSize:9,color:"rgba(255,255,255,0.22)",fontVariantNumeric:"tabular-nums"},children:hr(j.atSec)})]},`sec-div-${d}`)),d>0&&y.start-ae[d-1].end>Gc){const Y=ae[d-1].end,o=y.start;Yt.push(e.jsxs("span",{className:"inline-flex items-center gap-1 mx-1.5 cursor-pointer select-none group align-middle",onClick:()=>Q(Y,o),title:`${(o-Y).toFixed(1)}s removed â click to restore`,children:[e.jsx(gr,{className:"w-3 h-3 text-red-400/80 group-hover:text-red-300"}),e.jsxs("span",{className:"text-[10px] text-red-400/60 group-hover:text-red-300 underline",children:[(o-Y).toFixed(1),"s"]})]},`cut-${d}`))}for(const Y of Vt)if(St[Y.id].first===d){const o=Zr(c,Y.id),b=Y.id===p;Yt.push(e.jsx("span",{ref:g=>{g?pe.current.set(Y.id,g):pe.current.delete(Y.id)},onPointerDown:g=>Fs(Y.id,"start",g),onClick:()=>{m(Y.id),v(Y.start_sec),Dt(Y.id)},className:"inline-block cursor-ew-resize select-none mx-0.5 align-middle",style:{color:o,fontSize:14,fontWeight:700,opacity:b?1:.85,textShadow:b?`0 0 8px ${o}`:"none"},title:`B-roll starts â drag to move · ${hr(Y.start_sec)}`,children:"â¶"},`â¶-${Y.id}`))}const U=Lt[d],I=U?Zr(c,U):null,le=U===p,re=$t&&d>=$t.lo&&d<=$t.hi,Re=it(y),ge=ut===d;Yt.push(e.jsx("span",{"data-wi":d,onPointerDown:Y=>ss(d,Y),className:"sr-word cursor-pointer rounded select-none",onDragOver:E?Y=>{Y.preventDefault(),Y.dataTransfer.dropEffect="copy",ut!==d&&ht(d)}:void 0,onDragLeave:E?()=>ht(Y=>Y===d?null:Y):void 0,onDrop:E?Y=>{Y.preventDefault(),ht(null);const o=Y.dataTransfer.getData(Er);if(o)try{const b=JSON.parse(o);b!=null&&b.url&&E(ae[d].start,b)}catch{}}:void 0,style:{background:ge?"rgba(167,139,250,0.55)":re?"rgba(248,113,113,0.4)":!Re&&I?`${I}${le?"50":"2e"}`:"transparent",color:Re?"rgba(185,28,28,0.75)":re||ge?"#1b1a16":U?le?"#1b1a16":"rgba(27,26,22,0.92)":"rgba(38,36,31,0.66)",borderRadius:3,padding:"1px 2px",outline:ge?"2px solid rgba(167,139,250,0.95)":re?"1px dashed rgba(248,113,113,0.9)":"none",textDecoration:Re?"line-through":"none",textDecorationColor:Re?"rgba(248,113,113,0.9)":void 0},title:Re?"Removed from video":hr(y.start),children:y.word},`w-${d}`)),Yt.push(" ");for(const Y of Vt)if(St[Y.id].last===d){const o=Zr(c,Y.id),b=Y.id===p,g=Y.start_sec+Y.dur_sec;Yt.push(e.jsx("span",{onPointerDown:J=>Fs(Y.id,"end",J),onClick:()=>{m(Y.id),v(g),Dt(Y.id)},className:"inline-block cursor-ew-resize select-none mx-0.5 align-middle",style:{color:o,fontSize:14,fontWeight:700,opacity:b?1:.85,textShadow:b?`0 0 8px ${o}`:"none"},title:`B-roll ends â drag to adjust · ${hr(g)}`,children:"â"},`â-${Y.id}`))}}const Jt=d=>{if(!(se!=null&&se.length))return null;let y=0;for(let j=0;j<se.length;j++)se[j].at_sec<=d+.001&&(y=j);return se[y]},As=28,xs={},ls=[],Xt=[],Ot=[];for(const d of kt){const y=Jt(d.start_sec),j=(y==null?void 0:y.index)??-1,U=Ot[Ot.length-1];U&&U.secIdx===j?U.cards.push(d):Ot.push({secIdx:j,atSec:(y==null?void 0:y.at_sec)??d.start_sec,cards:[d]})}if(se!=null&&se.length){for(const d of[...se].sort((y,j)=>y.at_sec-j.at_sec))if(!Ot.some(y=>y.secIdx===d.index)){const y=Ot.findIndex(U=>U.atSec>
16d.at_sec),j={secIdx:d.index,atSec:d.at_sec,cards:[]};y<0?Ot.push(j):Ot.splice(y,0,j)}}const Ct=[];let Ht=8;for(const d of Ot){const y=d.cards.length>0?d.cards.find(re=>Xe.current[re.id]!=null)??d.cards[0]:null,j=(y==null?void 0:y.id)??null;let U=j!=null?Math.max(Ht,Xe.current[j]??8,8):Ht;if(se!=null&&se.length){U+=As;const re=se.find(Re=>Re.index===d.secIdx);re!=null&&re.label&&ls.push({y:U-22,label:re.label,atSec:re.at_sec,secIdx:d.secIdx})}let I=0;for(const re of d.cards)I>=Qs&&(I=0,U=Math.max(U+dr,Xe.current[re.id]??U+dr)),xs[re.id]={x:I*(Zs+ua),y:U},I++;let le=0;if(d.cards.length===0&&ue&&(te!=null&&te.length)){const re=Ot.filter(g=>g.cards.length===0),Re=re.indexOf(d),ge=Math.max(1,re.length),Y=Math.floor(Re*te.length/ge),o=Math.floor((Re+1)*te.length/ge),b=te.slice(Y,o);if(b.length>0){Ct.push({y:U,atSec:d.atSec,secIdx:d.secIdx,clips:b});const g=Math.floor(b.length/Qs),J=b.length%Qs;U+=g*dr,le=J}}if(A){I=Math.max(I,le),I>=Qs&&(I=0,U+=dr);const re=d.cards[d.cards.length-1],Re=(se??[]).filter(o=>o.at_sec>d.atSec+.01).reduce((o,b)=>Math.min(o,b.at_sec),1/0),ge=re?re.start_sec+re.dur_sec:d.atSec,Y=Number.isFinite(Re)?Math.min(ge,Re-.05):ge;Xt.push({x:I*(Zs+ua),y:U,atSec:d.atSec,secIdx:d.secIdx,endSec:Math.max(d.atSec,Y)})}Ht=U+(d.cards.length>0?dr:an+16)}Ct.length===0&&(te!=null&&te.length)&&ue&&(Ct.push({y:8,atSec:0,secIdx:-1,clips:te}),Ht=Math.max(Ht,8+Math.ceil(te.length/Qs)*dr+16));const Kt=Math.max(et,Ht),pt=kt.map(d=>d.id),ks=(()=>{const d=z.current;if(!d||ye==null)return pt;const y=pt.indexOf(d);if(y<0)return pt;const j=[...pt],[U]=j.splice(y,1);let I=ye;return y<ye&&(I=ye-1),j.splice(Math.max(0,Math.min(j.length,I)),0,U),j})(),cs=!K&&z.current!=null&&ye!=null,Ys=new Map(c.map(d=>[d.id,d])),rt=new Map;kt.forEach((d,y)=>rt.set(d.id,(cs?Ys.get(ks[y]):d)??d));const sr=(d,y)=>{if(y==="after")return d.start_sec+d.dur_sec;const j=c.filter(U=>U.id!==d.id&&U.start_sec<d.start_sec-.001).map(U=>Math.min(U.start_sec+U.dur_sec,d.start_sec));return j.length?Math.max(...j):0},ds=(d,y)=>{let j=0;for(const U of kt){const I=we.current.get(U.id);if(!I){j++;continue}const le=I.getBoundingClientRect();if(le.bottom<=y){j++;continue}if(y>=le.top&&d>=le.left+le.width/2){j++;continue}break}return j},Is=d=>{const y=kt;return y.length?d<=0?{id:y[0].id,side:"before"}:d>=y.length?{id:y[y.length-1].id,side:"after"}:{id:y[d].id,side:"before"}:null},us=(d,y)=>{const j=kt.filter(Y=>Y.id!==y);if(!j.length)return 0;const U=kt.findIndex(Y=>Y.id===y);let I=d;if(U>=0&&U<d&&(I-=1),I=Math.max(0,Math.min(j.length,I)),I>=j.length){const Y=j[j.length-1];return Y.start_sec+Y.dur_sec}const le=j[I];if(I<=0)return Math.max(0,le.start_sec-.01);const re=j[I-1],Re=Math.max(0,Math.min(re.start_sec+re.dur_sec,le.start_sec)),ge=Jt(le.start_sec);return ge&&ge.at_sec>Re?ge.at_sec:Re},Ls=(d,y)=>{var re;const j=kt.filter(Re=>Re.id!==y);if(!j.length)return;const U=kt.findIndex(Re=>Re.id===y);let I=d;U>=0&&U<d&&I--,I=Math.max(0,Math.min(j.length,I));const le=I<j.length?j[I]:j[j.length-1];return le?((re=Jt(le.start_sec))==null?void 0:re.index)??void 0:void 0},Pt=()=>{ot.current&&(cancelAnimationFrame(ot.current),ot.current=null),jt.current=0},Ss=d=>{const y=Oe.current;if(!y){Pt();return}const j=y.getBoundingClientRect(),U=52,I=d<j.top+U?-1:d>j.bottom-U?1:0;if(jt.current=I,I===0){Pt();return}if(ot.current)return;const le=()=>{const re=Oe.current;if(!jt.current||!re){Pt();return}re.scrollTop+=jt.current*11,Wt("strip"),ot.current=requestAnimationFrame(le)};ot.current=requestAnimationFrame(le)},ps=(d,y)=>{if(!w)return null;for(const j of kt){const U=we.current.get(j.id);if(!U)continue;const I=U.getBoundingClientRect();if(d>=I.left&&d<=I.right&&y>=I.top&&y<=I.bottom){const le=(d-I.left)/I.width;return le>.25&&le<.75?j.id:null}}return null},Ut=(d,y)=>{const j=rt.get(d.id)??d,U=br(da(j)),I=d.id===p,le=(Ve==null?void 0:Ve.id)===d.id?Ve.mode:null,re=(Ve==null?void 0:Ve.id)===d.id?Ve.side:void 0,Re=Zs,ge=an,Y=pt.indexOf(d.id),o=z.current===d.id,g=z.current!=null&&ye!=null?ye===Y?"left":ye!=null&&ye>=pt.length&&Y===pt.length-1?"right":null:null;return e.jsxs("div",{ref:J=>{J?we.current.set(d.id,J):we.current.delete(d.id)},draggable:!!(K||B),onDragStart:J=>{(K||B)&&(J.dataTransfer.setData(ur,d.id),J.dataTransfer.effectAllowed="move",z.current=d.id)},onDragEnd:()=>{z.current=null,je(null),D(null),ke(!1),Pt()},onClick:()=>m(d.id),className:"cursor-pointer select-none",style:{...y,zIndex:I||le||g?3:1,opacity:o?.5:1},children:[le==="insert"&&e.jsx("div",{className:"absolute top-0 rounded-full",style:{[re==="after"?"right":"left"]:-6,width:4,height:ge,background:U,boxShadow:`0 0 10px ${U}`,pointerEvents:"none"}}),g&&e.jsx("div",{className:"absolute top-0 rounded-full",style:{[g==="right"?"right":"left"]:-6,width:4,height:ge,background:Z?"#ef4444":"#22d3ee",boxShadow:`0 0 10px ${Z?"#ef4444":"#22d3ee"}`,pointerEvents:"none"}}),e.jsxs("div",{className:"relative rounded-lg overflow-hidden border-2 transition-all",style:{borderColor:le==="replace"?"#fff":U,boxShadow:le==="replace"?`0 0 16px ${U}`:I?`0 0 14px ${U}80`:"none",width:Re,height:ge,cursor:K||B?"grab":"pointer"},children:[j.type==="broll_video"?e.jsx("video",{src:on(j.asset_url),muted:!0,playsInl
16ine:!0,preload:"metadata",draggable:!1,style:{width:"100%",height:"100%",objectFit:"cover",pointerEvents:"none"}}):e.jsx("img",{src:j.asset_url,alt:"",draggable:!1,style:{width:"100%",height:"100%",objectFit:"cover",pointerEvents:"none"}}),e.jsx("div",{className:"absolute bottom-1 left-1 flex items-center justify-center rounded bg-black/55 px-1 py-0.5",style:{pointerEvents:"none"},children:j.type==="broll_video"?e.jsx(qt,{className:"w-3 h-3 text-white/90"}):e.jsx($s,{className:"w-3 h-3 text-white/90"})}),H&&e.jsx("button",{onClick:J=>{J.stopPropagation(),H(d.id)},draggable:!1,title:"Rotate this clip â swap in another shot (keep clicking to cycle)",className:"absolute top-1 right-1 w-6 h-6 rounded-full bg-black/65 hover:bg-black/85 border border-white/20 text-white/80 hover:text-white flex items-center justify-center transition-colors",style:{pointerEvents:"auto"},children:e.jsx(cn,{className:"w-3 h-3"})}),le==="replace"&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-[10px] font-black uppercase tracking-widest text-white",style:{background:"rgba(0,0,0,0.45)",pointerEvents:"none"},children:"Replace"})]}),e.jsx("div",{className:"text-center text-[9px] font-mono mt-0.5 leading-tight",style:{color:U},children:le==="insert"?"+ insert here":`${hr(d.start_sec)} · ${d.dur_sec.toFixed(1)}s`})]},`thumb-${d.id}`)};return e.jsxs("div",{className:"relative flex-1 min-h-0 flex flex-col",children:[$t&&e.jsxs("div",{className:"z-20 flex items-center gap-2 px-3 py-2 bg-red-500/15 border-b border-red-500/30 backdrop-blur shrink-0",children:[e.jsxs("span",{className:"text-[11px] text-red-200 flex-1 truncate",children:["Selected: â",ae.slice($t.lo,$t.hi+1).map(d=>d.word).join(" "),"â"]}),e.jsxs("button",{onClick:()=>{q(ae[$t.lo].start,ae[$t.hi].end,ae.slice($t.lo,$t.hi+1).map(d=>d.word).join(" ")),tt(null)},className:"flex items-center gap-1 px-2.5 py-1 rounded-lg bg-red-600/80 hover:bg-red-500 text-white text-[11px] font-bold transition-colors",children:[e.jsx(gr,{className:"w-3 h-3"})," Remove from video"]}),e.jsx("button",{onClick:()=>tt(null),className:"text-white/50 hover:text-white",children:e.jsx(os,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"flex-1 min-h-0 flex",children:[e.jsx("div",{ref:Oe,onScroll:()=>Wt("strip"),className:"shrink-0 overflow-y-auto overflow-x-hidden thin-scroll",style:{width:Xr},children:e.jsxs("div",{className:"relative",style:{width:Xr,height:Kt},onDragOver:E||B||K?d=>{var re;const y=d.dataTransfer.types,j=y.includes(ur),U=y.includes(Er);if(!j&&!U)return;if(d.preventDefault(),j&&(K||B)){Ss(d.clientY);const Re=ds(d.clientX,d.clientY);if(ye!==Re&&je(Re),Ve&&D(null),K&&z.current){const ge=c.find(b=>b.id===z.current),Y=Ls(Re,z.current)??-1,o=!!h&&(((re=Jt((ge==null?void 0:ge.start_sec)??0))==null?void 0:re.index)??-1)!==Y;Z!==o&&ke(o),d.dataTransfer.dropEffect=o?"none":"move"}else d.dataTransfer.dropEffect="move";return}if(!E)return;d.dataTransfer.dropEffect="copy";const I=ps(d.clientX,d.clientY),le=I?{id:I,mode:"replace",side:void 0}:(()=>{const Re=Is(ds(d.clientX,d.clientY));return Re?{id:Re.id,mode:"insert",side:Re.side}:null})();le&&((Ve==null?void 0:Ve.id)!==le.id||Ve.mode!==le.mode||Ve.side!==le.side)?D(le):!le&&Ve&&D(null)}:void 0,onDragLeave:E||B||K?d=>{d.currentTarget===d.target&&(D(null),je(null),ke(!1),Pt())}:void 0,onDrop:E||B||K?d=>{var ge;d.preventDefault(),Pt();const y=d.dataTransfer.getData(ur);if(y&&(K||B)){const Y=ds(d.clientX,d.clientY);if(z.current=null,je(null),D(null),ke(!1),K){const o=c.find(X=>X.id===y),b=us(Y,y),g=Ls(Y,y);!!h&&(((ge=Jt((o==null?void 0:o.start_sec)??0))==null?void 0:ge.index)??-1)!==(g??-1)?ee==null||ee():K(y,b,g)}else B&&B(ks);return}if(D(null),!E)return;const j=d.dataTransfer.getData(Er);if(!j)return;let U=null;try{const Y=JSON.parse(j);Y!=null&&Y.url&&(U={url:Y.url,kind:Y.kind==="video"?"video":"image"})}catch{}if(!U)return;const I=ps(d.clientX,d.clientY);if(I&&w){w(I,U);return}const le=kt;if(!le.length){E(0,U);return}const re=Is(ds(d.clientX,d.clientY)),Re=re?le.find(Y=>Y.id===re.id):null;E(Re&&re?sr(Re,re.side):0,U)}:void 0,children:[ls.map((d,y)=>{const j=!!k&<&&Math.abs(lt.atSec-d.atSec)<.001,U=()=>
16{if(lt){const I=lt.draft.trim();I&&I!==d.label&&(k==null||k(d.atSec,I))}vt(null)};return e.jsxs("div",{className:"absolute flex items-center gap-2",style:{left:2,top:Math.max(0,d.y),width:Xr-6,pointerEvents:k?"auto":"none"},onDragOver:I=>{z.current&&I.dataTransfer.types.includes(ur)&&(I.preventDefault(),I.dataTransfer.dropEffect="move")},children:[j?e.jsx("input",{autoFocus:!0,value:lt.draft,onChange:I=>vt({atSec:d.atSec,draft:I.target.value}),onBlur:U,onKeyDown:I=>{I.key==="Enter"?(I.preventDefault(),U()):I.key==="Escape"&&vt(null)},className:"min-w-0 flex-1 bg-black/40 border border-cyan-400/50 rounded px-1 py-0.5 text-[11px] font-black uppercase tracking-wider text-cyan-100 outline-none"}):e.jsx("button",{onClick:()=>k&&vt({atSec:d.atSec,draft:d.label}),title:k?"Click to rename this section â shows as a callout in the video":void 0,className:`text-[11px] font-black uppercase tracking-wider text-cyan-200/90 whitespace-nowrap truncate ${k?"hover:text-cyan-100 cursor-text":""}`,children:d.label}),e.jsx("span",{className:"flex-1 h-px bg-cyan-300/25"}),S&&e.jsx("button",{onClick:I=>{I.stopPropagation(),S(d.secIdx)},title:W&&W.size>0?"Magnet ON â all clips snapped together. Click to release.":"Magnet â snap ALL clips across every section back-to-back (no black gaps).",className:`shrink-0 w-5 h-5 rounded-md flex items-center justify-center border transition-colors ${W&&W.size>0?"bg-red-500/25 border-red-500/60 text-red-400":"bg-white/[0.04] border-white/15 text-white/35 hover:text-white/70"}`,children:e.jsx(_c,{className:"w-3 h-3"})}),xe&&y>0&&e.jsx("button",{onClick:I=>{I.stopPropagation(),xe(d.atSec)},title:"Delete this empty section",className:"shrink-0 w-5 h-5 rounded-md flex items-center justify-center border bg-white/[0.04] border-white/15 text-white/35 hover:text-red-400 hover:border-red-500/60 transition-colors",children:e.jsx(Xo,{className:"w-3 h-3"})}),Le&&e.jsx("button",{onClick:I=>{I.stopPropagation(),Le(d.atSec)},title:"Add a new section after this one",className:"shrink-0 w-5 h-5 rounded-md flex items-center justify-center border bg-white/[0.04] border-white/15 text-white/35 hover:text-cyan-300 hover:border-cyan-500/60 transition-colors",children:e.jsx(Hs,{className:"w-3 h-3"})})]},`sec-${y}`)}),kt.map(d=>Ut(d,{position:"absolute",left:(xs[d.id]??{x:0}).x,top:(xs[d.id]??{y:8}).y,width:Zs})),Xt.map((d,y)=>{const j=(Ie==null?void 0:Ie.i)===y,U=j&&!(Ie!=null&&Ie.blocked),I=j&&(Ie==null?void 0:Ie.blocked),le=re=>{var ge;const Re=c.find(Y=>Y.id===re);return!!h&&(((ge=Jt((Re==null?void 0:Re.start_sec)??0))==null?void 0:ge.index)??-1)!==d.secIdx};return e.jsxs("button",{onClick:re=>{re.stopPropagation(),A==null||A(d.atSec)},onDragOver:K||E||B?re=>{const Re=re.dataTransfer.types;if(Re.includes(ur)){if(!K&&!B)return;re.preventDefault(),re.stopPropagation();const ge=le(z.current);Ss(re.clientY),re.dataTransfer.dropEffect=ge?"none":"move",K?je(null):B&&je(pt.length),Ue({i:y,blocked:ge});return}Re.includes(Er)&&E&&(re.preventDefault(),re.stopPropagation(),re.dataTransfer.dropEffect="copy",Ue({i:y,blocked:!1}))}:void 0,onDragLeave:K||E||B?()=>Ue(re=>(re==null?void 0:re.i)===y?null:re):void 0,onDrop:K||E||B?re=>{const Re=re.dataTransfer.getData(ur);if(Re){if(!K&&!B)return;re.preventDefault(),re.stopPropagation();const Y=le(Re);if(Ue(null),z.current=null,je(null),ke(!1),Pt(),Y){ee==null||ee();return}if(K)K(Re,d.endSec,d.secIdx);else if(B){const o=pt.indexOf(Re);if(o!==-1&&o!==pt.length-1){const b=[...pt],[g]=b.splice(o,1);b.push(g),B(b)}}return}const ge=re.dataTransfer.getData(Er);if(ge&&E){re.preventDefault(),re.stopPropagation();let Y=null;try{const o=JSON.parse(ge);o!=null&&o.url&&(Y={url:o.url,kind:o.kind==="video"?"video":"image"})}catch{}Ue(null),Pt(),Y&&E(d.endSec,Y)}}:void 0,title:K||E?"Add a clip â or drag a clip here to drop it into this section":"Add a clip to this section",className:"absolute flex flex-col items-center justify-center gap-1 rounded-lg border-2 border-dashed transition-colors",style:{left:d.x,top:d.y,width:Zs,height:an,borderColor:U?"rgba(34,211,238,0.95)":I?"rgba(239,68,68,0.85)":"rgba(255,255,255,0.15)",background:U?"rgba(34,211,238,0.12)":I?"rgba(239,68,68,0.1)":"transparent",color:U?"#22d3ee":I?"rgba(239,68,68,0.9)":"rgba(255,255,255,0.35)",boxShadow:U?"0 0 16px rgba(34,211,238,0.4)":"none"},children:[e.jsx("span",{className:"text-3xl leading-none",children:"+"}),e.jsx("span",{className:"text-[9px] font-bold uppercase tracking-widest",children:U?"Drop here":I?"Locked":"Add clip"})]},`add-${y}`)}),Ct.map((d,y)=>e.jsxs("div",{className:"absolute",style:{left:0,top:d.y,width:Xr-4,pointerEvents:"auto"},children:[e.jsx("div",{className:"text-[9px] font-bold text-white/28 uppercase tracking-widest mb-1 px-1",children:"Detected scenes"}),e.jsx("div",{className:"grid grid-cols-3 gap-1.5 px-0.5",children:d.clips.map((j,U)=>e.jsxs("button",{onClick:()=>ue==null?void 0:ue(j.url,j.kind,d.atSec),title:"Click to add this
16scene",className:"relative rounded-lg overflow-hidden group outline-none",style:{border:"2px solid rgba(255,255,255,0.12)"},children:[j.kind==="video"?e.jsx("img",{src:ea(j.url),alt:"",draggable:!1,loading:"lazy",onError:Kr,style:{display:"block",width:"100%",height:"auto",pointerEvents:"none"}}):e.jsx("img",{src:j.url,alt:"",draggable:!1,style:{display:"block",width:"100%",height:"auto"}}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(Hs,{className:"w-5 h-5 text-white"})})]},U))})]},`sug-${y}`))]})}),e.jsxs("div",{ref:Ee,onScroll:()=>Wt("transcript"),className:"flex-1 min-w-0 overflow-y-auto thin-scroll flex flex-col",children:[(fe||be)&&e.jsxs("div",{className:"sticky top-0 z-10 flex items-center gap-2 px-3 py-1.5 bg-black/85 backdrop-blur border-b border-white/8 shrink-0",children:[fe&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[10px] text-white/35 uppercase tracking-wider",children:"Language"}),e.jsx("span",{className:"text-[11px] font-bold text-white/70",children:$o[fe]??fe.toUpperCase()})]}),e.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[he&&e.jsx("button",{onClick:()=>ie?G(!1):$e(),title:ie?"Done editing â type to refine the script; captions + AI voice use it":"Edit the script text by typing â feeds the captions and the AI voice",className:`flex items-center gap-1 px-2 py-0.5 rounded-md border text-[10px] font-bold transition-colors ${ie?"bg-emerald-500/30 border-emerald-400/50 text-emerald-100":"bg-white/[0.05] border-white/15 text-white/60 hover:text-white hover:bg-white/[0.08]"}`,children:ie?e.jsxs(e.Fragment,{children:[e.jsx(xa,{className:"w-3 h-3"})," Done"]}):e.jsxs(e.Fragment,{children:[e.jsx(hc,{className:"w-3 h-3"})," Edit script"]})}),Ce&&e.jsxs("button",{onClick:()=>x(st??Tr[0].id,wt??0),title:wt!=null?`Hear the voice read from â${((gs=ae[wt])==null?void 0:gs.word)??""}â onward`:"Hear the selected voice read the transcript (click a word first to start from there)",className:"flex items-center gap-1 px-2 py-0.5 rounded-md bg-emerald-500/15 hover:bg-emerald-500/30 border border-emerald-400/30 text-emerald-300 text-[10px] font-bold transition-colors max-w-[140px]",children:[bt===`${st??Tr[0].id}:${wt??0}`?e.jsx(Je,{className:"w-3 h-3 animate-spin shrink-0"}):e.jsx(_s,{className:"w-3 h-3 translate-x-px shrink-0"}),e.jsx("span",{className:"truncate",children:wt!=null?`From â${((Ds=ae[wt])==null?void 0:Ds.word)??""}â`:"Preview voice"})]}),be&&e.jsx(Xc,{voiceId:st,onVoiceChange:be,canPreview:!!Ce,playingId:P,onPlay:d=>x(d,0)}),R&&$&&e.jsxs("button",{onClick:$,title:"Restore the original-language transcript & captions",className:"flex items-center gap-1 px-2 py-0.5 rounded-md bg-amber-500/20 hover:bg-amber-500/35 border border-amber-400/30 text-amber-300 text-[10px] font-bold transition-colors",children:[e.jsx(cn,{className:"w-3 h-3"})," Revert to ",$o[R]??R.toUpperCase()]}),Ae&&fe&&e.jsx(Jc,{detectedLang:fe,onTranslate:Ae})]})]}),ie?e.jsxs("div",{className:"px-3 py-3 flex flex-col gap-2",children:[e.jsx("div",{className:"text-[10px] text-emerald-300/80 leading-relaxed mb-1",children:"â Editing the script â your text drives the burned captions and what the AI voice reads. Timecodes stay put; re-render (and re-synth the voice) to bake the new words."}),s.map((d,y)=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx("span",{className:"text-[9px] font-mono text-white/30 pt-2 w-9 shrink-0 text-right",children:hr(d.start_sec)}),e.jsx("textarea",{value:oe[y]??d.text,onChange:j=>Te(y,j.target.value),rows:Math.max(1,Math.ceil((oe[y]??d.text).length/38)),className:"flex-1 resize-none bg-white/[0.04] border border-white/12 rounded px-2 py-1.5 text-[13px] leading-snug text-white/90 outline-none focus:border-emerald-400/50 focus:bg-white/[0.06] transition-colors"})]},y))]}):e.jsx("div",{ref:Qe,className:"relative px-3 py-3 text-[13px]",style:{lineHeight:2.4},children:Yt})]})]})]})}async function Qc(s,i,c,u={}){var K;const p=(h,V=0)=>{var ee;return(ee=u.onProgress)==null?void 0:ee.call(u,{ratio:V,message:h})},m=Math.max(0,i),v=Math.max(.1,c-m);p("loading ffmpeg.wasm (~32 MB first time)â¦");const{ffmpeg:_,fetchFile:O}=await mc(h=>p(h)),q=`trim-in.${(((K=s.name.match(/\.([a-zA-Z0-9]+)$/))==null?void 0:K[1])||"mp4").toLowerCase()}`,F="trim-out.mp4";u.onProgress&&_.on("progress",h=>{const V=Math.max(0,Math.min(1,h.progress||0));p(V>0?`${Math.round(V*100)}% trimmed`:"trimmingâ¦",V)}),p(`reading file into ffmpeg (${(s.size/1024/1024).toFixed(0)} MB)â¦`),await _.writeFile(q,await O(s));const w=`${s.name.replace(/\.[^.]+$/,"")}-clip.mp4`,H=h=>{try{_.deleteFile(q),_.deleteFile(F)}catch{}return new File([h.slice().buffer],w,{type:"video/mp4"})};p("trimming (stream copy)â¦");try{await _.exec(["-ss",String(m),"-i",q,"-t",String(v),"-c","copy","-movflags","+faststart",F]);const h=await _.readFile(F);if(h&&h.length>1024)return p("done",1),H(h)}catch(h){console.warn("[videoTrim] stream-copy failed, re-encoding:",h)}p("trimming (re-encoding)â¦");try{await _.deleteFile(F)}catch{}await _.exec(["-ss",String(m),"-i",q,"-t",String(v),"-c:v","libx264","-preset","veryfast","-crf","23","-c:a","aac","-b:a","128k","-movflags","+faststart",F]);const B=await _.readFile(F);return p("done",1),H(B)}const ta=s=>{(!isFinite(s)||s<0)&&(s=0);const i=Math.floor(s/60),c=Math.floor(s%60);return`${i}:${String(c).padStart(2,"0")}`},Qr=s=>`${(s/1024/1024).toFixed(s>100*1024*1024?0:1)} MB`;function ed({file:s,pending:i,onResolve:c,onCancel:u}){const p=n.useMemo(()=>URL.createObjectURL(s),[s]);n.useEffect(()=>()=>URL.revokeObjectURL(p),[p]);const m=n.useRef(null),[v,_]=n.useState(0),[O,Q]=n.useState(0),[q,F]=n.useState(0),[E,w]=n.useState(!1),[H,B]=n.useState(""),[K,h]=n.useState(0);n.useEffect(()=>{const A=m.current;if(!A)return;const k=()=>{const xe=isFinite(A.duration)?A.duration:0;_(xe),Q(0),F(xe)};return A.addEventListener("loadedmetadata",k),()=>A.removeEventListener("loadedmetadata",k)},[]);const V=A=>{const k=m.current;if(k)try{k.currentTime=Math.max(0,Math.min(v||0,A))}catch{}},ee=Math.max(0,q-O),se=v>0&&ee<v-.05,W=v>0?Math.round(s.size*(ee/v)):s.size,S=async()=>{w(!0),B("preparingâ¦");try{const A=await Qc(s,O,q,{onProgress:k=>{B(k.message),h(k.ratio)}});c(A)}catch(A){B(`trim failed: ${(A==null?void 0:A.message)||A}`),w(!1)}};return e.jsx("div",{className:"fixed inset-0 z-[120] flex items-center justify-center bg-black/80 p-4",onClick:E?void 0:u,children:e.jsxs("div",{className:"w-full max-w-xl rounded-2xl border border-white/10 bg-[#0d1117] p-4 shadow-2xl",onClick:A=>A.stopPropagation(),children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-white",children:[e.jsx(gr,{className:"h-4 w-4 text-cyan-400"}),"Trim before upload"]}),e.jsxs("div",{className:"mt-0.5 truncate text-xs text-white/45",title:s.name,children:[s.name," · ",Qr(s.size),i>0?` · ${i} more queued`:""]})]}),!E&&e.jsx("button",{onClick:u,className:"rounded-md p-1 text-white/50 hover:bg-white/10 hover:text-white",title:"Skip this file",children:e.jsx(os,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"overflow-hidden rounded-lg bg-black",children:e.jsx("video",{ref:m,src:p,c
16ontrols:!0,playsInline:!0,className:"mx-auto max-h-[46vh] w-auto"})}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex justify-between text-[11px] text-white/55",children:[e.jsxs("span",{children:["Start: ",e.jsx("span",{className:"text-cyan-300",children:ta(O)})]}),e.jsxs("span",{children:["End: ",e.jsx("span",{className:"text-cyan-300",children:ta(q)})," · clip ",ta(ee)]})]}),e.jsx("input",{type:"range",min:0,max:Math.max(.1,v),step:.1,value:O,disabled:E||!v,onChange:A=>{const k=Math.min(Number(A.target.value),q-.1);Q(k),V(k)},className:"w-full accent-cyan-400"}),e.jsx("input",{type:"range",min:0,max:Math.max(.1,v),step:.1,value:q,disabled:E||!v,onChange:A=>{const k=Math.max(Number(A.target.value),O+.1);F(k),V(k)},className:"w-full accent-cyan-400"})]}),e.jsx("div",{className:"text-[11px] text-white/55",children:se?e.jsxs(e.Fragment,{children:["Uploads only the selection â ",e.jsxs("span",{className:"text-emerald-300",children:["â ",Qr(W)]})," instead of ",Qr(s.size),"."]}):e.jsxs(e.Fragment,{children:["Whole clip selected â uploads the full ",Qr(s.size),"."]})}),E&&e.jsxs("div",{children:[e.jsx("div",{className:"h-1.5 w-full overflow-hidden rounded-full bg-white/10",children:e.jsx("div",{className:"h-full bg-cyan-400 transition-[width]",style:{width:`${Math.round(K*100)}%`}})}),e.jsx("div",{className:"mt-1 truncate text-[11px] text-white/50",children:H})]})]}),e.jsxs("div",{className:"mt-4 flex items-center justify-end gap-2",children:[!E&&e.jsxs("button",{onClick:()=>c(s),className:"rounded-lg border border-white/15 px-3 py-1.5 text-xs text-white/80 hover:bg-white/5",children:[e.jsx(gc,{className:"mr-1 inline h-3.5 w-3.5"})," Upload full"]}),e.jsx("button",{onClick:S,disabled:E||!se,className:"rounded-lg bg-cyan-500 px-3 py-1.5 text-xs font-medium text-black hover:bg-cyan-400 disabled:opacity-40",children:E?e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"mr-1 inline h-3.5 w-3.5 animate-spin"})," Trimmingâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(gr,{className:"mr-1 inline h-3.5 w-3.5"})," Trim & upload"]})})]})]})})}const xr=new Map,td={"9x16":9/16,"1x1":1,"16x9":16/9},sa=.2,Rr=s=>Math.max(0,Math.min(1,s));function en({value:s,min:i,max:c,step:u=.1,decimals:p=1,suffix:m="s",onCommit:v,title:_}){const[O,Q]=n.useState(s.toFixed(p));n.useEffect(()=>{Q(s.toFixed(p))},[s,p]);const q=()=>{const F=parseFloat(O);isNaN(F)?Q(s.toFixed(p)):v(+Math.max(i,Math.min(c,F)).toFixed(2))};return e.jsxs("span",{className:"flex items-center gap-0.5 shrink-0",children:[e.jsx("input",{type:"number",inputMode:"decimal",min:i,max:c,step:u,value:O,title:_,onChange:F=>Q(F.target.value),onFocus:F=>F.currentTarget.select(),onBlur:q,onKeyDown:F=>{F.key==="Enter"&&F.currentTarget.blur()},className:"w-12 px-1.5 py-0.5 text-right font-mono text-[11px] text-cyan-200 bg-black/40 border border-white/20 rounded focus:outline-none focus:border-cyan-400 [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"}),m&&e.jsx("span",{className:"font-mono text-[10px] text-white/45",children:m})]})}function ci({assetUrl:s,motion:i,outputFormat:c,onMotion:u,durSec:p=2.5,onDurChange:m,maxDurSec:v,startSec:_=0,onStartChange:O,maxStartSec:Q,minStartSec:q,onSyncSeek:F,onSyncPlayMain:E,bare:w=!1,videoSrc:H,mediaElRef:B}){const K=td[c]??.5625,h=n.useRef(null),V=n.useRef(null),ee=n.useRef(null),se=n.useRef(null),W=n.useRef(null),S=n.useRef(_),A=n.useRef(null),[k,xe]=n.useState(!1),[Le,qe]=n.useState(0),[fe,Ae]=n.useState(1),R=x=>Math.min(1,x*K/fe),$=Math.min(1,fe/K),te=n.useRef(!1),ue=(x,P)=>{const ie=Math.min(1,K/fe),G=Math.min(1,fe/K),oe=Te=>Math.max(0,Math.min(1,Te)),Pe=ie<.999?oe((x-ie/2)/(1-ie)):.5,$e=G<.999?oe((P-G/2)/(1-G)):.5;return`${(Pe*100).toFixed(2)}% ${($e*100).toFixed(2)}%`},st=()=>{const x=Math.min(1,fe/K);if((i==null?void 0:i.type)==="pan_left"||(i==null?void 0:i.type)==="pan_right"){const ae=i.type==="pan_left"?.72:.28,it=i.type==="pan_left"?.28:.72;return{start:{cx:ae,cy:.5,h:x},end:{cx:it,cy:.5,h:x}}}const P=typeof(i==null?void 0:i.focus_x)=="number"&&typeof(i==null?void 0:i.focus_y)=="number",ie=i!=null&&i.start_scale&&i.start_scale>1.001?i.start_scale:1,G=Math.max(sa,Math.min(x,x/ie)),oe=P?{cx:i.focus_x,cy:i.focus_y}:{cx:.5,cy:.5},Pe={cx:oe.cx,cy:oe.cy,h:G},Te=typeof(i==null?void 0:i.focus_to_x)=="number"&&typeof(i==null?void 0:i.focus_to_y)=="number"?{cx:i.focus_to_x,cy:i.focus_to_y}:null;return{start:Pe,end:Te?{cx:Te.cx,cy:oe.cy,h:G}:null}},be=()=>{const x=i==null?void 0:i.type;return x==="static"||x==="pan_left"||x==="pan_right"?!1:x==="ken_burns"?!0:((i==null?void 0:i.end_scale)??1)>((i==null?void 0:i.start_scale)??1)+.001},Ce=n.useRef(st()),[he,Qe]=n.useState(Ce.current.start),[Oe,Ee]=n.useState(Ce.current.end),[L,pe]=n.useState(be()),[we,Ge]=n.useState(typeof(i==null?void 0:i.hold_sec)=="number"?i.hold_sec:.4),[et,dt]=n.useState(typeof(i==null?void 0:i.hold_start_sec)=="number"?i.hold_start_sec:0),Xe=n.useRef(_),[at,Ye]=n.useState(0),gt=v??6,Ke=Oe!==null,tt=n.useRef(null),ut=x=>Math.max(1,Math.min(4,$/Math.max(sa,x)));n.useEffect(()=>{te.current=!1;const x=st();
16Qe(x.start),Ee(x.end),pe(be()),Ge(typeof(i==null?void 0:i.hold_sec)=="number"?i.hold_sec:.4),dt(typeof(i==null?void 0:i.hold_start_sec)=="number"?i.hold_start_sec:0),Xe.current=_,S.current=_,Ye(0)},[fe,s]);const ht=x=>Math.max(0,Math.min(x,Math.max(0,p-.3))),Ve=x=>Math.max(0,Math.min(x,Math.max(0,p-.3-ht(et)))),D=x=>+Math.max(0,Math.min(1,x)).toFixed(3),z=(x,P,ie,G,oe)=>{te.current=!0;const Pe=!P&&x.h>=$-.03&&Math.abs(x.cx-.5)<.03&&Math.abs(x.cy-.5)<.03,$e=Math.max(0,p-.3),Te=+Math.max(0,Math.min(oe,$e)).toFixed(2),ae=+Math.max(0,Math.min(G,$e-Te)).toFixed(2);let it;if(Pe)it=ie?{type:"ken_burns",start_scale:1,end_scale:1.08,crop_hint:"center",hold_sec:ae,hold_start_sec:Te}:{type:"static",start_scale:1,end_scale:1,crop_hint:"center"};else{const Lt=ut(x.h),St={fx:D(x.cx),fy:D(x.cy)},Vt=P?{fx:D(P.cx),fy:D(P.cy)}:null;it={type:"zoom_in",start_scale:Lt,end_scale:ie?+(Lt*1.06).toFixed(3):Lt,crop_hint:"center",focus_x:St.fx,focus_y:St.fy,...Vt?{focus_to_x:Vt.fx,focus_to_y:Vt.fy}:{},hold_sec:ae,hold_start_sec:Te}}u(it)},ye=x=>{Qe(x),z(x,Oe,L,we,et)},je=x=>{Ee(x),z(he,x,L,we,et)},Z=x=>{pe(x),z(he,Oe,x,we,et)},ke=x=>{Ge(x),z(he,Oe,L,x,et)},Ie=x=>{dt(x),z(he,Oe,L,we,x)},Ue=(x,P)=>{var G;const ie=(G=h.current)==null?void 0:G.getBoundingClientRect();return ie?{x:Rr((x-ie.left)/ie.width),y:Rr((P-ie.top)/ie.height)}:{x:.5,y:.5}},ot=x=>{const P=tt.current;if(!P)return;const ie=Ue(x.clientX,x.clientY);if(P.which==="start"){const G=R(he.h),oe=P.mode==="move"?{...he,cx:Rr(Math.max(G/2,Math.min(1-G/2,ie.x))),cy:Rr(Math.max(he.h/2,Math.min(1-he.h/2,ie.y)))}:{...he,h:Math.max(sa,Math.min($,Math.abs(ie.y-he.cy)*2))};if(P.mode==="resize"&&Oe){const Pe={...Oe,h:oe.h};Qe(oe),Ee(Pe),z(oe,Pe,L,we,et)}else ye(oe)}else{const G={...Oe??he,cx:ie.x,cy:ie.y,h:he.h};je(G)}},jt=()=>{tt.current=null,window.removeEventListener("pointermove",ot),window.removeEventListener("pointerup",jt)},lt=(x,P,ie)=>{ie.preventDefault(),ie.stopPropagation(),tt.current={which:x,mode:P},window.addEventListener("pointermove",ot),window.addEventListener("pointerup",jt)},vt=()=>{je(Ke?null:{cx:Rr(he.cx+.25),cy:he.cy,h:he.h})},xt=()=>{const x={cx:.5,cy:.5,h:$};Qe(x),Ee(null),z(x,null,L,we,et)},Nt=()=>{const x=typeof(i==null?void 0:i.focus_x)=="number"?i.focus_x:.5,P=typeof(i==null?void 0:i.focus_y)=="number"?i.focus_y:.5,ie={cx:x,cy:P,h:Math.min(.66,$)};Qe(ie),Ee(null),z(ie,null,L,we,et)},bt=()=>{const x={offset:0,easing:"ease-out"},P={};if(Oe&&(x.objectPosition=ue(he.cx,he.cy),P.objectPosition=ue(Oe.cx,Oe.cy)),!Oe&&!L&&!H){xe(!1);return}const ie=ut(he.h);x.transform=`scale(${ie.toFixed(3)})`,P.transform=`scale(${(L?ie*1.09:ie).toFixed(3)})`;const G=ht(et),oe=Ve(we),Pe=Math.max(0,Math.min(.9,G/p)),$e=Math.max(Pe+.05,Math.min(1,(p-oe)/p)),Te=[{...x,offset:0},...Pe>.01?[{...x,offset:Pe,easing:"ease-out"}]:[],{...P,offset:$e,easing:"linear"},...$e<.999?[{...P,offset:1}]:[]];A.current={frames:Te,ms:Math.max(400,p*1e3)},xe(!0),qe(ae=>ae+1)};n.useEffect(()=>{if(!k)return;const x=A.current;if(!x)return;const P=S.current,ie=H?W.current:se.current,G=H?ee.current:V.current,Pe=[ie,G].filter(Boolean).map(ae=>(ae.getAnimations().forEach(it=>it.cancel()),ae.animate(x.frames,{duration:x.ms,fill:"forwards"}
16))),$e=[W.current,ee.current].filter(Boolean);$e.forEach(ae=>{ae.currentTime=P,ae.play().catch(()=>{})});const Te=window.setTimeout(()=>{Pe.forEach(ae=>ae.cancel()),$e.forEach(ae=>{ae.getAnimations().forEach(it=>it.cancel()),ae.pause()}),xe(!1)},x.ms);return()=>{clearTimeout(Te),Pe.forEach(ae=>ae.cancel()),$e.forEach(ae=>{ae.getAnimations().forEach(it=>it.cancel()),ae.pause()})}},[Le]);const Mt=()=>{bt(),F==null||F(),E==null||E()},wt=(x,P)=>{const ie=R(x.h);return{position:"absolute",left:`${(x.cx-ie/2)*100}%`,top:`${(x.cy-x.h/2)*100}%`,width:`${ie*100}%`,height:`${x.h*100}%`,border:`2px solid ${P?"#22d3ee":"#a78bfa"}`,boxShadow:"0 0 0 9999px rgba(0,0,0,0.35)",cursor:"grab",borderRadius:4}},yt=!Ke&&he.h>=$-.03&&Math.abs(he.cx-.5)<.03&&Math.abs(he.cy-.5)<.03;return e.jsxs("div",{className:w?"flex flex-col gap-2":"rounded-xl border border-white/10 bg-white/[0.02] p-3 flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ko,{className:"w-3.5 h-3.5 text-cyan-300"}),e.jsx("span",{className:"text-[11px] font-bold text-white/70",children:"Framing"}),e.jsx("span",{className:"ml-auto text-[10px] text-white/35",children:"drag the box to crop · corner to zoom"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs("button",{onClick:bt,title:"Play just this photo's animation here",className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-white/8 border border-white/15 text-white/70 hover:text-white text-[11px] font-bold transition-colors",children:[e.jsx(_s,{className:"w-3 h-3"})," ",k?"Playingâ¦":"Play clip"]}),e.jsxs("button",{onClick:Mt,title:"Position the main preview at this clip and play it",className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-cyan-500/15 border border-cyan-500/30 text-cyan-200 hover:bg-cyan-500/25 text-[11px] font-bold transition-colors",children:[e.jsx(_s,{className:"w-3 h-3"})," Sync & play"]})]}),e.jsx("div",{className:"rounded-md overflow-hidden border border-white/15 bg-black shrink-0",style:{height:64,aspectRatio:String(K)},children:H?e.jsx("video",{ref:ee,src:H,muted:!0,playsInline:!0,preload:"metadata",className:"w-full h-full object-cover",style:{objectPosition:`${he.cx*100}% ${he.cy*100}%`}}):e.jsx("img",{ref:V,src:s,alt:"",draggable:!1,className:"w-full h-full object-cover",style:{objectPosition:`${he.cx*100}% ${he.cy*100}%`}})})]}),e.jsxs("div",{ref:h,className:"relative bg-black rounded-lg overflow-hidden select-none mx-auto",style:{width:"fit-content",maxWidth:"100%"},children:[H?e.jsx("video",{ref:B,src:H,poster:s,muted:!0,playsInline:!0,preload:"metadata",onLoadedMetadata:x=>{const P=x.currentTarget;P.videoWidth&&P.videoHeight&&Ae(P.videoWidth/P.videoHeight)},className:"block select-none",style:{maxWidth:"100%",maxHeight:260,width:"auto",height:"auto"}}):e.jsx("img",{src:s,alt:"",draggable:!1,onLoad:x=>{const P=x.currentTarget;P.naturalWidth&&P.naturalHeight&&Ae(P.naturalWidth/P.naturalHeight)},className:"block select-none",style:{maxWidth:"100%",maxHeight:260,width:"auto",height:"auto"}}),e.jsx("div",{style:wt(he,!0),onPointerDown:x=>lt("start","move",x),children:e.jsx("div",{onPointerDown:x=>lt("start","resize",x),title:"Drag to zoom",className:"absolute -bottom-1.5 -right-1.5 w-3.5 h-3.5 rounded-full bg-cyan-300 border-2 border-[#0b
160b0f] cursor-nwse-resize"})}),Oe&&e.jsx("div",{style:wt({...Oe,h:he.h},!1),onPointerDown:x=>lt("end","move",x),children:e.jsx("span",{className:"absolute -top-4 left-0 text-[9px] font-bold text-violet-300",children:"end"})}),k&&e.jsx("div",{className:"absolute inset-0 z-20 flex items-center justify-center bg-black",children:e.jsx("div",{className:"relative h-full overflow-hidden",style:{aspectRatio:String(K),maxWidth:"100%"},children:H?e.jsx("video",{ref:W,src:H,muted:!0,playsInline:!0,className:"w-full h-full object-cover",style:{objectPosition:ue(he.cx,he.cy),transform:`scale(${ut(he.h).toFixed(3)})`,transformOrigin:ue(he.cx,he.cy)}}):e.jsx("img",{ref:se,src:s,alt:"",draggable:!1,className:"w-full h-full object-cover",style:{objectPosition:ue(he.cx,he.cy),transform:`scale(${ut(he.h).toFixed(3)})`,transformOrigin:ue(he.cx,he.cy)}})})})]}),e.jsxs("p",{className:"text-[10px] text-white/35",children:[yt?"Fills the frame (no extra crop)":Ke?"Pans start â end over the clip":"Crops to the box"," · ",L?"Ken Burns push on":"no zoom","."]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsx("button",{onClick:()=>Z(!L),className:`px-2 py-1 rounded-md border text-[10px] font-bold ${L?"bg-cyan-500/20 border-cyan-500/40 text-cyan-200":"bg-white/8 border-white/15 text-white/60 hover:text-white"}`,children:L?"Ken Burns: on":"Ken Burns: off"}),e.jsx("button",{onClick:vt,className:`px-2 py-1 rounded-md border text-[10px] font-bold ${Ke?"bg-violet-500/25 border-violet-500/50 text-violet-100":"bg-white/8 border-white/15 text-white/60 hover:text-white"}`,children:Ke?"Pan: on":"Pan: off"}),Ke&&e.jsx(kc,{className:"w-4 h-4 text-violet-300 self-center"}),e.jsxs("button",{onClick:Nt,className:"flex items-center gap-1 px-2 py-1 rounded-md bg-white/8 border border-white/15 text-white/60 hover:text-white text-[10px] font-bold",children:[e.jsx(as,{className:"w-3 h-3"})," Fit face"]}),e.jsx("button",{onClick:xt,className:"px-2 py-1 rounded-md bg-white/8 border border-white/15 text-white/60 hover:text-white text-[10px] font-bold",children:"Reset (full)"})]}),e.jsxs("div",{className:"flex flex-col gap-2 border-t border-white/10 pt-2",children:[m&&e.jsxs("label",{className:"flex items-center gap-2 text-[10px] text-white/55",children:[e.jsx("span",{className:"w-[68px] shrink-0 font-bold",children:"Clip length"}),e.jsx("input",{type:"range",min:.3,max:gt,step:.1,value:Math.min(p,gt),onChange:x=>m(+(+x.target.value).toFixed(2)),className:"flex-1 accent-cyan-400",title:"How many seconds this photo is on screen"}),e.jsx(en,{value:Math.min(p,gt),min:.3,max:gt,step:.1,decimals:1,onCommit:x=>m(x),title:`Type a length (max ${gt.toFixed(1)}s)`})]}),(()=>{const x=Math.min(1,Math.max(.1,p-.3));return e.jsxs("label",{className:"flex items-center gap-2 text-[10px] text-white/55",children:[e.jsx("span",{className:"w-[68px] shrink-0 font-bold",children:"Hold start"}),e.jsx("input",{type:"range",min:0,max:x,step:.05,value:ht(et),onChange:P=>Ie(+(+P.target.value).toFixed(2)),className:"flex-1 accent-cyan-400",title:"Seconds to freeze on the FIRST frame before the motion begins"}),e.jsx(en,{value:ht(et),min:0,max:x,step:.05,decimals:2,onCommit:P=>Ie(P),title:"Freeze on the first frame for this many seconds"})]})})(),(()=>{const x=Math.min(1,Math.max(.1,p-.3));return e.jsxs("label",{className:"flex items-center gap-2 text-[10px] text-white/55",children:[e.jsx("span",{className:"w-[68px] shrink-0 font-bold",children:"Hold end"}),e.jsx("input",{type:"range",min:0,max:x,step:.05,value:Ve(we),onChange:P=>ke(+(+P.target.value).toFixed(2)),className:"flex-1 accent-cyan-400",title:"Seconds to freeze on the final frame (so a pan lands and settles)"}),e.jsx(en,{value:Ve(we),min:0,max:x,step:.05,decimals:2,onCommit:P=>ke(P),title:"Freeze on the final frame for this many seconds"})]})})(),O&&(()=>{const x=Xe.current,ie=Math.max(-7,(q??0)-x),G=Math.max(ie,Math.min(5,Q!=null?Q-x:5)),oe=Math.max(ie,Math.min(G,at)),Pe=Math.max(0,+(x+oe).toFixed(2)),$e=Te=>`${Math.floor(Te/60)}:${String(Math.floor(Te%60)).padStart(2,"0")}`;return e.jsxs("label",{className:"flex items-center gap-2 text-[10px] text-white/55",children:[e.jsx("span",{className:"w-[68px] shrink-0 font-bold",children:"Start time"}),e.jsx("input",{type:"range",min:ie,max:G,step:.2,value:oe,onChange:Te=>{const ae=+(+Te.target.value).toFixed(1);Ye(ae),O(Math.max(0,+(x+ae).toFixed(2)))},className:"flex-1 accent-cyan-400",title:"Shift when this clip appears (+5s / â7s) â all later B-roll moves with it"}),e.jsx("span",{className:"shrink-0 w-9 text-right font-mono text-[10px] text-white/40",title:"When this clip appears (m:ss)",children:$e(Pe)}),e.jsx(en,{value:Pe,min:+(x+ie).toFixed(2),max:+(x+G).toFixed(2),step:.2,decimals:1,onCommit:Te=>{const ae=+(Te-x).toFixed(2);Ye(ae),O(Math.max(0,+Te.toFixed(2)))},title:"Type the second this clip appears (later B-roll moves with it)"})]})})(),e.jsxs("p",{className:"text-[9px] text-white/35",children:["Holds ",ht(et).toFixed(2),"s, animates over ",Math.max(0,p-Ve(we)-ht(et)).toFixed(1),"s, then freezes ",Ve(we).toFixed(2),"s. The live preview reflects this immediately."]})]})]})}const tn=.3,sn=16,sd=40;
16function rd({assetUrl:s,startOffset:i,durSec:c,maxDur:u,warnBeyondSec:p,onChange:m,placeStartSec:v=0,placeMinStartSec:_,placeMaxStartSec:O,onPlaceStartChange:Q,onSyncSeek:q,onSyncPlayMain:F,onLocate:E,bare:w=!1,externalVideoRef:H}){const B=n.useRef(null),K=H??B,h=n.useRef(null),V=n.useRef(null),[ee,se]=n.useState(0),[W,S]=n.useState(0),[A,k]=n.useState(1),xe=n.useRef(!1),[Le,qe]=n.useState(i),[fe,Ae]=n.useState(i+c),R=n.useRef(Le),$=n.useRef(fe),[te,ue]=n.useState(i),st=n.useRef(te),be=n.useRef(!1),Ce=n.useRef(null),[he,Qe]=n.useState(0),Oe=n.useRef(v);n.useEffect(()=>{Oe.current=v,Qe(0)},[s]),n.useEffect(()=>{R.current=Le},[Le]),n.useEffect(()=>{$.current=fe},[fe]),n.useEffect(()=>{st.current=te},[te]),n.useEffect(()=>{qe(i),Ae(i+c),ue(i)},[i,c,s]),n.useEffect(()=>{if(!H)return;const x=H.current;if(!x)return;const P=()=>{se(x.duration||0);try{x.currentTime=R.current}catch{}};return x.readyState>=1&&x.duration&&P(),x.addEventListener("loadedmetadata",P),x.addEventListener("timeupdate",Ie),x.addEventListener("seeked",gt),()=>{x.removeEventListener("loadedmetadata",P),x.removeEventListener("timeupdate",Ie),x.removeEventListener("seeked",gt)}},[H,s]),n.useLayoutEffect(()=>{const x=()=>{const P=h.current;P&&P.clientWidth&&S(P.clientWidth)};return x(),window.addEventListener("resize",x),()=>window.removeEventListener("resize",x)},[ee]);const Ee=u&&u>0?u:1/0,L=Math.max(0,fe-Le),pe=ee>0&&W>0?Math.max(1,W/ee*A):1,we=Math.max(W,ee*pe);n.useEffect(()=>{if(xe.current||ee<=0||W<=0||L<=0)return;const x=.4*ee/L;k(Math.max(1,Math.min(16,x))),xe.current=!0},[ee,W,L]);const Ge=x=>{R.current=x,qe(+x.toFixed(2))},et=x=>{$.current=x,Ae(+x.toFixed(2))},dt=x=>{const P=Math.max(0,Math.min(ee||x,x));st.current=P,ue(+P.toFixed(2))},Xe=n.useRef(null),at=n.useRef(!1),Ye=()=>{const x=K.current,P=Xe.current;if(!x||P==null){at.current=!1;return}Xe.current=null,at.current=!0;
16try{x.currentTime=P}catch{at.current=!1}},gt=()=>{at.current=!1,Xe.current!=null&&Ye()},Ke=x=>{Number.isFinite(x)&&(Xe.current=x,at.current||Ye())},tt=x=>{dt(x),Ke(x)},[ut,ht]=n.useState(!1),[Ve,D]=n.useState(null),z="Your browser canât preview this source (HEVC / .mov). Trimming still works â drag the handles and Re-render; the final video plays it fine.",ye=x=>{D(null),x.play().then(()=>ht(!0)).catch(()=>{x.muted=!0,x.play().then(()=>ht(!0)).catch(()=>{ht(!1),D(z)})})},je=()=>{const x=K.current;if(x){be.current=!0;try{x.currentTime=R.current}catch{}dt(R.current),x.muted=!1,ye(x)}},Z=()=>{const x=K.current;if(x){be.current=!1;try{x.currentTime=st.current}catch{}x.muted=!1,ye(x)}},ke=()=>{const x=K.current;x&&x.pause(),ht(!1)},Ie=()=>{const x=K.current;x&&(dt(x.currentTime),be.current&&x.currentTime>=$.current-.03&&(x.pause(),ht(!1)))},Ue=n.useRef(0),ot=()=>{Ue.current+=1;const x=Ue.current%2===0;q==null||q(),je(),x&&(F==null||F())},jt=x=>{var ie;const P=(ie=V.current)==null?void 0:ie.getBoundingClientRect();return P?Math.max(0,Math.min(ee,(x-P.left)/pe)):0};n.useEffect(()=>{const x=h.current;if(!x||!pe)return;const P=(R.current+$.current)/2*pe;x.scrollLeft=Math.max(0,P-x.clientWidth/2)},[A]);const lt=x=>{const P=h.current;if(!P)return;const ie=x*pe,G=28;ie<P.scrollLeft+G?P.scrollLeft=Math.max(0,ie-G):ie>P.scrollLeft+P.clientWidth-G&&(P.scrollLeft=ie-P.clientWidth+G)},vt=x=>{const P=Ce.current;if(!P||!ee)return;const ie=jt(x.clientX);if(P.mode==="in"){const G=Math.max(0,Math.min(ie,$.current-tn));Ge(Math.max(G,$.current-Ee)),Ke(R.current),lt(R.current)}else if(P.mode==="out"){const G=Math.max(ie,R.current+tn);et(Math.min(G,R.current+Ee,ee)),Ke($.current),lt($.current)}else if(P.mode==="head")tt(ie),lt(ie);else{const G=P.origOut-P.origIn,oe=Math.max(0,Math.min(P.origIn+(ie-P.grabSec),ee-G));Ge(oe),et(oe+G),Ke(oe),lt(Math.max(oe,Math.min(oe+G,ie)))}},xt=()=>{const x=Ce.current;x&&(Ce.current=null,window.removeEventListener("pointermove",vt),window.removeEventListener("pointerup",xt),x.mode!=="head"&&m(+R.current.toFixed(2),+Math.max(tn,$.current-R.current).toFixed(2)))},Nt=(x,P)=>{P.preventDefault(),P.stopPropagation(),ke(),Ce.current=x==="move"?{mode:x,grabSec:jt(P.clientX),origIn:R.current,origOut:$.current}:{mode:x},x==="head"?tt(jt(P.clientX)):Ke(x==="out"?$.current:R.current),window.addEventListener("pointermove",vt),window.addEventListener("pointerup",xt)},bt=x=>ee>=60?`${Math.floor(x/60)}:${String(Math.floor(x%60)).padStart(2,"0")}`:Number.isInteger(x)?`${x}s`:`${x.toFixed(1)}s`,Mt=Number.isFinite(Ee)&&L>=Ee-.05,wt=p!=null&&p>0&&L>p+.05,yt=wt?{bg:"rgba(245,158,11,0.28)",border:"rgba(245,158,11,0.7)"}:{bg:"rgba(34,211,238,0.25)",border:"rgba(34,211,238,0.5)"};return e.jsxs("div",{className:w?"flex flex-col gap-2":"rounded-xl border border-white/10 bg-white/[0.02] p-3 flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(gr,{className:"w-3.5 h-3.5 text-cyan-300"}),e.jsx("span",{className:"text-[11px] font-bold text-white/70",children:"Trim source clip"}),e.jsxs("span",{className:"ml-auto text-[11px] font-mono text-cyan-300",children:[Le.toFixed(1),"s · ",L.toFixed(1),"s"]}),e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsx("button",{onClick:()=>k(x=>Math.max(1,+(x/1.6).toFixed(2))),title:"Zoom out",className:"p-1 rounded-md bg-white/8 border border-white/15 text-white/60 hover:text-white",children:e.jsx(Zo,{className:"w-3 h-3"})}),e.jsx("button",{onClick:()=>k(x=>Math.min(sd,+(x*1.6).toFixed(2))),title:"Zoom in",className:"p-1 rounded-md bg-white/8 border border-white/15 text-white/60 hover:text-white",children:e.jsx(Qo,{className:"w-3 h-3"})})]})]}),!w&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:()=>ut?ke():(je(),E==null?void 0:E()),title:"Play this clipâs window with sound",className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-white/8 border border-white/15 text-white/70 hover:text-white text-[11px] font-bold transition-colors",children:[ut?e.jsx(la,{className:"w-3 h-3"}):e.jsx(_s,{className:"w-3 h-3"})," ",ut?"Stop":"Play clip"]}),e.jsxs("button",{onClick:ot,title:"1st click: position the main preview where this clip begins + play the clip. 2nd click: play both together.",className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-cyan-500/15 border border-cyan-500/30 text-cyan-200 hover:bg-cyan-500/25 text-[11px] font-bold transition-colors",children:[e.jsx(_s,{className:"w-3 h-3"})," Sync & play"]})]}),Ve&&e.jsxs("p",{className:"text-[10px] leading-snug text-amber-300/90 bg-amber-500/10 border border-amber-500/25 rounded-md px-2 py-1.5",children:["â ",Ve]}),Q&&(()=>{const x=Oe.current,ie=Math.max(-7,(_??0)-x),G=Math.max(ie,Math.min(5,O!=null?O-x:5)),oe=Math.max(ie,Math.min(G,he)),Pe=Math.max(0,+(x+oe).toFixed(2)),$e=Te=>`${Math.floor(Te/60)}:${String(Math.floor(Te%60)).padStart(2,"0")}`;return e.jsxs("label",{className:"flex items-center gap-2 text-[10px] text-white/55",children:[e.jsx("span",{className:"shrink-0 font-bold text-white/70",children:"Start time"}),e.jsx("input",{type:"range",min:ie,max:G,step:.2,value:oe,onChange:Te=>{const ae=+(+Te.target.value).toFixed(1);Qe(ae),Q(Math.max(0,+(x+ae).toFixed(2)))},className:"flex-1 accent-cyan-400",title:"Shift when this clip appears (+5s / â7s) â all later B-roll moves with it"}),e.jsxs("span",{className:"w-[58px] text-right font-mono text-white/70",children:[$e(Pe)," ",e.jsx("span",{className:"text-white/40",children:oe===0?"·0":`${oe>0?"+":""}${oe.toFixed(1)}`})]})]})})(),!H&&e.jsx("div",{className:"rounded-lg bg-black overflow-hidden mx-auto",style:{aspectRatio:"9 / 16",height:300,maxWidth:"100%"}
16,children:e.jsx("video",{ref:B,src:s,playsInline:!0,preload:"metadata",onLoadedMetadata:x=>{se(x.currentTarget.duration||0);try{x.currentTarget.currentTime=R.current}catch{}},onTimeUpdate:Ie,onSeeked:gt,onError:()=>{ht(!1),D(z)},onLoadedData:()=>D(null),onCanPlay:()=>D(null),onEnded:()=>ht(!1),onClick:()=>{ut?ke():(Z(),E==null||E())},title:"Click to play from the playhead (preview any part); use Play clip for the selected window",className:"w-full h-full object-cover cursor-pointer"})}),ee>tn?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:()=>ut?ke():Z(),title:"Play from the playhead (previews any part of the source)",className:"shrink-0 w-8 h-8 flex items-center justify-center rounded-full bg-amber-500/20 border border-amber-400/40 text-amber-300 hover:bg-amber-500/30 transition-colors",children:ut?e.jsx(la,{className:"w-3.5 h-3.5"}):e.jsx(_s,{className:"w-3.5 h-3.5"})}),e.jsx("div",{ref:h,className:"flex-1 min-w-0 overflow-x-auto overflow-y-hidden thin-scroll py-2",children:e.jsxs("div",{ref:V,className:"relative select-none",style:{width:we,height:48},children:[e.jsx("div",{onPointerDown:x=>Nt("head",x),className:"absolute inset-0 cursor-pointer",title:"Click or drag to preview anywhere in the source"}),(()=>{const x=pe>0?72/pe:5,ie=[.5,1,2,5,10,15,30,60,120,300,600].find(oe=>oe>=x)??600,G=[];for(let oe=0;oe<=ee+1e-4;oe+=ie){const Pe=+oe.toFixed(2);G.push(e.jsxs("div",{className:"absolute top-0 pointer-events-none",style:{left:Pe*pe},children:[e.jsx("div",{style:{width:1,height:6,background:"rgba(255,255,255,0.22)"}}),e.jsx("span",{className:"font-mono",style:{position:"absolute",top:6,left:2,fontSize:8,color:"rgba(255,255,255,0.38)",whiteSpace:"nowrap"},children:bt(Pe)})]},Pe))}return G})(),e.jsxs("div",{className:"absolute left-0 pointer-events-none",style:{top:24,width:we,height:22},children:[e.jsx("div",{className:"absolute left-0 right-0 top-1/2 -translate-y-1/2 rounded-full bg-white/12",style:{height:4}}),p!=null&&p>0&&Le+p<ee&&e.jsx("div",{className:"absolute top-0 bottom-0",title:"Past here overwrites the next clip",style:{left:(Le+p)*pe,width:2,background:"rgba(245,158,11,0.7)"}}),e.jsx("div",{onPointerDown:x=>Nt("move",x),title:"Drag to move the window (keeps length)",className:"absolute top-1/2 -translate-y-1/2 rounded border cursor-grab active:cursor-grabbing pointer-events-auto",style:{left:Le*pe,width:Math.max(2,L*pe),height:12,background:yt.bg,borderColor:yt.border}}),e.jsx("div",{onPointerDown:x=>Nt("in",x),title:"Drag â clip start (in-point)",className:"absolute top-1/2 rounded-full bg-cyan-300 border-2 border-[#0b
160b0f] cursor-ew-resize shadow z-10 pointer-events-auto",style:{width:sn,height:sn,transform:"translate(-50%, -50%)",left:Le*pe}}),e.jsx("div",{onPointerDown:x=>Nt("out",x),title:"Drag â clip end (sets length)",className:"absolute top-1/2 rounded-full bg-cyan-300 border-2 border-[#0b0b0f] cursor-ew-resize shadow z-10 pointer-events-auto",style:{width:sn,height:sn,transform:"translate(-50%, -50%)",left:fe*pe}})]}),e.jsx("div",{onPointerDown:x=>Nt("head",x),title:"Drag to preview anywhere in the source",className:"absolute z-20 cursor-ew-resize",style:{left:te*pe,top:14,bottom:0,width:2,marginLeft:-1,background:"#f59e0b"},children:e.jsx("div",{className:"absolute rounded-full bg-amber-400 border border-black/50",style:{width:11,height:11,top:-6,left:1,transform:"translateX(-50%)"}})})]})})]}),e.jsxs("p",{className:"text-[10px] text-white/35",children:["Plays ",L.toFixed(1),"s, from ",Le.toFixed(1),"s to ",fe.toFixed(1),"s of the ",ee.toFixed(1),"s source.",wt?e.jsx("span",{className:"text-amber-300/90",children:" Extends past the next clip â later clips shift back to fit (nothing deleted)."}):Mt?e.jsxs("span",{className:"text-amber-300/80",children:[" Maxed out â this clip already reaches the end of the finished video. Drag its ",e.jsx("b",{children:"Start time"})," earlier (above) to give it room to grow longer."]}):null]}),e.jsxs("p",{className:"text-[10px] text-white/25",children:["Drag the ends to trim · drag the middle to move · click the ruler/track or drag the ",e.jsx("span",{className:"text-amber-300/70",children:"playhead"})," to preview any moment · ",e.jsx("span",{className:"text-amber-300/70",children:"â¶"})," plays from the playhead · zoom for precision."]})]}):e.jsxs("p",{className:"text-[10px] text-white/35",children:["Source clip (",ee?ee.toFixed(1)+"s":"loadingâ¦",") is too short to trim â it plays from the start."]})]})}function di(s){const i=n.useRef(null);return e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.02] p-3 flex flex-col gap-3",children:[e.jsx(ci,{bare:!0,assetUrl:s.posterUrl,videoSrc:s.videoUrl,mediaElRef:i,motion:s.motion,outputFormat:s.outputFormat,durSec:s.durSec,onMotion:s.onMotion,onSyncSeek:s.onSyncSeek,onSyncPlayMain:s.onSyncPlayMain,startSec:s.startOffset}),e.jsx("div",{className:"border-t border-white/10"}),e.jsx(rd,{bare:!0,externalVideoRef:i,assetUrl:s.videoUrl,startOffset:s.startOffset,durSec:s.durSec,maxDur:s.maxDur,warnBeyondSec:s.warnBeyondSec,placeStartSec:s.placeStartSec,placeMinStartSec:s.placeMinStartSec,placeMaxStartSec:s.placeMaxStartSec,onPlaceStartChange:s.onPlaceStartChange,onSyncSeek:s.onSyncSeek,onSyncPlayMain:s.onSyncPlayMain,onLocate:s.onLocate,onChange:s.onChange})]})}const To=s=>`${Math.floor(s/60)}:${String(Math.floor(s%60)).padStart(2,"0")}`;function nd({label:s,videoSrc:i,outputFormat:c="9x16",suggestStart:u=0,suggestEnd:p,sections:m,placing:v,onClose:_,onPlace:O}){const[Q,q]=n.useState(u),[F,E]=n.useState(Math.max(.5,(p??u+3)-u)),[w,H]=n.useState(null),B={start:Q,end:+(Q+F).toFixed(2)};return e.jsx("div",{className:"fixed inset-0 z-[130] flex items-center justify-center bg-black/80 p-4",onClick:v?void 0:_,children:e.jsxs("div",{className:"w-full max-w-xl rounded-2xl border border-white/10 bg-[#0d1117] p-3 flex flex-col gap-2 max-h-[94vh] overflow-y-auto thin-scroll",onClick:K=>K.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-sm font-bold text-white min-w-0",children:[e.jsx(gr,{className:"w-4 h-4 text-cyan-400 shrink-0"})," ",e.jsxs("span",{className:"truncate",children:["Review · frame · trim â ",s]})]}),!v&&e.jsx("button",{onClick:_,className:"text-white/50 hover:text-white shrink-0",children:e.jsx(os,{className:"w-4 h-4"})})]}),e.jsxs("p",{className:"text-[11px] text-white/40",children:["Drag the box to crop/pan the ",c," frame · scrub + drag the trim handles to pick the snippet · then add it below."]}),e.jsx(di,{videoUrl:i,posterUrl:i,motion:w,outputFormat:c,durSec:F,startOffset:Q,onMotion:H,onChange:(K,h)=>{q(+K.toFixed(2)),E(+Math.max(.5,h).toFixed(2))}}),e.jsxs("div",{className:"border-t border-white/10 pt-2 flex flex-col gap-2",children:[e.jsxs("p",{className:"text-[11px] text-white/55",children:["Add ",e.jsxs("span",{className:"font-mono text-cyan-300",children:[To(B.start),"â",To(B.end)]})," ",e.jsxs("span",{className:"text-white/40",children:["(",F.toFixed(1),"s)"]})," to:"]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsx("button",{disabled:v,onClick:()=>O({kind:"end"},B,w),className:"px-2.5 py-1 rounded-lg bg-cyan-500 text-black text-[11px] font-bold hover:bg-cyan-400 disabled:opacity-40",children:v?e.jsx(Je,{className:"w-3.5 h-3.5 animate-spin inline"}):"End of video"}),(m??[]).map(K=>e.jsx("button",{disabled:v,onClick:()=>O({kind:"section",atSec:K.at_sec,label:K.label},B,w),className:"px-2.5 py-1 rounded-lg bg-white/8 border border-white/15 text-white/80 text-[11px] font-bold hover:bg-white/15 disabled:opacity-40",children:K.label},K.index))]}),((m==null?void 0:m.length)??0)>0&&e.jsx("p",{className:"text-[9px] text-white/30",children:"Or drag a clip from the grid onto a word
16in the transcript for precise placement."})]})]})})}const ad="viralspin-local-broll",tr="files",od=1;function ba(){return new Promise((s,i)=>{const c=indexedDB.open(ad,od);c.onupgradeneeded=()=>c.result.createObjectStore(tr,{keyPath:"id"}),c.onsuccess=()=>s(c.result),c.onerror=()=>i(c.error)})}async function Fo(s){const i=await ba();return new Promise((c,u)=>{const p=i.transaction(tr,"readwrite");p.objectStore(tr).put(s),p.oncomplete=()=>{i.close(),c()},p.onerror=()=>{i.close(),u(p.error)}})}async function id(){const s=await ba();return new Promise((i,c)=>{const p=s.transaction(tr,"readonly").objectStore(tr).getAll();p.onsuccess=()=>{s.close(),i(p.result)},p.onerror=()=>{s.close(),c(p.error)}})}async function ld(s){const i=await ba();return new Promise((c,u)=>{const p=i.transaction(tr,"readwrite");p.objectStore(tr).delete(s),p.oncomplete=()=>{i.close(),c()},p.onerror=()=>{i.close(),u(p.error)}})}const wa=s=>`viralspin:moments:${s}`;function ra(s){try{const i=localStorage.getItem(wa(s));return i?JSON.parse(i):null}catch{return null}}function cd(s,i){try{localStorage.setItem(wa(s),JSON.stringify(i))}catch{}}function Ao(s){try{localStorage.removeItem(wa(s))}catch{}}async function dd(s){try{if(!s.type.startsWith("image/"))return!1;const i=131072,c=m=>{const v=new Uint8Array(m);let _="";for(let O=0;O<v.length;O++)_+=String.fromCharCode(v[O]);return _},u=c(await s.slice(0,i).arrayBuffer());return/GCamera:MotionPhoto|MicroVideo|MotionPhoto\s*=\s*1/.test(u)?!0:c(await s.slice(Math.max(0,s.size-i)).arrayBuffer()).includes("ftyp")}catch{return!1}}const ui=n.createContext(null);function pr({pick:s}){const i=n.useContext(ui);return i?e.jsx("span",{role:"button",tabIndex:-1,onClick:c=>{c.stopPropagation(),i(s)},onPointerDown:c=>c.stopPropagation(),draggable:!1,title:s.kind==="video"?"Enlarge & play":"Enlarge",className:"absolute top-1 left-1 z-10 w-5 h-5 rounded-full bg-black/65 hover:bg-black/90 border border-white/25 text-white/85 hover:text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer",children:s.kind==="video"?e.jsx(Nc,{className:"w-3 h-3"}):e.jsx(wr,{className:"w-3 h-3"})}):null}function ud({pick:s,onClose:i}){return n.useEffect(()=>{if(!s)return;const c=u=>{u.key==="Escape"&&i()};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[s,i]),s?e.jsxs("div",{className:"fixed inset-0 z-[100] bg-black/85 backdrop-blur-sm flex items-center justify-center p-6",onClick:i,children:[e.jsx("button",{onClick:i,title:"Close (Esc)",className:"absolute top-4 right-4 w-9 h-9 rounded-full bg-white/10 hover:bg-white/20 border border-white/20 text-white flex items-center justify-center",children:e.jsx(os,{className:"w-5 h-5"})}),e.jsx("div",{onClick:c=>c.stopPropagation(),className:"flex items-center justify-center",children:s.kind==="video"?e.jsx("video",{src:s.url,controls:!0,autoPlay:!0,playsInline:!0,className:"max-w-[90vw] max-h-[88vh] rounded-lg bg-black"}):e.jsx("img",{src:s.url,alt:"",className:"max-w-[90vw] max-h-[88vh] rounded-lg object-contain"})})]}):null}const fr=s=>`/v1/assembly/thumb?kind=video&url=${encodeURIComponent(s)}`;async function hd(s){return new Promise(i=>{const c=document.createElement("video");c.preload="metadata",c.muted=!0,c.src=s,c.currentTime=.5,c.addEventListener("loadeddata",()=>{var u;try{const p=document.createElement("canvas");p.width=c.videoWidth||320,p.height=c.videoHeight||568,(u=p.getContext("2d"))==null||u.drawImage(c,0,0),i(p.toDataURL("image/jpeg",.7))}catch{i("")}},{once:!0}),c.addEventListener("error",()=>i(""),{once:!0})})}const xd=s=>new Promise(i=>setTimeout(i,s)),pd="application/x-viralspin-broll";function er(s,i){s.dataTransfer.setData(pd,JSON.stringify(i)),s.dataTransfer.effectAllowed="copy"}async function fd(){const s=await Rs("/v1/assembly/picker",{method:"POST"});window.open(s.pickerUri,"_blank","noopener,noreferrer");const i=Math.max(2e3,s.pollIntervalMs||3e3),c=Date.now()+10*60*1e3;for(;Date.now()<c;){await xd(i);const u=await Rs(`/v1/assembly/picker?sessionId=${encodeURIComponent(s.sessionId)}`);if(u.status==="ready")return(u.items||[]).map(p=>({url:p.url,kind:p.type==="VIDEO"?"video":"image"}))}throw new Error("Timed out waiting for photo selection.")}function Io({source:s,onPick:i,jobId:c,chosenColorByKey:u,chosenSectionByKey:p,onActivate:m,onLocate:v,kindFilter:_}){const{data:O,isLoading:Q}=js({queryKey:["swap-library",s,c??""],queryFn:()=>Cl({source:s,limit:80,jobId:c}),staleTime:3e4}),q=((O==null?void 0:O.items)??[]).filter(w=>!_||_==="all"||w.kind===_),F={gridTemplateColumns:"repeat(auto-fill, minmax(84px, 1fr))"},E=w=>{const H=(u==null?void 0:u.get(w.url))??null;return e.jsxs("button",{draggable:!0,onDragStart:B=>er(B,{url:w.url,kind:w.kind}),onClick:()=>{H&&v?v(w.url):(m??i)({url:w.url,kind:w.kind})},className:"group relative aspect-[3/4] rounded-lg overflow-hidden border-2 bg-white/[0.03] hover:border-cyan-400/60 cursor-grab active:cursor-grabbing transition-all",style:H?{borderColor:H,boxShadow:`0 0 8px ${H}66`}:{borderColor:"rgba(255,255,255,0.08)"},title:H?`${w.album} · used in this video â click to find it`:w.album,children:[w.kind==="video"?e.jsx("img",{src:w.thumb||fr(w.url),alt:"",draggable:!1,
16className:"w-full h-full object-cover",onError:B=>{B.target.style.display="none"}}):e.jsx("img",{src:w.thumb,alt:"",draggable:!1,className:"w-full h-full object-cover group-hover:scale-105 transition-transform",onError:B=>{B.target.style.display="none"}}),e.jsx(pr,{pick:{url:w.url,kind:w.kind}}),H&&e.jsx("span",{className:"absolute top-1 right-1 w-2.5 h-2.5 rounded-full border border-black/40",style:{background:H},title:"Used in this video"}),e.jsx("div",{className:"absolute bottom-1 left-1",children:w.kind==="video"?e.jsx(qt,{className:"w-3 h-3 text-white/70 drop-shadow"}):e.jsx($s,{className:"w-3 h-3 text-white/70 drop-shadow"})})]},w.id)};if(Q)return e.jsxs("div",{className:"flex items-center justify-center h-32 gap-2 text-sm text-white/40",children:[e.jsx(Je,{className:"w-4 h-4 animate-spin"})," Loadingâ¦"]});if(q.length===0)return e.jsx("div",{className:"flex items-center justify-center h-24 text-xs text-white/30 text-center px-4",children:s==="drive"?"No synced Drive media yet. Sync a Drive folder first.":s==="job"?"No saved clip pool for this video. (Older videos may predate pool snapshots.)":"No Google Photos picks yet â use âPick from Google Photosâ above."});if(p&&u){const w=q.filter(B=>u.has(B.url)),H=q.filter(B=>!u.has(B.url));if(w.length){const B=new Map;for(const K of w){const h=p.get(K.url)||"Other";B.has(h)||B.set(h,[]),B.get(h).push(K)}return e.jsxs("div",{className:"flex flex-col gap-3",children:[Array.from(B.entries()).map(([K,h])=>e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("div",{className:"text-[10px] font-black text-white/45 uppercase tracking-widest",children:K}),e.jsx("div",{className:"grid gap-2",style:F,children:h.map(E)})]},K)),H.length>0&&e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("div",{className:"text-[10px] font-black text-white/35 uppercase tracking-widest",children:"More picks"}),e.jsx("div",{className:"grid gap-2",style:F,children:H.map(E)})]})]})}}return e.jsx("div",{className:"grid gap-2",style:F,children:q.map(E)})}function md({jobId:s,onPick:i}){const{data:c,isLoading:u}=js({queryKey:["swap-ai-library",s],queryFn:()=>mr(s),staleTime:6e4}),p=((c==null?void 0:c.scenes)??[]).filter(m=>m.clip_url||m.image_url).sort((m,v)=>(m.timestamp_ms??0)-(v.timestamp_ms??0));return u?e.jsxs("div",{className:"flex items-center justify-center h-32 gap-2 text-sm text-white/40",children:[e.jsx(Je,{className:"w-4 h-4 animate-spin"})," Loadingâ¦"]}):p.length?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-[10px] text-white/30 mb-2",children:["Every AI clip from this video. ",e.jsx("span",{className:"text-white/45",children:"Drag one onto a word"})," to place it there, or click to add at the selected word / replace the selected clip."]}),e.jsx("div",{className:"grid gap-2",style:{gridTemplateColumns:"repeat(auto-fill, minmax(84px, 1fr))"},children:p.map(m=>e.jsxs("button",{draggable:!0,onDragStart:v=>er(v,{url:m.clip_url||m.image_url,kind:m.clip_url?"video":"image"}),onClick:()=>i({url:m.clip_url||m.image_url,kind:m.clip_url?"video":"image"}),className:"group relative rounded-lg overflow-hidden border border-white/[0.08] bg-white/[0.03] hover:border-violet-400/60 cursor-grab active:cursor-grabbing transition-all",style:{aspectRatio:"9 / 16"},title:m.description||`Beat ${m.beat_index}`,children:[m.image_url?e.jsx("img",{src:m.image_url,alt:"",loading:"lazy",draggable:!1,className:"w-full h-full object-cover group-hover:scale-105 transition-transform",onError:v=>{v.target.style.display="none"}}):e.jsx("img",{src:fr(m.clip_url),alt:"",loading:"lazy",draggable:!1,className:"w-full h-full object-cover",onError:v=>{v.target.style.display="none"}}),e.jsx(pr,{pick:{url:m.clip_url||m.image_url,kind:m.clip_url?"video":"image"}}),e.jsx("div",{className:"absolute bottom-1 left-1 flex items-center gap-1",children:m.clip_url?e.jsx(qt,{className:"w-3 h-3 text-white/70 drop-shadow"}):e.jsx($s,{className:"w-3 h-3 text-white/70 drop-shadow"})})]},m.id))})]}):e.jsx("div",{className:"flex items-center justify-center h-24 text-xs text-white/30 text-center px-4",children:"No AI-generated B-roll for this video."})}function rn({item:s,onPick:i,onLocate:c}){const u=s.asset_id||s.url,p=s.chosen?br(u):null;return e.jsxs("button",{draggable:!0,onDragStart:m=>er(m,{url:s.url,kind:s.kind}),onClick:()=>{s.chosen&&c?c(u):i({url:s.url,kind:s.kind})},className:"group relative aspect-[3/4] rounded-lg overflow-hidden border-2 bg-white/[0.03] hover:border-cyan-400/60 cursor-grab active:cursor-grabbing transition-all",style:p?{borderColor:p,boxShadow:`0 0 8px ${p}66`}:{borderColor:"rgba(255,255,255,0.08)"},title:s.chosen?"Used in this video â click to find it in the transcript":"Not used â click to place it",children:[s.kind==="video"?e.jsx("img",{src:s.thumb||fr(s.url),alt:"",loading:"lazy",draggable:!1,
16className:"w-full h-full object-cover",onError:m=>{m.target.style.display="none"}}):e.jsx("img",{src:s.thumb||s.url,alt:"",loading:"lazy",draggable:!1,className:"w-full h-full object-cover group-hover:scale-105 transition-transform",onError:m=>{m.target.style.display="none"}}),e.jsx(pr,{pick:{url:s.url,kind:s.kind}}),p&&e.jsx("span",{className:"absolute top-1 right-1 w-2.5 h-2.5 rounded-full border border-black/40",style:{background:p}}),e.jsx("div",{className:"absolute bottom-1 left-1",children:s.kind==="video"?e.jsx(qt,{className:"w-3 h-3 text-white/70 drop-shadow"}):e.jsx($s,{className:"w-3 h-3 text-white/70 drop-shadow"})})]})}function gd({jobId:s,onPick:i,onLocate:c,recentKeys:u,recentRemoved:p}){const{data:m,isLoading:v}=js({queryKey:["job-broll",s],queryFn:()=>oa(s),staleTime:3e4}),_=(m==null?void 0:m.items)??[],O=(m==null?void 0:m.sections)??[],Q=_.filter(h=>h.chosen),q=_.filter(h=>!h.chosen),[F,E]=n.useState("selected"),w=new Map((p??[]).map(h=>[h.asset_id||h.url,h])),H=(u??[]).map(h=>_.find(V=>(V.asset_id||V.url)===h)??w.get(h)??null).filter(h=>!!h).slice(0,8);if(v)return e.jsxs("div",{className:"flex items-center justify-center h-32 gap-2 text-sm text-white/40",children:[e.jsx(Je,{className:"w-4 h-4 animate-spin"})," Loadingâ¦"]});if(!_.length)return e.jsx("div",{className:"flex items-center justify-center h-24 text-xs text-white/30 text-center px-4",children:"No saved clip pool for this video. (Older videos may predate pool snapshots.)"});const B={gridTemplateColumns:"repeat(auto-fill, minmax(84px, 1fr))"},K=h=>{const V=O.map(se=>({section:se,list:h.filter(W=>W.section_index===se.index)})).filter(se=>se.list.length),ee=h.filter(se=>se.section_index==null);return!V.length&&ee.length?e.jsx("div",{className:"grid gap-2",style:B,children:ee.map(se=>e.jsx(rn,{item:se,onPick:i,onLocate:c},se.id))}):e.jsxs("div",{className:"flex flex-col gap-4",children:[V.map(se=>e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("div",{className:"text-[10px] font-black text-white/45 uppercase tracking-widest",children:se.section.label}),e.jsx("div",{className:"grid gap-2",style:B,children:se.list.map(W=>e.jsx(rn,{item:W,onPick:i,onLocate:c},W.id))})]},se.section.index)),ee.length>0&&e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("div",{className:"text-[10px] font-black text-white/45 uppercase tracking-widest",children:"Other"}),e.jsx("div",{className:"grid gap-2",style:B,children:ee.map(se=>e.jsx(rn,{item:se,onPick:i,onLocate:c},se.id))})]})]})};return e.jsxs("div",{className:"flex flex-col gap-3",children:[H.length>0&&e.jsxs("div",{className:"flex flex-col gap-1.5 pb-2 border-b border-white/[0.08]",children:[e.jsx("div",{className:"text-[10px] font-black text-white/45 uppercase tracking-widest",children:"Recently touched"}),e.jsx("div",{className:"grid gap-2",style:{gridTemplateColumns:"repeat(auto-fill, minmax(84px, 1fr))"},children:H.map(h=>e.jsx(rn,{item:h,onPick:i,onLocate:c},`recent-${h.id}`))})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("button",{onClick:()=>E("selected"),className:`px-2.5 py-1 rounded-md text-[11px] font-bold transition-all ${F==="selected"?"bg-cyan-500/20 border border-cyan-500/40 text-cyan-300":"text-white/40 hover:text-white border border-transparent"}`,children:["Selected · ",Q.length]}),e.jsxs("button",{onClick:()=>E("pool"),className:`px-2.5 py-1 rounded-md text-[11px] font-bold transition-all ${F==="pool"?"bg-cyan-500/20 border border-cyan-500/40 text-cyan-300":"text-white/40 hover:text-white border border-transparent"}`,children:["Pool · ",q.length]})]}),F==="selected"?Q.length===0?e.jsx("p",{className:"text-[11px] text-white/30 py-4 text-center",children:"Nothing placed yet."}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-[10px] text-white/30",children:["Photos the edit used, by story section. Outline color matches its transcript card â ",e.jsx("span",{className:"text-white/45",children:"click to find it"}),", drag to reuse."]}),K(Q)]}):q.length===0?e.jsx("p",{className:"text-[11px] text-white/30 py-4 text-center",children:"Every pool clip was used."}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-[10px] text-white/30",children:["Clips available to this video that the edit didnât use, by story section where known. ",e.jsx("span",{className:"text-white/45",children:"Click or drag"})," to add one."]}),K(q)]})]})}function hi({jobId:s,segment:i,isAiJob:c,onPick:u,onAddToEnd:p,chosenColorByKey:m,recentKeys:v,recentRemoved:_,chosenSectionByKey:O,arcSections:Q,onAddToSection:q,onLocate:F,placedUploads:E,focusSearchNonce:w}){var Re,ge,Y;const{toast:H}=pa(),[B,K]=n.useState("job"),[h,V]=n.useState(!1),[ee,se]=n.useState("all"),[W,S]=n.useState("all"),[A,k]=n.useState(()=>{try{const o=localStorage.getItem("swaprefine:gpPicks");return o?JSON.parse(o):[]}catch{return[]}}),xe=o=>{k(o);try{localStorage.setItem("swaprefine:gpPicks",JSON.stringify(o.slice(0,24)))}catch{}},Le=Yo(),[qe,fe]=n.useState(()=>{try{const o=localStorage.getItem(`swaprefine:uploads:${s}`);return o?JSON.parse(o):[]}catch{return[]}}),Ae=o=>{fe(b=>{const g=typeof o=="function"?o(b):o;try{localStorage.setItem(`swaprefine:uploads:${s}`,JSON.stringify(g.slice(0,40)))}catch{}return g})},{data:R}=js({queryKey:["job-uploads",s],queryFn:()=>El(s),staleTime:3e4}),$=n.useRef(!1);n.useEffect(()=>{if($.current||!R)return;const o=new Set((R.uploads??[]).map(g=>g.url)),b=qe.filter(g=>(g==null?void 0:g.url)&&!o.has(g.url));if(!b.length){$.current=!0;return}$.current=!0,fo(s,b.map(g=>({url:g.url,kind:g.kind}))).then(g=>
16Le.setQueryData(["job-uploads",s],g)).catch(()=>{})},[R,qe,s,Le]);const te=n.useMemo(()=>{const o=[],b=new Set,g=new Map;qe.forEach(X=>{X!=null&&X.url&&X.live&&g.set(X.url,!0)});const J=X=>{X!=null&&X.url&&!b.has(X.url)&&(b.add(X.url),o.push({url:X.url,kind:X.kind==="video"?"video":"image",...X.thumb?{thumb:X.thumb}:{},...X.live||g.get(X.url)?{live:!0}:{}}))};return(E??[]).forEach(J),((R==null?void 0:R.uploads)??[]).forEach(X=>J(X)),qe.forEach(J),o},[R,qe,E]),[ue,st]=n.useState(!1),[be,Ce]=n.useState(()=>{try{const o=localStorage.getItem(`swaprefine:recentUploads:${s}`);return o?JSON.parse(o):[]}catch{return[]}}),he=o=>Ce(b=>{const g=[...o,...b.filter(J=>!o.includes(J))].slice(0,40);try{localStorage.setItem(`swaprefine:recentUploads:${s}`,JSON.stringify(g))}catch{}return g}),[Qe,Oe]=n.useState("group"),Ee=o=>{const b=o.match(/\/(?:swap-uploads|aroll-uploads|broll-uploads|narration|uploads)\/(\d{10,})/);return b?Number(b[1]):0},[L,pe]=n.useState(null),[we,Ge]=n.useState(!1),[et,dt]=n.useState(null),[Xe,at]=n.useState(()=>{var o;return((o=ra(s))==null?void 0:o.q)??""}),[Ye,gt]=n.useState(!1),[Ke,tt]=n.useState(null),ut=n.useRef(null);n.useEffect(()=>{if(!w)return;const o=setTimeout(()=>{var b,g;(b=ut.current)==null||b.focus(),(g=ut.current)==null||g.select()},60);return()=>clearTimeout(o)},[w]);const ht=async()=>{const o=Xe.trim();if(!o){tt(null),D(null),Ao(s);return}if(B==="local"&&vt){Ie(o);return}gt(!0);try{const b=await Sl(o,80);tt(b.items??[])}catch(b){H({title:"Search failed",description:b==null?void 0:b.message,variant:"destructive"})}finally{gt(!1)}},[Ve,D]=n.useState(()=>{var o;return((o=ra(s))==null?void 0:o.results)??null}),[z,ye]=n.useState(null),[je,Z]=n.useState(null),ke=n.useRef(new Set(((Re=ra(s))==null?void 0:Re.indexed)??[])),Ie=async o=>{gt(!0),tt(null);try{const b=Te.filter(Se=>Se.kind==="video"&&Se.path&&!ke.current.has(Se.path));if(b.length)try{const{statuses:Se}=await Rs("/v1/assembly/indexed-status",{method:"POST",body:JSON.stringify({source_keys:b.map(We=>We.path)})});for(const We of b)((Se==null?void 0:Se[We.path])==="indexed"||(Se==null?void 0:Se[We.path])==="blocked")&&ke.current.add(We.path)}catch{}const g=b.filter(Se=>!ke.current.has(Se.path)),J=performance.now();let X=0,ve="";g.length&&Z({done:0,total:g.length,etaSec:0,name:""});for(let Se=0;Se<g.length;Se++){const We=g[Se],ft=We.path.split(/[/\\]/).pop()||"clip",Ps=(performance.now()-J)/1e3,yr=Se>0?Ps/Se*(g.length-Se):0;Z({done:Se,total:g.length,etaSec:yr,name:ft}),ye(`Analyzing ${Se+1}/${g.length}: ${ft}`);try{const fs=await fetch("http://localhost:7742/video-frames",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:We.path,every_sec:3,max_frames:48}),signal:AbortSignal.timeout(18e4)});if(!fs.ok)throw new Error(`frame extraction failed (${fs.status})`);const{frames:bs}=await fs.json();bs!=null&&bs.length&&await Rs("/v1/assembly/index-local",{method:"POST",body:JSON.stringify({source_key:We.path,label:ft,frames:bs})}),ke.current.add(We.path)}catch(fs){X++,ve||(ve=(fs==null?void 0:fs.message)||String(fs))}}Z(null),ye(null),X&&H({title:`${X} video${X>1?"s":""} couldn't be analyzed`,description:ve,variant:"destructive"});const Be=await Rs(`/v1/assembly/search-moments?q=${encodeURIComponent(o)}`,{method:"GET"});D(Be.items??[]),cd(s,{q:o,results:Be.items??[],indexed:[...ke.current]})}catch(b){H({title:"Moment search failed",description:b==null?void 0:b.message,variant:"destructive"})}finally{gt(!1),ye(null),Z(null)}},[Ue,ot]=n.useState({running:!1,updated:0,remaining:null,done:!1});n.useEffect(()=>{Rs("/v1/assembly/backfill-embeddings",{method:"GET"}).then(o=>ot(b=>({...b,remaining:o.remaining??0}))).catch(()=>{})},[]);const jt=async()=>{if(Ue.running)return;ot({running:!0,updated:0,remaining:null,done:!1});let o=0,b="";try{for(let g=0;g<80;g++){const J=await Rs("/v1/assembly/backfill-embeddings",{method:"POST",body:JSON.stringify({limit:400,after:b})});if(o+=J.updated||0,b=J.nextAfter||b,ot({running:!J.done,updated:o,remaining:J.remaining??0,done:J.done}),J.done)break}H({title:"Library indexed for semantic search",description:`Embedded ${o} asset${o===1?"":"s"}. Searches now match by meaning, not just exact tags.`})}catch(g){ot(J=>({...J,running:!1}
16)),H({title:"Backfill stopped",description:g==null?void 0:g.message,variant:"destructive"})}},lt=o=>{$t({lf:{id:o.media_item_id,blobUrl:"",kind:"video",path:o.local_path,indexed:!0},suggestStart:o.start_sec,suggestEnd:o.end_sec})},[vt,xt]=n.useState(!1),[Nt,bt]=n.useState(null),[Mt,wt]=n.useState(""),[yt,x]=n.useState(null);n.useEffect(()=>{const o=()=>fetch("http://localhost:7742/health",{signal:AbortSignal.timeout(800)}).then(async g=>{xt(g.ok);try{const J=await g.json();bt(typeof(J==null?void 0:J.public_url)=="string"?J.public_url:null)}catch{bt(null)}}).catch(()=>{xt(!1),bt(null)});o();const b=setInterval(o,4e3);return window.addEventListener("focus",o),()=>{clearInterval(b),window.removeEventListener("focus",o)}},[]);const P=async o=>{const b=o.map(g=>g.trim().replace(/^["']+|["']+$/g,"")).filter(Boolean);if(b.length){x("Indexingâ¦");try{const g=await fetch("http://localhost:7742/index-broll",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({broll_folder_paths:b}),signal:AbortSignal.timeout(15e3)});if(!g.ok)throw new Error(`bridge error ${g.status}`);const{job_id:J}=await g.json();if(!J){H({title:"Nothing to index"});return}const X=await new Promise((ve,Be)=>{const Se=setInterval(async()=>{try{const ft=await(await fetch(`http://localhost:7742/index-status/${J}`)).json();x(`Scanning your folders⦠${ft.scanned??0} media files found`),ft.done&&(clearInterval(Se),ft.error?Be(new Error(ft.error)):ve(ft.items||[]))}catch{}},800)});if(!X.length){H({title:"No photos or videos found there"});return}Fs(X),H({title:`Indexed ${X.length} clips`,description:Nt?"Nothing uploaded â browse below; placing a clip references it through the tunnel.":"Nothing uploaded â browse below; a clip uploads only when you place it."})}catch(g){let J=(g==null?void 0:g.message)||"unknown error";try{const X=await(await fetch("http://localhost:7742/health",{signal:AbortSignal.timeout(1500)})).json();(!(X!=null&&X.version)||X.version<"2.2")&&(J=`Your local bridge is out of date (v${(X==null?void 0:X.version)??"?"}). Restart it from the latest scripts/viralspin_bridge.py (git pull first).`)}catch{J="Can't reach the local bridge. Start it: python scripts/viralspin_bridge.py (and re-pull for the latest)."}H({title:"Local index failed",description:J,variant:"destructive"})}finally{x(null)}}},ie=async()=>{const o=Mt.trim().replace(/^["']+|["']+$/g,"");o&&(await P([o]),wt(""))},[G,oe]=n.useState(""),[Pe,$e]=n.useState(!1),[Te,ae]=n.useState([]),[it,Lt]=n.useState(!1),[St,Vt]=n.useState(null),[kt,Wt]=n.useState(""),[is,Dt]=n.useState(!1);n.useEffect(()=>{id().then(o=>{if(!o.length)return;const b=o.map(g=>{if(g.indexed||!g.arrayBuffer)return{id:g.id,blobUrl:"",indexed:!0,kind:g.kind,path:g.path,location:g.location,thumbUrl:g.path?`http://localhost:7742/local-file?path=${encodeURIComponent(g.path)}`:void 0};const J=new File([g.arrayBuffer],g.name,{type:g.type,lastModified:g.lastModified}),X=URL.createObjectURL(J);return{id:g.id,file:J,blobUrl:X,kind:g.kind,thumbDataUrl:g.thumbDataUrl,path:g.path,location:g.location}});ae(b)}).catch(()=>{})},[]);const Ts=o=>{const b=[];try{const g=o.dataTransfer.getData("text/uri-list");if(g)for(const J of g.split(/\r?\n/))J.startsWith("file:///")&&b.push(decodeURIComponent(new URL(J).pathname).replace(/^\/([A-Za-z]:)/,"$1").replace(/\//g,"\\"));if(!b.length){const J=o.dataTransfer.getData("text/plain")||o.dataTransfer.getData("text");for(const X of J.split(/\r?\n/)){const ve=X.trim().replace(/^["']+|["']+$/g,"");(/^[A-Za-z]:[\\/]/.test(ve)||ve.startsWith("\\\\"))&&b.push(ve.replace(/\//g,"\\"))}}}catch{}return b},Ft=(o,b)=>{const g=o.map((J,X)=>{const ve=J.type.startsWith("video/")?"video":"image",Be=URL.createObjectURL(J),Se=`local-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,We=Array.isArray(b)?b[X]:b;return{id:Se,file:J,blobUrl:Be,kind:ve,...We?{path:We}:{}}});ae(J=>[...g,...J]);for(const J of g){const X=J.file;if(!X)continue;(J.kind==="video"?hd(J.blobUrl):Promise.resolve(void 0)).then(Be=>{Be&&ae(Se=>Se.map(We=>We.id===J.id?{...We,thumbDataUrl:Be}:We)),X.arrayBuffer().then(Se=>
16{Fo({id:J.id,name:X.name,type:X.type,lastModified:X.lastModified,arrayBuffer:Se,kind:J.kind,thumbDataUrl:Be}).catch(()=>{})}).catch(()=>{})})}},Fs=o=>{const b=o.map(g=>({id:`idx-${Math.random().toString(36).slice(2,9)}`,blobUrl:"",thumbUrl:`http://localhost:7742/local-file?path=${encodeURIComponent(g.path)}`,indexed:!0,kind:g.kind,path:g.path}));ae(g=>{const J=new Set(g.map(ve=>ve.path).filter(Boolean)),X=b.filter(ve=>!J.has(ve.path));for(const ve of X)Fo({id:ve.id,name:ve.path.split(/[/\\]/).pop()||"clip",type:"",lastModified:0,kind:ve.kind,path:ve.path,indexed:!0}).catch(()=>{});return[...X,...g]})},Gt=o=>{ae(b=>{const g=b.find(J=>J.id===o);return g&&(g.blobUrl&&URL.revokeObjectURL(g.blobUrl),xr.delete(ls(g))),b.filter(J=>J.id!==o)}),ld(o).catch(()=>{})},At=async o=>{if(Nt&&o.path){const b=await fetch("http://localhost:7742/serve",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:o.path}),signal:AbortSignal.timeout(1e4)});if(b.ok){const g=await b.json();if(g!=null&&g.url)return{url:g.url,kind:o.kind}}}if(!o.file&&o.path){const b=await fetch("http://localhost:7742/upload-one",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:o.path}),signal:AbortSignal.timeout(12e4)});if(!b.ok)throw new Error(`bridge upload failed (${b.status})`);const g=await b.json();if(!(g!=null&&g.url))throw new Error("bridge returned no URL");return{url:g.url,kind:o.kind}}if(o.file)return Is(o.file);throw new Error("no bytes and no local path to place this clip")},[ss,$t]=n.useState(null),[ms,Yt]=n.useState(!1),Jt=o=>o.blobUrl||(o.path?`http://localhost:7742/local-file?path=${encodeURIComponent(o.path)}`:""),As=async o=>{if(o.kind==="video"){$t({lf:o});return}Vt(o.id);try{(p??u)(await At(o))}catch(b){H({title:"Couldn't place clip",description:b==null?void 0:b.message,variant:"destructive"})}finally{Vt(null)}},xs=async(o,b,g)=>{if(ss){Yt(!0);try{const X={...await At(ss.lf),assetWindow:b,durSec:+(b.end-b.start).toFixed(2),...g?{motion:g}:{}};o.kind==="section"&&q?q(X,o.atSec):(p??u)(X),$t(null)}catch(J){H({title:"Couldn't place clip",description:J==null?void 0:J.message,variant:"destructive"})}finally{Yt(!1)}}},ls=o=>o.blobUrl||o.thumbUrl||`localref:${o.id}`,Xt=o=>{const b=ls(o);xr.has(b)||xr.set(b,At(o).then(g=>g.url))},Ot=async()=>{const o=kt.trim().replace(/^["']+|["']+$/g,"");if(o){Dt(!0);try{await P([o]),Wt("")}finally{Dt(!1)}}},[Ct,Ht]=n.useState(null),Kt=!!(Q!=null&&Q.length&&q),pt=o=>{Kt?Ht(o):u(o)},{data:ks}=js({queryKey:["swap-ai-library",s],queryFn:()=>mr(s),staleTime:6e4}),cs=((ks==null?void 0:ks.scenes)??[]).some(o=>o.clip_url||o.image_url),Ys=n.useRef(!1);n.useEffect(()=>{cs&&!Ys.current&&(Ys.current=!0,K("ai_library"))},[cs]);const rt=(()=>{var b;const o=(b=i==null?void 0:i.asset_id)==null?void 0:b.match(/^ai_(\d+)$/);return o?parseInt(o[1],10):null})(),sr=[{key:"ai_library",label:"AI Library",show:cs},{key:"job",label:"This video",show:!0},{key:"local",label:"Local",show:!0},{key:"drive",label:"Drive",show:!0},{key:"google_photos",label:"Photos",show:!0},{key:"upload",label:"Upload",show:!0},{key:"generate",label:"Generate AI",show:c}],ds=async()=>{V(!0);try{const o=await fd();xe([...o,...A.filter(b=>!o.some(g=>g.url===b.url))]),o.length===0&&H({title:"No photos returned",description:"Nothing was picked."})}catch(o){H({title:"Google Photos picker failed",description:o==null?void 0:o.message,variant:"destructive"})}finally{V(!1)}},Is=async(o,b)=>{const{data:{user:g}}=await Bs.auth.getUser(),J=g==null?void 0:g.id;if(!J)throw new Error("Please sign in to upload.");const X=o.name.replace(/[^a-zA-Z0-9._-]/g,"_"),ve=`${J}/swap-uploads/${Date.now()}-${X}`;let Be;o.size>25*1024*1024?Be=await fc({file:o,bucket:"narrative",objectPath:ve,contentType:o.type||"application/octet-stream",cacheControlSec:604800,onProgress:ft=>b==null?void 0:b({loaded:ft.uploaded,total:ft.total})}):Be=(await ec("narrative",ve,o,{contentType:o.type||"application/octet-stream",onProgress:b,cacheControlSec:604800})).publicUrl;const Se=o.type.startsWith("video/")?"video":"image",We=Se==="image"?await dd(o):!1;
16if(Se==="video")try{const ft=await Ml(Be,"video");return{url:ft.url||Be,kind:Se,thumb:ft.poster_url}}catch{}return{url:Be,kind:Se,...We?{live:!0}:{}}},us=n.useRef([]),Ls=n.useRef(!1),Pt=n.useRef(0),Ss=n.useRef(0),ps=n.useRef(0),[Ut,gs]=n.useState(0),Ds=async()=>{if(Ls.current)return;Ls.current=!0,st(!0),ps.current||(ps.current=Date.now());let o=0;for(;us.current.length;){const b=us.current.shift();gs(us.current.length);try{const g=await Is(b,J=>pe({loaded:Ss.current+J.loaded,total:Pt.current,startedAt:ps.current}));Ae(J=>[g,...J.filter(X=>X.url!==g.url)]),he([g.url]);try{const J=await fo(s,[{url:g.url,kind:g.kind}]);Le.setQueryData(["job-uploads",s],J)}catch{}o++}catch(g){H({title:"One upload failed",description:g==null?void 0:g.message,variant:"destructive"})}Ss.current+=b.size||0,pe({loaded:Ss.current,total:Pt.current,startedAt:ps.current})}Ls.current=!1,st(!1),pe(null),gs(0),Pt.current=0,Ss.current=0,ps.current=0,o&&H({title:`Uploaded ${o}`,description:"Added to your uploads â drag onto a word/card or click to place."})},d=o=>{o.length&&(us.current.push(...o),Pt.current+=o.reduce((b,g)=>b+(g.size||0),0),gs(us.current.length),Ds())},[y,j]=n.useState([]),U=40*1024*1024,I=async o=>{const b=o?Array.from(o):[];if(!b.length)return;try{const X=await Rs("/v1/assembly/quota",{method:"GET"});if(b.reduce((Be,Se)=>Be+(Se.size||0),0)>X.remainingBytes){const Be=Se=>`${(Se/1024/1024/1024).toFixed(1)} GB`;H({title:"Upload limit reached",description:`You're using ${Be(X.usedBytes)} of ${Be(X.limitBytes)}. Trim clips before upload or remove old uploads to free space.`,variant:"destructive"});return}}catch{}const g=b.filter(X=>X.type.startsWith("video/")&&X.size>U),J=b.filter(X=>!g.includes(X));d(J),g.length&&j(X=>[...X,...g])},le=async()=>{if(rt!==null){$e(!0);try{const{scene:o}=await Jo(s,rt,G.trim()||void 0);o.image_url?(u({url:o.image_url,kind:"image"}),H({title:"Regenerated",description:"New AI image swapped in."})):H({title:"No image returned",variant:"destructive"})}catch(o){H({title:"Generate failed",description:o==null?void 0:o.message,variant:"destructive"})}finally{$e(!1)}}},re=o=>`${Math.floor(o/60)}:${String(Math.round(o%60)).padStart(2,"0")}`;return e.jsxs(ui.Provider,{value:dt,children:[e.jsx(ud,{pick:et,onClose:()=>dt(null)}),y.length>0&&e.jsx(ed,{file:y[0],pending:y.length-1,onResolve:o=>{d([o]),j(b=>b.slice(1))},onCancel:()=>j(o=>o.slice(1))}),ss&&e.jsx(nd,{label:((ge=ss.lf.path)==null?void 0:ge.split(/[/\\]/).pop())||((Y=ss.lf.file)==null?void 0:Y.name)||"clip",videoSrc:Jt(ss.lf),suggestStart:ss.suggestStart,suggestEnd:ss.suggestEnd,sections:Q,placing:ms,onClose:()=>$t(null),onPlace:xs}),Ct&&Q&&q&&e.jsxs("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",onClick:()=>Ht(null),children:[e.jsx("div",{className:"absolute inset-0 bg-black/55"}),e.jsxs("div",{className:"relative w-[280px] max-h-[72vh] overflow-auto thin-scroll rounded-xl border border-white/15 bg-[#15151b] p-3 flex flex-col gap-1.5 shadow-2xl",onClick:o=>o.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("div",{className:"w-10 h-14 rounded overflow-hidden border border-white/15 shrink-0 bg-black",children:Ct.kind==="video"?e.jsx("video",{src:on(Ct.url),muted:!0,playsInline:!0,preload:"metadata",className:"w-full h-full object-cover"}):e.jsx("img",{src:Ct.url,alt:"",className:"w-full h-full object-cover"})}),e.jsx("div",{className:"text-[12px] font-bold text-white/85",children:"Add to story section"})]}),Q.map(o=>e.jsxs("button",{onClick:()=>{q(Ct,o.at_sec),Ht(null)},className:"text-left px-2.5 py-1.5 rounded-md bg-white/8 border border-white/10 text-white/80 hover:bg-white/15 hover:text-white text-[12px] font-semibold transition-colors",children:[o.label," ",e.jsxs("span",{className:"text-white/35 text-[10px] font-mono",children:["· ",re(o.at_sec)]})]},o.index)),e.jsx("button",{onClick:()=>Ht(null),className:"mt-1 self-center text-[10px] text-white/40 hover:text-white",children:"Cancel"})]})]}),e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.02] overflow-hidden",children:[e.jsx("div",{className:"flex items-center gap-1 px-2 py-2 border-b border-white/[0.06]",children:sr.filter(o=>o.show).map(o=>e.jsx("button",{onClick:()=>K(o.key),className:`px-2.5 py-1 rounded-md text-[11px] font-bold transition-all ${B===o.key?"bg-cyan-500/20 border border-cyan-500/40 text-cyan-300":"text-white/40 hover:text-white"}`,children:o.label},o.key))}),e.jsxs("div",{className:"flex items-center gap-2 px-2 py-2 border-b border-white/[0.06]",children:[e.jsxs("div",{className:"flex-1 flex items-center gap-1.5 rounded-lg border border-white/12 bg-black/30 px-2 py-1",children:[e.jsx(bc,{className:"w-3.5 h-3.5 text-white/40 shrink-0"}),e.jsx("input",{ref:ut,value:Xe,onChange:o=>at(o.target.value),onKeyDown:o=>{o.key==="Enter"?ht():o.key==="Escape"&&(at(""),tt(null),D(null))},placeholder:B==="local"&&vt?"Search inside your local videos â e.g. âtennis ballâ, âcello close-upâ (finds the exact seconds)":"Search your whole library â e.g. âcouple on the waterfrontâ, âbaby smilingâ",className:"flex-1 min-w-0 bg-transparent outline-none text-[12px] text-white placeholder:text-white/30"}),Ke!==null&&e.jsx("button",{onClick:()=>{at(""),tt(null)},title:"Clear search",className:"shrink-0 text-white/40 hover:text-white text-[11px]",children:"â"})]}),e.jsx("button",{onClick:ht,disabled:Ye||!Xe.trim(),className:"shrink-0 px-2.5 py-1 rounded-lg bg-cyan-500/20 border border-cyan-500/40 text-cyan-200 text-[11px] font-bold disabled:opacity-40",children:Ye?"â¦":"Search"})]}),(Ue.running||(Ue.remaining??0)>0)&&e.jsx("div",{className:"px-2 py-2 flex items-center gap-2 border-b border-white/[0.06]",children:e.jsxs("button",{onClick:jt,disabled:Ue.running,title:"Embed older library assets so search matches by meaning (not just exact tags). New uploads do this automatically.",className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-violet-500/15 border border-violet-400/40 text-violet-200 text-[11px] font-bold hover:bg-violet-500/25 disabled:opacity-70 transition-colors",children:[Ue.running?e.jsx(Je,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(as,{className:"w-3.5 h-3.5"}),Ue.running?`Indexing library⦠${Ue.updated} done${Ue.remaining!=null?`, ${Ue.remaining} left`:""}`:`⨠Make ${Ue.remaining} older asset${Ue.remaining===1?"":"s"} semantically searchable`]})}),e.jsx("div",{className:"p-3",children:Ke!==null?Ye?e.jsxs("div",{className:"flex items-center justify-center h-24 gap-2 text-sm text-white/40",children:[e.jsx(Je,{className:"w-4 h-4 animate-spin"})," Searchingâ¦"]}):Ke.length===0?e.jsxs("p",{className:"text-xs text-white/30 py-6 text-center px-4",children:["No matches in your library for â",Xe,"â. Try simpler words (a scene or subject, not a name)."]}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-[10px] text-white/30 mb-2",children:[Ke.length," matches across your ",e.jsx("span",{className:"text-white/45",children:"whole library"})," · click to place · drag onto a word / card"]}),e.jsx("div",{className:"grid gap-2",style:{gridTemplateColumns:"repeat(auto-fill, minmax(84px, 1fr))"},children:Ke.map(o=>{const b=(m==null?void 0:m.get(o.url))??null;return e.jsxs("button",{draggable:!0,onDragStart:g=>er(g,{url:o.url,kind:o.kind}),onClick:()=>b&&F?F(o.url):pt({url:o.url,kind:o.kind}),title:b?"Used in this video â click to find it":"Click to place · or drag onto a word / card",className:"group relative aspect-[3/4] rounded-lg overflow-hidden border-2 bg-white/[0.03] hover:border-cyan-400/60 cursor-grab active:cursor-grabbing transition-all",style:b?{borderColor:b,boxShadow:`0 0 8px ${b}66`}:{borderColor:"rgba(255,255,255,0.08)"},children:[e.jsx("img",{src:o.kind==="video"?o.thumb||fr(o.url):o.thumb,alt:"",draggable:!1,
16className:"w-full h-full object-cover",onError:g=>{g.target.style.display="none"}}),e.jsx(pr,{pick:{url:o.url,kind:o.kind}}),b&&e.jsx("span",{className:"absolute top-1 right-1 w-2.5 h-2.5 rounded-full border border-black/40",style:{background:b}}),e.jsx("div",{className:"absolute bottom-1 left-1",children:o.kind==="video"?e.jsx(qt,{className:"w-3 h-3 text-white/70 drop-shadow"}):e.jsx($s,{className:"w-3 h-3 text-white/70 drop-shadow"})})]},o.id)})})]}):i?B==="ai_library"?e.jsx(md,{jobId:s,onPick:u}):B==="job"?e.jsx(gd,{jobId:s,onPick:u,onLocate:F,recentKeys:v,recentRemoved:_}):B==="drive"?e.jsx(Io,{source:"drive",onPick:u,chosenColorByKey:m,onLocate:F}):B==="google_photos"?e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("button",{onClick:ds,disabled:h,className:"flex items-center justify-center gap-2 py-2 rounded-lg bg-white/8 border border-white/15 text-white/70 hover:text-white text-xs font-bold disabled:opacity-40 transition-colors",children:h?e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-3.5 h-3.5 animate-spin"})," Waiting for your selectionâ¦"]}):e.jsx(e.Fragment,{children:"Pick from Google Photos"})}),e.jsx("div",{className:"flex items-center gap-1 p-0.5 rounded-lg border border-white/10 bg-white/[0.03] self-start",children:[["all","All"],["image","Photos"],["video","Videos"]].map(([o,b])=>e.jsx("button",{onClick:()=>se(o),className:`px-2.5 py-1 rounded-md text-[10px] font-black transition-all ${ee===o?"bg-gradient-to-r from-cyan-400 to-sky-400 text-black":"text-white/50 hover:text-white"}`,children:b},o))}),A.filter(o=>ee==="all"||o.kind===ee).length>0&&e.jsx("div",{className:"grid gap-2",style:{gridTemplateColumns:"repeat(auto-fill, minmax(84px, 1fr))"},children:A.filter(o=>ee==="all"||o.kind===ee).map((o,b)=>e.jsxs("button",{draggable:!0,onDragStart:g=>er(g,o),onClick:()=>pt(o),className:"group relative aspect-[3/4] rounded-lg overflow-hidden border border-white/[0.08] bg-white/[0.03] hover:border-cyan-400/60 cursor-grab active:cursor-grabbing transition-all",children:[o.kind==="video"?e.jsx("img",{src:o.thumb||fr(o.url),alt:"",draggable:!1,className:"w-full h-full object-cover",onError:g=>{g.target.style.display="none"}}):e.jsx("img",{src:o.url,alt:"",draggable:!1,className:"w-full h-full object-cover",onError:g=>{g.target.style.display="none"}}),e.jsx(pr,{pick:o}),e.jsx("div",{className:"absolute bottom-1 left-1",children:o.kind==="video"?e.jsx(qt,{className:"w-3 h-3 text-white/70 drop-shadow"}):e.jsx($s,{className:"w-3 h-3 text-white/70 drop-shadow"})})]},b))}),e.jsxs("div",{className:"border-t border-white/[0.06] pt-2",children:[e.jsxs("p",{className:"text-[10px] text-white/30 mb-2",children:["Previously picked ",e.jsx("span",{className:"text-white/25",children:"· click a photo to add it to a story section · used ones grouped + outlined"})]}),e.jsx(Io,{source:"google_photos",onPick:u,chosenColorByKey:m,chosenSectionByKey:O,onActivate:pt,onLocate:F,kindFilter:ee})]})]}):B==="upload"?e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("label",{onDragEnter:o=>{o.dataTransfer.types.includes("Files")&&Ge(!0)},onDragOver:o=>{o.dataTransfer.types.includes("Files")&&(o.preventDefault(),o.dataTransfer.dropEffect="copy",Ge(!0))},onDragLeave:o=>{o.currentTarget===o.target&&Ge(!1)},onDrop:o=>{Ge(!1);const b=Array.from(o.dataTransfer.files??[]);b.length&&(o.preventDefault(),I(b))},className:`flex flex-col items-center justify-center gap-2 py-6 rounded-lg border-2 border-dashed cursor-pointer transition-all ${we?"border-cyan-400 bg-cyan-400/10 ring-2 ring-cyan-400/40":"border-white/15 hover:border-white/30"}`,children:[e.jsx("input",{type:"file",accept:"image/*,video/*",multiple:!0,className:"hidden",onChange:o=>{const b=Array.from(o.target.files??[]);o.target.value="",I(b)}}),we?e.jsxs(e.Fragment,{children:[e.jsx(yo,{className:"w-6 h-6 text-cyan-300"}),e.jsxs("span",{className:"text-xs text-cyan-200 font-bold",children:["Drop to ",ue?"add to the queue":"upload"]})]}):ue?e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-5 h-5 animate-spin text-cyan-400"}),e.jsxs("span",{className:"text-xs text-cyan-200",children:["Uploadingâ¦",Ut>0?` · ${Ut} queued`:""," ",e.jsx("span",{className:"text-white/45",children:"· drop or choose more to add"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(yo,{className:"w-6 h-6 text-white/30"}),e.jsx("span",{className:"text-xs text-white/50",children:"Drop or choose images / videos (multiple OK)"})]})]}),vt&&e.jsxs("div",{className:"flex flex-col gap-1.5 rounded-lg border border-emerald-500/30 bg-emerald-500/[0.06] p-2.5",children:[e.jsx("div",{className:"text-[10px] font-bold text-emerald-300 flex items-center gap-1",children:"ð Local connector â batch-add a folder"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("input",{value:Mt,onChange:o=>wt(o.target.value),onKeyDown:o=>{o.key==="Enter"&&ie()},placeholder:"Paste a local folder path, e.g. C:\\\\Users\\\\â¦\\\\my-broll",className:"flex-1 min-w-0 bg-black/30 border border-white/12 rounded-md px-2 py-1 text-[12px] text-white outline-none placeholder:text-white/25"}),e.jsx("button",{onClick:ie,disabled:!!yt||!Mt.trim(),className:"shrink-0 px-2.5 py-1 rounded-md bg-emerald-500/25 border border-emerald-500/50 text-emerald-100 text-[11px] font-bold disabled:opacity-40",children:yt?e.jsx(Je,{className:"w-3.5 h-3.5 animate-spin"}):"Add"})]}),yt&&e.jsx("div",{className:"text-[10px] text-white/50",children:yt})]}),L&&L.total>0&&(()=>{const o=Math.min(100,Math.round(L.loaded/L.total*100)),b=Ql(L.loaded,L.total,L.startedAt,Date.now());return e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-[10px] text-white/50",children:[e.jsx("span",{className:"font-bold",children:"⬠Uploadingâ¦"}),e.jsxs("span",{className:"font-mono text-white/40",children:[o,"% · ",wo(L.loaded),"/",wo(L.total),b?` · ${b}`:""]})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-white/10 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-violet-400 to-cyan-400 transition-all duration-200",style:{width:`${Math.max(2,o)}%`}})})]})})(),te.length>0&&(()=>{const o=te.filter(b=>W==="all"||(W==="live"?!!b.live:b.kind===W));return e.jsxs("div",{className:"border-t border-white/[0.06] pt-2",children:[e.jsxs("p",{className:"text-[10px] text-white/30 mb-2",children:["Your uploads · ",e.jsx("span",{className:"text-white/45",children:"click to add to a
16section, or drag onto a word / card"})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mb-2",children:[e.jsx("div",{className:"flex items-center gap-1 p-0.5 rounded-lg border border-white/10 bg-white/[0.03] w-max",children:[["all","All"],["image","Images"],["video","Videos"],["live","Live"]].map(([b,g])=>e.jsx("button",{onClick:()=>S(b),className:`px-2.5 py-1 rounded-md text-[10px] font-black transition-all ${W===b?"bg-gradient-to-r from-cyan-400 to-sky-400 text-black":"text-white/50 hover:text-white"}`,children:g},b))}),e.jsx("div",{className:"flex items-center gap-1 p-0.5 rounded-lg border border-white/10 bg-white/[0.03] w-max",children:[["group","Recent"],["newest","Newest"],["oldest","Oldest"]].map(([b,g])=>e.jsx("button",{onClick:()=>Oe(b),className:`px-2 py-1 rounded-md text-[10px] font-black transition-all ${Qe===b?"bg-white/15 text-white":"text-white/45 hover:text-white"}`,children:g},b))})]}),o.length===0?e.jsx("p",{className:"text-[10px] text-white/30 py-3 text-center",children:W==="live"?"No live photos in your uploads (detected from motion-photo files).":`No ${W==="image"?"images":"videos"} in your uploads.`}):(()=>{const b=new Set(be),g=be.map(ve=>o.find(Be=>Be.url===ve)).filter(Boolean),J=o.filter(ve=>!b.has(ve.url)),X=ve=>{const Be=(m==null?void 0:m.get(ve.url))??null;return e.jsxs("button",{draggable:!0,onDragStart:Se=>er(Se,ve),onClick:()=>Be&&F?F(ve.url):pt(ve),title:Be?"In your video â click to find it on the transcript":"Click to add · or drag onto a word / card",className:"group relative shrink-0 rounded-lg overflow-hidden border-2 hover:border-cyan-400/60 cursor-grab active:cursor-grabbing transition-all bg-white/[0.03]",style:{width:84,aspectRatio:"3 / 4",...Be?{borderColor:Be,boxShadow:`0 0 8px ${Be}66`}:{borderColor:"rgba(255,255,255,0.08)"}},children:[ve.kind==="video"?e.jsx("img",{src:ve.thumb||fr(ve.url),alt:"",draggable:!1,className:"w-full h-full object-cover",onError:Se=>{Se.target.style.display="none"}}):e.jsx("img",{src:ve.url,alt:"",draggable:!1,className:"w-full h-full object-cover",onError:Se=>{Se.target.style.display="none"}}),e.jsx(pr,{pick:ve}),e.jsx("div",{className:"absolute bottom-1 left-1",children:ve.kind==="video"?e.jsx(qt,{className:"w-3 h-3 text-white/70 drop-shadow"}):e.jsx($s,{className:"w-3 h-3 text-white/70 drop-shadow"})}),ve.live&&e.jsx("span",{className:"absolute top-1 right-1 text-[7px] font-black bg-amber-400/90 text-black px-1 rounded",title:"Live / motion photo",children:"LIVE"})]},ve.url)};if(Qe!=="group"){const ve=[...o].sort((Be,Se)=>{const We=Ee(Be.url),ft=Ee(Se.url);return Qe==="newest"?ft-We:We-ft});return e.jsx("div",{className:"flex flex-wrap gap-2 pb-1",children:ve.map(X)})}return e.jsxs("div",{className:"flex flex-col gap-2",children:[g.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-black text-emerald-300/70 uppercase tracking-widest mb-1.5",children:"Recently uploaded"}),e.jsx("div",{className:"flex flex-wrap gap-2 pb-1",children:g.map(X)})]}),J.length>0&&e.jsxs("div",{children:[g.length>0&&e.jsx("div",{className:"text-[10px] font-black text-white/35 uppercase tracking-widest mb-1.5 mt-1",children:"All uploads"}),e.jsx("div",{className:"flex flex-wrap gap-2 pb-1",children:J.map(X)})]})]})})()]})})()]}):B==="local"?e.jsxs("div",{className:"flex flex-col gap-3",children:[je&&je.total>0?e.jsxs("div",{className:"flex flex-col gap-1.5 bg-violet-500/10 border border-violet-500/25 rounded-lg px-2.5 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-[11px] text-violet-200",children:[e.jsxs("span",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx(Je,{className:"w-3.5 h-3.5 animate-spin shrink-0"}),e.jsxs("span",{className:"truncate",children:["Analyzing videos · ",je.done,"/",je.total,je.name?` · ${je.name}`:""]})]}),e.jsx("span",{className:"shrink-0 font-mono text-violet-300/90",children:je.etaSec>0?`~${je.etaSec>=60?`${Math.floor(je.etaSec/60)}m ${Math.round(je.etaSec%60)}s`:`${Math.round(je.etaSec)}s`} left`:"estimatingâ¦"})]}),e.jsx("div",{className:"h-1.5 w-full overflow-hidden rounded-full bg-white/10",children:e.jsx("div",{className:"h-full bg-violet-400 transition-[width] duration-300",style:{width:`${Math.round(je.done/je.total*100)}%`}})}),e.jsx("p",{className:"text-[9px] text-white/35",children:"One-time per video â cached after, so future searches are instant."})]}):z?e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-violet-200 bg-vi
16olet-500/10 border border-violet-500/25 rounded-lg px-2.5 py-2",children:[e.jsx(Je,{className:"w-3.5 h-3.5 animate-spin shrink-0"})," ",z]}):null,Ve!==null&&!z&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-[10px] text-white/40",children:[Ve.length," moment",Ve.length!==1?"s":""," for â",Xe,"â · click to place that ~",Ve[0]?Ve[0].dur_sec.toFixed(0):3,"s"]}),e.jsx("button",{onClick:()=>{D(null),Ao(s)},className:"text-[10px] text-white/40 hover:text-white",children:"â clear"})]}),Ve.length===0?e.jsxs("p",{className:"text-[11px] text-white/30 py-3 text-center",children:["No moment found for â",Xe,"â. Try a simpler object/scene, or add more video folders."]}):e.jsx("div",{className:"flex flex-col gap-1.5",children:Ve.map(o=>{const b=g=>`${Math.floor(g/60)}:${String(Math.floor(g%60)).padStart(2,"0")}`;return e.jsxs("button",{onClick:()=>lt(o),className:"flex items-center gap-2 text-left rounded-lg border border-white/10 bg-white/[0.03] hover:border-violet-400/60 hover:bg-violet-400/5 p-1.5 transition-colors",children:[e.jsx("video",{src:on(`http://localhost:7742/local-file?path=${encodeURIComponent(o.local_path)}#t=${o.start_sec}`),muted:!0,playsInline:!0,preload:"metadata",className:"w-16 h-12 object-cover rounded shrink-0 bg-black"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[11px] font-bold text-white truncate",children:o.label}),e.jsxs("span",{className:"text-[10px] font-mono text-violet-300 shrink-0",children:[b(o.start_sec),"â",b(o.end_sec)]}),o.matched&&e.jsx("span",{className:"text-[9px] text-emerald-300 shrink-0",children:"â match"})]}),e.jsx("p",{className:"text-[10px] text-white/45 truncate",children:o.notes||"moment"})]})]},o.media_item_id+o.start_sec)})}),e.jsx("div",{className:"border-t border-white/10 my-1"})]}),e.jsxs("label",{onDragEnter:o=>{o.dataTransfer.types.includes("Files")&&Lt(!0)},onDragOver:o=>{o.dataTransfer.types.includes("Files")&&(o.preventDefault(),o.dataTransfer.dropEffect="copy",Lt(!0))},onDragLeave:o=>{o.currentTarget===o.target&&Lt(!1)},onDrop:o=>{Lt(!1),o.preventDefault();const b=Ts(o);if(vt&&b.length){P(b);return}const g=Array.from(o.dataTransfer.items??[]).some(X=>{var ve,Be;return(Be=(ve=X.webkitGetAsEntry)==null?void 0:ve.call(X))==null?void 0:Be.isDirectory}),J=Array.from(o.dataTransfer.files??[]).filter(X=>X.type||/\.[a-z0-9]+$/i.test(X.name));if(J.length){Ft(J,b.length?b:void 0);return}H({title:g?"Can't read a dropped folder":"Couldn't read that drop",description:vt?"Paste the folder (or file) path in âAdd by pathâ below â it indexes all subfolders, no upload.":"Start the local bridge, then paste the folder path in âAdd by pathâ.",variant:"destructive"})},className:`flex flex-col items-center justify-center gap-2 py-5 rounded-lg border-2 border-dashed cursor-pointer transition-all ${it?"border-violet-400 bg-violet-400/10 ring-2 ring-violet-400/40":"border-white/15 hover:border-white/30"}`,children:[e.jsx("input",{type:"file",accept:"image/*,video/*",multiple:!0,className:"hidden",onChange:o=>{const b=Array.from(o.target.files??[]);o.target.value="",Ft(b)}}),yt?e.jsx(Je,{className:"w-6 h-6 animate-spin text-violet-300"}):e.jsx(Jl,{className:`w-6 h-6 ${it?"text-violet-300":"text-white/30"}`}),e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:`text-xs font-bold ${yt||it?"text-violet-200":"text-white/50"}`,children:yt||(it?"Drop to index (folders OK · no upload)":"Drop files or a folder, or click to browse")}),!it&&!yt&&e.jsx("p",{className:"text-[10px] text-white/30 mt-0.5",children:vt?"Folders welcome â nothing uploads until you place a clip":"No upload until you place a clip"})]})]}),vt&&e.jsxs("div",{className:"flex flex-col gap-1.5 rounded-lg border border-violet-500/30 bg-violet-500/[0.06] p-2.5",children:[e.jsx("div",{className:"text-[10px] font-bold text-violet-300 flex items-center gap-1",children:"ð Add by path (local bridge)"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("input",{value:kt,onChange:o=>Wt(o.target.value),onKeyDown:o=>{o.key==="Enter"&&Ot()},placeholder:String.raw`File OR folder, e.g. E:\Cello\Pura Pura Lupa`,className:"flex-1 min-w-0 bg-black/30 border border-white/12 rounded-md px-2 py-1 text-[12px] text-white outline-none placeholder:text-white/25"}),e.jsx("button",{onClick:Ot,disabled:is||!kt.trim(),className:"shrink-0 px-2.5 py-1 rounded-md bg-vi
16olet-500/25 border border-violet-500/50 text-violet-100 text-[11px] font-bold disabled:opacity-40",children:is?e.jsx(Je,{className:"w-3.5 h-3.5 animate-spin"}):"Add"})]})]}),Te.length>0&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("p",{className:"text-[10px] text-white/30",children:["Staged locally · ",e.jsx("span",{className:"text-white/45",children:"drag onto a word/card, or click to place"}),Nt?e.jsx("span",{className:"ml-1 text-emerald-300/80",title:"The bridge tunnel is live â by-path clips are referenced from your machine, NOT uploaded. Keep the bridge running through the render.",children:"· ð no-upload (tunnel)"}):e.jsx("span",{className:"ml-1 text-white/30",title:"No public tunnel â clips upload to storage on place. Install cloudflared or set VIRALSPIN_BRIDGE_PUBLIC_URL on the bridge for no-upload.",children:"· uploads on place"})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Te.map(o=>{var X;const b=((X=o.file)==null?void 0:X.name)||(o.path?o.path.split(/[/\\]/).pop():void 0)||"clip",g=o.blobUrl||o.thumbUrl||"",J=o.blobUrl||o.thumbUrl||"";return e.jsxs("div",{draggable:!0,onDragStart:ve=>{Xt(o),er(ve,{url:ls(o),kind:o.kind})},onClick:()=>{St||As(o)},title:`${b} · click to place · drag onto a word or card`,className:"relative group shrink-0 rounded-lg overflow-hidden border-2 border-white/[0.08] hover:border-violet-400/60 cursor-grab active:cursor-grabbing transition-all bg-white/[0.03]",style:{width:84,aspectRatio:"3 / 4"},children:[o.kind==="image"?e.jsx("img",{src:g,alt:"",draggable:!1,loading:"lazy",className:"w-full h-full object-cover"}):o.thumbDataUrl?e.jsx("img",{src:o.thumbDataUrl,alt:"",draggable:!1,loading:"lazy",className:"w-full h-full object-cover"}):e.jsx("video",{src:on(J),muted:!0,playsInline:!0,preload:"metadata",draggable:!1,className:"w-full h-full object-cover"}),St===o.id&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/60",children:e.jsx(Je,{className:"w-5 h-5 animate-spin text-violet-300"})}),e.jsx("button",{onClick:ve=>{ve.stopPropagation(),Gt(o.id)},className:"absolute top-1 right-1 z-10 w-4 h-4 rounded-full bg-black/70 border border-white/20 text-white/70 hover:text-white hover:bg-red-500/80 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",title:"Remove from staging",children:e.jsx(os,{className:"w-2.5 h-2.5"})}),e.jsx("div",{className:"absolute bottom-1 left-1",children:o.kind==="video"?e.jsx(qt,{className:"w-3 h-3 text-white/70 drop-shadow"}):e.jsx($s,{className:"w-3 h-3 text-white/70 drop-shadow"})}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent px-1 pb-1 pt-3 opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none",children:e.jsx("p",{className:"text-[8px] text-white/70 truncate leading-tight",children:b})})]},o.id)})})]}),Te.length===0&&e.jsx("p",{className:"text-[10px] text-white/25 text-center py-2",children:"Staged files appear here â they're only on your machine until you place one."})]}):e.jsx("div",{className:"flex flex-col gap-2",children:rt===null?e.jsx("p",{className:"text-xs text-white/30 py-4 text-center",children:"This cut isnât an AI-generated beat, so it canât be regenerated. Use Drive / Photos / Upload instead."}):e.jsxs(e.Fragment,{children:[e.jsx("textarea",{value:G,onChange:o=>oe(o.target.value),rows:3,placeholder:"Optional: describe what this shot should show (leave blank to regenerate with the existing prompt)â¦",className:"w-full bg-white/[0.04] border border-white/10 rounded-lg px-3 py-2 text-white placeholder-white/25 text-xs focus:outline-none focus:border-violet-400/60 resize-none"}),e.jsx("button",{onClick:le,disabled:Pe,className:"flex items-center justify-center gap-2 py-2 rounded-lg bg-gradient-to-r from-violet-600 to-fuchsia-600 hover:from-violet-500 hover:to-fuchsia-500 disabled:opacity-40 text-white font-bold text-xs transition-all",children:Pe?e.jsxs(e.Fragment,{children:[e.jsx(Je,{className:"w-3.5 h-3.5 animate-spin"})," Generatingâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(as,{className:"w-3.5 h-3.5"})," Regenerate this clip"]})})]})}):e.jsx("p",{className:"text-xs text-white/30 py-6 text-center",children:"Select a cut above to swap its B-roll."})})]})]})}function Lo({jobId:s,open:i,onClose:c,inline:u=!1,segment:p,isAiJob:m,contextLabel:v,onPick:_,onAddToEnd:O,chosenColorByKey:
16Q,recentKeys:q,recentRemoved:F,chosenSectionByKey:E,arcSections:w,onAddToSection:H,onLocate:B,placedUploads:K,focusSearchNonce:h}){const[V,ee]=n.useState(()=>{const S=Number(typeof localStorage<"u"&&localStorage.getItem("swaprefine:libW"));return Number.isFinite(S)&&S>=380?Math.min(S,1100):460}),se=n.useRef(V);n.useEffect(()=>{se.current=V},[V]);const W=S=>{S.preventDefault();const A=xe=>ee(Math.max(380,Math.min(1100,window.innerWidth-xe.clientX))),k=()=>{window.removeEventListener("pointermove",A),window.removeEventListener("pointerup",k);try{localStorage.setItem("swaprefine:libW",String(Math.round(se.current)))}catch{}};window.addEventListener("pointermove",A),window.addEventListener("pointerup",k)};return n.useEffect(()=>{if(!i)return;const S=A=>{A.key==="Escape"&&c()};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[i,c]),!u&&!i?null:e.jsxs("div",{className:u?"sr-light flex h-full w-full flex-col overflow-hidden bg-[#f2f1ec]":"sr-light fixed right-0 top-0 bottom-0 z-50 bg-[#f2f1ec] border-l border-black/10 shadow-2xl flex flex-col",style:u?void 0:{width:V,maxWidth:"92vw"},children:[!u&&e.jsx("div",{onPointerDown:W,title:"Drag to resize the library",className:"absolute left-0 top-0 bottom-0 w-1.5 -ml-0.5 cursor-col-resize z-50 hover:bg-cyan-400/40 transition-colors"}),e.jsxs("header",{className:"flex items-center gap-2 px-4 py-3 border-b border-black/10 shrink-0",children:[!u&&e.jsx("button",{onClick:c,title:"Close (Esc)",className:"-ml-1 rounded-md p-1.5 text-[#6b675e] hover:bg-black/[0.06] hover:text-[#26241f]",children:e.jsx(os,{className:"w-4 h-4"})}),e.jsx("h2",{className:"text-sm font-black text-[#26241f]",children:"B-roll Library"}),v&&e.jsx("span",{className:"text-[11px] text-cyan-300/80 font-semibold truncate",children:v})]}),e.jsxs("p",{className:"px-4 py-2 text-[11px] text-white/40 border-b border-black/[0.06] shrink-0",children:[e.jsx("span",{className:"text-cyan-300 font-semibold",children:"Click"})," a clip to place it here, or ",e.jsx("span",{className:"text-violet-300 font-semibold",children:"drag"})," it onto a word / card in the transcript."]}),e.jsx("div",{className:"flex-1 overflow-auto thin-scroll p-3",children:e.jsx(hi,{jobId:s,segment:p,isAiJob:m,onPick:_,onAddToEnd:O,chosenColorByKey:Q,recentKeys:q,recentRemoved:F,chosenSectionByKey:E,arcSections:w,onAddToSection:H,onLocate:B,placedUploads:K,focusSearchNonce:h})})]})}const bd="application/x-viralspin-broll",wd=s=>{const i=Math.max(0,Math.round(s/1e3));return`${Math.floor(i/60)}:${String(i%60).padStart(2,"0")}`};function vd({jobId:s,open:i,onClose:c,onPick:u}){const{data:p,isLoading:m}=js({queryKey:["swap-ai-library",s],queryFn:()=>mr(s),staleTime:6e4,enabled:i});if(n.useEffect(()=>{if(!i)return;const _=O=>{O.key==="Escape"&&c()};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[i,c]),!i)return null;const v=((p==null?void 0:p.scenes)??[]).filter(_=>_.clip_url||_.image_url).sort((_,O)=>(_.timestamp_ms??0)-(O.timestamp_ms??0));return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-40 bg-black/30",onClick:c,"aria-hidden":"true"}),e.jsxs("div",{className:"fixed right-0 top-0 bottom-0 z-50 w-[380px] max-w-[90vw] bg-[#0e0e12] border-l border-white/10 shadow-2xl flex flex-col",children:[e.jsxs("header",{className:"flex items-center gap-2 px-4 py-3 border-b border-white/10 shrink-0",children:[e.jsx("h2",{className:"text-sm font-black text-white",children:"AI B-roll Library"}),e.jsxs("span",{className:"text-[11px] text-white/35",children:[v.length," clips"]}),e.jsx("button",{onClick:c,title:"Close (Esc)",className:"ml-auto -mr-1 p-1.5 rounded-md text-white/50 hover:text-white hover:bg-white/10",children:e.jsx(os,{className:"w-4 h-4"})})]}),e.jsxs("p",{className:"px-4 py-2 text-[11px] text-white/40 border-b border-white/[0.06] shrink-0",children:[e.jsx("span",{className:"text-violet-300 font-semibold",children:"Drag a clip onto a word"})," in the transcript to place it there â or click to add at the selected word / replace the selected clip."]}),m?e.jsxs("div",{className:"flex-1 flex items-center justify-center gap-2 text-sm text-white/40",children:[e.jsx(Je,{className:"w-4 h-4 animate-spin"})," Loadingâ¦"]}):v.length?e.jsx("div",{className:"flex-1 overflow-auto thin-scroll p-3 grid gap-3 content-start",style:{gridTemplateColumns:"repeat(auto-fill, minmax(120px, 1fr))"},children:v.map(_=>{const O={url:_.clip_url||_.image_url,kind:_.clip_url?"video":"image"};return e.jsxs("button",{draggable:!0,onDragStart:Q=>{Q.dataTransfer.setData(bd,JSON.stringify(O)),Q.dataTransfer.effectAllowed="copy"},onClick:()=>u(O),className:"group flex flex-col gap-1 cursor-grab active:cursor-grabbing",title:_.description||`Beat ${_.beat_index}`,children:[e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-white/[0.1] bg-white/[0.03] group-hover:border-violet-400/70 transition-all",style:{aspectRatio:"9 / 16"},children:[_.image_url?e.jsx("img",{src:_.image_url,alt:"",loading:"lazy",className:"w-full h-full object-cover group-hover:scale-[1.03] transition-transform",onError:Q=>{Q.target.style.display="none"}}
16):e.jsx("video",{src:_.clip_url,muted:!0,playsInline:!0,preload:"metadata",className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute bottom-1 left-1",children:_.clip_url?e.jsx(qt,{className:"w-3 h-3 text-white/70 drop-shadow"}):e.jsx($s,{className:"w-3 h-3 text-white/70 drop-shadow"})})]}),e.jsx("span",{className:"text-[9px] font-mono text-white/30",children:wd(_.timestamp_ms??0)})]},_.id)})}):e.jsx("div",{className:"flex-1 flex items-center justify-center text-xs text-white/30 text-center px-6",children:"No AI-generated B-roll for this video."})]})]})}const Do=new Set(["crossfade","dissolve","fade"]);function yd(s,i){if(!Do.has(s.transition_out)||!Do.has(i.transition_in))return 0;const c=Math.min(s.transition_out_duration_ms||0,i.transition_in_duration_ms||0)/1e3,u=.5*Math.min(s.duration_sec,i.duration_sec);return Math.max(0,Math.min(c,u,s.duration_sec-.05,i.duration_sec-.05))}function jd(s){const i=s.timeline??[],c={};let u=0;return i.forEach((p,m)=>{const v=m===0?0:u+i[m-1].duration_sec-yd(i[m-1],p);c[p.segment_id]=v,u=v}),c}const xi=s=>`/v1/assembly/thumb?kind=video&url=${encodeURIComponent(s)}`;function Nd({b:s}){const i=s.asset_url;if(!i||i.startsWith("blob:"))return null;const c=s.type==="broll_video"?xi(i):i;return e.jsx("img",{src:c,alt:"",loading:"lazy",className:"absolute inset-0 h-full w-full object-cover",onError:u=>{u.target.style.display="none"}})}const Po=3.2;function $r(s){const i=Math.floor(s/60),c=Math.floor(s%60);return`${i}:${c.toString().padStart(2,"0")}`}function Oo(s,i){if(s.reason)return s.reason;if(!i.length)return"";let c="";for(const u of i)u.at_sec<=s.start_sec+.001&&(c=u.label);return c?`chapter: ${c}`:""}function Uo(s){const i=Math.min(10,Math.max(2,Math.round(s/5)));return Array.from({length:i+1},(c,u)=>s*u/i)}function _d({brolls:s,durationSec:i,sections:c=[],label:u,playerRef:p,fps:m=30,onClipClick:v,onClipMove:_,audioUrl:O,arollUrl:Q,musicUrl:q,replaceArollAudio:F}){const E=Math.max(i,.001),w=[...s].sort((D,z)=>D.start_sec-z.start_sec),[H,B]=n.useState(null),[K,h]=n.useState(!1),[V,ee]=n.useState(1),[se,W]=n.useState(0),[S,A]=n.useState(!0),[k,xe]=n.useState(null),[Le,qe]=n.useState([]),[fe,Ae]=n.useState(0);n.useEffect(()=>{if(!O){qe([]);return}let D=!1;return(async()=>{try{const z=await(await fetch(O)).arrayBuffer(),ye=window.AudioContext||window.webkitAudioContext;if(!ye)return;const je=new ye,Z=await je.decodeAudioData(z),ke=Z.getChannelData(0),Ie=Math.min(2400,Math.max(300,Math.round(Z.duration*18))),Ue=Math.max(1,Math.floor(ke.length/Ie)),ot=[];for(let xt=0;xt<Ie;xt++){let Nt=0;const bt=xt*Ue,Mt=Math.min(ke.length,bt+Ue);for(let wt=bt;wt<Mt;wt+=2){const yt=Math.abs(ke[wt]);yt>Nt&&(Nt=yt)}ot.push(Nt)}let jt=1e-4;for(const xt of ot)xt>jt&&(jt=xt);const lt=ot.map(xt=>Math.sqrt(xt/jt)),vt=Z.duration;try{je.close()}catch{}D||(qe(lt),Ae(vt))}catch{D||qe([])}})(),()=>{D=!0}},[O]);const R=n.useRef(!1);n.useEffect(()=>{R.current||w.length===0||(R.current=!0,ee(Math.min(4,Math.max(1,Math.round(w.length/10)))))},[w.length]);const[$,te]=n.useState(0),[ue,st]=n.useState(!1),[be,Ce]=n.useState(!1),he=n.useRef(null),Qe=n.useRef(null);n.useEffect(()=>{const D=Qe.current;if(!D)return;const z=ye=>{if(D.scrollWidth<=D.clientWidth+1)return;const je=Math.abs(ye.deltaX)>=Math.abs(ye.deltaY)?ye.deltaX:ye.deltaY;je!==0&&(D.scrollLeft+=je,ye.preventDefault())};return D.addEventListener("wheel",z,{passive:!1}),()=>D.removeEventListener("wheel",z)},[]),n.useEffect(()=>{if(!p)return;let D=0,z=null;const ye=Ie=>{var Ue;return te(((Ue=Ie==null?void 0:Ie.detail)==null?void 0:Ue.frame)??0)},je=()=>st(!0),Z=()=>st(!1),ke=()=>{const Ie=p.current;if(Ie){z=Ie,Ie.addEventListener("frameupdate",ye),Ie.addEventListener("play",je),Ie.addEventListener("pause",Z);try{te(Ie.getCurrentFrame()),st(Ie.isPlaying())}catch{}}else D=requestAnimationFrame(ke)};return ke(),()=>{if(cancelAnimationFrame(D),z)try{z.removeEventListener("frameupdate",ye),z.removeEventListener("play",je),z.removeEventListener("pause",Z)}catch{}}},[p]);const Oe=Math.min(100,Math.max(0,$/m/E*100)),Ee=D=>{const z=he.current;if(!z)return 0;const ye=z.getBoundingClientRect();return Math.min(1,Math.max(0,(D-ye.left)/ye.width))*E},L=D=>{const z=p==null?void 0:p.current;if(z)try{z.seekTo(Math.round(Ee(D)/E*E*m))}catch{}},pe=n.useRef(null),we=!!p||!!v||!!_,Ge=D=>{var Z,ke;if(!we)return;const z=(ke=(Z=D.target)==null?void 0:Z.closest)==null?void 0:ke.call(Z,"[data-clip-id]"),ye=(z==null?void 0:z.getAttribute("data-clip-id"))??null;let je=0;if(ye){const Ie=w.find(Ue=>Ue.id===ye);Ie&&(je=Ee(D.clientX)-Ie.start_sec)}pe.current={x:D.clientX,moved:!1,clipId:ye,grabOffsetSec:je};try{D.currentTarget.setPointerCapture(D.pointerId)}catch{}},et=D=>{var ye;const z=pe.current;if(z){if(!z.moved&&Math.abs(D.clientX-z.x)>3&&(z.moved=!0,!(z.clipId&&_))){Ce(!0);try{(ye=p==null?void 0:p.current)==null||ye.pause()}catch{}}z.moved&&(z.clipId&&_?xe({id:z.clipId,startSec:Math.max(0,Ee(D.clientX)-z.grabOffsetSec)}):p!=null&&p.current&&L(D.clientX))}},dt=D=>{const z=pe.current;pe.current=null,Ce(!1);try{D.currentTarget.releasePointerCapture(D.pointerId)}catch{}
16if(z){if(!z.moved){z.clipId&&v?v(z.clipId):p!=null&&p.current&&L(D.clientX);return}z.clipId&&_&&_(z.clipId,Math.max(0,Ee(D.clientX)-z.grabOffsetSec)),xe(null)}},Xe=n.useRef(!1);n.useEffect(()=>{Xe.current||!w.length||(Xe.current=!0,A(!0))},[w.length]);const at=()=>{W(D=>D+1),A(!0)},Ye=n.useRef(new Map),[gt,Ke]=n.useState(new Set);n.useEffect(()=>{const D=[],z=new Map;for(const Z of s){z.set(Z.id,Z.asset_url);const ke=Ye.current.get(Z.id);ke!==void 0&&ke!==Z.asset_url&&D.push(Z.id)}const ye=Ye.current.size>0;if(Ye.current=z,!ye||!D.length)return;Ke(Z=>new Set([...Z,...D]));const je=setTimeout(()=>{Ke(Z=>{const ke=new Set(Z);return D.forEach(Ie=>ke.delete(Ie)),ke})},1200);return()=>clearTimeout(je)},[s]);const tt=H!=null?w[H]:null,ut=tt?Oo(tt,c):"",ht=K?"h-56":"h-32";let Ve=null;if(k){const D=w.find(z=>z.id===k.id);if(D){const z=w.filter(Ue=>Ue.id!==k.id),ye=k.startSec+(D.dur_sec||0)/2;let je=0;for(const Ue of z)Ue.start_sec+(Ue.dur_sec||0)/2<ye&&je++;const Z=[...z.slice(0,je),D,...z.slice(je)],ke=w.length?w[0].start_sec:0;Ve=new Map;let Ie=ke;for(const Ue of Z)Ve.set(Ue.id,Ie),Ie+=Ue.dur_sec||0}}return e.jsxs("div",{className:"w-full select-none",children:[e.jsxs("div",{className:"relative mb-1 flex items-center justify-between text-xs text-muted-foreground",children:[p&&e.jsx("button",{onClick:()=>{const D=p.current;if(D)try{ue?D.pause():D.play()}catch{}},title:ue?"Pause":"Play",className:"absolute left-1/2 top-1/2 z-10 -translate-x-1/2 -translate-y-1/2 inline-flex h-7 w-7 items-center justify-center rounded-full border border-cyan-400/40 bg-cyan-400/15 text-cyan-200 shadow-[0_0_10px_rgba(34,211,238,0.35)] transition-colors hover:bg-cyan-400/25",children:ue?e.jsx(la,{className:"h-3.5 w-3.5"}):e.jsx(_s,{className:"h-3.5 w-3.5 translate-x-[1px]"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-foreground",children:u??"Timeline"}),e.jsxs("button",{onClick:at,title:"Replay the build animation",className:"inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[11px] text-cyan-300 hover:bg-cyan-400/10",children:[e.jsx(_s,{className:"h-3 w-3"})," Replay"]}),e.jsx("button",{onClick:()=>h(D=>!D),title:K?"Collapse":"Expand",className:"inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[11px] hover:bg-white/10",children:K?e.jsx(wc,{className:"h-3 w-3"}):e.jsx(wr,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{children:[w.length," cutaway",w.length===1?"":"s"," · ",$r(E)]}),e.jsxs("div",{className:"inline-flex items-center gap-0.5 rounded-md border border-white/10 bg-white/[0.03] px-0.5",children:[e.jsx("button",{onClick:()=>ee(D=>Math.max(1,+(D-.5).toFixed(1))),disabled:V<=1,title:"Zoom out",className:"inline-flex items-center rounded px-1 py-0.5 hover:bg-white/10 disabled:opacity-30",children:e.jsx(Zo,{className:"h-3.5 w-3.5"})}),e.jsxs("span",{className:"w-7 text-center text-[10px] tabular-nums",children:[V.toFixed(1),"Ã"]}),e.jsx("button",{onClick:()=>ee(D=>Math.min(8,+(D+.5).toFixed(1))),disabled:V>=8,title:"Zoom in",className:"inline-flex items-center rounded px-1 py-0.5 hover:bg-white/10 disabled:opacity-30",children:e.jsx(Qo,{className:"h-3.5 w-3.5"})})]})]})]}),e.jsx("div",{ref:Qe,className:"overflow-x-auto overflow-y-hidden thin-scroll",children:e.jsxs("div",{ref:he,onPointerDown:we?Ge:void 0,onPointerMove:we?et:void 0,onPointerUp:we?dt:void 0,style:{width:`${V*100}%`,minWidth:"100%"},className:`relative ${p?"cursor-col-resize":""}`,children:[e.jsx("div",{className:"relative mb-1 h-5 w-full border-b border-white/10",children:Uo(E).map((D,z,ye)=>{const je=D/E*100,Z=ye[z+1],ke=Z!=null?(D+Z)/2/E*100:null;return e.jsxs("div",{children:[e.jsxs("div",{className:"absolute top-0 flex flex-col items-center",style:{left:`${je}%`,transform:"translateX(-50%)"},children:[e.jsx("span",{className:"text-[10px] leading-none text-muted-foreground/80",children:$r(D)}),e.jsx("span",{className:"mt-0.5 h-2 w-px",style:{background:"rgba(0,0,0,0.32)"}})]}),ke!=null&&e.jsx("span",{className:"absolute bottom-0 h-1.5 w-px",style:{left:`${ke}%`,background:"rgba(0,0,0,0.16)"}})]},z)})}),e.jsxs("div",{className:`relative ${ht} w-full overflow-hidden rounded-md border border-border bg-gradient-to-b from-muted/30 to-muted/60`,children:[e.jsx("span",{className:"pointer-events-none absolute right-1.5 top-1 z-20 rounded bg-black/55 px-1.5 py-0.5 text-[8px] font-black uppercase tracking-widest text-cyan-200/80",children:"B-roll"}),Uo(E).map((D,z)=>e.jsx("div",{className:"absolute top-0 bottom-0 w-px bg-white/5",style:{left:`${D/E*100}%`}},z)),e.jsx(vc,{children:w.map((D,z)=>{const ye=(k==null?void 0:k.id)===D.id,je=ye?k.startSec:(Ve==null?void 0:Ve.get(D.id))??D.start_sec,Z=Math.min(100,Math.max(0,je/E*100)),ke=Math.min(100-Z,Math.max(.6,(D.dur_sec||0)/E*100)),Ie=br(D.asset_id||D.asset_url),Ue=D.start_sec/E*Po;return e.jsxs(Cr.div,{layout:!ye,initial:{opacity:0,y:-18,scale:.7}
16,animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:14,scale:.7},transition:k?{type:"spring",stiffness:700,damping:42}:{type:"spring",stiffness:420,damping:32,delay:Ue},"data-clip-id":D.id,onMouseEnter:()=>B(z),onMouseLeave:()=>B(ot=>ot===z?null:ot),className:`absolute top-1 bottom-1 overflow-hidden rounded-[4px] ring-cyan-300 hover:ring-2 ${v?"cursor-pointer":""} ${ye?"z-40 ring-2 ring-cyan-200 shadow-[0_0_14px_rgba(34,211,238,0.8)]":""}`,style:{left:`${Z}%`,width:`${ke}%`,background:Ie,opacity:ye?.92:void 0},title:[`${D.type==="broll_video"?"video":"photo"} · ${$r(D.start_sec)}â${$r(D.start_sec+(D.dur_sec||0))}`,Oo(D,c)].filter(Boolean).join(` 17`),children:[e.jsx(Nd,{b:D},D.asset_url),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/50 via-transparent to-transparent"}),e.jsx("div",{className:"absolute inset-x-0 top-0 h-[3px]",style:{background:Ie}}),e.jsx(Cr.div,{className:"pointer-events-none absolute inset-0 bg-white",initial:{opacity:0},animate:{opacity:[0,.75,0]},transition:{duration:.45,delay:Ue,times:[0,.25,1]}},`land-${se}`),gt.has(D.id)&&e.jsx(Cr.div,{className:"pointer-events-none absolute inset-0 rounded-[4px] ring-2 ring-cyan-300",initial:{opacity:0}
17,animate:{opacity:[0,1,1,0],boxShadow:["0 0 0px rgba(34,211,238,0)","0 0 14px rgba(34,211,238,0.9)","0 0 14px rgba(34,211,238,0.9)","0 0 0px rgba(34,211,238,0)"]},transition:{duration:1.2}}),e.jsx(Cr.span,{initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.25},className:"absolute left-1 top-1 rounded bg-black/55 px-1 text-[10px] font-bold leading-tight text-white",children:z+1},`${D.asset_url}-n`),K&&e.jsxs("span",{className:"absolute bottom-0.5 left-1 text-[8px] font-medium leading-none text-white/85",children:[(D.dur_sec||0).toFixed(1),"s"]})]},`${D.id}-${se}`)})}),S&&w.length>0&&e.jsx(Cr.div,{className:"pointer-events-none absolute top-0 bottom-0 z-10 w-[2px] bg-cyan-300 shadow-[0_0_8px_2px_rgba(34,211,238,0.7)]",initial:{left:"0%",opacity:1},animate:{left:"100%",opacity:[1,1,1,0]},transition:{duration:Po,ease:"linear"},onAnimationComplete:()=>A(!1),children:e.jsx("div",{className:"absolute top-0 left-1/2 h-2 w-2 -translate-x-1/2 rotate-45 bg-cyan-300"})},`playhead-${se}`),w.length===0&&e.jsx("div",{className:"flex h-full items-center justify-center text-xs text-muted-foreground",children:"No cutaways yet â they'll stream in here as they're placed."})]}),e.jsxs("div",{className:"relative mt-1 h-10 w-full overflow-hidden rounded border border-emerald-400/40 bg-emerald-500/[0.06]",title:"A-roll â the backbone video",children:[e.jsx("span",{className:"pointer-events-none absolute right-1.5 top-1 z-20 rounded bg-black/55 px-1.5 py-0.5 text-[8px] font-black uppercase tracking-widest text-emerald-200/90",children:"A-roll"}),Q?e.jsx("div",{className:"absolute inset-y-0 left-0 overflow-hidden border-r-2 border-emerald-400/60 bg-black/30",style:{width:`${fe&&E?Math.min(100,fe/E*100):100}%`},children:e.jsx("img",{src:xi(Q),alt:"",loading:"lazy",className:"h-full w-full object-cover opacity-85",onError:D=>{D.target.style.display="none"}})}):e.jsx("div",{className:"flex h-full items-center pl-2 text-[9px] text-white/25",children:"No A-roll â narration / montage backbone"})]}),e.jsxs("div",{className:"relative mt-1 h-10 w-full overflow-hidden rounded border border-fuchsia-400/25 bg-black/40",title:q?"Audio â narration + music bed":"Audio â the A-roll narration",children:[e.jsx("span",{className:"pointer-events-none absolute right-1.5 top-1 z-20 rounded bg-black/55 px-1.5 py-0.5 text-[8px] font-black uppercase tracking-widest text-fuchsia-700",children:"Audio"}),Le.length>0?e.jsx("div",{className:"absolute inset-y-0 left-0",style:{width:`${fe&&E?Math.min(100,fe/E*100):100}%`},children:e.jsxs("svg",{className:"h-full w-full",viewBox:`0 0 ${Le.length} 100`,preserveAspectRatio:"none",children:[e.jsx("rect",{x:0,y:"49.6",width:Le.length,height:"0.8",fill:"rgba(5,150,105,0.3)"}),Le.map((D,z)=>{const ye=Math.max(1,D*98);return e.jsx("rect",{x:z+.1,width:.8,y:(100-ye)/2,height:ye,fill:"rgba(5,150,105,0.82)"},z)})]})}):e.jsx("div",{className:"flex h-full items-center pl-2 text-[9px] text-white/30",children:Q||O?"Audio waveform loadingâ¦":"No audio yet"}),q&&e.jsxs("div",{className:"absolute inset-x-0 bottom-0 flex items-center gap-1 border-t border-fuchsia-400/20 bg-fuchsia-500/10 px-2 py-0.5 text-[8px] font-semibold text-fuchsia-700",children:[e.jsx(Ws,{className:"h-2.5 w-2.5 shrink-0"})," ",F?"Music replaces A-roll audio":"+ Music bed"]})]}),p&&!S&&e.jsx("div",{className:"pointer-events-none absolute top-0 bottom-0 z-30 w-[2px] bg-cyan-400 shadow-[0_0_10px_2px_rgba(34,211,238,0.85)]",style:{left:`${Oe}%`},children:e.jsx("div",{className:"absolute left-1/2 -translate-x-1/2",style:{top:0,width:0,height:0,borderLeft:"10px solid transparent",borderRight:"10px solid transparent",borderTop:"16px solid rgb(34 211 238)",filter:"drop-shadow(0 0 5px rgba(34,211,238,0.95))"}})})]})}),e.jsx("div",{className:"mt-1 h-4 text-[11px] leading-4 text-muted-foreground",children:tt?e.jsxs("span",{children:[e.jsxs("span",{className:"font-semibold text-foreground",children:["Clip ",(H??0)+1]}),ut?e.jsxs(e.Fragment,{children:[" â ",ut]}):e.jsxs(e.Fragment,{children:[" â placed at ",$r(tt.start_sec)]})]}):e.jsx("span",{className:"opacity-60",children:"Hover a clip to see why it's there."})})]})}const kd="https://eojzlnapvjzhdsizwlmo.supabase.co",zo=s=>`${kd}/storage/v1/object/public/narrative/style-thumbnails/${s}.jpg`,Ks={original:"none",light:"saturate(1.15) contrast(1.08) brightness(1.05)",cinematic:"contrast(1.12) saturate(1.42) brightness(1.05)"},Es={original:{id:"original",label:"Original",filter:Ks.original,overlay:"none"},light:{id:"light",label:"Light grade",filter:Ks.light,badge:"free",overlay:"none"},cinematic:{id:"cinematic",label:"Cinematic grade",filter:Ks.cinematic,badge:"paid",sub:"40 credits",overlay:"none",cinematic:!0},basicCap:{id:"basicCap",label:"Basic",filter:Ks.light,overlay:"basicCap"},premiumCap:{id:"premiumCap",label:"Premium",filter:Ks.light,badge:"premium",overlay:"premiumCap"},behind:{id:"behind",label:"Text behind subject",filter:Ks.light,badge:"premium",overlay:"behind"},motion:{id:"motion",label:"Motion graphics",filter:Ks.light,badge:"premium",overlay:"motion"}},Bo={top:"top-[12%]",middle:"top-1/2 -translate-y-1/2",bottom:"bottom-[
1714%]"},Wo=["Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif","'Arial Black', 'Arial Bold', Gadget, sans-serif","'Trebuchet MS', 'Segoe UI', sans-serif","Georgia, 'Times New Roman', serif"],Sd=["TECH","STARTUP","SPACE"],Md=[{t:"THE",s:.82},{t:"DIFFERENT",s:1.3},{t:"SERVICES",s:1.02}],Cd="#FF9E1C";function na({premium:s,big:i,staticText:c}){const u=c?c.split(" ").map(q=>({t:q,s:1})):s?Md:Sd.map(q=>({t:q,s:1})),p=u.length,[m,v]=n.useState(0),[_,O]=n.useState(0);n.useEffect(()=>{if(!s||c)return;const q=setInterval(()=>v(E=>(E+1)%p),560),F=setInterval(()=>O(E=>(E+1)%Wo.length),1800);return()=>{clearInterval(q),clearInterval(F)}},[s,p,c]);const Q=i?"text-3xl":"text-[11px]";return e.jsx("span",{className:`flex flex-wrap items-center justify-center gap-x-1.5 gap-y-0.5 px-2 text-center font-black uppercase leading-tight ${Q}`,style:{fontFamily:s&&!c?Wo[_]:void 0,fontWeight:900},children:u.map((q,F)=>{const E=s&&!c&&F===m;return e.jsx("span",{style:{display:"inline-block",transform:`scale(${q.s*(E?1.14:1)})`,transformOrigin:"center",transition:"transform .16s ease, color .16s ease",color:E?Cd:"#fff",WebkitTextStroke:`${i?2.5:1.2}px #000`,paintOrder:"stroke fill",textShadow:"0 2px 8px rgba(0,0,0,0.95)",animation:s||c?void 0:`sr-cap-pop 2s ${(F*2/p).toFixed(2)}s infinite`},children:q.t},F)})})}function pi({effect:s,arollUrl:i,captionPos:c,big:u}){return e.jsxs("div",{className:"relative h-full w-full overflow-hidden rounded-lg bg-black",children:[i?e.jsx("video",{src:`${i}#t=0.1`,muted:!0,playsInline:!0,preload:"metadata",tabIndex:-1,className:"absolute inset-0 h-full w-full object-cover",style:{filter:s.filter}}):e.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(135deg,#2b2b36,#3a2a26)",filter:s.filter}}),s.cinematic&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"pointer-events-none absolute inset-0",style:{background:"radial-gradient(circle at 14% 24%, rgba(30,110,255,0.6) 0%, rgba(30,110,255,0) 42%)",mixBlendMode:"screen"}}),e.jsx("div",{className:"pointer-events-none absolute inset-0",style:{background:"radial-gradient(circle at 86% 24%, rgba(255,115,20,0.6) 0%, rgba(255,115,20,0) 42%)",mixBlendMode:"screen"}}),e.jsx("div",{className:"pointer-events-none absolute inset-0",style:{background:"radial-gradient(ellipse 50% 46% at 50% 60%, rgba(255,240,220,0.14) 0%, rgba(0,0,0,0) 55%)",mixBlendMode:"soft-light"}})]}),s.overlay==="basicCap"&&e.jsx("div",{className:`absolute inset-x-0 ${Bo[c]}`,children:e.jsx(na,{big:u})}),s.overlay==="premiumCap"&&e.jsx("div",{className:`absolute inset-x-0 ${Bo[c]}`,children:e.jsx(na,{premium:!0,big:u})}),s.overlay==="behind"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute inset-x-0 top-[46%] z-0 -translate-y-1/2",children:e.jsx(na,{staticText:"BEHIND YOU",big:u})}),i&&e.jsx("video",{src:`${i}#t=0.1`,muted:!0,playsInline:!0,preload:"metadata",tabIndex:-1,className:"absolute inset-0 z-10 h-full w-full object-cover",style:{filter:s.filter,clipPath:"ellipse(40% 52% at 50% 58%)"}}),e.jsx("span",{className:"absolute bottom-1 left-0 right-0 z-20 text-center text-[7px] font-semibold text-white/70",children:"matte-accurate on render"})]}),s.overlay==="motion"&&e.jsxs("div",{className:`absolute left-2 top-2 rounded-lg border border-white/25 bg-white/15 px-2 py-1 backdrop-blur-md ${u?"scale-150 origin-top-left":""}`,style:{animation:"sr-mg 2.6s ease-in-out infinite"},children:[e.jsx("div",{className:`${u?"text-3xl":"text-sm"} font-black leading-none text-white`,children:"+312%"}),e.jsx("div",{className:"text-[7px] uppercase tracking-wide text-white/70",children:"engagement"})]})]})}function nn({effect:s,arollUrl:i,captionPos:c,selected:u,onToggle:p,onEnlarge:m}){return e.jsxs("div",{className:"flex w-[86px] shrink-0 flex-col gap-1",children:[e.jsxs("button",{onClick:p,title:"Click to select / deselect · ⤢ to enlarge",className:`group relative aspect-[9/16] w-full overflow-hidden rounded-lg ring-1 transition-all hover:brightness-[1.06] ${u?"ring-2 ring-cyan-400":"ring-black/10 hover:ring-2 hover:ring-cyan-300/70"}`,children:[e.jsx(pi,{effect:s,arollUrl:i,captionPos:c}),e.jsx("span",{className:"pointer-events-none absolute inset-0 bg-cyan-200/0 transition-colors group-hover:bg-cyan-200/10"}),s.badge&&e.jsx("span",{className:`absolute left-1 top-1 z-20 rounded px-1 text-[8px] font-black ${s.badge==="free"?"bg-emerald-400/90 text-black":"bg-amber-400/90 text-black"}`,children:s.badge}),u&&e.jsx("span",{className:"absolute right-1 top-1 z-20 flex h-4 w-4 items-center justify-center rounded-full bg-cyan-400 text-white shadow",children:e.jsx(xa,{
17className:"h-2.5 w-2.5"})}),e.jsx("span",{role:"button",onClick:v=>{v.stopPropagation(),m()},title:"Enlarge",className:"absolute bottom-1 right-1 z-20 flex items-center justify-center rounded-md bg-black/60 p-1 text-white/90 ring-1 ring-white/25 transition-colors hover:bg-black/85 group-hover:ring-white/50",children:e.jsx(wr,{className:"h-3 w-3"})})]}),e.jsx("span",{className:`truncate text-[10px] font-bold ${u?"text-cyan-700":"text-[#26241f]"}`,children:s.label}),s.sub&&e.jsx("span",{className:"text-[9px] text-black/40",children:s.sub})]})}function Ed({arollUrl:s,styleKey:i,onStyleChange:c,onRegenerateAll:u,bridgeAvailable:p=!1}){const[m,v]=n.useState(!1),[_,O]=n.useState("middle"),[Q,q]=n.useState(null),[F,E]=n.useState(null),[w,H]=n.useState("original"),[B,K]=n.useState("basic"),[h,V]=n.useState(!1),[ee,se]=n.useState(!1),W=S=>e.jsx("p",{className:"mb-1.5 text-[10px] font-black uppercase tracking-widest text-black/45",children:S});return e.jsxs("div",{className:"mx-auto mt-4 w-full max-w-3xl rounded-xl border border-black/10 bg-white/60",children:[e.jsx("style",{children:"@keyframes sr-cap-pop{0%,100%{transform:scale(.84);opacity:.45}12%{transform:scale(1.18);opacity:1}32%{transform:scale(1);opacity:1}72%{transform:scale(1);opacity:1}}@keyframes sr-mg{0%{transform:translateY(7px) scale(.86);opacity:0}18%{transform:translateY(0) scale(1);opacity:1}80%{transform:translateY(-2px) scale(1.02);opacity:1}100%{transform:translateY(-5px) scale(1);opacity:.85}}"}),e.jsxs("button",{onClick:()=>v(S=>!S),className:"flex w-full items-center gap-2 px-3 py-2.5 text-left",children:[m?e.jsx(Ir,{className:"h-4 w-4 text-black/40"}):e.jsx(fa,{className:"h-4 w-4 text-black/40"}),e.jsx(as,{className:"h-4 w-4 text-violet-500"}),e.jsx("span",{className:"text-[13px] font-black text-[#26241f]",children:"Editing Features"}),e.jsx("span",{className:"text-[11px] text-black/40",children:"· captions, effects, cinematic themes"})]}),m&&e.jsxs("div",{className:"flex flex-col gap-4 border-t border-black/[0.06] px-3 py-3",children:[e.jsx("p",{className:"text-[10px] font-bold text-black/35",children:"Click a tile to select · ⤢ to enlarge · previewed on your first frame · selections apply on Re-render."}),e.jsxs("div",{children:[W("Lighting"),e.jsx("div",{className:"flex gap-3 overflow-x-auto thin-scroll pb-1",children:[["original",Es.original],["light",Es.light],["cinematic",Es.cinematic]].map(([S,A])=>e.jsx(nn,{effect:A,arollUrl:s,captionPos:_,selected:w===S,onToggle:()=>H(S),onEnlarge:()=>q(A)},A.id))}),e.jsxs("p",{className:"mt-1 text-[9.5px] text-black/35",children:["Cinematic is a ",e.jsx("span",{className:"font-semibold",children:"generative studio relight"})," â the directional blueâorange back-light applies on Re-render (Studio-only)."]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1.5 flex flex-wrap items-center justify-between gap-2",children:[W("Captions"),e.jsxs("div",{className:"flex items-center gap-1 text-[10px]",children:[e.jsx("span",{className:"font-bold text-black/40",children:"Placement:"}),e.jsx("div",{className:"inline-flex overflow-hidden rounded-md border border-black/15",children:["top","middle","bottom"].map(S=>e.jsx("button",{onClick:()=>O(S),className:`px-1.5 py-0.5 font-bold capitalize transition-colors ${_===S?"bg-cyan-500 text-white":"text-black/50 hover:bg-black/5"}`,children:S},S))})]})]}),e.jsx("div",{className:"flex gap-3 overflow-x-auto thin-scroll pb-1",children:[["basic",Es.basicCap],["premium",Es.premiumCap]].map(([S,A])=>e.jsx(nn,{effect:A,arollUrl:s,captionPos:_,selected:B===S,onToggle:()=>K(k=>k===S?"none":S),onEnlarge:()=>q(A)},A.id))})]}),e.jsxs("div",{className:"flex flex-wrap gap-6",children:[e.jsxs("div",{children:[W("Text behind subject"),e.jsx(nn,{effect:Es.behind,arollUrl:s,captionPos:_,selected:h,onToggle:()=>V(S=>!S),onEnlarge:()=>q(Es.behind)})]}),e.jsxs("div",{children:[W("Motion graphics"),e.jsx(nn,{effect:Es.motion,arollUrl:s,captionPos:_,selected:ee,onToggle:()=>se(S=>!S),onEnlarge:()=>q(Es.motion)})]})]}),e.jsxs("div",{children:[W("Cinematic B-roll theme"),e.jsx("div",{className:"flex gap-3 overflow-x-auto thin-scroll pb-1",children:ei.map(S=>{const A=S.key===i;return e.jsxs("div",{className:"flex w-[120px] shrink-0 flex-col gap-1",children:[e.jsxs("button",{onClick:()=>c(S.key),title:S.description,className:`relative aspect-[9/16] w-full overflow-hidden rounded-lg bg-black/5 ring-1 transition-all ${A?"ring-2 ring-cyan-400":"ring-black/10 hover:ring-black/25"}`,children:[e.jsx("img",{src:zo(S.key),alt:S.label,loading:"lazy",className:"absolute inset-0 h-full w-full object-cover",onError:k=>{k.currentTarget.style.display="none"}}),A&&e.jsx("span",{className:"absolute right-1.5 top-1.5 z-20 flex h-5 w-5 items-center justify-center rounded-full bg-cyan-400 text-white shadow",children:e.jsx(xa,{
17className:"h-3 w-3"})}),e.jsx("span",{role:"button",onClick:k=>{k.stopPropagation(),E({url:zo(S.key),label:S.label})},title:"Enlarge",className:"absolute bottom-1 right-1 z-20 flex items-center justify-center rounded-md bg-black/60 p-1 text-white/90 ring-1 ring-white/25 hover:bg-black/85",children:e.jsx(wr,{className:"h-3 w-3"})})]}),e.jsx("span",{className:`text-[11px] font-black ${A?"text-cyan-700":"text-[#26241f]"}`,children:S.label}),e.jsx("span",{className:"line-clamp-2 text-[9px] leading-tight text-black/40",children:S.description}),A&&u&&e.jsxs("button",{onClick:()=>u(S.key),className:"flex items-center justify-center gap-1 rounded-md border border-cyan-400/40 bg-cyan-500/10 py-1 text-[9px] font-bold text-cyan-700 hover:bg-cyan-500/20",children:[e.jsx(cn,{className:"h-2.5 w-2.5"})," Regenerate B-roll"]})]},S.key)})}),e.jsxs("p",{className:"mt-1 text-[9.5px] text-black/35",children:["Selecting a theme applies on your next render. Regenerate all now, or restyle single scenes from the ",e.jsx("span",{className:"font-semibold",children:"Storyboard"})," tab."]})]}),e.jsxs("div",{children:[W("Render on your machine"),p?e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-semibold text-emerald-600",children:[e.jsx("span",{children:"â¡"})," Connector running â renders locally, free & faster"]}):e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[11px] text-black/50",children:"Free & faster, no cloud queue:"}),e.jsxs("a",{href:Jr?ia:go,download:!0,className:"flex items-center gap-1.5 rounded-lg border border-cyan-400/40 bg-cyan-500/10 px-2.5 py-1 text-[11px] font-bold text-cyan-700 hover:bg-cyan-500/20",children:[e.jsx(aa,{className:"h-3.5 w-3.5"})," ",Jr?"Download for macOS":"Download for Windows"]}),e.jsxs("a",{href:Jr?go:ia,download:!0,className:"text-[10.5px] font-semibold text-black/45 hover:text-black/70",children:[Jr?"Windows":"macOS"," â"]})]})]})]}),Q&&e.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/80 p-6",onClick:()=>q(null),children:e.jsxs("div",{className:"flex flex-col items-center gap-2",onClick:S=>S.stopPropagation(),children:[e.jsx("div",{className:"overflow-hidden rounded-xl shadow-2xl",style:{height:"min(80vh, 720px)",aspectRatio:"9 / 16"},children:e.jsx(pi,{effect:Q,arollUrl:s,captionPos:_,big:!0})}),e.jsxs("div",{className:"flex items-center gap-3 text-white",children:[e.jsxs("span",{className:"text-sm font-bold",children:[Q.label,Q.sub?` · ${Q.sub}`:""]}),(Q.overlay==="basicCap"||Q.overlay==="premiumCap")&&e.jsx("div",{className:"inline-flex overflow-hidden rounded-md border border-white/25 text-[11px]",children:["top","middle","bottom"].map(S=>e.jsx("button",{onClick:()=>O(S),className:`px-2 py-0.5 font-bold capitalize ${_===S?"bg-white text-black":"text-white/70 hover:bg-white/10"}`,children:S},S))}),e.jsx("button",{onClick:()=>q(null),className:"rounded-md bg-white/10 px-2 py-0.5 text-[12px] font-bold hover:bg-white/20",children:"Close"})]})]})}),F&&e.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/80 p-6",onClick:()=>E(null),children:e.jsxs("div",{className:"flex flex-col items-center gap-2",onClick:S=>S.stopPropagation(),children:[e.jsx("img",{src:F.url,alt:F.label,className:"rounded-xl shadow-2xl",style:{height:"min(80vh, 720px)",aspectRatio:"9 / 16",objectFit:"cover"}}),e.jsxs("div",{className:"flex items-center gap-3 text-white",children:[e.jsx("span",{className:"text-sm font-bold",children:F.label}),e.jsx("button",{onClick:()=>E(null),className:"rounded-md bg-white/10 px-2 py-0.5 text-[12px] font-bold hover:bg-white/20",children:"Close"})]})]})})]})}const Rd=s=>{const i=Math.max(0,Math.round(s/1e3));return`${Math.floor(i/60)}:${String(i%60).padStart(2,"0")}`};function $d({jobId:s,status:i,pipelineStage:c,onRerenderStarted:u,onClose:p}){const{toast:m}=pa(),[v,_]=n.useState(null),[O,Q]=n.useState(null),[q,F]=n.useState(new Set),[E,w]=n.useState(null),[H,B]=n.useState(""),[K,h]=n.useState(null),[V,ee]=n.useState(null),[se,W]=n.useState(null),[S,A]=n.useState(null),[k,xe]=n.useState(!1),[Le,qe]=n.useState(!1);n.useEffect(()=>{let L=!0;return _(null),Q(null),mr(s).then(pe=>{L&&_((pe.scenes||[]).slice().sort((we,Ge)=>(we.timestamp_ms??0)-(Ge.timestamp_ms??0)))}).catch(pe=>{L&&Q((pe==null?void 0:pe.message)||"Couldn't load the storyboard")}),()=>{L=!1}},[s]);const fe=i==="complete",Ae=i==="failed",R=c==="generating_clips",$=(v==null?void 0:v.length)??0,te=n.useMemo(()=>(v??[]).filter(L=>R?L.clip_url:L.image_url).length,[v,R]),ue=$>0&&q.size>=$,st=fe||Ae||ue,be=L=>F(pe=>{const we=new Set(pe);return we.has(L)?we.delete(L):we.add(L),we}),Ce=()=>F(new Set((v??[]).map(L=>L.beat_index))),he=async L=>{h(L.beat_index),w(null);try{const{scene:pe}=await Jo(s,L.beat_index,H||void 0);_(we=>(we??[]).map(Ge=>Ge.id===L.id?pe:Ge)),F(we=>{const Ge=new Set(we);return Ge.delete(L.beat_index),Ge}),B("")}catch(pe){m({title:"Regeneration failed",description:pe==null?void 0:pe.message,variant:"destructive"})}finally{h(null)}},Qe=async L=>{const pe=v??[],we=pe.findIndex(at=>at.id===L.id),Ge=we>=0?pe[we+1]:void 0,et=L.timestamp_ms??0,dt=(Ge==null?void 0:Ge.timestamp_ms)??et+(L.duration_ms??3e3)+3e3,Xe=Math.round((et+dt)/2);W(L.beat_index);try{const{scene:at}=await Tl(s,{phrase:(Ge==null?void 0:Ge.beat_transcript)||L.beat_transcript||L.description||"",timestamp_ms:Xe,duration_ms:Math.max(1500,Math.round((dt-et)/2))});_(Ye=>[...Ye??[],at].sort((gt,Ke)=>(gt.timestamp_ms??0)-(Ke.timestamp_ms??0))),m({title:"B-roll inserted",description:"New scene added â Refine it, then re-render."})}catch(at){m({title:"Insert failed",description:(at==null?void 0:at.message)||"Unknown error",variant:"destructive"})}finally{W(null)}},Oe=async()=>
17{if(!Le){qe(!0);try{await Rl(s),m({title:"Animating B-rollâ¦",description:"Generating video clips from each image, then re-rendering."}),u==null||u()}catch(L){m({title:"Couldn't animate",description:L==null?void 0:L.message,variant:"destructive"})}finally{qe(!1)}}},Ee=async()=>{if(!(k||!st)){xe(!0);try{await $l(s),m({title:"Renderingâ¦",description:"Building your reel from the approved storyboard."}),u==null||u()}catch(L){m({title:"Couldn't start render",description:L==null?void 0:L.message,variant:"destructive"})}finally{xe(!1)}}};return e.jsxs("div",{className:"flex flex-col gap-3 pr-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(as,{className:"w-4 h-4 text-fuchsia-300 shrink-0"}),e.jsx("h2",{className:"text-sm font-bold text-white truncate",children:"Storyboard"}),$>0&&(q.size<$?e.jsxs("span",{className:"text-[10px] text-amber-300/80 font-bold shrink-0",children:[q.size,"/",$," approved"]}):e.jsx("span",{className:"text-[10px] text-green-300/80 font-bold shrink-0",children:"â All approved"}))]}),p&&e.jsx("button",{onClick:p,className:"p-1 rounded-md text-white/45 hover:text-white hover:bg-white/10 shrink-0",title:"Close",children:e.jsx(os,{className:"w-4 h-4"})})]}),e.jsxs("p",{className:"text-[10px] text-white/40 leading-snug",children:["AI-generated B-roll, one scene per story beat. Approve the ones you like, ",e.jsx("span",{className:"text-cyan-300 font-semibold",children:"Refine"})," any image with a prompt, or ",e.jsx("span",{className:"text-cyan-300 font-semibold",children:"Insert"})," more â then re-render."]}),$>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-[10px] font-black text-white/30 uppercase tracking-widest",children:R?"Animating clips":"Scenes"}),e.jsxs("span",{className:"text-[10px] text-violet-300/60 font-bold",children:[te,"/",$," ",R?"animated":"generated"]})]}),e.jsx("div",{className:"h-0.5 bg-white/10 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-violet-400 rounded-full transition-all duration-700",style:{width:`${Math.round(te/Math.max(1,$)*100)}%`}})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("button",{onClick:Ce,className:"px-2.5 py-1 rounded-lg bg-white/10 hover:bg-white/15 text-white/60 hover:text-white text-[10px] font-bold transition-colors",children:"â Approve all"}),(v??[]).some(L=>L.image_url)&&e.jsxs("button",{onClick:Oe,disabled:Le,className:"flex items-center gap-1.5 px-3 py-1 rounded-lg bg-gradient-to-r from-fuchsia-600 to-violet-600 hover:from-fuchsia-500 hover:to-violet-500 disabled:opacity-40 disabled:cursor-not-allowed text-white text-[10px] font-bold transition-all",children:[Le?e.jsx(Je,{className:"w-3 h-3 animate-spin"}):e.jsx(as,{className:"w-3 h-3"}),Le?"Startingâ¦":"Animate B-roll to Video"]}),e.jsxs("button",{onClick:Ee,disabled:k||!st,className:"flex items-center gap-1.5 px-3 py-1 rounded-lg bg-gradient-to-r from-orange-400 to-yellow-400 hover:brightness-105 disabled:opacity-40 disabled:cursor-not-allowed text-black text-[10px] font-black transition-all",children:[k?e.jsx(Je,{className:"w-3 h-3 animate-spin"}):e.jsx(Ar,{className:"w-3 h-3"}),k?"Startingâ¦":fe?"Re-render":Ae?"Retry render":"Approve & render"]})]})]}),O?e.jsx("p",{className:"text-[11px] text-red-400/80 py-4",children:O}):v===null?e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-white/45 py-6",children:[e.jsx(Je,{className:"w-3.5 h-3.5 animate-spin text-cyan-400"})," Loading storyboardâ¦"]}):v.length===0?e.jsx("p",{className:"text-[11px] text-white/30 py-6",children:"No AI storyboard for this project â it uses your own B-roll library."}):e.jsx("div",{className:"flex flex-col gap-2",children:v.map((L,pe)=>{const we=q.has(L.beat_index),Ge=E===L.beat_index,et=K===L.beat_index,dt=V===L.beat_index;return e.jsxs("div",{className:`flex gap-2.5 rounded-xl border p-2.5 transition-all ${we?"border-green-500/40 bg-green-500/[0.04]":"border-white/10 bg-black/20"}`,children:[e.jsxs("button",{onClick:()=>L.image_url&&A(L.image_url),className:"relative w-[64px] shrink-0 group",title:"Click to enlarge",children:[et&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/70 rounded-lg",children:e.jsx(Je,{className:"w-4 h-4 animate-spin text-cyan-400"})}),L.image_url?e.jsx("img",{src:L.image_url,alt:"",className:"w-[64px] aspect-[9/16] rounded-lg object-cover border border-white/15 group-hover:border-cyan-400/60 transition-colors"}):e.jsx("div",{className:"w-[64px] aspect-[9/16] rounded-lg flex items-center justify-center bg-white/[0.02] border border-white/10",children:e.jsx(Je,{className:"w-3.5 h-3.5 text-white/20 animate-spin"})}),L.clip_url&&e.jsx("span",{className:"absolute bottom-1 right-1 rounded px-1 py-0.5 bg-green-500/85",title:"Animated to video",children:e.jsx(qt,{className:"w-2.5 h-2.5 text-white"})})]}),e.jsxs("div",{className:"flex-1 flex flex-col gap-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-cyan-500/20 border border-cyan-500/30 text-[10px] font-black text-cyan-200 tabular-nums",children:Rd(L.timestamp_ms??0)}),e.jsxs("span",{className:"text-[9px] text-white/30 font-bold",children:["#",pe+1]}),we&&e.jsx("span",{className:"text-[9px] text-green-300/80 font-bold ml-auto",children:"â"})]}),(L.beat_transcript||L.description)&&e.jsx("p",{className:"text-[11px] text-white/80 leading-snug line-clamp-2",children:L.beat_transcript||L.description}),e.jsxs("button",{onClick:()=>ee(dt?null:L.beat_index),className:"flex items-center gap-1 text-[9px] text-white/35 hover:text-white/60 transition-colors self-start",children:[dt?e.jsx(Ir,{className:"w-2.5 h-2.5"}):e.jsx(fa,{className:"w-2.5 h-2.5"})," Image prompt"]}),dt&&e.jsx("p",{className:"text-[9px] text-white/40 leading-snug bg-black/30 rounded px-2 py-1 border border-white/5",children:L.image_prompt||"â"}),e.jsxs("div",{className:"flex flex-wrap gap-1 mt-0.5",children:[e.jsx("button",{onClick:()=>be(L.beat_index),className:`flex-1 min-w-[64px] py-1 rounded-lg text-[9px] font-bold border transition-colors ${we?"bg-green-500/15 border-green-500/40 text-green-300 hover:bg-red-500/10 hover:text-red-300":"bg-white/5 border-white/15 text-white/45 hover:bg-green-500/10 hover:text-green-300"}`,children:we?"â Approved":"Approve"}),e.jsx("button",{onClick:()=>{w(Ge?null:L.beat_index),B("")},className:"px-2 py-1 rounded-lg bg-white/5 border border-white/15 text-[9px] text-white/45 hover:text-white hover:bg-white/10 transition-colors",children:"âï¸ Refine"}),e.jsx("button",{onClick:()=>Qe(L),disabled:se===L.beat_index,className:"px-2 py-1 rounded-lg bg-cyan-500/10 border border-dashed border-cyan-500/40 text-[9px] text-cyan-300 hover:bg-cyan-500/20 disabled:opacity-40 transition-colors",children:se===L.beat_index?e.jsx(Je,{className:"w-2.5 h-2.5 animate-spin inline"}):"+ Insert after"})]}),Ge&&e.jsxs("div",{className:"flex flex-col gap-1 mt-0.5",children:[e.jsx("textarea",{value:H,onChange:Xe=>B(Xe.target.value),rows:2,placeholder:"Describe what to change about this imageâ¦",className:"w-full rounded-lg bg-black/50 border border-white/20 px-2 py-1 text-[10px] text-white placeholder:text-white/20 outline-none resize-none focus:border-cyan-500/50"}),e.jsxs("button",{onClick:()=>he(L),className:"flex items-center justify-center gap-1 py-1 rounded-lg bg-cyan-500/15 border border-cyan-500/35 text-[10px] font-bold text-cyan-300 hover:bg-cyan-500/25 transition-colors",children:[e.jsx(Ar,{className:"w-2.5 h-2.5"})," Regenerate this image"]})]})]})]},L.id)})}),S&&e.jsxs("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/80 p-6",onClick:()=>A(null),children:[e.jsx("img",{src:S,alt:"",className:"max-h-[90vh] max-w-[90vw] rounded-xl object-contain",onClick:L=>L.stopPropagation()}),e.jsx("button",{onClick:()=>A(null),className:"absolute top-4 right-4 p-2 rounded-lg bg-white/10 text-white/80 hover:bg-white/20",children:e.jsx(os,{className:"w-5 h-5"})})]})]})}const Td="application/x-viralspin-broll",Ho=(s,i)=>{try{s.dataTransfer.setData(Td,JSON.stringify({url:i,kind:"video"})),s.dataTransfer.effectAllowed="copy"}catch{}},Fd=[{title:"You Raise Me Up",artist:"Josh Groban"},{title:"The Prayer",artist:"Celine Dion"},{title:"Time to Say Goodbye",artist:"Andrea Bocelli"},{title:"Hallelujah",artist:"Leonard Cohen"},{title:"What a Wonderful World",artist:"Louis Armstrong"},{title:"Amazing Grace",artist:""}],qo=["queued","processing","review_ready"],ys=s=>`${Math.floor(s/60)}:${String(Math.floor(s%60)).padStart(2,"0")}`;function Vo(s){const i=(s||[]).filter(u=>u&&Number.isFinite(Number(u.start))&&Number.isFinite(Number(u.end))&&Number(u.end)>Number(u.start)).map(u=>({start:+Number(u.start).toFixed(2),end:+Number(u.end).toFixed(2)})).sort((u,p)=>u.start-p.start),c=[];for(const u of i){const p=c[c.length-1];p&&u.start<=p.end+.001?p.end=Math.max(p.end,u.end):c.push({...u})}return c}function Go({estimate:s=45}){const[i,c]=n.useState(0);n.useEffect(()=>{const m=Date.now(),v=setInterval(()=>c((Date.now()-m)/1e3),500);return()=>clearInterval(v)},[]);const u=Math.min(95,i/s*95),p=Math.max(0,Math.ceil(s-i));return e.jsxs("div",{className:"w-full max-w-xs flex flex-col gap-1.5",children:[e.jsx("div",{className:"h-1.5 w-full rounded-full bg-white/10 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-violet-400 transition-[width] duration-500 ease-out",style:{width:`${Math.max(4,u)}%`}})}),e.jsx("p",{className:"text-white/35 text-[11px] text-center",children:p>0?`about ${p}s remaining`:"almost readyâ¦"})]})}function Ru(){var io,lo,co;const{jobId:s=""}=Nl(),[i]=_l(),c=i.get("render"),u=i.get("n"),[p,m]=n.useState(!c),[v,_]=n.useState(null),[O,Q]=n.useState(null),[q,F]=n.useState(!1),E=n.useRef(!1);n.useEffect(()=>{!c||E.current||(E.current=!0,Fl(c).then(t=>{t!=null&&t.timeline&&(_(t.timeline),Q(t.created_at)),m(!0)}).catch(()=>m(!0)))},[c]);const{toast:w}=pa(),H=kl(),B=n.useRef(null),K=n.useRef(null),[h,V]=n.useState(null),[ee,se]=n.useState(null),W=n.useRef(!1),[S,A]=n.useState(null),k=n.useRef(null),xe=n.useRef(null),[Le,qe]=n.useState([]),[fe,Ae]=n.useState(!1),[R,$]=n.useState(null),[te,ue]=n.useState(null),st=n.useRef(null),[be,Ce]=n.useState(!1),[he,Qe]=n.useState(!1),[Oe,Ee]=n.useState(null),[L,pe]=n.useState(0),[we,Ge]=n.useState(()=>{try{return Number(localStorage.getItem("swaprefine:lastRenderMs"))||0}catch{return 0}}),[et,dt]=n.useState([]),Xe=n.useRef(new Set),at=100,[Ye,gt]=n.useState(()=>{try{const t=localStorage.getItem(`swaprefine:finals:${s}`),r=t?JSON.parse(t):[];return Array.isArray(r)?r:[]}catch{return[]}}),[Ke,tt]=n.useState(()=>{try{const t=localStorage.getItem(`swaprefine:finals:${s}`),r=t?JSON.parse(t):[];return Array.isArray(r)&&r.length?r.length-1:0}catch{return 0}});n.useEffect(()=>{try{localStorage.setItem(`swaprefine:finals:${s}`,JSON.stringify(Ye.slice(-at)))}catch{}},[Ye,s]);const ut=n.useRef(Ye);n.useEffect(()=>{ut.current=Ye},[Ye]);const[ht,Ve]=n.useState({}),D=t=>{t&>(r=>{const a=[...r.filter(l=>l!==t),t].slice(-at);return tt(a.length-1),a})},z=()=>{s&&Pl(s).then(t=>{if(!t.length)return;const r=t.map(l=>
17l.download_url||l.preview_url).filter(Boolean).reverse();if(!r.length)return;const a={};for(const l of t){const N={createdAt:l.created_at,renderId:l.render_id};l.download_url&&(a[l.download_url]=N),l.preview_url&&(a[l.preview_url]=N)}Ve(a),gt(l=>{const N=[...r];for(const M of l)N.includes(M)||N.push(M);const f=N.slice(-at);return tt(f.length-1),f})}).catch(()=>{})};n.useEffect(()=>{z()},[s]);const ye=n.useRef(!1);n.useEffect(()=>{if(ye.current&&!be){const t=setTimeout(z,1500);return ye.current=be,()=>clearTimeout(t)}ye.current=be},[be]);const je=Ye[Ke]??null,[Z,ke]=n.useState(0),Ie=15,Ue=6,[ot,jt]=n.useState(!1),[lt,vt]=n.useState(!1),[xt,Nt]=n.useState(""),[bt,Mt]=n.useState(""),[wt,yt]=n.useState(""),[x,P]=n.useState(!0),[ie,G]=n.useState(()=>{const t=Number(typeof localStorage<"u"&&localStorage.getItem("swaprefine:panelW"));return Number.isFinite(t)&&t>=300?Math.min(t,760):360}),oe=n.useRef(ie);n.useEffect(()=>{oe.current=ie},[ie]);const Pe=t=>{t.preventDefault();const r=l=>G(Math.max(300,Math.min(760,window.innerWidth-l.clientX))),a=()=>{window.removeEventListener("pointermove",r),window.removeEventListener("pointerup",a);try{localStorage.setItem("swaprefine:panelW",String(Math.round(oe.current)))}catch{}};window.addEventListener("pointermove",r),window.addEventListener("pointerup",a)},[$e,Te]=n.useState(()=>typeof window<"u"&&window.matchMedia("(max-width: 767px)").matches);n.useEffect(()=>{if(typeof window>"u")return;const t=window.matchMedia("(max-width: 767px)"),r=()=>Te(t.matches);return t.addEventListener("change",r),()=>t.removeEventListener("change",r)},[]);const[ae,it]=n.useState("preview"),Lt=n.useRef(null),[St,Vt]=n.useState(()=>{const t=Number(typeof localStorage<"u"&&localStorage.getItem("swaprefine:leftW"));return Number.isFinite(t)&&t>=360?Math.min(t,1e3):560}),kt=n.useRef(St);n.useEffect(()=>{kt.current=St},[St]);const Wt=t=>{var N;t.preventDefault();const r=((N=Lt.current)==null?void 0:N.getBoundingClientRect().left)??0,a=f=>Vt(Math.max(360,Math.min(1e3,f.clientX-r))),l=()=>{window.removeEventListener("pointermove",a),window.removeEventListener("pointerup",l);try{localStorage.setItem("swaprefine:leftW",String(Math.round(kt.current)))}catch{}};window.addEventListener("pointermove",a),window.addEventListener("pointerup",l)},[is,Dt]=n.useState(!1),[Ts,Ft]=n.useState(()=>{try{return localStorage.getItem("swaprefine:libOpen")!=="0"}catch{return!0}});n.useEffect(()=>{try{localStorage.setItem("swaprefine:libOpen",Ts?"1":"0")}catch{}},[Ts]);const[Fs,Gt]=n.useState(!1),[At,ss]=n.useState(()=>{try{return localStorage.getItem(`swaprefine:sectionsLocked:${s}`)==="1"}catch{return!1}});n.useEffect(()=>{try{localStorage.setItem(`swaprefine:sectionsLocked:${s}`,At?"1":"")}catch{}},[At,s]);const $t=t=>(t??k.current??[]).reduce((r,a)=>Math.max(r,a.start_sec+(a.dur_sec||0)),0),ms=()=>At?Z:Math.max(Z,$t()),Yt=()=>At?Z:Math.max(Z,$t())+Ie,Jt=n.useMemo(()=>At?Z:Math.max(Z,$t(S)),[At,Z,S]),As=n.useRef(null),xs=n.useRef(null),[ls,Xt]=n.useState(!1),[Ot,Ct]=n.useState(!1),[Ht,Kt]=n.useState(!1),[pt,ks]=n.useState(null),[cs,Ys]=n.useState(!1),[rt,sr]=n.useState(()=>{try{return localStorage.getItem(`swaprefine:noAroll:${s}`)==="1"}catch{return!1}});n.useEffect(()=>{try{localStorage.setItem(`swaprefine:noAroll:${s}`,rt?"1":"")}catch{}},[rt,s]);const[ds,Is]=n.useState(0),[us,Ls]=n.useState(.5),[Pt,Ss]=n.useState(0),ps=n.useRef(new Set),[Ut,gs]=n.useState(new Set),Ds=n.useRef(!1);n.useEffect(()=>{if(Ds.current)try{localStorage.setItem(`swaprefine:magnetOn:${s}`,Ut.size>0?"1":"")}catch{}},[Ut,s]);const[d,y]=n.useState(0),[j,U]=n.useState(null),[I,le]=n.useState(yc),re=n.useRef(!1),[Re,ge]=n.useState([]),[Y,o]=n.useState(null),[b,g]=n.useState(!1),[J,X]=n.useState(!1),[ve,Be]=n.useState(null),[Se,We]=n.useState(null),[ft,Ps]=n.useState(null),[yr,fs]=n.useState(null),bs=n.useRef({fromSec:.2,posX:.5,posY:.47}),va=n.useRef(null),[jr,ya]=n.useState([]),Os=n.useRef([]),ja=n.useRef(!1),Lr=n.useRef(!1),rr=n.useRef(""),Na=n.useRef(0),_a=n.useRef(!1),Zt=n.useRef(!1),nr=n.useRef(null),ka=n.useRef(null),Dr=Yo(),{data:ce,isLoading:fi,error:hn,refetch:mi}=js({queryKey:["narrative-job",s],queryFn:()=>mo(s),enabled:!!s,retry:(t,r)=>{const a=r==null?void 0:r.status;return a===401||a===403?!1:t<8},retryDelay:t=>Math.min(4e3,700*(t+1)),refetchInterval:t=>{const r=t.state.data;return r?be||qo.includes(r==null?void 0:r.status)||r&&!r.timeline&&r.status!=="failed"&&r.status!=="complete"?3e3:!1:2500}
17,refetchIntervalInBackground:!0}),[gi,xn]=n.useState(!1);n.useEffect(()=>{if(ce){xn(!1);return}const t=setTimeout(()=>xn(!0),35e3);return()=>clearTimeout(t)},[ce,s]);const Sa=hn==null?void 0:hn.status,Ma=Sa===401||Sa===403,[pn,fn]=n.useState(()=>typeof window<"u"&&window.location.hash.includes("handoff=")?"exchanging":"idle");n.useEffect(()=>{pn==="exchanging"&&(async()=>{const r=new URLSearchParams(window.location.hash.slice(1)).get("handoff");if(window.history.replaceState(null,"",window.location.pathname+window.location.search),!r){fn("idle");return}const{error:a}=await Bs.auth.verifyOtp({token_hash:r,type:"magiclink"});if(a){fn("failed");return}fn("idle"),Dr.invalidateQueries({queryKey:["narrative-job",s]})})()},[pn]);const[bi,mn]=n.useState(!1),{data:gn}=js({queryKey:["my-credits"],queryFn:()=>jl(),staleTime:3e4});n.useEffect(()=>{if(!s)return;const t=Bs.channel(`narrative-job-${s}`).on("postgres_changes",{event:"*",schema:"public",table:"narrative_jobs",filter:`id=eq.${s}`},()=>{Dr.invalidateQueries({queryKey:["narrative-job",s]}),z()}).subscribe();return()=>{Bs.removeChannel(t)}},[s,Dr]),n.useEffect(()=>{var r;if(ja.current||!p)return;const t=v??(ce==null?void 0:ce.timeline);!(t!=null&&t.aroll_url)&&!((r=t==null?void 0:t.timeline)!=null&&r.length)||(V(t),va.current={transcript:Array.isArray(t.transcript)?t.transcript:[],words:Array.isArray(t.words)?t.words:[]},ja.current=!0)},[ce,p,v]),n.useEffect(()=>{ka.current=ce??null},[ce]),n.useEffect(()=>{if(!ce)return;const t=ce.preview_url;ce.status==="complete"&&t&&!Ye.includes(t)&&D(t)},[ce,Ye]),n.useEffect(()=>{!ce||be||(ce.status==="processing"||ce.status==="queued")&&(Zt.current=!0,Ce(!0),tt(Ye.length))},[ce,be,Ye.length]),n.useEffect(()=>{if(be||!s)return;let t=!1;const r=async()=>{try{const{data:l}=await Bs.from("narrative_renders").select("progress,status,created_at").eq("job_id",s).eq("status","rendering").order("created_at",{ascending:!1}).limit(1);if(t)return;const N=l==null?void 0:l[0];if(!N)return;const f=ka.current;if((f==null?void 0:f.status)==="complete"||nr.current!==null&&nr.current===(f==null?void 0:f.error_message))return;Ce(!0),Zt.current=!0,tt(ut.current.length);const M=new Date(N.created_at).getTime();Number.isFinite(M)&&Ee(M)}catch{}};r();const a=window.setInterval(r,1e4);return()=>{t=!0,window.clearInterval(a)}},[be,s]),n.useEffect(()=>{if(_a.current||!ce||!p)return;const t=v??ce.timeline,r=Array.isArray(t==null?void 0:t.pending_removed_ranges)?t.pending_removed_ranges:[];let a=Vo(r);if(!a.length)try{const l=localStorage.getItem(`swaprefine:removed:${s}`);l&&(a=Vo(JSON.parse(l)||[]))}catch{}Os.current=a,ya(a),_a.current=!0},[ce,s,p,v]),n.useEffect(()=>{const t=Number(h==null?void 0:h.total_duration_sec),r=Number.isFinite(t)&&t>0;r&&ke(f=>f>0?f:t);const a=ee||(h==null?void 0:h.aroll_url);if(!a)return;const l=document.createElement(ee?"audio":"video");l.preload="metadata",l.muted=!0,l.src=a;const N=()=>{!Number.isFinite(l.duration)||l.duration<=0||ke(r?Math.max(l.duration,t):l.duration)};return l.addEventListener("loadedmetadata",N),()=>l.removeEventListener("loadedmetadata",N)},[ee,h==null?void 0:h.aroll_url,h==null?void 0:h.total_duration_sec]);const Ca=n.useRef(!1);n.useEffect(()=>{const t=h==null?void 0:h.aroll_url;if(!t||Ca.current)return;const r=h==null?void 0:h.output_format,a=document.createElement("video");a.preload="metadata",a.muted=!0,a.src=t;const l=()=>{const N=a.videoWidth,f=a.videoHeight;if(!N||!f)return;const M=N/f,T=M>1.5?"16x9":M<.75?"9x16":"1x1";T!==r&&(Ca.current=!0,V(C=>C&&{...C,output_format:T}),Bs.from("narrative_jobs").update({output_format:T}).eq("id",s).then(()=>{}))};return a.addEventListener("loadedmetadata",l),()=>{a.removeEventListener("loadedmetadata",l),a.src=""}},[h==null?void 0:h.aroll_url,h==null?void 0:h.output_format,s]),n.useEffect(()=>{const t=h;if(t!=null&&t.aroll_url){if(t.preview_audio_url){se(t.preview_audio_url);return}W.current||(W.current=!0,Al(s).then(r=>{r!=null&&r.ok&&r.preview_audio_url&&se(r.preview_audio_url)}).catch(()=>{}))}},[h==null?void 0:h.aroll_url,h==null?void 0:h.preview_audio_url,s]);const bn=(t,r)=>{var N;
17if(!((N=t==null?void 0:t.timeline)!=null&&N.length)||!r)return null;const a=t.overlay_model;if(a&&Array.isArray(a.brolls)&&a.brolls.length)return a.brolls.filter(f=>f&&f.asset_url&&Number(f.dur_sec)>.05).map(f=>({...f,start_sec:+Number(f.start_sec||0).toFixed(2),dur_sec:+Number(f.dur_sec).toFixed(2)}));const l=jd(t);return t.timeline.filter(f=>f.type!=="aroll"&&f.asset_url).map(f=>{const M=Math.min(l[f.segment_id]??0,Math.max(0,r-.5)),T=Math.min(f.duration_sec,Math.max(.5,r-M)),C=f;return{id:f.segment_id,asset_id:C.asset_id??null,asset_url:C.asset_url,type:f.type,asset_window:C.asset_window??null,motion:C.motion??null,start_sec:+M.toFixed(2),dur_sec:+T.toFixed(2),reason:C.reason??null,audio:C.audio_source==="clip"?{gain:Number(C.audio_gain)||1.5,duck:Number.isFinite(Number(C.duck))?Number(C.duck):.15}:null}}).filter(f=>f.dur_sec>.05&&f.start_sec<r)},Pr=t=>t!=null&&t.length?[...t].sort((r,a)=>r.start_sec-a.start_sec||String(r.id).localeCompare(String(a.id))).map(r=>[r.id,r.asset_url,r.type,Number(r.start_sec).toFixed(2),Number(r.dur_sec).toFixed(2),r.asset_window?`${r.asset_window.start}-${r.asset_window.end}`:"",r.motion??"",r.audio?`${r.audio.gain}/${r.audio.duck}`:""].join("~")).join("|"):"";n.useEffect(()=>{var r;if(Lr.current||!((r=h==null?void 0:h.timeline)!=null&&r.length)||!Z)return;const t=bn(h,Z);t&&(A(t),k.current=t,Lr.current=!0,rr.current=Pr(t))},[h,Z]),n.useEffect(()=>{if(!Lr.current||!Z)return;const t=ce==null?void 0:ce.timeline;if(!t)return;const r=bn(t,Z),a=Pr(r),l=Pr(k.current);if(a===l){rr.current=a,Ae(!1);return}if(a!==rr.current){if(l!==rr.current){Ae(!0);return}if(r){const N=Date.now();N-Na.current>4e3&&Tt(),Na.current=N,V(t),A(r),k.current=r,rr.current=a,Ae(!1)}}},[ce,Z]);const wi=()=>{const t=ce==null?void 0:ce.timeline,r=t?bn(t,Z):null;if(!r||!t){Ae(!1);return}Tt(),V(t),A(r),k.current=r,rr.current=Pr(r),Ae(!1)},[wn,Or]=n.useState(null);n.useEffect(()=>{if(!(!be||!ce)){if(qo.includes(ce.status)){Zt.current=!0;return}if(ce.status==="complete"&&(Zt.current||wn!==null)){if(Ce(!1),Zt.current=!1,Oe){const t=Date.now()-Oe;if(t>5e3){Ge(t);try{localStorage.setItem("swaprefine:lastRenderMs",String(t))}catch{}}}Ee(null),w({title:"Render complete",description:"Your refined video is ready."})}else if(ce.status==="failed"&&Zt.current){const t=ce.error_message||"",r=/render poll failed|502|503|unreachable after retries/i.test(t);t.toLowerCase().includes("superseded")?(Zt.current=!1,nr.current=t):r?(Ce(!1),Zt.current=!1,Ee(null),nr.current=t):(Ce(!1),Zt.current=!1,Ee(null),nr.current=t,w({title:"Render failed",description:t||"Try again.",variant:"destructive"}))}}},[ce,be,wn,w]),n.useEffect(()=>{st.current=te},[te]),n.useEffect(()=>{if(!be)return;pe(Date.now());const t=window.setInterval(()=>pe(Date.now()),500);return()=>window.clearInterval(t)},[be]),n.useEffect(()=>{if(!be){Or(null);return}let t=!1;const r=async()=>{try{const{data:l}=await Bs.from("narrative_renders").select("progress,status,created_at").eq("job_id",s).eq("status","rendering").order("created_at",{ascending:!1}).limit(1),N=l==null?void 0:l[0];if(!t&&N&&typeof N.progress=="number"&&Or(N.progress),!t&&(N!=null&&N.created_at)&&N.status==="rendering"){const f=new Date(N.created_at).getTime(),M=Date.now()-f<30*60*1e3;Number.isFinite(f)&&M&&Ee(T=>T==null||T>f?f:T)}}catch{}};r();const a=window.setInterval(r,5e3);return()=>{t=!0,window.clearInterval(a)}},[be,s]);const Ze=h??{},Ea=n.useMemo(()=>(h==null?void 0:h.transcript)??[],[h]),hs=n.useMemo(()=>Ze.words??[],[Ze]),vn=n.useMemo(()=>{if(!hs.length)return;const t=hs.map(r=>r.word).join(" ");return/[ê°-í¯]/.test(t)?"ko":/[ã-ã¿ã°-ã¿]/.test(t)?"ja":/[ä¸-é¿¿]/.test(t)?"zh":/[Ø-Û¿]/.test(t)?"ar":/[äöüÃÃÃÃ]/.test(t)||/\b(und|der|die|das|nicht|ein|sie|ist)\b/i.test(t)?"de":/[à âçéèêëîïôùûü]/.test(t)||/\b(les|des|une|est|avec|vous|dans|pour)\b/i.test(t)?"fr":/[¿¡ñÃ]/.test(t)||/\b(que|con|para|una|del|los|como|pero)\b/i.test(t)?"es":/[ãõçÃÃ]/.test(t)||/\b(não|isso|uma|para|com|mas|que)\b/i.test(t)?"pt":/[à èéìîòù]/.test(t)||/\b(che|della|sono|questo|anche|come)\b/i.test(t)?"it":"en"},[hs]),[vi,yi]=n.useState(()=>(h==null?void 0:h.seed_narration_voice)??"21m00Tcm4TlvDq8ikWAM"),ji=(t=0)=>(hs.length?hs.map(l=>l.word):((h==null?void 0:h.transcript)??[]).flatMap(l=>
17String((l==null?void 0:l.text)??"").trim().split(/\s+/).filter(Boolean))).slice(Math.max(0,t),Math.max(0,t)+60).join(" ").trim()||tc,Ur=n.useRef(null),[Ni,Ra]=n.useState(null),$a=t=>{const r=[];for(const a of t){const l=String((a==null?void 0:a.text)??"").trim().split(/\s+/).filter(Boolean),N=Number(a==null?void 0:a.start_sec)||0,f=Math.max(.001,(Number(a==null?void 0:a.end_sec)||0)-N);l.forEach((M,T)=>r.push({word:M,start:N+T/l.length*f,end:N+(T+1)/l.length*f}))}return r},_i=async t=>{const r=(h==null?void 0:h.transcript)??[];if(!r.length){w({title:"No transcript to translate"});return}const a=vn??"auto";if(a!==t){Ur.current||(Ur.current={transcript:r,words:Ze.words??[]},Ra(vn??null)),w({title:`Translating to ${Fa[t]??t.toUpperCase()}â¦`});try{const l=async M=>{var Me;const T=M.trim();if(!T)return M;const ne=await(await fetch(`https://api.mymemory.translated.net/get?q=${encodeURIComponent(T)}&langpair=${a}|${t}`)).json();return((Me=ne==null?void 0:ne.responseData)==null?void 0:Me.translatedText)||M},N=[];for(const M of r)N.push({...M,text:await l(String((M==null?void 0:M.text)??""))});const f=$a(N);V(M=>M&&{...M,transcript:N,words:f}),lr(s,N,f).catch(()=>{}),Ta(),w({title:`Translated to ${Fa[t]??t.toUpperCase()} â`,description:"Transcript & captions updated â re-render to bake it in."})}catch{w({title:"Translation failed",description:"Check your connection and try again.",variant:"destructive"})}}},ki=()=>{const t=Ur.current;t&&(V(r=>r&&{...r,transcript:t.transcript,words:t.words}),lr(s,t.transcript,t.words).catch(()=>{}),Ur.current=null,Ra(null),w({title:"Reverted to the original language â"}))},yn=n.useRef(null),Ta=()=>{Os.current.length&&(Ga([]),Ms(),w({title:"Cleared stale cuts",description:"Your edited script no longer hides any words â re-render to apply."}))},Si=t=>{var ne,Me;const r=Number((ne=t[0])==null?void 0:ne.start_sec)||0,a=Number((Me=t[t.length-1])==null?void 0:Me.end_sec)||r+1,l=Math.max(.5,a-r),N=t.map(Ne=>Math.max(1,String((Ne==null?void 0:Ne.text)??"").trim().length)),f=N.reduce((Ne,Fe)=>Ne+Fe,0)||1;let M=r;const T=t.map((Ne,Fe)=>{const De=N[Fe]/f*l,mt={...Ne,start_sec:+M.toFixed(2),end_sec:+(M+De).toFixed(2)};return M+=De,mt}),C=$a(T);V(Ne=>Ne&&{...Ne,transcript:T,words:C}),Ta(),yn.current&&clearTimeout(yn.current),yn.current=window.setTimeout(()=>{lr(s,T,C).catch(()=>{})},800)},Fa={en:"English",es:"Spanish",fr:"French",de:"German",it:"Italian",pt:"Portuguese",ko:"Korean",ja:"Japanese",zh:"Chinese",ar:"Arabic"},ar=!(S!=null&&S.length),Qt=h??(ce==null?void 0:ce.timeline),{data:Js}=js({queryKey:["job-storyboard-suggest",s],queryFn:()=>mr(s),enabled:!!s&&ar&&!!Qt,staleTime:6e4}),{data:zr}=js({queryKey:["job-broll-pool",s],queryFn:()=>oa(s,100),enabled:!!s&&ar&&!!Qt&&!((io=Js==null?void 0:Js.scenes)!=null&&io.length),staleTime:6e4}),jn=n.useMemo(()=>{const t=Qt==null?void 0:Qt.aroll_url,r=Number(Qt==null?void 0:Qt.total_duration_sec)||0;if(!ar||!t||r<1)return[];const a=Math.min(14,Math.max(5,Math.ceil(r/1.5)));return Array.from({length:a},(l,N)=>{const f=Math.round((N+.5)*r/a*10)/10,M=t.includes("#")?t:`${t}#t=${f}`;return{id:`scene-${N}`,url:M,kind:"video",section_index:null,timestamp_sec:f}})},[ar,Qt==null?void 0:Qt.aroll_url,Qt==null?void 0:Qt.total_duration_sec]),Nn=n.useMemo(()=>{var a;if(!ar)return;const t=((Js==null?void 0:Js.scenes)??[]).filter(l=>l.clip_url||l.image_url);if(t.length>0)return t.map(l=>({id:l.id,url:l.clip_url??l.image_url,kind:l.clip_url?"video":"image",section_index:typeof l.beat_index=="number"?l.beat_index:null}));const r=(a=zr==null?void 0:zr.items)==null?void 0:a.filter(l=>!l.chosen);if(r!=null&&r.length)return r.map(l=>({id:l.id,url:l.url,kind:l.kind,section_index:l.section_index??null}));if(jn.length>0)return jn},[ar,Js,zr,jn]),_n=n.useRef(!1);n.useEffect(()=>{if(_n.current)return;if(S===null||S.length>0){S!==null&&(_n.current=!0);return}if(!Z||!((ce==null?void 0:ce.aroll_kind)==="instrumental"||!hs.length&&(ce==null?void 0:ce.aroll_kind)!=="spoken"))return;const r=(Nn??[]).filter(f=>!f.url.includes("#t="));if(!r.length)return;_n.current=!0;const a=r.length,l=+(Z/a).toFixed(2),N=r.map((f,M)=>({id:`broll_auto_${Date.now()}_${M}
17`,asset_id:null,asset_url:f.url,type:f.kind==="video"?"broll_video":"broll_photo",asset_window:null,motion:null,start_sec:+(M*l).toFixed(2),dur_sec:l,audio:null}));A(N),k.current=N,Yr(s,N,Z,[],xe.current??void 0,es.current??void 0).catch(()=>{}),w({title:"Scenes placed",description:`${a} scenes distributed â drag to reorder, then Re-render.`})},[S,Z,Nn,ce==null?void 0:ce.aroll_kind,hs.length]);const de=(S??[]).find(t=>t.id===R)??null,kn=n.useMemo(()=>!!(S??[]).some(t=>{var r;return(r=t.asset_id)==null?void 0:r.startsWith("ai_")}),[S]),Aa=n.useMemo(()=>{const t=new Map;for(const r of S??[]){const a=br(r.asset_id||r.asset_url);r.asset_id&&t.set(r.asset_id,a),r.asset_url&&t.set(r.asset_url,a)}return t},[S]);n.useEffect(()=>{const t=new Set;Ze!=null&&Ze.aroll_url&&/\.mov(\?|$)/i.test(Ze.aroll_url)&&t.add(Ze.aroll_url);for(const a of S??[])a.asset_url&&/\.mov(\?|$)/i.test(a.asset_url)&&t.add(a.asset_url);const r=a=>dt(l=>l.includes(a)?l:[...l,a]);for(const a of t){if(Xe.current.has(a))continue;Xe.current.add(a);let l=!1;try{l=localStorage.getItem(`h264ok:${a}`)==="1"}catch{}if(l){r(a);continue}Rs("/v1/assembly/ensure-h264",{method:"POST",body:JSON.stringify({url:a})}).then(N=>{if((N==null?void 0:N.codec)==="h264"||N!=null&&N.transcoded){try{localStorage.setItem(`h264ok:${a}`,"1")}catch{}r(a)}}).catch(()=>{})}},[Ze==null?void 0:Ze.aroll_url,S]),n.useEffect(()=>{xe.current=Array.isArray(h==null?void 0:h.story_arc)?h.story_arc:null},[h]);const[Mi,Ia]=n.useState(!1),La=n.useRef(!1),Da=n.useRef(!1);n.useEffect(()=>{var t;La.current||!h||(La.current=!0,Ia(!!((t=h==null?void 0:h.render_options)!=null&&t.section_titles)))},[h]),n.useEffect(()=>{var t;Da.current||!h||(Da.current=!0,((t=h==null?void 0:h.render_options)==null?void 0:t.replace_aroll_audio)===!0&&Ys(!0))},[h]);const es=n.useRef(null);n.useEffect(()=>{es.current=(h==null?void 0:h.render_options)??null},[h]);const[Sn,Pa]=n.useState(!1),[Mn,Ci]=n.useState(!1);n.useEffect(()=>{try{Pa(localStorage.getItem("swaprefine:renderOnLocal")==="1")}catch{}},[]),n.useEffect(()=>{try{localStorage.setItem("swaprefine:renderOnLocal",Sn?"1":"")}catch{}},[Sn]),n.useEffect(()=>{let t=!1;const r=async()=>{const l=await bo(1200);t||Ci(!!(l!=null&&l.ok))};r();const a=window.setInterval(r,1e4);return()=>{t=!0,window.clearInterval(a)}},[]);const[rs,Oa]=n.useState(!0),Ua=n.useRef(!1);n.useEffect(()=>{var r;if(Ua.current||!h)return;Ua.current=!0,((r=h==null?void 0:h.render_options)==null?void 0:r.lyrics_enabled)===!1&&Oa(!1)},[h]);const Cn=t=>{Oa(t);const r={...es.current??{},lyrics_enabled:t};es.current=r,V(a=>a&&{...a,render_options:r}),Ms()},Ei=t=>{Ia(t);const r={...es.current??{},section_titles:t};es.current=r,V(a=>a&&{...a,render_options:r}),Ms()},nt=n.useMemo(()=>{const t=Array.isArray(h==null?void 0:h.story_arc)?h.story_arc:[];if(t.length>0)return t.map((f,M)=>({index:M,label:String((f==null?void 0:f.label)||`Section ${M+1}`),at_sec:Number(f==null?void 0:f.at_sec)||0})).sort((f,M)=>f.at_sec-M.at_sec).map((f,M)=>({...f,index:M}));const r=Number(h==null?void 0:h.total_duration_sec)||0;if(!r)return[];const a=["Intro","Build","Peak","Close"],l=Math.max(1,Math.min(4,Math.ceil(r/5))),N=r/l;return Array.from({length:l},(f,M)=>({index:M,label:a[M]??`Part ${M+1}`,at_sec:Math.round(M*N*10)/10}))},[h]);n.useEffect(()=>{if(!(!nt.length||Ds.current)){Ds.current=!0;try{const t=localStorage.getItem(`swaprefine:magnetOn:${s}`),r=(ce==null?void 0:ce.aroll_kind)==="instrumental"||!hs.length&&(ce==null?void 0:ce.aroll_kind)!=="spoken";if(t==="1"||t===null&&r){const l=new Set(nt.map(N=>N.index));gs(l),Lr.current&&setTimeout(()=>Xs(l),0)}}catch{}}},[nt,s,ce==null?void 0:ce.aroll_kind,hs.length]);const za=n.useMemo(()=>{const t=new Map;if(!nt.length)return t;const r=a=>{var N;let l=0;for(let f=0;f<nt.length;f++)nt[f].at_sec<=a+.001&&(l=f);return((N=nt[l])==null?void 0:N.label)??""};for(const a of S??[]){const l=r(a.start_sec);l&&(a.asset_id&&t.set(a.asset_id,l),a.asset_url&&t.set(a.asset_url,l))}return t},[S,nt]),Ba=n.useMemo(()=>{const t=/\/storage\/v1\/object\/public\/narrative\/[^/]+\/aroll\//,r=new Set,a=[];for(const l of S??[])l.asset_url&&t.test(l.asset_url)&&!r.has(l.asset_url)&&(r.add(l.asset_url),a.push({url:l.asset_url,kind:l.type==="broll_video"?"video":"image"}));return a},[S]),[Ri,$i]=n.useState(null),Ti=n.useRef(0),[En,Rn]=n.useState(!1),Wa=n.useRef(R);n.useEffect(()=>{Wa.current=R},[R]);const $n=(t,r=!1)=>{const a=(k.current??[]).find(l=>l.id===t);a&&(ue(null),Xt(!1),X(!1),Gt(!1),Dt(!1),Ct(!1),Kt(!1),P(!0),Ft(!1),ir(a.start_sec),ts(a.asset_id||a.asset_url),$(t),Rn(!0),r&&Wa.current!==t&&$i({id:t,nonce:++Ti.current}))},Tn=t=>{const r=(k.current??[]).find(a=>a.asset_id===t||a.asset_url===t);if(!r){w({title:"Not placed",description:"That clip isnât currently in the video."});return}
17$n(r.id,!0)},Fn=(t,r)=>{ws(t,{motion:r}),Ms()};n.useEffect(()=>{!ls||Re.length||Il().then(ge).catch(()=>{})},[ls,Re.length]);const Ha=async(t,r)=>{o("Swapping A-rollâ¦");try{await Ol(s,t,r),V(a=>{if(!a)return a;const{preview_audio_url:l,...N}=a;return{...N,aroll_url:t}}),se(null),W.current=!1,w({title:"A-roll swapped",description:"Preview updated â hit âRe-render with changesâ to bake it in."})}catch(a){w({title:"Couldnât swap A-roll",description:Us(a),variant:"destructive"})}finally{o(null)}},Fi=async t=>{if(t){o("Uploading A-rollâ¦");try{const r=(t.name.split(".").pop()||"mp4").toLowerCase(),{path:a,token:l,publicUrl:N}=await Ul(r),{error:f}=await Bs.storage.from("narrative").uploadToSignedUrl(a,l,t);if(f)throw new Error(f.message);ge(M=>[{path:a,url:N,size:t.size,created_at:new Date().toISOString()},...M]),await Ha(N,a)}catch(r){w({title:"A-roll upload failed",description:Us(r),variant:"destructive"}),o(null)}}},[qa,Ai]=n.useState(()=>{try{const t=localStorage.getItem(`swaprefine:recent:${s}`);return t?JSON.parse(t):[]}catch{return[]}}),[Va,Ii]=n.useState(()=>{try{const t=localStorage.getItem(`swaprefine:removed:${s}`);return t?JSON.parse(t):[]}catch{return[]}}),Li=t=>{const r=t.asset_id||t.asset_url;if(!r)return;const a={id:`removed-${r}`,url:t.asset_url,kind:t.type==="broll_video"?"video":"image",thumb:t.asset_url,album:null,asset_id:t.asset_id??null,chosen:!1,placed_sec:null,section_index:null};Ii(l=>{const N=[a,...l.filter(f=>(f.asset_id||f.url)!==r)].slice(0,16);try{localStorage.setItem(`swaprefine:removed:${s}`,JSON.stringify(N))}catch{}return N})},ts=t=>{t&&Ai(r=>{const a=[t,...r.filter(l=>l!==t)].slice(0,16);try{localStorage.setItem(`swaprefine:recent:${s}`,JSON.stringify(a))}catch{}return a})},Us=t=>typeof t=="string"?t:(t==null?void 0:t.message)||(t==null?void 0:t.detail)||"Network/timeout â your edit is kept here; hit Re-render to apply.",Et=()=>{const t=k.current;!t||!Z||Yr(s,t,ms(),Os.current,xe.current??void 0,es.current??void 0).catch(r=>w({title:"Couldnât save",description:Us(r),variant:"destructive"}))},Di=(t,r)=>{const l=(xe.current??(Array.isArray(h==null?void 0:h.story_arc)?h.story_arc:[])).slice();let N=0,f=1/0;l.forEach((M,T)=>{const C=Math.abs((Number(M==null?void 0:M.at_sec)||0)-t);C<f&&(f=C,N=T)}),l[N]={...l[N],label:r},xe.current=l,V(M=>M&&{...M,story_arc:l}),Vn(s,l).catch(M=>w({title:"Couldn't save section name",description:Us(M),variant:"destructive"}))},Pi=t=>{const a=(xe.current??(Array.isArray(h==null?void 0:h.story_arc)?h.story_arc:[])).filter(l=>Math.abs((Number(l==null?void 0:l.at_sec)||0)-t)>.001);xe.current=a,V(l=>l&&{...l,story_arc:a}),Vn(s,a).catch(l=>w({title:"Couldn't delete section",description:Us(l),variant:"destructive"}))},Oi=t=>{var T;const a=(xe.current??(Array.isArray(h==null?void 0:h.story_arc)?h.story_arc:[])).slice().sort((C,ne)=>(Number(C==null?void 0:C.at_sec)||0)-(Number(ne==null?void 0:ne.at_sec)||0)),l=a.findIndex(C=>Math.abs((Number(C==null?void 0:C.at_sec)||0)-t)<.001),N=l>=0&&l<a.length-1&&Number((T=a[l+1])==null?void 0:T.at_sec)||Z,f=+(t+(N-t)/2).toFixed(2),M=[...a,{at_sec:f,label:"New Section"}].sort((C,ne)=>(Number(C==null?void 0:C.at_sec)||0)-(Number(ne==null?void 0:ne.at_sec)||0));xe.current=M,V(C=>C&&{...C,story_arc:M}),Vn(s,M).catch(C=>w({title:"Couldn't add section",description:Us(C),variant:"destructive"}))},An=n.useRef(null),Ms=()=>{An.current&&clearTimeout(An.current),An.current=window.setTimeout(()=>Et(),500)},Ga=t=>{Os.current=t,ya(t);try{localStorage.setItem(`swaprefine:removed:${s}`,JSON.stringify(t))}catch{}},Tt=()=>{k.current&&qe(t=>[...t,k.current])},ws=(t,r)=>
17{const a=(k.current??[]).map(l=>l.id===t?{...l,...r}:l);k.current=a,A(a)},Ui=t=>{if(!R)return;Tt();const r=t.assetWindow&&t.assetWindow.end>t.assetWindow.start?t.assetWindow:null;ws(R,{asset_url:t.url,type:t.kind==="video"?"broll_video":"broll_photo",asset_window:r?{start:+r.start.toFixed(2),end:+r.end.toFixed(2)}:null,...r?{dur_sec:+Math.max(.5,t.durSec??r.end-r.start).toFixed(2)}:{},...t.motion?{motion:t.motion}:{}}),ts(t.url),Et()},zi=(t,r)=>{Tt(),ws(t,{asset_url:r.url,type:r.kind==="video"?"broll_video":"broll_photo",asset_window:null}),$(t),ue(null),ts(r.url),setTimeout(Et,0),w({title:"B-roll replaced",description:"Swapped this cardâs clip â drag its â/â¶ triangles to retime it."})},Br=n.useRef(null),Ya=n.useRef(new Map),[Bi,Ja]=n.useState(!1),Xa=async()=>{if(Br.current)return Br.current;const t=await oa(s,300).catch(()=>({items:[]}));return Br.current=(t.items||[]).map(r=>({url:r.url,kind:r.kind,section_index:r.section_index??null})),Br.current},Ka=t=>{let r=null;for(const a of nt)a.at_sec<=t+.001&&(r=a.index);return r},Wi=async t=>{if(!Bi){Ja(!0);try{const r=await Xa(),a=(k.current??[]).find(Ne=>Ne.id===t);if(!r.length){w({title:"No other clips to rotate to",description:"This video has no saved B-roll pool to cycle through. Use the B-roll library to swap."});return}const l=new Set((k.current??[]).map(Ne=>Ne.asset_url)),N=a?Ka(a.start_sec):null,f=Ne=>Ne.url!==(a==null?void 0:a.asset_url),M=Ne=>N!=null&&Ne.section_index===N,C=[r.filter(Ne=>f(Ne)&&M(Ne)&&!l.has(Ne.url)),r.filter(Ne=>f(Ne)&&M(Ne)),r.filter(Ne=>f(Ne)&&!l.has(Ne.url)),r.filter(Ne=>f(Ne))].find(Ne=>Ne.length)??[];if(!C.length){w({title:"No other clips to rotate to"});return}const ne=Ya.current.get(t)??0,Me=C[ne%C.length];Ya.current.set(t,ne+1),Tt(),ws(t,{asset_url:Me.url,type:Me.kind==="video"?"broll_video":"broll_photo",asset_window:null}),$(t),ts(Me.url),Ms()}finally{Ja(!1)}}},Hi={1:4,2:3,3:2.2,4:1.6,5:1.2},qi=async(t,r=!1)=>{if(!Z)return;const a=Hi[t]??2.2,l=await Xa();if(!l.length&&!r){w({title:"No B-roll pool to fill from",description:"Add clips via the B-roll library first."});return}let N=(k.current??[]).filter(_e=>!ps.current.has(_e.id)).sort((_e,me)=>_e.start_sec-me.start_sec);if(r){let _e=0;N=N.map(me=>{const ze={...me,start_sec:+_e.toFixed(2)};return _e+=me.dur_sec,ze})}const f=N.map(_e=>[_e.start_sec,_e.start_sec+_e.dur_sec]).sort((_e,me)=>_e[0]-me[0]),M=[];for(const _e of f){const me=M[M.length-1];me&&_e[0]<=me[1]+.01?me[1]=Math.max(me[1],_e[1]):M.push([..._e])}const T=new Set(N.map(_e=>_e.asset_url)),C=[],ne=new Set;let Me=0;const Ne=_e=>{const me=Ka(_e),ct=[l.filter(He=>me!=null&&He.section_index===me&&!T.has(He.url)),l.filter(He=>!T.has(He.url)),l.filter(He=>me!=null&&He.section_index===me),l].find(He=>He.length);if(!ct)return null;const Bt=ct[Me%ct.length];return Me++,Bt},Fe=(_e,me)=>{let ze=_e;for(;me-ze>.4;){const ct=+Math.min(a,me-ze).toFixed(2),Bt=Ne(ze);if(!Bt)break;T.add(Bt.url);const He=`fill_${(typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():String(Date.now()+Math.round(ze*100))).slice(0,8)}`;ne.add(He),C.push({id:He,asset_id:null,asset_url:Bt.url,type:Bt.kind==="video"?"broll_video":"broll_photo",asset_window:null,motion:null,start_sec:+ze.toFixed(2),dur_sec:ct}),ze+=ct}};let De=0;for(const[_e,me]of M)_e-De>.4&&Fe(De,_e),De=Math.max(De,me);Z-De>.4&&Fe(De,Z),Tt(),ps.current=ne;const mt=[...N,...C].sort((_e,me)=>_e.start_sec-me.start_sec);k.current=mt,A(mt),setTimeout(Et,0),w({title:r?"Collapsed B-roll to fill from 0:00":C.length?`Filled ${C.length} clips`:"No gaps to fill",description:r?`Existing clips pulled together from the start${C.length?` + ${C.length} added`:""}. Re-render to bake it in.`:C.length?"B-roll now covers the gaps. Re-render to bake it in.":"The timeline is already covered."})},Xs=(t,r=!1,a)=>{if(!Z)return;const l=[...k.current??[]].sort((Fe,De)=>Fe.start_sec-De.start_sec);if(!l.length)return;const N=nt,f=Fe=>{if(!N.length)return 0;let De=N[0].index;for(const mt of N)mt.at_sec<=Fe+.001&&(De=mt.index);return De},M=new Map;for(const Fe of l){const De=(a==null?void 0:a.get(Fe.id))??f(Fe.start_sec);M.has(De)||M.set(De,[]),M.get(De).push(Fe)}const T=N.length?N.map(Fe=>Fe.index):Array.from(M.keys()).sort((Fe,De)=>Fe-De),C=[],ne=new Map;let Me=0;for(const Fe of T){const De=(M.get(Fe)??[]).sort((mt,_e)=>mt.start_sec-_e.start_sec);if(!De.length){t.has(Fe)&&ne.set(Fe,+Me.toFixed(2));continue}if(t.has(Fe)){ne.set(Fe,+Me.toFixed(2));for(const mt of De)C.push({...mt,start_sec:+Me.toFixed(2)}),Me+=mt.dur_sec}else{ne.set(Fe,+De[0].start_sec.toFixed(2));for(const mt of De)C.push({...mt}),Me=Math.max(Me,mt.start_sec+mt.dur_sec)}}if(!C.length)return;r||Tt();const Ne=C.sort((Fe,De)=>Fe.start_sec-De.start_sec);if(k.current=Ne,A(Ne),N.length&&ne.size){const Fe=(xe.current&&xe.current.length?xe.current:N.map(_e=>({at_sec:_e.at_sec,label:_e.label}))).slice().sort((_e,me)=>(Number(_e.at_sec)||0)-(Number(me.at_sec)||0)),mt=N.slice().sort((_e,me)=>_e.at_sec-me.at_sec).map((_e,me)=>{const ze=Fe[me]||{label:_e.label,at_sec:_e.at_sec};return{...ze,at_sec:ne.has(_e.index)?+Math.max(0,ne.get(_e.index)).toFixed(2):Number(ze.at_sec)||_e.at_sec}}).sort((_e,me)=>_e.at_sec-me.at_sec);xe.current=mt,V(_e=>_e&&{..._e,story_arc:mt})}setTimeout(Et,0)},Vi=t=>{gs(r=>{const a=nt.map(f=>f.index),N=a.some(f=>
17r.has(f))?new Set:new Set(a);return setTimeout(()=>Xs(N),0),N})},In=n.useRef(!1);n.useEffect(()=>{var r;if(!rt){In.current=!1;return}if(In.current||!((r=k.current)!=null&&r.length)||!Z||!nt.length)return;In.current=!0;const t=new Set(nt.map(a=>a.index));gs(t),Xs(t)},[rt,Z,S,nt]);const Gi=t=>{const r=k.current??[],a=new Set(t),l=r.filter(T=>a.has(T.id)).sort((T,C)=>T.start_sec-C.start_sec).map(T=>T.id);if(l.length!==t.length||l.length<2||l.every((T,C)=>T===t[C]))return;const N=T=>{const C=r.find(ne=>ne.id===T);return C?{asset_url:C.asset_url,asset_id:C.asset_id,type:C.type,asset_window:C.asset_window??null,motion:C.motion??null,audio:C.audio??null}:null},f=new Map;l.forEach((T,C)=>{const ne=N(t[C]);ne&&f.set(T,ne)}),Tt();const M=r.map(T=>f.has(T.id)?{...T,...f.get(T.id)}:T);k.current=M,A(M),setTimeout(Et,0),w({title:"Reordered",description:"Shuffled the clips into the new order â timing slots stay put."})},Za=(t,r,a)=>{var De,mt,_e;const l=k.current??[],N=l.find(me=>me.id===t);if(!N)return;let f=+Math.max(0,Math.min(r,Math.max(0,Z-.1))).toFixed(2);const M=l.filter(me=>me.id!==t),T=me=>{if(!nt.length)return-1;let ze=nt[0].index;for(const ct of nt)ct.at_sec<=me+.001&&(ze=ct.index);return ze},C=T(N.start_sec),ne=a!==void 0?a:T(f),Me=C!==ne;if(Me&&T(f)!==ne){const me=nt.find(ze=>ze.index===ne);me&&(f=+me.at_sec.toFixed(2))}if(!Me&&Ut.size>0){const me=Math.max(0,f-.02),ze=l.map(ct=>ct.id===t?{...ct,start_sec:me}:ct);k.current=ze,Xs(Ut,!1,new Map([[t,ne]])),ts(N.asset_id||N.asset_url),w({title:"Reordered",description:"Moved the clip into its new spot in this chapter."});return}if(!Me){const me=Math.max(0,Z-.1),ze=((De=nt.filter(He=>He.at_sec>f).sort((He,ns)=>He.at_sec-ns.at_sec)[0])==null?void 0:De.at_sec)??me+1,ct=f;let Bt=0;for(;Bt++<60&&M.some(He=>Math.floor(He.start_sec)===Math.floor(f));){const He=+Math.min(f+1,ze-.1).toFixed(2);if(Math.abs(He-f)<.01)break;f=He}if(M.some(He=>Math.floor(He.start_sec)===Math.floor(f))){const He=M.find(ns=>Math.floor(ns.start_sec)===Math.floor(ct));if(He){const ns=+N.start_sec.toFixed(2);Tt();const vs=l.map(Cs=>Cs.id===t?{...Cs,start_sec:ct}:Cs.id===He.id?{...Cs,start_sec:ns}:Cs);k.current=vs,A(vs),setTimeout(Et,0),w({title:"Swapped",description:`Clips at ${ys(ns)} and ${ys(ct)} swapped.`})}return}}if(Me){const me=nt.find(_t=>_t.index===ne),ze=+(me?me.at_sec:f).toFixed(2),ct=nt.filter(_t=>_t.at_sec>ze+.001).reduce((_t,ho)=>Math.min(_t,ho.at_sec),1/0),Bt=M.filter(_t=>T(_t.start_sec)===ne),He=+Math.max(ze,Bt.length?Math.max(...Bt.map(_t=>_t.start_sec+_t.dur_sec)):ze).toFixed(2),ns=He+(N.dur_sec||0),vs=Number.isFinite(ct)&&ns>ct+.001?+(ns-ct).toFixed(2):0,Cs=(me==null?void 0:me.label)??"section";if(Ut.size>0){Xs(Ut,!1,new Map([[t,ne]])),ts(N.asset_id||N.asset_url),w({title:"Moved",description:`Clip moved into â${Cs}â.`});return}Tt();const uo=l.map(_t=>_t.id===t?{..._t,start_sec:He}:vs&&Number.isFinite(ct)&&_t.start_sec>=ct-.001?{..._t,start_sec:+(_t.start_sec+vs).toFixed(2)}:_t);k.current=uo,A(uo),vs&&V(_t=>{if(!_t)return _t;const xo=(Array.isArray(_t.story_arc)?_t.story_arc.slice():[]).map(kr=>{const po=Number(kr==null?void 0:kr.at_sec)||0;return po>ze+.001?{...kr,at_sec:+(po+vs).toFixed(2)}:kr});return xe.current=xo,{..._t,story_arc:xo}}),ts(N.asset_id||N.asset_url),setTimeout(Et,0),w({title:"Moved",description:vs?`Clip moved into â${Cs}â â chapter extended to fit.`:`Clip moved into â${Cs}â.`});return}if(Math.abs(f-N.start_sec)<.01)return;const Ne=M.find(me=>Math.floor(me.start_sec)===Math.floor(f)&&T(me.start_sec)===ne);if(Ne){const me=((mt=nt.filter(He=>He.at_sec>f+.001).sort((He,ns)=>He.at_sec-ns.at_sec)[0])==null?void 0:mt.at_sec)??Math.max(0,Z-.1)+1,ze=+Math.min(Math.floor(Ne.start_sec)+1,me-.1).toFixed(2);Tt();const ct=l.map(He=>He.id===t?{...He,start_sec:f}:He.id===Ne.id&&T(ze)===ne?{...He,start_sec:ze}:He);k.current=ct,A(ct),Ut.size>0&&Xs(Ut,!0),setTimeout(Et,0);const Bt=((_e=nt.find(He=>He.index===ne))==null?void 0:_e.label)??"section";w({title:"Moved",description:`Clip moved to start of ${Bt}.`});return}Tt();const Fe=l.map(me=>me.id===t?{...me,start_sec:f}:me);k.current=Fe,A(Fe),Me&&Ut.size>0&&Xs(Ut,!0),setTimeout(Et,0),w({title:"Moved",description:`Clip moved to ${ys(f)}.`})},Ln=t=>{const r=k.current??[],a=T=>T.id===t.id||T.start_sec>t.start_sec+.01,l=r.filter(T=>!a(T)).map(T=>T.start_sec+T.dur_sec),N=l.length?Math.max(0,...l):0,f=Math.max(t.start_sec,+(Yt()-Math.max(.3,t.dur_sec)).toFixed(2));return{minStart:Math.min(t.start_sec,+N.toFixed(2)),maxStart:f}},Dn=t=>{let r=0;for(let a=0;a<nt.length;a++)nt[a].at_sec<=t+.001&&(r=a);return nt.length?r:-1},Yi=(t,r)=>{V(a=>{if(!a)return a;const l=Array.isArray(a.story_arc)?a.story_arc.slice():[];return l.length?(t.forEach((N,f)=>{let M=0,T=1/0;l.forEach((C,ne)=>{const Me=Math.abs((Number(C==null?void 0:C.at_sec)||0)-N);Me<T&&(T=Me,M=ne)}),l[M]={...l[M],at_sec:+(r+f*.1).toFixed(2)}}),xe.current=l,{...a,story_arc:l}):a}),Ms(),w({title:"Section extended",description:"Kept the clip in its section â the next chapter now starts after it."})},Qa=(t,r)=>{const a=k.current??[],l=a.find(Fe=>Fe.id===t);if(!l)return;const N=Dn(l.start_sec),{minStart:f,maxStart:M}=Ln(l),T=Math.max(f,Math.min(M,r)),C=+(T-l.start_sec).toFixed(2);if(Math.abs(C)<.005)return;const ne=Fe=>Fe.id===l.id||Fe.start_sec>l.start_sec+.01;Tt();const Me=a.map(Fe=>ne(Fe)?{...Fe,start_sec:+(Fe.start_sec+C).toFixed(2)}:Fe);k.current=Me,A(Me),ts(l.asset_id||l.asset_url),Ms();const Ne=Dn(T);nt.length>1&&Ne>N&&((!xs.current||xs.current.id!==t)&&(xs.current={id:t,fromIdx:N}),As.current&&clearTimeout(As.current),As.current=setTimeout(()=>{var ct,Bt;const Fe=xs.current;if(xs.current=null,As.current=null,!Fe)return;const De=(k.current??[]).find(He=>He.id===Fe.id);if(!De)return;const mt=Dn(De.start_sec);if(mt<=Fe.fromIdx)return;const _e=((ct=nt[Fe.fromIdx])==null?void 0:ct.label)??"its section",me=((Bt=nt[mt])==null?void 0:Bt.label)??"the next section";if(window.confirm(`This clip moved into â${me}â. 18 19OK â keep it in â${_e}â (extend that section to cover it; â${me}â starts after the clip). 20Cancel â leave it in â${me}â.`)){const He=+(De.start_sec+(De.dur_sec||0)).toFixed(2),ns=nt.slice(Fe.fromIdx+1,mt+1).map(vs=>vs.at_sec);Yi(ns,He+.05)}},700))},eo=(t,r)=>{r&&(V(a=>
20{if(!a)return a;const l=Array.isArray(a.story_arc)?a.story_arc.slice():[];if(!l.length)return a;const N=l.map(f=>{const M=Number(f==null?void 0:f.at_sec)||0;return M>t+.01?{...f,at_sec:+(M+r).toFixed(2)}:f});return xe.current=N,{...a,story_arc:N}}),Ms())},Nr=t=>!/\.(mov|mp4|m4v|webm|mkv|avi|qt)(\?|$)/i.test((t||"").split("?")[0]),Rt=h==null?void 0:h.teaser,It=((lo=Rt==null?void 0:Rt.items)==null?void 0:lo.filter(t=>t.kind!=="video"&&Nr(t.url)).map(t=>({url:t.url,crop:t.crop})))??((co=Rt==null?void 0:Rt.image_urls)==null?void 0:co.filter(Nr).map(t=>({url:t})))??[],Ji=It.map(t=>t.url),Wr=t=>{const r=t.filter(a=>Nr(a.url));V(a=>{if(!a)return a;const l=a.teaser??{},N=r.length>=2?{...l,items:r.map(f=>({url:f.url,kind:"photo",...f.crop?{crop:f.crop}:{}})),image_urls:r.map(f=>f.url),from_sec:l.from_sec??.2,dur_sec:l.dur_sec??1.4}:null;return{...a,teaser:N}}),Gn(s,r).catch(a=>w({title:"Couldnât save teaser",description:a==null?void 0:a.message,variant:"destructive"}))},to=t=>{let r=t.url;if(t.kind==="video"||!Nr(t.url))if(t.thumb&&Nr(t.thumb))r=t.thumb;else{w({title:"Teaser needs a photo",description:"Thatâs a video clip â pick a photo (or a Live Photoâs still frame) for the teaser flash."});return}const a=ve===null||ve<0?[...It,{url:r}]:It.map((l,N)=>N===ve?{url:r}:l);Wr(a),Be(null)},Xi=t=>Wr(It.filter((r,a)=>a!==t)),Ki=(t,r)=>{if(t===r||t<0||r<0||t>=It.length||r>=It.length)return;const a=[...It],[l]=a.splice(t,1);a.splice(r,0,l),Wr(a)},Zi=(t,r)=>Wr(It.map((a,l)=>l===t?{url:a.url,...r?{crop:r}:{}}:a));n.useEffect(()=>{const t=Rt;t&&(bs.current={fromSec:t.from_sec??.2,posX:t.pos_x??.5,posY:t.pos_y??.47})},[Rt]);const Hr=t=>{const r={...bs.current,...t};bs.current=r,V(a=>{if(!a)return a;const l=a.teaser??{};return{...a,teaser:{...l,from_sec:r.fromSec,pos_x:r.posX,pos_y:r.posY}}})},Pn=()=>{const{fromSec:t,posX:r,posY:a}=bs.current;Gn(s,It,{from_sec:t,pos_x:r,pos_y:a}).catch(l=>w({title:"Couldn't save teaser timing",description:l==null?void 0:l.message,variant:"destructive"}))},qr=(t,r)=>{if(!Z)return;Tt();const a=Math.min(Math.max(0,t),Math.max(0,Z-.5)),l=(S??[]).map(ne=>ne.start_sec).filter(ne=>ne>a+.01),N=l.length?Math.min(...l):Z,f=r.assetWindow&&r.assetWindow.end>r.assetWindow.start?r.assetWindow:null,M=f?+Math.max(.5,r.durSec??f.end-f.start).toFixed(2):+Math.max(.5,Math.min(1.5,N-a,Z-a)).toFixed(2),T=`swap_${(typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():String(Date.now())).slice(0,8)}`,C={id:T,asset_id:null,asset_url:r.url,type:r.kind==="video"?"broll_video":"broll_photo",asset_window:f?{start:+f.start.toFixed(2),end:+f.end.toFixed(2)}:null,motion:r.motion??null,start_sec:+a.toFixed(2),dur_sec:M};A(ne=>{const Me=[...ne??[],C];return k.current=Me,Me}),$(T),ue(null),ts(r.url),setTimeout(Et,0),w({title:"B-roll added",description:`Dropped at ${ys(a)} for ${M.toFixed(1)}s â drag its â/â¶ triangles to move or resize.`})},Qi=t=>{const r=st.current??te;r!=null&&qr(r,t)},Vr=(t,r)=>{qr(t,r)},so=t=>{Tt();const r=k.current??[],a=+Math.max(Z,r.reduce((C,ne)=>Math.max(C,ne.start_sec+(ne.dur_sec||0)),0)).toFixed(2),l=t.assetWindow&&t.assetWindow.end>t.assetWindow.start?t.assetWindow:null,N=l?+Math.max(.5,t.durSec??l.end-l.start).toFixed(2):2,f=`swap_${(typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():String(Date.now())).slice(0,8)}`,M={id:f,asset_id:null,asset_url:t.url,type:t.kind==="video"?"broll_video":"broll_photo",asset_window:l?{start:+l.start.toFixed(2),end:+l.end.toFixed(2)}:null,motion:t.motion??null,start_sec:a,dur_sec:N},T=[...r,M];k.current=T,A(T),$(f),ue(null),P(!0),Rn(!0),ts(t.url),setTimeout(Et,0),w({title:"Added to the end",description:`${N.toFixed(1)}s at ${ys(a)} â preview & trim it in the panel, or drag its â/â¶ on the transcript.`})},On=t=>{R?Ui(t):te!=null?Qi(t):w({title:"Drag it onto a word",description:"Drag this clip onto a transcript word to place it â or click a word first, then click a clip."})},Un=(()=>{var r;const t=(r=de==null?void 0:de.asset_id)==null?void 0:r.match(/^(?:ai_(\d+)|b(\d+))$/);return t?Number(t[1]??t[2]):null})(),el=async()=>{if(!(!de||Un==null)){Qe(!0);try{const{scenes:t}=await mr(s),r=t.find(l=>l.beat_index===Un),a=(r==null?void 0:r.clip_url)||(r==null?void 0:r.image_url);if(!a){w({title:"Original not found",description:"No saved AI clip for this beat.",variant:"destructive"});return}Tt(),ws(de.id,{asset_url:a,type:r!=null&&r.clip_url?"broll_video":"broll_photo",asset_window:null}),Et(),w({title:"Original restored",description:"Swapped back to the AI-generated clip."})}catch(t){w({title:"Couldnât restore",description:t==null?void 0:t.message,variant:"destructive"})}finally{Qe(!1)}}},zn=(t,r)=>{ws(t,{audio:r});const a=(k.current??[]).find(l=>l.id===t);ts((a==null?void 0:a.asset_id)||(a==null?void 0:a.asset_url)),setTimeout(Et,0)},tl=()=>{if(!R)return;Tt();const t=(k.current??[]).find(r=>r.id===R);t&&(Li(t),ts(t.asset_id||t.asset_url)),A(r=>{const a=(r??[]).filter(l=>l.id!==R);return k.current=a,a}),$(null),setTimeout(Et,0)},ro=()=>{qe(t=>{if(!t.length)return t;const r=t[t.length-1];return A(r),k.current=r,t.slice(0,-1)}),setTimeout(Et,0)};n.useEffect(()=>{const t=r=>{if(!((r.metaKey||r.ctrlKey)&&!r.shiftKey&&r.key.toLowerCase()==="z"))return;const a=r.target;a&&(a.tagName==="INPUT"||a.tagName==="TEXTAREA"||a.isContentEditable)||Le.length&&(r.preventDefault(),ro())};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[Le]);const Bn=(t,r)=>{(t==null?void 0:t.status)===402?w({title:"Not enough credits",description:"Rendering uses credits. Add credits on the Pricing page, then try again.",variant:"destructive"}
20):w({title:r,description:t==null?void 0:t.message,variant:"destructive"})},sl=async()=>{var N,f,M;if(!((N=await bo(1200))!=null&&N.ok))return!1;let t;try{const T=await mo(s);t=Vl(T)}catch{return!1}if(!t.aroll_url||!((M=(f=t.timeline)==null?void 0:f.timeline)!=null&&M.length))return!1;const r=await Kl(t);if(!r)return!1;try{await Gl(s)}catch{}w({title:"Rendering on your machineâ¦",description:"Local render â free & fast, no cloud queue."});const a=Date.now()+20*60*1e3;let l=0;for(;Date.now()<a;){await new Promise(C=>setTimeout(C,2500));const T=await Zl(r);if(!T){if(++l>8)return!1;continue}if(l=0,Zt.current=!0,typeof T.progress=="number"&&Or(T.progress),T.done){if(T.error||!T.url)return!1;try{await Yl(s,T.url)}catch{return!1}return!0}}return!1},rl=async()=>{try{if(Zt.current=!1,nr.current=null,Or(null),Ee(Date.now()),Ce(!0),tt(Ye.length),k.current&&Z){const t=rt||cs,r={...es.current??{},...t?{replace_aroll_audio:!0}:{},...rt?{no_aroll:!0}:{}};es.current=r;let a=k.current;if(rt&&a.length>0){const f=ms(),M=[...a].sort((ne,Me)=>ne.start_sec-Me.start_sec),T=M[M.length-1];+(T.start_sec+T.dur_sec).toFixed(2)<f-.1&&(a=a.map(ne=>ne.id===T.id?{...ne,dur_sec:+(f-ne.start_sec).toFixed(2)}:ne),k.current=a,A(a))}const l=a.filter(f=>f.asset_url&&xr.has(f.asset_url));if(l.length>0){w({title:"Uploading local clipsâ¦",description:`Uploading ${l.length} local clip${l.length!==1?"s":""} before renderingâ¦`});try{for(const f of l){const M=await xr.get(f.asset_url);a=a.map(T=>T.id===f.id?{...T,asset_url:M}:T),ws(f.id,{asset_url:M})}k.current=a}catch(f){Ce(!1),w({title:"Upload failed",description:`A local clip couldn't upload: ${f==null?void 0:f.message}. Remove it or retry.`,variant:"destructive"});return}}const N=a.filter(f=>{var M;return(M=f.asset_url)==null?void 0:M.startsWith("blob:")});if(N.length>0&&(a=a.filter(f=>{var M;return!((M=f.asset_url)!=null&&M.startsWith("blob:"))}),k.current=a,N.forEach(f=>ws(f.id,{asset_url:void 0})),w({title:`${N.length} unuploaded clip${N.length!==1?"s":""} removed`,description:"Re-place them from the Sources panel to include in the next render.",variant:"destructive"})),It.length>=2){const{fromSec:f,posX:M,posY:T}=bs.current;await Gn(s,It,{from_sec:f,pos_x:M,pos_y:T}).catch(()=>{})}await Yr(s,a,ms(),Os.current,xe.current??void 0,r)}if(Mn){if(await sl())return;w({title:"Using cloud render",description:"Local render wasnât available â rendering in the cloud instead (uses credits)."})}await Yn(s),w({title:"Re-renderingâ¦",description:"Building your video â captions, B-roll & cuts exactly as previewed. This render uses credits."})}catch(t){Ce(!1),Bn(t,"Couldnât start render")}},nl=async()=>{const t=k.current;if(!t||t.length===0){w({title:"No B-roll to remix",description:"Add some clips first, then remix."});return}const r=(xe.current??[]).slice().sort((M,T)=>(Number(M.at_sec)||0)-(Number(T.at_sec)||0)),a=r.length>0?r.map((M,T)=>({start:Number(M.at_sec)||0,end:T+1<r.length?Number(r[T+1].at_sec)||0:1/0})):[{start:0,end:1/0}],l=new Map(a.map((M,T)=>[T,[]]));for(const M of[...t].sort((T,C)=>T.start_sec-C.start_sec)){let T=0;for(let C=0;C<a.length;C++)M.start_sec>=a[C].start-.001&&(T=C);l.get(T).push(M)}const N=new Map;for(const M of l.values()){if(M.length<=1)continue;const T=M.slice().sort((Me,Ne)=>Me.start_sec-Ne.start_sec),C=T.slice();for(let Me=C.length-1;Me>0;Me--){const Ne=Math.floor(Math.random()*(Me+1));[C[Me],C[Ne]]=[C[Ne],C[Me]]}let ne=T[0].start_sec;for(const Me of C)N.set(Me.id,+ne.toFixed(2)),ne+=Me.dur_sec||0}if(N.size===0){w({title:"Nothing to remix",description:"Each chapter has only one clip â no reordering possible."});return}const f=t.map(M=>N.has(M.id)?{...M,start_sec:N.get(M.id)}:M);try{w({title:"Creating variantâ¦",description:"Forking a new project with the shuffled order â your original stays as-is."});const M=rt||cs,T={...es.current??{},...M?{replace_aroll_audio:!0}:{},...rt?{no_aroll:!0}:{}},{job_id:C}=await zl(s,f,ms(),Os.current,xe.current??void 0,T);await Yn(C),H(`/swap-refine/${C}`),w({title:"Variant created",description:"Opened the new variant â it's rendering now. Your original project is unchanged."})}catch(M){w({title:"Couldn't create variant",description:Us(M),variant:"destructive"})}},al=()=>{Ce(!1),Ee(null),Zt.current=!1,tt(Math.max(0,Ye.length-1)),Bl(s).catch(()=>{}),w({title:"Render canceled",description:"Stopped the render â your previous one is still here. Re-render any time."})},Wn=(h==null?void 0:h.caption_source)==="lyrics",_r=n.useRef(null),ol=(t,r)=>{g(!0),V(a=>a&&{...a,transcript:t,...r?{words:r}:{}}),_r.current&&clearTimeout(_r.current),_r.current=window.setTimeout(()=>{lr(s,t,r).catch(a=>w({title:"Couldnât save caption timing",description:Us(a),variant:"destructive"}))},700)},il=()=>{const t=va.current;t&&(g(!1),V(r=>r&&{...r,transcript:t.transcript,words:t.words}),_r.current&&clearTimeout(_r.current),lr(s,t.transcript,t.words).catch(()=>{}))},ll=async()=>{var r;const t=h;if((r=t==null?void 0:t.transcript)!=null&&r.length)try{if(Zt.current=!1,Ee(Date.now()),Ce(!0),tt(Ye.length),await lr(s,t.transcript,t.words),k.current&&Z){const a=rt||cs,l={...es.current??{},...a?{replace_aroll_audio:!0}:{},...rt?{no_aroll:!0}:{}};es.current=l,await Yr(s,k.current,ms(),Os.current,xe.current??void 0,l)}await Yn(s),g(!1),w({title:"Re-renderingâ¦",description:"Baking your corrected caption timing. This render uses credits."})}catch(a){Ce(!1),Bn(a,"Couldnât start render")}},cl=t=>
20{if(!t)return null;const r=t.match(/\/music-beds\/([^/]+)\.mp3$/i);return r?decodeURIComponent(r[1]):t},or=t=>t?/^https?:\/\//.test(t)?t:rc(t):null;n.useEffect(()=>{!ce||re.current||(re.current=!0,ks(cl(ce.music_bed_url??null)))},[ce]);const Hn=n.useRef(null);n.useEffect(()=>{!re.current||!s||(Hn.current&&clearTimeout(Hn.current),Hn.current=window.setTimeout(()=>{Ll(s,or(pt)).catch(()=>{})},600))},[pt]);const dl=async()=>{if(!(!s||ot)){jt(!0);try{const t=await Wl(s);t!=null&&t.timeline&&V(t.timeline),w({title:"Captions re-synced",description:`${t.phrase_count} phrases timed to the audio, hook/pops refreshed.`})}catch(t){w({title:"Couldnât re-sync captions",description:t==null?void 0:t.message,variant:"destructive"})}finally{jt(!1)}}},no=async t=>{if(!(!s||lt)){vt(!0);try{const r=await Hl(s,t);r!=null&&r.ok&&r.timeline?(V(r.timeline),Nt(""),w({title:"Lyric captions applied",description:`${r.lines??""} lines from ${r.source??"lyrics"}. Adjust timing, then re-render.`})):w({title:"Couldnât find those lyrics",description:(r==null?void 0:r.detail)||"No lyrics found â try a different spelling or add the artist.",variant:"destructive"})}catch(r){w({title:"Rebuild failed",description:r==null?void 0:r.message,variant:"destructive"})}finally{vt(!1)}}},ul=async(t,r)=>{try{await ql(s,t,r),Zt.current=!1,Ee(Date.now()),Ce(!0),tt(Ye.length),w({title:"Restoring cutâ¦",description:"Re-trimming the A-roll to restore that content and re-rendering. This render uses credits."})}catch(a){Ce(!1),Bn(a,"Couldn't restore cut")}},hl=(t,r,a)=>{const l=[...Os.current,{start:t,end:r}];Ga(l),Et(),w({title:"Marked for removal",description:`â${a.slice(0,40)}â â struck through. Click âRe-render with changesâ to apply.`})},ir=t=>{var a;const r=$c(Z,jr,t);(a=B.current)==null||a.seekTo(Math.round(r*30))},xl=be?"Rendering your refined videoâ¦":je?"Done â final render below.":"",pl=we>0?we:Math.round((45+ni(Z,jr)*9+jr.length*30)*1e3),fl=be&&Oe?Math.max(0,L-Oe):0,ml=(()=>{const t=ce==null?void 0:ce.pipeline_stage;return t==="trimming_aroll"?"Trimming audio":t==="rendering"?"Rendering video":"Starting render"})(),[zt,qn]=n.useState(()=>{try{if(localStorage.getItem("swaprefine:studioMode")==="1"||typeof window<"u"&&window.location.hash.includes("handoff"))return!0}catch{}return!1});n.useEffect(()=>{try{localStorage.setItem("swaprefine:studioMode",zt?"1":"")}catch{}},[zt]),n.useEffect(()=>{$e&&zt&&qn(!1)},[$e,zt]),n.useEffect(()=>{$e&&ae==="broll"&&P(!0)},[$e,ae]);const ao=n.useRef(!1);n.useEffect(()=>{if(ao.current)return;const t=ce==null?void 0:ce.style_anchor;t&&ei.some(r=>r.key===t)&&(le(t),ao.current=!0)},[ce]);const gl=e.jsxs("header",{className:"flex items-center gap-2 sm:gap-3 px-3 sm:px-5 py-1 sm:py-3 border-b border-black/10 bg-[#eceae3] shrink-0 overflow-x-auto",children:[e.jsx("a",{href:"/swap-refine",className:"text-white/40 hover:text-white",title:"Back to Swap & Refine projects",children:e.jsx(Xn,{className:"w-4 h-4"})}),e.jsxs("a",{href:"https://www.viralspin.ai",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 no-underline shrink-0 group/logo",children:[e.jsx("img",{src:"/images/tornado-icon.jpg",alt:"
20ViralSpinAI",className:"w-7 h-7 rounded-lg object-cover shadow-lg shadow-cyan-500/20"}),e.jsxs("span",{className:"text-sm font-bold tracking-tight text-white hidden md:block group-hover/logo:text-cyan-400 transition-colors",children:["ViralSpin",e.jsx("span",{className:"text-cyan-400 group-hover/logo:text-white",children:"AI"})]})]}),e.jsxs(bl,{children:[e.jsx(wl,{asChild:!0,children:e.jsxs("button",{className:"inline-flex shrink-0 items-center gap-1 rounded-lg border border-orange-400/40 bg-orange-400/10 px-3 py-1 outline-none transition-colors hover:bg-orange-400/20",title:"New project · switch projects",children:[e.jsx("span",{className:"text-sm font-black italic tracking-tight bg-gradient-to-r from-orange-400 to-yellow-400 bg-clip-text text-transparent",children:"Swap & Refine"}),e.jsx(Ir,{className:"h-3.5 w-3.5 text-orange-400/70"})]})}),e.jsxs(vl,{align:"start",className:"w-60 border-black/10 bg-white text-[#26241f]",children:[e.jsx(Gr,{asChild:!0,className:"cursor-pointer text-[13px] font-semibold focus:bg-black/[0.05]",children:e.jsxs(Sr,{to:"/swap-refine",children:[e.jsx(Hs,{className:"mr-2 h-4 w-4 text-cyan-600"})," New project â drop a clip"]})}),e.jsx(Gr,{asChild:!0,className:"cursor-pointer text-[13px] focus:bg-black/[0.05]",children:e.jsxs(Sr,{to:"/record",children:[e.jsx(qt,{className:"mr-2 h-4 w-4 text-rose-500"})," Record A-roll (teleprompter)"]})}),e.jsx(Gr,{asChild:!0,className:"cursor-pointer text-[13px] focus:bg-black/[0.05]",children:e.jsxs(Sr,{to:"/history",children:[e.jsx(as,{className:"mr-2 h-4 w-4 text-violet-600"})," Start from an idea"]})}),e.jsx(yl,{className:"bg-black/10"}),e.jsx(Gr,{asChild:!0,className:"cursor-pointer text-[13px] text-[#6b675e] focus:bg-black/[0.05]",children:e.jsxs(Sr,{to:"/swap-refine",children:[e.jsx(cr,{className:"mr-2 h-4 w-4"})," All projects"]})})]})]}),e.jsxs("div",{className:"ml-auto flex items-center gap-1 p-0.5 rounded-xl border border-black/10 bg-black/[0.03] shrink-0",children:[e.jsxs("button",{onClick:()=>{Xt(!1),X(!1),Gt(!1),Dt(!1),Ct(!1),Kt(!1),P(!0),Ft(!0)},title:"Browse & swap B-roll â this videoâs clips, Drive, Google Photos, AI Library",className:`flex items-center gap-1.5 px-3 py-1 rounded-lg text-[11px] font-black transition-all ${!ls&&!J&&!is&&!Fs&&!Ot&&!Ht?"bg-gradient-to-r from-orange-400 to-yellow-400 text-black shadow-[0_0_10px_rgba(249,115,22,0.4)]":"text-black/50 hover:text-black hover:bg-black/[0.06]"}`,children:[e.jsx(cr,{className:"w-3.5 h-3.5"})," B-roll"]}),e.jsxs("button",{onClick:()=>{Xt(!0),X(!1),Gt(!1),Dt(!1),Ct(!1),Kt(!1),P(!0)},title:"Swap the underlying A-roll for a different video â keeps the story arc, captions & B-roll",className:`flex items-center gap-1.5 px-3 py-1 rounded-lg text-[11px] font-black transition-all ${ls?"bg-gradient-to-r from-orange-400 to-yellow-400 text-black shadow-[0_0_10px_rgba(249,115,22,0.4)]":"text-black/50 hover:text-black hover:bg-black/[0.06]"}`,children:[e.jsx(qt,{className:"w-3.5 h-3.5"})," A-roll"]}),Ji.length>=2&&e.jsxs("button",{onClick:()=>{X(!0),Xt(!1),Gt(!1),Dt(!1),Ct(!1),Kt(!1),P(!0),Be(null)},title:"Swap, remove, or reorder the opening teaser flash images",className:`flex items-center gap-1.5 px-3 py-1 rounded-lg text-[11px] font-black transition-all ${J?"bg-gradient-to-r from-orange-400 to-yellow-400 text-black shadow-[0_0_10px_rgba(249,115,22,0.4)]":"text-black/50 hover:text-black hover:bg-black/[0.06]"}`,children:[e.jsx(as,{className:"w-3.5 h-3.5"})," Teaser"]}),e.jsxs("button",{onClick:()=>{Dt(!0),Xt(!1),X(!1),Gt(!1),Ct(!1),Kt(!1)},title:"Browse every AI-generated B-roll clip â drag one onto a word to place it",className:`flex items-center gap-1.5 px-3 py-1 rounded-lg text-[11px] font-black transition-all ${is?"bg-gradient-to-r from-orange-400 to-yellow-400 text-black shadow-[0_0_10px_rgba(249,115,22,0.4)]":"text-black/50 hover:text-black hover:bg-black/[0.06]"}`,children:[e.jsx(as,{className:"w-3.5 h-3.5"})," AI Lib"]}),e.jsxs("button",{onClick:()=>{Ct(!0),Xt(!1),X(!1),Gt(!1),Dt(!1),Kt(!1),P(!0)},title:"Add, change, or remove the background music bed â plays under your narration",className:`flex items-center gap-1.5 px-3 py-1 rounded-lg text-[11px] font-black transition-all ${Ot?"bg-gradient-to-r from-orange-400 to-yellow-400 text-black shadow-[0_0_10px_rgba(249,115,22,0.4)]":"text-black/50 hover:text-black hover:bg-black/[0.06]"}`,children:[e.jsx(Ws,{className:"w-3.5 h-3.5"})," Music"]}
20),(ce==null?void 0:ce.broll_mode)==="ai_generated"&&e.jsxs("button",{onClick:()=>{Kt(!0),Xt(!1),X(!1),Gt(!1),Dt(!1),Ct(!1),P(!0)},title:"Approve & refine the AI-generated B-roll storyboard â regenerate or insert scenes, then re-render",className:`flex items-center gap-1.5 px-3 py-1 rounded-lg text-[11px] font-black transition-all ${Ht?"bg-gradient-to-r from-orange-400 to-yellow-400 text-black shadow-[0_0_10px_rgba(249,115,22,0.4)]":"text-black/50 hover:text-black hover:bg-black/[0.06]"}`,children:[e.jsx(as,{className:"w-3.5 h-3.5"})," Storyboard"]})]}),e.jsxs("div",{className:"shrink-0 inline-flex items-center rounded-lg border border-cyan-400/40 overflow-hidden text-[11px] font-black",children:[e.jsxs("button",{onClick:()=>qn(!1),title:"Editor view â transcript + B-roll cards",className:`flex items-center gap-1.5 px-3 py-1 transition-all ${zt?"text-cyan-200 hover:bg-cyan-400/10":"bg-cyan-400 text-black shadow-[0_0_10px_rgba(34,211,238,0.45)]"}`,children:[e.jsx(jo,{className:"w-3.5 h-3.5"})," Editor"]}),e.jsxs("button",{onClick:()=>qn(!0),title:"Timeline view â large preview + full-width multi-lane timeline",className:`flex items-center gap-1.5 px-3 py-1 border-l border-cyan-400/40 transition-all ${zt?"bg-cyan-400 text-black shadow-[0_0_10px_rgba(34,211,238,0.45)]":"text-cyan-200 hover:bg-cyan-400/10"}`,children:[e.jsx(cr,{className:"w-3.5 h-3.5"})," Timeline"]})]}),e.jsx("div",{className:"shrink-0",children:e.jsx(Xl,{})}),Wn&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:()=>Cn(!rs),title:rs?"Turn off lyrics â renders without captions":"Turn on lyrics â captions bake into render",className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg border text-[11px] font-bold transition-colors ${rs?"bg-pink-500/20 border-pink-500/40 text-pink-200 hover:bg-pink-500/30":"bg-white/[0.04] border-white/15 text-white/40 hover:bg-white/[0.08] hover:text-white/60"}`,children:[e.jsx("span",{className:`relative w-7 h-3.5 rounded-full border transition-colors shrink-0 ${rs?"bg-pink-400/70 border-pink-300/50":"bg-white/15 border-white/20"}`,children:e.jsx("span",{className:`absolute top-px w-2.5 h-2.5 rounded-full bg-white shadow transition-all ${rs?"left-[14px]":"left-px"}`})}),"Lyrics ",rs?"on":"off"]}),e.jsxs("button",{onClick:()=>{Gt(t=>!t),X(!1),Xt(!1),Ct(!1),Kt(!1),P(!0)},title:"Nudge the lyric caption timing â global offset + per-line, live preview (does NOT re-transcribe)",className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg border text-[11px] font-bold transition-colors ${Fs?"bg-pink-500/30 border-pink-500/50 text-pink-100":"bg-pink-500/15 border-pink-500/30 text-pink-200 hover:bg-pink-500/25"}`,children:[e.jsx(Ws,{className:"w-3.5 h-3.5"})," Adjust lyric timing"]}),e.jsxs("button",{onClick:()=>no(),disabled:lt,title:"Rebuild captions from the song lyrics â recovers them after an accidental re-transcribe; no full re-run. Then adjust timing + re-render.",className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg border text-[11px] font-bold transition-colors bg-pink-500/10 border-pink-500/25 text-pink-200 hover:bg-pink-500/20 disabled:opacity-40",children:[lt?e.jsx(Je,{className:"w-3.5 h-3.5 animate-spin"}):null,lt?"Rebuildingâ¦":"â» Rebuild lyrics"]})]}),!Wn&&e.jsxs("button",{onClick:dl,disabled:ot,title:"Re-transcribe the audio with Whisper so captions match the spoken words (for talking videos)",className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-amber-500/15 border border-amber-500/30 text-amber-300 hover:bg-amber-500/25 disabled:opacity-40 text-[11px] font-bold transition-colors",children:[ot?e.jsx(Je,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(No,{className:"w-3.5 h-3.5"}),ot?"Re-transcribingâ¦":"Re-transcribe audio"]})]});if(!s)return e.jsx("div",{className:"sr-light h-screen flex items-center justify-center bg-[#f2f1ec] text-[#6b675e]",children:"Missing job id."});let zs;if(!h&&pn==="exchanging")zs=e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center text-center gap-3 px-6",children:[e.jsx(Je,{className:"w-8 h-8 text-violet-400 animate-spin"}),e.jsx("p",{className:"text-white/70 text-sm font-bold",children:"Signing you inâ¦"}),e.jsx("p",{className:"text-white/35 text-xs max-w-xs",children:"Opening the draft you sent from your phone."})]});else if(!h&&(Ma||gi&&!ce))zs=e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center text-center gap-4 px-6",children:[e.jsx(_o,{className:"w-8 h-8 text-amber-400"}),Ma?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-white/80 text-sm font-bold",children:"Sign in to open this edit"}),e.jsx("p",{className:"text-white/40 text-xs max-w-xs",children:"You're not signed in to the studio in this browser. Your phone app has its own login â sign in here to open the draft you just sent."}),e.jsx(Sr,{to:`/auth?next=${encodeURIComponent(`/swap-refine/${s}`)}`,className:"px-4 py-2 rounded-lg bg-violet-500 hover:bg-violet-400 text-white text-xs font-bold transition-colors",children:"Sign in"})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-white/80 text-sm font-bold",children:"Couldn't load this edit"}),e.jsx("p",{className:"text-white/40 text-xs max-w-xs",children:"The studio backend may be waking up or the connection dropped. It usually recovers within a minute."}),e.jsx("button",{onClick:()=>{xn(!1),mi()},className:"px-4 py-2 rounded-lg bg-violet-500 hover:bg-violet-400 text-white text-xs font-bold transition-colors",children:"Try again"})]})]});else if(fi&&!h)zs=e.jsxs("div",{className:"flex-1 flex items-center justify-center text-white/50 gap-2",children:[e.jsx(Je,{className:"w-5 h-5 animate-spin"})," Loading editâ¦"]});else if(!h&&ce&&ce.status!=="failed"&&ce.status!=="complete"){const t=ce.pipeline_stage,r=t==="downloading"?"Downloading videoâ¦":t==="transcribing"?"Transcribing audioâ¦":t==="scene_detect"?"Detecting scenesâ¦":t==="arc_gen"?"Building story arcâ¦":t==="broll_match"?"Matching B-rollâ¦":"Building your projectâ¦";zs=e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center text-center gap-3 px-6",children:[e.jsx(Je,{className:"w-8 h-8 text-violet-400 animate-spin"}),e.jsx("p",{className:"text-white/70 text-sm font-bold",children:r}),e.jsx("p",{className:"text-white/35 text-xs max-w-xs",children:"Scenes are being detected and mapped to a story arc â this takes about 30â60 seconds"}),e.jsx(Go,{estimate:50})]})}else!h&&ce?zs=e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center text-center gap-2 px-6",children:[e.jsx(_o,{className:"w-6 h-6 text-amber-400"}),e.jsx("p",{className:"text-white/70 text-sm font-bold",children:"This edit has no timeline yet."}),e.jsx("p",{className:"text-white/40 text-xs max-w-sm",children:"Render the video first (from Video Assembly), then reopen Swap & Refine."})]}):h?zs=e.jsxs("div",{className:`flex flex-1 min-h-0 ${$e?"flex-col overflow-hidden":""}`,children:[!zt&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:Lt,className:`overflow-hidden border-white/10 flex flex-col ${$e?ae==="transcript"?"w-full flex-1 min-h-0":"hidden":"shrink-0 min-w-[360px] border-r"}`,style:{width:$e?void 0:St},children:[e.jsxs("div",{className:"px-3 py-2 shrink-0 bg-[#eceae3] z-30 border-b border-black/[0.06] flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:()=>ss(t=>!t),title:At?`Locked â clips stay in their story-arc section AND the video is fixed to the backbone length (${ys(Z)}); clips can't run past it. Click to unlock.`:`Unlocked â drag a clip into any section, and extending a clip grows the video to fit (currently ${ys(Jt)}). Click to lock to the backbone length.`,className:`shrink-0 flex items-center gap-1 px-2 py-0.5 rounded-md text-[10px] font-bold border transition-colors ${At?"bg-orange-500/25 border-orange-500/60 text-orange-300 hover:text-orange-100":"bg-emerald-500/20 border-emerald-500/50 text-emerald-200"}`,children:At?"ð Locked":"ð Unlocked"}),e.jsxs("span",{title:At?"Finished video length â locked to the backbone (A-roll/song). Unlock to let it grow with your clips.":"Finished video length â grows to fit your montage. Clips past this won't be in the video.",className:`shrink-0 flex items-center gap-1 px-2 py-0.5 rounded-md text-[10px] font-mono font-bold border ${Jt>
20Z+.1?"bg-cyan-500/15 border-cyan-500/40 text-cyan-200":"bg-white/[0.05] border-white/12 text-white/55"}`,children:["ð¬ ",ys(Jt)]}),e.jsxs("button",{onClick:()=>Cn(!rs),title:rs?"Captions on â burned into the render. Click to remove captions (preview updates instantly; re-render to bake in).":"Captions removed â the render will have no captions. Click to restore them.",className:`shrink-0 flex items-center gap-1 px-2 py-0.5 rounded-md text-[10px] font-bold border transition-colors ${rs?"bg-white/[0.05] border-white/15 text-white/55 hover:text-white":"bg-rose-500/20 border-rose-500/50 text-rose-200 hover:bg-rose-500/30"}`,children:[e.jsx(No,{className:"w-3 h-3"})," ",rs?"Captions on":"Captions off"]}),e.jsxs("label",{className:"flex items-center gap-1.5 ml-auto text-[10px] text-white/45",title:"Auto-fill uncovered time with more B-roll. Higher = more, shorter clips. Your hand-placed clips are kept.",children:[e.jsx("span",{className:"font-bold text-white/60 shrink-0",children:"Density"}),e.jsx("input",{type:"range",min:0,max:5,step:1,value:Pt,onCh
20ange:t=>{const r=+t.target.value;Ss(r),r>0&&qi(r,!1)},className:"w-20 accent-cyan-400"}),e.jsx("span",{className:"w-7 text-right font-mono",children:Pt===0?"off":`${Pt}Ã`})]})]}),e.jsx("span",{className:"text-[10px] font-black text-white/40 uppercase tracking-widest",children:"Transcript · click a word to seek (uncovered word â add a B-roll) · click it again to select it for removal · drag across words to select a range"})]}),e.jsx(Zc,{phrases:Ea,storedWords:hs,brolls:S??[],removedRanges:jr,selectedId:R,onSelect:t=>$n(t),onSeek:ir,onChange:(t,r)=>ws(t,r),onCommit:Et,onRestoreCut:ul,onRemoveWords:hl,onInsertPoint:t=>{$(null),ue(t),P(!0)},onDropBroll:Vr,onReplaceBroll:zi,onRotateBroll:Wi,onReorderBroll:Gi,onMoveBroll:Za,sectionsLocked:At,onToggleSectionsLock:()=>ss(t=>!t),onBlockedMove:()=>w({title:"Locked ð",description:"Click âð Lockedâ (top-left of the transcript) to unlock, then drag the clip into another section. (Unlocking also lets the video grow past the backbone length.)",variant:"destructive"}),arcSections:nt,magnetSections:Ut,onToggleMagnet:Vi,onAddCard:t=>{$(null),ue(t),P(!0),Ft(!0),y(r=>r+1)},onRenameSection:Di,onDeleteSection:Pi,onAddSection:Oi,locate:Ri,detectedLanguage:vn,onTranslate:_i,translatedFromLang:Ni,onRevertTranslation:ki,onPreviewVoice:(t,r=0)=>Dl(s,t,ji(r)),onEditPhrases:Si,suggestedPool:Nn,onAddSuggested:(t,r,a)=>Vr==null?void 0:Vr(a,{url:t,kind:r}),voiceId:vi,onVoiceChange:yi})]}),!$e&&e.jsx("div",{onPointerDown:Wt,title:"Drag to resize the transcript column",className:"w-1.5 shrink-0 cursor-col-resize hover:bg-cyan-400/40 transition-colors"})]}),e.jsxs("div",{className:`min-w-0 flex overflow-hidden ${zt?"flex-row":"flex-col"} ${$e?ae==="preview"?"w-full flex-1 min-h-0":"hidden":"flex-1"}`,children:[fe&&e.jsxs("div",{className:"shrink-0 mx-3 mt-2 flex items-center gap-3 rounded-md border border-cyan-400/30 bg-cyan-500/10 px-3 py-2 text-xs text-cyan-100",children:[e.jsx(as,{className:"w-4 h-4 shrink-0 text-cyan-300"}),e.jsx("span",{className:"flex-1",children:"Your agent edited this timeline. Reload to see the changes â your unsaved edits will be replaced."}),e.jsx("button",{onClick:wi,className:"shrink-0 rounded bg-cyan-400/20 px-2.5 py-1 font-medium text-cyan-50 hover:bg-cyan-400/30 transition-colors",children:"Reload"}),e.jsx("button",{onClick:()=>Ae(!1),title:"Dismiss",className:"shrink-0 text-cyan-200/60 hover:text-cyan-100",children:e.jsx(os,{className:"w-3.5 h-3.5"})})]}),e.jsx("div",{className:`flex items-center justify-center overflow-hidden bg-[#f2f1ec] ${zt?"order-2 shrink-0 w-[440px] max-w-[46%] h-full border-l border-black/10 p-3":"flex-1 min-h-0 p-3"} ${$e?"!w-full !max-w-full !border-l-0 !p-1.5":""}`,children:e.jsx("div",{className:`sr-dark flex overflow-hidden rounded-2xl bg-[#0b0b0f] shadow-xl ${zt||$e?"h-full w-full":"max-h-full"}`,children:e.jsx(Vc,{arollUrl:rt?"":Ze.aroll_url||"",h264Urls:et,audioUrl:ee||void 0,arollDur:Z,videoDurSec:Jt,brolls:(S??[]).filter(t=>!t.asset_url.startsWith("blob:")||xr.has(t.asset_url)),transcript:rs?Ze.transcript:[],words:rs?hs:[],removedRanges:jr,hook:Ze.hook,pops:Ze.pops,teaser:Ze.teaser,musicUrl:or(pt),replaceArollAudio:(cs||rt)&&!!or(pt),musicOffsetSec:ds,musicVolume:us,outputFormat:Ze.output_format||"9x16",playerRef:B,finalVideoRef:K,canUndo:Le.length>0,onUndo:ro,onRerender:()=>mn(!0),rerendering:be,renderElapsedMs:fl,renderEtaMs:pl,renderProgress:wn,renderStage:ml,hasEdits:(S??[]).length>0,status:xl,finals:Ye,finalMeta:ht,finalView:Ke,onSelectFinal:tt,onCancelRender:al,onRemixVariant:nl,renderOnLocal:Sn,onToggleRenderOnLocal:Pa,bridgeAvailable:Mn,sections:nt,showChapterTitles:Mi,onToggleChapterTitles:Ei,finalInTray:zt,fill:$e})})}),zt&&e.jsxs("div",{className:"order-1 flex-1 min-w-0 self-stretch flex flex-col justify-start overflow-auto thin-scroll border-r border-black/10 bg-[#eceae3] px-6 py-4",children:[e.jsx(_d,{brolls:S??[],durationSec:Jt,sections:nt,playerRef:B,fps:30,audioUrl:ee||Ze.aroll_url||void 0,arollUrl:rt?void 0:Ze.aroll_url||void 0,musicUrl:or(pt)||void 0,replaceArollAudio:(cs||rt)&&!!or(pt),onClipClick:t=>{$n(t);const r=(S??[]).find(a=>a.id===t);r!=null&&r.asset_url&&U({url:r.asset_url,isVideo:r.type==="broll_video"})},onClipMove:(t,r)=>Za(t,r)}
20),j&&e.jsxs("div",{className:"mt-4 flex flex-col items-center gap-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-black uppercase tracking-widest text-black/40",children:"Clip preview"}),e.jsx("button",{onClick:()=>U(null),title:"Close preview",className:"rounded-md p-0.5 text-black/40 hover:bg-black/5 hover:text-black/70",children:e.jsx(os,{className:"w-3.5 h-3.5"})})]}),e.jsx("div",{className:"overflow-hidden rounded-xl bg-black shadow-lg",style:{height:"clamp(220px, 40vh, 460px)",aspectRatio:"9 / 16"},children:j.isVideo?e.jsx("video",{src:j.url,controls:!0,autoPlay:!0,loop:!0,playsInline:!0,className:"h-full w-full object-contain bg-black"},j.url):e.jsx("img",{src:j.url,alt:"",className:"h-full w-full object-contain bg-black"})})]}),e.jsx(Ed,{arollUrl:rt?void 0:Ze.aroll_url||void 0,styleKey:I,onStyleChange:le,onRegenerateAll:t=>{le(t),w({title:"Theme selected",description:"Hit Re-render to generate your B-roll in this style."})},bridgeAvailable:Mn})]})]}),x?e.jsxs("div",{className:`overflow-auto thin-scroll p-4 flex flex-col gap-3 relative ${zt?"order-first border-r border-black/10":"border-l border-white/10"} ${$e?ae==="broll"?"w-full flex-1 min-h-0 border-l-0":"hidden":"shrink-0"}`,style:{width:$e?void 0:ie},children:[!$e&&e.jsx("div",{onPointerDown:Pe,title:"Drag to resize panel",className:"absolute left-0 top-0 bottom-0 w-1.5 -ml-0.5 cursor-col-resize z-40 hover:bg-cyan-400/40 transition-colors"}),!zt&&e.jsx("button",{onClick:()=>P(!1),title:"Collapse panel",className:"absolute top-3 right-3 z-20 text-white/30 hover:text-white",children:e.jsx(fa,{className:"w-4 h-4"})}),Ht?e.jsx("div",{className:"pr-7",children:e.jsx($d,{jobId:s,status:ce==null?void 0:ce.status,pipelineStage:ce==null?void 0:ce.pipeline_stage,onClose:()=>{Kt(!1),Ft(!0)},onRerenderStarted:()=>{Dr.invalidateQueries({queryKey:["narrative-job",s]}),Kt(!1)}})}):ls?e.jsxs("div",{className:"pr-7 flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qt,{className:"w-4 h-4 text-emerald-300"}),e.jsx("h2",{className:"text-sm font-bold text-white",children:"Swap A-roll"})]}),e.jsx("p",{className:"text-[11px] text-white/40 leading-snug",children:"Replace the underlying A-roll video. Your story arc, captions and B-roll placements are kept â only the base video changes. Hit âRe-render with changesâ to bake it in. (Captions are NOT re-transcribed â best for swapping in a re-shot take of the same script / duration.)"}),e.jsxs("label",{className:"flex items-start gap-2 cursor-pointer select-none rounded-lg border border-white/10 bg-white/[0.03] px-3 py-2",children:[e.jsx("input",{type:"checkbox",className:"accent-pink-400 w-3.5 h-3.5 mt-0.5",checked:rt,onChange:t=>sr(t.target.checked)}),e.jsxs("span",{className:"text-[11px] text-white/70 leading-snug",children:["No A-roll â use a ",e.jsx("span",{className:"font-bold text-white",children:"music backtrack"})," + B-roll instead",e.jsxs("span",{className:"block text-white/40",children:["Drops the A-roll; B-roll auto-snaps to fill (magnet). Pick a track in the"," ",e.jsx("button",{onClick:t=>{t.preventDefault(),Ct(!0),Xt(!1),X(!1),Gt(!1),Dt(!1),P(!0)},className:"text-pink-300 hover:text-pink-200 underline font-semibold",children:"Music tab"}),". Stays off across refreshes."]})]})]}),e.jsxs("label",{className:`flex items-center justify-center gap-2 py-2.5 rounded-lg border-2 border-dashed text-[11px] font-bold ${Y?"border-white/15 text-white/40 cursor-default":"border-emerald-500/40 text-emerald-200 hover:bg-emerald-500/10 cursor-pointer"}`,children:[e.jsx("input",{type:"file",accept:"video/*",className:"hidden",disabled:!!Y,onChange:t=>{var a;const r=(a=t.target.files)==null?void 0:a[0];r&&Fi(r),t.target.value=""}}),Y?e.jsx(Je,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(qt,{className:"w-3.5 h-3.5"}),Y??"Upload a new A-roll video"]}),Ze.aroll_url&&e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("div",{className:"text-[10px] font-black text-white/35 uppercase tracking-widest",children:"This videoâs A-roll"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:(()=>{const t=/\.(mp3|m4a|wav|aac|ogg)(\?|$)/i.test(Ze.aroll_url);return e.jsxs("div",{draggable:!t&&!rt,onDragStart:!t&&!rt?r=>Ho(r,Ze.aroll_url):void 0,onClick:()=>sr(r=>!r),title:rt?"A-roll removed â click to use it again":"Click to remove the A-roll (collapses B-roll to fill from 0:00, music backtrack + B-roll montage). Drag into the transcript to use it as B-roll.",className:`relative aspect-[9/16] rounded-lg overflow-hidden border-2 bg-black cursor-pointer transition-all ${rt?"border-white/15 opacity-40":"border-emerald-400"} ${t||rt?"":"active:cursor-grabbing"}`,children:[t?e.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center gap-1 text-emerald-300/80",children:[e.jsx(Ws,{className:"w-5 h-5"}),e.jsx("span",{className:"text-[8px] font-bold uppercase tracking-wider",children:"Narration"})]}
20):e.jsx("video",{src:Ze.aroll_url,muted:!0,playsInline:!0,preload:"metadata",draggable:!1,className:"w-full h-full object-cover"}),e.jsx("span",{className:`absolute top-1 right-1 text-[8px] font-black px-1 rounded ${rt?"bg-white/20 text-white/80":"bg-emerald-500/90 text-black"}`,children:rt?"REMOVED":"CURRENT"}),rt&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:e.jsx("span",{className:"text-[9px] font-black uppercase tracking-widest text-white/80 bg-black/55 px-1.5 py-0.5 rounded",children:"Click to re-add"})})]})})()}),e.jsx("div",{className:"text-[9px] text-white/30 font-mono truncate",children:decodeURIComponent(Ze.aroll_url.split("/").pop()||"").slice(0,48)||"A-roll"}),rt&&e.jsxs("p",{className:"text-[10px] text-amber-300/80 leading-snug",children:["A-roll removed â the video plays as a music + B-roll montage.",or(pt)?"":e.jsx("span",{className:"text-amber-300",children:" Pick a music bed in the Music tab so it isnât silent."})," Preview reflects it now; baking a no-A-roll cut needs a re-render."]})]}),Re.filter(t=>t.url!==Ze.aroll_url).length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[10px] font-black text-white/35 uppercase tracking-widest mt-1",children:"Or reuse a previous A-roll"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:Re.filter(t=>t.url!==Ze.aroll_url).map(t=>{const r=Ze.aroll_url===t.url;return e.jsxs("button",{disabled:!!Y||r,draggable:!0,onDragStart:a=>Ho(a,t.url),onClick:()=>Ha(t.url,t.path),title:r?"Current A-roll":"Click to use as A-roll · drag into the transcript to use as B-roll",className:`relative aspect-[9/16] rounded-lg overflow-hidden border-2 bg-black ${r?"border-emerald-400":"border-white/10 hover:border-emerald-400/60"} disabled:opacity-60`,children:[e.jsx("video",{src:t.url,muted:!0,playsInline:!0,preload:"metadata",draggable:!1,className:"w-full h-full object-cover"}),r&&e.jsx("span",{className:"absolute top-1 right-1 text-[8px] font-black bg-emerald-500/90 text-black px-1 rounded",children:"CURRENT"})]},t.path)})})]})]}):Ot?e.jsxs("div",{className:"pr-7 flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ws,{className:"w-4 h-4 text-pink-300"}),e.jsx("h2",{className:"text-sm font-bold text-white",children:"Music bed"})]}),e.jsx("p",{className:"text-[11px] text-white/40 leading-snug",children:"Add a song or instrumental that plays under your narration â handy if you skipped it up front. Pick a preset or upload your own track, then re-render (uses credits)."}),e.jsx(sc,{value:pt,onChange:ks,previewVolume:us}),e.jsxs("div",{className:"mt-1 flex flex-col gap-2 rounded-lg border border-pink-500/25 bg-pink-500/[0.06] p-2.5",children:[e.jsx("span",{className:"text-[11px] font-bold text-pink-300",children:"ðµ Use a song's lyrics as captions"}),e.jsxs("select",{value:xt,onChange:t=>Nt(t.target.value),className:"w-full px-2 py-1 rounded-lg border border-pink-500/30 bg-pink-500/10 text-pink-200 text-[11px] font-bold outline-none cursor-pointer",children:[e.jsx("option",{value:"",children:"Pick a songâ¦"}),Fd.map(t=>e.jsxs("option",{value:`${t.title}|${t.artist}`,children:[t.title,t.artist?` â ${t.artist}`:""]},t.title)),e.jsx("option",{value:"custom",children:"Customâ¦"})]}),xt==="custom"&&e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("input",{value:bt,onChange:t=>Mt(t.target.value),placeholder:"Song title",className:"flex-1 min-w-0 px-2 py-1 rounded-lg border border-pink-500/30 bg-black/30 text-pink-100 text-[11px] outline-none placeholder:text-pink-300/40"}),e.jsx("input",{value:wt,onChange:t=>yt(t.target.value),placeholder:"Artist (optional)",className:"flex-1 min-w-0 px-2 py-1 rounded-lg border border-pink-500/30 bg-black/30 text-pink-100 text-[11px] outline-none placeholder:text-pink-300/40"})]}),xt&&e.jsxs("button",{onClick:()=>{let t="",r="";
20if(xt==="custom")t=bt.trim(),r=wt.trim();else{const a=xt.split("|");t=a[0],r=a[1]||""}t&&no({songTitle:t,artist:r||void 0})},disabled:lt||xt==="custom"&&!bt.trim(),className:"flex items-center justify-center gap-1.5 px-2.5 py-1.5 rounded-lg border text-[11px] font-bold transition-colors bg-pink-500/20 border-pink-500/45 text-pink-100 hover:bg-pink-500/30 disabled:opacity-40",children:[lt?e.jsx(Je,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Ws,{className:"w-3.5 h-3.5"}),lt?"Applyingâ¦":"Apply lyrics as captions"]})]}),pt&&e.jsxs("label",{className:"flex items-center gap-2 text-[10px] text-white/55",children:[e.jsx("span",{className:"shrink-0 font-bold text-white/70",children:"Volume"}),e.jsx("input",{type:"range",min:0,max:1,step:.05,value:us,onChange:t=>Ls(+(+t.target.value).toFixed(2)),className:"flex-1 accent-pink-400",title:"Music bed volume"}),e.jsxs("span",{className:"w-[36px] text-right font-mono text-white/70",children:[Math.round(us*100),"%"]})]}),pt&&e.jsxs("label",{className:"flex items-start gap-2 cursor-pointer select-none rounded-lg border border-white/10 bg-white/[0.03] px-3 py-2",children:[e.jsx("input",{type:"checkbox",className:"accent-pink-400 w-3.5 h-3.5 mt-0.5",checked:cs,onChange:t=>Ys(t.target.checked)}),e.jsxs("span",{className:"text-[11px] text-white/70 leading-snug",children:["Use music ",e.jsx("span",{className:"font-bold text-white",children:"instead of"})," the A-rollâs audio",e.jsx("span",{className:"block text-white/40",children:"Mutes the original A-roll sound and makes the music the soundtrack. Press play above to hear it now â no re-render needed to preview."})]})]}),pt&&e.jsxs("label",{className:"flex items-center gap-2 text-[10px] text-white/55",children:[e.jsx("span",{className:"shrink-0 font-bold text-white/70",children:"Music offset"}),e.jsx("input",{type:"range",min:-10,max:10,step:.1,value:ds,onChange:t=>Is(+(+t.target.value).toFixed(1)),className:"flex-1 accent-pink-400",title:"Shift the music earlier (â) or later (+) â tenths of a second"}),e.jsxs("span",{className:"w-[52px] text-right font-mono text-white/70",children:[ds>0?"+":"",ds.toFixed(1),"s"]}),ds!==0&&e.jsx("button",{onClick:()=>Is(0),title:"Reset offset",className:"text-white/40 hover:text-white text-[10px] font-bold",children:"reset"})]}),e.jsxs("p",{className:"text-[10px] text-white/35 mt-1 leading-snug",children:["Your music choice plays in the preview instantly and saves automatically â press play above to hear it. Hit ",e.jsx("span",{className:"text-white/60 font-bold",children:"âRe-render with changesâ"})," when you want it baked into the final download."]})]}):J?e.jsxs("div",{className:"pr-7 flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(as,{className:"w-4 h-4 text-cyan-300"}),e.jsx("h2",{className:"text-sm font-bold text-white",children:"Teaser images"})]}),e.jsx("p",{className:"text-[11px] text-white/40 leading-snug",children:"The quick flash montage at the very start. Drag images to reorder, â¶ to enlarge & adjust crop/zoom, click to swap from a source, â to remove, or â+ addâ to append. Changes save automatically â hit âRe-render with changesâ to bake them in. (Needs at least 2 images; fewer clears the teaser.)"}),e.jsxs("div",{className:"flex gap-4 items-start rounded-xl border border-white/10 bg-white/[0.03] p-3",children:[e.jsxs("div",{className:"flex flex-col gap-2 flex-1 min-w-0",children:[e.jsx("span",{className:"text-[10px] font-black text-white/45 uppercase tracking-widest",children:"Appears at"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"range",min:0,max:5,step:.1,value:(Rt==null?void 0:Rt.from_sec)??.2,onChange:t=>Hr({fromSec:Number(t.target.value)}),onPointerUp:Pn,className:"flex-1 h-1.5 rounded-full accent-cyan-400 cursor-pointer"}),e.jsx("input",{type:"number",min:0,max:5,step:.1,value:((Rt==null?void 0:Rt.from_sec)??.2).toFixed(1),onChange:t=>{const r=+Math.max(0,Math.min(5,Number(t.target.value))).toFixed(1);Hr({fromSec:r}),Pn()},className:"w-14 bg-black/30 border border-white/12 rounded-md px-2 py-1 text-[12px] text-white text-center outline-none focus:border-cyan-400/60"}),e.jsx("span",{className:"text-[10px] text-white/30 shrink-0",children:"s"})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5 items-center shrink-0",children:[e.jsx("span",{className:"text-[10px] font-black text-white/45 uppercase tracking-widest",children:"Position"}),(()=>{const a=50.160000000000004,l=135*.35,N=(Rt==null?void 0:Rt.pos_x)??.5,f=(Rt==null?void 0:Rt.pos_y)??.47,M=Math.max(a/2,Math.min(76-a/2,N*76))-a/2,T=Math.max(l/2,Math.min(135-l/2,f*135))-l/2;return e.jsxs("div",{style:{width:76,height:135,position:"relative",borderRadius:8,border:"1.5px solid rgba(255,255,255,0.15)",background:"rgba(0,0,0,0.5)",cursor:"crosshair",touchAction:"none"},onPointerDown:C=>{C.currentTarget.setPointerCapture(C.pointerId);const ne=C.currentTarget.getBoundingClientRect(),Me=+Math.max(0,Math.min(1,(C.clientX-ne.left)/ne.width)).toFixed(3),Ne=+Math.max(0,Math.min(1,(C.clientY-ne.top)/ne.height)).toFixed(3);Hr({posX:Me,posY:Ne})},onPointerMove:C=>{if(C.buttons!==1)return;const ne=C.currentTarget.getBoundingClientRect(),Me=+Math.max(0,Math.min(1,(C.clientX-ne.left)/ne.width)).toFixed(3),Ne=+Math.max(0,Math.min(1,(C.clientY-ne.top)/ne.height)).toFixed(3);Hr({posX:Me,posY:Ne})},onPointerUp:Pn,children:[e.jsx("div",{style:{position:"absolute",inset:0,background:"linear-gradient(180deg,#1a1a2e 0%,#16213e 100%)",borderRadius:7,opacity:.7}}),e.jsx("div",{style:{position:"absolute",left:M,top:T,width:a,height:l,borderRadius:5,border:"2px s
20olid rgba(255,255,255,0.9)",boxShadow:"0 4px 14px rgba(0,0,0,0.6)",background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"},children:It[0]&&e.jsx("img",{src:It[0].url,style:{width:"100%",height:"100%",objectFit:"cover",borderRadius:3},alt:""})}),e.jsx("div",{style:{position:"absolute",left:N*76-3,top:f*135-3,width:6,height:6,borderRadius:"50%",background:"#22d3ee",boxShadow:"0 0 6px #22d3ee",pointerEvents:"none"}})]})})(),e.jsx("span",{className:"text-[9px] text-white/25",children:"drag to reposition"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",onDragOver:t=>{t.dataTransfer.types.includes("application/x-viralspin-broll")&&(t.preventDefault(),t.dataTransfer.dropEffect="copy")},onDrop:t=>{const r=t.dataTransfer.getData("application/x-viralspin-broll");if(r){t.preventDefault();try{to(JSON.parse(r))}catch{}}},children:[It.map((t,r)=>e.jsxs("div",{onDragOver:a=>{Se!==null&&(a.preventDefault(),a.dataTransfer.dropEffect="move",ft!==r&&Ps(r))},onDragLeave:()=>Ps(a=>a===r?null:a),onDrop:a=>{a.preventDefault(),Se!==null&&Se!==r&&Ki(Se,r),We(null),Ps(null)},className:`relative group rounded-lg transition-all ${ft===r&&Se!==null&&Se!==r?"ring-2 ring-cyan-400 ring-offset-2 ring-offset-black/40":""} ${Se===r?"opacity-40":""}`,children:[e.jsx("button",{draggable:!0,onDragStart:a=>{We(r);try{a.dataTransfer.effectAllowed="move"}catch{}},onDragEnd:()=>{We(null),Ps(null)},onClick:()=>Be(r),title:"Drag to reorder · click to swap this teaser image",className:`block rounded-lg overflow-hidden border-2 cursor-grab active:cursor-grabbing transition-all ${ve===r?"border-cyan-400":t.crop?"border-cyan-400/50":"border-white/15 hover:border-cyan-400/60"}`,style:{width:64,height:96},children:e.jsx("img",{src:t.url,alt:`teaser ${r+1}`,className:"w-full h-full pointer-events-none",style:si(t.crop)})}),e.jsx("button",{onClick:()=>fs(r),title:"Enlarge & adjust crop / zoom",className:"absolute -bottom-1.5 -right-1.5 w-5 h-5 rounded-full bg-black/80 border border-cyan-400/40 text-cyan-200 hover:text-white hover:border-cyan-400 flex items-center justify-center",children:e.jsx(wr,{className:"w-2.5 h-2.5"})}),e.jsx("button",{onClick:()=>Xi(r),title:"Remove from teaser",className:"absolute -top-1.5 -right-1.5 w-5 h-5 rounded-full bg-black/80 border border-white/20 text-white/70 hover:text-white text-[10px] font-bold flex items-center justify-center",children:"â"})]},`${t.url}-${r}`)),e.jsx("button",{onClick:()=>Be(-1),title:"Add a teaser image",className:`rounded-lg border-2 border-dashed flex items-center justify-center text-2xl transition-colors ${ve===-1?"border-cyan-400 text-cyan-300 bg-cyan-500/10":"border-white/15 text-white/40 hover:border-cyan-400/60 hover:text-cyan-300"}`,style:{width:64,height:96},children:"+"})]}),ve!==null&&e.jsxs("div",{className:"flex flex-col gap-2 border-t border-white/10 pt-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[11px] font-bold text-cyan-200",children:ve<0?"Pick an image to ADD":`Pick a replacement for image ${ve+1}`}),e.jsx("button",{onClick:()=>Be(null),className:"px-2 py-0.5 rounded-md bg-white/8 border border-white/15 text-white/55 hover:text-white text-[10px] font-bold",children:"Cancel"})]}),e.jsx(hi,{jobId:s,segment:{segment_id:"__teaser__",asset_id:null,type:"broll_photo"},isAiJob:kn,onPick:to})]})]}):Fs&&Wn?e.jsx("div",{className:"pr-7",children:e.jsx(Cc,{transcript:Ea,words:hs,onApply:ol,onSeek:ir,onSaveAndRerender:ll,onReset:il,rerendering:be,dirty:b,lyricsEnabled:rs,onToggleLyrics:Cn})}):de?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between pr-7",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>Ft(!0),title:"Back to the B-roll library",className:"-ml-1 p-1 rounded-md text-white/45 hover:text-white hover:bg-white/10",children:e.jsx(Xn,{className:"w-4 h-4"})}),e.jsx("h2",{className:"text-sm font-bold text-white",children:"Selected B-roll"})]}),e.jsxs("button",{onClick:tl,className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-red-600/20 border border-red-500/30 text-red-300 hover:bg-red-600/30 text-[11px] font-bold transition-colors",children:[e.jsx(Xo,{className:"w-3.5 h-3.5"})," Remove"]})]}),e.jsx("button",{onClick:()=>ir(de.start_sec),title:"Jump the preview to where this clip plays",className:"rounded-lg overflow-hidden border border-white/15 bg-black self-center",style:{width:150,aspectRatio:"9 / 16"},children:de.type==="broll_video"?e.jsx("video",{src:de.asset_url,muted:!0,playsInl
20ine:!0,preload:"metadata",className:"w-full h-full object-cover"}):e.jsx("img",{src:de.asset_url,alt:"",className:"w-full h-full object-cover"})}),(()=>{const t=de.motion,r=(t==null?void 0:t.focus_to_x)!=null||(t==null?void 0:t.type)==="pan_left"||(t==null?void 0:t.type)==="pan_right"?"Pan":((t==null?void 0:t.start_scale)??1)>1.001||(t==null?void 0:t.type)==="ken_burns"||(t==null?void 0:t.type)==="zoom_in"||(t==null?void 0:t.type)==="zoom_out"?"Ken Burns / zoom":"Static (no zoom)",a=r!=="Static (no zoom)";return e.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[e.jsxs("span",{className:"text-white/45",children:["Motion: ",e.jsx("span",{className:"text-white/70 font-semibold",children:r})]}),a&&e.jsx("button",{onClick:()=>Fn(de.id,{type:"static",start_scale:1,end_scale:1,crop_hint:(t==null?void 0:t.crop_hint)??"center"}),className:"ml-auto px-2 py-0.5 rounded-md bg-white/8 border border-white/15 text-white/60 hover:text-white text-[10px] font-bold",children:"Remove zoom"})]})})(),(()=>{const t=de.caption_pos||"auto",r=[{v:"auto",label:"Auto"},{v:"top",label:"Top"},{v:"mid",label:"Middle"},{v:"bottom",label:"Bottom"}];return e.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[e.jsx("span",{className:"text-white/45 shrink-0",children:"Caption"}),e.jsx("div",{className:"flex items-center gap-1 ml-auto",children:r.map(a=>e.jsx("button",{onClick:()=>{ws(de.id,{caption_pos:a.v==="auto"?null:a.v}),Ms()},title:a.v==="auto"?"Auto-place captions (face-aware)":`Place captions ${a.label.toLowerCase()} while this clip is on screen`,className:`px-2 py-0.5 rounded-md border text-[10px] font-bold transition-colors ${t===a.v?"bg-cyan-500/25 border-cyan-400/50 text-cyan-100":"bg-white/8 border-white/15 text-white/60 hover:text-white"}`,children:a.label},a.v))})]})})(),e.jsx("p",{className:"text-[11px] text-white/40",children:"Replace this clip from a source below, or drag its â¶/â triangle on the transcript to move / shorten it (shortening reveals the A-roll). Changes save automatically."}),Un!=null&&e.jsxs("button",{onClick:el,disabled:he,title:"Swap back to the AI-generated clip this beat originally used",className:"flex items-center justify-center gap-1.5 py-2 rounded-lg bg-violet-600/20 border border-violet-500/30 text-violet-200 hover:bg-violet-600/30 disabled:opacity-40 text-[11px] font-bold transition-colors",children:[he?e.jsx(Je,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(as,{className:"w-3.5 h-3.5"}),he?"Restoringâ¦":"Restore original AI clip"]}),e.jsxs("button",{onClick:()=>Rn(t=>!t),className:"flex items-center justify-center gap-2 py-2 rounded-lg bg-white/8 border border-white/15 text-white/70 hover:text-white text-[11px] font-bold transition-colors",children:[e.jsx(Ko,{className:"w-3.5 h-3.5"})," ",En?"Hide details":de.type==="broll_video"?"Trim clip":"Adjust framing (crop · zoom · pan)"]}),En&&de.type==="broll_photo"&&(()=>{(S??[]).filter(f=>f.id!==de.id).map(f=>f.start_sec).filter(f=>f>de.start_sec+.01);const t=Math.max(.5,+(Yt()-de.start_sec).toFixed(2)),r=Math.min(t,Ue),a=f=>{const M=+Math.max(.3,Math.min(f,r)).toFixed(2),T=de.start_sec+M,C=(k.current??[]).filter(De=>De.id!==de.id&&De.start_sec>de.start_sec+.01),ne=C.length?Math.min(...C.map(De=>De.start_sec)):1/0,Me=rt||!(Ze!=null&&Ze.aroll_url),Ne=Number.isFinite(ne)?Me?+(T-ne).toFixed(2):Math.max(0,+(T-ne).toFixed(2)):0;Tt();const Fe=(k.current??[]).map(De=>De.id===de.id?{...De,dur_sec:M}:Ne!==0&&De.start_sec>de.start_sec+.01?{...De,start_sec:+(De.start_sec+Ne).toFixed(2)}:De);k.current=Fe,A(Fe),Ne!==0&&eo(de.start_sec,Ne),ts(de.asset_id||de.asset_url),setTimeout(Et,0)},{minStart:l,maxStart:N}=Ln(de);return e.jsx(ci,{assetUrl:de.asset_url,motion:de.motion??null,outputFormat:Ze.output_format||"9x16",durSec:de.dur_sec,maxDurSec:r,onDurChange:a,startSec:de.start_sec,minStartSec:l,maxStartSec:N,onStartChange:f=>Qa(de.id,f),onMotion:f=>Fn(de.id,f),onSyncSeek:()=>ir(de.start_sec),onSyncPlayMain:()=>{var f;try{(f=B.current)==null||f.play()}catch{}}})})(),En&&de.type==="broll_video"&&(()=>{var T;const t=(S??[]).filter(C=>C.id!==de.id).map(C=>C.start_sec).filter(C=>C>de.start_sec+.01),r=t.length?Math.min(...t):Z,a=Math.max(.3,+(Math.min(r,Z)-de.start_sec).toFixed(2)),l=Math.max(.3,+(Yt()-de.start_sec).toFixed(2)),N=(C,ne)=>{const Me=Math.min(ne,l),Ne=de.start_sec+Me,Fe=(k.current??[]).filter(ze=>ze.id!==de.id&&ze.start_sec>de.start_sec+.01),De=Fe.length?Math.min(...Fe.map(ze=>ze.start_sec)):1/0,mt=rt||!(Ze!=null&&Ze.aroll_url),_e=Number.isFinite(De)?mt?+(Ne-De).toFixed(2):Math.max(0,+(Ne-De).toFixed(2)):0;Tt();const me=(k.current??[]).map(ze=>ze.id===de.id?{...ze,asset_window:{start:+C.toFixed(2),end:+(C+Me).toFixed(2)},dur_sec:+Me.toFixed(2)}:_e!==0&&ze.start_sec>de.start_sec+.01?{...ze,start_sec:+(ze.start_sec+_e).toFixed(2)}:ze);
20if(k.current=me,A(me),_e!==0&&eo(de.start_sec,_e),ts(de.asset_id||de.asset_url),setTimeout(Et,0),_e>0){const ze=Fe.length;w({title:"Clips shifted",description:`Pushed ${ze} later clip${ze>1?"s":""} back ${_e.toFixed(1)}s to fit â kept each in its section.`})}},{minStart:f,maxStart:M}=Ln(de);return e.jsx(di,{videoUrl:de.asset_url,posterUrl:`/v1/assembly/thumb?kind=video&url=${encodeURIComponent(de.asset_url)}`,motion:de.motion??null,outputFormat:Ze.output_format||"9x16",durSec:de.dur_sec,onMotion:C=>Fn(de.id,C),onSyncSeek:()=>ir(de.start_sec),onSyncPlayMain:()=>{var C;try{(C=B.current)==null||C.play()}catch{}},startOffset:((T=de.asset_window)==null?void 0:T.start)??0,maxDur:l,warnBeyondSec:a,placeStartSec:de.start_sec,placeMinStartSec:f,placeMaxStartSec:M,onPlaceStartChange:C=>Qa(de.id,C),onLocate:()=>Tn(de.asset_id||de.asset_url),onChange:(C,ne)=>N(C,ne)})})(),de.type==="broll_video"&&e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.02] p-3 flex flex-col gap-2",children:[e.jsxs("label",{className:"flex items-center justify-between gap-2 cursor-pointer",children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-[12px] font-bold text-white",children:[e.jsx(jc,{className:"w-3.5 h-3.5 text-cyan-300"})," Use this clipâs sound"]}),e.jsx("input",{type:"checkbox",className:"accent-cyan-400 w-4 h-4",checked:!!de.audio,onChange:t=>zn(de.id,t.target.checked?{gain:1.5,duck:.15}:null)})]}),e.jsx("p",{className:"text-[11px] text-white/40 leading-snug",children:"Plays this clipâs own audio (e.g. the ultrasound heartbeat). The preview un-mutes it right away; the music-duck + loudness boost are applied in the final mix on Re-render."}),de.audio&&e.jsxs("div",{className:"flex flex-col gap-2 pt-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] text-white/45 w-[68px] shrink-0",children:"Loudness"}),e.jsx("input",{type:"range",min:.5,max:2.5,step:.1,value:de.audio.gain??1.5,onChange:t=>zn(de.id,{...de.audio,gain:Number(t.target.value)}),className:"flex-1 accent-cyan-400"}),e.jsxs("span",{className:"text-[10px] font-mono text-cyan-300 w-9 text-right",children:[(de.audio.gain??1.5).toFixed(1),"Ã"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] text-white/45 w-[68px] shrink-0",children:"Music under"}),e.jsx("input",{type:"range",min:0,max:1,step:.05,value:de.audio.duck??.15,onChange:t=>zn(de.id,{...de.audio,duck:Number(t.target.value)}),className:"flex-1 accent-cyan-400"}),e.jsxs("span",{className:"text-[10px] font-mono text-cyan-300 w-9 text-right",children:[Math.round((de.audio.duck??.15)*100),"%"]})]})]})]}),e.jsxs("button",{onClick:()=>Ft(!0),className:"flex items-center justify-center gap-2 py-2.5 rounded-lg bg-cyan-500/15 border border-cyan-500/30 text-cyan-100 hover:bg-cyan-500/25 text-[12px] font-bold transition-colors",children:[e.jsx(cr,{className:"w-4 h-4"})," Swap from libraryâ¦"]})]}):te!=null?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between pr-7",children:[e.jsx("h2",{className:"text-sm font-bold text-white",children:"Add B-roll"}),e.jsx("button",{onClick:()=>ue(null),className:"px-2.5 py-1 rounded-lg bg-white/8 border border-white/15 text-white/60 hover:text-white text-[11px] font-bold transition-colors",children:"Cancel"})]}),e.jsxs("p",{className:"text-[11px] text-white/40",children:["Pick a source below to drop a new B-roll at ",e.jsx("span",{className:"font-bold text-cyan-300",children:ys(te)})," (the word you clicked). It covers ~1.5s of the A-roll; afterwards drag its â¶/â triangles to move or resize it."]}),e.jsxs("button",{onClick:()=>Ft(!0),className:"flex items-center justify-center gap-2 py-2.5 rounded-lg bg-cyan-500/15 border border-cyan-500/30 text-cyan-100 hover:bg-cyan-500/25 text-[12px] font-bold transition-colors",children:[e.jsx(cr,{className:"w-4 h-4"})," Choose from libraryâ¦"]})]}):zt?e.jsx("div",{className:"-m-4 flex min-h-0 flex-1 flex-col",children:e.jsx(Lo,{inline:!0,jobId:s,open:!0,onClose:()=>{},segment:{segment_id:"__browse__",asset_id:null,type:"broll_photo"},isAiJob:kn,onPick:t=>On(t),onAddToEnd:t=>so(t),chosenColorByKey:Aa,recentKeys:qa,recentRemoved:Va,chosenSectionByKey:za,arcSections:nt,onAddToSection:(t,r)=>qr(r,t),onLocate:Tn,placedUploads:Ba,focusSearchNonce:d})}):e.jsxs("div",{className:"mt-8 flex flex-col items-center gap-3 pr-7",children:[e.jsxs("p",{className:"text-xs text-white/30 text-center",children:["Click a B-roll thumbnail or triangle to swap, move, or remove it â or click any ",e.jsx("span",{className:"text-white/50 font-semibold",children:"uncovered word"})," in the transcript to add a new B-roll there."]}),e.jsxs("button",{onClick:()=>Ft(!0),className:"flex items-center justify-center gap-2 px-3 py-2 rounded-lg bg-cyan-500/15 border border-cyan-500/30 text-cyan-100 hover:bg-cyan-500/25 text-[12px] font-bold transition-colors",children:[e.jsx(cr,{className:"w-4 h-4"})," Browse B-roll library"]}),e.jsx("p",{className:"text-[10px] text-white/25 text-center",children:"Drag any clip from the library onto a word or card."})]})]}):!zt&&!$e&&e.jsxs("button",{onClick:()=>P(!0),title:"Open B-roll panel",className:"shrink-0 w-8 border-l border-white/10 flex flex-col items-center justify-center gap-2 text-white/40 hover:text-white hover:bg-white/[0.03] transition-colors",children:[e.jsx(Xn,{className:"w-4 h-4"}),e.jsx("span",{className:"text-[10px] font-bold tracking-widest",style:{writingMode:"vertical-rl"},children:"B-ROLL"})]}),$e&&e.jsx("nav",{className:"shrink-0 flex items-stretch border-t border-white/15 bg-[#141414] pb-[env(safe-area-inset-bottom)]",children:[{id:"preview",label:"Preview",icon:e.jsx(_s,{className:"w-5 h-5"}),on:"text-cyan-300 bg-cyan-400/15",off:"text-cyan-300/70"},{id:"transcript",label:"Transcript",icon:e.jsx(jo,{className:"w-5 h-5"}),on:"text-amber-300 bg-amber-400/15",off:"text-amber-300/70"},{id:"broll",label:"B-roll",icon:e.jsx(qt,{className:"w-5 h-5"}),on:"text-emerald-300 bg-emerald-400/15",off:"text-emerald-300/70"}].map(t=>e.jsxs("button",{onClick:()=>it(t.id),className:`flex-1 flex flex-col items-center justify-center gap-0.5 py-2.5 text-[11px] font-bold border-r border-white/10 last:border-r-0 transition-colors ${ae===t.id?t.on:t.off}`,children:[t.icon,e.jsx("span",{children:t.label})]},t.id))})]}):zs=e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center text-center gap-3 px-6",children:[e.jsx(Je,{className:"w-8 h-8 text-violet-400 animate-spin"}),e.jsx("p",{className:"text-white/70 text-sm font-bold",children:"Connecting to your editâ¦"}),e.jsx("p",{className:"text-white/35 text-xs max-w-xs",children:"Waking the editor up â this can take a few seconds the first time."}),e.jsx(Go,{estimate:20})]});const oo=Math.max(1,Math.ceil(((h==null?void 0:h.total_duration_sec)||0)/30));return e.jsxs("div",{className:"sr-light h-screen flex flex-col bg-[#f2f1ec] text-[#26241f]",children:[gl,bi&&e.jsx(ac,{videoUrl:h==null?void 0:h.aroll_url,basicCost:20*oo,premiumCost:20*oo,balance:(gn==null?void 0:gn.credits)??0,onClose:()=>mn(!1),onApprove:t=>{const r={...es.current??{},tier:t.tier,grade_mode:t.grade_mode,captions_mode:t.captions_mode,behind_subject:t.behind_subject,motion_graphics:t.motion_graphics};es.current=r,V(a=>a&&{...a,render_options:r}),mn(!1),rl()}}),v&&!q&&e.jsxs("div",{className:"shrink-0 flex items-center gap-2 px-4 py-2 bg-amber-500/10 border-b border-amber-500/20 text-xs text-amber-200",children:[e.jsx("span",{className:"text-amber-400 shrink-0",children:"âª"}),e.jsxs("span",{children:["Browsing settings from Render #",u||"?",O?` · ${new Date(O).toLocaleStr
20ing(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}`:""," ","â these are the exact B-roll and settings that produced that render. Edit or re-render to apply them to your project."]}),e.jsx("button",{className:"ml-auto shrink-0 text-amber-400/60 hover:text-amber-300 px-1",onClick:()=>F(!0),title:"Dismiss",children:"â"})]}),zs,e.jsx(vd,{jobId:s,open:is,onClose:()=>Dt(!1),onPick:On}),e.jsx(Lo,{jobId:s,open:Ts,onClose:()=>Ft(!1),segment:de?{segment_id:de.id,asset_id:de.asset_id??null,type:de.type}:{segment_id:"__browse__",asset_id:null,type:"broll_photo"},isAiJob:kn,contextLabel:de?"Replacing the selected clip":te!=null?`Adding at ${ys(te)}`:void 0,onPick:t=>{On(t),Ft(!1)},onAddToEnd:t=>{so(t),Ft(!1)},chosenColorByKey:Aa,recentKeys:qa,recentRemoved:Va,chosenSectionByKey:za,arcSections:nt,onAddToSection:(t,r)=>{qr(r,t),Ft(!1)},onLocate:Tn,placedUploads:Ba,focusSearchNonce:d}),yr!=null&&It[yr]&&(()=>{const a=({"9x16":.5625,"1x1":1,"16x9":1.7777777777777777}[Ze.output_format||"9x16"]??9/16)*(.66/.35),l=yr;return e.jsx(Sc,{assetUrl:It[l].url,boxAR:a,crop:It[l].crop,indexLabel:`${l+1} of ${It.length}`,onChange:N=>Zi(l,N),onClose:()=>fs(null)})})()]})}export{Ru as default};
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.