PageSourceSearch

https://sabhia.ai/assets/projeto-Co8emVjn.js

js sabhia.ai collected 2026-10-05 12:33:19 UTC 287,037 bytes, 33 lines download raw bytes

1import{j as e}from"./vendor-motion-CPxq9Xvn.js";import{r as o}from"./vendor-i18n-CO3kK2bH.js";import{n as Vn,a3 as nt,ai as Ct,a2 as Dn,ec as On,u as Ge,an as R,B as Ze,S as ce,W as qt,a7 as f,a$ as Ds,ap as et,D as Ln,q as qn,aj as Bn,r as _n,al as Un,C as ue,aZ as Hn,p as oa,ay as ks,i as Os,a4 as Gn,aa as tt,ab as Kn,ae as Qn,af as Yn,ag as Wn,ah as Jn,az as Xn,a6 as U,a1 as Zn,a as Ss,aB as Da,K as Ka,X as Ce,Z as Ls,f as zs,ao as Te,Y as jt,z as st,aJ as wt,l as Ie,aG as la,T as Oa,M as Ba,aY as ei,P as ti,as as ai,dJ as qs,d$ as Bs,o as si,$ as ni,k as ii}from"./index-CFAvyuXu.js";import{A as ri,a as oi,b as li,c as di,d as ci,e as mi,f as ui,g as xi}from"./alert-dialog-C9feqA9b.js";import{V as pi}from"./videos-shell-Dt9iLSCb.js";import{V as hi}from"./video-cta-picker-D_eDwzN8.js";import{P as bi}from"./pix-qr-image-D45mJvPS.js";import{b as _a,g as Ua,a as Vt,V as gi}from"./videoVoices-BUWm2xwS.js";import{G as Nt}from"./globe-D0MKCb1Y.js";import{C as Cs}from"./circle-alert-CixghSwT.js";import{D as Le}from"./download-B7FtiUYJ.js";import{Y as He}from"./youtube-C3-YPqKU.js";import{a as fi,g as vi}from"./moneyModeling-DaOS755u.js";import{g as yi}from"./videoImageTiers-C4oM9RWc.js";import{A as ji}from"./arrow-left-DY50GvQQ.js";import{F as fe}from"./film-5Ww7nMCK.js";import{C as kt}from"./cloud-upload-D4KUxAWd.js";import{R as sa}from"./rotate-ccw-yv6DhBa4.js";import{C as Ts}from"./captions-BbpovoyW.js";import{P as da}from"./pencil-DB7EhnQs.js";import{S as ma}from"./save-QXxXVhhp.js";import{M as As}from"./music-2-bgXxnB5k.js";import{M as Ps}from"./mic-vocal-DbvOzLSZ.js";import{L as Ni}from"./layers-B-zOJ8Vr.js";import{M as wi}from"./megaphone-CJoAWoYP.js";import{F as Ms}from"./fingerprint-D5-6a3FO.js";import{I as $s}from"./instagram-BJB2Fjof.js";import{C as St}from"./calendar-clock-yFtimZeY.js";import{M as _s}from"./maximize-2-BDHmjU2g.js";import{T as ki}from"./trash-2-BF2rPJAw.js";import"./vendor-react-CQmBMThG.js";import"./layout-dashboard-pnVssBCT.js";import"./bookmark-plus-CCXPoxjA.js";const Si=[["circle",{cx:"9",cy:"9",r:"7",key:"p2h5vp"}],["circle",{cx:"15",cy:"15",r:"7",key:"19ennj"}]],zi=Vn("blend",Si);let La=null;function Ci(){return La||(La=fetch("/api/stripe/publishable-key").then(a=>a.json()).then(a=>Jn(a.publishableKey)).catch(()=>null)),La}function Ot(a){return`${a.flag} ${a.native}`}const Ti={pending:{label:"Na fila",cls:"bg-blue-500/10 text-blue-300/80 border-blue-500/20"},generating:{label:"Dublando…",cls:"bg-blue-500/15 text-blue-300 border-blue-500/25",spin:!0},ready:{label:"Pronta",cls:"bg-emerald-500/15 text-emerald-300 border-emerald-500/25"},failed:{label:"Falhou",cls:"bg-rose-500/15 text-rose-300 border-rose-500/25"}};function Ai({amountReais:a,fmtPrice:i,onSuccess:b,onError:u}){const w=Qn(),v=Yn(),[p,l]=o.useState(!1),[g,C]=o.useState(!1),T=async()=>{if(!(!w||!v)){l(!0);try{const{error:j,paymentIntent:N}=await w.confirmPayment({elements:v,redirect:"if_required",confirmParams:{return_url:window.location.href}});j?(u(j.message||"Não foi possível processar o cartão."),l(!1)):N&&N.status==="succeeded"?b():(u("Pagamento não concluído. Tente novamente."),l(!1))}catch{u("Erro inesperado ao processar o cartão."),l(!1)}}};return e.jsxs("div",{className:"space-y-4 animate-in fade-in slide-in-from-top-2",children:[e.jsx("div",{className:"rounded-2xl border border-cyan-500/20 bg-cyan-500/[0.03] p-4",children:e.jsx(Wn,{onReady:()=>C(!0),options:{layout:"tabs"}})}),e.jsx(Ze,{onClick:T,disabled:p||!w||!v||!g,className:"w-full h-12 rounded-xl bg-cyan-500 hover:bg-cyan-400 text-cyan-950 font-semibold","data-testid":"button-pay-card-translation",children:p?e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(f,{className:"h-5 w-5 animate-spin"})," Processando…"]}):e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Os,{className:"h-4 w-4"})," Pagar ",i(a)]})})]})}function Pi({open:a,onOpenChange:i,projectId:b,priceReais:u,targetLocales:w,videoTitle:v,onPaid:p,allowPix:l,fmtPrice
1:g}){const{toast:C}=nt(),[T,j]=o.useState(null),[N,x]=o.useState(!1),[S,I]=o.useState(null),[y,L]=o.useState(null),[z,O]=o.useState(null),[P,V]=o.useState(!1),[H,G]=o.useState(!1),B=o.useRef(null),Q=o.useCallback(()=>{j(null),x(!1),I(null),L(null),O(null),V(!1),G(!1),B.current&&clearInterval(B.current)},[]);o.useEffect(()=>(a||Q(),()=>{B.current&&clearInterval(B.current)}),[a,Q]);const oe=o.useCallback(()=>{B.current&&clearInterval(B.current),V(!0),C({title:"Pagamento confirmado ✓",description:"Agora escolha a voz de cada idioma."}),setTimeout(()=>{p(),i(!1)},1400)},[p,i,C]),he=o.useCallback(r=>{B.current&&clearInterval(B.current),B.current=setInterval(async()=>{try{(await(await R("GET",`/api/orders/${r}/status`)).json())?.paid&&oe()}catch{}},3e3)},[oe]),se=async r=>{j(r),x(!0);try{const te=await(await R("POST",`/api/videos/projects/${b}/translation/checkout`,{paymentMethod:r,referrerPage:window.location.pathname})).json();if(r==="credits")if(te?.paid)oe();else throw new Error(te?.message||"Não foi possível pagar com créditos.");else if(r==="pix"){if(!te?.pixCharge?.brCode)throw new Error("Não foi possível gerar a cobrança PIX.");I(te.orderId),O(te.pixCharge),he(te.orderId)}else{if(!te?.clientSecret)throw new Error("Não foi possível preparar o cartão.");I(te.orderId),L(te.clientSecret)}}catch(be){C({title:"Não foi possível iniciar",description:be?.message||"Tente novamente.",variant:"destructive"}),j(null)}finally{x(!1)}},Z=o.useCallback(async()=>{if(S){try{await R("GET",`/api/stripe/verify-session?orderId=${S}`)}catch{}he(S);try{(await(await R("GET",`/api/orders/${S}/status`)).json())?.paid&&oe()}catch{}}},[S,he,oe]),ee=async()=>{if(z?.brCode)try{await navigator.clipboard.writeText(z.brCode),G(!0),setTimeout(()=>G(!1),2500)}catch{}};return e.jsx(Ln,{open:a,onOpenChange:i,children:e.jsx(qn,{className:"bg-[#0a0e14] border-cyan-500/15 text-white w-[95%] sm:max-w-md p-0 overflow-hidden gap-0 max-h-[90dvh] flex flex-col rounded-2xl","data-testid":"dialog-translation-checkout",children:e.jsxs("div",{className:"flex-1 overflow-y-auto p-5 sm:p-6",children:[e.jsxs(Bn,{className:"text-left",children:[e.jsxs(_n,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Nt,{className:"h-5 w-5 text-cyan-400"})," Leve seu vídeo para o mundo"]}),e.jsxs(Un,{className:"text-zinc-400",children:[w.length," idiomas · dublagem com voz nativa, título e descrição traduzidos + miniatura do vídeo."]})]}),P?e.jsxs("div",{className:"mt-6 rounded-2xl border border-emerald-500/20 bg-emerald-500/[0.06] p-6 text-center animate-in fade-in zoom-in","data-testid":"status-translation-paid",children:[e.jsx(ue,{className:"mx-auto mb-3 h-12 w-12 text-emerald-400"}),e.jsx("p",{className:"text-lg font-bold text-emerald-300",children:"Pagamento confirmado!"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-400",children:"Vamos escolher a voz de cada idioma…"})]}):T?N?e.jsxs("div",{className:"mt-8 flex flex-col items-center justify-center py-8",children:[e.jsx(f,{className:"mb-3 h-8 w-8 animate-spin text-cyan-400"}),e.jsx("p",{className:"text-sm text-zinc-400",children:"Preparando o pagamento…"})]}):T==="pix"&&z?e.jsxs("div",{className:"mt-5 rounded-2xl border border-cyan-500/15 bg-cyan-500/[0.03] p-4","data-testid":"block-pix-charge",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-center gap-2 text-xs font-bold text-cyan-300",children:[e.jsx(ks,{className:"h-4 w-4"})," Pague com PIX"]}),e.jsx("div",{className:"mb-4 flex justify-center",children:e.jsx("div",{className:"rounded-lg bg-white p-2",children:e.jsx(bi,{brCode:z.brCode,qrCodeImage:z.qrCodeImage,className:"h-40 w-40",testId:"pix-qrcode-translation"})})}),e.jsxs("div",{className:"mb-2 flex gap-2",children:[e.jsx(Gn,{readOnly:!0,value:z.brCode,className:"h-9 bg-black/30 border-white/10 font-mono text-[10px]","data-testid":"input-pix-brcode-translation"}),e.jsx(Ze,{size:"icon",variant:"outline",className:"h-9 w-9 shrink-0 border-white/10",onClick:ee,"data-testid":"button-copy-pix-translation",children:e.jsx(tt,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"mt-3 animate-pulse text-center text-[11px] text-zinc-500","data-testid":"text-waiting-pix",children:"Aguardando confirmação do pagamento…"}),e.jsx("button",{onClick:Q,className:"mt-2 w-full text-center text-[11px] text-zinc-500 hover:text-white",children:"Trocar forma de pagamento"})]}):T==="card"&&y?e.jsxs("div",{className:"mt-5",children:[e.jsx(Kn,{stripe:Ci(),options:{clientSecret:y,appearance:{theme:"night",variables:{colorPrimary:"#22d3ee"}}}
1,children:e.jsx(Ai,{amountReais:u,fmtPrice:g,onSuccess:Z,onError:r=>C({title:"Erro no cartão",description:r,variant:"destructive"})})}),e.jsx("button",{onClick:Q,className:"mt-3 w-full text-center text-[11px] text-zinc-500 hover:text-white",children:"Trocar forma de pagamento"})]}):e.jsxs("div",{className:"mt-8 flex flex-col items-center justify-center py-8",children:[e.jsx(f,{className:"mb-3 h-8 w-8 animate-spin text-cyan-400"}),e.jsx("p",{className:"text-sm text-zinc-400",children:"Carregando…"})]}):e.jsxs("div",{className:"mt-5 space-y-4",children:[e.jsxs("div",{className:"rounded-2xl border border-cyan-500/15 bg-cyan-500/[0.04] p-4",children:[e.jsxs("div",{className:"flex items-baseline justify-between",children:[e.jsx("span",{className:"text-sm text-zinc-300",children:"Pacote Poliglota"}),e.jsx("span",{className:"text-2xl font-extrabold text-cyan-300","data-testid":"text-translation-price",children:g(u)})]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-1.5","data-testid":"list-translation-languages",children:w.map(r=>e.jsx("span",{className:"rounded-full border border-white/10 bg-black/30 px-2.5 py-1 text-xs text-zinc-200","data-testid":`chip-language-${r.id}`,children:Ot(r)},r.id))})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:"Escolha como pagar:"}),e.jsxs("div",{className:"grid gap-2.5",children:[e.jsxs("button",{onClick:()=>se("credits"),disabled:N,className:"flex items-center justify-between rounded-xl border border-amber-500/20 bg-amber-500/[0.05] px-4 py-3 text-left transition-all hover:border-amber-500/40 hover:bg-amber-500/[0.08] disabled:opacity-50","data-testid":"button-pay-credits",children:[e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(Hn,{className:"h-5 w-5 text-amber-400"}),e.jsx("span",{className:"text-sm font-medium text-zinc-100",children:"Créditos Sábhia"})]}),e.jsx(oa,{className:"h-4 w-4 text-zinc-500"})]}),l&&e.jsxs("button",{onClick:()=>se("pix"),disabled:N,className:"flex items-center justify-between rounded-xl border border-cyan-500/20 bg-cyan-500/[0.05] px-4 py-3 text-left transition-all hover:border-cyan-500/40 hover:bg-cyan-500/[0.08] disabled:opacity-50","data-testid":"button-pay-pix",children:[e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(ks,{className:"h-5 w-5 text-cyan-400"}),e.jsx("span",{className:"text-sm font-medium text-zinc-100",children:"PIX"})]}),e.jsx(oa,{className:"h-4 w-4 text-zinc-500"})]}),e.jsxs("button",{onClick:()=>se("card"),disabled:N,className:"flex items-center justify-between rounded-xl border border-blue-500/20 bg-blue-500/[0.05] px-4 py-3 text-left transition-all hover:border-blue-500/40 hover:bg-blue-500/[0.08] disabled:opacity-50","data-testid":"button-pay-card",children:[e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(Os,{className:"h-5 w-5 text-blue-400"}),e.jsx("span",{className:"text-sm font-medium text-zinc-100",children:"Cartão de crédito"})]}),e.jsx(oa,{className:"h-4 w-4 text-zinc-500"})]})]})]})]})})})}function Mi({projectId:a,hasVideo:i,videoTitle:b}){const{toast:u}=nt(),w=Ct(),{user:v}=Dn(),{allowPix:p,fmtPrice:l}=On(v),g=["/api/videos/projects",a,"translation"],T=Ge({queryKey:g,queryFn:async()=>(await R("GET",`/api/videos/projects/${a}/translation`)).json(),refetchInterval:h=>h.state.data?.translation?.status==="generating"?5e3:!1}).data,j=T?.translation||null,N=j?.status||null,[x,S]=o.useState(!1),[I,y]=o.useState({}),[L,z]=o.useState(!1),[O,P]=o.useState(!1),[V,H]=o.useState(!1),G=o.useRef(null),[B,Q]=o.useState(null),[oe,he]=o.useState(null),se=o.useRef({});o.useEffect(()=>{const h=new Audio;h.preload="none";const M=()=>Q(null);return h.addEventListener("ended",M),G.current=h,()=>{h.removeEventListener("ended",M),h.pause(),G.current=null}},[]),o.useEffect(()=>{N!=="awaiting_voice_selection"||!T||y(h=>{if(Object.keys(h).length)return h;const M={};for(const W of T.targetLocales)M[W.id]=j?.voiceByLocale?.[W.id]||T.projectVoiceId;return M})},[N,T,j]);const Z=o.useCallback(async h=>{const M=G.current;if(!M||oe===h)return;if(B===h){M.pause(),Q(null);return}M.pause(),Q(null);let W=se.current[h];if(!W){he(h);try{if(W=(await(await R("POST","/api/videos/voice-preview",{voiceId:h})).json())?.url,!W)throw new Error("Sem áudio");se.current[h]=W}catch(n){he(null),u({title:"Não foi possível ouvir a voz",description:n?.message||"Tente novamente.",variant:"destructive"});return}he(null)}try{M.src=W,M.currentTime=0,await M.play(),Q(h)}catch{Q(null)}},[oe,B,u]),ee=o.useCallback(()=>w.invalidateQueries({queryKey:g}),[w,a]),r=async()=>
1{if(j){z(!0);try{await R("POST",`/api/videos/translations/${j.id}/voices`,{voiceByLocale:I}),u({title:"Vozes confirmadas ✓",description:"Estamos dublando seu vídeo — uma faixa por idioma."}),ee()}catch(h){u({title:"Não foi possível confirmar",description:h?.message||"Tente novamente.",variant:"destructive"})}finally{z(!1)}}},be=async()=>{if(j){P(!0);try{const M=await(await R("POST",`/api/videos/translations/${j.id}/retry`,{})).json();u({title:"Retomando…",description:`${M?.retried??0} faixa(s) reenfileirada(s).`}),ee()}catch(h){u({title:"Não foi possível retomar",description:h?.message||"Tente novamente.",variant:"destructive"})}finally{P(!1)}}},te=async()=>{if(j){H(!0);try{if(!(await(await R("GET",`/api/videos/translations/${j.id}/download-zip/check`)).json())?.ready){u({title:"Ainda não há faixas prontas",description:"Aguarde a dublagem terminar.",variant:"destructive"});return}window.location.href=`/api/videos/translations/${j.id}/download-zip`}catch(h){u({title:"Não foi possível baixar",description:h?.message||"Tente novamente.",variant:"destructive"})}finally{setTimeout(()=>H(!1),1500)}}};if(!T||!T.enabled||!T.eligible&&!j)return null;const A=T.tracks||[],de=A.filter(h=>h.status==="ready").length,ge=A.length||T.targetLocales.length,le=A.filter(h=>h.status==="failed").length,je=new Map(T.targetLocales.map(h=>[h.id,h])),me=!j||N==="pending_payment"||N==="failed";return e.jsxs("div",{className:"px-5 py-4 border-t border-white/[0.06]","data-testid":"section-video-translation",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(Nt,{className:"h-4 w-4 text-cyan-400"}),e.jsx("span",{className:"text-sm font-semibold text-zinc-100",children:"Tradução para o mundo"}),e.jsx("span",{className:"rounded-full border border-cyan-500/30 bg-cyan-500/15 px-2 py-0.5 text-[10px] font-medium text-cyan-300",children:"Pacote Poliglota"})]}),me&&e.jsxs("div",{className:"rounded-2xl border border-cyan-500/15 bg-gradient-to-br from-cyan-500/[0.06] to-blue-500/[0.03] p-4","data-testid":"card-translation-offer",children:[e.jsxs("p",{className:"text-sm text-zinc-200",children:["Transforme este vídeo em ",e.jsxs("span",{className:"font-semibold text-cyan-300",children:[T.targetLocales.length," idiomas"]})," com voz nativa — e alcance milhões de pessoas no mundo todo. 🌍"]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-1.5",children:T.targetLocales.map(h=>e.jsx("span",{className:"rounded-full border border-white/10 bg-black/30 px-2.5 py-1 text-xs text-zinc-200","data-testid":`offer-chip-${h.id}`,children:Ot(h)},h.id))}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-3",children:[e.jsx("span",{className:"text-2xl font-extrabold text-cyan-300",children:l(T.priceReais)}),e.jsxs(Ze,{onClick:()=>S(!0),className:"rounded-xl bg-cyan-500 hover:bg-cyan-400 text-cyan-950 font-semibold","data-testid":"button-open-translation-checkout",children:[e.jsx(ce,{className:"mr-1.5 h-4 w-4"})," ",N==="pending_payment"?"Concluir pagamento":"Traduzir meu vídeo"]})]})]}),N==="awaiting_voice_selection"&&e.jsxs("div",{className:"space-y-3","data-testid":"block-voice-selection",children:[e.jsxs("p",{className:"text-sm text-zinc-300",children:["Escolha a ",e.jsx("span",{className:"font-semibold text-cyan-300",children:"voz nativa"})," de cada idioma. Toque em ",e.jsx(qt,{className:"inline h-3 w-3"})," para ouvir uma amostra."]}),e.jsx("div",{className:"space-y-2.5",children:T.targetLocales.map(h=>{const M=I[h.id]||T.projectVoiceId,W=B===M,n=oe===M;return e.jsxs("div",{className:"flex items-center gap-2 rounded-xl border border-white/10 bg-black/20 p-2.5","data-testid":`row-voice-${h.id}`,children:[e.jsx("span",{className:"w-28 shrink-0 truncate text-sm text-zinc-100",title:h.native,children:Ot(h)}),e.jsx("select",{value:M,onChange:$=>y(_=>({..._,[h.id]:$.target.value})),className:"flex-1 rounded-lg border border-cyan-500/20 bg-[#0a0e14] px-2.5 py-2 text-sm text-zinc-100 outline-none focus:border-cyan-500/50","data-testid":`select-voice-${h.id}`,children:_a.map($=>e.jsxs("option",{value:$.id,children:[$.label," — ",$.desc]},$.id))}),e.jsx(Ze,{size:"icon",variant:"outline",className:"h-9 w-9 shrink-0 border-cyan-500/30 text-cyan-300 hover:bg-cyan-500/10",onClick:()=>Z(M),"data-testid":`button-preview-voice-${h.id}`,"aria-label":`Ouvir ${Ua(M)?.label||"voz"}`,children:n?e.jsx(f,{className:"h-4 w-4 animate-spin"}):W?e.jsx(Ds,{className:"h-4 w-4"}):e.jsx(qt,{className:"h-4 w-4"})})]}
1,h.id)})}),e.jsx(Ze,{onClick:r,disabled:L,className:"w-full rounded-xl bg-cyan-500 hover:bg-cyan-400 text-cyan-950 font-semibold","data-testid":"button-confirm-voices",children:L?e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(f,{className:"h-4 w-4 animate-spin"})," Iniciando…"]}):e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(et,{className:"h-4 w-4"})," Gerar as faixas"]})})]}),N==="generating"&&e.jsxs("div",{className:"space-y-3","data-testid":"block-translation-generating",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"inline-flex items-center gap-2 text-sm text-cyan-300",children:[e.jsx(f,{className:"h-4 w-4 animate-spin"})," Dublando seu vídeo…"]}),e.jsxs("span",{className:"text-sm font-semibold text-zinc-200","data-testid":"text-translation-progress",children:[de," de ",ge," faixas prontas"]})]}),e.jsx("div",{className:"h-2 overflow-hidden rounded-full bg-white/[0.06]",children:e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-cyan-500 to-blue-500 transition-all",style:{width:`${ge?Math.round(de/ge*100):0}%`}})}),e.jsx("div",{className:"space-y-1.5",children:A.map(h=>{const M=je.get(h.locale),W=Ti[h.status];return e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-white/[0.06] bg-black/20 px-3 py-2","data-testid":`track-row-${h.locale}`,children:[e.jsx("span",{className:"text-sm text-zinc-200",children:M?Ot(M):h.locale}),e.jsxs("span",{className:`inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5 text-[11px] font-medium ${W.cls}`,"data-testid":`track-status-${h.locale}`,children:[W.spin&&e.jsx(f,{className:"h-3 w-3 animate-spin"}),W.label]})]},h.id)})}),le>0&&e.jsxs(Ze,{onClick:be,disabled:O,variant:"outline",className:"w-full border-cyan-500/30 text-cyan-300 hover:bg-cyan-500/10","data-testid":"button-retry-translation",children:[O?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(Cs,{className:"h-4 w-4"}),e.jsxs("span",{className:"ml-1.5",children:["Retomar ",le," faixa(s) com falha"]})]})]}),N==="ready"&&e.jsxs("div",{className:"space-y-4","data-testid":"block-translation-ready",children:[e.jsxs("div",{className:"rounded-2xl border border-emerald-500/20 bg-emerald-500/[0.06] p-4 text-center",children:[e.jsx("div",{className:"text-3xl",children:"🌍"}),e.jsx("p",{className:"mt-1 text-base font-bold text-emerald-300",children:"Suas faixas estão prontas para ganhar o mundo!"}),e.jsxs("p",{className:"mt-1 text-sm text-zinc-400",children:[de," idioma(s) dublado(s) com voz nativa, título e descrição traduzidos + miniatura do vídeo."]})]}),e.jsx("div",{className:"space-y-2",children:A.map(h=>{const M=je.get(h.locale),W=Ua(h.voiceId),n=h.status==="ready"&&h.hasAudio;return e.jsx("div",{className:"rounded-xl border border-white/10 bg-black/20 p-3","data-testid":`ready-track-${h.locale}`,children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium text-zinc-100",children:M?Ot(M):h.locale}),h.title&&e.jsx("p",{className:"truncate text-xs text-zinc-400",title:h.title,children:h.title}),e.jsxs("p",{className:"text-[11px] text-zinc-500",children:["Voz: ",W?.label||h.voiceId]})]}),n?e.jsxs("a",{href:`/api/videos/translations/${j.id}/tracks/${h.id}/audio?download=1`,className:"inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-cyan-500/30 bg-cyan-500/10 px-3 py-2 text-xs font-medium text-cyan-300 hover:bg-cyan-500/20","data-testid":`button-download-track-${h.locale}`,children:[e.jsx(Le,{className:"h-3.5 w-3.5"})," .m4a"]}):e.jsx("span",{className:"shrink-0 rounded-full border border-rose-500/25 bg-rose-500/15 px-2 py-0.5 text-[11px] text-rose-300",children:"Falhou"})]})},h.id)})}),e.jsx(Ze,{onClick:te,disabled:V,className:"w-full rounded-xl bg-cyan-500 hover:bg-cyan-400 text-cyan-950 font-semibold","data-testid":"button-download-translation-zip",children:V?e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(f,{className:"h-4 w-4 animate-spin"})," Preparando…"]}):e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Le,{className:"h-4 w-4"})," Baixar pacote completo (.zip)"]})}),le>0&&e.jsxs(Ze,{onClick:be,disabled:O,variant:"outline",className:"w-full border-cyan-500/30 text-cyan-300 hover:bg-cyan-500/10","data-testid":"button-retry-translation-ready",children:[O?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(Cs,{className:"h-4 w-4"}),e.jsxs("span",{className:"ml-1.5",children:["Tentar de novo as ",le," faixa(s) com falha"]})]}),e.jsxs("details",{className:"rounded-xl border border-white/10 bg-black/20 p-3","data-testid":"details-youtube-guide",children:[e.jsxs("summary",{className:"flex cursor-pointer items-center gap-2 text-sm font-medium text-zinc-200",children:[e.jsx(He,{className:"h-4 w-4 text-rose-400"})," Como adicionar os idiomas no YouTube"]}),e.jsxs("ol",{className:"mt-3 list-decimal space-y-1.5 pl-5 text-xs text-zinc-400",children:[e.jsxs("li",{children:["Abra o ",e.jsx("span",{className:"text-zinc-200",children:"YouTube Studio"})," → Conteúdo → escolha este vídeo."]}
1),e.jsxs("li",{children:["No menu lateral, vá em ",e.jsx("span",{className:"text-zinc-200",children:"Idiomas"}),' (ou "Subtítulos/Faixas de áudio").']}),e.jsxs("li",{children:["Em cada idioma, faça upload do arquivo ",e.jsx("span",{className:"text-zinc-200",children:".m4a"})," correspondente do pacote."]}),e.jsxs("li",{children:["Copie o ",e.jsx("span",{className:"text-zinc-200",children:"título"})," e a ",e.jsx("span",{className:"text-zinc-200",children:"descrição"})," traduzidos do arquivo ",e.jsx("span",{className:"text-zinc-200",children:"METADATA.txt"}),"."]}),e.jsxs("li",{children:["Use a ",e.jsx("span",{className:"text-zinc-200",children:"miniatura"})," do vídeo (incluída no pacote, quando disponível) para cada idioma."]}),e.jsx("li",{children:"Publique — pronto, seu vídeo fala com o mundo! 🌍"})]})]})]}),e.jsx(Pi,{open:x,onOpenChange:S,projectId:a,priceReais:T.priceReais,targetLocales:T.targetLocales,videoTitle:b,onPaid:ee,allowPix:p,fmtPrice:l})]})}const $i={transparencyHeading:"⚠️ Aviso de Transparência",transparencyBodyLong:"Este vídeo foi produzido estritamente para fins educacionais e informativos. Tecnologias de Inteligência Artificial (IA) foram utilizadas em sua produção — incluindo roteiro, narração por voz sintética e/ou aprimoramentos visuais — para auxiliar na entrega do conteúdo. Todos os esforços foram feitos para garantir a precisão das informações apresentadas. Incentivamos você a consultar fontes primárias para pesquisas aprofundadas.",transparencyBodyShort:"Este vídeo foi produzido para fins educacionais e informativos. Tecnologias de Inteligência Artificial (IA) foram utilizadas em sua produção — incluindo roteiro, narração por voz sintética e/ou aprimoramentos visuais.",inThisVideo:"📌 NESTE VÍDEO:",sourcesOnline:"🔗 Fontes investigadas na internet:",sourcesShort:"📚 FONTES",subscribeFull:`🔔 Inscreva-se e ative o sininho para não perder nenhum vídeo!
2👍 Se gostou, deixe seu like e compartilhe — ajuda muito o canal!`,subscribeShort:"🔔 Se este conteúdo te ajudou, inscreva-se e ative o sino!",footer:"Produzido com Sábhia IA"},Us={transparencyHeading:"⚠️ Transparency Notice",transparencyBodyLong:"This video was produced strictly for educational and informational purposes. Artificial Intelligence (AI) technologies were used in its production — including scripting, synthetic voice narration, and/or visual enhancements — to assist in content delivery. Every effort has been made to ensure the accuracy of the information presented. We encourage you to consult primary sources for further research.",transparencyBodyShort:"This video was produced strictly for educational and informational purposes. Artificial Intelligence (AI) was used in its production — including scripting, synthetic voice narration, and/or visual enhancements — to assist in content delivery.",inThisVideo:"📌 IN THIS VIDEO:",sourcesOnline:"🔗 Sources researched online:",sourcesShort:"📚 SOURCES",subscribeFull:`🔔 Subscribe and hit the bell icon for more!
3👍 If you enjoyed it, please like and share — it helps a lot!`,subscribeShort:"🔔 If this content helped you, subscribe and hit the bell!",footer:"Produced with Sábhia AI"},Ei={transparencyHeading:"⚠️ Aviso de Transparencia",transparencyBodyLong:"Este vídeo fue producido estrictamente con fines educativos e informativos. Se utilizaron tecnologías de Inteligencia Artificial (IA) en su producción — incluyendo guión, narración de voz sintética y/o mejoras visuales — para asistir en la entrega del contenido. Se ha hecho todo lo posible para garantizar la precisión de la información presentada. Le animamos a consultar fuentes primarias para investigaciones adicionales.",transparencyBodyShort:"Este vídeo fue producido con fines educativos e informativos. Se utilizaron tecnologías de Inteligencia Artificial (IA) en su producción — incluyendo guión, narración sintética y/o mejoras visuales.",inThisVideo:"📌 EN ESTE VÍDEO:",sourcesOnline:"🔗 Fuentes investigadas en internet:",sourcesSh
3ort:"📚 FUENTES",subscribeFull:`🔔 ¡Suscríbete y activa la campana para más vídeos!
4👍 ¡Si te gustó, deja tu like y comparte!`,subscribeShort:"🔔 ¡Si este contenido te ayudó, suscríbete y activa la campana!",footer:"Producido con Sábhia IA"},Ii={transparencyHeading:"⚠️ Avis de Transparence",transparencyBodyLong:"Cette vidéo a été produite à des fins strictement éducatives et informatives. Des technologies d'intelligence artificielle (IA) ont été utilisées dans sa production — notamment le scénario, la narration par voix synthétique et/ou des améliorations visuelles — afin de faciliter la présentation du contenu. Nous vous encourageons à consulter des sources primaires pour des recherches approfondies.",transparencyBodyShort:"Cette vidéo a été produite à des fins éducatives et informatives. Des technologies d'intelligence artificielle (IA) ont été utilisées dans sa production — notamment le scénario, la narration par voix synthétique et/ou des améliorations visuelles.",inThisVideo:"📌 DANS CETTE VIDÉO :",sourcesOnline:"🔗 Sources recherchées en ligne :",sourcesShort:"📚 SOURCES",subscribeFull:`🔔 Abonnez-vous et activez la cloche pour ne rien manquer !
5👍 Si vous avez aimé, laissez un like et partagez — ça aide beaucoup la chaîne !`,subscribeShort:"🔔 Si ce contenu vous a aidé, abonnez-vous et activez la cloche !",footer:"Produit avec Sábhia IA"},Ri={transparencyHeading:"⚠️ Transparenzhinweis",transparencyBodyLong:"Dieses Video wurde ausschließlich zu Bildungs- und Informationszwecken erstellt. Bei der Produktion wurden Technologien der künstlichen Intelligenz (KI) eingesetzt — einschließlich Skript, synthetischer Sprachausgabe und/oder visueller Verbesserungen — um die Vermittlung der Inhalte zu unterstützen. Wir empfehlen Ihnen, für weitergehende Recherchen Primärquellen heranzuziehen.",transparencyBodyShort:"Dieses Video wurde zu Bildungs- und Informationszwecken erstellt. Bei der Produktion wurden Technologien der künstlichen Intelligenz (KI) eingesetzt — einschließlich Skript, synthetischer Sprachausgabe und/oder visueller Verbesserungen.",inThisVideo:"📌 IN DIESEM VIDEO:",sourcesOnline:"🔗 Online recherchierte Quellen:",sourcesShort:"📚 QUELLEN",subscribeFull:`🔔 Abonniere den Kanal und aktiviere die Glocke, um nichts zu verpassen!
6👍 Wenn es dir gefallen hat, hinterlasse ein Like und teile es — das hilft dem Kanal sehr!`,subscribeShort:"🔔 Wenn dir dieser Inhalt geholfen hat, abonniere und aktiviere die Glocke!",footer:"Produziert mit Sábhia KI"},Fi={transparencyHeading:"⚠️ Avviso di Trasparenza",transparencyBodyLong:"Questo video è stato prodotto esclusivamente a scopo educativo e informativo. Nella sua produzione sono state utilizzate tecnologie di intelligenza artificiale (IA) — tra cui sceneggiatura, narrazione con voce sintetica e/o miglioramenti visivi — per facilitare la presentazione dei contenuti. Ti invitiamo a consultare fonti primarie per ricerche approfondite.",transparencyBodyShort:"Questo video è stato prodotto a scopo educativo e informativo. Nella sua produzione sono state utilizzate tecnologie di intelligenza artificiale (IA) — tra cui sceneggiatura, narrazione con voce sintetica e/o miglioramenti visivi.",inThisVideo:"📌 IN QUESTO VIDEO:",sourcesOnline:"🔗 Fonti consultate online:",sourcesShort:"📚 FONTI",subscribeFull:`🔔 Iscriviti e attiva la campanella per non perdere nessun video!
7👍 Se ti è piaciuto, lascia un like e condividi — aiuta molto il canale!`,subscribeShort:"🔔 Se questo contenuto ti è stato utile, iscriviti e attiva la campanella!",footer:"Prodotto con Sábhia IA"},Vi={transparencyHeading:"⚠️ إشعار الشفافية",transparencyBodyLong:"أُنتج هذا الفيديو لأغراض تعليمية وإعلامية بحتة. استُخدمت تقنيات الذكاء الاصطناعي في إنتاجه — بما في ذلك كتابة النص والتعليق الصوتي الاصطناعي و/أو التحسينات البصرية — للمساعدة في تقديم المحتوى. بُذلت كل الجهود لضمان دقة المعلومات المقدَّمة، وننصحك بالرجوع إلى المصادر الأولية لمزيد من البحث.",transparencyBodyShort:"أُنتج هذا الفيديو لأغراض تعليمية وإعلامية. استُخدمت تقنيات الذكاء الاصطناعي في إنتاجه — بما في ذلك كتابة النص والتعليق الصوتي الاصطناعي و/أو التحسينات البصرية.",inThisVideo:"📌 في هذا الفيديو:",sourcesOnline:"🔗 مصادر تم البحث عنها عبر الإنترنت:",sourcesSh
7ort:"📚 المصادر",subscribeFull:`🔔 اشترك في القناة وفعّل جرس التنبيهات حتى لا تفوتك أي مقاطع!
8👍 إذا أعجبك المقطع، اترك إعجابًا وشاركه — هذا يدعم القناة كثيرًا!`,subscribeShort:"🔔 إذا ساعدك هذا المحتوى، فاشترك وفعّل جرس التنبيهات!",footer:"أُنتج بواسطة Sábhia AI"},Di={transparencyHeading:"⚠️ पारदर्शिता सूचना",transparencyBodyLong:"यह वीडियो केवल शैक्षिक और सूचनात्मक उद्देश्यों के लिए बनाया गया है। इसके निर्माण में आर्टिफिशियल इंटेलिजेंस (AI) तकनीकों का उपयोग किया गया है — जिसमें स्क्रिप्ट, सिंथेटिक आवाज़ में वर्णन और/या दृश्य सुधार शामिल हैं — ताकि सामग्री को बेहतर ढंग से प्रस्तुत किया जा सके। गहन शोध के लिए हम आपको प्राथमिक स्रोतों से जानकारी लेने की सलाह देते हैं।",transparencyBodyShort:"यह वीडियो शैक्षिक और सूचनात्मक उद्देश्यों के लिए बनाया गया है। इसके निर्माण में आर्टिफिशियल इंटेलिजेंस (AI) तकनीकों का उपयोग किया गया है — जिसमें स्क्रिप्ट, सिंथेटिक आवाज़ में वर्णन और/या दृश्य सुधार शामिल हैं।",inThisVideo:"📌 इस वीडियो में:",sourcesOnline:"🔗 इंटरनेट पर खोजे गए स्रोत:",sourcesShort:"📚 स्रोत",subscribeFull:`🔔 चैनल को सब्सक्राइब करें और बेल आइकन दबाएँ ताकि कोई वीडियो छूटे नहीं!
9👍 अगर पसंद आया तो लाइक करें और शेयर करें — इससे चैनल को बहुत मदद मिलती है!`,subscribeShort:"🔔 अगर यह सामग्री उपयोगी लगी, तो सब्सक्राइब करें और बेल दबाएँ!",footer:"Sábhia AI से निर्मित"},Oi={transparencyHeading:"⚠️ 透明性に関するお知らせ",transparencyBodyLong:"この動画は教育および情報提供のみを目的として制作されています。制作には、台本・合成音声によるナレーション・視覚的な加工など、人工知能(AI)技術が使用されています。提示された情報の正確性には最大限努めていますが、詳しく調べる際は一次資料の確認をおすすめします。",transparencyBodyShort:"この動画は教育および情報提供を目的として制作されています。制作には、台本・合成音声によるナレーション・視覚的な加工など、人工知能(AI)技術が使用されています。",inThisVideo:"📌 この動画の内容:",sourcesOnline:"🔗 オンラインで調査した情報源:",sourcesShort:"📚 出典",subscribeFull:`🔔 チャンネル登録と通知ベルをオンにして、最新動画をお見逃しなく!
10👍 気に入ったら高評価とシェアをお願いします — チャンネルの大きな励みになります!`,subscribeShort:"🔔 この動画が役に立ったら、チャンネル登録と通知ベルをオンにしてください!",footer:"Sábhia AI で制作"},Li={transparencyHeading:"⚠️ 透明度声明",transparencyBodyLong:"本视频仅用于教育和信息目的。在制作过程中使用了人工智能(AI)技术,包括脚本撰写、合成语音旁白和/或视觉增强,以协助内容呈现。我们已尽
10力确保所呈现信息的准确性,并建议您查阅原始资料以进行深入研究。",transparencyBodyShort:"本视频用于教育和信息目的。在制作过程中使用了人工智能(AI)技术,包括脚本撰写、合成语音旁白和/或视觉增强。",inThisVideo:"📌 本视频内容:",sourcesOnline:"🔗 在线查询的资料来源:",sourcesShort:"📚 资料来源",subscribeFull:`🔔 订阅频道并开启小铃铛,不错过每一个视频!
11👍 如果喜欢,请点赞并分享——这对频道帮助很大!`,subscribeShort:"🔔 如果这个内容对你有帮助,请订阅并开启小铃铛!",footer:"由 Sábhia AI 制作"},qi={transparencyHeading:"⚠️ 투명성 고지",transparencyBodyLong:"이 영상은 오로지 교육 및 정보 제공을 목적으로 제작되었습니다. 제작 과정에서 대본, 합성 음성 내레이션 및/또는 시각적 보정 등 인공지능(AI) 기술이 사용되었습니다. 제시된 정보의 정확성을 위해 최선을 다했으며, 더 깊은 조사를 위해 1차 자료를 참고하시길 권장합니다.",transparencyBodyShort:"이 영상은 교육 및 정보 제공을 목적으로 제작되었습니다. 제작 과정에서 대본, 합성 음성 내레이션 및/또는 시각적 보정 등 인공지능(AI) 기술이 사용되었습니다.",inThisVideo:"📌 이 영상에서:",sourcesOnline:"🔗 온라인에서 조사한 출처:",sourcesShort:"📚 출처",subscribeFull:`🔔 구독과 알림 설정을 켜고 새 영상을 놓치지 마세요!
12👍 마음에 드셨다면 좋아요와 공유 부탁드립니다 — 채널에 큰 힘이 됩니다!`,subscribeShort:"🔔 이 콘텐츠가 도움이 되었다면 구독하고 알림을 설정해 주세요!",footer:"Sábhia AI로 제작"},Bi={transparencyHeading:"⚠️ Уведомление о прозрачности",transparencyBodyLong:"Это видео создано исключительно в образовательных и информационных целях. При его производстве использовались технологии искусственного интеллекта (ИИ) — включая сценарий, синтезированную закадровую озвучку и/или визуальные улучшения — чтобы помочь в подаче материала. Рекомендуем обращаться к первоисточникам для углублённого изучения темы.",transparencyBodyShort:"Это видео создано в образовательных и информационных целях. При его производстве использовались технологии искусственного интеллекта (ИИ) — включая сценарий, синтезированную закадровую озвучку и/или визуальные улучшения.",inThisVideo:"📌 В ЭТОМ ВИДЕО:",sourcesOnline:"🔗 Источники, найденные в интернете:",sourcesShort:"📚 ИСТОЧНИКИ",subscribeFull:`🔔 Подпишитесь и включите колокольчик, чтобы не пропустить новые видео!
13👍 Если понравилось, поставьте лайк и поделитесь — это очень помогает каналу!`,subscribeShort:"🔔 Если это видео вам помогло, подпишитесь и включите уведомления!",footer:"Создано с помощью Sábhia AI"},_i={transparencyHeading:"⚠️ Şeffaflık Bildirimi",transparencyBodyLong:"Bu video yalnızca eğitim ve bilgilendirme amacıyla hazırlanmıştır. Yapımında — senaryo, sentetik seslendirme ve/veya görsel iyileştirmeler dahil — yapay zekâ (YZ) teknolojileri kullanılmıştır. Daha derin araştırmalar için birincil kaynaklara başvurmanızı öneririz.",transparencyBodyShort:"Bu video eğitim ve bilgilendirme amacıyla hazırlanmıştır. Yapımında — senaryo, sentetik seslendirme ve/veya görsel iyileştirmeler dahil — yapay zekâ (YZ) teknolojileri kullanılmıştır.",inThisVideo:"📌 BU VİDEODA:",sourcesOnline:"🔗 İnternette araştırılan kaynaklar:",sourcesSh
13ort:"📚 KAYNAKLAR",subscribeFull:`🔔 Hiçbir videoyu kaçırmamak için abone ol ve bildirim zilini aç!
14👍 Beğendiysen beğeni bırak ve paylaş — kanala çok yardımcı oluyor!`,subscribeShort:"🔔 Bu içerik işine yaradıysa abone ol ve bildirim zilini aç!",footer:"Sábhia AI ile üretildi"},Ui={transparencyHeading:"⚠️ Informacja o przejrzystości",transparencyBodyLong:"Ten film został wyprodukowany wyłącznie w celach edukacyjnych i informacyjnych. W jego produkcji wykorzystano technologie sztucznej inteligencji (SI) — w tym scenariusz, syntetyczny lektor i/lub udoskonalenia wizualne — aby ułatwić przekazanie treści. Zachęcamy do korzystania ze źródeł pierwotnych w celu pogłębienia tematu.",transparencyBodyShort:"Ten film został wyprodukowany w celach edukacyjnych i informacyjnych. W jego produkcji wykorzystano technologie sztucznej inteligencji (SI) — w tym scenariusz, syntetyczny lektor i/lub udoskonalenia wizualne.",inThisVideo:"📌 W TYM FILMIE:",sourcesOnline:"🔗 Źródła wyszukane w internecie:",sourcesShort:"📚 ŹRÓDŁA",subscribeFull:`🔔 Subskrybuj i włącz dzwonek, aby nie przegapić żadnego filmu!
15👍 Jeśli Ci się spodobało, zostaw łapkę w górę i udostępnij — to bardzo pomaga kanałowi!`,subscribeShort:"🔔 Jeśli ten materiał Ci pomógł, zasubskrybuj i włącz dzwonek!",footer:"Wyprodukowano z Sábhia AI"},Hi={transparencyHeading:"⚠️ Transparantiemelding",transparencyBodyLong:"Deze video is uitsluitend gemaakt voor educatieve en informatieve doeleinden. Bij de productie is gebruikgemaakt van kunstmatige intelligentie (AI) — waaronder script, synthetische voice-over en/of visuele verbeteringen — om de inhoud beter over te brengen. We raden je aan om primaire bronnen te raadplegen voor diepgaander onderzoek.",transparencyBodyShort:"Deze video is gemaakt voor educatieve en informatieve doeleinden. Bij de productie is gebruikgemaakt van kunstmatige intelligentie (AI) — waaronder script, synthetische voice-over en/of visuele verbeteringen.",inThisVideo:"📌 IN DEZE VIDEO:",sourcesOnline:"🔗 Online onderzochte bronnen:",sourcesShort:"📚 BRONNEN",subscribeFull:`🔔 Abonneer je en zet de bel aan zodat je geen video mist!
16👍 Vond je het leuk? Laat een like achter en deel — dat helpt het kanaal enorm!`,subscribeShort:"🔔 Heeft deze video je geholpen? Abonneer je en zet de bel aan!",footer:"Geproduceerd met Sábhia AI"},Gi={transparencyHeading:"⚠️ Pemberitahuan Transparansi",transparencyBodyLong:"Video ini diproduksi semata-mata untuk tujuan edukasi dan informasi. Teknologi kecerdasan buatan (AI) digunakan dalam produksinya — termasuk naskah, narasi suara sintetis, dan/atau penyempurnaan visual — untuk membantu penyampaian konten. Kami menganjurkan Anda merujuk pada sumber primer untuk penelitian lebih lanjut.",transparencyBodyShort:"Video ini diproduksi untuk tujuan edukasi dan informasi. Teknologi kecerdasan buatan (AI) digunakan dalam produksinya — termasuk naskah, narasi suara sintetis, dan/atau penyempurnaan visual.",inThisVideo:"📌 DALAM VIDEO INI:",sourcesOnline:"🔗 Sumber yang diteliti secara online:",sourcesShort:"📚 SUMBER",subscribeFull:`🔔 Subscribe dan aktifkan lonceng agar tidak ketinggalan video!
17👍 Jika suka, beri like dan bagikan — sangat membantu channel ini!`,subscribeShort:"🔔 Jika konten ini membantu, subscribe dan aktifkan lonceng!",footer:"Diproduksi dengan Sábhia AI"},Ki={transparencyHeading:"⚠️ Thông Báo Minh Bạch",transparencyBodyLong:"Video này được sản xuất hoàn toàn cho mục đích giáo dục và cung cấp thông tin. Công nghệ trí tuệ nhân tạo (AI) đã được sử dụng trong quá trình sản xuất — bao gồm kịch bản, lời thuyết minh bằng giọng nói tổng hợp và/hoặc các cải tiến hình ảnh — nhằm hỗ trợ truyền tải nội dung. Chúng tôi khuyến khích bạn tham khảo các nguồn sơ cấp để nghiên cứu sâu hơn.",transparencyBodyShort:"Video này được sản xuất cho mục đích giáo dục và cung cấp thông tin. Công nghệ trí tuệ nhân tạo (AI) đã được sử dụng trong quá trình sản xuất — bao gồm kịch bản, lời thuyết minh bằng giọng nói tổng hợp và/hoặc các cải tiến hình ảnh.",inThisVideo:"📌 TRONG VIDEO NÀY:",sourcesOnline:"🔗 Nguồn được tra cứu trực tuyến:",sourcesSh
17ort:"📚 NGUỒN",subscribeFull:`🔔 Đăng ký kênh và bật chuông thông báo để không bỏ lỡ video nào!
18👍 Nếu thấy hay, hãy nhấn thích và chia sẻ — điều đó giúp ích rất nhiều cho kênh!`,subscribeShort:"🔔 Nếu nội dung này hữu ích, hãy đăng ký và bật chuông thông báo!",footer:"Sản xuất bằng Sábhia AI"},Qi={transparencyHeading:"⚠️ ประกาศความโปร่งใส",transparencyBodyLong:"วิดีโอนี้จัดทำขึ้นเพื่อวัตถุประสงค์ทางการศึกษาและให้ข้อมูลเท่านั้น มีการใช้เทคโนโลยีปัญญาประดิษฐ์ (AI) ในการผลิต — รวมถึงบท การบรรยายด้วยเสียงสังเคราะห์ และ/หรือการปรับแต่งภาพ — เพื่อช่วยในการนำเสนอเนื้อหา เราขอแนะนำให้คุณตรวจสอบแหล่งข้อมูลปฐมภูมิเพื่อการค้นคว้าเพิ่มเติม",transparencyBodyShort:"วิดีโอนี้จัดทำขึ้นเพื่อวัตถุประสงค์ทางการศึกษาและให้ข้อมูล มีการใช้เทคโนโลยีปัญญาประดิษฐ์ (AI) ในการผลิต — รวมถึงบท การบรรยายด้วยเสียงสังเคราะห์ และ/หรือการปรับแต่งภาพ",inThisVideo:"📌 ในวิดีโอนี้:",sourcesOnline:"🔗 แหล่งข้อมูลที่ค้นคว้าทางออนไลน์:",sourcesShort:"📚 แหล่งข้อมูล",subscribeFull:`🔔 กดติดตามและเปิดกระดิ่งแจ้งเตือนเพื่อไม่พลาดทุกวิดีโอ!
19👍 ถ้าชอบ กดไลก์และแชร์ — ช่วยช่องได้มากเลย!`,subscribeShort:"🔔 ถ้าวิดีโอนี้มีประโยชน์ กดติดตามและเปิดกระดิ่งแจ้งเตือนด้วยนะ!",footer:"ผลิตด้วย Sábhia AI"},Yi={transparencyHeading:"⚠️ Повідомлення про прозорість",transparencyBodyLong:"Це відео створено виключно з освітньою та інформаційною метою. Під час його виробництва використовувалися технології штучного інтелекту (ШІ) — зокрема сценарій, синтезований закадровий голос та/або візуальні покращення — щоб допомогти в подачі матеріалу. Радимо звертатися до першоджерел для глибшого вивчення теми.",transparencyBodyShort:"Це відео створено з освітньою та інформаційною метою. Під час його виробництва використовувалися технології штучного інтелекту (ШІ) — зокрема сценарій, синтезований закадровий голос та/або візуальні покращення.",inThisVideo:"📌 У ЦЬОМУ ВІДЕО:",sourcesOnline:"🔗 Джерела, знайдені в інтернеті:",sourcesShort:"📚 ДЖЕРЕЛА",subscribeFull:`🔔 Підпишіться та увімкніть сповіщення, щоб не пропустити нові відео!
20👍 Якщо сподобалося, поставте вподобайку та поділіться — це дуже допомагає каналу!`,subscribeShort:"🔔 Якщо це вÑ
20–део було корисним, підпишіться та увімкніть сповіщення!",footer:"Створено за допомогою Sábhia AI"},Wi={transparencyHeading:"⚠️ Notă de Transparență",transparencyBodyLong:"Acest videoclip a fost produs exclusiv în scopuri educative și informative. În producția sa au fost utilizate tehnologii de inteligență artificială (IA) — inclusiv scenariu, narațiune cu voce sintetică și/sau îmbunătățiri vizuale — pentru a sprijini prezentarea conținutului. Te încurajăm să consulți surse primare pentru cercetări aprofundate.",transparencyBodyShort:"Acest videoclip a fost produs în scopuri educative și informative. În producția sa au fost utilizate tehnologii de inteligență artificială (IA) — inclusiv scenariu, narațiune cu voce sintetică și/sau îmbunătățiri vizuale.",inThisVideo:"📌 ÎN ACEST VIDEOCLIP:",sourcesOnline:"🔗 Surse cercetate online:",sourcesShort:"📚 SURSE",subscribeFull:`🔔 Abonează-te și activează clopoțelul ca să nu ratezi niciun videoclip!
21👍 Dacă ți-a plăcut, lasă un like și distribuie — ajută mult canalul!`,subscribeShort:"🔔 Dacă acest conținut te-a ajutat, abonează-te și activează clopoțelul!",footer:"Produs cu Sábhia IA"},Ji={transparencyHeading:"⚠️ Ειδοποίηση Διαφάνειας",transparencyBodyLong:"Αυτό το βίντεο δημιουργήθηκε αποκλειστικά για εκπαιδευτικούς και ενημερωτικούς σκοπούς. Κατά την παραγωγή του χρησιμοποιήθηκαν τεχνολογίες τεχνητής νοημοσύνης (AI) — συμπεριλαμβανομένων του σεναρίου, της αφήγησης με συνθετική φωνή ή/και οπτικών βελτιώσεων — για την υποστήριξη της παρουσίασης του περιεχομένου. Σας ενθαρρύνουμε να συμβουλεύεστε πρωτογενείς πηγές για περαιτέρω έρευνα.",transparencyBodyShort:"Αυτό το βίντεο δημιουργήθηκε για εκπαιδευτικούς και ενημερωτικούς σκοπούς. Κατά την παραγωγή του χρησιμοποιήθηκαν τεχνολογίες τεχνητής νοημοσύνης (AI) — συμπεριλαμβανομένων του σεναρίου, της αφήγησης με συνθετική φωνή ή/και οπτικών βελτιώσεων.",inThisVideo:"📌 ΣΕ ΑΥΤΟ ΤΟ ΒΙΝΤΕΟ:",sourcesOnline:"🔗 Πηγές που αναζητήθηκαν στο διαδίκτυο:",sourcesShort:"📚 ΠΗΓΕΣ",subscribeFull:`🔔 Κάνε εγγραφή και ενεργοποίησε το καμπανάκι για να μη χάνεις κανένα βίντεο!
22👍 Αν σου άρεσε, άφησε ένα like και κοινοποίησε — βοηθάει πολύ το κανάλι!`,subscribeShort:"🔔 Αν αυτό το βίντεο σε βοήθησε, κάνε εγγραφή και ενεργοποίησε το καμπανάκι!",footer:"Παράχθηκε με το Sábhia AI"},Xi={transparencyHeading:"⚠️ Upozornění o transparentnosti",transparencyBodyLong:"Toto video bylo vytvořeno výhradně pro vzdělávací a informační účely. Při jeho výrobě byly použity technologie umělé inteligence (AI) — včetně scénáře, syntetického hlasového komentáře a/nebo vizuálních vylepšení — aby napomohly k prezentaci obsahu. Pro hlubší zkoumání tématu doporučujeme nahlédnout do primárních zdrojů.",transparencyBodyShort:"Toto video bylo vytvořeno pro vzdělávací a informační účely. Při jeho výrobě byly použity technologie umělé inteligence (AI) — včetně scénáře, syntetického hlasového komentáře a/nebo vizuálních vylepšení.",inThisVideo:"📌 V TOMTO VIDEU:",sourcesOnline:"🔗 Zdroje vyhledané online:",sourcesShort:"📚 ZDROJE",subscribeFull:`🔔 Odebírejte kanál a zapněte zvoneček, ať vám neunikne žádné video!
23👍 Pokud se vám video líbilo, dejte like a sdílejte — kanálu to moc pomůže!`,subscribeShort:"🔔 Pokud vám toto video pomohlo, odebírejte a zapněte zvoneček!",footer
23:"Vytvořeno pomocí Sábhia AI"},Zi={transparencyHeading:"⚠️ Läpinäkyvyysilmoitus",transparencyBodyLong:"Tämä video on tuotettu yksinomaan opetus- ja tiedotustarkoituksiin. Sen tuotannossa on käytetty tekoälyteknologioita (AI) — mukaan lukien käsikirjoitus, synteettinen ääniselostus ja/tai visuaaliset parannukset — sisällön välittämisen tueksi. Suosittelemme tutustumaan alkuperäislähteisiin syvällisempää tutkimusta varten.",transparencyBodyShort:"Tämä video on tuotettu opetus- ja tiedotustarkoituksiin. Sen tuotannossa on käytetty tekoälyteknologioita (AI) — mukaan lukien käsikirjoitus, synteettinen ääniselostus ja/tai visuaaliset parannukset.",inThisVideo:"📌 TÄSSÄ VIDEOSSA:",sourcesOnline:"🔗 Verkosta haetut lähteet:",sourcesShort:"📚 LÄHTEET",subscribeFull:`🔔 Tilaa kanava ja laita ilmoitukset päälle, niin et missaa yhtään videota!
24👍 Jos pidit, jätä tykkäys ja jaa — se auttaa kanavaa paljon!`,subscribeShort:"🔔 Jos tästä videosta oli apua, tilaa kanava ja laita ilmoitukset päälle!",footer:"Tuotettu Sábhia AI:lla"},er={pt:$i,en:Us,es:Ei,fr:Ii,de:Ri,it:Fi,ar:Vi,hi:Di,ja:Oi,zh:Li,ko:qi,ru:Bi,tr:_i,pl:Ui,nl:Hi,id:Gi,vi:Ki,th:Qi,uk:Yi,ro:Wi,el:Ji,cs:Xi,fi:Zi};function tr(a){return String(a||"").toLowerCase().trim().split(/[-_]/)[0]||""}function Ha(a){return er[tr(a)]||Us}function Es(a,i="long"){const b=Ha(a),u=i==="short"?b.transparencyBodyShort:b.transparencyBodyLong;return`${b.transparencyHeading}
25${u}`}const Qa=1.5,Ya=4.5,ar=3,Wa=1.9,Ja=5.3,Ga=3.5,qe=30,Hs=32,Lt=Math.max(Hs,48);function Gs(a){let i=a>>>0;return function(){i|=0,i=i+1831565813|0;let b=Math.imul(i^i>>>15,1|i);return b=b+Math.imul(b^b>>>7,61|b)^b,((b^b>>>14)>>>0)/4294967296}}function Ks(a,i){const b=`${a}:${i}`;let u=2166136261;for(let w=0;w<b.length;w++)u^=b.charCodeAt(w),u=Math.imul(u,16777619);return u>>>0}function sr(a,i){const b=Math.ceil(Qa*qe),u=Math.floor(Ya*qe);if(!Number.isFinite(a)||b<1||u<=b)return null;const w=i>=2&&a>=i*b;if(a<=u&&!w)return null;const v=Math.max(1,Math.ceil(a/u)),p=Math.max(1,Math.floor(a/b));if(v>Lt)return null;const l=Math.round(a/(ar*qe));let g=Math.max(v,Math.min(l,Math.min(p,Hs)));i>=2&&(g=Math.max(g,Math.min(i,p,Lt))),g<2&&(g=2),g>Lt&&(g=Lt);const C=Gs(Ks(`plan-${a}`,g)),T=[];for(let I=0;I<g;I++){const y=g>1?.45+I/(g-1)*1.1:1,L=.82+C()*.36;T.push(y*L)}const j=T.reduce((I,y)=>I+y,0)||1,N=T.map(I=>Math.max(b,Math.min(u,Math.round(I/j*a))));let x=a-N.reduce((I,y)=>I+y,0),S=0;for(;x!==0&&S++<2e5;)if(x>0){let I=!1;for(let y=g-1;y>=0&&x>0;y--)N[y]<u&&(N[y]++,x--,I=!0);I||(N[g-1]+=x,x=0)}else{let I=!1;for(let y=0;y<g&&x<0;y++)N[y]>b&&(N[y]--,x++,I=!0);I||(N[g-1]+=x,x=0)}return N.length>=2?N:null}function nr(a,i=0){if(!(a>0))return[];const b=Math.round(a*qe),u=sr(b,i);return u?u.map(w=>w/qe):[Math.min(Math.max(a,Qa),Ya)]}const ir=12;function rr(a){if(!(a>0)||a<=Ga)return 1;const i=Math.ceil(a/Ga);return Math.max(2,Math.min(ir,i))}function or(a,i){const b=Math.max(1,Math.ceil(Wa*qe)),u=Math.max(b+1,Math.floor(Ja*qe)),w=Math.max(1,Math.round(Ga*qe)),v=Number.isFinite(a)&&a>=1?Math.round(a):1;if(i<2||v<2*b)return[v];const p=Math.max(1,Math.floor(v/b));let l=Math.round(v/w);if(l=Math.max(1,Math.min(l,i,p,Lt)),l<2)return[v];const g=Math.ceil(v/l),C=Math.max(u,g+Math.round(.5*qe)),T=Gs(Ks(`v2plan-${v}`,l)),j=[];for(let y=0;y<l;y++){const L=l>1?.6+y/(l-1)*.8:1,z=.85+T()*.3;j.push(L*z)}const N=j.reduce((y,L)=>y+L,0)||1,x=j.map(y=>Math.max(b,Math.min(C,Math.round(y/N*v))));let S=v-x.reduce((y,L)=>y+L,0),I=0;for(;S!==0&&I++<2e5;)if(S>0){let y=!1;for(let L=l-1;L>=0&&S>0;L--)x[L]<C&&(x[L]++,S--,y=!0);y||(x[l-1]+=S,S=0)}else{let y=!1;for(let L=0;L<l&&S<0;L++)x[L]>b&&(x[L]--,S++,y=!0);y||(x[l-1]+=S,S=0)}return x.length>=2?x:[v]}function lr(a,i){if(!(a>0))return[];const b=Math.round(a*qe),u=rr(a),w=or(b,u);return w.length<2?[Math.min(Math.max(a,Wa),Ja)]:w.map(v=>v/qe)}function dr(a){const i=(a||"").trim();return i?gi.find(b=>b.id===i)?.label||i:"—"}const lt=480;function Dt(a){const i=Math.max(0,Math.round(a||0)),b=Math.floor(i/3600),u=Math.floor(i%3600/60),w=i%60;return b>0?`${b}:${String(u).padStart(2,"0")}
25:${String(w).padStart(2,"0")}`:`${u}:${String(w).padStart(2,"0")}`}const cr={ar:"arabic",fa:"arabic",ur:"arabic",de:"germanic"},mr={arabic:"Árabe / Oriente Médio",germanic:"Germânico / Europa Central"},Is={resolution:.3,conclusion:.3,outro:.28,ending:.3,calm:.28,reflection:.34,setup:.42,context:.42,background:.4,intro:.5,exposition:.46,cta:.44,payoff:.58,justice:.62,hook:.64,development:.54,discovery:.7,revelation:.78,twist:.84,rising:.82,buildup:.82,tension:.88,injustice:.8,conflict:.86,confrontation:.9,escalation:.92,climax:.96};function ur(a){const i=String(a||"").toLowerCase().trim().split(/[-_]/)[0]||"";return cr[i]||""}function xr(a){const i=String(a||"").toLowerCase().trim();return i&&Object.prototype.hasOwnProperty.call(Is,i)?Is[i]:.5}function pr(a){const i=String(a||"").toLowerCase().trim();return i?{hook:"Gancho",intro:"Abertura",setup:"Preparação",context:"Contexto",exposition:"Exposição",development:"Desenvolv.",background:"Contexto",discovery:"Descoberta",revelation:"Revelação",twist:"Virada",rising:"Tensão",buildup:"Tensão",tension:"Tensão",injustice:"Injustiça",conflict:"Conflito",confrontation:"Confronto",escalation:"Escalada",climax:"Clímax",payoff:"Recompensa",justice:"Justiça",resolution:"Resolução",conclusion:"Conclusão",reflection:"Reflexão",calm:"Calmaria",outro:"Encerr.",ending:"Final",cta:"CTA"}[i]||i:"—"}function ca(a){const i=Number(a.metadata?.shotIndex);return Number.isFinite(i)&&i>0?Math.floor(i):0}const Rs={draft:{label:"Rascunho",cls:"bg-zinc-600/20 text-zinc-300 border-zinc-600/30"},script_generating:{label:"Gerando roteiro…",cls:"bg-blue-500/15 text-blue-300 border-blue-500/25",spin:!0},script_ready:{label:"Roteiro pronto",cls:"bg-sky-500/15 text-sky-300 border-sky-500/25"},awaiting_script_approval:{label:"Roteiro pronto — revise e gere o vídeo",cls:"bg-cyan-500/15 text-cyan-200 border-cyan-500/30"},assets_generating:{label:"Gerando imagens…",cls:"bg-blue-500/15 text-blue-300 border-blue-500/25",spin:!0},assets_ready:{label:"Imagens prontas",cls:"bg-sky-500/15 text-sky-300 border-sky-500/25"},takes_generating:{label:"Gerando cenas em vídeo…",cls:"bg-blue-500/15 text-blue-300 border-blue-500/25",spin:!0},takes_ready:{label:"Cenas em vídeo prontas",cls:"bg-sky-500/15 text-sky-300 border-sky-500/25"},narration_generating:{label:"Gerando narração…",cls:"bg-blue-500/15 text-blue-300 border-blue-500/25",spin:!0},ready_for_review:{label:"Pronto para revisão",cls:"bg-cyan-500/15 text-cyan-300 border-cyan-500/25"},awaiting_human_quality_review:{label:"Aguardando revisão humana de qualidade",cls:"bg-amber-500/15 text-amber-200 border-amber-500/30"},rendering:{label:"Renderizando…",cls:"bg-blue-500/15 text-blue-300 border-blue-500/25",spin:!0},completed:{label:"Concluído",cls:"bg-emerald-500/15 text-emerald-300 border-emerald-500/25"},failed:{label:"Falhou",cls:"bg-red-500/15 text-red-300 border-red-500/25"}},na={documentary:"Documental",mysterious:"Misteriosa",epic:"Épica",calm:"Calma",uplifting:"Inspiradora",tense:"Tensa"},qa={chunks:"Dinâmicas (poucas palavras por vez)",scene:"Cena inteira"};function hr(a){if(!a||typeof a!="string")return null;const i=a.match(/^(\d+)\s*[x×]\s*(\d+)$/i);if(!i)return null;const b=Number(i[1]),u=Number(i[2]);if(!Number.isFinite(b)||!Number.isFinite(u)||b<=0||u<=0)return null;const w=Math.min(b,u);return w>=2160?"4K Ultra HD":w>=1440?"2K · 1440p":w>=1080?"Full HD · 1080p":w>=720?"HD · 720p":`${w}p`}const Qs=new Set(["script_generating","assets_generating","takes_generating","takes_ready","narration_generating","rendering"]),br=new Set(["ready_for_review","completed","failed","rendered","published"]);function Fs(a){if(!a||a<=0)return"";const i=Math.round(a/1e3),b=Math.floor(i/60),u=i%60;return b>0?`${b}:${String(u).padStart(2,"0")}`:`${u}s`}const gr={preparing:"Preparando a montagem…",downloading:"Baixando os clipes de vídeo…",scenes:"Montando as cenas",assembling:"Aplicando transições",music:"Mixando a trilha sonora",uploading:"Finalizando o MP4",completed:"Concluído"};function fr(a){if(!a||!a.phase)return 0;const i=Math.max(1,a.total||1),b=Math.min(i,Math.max(0,a.current||0));switch(a.phase){case"preparing":return 4;case"downloading":return 1+Math.round(b/i*4);case"scenes":return 6+Math.round(b/i*74);case"assembling":return 84;case"music":return 90;case"uploading":return 96;case"completed":return 100;default:return 6}}function Vs(a){return a?Qs.has(a.project?.status)?!0:(a.jobs||[]).some(i=>i.status==="pending"||i.status==="running"):!1}function vr({projectId:a,initialCta:i,detailKey:b}){const{toast:u}
25=nt(),w=Ct(),[v,p]=o.useState(i||""),[l,g]=o.useState(!1);o.useEffect(()=>{l||p(i||"")},[i,l]);const C=N=>N.replace(/\s+/g," ").trim(),T=C(v)!==C(i||""),j=U({mutationFn:async()=>(await R("PATCH",`/api/videos/projects/${a}/cta`,{ctaText:C(v)})).json(),onSuccess:N=>{g(!1),w.invalidateQueries({queryKey:b}),u({title:N?.ctaText?"CTA do Reel salva ✨":"CTA removida",description:N?.ctaText?'Ela será queimada na cena final no próximo render (use "Renderizar novamente").':"O card de CTA some no próximo render."})},onError:N=>{u({title:"Não deu para salvar a CTA",description:N?.message||"Tente novamente.",variant:"destructive"})}});return e.jsxs("div",{className:"rounded-2xl bg-gradient-to-br from-cyan-500/[0.07] to-sky-500/[0.03] border border-cyan-400/20 p-4","data-testid":"panel-reel-cta-editor",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[11px] font-semibold text-cyan-300 uppercase tracking-wider",children:"📣 CTA escrita na tela (cena final)"}),e.jsxs("button",{onClick:()=>j.mutate(),disabled:!T||j.isPending||C(v).length>0&&C(v).length<3,className:"flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-medium text-cyan-200 bg-cyan-500/10 hover:bg-cyan-500/20 border border-cyan-400/30 transition-colors disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"button-save-reel-cta",children:[j.isPending?e.jsx(f,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ma,{className:"h-3.5 w-3.5"}),C(v)?"Salvar CTA":"Remover CTA"]})]}),e.jsx(hi,{value:v,onChange:N=>{g(!0),p(N)}}),e.jsx("p",{className:"mt-2 text-[11px] text-cyan-300/70",children:'A CTA nunca é falada: ela aparece escrita na tela nos segundos finais. Depois de salvar, clique em "Renderizar novamente" para aplicar — as cenas e a narração não são regeneradas.'})]})}function yr({projectId:a,initialSpeed:i,detailKey:b}){const{toast:u}=nt(),w=Ct(),[v,p]=o.useState(i),[l,g]=o.useState(!1);o.useEffect(()=>{l||p(i)},[i,l]);const C=Math.abs(v-i)>=.001,T=U({mutationFn:async()=>(await R("PATCH",`/api/videos/projects/${a}/speed`,{targetSpeed:v})).json(),onSuccess:()=>{g(!1),w.invalidateQueries({queryKey:b}),u({title:"Velocidade salva",description:`${v.toFixed(2)}x será aplicada no próximo render (use "Renderizar novamente") — TTS e imagens não são regenerados.`})},onError:j=>{u({title:"Erro ao salvar velocidade",description:j?.message||"Tente novamente.",variant:"destructive"})}});return e.jsxs("div",{className:"rounded-2xl bg-gradient-to-br from-sky-500/[0.05] to-cyan-500/[0.03] border border-sky-400/20 p-4","data-testid":"panel-video-speed-editor",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2",children:[e.jsx("span",{className:"text-[11px] font-semibold text-sky-300 uppercase tracking-wider",children:"⚡ Velocidade da narração"}),e.jsxs("span",{className:"text-[11px] font-semibold text-sky-300","data-testid":"text-current-speed",children:[v.toFixed(2),"x"]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-3",children:[1,1.05,1.1,1.15,1.2,1.25,1.3,1.35,1.4,1.45,1.5].map(j=>{const N=Math.abs(v-j)<.001;return e.jsxs("button",{type:"button",onClick:()=>{g(!0),p(j)},className:`rounded-lg border px-2 py-1 text-[11px] font-semibold transition-colors ${N?"border-sky-400/50 bg-sky-500/[0.14] text-sky-200":"border-white/10 bg-black/20 text-zinc-400 hover:border-white/20"}`,"data-testid":`button-speed-${String(j).replace(".","-")}`,children:[j.toFixed(2),"x",j===1.25?" · padrão":""]},j)})}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-[11px] text-sky-300/60",children:'Aceleração física via FFmpeg. Salve e clique "Renderizar novamente" para aplicar.'}),e.jsxs("button",{onClick:()=>T.mutate(),disabled:!C||T.isPending,className:"flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-medium text-sky-200 bg-sky-500/10 hover:bg-sky-500/20 border border-sky-400/30 transition-colors disabled:opacity-40 disabled:cursor-not-allowed shrink-0","data-testid":"button-save-speed",children:[T.isPending?e.jsx(f,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ma,{className:"h-3.5 w-3.5"}),"Salvar velocidade"]})]})]})}const ia=2200,jr={not_configured:"A publicação no Instagram ainda não está disponível.",not_professional:"Sua conta do Instagram precisa ser Profissional (Business ou Criador de conteúdo). Mude em Configurações → Tipo de conta no app do Instagram e conecte de novo.",insufficient_scope:"Você não autorizou a permissão de publicar. Conecte de novo e aceite todas as permissões.",access_de
25nied:"Você cancelou a conexão com o Instagram.",denied:"Você cancelou a conexão com o Instagram.",session:"Sua sessão expirou. Entre de novo e tente conectar.",bad_state:"A conexão expirou por segurança. Tente de novo.",bad_nonce:"A conexão expirou por segurança. Tente de novo.",uid_mismatch:"A conexão foi iniciada em outra conta. Tente de novo."},Nr=a=>jr[a]||"Não foi possível conectar ao Instagram. Tente de novo em instantes.";function Xa({open:a,onOpenChange:i,platform:b,destination:u,onConfirm:w,testId:v}){return e.jsx(ri,{open:a,onOpenChange:i,children:e.jsxs(oi,{className:"max-w-md rounded-2xl border-white/10 bg-[#0b1322] text-zinc-100",children:[e.jsxs(li,{children:[e.jsxs(di,{className:"flex items-center gap-2 text-zinc-100",children:[e.jsx(kt,{className:"h-5 w-5 text-cyan-300"}),"Publicar no ",b," agora?"]}),e.jsxs(ci,{className:"text-zinc-400",children:[u?e.jsxs(e.Fragment,{children:["O vídeo vai ao ar em ",e.jsx("span",{className:"font-medium text-zinc-200",children:u})," em alguns minutos."]}):e.jsx(e.Fragment,{children:"O vídeo vai ao ar no seu perfil em alguns minutos."})," ","Essa ação publica de verdade — confirme só se você quer postar agora."]})]}),e.jsxs(mi,{children:[e.jsx(ui,{className:"border-white/10 bg-white/[0.04] text-zinc-300 hover:bg-white/[0.08] hover:text-zinc-100","data-testid":`button-cancel-${v}`,children:"Cancelar"}),e.jsx(xi,{onClick:w,className:"bg-gradient-to-r from-cyan-500 to-blue-500 text-white hover:opacity-95","data-testid":`button-confirm-${v}`,children:"Sim, quero publicar agora"})]})]})})}const ua=3*36e5,Ys=[{label:"Manhã",emoji:"🌅",hours:[7,9]},{label:"Almoço",emoji:"☀️",hours:[12]},{label:"Tarde",emoji:"🌆",hours:[18,20]}];function at(a){const i=typeof a=="string"?new Date(a):a;return isNaN(i.getTime())?"":i.toLocaleString("pt-BR",{timeZone:"America/Sao_Paulo",weekday:"short",day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})}function dt(a=0){const i=new Date(Date.now()-ua);return new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate()+a)).toISOString().slice(0,10)}function zt(a,i){const[b,u,w]=a.split("-").map(Number);return new Date(Date.UTC(b,u-1,w,i)+ua)}function Ws(a){const i=dt(a),[,b,u]=i.split("-");return`${u}/${b}`}const wr=["Hoje","Amanhã","Depois de amanhã"];function kr({projectId:a,defaultCaption:i,igPubs:b,igJobActive:u,detailKey:w}){const{toast:v}=nt(),p=Ct(),g=Ge({queryKey:["/api/videos/instagram/status"]}).data,[C,T]=o.useState(!1),[j,N]=o.useState(!1),x=async()=>{if(g?.diag?.redirectUri)try{await navigator.clipboard.writeText(g.diag.redirectUri),T(!0),setTimeout(()=>T(!1),2e3)}catch{v({title:"Não foi possível copiar",description:"Selecione a URL manualmente.",variant:"destructive"})}};o.useEffect(()=>{const n=new URLSearchParams(window.location.search),$=n.get("ig"),_=n.get("ig_error");
25if(!$&&!_)return;$==="connected"?(v({title:"Instagram conectado! 🎉",description:"Agora você pode publicar seus Reels direto daqui."}),p.invalidateQueries({queryKey:["/api/videos/instagram/status"]})):_&&v({title:"Conexão com o Instagram falhou",description:Nr(_),variant:"destructive"}),n.delete("ig"),n.delete("ig_error");const Y=n.toString();window.history.replaceState({},"",`${window.location.pathname}${Y?`?${Y}`:""}`)},[]);const[S,I]=o.useState(i||""),[y,L]=o.useState(!1);o.useEffect(()=>{y||I(i||"")},[i,y]);const[z,O]=o.useState(null),[P,V]=o.useState(""),[H,G]=o.useState(null),[B,Q]=o.useState(""),oe=o.useRef(null),he=o.useCallback(()=>{O(null),G(null),Q(""),V("")},[]),se=Ge({queryKey:["/api/videos/instagram/scheduled-slots"],enabled:!!g?.connected,staleTime:3e4,refetchInterval:6e4}),Z=o.useMemo(()=>(se.data?.slots||[]).map(n=>new Date(n)),[se.data]),ee=o.useMemo(()=>z===null?null:z==="custom"?P||null:dt(z),[z,P]),r=o.useMemo(()=>{if(z===null||!ee)return null;if(H!==null){const n=zt(ee,H);return n.getTime()>Date.now()+6e4?n:null}if(B){const n=B.split(":").map(Number),$=n[0],_=n[1];if(!isNaN($)&&!isNaN(_)){const[Y,pe,Re]=ee.split("-").map(Number),ve=new Date(Date.UTC(Y,pe-1,Re,$,_)+ua);return ve.getTime()>Date.now()+6e4?ve:null}}return null},[z,ee,H,B]),be=o.useCallback((n,$)=>{const _=zt(n,$).getTime();return Z.some(Y=>Math.abs(Y.getTime()-_)<30*6e4)},[Z]),te=o.useCallback((n,$)=>zt(n,$).getTime()<Date.now()+5*6e4,[]),A=U({mutationFn:async()=>(await R("POST",`/api/videos/projects/${a}/publish-instagram`,{caption:S.slice(0,ia),...r?{scheduledPublishAt:r.toISOString()}:{}})).json(),onSuccess:n=>{n?.scheduled||n?.alreadyScheduled?(v({title:n?.alreadyScheduled?"Este Reel já tem agendamento":"Reel agendado! 🗓️",description:n?.scheduledAt?`Publicação automática ${at(n.scheduledAt)} (horário de Brasília). Pode fechar a tela.`:"A publicação sai sozinha no horário marcado."}),he(),p.invalidateQueries({queryKey:["/api/videos/instagram/scheduled-slots"]})):v({title:n?.alreadyPublished?"Reel já publicado":n?.alreadyQueued?"Publicação já está na fila":"Publicando no Instagram 🚀",description:n?.alreadyPublished?"Ele já está no seu perfil.":"Estamos enviando o Reel para o seu perfil. Isso leva alguns minutos."}),p.invalidateQueries({queryKey:w})},onError:n=>v({title:"Não foi possível publicar",description:n?.message,variant:"destructive"})}),de=U({mutationFn:async n=>(await R("DELETE",`/api/videos/projects/${a}/publications/${n}`)).json(),onSuccess:()=>{v({title:"Agendamento cancelado",description:"O Reel não será publicado automaticamente. Você pode publicar agora ou reagendar."}),p.invalidateQueries({queryKey:w})},onError:n=>v({title:"Não foi possível cancelar",description:n?.message||"Tente de novo em instantes.",variant:"destructive"})}),ge=U({mutationFn:async()=>(await R("POST","/api/videos/instagram/disconnect",{})).json(),onSuccess:()=>{v({title:"Instagram desconectado",description:"Você pode conectar de novo quando quiser."}),p.invalidateQueries({queryKey:["/api/videos/instagram/status"]})},onError:n=>v({title:"Não foi possível desconectar",description:n?.message,variant:"destructive"})});if(!g||!g.configured)return null;const le=b.find(n=>n.status==="published"&&n.externalId)||null,je=u||A.isPending||b.some(n=>n.status==="uploading"),me=!le&&!je&&b.find(n=>n.status==="pending_schedule")||null,h=!le&&!je&&!me&&b.find(n=>n.status==="failed")||null,W=`/api/videos/instagram/connect?returnTo=${encodeURIComponent(`/videos/projetos/${a}`)}`;return e.jsxs("div",{className:"rounded-2xl bg-gradient-to-br from-fuchsia-500/[0.10] via-pink-500/[0.06] to-purple-500/[0.08] border border-fuchsia-400/25 p-4 space-y-3","data-testid":"panel-instagram-publish",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"inline-flex h-7 w-7 items-center justify-center rounded-lg bg-gradient-to-br from-fuchsia-500 to-pink-500 shrink-0",children:e.jsx($s,{className:"h-4 w-4 text-white"})}),e.jsx("span",{className:"text-sm font-semibold text-zinc-100",children:"Publicar no Instagram"})]}),g.connected&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-xs text-fuchsia-200/90 font-medium truncate max-w-[180px]","data-testid":"text-ig-username",children:["@",g.username||"conectado"]}),e.jsx("button",{onClick:()=>ge.mutate(),disabled:ge.isPending||je,className:"text-[11px] text-zinc-500 hover:text-zinc-300 underline underline-offset-2 disabled:opacity-50","data-testid":"button-ig-disconnect",children:"desconectar"})]})]}),g.connected?le?e.jsxs("div",{className:"flex flex-wrap items-center gap-3","data-testid":"status-ig-published",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-emerald-500/15 border border-emerald-500/25 px-3 py-1 text-xs font-medium text-emerald-300",children:[e.jsx(ue,{className:"h-3.5 w-3.5"})," Publicado no Instagram"]}),le.url&&e.jsxs("a",{href:le.url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 text-sm font-medium text-fuchsia-300 hover:text-fuchsia-200","data-testid":"link-ig-permalink",children:["Ver no Instagram ",e.jsx(la,{className:"h-3.5 w-3.5"})]})]}):je?e.jsxs("div",{className:"flex items-center gap-2.5 text-sm text-fuchsia-200","data-testid":"status-ig-uploading",children:[e.jsx(f,{className:"h-4 w-4 animate-spin shrink-0"}),"Publicando seu Reel… isso leva alguns minutos. Pode sair desta tela — a publicação continua sozinha."]}):me?e.jsxs("div",{className:"space-y-2.5","data-testid":"status-ig-scheduled",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-amber-500/15 border border-amber-500/25 px-3 py-1 text-xs font-medium text-amber-300",children:[e.jsx(St,{className:"h-3.5 w-3.5"}),"Agendado ",me.scheduledAt?`para ${at(me.scheduledAt)}`:""]}),e.jsx("button",{onClick:()=>de.mutate(me.id),disabled:de.isPending,className:"text-[11px] text-zinc-500 hover:text-zinc-300 underline underline-offset-2 disabled:opacity-50","data-testid":"button-ig-cancel-schedule",children:de.isPending?"cancelando…":"cancelar agendamento"})]}),e.jsx("p",{className:"text-[11px] text-zinc-500",children:"A publicação sai sozinha no horário marcado (horário de Brasília) — não precisa deixar a tela aberta."})]}):e.jsxs("div",{className:"space-y-2.5",children:[h&&e.jsxs("div",{className:"flex items-start gap-2 rounded-xl bg-red-500/[0.08] border border-red-500/20 px-3 py-2.5","data-testid":"status-ig-failed",children:[e.jsx(Ce,{className:"h-4 w-4 text-red-400 shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-red-300",children:h.metadata?.error||"A publicação falhou. Revise a legenda e tente de novo."})]}),h&&(()=>{const n=h.metadata||{},$=n.retryNextAt?new Date(String(n.retryNextAt)):null,_=Number(n.retryAttempts)||0;return $&&!isNaN($.getTime())?e.jsxs("div",{className:"flex items-start gap-2 rounded-xl bg-fuchsia-500/[0.08] border border-fuchsia-500/25 px-3 py-2.5","data-testid":"status-ig-auto-retry",children:[e.jsx(Te,{className:"h-4 w-4 text-fuchsia-300 shrink-0 mt-0.5"}),e.jsxs("p",{className:"text-xs text-fuchsia-200/90",children:["Nova tentativa automática às ",at($),_>0?` — tentativa ${_}`:"",". Você não precisa fazer nada."]})]}):_>0?e.jsxs("p",{className:"text-[11px] text-zinc-500","data-testid":"text-ig-retry-exhausted",children:["Fizemos ",_," ",_>1?"tentativas automáticas":"tentativa automática"," sem sucesso — tente publicar de novo pelo botão."]}):null})(),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("span",{className:"text-[11px] font-semibold text-fuchsia-300/90 uppercase tracking-wider",children:"Legenda"}),e.jsxs("span",{className:`text-[11px] ${S.length>ia?"text-red-400":"text-zinc-500"}
25`,children:[S.length.toLocaleString("pt-BR"),"/",ia.toLocaleString("pt-BR")]})]}),e.jsx(wt,{value:S,onChange:n=>{L(!0),I(n.target.value)},rows:5,className:"bg-black/30 border-white/10 text-sm text-zinc-200 placeholder:text-zinc-600 focus-visible:ring-fuchsia-500/40",placeholder:"Escreva a legenda do seu Reel…","data-testid":"input-ig-caption"})]}),e.jsxs("div",{className:"rounded-xl border border-white/[0.07] bg-black/20 px-3 py-2.5 space-y-2.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(St,{className:"h-3.5 w-3.5 text-fuchsia-300/80"}),e.jsx("span",{className:"text-[11px] font-semibold text-fuchsia-300/90 uppercase tracking-wider",children:"Quando publicar"})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsx("button",{type:"button",onClick:()=>{O(null),G(null),Q(""),V("")},className:`rounded-lg px-2.5 py-1.5 text-[11px] font-medium border transition-colors ${z===null?"bg-fuchsia-500/20 border-fuchsia-400/40 text-fuchsia-100":"bg-white/[0.03] border-white/10 text-zinc-400 hover:text-zinc-200"}`,"data-testid":"chip-ig-now",children:"Agora"}),[0,1,2].map(n=>e.jsxs("button",{type:"button",onClick:()=>{O(n),G(null),Q("")},className:`rounded-lg px-2.5 py-1.5 text-[11px] font-medium border transition-colors ${z===n?"bg-fuchsia-500/20 border-fuchsia-400/40 text-fuchsia-100":"bg-white/[0.03] border-white/10 text-zinc-400 hover:text-zinc-200"}`,"data-testid":`chip-ig-day-${n}`,children:[wr[n],", ",Ws(n)]},n)),e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",onClick:()=>{const n=oe.current;if(n)try{typeof n.showPicker=="function"?n.showPicker():(n.focus(),n.click())}catch{}},className:`rounded-lg px-2.5 py-1.5 text-[11px] font-medium border transition-colors ${z==="custom"&&P?"bg-fuchsia-500/20 border-fuchsia-400/40 text-fuchsia-100":"bg-white/[0.03] border-white/10 text-zinc-400 hover:text-zinc-200"}`,"data-testid":"chip-ig-day-custom",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qs,{className:"h-3 w-3"}),z==="custom"&&P?(()=>{const[,n,$]=P.split("-");return`${$}/${n}`})():"📅 Outra data"]})}),e.jsx("input",{ref:oe,type:"date",value:P,min:dt(0),max:dt(30),onChange:n=>{V(n.target.value),n.target.value&&(O("custom"),G(null),Q(""))},className:"absolute inset-0 opacity-0 w-full h-full -z-10",tabIndex:-1,"aria-hidden":"true","data-testid":"input-ig-custom-date"})]})]}),z!==null&&ee&&e.jsxs("div",{className:"space-y-1.5 pt-1.5 border-t border-white/[0.06]",children:[Ys.map(({label:n,emoji:$,hours:_})=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("span",{className:"w-[52px] shrink-0 text-[10px] font-medium text-zinc-600 select-none pt-1.5",children:[$," ",n]}),e.jsx("div",{className:"flex flex-wrap gap-x-1.5 gap-y-2",children:_.map(Y=>{const pe=te(ee,Y),Re=H===Y&&!B,ve=!pe&&be(ee,Y);return e.jsxs("div",{className:"flex flex-col items-center gap-0.5",children:[e.jsxs("button",{type:"button",disabled:pe,onClick:()=>{G(Y),Q("")},className:`rounded-lg px-2.5 py-1.5 text-[11px] font-medium border transition-colors ${pe?"opacity-30 cursor-not-allowed bg-white/[0.02] border-white/5 text-zinc-600":Re?"bg-fuchsia-500/20 border-fuchsia-400/40 text-fuchsia-100":ve?"bg-amber-500/[0.08] border-amber-500/25 text-zinc-300 hover:border-amber-400/40":"bg-white/[0.03] border-white/10 text-zinc-400 hover:text-zinc-200"}`,"data-testid":`chip-ig-slot-${Y}`,children:[String(Y).padStart(2,"0"),":00"]}),ve&&e.jsx("span",{className:"text-[9px] text-amber-400/80 font-medium leading-none whitespace-nowrap",children:"Já programado"})]},Y)})})]},n)),e.jsxs("div",{className:"flex items-center gap-2 pt-0.5",children:[e.jsx("span",{className:"w-[52px] shrink-0 text-[10px] font-medium text-zinc-600 select-none",children:"🕐 Outro"}),e.jsx("input",{type:"time",value:B,onChange:n=>{Q(n.target.value),G(null)},className:"rounded-lg bg-white/[0.03] border border-white/10 px-2 py-1.5 text-[11px] text-zinc-300 focus:outline-none focus:border-fuchsia-400/40 [color-scheme:dark]","data-testid":"input-ig-schedule-custom"})]})]}),r&&e.jsxs("p",{className:"text-[11px] text-amber-300/90","data-testid":"text-ig-schedule-preview",children:["Vai ao ar ",at(r)," (horário de Brasília). Publicação 100% automática."]}),z!==null&&!r&&e.jsx("p",{className:"text-[11px] text-zinc-500",children:"Escolha um horário para agendar a publicação."})]}),e.jsxs("button",{onClick:()=>r?A.mutate():N(!0),disabled:A.isPending||S.length>ia||z!==null&&r===null,className:"inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-fuchsia-600 to-pink-500 px-4 py-2.5 text-sm font-semibold text-white shadow-lg shadow-fuchsia-900/40 hover:opacity-95 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"button-ig-publish",children:[A.isPending?e.jsx(f,{className:"h-4 w-4 animate-spin"}):r?e.jsx(St,{className:"h-4 w-4"}):e.jsx(kt,{className:"h-4 w-4"}),r?"Agendar Reel":h?"Tentar publicar de novo":"Publicar Reel agora"]}),e.jsx(Xa,{open:j,onOpenChange:N,platform:"Instagram",destination:g?.username?`@${g.username}`:null,onConfirm:()=>{N(!1),A.mutate()},testId:"ig-publish"})]}):e.jsxs("div",{className:"space-y-2.5",children:[e.jsx("p",{className:"text-sm text-zinc-300",children:"Conecte o SEU Instagram (conta Profissional — Business ou Criador de conteúdo) e publique este Reel direto daqui, sem sair da plataforma."}),e.jsxs("a",{href:W,className:"inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-fuchsia-600 to-pink-500 px-4 py-2.5 text-sm font-semibold text-white shadow-lg shadow-fuchsia-900/40 hover:opacity-95","data-testid":"button-ig-connect",children:[e.jsx($s,{className:"h-4 w-4"})," Conectar meu Instagram"]}),e.jsx("p",{className:"text-[11px] text-zinc-500",children:"Não precisa de página do Facebook. Você autoriza direto no Instagram e pode desconectar quando quiser."}),g.diag?.redirectUri&&e.jsxs("div",{className:"rounded-xl border border-amber-400/25 bg-gradient-to-br from-amber-500/[0.08] via-black/20 to-black/10 px-3.5 py-3 space-y-2.5","data-testid":"panel-ig-admin-diag",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ka,{className:"h-3.5 w-3.5 text-amber-300"}),e.jsx("span",{className:"text-[11px] font-semibold text-amber-300 uppercase tracking-wider",children:"Configuração Meta (visível só para admin)"})]}),e.jsxs("p",{className:"text-xs text-zinc-300 leading-relaxed",children:["Se o Instagram mostrar ",e.jsx("span",{className:"font-medium text-amber-200",children:"“Invalid redirect_uri”"}),", a URL de callback abaixo precisa estar cadastrada ",e.jsx("span",{className:"font-medium",children:"exatamente igual"}
25)," (byte a byte, sem barra no final) no painel da Meta."]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"flex-1 min-w-0 truncate rounded-lg bg-black/40 border border-white/10 px-2.5 py-1.5 text-[11px] text-fuchsia-200 font-mono","data-testid":"text-ig-redirect-uri",children:g.diag.redirectUri}),e.jsxs("button",{type:"button",onClick:x,className:"inline-flex items-center gap-1.5 rounded-lg border border-amber-400/30 bg-amber-500/15 px-2.5 py-1.5 text-[11px] font-medium text-amber-200 hover:bg-amber-500/25 shrink-0","data-testid":"button-ig-copy-redirect-uri",children:[C?e.jsx(et,{className:"h-3 w-3"}):e.jsx(tt,{className:"h-3 w-3"}),C?"Copiado!":"Copiar"]})]}),e.jsxs("ol",{className:"list-decimal list-inside space-y-1 text-[11px] text-zinc-400 leading-relaxed",children:[e.jsxs("li",{children:["Abra"," ",e.jsx("a",{href:"https://developers.facebook.com/apps/",target:"_blank",rel:"noopener noreferrer",className:"text-fuchsia-300 hover:text-fuchsia-200 underline underline-offset-2",children:"developers.facebook.com/apps"})," ","e entre no app",g.diag.appIdTail?e.jsxs(e.Fragment,{children:[" com ID terminando em ",e.jsxs("span",{className:"font-mono text-zinc-300",children:["…",g.diag.appIdTail]})]}):null,"."]}),e.jsxs("li",{children:["No menu lateral: ",e.jsx("span",{className:"text-zinc-300",children:"Instagram → Configuração da API com login do Instagram"}),"."]}),e.jsxs("li",{children:["Em ",e.jsx("span",{className:"text-zinc-300",children:"“Configurações de login para empresas” (Business login settings)"}),", cole a URL acima em ",e.jsx("span",{className:"text-zinc-300",children:"“URIs de redirecionamento OAuth”"})," e salve."]}),e.jsx("li",{children:"Volte aqui e clique em “Conectar meu Instagram” de novo — sem precisar reiniciar nada."})]})]})]})]})}const ra=2200,Sr=["Hoje","Amanhã","Depois de amanhã"];function zr({projectId:a,defaultCaption:i,ttPubs:b,ttJobActive:u,detailKey:w}){const{toast:v}=nt(),p=Ct(),g=Ge({queryKey:["/api/videos/tiktok/status"]}).data,[C,T]=o.useState(!1),[j,N]=o.useState(!1),x=async()=>{if(g?.diag?.redirectUri)try{await navigator.clipboard.writeText(g.diag.redirectUri),T(!0),setTimeout(()=>T(!1),2e3)}catch{v({title:"Não foi possível copiar",description:"Selecione a URL manualmente.",variant:"destructive"})}};o.useEffect(()=>{const n=new URLSearchParams(window.location.search),$=n.get("tt"),_=n.get("tt_error");if(!$&&!_)return;$==="connected"?(v({title:"TikTok conectado! 🎉",description:"Agora você pode publicar seus vídeos direto daqui."}),p.invalidateQueries({queryKey:["/api/videos/tiktok/status"]})):_&&v({title:"Conexão com o TikTok falhou",description:{not_configured:"Recurso não configurado no servidor.",denied:"Você cancelou a conexão com o TikTok.",exchange:"Não foi possível obter o token do TikTok. Tente novamente.",profile_fetch:"Não foi possível obter o perfil do TikTok. Tente novamente.",no_account:"Nenhuma conta TikTok associada ao token.",bad_state:"Sessão expirada. Tente conectar de novo.",session:"Sessão expirada. Faça login novamente."}[_]||`Código: ${_}`,variant:"destructive"}),n.delete("tt"),n.delete("tt_error");const Y=n.toString();window.history.replaceState({},"",`${window.location.pathname}${Y?`?${Y}`:""}`)},[]);const[S,I]=o.useState(i||""),[y,L]=o.useState(!1);o.useEffect(()=>{y||I(i||"")},[i,y]);const[z,O]=o.useState(null),[P,V]=o.useState(""),[H,G]=o.useState(null),[B,Q]=o.useState(""),oe=o.useRef(null),he=o.useCallback(()=>{O(null),G(null),Q(""),V("")},[]),se=Ge({queryKey:["/api/videos/tiktok/scheduled-slots"],enabled:!!g?.connected,staleTime:3e4,refetchInterval:6e4}),Z=o.useMemo(()=>(se.data?.slots||[]).map(n=>new Date(n)),[se.data]),ee=o.useMemo(()=>z===null?null:z==="custom"?P||null:dt(z),[z,P]),r=o.useMemo(()=>{if(z===null||!ee)return null;if(H!==null){const n=zt(ee,H);return n.getTime()>Date.now()+6e4?n:null}if(B){const n=B.split(":").map(Number),$=n[0],_=n[1];if(!isNaN($)&&!isNaN(_)){const[Y,pe,Re]=ee.split("-").map(Number),ve=new Date(Date.UTC(Y,pe-1,Re,$,_)+ua);return ve.getTime()>Date.now()+6e4?ve:null}}return null},[z,ee,H,B]),be=o.useCallback((n,$)=>{const _=zt(n,$).getTime();return Z.some(Y=>Math.abs(Y.getTime()-_)<30*6e4)},[Z]),te=o.useCallback((n,$)=>zt(n,$).getTime()<Date.now()+5*6e4,[]),A=U({mutationFn:async()=>(await R("POST",`/api/videos/projects/${a}/publish-tiktok`,{caption:S.slice(0,ra),...r?{scheduledPublishAt:r.toISOString()}:{}})).json(),onSuccess:n=>{n?.scheduled||n?.alreadyScheduled?(v({title:n?.alreadyScheduled?"Este vídeo já tem agendamento":"Vídeo agendado! 🗓️",description:n?.scheduledAt?`Publicação automática ${at(n.scheduledAt)} (horário de Brasília). Pode fechar a tela.`:"A publicação sai sozinha no horário marcado."}),he(),p.invalidateQueries({queryKey:["/api/videos/tiktok/scheduled-slots"]})):v({title:n?.alreadyPublished?"Vídeo já publicado":n?.alreadyQueued?"Publicação já está na fila":"Publicando no TikTok 🚀",description:n?.alreadyPublished?"Ele já está no seu perfil.":"Estamos enviando o vídeo para o seu perfil. Isso leva alguns minutos."}),p.invalidateQueries({queryKey:w})},onError:n=>v({title:"Não foi possível publicar",description:n?.message,variant:"destructive"})}),de=U({mutationFn:async n=>(await R("DELETE",`/api/videos/projects/${a}/publications/${n}`)).json(),onSuccess:()=>{v({title:"Agendamento cancelado",description:"O vídeo não será publicado automaticamente. Você pode publicar agora ou reagendar."}),p.invalidateQueries({queryKey:w})},onError:n=>v({title:"Não foi possível cancelar",description:n?.message||"Tente de novo em instantes.",variant:"destructive"})}),ge=U({mutationFn:async()=>(await R("POST","/api/videos/tiktok/disconnect",{})).json(),onSuccess:()=>{v({title:"TikTok desconectado",description:"Você pode conectar de novo quando quiser."}),p.invalidateQueries({queryKey:["/api/videos/tiktok/status"]})},onError:n=>v({title:"Não foi possível desconectar",description:n?.message,variant:"destructive"})});if(!g||!g.configured)return null;const le=b.find(n=>n.status==="published"&&n.externalId)||null,je=u||A.isPending||b.some(n=>n.status==="uploading"),me=!le&&!je&&b.find(n=>n.status==="pending_schedule")||null,h=!le&&!je&&!me&&b.find(n=>n.status==="failed")||null,W=`/api/videos/tiktok/connect?returnTo=${encodeURIComponent(`/videos/projetos/${a}`)}`;return e.jsxs("div",{className:"rounded-2xl bg-gradient-to-br from-[#010101]/60 via-[#fe2c55]/[0.08] to-[#25f4ee]/[0.06] border border-[#25f4ee]/20 p-4 space-y-3","data-testid":"panel-tiktok-publish",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"inline-flex h-7 w-7 items-center justify-center rounded-lg bg-gradient-to-br from-[#010101] to-[#2a2a2a] border border-[#25f4ee]/30 shrink-0",children:e.jsxs("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[e.jsx("path",{d:"M19.59 6.69a4.83 4.83 0 0 1-3.77-4.25V2h-3.45v13.67a2.89 2.89 0 0 1-2.88 2.5 2.89 2.89 0 0 1-2.89-2.89 2.89 2.89 0 0 1 2.89-2.89c.28 0 .54.04.79.1V9.01a6.28 6.28 0 0 0-.79-.05 6.34 6.34 0 0 0-6.34 6.34 6.34 6.34 0 0 0 6.34 6.34 6.34 6.34 0 0 0 6.34-6.34V8.58a8.18 8.18 0 0 0 4.79 1.52V6.65a4.84 4.84 0 0 1-1.03.04z",fill:"#fe2c55"}),e.jsx("path",{d:"M19.59 6.69a4.83 4.83 0 0 1-3.77-4.25V2h-3.45v13.67a2.89 2.89 0 0 1-2.88 2.5 2.89 2.89 0 0 1-2.89-2.89 2.89 2.89 0 0 1 2.89-2.89c.28 0 .54.04.79.1V9.01a6.28 6.28 0 0 0-.79-.05 6.34 6.34 0 0 0-6.34 6.34 6.34 6.34 0 0 0 6.34 6.34 6.34 6.34 0 0 0 6.34-6.34V8.58a8.18 8.18 0 0 0 4.79 1.52V6.65a4.84 4.84 0 0 1-1.03.04z",fill:"white",fillOpacity:"0.07"})]})}),e.jsx("span",{className:"text-sm font-semibold text-zinc-100",children:"Publicar no TikTok"})]}),g.connected&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-xs text-[#25f4ee]/90 font-medium truncate max-w-[180px]","data-testid":"text-tt-username",children:["@",g.displayName||"conectado"]}),e.jsx("button",{onClick:()=>ge.mutate(),disabled:ge.isPending||je,className:"text-[11px] text-zinc-500 hover:text-zinc-300 underline underline-offset-2 disabled:opacity-50","data-testid":"button-tt-disconnect",children:"desconectar"})]})]}),g.connected?le?e.jsxs("div",{className:"flex flex-wrap items-center gap-3","data-testid":"status-tt-published",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-emerald-500/15 border border-emerald-500/25 px-3 py-1 text-xs font-medium text-emerald-300",children:[e.jsx(ue,{className:"h-3.5 w-3.5"})," Publicado no TikTok"]}),le.url&&e.jsxs("a",{href:le.url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 text-sm font-medium text-[#25f4ee] hover:text-[#25f4ee]/80","data-testid":"link-tt-permalink",children:["Ver no TikTok ",e.jsx(la,{className:"h-3.5 w-3.5"})]})]}):je?e.jsxs("div",{className:"flex items-center gap-2.5 text-sm text-[#25f4ee]/90","data-testid":"status-tt-uploading",children:[e.jsx(f,{className:"h-4 w-4 animate-spin shrink-0"}),"Publicando no TikTok… isso leva alguns minutos. Pode sair desta tela — a publicação continua sozinha."]}):me?e.jsxs("div",{className:"space-y-2.5","data-testid":"status-tt-scheduled",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-amber-500/15 border border-amber-500/25 px-3 py-1 text-xs font-medium text-amber-300",children:[e.jsx(St,{className:"h-3.5 w-3.5"}),"Agendado ",me.scheduledAt?`para ${at(me.scheduledAt)}`:""]}),e.jsx("button",{onClick:()=>de.mutate(me.id),disabled:de.isPending,className:"text-[11px] text-zinc-500 hover:text-zinc-300 underline underline-offset-2 disabled:opacity-50","data-testid":"button-tt-cancel-schedule",children:de.isPending?"cancelando…":"cancelar agendamento"})]}),e.jsx("p",{className:"text-[11px] text-zinc-500",children:"A publicação sai sozinha no horário marcado (horário de Brasília) — não precisa deixar a tela aberta."})]}):e.jsxs("div",{className:"space-y-2.5",children:[h&&e.jsxs("div",{className:"flex items-start gap-2 rounded-xl bg-red-500/[0.08] border border-red-500/20 px-3 py-2.5","data-testid":"status-tt-failed",children:[e.jsx(Ce,{className:"h-4 w-4 text-red-400 shrink-0 mt-0.5"}),e.jsx("p",{className:"text-xs text-red-300",children:h.metadata?.error||"A publicação falhou. Revise a legenda e tente de novo."})]}),h&&(()=>{const n=h.metadata||{},$=n.retryNextAt?new Date(String(n.retryNextAt)):null,_=Number(n.retryAttempts)||0;return $&&!isNaN($.getTime())?e.jsxs("div",{className:"flex items-start gap-2 rounded-xl bg-[#25f4ee]/[0.06] border border-[#25f4ee]/25 px-3 py-2.5","data-testid":"status-tt-auto-retry",children:[e.jsx(Te,{className:"h-4 w-4 text-[#25f4ee] shrink-0 mt-0.5"}),e.jsxs("p",{className:"text-xs text-[#25f4ee]/90",children:["Nova tentativa automática às ",at($),_>0?` — tentativa ${_}`:"",". Você não precisa fazer nada."]})]}):_>0?e.jsxs("p",{className:"text-[11px] text-zinc-500","data-testid":"text-tt-retry-exhausted",children:["Fizemos ",_," ",_>1?"tentativas automáticas":"tentativa automática"," sem sucesso — tente publicar de novo pelo botão."]}):null})(),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("span",{className:"text-[11px] font-semibold text-[#25f4ee]/90 uppercase tracking-wider",children:"Legenda / título"}),e.jsxs("span",{className:`text-[11px] ${S.length>ra?"text-red-400":"text-zinc-500"}
25`,children:[S.length.toLocaleString("pt-BR"),"/",ra.toLocaleString("pt-BR")]})]}),e.jsx(wt,{value:S,onChange:n=>{L(!0),I(n.target.value)},rows:4,className:"bg-black/30 border-white/10 text-sm text-zinc-200 placeholder:text-zinc-600 focus-visible:ring-[#25f4ee]/30",placeholder:"Escreva a legenda do seu vídeo TikTok…","data-testid":"input-tt-caption"})]}),e.jsxs("div",{className:"rounded-xl border border-white/[0.07] bg-black/20 px-3 py-2.5 space-y-2.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(St,{className:"h-3.5 w-3.5 text-[#25f4ee]/70"}),e.jsx("span",{className:"text-[11px] font-semibold text-[#25f4ee]/80 uppercase tracking-wider",children:"Quando publicar"})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsx("button",{type:"button",onClick:()=>{O(null),G(null),Q(""),V("")},className:`rounded-lg px-2.5 py-1.5 text-[11px] font-medium border transition-colors ${z===null?"bg-[#25f4ee]/15 border-[#25f4ee]/40 text-[#25f4ee]":"bg-white/[0.03] border-white/10 text-zinc-400 hover:text-zinc-200"}`,"data-testid":"chip-tt-now",children:"Agora"}),[0,1,2].map(n=>e.jsxs("button",{type:"button",onClick:()=>{O(n),G(null),Q("")},className:`rounded-lg px-2.5 py-1.5 text-[11px] font-medium border transition-colors ${z===n?"bg-[#25f4ee]/15 border-[#25f4ee]/40 text-[#25f4ee]":"bg-white/[0.03] border-white/10 text-zinc-400 hover:text-zinc-200"}`,"data-testid":`chip-tt-day-${n}`,children:[Sr[n],", ",Ws(n)]},n)),e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",onClick:()=>{const n=oe.current;if(n)try{typeof n.showPicker=="function"?n.showPicker():(n.focus(),n.click())}catch{}},className:`rounded-lg px-2.5 py-1.5 text-[11px] font-medium border transition-colors ${z==="custom"&&P?"bg-[#25f4ee]/15 border-[#25f4ee]/40 text-[#25f4ee]":"bg-white/[0.03] border-white/10 text-zinc-400 hover:text-zinc-200"}`,"data-testid":"chip-tt-day-custom",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qs,{className:"h-3 w-3"}),z==="custom"&&P?(()=>{const[,n,$]=P.split("-");return`${$}/${n}`})():"📅 Outra data"]})}),e.jsx("input",{ref:oe,type:"date",value:P,min:dt(0),max:dt(30),onChange:n=>{V(n.target.value),n.target.value&&(O("custom"),G(null),Q(""))},className:"absolute inset-0 opacity-0 w-full h-full -z-10",tabIndex:-1,"aria-hidden":"true","data-testid":"input-tt-custom-date"})]})]}),z!==null&&ee&&e.jsxs("div",{className:"space-y-1.5 pt-1.5 border-t border-white/[0.06]",children:[Ys.map(({label:n,emoji:$,hours:_})=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("span",{className:"w-[52px] shrink-0 text-[10px] font-medium text-zinc-600 select-none pt-1.5",children:[$," ",n]}),e.jsx("div",{className:"flex flex-wrap gap-x-1.5 gap-y-2",children:_.map(Y=>{const pe=te(ee,Y),Re=H===Y&&!B,ve=!pe&&be(ee,Y);return e.jsxs("div",{className:"flex flex-col items-center gap-0.5",children:[e.jsxs("button",{type:"button",disabled:pe,onClick:()=>{G(Y),Q("")},className:`rounded-lg px-2.5 py-1.5 text-[11px] font-medium border transition-colors ${pe?"opacity-30 cursor-not-allowed bg-white/[0.02] border-white/5 text-zinc-600":Re?"bg-[#25f4ee]/15 border-[#25f4ee]/40 text-[#25f4ee]":ve?"bg-amber-500/[0.08] border-amber-500/25 text-zinc-300 hover:border-amber-400/40":"bg-white/[0.03] border-white/10 text-zinc-400 hover:text-zinc-200"}`,"data-testid":`chip-tt-slot-${Y}`,children:[String(Y).padStart(2,"0"),":00"]}),ve&&e.jsx("span",{className:"text-[9px] text-amber-400/80 font-medium leading-none whitespace-nowrap",children:"Já programado"})]},Y)})})]},n)),e.jsxs("div",{className:"flex items-center gap-2 pt-0.5",children:[e.jsx("span",{className:"w-[52px] shrink-0 text-[10px] font-medium text-zinc-600 select-none",children:"🕐 Outro"}),e.jsx("input",{type:"time",value:B,onChange:n=>{Q(n.target.value),G(null)},className:"rounded-lg bg-white/[0.03] border border-white/10 px-2 py-1.5 text-[11px] text-zinc-300 focus:outline-none focus:border-[#25f4ee]/40 [color-scheme:dark]","data-testid":"input-tt-schedule-custom"})]})]}),r&&e.jsxs("p",{className:"text-[11px] text-amber-300/90","data-testid":"text-tt-schedule-preview",children:["Vai ao ar ",at(r)," (horário de Brasília). Publicação 100% automática."]}),z!==null&&!r&&e.jsx("p",{className:"text-[11px] text-zinc-500",children:"Escolha um horário para agendar a publicação."})]}),e.jsxs("button",{onClick:()=>r?A.mutate():N(!0),disabled:A.isPending||S.length>ra||z!==null&&r===null,className:"inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-[#fe2c55] to-[#25f4ee]/80 px-4 py-2.5 text-sm font-semibold text-white shadow-lg shadow-[#fe2c55]/20 hover:opacity-95 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"button-tt-publish",children:[A.isPending?e.jsx(f,{className:"h-4 w-4 animate-spin"}):r?e.jsx(St,{className:"h-4 w-4"}):e.jsx(kt,{className:"h-4 w-4"}),r?"Agendar para o TikTok":h?"Tentar publicar de novo":"Publicar no TikTok agora"]}),e.jsx(Xa,{open:j,onOpenChange:N,platform:"TikTok",destination:g?.displayName?`@${g.displayName}`:null,onConfirm:()=>{N(!1),A.mutate()},testId:"tt-publish"})]}):e.jsxs("div",{className:"space-y-2.5",children:[e.jsx("p",{className:"text-sm text-zinc-300",children:"Conecte o SEU TikTok e publique este vídeo direto daqui, sem sair da plataforma. Funciona com qualquer conta."}),e.jsxs("a",{href:W,className:"inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-[#fe2c55] to-[#25f4ee]/80 px-4 py-2.5 text-sm font-semibold text-white shadow-lg shadow-[#fe2c55]/20 hover:opacity-95","data-testid":"button-tt-connect",children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"white",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:e.jsx("path",{d:"M19.59 6.69a4.83 4.83 0 0 1-3.77-4.25V2h-3.45v13.67a2.89 2.89 0 0 1-2.88 2.5 2.89 2.89 0 0 1-2.89-2.89 2.89 2.89 0 0 1 2.89-2.89c.28 0 .54.04.79.1V9.01a6.28 6.28 0 0 0-.79-.05 6.34 6.34 0 0 0-6.34 6.34 6.34 6.34 0 0 0 6.34 6.34 6.34 6.34 0 0 0 6.34-6.34V8.58a8.18 8.18 0 0 0 4.79 1.52V6.65a4.84 4.84 0 0 1-1.03.04z"})}),"Conectar meu TikTok"]}),e.jsx("p",{className:"text-[11px] text-zinc-500",children:"Você autoriza direto no TikTok e pode desconectar quando quiser. Seus tokens ficam cifrados e nunca são compartilhados."}),g.diag?.redirectUri&&e.jsxs("div",{className:"rounded-xl border border-amber-400/25 bg-gradient-to-br from-amber-500/[0.08] via-black/20 to-black/10 px-3.5 py-3 space-y-2.5","data-testid":"panel-tt-admin-diag",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ka,{className:"h-3.5 w-3.5 text-amber-300"}),e.jsx("span",{className:"text-[11px] font-semibold text-amber-300 uppercase tracking-wider",children:"Configuração TikTok (visível só para admin)"})]}),e.jsxs("p",{className:"text-xs text-zinc-300 leading-relaxed",children:["Se o TikTok mostrar ",e.jsx("span",{className:"font-medium text-amber-200",children:'"Invalid redirect_uri"'}),", esta URL precisa estar cadastrada"," ",e.jsx("span",{className:"font-medium",children:"exatamente igual"})," no painel do app TikTok for Developers."]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"flex-1 min-w-0 truncate rounded-lg bg-black/40 border border-white/10 px-2.5 py-1.5 text-[11px] text-[#25f4ee] font-mono","data-testid":"text-tt-redirect-uri",children:g.diag.redirectUri}),e.jsxs("button",{type:"button",onClick:x,className:"inline-flex items-center gap-1.5 rounded-lg border border-amber-400/30 bg-amber-500/15 px-2.5 py-1.5 text-[11px] font-medium text-amber-200 hover:bg-amber-500/25 shrink-0","data-testid":"button-tt-copy-redirect-uri",children:[C?e.jsx(et,{className:"h-3 w-3"}):e.jsx(tt,{className:"h-3 w-3"}),C?"Copiado!":"Copiar"]})]}),e.jsxs("ol",{className:"list-decimal list-inside space-y-1 text-[11px] text-zinc-400 leading-relaxed",children:[e.jsxs("li",{children:["Abra ",e.jsx("a",{href:"https://developers.tiktok.com/",target:"_blank",rel:"noopener noreferrer",className:"text-[#25f4ee] hover:text-[#25f4ee]/80 underline underline-offset-2",children:"developers.tiktok.com"})," e acesse o seu app",g.diag.clientKeyTail?e.jsxs(e.Fragment,{children:[" com Client Key terminando em ",e.jsxs("span",{className:"font-mono text-zinc-300",children:["…",g.diag.clientKeyTail]})]}):null,"."]}),e.jsxs("li",{children:["Em ",e.jsx("span",{className:"text-zinc-300",children:"Configure → Add products → Login Kit"}),", adicione a URL acima em ",e.jsx("span",{className:"text-zinc-300",children:'"Redirect URI for Login"'})," e salve."]}),e.jsx("li",{children:'Volte aqui e clique em "Conectar meu TikTok" de novo — sem precisar reiniciar nada.'})]})]})]})]})}function xo(){const{toast:a}=nt(),i=Ct(),[,b]=Xn("/videos/projetos/:id"),u=b?.id,w=[`/api/videos/projects/${u}`],v=Ge({queryKey:w,enabled:!!u,refetchInterval:t=>Vs(t.state.data)?4e3:!1}),p=v.data,l=p?.project,g=Ge({queryKey:["/api/videos/channels"],enabled:!!l}),C=o.useMemo(()=>(g.data||[]).filter(t=>t.youtubeConnected),[g.data]),[T,j]=o.useState(""),N=T||C.find(t=>
25t.id===l?.channelId)?.id||C[0]?.id||"";o.useEffect(()=>{const t=new URLSearchParams(window.location.search);if(t.get("yt")==="connected"){a({title:"YouTube conectado! 🎉",description:"Seu canal está pronto para receber publicações."}),i.invalidateQueries({queryKey:["/api/videos/channels"]}),t.delete("yt");const s=t.toString();window.history.replaceState({},"",window.location.pathname+(s?`?${s}`:""))}},[]);const x=o.useMemo(()=>[...p?.scenes||[]].sort((t,s)=>t.orderIndex-s.orderIndex),[p?.scenes]),S=o.useMemo(()=>{const t=new Map;for(const s of p?.assets||[])s.type==="image"&&s.sceneId&&ca(s)===0&&t.set(s.sceneId,s);return t},[p?.assets]),I=o.useMemo(()=>{const t=new Map;for(const c of p?.assets||[]){if(c.type!=="image"||!c.sceneId||!c.url||c.status!=="ready")continue;let d=t.get(c.sceneId);d||(d=new Map,t.set(c.sceneId,d)),d.set(ca(c),c)}const s=new Map;for(const[c,d]of t)s.set(c,[...d.entries()].sort((m,F)=>m[0]-F[0]).map(([,m])=>m));return s},[p?.assets]),y=o.useMemo(()=>{const t=new Map;for(const s of p?.assets||[])s.type==="video"&&s.sceneId&&s.status==="ready"&&s.url&&t.set(s.sceneId,s);return t},[p?.assets]),L=!!p?.animationEnabled,z=!!p?.t2vMode,O=(()=>{const t=p?.project?.metadata||{};return String(t.videoStyle||"").toLowerCase()==="reels"||t.platform==="instagram"})(),P=O&&!!p?.project?.metadata?.avatarTakesV2,V=o.useMemo(()=>{if(!P)return null;let t=0;for(const s of x)y.has(s.id)&&t++;return{ready:t,total:x.length}},[P,x,y]),H=!!p?.cancelRestartEnabled,[G,B]=o.useState(null),[Q,oe]=o.useState(null),he=o.useMemo(()=>(p?.jobs||[]).some(t=>t.type==="animate"&&(t.status==="pending"||t.status==="running")),[p?.jobs]),se=o.useMemo(()=>{let t=0;for(const s of x){const c=S.get(s.id);(c&&c.status==="ready"&&c.url||y.has(s.id))&&t++}return{ready:y.size,total:t}},[x,S,y]),Z=Q&&x.find(t=>t.id===Q)||null,ee=Z?x.findIndex(t=>t.id===Z.id):-1,r=p?.script?.metadata||null,be=!!r&&typeof r.estimatedMinutes=="number",te=(r?.research?.sources||[]).filter(t=>t&&t.uri),A=o.useMemo(()=>ur(l?.metadata?.language),[l?.metadata?.language]),de=o.useMemo(()=>{if(!x||x.length<2)return null;const t=x.map(s=>({nf:s.metadata?.narrativeFunction||null,intensity:xr(s.metadata?.narrativeFunction)}));return t.some(s=>s.nf)?t:null},[x]),ge=r?.directorPlan||null,le=(ge?.acts||[]).filter(t=>t&&(t.setting||t.palette||t.mood||t.era||t.title||t.keyImagery&&t.keyImagery.length)),je=(t,s,c)=>{const d=(t||"").toLowerCase();return d.includes("open")||d.includes("abert")||d.includes("iníc")||d.includes("inic")?"Início":d.includes("resol")||d.includes("desfech")||d.includes("clos")||d.includes("fim")||d.includes("final")?"Fim":d.includes("ris")||d.includes("desenvolv")||d.includes("meio")||d.includes("mid")?"Meio":s===0?"Início":s===c-1?"Fim":"Meio"},me=o.useMemo(()=>{const t=new Map;for(const s of p?.voiceTracks||[])s.sceneId&&t.set(s.sceneId,s);return t},[p?.voiceTracks]),h=o.useMemo(()=>{const t=new Set,s=new Set,c=new Set;for(const d of p?.jobs||[]){if(d.status!=="pending"&&d.status!=="running")continue;const m=d.payload?.sceneId;m&&(d.type==="assets"&&t.add(m),d.type==="narration"&&s.add(m),d.type==="animate"&&c.add(m))}return{img:t,narr:s,anim:c}},[p?.jobs]),M=()=>i.invalidateQueries({queryKey:w}),W=U({mutationFn:async()=>(await R("POST",`/api/videos/projects/${u}/render`,{})).json(),onSuccess:t=>{a({title:t?.alreadyQueued?"Render já está na fila":"Render iniciado 🎬",description:"O vídeo está sendo montado. Isso pode levar alguns minutos."}),M()},onError:t=>{const s=t?.status??t?.response?.status,c=String(t?.message||"");if(s===504||/demorou demais|timeout|tempo limite/i.test(c)){a({title:"Render em andamento ⏳",description:"O pedido foi enviado e o vídeo já está sendo montado em segundo plano. Pode levar alguns minutos — a tela atualiza sozinha."}),M();return}a({title:"Não foi possível renderizar",description:t?.message,variant:"destructive"})}}),$=Ge({queryKey:["/api/auth/me"],retry:!1,staleTime:300*1e3}).data?.role==="admin",_=o.useRef(null),[Y,pe]=o.useState(!1),Re=U({mutationFn:async t=>(await R("POST",`/api/videos/projects/${u}/narrasync-ref`,{dataUrl:t})).json(),onSuccess:()=>{a({title:"Personagem salvo ✓",description:"As próximas cenas vão usar esse mesmo personagem."}),M()},onError:t=>a({title:"Não foi possível enviar a imagem",description:t?.message,variant:"destructive"})}),ve=U({mutationFn:async()=>(await R("POST",`/api/videos/projects/${u}/narrasync-regen-scenes`,{})).json(),onSuccess:t=>{a({title:"Regeneração iniciada ✓",description:`${t.totalScenes} cenas sendo regeneradas com o personagem enviado.`}),setTimeout(()=>M(),1500)},onError:t=>a({title:"Não foi possível iniciar a regeneração",description:t?.message,variant:"destructive"})}),Js=t=>{if(!t)return;pe(!0);const s=new FileReader;s.onerror=()=>{pe(!1),a({title:"Não foi possível ler o arquivo",variant:"destructive"})},s.onload=c=>{const d=c.target?.result;if(!d){pe(!1);return}const m=new Image;m.onerror=()=>{pe(!1),a({title:"Imagem inválida",description:"Use PNG, JPG ou WEBP.",variant:"destructive"})},m.onload=()=>{try{let E=m.width,k=m.height;if(E>768||k>768){const K=Math.min(768/E,768/k);E=Math.round(E*K),k=Math.round(k*K)}const q=document.createElement("canvas");q.width=E,q.height=k;const ie=q.getContext("2d");if(!ie)throw new Error("canvas indisponível");ie.drawImage(m,0,0,E,k);const J=q.toDataURL("image/jpeg",.82);Re.mutate(J,{onSettled:()=>pe(!1)})}catch{Re.mutate(d,{onSettled:()=>pe(!1)})}},m.src=d},s.readAsDataURL(t)},Xs=!!Ge({queryKey:["/api/modeling/features"],staleTime:6e4}).data?.flags?.moneyHumanReview,[Za,es]=o.useState(""),[Ne,ct]=o.useState(null),[ts,as]=o.use
25State(!1),xa=U({mutationFn:async t=>(await R("POST",`/api/money/projects/${u}/quality-review`,{decision:t,note:Za.trim()||void 0})).json(),onSuccess:t=>{t?.approved?a({title:"Aprovado ✓",description:"Vídeo liberado para revisão e publicação."}):a({title:"Devolvido para ajustes",description:"A nota foi registrada no projeto."}),es(""),M()},onError:t=>a({title:"Não foi possível concluir a revisão",description:t?.message,variant:"destructive"})}),pa=U({mutationFn:async t=>(await R("POST",`/api/videos/projects/${u}/reels/hook-variant`,{index:t})).json(),onSuccess:()=>{a({title:"Gancho trocado ✓",description:"A primeira cena agora abre com a variação escolhida."}),M()},onError:t=>a({title:"Não foi possível trocar o gancho",description:t?.message,variant:"destructive"})}),ha=U({mutationFn:async()=>(await R("POST",`/api/admin/videos/projects/${u}/render-reset`,{})).json(),onSuccess:()=>{a({title:"Render reaberto ✓",description:"O contador de tentativas foi zerado. O autor já pode renderizar de novo."}),M()},onError:t=>a({title:"Não foi possível reabrir o render",description:t?.message,variant:"destructive"})}),mt=U({mutationFn:async()=>{const t=await R("POST",`/api/admin/videos/projects/${u}/gen-reset`,{});if(!t.ok){const s=await t.json().catch(()=>({}));throw new Error(s?.message||"Erro ao reabrir a geração")}return t.json()},onSuccess:t=>{const s={assets:"imagens",animate:"animações",takes:"takes",narration:"narração",script:"roteiro"},c=t?.autoResumeStep?s[t.autoResumeStep]||t.autoResumeStep:null;a({title:"Geração reaberta ✓",description:t?.autoResumed?`Retomando a geração de ${c??"mídia"} automaticamente — acompanhe o progresso abaixo.`:"Guard zerado. Clique em Retomar geração para continuar a partir do ponto onde parou."}),M()},onError:t=>a({title:"Não foi possível reabrir a geração",description:t?.message,variant:"destructive"})}),ba=U({mutationFn:async()=>(await R("POST",`/api/admin/videos/projects/${u}/render-reset`,{}),(await R("POST",`/api/videos/projects/${u}/render`,{})).json()),onSuccess:()=>{a({title:"EIO limpo + render disparado ✓",description:"O contador foi zerado e a montagem já está na fila."}),M()},onError:t=>a({title:"Não foi possível disparar o render",description:t?.message,variant:"destructive"})}),Ae=U({mutationFn:async()=>(await R("POST",`/api/videos/projects/${u}/resume`,{})).json(),onSuccess:t=>{a({title:t?.alreadyRunning?"A geração já está rodando":t?.action==="ready"?"Mídia pronta ✓":"Retomando a geração 🎬",description:t?.alreadyRunning?"Aguarde — já há um passo em andamento.":t?.action==="ready"?"As cenas já têm imagem e narração. Pode renderizar.":"Voltamos do ponto onde parou. Isso roda em segundo plano."}),M()},onError:t=>a({title:"Não foi possível retomar",description:t?.message,variant:"destructive"})}),Tt=U({mutationFn:async()=>{const t=await R("POST",`/api/videos/projects/${u}/render-partial`,{});if(!t.ok){const s=await t.json().catch(()=>({}));throw new Error(s?.message||"Erro ao iniciar a montagem parcial")}return t.json()},onSuccess:t=>{a({title:t?.alreadyQueued?"Montagem já na fila ✓":"Montando o vídeo 🎬",description:`${t?.readyTakes??"?"} cenas prontas estão sendo montadas em background.`}),M()},onError:t=>a({title:"Não foi possível iniciar a montagem",description:t?.message,variant:"destructive"})}),ga=U({mutationFn:async()=>{const t=await R("POST",`/api/videos/projects/${u}/pause-and-render`,{});if(!t.ok){const s=await t.json().catch(()=>({}));throw new Error(s?.message||"Erro ao pausar e montar o vídeo")}return t.json()},onSuccess:t=>{a({title:t?.alreadyQueued?"Montagem já na fila ✓":"Pausando e montando o vídeo 🎬",description:`${t?.renderableScenes??"?"} cena(s) pronta(s) estão sendo montadas em background. Nada foi perdido.`}),M()},onError:t=>a({title:"Não foi possível pausar e montar",description:t?.message,variant:"destructive"})}),[,ss]=Zn(),fa=U({mutationFn:async()=>{const t=await R("DELETE",`/api/videos/projects/${u}`);if(!t.ok){const s=await t.json().catch(()=>({}));throw new Error(s?.message||"Não foi possível cancelar.")}},onSuccess:()=>{a({title:"Geração cancelada",description:"O projeto foi removido."}),ss("/videos")},onError:t=>a({title:"Erro ao cancelar",description:t?.message,variant:"destructive"})}),it=U({mutationFn:async()=>{const t=await R("POST",`/api/videos/projects/${u}/cancel-and-restart`,{});if(!t.ok){const s=await t.json().catch(()=>({}));throw new Error(s?.message||"Não foi possível cancelar e recomeçar.")}return t.json()},onSuccess:t=>{a({title:"Recomeçando do zero 🎬",description:t?.opportunityReset?"Geração cancelada e oportunidade reaberta. Vamos montar um novo vídeo.":"Geração cancelada. Vamos montar um novo vídeo."});const s=t?.language?`&language=${encodeURIComponent(t.language)}
25`:"",c=t?.opportunityId?`&opportunityId=${encodeURIComponent(t.opportunityId)}`:"";ss(`/videos/novo-video?style=money${c}${s}`)},onError:t=>a({title:"Não foi possível cancelar e recomeçar",description:t?.message,variant:"destructive"})}),ut=U({mutationFn:async t=>{const s=await R("PATCH",`/api/videos/projects/${u}/channel`,{channelId:t});if(!s.ok){const c=await s.json().catch(()=>({}));throw new Error(c?.message||"Erro ao vincular canal")}return s.json()},onSuccess:t=>{a({title:"Canal vinculado ✅",description:`Este vídeo agora pertence a "${t?.channelName}".`}),M()},onError:t=>a({title:"Não foi possível vincular o canal",description:t?.message,variant:"destructive"})}),va=U({mutationFn:async()=>(await R("POST",`/api/videos/projects/${u}/generate`,{})).json(),onSuccess:t=>{a({title:t?.alreadyRunning?"A geração já está rodando":"Gerando o seu vídeo 🎬",description:t?.alreadyRunning?"Aguarde — já há um passo em andamento.":"Agora criamos as imagens, a narração, a trilha e montamos o vídeo. Roda em segundo plano."}),M()},onError:t=>a({title:"Não foi possível gerar o vídeo",description:t?.message,variant:"destructive"})}),xt=U({mutationFn:async t=>{const s=await R("POST",`/api/videos/projects/${u}/change-voice`,t);if(!s.ok){const c=await s.json().catch(()=>({}));throw new Error(c?.message||"Erro ao trocar a voz")}return s.json()},onSuccess:()=>{At(!1),we.current&&(we.current.pause(),we.current.src=""),ke(null),pt(null),i.invalidateQueries({queryKey:w}),a({title:"Voz atualizada!",description:"Regenerando a narração de todas as cenas — o vídeo será re-renderizado em seguida."})},onError:t=>a({title:"Não foi possível trocar a voz",description:t?.message,variant:"destructive"})}),ns=U({mutationFn:async()=>(await R("POST",`/api/videos/projects/${u}/publish`,{privacyStatus:"public",channelId:N||void 0})).json(),onSuccess:t=>{a({title:t?.alreadyPublished?"Vídeo já publicado":t?.alreadyQueued?"Publicação já está na fila":"Publicando no YouTube 🚀",description:t?.alreadyPublished?"Ele já está no seu canal.":"Estamos enviando o vídeo para o seu canal. Isso leva alguns minutos."}),M()},onError:t=>a({title:"Não foi possível publicar",description:t?.message,variant:"destructive"})}),[Zs,ya]=o.useState(!1),[en,Bt]=o.useState(!1),[is,At]=o.useState(!1),[_t,Pt]=o.useState(Vt),[Pe,pt]=o.useState(null),[tn,ke]=o.useState(null),[an,rs]=o.useState(null),[ja,os]=o.useState("all"),Na=o.useRef({}
25),we=o.useRef(null),{data:ls}=Ge({queryKey:["/api/videos/personas"],queryFn:async()=>{const t=await R("GET","/api/videos/personas");if(!t.ok)throw new Error("Erro ao carregar clones");return t.json()},enabled:is,staleTime:3e4}),sn=ls?.voiceCloneNarrationEnabled??!0,wa=(ls?.personas||[]).filter(t=>t.voiceStatus==="ready"&&t.status!=="archived"),[Mt,nn]=o.useState(()=>{const t=new Date;return t.setDate(t.getDate()+1),t.toISOString().slice(0,10)}),[$t,rn]=o.useState("18:00"),Et=U({mutationFn:async()=>{const t=new Date(`${Mt}T${$t}:00`);if(isNaN(t.getTime()))throw new Error("Data/hora inválida");if(t.getTime()<=Date.now())throw new Error("O horário deve ser no futuro");return(await R("POST",`/api/videos/projects/${u}/publish`,{privacyStatus:"public",channelId:N||void 0,scheduledAt:t.toISOString()})).json()},onSuccess:t=>{const s=Mt&&$t?new Date(`${Mt}T${$t}:00`).toLocaleString("pt-BR",{dateStyle:"short",timeStyle:"short"}):"";a({title:t?.alreadyScheduled?"Já há um agendamento ativo":"Vídeo agendado ✅",description:t?.alreadyScheduled?"Cancele o agendamento atual antes de criar um novo.":`Será publicado automaticamente em ${s}. Você pode cancelar enquanto o horário não chegar.`}),ya(!1),M()},onError:t=>a({title:"Não foi possível agendar",description:t?.message,variant:"destructive"})}),ka=U({mutationFn:async t=>(await R("DELETE",`/api/videos/projects/${u}/publications/${t}`,{})).json(),onSuccess:()=>{a({title:"Agendamento cancelado",description:"O vídeo não será publicado automaticamente."}),M()},onError:t=>a({title:"Não foi possível cancelar",description:t?.message,variant:"destructive"})}),Ut=U({mutationFn:async()=>(await R("POST",`/api/videos/projects/${u}/thumbnails/generate`,{})).json(),onSuccess:t=>{const s=Array.isArray(t?.candidates)?t.candidates.length:0;a({title:s>0?`${s} miniatura${s>1?"s":""} criada${s>1?"s":""} ✨`:"Tente novamente",description:s>0?"Escolha a sua favorita abaixo.":"Não conseguimos gerar agora. Tente de novo em instantes."}),M()},onError:t=>a({title:"Não foi possível gerar as miniaturas",description:t?.message,variant:"destructive"})}),Ht=U({mutationFn:async()=>(await R("POST",`/api/videos/projects/${u}/reels-cover/generate`,{})).json(),onSuccess:()=>{a({title:"Capa do Reels pronta ✨",description:"Sua capa em alta qualidade já está no kit de publicação."}),M()},onError:t=>a({title:"Não foi possível gerar a capa",description:t?.message,variant:"destructive"})}),ds=U({mutationFn:async t=>(await R("POST",`/api/videos/projects/${u}/thumbnails/choose`,{url:t})).json(),onSuccess:()=>{a({title:"Miniatura escolhida ✓",description:"Ela será usada quando você publicar no YouTube."}),M()},onError:t=>a({title:"Não foi possível escolher a miniatura",description:t?.message,variant:"destructive"})}),Sa=U({mutationFn:async t=>{const s=await new Promise((d,m)=>{const F=new FileReader;F.onload=()=>d(String(F.result||"")),F.onerror=()=>m(new Error("Não foi possível ler a imagem")),F.readAsDataURL(t)});return(await R("POST",`/api/videos/projects/${u}/thumbnails/upload-own`,{dataUrl:s})).json()},onSuccess:()=>{a({title:"Miniatura enviada ✓",description:"Ela já está escolhida para a publicação."}),M()},onError:t=>a({title:"Não foi possível enviar a miniatura",description:t?.message,variant:"destructive"})}),[on,za]=o.useState(null),[Ca,cs]=o.useState(""),[ms,us]=o.useState("#FFD23F"),Gt=U({mutationFn:async t=>(await R("POST",`/api/videos/projects/${u}/thumbnails/edit`,t)).json(),onSuccess:()=>{a({title:"Miniatura atualizada ✓",description:"O novo texto já está aplicado e escolhido para a publicação."}),za(null),M()},onError:t=>a({title:"Não foi possível editar a miniatura",description:t?.message,variant:"destructive"})}),Ta=U({mutationFn:async()=>(await R("POST",`/api/videos/projects/${u}/scenes`,{})).json(),onSuccess:()=>{a({title:"Cena adicionada",description:"Escreva o texto e o prompt, depois gere a mídia."}),M()},onError:t=>a({title:"Não foi possível adicionar a cena",description:t?.message,variant:"destructive"})}),ln=U({mutationFn:async t=>(await R("POST",`/api/videos/projects/${u}/scenes/reorder`,{order:t})).json(),onSuccess:()=>M(),onError:t=>a({title:"Não foi possível reordenar",description:t?.message,variant:"destructive"})}),dn=(t,s)=>{const c=t+s;if(c<0||c>=x.length)return;const d=x.map(m=>m.id);[d[t],d[c]]=[d[c],d[t]],ln.mutate(d)},xs=!!l?.metadata?.userScript,Aa=l?Rs[l.status]||Rs.draft:null,Kt=Aa&&xs&&l?.status==="script_generating"?{...Aa,label:"Processando roteiro…"}:Aa,ae=p?.render||null,ye=!!ae&&ae.status==="completed"&&!!ae.url,cn=!!l?.metadata?.chaosEngineEnabled,ps=!!l?.metadata?.fullAuto&&!cn,Pa=l?.metadata?.thumbnails||null,Ma=Array.isArray(Pa?.candidates)?Pa.candidates:[],$a=Pa?.chosenUrl||null,It=l?.metadata?.renderCrashGuard||null,ht=!!It?.maintenance,Ea=It?.maintenanceReason||null,mn=/muito longo|limite atual/i.test(Ea||""),Fe=l?.metadata?.heygenHealth?.lastError||null,un=Number(Fe?.status||0)===402||/insufficient|credit|quota/i.test(String(Fe?.message||"")),Qt=Fe?.strict===!0,xn=String(Fe?.code||"")==="moderation",hs=!!l&&br.has(l.status)&&!W.isPending&&!ht,Ye=l?.metadata?.genCrashGuard||null,bt=!!Ye?.maintenance,bs=Ye?.maintenanceReason||null,Yt=3,gt=Number(Ye?.autoRetryAttempts??0),Rt=!!Ye?.autoRetryAlerted||gt>=Yt,We=!bt||Rt?null:Ye?.nextAutoRetryAt?new Date(Ye.nextAutoRetryAt):Ye?.maintenanceAt?new Date(new Date(Ye.maintenanceAt).getTime()+1800*1e3):null,Ve=Vs(p),Wt=l?.metadata?.voiceId||Vt,Jt=Ua(Wt),ft=l?.metadata?.voicePersonaId||null,gs=(p?.jobs||[]).some(t=>["narration","assets","animate","render"].includes(t.type)&&(t.status==="pending"||t.status==="running")&&!t.payload?.sceneId),pn=!!l&&!p?.asmrMode&&!l.metadata?.cloneFullNarration&&x.length>0&&!gs&&!xt.isPending,hn=!Qs.has(l?.status??"")&&(p?.jobs||[]).some(t=>t.type==="render"&&(t.status==="pending"||t.status==="running")),Me=o.useMemo(()=>{let t=0,s=0;for(const c of x){if(!(c.visualPrompt||c.text||"").trim())continue;s++;const d=S.get(c.id),m=!!(d&&d.status==="ready"&&d.url);(y.has(c.id)||!z&&m)&&t++}return{ready:t,total:s}},[x,S,y,z]),bn=z?"cenas em vídeo":"imagens",$e=o.useMemo(()=>{const t=l?.metadata?.takePool;if(!t||t.enabled!==!0)return null;const s=Number(t.count)||0;if(s<=0)return null;
25let c=0;for(const d of p?.assets||[])d.type==="video"&&!d.sceneId&&d.status==="ready"&&d.url&&c++;return{ready:Math.min(c,s),total:s}},[l,p?.assets]),Je=$e||Me,gn=$e?"clipes de vídeo prontos":bn==="imagens"?"imagens prontas":"cenas em vídeo prontas",Be=o.useMemo(()=>{const t=l?.metadata?.takePool;if(!t||t.enabled!==!0)return null;const s=Number(t.count)||0,c=Number(t.takeSec)||0;if(s<=0||c<=0||x.length===0)return null;const d=new Map;for(const K of p?.assets||[]){if(K.type!=="video"||K.sceneId)continue;const D=K.metadata||{};if(D.pool!==!0||t.planHash&&D.planHash&&D.planHash!==t.planHash)continue;const ne=Number(D.poolIndex);Number.isFinite(ne)&&K.status==="ready"&&K.url&&d.set(ne,K)}const m=K=>{const D=me.get(K.id);return D&&D.status==="ready"&&D.durationMs?D.durationMs/1e3:0},F=x.some(K=>m(K)>0),E=Number(t.totalNarrSec)||s*c;let k;if(F)k=x.map(K=>Math.max(0,m(K)));else{const K=x.map(ne=>(ne.text||"").trim().split(/\s+/).filter(Boolean).length),D=K.reduce((ne,ze)=>ne+ze,0);k=D>0?K.map(ne=>ne/D*E):x.map(()=>E/x.length)}const q=new Map;let ie=0,J=0;for(let K=0;K<x.length;K++){const D=J,ne=J+(k[K]||0);J=ne;const ze=(D+ne)/2,X=Math.min(s-1,Math.max(0,Math.floor(ze/c))),De=Math.min(s-1,Math.max(0,Math.floor(D/c))),ot=d.get(X)||d.get(De),Ee=!!ot;Ee&&ie++,q.set(x[K].id,{preview:ot,covered:Ee})}return{coverByScene:q,coveredCount:ie,total:x.length,count:s}},[l,p?.assets,x,me]),fn=o.useMemo(()=>{const t=l?.metadata?.takePool;if(!t||t.enabled!==!0)return null;const s=Number(t.count)||0,c=Number(t.takeSec)||0;if(s<=0)return null;const d=new Map;for(const E of p?.assets||[]){if(E.type!=="video"||E.sceneId)continue;const k=E.metadata||{};if(k.pool!==!0||t.planHash&&k.planHash&&k.planHash!==t.planHash)continue;const q=Number(k.poolIndex);Number.isFinite(q)&&d.set(q,E)}const m=Array.from({length:s},(E,k)=>{const q=d.get(k),ie=q?.status==="ready"&&!!q?.url;return{index:k,status:ie?"ready":q?.status==="failed"?"failed":"pending",url:q?.url||null,chunk:String(q?.metadata?.textChunk||"").trim()}}),F=m.filter(E=>E.status==="ready").length;return{takes:m,count:s,takeSec:c,readyCount:F}},[l,p?.assets]),_e=o.useMemo(()=>{const t=x.length,s={perScene:[],starts:[],total:0,midrollIndex:-1,monetizable:!1};if(t===0)return s;const c=D=>{const ne=me.get(D.id);return ne&&ne.status==="ready"&&ne.durationMs?ne.durationMs/1e3:0},d=x.map(D=>(D.text||"").trim().split(/\s+/).filter(Boolean).length),m=d.reduce((D,ne)=>D+ne,0),E=typeof r?.estimatedMinutes=="number"&&r.estimatedMinutes>0?r.estimatedMinutes*60:m>0?m/150*60:0,k=x.map((D,ne)=>{const ze=c(D);return ze>0?ze:m>0&&E>0?d[ne]/m*E:E>0?E/t:0}),q=[];let ie=0;for(let D=0;D<t;D++)q.push(ie),ie+=k[D];const J=ie;let K=-1;if(J>=lt){for(let D=0;D<t;D++)if(q[D]+k[D]>=lt){K=D;break}}return{perScene:k,starts:q,total:J,midrollIndex:K,monetizable:J>=lt}},[x,me,r]),Ft=l?.metadata?.narrasyncTestarV2===!0,Ke=o.useMemo(()=>{const t=[];let s=0;_e.perScene.forEach((k,q)=>{if(!(k>0))return;const ie=Ft?lr(k):nr(k);for(const J of ie)t.push({sceneIdx:q,dur:J,start:s}),s+=J});const c=s,d=t.map(k=>k.dur),m=d.length?Math.min(...d):0,F=d.length?Math.max(...d):0,E=d.length?d.reduce((k,q)=>k+q,0)/d.length:0;return{cuts:t,total:c,minD:m,maxD:F,avgD:E}},[_e,Ft]),vn=o.useMemo(()=>{const t=l?.metadata?.videoPipelineMode==="asmr";let s=0,c=0;for(const d of x){if(!(d.visualPrompt||d.text||"").trim())continue;s++;const m=S.get(d.id),F=me.get(d.id),E=y.has(d.id)||m?.status==="ready"&&!!m.url;(t?E:E&&F?.status==="ready"&&F.url)&&c++}return s>0&&c===s},[x,S,y,me,l?.metadata?.videoPipelineMode]),yn=15e4,Xt=l?.updatedAt?Date.parse(l.updatedAt):NaN,jn=Number.isFinite(Xt)?Date.now()-Xt:0,Nn=(p?.jobs||[]).some(t=>t.status==="pending"||t.status==="running"),fs=Ve&&!Nn&&jn>yn;l&&l.status;const xe=(p?.jobs||[]).find(t=>t.type==="render"&&(t.status==="pending"||t.status==="running"))?.result?.renderProgress||null,vs=fr(xe),Zt=ae?.status==="rendering"&&ae?.createdAt?Date.parse(ae.createdAt):NaN,ys=xe?.startedAt?Date.parse(xe.startedAt):Number.isFinite(Zt)?Zt:Number.isFinite(Xt)?Xt:NaN,Ia=Number.isFinite(ys)?Math.max(0,Date.now()-ys):0,Ra=Ia>0?Fs(Ia):"",Xe=!xe&&l?.status==="rendering"&&ae?.status==="rendering"&&ae?.metadata?.backend==="cloudrun",wn=8*6e4,js=xe?.updatedAt?Date.parse(xe.updatedAt):NaN,kn=Number.isFinite(js)?Date.now()-js:Number.isFinite(Zt)?Date.now()-Zt:0,Sn=l?.status==="rendering"&&!Xe&&kn>wn,zn=$e?20:z?12:8,ea=Xe?Math.max(5*6e4,Math.max(1,x.length)*zn*1e3):0,Fa=Xe?Ia:0,Qe=ea>0?Math.min(96,Math.round(Fa/ea*100)):0,Ns=ea>Fa?ea-Fa:0,Cn=Xe?Qe<5?"Iniciando o render no servidor…":Qe<15?$e?"Baixando os clipes do pool…":"Preparando os arquivos de vídeo…":Qe<80?`Montando as cenas (est. ${Math.max(1,Math.round((Qe-15)/65*x.length))} de ${x.length})…`:Qe<90?"Aplicando trilha sonora e transições…":"Finalizando e enviando o vídeo…":null,Ue=o.useMemo(()=>{const t=ae?.metadata?.features;if(t)return{applied:!0,musicOn:!!t.music,moodLabel:t.music?na[t.music]||na.documentary:null,transitions:t.transitions!==!1,captionsLabel:qa[t.captions||"chunks"]||qa.chunks,resolutionLabel:hr(t.resolution)};const s=l?.metadata?.musicMood||"documentary";return{applied:!1,musicOn:!0,moodLabel:na[s]||na.documentary,transitions:!0,captionsLabel:qa.chunks,resolutionLabel:null}},[ae?.metadata?.features,l?.metadata?.musicMood]),Va=p?.publications||[],ta=Va.filter(t=>t.platform!=="instagram"&&t.platform!=="tiktok"),Tn=Va.filter(t=>t.platform==="instagram"),An=Va.filter(t=>t.platform==="tiktok"),Se=ta.find(t=>t.status==="published"&&t.externalId)||null,vt=Se?null:ta.find(t=>t.status==="failed")||null,aa=Se?null:ta.find(t=>t.status==="pending_schedule")||null,ws=C.length>0,Pn=(p?.jobs||[]).some(t=>t.type==="publish"&&(t.status==="pending"||t.status==="running")),rt=ns.isPending||Et.isPending||Pn||ta.some(t=>t.status==="scheduled"||t.status==="uploading"),Mn=(p?.jobs||[]).some(t=>t.type==="instagram_publish"&&(t.status==="pending"||t.status==="running")),$n=(p?.jobs||[]).some(t=>t.type==="tiktok_publish"&&(t.status==="pending"||t.status==="running"));function En(t){if(!t)return"—";const s=typeof t=="string"?new Date(t):t;
25return isNaN(s.getTime())?"—":s.toLocaleString("pt-BR",{dateStyle:"short",timeStyle:"short"})}const In=new Date().toISOString().slice(0,10);return e.jsxs(pi,{children:[e.jsxs("div",{className:"max-w-5xl mx-auto px-4 md:px-6 py-8 pb-28",children:[e.jsx(Ss,{href:"/videos",children:e.jsxs("button",{className:"flex items-center gap-2 text-sm text-zinc-400 hover:text-zinc-200 mb-6","data-testid":"button-back",children:[e.jsx(ji,{className:"h-4 w-4"})," Voltar"]})}),v.isLoading?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(f,{className:"h-7 w-7 animate-spin text-cyan-400"})}):l?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-6",children:e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-gradient-to-br from-blue-500 to-cyan-400 flex items-center justify-center shrink-0",children:e.jsx(Da,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight truncate","data-testid":"text-project-title",children:l.title}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[Kt&&e.jsxs("span",{className:`inline-flex items-center gap-1.5 text-[11px] px-2 py-0.5 rounded-full border ${Kt.cls}`,"data-testid":"badge-project-status",children:[Kt.spin&&e.jsx(f,{className:"h-3 w-3 animate-spin"})," ",Kt.label]}),(()=>{const t=l?.metadata?.imageTier;if(!t)return null;const s=yi(t);return e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-full border border-cyan-500/30 bg-cyan-500/10 text-cyan-200","data-testid":"badge-image-tier",title:s.description,children:["Imagem: ",s.label," · ",s.costHint]})})()]})]})]})}),(()=>{const t=(g.data||[]).filter(d=>!d.isStudio),s=(g.data||[]).find(d=>d.id===l.channelId),c=!s||!!s.isStudio;return!g.isFetched||!c||t.length===0?null:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-amber-500/25 bg-amber-500/[0.07] px-4 py-3 mb-6","data-testid":"panel-assign-channel",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-amber-200/80 min-w-0",children:[e.jsx(He,{className:"h-4 w-4 text-amber-400 shrink-0"}),e.jsxs("span",{children:["Este vídeo ainda ",e.jsx("strong",{className:"text-amber-200",children:"não está vinculado"})," a nenhum canal. Escolha um para organizar e publicar."]})]}),e.jsx("div",{className:"flex items-center gap-2 shrink-0",children:t.length===1?e.jsxs("button",{onClick:()=>ut.mutate(t[0].id),disabled:ut.isPending,className:"inline-flex items-center gap-1.5 rounded-xl bg-amber-500/20 border border-amber-500/30 hover:bg-amber-500/30 px-3 py-1.5 text-sm font-medium text-amber-200 disabled:opacity-50 transition-colors","data-testid":"button-assign-channel-single",children:[ut.isPending?e.jsx(f,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(He,{className:"h-3.5 w-3.5"}),"Vincular a «",t[0].name,"»"]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("select",{defaultValue:"",onChange:d=>{d.target.value&&ut.mutate(d.target.value)},disabled:ut.isPending,className:"rounded-lg bg-[#0b1322] border border-amber-500/30 text-sm text-zinc-200 px-3 py-1.5 focus:outline-none focus:border-amber-400/60 disabled:opacity-50","data-testid":"select-assign-channel",children:[e.jsx("option",{value:"",disabled:!0,children:"Escolher canal…"}),t.map(d=>e.jsx("option",{value:d.id,children:d.name},d.id))]}),ut.isPending&&e.jsx(f,{className:"h-4 w-4 animate-spin text-amber-400"})]})})]})})(),ps&&!ye&&e.jsxs("section",{className:"relative overflow-hidden rounded-3xl border border-cyan-400/25 bg-gradient-to-br from-[#061420]/70 via-[#071829]/55 to-[#060d1c]/45 p-5 md:p-6 mb-6","data-testid":"banner-full-auto-producing",children:[e.jsx("div",{className:"pointer-events-none absolute -top-14 -right-10 h-48 w-48 rounded-full bg-cyan-500/10 blur-3xl"}),e.jsxs("div",{className:"relative flex items-start gap-3.5",children:[e.jsx("span",{className:"mt-0.5 flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl bg-cyan-500/15 border border-cyan-500/20",children:e.jsx(f,{className:"h-5 w-5 text-cyan-300 animate-spin"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h2",{className:"text-base md:text-lg font-bold text-white",children:"Modo automático em produção"}),e.jsx("span",{className:"rounded-full bg-cyan-500/15 text-cyan-300 text-[10px] font-bold uppercase tracking-wide px-2 py-0.5 border border-cyan-500/20",children:"Zero-touch"})]}),e.jsxs("p",{className:"text-sm text-zinc-400 leading-relaxed",children:["A Sábhia está escrevendo o roteiro, gerando as imagens, narrando e montando o vídeo.",e.jsx("strong",{className:"text-zinc-200",children:" Pode fechar a página"})," — se algo travar, o sistema",e.jsx("strong",{className:"text-cyan-200",children:" se recupera e continua sozinho"}),". Volte mais tarde: o vídeo estará pronto para baixar e publicar quando você quiser."]})]})]})]}),ps&&ye&&e.jsxs("section",{className:"relative overflow-hidden rounded-3xl border border-emerald-400/25 bg-gradient-to-br from-[#06200f]/70 via-[#07291a]/55 to-[#06140d]/45 p-5 md:p-6 mb-6","data-testid":"banner-full-auto-ready",children:[e.jsx("div",{className:"pointer-events-none absolute -top-14 -right-10 h-48 w-48 rounded-full bg-emerald-500/10 blur-3xl"}),e.jsxs("div",{className:"relative flex items-start gap-3.5",children:[e.jsx("span",{className:"mt-0.5 flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl bg-emerald-500/15 border border-emerald-500/20",children:e.jsx(ue,{className:"h-5 w-5 text-emerald-300"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h2",{className:"text-base md:text-lg font-bold text-white",children:"Vídeo pronto — Modo automático"}),e.jsx("span",{className:"rounded-full bg-emerald-500/15 text-emerald-300 text-[10px] font-bold uppercase tracking-wide px-2 py-0.5 border border-emerald-500/20",children:"Pronto"})]}),e.jsxs("p",{className:"text-sm text-zinc-400 leading-relaxed",children:["A Sábhia montou tudo sozinha. Baixe o ",e.jsx("strong",{className:"text-zinc-200",children:"MP4"})," e a",e.jsx("strong",{className:"text-zinc-200",children:" legenda .srt"}),", e copie o título, a descrição e as tags no painel ",e.jsx("strong",{className:"text-emerald-200",children:"Publicação manual"})," abaixo. A postagem no YouTube continua ",e.jsx("strong",{className:"text-zinc-200",children:"100% sua"})," — nunca publicamos por você."]}),ae&&e.jsxs("a",{href:`/api/videos/renders/${ae.id}/download`,download:!0,className:"mt-3 inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-emerald-500 to-teal-600 px-4 py-2.5 text-sm font-semibold text-white shadow-lg shadow-emerald-900/30 hover:opacity-95 active:scale-[0.98] transition-all","data-testid":"link-full-auto-download-mp4",children:[e.jsx(Le,{className:"h-4 w-4"})," Baixar vídeo MP4"]})]})]})]}),!!l.metadata?.chaosEngineEnabled&&l.status==="awaiting_human_quality_review"&&ye&&ae&&(()=>{const t=l.metadata||{},s=t.scriptMetadata||{},c=s.selectedTitle||l.title||"Vídeo Money",d=x.slice(0,30);let m=0;const F=[];for(let X=0;X<d.length;X++){const ot=(d[X].text||"").replace(/\n/g," ").slice(0,60).trim()||`Cena ${X+1}`,Ee=String(Math.floor(m/60)).padStart(2,"0"),yt=String(Math.round(m%60)).padStart(2,"0");F.push(`${Ee}:${yt} ${ot}${ot.length>=60?"…":""}`),m+=40}const E=s.description||"",k=Array.isArray(s.research?.sources)?s.research.sources.slice(0,3).map(X=>
25X.title||X.uri||"").filter(Boolean):[],q=(t.language||"pt-BR").toLowerCase(),ie=Ha(q),J=Es(q,"long"),K=[c,"",E||`${c} — criado com IA editorial.`,"",J,"",ie.inThisVideo,...F,"",k.length>0?ie.sourcesShort:"",...k.map(X=>`• ${X}`),(k.length>0,""),"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",ie.subscribeShort].filter(X=>X!==void 0).join(`
26`).trim(),D=Array.isArray(s.tags)&&s.tags.length>0?s.tags:c.toLowerCase().replace(/[^a-záéíóúàâêôãõüç\s]/gi,"").split(/\s+/).filter(X=>X.length>3).slice(0,8).map(X=>`#${X}`),ne=D.slice(0,10).join(" "),ze=(X,De)=>{navigator.clipboard.writeText(X).then(()=>{ct(De),setTimeout(()=>ct(null),2200)})};return e.jsxs("section",{className:"relative overflow-hidden rounded-3xl border border-cyan-400/30 bg-gradient-to-br from-[#061420]/70 via-[#071829]/60 to-[#060d1c]/50 p-6 md:p-7 mb-6","data-testid":"panel-chaos-download-package",children:[e.jsx("div",{className:"pointer-events-none absolute -top-16 -right-12 h-56 w-56 rounded-full bg-cyan-500/10 blur-3xl"}),e.jsx("div",{className:"pointer-events-none absolute -bottom-12 -left-8 h-44 w-44 rounded-full bg-blue-500/10 blur-3xl"}),e.jsxs("div",{className:"relative flex flex-col gap-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2.5 mb-2",children:[e.jsx(Le,{className:"h-5 w-5 text-cyan-300 shrink-0"}),e.jsx("h2",{className:"text-lg md:text-xl font-bold text-white",children:"Pacote de Upload Pronto"}),e.jsx("span",{className:"ml-1 rounded-full bg-cyan-500/15 text-cyan-300 text-[11px] font-semibold px-2.5 py-0.5 border border-cyan-500/20",children:"CAOS MONEY"})]}),e.jsxs("p",{className:"text-sm text-zinc-400 leading-relaxed",children:["Baixe o MP4 e copie o pacote completo (título, descrição com timestamps, hashtags) pronto para colar no YouTube. A publicação é ",e.jsx("strong",{className:"text-zinc-200",children:"100% manual"})," — você tem controle total."]})]}),e.jsxs("a",{href:`/api/videos/renders/${ae.id}/download`,download:!0,className:"inline-flex items-center justify-center gap-2.5 w-full rounded-2xl py-4 px-6 bg-gradient-to-r from-cyan-500 to-blue-600 text-white font-bold text-base shadow-lg shadow-cyan-900/40 hover:opacity-95 active:scale-[0.98] transition-all","data-testid":"link-download-mp4",children:[e.jsx(Le,{className:"h-5 w-5"}),"Baixar vídeo MP4"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-semibold text-cyan-300 uppercase tracking-wider",children:"📌 Título Viral"}),e.jsxs("button",{onClick:()=>ze(c,"title"),className:"flex items-center gap-1 rounded-lg px-2.5 py-1 text-xs text-zinc-300 hover:text-white bg-white/5 hover:bg-white/10 transition-colors","data-testid":"button-copy-title",children:[Ne==="title"?e.jsx(ue,{className:"h-3.5 w-3.5 text-emerald-400"}):e.jsx(Le,{className:"h-3.5 w-3.5"}),Ne==="title"?"Copiado!":"Copiar"]})]}),e.jsx("div",{className:"rounded-xl bg-black/30 border border-cyan-500/15 px-4 py-3 text-sm text-white leading-relaxed",children:c})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-semibold text-cyan-300 uppercase tracking-wider",children:"📝 Descrição + Timestamps"}),e.jsxs("button",{onClick:()=>ze(K,"desc"),className:"flex items-center gap-1 rounded-lg px-2.5 py-1 text-xs text-zinc-300 hover:text-white bg-white/5 hover:bg-white/10 transition-colors","data-testid":"button-copy-description",children:[Ne==="desc"?e.jsx(ue,{className:"h-3.5 w-3.5 text-emerald-400"}):e.jsx(Le,{className:"h-3.5 w-3.5"}),Ne==="desc"?"Copiado!":"Copiar tudo"]})]}),e.jsx("textarea",{readOnly:!0,value:K,rows:8,className:"w-full rounded-xl bg-black/30 border border-cyan-500/15 px-4 py-3 text-xs text-zinc-200 font-mono leading-relaxed resize-none focus:outline-none focus:border-cyan-400/30 scrollbar-thin","data-testid":"textarea-description-preview",onClick:X=>X.target.select()})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-semibold text-cyan-300 uppercase tracking-wider",children:"#️⃣ Hashtags"}),e.jsxs("button",{onClick:()=>ze(ne,"tags"),className:"flex items-center gap-1 rounded-lg px-2.5 py-1 text-xs text-zinc-300 hover:text-white bg-white/5 hover:bg-white/10 transition-colors","data-testid":"button-copy-hashtags",children:[Ne==="tags"?e.jsx(ue,{className:"h-3.5 w-3.5 text-emerald-400"}):e.jsx(Le,{className:"h-3.5 w-3.5"}),Ne==="tags"?"Copiado!":"Copiar"]})]}),e.jsx("div",{className:"rounded-xl bg-black/30 border border-cyan-500/15 px-4 py-3 text-sm text-cyan-200 leading-relaxed flex flex-wrap gap-1.5",children:D.slice(0,10).map((X,De)=>e.jsx("span",{className:"rounded-full bg-cyan-500/10 border border-cyan-500/20 px-2.5 py-0.5 text-xs",children:X},De))})]}),e.jsxs("div",{className:"rounded-2xl bg-white/[0.03] border border-white/10 p-4 space-y-2.5",children:[e.jsxs("p",{className:"text-xs font-semibold text-zinc-300 uppercase tracking-wider flex items-center gap-2",children:[e.jsx(kt,{className:"h-3.5 w-3.5 text-cyan-400"}),"Como publicar no YouTube"]}),e.jsx("ol",{className:"space-y-1.5 text-xs text-zinc-400 list-none",children:["Baixe o MP4 acima e abra o YouTube Studio","Clique em «Criar» → «Enviar vídeos» e selecione o arquivo","Cole o Título Viral no campo de título","Cole a Descrição completa (com timestamps) no campo de descrição","Cole as Hashtags no final da descrição","Selecione a thumbnail gerada (se disponível) ou escolha um frame do vídeo","Defina como «Não listado» para revisar, depois publique quando estiver satisfeito"].map((X,De)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"shrink-0 w-5 h-5 rounded-full bg-cyan-500/15 border border-cyan-500/20 text-cyan-300 text-[10px] font-bold flex items-center justify-center mt-0.5",children:De+1}),e.jsx("span",{children:X})]},De))})]})]})]})})(),Xs&&l.status==="awaiting_human_quality_review"&&(()=>{const t=l.metadata?.moneyStrategy||{},s=fi(t.visualShieldMode),c=vi(t.complianceProfile),d=xa.isPending;return e.jsxs("section",{className:"relative overflow-hidden rounded-3xl border border-amber-500/30 bg-gradient-to-br from-[#2a1e0a]/55 via-[#1c1407]/50 to-[#120c04]/40 p-6 md:p-7 mb-8","data-testid":"panel-human-quality-review",children:[e.jsx("div",{className:"pointer-events-none absolute -top-16 -right-16 h-56 w-56 rounded-full bg-amber-500/15 blur-3xl"}),e.jsxs("div",{className:"relative flex flex-col gap-5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ka,{className:"h-5 w-5 text-amber-300 shrink-0"}),e.jsx("h2",{className:"text-lg md:text-xl font-bold text-white",children:"Revisão humana de qualidade"})]}),e.jsx("p",{className:"text-sm text-zinc-300 leading-relaxed",children:"Este vídeo Money está pronto e aguarda sua conferência final antes de seguir para publicação. Aprove para liberar ou devolva com uma nota de ajuste."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsxs("span",{className:"rounded-full bg-amber-500/10 text-amber-200 text-[11px] font-medium px-2.5 py-1","data-testid":"chip-review-shield",children:["🛡️ Blindagem: ",s.label]}),e.jsxs("span",{className:"rounded-full bg-amber-500/10 text-amber-200 text-[11px] font-medium px-2.5 py-1","data-testid":"chip-review-compliance",children:["Conformidade: ",c.label]})]})]}),e.jsx("textarea",{value:Za,onChange:m=>es(m.target.value.slice(0,1e3)),rows:2,placeholder:"Nota de revisão (opcional ao aprovar; recomendada ao devolver para ajuste)…",className:"w-full rounded-xl bg-black/30 border border-amber-400/25 px-4 py-3 text-sm text-white placeholder:text-zinc-500 focus:border-amber-400/55 focus:outline-none focus:ring-2 focus:ring-amber-500/20","data-testid":"input-review-note"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("button",{onClick:()=>xa.mutate("approve"),disabled:d,className:"inline-flex items-center justify-center gap-2 rounded-2xl px-6 py-3 font-semibold text-white bg-gradient-to-r from-emerald-500 to-emerald-600 shadow-lg shadow-emerald-900/30 hover:opacity-95 disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"button-review-approve",children:[d?e.jsx(f,{className:"h-5 w-5 animate-spin"}):e.jsx(et,{className:"h-5 w-5"}),"Aprovar e liberar"]}),e.jsxs("button",{onClick:()=>xa.mutate("rework"),disabled:d,className:"inline-flex items-center justify-center gap-2 rounded-2xl px-6 py-3 font-semibold text-amber-100 border border-amber-500/40 bg-amber-500/10 hover:bg-amber-500/20 disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"button-review-rework",children:[d?e.jsx(f,{className:"h-5 w-5 animate-spin"}):e.jsx(sa,{className:"h-5 w-5"}),"Devolver para ajuste"]})]})]})]})})(),l.status==="awaiting_script_approval"&&(()=>{const t=l.metadata||{},s=(t.slideshowScript||t.userScript||"").trim(),c=x.map(m=>
26(m.text||"").trim()).filter(Boolean).join(`
27
28`),d=s||c;return e.jsxs("section",{className:"relative overflow-hidden rounded-3xl border border-cyan-500/30 bg-gradient-to-br from-[#10224a]/60 via-[#0c1730]/55 to-[#0a1428]/45 p-6 md:p-7 mb-8","data-testid":"panel-script-approval",children:[e.jsx("div",{className:"pointer-events-none absolute -top-16 -right-16 h-56 w-56 rounded-full bg-cyan-500/20 blur-3xl"}),e.jsxs("div",{className:"relative flex flex-col gap-5",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center gap-5",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ce,{className:"h-5 w-5 text-cyan-300 shrink-0"}),e.jsx("h2",{className:"text-lg md:text-xl font-bold text-white",children:"Roteiro pronto — sua hora de revisar"})]}),e.jsxs("p",{className:"text-sm text-zinc-300 leading-relaxed",children:["Leia o roteiro abaixo. Quando estiver satisfeito, clique em ",e.jsx("span",{className:"font-semibold text-cyan-200",children:"Gerar vídeo"})," — só então criamos as imagens, a narração, a trilha e montamos o vídeo."]})]}),e.jsxs("button",{onClick:()=>va.mutate(),disabled:va.isPending,className:"shrink-0 inline-flex items-center justify-center gap-2 rounded-xl bg-gradient-to-r from-blue-500 to-cyan-400 px-6 py-3 text-sm font-semibold text-white shadow-lg shadow-blue-900/40 hover:opacity-95 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"button-generate-video",children:[va.isPending?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(fe,{className:"h-4 w-4"}),"Gerar vídeo"]})]}),(()=>{const m=t.reelsEditorial||{};if(!m.rejectedHold)return null;const F=Array.isArray(m.fatalFailures)?m.fatalFailures.filter(k=>typeof k=="string"&&k.trim()):[],E=Array.isArray(m.candidates)?m.candidates:[];return e.jsxs("div",{className:"rounded-2xl border border-amber-500/30 bg-amber-500/[0.06] p-4","data-testid":"panel-rejected-hold",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Ce,{className:"h-4 w-4 text-amber-300"}),e.jsx("span",{className:"text-sm font-semibold text-amber-100",children:"O editor-chefe NÃO aprovou este roteiro"}),typeof m.score=="number"?e.jsxs("span",{className:"ml-auto rounded-full border border-amber-400/40 bg-amber-500/10 px-2 py-0.5 text-[11px] font-semibold text-amber-200","data-testid":"text-rejected-score",children:["nota ",m.score,"/100"]}):null]}),e.jsxs("p",{className:"text-xs text-zinc-300 leading-relaxed mb-2",children:["Ele foi estacionado aqui de propósito — mesmo no modo automático — para você decidir. Leia o roteiro abaixo: se estiver bom pra você, toque em ",e.jsx("span",{className:"font-semibold text-cyan-200",children:"Gerar vídeo"})," normalmente; se não, edite as cenas antes."]}),m.newAngle?e.jsxs("p",{className:"text-xs text-cyan-200 mb-2","data-testid":"text-new-angle",children:["Tentamos até um ângulo novo: ",e.jsx("span",{className:"font-semibold",children:m.newAngle})]}):null,F.length?e.jsx("ul",{className:"mb-2 space-y-1","data-testid":"list-fatal-failures",children:F.map((k,q)=>e.jsxs("li",{className:"text-xs text-amber-200/90 leading-snug",children:["• ",k]},q))}):null,E.length?e.jsxs("div",{className:"mt-2 rounded-xl border border-white/10 bg-black/25 p-3","data-testid":"panel-version-history",children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wider text-zinc-400",children:"Versões testadas (ficou a melhor)"}),e.jsx("div",{className:"mt-1.5 space-y-1",children:E.map((k,q)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs","data-testid":`row-candidate-${q}`,children:[e.jsx("span",{className:k.accepted?"text-emerald-300":"text-zinc-500",children:k.accepted?"✓":"✕"}),e.jsx("span",{className:"text-zinc-300 truncate",children:String(k.label||"?")}),e.jsxs("span",{className:"ml-auto shrink-0 text-zinc-400",children:["média ",Number(k.weightedMean??0).toFixed(1),"/10",Number(k.fatalFailures??0)?` · ${k.fatalFailures} fatal(is)`:""]})]},q))})]}):null]})})(),(()=>{const m=Array.isArray(t.hookVariants)?t.hookVariants.filter(E=>typeof E=="string"&&E.trim()):[];if(!m.length)return null;const F=x.find(E=>E.orderIndex===0)||x[0];return e.jsxs("div",{className:"rounded-2xl border border-cyan-500/20 bg-black/30 p-4","data-testid":"panel-hook-variants",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Ls,{className:"h-4 w-4 text-cyan-300"}),e.jsx("span",{className:"text-sm font-semibold text-white",children:"Teste de gancho (A/B)"})]}),e.jsx("p",{className:"text-xs text-zinc-400 leading-relaxed mb-3",children:"O gancho é a primeira frase do Reel — o que decide se a pessoa fica. Toque numa variação pra trocar; a troca é grátis e dá pra voltar atrás enquanto o vídeo não foi gerado."}),F?.text?e.jsxs("div",{className:"mb-2 rounded-xl border border-cyan-400/40 bg-cyan-500/[0.08] px-3 py-2","data-testid":"text-current-hook",children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wider text-cyan-300",children:"Gancho atual"}),e.jsx("p",{className:"mt-0.5 text-sm text-zinc-100 leading-snug",children:F.text})]}
28):null,e.jsx("div",{className:"grid gap-2",children:m.map((E,k)=>e.jsxs("button",{type:"button",onClick:()=>pa.mutate(k),disabled:pa.isPending,className:"group flex items-start gap-2 rounded-xl border border-white/10 bg-black/20 px-3 py-2 text-left transition-all hover:border-cyan-400/40 hover:bg-cyan-500/[0.06] disabled:opacity-50 disabled:cursor-not-allowed","data-testid":`button-hook-variant-${k}`,children:[pa.isPending?e.jsx(f,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin text-cyan-300"}):e.jsx(sa,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-zinc-500 group-hover:text-cyan-300"}),e.jsx("span",{className:"text-sm text-zinc-300 leading-snug group-hover:text-white",children:E})]},`${k}-${E.slice(0,24)}`))})]})})(),d?e.jsxs("div",{className:"rounded-2xl border border-white/[0.08] bg-black/40 overflow-hidden","data-testid":"panel-full-script",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 px-4 py-2.5 border-b border-white/[0.06]",children:[e.jsxs("span",{className:"text-xs font-medium text-zinc-400 flex items-center gap-1.5",children:[e.jsx(zs,{className:"h-3.5 w-3.5"})," Roteiro completo"]}),e.jsxs("span",{className:"text-xs text-zinc-600",children:[d.trim().split(/\s+/).filter(Boolean).length.toLocaleString("pt-BR")," palavras"]})]}),e.jsx("div",{className:"max-h-[420px] overflow-y-auto px-4 py-4 scrollbar-thin scrollbar-thumb-white/10 scrollbar-track-transparent",children:e.jsx("p",{className:"text-sm text-zinc-300 whitespace-pre-wrap leading-relaxed font-sans",children:d})})]}):null]})]})})(),e.jsxs("section",{className:"rounded-3xl border border-white/[0.07] bg-gradient-to-br from-[#0f1f3d]/50 via-[#0a0f1e] to-[#0a1c38]/30 overflow-hidden mb-8","data-testid":"section-preview",children:[e.jsx("div",{className:"aspect-video bg-black/60 flex items-center justify-center",children:ye?e.jsx("video",{src:`/api/videos/renders/${ae.id}/stream`,controls:!0,playsInline:!0,className:"h-full w-full","data-testid":"video-preview"},`${ae.id}-${ae.updatedAt||""}`):e.jsx("div",{className:"text-center px-6 py-12","data-testid":"placeholder-preview",children:l.status==="rendering"?e.jsxs("div",{className:"w-full max-w-md mx-auto","data-testid":"render-progress",children:[e.jsx(f,{className:"h-9 w-9 mx-auto mb-3 animate-spin text-cyan-400"}),e.jsx("p",{className:"text-zinc-100 font-semibold","data-testid":"text-render-phase",children:xe?gr[xe.phase||"scenes"]||"Montando o seu vídeo…":Cn||"Montando o seu vídeo…"}),xe?.phase==="scenes"&&(xe.total||0)>0&&e.jsxs("p",{className:"text-cyan-300/90 text-sm mt-1","data-testid":"text-render-scene",children:["Cena ",Math.min(xe.total||0,xe.current||0)," de ",xe.total]}),xe?.phase==="downloading"&&(xe.total||0)>0&&e.jsxs("p",{className:"text-cyan-300/90 text-sm mt-1","data-testid":"text-render-downloading",children:[Math.min(xe.total||0,xe.current||0)," de ",xe.total," clipes"]}),e.jsx("div",{className:"mt-4 h-2.5 w-full rounded-full bg-white/[0.06] overflow-hidden",children:xe?e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-blue-500 to-cyan-400 transition-all duration-700 ease-out",style:{width:`${Math.max(4,vs)}%`},"data-testid":"bar-render-progress"}):Xe&&Qe>0?e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-blue-500 to-cyan-400 transition-all duration-1000 ease-out",style:{width:`${Math.max(4,Qe)}%`},"data-testid":"bar-render-progress"}):e.jsx("div",{className:"h-full w-1/3 rounded-full bg-gradient-to-r from-blue-500 to-cyan-400 animate-pulse"})}),e.jsxs("div",{className:"mt-2 flex items-center justify-center gap-2 text-xs text-zinc-500",children:[xe?e.jsxs("span",{"data-testid":"text-render-pct",children:[vs,"%"]}):Xe&&Qe>0?e.jsxs("span",{"data-testid":"text-render-pct",children:["~",Qe,"%"]}):null,Ra&&e.jsx("span",{"aria-hidden":!0,children:"·"}),Ra&&e.jsx("span",{"data-testid":"text-render-elapsed",children:Ra}),Xe&&Ns>9e4&&e.jsxs(e.Fragment,{children:[e.jsx("span",{"aria-hidden":!0,children:"·"}),e.jsxs("span",{children:["~",Math.ceil(Ns/6e4)," min restantes"]})]})]}),Xe&&e.jsx("p",{className:"text-zinc-600 text-xs mt-1",children:"Valores estimados — o render roda no servidor dedicado."}),e.jsx("p",{className:"text-zinc-500 text-sm mt-3",children:"A renderização roda em segundo plano. Atualizamos sozinhos."}),Sn&&e.jsxs("div",{className:"mt-4 flex flex-col items-center",children:[e.jsxs("p",{className:"text-amber-300/90 text-sm mb-2 inline-flex items-center gap-1.5",children:[e.jsx(Ce,{className:"h-4 w-4"})," Está demorando mais que o normal."]}),e.jsxs("button",{onClick:()=>
28W.mutate(),disabled:W.isPending||ht,className:"inline-flex items-center gap-2 rounded-xl border border-cyan-400/30 bg-cyan-500/10 px-5 py-2.5 text-sm font-semibold text-cyan-200 hover:bg-cyan-500/20 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"button-rerender-stuck",children:[W.isPending?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(Te,{className:"h-4 w-4"}),"Renderizar novamente"]})]})]}):l.status==="failed"?vn?e.jsxs(e.Fragment,{children:[e.jsx(Ce,{className:"h-10 w-10 mx-auto mb-3 text-amber-400"}),e.jsx("p",{className:"text-zinc-200 font-medium",children:"A montagem final do vídeo falhou."}),(It?.eioRefunds??0)>0?e.jsxs("p",{className:"text-amber-300/80 text-sm mt-1",children:["A falha é de infraestrutura (erro de I/O ao ler arquivos do servidor) — ",e.jsx("strong",{children:"não é o conteúdo do vídeo"}),". Clique para tentar de novo; se persistir, um novo deploy resolve."]}):e.jsx("p",{className:"text-zinc-500 text-sm mt-1",children:l?.metadata?.videoPipelineMode==="asmr"?"Todas as cenas ASMR estão prontas (clipes com áudio nativo) — faltou só montar o MP4. Renderize de novo.":"Boa notícia: as imagens e a narração de todas as cenas já estão prontas — faltou só montar o MP4 final. É só renderizar de novo."}),e.jsxs("button",{onClick:()=>W.mutate(),disabled:W.isPending||ht,className:"mt-4 inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-blue-500 to-cyan-400 px-5 py-2.5 text-sm font-semibold text-white shadow-lg shadow-blue-900/40 hover:opacity-95 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"button-rerender",children:[W.isPending?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(fe,{className:"h-4 w-4"}),"Renderizar novamente"]})]}):l?.metadata?.videoPipelineMode==="asmr"&&y.size>0?e.jsxs(e.Fragment,{children:[e.jsx(Ce,{className:"h-10 w-10 mx-auto mb-3 text-amber-400"}),e.jsxs("p",{className:"text-zinc-200 font-medium",children:["Geração interrompida — ",y.size," ",y.size===1?"cena pronta":"cenas prontas"]}),e.jsxs("p",{className:"text-zinc-400 text-sm mt-1 max-w-sm mx-auto",children:["Você pode montar o vídeo agora com as ",y.size," cenas disponíveis (sem gastar mais) ou retomar a geração para completar as cenas restantes."]}),e.jsxs("div",{className:"mt-4 flex flex-col sm:flex-row items-center justify-center gap-3",children:[e.jsxs("button",{onClick:()=>Tt.mutate(),disabled:Tt.isPending||Ae.isPending,className:"inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-blue-500 to-cyan-400 px-5 py-2.5 text-sm font-semibold text-white shadow-lg shadow-blue-900/40 hover:opacity-95 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"button-render-partial",children:[Tt.isPending?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(fe,{className:"h-4 w-4"}),"Montar com ",y.size," cenas prontas"]}),e.jsxs("button",{onClick:()=>Ae.mutate(),disabled:Ae.isPending||Tt.isPending,className:"inline-flex items-center gap-2 rounded-xl border border-zinc-600 bg-zinc-800/60 px-5 py-2.5 text-sm font-medium text-zinc-300 hover:bg-zinc-700/60 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"button-resume",children:[Ae.isPending?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(Te,{className:"h-4 w-4"}),"Retomar geração"]}),H&&e.jsxs("button",{onClick:()=>{window.confirm("Cancelar este vídeo e começar um NOVO do zero com a mesma fonte? Nada é apagado — este projeto continua salvo. A oportunidade de origem será reaberta e você vai para a tela de criar um novo vídeo.")&&it.mutate()},disabled:it.isPending||Tt.isPending||Ae.isPending,className:"inline-flex items-center gap-2 rounded-xl border border-cyan-400/40 bg-cyan-500/10 px-5 py-2.5 text-sm font-semibold text-cyan-200 hover:bg-cyan-500/20 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"button-cancel-restart",children:[it.isPending?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(sa,{className:"h-4 w-4"}),"Cancelar e gerar do zero"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ce,{className:`h-10 w-10 mx-auto mb-3 ${bt?"text-amber-400":"text-red-400"}`}),e.jsx("p",{className:"text-zinc-300 font-medium",children:bt?"Geração pausada por proteção automática":l?.metadata?.videoPipelineMode==="asmr"?"A geração dos clipes ASMR foi interrompida.":"A geração das imagens foi interrompida."}),e.jsx("p",{className:"text-zinc-500 text-sm mt-1",children:bt?"Todo o conteúdo gerado está salvo. A geração foi pausada automaticamente para proteger a plataforma.":"Pode ter sido uma instabilidade no provedor. Clique para retomar — vamos tentar de novo com provedores alternativos e aproveitar tudo que já ficou pronto."}),bt?$?e.jsxs("button",{onClick:()=>mt.mutate(),disabled:mt.isPending,className:"mt-4 inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-amber-500 to-orange-400 px-5 py-2.5 text-sm font-semibold text-white shadow-lg shadow-amber-900/40 hover:opacity-95 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"button-gen-reset-card",children:[mt.isPending?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(Te,{className:"h-4 w-4"}),"Reabrir e retomar geração"]}):Rt?e.jsx("p",{className:"text-amber-200/70 text-sm mt-3",children:"Nossa equipe já foi notificada e vai reabrir em breve."}):e.jsx("p",{className:"text-amber-200/70 text-sm mt-3","data-testid":"text-gen-auto-retry-info",children:We&&We.getTime()>Date.now()?`Tentativa automática às ${We.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}${gt>0?` (${gt+1}ª de ${Yt})`:""}.`:"Retomada automática em andamento…"}):e.jsxs("div",{className:"mt-4 flex flex-col sm:flex-row items-center justify-center gap-3",children:[e.jsxs("button",{onClick:()=>Ae.mutate(),disabled:Ae.isPending||it.isPending,className:"inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-blue-500 to-cyan-400 px-5 py-2.5 text-sm font-semibold text-white shadow-lg shadow-blue-900/40 hover:opacity-95 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"button-resume",children:[Ae.isPending?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(Te,{className:"h-4 w-4"}),"Retomar geração"]}),H&&e.jsxs("button",{onClick:()=>{window.confirm("Cancelar este vídeo e começar um NOVO do zero com a mesma fonte? Nada é apagado — este projeto continua salvo. A oportunidade de origem será reaberta e você vai para a tela de criar um novo vídeo.")&&it.mutate()},disabled:it.isPending||Ae.isPending,className:"inline-flex items-center gap-2 rounded-xl border border-cyan-400/40 bg-cyan-500/10 px-5 py-2.5 text-sm font-semibold text-cyan-200 hover:bg-cyan-500/20 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"button-cancel-restart",children:[it.isPending?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(sa,{className:"h-4 w-4"}),"Cancelar e gerar do zero"]})]})]}):Ve?hn?e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:"h-10 w-10 mx-auto mb-3 text-cyan-400 animate-pulse"}),e.jsx("p",{className:"text-zinc-300 font-medium",children:"Renderizando o vídeo…"}),e.jsx("p",{className:"text-zinc-500 text-sm mt-1",children:"A montagem final está rodando em segundo plano. Isso pode levar alguns minutos — a página atualiza sozinha quando ficar pronto."})]}):e.jsxs(e.Fragment,{children:[e.jsx(f,{className:"h-10 w-10 mx-auto mb-3 animate-spin text-cyan-400"}),e.jsx("p",{className:"text-zinc-300 font-medium",children:"Preparando a mídia…"}),e.jsx("p",{className:"text-zinc-500 text-sm mt-1",children:xs?"Seu roteiro está sendo processado: cenas visuais e narração estão sendo gerados.":z?"Roteiro, cenas em vídeo e narração estão sendo gerados.":"Roteiro, imagens e narração estão sendo gerados."}),Je.total>0&&e.jsxs("p",{className:"text-cyan-300/90 text-sm mt-2 font-medium","data-testid":"text-image-progress",children:[Je.ready," de ",Je.total," ",gn]}),$e&&e.jsxs("p",{className:"text-zinc-500 text-xs mt-1 max-w-sm mx-auto","data-testid":"text-pool-note",children:["Cada segundo é v
28ídeo real gerado pela IA — são ",$e.total," clipes. Pode levar alguns minutos."]}),fs&&e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"text-amber-300/90 text-sm mb-2",children:"Está demorando mais que o normal."}),e.jsxs("button",{onClick:()=>Ae.mutate(),disabled:Ae.isPending,className:"inline-flex items-center gap-2 rounded-xl border border-cyan-400/30 bg-cyan-500/10 px-5 py-2.5 text-sm font-semibold text-cyan-200 hover:bg-cyan-500/20 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"button-resume",children:[Ae.isPending?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(Te,{className:"h-4 w-4"}),"Retomar geração"]})]}),Je.ready>0&&e.jsxs("div",{className:"mt-5",children:[e.jsxs("button",{onClick:()=>{window.confirm(`Pausar a geração de novas imagens e montar o vídeo AGORA com as ${Je.ready} cena(s) já prontas? Nada é perdido e o projeto continua salvo — você pode gerar o resto e renderizar de novo depois.`)&&ga.mutate()},disabled:ga.isPending,className:"inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-cyan-500 to-blue-500 px-6 py-3 text-sm font-bold text-white shadow-lg shadow-cyan-500/20 hover:from-cyan-400 hover:to-blue-400 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"button-pause-and-render",children:[ga.isPending?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(fe,{className:"h-4 w-4"}),"Pausar e montar com ",Je.ready," cena",Je.ready===1?"":"s"," pronta",Je.ready===1?"":"s"]}),e.jsx("p",{className:"text-zinc-500 text-xs mt-2 max-w-sm mx-auto",children:"Interrompe a geração das próximas imagens e monta o vídeo já com o que está pronto. Você não perde nada — pode gerar o resto e renderizar de novo quando quiser."})]}),e.jsx("div",{className:"mt-4",children:e.jsxs("button",{onClick:()=>{window.confirm("Cancelar e excluir este projeto? Esta ação não pode ser desfeita.")&&fa.mutate()},disabled:fa.isPending,className:"inline-flex items-center gap-2 rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-2 text-sm font-medium text-red-300 hover:bg-red-500/20 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"button-cancel-generation",children:[fa.isPending?e.jsx(f,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(jt,{className:"h-3.5 w-3.5"}),"Cancelar geração"]})})]}):l.status==="awaiting_script_approval"?e.jsxs(e.Fragment,{children:[e.jsx(ce,{className:"h-10 w-10 mx-auto mb-3 text-cyan-400"}),e.jsx("p",{className:"text-zinc-300 font-medium",children:"Roteiro pronto para revisão"}),e.jsxs("p",{className:"text-zinc-500 text-sm mt-1",children:["Revise o roteiro abaixo e clique em ",e.jsx("span",{className:"text-cyan-300",children:"Gerar vídeo"})," para criar as imagens, a narração e montar o MP4."]})]}):e.jsxs(e.Fragment,{children:[e.jsx(qt,{className:"h-10 w-10 mx-auto mb-3 text-zinc-600"}),e.jsx("p",{className:"text-zinc-300 font-medium",children:"Ainda sem vídeo renderizado"}),e.jsxs("p",{className:"text-zinc-500 text-sm mt-1",children:["Quando as cenas estiverem prontas, clique em ",e.jsx("span",{className:"text-cyan-300",children:"Renderizar"}),"."]})]})})}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 px-5 py-4 border-t border-white/[0.06]",children:[e.jsxs("div",{className:"text-sm text-zinc-400 min-w-0",children:[ye?e.jsxs("span",{"data-testid":"text-render-duration",children:["Vídeo pronto",ae?.durationMs?` · ${Fs(ae.durationMs)}`:""]}):e.jsx("span",{children:"O render final junta imagens e narração num MP4. As legendas saem em arquivo .srt separado (nunca queimadas no vídeo)."}),ye&&!!ae?.metadata?.subtitles?.cues&&e.jsx("span",{className:"mt-1 block text-[12px] text-cyan-300/90","data-testid":"text-caption-policy",children:"Legendas em arquivo .srt — nunca queimadas no vídeo."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[ye&&e.jsxs("a",{href:`/api/videos/renders/${ae.id}/download`,className:"inline-flex items-center gap-2 rounded-xl border border-white/10 bg-white/[0.03] px-4 py-2.5 text-sm font-medium text-zinc-200 hover:bg-white/[0.06] transition-colors","data-testid":"button-download",children:[e.jsx(Le,{className:"h-4 w-4"})," Baixar MP4"]}
28),ye&&!!ae?.metadata?.subtitles?.cues&&e.jsxs("a",{href:`/api/videos/renders/${ae.id}/subtitles.srt`,className:"inline-flex items-center gap-2 rounded-xl border border-white/10 bg-white/[0.03] px-4 py-2.5 text-sm font-medium text-zinc-200 hover:bg-white/[0.06] transition-colors","data-testid":"button-download-srt",children:[e.jsx(Ts,{className:"h-4 w-4"})," Baixar legendas (.srt)"]}),ye&&ws&&!Se&&!O&&e.jsxs("button",{onClick:()=>Bt(!0),disabled:rt,className:"inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-rose-600 to-red-500 px-4 py-2.5 text-sm font-semibold text-white shadow-lg shadow-red-900/40 hover:opacity-95 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"button-publish-youtube",children:[rt?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(He,{className:"h-4 w-4"}),rt?"Publicando…":vt?"Tentar publicar de novo":"Publicar no YouTube"]}),e.jsxs("button",{onClick:()=>W.mutate(),disabled:!hs,className:"inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-blue-500 to-cyan-400 px-4 py-2.5 font-semibold text-white shadow-lg shadow-blue-900/40 hover:opacity-95 disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"button-render",title:ht?"Render em manutenção técnica":l.status==="rendering"?"Render em andamento — aguarde a conclusão":hs?"":"Aguarde a mídia das cenas ficar pronta",children:[W.isPending||l.status==="rendering"?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(fe,{className:"h-4 w-4"}),l.status==="rendering"?"Renderizando…":ye?"Renderizar de novo":"Renderizar"]})]})]}),ht&&e.jsx("div",{className:"px-5 py-4 border-t border-amber-400/20 bg-amber-500/[0.06]","data-testid":"banner-render-maintenance",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-2.5 min-w-0",children:[e.jsx(Ce,{className:"h-5 w-5 shrink-0 text-amber-400 mt-0.5"}),e.jsxs("div",{className:"min-w-0",children:[mn?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-amber-200 font-medium text-sm","data-testid":"text-maintenance-reason",children:"Vídeo longo demais para a montagem segura"}),e.jsx("p",{className:"text-amber-200/70 text-sm mt-0.5",children:"Este vídeo tem muitas cenas e, por enquanto, está acima do limite que conseguimos montar com segurança sem arriscar a plataforma. Suas imagens e narração estão salvas. Estamos liberando a montagem de vídeos longos — assim que o limite subir, este render é reaberto."})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-amber-200 font-medium text-sm","data-testid":"text-maintenance-reason",children:"Render em manutenção técnica"}),e.jsx("p",{className:"text-amber-200/70 text-sm mt-0.5",children:"A montagem deste vídeo apresentou instabilidade e foi pausada automaticamente para proteger a plataforma. Nossa equipe já foi avisada e vai liberar o render em breve. Suas imagens e narração estão salvas."})]}),$&&Ea&&e.jsx("p",{className:"text-amber-200/50 text-xs mt-1.5 font-mono","data-testid":"text-maintenance-detail",children:Ea})]})]}),$&&e.jsxs("button",{onClick:()=>ha.mutate(),disabled:ha.isPending,className:"shrink-0 inline-flex items-center gap-2 rounded-xl border border-cyan-400/30 bg-cyan-500/10 px-4 py-2.5 text-sm font-semibold text-cyan-200 hover:bg-cyan-500/20 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"button-render-reset",title:"Admin: zera o contador de tentativas e libera o render",children:[ha.isPending?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(Te,{className:"h-4 w-4"}),"Reabrir render"]})]})}),bt&&e.jsx("div",{className:"px-5 py-4 border-t border-amber-400/20 bg-amber-500/[0.05]","data-testid":"banner-gen-maintenance",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-2.5 min-w-0",children:[e.jsx(Ce,{className:"h-5 w-5 shrink-0 text-amber-400 mt-0.5"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-amber-200 font-medium text-sm","data-testid":"text-gen-maintenance-reason",children:"Geração pausada por proteção"}),e.jsx("p",{className:"text-amber-200/70 text-sm mt-0.5",children:"A geração deste vídeo apresentou instabilidade (o projeto era muito pesado) e foi pausada automaticamente para proteger a plataforma. Tudo o que já foi gerado está salvo."}),!$&&!Rt&&We&&e.jsx("p",{className:"text-amber-300/80 text-xs mt-1.5","data-testid":"text-gen-maintenance-retry-time",children:We.getTime()>Date.now()?`Retomada automática às ${We.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}${gt>0?` (${gt+1}ª de ${Yt})`:""}.`:"Retomada automática em andamento…"}),!$&&Rt&&e.jsx("p",{className:"text-amber-200/60 text-xs mt-1.5",children:"Nossa equipe já foi notificada e vai reabrir em breve."}),$&&bs&&e.jsx("p",{className:"text-amber-200/50 text-xs mt-1.5 font-mono","data-testid":"text-gen-maintenance-detail",children:bs}),$&&!Rt&&e.jsxs("p",{className:"text-amber-200/50 text-xs mt-0.5","data-testid":"text-gen-maintenance-retry-count",children:["Auto-retry: ",gt,"/",Yt,We&&` · próximo às ${We.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`]})]})]}),$&&e.jsxs("button",{onClick:()=>mt.mutate(),disabled:mt.isPending,className:"shrink-0 inline-flex items-center gap-2 rounded-xl border border-cyan-400/30 bg-cyan-500/10 px-4 py-2.5 text-sm font-semibold text-cyan-200 hover:bg-cyan-500/20 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"button-gen-reset",title:"Admin: zera o contador de tentativas e reabre a geração",children:[mt.isPending?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(Te,{className:"h-4 w-4"}),"Reabrir geração"]})]})}),$&&(It?.eioRefunds??0)>0&&!ht&&e.jsx("div",{className:"px-5 py-4 border-t border-cyan-400/20 bg-cyan-500/[0.05]","data-testid":"banner-eio-infra",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-2.5 min-w-0",children:[e.jsx(Ce,{className:"h-5 w-5 shrink-0 text-cyan-300 mt-0.5"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-cyan-200 font-medium text-sm",children:"EIO de infraestrutura detectado"}),e.jsxs("p",{className:"text-cyan-200/60 text-sm mt-0.5",children:["Este render falhou ",e.jsxs("strong",{className:"text-cyan-200",children:[It?.eioRefunds,"×"]})," por erro de I/O ao ler arquivos do servidor (overlay de deploy corrompido) — não é o conteúdo do vídeo. Após um ",e.jsx("strong",{className:"text-cyan-200",children:"republish"}),", o overlay é recriado e o EIO some. Clique para zerar o contador e disparar o render com o overlay limpo."]})]})]}),e.jsxs("button",{onClick:()=>ba.mutate(),disabled:ba.isPending,className:"shrink-0 inline-flex items-center gap-2 rounded-xl border border-cyan-400/30 bg-cyan-500/10 px-4 py-2.5 text-sm font-semibold text-cyan-200 hover:bg-cyan-500/20 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"button-reset-and-render",title:"Admin: zera EIO counter + dispara render imediatamente",children:[ba.isPending?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(fe,{className:"h-4 w-4"}),"Limpar EIO e Renderizar"]})]})}),ye&&!O&&e.jsxs("div",{className:"px-5 py-4 border-t border-white/[0.06]","data-testid":"section-thumbnails",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(st,{className:"h-4 w-4 text-cyan-300 shrink-0"}),e.jsx("span",{className:"text-sm font-semibold text-zinc-100",children:"Miniatura do YouTube"}),$a&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-full border border-cyan-500/30 bg-cyan-500/10 text-cyan-200","data-testid":"badge-thumb-chosen",children:[e.jsx(ue,{className:"h-3 w-3"})," Escolhida"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:()=>Ut.mutate(),disabled:Ut.isPending,className:"inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-blue-500 to-cyan-400 px-4 py-2 text-sm font-semibold text-white shadow-lg shadow-blue-900/40 hover:opacity-95 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"button-generate-thumbnails",children:[Ut.isPending?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(ce,{className:"h-4 w-4"}),Ut.isPending?"Gerando…":Ma.length>0?"Gerar de novo":"Gerar miniatura"]}),e.jsxs("label",{className:`inline-flex items-center gap-2 rounded-xl border border-white/10 bg-white/[0.03] px-4 py-2 text-sm font-medium text-zinc-200 hover:bg-white/[0.06] cursor-pointer ${Sa.isPending?"opacity-50 pointer-events-none":""}
28`,"data-testid":"button-upload-thumbnail",children:[Sa.isPending?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(kt,{className:"h-4 w-4"}),"Enviar a minha",e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:t=>{const s=t.target.files?.[0];if(t.target.value="",!!s){if(s.size>9*1024*1024){a({title:"Imagem muito grande",description:"Envie uma imagem de até 9 MB.",variant:"destructive"});return}Sa.mutate(s)}},"data-testid":"input-thumbnail-file"})]})]})]}),Ma.length>0?e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3","data-testid":"grid-thumbnails",children:Ma.map((t,s)=>{const c=$a===t.url,d=on===t.url;return e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>ds.mutate(t.url),disabled:ds.isPending,className:`group relative block overflow-hidden rounded-2xl border text-left transition-all disabled:cursor-not-allowed ${c?"border-cyan-400 ring-2 ring-cyan-400/40":"border-white/10 hover:border-cyan-400/40"}`,"data-testid":`button-thumbnail-${s}`,children:[e.jsx("img",{src:t.url,alt:t.hook||`Miniatura ${s+1}`,className:"aspect-video w-full object-cover",loading:"lazy"}),c&&e.jsx("span",{className:"absolute top-2 right-2 inline-flex items-center justify-center h-6 w-6 rounded-full bg-cyan-500 text-white shadow",children:e.jsx(ue,{className:"h-4 w-4"})}),t.source==="own"&&e.jsx("span",{className:"absolute top-2 left-2 text-[10px] px-1.5 py-0.5 rounded bg-black/60 text-cyan-200 border border-cyan-500/30",children:"Sua imagem"}),t.hook&&e.jsx("span",{className:"absolute bottom-0 inset-x-0 px-2 py-1.5 text-[11px] font-medium text-white bg-gradient-to-t from-black/80 to-transparent line-clamp-2",children:t.hook})]}),p?.thumbnailEditorEnabled&&!d&&e.jsxs("button",{type:"button",onClick:()=>{za(t.url),cs(t.hook||""),us("#FFD23F")},className:"inline-flex items-center justify-center gap-1.5 rounded-lg border border-cyan-500/30 bg-cyan-500/10 px-2.5 py-1.5 text-xs font-medium text-cyan-200 hover:bg-cyan-500/20 transition-colors","data-testid":`button-edit-thumbnail-${s}`,children:[e.jsx(da,{className:"h-3.5 w-3.5"})," Editar texto"]}),p?.thumbnailEditorEnabled&&d&&e.jsxs("div",{className:"rounded-xl border border-cyan-500/30 bg-cyan-500/[0.04] p-3 space-y-2","data-testid":`editor-thumbnail-${s}`,children:[e.jsx(wt,{value:Ca,onChange:m=>cs(m.target.value),rows:2,maxLength:80,placeholder:"Texto da miniatura (curto e impactante)",className:"w-full resize-none bg-black/40 border-white/10 text-sm text-white placeholder:text-zinc-500","data-testid":`input-thumbnail-text-${s}`}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("select",{value:ms,onChange:m=>us(m.target.value),className:"rounded-lg bg-black/40 border border-white/10 px-2 py-1.5 text-xs text-white focus:outline-none focus:border-cyan-400/50","data-testid":`select-thumbnail-accent-${s}`,children:[e.jsx("option",{value:"#FFD23F",children:"Dourado"}),e.jsx("option",{value:"#FF3B30",children:"Vermelho"}),e.jsx("option",{value:"#22D3EE",children:"Ciano"}),e.jsx("option",{value:"#FFFFFF",children:"Branco"})]}),e.jsxs("button",{type:"button",onClick:()=>Gt.mutate({url:t.url,text:Ca.trim(),accent:ms}),disabled:Gt.isPending||!Ca.trim(),className:"inline-flex items-center gap-1.5 rounded-lg bg-cyan-500 px-3 py-1.5 text-xs font-semibold text-white hover:bg-cyan-400 disabled:opacity-50 disabled:cursor-not-allowed transition-colors","data-testid":`button-save-thumbnail-${s}`,children:[Gt.isPending?e.jsx(f,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ma,{className:"h-3.5 w-3.5"}),"Salvar"]}),e.jsx("button",{type:"button",onClick:()=>za(null),disabled:Gt.isPending,className:"inline-flex items-center gap-1.5 rounded-lg border border-white/10 px-3 py-1.5 text-xs font-medium text-zinc-300 hover:bg-white/5 disabled:opacity-50 transition-colors","data-testid":`button-cancel-thumbnail-${s}`,children:"Cancelar"})]})]})]},t.url||s)})}):e.jsx("p",{className:"text-sm text-zinc-500","data-testid":"text-thumbnails-empty",children:"Gere uma miniatura poderosa por IA (estilo viral) ou envie a sua. A escolhida é aplicada automaticamente ao publicar no YouTube."})]}),ye&&(()=>{const t=l.metadata||{},s=(t.language||"pt-BR").toLowerCase(),c=r?.selectedTitle||l.title||"",d=r?.description||"",m=Array.isArray(r?.tags)&&r.tags.length>0?r.tags:c.toLowerCase().replace(/[^a-záéíóúàâêôãõüç\s]/gi,"").split(/\s+/).filter(re=>re.length>3).slice(0,8).map(re=>`#${re}`),F=Ha(s),E=Es(s,"short"),k=String(t.igCaption||r?.igCaption||d||"").trim(),ie=((Array.isArray(t.hashtags)&&t.hashtags.length>0?t.hashtags:Array.isArray(r?.hashtags)?r.hashtags:Array.isArray(m)?m:[])||[]).map(re=>`#${String(re).replace(/^#+/,"").trim()}`).filter(re=>re.length>
281).slice(0,15).join(" "),J=[k,ie].filter(Boolean).join(`
29
30`).trim(),K=x.slice(0,25);let D=0;const ne=[];for(const re of K){const Oe=(re.text||"").replace(/\n/g," ").slice(0,60).trim();if(Oe){const Rn=String(Math.floor(D/60)).padStart(2,"0"),Fn=String(Math.round(D%60)).padStart(2,"0");ne.push(`${Rn}:${Fn} ${Oe}${Oe.length>=60?"…":""}`)}D+=40}const ze=[c,"",d||`${c} — criado com IA editorial.`,"",E,"",ne.length>0?F.inThisVideo:"",...ne,"","━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",F.subscribeShort,"",m.slice(0,10).join(" ")].join(`
31`).trim(),X=(re,Oe)=>{navigator.clipboard.writeText(re).then(()=>{ct(Oe),setTimeout(()=>ct(null),2200)})},De=async()=>{if(ae){as(!0);try{const Oe=await(await fetch(`/api/videos/renders/${ae.id}/subtitles.srt`)).text();await navigator.clipboard.writeText(Oe),ct("pub-srt"),setTimeout(()=>ct(null),2200)}catch{a({title:"Erro ao copiar legenda",description:"Tente baixar o arquivo .srt diretamente.",variant:"destructive"})}finally{as(!1)}}},ot=!!ae?.metadata?.subtitles?.cues,Ee="flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-medium text-zinc-300 hover:text-white bg-white/[0.04] hover:bg-white/[0.07] border border-white/[0.08] hover:border-cyan-400/25 transition-colors",yt="flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-medium text-emerald-300 bg-emerald-500/10 border border-emerald-500/20 transition-colors";return e.jsxs("div",{className:"px-5 py-5 border-t border-white/[0.06]","data-testid":"section-publish-kit",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(tt,{className:"h-4 w-4 text-cyan-300 shrink-0"}),e.jsx("span",{className:"text-sm font-semibold text-zinc-100",children:"Publicação manual"}),e.jsxs("span",{className:"text-xs text-zinc-500",children:["· copie e cole no ",O?"Instagram":"YouTube Studio"]})]}),e.jsxs("div",{className:"space-y-3",children:[O&&e.jsx(kr,{projectId:u,defaultCaption:J,igPubs:Tn,igJobActive:Mn,detailKey:w}),O&&e.jsx(zr,{projectId:u,defaultCaption:J,ttPubs:An,ttJobActive:$n,detailKey:w}),O&&e.jsxs("div",{className:"rounded-2xl bg-gradient-to-br from-sky-500/[0.08] to-cyan-500/[0.04] border border-sky-400/25 p-4 space-y-2.5","data-testid":"panel-ig-caption",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[11px] font-semibold text-sky-300 uppercase tracking-wider",children:"📱 Legenda do Instagram"}),e.jsx("button",{onClick:()=>X(J,"pub-ig"),disabled:!J,className:Ne==="pub-ig"?yt:`${Ee} disabled:opacity-50 disabled:cursor-not-allowed`,"data-testid":"button-copy-ig-caption",children:Ne==="pub-ig"?e.jsxs(e.Fragment,{children:[e.jsx(et,{className:"h-3.5 w-3.5"})," Copiado!"]}):e.jsxs(e.Fragment,{children:[e.jsx(tt,{className:"h-3.5 w-3.5"})," Copiar legenda"]})})]}),J?e.jsx("textarea",{readOnly:!0,value:J,rows:8,className:"w-full rounded-xl bg-black/30 border border-white/[0.06] px-3 py-2.5 text-xs text-zinc-200 leading-relaxed resize-none focus:outline-none focus:border-sky-400/30 scrollbar-thin",onClick:re=>re.target.select(),"data-testid":"textarea-ig-caption"}):e.jsx("p",{className:"text-xs text-zinc-500 italic","data-testid":"text-ig-caption-empty",children:"A legenda será gerada junto com o roteiro. Se o vídeo já ficou pronto sem legenda, retome a geração."}),e.jsx("p",{className:"text-[11px] text-sky-300/80",children:"Baixe o MP4 vertical (9:16) acima, cole esta legenda no Instagram e poste. 🚀"})]}),O&&(()=>{const re=String(t?.reelsCover?.url||"");return e.jsxs("div",{className:"rounded-2xl bg-gradient-to-br from-fuchsia-500/[0.08] to-purple-500/[0.04] border border-fuchsia-400/25 p-4 space-y-2.5","data-testid":"panel-reels-cover",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[11px] font-semibold text-fuchsia-300 uppercase tracking-wider",children:"🖼 Capa do Reels"}),e.jsxs("div",{className:"flex items-center gap-2",children:[re&&e.jsxs("a",{href:re,download:!0,className:Ee,"data-testid":"link-download-reels-cover",children:[e.jsx(Le,{className:"h-3.5 w-3.5"})," Baixar capa"]}),e.jsx("button",{onClick:()=>Ht.mutate(),disabled:Ht.isPending,className:`${Ee} disabled:opacity-50 disabled:cursor-not-allowed`,"data-testid":"button-generate-reels-cover",children:Ht.isPending?e.jsxs(e.Fragment,{children:[e.jsx(f,{className:"h-3.5 w-3.5 animate-spin"})," Gerando…"]}):re?e.jsxs(e.Fragment,{children:[e.jsx(Te,{className:"h-3.5 w-3.5"})," Gerar novamente"]}):e.jsxs(e.Fragment,{children:[e.jsx(ce,{className:"h-3.5 w-3.5"})," Gerar capa"]})})]})]}),re?e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("img",{src:re,alt:"Capa do Reels",className:"w-24 aspect-[9/16] object-cover rounded-xl border border-white/10 shrink-0","data-testid":"img-reels-cover"}),e.jsx("p",{className:"text-[11px] text-zinc-500 leading-relaxed pt-1",children:"Capa vertical em alta qualidade com o seu clone e o personagem do vídeo. Ao publicar direto pelo painel acima, ela já vai como capa do Reels; no fluxo manual, baixe e selecione ao postar."})]}):e.jsx("p",{className:"text-[11px] text-zinc-500","data-testid":"text-reels-cover-empty",children:Ht.isPending?"Gerando a capa em alta qualidade — ela aparece aqui em instantes.":"A c
31apa é gerada automaticamente quando o vídeo fica pronto. Se ainda não apareceu, gere agora."})]})})(),O&&u&&e.jsx(vr,{projectId:u,initialCta:String(p?.project?.metadata?.ctaText||""),detailKey:w}),(()=>{const re=p?.project?.metadata?.postRenderSpeed,Oe=Number(re);return!u||!Number.isFinite(Oe)||Oe<=0?null:e.jsx(yr,{projectId:u,initialSpeed:Oe,detailKey:w})})(),e.jsxs("div",{className:"rounded-2xl bg-white/[0.025] border border-white/[0.07] p-4 space-y-2.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[11px] font-semibold text-cyan-300 uppercase tracking-wider",children:"📌 Título"}),e.jsx("button",{onClick:()=>X(c,"pub-title"),className:Ne==="pub-title"?yt:Ee,"data-testid":"button-copy-pub-title",children:Ne==="pub-title"?e.jsxs(e.Fragment,{children:[e.jsx(et,{className:"h-3.5 w-3.5"})," Copiado!"]}):e.jsxs(e.Fragment,{children:[e.jsx(tt,{className:"h-3.5 w-3.5"})," Copiar"]})})]}),e.jsx("p",{className:"text-sm text-white leading-snug break-words","data-testid":"text-pub-title",children:c||e.jsx("span",{className:"text-zinc-500 italic",children:"Título não definido"})})]}),!O&&e.jsxs("div",{className:"rounded-2xl bg-white/[0.025] border border-white/[0.07] p-4 space-y-2.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[11px] font-semibold text-cyan-300 uppercase tracking-wider",children:"📝 Descrição YouTube"}),e.jsx("button",{onClick:()=>X(ze,"pub-desc"),className:Ne==="pub-desc"?yt:Ee,"data-testid":"button-copy-pub-desc",children:Ne==="pub-desc"?e.jsxs(e.Fragment,{children:[e.jsx(et,{className:"h-3.5 w-3.5"})," Copiado!"]}):e.jsxs(e.Fragment,{children:[e.jsx(tt,{className:"h-3.5 w-3.5"})," Copiar tudo"]})})]}),e.jsx("textarea",{readOnly:!0,value:ze,rows:7,className:"w-full rounded-xl bg-black/30 border border-white/[0.06] px-3 py-2.5 text-xs text-zinc-300 font-mono leading-relaxed resize-none focus:outline-none focus:border-cyan-400/30 scrollbar-thin",onClick:re=>re.target.select(),"data-testid":"textarea-pub-desc"})]}),ot&&e.jsxs("div",{className:"rounded-2xl bg-white/[0.025] border border-white/[0.07] p-4 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[11px] font-semibold text-cyan-300 uppercase tracking-wider",children:"🗂 Legenda (.srt)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:De,disabled:ts,className:Ne==="pub-srt"?yt:`${Ee} disabled:opacity-50 disabled:cursor-not-allowed`,"data-testid":"button-copy-srt",children:ts?e.jsxs(e.Fragment,{children:[e.jsx(f,{className:"h-3.5 w-3.5 animate-spin"})," Copiando…"]}):Ne==="pub-srt"?e.jsxs(e.Fragment,{children:[e.jsx(et,{className:"h-3.5 w-3.5"})," Copiado!"]}):e.jsxs(e.Fragment,{children:[e.jsx(tt,{className:"h-3.5 w-3.5"})," Copiar conteúdo"]})}),e.jsxs("a",{href:`/api/videos/renders/${ae.id}/subtitles.srt`,download:!0,className:Ee,"data-testid":"link-download-srt-kit",children:[e.jsx(Le,{className:"h-3.5 w-3.5"})," Baixar .srt"]})]})]}),e.jsx("p",{className:"text-[11px] text-zinc-500",children:O?"Legenda sincronizada (.srt) — o Instagram gera legendas automáticas, mas você pode usar este arquivo onde quiser.":"Legenda sincronizada — suba no YouTube Studio após enviar o vídeo."})]})]})]})})(),ye&&!O&&e.jsx("div",{className:"px-5 py-4 border-t border-white/[0.06]","data-testid":"section-publish",children:aa?e.jsx("div",{className:"space-y-3","data-testid":"status-scheduled",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("span",{className:"inline-flex items-center gap-2 text-sm font-medium text-cyan-300","data-testid":"badge-scheduled-time",children:[e.jsx(Ie,{className:"h-4 w-4"}),"Publicação agendada para ",En(aa.scheduledAt)]}),(()=>{const t=g.data?.find(s=>s.id===aa.channelId)||g.data?.find(s=>s.id===l?.channelId)||C[0];return t?.name?e.jsxs("p",{className:"inline-flex items-center gap-1.5 text-[11px] text-zinc-400 pl-6","data-testid":"text-scheduled-channel",children:[e.jsx(He,{className:"h-3 w-3 text-red-400 shrink-0"}),t.name]}):null})(),e.jsx("p",{className:"text-[11px] text-zinc-500 pl-6",children:"Na hora certa, o vídeo será enviado automaticamente com chapters, tags SEO, thumbnail e playlist."})]}),e.jsxs("button",{onClick:()=>ka.mutate(aa.id),disabled:ka.isPending,className:"inline-flex items-center gap-1.5 rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2 text-sm text-zinc-300 hover:bg-white/[0.06] hover:text-red-300 hover:border-red-500/30 disabled:opacity-50","data-testid":"button-cancel-schedule",children:[ka.isPending?e.jsx(f,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(jt,{className:"h-3.5 w-3.5"}),"Cancelar agendamento"]})]})}):Se?e.jsxs("div",{className:"space-y-2.5","data-testid":"status-published",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("span",{className:"inline-flex items-center gap-2 text-sm text-emerald-300",children:[e.jsx(ue,{className:"h-4 w-4"})," Publicado no YouTube"]}),Se.url&&e.jsxs("a",{href:Se.url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 text-sm font-medium text-cyan-300 hover:text-cyan-200","data-testid":"link-youtube",children:["Ver no YouTube ",e.jsx(la,{className:"h-3.5 w-3.5"})]})]}),Se.metadata?.chaptersCount>0&&e.jsxs("div",{className:"flex flex-wrap gap-1.5","data-testid":"publish-features",children:[Se.metadata?.chaptersCount>=3&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-full bg-emerald-500/10 text-emerald-300 border border-emerald-500/20","data-testid":"badge-chapter
31s",children:["✓ ",Se.metadata.chaptersCount," capítulos indexados"]}),Se.metadata?.tagsCount>0&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-full bg-cyan-500/10 text-cyan-300 border border-cyan-500/20","data-testid":"badge-tags",children:["✓ ",Se.metadata.tagsCount," tags SEO"]}),Se.metadata?.addedToPlaylist&&e.jsx("span",{className:"inline-flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-full bg-violet-500/10 text-violet-300 border border-violet-500/20","data-testid":"badge-playlist",children:"✓ Adicionado à playlist do canal"}),Se.metadata?.captionUploaded&&e.jsx("span",{className:"inline-flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-full bg-amber-500/10 text-amber-300 border border-amber-500/20","data-testid":"badge-caption",children:"✓ Legenda enviada"})]})]}):rt?e.jsxs("div",{className:"space-y-1","data-testid":"status-publishing",children:[e.jsxs("span",{className:"inline-flex items-center gap-2 text-sm text-zinc-300",children:[e.jsx(kt,{className:"h-4 w-4 animate-pulse text-rose-300"})," Enviando para o YouTube — aguarde, pode levar alguns minutos…"]}),e.jsx("p",{className:"text-[11px] text-zinc-500 pl-6",children:"Descrição com chapters, tags SEO e playlist serão configurados automaticamente."})]}):ws?e.jsxs("div",{className:"space-y-3","data-testid":"status-ready-publish",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("span",{className:"inline-flex items-center gap-2 text-sm text-zinc-400",children:vt?e.jsxs(e.Fragment,{children:[e.jsx(Ce,{className:"h-4 w-4 text-red-300"}),e.jsxs("span",{className:"text-red-300",children:["A última publicação falhou",vt.metadata?.error?` (${String(vt.metadata.error).slice(0,80)})`:"",". Você pode tentar de novo."]})]}):e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"h-4 w-4 text-rose-400"})," Pronto para publicar no seu canal do YouTube."]})}),C.length>1?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{htmlFor:"publish-channel",className:"text-xs text-zinc-500 shrink-0",children:"Publicar em"}),e.jsx("select",{id:"publish-channel",value:N,onChange:t=>j(t.target.value),className:"rounded-lg bg-[#0b1322] border border-white/10 text-sm text-zinc-200 px-3 py-1.5 focus:outline-none focus:border-cyan-400/40","data-testid":"select-publish-channel",children:C.map(t=>e.jsx("option",{value:t.id,children:t.name},t.id))})]}):e.jsxs("span",{className:"text-xs text-zinc-500","data-testid":"text-publish-target",children:["Publicando em ",e.jsx("span",{className:"text-zinc-300",children:C[0]?.name})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5","data-testid":"publish-preview-features",children:[e.jsx("span",{className:"inline-flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-full bg-white/[0.04] text-zinc-400 border border-white/[0.06]",children:"⚡ Chapters automáticos"}),e.jsx("span",{className:"inline-flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-full bg-white/[0.04] text-zinc-400 border border-white/[0.06]",children:"⚡ Tags SEO geradas por IA"}),e.jsx("span",{className:"inline-flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-full bg-white/[0.04] text-zinc-400 border border-white/[0.06]",children:"⚡ Categoria + idioma corretos"}),e.jsx("span",{className:"inline-flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-full bg-white/[0.04] text-zinc-400 border border-white/[0.06]",children:"⚡ Playlist do canal"}),$a&&e.jsx("span",{className:"inline-flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-full bg-cyan-500/10 text-cyan-300 border border-cyan-500/20",children:"⚡ Thumbnail personalizada"})]}),Zs?e.jsxs("div",{className:"rounded-2xl border border-cyan-500/25 bg-cyan-500/[0.04] p-4 space-y-3","data-testid":"panel-scheduler",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-sm font-medium text-cyan-200 flex items-center gap-2",children:[e.jsx(Ie,{className:"h-4 w-4"})," Agendar publicação"]}),e.jsx("button",{onClick:()=>ya(!1),className:"text-zinc-500 hover:text-zinc-300","data-testid":"button-close-scheduler",children:e.jsx(jt,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"text-[11px] text-zinc-500",children:"Escolha a data e o horário no seu fuso local. A Sábhia publicará automaticamente quando chegar a hora."}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("input",{type:"date",value:Mt,min:In,onChange:t=>nn(t.target.value),className:"rounded-xl border border-white/10 bg-[#0b1322] px-3 py-2 text-sm text-zinc-200 focus:outline-none focus:border-cyan-400/40","data-testid":"input-sched-date"}
31),e.jsx("input",{type:"time",value:$t,onChange:t=>rn(t.target.value),className:"rounded-xl border border-white/10 bg-[#0b1322] px-3 py-2 text-sm text-zinc-200 focus:outline-none focus:border-cyan-400/40","data-testid":"input-sched-time"}),e.jsxs("button",{onClick:()=>Et.mutate(),disabled:Et.isPending||!Mt||!$t,className:"inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-cyan-600 to-blue-600 px-4 py-2 text-sm font-semibold text-white hover:opacity-95 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"button-confirm-schedule",children:[Et.isPending?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(Ie,{className:"h-4 w-4"}),Et.isPending?"Agendando…":"Confirmar agendamento"]})]})]}):e.jsxs("div",{className:"flex flex-wrap gap-2 pt-0.5","data-testid":"publish-actions",children:[e.jsxs("button",{onClick:()=>Bt(!0),disabled:rt,className:"inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-rose-600 to-red-500 px-4 py-2.5 text-sm font-semibold text-white shadow-lg shadow-red-900/40 hover:opacity-95 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"button-publish-now",children:[rt?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(He,{className:"h-4 w-4"}),rt?"Publicando…":vt?"Tentar de novo agora":"Publicar agora"]}),!vt&&e.jsxs("button",{onClick:()=>ya(!0),className:"inline-flex items-center gap-2 rounded-xl border border-cyan-500/30 bg-cyan-500/[0.06] px-4 py-2.5 text-sm font-medium text-cyan-300 hover:bg-cyan-500/[0.12] hover:border-cyan-400/50","data-testid":"button-open-scheduler",children:[e.jsx(Ie,{className:"h-4 w-4"})," Agendar para…"]})]})]}):g.isLoading?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-zinc-500","data-testid":"status-channels-loading",children:[e.jsx(f,{className:"h-4 w-4 animate-spin shrink-0"})," Verificando conexões YouTube…"]}):(g.data||[]).filter(t=>!t.isStudio).length>0?e.jsxs("div",{className:"space-y-2.5","data-testid":"status-not-connected",children:[e.jsxs("span",{className:"inline-flex items-center gap-2 text-sm text-zinc-400",children:[e.jsx(He,{className:"h-4 w-4 text-zinc-500"}),"Conecte um canal ao YouTube para publicar com 1 clique."]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:(g.data||[]).filter(t=>!t.isStudio).map(t=>e.jsxs("a",{href:`/api/videos/channels/${t.id}/youtube/connect?returnTo=/videos/projetos/${u}`,className:"inline-flex items-center gap-1.5 rounded-xl border border-red-500/30 bg-red-500/[0.06] px-3 py-2 text-sm text-red-300 hover:bg-red-500/[0.12] hover:text-red-200 transition-colors","data-testid":`button-connect-yt-${t.id}`,children:[e.jsx(He,{className:"h-3.5 w-3.5"}),t.name]},t.id))})]}):e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3","data-testid":"status-no-channels",children:[e.jsxs("span",{className:"inline-flex items-center gap-2 text-sm text-zinc-400",children:[e.jsx(He,{className:"h-4 w-4 text-zinc-500"})," Crie um canal para publicar no YouTube com 1 clique."]}),e.jsx(Ss,{href:"/videos/canais/novo",children:e.jsx("button",{className:"inline-flex items-center gap-1.5 rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2 text-sm text-zinc-200 hover:bg-white/[0.06]","data-testid":"button-create-channel",children:"Criar canal"})})]})})]}),ye&&l&&e.jsx("section",{className:"rounded-3xl border border-white/[0.07] bg-gradient-to-br from-[#0f1f3d]/40 via-[#0a0f1e] to-[#0a1c38]/20 mb-8 overflow-hidden","data-testid":"section-translation-wrapper",children:e.jsx(Mi,{projectId:u,hasVideo:ye,videoTitle:l.title||"Seu vídeo"})}),e.jsxs("section",{className:"rounded-3xl border border-white/[0.07] bg-gradient-to-br from-[#0f1f3d]/40 via-[#0a0f1e] to-[#0a1c38]/20 p-5 md:p-6 mb-8","data-testid":"section-finish",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 mb-4",children:[e.jsxs("h2",{className:"text-lg font-semibold tracking-tight flex items-center gap-2",children:[e.jsx(ce,{className:"h-4 w-4 text-cyan-400"})," Acabamento premium"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[Ue.resolutionLabel&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[11px] px-2.5 py-1 rounded-full border bg-cyan-500/15 text-cyan-200 border-cyan-500/25","data-testid":"badge-finish-resolution",title:"Resolução final do MP4 renderizado.",children:[e.jsx(ce,{className:"h-3 w-3"}),Ue.resolutionLabel]}),e.jsx("span",{className:`text-[11px] px-2.5 py-1 rounded-full border ${Ue.applied?"bg-emerald-500/15 text-emerald-300 border-emerald-500/25":"bg-cyan-500/15 text-cyan-300 border-cyan-500/25"}`,"data-testid":"badge-finish-state",children:Ue.applied?"Aplicado neste vídeo":"Aplicado ao renderizar"})]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"rounded-2xl border border-white/[0.06] bg-white/[0.02] p-4","data-testid":"card-finish-music",children:[e.jsxs("div",{className:"flex items-center gap-2 text-zinc-300",children:[e.jsx("span",{className:"h-8 w-8 rounded-xl bg-blue-500/15 text-blue-300 flex items-center justify-center shrink-0",children:e.jsx(As,{className:"h-4 w-4"})}),e.jsx("span",{className:"text-sm font-medium",children:"Trilha sonora"})]}),e.jsx("p",{className:"mt-2 text-sm text-zinc-400","data-testid":"text-finish-music",children:Ue.musicOn&&Ue.moodLabel?e.jsxs(e.Fragment,{children:["Bed instrumental ",e.jsx("span",{className:"text-cyan-300",children:Ue.moodLabel}),", com ducking sob a narração."]}):"Sem trilha neste vídeo."})]}),e.jsxs("div",{className:"rounded-2xl border border-white/[0.06] bg-white/[0.02] p-4","data-testid":"card-finish-transitions",children:[e.jsxs("div",{className:"flex items-center gap-2 text-zinc-300",children:[e.jsx("span",{className:"h-8 w-8 rounded-xl bg-blue-500/15 text-blue-300 flex items-center justify-center shrink-0",children:e.jsx(zi,{className:"h-4 w-4"})}),e.jsx("span",{className:"text-sm font-medium",children:"Transições"})]}),e.jsx("p",{className:"mt-2 text-sm text-zinc-400","data-testid":"text-finish-transitions",children:Ue.transitions?"Fusões suaves (crossfade) entre as cenas, no vídeo e no áudio.":"Cortes secos entre as cenas."})]}),e.jsxs("div",{className:"rounded-2xl border border-white/[0.06] bg-white/[0.02] p-4","data-testid":"card-finish-captions",children:[e.jsxs("div",{className:"flex items-center gap-2 text-zinc-300",children:[e.jsx("span",{className:"h-8 w-8 rounded-xl bg-blue-500/15 text-blue-300 flex items-center justify-center shrink-0",children:e.jsx(Ts,{className:"h-4 w-4"})}),e.jsx("span",{className:"text-sm font-medium",children:"Legendas"})]}),e.jsxs("p",{className:"mt-2 text-sm text-zinc-400","data-testid":"text-finish-captions",children:[e.jsx("span",{className:"text-cyan-300",children:Ue.captionsLabel}),", gravadas no vídeo no estilo do canal."]})]})]}),!p?.asmrMode&&!l?.metadata?.cloneFullNarration&&x.length>0&&e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4 roun
31ded-2xl border border-cyan-500/15 bg-cyan-500/[0.04] px-4 py-3","data-testid":"section-voice-swap",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("span",{className:"h-8 w-8 shrink-0 rounded-xl bg-cyan-500/15 text-cyan-300 flex items-center justify-center",children:e.jsx(Ps,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-zinc-300",children:"Voz da narração"}),e.jsx("p",{className:"text-xs text-zinc-500 truncate","data-testid":"text-current-voice",children:Jt?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-cyan-300",children:Jt.label}),Jt.desc?` · ${Jt.desc}`:""]}):e.jsx("span",{className:"text-zinc-500",children:"Voz padrão"})})]})]}),e.jsxs("button",{onClick:()=>{pt(ft),Pt(ft?Vt:Wt),os("all"),At(!0)},disabled:!pn,className:"shrink-0 flex items-center gap-1.5 rounded-xl border border-cyan-500/30 bg-cyan-500/10 px-4 py-2 text-sm font-medium text-cyan-300 hover:border-cyan-400/50 hover:bg-cyan-500/20 transition-all disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"button-change-voice-open",title:gs?"Aguarde o processamento atual terminar":"Trocar a voz da narração e regenerar o vídeo",children:[xt.isPending?e.jsx(f,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(da,{className:"h-3.5 w-3.5"}),"Trocar voz"]})]}),e.jsx("p",{className:"mt-4 text-xs text-zinc-500","data-testid":"text-finish-note",children:Ue.applied?"Estes recursos já fazem parte do MP4 acima. Renderize de novo para aplicar mudanças nas cenas.":"Aplicamos tudo isso automaticamente quando você clica em Renderizar — sem trabalho extra."})]}),be&&e.jsxs("section",{className:"mb-6 rounded-2xl border border-cyan-500/20 bg-gradient-to-br from-cyan-500/[0.05] via-white/[0.02] to-blue-500/[0.05] p-5","data-testid":"panel-script-quality",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("h3",{className:"text-base font-semibold tracking-tight flex items-center gap-2",children:[e.jsx(ce,{className:"h-4 w-4 text-cyan-400"})," Qualidade do roteiro"]}),O?e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-sky-500/30 bg-sky-500/15 px-3 py-1 text-xs font-semibold text-sky-300","data-testid":"badge-script-reels",children:[e.jsx(ce,{className:"h-3.5 w-3.5"}),"Formato Reels"]}):r?.monetizable?e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-emerald-500/30 bg-emerald-500/15 px-3 py-1 text-xs font-semibold text-emerald-300","data-testid":"badge-script-monetizable",children:[e.jsx(ue,{className:"h-3.5 w-3.5"}),r.estimatedMinutes," min · Monetizável"]}):e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-amber-500/30 bg-amber-500/15 px-3 py-1 text-xs font-semibold text-amber-300","data-testid":"badge-script-short",children:[e.jsx(Ie,{className:"h-3.5 w-3.5"}),r?.estimatedMinutes," min · abaixo de ",r?.minMinutes??8," min"]}),typeof r?.wordCount=="number"&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-white/10 bg-white/[0.03] px-3 py-1 text-xs font-medium text-zinc-300","data-testid":"text-script-wordcount",children:[r.wordCount.toLocaleString("pt-BR")," palavras"]}),!!l?.metadata?.language&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-cyan-500/25 bg-cyan-500/10 px-3 py-1 text-xs font-medium text-cyan-200","data-testid":"badge-script-language",children:[e.jsx(Nt,{className:"h-3.5 w-3.5"}),dr(l.metadata.language)]}),typeof r?.targetMinutes=="number"&&r.targetMinutes>0&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-white/10 bg-white/[0.03] px-3 py-1 text-xs font-medium text-zinc-300","data-testid":"badge-script-target",children:[e.jsx(Ie,{className:"h-3.5 w-3.5"}),"Meta ~",r.targetMinutes," min"]}),typeof r?.sceneCount=="number"&&r.sceneCount>0&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-cyan-500/25 bg-cyan-500/10 px-3 py-1 text-xs font-medium text-cyan-200","data-testid":"badge-script-density",children:[e.jsx(Ni,{className:"h-3.5 w-3.5"}),r.sceneCount," cenas",r.secondsPerScene?` · ~1 img/${r.secondsPerScene}s`:""]}),r?.engagement&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-cyan-500/25 bg-cyan-500/10 px-3 py-1 text-xs font-medium text-cyan-200","data-testid":"badge-script-engagement",children:[e.jsx(wi,{className:"h-3.5 w-3.5"}),"Aviso de IA + CTA incluídos",r.channelNamed?" · canal citado":""]}),r?.research?.used&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-blue-500/25 bg-blue-500/10 px-3 py-1 text-xs font-medium text-blue-300","data-testid":"badge-script-researched",children:[e.jsx(Nt,{className:"h-3.5 w-3.5"})," Pesquisado na internet"]}),r?.editorial?.engine==="v3"&&typeof r.editorial.score=="number"&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-emerald-500/30 bg-emerald-500/10 px-3 py-1 text-xs font-semibold text-emerald-300","data-testid":"badge-script-editorial-score",title:`Conselho editorial: o roteiro foi julgado por um crítico de IA (hook, progresso, especificidade, emoção, clareza) e ${(r.editorial.rewrites||0)>0?`reescrito ${r.editorial.rewrites}× até melhorar`:"aprovado sem reescrita"}.${r.editorial.vetoes?.length?` Vetos tratados: ${r.editorial.vetoes.join(" · ")}`:""}`,children:[e.jsx(ue,{className:"h-3.5 w-3.5"}),"Nota editorial ",r.editorial.score,"/100",(r.editorial.rewrites||0)>0?` · ${r.editorial.rewrites} reescrita(s)`:""]}),r?.editorial?.engine==="v3"&&(r.editorial.hookWinner||"").trim()&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-amber-500/30 bg-amber-500/10 px-3 py-1 text-xs font-medium text-amber-300","data-testid":"badge-script-editorial-hook",title:`Torneio de hooks: 5 candidatos disputaram a primeira frase; este venceu.${r.editorial.hookFinalists?.length?` Finalistas: ${r.editorial.hookFinalists.join(" · ")}`:""}${r.editorial.angle?` Ângulo: ${r.editorial.angle}`:""}`,children:[e.jsx(ce,{className:"h-3.5 w-3.5"}),"Hook campeão: “",String(r.editorial.hookWinner).slice(0,60),"”"]}
31),r?.editorial?.engine==="v4"&&typeof r.editorial.score=="number"&&e.jsxs("span",{className:`inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-semibold ${r.editorial.approved?"border-emerald-500/30 bg-emerald-500/15 text-emerald-300":"border-amber-500/30 bg-amber-500/15 text-amber-300"}`,"data-testid":"badge-script-editorial-v4-score",title:`Editorial V4: estratégia (ângulo/gancho/beats) montada ANTES do roteiro e julgada por um crítico de IA + bateria de testes determinísticos no código.${(r.editorial.rewrites||0)>0?` Reescrito ${r.editorial.rewrites}× até melhorar.`:" Aprovado sem reescrita."}${r.editorial.failedTests?.length?` Testes reprovados: ${r.editorial.failedTests.slice(0,4).join(" · ")}`:""}${r.editorial.needsHumanReview?" Recomenda revisão humana antes de publicar.":""}`,children:[r.editorial.approved?e.jsx(ue,{className:"h-3.5 w-3.5"}):e.jsx(Ie,{className:"h-3.5 w-3.5"}),"Editorial V4 · ",r.editorial.score,"/100",(r.editorial.rewrites||0)>0?` · ${r.editorial.rewrites} reescrita(s)`:"",!r.editorial.approved&&" · revisar"]}),r?.editorial?.engine==="v4"&&(r.editorial.hookWinner||"").trim()&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-amber-500/30 bg-amber-500/10 px-3 py-1 text-xs font-medium text-amber-300","data-testid":"badge-script-editorial-v4-hook",title:`Estratégia V4: gancho vencedor escolhido na fase de estratégia.${r.editorial.hookFinalists?.length?` Finalistas: ${r.editorial.hookFinalists.slice(0,4).join(" · ")}`:""}${r.editorial.angle?` Ângulo: ${r.editorial.angle}`:""}`,children:[e.jsx(ce,{className:"h-3.5 w-3.5"}),"Hook campeão: “",String(r.editorial.hookWinner).slice(0,60),"”"]}),r?.reelsDoc&&typeof r.docTargetMinutes=="number"&&r.docTargetMinutes>0&&typeof r.estimatedMinutes=="number"&&(()=>{const t=r.estimatedMinutes,s=r.docTargetMinutes,c=typeof r.docFloorWords=="number"&&typeof r.wordCount=="number"?r.wordCount>=r.docFloorWords:t>=s*.8,d=Math.floor(t),m=String(Math.round((t-d)*60)).padStart(2,"0");return e.jsxs("span",{className:`inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-semibold ${c?"border-emerald-500/30 bg-emerald-500/15 text-emerald-300":"border-amber-500/30 bg-amber-500/15 text-amber-300"}`,"data-testid":"badge-script-doc-duration",title:`Duração estimada da narração vs a pedida na criação (${s} min).${r.docPostExpanded?" O roteiro ficou curto após a revisão editorial e foi RE-EXPANDIDO automaticamente pela guarda de duração.":""}${c?"":" Ficou abaixo do piso — vale regenerar o roteiro."}`,children:[e.jsx(Ie,{className:"h-3.5 w-3.5"}),"~",d,":",m," de ",s," min pedidos",r.docPostExpanded?" · re-expandido":""]})})(),typeof r?.storyboard?.enriched=="number"&&r.storyboard.enriched>0&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-cyan-500/25 bg-cyan-500/10 px-3 py-1 text-xs font-medium text-cyan-200","data-testid":"badge-script-storyboard",title:"Cada cena recebeu um plano visual cinematográfico ancorado na narração, com personagens e cenários consistentes — para imagens que combinam com o que está sendo dito e sem repetições.",children:[e.jsx(Da,{className:"h-3.5 w-3.5"}),"Storyboard cinematográfico (",r.storyboard.enriched," cenas)"]}),le.length>0&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-sky-500/25 bg-sky-500/10 px-3 py-1 text-xs font-medium text-sky-200","data-testid":"badge-script-director",title:"Um cineasta dividiu o vídeo em atos com cenários, épocas e paletas DISTINTOS (início, meio e fim) — para o filme mudar de visual ao longo do tempo, em vez de parecer sempre a mesma coisa.",children:[e.jsx(fe,{className:"h-3.5 w-3.5"}),"Direção de cinema (",le.length," atos)"]}),r?.cinematicBeats&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-cyan-400/35 bg-gradient-to-r from-cyan-500/20 to-sky-500/15 px-3 py-1 text-xs font-semibold text-cyan-200","data-testid":"badge-script-cinematic-beats",title:"Cinema por Cenas: o roteiro é fatiado em planos de ≤8s e CADA plano vira um clipe de vídeo ÚNICO gerado diretamente do texto (Veo 3.1). Acabou a repetição de 'mesma cena, novo ângulo' — cada momento do vídeo é uma imagem em movimento diferente, com bíblia visual consistente entre as cenas.",children:[e.jsx(fe,{className:"h-3.5 w-3.5"}),"Cinema por Cenas"]}),r?.storyMode&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-rose-500/30 bg-rose-500/15 px-3 py-1 text-xs font-semibold text-rose-300","data-testid":"badge-script-story-mode",title:"Modo Histórias Emocionais: personagens inventados livremente, arco dramático Hook→Injustiça→Resolução. Sem disclaimer de IA na narração — como uma novela de TV.",children:[e.jsx(zs,{className:"h-3.5 w-3.5"}),"História Emocional"]}),r?.titleScore?.scoringApplied&&r.titleScore.winner&&e.jsxs("span",{className:`inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-semibold ${r.titleScore.belowMinimum?"border-amber-500/30 bg-amber-500/15 text-amber-300":r.titleScore.winner.score!=null&&r.titleScore.winner.score>=92?"border-yellow-400/40 bg-yellow-400/15 text-yellow-200":"border-emerald-500/30 bg-emerald-500/15 text-emerald-300"}`,"data-testid":"badge-script-title-score",title:`Título vencedor gerado por scoring 0–100 (${r.titleScore.all?.length??5}
31 candidatos avaliados). Score: ${r.titleScore.winner.score??"–"}/100${r.titleScore.winner.formula?` · ${r.titleScore.winner.formula}`:""}${r.titleScore.winner.why?`
32${r.titleScore.winner.why}`:""}`,children:[e.jsx(Oa,{className:"h-3.5 w-3.5"}),"Título ",r.titleScore.winner.score??"–","/100",r.titleScore.belowMinimum&&" · abaixo do ideal"]})]}),te.length>0&&e.jsxs("div",{className:"mt-4",children:[e.jsxs("p",{className:"text-xs font-medium uppercase tracking-wide text-zinc-500 mb-2",children:["Fontes investigadas (",te.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:te.slice(0,12).map((t,s)=>e.jsxs("a",{href:t.uri,target:"_blank",rel:"noopener noreferrer",className:"inline-flex max-w-[260px] items-center gap-1.5 rounded-lg border border-white/10 bg-white/[0.02] px-2.5 py-1.5 text-xs text-zinc-300 hover:border-cyan-500/40 hover:bg-cyan-500/[0.06] hover:text-cyan-200 transition-colors","data-testid":`link-script-source-${s}`,title:t.title||t.uri,children:[e.jsx(la,{className:"h-3 w-3 shrink-0 text-cyan-400"}),e.jsx("span",{className:"truncate",children:t.title||t.uri})]},s))})]}),e.jsx("p",{className:"mt-4 text-xs text-zinc-600 leading-relaxed",children:O?"Roteiro enxuto no formato Reels: gancho nos primeiros segundos, valor direto e chamada para a DM — feito para prender até o fim.":"Roteiros com 8+ minutos de narração liberam anúncios mid-roll no YouTube. O roteirista pesquisa o tema e estrutura a narrativa para máxima retenção automaticamente."})]}),l?.metadata?.ttsPhonetic===!0&&(()=>{const t=(l?.metadata?.ttsGlossary||[]).filter(c=>c&&c.de&&c.para),s=x.map((c,d)=>({idx:d,text:(c.text||"").trim(),tts:(c.metadata?.ttsText||"").trim()})).filter(c=>c.tts);return!t.length&&!s.length?null:e.jsxs("section",{className:"mb-6 rounded-2xl border border-cyan-500/20 bg-gradient-to-br from-cyan-500/[0.05] via-white/[0.02] to-blue-500/[0.05] p-5","data-testid":"panel-tts-phonetic",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("h3",{className:"text-base font-semibold tracking-tight flex items-center gap-2",children:[e.jsx(Ba,{className:"h-4 w-4 text-cyan-400"})," Como a Sábhia vai falar"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-emerald-500/30 bg-emerald-500/15 px-3 py-1 text-xs font-semibold text-emerald-300","data-testid":"badge-tts-phonetic",title:"A narração passa por um preparo fonético: nomes estrangeiros, siglas e números são reescritos do jeito que devem SOAR em português — só para a voz; as legendas e o texto das cenas continuam com a grafia original.",children:[e.jsx(ue,{className:"h-3.5 w-3.5"}),"Pronúncia preparada"]}),s.length>0&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-white/10 bg-white/[0.03] px-3 py-1 text-xs font-medium text-zinc-300","data-testid":"text-tts-phonetic-scenes",children:[s.length," de ",x.length," cenas preparadas"]})]}),t.length>0&&e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"text-xs font-medium text-zinc-400 mb-2",children:"Pronúncias combinadas (iguais no vídeo inteiro)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:t.slice(0,24).map((c,d)=>e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-lg border border-cyan-500/25 bg-cyan-500/[0.07] px-2.5 py-1.5 text-xs text-zinc-200","data-testid":`chip-tts-glossary-${d}`,title:`"${c.de}" será falado como "${c.para}" em todas as cenas`,children:[e.jsx("span",{className:"text-zinc-400",children:c.de}),e.jsx("span",{className:"text-cyan-400",children:"→"}),e.jsx("span",{className:"font-semibold text-cyan-200",children:c.para})]},d))})]}),s.length>0&&e.jsx("div",{className:"mt-4 space-y-1.5 max-h-64 overflow-y-auto pr-1",children:s.map(c=>e.jsxs("div",{className:"rounded-lg border border-white/5 bg-black/20 px-3 py-2","data-testid":`row-tts-phonetic-${c.idx}`,children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wide text-zinc-500 mb-0.5",children:["Cena ",c.idx+1]}),e.jsx("p",{className:"text-xs text-cyan-100/90 leading-relaxed",children:c.tts}),c.text&&c.text!==c.tts&&e.jsx("p",{className:"mt-1 text-[11px] text-zinc-500 leading-relaxed",title:"Texto original (o que aparece na legenda)",children:c.text})]},c.idx))}),e.jsx("p",{className:"mt-3 text-[11px] text-zinc-600",children:"Somente leitura: é assim que a voz vai pronunciar cada fala. As legendas e o texto das cenas continuam com a escrita original."})]})})(),!!p?.usage&&p.usage.byKind.length>0&&e.jsxs("section",{className:"mb-6 rounded-2xl border border-cyan-500/20 bg-gradient-to-br from-cyan-500/[0.05] via-white/[0.02] to-blue-500/[0.05] p-5","data-testid":"panel-project-cost",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("h3",{className:"text-base font-semibold tracking-tight flex items-center gap-2",children:[e.jsx(Oa,{className:"h-4 w-4 text-cyan-400"})," Custo real de produção"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-cyan-500/30 bg-cyan-500/15 px-3 py-1 text-xs font-semibold text-cyan-200","data-testid":"text-project-cost-total",title:"Somatório do custo REAL das chamadas de API deste projeto (imagens, narração, clipes de vídeo, pesquisa etc.), convertido pela taxa USD→BRL do dia.",children:["US$ ",(p.usage.totalCents/100).toFixed(2),e.jsx("span",{className:"text-cyan-400/80",children:"·"}),"R$ ",(p.usage.totalCents/100*p.usage.usdBrlRate).toFixed(2)]})]}),e.jsx("div",{className:"mt-3 grid grid-cols-1 gap-1.5 sm:grid-cols-2",children:p.usage.byKind.map(t=>{const s={image:"Imagens (cenas)",tts:"Narração (voz)",narration:"Narração (voz)",i2v:"Animação das cenas",t2v:"Clipes de vídeo (IA)",video:"Clipes de vídeo (IA)",avatar:"Clone (apresentador)",research:"Pesquisa na internet",script:"Roteiro",music:"Trilha sonora",thumbnail:"Miniatura",translation:"Tradução"};return e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-white/5 bg-black/20 px-3 py-2","data-testid":`row-project-cost-${t.kind}`,children:[e.jsxs("span",{className:"text-xs text-zinc-300",children:[s[t.kind]||t.kind,e.jsxs("span",{className:"ml-1.5 text-[10px] text-zinc-500",children:["×",t.calls]})]}),e.jsxs("span",{className:"text-xs font-semibold text-cyan-200",children:["US$ ",(t.costCents/100).toFixed(2)]})]},t.kind)})}),e.jsxs("p",{className:"mt-3 text-[11px] text-zinc-600",children:["Valores reais cobrados pelos provedores de IA neste projeto. Conversão: US$ 1 ≈ R$ ",p.usage.usdBrlRate.toFixed(2),"."]})]}),(A||de)&&e.jsxs("section",{className:"mb-8 rounded-2xl border border-cyan-500/20 bg-gradient-to-br from-cyan-500/[0.06] via-[#070d1a] to-[#060a14] p-5 md:p-6","data-testid":"panel-music-emotional",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-1",children:[e.jsx(As,{className:"h-4 w-4 text-cyan-400"}),e.jsx("h3",{className:"text-sm font-semibold tracking-tight text-cyan-100",children:"Trilha sonora emocional"}),A?e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-cyan-500/30 bg-cyan-500/15 px-3 py-1 text-xs font-semibold text-cyan-200","data-testid":"badge-music-culture",title:"A trilha instrumental (sem vocais) é escolhida para combinar com o idioma e a cultura do vídeo — instrumentos e escalas regionais.",children:[e.jsx(Nt,{className:"h-3.5 w-3.5"}),mr[A]||A]}):e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-white/10 bg-white/[0.03] px-3 py-1 text-xs font-medium text-zinc-400","data-testid":"badge-music-culture-default",title:"Idioma sem pack cultural dedicado — usa a trilha instrumental ocidental padrão.",children:[e.jsx(Nt,{className:"h-3.5 w-3.5"}),"Trilha ocidental padrão"]}),de&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-cyan-500/25 bg-cyan-500/10 px-3 py-1 text-xs font-medium text-cyan-200","data-testid":"badge-music-dynamic",title:"O volume da trilha SOBE nas cenas de tensão e DESCE nas cenas calmas, seguindo o arco emocional abaixo — automático, sem vocais.",children:[e.jsx(Oa,{className:"h-3.5 w-3.5"}),"Volume dinâmico"]})]}),e.jsx("p",{className:"text-xs text-zinc-500 leading-relaxed mt-1",children:"Música instrumental sem vocais, escolhida pela cultura do idioma e com o volume oscilando conforme a emoção de cada cena."}),de&&e.jsxs("div",{className:"mt-4","data-testid":"chart-music-arc",children:[e.jsxs("p",{className:"text-[11px] font-medium uppercase tracking-wide text-zinc-500 mb-2",children:["Arco emocional (",de.length," cenas)"]}),e.jsx("div",{className:"flex items-end gap-[3px] h-20 w-full overflow-x-auto pb-1",children:de.map((t,s)=>{const c=Math.round(Math.min(1,Math.max(.08,t.intensity))*100),d=t.intensity>=.66,m=t.intensity>=.46&&t.intensity<.66;return e.jsx("div",{className:"group relative flex-1 min-w-[4px] flex items-end",style:{height:"100%"},"data-testid":`bar-music-arc-${s}`,title:`Cena ${s+1}: ${pr(t.nf)} · intensidade ${Math.round(t.intensity*100)}%`,children:e.jsx("div",{className:`w-full rounded-t-sm transition-all ${d?"bg-gradient-to-t from-cyan-500/40 to-cyan-300":m?"bg-gradient-to-t from-cyan-600/30 to-cyan-400/80":"bg-gradient-to-t from-blue-700/30 to-blue-500/60"}`,style:{height:`${c}%`}})},s)})}),e.jsxs("div",{className:"flex items-center justify-between mt-2 text-[11px] text-zinc-600",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2 w-2 rounded-sm bg-blue-500/60"})," Calmaria (trilha desce)"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:["Tensão (trilha sobe) ",e.jsx("span",{className:"inline-block h-2 w-2 rounded-sm bg-cyan-300"})]})]})]})]}),le.length>0&&e.jsxs("section",{className:"mb-8 rounded-2xl border border-sky-500/15 bg-gradient-to-br from-sky-500/[0.06] via-[#070d1a] to-[#060a14] p-5 md:p-6","data-testid":"panel-director-plan",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(fe,{className:"h-4 w-4 text-sky-400"}),e.jsx("h3",{className:"text-sm font-semibold tracking-tight text-sky-100",children:"Plano de cinema"}),e.jsxs("span",{className:"text-xs text-zinc-500",children:["— ",le.length," atos (início, meio e fim)"]})]}),ge?.logline&&e.jsx("p",{className:"text-sm text-zinc-300 leading-relaxed mt-2","data-testid":"text-director-logline",children:ge.logline}),ge?.visualArc&&e.jsxs("p",{className:"text-xs text-zinc-500 leading-relaxed mt-2 flex items-start gap-1.5","data-testid":"text-director-visualarc",children:[e.jsx(ce,{className:"h-3.5 w-3.5 shrink-0 text-sky-400/80 mt-0.5"}),e.jsx("span",{children:ge.visualArc})]}),e.jsx("div",{className:"mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:le.map((t,s)=>e.jsxs("div",{className:"relative rounded-xl border border-white/10 bg-white/[0.02] p-4 hover:border-sky-500/30 transition-colors","data-testid":`card-director-act-${s}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-2",children:[e.jsx("span",{className:"inline-flex items-center rounded-full border border-sky-500/30 bg-sky-500/10 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-sky-200",children:je(t.narrativeRole??t.role,s,le.length)}),t.era&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-zinc-500",children:[e.jsx(Ie,{className:"h-3 w-3"})," ",t.era]})]}),t.title&&e.jsx("p",{className:"text-sm font-semibold text-zinc-100 leading-snug mb-2","data-testid":`text-director-act-title-${s}`,children:t.title}),e.jsxs("div",{className:"space-y-1.5",children:[t.setting&&e.jsxs("p",{className:"text-xs text-zinc-400 flex items-start gap-1.5",children:[e.jsx(ei,{className:"h-3 w-3 shrink-0 text-sky-400/80 mt-0.5"}),e.jsx("span",{children:t.setting})]}),t.palette&&e.jsxs("p",{className:"text-xs text-zinc-400 flex items-start gap-1.5",children:[e.jsx(ti,{className:"h-3 w-3 shrink-0 text-sky-400/80 mt-0.5"}),e.jsx("span",{children:t.palette})]}),t.mood&&e.jsxs("p",{className:"text-xs text-zinc-500 italic flex items-start gap-1.5",children:[e.jsx(ce,{className:"h-3 w-3 shrink-0 text-sky-400/60 mt-0.5"}),e.jsx("span",{children:t.mood})]})]}),t.keyImagery&&t.keyImagery.length>0&&e.jsx("div",{className:"mt-3 flex flex-wrap gap-1.5",children:t.keyImagery.slice(0,4).map((c,d)=>e.jsx("span",{className:"inline-flex rounded-md border border-white/10 bg-white/[0.03] px-2 py-0.5 text-[10px] text-zinc-400",children:c},d))})]},s))}),e.jsx("p",{className:"mt-4 text-xs text-zinc-600 leading-relaxed",children:"Um cineasta leu o roteiro inteiro e dividiu o filme em atos com cenários, épocas e paletas DISTINTOS — para o vídeo evoluir visualmente do início ao fim, em vez de parecer sempre a mesma coisa em movimento."})]}),l?.metadata?.videoPipelineMode==="narrasync"&&(()=>{const t=l?.metadata?.narrasyncCharacterRefUrl||null,s=String(l?.metadata?.narrasyncCharacterBible||"").trim()||null,c=Y||Re.isPending;return e.jsx("section",{className:"mb-6 rounded-2xl border border-cyan-500/15 bg-cyan-500/[0.04] p-4","data-testid":"section-narrasync-character",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start",children:[e.jsx("div",{className:"shrink-0",children:t?e.jsx("img",{src:t,alt:"Personagem NarraSync",className:"h-20 w-20 rounded-xl border border-cyan-500/30 bg-zinc-900 object-cover","data-testid":"img-narrasync-ref"}):e.jsx("div",{className:"flex h-20 w-20 items-center justify-center rounded-xl border border-dashed border-cyan-500/30 bg-zinc-900/60 text-3xl","aria-hidden":!0,
32children:"🧍"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("h2",{className:"flex flex-wrap items-center gap-2 text-base font-semibold tracking-tight",children:[e.jsx(ce,{className:"h-4 w-4 text-cyan-400"})," Personagem do vídeo",t?e.jsx("span",{className:"rounded-full border border-emerald-500/30 bg-emerald-500/15 px-2 py-0.5 text-[10px] font-semibold text-emerald-300","data-testid":"badge-narrasync-ref",children:"Personalizado ✓"}):e.jsx("span",{className:"rounded-full border border-zinc-600/40 bg-zinc-700/40 px-2 py-0.5 text-[10px] font-semibold text-zinc-400","data-testid":"badge-narrasync-ref",children:"Padrão"})]}),e.jsxs("p",{className:"mt-1 text-xs leading-relaxed text-zinc-400",children:["Envie a ",e.jsx("strong",{className:"text-zinc-200",children:"folha de personagem"})," (seu design, desenho ou character sheet) pra manter o mesmo personagem em ",e.jsx("strong",{className:"text-zinc-200",children:"todas as cenas"}),". O sistema extrai automaticamente uma descrição visual para consistência máxima. Se já gerou cenas antes do upload, use ",e.jsx("strong",{className:"text-zinc-200",children:"Regenerar todas"}),"."]}),s&&e.jsxs("div",{className:"mt-2.5 rounded-xl border border-cyan-500/15 bg-zinc-900/50 p-2.5","data-testid":"section-narrasync-bible",children:[e.jsx("p",{className:"mb-1 text-[10px] font-bold uppercase tracking-wider text-cyan-400/70",children:"Personagem identificado ✓"}),e.jsx("p",{className:"line-clamp-3 text-[11px] leading-relaxed text-zinc-400",children:s})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[e.jsx("button",{type:"button","data-testid":"button-narrasync-ref-upload",disabled:c,onClick:()=>_.current?.click(),className:"inline-flex items-center gap-2 rounded-lg border border-cyan-500/30 bg-cyan-500/10 px-3 py-2 text-xs font-semibold text-cyan-200 transition-colors hover:bg-cyan-500/20 disabled:opacity-50",children:c?e.jsxs(e.Fragment,{children:[e.jsx(f,{className:"h-3.5 w-3.5 animate-spin"})," Enviando…"]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"📁"})," ",t?"Trocar personagem":"Enviar personagem"]})}),t&&e.jsx("button",{type:"button","data-testid":"button-narrasync-force-regen",disabled:ve.isPending,onClick:()=>ve.mutate(),className:"inline-flex items-center gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs font-semibold text-amber-200 transition-colors hover:bg-amber-500/20 disabled:opacity-50",title:"Regenera TODAS as cenas usando o personagem enviado — mesmo as já geradas anteriormente",children:ve.isPending?e.jsxs(e.Fragment,{children:[e.jsx(f,{className:"h-3.5 w-3.5 animate-spin"})," Enfileirando…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Te,{className:"h-3.5 w-3.5"})," Regenerar todas as cenas"]})}),e.jsx("span",{className:"text-[11px] text-zinc-500",children:"PNG, JPG ou WEBP"})]}),e.jsx("input",{ref:_,type:"file",accept:"image/png,image/jpeg,image/webp",className:"hidden","data-testid":"input-narrasync-ref-file",onChange:d=>{Js(d.target.files?.[0]),d.target.value=""}})]})]})})})(),l?.metadata?.videoPipelineMode==="narrasync"&&x.length>0&&Ke.total>0&&(()=>{const t=Ke.minD,s=Ke.maxD,c=Ke.avgD,d=Ke.cuts.length,m=lt/Ke.total*100;return e.jsxs("section",{className:"mb-6 rounded-2xl border border-cyan-500/15 bg-cyan-500/[0.04] p-4","data-testid":"section-narrasync-timeline",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[e.jsxs("h2",{className:"text-lg font-semibold tracking-tight flex items-center gap-2",children:[e.jsx(Ie,{className:"h-4 w-4 text-cyan-400"})," Linha do tempo",e.jsxs("span",{className:"text-sm font-normal text-zinc-500",children:["(",x.length," cenas · ",d," cortes · ",Dt(Ke.total),")"]})]}),e.jsx("span",{className:`inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-semibold ${_e.monetizable?"border-emerald-500/30 bg-emerald-500/15 text-emerald-300":"border-amber-500/30 bg-amber-500/15 text-amber-300"}`,"data-testid":"badge-timeline-monetizable",title:_e.monetizable?"Narração ≥ 8 min → habilita anúncio no meio do vídeo (mid-roll).":"Falta narração para chegar aos 8 min que liberam o anúncio do meio.",children:_e.monetizable?e.jsxs(e.Fragment,{children:[e.jsx(ue,{className:"h-3.5 w-3.5"})," Monetizável"]}):e.jsxs(e.Fragment,{children:[e.jsx(ce,{className:"h-3.5 w-3.5"})," ",Dt(lt)," p/ mid-roll"]})})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"flex h-9 w-full overflow-hidden rounded-lg bg-zinc-900/60 ring-1 ring-white/5","data-testid":"timeline-track",children:Ke.cuts.map((F,E)=>{const k=x[F.sceneIdx],q=k?S.get(k.id):void 0,ie=q?.status==="ready"&&!!q.url,J=q?.status==="failed",K=F.dur/Ke.total*100,D=(k?.visualPrompt||k?.text||"").trim().slice(0,140);return e.jsx("div",{className:`h-full border-r border-black/40 last:border-r-0 transition-colors ${ie?"bg-cyan-500/70 hover:bg-cyan-400":J?"bg-red-500/60":"bg-zinc-700/60"}`,style:{width:`${K}%`},title:`Corte ${E+1} · Cena ${F.sceneIdx+1} · ${F.dur.toFixed(2)}s${ie?"":J?" · falhou":" · pendente"}
33${D}`,"data-testid":`timeline-seg-${E}`},E)})}),m>0&&m<=100&&e.jsxs("div",{className:"absolute top-0 bottom-0 pointer-events-none",style:{left:`${m}%`},"data-testid":"timeline-midroll",children:[e.jsx("div",{className:"h-9 w-0.5 bg-amber-400"}),e.jsxs("span",{className:"absolute -top-5 left-1 whitespace-nowrap rounded bg-amber-400/90 px-1 text-[10px] font-bold text-black",children:["Anúncio ",Dt(lt)]})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-zinc-400",children:[e.jsxs("span",{"data-testid":"text-timeline-duration-range",children:["Cada imagem aparece entre ",(Ft?Wa:Qa).toFixed(1).replace(".",","),"s e ",(Ft?Ja:Ya).toFixed(1).replace(".",","),"s — durações quebradas, como um humano editando (atual ",t.toFixed(2),"s–",s.toFixed(2),"s · média ",c.toFixed(2),"s · ",d," 
33cortes)",Ft?" · 1 imagem nova por corte":""]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-sm bg-cyan-500/70"})," pronta"]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-sm bg-zinc-700/60"})," pendente"]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-sm bg-red-500/60"})," falhou"]})]})]})})(),Fe&&e.jsx("div",{className:"mb-4 rounded-2xl border border-amber-400/25 bg-amber-500/[0.07] px-5 py-4","data-testid":"banner-heygen-health",children:e.jsxs("div",{className:"flex items-start gap-2.5 min-w-0",children:[e.jsx(Ce,{className:"h-5 w-5 shrink-0 text-amber-400 mt-0.5"}),e.jsx("div",{className:"min-w-0",children:xn?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-amber-200 font-medium text-sm","data-testid":"text-heygen-error-title",children:"HeyGen reprovou a imagem do take (moderação)"}),e.jsxs("p",{className:"text-amber-200/70 text-sm mt-0.5",children:["A HeyGen recusou a ",e.jsx("strong",{className:"text-amber-200",children:"imagem encenada"})," do seu clone na moderação de conteúdo — não é falta de créditos nem instabilidade. Clique em ",e.jsx("strong",{className:"text-amber-200",children:"Retomar geração"})," para criar uma nova encenação (cada tentativa gera uma imagem diferente); se repetir, troque a foto do clone em Meus Clones.",Qt?" Os takes do clone só saem pela HeyGen — o vídeo fica pausado até a imagem passar.":""]})]}):un?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-amber-200 font-medium text-sm","data-testid":"text-heygen-error-title",children:Qt?"HeyGen sem créditos de API — takes do clone pausados":"HeyGen sem créditos de API — takes gerados no motor reserva"}),e.jsxs("p",{className:"text-amber-200/70 text-sm mt-0.5",children:["A HeyGen recusou a geração por falta de créditos de ",e.jsx("strong",{className:"text-amber-200",children:"API"})," (erro 402). Atenção: os créditos de API são comprados ",e.jsx("strong",{className:"text-amber-200",children:"separadamente da assinatura do site"})," — assinar o plano web não libera a API. Compre em heygen.com → Space Settings → API. Depois, clique em ",e.jsx("strong",{className:"text-amber-200",children:"Retomar geração"}),Qt?" — os takes do clone saem exclusivamente pela HeyGen (o vídeo não avança em outro motor).":": os takes prontos são atualizados para o seu clone HeyGen automaticamente, sem regenerar nada no motor reserva."]})]}):Qt?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-amber-200 font-medium text-sm","data-testid":"text-heygen-error-title",children:"HeyGen falhou — takes do clone pausados"}),e.jsxs("p",{className:"text-amber-200/70 text-sm mt-0.5",children:["A HeyGen falhou na última geração",Fe?.status?` (erro ${Fe.status})`:"",": ",String(Fe?.message||"").slice(0,160),". Os takes do seu clone saem ",e.jsx("strong",{className:"text-amber-200",children:"exclusivamente pela HeyGen"})," — o vídeo NÃO avança em outro motor. Resolva o motivo acima (ou aguarde a HeyGen normalizar) e clique em ",e.jsx("strong",{className:"text-amber-200",children:"Retomar geração"}),": os takes prontos são mantidos e só o que falta é regenerado."]})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-amber-200 font-medium text-sm","data-testid":"text-heygen-error-title",children:"HeyGen indisponível — takes gerados no motor reserva"}),e.jsxs("p",{className:"text-amber-200/70 text-sm mt-0.5",children:["A HeyGen falhou na última geração",Fe?.status?` (erro ${Fe.status})`:"",": ",String(Fe?.message||"").slice(0,160),". Os takes saíram no motor reserva. Quando a HeyGen normalizar, clique em ",e.jsx("strong",{className:"text-amber-200",children:"Retomar geração"})," para atualizar os takes com o seu clone."]})]})})]})}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[e.jsxs("h2",{className:"text-lg font-semibold tracking-tight flex items-center gap-2",children:[e.jsx(Da,{className:"h-4 w-4 text-cyan-400"})," ",P?"Linha do tempo do roteiro":"Storyboard",e.jsxs("span",{className:"text-sm font-normal text-zinc-500",children:["(",x.length," ",P?`trecho${x.length===1?"":"s"}`:`cena${x.length===1?"":"s"}`,")"]})]}
33),V&&V.total>0&&(V.ready>=V.total&&!Ve?e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-emerald-500/30 bg-emerald-500/15 px-3 py-1 text-xs font-semibold text-emerald-300","data-testid":"badge-takesv2-progress",title:"Todos os trechos do roteiro já têm vídeo: takes do seu clone (Kling) + B-roll animado.",children:[e.jsx(ue,{className:"h-3.5 w-3.5"}),"100% em vídeo · ",V.total," trecho",V.total===1?"":"s"]}):e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-cyan-500/25 bg-cyan-500/10 px-3 py-1 text-xs font-medium text-cyan-200","data-testid":"badge-takesv2-progress",title:"Cada trecho do roteiro vira um vídeo: trechos-chave são takes do seu clone falando (Kling Avatar); os demais viram B-roll animado.",children:[Ve?e.jsx(f,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ce,{className:"h-3.5 w-3.5"}),V.ready," de ",V.total," trechos com vídeo"]})),!P&&L&&se.total>0&&(se.ready>=se.total&&!he?e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-emerald-500/30 bg-emerald-500/15 px-3 py-1 text-xs font-semibold text-emerald-300","data-testid":"badge-animation-progress",title:"Todas as cenas viraram clipes de vídeo com movimento real — nada de zoom em foto parada.",children:[e.jsx(ue,{className:"h-3.5 w-3.5"}),"100% animado · ",se.total," cena",se.total===1?"":"s"," com vídeo real"]}):e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-cyan-500/25 bg-cyan-500/10 px-3 py-1 text-xs font-medium text-cyan-200","data-testid":"badge-animation-progress",title:"Cada cena vira um clipe de vídeo com movimento real retratando a narração.",children:[he?e.jsx(f,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ce,{className:"h-3.5 w-3.5"}),se.ready," de ",se.total," cenas com vídeo real"]})),z&&Be?$e&&$e.ready>=$e.total&&!Ve?e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-emerald-500/30 bg-emerald-500/15 px-3 py-1 text-xs font-semibold text-emerald-300","data-testid":"badge-takes-progress",title:"Todas as cenas já têm vídeo REAL gerado direto do texto pela IA (Veo) — nada de foto parada. A montagem final acontece no render.",children:[e.jsx(ue,{className:"h-3.5 w-3.5"}),"100% em vídeo real · ",Be.total," cena",Be.total===1?"":"s"]}):e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-cyan-500/25 bg-cyan-500/10 px-3 py-1 text-xs font-medium text-cyan-200","data-testid":"badge-takes-progress",title:"Cada cena é montada a partir de clipes curtos de vídeo real gerados direto do texto pela IA (Veo). Os cards enchem conforme os clipes ficam prontos.",children:[Ve?e.jsx(f,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ce,{className:"h-3.5 w-3.5"}),$e?`${Be.coveredCount} de ${Be.total} cenas · ${$e.ready}/${$e.total} clipes`:`${Be.coveredCount} de ${Be.total} cenas com vídeo`]}):z&&Me.total>0?(()=>{const t=!!l?.metadata?.cinematicBeats,s=t?"Cinema por Cenas: todos os planos têm clipe de vídeo ÚNICO gerado direto do texto (Veo 3.1). Render pode começar.":"Cada cena é um take de vídeo REAL gerado direto do texto pela IA (Veo) — nada de foto parada.",c=t?"Cinema por Cenas: gerando clipes de vídeo únicos por plano (Veo 3.1). Cada plano ≤8s de narração vira 1 clipe diferente.":"Cada cena vira um take de vídeo real gerado direto do texto pela IA (Veo).";return Me.ready>=Me.total&&!Ve?e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-emerald-500/30 bg-emerald-500/15 px-3 py-1 text-xs font-semibold text-emerald-300","data-testid":"badge-takes-progress",title:s,children:[e.jsx(ue,{className:"h-3.5 w-3.5"}),t?`Cinema completo · ${Me.total} cena${Me.total===1?"":"s"}`:`100% em vídeo real · ${Me.total} cena${Me.total===1?"":"s"}`]}):e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-cyan-500/25 bg-cyan-500/10 px-3 py-1 text-xs font-medium text-cyan-200","data-testid":"badge-takes-progress",title:c,children:[Ve?e.jsx(f,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(fe,{className:"h-3.5 w-3.5"}),t?`Cinema por Cenas · ${Me.ready} de ${Me.total} clipes`:`${Me.ready} de ${Me.total} takes em vídeo real`]})})():null]}),L&&he&&e.jsxs("div",{className:"mb-4 flex items-center gap-3 rounded-2xl border border-cyan-500/20 bg-cyan-500/[0.06] px-4 py-3","data-testid":"banner-animating",children:[e.jsx(f,{className:"h-5 w-5 animate-spin text-cyan-300 shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-cyan-100",children:"Dando vida às cenas…"}),e.jsxs("p",{className:"text-xs text-cyan-300/80",children:[se.ready," de ",se.total," cenas já têm movimento real. Isso roda em segundo plano."]})]})]}),x.length===0?e.jsx("div",{className:"rounded-2xl border border-dashed border-white/10 bg-white/[0.01] py-14 text-center text-zinc-500","data-testid":"empty-scenes",children:Ve?"Gerando o roteiro…":"Este projeto ainda não tem cenas."}):e.jsxs(e.Fragment,{children:[_e.total>0&&e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2 text-xs","data-testid":"storyboard-stats",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-lg bg-white/[0.04] px-2.5 py-1 font-semibold text-cyan-100 ring-1 ring-white/10","data-testid":"text-total-duration",children:[e.jsx(Ie,{className:"h-3.5 w-3.5 text-cyan-300"})," ",Dt(_e.total)]}),e.jsxs("span",{className:"text-zinc-500",children:[x.length," cena",x.length===1?"":"s"]}),!O&&(_e.monetizable?e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-lg bg-emerald-500/15 px-2 py-1 font-semibold text-emerald-300 ring-1 ring-emerald-400/30","data-testid":"badge-monetizable",children:[e.jsx(ue,{className:"h-3.5 w-3.5"})," Mid-roll liberado (8:00)"]}):e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-lg bg-amber-500/10 px-2 py-1 font-medium text-amber-300/90 ring-1 ring-amber-400/20","data-testid":"badge-below-midroll",children:["Faltam ",Dt(Math.max(0,lt-_e.total))," p/ mid-roll"]}))]}),P?e.jsx("div",{className:"mt-1","data-testid":"timeline-roteiro",children:x.map((t,s)=>e.jsx(Cr,{scene:t,index:s,total:x.length,asset:S.get(t.id),clip:y.get(t.id),generating:Ve,regenerating:h.img.has(t.id)||h.anim.has(t.id),shotsCount:I.get(t.id)?.length,onOpen:()=>B(s),onEdit:()=>oe(t.id)},t.id))}):e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 ga
33p-3","data-testid":"grid-storyboard",children:x.map((t,s)=>{const c=Be?.coverByScene.get(t.id),d=z&&!!l?.metadata?.cinematicBeats,m=(()=>{if(!p?.fastCutsEnabled||!l?.metadata?.kenBurnsForced)return null;const F=Number(p?.fastCutMaxSec)||7.3,E=Number(p?.fastCutTargetSec)||4,k=_e.perScene[s]||0;if(!(k>F))return null;const q=Math.ceil(k/F),ie=Math.round(k/E);return Math.max(2,q,ie)})();return e.jsx(Tr,{scene:t,index:s,asset:S.get(t.id),clip:y.get(t.id),poolClip:c?.preview,poolPending:!!Be&&Ve&&!c?.preview,isT2vTake:d,fastCutCuts:m,shotsCount:I.get(t.id)?.length,regenImage:h.img.has(t.id),regenNarration:h.narr.has(t.id),regenAnimate:h.anim.has(t.id),onOpen:()=>B(s),onEdit:()=>oe(t.id)},t.id)})})]}),!fn&&e.jsxs("button",{onClick:()=>Ta.mutate(),disabled:Ta.isPending||x.length>=30,className:"mt-4 w-full inline-flex items-center justify-center gap-2 rounded-2xl border border-dashed border-white/12 bg-white/[0.02] px-5 py-4 text-sm font-medium text-zinc-300 hover:border-cyan-500/40 hover:bg-cyan-500/[0.04] transition-colors disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"button-add-scene",children:[Ta.isPending?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(ai,{className:"h-4 w-4"}),x.length>=30?"Limite de cenas atingido":"Adicionar cena"]}),e.jsxs("p",{className:"mt-6 text-xs text-zinc-600 leading-relaxed",children:["Dica: toque em um quadro para ver o take em ",e.jsx("span",{className:"text-zinc-400",children:"tela cheia"}),". Use"," ",e.jsx("span",{className:"text-zinc-400",children:"Editar"})," para ajustar a narração, o prompt da imagem e o"," ",e.jsx("span",{className:"text-cyan-300",children:"movimento"})," da cena — depois clique em"," ",e.jsx("span",{className:"text-cyan-300",children:"Renderizar de novo"})," para montar o MP4 atualizado."]}),G!==null&&x[G]&&e.jsx(Ar,{scenes:x,index:G,assetByScene:S,clipByScene:y,coverByScene:Be?.coverByScene,shotsByScene:I,onClose:()=>B(null),onIndex:t=>B(t)}),Z&&e.jsx(Pr,{projectId:u,scene:Z,asset:S.get(Z.id),clip:y.get(Z.id),voice:me.get(Z.id),index:ee,total:x.length,regenImage:h.img.has(Z.id),regenNarration:h.narr.has(Z.id),regenAnimate:h.anim.has(Z.id),animationEnabled:L,onClose:()=>oe(null),onChanged:M,onMove:t=>dn(ee,t)},Z.id)]}):e.jsxs("div",{className:"text-center py-20 text-zinc-500","data-testid":"text-not-found",children:[e.jsx(fe,{className:"h-10 w-10 mx-auto mb-3 text-zinc-700"}),"Projeto não encontrado."]})]}),e.jsx(Xa,{open:en,onOpenChange:Bt,platform:"YouTube",destination:C.find(t=>t.id===N)?.name||C[0]?.name||null,onConfirm:()=>{Bt(!1),ns.mutate()},testId:"yt-publish"}),is&&(()=>{const t=ft?Pe===ft:!Pe&&_t===Wt,s=Pe?wa.find(m=>m.id===Pe):null,c=Pe?s?.name||"Minha voz clonada":_a.find(m=>m.id===_t)?.label||"Selecione uma voz",d=t?"Mesma voz atual — escolha uma diferente":Pe?"Voz clonada selecionada":"Voz de catálogo selecionada";return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/75 backdrop-blur-sm","data-testid":"dialog-voice-change",onClick:m=>{m.target===m.currentTarget&&(At(!1),ke(null))},children:e.jsxs("div",{className:"relative w-full max-w-2xl rounded-3xl border border-white/[0.08] bg-[#060d1a] shadow-2xl flex flex-col max-h-[90vh]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 px-6 pt-6 pb-4 border-b border-white/[0.06] shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"h-10 w-10 rounded-2xl bg-cyan-500/15 text-cyan-400 flex items-center justify-center shrink-0",children:e.jsx(Ps,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold tracking-tight",children:"Trocar voz da narração"}),e.jsxs("p",{className:"text-xs text-zinc-500",children:["Todas as ",x.length," cena",x.length!==1?"s":""," serão re-narradas com a voz escolhida. O vídeo será re-renderizado em seguida."]})]})]}),e.jsx("button",{onClick:()=>{At(!1),ke(null)},className:"h-8 w-8 rounded-full flex items-center justify-center text-zinc-500 hover:text-zinc-200 hover:bg-white/10 transition-all","data-testid":"button-voice-dialog-close",children:e.jsx(jt,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"mx-6 mt-4 shrink-0 rounded-2xl border border-amber-500/20 bg-amber-500/[0.06] px-4 py-3",children:e.jsxs("p",{className:"text-xs text-amber-300/90 flex items-start gap-2",children:[e.jsx(Ce,{className:"h-3.5 w-3.5 shrink-0 mt-0.5"}),e.jsxs("span",{children:["A narração de ",e.jsxs("strong",{children:[x.length," cena",x.length!==1?"s":""]})," será regenerada do zero com a nova voz. O áudio antigo será substituído e o vídeo re-renderizado automaticamente."]})]})}),sn&&wa.length>0&&e.jsxs("div",{className:"px-6 pt-4 shrink-0",children:[e.jsxs("p",{className:"text-[11px] font-semibold uppercase tracking-widest text-zinc-500 mb-2.5 flex items-center gap-1.5",children:[e.jsx(Ms,{className:"h-3.5 w-3.5 text-violet-400"}
33),"Minha voz clonada"]}),e.jsx("div",{className:"flex flex-col gap-2",children:wa.map(m=>{const F=Pe===m.id,E=ft===m.id;return e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>{pt(m.id),Pt(Vt)},onKeyDown:k=>{k.key==="Enter"&&(pt(m.id),Pt(Vt))},className:`flex items-center gap-3 p-3.5 rounded-2xl border cursor-pointer transition-all ${F?"border-violet-500/50 bg-violet-500/[0.08] ring-1 ring-violet-500/30":"border-white/[0.06] bg-white/[0.02] hover:border-violet-500/30 hover:bg-violet-500/[0.05]"}`,"data-testid":`card-voice-clone-${m.id}`,children:[e.jsx("span",{className:`h-4 w-4 shrink-0 rounded-full border-2 flex items-center justify-center transition-all ${F?"border-violet-400 bg-violet-400":"border-white/20"}`,children:F&&e.jsx("span",{className:"h-2 w-2 rounded-full bg-white"})}),e.jsx("span",{className:`h-9 w-9 shrink-0 rounded-xl flex items-center justify-center ${F?"bg-violet-500/20 text-violet-300":"bg-white/[0.06] text-zinc-400"}`,children:e.jsx(Ms,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-sm font-semibold truncate ${F?"text-violet-200":"text-zinc-200"}`,children:m.name||"Minha voz clonada"}),e.jsx("p",{className:"text-xs text-zinc-500 truncate",children:"Voz gerada a partir da sua gravação"})]}),E&&e.jsx("span",{className:"shrink-0 text-[10px] px-1.5 py-0.5 rounded-md border border-violet-500/30 text-violet-400 bg-violet-500/10",children:"atual"})]},m.id)})}),e.jsxs("div",{className:"flex items-center gap-3 mt-4",children:[e.jsx("div",{className:"flex-1 h-px bg-white/[0.06]"}),e.jsx("span",{className:"text-[10px] text-zinc-600 font-medium uppercase tracking-wider shrink-0",children:"ou escolha do catálogo"}),e.jsx("div",{className:"flex-1 h-px bg-white/[0.06]"})]})]}),e.jsx("div",{className:"flex items-center gap-2 px-6 pt-4 shrink-0",children:["all","female","male"].map(m=>e.jsx("button",{onClick:()=>os(m),className:`px-3 py-1.5 rounded-xl text-xs font-medium transition-all border ${ja===m?"bg-cyan-500/20 text-cyan-200 border-cyan-500/40":"bg-white/[0.03] text-zinc-400 border-white/[0.06] hover:bg-white/[0.06]"}`,"data-testid":`tab-voice-gender-${m}`,children:m==="all"?"Todas":m==="female"?"Femininas":"Masculinas"},m))}),e.jsx("div",{className:"overflow-y-auto flex-1 px-6 pb-2 pt-3",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2.5",children:_a.filter(m=>ja==="female"?m.gender==="female":ja==="male"?m.gender==="male":!0).map(m=>{const F=!Pe&&_t===m.id,E=tn===m.id,k=an===m.id;return e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>{Pt(m.id),pt(null)},onKeyDown:q=>{q.key==="Enter"&&(Pt(m.id),pt(null))},className:`flex items-center gap-3 p-3 rounded-2xl border cursor-pointer transition-all ${F?"border-cyan-500/50 bg-cyan-500/[0.08] ring-1 ring-cyan-500/30":"border-white/[0.06] bg-white/[0.02] hover:border-white/[0.15] hover:bg-white/[0.05]"}`,"data-testid":`card-voice-${m.id}`,children:[e.jsx("span",{className:`h-4 w-4 shrink-0 rounded-full border-2 flex items-center justify-center transition-all ${F?"border-cyan-400 bg-cyan-400":"border-white/20"}`,children:F&&e.jsx("span",{className:"h-2 w-2 rounded-full bg-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-sm font-medium truncate ${F?"text-cyan-200":"text-zinc-200"}`,children:m.label}),m.desc&&e.jsx("p",{className:"text-xs text-zinc-500 truncate",children:m.desc})]}),!ft&&m.id===Wt&&e.jsx("span",{className:"shrink-0 text-[10px] px-1.5 py-0.5 rounded-md border border-cyan-500/30 text-cyan-400 bg-cyan-500/10",children:"atual"}),e.jsx("button",{onClick:q=>{q.stopPropagation(),(async()=>{if(E){we.current&&(we.current.pause(),we.current.src=""),ke(null);return}if(we.current&&(we.current.pause(),we.current.src=""),ke(null),Na.current[m.id]){const J=new Audio(Na.current[m.id]);we.current=J,J.onended=()=>ke(null),ke(m.id),J.play().catch(()=>ke(null));return}rs(m.id);try{const K=await(await R("POST","/api/videos/voice-preview",{voiceId:m.id})).json();if(K?.url){Na.current[m.id]=K.url;const D=new Audio(K.url);we.current=D,D.onended=()=>ke(null),ke(m.id),D.play().catch(()=>ke(null))}}catch{}finally{rs(null)}})()},className:`h-8 w-8 shrink-0 rounded-full flex items-center justify-center transition-all ${E||k?"bg-cyan-500/25 text-cyan-300":"bg-white/[0.05] text-zinc-400 hover:bg-white/[0.12] hover:text-zinc-200"}`,"data-testid":`button-voice-preview-${m.id}`,title:E?"Pausar":"Ouvir amostra",children:k?e.jsx(f,{className:"h-3.5 w-3.5 animate-spin"}
33):E?e.jsx(Ds,{className:"h-3.5 w-3.5"}):e.jsx(qt,{className:"h-3.5 w-3.5 translate-x-[1px]"})})]},m.id)})})}),e.jsxs("div",{className:"flex items-center justify-between gap-3 px-6 py-5 border-t border-white/[0.06] shrink-0 mt-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:`text-sm font-medium truncate ${Pe?"text-violet-300":"text-zinc-300"}`,children:c}),e.jsx("p",{className:"text-xs text-zinc-500",children:d})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx("button",{onClick:()=>{At(!1),ke(null)},className:"px-4 py-2 rounded-xl border border-white/[0.10] text-sm text-zinc-400 hover:text-zinc-200 hover:border-white/[0.20] transition-all","data-testid":"button-voice-cancel",children:"Cancelar"}),e.jsx("button",{onClick:()=>{we.current&&(we.current.pause(),we.current.src=""),ke(null),Pe?xt.mutate({voicePersonaId:Pe}):xt.mutate({voiceId:_t})},disabled:t||xt.isPending,className:`inline-flex items-center gap-2 px-5 py-2 rounded-xl text-sm font-semibold text-white shadow-lg transition-all disabled:opacity-40 disabled:cursor-not-allowed ${Pe?"bg-gradient-to-r from-violet-600 to-purple-600 shadow-violet-900/30 hover:opacity-95":"bg-gradient-to-r from-cyan-600 to-blue-600 shadow-cyan-900/30 hover:opacity-95"}`,"data-testid":"button-voice-confirm",children:xt.isPending?e.jsxs(e.Fragment,{children:[e.jsx(f,{className:"h-4 w-4 animate-spin"})," Trocando…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Te,{className:"h-4 w-4"})," Trocar e Regenerar"]})})]})]})]})})})()]})}function Cr({scene:a,index:i,total:b,asset:u,clip:w,generating:v,regenerating:p,shotsCount:l,onOpen:g,onEdit:C}){const T=o.useRef(null),j=w?.url||null,N=u?.url||null,x=!!w?.metadata?.avatarHash,S=p||!j&&v;return o.useEffect(()=>{const I=T.current;if(!I||!j)return;const y=new IntersectionObserver(([L])=>{L.isIntersecting?I.play().catch(()=>{}):I.pause()},{threshold:.25});return y.observe(I),()=>y.disconnect()},[j]),e.jsxs("div",{className:"relative flex gap-3","data-testid":`timeline-row-${a.id}`,children:[e.jsxs("div",{className:"flex flex-col items-center shrink-0",children:[e.jsx("span",{className:`h-7 w-7 rounded-full flex items-center justify-center text-xs font-bold ring-1 ${j?"bg-cyan-500/20 text-cyan-200 ring-cyan-400/40":"bg-white/[0.04] text-zinc-400 ring-white/10"}`,"data-testid":`timeline-node-${a.id}`,children:i+1}),i<b-1&&e.jsx("span",{className:"w-px flex-1 bg-gradient-to-b from-cyan-500/30 to-white/[0.06]"})]}),e.jsx("div",{className:"min-w-0 flex-1 pb-4",children:e.jsxs("div",{className:"rounded-2xl border border-white/[0.06] bg-white/[0.02] p-3 flex gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm text-zinc-200 leading-relaxed whitespace-pre-wrap","data-testid":`timeline-text-${a.id}`,children:a.text||e.jsx("span",{className:"text-zinc-600 italic",children:"Sem texto neste trecho"})}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[j?e.jsxs("span",{className:`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-semibold ring-1 ${x?"bg-gradient-to-r from-cyan-500/25 to-sky-500/20 text-cyan-200 ring-cyan-400/50":"bg-cyan-500/15 text-cyan-200 ring-cyan-400/30"}`,"data-testid":`timeline-status-${a.id}`,title:x?"Este trecho é um take de VÍDEO do seu clone falando (Kling Avatar) — rosto consistente, sem imagem intermediária.":"Este trecho tem B-roll animado (vídeo real) cobrindo a narração.",children:[e.jsx(ue,{className:"h-2.5 w-2.5"})," ",x?"Take do clone pronto":"B-roll pronto"]}):S?e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md bg-cyan-500/10 px-1.5 py-0.5 text-[10px] font-medium text-cyan-200 ring-1 ring-cyan-400/25","data-testid":`timeline-status-${a.id}`,children:[e.jsx(f,{className:"h-2.5 w-2.5 animate-spin"})," Gerando vídeo…"]}):e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md bg-white/[0.04] px-1.5 py-0.5 text-[10px] font-medium text-zinc-400 ring-1 ring-white/10","data-testid":`timeline-status-${a.id}`,children:[e.jsx(Ie,{className:"h-2.5 w-2.5"})," Aguardando"]}),typeof l=="number"&&l>=2&&e.jsxs("button",{onClick:g,className:"inline-flex items-center gap-1 rounded-md bg-white/[0.04] px-1.5 py-0.5 text-[10px] font-medium text-zinc-300 ring-1 ring-white/10 hover:text-cyan-200 hover:ring-cyan-400/40 transition-colors",title:"Esta cena tem mais de uma imagem — toque para ver todas lado a lado","data-testid":`timeline-shots-${a.id}`,children:[e.jsx(st,{className:"h-2.5 w-2.5"})," ",l," imagens"]}),e.jsxs("button",{onClick:C,className:"inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-medium text-zinc-400 ring-1 ring-white/10 hover:text-cyan-200 hover:ring-cyan-400/40 transition-colors","data-testid":`timeline-edit-${a.id}`,children:[e.jsx(da,{className:"h-2.5 w-2.5"})," Editar"]})]})]}),e.jsx("button",{onClick:g,className:"relative w-20 sm:w-24 shrink-0 aspect-[9/16] rounded-xl overflow-hidden bg-black/50 border border-white/[0.06] hover:ring-2 hover:ring-cyan-400/50 transition-all","data-testid":`timeline-media-${a.id}`,"aria-label":`Abrir trecho ${i+1} em tela cheia`,children:j?e.jsx("video",{ref:T,src:j,muted:!0,loop:!0,playsInl
33ine:!0,preload:"metadata",poster:N||void 0,className:"h-full w-full object-cover","data-testid":`timeline-video-${a.id}`}):N?e.jsx("img",{src:N,alt:`Trecho ${i+1}`,className:"h-full w-full object-cover","data-testid":`timeline-img-${a.id}`}):S?e.jsx("div",{className:"h-full w-full flex flex-col items-center justify-center gap-1 text-cyan-200 animate-pulse bg-gradient-to-br from-cyan-500/10 to-blue-500/10",children:e.jsx(f,{className:"h-4 w-4 animate-spin text-cyan-400"})}):e.jsx("div",{className:"h-full w-full flex items-center justify-center text-zinc-600",children:e.jsx(fe,{className:"h-5 w-5"})})})]})})]})}function Tr({scene:a,index:i,asset:b,clip:u,poolClip:w,poolPending:v,regenImage:p,regenNarration:l,regenAnimate:g,isT2vTake:C,fastCutCuts:T,shotsCount:j,onOpen:N,onEdit:x}){const S=o.useRef(null),I=o.useRef(null),[y,L]=o.useState(!1),z=u?.url||null,O=b?.url||null,P=!z&&!O&&w?.url||null,V=p||g;return o.useEffect(()=>{const H=S.current;if(!H||!z)return;const G=new IntersectionObserver(([B])=>{B.isIntersecting?H.play().catch(()=>{}):H.pause()},{threshold:.25});return G.observe(H),()=>G.disconnect()},[z]),o.useEffect(()=>{const H=I.current;if(!H||!P)return;const G=new IntersectionObserver(([B])=>{B.isIntersecting?(L(!0),H.play().catch(()=>{})):H.pause()},{threshold:.2,rootMargin:"200px"});return G.observe(H),()=>G.disconnect()},[P]),e.jsxs("div",{className:"group relative aspect-video","data-testid":`cell-scene-${a.id}`,children:[e.jsxs("button",{onClick:N,className:"absolute inset-0 block w-full h-full rounded-xl overflow-hidden bg-black/50 border border-white/[0.06] ring-0 ring-cyan-400/0 hover:ring-2 hover:ring-cyan-400/50 transition-all","data-testid":`button-open-scene-${a.id}`,"aria-label":`Abrir cena ${i+1} em tela cheia`,children:[z?e.jsx("video",{ref:S,src:z,muted:!0,loop:!0,playsInline:!0,preload:"metadata",poster:O||void 0,className:"h-full w-full object-cover","data-testid":`video-scene-${a.id}`}):O?e.jsx("img",{src:O,alt:`Cena ${i+1}`,className:"h-full w-full object-cover","data-testid":`img-scene-${a.id}`}):P?e.jsx("video",{ref:I,src:y?P:void 0,muted:!0,loop:!0,playsInline:!0,preload:"none",className:"h-full w-full object-cover bg-black","data-testid":`video-pool-scene-${a.id}`}):v?e.jsxs("div",{className:"h-full w-full flex flex-col items-center justify-center gap-1 text-cyan-200 animate-pulse bg-gradient-to-br from-cyan-500/10 to-blue-500/10",children:[e.jsx(f,{className:"h-5 w-5 animate-spin text-cyan-400"}),e.jsx("span",{className:"text-[11px]",children:"Gerando vídeo…"})]}):e.jsx("div",{className:"h-full w-full flex flex-col items-center justify-center text-zinc-600",children:!V&&e.jsxs(e.Fragment,{children:[e.jsx(st,{className:"h-6 w-6 mb-1"}),e.jsx("span",{className:"text-[11px]",children:"Sem imagem"})]})}),e.jsx("span",{className:"absolute top-1.5 left-1.5 h-6 min-w-[1.5rem] px-1.5 rounded-md bg-black/60 text-cyan-200 text-xs font-semibold flex items-center justify-center ring-1 ring-white/10 backdrop-blur-sm","data-testid":`text-scene-order-${a.id}`,children:i+1}),z&&(C?e.jsxs("span",{className:"absolute top-1.5 right-1.5 inline-flex items-center gap-1 rounded-md bg-gradient-to-r from-cyan-500/25 to-sky-500/20 px-1.5 py-0.5 text-[10px] font-semibold text-cyan-200 ring-1 ring-cyan-400/50 backdrop-blur-sm","data-testid":`badge-cinema-${a.id}`,title:"Cinema por Cenas: clipe de vídeo gerado diretamente do texto da cena (Veo 3.1 · ≤8s). Cada plano do roteiro vira um clipe único.",children:[e.jsx(fe,{className:"h-2.5 w-2.5"})," Cinema"]}):e.jsxs("span",{className:"absolute top-1.5 right-1.5 inline-flex items-center gap-1 rounded-md bg-cyan-500/20 px-1.5 py-0.5 text-[10px] font-semibold text-cyan-200 ring-1 ring-cyan-400/40 backdrop-blur-sm","data-testid":`badge-animated-${a.id}`,children:[e.jsx(ce,{className:"h-2.5 w-2.5"})," Animada"]})),P&&e.jsxs("span",{className:"absolute top-1.5 right-1.5 inline-flex items-center gap-1 rounded-md bg-blue-500/20 px-1.5 py-0.5 text-[10px] font-semibold text-blue-200 ring-1 ring-blue-400/40 backdrop-blur-sm","data-testid":`badge-preview-${a.id}`,children:[e.jsx(ce,{className:"h-2.5 w-2.5"})," Prévia"]}),!z&&!P&&O&&typeof T=="number"&&T>=2&&e.jsxs("span",{className:"absolute bottom-1.5 right-1.5 inline-flex items-center gap-1 rounded-md bg-cyan-500/20 px-1.5 py-0.5 text-[10px] font-semibold text-cyan-200 ring-1 ring-cyan-400/40 backdrop-blur-sm","data-testid":`badge-fastcuts-${a.id}`,title:"Cena longa: o vídeo final troca a imagem em vários cortes rápidos (1,5–7,3s cada) para prender a atenção, em vez de segurar uma foto parada o tempo todo.",children:[e.jsx(Ls,{className:"h-2.5 w-2.5"})," ≈",T," cortes"]}),e.jsx("span",{className:"absolute inset-0 flex items-center justify-center bg-black/0 group-hover:bg-black/25 opacity-0 group-hover:opacity-100 transition-all",children:e.jsx(_s,{className:"h-6 w-6 text-white drop-shadow-lg"})}),typeof j=="number"&&j>=2&&!(l&&!V)&&e.jsxs("span",{className:"absolute bottom-1.5 left-1.5 inline-flex items-center gap-1 rounded-md bg-black/60 px-1.5 py-0.5 text-[10px] font-semibold text-zinc-200 ring-1 ring-white/10 backdrop-blur-sm",title:"Esta cena tem mais de uma imagem — toque para ver todas lado a lado","data-testid":`badge-shots-${a.id}`,children:[e.jsx(st,{className:"h-2.5 w-2.5"})," ",j," imagens"]}),l&&!V&&e.jsxs("span",{className:"absolute bottom-1.5 left-1.5 inline-flex items-center gap-1 rounded-md bg-black/60 px-1.5 py-0.5 text-[10px] text-cyan-200 ring-1 ring-white/10 backdrop-blur-sm",children:[e.jsx(f,{className:"h-2.5 w-2.5 animate-spin"})," Narração…"]}),V&&e.jsxs("div",{className:"absolute inset-0 bg-black/60 flex flex-col items-center justify-center gap-1","data-testid":`overlay-regen-${a.id}`,children:[e.jsx(f,{className:"h-6 w-6 animate-spin text-cyan-400"}),e.jsx("span",{className:"text-[10px] text-cyan-200",children:g?"Animando…":"Gerando…"})]})]}),e.jsxs("button",{onClick:x,className:"absolute bottom-1.5 right-1.5 z-10 
33inline-flex items-center gap-1 rounded-lg bg-black/70 px-2 py-1 text-[11px] font-medium text-zinc-100 ring-1 ring-white/15 backdrop-blur-sm hover:bg-cyan-500/30 hover:ring-cyan-400/50 transition-colors","data-testid":`button-edit-scene-${a.id}`,children:[e.jsx(da,{className:"h-3 w-3"})," Editar"]})]})}function Ar({scenes:a,index:i,assetByScene:b,clipByScene:u,coverByScene:w,shotsByScene:v,onClose:p,onIndex:l}){const g=o.useRef(null),C=a[i],T=C?u.get(C.id):void 0,j=C?b.get(C.id):void 0,N=(C?v?.get(C.id):void 0)||[],[x,S]=o.useState(null);o.useEffect(()=>{S(null)},[i]);const I=x?N.find(P=>P.id===x):void 0,y=C&&!T?.url&&!j?.url?w?.get(C.id)?.preview:void 0,L=o.useCallback(()=>l(Math.max(0,i-1)),[i,l]),z=o.useCallback(()=>l(Math.min(a.length-1,i+1)),[i,a.length,l]);if(o.useEffect(()=>{const P=Bs("video-project-scene-lightbox"),V=H=>{H.key==="Escape"?p():H.key==="ArrowLeft"?L():H.key==="ArrowRight"&&z()};return window.addEventListener("keydown",V),()=>{window.removeEventListener("keydown",V),P()}},[p,L,z]),!C)return null;const O=()=>{const P=g.current,V=P?.requestFullscreen||P?.webkitEnterFullscreen||P?.webkitRequestFullscreen;if(V)try{V.call(P)}catch{}};return e.jsxs("div",{className:"fixed inset-0 z-[60] bg-black/95 backdrop-blur-sm flex flex-col","data-app-overlay-open":"true","data-scroll-lock-owner":"video-project-scene-lightbox","data-testid":"lightbox",onClick:p,children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 p-4",onClick:P=>P.stopPropagation(),children:[e.jsxs("span",{className:"text-sm text-zinc-300","data-testid":"text-lightbox-position",children:["Cena ",i+1," de ",a.length]}),e.jsxs("div",{className:"flex items-center gap-2",children:[(T?.url||y?.url)&&e.jsxs("button",{onClick:O,className:"inline-flex items-center gap-1.5 rounded-lg border border-white/10 bg-white/[0.04] px-3 py-1.5 text-sm text-zinc-200 hover:bg-white/[0.08]","data-testid":"button-lightbox-fullscreen",children:[e.jsx(_s,{className:"h-4 w-4"})," Tela cheia"]}),e.jsx("button",{onClick:p,className:"h-9 w-9 inline-flex items-center justify-center rounded-lg border border-white/10 bg-white/[0.04] text-zinc-200 hover:bg-white/[0.08]","data-testid":"button-lightbox-close","aria-label":"Fechar",children:e.jsx(jt,{className:"h-5 w-5"})})]})]}),e.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center gap-2 px-2 sm:px-4 pb-2",onClick:P=>P.stopPropagation(),children:[e.jsx("button",{onClick:L,disabled:i===0,className:"h-10 w-10 shrink-0 inline-flex items-center justify-center rounded-full border border-white/10 bg-white/[0.04] text-zinc-200 hover:bg-white/[0.08] disabled:opacity-30 disabled:cursor-not-allowed","data-testid":"button-lightbox-prev","aria-label":"Cena anterior",children:e.jsx(si,{className:"h-5 w-5"})}),e.jsx("div",{className:"flex-1 h-full flex items-center justify-center min-w-0",children:I?.url?e.jsx("img",{src:I.url,alt:`Cena ${i+1} — imagem ${ca(I)+1}`,className:"max-h-full max-w-full rounded-xl object-contain","data-testid":"img-lightbox-shot"},I.id):T?.url?e.jsx("video",{ref:g,src:T.url,controls:!0,autoPlay:!0,loop:!0,playsInline:!0,poster:j?.url||void 0,className:"max-h-full max-w-full rounded-xl","data-testid":"video-lightbox"},C.id):j?.url?e.jsx("img",{src:j.url,alt:`Cena ${i+1}`,className:"max-h-full max-w-full rounded-xl object-contain","data-testid":"img-lightbox"}):y?.url?e.jsx("video",{ref:g,src:y.url,controls:!0,autoPlay:!0,loop:!0,playsInline:!0,className:"max-h-full max-w-full rounded-xl","data-testid":"video-lightbox-pool"},C.id):e.jsx("div",{className:"text-zinc-500 text-sm",children:"Esta cena ainda não tem mídia."})}),e.jsx("button",{onClick:z,disabled:i===a.length-1,className:"h-10 w-10 shrink-0 inline-flex items-center justify-center rounded-full border border-white/10 bg-white/[0.04] text-zinc-200 hover:bg-white/[0.08] disabled:opacity-30 disabled:cursor-not-allowed","data-testid":"button-lightbox-next","aria-label":"Próxima cena",children:e.jsx(oa,{className:"h-5 w-5"})})]}),N.length>=2&&e.jsx("div",{className:"px-4 pb-2",onClick:P=>P.stopPropagation(),"data-testid":"strip-scene-shots",children:e.jsxs("div",{className:"mx-auto max-w-3xl rounded-2xl border border-white/[0.08] bg-white/[0.03] p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs font-semibold text-cyan-200",children:[e.jsx(st,{className:"h-3.5 w-3.5"})," Imagens desta cena (",N.length,")"]}),x&&(T?.url||y?.url)&&e.jsxs("button",{onClick:()=>S(null),className:"inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[11px] font-medium text-zinc-400 ring-1 ring-white/10 hover:text-cyan-200 hover:ring-cyan-400/40 transition-colors","data-testid":"button-lightbox-back-to-cl
33ip",children:[e.jsx(qt,{className:"h-2.5 w-2.5"})," Voltar ao vídeo"]})]}),e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-1",children:N.map(P=>{const V=ca(P),H=x===P.id;return e.jsxs("button",{onClick:()=>S(H?null:P.id),className:`group relative shrink-0 overflow-hidden rounded-xl border transition-all ${H?"border-cyan-400/70 ring-2 ring-cyan-400/50":"border-white/10 hover:border-cyan-400/40 hover:ring-1 hover:ring-cyan-400/30"}`,title:V===0?"Imagem principal — é a base do vídeo desta cena":`Imagem complementar ${V}`,"data-testid":`thumb-scene-shot-${V}`,children:[e.jsx("img",{src:P.url||void 0,alt:V===0?"Imagem principal":`Imagem ${V+1}`,className:"h-24 w-auto object-cover",loading:"lazy"}),e.jsx("span",{className:`absolute bottom-1 left-1 rounded px-1 py-px text-[9px] font-semibold ${V===0?"bg-cyan-500/80 text-white":"bg-black/70 text-zinc-200"}`,children:V===0?"Principal":`Extra ${V}`})]},P.id)})}),e.jsxs("p",{className:"mt-1.5 text-[11px] leading-relaxed text-zinc-500",children:["A imagem ",e.jsx("span",{className:"text-cyan-300",children:"principal"})," é a base do vídeo desta cena; as demais são ângulos complementares. Toque para ampliar cada uma."]})]})}),C.text&&e.jsx("p",{className:"px-6 pb-6 pt-1 text-center text-sm text-zinc-400 max-w-3xl mx-auto",onClick:P=>P.stopPropagation(),"data-testid":"text-lightbox-narration",children:C.text})]})}function Pr({projectId:a,scene:i,asset:b,clip:u,voice:w,index:v,total:p,regenImage:l,regenNarration:g,regenAnimate:C,animationEnabled:T,onClose:j,onChanged:N,onMove:x}){const{toast:S}=nt(),[I,y]=o.useState(i.text||""),[L,z]=o.useState(i.visualPrompt||""),[O,P]=o.useState(i.metadata?.motionPrompt||""),V=7.5,H=6,G=w?.status==="ready"&&w?.durationMs?w.durationMs/1e3:0,B=G>V?Math.min(H,Math.max(2,Math.ceil(G/V))):2,[Q,oe]=o.useState(B);o.useEffect(()=>{oe(B)},[B]);const he=I!==(i.text||"")||L!==(i.visualPrompt||"")||O!==(i.metadata?.motionPrompt||"");o.useEffect(()=>{const A=Bs("video-project-scene-editor"),de=ge=>{ge.key==="Escape"&&j()};return window.addEventListener("keydown",de),()=>{A(),window.removeEventListener("keydown",de)}},[j]);const se=U({mutationFn:async()=>(await R("PATCH",`/api/videos/projects/${a}/scenes/${i.id}`,{text:I,visualPrompt:L,motionPrompt:O})).json(),onSuccess:()=>{S({title:"Cena salva",description:"Refaça a imagem/animação para aplicar à mídia."}),N()},onError:A=>S({title:"Não foi possível salvar",description:A?.message,variant:"destructive"})}),Z=U({mutationFn:async A=>(await R("POST",`/api/videos/projects/${a}/scenes/${i.id}/regenerate`,{target:A})).json(),onSuccess:A=>{S({title:A?.target==="all"?"Refazendo a cena inteira ✨":A?.target==="narration"?"Refazendo a narração…":A?.target==="animate"?"Dando vida à cena ✨":"Refazendo a imagem…",description:A?.target==="all"?"Imagem, movimento e narração estão sendo refeitos. Aparecem aqui em alguns minutos.":A?.target==="animate"?"A IA está animando o quadro. O clipe aparece aqui em alguns minutos.":"A nova versão aparece aqui em instantes."}),N()},onError:A=>S({title:"Não foi possível refazer",description:A?.message,variant:"destructive"})}),ee=U({mutationFn:async A=>(await R("POST",`/api/videos/projects/${a}/scenes/${i.id}/split-images`,{count:A})).json(),onSuccess:A=>{S({title:"Dividindo a cena em mais imagens ✨",description:`Gerando ${A?.count||Q} imagens complementares sobre a MESMA narração. Aparecem aqui em alguns minutos.`}),N()},onError:A=>S({title:"Não foi possível dividir",description:A?.message,variant:"destructive"})}),r=U({mutationFn:async()=>(await R("DELETE",`/api/videos/projects/${a}/scenes/${i.id}`,{})).json(),onSuccess:()=>{S({title:"Cena excluída"}),N(),j()},onError:A=>S({title:"Não foi possível excluir",description:A?.message,variant:"destructive"})}),be="bg-white/[0.03] border border-white/10 rounded-xl text-zinc-100 placeholder:text-zinc-600 focus-visible:ring-cyan-500/40",te=l||C||g||Z.isPending||ee.isPending;return e.jsx("div",{className:"fixed inset-0 z-[55] bg-black/80 backdrop-blur-sm flex items-end sm:items-center justify-center p-0 sm:p-4","data-app-overlay-open":"true","data-scroll-lock-owner":"video-project-scene-editor","data-testid":`editor-scene-${i.id}`,onClick:j,children:e.jsxs("div",{className:"w-full sm:max-w-2xl max-h-[92vh] flex flex-col rounded-t-3xl sm:rounded-3xl border border-white/10 bg-[#0a0f1e] shadow-2xl overflow-hidden",onClick:A=>A.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 px-5 py-4 border-b border-white/[0.06] shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"h-7 w-7 rounded-lg bg-blue-500/15 text-cyan-300 text-sm font-semibold flex items-center justify-center shrink-0",children:v+1}),e.jsx("h3",{className:"text-base font-semibold tracking-tight truncate",children:"Editar cena"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{onClick:()=>x(-1),disabled:v===0,className:"h-8 w-8 rounded-lg border border-white/10 text-zinc-400 hover:text-white hover:border-cyan-500/40 disabled:opacity-30 disabled:cursor-not-allowed flex items-center justify-center","data-testid":`button-move-up-${i.id}`,"aria-label":"Mover para cima",children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>x(1),disabled:v===p-1,className:"h-8 w-8 rounded-lg border border-white/10 text-zinc-400 hover:text-white hover:border-cyan-500/40 disabled:opacity-30 disabled:cursor-not-allowed flex items-center justify-center","data-testid":`button-move-down-${i.id}`,"aria-label":"Mover para baixo",children:e.jsx(ii,{className:"h-4 w-4"})}),e.jsx("button",{onClick:j,className:"h-8 w-8 rounded-lg border border-white/10 text-zinc-400 hover:text-white flex items-center justify-center","data-testid":"button-editor-close","aria-label":"Fechar",children:e.jsx(jt,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4 space-y-4",children:[e.jsxs("div",{className:"relative w-full aspect-video rounded-xl overflow-hidden bg-black/50 border border-white/[0.06]",children:[u?.url?e.jsx("video",{src:u.url,muted:!0,loop:!0,playsInl
33ine:!0,autoPlay:!0,poster:b?.url||void 0,className:"h-full w-full object-cover","data-testid":`editor-video-${i.id}`}):b?.url?e.jsx("img",{src:b.url,alt:`Cena ${v+1}`,className:"h-full w-full object-cover","data-testid":`editor-img-${i.id}`}):e.jsxs("div",{className:"h-full w-full flex flex-col items-center justify-center text-zinc-600",children:[e.jsx(st,{className:"h-6 w-6 mb-1"}),e.jsx("span",{className:"text-[11px]",children:"Sem imagem ainda"})]}),u?.url&&e.jsxs("span",{className:"absolute top-1.5 right-1.5 inline-flex items-center gap-1 rounded-md bg-cyan-500/20 px-1.5 py-0.5 text-[10px] font-semibold text-cyan-200 ring-1 ring-cyan-400/40 backdrop-blur-sm",children:[e.jsx(ce,{className:"h-2.5 w-2.5"})," Animada"]}),(l||C)&&e.jsxs("div",{className:"absolute inset-0 bg-black/60 flex flex-col items-center justify-center gap-1",children:[e.jsx(f,{className:"h-6 w-6 animate-spin text-cyan-400"}),e.jsx("span",{className:"text-[10px] text-cyan-200",children:C?"Animando…":"Gerando…"})]})]}),w?.url?e.jsx("audio",{src:w.url,controls:!0,className:"w-full h-9","data-testid":`editor-audio-${i.id}`}):e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs text-zinc-500",children:[e.jsx(Ba,{className:"h-3.5 w-3.5"})," Sem narração ainda"]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-zinc-400 mb-1",children:"Narração (texto)"}),e.jsx(wt,{value:I,onChange:A=>y(A.target.value),rows:3,placeholder:"O que a Sábhia narra nesta cena…",className:be,"data-testid":`input-scene-text-${i.id}`})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-zinc-400 mb-1",children:"Prompt da imagem"}),e.jsx(wt,{value:L,onChange:A=>z(A.target.value),rows:2,placeholder:"Descrição da imagem desta cena…",className:be,"data-testid":`input-scene-prompt-${i.id}`})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-xs font-medium text-zinc-400 mb-1 flex items-center gap-1.5",children:[e.jsx(fe,{className:"h-3.5 w-3.5 text-cyan-400"})," Movimento da cena (animação)"]}),e.jsx(wt,{value:O,onChange:A=>P(A.target.value),rows:2,placeholder:"Ex.: o soldado caminha à frente e vira a cabeça enquanto a câmera se aproxima lentamente",className:be,"data-testid":`input-scene-motion-${i.id}`}),e.jsxs("p",{className:"mt-1 text-[11px] leading-tight text-zinc-600",children:["Descreva o movimento REAL do que aparece (pessoas andando, gesticulando, virando). Deixe em branco para a IA decidir. Aplica ao ",e.jsx("span",{className:"text-cyan-300",children:"Animar"}),"/",e.jsx("span",{className:"text-cyan-300",children:"Refazer tudo"}),"."]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("button",{onClick:()=>Z.mutate("image"),disabled:te,className:"inline-flex items-center justify-center gap-1.5 rounded-lg border border-white/10 bg-white/[0.03] px-2.5 py-2 text-xs text-zinc-300 hover:bg-white/[0.06] disabled:opacity-50 disabled:cursor-not-allowed","data-testid":`button-regen-image-${i.id}`,children:[l?e.jsx(f,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Te,{className:"h-3.5 w-3.5"}),"Refazer imagem"]}),e.jsxs("button",{onClick:()=>Z.mutate("narration"),disabled:te,className:"inline-flex items-center justify-center gap-1.5 rounded-lg border border-white/10 bg-white/[0.03] px-2.5 py-2 text-xs text-zinc-300 hover:bg-white/[0.06] disabled:opacity-50 disabled:cursor-not-allowed","data-testid":`button-regen-narration-${i.id}`,children:[g?e.jsx(f,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Ba,{className:"h-3.5 w-3.5"}),"Refazer narração"]}),T&&b?.url&&e.jsxs("button",{onClick:()=>Z.mutate("animation"),disabled:te,className:"inline-flex items-center justify-center gap-1.5 rounded-lg border border-cyan-500/30 bg-cyan-500/[0.08] px-2.5 py-2 text-xs font-medium text-cyan-200 hover:bg-cyan-500/[0.16] disabled:opacity-50 disabled:cursor-not-allowed","data-testid":`button-animate-scene-${i.id}`,children:[C?e.jsx(f,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(fe,{className:"h-3.5 w-3.5"}),u?.url?"Reanimar":"Animar"]}),e.jsxs("button",{onClick:()=>Z.mutate("all"),disabled:te,className:"inline-flex items-center justify-center gap-1.5 rounded-lg border border-cyan-500/30 bg-gradient-to-r from-blue-500/15 to-cyan-400/15 px-2.5 py-2 text-xs font-semibold text-cyan-100 hover:from-blue-500/25 hover:to-cyan-400/25 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":`button-regen-all-${i.id}`,children:[Z.isPending?e.jsx(f,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ce,{className:"h-3.5 w-3.5"}),"Refazer tudo"]})]}),e.jsxs("div",{className:"rounded-xl border border-cyan-500/20 bg-cyan-500/[0.04] p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[e.jsx(st,{className:"h-3.5 w-3.5 text-cyan-400"}),e.jsx("span",{className:"text-xs font-semibold text-cyan-100",children:"Dividir em mais imagens"})]}),e.jsxs("p",{className:"text-[11px] leading-tight text-zinc-500 mb-2.5",children:[G>0?`Esta cena tem ${G.toFixed(0)}s de narração. `:"","Mostre várias imagens complementares sobre a MESMA narração — nada de uma única imagem parada por muito tempo.",G>V?` Sugerimos ${B} imagens.`:""]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"inline-flex items-center rounded-lg border border-white/10 bg-white/[0.03] shrink-0",children:[e.jsx("button",{onClick:()=>oe(A=>Math.max(2,A-1)),disabled:te||Q<=2,className:"h-9 w-9 text-lg leading-none text-zinc-300 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed flex items-center justify-center","data-testid":`button-split-dec-${i.id}`,"aria-label":"Menos imagens",children:"−"}),e.jsx("span",{className:"w-8 text-center text-sm font-semibold text-cyan-100","data-testid":`text-split-count-${i.id}`,children:Q}),e.jsx("button",{onClick:()=>oe(A=>Math.min(H,A+1)),disabled:te||Q>=H,className:"h-9 w-9 text-lg leading-none text-zinc-300 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed flex items-center justify-center","data-testid":`button-split-inc-${i.id}`,"aria-label":"Mais imagens",children:"+"})]}),e.jsxs("button",{onClick:()=>ee.mutate(Q),disabled:te,className:"flex-1 inline-flex items-center justify-center gap-1.5 rounded-lg border border-cyan-500/30 bg-gradient-to-r from-blue-500/15 to-cyan-400/15 px-2.5 py-2 text-xs font-semibold text-cyan-100 hover:from-blue-500/25 hover:to-cyan-400/25 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":`button-split-images-${i.id}`,children:[ee.isPending?e.jsx(f,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(st,{className:"h-3.5 w-3.5"}),"Dividir em ",Q," imagens"]})]})]})]}),e.jsxs("div",{className:"shrink-0 border-t border-white/[0.06] px-5 py-3 flex items-center justify-between gap-3 bg-[#0a0f1e]",children:[e.jsxs("button",{onClick:()=>{window.confirm("Excluir esta cena? A imagem e a narração dela também serão removidas.")&&r.mutate()},disabled:r.isPending,className:"inline-flex items-center gap-2 rounded-xl border border-white/10 px-3 py-2 text-sm text-zinc-400 hover:text-red-400 hover:border-red-500/30 transition-colors disabled:opacity-50","data-testid":`button-delete-scene-${i.id}`,children:[r.isPending?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(ki,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Excluir"})]}),e.jsxs("button",{onClick:()=>se.mutate(),disabled:!he||se.isPending,className:"inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-blue-500 to-cyan-400 px-5 py-2 text-sm font-semibold text-white shadow-lg shadow-blue-900/40 hover:opacity-95 disabled:opacity-40 disabled:cursor-not-allowed","data-testid":`button-save-scene-${i.id}`,children:[se.isPending?e.jsx(f,{className:"h-4 w-4 animate-spin"}):e.jsx(ma,{className:"h-4 w-4"}),"Salvar cena"]}
33)]})]})})}export{xo 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.