limbo-component 2.3.0 → 2.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/limbo.es.js CHANGED
@@ -21,22 +21,22 @@ return s("div",{className:"fixed inset-0 bg-black/95 z-[10000] flex flex-col",ro
21
21
  /* @__PURE__ */l("kbd",{className:"px-1.5 py-0.5 bg-white/10 rounded text-white",children:"+"})," /"," ",
22
22
  /* @__PURE__ */l("kbd",{className:"px-1.5 py-0.5 bg-white/10 rounded text-white",children:"-"})," zoom •"," ","Doble click para ampliar/restablecer •"," ","Flechas para mover •"," ",
23
23
  /* @__PURE__ */l("kbd",{className:"px-1.5 py-0.5 bg-white/10 rounded text-white",children:"ESC"})," cerrar"]}),
24
- /* @__PURE__ */l("span",{className:"sm:hidden",children:"Doble click para zoom • ESC para cerrar"})]})})]})}function W({image:i,isOpen:o,onClose:u,onSelect:d,onDelete:m,onCrop:h,onVariantDeleted:p,allowedActions:f={select:!0,download:!0,copy:!0,delete:!0,crop:!0}}){const{loadVariants:g,getVariants:b,isLoading:y,getError:v,removeVariant:w}=q(),x=window.limboCore?.accessibilityManager,[k,C]=e.useState(null),[S,N]=e.useState(null),[E,$]=t(null),_=(window.limboCore?.config?.getGlobal()||{}).interaction||{allowSelection:!1,allowCropping:!0},z=_.allowSelection&&f.select&&d,T=_.allowCropping&&f.crop&&h,A=f.download,M=f.delete,[P,I]=e.useState(/* @__PURE__ */new Set),L=a(null),D=a(null),O=r(e=>{if("Escape"===e.key){if(E)return;e.preventDefault(),u?.()}if("Tab"===e.key&&L.current){const t=L.current.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'),n=t[0],r=t[t.length-1];e.shiftKey&&document.activeElement===n?(e.preventDefault(),r?.focus()):e.shiftKey||document.activeElement!==r||(e.preventDefault(),n?.focus())}},[u,E]);n(()=>{if(o)return D.current?.focus(),document.addEventListener("keydown",O),()=>document.removeEventListener("keydown",O)},[o,O]);const R=e.useMemo(()=>i?.variants||[],[i?.variants]),j=b(i?.id),F=R.length>0?R:j,U=0===R.length&&y(i?.id),W=0===R.length?v(i?.id):null;n(()=>{!o||!i?.id||i?.variants&&0!==i.variants.length||g(i.id)},[o,i?.id,i?.variants,g]),e.useEffect(()=>{o&&I(/* @__PURE__ */new Set)},[o]);if(!o)return null;const V=[{...i,isOriginal:!0},...F.map(e=>({...e,isOriginal:!1}))];/* @__PURE__ */
24
+ /* @__PURE__ */l("span",{className:"sm:hidden",children:"Doble click para zoom • ESC para cerrar"})]})})]})}function W({image:i,isOpen:o,onClose:u,onSelect:d,onDelete:m,onCrop:h,onVariantDeleted:p,allowedActions:f={select:!0,download:!0,copy:!0,delete:!0,crop:!0}}){const{loadVariants:g,getVariants:b,isLoading:y,getError:v,removeVariant:w}=q(),x=window.limboCore?.accessibilityManager,[k,C]=e.useState(null),[S,N]=e.useState(null),[E,$]=t(null),_=(window.limboCore?.config?.getGlobal()||{}).interaction||{allowSelection:!1,allowCropping:!0},z=_.allowSelection&&f.select&&d,T=_.allowCropping&&f.crop&&h,A=f.download,M=f.delete,[P,I]=e.useState(/* @__PURE__ */new Set),[L,D]=e.useState(/* @__PURE__ */new Set),O=a(null),R=a(null),j=r(e=>{if("Escape"===e.key){if(E)return;e.preventDefault(),u?.()}if("Tab"===e.key&&O.current){const t=O.current.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'),n=t[0],r=t[t.length-1];e.shiftKey&&document.activeElement===n?(e.preventDefault(),r?.focus()):e.shiftKey||document.activeElement!==r||(e.preventDefault(),n?.focus())}},[u,E]);n(()=>{if(o)return R.current?.focus(),document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[o,j]);const F=e.useMemo(()=>i?.variants||[],[i?.variants]),U=b(i?.id),W=(F.length>0?F:U).filter(e=>!L.has(e.id)),V=0===F.length&&y(i?.id),H=0===F.length?v(i?.id):null;n(()=>{!o||!i?.id||i?.variants&&0!==i.variants.length||g(i.id)},[o,i?.id,i?.variants,g]),e.useEffect(()=>{o&&(I(/* @__PURE__ */new Set),D(/* @__PURE__ */new Set))},[o]);if(!o)return null;const K=[{...i,isOriginal:!0},...W.map(e=>({...e,isOriginal:!1}))];/* @__PURE__ */
25
25
  return s("div",{className:"fixed inset-0 bg-black/85 flex items-center justify-center z-[1000] p-4",onClick:()=>{E||u?.()},role:"dialog","aria-modal":"true","aria-labelledby":"variants-modal-title","aria-describedby":"variants-modal-description",children:[
26
- /* @__PURE__ */s("div",{ref:L,className:"bg-white rounded-xl max-w-[95vw] max-h-[90vh] overflow-hidden shadow-2xl flex flex-col w-[900px]",onClick:e=>e.stopPropagation(),children:[
26
+ /* @__PURE__ */s("div",{ref:O,className:"bg-white rounded-xl max-w-[95vw] max-h-[90vh] overflow-hidden shadow-2xl flex flex-col w-[900px]",onClick:e=>e.stopPropagation(),children:[
27
27
  /* @__PURE__ */s("div",{className:"px-5 py-4 border-b border-gray-200 flex justify-between items-center bg-gray-50",children:[
28
28
  /* @__PURE__ */s("div",{className:"flex-1 min-w-0 pr-4",children:[
29
29
  /* @__PURE__ */l("h2",{id:"variants-modal-title",className:"m-0 text-lg font-semibold text-gray-900 truncate",children:i?.filename}),
30
- /* @__PURE__ */s("p",{id:"variants-modal-description",className:"text-sm text-gray-500 mt-1",children:["Imagen original y ",F.length," recorte",1!==F.length?"s":""," disponible",1!==F.length?"s":""]})]}),
31
- /* @__PURE__ */l("button",{ref:D,className:"w-10 h-10 flex items-center justify-center rounded-lg bg-gray-100 hover:bg-red-200 text-gray-500 hover:text-red-1000 transition-colors focus:outline-none focus:ring-2 focus:ring-brand-blue-400",onClick:u,"aria-label":"Cerrar modal (ESC)",title:"Cerrar (ESC)",children:/* @__PURE__ */l("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */l("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),k&&/* @__PURE__ */l("div",{className:"mx-2 mt-2 px-2 py-1.5 rounded text-xs "+("success"===S?"bg-green-50 text-green-1000":"bg-red-50 text-red-1000"),role:"alert",children:k}),
32
- /* @__PURE__ */l("div",{className:"p-5 overflow-y-auto flex-1 bg-gray-50/50",children:U?/* @__PURE__ */s("div",{className:"text-center py-16 text-gray-500",role:"status","aria-live":"polite",children:[
30
+ /* @__PURE__ */s("p",{id:"variants-modal-description",className:"text-sm text-gray-500 mt-1",children:["Imagen original y ",W.length," recorte",1!==W.length?"s":""," disponible",1!==W.length?"s":""]})]}),
31
+ /* @__PURE__ */l("button",{ref:R,className:"w-10 h-10 flex items-center justify-center rounded-lg bg-gray-100 hover:bg-red-200 text-gray-500 hover:text-red-1000 transition-colors focus:outline-none focus:ring-2 focus:ring-brand-blue-400",onClick:u,"aria-label":"Cerrar modal (ESC)",title:"Cerrar (ESC)",children:/* @__PURE__ */l("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */l("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),k&&/* @__PURE__ */l("div",{className:"mx-2 mt-2 px-2 py-1.5 rounded text-xs "+("success"===S?"bg-green-50 text-green-1000":"bg-red-50 text-red-1000"),role:"alert",children:k}),
32
+ /* @__PURE__ */l("div",{className:"p-5 overflow-y-auto flex-1 bg-gray-50/50",children:V?/* @__PURE__ */s("div",{className:"text-center py-16 text-gray-500",role:"status","aria-live":"polite",children:[
33
33
  /* @__PURE__ */l("div",{className:"w-12 h-12 border-4 border-gray-200 border-t-brand-blue-800 rounded-full animate-spin mx-auto mb-4"}),
34
- /* @__PURE__ */l("p",{className:"text-base",children:"Cargando variantes..."})]}):W?/* @__PURE__ */s("div",{className:"text-center py-16 text-red-1000",role:"alert",children:[
34
+ /* @__PURE__ */l("p",{className:"text-base",children:"Cargando variantes..."})]}):H?/* @__PURE__ */s("div",{className:"text-center py-16 text-red-1000",role:"alert",children:[
35
35
  /* @__PURE__ */l("svg",{className:"w-12 h-12 mx-auto mb-4 text-red-800",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */l("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),
36
- /* @__PURE__ */s("p",{className:"text-base font-medium",children:["Error: ",W]}),
37
- /* @__PURE__ */l("button",{onClick:()=>g(i.id),className:"mt-4 text-sm px-5 py-2.5 rounded-lg bg-brand-blue-800 text-white hover:bg-brand-blue-1000 focus:outline-none focus:ring-2 focus:ring-brand-blue-400 focus:ring-offset-2",children:"Reintentar"})]}):0===F.length?/* @__PURE__ */s("div",{className:"text-center py-16 text-gray-500",children:[
36
+ /* @__PURE__ */s("p",{className:"text-base font-medium",children:["Error: ",H]}),
37
+ /* @__PURE__ */l("button",{onClick:()=>g(i.id),className:"mt-4 text-sm px-5 py-2.5 rounded-lg bg-brand-blue-800 text-white hover:bg-brand-blue-1000 focus:outline-none focus:ring-2 focus:ring-brand-blue-400 focus:ring-offset-2",children:"Reintentar"})]}):0===W.length?/* @__PURE__ */s("div",{className:"text-center py-16 text-gray-500",children:[
38
38
  /* @__PURE__ */l("svg",{className:"w-12 h-12 mx-auto mb-4 text-gray-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */l("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})}),
39
- /* @__PURE__ */l("p",{className:"text-base",children:"No hay recortes disponibles"})]}):/* @__PURE__ */l("div",{className:"grid grid-cols-2 lg:grid-cols-3 gap-5",role:"list","aria-label":"Lista de imágenes",children:V.map((e,t)=>{const n=e.isOriginal,r=!n&&P.has(e.id),a=e.url,o=n?"Original":e.name||e.filename||`Recorte ${t}`,f=n?i.width:e.width,g=n?i.height:e.height,b=n?i.file_size:e.file_size||0;/* @__PURE__ */
39
+ /* @__PURE__ */l("p",{className:"text-base",children:"No hay recortes disponibles"})]}):/* @__PURE__ */l("div",{className:"grid grid-cols-2 lg:grid-cols-3 gap-5",role:"list","aria-label":"Lista de imágenes",children:K.map((e,t)=>{const n=e.isOriginal,r=!n&&P.has(e.id),a=e.url,o=n?"Original":e.name||e.filename||`Recorte ${t}`,f=n?i.width:e.width,g=n?i.height:e.height,b=n?i.file_size:e.file_size||0;/* @__PURE__ */
40
40
  return s("article",{role:"listitem","aria-label":`${o} - ${f}×${g} píxeles`,className:`rounded-xl overflow-hidden transition-all shadow-sm hover:shadow-lg ${n?"ring-2 ring-brand-blue-800 ring-offset-2 bg-white":"border border-gray-200 bg-white hover:border-brand-blue-400"} focus-within:ring-2 focus-within:ring-brand-blue-400`,children:[
41
41
  /* @__PURE__ */s("button",{type:"button",title:"Click para ampliar con zoom",className:"relative w-full cursor-pointer aspect-square flex items-center justify-center overflow-hidden bg-gray-100 focus:outline-none group",onClick:r?void 0:()=>{return n?(x?.announce(`Abriendo visor de imagen: ${i.filename}`),void $({src:i.url,title:i.filename||"Original",subtitle:`${i.width}×${i.height} · ${Math.round((i.file_size||0)/1024)}KB`})):(t=e,x?.announce(`Abriendo visor de imagen: ${t.name}`),void $({src:t.url,title:t.name||t.filename||"Recorte",subtitle:`${t.width}×${t.height} · ${Math.round((t.file_size||0)/1024)}KB`}));var t},"aria-label":`Ver ${o} en tamaño completo con zoom`,disabled:r,children:[r?/* @__PURE__ */s("div",{className:"text-center text-gray-400",children:[
42
42
  /* @__PURE__ */l("svg",{className:"w-10 h-10 mx-auto mb-2",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */l("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),
@@ -48,7 +48,7 @@ return s("article",{role:"listitem","aria-label":`${o} - ${f}×${g} píxeles`,cl
48
48
  /* @__PURE__ */l("h3",{className:"text-sm font-semibold text-gray-900 truncate mb-2",title:o,children:o}),
49
49
  /* @__PURE__ */s("div",{className:"flex items-center justify-between",children:[
50
50
  /* @__PURE__ */s("span",{className:"text-xs text-gray-500 font-medium",children:[f,"×",g," ·"," ",Math.round(b/1024),"KB"]}),
51
- /* @__PURE__ */s("div",{className:"flex gap-2",role:"group","aria-label":`Acciones para ${o}`,children:[n&&T&&/* @__PURE__ */l("button",{type:"button",className:"w-8 h-8 rounded-lg bg-brand-blue-400 hover:bg-brand-blue-800 cursor-pointer text-white flex items-center justify-center focus:outline-none focus:ring-2 focus:ring-brand-blue-400 focus:ring-offset-1 transition-colors shadow-sm",onClick:e=>{e.stopPropagation(),h&&(x?.announce(`Abriendo herramienta de recorte para ${i.filename}`),h(i),u?.())},"aria-label":"Crear nuevo recorte",title:"Recortar",children:/* @__PURE__ */l("span",{className:"icon icon-scissors-white icon--sm"})}),A&&/* @__PURE__ */l("button",{type:"button",className:"w-8 h-8 rounded-lg bg-brand-blue-400 hover:bg-brand-blue-800 cursor-pointer text-white flex items-center justify-center focus:outline-none focus:ring-2 focus:ring-brand-blue-400 focus:ring-offset-1 transition-colors shadow-sm",onClick:t=>{t.stopPropagation(),n?(async()=>{const{downloadImage:e}=await Promise.resolve().then(()=>Qt);await e(i.url||i.path,i.filename||"limbo-image",{originalFormat:i.format,accessibilityManager:x})})():(async e=>{const{downloadImage:t}=await Promise.resolve().then(()=>Qt);await t(e.url,e.name||"limbo-variant",{originalFormat:e.format||e.output_format,accessibilityManager:x})})(e)},"aria-label":`Descargar ${o}`,title:"Descargar",children:/* @__PURE__ */l("span",{className:"icon icon-download-white icon--sm"})}),M&&(!n||m)&&/* @__PURE__ */l("button",{type:"button",className:"w-8 h-8 rounded-lg bg-red-1000 hover:bg-red-800 cursor-pointer text-white flex items-center justify-center focus:outline-none focus:ring-2 focus:ring-red-800 focus:ring-offset-1 transition-colors shadow-sm",onClick:t=>{t.stopPropagation(),n?(async()=>{if(!m)return;window.confirm(`¿Estás seguro de que deseas eliminar "${i.filename}"? Esta acción también eliminará todos sus recortes.`)&&(x?.announce(`Eliminando imagen ${i.filename}`),await m(i.id),u?.())})():(async e=>{if(window.confirm(`¿Estás seguro de que deseas eliminar el recorte "${e.name||e.filename}"?`)){x?.announce(`Eliminando recorte ${e.name||e.filename}`);const t=await w(i.id,e.id);t.success?(C("Recorte eliminado correctamente"),N("success"),x?.announce("Recorte eliminado correctamente"),p?.(),setTimeout(()=>{C(null),N(null)},3e3)):(C(`Error al eliminar recorte: ${t.error}`),N("error"),x?.announceError(`Error al eliminar recorte: ${t.error}`),setTimeout(()=>{C(null),N(null)},5e3))}})(e)},"aria-label":`Eliminar ${o}`,title:"Eliminar",children:/* @__PURE__ */l("span",{className:"icon icon-close-small-white icon--sm"})}),z&&/* @__PURE__ */l("button",{type:"button",className:"w-8 h-8 cursor-pointer rounded-lg bg-brand-blue-1000 text-white hover:bg-brand-blue-800 flex items-center justify-center focus:outline-none focus:ring-2 focus:ring-brand-blue-400 focus:ring-offset-1 transition-colors shadow-sm",onClick:t=>{t.stopPropagation(),n?(d?.(i),u?.()):(e=>{const t={id:e.id,filename:`${i.filename}_${e.name}`,url:e.url,width:e.width,height:e.height,mime_type:`image/${e.format}`,file_size:e.file_size,upload_date:e.created_at,processing_status:"completed",is_variant:!0,parent_asset_id:i.id,variant_info:e};x?.announce(`Recorte seleccionado: ${e.name}`),d?.(t),u?.()})(e)},"aria-label":`Seleccionar ${o}`,title:"Seleccionar",children:/* @__PURE__ */l("span",{className:"icon icon-tick-white icon--sm"})})]})]})]})]},n?"original":e.id)})})})]}),
51
+ /* @__PURE__ */s("div",{className:"flex gap-2",role:"group","aria-label":`Acciones para ${o}`,children:[n&&T&&/* @__PURE__ */l("button",{type:"button",className:"w-8 h-8 rounded-lg bg-brand-blue-400 hover:bg-brand-blue-800 cursor-pointer text-white flex items-center justify-center focus:outline-none focus:ring-2 focus:ring-brand-blue-400 focus:ring-offset-1 transition-colors shadow-sm",onClick:e=>{e.stopPropagation(),h&&(x?.announce(`Abriendo herramienta de recorte para ${i.filename}`),h(i),u?.())},"aria-label":"Crear nuevo recorte",title:"Recortar",children:/* @__PURE__ */l("span",{className:"icon icon-scissors-white icon--sm"})}),A&&/* @__PURE__ */l("button",{type:"button",className:"w-8 h-8 rounded-lg bg-brand-blue-400 hover:bg-brand-blue-800 cursor-pointer text-white flex items-center justify-center focus:outline-none focus:ring-2 focus:ring-brand-blue-400 focus:ring-offset-1 transition-colors shadow-sm",onClick:t=>{t.stopPropagation(),n?(async()=>{const{downloadImage:e}=await Promise.resolve().then(()=>Qt);await e(i.url||i.path,i.filename||"limbo-image",{originalFormat:i.format,accessibilityManager:x})})():(async e=>{const{downloadImage:t}=await Promise.resolve().then(()=>Qt);await t(e.url,e.name||"limbo-variant",{originalFormat:e.format||e.output_format,accessibilityManager:x})})(e)},"aria-label":`Descargar ${o}`,title:"Descargar",children:/* @__PURE__ */l("span",{className:"icon icon-download-white icon--sm"})}),M&&(!n||m)&&/* @__PURE__ */l("button",{type:"button",className:"w-8 h-8 rounded-lg bg-red-1000 hover:bg-red-800 cursor-pointer text-white flex items-center justify-center focus:outline-none focus:ring-2 focus:ring-red-800 focus:ring-offset-1 transition-colors shadow-sm",onClick:t=>{t.stopPropagation(),n?(async()=>{if(!m)return;window.confirm(`¿Estás seguro de que deseas eliminar "${i.filename}"? Esta acción también eliminará todos sus recortes.`)&&(x?.announce(`Eliminando imagen ${i.filename}`),await m(i.id),u?.())})():(async e=>{if(window.confirm(`¿Estás seguro de que deseas eliminar el recorte "${e.name||e.filename}"?`)){x?.announce(`Eliminando recorte ${e.name||e.filename}`);const t=await w(i.id,e.id);t.success?(D(t=>/* @__PURE__ */new Set([...t,e.id])),C("Recorte eliminado correctamente"),N("success"),x?.announce("Recorte eliminado correctamente"),p?.(),setTimeout(()=>{C(null),N(null)},3e3)):(C(`Error al eliminar recorte: ${t.error}`),N("error"),x?.announceError(`Error al eliminar recorte: ${t.error}`),setTimeout(()=>{C(null),N(null)},5e3))}})(e)},"aria-label":`Eliminar ${o}`,title:"Eliminar",children:/* @__PURE__ */l("span",{className:"icon icon-close-small-white icon--sm"})}),z&&/* @__PURE__ */l("button",{type:"button",className:"w-8 h-8 cursor-pointer rounded-lg bg-brand-blue-1000 text-white hover:bg-brand-blue-800 flex items-center justify-center focus:outline-none focus:ring-2 focus:ring-brand-blue-400 focus:ring-offset-1 transition-colors shadow-sm",onClick:t=>{t.stopPropagation(),n?(d?.(i),u?.()):(e=>{const t={id:e.id,filename:`${i.filename}_${e.name}`,url:e.url,width:e.width,height:e.height,mime_type:`image/${e.format}`,file_size:e.file_size,upload_date:e.created_at,processing_status:"completed",is_variant:!0,parent_asset_id:i.id,variant_info:e};x?.announce(`Recorte seleccionado: ${e.name}`),d?.(t),u?.()})(e)},"aria-label":`Seleccionar ${o}`,title:"Seleccionar",children:/* @__PURE__ */l("span",{className:"icon icon-tick-white icon--sm"})})]})]})]})]},n?"original":e.id)})})})]}),
52
52
  /* @__PURE__ */l(B,{isOpen:!!E,src:E?.src||"",alt:E?.title||"Imagen",title:E?.title,subtitle:E?.subtitle,onClose:()=>$(null)})]})}function V({image:n,onDelete:r,onCrop:a,onSelect:i,thumbnailSize:o=32,isDeleting:u=!1,allowedActions:d={select:!0,download:!0,copy:!0,delete:!0,crop:!0,variants:!0}}){const[m,h]=t(!1),[p,f]=t(!1),[g,b]=t(!1),[y,v]=t(n.variants_count||0),{isMobile:w,isTouch:x}=N(),k=window.limboCore?.accessibilityManager,C=(window.limboCore?.config?.getGlobal()||{}).interaction||{allowSelection:!1,allowCropping:!0},S=e=>{e.stopPropagation(),k?.announce(`Eliminando imagen ${n.filename}`,"assertive"),r?.(n)},E=async e=>{e.stopPropagation();let t=n.url||n.path;try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t);else{const e=document.createElement("textarea");e.value=t,e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.focus(),e.select(),document.execCommand("copy"),document.body.removeChild(e)}h(!0),k?.announce(`URL de ${n.filename} copiada al portapapeles. Nota: La URL puede tener un tiempo de validez limitado.`),setTimeout(()=>h(!1),2e3)}catch(r){console.error("Error al copiar URL:",r),k?.announce(`Error al copiar URL de ${n.filename}. Inténtalo de nuevo.`),alert(`Error al copiar URL de ${n.filename}. Por favor, inténtalo de nuevo.`)}},$=async e=>{e.preventDefault(),e.stopPropagation();const{downloadImage:t}=await Promise.resolve().then(()=>Qt);await t(n.url||n.path,n.filename||"limbo-image",{originalFormat:n.format,accessibilityManager:k})},_=e=>{e.stopPropagation(),k?.announce(`Editando imagen ${n.filename}`),a?.(n)},z=n.variants&&n.variants.length>0||y>0,T=y,A=e.useCallback(()=>{v(e=>Math.max(0,e-1))},[]);e.useEffect(()=>{v(n.variants_count||0)},[n.variants_count]);const M=C.allowSelection&&d.select&&i,P=C.allowCropping&&d.crop&&a,I=()=>{z?(k?.announce(`Mostrando recortes de ${n.filename}`),f(!0)):(k?.announce(`Abriendo visor de ${n.filename}`),b(!0))};/* @__PURE__ */
53
53
  return s(c,{children:[
54
54
  /* @__PURE__ */s("div",{className:`limbo-image-card flex flex-col items-center cursor-pointer relative transition ${u?"opacity-50":""} ${w?"limbo-image-card--mobile":""}`,onClick:I,onKeyDown:e=>{switch(e.key){case"Enter":case" ":e.preventDefault(),I();break;case"d":case"D":d.download&&(e.preventDefault(),$(e));break;case"c":case"C":d.copy&&(e.preventDefault(),E(e));break;case"Delete":case"Backspace":d.delete&&r&&(e.preventDefault(),S(e));break;case"x":case"X":d.crop&&a&&(e.preventDefault(),_(e));break;case"v":case"V":d.variants&&(e.preventDefault(),(e=>{e.stopPropagation(),k?.announce(`Mostrando recortes de ${n.filename}`),f(!0)})(e))}},title:z?`Ver ${T} recorte${1!==T?"s":""} de ${n.filename}`:w?"Toque para ampliar imagen":"Click para ampliar imagen con zoom",role:"button",tabIndex:0,"aria-label":`Imagen ${n.filename}. ${n.width}x${n.height} px`,style:{...x&&{touchAction:"manipulation",WebkitTapHighlightColor:"transparent"}},children:[
@@ -61,8 +61,8 @@ return s("div",{className:"limbo-image-card animate-pulse",role:"status","aria-l
61
61
  /* @__PURE__ */l("div",{className:"w-full aspect-square bg-neutral-gray-200 rounded-md flex items-center justify-center",children:/* @__PURE__ */l("span",{className:"icon icon-spinner"})}),
62
62
  /* @__PURE__ */l("div",{className:"limbo-image-card-name opacity-100 position-relative bottom-0 p-2",children:/* @__PURE__ */l("div",{className:"h-4 bg-neutral-gray-200 rounded w-3/4"})}),
63
63
  /* @__PURE__ */l("span",{className:"sr-only",children:"Cargando imágen..."})]})}function K({onSelect:e,onCrop:t,onDelete:r,deletingId:i,images:o,loading:u,error:d,filters:m={name:"",dateFrom:"",dateTo:"",uploadedBy:""},onFiltersChange:h,filterConfig:p={showNameFilter:!0,showUploadedByFilter:!1,showDateFilter:!0},loadingConfig:f={showPlaceholders:!0,placeholderCount:10,showSpinner:!0},allowedActions:g={select:!0,download:!0,copy:!0,delete:!0,crop:!0,variants:!0}}){const b=!1!==p.showNameFilter,y=!0===p.showUploadedByFilter,v=!1!==p.showDateFilter,w=a(null),x=window.limboCore?.accessibilityManager;n(()=>{if(w.current&&window.limboCore?.keyboardManager){const e="gallery-grid";w.current.setAttribute("data-grid-id",e),window.limboCore.keyboardManager.setupGridNavigation(w.current,{itemSelector:".limbo-image-card",gridId:e,columns:"auto"})}},[o]),n(()=>{u?x?.announceLoading(!0,"galería"):u||d?d&&x?.announceError(d,"galería"):(x?.announceLoading(!1,"galería"),o.length>0&&x?.announce(`Se encontraron ${o.length} imágenes en la galería`))},[u,d,o.length,x]);const k=e=>{const{name:t,value:n}=e.target;h&&h({...m,[t]:n})};/* @__PURE__ */
64
- return s("div",{className:"w-full px-4 py-4",children:[
65
- /* @__PURE__ */l("div",{className:"p-2 mb-2",children:/* @__PURE__ */s("form",{className:"limbo-form-grid flex flex-col sm:flex-row flex-wrap gap-4 items-start sm:items-end justify-between",onSubmit:e=>e.preventDefault(),"aria-label":"Filtrar imágenes",children:[b&&/* @__PURE__ */s("div",{className:"flex flex-col w-full sm:min-w-45 sm:flex-1",children:[
64
+ return s("div",{className:"w-full py-4",children:[
65
+ /* @__PURE__ */l("div",{className:"p-2 px-4 mb-2",children:/* @__PURE__ */s("form",{className:"limbo-form-grid flex flex-col sm:flex-row flex-wrap gap-4 items-start sm:items-end justify-between",onSubmit:e=>e.preventDefault(),"aria-label":"Filtrar imágenes",children:[b&&/* @__PURE__ */s("div",{className:"flex flex-col w-full sm:min-w-45 sm:flex-1",children:[
66
66
  /* @__PURE__ */l("label",{htmlFor:"name",className:"limbo-form-label mb-1",children:"Nombre"}),
67
67
  /* @__PURE__ */l("input",{type:"text",name:"name",id:"name",placeholder:"Buscar por nombre...",value:m.name,onChange:k,className:"limbo-form-control",autoComplete:"off"})]}),
68
68
  /* @__PURE__ */s("div",{className:"flex flex-col sm:flex-row flex-wrap gap-2 justify-between items-start sm:items-end w-full sm:w-auto",children:[v&&/* @__PURE__ */s(c,{children:[
@@ -76,7 +76,7 @@ return s("div",{className:"w-full px-4 py-4",children:[
76
76
  /* @__PURE__ */l("input",{type:"text",name:"uploadedBy",id:"uploadedBy",placeholder:"Subido por",value:m.uploadedBy,onChange:k,className:"limbo-form-control"})]})]})]})}),u?/* @__PURE__ */s("div",{className:"relative",children:[
77
77
  /* @__PURE__ */l("div",{className:"absolute inset-0 flex items-center justify-center bg-white/80 z-10 min-h-75",children:/* @__PURE__ */s("div",{className:"flex flex-col items-center gap-3",children:[
78
78
  /* @__PURE__ */l("span",{className:"icon icon-spinner p-4 animate-spin"}),
79
- /* @__PURE__ */l("span",{className:"text-sm text-gray-600 font-medium",children:"Cargando imágenes..."})]})}),f.showPlaceholders&&/* @__PURE__ */l("div",{ref:w,className:"limbo-gallery opacity-30","data-limbo-responsive":!0,role:"grid","aria-label":"Cargando imágenes de la galería","aria-busy":"true",children:Array.from({length:f.placeholderCount}).map((e,t)=>/* @__PURE__ */l("div",{role:"gridcell","aria-posinset":t+1,"aria-setsize":f.placeholderCount,children:/* @__PURE__ */l(H,{})},`skeleton-${t}`))})]}):/* @__PURE__ */l("div",d?{className:"alert alert-danger text-center",children:d}:{ref:w,className:"limbo-gallery","data-limbo-responsive":!0,"data-grid-id":"gallery-grid",role:"grid","aria-label":"Galería de imágenes. Use las flechas para navegar entre imágenes",children:o.length>0?o.map((n,a)=>/* @__PURE__ */l("div",{role:"gridcell","aria-posinset":a+1,"aria-setsize":o.length,children:/* @__PURE__ */l(V,{image:n,onSelect:e,onCrop:t,onDelete:g.delete&&r?()=>r(n.id):null,thumbnailSize:32,isDeleting:i===n.id,allowedActions:g})},n.id)):/* @__PURE__ */l("div",{className:"col-span-full text-center text-gray-500 py-8",role:"status","aria-live":"polite",children:/* @__PURE__ */l("p",{children:"No se han encontrado imágenes"})})})]})}function G({image:e,onDiscard:r,onRetry:a,onDownload:i,onSelect:o,showRetry:c=!1,disabled:u=!1}){const[d,m]=t(null),[h,p]=t({name:"",size:"",type:""}),[f,g]=t(!1);n(()=>{if(!e)return void m(null);const t=URL.createObjectURL(e);return m(t),p({name:e.name||"imagen.webp",size:b(e.size||0),type:e.type||"image/webp"}),()=>{URL.revokeObjectURL(t)}},[e]);const b=e=>{if(0===e)return"0 Bytes";const t=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,t)*100)/100+" "+["Bytes","KB","MB","GB"][t]};return e&&d?/* @__PURE__ */s("div",{className:"w-fit md:w-full bg-white border border-gray-200 rounded-lg px-1 sm:px-3 py-2 m-0 shadow-sm",children:[
79
+ /* @__PURE__ */l("span",{className:"text-sm text-gray-600 font-medium",children:"Cargando imágenes..."})]})}),f.showPlaceholders&&/* @__PURE__ */l("div",{ref:w,className:"limbo-gallery opacity-30","data-limbo-responsive":!0,role:"grid","aria-label":"Cargando imágenes de la galería","aria-busy":"true",children:Array.from({length:f.placeholderCount}).map((e,t)=>/* @__PURE__ */l("div",{role:"gridcell","aria-posinset":t+1,"aria-setsize":f.placeholderCount,children:/* @__PURE__ */l(H,{})},`skeleton-${t}`))})]}):/* @__PURE__ */l("div",d?{className:"alert alert-danger text-center",children:d}:{ref:w,className:"limbo-gallery px-3","data-limbo-responsive":!0,"data-grid-id":"gallery-grid",role:"grid","aria-label":"Galería de imágenes. Use las flechas para navegar entre imágenes",children:o.length>0?o.map((n,a)=>/* @__PURE__ */l("div",{role:"gridcell","aria-posinset":a+1,"aria-setsize":o.length,children:/* @__PURE__ */l(V,{image:n,onSelect:e,onCrop:t,onDelete:g.delete&&r?()=>r(n.id):null,thumbnailSize:32,isDeleting:i===n.id,allowedActions:g})},n.id)):/* @__PURE__ */l("div",{className:"col-span-full text-center text-gray-500 py-8",role:"status","aria-live":"polite",children:/* @__PURE__ */l("p",{children:"No se han encontrado imágenes"})})})]})}function G({image:e,onDiscard:r,onRetry:a,onDownload:i,onSelect:o,showRetry:c=!1,disabled:u=!1}){const[d,m]=t(null),[h,p]=t({name:"",size:"",type:""}),[f,g]=t(!1);n(()=>{if(!e)return void m(null);const t=URL.createObjectURL(e);return m(t),p({name:e.name||"imagen.webp",size:b(e.size||0),type:e.type||"image/webp"}),()=>{URL.revokeObjectURL(t)}},[e]);const b=e=>{if(0===e)return"0 Bytes";const t=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,t)*100)/100+" "+["Bytes","KB","MB","GB"][t]};return e&&d?/* @__PURE__ */s("div",{className:"w-fit md:w-full bg-white border border-gray-200 rounded-lg px-1 sm:px-3 py-2 m-0 shadow-sm",children:[
80
80
  /* @__PURE__ */s("div",{className:"flex items-center justify-between mb-4 px-1",children:[
81
81
  /* @__PURE__ */l("h3",{className:"text-sm font-medium text-gray-700",children:"Vista previa de imagen"}),
82
82
  /* @__PURE__ */l("button",{type:"button",onClick:r,disabled:u,className:"p-1.5 text-gray-400 cursor-pointer hover:text-gray-600 hover:bg-red-300 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed","aria-label":"Descartar imagen",title:"Descartar imagen",children:/* @__PURE__ */l("span",{className:"icon icon-close-small icon--md"})})]}),
@@ -105,13 +105,13 @@ return s("div",{className:"w-full px-4 py-4",children:[
105
105
  /* @__PURE__ */s("button",{type:"button",onClick:()=>o&&o(h.name),disabled:u,className:"flex-1 md:flex-none flex items-center justify-center gap-2 px-4 py-2.5 bg-brand-blue-800 border border-brand-blue-800 text-white rounded-lg hover:bg-brand-blue-1000 cursor-pointer hover:border-brand-blue-1000 transition-colors disabled:opacity-50 disabled:cursor-not-allowed text-sm font-medium shadow-sm","aria-label":"Seleccionar imagen para recortar",children:[
106
106
  /* @__PURE__ */l("span",{className:"icon icon-tick-white icon--sm"}),
107
107
  /* @__PURE__ */l("span",{children:"Seleccionar"})]})]})]}),
108
- /* @__PURE__ */l(B,{isOpen:f,src:d,alt:h.name,title:h.name,subtitle:`${h.size} • ${h.type.split("/")[1]?.toUpperCase()||"IMAGE"}`,onClose:()=>g(!1)})]}):null}function Q({file:e,setFile:t,previewUrl:n,setPreviewUrl:r,fileInputRef:a,onSelect:i,disabled:o}){/* @__PURE__ */
108
+ /* @__PURE__ */l(B,{isOpen:f,src:d,alt:h.name,title:h.name,subtitle:`${h.size} • ${h.type.split("/")[1]?.toUpperCase()||"IMAGE"}`,onClose:()=>g(!1)})]}):null}function Q({file:e,setFile:n,previewUrl:r,setPreviewUrl:a,fileInputRef:i,onSelect:o,disabled:c}){const[u,d]=t(!1),m=e=>{if(n(e),e){const t=URL.createObjectURL(e);a(t)}else a(null)};/* @__PURE__ */
109
109
  return s("div",{className:"flex flex-col items-center gap-6","aria-label":"Subir imagen desde dispositivo",children:[
110
- /* @__PURE__ */s("label",{htmlFor:"file-input",className:"w-fit md:w-full flex flex-col items-center justify-center border-2 border-dashed border-brand-blue-200 rounded-xl p-8 cursor-pointer hover:border-brand-blue-1000 hover:to-bright-blue-200 hover:from-brand-blue-50 focus-within:border-brand-blue-800 from-bright-blue-50 to-brand-blue-50 bg-linear-to-br transition",tabIndex:0,style:{outline:"none"},children:[
110
+ /* @__PURE__ */s("label",{htmlFor:"file-input",className:"w-fit md:w-full flex flex-col items-center justify-center border-2 border-dashed rounded-xl p-8 cursor-pointer transition "+(u?"border-brand-blue-1000 bg-brand-blue-100 scale-[1.02]":"border-brand-blue-200 hover:border-brand-blue-1000 hover:to-bright-blue-200 hover:from-brand-blue-50 focus-within:border-brand-blue-800 from-bright-blue-50 to-brand-blue-50 bg-linear-to-br"),tabIndex:0,style:{outline:"none"},onDragOver:e=>{e.preventDefault(),e.stopPropagation()},onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),c||d(!0)},onDragLeave:e=>{e.preventDefault(),e.stopPropagation(),e.currentTarget.contains(e.relatedTarget)||d(!1)},onDrop:e=>{if(e.preventDefault(),e.stopPropagation(),d(!1),c)return;const t=e.dataTransfer?.files;if(t&&t.length>0){const e=t[0];e.type.startsWith("image/")&&m(e)}},children:[
111
111
  /* @__PURE__ */l("span",{className:"icon icon-upload icon--lg mb-2","aria-hidden":"true"}),
112
112
  /* @__PURE__ */l("span",{className:"font-medium text-brand-blue-1000 mb-1",children:"Haz clic o arrastra una imagen aquí"}),
113
113
  /* @__PURE__ */l("span",{className:"text-sm text-neutral-700",children:"Formatos permitidos: JPG, PNG, GIF, SVG, WebP"}),
114
- /* @__PURE__ */l("input",{id:"file-input",ref:a,type:"file",accept:"image/jpeg,image/png,image/svg,image/webp,image/gif",onChange:e=>{const n=e.target.files[0];if(t(n),n){const e=URL.createObjectURL(n);r(e)}else r(null)},disabled:o,className:"sr-only","aria-label":"Seleccionar imagen"})]}),e&&/* @__PURE__ */l(G,{image:e,onDiscard:()=>{t(null),r(null),a.current&&(a.current.value="")},onDownload:()=>{},onSelect:t=>{if(e&&!o&&i)if(t&&t!==e.name){const n=new File([e],t,{type:e.type});i(n)}else i(e)},showRetry:!1,disabled:o})]})}const Y="/api";const X=/* @__PURE__ */new Map;function J(e=!1){const[r,a]=t([]),[i,o]=t(!0),[l,s]=t(null);n(()=>{const t=`ai-services-${e}`,n=X.get(t),r=Date.now();if(n&&r-n.timestamp<864e5)return a(n.data),void o(!1);let i=!0;return(async()=>{try{const n=await function(e=!1){return A({endpoint:"/ai/services",prod:e,basePath:Y})}(e);if(!i)return;const o=n?.data||n?.result||[],l=Array.isArray(o)?o.map(e=>({label:e.name||e.label,slug:e.slug,type:e.type,description:e.description,image:e.image,costInfo:e.cost_info||null})):Object.entries(o).map(([e,t])=>({label:e,slug:t,type:"image_generation",description:null,image:null,costInfo:null}));a(l),X.set(t,{data:l,timestamp:r})}catch(n){i&&s(n.message)}finally{i&&o(!1)}})(),()=>{i=!1}},[e]);return{services:r,loading:i,error:l,invalidateCache:()=>{X.delete(`ai-services-${e}`)}}}const Z=/* @__PURE__ */new Map;function ee(e=!1){const[n,r]=t(null),[a,i]=t(!1),[o,l]=t(null);return{params:n,loading:a,error:o,fetchParams:async t=>{i(!0),l(null);const n=`${e}-${t}`,a=Date.now(),o=Z.get(n);if(o&&a-o.timestamp<864e5)return r(o.data),i(!1),o.data;try{const i=await function({services:e=null,form:t=!1}={},n=!1){const r={};return e&&(r.services=e),!1!==t&&(r.form=t),A({endpoint:"/ai/params"+(Object.keys(r).length?"?"+new URLSearchParams(r).toString():""),method:"GET",prod:n,basePath:"/api/atenea"})}({services:t,form:!1},e),o=i?.result?.data||i?.data||i?.result||i;return r(o),Z.set(n,{data:o,timestamp:a}),o}catch(s){return l(s.message),r(null),null}finally{i(!1)}},reset:()=>{l(null),r(null)}}}function te({show:e=!1,message:t="Cargando...",className:n=""}){return e?/* @__PURE__ */l("div",{className:`absolute inset-0 bg-white/80 backdrop-blur-sm z-50 flex flex-col items-center justify-center ${n}`,"aria-live":"polite","aria-busy":"true",role:"status",children:/* @__PURE__ */s("div",{className:"flex flex-col items-center gap-4",children:[
114
+ /* @__PURE__ */l("input",{id:"file-input",ref:i,type:"file",accept:"image/jpeg,image/png,image/svg,image/webp,image/gif",onChange:e=>{const t=e.target.files[0];m(t)},disabled:c,className:"sr-only","aria-label":"Seleccionar imagen"})]}),e&&/* @__PURE__ */l(G,{image:e,onDiscard:()=>{n(null),a(null),i.current&&(i.current.value="")},onDownload:()=>{},onSelect:t=>{if(e&&!c&&o)if(t&&t!==e.name){const n=new File([e],t,{type:e.type});o(n)}else o(e)},showRetry:!1,disabled:c})]})}const Y="/api";const X=/* @__PURE__ */new Map;function J(e=!1){const[r,a]=t([]),[i,o]=t(!0),[l,s]=t(null);n(()=>{const t=`ai-services-${e}`,n=X.get(t),r=Date.now();if(n&&r-n.timestamp<864e5)return a(n.data),void o(!1);let i=!0;return(async()=>{try{const n=await function(e=!1){return A({endpoint:"/ai/services",prod:e,basePath:Y})}(e);if(!i)return;const o=n?.data||n?.result||[],l=Array.isArray(o)?o.map(e=>({label:e.name||e.label,slug:e.slug,type:e.type,description:e.description,image:e.image,costInfo:e.cost_info||null})):Object.entries(o).map(([e,t])=>({label:e,slug:t,type:"image_generation",description:null,image:null,costInfo:null}));a(l),X.set(t,{data:l,timestamp:r})}catch(n){i&&s(n.message)}finally{i&&o(!1)}})(),()=>{i=!1}},[e]);return{services:r,loading:i,error:l,invalidateCache:()=>{X.delete(`ai-services-${e}`)}}}const Z=/* @__PURE__ */new Map;function ee(e=!1){const[n,r]=t(null),[a,i]=t(!1),[o,l]=t(null);return{params:n,loading:a,error:o,fetchParams:async t=>{i(!0),l(null);const n=`${e}-${t}`,a=Date.now(),o=Z.get(n);if(o&&a-o.timestamp<864e5)return r(o.data),i(!1),o.data;try{const i=await function({services:e=null,form:t=!1}={},n=!1){const r={};return e&&(r.services=e),!1!==t&&(r.form=t),A({endpoint:"/ai/params"+(Object.keys(r).length?"?"+new URLSearchParams(r).toString():""),method:"GET",prod:n,basePath:"/api/atenea"})}({services:t,form:!1},e),o=i?.result?.data||i?.data||i?.result||i;return r(o),Z.set(n,{data:o,timestamp:a}),o}catch(s){return l(s.message),r(null),null}finally{i(!1)}},reset:()=>{l(null),r(null)}}}function te({show:e=!1,message:t="Cargando...",className:n=""}){return e?/* @__PURE__ */l("div",{className:`absolute inset-0 min-h-50 bg-white/80 backdrop-blur-sm z-50 flex flex-col items-center justify-center ${n}`,"aria-live":"polite","aria-busy":"true",role:"status",children:/* @__PURE__ */s("div",{className:"flex flex-col items-center gap-4",children:[
115
115
  /* @__PURE__ */l("span",{className:"icon icon-spinner p-4 animate-spin"}),
116
116
  /* @__PURE__ */l("p",{className:"text-brand-blue-1000 font-medium text-lg",children:t})]})}):null}function ne({prod:n,disabled:r,onSelect:a}){const i=J(n),o=ee(n),[u,d]=t(""),[m,h]=t(""),[p,f]=t({}),[g,b]=t(!1),[y,v]=t(null),[w,x]=t(null),[k,C]=t(null),[S,N]=t(!0),[E,$]=t(!1);e.useEffect(()=>{if(!i.loading&&1===i.services.length){const e=i.services[0];h(e.slug),N(!1),o.fetchParams(e.slug,!0)}},[i.loading,i.services]),e.useEffect(()=>{if(!m)return;const e=o.params?.[m]?.parameters;if(e){const t=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default??""]));t.service=m,f(t)}},[m,o.params]);const _=e=>{const{name:t,value:n}=e.target;f(e=>({...e,[t]:n}))},z=async(e,t=!1)=>{e.preventDefault(),b(!0),v(null),x(null);try{t?p.prompt=u:d(p.prompt||"");const e=await function(e,t=!1){return A({endpoint:"/ai/generate",method:"POST",body:e,prod:t,basePath:Y})}(p,n);let a=null;if(e?.data?.images&&Array.isArray(e.data.images)&&e.data.images.length>0?a=e.data.images[0]:e?.result?.images&&Array.isArray(e.result.images)&&e.result.images.length>0?a=e.result.images[0]:Array.isArray(e)&&e.length>0?a=e[0]:"string"==typeof e&&(a=e),!a)throw new Error("No se pudo extraer la imagen de la respuesta");if(a.startsWith("http"))try{const e=`${window.limboCore?.config?.getGlobal()?.prod?"https://limbo.lefebvre.es":"https://led-dev-limbo-dev.eu.els.local"}/api/atenea/proxy?url=${encodeURIComponent(a)}`,t=await fetch(e,{credentials:"include",headers:{Authorization:`Bearer ${window.limboCore?.apiClient?.token||""}`}});if(!t.ok)throw new Error(`Failed to download image: ${t.status}`);const n=await t.blob(),r=new File([n],"ai-image.webp",{type:n.type||"image/webp"});C(r)}catch(r){throw new Error(`Error downloading image via proxy: ${r.message}`)}else{const e=a.replace(/^data:image\/\w+;base64,/,""),t=atob(e),n=new Array(t.length);for(let a=0;a<t.length;a++)n[a]=t.charCodeAt(a);const r=new Uint8Array(n),i=new File([r],"ai-image.webp",{type:"image/webp"});C(i)}x(e?.data?.images||e?.result?.images||null)}catch(a){v(a.message||"Error al generar la imagen")}finally{b(!1)}};return i.loading?/* @__PURE__ */s("div",{className:"flex items-center justify-center py-8",children:[
117
117
  /* @__PURE__ */l("span",{className:"limbo-loader mr-2"})," Cargando servicios IA..."]}):i.services.length?/* @__PURE__ */l("div",{className:"flex flex-col mx-4 pb-2",children:/* @__PURE__ */s(c,S?{children:[
@@ -197,7 +197,7 @@ return s("button",{type:"button",onClick:()=>{return t=e.id,void h(e=>e.includes
197
197
  /* @__PURE__ */l("h4",{className:"text-sm font-semibold mb-2",children:"Resultados por portal:"}),
198
198
  /* @__PURE__ */l("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2 text-sm",children:Object.entries(E).map(([e,t])=>/* @__PURE__ */s("div",{className:"flex items-center justify-between p-2 rounded "+(200===t.status?"bg-green-50":"bg-red-50"),children:[t.image?/* @__PURE__ */l("img",{src:t.image,alt:t.title,className:"w-10 h-10 object-cover rounded"}):/* @__PURE__ */l("span",{className:"font-medium",children:t.title}),
199
199
  /* @__PURE__ */l("span",{className:200===t.status?"text-green-1000":"text-red-1000",children:200===t.status?`${t.count} imágenes`:t.response})]},e))})]}),I&&/* @__PURE__ */l("div",{className:"mt-6 md:w-full mx-auto",children:/* @__PURE__ */l(G,{image:I,onDiscard:()=>{L(null),C(null)},onDownload:()=>{},onSelect:e=>{if(i)if(e&&I&&e!==I.name){const t=new File([I],e,{type:I.type});i(t)}else i(I)},showRetry:!1,disabled:r})}),!I&&(S.length>0||w)&&/* @__PURE__ */s(c,{children:[
200
- /* @__PURE__ */s("div",{className:"mt-6 relative","aria-live":"polite",children:[w&&/* @__PURE__ */l("div",{className:"absolute inset-0 bg-white/80 z-10 flex items-center justify-center rounded-lg",children:/* @__PURE__ */s("div",{className:"flex flex-col items-center gap-2",children:[
200
+ /* @__PURE__ */s("div",{className:"mt-6 relative min-h-50","aria-live":"polite",children:[w&&/* @__PURE__ */l("div",{className:"absolute inset-0 bg-white/80 z-10 flex items-center justify-center rounded-lg",children:/* @__PURE__ */s("div",{className:"flex flex-col items-center gap-2",children:[
201
201
  /* @__PURE__ */l("span",{className:"limbo-loader"}),
202
202
  /* @__PURE__ */l("span",{className:"text-sm text-brand-blue-800",children:"Buscando imágenes..."})]})}),
203
203
  /* @__PURE__ */s("div",{className:"relative grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-2",children:[
@@ -223,7 +223,7 @@ return s("button",{type:"button",onClick:()=>{return t=e.id,void h(e=>e.includes
223
223
  return s("div",{className:"limbo-upload-form py-4 min-w-fit max-w-7xl mx-auto",children:[
224
224
  /* @__PURE__ */l("div",{className:b,role:"tablist","aria-label":"Opciones de subida de imagen",style:o?{WebkitOverflowScrolling:"touch",scrollbarWidth:"none",msOverflowStyle:"none"}:void 0,children:me.map(e=>{const t=u===e.id;/* @__PURE__ */
225
225
  return l("button",{type:"button","data-upload-tab-id":e.id,className:y(t),"aria-current":t?"page":void 0,"aria-selected":t,role:"tab",tabIndex:t?0:-1,onClick:()=>d(e.id),onKeyDown:t=>((e,t)=>{const n=me.findIndex(e=>e.id===t);let r=n;switch(e.key){case"ArrowLeft":e.preventDefault(),r=n>0?n-1:me.length-1;break;case"ArrowRight":e.preventDefault(),r=n<me.length-1?n+1:0;break;case"Home":e.preventDefault(),r=0;break;case"End":e.preventDefault(),r=me.length-1;break;case"Enter":case" ":return e.preventDefault(),void d(t);default:return}const a=me[r];a&&(d(a.id),setTimeout(()=>{const e=document.querySelector(`[data-upload-tab-id="${a.id}"]`);e&&e.focus()},0))})(t,e.id),id:`upload-tab-${e.id}`,"aria-controls":`upload-tabpanel-${e.id}`,style:c?{WebkitTapHighlightColor:"transparent"}:void 0,children:e.label},e.id)})}),
226
- /* @__PURE__ */s("div",{className:"limbo-tab-content px-2 py-2",role:"tabpanel",id:`upload-tabpanel-${u}`,"aria-labelledby":`upload-tab-${u}`,children:["upload"===u&&/* @__PURE__ */l(Q,{file:m,setFile:h,previewUrl:p,setPreviewUrl:f,fileInputRef:g,onSelect:e,disabled:n}),"ai"===u&&/* @__PURE__ */l(ne,{apiKey:r,prod:i,disabled:n,onSelect:e}),"stock"===u&&/* @__PURE__ */l(oe,{apiKey:r,prod:i,disabled:n,onSelect:e}),"portals"===u&&/* @__PURE__ */l(de,{apiKey:r,prod:i,disabled:n,onSelect:e})]})]})}const pe="undefined"!=typeof window&&void 0!==window.document,fe=pe?window:{},ge=!!pe&&"ontouchstart"in fe.document.documentElement,be=!!pe&&"PointerEvent"in fe,ye="cropper",ve=`${ye}-canvas`,we=`${ye}-crosshair`,xe=`${ye}-grid`,ke=`${ye}-handle`,Ce=`${ye}-image`,Se=`${ye}-selection`,Ne=`${ye}-shade`,Ee=`${ye}-viewer`,$e="select",_e="move",ze="scale",Te="rotate",Ae="transform",Me="none",Pe="n-resize",Ie="e-resize",Le="s-resize",De="w-resize",Oe="ne-resize",Re="nw-resize",je="se-resize",Fe="sw-resize",Ue=be?"pointerdown":ge?"touchstart":"mousedown",qe=be?"pointermove":ge?"touchmove":"mousemove",Be=be?"pointerup pointercancel":ge?"touchend touchcancel":"mouseup",We="error",Ve="keydown",He="load",Ke="wheel",Ge="action",Qe="actionend",Ye="actionstart",Xe="change",Je="transform";const Ze=Number.isNaN||fe.isNaN;function et(e){return"number"==typeof e&&!Ze(e)}function tt(e){return et(e)&&e>0&&e<1/0}function nt(e){return"object"==typeof e&&null!==e}const{hasOwnProperty:rt}=Object.prototype;function at(e){if(!nt(e))return!1;try{const{constructor:t}=e,{prototype:n}=t;return t&&n&&rt.call(n,"isPrototypeOf")}catch(t){return!1}}function it(e){return"function"==typeof e}function ot(e){return"object"==typeof e&&null!==e&&1===e.nodeType}const lt=/([a-z\d])([A-Z])/g;function st(e){return String(e).replace(lt,"$1-$2").toLowerCase()}const ct=/-[A-z\d]/g;function ut(e){return e.replace(ct,e=>e.slice(1).toUpperCase())}const dt=/\s\s*/;function mt(e,t,n,r){t.trim().split(dt).forEach(t=>{e.removeEventListener(t,n,r)})}function ht(e,t,n,r){t.trim().split(dt).forEach(t=>{e.addEventListener(t,n,r)})}function pt(e,t,n,r){ht(e,t,n,Object.assign(Object.assign({},r),{once:!0}))}const ft={bubbles:!0,cancelable:!0,composed:!0};const gt=Promise.resolve();function bt(e){const{documentElement:t}=e.ownerDocument,n=e.getBoundingClientRect();return{left:n.left+(fe.pageXOffset-t.clientLeft),top:n.top+(fe.pageYOffset-t.clientTop)}}const yt=/deg|g?rad|turn$/i;function vt(e){const t=parseFloat(e)||0;if(0!==t){const[n="rad"]=String(e).match(yt)||[];switch(n.toLowerCase()){case"deg":return t/360*(2*Math.PI);case"grad":return t/400*(2*Math.PI);case"turn":return t*(2*Math.PI)}}return t}const wt="contain";function xt(e,t=wt){const{aspectRatio:n}=e;let{width:r,height:a}=e;const i=tt(r),o=tt(a);if(i&&o){const e=a*n;t===wt&&e>r||"cover"===t&&e<r?a=r/n:r=a*n}else i?a=r/n:o&&(r=a*n);return{width:r,height:a}}function kt(e,...t){if(0===t.length)return e;const[n,r,a,i,o,l]=e,[s,c,u,d,m,h]=t[0];return kt(e=[n*s+a*c,r*s+i*c,n*u+a*d,r*u+i*d,n*m+a*h+o,r*m+i*h+l],...t.slice(1))}const Ct=/left|top|width|height/i,St="open",Nt=/* @__PURE__ */new WeakMap,Et=/* @__PURE__ */new WeakMap,$t=/* @__PURE__ */new Map,_t=fe.document&&Array.isArray(fe.document.adoptedStyleSheets)&&"replaceSync"in fe.CSSStyleSheet.prototype;class zt extends HTMLElement{get $sharedStyle(){return(this.themeColor?`:host{--theme-color: ${this.themeColor};}`:"")+":host([hidden]){display:none!important}"}constructor(){var e,t;super(),this.shadowRootMode=St,this.slottable=!0;const n=null===(t=null===(e=Object.getPrototypeOf(this))||void 0===e?void 0:e.constructor)||void 0===t?void 0:t.$name;n&&$t.set(n,this.tagName.toLowerCase())}static get observedAttributes(){return["shadow-root-mode","slottable","theme-color"]}attributeChangedCallback(e,t,n){if(Object.is(n,t))return;const r=ut(e);let a=n;switch(typeof this[r]){case"boolean":a=null!==n&&"false"!==n;break;case"number":a=Number(n)}switch(this[r]=a,e){case"theme-color":{const e=Et.get(this),t=this.$sharedStyle;e&&t&&(_t?e.replaceSync(t):e.textContent=t);break}}}$propertyChangedCallback(e,t,n){if(!Object.is(n,t))switch(e=st(e),typeof n){case"boolean":!0===n?this.hasAttribute(e)||this.setAttribute(e,""):this.removeAttribute(e);break;case"number":n=Ze(n)?"":String(n);default:n?this.getAttribute(e)!==n&&this.setAttribute(e,n):this.removeAttribute(e)}}connectedCallback(){Object.getPrototypeOf(this).constructor.observedAttributes.forEach(e=>{const t=ut(e);let n=this[t];(function(e){return void 0===e})(n)||this.$propertyChangedCallback(t,void 0,n),Object.defineProperty(this,t,{enumerable:!0,configurable:!0,get:()=>n,set(e){const r=n;n=e,this.$propertyChangedCallback(t,r,e)}})});const e=this.shadowRoot||this.attachShadow({mode:this.shadowRootMode||St});if(Nt.set(this,e),Et.set(this,this.$addStyles(this.$sharedStyle)),this.$style&&this.$addStyles(this.$style),this.$template){const t=document.createElement("template");t.innerHTML=this.$template,e.appendChild(t.content)}if(this.slottable){const t=document.createElement("slot");e.appendChild(t)}}disconnectedCallback(){Et.has(this)&&Et.delete(this),Nt.has(this)&&Nt.delete(this)}$getTagNameOf(e){var t;return null!==(t=$t.get(e))&&void 0!==t?t:e}$setStyles(e){return Object.keys(e).forEach(t=>{let n=e[t];et(n)&&(n=0!==n&&Ct.test(t)?`${n}px`:String(n)),this.style[t]=n}),this}$getShadowRoot(){return this.shadowRoot||Nt.get(this)}$addStyles(e){let t;const n=this.$getShadowRoot();return _t?(t=new CSSStyleSheet,t.replaceSync(e),n.adoptedStyleSheets=n.adoptedStyleSheets.concat(t)):(t=document.createElement("style"),t.textContent=e,n.appendChild(t)),t}$emit(e,t,n){return function(e,t,n,r){return e.dispatchEvent(new CustomEvent(t,Object.assign(Object.assign(Object.assign({},ft),{detail:n}),r)))}(this,e,t,n)}$nextTick(e){return function(e,t){return t?gt.then(e?t.bind(e):t):gt}(this,e)}static $define(e,t){nt(e)&&(t=e,e=""),e||(e=this.$name||this.name),e=st(e),pe&&fe.customElements&&!fe.customElements.get(e)&&customElements.define(e,this,t)}}zt.$version="2.1.0";class Tt extends zt{constructor(){super(...arguments),this.$onPointerDown=null,this.$onPointerMove=null,this.$onPointerUp=null,this.$onWheel=null,this.$wheeling=!1,this.$pointers=/* @__PURE__ */new Map,this.$style=':host{display:block;min-height:100px;min-width:200px;overflow:hidden;position:relative;touch-action:none;-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}:host([background]){background-color:#fff;background-image:repeating-linear-gradient(45deg,#ccc 25%,transparent 0,transparent 75%,#ccc 0,#ccc),repeating-linear-gradient(45deg,#ccc 25%,transparent 0,transparent 75%,#ccc 0,#ccc);background-image:repeating-conic-gradient(#ccc 0 25%,#fff 0 50%);background-position:0 0,.5rem .5rem;background-size:1rem 1rem}:host([disabled]){pointer-events:none}:host([disabled]):after{bottom:0;content:"";cursor:not-allowed;display:block;left:0;pointer-events:none;position:absolute;right:0;top:0}',this.$action=Me,this.background=!1,this.disabled=!1,this.scaleStep=.1,this.themeColor="#39f"}static get observedAttributes(){return super.observedAttributes.concat(["background","disabled","scale-step"])}connectedCallback(){super.connectedCallback(),this.disabled||this.$bind()}disconnectedCallback(){this.disabled||this.$unbind(),super.disconnectedCallback()}$propertyChangedCallback(e,t,n){if(!Object.is(n,t)&&(super.$propertyChangedCallback(e,t,n),"disabled"===e))n?this.$unbind():this.$bind()}$bind(){this.$onPointerDown||(this.$onPointerDown=this.$handlePointerDown.bind(this),ht(this,Ue,this.$onPointerDown)),this.$onPointerMove||(this.$onPointerMove=this.$handlePointerMove.bind(this),ht(this.ownerDocument,qe,this.$onPointerMove)),this.$onPointerUp||(this.$onPointerUp=this.$handlePointerUp.bind(this),ht(this.ownerDocument,Be,this.$onPointerUp)),this.$onWheel||(this.$onWheel=this.$handleWheel.bind(this),ht(this,Ke,this.$onWheel,{passive:!1,capture:!0}))}$unbind(){this.$onPointerDown&&(mt(this,Ue,this.$onPointerDown),this.$onPointerDown=null),this.$onPointerMove&&(mt(this.ownerDocument,qe,this.$onPointerMove),this.$onPointerMove=null),this.$onPointerUp&&(mt(this.ownerDocument,Be,this.$onPointerUp),this.$onPointerUp=null),this.$onWheel&&(mt(this,Ke,this.$onWheel,{capture:!0}),this.$onWheel=null)}$handlePointerDown(e){const{buttons:t,button:n,type:r}=e;if(this.disabled||("pointerdown"===r&&"mouse"===e.pointerType||"mousedown"===r)&&(et(t)&&1!==t||et(n)&&0!==n||e.ctrlKey))return;const{$pointers:a}=this;let i="";if(e.changedTouches)Array.from(e.changedTouches).forEach(({identifier:e,pageX:t,pageY:n})=>{a.set(e,{startX:t,startY:n,endX:t,endY:n})});else{const{pointerId:t=0,pageX:n,pageY:r}=e;a.set(t,{startX:n,startY:r,endX:n,endY:r})}a.size>1?i=Ae:ot(e.target)&&(i=e.target.action||e.target.getAttribute("action")||""),!1!==this.$emit(Ye,{action:i,relatedEvent:e})&&(e.preventDefault(),this.$action=i,this.style.willChange="transform")}$handlePointerMove(e){const{$action:t,$pointers:n}=this;if(this.disabled||t===Me||0===n.size)return;if(!1===this.$emit("actionmove",{action:t,relatedEvent:e}))return;if(e.preventDefault(),e.changedTouches)Array.from(e.changedTouches).forEach(({identifier:e,pageX:t,pageY:r})=>{const a=n.get(e);a&&Object.assign(a,{endX:t,endY:r})});else{const{pointerId:t=0,pageX:r,pageY:a}=e,i=n.get(t);i&&Object.assign(i,{endX:r,endY:a})}const r={action:t,relatedEvent:e};if(t===Ae){const t=new Map(n);let a=0,i=0,o=0,l=0,s=e.pageX,c=e.pageY;n.forEach((e,n)=>{t.delete(n),t.forEach(t=>{let n=t.startX-e.startX,r=t.startY-e.startY,u=t.endX-e.endX,d=t.endY-e.endY,m=0,h=0,p=0,f=0;if(0===n?r<0?p=2*Math.PI:r>0&&(p=Math.PI):n>0?p=Math.PI/2+Math.atan(r/n):n<0&&(p=1.5*Math.PI+Math.atan(r/n)),0===u?d<0?f=2*Math.PI:d>0&&(f=Math.PI):u>0?f=Math.PI/2+Math.atan(d/u):u<0&&(f=1.5*Math.PI+Math.atan(d/u)),f>0||p>0){const n=f-p,r=Math.abs(n);r>a&&(a=r,o=n,s=(e.startX+t.startX)/2,c=(e.startY+t.startY)/2)}if(n=Math.abs(n),r=Math.abs(r),u=Math.abs(u),d=Math.abs(d),n>0&&r>0?m=Math.sqrt(n*n+r*r):n>0?m=n:r>0&&(m=r),u>0&&d>0?h=Math.sqrt(u*u+d*d):u>0?h=u:d>0&&(h=d),m>0&&h>0){const n=(h-m)/m,r=Math.abs(n);r>i&&(i=r,l=n,s=(e.startX+t.startX)/2,c=(e.startY+t.startY)/2)}})});const u=a>0,d=i>0;u&&d?(r.rotate=o,r.scale=l,r.centerX=s,r.centerY=c):u?(r.action=Te,r.rotate=o,r.centerX=s,r.centerY=c):d?(r.action=ze,r.scale=l,r.centerX=s,r.centerY=c):r.action=Me}else{const[e]=Array.from(n.values());Object.assign(r,e)}n.forEach(e=>{e.startX=e.endX,e.startY=e.endY}),r.action!==Me&&this.$emit(Ge,r,{cancelable:!1})}$handlePointerUp(e){const{$action:t,$pointers:n}=this;if(!this.disabled&&t!==Me&&!1!==this.$emit(Qe,{action:t,relatedEvent:e})){if(e.preventDefault(),e.changedTouches)Array.from(e.changedTouches).forEach(({identifier:e})=>{n.delete(e)});else{const{pointerId:t=0}=e;n.delete(t)}0===n.size&&(this.style.willChange="",this.$action=Me)}}$handleWheel(e){if(this.disabled)return;if(e.preventDefault(),this.$wheeling)return;this.$wheeling=!0,setTimeout(()=>{this.$wheeling=!1},50);const t=(e.deltaY>0?-1:1)*this.scaleStep;this.$emit(Ge,{action:ze,scale:t,relatedEvent:e},{cancelable:!1})}$setAction(e){return"string"==typeof e&&(this.$action=e),this}$toCanvas(e){return new Promise((t,n)=>{if(!this.isConnected)return void n(new Error("The current element is not connected to the DOM."));const r=document.createElement("canvas");let a=this.offsetWidth,i=this.offsetHeight,o=1;at(e)&&(tt(e.width)||tt(e.height))&&(({width:a,height:i}=xt({aspectRatio:a/i,width:e.width,height:e.height})),o=a/this.offsetWidth),r.width=a,r.height=i;const l=this.querySelector(this.$getTagNameOf(Ce));l?l.$ready().then(n=>{const s=r.getContext("2d");if(s){const[t,c,u,d,m,h]=l.$getTransform();let p=m,f=h,g=n.naturalWidth,b=n.naturalHeight;1!==o&&(p*=o,f*=o,g*=o,b*=o);const y=g/2,v=b/2;s.fillStyle="transparent",s.fillRect(0,0,a,i),at(e)&&it(e.beforeDraw)&&e.beforeDraw.call(this,s,r),s.save(),s.translate(y,v),s.transform(t,c,u,d,p,f),s.translate(-y,-v),s.drawImage(n,0,0,g,b),s.restore()}t(r)}).catch(n):t(r)})}}Tt.$name=ve,Tt.$version="2.1.0";const At=/* @__PURE__ */new WeakMap,Mt=["alt","crossorigin","decoding","elementtiming","fetchpriority","loading","referrerpolicy","sizes","src","srcset"];class Pt extends zt{constructor(){super(...arguments),this.$matrix=[1,0,0,1,0,0],this.$onLoad=null,this.$onCanvasAction=null,this.$onCanvasActionEnd=null,this.$onCanvasActionStart=null,this.$actionStartTarget=null,this.$style=":host{display:inline-block}img{display:block;height:100%;max-height:none!important;max-width:none!important;min-height:0!important;min-width:0!important;width:100%}",this.$image=new Image,this.initialCenterSize="contain",this.rotatable=!1,this.scalable=!1,this.skewable=!1,this.slottable=!1,this.translatable=!1,this.alt="",this.crossorigin="",this.decoding="",this.elementtiming="",this.fetchpriority="",this.loading="",this.referrerpolicy="",this.sizes="",this.src="",this.srcset=""}set $canvas(e){At.set(this,e)}get $canvas(){return At.get(this)}static get observedAttributes(){return super.observedAttributes.concat(Mt,["initial-center-size","rotatable","scalable","skewable","translatable"])}attributeChangedCallback(e,t,n){Object.is(n,t)||(super.attributeChangedCallback(e,t,n),Mt.includes(e)&&this.$image.setAttribute(e,n))}$propertyChangedCallback(e,t,n){if(!Object.is(n,t)&&(super.$propertyChangedCallback(e,t,n),"initialCenterSize"===e))this.$nextTick(()=>{this.$center(n)})}connectedCallback(){super.connectedCallback();const{$image:e}=this,t=this.closest(this.$getTagNameOf(ve));t&&(this.$canvas=t,this.$setStyles({display:"block",position:"absolute"}),this.$onCanvasActionStart=e=>{var t,n;this.$actionStartTarget=null===(n=null===(t=e.detail)||void 0===t?void 0:t.relatedEvent)||void 0===n?void 0:n.target},this.$onCanvasActionEnd=()=>{this.$actionStartTarget=null},this.$onCanvasAction=this.$handleAction.bind(this),ht(t,Ye,this.$onCanvasActionStart),ht(t,Qe,this.$onCanvasActionEnd),ht(t,Ge,this.$onCanvasAction)),this.$onLoad=this.$handleLoad.bind(this),ht(e,He,this.$onLoad),this.$getShadowRoot().appendChild(e)}disconnectedCallback(){const{$image:e,$canvas:t}=this;t&&(this.$onCanvasActionStart&&(mt(t,Ye,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(mt(t,Qe,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasAction&&(mt(t,Ge,this.$onCanvasAction),this.$onCanvasAction=null)),e&&this.$onLoad&&(mt(e,He,this.$onLoad),this.$onLoad=null),this.$getShadowRoot().removeChild(e),super.disconnectedCallback()}$handleLoad(){const{$image:e}=this;this.$setStyles({width:e.naturalWidth,height:e.naturalHeight}),this.$canvas&&this.$center(this.initialCenterSize)}$handleAction(e){if(this.hidden||!(this.rotatable||this.scalable||this.translatable))return;const{$canvas:t}=this,{detail:n}=e;if(n){const{relatedEvent:e}=n;let{action:r}=n;switch(r!==Ae||this.rotatable&&this.scalable||(r=this.rotatable?Te:this.scalable?ze:Me),r){case _e:if(this.translatable){let r=null;e&&(r=e.target.closest(this.$getTagNameOf(Se))),r||(r=t.querySelector(this.$getTagNameOf(Se))),r&&r.multiple&&!r.active&&(r=t.querySelector(`${this.$getTagNameOf(Se)}[active]`)),r&&!r.hidden&&r.movable&&!r.dynamic&&this.$actionStartTarget&&r.contains(this.$actionStartTarget)||this.$move(n.endX-n.startX,n.endY-n.startY)}break;case Te:if(this.rotatable)if(e){const{x:t,y:r}=this.getBoundingClientRect();this.$rotate(n.rotate,e.clientX-t,e.clientY-r)}else this.$rotate(n.rotate);break;case ze:if(this.scalable)if(e){const t=e.target.closest(this.$getTagNameOf(Se));if(!t||!t.zoomable||t.zoomable&&t.dynamic){const{x:t,y:r}=this.getBoundingClientRect();this.$zoom(n.scale,e.clientX-t,e.clientY-r)}}else this.$zoom(n.scale);break;case Ae:if(this.rotatable&&this.scalable){const{rotate:t}=n;let{scale:r}=n;r<0?r=1/(1-r):r+=1;const a=Math.cos(t),i=Math.sin(t),[o,l,s,c]=[a*r,i*r,-i*r,a*r];if(e){const t=this.getBoundingClientRect(),n=e.clientX-t.x,r=e.clientY-t.y,[a,i,u,d]=this.$matrix,m=n-t.width/2,h=r-t.height/2,p=(m*d-u*h)/(a*d-u*i),f=(h*a-i*m)/(a*d-u*i);this.$transform(o,l,s,c,p*(1-o)+f*s,f*(1-c)+p*l)}else this.$transform(o,l,s,c,0,0)}}}}$ready(e){const{$image:t}=this,n=new Promise((e,n)=>{const r=new Error("Failed to load the image source");if(t.complete)t.naturalWidth>0&&t.naturalHeight>0?e(t):n(r);else{const a=()=>{mt(t,We,i),setTimeout(()=>{e(t)})},i=()=>{mt(t,He,a),n(r)};pt(t,He,a),pt(t,We,i)}});return it(e)&&n.then(t=>(e(t),t)),n}$center(e){const{parentElement:t}=this;if(!t)return this;const n=t.getBoundingClientRect(),r=n.width,a=n.height,{x:i,y:o,width:l,height:s}=this.getBoundingClientRect(),c=i+l/2,u=o+s/2,d=n.x+r/2,m=n.y+a/2;if(this.$move(d-c,m-u),e&&(l!==r||s!==a)){const t=r/l,n=a/s;switch(e){case"cover":this.$scale(Math.max(t,n));break;case"contain":this.$scale(Math.min(t,n))}}return this}$move(e,t=e){if(this.translatable&&et(e)&&et(t)){const[n,r,a,i]=this.$matrix,o=(e*i-a*t)/(n*i-a*r),l=(t*n-r*e)/(n*i-a*r);this.$translate(o,l)}return this}$moveTo(e,t=e){if(this.translatable&&et(e)&&et(t)){const[n,r,a,i]=this.$matrix,o=(e*i-a*t)/(n*i-a*r),l=(t*n-r*e)/(n*i-a*r);this.$setTransform(n,r,a,i,o,l)}return this}$rotate(e,t,n){if(this.rotatable){const r=vt(e),a=Math.cos(r),i=Math.sin(r),[o,l,s,c]=[a,i,-i,a];if(et(t)&&et(n)){const[e,r,a,i]=this.$matrix,{width:u,height:d}=this.getBoundingClientRect(),m=t-u/2,h=n-d/2,p=(m*i-a*h)/(e*i-a*r),f=(h*e-r*m)/(e*i-a*r);this.$transform(o,l,s,c,p*(1-o)-f*s,f*(1-c)-p*l)}else this.$transform(o,l,s,c,0,0)}return this}$zoom(e,t,n){if(!this.scalable||0===e)return this;if(e<0?e=1/(1-e):e+=1,et(t)&&et(n)){const[r,a,i,o]=this.$matrix,{width:l,height:s}=this.getBoundingClientRect(),c=t-l/2,u=n-s/2,d=(c*o-i*u)/(r*o-i*a),m=(u*r-a*c)/(r*o-i*a);this.$transform(e,0,0,e,d*(1-e),m*(1-e))}else this.$scale(e);return this}$scale(e,t=e){return this.scalable&&this.$transform(e,0,0,t,0,0),this}$skew(e,t=0){if(this.skewable){const n=vt(e),r=vt(t);this.$transform(1,Math.tan(r),Math.tan(n),1,0,0)}return this}$translate(e,t=e){return this.translatable&&et(e)&&et(t)&&this.$transform(1,0,0,1,e,t),this}$transform(e,t,n,r,a,i){return et(e)&&et(t)&&et(n)&&et(r)&&et(a)&&et(i)?this.$setTransform(kt(this.$matrix,[e,t,n,r,a,i])):this}$setTransform(e,t,n,r,a,i){if((this.rotatable||this.scalable||this.skewable||this.translatable)&&(Array.isArray(e)&&([e,t,n,r,a,i]=e),et(e)&&et(t)&&et(n)&&et(r)&&et(a)&&et(i))){const o=[...this.$matrix],l=[e,t,n,r,a,i];if(!1===this.$emit(Je,{matrix:l,oldMatrix:o}))return this;this.$matrix=l,this.style.transform=`matrix(${l.join(", ")})`}return this}$getTransform(){return this.$matrix.slice()}$resetTransform(){return this.$setTransform([1,0,0,1,0,0])}}Pt.$name=Ce,Pt.$version="2.1.0";const It=/* @__PURE__ */new WeakMap;class Lt extends zt{constructor(){super(...arguments),this.$onCanvasActionEnd=null,this.$onCanvasActionStart=null,this.$onSelectionChange=null,this.$style=":host{display:block;height:0;left:0;outline:var(--theme-color) solid 1px;position:relative;top:0;width:0}:host([transparent]){outline-color:transparent}",this.x=0,this.y=0,this.width=0,this.height=0,this.slottable=!1,this.themeColor="rgba(0, 0, 0, 0.65)"}set $canvas(e){It.set(this,e)}get $canvas(){return It.get(this)}static get observedAttributes(){return super.observedAttributes.concat(["height","width","x","y"])}connectedCallback(){super.connectedCallback();const e=this.closest(this.$getTagNameOf(ve));if(e){this.$canvas=e,this.style.position="absolute";const t=e.querySelector(this.$getTagNameOf(Se));t&&(this.$onCanvasActionStart=e=>{t.hidden&&e.detail.action===$e&&(this.hidden=!1)},this.$onCanvasActionEnd=e=>{t.hidden&&e.detail.action===$e&&(this.hidden=!0)},this.$onSelectionChange=e=>{const{x:n,y:r,width:a,height:i}=e.defaultPrevented?t:e.detail;this.$change(n,r,a,i),(t.hidden||0===n&&0===r&&0===a&&0===i)&&(this.hidden=!0)},ht(e,Ye,this.$onCanvasActionStart),ht(e,Qe,this.$onCanvasActionEnd),ht(e,Xe,this.$onSelectionChange))}this.$render()}disconnectedCallback(){const{$canvas:e}=this;e&&(this.$onCanvasActionStart&&(mt(e,Ye,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(mt(e,Qe,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onSelectionChange&&(mt(e,Xe,this.$onSelectionChange),this.$onSelectionChange=null)),super.disconnectedCallback()}$change(e,t,n=this.width,r=this.height){return et(e)&&et(t)&&et(n)&&et(r)&&(e!==this.x||t!==this.y||n!==this.width||r!==this.height)?(this.hidden&&(this.hidden=!1),this.x=e,this.y=t,this.width=n,this.height=r,this.$render()):this}$reset(){return this.$change(0,0,0,0)}$render(){return this.$setStyles({transform:`translate(${this.x}px, ${this.y}px)`,width:this.width,height:this.height,outlineWidth:fe.innerWidth})}}Lt.$name=Ne,Lt.$version="2.1.0";class Dt extends zt{constructor(){super(...arguments),this.$onCanvasCropEnd=null,this.$onCanvasCropStart=null,this.$style=':host{background-color:var(--theme-color);display:block}:host([action=move]),:host([action=select]){height:100%;left:0;position:absolute;top:0;width:100%}:host([action=move]){cursor:move}:host([action=select]){cursor:crosshair}:host([action$=-resize]){background-color:transparent;height:15px;position:absolute;width:15px}:host([action$=-resize]):after{background-color:var(--theme-color);content:"";display:block;height:5px;left:50%;position:absolute;top:50%;transform:translate(-50%,-50%);width:5px}:host([action=n-resize]),:host([action=s-resize]){cursor:ns-resize;left:50%;transform:translateX(-50%);width:100%}:host([action=n-resize]){top:-8px}:host([action=s-resize]){bottom:-8px}:host([action=e-resize]),:host([action=w-resize]){cursor:ew-resize;height:100%;top:50%;transform:translateY(-50%)}:host([action=e-resize]){right:-8px}:host([action=w-resize]){left:-8px}:host([action=ne-resize]){cursor:nesw-resize;right:-8px;top:-8px}:host([action=nw-resize]){cursor:nwse-resize;left:-8px;top:-8px}:host([action=se-resize]){bottom:-8px;cursor:nwse-resize;right:-8px}:host([action=se-resize]):after{height:15px;width:15px}@media (pointer:coarse){:host([action=se-resize]):after{height:10px;width:10px}}@media (pointer:fine){:host([action=se-resize]):after{height:5px;width:5px}}:host([action=sw-resize]){bottom:-8px;cursor:nesw-resize;left:-8px}:host([plain]){background-color:transparent}',this.action=Me,this.plain=!1,this.slottable=!1,this.themeColor="rgba(51, 153, 255, 0.5)"}static get observedAttributes(){return super.observedAttributes.concat(["action","plain"])}}Dt.$name=ke,Dt.$version="2.1.0";const Ot=/* @__PURE__ */new WeakMap;class Rt extends zt{constructor(){super(...arguments),this.$onCanvasAction=null,this.$onCanvasActionStart=null,this.$onCanvasActionEnd=null,this.$onDocumentKeyDown=null,this.$action="",this.$actionStartTarget=null,this.$changing=!1,this.$style=':host{display:block;left:0;position:relative;right:0}:host([outlined]){outline:1px solid var(--theme-color)}:host([multiple]){outline:1px dashed hsla(0,0%,100%,.5)}:host([multiple]):after{bottom:0;content:"";cursor:pointer;display:block;left:0;position:absolute;right:0;top:0}:host([multiple][active]){outline-color:var(--theme-color);z-index:1}:host([multiple])>*{visibility:hidden}:host([multiple][active])>*{visibility:visible}:host([multiple][active]):after{display:none}',this.$initialSelection={x:0,y:0,width:0,height:0},this.x=0,this.y=0,this.width=0,this.height=0,this.aspectRatio=NaN,this.initialAspectRatio=NaN,this.initialCoverage=NaN,this.active=!1,this.linked=!1,this.dynamic=!1,this.movable=!1,this.resizable=!1,this.zoomable=!1,this.multiple=!1,this.keyboard=!1,this.outlined=!1,this.precise=!1}set $canvas(e){Ot.set(this,e)}get $canvas(){return Ot.get(this)}static get observedAttributes(){return super.observedAttributes.concat(["active","aspect-ratio","dynamic","height","initial-aspect-ratio","initial-coverage","keyboard","linked","movable","multiple","outlined","precise","resizable","width","x","y","zoomable"])}$propertyChangedCallback(e,t,n){if(!Object.is(n,t))switch(super.$propertyChangedCallback(e,t,n),e){case"x":case"y":case"width":case"height":this.$changing||this.$nextTick(()=>{this.$change(this.x,this.y,this.width,this.height,this.aspectRatio,!0)});break;case"aspectRatio":case"initialAspectRatio":this.$nextTick(()=>{this.$initSelection()});break;case"initialCoverage":this.$nextTick(()=>{tt(n)&&n<=1&&this.$initSelection(!0,!0)});break;case"keyboard":this.$nextTick(()=>{this.$canvas&&(n?this.$onDocumentKeyDown||(this.$onDocumentKeyDown=this.$handleKeyDown.bind(this),ht(this.ownerDocument,Ve,this.$onDocumentKeyDown)):this.$onDocumentKeyDown&&(mt(this.ownerDocument,Ve,this.$onDocumentKeyDown),this.$onDocumentKeyDown=null))});break;case"multiple":this.$nextTick(()=>{if(this.$canvas){const e=this.$getSelections();n?(e.forEach(e=>{e.active=!1}),this.active=!0,this.$emit(Xe,{x:this.x,y:this.y,width:this.width,height:this.height})):(this.active=!1,e.slice(1).forEach(e=>{this.$removeSelection(e)}))}});break;case"precise":this.$nextTick(()=>{this.$change(this.x,this.y)});break;case"linked":n&&(this.dynamic=!0)}}connectedCallback(){super.connectedCallback();const e=this.closest(this.$getTagNameOf(ve));e?(this.$canvas=e,this.$setStyles({position:"absolute",transform:`translate(${this.x}px, ${this.y}px)`}),this.hidden||this.$render(),this.$initSelection(!0),this.$onCanvasActionStart=this.$handleActionStart.bind(this),this.$onCanvasActionEnd=this.$handleActionEnd.bind(this),this.$onCanvasAction=this.$handleAction.bind(this),ht(e,Ye,this.$onCanvasActionStart),ht(e,Qe,this.$onCanvasActionEnd),ht(e,Ge,this.$onCanvasAction)):this.$render()}disconnectedCallback(){const{$canvas:e}=this;e&&(this.$onCanvasActionStart&&(mt(e,Ye,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(mt(e,Qe,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasAction&&(mt(e,Ge,this.$onCanvasAction),this.$onCanvasAction=null)),super.disconnectedCallback()}$getSelections(){let e=[];return this.parentElement&&(e=Array.from(this.parentElement.querySelectorAll(this.$getTagNameOf(Se)))),e}$initSelection(e=!1,t=!1){const{initialCoverage:n,parentElement:r}=this;if(tt(n)&&r){const a=this.aspectRatio||this.initialAspectRatio;let i=(t?0:this.width)||r.offsetWidth*n,o=(t?0:this.height)||r.offsetHeight*n;tt(a)&&({width:i,height:o}=xt({aspectRatio:a,width:i,height:o})),this.$change(this.x,this.y,i,o),e&&this.$center(),this.$initialSelection={x:this.x,y:this.y,width:this.width,height:this.height}}}$createSelection(){const e=this.cloneNode(!0);return this.hasAttribute("id")&&e.removeAttribute("id"),e.initialCoverage=NaN,this.active=!1,this.parentElement&&this.parentElement.insertBefore(e,this.nextSibling),e}$removeSelection(e=this){if(this.parentElement){const t=this.$getSelections();if(t.length>1){const n=t.indexOf(e),r=t[n+1]||t[n-1];r&&(e.active=!1,this.parentElement.removeChild(e),r.active=!0,r.$emit(Xe,{x:r.x,y:r.y,width:r.width,height:r.height}))}else this.$clear()}}$handleActionStart(e){var t,n;const r=null===(n=null===(t=e.detail)||void 0===t?void 0:t.relatedEvent)||void 0===n?void 0:n.target;this.$action="",this.$actionStartTarget=r,!this.hidden&&this.multiple&&!this.active&&r===this&&this.parentElement&&(this.$getSelections().forEach(e=>{e.active=!1}),this.active=!0,this.$emit(Xe,{x:this.x,y:this.y,width:this.width,height:this.height}))}$handleAction(e){const{currentTarget:t,detail:n}=e;if(!t||!n)return;const{relatedEvent:r}=n;let{action:a}=n;const i=r?function(e){if("function"==typeof e.composedPath)return e.composedPath().find(ot)||e.target;return e.target}(r):null;if(!a&&this.multiple&&(a=this.$action||(null==i?void 0:i.action),this.$action=a),!a||this.hidden&&a!==$e||this.multiple&&!this.active&&a!==ze)return;const{width:o,height:l}=this;let s=n.endX-n.startX,c=n.endY-n.startY,{aspectRatio:u}=this;switch(!tt(u)&&r.shiftKey&&(u=tt(o)&&tt(l)?o/l:1),a){case $e:if(0!==s||0!==c){0===s?s=c:0===c&&(c=s);const{$canvas:e}=this,r=bt(t);(this.multiple&&!this.hidden?this.$createSelection():this).$change(n.startX-r.left,n.startY-r.top,Math.abs(s),Math.abs(c),u),s<0?c<0?a=Re:c>0&&(a=Fe):s>0&&(c<0?a=Oe:c>0&&(a=je)),e&&(e.$action=a)}break;case _e:this.movable&&(this.dynamic||this.$actionStartTarget&&this.contains(this.$actionStartTarget))&&this.$move(s,c);break;case ze:if(r&&this.zoomable&&(this.dynamic||this.contains(r.target))){const e=bt(t);this.$zoom(n.scale,r.pageX-e.left,r.pageY-e.top)}break;default:this.$resize(a,s,c,u)}}$handleActionEnd(){this.$action="",this.$actionStartTarget=null}$handleKeyDown(e){if(this.hidden||!this.keyboard||this.multiple&&!this.active||e.defaultPrevented)return;const{activeElement:t}=document;if(!t||!["INPUT","TEXTAREA"].includes(t.tagName)&&!["true","plaintext-only"].includes(t.contentEditable))switch(e.key){case"Backspace":e.metaKey&&(e.preventDefault(),this.$removeSelection());break;case"Delete":e.preventDefault(),this.$removeSelection();break;case"ArrowLeft":e.preventDefault(),this.$move(-1,0);break;case"ArrowRight":e.preventDefault(),this.$move(1,0);break;case"ArrowUp":e.preventDefault(),this.$move(0,-1);break;case"ArrowDown":e.preventDefault(),this.$move(0,1);break;case"+":e.preventDefault(),this.$zoom(.1);break;case"-":e.preventDefault(),this.$zoom(-.1)}}$center(){const{parentElement:e}=this;if(!e)return this;const t=(e.offsetWidth-this.width)/2,n=(e.offsetHeight-this.height)/2;return this.$change(t,n)}$move(e,t=e){return this.$moveTo(this.x+e,this.y+t)}$moveTo(e,t=e){return this.movable?this.$change(e,t):this}$resize(e,t=0,n=0,r=this.aspectRatio){if(!this.resizable)return this;const a=tt(r),{$canvas:i}=this;let{x:o,y:l,width:s,height:c}=this;switch(e){case Pe:l+=n,c-=n,c<0&&(e=Le,c=-c,l-=c),a&&(o+=(t=n*r)/2,s-=t,s<0&&(s=-s,o-=s));break;case Ie:s+=t,s<0&&(e=De,s=-s,o-=s),a&&(l-=(n=t/r)/2,c+=n,c<0&&(c=-c,l-=c));break;case Le:c+=n,c<0&&(e=Pe,c=-c,l-=c),a&&(o-=(t=n*r)/2,s+=t,s<0&&(s=-s,o-=s));break;case De:o+=t,s-=t,s<0&&(e=Ie,s=-s,o-=s),a&&(l+=(n=t/r)/2,c-=n,c<0&&(c=-c,l-=c));break;case Oe:a&&(n=-t/r),l+=n,c-=n,s+=t,s<0&&c<0?(e=Fe,s=-s,c=-c,o-=s,l-=c):s<0?(e=Re,s=-s,o-=s):c<0&&(e=je,c=-c,l-=c);break;case Re:a&&(n=t/r),o+=t,l+=n,s-=t,c-=n,s<0&&c<0?(e=je,s=-s,c=-c,o-=s,l-=c):s<0?(e=Oe,s=-s,o-=s):c<0&&(e=Fe,c=-c,l-=c);break;case je:a&&(n=t/r),s+=t,c+=n,s<0&&c<0?(e=Re,s=-s,c=-c,o-=s,l-=c):s<0?(e=Fe,s=-s,o-=s):c<0&&(e=Oe,c=-c,l-=c);break;case Fe:a&&(n=-t/r),o+=t,s-=t,c+=n,s<0&&c<0?(e=Oe,s=-s,c=-c,o-=s,l-=c):s<0?(e=je,s=-s,o-=s):c<0&&(e=Re,c=-c,l-=c)}return i&&i.$setAction(e),this.$change(o,l,s,c)}$zoom(e,t,n){if(!this.zoomable||0===e)return this;e<0?e=1/(1-e):e+=1;const{width:r,height:a}=this,i=r*e,o=a*e;let l=this.x,s=this.y;return et(t)&&et(n)?(l-=(i-r)*((t-this.x)/r),s-=(o-a)*((n-this.y)/a)):(l-=(i-r)/2,s-=(o-a)/2),this.$change(l,s,i,o)}$change(e,t,n=this.width,r=this.height,a=this.aspectRatio,i=!1){return this.$changing||!et(e)||!et(t)||!et(n)||!et(r)||n<0||r<0?this:(tt(a)&&({width:n,height:r}=xt({aspectRatio:a,width:n,height:r},"cover")),this.precise||(e=Math.round(e),t=Math.round(t),n=Math.round(n),r=Math.round(r)),e===this.x&&t===this.y&&n===this.width&&r===this.height&&Object.is(a,this.aspectRatio)&&!i?this:(this.hidden&&(this.hidden=!1),!1===this.$emit(Xe,{x:e,y:t,width:n,height:r})?this:(this.$changing=!0,this.x=e,this.y=t,this.width=n,this.height=r,this.$changing=!1,this.$render())))}$reset(){const{x:e,y:t,width:n,height:r}=this.$initialSelection;return this.$change(e,t,n,r)}$clear(){return this.$change(0,0,0,0,NaN,!0),this.hidden=!0,this}$render(){return this.$setStyles({transform:`translate(${this.x}px, ${this.y}px)`,width:this.width,height:this.height})}$toCanvas(e){return new Promise((t,n)=>{if(!this.isConnected)return void n(new Error("The current element is not connected to the DOM."));const r=document.createElement("canvas");let{width:a,height:i}=this,o=1;if(at(e)&&(tt(e.width)||tt(e.height))&&(({width:a,height:i}=xt({aspectRatio:a/i,width:e.width,height:e.height})),o=a/this.width),r.width=a,r.height=i,!this.$canvas)return void t(r);const l=this.$canvas.querySelector(this.$getTagNameOf(Ce));l?l.$ready().then(n=>{const s=r.getContext("2d");if(s){const[t,c,u,d,m,h]=l.$getTransform(),p=-this.x,f=-this.y,g=(p*d-u*f)/(t*d-u*c),b=(f*t-c*p)/(t*d-u*c);let y=t*g+u*b+m,v=c*g+d*b+h,w=n.naturalWidth,x=n.naturalHeight;1!==o&&(y*=o,v*=o,w*=o,x*=o);const k=w/2,C=x/2;s.fillStyle="transparent",s.fillRect(0,0,a,i),at(e)&&it(e.beforeDraw)&&e.beforeDraw.call(this,s,r),s.save(),s.translate(k,C),s.transform(t,c,u,d,y,v),s.translate(-k,-C),s.drawImage(n,0,0,w,x),s.restore()}t(r)}).catch(n):t(r)})}}Rt.$name=Se,Rt.$version="2.1.0";class jt extends zt{constructor(){super(...arguments),this.$style=":host{display:flex;flex-direction:column;position:relative;touch-action:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}:host([bordered]){border:1px dashed var(--theme-color)}:host([covered]){bottom:0;left:0;position:absolute;right:0;top:0}:host>span{display:flex;flex:1}:host>span+span{border-top:1px dashed var(--theme-color)}:host>span>span{flex:1}:host>span>span+span{border-left:1px dashed var(--theme-color)}",this.bordered=!1,this.columns=3,this.covered=!1,this.rows=3,this.slottable=!1,this.themeColor="rgba(238, 238, 238, 0.5)"}static get observedAttributes(){return super.observedAttributes.concat(["bordered","columns","covered","rows"])}$propertyChangedCallback(e,t,n){Object.is(n,t)||(super.$propertyChangedCallback(e,t,n),"rows"!==e&&"columns"!==e||this.$nextTick(()=>{this.$render()}))}connectedCallback(){super.connectedCallback(),this.$render()}$render(){const e=this.$getShadowRoot(),t=document.createDocumentFragment();for(let n=0;n<this.rows;n+=1){const e=document.createElement("span");e.setAttribute("role","row");for(let t=0;t<this.columns;t+=1){const t=document.createElement("span");t.setAttribute("role","gridcell"),e.appendChild(t)}t.appendChild(e)}e&&(e.innerHTML="",e.appendChild(t))}}jt.$name=xe,jt.$version="2.1.0";class Ft extends zt{constructor(){super(...arguments),this.$style=':host{display:inline-block;height:1em;position:relative;touch-action:none;-webkit-user-select:none;-moz-user-select:none;user-select:none;vertical-align:middle;width:1em}:host:after,:host:before{background-color:var(--theme-color);content:"";display:block;position:absolute}:host:before{height:1px;left:0;top:50%;transform:translateY(-50%);width:100%}:host:after{height:100%;left:50%;top:0;transform:translateX(-50%);width:1px}:host([centered]){left:50%;position:absolute;top:50%;transform:translate(-50%,-50%)}',this.centered=!1,this.slottable=!1,this.themeColor="rgba(238, 238, 238, 0.5)"}static get observedAttributes(){return super.observedAttributes.concat(["centered"])}}Ft.$name=we,Ft.$version="2.1.0";const Ut=/* @__PURE__ */new WeakMap,qt=/* @__PURE__ */new WeakMap,Bt=/* @__PURE__ */new WeakMap,Wt=/* @__PURE__ */new WeakMap,Vt="vertical";class Ht extends zt{constructor(){super(...arguments),this.$onSelectionChange=null,this.$onSourceImageLoad=null,this.$onSourceImageTransform=null,this.$scale=1,this.$style=":host{display:block;height:100%;overflow:hidden;position:relative;width:100%}",this.resize=Vt,this.selection="",this.slottable=!1}set $image(e){qt.set(this,e)}get $image(){return qt.get(this)}set $sourceImage(e){Wt.set(this,e)}get $sourceImage(){return Wt.get(this)}set $canvas(e){Ut.set(this,e)}get $canvas(){return Ut.get(this)}set $selection(e){Bt.set(this,e)}get $selection(){return Bt.get(this)}static get observedAttributes(){return super.observedAttributes.concat(["resize","selection"])}connectedCallback(){var e,t;super.connectedCallback();let n=null;if(n=this.selection?null!==(t=null===(e=function(e){const t=e.getRootNode();switch(t.nodeType){case 1:return t.ownerDocument;case 9:case 11:return t}return null}(this))||void 0===e?void 0:e.querySelector(this.selection))&&void 0!==t?t:null:this.closest(this.$getTagNameOf(Se)),ot(n)){this.$selection=n,this.$onSelectionChange=this.$handleSelectionChange.bind(this),ht(n,Xe,this.$onSelectionChange);const e=n.closest(this.$getTagNameOf(ve));if(e){this.$canvas=e;const t=e.querySelector(this.$getTagNameOf(Ce));t&&(this.$sourceImage=t,this.$image=t.cloneNode(!0),this.$getShadowRoot().appendChild(this.$image),this.$onSourceImageLoad=this.$handleSourceImageLoad.bind(this),this.$onSourceImageTransform=this.$handleSourceImageTransform.bind(this),ht(t.$image,He,this.$onSourceImageLoad),ht(t,Je,this.$onSourceImageTransform))}this.$render()}}disconnectedCallback(){const{$selection:e,$sourceImage:t}=this;e&&this.$onSelectionChange&&(mt(e,Xe,this.$onSelectionChange),this.$onSelectionChange=null),t&&this.$onSourceImageLoad&&(mt(t.$image,He,this.$onSourceImageLoad),this.$onSourceImageLoad=null),t&&this.$onSourceImageTransform&&(mt(t,Je,this.$onSourceImageTransform),this.$onSourceImageTransform=null),super.disconnectedCallback()}$handleSelectionChange(e){this.$render(e.defaultPrevented?this.$selection:e.detail)}$handleSourceImageLoad(){const{$image:e,$sourceImage:t}=this,n=e.getAttribute("src"),r=t.getAttribute("src");r&&r!==n&&(e.setAttribute("src",r),e.$ready(()=>{this.$render()}))}$handleSourceImageTransform(e){this.$render(void 0,e.detail.matrix)}$render(e,t){const{$canvas:n,$selection:r}=this;e||r.hidden||(e=r),(!e||0===e.x&&0===e.y&&0===e.width&&0===e.height)&&(e={x:0,y:0,width:n.offsetWidth,height:n.offsetHeight});const{x:a,y:i,width:o,height:l}=e,s={},{clientWidth:c,clientHeight:u}=this;let d=c,m=u,h=NaN;switch(this.resize){case"both":h=1,d=o,m=l,s.width=o,s.height=l;break;case"horizontal":h=l>0?u/l:0,d=o*h,s.width=d;break;case Vt:h=o>0?c/o:0,m=l*h,s.height=m;break;default:c>0?h=o>0?c/o:0:u>0&&(h=l>0?u/l:0)}this.$scale=h,this.$setStyles(s),this.$sourceImage&&setTimeout(()=>{this.$transformImageByOffset(null!=t?t:this.$sourceImage.$getTransform(),-a,-i)})}$transformImageByOffset(e,t,n){const{$image:r,$scale:a,$sourceImage:i}=this;if(i&&r&&a>=0){const[i,o,l,s,c,u]=e,d=(t*s-l*n)/(i*s-l*o),m=(n*i-o*t)/(i*s-l*o),h=i*d+l*m+c,p=o*d+s*m+u;r.$ready(e=>{this.$setStyles.call(r,{width:e.naturalWidth*a,height:e.naturalHeight*a})}),r.$setTransform(i,o,l,s,h*a,p*a)}}}Ht.$name=Ee,Ht.$version="2.1.0",Tt.$define(),Ft.$define(),jt.$define(),Dt.$define(),Pt.$define(),Rt.$define(),Lt.$define(),Ht.$define();class Kt{constructor(e,t,n){this.canvasRef=e,this.imageRef=t,this.selectionRef=n}get canvasElement(){return this.canvasRef?.current}get image(){return this.imageRef?.current}get selectionElement(){return this.selectionRef?.current}get isReady(){return!!(this.canvasElement&&this.image&&this.selectionElement)}transform={move:(e,t)=>{if(!this.image)return!1;try{return this.image.$move(e,t),!0}catch(n){return console.warn("Error moving image:",n),!1}},moveTo:(e,t)=>{if(!this.image)return!1;try{return this.image.$moveTo(e,t),!0}catch(n){return console.warn("Error moving image to position:",n),!1}},zoom:e=>{if(!this.image)return!1;try{return this.image.$zoom(e),!0}catch(t){return console.warn("Error zooming image:",t),!1}},rotate:e=>{if(!this.image)return!1;try{const t=e*Math.PI/180;return this.image.$rotate(t),!0}catch(t){return console.warn("Error rotating image:",t),!1}},scale:(e,t=e)=>{if(!this.image)return!1;try{return this.image.$scale(e,t),!0}catch(n){return console.warn("Error scaling image:",n),!1}},center:(e="contain")=>{if(!this.image)return!1;try{return this.image.$center(e),!0}catch(t){return console.warn("Error centering image:",t),!1}},reset:()=>{if(!this.image)return!1;try{return this.image.$resetTransform(),!0}catch(e){return console.warn("Error resetting transform:",e),!1}},getTransform:()=>{if(!this.image)return null;try{return this.image.$getTransform()}catch(e){return console.warn("Error getting transform:",e),null}},setTransform:(e,t,n,r,a,i)=>{if(!this.image)return!1;try{return this.image.$setTransform(e,t,n,r,a,i),!0}catch(o){return console.warn("Error setting transform:",o),!1}},resetZoom:()=>{if(!this.image)return!1;try{const e=this.image.$getTransform();if(!e)return!1;const[t,n,r,a,i,o]=e,l=Math.sqrt(t*t+n*n),s=Math.sqrt(r*r+a*a),c=t/l,u=n/l,d=r/s,m=a/s;return this.image.$setTransform(c,u,d,m,i,o),!0}catch(e){return console.warn("Error resetting zoom:",e),!1}},setZoom:e=>{if(!this.image||e<=0)return!1;try{const t=this.image.$getTransform();if(!t)return!1;const[n,r,a,i,o,l]=t,s=Math.sqrt(n*n+r*r),c=Math.sqrt(a*a+i*i),u=n/s*e,d=r/s*e,m=a/c*e,h=i/c*e;return this.image.$setTransform(u,d,m,h,o,l),!0}catch(t){return console.warn("Error setting zoom level:",t),!1}},getZoom:()=>{if(!this.image)return 1;try{const e=this.image.$getTransform();if(!e)return 1;const[t,n]=e;return Math.sqrt(t*t+n*n)}catch(e){return console.warn("Error getting zoom level:",e),1}},fitToCanvas:(e=.1)=>{if(!this.image||!this.canvasElement)return!1;try{const t=this.canvasElement.getBoundingClientRect();let n=this.image.querySelector("img")||this.image;if(!n?.naturalWidth||!n?.naturalHeight)return!1;const r=1-e,a=t.width*r/n.naturalWidth,i=t.height*r/n.naturalHeight,o=Math.min(a,i,1);return this.transform.setZoom(o)}catch(t){return console.warn("Error fitting to canvas:",t),!1}}};selection={center:()=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$center(),!0}catch(e){return console.warn("Error centering selection:",e),!1}},reset:()=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$reset(),!0}catch(e){return console.warn("Error resetting selection:",e),!1}},setCoverage:e=>{if(!this.selectionElement||e<0||e>1)return!1;try{return this.selectionElement.initialCoverage=e,this.selectionElement.$reset(),!0}catch(t){return console.warn("Error setting coverage:",t),!1}},setAspectRatio:e=>{if(!this.selectionElement)return!1;try{let t;if(""===e||null==e)t=NaN;else if("number"==typeof e)t=e;else{if("string"!=typeof e)return console.warn("Unsupported aspect ratio type:",typeof e,e),!1;if(e.includes("/")){const[n,r]=e.split("/").map(e=>parseFloat(e.trim()));if(isNaN(n)||isNaN(r)||0===r)return console.warn("Invalid aspect ratio format:",e),!1;t=n/r}else if(t=parseFloat(e),isNaN(t))return console.warn("Invalid aspect ratio format:",e),!1}return this.selectionElement.aspectRatio=t,this.selectionElement.$render(),!0}catch(t){return console.warn("Error setting aspect ratio:",t),!1}},move:(e,t)=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$move(e,t),!0}catch(n){return console.warn("Error moving selection:",n),!1}},zoom:e=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$zoom(e),!0}catch(t){return console.warn("Error zooming selection:",t),!1}},change:(e,t,n,r,a)=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$change(e,t,n,r,a),!0}catch(i){return console.warn("Error changing selection:",i),!1}},set:(e,t,n,r)=>{if(!this.selectionElement)return!1;try{return this.selectionElement.x=e,this.selectionElement.y=t,this.selectionElement.width=n,this.selectionElement.height=r,this.selectionElement.$render(),!0}catch(a){return console.warn("Error setting selection:",a),!1}},toCanvas:async(e={})=>{if(!this.selectionElement)return null;try{const t={width:800,height:600,imageSmoothingEnabled:!0,imageSmoothingQuality:"high",...e};return await this.selectionElement.$toCanvas(t)}catch(t){return console.warn("Error exporting to canvas:",t),null}},getData:()=>{if(!this.selectionElement)return null;try{return{x:this.selectionElement.x,y:this.selectionElement.y,width:this.selectionElement.width,height:this.selectionElement.height,aspectRatio:this.selectionElement.aspectRatio}}catch(e){return console.warn("Error getting selection data:",e),null}}};canvas={setBackground:e=>{if(!this.canvasElement)return!1;try{return this.canvasElement.background=e,!0}catch(t){return console.warn("Error setting background:",t),!1}},setScaleStep:e=>{if(!this.canvasElement)return!1;try{return this.canvasElement.scaleStep=e,!0}catch(t){return console.warn("Error setting scale step:",t),!1}},setDisabled:e=>{if(!this.canvasElement)return!1;try{return this.canvasElement.disabled=e,!0}catch(t){return console.warn("Error setting disabled state:",t),!1}}};utils={flipHorizontal:()=>{const e=this.transform.getTransform();if(!e)return!1;const[t,n,r,a,i,o]=e;return this.transform.setTransform(-t,n,r,a,i,o)},flipVertical:()=>{const e=this.transform.getTransform();if(!e)return!1;const[t,n,r,a,i,o]=e;return this.transform.setTransform(t,n,r,-a,i,o)},setupInitialView:async(e={})=>{const{paspartuFactor:t=.85,retries:n=3,retryDelay:r=200}=e;return new Promise(e=>{const a=(i=0)=>{if(!this.isReady)return i<n?void setTimeout(()=>a(i+1),r):void e(!1);try{const o=this.canvasElement.getBoundingClientRect();let l=this.image.querySelector("img")||this.image;if(!l?.naturalWidth||!l?.naturalHeight)return i<n?void setTimeout(()=>a(i+1),r):(this.transform.center(),void e(!1));if(o.width>0&&o.height>0){const n=o.width*t/l.naturalWidth,r=o.height*t/l.naturalHeight,a=Math.min(n,r,1);this.transform.setTransform(a,0,0,a,0,0)?setTimeout(()=>{this.transform.center(),this.selection.center(),e(!0)},100):(this.transform.reset(),setTimeout(()=>{a<1&&this.transform.scale(a),setTimeout(()=>{this.transform.center(),this.selection.center(),e(!0)},100)},100))}else this.transform.center(),e(!1)}catch(o){console.warn("Error in setup:",o),this.transform.center(),e(!1)}};a()})},resetAll:()=>{const e={transform:this.transform.reset(),selection:this.selection.reset(),center:!1};return setTimeout(()=>{e.center=this.transform.center()&&this.selection.center()},100),e},checkExportability:async()=>{try{return!!(await this.selection.toCanvas({width:1,height:1}))}catch{return!1}},resetZoomOnly:()=>this.transform.resetZoom(),getZoomInfo:()=>{const e=this.transform.getZoom();return{current:e,isZoomedIn:e>1,isZoomedOut:e<1,percentage:Math.round(100*e)}},setBackground:e=>this.canvas.setBackground(e)};setupEventListeners(e={}){const{onSelectionChange:t,onImageTransform:n,onAction:r,onActionStart:a,onActionMove:i,onActionEnd:o}=e,l=[];if(t&&this.selectionElement){const e=e=>{t({x:e.detail.x,y:e.detail.y,width:e.detail.width,height:e.detail.height})};this.selectionElement.addEventListener("change",e),l.push(()=>{this.selectionElement&&this.selectionElement.removeEventListener("change",e)})}if(n&&this.image){const e=e=>{n({matrix:e.detail.matrix,oldMatrix:e.detail.oldMatrix})};this.image.addEventListener("transform",e),l.push(()=>{this.image&&this.image.removeEventListener("transform",e)})}if(this.canvasElement){if(r){const e=e=>r(e.detail);this.canvasElement.addEventListener("action",e),l.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("action",e)})}if(a){const e=e=>a(e.detail);this.canvasElement.addEventListener("actionstart",e),l.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionstart",e)})}if(i){const e=e=>i(e.detail);this.canvasElement.addEventListener("actionmove",e),l.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionmove",e)})}if(o){const e=e=>o(e.detail);this.canvasElement.addEventListener("actionend",e),l.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionend",e)})}}return()=>{l.forEach(e=>e())}}}async function Gt(e,t,n={}){const{format:r=null,originalFormat:a="webp",onSuccess:i=null,onError:o=null,accessibilityManager:l=null}=n;try{const n=window.limboCore?.config?.getGlobal(),o=r||n?.downloadFormat||a||"webp",s=`${t.split(".")[0]}.${o}`;if(l&&l.announce(`Descargando ${s}`),e.startsWith("data:image/"))return function(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.style.display="none",document.body.appendChild(n),n.click(),setTimeout(()=>{document.body.removeChild(n)},100)}(e,s),i&&i(s),l&&l.announce(`${s} descargado correctamente`),!0;const c=await fetch(e,{mode:"cors"});if(!c.ok)throw new Error(`HTTP error! status: ${c.status}`);const u=await c.blob();let d=u;const m=u.type;m!==`image/${"jpg"===o?"jpeg":o}`&&function(e){return["webp","jpeg","jpg","png"].includes(e.toLowerCase())}(o)&&(d=await async function(e,t){return new Promise((n,r)=>{const a=new Image,i=URL.createObjectURL(e);a.onload=()=>{try{const r=document.createElement("canvas");r.width=a.width,r.height=a.height;r.getContext("2d").drawImage(a,0,0);const o=`image/${"jpg"===t?"jpeg":t}`,l="png"===t?void 0:.92;r.toBlob(t=>{URL.revokeObjectURL(i),n(t||e)},o,l)}catch(r){URL.revokeObjectURL(i),n(e)}},a.onerror=()=>{URL.revokeObjectURL(i),n(e)},a.src=i})}(u,o));const h=window.URL.createObjectURL(d),p=document.createElement("a");return p.href=h,p.download=s,p.style.display="none",document.body.appendChild(p),p.click(),setTimeout(()=>{window.URL.revokeObjectURL(h),document.body.removeChild(p)},100),i&&i(s),l&&l.announce(`${s} descargado correctamente`),!0}catch(s){return console.error("Error downloading image:",s),o&&o(s),l&&l.announce(`Error al descargar la imagen: ${s.message}`),!1}}const Qt=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:Gt,downloadImage:Gt},Symbol.toStringTag,{value:"Module"}));function Yt({image:e,onSave:o,onCancel:u,onDelete:d,onError:m=null,deleting:h=!1,onVariantCreated:p=null,onUpload:f=null,uploading:g=!1,cropperConfig:b=null}){const[y,v]=t(!1),[w,x]=t(null),[k,C]=t(!1),[S,N]=t(!0),[E,$]=t(!0),[_,z]=t({x:20,y:100}),[T,A]=t(!1),[M,P]=t({x:0,y:0}),[I,L]=t(!1),[D,O]=t(!0),[R,j]=t(!1),[U,q]=t({horizontal:!1,vertical:!1}),[W,V]=t(!1),[H,K]=t(!1),[G,Q]=t(!1),[Y,X]=t(!1),[J]=t(()=>{if(!e||!e.filename)return"image";const[t]=e.filename.split(".");return t}),Z=i(()=>{if(b)return{mandatoryCrops:b.mandatoryCrops||[],allowCustomCrops:!1!==b.allowAdditionalCrops,showDimensionInputs:!0===b.showDimensionInputs,maxCrops:b.maxCrops||null};const e=window.limboCore?.config?.getGlobal()||{};return{mandatoryCrops:e.cropper?.mandatoryCrops||[],allowCustomCrops:!1!==e.cropper?.allowCustomCrops,showDimensionInputs:!0===e.cropper?.showDimensionInputs,maxCrops:e.cropper?.maxCrops||null}},[b]),[ee,ne]=t(()=>Z.mandatoryCrops.length>0?Z.mandatoryCrops.map((e,t)=>({id:`crop-${t}`,label:e.label,width:e.width,height:e.height,required:!1!==e.required,isCustom:!1,confirmed:!1,lockDimensions:!(!e.width||!e.height),savedState:null})):[{id:"crop-default-0",label:J,width:e.width||1920,height:e.height||1080,required:!1,isCustom:!0,confirmed:!1,savedState:null}]),[re,ae]=t(0),ie=ee[re],oe=i(()=>ie&&ie.width&&ie.height?ie.width/ie.height:"",[ie]),le=i(()=>{const e=50;if(!oe||""===oe)return{minWidth:e,minHeight:e};if(oe>=1){return{minWidth:e,minHeight:e/oe}}return{minWidth:e*oe,minHeight:e}},[oe]),[se,ce]=t(!1),[ue,de]=t([]),[me,he]=t(null),pe=window.limboCore?.accessibilityManager,{createCropVariant:fe,loading:ge,error:be}=function(){const[e,n]=t(!1),[r,a]=t(null),[i,o]=t(null),l=async(e,t)=>{if(!e||!t)return a("ID de asset y configuración de variante son requeridos"),null;n(!0),a(null),o(null);try{const n=await F(e,{variant_name:t.name,width:t.width,height:t.height,crop_params:t.crop_params,preset_aspect:t.preset_aspect,preset_size:t.preset_size,output_format:t.output_format});if(n?.result)return o(n.result),n.result;throw new Error("No se pudo crear la variante")}catch(r){return console.error("Error creating variant:",r),a(r.message||"Error desconocido al crear variante"),null}finally{n(!1)}};return{createVariant:l,createCropVariant:async(e,t,n={})=>{const r={name:n.name||`crop_${Date.now()}`,width:n.width||800,height:n.height||600,output_format:n.format||"webp",crop_params:{x:t.x||0,y:t.y||0,width:t.width||1,height:t.height||1}};return await l(e,r)},loading:e,error:r,createdVariant:i,reset:()=>{a(null),o(null)}}}(),ye=((e,i={})=>{const o=a(null),l=a(null),s=a(null),c=a(null),[u,d]=t(null),[m,h]=t(null),[p,f]=t(!1),[g,b]=t(!0),[y,v]=t(0),w={aspectRatio:"",shade:!0,paspartuFactor:.85,...i};n(()=>{o.current&&l.current&&s.current&&(c.current=new Kt(o,l,s),f(!0))},[]),n(()=>{if(c.current)return c.current.setupEventListeners({onSelectionChange:e=>{d(e)},onImageTransform:()=>{v(e=>e+1)}})},[p]),n(()=>{c.current&&e&&(async()=>{c.current.selection.setAspectRatio(w.aspectRatio),c.current.canvas.setBackground(w.shade),await c.current.utils.setupInitialView({paspartuFactor:w.paspartuFactor});const e=await c.current.utils.checkExportability();b(e);const t=l.current?.querySelector("img")||l.current;t?.naturalWidth&&t?.naturalHeight&&h({naturalWidth:t.naturalWidth,naturalHeight:t.naturalHeight,currentWidth:t.width,currentHeight:t.height})})()},[e]),n(()=>{c.current&&p&&c.current.selection.setAspectRatio(w.aspectRatio)},[w.aspectRatio,p]),n(()=>{c.current&&p&&c.current.canvas.setBackground(w.shade)},[w.shade,p]);const x=r(()=>({move:(e,t)=>c.current?.transform.move(e,t)||!1,zoom:e=>c.current?.transform.zoom(e)||!1,rotate:e=>c.current?.transform.rotate(e)||!1,center:()=>c.current?.transform.center()||!1,reset:()=>c.current?.transform.reset()||!1,resetZoom:()=>c.current?.transform.resetZoom()||!1,setZoom:e=>c.current?.transform.setZoom(e)||!1,getZoom:()=>c.current?.transform.getZoom()||1,fitToCanvas:e=>c.current?.transform.fitToCanvas(e)||!1,flipHorizontal:()=>c.current?.utils.flipHorizontal()||!1,flipVertical:()=>c.current?.utils.flipVertical()||!1}),[]),k=r(()=>({center:()=>c.current?.selection.center()||!1,reset:()=>c.current?.selection.reset()||!1,setCoverage:e=>c.current?.selection.setCoverage(e)||!1,setAspectRatio:e=>c.current?.selection.setAspectRatio(e)||!1,toCanvas:e=>c.current?.selection.toCanvas(e)||Promise.resolve(null)}),[]),C=r(()=>({resetAll:()=>{if(c.current){const e=c.current.utils.resetAll();return d(null),e}return!1},setBackground:e=>c.current?.canvas.setBackground(e)||!1,resetZoomOnly:()=>c.current?.utils.resetZoomOnly()||!1,getZoomInfo:()=>c.current?.utils.getZoomInfo()||{current:1,percentage:100,isZoomedIn:!1,isZoomedOut:!1}}),[]);return{refs:{canvasRef:o,imageRef:l,selectionRef:s},state:{cropData:u,imageInfo:m,isReady:p,canExport:g,transformVersion:y},transform:x(),selection:k(),utils:C(),manager:c.current}})(e,{aspectRatio:oe||null,showGrid:S,shade:E,initialCoverage:.5,paspartuFactor:.85}),{refs:ve,state:we,transform:xe,selection:ke,utils:Ce}=ye,{canvasRef:Se,imageRef:Ne,selectionRef:Ee}=ve,{cropData:$e,imageInfo:_e,canExport:ze,transformVersion:Te}=we,Ae=i(()=>_e||{naturalWidth:e.width||1920,naturalHeight:e.height||1080,currentWidth:e.width||1920,currentHeight:e.height||1080},[_e,e.width,e.height]),Me=r(()=>N(e=>!e),[]),Pe=r(()=>$(e=>!e),[]),Ie=r(()=>K(e=>!e),[]),Le=r(()=>Q(e=>!e),[]),De=r(()=>X(e=>!e),[]),Oe=r(()=>xe.center(),[xe]),Re=r(()=>ke.center(),[ke]),je=r(()=>ke.reset(),[ke]),Fe=r((e,t)=>xe.move(e,t),[xe]),Ue=r(e=>xe.zoom(e),[xe]),qe=r(e=>xe.rotate(e),[xe]),Be=r(e=>{ke.setCoverage(e)},[ke]),We=r(()=>{q(e=>{const t=!e.horizontal;return xe.flipHorizontal(),{...e,horizontal:t}})},[xe]),Ve=r(()=>{q(e=>{const t=!e.vertical;return xe.flipVertical(),{...e,vertical:t}})},[xe]),He=r(()=>{if(!ye.manager||!we.isReady)return null;try{const e=$e?{...$e}:null;let t=null;if(Ee.current){const e=Ee.current;t={x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0}}let n=null;if(Ne.current){const e=Ne.current.$getTransform?.();e&&Array.isArray(e)&&(n=[...e])}const r={cropData:e,selectorState:t,imageTransform:n,flipState:{horizontal:U.horizontal,vertical:U.vertical}};return console.log(`[CropperView] 💾 Guardando estado del crop ${re}:`,r),ne(e=>e.map((e,t)=>t===re?{...e,savedState:r}:e)),r}catch(e){return console.warn("Error saving crop state:",e),null}},[ye.manager,we.isReady,$e,U,re,Ne,Ee]),Ke=r(e=>{const t=ee[e];if(!t||!t.savedState)return console.log(`[CropperView] ℹ️ No hay estado guardado para crop ${e}, centrando...`),void setTimeout(()=>{Oe(),setTimeout(()=>Re(),100)},100);if(ye.manager&&we.isReady)try{const{savedState:n}=t;if(console.log(`[CropperView] ♻️ Restaurando estado del crop ${e}:`,n),n.imageTransform&&Ne.current&&Array.isArray(n.imageTransform)&&setTimeout(()=>{if(Ne.current&&Ne.current.$setTransform){const[e,t,r,a,i,o]=n.imageTransform;Ne.current.$setTransform(e,t,r,a,i,o),console.log(`[CropperView] ✅ Imagen restaurada: transform(${e.toFixed(2)}, ${t.toFixed(2)}, ${r.toFixed(2)}, ${a.toFixed(2)}, ${i.toFixed(0)}, ${o.toFixed(0)})`)}},100),n.selectorState&&Ee.current){const{x:e,y:t,width:r,height:a}=n.selectorState;setTimeout(()=>{Ee.current&&(Ee.current.x=e,Ee.current.y=t,Ee.current.width=r,Ee.current.height=a,Ee.current.$render&&Ee.current.$render(),console.log(`[CropperView] ✅ Selector restaurado: ${r}×${a} en (${e}, ${t})`))},150)}n.flipState&&q({horizontal:n.flipState.horizontal??!1,vertical:n.flipState.vertical??!1}),console.log("[CropperView] ✨ Estado restaurado completamente")}catch(n){console.error("Error restoring crop state:",n),setTimeout(()=>{Oe(),setTimeout(()=>Re(),100)},100)}else console.warn("Cropper not ready for state restoration")},[ee,ye.manager,we.isReady,Oe,Re,Ee,Ne]),Ge=r(()=>{for(let e=0;e<ee.length;e++){const t=ee[e];if(!t.label||""===t.label.trim())return e}return-1},[ee]),Qe=r(async e=>{e!==re&&(j(!0),He(),await new Promise(e=>setTimeout(e,100)),ae(e),await new Promise(e=>setTimeout(e,250)),Ke(e),await new Promise(e=>setTimeout(e,200)),j(!1))},[re,He,Ke]),Ye=r(()=>{if(!Z.allowCustomCrops)return void alert("No se pueden añadir recortes personalizados en este modo.");const t={id:`crop-custom-${Date.now()}`,label:`Recorte ${ee.length+1}`,width:e.width||1920,height:e.height||1080,required:!1,isCustom:!0,confirmed:!1,savedState:null};ne(e=>[...e,t]),pe?.announce(`Nuevo recorte personalizado añadido: ${t.label}. Selecciónalo para editarlo.`)},[Z.allowCustomCrops,ee.length,e.width,e.height,pe]),Xe=r((e,t)=>{const n=parseInt(t,10);""===t||isNaN(n)||ne(t=>t.map((t,r)=>r===re?{...t,[e]:n}:t))},[re]),Je=r(e=>{const t=ie[e];let n=100;if(Se.current&&_e){const e=Se.current.getBoundingClientRect(),t=Math.min(e.width,e.height);n=Math.max(100,Math.round(.05*t))}const r=Math.max(n,Math.min(5e3,t));r!==t&&ne(t=>t.map((t,n)=>n===re?{...t,[e]:r}:t));const a={...ie,[e]:r},i=a.width/a.height,o=ke.getData?.();ke.setAspectRatio(i),o&&void 0!==o.x&&setTimeout(()=>{ke.set?.(o.x,o.y,o.width,o.height)},50)},[re,ie,ke,Se,_e]),Ze=r(e=>{ne(t=>t.map((t,n)=>n===re?{...t,label:e}:t))},[re]),et=r((e,t=null)=>{t=t||ee[e].label;if(!window.confirm(`¿Estás seguro de que deseas eliminar "${t||"este recorte"}"? Esta acción también eliminará todos sus recortes.`))return;const n=ee[e];if(n.required)alert("No se puede eliminar un recorte obligatorio.");else if(1!==ee.length){if(ne(t=>t.filter((t,n)=>n!==e)),e===re){const t=Math.max(0,e-1);ae(t)}else e<re&&ae(e=>e-1);pe?.announce(`Recorte ${n.label} eliminado`)}else alert("Debe haber al menos un recorte.")},[ee,re,pe]),tt=r(async()=>{if(!ze)return null;try{const t=await ke.toCanvas({width:800,height:600,imageSmoothingEnabled:!0,imageSmoothingQuality:"high"});return t?t.toDataURL(`image/${globalThis.downloadFormat||e.mime_type.split("/")[1]||"webp"}`,.9):null}catch(t){return console.warn("Error generating preview:",t),null}},[ze,e.mime_type,ke]),nt=r(async()=>{if(y)return v(!1),x(null),void C(!1);if(ze){v(!0),C(!0);try{const e=await tt();e?x(e):(v(!1),alert("No se puede exportar el recorte por restricciones de CORS en la imagen original."))}finally{C(!1)}}else alert("No se puede exportar el recorte por restricciones de CORS en la imagen original.")},[ze,tt,y]),rt=r(e=>{e.target.closest(".limbo-preview-modal-header")&&(A(!0),P({x:e.clientX-_.x,y:e.clientY-_.y}))},[_]),at=r(e=>{T&&(e.preventDefault(),z({x:e.clientX-M.x,y:e.clientY-M.y}))},[T,M]),it=r(()=>{A(!1)},[]),ot=r(e=>{if(!e.target.closest(".limbo-preview-modal-header"))return;const t=e.touches[0];A(!0),P({x:t.clientX-_.x,y:t.clientY-_.y})},[_]),lt=r(e=>{if(!T)return;e.preventDefault();const t=e.touches[0];z({x:t.clientX-M.x,y:t.clientY-M.y})},[T,M]),st=r(()=>{A(!1)},[]);n(()=>{if(T)return document.addEventListener("mousemove",at),document.addEventListener("mouseup",it),document.addEventListener("touchmove",lt,{passive:!1}),document.addEventListener("touchend",st),()=>{document.removeEventListener("mousemove",at),document.removeEventListener("mouseup",it),document.removeEventListener("touchmove",lt),document.removeEventListener("touchend",st)}},[T,at,it,lt,st]),n(()=>{if(!I)return;const e=e=>{"Escape"===e.key&&L(!1)};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[I]);const ct=r(async(t,n=null)=>{const r=ee[t];if(!r)throw new Error(`Crop ${t} no encontrado`);let a;if(r.savedState&&r.savedState.cropData)a=r.savedState.cropData,console.log(`[CropperView] Usando savedState para crop ${t}:`,a);else{if(t!==re||!$e)throw new Error(`No hay datos de recorte para el crop "${r.label}". Ajusta el recorte antes de guardar.`);a=$e,console.log(`[CropperView] Usando cropData actual para crop activo ${t}:`,a)}if(!a.x&&0!==a.x||!a.y&&0!==a.y||!a.width||!a.height)throw new Error(`Datos de recorte inválidos para "${r.label}"`);if(!Ae?.naturalWidth||!Ae?.naturalHeight)throw new Error("Información de imagen no disponible");const{x:i,y:o,width:l,height:s}=a,{naturalWidth:c,naturalHeight:u}=Ae,d={x:i/c,y:o/u,width:l/c,height:s/u},m=Math.min(r.width,5e3),h=Math.min(r.height,5e3),f=`${r.label||"crop"}_${m}_${h}`,g=n||e.id,b=await fe(g,d,{name:f,width:m,height:h,format:globalThis.downloadFormat||"webp",quality:90});if(b)return pe?.announceSuccess(`Recorte creado: ${f}`),p?.(g,b),b;throw new Error("No se pudo crear la variante")},[ee,re,$e,Ae,fe,e.id,p,pe]),ut=r(async()=>{if(!ze){const e="No se puede exportar el recorte por restricciones de CORS en la imagen original.";return pe?.announceError(e),void alert(e)}if(!we.isReady){const e="El cropper aún no está inicializado. Espera un momento e inténtalo de nuevo.";return pe?.announceError(e),void alert(e)}He(),pe?.announce("Creando recorte de la imagen");try{let t=e.id,n=null;if(e.file&&f){pe?.announce("Subiendo imagen...");const r=await f(e.file);if(!r||!r.id)throw new Error("No se pudo subir la imagen al servidor");t=r.id,n=r,pe?.announceSuccess("Imagen subida correctamente")}const r=await ct(re,t);r&&o(n?{crops:[r],asset:n}:r)}catch(t){console.warn("Error creating crop variant:",t);const e=t.message||"No se pudo crear el recorte. Inténtalo de nuevo.";pe?.announceError(e),alert(e),m?.(t)}},[ze,we.isReady,pe,He,ct,re,o,m,e.file,e.id,f]),dt=r(async t=>{He(),pe?.announce(`Guardando ${t.length} recortes...`);try{let r=e.id,a=null;if(e.file&&f){pe?.announce("Subiendo imagen...");const t=await f(e.file);if(!t||!t.id)throw new Error("No se pudo subir la imagen al servidor");r=t.id,a=t,pe?.announceSuccess("Imagen subida correctamente")}const i=[],l=[];for(const e of t)try{const t=await ct(e,r);t&&i.push(t)}catch(n){l.push({crop:ee[e]?.label||`Crop ${e}`,error:n.message})}if(i.length>0&&(pe?.announceSuccess(`${i.length} recorte(s) guardado(s) correctamente`),o(a?{crops:i,asset:a}:i)),l.length>0){const e=`Errores al guardar algunos recortes:\n${l.map(e=>`- ${e.crop}: ${e.error}`).join("\n")}`;pe?.announceError(e),alert(e)}}catch(n){const e=n.message||"Error al procesar los recortes";pe?.announceError(e),alert(e),m?.(n)}},[He,ct,ee,pe,o,e.file,e.id,f,m]),mt=r(async()=>{const e=Ge();if(-1!==e){const t=ee[e];return alert(`El recorte "${t.label||t||"(sin nombre)"}" debe tener un nombre válido.`),void ae(e)}if(ee.length>1){he("save");const e=ee.map((e,t)=>({crop:e,index:t})).filter(({crop:e,index:t})=>e.required||e.savedState||t===re).map(({index:e})=>e);return de(e),void ce(!0)}await ut()},[Ge,ee,ut,re]),ht=r(async t=>{const n=ee[t];if(!n)throw new Error(`Crop ${t} no encontrado`);if(!n.savedState&&t!==re)throw new Error(`El recorte "${n.label}" aún no ha sido configurado`);const r={index:re,imageTransform:Ne.current?.$getTransform?.(),selectorState:Ee.current?{x:Ee.current.x,y:Ee.current.y,width:Ee.current.width,height:Ee.current.height}:null};try{if(t!==re&&n.savedState){if(console.log(`[CropperView] 🔄 Restaurando temporalmente crop ${t} para descarga...`),n.savedState.imageTransform&&Ne.current?.$setTransform){const[e,t,r,a,i,o]=n.savedState.imageTransform;Ne.current.$setTransform(e,t,r,a,i,o)}if(n.savedState.selectorState&&Ee.current){const{x:e,y:t,width:r,height:a}=n.savedState.selectorState;Ee.current.x=e,Ee.current.y=t,Ee.current.width=r,Ee.current.height=a,Ee.current.$render?.()}await new Promise(e=>setTimeout(e,100))}const r=await ke.toCanvas({width:n.width,height:n.height,imageSmoothingEnabled:!0,imageSmoothingQuality:"high"});if(!r)throw new Error(`No se pudo generar el canvas para "${n.label}"`);const a=r.toDataURL(`image/${globalThis.downloadFormat||e.mime_type.split("/")[1]||"webp"}`,.9),i=`${(n.label||"crop").replace(/\.[^/.]+$/,"").replace(/\s+/g,"-").trim()}_${n.width}_${n.height}`;return await Gt(a,i,{accessibilityManager:pe,onSuccess:e=>{console.log(`✅ Descargado: ${e}`)},onError:e=>{throw new Error(`Error al descargar "${n.label}": ${e.message}`)}}),{crop:n.label,filename:i}}finally{if(t!==re&&r.imageTransform&&Ne.current?.$setTransform){console.log(`[CropperView] ↩️ Restaurando estado original del crop ${r.index}...`);const[e,t,n,a,i,o]=r.imageTransform;if(Ne.current.$setTransform(e,t,n,a,i,o),r.selectorState&&Ee.current){const{x:e,y:t,width:n,height:a}=r.selectorState;Ee.current.x=e,Ee.current.y=t,Ee.current.width=n,Ee.current.height=a,Ee.current.$render?.()}}}},[ee,re,ke,e.mime_type,pe,Ne,Ee]),pt=r(async e=>{He(),pe?.announce(`Descargando ${e.length} recortes...`);const t=[],n=[];for(const a of e)try{const e=await ht(a);e&&t.push(e)}catch(r){n.push({crop:ee[a]?.label||`Crop ${a}`,error:r.message})}if(t.length>0&&pe?.announceSuccess(`${t.length} recorte(s) descargado(s) correctamente`),n.length>0){const e=`Errores al descargar algunos recortes:\n${n.map(e=>`- ${e.crop}: ${e.error}`).join("\n")}`;pe?.announceError(e),alert(e)}},[He,ht,ee,pe]),ft=r(async()=>{if(!ze){const e="No se puede descargar el recorte por restricciones de CORS en la imagen original.";return pe?.announceError(e),void alert(e)}He(),pe?.announce("Preparando descarga del recorte");try{await ht(re),pe?.announceSuccess("Recorte descargado correctamente")}catch(e){console.error("Error downloading crop:",e);const t=e.message||"Error al descargar el recorte";pe?.announceError(t),alert(t)}},[ze,pe,He,ht,re]),gt=r(async()=>{const e=Ge();if(-1!==e){const t=ee[e];return alert(`El recorte "${t.label||t||"(sin nombre)"}" debe tener un nombre válido.`),void ae(e)}if(ee.length>1){he("download");const e=ee.map((e,t)=>({crop:e,index:t})).filter(({crop:e,index:t})=>e.savedState||t===re).map(({index:e})=>e);return de(e),void ce(!0)}await ft()},[Ge,ee,ft,re]),bt=r(async()=>{if(e.file&&f)try{pe?.announce("Subiendo imagen original...");const t=await f(e.file);if(!t||!t.id)throw new Error("No se pudo subir la imagen al servidor");pe?.announceSuccess("Imagen guardada correctamente"),o({asset:t,crops:[]})}catch(t){console.error("Error guardando imagen original:",t);const e=t.message||"No se pudo guardar la imagen. Inténtalo de nuevo.";pe?.announceError(e),alert(e),m?.(t)}else u()},[e.file,f,u,o,m,pe]);return n(()=>{v(!1),x(null)},[e]),n(()=>{ye.manager&&we.isReady&&D&&(console.log("[CropperView] Carga inicial completada, centrando imagen y selector..."),setTimeout(()=>{Oe(),setTimeout(()=>{Re(),O(!1),console.log("[CropperView] Carga inicial finalizada")},100)},50))},[ye.manager,we.isReady,D,Oe,Re]),n(()=>{ye.manager&&we.isReady&&(oe&&ke.setAspectRatio(oe),Ce.setBackground(E))},[oe,E,ye.manager,we.isReady,ke,Ce]),n(()=>{if(!_e||!we.isReady||Z.mandatoryCrops.length>0)return;const e=ee[0];if(e&&"crop-default-0"===e.id&&(1920===e.width||1080===e.height)){const t=Math.min(_e.naturalWidth,5e3),n=Math.min(_e.naturalHeight,5e3);ne([{...e,width:t,height:n}]),console.log(`[CropperView] Crop por defecto actualizado a ${t}×${n}px`)}},[_e,we.isReady,Z.mandatoryCrops.length,ee]),n(()=>{if(!y||!ze)return;const e=setTimeout(async()=>{C(e=>!w&&!e||e);try{const e=await tt();e&&x(e)}finally{C(!1)}},300);return()=>{clearTimeout(e),C(!1)}},[$e,Te,y,ze,tt,oe,U,w]),n(()=>{const e=Se.current,t=t=>{if("Delete"===t.key||"Backspace"===t.key||"Backspace"===t.key&&t.metaKey||"Backspace"===t.key&&t.ctrlKey){const n=t.target;if(e&&(n===e||n===document.body||n===document.documentElement||"CROPPER-CANVAS"===n.tagName||"CROPPER-SELECTION"===n.tagName||"CROPPER-IMAGE"===n.tagName||"CROPPER-HANDLE"===n.tagName||"CROPPER-GRID"===n.tagName||n.closest("cropper-canvas")||e.contains(n)))return t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),!1}};return document.addEventListener("keydown",t,!0),document.addEventListener("keyup",t,!0),window.addEventListener("keydown",t,!0),e&&e.addEventListener("keydown",t,!0),()=>{document.removeEventListener("keydown",t,!0),document.removeEventListener("keyup",t,!0),window.removeEventListener("keydown",t,!0),e&&e.removeEventListener("keydown",t,!0)}},[Se]),e?/* @__PURE__ */s("div",{className:"limbo-cropper-view px-2 border-2 border-gray-200/50 rounded-lg max-w-7xl mx-auto w-full min-w-full h-full min-h-full flex flex-col",children:[
226
+ /* @__PURE__ */s("div",{className:"limbo-tab-content px-2 py-2",role:"tabpanel",id:`upload-tabpanel-${u}`,"aria-labelledby":`upload-tab-${u}`,children:["upload"===u&&/* @__PURE__ */l(Q,{file:m,setFile:h,previewUrl:p,setPreviewUrl:f,fileInputRef:g,onSelect:e,disabled:n}),"ai"===u&&/* @__PURE__ */l(ne,{apiKey:r,prod:i,disabled:n,onSelect:e}),"stock"===u&&/* @__PURE__ */l(oe,{apiKey:r,prod:i,disabled:n,onSelect:e}),"portals"===u&&/* @__PURE__ */l(de,{apiKey:r,prod:i,disabled:n,onSelect:e})]})]})}const pe="undefined"!=typeof window&&void 0!==window.document,fe=pe?window:{},ge=!!pe&&"ontouchstart"in fe.document.documentElement,be=!!pe&&"PointerEvent"in fe,ye="cropper",ve=`${ye}-canvas`,we=`${ye}-crosshair`,xe=`${ye}-grid`,ke=`${ye}-handle`,Ce=`${ye}-image`,Se=`${ye}-selection`,Ne=`${ye}-shade`,Ee=`${ye}-viewer`,$e="select",_e="move",ze="scale",Te="rotate",Ae="transform",Me="none",Pe="n-resize",Ie="e-resize",Le="s-resize",De="w-resize",Oe="ne-resize",Re="nw-resize",je="se-resize",Fe="sw-resize",Ue=be?"pointerdown":ge?"touchstart":"mousedown",qe=be?"pointermove":ge?"touchmove":"mousemove",Be=be?"pointerup pointercancel":ge?"touchend touchcancel":"mouseup",We="error",Ve="keydown",He="load",Ke="wheel",Ge="action",Qe="actionend",Ye="actionstart",Xe="change",Je="transform";const Ze=Number.isNaN||fe.isNaN;function et(e){return"number"==typeof e&&!Ze(e)}function tt(e){return et(e)&&e>0&&e<1/0}function nt(e){return"object"==typeof e&&null!==e}const{hasOwnProperty:rt}=Object.prototype;function at(e){if(!nt(e))return!1;try{const{constructor:t}=e,{prototype:n}=t;return t&&n&&rt.call(n,"isPrototypeOf")}catch(t){return!1}}function it(e){return"function"==typeof e}function ot(e){return"object"==typeof e&&null!==e&&1===e.nodeType}const lt=/([a-z\d])([A-Z])/g;function st(e){return String(e).replace(lt,"$1-$2").toLowerCase()}const ct=/-[A-z\d]/g;function ut(e){return e.replace(ct,e=>e.slice(1).toUpperCase())}const dt=/\s\s*/;function mt(e,t,n,r){t.trim().split(dt).forEach(t=>{e.removeEventListener(t,n,r)})}function ht(e,t,n,r){t.trim().split(dt).forEach(t=>{e.addEventListener(t,n,r)})}function pt(e,t,n,r){ht(e,t,n,Object.assign(Object.assign({},r),{once:!0}))}const ft={bubbles:!0,cancelable:!0,composed:!0};const gt=Promise.resolve();function bt(e){const{documentElement:t}=e.ownerDocument,n=e.getBoundingClientRect();return{left:n.left+(fe.pageXOffset-t.clientLeft),top:n.top+(fe.pageYOffset-t.clientTop)}}const yt=/deg|g?rad|turn$/i;function vt(e){const t=parseFloat(e)||0;if(0!==t){const[n="rad"]=String(e).match(yt)||[];switch(n.toLowerCase()){case"deg":return t/360*(2*Math.PI);case"grad":return t/400*(2*Math.PI);case"turn":return t*(2*Math.PI)}}return t}const wt="contain";function xt(e,t=wt){const{aspectRatio:n}=e;let{width:r,height:a}=e;const i=tt(r),o=tt(a);if(i&&o){const e=a*n;t===wt&&e>r||"cover"===t&&e<r?a=r/n:r=a*n}else i?a=r/n:o&&(r=a*n);return{width:r,height:a}}function kt(e,...t){if(0===t.length)return e;const[n,r,a,i,o,l]=e,[s,c,u,d,m,h]=t[0];return kt(e=[n*s+a*c,r*s+i*c,n*u+a*d,r*u+i*d,n*m+a*h+o,r*m+i*h+l],...t.slice(1))}const Ct=/left|top|width|height/i,St="open",Nt=/* @__PURE__ */new WeakMap,Et=/* @__PURE__ */new WeakMap,$t=/* @__PURE__ */new Map,_t=fe.document&&Array.isArray(fe.document.adoptedStyleSheets)&&"replaceSync"in fe.CSSStyleSheet.prototype;class zt extends HTMLElement{get $sharedStyle(){return(this.themeColor?`:host{--theme-color: ${this.themeColor};}`:"")+":host([hidden]){display:none!important}"}constructor(){var e,t;super(),this.shadowRootMode=St,this.slottable=!0;const n=null===(t=null===(e=Object.getPrototypeOf(this))||void 0===e?void 0:e.constructor)||void 0===t?void 0:t.$name;n&&$t.set(n,this.tagName.toLowerCase())}static get observedAttributes(){return["shadow-root-mode","slottable","theme-color"]}attributeChangedCallback(e,t,n){if(Object.is(n,t))return;const r=ut(e);let a=n;switch(typeof this[r]){case"boolean":a=null!==n&&"false"!==n;break;case"number":a=Number(n)}switch(this[r]=a,e){case"theme-color":{const e=Et.get(this),t=this.$sharedStyle;e&&t&&(_t?e.replaceSync(t):e.textContent=t);break}}}$propertyChangedCallback(e,t,n){if(!Object.is(n,t))switch(e=st(e),typeof n){case"boolean":!0===n?this.hasAttribute(e)||this.setAttribute(e,""):this.removeAttribute(e);break;case"number":n=Ze(n)?"":String(n);default:n?this.getAttribute(e)!==n&&this.setAttribute(e,n):this.removeAttribute(e)}}connectedCallback(){Object.getPrototypeOf(this).constructor.observedAttributes.forEach(e=>{const t=ut(e);let n=this[t];(function(e){return void 0===e})(n)||this.$propertyChangedCallback(t,void 0,n),Object.defineProperty(this,t,{enumerable:!0,configurable:!0,get:()=>n,set(e){const r=n;n=e,this.$propertyChangedCallback(t,r,e)}})});const e=this.shadowRoot||this.attachShadow({mode:this.shadowRootMode||St});if(Nt.set(this,e),Et.set(this,this.$addStyles(this.$sharedStyle)),this.$style&&this.$addStyles(this.$style),this.$template){const t=document.createElement("template");t.innerHTML=this.$template,e.appendChild(t.content)}if(this.slottable){const t=document.createElement("slot");e.appendChild(t)}}disconnectedCallback(){Et.has(this)&&Et.delete(this),Nt.has(this)&&Nt.delete(this)}$getTagNameOf(e){var t;return null!==(t=$t.get(e))&&void 0!==t?t:e}$setStyles(e){return Object.keys(e).forEach(t=>{let n=e[t];et(n)&&(n=0!==n&&Ct.test(t)?`${n}px`:String(n)),this.style[t]=n}),this}$getShadowRoot(){return this.shadowRoot||Nt.get(this)}$addStyles(e){let t;const n=this.$getShadowRoot();return _t?(t=new CSSStyleSheet,t.replaceSync(e),n.adoptedStyleSheets=n.adoptedStyleSheets.concat(t)):(t=document.createElement("style"),t.textContent=e,n.appendChild(t)),t}$emit(e,t,n){return function(e,t,n,r){return e.dispatchEvent(new CustomEvent(t,Object.assign(Object.assign(Object.assign({},ft),{detail:n}),r)))}(this,e,t,n)}$nextTick(e){return function(e,t){return t?gt.then(e?t.bind(e):t):gt}(this,e)}static $define(e,t){nt(e)&&(t=e,e=""),e||(e=this.$name||this.name),e=st(e),pe&&fe.customElements&&!fe.customElements.get(e)&&customElements.define(e,this,t)}}zt.$version="2.1.0";class Tt extends zt{constructor(){super(...arguments),this.$onPointerDown=null,this.$onPointerMove=null,this.$onPointerUp=null,this.$onWheel=null,this.$wheeling=!1,this.$pointers=/* @__PURE__ */new Map,this.$style=':host{display:block;min-height:100px;min-width:200px;overflow:hidden;position:relative;touch-action:none;-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}:host([background]){background-color:#fff;background-image:repeating-linear-gradient(45deg,#ccc 25%,transparent 0,transparent 75%,#ccc 0,#ccc),repeating-linear-gradient(45deg,#ccc 25%,transparent 0,transparent 75%,#ccc 0,#ccc);background-image:repeating-conic-gradient(#ccc 0 25%,#fff 0 50%);background-position:0 0,.5rem .5rem;background-size:1rem 1rem}:host([disabled]){pointer-events:none}:host([disabled]):after{bottom:0;content:"";cursor:not-allowed;display:block;left:0;pointer-events:none;position:absolute;right:0;top:0}',this.$action=Me,this.background=!1,this.disabled=!1,this.scaleStep=.1,this.themeColor="#39f"}static get observedAttributes(){return super.observedAttributes.concat(["background","disabled","scale-step"])}connectedCallback(){super.connectedCallback(),this.disabled||this.$bind()}disconnectedCallback(){this.disabled||this.$unbind(),super.disconnectedCallback()}$propertyChangedCallback(e,t,n){if(!Object.is(n,t)&&(super.$propertyChangedCallback(e,t,n),"disabled"===e))n?this.$unbind():this.$bind()}$bind(){this.$onPointerDown||(this.$onPointerDown=this.$handlePointerDown.bind(this),ht(this,Ue,this.$onPointerDown)),this.$onPointerMove||(this.$onPointerMove=this.$handlePointerMove.bind(this),ht(this.ownerDocument,qe,this.$onPointerMove)),this.$onPointerUp||(this.$onPointerUp=this.$handlePointerUp.bind(this),ht(this.ownerDocument,Be,this.$onPointerUp)),this.$onWheel||(this.$onWheel=this.$handleWheel.bind(this),ht(this,Ke,this.$onWheel,{passive:!1,capture:!0}))}$unbind(){this.$onPointerDown&&(mt(this,Ue,this.$onPointerDown),this.$onPointerDown=null),this.$onPointerMove&&(mt(this.ownerDocument,qe,this.$onPointerMove),this.$onPointerMove=null),this.$onPointerUp&&(mt(this.ownerDocument,Be,this.$onPointerUp),this.$onPointerUp=null),this.$onWheel&&(mt(this,Ke,this.$onWheel,{capture:!0}),this.$onWheel=null)}$handlePointerDown(e){const{buttons:t,button:n,type:r}=e;if(this.disabled||("pointerdown"===r&&"mouse"===e.pointerType||"mousedown"===r)&&(et(t)&&1!==t||et(n)&&0!==n||e.ctrlKey))return;const{$pointers:a}=this;let i="";if(e.changedTouches)Array.from(e.changedTouches).forEach(({identifier:e,pageX:t,pageY:n})=>{a.set(e,{startX:t,startY:n,endX:t,endY:n})});else{const{pointerId:t=0,pageX:n,pageY:r}=e;a.set(t,{startX:n,startY:r,endX:n,endY:r})}a.size>1?i=Ae:ot(e.target)&&(i=e.target.action||e.target.getAttribute("action")||""),!1!==this.$emit(Ye,{action:i,relatedEvent:e})&&(e.preventDefault(),this.$action=i,this.style.willChange="transform")}$handlePointerMove(e){const{$action:t,$pointers:n}=this;if(this.disabled||t===Me||0===n.size)return;if(!1===this.$emit("actionmove",{action:t,relatedEvent:e}))return;if(e.preventDefault(),e.changedTouches)Array.from(e.changedTouches).forEach(({identifier:e,pageX:t,pageY:r})=>{const a=n.get(e);a&&Object.assign(a,{endX:t,endY:r})});else{const{pointerId:t=0,pageX:r,pageY:a}=e,i=n.get(t);i&&Object.assign(i,{endX:r,endY:a})}const r={action:t,relatedEvent:e};if(t===Ae){const t=new Map(n);let a=0,i=0,o=0,l=0,s=e.pageX,c=e.pageY;n.forEach((e,n)=>{t.delete(n),t.forEach(t=>{let n=t.startX-e.startX,r=t.startY-e.startY,u=t.endX-e.endX,d=t.endY-e.endY,m=0,h=0,p=0,f=0;if(0===n?r<0?p=2*Math.PI:r>0&&(p=Math.PI):n>0?p=Math.PI/2+Math.atan(r/n):n<0&&(p=1.5*Math.PI+Math.atan(r/n)),0===u?d<0?f=2*Math.PI:d>0&&(f=Math.PI):u>0?f=Math.PI/2+Math.atan(d/u):u<0&&(f=1.5*Math.PI+Math.atan(d/u)),f>0||p>0){const n=f-p,r=Math.abs(n);r>a&&(a=r,o=n,s=(e.startX+t.startX)/2,c=(e.startY+t.startY)/2)}if(n=Math.abs(n),r=Math.abs(r),u=Math.abs(u),d=Math.abs(d),n>0&&r>0?m=Math.sqrt(n*n+r*r):n>0?m=n:r>0&&(m=r),u>0&&d>0?h=Math.sqrt(u*u+d*d):u>0?h=u:d>0&&(h=d),m>0&&h>0){const n=(h-m)/m,r=Math.abs(n);r>i&&(i=r,l=n,s=(e.startX+t.startX)/2,c=(e.startY+t.startY)/2)}})});const u=a>0,d=i>0;u&&d?(r.rotate=o,r.scale=l,r.centerX=s,r.centerY=c):u?(r.action=Te,r.rotate=o,r.centerX=s,r.centerY=c):d?(r.action=ze,r.scale=l,r.centerX=s,r.centerY=c):r.action=Me}else{const[e]=Array.from(n.values());Object.assign(r,e)}n.forEach(e=>{e.startX=e.endX,e.startY=e.endY}),r.action!==Me&&this.$emit(Ge,r,{cancelable:!1})}$handlePointerUp(e){const{$action:t,$pointers:n}=this;if(!this.disabled&&t!==Me&&!1!==this.$emit(Qe,{action:t,relatedEvent:e})){if(e.preventDefault(),e.changedTouches)Array.from(e.changedTouches).forEach(({identifier:e})=>{n.delete(e)});else{const{pointerId:t=0}=e;n.delete(t)}0===n.size&&(this.style.willChange="",this.$action=Me)}}$handleWheel(e){if(this.disabled)return;if(e.preventDefault(),this.$wheeling)return;this.$wheeling=!0,setTimeout(()=>{this.$wheeling=!1},50);const t=(e.deltaY>0?-1:1)*this.scaleStep;this.$emit(Ge,{action:ze,scale:t,relatedEvent:e},{cancelable:!1})}$setAction(e){return"string"==typeof e&&(this.$action=e),this}$toCanvas(e){return new Promise((t,n)=>{if(!this.isConnected)return void n(new Error("The current element is not connected to the DOM."));const r=document.createElement("canvas");let a=this.offsetWidth,i=this.offsetHeight,o=1;at(e)&&(tt(e.width)||tt(e.height))&&(({width:a,height:i}=xt({aspectRatio:a/i,width:e.width,height:e.height})),o=a/this.offsetWidth),r.width=a,r.height=i;const l=this.querySelector(this.$getTagNameOf(Ce));l?l.$ready().then(n=>{const s=r.getContext("2d");if(s){const[t,c,u,d,m,h]=l.$getTransform();let p=m,f=h,g=n.naturalWidth,b=n.naturalHeight;1!==o&&(p*=o,f*=o,g*=o,b*=o);const y=g/2,v=b/2;s.fillStyle="transparent",s.fillRect(0,0,a,i),at(e)&&it(e.beforeDraw)&&e.beforeDraw.call(this,s,r),s.save(),s.translate(y,v),s.transform(t,c,u,d,p,f),s.translate(-y,-v),s.drawImage(n,0,0,g,b),s.restore()}t(r)}).catch(n):t(r)})}}Tt.$name=ve,Tt.$version="2.1.0";const At=/* @__PURE__ */new WeakMap,Mt=["alt","crossorigin","decoding","elementtiming","fetchpriority","loading","referrerpolicy","sizes","src","srcset"];class Pt extends zt{constructor(){super(...arguments),this.$matrix=[1,0,0,1,0,0],this.$onLoad=null,this.$onCanvasAction=null,this.$onCanvasActionEnd=null,this.$onCanvasActionStart=null,this.$actionStartTarget=null,this.$style=":host{display:inline-block}img{display:block;height:100%;max-height:none!important;max-width:none!important;min-height:0!important;min-width:0!important;width:100%}",this.$image=new Image,this.initialCenterSize="contain",this.rotatable=!1,this.scalable=!1,this.skewable=!1,this.slottable=!1,this.translatable=!1,this.alt="",this.crossorigin="",this.decoding="",this.elementtiming="",this.fetchpriority="",this.loading="",this.referrerpolicy="",this.sizes="",this.src="",this.srcset=""}set $canvas(e){At.set(this,e)}get $canvas(){return At.get(this)}static get observedAttributes(){return super.observedAttributes.concat(Mt,["initial-center-size","rotatable","scalable","skewable","translatable"])}attributeChangedCallback(e,t,n){Object.is(n,t)||(super.attributeChangedCallback(e,t,n),Mt.includes(e)&&this.$image.setAttribute(e,n))}$propertyChangedCallback(e,t,n){if(!Object.is(n,t)&&(super.$propertyChangedCallback(e,t,n),"initialCenterSize"===e))this.$nextTick(()=>{this.$center(n)})}connectedCallback(){super.connectedCallback();const{$image:e}=this,t=this.closest(this.$getTagNameOf(ve));t&&(this.$canvas=t,this.$setStyles({display:"block",position:"absolute"}),this.$onCanvasActionStart=e=>{var t,n;this.$actionStartTarget=null===(n=null===(t=e.detail)||void 0===t?void 0:t.relatedEvent)||void 0===n?void 0:n.target},this.$onCanvasActionEnd=()=>{this.$actionStartTarget=null},this.$onCanvasAction=this.$handleAction.bind(this),ht(t,Ye,this.$onCanvasActionStart),ht(t,Qe,this.$onCanvasActionEnd),ht(t,Ge,this.$onCanvasAction)),this.$onLoad=this.$handleLoad.bind(this),ht(e,He,this.$onLoad),this.$getShadowRoot().appendChild(e)}disconnectedCallback(){const{$image:e,$canvas:t}=this;t&&(this.$onCanvasActionStart&&(mt(t,Ye,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(mt(t,Qe,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasAction&&(mt(t,Ge,this.$onCanvasAction),this.$onCanvasAction=null)),e&&this.$onLoad&&(mt(e,He,this.$onLoad),this.$onLoad=null),this.$getShadowRoot().removeChild(e),super.disconnectedCallback()}$handleLoad(){const{$image:e}=this;this.$setStyles({width:e.naturalWidth,height:e.naturalHeight}),this.$canvas&&this.$center(this.initialCenterSize)}$handleAction(e){if(this.hidden||!(this.rotatable||this.scalable||this.translatable))return;const{$canvas:t}=this,{detail:n}=e;if(n){const{relatedEvent:e}=n;let{action:r}=n;switch(r!==Ae||this.rotatable&&this.scalable||(r=this.rotatable?Te:this.scalable?ze:Me),r){case _e:if(this.translatable){let r=null;e&&(r=e.target.closest(this.$getTagNameOf(Se))),r||(r=t.querySelector(this.$getTagNameOf(Se))),r&&r.multiple&&!r.active&&(r=t.querySelector(`${this.$getTagNameOf(Se)}[active]`)),r&&!r.hidden&&r.movable&&!r.dynamic&&this.$actionStartTarget&&r.contains(this.$actionStartTarget)||this.$move(n.endX-n.startX,n.endY-n.startY)}break;case Te:if(this.rotatable)if(e){const{x:t,y:r}=this.getBoundingClientRect();this.$rotate(n.rotate,e.clientX-t,e.clientY-r)}else this.$rotate(n.rotate);break;case ze:if(this.scalable)if(e){const t=e.target.closest(this.$getTagNameOf(Se));if(!t||!t.zoomable||t.zoomable&&t.dynamic){const{x:t,y:r}=this.getBoundingClientRect();this.$zoom(n.scale,e.clientX-t,e.clientY-r)}}else this.$zoom(n.scale);break;case Ae:if(this.rotatable&&this.scalable){const{rotate:t}=n;let{scale:r}=n;r<0?r=1/(1-r):r+=1;const a=Math.cos(t),i=Math.sin(t),[o,l,s,c]=[a*r,i*r,-i*r,a*r];if(e){const t=this.getBoundingClientRect(),n=e.clientX-t.x,r=e.clientY-t.y,[a,i,u,d]=this.$matrix,m=n-t.width/2,h=r-t.height/2,p=(m*d-u*h)/(a*d-u*i),f=(h*a-i*m)/(a*d-u*i);this.$transform(o,l,s,c,p*(1-o)+f*s,f*(1-c)+p*l)}else this.$transform(o,l,s,c,0,0)}}}}$ready(e){const{$image:t}=this,n=new Promise((e,n)=>{const r=new Error("Failed to load the image source");if(t.complete)t.naturalWidth>0&&t.naturalHeight>0?e(t):n(r);else{const a=()=>{mt(t,We,i),setTimeout(()=>{e(t)})},i=()=>{mt(t,He,a),n(r)};pt(t,He,a),pt(t,We,i)}});return it(e)&&n.then(t=>(e(t),t)),n}$center(e){const{parentElement:t}=this;if(!t)return this;const n=t.getBoundingClientRect(),r=n.width,a=n.height,{x:i,y:o,width:l,height:s}=this.getBoundingClientRect(),c=i+l/2,u=o+s/2,d=n.x+r/2,m=n.y+a/2;if(this.$move(d-c,m-u),e&&(l!==r||s!==a)){const t=r/l,n=a/s;switch(e){case"cover":this.$scale(Math.max(t,n));break;case"contain":this.$scale(Math.min(t,n))}}return this}$move(e,t=e){if(this.translatable&&et(e)&&et(t)){const[n,r,a,i]=this.$matrix,o=(e*i-a*t)/(n*i-a*r),l=(t*n-r*e)/(n*i-a*r);this.$translate(o,l)}return this}$moveTo(e,t=e){if(this.translatable&&et(e)&&et(t)){const[n,r,a,i]=this.$matrix,o=(e*i-a*t)/(n*i-a*r),l=(t*n-r*e)/(n*i-a*r);this.$setTransform(n,r,a,i,o,l)}return this}$rotate(e,t,n){if(this.rotatable){const r=vt(e),a=Math.cos(r),i=Math.sin(r),[o,l,s,c]=[a,i,-i,a];if(et(t)&&et(n)){const[e,r,a,i]=this.$matrix,{width:u,height:d}=this.getBoundingClientRect(),m=t-u/2,h=n-d/2,p=(m*i-a*h)/(e*i-a*r),f=(h*e-r*m)/(e*i-a*r);this.$transform(o,l,s,c,p*(1-o)-f*s,f*(1-c)-p*l)}else this.$transform(o,l,s,c,0,0)}return this}$zoom(e,t,n){if(!this.scalable||0===e)return this;if(e<0?e=1/(1-e):e+=1,et(t)&&et(n)){const[r,a,i,o]=this.$matrix,{width:l,height:s}=this.getBoundingClientRect(),c=t-l/2,u=n-s/2,d=(c*o-i*u)/(r*o-i*a),m=(u*r-a*c)/(r*o-i*a);this.$transform(e,0,0,e,d*(1-e),m*(1-e))}else this.$scale(e);return this}$scale(e,t=e){return this.scalable&&this.$transform(e,0,0,t,0,0),this}$skew(e,t=0){if(this.skewable){const n=vt(e),r=vt(t);this.$transform(1,Math.tan(r),Math.tan(n),1,0,0)}return this}$translate(e,t=e){return this.translatable&&et(e)&&et(t)&&this.$transform(1,0,0,1,e,t),this}$transform(e,t,n,r,a,i){return et(e)&&et(t)&&et(n)&&et(r)&&et(a)&&et(i)?this.$setTransform(kt(this.$matrix,[e,t,n,r,a,i])):this}$setTransform(e,t,n,r,a,i){if((this.rotatable||this.scalable||this.skewable||this.translatable)&&(Array.isArray(e)&&([e,t,n,r,a,i]=e),et(e)&&et(t)&&et(n)&&et(r)&&et(a)&&et(i))){const o=[...this.$matrix],l=[e,t,n,r,a,i];if(!1===this.$emit(Je,{matrix:l,oldMatrix:o}))return this;this.$matrix=l,this.style.transform=`matrix(${l.join(", ")})`}return this}$getTransform(){return this.$matrix.slice()}$resetTransform(){return this.$setTransform([1,0,0,1,0,0])}}Pt.$name=Ce,Pt.$version="2.1.0";const It=/* @__PURE__ */new WeakMap;class Lt extends zt{constructor(){super(...arguments),this.$onCanvasActionEnd=null,this.$onCanvasActionStart=null,this.$onSelectionChange=null,this.$style=":host{display:block;height:0;left:0;outline:var(--theme-color) solid 1px;position:relative;top:0;width:0}:host([transparent]){outline-color:transparent}",this.x=0,this.y=0,this.width=0,this.height=0,this.slottable=!1,this.themeColor="rgba(0, 0, 0, 0.65)"}set $canvas(e){It.set(this,e)}get $canvas(){return It.get(this)}static get observedAttributes(){return super.observedAttributes.concat(["height","width","x","y"])}connectedCallback(){super.connectedCallback();const e=this.closest(this.$getTagNameOf(ve));if(e){this.$canvas=e,this.style.position="absolute";const t=e.querySelector(this.$getTagNameOf(Se));t&&(this.$onCanvasActionStart=e=>{t.hidden&&e.detail.action===$e&&(this.hidden=!1)},this.$onCanvasActionEnd=e=>{t.hidden&&e.detail.action===$e&&(this.hidden=!0)},this.$onSelectionChange=e=>{const{x:n,y:r,width:a,height:i}=e.defaultPrevented?t:e.detail;this.$change(n,r,a,i),(t.hidden||0===n&&0===r&&0===a&&0===i)&&(this.hidden=!0)},ht(e,Ye,this.$onCanvasActionStart),ht(e,Qe,this.$onCanvasActionEnd),ht(e,Xe,this.$onSelectionChange))}this.$render()}disconnectedCallback(){const{$canvas:e}=this;e&&(this.$onCanvasActionStart&&(mt(e,Ye,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(mt(e,Qe,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onSelectionChange&&(mt(e,Xe,this.$onSelectionChange),this.$onSelectionChange=null)),super.disconnectedCallback()}$change(e,t,n=this.width,r=this.height){return et(e)&&et(t)&&et(n)&&et(r)&&(e!==this.x||t!==this.y||n!==this.width||r!==this.height)?(this.hidden&&(this.hidden=!1),this.x=e,this.y=t,this.width=n,this.height=r,this.$render()):this}$reset(){return this.$change(0,0,0,0)}$render(){return this.$setStyles({transform:`translate(${this.x}px, ${this.y}px)`,width:this.width,height:this.height,outlineWidth:fe.innerWidth})}}Lt.$name=Ne,Lt.$version="2.1.0";class Dt extends zt{constructor(){super(...arguments),this.$onCanvasCropEnd=null,this.$onCanvasCropStart=null,this.$style=':host{background-color:var(--theme-color);display:block}:host([action=move]),:host([action=select]){height:100%;left:0;position:absolute;top:0;width:100%}:host([action=move]){cursor:move}:host([action=select]){cursor:crosshair}:host([action$=-resize]){background-color:transparent;height:15px;position:absolute;width:15px}:host([action$=-resize]):after{background-color:var(--theme-color);content:"";display:block;height:5px;left:50%;position:absolute;top:50%;transform:translate(-50%,-50%);width:5px}:host([action=n-resize]),:host([action=s-resize]){cursor:ns-resize;left:50%;transform:translateX(-50%);width:100%}:host([action=n-resize]){top:-8px}:host([action=s-resize]){bottom:-8px}:host([action=e-resize]),:host([action=w-resize]){cursor:ew-resize;height:100%;top:50%;transform:translateY(-50%)}:host([action=e-resize]){right:-8px}:host([action=w-resize]){left:-8px}:host([action=ne-resize]){cursor:nesw-resize;right:-8px;top:-8px}:host([action=nw-resize]){cursor:nwse-resize;left:-8px;top:-8px}:host([action=se-resize]){bottom:-8px;cursor:nwse-resize;right:-8px}:host([action=se-resize]):after{height:15px;width:15px}@media (pointer:coarse){:host([action=se-resize]):after{height:10px;width:10px}}@media (pointer:fine){:host([action=se-resize]):after{height:5px;width:5px}}:host([action=sw-resize]){bottom:-8px;cursor:nesw-resize;left:-8px}:host([plain]){background-color:transparent}',this.action=Me,this.plain=!1,this.slottable=!1,this.themeColor="rgba(51, 153, 255, 0.5)"}static get observedAttributes(){return super.observedAttributes.concat(["action","plain"])}}Dt.$name=ke,Dt.$version="2.1.0";const Ot=/* @__PURE__ */new WeakMap;class Rt extends zt{constructor(){super(...arguments),this.$onCanvasAction=null,this.$onCanvasActionStart=null,this.$onCanvasActionEnd=null,this.$onDocumentKeyDown=null,this.$action="",this.$actionStartTarget=null,this.$changing=!1,this.$style=':host{display:block;left:0;position:relative;right:0}:host([outlined]){outline:1px solid var(--theme-color)}:host([multiple]){outline:1px dashed hsla(0,0%,100%,.5)}:host([multiple]):after{bottom:0;content:"";cursor:pointer;display:block;left:0;position:absolute;right:0;top:0}:host([multiple][active]){outline-color:var(--theme-color);z-index:1}:host([multiple])>*{visibility:hidden}:host([multiple][active])>*{visibility:visible}:host([multiple][active]):after{display:none}',this.$initialSelection={x:0,y:0,width:0,height:0},this.x=0,this.y=0,this.width=0,this.height=0,this.aspectRatio=NaN,this.initialAspectRatio=NaN,this.initialCoverage=NaN,this.active=!1,this.linked=!1,this.dynamic=!1,this.movable=!1,this.resizable=!1,this.zoomable=!1,this.multiple=!1,this.keyboard=!1,this.outlined=!1,this.precise=!1}set $canvas(e){Ot.set(this,e)}get $canvas(){return Ot.get(this)}static get observedAttributes(){return super.observedAttributes.concat(["active","aspect-ratio","dynamic","height","initial-aspect-ratio","initial-coverage","keyboard","linked","movable","multiple","outlined","precise","resizable","width","x","y","zoomable"])}$propertyChangedCallback(e,t,n){if(!Object.is(n,t))switch(super.$propertyChangedCallback(e,t,n),e){case"x":case"y":case"width":case"height":this.$changing||this.$nextTick(()=>{this.$change(this.x,this.y,this.width,this.height,this.aspectRatio,!0)});break;case"aspectRatio":case"initialAspectRatio":this.$nextTick(()=>{this.$initSelection()});break;case"initialCoverage":this.$nextTick(()=>{tt(n)&&n<=1&&this.$initSelection(!0,!0)});break;case"keyboard":this.$nextTick(()=>{this.$canvas&&(n?this.$onDocumentKeyDown||(this.$onDocumentKeyDown=this.$handleKeyDown.bind(this),ht(this.ownerDocument,Ve,this.$onDocumentKeyDown)):this.$onDocumentKeyDown&&(mt(this.ownerDocument,Ve,this.$onDocumentKeyDown),this.$onDocumentKeyDown=null))});break;case"multiple":this.$nextTick(()=>{if(this.$canvas){const e=this.$getSelections();n?(e.forEach(e=>{e.active=!1}),this.active=!0,this.$emit(Xe,{x:this.x,y:this.y,width:this.width,height:this.height})):(this.active=!1,e.slice(1).forEach(e=>{this.$removeSelection(e)}))}});break;case"precise":this.$nextTick(()=>{this.$change(this.x,this.y)});break;case"linked":n&&(this.dynamic=!0)}}connectedCallback(){super.connectedCallback();const e=this.closest(this.$getTagNameOf(ve));e?(this.$canvas=e,this.$setStyles({position:"absolute",transform:`translate(${this.x}px, ${this.y}px)`}),this.hidden||this.$render(),this.$initSelection(!0),this.$onCanvasActionStart=this.$handleActionStart.bind(this),this.$onCanvasActionEnd=this.$handleActionEnd.bind(this),this.$onCanvasAction=this.$handleAction.bind(this),ht(e,Ye,this.$onCanvasActionStart),ht(e,Qe,this.$onCanvasActionEnd),ht(e,Ge,this.$onCanvasAction)):this.$render()}disconnectedCallback(){const{$canvas:e}=this;e&&(this.$onCanvasActionStart&&(mt(e,Ye,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(mt(e,Qe,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasAction&&(mt(e,Ge,this.$onCanvasAction),this.$onCanvasAction=null)),super.disconnectedCallback()}$getSelections(){let e=[];return this.parentElement&&(e=Array.from(this.parentElement.querySelectorAll(this.$getTagNameOf(Se)))),e}$initSelection(e=!1,t=!1){const{initialCoverage:n,parentElement:r}=this;if(tt(n)&&r){const a=this.aspectRatio||this.initialAspectRatio;let i=(t?0:this.width)||r.offsetWidth*n,o=(t?0:this.height)||r.offsetHeight*n;tt(a)&&({width:i,height:o}=xt({aspectRatio:a,width:i,height:o})),this.$change(this.x,this.y,i,o),e&&this.$center(),this.$initialSelection={x:this.x,y:this.y,width:this.width,height:this.height}}}$createSelection(){const e=this.cloneNode(!0);return this.hasAttribute("id")&&e.removeAttribute("id"),e.initialCoverage=NaN,this.active=!1,this.parentElement&&this.parentElement.insertBefore(e,this.nextSibling),e}$removeSelection(e=this){if(this.parentElement){const t=this.$getSelections();if(t.length>1){const n=t.indexOf(e),r=t[n+1]||t[n-1];r&&(e.active=!1,this.parentElement.removeChild(e),r.active=!0,r.$emit(Xe,{x:r.x,y:r.y,width:r.width,height:r.height}))}else this.$clear()}}$handleActionStart(e){var t,n;const r=null===(n=null===(t=e.detail)||void 0===t?void 0:t.relatedEvent)||void 0===n?void 0:n.target;this.$action="",this.$actionStartTarget=r,!this.hidden&&this.multiple&&!this.active&&r===this&&this.parentElement&&(this.$getSelections().forEach(e=>{e.active=!1}),this.active=!0,this.$emit(Xe,{x:this.x,y:this.y,width:this.width,height:this.height}))}$handleAction(e){const{currentTarget:t,detail:n}=e;if(!t||!n)return;const{relatedEvent:r}=n;let{action:a}=n;const i=r?function(e){if("function"==typeof e.composedPath)return e.composedPath().find(ot)||e.target;return e.target}(r):null;if(!a&&this.multiple&&(a=this.$action||(null==i?void 0:i.action),this.$action=a),!a||this.hidden&&a!==$e||this.multiple&&!this.active&&a!==ze)return;const{width:o,height:l}=this;let s=n.endX-n.startX,c=n.endY-n.startY,{aspectRatio:u}=this;switch(!tt(u)&&r.shiftKey&&(u=tt(o)&&tt(l)?o/l:1),a){case $e:if(0!==s||0!==c){0===s?s=c:0===c&&(c=s);const{$canvas:e}=this,r=bt(t);(this.multiple&&!this.hidden?this.$createSelection():this).$change(n.startX-r.left,n.startY-r.top,Math.abs(s),Math.abs(c),u),s<0?c<0?a=Re:c>0&&(a=Fe):s>0&&(c<0?a=Oe:c>0&&(a=je)),e&&(e.$action=a)}break;case _e:this.movable&&(this.dynamic||this.$actionStartTarget&&this.contains(this.$actionStartTarget))&&this.$move(s,c);break;case ze:if(r&&this.zoomable&&(this.dynamic||this.contains(r.target))){const e=bt(t);this.$zoom(n.scale,r.pageX-e.left,r.pageY-e.top)}break;default:this.$resize(a,s,c,u)}}$handleActionEnd(){this.$action="",this.$actionStartTarget=null}$handleKeyDown(e){if(this.hidden||!this.keyboard||this.multiple&&!this.active||e.defaultPrevented)return;const{activeElement:t}=document;if(!t||!["INPUT","TEXTAREA"].includes(t.tagName)&&!["true","plaintext-only"].includes(t.contentEditable))switch(e.key){case"Backspace":e.metaKey&&(e.preventDefault(),this.$removeSelection());break;case"Delete":e.preventDefault(),this.$removeSelection();break;case"ArrowLeft":e.preventDefault(),this.$move(-1,0);break;case"ArrowRight":e.preventDefault(),this.$move(1,0);break;case"ArrowUp":e.preventDefault(),this.$move(0,-1);break;case"ArrowDown":e.preventDefault(),this.$move(0,1);break;case"+":e.preventDefault(),this.$zoom(.1);break;case"-":e.preventDefault(),this.$zoom(-.1)}}$center(){const{parentElement:e}=this;if(!e)return this;const t=(e.offsetWidth-this.width)/2,n=(e.offsetHeight-this.height)/2;return this.$change(t,n)}$move(e,t=e){return this.$moveTo(this.x+e,this.y+t)}$moveTo(e,t=e){return this.movable?this.$change(e,t):this}$resize(e,t=0,n=0,r=this.aspectRatio){if(!this.resizable)return this;const a=tt(r),{$canvas:i}=this;let{x:o,y:l,width:s,height:c}=this;switch(e){case Pe:l+=n,c-=n,c<0&&(e=Le,c=-c,l-=c),a&&(o+=(t=n*r)/2,s-=t,s<0&&(s=-s,o-=s));break;case Ie:s+=t,s<0&&(e=De,s=-s,o-=s),a&&(l-=(n=t/r)/2,c+=n,c<0&&(c=-c,l-=c));break;case Le:c+=n,c<0&&(e=Pe,c=-c,l-=c),a&&(o-=(t=n*r)/2,s+=t,s<0&&(s=-s,o-=s));break;case De:o+=t,s-=t,s<0&&(e=Ie,s=-s,o-=s),a&&(l+=(n=t/r)/2,c-=n,c<0&&(c=-c,l-=c));break;case Oe:a&&(n=-t/r),l+=n,c-=n,s+=t,s<0&&c<0?(e=Fe,s=-s,c=-c,o-=s,l-=c):s<0?(e=Re,s=-s,o-=s):c<0&&(e=je,c=-c,l-=c);break;case Re:a&&(n=t/r),o+=t,l+=n,s-=t,c-=n,s<0&&c<0?(e=je,s=-s,c=-c,o-=s,l-=c):s<0?(e=Oe,s=-s,o-=s):c<0&&(e=Fe,c=-c,l-=c);break;case je:a&&(n=t/r),s+=t,c+=n,s<0&&c<0?(e=Re,s=-s,c=-c,o-=s,l-=c):s<0?(e=Fe,s=-s,o-=s):c<0&&(e=Oe,c=-c,l-=c);break;case Fe:a&&(n=-t/r),o+=t,s-=t,c+=n,s<0&&c<0?(e=Oe,s=-s,c=-c,o-=s,l-=c):s<0?(e=je,s=-s,o-=s):c<0&&(e=Re,c=-c,l-=c)}return i&&i.$setAction(e),this.$change(o,l,s,c)}$zoom(e,t,n){if(!this.zoomable||0===e)return this;e<0?e=1/(1-e):e+=1;const{width:r,height:a}=this,i=r*e,o=a*e;let l=this.x,s=this.y;return et(t)&&et(n)?(l-=(i-r)*((t-this.x)/r),s-=(o-a)*((n-this.y)/a)):(l-=(i-r)/2,s-=(o-a)/2),this.$change(l,s,i,o)}$change(e,t,n=this.width,r=this.height,a=this.aspectRatio,i=!1){return this.$changing||!et(e)||!et(t)||!et(n)||!et(r)||n<0||r<0?this:(tt(a)&&({width:n,height:r}=xt({aspectRatio:a,width:n,height:r},"cover")),this.precise||(e=Math.round(e),t=Math.round(t),n=Math.round(n),r=Math.round(r)),e===this.x&&t===this.y&&n===this.width&&r===this.height&&Object.is(a,this.aspectRatio)&&!i?this:(this.hidden&&(this.hidden=!1),!1===this.$emit(Xe,{x:e,y:t,width:n,height:r})?this:(this.$changing=!0,this.x=e,this.y=t,this.width=n,this.height=r,this.$changing=!1,this.$render())))}$reset(){const{x:e,y:t,width:n,height:r}=this.$initialSelection;return this.$change(e,t,n,r)}$clear(){return this.$change(0,0,0,0,NaN,!0),this.hidden=!0,this}$render(){return this.$setStyles({transform:`translate(${this.x}px, ${this.y}px)`,width:this.width,height:this.height})}$toCanvas(e){return new Promise((t,n)=>{if(!this.isConnected)return void n(new Error("The current element is not connected to the DOM."));const r=document.createElement("canvas");let{width:a,height:i}=this,o=1;if(at(e)&&(tt(e.width)||tt(e.height))&&(({width:a,height:i}=xt({aspectRatio:a/i,width:e.width,height:e.height})),o=a/this.width),r.width=a,r.height=i,!this.$canvas)return void t(r);const l=this.$canvas.querySelector(this.$getTagNameOf(Ce));l?l.$ready().then(n=>{const s=r.getContext("2d");if(s){const[t,c,u,d,m,h]=l.$getTransform(),p=-this.x,f=-this.y,g=(p*d-u*f)/(t*d-u*c),b=(f*t-c*p)/(t*d-u*c);let y=t*g+u*b+m,v=c*g+d*b+h,w=n.naturalWidth,x=n.naturalHeight;1!==o&&(y*=o,v*=o,w*=o,x*=o);const k=w/2,C=x/2;s.fillStyle="transparent",s.fillRect(0,0,a,i),at(e)&&it(e.beforeDraw)&&e.beforeDraw.call(this,s,r),s.save(),s.translate(k,C),s.transform(t,c,u,d,y,v),s.translate(-k,-C),s.drawImage(n,0,0,w,x),s.restore()}t(r)}).catch(n):t(r)})}}Rt.$name=Se,Rt.$version="2.1.0";class jt extends zt{constructor(){super(...arguments),this.$style=":host{display:flex;flex-direction:column;position:relative;touch-action:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}:host([bordered]){border:1px dashed var(--theme-color)}:host([covered]){bottom:0;left:0;position:absolute;right:0;top:0}:host>span{display:flex;flex:1}:host>span+span{border-top:1px dashed var(--theme-color)}:host>span>span{flex:1}:host>span>span+span{border-left:1px dashed var(--theme-color)}",this.bordered=!1,this.columns=3,this.covered=!1,this.rows=3,this.slottable=!1,this.themeColor="rgba(238, 238, 238, 0.5)"}static get observedAttributes(){return super.observedAttributes.concat(["bordered","columns","covered","rows"])}$propertyChangedCallback(e,t,n){Object.is(n,t)||(super.$propertyChangedCallback(e,t,n),"rows"!==e&&"columns"!==e||this.$nextTick(()=>{this.$render()}))}connectedCallback(){super.connectedCallback(),this.$render()}$render(){const e=this.$getShadowRoot(),t=document.createDocumentFragment();for(let n=0;n<this.rows;n+=1){const e=document.createElement("span");e.setAttribute("role","row");for(let t=0;t<this.columns;t+=1){const t=document.createElement("span");t.setAttribute("role","gridcell"),e.appendChild(t)}t.appendChild(e)}e&&(e.innerHTML="",e.appendChild(t))}}jt.$name=xe,jt.$version="2.1.0";class Ft extends zt{constructor(){super(...arguments),this.$style=':host{display:inline-block;height:1em;position:relative;touch-action:none;-webkit-user-select:none;-moz-user-select:none;user-select:none;vertical-align:middle;width:1em}:host:after,:host:before{background-color:var(--theme-color);content:"";display:block;position:absolute}:host:before{height:1px;left:0;top:50%;transform:translateY(-50%);width:100%}:host:after{height:100%;left:50%;top:0;transform:translateX(-50%);width:1px}:host([centered]){left:50%;position:absolute;top:50%;transform:translate(-50%,-50%)}',this.centered=!1,this.slottable=!1,this.themeColor="rgba(238, 238, 238, 0.5)"}static get observedAttributes(){return super.observedAttributes.concat(["centered"])}}Ft.$name=we,Ft.$version="2.1.0";const Ut=/* @__PURE__ */new WeakMap,qt=/* @__PURE__ */new WeakMap,Bt=/* @__PURE__ */new WeakMap,Wt=/* @__PURE__ */new WeakMap,Vt="vertical";class Ht extends zt{constructor(){super(...arguments),this.$onSelectionChange=null,this.$onSourceImageLoad=null,this.$onSourceImageTransform=null,this.$scale=1,this.$style=":host{display:block;height:100%;overflow:hidden;position:relative;width:100%}",this.resize=Vt,this.selection="",this.slottable=!1}set $image(e){qt.set(this,e)}get $image(){return qt.get(this)}set $sourceImage(e){Wt.set(this,e)}get $sourceImage(){return Wt.get(this)}set $canvas(e){Ut.set(this,e)}get $canvas(){return Ut.get(this)}set $selection(e){Bt.set(this,e)}get $selection(){return Bt.get(this)}static get observedAttributes(){return super.observedAttributes.concat(["resize","selection"])}connectedCallback(){var e,t;super.connectedCallback();let n=null;if(n=this.selection?null!==(t=null===(e=function(e){const t=e.getRootNode();switch(t.nodeType){case 1:return t.ownerDocument;case 9:case 11:return t}return null}(this))||void 0===e?void 0:e.querySelector(this.selection))&&void 0!==t?t:null:this.closest(this.$getTagNameOf(Se)),ot(n)){this.$selection=n,this.$onSelectionChange=this.$handleSelectionChange.bind(this),ht(n,Xe,this.$onSelectionChange);const e=n.closest(this.$getTagNameOf(ve));if(e){this.$canvas=e;const t=e.querySelector(this.$getTagNameOf(Ce));t&&(this.$sourceImage=t,this.$image=t.cloneNode(!0),this.$getShadowRoot().appendChild(this.$image),this.$onSourceImageLoad=this.$handleSourceImageLoad.bind(this),this.$onSourceImageTransform=this.$handleSourceImageTransform.bind(this),ht(t.$image,He,this.$onSourceImageLoad),ht(t,Je,this.$onSourceImageTransform))}this.$render()}}disconnectedCallback(){const{$selection:e,$sourceImage:t}=this;e&&this.$onSelectionChange&&(mt(e,Xe,this.$onSelectionChange),this.$onSelectionChange=null),t&&this.$onSourceImageLoad&&(mt(t.$image,He,this.$onSourceImageLoad),this.$onSourceImageLoad=null),t&&this.$onSourceImageTransform&&(mt(t,Je,this.$onSourceImageTransform),this.$onSourceImageTransform=null),super.disconnectedCallback()}$handleSelectionChange(e){this.$render(e.defaultPrevented?this.$selection:e.detail)}$handleSourceImageLoad(){const{$image:e,$sourceImage:t}=this,n=e.getAttribute("src"),r=t.getAttribute("src");r&&r!==n&&(e.setAttribute("src",r),e.$ready(()=>{this.$render()}))}$handleSourceImageTransform(e){this.$render(void 0,e.detail.matrix)}$render(e,t){const{$canvas:n,$selection:r}=this;e||r.hidden||(e=r),(!e||0===e.x&&0===e.y&&0===e.width&&0===e.height)&&(e={x:0,y:0,width:n.offsetWidth,height:n.offsetHeight});const{x:a,y:i,width:o,height:l}=e,s={},{clientWidth:c,clientHeight:u}=this;let d=c,m=u,h=NaN;switch(this.resize){case"both":h=1,d=o,m=l,s.width=o,s.height=l;break;case"horizontal":h=l>0?u/l:0,d=o*h,s.width=d;break;case Vt:h=o>0?c/o:0,m=l*h,s.height=m;break;default:c>0?h=o>0?c/o:0:u>0&&(h=l>0?u/l:0)}this.$scale=h,this.$setStyles(s),this.$sourceImage&&setTimeout(()=>{this.$transformImageByOffset(null!=t?t:this.$sourceImage.$getTransform(),-a,-i)})}$transformImageByOffset(e,t,n){const{$image:r,$scale:a,$sourceImage:i}=this;if(i&&r&&a>=0){const[i,o,l,s,c,u]=e,d=(t*s-l*n)/(i*s-l*o),m=(n*i-o*t)/(i*s-l*o),h=i*d+l*m+c,p=o*d+s*m+u;r.$ready(e=>{this.$setStyles.call(r,{width:e.naturalWidth*a,height:e.naturalHeight*a})}),r.$setTransform(i,o,l,s,h*a,p*a)}}}Ht.$name=Ee,Ht.$version="2.1.0",Tt.$define(),Ft.$define(),jt.$define(),Dt.$define(),Pt.$define(),Rt.$define(),Lt.$define(),Ht.$define();class Kt{constructor(e,t,n){this.canvasRef=e,this.imageRef=t,this.selectionRef=n}get canvasElement(){return this.canvasRef?.current}get image(){return this.imageRef?.current}get selectionElement(){return this.selectionRef?.current}get isReady(){return!!(this.canvasElement&&this.image&&this.selectionElement)}transform={move:(e,t)=>{if(!this.image)return!1;try{return this.image.$move(e,t),!0}catch(n){return console.warn("Error moving image:",n),!1}},moveTo:(e,t)=>{if(!this.image)return!1;try{return this.image.$moveTo(e,t),!0}catch(n){return console.warn("Error moving image to position:",n),!1}},zoom:e=>{if(!this.image)return!1;try{return this.image.$zoom(e),!0}catch(t){return console.warn("Error zooming image:",t),!1}},rotate:e=>{if(!this.image)return!1;try{const t=e*Math.PI/180;return this.image.$rotate(t),!0}catch(t){return console.warn("Error rotating image:",t),!1}},scale:(e,t=e)=>{if(!this.image)return!1;try{return this.image.$scale(e,t),!0}catch(n){return console.warn("Error scaling image:",n),!1}},center:(e="contain")=>{if(!this.image)return!1;try{return this.image.$center(e),!0}catch(t){return console.warn("Error centering image:",t),!1}},reset:()=>{if(!this.image)return!1;try{return this.image.$resetTransform(),!0}catch(e){return console.warn("Error resetting transform:",e),!1}},getTransform:()=>{if(!this.image)return null;try{return this.image.$getTransform()}catch(e){return console.warn("Error getting transform:",e),null}},setTransform:(e,t,n,r,a,i)=>{if(!this.image)return!1;try{return this.image.$setTransform(e,t,n,r,a,i),!0}catch(o){return console.warn("Error setting transform:",o),!1}},resetZoom:()=>{if(!this.image)return!1;try{const e=this.image.$getTransform();if(!e)return!1;const[t,n,r,a,i,o]=e,l=Math.sqrt(t*t+n*n),s=Math.sqrt(r*r+a*a),c=t/l,u=n/l,d=r/s,m=a/s;return this.image.$setTransform(c,u,d,m,i,o),!0}catch(e){return console.warn("Error resetting zoom:",e),!1}},setZoom:e=>{if(!this.image||e<=0)return!1;try{const t=this.image.$getTransform();if(!t)return!1;const[n,r,a,i,o,l]=t,s=Math.sqrt(n*n+r*r),c=Math.sqrt(a*a+i*i),u=n/s*e,d=r/s*e,m=a/c*e,h=i/c*e;return this.image.$setTransform(u,d,m,h,o,l),!0}catch(t){return console.warn("Error setting zoom level:",t),!1}},getZoom:()=>{if(!this.image)return 1;try{const e=this.image.$getTransform();if(!e)return 1;const[t,n]=e;return Math.sqrt(t*t+n*n)}catch(e){return console.warn("Error getting zoom level:",e),1}},fitToCanvas:(e=.1)=>{if(!this.image||!this.canvasElement)return!1;try{const t=this.canvasElement.getBoundingClientRect();let n=this.image.querySelector("img")||this.image;if(!n?.naturalWidth||!n?.naturalHeight)return!1;const r=1-e,a=t.width*r/n.naturalWidth,i=t.height*r/n.naturalHeight,o=Math.min(a,i,1);return this.transform.setZoom(o)}catch(t){return console.warn("Error fitting to canvas:",t),!1}}};selection={center:()=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$center(),!0}catch(e){return console.warn("Error centering selection:",e),!1}},reset:()=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$reset(),!0}catch(e){return console.warn("Error resetting selection:",e),!1}},setCoverage:e=>{if(!this.selectionElement||e<0||e>1)return!1;try{return this.selectionElement.initialCoverage=e,this.selectionElement.$reset(),!0}catch(t){return console.warn("Error setting coverage:",t),!1}},setAspectRatio:e=>{if(!this.selectionElement)return!1;try{let t;if(""===e||null==e)t=NaN;else if("number"==typeof e)t=e;else{if("string"!=typeof e)return console.warn("Unsupported aspect ratio type:",typeof e,e),!1;if(e.includes("/")){const[n,r]=e.split("/").map(e=>parseFloat(e.trim()));if(isNaN(n)||isNaN(r)||0===r)return console.warn("Invalid aspect ratio format:",e),!1;t=n/r}else if(t=parseFloat(e),isNaN(t))return console.warn("Invalid aspect ratio format:",e),!1}return this.selectionElement.aspectRatio=t,this.selectionElement.$render(),!0}catch(t){return console.warn("Error setting aspect ratio:",t),!1}},move:(e,t)=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$move(e,t),!0}catch(n){return console.warn("Error moving selection:",n),!1}},zoom:e=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$zoom(e),!0}catch(t){return console.warn("Error zooming selection:",t),!1}},change:(e,t,n,r,a)=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$change(e,t,n,r,a),!0}catch(i){return console.warn("Error changing selection:",i),!1}},set:(e,t,n,r)=>{if(!this.selectionElement)return!1;try{return this.selectionElement.x=e,this.selectionElement.y=t,this.selectionElement.width=n,this.selectionElement.height=r,this.selectionElement.$render(),!0}catch(a){return console.warn("Error setting selection:",a),!1}},toCanvas:async(e={})=>{if(!this.selectionElement)return null;try{const t={width:800,height:600,imageSmoothingEnabled:!0,imageSmoothingQuality:"high",...e};return await this.selectionElement.$toCanvas(t)}catch(t){return console.warn("Error exporting to canvas:",t),null}},getData:()=>{if(!this.selectionElement)return null;try{return{x:this.selectionElement.x,y:this.selectionElement.y,width:this.selectionElement.width,height:this.selectionElement.height,aspectRatio:this.selectionElement.aspectRatio}}catch(e){return console.warn("Error getting selection data:",e),null}}};canvas={setBackground:e=>{if(!this.canvasElement)return!1;try{return this.canvasElement.background=e,!0}catch(t){return console.warn("Error setting background:",t),!1}},setScaleStep:e=>{if(!this.canvasElement)return!1;try{return this.canvasElement.scaleStep=e,!0}catch(t){return console.warn("Error setting scale step:",t),!1}},setDisabled:e=>{if(!this.canvasElement)return!1;try{return this.canvasElement.disabled=e,!0}catch(t){return console.warn("Error setting disabled state:",t),!1}}};utils={flipHorizontal:()=>{const e=this.transform.getTransform();if(!e)return!1;const[t,n,r,a,i,o]=e;return this.transform.setTransform(-t,n,r,a,i,o)},flipVertical:()=>{const e=this.transform.getTransform();if(!e)return!1;const[t,n,r,a,i,o]=e;return this.transform.setTransform(t,n,r,-a,i,o)},setupInitialView:async(e={})=>{const{paspartuFactor:t=.85,retries:n=3,retryDelay:r=200}=e;return new Promise(e=>{const a=(i=0)=>{if(!this.isReady)return i<n?void setTimeout(()=>a(i+1),r):void e(!1);try{const o=this.canvasElement.getBoundingClientRect();let l=this.image.querySelector("img")||this.image;if(!l?.naturalWidth||!l?.naturalHeight)return i<n?void setTimeout(()=>a(i+1),r):(this.transform.center(),void e(!1));if(o.width>0&&o.height>0){const n=o.width*t/l.naturalWidth,r=o.height*t/l.naturalHeight,a=Math.min(n,r,1);this.transform.setTransform(a,0,0,a,0,0)?setTimeout(()=>{this.transform.center(),this.selection.center(),e(!0)},100):(this.transform.reset(),setTimeout(()=>{a<1&&this.transform.scale(a),setTimeout(()=>{this.transform.center(),this.selection.center(),e(!0)},100)},100))}else this.transform.center(),e(!1)}catch(o){console.warn("Error in setup:",o),this.transform.center(),e(!1)}};a()})},resetAll:()=>{const e={transform:this.transform.reset(),selection:this.selection.reset(),center:!1};return setTimeout(()=>{e.center=this.transform.center()&&this.selection.center()},100),e},checkExportability:async()=>{try{return!!(await this.selection.toCanvas({width:1,height:1}))}catch{return!1}},resetZoomOnly:()=>this.transform.resetZoom(),getZoomInfo:()=>{const e=this.transform.getZoom();return{current:e,isZoomedIn:e>1,isZoomedOut:e<1,percentage:Math.round(100*e)}},setBackground:e=>this.canvas.setBackground(e)};setupEventListeners(e={}){const{onSelectionChange:t,onImageTransform:n,onAction:r,onActionStart:a,onActionMove:i,onActionEnd:o}=e,l=[];if(t&&this.selectionElement){const e=e=>{t({x:e.detail.x,y:e.detail.y,width:e.detail.width,height:e.detail.height})};this.selectionElement.addEventListener("change",e),l.push(()=>{this.selectionElement&&this.selectionElement.removeEventListener("change",e)})}if(n&&this.image){const e=e=>{n({matrix:e.detail.matrix,oldMatrix:e.detail.oldMatrix})};this.image.addEventListener("transform",e),l.push(()=>{this.image&&this.image.removeEventListener("transform",e)})}if(this.canvasElement){if(r){const e=e=>r(e.detail);this.canvasElement.addEventListener("action",e),l.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("action",e)})}if(a){const e=e=>a(e.detail);this.canvasElement.addEventListener("actionstart",e),l.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionstart",e)})}if(i){const e=e=>i(e.detail);this.canvasElement.addEventListener("actionmove",e),l.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionmove",e)})}if(o){const e=e=>o(e.detail);this.canvasElement.addEventListener("actionend",e),l.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionend",e)})}}return()=>{l.forEach(e=>e())}}}async function Gt(e,t,n={}){const{format:r=null,originalFormat:a="webp",onSuccess:i=null,onError:o=null,accessibilityManager:l=null}=n;try{const n=window.limboCore?.config?.getGlobal(),o=r||n?.downloadFormat||a||"webp",s=`${t.split(".")[0]}.${o}`;if(l&&l.announce(`Descargando ${s}`),e.startsWith("data:image/"))return function(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.style.display="none",document.body.appendChild(n),n.click(),setTimeout(()=>{document.body.removeChild(n)},100)}(e,s),i&&i(s),l&&l.announce(`${s} descargado correctamente`),!0;const c=await fetch(e,{mode:"cors"});if(!c.ok)throw new Error(`HTTP error! status: ${c.status}`);const u=await c.blob();let d=u;const m=u.type;m!==`image/${"jpg"===o?"jpeg":o}`&&function(e){return["webp","jpeg","jpg","png"].includes(e.toLowerCase())}(o)&&(d=await async function(e,t){return new Promise((n,r)=>{const a=new Image,i=URL.createObjectURL(e);a.onload=()=>{try{const r=document.createElement("canvas");r.width=a.width,r.height=a.height;r.getContext("2d").drawImage(a,0,0);const o=`image/${"jpg"===t?"jpeg":t}`,l="png"===t?void 0:.92;r.toBlob(t=>{URL.revokeObjectURL(i),n(t||e)},o,l)}catch(r){URL.revokeObjectURL(i),n(e)}},a.onerror=()=>{URL.revokeObjectURL(i),n(e)},a.src=i})}(u,o));const h=window.URL.createObjectURL(d),p=document.createElement("a");return p.href=h,p.download=s,p.style.display="none",document.body.appendChild(p),p.click(),setTimeout(()=>{window.URL.revokeObjectURL(h),document.body.removeChild(p)},100),i&&i(s),l&&l.announce(`${s} descargado correctamente`),!0}catch(s){return console.error("Error downloading image:",s),o&&o(s),l&&l.announce(`Error al descargar la imagen: ${s.message}`),!1}}const Qt=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:Gt,downloadImage:Gt},Symbol.toStringTag,{value:"Module"}));function Yt({image:e,onSave:o,onCancel:u,onDelete:d,onError:m=null,deleting:h=!1,onVariantCreated:p=null,onUpload:f=null,uploading:g=!1,cropperConfig:b=null}){const[y,v]=t(!1),[w,x]=t(null),[k,C]=t(!1),[S,N]=t(!0),[E,$]=t(!0),[_,z]=t({x:20,y:100}),[T,A]=t(!1),[M,P]=t({x:0,y:0}),[I,L]=t(!1),[D,O]=t(!0),[R,j]=t(!1),[U,q]=t({horizontal:!1,vertical:!1}),[W,V]=t(!1),[H,K]=t(!1),[G,Q]=t(!1),[Y,X]=t(!1),[J]=t(()=>{if(!e||!e.filename)return"image";const[t]=e.filename.split(".");return t}),Z=i(()=>{if(b)return{mandatoryCrops:b.mandatoryCrops||[],allowCustomCrops:!1!==b.allowAdditionalCrops,showDimensionInputs:!0===b.showDimensionInputs,maxCrops:b.maxCrops||null};const e=window.limboCore?.config?.getGlobal()||{};return{mandatoryCrops:e.cropper?.mandatoryCrops||[],allowCustomCrops:!1!==e.cropper?.allowCustomCrops,showDimensionInputs:!0===e.cropper?.showDimensionInputs,maxCrops:e.cropper?.maxCrops||null}},[b]),[ee,ne]=t(()=>Z.mandatoryCrops.length>0?Z.mandatoryCrops.map((e,t)=>({id:`crop-${t}`,label:e.label,width:e.width,height:e.height,required:!1!==e.required,isCustom:!1,confirmed:!1,lockDimensions:!(!e.width||!e.height),savedState:null})):[{id:"crop-default-0",label:J,width:e.width||1920,height:e.height||1080,required:!1,isCustom:!0,confirmed:!1,savedState:null}]),[re,ae]=t(0),ie=ee[re],oe=i(()=>ie&&ie.width&&ie.height?ie.width/ie.height:"",[ie]),le=i(()=>{const e=50;if(!oe||""===oe)return{minWidth:e,minHeight:e};if(oe>=1){return{minWidth:e,minHeight:e/oe}}return{minWidth:e*oe,minHeight:e}},[oe]),[se,ce]=t(!1),[ue,de]=t([]),[me,he]=t(null),pe=window.limboCore?.accessibilityManager,{createCropVariant:fe,loading:ge,error:be}=function(){const[e,n]=t(!1),[r,a]=t(null),[i,o]=t(null),l=async(e,t)=>{if(!e||!t)return a("ID de asset y configuración de variante son requeridos"),null;n(!0),a(null),o(null);try{const n=await F(e,{variant_name:t.name,width:t.width,height:t.height,crop_params:t.crop_params,preset_aspect:t.preset_aspect,preset_size:t.preset_size,output_format:t.output_format});if(n?.result)return o(n.result),n.result;throw new Error("No se pudo crear la variante")}catch(r){return console.error("Error creating variant:",r),a(r.message||"Error desconocido al crear variante"),null}finally{n(!1)}};return{createVariant:l,createCropVariant:async(e,t,n={})=>{const r={name:n.name||`crop_${Date.now()}`,width:n.width||800,height:n.height||600,output_format:n.format||"webp",crop_params:{x:t.x||0,y:t.y||0,width:t.width||1,height:t.height||1}};return await l(e,r)},loading:e,error:r,createdVariant:i,reset:()=>{a(null),o(null)}}}(),ye=((e,i={})=>{const o=a(null),l=a(null),s=a(null),c=a(null),[u,d]=t(null),[m,h]=t(null),[p,f]=t(!1),[g,b]=t(!0),[y,v]=t(0),w={aspectRatio:"",shade:!0,paspartuFactor:.85,...i};n(()=>{o.current&&l.current&&s.current&&(c.current=new Kt(o,l,s),f(!0))},[]),n(()=>{if(c.current)return c.current.setupEventListeners({onSelectionChange:e=>{d(e)},onImageTransform:()=>{v(e=>e+1)}})},[p]),n(()=>{c.current&&e&&(async()=>{c.current.selection.setAspectRatio(w.aspectRatio),c.current.canvas.setBackground(w.shade),await c.current.utils.setupInitialView({paspartuFactor:w.paspartuFactor});const e=await c.current.utils.checkExportability();b(e);const t=l.current?.querySelector("img")||l.current;t?.naturalWidth&&t?.naturalHeight&&h({naturalWidth:t.naturalWidth,naturalHeight:t.naturalHeight,currentWidth:t.width,currentHeight:t.height})})()},[e]),n(()=>{c.current&&p&&c.current.selection.setAspectRatio(w.aspectRatio)},[w.aspectRatio,p]),n(()=>{c.current&&p&&c.current.canvas.setBackground(w.shade)},[w.shade,p]);const x=r(()=>({move:(e,t)=>c.current?.transform.move(e,t)||!1,zoom:e=>c.current?.transform.zoom(e)||!1,rotate:e=>c.current?.transform.rotate(e)||!1,center:()=>c.current?.transform.center()||!1,reset:()=>c.current?.transform.reset()||!1,resetZoom:()=>c.current?.transform.resetZoom()||!1,setZoom:e=>c.current?.transform.setZoom(e)||!1,getZoom:()=>c.current?.transform.getZoom()||1,fitToCanvas:e=>c.current?.transform.fitToCanvas(e)||!1,flipHorizontal:()=>c.current?.utils.flipHorizontal()||!1,flipVertical:()=>c.current?.utils.flipVertical()||!1}),[]),k=r(()=>({center:()=>c.current?.selection.center()||!1,reset:()=>c.current?.selection.reset()||!1,setCoverage:e=>c.current?.selection.setCoverage(e)||!1,setAspectRatio:e=>c.current?.selection.setAspectRatio(e)||!1,toCanvas:e=>c.current?.selection.toCanvas(e)||Promise.resolve(null)}),[]),C=r(()=>({resetAll:()=>{if(c.current){const e=c.current.utils.resetAll();return d(null),e}return!1},setBackground:e=>c.current?.canvas.setBackground(e)||!1,resetZoomOnly:()=>c.current?.utils.resetZoomOnly()||!1,getZoomInfo:()=>c.current?.utils.getZoomInfo()||{current:1,percentage:100,isZoomedIn:!1,isZoomedOut:!1}}),[]);return{refs:{canvasRef:o,imageRef:l,selectionRef:s},state:{cropData:u,imageInfo:m,isReady:p,canExport:g,transformVersion:y},transform:x(),selection:k(),utils:C(),manager:c.current}})(e,{aspectRatio:oe||null,showGrid:S,shade:E,initialCoverage:.5,paspartuFactor:.85}),{refs:ve,state:we,transform:xe,selection:ke,utils:Ce}=ye,{canvasRef:Se,imageRef:Ne,selectionRef:Ee}=ve,{cropData:$e,imageInfo:_e,canExport:ze,transformVersion:Te}=we,Ae=i(()=>_e||{naturalWidth:e.width||1920,naturalHeight:e.height||1080,currentWidth:e.width||1920,currentHeight:e.height||1080},[_e,e.width,e.height]),Me=r(()=>N(e=>!e),[]),Pe=r(()=>$(e=>!e),[]),Ie=r(()=>K(e=>!e),[]),Le=r(()=>Q(e=>!e),[]),De=r(()=>X(e=>!e),[]),Oe=r(()=>xe.center(),[xe]),Re=r(()=>ke.center(),[ke]),je=r(()=>ke.reset(),[ke]),Fe=r((e,t)=>xe.move(e,t),[xe]),Ue=r(e=>xe.zoom(e),[xe]),qe=r(e=>xe.rotate(e),[xe]),Be=r(e=>{ke.setCoverage(e)},[ke]),We=r(()=>{q(e=>{const t=!e.horizontal;return xe.flipHorizontal(),{...e,horizontal:t}})},[xe]),Ve=r(()=>{q(e=>{const t=!e.vertical;return xe.flipVertical(),{...e,vertical:t}})},[xe]),He=r(()=>{if(!ye.manager||!we.isReady)return null;try{const e=$e?{...$e}:null;let t=null;if(Ee.current){const e=Ee.current;t={x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0}}let n=null;if(Ne.current){const e=Ne.current.$getTransform?.();e&&Array.isArray(e)&&(n=[...e])}const r={cropData:e,selectorState:t,imageTransform:n,flipState:{horizontal:U.horizontal,vertical:U.vertical}};return console.log(`[CropperView] 💾 Guardando estado del crop ${re}:`,r),ne(e=>e.map((e,t)=>t===re?{...e,savedState:r}:e)),r}catch(e){return console.warn("Error saving crop state:",e),null}},[ye.manager,we.isReady,$e,U,re,Ne,Ee]),Ke=r(e=>{const t=ee[e];if(!t||!t.savedState)return console.log(`[CropperView] ℹ️ No hay estado guardado para crop ${e}, centrando...`),void setTimeout(()=>{Oe(),setTimeout(()=>Re(),100)},100);if(ye.manager&&we.isReady)try{const{savedState:n}=t;if(console.log(`[CropperView] ♻️ Restaurando estado del crop ${e}:`,n),n.imageTransform&&Ne.current&&Array.isArray(n.imageTransform)&&setTimeout(()=>{if(Ne.current&&Ne.current.$setTransform){const[e,t,r,a,i,o]=n.imageTransform;Ne.current.$setTransform(e,t,r,a,i,o),console.log(`[CropperView] ✅ Imagen restaurada: transform(${e.toFixed(2)}, ${t.toFixed(2)}, ${r.toFixed(2)}, ${a.toFixed(2)}, ${i.toFixed(0)}, ${o.toFixed(0)})`)}},100),n.selectorState&&Ee.current){const{x:e,y:t,width:r,height:a}=n.selectorState;setTimeout(()=>{Ee.current&&(Ee.current.x=e,Ee.current.y=t,Ee.current.width=r,Ee.current.height=a,Ee.current.$render&&Ee.current.$render(),console.log(`[CropperView] ✅ Selector restaurado: ${r}×${a} en (${e}, ${t})`))},150)}n.flipState&&q({horizontal:n.flipState.horizontal??!1,vertical:n.flipState.vertical??!1}),console.log("[CropperView] ✨ Estado restaurado completamente")}catch(n){console.error("Error restoring crop state:",n),setTimeout(()=>{Oe(),setTimeout(()=>Re(),100)},100)}else console.warn("Cropper not ready for state restoration")},[ee,ye.manager,we.isReady,Oe,Re,Ee,Ne]),Ge=r(()=>{for(let e=0;e<ee.length;e++){const t=ee[e];if(!t.label||""===t.label.trim())return e}return-1},[ee]),Qe=r(async e=>{e!==re&&(j(!0),He(),await new Promise(e=>setTimeout(e,100)),ae(e),await new Promise(e=>setTimeout(e,250)),Ke(e),await new Promise(e=>setTimeout(e,200)),j(!1))},[re,He,Ke]),Ye=r(()=>{if(!Z.allowCustomCrops)return void alert("No se pueden añadir recortes personalizados en este modo.");const t={id:`crop-custom-${Date.now()}`,label:`Recorte ${ee.length+1}`,width:e.width||1920,height:e.height||1080,required:!1,isCustom:!0,confirmed:!1,savedState:null};ne(e=>[...e,t]),pe?.announce(`Nuevo recorte personalizado añadido: ${t.label}. Selecciónalo para editarlo.`)},[Z.allowCustomCrops,ee.length,e.width,e.height,pe]),Xe=r((e,t)=>{const n=parseInt(t,10);""===t||isNaN(n)||ne(t=>t.map((t,r)=>r===re?{...t,[e]:n}:t))},[re]),Je=r(e=>{const t=ie[e];let n=100;if(Se.current&&_e){const e=Se.current.getBoundingClientRect(),t=Math.min(e.width,e.height);n=Math.max(100,Math.round(.05*t))}const r=Math.max(n,Math.min(5e3,t));r!==t&&ne(t=>t.map((t,n)=>n===re?{...t,[e]:r}:t));const a={...ie,[e]:r},i=a.width/a.height,o=ke.getData?.();ke.setAspectRatio(i),o&&void 0!==o.x&&setTimeout(()=>{ke.set?.(o.x,o.y,o.width,o.height)},50)},[re,ie,ke,Se,_e]),Ze=r(e=>{ne(t=>t.map((t,n)=>n===re?{...t,label:e}:t))},[re]),et=r((e,t=null)=>{t=t||ee[e].label;if(!window.confirm(`¿Estás seguro de que deseas eliminar "${t||"este recorte"}"? Esta acción también eliminará todos sus recortes.`))return;const n=ee[e];if(n.required)alert("No se puede eliminar un recorte obligatorio.");else if(1!==ee.length){if(ne(t=>t.filter((t,n)=>n!==e)),e===re){const t=Math.max(0,e-1);ae(t)}else e<re&&ae(e=>e-1);pe?.announce(`Recorte ${n.label} eliminado`)}else alert("Debe haber al menos un recorte.")},[ee,re,pe]),tt=r(async()=>{if(!ze)return null;try{const t=await ke.toCanvas({width:800,height:600,imageSmoothingEnabled:!0,imageSmoothingQuality:"high"});return t?t.toDataURL(`image/${globalThis.downloadFormat||e.mime_type.split("/")[1]||"webp"}`,.9):null}catch(t){return console.warn("Error generating preview:",t),null}},[ze,e.mime_type,ke]),nt=r(async()=>{if(y)return v(!1),x(null),void C(!1);if(ze){v(!0),C(!0);try{const e=await tt();e?x(e):(v(!1),alert("No se puede exportar el recorte por restricciones de CORS en la imagen original."))}finally{C(!1)}}else alert("No se puede exportar el recorte por restricciones de CORS en la imagen original.")},[ze,tt,y]),rt=r(e=>{e.target.closest(".limbo-preview-modal-header")&&(A(!0),P({x:e.clientX-_.x,y:e.clientY-_.y}))},[_]),at=r(e=>{T&&(e.preventDefault(),z({x:e.clientX-M.x,y:e.clientY-M.y}))},[T,M]),it=r(()=>{A(!1)},[]),ot=r(e=>{if(!e.target.closest(".limbo-preview-modal-header"))return;const t=e.touches[0];A(!0),P({x:t.clientX-_.x,y:t.clientY-_.y})},[_]),lt=r(e=>{if(!T)return;e.preventDefault();const t=e.touches[0];z({x:t.clientX-M.x,y:t.clientY-M.y})},[T,M]),st=r(()=>{A(!1)},[]);n(()=>{if(T)return document.addEventListener("mousemove",at),document.addEventListener("mouseup",it),document.addEventListener("touchmove",lt,{passive:!1}),document.addEventListener("touchend",st),()=>{document.removeEventListener("mousemove",at),document.removeEventListener("mouseup",it),document.removeEventListener("touchmove",lt),document.removeEventListener("touchend",st)}},[T,at,it,lt,st]),n(()=>{if(!I)return;const e=e=>{"Escape"===e.key&&L(!1)};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[I]);const ct=r(async(t,n=null)=>{const r=ee[t];if(!r)throw new Error(`Crop ${t} no encontrado`);let a;if(r.savedState&&r.savedState.cropData)a=r.savedState.cropData,console.log(`[CropperView] Usando savedState para crop ${t}:`,a);else{if(t!==re||!$e)throw new Error(`No hay datos de recorte para el crop "${r.label}". Ajusta el recorte antes de guardar.`);a=$e,console.log(`[CropperView] Usando cropData actual para crop activo ${t}:`,a)}if(!a.x&&0!==a.x||!a.y&&0!==a.y||!a.width||!a.height)throw new Error(`Datos de recorte inválidos para "${r.label}"`);if(!Ae?.naturalWidth||!Ae?.naturalHeight)throw new Error("Información de imagen no disponible");const{x:i,y:o,width:l,height:s}=a,{naturalWidth:c,naturalHeight:u}=Ae;let d=i,m=o,h=l,f=s;const g=Ne.current?.$getTransform?.();if(console.log("[CropperView] Raw transform matrix:",g),g&&Array.isArray(g)&&g.length>=6){const[e,t,n,r,a,p]=g,b=Math.sqrt(e*e+t*t),y=Math.sqrt(n*n+r*r);b>0&&y>0&&(d=(i-a)/b,m=(o-p)/y,h=l/b,f=s/y,console.log("[CropperView] Transform correction applied:",{originalCoords:{x:i,y:o,width:l,height:s},transform:{scaleX:b,scaleY:y,translateX:a,translateY:p},correctedCoords:{x:d,y:m,width:h,height:f},naturalSize:{naturalWidth:c,naturalHeight:u}}))}const b={x:Math.max(0,Math.min(1,d/c)),y:Math.max(0,Math.min(1,m/u)),width:Math.max(0,Math.min(1,h/c)),height:Math.max(0,Math.min(1,f/u))};console.log("[CropperView] Final cropParams being sent to backend:",{cropParams:b,usedCropData:a,transformMatrix:Ne.current?.$getTransform?.(),effectiveImageInfo:Ae});const y=Math.min(r.width,5e3),v=Math.min(r.height,5e3),w=`${r.label||"crop"}_${y}_${v}`,x=n||e.id,k=await fe(x,b,{name:w,width:y,height:v,format:globalThis.downloadFormat||"webp",quality:90});if(k)return pe?.announceSuccess(`Recorte creado: ${w}`),p?.(x,k),k;throw new Error("No se pudo crear la variante")},[ee,re,$e,Ae,fe,e.id,p,pe,Ne]),ut=r(async()=>{if(!ze){const e="No se puede exportar el recorte por restricciones de CORS en la imagen original.";return pe?.announceError(e),void alert(e)}if(!we.isReady){const e="El cropper aún no está inicializado. Espera un momento e inténtalo de nuevo.";return pe?.announceError(e),void alert(e)}He(),pe?.announce("Creando recorte de la imagen");try{let t=e.id,n=null;if(e.file&&f){pe?.announce("Subiendo imagen...");const r=await f(e.file);if(!r||!r.id)throw new Error("No se pudo subir la imagen al servidor");t=r.id,n=r,pe?.announceSuccess("Imagen subida correctamente")}const r=await ct(re,t);r&&o(n?{crops:[r],asset:n}:r)}catch(t){console.warn("Error creating crop variant:",t);const e=t.message||"No se pudo crear el recorte. Inténtalo de nuevo.";pe?.announceError(e),alert(e),m?.(t)}},[ze,we.isReady,pe,He,ct,re,o,m,e.file,e.id,f]),dt=r(async t=>{He(),pe?.announce(`Guardando ${t.length} recortes...`);try{let r=e.id,a=null;if(e.file&&f){pe?.announce("Subiendo imagen...");const t=await f(e.file);if(!t||!t.id)throw new Error("No se pudo subir la imagen al servidor");r=t.id,a=t,pe?.announceSuccess("Imagen subida correctamente")}const i=[],l=[];for(const e of t)try{const t=await ct(e,r);t&&i.push(t)}catch(n){l.push({crop:ee[e]?.label||`Crop ${e}`,error:n.message})}if(i.length>0&&(pe?.announceSuccess(`${i.length} recorte(s) guardado(s) correctamente`),o(a?{crops:i,asset:a}:i)),l.length>0){const e=`Errores al guardar algunos recortes:\n${l.map(e=>`- ${e.crop}: ${e.error}`).join("\n")}`;pe?.announceError(e),alert(e)}}catch(n){const e=n.message||"Error al procesar los recortes";pe?.announceError(e),alert(e),m?.(n)}},[He,ct,ee,pe,o,e.file,e.id,f,m]),mt=r(async()=>{const e=Ge();if(-1!==e){const t=ee[e];return alert(`El recorte "${t.label||t||"(sin nombre)"}" debe tener un nombre válido.`),void ae(e)}if(ee.length>1){he("save");const e=ee.map((e,t)=>({crop:e,index:t})).filter(({crop:e,index:t})=>e.required||e.savedState||t===re).map(({index:e})=>e);return de(e),void ce(!0)}await ut()},[Ge,ee,ut,re]),ht=r(async t=>{const n=ee[t];if(!n)throw new Error(`Crop ${t} no encontrado`);if(!n.savedState&&t!==re)throw new Error(`El recorte "${n.label}" aún no ha sido configurado`);const r={index:re,imageTransform:Ne.current?.$getTransform?.(),selectorState:Ee.current?{x:Ee.current.x,y:Ee.current.y,width:Ee.current.width,height:Ee.current.height}:null};try{if(t!==re&&n.savedState){if(console.log(`[CropperView] 🔄 Restaurando temporalmente crop ${t} para descarga...`),n.savedState.imageTransform&&Ne.current?.$setTransform){const[e,t,r,a,i,o]=n.savedState.imageTransform;Ne.current.$setTransform(e,t,r,a,i,o)}if(n.savedState.selectorState&&Ee.current){const{x:e,y:t,width:r,height:a}=n.savedState.selectorState;Ee.current.x=e,Ee.current.y=t,Ee.current.width=r,Ee.current.height=a,Ee.current.$render?.()}await new Promise(e=>setTimeout(e,100))}const r=await ke.toCanvas({width:n.width,height:n.height,imageSmoothingEnabled:!0,imageSmoothingQuality:"high"});if(!r)throw new Error(`No se pudo generar el canvas para "${n.label}"`);const a=r.toDataURL(`image/${globalThis.downloadFormat||e.mime_type.split("/")[1]||"webp"}`,.9),i=`${(n.label||"crop").replace(/\.[^/.]+$/,"").replace(/\s+/g,"-").trim()}_${n.width}_${n.height}`;return await Gt(a,i,{accessibilityManager:pe,onSuccess:e=>{console.log(`✅ Descargado: ${e}`)},onError:e=>{throw new Error(`Error al descargar "${n.label}": ${e.message}`)}}),{crop:n.label,filename:i}}finally{if(t!==re&&r.imageTransform&&Ne.current?.$setTransform){console.log(`[CropperView] ↩️ Restaurando estado original del crop ${r.index}...`);const[e,t,n,a,i,o]=r.imageTransform;if(Ne.current.$setTransform(e,t,n,a,i,o),r.selectorState&&Ee.current){const{x:e,y:t,width:n,height:a}=r.selectorState;Ee.current.x=e,Ee.current.y=t,Ee.current.width=n,Ee.current.height=a,Ee.current.$render?.()}}}},[ee,re,ke,e.mime_type,pe,Ne,Ee]),pt=r(async e=>{He(),pe?.announce(`Descargando ${e.length} recortes...`);const t=[],n=[];for(const a of e)try{const e=await ht(a);e&&t.push(e)}catch(r){n.push({crop:ee[a]?.label||`Crop ${a}`,error:r.message})}if(t.length>0&&pe?.announceSuccess(`${t.length} recorte(s) descargado(s) correctamente`),n.length>0){const e=`Errores al descargar algunos recortes:\n${n.map(e=>`- ${e.crop}: ${e.error}`).join("\n")}`;pe?.announceError(e),alert(e)}},[He,ht,ee,pe]),ft=r(async()=>{if(!ze){const e="No se puede descargar el recorte por restricciones de CORS en la imagen original.";return pe?.announceError(e),void alert(e)}He(),pe?.announce("Preparando descarga del recorte");try{await ht(re),pe?.announceSuccess("Recorte descargado correctamente")}catch(e){console.error("Error downloading crop:",e);const t=e.message||"Error al descargar el recorte";pe?.announceError(t),alert(t)}},[ze,pe,He,ht,re]),gt=r(async()=>{const e=Ge();if(-1!==e){const t=ee[e];return alert(`El recorte "${t.label||t||"(sin nombre)"}" debe tener un nombre válido.`),void ae(e)}if(ee.length>1){he("download");const e=ee.map((e,t)=>({crop:e,index:t})).filter(({crop:e,index:t})=>e.savedState||t===re).map(({index:e})=>e);return de(e),void ce(!0)}await ft()},[Ge,ee,ft,re]),bt=r(async()=>{if(e.file&&f)try{pe?.announce("Subiendo imagen original...");const t=await f(e.file);if(!t||!t.id)throw new Error("No se pudo subir la imagen al servidor");pe?.announceSuccess("Imagen guardada correctamente"),o({asset:t,crops:[]})}catch(t){console.error("Error guardando imagen original:",t);const e=t.message||"No se pudo guardar la imagen. Inténtalo de nuevo.";pe?.announceError(e),alert(e),m?.(t)}else u()},[e.file,f,u,o,m,pe]);return n(()=>{v(!1),x(null)},[e]),n(()=>{ye.manager&&we.isReady&&D&&(console.log("[CropperView] Carga inicial completada, centrando imagen y selector..."),setTimeout(()=>{Oe(),setTimeout(()=>{Re(),O(!1),console.log("[CropperView] Carga inicial finalizada")},100)},50))},[ye.manager,we.isReady,D,Oe,Re]),n(()=>{ye.manager&&we.isReady&&(oe&&ke.setAspectRatio(oe),Ce.setBackground(E))},[oe,E,ye.manager,we.isReady,ke,Ce]),n(()=>{if(!_e||!we.isReady||Z.mandatoryCrops.length>0)return;const e=ee[0];if(e&&"crop-default-0"===e.id&&(1920===e.width||1080===e.height)){const t=Math.min(_e.naturalWidth,5e3),n=Math.min(_e.naturalHeight,5e3);ne([{...e,width:t,height:n}]),console.log(`[CropperView] Crop por defecto actualizado a ${t}×${n}px`)}},[_e,we.isReady,Z.mandatoryCrops.length,ee]),n(()=>{if(!y||!ze)return;const e=setTimeout(async()=>{C(e=>!w&&!e||e);try{const e=await tt();e&&x(e)}finally{C(!1)}},300);return()=>{clearTimeout(e),C(!1)}},[$e,Te,y,ze,tt,oe,U,w]),n(()=>{const e=Se.current,t=t=>{if("Delete"===t.key||"Backspace"===t.key||"Backspace"===t.key&&t.metaKey||"Backspace"===t.key&&t.ctrlKey){const n=t.target;if(e&&(n===e||n===document.body||n===document.documentElement||"CROPPER-CANVAS"===n.tagName||"CROPPER-SELECTION"===n.tagName||"CROPPER-IMAGE"===n.tagName||"CROPPER-HANDLE"===n.tagName||"CROPPER-GRID"===n.tagName||n.closest("cropper-canvas")||e.contains(n)))return t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),!1}};return document.addEventListener("keydown",t,!0),document.addEventListener("keyup",t,!0),window.addEventListener("keydown",t,!0),e&&e.addEventListener("keydown",t,!0),()=>{document.removeEventListener("keydown",t,!0),document.removeEventListener("keyup",t,!0),window.removeEventListener("keydown",t,!0),e&&e.removeEventListener("keydown",t,!0)}},[Se]),e?/* @__PURE__ */s("div",{className:"limbo-cropper-view px-2 border-2 border-gray-200/50 rounded-lg max-w-7xl mx-auto w-full min-w-full h-full min-h-full flex flex-col",children:[
227
227
  /* @__PURE__ */s("div",{className:"limbo-cropper-header flex flex-row justify-between items-start flex-wrap mx-2 py-2 border-b border-gray-200 bg-white z-10 shrink-0 lg:gap-2",children:[
228
228
  /* @__PURE__ */s("div",{className:"flex-1 min-w-fit space-y-2 max-w-fit",children:[
229
229
  /* @__PURE__ */s("div",{className:"flex items-center gap-2",children:[