PageSourceSearch

https://sabhia.ai/assets/cover-studio-HewL20H7.js

js sabhia.ai collected 2026-10-05 12:33:34 UTC 107,627 bytes, 1 lines download raw bytes

1import{j as e,m as ts}from"./vendor-motion-CPxq9Xvn.js";import{n as as,a3 as Xt,a6 as wa,an as Y,ai as Zt,a7 as C,az as ss,a1 as rs,a2 as Ia,ec as Ra,u as ce,ar as Rt,z as Wt,B as T,P as bt,C as Te,S as F,ap as Ie,aJ as os,a4 as ya,eM as is,b as Ht,A as Oa,bP as Na,ay as Ca,i as Da,ab as ns,aa as ka,D as ls,q as cs,r as ds,Y as Yt,eN as ms,ae as us,af as xs,N as Sa,ag as ps,ac as hs,ad as fs,ah as gs}from"./index-CFAvyuXu.js";import{B as tt}from"./badge-B9GAfHbC.js";import{M as bs}from"./mobile-pipeline-bar-wnI4Ws72.js";import{C as Aa}from"./checkout-dialog-CtPFKUrs.js";import{r,u as vs}from"./vendor-i18n-CO3kK2bH.js";import{u as Ba}from"./useFeatureFlags-C-5VjyV0.js";import{W as Pa}from"./wand-sparkles-BFRdHggN.js";import{S as $a}from"./save-QXxXVhhp.js";import{P as js}from"./publication-pipeline-DFwPsRBR.js";import{P as ws}from"./pipeline-waiting-card-B1DCfEqh.js";import{g as wt}from"./pricing-BgVC2Us6.js";import{P as vt}from"./pricing-CEwbcjb3.js";import{A as jt}from"./arrow-left-DY50GvQQ.js";import{U as zt}from"./upload-BKNIN1AN.js";import{C as Ma}from"./camera-_nm-zf_d.js";import{T as ys}from"./trash-2-BF2rPJAw.js";import{D as Ea}from"./download-B7FtiUYJ.js";import{P as Ua}from"./pencil-DB7EhnQs.js";import{W as Ns}from"./wifi-BvXiCCFP.js";import"./vendor-react-CQmBMThG.js";import"./megaphone-CJoAWoYP.js";import"./barcode-DlYH0ciP.js";import"./book-marked-3-KNVwiq.js";import"./globe-D0MKCb1Y.js";import"./pix-qr-image-D45mJvPS.js";import"./alert-dialog-C9feqA9b.js";import"./stamp-BZO_gJDT.js";import"./select-B26x0xAv.js";import"./index-BdQq_4o_.js";const Cs=[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]],ks=as("zoom-in",Cs),Ss=["#000000","#0f172a","#0d9488","#7c3aed","#dc2626","#f59e0b","#ffffff","#1e293b"],Ps=["#ffffff","#000000","#fbbf24","#5eead4"];function $s({coverId:i,coverImageUrl:a,bookTitle:u,bookId:x,initialAdjustments:h}){const g=Ba(),{toast:p}=Xt(),o=r.useRef(null),n=r.useRef(null),[y,k]=r.useState(h?.bgOverlayColor||"#000000"),[f,P]=r.useState(h?.bgOverlayOpacity??.7),[I,L]=r.useState(h?.titleColor||"#ffffff"),[M,l]=r.useState(h?.titlePosition??50),[v,Ve]=r.useState(h?.titleAlignment||"center"),[$,de]=r.useState(!!(h&&(h.bgOverlayColor||h.titleColor))),je=r.useMemo(()=>({bgOverlayColor:$?y:null,bgOverlayOpacity:$?f:null,titleColor:$?I:null,titleText:u,titlePosition:$?M:null,titleAlignment:$?v:null}),[$,y,f,I,M,v,u]);r.useEffect(()=>{if(!a||!o.current)return;let c=!1;const R=new Image;return R.crossOrigin="anonymous",R.onload=()=>{c||(n.current=R,me())},R.onerror=()=>{},R.src=a,()=>{c=!0}},[a]),r.useEffect(()=>{me()},[$,y,f,I,M,v]);function me(){const c=o.current,R=n.current;if(!c||!R)return;const j=400,X=Math.round(R.naturalHeight/R.naturalWidth*j)||600;c.width=j,c.height=X;const w=c.getContext("2d");if(!w||(w.clearRect(0,0,j,X),w.drawImage(R,0,0,j,X),!$))return;const ue=Math.round(X*.18),oe=Math.round((X-ue)*M/100);w.globalAlpha=f,w.fillStyle=y,w.fillRect(0,oe,j,ue),w.globalAlpha=1;const xe=Math.round(X*.045);w.fillStyle=I,w.font=`bold ${xe}px Georgia, serif`,w.textBaseline="middle",w.textAlign=v==="left"?"left":v==="right"?"right":"center";const ie=Math.round(v==="left"?j*.06:v==="right"?j*.94:j/2),Z=oe+Math.round(ue/2);w.fillText(u.toUpperCase(),ie,Z,Math.round(j*.88))}const Q=wa({mutationFn:async()=>Y("PATCH",`/api/covers/${i}/adjustments`,$?je:null),onSuccess:()=>
1p({title:"Ajustes aplicados!",description:"Vão aparecer na próxima exportação (PDF/EPUB/DOCX)."}),onError:()=>p({title:"Não foi possível aplicar",description:"Tente novamente em instantes.",variant:"destructive"})}),J=Zt(),S=wa({mutationFn:async()=>Y("POST",`/api/covers/${i}/adjustments/save-as-new`,$?je:null),onSuccess:()=>{x&&J.invalidateQueries({queryKey:[`/api/books/${x}/covers`]}),p({title:"Nova versão salva!",description:"A capa original foi mantida intacta."})},onError:()=>p({title:"Não foi possível salvar a versão",description:"Tente novamente em instantes.",variant:"destructive"})});return g.coverDIYEditor?e.jsxs(ts.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},className:"rounded-2xl border border-emerald-500/20 bg-gradient-to-br from-emerald-500/[0.06] via-teal-500/[0.04] to-transparent backdrop-blur-md p-5 space-y-4","data-testid":"panel-cover-diy",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pa,{className:"w-4 h-4 text-emerald-300"}),e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Editor DIY de capa"}),e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-emerald-500/15 text-emerald-300 border border-emerald-500/25",children:"Beta"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:$,onChange:c=>de(c.target.checked),className:"accent-emerald-500","data-testid":"checkbox-cover-diy-enabled"}),"Aplicar ajustes"]})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[e.jsx("div",{className:"flex justify-center",children:e.jsx("canvas",{ref:o,className:"rounded-lg border border-white/10 max-w-full h-auto",style:{maxHeight:"320px"},"data-testid":"canvas-cover-diy-preview"})}),e.jsxs("div",{className:`space-y-4 ${$?"":"opacity-50 pointer-events-none"}`,children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-muted-foreground uppercase tracking-wider",children:"Cor de fundo do título"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[e.jsx("input",{type:"color",value:y,onChange:c=>k(c.target.value),className:"w-10 h-10 rounded cursor-pointer bg-transparent border border-white/10","data-testid":"input-cover-diy-bg-color"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Ss.map(c=>e.jsx("button",{type:"button",onClick:()=>k(c),className:`w-6 h-6 rounded border ${y===c?"border-emerald-400 ring-1 ring-emerald-400":"border-white/10"}`,style:{backgroundColor:c},"aria-label":c,"data-testid":`swatch-cover-diy-bg-${c.replace("#","")}`},c))})]}),e.jsxs("div",{className:"mt-2",children:[e.jsxs("label",{className:"text-[11px] text-muted-foreground",children:["Opacidade: ",Math.round(f*100),"%"]}),e.jsx("input",{type:"range",min:0,max:1,step:.05,value:f,onChange:c=>P(parseFloat(c.target.value)),className:"w-full accent-emerald-500","data-testid":"slider-cover-diy-opacity"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-muted-foreground uppercase tracking-wider",children:"Cor do título"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[e.jsx("input",{type:"color",value:I,onChange:c=>L(c.target.value),className:"w-10 h-10 rounded cursor-pointer bg-transparent border border-white/10","data-testid":"input-cover-diy-title-color"}),e.jsx("div",{className:"flex gap-1.5",children:Ps.map(c=>e.jsx("button",{type:"button",onClick:()=>L(c),className:`w-6 h-6 rounded border ${I===c?"border-emerald-400 ring-1 ring-emerald-400":"border-white/10"}`,style:{backgroundColor:c},"aria-label":c,"data-testid":`preset-cover-diy-title-${c.replace("#","")}`},c))})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-[11px] text-muted-foreground uppercase tracking-wider",children:["Posição vertical: ",M,"%"]}),e.jsx("input",{type:"range",min:0,max:100,step:1,value:M,onChange:c=>l(parseInt(c.target.value)),className:"w-full accent-emerald-500 mt-1.5","data-testid":"slider-cover-diy-position"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[11px] text-muted-foreground uppercase tracking-wider",children:"Alinhamento"}),e.jsx("div",{className:"flex gap-2 mt-1.5",children:["left","center","right"].map(c=>e.jsx("button",{type:"button",onClick:()=>Ve(c),className:`flex-1 py-1.5 text-xs rounded border transition-colors ${v===c?"bg-emerald-500/20 border-emerald-400/50 text-emerald-200":"bg-white/[0.02] border-white/10 text-muted-foreground hover:text-white"}`,"data-testid":`button-cover-diy-align-${c}`,children:c==="left"?"Esquerda":c==="right"?"Direita":"Centro"},c))})]})]})]}),e.jsxs("div",{className:"rounded-lg bg-amber-500/5 border border-amber-500/20 p-3 text-[11px] text-amber-200/90 leading-relaxed","data-testid":"text-cover-diy-boundary",children:[e.jsx(Pa,{className:"w-3.5 h-3.5 inline-block mr-1 -mt-0.5 text-amber-300"}),"Aqui você ajusta ",e.jsx("strong",{children:"cor, opacidade e posicionamento do título"}),". Para mudar a ",e.jsx("strong",{children:"imagem"})," da capa (objetos, cenário, estilo), use o"," ",e.jsx("a",{href:"#cover-adjustment-chat",className:"underline decoration-dotted underline-offset-2 hover:text-amber-100","data-testid":"link-cover-pro-adjustments",children:"ajustes profissionais (1 crédito)"}),"."]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:justify-end gap-2 pt-1",children:[e.jsxs("button",{type:"button",onClick:()=>S.mutate(),disabled:S.isPending||Q.isPending,className:"inline-flex items-center justify-center gap-2 px-4 py-2 rounded-lg border border-emerald-500/30 bg-emerald-500/10 hover:bg-emerald-500/20 disabled:opacity-50 text-emerald-200 text-sm font-medium transition-colors","data-testid":"button-cover-diy-save-as-new",children:[S.isPending?e.jsx(C,{className:"w-4 h-4 animate-spin"}):e.jsx($a,{className:"w-4 h-4"}),"Salvar como nova versão"]}),e.jsxs("button",{type:"button",onClick:()=>Q.mutate(),disabled:Q.isPending||S.isPending,className:"inline-flex items-center justify-center gap-2 px-4 py-2 rounded-lg bg-emerald-600 hover:bg-emerald-500 disabled:opacity-50 text-white text-sm font-medium transition-colors","data-testid":"button-cover-diy-apply",children:[Q.isPending?e.jsx(C,{className:"w-4 h-4 animate-spin"}):e.jsx($a,{className:"w-4 h-4"}),"Aplicar nesta capa"]})]})]}):null}const Jt="Upload do autor";function Es(i){return i?.style===Jt}function Ts(i,a){const u=a.trim().toLowerCase(),x=new Set(["image/jpeg","image/jpg","image/png","image/webp"]),h=/\.(jpe?g|png|webp)$/i.test(i.trim());return x.has(u)||h}
1function Is(i,a,u,x,h=[]){const g=new Set(a);for(const k of h)g.add(String(k));const p=u?i.filter(k=>g.has(String(k.id||""))||Es(k)):i,o=x?[x,...p]:p,n=new Set,y=new Set;return o.filter(k=>{const f=String(k.id||"").trim(),P=String(k.imageUrl||"").trim();return f&&n.has(f)||P&&y.has(P)?!1:(f&&n.add(f),P&&y.add(P),!0)})}function Rs(i,a,u){const x=Array.from(new Set(Array.from(i,n=>String(n).trim()).filter(Boolean))),h=new Set(a.map(n=>String(n.id||"").trim()).filter(Boolean)),g=x.filter(n=>!h.has(n)),p=Math.max(0,Math.floor(u||0)),o=x.length-g.length;return{expected:p,visible:o,complete:p>0&&x.length>=p&&o>=p,missingIds:g}}function Os(i,a){const u=i||[],x=String(a.id||""),h=String(a.imageUrl||"").trim(),g=u.find(o=>String(o.id||"")===x||String(o.imageUrl||"").trim()===h),p=u.filter(o=>String(o.id||"")!==x&&String(o.imageUrl||"").trim()!==h);return[{...a,selected:!!(g?.selected||a.selected)},...p]}function Ta(i,a,u){const x=document.createElement("canvas"),h=x.getContext("2d");if(!h)return;const g=1600,p=2560;x.width=g,x.height=p;const o=new Image;o.crossOrigin="anonymous",o.onload=()=>{const n=o.width/o.height,y=g/p;let k=0,f=0,P=o.width,I=o.height;n>y?(P=o.height*y,k=(o.width-P)/2):(I=o.width/y,f=(o.height-I)/2),h.drawImage(o,k,f,P,I,0,0,g,p),x.toBlob(L=>{if(!L)return;const M=URL.createObjectURL(L),l=document.createElement("a"),v=a.replace(/[^a-zA-Z0-9À-ÿ\s-]/g,"").trim().replace(/\s+/g,"-").toLowerCase();l.href=M,l.download=`${v||"capa"}-amazon-kdp.jpg`,document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(M)},"image/jpeg",.95)},o.onerror=()=>{u&&u()},o.src=i}const at=[{id:"artistic",image:"/images/cover-options/style-artistic.webp",label:"Artístico",desc:"Estilo pintura artística"},{id:"realistic",image:"/images/cover-options/style-realistic.webp",label:"Realista",desc:"Fotográfico e realista"},{id:"minimalist",image:"/images/cover-options/style-minimalist.webp",label:"Minimalista",desc:"Limpo e minimalista"},{id:"illustrated",image:"/images/cover-options/style-illustrated.webp",label:"Ilustrado",desc:"Ilustração desenhada"},{id:"abstract",image:"/images/cover-options/style-abstract.webp",label:"Abstrato",desc:"Formas abstratas"},{id:"classic",image:"/images/cover-options/style-classic.webp",label:"Clássico",desc:"Elegante e tradicional"}],Vt=[{id:"warm",image:"/images/cover-options/color-warm.webp",label:"Cores Quentes",desc:"Vermelho, laranja, dourado"},{id:"cool",image:"/images/cover-options/color-cool.webp",label:"Cores Frias",desc:"Azul, roxo, turquesa"},{id:"dark",image:"/images/cover-options/color-dark.webp",label:"Escuro e Misterioso",desc:"Preto, roxo escuro, carmesim"},{id:"earthy",image:"/images/cover-options/color-earthy.webp",label:"Natural e Terroso",desc:"Verde, marrom, bege"},{id:"vibrant",image:"/images/cover-options/color-vibrant.webp",label:"Vibrante e Colorido",desc:"Brilhante e multicolorido"},{id:"neutral",image:"/images/cover-options/color-neutral.webp",label:"Neutro e Elegante",desc:"Branco, cinza, creme"}],Ds=[{id:"person",image:"/images/cover-options/element-person.webp",label:"Uma Pessoa / Personagem"},{id:"landscape",image:"/images/cover-options/element-landscape.webp",label:"Uma Paisagem / Cenário"},{id:"symbolic",image:"/images/cover-options/element-symbolic.webp",label:"Um Objeto Simbólico"},{id:"abstract",image:"/images/cover-options/element-abstract.webp",label:"Formas Abstratas"},{id:"typography",image:"/images/cover-options/element-typography.webp",label:"Apenas Tipografia"}],Gt=[{id:"serif",image:"/images/cover-options/font-serif.webp",label:"Serifada",desc:"Clássica e elegante"},{id:"sans",image:"/images/cover-options/font-sans.webp",label:"Sem Serifa",desc:"Moderna e limpa"},{id:"script",image:"/images/cover-options/font-script.webp",label:"Cursiva",desc:"Sofisticada e fluida"},{id:"display",image:"/images/cover-options/font-display.webp",label:"Display Bold",desc:"Impactante e forte"},{id:"handwritten",image:"/images/cover-options/font-handwritten.webp",label:"Manuscrita",desc:"Pessoal e orgânica"},{id:"modern",image:"/images/cover-options/font-modern.webp",label:"Geométrica",desc:"Futurista e precisa"}],Kt=[{id:"white",color:"#FFFFFF",label:"Branco"},{id:"black",color:"#1a1a1a",label:"Preto"},{id:"gold",color:"#D4AF37",label:"Dourado"},{id:"silver",color:"#C0C0C0",label:"Prateado"},{id:"cream",color:"#FFFDD0",label:"Creme"},{id:"red",color:"#DC2626",label:"Vermelho"},{id:"navy",color:"#1E3A5F",label:"Azul Marinho"},{id:"emerald",color:"#065F46",label:"Esmeralda"}];let Qt=null;function As(){return Qt||(Qt=fetch("/api/stripe/publishable-key").then(i=>i.json()).then(i=>
1gs(i.publishableKey)).catch(()=>null)),Qt}function Bs({orderId:i,onSuccess:a,onError:u,amount:x,currency:h}){const g=us(),p=xs(),[o,n]=r.useState(!1),[y,k]=r.useState(!1),f=async()=>{if(!(!g||!p)){n(!0);try{const{error:P,paymentIntent:I}=await g.confirmPayment({elements:p,redirect:"if_required",confirmParams:{return_url:window.location.href}});if(P){let L="Erro ao processar pagamento.";(P.type==="card_error"||P.type==="validation_error")&&(L=P.message||L),u(L),n(!1)}else I&&I.status==="succeeded"?a():(u("Pagamento não foi concluído. Tente novamente."),n(!1))}catch{u("Erro inesperado. Tente novamente."),n(!1)}}};return e.jsxs("div",{className:"animate-in fade-in slide-in-from-top-2 space-y-4",children:[e.jsxs("div",{className:"relative rounded-2xl overflow-hidden","data-testid":"page-cover-card-black-design",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-gray-800 via-gray-900 to-black"}),e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top_right,rgba(45,212,191,0.08),transparent_60%)]"}),e.jsx("div",{className:"absolute top-0 left-0 right-0 h-px bg-gradient-to-r from-transparent via-white/20 to-transparent"}),e.jsxs("div",{className:"relative p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-8 h-6 rounded bg-gradient-to-br from-yellow-400 via-yellow-500 to-yellow-600 flex items-center justify-center",children:e.jsx(Ns,{className:"w-3.5 h-3.5 text-yellow-900 rotate-90"})}),e.jsx("span",{className:"text-[10px] text-white/40 uppercase tracking-widest font-medium",children:"Premium"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Sa,{className:"w-3 h-3 text-primary/60"}),e.jsx("span",{className:"text-[10px] text-primary/60 uppercase tracking-wider",children:"Seguro"})]})]}),e.jsx("div",{className:"pt-1",children:e.jsx(ps,{onReady:()=>k(!0),options:{layout:"tabs"}})})]})]}),e.jsx(T,{onClick:f,disabled:o||!g||!p||!y,className:"w-full h-12 text-base rounded-xl bg-primary hover:bg-primary/90 text-white font-semibold shadow-lg shadow-primary/20 hover:shadow-primary/40 transition-all","data-testid":"button-page-cover-pay-card",children:o?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(C,{className:"w-5 h-5 animate-spin"}),e.jsx("span",{children:"Processando..."})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ht,{className:"w-4 h-4"}),e.jsxs("span",{children:["Pagar"," ",h?hs(Math.round(x*100),fs(h)):`R$ ${x.toFixed(2).replace(".",",")}`]})]})}),e.jsxs("div",{className:"flex items-center justify-center gap-4 text-[10px] text-muted-foreground/60",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Sa,{className:"w-3 h-3"}),e.jsx("span",{children:"Criptografia SSL"})]}),e.jsx("span",{children:"•"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ht,{className:"w-3 h-3"}),e.jsx("span",{children:"Processado por Stripe"})]})]})]})}const Ms={theme:"night",variables:{colorPrimary:"#2dd4bf",colorBackground:"transparent",colorText:"#e4e4e7",colorTextPlaceholder:"#52525b",colorDanger:"#ef4444",fontFamily:"system-ui, -apple-system, sans-serif",borderRadius:"10px",spacingUnit:"4px",fontSizeBase:"14px"},rules:{".Input":{backgroundColor:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.12)",boxShadow:"none",padding:"12px 14px",fontSize:"15px",transition:"border-color 0.2s ease"},".Input:focus":{border:"1px solid rgba(45,212,191,0.5)",boxShadow:"0 0 0 2px rgba(45,212,191,0.15)"},".Input::placeholder":{color:"#52525b"},".Label":{color:"#a1a1aa",fontSize:"12px",fontWeight:"500",textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:"6px"},".Tab":{backgroundColor:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.1)",color:"#a1a1aa",borderRadius:"10px"},".Tab--selected":{backgroundColor:"rgba(45,212,191,0.1)",border:"1px solid rgba(45,212,191,0.3)",color:"#2dd4bf"},".Tab:hover":{backgroundColor:"rgba(255,255,255,0.08)",border:"1px solid rgba(255,255,255,0.15)",color:"#e4e4e7"},".Error":{color:"#ef4444",fontSize:"12px"}}};function Ot({selected:i,onClick:a,image:u,label:x,desc:h,testId:g}){return e.jsxs("button",{type:"button",onClick:a,"data-testid":g,className:`relative overflow-hidden rounded-xl border text-left transition-all duration-200 aspect-[4/3] ${i?"border-primary ring-2 ring-primary/30 shadow-lg shadow-primary/10":"border-white/10 hover:border-white/20"}`,children:[e.jsx("img",{src:u,alt:x,className:"absolute inset-0 w-full h-full object-cover",loading:"lazy"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/90 via-black/40 to-transparent"}),i&&e.jsx("div",{className:"absolute inset-0 bg-primary/15"}),e.jsxs("div",{className:"absolute bottom-0 left-0 right-0 p-3",children:[e.jsx("p",{className:`text-base font-bold leading-tight ${i?"text-primary":"text-white"}`,children:x}),h&&e.jsx("p",{className:"text-xs text-zinc-400 mt-0.5 leading-snug",children:h})]})]})}function Us({selected:i,onClick:a,color:u,label:x,testId:h}){return e.jsxs("button",{type:"button",onClick:a,"data-testid":h,className:`relative flex flex-col items-center gap-2 p-3 rounded-xl border transition-all duration-200 ${i?"border-primary ring-2 ring-primary/30 shadow-lg shadow-primary/10":"border-white/10 bg-white/5 hover:bg-white/10 hover:border-white/20"}`,children:[e.jsx("div",{className:"w-10 h-10 rounded-full border-2 border-white/20 shadow-inner",style:{backgroundColor:u}}),e.jsx("p",{className:`text-sm font-medium ${i?"text-primary":"text-white"}`,children:x})]})}
1function _s(i,a){return!i||typeof i!="string"?i:i.startsWith("/api/covers/image/")||i.startsWith("/generated-covers/")?`${i}${i.includes("?")?"&":"?"}w=${a}`:i}function Dt({src:i,alt:a,className:u,thumbWidth:x,...h}){const[g,p]=r.useState(!1),[o,n]=r.useState(i);if(i!==o&&(n(i),p(!1)),g||!i)return e.jsx("div",{className:`flex items-center justify-center bg-gradient-to-b from-white/5 to-white/[0.02] ${u||""}`,...h,children:e.jsxs("div",{className:"flex flex-col items-center gap-2 text-center p-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-white/5 flex items-center justify-center",children:e.jsx(Wt,{className:"w-6 h-6 text-muted-foreground/50"})}),e.jsx("span",{className:"text-xs text-muted-foreground/60",children:a||"Capa indisponível"})]})});const y=x?_s(typeof i=="string"?i:void 0,x):i;return e.jsx("img",{src:y,alt:a,className:u,onError:()=>p(!0),loading:"lazy",decoding:"async",...h})}const At=i=>i?.batchId||i?.id||null;function qs({coverId:i,bookId:a,bookTitle:u,onNewCover:x,onPaymentSuccess:h}){const[g,p]=r.useState(""),[o,n]=r.useState(!1),[y,k]=r.useState(null),[f,P]=r.useState(null),[I,L]=r.useState(!1),[M,l]=r.useState(!1),[v,Ve]=r.useState(!1),[$,de]=r.useState(!1),[je,me]=r.useState(!1),[Q,J]=r.useState(!1),[S,c]=r.useState(null),{structuredDislike:R}=Ba(),{toast:j}=Xt(),{user:X}=Ia(),{fmtPrice:w}=Ra(X),ue=r.useRef(null),oe=r.useRef(null),xe=r.useRef(null),ie=r.useRef(!1),Z=Zt(),{data:pe}=ce({queryKey:[`/api/books/${a}/cover-adjustment-info`],enabled:!!a,refetchInterval:d=>{const O=d.state.data,fe=O?.activeBatch||O?.latestBatch;return $||fe&&["running","partial","generating"].includes(fe.status||"")?5e3:!1}}),Bt=pe?.isFreeAvailable??!1,ae=pe?.price??19.99,N=pe?.activeBatch||pe?.latestBatch,z=N?.status,he=N?.completed??0,Re=N?.target??N?.targetCount??2,Ye=["running","partial","generating"].includes(z||""),Oe=pe?.reviewNeeded===!0,Mt=z==="reviewed"&&Re===2;r.useEffect(()=>{z&&!Ye&&de(!1)},[z,Ye]);const{data:we,refetch:De}=ce({queryKey:[`/api/covers/${i}/chat`],enabled:!!i});r.useEffect(()=>{if(!N)return;Z.invalidateQueries({queryKey:[`/api/books/${a}/covers`]}),De();const d=At(N),O=z==="completed"||z==="awaiting_review";if(!ie.current){ie.current=!0,O&&d&&(xe.current=d);return}const fe=he>=Re&&(N.coverIds?.length||0)>=Re;O&&fe&&d&&xe.current!==d&&(xe.current=d,x())},[N,z,he,Re,a,x,Z,De]),r.useEffect(()=>{ue.current?.scrollIntoView({behavior:"smooth"})},[we,o,I,y]);const ye=async d=>{const O=d.target.files?.[0];if(O){if(!O.type.startsWith("image/")){j({title:"Formato inválido",description:"Envie uma imagem (JPG, PNG ou WebP).",variant:"destructive"});return}if(O.size>10*1024*1024){j({title:"Arquivo muito grande",description:"O tamanho máximo é 10MB.",variant:"destructive"});return}J(!0);try{const fe=new FormData;fe.append("photo",O);const W=await fetch(`/api/books/${a}/upload-author-photo`,{method:"POST",body:fe,credentials:"include"});if(!W.ok)throw new Error("Upload falhou");const Ne=await W.json();P(Ne.url||Ne.imageUrl),j({title:"Imagem anexada!",description:"A imagem será usada como referência para o ajuste."})}catch{j({title:"Erro no upload",description:"Não foi possível enviar a imagem. Tente novamente.",variant:"destructive"})}finally{J(!1),oe.current&&(oe.current.value="")}}},Ge=async()=>{if(!g.trim()&&!f||o)return;const d=f?`${g.trim()||"Use esta imagem como referência para o ajuste da capa."} [Imagem de referência anexada: ${f}]`:g.trim();p(""),k(d.replace(/\[Imagem de referência anexada:.*\]/,"").trim()||"Imagem de referência enviada"),n(!0),P(null);try{await Y("POST",`/api/covers/${i}/chat`,{message:d}),await De(),k(null)}catch(O){k(null),j({title:"Erro ao enviar mensagem",description:O.message||"Tente novamente.",variant:"destructive"})}finally{n(!1)}},Ae={title:`Ajuste de capa — "${u&&u.length>30?u.slice(0,30)+"…":u||"seu livro"}"`,price:ae,originalPrice:wt(ae),description:"A SÁBHIA cria 2 novas variações da sua capa incorporando todos os ajustes que você pediu.",subtitle:"Design por SÁBHIA",features:["2 novas versões de capa profissionais","Todos os seus ajustes aplicad
1os","Título e autor renderizados na imagem","Pronto para publicação digital"]},Be=d=>{de(!0),L(!1),j({title:"Pagamento confirmado!",description:"Suas 2 novas capas estão sendo criadas. Aguarde alguns minutos."}),De(),h?.(),Z.invalidateQueries({queryKey:[`/api/books/${a}/cover-adjustment-info`]}),Z.invalidateQueries({queryKey:[`/api/books/${a}/covers`]})},st=async()=>{if(!(!At(N)||v)){Ve(!0);try{await Y("POST",`/api/covers/${i}/adjustment-review`,{orderId:N?.orderId}),await Z.invalidateQueries({queryKey:[`/api/books/${a}/cover-adjustment-info`]}),j({title:"Opções revisadas",description:"Quando quiser, você pode gerar mais 2 opções."})}catch(O){j({title:"Não foi possível registrar a revisão",description:O.message||"Tente novamente.",variant:"destructive"})}finally{Ve(!1)}}},Me=async()=>{const d=At(N);if(!(M||!d)){l(!0);try{await Y("POST",`/api/covers/${i}/generate-more-2`,{orderId:N?.orderId}),de(!0),j({title:"Novas opções a caminho!",description:"Estamos criando mais 2 capas para você."}),h?.(),Z.invalidateQueries({queryKey:[`/api/books/${a}/cover-adjustment-info`]}),Z.invalidateQueries({queryKey:[`/api/books/${a}/covers`]})}catch(O){j({title:"Não foi possível gerar mais opções",description:O.message||"Tente novamente.",variant:"destructive"})}finally{l(!1)}}},yt=async()=>{if(!je){me(!0);try{const d=[...we||[]].reverse().find(W=>W.role==="user")?.content||"";(await(await Y("POST",`/api/covers/${i}/free-adjustment`,{dislikeCategory:S||void 0,dislikeNote:d?String(d).slice(0,1e3):void 0})).json()).orderId&&(de(!0),j({title:"Correção gratuita iniciada!",description:"Suas 2 novas capas estão sendo criadas. Aguarde alguns minutos."}),De(),h?.(),Z.invalidateQueries({queryKey:[`/api/books/${a}/cover-adjustment-info`]}),Z.invalidateQueries({queryKey:[`/api/books/${a}/covers`]}))}catch(d){j({title:"Erro",description:d.message||"Não foi possível iniciar a correção gratuita.",variant:"destructive"})}finally{me(!1)}}};return e.jsxs("div",{className:"flex flex-col h-full min-h-0","data-testid":"section-cover-chat",children:[e.jsxs("div",{className:"p-3 border-b border-white/5 flex items-center gap-2 shrink-0",children:[e.jsx("div",{className:"w-7 h-7 rounded-lg bg-primary/20 flex items-center justify-center",children:e.jsx(F,{className:"w-3.5 h-3.5 text-primary"})}),e.jsx("h3",{className:"text-xs font-bold text-white",children:"Ajustar Capa"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-2.5 min-h-0 max-h-[350px]",children:[(!we||we.length===0)&&!o&&!y&&e.jsxs("div",{className:"text-center py-4",children:[e.jsx(Ua,{className:"w-7 h-7 text-muted-foreground/30 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Conte o que gostaria de mudar na sua capa."}),e.jsxs("p",{className:"text-[11px] text-muted-foreground/60 mt-1 leading-relaxed",children:["Vá adicionando tudo que deseja e quando",e.jsx("br",{}),"estiver pronto, gere 2 opções de capa."]})]}),(we||[]).map(d=>e.jsx("div",{className:`flex ${d.role==="user"?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[85%] rounded-2xl px-3.5 py-2 ${d.role==="user"?"bg-primary/20 text-white":"bg-white/5 text-gray-300"}`,"data-testid":`chat-message-${d.id}`,children:[e.jsx("p",{className:"text-sm",children:d.content}),d.imageUrl&&e.jsx("div",{className:"mt-2",children:e.jsx(Dt,{src:d.imageUrl,alt:"Nova capa",className:"w-28 aspect-[5/8] rounded-lg object-cover border border-white/10","data-testid":`chat-cover-image-${d.id}`})})]})},d.id)),y&&e.jsx("div",{className:"flex justify-end",children:e.jsx("div",{className:"max-w-[85%] rounded-2xl px-3.5 py-2 bg-primary/20 text-white",children:e.jsx("p",{className:"text-sm",children:y})})}),o&&e.jsx("div",{className:"flex justify-start",children:e.jsxs("div",{className:"bg-white/5 rounded-2xl px-3.5 py-2.5 flex items-center gap-2",children:[e.jsx(C,{className:"w-3.5 h-3.5 animate-spin text-primary"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"SÁBHIA está pensando..."})]})}),($||Ye)&&e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"bg-primary/10 border border-primary/20 rounded-2xl px-3.5 py-2.5",children:e.jsxs("p",{className:"text-sm text-primary font-medium",children:["Criando opções de capa (",he,"/",Re,"). Elas aparecerão na galeria assim que ficarem prontas."]})})}),e.jsx("div",{ref:ue})]}),!$&&!Ye&&e.jsx("div",{className:"px-3 py-2 border-t border-white/5 shrink-0",children:z==="failed"?e.jsxs("div",{className:"p-3 rounded-lg bg-red-500/10 border border-red-500/20 text-center","data-testid":"banner-adjustment-failed",children:[e.jsx("p",{className:"text-[12px] font-bold text-red-300",children:"Não foi possível concluir todas as opções"}),e.jsx("p",{className:"text-[10px] text-red-200/60 mt-1",children:"O time foi avisado automaticamente. Você não será cobrado novamente por este lote."})]}):Oe?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"p-2 rounded-lg bg-amber-500/10 border border-amber-500/20 text-center","data-testid":"banner-adjustment-review-needed",children:[e.jsx("p",{className:"text-[12px] font-bold text-amber-300",children:"Revise as 2 opções antes de pedir novas"}),e.jsx("p",{className:"text-[10px] text-amber-200/60 mt-1",children:"Isso ajuda a manter o próximo ajuste focado no que você quer."})]}),e.jsxs(T,{onClick:st,disabled:v,variant:"outline",className:"w-full h-9 border-amber-400/30 text-amber-200 hover:bg-amber-400/10","data-testid":"button-review-adjustment-options",children:[v?e.jsx(C,{className:"w-4 h-4 animate-spin mr-2"}):e.jsx(Ie,{className:"w-4 h-4 mr-2"}),"Revisei as 2 opções"]})]}):Mt?e.jsxs(T,{onClick:Me,disabled:M,className:"w-full h-10 rounded-xl bg-primary hover:bg-primary/90 text-white font-semibold shadow-lg shadow-primary/20 text-sm","data-testid":"button-generate-more-adjustment-options",children:[M?e.jsx(C,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(F,{className:"w-4 h-4 mr-2"}),"Gerar mais 2"]}):Bt?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-2 p-2 rounded-lg bg-emerald-500/10 border border-emerald-500/20","data-testid":"banner-free-correction",children:[e.jsxs("div",{className:"flex items-center gap-2 justify-center",children:[e.jsx("div",{className:"w-5 h-5 rounded-full bg-emerald-500/20 flex items-center justify-center",children:e.jsx(Ie,{className:"w-3 h-3 text-emerald-400"})}),e.jsx("span",{className:"text-[12px] font-bold text-emerald-400",children:"1 Correção Grátis Disponível"})]}),e.jsxs("p",{className:"text-[10px] text-emerald-400/60 text-center mt-1",children:["Sua primeira correção cria 2 opções por nossa conta. A partir da segunda, ",w(ae),"."]})]}),R&&e.jsxs("div",{className:"mb-2","data-testid":"section-dislike-reason",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground
1/70 mb-1.5 text-center",children:"O que não ficou bom? (opcional — ajuda a acertar na próxima)"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 justify-center",children:[{value:"style",label:"Estilo/visual"},{value:"colors",label:"Cores"},{value:"text_rendering",label:"Texto/título"},{value:"subject",label:"Imagem errada"},{value:"genre_mismatch",label:"Não combina com o livro"},{value:"quality",label:"Qualidade baixa"}].map(d=>e.jsx("button",{type:"button",onClick:()=>c(S===d.value?null:d.value),className:`px-2 py-1 rounded-full text-[10px] font-medium border transition-colors ${S===d.value?"bg-emerald-500/25 border-emerald-400/60 text-emerald-300":"bg-white/5 border-white/10 text-muted-foreground hover:border-emerald-400/30"}`,"data-testid":`chip-dislike-${d.value}`,children:d.label},d.value))})]}),e.jsx(T,{onClick:yt,disabled:je,className:"w-full h-10 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-semibold shadow-lg shadow-emerald-600/20 text-sm","data-testid":"button-free-adjustment",children:e.jsxs("div",{className:"flex items-center gap-2",children:[je?e.jsx(C,{className:"w-4 h-4 animate-spin"}):e.jsx(F,{className:"w-4 h-4"}),e.jsx("span",{children:"Gerar 2 Opções Grátis"})]})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-[11px] text-muted-foreground/70 text-center mb-2 leading-snug",children:[e.jsx("span",{className:"text-white/40 line-through",children:w(wt(ae))})," ",e.jsx("span",{className:"font-extrabold text-emerald-400",children:w(ae)})," para produzir 2 opções de capa com seus ajustes."," ",e.jsx("span",{className:"inline-flex items-center gap-1 text-[10px] px-2 py-0.5 rounded-full bg-amber-500/15 border border-amber-500/30 text-amber-400 font-semibold",children:"Oferta de lançamento"})]}),e.jsx(T,{onClick:()=>L(!0),className:"w-full h-10 rounded-xl bg-primary hover:bg-primary/90 text-white font-semibold shadow-lg shadow-primary/20 text-sm","data-testid":"button-pay-adjustment",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Da,{className:"w-4 h-4"}),e.jsxs("span",{children:["Pagar 2 Opções ",e.jsx("span",{className:"text-white/40 line-through text-xs",children:w(wt(ae))})," ",w(ae)]})]})})]})}),e.jsx(Aa,{open:I,onOpenChange:L,product:Ae,onConfirm:Be,bookId:a,bookTitle:u,orderType:"cover_adjustment",metadata:{coverId:i}}),!$&&e.jsxs("div",{className:"p-2.5 border-t border-white/5 shrink-0",children:[f&&e.jsxs("div",{className:"flex items-center gap-2 mb-2 bg-white/5 rounded-lg p-2","data-testid":"pending-image-preview",children:[e.jsx("img",{src:f,alt:"Referência",className:"w-10 h-10 rounded object-cover border border-white/20"}),e.jsx("span",{className:"text-xs text-muted-foreground flex-1",children:"Imagem de referência anexada"}),e.jsx("button",{onClick:()=>P(null),className:"text-muted-foreground hover:text-white transition-colors","data-testid":"button-remove-pending-image",children:e.jsx(Yt,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"file",ref:oe,accept:"image/*",className:"hidden",onChange:ye,"data-testid":"input-cover-chat-image"}),e.jsx("button",{onClick:()=>oe.current?.click(),disabled:o||Q,className:"shrink-0 w-9 h-9 flex items-center justify-center rounded-xl bg-white/5 border border-white/10 text-muted-foreground hover:text-white hover:border-primary/40 transition-colors disabled:opacity-40",title:"Anexar imagem de referência","data-testid":"button-attach-image-chat",children:Q?e.jsx(C,{className:"w-4 h-4 animate-spin"}):e.jsx(Ma,{className:"w-4 h-4"})}),e.jsx("input",{type:"text",value:g,onChange:d=>p(d.target.value),onKeyDown:d=>d.key==="Enter"&&!d.shiftKey&&Ge(),placeholder:"Descreva o ajuste desejado...",className:"flex-1 bg-white/5 border border-white/10 rounded-xl px-3.5 py-2 text-sm text-white placeholder:text-muted-foreground focus:outline-none focus:border-primary/50",disabled:o,"data-testid":"input-cover-chat"}),e.jsx(T,{onClick:Ge,disabled:!g.trim()&&!f||o,className:"rounded-xl px-3.5","data-testid":"button-send-cover-chat",children:o?e.jsx(C,{className:"w-4 h-4 animate-spin"}):e.jsx(Oa,{className:"w-4 h-4"})})]})]})]})}function gr(){const[,i]=ss("/capas/:bookId"),a=i?.bookId,[,u]=rs(),{user:x}
1=Ia(),{resolvedCurrency:h,allowPix:g,fmtPrice:p}=Ra(x),o=Zt(),{toast:n}=Xt(),{t:y}=vs("pipeline"),[k,f]=r.useState(2),[P,I]=r.useState(null),[L,M]=r.useState(!1),[l,v]=r.useState({style:"",colorMood:"",mainElement:"",fontStyle:"",fontColor:"",freeText:"",avoidText:"",authorPhotoUrl:""}),[Ve,$]=r.useState(""),[de,je]=r.useState(!1),me=r.useRef(null),[Q,J]=r.useState(!1),[S,c]=r.useState(null),[R,j]=r.useState(null),[X,w]=r.useState(null),[ue,oe]=r.useState(null),[xe,ie]=r.useState(!1),[Z,pe]=r.useState(!1),[Bt,ae]=r.useState(null),[N,z]=r.useState(!1),[he,Re]=r.useState(0),[Ye,Oe]=r.useState(!1),[Mt,we]=r.useState(!1),[De,ye]=r.useState(null),[Ge,Ae]=r.useState(null),[Be,st]=r.useState(null),[Me,yt]=r.useState(!1),[d,O]=r.useState(!1),[fe,W]=r.useState(!1),[Ne,Ut]=r.useState(!1),[Ce,ea]=r.useState(!1),Je=r.useRef(null),Ue=r.useRef(null),rt=r.useRef(null),ot=r.useRef(null),_e=r.useRef(null),ke=r.useRef(0),Se=r.useRef(null),[Nt,Ct]=r.useState(0),ta=r.useRef(0),it=r.useRef(null),ge=r.useCallback(()=>{rt.current&&clearInterval(rt.current),it.current&&clearInterval(it.current),ot.current&&clearTimeout(ot.current),_e.current?.abort(),rt.current=null,it.current=null,ot.current=null,_e.current=null,Se.current=null,ke.current+=1},[]),{data:E,isLoading:_t,refetch:nt}=ce({queryKey:[`/api/books/${a}`],enabled:!!a}),{data:aa}=ce({queryKey:[`/api/books/${a}/next-upsell`],enabled:!!a,staleTime:1e4,refetchInterval:15e3}),be=aa?.pipeline?.find(t=>t.step==="cover"),sa=be?.purchased&&!be?.done&&(be?.awaitingUser||be?.pipelineStep==="awaiting_user"),_a=be?.purchased&&!be?.done&&!sa&&(be?.generating||be?.pipelineStep==="pending"),Pe=r.useRef(void 0);r.useEffect(()=>{Pe.current=be},[be]);const{data:qa}=ce({queryKey:["/api/services"]}),Fa=(qa||[]).find(t=>t.type==="cover_ebook"),{data:kt,refetch:U}=ce({queryKey:[`/api/books/${a}/covers`],enabled:!!a}),{data:ra,refetch:oa}=ce({queryKey:[`/api/books/${a}/cover-adjustment-info`],enabled:!!a,refetchInterval:t=>{const s=t.state.data,m=s?.activeBatch||s?.latestBatch;return m&&["running","partial","generating"].includes(m.status||"")?5e3:!1}}),$e=ra?.activeBatch||ra?.latestBatch,St=["running","partial","generating"].includes($e?.status||""),qe=$e?.target??$e?.targetCount??2,Ke=$e?.completed??0,lt=$e?.coverIds||[],ia=new Set(lt.slice(-2)),na=At($e);r.useEffect(()=>{St&&U()},[St,Ke,U]);const{data:se,refetch:Qe}=ce({queryKey:[`/api/books/${a}/cover-entitlement`],enabled:!!a,staleTime:5e3,refetchInterval:15e3}),La=new Set(se?.activeCoverIds||[]),Pt=String(E?.coverImage||"").trim(),za=Pt?(kt||[]).find(t=>String(t?.imageUrl||"").trim()===Pt):null,Va=Pt?{...za||{id:`canonical-${a}`,imageUrl:Pt,style:"Capa publicada",readOnlyCanonical:!0},selected:!0}:null,V=Is(kt||[],La,!!se?.policy.deliverable,Va,lt),Xe=Rs(lt,V,qe),$t=$e?.status==="completed"||$e?.status==="awaiting_review",Et=$t&&Ke>=qe&&Xe.complete;r.useEffect(()=>{if(!$t||Et)return;let t=0,s=null;const m=()=>{t+=1,Promise.allSettled([U(),oa()]),t>=24&&(s&&clearInterval(s),console.error("[COVER_ADJUSTMENT_VISIBILITY] Terminal batch is not fully visible",{bookId:a,batchId:na,completed:Ke,target:qe,persistedResultIds:lt.length,visibleResultIds:Xe.visible,missingResultCount:Xe.missingIds.length}))};return m(),s=setInterval(m,5e3),()=>{s&&clearInterval(s)}},[$t,Et,na,Ke,qe,lt.length,Xe.visible,Xe.missingIds.length,a,U,oa]);const re=se?.targetCount||4,{data:ct}=ce({queryKey:[`/api/books/${a}/access-status`],enabled:!!a,refetchInterval:6e4}),{data:qt}=ce({queryKey:[`/api/books/${a}/translations`],enabled:!!a}),{data:Ft}=ce({queryKey:[`/api/books/${a}/chapters`],enabled:!!a});r.useEffect(()=>{a&&(yt(!0),Y("GET","/api/credits/balance").then(t=>t.json()).then(t=>st(t.balance??0)).catch(()=>st(0)).finally(()=>yt(!1)))},[a]);const H=E?.title||"",dt=E?.genre||"",mt=E?.planData?.synopsis||"",G=vt.cover,Fe=Fa?.type??"cover_ebook",ut=V&&V.length>0,la=V?.find(t=>t.selected)?.id||V?.[0]?.id,A=De&&V?.find(t=>t.id===De)||null,Ga=H&&H.length>45?H.slice(0,45)+"…":H||"seu livro",ca=at.find(t=>t.id===l.style)?.label||l.style,da=Vt.find(t=>t.id===l.colorMood)?.label||l.colorMood,ma=Gt.find(t=>
1t.id===l.fontStyle)?.label||"",ua=Kt.find(t=>t.id===l.fontColor)?.label||"",xt=P||{greeting:`Que projeto incrível, "${H||"seu livro"}"! ${dt?`Um livro de ${dt} merece uma capa à altura.`:"Seu livro merece uma capa que conquiste leitores à primeira vista."} Vamos criar algo especial para você.`,whatWeWillDo:`A SÁBHIA vai analisar o conteúdo do seu livro, combinar com o estilo ${ca} e a paleta de ${da} que você escolheu, e criar 4 capas profissionais únicas. Cada capa será pensada para destacar "${H||"seu livro"}" nas prateleiras digitais da Amazon, Apple Books, Google Play e Kobo.`,valueItems:[`4 capas exclusivas criadas especialmente para "${H||"seu livro"}"`,`Estilo ${ca} com paleta de ${da}${ma?`, fonte ${ma}`:""}${ua?` em ${ua}`:""}`,"Título e nome do autor renderizados com tipografia profissional","Resolução HD pronta para Amazon KDP (1600×2560)","Baseada no conteúdo e na essência do seu livro","Download em alta resolução ilimitado","Compatível com todas as plataformas de publicação","Entrega em minutos, não semanas"],designerComparison:"Designers tradicionais cobram entre R$ 500 e R$ 2.000 por uma única capa — e levam semanas para entregar.",closingPitch:"Capa profissional em minutos. Se não amar o resultado, geramos novamente."},Le={coverBrief:{style:l.style,colorMood:l.colorMood,mainElement:l.mainElement||void 0,fontStyle:l.fontStyle||void 0,fontColor:l.fontColor||void 0,freeText:l.freeText||void 0,avoidText:l.avoidText||void 0,authorPhotoUrl:l.authorPhotoUrl||void 0},coverRegenerate:se?.complete?!0:void 0},xa=r.useCallback(async t=>{if(a){if(!t.type.startsWith("image/")){n({title:"Formato inválido",description:"Envie uma imagem (JPG, PNG, WebP).",variant:"destructive"});return}if(t.size>10*1024*1024){n({title:"Arquivo muito grande",description:"O tamanho máximo é 10MB.",variant:"destructive"});return}je(!0);try{const s=URL.createObjectURL(t);$(s);const m=new FormData;m.append("photo",t);const b=await fetch(`/api/books/${a}/upload-author-photo`,{method:"POST",credentials:"include",body:m});if(!b.ok){const D=await b.json().catch(()=>({}));throw new Error(D.message||"Erro ao enviar foto")}const _=await b.json();v(D=>({...D,authorPhotoUrl:_.url})),n({title:"Foto enviada com sucesso!"})}catch(s){$(""),v(m=>({...m,authorPhotoUrl:""})),n({title:"Erro ao enviar foto",description:s.message||"Tente novamente.",variant:"destructive"})}finally{je(!1)}}},[a,n]),Ka=r.useCallback(()=>{$(""),v(t=>({...t,authorPhotoUrl:""})),me.current&&(me.current.value="")},[]),pt=l.style!==""&&l.colorMood!=="";r.useEffect(()=>{E&&x&&E.userId!==x.id&&x.role!=="admin"&&(n({title:"Acesso negado",description:"Este livro não pertence a você.",variant:"destructive"}),u("/dashboard"))},[E,x]),r.useEffect(()=>{!_t&&!E&&a&&(n({title:"Livro não encontrado",variant:"destructive"}),u("/dashboard"))},[_t,E,a]),r.useEffect(()=>{if(!a||!se||!E||!kt||d||N||!se.canGenerate||se.needsReconciliation)return;if(se.complete){W(!1);return}O(!0),z(!0);const t=0;Re(0),ie(!0),fetch(`/api/books/${a}/generate-covers`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"}}).catch(ee=>{console.error(`[COVER_RECOVERY] Failed to resume generation for book ${a}:`,ee)});const s=se.targetCount,m=Date.now();ta.current=m,Ct(0),ge();const b=ke.current;it.current=setInterval(()=>{Ct(Math.floor((Date.now()-m)/1e3))},1e3);const _=1200*1e3;let D=t,q=0;ot.current=setTimeout(()=>{ke.current===b&&(console.error(`[COVER_RECOVERY_POLL] Watchdog stopped cover recovery after ${_/6e4} minutes for book ${a}`),ge(),z(!1),W(!0),Oe(!1),ie(!1),Promise.allSettled([U(),Qe(),nt()]))},_),rt.current=setInterval(async()=>{if(ke.current!==b||Se.current!==null)return;Se.current=b;const ee=new AbortController;_e.current=ee;const K=setTimeout(()=>ee.abort(),15e3);try{const B=await fetch(`/api/books/${a}/cover-entitlement`,{credentials:"include",cache:"no-store",signal:ee.signal});if(!B.ok){console.warn(`[COVER_RECOVERY_POLL] Entitlement poll failed with HTTP ${B.status} for book ${a}; retrying.`);return}const te=await B.json(),ne=te.currentCount||0;if(await U(),await Qe(),ke.current!==b)return;ne===D?q++:(q=0,D=ne);const We=ne-t,ve=!!Pe.current&&Pe.current.purchased&&!Pe.current.generating&&Pe.current.pipelineStep!=="pending",Ze=Date.now()-m<6e4,It=We>=1&&q>=30&&!Ze,He=q>=18&&We===0&&ve&&!Ze,Lt=te.complete||ne>=s,et=!1;if(Lt||It||He){ge(),z(!1);let le=We;if(le===0&&(He||et))try{const Ee=await fetch(`/api/books/${a}/cover-entitlement?_=${Date.now()}`,{credentials:"include",cache:"no-store"});if(Ee.ok){const gt=(await Ee.json()).currentCount||0;gt>t&&(le=gt-t,console.log(`[COVER_RECOVERY_POLL] Defensive refetch recovered ${le}
1 covers — clearing failed state.`))}}catch(Ee){console.error(`[COVER_RECOVERY_POLL] Defensive entitlement refetch failed for book ${a}:`,Ee)}(et||He)&&le===0&&W(!0),Oe(!1),ie(!1),await U(),o.invalidateQueries({queryKey:[`/api/books/${a}`]})}}catch(B){const te=B instanceof DOMException&&B.name==="AbortError"?"request timed out":B;console.error(`[COVER_RECOVERY_POLL] Poll failed for book ${a}; retrying:`,te)}finally{clearTimeout(K),_e.current===ee&&(_e.current=null),Se.current===b&&(Se.current=null)}},5e3)},[a,se,E,kt,d,N,o,U,Qe,nt,ge]);const ht=r.useCallback(()=>{if(!a)return;ge();const t=ke.current;z(!0),W(!1);const s=0;Re(0);const m=Date.now();ta.current=m,Ct(0);const b=1200*1e3;it.current=setInterval(()=>{Ct(Math.floor((Date.now()-m)/1e3))},1e3);let _=s,D=0;ot.current=setTimeout(()=>{ke.current===t&&(console.error(`[COVER_POLL] Watchdog stopped cover polling after ${b/6e4} minutes for book ${a}`),ge(),z(!1),W(!0),Oe(!1),ie(!1),Promise.allSettled([U(),Qe(),nt()]))},b),rt.current=setInterval(async()=>{if(ke.current!==t||Se.current!==null)return;Se.current=t;const q=new AbortController;_e.current=q;const ee=setTimeout(()=>q.abort(),15e3);try{const K=await fetch(`/api/books/${a}/cover-entitlement`,{credentials:"include",cache:"no-store",signal:q.signal});if(!K.ok){console.warn(`[COVER_POLL] Entitlement poll failed with HTTP ${K.status} for book ${a}; retrying.`);return}const B=await K.json(),te=B.currentCount||0,ne=B.targetCount||re;if(await U(),await Qe(),ke.current!==t)return;te===_?D++:(D=0,_=te);const We=te-s,ve=!!Pe.current&&Pe.current.purchased&&!Pe.current.generating&&Pe.current.pipelineStep!=="pending",ft=Date.now()-m,Ze=ft<6e4,It=We>=1&&D>=30&&!Ze,He=D>=18&&We===0&&ve&&!Ze,Lt=B.complete||te>=ne,et=!1;if(Lt||It||He){ge(),z(!1);let le=te-s;if(le===0&&(He||et))try{const Ee=await fetch(`/api/books/${a}/cover-entitlement?_=${Date.now()}`,{credentials:"include",cache:"no-store"});if(Ee.ok){const gt=(await Ee.json()).currentCount||0;gt>s&&(le=gt-s,console.log(`[COVER_POLL] Defensive refetch recovered ${le}/4 covers — clearing failed state.`),await U())}}catch(Ee){console.error(`[COVER_POLL] Defensive entitlement refetch failed for book ${a}:`,Ee)}console.log(`[COVER_POLL] Generation complete: ${le}/${ne} covers generated (timeout=${et}, partialDone=${It}, stuck=${He}, elapsed=${Math.floor(ft/1e3)}s)`),le===0?(console.error(`[COVER_POLL] 0 covers generated — generation failed entirely for book ${a}`),W(!0)):et&&le<ne,Oe(!1),f(2),ie(!1),c(null),j(null),w(null),oe(null),v({style:"",colorMood:"",mainElement:"",freeText:"",avoidText:"",fontStyle:"",fontColor:"",authorPhotoUrl:""}),$(""),await U(),o.invalidateQueries({queryKey:[`/api/books/${a}`]})}}catch(K){const B=K instanceof DOMException&&K.name==="AbortError"?"request timed out":K;console.error(`[COVER_POLL] Poll failed for book ${a}; retrying:`,B)}finally{clearTimeout(ee),_e.current===q&&(_e.current=null),Se.current===t&&(Se.current=null)}},5e3)},[a,re,o,U,Qe,nt,ge]),pa=r.useCallback(async()=>{if(!(!a||Ne)){Ut(!0),W(!1);try{const t=await fetch(`/api/books/${a}/generate-covers`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"}});if(!t.ok){const s=await t.json();n({title:"Erro",description:s.message||"Não foi possível iniciar a geração",variant:"destructive"}),W(!0),Ut(!1);return}ht()}catch{n({title:"Erro",description:"Erro de conexão. Tente novamente.",variant:"destructive"}),W(!0)}Ut(!1)}},[a,Ne,n,ht]);r.useEffect(()=>()=>{Ue.current&&clearInterval(Ue.current),Ue.current=null,ge()},[a,ge]);const ze=r.useCallback(()=>{ie(!0),n({title:"Pagamento confirmado!",description:"Sua capa está sendo gerada."}),ht()},[n,ht]),Qa=r.useCallback(()=>{o.invalidateQueries({queryKey:[`/api/books/${a}/cover-adjustment-info`]}),o.invalidateQueries({queryKey:[`/api/books/${a}/covers`]}),setTimeout(()=>{ye(null),Ae(null)},5e3)},[a,o]),ha=r.useCallback(async()=>{if(a){J(!0);try{const s=await(await Y("POST","/api/orders",{bookId:a,type:Fe,amount:G,paymentMethod:"pix",metadata:Le})).json();w(s.id),s.pixCharge&&j(s.pixCharge)}catch{n({title:"Erro ao gerar cobrança",description:"Tente novamente em alguns instantes.",variant:"destructive"})}finally{J(!1)}}},[a,Fe,G,Le,n]),fa=r.useCallback(async()=>
1{if(a){J(!0),ae(null);try{const s=await(await Y("POST","/api/stripe/create-payment-intent",{bookId:a,type:Fe,amount:G,metadata:Le,referrerPage:window.location.pathname})).json();w(s.orderId),oe(s.clientSecret)}catch{n({title:"Erro ao preparar pagamento",description:"Tente novamente em alguns instantes.",variant:"destructive"})}finally{J(!1)}}},[a,Fe,G,Le,n]),Wa=r.useCallback(async()=>{if(a){J(!0);try{const s=await(await Y("POST","/api/orders/beta",{bookId:a,type:Fe,amount:G,metadata:Le})).json();w(s.id),ze()}catch(t){n({title:"Erro na ativação beta",description:t?.message||"Tente novamente.",variant:"destructive"})}finally{J(!1)}}},[a,Fe,G,Le,n,ze]),Ha=r.useCallback(async()=>{if(a){J(!0);try{const s=await(await Y("POST","/api/orders/pay-with-credits",{bookId:a,type:Fe,amount:G,metadata:Le,referrerPage:window.location.pathname})).json();w(s.id);const m=Math.round(G*100);st(b=>b!==null?b-m:null),ze()}catch(t){const s=t?.message||"";n({title:"Erro no pagamento",description:s.includes("insuficiente")?"Saldo de créditos insuficiente.":"Tente novamente.",variant:"destructive"})}finally{J(!1)}}},[a,Fe,G,Le,n,ze]),Tt=t=>{c(t),t==="pix"?ha():t==="beta"?Wa():t==="credits"?Ha():fa()},Ya=r.useCallback(()=>{ze()},[ze]),Ja=r.useCallback(t=>{ae(t),n({title:"Erro no pagamento",description:t,variant:"destructive"})},[n]);r.useEffect(()=>{if(!(!X||xe||S!=="pix"))return Ue.current=setInterval(async()=>{try{(await(await Y("GET",`/api/orders/${X}/status`)).json()).paid&&(Ue.current&&clearInterval(Ue.current),ze())}catch{}},3e3),()=>{Ue.current&&clearInterval(Ue.current)}},[X,xe,S,ze]);const ga=async()=>{if(R?.brCode)try{await navigator.clipboard.writeText(R.brCode),pe(!0),n({title:"Código PIX copiado!"}),setTimeout(()=>pe(!1),3e3)}catch{const t=document.querySelector('[data-testid="page-cover-pix-brcode-input"]');t&&(t.select(),document.execCommand("copy"),pe(!0),setTimeout(()=>pe(!1),3e3))}},ba=async t=>{try{if(!(await fetch(`/api/books/${a}/select-cover`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({coverId:t})})).ok)throw new Error("Erro ao selecionar capa");U(),o.invalidateQueries({queryKey:[`/api/books/${a}`]}),o.invalidateQueries({queryKey:["/api/store/public/listings"]}),o.invalidateQueries({queryKey:["/api/store/my-listings"]}),o.invalidateQueries({queryKey:[`/api/store/my-listings/${a}`]}),n({title:"Capa selecionada!"})}catch{n({title:"Erro ao selecionar capa",variant:"destructive"})}},Xa=async t=>{const s=t.target.files?.[0];if(!s)return;Je.current&&(Je.current.value="");const m=10*1024*1024;if(s.size>m){n({title:"Imagem muito grande",description:"O tamanho máximo é 10MB. Tente com uma imagem menor."});return}if(!Ts(s.name,s.type)){n({title:"Formato não suportado",description:"Use uma imagem JPG, PNG ou WebP."});return}ea(!0);const b=new AbortController,_=setTimeout(()=>b.abort(),6e4);try{const D=new FormData;D.append("cover",s);const q=await fetch(`/api/books/${a}/upload-cover`,{method:"POST",credentials:"include",body:D,signal:b.signal});if(!q.ok){const ve=await q.json().catch(()=>({}));throw new Error(ve.message||"Erro ao enviar")}const ee=await q.json(),K=ee?.cover||ee?.coverRecord,B=K?.id&&K?.imageUrl?{...K,style:K.style||Jt,selected:K.selected??!1}:{id:ee?.coverId,imageUrl:ee?.coverImage,prompt:null,style:Jt,selected:!1};if(!B?.id||!B?.imageUrl)throw new Error("A capa foi enviada, mas o servidor não retornou os dados da galeria.");const te=[`/api/books/${a}/covers`],ne=ve=>Os(ve,B);o.setQueryData(te,ne),(await Promise.allSettled([U(),Qe(),nt()])).forEach((ve,ft)=>{ve.status==="rejected"&&console.error(`[CUSTOM_COVER_UPLOAD] Failed to refresh ${["covers","entitlement","book"][ft]} for book ${a}:`,ve.reason)}),o.setQueryData(te,ne),n({title:"Capa adicionada!",description:"Sua capa apareceu na galeria. Selecione-a quando quiser."})}catch(D){const q=D?.name==="AbortError";n({title:q?"Demorou demais":"Ops!",description:q?"O envio da capa demorou mais que o esperado. Verifique sua conexão e tente novamente — ou use uma imagem menor.":D?.message&&D.message!=="Erro ao enviar"?D.message:"Não conseguimos adicionar sua capa. Tente novamente.",variant:"destructive"})}finally{clearTimeout(_),ea(!1)}};if(_t)return e.jsx(Rt,{children:e.jsx("div",{className:"min-h-screen flex items-center justify-center",children:e.jsx(C,{className:"w-8 h-8 text-primary animate-spin","data-testid":"spinner-loading"})})});if(!E)return e.jsx(Rt,{children:e.jsxs("div",{className:"min-h-screen flex flex-col items-center justify-center p-8 text-center animate-in fade-in duration-500",children:[e.jsx("div",{className:"w-20 h-20 rounded-2xl bg-red-500/10 border border-red-500/20 flex items-center justify-center mb-6",children:e.jsx(Wt,{className:"w-10 h-10 text-red-400/60"})}),e.jsx("h2",{className:"text-2xl font-bold text-white mb-3","data-testid":"text-book-not-found",children:"Livro não encontrado"}),e.jsx("p",{className:"text-muted-foreground mb-6 max-w-md",children:"Este livro pode ter sido removido ou não está mais disponível. Seus outros livros continuam seguros."}),e.jsxs(T,{onClick:()=>u("/dashboard"),"data-testid":"button-go-dashboard",children:[e.jsx(jt,{className:"w-4 h-4 mr-2"}),"Voltar ao início"]})]})});if(_a&&!ut)return e.jsx(Rt,{children:e.jsx("div",{className:"min-h-screen flex items-center justify-center p-4",children:e.jsx("div",{className:"w-full max-w-2xl",children:e.jsx(ws,{bookId:a||"",bookTitle:E?.title||"",serviceName:"cover",pipelineStatus:aa?.pipelineStatus||{},onBack:()=>u(`/book/${a}`)}
1)})})});const va=!!E?.translatedFromId,ja=Ye||!ut;return Ft&&Ft.some(t=>t.content),(Ft||[]).filter(t=>t.content).length,V?.some(t=>t.selected),qt&&qt.length>0,(qt||[]).length,e.jsxs(Rt,{children:[e.jsxs("div",{className:"min-h-screen lg:pr-[316px]",children:[e.jsx("div",{className:"sticky top-0 z-40 border-b border-white/5 bg-background/80 backdrop-blur-xl",children:e.jsxs("div",{className:"max-w-6xl mx-auto px-4 md:px-6 h-14 flex items-center justify-between",children:[e.jsxs("button",{onClick:()=>u(`/book/${a}`),className:"flex items-center gap-2 text-sm text-muted-foreground hover:text-white transition-colors","data-testid":"button-back-to-book",children:[e.jsx(jt,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Voltar ao meu livro"}),e.jsx("span",{className:"sm:hidden",children:"Voltar"})]}),e.jsx("h1",{className:"text-sm font-medium text-white truncate max-w-[200px] md:max-w-md text-center","data-testid":"text-nav-book-title",children:H}),e.jsxs(tt,{className:"bg-primary/20 text-primary border-primary/20 hover:bg-primary/20 text-xs shrink-0","data-testid":"badge-cover-studio",children:[e.jsx(bt,{className:"w-3 h-3 mr-1"}),"Cover Studio"]})]})}),e.jsx("div",{className:"max-w-6xl mx-auto px-4 md:px-6 py-8",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-8",children:[e.jsxs("div",{className:"flex-1 min-w-0 space-y-8 pb-40 md:pb-8",children:[e.jsx("input",{ref:Je,type:"file",accept:".jpg,.jpeg,.png,.webp,image/jpeg,image/png,image/webp",className:"hidden",onChange:Xa,"data-testid":"input-custom-cover-upload"}),ct?.access?.publishBundle&&(V?.length||0)>0&&e.jsx("div",{className:"rounded-2xl border border-emerald-500/20 bg-emerald-500/5 p-4 animate-in fade-in","data-testid":"section-bundle-active-banner",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Te,{className:"w-5 h-5 text-emerald-400 shrink-0"}),e.jsxs("p",{className:"text-sm text-emerald-200",children:[e.jsx("span",{className:"font-semibold",children:"Pacote Publicar ativo"})," — todas as capas estão grátis pra você. Escolha sua favorita abaixo."]})]})}),se?.canGenerate&&(V?.length||0)===0&&!N&&e.jsx("div",{className:"rounded-2xl border border-emerald-500/30 bg-gradient-to-r from-emerald-950/30 via-emerald-900/10 to-transparent p-6 animate-in fade-in","data-testid":"section-cover-access-recovery",children:e.jsxs("div",{className:"flex flex-col md:flex-row items-center gap-4",children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-emerald-500/15 border border-emerald-500/30 flex items-center justify-center shrink-0",children:e.jsx(F,{className:"w-7 h-7 text-emerald-400"})}),e.jsxs("div",{className:"flex-1 text-center md:text-left",children:[e.jsx("h3",{className:"text-lg font-bold text-white",children:ct?.access?.publishBundle?"Pacote Publicar ativo — vamos criar suas capas":"Sua compra cobre a criação da capa"}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["Identificamos um pagamento confirmado",ct?.access?.publishBundle?" do Pacote Publicar":" do seu pacote ou do plano de capa",", mas ",re===1?"a capa ainda não foi criada":`as ${re} capas ainda não foram criadas`,'. Clique em "Gerar Capas" abaixo — você não será cobrado novamente.']})]}),e.jsx(T,{onClick:pa,disabled:Ne,className:"bg-gradient-to-r from-emerald-500 to-emerald-600 hover:from-emerald-400 hover:to-emerald-500 text-emerald-950 font-semibold px-6 shadow-[0_0_15px_rgba(16,185,129,0.25)]","data-testid":"button-recover-covers",children:Ne?e.jsxs(e.Fragment,{children:[e.jsx(C,{className:"w-4 h-4 mr-2 animate-spin"}),"Iniciando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(F,{className:"w-4 h-4 mr-2"}),"Gerar Capas"]})})]})}),fe&&!N&&e.jsx("div",{className:"rounded-2xl border border-amber-500/20 bg-gradient-to-r from-amber-950/20 via-amber-900/10 to-transparent p-6 animate-in fade-in","data-testid":"section-cover-generation-failed",children:e.jsxs("div",{className:"flex flex-col md:flex-row items-center gap-4",children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-amber-500/10 border border-amber-500/20 flex items-center justify-center shrink-0",children:e.jsx(bt,{className:"w-7 h-7 text-amber-400"})}),e.jsxs("div",{className:"flex-1 text-center md:text-left",children:[e.jsx("h3",{className:"text-lg font-bold text-white",children:"Geração de capas incompleta"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"A geração anterior não foi concluída completamente. Clique abaixo para gerar novas capas profissionais para seu livro."})]}),e.jsx(T,{onClick:pa,disabled:Ne,className:"bg-gradient-to-r from-amber-500 to-amber-600 hover:from-amber-400 hover:to-amber-500 text-amber-950 font-semibold px-6 shadow-[0_0_15px_rgba(245,158,11,0.2)]","data-testid":"button-retry-covers",children:Ne?e.jsxs(e.Fragment,{children:[e.jsx(C,{className:"w-4 h-4 mr-2 animate-spin"}),"Iniciando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(F,{className:"w-4 h-4 mr-2"}),"Gerar Capas Novamente"]})})]})}),N&&e.jsxs("div",{className:"space-y-4 animate-in fade-in","data-testid":"section-generating-covers",children:[e.jsxs("div",{className:"text-center space-y-2 mb-2",children:[e.jsx("h2",{className:"text-xl font-bold text-white",children:"Criando suas capas profissionais..."}),(()=>{const t=se?.currentCount??(V?Math.max(0,V.filter(b=>b.imageUrl&&b.imageUrl.trim().length>0).length-he):0),s=Math.floor(Nt/60),m=Nt%60;return e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["A SÁBHIA está desenhando ",re===1?"sua capa exclusiva":`${re} opções exclusivas`," para seu livro",t>0&&e.jsxs("span",{className:"text-primary font-semibold",children:[" — ",t," de ",re," ",re===1?"pronta":"prontas","!"]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-3 mt-2",children:[e.jsx("div",{className:"flex gap-1",children:Array.from({length:re},(b,_)=>_).map(b=>e.jsx("div",{className:`w-2.5 h-2.5 rounded-full transition-all duration-500 ${b<t?"bg-primary scale-110":"bg-white/10 animate-pulse"}`,style:{animationDelay:`${b*200}ms`}},b))}
1),e.jsx("span",{className:"text-xs text-muted-foreground/60 font-mono","data-testid":"text-polling-elapsed",children:s>0?`${s}m ${m.toString().padStart(2,"0")}s`:`${m}s`})]}),Nt>180&&t<re&&e.jsx("p",{className:"text-xs text-amber-400/70 mt-1",children:"Suas capas estão sendo geradas. Você pode sair e voltar depois."})]})})()]}),e.jsx("div",{className:`grid grid-cols-1 ${re>1?"sm:grid-cols-2 md:grid-cols-4":"max-w-xs mx-auto"} gap-4`,children:Array.from({length:re},(t,s)=>s).map(t=>{const s=V||[],m=Math.max(0,s.length-he),_=s.slice(0,m).slice().reverse()[t];return _?e.jsxs("div",{className:"rounded-2xl border border-primary/30 overflow-hidden bg-gradient-to-b from-primary/5 to-background animate-in fade-in zoom-in-95 duration-500","data-testid":`generated-cover-${t}`,children:[e.jsxs("div",{className:"aspect-[5/8] relative",children:[e.jsx(Dt,{src:_.imageUrl,alt:`Capa ${t+1}`,className:"w-full h-full object-cover",thumbWidth:520}),e.jsxs("div",{className:"absolute top-2 right-2 flex items-center gap-1 rounded-full bg-emerald-500/90 px-2 py-0.5 text-[10px] font-semibold text-white shadow-lg backdrop-blur-sm animate-in fade-in zoom-in duration-300","data-testid":`badge-cover-ready-${t}`,children:[e.jsx(Ie,{className:"w-3 h-3"})," Pronta"]})]}),e.jsx("div",{className:"p-2 text-center",children:e.jsx("span",{className:"text-xs text-primary font-semibold",children:_.style||`Opção ${t+1}`})})]},_.id):e.jsx("div",{className:"rounded-2xl border border-white/10 overflow-hidden bg-gradient-to-b from-white/[0.03] to-transparent","data-testid":`placeholder-cover-${t}`,children:e.jsxs("div",{className:"aspect-[5/8] relative flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-primary/5 via-transparent to-primary/[0.02]"}),e.jsxs("div",{className:"relative flex flex-col items-center gap-3",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-primary/10 flex items-center justify-center animate-pulse",children:e.jsx(F,{className:"w-7 h-7 text-primary/40"})}),e.jsxs("div",{className:"space-y-2 w-3/4",children:[e.jsx("div",{className:"h-2.5 bg-white/[0.06] rounded-full animate-pulse",style:{animationDelay:`${t*150}ms`}}),e.jsx("div",{className:"h-2 bg-white/[0.04] rounded-full w-2/3 mx-auto animate-pulse",style:{animationDelay:`${t*150+75}ms`}})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground/40 mt-1",children:"Gerando..."})]})]})},`placeholder-${t}`)})}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(C,{className:"w-4 h-4 animate-spin text-primary"}),e.jsx("span",{children:Nt>120?"Suas capas estão sendo criadas pela SÁBHIA...":"Isso pode levar alguns minutos..."})]})]}),va&&ja&&!N&&ct&&!ct.canGenerateCovers&&e.jsx("div",{className:"space-y-6","data-testid":"section-translate-cover-flow",children:e.jsxs("div",{className:"glass-card rounded-2xl border border-white/10 p-6 md:p-8 animate-in fade-in slide-in-from-bottom-4 duration-300",children:[e.jsxs("div",{className:"text-center space-y-3 mb-8",children:[e.jsx("div",{className:"w-16 h-16 mx-auto rounded-2xl bg-gradient-to-br from-emerald-400/20 to-teal-600/20 flex items-center justify-center ring-2 ring-primary/30 mb-4",children:e.jsx(F,{className:"w-7 h-7 text-primary"})}),e.jsx("h2",{className:"text-2xl font-bold text-white",children:"Traduza sua capa"}),e.jsx("p",{className:"text-muted-foreground text-base max-w-md mx-auto",children:"Sua capa original será adaptada para o novo idioma mantendo o mesmo estilo visual"})]}),E?.coverImage&&e.jsxs("div",{className:"flex flex-col items-center gap-6 mb-8",children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute -inset-1 bg-gradient-to-br from-emerald-500/30 to-teal-500/30 rounded-2xl blur-sm"}),e.jsx("img",{src:E.coverImage,alt:"Capa original",className:"relative w-48 h-auto rounded-xl shadow-2xl border border-white/10","data-testid":"img-original-cover-preview"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ie,{className:"w-4 h-4 text-emerald-400"}),e.jsx("span",{children:"Capa original do livro"})]})]}),e.jsxs("div",{className:"bg-white/[0.03] border border-white/8 rounded-xl p-5 space-y-3 mb-6",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ie,{className:"w-5 h-5 text-emerald-400 mt-0.5 shrink-0"}),e.jsx("span",{className:"text-sm text-white/80",children:"O título e subtítulo serão traduzidos automaticamente na capa"})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ie,{className:"w-5 h-5 text-emerald-400 mt-0.5 shrink-0"}),e.jsx("span",{className:"text-sm text-white/80",children:"O estilo visual e cores da capa original são preservados"})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ie,{className:"w-5 h-5 text-emerald-400 mt-0.5 shrink-0"}),e.jsx("span",{className:"text-sm text-white/80",children:"4 variações geradas com o título no novo idioma"})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ie,{className:"w-5 h-5 text-emerald-400 mt-0.5 shrink-0"}),e.jsx("span",{className:"text-sm text-white/80",children:"Download em alta resolução para todas as plataformas"})]})]}),e.jsxs("div",{className:"text-center space-y-4",children:[e.jsxs("div",{className:"inline-flex items-baseline gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground line-through",children:p(99.99)}),e.jsx("span",{className:"text-3xl font-bold text-white",children:p(vt.cover_translation)})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Você já criou sua capa — pague apenas pela tradução"}),e.jsxs(T,{size:"lg",onClick:()=>we(!0),className:"w-full max-w-sm bg-gradient-to-r from-emerald-500 to-teal-500 text-white font-bold text-base py-6 rounded-xl shadow-lg shadow-emerald-500/25 hover:shadow-emerald-500/40 hover:scale-[1.02] transition-all duration-200","data-testid":"button-translate-cover",children:["🎨 Traduzir Minha Capa — ",p(vt.cover_translation)]}),e.jsx(Aa,{open:Mt,onOpenChange:we,product:{title:`Traduzir Capa — ${H}`,description:"Tradução da capa para o novo idioma com 4 variações",price:vt.cover_translation,originalPrice
1:99.99,features:["Título e subtítulo traduzidos na capa","Estilo visual e cores preservados","4 variações profissionais","Download em alta resolução"]},onConfirm:t=>{we(!1),n({title:"Tradução da capa iniciada!",description:"Suas 4 capas traduzidas estão sendo criadas."}),ht()},bookId:a,bookTitle:H,orderType:"cover_translation",metadata:{coverBrief:{style:"translation",translatedFromId:E?.translatedFromId}}}),e.jsx("div",{className:"pt-3 mt-1 border-t border-white/5",children:e.jsxs("button",{onClick:()=>Je.current?.click(),disabled:Ce,className:"text-xs text-muted-foreground/50 hover:text-muted-foreground/80 transition-colors inline-flex items-center gap-1.5","data-testid":"button-upload-custom-cover-translation",children:[Ce?e.jsx(C,{className:"w-3 h-3 animate-spin"}):e.jsx(zt,{className:"w-3 h-3"}),Ce?"Enviando...":"Já tenho uma capa"]})})]})]})}),!va&&ja&&!N&&e.jsxs("div",{className:"space-y-6","data-testid":"section-create-flow",children:[k===2&&e.jsxs("div",{className:"glass-card rounded-2xl border border-white/10 p-6 md:p-8 animate-in fade-in slide-in-from-right-4 duration-300",children:[e.jsxs("div",{className:"text-center space-y-2 mb-8",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 mb-1",children:[e.jsx(Wt,{className:"w-6 h-6 text-primary"}),e.jsx("span",{className:"text-sm font-semibold text-primary uppercase tracking-wider",children:y("coverCreate.personalizeTitle","Personalize sua capa")})]}),e.jsx("p",{className:"text-muted-foreground text-base",children:y("coverCreate.personalizeSubtitle","Conte como você imagina sua capa ideal")}),e.jsxs("button",{onClick:()=>Je.current?.click(),disabled:Ce,className:"text-[11px] text-muted-foreground/40 hover:text-muted-foreground/70 transition-colors inline-flex items-center gap-1 mt-2","data-testid":"button-upload-custom-cover-create",children:[Ce?e.jsx(C,{className:"w-3 h-3 animate-spin"}):e.jsx(zt,{className:"w-3 h-3"}),Ce?"Enviando...":"Já tenho uma capa"]})]}),e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"text-lg font-bold text-white block",children:["Que estilo você imagina para sua capa? ",e.jsx("span",{className:"text-red-400",children:"*"})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:at.map(t=>e.jsx(Ot,{selected:l.style===t.id,onClick:()=>v(s=>({...s,style:t.id})),image:t.image,label:t.label,desc:t.desc,testId:`page-card-style-${t.id}`},t.id))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"text-lg font-bold text-white block",children:["Quais cores representam melhor seu livro? ",e.jsx("span",{className:"text-red-400",children:"*"})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:Vt.map(t=>e.jsx(Ot,{selected:l.colorMood===t.id,onClick:()=>v(s=>({...s,colorMood:t.id})),image:t.image,label:t.label,desc:t.desc,testId:`page-card-color-${t.id}`},t.id))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"text-lg font-bold text-white block",children:["O que gostaria de ver na capa?"," ",e.jsx("span",{className:"text-sm text-muted-foreground font-normal",children:"(opcional)"})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:Ds.map(t=>e.jsx(Ot,{selected:l.mainElement===t.id,onClick:()=>v(s=>({...s,mainElement:s.mainElement===t.id?"":t.id})),image:t.image,label:t.label,testId:`page-card-element-${t.id}`},t.id))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"text-lg font-bold text-white block",children:["Usar sua foto na capa"," ",e.jsx("span",{className:"text-sm text-muted-foreground font-normal",children:"(opcional)"})]}),e.jsx("p",{className:"text-sm text-muted-foreground -mt-1",children:"Envie uma foto sua e a SÁBHIA criará uma versão profissional e poderosa para a capa do livro"}),e.jsx("input",{ref:me,type:"file",accept:"image/jpeg,image/png,image/webp,image/jpg",className:"hidden","data-testid":"page-input-author-photo",onChange:t=>{const s=t.target.files?.[0];s&&xa(s)}}),!Ve&&!l.authorPhotoUrl?e.jsxs("button",{type:"button",onClick:()=>me.current?.click(),disabled:de,onDragOver:t=>{t.preventDefault(),t.currentTarget.classList.add("border-primary","bg-primary/10")},onDragLeave:t=>{t.currentTarget.classList.remove("border-primary","bg-primary/10")},onDrop:t=>{t.preventDefault(),t.currentTarget.classList.remove("border-primary","bg-primary/10");const s=t.dataTransfer.files?.[0];s&&xa(s)},className:"w-full rounded-xl border-2 border-dashed border-white/15 hover:border-primary/40 bg-white/[0.03] hover:bg-primary/5 p-6 flex flex-col items-center gap-3 transition-all text-center group","data-testid":"page-button-upload-photo",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-gradient-to-br from-violet-500/20 to-fuchsia-500/20 border border-white/10 flex items-center justify-center group-hover:scale-105 transition-transform",children:e.jsx(Ma,{className:"w-7 h-7 text-violet-400"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-white font-semibold text-base",children:"Clique para enviar sua foto"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"ou arraste e solte aqui · JPG, PNG ou WebP · Máx 10MB"})]})]}):e.jsxs("div",{className:"rounded-xl border border-primary/30 bg-gradient-to-br from-violet-950/20 via-fuchsia-950/10 to-transparent p-4 flex items-center gap-4","data-testid":"page-photo-preview",children:[e.jsxs("div",{className:"relative w-20 h-20 rounded-xl overflow-hidden border border-white/20 shrink-0",children:[e.jsx("img",{src:Ve||l.authorPhotoUrl,alt:"Sua foto",className:"w-full h-full object-cover"}),de&&e.jsx("div",{className:"absolute inset-0 bg-black/60 flex items-center justify-center",children:e.jsx(C,{className:"w-6 h-6 text-primary animate-spin"})})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-white",children:de?"Enviando foto...":"Foto enviada com sucesso"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"A SÁBHIA usará esta foto como base para criar uma ver
1são profissional e impactante na capa"})]}),e.jsx("button",{type:"button",onClick:Ka,className:"shrink-0 w-9 h-9 rounded-lg bg-white/5 hover:bg-red-500/20 border border-white/10 hover:border-red-500/30 flex items-center justify-center transition-all group/del","data-testid":"page-button-remove-photo",children:e.jsx(ys,{className:"w-4 h-4 text-muted-foreground group-hover/del:text-red-400 transition-colors"})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"text-lg font-bold text-white block",children:["Estilo da fonte do título ",e.jsx("span",{className:"text-sm text-muted-foreground font-normal",children:"(opcional)"})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:Gt.map(t=>e.jsx(Ot,{selected:l.fontStyle===t.id,onClick:()=>v(s=>({...s,fontStyle:s.fontStyle===t.id?"":t.id})),image:t.image,label:t.label,desc:t.desc,testId:`page-card-font-${t.id}`},t.id))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"text-lg font-bold text-white block",children:["Cor da fonte ",e.jsx("span",{className:"text-sm text-muted-foreground font-normal",children:"(opcional)"})]}),e.jsx("div",{className:"grid grid-cols-4 gap-3",children:Kt.map(t=>e.jsx(Us,{selected:l.fontColor===t.id,onClick:()=>v(s=>({...s,fontColor:s.fontColor===t.id?"":t.id})),color:t.color,label:t.label,testId:`page-card-fontcolor-${t.id}`},t.id))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"text-lg font-bold text-white block",children:["Descreva com suas palavras como imagina sua capa"," ",e.jsx("span",{className:"text-sm text-muted-foreground font-normal",children:"(opcional)"})]}),e.jsx(os,{value:l.freeText,onChange:t=>{t.target.value.length<=500&&v(s=>({...s,freeText:t.target.value}))},placeholder:"Ex: Gostaria de uma capa com um pôr do sol sobre o mar, com tons dourados...",rows:4,className:"bg-white/5 border-white/10 text-white placeholder:text-white/30 text-base resize-none","data-testid":"page-textarea-cover-freetext"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[l.freeText.length,"/500"]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"text-lg font-bold text-white block",children:["Há algo que NÃO quer na capa?"," ",e.jsx("span",{className:"text-sm text-muted-foreground font-normal",children:"(opcional)"})]}),e.jsx(ya,{value:l.avoidText,onChange:t=>{t.target.value.length<=200&&v(s=>({...s,avoidText:t.target.value}))},placeholder:"Ex: Não quero rostos humanos, não quero cores escuras...",className:"bg-white/5 border-white/10 text-white placeholder:text-white/30 text-base h-12","data-testid":"page-input-cover-avoid"})]}),(H||dt||mt)&&e.jsxs("div",{className:"rounded-xl bg-white/5 border border-white/[0.07] p-4 space-y-2",children:[e.jsx("p",{className:"text-base font-semibold text-white flex items-center gap-2",children:"📚 SÁBHIA já sabe sobre seu livro:"}),H&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"text-zinc-400 font-medium",children:"Título:"})," ",H]}),dt&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"text-zinc-400 font-medium",children:"Gênero:"})," ",dt]}),mt&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"text-zinc-400 font-medium",children:"Sinopse:"})," ",mt.length>150?mt.slice(0,150)+"...":mt]})]}),e.jsxs("div",{className:"flex items-center gap-4 pt-2",children:[e.jsxs("button",{onClick:()=>ut?Oe(!1):u(`/book/${a}`),className:"flex items-center gap-2 text-base text-muted-foreground hover:text-white transition-colors","data-testid":"button-page-cover-back-step1",children:[e.jsx(jt,{className:"w-4 h-4"}),"Voltar"]}),e.jsxs("div",{className:"flex-1",children:[sa?e.jsxs(T,{onClick:async()=>{try{await Y("POST",`/api/books/${a}/pipeline-start/cover`,{coverBrief:{style:l.style,colorMood:l.colorMood,mainElement:l.mainElement||void 0,fontStyle:l.fontStyle||void 0,fontColor:l.fontColor||void 0,freeText:l.freeText||void 0,avoidText:l.avoidText||void 0,authorPhotoUrl:l.authorPhotoUrl||void 0}}),o.invalidateQueries({queryKey:[`/api/books/${a}/next-upsell`]}),o.invalidateQueries({queryKey:[`/api/books/${a}/covers`]})}catch(t){console.error("Failed to start cover generation:",t)}},disabled:!pt,className:"w-full h-14 text-lg rounded-xl bg-blue-600 hover:bg-blue-500 text-white font-bold shadow-lg shadow-blue-500/20 hover:shadow-blue-500/40 transition-all disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"button-page-cover-pipeline-start",title:pt?void 0:"Selecione um estilo e uma paleta de cores para continuar",children:[e.jsx(F,{className:"w-5 h-5 mr-2"}),"Já Pago — Gerar Minha Capa"]}):e.jsxs(T,{onClick:()=>{f(2.5),is("Capa Profissional",99.99),ms("customize_product",{item_name:"Capa Profissional",value:99.99,currency:"BRL"}),I(null),M(!0),Y("POST",`/api/books/${a}/cover-offer-copy`,{coverBrief:l}).then(t=>t.json()).then(t=>I(t)).catch(()=>I(null)).finally(()=>M(!1))},disabled:!pt,className:"w-full h-14 text-lg rounded-xl bg-primary hover:bg-primary/90 text-white font-bold shadow-lg shadow-primary/20 hover:shadow-
1primary/40 transition-all disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"button-page-cover-proceed-payment",title:pt?void 0:"Selecione um estilo e uma paleta de cores para continuar",children:[e.jsx(F,{className:"w-5 h-5 mr-2"}),"Gerar Capa"]}),!pt&&e.jsx("p",{className:"text-xs text-amber-400/80 text-center mt-2",children:"Selecione um estilo e uma paleta de cores para continuar"})]})]})]})]}),k===2.5&&e.jsx("div",{className:"glass-card rounded-2xl border border-white/10 p-6 md:p-8 animate-in fade-in slide-in-from-right-4 duration-300","data-testid":"section-offer-step",children:L?e.jsxs("div",{className:"space-y-6 animate-pulse",children:[e.jsxs("div",{className:"text-center space-y-3",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-primary/15 border border-primary/20",children:[e.jsx(F,{className:"w-4 h-4 text-primary"}),e.jsx("span",{className:"text-xs font-bold text-primary uppercase tracking-wider",children:"Cover Studio SÁBHIA"})]}),e.jsx("div",{className:"h-6 bg-white/10 rounded-lg w-3/4 mx-auto"}),e.jsx("div",{className:"h-4 bg-white/5 rounded-lg w-full mx-auto"}),e.jsx("div",{className:"h-4 bg-white/5 rounded-lg w-5/6 mx-auto"})]}),e.jsxs("div",{className:"space-y-3 pt-2",children:[e.jsx("div",{className:"h-4 bg-white/5 rounded-lg w-full"}),e.jsx("div",{className:"h-4 bg-white/5 rounded-lg w-11/12"}),e.jsx("div",{className:"h-4 bg-white/5 rounded-lg w-4/5"})]}),e.jsx("div",{className:"space-y-2.5 pt-2",children:[1,2,3,4,5,6].map(t=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-5 h-5 rounded-full bg-white/10 shrink-0"}),e.jsx("div",{className:"h-4 bg-white/5 rounded-lg flex-1",style:{width:`${70+Math.random()*25}%`}})]},t))}),e.jsxs("div",{className:"rounded-xl bg-white/5 border border-white/10 p-5 text-center space-y-3",children:[e.jsx("div",{className:"h-4 bg-white/5 rounded-lg w-1/2 mx-auto"}),e.jsx("div",{className:"h-8 bg-white/10 rounded-lg w-1/3 mx-auto"}),e.jsx("div",{className:"h-10 bg-white/10 rounded-lg w-2/3 mx-auto"})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(C,{className:"w-4 h-4 animate-spin text-primary"}),e.jsx("span",{children:"Preparando sua proposta personalizada..."})]})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"text-center space-y-3",children:e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-primary/15 border border-primary/20",children:[e.jsx(F,{className:"w-4 h-4 text-primary"}),e.jsx("span",{className:"text-xs font-bold text-primary uppercase tracking-wider",children:"Cover Studio SÁBHIA"})]})}),e.jsx("p",{className:"text-lg md:text-xl text-zinc-200 leading-relaxed text-center","data-testid":"text-offer-greeting",children:xt.greeting}),e.jsxs("div",{className:"rounded-xl bg-primary/5 border border-primary/10 p-5 space-y-2",children:[e.jsxs("p",{className:"text-base font-semibold text-primary flex items-center gap-2",children:[e.jsx(F,{className:"w-4 h-4"}),"O que vamos criar para você"]}),e.jsx("p",{className:"text-base text-zinc-300 leading-relaxed","data-testid":"text-offer-whatwedo",children:xt.whatWeWillDo})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-lg font-bold text-white text-center",children:"Tudo que você recebe:"}),e.jsx("div",{className:"space-y-2.5",children:xt.valueItems.map((t,s)=>e.jsxs("div",{className:"flex items-start gap-3","data-testid":`offer-value-item-${s}`,children:[e.jsx("div",{className:"w-5 h-5 rounded-full bg-emerald-500/20 flex items-center justify-center shrink-0 mt-0.5",children:e.jsx(Ie,{className:"w-3 h-3 text-emerald-400"})}),e.jsx("span",{className:"text-base text-zinc-300 leading-snug",children:t})]},s))})]}),e.jsxs("div",{className:"rounded-xl bg-white/5 border border-white/10 p-5 text-center space-y-3",children:[e.jsx("p",{className:"text-base text-zinc-400","data-testid":"text-offer-comparison",children:xt.designerComparison}),e.jsx("p",{className:"text-2xl font-bold text-zinc-500 line-through",children:"R$ 500 a R$ 2.000"}),e.jsx("div",{className:"w-16 h-px bg-gradient-to-r from-transparent via-primary/50 to-transparent mx-auto"}),e.jsx("p",{className:"text-base text-primary font-semibold",children:"Você recebe 4 capas profissionais por:"}),e.jsx("p",{className:"text-lg text-white/40 line-through mb-1",children:p(wt(G))}),e.jsx("p",{className:"text-4xl md:text-5xl font-extrabold text-emerald-400","data-testid":"text-offer-price",children:p(G)}),e.jsx("span",{className:"inline-flex items-center gap-1 text-[10px] px-2 py-0.5 rounded-full bg-amber-500/15 border border-amber-500/30 text-amber-400 font-semibold mt-2",children:"Oferta de lançamento"})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-base text-zinc-400 text-center",children:[e.jsx(Ht,{className:"w-4 h-4 text-primary shrink-0"}),e.jsx("span",{"data-testid":"text-offer-closing",children:xt.closingPitch})]}),e.jsxs(T,{onClick:()=>f(3),className:"w-full h-14 text-lg rounded-xl bg-primary hover:bg-primary/90 text-white font-extrabold shadow-lg shadow-primary/25 hover:shadow-
1primary/40 transition-all","data-testid":"button-offer-cta",children:["Quero Minha Capa Profissional",e.jsx(Oa,{className:"w-5 h-5 ml-2"})]}),e.jsxs("button",{onClick:()=>f(2),className:"flex items-center gap-2 text-base text-muted-foreground hover:text-white transition-colors mx-auto","data-testid":"button-offer-back-briefing",children:[e.jsx(jt,{className:"w-4 h-4"}),"Voltar ao briefing"]})]})}),k===3&&e.jsxs("div",{className:"glass-card rounded-2xl border border-white/10 p-6 md:p-8 max-w-md mx-auto animate-in fade-in slide-in-from-right-4 duration-300",children:[xe?(()=>{const t=S==="beta"||S==="credits",s=vt.cover,m=t?0:Math.round(s*100*.1);return e.jsxs("div",{className:"bg-green-500/10 rounded-2xl p-8 border border-green-500/20 text-center animate-in fade-in zoom-in",children:[e.jsx(Te,{className:"w-14 h-14 text-green-500 mx-auto mb-4"}),e.jsx("p",{className:"text-green-400 font-bold text-xl","data-testid":"text-page-cover-payment-confirmed",children:"Pagamento Confirmado!"}),e.jsx("p",{className:"text-muted-foreground text-base mt-2",children:"Gerando sua capa com SÁBHIA..."}),m>0&&e.jsxs("div",{className:"mt-4 pt-4 border-t border-white/10 animate-in fade-in slide-in-from-bottom-3 duration-700",style:{animationDelay:"600ms",animationFillMode:"both"},children:[e.jsx("div",{className:"flex items-center justify-center gap-2 mb-2",children:e.jsx("div",{className:"w-8 h-8 rounded-full bg-amber-500/20 flex items-center justify-center animate-bounce",style:{animationDuration:"1.5s"},children:e.jsx(Na,{size:"sm"})})}),e.jsxs("p",{className:"text-amber-400 font-bold text-base","data-testid":"text-cover-cashback-earned",children:["+",m.toLocaleString("pt-BR")," créditos"]}),e.jsx("p",{className:"text-muted-foreground text-xs mt-1",children:"Você ganhou créditos com esta compra!"})]})]})})():S?S==="card"&&Q?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(C,{className:"w-8 h-8 text-blue-400 animate-spin mb-3"}),e.jsx("p",{className:"text-muted-foreground text-base","data-testid":"text-page-cover-loading-card",children:"Preparando formulário seguro..."})]}):S==="card"&&ue?e.jsxs(ns,{stripe:As(),options:{clientSecret:ue,appearance:Ms,locale:"pt-BR"},children:[e.jsx(Bs,{orderId:X||"",onSuccess:Ya,onError:Ja,amount:G,currency:h}),e.jsx("button",{onClick:()=>{c(null),oe(null),w(null),ae(null)},className:"w-full text-xs text-center text-muted-foreground hover:text-white transition-colors mt-4","data-testid":"button-page-cover-change-method-card",children:"Alterar forma de pagamento"})]}):S==="card"&&!ue&&!Q?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx("p",{className:"text-muted-foreground text-base","data-testid":"text-page-cover-card-error",children:Bt||"Erro ao preparar pagamento. Tente novamente."}),e.jsx(T,{variant:"outline",className:"mt-3 border-white/10",onClick:fa,"data-testid":"button-page-cover-retry-card",children:"Tentar novamente"}),e.jsx("button",{onClick:()=>{c(null),ae(null)},className:"text-sm text-muted-foreground mt-2 hover:text-white transition-colors",children:"Alterar forma de pagamento"})]}
1):S==="pix"&&Q?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(C,{className:"w-8 h-8 text-primary animate-spin mb-3"}),e.jsx("p",{className:"text-muted-foreground text-base","data-testid":"text-page-cover-loading-pix",children:"Gerando cobrança PIX..."})]}):S==="pix"&&R?e.jsxs("div",{className:"bg-white/5 rounded-xl p-4 md:p-6 border border-white/10 animate-in fade-in slide-in-from-top-2",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 mb-4",children:[e.jsx(Ca,{className:"h-5 w-5 text-primary"}),e.jsx("span",{className:"text-sm font-bold text-white","data-testid":"text-page-cover-pix-method",children:"Pagamento via PIX"})]}),e.jsx("p",{className:"text-sm text-center text-muted-foreground mb-4",children:"Escaneie o QR Code ou copie o código abaixo:"}),e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx("div",{className:"bg-white p-3 rounded-lg",children:e.jsx("img",{src:R.qrCodeImage,alt:"QR Code PIX",className:"w-40 h-40 md:w-48 md:h-48","data-testid":"page-cover-pix-qrcode"})})}),e.jsxs("div",{className:"flex gap-2 mb-3",children:[e.jsx(ya,{readOnly:!0,value:R.brCode,className:"bg-black/20 border-white/10 h-10 text-xs font-mono","data-testid":"page-cover-pix-brcode-input"}),e.jsx(T,{size:"icon",variant:"outline",className:"h-10 w-10 shrink-0 border-white/10 hover:bg-white/10",onClick:ga,"data-testid":"button-page-cover-copy-pix",children:e.jsx(ka,{className:"w-4 h-4"})})]}),e.jsxs(T,{variant:"secondary",className:"w-full h-10 text-sm bg-white/10 hover:bg-white/20 text-white border border-white/5",onClick:ga,"data-testid":"button-page-cover-copy-pix-full",children:[e.jsx(ka,{className:"w-4 h-4 mr-2"}),Z?"Copiado!":"Copiar código PIX"]}),e.jsx("p",{className:"text-xs text-center text-muted-foreground mt-4 animate-pulse","data-testid":"text-page-cover-waiting-payment",children:"Aguardando pagamento... A confirmação é automática."}),e.jsx("button",{onClick:()=>{c(null),j(null),w(null)},className:"w-full text-xs text-center text-muted-foreground mt-3 hover:text-white transition-colors","data-testid":"button-page-cover-change-method",children:"Alterar forma de pagamento"})]}):S==="pix"&&!R&&!Q?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx("p",{className:"text-muted-foreground text-base","data-testid":"text-page-cover-charge-error",children:"Erro ao gerar cobrança. Tente novamente."}),e.jsx(T,{variant:"outline",className:"mt-3",onClick:ha,"data-testid":"button-page-cover-retry-charge",children:"Tentar novamente"}),e.jsx("button",{onClick:()=>c(null),className:"text-sm text-muted-foreground mt-2 hover:text-white transition-colors",children:"Alterar forma de pagamento"})]}):S==="beta"&&Q?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(C,{className:"w-8 h-8 text-amber-400 animate-spin mb-3"}),e.jsx("p",{className:"text-muted-foreground text-base",children:"Ativando modo beta..."})]}):S==="credits"&&Q?e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(C,{className:"w-8 h-8 text-amber-400 animate-spin mb-3"}),e.jsx("p",{className:"text-muted-foreground text-base",children:"Processando pagamento com créditos..."})]}):null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-center mb-4",children:[e.jsx("h3",{className:"text-xl font-bold text-white","data-testid":"text-page-cover-payment-title",children:"Finalizar Pagamento"}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:['Capa para "',Ga,'"']})]}),e.jsxs("div",{className:"rounded-xl bg-white/5 border border-white/[0.07] p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(bt,{className:"w-4 h-4 text-primary"}),e.jsxs("span",{children:["Estilo:"," ",e.jsx("span",{className:"text-white font-medium",children:at.find(t=>t.id===l.style)?.label})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(bt,{className:"w-4 h-4 text-primary"}),e.jsxs("span",{children:["Cores:"," ",e.jsx("span",{className:"text-white font-medium",children:Vt.find(t=>
1t.id===l.colorMood)?.label})]})]}),l.fontStyle&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(bt,{className:"w-4 h-4 text-primary"}),e.jsxs("span",{children:["Fonte:"," ",e.jsxs("span",{className:"text-white font-medium",children:[Gt.find(t=>t.id===l.fontStyle)?.label,l.fontColor&&` em ${Kt.find(t=>t.id===l.fontColor)?.label}`]})]})]})]}),e.jsxs("div",{className:"text-center py-2",children:[e.jsx("span",{className:"text-lg text-white/40 line-through mr-2",children:p(wt(G))}),e.jsx("span",{className:"text-4xl font-bold text-emerald-400","data-testid":"text-page-cover-payment-price",children:p(G)})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-center text-muted-foreground",children:"Escolha a forma de pagamento:"}),g&&e.jsxs("button",{onClick:()=>Tt("pix"),className:"w-full p-4 rounded-xl border border-white/10 hover:border-primary/50 bg-white/5 hover:bg-white/10 transition-all flex items-center gap-4 group","data-testid":"button-page-cover-select-pix",children:[e.jsx("div",{className:"w-12 h-12 rounded-lg bg-green-500/10 flex items-center justify-center shrink-0",children:e.jsx(Ca,{className:"w-6 h-6 text-green-400"})}),e.jsxs("div",{className:"text-left flex-1",children:[e.jsx("p",{className:"font-semibold text-white text-base",children:"PIX"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Aprovação imediata"})]}),e.jsx(tt,{variant:"outline",className:"text-xs border-green-500/30 text-green-400 shrink-0",children:"Instantâneo"})]}),e.jsxs("button",{onClick:()=>Tt("card"),className:"w-full p-4 rounded-xl border border-white/10 hover:border-primary/50 bg-white/5 hover:bg-white/10 transition-all flex items-center gap-4 group","data-testid":"button-page-cover-select-card",children:[e.jsx("div",{className:"w-12 h-12 rounded-lg bg-blue-500/10 flex items-center justify-center shrink-0",children:e.jsx(Da,{className:"w-6 h-6 text-blue-400"})}),e.jsxs("div",{className:"text-left flex-1",children:[e.jsx("p",{className:"font-semibold text-white text-base",children:"Cartão de Crédito"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Visa, Mastercard, Elo..."})]}),e.jsx(tt,{variant:"outline",className:"text-xs border-blue-500/30 text-blue-400 shrink-0",children:"Seguro"})]}),(()=>{const t=Math.round(G*100),s=Be!==null,m=s&&Be>=t;return e.jsxs("button",{onClick:()=>{Me||!s||(m?Tt("credits"):u("/creditos"))},className:`w-full p-4 rounded-xl border-2 transition-all flex items-center gap-4 group relative overflow-hidden ${Me||!s?"border-amber-500/10 bg-gradient-to-r from-amber-950/20 to-amber-900/10 cursor-wait":m?"border-amber-500/30 hover:border-amber-400/50 bg-gradient-to-r from-amber-950/30 via-amber-900/20 to-amber-950/10 hover:from-amber-950/40 hover:via-amber-900/30 hover:to-amber-950/20 cursor-pointer shadow-[0_0_20px_rgba(245,158,11,0.08)] hover:shadow-[0_0_30px_rgba(245,158,11,0.15)]":"border-amber-500/15 hover:border-amber-500/25 bg-gradient-to-r from-amber-950/15 to-transparent hover:from-amber-950/25 cursor-pointer"}`,"data-testid":"button-page-cover-select-credits",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-gradient-to-br from-amber-900/40 to-amber-800/20 border border-amber-500/10 flex items-center justify-center shrink-0",children:e.jsx(Na,{size:"lg"})}),e.jsxs("div",{className:"text-left flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-amber-100 text-sm uppercase tracking-wide",children:"Créditos"}),!Me&&s&&e.jsx("span",{className:"text-lg font-bold text-amber-300 tabular-nums",children:Be.toLocaleString("pt-BR")})]}),e.jsx("p",{className:"text-xs text-amber-400/60 mt-0.5",children:Me||!s?"Carregando saldo...":m?`Saldo equivalente a ${p(Be/100)} · Pagamento instantâneo`:`Faltam ${(t-Be).toLocaleString("pt-BR")} créditos (${p((t-Be)/100)}) · Comprar mais`})]}),e.jsx("div",{className:`shrink-0 px-3 py-1.5 rounded-lg text-xs font-semibold transition-all ${Me||!s?"bg-amber-500/10 text-amber-400/50":m?"bg-gradient-to-r from-amber-500 to-amber-600 text-amber-950 shadow-[0_0_10px_rgba(245,158,11,0.3)]":"bg-
1amber-500/10 border border-amber-500/20 text-amber-400"}`,children:Me||!s?e.jsx(C,{className:"w-3 h-3 animate-spin"}):m?"Pagar":"Comprar"})]})})()]}),e.jsxs("button",{onClick:()=>f(2.5),className:"flex items-center gap-2 text-sm text-muted-foreground hover:text-white transition-colors mx-auto mt-3","data-testid":"button-page-cover-back-step2",children:[e.jsx(jt,{className:"w-4 h-4"}),"Voltar"]})]}),!xe&&!S&&e.jsxs("p",{className:"text-xs text-center text-muted-foreground mt-4",children:["Pagamento processado ",e.jsx("span",{onClick:()=>Tt("beta"),className:"cursor-default select-none",children:"com"})," segurança"]})]})]}),ut&&!N&&e.jsxs("div",{className:"space-y-4","data-testid":"section-existing-covers",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-white","data-testid":"text-covers-heading",children:"Suas Capas"}),e.jsx("p",{className:"text-base text-muted-foreground mt-1",children:(()=>{const t=V.filter(s=>s.imageUrl&&s.imageUrl.trim().length>0).length;return N?`${Math.min(he,t)} capa${he!==1?"s":""} anterior${he!==1?"es":""}`:`${t} capa${t!==1?"s":""} gerada${t!==1?"s":""}`})()})]}),!N&&e.jsxs(T,{variant:"outline",onClick:()=>{Oe(!0),f(2)},className:"border-white/10 hover:bg-white/10 text-white","data-testid":"button-generate-new-covers",children:[e.jsx(F,{className:"w-4 h-4 mr-2"}),"Gerar Novas Capas"]})]}),St&&e.jsxs("div",{className:"flex items-center gap-3 rounded-xl bg-primary/10 border border-primary/20 p-3 mb-2 animate-in fade-in slide-in-from-top-2","data-testid":"adjustment-generating-banner",children:[e.jsx(C,{className:"w-5 h-5 animate-spin text-primary shrink-0"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-semibold text-primary",children:[$e?.status==="partial"?"Lote parcialmente pronto":"Lote em geração"," (",Ke,"/",qe,")"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Cada opção aparece na galeria assim que ficar pronta"})]})]}),$t&&!Et&&e.jsxs("div",{className:"flex items-center gap-3 rounded-xl bg-amber-500/10 border border-amber-500/20 p-3 mb-2","data-testid":"adjustment-batch-finalizing-banner",children:[e.jsx(C,{className:"w-5 h-5 animate-spin text-amber-300 shrink-0"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-semibold text-amber-200",children:["Finalizando sua galeria (",Xe.visible,"/",qe,")"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"O lote está salvo e suas opções aparecerão aqui automaticamente. Você não precisa comprar novamente."})]})]}),Et&&e.jsxs("div",{className:"flex items-center gap-3 rounded-xl bg-emerald-500/10 border border-emerald-500/20 p-3 mb-2","data-testid":"adjustment-batch-completed-banner",children:[e.jsx(Te,{className:"w-5 h-5 text-emerald-400 shrink-0"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-semibold text-emerald-300",children:["Lote de ajuste concluído (",Ke,"/",qe,")"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"As 2 opções mais recentes estão destacadas na galeria."})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[(()=>{const t=V.filter(s=>s.imageUrl&&s.imageUrl.trim().length>0);if(N){const s=Math.min(Math.max(0,t.length-he),4);return t.slice(s)}return t})().map(t=>e.jsxs("div",{className:`group relative rounded-2xl border overflow-hidden transition-all duration-200 ${t.selected?"border-primary ring-2 ring-primary/30 shadow-lg shadow-primary/10":ia.has(t.id)?"border-primary/60 ring-1 ring-primary/20 shadow-lg shadow-primary/5":"border-white/10 hover:border-white/20"}`,"data-testid":`card-cover-${t.id}`,children:[e.jsxs("div",{className:"aspect-[5/8] relative cursor-pointer",onClick:()=>ye(t.id),children:[e.jsx(Dt,{src:t.imageUrl,alt:t.style||"Capa",className:"w-full h-full object-cover",thumbWidth:520}),t.selected&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(tt,{className:"bg-primary text-white text-[10px] shadow-lg","data-testid":`badge-selected-${t.id}`,children:[e.jsx(Te,{className:"w-3 h-3 mr-1"}),"Selecionada"]}
1)}),ia.has(t.id)&&!t.selected&&e.jsx("div",{className:"absolute top-2 left-2",children:e.jsxs(tt,{className:"bg-primary/90 text-white text-[10px] shadow-lg","data-testid":`badge-latest-adjustment-${t.id}`,children:[e.jsx(F,{className:"w-3 h-3 mr-1"}),"Nova opção"]})}),e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors flex items-center justify-center",children:e.jsx("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx("div",{className:"w-10 h-10 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center",children:e.jsx(ks,{className:"w-5 h-5 text-white"})})})}),e.jsxs("div",{className:"absolute bottom-2 left-2 right-2 flex items-center justify-between opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx("span",{className:"text-xs text-white font-medium",children:t.style?at.find(s=>s.id===t.style)?.label||t.style:"Capa"}),e.jsx("button",{onClick:s=>{s.stopPropagation(),Ta(t.imageUrl,E?.title||"capa",()=>n({title:"Não foi possível processar a capa para formato KDP",description:"Tente novamente.",variant:"destructive"}))},className:"w-7 h-7 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center hover:bg-white/40 transition-colors","data-testid":`button-download-cover-${t.id}`,children:e.jsx(Ea,{className:"w-3.5 h-3.5 text-white"})})]})]}),e.jsx("div",{className:"p-2",children:t.selected?e.jsxs("div",{className:"flex items-center justify-center gap-1.5 py-1.5 text-primary text-xs font-medium","data-testid":`text-cover-selected-${t.id}`,children:[e.jsx(Te,{className:"w-3.5 h-3.5"}),"Capa Selecionada"]}):e.jsxs(T,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground hover:text-white hover:bg-white/10",onClick:()=>ba(t.id),"data-testid":`button-select-cover-${t.id}`,children:[e.jsx(Te,{className:"w-3.5 h-3.5 mr-1.5"}),"Selecionar Essa"]})})]},t.id)),St&&(()=>{const t=Math.max(0,qe-Ke);return Array.from({length:t}).map((s,m)=>e.jsxs("div",{className:"rounded-2xl border border-primary/20 overflow-hidden bg-gradient-to-b from-primary/5 to-transparent animate-in fade-in zoom-in-95",style:{animationDelay:`${m*100}ms`},"data-testid":`adj-skeleton-cover-${m}`,children:[e.jsxs("div",{className:"aspect-[5/8] relative flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-primary/5 via-transparent to-primary/[0.02]"}),e.jsxs("div",{className:"relative flex flex-col items-center gap-3",children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-primary/10 flex items-center justify-center animate-pulse",children:e.jsx(F,{className:"w-6 h-6 text-primary/40"})}),e.jsxs("div",{className:"space-y-2 w-3/4",children:[e.jsx("div",{className:"h-2.5 bg-white/[0.06] rounded-full animate-pulse",style:{animationDelay:`${m*150}ms`}}),e.jsx("div",{className:"h-2 bg-white/[0.04] rounded-full w-2/3 mx-auto animate-pulse",style:{animationDelay:`${m*150+75}ms`}})]}),e.jsxs("p",{className:"text-[10px] text-primary/60 mt-1 font-medium",children:["Ajuste ",String.fromCharCode(65+m),"..."]})]})]}),e.jsx("div",{className:"p-2 text-center",children:e.jsx("span",{className:"text-xs text-muted-foreground/50",children:"Gerando..."})})]},`adj-skeleton-${m}`))})()]}),e.jsx("div",{className:"flex justify-center pt-2",children:e.jsxs("button",{onClick:()=>Je.current?.click(),disabled:Ce,className:"text-xs text-muted-foreground/50 hover:text-muted-foreground/80 transition-colors flex items-center gap-1.5 py-1","data-testid":"button-upload-custom-cover",children:[Ce?e.jsx(C,{className:"w-3 h-3 animate-spin"}):e.jsx(zt,{className:"w-3 h-3"}),Ce?"Enviando...":"Já tenho uma capa"]})})]}),ut&&la&&(()=>{const t=V?.find(s=>s.id===la);return t?.imageUrl?e.jsx($s,{coverId:t.id,coverImageUrl:t.imageUrl,bookTitle:H||"Meu Livro",bookId:a,initialAdjustments:t.userAdjustments??null}):null})(),e.jsx(ls,{open:!!A,onOpenChange:t=>{t||(ye(null),Ae(null))},children:e.jsxs(cs,{className:"max-w-3xl w-[96%] p-0 bg-background/95 backdrop-blur-xl border-white/10 rounded-2xl overflow-hidden [&>button]:hidden max-h-[95dvh] flex flex-col",children:[e.jsx(ds,{className:"sr-only",children:"Visualizar Capa"}),A&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"md:hidden flex items-center justify-between px-4 py-3 border-b border-white/10 bg-background/95 backdrop-blur-xl shrink-0",children:[e.jsxs("div",{className:"min-w-0 flex-1 pr-3",children:[e.jsx("h3",{className:"text-base font-bold text-white truncate",children:Ge?"Editar Capa":"Visualizar Capa"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:A.style?at.find(t=>
1t.id===A.style)?.label||A.style:"Capa profissional"})]}),e.jsx("button",{onClick:()=>{ye(null),Ae(null)},className:"w-9 h-9 rounded-full bg-white/10 flex items-center justify-center hover:bg-white/20 transition-colors shrink-0","data-testid":"button-close-preview-mobile","aria-label":"Fechar",children:e.jsx(Yt,{className:"w-4 h-4 text-white"})})]}),e.jsxs("div",{className:"flex flex-col md:flex-row flex-1 min-h-0",children:[e.jsx("div",{className:"md:w-1/2 p-4 md:p-6 flex items-center justify-center bg-black/30 overflow-y-auto md:overflow-visible",children:e.jsxs("div",{className:"relative w-full max-w-[220px] md:max-w-[300px] mx-auto",children:[e.jsx(Dt,{src:A.imageUrl,alt:A.style||"Capa",className:"w-full aspect-[5/8] object-cover rounded-xl shadow-2xl","data-testid":"img-preview-cover"}),A.selected&&e.jsx("div",{className:"absolute top-3 right-3",children:e.jsxs(tt,{className:"bg-primary text-white text-xs shadow-lg","data-testid":"badge-preview-selected",children:[e.jsx(Te,{className:"w-3.5 h-3.5 mr-1"}),"Selecionada"]})})]})}),e.jsxs("div",{className:"md:w-1/2 flex flex-col min-h-0 shrink-0 md:shrink md:flex-1",children:[e.jsxs("div",{className:"hidden md:flex items-center justify-between p-6 pb-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-bold text-white",children:Ge?"Editar Capa":"Visualizar Capa"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:A.style?at.find(t=>t.id===A.style)?.label||A.style:"Capa profissional"})]}),e.jsx("button",{onClick:()=>{ye(null),Ae(null)},className:"w-8 h-8 rounded-full bg-white/10 flex items-center justify-center hover:bg-white/20 transition-colors","data-testid":"button-close-preview",children:e.jsx(Yt,{className:"w-4 h-4 text-white"})})]}),Ge?e.jsx("div",{className:"flex-1 flex flex-col min-h-0 overflow-hidden",children:e.jsx(qs,{coverId:Ge,bookId:E?.id||"",bookTitle:E?.title||"",onNewCover:()=>{U(),ye(null),Ae(null)},onPaymentSuccess:Qa})}):e.jsx(e.Fragment,{children:e.jsxs("div",{className:"px-4 py-3 md:px-6 md:pb-6 md:pt-0 border-t border-white/10 md:border-t-0 bg-background/98 md:bg-transparent backdrop-blur-xl md:backdrop-blur-none shrink-0",children:[e.jsxs("div",{className:"space-y-2.5 md:space-y-3",children:[!A.selected&&e.jsxs(T,{onClick:()=>{ba(A.id),ye(null)},className:"w-full h-12 rounded-xl bg-primary hover:bg-primary/90 text-white font-semibold shadow-lg shadow-primary/25","data-testid":"button-preview-select",children:[e.jsx(Te,{className:"w-4 h-4 mr-2"}),"Selecionar Essa Capa"]}),A.selected&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-3 rounded-xl bg-primary/10 border border-primary/20",children:[e.jsx(Te,{className:"w-4 h-4 text-primary"}),e.jsx("span",{className:"text-sm font-semibold text-primary",children:"Esta capa já está selecionada"})]}),!A.readOnlyCanonical&&e.jsxs(T,{variant:"outline",onClick:()=>Ae(A.id),className:"w-full h-12 rounded-xl border-white/10 hover:bg-white/10 text-white font-semibold","data-testid":"button-preview-edit",children:[e.jsx(Ua,{className:"w-4 h-4 mr-2"}),"Editar Essa Capa"]}),e.jsxs("button",{onClick:()=>Ta(A.imageUrl,E?.title||"capa",()=>n({title:"Não foi possível processar a capa para formato KDP",description:"Tente novamente.",variant:"destructive"})),className:"flex items-center justify-center gap-2 w-full h-12 rounded-xl border border-white/10 hover:bg-white/10 text-white font-semibold transition-colors","data-testid":"button-preview-download",children:[e.jsx(Ea,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Baixar para Amazon KDP (1600×2560)"}),e.jsx("span",{className:"sm:hidden",children:"Baixar para Amazon KDP"})]})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground text-center mt-3 md:mt-4",children:"Resolução otimizada para Amazon KDP e plataformas de publicação"})]})})]})]})]})]})})]}),e.jsx("div",{className:"hidden lg:block fixed right-4 top-20 w-[300px] max-h-[calc(100vh-6rem)] overflow-y-auto z-30",children:e.jsx(js,{bookId:a,currentStep:"cover",inProgressSteps:{cover:N}})})]})})]}),e.jsx(bs,{bookId:a,currentStep:"cover"})]})}
1export{gr 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.