var useState=React.useState,useEffect=React.useEffect,useRef=React.useRef,useCallback=React.useCallback,h=React.createElement;
var AC="#0EA5E9",AD="rgba(14,165,233,0.12)",AB="rgba(14,165,233,0.3)";
var BG0="#07070a",BG1="#0c0c10",BG2="#111116",BG3="#1a1a20",BGC="#141418";
var BD="rgba(255,255,255,0.06)",BDH="rgba(255,255,255,0.12)";
var T1="#f0f0f2",T2="#a0a0aa",TM="#66666e",GR="#22C55E",RD="#EF4444",YL="#EAB308",PK="#EC4899",PU="#A855F7";
var STEPS=[{id:1,label:"Source video",icon:"video"},{id:2,label:"Extract frame",icon:"frame"},{id:3,label:"Generate image",icon:"sparkle"},{id:4,label:"Motion control",icon:"motion"},{id:5,label:"Lip sync",icon:"mic"}];
var DPROMPT="Recreate the first image but replace the person entirely with the person from the second image. Match all physical features (face, body, hair color, skin tone) from the second image. Keep the pose, background, and framing from the first image.";
function api(p,o){o=o||{};return fetch(p,Object.assign({headers:{"Content-Type":"application/json"}},o)).then(function(r){return r.json().then(function(d){if(!r.ok)throw new Error(d.error||"Error");return d;});});}
function upld(p,f,field,extra){var fd=new FormData();fd.append(field||"file",f);if(extra)Object.keys(extra).forEach(function(k){fd.append(k,extra[k]);});return fetch(p,{method:"POST",body:fd}).then(function(r){return r.json().then(function(d){if(!r.ok)throw new Error(d.error||"Upload failed");return d;});});}
function fSrc(p){if(!p)return null;return"/files/"+p.replace(/^.*?storage\//,"");}
function isImg(n){return/\.(jpg|jpeg|png|webp|gif)$/i.test(n);}
function isVid(n){return/\.(mp4|mov|webm)$/i.test(n);}
function isAud(n){return/\.(mp3|wav|m4a|ogg)$/i.test(n);}

function Ico(props){var n=props.name,s=props.size||18,c=props.color||"currentColor";var p={style:{width:s,height:s,display:"inline-block",flexShrink:0,verticalAlign:"middle"},viewBox:"0 0 24 24",fill:"none",stroke:c,strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round"};
if(n==="video")return h("svg",p,h("polygon",{points:"23 7 16 12 23 17 23 7",fill:c,stroke:"none"}),h("rect",{x:1,y:5,width:15,height:14,rx:2}));
if(n==="frame")return h("svg",p,h("rect",{x:2,y:2,width:20,height:20,rx:2}),h("line",{x1:9,y1:2,x2:9,y2:22}));
if(n==="sparkle")return h("svg",p,h("path",{d:"M12 2l2.09 6.26L20 10l-5.91 1.74L12 18l-2.09-6.26L4 10l5.91-1.74z",fill:c+"30",stroke:c}));
if(n==="motion")return h("svg",p,h("path",{d:"M5 3l14 9-14 9V3z",fill:c+"20"}),h("line",{x1:19,y1:4,x2:19,y2:20}));
if(n==="mic")return h("svg",p,h("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),h("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),h("line",{x1:12,y1:19,x2:12,y2:23}));
if(n==="pipeline")return h("svg",p,h("circle",{cx:5,cy:12,r:2}),h("circle",{cx:12,cy:12,r:2}),h("circle",{cx:19,cy:12,r:2}),h("line",{x1:7,y1:12,x2:10,y2:12}),h("line",{x1:14,y1:12,x2:17,y2:12}));
if(n==="vault")return h("svg",p,h("rect",{x:3,y:3,width:18,height:18,rx:2,fill:c+"10"}),h("path",{d:"M3 9h18"}),h("path",{d:"M9 21V9"}));
if(n==="costs")return h("svg",p,h("line",{x1:12,y1:2,x2:12,y2:22}),h("path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"}));
if(n==="upload")return h("svg",p,h("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),h("polyline",{points:"17 8 12 3 7 8"}),h("line",{x1:12,y1:3,x2:12,y2:15}));
if(n==="check")return h("svg",Object.assign({},p,{strokeWidth:"2.5"}),h("polyline",{points:"20 6 9 17 4 12"}));
if(n==="plus")return h("svg",Object.assign({},p,{strokeWidth:"2"}),h("line",{x1:12,y1:5,x2:12,y2:19}),h("line",{x1:5,y1:12,x2:19,y2:12}));
if(n==="folder")return h("svg",p,h("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z",fill:c+"15"}));
if(n==="download")return h("svg",p,h("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),h("polyline",{points:"7 10 12 15 17 10"}),h("line",{x1:12,y1:15,x2:12,y2:3}));
if(n==="image")return h("svg",p,h("rect",{x:3,y:3,width:18,height:18,rx:2}),h("circle",{cx:8.5,cy:8.5,r:1.5}),h("polyline",{points:"21 15 16 10 5 21"}));
if(n==="music")return h("svg",p,h("path",{d:"M9 18V5l12-2v13"}),h("circle",{cx:6,cy:18,r:3}),h("circle",{cx:18,cy:16,r:3}));
if(n==="x")return h("svg",Object.assign({},p,{strokeWidth:"2"}),h("line",{x1:18,y1:6,x2:6,y2:18}),h("line",{x1:6,y1:6,x2:18,y2:18}));
if(n==="back")return h("svg",p,h("polyline",{points:"15 18 9 12 15 6"}));
if(n==="fwd")return h("svg",p,h("polyline",{points:"9 18 15 12 9 6"}));
if(n==="trash")return h("svg",p,h("polyline",{points:"3 6 5 6 21 6"}),h("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}));
if(n==="expand")return h("svg",p,h("polyline",{points:"15 3 21 3 21 9"}),h("polyline",{points:"9 21 3 21 3 15"}),h("line",{x1:21,y1:3,x2:14,y2:10}),h("line",{x1:3,y1:21,x2:10,y2:14}));
return null;}

function Spinner(props){return h("span",{style:{width:props.s||14,height:props.s||14,border:"2px solid rgba(255,255,255,0.15)",borderTopColor:props.c||"#fff",borderRadius:"50%",animation:"spin .6s linear infinite",display:"inline-block"}});}
function Btn(props){return h("button",{onClick:props.onClick,disabled:props.disabled||props.loading,style:Object.assign({display:"inline-flex",alignItems:"center",gap:6,padding:"9px 16px",borderRadius:8,fontSize:12,fontWeight:600,border:props.primary?"none":"1px solid "+BD,background:props.primary?"linear-gradient(135deg,"+AC+",#3B82F6)":"transparent",color:props.primary?"#fff":T2,cursor:props.disabled?"not-allowed":"pointer",opacity:props.disabled?.35:1,transition:"all .15s"},props.sx||{}),className:"btn-hover"},props.loading?h(Spinner,{s:12}):null,props.children);}
function Toast(props){if(!props.msg)return null;var c=props.type==="error"?RD:GR;return h("div",{style:{position:"fixed",top:16,right:16,zIndex:9999,padding:"10px 16px",borderRadius:10,background:BG3,border:"1px solid "+c+"40",display:"flex",alignItems:"center",gap:10,maxWidth:400,fontSize:12,color:T1,boxShadow:"0 8px 32px rgba(0,0,0,.5)",animation:"slideIn .25s"}},h("div",{style:{width:6,height:6,borderRadius:"50%",background:c}}),props.msg,h("button",{onClick:props.onClose,style:{background:"none",border:"none",color:TM,cursor:"pointer",marginLeft:8,fontSize:14}},"×"));}

// ============================================
// Fullscreen Viewer
// ============================================
function Lightbox(props){
  if(!props.file)return null;
  var name=props.file.filename||props.file.file_path.split("/").pop();
  var src=fSrc(props.file.file_path);
  var vid=isVid(name);
  useEffect(function(){var fn=function(e){if(e.key==="Escape")props.onClose();if(e.key==="ArrowLeft"&&props.onPrev)props.onPrev();if(e.key==="ArrowRight"&&props.onNext)props.onNext();};document.addEventListener("keydown",fn);return function(){document.removeEventListener("keydown",fn);};},[]);
  return h("div",{style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,.92)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn .15s"},onClick:props.onClose},
    h("button",{onClick:props.onClose,style:{position:"absolute",top:16,right:16,background:"none",border:"none",cursor:"pointer",zIndex:10}},h(Ico,{name:"x",size:24,color:"#fff"})),
    props.onPrev?h("button",{onClick:function(e){e.stopPropagation();props.onPrev();},style:{position:"absolute",left:16,top:"50%",transform:"translateY(-50%)",background:"rgba(255,255,255,.1)",border:"none",borderRadius:"50%",width:44,height:44,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"}},h(Ico,{name:"back",size:22,color:"#fff"})):null,
    props.onNext?h("button",{onClick:function(e){e.stopPropagation();props.onNext();},style:{position:"absolute",right:16,top:"50%",transform:"translateY(-50%)",background:"rgba(255,255,255,.1)",border:"none",borderRadius:"50%",width:44,height:44,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"}},h(Ico,{name:"fwd",size:22,color:"#fff"})):null,
    h("div",{onClick:function(e){e.stopPropagation();},style:{maxWidth:"85vw",maxHeight:"85vh",display:"flex",flexDirection:"column",alignItems:"center"}},
      vid?h("video",{src:src,controls:true,autoPlay:true,style:{maxWidth:"85vw",maxHeight:"80vh",borderRadius:10}}):h("img",{src:src,style:{maxWidth:"85vw",maxHeight:"80vh",borderRadius:10,objectFit:"contain"}}),
      h("div",{style:{marginTop:10,display:"flex",alignItems:"center",gap:10}},
        h("span",{style:{fontSize:12,color:T2}},name),
        h("a",{href:src,download:true,style:{fontSize:11,color:AC,textDecoration:"none",display:"flex",alignItems:"center",gap:4,padding:"4px 10px",borderRadius:6,border:"1px solid "+AB}},h(Ico,{name:"download",size:12,color:AC}),"Download")
      )
    )
  );
}

// ============================================
// Vault Picker Modal
// ============================================
function VaultPicker(props){
  if(!props.open)return null;
  var fs=useState([]),files=fs[0],setFiles=fs[1];
  var fds=useState([]),folders=fds[0],setFolders=fds[1];
  var cs=useState("all"),cur=cs[0],setCur=cs[1];
  var pvs=useState(null),pvFile=pvs[0],setPvFile=pvs[1];
  useEffect(function(){
    api("/api/vault/folders").then(setFolders).catch(function(){setFolders([]);});
    api("/api/vault/files?folder="+(cur==="all"?"":cur)).then(function(all){
      if(props.fileType)setFiles(all.filter(function(f){return f.file_type===props.fileType;}));
      else setFiles(all);
    }).catch(function(){setFiles([]);});
  },[cur,props.fileType]);
  var pick=function(f){props.onSelect(f);props.onClose();setPvFile(null);};
  if(pvFile){var pvn=pvFile.filename||pvFile.file_path.split("/").pop();var pvs2=fSrc(pvFile.file_path);var pvv=isVid(pvn);
    return h("div",{style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,.95)",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",animation:"fadeIn .12s"}},
      h("button",{onClick:function(){setPvFile(null);},style:{position:"absolute",top:16,left:16,background:"rgba(255,255,255,.08)",border:"1px solid rgba(255,255,255,.1)",borderRadius:8,padding:"8px 14px",cursor:"pointer",display:"flex",alignItems:"center",gap:6,color:T2,fontSize:12}},h(Ico,{name:"back",size:14,color:T2}),"Back to grid"),
      h("button",{onClick:function(){setPvFile(null);props.onClose();},style:{position:"absolute",top:16,right:16,background:"none",border:"none",cursor:"pointer"}},h(Ico,{name:"x",size:22,color:"#fff"})),
      h("div",{style:{maxWidth:"80vw",maxHeight:"65vh",display:"flex",alignItems:"center",justifyContent:"center"}},
        pvv?h("video",{src:pvs2,controls:true,autoPlay:true,style:{maxWidth:"80vw",maxHeight:"65vh",borderRadius:10}}):
        h("img",{src:pvs2,style:{maxWidth:"80vw",maxHeight:"65vh",borderRadius:10,objectFit:"contain"}})
      ),
      h("div",{style:{marginTop:14,display:"flex",alignItems:"center",gap:10}},
        h("span",{style:{fontSize:12,color:T2,maxWidth:300,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}},pvn),
        pvFile.source&&pvFile.source!=="upload"?h("span",{style:{fontSize:9,color:AC,textTransform:"uppercase",fontWeight:700,padding:"2px 8px",borderRadius:4,background:AD}},pvFile.source):null
      ),
      h("button",{onClick:function(){pick(pvFile);},style:{marginTop:16,padding:"11px 32px",borderRadius:8,fontSize:13,fontWeight:600,background:"linear-gradient(135deg,"+AC+",#3B82F6)",border:"none",color:"#fff",cursor:"pointer",display:"flex",alignItems:"center",gap:6}},h(Ico,{name:"check",size:14,color:"#fff"}),"Use this")
    );
  }
  return h("div",{style:{position:"fixed",inset:0,zIndex:9998,background:"rgba(0,0,0,.75)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn .15s"},onClick:props.onClose},
    h("div",{onClick:function(e){e.stopPropagation();},style:{width:680,maxHeight:"78vh",background:BG2,borderRadius:14,border:"1px solid "+BD,overflow:"hidden",display:"flex",flexDirection:"column"}},
      h("div",{style:{padding:"14px 18px",borderBottom:"1px solid "+BD,display:"flex",justifyContent:"space-between",alignItems:"center"}},
        h("div",{style:{display:"flex",alignItems:"center",gap:8}},h(Ico,{name:"vault",size:16,color:AC}),h("span",{style:{fontSize:14,fontWeight:600,color:T1}},"Select from Vault"),props.fileType?h("span",{style:{fontSize:10,color:TM,marginLeft:6,padding:"2px 8px",borderRadius:4,background:BG3,border:"1px solid "+BD}},props.fileType+"s only"):null),
        h("button",{onClick:props.onClose,style:{background:"none",border:"none",cursor:"pointer",color:TM}},h(Ico,{name:"x",size:16}))),
      h("div",{style:{display:"flex",gap:4,padding:"10px 18px",overflowX:"auto",flexShrink:0}},
        h("button",{onClick:function(){setCur("all");},style:{padding:"5px 12px",borderRadius:6,fontSize:11,fontWeight:500,background:cur==="all"?AD:"transparent",border:"1px solid "+(cur==="all"?AB:"transparent"),color:cur==="all"?AC:TM,cursor:"pointer"}},"All"),
        folders.map(function(f){return h("button",{key:f.id,onClick:function(){setCur(f.id);},style:{padding:"5px 12px",borderRadius:6,fontSize:11,fontWeight:500,background:cur===f.id?AD:"transparent",border:"1px solid "+(cur===f.id?AB:"transparent"),color:cur===f.id?AC:TM,cursor:"pointer"}},f.name);})),
      h("div",{style:{flex:1,overflow:"auto",padding:"10px 18px 18px",display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:8}},
        files.length===0?h("div",{style:{gridColumn:"1/-1",padding:40,textAlign:"center",color:TM,fontSize:12}},props.fileType?"No "+props.fileType+"s in this folder":"Empty"):
        files.map(function(f){
          var name=f.filename||f.file_path.split("/").pop();
          var src=fSrc(f.file_path);var vid=isVid(name);var img=isImg(name);var aud=isAud(name);
          return h("div",{key:f.id,style:{position:"relative",borderRadius:8,background:BG3,border:"2px solid "+BD,overflow:"hidden",cursor:"pointer",transition:"all .15s"},className:"vault-item"},
            h("div",{onClick:function(){setPvFile(f);},style:{width:"100%",aspectRatio:"3/4",background:BG1,display:"flex",alignItems:"center",justifyContent:"center",overflow:"hidden",position:"relative"}},
              img?h("img",{src:src,loading:"lazy",style:{width:"100%",height:"100%",objectFit:"cover"}}):
              vid?h("video",{src:src,muted:true,preload:"metadata",style:{width:"100%",height:"100%",objectFit:"cover"}}):
              h("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:4}},h(Ico,{name:"music",size:28,color:PU}),h("span",{style:{fontSize:9,color:TM}},"Audio")),
              vid?h("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"}},h("div",{style:{width:34,height:34,borderRadius:"50%",background:"rgba(0,0,0,.5)",display:"flex",alignItems:"center",justifyContent:"center",backdropFilter:"blur(4px)"}},h(Ico,{name:"video",size:14,color:"#fff"}))):null
            ),
            h("div",{onClick:function(e){e.stopPropagation();pick(f);},style:{position:"absolute",top:5,right:5,width:24,height:24,borderRadius:"50%",background:AC,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",opacity:0,transition:"opacity .15s",boxShadow:"0 2px 8px rgba(0,0,0,.4)"},className:"sel-cb"},h(Ico,{name:"check",size:12,color:"#fff"})),
            h("div",{style:{padding:"5px 8px",display:"flex",justifyContent:"space-between",alignItems:"center"}},
              h("div",{style:{fontSize:10,color:T2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1}},name.length>18?name.substring(0,16)+"…":name),
              f.source&&f.source!=="upload"?h("span",{style:{fontSize:8,color:AC,textTransform:"uppercase",fontWeight:700}},f.source):null
            )
          );
        }))
    )
  );
}

// ============================================
// Drop Zone with Vault
// ============================================
function Drop(props){
  var ref=useRef(null),ov=useState(false),over=ov[0],setOver=ov[1];
  var vs=useState(false),showV=vs[0],setShowV=vs[1];
  return h("div",null,
    h("div",{onClick:function(){ref.current&&ref.current.click();},onDragOver:function(e){e.preventDefault();setOver(true);},onDragLeave:function(){setOver(false);},onDrop:function(e){e.preventDefault();setOver(false);if(e.dataTransfer.files[0])props.onFile(e.dataTransfer.files[0]);},style:{border:"1.5px dashed "+(over?AC:props.preview?"rgba(34,197,94,0.4)":BD),borderRadius:12,padding:props.compact?12:20,textAlign:"center",cursor:"pointer",background:over?AD:props.preview?"rgba(34,197,94,0.04)":"transparent",transition:"all .2s"}},
      h("input",{ref:ref,type:"file",accept:props.accept,style:{display:"none"},onChange:function(e){if(e.target.files[0])props.onFile(e.target.files[0]);}}),
      props.preview?h("div",null,h(Ico,{name:"check",size:16,color:GR}),h("div",{style:{fontSize:11,fontWeight:500,color:GR,marginTop:4}},props.preview),h("div",{style:{fontSize:10,color:TM,marginTop:1}},"Click to replace")):
      h("div",null,h(Ico,{name:"upload",size:18,color:TM}),h("div",{style:{fontSize:12,fontWeight:500,color:T2,marginTop:5}},props.label))
    ),
    h("button",{onClick:function(){setShowV(true);},style:{width:"100%",marginTop:5,padding:"6px 0",borderRadius:7,fontSize:10,fontWeight:500,background:"transparent",border:"1px solid "+BD,color:TM,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:4,transition:"all .15s"},className:"btn-hover"},h(Ico,{name:"vault",size:11,color:TM}),"From Vault"),
    h(VaultPicker,{open:showV,onClose:function(){setShowV(false);},onSelect:function(f){if(props.onVaultSelect)props.onVaultSelect(f);},fileType:props.vaultType||null})
  );
}

// ============================================
// Steps
// ============================================
function Step1(props){
  var fs=useState(null),f=fs[0],setF=fs[1];var ls=useState(false),ld=ls[0],setLd=ls[1];var pn=useState(null),prevName=pn[0],setPrevName=pn[1];
var ads=useState(0),audioDur=ads[0],setAudioDur=ads[1];var vds=useState(0),videoDur=vds[0],setVideoDur=vds[1];
  var go=function(){if(!f)return;setLd(true);upld("/api/jobs/"+props.job.id+"/motion-video",f,"video").then(function(r){props.setJob(function(p){return Object.assign({},p,{motion_video_path:r.path,current_step:2});});props.toast("Video uploaded","success");props.advance();}).catch(function(e){props.toast(e.message,"error");}).finally(function(){setLd(false);});};
  var fromVault=function(vf){setLd(true);api("/api/jobs/"+props.job.id+"/set-vault-file",{method:"POST",body:JSON.stringify({step:"motion-video",filePath:vf.file_path})}).then(function(){props.setJob(function(p){return Object.assign({},p,{motion_video_path:vf.file_path,current_step:2});});props.toast("Video selected from vault","success");props.advance();}).catch(function(e){props.toast(e.message,"error");}).finally(function(){setLd(false);});};
  return h("div",null,
    h("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:14}},h(Ico,{name:"video",size:20,color:AC}),h("div",null,h("h3",{style:{fontSize:15,fontWeight:600,color:T1,margin:0}},"Source motion video"),h("p",{style:{fontSize:12,color:TM,margin:0}},"Upload reference video for pose & movement"))),
    h(Drop,{label:"Upload video (.mp4, .mov)",accept:"video/*",vaultType:"video",onFile:function(file){setF(file);setPrevName(file.name);},onVaultSelect:fromVault,preview:prevName}),
    f&&f.size?h("div",{style:{marginTop:10}},h("video",{src:URL.createObjectURL(f),controls:true,style:{width:"100%",maxHeight:220,borderRadius:10,border:"1px solid "+BD}})):null,
    f?h("div",{style:{marginTop:8}},h(Btn,{primary:true,onClick:go,loading:ld},h(Ico,{name:"upload",size:13})," Upload & continue")):null
  );
}

function Step2(props){
  var fs=useState(null),f=fs[0],setF=fs[1];var ls=useState(false),ld=ls[0],setLd=ls[1];var pn=useState(null),prevName=pn[0],setPrevName=pn[1];
var ads=useState(0),audioDur=ads[0],setAudioDur=ads[1];var vds=useState(0),videoDur=vds[0],setVideoDur=vds[1];
  var go=function(){if(!f)return;setLd(true);upld("/api/jobs/"+props.job.id+"/upload-frame",f,"frame").then(function(r){props.setJob(function(p){return Object.assign({},p,{frame_path:r.path,current_step:3});});props.toast("Frame saved","success");props.advance();}).catch(function(e){props.toast(e.message,"error");}).finally(function(){setLd(false);});};
  var fromVault=function(vf){setLd(true);api("/api/jobs/"+props.job.id+"/set-vault-file",{method:"POST",body:JSON.stringify({step:"frame",filePath:vf.file_path})}).then(function(){props.setJob(function(p){return Object.assign({},p,{frame_path:vf.file_path,current_step:3});});props.toast("Frame selected from vault","success");props.advance();}).catch(function(e){props.toast(e.message,"error");}).finally(function(){setLd(false);});};
  return h("div",null,
    h("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:14}},h(Ico,{name:"frame",size:20,color:AC}),h("div",null,h("h3",{style:{fontSize:15,fontWeight:600,color:T1,margin:0}},"Extract frame"),h("p",{style:{fontSize:12,color:TM,margin:0}},"Screenshot a clean frame from the video"))),
    h(Drop,{label:"Upload frame (.jpg, .png)",accept:"image/*",vaultType:"image",onFile:function(file){setF(file);setPrevName(file.name);},onVaultSelect:fromVault,preview:prevName}),
    f&&f.size?h("div",{style:{marginTop:10,textAlign:"center"}},h("img",{src:URL.createObjectURL(f),style:{maxHeight:200,borderRadius:10,border:"1px solid "+BD,maxWidth:"100%"}})):null,
    f?h("div",{style:{marginTop:8}},h(Btn,{primary:true,onClick:go,loading:ld},h(Ico,{name:"check",size:13})," Use this frame")):null
  );
}

function Step3(props){
  var rs=useState(null),rf=rs[0],setRf=rs[1];var vrs=useState(null),vaultRef=vrs[0],setVaultRef=vrs[1];var ps=useState(DPROMPT),prompt=ps[0],setPrompt=ps[1];
  var ls=useState(false),ld=ls[0],setLd=ls[1];var os=useState(null),out=os[0],setOut=os[1];
  var rss=useState([]),results=rss[0],setResults=rss[1];
  var rps=useState(""),refPrompt=rps[0],setRefPrompt=rps[1];
  var rls=useState(false),refLd=rls[0],setRefLd=rls[1];var gss=useState(""),genStatus=gss[0],setGenStatus=gss[1];
  var rfPrev=rf&&rf.size?URL.createObjectURL(rf):vaultRef?fSrc(vaultRef):null;
  var frameSrc=fSrc(props.job.frame_path);
  var callGen=function(rp,mdl){var b={prompt:prompt,referenceImagePath:rp};if(mdl)b.model=mdl;return api("/api/jobs/"+props.job.id+"/generate",{method:"POST",body:JSON.stringify(b)});};var is503=function(e){return e.message&&(e.message.indexOf("503")>=0||e.message.indexOf("UNAVAILABLE")>=0);};var callRefine=function(imgP,prm,mdl){var b={imagePath:imgP,prompt:prm};if(mdl)b.model=mdl;return api("/api/jobs/"+props.job.id+"/refine",{method:"POST",body:JSON.stringify(b)});};var doRefine=function(){if(!refPrompt.trim()||refLd)return;var lp=results[results.length-1].path;var prm=refPrompt.trim();setRefLd(true);setGenStatus("Refining with Flash...");callRefine(lp,prm,null).catch(function(e1){if(!is503(e1))throw e1;setGenStatus("Server overloaded \u2014 retrying in 30s...");return new Promise(function(r){setTimeout(r,30000);}).then(function(){setGenStatus("Retry #2 with Flash...");return callRefine(lp,prm,null);}).catch(function(e2){if(!is503(e2))throw e2;setGenStatus("Still busy \u2014 trying Pro model...");return callRefine(lp,prm,"gemini-3-pro-image-preview");});}).then(function(res){setGenStatus("");setResults(function(p){return p.concat([{path:res.path,label:"Refinement "+p.length,model:res.model}]);});setRefPrompt("");props.toast("Refined!","success");}).catch(function(e){setGenStatus("");props.toast(e.message,"error");}).finally(function(){setRefLd(false);});};var go=function(){if(!rf&&!vaultRef)return props.toast("Upload reference photo","error");setLd(true);setGenStatus("Uploading reference...");
    var refP=vaultRef?Promise.resolve({path:vaultRef}):upld("/api/models/default/references",rf,"image",{label:"ref"});refP.then(function(rr){
      setGenStatus("Generating with Flash...");return callGen(rr.path,null).catch(function(e1){if(!is503(e1))throw e1;setGenStatus("Server overloaded \u2014 retrying in 30s...");return new Promise(function(r){setTimeout(r,30000);}).then(function(){setGenStatus("Retry #2 with Flash...");return callGen(rr.path,null);}).catch(function(e2){if(!is503(e2))throw e2;setGenStatus("Still busy \u2014 trying Pro model...");return callGen(rr.path,"gemini-3-pro-image-preview");});});
    }).then(function(res){props.setJob(function(p){return Object.assign({},p,{generated_image_path:res.path,current_step:4});});setGenStatus("");setOut(res.path);setResults([{path:res.path,label:"Generation 1"}]);setRefPrompt("");props.toast("Generated!","success");}).catch(function(e){setGenStatus("");props.toast(e.message,"error");}).finally(function(){setLd(false);});
  };
  return h("div",null,
    h("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:14}},h(Ico,{name:"sparkle",size:20,color:AC}),h("div",null,h("h3",{style:{fontSize:15,fontWeight:600,color:T1,margin:0}},"Generate with Gemini"),h("p",{style:{fontSize:12,color:TM,margin:0}},"Upload model reference + swap"))),
    h("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10,marginBottom:12}},
      h("div",{style:{borderRadius:10,background:BG3,border:"1px solid "+BD,overflow:"hidden"}},
        h("div",{style:{padding:"7px 10px",borderBottom:"1px solid "+BD,fontSize:10,fontWeight:600,color:TM,textTransform:"uppercase",letterSpacing:.5,display:"flex",alignItems:"center",gap:4}},h(Ico,{name:"frame",size:11,color:TM}),"Frame"),
        h("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",aspectRatio:"3/4",overflow:"hidden"}},
          frameSrc?h("img",{src:frameSrc,style:{width:"100%",height:"100%",objectFit:"cover"}}):h("span",{style:{fontSize:11,color:TM}},"No frame"))
      ),
      h("div",{style:{borderRadius:10,background:BG3,border:"1px solid "+BD,overflow:"hidden"}},
        h("div",{style:{padding:"7px 10px",borderBottom:"1px solid "+BD,fontSize:10,fontWeight:600,color:TM,textTransform:"uppercase",letterSpacing:.5,display:"flex",alignItems:"center",gap:4}},h(Ico,{name:"image",size:11,color:TM}),"Model ref"),
        rfPrev?h("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",aspectRatio:"3/4",overflow:"hidden",position:"relative"}},
          h("img",{src:rfPrev,style:{width:"100%",height:"100%",objectFit:"cover"}}),
          h("button",{onClick:function(){setRf(null);setVaultRef(null);},style:{position:"absolute",top:6,right:6,width:22,height:22,borderRadius:6,background:"rgba(0,0,0,.6)",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"}},h(Ico,{name:"x",size:12,color:"#fff"}))
        ):
        h("div",{style:{padding:8}},h(Drop,{label:"Model photo",accept:"image/*",compact:true,vaultType:"image",onFile:function(f){setRf(f);setVaultRef(null);},onVaultSelect:function(vf){setVaultRef(vf.file_path);setRf(null);}}))
      )
    ),
    h("div",{style:{marginBottom:8}},h("label",{style:{fontSize:11,color:T2,marginBottom:4,display:"block"}},"Prompt"),h("textarea",{value:prompt,onChange:function(e){setPrompt(e.target.value);},rows:3,style:{width:"100%",padding:"10px 12px",borderRadius:8,fontSize:12,background:BG3,border:"1px solid "+BD,color:T1,outline:"none",resize:"vertical",fontFamily:"inherit",lineHeight:1.5,boxSizing:"border-box"}})),
    h("div",{style:{display:"flex",gap:4,flexWrap:"wrap",marginBottom:10}},["Keep my hair color.","Remove text overlay.","Keep accessories.","Remove accessories.","Replace accessories with different ones."].map(function(t){return h("button",{key:t,onClick:function(){setPrompt(function(p){return p+" "+t;});},style:{fontSize:10,padding:"3px 8px",borderRadius:6,background:BG3,border:"1px solid "+BD,color:TM,cursor:"pointer"},className:"btn-hover"},t);})),
    h("div",{style:{display:"flex",gap:8,alignItems:"center"}},h(Btn,{primary:true,onClick:go,loading:ld,disabled:!rf&&!vaultRef},h(Ico,{name:"sparkle",size:13})," Generate"),ld?h("div",{style:{marginTop:8,padding:"8px 12px",borderRadius:8,background:BG3,border:"1px solid "+(genStatus.indexOf("busy")>=0||genStatus.indexOf("Retry")>=0?"rgba(234,179,8,0.2)":genStatus.indexOf("Pro")>=0?"rgba(168,85,247,0.2)":BD),display:"flex",alignItems:"center",gap:8}},h(Spinner,{s:12,c:genStatus.indexOf("busy")>=0||genStatus.indexOf("Retry")>=0?YL:genStatus.indexOf("Pro")>=0?PU:AC}),h("span",{style:{fontSize:11,color:genStatus.indexOf("busy")>=0||genStatus.indexOf("Retry")>=0?YL:genStatus.indexOf("Pro")>=0?PU:T2}},genStatus||"Generating...")):null),
    results.length>0?h("div",{style:{marginTop:14}},
      h("div",{style:{padding:"10px 14px",marginBottom:10,borderRadius:10,background:BG3,border:"1px solid "+BD}},
        h("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:8}},h(Ico,{name:"sparkle",size:14,color:PU}),h("span",{style:{fontSize:12,fontWeight:600,color:T1}},"Refine with Gemini"),refLd?h(Spinner,{s:12,c:PU}):null),
        h("div",{style:{display:"flex",gap:6}},
          h("input",{value:refPrompt,onChange:function(e){setRefPrompt(e.target.value);},onKeyDown:function(e){if(e.key==="Enter"&&refPrompt.trim()&&!refLd)doRefine();},placeholder:"e.g. Close my mouth, keep expressions neutral",style:{flex:1,padding:"8px 12px",borderRadius:7,fontSize:12,background:BG2,border:"1px solid "+BD,color:T1,outline:"none",fontFamily:"inherit"}}),
          h(Btn,{onClick:doRefine,loading:refLd,disabled:!refPrompt.trim(),sx:{padding:"8px 14px",fontSize:11}},h(Ico,{name:"sparkle",size:12})," Refine")),
        h("div",{style:{display:"flex",gap:4,flexWrap:"wrap",marginTop:6}},["Close my mouth.","Make expression neutral.","Fix my hands.","Make lighting warmer."].map(function(t){return h("button",{key:t,onClick:function(){setRefPrompt(t);},style:{fontSize:9,padding:"2px 7px",borderRadius:5,background:BG2,border:"1px solid "+BD,color:TM,cursor:"pointer"},className:"btn-hover"},t);}))),
      results.map(function(r,i){var isActive=r.path===out;return h("div",{key:i,style:{marginBottom:8,borderRadius:12,background:isActive?"rgba(34,197,94,0.04)":"rgba(255,255,255,0.02)",border:"1px solid "+(isActive?"rgba(34,197,94,0.2)":BD),overflow:"hidden"}},
        h("div",{style:{padding:"8px 14px",borderBottom:"1px solid "+(isActive?"rgba(34,197,94,0.1)":BD),display:"flex",justifyContent:"space-between",alignItems:"center"}},
          h("span",{style:{fontSize:12,fontWeight:600,color:isActive?GR:T2,display:"flex",alignItems:"center",gap:5}},isActive?h(Ico,{name:"check",size:14,color:GR}):h("span",{style:{width:14,height:14,borderRadius:"50%",border:"2px solid "+TM,display:"inline-flex"}}),r.label,r.model?h("span",{style:{fontSize:9,color:PU,fontWeight:500,marginLeft:4,padding:"1px 5px",borderRadius:3,background:"rgba(168,85,247,0.1)"}},r.model.replace("gemini-","").replace("-image-preview","").replace("-image","")):null,isActive?h("span",{style:{fontSize:9,color:GR,fontWeight:700,marginLeft:4}},"ACTIVE"):null),
          h("div",{style:{display:"flex",gap:4}},
            !isActive?h("button",{onClick:function(){setOut(r.path);props.setJob(function(p){return Object.assign({},p,{generated_image_path:r.path});});props.toast("Using "+r.label,"success");},style:{fontSize:10,padding:"4px 10px",borderRadius:5,background:AD,border:"1px solid "+AB,color:AC,cursor:"pointer",fontWeight:600},className:"btn-hover"},"Use this"):null,
            h("a",{href:fSrc(r.path),download:true,style:{fontSize:10,color:TM,textDecoration:"none",display:"flex",alignItems:"center",gap:3,padding:"4px 8px",borderRadius:5,border:"1px solid "+BD},className:"btn-hover"},h(Ico,{name:"download",size:11,color:TM}),"Save"))),
        h("div",{style:{padding:10,textAlign:"center"}},h("img",{src:fSrc(r.path),style:{maxHeight:280,borderRadius:8,maxWidth:"100%"}}))
      );})
    ):null
  );
}

function Step4(props){var ls=useState(false),ld=ls[0],setLd=ls[1];var ps=useState(false),poll=ps[0],setPoll=ps[1];var ss=useState(null),st=ss[0],setSt=ss[1];var ref=useRef(null);
var imagePath=props.job.clean_image_path||props.job.generated_image_path;
var go=function(){setLd(true);api("/api/jobs/"+props.job.id+"/motion-control",{method:"POST",body:JSON.stringify({modelName:"kling-v3",characterOrientation:"video",mode:"pro"})}).then(function(r){props.setJob(function(p){return Object.assign({},p,{kling_task_id:r.taskId});});setSt({status:"submitted"});props.toast("Motion started","success");startPoll();}).catch(function(e){props.toast(e.message,"error");}).finally(function(){setLd(false);});};
var startPoll=function(){setPoll(true);ref.current=setInterval(function(){api("/api/jobs/"+props.job.id+"/motion-status").then(function(r){setSt(r);if(r.status==="succeed"){clearInterval(ref.current);setPoll(false);props.setJob(function(p){return Object.assign({},p,{motion_output_path:r.localPath,current_step:5});});props.toast("Motion ready!","success");}else if(r.status==="failed"){clearInterval(ref.current);setPoll(false);props.toast("Failed: "+(r.statusMsg||""),"error");}}).catch(function(){});},10000);};
useEffect(function(){return function(){if(ref.current)clearInterval(ref.current);};},{});
return h("div",null,
  h("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:14}},h(Ico,{name:"motion",size:20,color:AC}),h("div",null,h("h3",{style:{fontSize:15,fontWeight:600,color:T1,margin:0}},"Motion control"),h("p",{style:{fontSize:12,color:TM,margin:0}},"Kling V3 · Pro · Match video"))),
  imagePath?h("div",{style:{marginBottom:12,textAlign:"center"}},h("img",{src:fSrc(imagePath),style:{maxHeight:150,borderRadius:8,border:"1px solid "+BD}})):null,
  !poll&&!(st&&st.localPath)?h(Btn,{primary:true,onClick:go,loading:ld,disabled:!imagePath||!props.job.motion_video_path},h(Ico,{name:"motion",size:13})," Generate motion video"):null,
  poll?h("div",{style:{padding:14,borderRadius:10,background:"rgba(234,179,8,0.06)",border:"1px solid rgba(234,179,8,0.15)",display:"flex",alignItems:"center",gap:10}},h(Spinner,{s:16,c:YL}),h("div",null,h("div",{style:{fontSize:12,fontWeight:600,color:YL}},"Processing — "+(st?st.status:"")),h("div",{style:{fontSize:11,color:TM}},"Polling every 10s"))):null,
  st&&st.localPath?h("div",{style:{marginTop:12,borderRadius:12,background:"rgba(34,197,94,0.04)",border:"1px solid rgba(34,197,94,0.15)",overflow:"hidden"}},
    h("div",{style:{padding:"8px 14px",borderBottom:"1px solid rgba(34,197,94,0.1)",display:"flex",justifyContent:"space-between"}},h("span",{style:{fontSize:12,fontWeight:600,color:GR,display:"flex",alignItems:"center",gap:5}},h(Ico,{name:"check",size:14,color:GR}),"Ready"),h("a",{href:"/files/motion-outputs/"+st.localPath.split("/").pop(),download:true,style:{fontSize:10,color:AC,textDecoration:"none",display:"flex",alignItems:"center",gap:3,padding:"4px 8px",borderRadius:5,border:"1px solid "+AB}},h(Ico,{name:"download",size:12,color:AC}),"Download")),
    h("div",{style:{padding:12}},h("video",{src:"/files/motion-outputs/"+st.localPath.split("/").pop(),controls:true,style:{width:"100%",maxHeight:280,borderRadius:8}}))):null);}

function Step5(props){var afs=useState(null),af=afs[0],setAf=afs[1];var sms=useState("cut_off"),sm=sms[0],setSm=sms[1];var ls=useState(false),ld=ls[0],setLd=ls[1];var ps=useState(false),poll=ps[0],setPoll=ps[1];var ss=useState(null),st=ss[0],setSt=ss[1];var ref=useRef(null);var pn=useState(null),prevName=pn[0],setPrevName=pn[1];
var ads=useState(0),audioDur=ads[0],setAudioDur=ads[1];var vds=useState(0),videoDur=vds[0],setVideoDur=vds[1];
var fromVault=function(vf){api("/api/jobs/"+props.job.id+"/set-vault-file",{method:"POST",body:JSON.stringify({step:"audio",filePath:vf.file_path})}).then(function(){props.setJob(function(p){return Object.assign({},p,{audio_path:vf.file_path});});setPrevName(vf.filename||"vault audio");props.toast("Audio selected","success");var a=new Audio();a.src=fSrc(vf.file_path);a.onloadedmetadata=function(){if(a.duration&&isFinite(a.duration))setAudioDur(a.duration);};}).catch(function(e){props.toast(e.message,"error");});};
var go=function(){if(!af&&!props.job.audio_path)return props.toast("Upload audio","error");setLd(true);var p=af&&af.size?upld("/api/jobs/"+props.job.id+"/upload-audio",af,"audio"):Promise.resolve();p.then(function(){return api("/api/jobs/"+props.job.id);}).then(function(fj){return api("/api/jobs/"+props.job.id+"/lip-sync",{method:"POST",body:JSON.stringify({model:"lipsync-2-pro",syncMode:sm,audioPath:fj.audio_path})});}).then(function(){setSt({status:"PENDING"});props.toast("Lip sync started","success");startPoll();}).catch(function(e){props.toast(e.message,"error");}).finally(function(){setLd(false);});};
var startPoll=function(){setPoll(true);ref.current=setInterval(function(){api("/api/jobs/"+props.job.id+"/sync-status").then(function(r){setSt(r);if(r.status==="COMPLETED"){clearInterval(ref.current);setPoll(false);props.setJob(function(p){return Object.assign({},p,{final_video_path:r.localPath,status:"completed"});});props.toast("Final video ready!","success");}else if(r.status==="FAILED"||r.status==="REJECTED"){clearInterval(ref.current);setPoll(false);props.toast("Failed: "+(r.error||""),"error");}}).catch(function(){});},5000);};
useEffect(function(){return function(){if(ref.current)clearInterval(ref.current);};},{});
useEffect(function(){if(props.job.motion_output_path){var v=document.createElement("video");v.preload="metadata";v.onloadedmetadata=function(){if(v.duration&&isFinite(v.duration))setVideoDur(v.duration);};v.src=fSrc(props.job.motion_output_path);}return function(){};},[props.job.motion_output_path]);
useEffect(function(){if(audioDur>0&&videoDur>0){if(videoDur>audioDur+0.5)setSm("cut_off");else if(audioDur>videoDur+0.5)setSm("remap");else setSm("cut_off");}return function(){};},[audioDur,videoDur]);
var modes=[{id:"cut_off",l:"Cut off",d:"Trim if video longer"},{id:"remap",l:"Remap",d:"Slow if audio longer"},{id:"silence",l:"Silence",d:"Pad with silence"}];
return h("div",null,
  h("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:14}},h(Ico,{name:"mic",size:20,color:AC}),h("div",null,h("h3",{style:{fontSize:15,fontWeight:600,color:T1,margin:0}},"Lip sync"),h("p",{style:{fontSize:12,color:TM,margin:0}},"Sync voice audio to motion video"))),
  h(Drop,{label:"Upload voice (.wav, .mp3)",accept:"audio/*",vaultType:"audio",onFile:function(file){setAf(file);setPrevName(file.name);var a=new Audio();a.src=URL.createObjectURL(file);a.onloadedmetadata=function(){if(a.duration&&isFinite(a.duration))setAudioDur(a.duration);};},onVaultSelect:fromVault,preview:prevName||props.job.audio_path?"Audio loaded":null}),
  h("div",{style:{marginTop:12,marginBottom:14}},h("label",{style:{fontSize:11,color:T2,marginBottom:6,display:"flex",alignItems:"center",gap:8}},"Sync mode",audioDur>0||videoDur>0?h("span",{style:{fontSize:10,color:TM,fontWeight:400}},(videoDur>0?"Video: "+videoDur.toFixed(1)+"s":"")+(audioDur>0&&videoDur>0?" · ":"")+(audioDur>0?"Audio: "+audioDur.toFixed(1)+"s":"")):null,audioDur>0&&videoDur>0?h("span",{style:{fontSize:9,fontWeight:600,color:AC,padding:"1px 6px",borderRadius:4,background:AD}},"auto"):null),h("div",{style:{display:"flex",gap:6}},modes.map(function(m){return h("button",{key:m.id,onClick:function(){setSm(m.id);},style:{flex:1,padding:"10px 12px",borderRadius:8,textAlign:"left",background:sm===m.id?AD:BG3,border:"1px solid "+(sm===m.id?AB:BD),cursor:"pointer",transition:"all .15s"}},h("div",{style:{fontSize:12,fontWeight:600,color:sm===m.id?AC:T2}},m.l),h("div",{style:{fontSize:10,color:TM,marginTop:2}},m.d));}))),
  !poll&&!(st&&st.localPath)?h(Btn,{primary:true,onClick:go,loading:ld,disabled:!props.job.motion_output_path||(!af&&!prevName&&!props.job.audio_path)},h(Ico,{name:"mic",size:13})," Sync and generate"):null,
  poll?h("div",{style:{padding:14,borderRadius:10,background:"rgba(236,72,153,0.06)",border:"1px solid rgba(236,72,153,0.15)",display:"flex",alignItems:"center",gap:10}},h(Spinner,{s:16,c:PK}),h("div",null,h("div",{style:{fontSize:12,fontWeight:600,color:PK}},"Syncing — "+(st?st.status:"")),h("div",{style:{fontSize:11,color:TM}},"Polling every 5s"))):null,
  st&&st.localPath?h("div",{style:{marginTop:12,borderRadius:12,background:"rgba(34,197,94,0.06)",border:"1px solid rgba(34,197,94,0.2)",overflow:"hidden"}},
    h("div",{style:{padding:"10px 14px",borderBottom:"1px solid rgba(34,197,94,0.1)",display:"flex",justifyContent:"space-between"}},h("span",{style:{fontSize:13,fontWeight:700,color:GR,display:"flex",alignItems:"center",gap:6}},h(Ico,{name:"check",size:16,color:GR}),"Final video!"),h("a",{href:"/files/final-videos/"+st.localPath.split("/").pop(),download:true,style:{fontSize:11,color:AC,textDecoration:"none",display:"flex",alignItems:"center",gap:4,padding:"5px 10px",borderRadius:6,background:AD,border:"1px solid "+AB,fontWeight:600}},h(Ico,{name:"download",size:13,color:AC}),"Download")),
    h("div",{style:{padding:12}},h("video",{src:"/files/final-videos/"+st.localPath.split("/").pop(),controls:true,style:{width:"100%",maxHeight:320,borderRadius:8}}))):null);}

// ============================================
// Vault Page
// ============================================
function VaultPage(props){
  var fds=useState([]),folders=fds[0],setFolders=fds[1];var fs=useState([]),files=fs[0],setFiles=fs[1];
  var cs=useState("all"),cur=cs[0],setCur=cs[1];var ns=useState(""),nn=ns[0],setNn=ns[1];
  var ss=useState(false),showNew=ss[0],setShowNew=ss[1];var ref=useRef(null);
  var lbs=useState(null),lbFile=lbs[0],setLbFile=lbs[1];var lbi=useState(0),lbIdx=lbi[0],setLbIdx=lbi[1];
  var sels=useState({}),selected=sels[0],setSelected=sels[1];
  var selCount=Object.keys(selected).length;
  var toggleSel=function(id,e){e.stopPropagation();setSelected(function(p){var n=Object.assign({},p);if(n[id])delete n[id];else n[id]=true;return n;});};
  var clearSel=function(){setSelected({});};var mds=useState(false),showMoveDrop=mds[0],setShowMoveDrop=mds[1];
  var batchDel=function(){if(!confirm("Delete "+selCount+" files?"))return;api("/api/vault/batch-delete",{method:"POST",body:JSON.stringify({ids:Object.keys(selected)})}).then(function(){clearSel();load();props.toast(selCount+" deleted","success");}).catch(function(e){props.toast(e.message,"error");});};
  var batchMove=function(fid){var realFid=fid==="__root__"?"":fid;api("/api/vault/batch-move",{method:"POST",body:JSON.stringify({ids:Object.keys(selected),folderId:realFid})}).then(function(){clearSel();load();props.toast(selCount+" moved","success");}).catch(function(e){props.toast(e.message,"error");});};
  var load=useCallback(function(){api("/api/vault/folders").then(setFolders).catch(function(){setFolders([]);});api("/api/vault/files?folder="+(cur==="all"?"":cur)).then(setFiles).catch(function(){setFiles([]);});},[cur]);
  useEffect(function(){load();},[load]);
  var createFolder=function(){if(!nn.trim())return;api("/api/vault/folders",{method:"POST",body:JSON.stringify({name:nn.trim()})}).then(function(){load();setNn("");setShowNew(false);props.toast("Folder created","success");}).catch(function(e){props.toast(e.message,"error");});};
  var handleUpload=function(e){var file=e.target.files[0];if(!file)return;upld("/api/vault/upload",file,"file",{folder:cur==="all"?"":cur}).then(function(){load();props.toast("Uploaded","success");}).catch(function(e){props.toast(e.message,"error");});};
  var deleteFile=function(id,e){e.stopPropagation();if(!confirm("Delete this file?"))return;api("/api/vault/files/"+id,{method:"DELETE"}).then(function(){load();props.toast("Deleted","success");}).catch(function(e){props.toast(e.message,"error");});};
  var openLb=function(f,i){setLbFile(f);setLbIdx(i);};
  var navLb=function(dir){var ni=lbIdx+dir;if(ni>=0&&ni<files.length){setLbFile(files[ni]);setLbIdx(ni);}};
  return h("div",null,
    h("input",{ref:ref,type:"file",multiple:true,style:{display:"none"},onChange:handleUpload,accept:"*/*"}),
    h(Lightbox,{file:lbFile,onClose:function(){setLbFile(null);},onPrev:lbIdx>0?function(){navLb(-1);}:null,onNext:lbIdx<files.length-1?function(){navLb(1);}:null}),
    h("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:18}},
      h("div",{style:{display:"flex",alignItems:"center",gap:8}},h(Ico,{name:"vault",size:22,color:AC}),h("h2",{style:{fontSize:20,fontWeight:700,color:T1,margin:0}},"Vault")),
      h("div",{style:{display:"flex",gap:6}},h(Btn,{onClick:function(){setShowNew(!showNew);},sx:{padding:"7px 12px",fontSize:11}},h(Ico,{name:"folder",size:13})," New folder"),h(Btn,{primary:true,onClick:function(){ref.current&&ref.current.click();},sx:{padding:"7px 12px",fontSize:11}},h(Ico,{name:"upload",size:13})," Upload"))),
    showNew?h("div",{style:{display:"flex",gap:6,marginBottom:12}},h("input",{value:nn,onChange:function(e){setNn(e.target.value);},onKeyDown:function(e){if(e.key==="Enter")createFolder();},placeholder:"Folder name...",style:{flex:1,padding:"8px 12px",borderRadius:8,fontSize:12,background:BG3,border:"1px solid "+BD,color:T1,outline:"none"}}),h(Btn,{primary:true,onClick:createFolder,sx:{padding:"7px 12px"}},h(Ico,{name:"check",size:13}))):null,
    h("div",{style:{display:"flex",gap:4,marginBottom:16,overflowX:"auto",paddingBottom:4}},
      h("button",{onClick:function(){setCur("all");},style:{padding:"7px 14px",borderRadius:8,fontSize:11,fontWeight:600,background:cur==="all"?AD:"transparent",border:"1px solid "+(cur==="all"?AB:BD),color:cur==="all"?AC:TM,cursor:"pointer",display:"flex",alignItems:"center",gap:5,whiteSpace:"nowrap"},className:"btn-hover"},h(Ico,{name:"vault",size:13,color:cur==="all"?AC:TM}),"All"),
      folders.map(function(f){return h("button",{key:f.id,onClick:function(){setCur(f.id);},style:{padding:"7px 14px",borderRadius:8,fontSize:11,fontWeight:500,background:cur===f.id?AD:"transparent",border:"1px solid "+(cur===f.id?AB:BD),color:cur===f.id?AC:TM,cursor:"pointer",display:"flex",alignItems:"center",gap:5,whiteSpace:"nowrap"},className:"btn-hover"},h(Ico,{name:"folder",size:13,color:cur===f.id?AC:TM}),f.name);})),
    selCount>0?h("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:12,padding:"10px 14px",borderRadius:10,background:AD,border:"1px solid "+AB}},
      h("span",{style:{fontSize:12,fontWeight:600,color:AC}},selCount+" selected"),
      h("div",{style:{flex:1}}),
      h("div",{style:{position:"relative"}},
        h("button",{onClick:function(){setShowMoveDrop(!showMoveDrop);},style:{padding:"6px 14px",borderRadius:6,fontSize:12,fontWeight:500,background:BG3,border:"1px solid "+(showMoveDrop?AB:BD),color:showMoveDrop?AC:T2,cursor:"pointer",display:"flex",alignItems:"center",gap:6,transition:"all .15s"}},h(Ico,{name:"folder",size:13,color:showMoveDrop?AC:TM}),"Move to",h("span",{style:{fontSize:9,marginLeft:2,opacity:.5}},showMoveDrop?"▲":"▼")),
        showMoveDrop?h("div",{style:{position:"absolute",top:"100%",left:0,marginTop:4,minWidth:180,background:BG2,border:"1px solid "+BDH,borderRadius:10,overflow:"hidden",zIndex:50,boxShadow:"0 12px 40px rgba(0,0,0,.6)",animation:"fadeIn .12s"}},
          h("div",{style:{padding:"6px 8px",borderBottom:"1px solid "+BD}},h("div",{style:{fontSize:10,fontWeight:600,color:TM,textTransform:"uppercase",letterSpacing:.5,padding:"4px 6px"}},"Choose folder")),
          h("button",{onClick:function(){batchMove("__root__");setShowMoveDrop(false);},style:{width:"100%",padding:"9px 14px",background:"transparent",border:"none",color:T2,fontSize:12,cursor:"pointer",textAlign:"left",display:"flex",alignItems:"center",gap:8,transition:"background .1s"},onMouseOver:function(e){e.currentTarget.style.background=AD;},onMouseOut:function(e){e.currentTarget.style.background="transparent";}},h(Ico,{name:"vault",size:14,color:TM}),"Unfiled"),
          folders.map(function(fo){return h("button",{key:fo.id,onClick:function(){batchMove(fo.id);setShowMoveDrop(false);},style:{width:"100%",padding:"9px 14px",background:"transparent",border:"none",color:T1,fontSize:12,cursor:"pointer",textAlign:"left",display:"flex",alignItems:"center",gap:8,transition:"background .1s"},onMouseOver:function(e){e.currentTarget.style.background=AD;},onMouseOut:function(e){e.currentTarget.style.background="transparent";}},h(Ico,{name:"folder",size:14,color:AC}),fo.name);})
        ):null),
      h("button",{onClick:batchDel,style:{padding:"6px 12px",borderRadius:6,fontSize:11,fontWeight:600,background:"rgba(239,68,68,0.15)",border:"1px solid rgba(239,68,68,0.3)",color:RD,cursor:"pointer",display:"flex",alignItems:"center",gap:4}},h(Ico,{name:"trash",size:12,color:RD}),"Delete"),
      h("button",{onClick:clearSel,style:{padding:"6px 10px",borderRadius:6,fontSize:11,background:"transparent",border:"1px solid "+BD,color:TM,cursor:"pointer"}},"Clear")
    ):null,
    files.length===0?h("div",{style:{padding:60,textAlign:"center"}},h(Ico,{name:"vault",size:36,color:TM}),h("div",{style:{fontSize:13,color:TM,marginTop:10}},"Empty")):
    h("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(160px,1fr))",gap:10}},
      files.map(function(f,idx){
        var name=f.filename||f.file_path.split("/").pop();
        var src=fSrc(f.file_path);var img=isImg(name);var vid=isVid(name);var aud=isAud(name);
        var shortName=name.length>22?name.substring(0,20)+"…":name;
        return h("div",{key:f.id,onClick:function(){openLb(f,idx);},style:{borderRadius:10,background:BGC,border:"1px solid "+BD,overflow:"hidden",cursor:"pointer",transition:"all .15s"},className:"vault-item"},
          h("div",{style:{width:"100%",aspectRatio:"3/4",background:BG1,display:"flex",alignItems:"center",justifyContent:"center",overflow:"hidden",position:"relative"}},
            img?h("img",{src:src,loading:"lazy",style:{width:"100%",height:"100%",objectFit:"cover"}}):
            vid?h("video",{src:src,muted:true,preload:"metadata",style:{width:"100%",height:"100%",objectFit:"cover"},onMouseOver:function(e){try{e.target.play();}catch(x){}},onMouseOut:function(e){try{e.target.pause();e.target.currentTime=0;}catch(x){}}}):
            h("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:6}},h(Ico,{name:aud?"music":"image",size:30,color:aud?PU:TM}),h("span",{style:{fontSize:10,color:TM}},aud?"Audio":"File")),
            h("div",{onClick:function(e){toggleSel(f.id,e);},style:{position:"absolute",top:6,left:6,width:22,height:22,borderRadius:"50%",border:"2px solid "+(selected[f.id]?AC:"rgba(255,255,255,0.4)"),background:selected[f.id]?AC:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",zIndex:2,transition:"all .15s",opacity:selected[f.id]?1:0,backdropFilter:"blur(4px)"},className:"sel-cb"},selected[f.id]?h(Ico,{name:"check",size:12,color:"#fff"}):null),
            h("div",{style:{position:"absolute",top:0,right:0,display:"flex",gap:2,padding:5,opacity:0,transition:"opacity .15s"},className:"dl-btn"},
              h("a",{href:src,download:true,onClick:function(e){e.stopPropagation();},style:{width:26,height:26,borderRadius:6,background:"rgba(0,0,0,.65)",display:"flex",alignItems:"center",justifyContent:"center"}},h(Ico,{name:"download",size:12,color:"#fff"})),
              h("button",{onClick:function(e){deleteFile(f.id,e);},style:{width:26,height:26,borderRadius:6,background:"rgba(239,68,68,.7)",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"}},h(Ico,{name:"trash",size:12,color:"#fff"}))
            ),
            vid?h("div",{style:{position:"absolute",bottom:6,left:6,padding:"2px 6px",borderRadius:4,background:"rgba(0,0,0,.6)",fontSize:9,color:"#fff",display:"flex",alignItems:"center",gap:3}},h(Ico,{name:"video",size:10,color:"#fff"}),"Video"):null
          ),
          h("div",{style:{padding:"8px 10px"}},
            h("div",{style:{fontSize:11,fontWeight:500,color:T1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginBottom:2}},shortName),
            h("div",{style:{display:"flex",justifyContent:"space-between"}},
              h("span",{style:{fontSize:10,color:TM}},new Date(f.created_at).toLocaleDateString()),
              f.source&&f.source!=="upload"?h("span",{style:{fontSize:9,color:AC,textTransform:"uppercase",fontWeight:600}},f.source):null
            )
          )
        );
      })
    )
  );
}

// Costs
function CostsPage(){var ds=useState(null),d=ds[0],setD=ds[1];useEffect(function(){api("/api/costs").then(setD).catch(function(){});},[]);var data=d&&d.summary?d.summary:[],total=0,tc=0;data.forEach(function(x){total+=x.total_cost||0;tc+=x.calls||0;});var colors={gemini:PU,grok:GR,kling:YL,sync:PK};
return h("div",null,h("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:20}},h(Ico,{name:"costs",size:22,color:AC}),h("h2",{style:{fontSize:20,fontWeight:700,color:T1,margin:0}},"Cost tracking")),
data.length===0?h("div",{style:{padding:60,textAlign:"center"}},h(Ico,{name:"costs",size:36,color:TM}),h("div",{style:{fontSize:13,color:TM,marginTop:10}},"No API calls yet")):
h("div",null,h("div",{style:{display:"grid",gridTemplateColumns:"repeat("+Math.min(data.length,4)+",1fr)",gap:10,marginBottom:16}},data.map(function(x){return h("div",{key:x.api,style:{padding:16,borderRadius:10,background:BGC,border:"1px solid "+BD}},h("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:8}},h("div",{style:{width:8,height:8,borderRadius:"50%",background:colors[x.api]||AC}}),h("span",{style:{fontSize:11,color:T2,fontWeight:500,textTransform:"capitalize"}},x.api)),h("div",{style:{fontSize:22,fontWeight:700,color:T1}},"$"+(x.total_cost||0).toFixed(3)),h("div",{style:{fontSize:10,color:TM,marginTop:2}},x.calls+" calls"));})),
h("div",{style:{padding:18,borderRadius:12,background:"linear-gradient(135deg,rgba(14,165,233,0.06),rgba(14,165,233,0.01))",border:"1px solid "+AB}},h("div",{style:{fontSize:11,color:AC,fontWeight:600,letterSpacing:.4}},"TOTAL SPEND"),h("div",{style:{fontSize:30,fontWeight:700,color:T1,marginTop:4}},"$"+total.toFixed(3)),h("div",{style:{fontSize:11,color:TM,marginTop:4}},tc+" total calls"))));}

// ============================================
// Main
// ============================================
window.AIStudio=function(){
var pgs=useState("pipeline"),pg=pgs[0],setPg=pgs[1];var sts=useState(1),step=sts[0],setStep=sts[1];var js=useState(null),job=js[0],setJob=js[1];
var tms=useState(null),tmsg=tms[0],setTmsg=tms[1];var tts=useState("info"),ttype=tts[0],setTtype=tts[1];
var toast=function(m,t){setTmsg(m);setTtype(t||"info");setTimeout(function(){setTmsg(null);},4000);};
var advance=function(){setStep(function(s){return Math.min(5,s+1);});};
var newJob=function(){api("/api/jobs",{method:"POST",body:JSON.stringify({modelId:"default"})}).then(function(j){setJob(j);setStep(1);toast("Pipeline started","success");}).catch(function(e){toast(e.message,"error");});};
var stepProps={job:job,setJob:setJob,toast:toast,advance:advance};
var nav=[["pipeline","Pipeline","pipeline"],["vault","Vault","vault"],["costs","Costs","costs"]];
return h("div",{style:{display:"flex",height:"100vh",background:BG0,color:T1,fontFamily:"'Inter','SF Pro Display',system-ui,-apple-system,sans-serif",overflow:"hidden"}},
h("style",null,"@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');@keyframes spin{to{transform:rotate(360deg)}}@keyframes fadeIn{from{opacity:0}to{opacity:1}}@keyframes slideIn{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}*{margin:0;padding:0;box-sizing:border-box}::-webkit-scrollbar{width:4px}::-webkit-scrollbar-thumb{background:rgba(255,255,255,0.08);border-radius:2px}.btn-hover:hover:not(:disabled){filter:brightness(1.15);border-color:"+BDH+"!important}.vault-item:hover{border-color:"+BDH+"!important;transform:translateY(-1px)}.vault-item:hover .dl-btn{opacity:1!important}.vault-item:hover .sel-cb{opacity:1!important}"),
h(Toast,{msg:tmsg,type:ttype,onClose:function(){setTmsg(null);}}),
// Sidebar
h("div",{style:{width:180,background:BG1,borderRight:"1px solid "+BD,display:"flex",flexDirection:"column",flexShrink:0}},
  h("div",{style:{padding:"16px 14px",borderBottom:"1px solid "+BD,display:"flex",alignItems:"center",gap:8}},h("div",{style:{width:28,height:28,borderRadius:8,background:"linear-gradient(135deg,"+AC+",#6366F1)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:11,fontWeight:800,color:"#fff"}},"AI"),h("div",null,h("div",{style:{fontSize:13,fontWeight:700,color:T1,letterSpacing:-.3}},"Studio"),h("div",{style:{fontSize:8,color:TM,textTransform:"uppercase",letterSpacing:1.5,fontWeight:600}},"Content engine"))),
  h("div",{style:{flex:1,padding:"8px 6px"}},nav.map(function(n){return h("button",{key:n[0],onClick:function(){setPg(n[0]);},style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"9px 11px",borderRadius:8,border:"none",background:pg===n[0]?AD:"transparent",color:pg===n[0]?AC:T2,cursor:"pointer",fontSize:12,fontWeight:pg===n[0]?600:500,marginBottom:2,textAlign:"left",transition:"all .15s"},className:"btn-hover"},h(Ico,{name:n[2],size:16}),n[1]);})),
  h("div",{style:{padding:"12px 14px",borderTop:"1px solid "+BD,fontSize:10,color:TM}},"v1.0 · 4 APIs")),
// Main
h("div",{style:{flex:1,overflow:"auto",padding:"20px 0"}},h("div",{style:{maxWidth:960,margin:"0 auto",padding:"0 24px"}},
pg==="costs"?h(CostsPage):pg==="vault"?h(VaultPage,{toast:toast}):
h("div",null,
  h("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:16}},h("div",null,h("h2",{style:{fontSize:18,fontWeight:700,color:T1}},"Content pipeline"),h("p",{style:{fontSize:12,color:TM}},job?"Job "+job.id.slice(0,8):"Start a new pipeline")),h(Btn,{primary:true,onClick:newJob,sx:{padding:"8px 14px",fontSize:12}},h(Ico,{name:"plus",size:14})," New")),
  job?h("div",{style:{display:"flex",gap:0,marginBottom:18,overflowX:"auto"}},STEPS.map(function(s,i){var active=s.id===step,done=s.id<step;return h("div",{key:s.id,style:{display:"flex",alignItems:"center",flex:i<4?1:"none"}},h("button",{onClick:function(){setStep(s.id);},style:{display:"flex",alignItems:"center",gap:6,background:active?AD:"transparent",border:"1px solid "+(active?AB:"transparent"),borderRadius:8,padding:"6px 10px",cursor:"pointer",transition:"all .15s",whiteSpace:"nowrap"},className:"btn-hover"},h("div",{style:{width:24,height:24,borderRadius:7,background:done?GR:active?AC:BG3,border:"1px solid "+(done||active?"transparent":BD),display:"flex",alignItems:"center",justifyContent:"center",fontSize:10,fontWeight:700,color:done||active?"#fff":TM}},done?h(Ico,{name:"check",size:12,color:"#fff"}):s.id),h("span",{style:{fontSize:11,fontWeight:active?600:500,color:active?T1:T2}},s.label)),i<4?h("div",{style:{flex:1,height:1,minWidth:8,background:done?GR:BD}}):null);})):null,
  h("div",{style:{display:"grid",gridTemplateColumns:job?"1fr 200px":"1fr",gap:12}},
    h("div",{style:{padding:22,borderRadius:12,background:BGC,border:"1px solid "+BD,minHeight:360}},
      !job?h("div",{style:{textAlign:"center",padding:50}},h(Ico,{name:"pipeline",size:40,color:TM}),h("div",{style:{fontSize:14,color:T2,marginTop:12,marginBottom:16}},"Start a new content pipeline"),h(Btn,{primary:true,onClick:newJob},h(Ico,{name:"plus",size:14})," New")):
      step===1?h(Step1,stepProps):step===2?h(Step2,stepProps):step===3?h(Step3,stepProps):step===4?h(Step4,stepProps):h(Step5,stepProps)),
    job?h("div",{style:{padding:12,borderRadius:10,background:BGC,border:"1px solid "+BD,alignSelf:"start"}},
      h("div",{style:{fontSize:9,fontWeight:600,color:TM,textTransform:"uppercase",letterSpacing:.8,marginBottom:6}},"Steps"),
      STEPS.map(function(s){var done=s.id<step,active=s.id===step;return h("div",{key:s.id,onClick:function(){setStep(s.id);},style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"5px 6px",borderRadius:5,cursor:"pointer",background:active?"rgba(14,165,233,0.06)":"transparent"}},h("span",{style:{fontSize:11,fontWeight:active?600:400,color:active?T1:done?T2:TM,display:"flex",alignItems:"center",gap:5}},h(Ico,{name:s.icon,size:11,color:done?GR:active?AC:TM}),s.label),h("span",{style:{fontSize:9,fontWeight:600,color:done?GR:active?AC:TM}},done?"done":active?"active":"—"));}),
      h("div",{style:{display:"flex",gap:5,marginTop:8}},h("button",{onClick:function(){setStep(Math.max(1,step-1));},disabled:step===1,style:{flex:1,padding:6,borderRadius:6,fontSize:10,fontWeight:600,background:BG3,border:"1px solid "+BD,color:T2,cursor:step===1?"not-allowed":"pointer",opacity:step===1?.3:1,display:"flex",alignItems:"center",justifyContent:"center",gap:3}},h(Ico,{name:"back",size:10}),"Back"),h("button",{onClick:function(){setStep(Math.min(5,step+1));},disabled:step===5,style:{flex:1,padding:6,borderRadius:6,fontSize:10,fontWeight:600,background:AC,border:"none",color:"#fff",cursor:step===5?"not-allowed":"pointer",opacity:step===5?.3:1}},"Next"))
    ):null
  )
))))};
