limbo-component 3.3.5 → 3.3.7

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
@@ -114,7 +114,7 @@ return c(u,{children:[
114
114
  /* @__PURE__ */s("span",{className:"icon icon-spinner lb:animate-spin lb:w-6 lb:h-6"}),
115
115
  /* @__PURE__ */s("span",{className:"lb:text-xs lb:text-gray-600 lb:font-medium",children:"Moviendo..."})]}),
116
116
  /* @__PURE__ */c("div",{className:`limbo-image-actions ${z?"limbo-image-actions--expanded":""} ${Q?"limbo-image-actions--mobile":""}`,children:[
117
- /* @__PURE__ */c("div",{className:"limbo-image-actions__buttons",children:[(be||!O)&&/* @__PURE__ */s("button",{type:"button",title:ie?`Ver ${oe} recortes`:O?"Ampliar imagen":"Previsualizar archivo",className:"limbo-action-btn lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:border lb:border-brand-blue-1000 "+(Q?"lb:btn--touch":""),onClick:e=>{e?.stopPropagation(),ie?(Y?.announce(`Mostrando recortes de ${l.filename}`),C(!0)):(Y?.announce(`Abriendo visor de ${l.filename}`),S(!0))},tabIndex:-1,style:{...Q&&{width:"40px",height:"40px"}},children:/* @__PURE__ */s("span",{className:`icon ${ie||O?"icon-zoom-white":"icon-search-white"} icon--sm`,"aria-hidden":"true"})}),me&&/* @__PURE__ */s("button",{type:"button",title:"Editar imagen",className:"limbo-action-btn limbo-btn-crop lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:border lb:border-brand-blue-1000 "+(Q?"lb:btn--touch":""),onClick:ae,tabIndex:-1,style:{...Q&&{width:"40px",height:"40px"}},children:/* @__PURE__ */s("span",{className:"icon icon-scissors-white icon--sm","aria-hidden":"true"})}),v.copy&&/* @__PURE__ */s("button",{type:"button",title:w?"¡Copiado!":"Copiar URL",className:"limbo-action-btn limbo-btn-copy lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:border lb:border-brand-blue-1000 "+(Q?"lb:btn--touch":""),onClick:le,tabIndex:-1,style:{...Q&&{width:"40px",height:"40px"}},children:/* @__PURE__ */s("span",{className:`icon ${w?"icon-copied-white":"icon-copy-white"} icon--sm`,"aria-hidden":"true"})}),v.download&&/* @__PURE__ */s("button",{type:"button",title:"Descargar",className:"limbo-action-btn limbo-btn-download lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:border lb:border-brand-blue-1000 "+(Q?"lb:btn--touch":""),onClick:re,tabIndex:-1,style:{...Q&&{width:"40px",height:"40px"}},children:/* @__PURE__ */s("span",{className:"icon icon-download-white icon--sm","aria-hidden":"true"})}),p&&d&&/* @__PURE__ */s("button",{type:"button",title:l.folder?`Mover de carpeta (${l.folder?.name||l.folder?.slug||""})`:"Asignar a carpeta",className:"limbo-action-btn limbo-btn-folder lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:border lb:border-brand-blue-1000 "+(Q?"lb:btn--touch":""),onClick:e=>{e.stopPropagation(),T(!z)},tabIndex:-1,style:{...Q&&{width:"40px",height:"40px"}},children:/* @__PURE__ */s("span",{className:"icon icon-folder-white icon--sm","aria-hidden":"true"})}),v.delete&&r&&/* @__PURE__ */s("button",{onClick:Z,disabled:m,className:"limbo-action-btn limbo-btn-delete lb:bg-red-800 lb:hover:bg-red-700 lb:border lb:border-red-700 "+(Q?"lb:btn--touch lb:active:lb:bg-red-800":""),title:"Eliminar archivo",tabIndex:-1,style:{...Q&&{width:"40px",height:"40px"}},children:m?"…":/* @__PURE__ */s("span",{className:"icon icon-close-small-white icon--sm","aria-hidden":"true"})})]}),z&&p&&d&&/* @__PURE__ */s("div",{className:"limbo-image-actions__folder",onClick:e=>e.stopPropagation(),children:/* @__PURE__ */s(ge,{value:l.folder?.slug||null,onChange:async e=>{if(!M){P(!0);try{const t=e?.slug||null;await(d?.(l,t)),he(),Y?.announce(e?`${l.filename} movido a carpeta ${e.name}`:`${l.filename} movido a Sin carpeta`)}catch(t){console.error("Error moving to folder:",t),Y?.announce(`Error al mover ${l.filename}`)}finally{P(!1),T(!1)}}},allowCreate:y,placeholder:"Sin carpeta",label:"Mover a carpeta",includeNoFolder:!0,allowedSlugs:f,excludeSlugs:g,disabled:M,mode:"upload"})})]}),
117
+ /* @__PURE__ */c("div",{className:"limbo-image-actions__buttons",children:[(be||!O)&&/* @__PURE__ */s("button",{type:"button",title:ie?`Ver ${oe} recortes`:O?"Ampliar imagen":"Previsualizar archivo",className:"limbo-action-btn lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:border lb:border-brand-blue-1000 "+(Q?"lb:btn--touch":""),onClick:e=>{e?.stopPropagation(),ie?(Y?.announce(`Mostrando recortes de ${l.filename}`),C(!0)):(Y?.announce(`Abriendo visor de ${l.filename}`),S(!0))},tabIndex:-1,style:{...Q&&{width:"40px",height:"40px"}},children:/* @__PURE__ */s("span",{className:`icon ${O?"icon-zoom-in-white":"icon-search-white"} icon--sm`,"aria-hidden":"true"})}),me&&/* @__PURE__ */s("button",{type:"button",title:"Editar imagen",className:"limbo-action-btn limbo-btn-crop lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:border lb:border-brand-blue-1000 "+(Q?"lb:btn--touch":""),onClick:ae,tabIndex:-1,style:{...Q&&{width:"40px",height:"40px"}},children:/* @__PURE__ */s("span",{className:"icon icon-scissors-white icon--sm","aria-hidden":"true"})}),v.copy&&/* @__PURE__ */s("button",{type:"button",title:w?"¡Copiado!":"Copiar URL",className:"limbo-action-btn limbo-btn-copy lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:border lb:border-brand-blue-1000 "+(Q?"lb:btn--touch":""),onClick:le,tabIndex:-1,style:{...Q&&{width:"40px",height:"40px"}},children:/* @__PURE__ */s("span",{className:`icon ${w?"icon-copied-white":"icon-copy-white"} icon--sm`,"aria-hidden":"true"})}),v.download&&/* @__PURE__ */s("button",{type:"button",title:"Descargar",className:"limbo-action-btn limbo-btn-download lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:border lb:border-brand-blue-1000 "+(Q?"lb:btn--touch":""),onClick:re,tabIndex:-1,style:{...Q&&{width:"40px",height:"40px"}},children:/* @__PURE__ */s("span",{className:"icon icon-download-white icon--sm","aria-hidden":"true"})}),p&&d&&/* @__PURE__ */s("button",{type:"button",title:l.folder?`Mover de carpeta (${l.folder?.name||l.folder?.slug||""})`:"Asignar a carpeta",className:"limbo-action-btn limbo-btn-folder lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:border lb:border-brand-blue-1000 "+(Q?"lb:btn--touch":""),onClick:e=>{e.stopPropagation(),T(!z)},tabIndex:-1,style:{...Q&&{width:"40px",height:"40px"}},children:/* @__PURE__ */s("span",{className:"icon icon-folder-white icon--sm","aria-hidden":"true"})}),v.delete&&r&&/* @__PURE__ */s("button",{onClick:Z,disabled:m,className:"limbo-action-btn limbo-btn-delete lb:bg-red-800 lb:hover:bg-red-700 lb:border lb:border-red-700 "+(Q?"lb:btn--touch lb:active:lb:bg-red-800":""),title:"Eliminar archivo",tabIndex:-1,style:{...Q&&{width:"40px",height:"40px"}},children:m?"…":/* @__PURE__ */s("span",{className:"icon icon-close-small-white icon--sm","aria-hidden":"true"})})]}),z&&p&&d&&/* @__PURE__ */s("div",{className:"limbo-image-actions__folder",onClick:e=>e.stopPropagation(),children:/* @__PURE__ */s(ge,{value:l.folder?.slug||null,onChange:async e=>{if(!M){P(!0);try{const t=e?.slug||null;await(d?.(l,t)),he(),Y?.announce(e?`${l.filename} movido a carpeta ${e.name}`:`${l.filename} movido a Sin carpeta`)}catch(t){console.error("Error moving to folder:",t),Y?.announce(`Error al mover ${l.filename}`)}finally{P(!1),T(!1)}}},allowCreate:y,placeholder:"Sin carpeta",label:"Mover a carpeta",includeNoFolder:!0,allowedSlugs:f,excludeSlugs:g,disabled:M,mode:"upload"})})]}),
118
118
  /* @__PURE__ */c("div",{className:"limbo-image-card "+(Q?"limbo-image-card--mobile":""),children:[!O&&(l.thumbnail_url?
119
119
  /* @__PURE__ */c("div",{className:"lb:relative lb:w-full lb:h-full lb:rounded lb:overflow-hidden lb:border lb:border-neutral-300",style:{...Q&&{minHeight:`${Math.max(3*b,80)}px`}},children:[
120
120
  /* @__PURE__ */s("img",{src:l.thumbnail_url,alt:l.filename,className:"lb:w-full lb:h-full lb:object-cover lb:aspect-square",loading:"lazy",decoding:"async",draggable:!1,onError:e=>{e.target.style.display="none",e.target.nextElementSibling?.classList.remove("lb:hidden")}}),
@@ -135,8 +135,8 @@ return c("div",{className:"limbo-image-card lb:animate-pulse",role:"status","ari
135
135
  /* @__PURE__ */s("div",{className:"lb:w-full lb:aspect-square lb:bg-neutral-gray-200 lb:rounded-md lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-spinner"})}),
136
136
  /* @__PURE__ */s("div",{className:"limbo-image-card-name lb:opacity-100 lb:position-relative lb:bottom-0 lb:p-2",children:/* @__PURE__ */s("div",{className:"lb:h-4 lb:bg-neutral-gray-200 lb:rounded lb:w-3/4"})}),
137
137
  /* @__PURE__ */s("span",{className:"lb:sr-only",children:"Cargando imágen..."})]})}const xe=[{value:"",label:"Todos los tipos"},{value:"image",label:"Imágenes"},{value:"video",label:"Videos"},{value:"document",label:"Documentos"},{value:"audio",label:"Audio"}];function ke({onSelect:e,onCrop:l,onDelete:a,deletingId:o,images:u,loading:d,error:b,filters:m={name:"",dateFrom:"",dateTo:"",uploadedBy:"",assetType:"",folder:""},debouncedFilters:h=null,onFiltersChange:p,filterConfig:f={showNameFilter:!0,showUploadedByFilter:!1,showDateFilter:!0,showTypeFilter:!1},loadingConfig:g={showPlaceholders:!0,placeholderCount:10,showSpinner:!0},allowedActions:y={select:!0,download:!0,copy:!0,delete:!0,crop:!0,variants:!0},allowedCategories:v=null,folderConfig:w=null,onFolderChange:x=null}){const{isSearching:k,searchPending:C}=function(e,l,a){const[i,o]=t(!1),s=r(null);return n(()=>(Object.keys(e).some(t=>e[t]!==l[t])?s.current=setTimeout(()=>{o(!0)},150):(s.current&&clearTimeout(s.current),o(!1)),()=>{s.current&&clearTimeout(s.current)}),[e,l]),{isSearching:i||a,searchPending:i}}(m,h||m,d),N=!1!==f.showNameFilter,S=!0===f.showUploadedByFilter,E=!1!==f.showDateFilter,$=!0===f.showTypeFilter,_=!0===w?.showFolderFilter,z=w?.include?.length>0?w.include:null,T=w?.exclude?.length>0?w.exclude:null,I=!1!==w?.showFolderInfo,A=!1!==w?.allowMoveFolder&&!!x,L=!0===w?.allowCreateFolder,P=v?xe.filter(e=>""===e.value||v.includes(e.value)):xe,D=r(null),O=window.limboCore?.accessibilityManager;n(()=>{if(D.current&&window.limboCore?.keyboardManager){const e="gallery-grid";D.current.setAttribute("data-grid-id",e),window.limboCore.keyboardManager.setupGridNavigation(D.current,{itemSelector:".limbo-image-card",gridId:e,columns:"auto"})}},[u]),n(()=>{if(!d&&u.length>0){const e=u.slice(0,12).map(e=>e.url||e.path).filter(Boolean);e.length>0&&M(e,4)}},[d,u]);const R=i(()=>{if(!m.assetType)return"archivos";return{image:"imágenes",video:"videos",document:"documentos",audio:"archivos de audio"}[m.assetType]||"archivos"},[m.assetType]);n(()=>{d?O?.announceLoading(!0,"galería"):d||b?b&&O?.announceError(b,"galería"):(O?.announceLoading(!1,"galería"),u.length>0&&O?.announce(`Se encontraron ${u.length} ${R} en la galería`))},[d,b,u.length,O,R]),n(()=>{C&&O?.announce("Buscando...","polite")},[C,O]);const F=e=>{const{name:t,value:n}=e.target;p&&p({...m,[t]:n})},j=m.name||m.dateFrom||m.dateTo||m.uploadedBy||m.assetType||m.folder,U=k&&u.length>0&&!d;/* @__PURE__ */
138
- return c("div",{className:"lb:w-full lb:py-2",children:[
139
- /* @__PURE__ */s("div",{className:"lb:px-2 lb:mb-3 lb:mx-2 lb:w-max lb:max-w-full",children:/* @__PURE__ */c("form",{className:"limbo-filters lb:flex lb:items-stretch lb:content-stretch lb:flex-row",onSubmit:e=>e.preventDefault(),role:"search","aria-label":"Filtrar archivos",children:[N&&/* @__PURE__ */c("div",{className:"limbo-filter-group limbo-filter-group--name",children:[
138
+ return c("div",{className:"lb:w-full lb:max-w-full lb:py-2 lb:overflow-x-hidden lb:box-border",children:[
139
+ /* @__PURE__ */s("div",{className:"lb:px-2 lb:mb-3 lb:mx-2 lb:max-w-full lb:overflow-x-hidden lb:box-border",children:/* @__PURE__ */c("form",{className:"limbo-filters lb:flex lb:items-stretch lb:content-stretch lb:flex-row",onSubmit:e=>e.preventDefault(),role:"search","aria-label":"Filtrar archivos",children:[N&&/* @__PURE__ */c("div",{className:"limbo-filter-group limbo-filter-group--name",children:[
140
140
  /* @__PURE__ */c("label",{htmlFor:"name",className:"limbo-filter-label",children:["Nombre",C&&/* @__PURE__ */s("span",{className:"limbo-filter-searching","aria-hidden":"true",children:/* @__PURE__ */s("span",{className:"icon icon-spinner lb:animate-spin lb:w-3 lb:h-3"})})]}),
141
141
  /* @__PURE__ */s("input",{type:"text",name:"name",id:"name",placeholder:"Buscar...",value:m.name,onChange:F,className:"limbo-filter-input",autoComplete:"off"})]}),E&&/* @__PURE__ */c("div",{className:"limbo-filter-dates",children:[
142
142
  /* @__PURE__ */c("div",{className:"limbo-filter-group limbo-filter-group--date",children:[
@@ -158,7 +158,7 @@ return c("div",{className:"lb:w-full lb:py-2",children:[
158
158
  /* @__PURE__ */c("span",{className:"lb:text-sm lb:text-gray-600 lb:font-medium",children:["Cargando ",R,"..."]})]})}),g.showPlaceholders&&/* @__PURE__ */s("div",{ref:D,className:"limbo-gallery lb:opacity-30","data-limbo-responsive":!0,role:"grid","aria-label":`Cargando ${R} de la galería`,"aria-busy":"true",children:Array.from({length:g.placeholderCount}).map((e,t)=>/* @__PURE__ */s("div",{role:"gridcell","aria-posinset":t+1,"aria-setsize":g.placeholderCount,className:"lb:min-w-0",children:/* @__PURE__ */s(we,{})},`skeleton-${t}`))})]}):b?/* @__PURE__ */s("div",{className:"alert alert-danger lb:text-center",children:b}):/* @__PURE__ */c("div",{className:"lb:relative",children:[U&&/* @__PURE__ */s("div",{className:"limbo-search-overlay",role:"status","aria-live":"polite","aria-label":"Buscando archivos",children:/* @__PURE__ */c("div",{className:"limbo-search-overlay__content",children:[
159
159
  /* @__PURE__ */s("span",{className:"icon icon-spinner lb:animate-spin"}),
160
160
  /* @__PURE__ */s("span",{children:"Buscando..."})]})}),
161
- /* @__PURE__ */s("div",{ref:D,className:"limbo-gallery lb:px-3 "+(U?"lb:opacity-50 lb:pointer-events-none":""),"data-limbo-responsive":!0,"data-grid-id":"gallery-grid",role:"grid","aria-label":`Galería de ${R}. Use las flechas para navegar`,"aria-busy":U,children:u.length>0?u.map((t,n)=>/* @__PURE__ */s("div",{role:"gridcell","aria-posinset":n+1,"aria-setsize":u.length,className:"lb:min-w-0",children:/* @__PURE__ */s(ve,{image:t,onSelect:e,onCrop:l,onDelete:y.delete&&a?()=>a(t.id):null,onFolderChange:x,thumbnailSize:32,isDeleting:o===t.id,showFolderInfo:I,allowMoveFolder:A,allowedFolderSlugs:z,excludedFolderSlugs:T,allowCreateFolder:L,allowedActions:y})},t.id)):/* @__PURE__ */s("div",{className:"lb:col-span-full lb:text-center lb:text-gray-500 lb:py-8",role:"status","aria-live":"polite",children:/* @__PURE__ */c("p",{children:["No se han encontrado ",R]})})})]})]})}function Ce({previewUrl:e,fileName:n}){const[l,a]=t(!1),[i,o]=t(!1),u=r(null);/* @__PURE__ */
161
+ /* @__PURE__ */s("div",{ref:D,className:"limbo-gallery lb:px-3 lb:pt-11 lb:box-border lb:max-w-full "+(U?"lb:opacity-50 lb:pointer-events-none":""),"data-limbo-responsive":!0,"data-grid-id":"gallery-grid",role:"grid","aria-label":`Galería de ${R}. Use las flechas para navegar`,"aria-busy":U,children:u.length>0?u.map((t,n)=>/* @__PURE__ */s("div",{role:"gridcell","aria-posinset":n+1,"aria-setsize":u.length,className:"lb:min-w-0",children:/* @__PURE__ */s(ve,{image:t,onSelect:e,onCrop:l,onDelete:y.delete&&a?()=>a(t.id):null,onFolderChange:x,thumbnailSize:32,isDeleting:o===t.id,showFolderInfo:I,allowMoveFolder:A,allowedFolderSlugs:z,excludedFolderSlugs:T,allowCreateFolder:L,allowedActions:y})},t.id)):/* @__PURE__ */s("div",{className:"lb:col-span-full lb:text-center lb:text-gray-500 lb:py-8",role:"status","aria-live":"polite",children:/* @__PURE__ */c("p",{children:["No se han encontrado ",R]})})})]})]})}function Ce({previewUrl:e,fileName:n}){const[l,a]=t(!1),[i,o]=t(!1),u=r(null);/* @__PURE__ */
162
162
  return c("div",i?{className:"lb:flex lb:flex-col lb:items-center lb:justify-center lb:p-8 lb:min-h-[200px] lb:bg-gray-100 lb:rounded-lg",children:[
163
163
  /* @__PURE__ */s("span",{className:"icon icon-video icon--xl lb:text-gray-400 lb:mb-4"}),
164
164
  /* @__PURE__ */s("p",{className:"lb:text-sm lb:text-gray-600",children:"No se puede reproducir el video"}),
@@ -183,7 +183,7 @@ return c("div",o?{className:"lb:flex lb:flex-col lb:items-center lb:justify-cent
183
183
  /* @__PURE__ */s("span",{children:ie(l)})]})]}),
184
184
  /* @__PURE__ */s("div",{className:"lb:w-full lb:max-w-xs lb:mt-3",children:/* @__PURE__ */s("div",{className:"lb:h-1.5 lb:bg-gray-200 lb:rounded-full lb:overflow-hidden",children:/* @__PURE__ */s("div",{className:"lb:h-full lb:bg-purple-500 lb:rounded-full lb:transition-all lb:duration-100",style:{width:b>0?h/b*100+"%":"0%"}})})}),
185
185
  /* @__PURE__ */s("audio",{ref:f,src:e,onPlay:()=>i(!0),onPause:()=>i(!1),onTimeUpdate:()=>{f.current&&p(f.current.currentTime)},onLoadedMetadata:()=>{f.current&&m(f.current.duration)},onEnded:()=>{i(!1),p(0)},onError:()=>{d(!0)},preload:"metadata"})]})}function Se({file:e,image:l,onDiscard:r,onRetry:a,onDownload:i,onSelect:o,showRetry:u=!1,disabled:d=!1,showCropButton:b,selectedFolder:m=null,onFolderChange:h=null,folderConfig:p=null}){const f=e||l,[g,y]=t(null),[v,w]=t({name:"",size:"",type:"",category:"unknown"}),[x,k]=t(!1),[C,N]=t(!1),[S,E]=t(""),$="image"===v.category,_="video"===v.category,z="audio"===v.category,T=void 0!==b?b:$;n(()=>{if(!f)return void y(null);const e=URL.createObjectURL(f);y(e);const t=f.name||"archivo",n=f.type||"",l=(e=>e?e.startsWith("image/")?"image":e.startsWith("video/")?"video":e.startsWith("audio/")?"audio":"application/pdf"===e||e.includes("document")||e.includes("msword")||e.includes("spreadsheet")||e.includes("presentation")||e.startsWith("text/")?"document":"unknown":"unknown")(n),r=(e=>{const t=e?.split(".")[0]?.toLowerCase()||"";return["ai-image","ai_image","generated","imagen-ia","imagen_ia"].some(e=>t.startsWith(e))})(t);if(w({name:t,size:ie(f.size||0),type:n,category:l}),r)E(""),N(!1);else{const e=t.split(".")[0];E(e)}return()=>{URL.revokeObjectURL(e)}},[f]);if(!f||!g)return null;/* @__PURE__ */
186
- return c("div",{className:"lb:w-fit lb:md:w-full lb:bg-white lb:border lb:border-gray-200 lb:rounded-lg lb:px-1 lb:sm:px-3 lb:py-2 lb:m-0 lb:shadow-sm",children:[
186
+ return c("div",{className:"lb:w-full lb:max-w-full lb:bg-white lb:border lb:border-gray-200 lb:rounded-lg lb:px-1 lb:sm:px-3 lb:py-2 lb:m-0 lb:shadow-sm lb:overflow-hidden lb:box-border",children:[
187
187
  /* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:justify-between lb:mb-4 lb:px-1",children:[
188
188
  /* @__PURE__ */s("h3",{className:"lb:text-sm lb:font-medium lb:text-gray-700",children:(()=>{switch(v.category){case"image":return"Vista previa de imagen";case"video":return"Vista previa de video";case"audio":return"Vista previa de audio";case"document":return"Vista previa de documento";default:return"Vista previa de archivo"}})()}),
189
189
  /* @__PURE__ */s("button",{type:"button",onClick:r,disabled:d,className:"lb:p-1.5 lb:text-gray-400 lb:cursor-pointer lb:hover:text-gray-600 lb:hover:bg-red-300 lb:rounded lb:transition-colors lb:disabled:opacity-50 lb:disabled:cursor-not-allowed","aria-label":"Descartar archivo",title:"Descartar archivo",children:/* @__PURE__ */s("span",{className:"icon icon-close-small icon--md"})})]}),
@@ -212,14 +212,14 @@ return c("div",{className:"lb:w-fit lb:md:w-full lb:bg-white lb:border lb:border
212
212
  /* @__PURE__ */s("span",{className:"icon icon-tick-white icon--sm"}),
213
213
  /* @__PURE__ */s("span",{children:"Seleccionar"})]})]})]})]})}),$&&/* @__PURE__ */s(ce,{isOpen:x,src:g,alt:v.name,title:v.name,subtitle:`${v.size} • ${v.type.split("/")[1]?.toUpperCase()||"IMAGE"}`,onClose:()=>k(!1)})]})}const Ee={image:["image/jpeg","image/png","image/gif","image/webp","image/svg+xml"],video:["video/mp4","video/webm","video/quicktime","video/x-msvideo"],document:["application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","text/plain","text/csv"],audio:["audio/mpeg","audio/wav","audio/ogg","audio/webm"]},$e={image:"JPG, PNG, GIF, SVG, WebP",video:"MP4, WebM, MOV, AVI",document:"PDF, DOC, DOCX, XLS, XLSX, TXT",audio:"MP3, WAV, OGG"},_e=["image","video","document","audio"];function ze({file:e,setFile:n,previewUrl:l,setPreviewUrl:r,fileInputRef:a,onSelect:o,disabled:u,allowedCategories:d=null,selectedFolder:b=null,onFolderChange:m=null,folderConfig:h=null}){const[p,f]=t(!1),{acceptAttribute:g,allowedMimeTypes:y,formatLabels:v,categories:w}=i(()=>{const e=null===d?_e:d,t=[],n=[];return e.forEach(e=>{Ee[e]&&(t.push(...Ee[e]),$e[e]&&n.push($e[e]))}),{acceptAttribute:t.join(","),allowedMimeTypes:new Set(t),formatLabels:n.join(", "),categories:e}},[d]),x=1===w.length&&"image"===w[0],k=e=>{if(n(e),e){const t=URL.createObjectURL(e);r(t)}else r(null)};/* @__PURE__ */
214
214
  return c("div",{className:"lb:flex lb:flex-col lb:items-center lb:gap-6","aria-label":x?"Subir imagen desde dispositivo":"Subir archivo desde dispositivo",children:[
215
- /* @__PURE__ */c("label",{htmlFor:"file-input",className:"lb:w-fit lb:md:w-full lb:flex lb:flex-col lb:items-center lb:justify-center lb:border-2 lb:border-dashed lb:rounded-xl lb:p-8 lb:cursor-pointer lb:transition "+(p?"lb:border-brand-blue-1000 lb:bg-brand-blue-100 lb:scale-[1.02]":"lb:border-brand-blue-200 lb:hover:border-brand-blue-1000 lb:hover:to-bright-blue-200 lb:hover:from-brand-blue-50 lb:focus-within:border-brand-blue-800 lb:from-bright-blue-50 lb:to-brand-blue-50 lb:bg-linear-to-br"),tabIndex:0,style:{outline:"none"},onDragOver:e=>{e.preventDefault(),e.stopPropagation()},onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),u||f(!0)},onDragLeave:e=>{e.preventDefault(),e.stopPropagation(),e.currentTarget.contains(e.relatedTarget)||f(!1)},onDrop:e=>{if(e.preventDefault(),e.stopPropagation(),f(!1),u)return;const t=e.dataTransfer?.files;if(t&&t.length>0){const e=t[0];(e=>{if(!e||!e.type)return!1;if(y.has(e.type))return!0;for(const t of w)if("image"===t&&e.type.startsWith("image/")||"video"===t&&e.type.startsWith("video/")||"audio"===t&&e.type.startsWith("audio/"))return!0;return!1})(e)&&k(e)}},children:[
215
+ /* @__PURE__ */c("label",{htmlFor:"file-input",className:"lb:w-full lb:max-w-full lb:flex lb:flex-col lb:items-center lb:justify-center lb:border-2 lb:border-dashed lb:rounded-xl lb:p-8 lb:cursor-pointer lb:transition lb:box-border "+(p?"lb:border-brand-blue-1000 lb:bg-brand-blue-100 lb:scale-[1.02]":"lb:border-brand-blue-200 lb:hover:border-brand-blue-1000 lb:hover:to-bright-blue-200 lb:hover:from-brand-blue-50 lb:focus-within:border-brand-blue-800 lb:from-bright-blue-50 lb:to-brand-blue-50 lb:bg-linear-to-br"),tabIndex:0,style:{outline:"none"},onDragOver:e=>{e.preventDefault(),e.stopPropagation()},onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),u||f(!0)},onDragLeave:e=>{e.preventDefault(),e.stopPropagation(),e.currentTarget.contains(e.relatedTarget)||f(!1)},onDrop:e=>{if(e.preventDefault(),e.stopPropagation(),f(!1),u)return;const t=e.dataTransfer?.files;if(t&&t.length>0){const e=t[0];(e=>{if(!e||!e.type)return!1;if(y.has(e.type))return!0;for(const t of w)if("image"===t&&e.type.startsWith("image/")||"video"===t&&e.type.startsWith("video/")||"audio"===t&&e.type.startsWith("audio/"))return!0;return!1})(e)&&k(e)}},children:[
216
216
  /* @__PURE__ */s("span",{className:"icon icon-upload icon--lg lb:mb-2","aria-hidden":"true"}),
217
217
  /* @__PURE__ */s("span",{className:"lb:font-medium lb:text-brand-blue-1000 lb:mb-1",children:x?"Haz clic o arrastra una imagen aqui":"Haz clic o arrastra un archivo aqui"}),
218
218
  /* @__PURE__ */c("span",{className:"lb:text-sm lb:text-neutral-700",children:["Formatos permitidos: ",
219
219
  /* @__PURE__ */s("span",{className:"lb:truncate lb:wrap-",children:v})]}),
220
220
  /* @__PURE__ */s("input",{id:"file-input",ref:a,type:"file",accept:g,onChange:e=>{const t=e.target.files[0];k(t)},disabled:u,className:"lb:sr-only","aria-label":x?"Seleccionar imagen":"Seleccionar archivo"})]}),e&&/* @__PURE__ */s(Se,{file:e,onDiscard:()=>{n(null),r(null),a.current&&(a.current.value="")},onDownload:()=>{},onSelect:t=>{if(e&&!u&&o)if(t&&t!==e.name){const n=new File([e],t,{type:e.type});o(n)}else o(e)},showRetry:!1,disabled:u,selectedFolder:b,onFolderChange:m,folderConfig:h})]})}const Te="/api";const Ie=/* @__PURE__ */new Map;function Ae(e=!1){const[l,r]=t([]),[a,i]=t(!0),[o,s]=t(null);n(()=>{const t=`ai-services-${e}`,n=Ie.get(t),l=Date.now();if(n&&l-n.timestamp<864e5)return r(n.data),void i(!1);let a=!0;return(async()=>{try{const n=await function(e=!1){return j({endpoint:"/ai/services",prod:e,basePath:Te})}(e);if(!a)return;const i=n?.data||n?.result||[],o=Array.isArray(i)?i.map(e=>({label:e.name||e.label,slug:e.slug,type:e.type,description:e.description,image:e.image,costInfo:e.cost_info||null,supportsImageInput:e.supports_image_input||!1})):Object.entries(i).map(([e,t])=>({label:e,slug:t,type:"image_generation",description:null,image:null,costInfo:null,supportsImageInput:!1}));r(o),Ie.set(t,{data:o,timestamp:l})}catch(n){a&&s(n.message)}finally{a&&i(!1)}})(),()=>{a=!1}},[e]);return{services:l,loading:a,error:o,invalidateCache:()=>{Ie.delete(`ai-services-${e}`)}}}const Le=/* @__PURE__ */new Map;function Me(e=!1){const[n,l]=t(null),[r,a]=t(!1),[i,o]=t(null);return{params:n,loading:r,error:i,fetchParams:async t=>{a(!0),o(null);const n=`${e}-${t}`,r=Date.now(),i=Le.get(n);if(i&&r-i.timestamp<864e5)return l(i.data),a(!1),i.data;try{const a=await function({services:e=null,form:t=!1}={},n=!1){const l={};return e&&(l.services=e),!1!==t&&(l.form=t),j({endpoint:"/ai/params"+(Object.keys(l).length?"?"+new URLSearchParams(l).toString():""),method:"GET",prod:n,basePath:"/api/atenea"})}({services:t,form:!1},e),i=a?.result?.data||a?.data||a?.result||a;return l(i),Le.set(n,{data:i,timestamp:r}),i}catch(s){return o(s.message),l(null),null}finally{a(!1)}},reset:()=>{o(null),l(null)}}}function Pe({show:e=!1,message:t="Cargando...",className:n=""}){return e?/* @__PURE__ */s("div",{className:`lb:absolute lb:inset-0 lb:min-h-50 lb:bg-white/80 lb:backdrop-blur-sm lb:z-50 lb:flex lb:flex-col lb:items-center lb:justify-center ${n}`,"aria-live":"polite","aria-busy":"true",role:"status",children:/* @__PURE__ */c("div",{className:"lb:flex lb:flex-col lb:items-center lb:gap-4",children:[
221
221
  /* @__PURE__ */s("span",{className:"icon icon-spinner lb:p-4 lb:animate-spin"}),
222
- /* @__PURE__ */s("p",{className:"lb:text-brand-blue-1000 lb:font-medium lb:text-lg",children:t})]})}):null}function De({image:e,onDiscard:l,onRetry:r,onDownload:a,onSelect:i,showRetry:o=!1,disabled:u=!1,selectedFolder:d=null,onFolderChange:b=null,folderConfig:m=null}){const[h,p]=t(null),[f,g]=t({name:"",size:"",type:""}),[y,v]=t(!1),[w,x]=t(!1),[k,C]=t("");n(()=>{if(!e)return void p(null);const t=URL.createObjectURL(e);p(t);const n=e.name||"imagen.webp",l=(e=>{const t=e?.split(".")[0]?.toLowerCase()||"";return["ai-image","ai_image","generated","imagen-ia","imagen_ia"].some(e=>t.startsWith(e))})(n);return g({name:n,size:N(e.size||0),type:e.type||"image/webp"}),l?(C(""),x(!1)):C(n.split(".")[0]),()=>{URL.revokeObjectURL(t)}},[e]);const N=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&&h?/* @__PURE__ */c("div",{className:"lb:w-fit lb:md:w-full lb:bg-white lb:border lb:border-gray-200 lb:rounded-lg lb:px-1 lb:sm:px-3 lb:py-2 lb:m-0 lb:shadow-sm",children:[
222
+ /* @__PURE__ */s("p",{className:"lb:text-brand-blue-1000 lb:font-medium lb:text-lg",children:t})]})}):null}function De({image:e,onDiscard:l,onRetry:r,onDownload:a,onSelect:i,showRetry:o=!1,disabled:u=!1,selectedFolder:d=null,onFolderChange:b=null,folderConfig:m=null}){const[h,p]=t(null),[f,g]=t({name:"",size:"",type:""}),[y,v]=t(!1),[w,x]=t(!1),[k,C]=t("");n(()=>{if(!e)return void p(null);const t=URL.createObjectURL(e);p(t);const n=e.name||"imagen.webp",l=(e=>{const t=e?.split(".")[0]?.toLowerCase()||"";return["ai-image","ai_image","generated","imagen-ia","imagen_ia"].some(e=>t.startsWith(e))})(n);return g({name:n,size:N(e.size||0),type:e.type||"image/webp"}),l?(C(""),x(!1)):C(n.split(".")[0]),()=>{URL.revokeObjectURL(t)}},[e]);const N=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&&h?/* @__PURE__ */c("div",{className:"lb:w-full lb:max-w-full lb:bg-white lb:border lb:border-gray-200 lb:rounded-lg lb:px-1 lb:sm:px-3 lb:py-2 lb:m-0 lb:shadow-sm lb:overflow-hidden lb:box-border",children:[
223
223
  /* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:justify-between lb:mb-4 lb:px-1",children:[
224
224
  /* @__PURE__ */s("h3",{className:"lb:text-sm lb:font-medium lb:text-gray-700",children:"Vista previa de imagen"}),
225
225
  /* @__PURE__ */s("button",{type:"button",onClick:l,disabled:u,className:"lb:p-1.5 lb:text-gray-400 lb:cursor-pointer lb:hover:text-gray-600 lb:hover:bg-red-300 lb:rounded lb:transition-colors lb:disabled:opacity-50 lb:disabled:cursor-not-allowed","aria-label":"Descartar imagen",title:"Descartar imagen",children:/* @__PURE__ */s("span",{className:"icon icon-close-small icon--md"})})]}),m?.showFolderSelector&&b&&/* @__PURE__ */s("div",{className:"lb:mb-4 lb:px-1",children:/* @__PURE__ */s(ge,{value:d?.slug||d,onChange:b,allowCreate:!1!==m?.allowCreateFolder,label:"Guardar en carpeta",showAssetCount:!0,allowedSlugs:m?.include?.length>0?m.include:null,mode:"upload",disabled:u})}),
@@ -372,7 +372,7 @@ return c("button",{type:"button",onClick:()=>{return t=e.id,void f(e=>e.includes
372
372
  return c("div",{className:"limbo-upload-form lb:py-4 lb:min-w-fit lb:max-w-7xl lb:mx-auto",children:[
373
373
  /* @__PURE__ */s("div",{className:x,role:"tablist","aria-label":"Opciones de subida",style:b?{WebkitOverflowScrolling:"touch",scrollbarWidth:"none",msOverflowStyle:"none"}:void 0,children:Ke.map(e=>{const t=h===e.id;/* @__PURE__ */
374
374
  return c("button",{type:"button","data-upload-tab-id":e.id,className:k(t),"aria-current":t?"page":void 0,"aria-selected":t,role:"tab",tabIndex:t?0:-1,onClick:()=>p(e.id),onKeyDown:t=>((e,t)=>{const n=Ke.findIndex(e=>e.id===t);let l=n;switch(e.key){case"ArrowLeft":e.preventDefault(),l=n>0?n-1:Ke.length-1;break;case"ArrowRight":e.preventDefault(),l=n<Ke.length-1?n+1:0;break;case"Home":e.preventDefault(),l=0;break;case"End":e.preventDefault(),l=Ke.length-1;break;case"Enter":case" ":return e.preventDefault(),void p(t);default:return}const r=Ke[l];r&&(p(r.id),setTimeout(()=>{const e=document.querySelector(`[data-upload-tab-id="${r.id}"]`);e&&e.focus()},0))})(t,e.id),id:`upload-tab-${e.id}`,"aria-controls":`upload-tabpanel-${e.id}`,style:m?{WebkitTapHighlightColor:"transparent"}:void 0,children:["ai"===e.id?/* @__PURE__ */s("span",{className:"icon icon-ia lb:me-1"}):null,e.label]},e.id)})}),
375
- /* @__PURE__ */c("div",{className:"limbo-tab-content lb:px-2 lb:py-2",role:"tabpanel",id:`upload-tabpanel-${h}`,"aria-labelledby":`upload-tab-${h}`,children:["upload"===h&&/* @__PURE__ */s(ze,{file:f,setFile:g,previewUrl:y,setPreviewUrl:v,fileInputRef:w,onSelect:e,disabled:n,allowedCategories:i,selectedFolder:u,onFolderChange:d,folderConfig:o}),"ai"===h&&/* @__PURE__ */s(Oe,{apiKey:l,prod:a,disabled:n,onSelect:e,selectedFolder:u,onFolderChange:d,folderConfig:o}),"stock"===h&&/* @__PURE__ */s(Ue,{apiKey:l,prod:a,disabled:n,onSelect:e,selectedFolder:u,onFolderChange:d,folderConfig:o}),"portals"===h&&/* @__PURE__ */s(He,{apiKey:l,prod:a,disabled:n,onSelect:e,selectedFolder:u,onFolderChange:d,folderConfig:o})]})]})}const Qe="undefined"!=typeof window&&void 0!==window.document,Xe=Qe?window:{},Ye=!!Qe&&"ontouchstart"in Xe.document.documentElement,Je=!!Qe&&"PointerEvent"in Xe,Ze="cropper",et=`${Ze}-canvas`,tt=`${Ze}-crosshair`,nt=`${Ze}-grid`,lt=`${Ze}-handle`,rt=`${Ze}-image`,at=`${Ze}-selection`,it=`${Ze}-shade`,ot=`${Ze}-viewer`,st="select",ct="move",ut="scale",dt="rotate",bt="transform",mt="none",ht="n-resize",pt="e-resize",ft="s-resize",gt="w-resize",yt="ne-resize",vt="nw-resize",wt="se-resize",xt="sw-resize",kt=Je?"pointerdown":Ye?"touchstart":"mousedown",Ct=Je?"pointermove":Ye?"touchmove":"mousemove",Nt=Je?"pointerup pointercancel":Ye?"touchend touchcancel":"mouseup",St="error",Et="keydown",$t="load",_t="wheel",zt="action",Tt="actionend",It="actionstart",At="change",Lt="transform";const Mt=Number.isNaN||Xe.isNaN;function Pt(e){return"number"==typeof e&&!Mt(e)}function Dt(e){return Pt(e)&&e>0&&e<1/0}function Ot(e){return"object"==typeof e&&null!==e}const{hasOwnProperty:Rt}=Object.prototype;function Ft(e){if(!Ot(e))return!1;try{const{constructor:t}=e,{prototype:n}=t;return t&&n&&Rt.call(n,"isPrototypeOf")}catch(t){return!1}}function jt(e){return"function"==typeof e}function Ut(e){return"object"==typeof e&&null!==e&&1===e.nodeType}const Bt=/([a-z\d])([A-Z])/g;function qt(e){return String(e).replace(Bt,"$1-$2").toLowerCase()}const Wt=/-[A-z\d]/g;function Vt(e){return e.replace(Wt,e=>e.slice(1).toUpperCase())}const Ht=/\s\s*/;function Kt(e,t,n,l){t.trim().split(Ht).forEach(t=>{e.removeEventListener(t,n,l)})}function Gt(e,t,n,l){t.trim().split(Ht).forEach(t=>{e.addEventListener(t,n,l)})}function Qt(e,t,n,l){Gt(e,t,n,Object.assign(Object.assign({},l),{once:!0}))}const Xt={bubbles:!0,cancelable:!0,composed:!0};const Yt=Promise.resolve();function Jt(e){const{documentElement:t}=e.ownerDocument,n=e.getBoundingClientRect();return{left:n.left+(Xe.pageXOffset-t.clientLeft),top:n.top+(Xe.pageYOffset-t.clientTop)}}const Zt=/deg|g?rad|turn$/i;function en(e){const t=parseFloat(e)||0;if(0!==t){const[n="rad"]=String(e).match(Zt)||[];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 tn="contain";function nn(e,t=tn){const{aspectRatio:n}=e;let{width:l,height:r}=e;const a=Dt(l),i=Dt(r);if(a&&i){const e=r*n;t===tn&&e>l||"cover"===t&&e<l?r=l/n:l=r*n}else a?r=l/n:i&&(l=r*n);return{width:l,height:r}}function ln(e,...t){if(0===t.length)return e;const[n,l,r,a,i,o]=e,[s,c,u,d,b,m]=t[0];return ln(e=[n*s+r*c,l*s+a*c,n*u+r*d,l*u+a*d,n*b+r*m+i,l*b+a*m+o],...t.slice(1))}const rn=/left|top|width|height/i,an="open",on=/* @__PURE__ */new WeakMap,sn=/* @__PURE__ */new WeakMap,cn=/* @__PURE__ */new Map,un=Xe.document&&Array.isArray(Xe.document.adoptedStyleSheets)&&"replaceSync"in Xe.CSSStyleSheet.prototype;class dn extends HTMLElement{get $sharedStyle(){return(this.themeColor?`:host{--theme-color: ${this.themeColor};}`:"")+":host([hidden]){display:none!important}"}constructor(){var e,t;super(),this.shadowRootMode=an,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&&cn.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 l=Vt(e);let r=n;switch(typeof this[l]){case"boolean":r=null!==n&&"false"!==n;break;case"number":r=Number(n)}switch(this[l]=r,e){case"theme-color":{const e=sn.get(this),t=this.$sharedStyle;e&&t&&(un?e.replaceSync(t):e.textContent=t);break}}}$propertyChangedCallback(e,t,n){if(!Object.is(n,t))switch(e=qt(e),typeof n){case"boolean":!0===n?this.hasAttribute(e)||this.setAttribute(e,""):this.removeAttribute(e);break;case"number":n=Mt(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=Vt(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 l=n;n=e,this.$propertyChangedCallback(t,l,e)}})});const e=this.shadowRoot||this.attachShadow({mode:this.shadowRootMode||an});if(on.set(this,e),sn.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(){sn.has(this)&&sn.delete(this),on.has(this)&&on.delete(this)}$getTagNameOf(e){var t;return null!==(t=cn.get(e))&&void 0!==t?t:e}$setStyles(e){return Object.keys(e).forEach(t=>{let n=e[t];Pt(n)&&(n=0!==n&&rn.test(t)?`${n}px`:String(n)),this.style[t]=n}),this}$getShadowRoot(){return this.shadowRoot||on.get(this)}$addStyles(e){let t;const n=this.$getShadowRoot();return un?(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,l){return e.dispatchEvent(new CustomEvent(t,Object.assign(Object.assign(Object.assign({},Xt),{detail:n}),l)))}(this,e,t,n)}$nextTick(e){return function(e,t){return t?Yt.then(e?t.bind(e):t):Yt}(this,e)}static $define(e,t){Ot(e)&&(t=e,e=""),e||(e=this.$name||this.name),e=qt(e),Qe&&Xe.customElements&&!Xe.customElements.get(e)&&customElements.define(e,this,t)}}dn.$version="2.1.0";class bn extends dn{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=mt,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),Gt(this,kt,this.$onPointerDown)),this.$onPointerMove||(this.$onPointerMove=this.$handlePointerMove.bind(this),Gt(this.ownerDocument,Ct,this.$onPointerMove)),this.$onPointerUp||(this.$onPointerUp=this.$handlePointerUp.bind(this),Gt(this.ownerDocument,Nt,this.$onPointerUp)),this.$onWheel||(this.$onWheel=this.$handleWheel.bind(this),Gt(this,_t,this.$onWheel,{passive:!1,capture:!0}))}$unbind(){this.$onPointerDown&&(Kt(this,kt,this.$onPointerDown),this.$onPointerDown=null),this.$onPointerMove&&(Kt(this.ownerDocument,Ct,this.$onPointerMove),this.$onPointerMove=null),this.$onPointerUp&&(Kt(this.ownerDocument,Nt,this.$onPointerUp),this.$onPointerUp=null),this.$onWheel&&(Kt(this,_t,this.$onWheel,{capture:!0}),this.$onWheel=null)}$handlePointerDown(e){const{buttons:t,button:n,type:l}=e;if(this.disabled||("pointerdown"===l&&"mouse"===e.pointerType||"mousedown"===l)&&(Pt(t)&&1!==t||Pt(n)&&0!==n||e.ctrlKey))return;const{$pointers:r}=this;let a="";if(e.changedTouches)Array.from(e.changedTouches).forEach(({identifier:e,pageX:t,pageY:n})=>{r.set(e,{startX:t,startY:n,endX:t,endY:n})});else{const{pointerId:t=0,pageX:n,pageY:l}=e;r.set(t,{startX:n,startY:l,endX:n,endY:l})}r.size>1?a=bt:Ut(e.target)&&(a=e.target.action||e.target.getAttribute("action")||""),!1!==this.$emit(It,{action:a,relatedEvent:e})&&(e.preventDefault(),this.$action=a,this.style.willChange="transform")}$handlePointerMove(e){const{$action:t,$pointers:n}=this;if(this.disabled||t===mt||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:l})=>{const r=n.get(e);r&&Object.assign(r,{endX:t,endY:l})});else{const{pointerId:t=0,pageX:l,pageY:r}=e,a=n.get(t);a&&Object.assign(a,{endX:l,endY:r})}const l={action:t,relatedEvent:e};if(t===bt){const t=new Map(n);let r=0,a=0,i=0,o=0,s=e.pageX,c=e.pageY;n.forEach((e,n)=>{t.delete(n),t.forEach(t=>{let n=t.startX-e.startX,l=t.startY-e.startY,u=t.endX-e.endX,d=t.endY-e.endY,b=0,m=0,h=0,p=0;if(0===n?l<0?h=2*Math.PI:l>0&&(h=Math.PI):n>0?h=Math.PI/2+Math.atan(l/n):n<0&&(h=1.5*Math.PI+Math.atan(l/n)),0===u?d<0?p=2*Math.PI:d>0&&(p=Math.PI):u>0?p=Math.PI/2+Math.atan(d/u):u<0&&(p=1.5*Math.PI+Math.atan(d/u)),p>0||h>0){const n=p-h,l=Math.abs(n);l>r&&(r=l,i=n,s=(e.startX+t.startX)/2,c=(e.startY+t.startY)/2)}if(n=Math.abs(n),l=Math.abs(l),u=Math.abs(u),d=Math.abs(d),n>0&&l>0?b=Math.sqrt(n*n+l*l):n>0?b=n:l>0&&(b=l),u>0&&d>0?m=Math.sqrt(u*u+d*d):u>0?m=u:d>0&&(m=d),b>0&&m>0){const n=(m-b)/b,l=Math.abs(n);l>a&&(a=l,o=n,s=(e.startX+t.startX)/2,c=(e.startY+t.startY)/2)}})});const u=r>0,d=a>0;u&&d?(l.rotate=i,l.scale=o,l.centerX=s,l.centerY=c):u?(l.action=dt,l.rotate=i,l.centerX=s,l.centerY=c):d?(l.action=ut,l.scale=o,l.centerX=s,l.centerY=c):l.action=mt}else{const[e]=Array.from(n.values());Object.assign(l,e)}n.forEach(e=>{e.startX=e.endX,e.startY=e.endY}),l.action!==mt&&this.$emit(zt,l,{cancelable:!1})}$handlePointerUp(e){const{$action:t,$pointers:n}=this;if(!this.disabled&&t!==mt&&!1!==this.$emit(Tt,{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=mt)}}$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(zt,{action:ut,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 l=document.createElement("canvas");let r=this.offsetWidth,a=this.offsetHeight,i=1;Ft(e)&&(Dt(e.width)||Dt(e.height))&&(({width:r,height:a}=nn({aspectRatio:r/a,width:e.width,height:e.height})),i=r/this.offsetWidth),l.width=r,l.height=a;const o=this.querySelector(this.$getTagNameOf(rt));o?o.$ready().then(n=>{const s=l.getContext("2d");if(s){const[t,c,u,d,b,m]=o.$getTransform();let h=b,p=m,f=n.naturalWidth,g=n.naturalHeight;1!==i&&(h*=i,p*=i,f*=i,g*=i);const y=f/2,v=g/2;s.fillStyle="transparent",s.fillRect(0,0,r,a),Ft(e)&&jt(e.beforeDraw)&&e.beforeDraw.call(this,s,l),s.save(),s.translate(y,v),s.transform(t,c,u,d,h,p),s.translate(-y,-v),s.drawImage(n,0,0,f,g),s.restore()}t(l)}).catch(n):t(l)})}}bn.$name=et,bn.$version="2.1.0";const mn=/* @__PURE__ */new WeakMap,hn=["alt","crossorigin","decoding","elementtiming","fetchpriority","loading","referrerpolicy","sizes","src","srcset"];class pn extends dn{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){mn.set(this,e)}get $canvas(){return mn.get(this)}static get observedAttributes(){return super.observedAttributes.concat(hn,["initial-center-size","rotatable","scalable","skewable","translatable"])}attributeChangedCallback(e,t,n){Object.is(n,t)||(super.attributeChangedCallback(e,t,n),hn.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(et));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),Gt(t,It,this.$onCanvasActionStart),Gt(t,Tt,this.$onCanvasActionEnd),Gt(t,zt,this.$onCanvasAction)),this.$onLoad=this.$handleLoad.bind(this),Gt(e,$t,this.$onLoad),this.$getShadowRoot().appendChild(e)}disconnectedCallback(){const{$image:e,$canvas:t}=this;t&&(this.$onCanvasActionStart&&(Kt(t,It,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(Kt(t,Tt,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasAction&&(Kt(t,zt,this.$onCanvasAction),this.$onCanvasAction=null)),e&&this.$onLoad&&(Kt(e,$t,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:l}=n;switch(l!==bt||this.rotatable&&this.scalable||(l=this.rotatable?dt:this.scalable?ut:mt),l){case ct:if(this.translatable){let l=null;e&&(l=e.target.closest(this.$getTagNameOf(at))),l||(l=t.querySelector(this.$getTagNameOf(at))),l&&l.multiple&&!l.active&&(l=t.querySelector(`${this.$getTagNameOf(at)}[active]`)),l&&!l.hidden&&l.movable&&!l.dynamic&&this.$actionStartTarget&&l.contains(this.$actionStartTarget)||this.$move(n.endX-n.startX,n.endY-n.startY)}break;case dt:if(this.rotatable)if(e){const{x:t,y:l}=this.getBoundingClientRect();this.$rotate(n.rotate,e.clientX-t,e.clientY-l)}else this.$rotate(n.rotate);break;case ut:if(this.scalable)if(e){const t=e.target.closest(this.$getTagNameOf(at));if(!t||!t.zoomable||t.zoomable&&t.dynamic){const{x:t,y:l}=this.getBoundingClientRect();this.$zoom(n.scale,e.clientX-t,e.clientY-l)}}else this.$zoom(n.scale);break;case bt:if(this.rotatable&&this.scalable){const{rotate:t}=n;let{scale:l}=n;l<0?l=1/(1-l):l+=1;const r=Math.cos(t),a=Math.sin(t),[i,o,s,c]=[r*l,a*l,-a*l,r*l];if(e){const t=this.getBoundingClientRect(),n=e.clientX-t.x,l=e.clientY-t.y,[r,a,u,d]=this.$matrix,b=n-t.width/2,m=l-t.height/2,h=(b*d-u*m)/(r*d-u*a),p=(m*r-a*b)/(r*d-u*a);this.$transform(i,o,s,c,h*(1-i)+p*s,p*(1-c)+h*o)}else this.$transform(i,o,s,c,0,0)}}}}$ready(e){const{$image:t}=this,n=new Promise((e,n)=>{const l=new Error("Failed to load the image source");if(t.complete)t.naturalWidth>0&&t.naturalHeight>0?e(t):n(l);else{const r=()=>{Kt(t,St,a),setTimeout(()=>{e(t)})},a=()=>{Kt(t,$t,r),n(l)};Qt(t,$t,r),Qt(t,St,a)}});return jt(e)&&n.then(t=>(e(t),t)),n}$center(e){const{parentElement:t}=this;if(!t)return this;const n=t.getBoundingClientRect(),l=n.width,r=n.height,{x:a,y:i,width:o,height:s}=this.getBoundingClientRect(),c=a+o/2,u=i+s/2,d=n.x+l/2,b=n.y+r/2;if(this.$move(d-c,b-u),e&&(o!==l||s!==r)){const t=l/o,n=r/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&&Pt(e)&&Pt(t)){const[n,l,r,a]=this.$matrix,i=(e*a-r*t)/(n*a-r*l),o=(t*n-l*e)/(n*a-r*l);this.$translate(i,o)}return this}$moveTo(e,t=e){if(this.translatable&&Pt(e)&&Pt(t)){const[n,l,r,a]=this.$matrix,i=(e*a-r*t)/(n*a-r*l),o=(t*n-l*e)/(n*a-r*l);this.$setTransform(n,l,r,a,i,o)}return this}$rotate(e,t,n){if(this.rotatable){const l=en(e),r=Math.cos(l),a=Math.sin(l),[i,o,s,c]=[r,a,-a,r];if(Pt(t)&&Pt(n)){const[e,l,r,a]=this.$matrix,{width:u,height:d}=this.getBoundingClientRect(),b=t-u/2,m=n-d/2,h=(b*a-r*m)/(e*a-r*l),p=(m*e-l*b)/(e*a-r*l);this.$transform(i,o,s,c,h*(1-i)-p*s,p*(1-c)-h*o)}else this.$transform(i,o,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,Pt(t)&&Pt(n)){const[l,r,a,i]=this.$matrix,{width:o,height:s}=this.getBoundingClientRect(),c=t-o/2,u=n-s/2,d=(c*i-a*u)/(l*i-a*r),b=(u*l-r*c)/(l*i-a*r);this.$transform(e,0,0,e,d*(1-e),b*(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=en(e),l=en(t);this.$transform(1,Math.tan(l),Math.tan(n),1,0,0)}return this}$translate(e,t=e){return this.translatable&&Pt(e)&&Pt(t)&&this.$transform(1,0,0,1,e,t),this}$transform(e,t,n,l,r,a){return Pt(e)&&Pt(t)&&Pt(n)&&Pt(l)&&Pt(r)&&Pt(a)?this.$setTransform(ln(this.$matrix,[e,t,n,l,r,a])):this}$setTransform(e,t,n,l,r,a){if((this.rotatable||this.scalable||this.skewable||this.translatable)&&(Array.isArray(e)&&([e,t,n,l,r,a]=e),Pt(e)&&Pt(t)&&Pt(n)&&Pt(l)&&Pt(r)&&Pt(a))){const i=[...this.$matrix],o=[e,t,n,l,r,a];if(!1===this.$emit(Lt,{matrix:o,oldMatrix:i}))return this;this.$matrix=o,this.style.transform=`matrix(${o.join(", ")})`}return this}$getTransform(){return this.$matrix.slice()}$resetTransform(){return this.$setTransform([1,0,0,1,0,0])}}pn.$name=rt,pn.$version="2.1.0";const fn=/* @__PURE__ */new WeakMap;class gn extends dn{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){fn.set(this,e)}get $canvas(){return fn.get(this)}static get observedAttributes(){return super.observedAttributes.concat(["height","width","x","y"])}connectedCallback(){super.connectedCallback();const e=this.closest(this.$getTagNameOf(et));if(e){this.$canvas=e,this.style.position="absolute";const t=e.querySelector(this.$getTagNameOf(at));t&&(this.$onCanvasActionStart=e=>{t.hidden&&e.detail.action===st&&(this.hidden=!1)},this.$onCanvasActionEnd=e=>{t.hidden&&e.detail.action===st&&(this.hidden=!0)},this.$onSelectionChange=e=>{const{x:n,y:l,width:r,height:a}=e.defaultPrevented?t:e.detail;this.$change(n,l,r,a),(t.hidden||0===n&&0===l&&0===r&&0===a)&&(this.hidden=!0)},Gt(e,It,this.$onCanvasActionStart),Gt(e,Tt,this.$onCanvasActionEnd),Gt(e,At,this.$onSelectionChange))}this.$render()}disconnectedCallback(){const{$canvas:e}=this;e&&(this.$onCanvasActionStart&&(Kt(e,It,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(Kt(e,Tt,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onSelectionChange&&(Kt(e,At,this.$onSelectionChange),this.$onSelectionChange=null)),super.disconnectedCallback()}$change(e,t,n=this.width,l=this.height){return Pt(e)&&Pt(t)&&Pt(n)&&Pt(l)&&(e!==this.x||t!==this.y||n!==this.width||l!==this.height)?(this.hidden&&(this.hidden=!1),this.x=e,this.y=t,this.width=n,this.height=l,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:Xe.innerWidth})}}gn.$name=it,gn.$version="2.1.0";class yn extends dn{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=mt,this.plain=!1,this.slottable=!1,this.themeColor="rgba(51, 153, 255, 0.5)"}static get observedAttributes(){return super.observedAttributes.concat(["action","plain"])}}yn.$name=lt,yn.$version="2.1.0";const vn=/* @__PURE__ */new WeakMap;class wn extends dn{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){vn.set(this,e)}get $canvas(){return vn.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(()=>{Dt(n)&&n<=1&&this.$initSelection(!0,!0)});break;case"keyboard":this.$nextTick(()=>{this.$canvas&&(n?this.$onDocumentKeyDown||(this.$onDocumentKeyDown=this.$handleKeyDown.bind(this),Gt(this.ownerDocument,Et,this.$onDocumentKeyDown)):this.$onDocumentKeyDown&&(Kt(this.ownerDocument,Et,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(At,{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(et));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),Gt(e,It,this.$onCanvasActionStart),Gt(e,Tt,this.$onCanvasActionEnd),Gt(e,zt,this.$onCanvasAction)):this.$render()}disconnectedCallback(){const{$canvas:e}=this;e&&(this.$onCanvasActionStart&&(Kt(e,It,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(Kt(e,Tt,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasAction&&(Kt(e,zt,this.$onCanvasAction),this.$onCanvasAction=null)),super.disconnectedCallback()}$getSelections(){let e=[];return this.parentElement&&(e=Array.from(this.parentElement.querySelectorAll(this.$getTagNameOf(at)))),e}$initSelection(e=!1,t=!1){const{initialCoverage:n,parentElement:l}=this;if(Dt(n)&&l){const r=this.aspectRatio||this.initialAspectRatio;let a=(t?0:this.width)||l.offsetWidth*n,i=(t?0:this.height)||l.offsetHeight*n;Dt(r)&&({width:a,height:i}=nn({aspectRatio:r,width:a,height:i})),this.$change(this.x,this.y,a,i),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),l=t[n+1]||t[n-1];l&&(e.active=!1,this.parentElement.removeChild(e),l.active=!0,l.$emit(At,{x:l.x,y:l.y,width:l.width,height:l.height}))}else this.$clear()}}$handleActionStart(e){var t,n;const l=null===(n=null===(t=e.detail)||void 0===t?void 0:t.relatedEvent)||void 0===n?void 0:n.target;this.$action="",this.$actionStartTarget=l,!this.hidden&&this.multiple&&!this.active&&l===this&&this.parentElement&&(this.$getSelections().forEach(e=>{e.active=!1}),this.active=!0,this.$emit(At,{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:l}=n;let{action:r}=n;const a=l?function(e){if("function"==typeof e.composedPath)return e.composedPath().find(Ut)||e.target;return e.target}(l):null;if(!r&&this.multiple&&(r=this.$action||(null==a?void 0:a.action),this.$action=r),!r||this.hidden&&r!==st||this.multiple&&!this.active&&r!==ut)return;const{width:i,height:o}=this;let s=n.endX-n.startX,c=n.endY-n.startY,{aspectRatio:u}=this;switch(!Dt(u)&&l.shiftKey&&(u=Dt(i)&&Dt(o)?i/o:1),r){case st:if(0!==s||0!==c){0===s?s=c:0===c&&(c=s);const{$canvas:e}=this,l=Jt(t);(this.multiple&&!this.hidden?this.$createSelection():this).$change(n.startX-l.left,n.startY-l.top,Math.abs(s),Math.abs(c),u),s<0?c<0?r=vt:c>0&&(r=xt):s>0&&(c<0?r=yt:c>0&&(r=wt)),e&&(e.$action=r)}break;case ct:this.movable&&(this.dynamic||this.$actionStartTarget&&this.contains(this.$actionStartTarget))&&this.$move(s,c);break;case ut:if(l&&this.zoomable&&(this.dynamic||this.contains(l.target))){const e=Jt(t);this.$zoom(n.scale,l.pageX-e.left,l.pageY-e.top)}break;default:this.$resize(r,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,l=this.aspectRatio){if(!this.resizable)return this;const r=Dt(l),{$canvas:a}=this;let{x:i,y:o,width:s,height:c}=this;switch(e){case ht:o+=n,c-=n,c<0&&(e=ft,c=-c,o-=c),r&&(i+=(t=n*l)/2,s-=t,s<0&&(s=-s,i-=s));break;case pt:s+=t,s<0&&(e=gt,s=-s,i-=s),r&&(o-=(n=t/l)/2,c+=n,c<0&&(c=-c,o-=c));break;case ft:c+=n,c<0&&(e=ht,c=-c,o-=c),r&&(i-=(t=n*l)/2,s+=t,s<0&&(s=-s,i-=s));break;case gt:i+=t,s-=t,s<0&&(e=pt,s=-s,i-=s),r&&(o+=(n=t/l)/2,c-=n,c<0&&(c=-c,o-=c));break;case yt:r&&(n=-t/l),o+=n,c-=n,s+=t,s<0&&c<0?(e=xt,s=-s,c=-c,i-=s,o-=c):s<0?(e=vt,s=-s,i-=s):c<0&&(e=wt,c=-c,o-=c);break;case vt:r&&(n=t/l),i+=t,o+=n,s-=t,c-=n,s<0&&c<0?(e=wt,s=-s,c=-c,i-=s,o-=c):s<0?(e=yt,s=-s,i-=s):c<0&&(e=xt,c=-c,o-=c);break;case wt:r&&(n=t/l),s+=t,c+=n,s<0&&c<0?(e=vt,s=-s,c=-c,i-=s,o-=c):s<0?(e=xt,s=-s,i-=s):c<0&&(e=yt,c=-c,o-=c);break;case xt:r&&(n=-t/l),i+=t,s-=t,c+=n,s<0&&c<0?(e=yt,s=-s,c=-c,i-=s,o-=c):s<0?(e=wt,s=-s,i-=s):c<0&&(e=vt,c=-c,o-=c)}return a&&a.$setAction(e),this.$change(i,o,s,c)}$zoom(e,t,n){if(!this.zoomable||0===e)return this;e<0?e=1/(1-e):e+=1;const{width:l,height:r}=this,a=l*e,i=r*e;let o=this.x,s=this.y;return Pt(t)&&Pt(n)?(o-=(a-l)*((t-this.x)/l),s-=(i-r)*((n-this.y)/r)):(o-=(a-l)/2,s-=(i-r)/2),this.$change(o,s,a,i)}$change(e,t,n=this.width,l=this.height,r=this.aspectRatio,a=!1){return this.$changing||!Pt(e)||!Pt(t)||!Pt(n)||!Pt(l)||n<0||l<0?this:(Dt(r)&&({width:n,height:l}=nn({aspectRatio:r,width:n,height:l},"cover")),this.precise||(e=Math.round(e),t=Math.round(t),n=Math.round(n),l=Math.round(l)),e===this.x&&t===this.y&&n===this.width&&l===this.height&&Object.is(r,this.aspectRatio)&&!a?this:(this.hidden&&(this.hidden=!1),!1===this.$emit(At,{x:e,y:t,width:n,height:l})?this:(this.$changing=!0,this.x=e,this.y=t,this.width=n,this.height=l,this.$changing=!1,this.$render())))}$reset(){const{x:e,y:t,width:n,height:l}=this.$initialSelection;return this.$change(e,t,n,l)}$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 l=document.createElement("canvas");let{width:r,height:a}=this,i=1;if(Ft(e)&&(Dt(e.width)||Dt(e.height))&&(({width:r,height:a}=nn({aspectRatio:r/a,width:e.width,height:e.height})),i=r/this.width),l.width=r,l.height=a,!this.$canvas)return void t(l);const o=this.$canvas.querySelector(this.$getTagNameOf(rt));o?o.$ready().then(n=>{const s=l.getContext("2d");if(s){const[t,c,u,d,b,m]=o.$getTransform(),h=-this.x,p=-this.y,f=(h*d-u*p)/(t*d-u*c),g=(p*t-c*h)/(t*d-u*c);let y=t*f+u*g+b,v=c*f+d*g+m,w=n.naturalWidth,x=n.naturalHeight;1!==i&&(y*=i,v*=i,w*=i,x*=i);const k=w/2,C=x/2;s.fillStyle="transparent",s.fillRect(0,0,r,a),Ft(e)&&jt(e.beforeDraw)&&e.beforeDraw.call(this,s,l),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(l)}).catch(n):t(l)})}}wn.$name=at,wn.$version="2.1.0";class xn extends dn{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))}}xn.$name=nt,xn.$version="2.1.0";class kn extends dn{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"])}}kn.$name=tt,kn.$version="2.1.0";const Cn=/* @__PURE__ */new WeakMap,Nn=/* @__PURE__ */new WeakMap,Sn=/* @__PURE__ */new WeakMap,En=/* @__PURE__ */new WeakMap,$n="vertical";class _n extends dn{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=$n,this.selection="",this.slottable=!1}set $image(e){Nn.set(this,e)}get $image(){return Nn.get(this)}set $sourceImage(e){En.set(this,e)}get $sourceImage(){return En.get(this)}set $canvas(e){Cn.set(this,e)}get $canvas(){return Cn.get(this)}set $selection(e){Sn.set(this,e)}get $selection(){return Sn.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(at)),Ut(n)){this.$selection=n,this.$onSelectionChange=this.$handleSelectionChange.bind(this),Gt(n,At,this.$onSelectionChange);const e=n.closest(this.$getTagNameOf(et));if(e){this.$canvas=e;const t=e.querySelector(this.$getTagNameOf(rt));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),Gt(t.$image,$t,this.$onSourceImageLoad),Gt(t,Lt,this.$onSourceImageTransform))}this.$render()}}disconnectedCallback(){const{$selection:e,$sourceImage:t}=this;e&&this.$onSelectionChange&&(Kt(e,At,this.$onSelectionChange),this.$onSelectionChange=null),t&&this.$onSourceImageLoad&&(Kt(t.$image,$t,this.$onSourceImageLoad),this.$onSourceImageLoad=null),t&&this.$onSourceImageTransform&&(Kt(t,Lt,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"),l=t.getAttribute("src");l&&l!==n&&(e.setAttribute("src",l),e.$ready(()=>{this.$render()}))}$handleSourceImageTransform(e){this.$render(void 0,e.detail.matrix)}$render(e,t){const{$canvas:n,$selection:l}=this;e||l.hidden||(e=l),(!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:r,y:a,width:i,height:o}=e,s={},{clientWidth:c,clientHeight:u}=this;let d=c,b=u,m=NaN;switch(this.resize){case"both":m=1,d=i,b=o,s.width=i,s.height=o;break;case"horizontal":m=o>0?u/o:0,d=i*m,s.width=d;break;case $n:m=i>0?c/i:0,b=o*m,s.height=b;break;default:c>0?m=i>0?c/i:0:u>0&&(m=o>0?u/o:0)}this.$scale=m,this.$setStyles(s),this.$sourceImage&&setTimeout(()=>{this.$transformImageByOffset(null!=t?t:this.$sourceImage.$getTransform(),-r,-a)})}$transformImageByOffset(e,t,n){const{$image:l,$scale:r,$sourceImage:a}=this;if(a&&l&&r>=0){const[a,i,o,s,c,u]=e,d=(t*s-o*n)/(a*s-o*i),b=(n*a-i*t)/(a*s-o*i),m=a*d+o*b+c,h=i*d+s*b+u;l.$ready(e=>{this.$setStyles.call(l,{width:e.naturalWidth*r,height:e.naturalHeight*r})}),l.$setTransform(a,i,o,s,m*r,h*r)}}}function zn(){const[e,n]=t(!1),[l,r]=t(null),[a,i]=t(null),o=async(e,t)=>{if(!e||!t)return r("ID de asset y configuración de variante son requeridos"),null;n(!0),r(null),i(null);try{const n=await async function(e,{variant_name:t,width:n,height:r,crop_params:a,preset_aspect:i=null,preset_size:o=null,output_format:s="webp"}){try{const l=[{name:t,width:n,height:r,output_format:s,crop_params:a}];return i&&(l[0].preset_aspect=i),o&&(l[0].preset_size=o),H(await j({endpoint:`/assets/${e}/variants`,method:"POST",body:{variants:l,async:!1},basePath:G,useJWT:!0}))}catch(l){throw K(l)}}(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 i(n.result),n.result;throw new Error("No se pudo crear la variante")}catch(a){return console.error("Error creating variant:",a),r(a.message||"Error desconocido al crear variante"),null}finally{n(!1)}};return{createVariant:o,createCropVariant:async(e,t,n={})=>{const l={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 o(e,l)},createVariantFromBlob:async(e,t,a={})=>{if(!e||!t)return r("ID de asset y blob son requeridos"),null;n(!0),r(null),i(null);try{const n=await async function(e,t,n={}){try{const l=new FormData,r=n.format||"webp",a=`${n.name||"variant"}.${r}`;return l.append("file",t,a),l.append("variant_name",n.name||"variant"),l.append("width",String(n.width||0)),l.append("height",String(n.height||0)),l.append("output_format",n.format||"webp"),l.append("permanent_url",!1!==n.permanentUrl?"true":"false"),H(await j({endpoint:`/assets/${e}/variants/upload`,method:"POST",body:l,basePath:G,isFormData:!0,useJWT:!0}))}catch(l){throw K(l)}}(e,t,{name:a.name||`crop_${Date.now()}`,width:a.width||0,height:a.height||0,format:a.format||"webp"});if(n?.result)return i(n.result),n.result;throw new Error("No se pudo crear la variante")}catch(o){return console.error("Error creating variant from blob:",o),r(o.message||"Error desconocido al crear variante"),null}finally{n(!1)}},loading:e,error:l,createdVariant:a,reset:()=>{r(null),i(null)}}}_n.$name=ot,_n.$version="2.1.0",bn.$define(),kn.$define(),xn.$define(),yn.$define(),pn.$define(),wn.$define(),gn.$define(),_n.$define();class Tn{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,l,r,a)=>{if(!this.image)return!1;try{return this.image.$setTransform(e,t,n,l,r,a),!0}catch(i){return console.warn("Error setting transform:",i),!1}},resetZoom:()=>{if(!this.image)return!1;try{const e=this.image.$getTransform();if(!e)return!1;const[t,n,l,r,a,i]=e,o=Math.sqrt(t*t+n*n),s=Math.sqrt(l*l+r*r),c=t/o,u=n/o,d=l/s,b=r/s;return this.image.$setTransform(c,u,d,b,a,i),!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,l,r,a,i,o]=t,s=Math.sqrt(n*n+l*l),c=Math.sqrt(r*r+a*a),u=n/s*e,d=l/s*e,b=r/c*e,m=a/c*e;return this.image.$setTransform(u,d,b,m,i,o),!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 l=1-e,r=t.width*l/n.naturalWidth,a=t.height*l/n.naturalHeight,i=Math.min(r,a,1);return this.transform.setZoom(i)}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,l]=e.split("/").map(e=>parseFloat(e.trim()));if(isNaN(n)||isNaN(l)||0===l)return console.warn("Invalid aspect ratio format:",e),!1;t=n/l}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,l,r)=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$change(e,t,n,l,r),!0}catch(a){return console.warn("Error changing selection:",a),!1}},set:(e,t,n,l)=>{if(!this.selectionElement)return!1;try{return this.selectionElement.x=e,this.selectionElement.y=t,this.selectionElement.width=n,this.selectionElement.height=l,this.selectionElement.$render(),!0}catch(r){return console.warn("Error setting selection:",r),!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,l,r,a,i]=e;return this.transform.setTransform(-t,n,l,r,a,i)},flipVertical:()=>{const e=this.transform.getTransform();if(!e)return!1;const[t,n,l,r,a,i]=e;return this.transform.setTransform(t,n,l,-r,a,i)},setupInitialView:async(e={})=>{const{paspartuFactor:t=.85,retries:n=3,retryDelay:l=200}=e;return new Promise(e=>{const r=(a=0)=>{if(!this.isReady)return a<n?void setTimeout(()=>r(a+1),l):void e(!1);try{const i=this.canvasElement.getBoundingClientRect();let o=this.image.querySelector("img")||this.image;if(!o?.naturalWidth||!o?.naturalHeight)return a<n?void setTimeout(()=>r(a+1),l):(this.transform.center(),void e(!1));if(i.width>0&&i.height>0){const n=i.width*t/o.naturalWidth,l=i.height*t/o.naturalHeight,r=Math.min(n,l,1);this.transform.setTransform(r,0,0,r,0,0)?setTimeout(()=>{this.transform.center(),this.selection.center(),e(!0)},100):(this.transform.reset(),setTimeout(()=>{r<1&&this.transform.scale(r),setTimeout(()=>{this.transform.center(),this.selection.center(),e(!0)},100)},100))}else this.transform.center(),e(!1)}catch(i){console.warn("Error in setup:",i),this.transform.center(),e(!1)}};r()})},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:l,onActionStart:r,onActionMove:a,onActionEnd:i}=e,o=[];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),o.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),o.push(()=>{this.image&&this.image.removeEventListener("transform",e)})}if(this.canvasElement){if(l){const e=e=>l(e.detail);this.canvasElement.addEventListener("action",e),o.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("action",e)})}if(r){const e=e=>r(e.detail);this.canvasElement.addEventListener("actionstart",e),o.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionstart",e)})}if(a){const e=e=>a(e.detail);this.canvasElement.addEventListener("actionmove",e),o.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionmove",e)})}if(i){const e=e=>i(e.detail);this.canvasElement.addEventListener("actionend",e),o.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionend",e)})}}return()=>{o.forEach(e=>e())}}}async function In(e,t,n={}){const{format:l=null,originalFormat:r="webp",onSuccess:a=null,onError:i=null,accessibilityManager:o=null}=n;try{const n=window.limboCore?.config?.getGlobal(),i=l||n?.downloadFormat||r||"webp",c=`${t.split(".")[0]}.${i}`;if(o&&o.announce(`Descargando ${c}`),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,c),a&&a(c),o&&o.announce(`${c} descargado correctamente`),!0;let u;try{if(u=await fetch(e,{mode:"cors"}),!u.ok)throw new Error(`HTTP error! status: ${u.status}`)}catch(s){if(!e.startsWith("http"))throw s;{const t=(window.limboCore?.config?.getGlobal()||{}).prod?"https://limbo.lefebvre.es":"https://led-dev-limbo-dev.eu.els.local",n=window.limboCore?.apiClient?.token||"",l=`${t}/api/atenea/proxy?url=${encodeURIComponent(e)}`;if(u=await fetch(l,{credentials:"include",headers:{Authorization:`Bearer ${n}`}}),!u.ok)throw new Error(`Proxy error: ${u.status}`)}}const d=await u.blob();let b=d;const m=d.type;m!==`image/${"jpg"===i?"jpeg":i}`&&function(e){return["webp","jpeg","jpg","png"].includes(e.toLowerCase())}(i)&&(b=await async function(e,t){return new Promise((n,l)=>{const r=new Image,a=URL.createObjectURL(e);r.onload=()=>{try{const l=document.createElement("canvas");l.width=r.width,l.height=r.height;l.getContext("2d").drawImage(r,0,0);const i=`image/${"jpg"===t?"jpeg":t}`,o="png"===t?void 0:.92;l.toBlob(t=>{URL.revokeObjectURL(a),n(t||e)},i,o)}catch(l){URL.revokeObjectURL(a),n(e)}},r.onerror=()=>{URL.revokeObjectURL(a),n(e)},r.src=a})}(d,i));const h=window.URL.createObjectURL(b),p=document.createElement("a");return p.href=h,p.download=c,p.style.display="none",document.body.appendChild(p),p.click(),setTimeout(()=>{window.URL.revokeObjectURL(h),document.body.removeChild(p)},100),a&&a(c),o&&o.announce(`${c} descargado correctamente`),!0}catch(c){return console.error("Error downloading image:",c),i&&i(c),o&&o.announce(`Error al descargar la imagen: ${c.message}`),!1}}const An=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:In,downloadImage:In},Symbol.toStringTag,{value:"Module"}));function Ln({image:e,onSave:a,onCancel:o,onDelete:d,onError:b=null,deleting:m=!1,onVariantCreated:h=null,onUpload:p=null,uploading:f=!1,cropperConfig:g=null}){const[y,v]=t(!1),[w,x]=t(null),[k,C]=t(!1),[N,S]=t(!0),[E,$]=t(!0),[_,z]=t({x:20,y:100}),[T,I]=t(!1),[A,L]=t({x:0,y:0}),[M,P]=t(!1),[D,O]=t(!0),[R,F]=t(!1),[j,U]=t({horizontal:!1,vertical:!1}),[B,q]=t(!1),[W,V]=t(!1),[H,K]=t(!1),[G,Q]=t(!1),[X]=t(()=>{if(!e||!e.filename)return"image";const[t]=e.filename.split(".");return t}),Y=i(()=>{if(g)return{mandatoryCrops:g.mandatoryCrops||[],allowCustomCrops:!1!==g.allowAdditionalCrops,showDimensionInputs:!0===g.showDimensionInputs,maxCrops:g.maxCrops||null,localCropsOnly:!0===g.localCropsOnly,existingCrops:g.existingCrops||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,localCropsOnly:!0===e.cropper?.localCropsOnly,existingCrops:e.cropper?.existingCrops||null}},[g]),[J,Z]=t(()=>Y.mandatoryCrops.length>0?Y.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:X,width:e.width||1920,height:e.height||1080,required:!1,isCustom:!0,confirmed:!1,savedState:null}]),[ee,te]=t(0),ne=J[ee],le=i(()=>ne&&ne.width&&ne.height?ne.width/ne.height:"",[ne]),re=i(()=>{const e=50;if(!le||""===le)return{minWidth:e,minHeight:e};if(le>=1){return{minWidth:e,minHeight:e/le}}return{minWidth:e*le,minHeight:e}},[le]),[ae,ie]=t(!1),[oe,se]=t([]),[ue,de]=t(null),be=window.limboCore?.accessibilityManager,{createVariantFromBlob:me,loading:he,error:pe}=zn(),fe=((e,a={})=>{const i=r(null),o=r(null),s=r(null),c=r(null),[u,d]=t(null),[b,m]=t(null),[h,p]=t(!1),[f,g]=t(!0),[y,v]=t(0),w={aspectRatio:"",shade:!0,paspartuFactor:.85,...a};n(()=>{i.current&&o.current&&s.current&&(c.current=new Tn(i,o,s),p(!0))},[]),n(()=>{if(c.current)return c.current.setupEventListeners({onSelectionChange:e=>{d(e)},onImageTransform:()=>{v(e=>e+1)}})},[h]),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();g(e);const t=o.current?.querySelector("img")||o.current;t?.naturalWidth&&t?.naturalHeight&&m({naturalWidth:t.naturalWidth,naturalHeight:t.naturalHeight,currentWidth:t.width,currentHeight:t.height})})()},[e]),n(()=>{c.current&&h&&c.current.selection.setAspectRatio(w.aspectRatio)},[w.aspectRatio,h]),n(()=>{c.current&&h&&c.current.canvas.setBackground(w.shade)},[w.shade,h]);const x=l(()=>({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=l(()=>({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=l(()=>({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:i,imageRef:o,selectionRef:s},state:{cropData:u,imageInfo:b,isReady:h,canExport:f,transformVersion:y},transform:x(),selection:k(),utils:C(),manager:c.current}})(e,{aspectRatio:le||null,showGrid:N,shade:E,initialCoverage:.5,paspartuFactor:.85}),{refs:ge,state:ye,transform:ve,selection:we,utils:xe}=fe,{canvasRef:ke,imageRef:Ce,selectionRef:Ne}=ge,{cropData:Se,imageInfo:Ee,canExport:$e,transformVersion:_e}=ye,ze=i(()=>Ee||{naturalWidth:e.width||1920,naturalHeight:e.height||1080,currentWidth:e.width||1920,currentHeight:e.height||1080},[Ee,e.width,e.height]),Te=l(()=>S(e=>!e),[]),Ie=l(()=>$(e=>!e),[]),Ae=l(()=>V(e=>!e),[]),Le=l(()=>K(e=>!e),[]),Me=l(()=>Q(e=>!e),[]),De=l(()=>ve.center(),[ve]),Oe=l(()=>we.center(),[we]),Re=l(()=>we.reset(),[we]),Fe=l((e,t)=>ve.move(e,t),[ve]),je=l(e=>ve.zoom(e),[ve]),Ue=l(e=>ve.rotate(e),[ve]),Be=l(e=>{we.setCoverage(e)},[we]),qe=l(()=>{U(e=>{const t=!e.horizontal;return ve.flipHorizontal(),{...e,horizontal:t}})},[ve]),We=l(()=>{U(e=>{const t=!e.vertical;return ve.flipVertical(),{...e,vertical:t}})},[ve]),Ve=l(()=>{if(!fe.manager||!ye.isReady)return null;try{const e=Se?{...Se}:null;let t=null;if(Ne.current){const e=Ne.current;t={x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0}}let n=null;if(Ce.current){const e=Ce.current.$getTransform?.();e&&Array.isArray(e)&&(n=[...e])}const l={cropData:e,selectorState:t,imageTransform:n,flipState:{horizontal:j.horizontal,vertical:j.vertical}};return console.log(`[CropperView] 💾 Guardando estado del crop ${ee}:`,l),Z(e=>e.map((e,t)=>t===ee?{...e,savedState:l}:e)),l}catch(e){return console.warn("Error saving crop state:",e),null}},[fe.manager,ye.isReady,Se,j,ee,Ce,Ne]),He=l(e=>{const t=J[e];if(!t||!t.savedState)return console.log(`[CropperView] ℹ️ No hay estado guardado para crop ${e}, centrando...`),void setTimeout(()=>{De(),setTimeout(()=>Oe(),100)},100);if(fe.manager&&ye.isReady)try{const{savedState:n}=t;if(console.log(`[CropperView] ♻️ Restaurando estado del crop ${e}:`,n),n.imageTransform&&Ce.current&&Array.isArray(n.imageTransform)&&setTimeout(()=>{if(Ce.current&&Ce.current.$setTransform){const[e,t,l,r,a,i]=n.imageTransform;Ce.current.$setTransform(e,t,l,r,a,i),console.log(`[CropperView] ✅ Imagen restaurada: transform(${e.toFixed(2)}, ${t.toFixed(2)}, ${l.toFixed(2)}, ${r.toFixed(2)}, ${a.toFixed(0)}, ${i.toFixed(0)})`)}},100),n.selectorState&&Ne.current){const{x:e,y:t,width:l,height:r}=n.selectorState;setTimeout(()=>{Ne.current&&(Ne.current.x=e,Ne.current.y=t,Ne.current.width=l,Ne.current.height=r,Ne.current.$render&&Ne.current.$render(),console.log(`[CropperView] ✅ Selector restaurado: ${l}×${r} en (${e}, ${t})`))},150)}n.flipState&&U({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(()=>{De(),setTimeout(()=>Oe(),100)},100)}else console.warn("Cropper not ready for state restoration")},[J,fe.manager,ye.isReady,De,Oe,Ne,Ce]),Ke=l(()=>{for(let e=0;e<J.length;e++){const t=J[e];if(!t.label||""===t.label.trim())return e}return-1},[J]),Ge=l(async e=>{e!==ee&&(F(!0),Ve(),await new Promise(e=>setTimeout(e,100)),te(e),await new Promise(e=>setTimeout(e,250)),He(e),await new Promise(e=>setTimeout(e,200)),F(!1))},[ee,Ve,He]),Qe=l(()=>{if(!Y.allowCustomCrops)return void alert("No se pueden añadir recortes personalizados en este modo.");const t={id:`crop-custom-${Date.now()}`,label:`Recorte ${J.length+1}`,width:e.width||1920,height:e.height||1080,required:!1,isCustom:!0,confirmed:!1,savedState:null};Z(e=>[...e,t]),be?.announce(`Nuevo recorte personalizado añadido: ${t.label}. Selecciónalo para editarlo.`)},[Y.allowCustomCrops,J.length,e.width,e.height,be]),Xe=l((e,t)=>{const n=parseInt(t,10);""===t||isNaN(n)||Z(t=>t.map((t,l)=>l===ee?{...t,[e]:n}:t))},[ee]),Ye=l(e=>{const t=ne[e];let n=100;if(ke.current&&Ee){const e=ke.current.getBoundingClientRect(),t=Math.min(e.width,e.height);n=Math.max(100,Math.round(.05*t))}const l=Math.max(n,Math.min(5e3,t));l!==t&&Z(t=>t.map((t,n)=>n===ee?{...t,[e]:l}:t));const r={...ne,[e]:l},a=r.width/r.height,i=we.getData?.();we.setAspectRatio(a),i&&void 0!==i.x&&setTimeout(()=>{we.set?.(i.x,i.y,i.width,i.height)},50)},[ee,ne,we,ke,Ee]),Je=l(e=>{Z(t=>t.map((t,n)=>n===ee?{...t,label:e}:t))},[ee]),Ze=l((e,t=null)=>{t=t||J[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=J[e];if(n.required)alert("No se puede eliminar un recorte obligatorio.");else if(1!==J.length){if(Z(t=>t.filter((t,n)=>n!==e)),e===ee){const t=Math.max(0,e-1);te(t)}else e<ee&&te(e=>e-1);be?.announce(`Recorte ${n.label} eliminado`)}else alert("Debe haber al menos un recorte.")},[J,ee,be]),et=l(async()=>{if(!$e)return null;try{const t=await we.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}},[$e,e.mime_type,we]),tt=l(async()=>{if(y)return v(!1),x(null),void C(!1);if($e){v(!0),C(!0);try{const e=await et();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.")},[$e,et,y]),nt=l(e=>{e.target.closest(".limbo-preview-modal-header")&&(I(!0),L({x:e.clientX-_.x,y:e.clientY-_.y}))},[_]),lt=l(e=>{T&&(e.preventDefault(),z({x:e.clientX-A.x,y:e.clientY-A.y}))},[T,A]),rt=l(()=>{I(!1)},[]),at=l(e=>{if(!e.target.closest(".limbo-preview-modal-header"))return;const t=e.touches[0];I(!0),L({x:t.clientX-_.x,y:t.clientY-_.y})},[_]),it=l(e=>{if(!T)return;e.preventDefault();const t=e.touches[0];z({x:t.clientX-A.x,y:t.clientY-A.y})},[T,A]),ot=l(()=>{I(!1)},[]);n(()=>{if(T)return document.addEventListener("mousemove",lt),document.addEventListener("mouseup",rt),document.addEventListener("touchmove",it,{passive:!1}),document.addEventListener("touchend",ot),()=>{document.removeEventListener("mousemove",lt),document.removeEventListener("mouseup",rt),document.removeEventListener("touchmove",it),document.removeEventListener("touchend",ot)}},[T,lt,rt,it,ot]),n(()=>{if(!M)return;const e=e=>{"Escape"===e.key&&P(!1)};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[M]);const st=l(async(t,n=null)=>{const l=J[t];if(!l)throw new Error(`Crop ${t} no encontrado`);if(!l.savedState&&t!==ee)throw new Error(`El recorte "${l.label}" aún no ha sido configurado`);const r={index:ee,imageTransform:Ce.current?.$getTransform?.(),selectorState:Ne.current?{x:Ne.current.x,y:Ne.current.y,width:Ne.current.width,height:Ne.current.height}:null};try{if(t!==ee&&l.savedState){if(console.log(`[CropperView] 🔄 Restaurando temporalmente crop ${t} para guardado...`),l.savedState.imageTransform&&Ce.current?.$setTransform){const[e,t,n,r,a,i]=l.savedState.imageTransform;Ce.current.$setTransform(e,t,n,r,a,i)}if(l.savedState.selectorState&&Ne.current){const{x:e,y:t,width:n,height:r}=l.savedState.selectorState;Ne.current.x=e,Ne.current.y=t,Ne.current.width=n,Ne.current.height=r,Ne.current.$render?.()}await new Promise(e=>setTimeout(e,100))}const r=Math.min(l.width,5e3),i=Math.min(l.height,5e3),o=await we.toCanvas({width:r,height:i,imageSmoothingEnabled:!0,imageSmoothingQuality:"high"});if(!o)throw new Error(`No se pudo generar el canvas para "${l.label}"`);const s=globalThis.downloadFormat||"webp",c="webp"===s?"image/webp":"png"===s?"image/png":"image/jpeg",u=.9,d=await new Promise((e,t)=>{o.toBlob(n=>{n?e(n):t(new Error("No se pudo convertir el canvas a blob"))},c,u)});console.log("[CropperView] Canvas convertido a blob:",{size:d.size,type:d.type,dimensions:`${r}x${i}`});const b=`${l.label||"crop"}_${r}_${i}`,m=n||e.id,f=!m||"string"==typeof m&&m.startsWith("external"),g=(f||Y.localCropsOnly)&&!p;if(f&&p&&!Y.localCropsOnly){console.log("[CropperView] 📤 Imagen externa con onUpload disponible, subiendo crop como nuevo asset...");try{const e=new File([d],`${b}.${s}`,{type:c}),t=await p(e);if(t&&(t.id||t.url)){console.log("[CropperView] ✅ Crop subido exitosamente:",t);const e=l.savedState||{selectorState:Ne.current?{x:Ne.current.x,y:Ne.current.y,width:Ne.current.width,height:Ne.current.height}:null,imageTransform:Ce.current?.$getTransform?.()||null,flipState:{horizontal:j.horizontal,vertical:j.vertical}},n={id:t.id||`uploaded-${Date.now()}`,name:b,filename:`${b}.${s}`,url:t.urlSigned||t.url,urlSigned:t.urlSigned||t.url,width:r,height:i,format:s,size:d.size,mime_type:c,isLocal:!1,originalAssetId:null,uploadedAssetId:t.id,cropState:e};return be?.announceSuccess(`Recorte guardado: ${b}`),n}}catch(a){console.error("[CropperView] ❌ Error subiendo crop, fallback a local:",a)}}if(g){console.log(`[CropperView] 🌐 Generando resultado local (isExternal: ${f}, localCropsOnly: ${Y.localCropsOnly})`);const e=URL.createObjectURL(d),t=l.savedState||{selectorState:Ne.current?{x:Ne.current.x,y:Ne.current.y,width:Ne.current.width,height:Ne.current.height}:null,imageTransform:Ce.current?.$getTransform?.()||null,flipState:{horizontal:j.horizontal,vertical:j.vertical}},n={id:`local-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:b,filename:`${b}.${s}`,url:e,urlSigned:e,width:r,height:i,format:s,size:d.size,mime_type:c,blob:d,isLocal:!0,originalAssetId:m||null,cropState:t};return be?.announceSuccess(`Recorte creado localmente: ${b}`),n}const y=l.savedState||{selectorState:Ne.current?{x:Ne.current.x,y:Ne.current.y,width:Ne.current.width,height:Ne.current.height}:null,imageTransform:Ce.current?.$getTransform?.()||null,flipState:{horizontal:j.horizontal,vertical:j.vertical}},v=await me(m,d,{name:b,width:r,height:i,format:s});if(v)return v.cropState=y,be?.announceSuccess(`Recorte creado: ${b}`),h?.(m,v),v;throw new Error("No se pudo crear la variante")}finally{if(t!==ee&&r.imageTransform&&Ce.current?.$setTransform){console.log(`[CropperView] ↩️ Restaurando estado original del crop ${r.index}...`);const[e,t,n,l,a,i]=r.imageTransform;if(Ce.current.$setTransform(e,t,n,l,a,i),r.selectorState&&Ne.current){const{x:e,y:t,width:n,height:l}=r.selectorState;Ne.current.x=e,Ne.current.y=t,Ne.current.width=n,Ne.current.height=l,Ne.current.$render?.()}}}},[J,ee,we,me,e.id,h,be,Ce,Ne]),ct=l(async()=>{if(!$e){const e="No se puede exportar el recorte por restricciones de CORS en la imagen original.";return be?.announceError(e),void alert(e)}if(!ye.isReady){const e="El cropper aún no está inicializado. Espera un momento e inténtalo de nuevo.";return be?.announceError(e),void alert(e)}Ve(),be?.announce("Creando recorte de la imagen");try{let t=e.id,n=null;if(e.file&&p){be?.announce("Subiendo imagen...");const l=await p(e.file);if(!l||!l.id)throw new Error("No se pudo subir la imagen al servidor");t=l.id,n=l,be?.announceSuccess("Imagen subida correctamente")}const l=await st(ee,t);l&&a(n?{crops:[l],asset:n}:l)}catch(t){console.warn("Error creating crop variant:",t);const e=t.message||"No se pudo crear el recorte. Inténtalo de nuevo.";be?.announceError(e),alert(e),b?.(t)}},[$e,ye.isReady,be,Ve,st,ee,a,b,e.file,e.id,p]),ut=l(async t=>{Ve(),be?.announce(`Guardando ${t.length} recortes...`);try{let l=e.id,r=null;if(e.file&&p){be?.announce("Subiendo imagen...");const t=await p(e.file);if(!t||!t.id)throw new Error("No se pudo subir la imagen al servidor");l=t.id,r=t,be?.announceSuccess("Imagen subida correctamente")}const i=[],o=[];for(const e of t)try{const t=await st(e,l);t&&i.push(t)}catch(n){o.push({crop:J[e]?.label||`Crop ${e}`,error:n.message})}if(i.length>0&&(be?.announceSuccess(`${i.length} recorte(s) guardado(s) correctamente`),a(r?{crops:i,asset:r}:i)),o.length>0){const e=`Errores al guardar algunos recortes:\n${o.map(e=>`- ${e.crop}: ${e.error}`).join("\n")}`;be?.announceError(e),alert(e)}}catch(n){const e=n.message||"Error al procesar los recortes";be?.announceError(e),alert(e),b?.(n)}},[Ve,st,J,be,a,e.file,e.id,p,b]),dt=l(async()=>{const e=Ke();if(-1!==e){const t=J[e];return alert(`El recorte "${t.label||t||"(sin nombre)"}" debe tener un nombre válido.`),void te(e)}const t=J.findIndex((e,t)=>e.required&&!e.savedState&&t!==ee);if(-1!==t){const e=J[t];return alert(`El recorte obligatorio "${e.label}" aún no ha sido configurado.\n\nPor favor, configura todos los recortes obligatorios antes de guardar.`),te(t),void be?.announce(`Recorte obligatorio "${e.label}" sin configurar. Por favor, configúralo.`,"assertive")}if(J.length>1){de("save");const e=J.map((e,t)=>({crop:e,index:t})).filter(({crop:e,index:t})=>e.required||e.savedState||t===ee).map(({index:e})=>e);return se(e),void ie(!0)}await ct()},[Ke,J,ct,ee,be]),bt=l(async t=>{const n=J[t];if(!n)throw new Error(`Crop ${t} no encontrado`);if(!n.savedState&&t!==ee)throw new Error(`El recorte "${n.label}" aún no ha sido configurado`);const l={index:ee,imageTransform:Ce.current?.$getTransform?.(),selectorState:Ne.current?{x:Ne.current.x,y:Ne.current.y,width:Ne.current.width,height:Ne.current.height}:null};try{if(t!==ee&&n.savedState){if(console.log(`[CropperView] 🔄 Restaurando temporalmente crop ${t} para descarga...`),n.savedState.imageTransform&&Ce.current?.$setTransform){const[e,t,l,r,a,i]=n.savedState.imageTransform;Ce.current.$setTransform(e,t,l,r,a,i)}if(n.savedState.selectorState&&Ne.current){const{x:e,y:t,width:l,height:r}=n.savedState.selectorState;Ne.current.x=e,Ne.current.y=t,Ne.current.width=l,Ne.current.height=r,Ne.current.$render?.()}await new Promise(e=>setTimeout(e,100))}const l=await we.toCanvas({width:n.width,height:n.height,imageSmoothingEnabled:!0,imageSmoothingQuality:"high"});if(!l)throw new Error(`No se pudo generar el canvas para "${n.label}"`);const r=l.toDataURL(`image/${globalThis.downloadFormat||e.mime_type.split("/")[1]||"webp"}`,.9),a=`${(n.label||"crop").replace(/\.[^/.]+$/,"").replace(/\s+/g,"-").trim()}_${n.width}_${n.height}`;return await In(r,a,{accessibilityManager:be,onSuccess:e=>{console.log(`✅ Descargado: ${e}`)},onError:e=>{throw new Error(`Error al descargar "${n.label}": ${e.message}`)}}),{crop:n.label,filename:a}}finally{if(t!==ee&&l.imageTransform&&Ce.current?.$setTransform){console.log(`[CropperView] ↩️ Restaurando estado original del crop ${l.index}...`);const[e,t,n,r,a,i]=l.imageTransform;if(Ce.current.$setTransform(e,t,n,r,a,i),l.selectorState&&Ne.current){const{x:e,y:t,width:n,height:r}=l.selectorState;Ne.current.x=e,Ne.current.y=t,Ne.current.width=n,Ne.current.height=r,Ne.current.$render?.()}}}},[J,ee,we,e.mime_type,be,Ce,Ne]),mt=l(async e=>{Ve(),be?.announce(`Descargando ${e.length} recortes...`);const t=[],n=[];for(const r of e)try{const e=await bt(r);e&&t.push(e)}catch(l){n.push({crop:J[r]?.label||`Crop ${r}`,error:l.message})}if(t.length>0&&be?.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")}`;be?.announceError(e),alert(e)}},[Ve,bt,J,be]),ht=l(async()=>{if(!$e){const e="No se puede descargar el recorte por restricciones de CORS en la imagen original.";return be?.announceError(e),void alert(e)}Ve(),be?.announce("Preparando descarga del recorte");try{await bt(ee),be?.announceSuccess("Recorte descargado correctamente")}catch(e){console.error("Error downloading crop:",e);const t=e.message||"Error al descargar el recorte";be?.announceError(t),alert(t)}},[$e,be,Ve,bt,ee]),pt=l(async()=>{const e=Ke();if(-1!==e){const t=J[e];return alert(`El recorte "${t.label||t||"(sin nombre)"}" debe tener un nombre válido.`),void te(e)}if(J.length>1){de("download");const e=J.map((e,t)=>({crop:e,index:t})).filter(({crop:e,index:t})=>e.savedState||t===ee).map(({index:e})=>e);return se(e),void ie(!0)}await ht()},[Ke,J,ht,ee]),ft=i(()=>!!e.file||(!e.id||!("string"!=typeof e.id||!e.id.startsWith("external"))),[e.file,e.id]),gt=l(async()=>{try{if(e.file&&p){be?.announce("Subiendo imagen original...");const t=await p(e.file);if(!t||!t.id)throw new Error("No se pudo subir la imagen al servidor");return be?.announceSuccess("Imagen guardada correctamente"),void a({asset:t,crops:[]})}if(ft){be?.announce("Conservando imagen original...");const t={id:`local-original-${Date.now()}`,name:e.filename||"original",filename:e.filename||"image.jpg",url:e.url,urlSigned:e.url,width:e.width||Ee?.naturalWidth||1920,height:e.height||Ee?.naturalHeight||1080,mime_type:e.mime_type||"image/jpeg",isLocal:!0,isOriginal:!0};return be?.announceSuccess("Imagen original conservada"),void a({crops:[t]})}if(e.id&&!e.id.startsWith("external")){be?.announce("Seleccionando imagen original...");const t={id:e.id,name:e.filename||"original",filename:e.filename||"image.jpg",url:e.url,urlSigned:e.urlSigned||e.url,width:e.width||Ee?.naturalWidth||1920,height:e.height||Ee?.naturalHeight||1080,mime_type:e.mime_type||"image/jpeg",isOriginal:!0};return be?.announceSuccess("Imagen original seleccionada"),void a({crops:[t],assetId:e.id})}o()}catch(t){console.error("Error guardando imagen original:",t);const e=t.message||"No se pudo guardar la imagen. Inténtalo de nuevo.";be?.announceError(e),alert(e),b?.(t)}},[e,Ee,p,o,a,b,be,ft]);return n(()=>{v(!1),x(null)},[e]),n(()=>{if(!fe.manager||!ye.isReady||!D)return;console.log("[CropperView] Carga inicial completada, centrando imagen y selector...");const e=Y.existingCrops?.[0],t=e?.cropState;setTimeout(()=>{De(),setTimeout(()=>{if(t){if(console.log("[CropperView] 🔄 Restaurando estado del crop existente:",t),t.imageTransform&&Ce.current?.$setTransform){const[e,n,l,r,a,i]=t.imageTransform;Ce.current.$setTransform(e,n,l,r,a,i),console.log("[CropperView] ✅ Transformación de imagen restaurada")}if(t.selectorState&&Ne.current){const{x:e,y:n,width:l,height:r}=t.selectorState;Ne.current.x=e,Ne.current.y=n,Ne.current.width=l,Ne.current.height=r,Ne.current.$render?.(),console.log("[CropperView] ✅ Posición del selector restaurada:",t.selectorState)}t.flipState&&(U(t.flipState),console.log("[CropperView] ✅ Estado de flip restaurado:",t.flipState))}else Oe();O(!1),console.log("[CropperView] Carga inicial finalizada")},100)},50)},[fe.manager,ye.isReady,D,De,Oe,Y.existingCrops]),n(()=>{fe.manager&&ye.isReady&&(le&&we.setAspectRatio(le),xe.setBackground(E))},[le,E,fe.manager,ye.isReady,we,xe]),n(()=>{if(!Ee||!ye.isReady||Y.mandatoryCrops.length>0)return;const e=J[0];if(e&&"crop-default-0"===e.id&&(1920===e.width||1080===e.height)){const t=Math.min(Ee.naturalWidth,5e3),n=Math.min(Ee.naturalHeight,5e3);Z([{...e,width:t,height:n}]),console.log(`[CropperView] Crop por defecto actualizado a ${t}×${n}px`)}},[Ee,ye.isReady,Y.mandatoryCrops.length,J]),n(()=>{if(!y||!$e)return;const e=setTimeout(async()=>{C(e=>!w&&!e||e);try{const e=await et();e&&x(e)}finally{C(!1)}},300);return()=>{clearTimeout(e),C(!1)}},[Se,_e,y,$e,et,le,j,w]),n(()=>{const e=ke.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)}},[ke]),e?/* @__PURE__ */c("div",{className:"limbo-cropper-view lb:px-2 lb:border-2 lb:border-gray-200/50 lb:rounded-lg lb:max-w-7xl lb:mx-auto lb:w-full lb:min-w-full lb:h-full lb:min-h-full lb:flex lb:flex-col",children:[
375
+ /* @__PURE__ */c("div",{className:"limbo-tab-content lb:px-2 lb:py-2",role:"tabpanel",id:`upload-tabpanel-${h}`,"aria-labelledby":`upload-tab-${h}`,children:["upload"===h&&/* @__PURE__ */s(ze,{file:f,setFile:g,previewUrl:y,setPreviewUrl:v,fileInputRef:w,onSelect:e,disabled:n,allowedCategories:i,selectedFolder:u,onFolderChange:d,folderConfig:o}),"ai"===h&&/* @__PURE__ */s(Oe,{apiKey:l,prod:a,disabled:n,onSelect:e,selectedFolder:u,onFolderChange:d,folderConfig:o}),"stock"===h&&/* @__PURE__ */s(Ue,{apiKey:l,prod:a,disabled:n,onSelect:e,selectedFolder:u,onFolderChange:d,folderConfig:o}),"portals"===h&&/* @__PURE__ */s(He,{apiKey:l,prod:a,disabled:n,onSelect:e,selectedFolder:u,onFolderChange:d,folderConfig:o})]})]})}const Qe="undefined"!=typeof window&&void 0!==window.document,Xe=Qe?window:{},Ye=!!Qe&&"ontouchstart"in Xe.document.documentElement,Je=!!Qe&&"PointerEvent"in Xe,Ze="cropper",et=`${Ze}-canvas`,tt=`${Ze}-crosshair`,nt=`${Ze}-grid`,lt=`${Ze}-handle`,rt=`${Ze}-image`,at=`${Ze}-selection`,it=`${Ze}-shade`,ot=`${Ze}-viewer`,st="select",ct="move",ut="scale",dt="rotate",bt="transform",mt="none",ht="n-resize",pt="e-resize",ft="s-resize",gt="w-resize",yt="ne-resize",vt="nw-resize",wt="se-resize",xt="sw-resize",kt=Je?"pointerdown":Ye?"touchstart":"mousedown",Ct=Je?"pointermove":Ye?"touchmove":"mousemove",Nt=Je?"pointerup pointercancel":Ye?"touchend touchcancel":"mouseup",St="error",Et="keydown",$t="load",_t="wheel",zt="action",Tt="actionend",It="actionstart",At="change",Lt="transform";const Mt=Number.isNaN||Xe.isNaN;function Pt(e){return"number"==typeof e&&!Mt(e)}function Dt(e){return Pt(e)&&e>0&&e<1/0}function Ot(e){return"object"==typeof e&&null!==e}const{hasOwnProperty:Rt}=Object.prototype;function Ft(e){if(!Ot(e))return!1;try{const{constructor:t}=e,{prototype:n}=t;return t&&n&&Rt.call(n,"isPrototypeOf")}catch(t){return!1}}function jt(e){return"function"==typeof e}function Ut(e){return"object"==typeof e&&null!==e&&1===e.nodeType}const Bt=/([a-z\d])([A-Z])/g;function qt(e){return String(e).replace(Bt,"$1-$2").toLowerCase()}const Wt=/-[A-z\d]/g;function Vt(e){return e.replace(Wt,e=>e.slice(1).toUpperCase())}const Ht=/\s\s*/;function Kt(e,t,n,l){t.trim().split(Ht).forEach(t=>{e.removeEventListener(t,n,l)})}function Gt(e,t,n,l){t.trim().split(Ht).forEach(t=>{e.addEventListener(t,n,l)})}function Qt(e,t,n,l){Gt(e,t,n,Object.assign(Object.assign({},l),{once:!0}))}const Xt={bubbles:!0,cancelable:!0,composed:!0};const Yt=Promise.resolve();function Jt(e){const{documentElement:t}=e.ownerDocument,n=e.getBoundingClientRect();return{left:n.left+(Xe.pageXOffset-t.clientLeft),top:n.top+(Xe.pageYOffset-t.clientTop)}}const Zt=/deg|g?rad|turn$/i;function en(e){const t=parseFloat(e)||0;if(0!==t){const[n="rad"]=String(e).match(Zt)||[];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 tn="contain";function nn(e,t=tn){const{aspectRatio:n}=e;let{width:l,height:r}=e;const a=Dt(l),i=Dt(r);if(a&&i){const e=r*n;t===tn&&e>l||"cover"===t&&e<l?r=l/n:l=r*n}else a?r=l/n:i&&(l=r*n);return{width:l,height:r}}function ln(e,...t){if(0===t.length)return e;const[n,l,r,a,i,o]=e,[s,c,u,d,b,m]=t[0];return ln(e=[n*s+r*c,l*s+a*c,n*u+r*d,l*u+a*d,n*b+r*m+i,l*b+a*m+o],...t.slice(1))}const rn=/left|top|width|height/i,an="open",on=/* @__PURE__ */new WeakMap,sn=/* @__PURE__ */new WeakMap,cn=/* @__PURE__ */new Map,un=Xe.document&&Array.isArray(Xe.document.adoptedStyleSheets)&&"replaceSync"in Xe.CSSStyleSheet.prototype;class dn extends HTMLElement{get $sharedStyle(){return(this.themeColor?`:host{--theme-color: ${this.themeColor};}`:"")+":host([hidden]){display:none!important}"}constructor(){var e,t;super(),this.shadowRootMode=an,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&&cn.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 l=Vt(e);let r=n;switch(typeof this[l]){case"boolean":r=null!==n&&"false"!==n;break;case"number":r=Number(n)}switch(this[l]=r,e){case"theme-color":{const e=sn.get(this),t=this.$sharedStyle;e&&t&&(un?e.replaceSync(t):e.textContent=t);break}}}$propertyChangedCallback(e,t,n){if(!Object.is(n,t))switch(e=qt(e),typeof n){case"boolean":!0===n?this.hasAttribute(e)||this.setAttribute(e,""):this.removeAttribute(e);break;case"number":n=Mt(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=Vt(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 l=n;n=e,this.$propertyChangedCallback(t,l,e)}})});const e=this.shadowRoot||this.attachShadow({mode:this.shadowRootMode||an});if(on.set(this,e),sn.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(){sn.has(this)&&sn.delete(this),on.has(this)&&on.delete(this)}$getTagNameOf(e){var t;return null!==(t=cn.get(e))&&void 0!==t?t:e}$setStyles(e){return Object.keys(e).forEach(t=>{let n=e[t];Pt(n)&&(n=0!==n&&rn.test(t)?`${n}px`:String(n)),this.style[t]=n}),this}$getShadowRoot(){return this.shadowRoot||on.get(this)}$addStyles(e){let t;const n=this.$getShadowRoot();return un?(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,l){return e.dispatchEvent(new CustomEvent(t,Object.assign(Object.assign(Object.assign({},Xt),{detail:n}),l)))}(this,e,t,n)}$nextTick(e){return function(e,t){return t?Yt.then(e?t.bind(e):t):Yt}(this,e)}static $define(e,t){Ot(e)&&(t=e,e=""),e||(e=this.$name||this.name),e=qt(e),Qe&&Xe.customElements&&!Xe.customElements.get(e)&&customElements.define(e,this,t)}}dn.$version="2.1.0";class bn extends dn{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=mt,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),Gt(this,kt,this.$onPointerDown)),this.$onPointerMove||(this.$onPointerMove=this.$handlePointerMove.bind(this),Gt(this.ownerDocument,Ct,this.$onPointerMove)),this.$onPointerUp||(this.$onPointerUp=this.$handlePointerUp.bind(this),Gt(this.ownerDocument,Nt,this.$onPointerUp)),this.$onWheel||(this.$onWheel=this.$handleWheel.bind(this),Gt(this,_t,this.$onWheel,{passive:!1,capture:!0}))}$unbind(){this.$onPointerDown&&(Kt(this,kt,this.$onPointerDown),this.$onPointerDown=null),this.$onPointerMove&&(Kt(this.ownerDocument,Ct,this.$onPointerMove),this.$onPointerMove=null),this.$onPointerUp&&(Kt(this.ownerDocument,Nt,this.$onPointerUp),this.$onPointerUp=null),this.$onWheel&&(Kt(this,_t,this.$onWheel,{capture:!0}),this.$onWheel=null)}$handlePointerDown(e){const{buttons:t,button:n,type:l}=e;if(this.disabled||("pointerdown"===l&&"mouse"===e.pointerType||"mousedown"===l)&&(Pt(t)&&1!==t||Pt(n)&&0!==n||e.ctrlKey))return;const{$pointers:r}=this;let a="";if(e.changedTouches)Array.from(e.changedTouches).forEach(({identifier:e,pageX:t,pageY:n})=>{r.set(e,{startX:t,startY:n,endX:t,endY:n})});else{const{pointerId:t=0,pageX:n,pageY:l}=e;r.set(t,{startX:n,startY:l,endX:n,endY:l})}r.size>1?a=bt:Ut(e.target)&&(a=e.target.action||e.target.getAttribute("action")||""),!1!==this.$emit(It,{action:a,relatedEvent:e})&&(e.preventDefault(),this.$action=a,this.style.willChange="transform")}$handlePointerMove(e){const{$action:t,$pointers:n}=this;if(this.disabled||t===mt||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:l})=>{const r=n.get(e);r&&Object.assign(r,{endX:t,endY:l})});else{const{pointerId:t=0,pageX:l,pageY:r}=e,a=n.get(t);a&&Object.assign(a,{endX:l,endY:r})}const l={action:t,relatedEvent:e};if(t===bt){const t=new Map(n);let r=0,a=0,i=0,o=0,s=e.pageX,c=e.pageY;n.forEach((e,n)=>{t.delete(n),t.forEach(t=>{let n=t.startX-e.startX,l=t.startY-e.startY,u=t.endX-e.endX,d=t.endY-e.endY,b=0,m=0,h=0,p=0;if(0===n?l<0?h=2*Math.PI:l>0&&(h=Math.PI):n>0?h=Math.PI/2+Math.atan(l/n):n<0&&(h=1.5*Math.PI+Math.atan(l/n)),0===u?d<0?p=2*Math.PI:d>0&&(p=Math.PI):u>0?p=Math.PI/2+Math.atan(d/u):u<0&&(p=1.5*Math.PI+Math.atan(d/u)),p>0||h>0){const n=p-h,l=Math.abs(n);l>r&&(r=l,i=n,s=(e.startX+t.startX)/2,c=(e.startY+t.startY)/2)}if(n=Math.abs(n),l=Math.abs(l),u=Math.abs(u),d=Math.abs(d),n>0&&l>0?b=Math.sqrt(n*n+l*l):n>0?b=n:l>0&&(b=l),u>0&&d>0?m=Math.sqrt(u*u+d*d):u>0?m=u:d>0&&(m=d),b>0&&m>0){const n=(m-b)/b,l=Math.abs(n);l>a&&(a=l,o=n,s=(e.startX+t.startX)/2,c=(e.startY+t.startY)/2)}})});const u=r>0,d=a>0;u&&d?(l.rotate=i,l.scale=o,l.centerX=s,l.centerY=c):u?(l.action=dt,l.rotate=i,l.centerX=s,l.centerY=c):d?(l.action=ut,l.scale=o,l.centerX=s,l.centerY=c):l.action=mt}else{const[e]=Array.from(n.values());Object.assign(l,e)}n.forEach(e=>{e.startX=e.endX,e.startY=e.endY}),l.action!==mt&&this.$emit(zt,l,{cancelable:!1})}$handlePointerUp(e){const{$action:t,$pointers:n}=this;if(!this.disabled&&t!==mt&&!1!==this.$emit(Tt,{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=mt)}}$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(zt,{action:ut,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 l=document.createElement("canvas");let r=this.offsetWidth,a=this.offsetHeight,i=1;Ft(e)&&(Dt(e.width)||Dt(e.height))&&(({width:r,height:a}=nn({aspectRatio:r/a,width:e.width,height:e.height})),i=r/this.offsetWidth),l.width=r,l.height=a;const o=this.querySelector(this.$getTagNameOf(rt));o?o.$ready().then(n=>{const s=l.getContext("2d");if(s){const[t,c,u,d,b,m]=o.$getTransform();let h=b,p=m,f=n.naturalWidth,g=n.naturalHeight;1!==i&&(h*=i,p*=i,f*=i,g*=i);const y=f/2,v=g/2;s.fillStyle="transparent",s.fillRect(0,0,r,a),Ft(e)&&jt(e.beforeDraw)&&e.beforeDraw.call(this,s,l),s.save(),s.translate(y,v),s.transform(t,c,u,d,h,p),s.translate(-y,-v),s.drawImage(n,0,0,f,g),s.restore()}t(l)}).catch(n):t(l)})}}bn.$name=et,bn.$version="2.1.0";const mn=/* @__PURE__ */new WeakMap,hn=["alt","crossorigin","decoding","elementtiming","fetchpriority","loading","referrerpolicy","sizes","src","srcset"];class pn extends dn{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){mn.set(this,e)}get $canvas(){return mn.get(this)}static get observedAttributes(){return super.observedAttributes.concat(hn,["initial-center-size","rotatable","scalable","skewable","translatable"])}attributeChangedCallback(e,t,n){Object.is(n,t)||(super.attributeChangedCallback(e,t,n),hn.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(et));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),Gt(t,It,this.$onCanvasActionStart),Gt(t,Tt,this.$onCanvasActionEnd),Gt(t,zt,this.$onCanvasAction)),this.$onLoad=this.$handleLoad.bind(this),Gt(e,$t,this.$onLoad),this.$getShadowRoot().appendChild(e)}disconnectedCallback(){const{$image:e,$canvas:t}=this;t&&(this.$onCanvasActionStart&&(Kt(t,It,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(Kt(t,Tt,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasAction&&(Kt(t,zt,this.$onCanvasAction),this.$onCanvasAction=null)),e&&this.$onLoad&&(Kt(e,$t,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:l}=n;switch(l!==bt||this.rotatable&&this.scalable||(l=this.rotatable?dt:this.scalable?ut:mt),l){case ct:if(this.translatable){let l=null;e&&(l=e.target.closest(this.$getTagNameOf(at))),l||(l=t.querySelector(this.$getTagNameOf(at))),l&&l.multiple&&!l.active&&(l=t.querySelector(`${this.$getTagNameOf(at)}[active]`)),l&&!l.hidden&&l.movable&&!l.dynamic&&this.$actionStartTarget&&l.contains(this.$actionStartTarget)||this.$move(n.endX-n.startX,n.endY-n.startY)}break;case dt:if(this.rotatable)if(e){const{x:t,y:l}=this.getBoundingClientRect();this.$rotate(n.rotate,e.clientX-t,e.clientY-l)}else this.$rotate(n.rotate);break;case ut:if(this.scalable)if(e){const t=e.target.closest(this.$getTagNameOf(at));if(!t||!t.zoomable||t.zoomable&&t.dynamic){const{x:t,y:l}=this.getBoundingClientRect();this.$zoom(n.scale,e.clientX-t,e.clientY-l)}}else this.$zoom(n.scale);break;case bt:if(this.rotatable&&this.scalable){const{rotate:t}=n;let{scale:l}=n;l<0?l=1/(1-l):l+=1;const r=Math.cos(t),a=Math.sin(t),[i,o,s,c]=[r*l,a*l,-a*l,r*l];if(e){const t=this.getBoundingClientRect(),n=e.clientX-t.x,l=e.clientY-t.y,[r,a,u,d]=this.$matrix,b=n-t.width/2,m=l-t.height/2,h=(b*d-u*m)/(r*d-u*a),p=(m*r-a*b)/(r*d-u*a);this.$transform(i,o,s,c,h*(1-i)+p*s,p*(1-c)+h*o)}else this.$transform(i,o,s,c,0,0)}}}}$ready(e){const{$image:t}=this,n=new Promise((e,n)=>{const l=new Error("Failed to load the image source");if(t.complete)t.naturalWidth>0&&t.naturalHeight>0?e(t):n(l);else{const r=()=>{Kt(t,St,a),setTimeout(()=>{e(t)})},a=()=>{Kt(t,$t,r),n(l)};Qt(t,$t,r),Qt(t,St,a)}});return jt(e)&&n.then(t=>(e(t),t)),n}$center(e){const{parentElement:t}=this;if(!t)return this;const n=t.getBoundingClientRect(),l=n.width,r=n.height,{x:a,y:i,width:o,height:s}=this.getBoundingClientRect(),c=a+o/2,u=i+s/2,d=n.x+l/2,b=n.y+r/2;if(this.$move(d-c,b-u),e&&(o!==l||s!==r)){const t=l/o,n=r/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&&Pt(e)&&Pt(t)){const[n,l,r,a]=this.$matrix,i=(e*a-r*t)/(n*a-r*l),o=(t*n-l*e)/(n*a-r*l);this.$translate(i,o)}return this}$moveTo(e,t=e){if(this.translatable&&Pt(e)&&Pt(t)){const[n,l,r,a]=this.$matrix,i=(e*a-r*t)/(n*a-r*l),o=(t*n-l*e)/(n*a-r*l);this.$setTransform(n,l,r,a,i,o)}return this}$rotate(e,t,n){if(this.rotatable){const l=en(e),r=Math.cos(l),a=Math.sin(l),[i,o,s,c]=[r,a,-a,r];if(Pt(t)&&Pt(n)){const[e,l,r,a]=this.$matrix,{width:u,height:d}=this.getBoundingClientRect(),b=t-u/2,m=n-d/2,h=(b*a-r*m)/(e*a-r*l),p=(m*e-l*b)/(e*a-r*l);this.$transform(i,o,s,c,h*(1-i)-p*s,p*(1-c)-h*o)}else this.$transform(i,o,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,Pt(t)&&Pt(n)){const[l,r,a,i]=this.$matrix,{width:o,height:s}=this.getBoundingClientRect(),c=t-o/2,u=n-s/2,d=(c*i-a*u)/(l*i-a*r),b=(u*l-r*c)/(l*i-a*r);this.$transform(e,0,0,e,d*(1-e),b*(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=en(e),l=en(t);this.$transform(1,Math.tan(l),Math.tan(n),1,0,0)}return this}$translate(e,t=e){return this.translatable&&Pt(e)&&Pt(t)&&this.$transform(1,0,0,1,e,t),this}$transform(e,t,n,l,r,a){return Pt(e)&&Pt(t)&&Pt(n)&&Pt(l)&&Pt(r)&&Pt(a)?this.$setTransform(ln(this.$matrix,[e,t,n,l,r,a])):this}$setTransform(e,t,n,l,r,a){if((this.rotatable||this.scalable||this.skewable||this.translatable)&&(Array.isArray(e)&&([e,t,n,l,r,a]=e),Pt(e)&&Pt(t)&&Pt(n)&&Pt(l)&&Pt(r)&&Pt(a))){const i=[...this.$matrix],o=[e,t,n,l,r,a];if(!1===this.$emit(Lt,{matrix:o,oldMatrix:i}))return this;this.$matrix=o,this.style.transform=`matrix(${o.join(", ")})`}return this}$getTransform(){return this.$matrix.slice()}$resetTransform(){return this.$setTransform([1,0,0,1,0,0])}}pn.$name=rt,pn.$version="2.1.0";const fn=/* @__PURE__ */new WeakMap;class gn extends dn{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){fn.set(this,e)}get $canvas(){return fn.get(this)}static get observedAttributes(){return super.observedAttributes.concat(["height","width","x","y"])}connectedCallback(){super.connectedCallback();const e=this.closest(this.$getTagNameOf(et));if(e){this.$canvas=e,this.style.position="absolute";const t=e.querySelector(this.$getTagNameOf(at));t&&(this.$onCanvasActionStart=e=>{t.hidden&&e.detail.action===st&&(this.hidden=!1)},this.$onCanvasActionEnd=e=>{t.hidden&&e.detail.action===st&&(this.hidden=!0)},this.$onSelectionChange=e=>{const{x:n,y:l,width:r,height:a}=e.defaultPrevented?t:e.detail;this.$change(n,l,r,a),(t.hidden||0===n&&0===l&&0===r&&0===a)&&(this.hidden=!0)},Gt(e,It,this.$onCanvasActionStart),Gt(e,Tt,this.$onCanvasActionEnd),Gt(e,At,this.$onSelectionChange))}this.$render()}disconnectedCallback(){const{$canvas:e}=this;e&&(this.$onCanvasActionStart&&(Kt(e,It,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(Kt(e,Tt,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onSelectionChange&&(Kt(e,At,this.$onSelectionChange),this.$onSelectionChange=null)),super.disconnectedCallback()}$change(e,t,n=this.width,l=this.height){return Pt(e)&&Pt(t)&&Pt(n)&&Pt(l)&&(e!==this.x||t!==this.y||n!==this.width||l!==this.height)?(this.hidden&&(this.hidden=!1),this.x=e,this.y=t,this.width=n,this.height=l,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:Xe.innerWidth})}}gn.$name=it,gn.$version="2.1.0";class yn extends dn{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=mt,this.plain=!1,this.slottable=!1,this.themeColor="rgba(51, 153, 255, 0.5)"}static get observedAttributes(){return super.observedAttributes.concat(["action","plain"])}}yn.$name=lt,yn.$version="2.1.0";const vn=/* @__PURE__ */new WeakMap;class wn extends dn{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){vn.set(this,e)}get $canvas(){return vn.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(()=>{Dt(n)&&n<=1&&this.$initSelection(!0,!0)});break;case"keyboard":this.$nextTick(()=>{this.$canvas&&(n?this.$onDocumentKeyDown||(this.$onDocumentKeyDown=this.$handleKeyDown.bind(this),Gt(this.ownerDocument,Et,this.$onDocumentKeyDown)):this.$onDocumentKeyDown&&(Kt(this.ownerDocument,Et,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(At,{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(et));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),Gt(e,It,this.$onCanvasActionStart),Gt(e,Tt,this.$onCanvasActionEnd),Gt(e,zt,this.$onCanvasAction)):this.$render()}disconnectedCallback(){const{$canvas:e}=this;e&&(this.$onCanvasActionStart&&(Kt(e,It,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(Kt(e,Tt,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasAction&&(Kt(e,zt,this.$onCanvasAction),this.$onCanvasAction=null)),super.disconnectedCallback()}$getSelections(){let e=[];return this.parentElement&&(e=Array.from(this.parentElement.querySelectorAll(this.$getTagNameOf(at)))),e}$initSelection(e=!1,t=!1){const{initialCoverage:n,parentElement:l}=this;if(Dt(n)&&l){const r=this.aspectRatio||this.initialAspectRatio;let a=(t?0:this.width)||l.offsetWidth*n,i=(t?0:this.height)||l.offsetHeight*n;Dt(r)&&({width:a,height:i}=nn({aspectRatio:r,width:a,height:i})),this.$change(this.x,this.y,a,i),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),l=t[n+1]||t[n-1];l&&(e.active=!1,this.parentElement.removeChild(e),l.active=!0,l.$emit(At,{x:l.x,y:l.y,width:l.width,height:l.height}))}else this.$clear()}}$handleActionStart(e){var t,n;const l=null===(n=null===(t=e.detail)||void 0===t?void 0:t.relatedEvent)||void 0===n?void 0:n.target;this.$action="",this.$actionStartTarget=l,!this.hidden&&this.multiple&&!this.active&&l===this&&this.parentElement&&(this.$getSelections().forEach(e=>{e.active=!1}),this.active=!0,this.$emit(At,{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:l}=n;let{action:r}=n;const a=l?function(e){if("function"==typeof e.composedPath)return e.composedPath().find(Ut)||e.target;return e.target}(l):null;if(!r&&this.multiple&&(r=this.$action||(null==a?void 0:a.action),this.$action=r),!r||this.hidden&&r!==st||this.multiple&&!this.active&&r!==ut)return;const{width:i,height:o}=this;let s=n.endX-n.startX,c=n.endY-n.startY,{aspectRatio:u}=this;switch(!Dt(u)&&l.shiftKey&&(u=Dt(i)&&Dt(o)?i/o:1),r){case st:if(0!==s||0!==c){0===s?s=c:0===c&&(c=s);const{$canvas:e}=this,l=Jt(t);(this.multiple&&!this.hidden?this.$createSelection():this).$change(n.startX-l.left,n.startY-l.top,Math.abs(s),Math.abs(c),u),s<0?c<0?r=vt:c>0&&(r=xt):s>0&&(c<0?r=yt:c>0&&(r=wt)),e&&(e.$action=r)}break;case ct:this.movable&&(this.dynamic||this.$actionStartTarget&&this.contains(this.$actionStartTarget))&&this.$move(s,c);break;case ut:if(l&&this.zoomable&&(this.dynamic||this.contains(l.target))){const e=Jt(t);this.$zoom(n.scale,l.pageX-e.left,l.pageY-e.top)}break;default:this.$resize(r,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,l=this.aspectRatio){if(!this.resizable)return this;const r=Dt(l),{$canvas:a}=this;let{x:i,y:o,width:s,height:c}=this;switch(e){case ht:o+=n,c-=n,c<0&&(e=ft,c=-c,o-=c),r&&(i+=(t=n*l)/2,s-=t,s<0&&(s=-s,i-=s));break;case pt:s+=t,s<0&&(e=gt,s=-s,i-=s),r&&(o-=(n=t/l)/2,c+=n,c<0&&(c=-c,o-=c));break;case ft:c+=n,c<0&&(e=ht,c=-c,o-=c),r&&(i-=(t=n*l)/2,s+=t,s<0&&(s=-s,i-=s));break;case gt:i+=t,s-=t,s<0&&(e=pt,s=-s,i-=s),r&&(o+=(n=t/l)/2,c-=n,c<0&&(c=-c,o-=c));break;case yt:r&&(n=-t/l),o+=n,c-=n,s+=t,s<0&&c<0?(e=xt,s=-s,c=-c,i-=s,o-=c):s<0?(e=vt,s=-s,i-=s):c<0&&(e=wt,c=-c,o-=c);break;case vt:r&&(n=t/l),i+=t,o+=n,s-=t,c-=n,s<0&&c<0?(e=wt,s=-s,c=-c,i-=s,o-=c):s<0?(e=yt,s=-s,i-=s):c<0&&(e=xt,c=-c,o-=c);break;case wt:r&&(n=t/l),s+=t,c+=n,s<0&&c<0?(e=vt,s=-s,c=-c,i-=s,o-=c):s<0?(e=xt,s=-s,i-=s):c<0&&(e=yt,c=-c,o-=c);break;case xt:r&&(n=-t/l),i+=t,s-=t,c+=n,s<0&&c<0?(e=yt,s=-s,c=-c,i-=s,o-=c):s<0?(e=wt,s=-s,i-=s):c<0&&(e=vt,c=-c,o-=c)}return a&&a.$setAction(e),this.$change(i,o,s,c)}$zoom(e,t,n){if(!this.zoomable||0===e)return this;e<0?e=1/(1-e):e+=1;const{width:l,height:r}=this,a=l*e,i=r*e;let o=this.x,s=this.y;return Pt(t)&&Pt(n)?(o-=(a-l)*((t-this.x)/l),s-=(i-r)*((n-this.y)/r)):(o-=(a-l)/2,s-=(i-r)/2),this.$change(o,s,a,i)}$change(e,t,n=this.width,l=this.height,r=this.aspectRatio,a=!1){return this.$changing||!Pt(e)||!Pt(t)||!Pt(n)||!Pt(l)||n<0||l<0?this:(Dt(r)&&({width:n,height:l}=nn({aspectRatio:r,width:n,height:l},"cover")),this.precise||(e=Math.round(e),t=Math.round(t),n=Math.round(n),l=Math.round(l)),e===this.x&&t===this.y&&n===this.width&&l===this.height&&Object.is(r,this.aspectRatio)&&!a?this:(this.hidden&&(this.hidden=!1),!1===this.$emit(At,{x:e,y:t,width:n,height:l})?this:(this.$changing=!0,this.x=e,this.y=t,this.width=n,this.height=l,this.$changing=!1,this.$render())))}$reset(){const{x:e,y:t,width:n,height:l}=this.$initialSelection;return this.$change(e,t,n,l)}$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 l=document.createElement("canvas");let{width:r,height:a}=this,i=1;if(Ft(e)&&(Dt(e.width)||Dt(e.height))&&(({width:r,height:a}=nn({aspectRatio:r/a,width:e.width,height:e.height})),i=r/this.width),l.width=r,l.height=a,!this.$canvas)return void t(l);const o=this.$canvas.querySelector(this.$getTagNameOf(rt));o?o.$ready().then(n=>{const s=l.getContext("2d");if(s){const[t,c,u,d,b,m]=o.$getTransform(),h=-this.x,p=-this.y,f=(h*d-u*p)/(t*d-u*c),g=(p*t-c*h)/(t*d-u*c);let y=t*f+u*g+b,v=c*f+d*g+m,w=n.naturalWidth,x=n.naturalHeight;1!==i&&(y*=i,v*=i,w*=i,x*=i);const k=w/2,C=x/2;s.fillStyle="transparent",s.fillRect(0,0,r,a),Ft(e)&&jt(e.beforeDraw)&&e.beforeDraw.call(this,s,l),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(l)}).catch(n):t(l)})}}wn.$name=at,wn.$version="2.1.0";class xn extends dn{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))}}xn.$name=nt,xn.$version="2.1.0";class kn extends dn{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"])}}kn.$name=tt,kn.$version="2.1.0";const Cn=/* @__PURE__ */new WeakMap,Nn=/* @__PURE__ */new WeakMap,Sn=/* @__PURE__ */new WeakMap,En=/* @__PURE__ */new WeakMap,$n="vertical";class _n extends dn{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=$n,this.selection="",this.slottable=!1}set $image(e){Nn.set(this,e)}get $image(){return Nn.get(this)}set $sourceImage(e){En.set(this,e)}get $sourceImage(){return En.get(this)}set $canvas(e){Cn.set(this,e)}get $canvas(){return Cn.get(this)}set $selection(e){Sn.set(this,e)}get $selection(){return Sn.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(at)),Ut(n)){this.$selection=n,this.$onSelectionChange=this.$handleSelectionChange.bind(this),Gt(n,At,this.$onSelectionChange);const e=n.closest(this.$getTagNameOf(et));if(e){this.$canvas=e;const t=e.querySelector(this.$getTagNameOf(rt));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),Gt(t.$image,$t,this.$onSourceImageLoad),Gt(t,Lt,this.$onSourceImageTransform))}this.$render()}}disconnectedCallback(){const{$selection:e,$sourceImage:t}=this;e&&this.$onSelectionChange&&(Kt(e,At,this.$onSelectionChange),this.$onSelectionChange=null),t&&this.$onSourceImageLoad&&(Kt(t.$image,$t,this.$onSourceImageLoad),this.$onSourceImageLoad=null),t&&this.$onSourceImageTransform&&(Kt(t,Lt,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"),l=t.getAttribute("src");l&&l!==n&&(e.setAttribute("src",l),e.$ready(()=>{this.$render()}))}$handleSourceImageTransform(e){this.$render(void 0,e.detail.matrix)}$render(e,t){const{$canvas:n,$selection:l}=this;e||l.hidden||(e=l),(!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:r,y:a,width:i,height:o}=e,s={},{clientWidth:c,clientHeight:u}=this;let d=c,b=u,m=NaN;switch(this.resize){case"both":m=1,d=i,b=o,s.width=i,s.height=o;break;case"horizontal":m=o>0?u/o:0,d=i*m,s.width=d;break;case $n:m=i>0?c/i:0,b=o*m,s.height=b;break;default:c>0?m=i>0?c/i:0:u>0&&(m=o>0?u/o:0)}this.$scale=m,this.$setStyles(s),this.$sourceImage&&setTimeout(()=>{this.$transformImageByOffset(null!=t?t:this.$sourceImage.$getTransform(),-r,-a)})}$transformImageByOffset(e,t,n){const{$image:l,$scale:r,$sourceImage:a}=this;if(a&&l&&r>=0){const[a,i,o,s,c,u]=e,d=(t*s-o*n)/(a*s-o*i),b=(n*a-i*t)/(a*s-o*i),m=a*d+o*b+c,h=i*d+s*b+u;l.$ready(e=>{this.$setStyles.call(l,{width:e.naturalWidth*r,height:e.naturalHeight*r})}),l.$setTransform(a,i,o,s,m*r,h*r)}}}function zn(){const[e,n]=t(!1),[l,r]=t(null),[a,i]=t(null),o=async(e,t)=>{if(!e||!t)return r("ID de asset y configuración de variante son requeridos"),null;n(!0),r(null),i(null);try{const n=await async function(e,{variant_name:t,width:n,height:r,crop_params:a,preset_aspect:i=null,preset_size:o=null,output_format:s="webp"}){try{const l=[{name:t,width:n,height:r,output_format:s,crop_params:a}];return i&&(l[0].preset_aspect=i),o&&(l[0].preset_size=o),H(await j({endpoint:`/assets/${e}/variants`,method:"POST",body:{variants:l,async:!1},basePath:G,useJWT:!0}))}catch(l){throw K(l)}}(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 i(n.result),n.result;throw new Error("No se pudo crear la variante")}catch(a){return console.error("Error creating variant:",a),r(a.message||"Error desconocido al crear variante"),null}finally{n(!1)}};return{createVariant:o,createCropVariant:async(e,t,n={})=>{const l={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 o(e,l)},createVariantFromBlob:async(e,t,a={})=>{if(!e||!t)return r("ID de asset y blob son requeridos"),null;n(!0),r(null),i(null);try{const n=await async function(e,t,n={}){try{const l=new FormData,r=n.format||"webp",a=`${n.name||"variant"}.${r}`;return l.append("file",t,a),l.append("variant_name",n.name||"variant"),l.append("width",String(n.width||0)),l.append("height",String(n.height||0)),l.append("output_format",n.format||"webp"),l.append("permanent_url",!1!==n.permanentUrl?"true":"false"),H(await j({endpoint:`/assets/${e}/variants/upload`,method:"POST",body:l,basePath:G,isFormData:!0,useJWT:!0}))}catch(l){throw K(l)}}(e,t,{name:a.name||`crop_${Date.now()}`,width:a.width||0,height:a.height||0,format:a.format||"webp"});if(n?.result)return i(n.result),n.result;throw new Error("No se pudo crear la variante")}catch(o){return console.error("Error creating variant from blob:",o),r(o.message||"Error desconocido al crear variante"),null}finally{n(!1)}},loading:e,error:l,createdVariant:a,reset:()=>{r(null),i(null)}}}_n.$name=ot,_n.$version="2.1.0",bn.$define(),kn.$define(),xn.$define(),yn.$define(),pn.$define(),wn.$define(),gn.$define(),_n.$define();class Tn{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,l,r,a)=>{if(!this.image)return!1;try{return this.image.$setTransform(e,t,n,l,r,a),!0}catch(i){return console.warn("Error setting transform:",i),!1}},resetZoom:()=>{if(!this.image)return!1;try{const e=this.image.$getTransform();if(!e)return!1;const[t,n,l,r,a,i]=e,o=Math.sqrt(t*t+n*n),s=Math.sqrt(l*l+r*r),c=t/o,u=n/o,d=l/s,b=r/s;return this.image.$setTransform(c,u,d,b,a,i),!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,l,r,a,i,o]=t,s=Math.sqrt(n*n+l*l),c=Math.sqrt(r*r+a*a),u=n/s*e,d=l/s*e,b=r/c*e,m=a/c*e;return this.image.$setTransform(u,d,b,m,i,o),!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 l=1-e,r=t.width*l/n.naturalWidth,a=t.height*l/n.naturalHeight,i=Math.min(r,a,1);return this.transform.setZoom(i)}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,l]=e.split("/").map(e=>parseFloat(e.trim()));if(isNaN(n)||isNaN(l)||0===l)return console.warn("Invalid aspect ratio format:",e),!1;t=n/l}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,l,r)=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$change(e,t,n,l,r),!0}catch(a){return console.warn("Error changing selection:",a),!1}},set:(e,t,n,l)=>{if(!this.selectionElement)return!1;try{return this.selectionElement.x=e,this.selectionElement.y=t,this.selectionElement.width=n,this.selectionElement.height=l,this.selectionElement.$render(),!0}catch(r){return console.warn("Error setting selection:",r),!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,l,r,a,i]=e;return this.transform.setTransform(-t,n,l,r,a,i)},flipVertical:()=>{const e=this.transform.getTransform();if(!e)return!1;const[t,n,l,r,a,i]=e;return this.transform.setTransform(t,n,l,-r,a,i)},setupInitialView:async(e={})=>{const{paspartuFactor:t=.85,retries:n=3,retryDelay:l=200}=e;return new Promise(e=>{const r=(a=0)=>{if(!this.isReady)return a<n?void setTimeout(()=>r(a+1),l):void e(!1);try{const i=this.canvasElement.getBoundingClientRect();let o=this.image.querySelector("img")||this.image;if(!o?.naturalWidth||!o?.naturalHeight)return a<n?void setTimeout(()=>r(a+1),l):(this.transform.center(),void e(!1));if(i.width>0&&i.height>0){const n=i.width*t/o.naturalWidth,l=i.height*t/o.naturalHeight,r=Math.min(n,l,1);this.transform.setTransform(r,0,0,r,0,0)?setTimeout(()=>{this.transform.center(),this.selection.center(),e(!0)},100):(this.transform.reset(),setTimeout(()=>{r<1&&this.transform.scale(r),setTimeout(()=>{this.transform.center(),this.selection.center(),e(!0)},100)},100))}else this.transform.center(),e(!1)}catch(i){console.warn("Error in setup:",i),this.transform.center(),e(!1)}};r()})},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:l,onActionStart:r,onActionMove:a,onActionEnd:i}=e,o=[];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),o.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),o.push(()=>{this.image&&this.image.removeEventListener("transform",e)})}if(this.canvasElement){if(l){const e=e=>l(e.detail);this.canvasElement.addEventListener("action",e),o.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("action",e)})}if(r){const e=e=>r(e.detail);this.canvasElement.addEventListener("actionstart",e),o.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionstart",e)})}if(a){const e=e=>a(e.detail);this.canvasElement.addEventListener("actionmove",e),o.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionmove",e)})}if(i){const e=e=>i(e.detail);this.canvasElement.addEventListener("actionend",e),o.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionend",e)})}}return()=>{o.forEach(e=>e())}}}async function In(e,t,n={}){const{format:l=null,originalFormat:r="webp",onSuccess:a=null,onError:i=null,accessibilityManager:o=null}=n;try{const n=window.limboCore?.config?.getGlobal(),i=l||n?.downloadFormat||r||"webp",c=`${t.split(".")[0]}.${i}`;if(o&&o.announce(`Descargando ${c}`),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,c),a&&a(c),o&&o.announce(`${c} descargado correctamente`),!0;let u;try{if(u=await fetch(e,{mode:"cors"}),!u.ok)throw new Error(`HTTP error! status: ${u.status}`)}catch(s){if(!e.startsWith("http"))throw s;{const t=(window.limboCore?.config?.getGlobal()||{}).prod?"https://limbo.lefebvre.es":"https://led-dev-limbo-dev.eu.els.local",n=window.limboCore?.apiClient?.token||"",l=`${t}/api/atenea/proxy?url=${encodeURIComponent(e)}`;if(u=await fetch(l,{credentials:"include",headers:{Authorization:`Bearer ${n}`}}),!u.ok)throw new Error(`Proxy error: ${u.status}`)}}const d=await u.blob();let b=d;const m=d.type;m!==`image/${"jpg"===i?"jpeg":i}`&&function(e){return["webp","jpeg","jpg","png"].includes(e.toLowerCase())}(i)&&(b=await async function(e,t){return new Promise((n,l)=>{const r=new Image,a=URL.createObjectURL(e);r.onload=()=>{try{const l=document.createElement("canvas");l.width=r.width,l.height=r.height;l.getContext("2d").drawImage(r,0,0);const i=`image/${"jpg"===t?"jpeg":t}`,o="png"===t?void 0:.92;l.toBlob(t=>{URL.revokeObjectURL(a),n(t||e)},i,o)}catch(l){URL.revokeObjectURL(a),n(e)}},r.onerror=()=>{URL.revokeObjectURL(a),n(e)},r.src=a})}(d,i));const h=window.URL.createObjectURL(b),p=document.createElement("a");return p.href=h,p.download=c,p.style.display="none",document.body.appendChild(p),p.click(),setTimeout(()=>{window.URL.revokeObjectURL(h),document.body.removeChild(p)},100),a&&a(c),o&&o.announce(`${c} descargado correctamente`),!0}catch(c){return console.error("Error downloading image:",c),i&&i(c),o&&o.announce(`Error al descargar la imagen: ${c.message}`),!1}}const An=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:In,downloadImage:In},Symbol.toStringTag,{value:"Module"}));function Ln({image:e,onSave:a,onCancel:o,onDelete:d,onError:b=null,deleting:m=!1,onVariantCreated:h=null,onUpload:p=null,uploading:f=!1,cropperConfig:g=null}){const[y,v]=t(!1),[w,x]=t(null),[k,C]=t(!1),[N,S]=t(!0),[E,$]=t(!0),[_,z]=t({x:20,y:100}),[T,I]=t(!1),[A,L]=t({x:0,y:0}),[M,P]=t(!1),[D,O]=t(!0),[R,F]=t(!1),[j,U]=t({horizontal:!1,vertical:!1}),[B,q]=t(!1),[W,V]=t(!1),[H,K]=t(!1),[G,Q]=t(!1),[X]=t(()=>{if(!e||!e.filename)return"image";const[t]=e.filename.split(".");return t}),Y=i(()=>{if(g)return{mandatoryCrops:g.mandatoryCrops||[],allowCustomCrops:!1!==g.allowAdditionalCrops,showDimensionInputs:!0===g.showDimensionInputs,maxCrops:g.maxCrops||null,localCropsOnly:!0===g.localCropsOnly,existingCrops:g.existingCrops||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,localCropsOnly:!0===e.cropper?.localCropsOnly,existingCrops:e.cropper?.existingCrops||null}},[g]),[J,Z]=t(()=>Y.mandatoryCrops.length>0?Y.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),format:e.format||null,savedState:null})):[{id:"crop-default-0",label:X,width:e.width||1920,height:e.height||1080,required:!1,isCustom:!0,confirmed:!1,savedState:null}]),[ee,te]=t(0),ne=J[ee],le=i(()=>ne&&ne.width&&ne.height?ne.width/ne.height:"",[ne]),re=i(()=>{const e=50;if(!le||""===le)return{minWidth:e,minHeight:e};if(le>=1){return{minWidth:e,minHeight:e/le}}return{minWidth:e*le,minHeight:e}},[le]),[ae,ie]=t(!1),[oe,se]=t([]),[ue,de]=t(null),be=window.limboCore?.accessibilityManager,{createVariantFromBlob:me,loading:he,error:pe}=zn(),fe=((e,a={})=>{const i=r(null),o=r(null),s=r(null),c=r(null),[u,d]=t(null),[b,m]=t(null),[h,p]=t(!1),[f,g]=t(!0),[y,v]=t(0),w={aspectRatio:"",shade:!0,paspartuFactor:.85,...a};n(()=>{i.current&&o.current&&s.current&&(c.current=new Tn(i,o,s),p(!0))},[]),n(()=>{if(c.current)return c.current.setupEventListeners({onSelectionChange:e=>{d(e)},onImageTransform:()=>{v(e=>e+1)}})},[h]),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();g(e);const t=o.current?.querySelector("img")||o.current;t?.naturalWidth&&t?.naturalHeight&&m({naturalWidth:t.naturalWidth,naturalHeight:t.naturalHeight,currentWidth:t.width,currentHeight:t.height})})()},[e]),n(()=>{c.current&&h&&c.current.selection.setAspectRatio(w.aspectRatio)},[w.aspectRatio,h]),n(()=>{c.current&&h&&c.current.canvas.setBackground(w.shade)},[w.shade,h]);const x=l(()=>({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=l(()=>({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=l(()=>({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:i,imageRef:o,selectionRef:s},state:{cropData:u,imageInfo:b,isReady:h,canExport:f,transformVersion:y},transform:x(),selection:k(),utils:C(),manager:c.current}})(e,{aspectRatio:le||null,showGrid:N,shade:E,initialCoverage:.5,paspartuFactor:.85}),{refs:ge,state:ye,transform:ve,selection:we,utils:xe}=fe,{canvasRef:ke,imageRef:Ce,selectionRef:Ne}=ge,{cropData:Se,imageInfo:Ee,canExport:$e,transformVersion:_e}=ye,ze=i(()=>Ee||{naturalWidth:e.width||1920,naturalHeight:e.height||1080,currentWidth:e.width||1920,currentHeight:e.height||1080},[Ee,e.width,e.height]),Te=l(()=>S(e=>!e),[]),Ie=l(()=>$(e=>!e),[]),Ae=l(()=>V(e=>!e),[]),Le=l(()=>K(e=>!e),[]),Me=l(()=>Q(e=>!e),[]),De=l(()=>ve.center(),[ve]),Oe=l(()=>we.center(),[we]),Re=l(()=>we.reset(),[we]),Fe=l((e,t)=>ve.move(e,t),[ve]),je=l(e=>ve.zoom(e),[ve]),Ue=l(e=>ve.rotate(e),[ve]),Be=l(e=>{we.setCoverage(e)},[we]),qe=l(()=>{U(e=>{const t=!e.horizontal;return ve.flipHorizontal(),{...e,horizontal:t}})},[ve]),We=l(()=>{U(e=>{const t=!e.vertical;return ve.flipVertical(),{...e,vertical:t}})},[ve]),Ve=l(()=>{if(!fe.manager||!ye.isReady)return null;try{const e=Se?{...Se}:null;let t=null;if(Ne.current){const e=Ne.current;t={x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0}}let n=null;if(Ce.current){const e=Ce.current.$getTransform?.();e&&Array.isArray(e)&&(n=[...e])}const l={cropData:e,selectorState:t,imageTransform:n,flipState:{horizontal:j.horizontal,vertical:j.vertical}};return console.log(`[CropperView] 💾 Guardando estado del crop ${ee}:`,l),Z(e=>e.map((e,t)=>t===ee?{...e,savedState:l}:e)),l}catch(e){return console.warn("Error saving crop state:",e),null}},[fe.manager,ye.isReady,Se,j,ee,Ce,Ne]),He=l(e=>{const t=J[e];if(!t||!t.savedState)return console.log(`[CropperView] ℹ️ No hay estado guardado para crop ${e}, centrando...`),void setTimeout(()=>{De(),setTimeout(()=>Oe(),100)},100);if(fe.manager&&ye.isReady)try{const{savedState:n}=t;if(console.log(`[CropperView] ♻️ Restaurando estado del crop ${e}:`,n),n.imageTransform&&Ce.current&&Array.isArray(n.imageTransform)&&setTimeout(()=>{if(Ce.current&&Ce.current.$setTransform){const[e,t,l,r,a,i]=n.imageTransform;Ce.current.$setTransform(e,t,l,r,a,i),console.log(`[CropperView] ✅ Imagen restaurada: transform(${e.toFixed(2)}, ${t.toFixed(2)}, ${l.toFixed(2)}, ${r.toFixed(2)}, ${a.toFixed(0)}, ${i.toFixed(0)})`)}},100),n.selectorState&&Ne.current){const{x:e,y:t,width:l,height:r}=n.selectorState;setTimeout(()=>{Ne.current&&(Ne.current.x=e,Ne.current.y=t,Ne.current.width=l,Ne.current.height=r,Ne.current.$render&&Ne.current.$render(),console.log(`[CropperView] ✅ Selector restaurado: ${l}×${r} en (${e}, ${t})`))},150)}n.flipState&&U({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(()=>{De(),setTimeout(()=>Oe(),100)},100)}else console.warn("Cropper not ready for state restoration")},[J,fe.manager,ye.isReady,De,Oe,Ne,Ce]),Ke=l(()=>{for(let e=0;e<J.length;e++){const t=J[e];if(!t.label||""===t.label.trim())return e}return-1},[J]),Ge=l(async e=>{e!==ee&&(F(!0),Ve(),await new Promise(e=>setTimeout(e,100)),te(e),await new Promise(e=>setTimeout(e,250)),He(e),await new Promise(e=>setTimeout(e,200)),F(!1))},[ee,Ve,He]),Qe=l(()=>{if(!Y.allowCustomCrops)return void alert("No se pueden añadir recortes personalizados en este modo.");const t={id:`crop-custom-${Date.now()}`,label:`Recorte ${J.length+1}`,width:e.width||1920,height:e.height||1080,required:!1,isCustom:!0,confirmed:!1,savedState:null};Z(e=>[...e,t]),be?.announce(`Nuevo recorte personalizado añadido: ${t.label}. Selecciónalo para editarlo.`)},[Y.allowCustomCrops,J.length,e.width,e.height,be]),Xe=l((e,t)=>{const n=parseInt(t,10);""===t||isNaN(n)||Z(t=>t.map((t,l)=>l===ee?{...t,[e]:n}:t))},[ee]),Ye=l(e=>{const t=ne[e];let n=100;if(ke.current&&Ee){const e=ke.current.getBoundingClientRect(),t=Math.min(e.width,e.height);n=Math.max(100,Math.round(.05*t))}const l=Math.max(n,Math.min(5e3,t));l!==t&&Z(t=>t.map((t,n)=>n===ee?{...t,[e]:l}:t));const r={...ne,[e]:l},a=r.width/r.height,i=we.getData?.();we.setAspectRatio(a),i&&void 0!==i.x&&setTimeout(()=>{we.set?.(i.x,i.y,i.width,i.height)},50)},[ee,ne,we,ke,Ee]),Je=l(e=>{Z(t=>t.map((t,n)=>n===ee?{...t,label:e}:t))},[ee]),Ze=l((e,t=null)=>{t=t||J[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=J[e];if(n.required)alert("No se puede eliminar un recorte obligatorio.");else if(1!==J.length){if(Z(t=>t.filter((t,n)=>n!==e)),e===ee){const t=Math.max(0,e-1);te(t)}else e<ee&&te(e=>e-1);be?.announce(`Recorte ${n.label} eliminado`)}else alert("Debe haber al menos un recorte.")},[J,ee,be]),et=l(async()=>{if(!$e)return null;try{const t=await we.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}},[$e,e.mime_type,we]),tt=l(async()=>{if(y)return v(!1),x(null),void C(!1);if($e){v(!0),C(!0);try{const e=await et();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.")},[$e,et,y]),nt=l(e=>{e.target.closest(".limbo-preview-modal-header")&&(I(!0),L({x:e.clientX-_.x,y:e.clientY-_.y}))},[_]),lt=l(e=>{T&&(e.preventDefault(),z({x:e.clientX-A.x,y:e.clientY-A.y}))},[T,A]),rt=l(()=>{I(!1)},[]),at=l(e=>{if(!e.target.closest(".limbo-preview-modal-header"))return;const t=e.touches[0];I(!0),L({x:t.clientX-_.x,y:t.clientY-_.y})},[_]),it=l(e=>{if(!T)return;e.preventDefault();const t=e.touches[0];z({x:t.clientX-A.x,y:t.clientY-A.y})},[T,A]),ot=l(()=>{I(!1)},[]);n(()=>{if(T)return document.addEventListener("mousemove",lt),document.addEventListener("mouseup",rt),document.addEventListener("touchmove",it,{passive:!1}),document.addEventListener("touchend",ot),()=>{document.removeEventListener("mousemove",lt),document.removeEventListener("mouseup",rt),document.removeEventListener("touchmove",it),document.removeEventListener("touchend",ot)}},[T,lt,rt,it,ot]),n(()=>{if(!M)return;const e=e=>{"Escape"===e.key&&P(!1)};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[M]);const st=l(async(t,n=null)=>{const l=J[t];if(!l)throw new Error(`Crop ${t} no encontrado`);if(!l.savedState&&t!==ee)throw new Error(`El recorte "${l.label}" aún no ha sido configurado`);const r={index:ee,imageTransform:Ce.current?.$getTransform?.(),selectorState:Ne.current?{x:Ne.current.x,y:Ne.current.y,width:Ne.current.width,height:Ne.current.height}:null};try{if(t!==ee&&l.savedState){if(console.log(`[CropperView] 🔄 Restaurando temporalmente crop ${t} para guardado...`),l.savedState.imageTransform&&Ce.current?.$setTransform){const[e,t,n,r,a,i]=l.savedState.imageTransform;Ce.current.$setTransform(e,t,n,r,a,i)}if(l.savedState.selectorState&&Ne.current){const{x:e,y:t,width:n,height:r}=l.savedState.selectorState;Ne.current.x=e,Ne.current.y=t,Ne.current.width=n,Ne.current.height=r,Ne.current.$render?.()}await new Promise(e=>setTimeout(e,100))}const r=Math.min(l.width,5e3),i=Math.min(l.height,5e3),o=await we.toCanvas({width:r,height:i,imageSmoothingEnabled:!0,imageSmoothingQuality:"high"});if(!o)throw new Error(`No se pudo generar el canvas para "${l.label}"`);const s=l.format||globalThis.downloadFormat||"webp",c="webp"===s?"image/webp":"png"===s?"image/png":"image/jpeg",u=.9,d=await new Promise((e,t)=>{o.toBlob(n=>{n?e(n):t(new Error("No se pudo convertir el canvas a blob"))},c,u)});console.log("[CropperView] Canvas convertido a blob:",{size:d.size,type:d.type,dimensions:`${r}x${i}`});const b=`${l.label||"crop"}_${r}_${i}`,m=n||e.id,f=!m||"string"==typeof m&&m.startsWith("external"),g=(f||Y.localCropsOnly)&&!p;if(f&&p&&!Y.localCropsOnly){console.log("[CropperView] 📤 Imagen externa con onUpload disponible, subiendo crop como nuevo asset...");try{const e=new File([d],`${b}.${s}`,{type:c}),t=await p(e);if(t&&(t.id||t.url)){console.log("[CropperView] ✅ Crop subido exitosamente:",t);const e=l.savedState||{selectorState:Ne.current?{x:Ne.current.x,y:Ne.current.y,width:Ne.current.width,height:Ne.current.height}:null,imageTransform:Ce.current?.$getTransform?.()||null,flipState:{horizontal:j.horizontal,vertical:j.vertical}},n={id:t.id||`uploaded-${Date.now()}`,name:b,filename:`${b}.${s}`,url:t.urlSigned||t.url,urlSigned:t.urlSigned||t.url,width:r,height:i,format:s,size:d.size,mime_type:c,isLocal:!1,originalAssetId:null,uploadedAssetId:t.id,cropState:e};return be?.announceSuccess(`Recorte guardado: ${b}`),n}}catch(a){console.error("[CropperView] ❌ Error subiendo crop, fallback a local:",a)}}if(g){console.log(`[CropperView] 🌐 Generando resultado local (isExternal: ${f}, localCropsOnly: ${Y.localCropsOnly})`);const e=URL.createObjectURL(d),t=l.savedState||{selectorState:Ne.current?{x:Ne.current.x,y:Ne.current.y,width:Ne.current.width,height:Ne.current.height}:null,imageTransform:Ce.current?.$getTransform?.()||null,flipState:{horizontal:j.horizontal,vertical:j.vertical}},n={id:`local-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:b,filename:`${b}.${s}`,url:e,urlSigned:e,width:r,height:i,format:s,size:d.size,mime_type:c,blob:d,isLocal:!0,originalAssetId:m||null,cropState:t};return be?.announceSuccess(`Recorte creado localmente: ${b}`),n}const y=l.savedState||{selectorState:Ne.current?{x:Ne.current.x,y:Ne.current.y,width:Ne.current.width,height:Ne.current.height}:null,imageTransform:Ce.current?.$getTransform?.()||null,flipState:{horizontal:j.horizontal,vertical:j.vertical}},v=await me(m,d,{name:b,width:r,height:i,format:s});if(v)return v.cropState=y,be?.announceSuccess(`Recorte creado: ${b}`),h?.(m,v),v;throw new Error("No se pudo crear la variante")}finally{if(t!==ee&&r.imageTransform&&Ce.current?.$setTransform){console.log(`[CropperView] ↩️ Restaurando estado original del crop ${r.index}...`);const[e,t,n,l,a,i]=r.imageTransform;if(Ce.current.$setTransform(e,t,n,l,a,i),r.selectorState&&Ne.current){const{x:e,y:t,width:n,height:l}=r.selectorState;Ne.current.x=e,Ne.current.y=t,Ne.current.width=n,Ne.current.height=l,Ne.current.$render?.()}}}},[J,ee,we,me,e.id,h,be,Ce,Ne]),ct=l(async()=>{if(!$e){const e="No se puede exportar el recorte por restricciones de CORS en la imagen original.";return be?.announceError(e),void alert(e)}if(!ye.isReady){const e="El cropper aún no está inicializado. Espera un momento e inténtalo de nuevo.";return be?.announceError(e),void alert(e)}Ve(),be?.announce("Creando recorte de la imagen");try{let t=e.id,n=null;if(e.file&&p){be?.announce("Subiendo imagen...");const l=await p(e.file);if(!l||!l.id)throw new Error("No se pudo subir la imagen al servidor");t=l.id,n=l,be?.announceSuccess("Imagen subida correctamente")}const l=await st(ee,t);l&&a(n?{crops:[l],asset:n}:l)}catch(t){console.warn("Error creating crop variant:",t);const e=t.message||"No se pudo crear el recorte. Inténtalo de nuevo.";be?.announceError(e),alert(e),b?.(t)}},[$e,ye.isReady,be,Ve,st,ee,a,b,e.file,e.id,p]),ut=l(async t=>{Ve(),be?.announce(`Guardando ${t.length} recortes...`);try{let l=e.id,r=null;if(e.file&&p){be?.announce("Subiendo imagen...");const t=await p(e.file);if(!t||!t.id)throw new Error("No se pudo subir la imagen al servidor");l=t.id,r=t,be?.announceSuccess("Imagen subida correctamente")}const i=[],o=[];for(const e of t)try{const t=await st(e,l);t&&i.push(t)}catch(n){o.push({crop:J[e]?.label||`Crop ${e}`,error:n.message})}if(i.length>0&&(be?.announceSuccess(`${i.length} recorte(s) guardado(s) correctamente`),a(r?{crops:i,asset:r}:i)),o.length>0){const e=`Errores al guardar algunos recortes:\n${o.map(e=>`- ${e.crop}: ${e.error}`).join("\n")}`;be?.announceError(e),alert(e)}}catch(n){const e=n.message||"Error al procesar los recortes";be?.announceError(e),alert(e),b?.(n)}},[Ve,st,J,be,a,e.file,e.id,p,b]),dt=l(async()=>{const e=Ke();if(-1!==e){const t=J[e];return alert(`El recorte "${t.label||t||"(sin nombre)"}" debe tener un nombre válido.`),void te(e)}const t=J.findIndex((e,t)=>e.required&&!e.savedState&&t!==ee);if(-1!==t){const e=J[t];return alert(`El recorte obligatorio "${e.label}" aún no ha sido configurado.\n\nPor favor, configura todos los recortes obligatorios antes de guardar.`),te(t),void be?.announce(`Recorte obligatorio "${e.label}" sin configurar. Por favor, configúralo.`,"assertive")}if(J.length>1){de("save");const e=J.map((e,t)=>({crop:e,index:t})).filter(({crop:e,index:t})=>e.required||e.savedState||t===ee).map(({index:e})=>e);return se(e),void ie(!0)}await ct()},[Ke,J,ct,ee,be]),bt=l(async t=>{const n=J[t];if(!n)throw new Error(`Crop ${t} no encontrado`);if(!n.savedState&&t!==ee)throw new Error(`El recorte "${n.label}" aún no ha sido configurado`);const l={index:ee,imageTransform:Ce.current?.$getTransform?.(),selectorState:Ne.current?{x:Ne.current.x,y:Ne.current.y,width:Ne.current.width,height:Ne.current.height}:null};try{if(t!==ee&&n.savedState){if(console.log(`[CropperView] 🔄 Restaurando temporalmente crop ${t} para descarga...`),n.savedState.imageTransform&&Ce.current?.$setTransform){const[e,t,l,r,a,i]=n.savedState.imageTransform;Ce.current.$setTransform(e,t,l,r,a,i)}if(n.savedState.selectorState&&Ne.current){const{x:e,y:t,width:l,height:r}=n.savedState.selectorState;Ne.current.x=e,Ne.current.y=t,Ne.current.width=l,Ne.current.height=r,Ne.current.$render?.()}await new Promise(e=>setTimeout(e,100))}const l=await we.toCanvas({width:n.width,height:n.height,imageSmoothingEnabled:!0,imageSmoothingQuality:"high"});if(!l)throw new Error(`No se pudo generar el canvas para "${n.label}"`);const r=l.toDataURL(`image/${globalThis.downloadFormat||e.mime_type.split("/")[1]||"webp"}`,.9),a=`${(n.label||"crop").replace(/\.[^/.]+$/,"").replace(/\s+/g,"-").trim()}_${n.width}_${n.height}`;return await In(r,a,{accessibilityManager:be,onSuccess:e=>{console.log(`✅ Descargado: ${e}`)},onError:e=>{throw new Error(`Error al descargar "${n.label}": ${e.message}`)}}),{crop:n.label,filename:a}}finally{if(t!==ee&&l.imageTransform&&Ce.current?.$setTransform){console.log(`[CropperView] ↩️ Restaurando estado original del crop ${l.index}...`);const[e,t,n,r,a,i]=l.imageTransform;if(Ce.current.$setTransform(e,t,n,r,a,i),l.selectorState&&Ne.current){const{x:e,y:t,width:n,height:r}=l.selectorState;Ne.current.x=e,Ne.current.y=t,Ne.current.width=n,Ne.current.height=r,Ne.current.$render?.()}}}},[J,ee,we,e.mime_type,be,Ce,Ne]),mt=l(async e=>{Ve(),be?.announce(`Descargando ${e.length} recortes...`);const t=[],n=[];for(const r of e)try{const e=await bt(r);e&&t.push(e)}catch(l){n.push({crop:J[r]?.label||`Crop ${r}`,error:l.message})}if(t.length>0&&be?.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")}`;be?.announceError(e),alert(e)}},[Ve,bt,J,be]),ht=l(async()=>{if(!$e){const e="No se puede descargar el recorte por restricciones de CORS en la imagen original.";return be?.announceError(e),void alert(e)}Ve(),be?.announce("Preparando descarga del recorte");try{await bt(ee),be?.announceSuccess("Recorte descargado correctamente")}catch(e){console.error("Error downloading crop:",e);const t=e.message||"Error al descargar el recorte";be?.announceError(t),alert(t)}},[$e,be,Ve,bt,ee]),pt=l(async()=>{const e=Ke();if(-1!==e){const t=J[e];return alert(`El recorte "${t.label||t||"(sin nombre)"}" debe tener un nombre válido.`),void te(e)}if(J.length>1){de("download");const e=J.map((e,t)=>({crop:e,index:t})).filter(({crop:e,index:t})=>e.savedState||t===ee).map(({index:e})=>e);return se(e),void ie(!0)}await ht()},[Ke,J,ht,ee]),ft=i(()=>!!e.file||(!e.id||!("string"!=typeof e.id||!e.id.startsWith("external"))),[e.file,e.id]),gt=l(async()=>{try{if(e.file&&p){be?.announce("Subiendo imagen original...");const t=await p(e.file);if(!t||!t.id)throw new Error("No se pudo subir la imagen al servidor");return be?.announceSuccess("Imagen guardada correctamente"),void a({asset:t,crops:[]})}if(ft){be?.announce("Conservando imagen original...");const t={id:`local-original-${Date.now()}`,name:e.filename||"original",filename:e.filename||"image.jpg",url:e.url,urlSigned:e.url,width:e.width||Ee?.naturalWidth||1920,height:e.height||Ee?.naturalHeight||1080,mime_type:e.mime_type||"image/jpeg",isLocal:!0,isOriginal:!0};return be?.announceSuccess("Imagen original conservada"),void a({crops:[t]})}if(e.id&&!e.id.startsWith("external")){be?.announce("Seleccionando imagen original...");const t={id:e.id,name:e.filename||"original",filename:e.filename||"image.jpg",url:e.url,urlSigned:e.urlSigned||e.url,width:e.width||Ee?.naturalWidth||1920,height:e.height||Ee?.naturalHeight||1080,mime_type:e.mime_type||"image/jpeg",isOriginal:!0};return be?.announceSuccess("Imagen original seleccionada"),void a({crops:[t],assetId:e.id})}o()}catch(t){console.error("Error guardando imagen original:",t);const e=t.message||"No se pudo guardar la imagen. Inténtalo de nuevo.";be?.announceError(e),alert(e),b?.(t)}},[e,Ee,p,o,a,b,be,ft]);return n(()=>{v(!1),x(null)},[e]),n(()=>{if(!fe.manager||!ye.isReady||!D)return;console.log("[CropperView] Carga inicial completada, centrando imagen y selector...");const e=Y.existingCrops?.[0],t=e?.cropState;setTimeout(()=>{De(),setTimeout(()=>{if(t){if(console.log("[CropperView] 🔄 Restaurando estado del crop existente:",t),t.imageTransform&&Ce.current?.$setTransform){const[e,n,l,r,a,i]=t.imageTransform;Ce.current.$setTransform(e,n,l,r,a,i),console.log("[CropperView] ✅ Transformación de imagen restaurada")}if(t.selectorState&&Ne.current){const{x:e,y:n,width:l,height:r}=t.selectorState;Ne.current.x=e,Ne.current.y=n,Ne.current.width=l,Ne.current.height=r,Ne.current.$render?.(),console.log("[CropperView] ✅ Posición del selector restaurada:",t.selectorState)}t.flipState&&(U(t.flipState),console.log("[CropperView] ✅ Estado de flip restaurado:",t.flipState))}else Oe();O(!1),console.log("[CropperView] Carga inicial finalizada")},100)},50)},[fe.manager,ye.isReady,D,De,Oe,Y.existingCrops]),n(()=>{fe.manager&&ye.isReady&&(le&&we.setAspectRatio(le),xe.setBackground(E))},[le,E,fe.manager,ye.isReady,we,xe]),n(()=>{if(!Ee||!ye.isReady||Y.mandatoryCrops.length>0)return;const e=J[0];if(e&&"crop-default-0"===e.id&&(1920===e.width||1080===e.height)){const t=Math.min(Ee.naturalWidth,5e3),n=Math.min(Ee.naturalHeight,5e3);Z([{...e,width:t,height:n}]),console.log(`[CropperView] Crop por defecto actualizado a ${t}×${n}px`)}},[Ee,ye.isReady,Y.mandatoryCrops.length,J]),n(()=>{if(!y||!$e)return;const e=setTimeout(async()=>{C(e=>!w&&!e||e);try{const e=await et();e&&x(e)}finally{C(!1)}},300);return()=>{clearTimeout(e),C(!1)}},[Se,_e,y,$e,et,le,j,w]),n(()=>{const e=ke.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)}},[ke]),e?/* @__PURE__ */c("div",{className:"limbo-cropper-view lb:px-2 lb:border-2 lb:border-gray-200/50 lb:rounded-lg lb:max-w-7xl lb:mx-auto lb:w-full lb:min-w-full lb:h-full lb:min-h-full lb:flex lb:flex-col",children:[
376
376
  /* @__PURE__ */c("div",{className:"limbo-cropper-header lb:flex lb:flex-row lb:justify-between lb:items-start lb:flex-wrap lb:mx-2 lb:py-2 lb:border-b lb:border-gray-200 lb:bg-white lb:z-10 lb:shrink-0 lb:lg:gap-2",children:[
377
377
  /* @__PURE__ */c("div",{className:"lb:flex-1 lb:min-w-fit lb:space-y-2 lb:max-w-fit",children:[
378
378
  /* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-2",children:[
@@ -634,10 +634,8 @@ return s("div",{className:"lb:flex lb:flex-col lb:items-center lb:justify-center
634
634
  /* @__PURE__ */s("div",{className:"lb:flex lb:space-x-1",children:a.map((n,a)=>/* @__PURE__ */s(e.Fragment,{children:"..."===n?/* @__PURE__ */s("span",{className:"lb:px-3 lb:py-2 lb:text-sm lb:text-gray-500",children:"..."}):/* @__PURE__ */s("button",{onClick:()=>(e=>{e!==t&&l(e)})(n),disabled:r,className:` lb:px-3 lb:py-2 lb:text-sm lb:font-medium lb:rounded-md lb:transition-colors lb:disabled:cursor-default lb:cursor-pointer ${n===t?"lb:bg-brand-blue-800 lb:text-white lb:border lb:border-brand-blue-1000":r?"lb:text-gray-400 lb:bg-gray-100 lb:cursor-not-allowed":"lb:text-gray-700 lb:bg-white lb:border lb:border-gray-300 lb:hover:bg-gray-50 lb:focus:ring-2 lb:focus:ring-blue-500"} `,children:n})},`page-${n}-${a}`))}),
635
635
  /* @__PURE__ */c("button",{onClick:()=>{t<n&&l(t+1)},disabled:r||t>=n,className:` lb:px-3 lb:py-2 lb:text-sm lb:font-medium lb:rounded-md lb:transition-colors lb:disabled:cursor-default lb:cursor-pointer ${r||t>=n?"lb:text-gray-400 lb:bg-gray-100 lb:cursor-not-allowed":"lb:text-gray-700 lb:bg-white lb:border lb:border-gray-300 lb:hover:bg-gray-50 lb:focus:ring-2 lb:focus:ring-blue-500"} `,children:["Siguiente ",
636
636
  /* @__PURE__ */s("span",{className:"icon icon-arrow-right icon--sm"})]})]})})}function Pn({text:e="Cargando..."}){/* @__PURE__ */
637
- return c("div",{className:"lb:flex lb:flex-col lb:items-center lb:justify-center lb:py-8 lb:text-gray-600",role:"status","aria-live":"polite","aria-label":e,children:[
638
- /* @__PURE__ */c("svg",{className:"lb:animate-spin lb:h-6 lb:w-6 lb:mb-2 lb:text-blue-500",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24","aria-hidden":"true",children:[
639
- /* @__PURE__ */s("circle",{className:"lb:opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),
640
- /* @__PURE__ */s("path",{className:"lb:opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8v8H4z"})]}),
637
+ return c("div",{className:"lb:absolute lb:inset-0 lb:bg-neutral-gray-1000/20 lb:z-10 lb:flex lb:flex-col lb:items-center lb:justify-center lb:py-8 lb:text-gray-600",role:"status","aria-live":"polite","aria-label":e,children:[
638
+ /* @__PURE__ */s("span",{className:"limbo-filter-searching","aria-hidden":"true",children:/* @__PURE__ */s("span",{className:"icon icon-spinner lb:animate-spin lb:min-w-7 lb:min-h-7"})}),
641
639
  /* @__PURE__ */s("p",{className:"lb:text-sm",id:"loader-text",children:e})]})}function Dn({isOpen:e,onClose:t}){return e?/* @__PURE__ */s("div",{className:"lb:fixed lb:inset-0 lb:bg-black lb:bg-opacity-50 lb:flex lb:items-center lb:justify-center lb:z-50",style:{zIndex:9999},children:/* @__PURE__ */c("div",{className:"lb:bg-white lb:rounded-lg lb:p-6 lb:max-w-md lb:mx-4 lb:shadow-xl",children:[
642
640
  /* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:mb-4",children:[
643
641
  /* @__PURE__ */s("svg",{className:"lb:w-6 lb:h-6 lb:text-red-1000 lb:mr-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"})}),
@@ -663,5 +661,5 @@ return c(u,{children:[d.showTabs&&"cropper"!=_&&/* @__PURE__ */s($,{tabs:de,acti
663
661
  /* @__PURE__ */s("div",{className:"lb:text-gray-400 lb:mb-4",children:/* @__PURE__ */s("svg",{className:"lb:w-16 lb:h-16 lb:mx-auto",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,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"})})}),
664
662
  /* @__PURE__ */s("p",{className:"lb:text-gray-600 lb:mb-4",children:"Selecciona una imagen de la galería para comenzar a recortar."})]}),
665
663
  /* @__PURE__ */s(qn,{}),
666
- /* @__PURE__ */s(Dn,{isOpen:D,onClose:O})]})}(()=>{try{const e=sessionStorage.getItem(jn);if(e){const t=JSON.parse(e),n=Date.now();Object.entries(t).forEach(([e,t])=>{t.timestamp&&n-t.timestamp<Fn&&Rn.set(e,t)})}}catch{}})();class Vn{constructor(e,t,n,l){this.id=e,this.config=t,this.eventManager=n,this.modalManager=l,this.root=null,this.container=null,this.modal=null,this.mounted=!1,this.destroyed=!1,this.button=null,this._validateConfig(),this._initialize()}_initialize(){"embed"===this.config.mode?this.mount():"button"===this.config.mode&&this._createButton(),this._emitDOMEvent("ready",{instance:this,config:this.config,timestamp:Date.now()})}mount(){if(this.mounted||this.destroyed)return this;if(this.container=this._resolveContainer(),!this.container)return this.eventManager.emit("error",{instanceId:this.id,error:"Container not found"}),this;try{this.root=N.createRoot(this.container),this.root.render(this._renderApp()),this.mounted=!0,this.eventManager.emit("ready",{instance:this})}catch(e){this.eventManager.emit("error",{instanceId:this.id,error:e.message})}return this}unmount(){return this.mounted?(this.root&&(this.root.unmount(),this.root=null),"button"===this.config.mode&&this.button,this.mounted=!1,this):this}open(){return"modal"!==this.config.mode&&"button"!==this.config.mode||(this.modal||this._createModal(),this.modal&&!this.modal.isOpened()&&(this.modal.open(),this.eventManager.emit("modal:open",{instance:this}))),this}close(){return this.modal&&this.modal.isOpened()&&(this.eventManager?.emit("modal:close",{instance:this}),this.modal.close()),this}updateConfig(e){return this.config={...this.config,...e},this.mounted&&this.root.render(this._renderApp()),this.eventManager.emit("config:updated",{instance:this,newConfig:e}),this}destroy(){this.destroyed||(this.unmount(),this.modal&&(this.modal.destroy(),this.modal=null),this.button&&this.button.parentNode&&(this.button.parentNode.removeChild(this.button),this.button=null),this.eventManager.emit("destroy",{instance:this}),this.container=null,this.config=null,this.eventManager=null,this.modalManager=null,this.destroyed=!0)}getId(){return this.id}getMode(){return this.config.mode}isMounted(){return this.mounted}isDestroyed(){return this.destroyed}getContainer(){return this.container}getConfig(){return{...this.config}}isContainerInDOM(){return this.container&&document.contains(this.container)}_createModal(){if(this.modalManager&&"modal"===this.config.mode&&(this.modal=this.modalManager.createModal({title:this.config.title||"Limbo Image Manager",size:this.config.modalSize||"large",onOpen:()=>{const e={instance:this,mode:"modal",timestamp:Date.now()};this._emitDOMEvent("modal:open",e),this.config.callbacks?.onOpen&&this.config.callbacks.onOpen(e)},onClose:()=>{const e={instance:this,mode:"modal",timestamp:Date.now()};this._emitDOMEvent("modal:close",e),this.config.callbacks?.onClose&&this.config.callbacks.onClose(e),this.config.autoDestroy&&this.destroy()},onDestroy:()=>{this.modal=null}}),this.modal)){const e=this.modal.getBodyContainer();this.root=N.createRoot(e),this.root.render(this._renderApp()),this.mounted=!0}}_createButton(){if(this.container||(this.container=this._resolveContainer()),!this.container)return void this.eventManager.emit("error",{instanceId:this.id,error:"Container not found for button mode"});const e=document.createElement("button");e.type="button",e.className="limbo-trigger-button",e.textContent=this.config.buttonText||"Abrir Limbo",e.style.cssText="\n background: #001978;\n color: white;\n border: none;\n padding: 10px 20px;\n border-radius: 6px;\n cursor: pointer;\n font-family: inherit;\n font-size: 14px;\n font-weight: 500;\n transition: all 0.2s ease;\n ",e.addEventListener("mouseenter",()=>{e.style.backgroundColor="#334793",e.style.transform="translateY(-1px)"}),e.addEventListener("mouseleave",()=>{e.style.backgroundColor="#001978",e.style.transform="translateY(0)"}),e.addEventListener("click",()=>{this.open()}),this.container.appendChild(e),this.button=e,this.mounted=!0}_resolveContainer(){const{container:e}=this.config;return e?"string"==typeof e?document.querySelector(e):e instanceof Element?e:null:null}_renderApp(){return e.createElement("div",{id:`limbo-component-container-${this.id}`,className:"limbo-scope limbo-instance limbo-component-container-wrapper lb:h-full lb:w-full lb:py-2 lb:pb-0 lb:bg-white","data-limbo-id":this.id,"data-limbo-mode":this.config.mode,"data-limbo-version":"3.3.5","data-limbo-isolated":"true","aria-label":"Limbo Image Manager",role:"region"},e.createElement(Wn,{apiKey:this.config.apiKey||null,publicKey:this.config.publicKey||null,token:this.config.token||null,prod:this.config.prod||!1,url:this.config.url,features:this.config.features,modeUI:this.config.modeUI||"full",ui:this.config.ui,callbacks:this._createCallbacks(),instanceId:this.id,authMode:this.config.authMode||(this.config.publicKey?"session":"manual"),_externalImage:this.config._externalImage||null,cropperConfig:this.config.cropper||null,allowedCategories:this.config.validation?.allowedCategories||null,folderConfig:this.config.folders||{include:[],exclude:[],includeNoFolder:!0}}))}_createCallbacks(){return{onSelect:e=>{const t=this.config?.callbacks?.onSelect,n=this._createStandardPayload(e,"select");t&&Promise.resolve(t(n)).catch(e=>{console.error("[LimboInstance] Error en onSelect callback:",e)}),this.destroyed||this._emitDOMEvent("select",n)},onUpload:e=>{const t=this.config?.callbacks?.onUpload,n=this._createStandardPayload(e,"upload");t&&Promise.resolve(t(n)).catch(e=>{console.error("[LimboInstance] Error en onUpload callback:",e)}),this.destroyed||this._emitDOMEvent("upload",n)},onError:e=>{const t=this.config?.callbacks?.onError,n={instance:this,error:{message:e.message||"Unknown error",code:e.code||"UNKNOWN",timestamp:Date.now()}};t&&t(n.error),this.destroyed||this._emitDOMEvent("error",n)},onClose:()=>{const e=this.config?.callbacks?.onClose,t={instance:this,timestamp:Date.now()};e&&e(),this.destroyed||this._emitDOMEvent("close",t)},onCropsSaved:e=>{console.log("[LimboInstance] onCropsSaved recibido:",e),console.log("[LimboInstance] this.config?.callbacks:",this.config?.callbacks);const t=this.config?.callbacks?.onCropsSaved;console.log("[LimboInstance] userCallback existe:",!!t);const n={instance:this,eventType:"cropsSaved",timestamp:Date.now(),instanceId:this.id,...e};if(console.log("[LimboInstance] payload.crops:",n.crops),t){console.log("[LimboInstance] Llamando userCallback onCropsSaved");try{t(n),console.log("[LimboInstance] userCallback ejecutado correctamente")}catch(l){console.error("[LimboInstance] Error en userCallback:",l)}}else console.warn("[LimboInstance] ⚠️ userCallback onCropsSaved NO existe");this.destroyed||this._emitDOMEvent("cropsSaved",n)},onCropperComplete:e=>{console.log("[LimboInstance] onCropperComplete recibido:",e);const t=this.config?.callbacks?.onCropperComplete,n={instance:this,eventType:"cropperComplete",timestamp:Date.now(),instanceId:this.id,...e};t&&(console.log("[LimboInstance] Llamando userCallback onCropperComplete"),t(n)),this.destroyed||this._emitDOMEvent("cropperComplete",n)}}}_createStandardPayload(e,t){const n={instance:this,eventType:t,timestamp:Date.now(),instanceId:this.id,mode:this.config?.mode,features:this.config?.features};return e&&(e.assetId||e.id?(n.assetId=e.assetId||e.id,n.variants=e.variants||[],n.master=e.master||{urlSigned:e.url||e.urlSigned,width:e.width,height:e.height,mime:e.mime||e.mimeType},n.fileName=e.fileName||e.name,n.mime=e.mime||e.mimeType,n.width=e.width,n.height=e.height,n.fileBlob=e.fileBlob||e.file,n.metadata={uploadedBy:e.uploadedBy,uploadedAt:e.uploadedAt||e.timestamp,size:e.size,...e.metadata}):Object.assign(n,e)),n}_emitDOMEvent(e,t){if(this.destroyed)return;const n=new CustomEvent(`limbo:${e}`,{detail:t,bubbles:!0,cancelable:!0});(this.getContainer()||document).dispatchEvent(n),this.eventManager?.emit(e,t)}_validateConfig(){const e=F();if(!(this.config.auth?.apiKey||this.config.auth?.publicKey||this.config.auth?.token||this.config.apiKey||this.config.publicKey||this.config.token||this.config.tokenProvider||this.config.auth?.tokenProvider||e.token||e.publicKey||e.tokenProvider))throw new Error(`LimboInstance ${this.id}: Authentication is required. Provide either auth.publicKey (recommended), auth.apiKey (for server-side only), token, or tokenProvider`);if((this.config.auth?.apiKey||this.config.apiKey)&&"undefined"!=typeof window&&console.warn("⚠️ SECURITY WARNING: API Key detected in client-side code.\nThis is a security risk! Use publicKey instead for client applications.\nAPI Keys should only be used in server-side environments."),!["embed","modal","button"].includes(this.config.mode))throw new Error(`LimboInstance ${this.id}: invalid mode ${this.config.mode}`);if("embed"===this.config.mode&&!this.config.container)throw new Error(`LimboInstance ${this.id}: container is required for embed mode`);if("button"===this.config.mode&&!this.config.container)throw new Error(`LimboInstance ${this.id}: container is required for button mode`)}}class Hn{constructor(){this.instances=/* @__PURE__ */new Map,this.counter=0}create(e,t,n){const l="limbo-"+ ++this.counter,r=new Vn(l,e,t,n);return this.instances.set(l,r),r}get(e){return this.instances.get(e)}getAll(){return Array.from(this.instances.values())}getActive(){return this.getAll().filter(e=>e.isMounted())}destroy(e){const t=this.instances.get(e);return!!t&&(t.destroy(),this.instances.delete(e),!0)}destroyAll(){this.instances.forEach(e=>e.destroy()),this.instances.clear()}cleanupOrphans(){const e=[];return this.instances.forEach((t,n)=>{t.isContainerInDOM()||e.push(n)}),e.forEach(e=>this.destroy(e)),e.length}getStats(){const e=this.getAll();return{total:e.length,active:e.filter(e=>e.isMounted()).length,embed:e.filter(e=>"embed"===e.getMode()).length,modal:e.filter(e=>"modal"===e.getMode()).length,button:e.filter(e=>"button"===e.getMode()).length}}}class Kn{constructor(){this.config=null,this.instances=/* @__PURE__ */new Map,this.observer=null,this.initialized=!1}configure(e,t,n){return this.config={selector:e.selector||null,dataset:e.dataset||"data-limbo-input-file",return:e.return||e.returnType||"json",mode:e.mode||"modal",features:e.features||["gallery","upload","cropper"],crop:e.crop||"free",quality:e.quality||.9,format:e.format||"webp",modeUI:e.modeUI||"full",modalSize:e.modalSize||"fullscreen",theme:e.theme||"light",compact:e.compact||!1,maxSize:e.maxSize||"10MB",formats:e.formats||["jpg","jpeg","png","webp"],minWidth:e.minWidth||null,minHeight:e.minHeight||null,maxWidth:e.maxWidth||null,maxHeight:e.maxHeight||null,buttonText:e.buttonText||"Seleccionar archivo",buttonClass:e.buttonClass||"limbo-auto-button",buttonStyle:e.buttonStyle||"primary",showPreview:!1!==e.showPreview,allowMultiple:e.allowMultiple||!1,autoAssign:!1!==e.autoAssign,localCropsOnly:e.localCropsOnly||!1,...e},this.configManager=t,this.eventManager=n,this._initialize(),this}cleanup(){this.observer&&(this.observer.disconnect(),this.observer=null),this.instances.forEach(({input:e,button:t})=>{this._restoreInput(e,t)}),this.instances.clear(),this.config=null,this.initialized=!1}getStats(){return{configured:null!==this.config,totalInputs:this.instances.size,dataset:this.config?.dataset,returnType:this.config?.return}}_initialize(){this.initialized||(this._scanExistingInputs(),this._setupObserver(),this.initialized=!0,this.eventManager.emit("autoInputs:initialized",{config:this.config,inputsFound:this.instances.size}))}_scanExistingInputs(){const e=this.config.selector||`input[${this.config.dataset}]`;document.querySelectorAll(e).forEach(e=>this._processInput(e))}_processInput(e){const t=this._getInputId(e);if(this.instances.has(t))return;if(!this._validateInput(e))return;const n=this._createButton(e);this._hideInput(e),this._insertButton(e,n),this.instances.set(t,{input:e,button:n,config:this._getInputConfig(e)}),this.eventManager.emit("autoInputs:processed",{inputId:t,input:e,button:n})}_createButton(e){const t=document.createElement("button"),n=this._getInputConfig(e);t.type="button",t.textContent=n.buttonText||this.config.buttonText;const l=[this.config.buttonClass];return n.buttonClass&&n.buttonClass!==this.config.buttonClass&&l.push(n.buttonClass),t.className=l.join(" "),this._styleButton(t,n),this._attachButtonEvents(t,e),t.setAttribute("aria-label",n.buttonText||this.config.buttonText),t.setAttribute("data-limbo-trigger","true"),t.setAttribute("data-limbo-input-id",n.inputId),n.disabled&&(t.disabled=!0),t}_styleButton(e,t){const n=t.buttonStyle||this.config.buttonStyle,l=t.theme||this.config.theme,r=t.compact||this.config.compact,a={border:"none",borderRadius:"8px",cursor:"pointer",fontFamily:"inherit",fontSize:r?"12px":"14px",fontWeight:"500",transition:"all 0.2s ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",padding:r?"6px 12px":"8px 16px",textDecoration:"none",userSelect:"none"},i={primary:{backgroundColor:"dark"===l?"#3b82f6":"#001978",color:"white",hoverBg:"dark"===l?"#2563eb":"#334793"},secondary:{backgroundColor:"dark"===l?"#374151":"#f3f4f6",color:"dark"===l?"#f9fafb":"#374151",border:"1px solid "+("dark"===l?"#4b5563":"#d1d5db"),hoverBg:"dark"===l?"#4b5563":"#e5e7eb"},outline:{backgroundColor:"transparent",color:"dark"===l?"#3b82f6":"#001978",border:"2px solid "+("dark"===l?"#3b82f6":"#001978"),hoverBg:"dark"===l?"#3b82f6":"#001978",hoverColor:"white"},ghost:{backgroundColor:"transparent",color:"dark"===l?"#f9fafb":"#374151",hoverBg:"dark"===l?"#374151":"#f3f4f6"}},o=i[n]||i.primary;Object.assign(e.style,{...a,...o});const s=o.backgroundColor,c=o.color;e.addEventListener("mouseenter",()=>{e.style.backgroundColor=o.hoverBg||o.backgroundColor,o.hoverColor&&(e.style.color=o.hoverColor),e.style.transform="translateY(-1px)",e.style.boxShadow="0 4px 12px rgba(0, 0, 0, 0.15)"}),e.addEventListener("mouseleave",()=>{e.style.backgroundColor=s,e.style.color=c,e.style.transform="translateY(0)",e.style.boxShadow="none"}),t.disabled&&(e.style.opacity="0.5",e.style.cursor="not-allowed")}_attachButtonEvents(e,t){e.addEventListener("click",e=>{e.preventDefault(),this._handleButtonClick(t)})}_handleButtonClick(e){const t=this._getInputConfig(e),n=this._createModalConfig(t);this.eventManager.emit("autoInputs:modalRequest",{input:e,config:n,callback:async t=>await this._handleImageSelection(e,t)})}async _handleImageSelection(e,t){const n=this._getInputConfig(e);let l=t;try{if(!t.original&&!t.images&&(t.id||t.assetId)){console.log("[AutoInputManager] 🔗 Selección directa detectada, obteniendo URL permanente...");const e=t.id||t.assetId;try{const n=await async function(e,t=!0,n=!0,l=0){try{const r=new URLSearchParams({include_variants:t.toString(),include_metadata:n.toString(),url_expires:l.toString()});return W(await j({endpoint:`/assets/${e}?${r}`,method:"GET",basePath:G,useJWT:!0}))}catch(r){throw K(r)}}(e,!1,!1,!0);n?.result?.url?(console.log("[AutoInputManager] ✅ URL permanente obtenida:",n.result.url),l={original:{url:n.result.url,width:n.result.width||t.width,height:n.result.height||t.height,assetId:e},images:[]}):(console.warn("[AutoInputManager] ⚠️ No se pudo obtener URL permanente, usando URL temporal"),l={original:{url:t.url||t.path,width:t.width,height:t.height,assetId:e},images:[]})}catch(r){console.error("[AutoInputManager] Error obteniendo URL permanente:",r),l={original:{url:t.url||t.path,width:t.width,height:t.height,assetId:e},images:[]}}}const a=await this._formatImageData(l,n);console.log("[AutoInputManager] Valor formateado:",a),console.log("[AutoInputManager] Tipo de valor:",typeof a),!1!==n.autoAssign&&(e.value=a,console.log("[AutoInputManager] Valor asignado al input:",e.value)),this._updateButtonFeedback(e,l),e.dispatchEvent(new Event("change",{bubbles:!0})),e.dispatchEvent(new CustomEvent("limbo:resultReady",{detail:{imageData:l,input:e,value:a,config:n,assignment:{format:n.return,smartAssign:!1!==n.smartAssign,autoAssign:!1!==n.autoAssign},legacy:{imageData:l,formatted:this._createFormattedResult(l,n)}},bubbles:!0})),e.dispatchEvent(new CustomEvent("limbo:imageSelected",{detail:{imageData:l,input:e,value:a,config:n,formatted:this._createFormattedResult(l,n)},bubbles:!0})),this.eventManager.emit("autoInputs:imageSelected",{input:e,imageData:l,value:a,config:n})}catch(a){console.error("Error handling image selection:",a),e.dispatchEvent(new CustomEvent("limbo:error",{detail:{error:a.message,input:e,imageData:l,config:n},bubbles:!0})),this._handleImageSelectionLegacy(e,t)}}_updateButtonFeedback(e,t){const n=this._getInputId(e),l=this.instances.get(n);if(!l||!l.button)return;const r=l.button,a=r.nextElementSibling;a&&a.classList.contains("limbo-button-feedback")&&a.remove();const i=document.createElement("span");i.className="limbo-button-feedback",i.style.cssText="\n display: inline-flex;\n align-items: center;\n gap: 6px;\n margin-left: 8px;\n padding: 4px 8px;\n background: #10b981;\n color: white;\n border-radius: 6px;\n font-size: 12px;\n font-weight: 500;\n animation: limbo-fade-in 0.3s ease-out;\n ";const o=t.images&&t.images.length>0,s=o?t.images.length:0;i.innerHTML=o?`\n <svg width="14" height="14" viewBox="0 0 20 20" fill="currentColor">\n <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"/>\n </svg>\n <span>${s} recorte${1!==s?"s":""} configurado${1!==s?"s":""}</span>\n `:'\n <svg width="14" height="14" viewBox="0 0 20 20" fill="currentColor">\n <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"/>\n </svg>\n <span>Archivo seleccionado</span>\n ',r.parentNode.insertBefore(i,r.nextSibling);let c=r.parentNode.querySelector(".limbo-powered-by");c||(c=document.createElement("div"),c.className="limbo-powered-by",c.innerHTML='<span style="display:block;margin-top:2px;font-size:10px;color:#aaa;text-align:left;font-family:inherit;opacity:0.7;">Powered by <b>Limbo</b></span>',r.parentNode.insertBefore(c,i.nextSibling)),r.style.backgroundColor="#10b981",r.textContent="Cambiar archivo"}async _handleImageSelectionLegacy(e,t){const n=this._getInputConfig(e),l=await this._formatImageData(t,n);!1!==n.autoAssign&&(e.value=l),e.dispatchEvent(new Event("change",{bubbles:!0})),e.dispatchEvent(new CustomEvent("limbo:imageSelected",{detail:{imageData:t,input:e,value:l,config:n,formatted:this._createFormattedResult(t,n)},bubbles:!0})),this.eventManager.emit("autoInputs:imageSelected",{input:e,imageData:t,value:l,config:n})}_createFormattedResult(e,t){return{url:e.url||e.path||"",base64:e.base64||e.dataUrl||"",assetId:e.assetId||e.id||"",fileName:e.fileName||e.filename||"",object:{url:e.url||e.path,assetId:e.assetId||e.id,fileName:e.fileName||e.filename,mime:e.mime||e.mime_type,width:e.width,height:e.height,size:e.size||e.file_size,created:e.created_at||e.created,metadata:e.metadata||{}},json:JSON.stringify({url:e.url||e.path,assetId:e.assetId||e.id,fileName:e.fileName||e.filename,mime:e.mime||e.mime_type,width:e.width,height:e.height,size:e.size||e.file_size}),metadata:{width:e.width,height:e.height,size:e.size||e.file_size,format:e.format||e.mime_type,quality:t.quality||this.config.quality,aspectRatio:e.width&&e.height?e.width/e.height:null}}}async _formatImageData(e,t=null){const n=(t||{}).return||this.config.return||"json",l=void 0!==e.original;switch(n){case"url":return l?e.images?.[0]?.url||e.original?.url||"":e.url||e.path||"";case"base64":return e.base64||e.dataUrl||"";case"assetId":return l?e.original?.assetId||"":e.assetId||e.id||"";case"fileName":return e.fileName||e.filename||"";default:try{if(l){const t={original:e.original?{url:e.original.url||e.original.urlSigned,width:e.original.width,height:e.original.height,assetId:e.original.assetId||e.original.id}:null,images:Array.isArray(e.images)?e.images.map(e=>{const t={url:e.url||e.urlSigned,width:e.width,height:e.height,name:e.name||e.filename||e.label};return e.cropState&&(t.cropState={selectorState:e.cropState.selectorState||null,imageTransform:e.cropState.imageTransform||null,flipState:e.cropState.flipState||null}),t}):[]};console.log("[AutoInputManager] Datos limpios para JSON:",t);const n=JSON.stringify(t);return console.log("[AutoInputManager] JSON generado:",n),n}const t={original:{url:e.url||e.path,width:e.width,height:e.height,assetId:e.assetId||e.id}};return console.log("[AutoInputManager] Datos legacy para JSON:",t),JSON.stringify(t)}catch(r){return console.error("[AutoInputManager] Error al serializar JSON:",r),console.error("[AutoInputManager] imageData problemático:",e),"{}"}}}_createModalConfig(e){return{mode:e.mode||this.config.mode||"modal",modeUI:e.modeUI||this.config.modeUI||"full",features:e.features||this.config.features,modalSize:e.modalSize||this.config.modalSize||"fullscreen",title:e.description||this.config.title||"Seleccionar archivo",cropper:this._getCropperConfig(e),ui:{showActions:this._getUIActions(e),hideActions:[],showTabs:this._shouldShowTabs(e),theme:e.theme||this.config.theme,compact:e.compact||this.config.compact,showPreview:void 0!==e.showPreview?e.showPreview:this.config.showPreview},validation:{maxSize:e.maxSize||this.config.maxSize,formats:e.formats||this.config.formats,minWidth:e.minWidth||this.config.minWidth,minHeight:e.minHeight||this.config.minHeight,maxWidth:e.maxWidth||this.config.maxWidth,maxHeight:e.maxHeight||this.config.maxHeight,required:e.required||!1},behavior:{allowMultiple:e.allowMultiple||this.config.allowMultiple,closeOnSelect:!0,autoAssign:void 0!==e.autoAssign?e.autoAssign:this.config.autoAssign,allowSelectNew:!1!==e.allowSelectNew},initialImageUrl:e.initialImageUrl||null,existingCrops:e.existingCrops||null,existingData:e.existingData||null,returnConfig:{format:e.return||this.config.return,quality:e.quality||this.config.quality,outputFormat:e.format||this.config.format},inputMeta:{inputId:e.inputId,inputName:e.inputName,inputType:e.inputType,placeholder:e.placeholder}}}_getCropperConfig(e){const t=e.crop||this.config.crop,n={quality:e.quality||this.config.quality,format:e.format||this.config.format,mandatoryCrops:e.mandatoryCrops||[],allowAdditionalCrops:!1!==e.allowAdditionalCrops,maxCrops:e.maxCrops||null,localCropsOnly:e.localCropsOnly??this.config.localCropsOnly??!1,existingCrops:e.existingCrops||null};if(e.mandatoryCrops&&e.mandatoryCrops.length>0)return{...n,aspectRatio:null};if(!t||"none"===t||"false"===t)return null;if("free"===t)return{...n,aspectRatio:null};const l={"1:1":1,"16:9":16/9,"4:3":4/3,"3:2":1.5,"2:1":2,square:1,landscape:16/9,portrait:3/4};if(l[t])return{...n,aspectRatio:l[t],minCropBoxWidth:e.minWidth||this.config.minWidth,minCropBoxHeight:e.minHeight||this.config.minHeight};if("string"==typeof t&&t.includes(":")){const[e,l]=t.split(":").map(Number);if(!isNaN(e)&&!isNaN(l)&&0!==l)return{...n,aspectRatio:e/l}}const r=parseFloat(t);return!isNaN(r)&&r>0?{...n,aspectRatio:r}:"object"==typeof t?{...n,...t}:null}_shouldShowTabs(e){const t=e.modeUI||this.config.modeUI||"full",n=e.features||this.config.features;return!["gallery-only","upload-only","crop-only","ia-only"].includes(t)&&(n&&n.length>1)}_getUIActions(e){const t=e.modeUI||this.config.modeUI||"full",n=e.features||this.config.features;let l=[];switch(t){case"gallery-only":case"upload-only":l=["select"];break;case"crop-only":l=["select","crop"];break;default:l=["select"],n.includes("cropper")&&l.push("crop"),n.includes("gallery")&&(l.push("download","copy"),this.config.allowDelete&&l.push("delete"))}return l}_getInputId(e){if(e.id)return e.id;if(e.name)return e.name;let t=e.getAttribute("data-limbo-uid");return t||(t=`limbo-auto-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,e.setAttribute("data-limbo-uid",t)),t}_validateInput(e){return e instanceof HTMLInputElement}_getInputConfig(e){const t=e=>e?e.split(",").map(e=>e.trim()):null,n=e=>{if(!e)return null;const t=e.match(/^(\d+(?:\.\d+)?)(MB|KB|B)?$/i);if(!t)return null;const n=parseFloat(t[1]);switch((t[2]||"B").toUpperCase()){case"MB":return 1024*n*1024;case"KB":return 1024*n;default:return n}},l=(e,t=!1)=>null===e?t:"true"===e||"1"===e||""===e,r=e=>e?parseFloat(e):null,a=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return console.warn("[Limbo AutoInputManager] Error parsing JSON attribute:",t),null}},i=a(e.dataset.mandatorycrops)||a(e.dataset.mandatoryCrops)||a(e.getAttribute("data-mandatory-crops"))||a(e.getAttribute("data-limbo-mandatory-crops"))||null;return{return:e.dataset.returntype||e.getAttribute("data-limbo-return")||this.config.return,mode:e.dataset.mode||e.getAttribute("data-limbo-mode")||this.config.mode,features:t(e.dataset.features)||t(e.getAttribute("data-limbo-features"))||this.config.features,crop:e.dataset.crop||e.getAttribute("data-limbo-crop")||this.config.crop,quality:r(e.dataset.quality)||r(e.getAttribute("data-limbo-quality"))||this.config.quality,format:e.dataset.format||e.getAttribute("data-limbo-format")||this.config.format,modeUI:e.dataset.modeui||e.dataset.modeUI||e.getAttribute("data-limbo-mode-ui")||this.config.modeUI,modalSize:e.dataset.modalsize||e.getAttribute("data-limbo-modal-size")||this.config.modalSize,theme:e.dataset.theme||e.getAttribute("data-limbo-theme")||this.config.theme,compact:l(e.dataset.compact,null)??l(e.getAttribute("data-limbo-compact"),this.config.compact),maxSize:n(e.getAttribute("data-limbo-max-size"))||n(this.config.maxSize),formats:t(e.getAttribute("data-limbo-formats"))||this.config.formats,minWidth:r(e.getAttribute("data-limbo-min-width"))||this.config.minWidth,minHeight:r(e.getAttribute("data-limbo-min-height"))||this.config.minHeight,maxWidth:r(e.getAttribute("data-limbo-max-width"))||this.config.maxWidth,maxHeight:r(e.getAttribute("data-limbo-max-height"))||this.config.maxHeight,buttonText:e.dataset.buttontext||e.getAttribute("data-limbo-button-text")||this.config.buttonText,buttonStyle:e.dataset.buttonstyle||e.getAttribute("data-limbo-button-style")||this.config.buttonStyle,buttonClass:e.dataset.buttonclass||e.getAttribute("data-limbo-button-class")||this.config.buttonClass,showPreview:l(e.getAttribute("data-limbo-show-preview"),this.config.showPreview),allowMultiple:l(e.getAttribute("data-limbo-allow-multiple"),this.config.allowMultiple),autoAssign:l(e.getAttribute("data-limbo-auto-assign"),this.config.autoAssign),placeholder:e.getAttribute("data-limbo-placeholder"),description:e.getAttribute("data-limbo-description"),required:l(e.getAttribute("data-limbo-required"),!1),disabled:l(e.getAttribute("data-limbo-disabled"),!1),inputId:this._getInputId(e),inputName:e.name,inputType:e.type,mandatoryCrops:i,allowAdditionalCrops:l(e.dataset.allowadditionalcrops,null)??l(e.getAttribute("data-limbo-allow-additional-crops"),!0),maxCrops:r(e.dataset.maxcrops)||r(e.getAttribute("data-limbo-max-crops"))||null,allowSelectNew:l(e.dataset.allowselectnew,null)??l(e.getAttribute("data-limbo-allow-select-new"),!0),...this._parseExistingInputValue(e.value)}}_parseExistingInputValue(e){if(!e||""===e.trim())return{initialImageUrl:null,existingCrops:null,existingData:null};try{const t=JSON.parse(e);return t.original&&t.original.url?(console.log("[AutoInputManager] Valor existente parseado:",t),{initialImageUrl:t.original.url,existingCrops:t.images||null,existingData:t}):t.url?{initialImageUrl:t.url,existingCrops:null,existingData:t}:{initialImageUrl:null,existingCrops:null,existingData:t}}catch(t){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?{initialImageUrl:e,existingCrops:null,existingData:null}:{initialImageUrl:null,existingCrops:null,existingData:null}}}_generateInputId(){return`limbo-auto-input-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}_hideInput(e){e.style.display="none"}_insertButton(e,t){e.parentNode.insertBefore(t,e.nextSibling)}_restoreInput(e,t){e.style.display="",t&&t.parentNode&&t.parentNode.removeChild(t)}_setupObserver(){this.observer=new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e.nodeType===Node.ELEMENT_NODE&&this._scanNodeForInputs(e)})})}),this.observer.observe(document.body,{childList:!0,subtree:!0})}_scanNodeForInputs(e){const t=this.config.selector||`input[${this.config.dataset}]`;e.matches&&e.matches(t)&&this._processInput(e);const n=e.querySelectorAll&&e.querySelectorAll(t);n&&n.forEach(e=>this._processInput(e))}}class Gn{constructor(){this.listeners=/* @__PURE__ */new Map}emit(e,t={}){this._emitDOMEvent(e,t),this._executeListeners(e,t)}on(e,t){return this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t),()=>this.off(e,t)}off(e,t){const n=this.listeners.get(e);if(n){const e=n.indexOf(t);e>-1&&n.splice(e,1)}}cleanup(){this.listeners.clear()}_emitDOMEvent(e,t){const n=new CustomEvent(`limbo:${e}`,{detail:{...t,timestamp:Date.now()},bubbles:!0,cancelable:!0});(t.instance?.getContainer()||document).dispatchEvent(n)}_executeListeners(e,t){const n=this.listeners.get(e);n&&n.forEach(n=>{try{n(t)}catch(l){console.error(`Error executing listener for ${e}:`,l)}})}getStats(){const e={};return this.listeners.forEach((t,n)=>{e[n]=t.length}),e}}class Qn{constructor(){this.activeModals=/* @__PURE__ */new Set,this.zIndexBase=1e4,this.focusableSelectors=["button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"]):not([disabled])',"a[href]"].join(", "),this.initialized=!1,this._initGlobalListeners()}createModal(e){const t=new Xn(this._generateModalId(),e,this);return this.activeModals.add(t),t}closeModal(e){const t=this._findModal(e);return!!t&&(t.close(),!0)}closeAllModals(){this.activeModals.forEach(e=>e.close()),this.activeModals.clear()}getActiveModal(){return Array.from(this.activeModals).pop()||null}getStats(){return{active:this.activeModals.size,nextZIndex:this._getNextZIndex()}}_generateModalId(){return`limbo-modal-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}_findModal(e){return Array.from(this.activeModals).find(t=>t.getId()===e)}_getNextZIndex(){return this.zIndexBase+10*this.activeModals.size}_removeModal(e){this.activeModals.delete(e),window.limboCore?.events&&window.limboCore.events.emit("modal:closed",{modalId:e.getId(),remainingModals:this.activeModals.size})}_handleGlobalKeydown(e){const t=this.getActiveModal();t&&("Escape"===e.key&&(e.preventDefault(),t.close()),"Tab"===e.key&&this._handleTabTrap(e,t))}_handleTabTrap(e,t){const n=t.getFocusableElements();if(0===n.length)return;const l=n[0],r=n[n.length-1];e.shiftKey?document.activeElement===l&&(e.preventDefault(),r.focus()):document.activeElement===r&&(e.preventDefault(),l.focus())}_initGlobalListeners(){this.initialized||(this.globalKeydownHandler=e=>this._handleGlobalKeydown(e),document.addEventListener("keydown",this.globalKeydownHandler),this.initialized=!0)}destroy(){this.closeAllModals(),this.initialized&&this.globalKeydownHandler&&(document.removeEventListener("keydown",this.globalKeydownHandler),this.initialized=!1,this.globalKeydownHandler=null)}}class Xn{constructor(e,t,n){this.id=e,this.config={title:t.title||"Limbo",content:t.content||null,showCloseButton:!1!==t.showCloseButton,backdrop:!1!==t.backdrop,keyboard:!1!==t.keyboard,focus:!1!==t.focus,animation:!1!==t.animation,size:t.size||"large",onOpen:t.onOpen||null,onClose:t.onClose||null,onDestroy:t.onDestroy||null,...t},this.manager=n,this.element=null,this.backdrop=null,this.isOpen=!1,this.previousFocus=null,this._create()}_create(){this._createBackdrop(),this._createModal(),this._attachEvents()}_createBackdrop(){this.config.backdrop&&(this.backdrop=document.createElement("div"),this.backdrop.className="limbo-modal-backdrop",this.backdrop.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: rgba(0, 0, 0, 0.5);\n z-index: ${this.manager._getNextZIndex()};\n opacity: 0;\n transition: opacity 0.3s ease;\n `,this.backdrop.addEventListener("click",e=>{e.target===this.backdrop&&this.close()}))}_createModal(){this.element=document.createElement("div"),this.element.className=`limbo-scope limbo-modal limbo-modal--${this.config.size}`,this.element.id=this.id,this.element.role="dialog",this.element.setAttribute("aria-modal","true"),this.element.setAttribute("aria-labelledby",`${this.id}-title`),this.element.tabIndex=-1;const e=window.innerWidth<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),t={small:e?"width: 100%; height: 100%;":"max-width: 500px; min-height: 400px;",medium:e?"width: 100%; height: 100%;":"max-width: 800px; min-height: 500px;",large:e?"width: 100%; height: 100%;":"max-width: 1400px; min-height: 700px;",xlarge:e?"width: 100%; height: 100%;":"max-width: 95dvw; min-height: 85vh;",fullscreen:"width: 100%; height: 100%; max-width: 100%; max-height: 100%; border-radius: 0;"},n="fullscreen"===this.config.size,l=e||n?`\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n transform: ${e?"translateY(100%)":"scale(0.95)"};\n width: 100%;\n height: 100%;\n max-width: none;\n max-height: none;\n border-radius: 0;\n background: white;\n z-index: ${this.manager._getNextZIndex()+1};\n opacity: ${e?"1":"0"};\n transition: ${e?"transform":"all"} 0.3s cubic-bezier(0.4, 0, 0.2, 1);\n overflow: hidden;\n display: flex;\n flex-direction: column;\n padding-top: env(safe-area-inset-top);\n padding-left: env(safe-area-inset-left);\n padding-right: env(safe-area-inset-right);\n padding-bottom: env(safe-area-inset-bottom);\n `:`\n position: fixed;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%) scale(0.8);\n ${t[this.config.size]}\n width: 90%;\n max-height: 90vh;\n background: white;\n border-radius: 16px;\n box-shadow: 0 25px 50px rgba(0, 0, 0, 0.25);\n z-index: ${this.manager._getNextZIndex()+1};\n opacity: 0;\n transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);\n overflow: hidden;\n display: flex;\n flex-direction: column;\n `;this.element.style.cssText=l,this._createHeader(),this._createBody(),document.body.appendChild(this.backdrop),document.body.appendChild(this.element)}_createHeader(){const e=document.createElement("div");e.className="limbo-modal-header";const t=window.innerWidth<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);e.style.cssText=`\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: ${t?"16px 20px":"20px 24px"};\n border-bottom: 1px solid #e9ecef;\n background: #f8f9fa;\n ${t?"position: sticky; top: 0; z-index: 10;":""}\n min-height: ${t?"60px":"auto"};\n `;const n=document.createElement("h2");if(n.id=`${this.id}-title`,n.className="limbo-modal-title",n.textContent=this.config.title,n.style.cssText="\n margin: 0;\n font-size: 18px;\n font-weight: 600;\n color: #001978;\n flex: 1;\n margin-right: 16px;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n ",e.appendChild(n),this.config.showCloseButton){const n=document.createElement("button");n.type="button",n.className="limbo-modal-close",n.innerHTML="✕",n.setAttribute("aria-label","Cerrar modal"),n.style.cssText=`\n background: none;\n border: none;\n font-size: ${t?"28px":"24px"};\n color: #6c757d;\n cursor: pointer;\n padding: ${t?"8px":"4px"};\n border-radius: 4px;\n transition: all 0.2s ease;\n min-width: ${t?"44px":"auto"};\n min-height: ${t?"44px":"auto"};\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n `,n.addEventListener("mouseenter",()=>{n.style.backgroundColor="#f8f9fa",n.style.color="#001978"}),n.addEventListener("mouseleave",()=>{n.style.backgroundColor="transparent",n.style.color="#6c757d"}),n.addEventListener("click",()=>this.close()),e.appendChild(n)}this.element.appendChild(e)}_createBody(){const e=window.innerWidth<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),t=document.createElement("div");t.className="limbo-modal-body",t.id=`${this.id}-body`,t.style.cssText=`\n flex: 1;\n overflow-y: auto;\n padding: 0;\n -webkit-overflow-scrolling: touch;\n ${e?"height: 100%; overscroll-behavior: contain;":""}\n `,this.config.content&&("string"==typeof this.config.content?t.innerHTML=this.config.content:this.config.content instanceof Element&&t.appendChild(this.config.content)),this.element.appendChild(t)}_attachEvents(){this._originalBodyOverflow=document.body.style.overflow}open(){if(this.isOpen)return this;window.limbo&&window.limbo.core&&window.limbo.core.keyboard?(window.limbo.core.keyboard.pushFocus(document.activeElement),window.limbo.core.keyboard.setActiveModal(this.element)):this.previousFocus=document.activeElement,document.body.style.overflow="hidden";const e=window.innerWidth<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),t="fullscreen"===this.config.size;return requestAnimationFrame(()=>{this.backdrop&&(this.backdrop.style.opacity="1"),this.element.style.opacity="1",this.element.style.transform=e?"translateY(0%)":t?"scale(1)":"translate(-50%, -50%) scale(1)"}),this.isOpen=!0,this.config.focus&&setTimeout(()=>{if(window.limbo&&window.limbo.core&&window.limbo.core.keyboard)window.limbo.core.keyboard.focusFirst(this.element);else{const e=this.getFocusableElements()[0];e&&e.focus()}},300),this.config.onOpen&&this.config.onOpen(this),this}close(){if(!this.isOpen)return this;const e=window.innerWidth<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),t="fullscreen"===this.config.size;return this.backdrop&&(this.backdrop.style.opacity="0"),this.element.style.opacity="0",this.element.style.transform=e?"translateY(100%)":t?"scale(0.95)":"translate(-50%, -50%) scale(0.8)",setTimeout(()=>{this._cleanup()},300),this.isOpen=!1,window.limbo&&window.limbo.core&&window.limbo.core.keyboard&&(window.limbo.core.keyboard.setActiveModal(null),window.limbo.core.keyboard.releaseFocus()),this.config.onClose&&this.config.onClose(this),this}destroy(){this.close(),this.manager._removeModal(this),this.config.onDestroy&&this.config.onDestroy(this)}getBodyContainer(){return this.element.querySelector(".limbo-modal-body")}getFocusableElements(){return Array.from(this.element.querySelectorAll(this.manager.focusableSelectors))}getId(){return this.id}isOpened(){return this.isOpen}getConfig(){return{...this.config}}_cleanup(){document.body.style.overflow=this._originalBodyOverflow||"",this.previousFocus&&"function"==typeof this.previousFocus.focus&&this.previousFocus.focus(),this.backdrop&&this.backdrop.parentNode&&this.backdrop.parentNode.removeChild(this.backdrop),this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element)}}class Yn{constructor(){this.currentTheme=null,this.customThemes=/* @__PURE__ */new Map,this.config=this._getDefaultConfig(),this.isInitialized=!1,this.isCompactMode=!1,this.compactBreakpoint=null,this.compactObserver=null,this.mediaQueryObserver=null,this.mutationObserver=null,this.storageListener=null,this.themeCache=/* @__PURE__ */new Map,this.appliedStyles=/* @__PURE__ */new Set,this.changeCallbacks=/* @__PURE__ */new Set}_getDefaultConfig(){return{theme:{auto:!0,storage:!0,inherit:!0,smooth:!0,detectSystem:!0},compact:{enabled:!1,auto:!0,breakpoint:768,forceOnMobile:!0,persistPreference:!0},presets:{light:{name:"light",displayName:"Claro",variables:{"--limbo-primary":"#3b82f6","--limbo-primary-hover":"#2563eb","--limbo-primary-light":"#dbeafe","--limbo-primary-dark":"#1e40af","--limbo-bg-primary":"#ffffff","--limbo-bg-secondary":"#f8fafc","--limbo-bg-tertiary":"#f1f5f9","--limbo-bg-overlay":"rgba(0, 0, 0, 0.5)","--limbo-bg-card":"#ffffff","--limbo-bg-input":"#ffffff","--limbo-text-primary":"#0f172a","--limbo-text-secondary":"#475569","--limbo-text-tertiary":"#64748b","--limbo-text-inverse":"#ffffff","--limbo-text-muted":"#94a3b8","--limbo-border-light":"#e2e8f0","--limbo-border-medium":"#cbd5e1","--limbo-border-strong":"#94a3b8","--limbo-border-focus":"#3b82f6","--limbo-success":"#10b981","--limbo-success-light":"#d1fae5","--limbo-error":"#ef4444","--limbo-error-light":"#fee2e2","--limbo-warning":"#f59e0b","--limbo-warning-light":"#fef3c7","--limbo-info":"#3b82f6","--limbo-info-light":"#dbeafe","--limbo-shadow-sm":"0 1px 2px 0 rgba(0, 0, 0, 0.05)","--limbo-shadow-md":"0 4px 6px -1px rgba(0, 0, 0, 0.1)","--limbo-shadow-lg":"0 10px 15px -3px rgba(0, 0, 0, 0.1)","--limbo-shadow-xl":"0 20px 25px -5px rgba(0, 0, 0, 0.1)","--limbo-radius-sm":"4px","--limbo-radius-md":"6px","--limbo-radius-lg":"8px","--limbo-radius-xl":"12px","--limbo-font-family":"system-ui, -apple-system, sans-serif","--limbo-font-size-xs":"12px","--limbo-font-size-sm":"14px","--limbo-font-size-md":"16px","--limbo-font-size-lg":"18px","--limbo-font-size-xl":"20px","--limbo-z-dropdown":"1000","--limbo-z-sticky":"1020","--limbo-z-fixed":"1030","--limbo-z-modal":"1050","--limbo-z-tooltip":"1070","--limbo-transition-fast":"150ms cubic-bezier(0.4, 0, 0.2, 1)","--limbo-transition-normal":"300ms cubic-bezier(0.4, 0, 0.2, 1)","--limbo-transition-slow":"500ms cubic-bezier(0.4, 0, 0.2, 1)","--limbo-spacing-compact":"0.5rem","--limbo-spacing-compact-sm":"0.25rem","--limbo-spacing-compact-lg":"0.75rem","--limbo-font-size-compact-xs":"11px","--limbo-font-size-compact-sm":"12px","--limbo-font-size-compact-md":"14px","--limbo-font-size-compact-lg":"16px","--limbo-radius-compact":"4px","--limbo-radius-compact-sm":"3px","--limbo-radius-compact-lg":"6px","--limbo-button-height-compact":"32px","--limbo-input-height-compact":"36px","--limbo-modal-padding-compact":"12px","--limbo-card-padding-compact":"12px","--limbo-gap-compact":"8px","--limbo-gap-compact-sm":"4px","--limbo-gap-compact-lg":"12px"}},dark:{name:"dark",displayName:"Oscuro",variables:{"--limbo-primary":"#60a5fa","--limbo-primary-hover":"#3b82f6","--limbo-primary-light":"#1e293b","--limbo-primary-dark":"#93c5fd","--limbo-bg-primary":"#0f172a","--limbo-bg-secondary":"#1e293b","--limbo-bg-tertiary":"#334155","--limbo-bg-overlay":"rgba(0, 0, 0, 0.8)","--limbo-bg-card":"#1e293b","--limbo-bg-input":"#334155","--limbo-text-primary":"#f8fafc","--limbo-text-secondary":"#cbd5e1","--limbo-text-tertiary":"#94a3b8","--limbo-text-inverse":"#0f172a","--limbo-text-muted":"#64748b","--limbo-border-light":"#334155","--limbo-border-medium":"#475569","--limbo-border-strong":"#64748b","--limbo-border-focus":"#60a5fa","--limbo-success":"#34d399","--limbo-success-light":"#064e3b","--limbo-error":"#f87171","--limbo-error-light":"#7f1d1d","--limbo-warning":"#fbbf24","--limbo-warning-light":"#78350f","--limbo-info":"#60a5fa","--limbo-info-light":"#1e3a8a","--limbo-shadow-sm":"0 1px 2px 0 rgba(0, 0, 0, 0.2)","--limbo-shadow-md":"0 4px 6px -1px rgba(0, 0, 0, 0.3)","--limbo-shadow-lg":"0 10px 15px -3px rgba(0, 0, 0, 0.4)","--limbo-shadow-xl":"0 20px 25px -5px rgba(0, 0, 0, 0.5)","--limbo-radius-sm":"4px","--limbo-radius-md":"6px","--limbo-radius-lg":"8px","--limbo-radius-xl":"12px","--limbo-font-family":"system-ui, -apple-system, sans-serif","--limbo-font-size-xs":"12px","--limbo-font-size-sm":"14px","--limbo-font-size-md":"16px","--limbo-font-size-lg":"18px","--limbo-font-size-xl":"20px","--limbo-z-dropdown":"1000","--limbo-z-sticky":"1020","--limbo-z-fixed":"1030","--limbo-z-modal":"1050","--limbo-z-tooltip":"1070","--limbo-transition-fast":"150ms cubic-bezier(0.4, 0, 0.2, 1)","--limbo-transition-normal":"300ms cubic-bezier(0.4, 0, 0.2, 1)","--limbo-transition-slow":"500ms cubic-bezier(0.4, 0, 0.2, 1)","--limbo-spacing-compact":"0.5rem","--limbo-spacing-compact-sm":"0.25rem","--limbo-spacing-compact-lg":"0.75rem","--limbo-font-size-compact-xs":"11px","--limbo-font-size-compact-sm":"12px","--limbo-font-size-compact-md":"14px","--limbo-font-size-compact-lg":"16px","--limbo-radius-compact":"4px","--limbo-radius-compact-sm":"3px","--limbo-radius-compact-lg":"6px","--limbo-button-height-compact":"32px","--limbo-input-height-compact":"36px","--limbo-modal-padding-compact":"12px","--limbo-card-padding-compact":"12px","--limbo-gap-compact":"8px","--limbo-gap-compact-sm":"4px","--limbo-gap-compact-lg":"12px"}},auto:{name:"auto",displayName:"Automático",variables:{}}},inheritance:{portalSelectors:["body","[data-theme]",".theme-light",".theme-dark",".light-theme",".dark-theme"],variablePrefix:"--",fallbackTheme:"light"},transitions:{duration:"300ms",easing:"cubic-bezier(0.4, 0, 0.2, 1)",properties:["background-color","border-color","color","fill","stroke","box-shadow"]}}}initialize(e={}){this.isInitialized?console.warn("ThemeManager already initialized"):(this.config=this._deepMerge(this.config,e),this._loadCustomThemes(),this.config.theme.inherit&&this._inheritPortalTheme(),this._applyInitialTheme(),this._applyInitialCompactMode(),this._setupObservers(),this._injectBaseStyles(),this.isInitialized=!0)}_injectBaseStyles(){if(document.getElementById("limbo-theme-styles"))return;const e=`\n :root {\n /* Variables de transición para cambios de tema */\n color-scheme: light dark;\n }\n \n [data-limbo-theme] {\n transition: ${this.config.transitions.properties.map(e=>`${e} ${this.config.transitions.duration} ${this.config.transitions.easing}`).join(", ")};\n }\n \n /* Clases de utilidad para temas */\n .limbo-theme-light {\n color-scheme: light;\n }\n \n .limbo-theme-dark {\n color-scheme: dark;\n }\n \n .limbo-theme-auto {\n color-scheme: light dark;\n }\n \n /* Estilos para elementos del componente con variables CSS */\n .limbo-component {\n background-color: var(--limbo-bg-primary);\n color: var(--limbo-text-primary);\n border-color: var(--limbo-border-light);\n border-radius: var(--limbo-radius-md);\n font-family: var(--limbo-font-family);\n font-size: var(--limbo-font-size-md);\n transition: var(--limbo-transition-normal);\n }\n \n .limbo-card {\n background-color: var(--limbo-bg-card);\n border: 1px solid var(--limbo-border-light);\n border-radius: var(--limbo-radius-lg);\n box-shadow: var(--limbo-shadow-md);\n color: var(--limbo-text-primary);\n }\n \n .limbo-input {\n background-color: var(--limbo-bg-input);\n border: 1px solid var(--limbo-border-medium);\n border-radius: var(--limbo-radius-md);\n color: var(--limbo-text-primary);\n font-family: var(--limbo-font-family);\n font-size: var(--limbo-font-size-md);\n transition: var(--limbo-transition-fast);\n }\n \n .limbo-input:focus {\n border-color: var(--limbo-border-focus);\n box-shadow: 0 0 0 3px var(--limbo-primary-light);\n outline: none;\n }\n \n .limbo-button {\n background-color: var(--limbo-primary);\n border: 1px solid var(--limbo-primary);\n border-radius: var(--limbo-radius-md);\n color: var(--limbo-text-inverse);\n font-family: var(--limbo-font-family);\n font-size: var(--limbo-font-size-md);\n transition: var(--limbo-transition-fast);\n cursor: pointer;\n }\n \n .limbo-button:hover {\n background-color: var(--limbo-primary-hover);\n border-color: var(--limbo-primary-hover);\n }\n \n .limbo-button.secondary {\n background-color: var(--limbo-bg-secondary);\n border-color: var(--limbo-border-medium);\n color: var(--limbo-text-primary);\n }\n \n .limbo-button.secondary:hover {\n background-color: var(--limbo-bg-tertiary);\n }\n \n /* Estados de feedback con variables */\n .limbo-state-success {\n background-color: var(--limbo-success-light);\n border-color: var(--limbo-success);\n color: var(--limbo-success);\n }\n \n .limbo-state-error {\n background-color: var(--limbo-error-light);\n border-color: var(--limbo-error);\n color: var(--limbo-error);\n }\n \n .limbo-state-warning {\n background-color: var(--limbo-warning-light);\n border-color: var(--limbo-warning);\n color: var(--limbo-warning);\n }\n \n .limbo-state-info {\n background-color: var(--limbo-info-light);\n border-color: var(--limbo-info);\n color: var(--limbo-info);\n }\n \n /* Overlay y modal con variables */\n .limbo-overlay {\n background-color: var(--limbo-bg-overlay);\n backdrop-filter: blur(4px);\n }\n \n .limbo-modal {\n background-color: var(--limbo-bg-card);\n border-radius: var(--limbo-radius-xl);\n box-shadow: var(--limbo-shadow-xl);\n color: var(--limbo-text-primary);\n }\n \n /* Responsive design con variables */\n @media (max-width: 640px) {\n .limbo-component {\n font-size: var(--limbo-font-size-sm);\n }\n }\n \n /* Modo reducido de movimiento */\n @media (prefers-reduced-motion: reduce) {\n [data-limbo-theme] {\n transition: none;\n }\n \n .limbo-component,\n .limbo-input,\n .limbo-button {\n transition: none;\n }\n }\n \n /* Esquemas de color automático */\n @media (prefers-color-scheme: dark) {\n :root:not([data-limbo-theme]) {\n color-scheme: dark;\n }\n }\n \n @media (prefers-color-scheme: light) {\n :root:not([data-limbo-theme]) {\n color-scheme: light;\n }\n }\n \n /* ===================================\n MODO COMPACTO - ESTILOS ESPECÍFICOS \n =================================== */\n \n /* Activación del modo compacto por atributo o clase */\n [data-limbo-compact="true"],\n .limbo-compact-mode {\n /* Componentes base más pequeños */\n --limbo-font-size-md: var(--limbo-font-size-compact-md);\n --limbo-font-size-sm: var(--limbo-font-size-compact-sm);\n --limbo-font-size-lg: var(--limbo-font-size-compact-lg);\n --limbo-spacing: var(--limbo-spacing-compact);\n --limbo-radius-md: var(--limbo-radius-compact);\n --limbo-gap: var(--limbo-gap-compact);\n }\n \n /* Botones compactos */\n [data-limbo-compact="true"] .limbo-button,\n .limbo-compact-mode .limbo-button {\n height: var(--limbo-button-height-compact);\n padding: var(--limbo-spacing-compact-sm) var(--limbo-spacing-compact);\n font-size: var(--limbo-font-size-compact-sm);\n border-radius: var(--limbo-radius-compact);\n min-width: auto;\n }\n \n /* Inputs compactos */\n [data-limbo-compact="true"] .limbo-input,\n .limbo-compact-mode .limbo-input {\n height: var(--limbo-input-height-compact);\n padding: var(--limbo-spacing-compact-sm) var(--limbo-spacing-compact);\n font-size: var(--limbo-font-size-compact-md);\n border-radius: var(--limbo-radius-compact);\n }\n \n /* Cards compactas */\n [data-limbo-compact="true"] .limbo-card,\n .limbo-compact-mode .limbo-card {\n padding: var(--limbo-card-padding-compact);\n border-radius: var(--limbo-radius-compact-lg);\n }\n \n /* Modales compactos */\n [data-limbo-compact="true"] .limbo-modal,\n .limbo-compact-mode .limbo-modal {\n padding: var(--limbo-modal-padding-compact);\n border-radius: var(--limbo-radius-compact-lg);\n max-width: 90vw;\n max-height: 90vh;\n }\n \n /* Tabs compactas */\n [data-limbo-compact="true"] .limbo-tabs,\n .limbo-compact-mode .limbo-tabs {\n gap: var(--limbo-gap-compact-sm);\n }\n \n [data-limbo-compact="true"] .limbo-tab,\n .limbo-compact-mode .limbo-tab {\n padding: var(--limbo-spacing-compact-sm) var(--limbo-spacing-compact);\n font-size: var(--limbo-font-size-compact-sm);\n border-radius: var(--limbo-radius-compact-sm);\n }\n \n /* Gallery compacta */\n [data-limbo-compact="true"] .limbo-gallery,\n .limbo-compact-mode .limbo-gallery {\n gap: var(--limbo-gap-compact-sm);\n }\n \n [data-limbo-compact="true"] .limbo-gallery-item,\n .limbo-compact-mode .limbo-gallery-item {\n border-radius: var(--limbo-radius-compact);\n min-height: 120px; /* Más pequeño para móviles */\n }\n \n /* Notificaciones compactas */\n [data-limbo-compact="true"] .limbo-notification,\n .limbo-compact-mode .limbo-notification {\n padding: var(--limbo-spacing-compact-sm) var(--limbo-spacing-compact);\n font-size: var(--limbo-font-size-compact-sm);\n border-radius: var(--limbo-radius-compact);\n }\n \n /* Progress indicators compactos */\n [data-limbo-compact="true"] .limbo-progress,\n .limbo-compact-mode .limbo-progress {\n height: 3px; /* Más delgado */\n }\n \n [data-limbo-compact="true"] .limbo-progress-circular,\n .limbo-compact-mode .limbo-progress-circular {\n width: 20px;\n height: 20px;\n }\n \n /* Auto-activación en pantallas pequeñas */\n @media (max-width: 768px) {\n :root[data-limbo-compact="auto"],\n .limbo-component[data-limbo-compact="auto"] {\n /* Aplicar automáticamente estilos compactos */\n --limbo-font-size-md: var(--limbo-font-size-compact-md);\n --limbo-font-size-sm: var(--limbo-font-size-compact-sm);\n --limbo-spacing: var(--limbo-spacing-compact);\n --limbo-radius-md: var(--limbo-radius-compact);\n --limbo-gap: var(--limbo-gap-compact);\n }\n \n /* Modal full-screen en móvil cuando es compacto */\n [data-limbo-compact="auto"] .limbo-modal,\n [data-limbo-compact="true"] .limbo-modal {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n width: 100vw;\n height: 100vh;\n max-width: 100vw;\n max-height: 100vh;\n border-radius: 0;\n margin: 0;\n }\n \n /* Tabs en accordion en móvil */\n [data-limbo-compact="auto"] .limbo-tabs,\n [data-limbo-compact="true"] .limbo-tabs {\n flex-direction: column;\n width: 100%;\n }\n \n /* Gallery de 2 columnas en móvil */\n [data-limbo-compact="auto"] .limbo-gallery,\n [data-limbo-compact="true"] .limbo-gallery {\n grid-template-columns: 1fr 1fr;\n gap: var(--limbo-gap-compact);\n }\n }\n \n /* Touch targets más grandes en móviles */\n @media (max-width: 768px) and (pointer: coarse) {\n [data-limbo-compact="auto"] .limbo-button,\n [data-limbo-compact="true"] .limbo-button {\n min-height: 44px; /* Tamaño mínimo de toque recomendado */\n padding: var(--limbo-spacing-compact) var(--limbo-spacing-compact-lg);\n }\n \n [data-limbo-compact="auto"] .limbo-tab,\n [data-limbo-compact="true"] .limbo-tab {\n min-height: 44px;\n }\n }\n `,t=document.createElement("style");t.id="limbo-theme-styles",t.textContent=e,document.head.appendChild(t)}applyTheme(e,t={}){const n=this._getTheme(e);if(!n)return console.warn(`Theme '${e}' not found`),!1;const l=this.currentTheme;return this._applyThemeVariables(n,t.scope),this._updateThemeAttributes(n.name),this.config.theme.storage&&!t.temporary&&this._saveThemePreference(n.name),this.currentTheme=n.name,this._triggerChangeCallbacks(n.name,l),!0}toggleTheme(e="light",t="dark"){const n=this.currentTheme===e?t:e;return this.applyTheme(n)}applyAutoTheme(){const e=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";return this.applyTheme(e)}registerTheme(e,t){const n={name:e,displayName:t.displayName||e,variables:t.variables||{},extends:t.extends||null,...t};if(n.extends){const e=this._getTheme(n.extends);e&&(n.variables={...e.variables,...n.variables})}return this.customThemes.set(e,n),this}removeTheme(e){if(this.config.presets[e])return console.warn(`Cannot remove predefined theme: ${e}`),!1;const t=this.customThemes.delete(e);return t&&this.currentTheme===e&&this.applyTheme(this.config.inheritance.fallbackTheme),t}getAvailableThemes(){const e=Object.keys(this.config.presets),t=Array.from(this.customThemes.keys());return{presets:e,custom:t,all:[...e,...t]}}getCurrentTheme(){return{name:this.currentTheme,theme:this._getTheme(this.currentTheme),isCustom:this.customThemes.has(this.currentTheme),variables:this._getCurrentVariables()}}enableCompactMode(e={}){const t={element:document.documentElement,persist:!0,...e};return t.element.setAttribute("data-limbo-compact","true"),t.element.classList.add("limbo-compact-mode"),this.isCompactMode=!0,t.persist&&this.config.compact.persistPreference&&this._saveCompactPreference(!0),this._triggerCompactChange(!0),this}disableCompactMode(e={}){const t={element:document.documentElement,persist:!0,...e};return t.element.setAttribute("data-limbo-compact","false"),t.element.classList.remove("limbo-compact-mode"),this.isCompactMode=!1,t.persist&&this.config.compact.persistPreference&&this._saveCompactPreference(!1),this._triggerCompactChange(!1),this}toggleCompactMode(e={}){return this.isCompactMode?this.disableCompactMode(e):this.enableCompactMode(e)}applyAutoCompactMode(){const e=this._shouldUseCompactMode();return e&&!this.isCompactMode?this.enableCompactMode({persist:!1}):!e&&this.isCompactMode&&this.disableCompactMode({persist:!1}),this}getCompactState(){return{isEnabled:this.isCompactMode,isAuto:this.config.compact.auto,breakpoint:this.config.compact.breakpoint,currentViewport:window.innerWidth,shouldBeCompact:this._shouldUseCompactMode()}}_shouldUseCompactMode(){if(!this.config.compact.auto)return this.config.compact.enabled;const e=window.innerWidth<=this.config.compact.breakpoint,t=/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),n="ontouchstart"in window||navigator.maxTouchPoints>0;return!(!this.config.compact.forceOnMobile||!t&&!n)||e}_saveCompactPreference(e){try{localStorage.setItem("limbo-compact-preference",e.toString())}catch(t){console.warn("Could not save compact preference:",t)}}_loadCompactPreference(){try{return"true"===localStorage.getItem("limbo-compact-preference")}catch(e){return console.warn("Could not load compact preference:",e),null}}_triggerCompactChange(e){this.changeCallbacks.forEach(t=>{try{t({type:"compact",isCompact:e,viewport:window.innerWidth,timestamp:Date.now()})}catch(n){console.error("Error in compact mode change callback:",n)}})}_inheritPortalTheme(){const e=this._detectPortalTheme();return e?(this.registerTheme("portal-inherited",e),"portal-inherited"):null}_detectPortalTheme(){const e={name:"portal-detected",displayName:"Tema del Portal",variables:{}};for(const t of this.config.inheritance.portalSelectors){const n=document.querySelector(t);if(n){const t=this._extractCSSVariables(n);Object.keys(t).length>0&&(e.variables={...e.variables,...t});const l=n.getAttribute("data-theme")||n.getAttribute("class")?.match(/theme-(\w+)/)||n.getAttribute("class")?.match(/(\w+)-theme/);l&&(e.detectedName=Array.isArray(l)?l[1]:l)}}return Object.keys(e.variables).length>0?e:null}_extractCSSVariables(e){const t={},n=getComputedStyle(e);["primary","primary-hover","primary-light","primary-dark","bg-primary","bg-secondary","bg-tertiary","bg-card","bg-input","text-primary","text-secondary","text-tertiary","text-inverse","border-light","border-medium","border-strong","border-focus","success","error","warning","info","shadow-sm","shadow-md","shadow-lg","shadow-xl","radius-sm","radius-md","radius-lg","radius-xl"].forEach(e=>{const l=`--limbo-${e}`,r=n.getPropertyValue(l).trim();r&&(t[l]=r)});return["--primary-color","--background-color","--text-color","--border-color","--accent-color","--surface-color"].forEach(e=>{const l=n.getPropertyValue(e).trim();if(l){const n=this._mapGenericToLimbo(e,l);n&&Object.assign(t,n)}}),t}_mapGenericToLimbo(e,t){return{"--primary-color":{"--limbo-primary":t},"--background-color":{"--limbo-bg-primary":t},"--text-color":{"--limbo-text-primary":t},"--border-color":{"--limbo-border-light":t},"--accent-color":{"--limbo-primary":t},"--surface-color":{"--limbo-bg-card":t}}[e]||null}_applyInitialTheme(){let e=this.config.inheritance.fallbackTheme;if(this.config.theme.storage){const t=this._loadThemePreference();t&&this._getTheme(t)&&(e=t)}const t=document.documentElement.getAttribute("data-limbo-theme");t&&this._getTheme(t)&&(e=t);const n=this._inheritPortalTheme();n&&(e=n),this.config.theme.auto&&"auto"===e&&(e=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),this.applyTheme(e,{temporary:!1})}_applyInitialCompactMode(){let e=!1;if(this.config.compact.persistPreference){const t=this._loadCompactPreference();null!==t&&(e=t)}const t=document.documentElement.getAttribute("data-limbo-compact");"true"===t?e=!0:"false"===t&&(e=!1),("auto"===t||this.config.compact.auto)&&(e=this._shouldUseCompactMode()),e?this.enableCompactMode({persist:!1}):this.disableCompactMode({persist:!1})}_applyThemeVariables(e,t=document.documentElement){const n="string"==typeof t?document.querySelector(t):t;n?(Object.entries(e.variables).forEach(([e,t])=>{n.style.setProperty(e,t),this.appliedStyles.add(`${n.tagName}:${e}`)}),this.themeCache.set(e.name,{theme:e,appliedAt:Date.now(),scope:n})):console.warn("Theme scope element not found")}_updateThemeAttributes(e){document.documentElement.setAttribute("data-limbo-theme",e),document.documentElement.classList.remove("limbo-theme-light","limbo-theme-dark","limbo-theme-auto"),document.documentElement.classList.add(`limbo-theme-${e}`),this._updateMetaThemeColor(e)}_updateMetaThemeColor(e){const t=this._getTheme(e);if(!t)return;const n=t.variables["--limbo-primary"]||"#3b82f6";let l=document.querySelector('meta[name="theme-color"]');l||(l=document.createElement("meta"),l.name="theme-color",document.head.appendChild(l)),l.content=n}_getTheme(e){return this.config.presets[e]?this.config.presets[e]:this.customThemes.has(e)?this.customThemes.get(e):null}_getCurrentVariables(){const e=this._getTheme(this.currentTheme);if(!e)return{};const t=getComputedStyle(document.documentElement),n={};return Object.keys(e.variables).forEach(e=>{n[e]=t.getPropertyValue(e).trim()}),n}_saveThemePreference(e){try{localStorage.setItem("limbo-theme-preference",e)}catch(t){console.warn("Could not save theme preference:",t)}}_loadThemePreference(){try{return localStorage.getItem("limbo-theme-preference")}catch(e){return console.warn("Could not load theme preference:",e),null}}_loadCustomThemes(){try{const e=localStorage.getItem("limbo-custom-themes");if(e){const t=JSON.parse(e);Object.entries(t).forEach(([e,t])=>{this.customThemes.set(e,t)})}}catch(e){console.warn("Could not load custom themes:",e)}}_saveCustomThemes(){try{const e=Object.fromEntries(this.customThemes);localStorage.setItem("limbo-custom-themes",JSON.stringify(e))}catch(e){console.warn("Could not save custom themes:",e)}}_setupObservers(){this.config.theme.detectSystem&&this._setupSystemObserver(),this.config.theme.storage&&this._setupStorageObserver(),this._setupMutationObserver(),this.config.compact.auto&&this._setupViewportObserver()}_setupSystemObserver(){const e=window.matchMedia("(prefers-color-scheme: dark)");e.addEventListener("change",e=>{if("auto"===this.currentTheme||this.config.theme.auto){const t=e.matches?"dark":"light";this.applyTheme(t,{temporary:!0})}}),this.mediaQueryObserver=e}_setupStorageObserver(){const e=e=>{"limbo-theme-preference"===e.key&&e.newValue!==this.currentTheme&&this._getTheme(e.newValue)&&this.applyTheme(e.newValue)};window.addEventListener("storage",e),this.storageListener=e}_setupMutationObserver(){const e=new MutationObserver(e=>{e.forEach(e=>{if("attributes"===e.type&&"data-limbo-theme"===e.attributeName){const t=e.target.getAttribute("data-limbo-theme");t&&t!==this.currentTheme&&this._getTheme(t)&&this.applyTheme(t)}})});e.observe(document.documentElement,{attributes:!0,attributeFilter:["data-limbo-theme"]}),this.mutationObserver=e}_setupViewportObserver(){const e=`(max-width: ${this.config.compact.breakpoint}px)`,t=window.matchMedia(e);t.addEventListener("change",()=>{("auto"===document.documentElement.getAttribute("data-limbo-compact")||this.config.compact.auto)&&this.applyAutoCompactMode()}),this.compactObserver=t,window.addEventListener("orientationchange",()=>{setTimeout(()=>{("auto"===document.documentElement.getAttribute("data-limbo-compact")||this.config.compact.auto)&&this.applyAutoCompactMode()},100)})}onThemeChange(e){return this.changeCallbacks.add(e),()=>this.changeCallbacks.delete(e)}_triggerChangeCallbacks(e,t){this.changeCallbacks.forEach(n=>{try{n({theme:e,previousTheme:t,themeData:this._getTheme(e),variables:this._getCurrentVariables()})}catch(l){console.error("Error in theme change callback:",l)}})}generateThemeFromColors(e,t){const n={name:e,displayName:e,variables:{}};t.primary&&(n.variables["--limbo-primary"]=t.primary,n.variables["--limbo-primary-hover"]=this._darkenColor(t.primary,10),n.variables["--limbo-primary-light"]=this._lightenColor(t.primary,40),n.variables["--limbo-primary-dark"]=this._darkenColor(t.primary,20)),t.background&&(n.variables["--limbo-bg-primary"]=t.background,n.variables["--limbo-bg-secondary"]=this._lightenColor(t.background,5),n.variables["--limbo-bg-tertiary"]=this._lightenColor(t.background,10),n.variables["--limbo-bg-card"]=t.background),t.text&&(n.variables["--limbo-text-primary"]=t.text,n.variables["--limbo-text-secondary"]=this._lightenColor(t.text,20),n.variables["--limbo-text-tertiary"]=this._lightenColor(t.text,40));const l=this._getTheme(this.config.inheritance.fallbackTheme);return l&&(n.variables={...l.variables,...n.variables}),this.registerTheme(e,n),n}_darkenColor(e,t){const n=parseInt(e.replace("#",""),16),l=Math.round(2.55*t),r=(n>>16)-l,a=(n>>8&255)-l,i=(255&n)-l;return"#"+(16777216+65536*(r<255?r<1?0:r:255)+256*(a<255?a<1?0:a:255)+(i<255?i<1?0:i:255)).toString(16).slice(1)}_lightenColor(e,t){const n=parseInt(e.replace("#",""),16),l=Math.round(2.55*t),r=(n>>16)+l,a=(n>>8&255)+l,i=(255&n)+l;return"#"+(16777216+65536*(r<255?r<1?0:r:255)+256*(a<255?a<1?0:a:255)+(i<255?i<1?0:i:255)).toString(16).slice(1)}_deepMerge(e,t){const n={...e};return Object.keys(t).forEach(l=>{t[l]&&"object"==typeof t[l]&&!Array.isArray(t[l])?n[l]=this._deepMerge(e[l]||{},t[l]):n[l]=t[l]}),n}getThemeInfo(){return{current:this.getCurrentTheme(),available:this.getAvailableThemes(),compact:this.getCompactState(),config:this.config,isInitialized:this.isInitialized,cache:{themes:this.themeCache.size,applied:this.appliedStyles.size},observers:{system:!!this.mediaQueryObserver,storage:!!this.storageListener,mutation:!!this.mutationObserver,viewport:!!this.compactObserver}}}debug(){return console.table(this.getThemeInfo()),this.getThemeInfo()}destroy(){this.mediaQueryObserver&&this.mediaQueryObserver.removeEventListener("change",this._setupSystemObserver),this.storageListener&&window.removeEventListener("storage",this.storageListener),this.mutationObserver&&this.mutationObserver.disconnect(),this.compactObserver&&this.compactObserver.removeEventListener("change",this._setupViewportObserver),this.changeCallbacks.clear(),this.themeCache.clear(),this.appliedStyles.clear(),this._saveCustomThemes();const e=document.getElementById("limbo-theme-styles");e&&e.remove(),this.isInitialized=!1}}const Jn={DEV:"https://led-dev-limbo-dev.eu.els.local",PROD:"https://limbo.lefebvre.es"};function Zn(e,t=!1){if(!e)return"";if(e.startsWith("/files/")){return(t?Jn.PROD:Jn.DEV)+e}return e}function el(e){return"string"!=typeof e?e:e.replace(/&quot;/g,'"').replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&#39;/g,"'").replace(/&#x27;/g,"'")}function tl(e){return!(!e||"string"!=typeof e)&&!e.startsWith("blob:")}function nl(e,t={}){if(!e)return"";const{prefer:n="crop",isProd:l=!1}=t,r=el(e);try{const e=JSON.parse(r),t=()=>{if(e.images&&Array.isArray(e.images))for(const t of e.images)if(t&&tl(t.url))return t.url;return null},a=e.original?.url,i=t();if("crop"===n){if(i)return Zn(i,l);if(tl(a))return Zn(a,l)}else{if(tl(a))return Zn(a,l);if(i)return Zn(i,l)}return tl(e.url)?Zn(e.url,l):""}catch{if("string"==typeof r){if(r.startsWith("blob:"))return"";if(r.startsWith("/files/"))return Zn(r,l);if(r.startsWith("http")||r.startsWith("/"))return r}}return"string"==typeof e&&(e.startsWith("{")||e.startsWith("["))?"":e}function ll(e,t={}){const{isProd:n=!1}=t;if(!e)return{original:null,images:[],url:""};try{const t=JSON.parse(el(e)),l=t.original?{...t.original,url:Zn(t.original.url,n)}:null,r=(t.images||[]).map(e=>({...e,url:Zn(e.url,n)}));return{original:l,images:r,url:r[0]?.url||l?.url||Zn(t.url,n)||""}}catch{return{original:null,images:[],url:Zn(e,n)}}}function rl(e,t={}){const{isProd:n=!1}=t;if(!e?.fields)return e;const l=e.fields.map(e=>{if("image"===e.type&&"string"==typeof e.example_value){const t=nl(e.example_value,{isProd:n});return{...e,example_value:t||e.example_value}}return e});return{...e,fields:l}}const al=new class{constructor(){this.config=new m,this.instances=new Hn,this.autoInputs=new Kn,this.events=new Gn,this.modals=new Qn,this.theme=new Yn,this.containerQueryDetector=S,this._setupInternalListeners(),this._initializeContainerQueries()}configure(e){var t;return this.config.setGlobal(e),t={publicKey:e.publicKey,apiKey:e.apiKey,token:e.token,authMode:e.authMode||"manual",tokenProvider:e.tokenProvider,prod:Boolean(e.prod)||!1,mode:e.mode||"embed",callbacks:e.callbacks||null},O={...O,...t},O.authMode||(O.token?O.authMode="manual":O.authMode="session"),this.config}setToken(e){return function(e){O.token=e}(e),this.config.setGlobal({token:e}),this}create(e){const t=this.config.merge(e);return this.instances.create(t,this.events,this.modals)}configureAutoInputs(e){return this.autoInputs.configure(e,this.config,this.events)}setTheme(e){return e&&(this.config.set("theme",e),this.theme.setTheme(e),this.events.emit("theme:changed",{theme:e})),this}getTheme(){return this.theme.getCurrentTheme()}scanAndActivate(e=null){const t=this.autoInputs.config?.dataset||"data-limbo-input-file",n=e||`[${t}]`,l=document.querySelectorAll(n);if(0===l.length)return{found:0,processed:0,skipped:0};let r=0,a=0;return l.forEach(e=>{try{this.autoInputs._processInput(e),r++}catch(t){console.warn(`⚠️ Limbo: Error procesando input ${e.id||e.name}:`,t),a++}}),this.events.emit("limbo:scanCompleted",{found:l.length,processed:r,skipped:a,inputs:Array.from(l)}),{found:l.length,processed:r,skipped:a}}_initializeContainerQueries(){this.containerQueryDetector.observeResize(),setTimeout(()=>{document.querySelectorAll(".limbo-component-container-wrapper").forEach(e=>{this.containerQueryDetector.applyResponsiveClasses(e)})},100)}rescan(e=document){const t=this.autoInputs.config?.dataset||"data-limbo-input-file",n=e.querySelectorAll(`[${t}]`);let l=0;return n.forEach(e=>{if(!this.autoInputs.instances.has(this.autoInputs._getInputId(e)))try{this.autoInputs._processInput(e),l++}catch(t){console.warn("⚠️ Limbo: Error procesando nuevo input:",t)}}),l}init(e){const t=this._mapLegacyOptions(e);return this.create(t)}getInstances(){return this.instances.getAll()}destroy(){this.instances.destroyAll(),this.autoInputs.cleanup(),this.events.cleanup(),this.theme.removeTheme()}_mapLegacyOptions(e){return{container:e.container||"#image-manager",mode:"embed",features:["gallery","upload","cropper"],apiKey:e.apiKey,prod:e.prod||!1,url:void 0===e.url||e.url}}_setupInternalListeners(){this.events.on("autoInputs:modalRequest",({config:e,callback:t,input:n})=>{this._handleAutoInputModalRequest({config:e,callback:t,input:n})})}_handleAutoInputModalRequest({config:e,callback:t,input:n}){const l=n,r=async n=>{let r={};if(n.crops&&n.crops.length>0){const e=n.asset||n.original;r.original={url:e?.url||e?.urlSigned||n.originalUrl,width:e?.width||n.originalWidth,height:e?.height||n.originalHeight,assetId:e?.id||n.assetId},r.images=n.crops.map(e=>({url:e.url||e.urlSigned,width:e.width,height:e.height,name:e.name||e.filename}))}else n.asset?r.original={url:n.asset.url||n.asset.urlSigned,width:n.asset.width,height:n.asset.height,assetId:n.asset.id}:n.master?.urlSigned||n.master?.url?r.original={url:n.master.urlSigned||n.master.url,width:n.master.width||n.width,height:n.master.height||n.height,assetId:n.assetId}:n.url||n.urlSigned?r.original={url:n.url||n.urlSigned,width:n.width,height:n.height,assetId:n.assetId||n.id}:(console.warn("[Limbo] handleResult: formato de datos no reconocido",n),r=n);if(l){var a=e?.returnConfig?.format||"json",o="";o="url"===a?r.images?.[0]?.url||r.original?.url||"":"assetId"===a?r.original?.assetId||"":JSON.stringify(r),l.value=o,l.dispatchEvent(new Event("change",{bubbles:!0})),console.log("[Limbo] ✅ Valor asignado al input:",l.value?.substring(0,80))}try{await t(r)}catch(s){}i.close()},a={...e,mode:"modal",autoDestroy:!0,interaction:{allowSelection:!0,allowCropping:!0,...e.interaction},callbacks:{onSelect:e=>{r(e)},onCropsSaved:e=>{r(e)},onCropperComplete:e=>{r(e)},onUpload:t=>{"upload-only"!==e.modeUI||e.features?.includes("cropper")||r(t)},onClose:()=>{}}};if(e.initialImageUrl){const t=this._extractAssetIdFromUrl(e.initialImageUrl)||e.existingData?.original?.assetId||null;t&&(a._externalImage={url:e.initialImageUrl,filename:e.initialImageUrl.split("/").pop()?.split("?")[0]||"image.jpg",width:1920,height:1080,mime_type:"image/jpeg",id:t})}e.cropper&&(a.cropper=e.cropper),this.config.setGlobal({interaction:{allowSelection:!0,allowCropping:!0,...e.interaction}});const i=this.create(a);i.open()}_extractAssetIdFromUrl(e){if(!e)return null;try{const t=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,n=e.match(t);return n&&n.length>=2?n[1]:n&&1===n.length?n[0]:null}catch(t){return console.warn("Error extracting asset ID from URL:",t),null}}openGallery(e={}){const t=this.create({mode:"modal",modeUI:"gallery-only",features:["gallery"],autoDestroy:!0,modal:{title:e.title||"Seleccionar Imagen",size:e.size||"large"},callbacks:{onSelect:n=>{e.onSelect?.(n),!1!==e.autoClose&&t.close()}},...e});return t.open(),t}openUploader(e={}){const t=!1!==e.redirectToGallery?["upload","gallery"]:["upload"],n=this.create({mode:"modal",modeUI:!1!==e.redirectToGallery?"full":"upload-only",features:t,autoDestroy:!0,modal:{title:e.title||"Subir Imagen",size:e.size||"medium"},callbacks:{onUpload:t=>{e.onUpload?.(t),!1===e.autoClose||e.redirectToGallery||n.close()}},...e});return n.open(),n}openCropper(e,t={}){if(!e)throw new Error("Limbo.openCropper: imageUrl es requerido");const n={url:e,filename:t.filename||"image.jpg",width:t.width||1920,height:t.height||1080,mime_type:t.mimeType||"image/jpeg",id:t.assetId||`external-${Date.now()}`},l=this.create({mode:"modal",modeUI:"crop-only",features:["cropper"],autoDestroy:!0,modal:{title:t.title||"Recortar Imagen",size:"xlarge"},cropper:{mandatoryCrops:t.mandatoryCrops||[],allowCustomCrops:!1!==t.allowCustomCrops,enforceRequiredCrops:!1!==t.enforceRequiredCrops},callbacks:{onCropperComplete:e=>{t.onComplete?.(e),!1!==t.autoClose&&l.close()},onCropperCancelled:e=>{t.onCancelled?.(e),!1!==t.autoClose&&l.close()},onCropperError:e=>{t.onError?.(e)}},_externalImage:n,...t});return l.open(),l}createInlineGallery(e,t={}){return this.create({container:e,mode:"embed",modeUI:"gallery-only",features:["gallery"],callbacks:{onSelect:t.onSelect,onDelete:t.onDelete},...t})}createInlineUploader(e,t={}){return this.create({container:e,mode:"embed",modeUI:"upload-only",features:["upload"],callbacks:{onUpload:t.onUpload},...t})}createStandaloneCropper(e,t,n={}){if(!e)throw new Error("Limbo.createStandaloneCropper: container es requerido");if(!t)throw new Error("Limbo.createStandaloneCropper: imageUrl es requerido");const l={url:t,filename:n.filename||"image.jpg",width:n.width||1920,height:n.height||1080,mime_type:n.mimeType||"image/jpeg",id:n.assetId||`external-${Date.now()}`};return this.create({container:e,mode:"embed",modeUI:"crop-only",features:["cropper"],autoHideOnComplete:!1!==n.autoHideOnComplete,cropper:{mandatoryCrops:n.mandatoryCrops||[],allowCustomCrops:!1!==n.allowCustomCrops,enforceRequiredCrops:!1!==n.enforceRequiredCrops},callbacks:{onCropperComplete:n.onComplete,onCropperCancelled:n.onCancelled,onCropperError:n.onError},_externalImage:l,...n})}createFullSelector(e,t={}){return this.create({container:e,mode:t.mode||"embed",modeUI:"full",features:["gallery","upload","cropper"],callbacks:{onSelect:t.onSelect,onUpload:t.onUpload,onDelete:t.onDelete,onCropsSaved:t.onCropsSaved},...t})}};"undefined"!=typeof window&&(window.Limbo=al,window.limboCore=al);"undefined"!=typeof window&&document.querySelector("#root")&&(al.configure({prod:!1,publicKey:"pk_e464fd744106b7a8d63d453c4bd02582",authMode:"session"}),al.create({container:"#root",mode:"embed",modeUI:"full",features:["gallery","upload","cropper"],title:"Limbo Image Manager - Development",url:!0}),al.configureAutoInputs({dataset:"data-limbo-input-file",return:"json",features:["gallery","upload","cropper"],modeUI:"full",modalSize:"large",title:"Seleccionar archivo",crops:"free",allowDelete:!1}));export{Jn as LIMBO_BASE_URL,el as decodeHtmlEntities,al as default,nl as extractImageUrl,tl as isValidImageUrl,ll as parseImageData,rl as prepareImageFieldsForPreview,Zn as resolveUrl};
664
+ /* @__PURE__ */s(Dn,{isOpen:D,onClose:O})]})}(()=>{try{const e=sessionStorage.getItem(jn);if(e){const t=JSON.parse(e),n=Date.now();Object.entries(t).forEach(([e,t])=>{t.timestamp&&n-t.timestamp<Fn&&Rn.set(e,t)})}}catch{}})();class Vn{constructor(e,t,n,l){this.id=e,this.config=t,this.eventManager=n,this.modalManager=l,this.root=null,this.container=null,this.modal=null,this.mounted=!1,this.destroyed=!1,this.button=null,this._validateConfig(),this._initialize()}_initialize(){"embed"===this.config.mode?this.mount():"button"===this.config.mode&&this._createButton(),this._emitDOMEvent("ready",{instance:this,config:this.config,timestamp:Date.now()})}mount(){if(this.mounted||this.destroyed)return this;if(this.container=this._resolveContainer(),!this.container)return this.eventManager.emit("error",{instanceId:this.id,error:"Container not found"}),this;try{this.root=N.createRoot(this.container),this.root.render(this._renderApp()),this.mounted=!0,this.eventManager.emit("ready",{instance:this})}catch(e){this.eventManager.emit("error",{instanceId:this.id,error:e.message})}return this}unmount(){return this.mounted?(this.root&&(this.root.unmount(),this.root=null),"button"===this.config.mode&&this.button,this.mounted=!1,this):this}open(){return"modal"!==this.config.mode&&"button"!==this.config.mode||(this.modal||this._createModal(),this.modal&&!this.modal.isOpened()&&(this.modal.open(),this.eventManager.emit("modal:open",{instance:this}))),this}close(){return this.modal&&this.modal.isOpened()&&(this.eventManager?.emit("modal:close",{instance:this}),this.modal.close()),this}updateConfig(e){return this.config={...this.config,...e},this.mounted&&this.root.render(this._renderApp()),this.eventManager.emit("config:updated",{instance:this,newConfig:e}),this}destroy(){this.destroyed||(this.unmount(),this.modal&&(this.modal.destroy(),this.modal=null),this.button&&this.button.parentNode&&(this.button.parentNode.removeChild(this.button),this.button=null),this.eventManager.emit("destroy",{instance:this}),this.container=null,this.config=null,this.eventManager=null,this.modalManager=null,this.destroyed=!0)}getId(){return this.id}getMode(){return this.config.mode}isMounted(){return this.mounted}isDestroyed(){return this.destroyed}getContainer(){return this.container}getConfig(){return{...this.config}}isContainerInDOM(){return this.container&&document.contains(this.container)}_createModal(){if(this.modalManager&&"modal"===this.config.mode&&(this.modal=this.modalManager.createModal({title:this.config.title||"Limbo Image Manager",size:this.config.modalSize||"large",onOpen:()=>{const e={instance:this,mode:"modal",timestamp:Date.now()};this._emitDOMEvent("modal:open",e),this.config.callbacks?.onOpen&&this.config.callbacks.onOpen(e)},onClose:()=>{const e={instance:this,mode:"modal",timestamp:Date.now()};this._emitDOMEvent("modal:close",e),this.config.callbacks?.onClose&&this.config.callbacks.onClose(e),this.config.autoDestroy&&this.destroy()},onDestroy:()=>{this.modal=null}}),this.modal)){const e=this.modal.getBodyContainer();this.root=N.createRoot(e),this.root.render(this._renderApp()),this.mounted=!0}}_createButton(){if(this.container||(this.container=this._resolveContainer()),!this.container)return void this.eventManager.emit("error",{instanceId:this.id,error:"Container not found for button mode"});const e=document.createElement("button");e.type="button",e.className="limbo-trigger-button",e.textContent=this.config.buttonText||"Abrir Limbo",e.style.cssText="\n background: #001978;\n color: white;\n border: none;\n padding: 10px 20px;\n border-radius: 6px;\n cursor: pointer;\n font-family: inherit;\n font-size: 14px;\n font-weight: 500;\n transition: all 0.2s ease;\n ",e.addEventListener("mouseenter",()=>{e.style.backgroundColor="#334793",e.style.transform="translateY(-1px)"}),e.addEventListener("mouseleave",()=>{e.style.backgroundColor="#001978",e.style.transform="translateY(0)"}),e.addEventListener("click",()=>{this.open()}),this.container.appendChild(e),this.button=e,this.mounted=!0}_resolveContainer(){const{container:e}=this.config;return e?"string"==typeof e?document.querySelector(e):e instanceof Element?e:null:null}_renderApp(){return e.createElement("div",{id:`limbo-component-container-${this.id}`,className:"limbo-scope limbo-instance limbo-component-container-wrapper lb:h-full lb:w-full lb:py-2 lb:pb-0 lb:bg-white","data-limbo-id":this.id,"data-limbo-mode":this.config.mode,"data-limbo-version":"3.3.6","data-limbo-isolated":"true","aria-label":"Limbo Image Manager",role:"region"},e.createElement(Wn,{apiKey:this.config.apiKey||null,publicKey:this.config.publicKey||null,token:this.config.token||null,prod:this.config.prod||!1,url:this.config.url,features:this.config.features,modeUI:this.config.modeUI||"full",ui:this.config.ui,callbacks:this._createCallbacks(),instanceId:this.id,authMode:this.config.authMode||(this.config.publicKey?"session":"manual"),_externalImage:this.config._externalImage||null,cropperConfig:this.config.cropper||null,allowedCategories:this.config.validation?.allowedCategories||null,folderConfig:this.config.folders||{include:[],exclude:[],includeNoFolder:!0}}))}_createCallbacks(){return{onSelect:e=>{const t=this.config?.callbacks?.onSelect,n=this._createStandardPayload(e,"select");t&&Promise.resolve(t(n)).catch(e=>{console.error("[LimboInstance] Error en onSelect callback:",e)}),this.destroyed||this._emitDOMEvent("select",n)},onUpload:e=>{const t=this.config?.callbacks?.onUpload,n=this._createStandardPayload(e,"upload");t&&Promise.resolve(t(n)).catch(e=>{console.error("[LimboInstance] Error en onUpload callback:",e)}),this.destroyed||this._emitDOMEvent("upload",n)},onError:e=>{const t=this.config?.callbacks?.onError,n={instance:this,error:{message:e.message||"Unknown error",code:e.code||"UNKNOWN",timestamp:Date.now()}};t&&t(n.error),this.destroyed||this._emitDOMEvent("error",n)},onClose:()=>{const e=this.config?.callbacks?.onClose,t={instance:this,timestamp:Date.now()};e&&e(),this.destroyed||this._emitDOMEvent("close",t)},onCropsSaved:e=>{console.log("[LimboInstance] onCropsSaved recibido:",e),console.log("[LimboInstance] this.config?.callbacks:",this.config?.callbacks);const t=this.config?.callbacks?.onCropsSaved;console.log("[LimboInstance] userCallback existe:",!!t);const n={instance:this,eventType:"cropsSaved",timestamp:Date.now(),instanceId:this.id,...e};if(console.log("[LimboInstance] payload.crops:",n.crops),t){console.log("[LimboInstance] Llamando userCallback onCropsSaved");try{t(n),console.log("[LimboInstance] userCallback ejecutado correctamente")}catch(l){console.error("[LimboInstance] Error en userCallback:",l)}}else console.warn("[LimboInstance] ⚠️ userCallback onCropsSaved NO existe");this.destroyed||this._emitDOMEvent("cropsSaved",n)},onCropperComplete:e=>{console.log("[LimboInstance] onCropperComplete recibido:",e);const t=this.config?.callbacks?.onCropperComplete,n={instance:this,eventType:"cropperComplete",timestamp:Date.now(),instanceId:this.id,...e};t&&(console.log("[LimboInstance] Llamando userCallback onCropperComplete"),t(n)),this.destroyed||this._emitDOMEvent("cropperComplete",n)}}}_createStandardPayload(e,t){const n={instance:this,eventType:t,timestamp:Date.now(),instanceId:this.id,mode:this.config?.mode,features:this.config?.features};return e&&(e.assetId||e.id?(n.assetId=e.assetId||e.id,n.variants=e.variants||[],n.master=e.master||{urlSigned:e.url||e.urlSigned,width:e.width,height:e.height,mime:e.mime||e.mimeType},n.fileName=e.fileName||e.name,n.mime=e.mime||e.mimeType,n.width=e.width,n.height=e.height,n.fileBlob=e.fileBlob||e.file,n.metadata={uploadedBy:e.uploadedBy,uploadedAt:e.uploadedAt||e.timestamp,size:e.size,...e.metadata}):Object.assign(n,e)),n}_emitDOMEvent(e,t){if(this.destroyed)return;const n=new CustomEvent(`limbo:${e}`,{detail:t,bubbles:!0,cancelable:!0});(this.getContainer()||document).dispatchEvent(n),this.eventManager?.emit(e,t)}_validateConfig(){const e=F();if(!(this.config.auth?.apiKey||this.config.auth?.publicKey||this.config.auth?.token||this.config.apiKey||this.config.publicKey||this.config.token||this.config.tokenProvider||this.config.auth?.tokenProvider||e.token||e.publicKey||e.tokenProvider))throw new Error(`LimboInstance ${this.id}: Authentication is required. Provide either auth.publicKey (recommended), auth.apiKey (for server-side only), token, or tokenProvider`);if((this.config.auth?.apiKey||this.config.apiKey)&&"undefined"!=typeof window&&console.warn("⚠️ SECURITY WARNING: API Key detected in client-side code.\nThis is a security risk! Use publicKey instead for client applications.\nAPI Keys should only be used in server-side environments."),!["embed","modal","button"].includes(this.config.mode))throw new Error(`LimboInstance ${this.id}: invalid mode ${this.config.mode}`);if("embed"===this.config.mode&&!this.config.container)throw new Error(`LimboInstance ${this.id}: container is required for embed mode`);if("button"===this.config.mode&&!this.config.container)throw new Error(`LimboInstance ${this.id}: container is required for button mode`)}}class Hn{constructor(){this.instances=/* @__PURE__ */new Map,this.counter=0}create(e,t,n){const l="limbo-"+ ++this.counter,r=new Vn(l,e,t,n);return this.instances.set(l,r),r}get(e){return this.instances.get(e)}getAll(){return Array.from(this.instances.values())}getActive(){return this.getAll().filter(e=>e.isMounted())}destroy(e){const t=this.instances.get(e);return!!t&&(t.destroy(),this.instances.delete(e),!0)}destroyAll(){this.instances.forEach(e=>e.destroy()),this.instances.clear()}cleanupOrphans(){const e=[];return this.instances.forEach((t,n)=>{t.isContainerInDOM()||e.push(n)}),e.forEach(e=>this.destroy(e)),e.length}getStats(){const e=this.getAll();return{total:e.length,active:e.filter(e=>e.isMounted()).length,embed:e.filter(e=>"embed"===e.getMode()).length,modal:e.filter(e=>"modal"===e.getMode()).length,button:e.filter(e=>"button"===e.getMode()).length}}}class Kn{constructor(){this.config=null,this.instances=/* @__PURE__ */new Map,this.observer=null,this.initialized=!1}configure(e,t,n){return this.config={selector:e.selector||null,dataset:e.dataset||"data-limbo-input-file",return:e.return||e.returnType||"json",mode:e.mode||"modal",features:e.features||["gallery","upload","cropper"],crop:e.crop||"free",quality:e.quality||.9,format:e.format||"webp",modeUI:e.modeUI||"full",modalSize:e.modalSize||"fullscreen",theme:e.theme||"light",compact:e.compact||!1,maxSize:e.maxSize||"10MB",formats:e.formats||["jpg","jpeg","png","webp"],minWidth:e.minWidth||null,minHeight:e.minHeight||null,maxWidth:e.maxWidth||null,maxHeight:e.maxHeight||null,buttonText:e.buttonText||"Seleccionar archivo",buttonClass:e.buttonClass||"limbo-auto-button",buttonStyle:e.buttonStyle||"primary",showPreview:!1!==e.showPreview,allowMultiple:e.allowMultiple||!1,autoAssign:!1!==e.autoAssign,localCropsOnly:e.localCropsOnly||!1,...e},this.configManager=t,this.eventManager=n,this._initialize(),this}cleanup(){this.observer&&(this.observer.disconnect(),this.observer=null),this.instances.forEach(({input:e,button:t})=>{this._restoreInput(e,t)}),this.instances.clear(),this.config=null,this.initialized=!1}getStats(){return{configured:null!==this.config,totalInputs:this.instances.size,dataset:this.config?.dataset,returnType:this.config?.return}}_initialize(){this.initialized||(this._scanExistingInputs(),this._setupObserver(),this.initialized=!0,this.eventManager.emit("autoInputs:initialized",{config:this.config,inputsFound:this.instances.size}))}_scanExistingInputs(){const e=this.config.selector||`input[${this.config.dataset}]`;document.querySelectorAll(e).forEach(e=>this._processInput(e))}_processInput(e){const t=this._getInputId(e);if(this.instances.has(t))return;if(!this._validateInput(e))return;const n=this._createButton(e);this._hideInput(e),this._insertButton(e,n),this.instances.set(t,{input:e,button:n,config:this._getInputConfig(e)}),this.eventManager.emit("autoInputs:processed",{inputId:t,input:e,button:n})}_createButton(e){const t=document.createElement("button"),n=this._getInputConfig(e);t.type="button",t.textContent=n.buttonText||this.config.buttonText;const l=[this.config.buttonClass];return n.buttonClass&&n.buttonClass!==this.config.buttonClass&&l.push(n.buttonClass),t.className=l.join(" "),this._styleButton(t,n),this._attachButtonEvents(t,e),t.setAttribute("aria-label",n.buttonText||this.config.buttonText),t.setAttribute("data-limbo-trigger","true"),t.setAttribute("data-limbo-input-id",n.inputId),n.disabled&&(t.disabled=!0),t}_styleButton(e,t){const n=t.buttonStyle||this.config.buttonStyle,l=t.theme||this.config.theme,r=t.compact||this.config.compact,a={border:"none",borderRadius:"8px",cursor:"pointer",fontFamily:"inherit",fontSize:r?"12px":"14px",fontWeight:"500",transition:"all 0.2s ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",padding:r?"6px 12px":"8px 16px",textDecoration:"none",userSelect:"none"},i={primary:{backgroundColor:"dark"===l?"#3b82f6":"#001978",color:"white",hoverBg:"dark"===l?"#2563eb":"#334793"},secondary:{backgroundColor:"dark"===l?"#374151":"#f3f4f6",color:"dark"===l?"#f9fafb":"#374151",border:"1px solid "+("dark"===l?"#4b5563":"#d1d5db"),hoverBg:"dark"===l?"#4b5563":"#e5e7eb"},outline:{backgroundColor:"transparent",color:"dark"===l?"#3b82f6":"#001978",border:"2px solid "+("dark"===l?"#3b82f6":"#001978"),hoverBg:"dark"===l?"#3b82f6":"#001978",hoverColor:"white"},ghost:{backgroundColor:"transparent",color:"dark"===l?"#f9fafb":"#374151",hoverBg:"dark"===l?"#374151":"#f3f4f6"}},o=i[n]||i.primary;Object.assign(e.style,{...a,...o});const s=o.backgroundColor,c=o.color;e.addEventListener("mouseenter",()=>{e.style.backgroundColor=o.hoverBg||o.backgroundColor,o.hoverColor&&(e.style.color=o.hoverColor),e.style.transform="translateY(-1px)",e.style.boxShadow="0 4px 12px rgba(0, 0, 0, 0.15)"}),e.addEventListener("mouseleave",()=>{e.style.backgroundColor=s,e.style.color=c,e.style.transform="translateY(0)",e.style.boxShadow="none"}),t.disabled&&(e.style.opacity="0.5",e.style.cursor="not-allowed")}_attachButtonEvents(e,t){e.addEventListener("click",e=>{e.preventDefault(),this._handleButtonClick(t)})}_handleButtonClick(e){const t=this._getInputConfig(e),n=this._createModalConfig(t);this.eventManager.emit("autoInputs:modalRequest",{input:e,config:n,callback:async t=>await this._handleImageSelection(e,t)})}async _handleImageSelection(e,t){const n=this._getInputConfig(e);let l=t;try{if(!t.original&&!t.images&&(t.id||t.assetId)){console.log("[AutoInputManager] 🔗 Selección directa detectada, obteniendo URL permanente...");const e=t.id||t.assetId;try{const n=await async function(e,t=!0,n=!0,l=0){try{const r=new URLSearchParams({include_variants:t.toString(),include_metadata:n.toString(),url_expires:l.toString()});return W(await j({endpoint:`/assets/${e}?${r}`,method:"GET",basePath:G,useJWT:!0}))}catch(r){throw K(r)}}(e,!1,!1,!0);n?.result?.url?(console.log("[AutoInputManager] ✅ URL permanente obtenida:",n.result.url),l={original:{url:n.result.url,width:n.result.width||t.width,height:n.result.height||t.height,assetId:e},images:[]}):(console.warn("[AutoInputManager] ⚠️ No se pudo obtener URL permanente, usando URL temporal"),l={original:{url:t.url||t.path,width:t.width,height:t.height,assetId:e},images:[]})}catch(r){console.error("[AutoInputManager] Error obteniendo URL permanente:",r),l={original:{url:t.url||t.path,width:t.width,height:t.height,assetId:e},images:[]}}}const a=await this._formatImageData(l,n);console.log("[AutoInputManager] Valor formateado:",a),console.log("[AutoInputManager] Tipo de valor:",typeof a),!1!==n.autoAssign&&(e.value=a,console.log("[AutoInputManager] Valor asignado al input:",e.value)),this._updateButtonFeedback(e,l),e.dispatchEvent(new Event("change",{bubbles:!0})),e.dispatchEvent(new CustomEvent("limbo:resultReady",{detail:{imageData:l,input:e,value:a,config:n,assignment:{format:n.return,smartAssign:!1!==n.smartAssign,autoAssign:!1!==n.autoAssign},legacy:{imageData:l,formatted:this._createFormattedResult(l,n)}},bubbles:!0})),e.dispatchEvent(new CustomEvent("limbo:imageSelected",{detail:{imageData:l,input:e,value:a,config:n,formatted:this._createFormattedResult(l,n)},bubbles:!0})),this.eventManager.emit("autoInputs:imageSelected",{input:e,imageData:l,value:a,config:n})}catch(a){console.error("Error handling image selection:",a),e.dispatchEvent(new CustomEvent("limbo:error",{detail:{error:a.message,input:e,imageData:l,config:n},bubbles:!0})),this._handleImageSelectionLegacy(e,t)}}_updateButtonFeedback(e,t){const n=this._getInputId(e),l=this.instances.get(n);if(!l||!l.button)return;const r=l.button,a=r.nextElementSibling;a&&a.classList.contains("limbo-button-feedback")&&a.remove();const i=document.createElement("span");i.className="limbo-button-feedback",i.style.cssText="\n display: inline-flex;\n align-items: center;\n gap: 6px;\n margin-left: 8px;\n padding: 4px 8px;\n background: #10b981;\n color: white;\n border-radius: 6px;\n font-size: 12px;\n font-weight: 500;\n animation: limbo-fade-in 0.3s ease-out;\n ";const o=t.images&&t.images.length>0,s=o?t.images.length:0;i.innerHTML=o?`\n <svg width="14" height="14" viewBox="0 0 20 20" fill="currentColor">\n <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"/>\n </svg>\n <span>${s} recorte${1!==s?"s":""} configurado${1!==s?"s":""}</span>\n `:'\n <svg width="14" height="14" viewBox="0 0 20 20" fill="currentColor">\n <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"/>\n </svg>\n <span>Archivo seleccionado</span>\n ',r.parentNode.insertBefore(i,r.nextSibling);let c=r.parentNode.querySelector(".limbo-powered-by");c||(c=document.createElement("div"),c.className="limbo-powered-by",c.innerHTML='<span style="display:block;margin-top:2px;font-size:10px;color:#aaa;text-align:left;font-family:inherit;opacity:0.7;">Powered by <b>Limbo</b></span>',r.parentNode.insertBefore(c,i.nextSibling)),r.style.backgroundColor="#10b981",r.textContent="Cambiar archivo"}async _handleImageSelectionLegacy(e,t){const n=this._getInputConfig(e),l=await this._formatImageData(t,n);!1!==n.autoAssign&&(e.value=l),e.dispatchEvent(new Event("change",{bubbles:!0})),e.dispatchEvent(new CustomEvent("limbo:imageSelected",{detail:{imageData:t,input:e,value:l,config:n,formatted:this._createFormattedResult(t,n)},bubbles:!0})),this.eventManager.emit("autoInputs:imageSelected",{input:e,imageData:t,value:l,config:n})}_createFormattedResult(e,t){return{url:e.url||e.path||"",base64:e.base64||e.dataUrl||"",assetId:e.assetId||e.id||"",fileName:e.fileName||e.filename||"",object:{url:e.url||e.path,assetId:e.assetId||e.id,fileName:e.fileName||e.filename,mime:e.mime||e.mime_type,width:e.width,height:e.height,size:e.size||e.file_size,created:e.created_at||e.created,metadata:e.metadata||{}},json:JSON.stringify({url:e.url||e.path,assetId:e.assetId||e.id,fileName:e.fileName||e.filename,mime:e.mime||e.mime_type,width:e.width,height:e.height,size:e.size||e.file_size}),metadata:{width:e.width,height:e.height,size:e.size||e.file_size,format:e.format||e.mime_type,quality:t.quality||this.config.quality,aspectRatio:e.width&&e.height?e.width/e.height:null}}}async _formatImageData(e,t=null){const n=(t||{}).return||this.config.return||"json",l=void 0!==e.original;switch(n){case"url":return l?e.images?.[0]?.url||e.original?.url||"":e.url||e.path||"";case"base64":return e.base64||e.dataUrl||"";case"assetId":return l?e.original?.assetId||"":e.assetId||e.id||"";case"fileName":return e.fileName||e.filename||"";default:try{if(l){const t={original:e.original?{url:e.original.url||e.original.urlSigned,width:e.original.width,height:e.original.height,assetId:e.original.assetId||e.original.id}:null,images:Array.isArray(e.images)?e.images.map(e=>{const t={url:e.url||e.urlSigned,width:e.width,height:e.height,name:e.name||e.filename||e.label};return e.cropState&&(t.cropState={selectorState:e.cropState.selectorState||null,imageTransform:e.cropState.imageTransform||null,flipState:e.cropState.flipState||null}),t}):[]};console.log("[AutoInputManager] Datos limpios para JSON:",t);const n=JSON.stringify(t);return console.log("[AutoInputManager] JSON generado:",n),n}const t={original:{url:e.url||e.path,width:e.width,height:e.height,assetId:e.assetId||e.id}};return console.log("[AutoInputManager] Datos legacy para JSON:",t),JSON.stringify(t)}catch(r){return console.error("[AutoInputManager] Error al serializar JSON:",r),console.error("[AutoInputManager] imageData problemático:",e),"{}"}}}_createModalConfig(e){return{mode:e.mode||this.config.mode||"modal",modeUI:e.modeUI||this.config.modeUI||"full",features:e.features||this.config.features,modalSize:e.modalSize||this.config.modalSize||"fullscreen",title:e.description||this.config.title||"Seleccionar archivo",cropper:this._getCropperConfig(e),ui:{showActions:this._getUIActions(e),hideActions:[],showTabs:this._shouldShowTabs(e),theme:e.theme||this.config.theme,compact:e.compact||this.config.compact,showPreview:void 0!==e.showPreview?e.showPreview:this.config.showPreview},validation:{maxSize:e.maxSize||this.config.maxSize,formats:e.formats||this.config.formats,minWidth:e.minWidth||this.config.minWidth,minHeight:e.minHeight||this.config.minHeight,maxWidth:e.maxWidth||this.config.maxWidth,maxHeight:e.maxHeight||this.config.maxHeight,required:e.required||!1},behavior:{allowMultiple:e.allowMultiple||this.config.allowMultiple,closeOnSelect:!0,autoAssign:void 0!==e.autoAssign?e.autoAssign:this.config.autoAssign,allowSelectNew:!1!==e.allowSelectNew},initialImageUrl:e.initialImageUrl||null,existingCrops:e.existingCrops||null,existingData:e.existingData||null,returnConfig:{format:e.return||this.config.return,quality:e.quality||this.config.quality,outputFormat:e.format||this.config.format},inputMeta:{inputId:e.inputId,inputName:e.inputName,inputType:e.inputType,placeholder:e.placeholder}}}_getCropperConfig(e){const t=e.crop||this.config.crop,n={quality:e.quality||this.config.quality,format:e.format||this.config.format,mandatoryCrops:e.mandatoryCrops||[],allowAdditionalCrops:!1!==e.allowAdditionalCrops,maxCrops:e.maxCrops||null,localCropsOnly:e.localCropsOnly??this.config.localCropsOnly??!1,existingCrops:e.existingCrops||null};if(e.mandatoryCrops&&e.mandatoryCrops.length>0)return{...n,aspectRatio:null};if(!t||"none"===t||"false"===t)return null;if("free"===t)return{...n,aspectRatio:null};const l={"1:1":1,"16:9":16/9,"4:3":4/3,"3:2":1.5,"2:1":2,square:1,landscape:16/9,portrait:3/4};if(l[t])return{...n,aspectRatio:l[t],minCropBoxWidth:e.minWidth||this.config.minWidth,minCropBoxHeight:e.minHeight||this.config.minHeight};if("string"==typeof t&&t.includes(":")){const[e,l]=t.split(":").map(Number);if(!isNaN(e)&&!isNaN(l)&&0!==l)return{...n,aspectRatio:e/l}}const r=parseFloat(t);return!isNaN(r)&&r>0?{...n,aspectRatio:r}:"object"==typeof t?{...n,...t}:null}_shouldShowTabs(e){const t=e.modeUI||this.config.modeUI||"full",n=e.features||this.config.features;return!["gallery-only","upload-only","crop-only","ia-only"].includes(t)&&(n&&n.length>1)}_getUIActions(e){const t=e.modeUI||this.config.modeUI||"full",n=e.features||this.config.features;let l=[];switch(t){case"gallery-only":case"upload-only":l=["select"];break;case"crop-only":l=["select","crop"];break;default:l=["select"],n.includes("cropper")&&l.push("crop"),n.includes("gallery")&&(l.push("download","copy"),this.config.allowDelete&&l.push("delete"))}return l}_getInputId(e){if(e.id)return e.id;if(e.name)return e.name;let t=e.getAttribute("data-limbo-uid");return t||(t=`limbo-auto-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,e.setAttribute("data-limbo-uid",t)),t}_validateInput(e){return e instanceof HTMLInputElement}_getInputConfig(e){const t=e=>e?e.split(",").map(e=>e.trim()):null,n=e=>{if(!e)return null;const t=e.match(/^(\d+(?:\.\d+)?)(MB|KB|B)?$/i);if(!t)return null;const n=parseFloat(t[1]);switch((t[2]||"B").toUpperCase()){case"MB":return 1024*n*1024;case"KB":return 1024*n;default:return n}},l=(e,t=!1)=>null===e?t:"true"===e||"1"===e||""===e,r=e=>e?parseFloat(e):null,a=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return console.warn("[Limbo AutoInputManager] Error parsing JSON attribute:",t),null}},i=a(e.dataset.mandatorycrops)||a(e.dataset.mandatoryCrops)||a(e.getAttribute("data-mandatory-crops"))||a(e.getAttribute("data-limbo-mandatory-crops"))||null;return{return:e.dataset.returntype||e.getAttribute("data-limbo-return")||this.config.return,mode:e.dataset.mode||e.getAttribute("data-limbo-mode")||this.config.mode,features:t(e.dataset.features)||t(e.getAttribute("data-limbo-features"))||this.config.features,crop:e.dataset.crop||e.getAttribute("data-limbo-crop")||this.config.crop,quality:r(e.dataset.quality)||r(e.getAttribute("data-limbo-quality"))||this.config.quality,format:e.dataset.format||e.getAttribute("data-limbo-format")||this.config.format,modeUI:e.dataset.modeui||e.dataset.modeUI||e.getAttribute("data-limbo-mode-ui")||this.config.modeUI,modalSize:e.dataset.modalsize||e.getAttribute("data-limbo-modal-size")||this.config.modalSize,theme:e.dataset.theme||e.getAttribute("data-limbo-theme")||this.config.theme,compact:l(e.dataset.compact,null)??l(e.getAttribute("data-limbo-compact"),this.config.compact),maxSize:n(e.getAttribute("data-limbo-max-size"))||n(this.config.maxSize),formats:t(e.getAttribute("data-limbo-formats"))||this.config.formats,minWidth:r(e.getAttribute("data-limbo-min-width"))||this.config.minWidth,minHeight:r(e.getAttribute("data-limbo-min-height"))||this.config.minHeight,maxWidth:r(e.getAttribute("data-limbo-max-width"))||this.config.maxWidth,maxHeight:r(e.getAttribute("data-limbo-max-height"))||this.config.maxHeight,buttonText:e.dataset.buttontext||e.getAttribute("data-limbo-button-text")||this.config.buttonText,buttonStyle:e.dataset.buttonstyle||e.getAttribute("data-limbo-button-style")||this.config.buttonStyle,buttonClass:e.dataset.buttonclass||e.getAttribute("data-limbo-button-class")||this.config.buttonClass,showPreview:l(e.getAttribute("data-limbo-show-preview"),this.config.showPreview),allowMultiple:l(e.getAttribute("data-limbo-allow-multiple"),this.config.allowMultiple),autoAssign:l(e.getAttribute("data-limbo-auto-assign"),this.config.autoAssign),placeholder:e.getAttribute("data-limbo-placeholder"),description:e.getAttribute("data-limbo-description"),required:l(e.getAttribute("data-limbo-required"),!1),disabled:l(e.getAttribute("data-limbo-disabled"),!1),inputId:this._getInputId(e),inputName:e.name,inputType:e.type,mandatoryCrops:i,allowAdditionalCrops:l(e.dataset.allowadditionalcrops,null)??l(e.getAttribute("data-limbo-allow-additional-crops"),!0),maxCrops:r(e.dataset.maxcrops)||r(e.getAttribute("data-limbo-max-crops"))||null,allowSelectNew:l(e.dataset.allowselectnew,null)??l(e.getAttribute("data-limbo-allow-select-new"),!0),...this._parseExistingInputValue(e.value)}}_parseExistingInputValue(e){if(!e||""===e.trim())return{initialImageUrl:null,existingCrops:null,existingData:null};try{const t=JSON.parse(e);return t.original&&t.original.url?(console.log("[AutoInputManager] Valor existente parseado:",t),{initialImageUrl:t.original.url,existingCrops:t.images||null,existingData:t}):t.url?{initialImageUrl:t.url,existingCrops:null,existingData:t}:{initialImageUrl:null,existingCrops:null,existingData:t}}catch(t){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?{initialImageUrl:e,existingCrops:null,existingData:null}:{initialImageUrl:null,existingCrops:null,existingData:null}}}_generateInputId(){return`limbo-auto-input-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}_hideInput(e){e.style.display="none"}_insertButton(e,t){e.parentNode.insertBefore(t,e.nextSibling)}_restoreInput(e,t){e.style.display="",t&&t.parentNode&&t.parentNode.removeChild(t)}_setupObserver(){this.observer=new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e.nodeType===Node.ELEMENT_NODE&&this._scanNodeForInputs(e)})})}),this.observer.observe(document.body,{childList:!0,subtree:!0})}_scanNodeForInputs(e){const t=this.config.selector||`input[${this.config.dataset}]`;e.matches&&e.matches(t)&&this._processInput(e);const n=e.querySelectorAll&&e.querySelectorAll(t);n&&n.forEach(e=>this._processInput(e))}}class Gn{constructor(){this.listeners=/* @__PURE__ */new Map}emit(e,t={}){this._emitDOMEvent(e,t),this._executeListeners(e,t)}on(e,t){return this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t),()=>this.off(e,t)}off(e,t){const n=this.listeners.get(e);if(n){const e=n.indexOf(t);e>-1&&n.splice(e,1)}}cleanup(){this.listeners.clear()}_emitDOMEvent(e,t){const n=new CustomEvent(`limbo:${e}`,{detail:{...t,timestamp:Date.now()},bubbles:!0,cancelable:!0});(t.instance?.getContainer()||document).dispatchEvent(n)}_executeListeners(e,t){const n=this.listeners.get(e);n&&n.forEach(n=>{try{n(t)}catch(l){console.error(`Error executing listener for ${e}:`,l)}})}getStats(){const e={};return this.listeners.forEach((t,n)=>{e[n]=t.length}),e}}class Qn{constructor(){this.activeModals=/* @__PURE__ */new Set,this.zIndexBase=1e4,this.focusableSelectors=["button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"]):not([disabled])',"a[href]"].join(", "),this.initialized=!1,this._initGlobalListeners()}createModal(e){const t=new Xn(this._generateModalId(),e,this);return this.activeModals.add(t),t}closeModal(e){const t=this._findModal(e);return!!t&&(t.close(),!0)}closeAllModals(){this.activeModals.forEach(e=>e.close()),this.activeModals.clear()}getActiveModal(){return Array.from(this.activeModals).pop()||null}getStats(){return{active:this.activeModals.size,nextZIndex:this._getNextZIndex()}}_generateModalId(){return`limbo-modal-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}_findModal(e){return Array.from(this.activeModals).find(t=>t.getId()===e)}_getNextZIndex(){return this.zIndexBase+10*this.activeModals.size}_removeModal(e){this.activeModals.delete(e),window.limboCore?.events&&window.limboCore.events.emit("modal:closed",{modalId:e.getId(),remainingModals:this.activeModals.size})}_handleGlobalKeydown(e){const t=this.getActiveModal();t&&("Escape"===e.key&&(e.preventDefault(),t.close()),"Tab"===e.key&&this._handleTabTrap(e,t))}_handleTabTrap(e,t){const n=t.getFocusableElements();if(0===n.length)return;const l=n[0],r=n[n.length-1];e.shiftKey?document.activeElement===l&&(e.preventDefault(),r.focus()):document.activeElement===r&&(e.preventDefault(),l.focus())}_initGlobalListeners(){this.initialized||(this.globalKeydownHandler=e=>this._handleGlobalKeydown(e),document.addEventListener("keydown",this.globalKeydownHandler),this.initialized=!0)}destroy(){this.closeAllModals(),this.initialized&&this.globalKeydownHandler&&(document.removeEventListener("keydown",this.globalKeydownHandler),this.initialized=!1,this.globalKeydownHandler=null)}}class Xn{constructor(e,t,n){this.id=e,this.config={title:t.title||"Limbo",content:t.content||null,showCloseButton:!1!==t.showCloseButton,backdrop:!1!==t.backdrop,keyboard:!1!==t.keyboard,focus:!1!==t.focus,animation:!1!==t.animation,size:t.size||"large",onOpen:t.onOpen||null,onClose:t.onClose||null,onDestroy:t.onDestroy||null,...t},this.manager=n,this.element=null,this.backdrop=null,this.isOpen=!1,this.previousFocus=null,this._create()}_create(){this._createBackdrop(),this._createModal(),this._attachEvents()}_createBackdrop(){this.config.backdrop&&(this.backdrop=document.createElement("div"),this.backdrop.className="limbo-modal-backdrop",this.backdrop.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: rgba(0, 0, 0, 0.5);\n z-index: ${this.manager._getNextZIndex()};\n opacity: 0;\n transition: opacity 0.3s ease;\n `,this.backdrop.addEventListener("click",e=>{e.target===this.backdrop&&this.close()}))}_createModal(){this.element=document.createElement("div"),this.element.className=`limbo-scope limbo-modal limbo-modal--${this.config.size}`,this.element.id=this.id,this.element.role="dialog",this.element.setAttribute("aria-modal","true"),this.element.setAttribute("aria-labelledby",`${this.id}-title`),this.element.tabIndex=-1;const e=window.innerWidth<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),t={small:e?"width: 100%; height: 100%;":"max-width: 500px; min-height: 400px;",medium:e?"width: 100%; height: 100%;":"max-width: 800px; min-height: 500px;",large:e?"width: 100%; height: 100%;":"max-width: 1400px; min-height: 700px;",xlarge:e?"width: 100%; height: 100%;":"max-width: 95dvw; min-height: 85vh;",fullscreen:"width: 100%; height: 100%; max-width: 100%; max-height: 100%; border-radius: 0;"},n="fullscreen"===this.config.size,l=e||n?`\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n transform: ${e?"translateY(100%)":"scale(0.95)"};\n width: 100%;\n height: 100%;\n max-width: none;\n max-height: none;\n border-radius: 0;\n background: white;\n z-index: ${this.manager._getNextZIndex()+1};\n opacity: ${e?"1":"0"};\n transition: ${e?"transform":"all"} 0.3s cubic-bezier(0.4, 0, 0.2, 1);\n overflow: hidden;\n display: flex;\n flex-direction: column;\n padding-top: env(safe-area-inset-top);\n padding-left: env(safe-area-inset-left);\n padding-right: env(safe-area-inset-right);\n padding-bottom: env(safe-area-inset-bottom);\n `:`\n position: fixed;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%) scale(0.8);\n ${t[this.config.size]}\n width: 90%;\n max-height: 90vh;\n background: white;\n border-radius: 16px;\n box-shadow: 0 25px 50px rgba(0, 0, 0, 0.25);\n z-index: ${this.manager._getNextZIndex()+1};\n opacity: 0;\n transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);\n overflow: hidden;\n display: flex;\n flex-direction: column;\n `;this.element.style.cssText=l,this._createHeader(),this._createBody(),document.body.appendChild(this.backdrop),document.body.appendChild(this.element)}_createHeader(){const e=document.createElement("div");e.className="limbo-modal-header";const t=window.innerWidth<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);e.style.cssText=`\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: ${t?"16px 20px":"20px 24px"};\n border-bottom: 1px solid #e9ecef;\n background: #f8f9fa;\n ${t?"position: sticky; top: 0; z-index: 10;":""}\n min-height: ${t?"60px":"auto"};\n `;const n=document.createElement("h2");if(n.id=`${this.id}-title`,n.className="limbo-modal-title",n.textContent=this.config.title,n.style.cssText="\n margin: 0;\n font-size: 18px;\n font-weight: 600;\n color: #001978;\n flex: 1;\n margin-right: 16px;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n ",e.appendChild(n),this.config.showCloseButton){const n=document.createElement("button");n.type="button",n.className="limbo-modal-close",n.innerHTML="✕",n.setAttribute("aria-label","Cerrar modal"),n.style.cssText=`\n background: none;\n border: none;\n font-size: ${t?"28px":"24px"};\n color: #6c757d;\n cursor: pointer;\n padding: ${t?"8px":"4px"};\n border-radius: 4px;\n transition: all 0.2s ease;\n min-width: ${t?"44px":"auto"};\n min-height: ${t?"44px":"auto"};\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n `,n.addEventListener("mouseenter",()=>{n.style.backgroundColor="#f8f9fa",n.style.color="#001978"}),n.addEventListener("mouseleave",()=>{n.style.backgroundColor="transparent",n.style.color="#6c757d"}),n.addEventListener("click",()=>this.close()),e.appendChild(n)}this.element.appendChild(e)}_createBody(){const e=window.innerWidth<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),t=document.createElement("div");t.className="limbo-modal-body",t.id=`${this.id}-body`,t.style.cssText=`\n flex: 1;\n overflow-y: auto;\n padding: 0;\n -webkit-overflow-scrolling: touch;\n ${e?"height: 100%; overscroll-behavior: contain;":""}\n `,this.config.content&&("string"==typeof this.config.content?t.innerHTML=this.config.content:this.config.content instanceof Element&&t.appendChild(this.config.content)),this.element.appendChild(t)}_attachEvents(){this._originalBodyOverflow=document.body.style.overflow}open(){if(this.isOpen)return this;window.limbo&&window.limbo.core&&window.limbo.core.keyboard?(window.limbo.core.keyboard.pushFocus(document.activeElement),window.limbo.core.keyboard.setActiveModal(this.element)):this.previousFocus=document.activeElement,document.body.style.overflow="hidden";const e=window.innerWidth<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),t="fullscreen"===this.config.size;return requestAnimationFrame(()=>{this.backdrop&&(this.backdrop.style.opacity="1"),this.element.style.opacity="1",this.element.style.transform=e?"translateY(0%)":t?"scale(1)":"translate(-50%, -50%) scale(1)"}),this.isOpen=!0,this.config.focus&&setTimeout(()=>{if(window.limbo&&window.limbo.core&&window.limbo.core.keyboard)window.limbo.core.keyboard.focusFirst(this.element);else{const e=this.getFocusableElements()[0];e&&e.focus()}},300),this.config.onOpen&&this.config.onOpen(this),this}close(){if(!this.isOpen)return this;const e=window.innerWidth<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),t="fullscreen"===this.config.size;return this.backdrop&&(this.backdrop.style.opacity="0"),this.element.style.opacity="0",this.element.style.transform=e?"translateY(100%)":t?"scale(0.95)":"translate(-50%, -50%) scale(0.8)",setTimeout(()=>{this._cleanup()},300),this.isOpen=!1,window.limbo&&window.limbo.core&&window.limbo.core.keyboard&&(window.limbo.core.keyboard.setActiveModal(null),window.limbo.core.keyboard.releaseFocus()),this.config.onClose&&this.config.onClose(this),this}destroy(){this.close(),this.manager._removeModal(this),this.config.onDestroy&&this.config.onDestroy(this)}getBodyContainer(){return this.element.querySelector(".limbo-modal-body")}getFocusableElements(){return Array.from(this.element.querySelectorAll(this.manager.focusableSelectors))}getId(){return this.id}isOpened(){return this.isOpen}getConfig(){return{...this.config}}_cleanup(){document.body.style.overflow=this._originalBodyOverflow||"",this.previousFocus&&"function"==typeof this.previousFocus.focus&&this.previousFocus.focus(),this.backdrop&&this.backdrop.parentNode&&this.backdrop.parentNode.removeChild(this.backdrop),this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element)}}class Yn{constructor(){this.currentTheme=null,this.customThemes=/* @__PURE__ */new Map,this.config=this._getDefaultConfig(),this.isInitialized=!1,this.isCompactMode=!1,this.compactBreakpoint=null,this.compactObserver=null,this.mediaQueryObserver=null,this.mutationObserver=null,this.storageListener=null,this.themeCache=/* @__PURE__ */new Map,this.appliedStyles=/* @__PURE__ */new Set,this.changeCallbacks=/* @__PURE__ */new Set}_getDefaultConfig(){return{theme:{auto:!0,storage:!0,inherit:!0,smooth:!0,detectSystem:!0},compact:{enabled:!1,auto:!0,breakpoint:768,forceOnMobile:!0,persistPreference:!0},presets:{light:{name:"light",displayName:"Claro",variables:{"--limbo-primary":"#3b82f6","--limbo-primary-hover":"#2563eb","--limbo-primary-light":"#dbeafe","--limbo-primary-dark":"#1e40af","--limbo-bg-primary":"#ffffff","--limbo-bg-secondary":"#f8fafc","--limbo-bg-tertiary":"#f1f5f9","--limbo-bg-overlay":"rgba(0, 0, 0, 0.5)","--limbo-bg-card":"#ffffff","--limbo-bg-input":"#ffffff","--limbo-text-primary":"#0f172a","--limbo-text-secondary":"#475569","--limbo-text-tertiary":"#64748b","--limbo-text-inverse":"#ffffff","--limbo-text-muted":"#94a3b8","--limbo-border-light":"#e2e8f0","--limbo-border-medium":"#cbd5e1","--limbo-border-strong":"#94a3b8","--limbo-border-focus":"#3b82f6","--limbo-success":"#10b981","--limbo-success-light":"#d1fae5","--limbo-error":"#ef4444","--limbo-error-light":"#fee2e2","--limbo-warning":"#f59e0b","--limbo-warning-light":"#fef3c7","--limbo-info":"#3b82f6","--limbo-info-light":"#dbeafe","--limbo-shadow-sm":"0 1px 2px 0 rgba(0, 0, 0, 0.05)","--limbo-shadow-md":"0 4px 6px -1px rgba(0, 0, 0, 0.1)","--limbo-shadow-lg":"0 10px 15px -3px rgba(0, 0, 0, 0.1)","--limbo-shadow-xl":"0 20px 25px -5px rgba(0, 0, 0, 0.1)","--limbo-radius-sm":"4px","--limbo-radius-md":"6px","--limbo-radius-lg":"8px","--limbo-radius-xl":"12px","--limbo-font-family":"system-ui, -apple-system, sans-serif","--limbo-font-size-xs":"12px","--limbo-font-size-sm":"14px","--limbo-font-size-md":"16px","--limbo-font-size-lg":"18px","--limbo-font-size-xl":"20px","--limbo-z-dropdown":"1000","--limbo-z-sticky":"1020","--limbo-z-fixed":"1030","--limbo-z-modal":"1050","--limbo-z-tooltip":"1070","--limbo-transition-fast":"150ms cubic-bezier(0.4, 0, 0.2, 1)","--limbo-transition-normal":"300ms cubic-bezier(0.4, 0, 0.2, 1)","--limbo-transition-slow":"500ms cubic-bezier(0.4, 0, 0.2, 1)","--limbo-spacing-compact":"0.5rem","--limbo-spacing-compact-sm":"0.25rem","--limbo-spacing-compact-lg":"0.75rem","--limbo-font-size-compact-xs":"11px","--limbo-font-size-compact-sm":"12px","--limbo-font-size-compact-md":"14px","--limbo-font-size-compact-lg":"16px","--limbo-radius-compact":"4px","--limbo-radius-compact-sm":"3px","--limbo-radius-compact-lg":"6px","--limbo-button-height-compact":"32px","--limbo-input-height-compact":"36px","--limbo-modal-padding-compact":"12px","--limbo-card-padding-compact":"12px","--limbo-gap-compact":"8px","--limbo-gap-compact-sm":"4px","--limbo-gap-compact-lg":"12px"}},dark:{name:"dark",displayName:"Oscuro",variables:{"--limbo-primary":"#60a5fa","--limbo-primary-hover":"#3b82f6","--limbo-primary-light":"#1e293b","--limbo-primary-dark":"#93c5fd","--limbo-bg-primary":"#0f172a","--limbo-bg-secondary":"#1e293b","--limbo-bg-tertiary":"#334155","--limbo-bg-overlay":"rgba(0, 0, 0, 0.8)","--limbo-bg-card":"#1e293b","--limbo-bg-input":"#334155","--limbo-text-primary":"#f8fafc","--limbo-text-secondary":"#cbd5e1","--limbo-text-tertiary":"#94a3b8","--limbo-text-inverse":"#0f172a","--limbo-text-muted":"#64748b","--limbo-border-light":"#334155","--limbo-border-medium":"#475569","--limbo-border-strong":"#64748b","--limbo-border-focus":"#60a5fa","--limbo-success":"#34d399","--limbo-success-light":"#064e3b","--limbo-error":"#f87171","--limbo-error-light":"#7f1d1d","--limbo-warning":"#fbbf24","--limbo-warning-light":"#78350f","--limbo-info":"#60a5fa","--limbo-info-light":"#1e3a8a","--limbo-shadow-sm":"0 1px 2px 0 rgba(0, 0, 0, 0.2)","--limbo-shadow-md":"0 4px 6px -1px rgba(0, 0, 0, 0.3)","--limbo-shadow-lg":"0 10px 15px -3px rgba(0, 0, 0, 0.4)","--limbo-shadow-xl":"0 20px 25px -5px rgba(0, 0, 0, 0.5)","--limbo-radius-sm":"4px","--limbo-radius-md":"6px","--limbo-radius-lg":"8px","--limbo-radius-xl":"12px","--limbo-font-family":"system-ui, -apple-system, sans-serif","--limbo-font-size-xs":"12px","--limbo-font-size-sm":"14px","--limbo-font-size-md":"16px","--limbo-font-size-lg":"18px","--limbo-font-size-xl":"20px","--limbo-z-dropdown":"1000","--limbo-z-sticky":"1020","--limbo-z-fixed":"1030","--limbo-z-modal":"1050","--limbo-z-tooltip":"1070","--limbo-transition-fast":"150ms cubic-bezier(0.4, 0, 0.2, 1)","--limbo-transition-normal":"300ms cubic-bezier(0.4, 0, 0.2, 1)","--limbo-transition-slow":"500ms cubic-bezier(0.4, 0, 0.2, 1)","--limbo-spacing-compact":"0.5rem","--limbo-spacing-compact-sm":"0.25rem","--limbo-spacing-compact-lg":"0.75rem","--limbo-font-size-compact-xs":"11px","--limbo-font-size-compact-sm":"12px","--limbo-font-size-compact-md":"14px","--limbo-font-size-compact-lg":"16px","--limbo-radius-compact":"4px","--limbo-radius-compact-sm":"3px","--limbo-radius-compact-lg":"6px","--limbo-button-height-compact":"32px","--limbo-input-height-compact":"36px","--limbo-modal-padding-compact":"12px","--limbo-card-padding-compact":"12px","--limbo-gap-compact":"8px","--limbo-gap-compact-sm":"4px","--limbo-gap-compact-lg":"12px"}},auto:{name:"auto",displayName:"Automático",variables:{}}},inheritance:{portalSelectors:["body","[data-theme]",".theme-light",".theme-dark",".light-theme",".dark-theme"],variablePrefix:"--",fallbackTheme:"light"},transitions:{duration:"300ms",easing:"cubic-bezier(0.4, 0, 0.2, 1)",properties:["background-color","border-color","color","fill","stroke","box-shadow"]}}}initialize(e={}){this.isInitialized?console.warn("ThemeManager already initialized"):(this.config=this._deepMerge(this.config,e),this._loadCustomThemes(),this.config.theme.inherit&&this._inheritPortalTheme(),this._applyInitialTheme(),this._applyInitialCompactMode(),this._setupObservers(),this._injectBaseStyles(),this.isInitialized=!0)}_injectBaseStyles(){if(document.getElementById("limbo-theme-styles"))return;const e=`\n :root {\n /* Variables de transición para cambios de tema */\n color-scheme: light dark;\n }\n \n [data-limbo-theme] {\n transition: ${this.config.transitions.properties.map(e=>`${e} ${this.config.transitions.duration} ${this.config.transitions.easing}`).join(", ")};\n }\n \n /* Clases de utilidad para temas */\n .limbo-theme-light {\n color-scheme: light;\n }\n \n .limbo-theme-dark {\n color-scheme: dark;\n }\n \n .limbo-theme-auto {\n color-scheme: light dark;\n }\n \n /* Estilos para elementos del componente con variables CSS */\n .limbo-component {\n background-color: var(--limbo-bg-primary);\n color: var(--limbo-text-primary);\n border-color: var(--limbo-border-light);\n border-radius: var(--limbo-radius-md);\n font-family: var(--limbo-font-family);\n font-size: var(--limbo-font-size-md);\n transition: var(--limbo-transition-normal);\n }\n \n .limbo-card {\n background-color: var(--limbo-bg-card);\n border: 1px solid var(--limbo-border-light);\n border-radius: var(--limbo-radius-lg);\n box-shadow: var(--limbo-shadow-md);\n color: var(--limbo-text-primary);\n }\n \n .limbo-input {\n background-color: var(--limbo-bg-input);\n border: 1px solid var(--limbo-border-medium);\n border-radius: var(--limbo-radius-md);\n color: var(--limbo-text-primary);\n font-family: var(--limbo-font-family);\n font-size: var(--limbo-font-size-md);\n transition: var(--limbo-transition-fast);\n }\n \n .limbo-input:focus {\n border-color: var(--limbo-border-focus);\n box-shadow: 0 0 0 3px var(--limbo-primary-light);\n outline: none;\n }\n \n .limbo-button {\n background-color: var(--limbo-primary);\n border: 1px solid var(--limbo-primary);\n border-radius: var(--limbo-radius-md);\n color: var(--limbo-text-inverse);\n font-family: var(--limbo-font-family);\n font-size: var(--limbo-font-size-md);\n transition: var(--limbo-transition-fast);\n cursor: pointer;\n }\n \n .limbo-button:hover {\n background-color: var(--limbo-primary-hover);\n border-color: var(--limbo-primary-hover);\n }\n \n .limbo-button.secondary {\n background-color: var(--limbo-bg-secondary);\n border-color: var(--limbo-border-medium);\n color: var(--limbo-text-primary);\n }\n \n .limbo-button.secondary:hover {\n background-color: var(--limbo-bg-tertiary);\n }\n \n /* Estados de feedback con variables */\n .limbo-state-success {\n background-color: var(--limbo-success-light);\n border-color: var(--limbo-success);\n color: var(--limbo-success);\n }\n \n .limbo-state-error {\n background-color: var(--limbo-error-light);\n border-color: var(--limbo-error);\n color: var(--limbo-error);\n }\n \n .limbo-state-warning {\n background-color: var(--limbo-warning-light);\n border-color: var(--limbo-warning);\n color: var(--limbo-warning);\n }\n \n .limbo-state-info {\n background-color: var(--limbo-info-light);\n border-color: var(--limbo-info);\n color: var(--limbo-info);\n }\n \n /* Overlay y modal con variables */\n .limbo-overlay {\n background-color: var(--limbo-bg-overlay);\n backdrop-filter: blur(4px);\n }\n \n .limbo-modal {\n background-color: var(--limbo-bg-card);\n border-radius: var(--limbo-radius-xl);\n box-shadow: var(--limbo-shadow-xl);\n color: var(--limbo-text-primary);\n }\n \n /* Responsive design con variables */\n @media (max-width: 640px) {\n .limbo-component {\n font-size: var(--limbo-font-size-sm);\n }\n }\n \n /* Modo reducido de movimiento */\n @media (prefers-reduced-motion: reduce) {\n [data-limbo-theme] {\n transition: none;\n }\n \n .limbo-component,\n .limbo-input,\n .limbo-button {\n transition: none;\n }\n }\n \n /* Esquemas de color automático */\n @media (prefers-color-scheme: dark) {\n :root:not([data-limbo-theme]) {\n color-scheme: dark;\n }\n }\n \n @media (prefers-color-scheme: light) {\n :root:not([data-limbo-theme]) {\n color-scheme: light;\n }\n }\n \n /* ===================================\n MODO COMPACTO - ESTILOS ESPECÍFICOS \n =================================== */\n \n /* Activación del modo compacto por atributo o clase */\n [data-limbo-compact="true"],\n .limbo-compact-mode {\n /* Componentes base más pequeños */\n --limbo-font-size-md: var(--limbo-font-size-compact-md);\n --limbo-font-size-sm: var(--limbo-font-size-compact-sm);\n --limbo-font-size-lg: var(--limbo-font-size-compact-lg);\n --limbo-spacing: var(--limbo-spacing-compact);\n --limbo-radius-md: var(--limbo-radius-compact);\n --limbo-gap: var(--limbo-gap-compact);\n }\n \n /* Botones compactos */\n [data-limbo-compact="true"] .limbo-button,\n .limbo-compact-mode .limbo-button {\n height: var(--limbo-button-height-compact);\n padding: var(--limbo-spacing-compact-sm) var(--limbo-spacing-compact);\n font-size: var(--limbo-font-size-compact-sm);\n border-radius: var(--limbo-radius-compact);\n min-width: auto;\n }\n \n /* Inputs compactos */\n [data-limbo-compact="true"] .limbo-input,\n .limbo-compact-mode .limbo-input {\n height: var(--limbo-input-height-compact);\n padding: var(--limbo-spacing-compact-sm) var(--limbo-spacing-compact);\n font-size: var(--limbo-font-size-compact-md);\n border-radius: var(--limbo-radius-compact);\n }\n \n /* Cards compactas */\n [data-limbo-compact="true"] .limbo-card,\n .limbo-compact-mode .limbo-card {\n padding: var(--limbo-card-padding-compact);\n border-radius: var(--limbo-radius-compact-lg);\n }\n \n /* Modales compactos */\n [data-limbo-compact="true"] .limbo-modal,\n .limbo-compact-mode .limbo-modal {\n padding: var(--limbo-modal-padding-compact);\n border-radius: var(--limbo-radius-compact-lg);\n max-width: 90vw;\n max-height: 90vh;\n }\n \n /* Tabs compactas */\n [data-limbo-compact="true"] .limbo-tabs,\n .limbo-compact-mode .limbo-tabs {\n gap: var(--limbo-gap-compact-sm);\n }\n \n [data-limbo-compact="true"] .limbo-tab,\n .limbo-compact-mode .limbo-tab {\n padding: var(--limbo-spacing-compact-sm) var(--limbo-spacing-compact);\n font-size: var(--limbo-font-size-compact-sm);\n border-radius: var(--limbo-radius-compact-sm);\n }\n \n /* Gallery compacta */\n [data-limbo-compact="true"] .limbo-gallery,\n .limbo-compact-mode .limbo-gallery {\n gap: var(--limbo-gap-compact-sm);\n }\n \n [data-limbo-compact="true"] .limbo-gallery-item,\n .limbo-compact-mode .limbo-gallery-item {\n border-radius: var(--limbo-radius-compact);\n min-height: 120px; /* Más pequeño para móviles */\n }\n \n /* Notificaciones compactas */\n [data-limbo-compact="true"] .limbo-notification,\n .limbo-compact-mode .limbo-notification {\n padding: var(--limbo-spacing-compact-sm) var(--limbo-spacing-compact);\n font-size: var(--limbo-font-size-compact-sm);\n border-radius: var(--limbo-radius-compact);\n }\n \n /* Progress indicators compactos */\n [data-limbo-compact="true"] .limbo-progress,\n .limbo-compact-mode .limbo-progress {\n height: 3px; /* Más delgado */\n }\n \n [data-limbo-compact="true"] .limbo-progress-circular,\n .limbo-compact-mode .limbo-progress-circular {\n width: 20px;\n height: 20px;\n }\n \n /* Auto-activación en pantallas pequeñas */\n @media (max-width: 768px) {\n :root[data-limbo-compact="auto"],\n .limbo-component[data-limbo-compact="auto"] {\n /* Aplicar automáticamente estilos compactos */\n --limbo-font-size-md: var(--limbo-font-size-compact-md);\n --limbo-font-size-sm: var(--limbo-font-size-compact-sm);\n --limbo-spacing: var(--limbo-spacing-compact);\n --limbo-radius-md: var(--limbo-radius-compact);\n --limbo-gap: var(--limbo-gap-compact);\n }\n \n /* Modal full-screen en móvil cuando es compacto */\n [data-limbo-compact="auto"] .limbo-modal,\n [data-limbo-compact="true"] .limbo-modal {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n width: 100vw;\n height: 100vh;\n max-width: 100vw;\n max-height: 100vh;\n border-radius: 0;\n margin: 0;\n }\n \n /* Tabs en accordion en móvil */\n [data-limbo-compact="auto"] .limbo-tabs,\n [data-limbo-compact="true"] .limbo-tabs {\n flex-direction: column;\n width: 100%;\n }\n \n /* Gallery de 2 columnas en móvil */\n [data-limbo-compact="auto"] .limbo-gallery,\n [data-limbo-compact="true"] .limbo-gallery {\n grid-template-columns: 1fr 1fr;\n gap: var(--limbo-gap-compact);\n }\n }\n \n /* Touch targets más grandes en móviles */\n @media (max-width: 768px) and (pointer: coarse) {\n [data-limbo-compact="auto"] .limbo-button,\n [data-limbo-compact="true"] .limbo-button {\n min-height: 44px; /* Tamaño mínimo de toque recomendado */\n padding: var(--limbo-spacing-compact) var(--limbo-spacing-compact-lg);\n }\n \n [data-limbo-compact="auto"] .limbo-tab,\n [data-limbo-compact="true"] .limbo-tab {\n min-height: 44px;\n }\n }\n `,t=document.createElement("style");t.id="limbo-theme-styles",t.textContent=e,document.head.appendChild(t)}applyTheme(e,t={}){const n=this._getTheme(e);if(!n)return console.warn(`Theme '${e}' not found`),!1;const l=this.currentTheme;return this._applyThemeVariables(n,t.scope),this._updateThemeAttributes(n.name),this.config.theme.storage&&!t.temporary&&this._saveThemePreference(n.name),this.currentTheme=n.name,this._triggerChangeCallbacks(n.name,l),!0}toggleTheme(e="light",t="dark"){const n=this.currentTheme===e?t:e;return this.applyTheme(n)}applyAutoTheme(){const e=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";return this.applyTheme(e)}registerTheme(e,t){const n={name:e,displayName:t.displayName||e,variables:t.variables||{},extends:t.extends||null,...t};if(n.extends){const e=this._getTheme(n.extends);e&&(n.variables={...e.variables,...n.variables})}return this.customThemes.set(e,n),this}removeTheme(e){if(this.config.presets[e])return console.warn(`Cannot remove predefined theme: ${e}`),!1;const t=this.customThemes.delete(e);return t&&this.currentTheme===e&&this.applyTheme(this.config.inheritance.fallbackTheme),t}getAvailableThemes(){const e=Object.keys(this.config.presets),t=Array.from(this.customThemes.keys());return{presets:e,custom:t,all:[...e,...t]}}getCurrentTheme(){return{name:this.currentTheme,theme:this._getTheme(this.currentTheme),isCustom:this.customThemes.has(this.currentTheme),variables:this._getCurrentVariables()}}enableCompactMode(e={}){const t={element:document.documentElement,persist:!0,...e};return t.element.setAttribute("data-limbo-compact","true"),t.element.classList.add("limbo-compact-mode"),this.isCompactMode=!0,t.persist&&this.config.compact.persistPreference&&this._saveCompactPreference(!0),this._triggerCompactChange(!0),this}disableCompactMode(e={}){const t={element:document.documentElement,persist:!0,...e};return t.element.setAttribute("data-limbo-compact","false"),t.element.classList.remove("limbo-compact-mode"),this.isCompactMode=!1,t.persist&&this.config.compact.persistPreference&&this._saveCompactPreference(!1),this._triggerCompactChange(!1),this}toggleCompactMode(e={}){return this.isCompactMode?this.disableCompactMode(e):this.enableCompactMode(e)}applyAutoCompactMode(){const e=this._shouldUseCompactMode();return e&&!this.isCompactMode?this.enableCompactMode({persist:!1}):!e&&this.isCompactMode&&this.disableCompactMode({persist:!1}),this}getCompactState(){return{isEnabled:this.isCompactMode,isAuto:this.config.compact.auto,breakpoint:this.config.compact.breakpoint,currentViewport:window.innerWidth,shouldBeCompact:this._shouldUseCompactMode()}}_shouldUseCompactMode(){if(!this.config.compact.auto)return this.config.compact.enabled;const e=window.innerWidth<=this.config.compact.breakpoint,t=/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),n="ontouchstart"in window||navigator.maxTouchPoints>0;return!(!this.config.compact.forceOnMobile||!t&&!n)||e}_saveCompactPreference(e){try{localStorage.setItem("limbo-compact-preference",e.toString())}catch(t){console.warn("Could not save compact preference:",t)}}_loadCompactPreference(){try{return"true"===localStorage.getItem("limbo-compact-preference")}catch(e){return console.warn("Could not load compact preference:",e),null}}_triggerCompactChange(e){this.changeCallbacks.forEach(t=>{try{t({type:"compact",isCompact:e,viewport:window.innerWidth,timestamp:Date.now()})}catch(n){console.error("Error in compact mode change callback:",n)}})}_inheritPortalTheme(){const e=this._detectPortalTheme();return e?(this.registerTheme("portal-inherited",e),"portal-inherited"):null}_detectPortalTheme(){const e={name:"portal-detected",displayName:"Tema del Portal",variables:{}};for(const t of this.config.inheritance.portalSelectors){const n=document.querySelector(t);if(n){const t=this._extractCSSVariables(n);Object.keys(t).length>0&&(e.variables={...e.variables,...t});const l=n.getAttribute("data-theme")||n.getAttribute("class")?.match(/theme-(\w+)/)||n.getAttribute("class")?.match(/(\w+)-theme/);l&&(e.detectedName=Array.isArray(l)?l[1]:l)}}return Object.keys(e.variables).length>0?e:null}_extractCSSVariables(e){const t={},n=getComputedStyle(e);["primary","primary-hover","primary-light","primary-dark","bg-primary","bg-secondary","bg-tertiary","bg-card","bg-input","text-primary","text-secondary","text-tertiary","text-inverse","border-light","border-medium","border-strong","border-focus","success","error","warning","info","shadow-sm","shadow-md","shadow-lg","shadow-xl","radius-sm","radius-md","radius-lg","radius-xl"].forEach(e=>{const l=`--limbo-${e}`,r=n.getPropertyValue(l).trim();r&&(t[l]=r)});return["--primary-color","--background-color","--text-color","--border-color","--accent-color","--surface-color"].forEach(e=>{const l=n.getPropertyValue(e).trim();if(l){const n=this._mapGenericToLimbo(e,l);n&&Object.assign(t,n)}}),t}_mapGenericToLimbo(e,t){return{"--primary-color":{"--limbo-primary":t},"--background-color":{"--limbo-bg-primary":t},"--text-color":{"--limbo-text-primary":t},"--border-color":{"--limbo-border-light":t},"--accent-color":{"--limbo-primary":t},"--surface-color":{"--limbo-bg-card":t}}[e]||null}_applyInitialTheme(){let e=this.config.inheritance.fallbackTheme;if(this.config.theme.storage){const t=this._loadThemePreference();t&&this._getTheme(t)&&(e=t)}const t=document.documentElement.getAttribute("data-limbo-theme");t&&this._getTheme(t)&&(e=t);const n=this._inheritPortalTheme();n&&(e=n),this.config.theme.auto&&"auto"===e&&(e=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),this.applyTheme(e,{temporary:!1})}_applyInitialCompactMode(){let e=!1;if(this.config.compact.persistPreference){const t=this._loadCompactPreference();null!==t&&(e=t)}const t=document.documentElement.getAttribute("data-limbo-compact");"true"===t?e=!0:"false"===t&&(e=!1),("auto"===t||this.config.compact.auto)&&(e=this._shouldUseCompactMode()),e?this.enableCompactMode({persist:!1}):this.disableCompactMode({persist:!1})}_applyThemeVariables(e,t=document.documentElement){const n="string"==typeof t?document.querySelector(t):t;n?(Object.entries(e.variables).forEach(([e,t])=>{n.style.setProperty(e,t),this.appliedStyles.add(`${n.tagName}:${e}`)}),this.themeCache.set(e.name,{theme:e,appliedAt:Date.now(),scope:n})):console.warn("Theme scope element not found")}_updateThemeAttributes(e){document.documentElement.setAttribute("data-limbo-theme",e),document.documentElement.classList.remove("limbo-theme-light","limbo-theme-dark","limbo-theme-auto"),document.documentElement.classList.add(`limbo-theme-${e}`),this._updateMetaThemeColor(e)}_updateMetaThemeColor(e){const t=this._getTheme(e);if(!t)return;const n=t.variables["--limbo-primary"]||"#3b82f6";let l=document.querySelector('meta[name="theme-color"]');l||(l=document.createElement("meta"),l.name="theme-color",document.head.appendChild(l)),l.content=n}_getTheme(e){return this.config.presets[e]?this.config.presets[e]:this.customThemes.has(e)?this.customThemes.get(e):null}_getCurrentVariables(){const e=this._getTheme(this.currentTheme);if(!e)return{};const t=getComputedStyle(document.documentElement),n={};return Object.keys(e.variables).forEach(e=>{n[e]=t.getPropertyValue(e).trim()}),n}_saveThemePreference(e){try{localStorage.setItem("limbo-theme-preference",e)}catch(t){console.warn("Could not save theme preference:",t)}}_loadThemePreference(){try{return localStorage.getItem("limbo-theme-preference")}catch(e){return console.warn("Could not load theme preference:",e),null}}_loadCustomThemes(){try{const e=localStorage.getItem("limbo-custom-themes");if(e){const t=JSON.parse(e);Object.entries(t).forEach(([e,t])=>{this.customThemes.set(e,t)})}}catch(e){console.warn("Could not load custom themes:",e)}}_saveCustomThemes(){try{const e=Object.fromEntries(this.customThemes);localStorage.setItem("limbo-custom-themes",JSON.stringify(e))}catch(e){console.warn("Could not save custom themes:",e)}}_setupObservers(){this.config.theme.detectSystem&&this._setupSystemObserver(),this.config.theme.storage&&this._setupStorageObserver(),this._setupMutationObserver(),this.config.compact.auto&&this._setupViewportObserver()}_setupSystemObserver(){const e=window.matchMedia("(prefers-color-scheme: dark)");e.addEventListener("change",e=>{if("auto"===this.currentTheme||this.config.theme.auto){const t=e.matches?"dark":"light";this.applyTheme(t,{temporary:!0})}}),this.mediaQueryObserver=e}_setupStorageObserver(){const e=e=>{"limbo-theme-preference"===e.key&&e.newValue!==this.currentTheme&&this._getTheme(e.newValue)&&this.applyTheme(e.newValue)};window.addEventListener("storage",e),this.storageListener=e}_setupMutationObserver(){const e=new MutationObserver(e=>{e.forEach(e=>{if("attributes"===e.type&&"data-limbo-theme"===e.attributeName){const t=e.target.getAttribute("data-limbo-theme");t&&t!==this.currentTheme&&this._getTheme(t)&&this.applyTheme(t)}})});e.observe(document.documentElement,{attributes:!0,attributeFilter:["data-limbo-theme"]}),this.mutationObserver=e}_setupViewportObserver(){const e=`(max-width: ${this.config.compact.breakpoint}px)`,t=window.matchMedia(e);t.addEventListener("change",()=>{("auto"===document.documentElement.getAttribute("data-limbo-compact")||this.config.compact.auto)&&this.applyAutoCompactMode()}),this.compactObserver=t,window.addEventListener("orientationchange",()=>{setTimeout(()=>{("auto"===document.documentElement.getAttribute("data-limbo-compact")||this.config.compact.auto)&&this.applyAutoCompactMode()},100)})}onThemeChange(e){return this.changeCallbacks.add(e),()=>this.changeCallbacks.delete(e)}_triggerChangeCallbacks(e,t){this.changeCallbacks.forEach(n=>{try{n({theme:e,previousTheme:t,themeData:this._getTheme(e),variables:this._getCurrentVariables()})}catch(l){console.error("Error in theme change callback:",l)}})}generateThemeFromColors(e,t){const n={name:e,displayName:e,variables:{}};t.primary&&(n.variables["--limbo-primary"]=t.primary,n.variables["--limbo-primary-hover"]=this._darkenColor(t.primary,10),n.variables["--limbo-primary-light"]=this._lightenColor(t.primary,40),n.variables["--limbo-primary-dark"]=this._darkenColor(t.primary,20)),t.background&&(n.variables["--limbo-bg-primary"]=t.background,n.variables["--limbo-bg-secondary"]=this._lightenColor(t.background,5),n.variables["--limbo-bg-tertiary"]=this._lightenColor(t.background,10),n.variables["--limbo-bg-card"]=t.background),t.text&&(n.variables["--limbo-text-primary"]=t.text,n.variables["--limbo-text-secondary"]=this._lightenColor(t.text,20),n.variables["--limbo-text-tertiary"]=this._lightenColor(t.text,40));const l=this._getTheme(this.config.inheritance.fallbackTheme);return l&&(n.variables={...l.variables,...n.variables}),this.registerTheme(e,n),n}_darkenColor(e,t){const n=parseInt(e.replace("#",""),16),l=Math.round(2.55*t),r=(n>>16)-l,a=(n>>8&255)-l,i=(255&n)-l;return"#"+(16777216+65536*(r<255?r<1?0:r:255)+256*(a<255?a<1?0:a:255)+(i<255?i<1?0:i:255)).toString(16).slice(1)}_lightenColor(e,t){const n=parseInt(e.replace("#",""),16),l=Math.round(2.55*t),r=(n>>16)+l,a=(n>>8&255)+l,i=(255&n)+l;return"#"+(16777216+65536*(r<255?r<1?0:r:255)+256*(a<255?a<1?0:a:255)+(i<255?i<1?0:i:255)).toString(16).slice(1)}_deepMerge(e,t){const n={...e};return Object.keys(t).forEach(l=>{t[l]&&"object"==typeof t[l]&&!Array.isArray(t[l])?n[l]=this._deepMerge(e[l]||{},t[l]):n[l]=t[l]}),n}getThemeInfo(){return{current:this.getCurrentTheme(),available:this.getAvailableThemes(),compact:this.getCompactState(),config:this.config,isInitialized:this.isInitialized,cache:{themes:this.themeCache.size,applied:this.appliedStyles.size},observers:{system:!!this.mediaQueryObserver,storage:!!this.storageListener,mutation:!!this.mutationObserver,viewport:!!this.compactObserver}}}debug(){return console.table(this.getThemeInfo()),this.getThemeInfo()}destroy(){this.mediaQueryObserver&&this.mediaQueryObserver.removeEventListener("change",this._setupSystemObserver),this.storageListener&&window.removeEventListener("storage",this.storageListener),this.mutationObserver&&this.mutationObserver.disconnect(),this.compactObserver&&this.compactObserver.removeEventListener("change",this._setupViewportObserver),this.changeCallbacks.clear(),this.themeCache.clear(),this.appliedStyles.clear(),this._saveCustomThemes();const e=document.getElementById("limbo-theme-styles");e&&e.remove(),this.isInitialized=!1}}const Jn={DEV:"https://led-dev-limbo-dev.eu.els.local",PROD:"https://limbo.lefebvre.es"};function Zn(e,t=!1){if(!e)return"";if(e.startsWith("/files/")){return(t?Jn.PROD:Jn.DEV)+e}return e}function el(e){return"string"!=typeof e?e:e.replace(/&quot;/g,'"').replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&#39;/g,"'").replace(/&#x27;/g,"'")}function tl(e){return!(!e||"string"!=typeof e)&&!e.startsWith("blob:")}function nl(e,t={}){if(!e)return"";const{prefer:n="crop",isProd:l=!1}=t,r=el(e);try{const e=JSON.parse(r),t=()=>{if(e.images&&Array.isArray(e.images))for(const t of e.images)if(t&&tl(t.url))return t.url;return null},a=e.original?.url,i=t();if("crop"===n){if(i)return Zn(i,l);if(tl(a))return Zn(a,l)}else{if(tl(a))return Zn(a,l);if(i)return Zn(i,l)}return tl(e.url)?Zn(e.url,l):""}catch{if("string"==typeof r){if(r.startsWith("blob:"))return"";if(r.startsWith("/files/"))return Zn(r,l);if(r.startsWith("http")||r.startsWith("/"))return r}}return"string"==typeof e&&(e.startsWith("{")||e.startsWith("["))?"":e}function ll(e,t={}){const{isProd:n=!1}=t;if(!e)return{original:null,images:[],url:""};try{const t=JSON.parse(el(e)),l=t.original?{...t.original,url:Zn(t.original.url,n)}:null,r=(t.images||[]).map(e=>({...e,url:Zn(e.url,n)}));return{original:l,images:r,url:r[0]?.url||l?.url||Zn(t.url,n)||""}}catch{return{original:null,images:[],url:Zn(e,n)}}}function rl(e,t={}){const{isProd:n=!1}=t;if(!e?.fields)return e;const l=e.fields.map(e=>{if("image"===e.type&&"string"==typeof e.example_value){const t=nl(e.example_value,{isProd:n});return{...e,example_value:t||e.example_value}}return e});return{...e,fields:l}}const al=new class{constructor(){this.config=new m,this.instances=new Hn,this.autoInputs=new Kn,this.events=new Gn,this.modals=new Qn,this.theme=new Yn,this.containerQueryDetector=S,this._setupInternalListeners(),this._initializeContainerQueries()}configure(e){var t;return this.config.setGlobal(e),t={publicKey:e.publicKey,apiKey:e.apiKey,token:e.token,authMode:e.authMode||"manual",tokenProvider:e.tokenProvider,prod:Boolean(e.prod)||!1,mode:e.mode||"embed",callbacks:e.callbacks||null},O={...O,...t},O.authMode||(O.token?O.authMode="manual":O.authMode="session"),this.config}setToken(e){return function(e){O.token=e}(e),this.config.setGlobal({token:e}),this}create(e){const t=this.config.merge(e);return this.instances.create(t,this.events,this.modals)}configureAutoInputs(e){return this.autoInputs.configure(e,this.config,this.events)}setTheme(e){return e&&(this.config.set("theme",e),this.theme.setTheme(e),this.events.emit("theme:changed",{theme:e})),this}getTheme(){return this.theme.getCurrentTheme()}scanAndActivate(e=null){const t=this.autoInputs.config?.dataset||"data-limbo-input-file",n=e||`[${t}]`,l=document.querySelectorAll(n);if(0===l.length)return{found:0,processed:0,skipped:0};let r=0,a=0;return l.forEach(e=>{try{this.autoInputs._processInput(e),r++}catch(t){console.warn(`⚠️ Limbo: Error procesando input ${e.id||e.name}:`,t),a++}}),this.events.emit("limbo:scanCompleted",{found:l.length,processed:r,skipped:a,inputs:Array.from(l)}),{found:l.length,processed:r,skipped:a}}_initializeContainerQueries(){this.containerQueryDetector.observeResize(),setTimeout(()=>{document.querySelectorAll(".limbo-component-container-wrapper").forEach(e=>{this.containerQueryDetector.applyResponsiveClasses(e)})},100)}rescan(e=document){const t=this.autoInputs.config?.dataset||"data-limbo-input-file",n=e.querySelectorAll(`[${t}]`);let l=0;return n.forEach(e=>{if(!this.autoInputs.instances.has(this.autoInputs._getInputId(e)))try{this.autoInputs._processInput(e),l++}catch(t){console.warn("⚠️ Limbo: Error procesando nuevo input:",t)}}),l}init(e){const t=this._mapLegacyOptions(e);return this.create(t)}getInstances(){return this.instances.getAll()}destroy(){this.instances.destroyAll(),this.autoInputs.cleanup(),this.events.cleanup(),this.theme.removeTheme()}_mapLegacyOptions(e){return{container:e.container||"#image-manager",mode:"embed",features:["gallery","upload","cropper"],apiKey:e.apiKey,prod:e.prod||!1,url:void 0===e.url||e.url}}_setupInternalListeners(){this.events.on("autoInputs:modalRequest",({config:e,callback:t,input:n})=>{this._handleAutoInputModalRequest({config:e,callback:t,input:n})})}_handleAutoInputModalRequest({config:e,callback:t,input:n}){const l=n,r=async n=>{let r={};if(n.crops&&n.crops.length>0){const e=n.asset||n.original;r.original={url:e?.url||e?.urlSigned||n.originalUrl,width:e?.width||n.originalWidth,height:e?.height||n.originalHeight,assetId:e?.id||n.assetId},r.images=n.crops.map(e=>({url:e.url||e.urlSigned,width:e.width,height:e.height,name:e.name||e.filename}))}else n.asset?r.original={url:n.asset.url||n.asset.urlSigned,width:n.asset.width,height:n.asset.height,assetId:n.asset.id}:n.master?.urlSigned||n.master?.url?r.original={url:n.master.urlSigned||n.master.url,width:n.master.width||n.width,height:n.master.height||n.height,assetId:n.assetId}:n.url||n.urlSigned?r.original={url:n.url||n.urlSigned,width:n.width,height:n.height,assetId:n.assetId||n.id}:(console.warn("[Limbo] handleResult: formato de datos no reconocido",n),r=n);if(l){var a=e?.returnConfig?.format||"json",o="";o="url"===a?r.images?.[0]?.url||r.original?.url||"":"assetId"===a?r.original?.assetId||"":JSON.stringify(r),l.value=o,l.dispatchEvent(new Event("change",{bubbles:!0})),console.log("[Limbo] ✅ Valor asignado al input:",l.value?.substring(0,80))}try{await t(r)}catch(s){}i.close()},a={...e,mode:"modal",autoDestroy:!0,interaction:{allowSelection:!0,allowCropping:!0,...e.interaction},callbacks:{onSelect:e=>{r(e)},onCropsSaved:e=>{r(e)},onCropperComplete:e=>{r(e)},onUpload:t=>{"upload-only"!==e.modeUI||e.features?.includes("cropper")||r(t)},onClose:()=>{}}};if(e.initialImageUrl){const t=this._extractAssetIdFromUrl(e.initialImageUrl)||e.existingData?.original?.assetId||null;t&&(a._externalImage={url:e.initialImageUrl,filename:e.initialImageUrl.split("/").pop()?.split("?")[0]||"image.jpg",width:1920,height:1080,mime_type:"image/jpeg",id:t})}e.cropper&&(a.cropper=e.cropper),this.config.setGlobal({interaction:{allowSelection:!0,allowCropping:!0,...e.interaction}});const i=this.create(a);i.open()}_extractAssetIdFromUrl(e){if(!e)return null;try{const t=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,n=e.match(t);return n&&n.length>=2?n[1]:n&&1===n.length?n[0]:null}catch(t){return console.warn("Error extracting asset ID from URL:",t),null}}openGallery(e={}){const t=this.create({mode:"modal",modeUI:"gallery-only",features:["gallery"],autoDestroy:!0,modal:{title:e.title||"Seleccionar Imagen",size:e.size||"large"},callbacks:{onSelect:n=>{e.onSelect?.(n),!1!==e.autoClose&&t.close()}},...e});return t.open(),t}openUploader(e={}){const t=!1!==e.redirectToGallery?["upload","gallery"]:["upload"],n=this.create({mode:"modal",modeUI:!1!==e.redirectToGallery?"full":"upload-only",features:t,autoDestroy:!0,modal:{title:e.title||"Subir Imagen",size:e.size||"medium"},callbacks:{onUpload:t=>{e.onUpload?.(t),!1===e.autoClose||e.redirectToGallery||n.close()}},...e});return n.open(),n}openCropper(e,t={}){if(!e)throw new Error("Limbo.openCropper: imageUrl es requerido");const n={url:e,filename:t.filename||"image.jpg",width:t.width||1920,height:t.height||1080,mime_type:t.mimeType||"image/jpeg",id:t.assetId||`external-${Date.now()}`},l=this.create({mode:"modal",modeUI:"crop-only",features:["cropper"],autoDestroy:!0,modal:{title:t.title||"Recortar Imagen",size:"xlarge"},cropper:{mandatoryCrops:t.mandatoryCrops||[],allowCustomCrops:!1!==t.allowCustomCrops,enforceRequiredCrops:!1!==t.enforceRequiredCrops},callbacks:{onCropperComplete:e=>{t.onComplete?.(e),!1!==t.autoClose&&l.close()},onCropperCancelled:e=>{t.onCancelled?.(e),!1!==t.autoClose&&l.close()},onCropperError:e=>{t.onError?.(e)}},_externalImage:n,...t});return l.open(),l}createInlineGallery(e,t={}){return this.create({container:e,mode:"embed",modeUI:"gallery-only",features:["gallery"],callbacks:{onSelect:t.onSelect,onDelete:t.onDelete},...t})}createInlineUploader(e,t={}){return this.create({container:e,mode:"embed",modeUI:"upload-only",features:["upload"],callbacks:{onUpload:t.onUpload},...t})}createStandaloneCropper(e,t,n={}){if(!e)throw new Error("Limbo.createStandaloneCropper: container es requerido");if(!t)throw new Error("Limbo.createStandaloneCropper: imageUrl es requerido");const l={url:t,filename:n.filename||"image.jpg",width:n.width||1920,height:n.height||1080,mime_type:n.mimeType||"image/jpeg",id:n.assetId||`external-${Date.now()}`};return this.create({container:e,mode:"embed",modeUI:"crop-only",features:["cropper"],autoHideOnComplete:!1!==n.autoHideOnComplete,cropper:{mandatoryCrops:n.mandatoryCrops||[],allowCustomCrops:!1!==n.allowCustomCrops,enforceRequiredCrops:!1!==n.enforceRequiredCrops},callbacks:{onCropperComplete:n.onComplete,onCropperCancelled:n.onCancelled,onCropperError:n.onError},_externalImage:l,...n})}createFullSelector(e,t={}){return this.create({container:e,mode:t.mode||"embed",modeUI:"full",features:["gallery","upload","cropper"],callbacks:{onSelect:t.onSelect,onUpload:t.onUpload,onDelete:t.onDelete,onCropsSaved:t.onCropsSaved},...t})}};"undefined"!=typeof window&&(window.Limbo=al,window.limboCore=al);"undefined"!=typeof window&&document.querySelector("#root")&&(al.configure({prod:!1,publicKey:"pk_e464fd744106b7a8d63d453c4bd02582",authMode:"session"}),al.create({container:"#root",mode:"embed",modeUI:"full",features:["gallery","upload","cropper"],title:"Limbo Image Manager - Development",url:!0}),al.configureAutoInputs({dataset:"data-limbo-input-file",return:"json",features:["gallery","upload","cropper"],modeUI:"full",modalSize:"large",title:"Seleccionar archivo",crops:"free",allowDelete:!1}));export{Jn as LIMBO_BASE_URL,el as decodeHtmlEntities,al as default,nl as extractImageUrl,tl as isValidImageUrl,ll as parseImageData,rl as prepareImageFieldsForPreview,Zn as resolveUrl};
667
665
  //# sourceMappingURL=limbo.es.map