PageSourceSearch

https://drophighlight.com/assets/SuperadminCoverMaintenance-CuwSELXQ.js

js drophighlight.com collected 2026-09-30 06:38:23 UTC 88,831 bytes, 6 lines download raw bytes

1import{p as Ps,s as ge,a as cs,r as C,J as w,j as e,C as ze,h as Re,i as Te,k as ms,l as Ee,o as X,bQ as Oe,ax as Ds,ag as ys,B as U,I as as,ah as Cs,aj as _s,R as Xe,D as Je,b as Qe,c as Ye,d as Ze,e as es,aa as Os,aN as Bs,Q as Ws,U as Fs,V as Ls,W as Us,Y as Gs,Z as qs,_ as Hs,$ as Ks}from"./index-P0N1Je5T.js";import{L as gs}from"./label-CoHN_xq2.js";import{A as Be,b as rs,a as We}from"./alert-BjIlbniu.js";import{C as Xs,b as Js,a as Qs}from"./collapsible-CaFg5345.js";import{T as Ss,a as Vs,b as ns,c as ue,d as ks,e as me}from"./table-DyXCBCTZ.js";import{C as ts}from"./checkbox-wSZ1kz90.js";import{P as is}from"./progress-BO5nxn_Q.js";import{THUMBNAIL_CONFIGS as ss,createUnifiedThumbnail as Ys}from"./mediaUtils-FkLO5AK0.js";import{s as xs,f as hs,P as Ce,C as Ns,S as Zs}from"./canvasRegenerationAudit-ClzSuWls.js";import{T as $e}from"./triangle-alert-Dfdm1-MX.js";import{C as Se}from"./circle-check-CYFFE5P4.js";import{L as ve}from"./loader-circle-BQs4OzSl.js";import{C as Ae}from"./circle-x-C-UIuONs.js";import{P as ps}from"./play-B168p-g_.js";import{P as Is}from"./pause-DHdaaDAk.js";import{U as ea}from"./upload-kDtOV4MB.js";import{D as sa}from"./download-JbV5bimG.js";import{S as Ne}from"./search-md8nLj6W.js";import{I as ls}from"./image-off-CV_s2Uwh.js";import{I as aa}from"./info-Bc8MGwTj.js";import{H as ra}from"./hard-drive-Db7S_XsL.js";import{T as us}from"./trash-2-Dwmr_5Bh.js";/**
2 * @license lucide-react v0.462.0 - ISC
3 *
4 * This source code is licensed under the ISC license.
5 * See the LICENSE file in the root directory of this source tree.
6 */const bs=Ps("CircleArrowDown",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 8v8",key:"napkw2"}],["path",{d:"m8 12 4 4 4-4",key:"k98ssh"}]]),na={thumbnail:ss.admin,medium:ss.medium,large:ss.large,social:ss.social};function Ms(s){if(!s)return null;const f=s.match(/cover_([a-f0-9-]{36})\.(jpg|jpeg|png|webp|gif)/i);if(f)return f[1];const _=s.match(/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/i);return _?_[1]:null}function ta(s,f){return{thumbnail:`${s}/covers/thumbnail/thumbnail_cover_${f}.webp`,medium:`${s}/covers/medium/medium_cover_${f}.webp`,large:`${s}/covers/large/large_cover_${f}.webp`,social:`${s}/covers/social_cover_${f}.jpg`}}async function ia(s,f){try{const{data:_,error:t}=await ge.storage.from(s).list(f.substring(0,f.lastIndexOf("/")),{search:f.substring(f.lastIndexOf("/")+1)});if(t)return!1;const d=f.substring(f.lastIndexOf("/")+1);return(_==null?void 0:_.some(c=>c.name===d))||!1}catch{return!1}}function ws(s,f,_){return new Promise((t,d)=>{const c=setTimeout(()=>{d(new Error(`Timeout: ${_} exceeded ${f/1e3}s`))},f);s.then(b=>{clearTimeout(c),t(b)}).catch(b=>{clearTimeout(c),d(b)})})}async function la(s){let t=null;for(let d=1;d<=3;d++){const c=new AbortController,b=setTimeout(()=>c.abort(),6e4);try{console.log(`[Canvas Cover] Download attempt ${d}/3...`);const x=await fetch(s,{signal:c.signal,cache:"no-store"});if(clearTimeout(b),x.ok){const O=await x.blob();return console.log(`[Canvas Cover] Download complete: ${(O.size/1024/1024).toFixed(2)} MB`),O}if(!(x.status===408||x.status===429||x.status>=500))throw new Error(`Failed to download image: HTTP ${x.status}`);t=new Error(`Download HTTP ${x.status}`),console.warn(`[Canvas Cover] Download retry ${d}/3: HTTP ${x.status}`)}catch(x){clearTimeout(b),t=x;const S=(x==null?void 0:x.name)==="AbortError"?`timeout ${6e4/1e3}s`:(x==null?void 0:x.message)||"network error";if(d===3)break;console.warn(`[Canvas Cover] Download retry ${d}/3: ${S}`)}await new Promise(x=>setTimeout(x,d===1?1e3:3e3))}throw t instanceof Error?t:new Error("Download failed after retries")}function oa(s,f){return new File([s],f,{type:s.type||"image/jpeg"})}async function ca(s,f,_,t){const{data:d,error:c}=await ge.storage.from(s).createSignedUploadUrl(f,{upsert:!0});if(c||!d)throw new Error(`Failed to create signed URL: ${c==null?void 0:c.message}`);const b=3;let x=null;for(let S=1;S<=b;S++){const O=new AbortController,l=setTimeout(()=>O.abort(),25e3);try{const a=await fetch(d.signedUrl,{method:"PUT",body:_,headers:{"Content-Type":t},signal:O.signal});if(clearTimeout(l),a.ok){const{data:h}=ge.storage.from(s).getPublicUrl(f);return h.publicUrl}if(!(a.status===408||a.status===429||a.status>=500))throw new Error(`Upload failed: ${a.status}`);x=new Error(`Upload HTTP ${a.status}`),console.warn(`[Canvas Cover] Upload retry ${S}/${b} for ${f}: HTTP ${a.status}`)}catch(a){clearTimeout(l),x=a;const L=(a==null?void 0:a.name)==="AbortError"?"timeout 25s":(a==null?void 0:a.message)||"network error";if(S===b)break;console.warn(`[Canvas Cover] Upload retry ${S}/${b} for ${f}: ${L}`)}await new Promise(a=>setTimeout(a,S===1?1e3:3e3))}throw x instanceof Error?x:new Error("Upload failed after retries")}async function da(s,f,_={}){const{force:t=!1,dryRun:d=!1,versionsToRegenerate:c,onVersionProgress:b}=_,x=Ms(s);if(!x)return{success:!1,versions:{},uploadedPaths:[],error:"Could not extract UUID from cover URL"};const S=ta(f,x),O=[],l={thumbnail:!1,medium:!1,large:!1,social:!1},a=Object.entries(na),L=c?a.filter(([h])=>c.includes(h)):a;if(L.length===0)return{success:!0,versions:l,uploadedPaths:O,error:"No versions to process"};console.log(`[Canvas Cover] Will process ${L.length} version(s): ${L.map(([h])=>h).join(", ")}`);
6try{const h=await la(s),g=oa(h,`cover_${x}.jpg`);console.log(`[Canvas Cover] Downloaded original: ${s}, size: ${h.size}`);for(const[y,A]of L){const H=y,te=S[H];if(!t&&await ia("thumbnails",te)){console.log(`[Canvas Cover] Skipping ${y} - already exists`),l[y]=!0;continue}try{b==null||b({version:H,step:"processing",versions:l}),console.log(`[Canvas Cover] Processing ${y} (${A.maxWidth}x${A.maxHeight})...`);const{thumbnail:ee}=await ws(Ys(g,A),6e4,`Canvas processing ${y}`);if(!ee){console.warn(`[Canvas Cover] Failed to generate ${y} - no output`);continue}const ie=A.format==="webp"?"image/webp":"image/jpeg";console.log(`[Canvas Cover] Generated ${y}: ${(ee.size/1024).toFixed(1)} KB`),d||(b==null||b({version:H,step:"uploading",versions:l}),await ws(ca("thumbnails",te,ee,ie),9e4,`Upload ${y}`),O.push(te),console.log(`[Canvas Cover] Uploaded ${y} to ${te}`)),l[y]=!0,b==null||b({version:H,step:"done",versions:l})}catch(ee){console.error(`[Canvas Cover] Error on ${y}:`,ee.message)}}return{success:L.map(([y])=>y).every(y=>l[y]),versions:l,uploadedPaths:O}}catch(h){return console.error("[Canvas Cover] Error processing cover:",h),{success:!1,versions:l,uploadedPaths:O,error:h.message}}}async function zs(s,f,_={}){const{force:t=!1,dryRun:d=!1,versionsToRegenerate:c,onVersionProgress:b}=_;try{const x=await da(s.cover_image_url,f,{force:t,dryRun:d,versionsToRegenerate:c,onVersionProgress:b});if(!d&&x.versions.social&&x.uploadedPaths.some(S=>S.includes("social"))){const S=Ms(s.cover_image_url);if(S){const O=`${f}/covers/social_cover_${S}.jpg`,{data:l}=ge.storage.from("thumbnails").getPublicUrl(O);await ge.from("galleries").update({social_cover_url:l.publicUrl}).eq("id",s.id)}}return{galleryId:s.id,galleryTitle:s.title,success:x.success,versions:{thumbnail:x.versions.thumbnail||!1,medium:x.versions.medium||!1,large:x.versions.large||!1,social:x.versions.social||!1},uploadedPaths:x.uploadedPaths,error:x.error}}catch(x){return{galleryId:s.id,galleryTitle:s.title,success:!1,versions:{thumbnail:!1,medium:!1,large:!1,social:!1},error:x.message}}}async function ua(s,f={}){var h;const{force:_=!1,dryRun:t=!1,concurrency:d=1,onProgress:c,shouldCancel:b,delayBetweenItems:x=300}=f,{data:S,error:O}=await ge.from("galleries").select("id, title, cover_image_url").eq("company_id",s).not("cover_image_url","is",null);if(O||!S)throw new Error(`Failed to fetch galleries: ${O==null?void 0:O.message}`);const l=S.map(g=>({id:g.id,title:g.title,status:"pending"})),a={total:S.length,processed:0,success:0,errors:0,skipped:0,errorDetails:[],startTime:Date.now(),galleries:l,currentVersions:{thumbnail:!1,medium:!1,large:!1,social:!1}},L=await xs({companyId:s,kind:"covers",total:S.length,toProcess:S.length,force:_,dryRun:t});c==null||c(a);for(let g=0;g<S.length;g++){if(b!=null&&b()){console.log("[Canvas Batch] Cancelled by user");break}const k=S[g];a.currentGallery=k.title,a.currentGalleryId=k.id,a.currentStep="downloading",a.
6currentVersion=void 0,a.currentVersions={thumbnail:!1,medium:!1,large:!1,social:!1},a.galleries&&(a.galleries=a.galleries.map((z,y)=>y===g?{...z,status:"processing"}:z)),c==null||c({...a});try{const z=await zs(k,s,{force:_,dryRun:t,onVersionProgress:y=>{a.currentVersion=y.version,a.currentStep=y.step,a.currentVersions=y.versions,c==null||c(a)}});if(a.processed++,z.success){a.success++;const y=(((h=z.uploadedPaths)==null?void 0:h.length)??0)===0;y&&a.skipped++,a.galleries&&(a.galleries=a.galleries.map((A,H)=>H===g?{...A,status:y?"skipped":"done"}:A))}else a.errors++,a.galleries&&(a.galleries=a.galleries.map((y,A)=>A===g?{...y,status:"error"}:y)),z.error&&a.errorDetails.push({galleryId:k.id,galleryTitle:k.title,error:z.error})}catch(z){a.processed++,a.errors++,a.galleries&&(a.galleries=a.galleries.map((y,A)=>A===g?{...y,status:"error"}:y)),a.errorDetails.push({galleryId:k.id,galleryTitle:k.title,error:z.message})}c==null||c({...a}),g<S.length-1&&x>0&&await new Promise(z=>setTimeout(z,x))}return a.currentGallery=void 0,a.currentGalleryId=void 0,a.currentVersion=void 0,a.currentStep=void 0,c==null||c(a),await hs(L,{processed:a.processed,success:a.success,errors:a.errors,status:b!=null&&b()?"aborted":"completed",errorDetails:a.errorDetails.map(g=>({id:g.galleryId,title:g.galleryTitle,error:g.error}))}),a}async function os(s,f,_={}){var L;const{force:t=!0,dryRun:d=!1,onProgress:c,shouldCancel:b,delayBetweenItems:x=300}=_,S=new Set;s.forEach(h=>{h.versionsToRegenerate?h.versionsToRegenerate.forEach(g=>S.add(g)):["thumbnail","medium","large","social"].forEach(g=>S.add(g))});const O=s.map(h=>({id:h.id,title:h.title,status:"pending"})),l={total:s.length,processed:0,success:0,errors:0,skipped:0,errorDetails:[],targetVersions:Array.from(S),startTime:Date.now(),galleries:O,currentVersions:{thumbnail:!1,medium:!1,large:!1,social:!1}},a=await xs({companyId:f,kind:"covers",total:s.length,toProcess:s.length,force:t,dryRun:d});c==null||c(l);for(let h=0;h<s.length;h++){if(b!=null&&b()){console.log("[Canvas Selected] Cancelled by user");break}const g=s[h];l.currentGallery=g.title,l.currentGalleryId=g.id,l.currentStep="downloading",l.currentVersion=void 0,l.currentVersions={thumbnail:!1,medium:!1,large:!1,social:!1},l.galleries&&(l.galleries=l.galleries.map((k,z)=>z===h?{...k,status:"processing"}:k)),c==null||c({...l});try{const k=await zs(g,f,{force:t,dryRun:d,versionsToRegenerate:g.versionsToRegenerate,onVersionProgress:z=>{l.currentVersion=z.version,l.currentStep=z.step,l.currentVersions=z.versions,c==null||c({...l})}});if(l.processed++,k.success){l.success++;const z=(((L=k.uploadedPaths)==null?void 0:L.length)??0)===0;z&&l.skipped++,l.galleries&&(l.galleries=l.galleries.map((y,A)=>A===h?{...y,status:z?"skipped":"done"}:y))}else l.errors++,l.galleries&&(l.galleries=l.galleries.map((z,y)=>y===h?{...z,status:"error"}:z)),k.error&&l.errorDetails.push({galleryId:g.id,galleryTitle:g.title,error:k.error})}catch(k){l.processed++,l.errors++,l.galleries&&(l.galleries=l.galleries.map((z,y)=>y===h?{...z,status:"error"}:z)),l.errorDetails.push({galleryId:g.id,galleryTitle:g.title,error:k.message})}c==null||c({...l}),h<s.length-1&&x>0&&await new Promise(k=>setTimeout(k,x))}return l.currentGallery=void 0,l.currentGalleryId=void 0,l.currentVersion=void 0,l.currentStep=void 0,c==null||c({...l}),await hs(a,{processed:l.processed,success:l.success,errors:l.errors,status:b!=null&&b()?"aborted":"completed",errorDetails:l.errorDetails.map(h=>({id:h.galleryId,title:h.galleryTitle,error:h.error}))}),l}const ma=({companyId:s,companyName:f,totalGalleries:_,onComplete:t})=>{const{t:d}=cs(),[c,b]=C.useState(!1),[x,S]=C.useState(!1),[O,l]=C.useState(!0),[a,L]=C.useState(null),[h,g]=C.useState(null),k=C.useRef(!1),z=i=>{const B=Math.floor(i/1e3),le=Math.floor(B/60),ce=B%60;return le>0?`${le}m ${ce}s`:`${B}s`},y=()=>{var le;if(!a)return{icon:null,text:d("superadmin.canvasRegeneration.progress.readyToStart")};if(!a.currentStep&&!c)return{icon:null,text:d("superadmin.canvasRegeneration.progress.readyToStart")};if(!a.currentStep&&c)return{icon:e.jsx(ve,{className:"w-3 h-3 animate-spin"}),text:d("superadmin.canvasRegeneration.progress.preparing")};const i=a.currentGallery||"",B=((le=a.currentVersion)==null?void 0:le.toUpperCase())||"";switch(a.currentStep){case"downloading":return{icon:e.jsx(sa,{className:"w-3 h-3 animate-pulse text-blue-500"}),text:d("superadmin.canvasRegeneration.progress.downloading").replace("{gallery}",i)};case"processing":return{icon:e.jsx(as,{className:"w-3 h-3 animate-pulse text-purple-500"}),text:d("superadmin.canvasRegeneration.progress.processing").replace("{version}",B).replace("{gallery}",i)};case"uploading":return{icon:e.jsx(ea,{className:"w-3 h-3 animate-pulse text-green-500"}),text:d("superadmin.canvasRegeneration.progress.uploading").replace("{version}",B).replace("{gallery}",i)};default:return{icon:e.jsx(ve,{className:"w-3 h-3 animate-spin"}),text:i||d("superadmin.canvasRegeneration.progress.preparing")}}},A=C.useCallback(async()=>
6{if(!c){k.current=!1,b(!0),g(null),L(null);try{w.info(d("superadmin.canvasRegeneration.messages.starting").replace("{company}",f));const i=await ua(s,{force:O,dryRun:x,concurrency:1,delayBetweenItems:500,onProgress:L,shouldCancel:()=>k.current});k.current?w.info(d("superadmin.canvasRegeneration.messages.cancelled").replace("{success}",String(i.success))):i.errors===0?w.success(d("superadmin.canvasRegeneration.messages.success").replace("{count}",String(i.success))):w.warning(d("superadmin.canvasRegeneration.messages.partial").replace("{success}",String(i.success)).replace("{errors}",String(i.errors))),t==null||t()}catch(i){console.error("[Canvas Regeneration] Error:",i),g(i.message),w.error(d("superadmin.canvasRegeneration.messages.error").replace("{message}",i.message))}finally{b(!1)}}},[s,f,O,x,c,t,d]),H=C.useCallback(async()=>{var Q;if(c||!((Q=a==null?void 0:a.errorDetails)!=null&&Q.length))return;const i=a.errorDetails.map(Z=>Z.galleryId),{data:B,error:le}=await ge.from("galleries").select("id, title, cover_image_url").in("id",i);if(le||!B||B.length===0){w.error(`Falha ao recarregar galerias: ${(le==null?void 0:le.message)||"sem resultados"}`);return}const ce=B.filter(Z=>!!Z.cover_image_url).map(Z=>({id:Z.id,title:Z.title,cover_image_url:Z.cover_image_url}));if(ce.length===0){w.error("Galerias falhadas não possuem cover_image_url");return}k.current=!1,b(!0),g(null),L(null),w.info(`Retentando ${ce.length} cover(s) falha(s)...`);try{const Z=await os(ce,s,{force:!0,dryRun:x,delayBetweenItems:500,onProgress:L,shouldCancel:()=>k.current});Z.errors===0?w.success(`Retry concluído: ${Z.success} reprocessadas`):w.warning(`Retry parcial: ${Z.success} OK / ${Z.errors} erros`),t==null||t()}catch(Z){g(Z.message),w.error(`Erro no retry: ${Z.message}`)}finally{b(!1)}},[s,x,c,t,a]),te=C.useCallback(()=>{k.current=!0},[]),ee=a&&a.total>0?Math.round(a.processed/a.total*100):0,ie=y();return e.jsxs(ze,{className:"border-2 border-purple-500/30 bg-purple-500/5",children:[e.jsxs(Re,{className:"pb-3",children:[e.jsxs(Te,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Ce,{className:"h-5 w-5 text-purple-500"}),d("superadmin.canvasRegeneration.title")]}),e.jsx(ms,{children:d("superadmin.canvasRegeneration.description")})]}),e.jsxs(Ee,{className:"space-y-4",children:[h&&e.jsxs(Be,{variant:"destructive",children:[e.jsx($e,{className:"h-4 w-4"}),e.jsx(rs,{children:d("superadmin.common.error")}),e.jsx(We,{children:h})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-3 text-sm",children:[e.jsxs("div",{className:"text-center p-2 bg-muted rounded-lg",children:[e.jsx("div",{className:"text-xl font-bold",children:_}),e.jsx("div",{className:"text-xs text-muted-foreground",children:d("superadmin.canvasRegeneration.stats.galleries")})]}),e.jsxs("div",{className:"text-center p-2 bg-muted rounded-lg",children:[e.jsx("div",{className:"text-xl font-bold text-green-600",children:(a==null?void 0:a.success)||0}),e.jsx("div",{className:"text-xs text-muted-foreground",children:d("superadmin.canvasRegeneration.stats.success")})]}),e.jsxs("div",{className:"text-center p-2 bg-muted rounded-lg",children:[e.jsx("div",{className:"text-xl font-bold text-slate-500",children:(a==null?void 0:a.skipped)||0}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Skipped (already OK)"})]}),e.jsxs("div",{className:"text-center p-2 bg-muted rounded-lg",children:[e.jsx("div",{className:"text-xl font-bold text-red-600",children:(a==null?void 0:a.errors)||0}),e.jsx("div",{className:"text-xs text-muted-foreground",children:d("superadmin.canvasRegeneration.stats.errors")})]})]}),(c||a)&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between items-center text-sm",children:[e.jsxs("span",{className:"text-muted-foreground flex items-center gap-2 truncate max-w-[80%]",children:[ie.icon,e.jsx("span",{className:"truncate",children:ie.text})]}),e.jsxs("span",{className:"font-medium",children:[ee,"%"]})]}),e.jsx(is,{value:ee,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[(a==null?void 0:a.processed)||0,"/",(a==null?void 0:a.total)||0," ",d("superadmin.canvasRegeneration.progress.processed")]}),(a==null?void 0:a.startTime)&&e.jsx("span",{children:z(Date.now()-a.startTime)})]}),c&&(a==null?void 0:a.currentVersions)&&e.jsxs("div",{className:"flex items-center gap-1.5 pt-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground mr-1",children:d("superadmin.canvasRegeneration.progress.versions")}),e.jsxs(X,{variant:a.currentVersions.thumbnail?"default":"outline",className:`text-[10px] px-1.5 py-0 h-5 ${a.currentVersion==="thumbnail"&&a.currentStep!=="done"?"animate-pulse border-purple-500 bg-purple-500/20":a.currentVersions.thumbnail?"bg-green-600":""}`,children:[a.currentVersions.thumbnail?"✓":""," thumb"]}),e.jsxs(X,{variant:a.currentVersions.medium?"default":"outline",className:`text-[10px] px-1.5 py-0 h-5 ${a.currentVersion==="medium"&&a.currentStep!=="done"?"animate-pulse border-purple-500 bg-purple-500/20":a.currentVersions.medium?"bg-green-600":""}`,children:[a.currentVersions.medium?"✓":""," med"]}),e.jsxs(X,{variant:a.currentVersions.large?"default":"outline",className:`text-[10px] px-1.5 py-0 h-5 ${a.currentVersion==="large"&&a.currentStep!=="done"?"animate-pulse border-purple-500 bg-purple-500/20":a.currentVersions.large?"bg-green-600":""}`,children:[a.currentVersions.large?"✓":""," lg"]}),e.jsxs(X,{variant:a.currentVersions.social?"default":"outline",className:`text-[10px] px-1.5 py-0 h-5 ${a.currentVersion==="social"&&a.currentStep!=="done"?"animate-pulse border-purple-500 bg-purple-500/20":a.currentVersions.social?"bg-green-600":""}`,children:[a.currentVersions.social?"✓":""," social"]})]})]}),(a==null?void 0:a.galleries)&&a.galleries.length>0&&(c||a.processed>0)&&e.jsxs("div",{className:"pt-2 border-t",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-2",children:d("superadmin.canvasRegeneration.progress.galleryStatus")}),e.jsx(Oe,{className:"max-h-32 border rounded-md p-2 bg-muted/30",children:e.jsx("div",{className:"space-y-1",children:a.galleries.map(i=>e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[i.status==="done"&&e.jsx(Se,{className:"w-3 h-3 text-green-500 shrink-0"}),i.status==="processing"&&e.jsx(ve,{className:"w-3 h-3 animate-spin text-purple-500 shrink-0"}),i.status==="error"&&e.jsx(Ae,{className:"w-3 h-3 text-red-500 shrink-0"}),i.status==="pending"&&e.jsx(Ds,{className:"w-3 h-3 text-muted-foreground
6/50 shrink-0"}),e.jsx("span",{className:`truncate ${i.status==="processing"?"font-medium text-foreground":i.status==="done"?"text-green-600":i.status==="error"?"text-red-500":"text-muted-foreground"}`,children:i.title})]},i.id))})})]}),a&&a.errorDetails.length>0&&!c&&e.jsxs("div",{className:"pt-2 border-t",children:[e.jsxs("p",{className:"text-sm font-medium text-destructive mb-2",children:[d("superadmin.canvasRegeneration.galleriesWithError")," (",a.errorDetails.length,"):"]}),e.jsx(Oe,{className:"max-h-24",children:e.jsx("div",{className:"space-y-1 text-xs",children:a.errorDetails.map((i,B)=>e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Ae,{className:"w-3 h-3 text-destructive shrink-0"}),e.jsx("span",{className:"truncate",children:i.galleryTitle}),e.jsx("span",{className:"text-destructive shrink-0 truncate max-w-[150px]",children:i.error})]},B))})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 pt-2 border-t",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ys,{id:`canvas-dry-run-${s}`,checked:x,onCheckedChange:S,disabled:c}),e.jsx(gs,{htmlFor:`canvas-dry-run-${s}`,className:"text-sm",children:d("superadmin.canvasRegeneration.controls.simulation")})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ys,{id:`canvas-force-${s}`,checked:O,onCheckedChange:l,disabled:c}),e.jsx(gs,{htmlFor:`canvas-force-${s}`,className:"text-sm text-orange-600",children:d("superadmin.canvasRegeneration.controls.forceAll")})]}),c?e.jsxs(U,{onClick:te,variant:"destructive",size:"sm",children:[e.jsx(Is,{className:"w-4 h-4 mr-2"}),d("superadmin.canvasRegeneration.controls.cancel")]}):e.jsxs(U,{onClick:A,disabled:_===0,size:"sm",className:"bg-purple-600 hover:bg-purple-700",children:[e.jsx(ps,{className:"w-4 h-4 mr-2"}),d(x?"superadmin.canvasRegeneration.controls.simulateCanvas":"superadmin.canvasRegeneration.controls.regenerateCanvas")]}),a&&!c&&a.errorDetails.length>0&&e.jsxs(U,{onClick:H,variant:"outline",size:"sm",className:"border-orange-500 text-orange-700 hover:bg-orange-50",children:[e.jsx(ps,{className:"w-4 h-4 mr-2"}),"Retentar ",a.errorDetails.length," falha(s)"]}),a&&!c&&a.errors===0&&a.success>0&&e.jsxs(X,{variant:"default",className:"bg-green-600",children:[e.jsx(Se,{className:"w-3 h-3 mr-1"}),d("superadmin.canvasRegeneration.controls.completed")]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground pt-2 border-t",children:[e.jsxs("p",{children:["• ",d("superadmin.canvasRegeneration.info.thumbnail")]}),e.jsxs("p",{children:["• ",d("superadmin.canvasRegeneration.info.medium")]}),e.jsxs("p",{children:["• ",d("superadmin.canvasRegeneration.info.large")]}),e.jsxs("p",{children:["• ",d("superadmin.canvasRegeneration.info.social")]})]})]})]})},ga={thumbnail:{maxWidth:960,maxHeight:540},medium:{maxWidth:1920,maxHeight:1080},large:{maxWidth:2880,maxHeight:1620},social:{width:1200,height:630}};function pa({companyId:s,companyName:f,onClose:_}){const{t}=cs(),[d,c]=C.useState(!1),[b,x]=C.useState({current:0,total:0}),[S,O]=C.useState([]),[l,a]=C.useState(null),[L,h]=C.useState(null),[g,k]=C.useState(new Set),[z,y]=C.useState(!1),[A,H]=C.useState(null),te=async()=>{c(!0),h(null),O([]),a(null),x({current:0,total:0}),k(new Set);try{let u=[],D=null,W,se=!0,q=0;for(;se;){const{data:de,error:n}=await ge.functions.invoke("regenerate-cover-thumbnails",{body:{action:"deep-validate",companyId:s,deepValidationCursor:W}});if(n)throw new Error(n.message);if(!de.success)throw new Error(de.error||"Validation failed");u=de.galleries||[],D=de.summary||null,q=de.totalGalleries||0,se=de.hasMore||!1,W=de.nextCursor,x({current:u.length,total:q}),O([...u]),a(D)}const pe=((D==null?void 0:D.oversized)||0)+((D==null?void 0:D.undersized)||0)+((D==null?void 0:D.corrupted)||0);pe>0?w.warning(t("superadmin.deepValidation.messages.issues").replace("{count}",String(pe))):w.success(t("superadmin.deepValidation.messages.allCorrect"))}catch(u){console.error("[DeepValidation] Error:",u),h(u.message),w.error(t("superadmin.deepValidation.messages.error").replace("{message}",u.message))}finally{c(!1)}},ee=u=>{switch(u){case"valid":return e.jsx(Se,{className:"w-4 h-4 text-green-500"});case"oversized":return e.jsx(Ns,{className:"w-4 h-4 text-orange-500"});case"undersized":return e.jsx(bs,{className:"w-4 h-4 text-yellow-500"});case"corrupted":return e.jsx(ls,{className:"w-4 h-4 text-red-500"});case"missing":return e.jsx(Ae,{className:"w-4 h-4 text-muted-foreground"})}},ie=(u,D)=>{if(!u||!u.exists)return e.jsx("span",{className:"text-muted-foreground",children:"—"});if(!u.width||!u.height)return e.jsx("span",{className:"text-red-500",children:t("superadmin.deepValidation.status.error")});const W=ga[D],se="width"in W;let q;se?q=`${W.width}×${W.height}`:q=`≤${W.maxWidth}×${W.maxHeight}`;const pe=u.status==="oversized",de=u.status==="undersized";return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("span",{className:pe?"text-orange-600 font-medium":de?"text-yellow-600":"text-green-600",children:[u.width,"×",u.height]}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["(",q,")"]})]})},i=S.filter(u=>Object.values(u.versions).some(W=>W&&W.status!=="valid"&&W.status!=="missing")),B=S.filter(u=>Object.values(u.versions).every(W=>!W||W.status==="valid"||W.status==="missing")),le=()=>{g.size===i.length&&i.length>0?k(new Set):k(new Set(i.map(u=>u.galleryId)))},ce=u=>{const D=new Set(g);D.has(u)?D.delete(u):D.add(u),k(D)},Q=i.length>0&&g.size===i.length,Z=g.size>0&&g.size<i.length,fe=()=>{const u={thumbnail:0,medium:0,large:0,social:0};for(const D of g){const W=S.find(se=>se.galleryId===D);
6if(W)for(const[se,q]of Object.entries(W.versions))q&&["oversized","undersized","corrupted"].includes(q.status)&&u[se]++}return u},Pe=async()=>{if(g.size!==0){y(!0),H(null);try{const u=[];for(const se of g){const q=S.find(de=>de.galleryId===se);if(!q||!q.coverUrl)continue;const pe=[];for(const[de,n]of Object.entries(q.versions))n&&["oversized","undersized","corrupted"].includes(n.status)&&pe.push(de);pe.length>0&&u.push({id:q.galleryId,title:q.galleryTitle,cover_image_url:q.coverUrl,versionsToRegenerate:pe})}if(u.length===0){w.warning(t("superadmin.deepValidation.selection.noValidCovers"));return}const D=u.reduce((se,q)=>{var pe;return se+(((pe=q.versionsToRegenerate)==null?void 0:pe.length)||0)},0);w.info(t("superadmin.deepValidation.selection.startingSelectiveRegeneration").replace("{galleries}",String(u.length)).replace("{versions}",String(D)));const W=await os(u,s,{force:!0,dryRun:!1,onProgress:H});W.errors>0?w.warning(t("superadmin.deepValidation.selection.successWithErrors").replace("{success}",String(W.success)).replace("{errors}",String(W.errors))):w.success(t("superadmin.deepValidation.selection.success").replace("{count}",String(W.success))),k(new Set),await te()}catch(u){console.error("[DeepValidation] Regeneration error:",u),w.error(t("superadmin.deepValidation.selection.regenerationError").replace("{message}",u.message))}finally{y(!1),H(null)}}},Ve=g.size>0?fe():null;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(Ne,{className:"w-4 h-4"}),t("superadmin.deepValidation.companyTitle").replace("{company}",f)]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:t("superadmin.deepValidation.description")})]}),e.jsx(U,{onClick:te,disabled:d||z,variant:S.length>0?"outline":"default",children:d?e.jsxs(e.Fragment,{children:[e.jsx(ve,{className:"w-4 h-4 mr-2 animate-spin"}),t("superadmin.deepValidation.validating")]}):S.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Ne,{className:"w-4 h-4 mr-2"}),t("superadmin.deepValidation.revalidate")]}):e.jsxs(e.Fragment,{children:[e.jsx(Ne,{className:"w-4 h-4 mr-2"}),t("superadmin.deepValidation.startValidation")]})})]}),d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(is,{value:b.total>0?b.current/b.total*100:0}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:t("superadmin.deepValidation.analyzingGalleries")})]}),z&&A&&e.jsxs("div",{className:"space-y-2 p-3 bg-muted rounded-lg",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(ve,{className:"w-4 h-4 animate-spin"}),t("superadmin.deepValidation.selection.regenerating")," ",A.currentGallery||t("superadmin.deepValidation.selection.preparing")]}),e.jsxs("span",{className:"text-muted-foreground",children:[A.processed,"/",A.total]})]}),e.jsx(is,{value:A.total>0?A.processed/A.total*100:0}),A.currentVersion&&e.jsx("div",{className:"flex gap-1 flex-wrap",children:["thumbnail","medium","large","social"].map(u=>{var D;return e.jsx(X,{variant:(D=A.currentVersions)!=null&&D[u]?"default":"outline",className:A.currentVersion===u?"animate-pulse":"",children:u},u)})})]}),L&&e.jsxs(Be,{variant:"destructive",children:[e.jsx($e,{className:"h-4 w-4"}),e.jsx(We,{children:L})]}),l&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-2",children:[e.jsxs("div",{className:"text-center p-2 bg-muted rounded-lg",children:[e.jsx("div",{className:"text-xl font-bold",children:l.total}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t("superadmin.deepValidation.summary.total")})]}),e.jsxs("div",{className:"text-center p-2 bg-green-500/10 rounded-lg",children:[e.jsx("div",{className:"text-xl font-bold text-green-600",children:l.valid}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t("superadmin.deepValidation.summary.ok")})]}),e.jsxs("div",{className:"text-center p-2 bg-orange-500/10 rounded-lg",children:[e.jsx("div",{className:"text-xl font-bold text-orange-600",children:l.oversized}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t("superadmin.deepValidation.summary.oversized")})]}),e.jsxs("div",{className:"text-center p-2 bg-yellow-500/10 rounded-lg",children:[e.jsx("div",{className:"text-xl font-bold text-yellow-600",children:l.undersized}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t("superadmin.deepValidation.summary.undersized")})]}),e.jsxs("div",{className:"text-center p-2 bg-red-500/10 rounded-lg",children:[e.jsx("div",{className:"text-xl font-bold text-red-600",children:l.corrupted}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t("superadmin.deepValidation.summary.corrupted")})]}),e.jsxs("div",{className:"text-center p-2 bg-muted rounded-lg",children:[e.jsx("div",{className:"text-xl font-bold text-muted-foreground",children:l.missing}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t("superadmin.deepValidation.summary.missing")})]})]}),S.length>0&&e.jsxs("div",{className:"space-y-4",children:[i.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("h4",{className:"font-medium text-orange-600 flex items-center gap-2",children:[e.jsx($e,{className:"w-4 h-4"}
6),t("superadmin.deepValidation.galleriesWithIssues")," (",i.length,")"]}),g.size>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[Ve&&e.jsx("div",{className:"flex gap-1 text-xs",children:["thumbnail","medium","large","social"].map(u=>Ve[u]>0&&e.jsxs(X,{variant:"outline",className:"text-[10px] px-1.5",children:[u,": ",Ve[u]]},u))}),e.jsxs(U,{size:"sm",onClick:Pe,disabled:z||d,children:[e.jsx(Ce,{className:"w-4 h-4 mr-2"}),t("superadmin.deepValidation.selection.regenerateSelected").replace("{count}",String(g.size))]})]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto border rounded-lg",children:e.jsxs(Ss,{children:[e.jsx(Vs,{children:e.jsxs(ns,{children:[e.jsx(ue,{className:"w-10",children:e.jsx(ts,{checked:Q,ref:u=>{u&&(u.indeterminate=Z)},onCheckedChange:le,"aria-label":t("superadmin.deepValidation.selection.selectAll"),disabled:z})}),e.jsx(ue,{children:t("superadmin.deepValidation.table.gallery")}),e.jsx(ue,{className:"text-center",children:t("superadmin.deepValidation.table.thumbnail")}),e.jsx(ue,{className:"text-center",children:t("superadmin.deepValidation.table.medium")}),e.jsx(ue,{className:"text-center",children:t("superadmin.deepValidation.table.large")}),e.jsx(ue,{className:"text-center",children:t("superadmin.deepValidation.table.social")})]})}),e.jsx(ks,{children:i.map(u=>{var D,W,se,q;return e.jsxs(ns,{children:[e.jsx(me,{children:e.jsx(ts,{checked:g.has(u.galleryId),onCheckedChange:()=>ce(u.galleryId),"aria-label":`Selecionar ${u.galleryTitle}`,disabled:z})}),e.jsx(me,{children:e.jsxs("div",{className:"max-w-[200px]",children:[e.jsx("p",{className:"font-medium truncate",children:u.galleryTitle}),e.jsxs("code",{className:"text-[10px] text-muted-foreground",children:[u.galleryId.substring(0,8),"..."]})]})}),e.jsx(me,{className:"text-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[ee(((D=u.versions.thumbnail)==null?void 0:D.status)||"missing"),ie(u.versions.thumbnail,"thumbnail")]})}),e.jsx(me,{className:"text-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[ee(((W=u.versions.medium)==null?void 0:W.status)||"missing"),ie(u.versions.medium,"medium")]})}),e.jsx(me,{className:"text-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[ee(((se=u.versions.large)==null?void 0:se.status)||"missing"),ie(u.versions.large,"large")]})}),e.jsx(me,{className:"text-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[ee(((q=u.versions.social)==null?void 0:q.status)||"missing"),ie(u.versions.social,"social")]})})]},u.galleryId)})})]})})]}),B.length>0&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx(Se,{className:"w-4 h-4 inline mr-1 text-green-500"}),B.length," galerias com todas as dimensões corretas"]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground pt-2 border-t space-y-1",children:[e.jsxs("p",{children:[e.jsx(Ns,{className:"w-3 h-3 inline mr-1 text-orange-500"})," Oversized: dimensões maiores que o esperado (precisa regenerar)"]}),e.jsxs("p",{children:[e.jsx(bs,{className:"w-3 h-3 inline mr-1 text-yellow-500"})," Undersized: dimensões menores que o esperado"]}),e.jsxs("p",{children:[e.jsx(ls,{className:"w-3 h-3 inline mr-1 text-red-500"})," Corrompido: não foi possível ler dimensões do arquivo"]})]})]})}const xa={thumbnail:{width:960,height:540},medium:{width:1920,height:1080},large:{width:2880,height:1620},social:{width:1200,height:630}},ha=12e4,fa=50;function va({companies:s,autoRegenerate:f=!1,onClose:_}){const{t}=cs(),[d,c]=C.useState(!1),[b,x]=C.useState(!1),[S,O]=C.useState(0),[l,a]=C.useState(()=>s.map(n=>({companyId:n.companyId,companyName:n.companyName,status:"pending"}))),[L,h]=C.useState(new Set),g=C.useRef(!1),k=C.useRef(!1),z=n=>{h(I=>{const j=new Set(I);return j.has(n)?j.delete(n):j.add(n),j})},y=C.useCallback(async(n,I)=>{var j;try{let R=[],o=null,V,K=!0,je=0;const ke=Date.now();for(;K;){if(g.current)throw new Error("Cancelled");if(Date.now()-ke>ha)throw new Error("Timeout: validation took too long");if(++je>fa)throw new Error("Too many pages - possible infinite loop");I(`Page ${je}...`);const{data:ne,error:xe}=await ge.functions.invoke("regenerate-cover-thumbnails",{body:{action:"deep-validate",companyId:n.companyId,deepValidationCursor:V}});if(xe)throw new Error(xe.message);if(!ne.success)throw new Error(ne.error||"Validation failed");K=ne.hasMore||!1,K?(V=ne.nextCursor,I(`${((j=ne.galleries)==null?void 0:j.length)||0} galleries so far...`)):(R=ne.galleries||[],o=ne.summary||null)}const Y=R.filter(ne=>Object.values(ne.versions).some(be=>be&&be.status!=="valid"&&be.status!=="missing")),ye=((o==null?void 0:o.oversized)||0)+((o==null?void 0:o.undersized)||0)+((o==null?void 0:o.corrupted)||0);return{companyId:n.companyId,companyName:n.companyName,status:"completed",summary:o||void 0,issueC
6ount:ye,issueBreakdown:{oversized:(o==null?void 0:o.oversized)||0,undersized:(o==null?void 0:o.undersized)||0,corrupted:(o==null?void 0:o.corrupted)||0},galleriesWithIssues:Y}}catch(R){return{companyId:n.companyId,companyName:n.companyName,status:"error",error:R.message}}},[]),A=C.useCallback(async(n,I)=>{if(!n.galleriesWithIssues||n.galleriesWithIssues.length===0)return n;const j=[];for(const Y of n.galleriesWithIssues){if(!Y.coverUrl)continue;const ye=[];for(const[ne,xe]of Object.entries(Y.versions))xe&&["oversized","undersized","corrupted"].includes(xe.status)&&ye.push(ne);ye.length>0&&j.push({id:Y.galleryId,title:Y.galleryTitle,cover_image_url:Y.coverUrl,versionsToRegenerate:ye})}if(j.length===0)return n;I==null||I("regenerating");const R=await xs({companyId:n.companyId,kind:"covers",total:j.length,toProcess:j.length,force:!0,dryRun:!1});let o=null,V=null;try{const Y=await os(j,n.companyId,{force:!0,dryRun:!1});o={success:Y.success,errors:Y.errors??0,processed:Y.processed??Y.success,errorDetails:Y.errorDetails??[]}}catch(Y){V=Y.message}if(await hs(R,{processed:(o==null?void 0:o.processed)??0,success:(o==null?void 0:o.success)??0,errors:(o==null?void 0:o.errors)??(V?j.length:0),status:V?"failed":"completed",errorDetails:V?[{error:V}]:(o==null?void 0:o.errorDetails)??[]}),V)return{...n,status:"error",error:`Regeneration failed: ${V}`};I==null||I("revalidating");const K=await y({companyId:n.companyId,companyName:n.companyName},()=>{}),je=n.regenerated??0,ke=(o==null?void 0:o.success)??0;return K.status==="error"?{...n,status:"completed",regenerated:je+ke}:{...K,regenerated:je+ke}},[y]),H=C.useCallback(async()=>{c(!0),g.current=!1,k.current=!1;for(let n=0;n<s.length&&!g.current;n++){for(;k.current&&!g.current;)await new Promise(R=>setTimeout(R,100));if(g.current)break;O(n),a(R=>R.map((o,V)=>V===n?{...o,status:"validating",validationProgress:"Starting..."}:o));const I=R=>{a(o=>o.map((V,K)=>K===n?{...V,validationProgress:R}:V))};let j=await y(s[n],I);f&&j.status==="completed"&&(j.issueCount||0)>0&&(j=await A(j,R=>{a(o=>o.map((V,K)=>K===n?{...V,status:R,validationProgress:R==="revalidating"?t("superadmin.batchValidation.confirming"):void 0}:V))})),a(R=>R.map((o,V)=>V===n?j:o))}c(!1),w.success(t("superadmin.batchValidation.completed"))},[s,f,y,A,t]),te=C.useCallback(async()=>{c(!0),g.current=!1;for(let n=0;n<l.length&&!g.current;n++){const I=l[n];if(I.status!=="completed"||!I.galleriesWithIssues||I.galleriesWithIssues.length===0)continue;const j=await A(I,R=>{a(o=>o.map((V,K)=>K===n?{...V,status:R,validationProgress:R==="revalidating"?t("superadmin.batchValidation.confirming"):void 0}:V))});a(R=>R.map((o,V)=>V===n?j:o))}c(!1),w.success(t("superadmin.batchValidation.regenerationCompleted"))},[l,A,t]),ee=C.useCallback(async n=>{const I=l.findIndex(o=>o.companyId===n);if(I===-1)return;const j=l[I];if(j.status!=="completed"||!j.galleriesWithIssues||j.galleriesWithIssues.length===0)return;const R=await A(j,o=>{a(V=>V.map((K,je)=>je===I?{...K,status:o,validationProgress:o==="revalidating"?t("superadmin.batchValidation.confirming"):void 0}:K))});a(o=>o.map((V,K)=>K===I?R:V)),w.success(t("superadmin.batchValidation.companyRegenerated").replace("{company}",j.companyName))},[l,A,t]),ie=C.useCallback(async(n,I,j,R,o)=>{const V=l.findIndex(K=>K.companyId===n);if(V!==-1)try{(await os([{id:I,title:j,cover_image_url:R,versionsToRegenerate:[o]}],n,{force:!0,dryRun:!1})).success>0&&(a(ke=>ke.map((Y,ye)=>{var m;if(ye!==V)return Y;const ne=(m=Y.galleriesWithIssues)==null?void 0:m.map(N=>N.galleryId!==I?N:{...N,versions:{...N.versions,[o]:{...N.versions[o],status:"valid"}}});let xe=0,be=0,Fe=0,r=0;return ne==null||ne.forEach(N=>
6{Object.values(N.versions).forEach(M=>{M&&M.status==="oversized"&&(xe++,be++),M&&M.status==="undersized"&&(xe++,Fe++),M&&M.status==="corrupted"&&(xe++,r++)})}),{...Y,galleriesWithIssues:ne,issueCount:xe,issueBreakdown:{oversized:be,undersized:Fe,corrupted:r},regenerated:(Y.regenerated||0)+1}})),w.success(t("superadmin.batchValidation.versionFixed").replace("{version}",o)))}catch(K){w.error(`Failed to fix ${o}: ${K.message}`)}},[l,t]),i=()=>{k.current=!k.current,x(!b)},B=()=>{g.current=!0,c(!1),w.info(t("superadmin.batchValidation.cancelled"))},le=C.useCallback(async()=>{c(!0),g.current=!1;for(let n=0;n<s.length&&!g.current;n++){O(n),a(j=>j.map((R,o)=>o===n?{...R,status:"revalidating",validationProgress:t("superadmin.batchValidation.confirming")}:R));const I=await y(s[n],j=>{a(R=>R.map((o,V)=>V===n?{...o,validationProgress:j}:o))});a(j=>j.map((R,o)=>o===n?{...I,regenerated:R.regenerated}:R))}c(!1),w.success(t("superadmin.batchValidation.revalidationCompleted"))},[s,y,t]),ce=n=>{switch(n){case"valid":return e.jsx("span",{className:"text-green-600",children:"✓"});case"oversized":return e.jsx("span",{className:"text-orange-600",children:"↑"});case"undersized":return e.jsx("span",{className:"text-yellow-600",children:"↓"});case"corrupted":return e.jsx("span",{className:"text-red-600",children:"✕"});case"missing":return e.jsx("span",{className:"text-muted-foreground",children:"-"});default:return null}},Q=l.filter(n=>n.status==="completed").length,Z=l.filter(n=>n.status==="error").length,fe=l.reduce((n,I)=>n+(I.issueCount||0),0),Pe=l.reduce((n,I)=>n+(I.regenerated||0),0),Ve=l.reduce((n,I)=>{var j;return n+(((j=I.issueBreakdown)==null?void 0:j.oversized)||0)},0),u=l.reduce((n,I)=>{var j;return n+(((j=I.issueBreakdown)==null?void 0:j.undersized)||0)},0),D=l.reduce((n,I)=>{var j;return n+(((j=I.issueBreakdown)==null?void 0:j.corrupted)||0)},0),W=!d&&Q===s.length&&Q>0,se=fe>0,q=se&&!f&&!d,pe=s.length>0?(S+(d?0:1))/s.length*100:0,de=n=>{switch(n){case"pending":return e.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-muted-foreground/30"});case"validating":return e.jsx(ve,{className:"w-4 h-4 animate-spin text-blue-500"});case"regenerating":return e.jsx(Ce,{className:"w-4 h-4 animate-pulse text-purple-500"});case"revalidating":return e.jsx(ve,{className:"w-4 h-4 animate-spin text-blue-400"});case"completed":return e.jsx(Se,{className:"w-4 h-4 text-green-500"});case"error":return e.jsx(Ae,{className:"w-4 h-4 text-destructive"});case"skipped":return e.jsx($e,{className:"w-4 h-4 text-muted-foreground"})}};return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center justify-end",children:d?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(U,{variant:"outline",size:"sm",onClick:i,children:b?e.jsx(ps,{className:"w-4 h-4"}):e.jsx(Is,{className:"w-4 h-4"})}),e.jsx(U,{variant:"destructive",size:"sm",onClick:B,children:e.jsx(Zs,{className:"w-4 h-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(U,{onClick:H,disabled:s.length===0,children:[e.jsx(Ne,{className:"w-4 h-4 mr-2"}),t("superadmin.batchValidation.start")]}),Q>0&&e.jsxs(U,{variant:"outline",onClick:le,children:[e.jsx(Ne,{className:"w-4 h-4 mr-2"}),t("superadmin.batchValidation.revalidateAll")]})]})}),(d||Q>0)&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:[Q,"/",s.length," ",t("superadmin.batchValidation.companiesProcessed")]}),b&&e.jsx(X,{variant:"outline",children:t("superadmin.batchValidation.paused")})]}),e.jsx(is,{value:pe})]}),Q>0&&e.jsxs("div",{className:"grid grid-cols-4 gap-2",children:[e.jsxs("div",{className:"text-center p-2 bg-green-500/10 rounded-lg",children:[e.jsx("div",{className:"text-lg font-bold text-green-600",children:Q}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t("superadmin.batchValidation.validated")})]}),e.jsxs("div",{className:"text-center p-2 bg-orange-500/10 rounded-lg",children:[e.jsx("div",{className:"text-lg font-bold text-orange-600",children:fe}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t("superadmin.batchValidation.issues")}),fe>0&&e.jsxs("div",{className:"flex justify-center gap-1 mt-1 flex-wrap",children:[Ve>0&&e.jsxs(X,{variant:"outline",className:"text-[9px] px-1 py-0 bg-orange-500/20 text-orange-700 border-orange-300",children:["↑",Ve]}),u>0&&e.jsxs(X,{variant:"outline",className:"text-[9px] px-1 py-0 bg-yellow-500/20 text-yellow-700 border-yellow-300",children:["↓",u]}),D>0&&e.jsxs(X,{variant:"outline",className:"text-[9px] px-1 py-0 bg-red-500/20 text-red-700 border-red-300",children:["✕",D]})]})]}),Pe>0&&e.jsxs("div",{className:"text-center p-2 bg-purple-500/10 rounded-lg",children:[e.jsx("div",{className:"text-lg font-bold text-purple-600",children:Pe}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t("superadmin.batchValidation.regenerated")})]}),e.jsxs("div",{className:"text-center p-2 bg-red-500/10 rounded-lg",children:[e.jsx("div",{className:"text-lg font-bold text-red-600",children:Z}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t("superadmin.batchValidation.errors")})]})]}),e.jsx(Oe,{className:"h-[400px] border rounded-lg",children:e.jsx("div",{className:"p-2 space-y-1",children:l.map((n,I)=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg transition-colors ${n.status==="validating"||n.status==="regenerating"||n.status==="revalidating"?"bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx("span",{className:"text-xs text-muted-foreground w-6",children:I+1}),de(n.status),e.jsx("span",{className:"flex-1 font-medium truncate",children:n.companyName}),n.status==="validating"&&n.validationProgress&&e.jsx("span",{className:"text-xs text-muted-foreground animate-pulse",children:n.validationProgress}),n.status==="completed"&&n.summary&&e.jsxs("div",{className:"flex gap-1 items-center flex-wrap justify-end",children:[e.jsxs(X,{variant:"outline",className:"text-[10px] bg-green-500/10 text-green-600",children:["✓ ",n.summary.valid]}),n.issueBreakdown&&(n.issueBreakdown.oversized>0||n.issueBreakdown.undersized>0||n.issueBreakdown.corrupted>0)&&e.jsxs(e.Fragment,{children:[n.issueBreakdown.oversized>
60&&e.jsxs(X,{variant:"outline",className:"text-[10px] bg-orange-500/10 text-orange-600",children:["↑",n.issueBreakdown.oversized]}),n.issueBreakdown.undersized>0&&e.jsxs(X,{variant:"outline",className:"text-[10px] bg-yellow-500/10 text-yellow-600",children:["↓",n.issueBreakdown.undersized]}),n.issueBreakdown.corrupted>0&&e.jsxs(X,{variant:"outline",className:"text-[10px] bg-red-500/10 text-red-600",children:["✕",n.issueBreakdown.corrupted]})]}),(n.regenerated||0)>0&&e.jsxs(X,{variant:"outline",className:"text-[10px] bg-purple-500/10 text-purple-600",children:["🔄 ",n.regenerated]}),n.galleriesWithIssues&&n.galleriesWithIssues.length>0&&(n.issueCount||0)>0&&e.jsx(U,{variant:"outline",size:"sm",className:"h-6 px-2 ml-2",onClick:()=>ee(n.companyId),disabled:d,children:e.jsx(Ce,{className:"w-3 h-3"})}),n.galleriesWithIssues&&n.galleriesWithIssues.length>0&&e.jsxs(U,{variant:"ghost",size:"sm",className:"h-6 px-2",onClick:()=>z(n.companyId),children:[L.has(n.companyId)?e.jsx(Cs,{className:"w-3 h-3"}):e.jsx(_s,{className:"w-3 h-3"}),e.jsx("span",{className:"text-[10px] ml-1",children:L.has(n.companyId)?t("superadmin.batchValidation.hideDetails"):t("superadmin.batchValidation.viewDetails")})]})]}),n.status==="error"&&e.jsx("span",{className:"text-xs text-destructive truncate max-w-[200px]",children:n.error})]}),L.has(n.companyId)&&n.galleriesWithIssues&&e.jsx("div",{className:"ml-8 pl-4 border-l-2 border-muted space-y-2 py-2",children:n.galleriesWithIssues.map(j=>e.jsxs("div",{className:"text-xs space-y-1",children:[e.jsx("div",{className:"font-medium text-foreground",children:j.galleryTitle}),e.jsx("div",{className:"pl-2 space-y-0.5",children:Object.entries(j.versions).map(([R,o])=>{if(!o||o.status==="valid"||o.status==="missing")return null;const V=xa[R];return e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[ce(o.status),e.jsx("span",{className:"font-mono",children:R}),e.jsx("span",{children:":"}),e.jsxs("span",{className:"text-foreground",children:[o.width,"x",o.height]}),e.jsxs("span",{className:"text-muted-foreground",children:["(",t("superadmin.batchValidation.expected"),": ",V==null?void 0:V.width,"x",V==null?void 0:V.height,")"]}),e.jsx(X,{variant:"outline",className:`text-[9px] px-1 py-0 ${o.status==="oversized"?"text-orange-600 border-orange-300":o.status==="undersized"?"text-yellow-600 border-yellow-300":"text-red-600 border-red-300"}`,children:o.status}),j.coverUrl&&e.jsxs(U,{variant:"ghost",size:"sm",className:"h-5 px-1.5 text-[10px]",onClick:()=>ie(n.companyId,j.galleryId,j.galleryTitle,j.coverUrl,R),disabled:d,children:[e.jsx(Ce,{className:"w-3 h-3 mr-1"}),t("superadmin.batchValidation.fix")]})]},R)})})]},j.galleryId))})]},n.companyId))})}),(W||se)&&e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[fe>0&&e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"font-medium",children:[t("superadmin.batchValidation.legend"),":"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-orange-600",children:"↑"})," ",t("superadmin.batchValidation.oversized")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-yellow-600",children:"↓"})," ",t("superadmin.batchValidation.undersized")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-red-600",children:"✕"})," ",t("superadmin.batchValidation.corrupted")]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[W?e.jsxs(Be,{className:"flex-1 mr-4",children:[e.jsx(Se,{className:"h-4 w-4"}),e.jsx(We,{children:t("superadmin.batchValidation.allDone").replace("{companies}",String(Q)).replace("{issues}",String(fe))})]}):e.jsx("div",{className:"flex-1 mr-4 text-sm text-muted-foreground",children:t("superadmin.batchValidation.issuesFoundSoFar").replace("{count}",String(fe))}),q&&e.jsxs(U,{onClick:te,className:"shrink-0",children:[e.jsx(Ce,{className:"w-4 h-4 mr-2"}),t("superadmin.batchValidation.regenerateAll").replace("{count}",String(fe))]})]})]})]})}const Wa=()=>{var ye,ne,xe,be,Fe;const{t:s}=cs(),[f,_]=C.useState([]),[t,d]=C.useState(!1),[c,b]=C.useState(!1),[x,S]=C.useState(!1),[O,l]=C.useState(null),[a,L]=C.useState(null),[h,g]=C.useState(null),[k,z]=C.useState(null),[y,A]=C.useState(null),[H,te]=C.useState(new Set),[ee,ie]=C.useState(null),[i,B]=C.useState({isAnalyzing:!1,isCleaning:!1,isAnalyzingLegacy:!1,isCleaningLegacy:!1,analysis:null,legacyAnalysis:null,deleted:null,errors:[]}),le=C.useRef(!1),ce=C.useRef(0),Q=C.useRef(!0);C.useEffect(()=>(Q.current=!0,()=>{Q.current=!1}),[]);const Z=async r=>{let m,N,M,T=(r==null?void 0:r.message)||"Unknown error";try{const p=r==null?void 0:r.context;if(p&&typeof p=="object"&&(m=p.status||(r==null?void 0:r.status),typeof p.clone=="function"))try{const $=await p.clone().text();N=$.substring(0,500);try{const E=JSON.parse($);M=E.requestId,E.error&&(T=E.error)}catch{}}catch(v){console.warn("[extractErrorDetails] Failed to read body:",v)}m||(m=r==null?void 0:r.status)}catch(p){console.error("[extractErrorDetails] Exception:",p)}return{httpStatus:m,errorBody:N,requestId:M,message:T}},fe=async(r,m,N=3,M=1500)=>{let T=null,p,v,$;for(let E=0;E<=N;E++)try{const{data:P,error:G}=await ge.functions.invoke(r,{body:m});if(!G){const he=P==null?void 0:P.requestId;return{data:P,error:null,httpStatus:200,requestId:he}}const F=await Z(G);p=F.httpStatus,v=F.errorBody,$=F.requestId,T={...G,message:F.message};const we=[429,502,503,504,546].includes(p||0),ae=p===546;if(!we||E===N)return console.error("[invokeWithRetry] Non-retryable or max retries",{functionName:r,attempt:E,httpStatus:p,errorBody:v==null?void 0:v.substring(0,200),requestId:$}),{data:null,error:T,httpStatus:p,errorBody:v,requestId:$};const oe=M*Math.pow(ae?2.5:2,E);console.warn(`[invokeWithRetry] Retry ${E+1}/${N} in ${oe}ms (HTTP ${p})`),await new Promise(he=>setTimeout(he,oe))}catch(P){if(T=P,console.error(`[invokeWithRetry] Exception on attempt ${E}:`,P),E===N)return{data:null,error:P};const G=M*Math.pow(2,E);await new Promise(F=>setTimeout(F,G))}return{data:null,error:T,httpStatus:p,errorBody:v,requestId:$}},Pe=async(r,m)=>{console.log(`[SuperadminCoverMaintenance] Reanalyzing company: ${m}`),_(N=>N.map(M=>M.companyId===r?{...M,status:"processing",analysisError:void 0}:M));try{let N,M=0;const T=30;let p=null,v=[];for(;M<T;){M++,console.log(`[SuperadminCoverMaintenance] ${m} iteration ${M}${N?" (continuing)":""}`);const{data:$,error:E,httpStatus:P,errorBody:G,requestId:F}=await fe("regenerate-cover-thumbnails",{action:"analyze-covers",companyId:r,cursor:N});if(E||!$){const we=(E==null?void 0:E.message)||"Unknown error";console.error(`[SuperadminCoverMaintenance] Reanalysis failed for ${m}:`,{error:we,httpStatus:P,errorBody:G==null?void 0:G.substring(0,200),requestId:F,iteration:M});const ae=P===546;_(J=>J.map(oe=>oe.companyId===r?{...oe,status:ae?"partial":"error",analysisError:ae?"Timeout na análise (546)":we,httpStatus:P,analysisErrorBody:G,requestId:F,isPartialAnalysis:ae,partialReason:ae?"HTTP 546 timeout":void 0,galleriesNeedingVersions:ae?oe.galleriesNeedingVersions||v:void 0}:oe)),ae?w.warning(s("superadmin.coverMaintenance.messages.analysisPartial").replace("{company}",m)):w.error(s("superadmin.coverMaintenance.messages.reanalysisError").replace("{company}",m).replace("{status}",String(P||"?")));return}if(p=$,$.galleriesNeedingVersions&&(v=[...v,...$.galleriesNeedingVersions]),!$.hasMore){console.log(`[SuperadminCoverMaintenance] ${m} analysis complete after ${M} iterations`);break}N=$.nextCursor,M%3===0&&w.info(s("superadmin.coverMaintenance.messages.processingIterations").replace("{company}",m).replace("{iterations}",String(M)))}if(M>=T){console.warn(`[SuperadminCoverMaintenance] ${m} hit max iterations limit`),_($=>$.map(E=>E.companyId===r?{...E,status:"partial",isPartialAnalysis:!0,partialReason:`max_iterations: ${T}`,missingVersions:(p==null?void 0:p.missingVersionsCount)||0,existingVersions:(p==null?void 0:p.existingVersionsCount)||0,galleriesNeedingVersions:v}:E)),w.warning(s("superadmin.coverMaintenance.messages.analysisPartialLimit").replace("{company}",m));return}_($=>$.map(E=>E.companyId===r?{...E,galleriesNeedingRegeneration:(p==null?void 0:p.galleriesNeedingRegeneration)||0,existingVersions:(p==null?void 0:p.existingVersionsCount)||0,missingVersions:(p==null?void 0:p.missingVersionsCount)||0,status:((p==null?void 0:p.missingVersionsCount)||0)>0?"pending":"completed",isPartialAnalysis:!1,partialReason:void 0,analysisError:void 0,httpStatus:void 0,galleriesNeedingVersions:v.length>0?v:(p==null?void 0:p.galleriesNeedingVersions)||[]}:E)),w.success(s("superadmin.coverMaintenance.messages.missingVersions").replace("{company}",m).replace("{count}",String((p==null?void 0:p.missingVersionsCount)||0)))}catch(N){console.error(`[SuperadminCoverMaintenance] Reanalysis exception for ${m}:`,N),_(M=>M.map(T=>T.companyId===r?{...T,status:"error",analysisError:N.message}:T)),w.error(s("superadmin.coverMaintenance.messages.reanalysisError").replace("{company}",m).replace("{status}","?"))}},Ve=async()=>{var m,N,M,T,p,v,$,E;
6if(le.current){console.log("[SuperadminCoverMaintenance] Analysis already in progress, skipping");return}le.current=!0;const r=++ce.current;d(!0),l(null),S(!0);try{const{data:P,error:G}=await ge.rpc("get_all_companies_for_superadmin");if(G)throw G;console.log(`[SuperadminCoverMaintenance] Analyzing ${(P==null?void 0:P.length)||0} companies`);const F=[],we=1;for(let ae=0;ae<((P==null?void 0:P.length)||0);ae+=we){const J=P[ae];try{const[{count:oe},{count:he}]=await Promise.all([ge.from("galleries").select("id",{count:"exact",head:!0}).eq("company_id",J.id),ge.from("galleries").select("id",{count:"exact",head:!0}).eq("company_id",J.id).not("cover_image_url","is",null)]);if((he||0)===0){F.push({companyId:J.id,companyName:J.name,slug:J.slug,totalGalleries:oe||0,galleriesWithCovers:0,galleriesNeedingRegeneration:0,existingVersions:0,missingVersions:0,status:"skipped",galleriesNeedingVersions:[],webpPending:0,jpgPending:0,webpExisting:0,jpgExisting:0}),Q.current&&ce.current===r&&_([...F]);continue}let Ue,Le=0;const ds=30;let re=null,Ie="pending",De={},Ge=[];for(;Le<ds;){Le++;const{data:_e,error:qe,httpStatus:He,errorBody:Ke,requestId:fs}=await fe("regenerate-cover-thumbnails",{action:"analyze-covers",companyId:J.id,cursor:Ue});if(qe||!_e){const vs=(qe==null?void 0:qe.message)||"Unknown error";console.error(`Error processing ${J.name} (iteration ${Le}):`,{error:vs,httpStatus:He,errorBody:Ke==null?void 0:Ke.substring(0,200),requestId:fs});const js=He===546;js&&re?(Ie="partial",De={message:"HTTP 546 timeout",httpStatus:He}):(Ie=js?"partial":"error",De={message:vs,httpStatus:He,errorBody:Ke,requestId:fs});break}if(re=_e,_e.galleriesNeedingVersions&&(Ge=[...Ge,..._e.galleriesNeedingVersions]),!_e.hasMore){Ie=(_e.missingVersionsCount||0)>0?"pending":"completed";break}Ue=_e.nextCursor}Le>=ds&&Ie!=="error"&&(Ie="partial");const Me=(re==null?void 0:re.versionCounts)||{},Rs=(((m=Me.thumbnail)==null?void 0:m.missing)||0)+(((N=Me.medium)==null?void 0:N.missing)||0)+(((M=Me.large)==null?void 0:M.missing)||0),Ts=(((T=Me.thumbnail)==null?void 0:T.exists)||0)+(((p=Me.medium)==null?void 0:p.exists)||0)+(((v=Me.large)==null?void 0:v.exists)||0),Es=(($=Me.social)==null?void 0:$.missing)||0,$s=((E=Me.social)==null?void 0:E.exists)||0,As={companyId:J.id,companyName:J.name,slug:J.slug,totalGalleries:oe||0,galleriesWithCovers:he||0,galleriesNeedingRegeneration:(re==null?void 0:re.galleriesNeedingRegeneration)||0,existingVersions:(re==null?void 0:re.existingVersionsCount)||0,missingVersions:(re==null?void 0:re.missingVersionsCount)||0,status:Ie,isPartialAnalysis:Ie==="partial",partialReason:Ie==="partial"?De.httpStatus===546?"HTTP 546 timeout":`max_iterations: ${ds}`:void 0,analysisError:De.message,httpStatus:De.httpStatus,analysisErrorBody:De.errorBody,requestId:De.requestId,galleriesNeedingVersions:Ge.length>0?Ge:(re==null?void 0:re.galleriesNeedingVersions)||[],webpPending:Rs,jpgPending:Es,webpExisting:Ts,jpgExisting:$s};F.push(As),Q.current&&ce.current===r&&_([...F]),console.log(`[SuperadminCoverMaintenance] ${J.name}: ${Le} iterations, ${(re==null?void 0:re.missingVersionsCount)||0} missing`)}catch(oe){console.error(`[SuperadminCoverMaintenance] Exception analyzing ${J.name}:`,oe),F.push({companyId:J.id,companyName:J.name,slug:J.slug,totalGalleries:0,galleriesWithCovers:0,galleriesNeedingRegeneration:0,existingVersions:0,missingVersions:0,status:"error",analysisError:oe.message||"Unknown exception",galleriesNeedingVersions:[],webpPending:0,jpgPending:0,webpExisting:0,jpgExisting:0}),Q.current&&ce.current===r&&_([...F])}ae+1<((P==null?void 0:P.length)||0)&&await new Promise(oe=>setTimeout(oe,200))}if(Q.current&&ce.current===r){const ae=F.reduce((he,Ue)=>he+Ue.missingVersions,0),J=F.filter(he=>he.status==="error").length,oe=F.filter(he=>he.status==="partial").length;J>0||oe>0?w.warning(s("superadmin.coverMaintenance.messages.analysisResult").replace("{count}",String(ae)).replace("{errors}",String(J)).replace("{partial}",String(oe))):w.success(s("superadmin.coverMaintenance.messages.analysisSuccess").replace("{count}",String(ae)).replace("{companies}",String(F.filter(he=>he.missingVersions>0).length)))}}catch(P){console.error("Analysis error:",P),Q.current&&ce.current===r&&(l(P.message),w.error(s("superadmin.coverMaintenance.messages.analyzeError")))}finally{ce.current===r&&(le.current=!1),Q.current&&(d(!1),b(!0))}},u=async(r,m)=>{var N,M,T,p;B(v=>({...v,isAnalyzing:!0,analysis:null,deleted:null,errors:[],companyId:r,companyName:m}));try{const v={action:"analyze"},{data:$,error:E}=await ge.functions.invoke("cleanup-orphaned-storage",{body:v});if(E)throw new Error(E.message||"Failed to analyze orphaned storage");if(!$.success)throw new Error($.error||"Analysis failed");B(G=>({...G,isAnalyzing:!1,analysis:$.analyzed,errors:$.errors||[]}));const P=(((M=(N=$.analyzed)==null?void 0:N.thumbnailsBucket)==null?void 0:M.orphaned)||0)+(((p=(T=$.analyzed)==null?void 0:T.contentBucket)==null?void 0:p.orphaned)||0);P>0?w.info(m?s("superadmin.coverMaintenance.messages.foundOrphanedIn").replace("{count}",String(P)).replace("{company}",m):s("superadmin.coverMaintenance.messages.foundOrphaned").replace("{count}",String(P))):w.success(m?s("superadmin.coverMaintenance.messages.noOrphanedFoundIn").replace("{company}",m):s("superadmin.coverMaintenance.messages.noOrphanedFound"))}catch(v){console.error("[analyzeOrphanedStorage] Error:",v),B($=>({...$,isAnalyzing:!1,errors:[v.message]})),w.error(s("superadmin.coverMaintenance.messages.analysisErrorGeneric").replace("{message}",v.message))}},D=async()=>{var T,p,v,$,E,P;const{companyId:r,companyName:m,analysis:N}=i;
6if(!N){w.error(s("superadmin.coverMaintenance.messages.runAnalysisFirst"));return}if((((T=N.thumbnailsBucket)==null?void 0:T.orphaned)||0)+(((p=N.contentBucket)==null?void 0:p.orphaned)||0)===0){w.info(s("superadmin.coverMaintenance.messages.noOrphanedToClean"));return}B(G=>({...G,isCleaning:!0}));try{const G={action:r?"cleanup-company":"cleanup",dryRun:!1};r&&(G.companyId=r);const{data:F,error:we}=await ge.functions.invoke("cleanup-orphaned-storage",{body:G});if(we)throw new Error(we.message||"Failed to cleanup orphaned storage");if(!F.success)throw new Error(F.error||"Cleanup failed");const ae=((($=(v=F.deleted)==null?void 0:v.thumbnails)==null?void 0:$.length)||0)+(((P=(E=F.deleted)==null?void 0:E.content)==null?void 0:P.length)||0);B(J=>({...J,isCleaning:!1,deleted:F.deleted,analysis:F.analyzed,errors:F.errors||[]})),ae>0?w.success(m?s("superadmin.coverMaintenance.messages.deletedOrphanedFrom").replace("{count}",String(ae)).replace("{company}",m):s("superadmin.coverMaintenance.messages.deletedOrphaned").replace("{count}",String(ae))):w.info(s("superadmin.coverMaintenance.messages.noFilesDeleted"))}catch(G){console.error("[cleanupOrphanedStorage] Error:",G),B(F=>({...F,isCleaning:!1,errors:[G.message]})),w.error(s("superadmin.coverMaintenance.messages.cleanupError").replace("{message}",G.message))}},W=()=>{B({isAnalyzing:!1,isCleaning:!1,isAnalyzingLegacy:!1,isCleaningLegacy:!1,analysis:null,legacyAnalysis:null,deleted:null,errors:[]})},se=async(r,m)=>{var N,M;B(T=>({...T,isAnalyzingLegacy:!0,legacyAnalysis:null,errors:[],companyId:r,companyName:m}));try{const{data:T,error:p}=await ge.functions.invoke("cleanup-orphaned-storage",{body:{action:"analyze-legacy-versions",companyId:r}});if(p)throw new Error(p.message||"Failed to analyze legacy versions");if(!T.success)throw new Error(T.error||"Analysis failed");B($=>{var E;return{...$,isAnalyzingLegacy:!1,legacyAnalysis:((E=T.analyzed)==null?void 0:E.legacyVersions)||null,errors:T.errors||[]}});const v=((M=(N=T.analyzed)==null?void 0:N.legacyVersions)==null?void 0:M.total)||0;v>0?w.info(s("superadmin.coverMaintenance.messages.foundLegacy").replace("{count}",String(v)).replace("{company}",m)):w.success(s("superadmin.coverMaintenance.messages.noLegacyFound").replace("{company}",m))}catch(T){console.error("[analyzeLegacyVersions] Error:",T),B(p=>({...p,isAnalyzingLegacy:!1,errors:[T.message]})),w.error(s("superadmin.coverMaintenance.messages.analysisErrorGeneric").replace("{message}",T.message))}},q=async()=>{var T,p;const{companyId:r,companyName:m,legacyAnalysis:N}=i;if(!r||!N){w.error(s("superadmin.coverMaintenance.messages.runLegacyFirst"));return}if(N.files.thumbnail.filter(v=>v.hasWebpEquivalent).length+N.files.medium.filter(v=>v.hasWebpEquivalent).length+N.files.large.filter(v=>v.hasWebpEquivalent).length===0){w.info(s("superadmin.coverMaintenance.messages.noLegacyToClean"));return}B(v=>({...v,isCleaningLegacy:!0}));try{const{data:v,error:$}=await ge.functions.invoke("cleanup-orphaned-storage",{body:{action:"cleanup-legacy-versions",companyId:r,dryRun:!1}});if($)throw new Error($.message||"Failed to cleanup legacy versions");if(!v.success)throw new Error(v.error||"Cleanup failed");const E=((p=(T=v.deleted)==null?void 0:T.legacyVersions)==null?void 0:p.length)||0;B(P=>{var G;return{...P,isCleaningLegacy:!1,deleted:v.deleted,legacyAnalysis:((G=v.analyzed)==null?void 0:G.legacyVersions)||null,errors:v.errors||[]}}),E>0?w.success(s("superadmin.coverMaintenance.messages.jpgLegacyDeletedFrom").replace("{count}",String(E)).replace("{company}",m||"")):w.info(s("superadmin.coverMaintenance.messages.noFilesDeleted"))}catch(v){console.error("[cleanupLegacyVersions] Error:",v),B($=>({...$,isCleaningLegacy:!1,errors:[v.message]})),w.error(s("superadmin.coverMaintenance.messages.cleanupError").replace("{message}",v.message))}},pe=r=>{switch(r.status){case"completed":return e.jsxs(X,{variant:"default",className:"bg-primary",children:[e.jsx(Se,{className:"w-3 h-3 mr-1"})," OK"]});case"processing":return e.jsxs(X,{variant:"default",className:"bg-secondary text-secondary-foreground",children:[e.jsx(ve,{className:"w-3 h-3 mr-1 animate-spin"})," ",s("superadmin.coverMaintenance.status.processing")]});case"error":return e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs(X,{variant:"destructive",children:[e.jsx(Ae,{className:"w-3 h-3 mr-1"})," ",s("superadmin.coverMaintenance.status.error")]}),r.analysisError&&e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("span",{className:"text-xs text-destructive max-w-64 truncate",title:r.analysisError,children:[r.httpStatus?`HTTP ${r.httpStatus}
6: `:"",r.analysisError]}),r.requestId&&e.jsxs("span",{className:"text-[10px] text-muted-foreground font-mono",title:"Request ID",children:["ID: ",r.requestId]})]})]});case"partial":return e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs(X,{variant:"outline",className:"border-warning text-warning",children:[e.jsx($e,{className:"w-3 h-3 mr-1"})," ",s("superadmin.coverMaintenance.status.partial")]}),r.partialReason&&e.jsx("span",{className:"text-xs text-muted-foreground max-w-48 truncate",title:r.partialReason,children:r.partialReason})]});case"skipped":return e.jsx(X,{variant:"secondary",children:s("superadmin.coverMaintenance.status.ok")});default:return e.jsx(X,{variant:"outline",children:s("superadmin.coverMaintenance.status.pending")})}},de=f.reduce((r,m)=>r+m.galleriesWithCovers,0),n=f.reduce((r,m)=>r+m.galleriesNeedingRegeneration,0),I=f.reduce((r,m)=>r+m.missingVersions,0),j=f.reduce((r,m)=>r+m.existingVersions,0),R=f.filter(r=>r.galleriesNeedingRegeneration>0).length,o=f.filter(r=>r.galleriesWithCovers>0),V=o.length>0&&H.size===o.length,K=H.size>0&&H.size<o.length,je=()=>{te(V?new Set:new Set(o.map(r=>r.companyId)))},ke=r=>{const m=new Set(H);m.has(r)?m.delete(r):m.add(r),te(m)},Y=r=>{navigator.clipboard.writeText(r),w.success(s("superadmin.coverMaintenance.messages.idCopied"))};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold",children:s("superadmin.coverMaintenance.title")}),e.jsx("p",{className:"text-muted-foreground",children:s("superadmin.coverMaintenance.subtitle")})]}),e.jsxs(U,{onClick:Ve,disabled:t,variant:c?"outline":"default",children:[e.jsx(Xe,{className:`w-4 h-4 mr-2 ${t?"animate-spin":""}`}),s(c?"superadmin.coverMaintenance.updateAnalysis":"superadmin.coverMaintenance.startAnalysis")]})]}),!c&&!t&&e.jsxs(Be,{children:[e.jsx(Ne,{className:"h-4 w-4"}),e.jsx(rs,{children:s("superadmin.coverMaintenance.noAnalysis.title")}),e.jsx(We,{children:s("superadmin.coverMaintenance.noAnalysis.description")})]}),t&&e.jsxs(Be,{className:"border-blue-200 bg-blue-50 dark:border-blue-800 dark:bg-blue-950",children:[e.jsx(aa,{className:"h-4 w-4 text-blue-600 dark:text-blue-400"}),e.jsx(rs,{className:"text-blue-800 dark:text-blue-200",children:"Analysis in progress"}),e.jsx(We,{className:"text-blue-700 dark:text-blue-300",children:"Please do not leave this page while the analysis is being performed. This process may take a few minutes depending on the number of companies and galleries."})]}),O&&e.jsxs(Be,{variant:"destructive",children:[e.jsx($e,{className:"h-4 w-4"}),e.jsx(rs,{children:"Erro"}),e.jsx(We,{children:O})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsxs(ze,{children:[e.jsx(Re,{className:"pb-2",children:e.jsx(Te,{className:"text-sm font-medium text-muted-foreground",children:s("superadmin.coverMaintenance.cards.companies")})}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:f.length}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[R," ",s("superadmin.coverMaintenance.cards.withCoversToGenerate")]})]})]}),e.jsxs(ze,{children:[e.jsx(Re,{className:"pb-2",children:e.jsx(Te,{className:"text-sm font-medium text-muted-foreground",children:s("superadmin.coverMaintenance.cards.galleriesWithCover")})}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:de}),e.jsx("p",{className:"text-xs text-muted-foreground",children:s("superadmin.coverMaintenance.cards.inAllCompanies")})]})]}),e.jsxs(ze,{children:[e.jsx(Re,{className:"pb-2",children:e.jsx(Te,{className:"text-sm font-medium text-muted-foreground",children:s("superadmin.coverMaintenance.cards.versionsToGenerate")})}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold text-orange-600",children:I}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[n," ",s("superadmin.coverMaintenance.cards.galleriesPending")]}),e.jsxs("p",{className:"text-xs text-green-600 mt-1",children:[j," ",s("superadmin.coverMaintenance.cards.versionsExisting")]})]})]}),e.jsxs(ze,{children:[e.jsx(Re,{className:"pb-2",children:e.jsx(Te,{className:"text-sm font-medium text-muted-foreground",children:s("superadmin.coverMaintenance.cards.estimatedTime")})}),e.jsxs(Ee,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[Math.ceil(I/10*3/60)," ",s("superadmin.common.min")]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:s("superadmin.coverMaintenance.cards.batchInfo")})]})]})]}),e.jsx(Xs,{open:x,onOpenChange:S,children:e.jsxs(ze,{children:[e.jsx(Re,{children:e.jsx(Js,{asChild:!0,children:e.jsxs(U,{variant:"ghost",className:"w-full justify-between p-0 h-auto hover:bg-transparent",children:[e.jsx(Te,{className:"flex items-center gap-2",children:s("superadmin.coverMaintenance.detailsByCompany")}),e.jsx(Cs,{className:`w-5 h-5 transition-transform ${x?"rotate-180":""}`})]})})}),e.jsx(Qs,{children:e.jsxs(Ee,{className:"space-y-4",children:[H.size>0&&e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/50 rounded-lg border",children:[e.jsxs("span",{className:"text-sm font-medium",children:[H.size," ",s("superadmin.coverMaintenance.batch.companiesSelected")]}),e.jsx("div",{className:"flex-1"}),e.jsxs(U,{size:"sm",variant:"outline",onClick:()=>{const r=f.filter(m=>H.has(m.companyId)).map(m=>({companyId:m.companyId,companyName:m.companyName}));r.length>0&&A(r)},children:[e.jsx(Ne,{className:"w-4 h-4 mr-2"}),s("superadmin.coverMaintenance.batch.deepValidation")]}),e.jsxs(U,{size:"sm",onClick:()=>{const r=f.find(m=>H.has(m.companyId));r&&g({companyId:r.companyId,companyName:r.companyName,galleries:r.galleriesNeedingVersions||[],allGalleriesCount:r.galleriesWithCovers})},children:[e.jsx(Ce,{className:"w-4 h-4 mr-2"}),s("superadmin.coverMaintenance.batch.regenerate")]}),e.jsx(U,{size:"sm",variant:"ghost",onClick:()=>te(new Set),children:s("superadmin.coverMaintenance.batch.clearSelection")})]}),e.jsxs(Ss,{children:[e.jsx(Vs,{children:e.jsxs(ns,{children:[e.jsx(ue,{className:"w-10",children:e.jsx(ts,{checked:V,ref:r=>{r&&(r.indeterminate=K)},onCheckedChange:je,"aria-label":s("superadmin.coverMaintenance.batch.selectAll"),disabled:o.length===0})}),e.jsx(ue,{children:s("superadmin.coverMaintenance.table.company")}),e.jsx(ue,{children:s("superadmin.coverMaintenance.table.slug")}),e.jsx(ue,{className:"text-right",children:s("superadmin.coverMaintenance.table.galleries")}),e.jsx(ue,{className:"text-right",children:s("superadmin.coverMaintenance.table.withCover")}),e.jsx(ue,{className:"text-right text-orange-600",children:s("superadmin.coverMaintenance.table.webpPending")}),e.jsx(ue,{className:"text-right text-orange-600",children:s("superadmin.coverMaintenance.table.jpgPending")}),e.jsx(ue,{className:"text-right text-green-600",children:s("superadmin.coverMaintenance.table.webpOk")}),e.jsx(ue,{className:"text-right text-green-600",children:s("superadmin.coverMaintenance.table.jpgOk")}),e.jsx(ue,{children:s("superadmin.coverMaintenance.table.status")}),e.jsx(ue,{children:s("superadmin.coverMaintenance.table.actions")})]})}),e.jsx(ks,{children:f.map(r=>e.jsxs(ns,{children:[e.jsx(me,{children:e.jsx(ts,{checked:H.has(r.companyId),onCheckedChange:()=>ke(r.companyId),disabled:r.galleriesWithCovers===0,"aria-label":`${s("superadmin.coverMaintenance.batch.select")} ${r.companyName}`})}),e.jsx(me,{className:"font-medium",children:r.companyName}),e.jsx(me,{className:"text-muted-foreground",children:r.slug}),e.jsx(me,{className:"text-right",children:r.totalGalleries}),e.jsx(me,{className:"text-right",children:r.galleriesWithCovers}),e.jsx(me,{className:"text-right",children:e.jsx("span",{className:r.webpPending>0?"text-orange-600 font-medium":"text-muted-foreground",children:r.webpPending})}),e.jsx(me,{className:"text-right",children:e.jsx("span",{className:r.jpgPending>0?"text-orange-600 font-medium":"text-muted-foreground",children:r.jpgPending})}),e.jsx(me,{className:"text-right",children:e.jsx("span",{className:"text-green-600",children:r.webpExisting})}),e.jsx(me,{className:"text-right",children:e.jsx("span",{className:"text-green-600",children:r.jpgExisting})}),e.jsx(me,{children:pe(r)}),e.jsx(me,{children:e.jsxs("div",{className:"flex gap-1",children:[r.galleriesWithCovers>0&&e.jsxs(U,{variant:"ghost",size:"sm",onClick:()=>g({companyId:r.companyId,companyName:r.companyName,galleries:r.galleriesNeedingVersions||[],allGalleriesCount:r.galleriesWithCovers}),disabled:!1,title:s("superadmin.coverMaintenance.table.regenerate"),className:"text-purple-600 hover:text-purple-700 hover:bg-purple-50 dark:hover:bg-purple-950",children:[e.jsx(Ce,{className:"w-4 h-4 mr-1"}),s("superadmin.coverMaintenance.table.regenerate")]}),r.galleriesWithCovers>0&&r.status!=="skipped"&&e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>z({companyId:r.companyId,companyName:r.companyName}),title:"Validação profunda de dimensões",className:"text-blue-600 hover:text-blue-700 hover:bg-blue-50 dark:hover:bg-blue-950",children:e.jsx(Ne,{className:"w-4 h-4"})}),(r.status==="error"||r.status==="partial")&&e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>Pe(r.companyId,r.companyName),disabled:!1,title:s("superadmin.coverMaintenance.messages.reanalyzeCompany"),children:e.jsx(Xe,{className:"w-4 h-4"})}),r.errorDetails&&r.errorDetails.length>0&&e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>L({companyName:r.companyName,errors:r.errorDetails}),title:s("superadmin.coverMaintenance.errorsModal.title").replace(" - {company}",""),children:e.jsx(Ae,{className:"w-4 h-4 text-destructive"})})]})})]},r.companyId))})]})]})})]})}),e.jsxs(ze,{children:[e.jsxs(Re,{children:[e.jsxs(Te,{className:"flex items-center gap-2",children:[e.jsx(ra,{className:"w-5 h-5"}),s("superadmin.coverMaintenance.orphanedStorage.title")]}),e.jsx(ms,{children:s("superadmin.coverMaintenance.orphanedStorage.description")})]}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-4 flex-wrap",children:[e.jsxs(U,{onClick:()=>u(),disabled:i.isAnalyzing||i.isCleaning,variant:"outline",children:[i.isAnalyzing?e.jsx(ve,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Xe,{className:"w-4 h-4 mr-2"}),s("superadmin.coverMaintenance.orphanedStorage.analyzeAllCompanies")]}),i.analysis&&e.jsxs(e.Fragment,{children:[e.jsxs(U,{onClick:D,disabled:i.isCleaning||i.isAnalyzing||(((ne=(ye=i.analysis)==null?void 0:ye.thumbnailsBucket)==null?void 0:ne.orphaned)||0)+(((be=(xe=i.analysis)==null?void 0:xe.contentBucket)==null?void 0:be.orphaned)||0)===0,variant:"destructive",children:[i.isCleaning?e.jsx(ve,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(us,{className:"w-4 h-4 mr-2"}),s("superadmin.coverMaintenance.orphanedStorage.cleanOrphanedFiles")]}),e.jsx(U,{onClick:W,variant:"ghost",disabled:i.isAnalyzing||i.isCleaning,children:s("superadmin.coverMaintenance.orphanedStorage.clearResults")})]})]}),i.analysis&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 pt-4 border-t",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"font-medium flex items-center gap-2",children:[e.jsx(as,{className:"w-4 h-4"}),s("superadmin.coverMaintenance.orphanedStorage.bucket"),": ",s("superadmin.coverMaintenance.orphanedStorage.thumbnailsBucket")]}),e.jsxs("div",{className:"text-sm space-y-1",children:[e.jsxs("p",{className:"text-muted-foreground",children:[s("superadmin.coverMaintenance.orphanedStorage.totalFiles"),": ",e.jsx("span",{className:"font-medium text-foreground",children:i.analysis.thumbnailsBucket.total})]}),e.jsxs("p",{className:i.analysis.thumbnailsBucket.orphaned>0?"text-destructive":"text-muted-foreground",children:[s("superadmin.coverMaintenance.orphanedStorage.orphaned"),": ",e.jsx("span",{className:"font-medium",children:i.analysis.thumbnailsBucket.orphaned})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h4",{className:"font-medium flex items-center gap-2",children:[e.jsx(as,{className:"w-4 h-4"}),s("superadmin.coverMaintenance.orphanedStorage.bucket"),": ",s("superadmin.coverMaintenance.orphanedStorage.contentBucket")]}),e.jsxs("div",{className:"text-sm space-y-1",children:[e.jsxs("p",{className:"text-muted-foreground",children:[s("superadmin.coverMaintenance.orphanedStorage.totalFiles"),": ",e.jsx("span",{className:"font-medium text-foreground",children:i.analysis.contentBucket.total})]}),e.jsxs("p",{className:i.analysis.contentBucket.orphaned>0?"text-destructive":"text-muted-foreground",children:[s("superadmin.coverMaintenance.orphanedStorage.orphaned"),": ",e.jsx("span",{className:"font-medium",children:i.analysis.contentBucket.orphaned})]})]})]})]}),i.deleted&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsxs("h4",{className:"font-medium text-green-600 flex items-center gap-2 mb-2",children:[e.jsx(Se,{className:"w-4 h-4"}),s("superadmin.coverMaintenance.orphanedStorage.filesDeleted")]}),e.jsxs("div",{className:"text-sm space-y-1",children:[e.jsxs("p",{children:[s("superadmin.coverMaintenance.orphanedStorage.thumbnailsBucket"),": ",e.jsx("span",{className:"font-medium",children:i.deleted.thumbnails.length})]}),e.jsxs("p",{children:[s("superadmin.coverMaintenance.orphanedStorage.contentBucket"),": ",e.jsx("span",{className:"font-medium",children:i.deleted.content.length})]})]})]}),i.errors.length>0&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsxs("h4",{className:"font-medium text-destructive flex items-center gap-2 mb-2",children:[e.jsx(Ae,{className:"w-4 h-4"}
6),s("superadmin.coverMaintenance.orphanedStorage.errors")," (",i.errors.length,")"]}),e.jsx(Oe,{className:"max-h-32",children:e.jsx("div",{className:"space-y-1 text-xs text-muted-foreground",children:i.errors.map((r,m)=>e.jsx("p",{children:r},m))})})]})]})]}),e.jsxs(ze,{className:"border-2 border-orange-500/30 bg-orange-500/5",children:[e.jsxs(Re,{children:[e.jsxs(Te,{className:"flex items-center gap-2",children:[e.jsx(us,{className:"w-5 h-5 text-orange-500"}),s("superadmin.coverMaintenance.legacyCleanup.title")]}),e.jsx(ms,{children:s("superadmin.coverMaintenance.legacyCleanup.description")})]}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-4 flex-wrap items-end",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(gs,{className:"text-sm font-medium",children:s("superadmin.coverMaintenance.legacyCleanup.company")}),e.jsxs("select",{className:"flex h-10 w-64 rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring",value:i.companyId||"",onChange:r=>{const m=f.find(N=>N.companyId===r.target.value);B(N=>({...N,companyId:r.target.value||void 0,companyName:m==null?void 0:m.companyName,legacyAnalysis:null}))},disabled:i.isAnalyzingLegacy||i.isCleaningLegacy,children:[e.jsx("option",{value:"",children:s("superadmin.coverMaintenance.legacyCleanup.selectCompany")}),f.map(r=>e.jsx("option",{value:r.companyId,children:r.companyName},r.companyId))]})]}),e.jsxs(U,{onClick:()=>{i.companyId&&i.companyName&&se(i.companyId,i.companyName)},disabled:!i.companyId||i.isAnalyzingLegacy||i.isCleaningLegacy,variant:"outline",children:[i.isAnalyzingLegacy?e.jsx(ve,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Xe,{className:"w-4 h-4 mr-2"}),s("superadmin.coverMaintenance.legacyCleanup.analyzeLegacy")]}),i.legacyAnalysis&&i.legacyAnalysis.total>0&&e.jsxs(U,{onClick:q,disabled:i.isCleaningLegacy||i.isAnalyzingLegacy,variant:"destructive",children:[i.isCleaningLegacy?e.jsx(ve,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(us,{className:"w-4 h-4 mr-2"}),s("superadmin.coverMaintenance.legacyCleanup.cleanJpgLegacy")]})]}),i.legacyAnalysis&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4 pt-4 border-t",children:[e.jsxs("div",{className:"text-center p-3 bg-muted rounded-lg",children:[e.jsx("div",{className:"text-2xl font-bold",children:i.legacyAnalysis.total}),e.jsx("div",{className:"text-xs text-muted-foreground",children:s("superadmin.coverMaintenance.legacyCleanup.totalJpgLegacy")})]}),e.jsxs("div",{className:"text-center p-3 bg-muted rounded-lg",children:[e.jsx("div",{className:"text-xl font-bold",children:i.legacyAnalysis.thumbnail}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"thumbnail/"})]}),e.jsxs("div",{className:"text-center p-3 bg-muted rounded-lg",children:[e.jsx("div",{className:"text-xl font-bold",children:i.legacyAnalysis.medium}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"medium/"})]}),e.jsxs("div",{className:"text-center p-3 bg-muted rounded-lg",children:[e.jsx("div",{className:"text-xl font-bold",children:i.legacyAnalysis.large}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"large/"})]})]}),((Fe=i.deleted)==null?void 0:Fe.legacyVersions)&&i.deleted.legacyVersions.length>0&&e.jsx("div",{className:"pt-4 border-t",children:e.jsxs("h4",{className:"font-medium text-green-600 flex items-center gap-2 mb-2",children:[e.jsx(Se,{className:"w-4 h-4"}),s("superadmin.coverMaintenance.legacyCleanup.jpgLegacyDeleted").replace("{count}",String(i.deleted.legacyVersions.length))]})}),e.jsxs("div",{className:"text-xs text-muted-foreground pt-2 border-t",children:[e.jsxs("p",{children:["• ",s("superadmin.coverMaintenance.legacyCleanup.info.analyzeSubfolders")]}),e.jsxs("p",{children:["• ",s("superadmin.coverMaintenance.legacyCleanup.info.removeOnlyWithWebp")]}),e.jsxs("p",{children:["• ",s("superadmin.coverMaintenance.legacyCleanup.info.noAffectCurrent")]})]})]})]}),e.jsx(Je,{open:!!h,onOpenChange:async r=>{if(!r&&h){const{companyId:m,companyName:N}=h;g(null),await new Promise(M=>
6setTimeout(M,1500)),Pe(m,N);return}r||g(null)},children:e.jsxs(Qe,{className:"max-w-4xl max-h-[90vh]",children:[e.jsxs(Ye,{children:[e.jsxs(Ze,{className:"flex items-center gap-2",children:[e.jsx(as,{className:"w-5 h-5 text-warning"}),s("superadmin.coverMaintenance.galleriesModal.title").replace("{company}",(h==null?void 0:h.companyName)||"")]}),e.jsx(es,{children:s("superadmin.coverMaintenance.galleriesModal.description").replace("{count}",String((h==null?void 0:h.galleries.length)||0))})]}),h&&e.jsx(ma,{companyId:h.companyId,companyName:h.companyName,totalGalleries:h.galleries.length>0?h.galleries.length:h.allGalleriesCount}),e.jsx(Oe,{className:"max-h-[30vh]",children:e.jsx("div",{className:"space-y-2 pr-4",children:h==null?void 0:h.galleries.map((r,m)=>e.jsx("div",{className:"p-3 border rounded-lg hover:bg-muted/50",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[m+1,"."]}),e.jsx("p",{className:"font-medium truncate",children:r.title||s("superadmin.coverMaintenance.galleriesModal.noTitle")})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsxs("code",{className:"text-xs text-muted-foreground font-mono bg-muted px-1 rounded",children:[r.id.substring(0,8),"..."]}),e.jsx(U,{variant:"ghost",size:"sm",className:"h-5 px-1",onClick:()=>Y(r.id),children:e.jsx(Os,{className:"w-3 h-3"})})]})]}),e.jsx("div",{className:"flex flex-wrap gap-1 shrink-0",children:r.missingVersions.map(N=>e.jsx(X,{variant:"outline",className:"text-xs",children:N},N))})]})},r.id))})}),e.jsx("div",{className:"pt-4 border-t text-sm text-muted-foreground",children:e.jsxs("p",{children:[e.jsx(Ce,{className:"w-4 h-4 inline mr-1 text-purple-500"}),s("superadmin.coverMaintenance.galleriesModal.useCanvasInfo"),e.jsx(Bs,{className:"w-4 h-4 inline mr-1 ml-1"}),e.jsx("strong",{children:"Edge Function:"})," ",s("superadmin.coverMaintenance.galleriesModal.edgeFunctionFallback").replace("Edge Function: ","")]})})]})}),e.jsx(Je,{open:!!a,onOpenChange:()=>L(null),children:e.jsxs(Qe,{className:"max-w-3xl",children:[e.jsxs(Ye,{children:[e.jsxs(Ze,{className:"flex items-center gap-2",children:[e.jsx(ls,{className:"w-5 h-5 text-destructive"}),"Erros de Cover - ",a==null?void 0:a.companyName]}),e.jsx(es,{children:"Galerias com imagens de cover inválidas ou corrompidas que precisam de re-upload manual."})]}),e.jsx(Oe,{className:"max-h-[60vh]",children:e.jsx("div",{className:"space-y-3 pr-4",children:a==null?void 0:a.errors.map((r,m)=>{const N=r.message.toLowerCase().includes("invalid"),M=r.message.toLowerCase().includes("not found"),T=r.message.toLowerCase().includes("content-type");let p="Verifique o arquivo original.",v=e.jsx(Ae,{className:"w-4 h-4 text-destructive shrink-0"});return N||T?(p="A imagem está corrompida ou em formato inválido. Re-upload necessário.",v=e.jsx(ls,{className:"w-4 h-4 text-destructive shrink-0"})):M&&(p="O arquivo não existe mais no storage. Re-upload necessário.",v=e.jsx($e,{className:"w-4 h-4 text-yellow-500 shrink-0"})),e.jsx("div",{className:"p-3 border rounded-lg bg-destructive/5",children:e.jsxs("div",{className:"flex items-start gap-3",children:[v,e.jsxs("div",{className:"space-y-1 flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:r.galleryTitle||"Sem título"}),e.jsx("p",{className:"text-sm text-destructive",children:r.message}),e.jsx("p",{className:"text-xs text-muted-foreground italic",children:p}),e.jsx("p",{className:"text-xs text-muted-foreground font-mono truncate",children:r.galleryId})]}),r.coverUrl&&e.jsx("a",{href:r.coverUrl,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline shrink-0",children:"Ver Original"})]})},m)})})}),e.jsx("div",{className:"pt-4 border-t",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx($e,{className:"w-4 h-4 inline mr-1 text-yellow-500"}
6),"Essas galerias precisam ter suas imagens de cover re-enviadas pelo admin da empresa."]})})]})}),e.jsx(Je,{open:!!k,onOpenChange:r=>{if(!r){ie("deepValidation");return}},children:e.jsxs(Qe,{className:"max-w-5xl max-h-[90vh]",onInteractOutside:r=>r.preventDefault(),onEscapeKeyDown:r=>{r.preventDefault(),ie("deepValidation")},children:[e.jsxs(Ye,{children:[e.jsxs(Ze,{className:"flex items-center gap-2",children:[e.jsx(Ne,{className:"w-5 h-5"}),s("superadmin.coverMaintenance.deepValidationModal.title")]}),e.jsx(es,{children:s("superadmin.coverMaintenance.deepValidationModal.description")})]}),k&&e.jsx(pa,{companyId:k.companyId,companyName:k.companyName,onClose:()=>z(null)})]})}),e.jsx(Je,{open:!!y,onOpenChange:r=>{if(!r){ie("batchValidation");return}},children:e.jsxs(Qe,{className:"max-w-4xl max-h-[90vh]",onInteractOutside:r=>r.preventDefault(),onEscapeKeyDown:r=>{r.preventDefault(),ie("batchValidation")},children:[e.jsxs(Ye,{children:[e.jsxs(Ze,{className:"flex items-center gap-2",children:[e.jsx(Ne,{className:"w-5 h-5"}),s("superadmin.coverMaintenance.batchValidationModal.title")]}),e.jsx(es,{children:s("superadmin.coverMaintenance.batchValidationModal.description")})]}),y&&e.jsx(va,{companies:y,autoRegenerate:!1,onClose:()=>{A(null),te(new Set)}})]})}),e.jsx(Ws,{open:!!ee,onOpenChange:r=>!r&&ie(null),children:e.jsxs(Fs,{children:[e.jsxs(Ls,{children:[e.jsx(Us,{children:s("superadmin.coverMaintenance.closeConfirm.title")}),e.jsx(Gs,{children:s("superadmin.coverMaintenance.closeConfirm.description")})]}),e.jsxs(qs,{children:[e.jsx(Hs,{children:s("superadmin.coverMaintenance.closeConfirm.cancel")}),e.jsx(Ks,{onClick:()=>{ee==="deepValidation"?z(null):ee==="batchValidation"&&(A(null),te(new Set)),ie(null)},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:s("superadmin.coverMaintenance.closeConfirm.confirm")})]})]})})]})};export{Wa 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.