limbo-component 3.7.4 → 3.7.6
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.cjs.js +1 -1
- package/dist/limbo.cjs.map +1 -1
- package/dist/limbo.es.js +134 -133
- package/dist/limbo.es.map +1 -1
- package/dist/limbo.min.js +1 -1
- package/dist/limbo.min.js.map +1 -1
- package/dist/limbo.umd.js +1 -1
- package/dist/limbo.umd.js.map +1 -1
- package/dist/types/components/CropperView.d.ts.map +1 -1
- package/dist/types/components/ImageCard.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/limbo.es.js
CHANGED
|
@@ -111,7 +111,7 @@ return c("article",{role:"listitem","aria-label":`${i} - ${h}×${p} píxeles`,cl
|
|
|
111
111
|
/* @__PURE__ */s("h3",{className:"lb:text-sm lb:font-semibold lb:text-gray-900 lb:truncate lb:mb-2",title:i,children:i}),
|
|
112
112
|
/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:justify-between",children:[
|
|
113
113
|
/* @__PURE__ */c("span",{className:"lb:text-xs lb:text-gray-500 lb:font-medium",children:[h,"×",p," ·"," ",Math.round(f/1024),"KB"]}),
|
|
114
|
-
/* @__PURE__ */c("div",{className:"lb:flex lb:gap-2",role:"group","aria-label":`Acciones para ${i}`,children:[n&&D&&/* @__PURE__ */s("button",{type:"button",className:"lb:w-8 lb:h-8 lb:rounded-lg lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:cursor-pointer lb:text-white lb:flex lb:items-center lb:justify-center lb:focus:outline-none lb:focus:ring-2 lb:focus:ring-brand-blue-400 lb:focus:ring-offset-1 lb:transition-colors lb:shadow-sm",onClick:e=>{e.stopPropagation(),m&&(x?.announce(`Abriendo herramienta de recorte para ${a.filename}`),m(a),o?.())},"aria-label":"Crear nuevo recorte",title:"Recortar",children:/* @__PURE__ */s("span",{className:"icon icon-scissors-white icon--sm"})}),R&&/* @__PURE__ */s("button",{type:"button",className:"lb:w-8 lb:h-8 lb:rounded-lg lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:cursor-pointer lb:text-white lb:flex lb:items-center lb:justify-center lb:focus:outline-none lb:focus:ring-2 lb:focus:ring-brand-blue-400 lb:focus:ring-offset-1 lb:transition-colors lb:shadow-sm",onClick:t=>{t.stopPropagation();(async(e,t,n)=>{try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t);else{const e=document.createElement("textarea");e.value=t,e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.focus(),e.select(),document.execCommand("copy"),document.body.removeChild(e)}T(e),x?.announce(`URL de ${n} copiada al portapapeles`),setTimeout(()=>T(null),2e3)}catch(l){console.error("Error al copiar URL:",l),x?.announceError(`Error al copiar URL de ${n}. Inténtalo de nuevo.`)}})(n?"original":e.id,n?a.url||a.path:e.url,i)},"aria-label":_===(n?"original":e.id)?"¡Copiado!":`Copiar URL de ${i}`,title:_===(n?"original":e.id)?"¡Copiado!":"Copiar URL",children:/* @__PURE__ */s("span",{className:`icon ${_===(n?"original":e.id)?"icon-copied-white":"icon-copy-white"} icon--sm`})}),O&&/* @__PURE__ */s("button",{type:"button",className:"lb:w-8 lb:h-8 lb:rounded-lg lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:cursor-pointer lb:text-white lb:flex lb:items-center lb:justify-center lb:focus:outline-none lb:focus:ring-2 lb:focus:ring-brand-blue-400 lb:focus:ring-offset-1 lb:transition-colors lb:shadow-sm",onClick:t=>{t.stopPropagation(),n?(async()=>{const{downloadImage:e}=await Promise.resolve().then(()=>
|
|
114
|
+
/* @__PURE__ */c("div",{className:"lb:flex lb:gap-2",role:"group","aria-label":`Acciones para ${i}`,children:[n&&D&&/* @__PURE__ */s("button",{type:"button",className:"lb:w-8 lb:h-8 lb:rounded-lg lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:cursor-pointer lb:text-white lb:flex lb:items-center lb:justify-center lb:focus:outline-none lb:focus:ring-2 lb:focus:ring-brand-blue-400 lb:focus:ring-offset-1 lb:transition-colors lb:shadow-sm",onClick:e=>{e.stopPropagation(),m&&(x?.announce(`Abriendo herramienta de recorte para ${a.filename}`),m(a),o?.())},"aria-label":"Crear nuevo recorte",title:"Recortar",children:/* @__PURE__ */s("span",{className:"icon icon-scissors-white icon--sm"})}),R&&/* @__PURE__ */s("button",{type:"button",className:"lb:w-8 lb:h-8 lb:rounded-lg lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:cursor-pointer lb:text-white lb:flex lb:items-center lb:justify-center lb:focus:outline-none lb:focus:ring-2 lb:focus:ring-brand-blue-400 lb:focus:ring-offset-1 lb:transition-colors lb:shadow-sm",onClick:t=>{t.stopPropagation();(async(e,t,n)=>{try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t);else{const e=document.createElement("textarea");e.value=t,e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.focus(),e.select(),document.execCommand("copy"),document.body.removeChild(e)}T(e),x?.announce(`URL de ${n} copiada al portapapeles`),setTimeout(()=>T(null),2e3)}catch(l){console.error("Error al copiar URL:",l),x?.announceError(`Error al copiar URL de ${n}. Inténtalo de nuevo.`)}})(n?"original":e.id,n?a.url||a.path:e.url,i)},"aria-label":_===(n?"original":e.id)?"¡Copiado!":`Copiar URL de ${i}`,title:_===(n?"original":e.id)?"¡Copiado!":"Copiar URL",children:/* @__PURE__ */s("span",{className:`icon ${_===(n?"original":e.id)?"icon-copied-white":"icon-copy-white"} icon--sm`})}),O&&/* @__PURE__ */s("button",{type:"button",className:"lb:w-8 lb:h-8 lb:rounded-lg lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:cursor-pointer lb:text-white lb:flex lb:items-center lb:justify-center lb:focus:outline-none lb:focus:ring-2 lb:focus:ring-brand-blue-400 lb:focus:ring-offset-1 lb:transition-colors lb:shadow-sm",onClick:t=>{t.stopPropagation(),n?(async()=>{const{downloadImage:e}=await Promise.resolve().then(()=>rl);await e(a.url||a.path,a.filename||"limbo-image",{originalFormat:a.format,accessibilityManager:x})})():(async e=>{const{downloadImage:t}=await Promise.resolve().then(()=>rl);await t(e.url,e.name||"limbo-variant",{originalFormat:e.format||e.output_format,accessibilityManager:x})})(e)},"aria-label":`Descargar ${i}`,title:"Descargar",children:/* @__PURE__ */s("span",{className:"icon icon-download-white icon--sm"})}),j&&(!n||b)&&/* @__PURE__ */s("button",{type:"button",className:"lb:w-8 lb:h-8 lb:rounded-lg lb:bg-red-1000 lb:hover:bg-red-800 lb:cursor-pointer lb:text-white lb:flex lb:items-center lb:justify-center lb:focus:outline-none lb:focus:ring-2 lb:focus:ring-red-800 lb:focus:ring-offset-1 lb:transition-colors lb:shadow-sm",onClick:t=>{t.stopPropagation(),n?(async()=>{if(!b)return;window.confirm(`¿Estás seguro de que deseas eliminar "${a.filename}"? Esta acción también eliminará todos sus recortes.`)&&(x?.announce(`Eliminando imagen ${a.filename}`),await b(a.id),o?.())})():de(e)},"aria-label":`Eliminar ${i}`,title:"Eliminar",children:/* @__PURE__ */s("span",{className:"icon icon-close-small-white icon--sm"})}),I&&/* @__PURE__ */s("button",{type:"button",className:"lb:w-8 lb:h-8 lb:cursor-pointer lb:rounded-lg lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:text-white lb:flex lb:items-center lb:justify-center lb:focus:outline-none lb:focus:ring-2 lb:focus:ring-brand-blue-400 lb:focus:ring-offset-1 lb:transition-colors lb:shadow-sm",onClick:t=>{t.stopPropagation(),n?ue():ce(e)},"aria-label":`Ampliar ${i}`,title:"Ampliar",children:/* @__PURE__ */s("svg",{className:"lb:w-4 lb:h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM10 7v3m0 0v3m0-3h3m-3 0H7"})})})]})]})]})]},n?"original":e.id)})})})]}),
|
|
115
115
|
/* @__PURE__ */s(Te,{isOpen:!!E,src:E?.src||"",alt:E?.title||"Imagen",title:E?.title,subtitle:E?.subtitle,onClose:()=>$(null)})]})}const Le="/api";let Ae={data:null,timestamp:0,pending:null};const Me=/* @__PURE__ */new Set;function Pe(){Ae.data=null,Ae.timestamp=0,Ae.pending=null,Me.forEach(e=>e())}async function Ie(e={}){return Ae.data&&Date.now()-Ae.timestamp<3e5?Ae.data:(Ae.pending||(Ae.pending=async function(e={}){try{const t={include_counts:"true",...e},n=`/folders?${new URLSearchParams(t).toString()}`;return function(e){if(!e?.success||!e?.data)return{folders:[],total:0};const t=(e.data.folders||[]).map(e=>({id:e.id,name:e.name,slug:e.slug,description:e.description,visibility:e.visibility||"public",sort_order:e.sort_order||0,assets_count:e.assets_count||0,created_at:e.created_at,updated_at:e.updated_at}));return{folders:t,total:e.data.total||t.length}}(await le({endpoint:n,method:"GET",basePath:Le,useJWT:!0}))}catch(t){throw ue(t)}}(e).then(e=>(Ae.data=e,Ae.timestamp=Date.now(),Ae.pending=null,e)).catch(e=>{throw Ae.pending=null,e})),Ae.pending)}function De(e={}){const{autoFetch:a=!0,visibility:i=null,allowedSlugs:o=null,excludeSlugs:s=null}=e,[c,u]=t([]),[d,b]=t(!1),[m,h]=t(null),[p,f]=t(!1),g=r(null),v=l(e=>{let t=[...e];return o&&o.length>0&&(t=t.filter(e=>o.includes(e.slug))),s&&s.length>0&&(t=t.filter(e=>!s.includes(e.slug))),t.sort((e,t)=>e.sort_order!==t.sort_order?e.sort_order-t.sort_order:e.name.localeCompare(t.name)),t},[o,s]),y=l(async(e={})=>{b(!0),h(null);try{const t={...i&&{visibility:i},...e},n=await Ie(t),l=v(n.folders||[]);return u(l),l}catch(t){return h(t.message),[]}finally{b(!1)}},[i,v]),w=l(()=>(Pe(),y()),[y]),x=l(async e=>{f(!0),h(null);try{const t=await async function(e){try{return function(e){if(!e?.success||!e?.data)return{folder:null};const t=e.data;return{folder:{id:t.id,name:t.name,slug:t.slug,description:t.description,visibility:t.visibility||"public",sort_order:t.sort_order||0,assets_count:t.assets_count||0,created_at:t.created_at,updated_at:t.updated_at}}}(await le({endpoint:"/folders",method:"POST",body:{name:e.name,...e.slug&&{slug:e.slug},...e.description&&{description:e.description},...e.visibility&&{visibility:e.visibility}},basePath:Le,useJWT:!0}))}catch(m){throw ue(m)}}(e),n=t.folder;return n&&(Pe(),u(e=>{const t=[...e,n];return t.sort((e,t)=>e.sort_order!==t.sort_order?e.sort_order-t.sort_order:e.name.localeCompare(t.name)),t})),n}catch(t){return h(t.message),null}finally{f(!1)}},[]),k=l(e=>c.find(t=>t.slug===e)||null,[c]),C=l(e=>c.find(t=>t.id===e)||null,[c]);return g.current=y,n(()=>{const e=()=>g.current?.();return Me.add(e),()=>Me.delete(e)},[]),n(()=>{a&&y()},[a,y]),{folders:c,loading:d,error:m,creating:p,fetchFolders:y,create:x,refresh:w,findBySlug:k,findById:C,hasLoaded:!d&&c.length>=0}}function Oe({value:e=null,onChange:n,allowCreate:l=!0,placeholder:r="Sin carpeta",label:i=null,disabled:o=!1,className:d="",showAssetCount:b=!1,includeNoFolder:m=!0,allowedSlugs:h=null,excludeSlugs:p=null,mode:f="upload"}){const g=a(),[v,y]=t(!1),[w,x]=t(""),[k,C]=t(null),{folders:N,loading:S,error:E,creating:$,create:_,refresh:T}=De({autoFetch:!0,allowedSlugs:h,excludeSlugs:p}),z=async e=>{if(e.preventDefault(),C(null),!w.trim())return void C("El nombre es requerido");const t=await _({name:w.trim()});t?(n?.(t),y(!1),x("")):C("Error al crear la carpeta")},L=()=>{y(!1),x(""),C(null)};if(v)/* @__PURE__ */
|
|
116
116
|
return c("div",{className:`limbo-folder-selector limbo-folder-selector--creating ${d}`,children:[i&&/* @__PURE__ */c("label",{className:"limbo-filter-label lb:block lb:mb-1",children:[i," ",$&&/* @__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"})})]}),
|
|
117
117
|
/* @__PURE__ */c("form",{onSubmit:z,className:"lb:flex lb:gap-2 lb:items-center lb:flex-col",children:[
|
|
@@ -124,38 +124,39 @@ return c("div",{className:`limbo-folder-selector ${d}`,children:[i&&/* @__PURE__
|
|
|
124
124
|
/* @__PURE__ */s("option",{disabled:!0,children:"──────────────"}),
|
|
125
125
|
/* @__PURE__ */s("option",{value:"__create__",children:"+ Crear nueva carpeta..."})]})]})}),E&&/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-2 lb:mt-1",children:[
|
|
126
126
|
/* @__PURE__ */s("p",{className:"lb:text-red-600 lb:text-xs",children:E}),
|
|
127
|
-
/* @__PURE__ */s("button",{type:"button",onClick:T,className:"lb:text-xs lb:text-brand-blue-1000 lb:underline lb:cursor-pointer",children:"Reintentar"})]})]})}const Re={pdf:{symbol:"icon-doc-pdf",color:"#dc2626"},doc:{symbol:"icon-doc-word",color:"#2563eb"},docx:{symbol:"icon-doc-word",color:"#2563eb"},xls:{symbol:"icon-doc-xls",color:"#16a34a"},xlsx:{symbol:"icon-doc-xls",color:"#16a34a"},ppt:{symbol:"icon-doc-ppt",color:"#ea580c"},pptx:{symbol:"icon-doc-ppt",color:"#ea580c"},txt:{symbol:"icon-doc-text",color:"#6b7280"},csv:{symbol:"icon-doc-report",color:"#16a34a"},mp4:{symbol:"icon-video",color:"#7c3aed"},webm:{symbol:"icon-video",color:"#7c3aed"},mov:{symbol:"icon-video",color:"#7c3aed"},avi:{symbol:"icon-video",color:"#7c3aed"},mkv:{symbol:"icon-video",color:"#7c3aed"},gif:{symbol:"icon-video",color:"#7a3f2d"},mp3:{symbol:"icon-support-person",color:"#0891b2"},mpeg:{symbol:"icon-support-person",color:"#0891b2"},wav:{symbol:"icon-support-person",color:"#0891b2"},ogg:{symbol:"icon-support-person",color:"#0891b2"},aac:{symbol:"icon-support-person",color:"#0891b2"},flac:{symbol:"icon-support-person",color:"#0891b2"},default:{symbol:"icon-clip",color:"#6b7280"}},je=/* @__PURE__ */new Set(["text/plain","text/csv","text/html","text/xml","text/css","text/javascript","text/markdown","application/json","application/xml","application/javascript"]);const
|
|
127
|
+
/* @__PURE__ */s("button",{type:"button",onClick:T,className:"lb:text-xs lb:text-brand-blue-1000 lb:underline lb:cursor-pointer",children:"Reintentar"})]})]})}const Re={pdf:{symbol:"icon-doc-pdf",color:"#dc2626"},doc:{symbol:"icon-doc-word",color:"#2563eb"},docx:{symbol:"icon-doc-word",color:"#2563eb"},xls:{symbol:"icon-doc-xls",color:"#16a34a"},xlsx:{symbol:"icon-doc-xls",color:"#16a34a"},ppt:{symbol:"icon-doc-ppt",color:"#ea580c"},pptx:{symbol:"icon-doc-ppt",color:"#ea580c"},txt:{symbol:"icon-doc-text",color:"#6b7280"},csv:{symbol:"icon-doc-report",color:"#16a34a"},mp4:{symbol:"icon-video",color:"#7c3aed"},webm:{symbol:"icon-video",color:"#7c3aed"},mov:{symbol:"icon-video",color:"#7c3aed"},avi:{symbol:"icon-video",color:"#7c3aed"},mkv:{symbol:"icon-video",color:"#7c3aed"},gif:{symbol:"icon-video",color:"#7a3f2d"},mp3:{symbol:"icon-support-person",color:"#0891b2"},mpeg:{symbol:"icon-support-person",color:"#0891b2"},wav:{symbol:"icon-support-person",color:"#0891b2"},ogg:{symbol:"icon-support-person",color:"#0891b2"},aac:{symbol:"icon-support-person",color:"#0891b2"},flac:{symbol:"icon-support-person",color:"#0891b2"},default:{symbol:"icon-clip",color:"#6b7280"}},je=(e,t)=>0===t?e:je(t,e%t),Fe=/* @__PURE__ */new Set(["text/plain","text/csv","text/html","text/xml","text/css","text/javascript","text/markdown","application/json","application/xml","application/javascript"]);const Ue=e.memo(function({image:a,onDelete:o,onCrop:d,onSelect:b,onFolderChange:m,thumbnailSize:h=32,isDeleting:p=!1,showFolderInfo:f=!0,allowMoveFolder:g=!0,allowedFolderSlugs:v=null,excludedFolderSlugs:y=null,allowCreateFolder:w=!1,allowedActions:x={select:!0,download:!0,copy:!0,delete:!0,crop:!0,variants:!0,rename:!0},onRename:k=null}){const[C,N]=t(!1),[S,E]=t(!1),[$,_]=t(!1),[T,z]=t(a.variants_count||0),[L,A]=t(!1),[P,I]=t(!1),[D,O]=t(!1),[R,j]=t(""),[F,U]=t(null),[W,q]=t(!1),V=r(null);n(()=>{if(!L)return;const e=e=>{e.target.closest(".limbo-image-card-wrapper")||A(!1)};return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[L]);const H=i(()=>(e=>{if(e.asset_type)return e.asset_type;const t=e.mime_type||e.original_mime||"";return"image/gif"===t?"video":t.startsWith("image/")?"image":t.startsWith("video/")?"video":t.startsWith("audio/")?"audio":t.includes("pdf")||t.includes("document")||t.includes("spreadsheet")||t.includes("presentation")||t.includes("text/")?"document":"unknown"})(a),[a]),X="image"===H,Y=(a.mime_type||a.original_mime||"").includes("image/gif"),J=X||Y,Z=i(()=>(e=>{if(!e)return"";const t=e.split(".");return t.length>1?t.pop().toLowerCase():""})(a.filename),[a.filename]),ee=Re[Z]||Re.default,te=i(()=>((e,t)=>{if(!e||!t||e<=0||t<=0)return null;const n=je(Math.round(e),Math.round(t)),l=Math.round(e)/n,r=Math.round(t)/n;return l>20||r>20?null:`${l}:${r}`})(a.width,a.height),[a.width,a.height]),ne=a.url||a.path,le=J&&a.thumbnail_url?a.thumbnail_url:ne,[re,ae]=t(()=>G(le)),[ie,oe]=t(()=>!Q(le)),[se,ce]=t(!1),[ue,de]=t(()=>Q(le)),{isMobile:be,isTouch:me}=M(),he=window.limboCore?.accessibilityManager,pe=(window.limboCore?.config?.getGlobal()||{}).interaction||{allowSelection:!1,allowCropping:!0},fe=e=>{e.stopPropagation(),he?.announce(`Eliminando imagen ${a.filename}`,"assertive"),o?.(a)},ge=async e=>{e.stopPropagation();let t=a.url||a.path;try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t);else{const e=document.createElement("textarea");e.value=t,e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.focus(),e.select(),document.execCommand("copy"),document.body.removeChild(e)}N(!0),he?.announce(`URL de ${a.filename} copiada al portapapeles. Nota: La URL puede tener un tiempo de validez limitado.`),setTimeout(()=>N(!1),2e3)}catch(n){console.error("Error al copiar URL:",n),he?.announce(`Error al copiar URL de ${a.filename}. Inténtalo de nuevo.`),alert(`Error al copiar URL de ${a.filename}. Por favor, inténtalo de nuevo.`)}},xe=async e=>{e.preventDefault(),e.stopPropagation();const t=a.url||a.path,n=a.filename||"limbo-file";if(!X){try{he?.announce(`Descargando ${n}`);const e=await fetch(t,{mode:"cors"});if(!e.ok)throw new Error(`HTTP error: ${e.status}`);const l=await e.blob(),r=window.URL.createObjectURL(l),a=document.createElement("a");a.href=r,a.download=n,a.style.display="none",document.body.appendChild(a),a.click(),setTimeout(()=>{window.URL.revokeObjectURL(r),document.body.removeChild(a)},100),he?.announce(`${n} descargado correctamente`)}catch(r){console.error("Error downloading file:",r),he?.announce(`Error al descargar ${n}`)}return}const{downloadImage:l}=await Promise.resolve().then(()=>rl);await l(t,n,{originalFormat:a.format,accessibilityManager:he})},ke=e=>{e.stopPropagation(),he?.announce(`Editando imagen ${a.filename}`),d?.(a)},Ce=l(e=>{e.stopPropagation();const t=a.filename.replace(/\.[^.]+$/,"");j(t),U(null),O(!0),setTimeout(()=>V.current?.select(),0)},[a.filename]),Ne=l(e=>{e?.stopPropagation(),O(!1),U(null)},[]),Se=l(e=>{const t=e.target.value;j(t);const n=B(t||"_");U(n.valid?null:n.error)},[]),$e=l(async e=>{e?.preventDefault(),e?.stopPropagation();const t=R.trim(),n=B(t);if(!n.valid)return void U(n.error);const l=t+(a.filename.includes(".")?"."+a.filename.split(".").pop():"");if(l!==a.filename){q(!0);try{await(k?.(a,l)),O(!1)}catch{U("Error al renombrar. Inténtalo de nuevo.")}finally{q(!1)}}else O(!1)},[R,a,k]),Le=X&&(a.variants&&a.variants.length>0||T>0),Ae=T,Me=e.useCallback(()=>{z(e=>Math.max(0,e-1))},[]);e.useEffect(()=>{z(a.variants_count||0)},[a.variants_count]),n(()=>{if(!J)return oe(!1),void de(!0);if(a.thumbnail_url)return ae(a.thumbnail_url),oe(!0),ce(!1),void de(!1);const e=a.url||a.path;if(Q(e))return ae(G(e)),oe(!1),ce(!1),void de(!0);oe(!0),ce(!1),de(!1),K(e).then(e=>{ae(e),oe(!1),de(!0)}).catch(()=>{ae(e),oe(!1),ce(!0)})},[a.url,a.path,a.thumbnail_url,J]);const Ie=pe.allowSelection&&x.select&&b,De=Y?ne:null,Ue=X&&!Y&&pe.allowCropping&&x.crop&&d,Be=()=>{Ie?(he?.announce(`Seleccionando ${a.filename} para el portal`),b?.(a)):Le?(he?.announce(`Mostrando recortes de ${a.filename}`),E(!0)):(he?.announce(`Abriendo visor de ${a.filename}`),_(!0))};/* @__PURE__ */
|
|
128
128
|
return c(u,{children:[
|
|
129
|
-
/* @__PURE__ */c("div",{className:`limbo-image-card-wrapper lb:relative lb:cursor-pointer lb:focus:outline-0 ${p?"lb:opacity-50":""} ${
|
|
129
|
+
/* @__PURE__ */c("div",{className:`limbo-image-card-wrapper lb:relative lb:cursor-pointer lb:focus:outline-0 ${p?"lb:opacity-50":""} ${be?"limbo-image-card-wrapper--mobile":""}`,onClick:Be,onKeyDown:e=>{if("INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName)switch(e.key){case"Enter":case" ":e.preventDefault(),Be();break;case"d":case"D":x.download&&(e.preventDefault(),xe(e));break;case"c":case"C":x.copy&&(e.preventDefault(),ge(e));break;case"Delete":case"Backspace":x.delete&&o&&(e.preventDefault(),fe(e));break;case"x":case"X":x.crop&&d&&(e.preventDefault(),ke(e));break;case"v":case"V":x.variants&&(e.preventDefault(),(e=>{e.stopPropagation(),he?.announce(`Mostrando recortes de ${a.filename}`),E(!0)})(e))}},onMouseEnter:De?()=>{De&&a.thumbnail_url&&ae(De)}:void 0,onMouseLeave:De?()=>{De&&a.thumbnail_url&&ae(a.thumbnail_url)}:void 0,title:Le?`Ver ${Ae} recorte${1!==Ae?"s":""} de ${a.filename}`:J?be?"Toque para ampliar imagen":"Click para ampliar imagen con zoom":be?"Toque para previsualizar":"Click para previsualizar",role:"button",tabIndex:0,"aria-label":J?`${Y?"GIF":"Imagen"} ${a.filename}. ${a.width}x${a.height} px`:`Archivo ${a.filename}. Tipo: ${H}`,style:{...me&&{touchAction:"manipulation",WebkitTapHighlightColor:"transparent"}},children:[P&&/* @__PURE__ */c("div",{className:"limbo-moving-overlay",children:[
|
|
130
130
|
/* @__PURE__ */s("span",{className:"icon icon-spinner lb:animate-spin lb:w-6 lb:h-6"}),
|
|
131
131
|
/* @__PURE__ */s("span",{className:"lb:text-xs lb:text-gray-600 lb:font-medium",children:"Moviendo..."})]}),
|
|
132
|
-
/* @__PURE__ */c("div",{className:`limbo-image-actions ${L?"limbo-image-actions--expanded":""} ${
|
|
133
|
-
/* @__PURE__ */c("div",{className:"limbo-image-actions__buttons",children:[(
|
|
134
|
-
/* @__PURE__ */c("div",{className:"limbo-image-card "+(
|
|
135
|
-
/* @__PURE__ */c("div",{className:"lb:relative lb:w-full lb:h-full lb:rounded lb:overflow-hidden lb:border lb:border-neutral-300",style:{...
|
|
132
|
+
/* @__PURE__ */c("div",{className:`limbo-image-actions ${L?"limbo-image-actions--expanded":""} ${be?"limbo-image-actions--mobile":""}`,children:[
|
|
133
|
+
/* @__PURE__ */c("div",{className:"limbo-image-actions__buttons",children:[(Ie||!J)&&/* @__PURE__ */s("button",{type:"button",title:Le?`Ver ${Ae} recortes`:J?"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 "+(be?"lb:btn--touch":""),onClick:e=>{e?.stopPropagation(),Le?(he?.announce(`Mostrando recortes de ${a.filename}`),E(!0)):(he?.announce(`Abriendo visor de ${a.filename}`),_(!0))},tabIndex:-1,style:{...be&&{width:"40px",height:"40px"}},children:/* @__PURE__ */s("span",{className:`icon ${J?"icon-zoom-in-white":"icon-search-white"} icon--sm`,"aria-hidden":"true"})}),Ue&&/* @__PURE__ */s("button",{type:"button",title:"Nuevo recorte",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 "+(be?"lb:btn--touch":""),onClick:ke,tabIndex:-1,style:{...be&&{width:"40px",height:"40px"}},children:/* @__PURE__ */s("span",{className:"icon icon-scissors-white icon--sm","aria-hidden":"true"})}),x.copy&&/* @__PURE__ */s("button",{type:"button",title:C?"¡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 "+(be?"lb:btn--touch":""),onClick:ge,tabIndex:-1,style:{...be&&{width:"40px",height:"40px"}},children:/* @__PURE__ */s("span",{className:`icon ${C?"icon-copied-white":"icon-copy-white"} icon--sm`,"aria-hidden":"true"})}),x.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 "+(be?"lb:btn--touch":""),onClick:xe,tabIndex:-1,style:{...be&&{width:"40px",height:"40px"}},children:/* @__PURE__ */s("span",{className:"icon icon-download-white icon--sm","aria-hidden":"true"})}),g&&m&&/* @__PURE__ */s("button",{type:"button",title:a.folder?`Mover de carpeta (${a.folder?.name||a.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 "+(be?"lb:btn--touch":""),onClick:e=>{e.stopPropagation(),A(!L)},tabIndex:-1,style:{...be&&{width:"40px",height:"40px"}},children:/* @__PURE__ */s("span",{className:"icon icon-folder-white icon--sm","aria-hidden":"true"})}),x.rename&&k&&/* @__PURE__ */s("button",{type:"button",title:"Renombrar archivo",className:"limbo-action-btn limbo-btn-rename lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:border lb:border-brand-blue-1000 "+(be?"lb:btn--touch":""),onClick:Ce,tabIndex:-1,style:{...be&&{width:"40px",height:"40px"}},children:/* @__PURE__ */s("span",{className:"icon icon-edit-white icon--sm","aria-hidden":"true"})}),x.delete&&o&&/* @__PURE__ */s("button",{onClick:fe,disabled:p,className:"limbo-action-btn limbo-btn-delete lb:bg-red-800 lb:hover:bg-red-700 lb:border lb:border-red-700 "+(be?"lb:btn--touch lb:active:lb:bg-red-800":""),title:"Eliminar archivo",tabIndex:-1,style:{...be&&{width:"40px",height:"40px"}},children:p?"…":/* @__PURE__ */s("span",{className:"icon icon-close-small-white icon--sm","aria-hidden":"true"})})]}),L&&g&&m&&/* @__PURE__ */s("div",{className:"limbo-image-actions__folder",onClick:e=>e.stopPropagation(),children:/* @__PURE__ */s(Oe,{value:a.folder?.slug||null,onChange:async e=>{if(!P){I(!0);try{const t=e?.slug||null;await(m?.(a,t)),Pe(),he?.announce(e?`${a.filename} movido a carpeta ${e.name}`:`${a.filename} movido a Sin carpeta`)}catch(t){console.error("Error moving to folder:",t),he?.announce(`Error al mover ${a.filename}`)}finally{I(!1),A(!1)}}},allowCreate:w,placeholder:"Sin carpeta",label:"Mover a carpeta",includeNoFolder:!0,allowedSlugs:v,excludeSlugs:y,disabled:P,mode:"upload"})})]}),
|
|
134
|
+
/* @__PURE__ */c("div",{className:"limbo-image-card "+(be?"limbo-image-card--mobile":""),children:[!J&&(a.thumbnail_url?
|
|
135
|
+
/* @__PURE__ */c("div",{className:"lb:relative lb:w-full lb:h-full lb:rounded lb:overflow-hidden lb:border lb:border-neutral-300",style:{...be&&{minHeight:`${Math.max(3*h,80)}px`}},children:[
|
|
136
136
|
/* @__PURE__ */s("img",{src:a.thumbnail_url,alt:a.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")}}),
|
|
137
137
|
/* @__PURE__ */s("div",{className:(a.thumbnail_url?"lb:flex":"lb:hidden")+"lb:absolute lb:inset-0 lb:bg-linear-to-br lb:from-neutral-100 lb:to-neutral-200 lb:flex-col lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"lb:mb-2 lb:h-[25%] lb:w-[25%]","aria-hidden":"true",children:/* @__PURE__ */s("span",{className:`icon ${ee.symbol} lb:min-w-full lb:min-h-full`})})}),
|
|
138
138
|
/* @__PURE__ */s("span",{className:"lb:absolute lb:bottom-1.5 lb:right-1.5 lb:text-[10px] lb:uppercase lb:font-bold lb:tracking-wide lb:px-1.5 lb:py-0.5 lb:rounded lb:shadow-sm",style:{backgroundColor:ee.color,color:"white"},children:Z||H})]}):
|
|
139
|
-
/* @__PURE__ */c("div",{className:"lb:w-full lb:h-full lb:rounded lb:bg-linear-to-br lb:from-neutral-100 lb:to-neutral-200 lb:flex lb:flex-col lb:items-center lb:justify-center lb:border lb:border-neutral-300",style:{...
|
|
139
|
+
/* @__PURE__ */c("div",{className:"lb:w-full lb:h-full lb:rounded lb:bg-linear-to-br lb:from-neutral-100 lb:to-neutral-200 lb:flex lb:flex-col lb:items-center lb:justify-center lb:border lb:border-neutral-300",style:{...be&&{minHeight:`${Math.max(3*h,80)}px`}},children:[
|
|
140
140
|
/* @__PURE__ */s("span",{className:"lb:mb-2 lb:h-[25%] lb:w-[25%]","aria-hidden":"true",children:/* @__PURE__ */s("span",{className:`icon ${ee.symbol} lb:min-w-full lb:min-h-full`})}),
|
|
141
|
-
/* @__PURE__ */s("span",{className:"lb:text-xs lb:uppercase lb:font-bold lb:tracking-wide lb:px-2 lb:py-0.5 lb:rounded",style:{backgroundColor:ee.color,color:"white"},children:Z||H})]})),J&&/* @__PURE__ */c(u,{children:[
|
|
141
|
+
/* @__PURE__ */s("span",{className:"lb:text-xs lb:uppercase lb:font-bold lb:tracking-wide lb:px-2 lb:py-0.5 lb:rounded",style:{backgroundColor:ee.color,color:"white"},children:Z||H})]})),J&&/* @__PURE__ */c(u,{children:[ie&&!se&&/* @__PURE__ */s("div",{className:"lb:w-full lb:aspect-square lb:rounded lb:bg-neutral-200 lb:animate-pulse lb:flex lb:items-center lb:justify-center lb:absolute lb:inset-0 lb:z-10 "+(Le?"lb:ring-2 lb:ring-brand-blue-400 lb:ring-offset-2":""),style:{...be&&{minHeight:`${Math.max(3*h,80)}px`}},children:/* @__PURE__ */s("span",{className:"icon icon-spinner lb:w-8 lb:h-8 lb:animate-spin"})}),se&&/* @__PURE__ */c("div",{className:"lb:z-0 lb:absolute lb:top-0 lb:left-0 lb:w-full lb:aspect-square lb:rounded lb:bg-neutral-100 lb:flex lb:flex-col lb:items-center lb:justify-center lb:text-neutral-400",style:{...be&&{minHeight:`${Math.max(3*h,80)}px`}},children:[
|
|
142
142
|
/* @__PURE__ */s("span",{className:"icon icon-close icon--lg lb:mb-1","aria-hidden":"true"}),
|
|
143
143
|
/* @__PURE__ */s("span",{className:"lb:text-xs",children:"Error al cargar"})]}),
|
|
144
|
-
/* @__PURE__ */s("img",{src:
|
|
145
|
-
/* @__PURE__ */c("
|
|
144
|
+
/* @__PURE__ */s("img",{src:re,loading:"lazy",decoding:"async",alt:a.filename.split(".")[0]??a.filename,className:`lb:z-1 lb:w-full lb:object-cover lb:rounded lb:aspect-square lb:transition-opacity lb:duration-300 ${Le?"lb:ring-2 lb:ring-brand-blue-400 lb:ring-offset-2":""} ${ue?"lb:opacity-100":"lb:opacity-0"}`,sizes:`height: ${6*h}px,width: ${6*h}px`,draggable:!1,onLoad:()=>{oe(!1),de(!0)},onError:()=>{oe(!1),ce(!0)},style:{...be&&{minHeight:`${Math.max(3*h,80)}px`,height:"auto",aspectRatio:"1 / 1",objectFit:"cover"}}}),Y&&/* @__PURE__ */s("span",{className:"lb:absolute lb:bottom-1.5 lb:right-1.5 lb:text-[10px] lb:uppercase lb:font-bold lb:tracking-wide lb:px-1.5 lb:py-0.5 lb:rounded lb:shadow-sm",style:{backgroundColor:ee.color,color:"white"},children:Z||H}),X&&!Le&&a.width&&a.height&&/* @__PURE__ */c("span",{className:"lb:absolute lb:bottom-1.5 lb:right-1.5 lb:text-[10px] lb:font-bold lb:tracking-wide lb:px-1.5 lb:py-0.5 lb:rounded lb:shadow-sm lb:leading-tight lb:text-center lb:flex lb:flex-col lb:items-center",style:{backgroundColor:"rgba(15,23,42,0.72)",color:"white"},title:`${a.width} × ${a.height} px`,children:[
|
|
145
|
+
/* @__PURE__ */c("span",{children:[a.width,"×",a.height]}),te&&/* @__PURE__ */s("span",{style:{opacity:.85},children:te})]})]}),
|
|
146
|
+
/* @__PURE__ */c("div",{className:"limbo-card-info-overlay lb:z-99999999999 "+(be?"limbo-card-info-overlay--mobile":""),style:D?{pointerEvents:"auto"}:void 0,children:[D?/* @__PURE__ */c("form",{className:"lb:flex lb:flex-col lb:w-full lb:gap-1",onSubmit:$e,onClick:e=>e.stopPropagation(),children:[
|
|
146
147
|
/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-1 lb:w-full",children:[
|
|
147
|
-
/* @__PURE__ */s("input",{ref:V,type:"text",value:R,onChange:
|
|
148
|
+
/* @__PURE__ */s("input",{ref:V,type:"text",value:R,onChange:Se,onKeyDown:e=>"Escape"===e.key&&Ne(e),className:`lb:flex-1 lb:min-w-0 lb:px-1 lb:py-0.5 lb:text-xs lb:rounded lb:border ${F?"lb:border-red-400":"lb:border-gray-400"} lb:bg-white lb:text-gray-900 lb:outline-none`,placeholder:"Nuevo nombre",disabled:W,autoFocus:!0}),
|
|
148
149
|
/* @__PURE__ */s("button",{type:"submit",disabled:W||!!F,className:"lb:px-1.5 lb:py-0.5 lb:text-xs lb:bg-brand-blue-400 lb:text-white lb:rounded lb:shrink-0 lb:disabled:opacity-40 lb:hover:outline-brand-blue-400/50 lb:hover:outline-2",title:"Guardar nombre",children:W?"…":"✓"}),
|
|
149
|
-
/* @__PURE__ */s("button",{type:"button",onClick:
|
|
150
|
+
/* @__PURE__ */s("button",{type:"button",onClick:Ne,className:"lb:px-1.5 lb:py-0.5 lb:text-xs lb:bg-gray-500 lb:hover:outline-gray-500/50 lb:hover:outline-2 lb:text-white lb:rounded lb:shrink-0",title:"Cancelar",children:"✕"})]}),F&&/* @__PURE__ */s("span",{className:"lb:text-xs lb:text-red-300 lb:leading-tight",children:F})]}):/* @__PURE__ */c("span",{className:"limbo-card-info-name lb:truncate lb:max-w-full",children:[a.filename.split(".")[0]??a.filename,Le&&/* @__PURE__ */s("span",{className:"limbo-variants-indicator",style:{marginLeft:"4px",padding:"1px 6px",backgroundColor:"#dc2626",color:"white",borderRadius:"10px",fontSize:"10px",fontWeight:"700",display:"inline-block"},title:`${Ae} recorte${1!==Ae?"s":""}`,children:Ae})]}),f&&a.folder&&/* @__PURE__ */c("span",{className:"limbo-card-info-folder lb:flex lb:items-center lb:gap-1 lb:bg-brand-blue-50 lb:rounded-md lb:px-1",title:`Carpeta: ${a.folder?.name||a.folder?.slug||a.folder}`,children:[
|
|
150
151
|
/* @__PURE__ */s("span",{className:"icon icon-folder icon--sm"}),
|
|
151
152
|
/* @__PURE__ */s("span",{className:"lb:truncate lb:max-w-20",children:a.folder?.name||a.folder?.slug||("string"==typeof a.folder?a.folder:"Sin carpeta")})]})]})]})]}),
|
|
152
|
-
/* @__PURE__ */s(ze,{image:a,isOpen:S,onClose:()=>E(!1),onSelect:b,onDelete:o,onCrop:d,onVariantDeleted:
|
|
153
|
+
/* @__PURE__ */s(ze,{image:a,isOpen:S,onClose:()=>E(!1),onSelect:b,onDelete:o,onCrop:d,onVariantDeleted:Me,allowedActions:{select:x.select,download:x.download,copy:x.copy,delete:x.delete,crop:x.crop}}),$&&(()=>{const e=a.url||a.path,t=()=>_(!1),n=a.file_size?`${Math.round(a.file_size/1024)}KB`:"",l=a.mime_type||"";return J?/* @__PURE__ */s(Te,{isOpen:!0,src:e,alt:a.filename,title:a.filename,subtitle:`${a.width||"?"}×${a.height||"?"} · ${n}`,onClose:t}):"video"===H?/* @__PURE__ */s(ve,{isOpen:!0,src:e,title:a.filename,subtitle:`${Z.toUpperCase()} · ${n}`,onClose:t}):"audio"===H?/* @__PURE__ */s(ye,{isOpen:!0,src:e,title:a.filename,subtitle:`${Z.toUpperCase()} · ${n}`,onClose:t}):l.includes("pdf")?/* @__PURE__ */s(we,{isOpen:!0,src:e,title:a.filename,subtitle:n,onClose:t}):(e=>!(!e||!Fe.has(e)&&!e.startsWith("text/")))(l)?/* @__PURE__ */s(_e,{isOpen:!0,src:e,title:a.filename,subtitle:`${Z.toUpperCase()} · ${n}`,mimeType:l,fileSize:a.file_size||0,onClose:t}):/* @__PURE__ */s(Ee,{isOpen:!0,src:e,title:a.filename,subtitle:`${Z.toUpperCase()} · ${n}`,mimeType:l,fileSize:a.file_size||0,onClose:t})})()]})});function Be(){/* @__PURE__ */
|
|
153
154
|
return c("div",{className:"limbo-image-card lb:animate-pulse",role:"status","aria-label":"Cargando imágen...",children:[
|
|
154
155
|
/* @__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"})}),
|
|
155
156
|
/* @__PURE__ */s("div",{className:"limbo-image-card-name lb:opacity-100 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"})}),
|
|
156
|
-
/* @__PURE__ */s("span",{className:"sr-only",children:"Cargando imágen..."})]})}function
|
|
157
|
+
/* @__PURE__ */s("span",{className:"sr-only",children:"Cargando imágen..."})]})}function We({variant:e="info",toast:l=!1,fixed:r=!1,onClose:a,className:i="",children:o,role:u}){const[d,b]=t(!1);if(n(()=>{b(!1)},[o]),d)return null;/* @__PURE__ */
|
|
157
158
|
return c("div",{className:`${l||r?`${r?"lb:fixed lb:top-4 lb:right-4 lb:z-10000":l?"lb:absolute lb:top-5 lb:right-5 lb:w-fit lb:m-4 lb:z-50":""} ${{success:"lb:bg-green-600",danger:"lb:bg-red-500",warning:"lb:bg-yellow-500",info:"lb:bg-blue-500"}[e]||"lb:bg-gray-600"} lb:text-white lb:px-5 lb:py-3 lb:rounded-lg lb:shadow-lg lb:transition-all lb:duration-300 lb:animate-fade-in`:`limbo-alert limbo-alert-${e}`} lb:pr-8 ${i}`,role:u||"alert",children:[o,
|
|
158
|
-
/* @__PURE__ */s("button",{type:"button",onClick:e=>{e.stopPropagation(),a?a():b(!0)},className:"lb:absolute lb:top-1/2 lb:-translate-y-1/2 lb:right-2 lb:p-1 lb:rounded-full lb:opacity-60 lb:hover:opacity-100 lb:transition-opacity lb:cursor-pointer","aria-label":"Cerrar",children:/* @__PURE__ */s("span",{className:"icon icon-close-small-white icon--sm","aria-hidden":"true"})})]})}const
|
|
159
|
+
/* @__PURE__ */s("button",{type:"button",onClick:e=>{e.stopPropagation(),a?a():b(!0)},className:"lb:absolute lb:top-1/2 lb:-translate-y-1/2 lb:right-2 lb:p-1 lb:rounded-full lb:opacity-60 lb:hover:opacity-100 lb:transition-opacity lb:cursor-pointer","aria-label":"Cerrar",children:/* @__PURE__ */s("span",{className:"icon icon-close-small-white icon--sm","aria-hidden":"true"})})]})}const qe=[{value:"",label:"Todos los tipos"},{value:"image",label:"Imágenes"},{value:"video",label:"Videos"},{value:"document",label:"Documentos"},{value:"audio",label:"Audio"}];function Ve({onSelect:e,onCrop:l,onDelete:a,deletingId:o,images:u,loading:m,error:h,filters:p={name:"",dateFrom:"",dateTo:"",uploadedBy:"",assetType:"",folder:""},debouncedFilters:f=null,onFiltersChange:g,filterConfig:v={showNameFilter:!0,showUploadedByFilter:!1,showDateFilter:!0,showTypeFilter:!1},loadingConfig:y={showPlaceholders:!0,placeholderCount:10,showSpinner:!0},allowedActions:w={select:!0,download:!0,copy:!0,delete:!0,crop:!0,variants:!0},allowedCategories:x=null,resolvedAccept:k=null,folderConfig:C=null,onFolderChange:N=null,onRename:S=null}){const{isSearching:E,searchPending:$}=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}}(p,f||p,m),_=!1!==v.showNameFilter,T=!0===v.showUploadedByFilter,z=!1!==v.showDateFilter,L=!1!==v.showTypeFilter,A=!0===C?.showFolderFilter,M=C?.include?.length>0?C.include:null,P=C?.exclude?.length>0?C.exclude:null,I=!1!==C?.showFolderInfo,D=!1!==C?.allowMoveFolder&&!!N,O=!0===C?.allowCreateFolder,R=i(()=>{const e=k&&!k.isAllTypes?function(e){if(!e||e.isAllTypes)return null;const t=new Set(e.categories);for(const n of e.extensions){const e=d[n]||[];for(const n of e)for(const[e,l]of Object.entries(b))l.includes(n)&&t.add(e)}for(const n of e.mimeTypes)for(const[e,l]of Object.entries(b))(l.includes(n)||n.startsWith(e+"/"))&&t.add(e);return t.size>0?[...t]:null}(k):x;return e?qe.filter(t=>""===t.value||e.includes(t.value)):qe},[k,x]),j=r(null),F=window.limboCore?.accessibilityManager;n(()=>{if(j.current&&window.limboCore?.keyboardManager){const e="gallery-grid";j.current.setAttribute("data-grid-id",e),window.limboCore.keyboardManager.setupGridNavigation(j.current,{itemSelector:".limbo-image-card",gridId:e,columns:"auto"})}},[u]),n(()=>{if(!m&&u.length>0){const e=u.slice(0,12).map(e=>e.url||e.path).filter(Boolean);e.length>0&&X(e,4)}},[m,u]);const U=i(()=>{if(!p.assetType)return"archivos";return{image:"imágenes",video:"videos",document:"documentos",audio:"archivos de audio"}[p.assetType]||"archivos"},[p.assetType]);n(()=>{m?F?.announceLoading(!0,"galería"):m||h?h&&F?.announceError(h,"galería"):(F?.announceLoading(!1,"galería"),u.length>0&&F?.announce(`Se encontraron ${u.length} ${U} en la galería`))},[m,h,u.length,F,U]),n(()=>{$&&F?.announce("Buscando...","polite")},[$,F]);const B=e=>{const{name:t,value:n}=e.target;g&&g({...p,[t]:n})},W=p.name||p.dateFrom||p.dateTo||p.uploadedBy||p.assetType||p.folder,q=E&&u.length>0&&!m;/* @__PURE__ */
|
|
159
160
|
return c("div",{className:"lb:w-full lb:max-w-full lb:py-2 lb:overflow-x-hidden lb:box-border",children:[
|
|
160
161
|
/* @__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 flex items-stretch content-stretch flex-row",onSubmit:e=>e.preventDefault(),role:"search","aria-label":"Filtrar archivos",children:[_&&/* @__PURE__ */c("div",{className:"limbo-filter-group limbo-filter-group--name",children:[
|
|
161
162
|
/* @__PURE__ */c("label",{htmlFor:"name",className:"limbo-filter-label",children:["Nombre",$&&/* @__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"})})]}),
|
|
@@ -176,10 +177,10 @@ return c("div",{className:"lb:w-full lb:max-w-full lb:py-2 lb:overflow-x-hidden
|
|
|
176
177
|
/* @__PURE__ */s("span",{className:"icon icon-close-small"}),"Limpiar"]})]})]})}),m?/* @__PURE__ */c("div",{className:"lb:relative",children:[
|
|
177
178
|
/* @__PURE__ */s("div",{className:"lb:relative lb:inset-0 lb:flex lb:items-center lb:justify-center lb:bg-white/80 lb:z-10 lb:min-h-75",children:/* @__PURE__ */c("div",{className:"lb:flex lb:flex-col lb:items-center lb:gap-3",children:[
|
|
178
179
|
/* @__PURE__ */s("span",{className:"icon icon-spinner lb:p-4 lb:animate-spin"}),
|
|
179
|
-
/* @__PURE__ */c("span",{className:"lb:text-sm lb:text-gray-600 lb:font-medium",children:["Cargando ",U,"..."]})]})}),y.showPlaceholders&&/* @__PURE__ */s("div",{ref:j,className:"limbo-gallery lb:opacity-30","data-limbo-responsive":!0,role:"grid","aria-label":`Cargando ${U} de la galería`,"aria-busy":"true",children:Array.from({length:y.placeholderCount}).map((e,t)=>/* @__PURE__ */s("div",{role:"gridcell","aria-posinset":t+1,"aria-setsize":y.placeholderCount,className:"lb:min-w-0",children:/* @__PURE__ */s(
|
|
180
|
+
/* @__PURE__ */c("span",{className:"lb:text-sm lb:text-gray-600 lb:font-medium",children:["Cargando ",U,"..."]})]})}),y.showPlaceholders&&/* @__PURE__ */s("div",{ref:j,className:"limbo-gallery lb:opacity-30","data-limbo-responsive":!0,role:"grid","aria-label":`Cargando ${U} de la galería`,"aria-busy":"true",children:Array.from({length:y.placeholderCount}).map((e,t)=>/* @__PURE__ */s("div",{role:"gridcell","aria-posinset":t+1,"aria-setsize":y.placeholderCount,className:"lb:min-w-0",children:/* @__PURE__ */s(Be,{})},`skeleton-${t}`))})]}):h?/* @__PURE__ */s(We,{variant:"danger",className:"lb:text-center",children:h}):/* @__PURE__ */c("div",{className:"lb:relative",children:[q&&/* @__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:[
|
|
180
181
|
/* @__PURE__ */s("span",{className:"icon icon-spinner lb:animate-spin"}),
|
|
181
182
|
/* @__PURE__ */s("span",{children:"Buscando..."})]})}),
|
|
182
|
-
/* @__PURE__ */s("div",{ref:j,className:"limbo-gallery lb:px-3 lb:pt-4 lb:box-border lb:max-w-full "+(q?"lb:opacity-50 lb:pointer-events-none":""),"data-limbo-responsive":!0,"data-grid-id":"gallery-grid",role:"grid","aria-label":`Galería de ${U}. Use las flechas para navegar`,"aria-busy":q,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(
|
|
183
|
+
/* @__PURE__ */s("div",{ref:j,className:"limbo-gallery lb:px-3 lb:pt-4 lb:box-border lb:max-w-full "+(q?"lb:opacity-50 lb:pointer-events-none":""),"data-limbo-responsive":!0,"data-grid-id":"gallery-grid",role:"grid","aria-label":`Galería de ${U}. Use las flechas para navegar`,"aria-busy":q,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(Ue,{image:t,onSelect:e,onCrop:l,onDelete:w.delete&&a?()=>a(t.id):null,onFolderChange:N,onRename:S,thumbnailSize:32,isDeleting:o===t.id,showFolderInfo:I,allowMoveFolder:D,allowedFolderSlugs:M,excludedFolderSlugs:P,allowCreateFolder:O,allowedActions:w})},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 ",U]})})})]})]})}function He({previewUrl:e,fileName:n}){const[l,a]=t(!1),[i,o]=t(!1),u=r(null);/* @__PURE__ */
|
|
183
184
|
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:[
|
|
184
185
|
/* @__PURE__ */s("span",{className:"icon icon-video icon--xl lb:text-gray-400 lb:mb-4"}),
|
|
185
186
|
/* @__PURE__ */s("p",{className:"lb:text-sm lb:text-gray-600",children:"No se puede reproducir el video"}),
|
|
@@ -187,7 +188,7 @@ return c("div",i?{className:"lb:flex lb:flex-col lb:items-center lb:justify-cent
|
|
|
187
188
|
/* @__PURE__ */s("video",{ref:u,src:e,className:"lb:absolute lb:inset-0 lb:w-full lb:h-full lb:object-contain",onEnded:()=>{a(!1)},onError:()=>{o(!0)},onPlay:()=>a(!0),onPause:()=>a(!1),controls:!0,preload:"metadata",children:"Tu navegador no soporta la reproduccion de video."}),!l&&/* @__PURE__ */s("button",{type:"button",onClick:()=>{u.current&&(l?u.current.pause():u.current.play(),a(!l))},className:"lb:absolute lb:inset-0 lb:flex lb:items-center lb:justify-center lb:bg-black/30 lb:hover:bg-black/40 lb:transition-colors lb:cursor-pointer","aria-label":"Reproducir video",children:/* @__PURE__ */s("div",{className:"lb:w-16 lb:h-16 lb:rounded-full lb:bg-white/90 lb:flex lb:items-center lb:justify-center lb:shadow-lg",children:/* @__PURE__ */s("span",{className:"icon icon-play icon--lg lb:text-gray-800 lb:ml-1"})})}),
|
|
188
189
|
/* @__PURE__ */c("div",{className:"lb:absolute lb:top-2 lb:right-2 lb:bg-black/60 lb:text-white lb:px-2 lb:py-1 lb:rounded lb:text-xs lb:flex lb:items-center lb:gap-1",children:[
|
|
189
190
|
/* @__PURE__ */s("span",{className:"icon icon-video icon--xs"}),
|
|
190
|
-
/* @__PURE__ */s("span",{children:"VIDEO"})]})]})}function
|
|
191
|
+
/* @__PURE__ */s("span",{children:"VIDEO"})]})]})}function Ke({previewUrl:e,fileName:n,fileSize:l}){const[a,i]=t(!1),[o,d]=t(!1),[b,m]=t(0),[h,p]=t(0),f=r(null),g=e=>{if(!e||isNaN(e))return"0:00";return`${Math.floor(e/60)}:${Math.floor(e%60).toString().padStart(2,"0")}`};/* @__PURE__ */
|
|
191
192
|
return c("div",o?{className:"lb:flex lb:flex-col lb:items-center lb:justify-center lb:p-8 lb:min-h-50 lb:bg-gray-100 lb:rounded-lg",children:[
|
|
192
193
|
/* @__PURE__ */s("span",{className:"icon icon-audio icon--xl lb:text-gray-400 lb:mb-4"}),
|
|
193
194
|
/* @__PURE__ */s("p",{className:"lb:text-sm lb:text-gray-600",children:"No se puede reproducir el audio"}),
|
|
@@ -203,7 +204,7 @@ return c("div",o?{className:"lb:flex lb:flex-col lb:items-center lb:justify-cent
|
|
|
203
204
|
/* @__PURE__ */s("span",{children:"•"}),
|
|
204
205
|
/* @__PURE__ */s("span",{children:Ne(l)})]})]}),
|
|
205
206
|
/* @__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 lb:cursor-pointer",onClick:e=>{if(!f.current||!b)return;const t=e.currentTarget.getBoundingClientRect(),n=e.clientX-t.left;f.current.currentTime=n/t.width*b},role:"slider","aria-label":"Progreso de audio","aria-valuenow":h,"aria-valuemin":0,"aria-valuemax":b,tabIndex:0,children:/* @__PURE__ */s("div",{className:"lb:h-full lb:bg-purple-500 lb:rounded-full lb:transition-all lb:duration-100 lb:pointer-events-none",style:{width:b>0?h/b*100+"%":"0%"}})})}),
|
|
206
|
-
/* @__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
|
|
207
|
+
/* @__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 Ge({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,v]=t(null),[y,w]=t({name:"",size:"",type:"",category:"unknown"}),[x,k]=t(!1),[C,N]=t(!1),[S,E]=t(""),$="image"===y.category,_="video"===y.category,T="audio"===y.category,z=void 0!==b?b:$;n(()=>{if(!f)return void v(null);const e=URL.createObjectURL(f);v(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:Ne(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__ */
|
|
207
208
|
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:[
|
|
208
209
|
/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:justify-between lb:mb-4 lb:px-1",children:[
|
|
209
210
|
/* @__PURE__ */s("h3",{className:"lb:text-sm lb:font-medium lb:text-gray-700",children:(()=>{switch(y.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"}})()}),
|
|
@@ -214,7 +215,7 @@ return c("div",{className:"lb:w-full lb:max-w-full lb:bg-white lb:border lb:bord
|
|
|
214
215
|
/* @__PURE__ */s("img",{src:g,alt:"Vista previa",className:"lb:absolute lb:inset-0 lb:w-full lb:h-full lb:object-contain"}),
|
|
215
216
|
/* @__PURE__ */c("div",{className:"lb:absolute lb:top-2 lb:right-2 lb:bg-black/50 lb:text-white lb:px-2 lb:py-1 lb:rounded lb:text-xs lb:flex lb:items-center lb:gap-1",children:[
|
|
216
217
|
/* @__PURE__ */s("span",{className:"icon icon-search-white icon--xs"}),
|
|
217
|
-
/* @__PURE__ */s("span",{className:"lb:hidden lb:sm:inline",children:"Ampliar"})]})]}):_?/* @__PURE__ */s(
|
|
218
|
+
/* @__PURE__ */s("span",{className:"lb:hidden lb:sm:inline",children:"Ampliar"})]})]}):_?/* @__PURE__ */s(He,{previewUrl:g,fileName:y.name}):T?/* @__PURE__ */s(Ke,{previewUrl:g,fileName:y.name,fileSize:f?.size}):/* @__PURE__ */s(Se,{file:f,mimeType:y.type,category:y.category}),$&&/* @__PURE__ */s("div",{className:"lb:mt-3 lb:text-center lb:space-y-1 lb:w-full",children:/* @__PURE__ */s("div",{className:"lb:rounded-sm lb:w-fit lb:gap-0.5 lb:p-0.5 lb:min-w-fit lb:mx-auto",children:/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:justify-center lb:gap-3 lb:text-xs lb:text-gray-500",children:[
|
|
218
219
|
/* @__PURE__ */s("span",{children:y.size}),
|
|
219
220
|
/* @__PURE__ */s("span",{children:"•"}),
|
|
220
221
|
/* @__PURE__ */s("span",{children:y.type.split("/")[1]?.toUpperCase()||"FILE"})]})})})]}),
|
|
@@ -231,16 +232,16 @@ return c("div",{className:"lb:w-full lb:max-w-full lb:bg-white lb:border lb:bord
|
|
|
231
232
|
/* @__PURE__ */s("span",{children:"Descargar"})]}),
|
|
232
233
|
/* @__PURE__ */c("button",{type:"button",onClick:()=>{S.trim()?(N(!1),o&&o(y.name)):N(!0)},disabled:d,className:"lb:flex-1 lb:md:flex-none lb:flex lb:items-center lb:justify-center lb:gap-2 lb:px-4 lb:py-2.5 lb:bg-brand-blue-800 lb:border lb:border-brand-blue-800 lb:text-white lb:rounded-lg lb:hover:bg-brand-blue-1000 lb:cursor-pointer lb:hover:border-brand-blue-1000 lb:transition-colors lb:disabled:opacity-50 lb:disabled:cursor-not-allowed lb:text-sm lb:font-medium lb:shadow-sm","aria-label":z?"Seleccionar para recortar":"Seleccionar archivo",children:[
|
|
233
234
|
/* @__PURE__ */s("span",{className:"icon icon-tick-white icon--sm"}),
|
|
234
|
-
/* @__PURE__ */s("span",{children:"Seleccionar"})]})]})]})]})}),$&&/* @__PURE__ */s(Te,{isOpen:x,src:g,alt:y.name,title:y.name,subtitle:`${y.size} • ${y.type.split("/")[1]?.toUpperCase()||"IMAGE"}`,onClose:()=>k(!1)})]})}const
|
|
235
|
+
/* @__PURE__ */s("span",{children:"Seleccionar"})]})]})]})]})}),$&&/* @__PURE__ */s(Te,{isOpen:x,src:g,alt:y.name,title:y.name,subtitle:`${y.size} • ${y.type.split("/")[1]?.toUpperCase()||"IMAGE"}`,onClose:()=>k(!1)})]})}const Qe={image:["image/jpeg","image/png","image/webp","image/svg+xml"],video:["image/gif","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","application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation"],audio:["audio/mpeg","audio/wav","audio/ogg","audio/webm"]},Xe={image:"JPG, PNG, SVG, WebP, GIF",video:"GIF, MP4, WebM, MOV, AVI",document:"PDF, DOC, DOCX, XLS, XLSX, TXT, PPT, PPTX",audio:"MP3, WAV, OGG"},Ye=["image","video","document","audio"];function Je({file:e,setFile:n,previewUrl:l,setPreviewUrl:r,fileInputRef:a,onSelect:o,disabled:u,allowedCategories:d=null,resolvedAccept:b=null,selectedFolder:m=null,onFolderChange:h=null,folderConfig:p=null}){const[f,v]=t(!1),{acceptAttribute:y,allowedMimeTypes:w,formatLabels:x,categories:k}=i(()=>{if(b&&!b.isAllTypes)return{acceptAttribute:b.acceptString,allowedMimeTypes:new Set(b.mimeTypes),formatLabels:g(b),categories:b.categories.length>0?b.categories:Ye};const e=null===d?Ye:d,t=[],n=[];return e.forEach(e=>{Qe[e]&&(t.push(...Qe[e]),Xe[e]&&n.push(Xe[e]))}),{acceptAttribute:t.join(","),allowedMimeTypes:new Set(t),formatLabels:n.join(", "),categories:e}},[d,b]),C=b&&!b.isAllTypes?b.includesImages&&1===b.categories.length&&"image"===b.categories[0]:1===k.length&&"image"===k[0],N=e=>{if(n(e),e){const t=URL.createObjectURL(e);r(t)}else r(null)};/* @__PURE__ */
|
|
235
236
|
return c("div",{className:"lb:flex lb:flex-col lb:items-center lb:gap-6","aria-label":C?"Subir imagen desde dispositivo":"Subir archivo desde dispositivo",children:[
|
|
236
237
|
/* @__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 "+(f?"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||v(!0)},onDragLeave:e=>{e.preventDefault(),e.stopPropagation(),e.currentTarget.contains(e.relatedTarget)||v(!1)},onDrop:e=>{if(e.preventDefault(),e.stopPropagation(),v(!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(b&&!b.isAllTypes)return function(e,t){if(!t||t.isAllTypes)return!0;if(!e)return!1;if(t.mimeTypes.includes(e))return!0;for(const n of t.categories)if(e.startsWith(n+"/"))return!0;return!1}(e.type,b);if(w.has(e.type))return!0;for(const t of k)if("image"===t&&e.type.startsWith("image/")||"video"===t&&e.type.startsWith("video/")||"audio"===t&&e.type.startsWith("audio/"))return!0;return!1})(e)&&N(e)}},children:[
|
|
237
238
|
/* @__PURE__ */s("span",{className:"icon icon-upload icon--lg lb:mb-2","aria-hidden":"true"}),
|
|
238
239
|
/* @__PURE__ */s("span",{className:"lb:font-medium lb:text-brand-blue-1000 lb:mb-1",children:C?"Haz clic o arrastra una imagen aqui":"Haz clic o arrastra un archivo aqui"}),
|
|
239
240
|
/* @__PURE__ */c("span",{className:"lb:text-sm lb:text-neutral-700",children:["Formatos permitidos: ",
|
|
240
241
|
/* @__PURE__ */s("span",{className:"lb:truncate lb:wrap-",children:x})]}),
|
|
241
|
-
/* @__PURE__ */s("input",{id:"file-input",ref:a,type:"file",accept:y,onChange:e=>{const t=e.target.files[0];N(t)},disabled:u,className:"lb:sr-only","aria-label":C?"Seleccionar imagen":"Seleccionar archivo"})]}),e&&/* @__PURE__ */s(
|
|
242
|
+
/* @__PURE__ */s("input",{id:"file-input",ref:a,type:"file",accept:y,onChange:e=>{const t=e.target.files[0];N(t)},disabled:u,className:"lb:sr-only","aria-label":C?"Seleccionar imagen":"Seleccionar archivo"})]}),e&&/* @__PURE__ */s(Ge,{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:m,onFolderChange:h,folderConfig:p})]})}const Ze="/api";const et=/* @__PURE__ */new Map;function tt(e=!1){const[l,r]=t([]),[a,i]=t(!0),[o,s]=t(null);n(()=>{const t=`ai-services-${e}`,n=et.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 le({endpoint:"/ai/services",prod:e,basePath:Ze})}(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),et.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:()=>{et.delete(`ai-services-${e}`)}}}const nt=/* @__PURE__ */new Map;function lt(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=nt.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),le({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),nt.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 rt({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:[
|
|
242
243
|
/* @__PURE__ */s("span",{className:"icon icon-spinner lb:p-4 lb:animate-spin"}),
|
|
243
|
-
/* @__PURE__ */s("p",{className:"lb:text-brand-blue-1000 lb:font-medium lb:text-lg",children:t})]})}):null}function
|
|
244
|
+
/* @__PURE__ */s("p",{className:"lb:text-brand-blue-1000 lb:font-medium lb:text-lg",children:t})]})}):null}function at({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:""}),[v,y]=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:[
|
|
244
245
|
/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:justify-between lb:mb-4 lb:px-1",children:[
|
|
245
246
|
/* @__PURE__ */s("h3",{className:"lb:text-sm lb:font-medium lb:text-gray-700",children:"Vista previa de imagen"}),
|
|
246
247
|
/* @__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(Oe,{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})}),
|
|
@@ -269,9 +270,9 @@ return c("div",{className:"lb:flex lb:flex-col lb:items-center lb:gap-6","aria-l
|
|
|
269
270
|
/* @__PURE__ */c("button",{type:"button",onClick:()=>{const e=k.trim();if(!e)return void x("El nombre no puede estar vacío");const t=B(e);t.valid?(x(!1),i&&i(f.name)):x(t.error)},disabled:u,className:"lb:flex-1 lb:md:flex-none lb:flex lb:items-center lb:justify-center lb:gap-2 lb:px-4 lb:py-2.5 lb:bg-brand-blue-800 lb:border lb:border-brand-blue-800 lb:text-white lb:rounded-lg lb:hover:bg-brand-blue-1000 lb:cursor-pointer lb:hover:border-brand-blue-1000 lb:transition-colors lb:disabled:opacity-50 lb:disabled:cursor-not-allowed lb:text-sm lb:font-medium lb:shadow-sm","aria-label":"Seleccionar imagen para recortar",children:[
|
|
270
271
|
/* @__PURE__ */s("span",{className:"icon icon-tick-white icon--sm"}),
|
|
271
272
|
/* @__PURE__ */s("span",{children:"Seleccionar"})]})]})]}),
|
|
272
|
-
/* @__PURE__ */s(Te,{isOpen:v,src:h,alt:f.name,title:f.name,subtitle:`${f.size} • ${f.type.split("/")[1]?.toUpperCase()||"IMAGE"}`,onClose:()=>y(!1)})]}):null}function
|
|
273
|
+
/* @__PURE__ */s(Te,{isOpen:v,src:h,alt:f.name,title:f.name,subtitle:`${f.size} • ${f.type.split("/")[1]?.toUpperCase()||"IMAGE"}`,onClose:()=>y(!1)})]}):null}function it({prod:n,disabled:l,onSelect:r,selectedFolder:a,onFolderChange:i,folderConfig:o}){const d=tt(n),b=lt(n),[m,h]=t(""),[p,f]=t(""),[g,v]=t({}),[y,w]=t(!1),[x,k]=t(null),[C,N]=t(null),[S,E]=t(null),[$,_]=t(!0),[T,z]=t(!1),[L,A]=t(null),[M,P]=t(null),[I,D]=t(!1),O=e.useRef(null),R=e.useRef(0);e.useEffect(()=>{if(!d.loading&&1===d.services.length){const e=d.services[0];f(e.slug),_(!1),b.fetchParams(e.slug,!0)}},[d.loading,d.services]),e.useEffect(()=>{if(!p)return;const e=b.params?.[p]?.parameters;if(e){const t=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default??""]));t.service=p,v(t)}},[p,b.params]);const j=e.useMemo(()=>{const e=d.services.find(e=>e.slug===p);if(e?.supportsImageInput)return!0;const t=b.params?.[p]?.parameters;return!!t&&Object.entries(t).some(([e,t])=>"image"===t.type||"file"===t.type||"image_data"===e||"image"===e||"reference_image"===e)},[p,d.services,b.params]),F=e=>{e&&(["image/jpeg","image/png","image/webp"].includes(e.type)?e.size>4194304?k("La imagen de referencia no puede superar los 4MB."):(A(e),P(URL.createObjectURL(e)),k(null)):k("Formato no soportado. Usa JPG, PNG o WebP."))},U=e=>{F(e.target.files?.[0])},B=e=>{e.preventDefault(),e.stopPropagation(),R.current++,D(!0)},W=e=>{e.preventDefault(),e.stopPropagation(),R.current--,0===R.current&&D(!1)},q=e=>{e.preventDefault(),e.stopPropagation()},V=e=>{e.preventDefault(),e.stopPropagation(),R.current=0,D(!1);const t=e.dataTransfer?.files?.[0];F(t)},H=()=>{A(null),M&&URL.revokeObjectURL(M),P(null),O.current&&(O.current.value="")};e.useEffect(()=>()=>{M&&URL.revokeObjectURL(M)},[M]);const K=e=>{const{name:t,value:n}=e.target;v(e=>({...e,[t]:n}))},G=async(e,t=!1)=>{e.preventDefault(),w(!0),k(null),N(null);try{t?g.prompt=m:h(g.prompt||"");let e={...g};L&&(e.image=await(l=L,new Promise((e,t)=>{const n=new FileReader;n.onload=()=>e(n.result),n.onerror=t,n.readAsDataURL(l)})));const a=await function(e,t=!1){return le({endpoint:"/ai/generate",method:"POST",body:e,prod:t,basePath:Ze})}(e,n);let i=null;if(a?.data?.images&&Array.isArray(a.data.images)&&a.data.images.length>0?i=a.data.images[0]:a?.result?.images&&Array.isArray(a.result.images)&&a.result.images.length>0?i=a.result.images[0]:Array.isArray(a)&&a.length>0?i=a[0]:"string"==typeof a&&(i=a),!i)throw new Error("No se pudo extraer la imagen de la respuesta");if(i.startsWith("http"))try{const e=`${window.limboCore?.config?.getGlobal()?.prod?"https://limbo.lefebvre.es":"https://led-dev-limbo-dev.eu.els.local"}/api/atenea/proxy?url=${encodeURIComponent(i)}`,t=await fetch(e,{credentials:"include",headers:{Authorization:`Bearer ${window.limboCore?.apiClient?.token||""}`}});if(!t.ok)throw new Error(`Failed to download image: ${t.status}`);const n=await t.blob(),l=new File([n],"ai-image.webp",{type:n.type||"image/webp"});E(l)}catch(r){throw new Error(`Error downloading image via proxy: ${r.message}`)}else{const e=i.replace(/^data:image\/\w+;base64,/,""),t=atob(e),n=new Array(t.length);for(let a=0;a<t.length;a++)n[a]=t.charCodeAt(a);const l=new Uint8Array(n),r=new File([l],"ai-image.webp",{type:"image/webp"});E(r)}N(a?.data?.images||a?.result?.images||null)}catch(a){k(a.message||"Error al generar la imagen")}finally{w(!1)}var l};return d.loading?/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:justify-center lb:py-8",children:[
|
|
273
274
|
/* @__PURE__ */s("span",{className:"limbo-loader lb:mr-2"})," Cargando servicios IA..."]}):d.services.length?/* @__PURE__ */s("div",{className:"lb:flex lb:flex-col lb:mx-4 lb:pb-2",children:/* @__PURE__ */c(u,$?{children:[
|
|
274
|
-
/* @__PURE__ */s("h3",{id:"aiSelectDescription",className:"lb:text-2xl lb:font-semibold lb:text-brand-blue-1000 lb:mb-3",children:"Selecciona el modelo IA"}),d.error&&/* @__PURE__ */s(
|
|
275
|
+
/* @__PURE__ */s("h3",{id:"aiSelectDescription",className:"lb:text-2xl lb:font-semibold lb:text-brand-blue-1000 lb:mb-3",children:"Selecciona el modelo IA"}),d.error&&/* @__PURE__ */s(We,{variant:"danger",children:d.error}),
|
|
275
276
|
/* @__PURE__ */s("div",{className:"lb:flex lb:flex-row lb:flex-wrap lb:justify-around lb:items-stretch lb:justify-items-stretch lb:content-stretch lb:gap-3 lb:w-full lb:max-w-7xl",children:d.services.map(e=>/* @__PURE__ */c("button",{type:"button",onClick:()=>{f(e.slug),_(!1),v({}),N(null),k(null),E(null),b.fetchParams(e.slug,!0)},disabled:d.loading||l,className:`lb:group lb:relative lb:p-4 lb:rounded-lg lb:border-2 lb:transition-all lb:duration-200 lb:overflow-hidden lb:flex lb:flex-col lb:items-center lb:justify-center lb:min-h-30 lb:grow basis-sm lb:min-w-70 lb:border-gray-200 lb:hover:border-brand-blue-800 lb:hover:shadow-md lb:hover:text-black lb:lg:w-min ${d.loading||l?"lb:opacity-50 lb:cursor-not-allowed":"lb:cursor-pointer"} `,style:{position:"relative"},children:[e.image&&/* @__PURE__ */s("div",{className:"lb:absolute lb:inset-0 lb:bg-cover lb:bg-center lb:transition-opacity lb:duration-200 lb:group-hover:opacity-35",style:{backgroundImage:`url(${e.image})`,opacity:.2}}),
|
|
276
277
|
/* @__PURE__ */c("div",{className:"lb:relative lb:z-10 lb:flex lb:flex-col lb:items-center lb:justify-center lb:gap-2 lb:text-center",children:[
|
|
277
278
|
/* @__PURE__ */s("span",{className:"lb:text-base lb:font-semibold lb:text-neutral-black-000",children:e.label}),e.description&&/* @__PURE__ */s("span",{className:"lb:text-sm lb:text-gray-950 lb:line-clamp-2 lb:drop-shadow lb:drop-shadow-neutral-white-000",children:e.description})]}),e.costInfo&&/* @__PURE__ */s("span",{className:"lb:absolute lb:top-0 lb:left-1 lb:inline-flex lb:items-center lb:gap-1 lb:py-0 lb:px-1 lb:mt-1 lb:text-xs lb:font-medium lb:text-warning-1000 lb:rounded-md lb:group-hover:bg-white/90",style:{zoom:"82%"},children:e.costInfo})]},e.slug))})]}:{children:[
|
|
@@ -279,13 +280,13 @@ return c("div",{className:"lb:flex lb:flex-col lb:items-center lb:gap-6","aria-l
|
|
|
279
280
|
/* @__PURE__ */s("h3",{className:"lb:text-2xl lb:font-semibold lb:text-brand-blue-1000",children:d.services.find(e=>e.slug===p)?.label||"Generación IA"}),d.services.find(e=>e.slug===p)?.costInfo&&/* @__PURE__ */c("div",{title:"Coste estimado por imagen que le cuesta a la empresa, este coste depende de la calidad de la imagen generada y puede variar según el proveedor IA, ten en cuenta este coste para hacer un uso más responsable del servicio IA",className:"lb:flex lb:items-center lb:gap-1","aria-description":"Coste estimado por imagen que le cuesta a la empresa, este coste depende de la calidad de la imagen generada y puede variar según el proveedor IA, ten en cuenta este coste para hacer un uso más responsable del servicio IA",children:[
|
|
280
281
|
/* @__PURE__ */c("span",{className:"lb:inline-flex lb:items-center lb:gap-1 lb:px-2 lb:py-0.5 lb:text-xs lb:font-medium lb:text-warning-1000 lb:bg-yellow-200/60 lb:rounded-full lb:border lb:border-warning-1000 lb:select-none",children:[
|
|
281
282
|
/* @__PURE__ */s("span",{className:"icon icon-euro-blue icon--2sm icon--warning",style:{filter:"var(--limbo-icon-warning-dark)"}}),"Coste:"," ",d.services.find(e=>e.slug===p)?.costInfo]}),
|
|
282
|
-
/* @__PURE__ */s("span",{className:"icon icon-info lb:cursor-help"})]})]}),b.loading&&/* @__PURE__ */s("div",{children:"Cargando parámetros..."}),b.error&&/* @__PURE__ */s(
|
|
283
|
+
/* @__PURE__ */s("span",{className:"icon icon-info lb:cursor-help"})]})]}),b.loading&&/* @__PURE__ */s("div",{children:"Cargando parámetros..."}),b.error&&/* @__PURE__ */s(We,{variant:"danger",children:b.error}),p&&(()=>{const e=b.params?.[p]?.parameters;if(!e)return null;const t=Object.entries(e).filter(([e,t])=>!t.hidden&&"image"!==t.type&&"file"!==t.type),n=t.filter(([e])=>e.toLowerCase().includes("prompt")||e.toLowerCase().includes("query")),r=t.filter(([e])=>!e.toLowerCase().includes("prompt")&&!e.toLowerCase().includes("query")),a=(e,t)=>{let n=t.placeholder||"";n||(n="integer"===t.type?t.minValue&&t.maxValue?`Entre ${t.minValue} y ${t.maxValue}`:t.minValue?`Mínimo ${t.minValue}`:t.maxValue?`Máximo ${t.maxValue}`:"Introduce un número":e.toLowerCase().includes("prompt")?"Describe la imagen que deseas generar...":e.toLowerCase().includes("negative")?"Elementos a evitar en la imagen...":`Introduce ${(t.label||e).toLowerCase()}`);const r=e.toLowerCase().includes("prompt")||e.toLowerCase().includes("query");/* @__PURE__ */
|
|
283
284
|
return c("div",{className:"lb:flex lb:flex-col lb:gap-1",children:[
|
|
284
285
|
/* @__PURE__ */c("label",{htmlFor:`ai-${e}`,className:"lb:text-xs lb:font-medium lb:text-brand-blue-1000",children:[t.label||e,t.required&&/* @__PURE__ */s("span",{className:"lb:text-red-1000 lb:ml-1",children:"*"})]}),t.options?/* @__PURE__ */s("select",{id:`ai-${e}`,name:e,value:g[e]??"",onChange:K,className:"limbo-input",disabled:l,title:t.label||e,children:t.options.map(e=>/* @__PURE__ */s("option",{value:e,children:e},e))}):r?/* @__PURE__ */s("textarea",{id:`ai-${e}`,name:e,value:g[e]??"",onChange:K,className:"limbo-input lb:resize-none lb:overflow-y-auto",disabled:l,required:t.required,placeholder:n,title:t.label||e,rows:3,style:{maxHeight:"9rem",minHeight:"3rem"},onInput:e=>{e.target.style.height="auto";const t=Math.min(e.target.scrollHeight,144);e.target.style.height=`${t}px`}}):/* @__PURE__ */s("input",{id:`ai-${e}`,type:"integer"===t.type?"number":"text",name:e,value:g[e]??"",onChange:K,className:"limbo-input",disabled:l,required:t.required,min:t.minValue,max:t.maxValue,placeholder:n,title:t.label||e})]},e)};/* @__PURE__ */
|
|
285
286
|
return c("div",{className:"lb:h-fit lb:w-full",children:[d.services.length>1&&/* @__PURE__ */c("button",{type:"button",onClick:()=>{_(!0),f(""),v({}),N(null),k(null),E(null),H()},className:"lb:flex lb:cursor-pointer lb:items-center lb:gap-2 lb:text-brand-blue-800 lb:hover:text-brand-blue-1000 lb:mb-4 lb:font-medium",children:[
|
|
286
287
|
/* @__PURE__ */s("span",{className:"icon icon-arrow-left"}),"Volver al menú de servicios"]}),
|
|
287
288
|
/* @__PURE__ */c("div",{className:"lb:relative",children:[
|
|
288
|
-
/* @__PURE__ */c("form",{onSubmit:G,"data-type":"ai",className:"lb:flex lb:flex-col lb:gap-3 lb:mt-4 lb:border-t lb:pt-4 lb:border-brand-blue-200","aria-label":"Formulario generación IA",children:[x&&/* @__PURE__ */s(
|
|
289
|
+
/* @__PURE__ */c("form",{onSubmit:G,"data-type":"ai",className:"lb:flex lb:flex-col lb:gap-3 lb:mt-4 lb:border-t lb:pt-4 lb:border-brand-blue-200","aria-label":"Formulario generación IA",children:[x&&/* @__PURE__ */s(We,{variant:"danger",className:"lb:mb-2",children:x}),
|
|
289
290
|
/* @__PURE__ */s("div",{className:"lb:flex lb:flex-col lb:gap-3",children:n.map(([e,t])=>a(e,t))}),j&&/* @__PURE__ */c("div",{className:"lb:flex lb:flex-col lb:gap-2 lb:mt-1",children:[
|
|
290
291
|
/* @__PURE__ */c("label",{className:"lb:text-xs lb:font-medium lb:text-brand-blue-1000",children:["Imagen de referencia",
|
|
291
292
|
/* @__PURE__ */s("span",{className:"lb:text-neutral-gray-500 lb:ml-1 lb:font-normal",children:"(opcional)"})]}),L?/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-3 lb:p-2 lb:bg-neutral-gray-50 lb:border lb:border-neutral-gray-200 lb:rounded-lg",children:[
|
|
@@ -304,21 +305,21 @@ return c("div",{className:"lb:h-fit lb:w-full",children:[d.services.length>1&&/*
|
|
|
304
305
|
/* @__PURE__ */c("button",{type:"button",onClick:()=>z(!T),className:"lb:flex lb:items-center lb:gap-2 lb:text-sm lb:font-medium lb:text-brand-blue-800 lb:hover:text-brand-blue-1000 lb:mb-3 lb:transition-colors",children:[
|
|
305
306
|
/* @__PURE__ */s("svg",{className:"lb:w-4 lb:h-4 lb:transition-transform "+(T?"lb:rotate-90":""),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),"Opciones avanzadas",!T&&/* @__PURE__ */c("span",{className:"lb:text-xs lb:text-gray-500",children:["(",r.length," opciones)"]})]}),T&&/* @__PURE__ */s("div",{className:"lb:grid lb:grid-cols-2 lb:lg:grid-cols-3 lb:xl:grid-cols-4 lb:gap-3 lb:animate-fadeIn",children:r.map(([e,t])=>a(e,t))})]}),
|
|
306
307
|
/* @__PURE__ */s("button",{type:"submit",disabled:y||l,title:y?"Generando imagen...":S?"Generar otra imagen":"Generar imagen",className:"limbo-btn lb:w-full lb:mt-2 "+(y?"lb:cursor-not-allowed limbo-btn-disabled":"limbo-btn-primary"),style:{minHeight:44},children:y?"Generando imagen...":S?"Generar otra imagen":"Generar imagen"})]}),
|
|
307
|
-
/* @__PURE__ */s(
|
|
308
|
+
/* @__PURE__ */s(rt,{show:y,message:"Generando imagen con IA..."})]})]})})(),S&&/* @__PURE__ */s("div",{className:"lb:mt-6 lb:md:w-full lb:mx-auto",children:/* @__PURE__ */s(at,{image:S,onDiscard:()=>{E(null),N(null),k(null)},onRetry:e=>G(e,!0),onDownload:()=>{},onSelect:e=>{if(r){const t=S||C;if(e&&t&&e!==t.name){const n=new File([t],e,{type:t.type});r(n)}else r(t)}},showRetry:!0,disabled:y||l,selectedFolder:a,onFolderChange:i,folderConfig:o})})]})}):/* @__PURE__ */s(We,{variant:"warning",children:"No hay servicios IA disponibles."})}const ot="/api";const st=/* @__PURE__ */new Map;function ct(e=!1){const[l,r]=t([]),[a,i]=t(!0),[o,s]=t(null);n(()=>{const t=`stock-services-${e}`,n=st.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 le({endpoint:"/stock/services",prod:e,basePath:ot})}(e);if(!a)return;if(204===n?.httpCode||null===n?.data)return r([]),s("No hay servicios de stock disponibles en este momento"),void st.set(t,{data:[],timestamp:l});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})):Object.entries(i).map(([e,t])=>({label:e,slug:t,type:"stock_image",description:null,image:null}));r(o),st.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:()=>{st.delete(`stock-services-${e}`)}}}function ut({isOpen:e,image:l,onSelect:r,onCancel:a}){const[i,o]=t(null),[d,b]=t(!1),[m,h]=t(!1),[p,f]=t(!1);n(()=>{e&&l&&(o(l.previewUrl),b(!1),h(!1),f(!1))},[e,l]);const g=/* @__PURE__ */c("div",{className:"lb:flex lb:gap-2 lb:ml-4 lb:shrink-0",children:[
|
|
308
309
|
/* @__PURE__ */s("button",{type:"button",onClick:a,className:"lb:px-4 lb:py-2 lb:text-sm lb:font-medium lb:text-white lb:border lb:border-white/30 lb:rounded-md lb:hover:bg-white/10 lb:transition-colors lb:cursor-pointer",children:"Cancelar"}),
|
|
309
310
|
/* @__PURE__ */s("button",{type:"button",onClick:r,className:"lb:px-4 lb:py-2 lb:text-sm lb:font-medium lb:bg-brand-blue-800 lb:text-white lb:rounded-md lb:hover:bg-brand-blue-1000 lb:transition-colors lb:cursor-pointer",children:"Seleccionar"})]});/* @__PURE__ */
|
|
310
311
|
return s(ge,{isOpen:e,onClose:a,title:l?.title||"Previsualizar imagen",ariaLabel:"Previsualización de imagen externa",headerActions:g,children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center lb:w-full lb:h-full lb:p-4",children:p?/* @__PURE__ */c("div",{className:"lb:text-white/70 lb:text-sm lb:text-center",children:[
|
|
311
312
|
/* @__PURE__ */s("p",{children:"No se pudo cargar la imagen."}),
|
|
312
313
|
/* @__PURE__ */s("p",{className:"lb:text-xs lb:mt-1 lb:text-white/50",children:"Puedes seleccionarla igualmente para continuar."})]}):/* @__PURE__ */c(u,{children:[!m&&/* @__PURE__ */s("div",{className:"lb:absolute lb:inset-0 lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"limbo-loader"})}),
|
|
313
|
-
/* @__PURE__ */s("img",{src:i,alt:l?.title||"Imagen",onLoad:()=>h(!0),onError:()=>{!d&&l?.proxyUrl&&l.proxyUrl!==i?(b(!0),o(l.proxyUrl)):f(!0)},className:"lb:max-w-full lb:object-contain lb:rounded lb:transition-opacity lb:duration-300 "+(m?"lb:opacity-100":"lb:opacity-0"),style:{maxHeight:"calc(100vh - 130px)"}},i)]})})})}function
|
|
314
|
+
/* @__PURE__ */s("img",{src:i,alt:l?.title||"Imagen",onLoad:()=>h(!0),onError:()=>{!d&&l?.proxyUrl&&l.proxyUrl!==i?(b(!0),o(l.proxyUrl)):f(!0)},className:"lb:max-w-full lb:object-contain lb:rounded lb:transition-opacity lb:duration-300 "+(m?"lb:opacity-100":"lb:opacity-0"),style:{maxHeight:"calc(100vh - 130px)"}},i)]})})})}function dt({src:t,fallbackSrc:n,alt:l}){const[r,a]=e.useState(t),[i,o]=e.useState(!1),[u,d]=e.useState(!1);e.useEffect(()=>{a(t),o(!1),d(!1)},[t]);/* @__PURE__ */
|
|
314
315
|
return c("div",{className:"lb:relative lb:w-full lb:h-full",children:[!u&&/* @__PURE__ */s("div",{className:"lb:absolute lb:inset-0 lb:bg-linear-to-r lb:from-gray-200 lb:via-gray-100 lb:to-gray-200 lb:animate-pulse"}),
|
|
315
|
-
/* @__PURE__ */s("img",{src:r,alt:l,onLoad:()=>d(!0),onError:()=>{!i&&n&&n!==r&&(o(!0),a(n))},className:"lb:object-cover lb:w-full lb:h-full lb:transition-opacity lb:duration-300 "+(u?"lb:opacity-100":"lb:opacity-0"),loading:"lazy"})]})}function
|
|
316
|
+
/* @__PURE__ */s("img",{src:r,alt:l,onLoad:()=>d(!0),onError:()=>{!i&&n&&n!==r&&(o(!0),a(n))},className:"lb:object-cover lb:w-full lb:h-full lb:transition-opacity lb:duration-300 "+(u?"lb:opacity-100":"lb:opacity-0"),loading:"lazy"})]})}function bt({prod:n,disabled:l,onSelect:r,selectedFolder:a,onFolderChange:i,folderConfig:o}){const d=e.useRef(null),b=ct(n),m=(e,t)=>{try{const n=sessionStorage.getItem(`limbo_stock_${e}`);return n?JSON.parse(n):t}catch{return t}},[h,p]=t(()=>m("selectedService","")),[f,g]=t(()=>m("dynamicForm",{})),[v,y]=t(()=>m("stockImages",[])),[w,x]=t(()=>m("currentPage",1)),[k,C]=t(()=>m("paginationInfo",null)),[N,S]=t(null),E=lt(n),[$,_]=t(!1),[T,z]=t(null),[L,A]=t(null),[M,P]=t(!0),[I,D]=t(!1),[O,R]=t(null),[j,F]=t(null);e.useEffect(()=>{sessionStorage.setItem("limbo_stock_selectedService",JSON.stringify(h))},[h]),e.useEffect(()=>{sessionStorage.setItem("limbo_stock_dynamicForm",JSON.stringify(f))},[f]),e.useEffect(()=>{sessionStorage.setItem("limbo_stock_stockImages",JSON.stringify(v))},[v]),e.useEffect(()=>{sessionStorage.setItem("limbo_stock_currentPage",JSON.stringify(w))},[w]),e.useEffect(()=>{sessionStorage.setItem("limbo_stock_paginationInfo",JSON.stringify(k))},[k]),e.useEffect(()=>{if(!b.loading&&1===b.services.length){const e=b.services[0];p(e.slug),P(!1),E.fetchParams(e.slug,!0)}},[b.loading,b.services]),e.useEffect(()=>{if(!h)return;const e=E.params?.[h]?.parameters;if(e){const t=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default??""]));t.service=h,g(t)}},[h,E.params]);const U=e=>{const{name:t,value:n}=e.target;g(e=>({...e,[t]:n}))},B=async(e=1)=>{_(!0),z(null),1===e&&y([]);try{let t;if(1===e){const n=E.params?.[h]?.parameters,l={...f};Object.entries(n||{}).forEach(([e,t])=>{e in l||(l[e]=t.default??"")}),l.per_page=parseInt(l.per_page),l.service=h,l.page=e,t=l,d.current={...l}}else t={...d.current,page:e};const l=await function(e,t=!1){return le({endpoint:"/stock/search",method:"POST",body:e,prod:t,basePath:ot})}(t,n),r=l?.data?.images||[];let a=l?.data?.pagination||null,i=null;a&&(i={total:a.total_count??a.total??r.length,per_page:a.per_page??(Array.isArray(r)?r.length:0),current_page:a.page??a.current_page??e}),y(W(Array.isArray(r)?r:[])),C(i),x(i?.current_page||e)}catch(t){z(t.message||"Error al buscar imágenes")}finally{_(!1)}},W=e=>{const t=/* @__PURE__ */new Set,n=[];return(e||[]).forEach((e,l)=>{const r=e.url||e.preview_url||e.full||e.preview;r&&!t.has(r)&&(t.add(r),n.push({...e,preview:e.preview_url||e.preview||e.url||e.full,full:e.url||e.full||e.preview_url,id:e.id||l,title:e.title||e.filename||`Imagen ${l+1}`,source:e.service||h,sourceTitle:b.services.find(e=>e.slug===h)?.label||h}))}),n},q=async e=>{e.preventDefault();const t=f.query||f.search||f.term||"";t.trim().length<5?z("La búsqueda debe tener al menos 5 caracteres"):(S(t),await B(1))},V=e=>{e<1||B(e)},H=async e=>{A(e.id),z(null);try{const t={service:h,image_id:e.id},l=await function(e,t=!1){return le({endpoint:"/stock/download",method:"POST",body:e,prod:t,basePath:ot})}(t,n),r=l?.result?.url||l?.result?.download_url||l?.data?.images?.url||l?.data?.url||l?.images?.url||l?.url;if(!r)throw console.error("Download response structure:",l),new Error("No se pudo obtener la URL de descarga");{const t=`${ee({prod:n})}/api/atenea/proxy?url=${encodeURIComponent(r)}`,a=await fetch(t,{credentials:"include",headers:{Authorization:`Bearer ${ne().token||""}`}});if(!a.ok)throw new Error(`Error al descargar imagen: ${a.status}`);const i=await a.blob(),o=l?.result?.filename||l?.data?.images?.filename||l?.data?.filename||`stock-${e.id}.jpg`,s=new File([i],o,{type:i.type||"image/jpeg"});R(s)}}catch(t){z(t.message||"No se pudo recuperar la imagen seleccionada")}finally{A(null)}};return b.loading?/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:justify-center lb:py-8",children:[
|
|
316
317
|
/* @__PURE__ */s("span",{className:"limbo-loader lb:mr-2"})," Cargando servicios de Stock..."]}):b.services.length?/* @__PURE__ */s("div",{className:"lb:flex lb:flex-col lb:mx-4 lb:pb-2",children:/* @__PURE__ */c(u,M?{children:[
|
|
317
|
-
/* @__PURE__ */s("h3",{className:"lb:text-2xl lb:font-semibold lb:text-brand-blue-1000 lb:mb-3",children:"Selecciona el servicio de Stock"}),b.error&&/* @__PURE__ */s(
|
|
318
|
+
/* @__PURE__ */s("h3",{className:"lb:text-2xl lb:font-semibold lb:text-brand-blue-1000 lb:mb-3",children:"Selecciona el servicio de Stock"}),b.error&&/* @__PURE__ */s(We,{variant:"danger",children:b.error}),
|
|
318
319
|
/* @__PURE__ */s("div",{className:"lb:grid lb:grid-cols-2 lb:md:grid-cols-3 lb:gap-3",children:b.services.map(e=>/* @__PURE__ */c("button",{type:"button",onClick:()=>{p(e.slug),P(!1),g({}),y([]),x(1),C(null),z(null),E.fetchParams(e.slug,!0)},disabled:b.loading||l,className:`lb:group lb:relative lb:p-4 lb:rounded-lg lb:border-2 lb:transition-all lb:duration-200 lb:overflow-hidden lb:flex lb:flex-col lb:items-center lb:justify-center lb:min-h-30 lb:border-gray-200 lb:hover:border-brand-blue-300 lb:hover:shadow-md lb:lg:w-min ${b.loading||l?"lb:opacity-50 lb:cursor-not-allowed":"lb:cursor-pointer"} `,style:{position:"relative"},children:[e.image&&/* @__PURE__ */s("div",{className:"lb:absolute lb:inset-0 lb:bg-cover lb:bg-center lb:transition-opacity lb:duration-200 lb:group-hover:opacity-35",style:{backgroundImage:`url(${e.image})`,opacity:.2}}),
|
|
319
320
|
/* @__PURE__ */c("div",{className:"lb:relative lb:z-10 lb:flex lb:flex-col lb:items-center lb:justify-center lb:gap-2 lb:text-center",children:[
|
|
320
321
|
/* @__PURE__ */s("span",{className:"lb:text-base lb:font-semibold lb:text-neutral-black-000",children:e.label}),e.description&&/* @__PURE__ */s("span",{className:"lb:text-sm lb:text-gray-950 lb:line-clamp-2 lb:drop-shadow lb:drop-shadow-neutral-white-000",children:e.description})]})]},e.slug))})]}:{children:[
|
|
321
|
-
/* @__PURE__ */s("h3",{className:"lb:text-2xl lb:font-semibold lb:text-brand-blue-1000",children:b.services.find(e=>e.slug===h)?.label||"Búsqueda Stock"}),E.loading&&/* @__PURE__ */s("div",{children:"Cargando parámetros..."}),E.error&&/* @__PURE__ */s(
|
|
322
|
+
/* @__PURE__ */s("h3",{className:"lb:text-2xl lb:font-semibold lb:text-brand-blue-1000",children:b.services.find(e=>e.slug===h)?.label||"Búsqueda Stock"}),E.loading&&/* @__PURE__ */s("div",{children:"Cargando parámetros..."}),E.error&&/* @__PURE__ */s(We,{variant:"danger",children:E.error}),h&&(()=>{const e=E.params?.[h]?.parameters;if(!e)return null;const t=Object.entries(e).filter(([,e])=>!e.hidden),n=t.filter(([e])=>e.toLowerCase().includes("query")||e.toLowerCase().includes("search")||e.toLowerCase().includes("term")),r=t.filter(([e])=>!e.toLowerCase().includes("query")&&!e.toLowerCase().includes("search")&&!e.toLowerCase().includes("term")),a=(e,t)=>{let n=t.placeholder||"";n||(n="integer"===t.type?t.minValue&&t.maxValue?`Entre ${t.minValue} y ${t.maxValue}`:t.minValue?`Mínimo ${t.minValue}`:t.maxValue?`Máximo ${t.maxValue}`:"Introduce un número":e.toLowerCase().includes("query")||e.toLowerCase().includes("search")||e.toLowerCase().includes("term")?"Buscar imágenes...":`Introduce ${(t.label||e).toLowerCase()}`);const r=e.toLowerCase().includes("query")||e.toLowerCase().includes("search")||e.toLowerCase().includes("term");/* @__PURE__ */
|
|
322
323
|
return c("div",{className:"lb:flex lb:flex-col lb:gap-1",children:[
|
|
323
324
|
/* @__PURE__ */c("label",{htmlFor:`stock-${e}`,className:"lb:text-xs lb:font-medium lb:text-brand-blue-1000",children:[t.label||e,t.required&&/* @__PURE__ */s("span",{className:"lb:text-red-1000 lb:ml-1",children:"*"})]}),t.options&&t.multiple?/* @__PURE__ */s("div",{className:"lb:flex lb:flex-wrap lb:gap-2 lb:min-h-[50px] lb:px-2 lb:justify-between lb:border-2 lb:border-gray-transparent-500 lb:rounded-lg",children:t.options.map(t=>/* @__PURE__ */c("label",{className:"lb:flex lb:items-center lb:gap-1",children:[
|
|
324
325
|
/* @__PURE__ */s("input",{type:"checkbox",name:`stock-${e}`,value:t,checked:Array.isArray(f[e])&&f[e].includes(t),onChange:()=>((e,t)=>{g(n=>{const l=Array.isArray(n[e])?n[e]:[];return l.includes(t)?{...n,[e]:l.filter(e=>e!==t)}:{...n,[e]:[...l,t]}})})(e,t),disabled:l}),
|
|
@@ -326,16 +327,16 @@ return c("div",{className:"lb:flex lb:flex-col lb:gap-1",children:[
|
|
|
326
327
|
return c("div",{children:[b.services.length>1&&/* @__PURE__ */c("button",{type:"button",onClick:()=>{P(!0),p(""),g({}),y([]),x(1),C(null),z(null)},className:"lb:flex lb:cursor-pointer lb:items-center lb:gap-2 lb:text-brand-blue-800 lb:hover:text-brand-blue-1000 lb:mb-4 lb:font-medium",children:[
|
|
327
328
|
/* @__PURE__ */s("span",{className:"icon icon-arrow-left"}),"Volver al menú de servicios"]}),
|
|
328
329
|
/* @__PURE__ */c("div",{className:"lb:relative",children:[
|
|
329
|
-
/* @__PURE__ */c("form",{onSubmit:q,"data-type":"stock",className:"lb:flex lb:flex-col lb:gap-3 lb:mt-4 lb:border-t-1 lb:pt-4 lb:border-brand-blue-200","aria-label":"Formulario búsqueda de imágenes de Stock",children:[T&&/* @__PURE__ */s(
|
|
330
|
+
/* @__PURE__ */c("form",{onSubmit:q,"data-type":"stock",className:"lb:flex lb:flex-col lb:gap-3 lb:mt-4 lb:border-t-1 lb:pt-4 lb:border-brand-blue-200","aria-label":"Formulario búsqueda de imágenes de Stock",children:[T&&/* @__PURE__ */s(We,{variant:"danger",className:"lb:mt-4",children:T}),
|
|
330
331
|
/* @__PURE__ */s("div",{className:"lb:flex lb:flex-col lb:gap-3",children:n.map(([e,t])=>a(e,t))}),r.length>0&&/* @__PURE__ */c("div",{className:"lb:border-t lb:border-gray-200 lb:pt-3",children:[
|
|
331
332
|
/* @__PURE__ */c("button",{type:"button",onClick:()=>D(!I),className:"lb:flex lb:items-center lb:gap-2 lb:text-sm lb:font-medium lb:text-brand-blue-800 lb:hover:text-brand-blue-1000 lb:mb-3 lb:transition-colors",children:[
|
|
332
333
|
/* @__PURE__ */s("svg",{className:"lb:w-4 lb:h-4 lb:transition-transform "+(I?"lb:rotate-90":""),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),"Opciones avanzadas",!I&&/* @__PURE__ */c("span",{className:"lb:text-xs lb:text-gray-500",children:["(",r.length," opciones)"]})]}),I&&/* @__PURE__ */s("div",{className:"lb:grid lb:grid-cols-1 lb:md:grid-cols-2 lb:gap-3 lb:animate-fadeIn",children:r.map(([e,t])=>a(e,t))})]}),
|
|
333
334
|
/* @__PURE__ */s("button",{type:"submit",disabled:$||l,className:"limbo-btn lb:w-full lb:mt-2 "+($?"lb:cursor-not-allowed limbo-btn-disabled":"limbo-btn-primary"),style:{minHeight:44},children:$?"Buscando...":"Buscar imágenes"})]}),
|
|
334
|
-
/* @__PURE__ */s(
|
|
335
|
+
/* @__PURE__ */s(rt,{show:$&&!v.length,message:"Buscando imágenes..."})]})]})})(),O&&/* @__PURE__ */s("div",{className:"lb:mt-6 lb:md:w-full lb:mx-auto",children:/* @__PURE__ */s(at,{image:O,onDiscard:()=>{R(null),z(null)},onDownload:()=>{},onSelect:e=>{if(r)if(e&&O&&e!==O.name){const t=new File([O],e,{type:O.type});r(t)}else r(O)},showRetry:!1,disabled:l,selectedFolder:a,onFolderChange:i,folderConfig:o})}),!O&&v.length>0&&/* @__PURE__ */c(u,{children:[
|
|
335
336
|
/* @__PURE__ */c("div",{className:"lb:mt-6 lb:grid lb:grid-cols-2 lb:md:grid-cols-3 lb:lg:grid-cols-4 lb:gap-1 lb:relative","aria-live":"polite",children:[
|
|
336
|
-
/* @__PURE__ */s(
|
|
337
|
+
/* @__PURE__ */s(rt,{show:$,message:"Cargando imágenes..."}),v.map((e,t)=>{const r=ee({prod:n}),a=e.preview||e.thumbnail||e.url,i=a?`${r}/api/atenea/proxy?url=${encodeURIComponent(a)}`:null;/* @__PURE__ */
|
|
337
338
|
return s("div",{className:"lb:border lb:border-brand-blue-200 lb:rounded-sm lb:overflow-hidden lb:bg-white lb:shadow-sm lb:hover:shadow-md lb:transition-all lb:duration-200 lb:cursor-pointer",title:"Ver imagen",onClick:()=>{L||$||l||F(e)},children:/* @__PURE__ */c("div",{className:"lb:relative lb:aspect-video lb:bg-neutral-100",children:[
|
|
338
|
-
/* @__PURE__ */s(
|
|
339
|
+
/* @__PURE__ */s(dt,{src:a,fallbackSrc:i,alt:e.title||`Resultado ${t+1}`}),L===e.id&&/* @__PURE__ */c("div",{className:"lb:absolute lb:inset-0 lb:bg-white/90 lb:flex lb:flex-col lb:items-center lb:justify-center lb:gap-2",children:[
|
|
339
340
|
/* @__PURE__ */c("div",{className:"lb:relative lb:w-10 lb:h-10",children:[
|
|
340
341
|
/* @__PURE__ */s("div",{className:"lb:absolute lb:inset-0 lb:border-4 lb:border-brand-blue-200 lb:rounded-full"}),
|
|
341
342
|
/* @__PURE__ */s("div",{className:"lb:absolute lb:inset-0 lb:border-4 lb:border-brand-blue-800 lb:rounded-full lb:border-t-transparent lb:animate-spin"})]}),
|
|
@@ -349,7 +350,7 @@ return s("div",{className:"lb:border lb:border-brand-blue-200 lb:rounded-sm lb:o
|
|
|
349
350
|
/* @__PURE__ */s("span",{className:"icon icon-search icon--lg lb:mb-2"}),
|
|
350
351
|
/* @__PURE__ */c("p",{children:['No se encontraron imágenes para "',f.query,'"']}),
|
|
351
352
|
/* @__PURE__ */s("p",{className:"lb:text-sm lb:mt-1",children:"Intenta con otros términos de búsqueda"})]}),j&&(()=>{const e=ee({prod:n}),t=j.preview||j.thumbnail||j.url,l=t?`${e}/api/atenea/proxy?url=${encodeURIComponent(t)}`:null;/* @__PURE__ */
|
|
352
|
-
return s(
|
|
353
|
+
return s(ut,{isOpen:!!j,image:{previewUrl:t,proxyUrl:l,title:j.title||j.filename||"Imagen"},onCancel:()=>F(null),onSelect:()=>{const e=j;F(null),H(e)}})})()]})}):/* @__PURE__ */s(We,{variant:"warning",children:"No hay servicios de Stock disponibles."})}const mt="/api";const ht=/* @__PURE__ */new Map;function pt(e=!1){const[l,r]=t([]),[a,i]=t(!0),[o,s]=t(null);n(()=>{const t=`portal-sources-${e}`,n=ht.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,t=!0){const n=new URLSearchParams;return n.set("active",t?"true":"false"),le({endpoint:`/external/portals?${n.toString()}`,method:"GET",prod:e,basePath:mt})}(e,!0);if(!a)return;let i=n?.data||[];Array.isArray(i)||(i=[]);const o=i.map(e=>({id:e.slug||e.id,numericId:e.id,name:e.name,title:e.name,slug:e.slug,url:e.website_url,image:e.logo_url,isActive:e.is_active}));r(o),ht.set(t,{data:o,timestamp:l})}catch(n){a&&s(n.message)}finally{a&&i(!1)}})(),()=>{a=!1}},[e]);return{sources:l,loading:a,error:o,invalidateCache:()=>{ht.delete(`portal-sources-${e}`)}}}function ft({isOpen:e=!1,video:n,onClose:r,onSelect:a=null}){const[o,d]=t(!1),b=i(()=>n?"youtube"===n.platform&&n.video_id?`https://www.youtube.com/embed/${n.video_id}?autoplay=1&rel=0`:"vimeo"===n.platform&&n.video_id?`https://player.vimeo.com/video/${n.video_id}?autoplay=1`:n.embed_url||null:null,[n]),m=i(()=>n&&(n.player_url||n.embed_url||n.post_url)||"",[n]),h=l(async()=>{if(m)try{await navigator.clipboard.writeText(m),d(!0),setTimeout(()=>d(!1),2e3)}catch{const e=document.createElement("textarea");e.value=m,e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e),d(!0),setTimeout(()=>d(!1),2e3)}},[m]),p=l(()=>{a&&n&&a(n)},[a,n]);if(!n)return null;const f=[n.portal_name,n.platform].filter(Boolean).join(" · "),g=a?/* @__PURE__ */c("button",{type:"button",onClick:p,className:"lb:flex lb:items-center lb:gap-2 lb:px-4 lb:py-1.5 lb:rounded-lg lb:bg-brand-blue-800 lb:hover:bg-brand-blue-900 lb:text-white lb:text-sm lb:font-medium lb:transition-colors","aria-label":"Seleccionar video",children:[
|
|
353
354
|
/* @__PURE__ */s("svg",{className:"lb:w-4 lb:h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),
|
|
354
355
|
/* @__PURE__ */s("span",{children:"Seleccionar"})]}):/* @__PURE__ */s("button",{type:"button",onClick:h,disabled:!m,className:"lb:flex lb:items-center lb:gap-2 lb:px-4 lb:py-1.5 lb:rounded-lg lb:text-sm lb:font-medium lb:transition-colors "+(o?"lb:bg-green-600 lb:text-white":"lb:bg-white/10 lb:hover:bg-white/20 lb:text-white"),"aria-label":"Copiar URL del video",children:/* @__PURE__ */c(u,o?{children:[
|
|
355
356
|
/* @__PURE__ */s("svg",{className:"lb:w-4 lb:h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),
|
|
@@ -364,13 +365,13 @@ return s(ge,{isOpen:e,onClose:r,title:n.title||"Video",subtitle:f,ariaLabel:"Vis
|
|
|
364
365
|
/* @__PURE__ */s("strong",{className:"lb:capitalize",children:n.platform||"plataforma externa"})]})]}),
|
|
365
366
|
/* @__PURE__ */s("div",{className:"lb:relative lb:w-full lb:aspect-video lb:bg-black lb:rounded-lg lb:overflow-hidden",children:b?/* @__PURE__ */s("iframe",{src:b,className:"lb:absolute lb:inset-0 lb:w-full lb:h-full",allow:"autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0,title:n.title||"Video"}):/* @__PURE__ */c("div",{className:"lb:absolute lb:inset-0 lb:flex lb:flex-col lb:items-center lb:justify-center lb:text-white lb:gap-3",children:[
|
|
366
367
|
/* @__PURE__ */s("svg",{className:"lb:w-16 lb:h-16 lb:text-gray-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"})}),
|
|
367
|
-
/* @__PURE__ */s("p",{className:"lb:text-sm lb:text-gray-400",children:"No se puede previsualizar este video"}),m&&/* @__PURE__ */s("a",{href:m,target:"_blank",rel:"noopener noreferrer",className:"lb:text-sm lb:text-brand-blue-400 lb:hover:text-brand-blue-300 lb:underline",children:"Abrir en nueva pestaña"})]})}),m&&/* @__PURE__ */s("p",{className:"lb:text-xs lb:text-gray-500 lb:truncate lb:max-w-full lb:px-2",children:m})]})})}const
|
|
368
|
-
/* @__PURE__ */s("img",{src:u,alt:l,className:`${r} ${"loading"===i?"lb:opacity-0":"lb:opacity-100"} lb:transition-opacity lb:duration-300`,loading:"lazy",onLoad:()=>{o("loaded")},onError:()=>{n&&!b?(m(!0),d(n),o("loading")):(o("error"),a&&a())}})]})};function
|
|
368
|
+
/* @__PURE__ */s("p",{className:"lb:text-sm lb:text-gray-400",children:"No se puede previsualizar este video"}),m&&/* @__PURE__ */s("a",{href:m,target:"_blank",rel:"noopener noreferrer",className:"lb:text-sm lb:text-brand-blue-400 lb:hover:text-brand-blue-300 lb:underline",children:"Abrir en nueva pestaña"})]})}),m&&/* @__PURE__ */s("p",{className:"lb:text-xs lb:text-gray-500 lb:truncate lb:max-w-full lb:px-2",children:m})]})})}const gt=({src:t,fallbackSrc:n,alt:l,className:r,onError:a})=>{const[i,o]=e.useState("loading"),[u,d]=e.useState(t),[b,m]=e.useState(!1);return"error"===i?null:/* @__PURE__ */c("div",{className:"lb:relative lb:w-full lb:h-full",children:["loading"===i&&/* @__PURE__ */s("div",{className:"lb:absolute lb:inset-0 lb:bg-linear-to-r lb:from-gray-200 lb:via-gray-100 lb:to-gray-200 lb:animate-pulse lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-spinner lb:w-8 lb:h-8 lb:text-gray-400 lb:animate-spin"})}),
|
|
369
|
+
/* @__PURE__ */s("img",{src:u,alt:l,className:`${r} ${"loading"===i?"lb:opacity-0":"lb:opacity-100"} lb:transition-opacity lb:duration-300`,loading:"lazy",onLoad:()=>{o("loaded")},onError:()=>{n&&!b?(m(!0),d(n),o("loading")):(o("error"),a&&a())}})]})};function vt({prod:e,disabled:n,onSelect:a,onVideoSelect:o,selectedFolder:d,onFolderChange:b,folderConfig:m,resolvedAccept:h=null,returnConfig:p=null}){const{sources:f,loading:g,error:v}=pt(e),y=i(()=>{if(!h||h.isAllTypes)return[{value:"images",label:"Imágenes"},{value:"videos",label:"Vídeos"},{value:"all",label:"Todo"}];const e=[];return h.includesImages&&e.push({value:"images",label:"Imágenes"}),h.includesVideos&&e.push({value:"videos",label:"Vídeos"}),e.length>1&&e.push({value:"all",label:"Todo"}),e.length>0?e:[{value:"images",label:"Imágenes"}]},[h]),w=y[0]?.value||"images",[x,k]=t(null),[C,N]=t(w),[S,E]=t(""),[$,_]=t([]),[T,z]=t(1),[L,A]=t(null),[M,P]=t(!1),[I,D]=t(null),[O,R]=t(null),[j,F]=t(null),[U,B]=t(/* @__PURE__ */new Set),[W,q]=t(!1),[V,H]=t(null),[K,G]=t(null),Q=!!p&&"url"===p.format,X=r({}),Y=l((e,t,n,l)=>`${e}_${t}_${n}_${l}`,[]),J=l(async(t,n,l,r)=>{const a=Y(t,n,l,r),i=X.current[a];if(i)return _(i.items),A(i.pagination),z(r),D(null),void q(!0);P(!0),D(null);try{const i={portal:t,media_type:n,page:r,per_page:20};l.trim()&&(i.search=l.trim());const o=await function(e,t=!1){const n=new URLSearchParams;return e.portal&&n.set("portal",e.portal),e.media_type&&n.set("media_type",e.media_type),e.page&&n.set("page",String(e.page)),n.set("per_page",String(e.per_page)),e.search&&n.set("search",e.search),e.order&&n.set("order",e.order),le({endpoint:`/external/media?${n.toString()}`,method:"GET",prod:t,basePath:mt})}(i,e),s=o?.data||{},c=s.items||[],u=s.pagination||{total_items:c.length,total_pages:1,current_page:r,per_page:20};X.current[a]={items:c,pagination:u},_(c),A(u),z(r),B(/* @__PURE__ */new Set),q(!0),0===c.length&&D("No se encontraron resultados para este portal.")}catch(o){D(o.message||"Error al cargar media del portal"),_([]),A(null),q(!0)}finally{P(!1)}},[e,Y]),Z=l(e=>{e!==x&&(k(e),E(""),N(w),_([]),A(null),D(null),R(null),H(null),B(/* @__PURE__ */new Set),q(!1),X.current={})},[x,w]),te=l(()=>{k(null),_([]),A(null),D(null),E(""),R(null),H(null),B(/* @__PURE__ */new Set),q(!1),X.current={}},[]),ne=l(()=>{x&&(X.current={},J(x,C,S,1))},[x,C,S,J]),re=l(e=>{"Enter"===e.key&&(e.preventDefault(),ne())},[ne]),ae=l(e=>{e<1||!x||J(x,C,S,e)},[x,C,S,J]),ie=l(e=>{H(null),o?o(e):a&&a(e)},[o,a]),oe=l(async t=>{if("video"===t.type){const e={type:"video",source:"portal",title:t.title||"",thumbnail:t.thumbnail||t.url,embed_url:t.embed_url||null,player_url:t.player_url||null,post_url:t.post_url||null,platform:t.platform||null,video_id:t.video_id||null,portal_slug:t.portal_slug||x,portal_name:t.portal_name||f.find(e=>e.slug===x)?.name||null,date_published:t.date_published||null,author:t.author||null};return void H(e)}const n=t.url||t.thumbnail;if(n){F(n),D(null);try{let l=null;try{const e=await fetch(n,{mode:"cors"});e.ok&&(l=await e.blob())}catch{}if(!l){const t=`${ee({prod:e})}/api/external/proxy?url=${encodeURIComponent(n)}`,r=await fetch(t);if(!r.ok)throw new Error(`Error al descargar: ${r.status}`);l=await r.blob()}const r=t.title?`${t.title.substring(0,80)}.${"image/png"===t.mime_type?"png":"jpg"}`:`portal-${Date.now()}.jpg`,a=new File([l],r,{type:l.type||t.mime_type||"image/jpeg"});R(a)}catch(l){D(l.message||"No se pudo recuperar la imagen del portal")}finally{F(null)}}else D("No se encontró URL de la imagen")},[e,x,f]);if(g)/* @__PURE__ */
|
|
369
370
|
return c("div",{className:"lb:flex lb:items-center lb:justify-center lb:py-8",children:[
|
|
370
371
|
/* @__PURE__ */s("span",{className:"limbo-loader lb:mr-2"})," Cargando portales disponibles..."]});if(!f.length)/* @__PURE__ */
|
|
371
|
-
return s(
|
|
372
|
+
return s(We,{variant:"warning",children:"No hay portales externos disponibles."});if(!x)/* @__PURE__ */
|
|
372
373
|
return c("div",{className:"lb:flex lb:flex-col lb:gap-4",children:[
|
|
373
|
-
/* @__PURE__ */s("h3",{className:"lb:text-lg lb:font-semibold lb:text-brand-blue-1000",children:"Selecciona un Portal"}),v&&/* @__PURE__ */s(
|
|
374
|
+
/* @__PURE__ */s("h3",{className:"lb:text-lg lb:font-semibold lb:text-brand-blue-1000",children:"Selecciona un Portal"}),v&&/* @__PURE__ */s(We,{variant:"danger",children:v}),
|
|
374
375
|
/* @__PURE__ */s("div",{className:"lb:grid lb:grid-cols-2 lb:md:grid-cols-3 lb:gap-3",children:f.map(e=>/* @__PURE__ */s("button",{type:"button",onClick:()=>Z(e.slug),disabled:n,className:"lb:relative lb:p-4 lb:rounded-lg lb:border-2 lb:transition-all lb:duration-200 lb:flex lb:flex-col lb:items-center lb:justify-center lb:min-h-25 lb:gap-2 lb:max-h-27.5 lb:box-border lb:border-gray-200 lb:bg-white lb:hover:border-brand-blue-350 lb:hover:shadow-md "+(n?"lb:opacity-50 lb:cursor-not-allowed":"lb:cursor-pointer"),children:e.image?/* @__PURE__ */s("img",{className:"lb:object-auto lb:bg-no-repeat lb:bg-center lb:max-h-full",src:e.image,alt:e.title}):/* @__PURE__ */s("span",{className:"lb:text-sm lb:font-medium lb:text-brand-blue-800",children:e.name})},e.slug))})]});const se=f.find(e=>e.slug===x),ce=ee({prod:e});/* @__PURE__ */
|
|
375
376
|
return c("div",{className:"lb:flex lb:flex-col lb:gap-3",children:[
|
|
376
377
|
/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-3",children:[
|
|
@@ -381,14 +382,14 @@ return c("div",{className:"lb:flex lb:flex-col lb:gap-3",children:[
|
|
|
381
382
|
/* @__PURE__ */c("div",{className:"lb:flex lb:flex-col lb:gap-3 lb:border-t lb:pt-3 lb:border-brand-blue-200",children:[y.length>1&&/* @__PURE__ */s("div",{className:"lb:flex lb:gap-2",children:y.map(({value:e,label:t})=>/* @__PURE__ */s("button",{type:"button",onClick:()=>N(e),disabled:n||M,className:"lb:px-3 lb:py-1.5 lb:text-sm lb:rounded-md lb:font-medium lb:transition-colors "+(C===e?"lb:bg-brand-blue-800 lb:text-white":"lb:bg-gray-100 lb:text-gray-700 lb:hover:bg-gray-200"),children:t},e))}),
|
|
382
383
|
/* @__PURE__ */c("div",{className:"lb:flex lb:gap-2",children:[
|
|
383
384
|
/* @__PURE__ */s("input",{type:"text",value:S,onChange:e=>E(e.target.value),onKeyDown:re,className:"limbo-input lb:flex-1",placeholder:"Buscar en el portal...",disabled:n||M}),
|
|
384
|
-
/* @__PURE__ */c("button",{type:"button",onClick:ne,disabled:n||M,className:"limbo-btn limbo-btn-primary lb:px-4 lb:py-2 lb:text-sm lb:font-medium lb:whitespace-nowrap lb:flex lb:items-center lb:gap-1.5",children:[/* @__PURE__ */s("span",M?{className:"limbo-loader limbo-loader--sm"}:{className:"icon icon-search-white icon--sm"}),"Buscar"]})]})]}),I&&!M&&/* @__PURE__ */s(
|
|
385
|
+
/* @__PURE__ */c("button",{type:"button",onClick:ne,disabled:n||M,className:"limbo-btn limbo-btn-primary lb:px-4 lb:py-2 lb:text-sm lb:font-medium lb:whitespace-nowrap lb:flex lb:items-center lb:gap-1.5",children:[/* @__PURE__ */s("span",M?{className:"limbo-loader limbo-loader--sm"}:{className:"icon icon-search-white icon--sm"}),"Buscar"]})]})]}),I&&!M&&/* @__PURE__ */s(We,{variant:"warning",children:I}),O&&/* @__PURE__ */s("div",{className:"lb:mt-2 lb:md:w-full lb:mx-auto",children:/* @__PURE__ */s(at,{image:O,onDiscard:()=>{R(null),D(null)},onDownload:()=>{},onSelect:e=>{if(a)if(e&&O&&e!==O.name){const t=new File([O],e,{type:O.type});a(t)}else a(O)},showRetry:!1,disabled:n,selectedFolder:d,onFolderChange:b,folderConfig:m})}),!O&&/* @__PURE__ */c(u,{children:[
|
|
385
386
|
/* @__PURE__ */c("div",{className:"lb:relative lb:min-h-50","aria-live":"polite",children:[M&&/* @__PURE__ */s("div",{className:"lb:absolute lb:inset-0 lb:bg-white/80 lb:z-10 lb:flex lb:items-center lb:justify-center lb:rounded-lg",children:/* @__PURE__ */c("div",{className:"lb:flex lb:flex-col lb:items-center lb:gap-2",children:[
|
|
386
387
|
/* @__PURE__ */s("span",{className:"limbo-loader"}),
|
|
387
388
|
/* @__PURE__ */s("span",{className:"lb:text-sm lb:text-brand-blue-800",children:"Cargando media..."})]})}),$.length>0&&/* @__PURE__ */c("div",{className:"lb:relative lb:grid lb:grid-cols-2 lb:md:grid-cols-3 lb:lg:grid-cols-4 lb:gap-2",children:[
|
|
388
|
-
/* @__PURE__ */s(
|
|
389
|
+
/* @__PURE__ */s(rt,{show:M,message:"Cargando media..."}),$.map((e,t)=>{const l=`${e.portal_slug}-${e.id||t}`,r=e.thumbnail||e.url;if(U.has(l)||!r)return null;const a=`${ce}/api/external/proxy?url=${encodeURIComponent(r)}`,i="video"===e.type;/* @__PURE__ */
|
|
389
390
|
return c("div",{className:"lb:group lb:border lb:border-brand-blue-200 lb:rounded-lg lb:overflow-hidden lb:bg-white lb:shadow-sm lb:hover:shadow-md lb:transition-all lb:duration-200 lb:cursor-pointer",onClick:()=>{j||M||n||(i?oe(e):G(e))},children:[
|
|
390
391
|
/* @__PURE__ */c("div",{className:"lb:relative lb:aspect-video lb:bg-neutral-100",children:[
|
|
391
|
-
/* @__PURE__ */s(
|
|
392
|
+
/* @__PURE__ */s(gt,{src:r,fallbackSrc:a,alt:e.alt||e.title||`Media ${t+1}`,className:"lb:object-cover lb:w-full lb:h-full",onError:()=>{B(e=>{const t=new Set(e);return t.add(l),t})}}),i&&/* @__PURE__ */s("span",{className:"lb:absolute lb:top-1 lb:left-1 lb:bg-black/60 lb:text-white lb:text-xs lb:px-2 lb:py-1 lb:rounded",children:"Video"}),j===(e.url||e.thumbnail)?/* @__PURE__ */c("div",{className:"lb:absolute lb:inset-0 lb:bg-white/90 lb:flex lb:flex-col lb:items-center lb:justify-center lb:gap-2",children:[
|
|
392
393
|
/* @__PURE__ */c("div",{className:"lb:relative lb:w-10 lb:h-10",children:[
|
|
393
394
|
/* @__PURE__ */s("div",{className:"lb:absolute lb:inset-0 lb:border-4 lb:border-brand-blue-200 lb:rounded-full"}),
|
|
394
395
|
/* @__PURE__ */s("div",{className:"lb:absolute lb:inset-0 lb:border-4 lb:border-brand-blue-800 lb:rounded-full lb:border-t-transparent lb:animate-spin"})]}),
|
|
@@ -406,45 +407,45 @@ return c("div",{className:"lb:group lb:border lb:border-brand-blue-200 lb:rounde
|
|
|
406
407
|
/* @__PURE__ */c("span",{className:"lb:text-xs lb:text-neutral-500 lb:block",children:["(",L.total_items," resultados)"]})]}),
|
|
407
408
|
/* @__PURE__ */c("button",{onClick:()=>ae(T+1),disabled:M||T>=L.total_pages,className:"limbo-btn limbo-btn-secondary px-4 py-2 disabled:opacity-25"+(M||T>=L.total_pages?" pointer-events-none cursor-default":" limbo-btn-primary"),children:["Siguiente"," ",
|
|
408
409
|
/* @__PURE__ */s("span",{className:"icon icon-arrow-right-white icon--sm"})]})]})]}),
|
|
409
|
-
/* @__PURE__ */s(
|
|
410
|
-
return s(
|
|
410
|
+
/* @__PURE__ */s(ft,{isOpen:!!V,video:V,onClose:()=>H(null),onSelect:Q?ie:null}),K&&(()=>{const e=K.thumbnail||K.url,t=`${ce}/api/external/proxy?url=${encodeURIComponent(e)}`;/* @__PURE__ */
|
|
411
|
+
return s(ut,{isOpen:!!K,image:{previewUrl:e,proxyUrl:t,title:K.title||K.alt||"Imagen"},onCancel:()=>G(null),onSelect:()=>{const e=K;G(null),oe(e)}})})()]})}const yt=[{id:"upload",label:"Subir archivo"},{id:"ai",label:"Generar"},{id:"stock",label:"Buscar en Stock"},{id:"portals",label:"Otros portales"}];function wt({onSelect:e,onVideoSelect:n,disabled:l=!1,apiKey:a,prod:o=!1,allowedCategories:u=null,resolvedAccept:d=null,returnConfig:b=null,folderConfig:m=null,selectedFolder:h=null,onFolderChange:p=null}){const{isMobile:f,isTouch:g}=M(),v=i(()=>!d||d.isAllTypes||d.includesImages?yt:d.includesVideos?yt.filter(e=>"upload"===e.id||"portals"===e.id):yt.filter(e=>"upload"===e.id),[d]),[y,w]=t("upload"),[x,k]=t(null),[C,N]=t(null),S=r(),E=["limbo-tabs","lb:flex","lb:gap-4","lb:border-b-2","lb:border-brand-blue-200","lb:mb-4",f&&"lb:overflow-x-auto lb:scrollbar-none"].filter(Boolean).join(" "),$=e=>{const t=["limbo-tab","lb:relative","lb:px-4","lb:py-2","lb:font-medium","lb:text-brand-blue-1000","lb:bg-transparent","lb:border-0","lb:border-b-2","lb:cursor-pointer","lb:transition-all","lb:duration-200","lb:hover:text-pink-1000","lb:focus:outline-none","lb:focus-visible:ring-2","lb:focus-visible:ring-brand-blue-400","lb:focus-visible:ring-offset-2","lb:text-nowrap"];return e?t.push("lb:border-b-brand-blue-1000","lb:font-semibold","limbo-active"):t.push("lb:border-b-transparent"),f&&t.push("lb:min-w-[100px]","lb:min-h-[44px]","lb:text-sm","lb:shrink-0"),g&&t.push("lb:touch-manipulation"),t.join(" ")};/* @__PURE__ */
|
|
411
412
|
return c("div",{className:"limbo-upload-form lb:py-4 lb:min-w-fit lb:max-w-7xl lb:mx-auto",children:[v.length>1&&/* @__PURE__ */s("div",{className:E,role:"tablist","aria-label":"Opciones de subida",style:f?{WebkitOverflowScrolling:"touch",scrollbarWidth:"none",msOverflowStyle:"none"}:void 0,children:v.map(e=>{const t=y===e.id;/* @__PURE__ */
|
|
412
413
|
return c("button",{type:"button","data-upload-tab-id":e.id,className:$(t),"aria-current":t?"page":void 0,"aria-selected":t,role:"tab",tabIndex:t?0:-1,onClick:()=>w(e.id),onKeyDown:t=>((e,t)=>{const n=v.findIndex(e=>e.id===t);let l=n;switch(e.key){case"ArrowLeft":e.preventDefault(),l=n>0?n-1:v.length-1;break;case"ArrowRight":e.preventDefault(),l=n<v.length-1?n+1:0;break;case"Home":e.preventDefault(),l=0;break;case"End":e.preventDefault(),l=v.length-1;break;case"Enter":case" ":return e.preventDefault(),void w(t);default:return}const r=v[l];r&&(w(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:g?{WebkitTapHighlightColor:"transparent"}:void 0,children:["ai"===e.id?/* @__PURE__ */s("span",{className:"icon icon-ia lb:me-1"}):null,e.label]},e.id)})}),
|
|
413
|
-
/* @__PURE__ */c("div",{className:"limbo-tab-content lb:px-2 lb:py-2",role:"tabpanel",id:`upload-tabpanel-${y}`,"aria-labelledby":`upload-tab-${y}`,children:["upload"===y&&/* @__PURE__ */s(Ye,{file:x,setFile:k,previewUrl:C,setPreviewUrl:N,fileInputRef:S,onSelect:e,disabled:l,allowedCategories:u,resolvedAccept:d,selectedFolder:h,onFolderChange:p,folderConfig:m}),"ai"===y&&/* @__PURE__ */s(at,{apiKey:a,prod:o,disabled:l,onSelect:e,selectedFolder:h,onFolderChange:p,folderConfig:m}),"stock"===y&&/* @__PURE__ */s(dt,{apiKey:a,prod:o,disabled:l,onSelect:e,selectedFolder:h,onFolderChange:p,folderConfig:m}),"portals"===y&&/* @__PURE__ */s(gt,{apiKey:a,prod:o,disabled:l,onSelect:e,onVideoSelect:n,resolvedAccept:d,returnConfig:b,selectedFolder:h,onFolderChange:p,folderConfig:m})]})]})}const wt="undefined"!=typeof window&&void 0!==window.document,xt=wt?window:{},kt=!!wt&&"ontouchstart"in xt.document.documentElement,Ct=!!wt&&"PointerEvent"in xt,Nt="cropper",St=`${Nt}-canvas`,Et=`${Nt}-crosshair`,$t=`${Nt}-grid`,_t=`${Nt}-handle`,Tt=`${Nt}-image`,zt=`${Nt}-selection`,Lt=`${Nt}-shade`,At=`${Nt}-viewer`,Mt="select",Pt="move",It="scale",Dt="rotate",Ot="transform",Rt="none",jt="n-resize",Ft="e-resize",Ut="s-resize",Bt="w-resize",Wt="ne-resize",qt="nw-resize",Vt="se-resize",Ht="sw-resize",Kt=Ct?"pointerdown":kt?"touchstart":"mousedown",Gt=Ct?"pointermove":kt?"touchmove":"mousemove",Qt=Ct?"pointerup pointercancel":kt?"touchend touchcancel":"mouseup",Xt="error",Yt="keydown",Jt="load",Zt="wheel",en="action",tn="actionend",nn="actionstart",ln="change",rn="transform";const an=Number.isNaN||xt.isNaN;function on(e){return"number"==typeof e&&!an(e)}function sn(e){return on(e)&&e>0&&e<1/0}function cn(e){return"object"==typeof e&&null!==e}const{hasOwnProperty:un}=Object.prototype;function dn(e){if(!cn(e))return!1;try{const{constructor:t}=e,{prototype:n}=t;return t&&n&&un.call(n,"isPrototypeOf")}catch(t){return!1}}function bn(e){return"function"==typeof e}function mn(e){return"object"==typeof e&&null!==e&&1===e.nodeType}const hn=/([a-z\d])([A-Z])/g;function pn(e){return String(e).replace(hn,"$1-$2").toLowerCase()}const fn=/-[A-z\d]/g;function gn(e){return e.replace(fn,e=>e.slice(1).toUpperCase())}const vn=/\s\s*/;function yn(e,t,n,l){t.trim().split(vn).forEach(t=>{e.removeEventListener(t,n,l)})}function wn(e,t,n,l){t.trim().split(vn).forEach(t=>{e.addEventListener(t,n,l)})}function xn(e,t,n,l){wn(e,t,n,Object.assign(Object.assign({},l),{once:!0}))}const kn={bubbles:!0,cancelable:!0,composed:!0};const Cn=Promise.resolve();function Nn(e){const{documentElement:t}=e.ownerDocument,n=e.getBoundingClientRect();return{left:n.left+(xt.pageXOffset-t.clientLeft),top:n.top+(xt.pageYOffset-t.clientTop)}}const Sn=/deg|g?rad|turn$/i;function En(e){const t=parseFloat(e)||0;if(0!==t){const[n="rad"]=String(e).match(Sn)||[];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 $n="contain";function _n(e,t=$n){const{aspectRatio:n}=e;let{width:l,height:r}=e;const a=sn(l),i=sn(r);if(a&&i){const e=r*n;t===$n&&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 Tn(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 Tn(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 zn=/left|top|width|height/i,Ln="open",An=/* @__PURE__ */new WeakMap,Mn=/* @__PURE__ */new WeakMap,Pn=/* @__PURE__ */new Map,In=xt.document&&Array.isArray(xt.document.adoptedStyleSheets)&&"replaceSync"in xt.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=Ln,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&&Pn.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=gn(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=Mn.get(this),t=this.$sharedStyle;e&&t&&(In?e.replaceSync(t):e.textContent=t);break}}}$propertyChangedCallback(e,t,n){if(!Object.is(n,t))switch(e=pn(e),typeof n){case"boolean":!0===n?this.hasAttribute(e)||this.setAttribute(e,""):this.removeAttribute(e);break;case"number":n=an(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=gn(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||Ln});if(An.set(this,e),Mn.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(){Mn.has(this)&&Mn.delete(this),An.has(this)&&An.delete(this)}$getTagNameOf(e){var t;return null!==(t=Pn.get(e))&&void 0!==t?t:e}$setStyles(e){return Object.keys(e).forEach(t=>{let n=e[t];on(n)&&(n=0!==n&&zn.test(t)?`${n}px`:String(n)),this.style[t]=n}),this}$getShadowRoot(){return this.shadowRoot||An.get(this)}$addStyles(e){let t;const n=this.$getShadowRoot();return In?(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({},kn),{detail:n}),l)))}(this,e,t,n)}$nextTick(e){return function(e,t){return t?Cn.then(e?t.bind(e):t):Cn}(this,e)}static $define(e,t){cn(e)&&(t=e,e=""),e||(e=this.$name||this.name),e=pn(e),wt&&xt.customElements&&!xt.customElements.get(e)&&customElements.define(e,this,t)}}Dn.$version="2.1.0";class On 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=Rt,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),wn(this,Kt,this.$onPointerDown)),this.$onPointerMove||(this.$onPointerMove=this.$handlePointerMove.bind(this),wn(this.ownerDocument,Gt,this.$onPointerMove)),this.$onPointerUp||(this.$onPointerUp=this.$handlePointerUp.bind(this),wn(this.ownerDocument,Qt,this.$onPointerUp)),this.$onWheel||(this.$onWheel=this.$handleWheel.bind(this),wn(this,Zt,this.$onWheel,{passive:!1,capture:!0}))}$unbind(){this.$onPointerDown&&(yn(this,Kt,this.$onPointerDown),this.$onPointerDown=null),this.$onPointerMove&&(yn(this.ownerDocument,Gt,this.$onPointerMove),this.$onPointerMove=null),this.$onPointerUp&&(yn(this.ownerDocument,Qt,this.$onPointerUp),this.$onPointerUp=null),this.$onWheel&&(yn(this,Zt,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)&&(on(t)&&1!==t||on(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=Ot:mn(e.target)&&(a=e.target.action||e.target.getAttribute("action")||""),!1!==this.$emit(nn,{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===Rt||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===Ot){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=It,l.scale=o,l.centerX=s,l.centerY=c):l.action=Rt}else{const[e]=Array.from(n.values());Object.assign(l,e)}n.forEach(e=>{e.startX=e.endX,e.startY=e.endY}),l.action!==Rt&&this.$emit(en,l,{cancelable:!1})}$handlePointerUp(e){const{$action:t,$pointers:n}=this;if(!this.disabled&&t!==Rt&&!1!==this.$emit(tn,{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=Rt)}}$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(en,{action:It,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;dn(e)&&(sn(e.width)||sn(e.height))&&(({width:r,height:a}=_n({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(Tt));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 v=f/2,y=g/2;s.fillStyle="transparent",s.fillRect(0,0,r,a),dn(e)&&bn(e.beforeDraw)&&e.beforeDraw.call(this,s,l),s.save(),s.translate(v,y),s.transform(t,c,u,d,h,p),s.translate(-v,-y),s.drawImage(n,0,0,f,g),s.restore()}t(l)}).catch(n):t(l)})}}On.$name=St,On.$version="2.1.0";const Rn=/* @__PURE__ */new WeakMap,jn=["alt","crossorigin","decoding","elementtiming","fetchpriority","loading","referrerpolicy","sizes","src","srcset"];class Fn 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){Rn.set(this,e)}get $canvas(){return Rn.get(this)}static get observedAttributes(){return super.observedAttributes.concat(jn,["initial-center-size","rotatable","scalable","skewable","translatable"])}attributeChangedCallback(e,t,n){Object.is(n,t)||(super.attributeChangedCallback(e,t,n),jn.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(St));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),wn(t,nn,this.$onCanvasActionStart),wn(t,tn,this.$onCanvasActionEnd),wn(t,en,this.$onCanvasAction)),this.$onLoad=this.$handleLoad.bind(this),wn(e,Jt,this.$onLoad),this.$getShadowRoot().appendChild(e)}disconnectedCallback(){const{$image:e,$canvas:t}=this;t&&(this.$onCanvasActionStart&&(yn(t,nn,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(yn(t,tn,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasAction&&(yn(t,en,this.$onCanvasAction),this.$onCanvasAction=null)),e&&this.$onLoad&&(yn(e,Jt,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!==Ot||this.rotatable&&this.scalable||(l=this.rotatable?Dt:this.scalable?It:Rt),l){case Pt:if(this.translatable){let l=null;e&&(l=e.target.closest(this.$getTagNameOf(zt))),l||(l=t.querySelector(this.$getTagNameOf(zt))),l&&l.multiple&&!l.active&&(l=t.querySelector(`${this.$getTagNameOf(zt)}[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 It:if(this.scalable)if(e){const t=e.target.closest(this.$getTagNameOf(zt));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 Ot: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=()=>{yn(t,Xt,a),setTimeout(()=>{e(t)})},a=()=>{yn(t,Jt,r),n(l)};xn(t,Jt,r),xn(t,Xt,a)}});return bn(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&&on(e)&&on(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&&on(e)&&on(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(on(t)&&on(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,on(t)&&on(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&&on(e)&&on(t)&&this.$transform(1,0,0,1,e,t),this}$transform(e,t,n,l,r,a){return on(e)&&on(t)&&on(n)&&on(l)&&on(r)&&on(a)?this.$setTransform(Tn(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),on(e)&&on(t)&&on(n)&&on(l)&&on(r)&&on(a))){const i=[...this.$matrix],o=[e,t,n,l,r,a];if(!1===this.$emit(rn,{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])}}Fn.$name=Tt,Fn.$version="2.1.0";const Un=/* @__PURE__ */new WeakMap;class Bn 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){Un.set(this,e)}get $canvas(){return Un.get(this)}static get observedAttributes(){return super.observedAttributes.concat(["height","width","x","y"])}connectedCallback(){super.connectedCallback();const e=this.closest(this.$getTagNameOf(St));if(e){this.$canvas=e,this.style.position="absolute";const t=e.querySelector(this.$getTagNameOf(zt));t&&(this.$onCanvasActionStart=e=>{t.hidden&&e.detail.action===Mt&&(this.hidden=!1)},this.$onCanvasActionEnd=e=>{t.hidden&&e.detail.action===Mt&&(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)},wn(e,nn,this.$onCanvasActionStart),wn(e,tn,this.$onCanvasActionEnd),wn(e,ln,this.$onSelectionChange))}this.$render()}disconnectedCallback(){const{$canvas:e}=this;e&&(this.$onCanvasActionStart&&(yn(e,nn,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(yn(e,tn,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onSelectionChange&&(yn(e,ln,this.$onSelectionChange),this.$onSelectionChange=null)),super.disconnectedCallback()}$change(e,t,n=this.width,l=this.height){return on(e)&&on(t)&&on(n)&&on(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:xt.innerWidth})}}Bn.$name=Lt,Bn.$version="2.1.0";class Wn 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=Rt,this.plain=!1,this.slottable=!1,this.themeColor="rgba(51, 153, 255, 0.5)"}static get observedAttributes(){return super.observedAttributes.concat(["action","plain"])}}Wn.$name=_t,Wn.$version="2.1.0";const qn=/* @__PURE__ */new WeakMap;class Vn 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){qn.set(this,e)}get $canvas(){return qn.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(()=>{sn(n)&&n<=1&&this.$initSelection(!0,!0)});break;case"keyboard":this.$nextTick(()=>{this.$canvas&&(n?this.$onDocumentKeyDown||(this.$onDocumentKeyDown=this.$handleKeyDown.bind(this),wn(this.ownerDocument,Yt,this.$onDocumentKeyDown)):this.$onDocumentKeyDown&&(yn(this.ownerDocument,Yt,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(ln,{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(St));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),wn(e,nn,this.$onCanvasActionStart),wn(e,tn,this.$onCanvasActionEnd),wn(e,en,this.$onCanvasAction)):this.$render()}disconnectedCallback(){const{$canvas:e}=this;e&&(this.$onCanvasActionStart&&(yn(e,nn,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(yn(e,tn,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasAction&&(yn(e,en,this.$onCanvasAction),this.$onCanvasAction=null)),super.disconnectedCallback()}$getSelections(){let e=[];return this.parentElement&&(e=Array.from(this.parentElement.querySelectorAll(this.$getTagNameOf(zt)))),e}$initSelection(e=!1,t=!1){const{initialCoverage:n,parentElement:l}=this;if(sn(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;sn(r)&&({width:a,height:i}=_n({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(ln,{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(ln,{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(mn)||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!==Mt||this.multiple&&!this.active&&r!==It)return;const{width:i,height:o}=this;let s=n.endX-n.startX,c=n.endY-n.startY,{aspectRatio:u}=this;switch(!sn(u)&&l.shiftKey&&(u=sn(i)&&sn(o)?i/o:1),r){case Mt:if(0!==s||0!==c){0===s?s=c:0===c&&(c=s);const{$canvas:e}=this,l=Nn(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=qt:c>0&&(r=Ht):s>0&&(c<0?r=Wt:c>0&&(r=Vt)),e&&(e.$action=r)}break;case Pt:this.movable&&(this.dynamic||this.$actionStartTarget&&this.contains(this.$actionStartTarget))&&this.$move(s,c);break;case It:if(l&&this.zoomable&&(this.dynamic||this.contains(l.target))){const e=Nn(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=sn(l),{$canvas:a}=this;let{x:i,y:o,width:s,height:c}=this;switch(e){case jt:o+=n,c-=n,c<0&&(e=Ut,c=-c,o-=c),r&&(i+=(t=n*l)/2,s-=t,s<0&&(s=-s,i-=s));break;case Ft:s+=t,s<0&&(e=Bt,s=-s,i-=s),r&&(o-=(n=t/l)/2,c+=n,c<0&&(c=-c,o-=c));break;case Ut:c+=n,c<0&&(e=jt,c=-c,o-=c),r&&(i-=(t=n*l)/2,s+=t,s<0&&(s=-s,i-=s));break;case Bt:i+=t,s-=t,s<0&&(e=Ft,s=-s,i-=s),r&&(o+=(n=t/l)/2,c-=n,c<0&&(c=-c,o-=c));break;case Wt:r&&(n=-t/l),o+=n,c-=n,s+=t,s<0&&c<0?(e=Ht,s=-s,c=-c,i-=s,o-=c):s<0?(e=qt,s=-s,i-=s):c<0&&(e=Vt,c=-c,o-=c);break;case qt:r&&(n=t/l),i+=t,o+=n,s-=t,c-=n,s<0&&c<0?(e=Vt,s=-s,c=-c,i-=s,o-=c):s<0?(e=Wt,s=-s,i-=s):c<0&&(e=Ht,c=-c,o-=c);break;case Vt:r&&(n=t/l),s+=t,c+=n,s<0&&c<0?(e=qt,s=-s,c=-c,i-=s,o-=c):s<0?(e=Ht,s=-s,i-=s):c<0&&(e=Wt,c=-c,o-=c);break;case Ht:r&&(n=-t/l),i+=t,s-=t,c+=n,s<0&&c<0?(e=Wt,s=-s,c=-c,i-=s,o-=c):s<0?(e=Vt,s=-s,i-=s):c<0&&(e=qt,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 on(t)&&on(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||!on(e)||!on(t)||!on(n)||!on(l)||n<0||l<0?this:(sn(r)&&({width:n,height:l}=_n({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(ln,{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(dn(e)&&(sn(e.width)||sn(e.height))&&(({width:r,height:a}=_n({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(Tt));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 v=t*f+u*g+b,y=c*f+d*g+m,w=n.naturalWidth,x=n.naturalHeight;1!==i&&(v*=i,y*=i,w*=i,x*=i);const k=w/2,C=x/2;s.fillStyle="transparent",s.fillRect(0,0,r,a),dn(e)&&bn(e.beforeDraw)&&e.beforeDraw.call(this,s,l),s.save(),s.translate(k,C),s.transform(t,c,u,d,v,y),s.translate(-k,-C),s.drawImage(n,0,0,w,x),s.restore()}t(l)}).catch(n):t(l)})}}Vn.$name=zt,Vn.$version="2.1.0";class Hn 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))}}Hn.$name=$t,Hn.$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=Et,Kn.$version="2.1.0";const Gn=/* @__PURE__ */new WeakMap,Qn=/* @__PURE__ */new WeakMap,Xn=/* @__PURE__ */new WeakMap,Yn=/* @__PURE__ */new WeakMap,Jn="vertical";class Zn 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=Jn,this.selection="",this.slottable=!1}set $image(e){Qn.set(this,e)}get $image(){return Qn.get(this)}set $sourceImage(e){Yn.set(this,e)}get $sourceImage(){return Yn.get(this)}set $canvas(e){Gn.set(this,e)}get $canvas(){return Gn.get(this)}set $selection(e){Xn.set(this,e)}get $selection(){return Xn.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(zt)),mn(n)){this.$selection=n,this.$onSelectionChange=this.$handleSelectionChange.bind(this),wn(n,ln,this.$onSelectionChange);const e=n.closest(this.$getTagNameOf(St));if(e){this.$canvas=e;const t=e.querySelector(this.$getTagNameOf(Tt));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),wn(t.$image,Jt,this.$onSourceImageLoad),wn(t,rn,this.$onSourceImageTransform))}this.$render()}}disconnectedCallback(){const{$selection:e,$sourceImage:t}=this;e&&this.$onSelectionChange&&(yn(e,ln,this.$onSelectionChange),this.$onSelectionChange=null),t&&this.$onSourceImageLoad&&(yn(t.$image,Jt,this.$onSourceImageLoad),this.$onSourceImageLoad=null),t&&this.$onSourceImageTransform&&(yn(t,rn,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 Jn: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 el(){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),ce(await le({endpoint:`/assets/${e}/variants`,method:"POST",body:{variants:l,async:!1},basePath:de,useJWT:!0}))}catch(l){throw ue(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"),ce(await le({endpoint:`/assets/${e}/variants/upload`,method:"POST",body:l,basePath:de,isFormData:!0,useJWT:!0}))}catch(l){throw ue(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)}}}Zn.$name=At,Zn.$version="2.1.0",On.$define(),Kn.$define(),Hn.$define(),Wn.$define(),Fn.$define(),Vn.$define(),Bn.$define(),Zn.$define();class tl{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 nl(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 ll=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:nl,downloadImage:nl},Symbol.toStringTag,{value:"Module"}));function rl({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[v,y]=t(!1),[w,x]=t(null),[k,C]=t(!1),[N,S]=t(!0),[E,$]=t(!0),[_,T]=t({x:20,y:100}),[z,L]=t(!1),[A,M]=t({x:0,y:0}),[P,I]=t(!1),[D,O]=t(!0),[R,j]=t(!1),[F,U]=t({horizontal:!1,vertical:!1}),[B,W]=t(!1),[q,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([]),[ce,ue]=t(null),de=window.limboCore?.accessibilityManager,{createVariantFromBlob:be,loading:me,error:he}=el(),pe=((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),[v,y]=t(0),w={aspectRatio:"",shade:!0,paspartuFactor:.85,...a};n(()=>{i.current&&o.current&&s.current&&(c.current=new tl(i,o,s),p(!0))},[]),n(()=>{if(c.current)return c.current.setupEventListeners({onSelectionChange:e=>{d(e)},onImageTransform:()=>{y(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:v},transform:x(),selection:k(),utils:C(),manager:c.current}})(e,{aspectRatio:le||null,showGrid:N,shade:E,initialCoverage:.5,paspartuFactor:.85}),{refs:fe,state:ge,transform:ve,selection:ye,utils:we}=pe,{canvasRef:xe,imageRef:ke,selectionRef:Ce}=fe,{cropData:Ne,imageInfo:Se,canExport:Ee,transformVersion:$e}=ge,_e=i(()=>Se||{naturalWidth:e.width||1920,naturalHeight:e.height||1080,currentWidth:e.width||1920,currentHeight:e.height||1080},[Se,e.width,e.height]),ze=l(()=>S(e=>!e),[]),Le=l(()=>$(e=>!e),[]),Ae=l(()=>V(e=>!e),[]),Me=l(()=>K(e=>!e),[]),Pe=l(()=>Q(e=>!e),[]),Ie=l(()=>ve.center(),[ve]),De=l(()=>ye.center(),[ye]),Oe=l(()=>ye.reset(),[ye]),Re=l((e,t)=>ve.move(e,t),[ve]),je=l(e=>ve.zoom(e),[ve]),Fe=l(e=>ve.rotate(e),[ve]),Ue=l(e=>{ye.setCoverage(e)},[ye]),We=l(()=>{U(e=>{const t=!e.horizontal;return ve.flipHorizontal(),{...e,horizontal:t}})},[ve]),qe=l(()=>{U(e=>{const t=!e.vertical;return ve.flipVertical(),{...e,vertical:t}})},[ve]),Ve=l(()=>{if(!pe.manager||!ge.isReady)return null;try{const e=Ne?{...Ne}:null;let t=null;if(Ce.current){const e=Ce.current;t={x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0}}let n=null;if(ke.current){const e=ke.current.$getTransform?.();e&&Array.isArray(e)&&(n=[...e])}const l={cropData:e,selectorState:t,imageTransform:n,flipState:{horizontal:F.horizontal,vertical:F.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}},[pe.manager,ge.isReady,Ne,F,ee,ke,Ce]),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(()=>{Ie(),setTimeout(()=>De(),100)},100);if(pe.manager&&ge.isReady)try{const{savedState:n}=t;if(console.log(`[CropperView] ♻️ Restaurando estado del crop ${e}:`,n),n.imageTransform&&ke.current&&Array.isArray(n.imageTransform)&&setTimeout(()=>{if(ke.current&&ke.current.$setTransform){const[e,t,l,r,a,i]=n.imageTransform;ke.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&&Ce.current){const{x:e,y:t,width:l,height:r}=n.selectorState;setTimeout(()=>{Ce.current&&(Ce.current.x=e,Ce.current.y=t,Ce.current.width=l,Ce.current.height=r,Ce.current.$render&&Ce.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(()=>{Ie(),setTimeout(()=>De(),100)},100)}else console.warn("Cropper not ready for state restoration")},[J,pe.manager,ge.isReady,Ie,De,Ce,ke]),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&&(j(!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)),j(!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]),de?.announce(`Nuevo recorte personalizado añadido: ${t.label}. Selecciónalo para editarlo.`)},[Y.allowCustomCrops,J.length,e.width,e.height,de]),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(xe.current&&Se){const e=xe.current.getBoundingClientRect(),t=Math.min(e.width,e.height);n=Math.max(100,Math.round(.05*t))}const l=Math.max(n,Math.min(3500,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=ye.getData?.();ye.setAspectRatio(a),i&&void 0!==i.x&&setTimeout(()=>{ye.set?.(i.x,i.y,i.width,i.height)},50)},[ee,ne,ye,xe,Se]),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);de?.announce(`Recorte ${n.label} eliminado`)}else alert("Debe haber al menos un recorte.")},[J,ee,de]),et=l(async()=>{if(!Ee)return null;try{const t=await ye.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}},[Ee,e.mime_type,ye]),tt=l(async()=>{if(v)return y(!1),x(null),void C(!1);if(Ee){y(!0),C(!0);try{const e=await et();e?x(e):(y(!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.")},[Ee,et,v]),nt=l(e=>{e.target.closest(".limbo-preview-modal-header")&&(L(!0),M({x:e.clientX-_.x,y:e.clientY-_.y}))},[_]),rt=l(e=>{z&&(e.preventDefault(),T({x:e.clientX-A.x,y:e.clientY-A.y}))},[z,A]),at=l(()=>{L(!1)},[]),it=l(e=>{if(!e.target.closest(".limbo-preview-modal-header"))return;const t=e.touches[0];L(!0),M({x:t.clientX-_.x,y:t.clientY-_.y})},[_]),ot=l(e=>{if(!z)return;e.preventDefault();const t=e.touches[0];T({x:t.clientX-A.x,y:t.clientY-A.y})},[z,A]),st=l(()=>{L(!1)},[]);n(()=>{if(z)return document.addEventListener("mousemove",rt),document.addEventListener("mouseup",at),document.addEventListener("touchmove",ot,{passive:!1}),document.addEventListener("touchend",st),()=>{document.removeEventListener("mousemove",rt),document.removeEventListener("mouseup",at),document.removeEventListener("touchmove",ot),document.removeEventListener("touchend",st)}},[z,rt,at,ot,st]),n(()=>{if(!P)return;const e=e=>{"Escape"===e.key&&I(!1)};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[P]);const ct=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:ke.current?.$getTransform?.(),selectorState:Ce.current?{x:Ce.current.x,y:Ce.current.y,width:Ce.current.width,height:Ce.current.height}:null};try{if(t!==ee&&l.savedState){if(console.log(`[CropperView] 🔄 Restaurando temporalmente crop ${t} para guardado...`),l.savedState.imageTransform&&ke.current?.$setTransform){const[e,t,n,r,a,i]=l.savedState.imageTransform;ke.current.$setTransform(e,t,n,r,a,i)}if(l.savedState.selectorState&&Ce.current){const{x:e,y:t,width:n,height:r}=l.savedState.selectorState;Ce.current.x=e,Ce.current.y=t,Ce.current.width=n,Ce.current.height=r,Ce.current.$render?.()}await new Promise(e=>setTimeout(e,100))}const r=Math.min(l.width,3500),i=Math.min(l.height,3500),o=await ye.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:Ce.current?{x:Ce.current.x,y:Ce.current.y,width:Ce.current.width,height:Ce.current.height}:null,imageTransform:ke.current?.$getTransform?.()||null,flipState:{horizontal:F.horizontal,vertical:F.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 de?.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:Ce.current?{x:Ce.current.x,y:Ce.current.y,width:Ce.current.width,height:Ce.current.height}:null,imageTransform:ke.current?.$getTransform?.()||null,flipState:{horizontal:F.horizontal,vertical:F.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 de?.announceSuccess(`Recorte creado localmente: ${b}`),n}const v=l.savedState||{selectorState:Ce.current?{x:Ce.current.x,y:Ce.current.y,width:Ce.current.width,height:Ce.current.height}:null,imageTransform:ke.current?.$getTransform?.()||null,flipState:{horizontal:F.horizontal,vertical:F.vertical}},y=await be(m,d,{name:b,width:r,height:i,format:s});if(y)return y.cropState=v,de?.announceSuccess(`Recorte creado: ${b}`),h?.(m,y),y;throw new Error("No se pudo crear la variante")}finally{if(t!==ee&&r.imageTransform&&ke.current?.$setTransform){console.log(`[CropperView] ↩️ Restaurando estado original del crop ${r.index}...`);const[e,t,n,l,a,i]=r.imageTransform;if(ke.current.$setTransform(e,t,n,l,a,i),r.selectorState&&Ce.current){const{x:e,y:t,width:n,height:l}=r.selectorState;Ce.current.x=e,Ce.current.y=t,Ce.current.width=n,Ce.current.height=l,Ce.current.$render?.()}}}},[J,ee,ye,be,e.id,h,de,ke,Ce]),ut=l(async()=>{if(!Ee){const e="No se puede exportar el recorte por restricciones de CORS en la imagen original.";return de?.announceError(e),void alert(e)}if(!ge.isReady){const e="El cropper aún no está inicializado. Espera un momento e inténtalo de nuevo.";return de?.announceError(e),void alert(e)}Ve(),de?.announce("Creando recorte de la imagen");try{let t=e.id,n=null;if(e.file&&p){de?.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,de?.announceSuccess("Imagen subida correctamente")}const l=await ct(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.";de?.announceError(e),alert(e),b?.(t)}},[Ee,ge.isReady,de,Ve,ct,ee,a,b,e.file,e.id,p]),dt=l(async t=>{Ve(),de?.announce(`Guardando ${t.length} recortes...`);try{let l=e.id,r=null;if(e.file&&p){de?.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,de?.announceSuccess("Imagen subida correctamente")}const i=[],o=[];for(const e of t)try{const t=await ct(e,l);t&&i.push(t)}catch(n){o.push({crop:J[e]?.label||`Crop ${e}`,error:n.message})}if(i.length>0&&(de?.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")}`;de?.announceError(e),alert(e)}}catch(n){const e=n.message||"Error al procesar los recortes";de?.announceError(e),alert(e),b?.(n)}},[Ve,ct,J,de,a,e.file,e.id,p,b]),bt=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 de?.announce(`Recorte obligatorio "${e.label}" sin configurar. Por favor, configúralo.`,"assertive")}if(J.length>1){ue("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 ut()},[Ke,J,ut,ee,de]),mt=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:ke.current?.$getTransform?.(),selectorState:Ce.current?{x:Ce.current.x,y:Ce.current.y,width:Ce.current.width,height:Ce.current.height}:null};try{if(t!==ee&&n.savedState){if(console.log(`[CropperView] 🔄 Restaurando temporalmente crop ${t} para descarga...`),n.savedState.imageTransform&&ke.current?.$setTransform){const[e,t,l,r,a,i]=n.savedState.imageTransform;ke.current.$setTransform(e,t,l,r,a,i)}if(n.savedState.selectorState&&Ce.current){const{x:e,y:t,width:l,height:r}=n.savedState.selectorState;Ce.current.x=e,Ce.current.y=t,Ce.current.width=l,Ce.current.height=r,Ce.current.$render?.()}await new Promise(e=>setTimeout(e,100))}const l=await ye.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 nl(r,a,{accessibilityManager:de,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&&ke.current?.$setTransform){console.log(`[CropperView] ↩️ Restaurando estado original del crop ${l.index}...`);const[e,t,n,r,a,i]=l.imageTransform;if(ke.current.$setTransform(e,t,n,r,a,i),l.selectorState&&Ce.current){const{x:e,y:t,width:n,height:r}=l.selectorState;Ce.current.x=e,Ce.current.y=t,Ce.current.width=n,Ce.current.height=r,Ce.current.$render?.()}}}},[J,ee,ye,e.mime_type,de,ke,Ce]),ht=l(async e=>{Ve(),de?.announce(`Descargando ${e.length} recortes...`);const t=[],n=[];for(const r of e)try{const e=await mt(r);e&&t.push(e)}catch(l){n.push({crop:J[r]?.label||`Crop ${r}`,error:l.message})}if(t.length>0&&de?.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")}`;de?.announceError(e),alert(e)}},[Ve,mt,J,de]),pt=l(async()=>{if(!Ee){const e="No se puede descargar el recorte por restricciones de CORS en la imagen original.";return de?.announceError(e),void alert(e)}Ve(),de?.announce("Preparando descarga del recorte");try{await mt(ee),de?.announceSuccess("Recorte descargado correctamente")}catch(e){console.error("Error downloading crop:",e);const t=e.message||"Error al descargar el recorte";de?.announceError(t),alert(t)}},[Ee,de,Ve,mt,ee]),ft=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){ue("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 pt()},[Ke,J,pt,ee]),gt=i(()=>!!e.file||(!e.id||!("string"!=typeof e.id||!e.id.startsWith("external"))),[e.file,e.id]),vt=l(async()=>{try{if(e.file&&p){de?.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 de?.announceSuccess("Imagen guardada correctamente"),void a({asset:t,crops:[]})}if(gt){de?.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||Se?.naturalWidth||1920,height:e.height||Se?.naturalHeight||1080,mime_type:e.mime_type||"image/jpeg",isLocal:!0,isOriginal:!0};return de?.announceSuccess("Imagen original conservada"),void a({crops:[t]})}if(e.id&&!e.id.startsWith("external")){de?.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||Se?.naturalWidth||1920,height:e.height||Se?.naturalHeight||1080,mime_type:e.mime_type||"image/jpeg",isOriginal:!0};return de?.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.";de?.announceError(e),alert(e),b?.(t)}},[e,Se,p,o,a,b,de,gt]);return n(()=>{y(!1),x(null)},[e]),n(()=>{if(!pe.manager||!ge.isReady||!D)return;console.log("[CropperView] Carga inicial completada, centrando imagen y selector...");const e=Y.existingCrops?.[0],t=e?.cropState;setTimeout(()=>{Ie(),setTimeout(()=>{if(t){if(console.log("[CropperView] 🔄 Restaurando estado del crop existente:",t),t.imageTransform&&ke.current?.$setTransform){const[e,n,l,r,a,i]=t.imageTransform;ke.current.$setTransform(e,n,l,r,a,i),console.log("[CropperView] ✅ Transformación de imagen restaurada")}if(t.selectorState&&Ce.current){const{x:e,y:n,width:l,height:r}=t.selectorState;Ce.current.x=e,Ce.current.y=n,Ce.current.width=l,Ce.current.height=r,Ce.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 De();O(!1),console.log("[CropperView] Carga inicial finalizada")},100)},50)},[pe.manager,ge.isReady,D,Ie,De,Y.existingCrops]),n(()=>{pe.manager&&ge.isReady&&(le&&ye.setAspectRatio(le),we.setBackground(E))},[le,E,pe.manager,ge.isReady,ye,we]),n(()=>{if(!Se||!ge.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(Se.naturalWidth,3500),n=Math.min(Se.naturalHeight,3500);Z([{...e,width:t,height:n}]),console.log(`[CropperView] Crop por defecto actualizado a ${t}×${n}px`)}},[Se,ge.isReady,Y.mandatoryCrops.length,J]),n(()=>{if(!v||!Ee)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)}},[Ne,$e,v,Ee,et,le,F,w]),n(()=>{const e=xe.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)}},[xe]),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:[
|
|
414
|
+
/* @__PURE__ */c("div",{className:"limbo-tab-content lb:px-2 lb:py-2",role:"tabpanel",id:`upload-tabpanel-${y}`,"aria-labelledby":`upload-tab-${y}`,children:["upload"===y&&/* @__PURE__ */s(Je,{file:x,setFile:k,previewUrl:C,setPreviewUrl:N,fileInputRef:S,onSelect:e,disabled:l,allowedCategories:u,resolvedAccept:d,selectedFolder:h,onFolderChange:p,folderConfig:m}),"ai"===y&&/* @__PURE__ */s(it,{apiKey:a,prod:o,disabled:l,onSelect:e,selectedFolder:h,onFolderChange:p,folderConfig:m}),"stock"===y&&/* @__PURE__ */s(bt,{apiKey:a,prod:o,disabled:l,onSelect:e,selectedFolder:h,onFolderChange:p,folderConfig:m}),"portals"===y&&/* @__PURE__ */s(vt,{apiKey:a,prod:o,disabled:l,onSelect:e,onVideoSelect:n,resolvedAccept:d,returnConfig:b,selectedFolder:h,onFolderChange:p,folderConfig:m})]})]})}const xt="undefined"!=typeof window&&void 0!==window.document,kt=xt?window:{},Ct=!!xt&&"ontouchstart"in kt.document.documentElement,Nt=!!xt&&"PointerEvent"in kt,St="cropper",Et=`${St}-canvas`,$t=`${St}-crosshair`,_t=`${St}-grid`,Tt=`${St}-handle`,zt=`${St}-image`,Lt=`${St}-selection`,At=`${St}-shade`,Mt=`${St}-viewer`,Pt="select",It="move",Dt="scale",Ot="rotate",Rt="transform",jt="none",Ft="n-resize",Ut="e-resize",Bt="s-resize",Wt="w-resize",qt="ne-resize",Vt="nw-resize",Ht="se-resize",Kt="sw-resize",Gt=Nt?"pointerdown":Ct?"touchstart":"mousedown",Qt=Nt?"pointermove":Ct?"touchmove":"mousemove",Xt=Nt?"pointerup pointercancel":Ct?"touchend touchcancel":"mouseup",Yt="error",Jt="keydown",Zt="load",en="wheel",tn="action",nn="actionend",ln="actionstart",rn="change",an="transform";const on=Number.isNaN||kt.isNaN;function sn(e){return"number"==typeof e&&!on(e)}function cn(e){return sn(e)&&e>0&&e<1/0}function un(e){return"object"==typeof e&&null!==e}const{hasOwnProperty:dn}=Object.prototype;function bn(e){if(!un(e))return!1;try{const{constructor:t}=e,{prototype:n}=t;return t&&n&&dn.call(n,"isPrototypeOf")}catch(t){return!1}}function mn(e){return"function"==typeof e}function hn(e){return"object"==typeof e&&null!==e&&1===e.nodeType}const pn=/([a-z\d])([A-Z])/g;function fn(e){return String(e).replace(pn,"$1-$2").toLowerCase()}const gn=/-[A-z\d]/g;function vn(e){return e.replace(gn,e=>e.slice(1).toUpperCase())}const yn=/\s\s*/;function wn(e,t,n,l){t.trim().split(yn).forEach(t=>{e.removeEventListener(t,n,l)})}function xn(e,t,n,l){t.trim().split(yn).forEach(t=>{e.addEventListener(t,n,l)})}function kn(e,t,n,l){xn(e,t,n,Object.assign(Object.assign({},l),{once:!0}))}const Cn={bubbles:!0,cancelable:!0,composed:!0};const Nn=Promise.resolve();function Sn(e){const{documentElement:t}=e.ownerDocument,n=e.getBoundingClientRect();return{left:n.left+(kt.pageXOffset-t.clientLeft),top:n.top+(kt.pageYOffset-t.clientTop)}}const En=/deg|g?rad|turn$/i;function $n(e){const t=parseFloat(e)||0;if(0!==t){const[n="rad"]=String(e).match(En)||[];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 _n="contain";function Tn(e,t=_n){const{aspectRatio:n}=e;let{width:l,height:r}=e;const a=cn(l),i=cn(r);if(a&&i){const e=r*n;t===_n&&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 zn(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 zn(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 Ln=/left|top|width|height/i,An="open",Mn=/* @__PURE__ */new WeakMap,Pn=/* @__PURE__ */new WeakMap,In=/* @__PURE__ */new Map,Dn=kt.document&&Array.isArray(kt.document.adoptedStyleSheets)&&"replaceSync"in kt.CSSStyleSheet.prototype;class On 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&&In.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=vn(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=Pn.get(this),t=this.$sharedStyle;e&&t&&(Dn?e.replaceSync(t):e.textContent=t);break}}}$propertyChangedCallback(e,t,n){if(!Object.is(n,t))switch(e=fn(e),typeof n){case"boolean":!0===n?this.hasAttribute(e)||this.setAttribute(e,""):this.removeAttribute(e);break;case"number":n=on(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=vn(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(Mn.set(this,e),Pn.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(){Pn.has(this)&&Pn.delete(this),Mn.has(this)&&Mn.delete(this)}$getTagNameOf(e){var t;return null!==(t=In.get(e))&&void 0!==t?t:e}$setStyles(e){return Object.keys(e).forEach(t=>{let n=e[t];sn(n)&&(n=0!==n&&Ln.test(t)?`${n}px`:String(n)),this.style[t]=n}),this}$getShadowRoot(){return this.shadowRoot||Mn.get(this)}$addStyles(e){let t;const n=this.$getShadowRoot();return Dn?(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({},Cn),{detail:n}),l)))}(this,e,t,n)}$nextTick(e){return function(e,t){return t?Nn.then(e?t.bind(e):t):Nn}(this,e)}static $define(e,t){un(e)&&(t=e,e=""),e||(e=this.$name||this.name),e=fn(e),xt&&kt.customElements&&!kt.customElements.get(e)&&customElements.define(e,this,t)}}On.$version="2.1.0";class Rn extends On{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=jt,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),xn(this,Gt,this.$onPointerDown)),this.$onPointerMove||(this.$onPointerMove=this.$handlePointerMove.bind(this),xn(this.ownerDocument,Qt,this.$onPointerMove)),this.$onPointerUp||(this.$onPointerUp=this.$handlePointerUp.bind(this),xn(this.ownerDocument,Xt,this.$onPointerUp)),this.$onWheel||(this.$onWheel=this.$handleWheel.bind(this),xn(this,en,this.$onWheel,{passive:!1,capture:!0}))}$unbind(){this.$onPointerDown&&(wn(this,Gt,this.$onPointerDown),this.$onPointerDown=null),this.$onPointerMove&&(wn(this.ownerDocument,Qt,this.$onPointerMove),this.$onPointerMove=null),this.$onPointerUp&&(wn(this.ownerDocument,Xt,this.$onPointerUp),this.$onPointerUp=null),this.$onWheel&&(wn(this,en,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)&&(sn(t)&&1!==t||sn(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=Rt:hn(e.target)&&(a=e.target.action||e.target.getAttribute("action")||""),!1!==this.$emit(ln,{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===jt||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===Rt){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=Ot,l.rotate=i,l.centerX=s,l.centerY=c):d?(l.action=Dt,l.scale=o,l.centerX=s,l.centerY=c):l.action=jt}else{const[e]=Array.from(n.values());Object.assign(l,e)}n.forEach(e=>{e.startX=e.endX,e.startY=e.endY}),l.action!==jt&&this.$emit(tn,l,{cancelable:!1})}$handlePointerUp(e){const{$action:t,$pointers:n}=this;if(!this.disabled&&t!==jt&&!1!==this.$emit(nn,{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=jt)}}$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(tn,{action:Dt,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;bn(e)&&(cn(e.width)||cn(e.height))&&(({width:r,height:a}=Tn({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(zt));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 v=f/2,y=g/2;s.fillStyle="transparent",s.fillRect(0,0,r,a),bn(e)&&mn(e.beforeDraw)&&e.beforeDraw.call(this,s,l),s.save(),s.translate(v,y),s.transform(t,c,u,d,h,p),s.translate(-v,-y),s.drawImage(n,0,0,f,g),s.restore()}t(l)}).catch(n):t(l)})}}Rn.$name=Et,Rn.$version="2.1.0";const jn=/* @__PURE__ */new WeakMap,Fn=["alt","crossorigin","decoding","elementtiming","fetchpriority","loading","referrerpolicy","sizes","src","srcset"];class Un extends On{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){jn.set(this,e)}get $canvas(){return jn.get(this)}static get observedAttributes(){return super.observedAttributes.concat(Fn,["initial-center-size","rotatable","scalable","skewable","translatable"])}attributeChangedCallback(e,t,n){Object.is(n,t)||(super.attributeChangedCallback(e,t,n),Fn.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),xn(t,ln,this.$onCanvasActionStart),xn(t,nn,this.$onCanvasActionEnd),xn(t,tn,this.$onCanvasAction)),this.$onLoad=this.$handleLoad.bind(this),xn(e,Zt,this.$onLoad),this.$getShadowRoot().appendChild(e)}disconnectedCallback(){const{$image:e,$canvas:t}=this;t&&(this.$onCanvasActionStart&&(wn(t,ln,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(wn(t,nn,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasAction&&(wn(t,tn,this.$onCanvasAction),this.$onCanvasAction=null)),e&&this.$onLoad&&(wn(e,Zt,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!==Rt||this.rotatable&&this.scalable||(l=this.rotatable?Ot:this.scalable?Dt:jt),l){case It:if(this.translatable){let l=null;e&&(l=e.target.closest(this.$getTagNameOf(Lt))),l||(l=t.querySelector(this.$getTagNameOf(Lt))),l&&l.multiple&&!l.active&&(l=t.querySelector(`${this.$getTagNameOf(Lt)}[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 Ot: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 Dt:if(this.scalable)if(e){const t=e.target.closest(this.$getTagNameOf(Lt));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 Rt: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=()=>{wn(t,Yt,a),setTimeout(()=>{e(t)})},a=()=>{wn(t,Zt,r),n(l)};kn(t,Zt,r),kn(t,Yt,a)}});return mn(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&&sn(e)&&sn(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&&sn(e)&&sn(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=$n(e),r=Math.cos(l),a=Math.sin(l),[i,o,s,c]=[r,a,-a,r];if(sn(t)&&sn(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,sn(t)&&sn(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=$n(e),l=$n(t);this.$transform(1,Math.tan(l),Math.tan(n),1,0,0)}return this}$translate(e,t=e){return this.translatable&&sn(e)&&sn(t)&&this.$transform(1,0,0,1,e,t),this}$transform(e,t,n,l,r,a){return sn(e)&&sn(t)&&sn(n)&&sn(l)&&sn(r)&&sn(a)?this.$setTransform(zn(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),sn(e)&&sn(t)&&sn(n)&&sn(l)&&sn(r)&&sn(a))){const i=[...this.$matrix],o=[e,t,n,l,r,a];if(!1===this.$emit(an,{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])}}Un.$name=zt,Un.$version="2.1.0";const Bn=/* @__PURE__ */new WeakMap;class Wn extends On{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){Bn.set(this,e)}get $canvas(){return Bn.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(Lt));t&&(this.$onCanvasActionStart=e=>{t.hidden&&e.detail.action===Pt&&(this.hidden=!1)},this.$onCanvasActionEnd=e=>{t.hidden&&e.detail.action===Pt&&(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)},xn(e,ln,this.$onCanvasActionStart),xn(e,nn,this.$onCanvasActionEnd),xn(e,rn,this.$onSelectionChange))}this.$render()}disconnectedCallback(){const{$canvas:e}=this;e&&(this.$onCanvasActionStart&&(wn(e,ln,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(wn(e,nn,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onSelectionChange&&(wn(e,rn,this.$onSelectionChange),this.$onSelectionChange=null)),super.disconnectedCallback()}$change(e,t,n=this.width,l=this.height){return sn(e)&&sn(t)&&sn(n)&&sn(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:kt.innerWidth})}}Wn.$name=At,Wn.$version="2.1.0";class qn extends On{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=jt,this.plain=!1,this.slottable=!1,this.themeColor="rgba(51, 153, 255, 0.5)"}static get observedAttributes(){return super.observedAttributes.concat(["action","plain"])}}qn.$name=Tt,qn.$version="2.1.0";const Vn=/* @__PURE__ */new WeakMap;class Hn extends On{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(()=>{cn(n)&&n<=1&&this.$initSelection(!0,!0)});break;case"keyboard":this.$nextTick(()=>{this.$canvas&&(n?this.$onDocumentKeyDown||(this.$onDocumentKeyDown=this.$handleKeyDown.bind(this),xn(this.ownerDocument,Jt,this.$onDocumentKeyDown)):this.$onDocumentKeyDown&&(wn(this.ownerDocument,Jt,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(rn,{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),xn(e,ln,this.$onCanvasActionStart),xn(e,nn,this.$onCanvasActionEnd),xn(e,tn,this.$onCanvasAction)):this.$render()}disconnectedCallback(){const{$canvas:e}=this;e&&(this.$onCanvasActionStart&&(wn(e,ln,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(wn(e,nn,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasAction&&(wn(e,tn,this.$onCanvasAction),this.$onCanvasAction=null)),super.disconnectedCallback()}$getSelections(){let e=[];return this.parentElement&&(e=Array.from(this.parentElement.querySelectorAll(this.$getTagNameOf(Lt)))),e}$initSelection(e=!1,t=!1){const{initialCoverage:n,parentElement:l}=this;if(cn(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;cn(r)&&({width:a,height:i}=Tn({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(rn,{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(rn,{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(hn)||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!==Pt||this.multiple&&!this.active&&r!==Dt)return;const{width:i,height:o}=this;let s=n.endX-n.startX,c=n.endY-n.startY,{aspectRatio:u}=this;switch(!cn(u)&&l.shiftKey&&(u=cn(i)&&cn(o)?i/o:1),r){case Pt:if(0!==s||0!==c){0===s?s=c:0===c&&(c=s);const{$canvas:e}=this,l=Sn(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=Kt):s>0&&(c<0?r=qt:c>0&&(r=Ht)),e&&(e.$action=r)}break;case It:this.movable&&(this.dynamic||this.$actionStartTarget&&this.contains(this.$actionStartTarget))&&this.$move(s,c);break;case Dt:if(l&&this.zoomable&&(this.dynamic||this.contains(l.target))){const e=Sn(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=cn(l),{$canvas:a}=this;let{x:i,y:o,width:s,height:c}=this;switch(e){case Ft:o+=n,c-=n,c<0&&(e=Bt,c=-c,o-=c),r&&(i+=(t=n*l)/2,s-=t,s<0&&(s=-s,i-=s));break;case Ut:s+=t,s<0&&(e=Wt,s=-s,i-=s),r&&(o-=(n=t/l)/2,c+=n,c<0&&(c=-c,o-=c));break;case Bt: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 Wt:i+=t,s-=t,s<0&&(e=Ut,s=-s,i-=s),r&&(o+=(n=t/l)/2,c-=n,c<0&&(c=-c,o-=c));break;case qt:r&&(n=-t/l),o+=n,c-=n,s+=t,s<0&&c<0?(e=Kt,s=-s,c=-c,i-=s,o-=c):s<0?(e=Vt,s=-s,i-=s):c<0&&(e=Ht,c=-c,o-=c);break;case Vt:r&&(n=t/l),i+=t,o+=n,s-=t,c-=n,s<0&&c<0?(e=Ht,s=-s,c=-c,i-=s,o-=c):s<0?(e=qt,s=-s,i-=s):c<0&&(e=Kt,c=-c,o-=c);break;case Ht: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=Kt,s=-s,i-=s):c<0&&(e=qt,c=-c,o-=c);break;case Kt:r&&(n=-t/l),i+=t,s-=t,c+=n,s<0&&c<0?(e=qt,s=-s,c=-c,i-=s,o-=c):s<0?(e=Ht,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 sn(t)&&sn(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||!sn(e)||!sn(t)||!sn(n)||!sn(l)||n<0||l<0?this:(cn(r)&&({width:n,height:l}=Tn({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(rn,{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(bn(e)&&(cn(e.width)||cn(e.height))&&(({width:r,height:a}=Tn({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(zt));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 v=t*f+u*g+b,y=c*f+d*g+m,w=n.naturalWidth,x=n.naturalHeight;1!==i&&(v*=i,y*=i,w*=i,x*=i);const k=w/2,C=x/2;s.fillStyle="transparent",s.fillRect(0,0,r,a),bn(e)&&mn(e.beforeDraw)&&e.beforeDraw.call(this,s,l),s.save(),s.translate(k,C),s.transform(t,c,u,d,v,y),s.translate(-k,-C),s.drawImage(n,0,0,w,x),s.restore()}t(l)}).catch(n):t(l)})}}Hn.$name=Lt,Hn.$version="2.1.0";class Kn extends On{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))}}Kn.$name=_t,Kn.$version="2.1.0";class Gn extends On{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"])}}Gn.$name=$t,Gn.$version="2.1.0";const Qn=/* @__PURE__ */new WeakMap,Xn=/* @__PURE__ */new WeakMap,Yn=/* @__PURE__ */new WeakMap,Jn=/* @__PURE__ */new WeakMap,Zn="vertical";class el extends On{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=Zn,this.selection="",this.slottable=!1}set $image(e){Xn.set(this,e)}get $image(){return Xn.get(this)}set $sourceImage(e){Jn.set(this,e)}get $sourceImage(){return Jn.get(this)}set $canvas(e){Qn.set(this,e)}get $canvas(){return Qn.get(this)}set $selection(e){Yn.set(this,e)}get $selection(){return Yn.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(Lt)),hn(n)){this.$selection=n,this.$onSelectionChange=this.$handleSelectionChange.bind(this),xn(n,rn,this.$onSelectionChange);const e=n.closest(this.$getTagNameOf(Et));if(e){this.$canvas=e;const t=e.querySelector(this.$getTagNameOf(zt));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),xn(t.$image,Zt,this.$onSourceImageLoad),xn(t,an,this.$onSourceImageTransform))}this.$render()}}disconnectedCallback(){const{$selection:e,$sourceImage:t}=this;e&&this.$onSelectionChange&&(wn(e,rn,this.$onSelectionChange),this.$onSelectionChange=null),t&&this.$onSourceImageLoad&&(wn(t.$image,Zt,this.$onSourceImageLoad),this.$onSourceImageLoad=null),t&&this.$onSourceImageTransform&&(wn(t,an,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 Zn: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 tl(){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),ce(await le({endpoint:`/assets/${e}/variants`,method:"POST",body:{variants:l,async:!1},basePath:de,useJWT:!0}))}catch(l){throw ue(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"),ce(await le({endpoint:`/assets/${e}/variants/upload`,method:"POST",body:l,basePath:de,isFormData:!0,useJWT:!0}))}catch(l){throw ue(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)}}}el.$name=Mt,el.$version="2.1.0",Rn.$define(),Gn.$define(),Kn.$define(),qn.$define(),Un.$define(),Hn.$define(),Wn.$define(),el.$define();class nl{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 ll(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 rl=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:ll,downloadImage:ll},Symbol.toStringTag,{value:"Module"}));function al({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[v,y]=t(!1),[w,x]=t(null),[k,C]=t(!1),[N,S]=t(!0),[E,$]=t(!0),[_,T]=t(e.url||e.path||null);n(()=>{const t=e.url||e.path;if(!t||t.startsWith("blob:")||t.startsWith("data:"))return void T(t);let n=!1;return K(t).then(e=>{n||T(e)}).catch(()=>{n||T(t)}),()=>{n=!0}},[e.url,e.path]);const[z,L]=t({x:20,y:100}),[A,M]=t(!1),[P,I]=t({x:0,y:0}),[D,O]=t(!1),[R,j]=t(!0),[F,U]=t(!1),[B,W]=t({horizontal:!1,vertical:!1}),[q,V]=t(!1),[H,G]=t(!1),[Q,X]=t(!1),[Y,J]=t(!1),[Z]=t(()=>{if(!e||!e.filename)return"image";const[t]=e.filename.split(".");return t}),ee=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]),[te,ne]=t(()=>ee.mandatoryCrops.length>0?ee.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:Z,width:e.width||1920,height:e.height||1080,required:!1,isCustom:!0,confirmed:!1,savedState:null}]),[le,re]=t(0),ae=te[le],ie=i(()=>ae&&ae.width&&ae.height?ae.width/ae.height:"",[ae]),oe=i(()=>{const e=50;if(!ie||""===ie)return{minWidth:e,minHeight:e};if(ie>=1){return{minWidth:e,minHeight:e/ie}}return{minWidth:e*ie,minHeight:e}},[ie]),[se,ce]=t(!1),[ue,de]=t([]),[be,me]=t(null),he=window.limboCore?.accessibilityManager,{createVariantFromBlob:pe,loading:fe,error:ge}=tl(),ve=((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),[v,y]=t(0),w={aspectRatio:"",shade:!0,paspartuFactor:.85,...a};n(()=>{i.current&&o.current&&s.current&&(c.current=new nl(i,o,s),p(!0))},[]),n(()=>{if(c.current)return c.current.setupEventListeners({onSelectionChange:e=>{d(e)},onImageTransform:()=>{y(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:v},transform:x(),selection:k(),utils:C(),manager:c.current}})(e,{aspectRatio:ie||null,showGrid:N,shade:E,initialCoverage:.5,paspartuFactor:.85}),{refs:ye,state:we,transform:xe,selection:ke,utils:Ce}=ve,{canvasRef:Ne,imageRef:Se,selectionRef:Ee}=ye,{cropData:$e,imageInfo:_e,canExport:ze,transformVersion:Le}=we,Ae=i(()=>_e||{naturalWidth:e.width||1920,naturalHeight:e.height||1080,currentWidth:e.width||1920,currentHeight:e.height||1080},[_e,e.width,e.height]),Me=l(()=>S(e=>!e),[]),Pe=l(()=>$(e=>!e),[]),Ie=l(()=>G(e=>!e),[]),De=l(()=>X(e=>!e),[]),Oe=l(()=>J(e=>!e),[]),Re=l(()=>xe.center(),[xe]),je=l(()=>ke.center(),[ke]),Fe=l(()=>ke.reset(),[ke]),Ue=l((e,t)=>xe.move(e,t),[xe]),Be=l(e=>xe.zoom(e),[xe]),qe=l(e=>xe.rotate(e),[xe]),Ve=l(e=>{ke.setCoverage(e)},[ke]),He=l(()=>{W(e=>{const t=!e.horizontal;return xe.flipHorizontal(),{...e,horizontal:t}})},[xe]),Ke=l(()=>{W(e=>{const t=!e.vertical;return xe.flipVertical(),{...e,vertical:t}})},[xe]),Ge=l(()=>{if(!ve.manager||!we.isReady)return null;try{const e=$e?{...$e}:null;let t=null;if(Ee.current){const e=Ee.current;t={x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0}}let n=null;if(Se.current){const e=Se.current.$getTransform?.();e&&Array.isArray(e)&&(n=[...e])}const l={cropData:e,selectorState:t,imageTransform:n,flipState:{horizontal:B.horizontal,vertical:B.vertical}};return console.log(`[CropperView] 💾 Guardando estado del crop ${le}:`,l),ne(e=>e.map((e,t)=>t===le?{...e,savedState:l}:e)),l}catch(e){return console.warn("Error saving crop state:",e),null}},[ve.manager,we.isReady,$e,B,le,Se,Ee]),Qe=l(e=>{const t=te[e];if(!t||!t.savedState)return console.log(`[CropperView] ℹ️ No hay estado guardado para crop ${e}, centrando...`),void setTimeout(()=>{Re(),setTimeout(()=>je(),100)},100);if(ve.manager&&we.isReady)try{const{savedState:n}=t;if(console.log(`[CropperView] ♻️ Restaurando estado del crop ${e}:`,n),n.imageTransform&&Se.current&&Array.isArray(n.imageTransform)&&setTimeout(()=>{if(Se.current&&Se.current.$setTransform){const[e,t,l,r,a,i]=n.imageTransform;Se.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&&Ee.current){const{x:e,y:t,width:l,height:r}=n.selectorState;setTimeout(()=>{Ee.current&&(Ee.current.x=e,Ee.current.y=t,Ee.current.width=l,Ee.current.height=r,Ee.current.$render&&Ee.current.$render(),console.log(`[CropperView] ✅ Selector restaurado: ${l}×${r} en (${e}, ${t})`))},150)}n.flipState&&W({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(()=>{Re(),setTimeout(()=>je(),100)},100)}else console.warn("Cropper not ready for state restoration")},[te,ve.manager,we.isReady,Re,je,Ee,Se]),Xe=l(()=>{for(let e=0;e<te.length;e++){const t=te[e];if(!t.label||""===t.label.trim())return e}return-1},[te]),Ye=l(async e=>{e!==le&&(U(!0),Ge(),await new Promise(e=>setTimeout(e,100)),re(e),await new Promise(e=>setTimeout(e,250)),Qe(e),await new Promise(e=>setTimeout(e,200)),U(!1))},[le,Ge,Qe]),Je=l(()=>{if(!ee.allowCustomCrops)return void alert("No se pueden añadir recortes personalizados en este modo.");const t={id:`crop-custom-${Date.now()}`,label:`Recorte ${te.length+1}`,width:e.width||1920,height:e.height||1080,required:!1,isCustom:!0,confirmed:!1,savedState:null};ne(e=>[...e,t]),he?.announce(`Nuevo recorte personalizado añadido: ${t.label}. Selecciónalo para editarlo.`)},[ee.allowCustomCrops,te.length,e.width,e.height,he]),Ze=l((e,t)=>{const n=parseInt(t,10);""===t||isNaN(n)||ne(t=>t.map((t,l)=>l===le?{...t,[e]:n}:t))},[le]),et=l(e=>{const t=ae[e];let n=100;if(Ne.current&&_e){const e=Ne.current.getBoundingClientRect(),t=Math.min(e.width,e.height);n=Math.max(100,Math.round(.05*t))}const l=Math.max(n,Math.min(3500,t));l!==t&&ne(t=>t.map((t,n)=>n===le?{...t,[e]:l}:t));const r={...ae,[e]:l},a=r.width/r.height,i=ke.getData?.();ke.setAspectRatio(a),i&&void 0!==i.x&&setTimeout(()=>{ke.set?.(i.x,i.y,i.width,i.height)},50)},[le,ae,ke,Ne,_e]),tt=l(e=>{ne(t=>t.map((t,n)=>n===le?{...t,label:e}:t))},[le]),nt=l((e,t=null)=>{t=t||te[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=te[e];if(n.required)alert("No se puede eliminar un recorte obligatorio.");else if(1!==te.length){if(ne(t=>t.filter((t,n)=>n!==e)),e===le){const t=Math.max(0,e-1);re(t)}else e<le&&re(e=>e-1);he?.announce(`Recorte ${n.label} eliminado`)}else alert("Debe haber al menos un recorte.")},[te,le,he]),lt=l(async()=>{if(!ze)return null;try{const t=await ke.toCanvas({width:800,height:600,imageSmoothingEnabled:!0,imageSmoothingQuality:"high"});return t?t.toDataURL(`image/${globalThis.downloadFormat||e.mime_type.split("/")[1]||"webp"}`,.9):null}catch(t){return console.warn("Error generating preview:",t),null}},[ze,e.mime_type,ke]),at=l(async()=>{if(v)return y(!1),x(null),void C(!1);if(ze){y(!0),C(!0);try{const e=await lt();e?x(e):(y(!1),alert("No se puede exportar el recorte por restricciones de CORS en la imagen original."))}finally{C(!1)}}else alert("No se puede exportar el recorte por restricciones de CORS en la imagen original.")},[ze,lt,v]),it=l(e=>{e.target.closest(".limbo-preview-modal-header")&&(M(!0),I({x:e.clientX-z.x,y:e.clientY-z.y}))},[z]),ot=l(e=>{A&&(e.preventDefault(),L({x:e.clientX-P.x,y:e.clientY-P.y}))},[A,P]),st=l(()=>{M(!1)},[]),ct=l(e=>{if(!e.target.closest(".limbo-preview-modal-header"))return;const t=e.touches[0];M(!0),I({x:t.clientX-z.x,y:t.clientY-z.y})},[z]),ut=l(e=>{if(!A)return;e.preventDefault();const t=e.touches[0];L({x:t.clientX-P.x,y:t.clientY-P.y})},[A,P]),dt=l(()=>{M(!1)},[]);n(()=>{if(A)return document.addEventListener("mousemove",ot),document.addEventListener("mouseup",st),document.addEventListener("touchmove",ut,{passive:!1}),document.addEventListener("touchend",dt),()=>{document.removeEventListener("mousemove",ot),document.removeEventListener("mouseup",st),document.removeEventListener("touchmove",ut),document.removeEventListener("touchend",dt)}},[A,ot,st,ut,dt]),n(()=>{if(!D)return;const e=e=>{"Escape"===e.key&&O(!1)};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[D]);const bt=l(async(t,n=null)=>{const l=te[t];if(!l)throw new Error(`Crop ${t} no encontrado`);if(!l.savedState&&t!==le)throw new Error(`El recorte "${l.label}" aún no ha sido configurado`);const r={index:le,imageTransform:Se.current?.$getTransform?.(),selectorState:Ee.current?{x:Ee.current.x,y:Ee.current.y,width:Ee.current.width,height:Ee.current.height}:null};try{if(t!==le&&l.savedState){if(console.log(`[CropperView] 🔄 Restaurando temporalmente crop ${t} para guardado...`),l.savedState.imageTransform&&Se.current?.$setTransform){const[e,t,n,r,a,i]=l.savedState.imageTransform;Se.current.$setTransform(e,t,n,r,a,i)}if(l.savedState.selectorState&&Ee.current){const{x:e,y:t,width:n,height:r}=l.savedState.selectorState;Ee.current.x=e,Ee.current.y=t,Ee.current.width=n,Ee.current.height=r,Ee.current.$render?.()}await new Promise(e=>setTimeout(e,100))}const r=Math.min(l.width,3500),i=Math.min(l.height,3500),o=await ke.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||ee.localCropsOnly)&&!p;if(f&&p&&!ee.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:Ee.current?{x:Ee.current.x,y:Ee.current.y,width:Ee.current.width,height:Ee.current.height}:null,imageTransform:Se.current?.$getTransform?.()||null,flipState:{horizontal:B.horizontal,vertical:B.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 he?.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: ${ee.localCropsOnly})`);const e=URL.createObjectURL(d),t=l.savedState||{selectorState:Ee.current?{x:Ee.current.x,y:Ee.current.y,width:Ee.current.width,height:Ee.current.height}:null,imageTransform:Se.current?.$getTransform?.()||null,flipState:{horizontal:B.horizontal,vertical:B.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 he?.announceSuccess(`Recorte creado localmente: ${b}`),n}const v=l.savedState||{selectorState:Ee.current?{x:Ee.current.x,y:Ee.current.y,width:Ee.current.width,height:Ee.current.height}:null,imageTransform:Se.current?.$getTransform?.()||null,flipState:{horizontal:B.horizontal,vertical:B.vertical}},y=await pe(m,d,{name:b,width:r,height:i,format:s});if(y)return y.cropState=v,he?.announceSuccess(`Recorte creado: ${b}`),h?.(m,y),y;throw new Error("No se pudo crear la variante")}finally{if(t!==le&&r.imageTransform&&Se.current?.$setTransform){console.log(`[CropperView] ↩️ Restaurando estado original del crop ${r.index}...`);const[e,t,n,l,a,i]=r.imageTransform;if(Se.current.$setTransform(e,t,n,l,a,i),r.selectorState&&Ee.current){const{x:e,y:t,width:n,height:l}=r.selectorState;Ee.current.x=e,Ee.current.y=t,Ee.current.width=n,Ee.current.height=l,Ee.current.$render?.()}}}},[te,le,ke,pe,e.id,h,he,Se,Ee]),mt=l(async()=>{if(!ze){const e="No se puede exportar el recorte por restricciones de CORS en la imagen original.";return he?.announceError(e),void alert(e)}if(!we.isReady){const e="El cropper aún no está inicializado. Espera un momento e inténtalo de nuevo.";return he?.announceError(e),void alert(e)}Ge(),he?.announce("Creando recorte de la imagen");try{let t=e.id,n=null;if(e.file&&p){he?.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,he?.announceSuccess("Imagen subida correctamente")}const l=await bt(le,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.";he?.announceError(e),alert(e),b?.(t)}},[ze,we.isReady,he,Ge,bt,le,a,b,e.file,e.id,p]),ht=l(async t=>{Ge(),he?.announce(`Guardando ${t.length} recortes...`);try{let l=e.id,r=null;if(e.file&&p){he?.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,he?.announceSuccess("Imagen subida correctamente")}const i=[],o=[];for(const e of t)try{const t=await bt(e,l);t&&i.push(t)}catch(n){o.push({crop:te[e]?.label||`Crop ${e}`,error:n.message})}if(i.length>0&&(he?.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")}`;he?.announceError(e),alert(e)}}catch(n){const e=n.message||"Error al procesar los recortes";he?.announceError(e),alert(e),b?.(n)}},[Ge,bt,te,he,a,e.file,e.id,p,b]),pt=l(async()=>{const e=Xe();if(-1!==e){const t=te[e];return alert(`El recorte "${t.label||t||"(sin nombre)"}" debe tener un nombre válido.`),void re(e)}const t=te.findIndex((e,t)=>e.required&&!e.savedState&&t!==le);if(-1!==t){const e=te[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.`),re(t),void he?.announce(`Recorte obligatorio "${e.label}" sin configurar. Por favor, configúralo.`,"assertive")}if(te.length>1){me("save");const e=te.map((e,t)=>({crop:e,index:t})).filter(({crop:e,index:t})=>e.required||e.savedState||t===le).map(({index:e})=>e);return de(e),void ce(!0)}await mt()},[Xe,te,mt,le,he]),ft=l(async t=>{const n=te[t];if(!n)throw new Error(`Crop ${t} no encontrado`);if(!n.savedState&&t!==le)throw new Error(`El recorte "${n.label}" aún no ha sido configurado`);const l={index:le,imageTransform:Se.current?.$getTransform?.(),selectorState:Ee.current?{x:Ee.current.x,y:Ee.current.y,width:Ee.current.width,height:Ee.current.height}:null};try{if(t!==le&&n.savedState){if(console.log(`[CropperView] 🔄 Restaurando temporalmente crop ${t} para descarga...`),n.savedState.imageTransform&&Se.current?.$setTransform){const[e,t,l,r,a,i]=n.savedState.imageTransform;Se.current.$setTransform(e,t,l,r,a,i)}if(n.savedState.selectorState&&Ee.current){const{x:e,y:t,width:l,height:r}=n.savedState.selectorState;Ee.current.x=e,Ee.current.y=t,Ee.current.width=l,Ee.current.height=r,Ee.current.$render?.()}await new Promise(e=>setTimeout(e,100))}const l=await ke.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 ll(r,a,{accessibilityManager:he,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!==le&&l.imageTransform&&Se.current?.$setTransform){console.log(`[CropperView] ↩️ Restaurando estado original del crop ${l.index}...`);const[e,t,n,r,a,i]=l.imageTransform;if(Se.current.$setTransform(e,t,n,r,a,i),l.selectorState&&Ee.current){const{x:e,y:t,width:n,height:r}=l.selectorState;Ee.current.x=e,Ee.current.y=t,Ee.current.width=n,Ee.current.height=r,Ee.current.$render?.()}}}},[te,le,ke,e.mime_type,he,Se,Ee]),gt=l(async e=>{Ge(),he?.announce(`Descargando ${e.length} recortes...`);const t=[],n=[];for(const r of e)try{const e=await ft(r);e&&t.push(e)}catch(l){n.push({crop:te[r]?.label||`Crop ${r}`,error:l.message})}if(t.length>0&&he?.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")}`;he?.announceError(e),alert(e)}},[Ge,ft,te,he]),vt=l(async()=>{if(!ze){const e="No se puede descargar el recorte por restricciones de CORS en la imagen original.";return he?.announceError(e),void alert(e)}Ge(),he?.announce("Preparando descarga del recorte");try{await ft(le),he?.announceSuccess("Recorte descargado correctamente")}catch(e){console.error("Error downloading crop:",e);const t=e.message||"Error al descargar el recorte";he?.announceError(t),alert(t)}},[ze,he,Ge,ft,le]),yt=l(async()=>{const e=Xe();if(-1!==e){const t=te[e];return alert(`El recorte "${t.label||t||"(sin nombre)"}" debe tener un nombre válido.`),void re(e)}if(te.length>1){me("download");const e=te.map((e,t)=>({crop:e,index:t})).filter(({crop:e,index:t})=>e.savedState||t===le).map(({index:e})=>e);return de(e),void ce(!0)}await vt()},[Xe,te,vt,le]),wt=i(()=>!!e.file||(!e.id||!("string"!=typeof e.id||!e.id.startsWith("external"))),[e.file,e.id]),xt=l(async()=>{try{if(e.file&&p){he?.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 he?.announceSuccess("Imagen guardada correctamente"),void a({asset:t,crops:[]})}if(wt){he?.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||_e?.naturalWidth||1920,height:e.height||_e?.naturalHeight||1080,mime_type:e.mime_type||"image/jpeg",isLocal:!0,isOriginal:!0};return he?.announceSuccess("Imagen original conservada"),void a({crops:[t]})}if(e.id&&!e.id.startsWith("external")){he?.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||_e?.naturalWidth||1920,height:e.height||_e?.naturalHeight||1080,mime_type:e.mime_type||"image/jpeg",isOriginal:!0};return he?.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.";he?.announceError(e),alert(e),b?.(t)}},[e,_e,p,o,a,b,he,wt]);return n(()=>{y(!1),x(null)},[e]),n(()=>{if(!ve.manager||!we.isReady||!R)return;console.log("[CropperView] Carga inicial completada, centrando imagen y selector...");const e=ee.existingCrops?.[0],t=e?.cropState;setTimeout(()=>{Re(),setTimeout(()=>{if(t){if(console.log("[CropperView] 🔄 Restaurando estado del crop existente:",t),t.imageTransform&&Se.current?.$setTransform){const[e,n,l,r,a,i]=t.imageTransform;Se.current.$setTransform(e,n,l,r,a,i),console.log("[CropperView] ✅ Transformación de imagen restaurada")}if(t.selectorState&&Ee.current){const{x:e,y:n,width:l,height:r}=t.selectorState;Ee.current.x=e,Ee.current.y=n,Ee.current.width=l,Ee.current.height=r,Ee.current.$render?.(),console.log("[CropperView] ✅ Posición del selector restaurada:",t.selectorState)}t.flipState&&(W(t.flipState),console.log("[CropperView] ✅ Estado de flip restaurado:",t.flipState))}else je();j(!1),console.log("[CropperView] Carga inicial finalizada")},100)},50)},[ve.manager,we.isReady,R,Re,je,ee.existingCrops]),n(()=>{ve.manager&&we.isReady&&(ie&&ke.setAspectRatio(ie),Ce.setBackground(E))},[ie,E,ve.manager,we.isReady,ke,Ce]),n(()=>{if(!_e||!we.isReady||ee.mandatoryCrops.length>0)return;const e=te[0];if(e&&"crop-default-0"===e.id&&(1920===e.width||1080===e.height)){const t=Math.min(_e.naturalWidth,3500),n=Math.min(_e.naturalHeight,3500);ne([{...e,width:t,height:n}]),console.log(`[CropperView] Crop por defecto actualizado a ${t}×${n}px`)}},[_e,we.isReady,ee.mandatoryCrops.length,te]),n(()=>{if(!v||!ze)return;const e=setTimeout(async()=>{C(e=>!w&&!e||e);try{const e=await lt();e&&x(e)}finally{C(!1)}},300);return()=>{clearTimeout(e),C(!1)}},[$e,Le,v,ze,lt,ie,B,w]),n(()=>{const e=Ne.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)}},[Ne]),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:[
|
|
414
415
|
/* @__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:[
|
|
415
416
|
/* @__PURE__ */c("div",{className:"lb:flex-1 lb:min-w-fit lb:space-y-2 lb:max-w-fit",children:[
|
|
416
417
|
/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-2",children:[
|
|
417
|
-
/* @__PURE__ */s("h2",{className:"lb:text-lg lb:sm:text-xl lb:font-extrabold lb:text-gray-800",children:"Generar recortes"}),
|
|
418
|
+
/* @__PURE__ */s("h2",{className:"lb:text-lg lb:sm:text-xl lb:font-extrabold lb:text-gray-800",children:"Generar recortes"}),te.length>1&&/* @__PURE__ */s("span",{className:"lb:px-2 lb:py-0.5 lb:bg-blue-100 lb:text-blue-800 lb:text-xs lb:font-semibold lb:rounded",children:ae.label})]}),
|
|
418
419
|
/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-2",children:[
|
|
419
420
|
/* @__PURE__ */s("label",{className:"lb:text-xs lb:text-gray-500 lb:whitespace-nowrap lb:w-fit",children:"Nombre:"}),
|
|
420
|
-
/* @__PURE__ */s("div",{className:"",children:
|
|
421
|
+
/* @__PURE__ */s("div",{className:"",children:Z+"."+(globalThis.downloadFormat||e.mime_type.split("/")[1]||"webp")})]})]}),
|
|
421
422
|
/* @__PURE__ */c("div",{className:"lb:flex lb:flex-row lb:self-end lb:gap-2 lb:w-full lb:max-w-fit lb:sm:w-auto lb:flex-wrap",children:[
|
|
422
|
-
/* @__PURE__ */c("button",{onClick:()=>{window.confirm("Si cancelas, perderás todos los cambios realizados. ¿Deseas continuar?")&&o()},disabled:
|
|
423
|
-
/* @__PURE__ */s("span",{className:"icon icon-arrow-left-white icon--sm lb:m-0 lb:p-0"})," ","Cancelar"]}),d&&/* @__PURE__ */c("button",{onClick:()=>d(e),disabled:m|
|
|
423
|
+
/* @__PURE__ */c("button",{onClick:()=>{window.confirm("Si cancelas, perderás todos los cambios realizados. ¿Deseas continuar?")&&o()},disabled:fe,className:"lb:flex lb:flex-row lb:items-center lb:gap-1 lb:self-end lb:w-full lb:max-w-fit lb:sm:w-auto lb:px-3 lb:cursor-pointer lb:py-1.5 lb:text-sm lb:rounded lb:bg-neutral-gray-500 lb:hover:bg-neutral-gray-700 lb:transition-colors lb:text-white lb:disabled:opacity-50 lb:disabled:cursor-not-allowed","aria-label":"Cancelar y volver",title:"Cancelar y volver",children:[
|
|
424
|
+
/* @__PURE__ */s("span",{className:"icon icon-arrow-left-white icon--sm lb:m-0 lb:p-0"})," ","Cancelar"]}),d&&/* @__PURE__ */c("button",{onClick:()=>d(e),disabled:m|fe,className:"lb:flex lb:flex-row lb:items-center lb:gap-1 lb:self-end lb:w-full lb:max-w-fit lb:sm:w-auto lb:px-3 lb:cursor-pointer lb:py-1.5 lb:text-sm lb:rounded lb:bg-red-800 lb:hover:bg-red-1000 lb:transition-colors lb:text-white lb:disabled:opacity-50 lb:disabled:cursor-not-allowed","aria-label":`Eliminar imagen ${e.filename}`,title:`Eliminar imagen ${e.filename}`,children:[
|
|
424
425
|
/* @__PURE__ */s("span",{className:"icon icon-close-small-white icon--sm lb:m-0 lb:p-0"}),m?"Eliminando...":"Eliminar"]})]})]}),
|
|
425
|
-
/* @__PURE__ */c("div",{className:"limbo-cropper-status lb:bg-white lb:border-gray-100 lb:py-0 lb:pb-0 lb:flex-shrink-0",children:[
|
|
426
|
-
/* @__PURE__ */s("strong",{children:"Error:"})," ",
|
|
427
|
-
/* @__PURE__ */s("strong",{children:"Original:"})," ",
|
|
426
|
+
/* @__PURE__ */c("div",{className:"limbo-cropper-status lb:bg-white lb:border-gray-100 lb:py-0 lb:pb-0 lb:flex-shrink-0",children:[ge&&/* @__PURE__ */c(We,{variant:"danger",className:"lb:mb-2 lb:text-sm",children:[
|
|
427
|
+
/* @__PURE__ */s("strong",{children:"Error:"})," ",ge]}),_e&&/* @__PURE__ */c(We,{variant:"info",className:"lb:mb-2 lb:text-sm",role:"status",children:[
|
|
428
|
+
/* @__PURE__ */s("strong",{children:"Original:"})," ",_e.naturalWidth," ×"," ",_e.naturalHeight," px",_e.currentWidth!==_e.naturalWidth&&/* @__PURE__ */c("span",{className:"lb:ml-2 lb:sm:ml-3 lb:text-xs lb:block lb:sm:inline",children:["(Mostrada: ",Math.round(_e.currentWidth)," ×"," ",Math.round(_e.currentHeight)," px)"]})]}),!ze&&/* @__PURE__ */s(We,{variant:"warning",className:"lb:mb-2 lb:text-sm",children:"No se puede exportar por restricciones CORS"}),
|
|
428
429
|
/* @__PURE__ */c("div",{className:"lb:bg-white lb:border-b lb:border-gray-200 lb:py-2 lb:mx-2 lb:shrink-0 lb:sticky lb:top-0 lb:z-10 lb:mb-1",children:[
|
|
429
430
|
/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:justify-between lb:mb-2",children:[
|
|
430
|
-
/* @__PURE__ */c("h3",{className:"lb:text-sm lb:font-semibold lb:text-gray-700",children:["Recortes ",
|
|
431
|
+
/* @__PURE__ */c("h3",{className:"lb:text-sm lb:font-semibold lb:text-gray-700",children:["Recortes ",te.length>1&&`(${te.length})`]}),ee.allowCustomCrops&&/* @__PURE__ */c("button",{onClick:Je,disabled:fe,className:"lb:text-xs lb:cursor-pointer lb:px-2 lb:py-1 lb:bg-brand-blue-50 lb:hover:bg-brand-blue-200 lb:text-brand-blue-1000 lb:rounded lb:border lb:border-brand-blue-200 lb:transition-colors lb:flex lb:items-center lb:gap-1",title:"Añadir recorte personalizado",children:[
|
|
431
432
|
/* @__PURE__ */s("span",{className:"icon icon-add icon--sm",style:{filter:"var(--limbo-icon-blue)"}}),"Añadir recorte"]})]}),
|
|
432
|
-
/* @__PURE__ */s("div",{className:"lb:grid lb:grid-cols-2 lb:md:grid-cols-3 lb:lg:grid-cols-4 lb:xl:grid-cols-5 lb:gap-1.5 lb:max-h-48 lb:overflow-y-auto",children:
|
|
433
|
-
return c("label",{className:"lb:h-fit lb:flex lb:flex-col lb:p-1.5 lb:rounded lb:border lb:cursor-pointer lb:transition-colors lb:min-h-17.5 lb:w-full "+(
|
|
434
|
-
/* @__PURE__ */s("input",{type:"radio",name:"active-crop",checked:
|
|
433
|
+
/* @__PURE__ */s("div",{className:"lb:grid lb:grid-cols-2 lb:md:grid-cols-3 lb:lg:grid-cols-4 lb:xl:grid-cols-5 lb:gap-1.5 lb:max-h-48 lb:overflow-y-auto",children:te.map((e,t)=>{const n=e.savedState||t===le;/* @__PURE__ */
|
|
434
|
+
return c("label",{className:"lb:h-fit lb:flex lb:flex-col lb:p-1.5 lb:rounded lb:border lb:cursor-pointer lb:transition-colors lb:min-h-17.5 lb:w-full "+(le===t?"lb:bg-blue-50 lb:border-blue-300":n?"lb:bg-gray-50 lb:border-gray-200 lb:hover:bg-gray-100":"lb:bg-orange-50 lb:border-orange-300 lb:hover:bg-orange-100"),children:[
|
|
435
|
+
/* @__PURE__ */s("input",{type:"radio",name:"active-crop",checked:le===t,onChange:()=>Ye(t),disabled:fe,className:"lb:hidden"}),
|
|
435
436
|
/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-1 lb:mb-1",children:[
|
|
436
|
-
/* @__PURE__ */s("div",{className:"lb:flex-1 lb:min-w-0",children:/* @__PURE__ */c("div",{className:"lb:flex lb:flex-wrap lb:items-center lb:gap-1 lb:min-h-",children:[
|
|
437
|
-
/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:gap-1 lb:mt-auto",children:
|
|
438
|
-
/* @__PURE__ */s("input",{type:"number",min:"100",max:"3500",value:e.width,onChange:e=>
|
|
437
|
+
/* @__PURE__ */s("div",{className:"lb:flex-1 lb:min-w-0",children:/* @__PURE__ */c("div",{className:"lb:flex lb:flex-wrap lb:items-center lb:gap-1 lb:min-h-",children:[le!==t||e.required?/* @__PURE__ */s("span",{className:"lb:text-xs lb:font-medium lb:text-gray-800 lb:truncate",children:e.label}):/* @__PURE__ */s("input",{type:"text",value:e.label,onChange:e=>tt(e.target.value),disabled:fe,className:"lb:w-full lb:max-h-fit lb:text-xs lb:px-1 lb:py-0.5 lb:border lb:border-gray-300 lb:rounded lb:focus:outline-none lb:focus:ring-1 lb:focus:ring-blue-500 lb:h-1",placeholder:"Nombre",maxLength:25,onClick:e=>e.stopPropagation()}),e.required&&/* @__PURE__ */s("span",{className:"lb:text-[10px] lb:px-1 lb:py-0.5 lb:bg-red-200 lb:text-red-1000 lb:rounded lb:whitespace-nowrap lb:truncate",children:"Obligatorio"})]})}),!e.required&&te.length>1&&/* @__PURE__ */s("button",{onClick:n=>{n.preventDefault(),n.stopPropagation(),nt(t,e.label)},className:"lb:shrink-0 lb:hover:bg-red-500/70 lb:text-red-1000 lb:p-1 lb:rounded lb:max-h-fit lb:aspect-square lb:cursor-pointer lb:flex",title:"Eliminar",children:/* @__PURE__ */s("span",{className:"icon icon-close-small icon--xs"})})]}),
|
|
438
|
+
/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:gap-1 lb:mt-auto",children:le===t?/* @__PURE__ */c(u,{children:[
|
|
439
|
+
/* @__PURE__ */s("input",{type:"number",min:"100",max:"3500",value:e.width,onChange:e=>Ze("width",e.target.value),onBlur:()=>et("width"),disabled:fe||e.lockDimensions,className:"lb:max-h-fit lb:flex-1 lb:text-xs lb:px-1 lb:py-0.5 lb:border lb:rounded lb:focus:outline-none lb:focus:ring-1 lb:focus:ring-blue-500 "+(e.lockDimensions?"lb:border-gray-200 lb:bg-gray-100 lb:text-gray-500 lb:cursor-not-allowed":"lb:border-gray-300"),placeholder:"W",onClick:e=>e.stopPropagation(),title:e.lockDimensions?"Dimensiones bloqueadas (recorte obligatorio)":"Ancho en píxeles"}),
|
|
439
440
|
/* @__PURE__ */s("span",{className:"lb:text-gray-400 lb:text-xs",children:"×"}),
|
|
440
|
-
/* @__PURE__ */s("input",{type:"number",min:"100",max:"3500",value:e.height,onChange:e=>
|
|
441
|
+
/* @__PURE__ */s("input",{type:"number",min:"100",max:"3500",value:e.height,onChange:e=>Ze("height",e.target.value),onBlur:()=>et("height"),disabled:fe||e.lockDimensions,className:"lb:max-h-fit lb:flex-1 lb:text-xs lb:px-1 lb:py-0.5 lb:border lb:rounded lb:focus:outline-none lb:focus:ring-1 lb:focus:ring-blue-500 "+(e.lockDimensions?"lb:border-gray-200 lb:bg-gray-100 lb:text-gray-500 lb:cursor-not-allowed":"lb:border-gray-300"),placeholder:"H",onClick:e=>e.stopPropagation(),title:e.lockDimensions?"Dimensiones bloqueadas (recorte obligatorio)":"Alto en píxeles"})]}):/* @__PURE__ */c("span",{className:"lb:text-xs lb:text-gray-500",children:[e.width," × ",e.height," px"]})}),!n&&/* @__PURE__ */s("div",{className:"lb:text-xs lb:px-1 lb:py-0.5 lb:bg-orange-300 lb:text-neutral-gray-25 lb:text-shadow-xs lb:font-semibold lb:rounded lb:text-center lb:mt-1",children:"Sin configurar"})]},e.id)})})]})]}),
|
|
441
442
|
/* @__PURE__ */c("div",{className:"lb:flex lb:flex-col lb:lg:flex-row lb:flex-1 lb:w-full lb:overflow-hidden lb:lg:max-h-130 lb:mx-2 lb:py-1",children:[
|
|
442
443
|
/* @__PURE__ */s("div",{className:"lb:relative lb:flex-1 lg:flex-2 lb:h-full lb:shrink-0 lb:grow-1 lb:order-0 lb:min-h-100 lb:lg:min-h-130",children:/* @__PURE__ */c("div",{className:"lb:absolute lb:inset-0 lb:bg-white lb:rounded-lg lb:border-2 lb:border-gray-200 lb:overflow-hidden",children:[
|
|
443
|
-
/* @__PURE__ */s(
|
|
444
|
-
/* @__PURE__ */s(
|
|
445
|
-
/* @__PURE__ */c("cropper-canvas",{ref:
|
|
446
|
-
/* @__PURE__ */s("cropper-image",{ref:
|
|
447
|
-
/* @__PURE__ */c("cropper-selection",{ref:
|
|
444
|
+
/* @__PURE__ */s(rt,{show:R,message:"Cargando recortador..."}),
|
|
445
|
+
/* @__PURE__ */s(rt,{show:F,message:`Cambiando a: ${te[le]?.label||"recorte"}...`}),
|
|
446
|
+
/* @__PURE__ */c("cropper-canvas",{ref:Ne,style:{width:"100%",height:"100%",display:"block"},background:!!E||void 0,id:"limbo-cropperjs-canvas",tabindex:"-1",onKeyDown:e=>{"Delete"!==e.key&&"Backspace"!==e.key||(e.preventDefault(),e.stopPropagation())},children:[
|
|
447
|
+
/* @__PURE__ */s("cropper-image",{ref:Se,src:_,alt:e.filename,id:"limbo-cropperjs-image",action:"move",crossOrigin:"anonymous",rotatable:!0,scalable:!0,skewable:!0,translatable:!0}),
|
|
448
|
+
/* @__PURE__ */c("cropper-selection",{ref:Ee,"initial-coverage":"0.5",movable:!0,resizable:!0,keyboard:"true",action:"move",style:{cursor:"move",minWidth:`${oe.minWidth}px`,minHeight:`${oe.minHeight}px`},"data-prevent-delete":"true",tabindex:"-1",children:[N&&/* @__PURE__ */s("cropper-grid",{role:"grid",action:"move",covered:!0,bordered:!0}),
|
|
448
449
|
/* @__PURE__ */s("cropper-handle",{action:"move",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:"32px",height:"32px",zIndex:"10"}}),
|
|
449
450
|
/* @__PURE__ */s("cropper-handle",{action:"n-resize"}),
|
|
450
451
|
/* @__PURE__ */s("cropper-handle",{action:"e-resize"}),
|
|
@@ -456,95 +457,95 @@ return c("label",{className:"lb:h-fit lb:flex lb:flex-col lb:p-1.5 lb:rounded lb
|
|
|
456
457
|
/* @__PURE__ */s("cropper-handle",{action:"sw-resize"})]})]})]})}),
|
|
457
458
|
/* @__PURE__ */s("div",{className:"lb:w-full lb:lg:max-w-80 lb:mt-2 lb:lg:my-0 lb:overflow-y-auto lb:bg-white lb:border-t lb:lg:border-t-0 lb:lg:border-l lb:border-gray-200 lb:shrink-0",children:/* @__PURE__ */c("div",{className:"lb:h-full lb:mt-2 lb:lg:my-0 lb:me-2 lb:lg:mx-2 lb:space-y-2 lb:grid lb:grid-cols-2 lb:md:grid-cols-3 lb:flex-wrap lb:md:flex-nowrap lb:items-start lb:flex-row lb:gap-2 lb:lg:gap-0 lb:lg:block",children:[
|
|
458
459
|
/* @__PURE__ */c("div",{className:"lb:bg-white lb:rounded lb:border lb:w-full lb:border-gray-200 lb:mb-2",children:[
|
|
459
|
-
/* @__PURE__ */s("button",{onClick:
|
|
460
|
+
/* @__PURE__ */s("button",{onClick:Oe,className:"lb:hidden lb:sm:block lb:w-full lb:p-2 lb:mb-05 lb:cursor-pointer lb:hover:bg-neutral-gray-050/50 lb:transition-colors lb:rounded-t-sm","aria-expanded":Y,"aria-label":"Mostrar/ocultar opciones de visualización",children:/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:justify-between",children:[
|
|
460
461
|
/* @__PURE__ */s("h3",{className:"lb:text-sm lb:font-semibold lb:text-gray-700",children:"Transformar imagen"}),
|
|
461
|
-
/* @__PURE__ */s("div",{className:"lb:text-center",children:/* @__PURE__ */s("span",{className:`icon ${
|
|
462
|
-
/* @__PURE__ */c("div",{className:"lb:p-2 lb:space-y-2 lb:justify-items-stretch lb:static "+(
|
|
462
|
+
/* @__PURE__ */s("div",{className:"lb:text-center",children:/* @__PURE__ */s("span",{className:`icon ${Y?"icon-chevron-up":"icon-chevron-down"} lb:text-center icon--xs`})})]})}),
|
|
463
|
+
/* @__PURE__ */c("div",{className:"lb:p-2 lb:space-y-2 lb:justify-items-stretch lb:static "+(Y?"lb:block":"lb:sm:hidden"),children:[
|
|
463
464
|
/* @__PURE__ */s("div",{className:"lb:mb-3 lb:block",children:/* @__PURE__ */c("div",{className:"lb:grid lb:grid-cols-5 lb:gap-1 lb:content-center lb:h-fit lb:mx-auto",children:[
|
|
464
|
-
/* @__PURE__ */s("button",{onClick:()=>
|
|
465
|
-
/* @__PURE__ */s("button",{onClick:()=>
|
|
466
|
-
/* @__PURE__ */s("button",{onClick:()=>
|
|
467
|
-
/* @__PURE__ */s("button",{onClick:()=>
|
|
468
|
-
/* @__PURE__ */s("button",{onClick:()=>
|
|
469
|
-
/* @__PURE__ */s("button",{onClick:()=>
|
|
470
|
-
/* @__PURE__ */s("button",{onClick:()=>
|
|
471
|
-
/* @__PURE__ */s("button",{onClick:
|
|
472
|
-
/* @__PURE__ */s("button",{onClick:()=>
|
|
473
|
-
/* @__PURE__ */s("button",{onClick:()=>
|
|
474
|
-
/* @__PURE__ */s("button",{onClick:
|
|
475
|
-
/* @__PURE__ */s("button",{onClick:()=>
|
|
476
|
-
/* @__PURE__ */s("button",{onClick:()=>
|
|
477
|
-
/* @__PURE__ */s("button",{onClick:()=>
|
|
478
|
-
/* @__PURE__ */s("button",{onClick:
|
|
479
|
-
/* @__PURE__ */s("div",{className:"lb:flex lb:flex-col lb:gap-2",children:/* @__PURE__ */s("button",{onClick:()=>{
|
|
465
|
+
/* @__PURE__ */s("button",{onClick:()=>Be(-.2),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Alejar",disabled:fe,"aria-label":"Alejar imagen",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-zoom-out-blue"})})}),
|
|
466
|
+
/* @__PURE__ */s("button",{onClick:()=>Ue(-10,-10),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Mover arriba-izquierda",disabled:fe,"aria-label":"Mover imagen hacia arriba-izquierda",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-arrow-up-blue icon--md lb:-rotate-45"})})}),
|
|
467
|
+
/* @__PURE__ */s("button",{onClick:()=>Ue(0,-10),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Mover arriba",disabled:fe,"aria-label":"Mover imagen hacia arriba",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-arrow-up-blue icon--md"})})}),
|
|
468
|
+
/* @__PURE__ */s("button",{onClick:()=>Ue(10,-10),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Mover arriba-derecha",disabled:fe,"aria-label":"Mover imagen hacia arriba-derecha",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-arrow-up-blue icon--md lb:rotate-45"})})}),
|
|
469
|
+
/* @__PURE__ */s("button",{onClick:()=>Be(.2),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Acercar 20%",disabled:fe,"aria-label":"Acercar imagen",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-zoom-in-blue"})})}),
|
|
470
|
+
/* @__PURE__ */s("button",{onClick:()=>qe(-45),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Rotar -45°",disabled:fe,"aria-label":"Rotar imagen 45 grados a la izquierda",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"lb:text-brand-blue-1000 lb:font-medium",children:"-45°"})})}),
|
|
471
|
+
/* @__PURE__ */s("button",{onClick:()=>Ue(-10,0),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Mover izquierda",disabled:fe,"aria-label":"Mover imagen hacia la izquierda",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-arrow-left-blue"})})}),
|
|
472
|
+
/* @__PURE__ */s("button",{onClick:Re,className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Centrar y ajustar imagen",disabled:fe,"aria-label":"Centrar y ajustar imagen",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-radio-button-blue icon-md"})})}),
|
|
473
|
+
/* @__PURE__ */s("button",{onClick:()=>Ue(10,0),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Mover derecha",disabled:fe,"aria-label":"Mover imagen hacia la derecha",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-arrow-right-blue"})})}),
|
|
474
|
+
/* @__PURE__ */s("button",{onClick:()=>qe(45),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Rotar +45°",disabled:fe,"aria-label":"Rotar imagen 45 grados a la derecha",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"lb:text-brand-blue-1000 lb:font-medium",children:"+45°"})})}),
|
|
475
|
+
/* @__PURE__ */s("button",{onClick:He,className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:aspect-square "+(B.horizontal?"lb:bg-blue-100 lb:border lb:border-blue-300 lb:text-blue-800":"lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200"),title:"Voltear horizontalmente "+(B.horizontal?"(activo)":""),disabled:fe,"aria-label":"Voltear imagen horizontalmente","aria-pressed":B.horizontal,children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center lb:gap-2",children:/* @__PURE__ */s("span",{className:"icon icon-arrow-left-right-blue lb:border lb:border-brand-blue-1000 lb:rounded"})})}),
|
|
476
|
+
/* @__PURE__ */s("button",{onClick:()=>Ue(-10,10),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Mover abajo-izquierda",disabled:fe,"aria-label":"Mover imagen hacia abajo-izquierda",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-arrow-up-blue icon--md lb:-rotate-145"})})}),
|
|
477
|
+
/* @__PURE__ */s("button",{onClick:()=>Ue(0,10),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Mover abajo",disabled:fe,"aria-label":"Mover imagen hacia abajo",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-arrow-down-blue"})})}),
|
|
478
|
+
/* @__PURE__ */s("button",{onClick:()=>Ue(10,10),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Mover abajo-derecha",disabled:fe,"aria-label":"Mover imagen hacia abajo-derecha",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-arrow-up-blue icon--md lb:rotate-145"})})}),
|
|
479
|
+
/* @__PURE__ */s("button",{onClick:Ke,className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:aspect-square lb:text-sm "+(B.vertical?"lb:bg-blue-100 lb:border lb:border-blue-300 lb:text-blue-800":"lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200"),title:"Voltear verticalmente "+(B.vertical?"(activo)":""),disabled:fe,"aria-label":"Voltear imagen verticalmente","aria-pressed":B.vertical,children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-arrow-up-down-blue lb:border lb:border-brand-blue-1000 lb:rounded"})})})]})}),
|
|
480
|
+
/* @__PURE__ */s("div",{className:"lb:flex lb:flex-col lb:gap-2",children:/* @__PURE__ */s("button",{onClick:()=>{xe.reset(),W({horizontal:!1,vertical:!1})},className:"lb:w-full lb:p-2 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200",title:"Reiniciar transformaciones",disabled:fe,"aria-label":"Reiniciar todas las transformaciones de la imagen",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */c("span",{children:[
|
|
480
481
|
/* @__PURE__ */s("span",{className:"icon icon-refresh-blue icon--sm lb:align-[middle!important] "})," ","Reiniciar ajustes"]})})})})]})]}),
|
|
481
|
-
/* @__PURE__ */c("div",{className:"lb:bg-white lb:rounded lb:border lb:border-gray-200 lb:w-full"+(
|
|
482
|
-
/* @__PURE__ */s("button",{onClick:
|
|
482
|
+
/* @__PURE__ */c("div",{className:"lb:bg-white lb:rounded lb:border lb:border-gray-200 lb:w-full"+(Q?"":" lb:bg-neutral-gray-50/50"),children:[
|
|
483
|
+
/* @__PURE__ */s("button",{onClick:De,className:"lb:hidden lb:sm:block lb:w-full lb:cursor-pointer lb:hover:bg-neutral-gray-050/50 lb:p-2 lb:mb-05 lb:transition-colors lb:rounded-t-sm","aria-expanded":Q,"aria-label":"Mostrar/ocultar opciones de visualizción",children:/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:justify-between",children:[
|
|
483
484
|
/* @__PURE__ */s("h3",{className:"lb:text-sm lb:font-semibold lb:text-gray-700",children:"Ajustes del selector"}),
|
|
484
|
-
/* @__PURE__ */s("div",{className:"lb:text-center",children:/* @__PURE__ */s("span",{className:`icon ${
|
|
485
|
-
/* @__PURE__ */c("div",{className:"lb:p-2 lb:space-y-2 lb:justify-items-stretch lb:static "+(
|
|
485
|
+
/* @__PURE__ */s("div",{className:"lb:text-center",children:/* @__PURE__ */s("span",{className:`icon ${Q?"icon-chevron-up":"icon-chevron-down"} lb:text-center icon--xs`})})]})}),
|
|
486
|
+
/* @__PURE__ */c("div",{className:"lb:p-2 lb:space-y-2 lb:justify-items-stretch lb:static "+(Q?"lb:block":"lb:sm:hidden"),children:[
|
|
486
487
|
/* @__PURE__ */s("div",{children:/* @__PURE__ */c("div",{className:"lb:grid lb:grid-cols-2 lb:gap-2",children:[
|
|
487
|
-
/* @__PURE__ */s("button",{onClick:()=>
|
|
488
|
-
/* @__PURE__ */s("button",{onClick:()=>
|
|
489
|
-
/* @__PURE__ */s("button",{onClick:()=>
|
|
490
|
-
/* @__PURE__ */s("button",{onClick:()=>
|
|
488
|
+
/* @__PURE__ */s("button",{onClick:()=>Ve(.5),className:"lb:p-1 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-xs lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200",disabled:fe,"aria-label":"Selección 50%",title:"Tamaño de selector 50%",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{children:"50%"})})}),
|
|
489
|
+
/* @__PURE__ */s("button",{onClick:()=>Ve(.7),className:"lb:p-1 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-xs lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200",disabled:fe,"aria-label":"Selección 70%",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{children:"70%"})})}),
|
|
490
|
+
/* @__PURE__ */s("button",{onClick:()=>Ve(.9),className:"lb:p-1 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-xs lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200",disabled:fe,"aria-label":"Selección 90%",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{children:"90%"})})}),
|
|
491
|
+
/* @__PURE__ */s("button",{onClick:()=>Ve(1),className:"lb:p-1 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-xs lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200",disabled:fe,"aria-label":"Selección completa",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{children:"100%"})})})]})}),
|
|
491
492
|
/* @__PURE__ */c("div",{className:"lb:space-y-2 lb:pt-2",children:[
|
|
492
|
-
/* @__PURE__ */s("button",{onClick:
|
|
493
|
+
/* @__PURE__ */s("button",{onClick:je,className:"lb:w-full lb:p-1 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200",title:"Centrar selección",disabled:fe,"aria-label":"Centrar área de selección",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */c("span",{children:[
|
|
493
494
|
/* @__PURE__ */s("span",{className:"icon icon-radio-button icon--sm lb:align-[middle!important] "})," ","Centrar selección"]})})}),
|
|
494
|
-
/* @__PURE__ */s("button",{onClick:
|
|
495
|
+
/* @__PURE__ */s("button",{onClick:Fe,className:"lb:w-full lb:p-1 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200",title:"Reiniciar selección",disabled:fe,"aria-label":"Reiniciar área de selección",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */c("span",{children:[
|
|
495
496
|
/* @__PURE__ */s("span",{className:"icon icon-refresh icon--sm lb:align-[middle!important]"})," ","Reset selección"]})})})]})]})]}),
|
|
496
497
|
/* @__PURE__ */c("div",{className:"lb:bg-white lb:rounded lb:border lb:border-gray-200 lb:w-full",children:[
|
|
497
|
-
/* @__PURE__ */s("button",{onClick:
|
|
498
|
+
/* @__PURE__ */s("button",{onClick:Ie,className:"lb:hidden lb:sm:block lb:w-full lb:cursor-pointer lb:hover:bg-neutral-gray-050/50 lb:transition-colors lb:rounded-t-sm lb:mb-05 lb:p-2","aria-expanded":H,"aria-label":"Mostrar/ocultar opciones de visualización",children:/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:justify-between",children:[
|
|
498
499
|
/* @__PURE__ */s("h3",{className:"lb:text-sm lb:font-semibold lb:text-gray-700",children:"Visualización"}),
|
|
499
|
-
/* @__PURE__ */s("div",{className:"lb:text-center",children:/* @__PURE__ */s("span",{className:`icon ${
|
|
500
|
-
/* @__PURE__ */c("div",{className:"lb:py-2 lb:space-y-2 lb:justify-items-stretch lb:static "+(
|
|
501
|
-
/* @__PURE__ */c("button",{onClick:
|
|
500
|
+
/* @__PURE__ */s("div",{className:"lb:text-center",children:/* @__PURE__ */s("span",{className:`icon ${H?"icon-chevron-up":"icon-chevron-down"} lb:text-center icon--xs`})})]})}),
|
|
501
|
+
/* @__PURE__ */c("div",{className:"lb:py-2 lb:space-y-2 lb:justify-items-stretch lb:static "+(H?"lb:block":"lb:sm:hidden"),children:[
|
|
502
|
+
/* @__PURE__ */c("button",{onClick:Me,className:"lb:w-auto lb:flex lb:cursor-pointer lb:items-center lb:justify-between lb:mx-2 lb:p-1 lb:rounded lb:transition-colors "+(N?"lb:bg-blue-100 lb:border lb:border-blue-300 lb:text-blue-800":"lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200"),disabled:fe,"aria-pressed":N,title:"Mostrar/ocultar cuadrícula de la regla de los tercios en el selector","aria-label":"Activar/desactivar grid",children:[
|
|
502
503
|
/* @__PURE__ */c("span",{className:"lb:text-sm lb:flex lb:items-center",children:[
|
|
503
504
|
/* @__PURE__ */s("span",{className:"icon icon-area-blue lb:me-1"})," ","Cuadrícula"]}),
|
|
504
505
|
/* @__PURE__ */s("span",{className:"lb:text-xs",children:N?/* @__PURE__ */c(u,{children:[
|
|
505
506
|
/* @__PURE__ */s("span",{className:"icon icon-tick icon--xs lb:align-[middle!important] lb:-mt-0.5"})," ","Activo"]}):"Inactivo"})]}),
|
|
506
|
-
/* @__PURE__ */c("button",{onClick:
|
|
507
|
+
/* @__PURE__ */c("button",{onClick:Pe,className:"lb:w-auto lb:flex lb:cursor-pointer lb:items-center lb:justify-between lb:mx-2 lb:p-1 lb:rounded lb:transition-colors "+(E?"lb:bg-blue-100 lb:border lb:border-blue-300 lb:text-blue-800":"lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200"),disabled:fe,"aria-pressed":E,"aria-label":"Activar/desactivar sombreado",children:[
|
|
507
508
|
/* @__PURE__ */c("span",{className:"lb:text-sm lb:flex lb:items-center",children:[
|
|
508
509
|
/* @__PURE__ */s("span",{className:"icon icon-comparison-blue lb:me-1"})," ","Tablero"]}),
|
|
509
510
|
/* @__PURE__ */s("span",{className:"lb:text-xs",children:E?/* @__PURE__ */c(u,{children:[
|
|
510
511
|
/* @__PURE__ */s("span",{className:"icon icon-tick icon--xs lb:align-[middle!important] lb:-mt-0.5"})," ","Activo"]}):"Inactivo"})]})]})]})]})})]}),
|
|
511
512
|
/* @__PURE__ */c("div",{className:"lb:flex lb:justify-between lb:shrink-0 lb:border-t lb:border-gray-200 lb:bg-white lb:mx-2 lb:mt-1 lb:py-2 lb:lg:gap-0",children:[
|
|
512
|
-
/* @__PURE__ */c("button",{onClick:()=>
|
|
513
|
+
/* @__PURE__ */c("button",{onClick:()=>V(!0),className:"lb:text-nowrap lb:block lb:cursor-pointer lb:lg:flex lb:items-center lb:gap-2 lb:px-2 lb:py-1 lb:bg-gradient-to-br lb:from-brand-blue-50 lb:to-green-50 lb:hover:from-brand-blue-100 lb:hover:to-green-100 lb:border lb:border-blue-200 lb:rounded-lg lb:shadow-sm lb:transition-colors","aria-label":"Abrir guía de uso",children:[
|
|
513
514
|
/* @__PURE__ */s("span",{className:"icon icon-lightbulb lb:text-yellow-500"}),
|
|
514
515
|
/* @__PURE__ */s("span",{className:"lb:text-sm lb:font-semibold lb:text-blue-800",children:"Guía de uso"}),
|
|
515
516
|
/* @__PURE__ */s("span",{className:"icon icon-arrow-down lb:scale-75 lb:-rotate-145"})]}),
|
|
516
|
-
/* @__PURE__ */s("button",{onClick:
|
|
517
|
+
/* @__PURE__ */s("button",{onClick:at,disabled:fe||!ze,className:`lb:px-3 lb:cursor-pointer lb:py-1.5 lb:text-sm lb:rounded lb:transition-colors ${v?"lb:bg-red-1000 lb:hover:bg-red-800 lb:text-white":"lb:bg-brand-blue-800 lb:hover:bg-brand-blue-1000 lb:text-white"} lb:disabled:opacity-50 lb:disabled:cursor-not-allowed`,"aria-label":"Vista previa",title:"Mostrar/Ocultar vista previa",children:/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-1",children:[
|
|
517
518
|
/* @__PURE__ */s("span",{className:"icon icon-search-white icon--sm"}),
|
|
518
519
|
/* @__PURE__ */s("span",{className:"lb:hidden lb:sm:inline lb:whitespace-nowrap",children:v?"Cerrar previa":"Vista previa"})]})}),
|
|
519
520
|
/* @__PURE__ */c("div",{className:"lb:flex lb:flex-row lb:gap-1 lb:lg:gap-2 lb:items-center lb:justify-end",children:[
|
|
520
|
-
/* @__PURE__ */s("button",{onClick:
|
|
521
|
+
/* @__PURE__ */s("button",{onClick:yt,disabled:fe||!ze,className:"lb:cursor-pointer lb:px-3 lb:py-1.5 lb:text-sm lb:rounded lb:bg-brand-blue-800 lb:hover:bg-brand-blue-1000 lb:text-white lb:transition-colors lb:disabled:opacity-50 lb:disabled:cursor-not-allowed","aria-label":"Descargar",title:"Descargar recorte sin guardar",children:/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-1",children:[
|
|
521
522
|
/* @__PURE__ */s("span",{className:"icon icon-download-white icon--sm"}),
|
|
522
523
|
/* @__PURE__ */s("span",{className:"lb:hidden lb:md:inline lb:whitespace-nowrap",children:"Descargar"})]})}),
|
|
523
|
-
/* @__PURE__ */s("button",{onClick:
|
|
524
|
+
/* @__PURE__ */s("button",{onClick:xt,disabled:fe||f,className:"lb:px-3 lb:cursor-pointer lb:py-1.5 lb:text-sm lb:rounded lb:bg-teal-600 lb:hover:bg-teal-700 lb:text-white lb:transition-colors lb:disabled:opacity-50 lb:disabled:cursor-not-allowed","aria-label":"Conservar solo imagen original sin crear recortes",title:e.file?"Subir y guardar la imagen original sin crear recortes":"Seleccionar la imagen original sin crear recortes",children:/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-1",children:[
|
|
524
525
|
/* @__PURE__ */s("span",{className:"icon icon-tick-white icon--sm"}),
|
|
525
526
|
/* @__PURE__ */s("span",{className:"lb:hidden lb:md:inline lb:whitespace-nowrap",children:"Guardar sin recortar"})]})}),
|
|
526
|
-
/* @__PURE__ */s("button",{onClick:
|
|
527
|
+
/* @__PURE__ */s("button",{onClick:pt,disabled:fe||!$e||!Ae||!ze||!we.isReady,className:"lb:px-3 lb:cursor-pointer lb:py-1.5 lb:text-sm lb:rounded lb:bg-green-600 lb:hover:bg-green-700 lb:text-white lb:transition-colors lb:disabled:opacity-50 lb:disabled:cursor-not-allowed",title:"Guardar imagen recortada",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:gap-1",children:/* @__PURE__ */c(u,fe?{children:[
|
|
527
528
|
/* @__PURE__ */s("span",{className:"icon icon-save-white icon--sm"}),
|
|
528
529
|
/* @__PURE__ */s("span",{children:"Guardando..."})]}:{children:[
|
|
529
530
|
/* @__PURE__ */s("span",{className:"icon icon-save-white icon--sm"}),
|
|
530
|
-
/* @__PURE__ */s("span",{className:"lb:hidden lb:md:inline lb:whitespace-nowrap",children:"Guardar recorte"})]})})})]})]}),
|
|
531
|
+
/* @__PURE__ */s("span",{className:"lb:hidden lb:md:inline lb:whitespace-nowrap",children:"Guardar recorte"})]})})})]})]}),se&&/* @__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-[9999] lb:p-4",children:/* @__PURE__ */c("div",{className:"lb:bg-white lb:rounded-lg lb:shadow-xl lb:max-w-lg lb:w-full lb:max-h-[80vh] lb:overflow-hidden lb:flex lb:flex-col",children:[
|
|
531
532
|
/* @__PURE__ */c("div",{className:"lb:px-6 lb:py-4 lb:border-b lb:border-gray-200",children:[
|
|
532
|
-
/* @__PURE__ */s("h3",{className:"lb:text-lg lb:font-semibold lb:text-gray-800",children:"save"===
|
|
533
|
-
/* @__PURE__ */c("p",{className:"lb:text-sm lb:text-gray-600 lb:mt-1",children:["Marca los recortes que deseas"," ","save"===
|
|
534
|
-
/* @__PURE__ */s("div",{className:"lb:px-6 lb:py-4 lb:overflow-y-auto lb:flex-1",children:/* @__PURE__ */s("div",{className:"lb:space-y-2",children:
|
|
535
|
-
return c("label",{className:`lb:flex lb:items-center lb:gap-3 lb:p-3 lb:rounded lb:border lb:transition-colors ${
|
|
536
|
-
/* @__PURE__ */s("input",{type:"checkbox",checked:
|
|
533
|
+
/* @__PURE__ */s("h3",{className:"lb:text-lg lb:font-semibold lb:text-gray-800",children:"save"===be?"Seleccionar recortes a guardar":"Seleccionar recortes a descargar"}),
|
|
534
|
+
/* @__PURE__ */c("p",{className:"lb:text-sm lb:text-gray-600 lb:mt-1",children:["Marca los recortes que deseas"," ","save"===be?"guardar":"descargar"]})]}),
|
|
535
|
+
/* @__PURE__ */s("div",{className:"lb:px-6 lb:py-4 lb:overflow-y-auto lb:flex-1",children:/* @__PURE__ */s("div",{className:"lb:space-y-2",children:te.map((e,t)=>{const n=e.savedState||t===le,l=!e.required&&!n,r=e.required&&"save"===be;/* @__PURE__ */
|
|
536
|
+
return c("label",{className:`lb:flex lb:items-center lb:gap-3 lb:p-3 lb:rounded lb:border lb:transition-colors ${ue.includes(t)?"lb:bg-blue-50 lb:border-blue-300":l?"lb:bg-gray-100 lb:border-gray-300 lb:opacity-60":"lb:bg-gray-50 lb:border-gray-200 lb:hover:bg-gray-100"} ${l||r?"lb:cursor-not-allowed":"lb:cursor-pointer"}`,title:r?"Este recorte es obligatorio y debe ser guardado":"",children:[
|
|
537
|
+
/* @__PURE__ */s("input",{type:"checkbox",checked:ue.includes(t),disabled:l||r,onChange:e=>{e.target.checked?de(e=>[...e,t]):de(e=>e.filter(e=>e!==t))},className:"lb:w-4 lb:h-4 lb:text-blue-600"}),
|
|
537
538
|
/* @__PURE__ */c("div",{className:"lb:flex-1 lb:min-w-0",children:[
|
|
538
539
|
/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-2 lb:flex-wrap",children:[
|
|
539
540
|
/* @__PURE__ */c("span",{title:"Nombre del archivo a descargar",className:"lb:text-sm lb:font-medium lb:text-gray-800 lb:truncate",children:[e.label,"_",e.width,"_",e.height]}),e.required&&/* @__PURE__ */s("span",{className:"lb:text-xs lb:px-1.5 lb:py-0.5 lb:bg-red-200 lb:text-red-1000 lb:rounded lb:whitespace-nowrap",children:"Obligatorio"}),!n&&!e.required&&/* @__PURE__ */s("span",{className:"lb:text-xs lb:px-1.5 lb:py-0.5 lb:bg-orange-100 lb:text-orange-700 lb:rounded lb:whitespace-nowrap",children:"Sin configurar"})]}),
|
|
540
541
|
/* @__PURE__ */c("span",{title:"Dimensiones del recorte",className:"lb:text-xs lb:text-gray-500",children:[e.width," × ",e.height," px"]})]})]},e.id)})})}),
|
|
541
542
|
/* @__PURE__ */c("div",{className:"lb:px-6 lb:py-4 lb:border-t lb:border-gray-200 lb:flex lb:gap-3 lb:justify-end",children:[
|
|
542
|
-
/* @__PURE__ */s("button",{onClick:()=>{
|
|
543
|
-
/* @__PURE__ */c("button",{onClick:async()=>{if(
|
|
543
|
+
/* @__PURE__ */s("button",{onClick:()=>{ce(!1),me(null),de([])},className:"limbo-btn limbo-btn-secondary lb:px-4 lb:py-2",children:"Cancelar"}),
|
|
544
|
+
/* @__PURE__ */c("button",{onClick:async()=>{if(ce(!1),"save"===be)if(1===ue.length){const e=le;re(ue[0]),await new Promise(e=>setTimeout(e,100)),await mt(),re(e)}else await ht(ue);else if(1===ue.length){const e=le;re(ue[0]),await new Promise(e=>setTimeout(e,100)),await vt(),re(e)}else await gt(ue);me(null),de([])},disabled:0===ue.length,className:"limbo-btn limbo-btn-primary lb:px-4 lb:py-2 lb:disabled:opacity-50 lb:disabled:cursor-not-allowed",children:["save"===be?"Guardar":"Descargar"," (",ue.length,")"]})]})]})}),q&&/* @__PURE__ */s("div",{className:"lb:fixed lb:inset-0 lb:bg-black/50 lb:flex lb:items-center lb:justify-center lb:z-[9999] lb:p-4",children:/* @__PURE__ */c("div",{className:"lb:bg-white lb:rounded-lg lb:shadow-xl lb:max-w-5xl lb:w-full lb:max-h-[90vh] lb:overflow-hidden lb:flex lb:flex-col",children:[
|
|
544
545
|
/* @__PURE__ */s("div",{className:"lb:px-6 lb:py-4 lb:border-b lb:border-gray-200 lb:bg-brand-blue-50",children:/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:justify-between",children:[
|
|
545
546
|
/* @__PURE__ */c("h3",{className:"lb:text-xl lb:font-semibold lb:text-brand-blue-1000 lb:flex lb:items-center lb:gap-2",children:[
|
|
546
547
|
/* @__PURE__ */s("span",{className:"icon icon-lightbulb lb:text-yellow-500"}),"Guía de uso del Cropper"]}),
|
|
547
|
-
/* @__PURE__ */s("button",{onClick:()=>
|
|
548
|
+
/* @__PURE__ */s("button",{onClick:()=>V(!1),className:"lb:text-gray-400 lb:hover:text-gray-600 lb:p-1 lb:rounded-full lb:hover:bg-gray-100 lb:transition-colors","aria-label":"Cerrar modal",children:/* @__PURE__ */s("span",{className:"icon icon-close-small icon--lg"})})]})}),
|
|
548
549
|
/* @__PURE__ */c("div",{className:"lb:px-6 lb:py-4 lb:overflow-y-auto lb:flex-1 lb:space-y-4",children:[
|
|
549
550
|
/* @__PURE__ */c("div",{className:"lb:bg-brand-blue-50 lb:rounded-lg lb:p-4 lb:border-l-4 lb:border-brand-blue-400",children:[
|
|
550
551
|
/* @__PURE__ */s("h4",{className:"lb:font-semibold lb:text-brand-blue-1000 lb:mb-3 lb:text-base lb:flex lb:items-center lb:gap-2",children:"🖱️ Navegación básica"}),
|
|
@@ -646,8 +647,8 @@ return c("label",{className:`lb:flex lb:items-center lb:gap-3 lb:p-3 lb:rounded
|
|
|
646
647
|
/* @__PURE__ */s("span",{className:"lb:font-bold lb:min-w-fit",children:"•"}),
|
|
647
648
|
/* @__PURE__ */c("div",{children:[
|
|
648
649
|
/* @__PURE__ */s("strong",{children:"Cambios pendientes:"})," Recuerda guardar tus cambios antes de cerrar o cambiar de imagen"]})]})]})]})]}),
|
|
649
|
-
/* @__PURE__ */s("div",{className:"lb:px-6 lb:py-4 lb:border-t lb:border-gray-200 lb:bg-gray-50",children:/* @__PURE__ */s("button",{onClick:()=>
|
|
650
|
-
/* @__PURE__ */c("div",{className:"limbo-preview-modal-header lb:px-4 lb:py-3 lb:bg-linear-to-r lb:from-brand-blue-800 lb:to-brand-blue-1000 lb:text-white lb:flex lb:items-center lb:justify-between lb:cursor-grab lb:active:cursor-grabbing lb:select-none",style:{cursor:
|
|
650
|
+
/* @__PURE__ */s("div",{className:"lb:px-6 lb:py-4 lb:border-t lb:border-gray-200 lb:bg-gray-50",children:/* @__PURE__ */s("button",{onClick:()=>V(!1),className:"limbo-btn limbo-btn-primary lb:w-full",children:"Entendido"})})]})}),v&&/* @__PURE__ */s("div",{className:"lb:min-w-[90%] lb:fixed lb:md:absolute lb:inset-0 lb:md:inset-auto lb:bg-black/50 lb:md:bg-transparent lb:flex lb:items-center lb:justify-center lb:md:block lb:z-9999 lb:md:z-50 lb:pointer-events-none",onClick:e=>{e.target===e.currentTarget&&window.innerWidth<768&&(y(!1),x(null))},children:/* @__PURE__ */c("div",{className:"lb:pointer-events-auto lb:bg-white lb:rounded-lg lb:shadow-2xl lb:border-2 lb:border-brand-blue-800 lb:overflow-hidden lb:flex lb:flex-col lb:max-w-md lb:w-full lb:mx-4 lb:md:mx-0 lb:max-h-[80vh] lb:md:max-h-[600px]",style:{...window.innerWidth>=768?{position:"absolute",left:`${z.x}px`,top:`${z.y}px`,width:"420px",cursor:A?"grabbing":"default"}:{}},onMouseDown:it,onTouchStart:ct,children:[
|
|
651
|
+
/* @__PURE__ */c("div",{className:"limbo-preview-modal-header lb:px-4 lb:py-3 lb:bg-linear-to-r lb:from-brand-blue-800 lb:to-brand-blue-1000 lb:text-white lb:flex lb:items-center lb:justify-between lb:cursor-grab lb:active:cursor-grabbing lb:select-none",style:{cursor:A?"grabbing":"grab"},children:[
|
|
651
652
|
/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-2",children:[
|
|
652
653
|
/* @__PURE__ */s("span",{className:"icon icon-search-white icon--sm"}),
|
|
653
654
|
/* @__PURE__ */s("h3",{className:"lb:text-sm lb:font-semibold lb:text-white",children:"Vista previa"})]}),
|
|
@@ -655,26 +656,26 @@ return c("label",{className:`lb:flex lb:items-center lb:gap-3 lb:p-3 lb:rounded
|
|
|
655
656
|
/* @__PURE__ */s("div",{className:"lb:flex-1 lb:overflow-auto lb:bg-gray-50 lb:p-4",children:k?/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center lb:h-full lb:min-h-[200px]",children:/* @__PURE__ */c("div",{className:"lb:text-center",children:[
|
|
656
657
|
/* @__PURE__ */s("div",{className:"lb:animate-spin lb:rounded-full lb:h-12 lb:w-12 lb:border-b-2 lb:border-blue-600 lb:mx-auto lb:mb-3"}),
|
|
657
658
|
/* @__PURE__ */s("p",{className:"lb:text-sm lb:text-gray-600",children:"Generando vista previa..."})]})}):w?/* @__PURE__ */c("div",{className:"lb:flex lb:flex-col lb:items-center lb:gap-3",children:[
|
|
658
|
-
/* @__PURE__ */c("div",{className:"lb:relative lb:w-full lb:bg-white lb:rounded-lg lb:border lb:border-gray-200 lb:overflow-hidden lb:shadow-sm lb:cursor-zoom-in lb:hover:ring-2 lb:hover:ring-brand-blue-800 lb:transition-all",onClick:()=>
|
|
659
|
+
/* @__PURE__ */c("div",{className:"lb:relative lb:w-full lb:bg-white lb:rounded-lg lb:border lb:border-gray-200 lb:overflow-hidden lb:shadow-sm lb:cursor-zoom-in lb:hover:ring-2 lb:hover:ring-brand-blue-800 lb:transition-all",onClick:()=>O(!0),role:"button",tabIndex:0,onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),O(!0))},"aria-label":"Click para ver recorte en tamaño completo",title:"Click para ampliar",children:[
|
|
659
660
|
/* @__PURE__ */s("img",{src:w,alt:"Vista previa del recorte",className:"lb:w-full lb:h-auto lb:object-contain lb:max-h-[400px]"}),
|
|
660
661
|
/* @__PURE__ */c("div",{className:"lb:absolute lb:top-2 lb:right-2 lb:bg-black/60 lb:text-white lb:px-2 lb:py-1 lb:rounded lb:text-xs lb:flex lb:items-center lb:gap-1",children:[
|
|
661
662
|
/* @__PURE__ */s("span",{className:"icon icon-search-white icon--xs"}),
|
|
662
663
|
/* @__PURE__ */s("span",{children:"Ampliar"})]})]}),
|
|
663
664
|
/* @__PURE__ */c("div",{className:"lb:text-center lb:text-xs lb:text-gray-500",children:[
|
|
664
|
-
/* @__PURE__ */s("p",{className:"lb:font-medium lb:text-gray-700 lb:mb-1",children:
|
|
665
|
-
/* @__PURE__ */c("p",{children:[
|
|
665
|
+
/* @__PURE__ */s("p",{className:"lb:font-medium lb:text-gray-700 lb:mb-1",children:ae?.label||"Recorte"}),
|
|
666
|
+
/* @__PURE__ */c("p",{children:[ae?.width," × ",ae?.height," px"]})]})]}):/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center lb:h-full lb:min-h-[200px]",children:/* @__PURE__ */s("p",{className:"lb:text-sm lb:text-gray-500",children:"No se pudo generar la vista previa"})})}),
|
|
666
667
|
/* @__PURE__ */s("div",{className:"lb:px-4 lb:py-2 lb:bg-gray-100 lb:border-t lb:border-gray-200",children:/* @__PURE__ */c("p",{className:"lb:text-xs lb:text-gray-600 lb:text-center",children:[
|
|
667
668
|
/* @__PURE__ */c("span",{className:"lb:hidden lb:md:inline",children:["Arrastra desde el título para mover •"," "]}),"Actualización automática al editar"]})})]})}),
|
|
668
|
-
/* @__PURE__ */s(Te,{src:w,alt:"Vista previa del recorte",title:
|
|
669
|
+
/* @__PURE__ */s(Te,{src:w,alt:"Vista previa del recorte",title:ae?.label||"Recorte",subtitle:`${ae?.width||0} × ${ae?.height||0} px`,isOpen:D&&!!w,onClose:()=>O(!1)})]}):null}function il({currentPage:t,totalPages:n,onPageChange:l,disabled:r=!1}){if(!n||n<=1)return null;const a=(()=>{const e=[],l=[],r=Math.max(1,t-2),a=Math.min(n,t+2);for(let t=r;t<=a;t++)e.push(t);return r>1&&(l.push(1),r>2&&l.push("...")),l.push(...e),a<n&&(a<n-1&&l.push("..."),l.push(n)),l})();/* @__PURE__ */
|
|
669
670
|
return s("div",{className:"lb:flex lb:flex-col lb:items-center lb:justify-center lb:space-x-2 lb:py-4",children:/* @__PURE__ */c("div",{className:"lb:flex lb:space-x-2 lb:mt-2",children:[
|
|
670
671
|
/* @__PURE__ */c("button",{onClick:()=>{t>1&&l(t-1)},disabled:r||t<=1,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<=1?"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:[
|
|
671
672
|
/* @__PURE__ */s("span",{className:"icon icon-arrow-left icon--sm"})," Anterior"]}),
|
|
672
673
|
/* @__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}`))}),
|
|
673
674
|
/* @__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 ",
|
|
674
|
-
/* @__PURE__ */s("span",{className:"icon icon-arrow-right icon--sm"})]})]})})}function
|
|
675
|
+
/* @__PURE__ */s("span",{className:"icon icon-arrow-right icon--sm"})]})]})})}function ol({text:e="Cargando..."}){/* @__PURE__ */
|
|
675
676
|
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:[
|
|
676
677
|
/* @__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"})}),
|
|
677
|
-
/* @__PURE__ */s("p",{className:"lb:text-sm",id:"loader-text",children:e})]})}function
|
|
678
|
+
/* @__PURE__ */s("p",{className:"lb:text-sm",id:"loader-text",children:e})]})}function sl({isOpen:e,onReload:t,onClose:n}){return e?/* @__PURE__ */s("div",{className:"lb:fixed lb:inset-0 lb:bg-black/50 lb:flex lb:items-center lb:justify-center lb:z-[9999]",onClick:e=>{e.target===e.currentTarget&&n?.()},children:/* @__PURE__ */c("div",{className:"lb:bg-white lb:rounded-lg lb:p-6 lb:max-w-sm lb:w-full lb:mx-4 lb:shadow-xl",children:[
|
|
678
679
|
/* @__PURE__ */c("div",{className:"lb:flex lb:items-start lb:gap-3 lb:mb-4",children:[
|
|
679
680
|
/* @__PURE__ */s("div",{className:"lb:flex-shrink-0 lb:w-10 lb:h-10 lb:bg-amber-100 lb:rounded-full lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("svg",{className:"lb:w-5 lb:h-5 lb:text-amber-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"})})}),
|
|
680
681
|
/* @__PURE__ */c("div",{children:[
|
|
@@ -686,23 +687,23 @@ return c("div",{className:"lb:absolute lb:inset-0 lb:bg-neutral-gray-1000/20 lb:
|
|
|
686
687
|
/* @__PURE__ */s("li",{children:"Recarga la página para continuar con tu trabajo."}),
|
|
687
688
|
/* @__PURE__ */s("li",{children:"Si el problema persiste, cierra sesión y vuelve a entrar."})]})]}),
|
|
688
689
|
/* @__PURE__ */c("div",{className:"lb:flex lb:justify-end lb:gap-2",children:[n&&/* @__PURE__ */s("button",{type:"button",onClick:n,className:"lb:px-4 lb:py-2 lb:text-sm lb:font-medium lb:text-gray-700 lb:border lb:border-gray-300 lb:rounded-md lb:hover:bg-gray-50 lb:transition-colors",children:"Ignorar"}),
|
|
689
|
-
/* @__PURE__ */s("button",{type:"button",onClick:t,className:"lb:px-4 lb:py-2 lb:text-sm lb:font-medium lb:bg-brand-blue-800 lb:text-white lb:rounded-md lb:hover:bg-brand-blue-1000 lb:transition-colors",children:"Recargar página"})]})]})}):null}function
|
|
690
|
+
/* @__PURE__ */s("button",{type:"button",onClick:t,className:"lb:px-4 lb:py-2 lb:text-sm lb:font-medium lb:bg-brand-blue-800 lb:text-white lb:rounded-md lb:hover:bg-brand-blue-1000 lb:transition-colors",children:"Recargar página"})]})]})}):null}function cl(){const[e,n]=t(!1),[l,r]=t(null);return{deleteImg:async e=>{if(!e)return r("ID de imagen no proporcionado"),!1;n(!0),r(null);try{const t=await async function(e){try{return await le({endpoint:`/assets/${e}`,method:"DELETE",basePath:de,useJWT:!0})}catch(l){throw ue(l)}}(e);return!1!==t.success}catch(t){return r(t.message),!1}finally{n(!1)}},loading:e,error:l,reset:()=>{r(null)}}}const ul=/* @__PURE__ */new Map,dl=6e5,bl="limbo_gallery_cache";function ml(e,l=!1,a={},o=!0){const s=i(()=>JSON.stringify(a),[a]),c=r((()=>{const e=s,t=ul.get(e),n=Date.now();return t&&n-t.timestamp<dl?{images:t.data,pagination:t.pagination||null,loading:!1}:{images:[],pagination:null,loading:o}})()),[u,d]=t(c.current.images),[b,m]=t(c.current.loading),[h,p]=t(null),[f,g]=t(c.current.pagination),[v,y]=t(0),[w,x]=t(0);n(()=>{if(!o)return void m(!1);const e=`${s}`,t=ul.get(e),n=Date.now();if(t&&n-t.timestamp<dl)return d(t.data),g(t.pagination||null),void m(!1);let l=!0;return(async()=>{if(v>=3)l&&(p("Error de autenticación: Verifica tus credenciales API"),m(!1));else try{const t=await be(a);if(!l)return;const r=t.result||t.data||[],i=t.pagination||null;d(r),g(i),p(null),y(0),ul.set(e,{data:r,pagination:i,timestamp:n}),(()=>{try{const e={};ul.forEach((t,n)=>{e[n]=t}),sessionStorage.setItem(bl,JSON.stringify(e))}catch{}})()}catch(t){l&&(p(t.message),y(e=>e+1))}finally{l&&m(!1)}})(),()=>{l=!1}},[e,l,s,v,a,o,w]);return{images:u,loading:b,error:h,pagination:f,setImages:d,invalidateCache:()=>{ul.clear();try{sessionStorage.removeItem(bl)}catch{}},refetch:()=>{ul.clear();try{sessionStorage.removeItem(bl)}catch{}m(!0),x(e=>e+1)}}}function hl(e,l=500){const[r,a]=t(e);return n(()=>{const t=setTimeout(()=>{a(e)},l);return()=>{clearTimeout(t)}},[e,l]),r}function pl(){/* @__PURE__ */
|
|
690
691
|
return c("div",{className:"lb:flex lb:items-center lb:justify-center lb:gap-2 lb:py-2 lb:px-4 lb:border-t lb:h-8 lb:border-brand-purple-200 lb:bg-brand-purple-50 lb:rounded-b-md lb:mt-3",style:{background:"linear-gradient(90deg,#001978,#2134f1 50%,#f81bbd 95%)",color:"white"},children:[
|
|
691
692
|
/* @__PURE__ */c("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 48 52",fill:"currentColor",className:"lb:w-5 lb:h-5 lb:text-white","aria-hidden":"true",children:[
|
|
692
693
|
/* @__PURE__ */s("path",{d:"M29.0863 15.2704H24.9419V36.7321H37.5259V33.1048H29.0863V15.2704Z"}),
|
|
693
694
|
/* @__PURE__ */s("path",{d:"M18.1601 33.1048H9.72056V36.7321H22.3045V15.2704H18.1601V33.1048Z"}),
|
|
694
695
|
/* @__PURE__ */s("path",{d:"M44.0063 51.846L3.16483 50.1834C1.35636 50.1834 0 48.5965 0 46.8584V4.99294C0 3.33041 1.65777 1.8946 3.31554 1.81903L44.157 0.1565C46.2669 0.0809304 48 1.74346 48 3.8594V47.8408C48 50.0323 46.1915 51.846 43.9309 51.7704H44.0063V51.846ZM4.89796 46.405L42.9513 47.4629C43.4788 47.4629 44.0063 47.0095 44.0063 46.4805V5.21965C44.0063 4.69066 43.6295 4.31282 43.102 4.31282L4.82261 5.67307C4.14443 5.67307 3.61695 6.27762 3.61695 6.95775V45.1203C3.61695 45.8004 4.14443 46.3294 4.82261 46.405H4.89796Z"})]}),
|
|
695
696
|
/* @__PURE__ */c("span",{className:"lb:text-xs lb:text-neutral-50",children:["Powered by ",
|
|
696
|
-
/* @__PURE__ */s("span",{className:"lb:font-semibold lb:text-white",children:"Limbo"})]})]})}function
|
|
697
|
-
return c(u,{children:[m.showTabs&&"cropper"!=I&&/* @__PURE__ */s(P,{tabs:ye,active:I,onChange:e=>{D(e),"upload"!==e&&Y(),"gallery"!==e&&le()}}),se&&/* @__PURE__ */c(
|
|
697
|
+
/* @__PURE__ */s("span",{className:"lb:font-semibold lb:text-white",children:"Limbo"})]})]})}function fl({apiKey:a,prod:i=!1,url:o=!0,features:d=["gallery","upload","cropper"],modeUI:b="full",ui:m={showActions:["select","download","copy","delete","crop","variants","rename"],hideActions:[],theme:"light",language:"es",compactMode:!1,showTabs:!0},callbacks:h={},instanceId:p=null,itemsPerPage:g=30,_externalImage:v=null,cropperConfig:y=null,folderConfig:w={include:[],exclude:[],includeNoFolder:!0,showFolderSelector:!0,showFolderFilter:!0,showFolderInfo:!0,allowMoveFolder:!0,allowCreateFolder:!0,defaultFolder:null},allowedCategories:x=null,accept:k=null,returnConfig:C=null}){sessionStorage.removeItem("limbo_stock_selectedService"),sessionStorage.removeItem("limbo_stock_dynamicForm"),sessionStorage.removeItem("limbo_stock_stockImages"),sessionStorage.removeItem("limbo_stock_currentPage"),sessionStorage.removeItem("limbo_stock_paginationInfo"),sessionStorage.removeItem("limbo_portals_searchName"),sessionStorage.removeItem("limbo_portals_limit"),sessionStorage.removeItem("limbo_portals_currentPage"),sessionStorage.removeItem("limbo_portals_images"),sessionStorage.removeItem("limbo_portals_portalResults"),sessionStorage.removeItem("limbo_portals_paginationInfo");const[N,S]=t({name:"",uploadedBy:"",dateFrom:"",dateTo:"",assetType:"",folder:""}),[E,$]=t(w?.defaultFolder||null),_=hl(N.name,400),T=hl(N.uploadedBy,400),z=e.useMemo(()=>f(k||(x?x.map(e=>`${e}/*`).join(","):null)),[k,x]),L=e=>!!e&&(e.startsWith("image/")&&"image/gif"!==e),A=(()=>{let e;switch(b){case"gallery-only":e=["gallery"];break;case"upload-only":e=["upload","cropper"];break;case"crop-only":e=["cropper"];break;case"ia-only":e=["ia"];break;default:e=[...d]}return z.isAllTypes||z.includesImages||(e=e.filter(e=>"cropper"!==e)),e})(),M=()=>A.includes("gallery")?"gallery":A.includes("upload")?"upload":A.includes("cropper")?"cropper":A.includes("ia")?"ia":A[0]||"gallery",[I,D]=t(M()),[O,R]=t(null),j=r(null);n(()=>{!O&&j.current&&(URL.revokeObjectURL(j.current),j.current=null)},[O]);const[F,U]=t(null);n(()=>{v&&(console.log("📸 Imagen externa detectada:",v),R(v),D("cropper"))},[v]),n(()=>{const e=()=>{console.log("[App] Modal cerrado, reseteando estado..."),R(null),D(M())};return window.limboCore?.events&&window.limboCore.events.on("modal:closed",e),()=>{window.limboCore?.events&&window.limboCore.events.off("modal:closed",e)}},[]);const[B,W]=t(1),{isTokenExpired:q,handleTokenExpiredClose:V,handleTokenExpiredReload:H}=function(){const[e,r]=t(!1),[a,i]=t(!1),o=l(async()=>{const e=ne();if("jwt"!==e.authMode||!e.tokenProvider)return!1;i(!0);try{return te(await e.tokenProvider()),r(!1),!0}catch{return!1}finally{i(!1)}},[]),s=l(e=>{if(401===e?.response?.status){const t=e.response.data;if("token_expired"===t?.error||t?.message?.includes("expired")||t?.message?.includes("caducado")||"string"==typeof t?.error&&t.error.includes("expired"))return r(!0),!0}return!1},[]),c=l(()=>{r(!1)},[]),u=l(()=>{r(!1),window.location.reload()},[]);return n(()=>{const e=e=>{if(e.detail?.error&&s(e.detail.error)){const e=ne();"jwt"===e.authMode&&e.tokenProvider&&o().then(e=>{e||r(!0)})}};return window.addEventListener("tokenExpiredError",e),()=>window.removeEventListener("tokenExpiredError",e)},[s,o]),{isTokenExpired:e,isRefreshing:a,checkTokenExpiration:s,handleTokenExpiredClose:c,handleTokenExpiredReload:u,tryRefreshToken:o}}(),{upload:K,loading:G,error:Q,uploadedImage:X,reset:Y}=function(){const[e,n]=t(!1),[l,r]=t(null),[a,i]=t(null);return{upload:async(e,t=null,l=null)=>{if(!e)return r("No se ha proporcionado ningún archivo"),null;n(!0),r(null),i(null);try{const n="object"==typeof l?l?.slug:l,r=await me(e,t,!1,n),a=r.result||r;return i(a),a}catch(a){return r(a.message),null}finally{n(!1)}},loading:e,error:l,uploadedImage:a,reset:()=>{r(null),i(null)}}}(),{deleteImg:J,loading:Z,error:ee,reset:le}=cl(),re={limit:g,page:B,..._&&{name:_},...T&&{uploadedBy:T},...N.dateFrom&&{dateFrom:N.dateFrom},...N.dateTo&&{dateTo:N.dateTo},...N.assetType&&{asset_type:N.assetType},...!z.isAllTypes&&z.raw&&{accept:z.raw},...N.folder&&{folder:N.folder},...w.include?.length>0&&{folders_include:w.include.join(",")},...0===w.include?.length&&w.exclude?.length>0&&{folders_exclude:w.exclude.join(",")},...(w.include?.length>0||w.exclude?.length>0)&&void 0!==w.includeNoFolder&&{include_no_folder:w.includeNoFolder?"1":"0"}},ae=A.includes("gallery"),{images:ie,loading:oe,error:se,pagination:ce,invalidateCache:ue,setImages:de,refetch:be}=ml(a,i,re,ae);n(()=>{const e=()=>{be()};return document.addEventListener("limbo:variantsCleared",e),document.addEventListener("limbo:variantDeleted",e),()=>{document.removeEventListener("limbo:variantsCleared",e),document.removeEventListener("limbo:variantDeleted",e)}},[be]);const{refreshVariants:pe}=fe(),ge=l((e,t=null)=>K(e,t,E?.slug||E),[K,E]),ve=e=>!m.hideActions?.includes(e)&&(!!m.showActions?.includes(e)||!(m.showActions?.length>0)),ye=[{id:"gallery",label:"Galería",feature:"gallery"},{id:"upload",label:"Subir",feature:"upload"},{id:"cropper",label:"Recortador",hideNonActive:!0,feature:"cropper"}].filter(e=>A.includes(e.feature)),we=async e=>{if(!(e.type?.startsWith("image/")&&"image/gif"!==e.type)){const t=E?.slug||E,n=await K(e,null,t);return void(n&&(ue(),W(1),de(e=>[n,...e]),A.includes("gallery")&&D("gallery"),h.onUpload&&h.onUpload({assetId:n.id,url:n.url,fileName:n.filename,mime:n.mime_type,width:n.width,height:n.height,instanceId:p})))}const t=URL.createObjectURL(e),n=await new Promise(e=>{const n=new Image;n.onload=()=>{e({width:n.naturalWidth,height:n.naturalHeight}),URL.revokeObjectURL(t)},n.onerror=()=>{e({width:1920,height:1080}),URL.revokeObjectURL(t)},n.src=t}),l={file:e,filename:e.name,mime_type:e.type,url:(()=>{const t=URL.createObjectURL(e);return j.current=t,t})(),width:n.width,height:n.height};if(R(l),A.includes("cropper"))D("cropper");else{const t=E?.slug||E,n=await K(e,null,t);n&&(ue(),W(1),de(e=>[n,...e]),D("gallery"),h.onUpload&&h.onUpload({assetId:n.id,url:n.url,fileName:n.filename,mime:n.mime_type,width:n.width,height:n.height,instanceId:p}))}},xe=l(e=>{const t={...e,instanceId:p};h.onSelect&&h.onSelect(t),window.limboCore?.events&&window.limboCore.events.emit("select",t);"modal"===((window.limboCore?.config?.getGlobal()||{}).mode||"embed")&&window.limboCore?.modals?.closeAllModals(),U(`Vídeo seleccionado: ${e.title||"Sin título"}`),setTimeout(()=>U(null),3e3)},[h,p]),ke=async e=>{if(!confirm("¿Estás seguro de que deseas eliminar este archivo? Esta acción también eliminará todos sus recortes."))return;await J(e)&&(ue(),W(1),de(t=>t.filter(t=>t.id!==e)),O&&O.id===e&&(R(null),D("gallery")))},Ce=l(async(e,t)=>{const n=await he(e.id,{original_filename:t}),l=n?.result||{};return ue(),de(n=>n.map(n=>n.id!==e.id?n:{...n,filename:l.filename??t,...l.url&&{url:l.url},...void 0!==l.url_webp&&{url_webp:l.url_webp}})),n},[ue]),Ne=e=>{L(e.mime_type||e.original_mime)?(R(e),A.includes("cropper")&&D("cropper")):console.log("[App] ⚠️ Archivo no recortable:",e.mime_type||e.original_mime,"- saltando cropper")},Se=()=>"crop-only"===b||1===A.length&&"cropper"===A[0]?"crop-only":A.includes("gallery")?"with-gallery":A.includes("upload")&&!A.includes("gallery")?"upload-only":"with-gallery";/* @__PURE__ */
|
|
698
|
+
return c(u,{children:[m.showTabs&&"cropper"!=I&&/* @__PURE__ */s(P,{tabs:ye,active:I,onChange:e=>{D(e),"upload"!==e&&Y(),"gallery"!==e&&le()}}),se&&/* @__PURE__ */c(We,{variant:"danger",children:["Error al cargar archivos: ",se]}),ee&&/* @__PURE__ */c(We,{variant:"danger",children:["Error al eliminar archivo: ",ee]}),F&&/* @__PURE__ */s(We,{variant:"success",fixed:!0,onClose:()=>U(null),children:F}),"gallery"===I&&/* @__PURE__ */c(u,{children:[Z&&/* @__PURE__ */s(ol,{text:"Eliminando archivo..."}),X&&/* @__PURE__ */c(We,{variant:"success",toast:!0,onClose:Y,children:[
|
|
698
699
|
/* @__PURE__ */s("span",{className:"icon icon-tick-white icon--2sm"})," Archivo subido correctamente: ",X.filename]}),
|
|
699
|
-
/* @__PURE__ */s(
|
|
700
|
+
/* @__PURE__ */s(Ve,{onSelect:e=>{const t=y?.mandatoryCrops?.length>0,n=L(e.mime_type||e.original_mime);if(t&&n&&A.includes("cropper"))return console.log("[App] 📐 MandatoryCrops detectados, navegando al cropper primero"),void Ne(e);h.onSelect&&h.onSelect({assetId:e.id,url:e.url,fileName:e.filename,mime:e.mime_type,width:e.width,height:e.height,instanceId:p})},onCrop:Ne,onDelete:ve("delete")?ke:null,deletingId:Z,images:ie,loading:oe,error:se,filters:N,debouncedFilters:{name:_,uploadedBy:T,dateFrom:N.dateFrom,dateTo:N.dateTo,assetType:N.assetType,folder:N.folder},onFiltersChange:e=>{S(e),W(1)},filterConfig:m.galleryFilters||{},loadingConfig:m.galleryLoading||{},allowedActions:{select:ve("select"),download:ve("download"),copy:ve("copy"),delete:ve("delete"),crop:ve("crop"),rename:ve("rename")},resolvedAccept:z,allowedCategories:x,folderConfig:w,onFolderChange:async(e,t)=>{try{const n=await he(e.id,{folder:t});return ue(),de(t=>t.map(t=>t.id===e.id?{...t,folder:n.folder||null}:t)),n}catch(n){throw console.error("Error al cambiar carpeta:",n),n}},onRename:Ce}),ce&&!oe&&/* @__PURE__ */s(il,{currentPage:ce.page||B,totalPages:ce.pages||1,onPageChange:e=>{W(e)},disabled:oe||Z})]}),"upload"===I&&/* @__PURE__ */c("div",{children:[G&&/* @__PURE__ */s(ol,{text:"Subiendo archivo..."}),Q&&/* @__PURE__ */c(We,{variant:"danger",toast:!0,onClose:Y,children:["Error al subir archivo: ",Q]}),X&&/* @__PURE__ */c(We,{variant:"success",toast:!0,onClose:Y,children:[
|
|
700
701
|
/* @__PURE__ */s("span",{className:"icon icon-tick-white icon--2sm"})," Archivo subido correctamente: ",X.filename]}),
|
|
701
|
-
/* @__PURE__ */s(
|
|
702
|
-
/* @__PURE__ */c("div","crop-only"===b?{children:[G&&/* @__PURE__ */s(
|
|
703
|
-
/* @__PURE__ */s(
|
|
702
|
+
/* @__PURE__ */s(wt,{onSelect:we,onVideoSelect:xe,disabled:G,apiKey:a,prod:i,allowedCategories:x,resolvedAccept:z,returnConfig:C,folderConfig:w,selectedFolder:E,onFolderChange:$})]}),"cropper"===I&&O&&/* @__PURE__ */s(al,{image:O,onSave:e=>{const t=Se(),n=window.limboCore?.config?.getGlobal()||{},l=n.mode||"embed",r=n.autoHideOnComplete||!1;let a=[],i=null;e.crops&&e.asset?(a=e.crops,i=e.asset):a=e.crops&&Array.isArray(e.crops)?e.crops:Array.isArray(e)?e:[e],i&&"with-gallery"===t&&(de(e=>[i,...e]),W(1),h.onUpload&&h.onUpload({assetId:i.id,url:i.url,fileName:i.filename,mime:i.mime_type,width:i.width,height:i.height,instanceId:p})),"with-gallery"===t&&ue();const o=i||O,s=a.some(e=>!0===e.isLocal),c={crops:a,assetId:o?.id,instanceId:p,localCrops:s,asset:o?{id:o.id,url:o.url||o.urlSigned,width:o.width,height:o.height,filename:o.filename,mime_type:o.mime_type}:null};console.log("[App] handleCropSave - callbackPayload:",c),console.log("[App] handleCropSave - crops:",a),console.log("[App] handleCropSave - crops[0]?.url:",a[0]?.url),console.log("[App] handleCropSave - asset:",c.asset),console.log("[App] handleCropSave - callbacks.onCropsSaved existe:",!!h.onCropsSaved),h.onCropsSaved?(console.log("[App] Llamando callbacks.onCropsSaved..."),h.onCropsSaved(c),console.log("[App] callbacks.onCropsSaved ejecutado")):console.warn("[App] ⚠️ callbacks.onCropsSaved NO existe"),window.limboCore?.events&&window.limboCore.events.emit("cropsSaved",c);const u=a.length;switch(U(`✅ ${u} recorte${1!==u?"s":""} guardado${1!==u?"s":""} correctamente`),setTimeout(()=>U(null),3e3),t){case"with-gallery":"modal"===l?h.onCropsSaved||(window.limboCore?.modals?.closeAllModals(),R(null),D("gallery")):(R(null),D("gallery"));break;case"upload-only":"modal"===l?h.onCropsSaved||(window.limboCore?.modals?.closeAllModals(),R(null),D("upload")):(R(null),D("upload"));break;case"crop-only":if("modal"===l)h.onCropperComplete&&h.onCropperComplete({crops:a,instanceId:p}),window.limboCore?.events&&window.limboCore.events.emit("cropperComplete",{crops:a,instanceId:p}),window.limboCore?.modals?.closeAllModals();else if(h.onCropperComplete&&h.onCropperComplete({crops:a,instanceId:p}),window.limboCore?.events&&window.limboCore.events.emit("cropperComplete",{crops:a,instanceId:p}),r){const e=document.querySelector(`#limbo-instance-${p}`);e&&(e.style.display="none")}}},onCancel:()=>{const e=Se(),t=(window.limboCore?.config?.getGlobal()||{}).mode||"embed";switch(h.onCropperCancelled&&h.onCropperCancelled({assetId:O?.id,instanceId:p}),window.limboCore?.events&&window.limboCore.events.emit("cropperCancelled",{assetId:O?.id,instanceId:p}),e){case"with-gallery":R(null),D("gallery");break;case"upload-only":"modal"===t?window.limboCore?.modals?.closeAllModals():(R(null),D("upload"));break;case"crop-only":"modal"===t?window.limboCore?.modals?.closeAllModals():window.limboCore?.events&&window.limboCore.events.emit("cropperClosed",{instanceId:p,reason:"cancelled"})}},onDelete:O?.id&&ve("delete")?()=>ke(O.id):null,onError:e=>{h.onCropperError&&h.onCropperError(e,p),window.limboCore?.events&&window.limboCore.events.emit("cropperError",{error:e,assetId:O?.id,instanceId:p}),console.error("Cropper error:",e)},deleting:Z,onVariantCreated:(e,t)=>{pe(e),ue()},onUpload:ge,uploading:G,cropperConfig:y}),"cropper"===I&&!O&&
|
|
703
|
+
/* @__PURE__ */c("div","crop-only"===b?{children:[G&&/* @__PURE__ */s(ol,{text:"Subiendo archivo..."}),Q&&/* @__PURE__ */c(We,{variant:"danger",toast:!0,onClose:Y,children:["Error al subir archivo: ",Q]}),
|
|
704
|
+
/* @__PURE__ */s(wt,{onSelect:we,onVideoSelect:xe,disabled:G,apiKey:a,prod:i,allowedCategories:x,resolvedAccept:z,returnConfig:C,folderConfig:w,selectedFolder:E,onFolderChange:$})]}:{className:"limbo-empty-state lb:flex lb:flex-col lb:items-center lb:justify-center lb:py-12 lb:px-6 lb:text-center",children:[
|
|
704
705
|
/* @__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"})})}),
|
|
705
706
|
/* @__PURE__ */s("p",{className:"lb:text-gray-600 lb:mb-4",children:"Selecciona una imagen de la galería para comenzar a recortar."})]}),
|
|
706
|
-
/* @__PURE__ */s(
|
|
707
|
-
/* @__PURE__ */s(ol,{isOpen:q,onClose:V,onReload:H})]})}(()=>{try{const e=sessionStorage.getItem(dl);if(e){const t=JSON.parse(e),n=Date.now();Object.entries(t).forEach(([e,t])=>{t.timestamp&&n-t.timestamp<ul&&cl.set(e,t)})}}catch{}})();class fl{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=L.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=L.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.7.4","data-limbo-isolated":"true","aria-label":"Limbo Image Manager",role:"region"},e.createElement(pl,{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,accept:this.config.validation?.accept||null,returnConfig:this.config.returnConfig||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=ne();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 gl{constructor(){this.instances=/* @__PURE__ */new Map,this.counter=0}create(e,t,n){const l="limbo-"+ ++this.counter,r=new fl(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 vl{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 oe(await le({endpoint:`/assets/${e}?${r}`,method:"GET",basePath:de,useJWT:!0}))}catch(r){throw ue(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:{accept:e.accept||null,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","rename"),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,accept:e.dataset.accept||e.getAttribute("data-limbo-accept")||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 yl{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 wl{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 xl(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 xl{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 kl{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 Cl=new class{constructor(){this.config=new w,this.instances=new gl,this.autoInputs=new vl,this.events=new yl,this.modals=new wl,this.theme=new kl,this.containerQueryDetector=A,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},Z={...Z,...t},Z.authMode||(Z.token?Z.authMode="manual":Z.authMode="session"),this.config}setToken(e){return te(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",i="";i="url"===a?r.images?.[0]?.url||r.original?.url||"":"assetId"===a?r.original?.assetId||"":JSON.stringify(r),l.value=i,l.dispatchEvent(new Event("change",{bubbles:!0})),console.log("[Limbo] ✅ Valor asignado al input:",l.value?.substring(0,80))}try{await t(r)}catch(o){}c.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:()=>{}}},i=e.validation?.accept||null,o=i?f(i):null,s=!o||o.isAllTypes||o.includesImages;if(e.initialImageUrl&&s){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 c=this.create(a);c.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"},validation:{accept:e.accept||null},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"},validation:{accept:e.accept||null},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"],validation:{accept:t.accept||null},callbacks:{onSelect:t.onSelect,onDelete:t.onDelete},...t})}createInlineUploader(e,t={}){return this.create({container:e,mode:"embed",modeUI:"upload-only",features:["upload"],validation:{accept:t.accept||null},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"],validation:{accept:t.accept||null},callbacks:{onSelect:t.onSelect,onUpload:t.onUpload,onDelete:t.onDelete,onCropsSaved:t.onCropsSaved},...t})}};"undefined"!=typeof window&&(window.Limbo=Cl,window.limboCore=Cl);"undefined"!=typeof window&&document.querySelector("#root")&&(Cl.configure({prod:!1,publicKey:"pk_e464fd744106b7a8d63d453c4bd02582",authMode:"session"}),Cl.create({container:"#root",mode:"embed",modeUI:"full",features:["gallery","upload","cropper"],title:"Limbo Image Manager - Development",url:!0}),Cl.configureAutoInputs({dataset:"data-limbo-input-file",return:"json",features:["gallery","upload","cropper"],modeUI:"full",modalSize:"large",title:"Seleccionar archivo",crops:"free",allowDelete:!1}));export{I as LIMBO_BASE_URL,O as decodeHtmlEntities,Cl as default,j as extractImageUrl,R as isValidImageUrl,F as parseImageData,W as prepareImageFieldsForPreview,D as resolveUrl};
|
|
707
|
+
/* @__PURE__ */s(pl,{}),
|
|
708
|
+
/* @__PURE__ */s(sl,{isOpen:q,onClose:V,onReload:H})]})}(()=>{try{const e=sessionStorage.getItem(bl);if(e){const t=JSON.parse(e),n=Date.now();Object.entries(t).forEach(([e,t])=>{t.timestamp&&n-t.timestamp<dl&&ul.set(e,t)})}}catch{}})();class gl{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=L.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=L.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.7.4","data-limbo-isolated":"true","aria-label":"Limbo Image Manager",role:"region"},e.createElement(fl,{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,accept:this.config.validation?.accept||null,returnConfig:this.config.returnConfig||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=ne();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 vl{constructor(){this.instances=/* @__PURE__ */new Map,this.counter=0}create(e,t,n){const l="limbo-"+ ++this.counter,r=new gl(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 yl{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 oe(await le({endpoint:`/assets/${e}?${r}`,method:"GET",basePath:de,useJWT:!0}))}catch(r){throw ue(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:{accept:e.accept||null,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","rename"),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,accept:e.dataset.accept||e.getAttribute("data-limbo-accept")||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 wl{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 xl{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 kl(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 kl{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 Cl{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 Nl=new class{constructor(){this.config=new w,this.instances=new vl,this.autoInputs=new yl,this.events=new wl,this.modals=new xl,this.theme=new Cl,this.containerQueryDetector=A,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},Z={...Z,...t},Z.authMode||(Z.token?Z.authMode="manual":Z.authMode="session"),this.config}setToken(e){return te(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",i="";i="url"===a?r.images?.[0]?.url||r.original?.url||"":"assetId"===a?r.original?.assetId||"":JSON.stringify(r),l.value=i,l.dispatchEvent(new Event("change",{bubbles:!0})),console.log("[Limbo] ✅ Valor asignado al input:",l.value?.substring(0,80))}try{await t(r)}catch(o){}c.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:()=>{}}},i=e.validation?.accept||null,o=i?f(i):null,s=!o||o.isAllTypes||o.includesImages;if(e.initialImageUrl&&s){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 c=this.create(a);c.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"},validation:{accept:e.accept||null},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"},validation:{accept:e.accept||null},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"],validation:{accept:t.accept||null},callbacks:{onSelect:t.onSelect,onDelete:t.onDelete},...t})}createInlineUploader(e,t={}){return this.create({container:e,mode:"embed",modeUI:"upload-only",features:["upload"],validation:{accept:t.accept||null},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"],validation:{accept:t.accept||null},callbacks:{onSelect:t.onSelect,onUpload:t.onUpload,onDelete:t.onDelete,onCropsSaved:t.onCropsSaved},...t})}};"undefined"!=typeof window&&(window.Limbo=Nl,window.limboCore=Nl);"undefined"!=typeof window&&document.querySelector("#root")&&(Nl.configure({prod:!1,publicKey:"pk_e464fd744106b7a8d63d453c4bd02582",authMode:"session"}),Nl.create({container:"#root",mode:"embed",modeUI:"full",features:["gallery","upload","cropper"],title:"Limbo Image Manager - Development",url:!0}),Nl.configureAutoInputs({dataset:"data-limbo-input-file",return:"json",features:["gallery","upload","cropper"],modeUI:"full",modalSize:"large",title:"Seleccionar archivo",crops:"free",allowDelete:!1}));export{I as LIMBO_BASE_URL,O as decodeHtmlEntities,Nl as default,j as extractImageUrl,R as isValidImageUrl,F as parseImageData,W as prepareImageFieldsForPreview,D as resolveUrl};
|
|
708
709
|
//# sourceMappingURL=limbo.es.map
|