limbo-component 2.3.2 → 2.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/limbo.es.js CHANGED
@@ -225,7 +225,7 @@ return s("button",{type:"button",onClick:()=>{return t=e.id,void h(e=>e.includes
225
225
  return s("div",{className:"limbo-upload-form py-4 min-w-fit max-w-7xl mx-auto",children:[
226
226
  /* @__PURE__ */l("div",{className:b,role:"tablist","aria-label":"Opciones de subida de imagen",style:o?{WebkitOverflowScrolling:"touch",scrollbarWidth:"none",msOverflowStyle:"none"}:void 0,children:me.map(e=>{const t=u===e.id;/* @__PURE__ */
227
227
  return l("button",{type:"button","data-upload-tab-id":e.id,className:y(t),"aria-current":t?"page":void 0,"aria-selected":t,role:"tab",tabIndex:t?0:-1,onClick:()=>d(e.id),onKeyDown:t=>((e,t)=>{const n=me.findIndex(e=>e.id===t);let r=n;switch(e.key){case"ArrowLeft":e.preventDefault(),r=n>0?n-1:me.length-1;break;case"ArrowRight":e.preventDefault(),r=n<me.length-1?n+1:0;break;case"Home":e.preventDefault(),r=0;break;case"End":e.preventDefault(),r=me.length-1;break;case"Enter":case" ":return e.preventDefault(),void d(t);default:return}const a=me[r];a&&(d(a.id),setTimeout(()=>{const e=document.querySelector(`[data-upload-tab-id="${a.id}"]`);e&&e.focus()},0))})(t,e.id),id:`upload-tab-${e.id}`,"aria-controls":`upload-tabpanel-${e.id}`,style:c?{WebkitTapHighlightColor:"transparent"}:void 0,children:e.label},e.id)})}),
228
- /* @__PURE__ */s("div",{className:"limbo-tab-content px-2 py-2",role:"tabpanel",id:`upload-tabpanel-${u}`,"aria-labelledby":`upload-tab-${u}`,children:["upload"===u&&/* @__PURE__ */l(Q,{file:m,setFile:h,previewUrl:p,setPreviewUrl:f,fileInputRef:g,onSelect:e,disabled:n}),"ai"===u&&/* @__PURE__ */l(ne,{apiKey:r,prod:i,disabled:n,onSelect:e}),"stock"===u&&/* @__PURE__ */l(oe,{apiKey:r,prod:i,disabled:n,onSelect:e}),"portals"===u&&/* @__PURE__ */l(de,{apiKey:r,prod:i,disabled:n,onSelect:e})]})]})}const pe="undefined"!=typeof window&&void 0!==window.document,fe=pe?window:{},ge=!!pe&&"ontouchstart"in fe.document.documentElement,be=!!pe&&"PointerEvent"in fe,ye="cropper",ve=`${ye}-canvas`,we=`${ye}-crosshair`,xe=`${ye}-grid`,ke=`${ye}-handle`,Ce=`${ye}-image`,Se=`${ye}-selection`,Ne=`${ye}-shade`,Ee=`${ye}-viewer`,$e="select",_e="move",ze="scale",Te="rotate",Ae="transform",Pe="none",Me="n-resize",Ie="e-resize",Le="s-resize",De="w-resize",Oe="ne-resize",Re="nw-resize",je="se-resize",Fe="sw-resize",Ue=be?"pointerdown":ge?"touchstart":"mousedown",qe=be?"pointermove":ge?"touchmove":"mousemove",Be=be?"pointerup pointercancel":ge?"touchend touchcancel":"mouseup",We="error",Ve="keydown",He="load",Ke="wheel",Ge="action",Qe="actionend",Ye="actionstart",Xe="change",Je="transform";const Ze=Number.isNaN||fe.isNaN;function et(e){return"number"==typeof e&&!Ze(e)}function tt(e){return et(e)&&e>0&&e<1/0}function nt(e){return"object"==typeof e&&null!==e}const{hasOwnProperty:rt}=Object.prototype;function at(e){if(!nt(e))return!1;try{const{constructor:t}=e,{prototype:n}=t;return t&&n&&rt.call(n,"isPrototypeOf")}catch(t){return!1}}function it(e){return"function"==typeof e}function ot(e){return"object"==typeof e&&null!==e&&1===e.nodeType}const lt=/([a-z\d])([A-Z])/g;function st(e){return String(e).replace(lt,"$1-$2").toLowerCase()}const ct=/-[A-z\d]/g;function ut(e){return e.replace(ct,e=>e.slice(1).toUpperCase())}const dt=/\s\s*/;function mt(e,t,n,r){t.trim().split(dt).forEach(t=>{e.removeEventListener(t,n,r)})}function ht(e,t,n,r){t.trim().split(dt).forEach(t=>{e.addEventListener(t,n,r)})}function pt(e,t,n,r){ht(e,t,n,Object.assign(Object.assign({},r),{once:!0}))}const ft={bubbles:!0,cancelable:!0,composed:!0};const gt=Promise.resolve();function bt(e){const{documentElement:t}=e.ownerDocument,n=e.getBoundingClientRect();return{left:n.left+(fe.pageXOffset-t.clientLeft),top:n.top+(fe.pageYOffset-t.clientTop)}}const yt=/deg|g?rad|turn$/i;function vt(e){const t=parseFloat(e)||0;if(0!==t){const[n="rad"]=String(e).match(yt)||[];switch(n.toLowerCase()){case"deg":return t/360*(2*Math.PI);case"grad":return t/400*(2*Math.PI);case"turn":return t*(2*Math.PI)}}return t}const wt="contain";function xt(e,t=wt){const{aspectRatio:n}=e;let{width:r,height:a}=e;const i=tt(r),o=tt(a);if(i&&o){const e=a*n;t===wt&&e>r||"cover"===t&&e<r?a=r/n:r=a*n}else i?a=r/n:o&&(r=a*n);return{width:r,height:a}}function kt(e,...t){if(0===t.length)return e;const[n,r,a,i,o,l]=e,[s,c,u,d,m,h]=t[0];return kt(e=[n*s+a*c,r*s+i*c,n*u+a*d,r*u+i*d,n*m+a*h+o,r*m+i*h+l],...t.slice(1))}const Ct=/left|top|width|height/i,St="open",Nt=/* @__PURE__ */new WeakMap,Et=/* @__PURE__ */new WeakMap,$t=/* @__PURE__ */new Map,_t=fe.document&&Array.isArray(fe.document.adoptedStyleSheets)&&"replaceSync"in fe.CSSStyleSheet.prototype;class zt extends HTMLElement{get $sharedStyle(){return(this.themeColor?`:host{--theme-color: ${this.themeColor};}`:"")+":host([hidden]){display:none!important}"}constructor(){var e,t;super(),this.shadowRootMode=St,this.slottable=!0;const n=null===(t=null===(e=Object.getPrototypeOf(this))||void 0===e?void 0:e.constructor)||void 0===t?void 0:t.$name;n&&$t.set(n,this.tagName.toLowerCase())}static get observedAttributes(){return["shadow-root-mode","slottable","theme-color"]}attributeChangedCallback(e,t,n){if(Object.is(n,t))return;const r=ut(e);let a=n;switch(typeof this[r]){case"boolean":a=null!==n&&"false"!==n;break;case"number":a=Number(n)}switch(this[r]=a,e){case"theme-color":{const e=Et.get(this),t=this.$sharedStyle;e&&t&&(_t?e.replaceSync(t):e.textContent=t);break}}}$propertyChangedCallback(e,t,n){if(!Object.is(n,t))switch(e=st(e),typeof n){case"boolean":!0===n?this.hasAttribute(e)||this.setAttribute(e,""):this.removeAttribute(e);break;case"number":n=Ze(n)?"":String(n);default:n?this.getAttribute(e)!==n&&this.setAttribute(e,n):this.removeAttribute(e)}}connectedCallback(){Object.getPrototypeOf(this).constructor.observedAttributes.forEach(e=>{const t=ut(e);let n=this[t];(function(e){return void 0===e})(n)||this.$propertyChangedCallback(t,void 0,n),Object.defineProperty(this,t,{enumerable:!0,configurable:!0,get:()=>n,set(e){const r=n;n=e,this.$propertyChangedCallback(t,r,e)}})});const e=this.shadowRoot||this.attachShadow({mode:this.shadowRootMode||St});if(Nt.set(this,e),Et.set(this,this.$addStyles(this.$sharedStyle)),this.$style&&this.$addStyles(this.$style),this.$template){const t=document.createElement("template");t.innerHTML=this.$template,e.appendChild(t.content)}if(this.slottable){const t=document.createElement("slot");e.appendChild(t)}}disconnectedCallback(){Et.has(this)&&Et.delete(this),Nt.has(this)&&Nt.delete(this)}$getTagNameOf(e){var t;return null!==(t=$t.get(e))&&void 0!==t?t:e}$setStyles(e){return Object.keys(e).forEach(t=>{let n=e[t];et(n)&&(n=0!==n&&Ct.test(t)?`${n}px`:String(n)),this.style[t]=n}),this}$getShadowRoot(){return this.shadowRoot||Nt.get(this)}$addStyles(e){let t;const n=this.$getShadowRoot();return _t?(t=new CSSStyleSheet,t.replaceSync(e),n.adoptedStyleSheets=n.adoptedStyleSheets.concat(t)):(t=document.createElement("style"),t.textContent=e,n.appendChild(t)),t}$emit(e,t,n){return function(e,t,n,r){return e.dispatchEvent(new CustomEvent(t,Object.assign(Object.assign(Object.assign({},ft),{detail:n}),r)))}(this,e,t,n)}$nextTick(e){return function(e,t){return t?gt.then(e?t.bind(e):t):gt}(this,e)}static $define(e,t){nt(e)&&(t=e,e=""),e||(e=this.$name||this.name),e=st(e),pe&&fe.customElements&&!fe.customElements.get(e)&&customElements.define(e,this,t)}}zt.$version="2.1.0";class Tt extends zt{constructor(){super(...arguments),this.$onPointerDown=null,this.$onPointerMove=null,this.$onPointerUp=null,this.$onWheel=null,this.$wheeling=!1,this.$pointers=/* @__PURE__ */new Map,this.$style=':host{display:block;min-height:100px;min-width:200px;overflow:hidden;position:relative;touch-action:none;-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}:host([background]){background-color:#fff;background-image:repeating-linear-gradient(45deg,#ccc 25%,transparent 0,transparent 75%,#ccc 0,#ccc),repeating-linear-gradient(45deg,#ccc 25%,transparent 0,transparent 75%,#ccc 0,#ccc);background-image:repeating-conic-gradient(#ccc 0 25%,#fff 0 50%);background-position:0 0,.5rem .5rem;background-size:1rem 1rem}:host([disabled]){pointer-events:none}:host([disabled]):after{bottom:0;content:"";cursor:not-allowed;display:block;left:0;pointer-events:none;position:absolute;right:0;top:0}',this.$action=Pe,this.background=!1,this.disabled=!1,this.scaleStep=.1,this.themeColor="#39f"}static get observedAttributes(){return super.observedAttributes.concat(["background","disabled","scale-step"])}connectedCallback(){super.connectedCallback(),this.disabled||this.$bind()}disconnectedCallback(){this.disabled||this.$unbind(),super.disconnectedCallback()}$propertyChangedCallback(e,t,n){if(!Object.is(n,t)&&(super.$propertyChangedCallback(e,t,n),"disabled"===e))n?this.$unbind():this.$bind()}$bind(){this.$onPointerDown||(this.$onPointerDown=this.$handlePointerDown.bind(this),ht(this,Ue,this.$onPointerDown)),this.$onPointerMove||(this.$onPointerMove=this.$handlePointerMove.bind(this),ht(this.ownerDocument,qe,this.$onPointerMove)),this.$onPointerUp||(this.$onPointerUp=this.$handlePointerUp.bind(this),ht(this.ownerDocument,Be,this.$onPointerUp)),this.$onWheel||(this.$onWheel=this.$handleWheel.bind(this),ht(this,Ke,this.$onWheel,{passive:!1,capture:!0}))}$unbind(){this.$onPointerDown&&(mt(this,Ue,this.$onPointerDown),this.$onPointerDown=null),this.$onPointerMove&&(mt(this.ownerDocument,qe,this.$onPointerMove),this.$onPointerMove=null),this.$onPointerUp&&(mt(this.ownerDocument,Be,this.$onPointerUp),this.$onPointerUp=null),this.$onWheel&&(mt(this,Ke,this.$onWheel,{capture:!0}),this.$onWheel=null)}$handlePointerDown(e){const{buttons:t,button:n,type:r}=e;if(this.disabled||("pointerdown"===r&&"mouse"===e.pointerType||"mousedown"===r)&&(et(t)&&1!==t||et(n)&&0!==n||e.ctrlKey))return;const{$pointers:a}=this;let i="";if(e.changedTouches)Array.from(e.changedTouches).forEach(({identifier:e,pageX:t,pageY:n})=>{a.set(e,{startX:t,startY:n,endX:t,endY:n})});else{const{pointerId:t=0,pageX:n,pageY:r}=e;a.set(t,{startX:n,startY:r,endX:n,endY:r})}a.size>1?i=Ae:ot(e.target)&&(i=e.target.action||e.target.getAttribute("action")||""),!1!==this.$emit(Ye,{action:i,relatedEvent:e})&&(e.preventDefault(),this.$action=i,this.style.willChange="transform")}$handlePointerMove(e){const{$action:t,$pointers:n}=this;if(this.disabled||t===Pe||0===n.size)return;if(!1===this.$emit("actionmove",{action:t,relatedEvent:e}))return;if(e.preventDefault(),e.changedTouches)Array.from(e.changedTouches).forEach(({identifier:e,pageX:t,pageY:r})=>{const a=n.get(e);a&&Object.assign(a,{endX:t,endY:r})});else{const{pointerId:t=0,pageX:r,pageY:a}=e,i=n.get(t);i&&Object.assign(i,{endX:r,endY:a})}const r={action:t,relatedEvent:e};if(t===Ae){const t=new Map(n);let a=0,i=0,o=0,l=0,s=e.pageX,c=e.pageY;n.forEach((e,n)=>{t.delete(n),t.forEach(t=>{let n=t.startX-e.startX,r=t.startY-e.startY,u=t.endX-e.endX,d=t.endY-e.endY,m=0,h=0,p=0,f=0;if(0===n?r<0?p=2*Math.PI:r>0&&(p=Math.PI):n>0?p=Math.PI/2+Math.atan(r/n):n<0&&(p=1.5*Math.PI+Math.atan(r/n)),0===u?d<0?f=2*Math.PI:d>0&&(f=Math.PI):u>0?f=Math.PI/2+Math.atan(d/u):u<0&&(f=1.5*Math.PI+Math.atan(d/u)),f>0||p>0){const n=f-p,r=Math.abs(n);r>a&&(a=r,o=n,s=(e.startX+t.startX)/2,c=(e.startY+t.startY)/2)}if(n=Math.abs(n),r=Math.abs(r),u=Math.abs(u),d=Math.abs(d),n>0&&r>0?m=Math.sqrt(n*n+r*r):n>0?m=n:r>0&&(m=r),u>0&&d>0?h=Math.sqrt(u*u+d*d):u>0?h=u:d>0&&(h=d),m>0&&h>0){const n=(h-m)/m,r=Math.abs(n);r>i&&(i=r,l=n,s=(e.startX+t.startX)/2,c=(e.startY+t.startY)/2)}})});const u=a>0,d=i>0;u&&d?(r.rotate=o,r.scale=l,r.centerX=s,r.centerY=c):u?(r.action=Te,r.rotate=o,r.centerX=s,r.centerY=c):d?(r.action=ze,r.scale=l,r.centerX=s,r.centerY=c):r.action=Pe}else{const[e]=Array.from(n.values());Object.assign(r,e)}n.forEach(e=>{e.startX=e.endX,e.startY=e.endY}),r.action!==Pe&&this.$emit(Ge,r,{cancelable:!1})}$handlePointerUp(e){const{$action:t,$pointers:n}=this;if(!this.disabled&&t!==Pe&&!1!==this.$emit(Qe,{action:t,relatedEvent:e})){if(e.preventDefault(),e.changedTouches)Array.from(e.changedTouches).forEach(({identifier:e})=>{n.delete(e)});else{const{pointerId:t=0}=e;n.delete(t)}0===n.size&&(this.style.willChange="",this.$action=Pe)}}$handleWheel(e){if(this.disabled)return;if(e.preventDefault(),this.$wheeling)return;this.$wheeling=!0,setTimeout(()=>{this.$wheeling=!1},50);const t=(e.deltaY>0?-1:1)*this.scaleStep;this.$emit(Ge,{action:ze,scale:t,relatedEvent:e},{cancelable:!1})}$setAction(e){return"string"==typeof e&&(this.$action=e),this}$toCanvas(e){return new Promise((t,n)=>{if(!this.isConnected)return void n(new Error("The current element is not connected to the DOM."));const r=document.createElement("canvas");let a=this.offsetWidth,i=this.offsetHeight,o=1;at(e)&&(tt(e.width)||tt(e.height))&&(({width:a,height:i}=xt({aspectRatio:a/i,width:e.width,height:e.height})),o=a/this.offsetWidth),r.width=a,r.height=i;const l=this.querySelector(this.$getTagNameOf(Ce));l?l.$ready().then(n=>{const s=r.getContext("2d");if(s){const[t,c,u,d,m,h]=l.$getTransform();let p=m,f=h,g=n.naturalWidth,b=n.naturalHeight;1!==o&&(p*=o,f*=o,g*=o,b*=o);const y=g/2,v=b/2;s.fillStyle="transparent",s.fillRect(0,0,a,i),at(e)&&it(e.beforeDraw)&&e.beforeDraw.call(this,s,r),s.save(),s.translate(y,v),s.transform(t,c,u,d,p,f),s.translate(-y,-v),s.drawImage(n,0,0,g,b),s.restore()}t(r)}).catch(n):t(r)})}}Tt.$name=ve,Tt.$version="2.1.0";const At=/* @__PURE__ */new WeakMap,Pt=["alt","crossorigin","decoding","elementtiming","fetchpriority","loading","referrerpolicy","sizes","src","srcset"];class Mt extends zt{constructor(){super(...arguments),this.$matrix=[1,0,0,1,0,0],this.$onLoad=null,this.$onCanvasAction=null,this.$onCanvasActionEnd=null,this.$onCanvasActionStart=null,this.$actionStartTarget=null,this.$style=":host{display:inline-block}img{display:block;height:100%;max-height:none!important;max-width:none!important;min-height:0!important;min-width:0!important;width:100%}",this.$image=new Image,this.initialCenterSize="contain",this.rotatable=!1,this.scalable=!1,this.skewable=!1,this.slottable=!1,this.translatable=!1,this.alt="",this.crossorigin="",this.decoding="",this.elementtiming="",this.fetchpriority="",this.loading="",this.referrerpolicy="",this.sizes="",this.src="",this.srcset=""}set $canvas(e){At.set(this,e)}get $canvas(){return At.get(this)}static get observedAttributes(){return super.observedAttributes.concat(Pt,["initial-center-size","rotatable","scalable","skewable","translatable"])}attributeChangedCallback(e,t,n){Object.is(n,t)||(super.attributeChangedCallback(e,t,n),Pt.includes(e)&&this.$image.setAttribute(e,n))}$propertyChangedCallback(e,t,n){if(!Object.is(n,t)&&(super.$propertyChangedCallback(e,t,n),"initialCenterSize"===e))this.$nextTick(()=>{this.$center(n)})}connectedCallback(){super.connectedCallback();const{$image:e}=this,t=this.closest(this.$getTagNameOf(ve));t&&(this.$canvas=t,this.$setStyles({display:"block",position:"absolute"}),this.$onCanvasActionStart=e=>{var t,n;this.$actionStartTarget=null===(n=null===(t=e.detail)||void 0===t?void 0:t.relatedEvent)||void 0===n?void 0:n.target},this.$onCanvasActionEnd=()=>{this.$actionStartTarget=null},this.$onCanvasAction=this.$handleAction.bind(this),ht(t,Ye,this.$onCanvasActionStart),ht(t,Qe,this.$onCanvasActionEnd),ht(t,Ge,this.$onCanvasAction)),this.$onLoad=this.$handleLoad.bind(this),ht(e,He,this.$onLoad),this.$getShadowRoot().appendChild(e)}disconnectedCallback(){const{$image:e,$canvas:t}=this;t&&(this.$onCanvasActionStart&&(mt(t,Ye,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(mt(t,Qe,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasAction&&(mt(t,Ge,this.$onCanvasAction),this.$onCanvasAction=null)),e&&this.$onLoad&&(mt(e,He,this.$onLoad),this.$onLoad=null),this.$getShadowRoot().removeChild(e),super.disconnectedCallback()}$handleLoad(){const{$image:e}=this;this.$setStyles({width:e.naturalWidth,height:e.naturalHeight}),this.$canvas&&this.$center(this.initialCenterSize)}$handleAction(e){if(this.hidden||!(this.rotatable||this.scalable||this.translatable))return;const{$canvas:t}=this,{detail:n}=e;if(n){const{relatedEvent:e}=n;let{action:r}=n;switch(r!==Ae||this.rotatable&&this.scalable||(r=this.rotatable?Te:this.scalable?ze:Pe),r){case _e:if(this.translatable){let r=null;e&&(r=e.target.closest(this.$getTagNameOf(Se))),r||(r=t.querySelector(this.$getTagNameOf(Se))),r&&r.multiple&&!r.active&&(r=t.querySelector(`${this.$getTagNameOf(Se)}[active]`)),r&&!r.hidden&&r.movable&&!r.dynamic&&this.$actionStartTarget&&r.contains(this.$actionStartTarget)||this.$move(n.endX-n.startX,n.endY-n.startY)}break;case Te:if(this.rotatable)if(e){const{x:t,y:r}=this.getBoundingClientRect();this.$rotate(n.rotate,e.clientX-t,e.clientY-r)}else this.$rotate(n.rotate);break;case ze:if(this.scalable)if(e){const t=e.target.closest(this.$getTagNameOf(Se));if(!t||!t.zoomable||t.zoomable&&t.dynamic){const{x:t,y:r}=this.getBoundingClientRect();this.$zoom(n.scale,e.clientX-t,e.clientY-r)}}else this.$zoom(n.scale);break;case Ae:if(this.rotatable&&this.scalable){const{rotate:t}=n;let{scale:r}=n;r<0?r=1/(1-r):r+=1;const a=Math.cos(t),i=Math.sin(t),[o,l,s,c]=[a*r,i*r,-i*r,a*r];if(e){const t=this.getBoundingClientRect(),n=e.clientX-t.x,r=e.clientY-t.y,[a,i,u,d]=this.$matrix,m=n-t.width/2,h=r-t.height/2,p=(m*d-u*h)/(a*d-u*i),f=(h*a-i*m)/(a*d-u*i);this.$transform(o,l,s,c,p*(1-o)+f*s,f*(1-c)+p*l)}else this.$transform(o,l,s,c,0,0)}}}}$ready(e){const{$image:t}=this,n=new Promise((e,n)=>{const r=new Error("Failed to load the image source");if(t.complete)t.naturalWidth>0&&t.naturalHeight>0?e(t):n(r);else{const a=()=>{mt(t,We,i),setTimeout(()=>{e(t)})},i=()=>{mt(t,He,a),n(r)};pt(t,He,a),pt(t,We,i)}});return it(e)&&n.then(t=>(e(t),t)),n}$center(e){const{parentElement:t}=this;if(!t)return this;const n=t.getBoundingClientRect(),r=n.width,a=n.height,{x:i,y:o,width:l,height:s}=this.getBoundingClientRect(),c=i+l/2,u=o+s/2,d=n.x+r/2,m=n.y+a/2;if(this.$move(d-c,m-u),e&&(l!==r||s!==a)){const t=r/l,n=a/s;switch(e){case"cover":this.$scale(Math.max(t,n));break;case"contain":this.$scale(Math.min(t,n))}}return this}$move(e,t=e){if(this.translatable&&et(e)&&et(t)){const[n,r,a,i]=this.$matrix,o=(e*i-a*t)/(n*i-a*r),l=(t*n-r*e)/(n*i-a*r);this.$translate(o,l)}return this}$moveTo(e,t=e){if(this.translatable&&et(e)&&et(t)){const[n,r,a,i]=this.$matrix,o=(e*i-a*t)/(n*i-a*r),l=(t*n-r*e)/(n*i-a*r);this.$setTransform(n,r,a,i,o,l)}return this}$rotate(e,t,n){if(this.rotatable){const r=vt(e),a=Math.cos(r),i=Math.sin(r),[o,l,s,c]=[a,i,-i,a];if(et(t)&&et(n)){const[e,r,a,i]=this.$matrix,{width:u,height:d}=this.getBoundingClientRect(),m=t-u/2,h=n-d/2,p=(m*i-a*h)/(e*i-a*r),f=(h*e-r*m)/(e*i-a*r);this.$transform(o,l,s,c,p*(1-o)-f*s,f*(1-c)-p*l)}else this.$transform(o,l,s,c,0,0)}return this}$zoom(e,t,n){if(!this.scalable||0===e)return this;if(e<0?e=1/(1-e):e+=1,et(t)&&et(n)){const[r,a,i,o]=this.$matrix,{width:l,height:s}=this.getBoundingClientRect(),c=t-l/2,u=n-s/2,d=(c*o-i*u)/(r*o-i*a),m=(u*r-a*c)/(r*o-i*a);this.$transform(e,0,0,e,d*(1-e),m*(1-e))}else this.$scale(e);return this}$scale(e,t=e){return this.scalable&&this.$transform(e,0,0,t,0,0),this}$skew(e,t=0){if(this.skewable){const n=vt(e),r=vt(t);this.$transform(1,Math.tan(r),Math.tan(n),1,0,0)}return this}$translate(e,t=e){return this.translatable&&et(e)&&et(t)&&this.$transform(1,0,0,1,e,t),this}$transform(e,t,n,r,a,i){return et(e)&&et(t)&&et(n)&&et(r)&&et(a)&&et(i)?this.$setTransform(kt(this.$matrix,[e,t,n,r,a,i])):this}$setTransform(e,t,n,r,a,i){if((this.rotatable||this.scalable||this.skewable||this.translatable)&&(Array.isArray(e)&&([e,t,n,r,a,i]=e),et(e)&&et(t)&&et(n)&&et(r)&&et(a)&&et(i))){const o=[...this.$matrix],l=[e,t,n,r,a,i];if(!1===this.$emit(Je,{matrix:l,oldMatrix:o}))return this;this.$matrix=l,this.style.transform=`matrix(${l.join(", ")})`}return this}$getTransform(){return this.$matrix.slice()}$resetTransform(){return this.$setTransform([1,0,0,1,0,0])}}Mt.$name=Ce,Mt.$version="2.1.0";const It=/* @__PURE__ */new WeakMap;class Lt extends zt{constructor(){super(...arguments),this.$onCanvasActionEnd=null,this.$onCanvasActionStart=null,this.$onSelectionChange=null,this.$style=":host{display:block;height:0;left:0;outline:var(--theme-color) solid 1px;position:relative;top:0;width:0}:host([transparent]){outline-color:transparent}",this.x=0,this.y=0,this.width=0,this.height=0,this.slottable=!1,this.themeColor="rgba(0, 0, 0, 0.65)"}set $canvas(e){It.set(this,e)}get $canvas(){return It.get(this)}static get observedAttributes(){return super.observedAttributes.concat(["height","width","x","y"])}connectedCallback(){super.connectedCallback();const e=this.closest(this.$getTagNameOf(ve));if(e){this.$canvas=e,this.style.position="absolute";const t=e.querySelector(this.$getTagNameOf(Se));t&&(this.$onCanvasActionStart=e=>{t.hidden&&e.detail.action===$e&&(this.hidden=!1)},this.$onCanvasActionEnd=e=>{t.hidden&&e.detail.action===$e&&(this.hidden=!0)},this.$onSelectionChange=e=>{const{x:n,y:r,width:a,height:i}=e.defaultPrevented?t:e.detail;this.$change(n,r,a,i),(t.hidden||0===n&&0===r&&0===a&&0===i)&&(this.hidden=!0)},ht(e,Ye,this.$onCanvasActionStart),ht(e,Qe,this.$onCanvasActionEnd),ht(e,Xe,this.$onSelectionChange))}this.$render()}disconnectedCallback(){const{$canvas:e}=this;e&&(this.$onCanvasActionStart&&(mt(e,Ye,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(mt(e,Qe,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onSelectionChange&&(mt(e,Xe,this.$onSelectionChange),this.$onSelectionChange=null)),super.disconnectedCallback()}$change(e,t,n=this.width,r=this.height){return et(e)&&et(t)&&et(n)&&et(r)&&(e!==this.x||t!==this.y||n!==this.width||r!==this.height)?(this.hidden&&(this.hidden=!1),this.x=e,this.y=t,this.width=n,this.height=r,this.$render()):this}$reset(){return this.$change(0,0,0,0)}$render(){return this.$setStyles({transform:`translate(${this.x}px, ${this.y}px)`,width:this.width,height:this.height,outlineWidth:fe.innerWidth})}}Lt.$name=Ne,Lt.$version="2.1.0";class Dt extends zt{constructor(){super(...arguments),this.$onCanvasCropEnd=null,this.$onCanvasCropStart=null,this.$style=':host{background-color:var(--theme-color);display:block}:host([action=move]),:host([action=select]){height:100%;left:0;position:absolute;top:0;width:100%}:host([action=move]){cursor:move}:host([action=select]){cursor:crosshair}:host([action$=-resize]){background-color:transparent;height:15px;position:absolute;width:15px}:host([action$=-resize]):after{background-color:var(--theme-color);content:"";display:block;height:5px;left:50%;position:absolute;top:50%;transform:translate(-50%,-50%);width:5px}:host([action=n-resize]),:host([action=s-resize]){cursor:ns-resize;left:50%;transform:translateX(-50%);width:100%}:host([action=n-resize]){top:-8px}:host([action=s-resize]){bottom:-8px}:host([action=e-resize]),:host([action=w-resize]){cursor:ew-resize;height:100%;top:50%;transform:translateY(-50%)}:host([action=e-resize]){right:-8px}:host([action=w-resize]){left:-8px}:host([action=ne-resize]){cursor:nesw-resize;right:-8px;top:-8px}:host([action=nw-resize]){cursor:nwse-resize;left:-8px;top:-8px}:host([action=se-resize]){bottom:-8px;cursor:nwse-resize;right:-8px}:host([action=se-resize]):after{height:15px;width:15px}@media (pointer:coarse){:host([action=se-resize]):after{height:10px;width:10px}}@media (pointer:fine){:host([action=se-resize]):after{height:5px;width:5px}}:host([action=sw-resize]){bottom:-8px;cursor:nesw-resize;left:-8px}:host([plain]){background-color:transparent}',this.action=Pe,this.plain=!1,this.slottable=!1,this.themeColor="rgba(51, 153, 255, 0.5)"}static get observedAttributes(){return super.observedAttributes.concat(["action","plain"])}}Dt.$name=ke,Dt.$version="2.1.0";const Ot=/* @__PURE__ */new WeakMap;class Rt extends zt{constructor(){super(...arguments),this.$onCanvasAction=null,this.$onCanvasActionStart=null,this.$onCanvasActionEnd=null,this.$onDocumentKeyDown=null,this.$action="",this.$actionStartTarget=null,this.$changing=!1,this.$style=':host{display:block;left:0;position:relative;right:0}:host([outlined]){outline:1px solid var(--theme-color)}:host([multiple]){outline:1px dashed hsla(0,0%,100%,.5)}:host([multiple]):after{bottom:0;content:"";cursor:pointer;display:block;left:0;position:absolute;right:0;top:0}:host([multiple][active]){outline-color:var(--theme-color);z-index:1}:host([multiple])>*{visibility:hidden}:host([multiple][active])>*{visibility:visible}:host([multiple][active]):after{display:none}',this.$initialSelection={x:0,y:0,width:0,height:0},this.x=0,this.y=0,this.width=0,this.height=0,this.aspectRatio=NaN,this.initialAspectRatio=NaN,this.initialCoverage=NaN,this.active=!1,this.linked=!1,this.dynamic=!1,this.movable=!1,this.resizable=!1,this.zoomable=!1,this.multiple=!1,this.keyboard=!1,this.outlined=!1,this.precise=!1}set $canvas(e){Ot.set(this,e)}get $canvas(){return Ot.get(this)}static get observedAttributes(){return super.observedAttributes.concat(["active","aspect-ratio","dynamic","height","initial-aspect-ratio","initial-coverage","keyboard","linked","movable","multiple","outlined","precise","resizable","width","x","y","zoomable"])}$propertyChangedCallback(e,t,n){if(!Object.is(n,t))switch(super.$propertyChangedCallback(e,t,n),e){case"x":case"y":case"width":case"height":this.$changing||this.$nextTick(()=>{this.$change(this.x,this.y,this.width,this.height,this.aspectRatio,!0)});break;case"aspectRatio":case"initialAspectRatio":this.$nextTick(()=>{this.$initSelection()});break;case"initialCoverage":this.$nextTick(()=>{tt(n)&&n<=1&&this.$initSelection(!0,!0)});break;case"keyboard":this.$nextTick(()=>{this.$canvas&&(n?this.$onDocumentKeyDown||(this.$onDocumentKeyDown=this.$handleKeyDown.bind(this),ht(this.ownerDocument,Ve,this.$onDocumentKeyDown)):this.$onDocumentKeyDown&&(mt(this.ownerDocument,Ve,this.$onDocumentKeyDown),this.$onDocumentKeyDown=null))});break;case"multiple":this.$nextTick(()=>{if(this.$canvas){const e=this.$getSelections();n?(e.forEach(e=>{e.active=!1}),this.active=!0,this.$emit(Xe,{x:this.x,y:this.y,width:this.width,height:this.height})):(this.active=!1,e.slice(1).forEach(e=>{this.$removeSelection(e)}))}});break;case"precise":this.$nextTick(()=>{this.$change(this.x,this.y)});break;case"linked":n&&(this.dynamic=!0)}}connectedCallback(){super.connectedCallback();const e=this.closest(this.$getTagNameOf(ve));e?(this.$canvas=e,this.$setStyles({position:"absolute",transform:`translate(${this.x}px, ${this.y}px)`}),this.hidden||this.$render(),this.$initSelection(!0),this.$onCanvasActionStart=this.$handleActionStart.bind(this),this.$onCanvasActionEnd=this.$handleActionEnd.bind(this),this.$onCanvasAction=this.$handleAction.bind(this),ht(e,Ye,this.$onCanvasActionStart),ht(e,Qe,this.$onCanvasActionEnd),ht(e,Ge,this.$onCanvasAction)):this.$render()}disconnectedCallback(){const{$canvas:e}=this;e&&(this.$onCanvasActionStart&&(mt(e,Ye,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(mt(e,Qe,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasAction&&(mt(e,Ge,this.$onCanvasAction),this.$onCanvasAction=null)),super.disconnectedCallback()}$getSelections(){let e=[];return this.parentElement&&(e=Array.from(this.parentElement.querySelectorAll(this.$getTagNameOf(Se)))),e}$initSelection(e=!1,t=!1){const{initialCoverage:n,parentElement:r}=this;if(tt(n)&&r){const a=this.aspectRatio||this.initialAspectRatio;let i=(t?0:this.width)||r.offsetWidth*n,o=(t?0:this.height)||r.offsetHeight*n;tt(a)&&({width:i,height:o}=xt({aspectRatio:a,width:i,height:o})),this.$change(this.x,this.y,i,o),e&&this.$center(),this.$initialSelection={x:this.x,y:this.y,width:this.width,height:this.height}}}$createSelection(){const e=this.cloneNode(!0);return this.hasAttribute("id")&&e.removeAttribute("id"),e.initialCoverage=NaN,this.active=!1,this.parentElement&&this.parentElement.insertBefore(e,this.nextSibling),e}$removeSelection(e=this){if(this.parentElement){const t=this.$getSelections();if(t.length>1){const n=t.indexOf(e),r=t[n+1]||t[n-1];r&&(e.active=!1,this.parentElement.removeChild(e),r.active=!0,r.$emit(Xe,{x:r.x,y:r.y,width:r.width,height:r.height}))}else this.$clear()}}$handleActionStart(e){var t,n;const r=null===(n=null===(t=e.detail)||void 0===t?void 0:t.relatedEvent)||void 0===n?void 0:n.target;this.$action="",this.$actionStartTarget=r,!this.hidden&&this.multiple&&!this.active&&r===this&&this.parentElement&&(this.$getSelections().forEach(e=>{e.active=!1}),this.active=!0,this.$emit(Xe,{x:this.x,y:this.y,width:this.width,height:this.height}))}$handleAction(e){const{currentTarget:t,detail:n}=e;if(!t||!n)return;const{relatedEvent:r}=n;let{action:a}=n;const i=r?function(e){if("function"==typeof e.composedPath)return e.composedPath().find(ot)||e.target;return e.target}(r):null;if(!a&&this.multiple&&(a=this.$action||(null==i?void 0:i.action),this.$action=a),!a||this.hidden&&a!==$e||this.multiple&&!this.active&&a!==ze)return;const{width:o,height:l}=this;let s=n.endX-n.startX,c=n.endY-n.startY,{aspectRatio:u}=this;switch(!tt(u)&&r.shiftKey&&(u=tt(o)&&tt(l)?o/l:1),a){case $e:if(0!==s||0!==c){0===s?s=c:0===c&&(c=s);const{$canvas:e}=this,r=bt(t);(this.multiple&&!this.hidden?this.$createSelection():this).$change(n.startX-r.left,n.startY-r.top,Math.abs(s),Math.abs(c),u),s<0?c<0?a=Re:c>0&&(a=Fe):s>0&&(c<0?a=Oe:c>0&&(a=je)),e&&(e.$action=a)}break;case _e:this.movable&&(this.dynamic||this.$actionStartTarget&&this.contains(this.$actionStartTarget))&&this.$move(s,c);break;case ze:if(r&&this.zoomable&&(this.dynamic||this.contains(r.target))){const e=bt(t);this.$zoom(n.scale,r.pageX-e.left,r.pageY-e.top)}break;default:this.$resize(a,s,c,u)}}$handleActionEnd(){this.$action="",this.$actionStartTarget=null}$handleKeyDown(e){if(this.hidden||!this.keyboard||this.multiple&&!this.active||e.defaultPrevented)return;const{activeElement:t}=document;if(!t||!["INPUT","TEXTAREA"].includes(t.tagName)&&!["true","plaintext-only"].includes(t.contentEditable))switch(e.key){case"Backspace":e.metaKey&&(e.preventDefault(),this.$removeSelection());break;case"Delete":e.preventDefault(),this.$removeSelection();break;case"ArrowLeft":e.preventDefault(),this.$move(-1,0);break;case"ArrowRight":e.preventDefault(),this.$move(1,0);break;case"ArrowUp":e.preventDefault(),this.$move(0,-1);break;case"ArrowDown":e.preventDefault(),this.$move(0,1);break;case"+":e.preventDefault(),this.$zoom(.1);break;case"-":e.preventDefault(),this.$zoom(-.1)}}$center(){const{parentElement:e}=this;if(!e)return this;const t=(e.offsetWidth-this.width)/2,n=(e.offsetHeight-this.height)/2;return this.$change(t,n)}$move(e,t=e){return this.$moveTo(this.x+e,this.y+t)}$moveTo(e,t=e){return this.movable?this.$change(e,t):this}$resize(e,t=0,n=0,r=this.aspectRatio){if(!this.resizable)return this;const a=tt(r),{$canvas:i}=this;let{x:o,y:l,width:s,height:c}=this;switch(e){case Me:l+=n,c-=n,c<0&&(e=Le,c=-c,l-=c),a&&(o+=(t=n*r)/2,s-=t,s<0&&(s=-s,o-=s));break;case Ie:s+=t,s<0&&(e=De,s=-s,o-=s),a&&(l-=(n=t/r)/2,c+=n,c<0&&(c=-c,l-=c));break;case Le:c+=n,c<0&&(e=Me,c=-c,l-=c),a&&(o-=(t=n*r)/2,s+=t,s<0&&(s=-s,o-=s));break;case De:o+=t,s-=t,s<0&&(e=Ie,s=-s,o-=s),a&&(l+=(n=t/r)/2,c-=n,c<0&&(c=-c,l-=c));break;case Oe:a&&(n=-t/r),l+=n,c-=n,s+=t,s<0&&c<0?(e=Fe,s=-s,c=-c,o-=s,l-=c):s<0?(e=Re,s=-s,o-=s):c<0&&(e=je,c=-c,l-=c);break;case Re:a&&(n=t/r),o+=t,l+=n,s-=t,c-=n,s<0&&c<0?(e=je,s=-s,c=-c,o-=s,l-=c):s<0?(e=Oe,s=-s,o-=s):c<0&&(e=Fe,c=-c,l-=c);break;case je:a&&(n=t/r),s+=t,c+=n,s<0&&c<0?(e=Re,s=-s,c=-c,o-=s,l-=c):s<0?(e=Fe,s=-s,o-=s):c<0&&(e=Oe,c=-c,l-=c);break;case Fe:a&&(n=-t/r),o+=t,s-=t,c+=n,s<0&&c<0?(e=Oe,s=-s,c=-c,o-=s,l-=c):s<0?(e=je,s=-s,o-=s):c<0&&(e=Re,c=-c,l-=c)}return i&&i.$setAction(e),this.$change(o,l,s,c)}$zoom(e,t,n){if(!this.zoomable||0===e)return this;e<0?e=1/(1-e):e+=1;const{width:r,height:a}=this,i=r*e,o=a*e;let l=this.x,s=this.y;return et(t)&&et(n)?(l-=(i-r)*((t-this.x)/r),s-=(o-a)*((n-this.y)/a)):(l-=(i-r)/2,s-=(o-a)/2),this.$change(l,s,i,o)}$change(e,t,n=this.width,r=this.height,a=this.aspectRatio,i=!1){return this.$changing||!et(e)||!et(t)||!et(n)||!et(r)||n<0||r<0?this:(tt(a)&&({width:n,height:r}=xt({aspectRatio:a,width:n,height:r},"cover")),this.precise||(e=Math.round(e),t=Math.round(t),n=Math.round(n),r=Math.round(r)),e===this.x&&t===this.y&&n===this.width&&r===this.height&&Object.is(a,this.aspectRatio)&&!i?this:(this.hidden&&(this.hidden=!1),!1===this.$emit(Xe,{x:e,y:t,width:n,height:r})?this:(this.$changing=!0,this.x=e,this.y=t,this.width=n,this.height=r,this.$changing=!1,this.$render())))}$reset(){const{x:e,y:t,width:n,height:r}=this.$initialSelection;return this.$change(e,t,n,r)}$clear(){return this.$change(0,0,0,0,NaN,!0),this.hidden=!0,this}$render(){return this.$setStyles({transform:`translate(${this.x}px, ${this.y}px)`,width:this.width,height:this.height})}$toCanvas(e){return new Promise((t,n)=>{if(!this.isConnected)return void n(new Error("The current element is not connected to the DOM."));const r=document.createElement("canvas");let{width:a,height:i}=this,o=1;if(at(e)&&(tt(e.width)||tt(e.height))&&(({width:a,height:i}=xt({aspectRatio:a/i,width:e.width,height:e.height})),o=a/this.width),r.width=a,r.height=i,!this.$canvas)return void t(r);const l=this.$canvas.querySelector(this.$getTagNameOf(Ce));l?l.$ready().then(n=>{const s=r.getContext("2d");if(s){const[t,c,u,d,m,h]=l.$getTransform(),p=-this.x,f=-this.y,g=(p*d-u*f)/(t*d-u*c),b=(f*t-c*p)/(t*d-u*c);let y=t*g+u*b+m,v=c*g+d*b+h,w=n.naturalWidth,x=n.naturalHeight;1!==o&&(y*=o,v*=o,w*=o,x*=o);const k=w/2,C=x/2;s.fillStyle="transparent",s.fillRect(0,0,a,i),at(e)&&it(e.beforeDraw)&&e.beforeDraw.call(this,s,r),s.save(),s.translate(k,C),s.transform(t,c,u,d,y,v),s.translate(-k,-C),s.drawImage(n,0,0,w,x),s.restore()}t(r)}).catch(n):t(r)})}}Rt.$name=Se,Rt.$version="2.1.0";class jt extends zt{constructor(){super(...arguments),this.$style=":host{display:flex;flex-direction:column;position:relative;touch-action:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}:host([bordered]){border:1px dashed var(--theme-color)}:host([covered]){bottom:0;left:0;position:absolute;right:0;top:0}:host>span{display:flex;flex:1}:host>span+span{border-top:1px dashed var(--theme-color)}:host>span>span{flex:1}:host>span>span+span{border-left:1px dashed var(--theme-color)}",this.bordered=!1,this.columns=3,this.covered=!1,this.rows=3,this.slottable=!1,this.themeColor="rgba(238, 238, 238, 0.5)"}static get observedAttributes(){return super.observedAttributes.concat(["bordered","columns","covered","rows"])}$propertyChangedCallback(e,t,n){Object.is(n,t)||(super.$propertyChangedCallback(e,t,n),"rows"!==e&&"columns"!==e||this.$nextTick(()=>{this.$render()}))}connectedCallback(){super.connectedCallback(),this.$render()}$render(){const e=this.$getShadowRoot(),t=document.createDocumentFragment();for(let n=0;n<this.rows;n+=1){const e=document.createElement("span");e.setAttribute("role","row");for(let t=0;t<this.columns;t+=1){const t=document.createElement("span");t.setAttribute("role","gridcell"),e.appendChild(t)}t.appendChild(e)}e&&(e.innerHTML="",e.appendChild(t))}}jt.$name=xe,jt.$version="2.1.0";class Ft extends zt{constructor(){super(...arguments),this.$style=':host{display:inline-block;height:1em;position:relative;touch-action:none;-webkit-user-select:none;-moz-user-select:none;user-select:none;vertical-align:middle;width:1em}:host:after,:host:before{background-color:var(--theme-color);content:"";display:block;position:absolute}:host:before{height:1px;left:0;top:50%;transform:translateY(-50%);width:100%}:host:after{height:100%;left:50%;top:0;transform:translateX(-50%);width:1px}:host([centered]){left:50%;position:absolute;top:50%;transform:translate(-50%,-50%)}',this.centered=!1,this.slottable=!1,this.themeColor="rgba(238, 238, 238, 0.5)"}static get observedAttributes(){return super.observedAttributes.concat(["centered"])}}Ft.$name=we,Ft.$version="2.1.0";const Ut=/* @__PURE__ */new WeakMap,qt=/* @__PURE__ */new WeakMap,Bt=/* @__PURE__ */new WeakMap,Wt=/* @__PURE__ */new WeakMap,Vt="vertical";class Ht extends zt{constructor(){super(...arguments),this.$onSelectionChange=null,this.$onSourceImageLoad=null,this.$onSourceImageTransform=null,this.$scale=1,this.$style=":host{display:block;height:100%;overflow:hidden;position:relative;width:100%}",this.resize=Vt,this.selection="",this.slottable=!1}set $image(e){qt.set(this,e)}get $image(){return qt.get(this)}set $sourceImage(e){Wt.set(this,e)}get $sourceImage(){return Wt.get(this)}set $canvas(e){Ut.set(this,e)}get $canvas(){return Ut.get(this)}set $selection(e){Bt.set(this,e)}get $selection(){return Bt.get(this)}static get observedAttributes(){return super.observedAttributes.concat(["resize","selection"])}connectedCallback(){var e,t;super.connectedCallback();let n=null;if(n=this.selection?null!==(t=null===(e=function(e){const t=e.getRootNode();switch(t.nodeType){case 1:return t.ownerDocument;case 9:case 11:return t}return null}(this))||void 0===e?void 0:e.querySelector(this.selection))&&void 0!==t?t:null:this.closest(this.$getTagNameOf(Se)),ot(n)){this.$selection=n,this.$onSelectionChange=this.$handleSelectionChange.bind(this),ht(n,Xe,this.$onSelectionChange);const e=n.closest(this.$getTagNameOf(ve));if(e){this.$canvas=e;const t=e.querySelector(this.$getTagNameOf(Ce));t&&(this.$sourceImage=t,this.$image=t.cloneNode(!0),this.$getShadowRoot().appendChild(this.$image),this.$onSourceImageLoad=this.$handleSourceImageLoad.bind(this),this.$onSourceImageTransform=this.$handleSourceImageTransform.bind(this),ht(t.$image,He,this.$onSourceImageLoad),ht(t,Je,this.$onSourceImageTransform))}this.$render()}}disconnectedCallback(){const{$selection:e,$sourceImage:t}=this;e&&this.$onSelectionChange&&(mt(e,Xe,this.$onSelectionChange),this.$onSelectionChange=null),t&&this.$onSourceImageLoad&&(mt(t.$image,He,this.$onSourceImageLoad),this.$onSourceImageLoad=null),t&&this.$onSourceImageTransform&&(mt(t,Je,this.$onSourceImageTransform),this.$onSourceImageTransform=null),super.disconnectedCallback()}$handleSelectionChange(e){this.$render(e.defaultPrevented?this.$selection:e.detail)}$handleSourceImageLoad(){const{$image:e,$sourceImage:t}=this,n=e.getAttribute("src"),r=t.getAttribute("src");r&&r!==n&&(e.setAttribute("src",r),e.$ready(()=>{this.$render()}))}$handleSourceImageTransform(e){this.$render(void 0,e.detail.matrix)}$render(e,t){const{$canvas:n,$selection:r}=this;e||r.hidden||(e=r),(!e||0===e.x&&0===e.y&&0===e.width&&0===e.height)&&(e={x:0,y:0,width:n.offsetWidth,height:n.offsetHeight});const{x:a,y:i,width:o,height:l}=e,s={},{clientWidth:c,clientHeight:u}=this;let d=c,m=u,h=NaN;switch(this.resize){case"both":h=1,d=o,m=l,s.width=o,s.height=l;break;case"horizontal":h=l>0?u/l:0,d=o*h,s.width=d;break;case Vt:h=o>0?c/o:0,m=l*h,s.height=m;break;default:c>0?h=o>0?c/o:0:u>0&&(h=l>0?u/l:0)}this.$scale=h,this.$setStyles(s),this.$sourceImage&&setTimeout(()=>{this.$transformImageByOffset(null!=t?t:this.$sourceImage.$getTransform(),-a,-i)})}$transformImageByOffset(e,t,n){const{$image:r,$scale:a,$sourceImage:i}=this;if(i&&r&&a>=0){const[i,o,l,s,c,u]=e,d=(t*s-l*n)/(i*s-l*o),m=(n*i-o*t)/(i*s-l*o),h=i*d+l*m+c,p=o*d+s*m+u;r.$ready(e=>{this.$setStyles.call(r,{width:e.naturalWidth*a,height:e.naturalHeight*a})}),r.$setTransform(i,o,l,s,h*a,p*a)}}}function Kt(){const[e,n]=t(!1),[r,a]=t(null),[i,o]=t(null),l=async(e,t)=>{if(!e||!t)return a("ID de asset y configuración de variante son requeridos"),null;n(!0),a(null),o(null);try{const n=await async function(e,{variant_name:t,width:n,height:a,crop_params:i,preset_aspect:o=null,preset_size:l=null,output_format:s="webp"}){try{const r=[{name:t,width:n,height:a,output_format:s,crop_params:i}];return o&&(r[0].preset_aspect=o),l&&(r[0].preset_size=l),D(await A({endpoint:`/assets/${e}/variants`,method:"POST",body:{variants:r,async:!1},basePath:R,useJWT:!0}))}catch(r){throw O(r)}}(e,{variant_name:t.name,width:t.width,height:t.height,crop_params:t.crop_params,preset_aspect:t.preset_aspect,preset_size:t.preset_size,output_format:t.output_format});if(n?.result)return o(n.result),n.result;throw new Error("No se pudo crear la variante")}catch(i){return console.error("Error creating variant:",i),a(i.message||"Error desconocido al crear variante"),null}finally{n(!1)}};return{createVariant:l,createCropVariant:async(e,t,n={})=>{const r={name:n.name||`crop_${Date.now()}`,width:n.width||800,height:n.height||600,output_format:n.format||"webp",crop_params:{x:t.x||0,y:t.y||0,width:t.width||1,height:t.height||1}};return await l(e,r)},createVariantFromBlob:async(e,t,i={})=>{if(!e||!t)return a("ID de asset y blob son requeridos"),null;n(!0),a(null),o(null);try{const n=await async function(e,t,n={}){try{const r=new FormData,a=n.format||"webp",i=`${n.name||"variant"}.${a}`;return r.append("file",t,i),r.append("variant_name",n.name||"variant"),r.append("width",String(n.width||0)),r.append("height",String(n.height||0)),r.append("output_format",n.format||"webp"),D(await A({endpoint:`/assets/${e}/variants/upload`,method:"POST",body:r,basePath:R,isFormData:!0,useJWT:!0}))}catch(r){throw O(r)}}(e,t,{name:i.name||`crop_${Date.now()}`,width:i.width||0,height:i.height||0,format:i.format||"webp"});if(n?.result)return o(n.result),n.result;throw new Error("No se pudo crear la variante")}catch(l){return console.error("Error creating variant from blob:",l),a(l.message||"Error desconocido al crear variante"),null}finally{n(!1)}},loading:e,error:r,createdVariant:i,reset:()=>{a(null),o(null)}}}Ht.$name=Ee,Ht.$version="2.1.0",Tt.$define(),Ft.$define(),jt.$define(),Dt.$define(),Mt.$define(),Rt.$define(),Lt.$define(),Ht.$define();class Gt{constructor(e,t,n){this.canvasRef=e,this.imageRef=t,this.selectionRef=n}get canvasElement(){return this.canvasRef?.current}get image(){return this.imageRef?.current}get selectionElement(){return this.selectionRef?.current}get isReady(){return!!(this.canvasElement&&this.image&&this.selectionElement)}transform={move:(e,t)=>{if(!this.image)return!1;try{return this.image.$move(e,t),!0}catch(n){return console.warn("Error moving image:",n),!1}},moveTo:(e,t)=>{if(!this.image)return!1;try{return this.image.$moveTo(e,t),!0}catch(n){return console.warn("Error moving image to position:",n),!1}},zoom:e=>{if(!this.image)return!1;try{return this.image.$zoom(e),!0}catch(t){return console.warn("Error zooming image:",t),!1}},rotate:e=>{if(!this.image)return!1;try{const t=e*Math.PI/180;return this.image.$rotate(t),!0}catch(t){return console.warn("Error rotating image:",t),!1}},scale:(e,t=e)=>{if(!this.image)return!1;try{return this.image.$scale(e,t),!0}catch(n){return console.warn("Error scaling image:",n),!1}},center:(e="contain")=>{if(!this.image)return!1;try{return this.image.$center(e),!0}catch(t){return console.warn("Error centering image:",t),!1}},reset:()=>{if(!this.image)return!1;try{return this.image.$resetTransform(),!0}catch(e){return console.warn("Error resetting transform:",e),!1}},getTransform:()=>{if(!this.image)return null;try{return this.image.$getTransform()}catch(e){return console.warn("Error getting transform:",e),null}},setTransform:(e,t,n,r,a,i)=>{if(!this.image)return!1;try{return this.image.$setTransform(e,t,n,r,a,i),!0}catch(o){return console.warn("Error setting transform:",o),!1}},resetZoom:()=>{if(!this.image)return!1;try{const e=this.image.$getTransform();if(!e)return!1;const[t,n,r,a,i,o]=e,l=Math.sqrt(t*t+n*n),s=Math.sqrt(r*r+a*a),c=t/l,u=n/l,d=r/s,m=a/s;return this.image.$setTransform(c,u,d,m,i,o),!0}catch(e){return console.warn("Error resetting zoom:",e),!1}},setZoom:e=>{if(!this.image||e<=0)return!1;try{const t=this.image.$getTransform();if(!t)return!1;const[n,r,a,i,o,l]=t,s=Math.sqrt(n*n+r*r),c=Math.sqrt(a*a+i*i),u=n/s*e,d=r/s*e,m=a/c*e,h=i/c*e;return this.image.$setTransform(u,d,m,h,o,l),!0}catch(t){return console.warn("Error setting zoom level:",t),!1}},getZoom:()=>{if(!this.image)return 1;try{const e=this.image.$getTransform();if(!e)return 1;const[t,n]=e;return Math.sqrt(t*t+n*n)}catch(e){return console.warn("Error getting zoom level:",e),1}},fitToCanvas:(e=.1)=>{if(!this.image||!this.canvasElement)return!1;try{const t=this.canvasElement.getBoundingClientRect();let n=this.image.querySelector("img")||this.image;if(!n?.naturalWidth||!n?.naturalHeight)return!1;const r=1-e,a=t.width*r/n.naturalWidth,i=t.height*r/n.naturalHeight,o=Math.min(a,i,1);return this.transform.setZoom(o)}catch(t){return console.warn("Error fitting to canvas:",t),!1}}};selection={center:()=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$center(),!0}catch(e){return console.warn("Error centering selection:",e),!1}},reset:()=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$reset(),!0}catch(e){return console.warn("Error resetting selection:",e),!1}},setCoverage:e=>{if(!this.selectionElement||e<0||e>1)return!1;try{return this.selectionElement.initialCoverage=e,this.selectionElement.$reset(),!0}catch(t){return console.warn("Error setting coverage:",t),!1}},setAspectRatio:e=>{if(!this.selectionElement)return!1;try{let t;if(""===e||null==e)t=NaN;else if("number"==typeof e)t=e;else{if("string"!=typeof e)return console.warn("Unsupported aspect ratio type:",typeof e,e),!1;if(e.includes("/")){const[n,r]=e.split("/").map(e=>parseFloat(e.trim()));if(isNaN(n)||isNaN(r)||0===r)return console.warn("Invalid aspect ratio format:",e),!1;t=n/r}else if(t=parseFloat(e),isNaN(t))return console.warn("Invalid aspect ratio format:",e),!1}return this.selectionElement.aspectRatio=t,this.selectionElement.$render(),!0}catch(t){return console.warn("Error setting aspect ratio:",t),!1}},move:(e,t)=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$move(e,t),!0}catch(n){return console.warn("Error moving selection:",n),!1}},zoom:e=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$zoom(e),!0}catch(t){return console.warn("Error zooming selection:",t),!1}},change:(e,t,n,r,a)=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$change(e,t,n,r,a),!0}catch(i){return console.warn("Error changing selection:",i),!1}},set:(e,t,n,r)=>{if(!this.selectionElement)return!1;try{return this.selectionElement.x=e,this.selectionElement.y=t,this.selectionElement.width=n,this.selectionElement.height=r,this.selectionElement.$render(),!0}catch(a){return console.warn("Error setting selection:",a),!1}},toCanvas:async(e={})=>{if(!this.selectionElement)return null;try{const t={width:800,height:600,imageSmoothingEnabled:!0,imageSmoothingQuality:"high",...e};return await this.selectionElement.$toCanvas(t)}catch(t){return console.warn("Error exporting to canvas:",t),null}},getData:()=>{if(!this.selectionElement)return null;try{return{x:this.selectionElement.x,y:this.selectionElement.y,width:this.selectionElement.width,height:this.selectionElement.height,aspectRatio:this.selectionElement.aspectRatio}}catch(e){return console.warn("Error getting selection data:",e),null}}};canvas={setBackground:e=>{if(!this.canvasElement)return!1;try{return this.canvasElement.background=e,!0}catch(t){return console.warn("Error setting background:",t),!1}},setScaleStep:e=>{if(!this.canvasElement)return!1;try{return this.canvasElement.scaleStep=e,!0}catch(t){return console.warn("Error setting scale step:",t),!1}},setDisabled:e=>{if(!this.canvasElement)return!1;try{return this.canvasElement.disabled=e,!0}catch(t){return console.warn("Error setting disabled state:",t),!1}}};utils={flipHorizontal:()=>{const e=this.transform.getTransform();if(!e)return!1;const[t,n,r,a,i,o]=e;return this.transform.setTransform(-t,n,r,a,i,o)},flipVertical:()=>{const e=this.transform.getTransform();if(!e)return!1;const[t,n,r,a,i,o]=e;return this.transform.setTransform(t,n,r,-a,i,o)},setupInitialView:async(e={})=>{const{paspartuFactor:t=.85,retries:n=3,retryDelay:r=200}=e;return new Promise(e=>{const a=(i=0)=>{if(!this.isReady)return i<n?void setTimeout(()=>a(i+1),r):void e(!1);try{const o=this.canvasElement.getBoundingClientRect();let l=this.image.querySelector("img")||this.image;if(!l?.naturalWidth||!l?.naturalHeight)return i<n?void setTimeout(()=>a(i+1),r):(this.transform.center(),void e(!1));if(o.width>0&&o.height>0){const n=o.width*t/l.naturalWidth,r=o.height*t/l.naturalHeight,a=Math.min(n,r,1);this.transform.setTransform(a,0,0,a,0,0)?setTimeout(()=>{this.transform.center(),this.selection.center(),e(!0)},100):(this.transform.reset(),setTimeout(()=>{a<1&&this.transform.scale(a),setTimeout(()=>{this.transform.center(),this.selection.center(),e(!0)},100)},100))}else this.transform.center(),e(!1)}catch(o){console.warn("Error in setup:",o),this.transform.center(),e(!1)}};a()})},resetAll:()=>{const e={transform:this.transform.reset(),selection:this.selection.reset(),center:!1};return setTimeout(()=>{e.center=this.transform.center()&&this.selection.center()},100),e},checkExportability:async()=>{try{return!!(await this.selection.toCanvas({width:1,height:1}))}catch{return!1}},resetZoomOnly:()=>this.transform.resetZoom(),getZoomInfo:()=>{const e=this.transform.getZoom();return{current:e,isZoomedIn:e>1,isZoomedOut:e<1,percentage:Math.round(100*e)}},setBackground:e=>this.canvas.setBackground(e)};setupEventListeners(e={}){const{onSelectionChange:t,onImageTransform:n,onAction:r,onActionStart:a,onActionMove:i,onActionEnd:o}=e,l=[];if(t&&this.selectionElement){const e=e=>{t({x:e.detail.x,y:e.detail.y,width:e.detail.width,height:e.detail.height})};this.selectionElement.addEventListener("change",e),l.push(()=>{this.selectionElement&&this.selectionElement.removeEventListener("change",e)})}if(n&&this.image){const e=e=>{n({matrix:e.detail.matrix,oldMatrix:e.detail.oldMatrix})};this.image.addEventListener("transform",e),l.push(()=>{this.image&&this.image.removeEventListener("transform",e)})}if(this.canvasElement){if(r){const e=e=>r(e.detail);this.canvasElement.addEventListener("action",e),l.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("action",e)})}if(a){const e=e=>a(e.detail);this.canvasElement.addEventListener("actionstart",e),l.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionstart",e)})}if(i){const e=e=>i(e.detail);this.canvasElement.addEventListener("actionmove",e),l.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionmove",e)})}if(o){const e=e=>o(e.detail);this.canvasElement.addEventListener("actionend",e),l.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionend",e)})}}return()=>{l.forEach(e=>e())}}}async function Qt(e,t,n={}){const{format:r=null,originalFormat:a="webp",onSuccess:i=null,onError:o=null,accessibilityManager:l=null}=n;try{const n=window.limboCore?.config?.getGlobal(),o=r||n?.downloadFormat||a||"webp",s=`${t.split(".")[0]}.${o}`;if(l&&l.announce(`Descargando ${s}`),e.startsWith("data:image/"))return function(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.style.display="none",document.body.appendChild(n),n.click(),setTimeout(()=>{document.body.removeChild(n)},100)}(e,s),i&&i(s),l&&l.announce(`${s} descargado correctamente`),!0;const c=await fetch(e,{mode:"cors"});if(!c.ok)throw new Error(`HTTP error! status: ${c.status}`);const u=await c.blob();let d=u;const m=u.type;m!==`image/${"jpg"===o?"jpeg":o}`&&function(e){return["webp","jpeg","jpg","png"].includes(e.toLowerCase())}(o)&&(d=await async function(e,t){return new Promise((n,r)=>{const a=new Image,i=URL.createObjectURL(e);a.onload=()=>{try{const r=document.createElement("canvas");r.width=a.width,r.height=a.height;r.getContext("2d").drawImage(a,0,0);const o=`image/${"jpg"===t?"jpeg":t}`,l="png"===t?void 0:.92;r.toBlob(t=>{URL.revokeObjectURL(i),n(t||e)},o,l)}catch(r){URL.revokeObjectURL(i),n(e)}},a.onerror=()=>{URL.revokeObjectURL(i),n(e)},a.src=i})}(u,o));const h=window.URL.createObjectURL(d),p=document.createElement("a");return p.href=h,p.download=s,p.style.display="none",document.body.appendChild(p),p.click(),setTimeout(()=>{window.URL.revokeObjectURL(h),document.body.removeChild(p)},100),i&&i(s),l&&l.announce(`${s} descargado correctamente`),!0}catch(s){return console.error("Error downloading image:",s),o&&o(s),l&&l.announce(`Error al descargar la imagen: ${s.message}`),!1}}const Yt=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:Qt,downloadImage:Qt},Symbol.toStringTag,{value:"Module"}));function Xt({image:e,onSave:o,onCancel:u,onDelete:d,onError:m=null,deleting:h=!1,onVariantCreated:p=null,onUpload:f=null,uploading:g=!1,cropperConfig:b=null}){const[y,v]=t(!1),[w,x]=t(null),[k,C]=t(!1),[S,N]=t(!0),[E,$]=t(!0),[_,z]=t({x:20,y:100}),[T,A]=t(!1),[P,M]=t({x:0,y:0}),[I,L]=t(!1),[D,O]=t(!0),[R,j]=t(!1),[F,U]=t({horizontal:!1,vertical:!1}),[q,W]=t(!1),[V,H]=t(!1),[K,G]=t(!1),[Q,Y]=t(!1),[X]=t(()=>{if(!e||!e.filename)return"image";const[t]=e.filename.split(".");return t}),J=i(()=>{if(b)return{mandatoryCrops:b.mandatoryCrops||[],allowCustomCrops:!1!==b.allowAdditionalCrops,showDimensionInputs:!0===b.showDimensionInputs,maxCrops:b.maxCrops||null};const e=window.limboCore?.config?.getGlobal()||{};return{mandatoryCrops:e.cropper?.mandatoryCrops||[],allowCustomCrops:!1!==e.cropper?.allowCustomCrops,showDimensionInputs:!0===e.cropper?.showDimensionInputs,maxCrops:e.cropper?.maxCrops||null}},[b]),[Z,ee]=t(()=>J.mandatoryCrops.length>0?J.mandatoryCrops.map((e,t)=>({id:`crop-${t}`,label:e.label,width:e.width,height:e.height,required:!1!==e.required,isCustom:!1,confirmed:!1,lockDimensions:!(!e.width||!e.height),savedState:null})):[{id:"crop-default-0",label:X,width:e.width||1920,height:e.height||1080,required:!1,isCustom:!0,confirmed:!1,savedState:null}]),[ne,re]=t(0),ae=Z[ne],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]),[le,se]=t(!1),[ce,ue]=t([]),[de,me]=t(null),he=window.limboCore?.accessibilityManager,{createVariantFromBlob:pe,loading:fe,error:ge}=Kt(),be=((e,i={})=>{const o=a(null),l=a(null),s=a(null),c=a(null),[u,d]=t(null),[m,h]=t(null),[p,f]=t(!1),[g,b]=t(!0),[y,v]=t(0),w={aspectRatio:"",shade:!0,paspartuFactor:.85,...i};n(()=>{o.current&&l.current&&s.current&&(c.current=new Gt(o,l,s),f(!0))},[]),n(()=>{if(c.current)return c.current.setupEventListeners({onSelectionChange:e=>{d(e)},onImageTransform:()=>{v(e=>e+1)}})},[p]),n(()=>{c.current&&e&&(async()=>{c.current.selection.setAspectRatio(w.aspectRatio),c.current.canvas.setBackground(w.shade),await c.current.utils.setupInitialView({paspartuFactor:w.paspartuFactor});const e=await c.current.utils.checkExportability();b(e);const t=l.current?.querySelector("img")||l.current;t?.naturalWidth&&t?.naturalHeight&&h({naturalWidth:t.naturalWidth,naturalHeight:t.naturalHeight,currentWidth:t.width,currentHeight:t.height})})()},[e]),n(()=>{c.current&&p&&c.current.selection.setAspectRatio(w.aspectRatio)},[w.aspectRatio,p]),n(()=>{c.current&&p&&c.current.canvas.setBackground(w.shade)},[w.shade,p]);const x=r(()=>({move:(e,t)=>c.current?.transform.move(e,t)||!1,zoom:e=>c.current?.transform.zoom(e)||!1,rotate:e=>c.current?.transform.rotate(e)||!1,center:()=>c.current?.transform.center()||!1,reset:()=>c.current?.transform.reset()||!1,resetZoom:()=>c.current?.transform.resetZoom()||!1,setZoom:e=>c.current?.transform.setZoom(e)||!1,getZoom:()=>c.current?.transform.getZoom()||1,fitToCanvas:e=>c.current?.transform.fitToCanvas(e)||!1,flipHorizontal:()=>c.current?.utils.flipHorizontal()||!1,flipVertical:()=>c.current?.utils.flipVertical()||!1}),[]),k=r(()=>({center:()=>c.current?.selection.center()||!1,reset:()=>c.current?.selection.reset()||!1,setCoverage:e=>c.current?.selection.setCoverage(e)||!1,setAspectRatio:e=>c.current?.selection.setAspectRatio(e)||!1,toCanvas:e=>c.current?.selection.toCanvas(e)||Promise.resolve(null)}),[]),C=r(()=>({resetAll:()=>{if(c.current){const e=c.current.utils.resetAll();return d(null),e}return!1},setBackground:e=>c.current?.canvas.setBackground(e)||!1,resetZoomOnly:()=>c.current?.utils.resetZoomOnly()||!1,getZoomInfo:()=>c.current?.utils.getZoomInfo()||{current:1,percentage:100,isZoomedIn:!1,isZoomedOut:!1}}),[]);return{refs:{canvasRef:o,imageRef:l,selectionRef:s},state:{cropData:u,imageInfo:m,isReady:p,canExport:g,transformVersion:y},transform:x(),selection:k(),utils:C(),manager:c.current}})(e,{aspectRatio:ie||null,showGrid:S,shade:E,initialCoverage:.5,paspartuFactor:.85}),{refs:ye,state:ve,transform:we,selection:xe,utils:ke}=be,{canvasRef:Ce,imageRef:Se,selectionRef:Ne}=ye,{cropData:Ee,imageInfo:$e,canExport:_e,transformVersion:ze}=ve,Te=i(()=>$e||{naturalWidth:e.width||1920,naturalHeight:e.height||1080,currentWidth:e.width||1920,currentHeight:e.height||1080},[$e,e.width,e.height]),Ae=r(()=>N(e=>!e),[]),Pe=r(()=>$(e=>!e),[]),Me=r(()=>H(e=>!e),[]),Ie=r(()=>G(e=>!e),[]),Le=r(()=>Y(e=>!e),[]),De=r(()=>we.center(),[we]),Oe=r(()=>xe.center(),[xe]),Re=r(()=>xe.reset(),[xe]),je=r((e,t)=>we.move(e,t),[we]),Fe=r(e=>we.zoom(e),[we]),Ue=r(e=>we.rotate(e),[we]),qe=r(e=>{xe.setCoverage(e)},[xe]),Be=r(()=>{U(e=>{const t=!e.horizontal;return we.flipHorizontal(),{...e,horizontal:t}})},[we]),We=r(()=>{U(e=>{const t=!e.vertical;return we.flipVertical(),{...e,vertical:t}})},[we]),Ve=r(()=>{if(!be.manager||!ve.isReady)return null;try{const e=Ee?{...Ee}:null;let t=null;if(Ne.current){const e=Ne.current;t={x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0}}let n=null;if(Se.current){const e=Se.current.$getTransform?.();e&&Array.isArray(e)&&(n=[...e])}const r={cropData:e,selectorState:t,imageTransform:n,flipState:{horizontal:F.horizontal,vertical:F.vertical}};return console.log(`[CropperView] 💾 Guardando estado del crop ${ne}:`,r),ee(e=>e.map((e,t)=>t===ne?{...e,savedState:r}:e)),r}catch(e){return console.warn("Error saving crop state:",e),null}},[be.manager,ve.isReady,Ee,F,ne,Se,Ne]),He=r(e=>{const t=Z[e];if(!t||!t.savedState)return console.log(`[CropperView] ℹ️ No hay estado guardado para crop ${e}, centrando...`),void setTimeout(()=>{De(),setTimeout(()=>Oe(),100)},100);if(be.manager&&ve.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,r,a,i,o]=n.imageTransform;Se.current.$setTransform(e,t,r,a,i,o),console.log(`[CropperView] ✅ Imagen restaurada: transform(${e.toFixed(2)}, ${t.toFixed(2)}, ${r.toFixed(2)}, ${a.toFixed(2)}, ${i.toFixed(0)}, ${o.toFixed(0)})`)}},100),n.selectorState&&Ne.current){const{x:e,y:t,width:r,height:a}=n.selectorState;setTimeout(()=>{Ne.current&&(Ne.current.x=e,Ne.current.y=t,Ne.current.width=r,Ne.current.height=a,Ne.current.$render&&Ne.current.$render(),console.log(`[CropperView] ✅ Selector restaurado: ${r}×${a} en (${e}, ${t})`))},150)}n.flipState&&U({horizontal:n.flipState.horizontal??!1,vertical:n.flipState.vertical??!1}),console.log("[CropperView] ✨ Estado restaurado completamente")}catch(n){console.error("Error restoring crop state:",n),setTimeout(()=>{De(),setTimeout(()=>Oe(),100)},100)}else console.warn("Cropper not ready for state restoration")},[Z,be.manager,ve.isReady,De,Oe,Ne,Se]),Ke=r(()=>{for(let e=0;e<Z.length;e++){const t=Z[e];if(!t.label||""===t.label.trim())return e}return-1},[Z]),Ge=r(async e=>{e!==ne&&(j(!0),Ve(),await new Promise(e=>setTimeout(e,100)),re(e),await new Promise(e=>setTimeout(e,250)),He(e),await new Promise(e=>setTimeout(e,200)),j(!1))},[ne,Ve,He]),Qe=r(()=>{if(!J.allowCustomCrops)return void alert("No se pueden añadir recortes personalizados en este modo.");const t={id:`crop-custom-${Date.now()}`,label:`Recorte ${Z.length+1}`,width:e.width||1920,height:e.height||1080,required:!1,isCustom:!0,confirmed:!1,savedState:null};ee(e=>[...e,t]),he?.announce(`Nuevo recorte personalizado añadido: ${t.label}. Selecciónalo para editarlo.`)},[J.allowCustomCrops,Z.length,e.width,e.height,he]),Ye=r((e,t)=>{const n=parseInt(t,10);""===t||isNaN(n)||ee(t=>t.map((t,r)=>r===ne?{...t,[e]:n}:t))},[ne]),Xe=r(e=>{const t=ae[e];let n=100;if(Ce.current&&$e){const e=Ce.current.getBoundingClientRect(),t=Math.min(e.width,e.height);n=Math.max(100,Math.round(.05*t))}const r=Math.max(n,Math.min(5e3,t));r!==t&&ee(t=>t.map((t,n)=>n===ne?{...t,[e]:r}:t));const a={...ae,[e]:r},i=a.width/a.height,o=xe.getData?.();xe.setAspectRatio(i),o&&void 0!==o.x&&setTimeout(()=>{xe.set?.(o.x,o.y,o.width,o.height)},50)},[ne,ae,xe,Ce,$e]),Je=r(e=>{ee(t=>t.map((t,n)=>n===ne?{...t,label:e}:t))},[ne]),Ze=r((e,t=null)=>{t=t||Z[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=Z[e];if(n.required)alert("No se puede eliminar un recorte obligatorio.");else if(1!==Z.length){if(ee(t=>t.filter((t,n)=>n!==e)),e===ne){const t=Math.max(0,e-1);re(t)}else e<ne&&re(e=>e-1);he?.announce(`Recorte ${n.label} eliminado`)}else alert("Debe haber al menos un recorte.")},[Z,ne,he]),et=r(async()=>{if(!_e)return null;try{const t=await xe.toCanvas({width:800,height:600,imageSmoothingEnabled:!0,imageSmoothingQuality:"high"});return t?t.toDataURL(`image/${globalThis.downloadFormat||e.mime_type.split("/")[1]||"webp"}`,.9):null}catch(t){return console.warn("Error generating preview:",t),null}},[_e,e.mime_type,xe]),tt=r(async()=>{if(y)return v(!1),x(null),void C(!1);if(_e){v(!0),C(!0);try{const e=await et();e?x(e):(v(!1),alert("No se puede exportar el recorte por restricciones de CORS en la imagen original."))}finally{C(!1)}}else alert("No se puede exportar el recorte por restricciones de CORS en la imagen original.")},[_e,et,y]),nt=r(e=>{e.target.closest(".limbo-preview-modal-header")&&(A(!0),M({x:e.clientX-_.x,y:e.clientY-_.y}))},[_]),rt=r(e=>{T&&(e.preventDefault(),z({x:e.clientX-P.x,y:e.clientY-P.y}))},[T,P]),at=r(()=>{A(!1)},[]),it=r(e=>{if(!e.target.closest(".limbo-preview-modal-header"))return;const t=e.touches[0];A(!0),M({x:t.clientX-_.x,y:t.clientY-_.y})},[_]),ot=r(e=>{if(!T)return;e.preventDefault();const t=e.touches[0];z({x:t.clientX-P.x,y:t.clientY-P.y})},[T,P]),lt=r(()=>{A(!1)},[]);n(()=>{if(T)return document.addEventListener("mousemove",rt),document.addEventListener("mouseup",at),document.addEventListener("touchmove",ot,{passive:!1}),document.addEventListener("touchend",lt),()=>{document.removeEventListener("mousemove",rt),document.removeEventListener("mouseup",at),document.removeEventListener("touchmove",ot),document.removeEventListener("touchend",lt)}},[T,rt,at,ot,lt]),n(()=>{if(!I)return;const e=e=>{"Escape"===e.key&&L(!1)};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[I]);const st=r(async(t,n=null)=>{const r=Z[t];if(!r)throw new Error(`Crop ${t} no encontrado`);if(!r.savedState&&t!==ne)throw new Error(`El recorte "${r.label}" aún no ha sido configurado`);const a={index:ne,imageTransform:Se.current?.$getTransform?.(),selectorState:Ne.current?{x:Ne.current.x,y:Ne.current.y,width:Ne.current.width,height:Ne.current.height}:null};try{if(t!==ne&&r.savedState){if(console.log(`[CropperView] 🔄 Restaurando temporalmente crop ${t} para guardado...`),r.savedState.imageTransform&&Se.current?.$setTransform){const[e,t,n,a,i,o]=r.savedState.imageTransform;Se.current.$setTransform(e,t,n,a,i,o)}if(r.savedState.selectorState&&Ne.current){const{x:e,y:t,width:n,height:a}=r.savedState.selectorState;Ne.current.x=e,Ne.current.y=t,Ne.current.width=n,Ne.current.height=a,Ne.current.$render?.()}await new Promise(e=>setTimeout(e,100))}const a=Math.min(r.width,5e3),i=Math.min(r.height,5e3),o=await xe.toCanvas({width:a,height:i,imageSmoothingEnabled:!0,imageSmoothingQuality:"high"});if(!o)throw new Error(`No se pudo generar el canvas para "${r.label}"`);const l=globalThis.downloadFormat||"webp",s="webp"===l?"image/webp":"png"===l?"image/png":"image/jpeg",c=.9,u=await new Promise((e,t)=>{o.toBlob(n=>{n?e(n):t(new Error("No se pudo convertir el canvas a blob"))},s,c)});console.log("[CropperView] Canvas convertido a blob:",{size:u.size,type:u.type,dimensions:`${a}x${i}`});const d=`${r.label||"crop"}_${a}_${i}`,m=n||e.id,h=await pe(m,u,{name:d,width:a,height:i,format:l});if(h)return he?.announceSuccess(`Recorte creado: ${d}`),p?.(m,h),h;throw new Error("No se pudo crear la variante")}finally{if(t!==ne&&a.imageTransform&&Se.current?.$setTransform){console.log(`[CropperView] ↩️ Restaurando estado original del crop ${a.index}...`);const[e,t,n,r,i,o]=a.imageTransform;if(Se.current.$setTransform(e,t,n,r,i,o),a.selectorState&&Ne.current){const{x:e,y:t,width:n,height:r}=a.selectorState;Ne.current.x=e,Ne.current.y=t,Ne.current.width=n,Ne.current.height=r,Ne.current.$render?.()}}}},[Z,ne,xe,pe,e.id,p,he,Se,Ne]),ct=r(async()=>{if(!_e){const e="No se puede exportar el recorte por restricciones de CORS en la imagen original.";return he?.announceError(e),void alert(e)}if(!ve.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)}Ve(),he?.announce("Creando recorte de la imagen");try{let t=e.id,n=null;if(e.file&&f){he?.announce("Subiendo imagen...");const r=await f(e.file);if(!r||!r.id)throw new Error("No se pudo subir la imagen al servidor");t=r.id,n=r,he?.announceSuccess("Imagen subida correctamente")}const r=await st(ne,t);r&&o(n?{crops:[r],asset:n}:r)}catch(t){console.warn("Error creating crop variant:",t);const e=t.message||"No se pudo crear el recorte. Inténtalo de nuevo.";he?.announceError(e),alert(e),m?.(t)}},[_e,ve.isReady,he,Ve,st,ne,o,m,e.file,e.id,f]),ut=r(async t=>{Ve(),he?.announce(`Guardando ${t.length} recortes...`);try{let r=e.id,a=null;if(e.file&&f){he?.announce("Subiendo imagen...");const t=await f(e.file);if(!t||!t.id)throw new Error("No se pudo subir la imagen al servidor");r=t.id,a=t,he?.announceSuccess("Imagen subida correctamente")}const i=[],l=[];for(const e of t)try{const t=await st(e,r);t&&i.push(t)}catch(n){l.push({crop:Z[e]?.label||`Crop ${e}`,error:n.message})}if(i.length>0&&(he?.announceSuccess(`${i.length} recorte(s) guardado(s) correctamente`),o(a?{crops:i,asset:a}:i)),l.length>0){const e=`Errores al guardar algunos recortes:\n${l.map(e=>`- ${e.crop}: ${e.error}`).join("\n")}`;he?.announceError(e),alert(e)}}catch(n){const e=n.message||"Error al procesar los recortes";he?.announceError(e),alert(e),m?.(n)}},[Ve,st,Z,he,o,e.file,e.id,f,m]),dt=r(async()=>{const e=Ke();if(-1!==e){const t=Z[e];return alert(`El recorte "${t.label||t||"(sin nombre)"}" debe tener un nombre válido.`),void re(e)}if(Z.length>1){me("save");const e=Z.map((e,t)=>({crop:e,index:t})).filter(({crop:e,index:t})=>e.required||e.savedState||t===ne).map(({index:e})=>e);return ue(e),void se(!0)}await ct()},[Ke,Z,ct,ne]),mt=r(async t=>{const n=Z[t];if(!n)throw new Error(`Crop ${t} no encontrado`);if(!n.savedState&&t!==ne)throw new Error(`El recorte "${n.label}" aún no ha sido configurado`);const r={index:ne,imageTransform:Se.current?.$getTransform?.(),selectorState:Ne.current?{x:Ne.current.x,y:Ne.current.y,width:Ne.current.width,height:Ne.current.height}:null};try{if(t!==ne&&n.savedState){if(console.log(`[CropperView] 🔄 Restaurando temporalmente crop ${t} para descarga...`),n.savedState.imageTransform&&Se.current?.$setTransform){const[e,t,r,a,i,o]=n.savedState.imageTransform;Se.current.$setTransform(e,t,r,a,i,o)}if(n.savedState.selectorState&&Ne.current){const{x:e,y:t,width:r,height:a}=n.savedState.selectorState;Ne.current.x=e,Ne.current.y=t,Ne.current.width=r,Ne.current.height=a,Ne.current.$render?.()}await new Promise(e=>setTimeout(e,100))}const r=await xe.toCanvas({width:n.width,height:n.height,imageSmoothingEnabled:!0,imageSmoothingQuality:"high"});if(!r)throw new Error(`No se pudo generar el canvas para "${n.label}"`);const a=r.toDataURL(`image/${globalThis.downloadFormat||e.mime_type.split("/")[1]||"webp"}`,.9),i=`${(n.label||"crop").replace(/\.[^/.]+$/,"").replace(/\s+/g,"-").trim()}_${n.width}_${n.height}`;return await Qt(a,i,{accessibilityManager:he,onSuccess:e=>{console.log(`✅ Descargado: ${e}`)},onError:e=>{throw new Error(`Error al descargar "${n.label}": ${e.message}`)}}),{crop:n.label,filename:i}}finally{if(t!==ne&&r.imageTransform&&Se.current?.$setTransform){console.log(`[CropperView] ↩️ Restaurando estado original del crop ${r.index}...`);const[e,t,n,a,i,o]=r.imageTransform;if(Se.current.$setTransform(e,t,n,a,i,o),r.selectorState&&Ne.current){const{x:e,y:t,width:n,height:a}=r.selectorState;Ne.current.x=e,Ne.current.y=t,Ne.current.width=n,Ne.current.height=a,Ne.current.$render?.()}}}},[Z,ne,xe,e.mime_type,he,Se,Ne]),ht=r(async e=>{Ve(),he?.announce(`Descargando ${e.length} recortes...`);const t=[],n=[];for(const a of e)try{const e=await mt(a);e&&t.push(e)}catch(r){n.push({crop:Z[a]?.label||`Crop ${a}`,error:r.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)}},[Ve,mt,Z,he]),pt=r(async()=>{if(!_e){const e="No se puede descargar el recorte por restricciones de CORS en la imagen original.";return he?.announceError(e),void alert(e)}Ve(),he?.announce("Preparando descarga del recorte");try{await mt(ne),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)}},[_e,he,Ve,mt,ne]),ft=r(async()=>{const e=Ke();if(-1!==e){const t=Z[e];return alert(`El recorte "${t.label||t||"(sin nombre)"}" debe tener un nombre válido.`),void re(e)}if(Z.length>1){me("download");const e=Z.map((e,t)=>({crop:e,index:t})).filter(({crop:e,index:t})=>e.savedState||t===ne).map(({index:e})=>e);return ue(e),void se(!0)}await pt()},[Ke,Z,pt,ne]),gt=r(async()=>{if(e.file&&f)try{he?.announce("Subiendo imagen original...");const t=await f(e.file);if(!t||!t.id)throw new Error("No se pudo subir la imagen al servidor");he?.announceSuccess("Imagen guardada correctamente"),o({asset:t,crops:[]})}catch(t){console.error("Error guardando imagen original:",t);const e=t.message||"No se pudo guardar la imagen. Inténtalo de nuevo.";he?.announceError(e),alert(e),m?.(t)}else u()},[e.file,f,u,o,m,he]);return n(()=>{v(!1),x(null)},[e]),n(()=>{be.manager&&ve.isReady&&D&&(console.log("[CropperView] Carga inicial completada, centrando imagen y selector..."),setTimeout(()=>{De(),setTimeout(()=>{Oe(),O(!1),console.log("[CropperView] Carga inicial finalizada")},100)},50))},[be.manager,ve.isReady,D,De,Oe]),n(()=>{be.manager&&ve.isReady&&(ie&&xe.setAspectRatio(ie),ke.setBackground(E))},[ie,E,be.manager,ve.isReady,xe,ke]),n(()=>{if(!$e||!ve.isReady||J.mandatoryCrops.length>0)return;const e=Z[0];if(e&&"crop-default-0"===e.id&&(1920===e.width||1080===e.height)){const t=Math.min($e.naturalWidth,5e3),n=Math.min($e.naturalHeight,5e3);ee([{...e,width:t,height:n}]),console.log(`[CropperView] Crop por defecto actualizado a ${t}×${n}px`)}},[$e,ve.isReady,J.mandatoryCrops.length,Z]),n(()=>{if(!y||!_e)return;const e=setTimeout(async()=>{C(e=>!w&&!e||e);try{const e=await et();e&&x(e)}finally{C(!1)}},300);return()=>{clearTimeout(e),C(!1)}},[Ee,ze,y,_e,et,ie,F,w]),n(()=>{const e=Ce.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)}},[Ce]),e?/* @__PURE__ */s("div",{className:"limbo-cropper-view px-2 border-2 border-gray-200/50 rounded-lg max-w-7xl mx-auto w-full min-w-full h-full min-h-full flex flex-col",children:[
228
+ /* @__PURE__ */s("div",{className:"limbo-tab-content px-2 py-2",role:"tabpanel",id:`upload-tabpanel-${u}`,"aria-labelledby":`upload-tab-${u}`,children:["upload"===u&&/* @__PURE__ */l(Q,{file:m,setFile:h,previewUrl:p,setPreviewUrl:f,fileInputRef:g,onSelect:e,disabled:n}),"ai"===u&&/* @__PURE__ */l(ne,{apiKey:r,prod:i,disabled:n,onSelect:e}),"stock"===u&&/* @__PURE__ */l(oe,{apiKey:r,prod:i,disabled:n,onSelect:e}),"portals"===u&&/* @__PURE__ */l(de,{apiKey:r,prod:i,disabled:n,onSelect:e})]})]})}const pe="undefined"!=typeof window&&void 0!==window.document,fe=pe?window:{},ge=!!pe&&"ontouchstart"in fe.document.documentElement,be=!!pe&&"PointerEvent"in fe,ye="cropper",ve=`${ye}-canvas`,we=`${ye}-crosshair`,xe=`${ye}-grid`,ke=`${ye}-handle`,Ce=`${ye}-image`,Se=`${ye}-selection`,Ne=`${ye}-shade`,Ee=`${ye}-viewer`,$e="select",_e="move",ze="scale",Te="rotate",Ae="transform",Pe="none",Me="n-resize",Ie="e-resize",Le="s-resize",De="w-resize",Oe="ne-resize",Re="nw-resize",je="se-resize",Fe="sw-resize",Ue=be?"pointerdown":ge?"touchstart":"mousedown",qe=be?"pointermove":ge?"touchmove":"mousemove",Be=be?"pointerup pointercancel":ge?"touchend touchcancel":"mouseup",We="error",Ve="keydown",He="load",Ke="wheel",Ge="action",Qe="actionend",Ye="actionstart",Xe="change",Je="transform";const Ze=Number.isNaN||fe.isNaN;function et(e){return"number"==typeof e&&!Ze(e)}function tt(e){return et(e)&&e>0&&e<1/0}function nt(e){return"object"==typeof e&&null!==e}const{hasOwnProperty:rt}=Object.prototype;function at(e){if(!nt(e))return!1;try{const{constructor:t}=e,{prototype:n}=t;return t&&n&&rt.call(n,"isPrototypeOf")}catch(t){return!1}}function it(e){return"function"==typeof e}function ot(e){return"object"==typeof e&&null!==e&&1===e.nodeType}const lt=/([a-z\d])([A-Z])/g;function st(e){return String(e).replace(lt,"$1-$2").toLowerCase()}const ct=/-[A-z\d]/g;function ut(e){return e.replace(ct,e=>e.slice(1).toUpperCase())}const dt=/\s\s*/;function mt(e,t,n,r){t.trim().split(dt).forEach(t=>{e.removeEventListener(t,n,r)})}function ht(e,t,n,r){t.trim().split(dt).forEach(t=>{e.addEventListener(t,n,r)})}function pt(e,t,n,r){ht(e,t,n,Object.assign(Object.assign({},r),{once:!0}))}const ft={bubbles:!0,cancelable:!0,composed:!0};const gt=Promise.resolve();function bt(e){const{documentElement:t}=e.ownerDocument,n=e.getBoundingClientRect();return{left:n.left+(fe.pageXOffset-t.clientLeft),top:n.top+(fe.pageYOffset-t.clientTop)}}const yt=/deg|g?rad|turn$/i;function vt(e){const t=parseFloat(e)||0;if(0!==t){const[n="rad"]=String(e).match(yt)||[];switch(n.toLowerCase()){case"deg":return t/360*(2*Math.PI);case"grad":return t/400*(2*Math.PI);case"turn":return t*(2*Math.PI)}}return t}const wt="contain";function xt(e,t=wt){const{aspectRatio:n}=e;let{width:r,height:a}=e;const i=tt(r),o=tt(a);if(i&&o){const e=a*n;t===wt&&e>r||"cover"===t&&e<r?a=r/n:r=a*n}else i?a=r/n:o&&(r=a*n);return{width:r,height:a}}function kt(e,...t){if(0===t.length)return e;const[n,r,a,i,o,l]=e,[s,c,u,d,m,h]=t[0];return kt(e=[n*s+a*c,r*s+i*c,n*u+a*d,r*u+i*d,n*m+a*h+o,r*m+i*h+l],...t.slice(1))}const Ct=/left|top|width|height/i,St="open",Nt=/* @__PURE__ */new WeakMap,Et=/* @__PURE__ */new WeakMap,$t=/* @__PURE__ */new Map,_t=fe.document&&Array.isArray(fe.document.adoptedStyleSheets)&&"replaceSync"in fe.CSSStyleSheet.prototype;class zt extends HTMLElement{get $sharedStyle(){return(this.themeColor?`:host{--theme-color: ${this.themeColor};}`:"")+":host([hidden]){display:none!important}"}constructor(){var e,t;super(),this.shadowRootMode=St,this.slottable=!0;const n=null===(t=null===(e=Object.getPrototypeOf(this))||void 0===e?void 0:e.constructor)||void 0===t?void 0:t.$name;n&&$t.set(n,this.tagName.toLowerCase())}static get observedAttributes(){return["shadow-root-mode","slottable","theme-color"]}attributeChangedCallback(e,t,n){if(Object.is(n,t))return;const r=ut(e);let a=n;switch(typeof this[r]){case"boolean":a=null!==n&&"false"!==n;break;case"number":a=Number(n)}switch(this[r]=a,e){case"theme-color":{const e=Et.get(this),t=this.$sharedStyle;e&&t&&(_t?e.replaceSync(t):e.textContent=t);break}}}$propertyChangedCallback(e,t,n){if(!Object.is(n,t))switch(e=st(e),typeof n){case"boolean":!0===n?this.hasAttribute(e)||this.setAttribute(e,""):this.removeAttribute(e);break;case"number":n=Ze(n)?"":String(n);default:n?this.getAttribute(e)!==n&&this.setAttribute(e,n):this.removeAttribute(e)}}connectedCallback(){Object.getPrototypeOf(this).constructor.observedAttributes.forEach(e=>{const t=ut(e);let n=this[t];(function(e){return void 0===e})(n)||this.$propertyChangedCallback(t,void 0,n),Object.defineProperty(this,t,{enumerable:!0,configurable:!0,get:()=>n,set(e){const r=n;n=e,this.$propertyChangedCallback(t,r,e)}})});const e=this.shadowRoot||this.attachShadow({mode:this.shadowRootMode||St});if(Nt.set(this,e),Et.set(this,this.$addStyles(this.$sharedStyle)),this.$style&&this.$addStyles(this.$style),this.$template){const t=document.createElement("template");t.innerHTML=this.$template,e.appendChild(t.content)}if(this.slottable){const t=document.createElement("slot");e.appendChild(t)}}disconnectedCallback(){Et.has(this)&&Et.delete(this),Nt.has(this)&&Nt.delete(this)}$getTagNameOf(e){var t;return null!==(t=$t.get(e))&&void 0!==t?t:e}$setStyles(e){return Object.keys(e).forEach(t=>{let n=e[t];et(n)&&(n=0!==n&&Ct.test(t)?`${n}px`:String(n)),this.style[t]=n}),this}$getShadowRoot(){return this.shadowRoot||Nt.get(this)}$addStyles(e){let t;const n=this.$getShadowRoot();return _t?(t=new CSSStyleSheet,t.replaceSync(e),n.adoptedStyleSheets=n.adoptedStyleSheets.concat(t)):(t=document.createElement("style"),t.textContent=e,n.appendChild(t)),t}$emit(e,t,n){return function(e,t,n,r){return e.dispatchEvent(new CustomEvent(t,Object.assign(Object.assign(Object.assign({},ft),{detail:n}),r)))}(this,e,t,n)}$nextTick(e){return function(e,t){return t?gt.then(e?t.bind(e):t):gt}(this,e)}static $define(e,t){nt(e)&&(t=e,e=""),e||(e=this.$name||this.name),e=st(e),pe&&fe.customElements&&!fe.customElements.get(e)&&customElements.define(e,this,t)}}zt.$version="2.1.0";class Tt extends zt{constructor(){super(...arguments),this.$onPointerDown=null,this.$onPointerMove=null,this.$onPointerUp=null,this.$onWheel=null,this.$wheeling=!1,this.$pointers=/* @__PURE__ */new Map,this.$style=':host{display:block;min-height:100px;min-width:200px;overflow:hidden;position:relative;touch-action:none;-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}:host([background]){background-color:#fff;background-image:repeating-linear-gradient(45deg,#ccc 25%,transparent 0,transparent 75%,#ccc 0,#ccc),repeating-linear-gradient(45deg,#ccc 25%,transparent 0,transparent 75%,#ccc 0,#ccc);background-image:repeating-conic-gradient(#ccc 0 25%,#fff 0 50%);background-position:0 0,.5rem .5rem;background-size:1rem 1rem}:host([disabled]){pointer-events:none}:host([disabled]):after{bottom:0;content:"";cursor:not-allowed;display:block;left:0;pointer-events:none;position:absolute;right:0;top:0}',this.$action=Pe,this.background=!1,this.disabled=!1,this.scaleStep=.1,this.themeColor="#39f"}static get observedAttributes(){return super.observedAttributes.concat(["background","disabled","scale-step"])}connectedCallback(){super.connectedCallback(),this.disabled||this.$bind()}disconnectedCallback(){this.disabled||this.$unbind(),super.disconnectedCallback()}$propertyChangedCallback(e,t,n){if(!Object.is(n,t)&&(super.$propertyChangedCallback(e,t,n),"disabled"===e))n?this.$unbind():this.$bind()}$bind(){this.$onPointerDown||(this.$onPointerDown=this.$handlePointerDown.bind(this),ht(this,Ue,this.$onPointerDown)),this.$onPointerMove||(this.$onPointerMove=this.$handlePointerMove.bind(this),ht(this.ownerDocument,qe,this.$onPointerMove)),this.$onPointerUp||(this.$onPointerUp=this.$handlePointerUp.bind(this),ht(this.ownerDocument,Be,this.$onPointerUp)),this.$onWheel||(this.$onWheel=this.$handleWheel.bind(this),ht(this,Ke,this.$onWheel,{passive:!1,capture:!0}))}$unbind(){this.$onPointerDown&&(mt(this,Ue,this.$onPointerDown),this.$onPointerDown=null),this.$onPointerMove&&(mt(this.ownerDocument,qe,this.$onPointerMove),this.$onPointerMove=null),this.$onPointerUp&&(mt(this.ownerDocument,Be,this.$onPointerUp),this.$onPointerUp=null),this.$onWheel&&(mt(this,Ke,this.$onWheel,{capture:!0}),this.$onWheel=null)}$handlePointerDown(e){const{buttons:t,button:n,type:r}=e;if(this.disabled||("pointerdown"===r&&"mouse"===e.pointerType||"mousedown"===r)&&(et(t)&&1!==t||et(n)&&0!==n||e.ctrlKey))return;const{$pointers:a}=this;let i="";if(e.changedTouches)Array.from(e.changedTouches).forEach(({identifier:e,pageX:t,pageY:n})=>{a.set(e,{startX:t,startY:n,endX:t,endY:n})});else{const{pointerId:t=0,pageX:n,pageY:r}=e;a.set(t,{startX:n,startY:r,endX:n,endY:r})}a.size>1?i=Ae:ot(e.target)&&(i=e.target.action||e.target.getAttribute("action")||""),!1!==this.$emit(Ye,{action:i,relatedEvent:e})&&(e.preventDefault(),this.$action=i,this.style.willChange="transform")}$handlePointerMove(e){const{$action:t,$pointers:n}=this;if(this.disabled||t===Pe||0===n.size)return;if(!1===this.$emit("actionmove",{action:t,relatedEvent:e}))return;if(e.preventDefault(),e.changedTouches)Array.from(e.changedTouches).forEach(({identifier:e,pageX:t,pageY:r})=>{const a=n.get(e);a&&Object.assign(a,{endX:t,endY:r})});else{const{pointerId:t=0,pageX:r,pageY:a}=e,i=n.get(t);i&&Object.assign(i,{endX:r,endY:a})}const r={action:t,relatedEvent:e};if(t===Ae){const t=new Map(n);let a=0,i=0,o=0,l=0,s=e.pageX,c=e.pageY;n.forEach((e,n)=>{t.delete(n),t.forEach(t=>{let n=t.startX-e.startX,r=t.startY-e.startY,u=t.endX-e.endX,d=t.endY-e.endY,m=0,h=0,p=0,f=0;if(0===n?r<0?p=2*Math.PI:r>0&&(p=Math.PI):n>0?p=Math.PI/2+Math.atan(r/n):n<0&&(p=1.5*Math.PI+Math.atan(r/n)),0===u?d<0?f=2*Math.PI:d>0&&(f=Math.PI):u>0?f=Math.PI/2+Math.atan(d/u):u<0&&(f=1.5*Math.PI+Math.atan(d/u)),f>0||p>0){const n=f-p,r=Math.abs(n);r>a&&(a=r,o=n,s=(e.startX+t.startX)/2,c=(e.startY+t.startY)/2)}if(n=Math.abs(n),r=Math.abs(r),u=Math.abs(u),d=Math.abs(d),n>0&&r>0?m=Math.sqrt(n*n+r*r):n>0?m=n:r>0&&(m=r),u>0&&d>0?h=Math.sqrt(u*u+d*d):u>0?h=u:d>0&&(h=d),m>0&&h>0){const n=(h-m)/m,r=Math.abs(n);r>i&&(i=r,l=n,s=(e.startX+t.startX)/2,c=(e.startY+t.startY)/2)}})});const u=a>0,d=i>0;u&&d?(r.rotate=o,r.scale=l,r.centerX=s,r.centerY=c):u?(r.action=Te,r.rotate=o,r.centerX=s,r.centerY=c):d?(r.action=ze,r.scale=l,r.centerX=s,r.centerY=c):r.action=Pe}else{const[e]=Array.from(n.values());Object.assign(r,e)}n.forEach(e=>{e.startX=e.endX,e.startY=e.endY}),r.action!==Pe&&this.$emit(Ge,r,{cancelable:!1})}$handlePointerUp(e){const{$action:t,$pointers:n}=this;if(!this.disabled&&t!==Pe&&!1!==this.$emit(Qe,{action:t,relatedEvent:e})){if(e.preventDefault(),e.changedTouches)Array.from(e.changedTouches).forEach(({identifier:e})=>{n.delete(e)});else{const{pointerId:t=0}=e;n.delete(t)}0===n.size&&(this.style.willChange="",this.$action=Pe)}}$handleWheel(e){if(this.disabled)return;if(e.preventDefault(),this.$wheeling)return;this.$wheeling=!0,setTimeout(()=>{this.$wheeling=!1},50);const t=(e.deltaY>0?-1:1)*this.scaleStep;this.$emit(Ge,{action:ze,scale:t,relatedEvent:e},{cancelable:!1})}$setAction(e){return"string"==typeof e&&(this.$action=e),this}$toCanvas(e){return new Promise((t,n)=>{if(!this.isConnected)return void n(new Error("The current element is not connected to the DOM."));const r=document.createElement("canvas");let a=this.offsetWidth,i=this.offsetHeight,o=1;at(e)&&(tt(e.width)||tt(e.height))&&(({width:a,height:i}=xt({aspectRatio:a/i,width:e.width,height:e.height})),o=a/this.offsetWidth),r.width=a,r.height=i;const l=this.querySelector(this.$getTagNameOf(Ce));l?l.$ready().then(n=>{const s=r.getContext("2d");if(s){const[t,c,u,d,m,h]=l.$getTransform();let p=m,f=h,g=n.naturalWidth,b=n.naturalHeight;1!==o&&(p*=o,f*=o,g*=o,b*=o);const y=g/2,v=b/2;s.fillStyle="transparent",s.fillRect(0,0,a,i),at(e)&&it(e.beforeDraw)&&e.beforeDraw.call(this,s,r),s.save(),s.translate(y,v),s.transform(t,c,u,d,p,f),s.translate(-y,-v),s.drawImage(n,0,0,g,b),s.restore()}t(r)}).catch(n):t(r)})}}Tt.$name=ve,Tt.$version="2.1.0";const At=/* @__PURE__ */new WeakMap,Pt=["alt","crossorigin","decoding","elementtiming","fetchpriority","loading","referrerpolicy","sizes","src","srcset"];class Mt extends zt{constructor(){super(...arguments),this.$matrix=[1,0,0,1,0,0],this.$onLoad=null,this.$onCanvasAction=null,this.$onCanvasActionEnd=null,this.$onCanvasActionStart=null,this.$actionStartTarget=null,this.$style=":host{display:inline-block}img{display:block;height:100%;max-height:none!important;max-width:none!important;min-height:0!important;min-width:0!important;width:100%}",this.$image=new Image,this.initialCenterSize="contain",this.rotatable=!1,this.scalable=!1,this.skewable=!1,this.slottable=!1,this.translatable=!1,this.alt="",this.crossorigin="",this.decoding="",this.elementtiming="",this.fetchpriority="",this.loading="",this.referrerpolicy="",this.sizes="",this.src="",this.srcset=""}set $canvas(e){At.set(this,e)}get $canvas(){return At.get(this)}static get observedAttributes(){return super.observedAttributes.concat(Pt,["initial-center-size","rotatable","scalable","skewable","translatable"])}attributeChangedCallback(e,t,n){Object.is(n,t)||(super.attributeChangedCallback(e,t,n),Pt.includes(e)&&this.$image.setAttribute(e,n))}$propertyChangedCallback(e,t,n){if(!Object.is(n,t)&&(super.$propertyChangedCallback(e,t,n),"initialCenterSize"===e))this.$nextTick(()=>{this.$center(n)})}connectedCallback(){super.connectedCallback();const{$image:e}=this,t=this.closest(this.$getTagNameOf(ve));t&&(this.$canvas=t,this.$setStyles({display:"block",position:"absolute"}),this.$onCanvasActionStart=e=>{var t,n;this.$actionStartTarget=null===(n=null===(t=e.detail)||void 0===t?void 0:t.relatedEvent)||void 0===n?void 0:n.target},this.$onCanvasActionEnd=()=>{this.$actionStartTarget=null},this.$onCanvasAction=this.$handleAction.bind(this),ht(t,Ye,this.$onCanvasActionStart),ht(t,Qe,this.$onCanvasActionEnd),ht(t,Ge,this.$onCanvasAction)),this.$onLoad=this.$handleLoad.bind(this),ht(e,He,this.$onLoad),this.$getShadowRoot().appendChild(e)}disconnectedCallback(){const{$image:e,$canvas:t}=this;t&&(this.$onCanvasActionStart&&(mt(t,Ye,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(mt(t,Qe,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasAction&&(mt(t,Ge,this.$onCanvasAction),this.$onCanvasAction=null)),e&&this.$onLoad&&(mt(e,He,this.$onLoad),this.$onLoad=null),this.$getShadowRoot().removeChild(e),super.disconnectedCallback()}$handleLoad(){const{$image:e}=this;this.$setStyles({width:e.naturalWidth,height:e.naturalHeight}),this.$canvas&&this.$center(this.initialCenterSize)}$handleAction(e){if(this.hidden||!(this.rotatable||this.scalable||this.translatable))return;const{$canvas:t}=this,{detail:n}=e;if(n){const{relatedEvent:e}=n;let{action:r}=n;switch(r!==Ae||this.rotatable&&this.scalable||(r=this.rotatable?Te:this.scalable?ze:Pe),r){case _e:if(this.translatable){let r=null;e&&(r=e.target.closest(this.$getTagNameOf(Se))),r||(r=t.querySelector(this.$getTagNameOf(Se))),r&&r.multiple&&!r.active&&(r=t.querySelector(`${this.$getTagNameOf(Se)}[active]`)),r&&!r.hidden&&r.movable&&!r.dynamic&&this.$actionStartTarget&&r.contains(this.$actionStartTarget)||this.$move(n.endX-n.startX,n.endY-n.startY)}break;case Te:if(this.rotatable)if(e){const{x:t,y:r}=this.getBoundingClientRect();this.$rotate(n.rotate,e.clientX-t,e.clientY-r)}else this.$rotate(n.rotate);break;case ze:if(this.scalable)if(e){const t=e.target.closest(this.$getTagNameOf(Se));if(!t||!t.zoomable||t.zoomable&&t.dynamic){const{x:t,y:r}=this.getBoundingClientRect();this.$zoom(n.scale,e.clientX-t,e.clientY-r)}}else this.$zoom(n.scale);break;case Ae:if(this.rotatable&&this.scalable){const{rotate:t}=n;let{scale:r}=n;r<0?r=1/(1-r):r+=1;const a=Math.cos(t),i=Math.sin(t),[o,l,s,c]=[a*r,i*r,-i*r,a*r];if(e){const t=this.getBoundingClientRect(),n=e.clientX-t.x,r=e.clientY-t.y,[a,i,u,d]=this.$matrix,m=n-t.width/2,h=r-t.height/2,p=(m*d-u*h)/(a*d-u*i),f=(h*a-i*m)/(a*d-u*i);this.$transform(o,l,s,c,p*(1-o)+f*s,f*(1-c)+p*l)}else this.$transform(o,l,s,c,0,0)}}}}$ready(e){const{$image:t}=this,n=new Promise((e,n)=>{const r=new Error("Failed to load the image source");if(t.complete)t.naturalWidth>0&&t.naturalHeight>0?e(t):n(r);else{const a=()=>{mt(t,We,i),setTimeout(()=>{e(t)})},i=()=>{mt(t,He,a),n(r)};pt(t,He,a),pt(t,We,i)}});return it(e)&&n.then(t=>(e(t),t)),n}$center(e){const{parentElement:t}=this;if(!t)return this;const n=t.getBoundingClientRect(),r=n.width,a=n.height,{x:i,y:o,width:l,height:s}=this.getBoundingClientRect(),c=i+l/2,u=o+s/2,d=n.x+r/2,m=n.y+a/2;if(this.$move(d-c,m-u),e&&(l!==r||s!==a)){const t=r/l,n=a/s;switch(e){case"cover":this.$scale(Math.max(t,n));break;case"contain":this.$scale(Math.min(t,n))}}return this}$move(e,t=e){if(this.translatable&&et(e)&&et(t)){const[n,r,a,i]=this.$matrix,o=(e*i-a*t)/(n*i-a*r),l=(t*n-r*e)/(n*i-a*r);this.$translate(o,l)}return this}$moveTo(e,t=e){if(this.translatable&&et(e)&&et(t)){const[n,r,a,i]=this.$matrix,o=(e*i-a*t)/(n*i-a*r),l=(t*n-r*e)/(n*i-a*r);this.$setTransform(n,r,a,i,o,l)}return this}$rotate(e,t,n){if(this.rotatable){const r=vt(e),a=Math.cos(r),i=Math.sin(r),[o,l,s,c]=[a,i,-i,a];if(et(t)&&et(n)){const[e,r,a,i]=this.$matrix,{width:u,height:d}=this.getBoundingClientRect(),m=t-u/2,h=n-d/2,p=(m*i-a*h)/(e*i-a*r),f=(h*e-r*m)/(e*i-a*r);this.$transform(o,l,s,c,p*(1-o)-f*s,f*(1-c)-p*l)}else this.$transform(o,l,s,c,0,0)}return this}$zoom(e,t,n){if(!this.scalable||0===e)return this;if(e<0?e=1/(1-e):e+=1,et(t)&&et(n)){const[r,a,i,o]=this.$matrix,{width:l,height:s}=this.getBoundingClientRect(),c=t-l/2,u=n-s/2,d=(c*o-i*u)/(r*o-i*a),m=(u*r-a*c)/(r*o-i*a);this.$transform(e,0,0,e,d*(1-e),m*(1-e))}else this.$scale(e);return this}$scale(e,t=e){return this.scalable&&this.$transform(e,0,0,t,0,0),this}$skew(e,t=0){if(this.skewable){const n=vt(e),r=vt(t);this.$transform(1,Math.tan(r),Math.tan(n),1,0,0)}return this}$translate(e,t=e){return this.translatable&&et(e)&&et(t)&&this.$transform(1,0,0,1,e,t),this}$transform(e,t,n,r,a,i){return et(e)&&et(t)&&et(n)&&et(r)&&et(a)&&et(i)?this.$setTransform(kt(this.$matrix,[e,t,n,r,a,i])):this}$setTransform(e,t,n,r,a,i){if((this.rotatable||this.scalable||this.skewable||this.translatable)&&(Array.isArray(e)&&([e,t,n,r,a,i]=e),et(e)&&et(t)&&et(n)&&et(r)&&et(a)&&et(i))){const o=[...this.$matrix],l=[e,t,n,r,a,i];if(!1===this.$emit(Je,{matrix:l,oldMatrix:o}))return this;this.$matrix=l,this.style.transform=`matrix(${l.join(", ")})`}return this}$getTransform(){return this.$matrix.slice()}$resetTransform(){return this.$setTransform([1,0,0,1,0,0])}}Mt.$name=Ce,Mt.$version="2.1.0";const It=/* @__PURE__ */new WeakMap;class Lt extends zt{constructor(){super(...arguments),this.$onCanvasActionEnd=null,this.$onCanvasActionStart=null,this.$onSelectionChange=null,this.$style=":host{display:block;height:0;left:0;outline:var(--theme-color) solid 1px;position:relative;top:0;width:0}:host([transparent]){outline-color:transparent}",this.x=0,this.y=0,this.width=0,this.height=0,this.slottable=!1,this.themeColor="rgba(0, 0, 0, 0.65)"}set $canvas(e){It.set(this,e)}get $canvas(){return It.get(this)}static get observedAttributes(){return super.observedAttributes.concat(["height","width","x","y"])}connectedCallback(){super.connectedCallback();const e=this.closest(this.$getTagNameOf(ve));if(e){this.$canvas=e,this.style.position="absolute";const t=e.querySelector(this.$getTagNameOf(Se));t&&(this.$onCanvasActionStart=e=>{t.hidden&&e.detail.action===$e&&(this.hidden=!1)},this.$onCanvasActionEnd=e=>{t.hidden&&e.detail.action===$e&&(this.hidden=!0)},this.$onSelectionChange=e=>{const{x:n,y:r,width:a,height:i}=e.defaultPrevented?t:e.detail;this.$change(n,r,a,i),(t.hidden||0===n&&0===r&&0===a&&0===i)&&(this.hidden=!0)},ht(e,Ye,this.$onCanvasActionStart),ht(e,Qe,this.$onCanvasActionEnd),ht(e,Xe,this.$onSelectionChange))}this.$render()}disconnectedCallback(){const{$canvas:e}=this;e&&(this.$onCanvasActionStart&&(mt(e,Ye,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(mt(e,Qe,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onSelectionChange&&(mt(e,Xe,this.$onSelectionChange),this.$onSelectionChange=null)),super.disconnectedCallback()}$change(e,t,n=this.width,r=this.height){return et(e)&&et(t)&&et(n)&&et(r)&&(e!==this.x||t!==this.y||n!==this.width||r!==this.height)?(this.hidden&&(this.hidden=!1),this.x=e,this.y=t,this.width=n,this.height=r,this.$render()):this}$reset(){return this.$change(0,0,0,0)}$render(){return this.$setStyles({transform:`translate(${this.x}px, ${this.y}px)`,width:this.width,height:this.height,outlineWidth:fe.innerWidth})}}Lt.$name=Ne,Lt.$version="2.1.0";class Dt extends zt{constructor(){super(...arguments),this.$onCanvasCropEnd=null,this.$onCanvasCropStart=null,this.$style=':host{background-color:var(--theme-color);display:block}:host([action=move]),:host([action=select]){height:100%;left:0;position:absolute;top:0;width:100%}:host([action=move]){cursor:move}:host([action=select]){cursor:crosshair}:host([action$=-resize]){background-color:transparent;height:15px;position:absolute;width:15px}:host([action$=-resize]):after{background-color:var(--theme-color);content:"";display:block;height:5px;left:50%;position:absolute;top:50%;transform:translate(-50%,-50%);width:5px}:host([action=n-resize]),:host([action=s-resize]){cursor:ns-resize;left:50%;transform:translateX(-50%);width:100%}:host([action=n-resize]){top:-8px}:host([action=s-resize]){bottom:-8px}:host([action=e-resize]),:host([action=w-resize]){cursor:ew-resize;height:100%;top:50%;transform:translateY(-50%)}:host([action=e-resize]){right:-8px}:host([action=w-resize]){left:-8px}:host([action=ne-resize]){cursor:nesw-resize;right:-8px;top:-8px}:host([action=nw-resize]){cursor:nwse-resize;left:-8px;top:-8px}:host([action=se-resize]){bottom:-8px;cursor:nwse-resize;right:-8px}:host([action=se-resize]):after{height:15px;width:15px}@media (pointer:coarse){:host([action=se-resize]):after{height:10px;width:10px}}@media (pointer:fine){:host([action=se-resize]):after{height:5px;width:5px}}:host([action=sw-resize]){bottom:-8px;cursor:nesw-resize;left:-8px}:host([plain]){background-color:transparent}',this.action=Pe,this.plain=!1,this.slottable=!1,this.themeColor="rgba(51, 153, 255, 0.5)"}static get observedAttributes(){return super.observedAttributes.concat(["action","plain"])}}Dt.$name=ke,Dt.$version="2.1.0";const Ot=/* @__PURE__ */new WeakMap;class Rt extends zt{constructor(){super(...arguments),this.$onCanvasAction=null,this.$onCanvasActionStart=null,this.$onCanvasActionEnd=null,this.$onDocumentKeyDown=null,this.$action="",this.$actionStartTarget=null,this.$changing=!1,this.$style=':host{display:block;left:0;position:relative;right:0}:host([outlined]){outline:1px solid var(--theme-color)}:host([multiple]){outline:1px dashed hsla(0,0%,100%,.5)}:host([multiple]):after{bottom:0;content:"";cursor:pointer;display:block;left:0;position:absolute;right:0;top:0}:host([multiple][active]){outline-color:var(--theme-color);z-index:1}:host([multiple])>*{visibility:hidden}:host([multiple][active])>*{visibility:visible}:host([multiple][active]):after{display:none}',this.$initialSelection={x:0,y:0,width:0,height:0},this.x=0,this.y=0,this.width=0,this.height=0,this.aspectRatio=NaN,this.initialAspectRatio=NaN,this.initialCoverage=NaN,this.active=!1,this.linked=!1,this.dynamic=!1,this.movable=!1,this.resizable=!1,this.zoomable=!1,this.multiple=!1,this.keyboard=!1,this.outlined=!1,this.precise=!1}set $canvas(e){Ot.set(this,e)}get $canvas(){return Ot.get(this)}static get observedAttributes(){return super.observedAttributes.concat(["active","aspect-ratio","dynamic","height","initial-aspect-ratio","initial-coverage","keyboard","linked","movable","multiple","outlined","precise","resizable","width","x","y","zoomable"])}$propertyChangedCallback(e,t,n){if(!Object.is(n,t))switch(super.$propertyChangedCallback(e,t,n),e){case"x":case"y":case"width":case"height":this.$changing||this.$nextTick(()=>{this.$change(this.x,this.y,this.width,this.height,this.aspectRatio,!0)});break;case"aspectRatio":case"initialAspectRatio":this.$nextTick(()=>{this.$initSelection()});break;case"initialCoverage":this.$nextTick(()=>{tt(n)&&n<=1&&this.$initSelection(!0,!0)});break;case"keyboard":this.$nextTick(()=>{this.$canvas&&(n?this.$onDocumentKeyDown||(this.$onDocumentKeyDown=this.$handleKeyDown.bind(this),ht(this.ownerDocument,Ve,this.$onDocumentKeyDown)):this.$onDocumentKeyDown&&(mt(this.ownerDocument,Ve,this.$onDocumentKeyDown),this.$onDocumentKeyDown=null))});break;case"multiple":this.$nextTick(()=>{if(this.$canvas){const e=this.$getSelections();n?(e.forEach(e=>{e.active=!1}),this.active=!0,this.$emit(Xe,{x:this.x,y:this.y,width:this.width,height:this.height})):(this.active=!1,e.slice(1).forEach(e=>{this.$removeSelection(e)}))}});break;case"precise":this.$nextTick(()=>{this.$change(this.x,this.y)});break;case"linked":n&&(this.dynamic=!0)}}connectedCallback(){super.connectedCallback();const e=this.closest(this.$getTagNameOf(ve));e?(this.$canvas=e,this.$setStyles({position:"absolute",transform:`translate(${this.x}px, ${this.y}px)`}),this.hidden||this.$render(),this.$initSelection(!0),this.$onCanvasActionStart=this.$handleActionStart.bind(this),this.$onCanvasActionEnd=this.$handleActionEnd.bind(this),this.$onCanvasAction=this.$handleAction.bind(this),ht(e,Ye,this.$onCanvasActionStart),ht(e,Qe,this.$onCanvasActionEnd),ht(e,Ge,this.$onCanvasAction)):this.$render()}disconnectedCallback(){const{$canvas:e}=this;e&&(this.$onCanvasActionStart&&(mt(e,Ye,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(mt(e,Qe,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasAction&&(mt(e,Ge,this.$onCanvasAction),this.$onCanvasAction=null)),super.disconnectedCallback()}$getSelections(){let e=[];return this.parentElement&&(e=Array.from(this.parentElement.querySelectorAll(this.$getTagNameOf(Se)))),e}$initSelection(e=!1,t=!1){const{initialCoverage:n,parentElement:r}=this;if(tt(n)&&r){const a=this.aspectRatio||this.initialAspectRatio;let i=(t?0:this.width)||r.offsetWidth*n,o=(t?0:this.height)||r.offsetHeight*n;tt(a)&&({width:i,height:o}=xt({aspectRatio:a,width:i,height:o})),this.$change(this.x,this.y,i,o),e&&this.$center(),this.$initialSelection={x:this.x,y:this.y,width:this.width,height:this.height}}}$createSelection(){const e=this.cloneNode(!0);return this.hasAttribute("id")&&e.removeAttribute("id"),e.initialCoverage=NaN,this.active=!1,this.parentElement&&this.parentElement.insertBefore(e,this.nextSibling),e}$removeSelection(e=this){if(this.parentElement){const t=this.$getSelections();if(t.length>1){const n=t.indexOf(e),r=t[n+1]||t[n-1];r&&(e.active=!1,this.parentElement.removeChild(e),r.active=!0,r.$emit(Xe,{x:r.x,y:r.y,width:r.width,height:r.height}))}else this.$clear()}}$handleActionStart(e){var t,n;const r=null===(n=null===(t=e.detail)||void 0===t?void 0:t.relatedEvent)||void 0===n?void 0:n.target;this.$action="",this.$actionStartTarget=r,!this.hidden&&this.multiple&&!this.active&&r===this&&this.parentElement&&(this.$getSelections().forEach(e=>{e.active=!1}),this.active=!0,this.$emit(Xe,{x:this.x,y:this.y,width:this.width,height:this.height}))}$handleAction(e){const{currentTarget:t,detail:n}=e;if(!t||!n)return;const{relatedEvent:r}=n;let{action:a}=n;const i=r?function(e){if("function"==typeof e.composedPath)return e.composedPath().find(ot)||e.target;return e.target}(r):null;if(!a&&this.multiple&&(a=this.$action||(null==i?void 0:i.action),this.$action=a),!a||this.hidden&&a!==$e||this.multiple&&!this.active&&a!==ze)return;const{width:o,height:l}=this;let s=n.endX-n.startX,c=n.endY-n.startY,{aspectRatio:u}=this;switch(!tt(u)&&r.shiftKey&&(u=tt(o)&&tt(l)?o/l:1),a){case $e:if(0!==s||0!==c){0===s?s=c:0===c&&(c=s);const{$canvas:e}=this,r=bt(t);(this.multiple&&!this.hidden?this.$createSelection():this).$change(n.startX-r.left,n.startY-r.top,Math.abs(s),Math.abs(c),u),s<0?c<0?a=Re:c>0&&(a=Fe):s>0&&(c<0?a=Oe:c>0&&(a=je)),e&&(e.$action=a)}break;case _e:this.movable&&(this.dynamic||this.$actionStartTarget&&this.contains(this.$actionStartTarget))&&this.$move(s,c);break;case ze:if(r&&this.zoomable&&(this.dynamic||this.contains(r.target))){const e=bt(t);this.$zoom(n.scale,r.pageX-e.left,r.pageY-e.top)}break;default:this.$resize(a,s,c,u)}}$handleActionEnd(){this.$action="",this.$actionStartTarget=null}$handleKeyDown(e){if(this.hidden||!this.keyboard||this.multiple&&!this.active||e.defaultPrevented)return;const{activeElement:t}=document;if(!t||!["INPUT","TEXTAREA"].includes(t.tagName)&&!["true","plaintext-only"].includes(t.contentEditable))switch(e.key){case"Backspace":e.metaKey&&(e.preventDefault(),this.$removeSelection());break;case"Delete":e.preventDefault(),this.$removeSelection();break;case"ArrowLeft":e.preventDefault(),this.$move(-1,0);break;case"ArrowRight":e.preventDefault(),this.$move(1,0);break;case"ArrowUp":e.preventDefault(),this.$move(0,-1);break;case"ArrowDown":e.preventDefault(),this.$move(0,1);break;case"+":e.preventDefault(),this.$zoom(.1);break;case"-":e.preventDefault(),this.$zoom(-.1)}}$center(){const{parentElement:e}=this;if(!e)return this;const t=(e.offsetWidth-this.width)/2,n=(e.offsetHeight-this.height)/2;return this.$change(t,n)}$move(e,t=e){return this.$moveTo(this.x+e,this.y+t)}$moveTo(e,t=e){return this.movable?this.$change(e,t):this}$resize(e,t=0,n=0,r=this.aspectRatio){if(!this.resizable)return this;const a=tt(r),{$canvas:i}=this;let{x:o,y:l,width:s,height:c}=this;switch(e){case Me:l+=n,c-=n,c<0&&(e=Le,c=-c,l-=c),a&&(o+=(t=n*r)/2,s-=t,s<0&&(s=-s,o-=s));break;case Ie:s+=t,s<0&&(e=De,s=-s,o-=s),a&&(l-=(n=t/r)/2,c+=n,c<0&&(c=-c,l-=c));break;case Le:c+=n,c<0&&(e=Me,c=-c,l-=c),a&&(o-=(t=n*r)/2,s+=t,s<0&&(s=-s,o-=s));break;case De:o+=t,s-=t,s<0&&(e=Ie,s=-s,o-=s),a&&(l+=(n=t/r)/2,c-=n,c<0&&(c=-c,l-=c));break;case Oe:a&&(n=-t/r),l+=n,c-=n,s+=t,s<0&&c<0?(e=Fe,s=-s,c=-c,o-=s,l-=c):s<0?(e=Re,s=-s,o-=s):c<0&&(e=je,c=-c,l-=c);break;case Re:a&&(n=t/r),o+=t,l+=n,s-=t,c-=n,s<0&&c<0?(e=je,s=-s,c=-c,o-=s,l-=c):s<0?(e=Oe,s=-s,o-=s):c<0&&(e=Fe,c=-c,l-=c);break;case je:a&&(n=t/r),s+=t,c+=n,s<0&&c<0?(e=Re,s=-s,c=-c,o-=s,l-=c):s<0?(e=Fe,s=-s,o-=s):c<0&&(e=Oe,c=-c,l-=c);break;case Fe:a&&(n=-t/r),o+=t,s-=t,c+=n,s<0&&c<0?(e=Oe,s=-s,c=-c,o-=s,l-=c):s<0?(e=je,s=-s,o-=s):c<0&&(e=Re,c=-c,l-=c)}return i&&i.$setAction(e),this.$change(o,l,s,c)}$zoom(e,t,n){if(!this.zoomable||0===e)return this;e<0?e=1/(1-e):e+=1;const{width:r,height:a}=this,i=r*e,o=a*e;let l=this.x,s=this.y;return et(t)&&et(n)?(l-=(i-r)*((t-this.x)/r),s-=(o-a)*((n-this.y)/a)):(l-=(i-r)/2,s-=(o-a)/2),this.$change(l,s,i,o)}$change(e,t,n=this.width,r=this.height,a=this.aspectRatio,i=!1){return this.$changing||!et(e)||!et(t)||!et(n)||!et(r)||n<0||r<0?this:(tt(a)&&({width:n,height:r}=xt({aspectRatio:a,width:n,height:r},"cover")),this.precise||(e=Math.round(e),t=Math.round(t),n=Math.round(n),r=Math.round(r)),e===this.x&&t===this.y&&n===this.width&&r===this.height&&Object.is(a,this.aspectRatio)&&!i?this:(this.hidden&&(this.hidden=!1),!1===this.$emit(Xe,{x:e,y:t,width:n,height:r})?this:(this.$changing=!0,this.x=e,this.y=t,this.width=n,this.height=r,this.$changing=!1,this.$render())))}$reset(){const{x:e,y:t,width:n,height:r}=this.$initialSelection;return this.$change(e,t,n,r)}$clear(){return this.$change(0,0,0,0,NaN,!0),this.hidden=!0,this}$render(){return this.$setStyles({transform:`translate(${this.x}px, ${this.y}px)`,width:this.width,height:this.height})}$toCanvas(e){return new Promise((t,n)=>{if(!this.isConnected)return void n(new Error("The current element is not connected to the DOM."));const r=document.createElement("canvas");let{width:a,height:i}=this,o=1;if(at(e)&&(tt(e.width)||tt(e.height))&&(({width:a,height:i}=xt({aspectRatio:a/i,width:e.width,height:e.height})),o=a/this.width),r.width=a,r.height=i,!this.$canvas)return void t(r);const l=this.$canvas.querySelector(this.$getTagNameOf(Ce));l?l.$ready().then(n=>{const s=r.getContext("2d");if(s){const[t,c,u,d,m,h]=l.$getTransform(),p=-this.x,f=-this.y,g=(p*d-u*f)/(t*d-u*c),b=(f*t-c*p)/(t*d-u*c);let y=t*g+u*b+m,v=c*g+d*b+h,w=n.naturalWidth,x=n.naturalHeight;1!==o&&(y*=o,v*=o,w*=o,x*=o);const k=w/2,C=x/2;s.fillStyle="transparent",s.fillRect(0,0,a,i),at(e)&&it(e.beforeDraw)&&e.beforeDraw.call(this,s,r),s.save(),s.translate(k,C),s.transform(t,c,u,d,y,v),s.translate(-k,-C),s.drawImage(n,0,0,w,x),s.restore()}t(r)}).catch(n):t(r)})}}Rt.$name=Se,Rt.$version="2.1.0";class jt extends zt{constructor(){super(...arguments),this.$style=":host{display:flex;flex-direction:column;position:relative;touch-action:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}:host([bordered]){border:1px dashed var(--theme-color)}:host([covered]){bottom:0;left:0;position:absolute;right:0;top:0}:host>span{display:flex;flex:1}:host>span+span{border-top:1px dashed var(--theme-color)}:host>span>span{flex:1}:host>span>span+span{border-left:1px dashed var(--theme-color)}",this.bordered=!1,this.columns=3,this.covered=!1,this.rows=3,this.slottable=!1,this.themeColor="rgba(238, 238, 238, 0.5)"}static get observedAttributes(){return super.observedAttributes.concat(["bordered","columns","covered","rows"])}$propertyChangedCallback(e,t,n){Object.is(n,t)||(super.$propertyChangedCallback(e,t,n),"rows"!==e&&"columns"!==e||this.$nextTick(()=>{this.$render()}))}connectedCallback(){super.connectedCallback(),this.$render()}$render(){const e=this.$getShadowRoot(),t=document.createDocumentFragment();for(let n=0;n<this.rows;n+=1){const e=document.createElement("span");e.setAttribute("role","row");for(let t=0;t<this.columns;t+=1){const t=document.createElement("span");t.setAttribute("role","gridcell"),e.appendChild(t)}t.appendChild(e)}e&&(e.innerHTML="",e.appendChild(t))}}jt.$name=xe,jt.$version="2.1.0";class Ft extends zt{constructor(){super(...arguments),this.$style=':host{display:inline-block;height:1em;position:relative;touch-action:none;-webkit-user-select:none;-moz-user-select:none;user-select:none;vertical-align:middle;width:1em}:host:after,:host:before{background-color:var(--theme-color);content:"";display:block;position:absolute}:host:before{height:1px;left:0;top:50%;transform:translateY(-50%);width:100%}:host:after{height:100%;left:50%;top:0;transform:translateX(-50%);width:1px}:host([centered]){left:50%;position:absolute;top:50%;transform:translate(-50%,-50%)}',this.centered=!1,this.slottable=!1,this.themeColor="rgba(238, 238, 238, 0.5)"}static get observedAttributes(){return super.observedAttributes.concat(["centered"])}}Ft.$name=we,Ft.$version="2.1.0";const Ut=/* @__PURE__ */new WeakMap,qt=/* @__PURE__ */new WeakMap,Bt=/* @__PURE__ */new WeakMap,Wt=/* @__PURE__ */new WeakMap,Vt="vertical";class Ht extends zt{constructor(){super(...arguments),this.$onSelectionChange=null,this.$onSourceImageLoad=null,this.$onSourceImageTransform=null,this.$scale=1,this.$style=":host{display:block;height:100%;overflow:hidden;position:relative;width:100%}",this.resize=Vt,this.selection="",this.slottable=!1}set $image(e){qt.set(this,e)}get $image(){return qt.get(this)}set $sourceImage(e){Wt.set(this,e)}get $sourceImage(){return Wt.get(this)}set $canvas(e){Ut.set(this,e)}get $canvas(){return Ut.get(this)}set $selection(e){Bt.set(this,e)}get $selection(){return Bt.get(this)}static get observedAttributes(){return super.observedAttributes.concat(["resize","selection"])}connectedCallback(){var e,t;super.connectedCallback();let n=null;if(n=this.selection?null!==(t=null===(e=function(e){const t=e.getRootNode();switch(t.nodeType){case 1:return t.ownerDocument;case 9:case 11:return t}return null}(this))||void 0===e?void 0:e.querySelector(this.selection))&&void 0!==t?t:null:this.closest(this.$getTagNameOf(Se)),ot(n)){this.$selection=n,this.$onSelectionChange=this.$handleSelectionChange.bind(this),ht(n,Xe,this.$onSelectionChange);const e=n.closest(this.$getTagNameOf(ve));if(e){this.$canvas=e;const t=e.querySelector(this.$getTagNameOf(Ce));t&&(this.$sourceImage=t,this.$image=t.cloneNode(!0),this.$getShadowRoot().appendChild(this.$image),this.$onSourceImageLoad=this.$handleSourceImageLoad.bind(this),this.$onSourceImageTransform=this.$handleSourceImageTransform.bind(this),ht(t.$image,He,this.$onSourceImageLoad),ht(t,Je,this.$onSourceImageTransform))}this.$render()}}disconnectedCallback(){const{$selection:e,$sourceImage:t}=this;e&&this.$onSelectionChange&&(mt(e,Xe,this.$onSelectionChange),this.$onSelectionChange=null),t&&this.$onSourceImageLoad&&(mt(t.$image,He,this.$onSourceImageLoad),this.$onSourceImageLoad=null),t&&this.$onSourceImageTransform&&(mt(t,Je,this.$onSourceImageTransform),this.$onSourceImageTransform=null),super.disconnectedCallback()}$handleSelectionChange(e){this.$render(e.defaultPrevented?this.$selection:e.detail)}$handleSourceImageLoad(){const{$image:e,$sourceImage:t}=this,n=e.getAttribute("src"),r=t.getAttribute("src");r&&r!==n&&(e.setAttribute("src",r),e.$ready(()=>{this.$render()}))}$handleSourceImageTransform(e){this.$render(void 0,e.detail.matrix)}$render(e,t){const{$canvas:n,$selection:r}=this;e||r.hidden||(e=r),(!e||0===e.x&&0===e.y&&0===e.width&&0===e.height)&&(e={x:0,y:0,width:n.offsetWidth,height:n.offsetHeight});const{x:a,y:i,width:o,height:l}=e,s={},{clientWidth:c,clientHeight:u}=this;let d=c,m=u,h=NaN;switch(this.resize){case"both":h=1,d=o,m=l,s.width=o,s.height=l;break;case"horizontal":h=l>0?u/l:0,d=o*h,s.width=d;break;case Vt:h=o>0?c/o:0,m=l*h,s.height=m;break;default:c>0?h=o>0?c/o:0:u>0&&(h=l>0?u/l:0)}this.$scale=h,this.$setStyles(s),this.$sourceImage&&setTimeout(()=>{this.$transformImageByOffset(null!=t?t:this.$sourceImage.$getTransform(),-a,-i)})}$transformImageByOffset(e,t,n){const{$image:r,$scale:a,$sourceImage:i}=this;if(i&&r&&a>=0){const[i,o,l,s,c,u]=e,d=(t*s-l*n)/(i*s-l*o),m=(n*i-o*t)/(i*s-l*o),h=i*d+l*m+c,p=o*d+s*m+u;r.$ready(e=>{this.$setStyles.call(r,{width:e.naturalWidth*a,height:e.naturalHeight*a})}),r.$setTransform(i,o,l,s,h*a,p*a)}}}function Kt(){const[e,n]=t(!1),[r,a]=t(null),[i,o]=t(null),l=async(e,t)=>{if(!e||!t)return a("ID de asset y configuración de variante son requeridos"),null;n(!0),a(null),o(null);try{const n=await async function(e,{variant_name:t,width:n,height:a,crop_params:i,preset_aspect:o=null,preset_size:l=null,output_format:s="webp"}){try{const r=[{name:t,width:n,height:a,output_format:s,crop_params:i}];return o&&(r[0].preset_aspect=o),l&&(r[0].preset_size=l),D(await A({endpoint:`/assets/${e}/variants`,method:"POST",body:{variants:r,async:!1},basePath:R,useJWT:!0}))}catch(r){throw O(r)}}(e,{variant_name:t.name,width:t.width,height:t.height,crop_params:t.crop_params,preset_aspect:t.preset_aspect,preset_size:t.preset_size,output_format:t.output_format});if(n?.result)return o(n.result),n.result;throw new Error("No se pudo crear la variante")}catch(i){return console.error("Error creating variant:",i),a(i.message||"Error desconocido al crear variante"),null}finally{n(!1)}};return{createVariant:l,createCropVariant:async(e,t,n={})=>{const r={name:n.name||`crop_${Date.now()}`,width:n.width||800,height:n.height||600,output_format:n.format||"webp",crop_params:{x:t.x||0,y:t.y||0,width:t.width||1,height:t.height||1}};return await l(e,r)},createVariantFromBlob:async(e,t,i={})=>{if(!e||!t)return a("ID de asset y blob son requeridos"),null;n(!0),a(null),o(null);try{const n=await async function(e,t,n={}){try{const r=new FormData,a=n.format||"webp",i=`${n.name||"variant"}.${a}`;return r.append("file",t,i),r.append("variant_name",n.name||"variant"),r.append("width",String(n.width||0)),r.append("height",String(n.height||0)),r.append("output_format",n.format||"webp"),D(await A({endpoint:`/assets/${e}/variants/upload`,method:"POST",body:r,basePath:R,isFormData:!0,useJWT:!0}))}catch(r){throw O(r)}}(e,t,{name:i.name||`crop_${Date.now()}`,width:i.width||0,height:i.height||0,format:i.format||"webp"});if(n?.result)return o(n.result),n.result;throw new Error("No se pudo crear la variante")}catch(l){return console.error("Error creating variant from blob:",l),a(l.message||"Error desconocido al crear variante"),null}finally{n(!1)}},loading:e,error:r,createdVariant:i,reset:()=>{a(null),o(null)}}}Ht.$name=Ee,Ht.$version="2.1.0",Tt.$define(),Ft.$define(),jt.$define(),Dt.$define(),Mt.$define(),Rt.$define(),Lt.$define(),Ht.$define();class Gt{constructor(e,t,n){this.canvasRef=e,this.imageRef=t,this.selectionRef=n}get canvasElement(){return this.canvasRef?.current}get image(){return this.imageRef?.current}get selectionElement(){return this.selectionRef?.current}get isReady(){return!!(this.canvasElement&&this.image&&this.selectionElement)}transform={move:(e,t)=>{if(!this.image)return!1;try{return this.image.$move(e,t),!0}catch(n){return console.warn("Error moving image:",n),!1}},moveTo:(e,t)=>{if(!this.image)return!1;try{return this.image.$moveTo(e,t),!0}catch(n){return console.warn("Error moving image to position:",n),!1}},zoom:e=>{if(!this.image)return!1;try{return this.image.$zoom(e),!0}catch(t){return console.warn("Error zooming image:",t),!1}},rotate:e=>{if(!this.image)return!1;try{const t=e*Math.PI/180;return this.image.$rotate(t),!0}catch(t){return console.warn("Error rotating image:",t),!1}},scale:(e,t=e)=>{if(!this.image)return!1;try{return this.image.$scale(e,t),!0}catch(n){return console.warn("Error scaling image:",n),!1}},center:(e="contain")=>{if(!this.image)return!1;try{return this.image.$center(e),!0}catch(t){return console.warn("Error centering image:",t),!1}},reset:()=>{if(!this.image)return!1;try{return this.image.$resetTransform(),!0}catch(e){return console.warn("Error resetting transform:",e),!1}},getTransform:()=>{if(!this.image)return null;try{return this.image.$getTransform()}catch(e){return console.warn("Error getting transform:",e),null}},setTransform:(e,t,n,r,a,i)=>{if(!this.image)return!1;try{return this.image.$setTransform(e,t,n,r,a,i),!0}catch(o){return console.warn("Error setting transform:",o),!1}},resetZoom:()=>{if(!this.image)return!1;try{const e=this.image.$getTransform();if(!e)return!1;const[t,n,r,a,i,o]=e,l=Math.sqrt(t*t+n*n),s=Math.sqrt(r*r+a*a),c=t/l,u=n/l,d=r/s,m=a/s;return this.image.$setTransform(c,u,d,m,i,o),!0}catch(e){return console.warn("Error resetting zoom:",e),!1}},setZoom:e=>{if(!this.image||e<=0)return!1;try{const t=this.image.$getTransform();if(!t)return!1;const[n,r,a,i,o,l]=t,s=Math.sqrt(n*n+r*r),c=Math.sqrt(a*a+i*i),u=n/s*e,d=r/s*e,m=a/c*e,h=i/c*e;return this.image.$setTransform(u,d,m,h,o,l),!0}catch(t){return console.warn("Error setting zoom level:",t),!1}},getZoom:()=>{if(!this.image)return 1;try{const e=this.image.$getTransform();if(!e)return 1;const[t,n]=e;return Math.sqrt(t*t+n*n)}catch(e){return console.warn("Error getting zoom level:",e),1}},fitToCanvas:(e=.1)=>{if(!this.image||!this.canvasElement)return!1;try{const t=this.canvasElement.getBoundingClientRect();let n=this.image.querySelector("img")||this.image;if(!n?.naturalWidth||!n?.naturalHeight)return!1;const r=1-e,a=t.width*r/n.naturalWidth,i=t.height*r/n.naturalHeight,o=Math.min(a,i,1);return this.transform.setZoom(o)}catch(t){return console.warn("Error fitting to canvas:",t),!1}}};selection={center:()=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$center(),!0}catch(e){return console.warn("Error centering selection:",e),!1}},reset:()=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$reset(),!0}catch(e){return console.warn("Error resetting selection:",e),!1}},setCoverage:e=>{if(!this.selectionElement||e<0||e>1)return!1;try{return this.selectionElement.initialCoverage=e,this.selectionElement.$reset(),!0}catch(t){return console.warn("Error setting coverage:",t),!1}},setAspectRatio:e=>{if(!this.selectionElement)return!1;try{let t;if(""===e||null==e)t=NaN;else if("number"==typeof e)t=e;else{if("string"!=typeof e)return console.warn("Unsupported aspect ratio type:",typeof e,e),!1;if(e.includes("/")){const[n,r]=e.split("/").map(e=>parseFloat(e.trim()));if(isNaN(n)||isNaN(r)||0===r)return console.warn("Invalid aspect ratio format:",e),!1;t=n/r}else if(t=parseFloat(e),isNaN(t))return console.warn("Invalid aspect ratio format:",e),!1}return this.selectionElement.aspectRatio=t,this.selectionElement.$render(),!0}catch(t){return console.warn("Error setting aspect ratio:",t),!1}},move:(e,t)=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$move(e,t),!0}catch(n){return console.warn("Error moving selection:",n),!1}},zoom:e=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$zoom(e),!0}catch(t){return console.warn("Error zooming selection:",t),!1}},change:(e,t,n,r,a)=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$change(e,t,n,r,a),!0}catch(i){return console.warn("Error changing selection:",i),!1}},set:(e,t,n,r)=>{if(!this.selectionElement)return!1;try{return this.selectionElement.x=e,this.selectionElement.y=t,this.selectionElement.width=n,this.selectionElement.height=r,this.selectionElement.$render(),!0}catch(a){return console.warn("Error setting selection:",a),!1}},toCanvas:async(e={})=>{if(!this.selectionElement)return null;try{const t={width:800,height:600,imageSmoothingEnabled:!0,imageSmoothingQuality:"high",...e};return await this.selectionElement.$toCanvas(t)}catch(t){return console.warn("Error exporting to canvas:",t),null}},getData:()=>{if(!this.selectionElement)return null;try{return{x:this.selectionElement.x,y:this.selectionElement.y,width:this.selectionElement.width,height:this.selectionElement.height,aspectRatio:this.selectionElement.aspectRatio}}catch(e){return console.warn("Error getting selection data:",e),null}}};canvas={setBackground:e=>{if(!this.canvasElement)return!1;try{return this.canvasElement.background=e,!0}catch(t){return console.warn("Error setting background:",t),!1}},setScaleStep:e=>{if(!this.canvasElement)return!1;try{return this.canvasElement.scaleStep=e,!0}catch(t){return console.warn("Error setting scale step:",t),!1}},setDisabled:e=>{if(!this.canvasElement)return!1;try{return this.canvasElement.disabled=e,!0}catch(t){return console.warn("Error setting disabled state:",t),!1}}};utils={flipHorizontal:()=>{const e=this.transform.getTransform();if(!e)return!1;const[t,n,r,a,i,o]=e;return this.transform.setTransform(-t,n,r,a,i,o)},flipVertical:()=>{const e=this.transform.getTransform();if(!e)return!1;const[t,n,r,a,i,o]=e;return this.transform.setTransform(t,n,r,-a,i,o)},setupInitialView:async(e={})=>{const{paspartuFactor:t=.85,retries:n=3,retryDelay:r=200}=e;return new Promise(e=>{const a=(i=0)=>{if(!this.isReady)return i<n?void setTimeout(()=>a(i+1),r):void e(!1);try{const o=this.canvasElement.getBoundingClientRect();let l=this.image.querySelector("img")||this.image;if(!l?.naturalWidth||!l?.naturalHeight)return i<n?void setTimeout(()=>a(i+1),r):(this.transform.center(),void e(!1));if(o.width>0&&o.height>0){const n=o.width*t/l.naturalWidth,r=o.height*t/l.naturalHeight,a=Math.min(n,r,1);this.transform.setTransform(a,0,0,a,0,0)?setTimeout(()=>{this.transform.center(),this.selection.center(),e(!0)},100):(this.transform.reset(),setTimeout(()=>{a<1&&this.transform.scale(a),setTimeout(()=>{this.transform.center(),this.selection.center(),e(!0)},100)},100))}else this.transform.center(),e(!1)}catch(o){console.warn("Error in setup:",o),this.transform.center(),e(!1)}};a()})},resetAll:()=>{const e={transform:this.transform.reset(),selection:this.selection.reset(),center:!1};return setTimeout(()=>{e.center=this.transform.center()&&this.selection.center()},100),e},checkExportability:async()=>{try{return!!(await this.selection.toCanvas({width:1,height:1}))}catch{return!1}},resetZoomOnly:()=>this.transform.resetZoom(),getZoomInfo:()=>{const e=this.transform.getZoom();return{current:e,isZoomedIn:e>1,isZoomedOut:e<1,percentage:Math.round(100*e)}},setBackground:e=>this.canvas.setBackground(e)};setupEventListeners(e={}){const{onSelectionChange:t,onImageTransform:n,onAction:r,onActionStart:a,onActionMove:i,onActionEnd:o}=e,l=[];if(t&&this.selectionElement){const e=e=>{t({x:e.detail.x,y:e.detail.y,width:e.detail.width,height:e.detail.height})};this.selectionElement.addEventListener("change",e),l.push(()=>{this.selectionElement&&this.selectionElement.removeEventListener("change",e)})}if(n&&this.image){const e=e=>{n({matrix:e.detail.matrix,oldMatrix:e.detail.oldMatrix})};this.image.addEventListener("transform",e),l.push(()=>{this.image&&this.image.removeEventListener("transform",e)})}if(this.canvasElement){if(r){const e=e=>r(e.detail);this.canvasElement.addEventListener("action",e),l.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("action",e)})}if(a){const e=e=>a(e.detail);this.canvasElement.addEventListener("actionstart",e),l.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionstart",e)})}if(i){const e=e=>i(e.detail);this.canvasElement.addEventListener("actionmove",e),l.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionmove",e)})}if(o){const e=e=>o(e.detail);this.canvasElement.addEventListener("actionend",e),l.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionend",e)})}}return()=>{l.forEach(e=>e())}}}async function Qt(e,t,n={}){const{format:r=null,originalFormat:a="webp",onSuccess:i=null,onError:o=null,accessibilityManager:l=null}=n;try{const n=window.limboCore?.config?.getGlobal(),o=r||n?.downloadFormat||a||"webp",s=`${t.split(".")[0]}.${o}`;if(l&&l.announce(`Descargando ${s}`),e.startsWith("data:image/"))return function(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.style.display="none",document.body.appendChild(n),n.click(),setTimeout(()=>{document.body.removeChild(n)},100)}(e,s),i&&i(s),l&&l.announce(`${s} descargado correctamente`),!0;const c=await fetch(e,{mode:"cors"});if(!c.ok)throw new Error(`HTTP error! status: ${c.status}`);const u=await c.blob();let d=u;const m=u.type;m!==`image/${"jpg"===o?"jpeg":o}`&&function(e){return["webp","jpeg","jpg","png"].includes(e.toLowerCase())}(o)&&(d=await async function(e,t){return new Promise((n,r)=>{const a=new Image,i=URL.createObjectURL(e);a.onload=()=>{try{const r=document.createElement("canvas");r.width=a.width,r.height=a.height;r.getContext("2d").drawImage(a,0,0);const o=`image/${"jpg"===t?"jpeg":t}`,l="png"===t?void 0:.92;r.toBlob(t=>{URL.revokeObjectURL(i),n(t||e)},o,l)}catch(r){URL.revokeObjectURL(i),n(e)}},a.onerror=()=>{URL.revokeObjectURL(i),n(e)},a.src=i})}(u,o));const h=window.URL.createObjectURL(d),p=document.createElement("a");return p.href=h,p.download=s,p.style.display="none",document.body.appendChild(p),p.click(),setTimeout(()=>{window.URL.revokeObjectURL(h),document.body.removeChild(p)},100),i&&i(s),l&&l.announce(`${s} descargado correctamente`),!0}catch(s){return console.error("Error downloading image:",s),o&&o(s),l&&l.announce(`Error al descargar la imagen: ${s.message}`),!1}}const Yt=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:Qt,downloadImage:Qt},Symbol.toStringTag,{value:"Module"}));function Xt({image:e,onSave:o,onCancel:u,onDelete:d,onError:m=null,deleting:h=!1,onVariantCreated:p=null,onUpload:f=null,uploading:g=!1,cropperConfig:b=null}){const[y,v]=t(!1),[w,x]=t(null),[k,C]=t(!1),[S,N]=t(!0),[E,$]=t(!0),[_,z]=t({x:20,y:100}),[T,A]=t(!1),[P,M]=t({x:0,y:0}),[I,L]=t(!1),[D,O]=t(!0),[R,j]=t(!1),[F,U]=t({horizontal:!1,vertical:!1}),[q,W]=t(!1),[V,H]=t(!1),[K,G]=t(!1),[Q,Y]=t(!1),[X]=t(()=>{if(!e||!e.filename)return"image";const[t]=e.filename.split(".");return t}),J=i(()=>{if(b)return{mandatoryCrops:b.mandatoryCrops||[],allowCustomCrops:!1!==b.allowAdditionalCrops,showDimensionInputs:!0===b.showDimensionInputs,maxCrops:b.maxCrops||null};const e=window.limboCore?.config?.getGlobal()||{};return{mandatoryCrops:e.cropper?.mandatoryCrops||[],allowCustomCrops:!1!==e.cropper?.allowCustomCrops,showDimensionInputs:!0===e.cropper?.showDimensionInputs,maxCrops:e.cropper?.maxCrops||null}},[b]),[Z,ee]=t(()=>J.mandatoryCrops.length>0?J.mandatoryCrops.map((e,t)=>({id:`crop-${t}`,label:e.label,width:e.width,height:e.height,required:!1!==e.required,isCustom:!1,confirmed:!1,lockDimensions:!(!e.width||!e.height),savedState:null})):[{id:"crop-default-0",label:X,width:e.width||1920,height:e.height||1080,required:!1,isCustom:!0,confirmed:!1,savedState:null}]),[ne,re]=t(0),ae=Z[ne],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]),[le,se]=t(!1),[ce,ue]=t([]),[de,me]=t(null),he=window.limboCore?.accessibilityManager,{createVariantFromBlob:pe,loading:fe,error:ge}=Kt(),be=((e,i={})=>{const o=a(null),l=a(null),s=a(null),c=a(null),[u,d]=t(null),[m,h]=t(null),[p,f]=t(!1),[g,b]=t(!0),[y,v]=t(0),w={aspectRatio:"",shade:!0,paspartuFactor:.85,...i};n(()=>{o.current&&l.current&&s.current&&(c.current=new Gt(o,l,s),f(!0))},[]),n(()=>{if(c.current)return c.current.setupEventListeners({onSelectionChange:e=>{d(e)},onImageTransform:()=>{v(e=>e+1)}})},[p]),n(()=>{c.current&&e&&(async()=>{c.current.selection.setAspectRatio(w.aspectRatio),c.current.canvas.setBackground(w.shade),await c.current.utils.setupInitialView({paspartuFactor:w.paspartuFactor});const e=await c.current.utils.checkExportability();b(e);const t=l.current?.querySelector("img")||l.current;t?.naturalWidth&&t?.naturalHeight&&h({naturalWidth:t.naturalWidth,naturalHeight:t.naturalHeight,currentWidth:t.width,currentHeight:t.height})})()},[e]),n(()=>{c.current&&p&&c.current.selection.setAspectRatio(w.aspectRatio)},[w.aspectRatio,p]),n(()=>{c.current&&p&&c.current.canvas.setBackground(w.shade)},[w.shade,p]);const x=r(()=>({move:(e,t)=>c.current?.transform.move(e,t)||!1,zoom:e=>c.current?.transform.zoom(e)||!1,rotate:e=>c.current?.transform.rotate(e)||!1,center:()=>c.current?.transform.center()||!1,reset:()=>c.current?.transform.reset()||!1,resetZoom:()=>c.current?.transform.resetZoom()||!1,setZoom:e=>c.current?.transform.setZoom(e)||!1,getZoom:()=>c.current?.transform.getZoom()||1,fitToCanvas:e=>c.current?.transform.fitToCanvas(e)||!1,flipHorizontal:()=>c.current?.utils.flipHorizontal()||!1,flipVertical:()=>c.current?.utils.flipVertical()||!1}),[]),k=r(()=>({center:()=>c.current?.selection.center()||!1,reset:()=>c.current?.selection.reset()||!1,setCoverage:e=>c.current?.selection.setCoverage(e)||!1,setAspectRatio:e=>c.current?.selection.setAspectRatio(e)||!1,toCanvas:e=>c.current?.selection.toCanvas(e)||Promise.resolve(null)}),[]),C=r(()=>({resetAll:()=>{if(c.current){const e=c.current.utils.resetAll();return d(null),e}return!1},setBackground:e=>c.current?.canvas.setBackground(e)||!1,resetZoomOnly:()=>c.current?.utils.resetZoomOnly()||!1,getZoomInfo:()=>c.current?.utils.getZoomInfo()||{current:1,percentage:100,isZoomedIn:!1,isZoomedOut:!1}}),[]);return{refs:{canvasRef:o,imageRef:l,selectionRef:s},state:{cropData:u,imageInfo:m,isReady:p,canExport:g,transformVersion:y},transform:x(),selection:k(),utils:C(),manager:c.current}})(e,{aspectRatio:ie||null,showGrid:S,shade:E,initialCoverage:.5,paspartuFactor:.85}),{refs:ye,state:ve,transform:we,selection:xe,utils:ke}=be,{canvasRef:Ce,imageRef:Se,selectionRef:Ne}=ye,{cropData:Ee,imageInfo:$e,canExport:_e,transformVersion:ze}=ve,Te=i(()=>$e||{naturalWidth:e.width||1920,naturalHeight:e.height||1080,currentWidth:e.width||1920,currentHeight:e.height||1080},[$e,e.width,e.height]),Ae=r(()=>N(e=>!e),[]),Pe=r(()=>$(e=>!e),[]),Me=r(()=>H(e=>!e),[]),Ie=r(()=>G(e=>!e),[]),Le=r(()=>Y(e=>!e),[]),De=r(()=>we.center(),[we]),Oe=r(()=>xe.center(),[xe]),Re=r(()=>xe.reset(),[xe]),je=r((e,t)=>we.move(e,t),[we]),Fe=r(e=>we.zoom(e),[we]),Ue=r(e=>we.rotate(e),[we]),qe=r(e=>{xe.setCoverage(e)},[xe]),Be=r(()=>{U(e=>{const t=!e.horizontal;return we.flipHorizontal(),{...e,horizontal:t}})},[we]),We=r(()=>{U(e=>{const t=!e.vertical;return we.flipVertical(),{...e,vertical:t}})},[we]),Ve=r(()=>{if(!be.manager||!ve.isReady)return null;try{const e=Ee?{...Ee}:null;let t=null;if(Ne.current){const e=Ne.current;t={x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0}}let n=null;if(Se.current){const e=Se.current.$getTransform?.();e&&Array.isArray(e)&&(n=[...e])}const r={cropData:e,selectorState:t,imageTransform:n,flipState:{horizontal:F.horizontal,vertical:F.vertical}};return console.log(`[CropperView] 💾 Guardando estado del crop ${ne}:`,r),ee(e=>e.map((e,t)=>t===ne?{...e,savedState:r}:e)),r}catch(e){return console.warn("Error saving crop state:",e),null}},[be.manager,ve.isReady,Ee,F,ne,Se,Ne]),He=r(e=>{const t=Z[e];if(!t||!t.savedState)return console.log(`[CropperView] ℹ️ No hay estado guardado para crop ${e}, centrando...`),void setTimeout(()=>{De(),setTimeout(()=>Oe(),100)},100);if(be.manager&&ve.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,r,a,i,o]=n.imageTransform;Se.current.$setTransform(e,t,r,a,i,o),console.log(`[CropperView] ✅ Imagen restaurada: transform(${e.toFixed(2)}, ${t.toFixed(2)}, ${r.toFixed(2)}, ${a.toFixed(2)}, ${i.toFixed(0)}, ${o.toFixed(0)})`)}},100),n.selectorState&&Ne.current){const{x:e,y:t,width:r,height:a}=n.selectorState;setTimeout(()=>{Ne.current&&(Ne.current.x=e,Ne.current.y=t,Ne.current.width=r,Ne.current.height=a,Ne.current.$render&&Ne.current.$render(),console.log(`[CropperView] ✅ Selector restaurado: ${r}×${a} en (${e}, ${t})`))},150)}n.flipState&&U({horizontal:n.flipState.horizontal??!1,vertical:n.flipState.vertical??!1}),console.log("[CropperView] ✨ Estado restaurado completamente")}catch(n){console.error("Error restoring crop state:",n),setTimeout(()=>{De(),setTimeout(()=>Oe(),100)},100)}else console.warn("Cropper not ready for state restoration")},[Z,be.manager,ve.isReady,De,Oe,Ne,Se]),Ke=r(()=>{for(let e=0;e<Z.length;e++){const t=Z[e];if(!t.label||""===t.label.trim())return e}return-1},[Z]),Ge=r(async e=>{e!==ne&&(j(!0),Ve(),await new Promise(e=>setTimeout(e,100)),re(e),await new Promise(e=>setTimeout(e,250)),He(e),await new Promise(e=>setTimeout(e,200)),j(!1))},[ne,Ve,He]),Qe=r(()=>{if(!J.allowCustomCrops)return void alert("No se pueden añadir recortes personalizados en este modo.");const t={id:`crop-custom-${Date.now()}`,label:`Recorte ${Z.length+1}`,width:e.width||1920,height:e.height||1080,required:!1,isCustom:!0,confirmed:!1,savedState:null};ee(e=>[...e,t]),he?.announce(`Nuevo recorte personalizado añadido: ${t.label}. Selecciónalo para editarlo.`)},[J.allowCustomCrops,Z.length,e.width,e.height,he]),Ye=r((e,t)=>{const n=parseInt(t,10);""===t||isNaN(n)||ee(t=>t.map((t,r)=>r===ne?{...t,[e]:n}:t))},[ne]),Xe=r(e=>{const t=ae[e];let n=100;if(Ce.current&&$e){const e=Ce.current.getBoundingClientRect(),t=Math.min(e.width,e.height);n=Math.max(100,Math.round(.05*t))}const r=Math.max(n,Math.min(5e3,t));r!==t&&ee(t=>t.map((t,n)=>n===ne?{...t,[e]:r}:t));const a={...ae,[e]:r},i=a.width/a.height,o=xe.getData?.();xe.setAspectRatio(i),o&&void 0!==o.x&&setTimeout(()=>{xe.set?.(o.x,o.y,o.width,o.height)},50)},[ne,ae,xe,Ce,$e]),Je=r(e=>{ee(t=>t.map((t,n)=>n===ne?{...t,label:e}:t))},[ne]),Ze=r((e,t=null)=>{t=t||Z[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=Z[e];if(n.required)alert("No se puede eliminar un recorte obligatorio.");else if(1!==Z.length){if(ee(t=>t.filter((t,n)=>n!==e)),e===ne){const t=Math.max(0,e-1);re(t)}else e<ne&&re(e=>e-1);he?.announce(`Recorte ${n.label} eliminado`)}else alert("Debe haber al menos un recorte.")},[Z,ne,he]),et=r(async()=>{if(!_e)return null;try{const t=await xe.toCanvas({width:800,height:600,imageSmoothingEnabled:!0,imageSmoothingQuality:"high"});return t?t.toDataURL(`image/${globalThis.downloadFormat||e.mime_type.split("/")[1]||"webp"}`,.9):null}catch(t){return console.warn("Error generating preview:",t),null}},[_e,e.mime_type,xe]),tt=r(async()=>{if(y)return v(!1),x(null),void C(!1);if(_e){v(!0),C(!0);try{const e=await et();e?x(e):(v(!1),alert("No se puede exportar el recorte por restricciones de CORS en la imagen original."))}finally{C(!1)}}else alert("No se puede exportar el recorte por restricciones de CORS en la imagen original.")},[_e,et,y]),nt=r(e=>{e.target.closest(".limbo-preview-modal-header")&&(A(!0),M({x:e.clientX-_.x,y:e.clientY-_.y}))},[_]),rt=r(e=>{T&&(e.preventDefault(),z({x:e.clientX-P.x,y:e.clientY-P.y}))},[T,P]),at=r(()=>{A(!1)},[]),it=r(e=>{if(!e.target.closest(".limbo-preview-modal-header"))return;const t=e.touches[0];A(!0),M({x:t.clientX-_.x,y:t.clientY-_.y})},[_]),ot=r(e=>{if(!T)return;e.preventDefault();const t=e.touches[0];z({x:t.clientX-P.x,y:t.clientY-P.y})},[T,P]),lt=r(()=>{A(!1)},[]);n(()=>{if(T)return document.addEventListener("mousemove",rt),document.addEventListener("mouseup",at),document.addEventListener("touchmove",ot,{passive:!1}),document.addEventListener("touchend",lt),()=>{document.removeEventListener("mousemove",rt),document.removeEventListener("mouseup",at),document.removeEventListener("touchmove",ot),document.removeEventListener("touchend",lt)}},[T,rt,at,ot,lt]),n(()=>{if(!I)return;const e=e=>{"Escape"===e.key&&L(!1)};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[I]);const st=r(async(t,n=null)=>{const r=Z[t];if(!r)throw new Error(`Crop ${t} no encontrado`);if(!r.savedState&&t!==ne)throw new Error(`El recorte "${r.label}" aún no ha sido configurado`);const a={index:ne,imageTransform:Se.current?.$getTransform?.(),selectorState:Ne.current?{x:Ne.current.x,y:Ne.current.y,width:Ne.current.width,height:Ne.current.height}:null};try{if(t!==ne&&r.savedState){if(console.log(`[CropperView] 🔄 Restaurando temporalmente crop ${t} para guardado...`),r.savedState.imageTransform&&Se.current?.$setTransform){const[e,t,n,a,i,o]=r.savedState.imageTransform;Se.current.$setTransform(e,t,n,a,i,o)}if(r.savedState.selectorState&&Ne.current){const{x:e,y:t,width:n,height:a}=r.savedState.selectorState;Ne.current.x=e,Ne.current.y=t,Ne.current.width=n,Ne.current.height=a,Ne.current.$render?.()}await new Promise(e=>setTimeout(e,100))}const a=Math.min(r.width,5e3),i=Math.min(r.height,5e3),o=await xe.toCanvas({width:a,height:i,imageSmoothingEnabled:!0,imageSmoothingQuality:"high"});if(!o)throw new Error(`No se pudo generar el canvas para "${r.label}"`);const l=globalThis.downloadFormat||"webp",s="webp"===l?"image/webp":"png"===l?"image/png":"image/jpeg",c=.9,u=await new Promise((e,t)=>{o.toBlob(n=>{n?e(n):t(new Error("No se pudo convertir el canvas a blob"))},s,c)});console.log("[CropperView] Canvas convertido a blob:",{size:u.size,type:u.type,dimensions:`${a}x${i}`});const d=`${r.label||"crop"}_${a}_${i}`,m=n||e.id;if(!m||"string"==typeof m&&m.startsWith("external")){console.log("[CropperView] 🌐 Imagen externa detectada, generando resultado local");const e=URL.createObjectURL(u),t={id:`local-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:d,filename:`${d}.${l}`,url:e,urlSigned:e,width:a,height:i,format:l,size:u.size,mime_type:s,blob:u,isLocal:!0};return he?.announceSuccess(`Recorte creado localmente: ${d}`),t}const h=await pe(m,u,{name:d,width:a,height:i,format:l});if(h)return he?.announceSuccess(`Recorte creado: ${d}`),p?.(m,h),h;throw new Error("No se pudo crear la variante")}finally{if(t!==ne&&a.imageTransform&&Se.current?.$setTransform){console.log(`[CropperView] ↩️ Restaurando estado original del crop ${a.index}...`);const[e,t,n,r,i,o]=a.imageTransform;if(Se.current.$setTransform(e,t,n,r,i,o),a.selectorState&&Ne.current){const{x:e,y:t,width:n,height:r}=a.selectorState;Ne.current.x=e,Ne.current.y=t,Ne.current.width=n,Ne.current.height=r,Ne.current.$render?.()}}}},[Z,ne,xe,pe,e.id,p,he,Se,Ne]),ct=r(async()=>{if(!_e){const e="No se puede exportar el recorte por restricciones de CORS en la imagen original.";return he?.announceError(e),void alert(e)}if(!ve.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)}Ve(),he?.announce("Creando recorte de la imagen");try{let t=e.id,n=null;if(e.file&&f){he?.announce("Subiendo imagen...");const r=await f(e.file);if(!r||!r.id)throw new Error("No se pudo subir la imagen al servidor");t=r.id,n=r,he?.announceSuccess("Imagen subida correctamente")}const r=await st(ne,t);r&&o(n?{crops:[r],asset:n}:r)}catch(t){console.warn("Error creating crop variant:",t);const e=t.message||"No se pudo crear el recorte. Inténtalo de nuevo.";he?.announceError(e),alert(e),m?.(t)}},[_e,ve.isReady,he,Ve,st,ne,o,m,e.file,e.id,f]),ut=r(async t=>{Ve(),he?.announce(`Guardando ${t.length} recortes...`);try{let r=e.id,a=null;if(e.file&&f){he?.announce("Subiendo imagen...");const t=await f(e.file);if(!t||!t.id)throw new Error("No se pudo subir la imagen al servidor");r=t.id,a=t,he?.announceSuccess("Imagen subida correctamente")}const i=[],l=[];for(const e of t)try{const t=await st(e,r);t&&i.push(t)}catch(n){l.push({crop:Z[e]?.label||`Crop ${e}`,error:n.message})}if(i.length>0&&(he?.announceSuccess(`${i.length} recorte(s) guardado(s) correctamente`),o(a?{crops:i,asset:a}:i)),l.length>0){const e=`Errores al guardar algunos recortes:\n${l.map(e=>`- ${e.crop}: ${e.error}`).join("\n")}`;he?.announceError(e),alert(e)}}catch(n){const e=n.message||"Error al procesar los recortes";he?.announceError(e),alert(e),m?.(n)}},[Ve,st,Z,he,o,e.file,e.id,f,m]),dt=r(async()=>{const e=Ke();if(-1!==e){const t=Z[e];return alert(`El recorte "${t.label||t||"(sin nombre)"}" debe tener un nombre válido.`),void re(e)}if(Z.length>1){me("save");const e=Z.map((e,t)=>({crop:e,index:t})).filter(({crop:e,index:t})=>e.required||e.savedState||t===ne).map(({index:e})=>e);return ue(e),void se(!0)}await ct()},[Ke,Z,ct,ne]),mt=r(async t=>{const n=Z[t];if(!n)throw new Error(`Crop ${t} no encontrado`);if(!n.savedState&&t!==ne)throw new Error(`El recorte "${n.label}" aún no ha sido configurado`);const r={index:ne,imageTransform:Se.current?.$getTransform?.(),selectorState:Ne.current?{x:Ne.current.x,y:Ne.current.y,width:Ne.current.width,height:Ne.current.height}:null};try{if(t!==ne&&n.savedState){if(console.log(`[CropperView] 🔄 Restaurando temporalmente crop ${t} para descarga...`),n.savedState.imageTransform&&Se.current?.$setTransform){const[e,t,r,a,i,o]=n.savedState.imageTransform;Se.current.$setTransform(e,t,r,a,i,o)}if(n.savedState.selectorState&&Ne.current){const{x:e,y:t,width:r,height:a}=n.savedState.selectorState;Ne.current.x=e,Ne.current.y=t,Ne.current.width=r,Ne.current.height=a,Ne.current.$render?.()}await new Promise(e=>setTimeout(e,100))}const r=await xe.toCanvas({width:n.width,height:n.height,imageSmoothingEnabled:!0,imageSmoothingQuality:"high"});if(!r)throw new Error(`No se pudo generar el canvas para "${n.label}"`);const a=r.toDataURL(`image/${globalThis.downloadFormat||e.mime_type.split("/")[1]||"webp"}`,.9),i=`${(n.label||"crop").replace(/\.[^/.]+$/,"").replace(/\s+/g,"-").trim()}_${n.width}_${n.height}`;return await Qt(a,i,{accessibilityManager:he,onSuccess:e=>{console.log(`✅ Descargado: ${e}`)},onError:e=>{throw new Error(`Error al descargar "${n.label}": ${e.message}`)}}),{crop:n.label,filename:i}}finally{if(t!==ne&&r.imageTransform&&Se.current?.$setTransform){console.log(`[CropperView] ↩️ Restaurando estado original del crop ${r.index}...`);const[e,t,n,a,i,o]=r.imageTransform;if(Se.current.$setTransform(e,t,n,a,i,o),r.selectorState&&Ne.current){const{x:e,y:t,width:n,height:a}=r.selectorState;Ne.current.x=e,Ne.current.y=t,Ne.current.width=n,Ne.current.height=a,Ne.current.$render?.()}}}},[Z,ne,xe,e.mime_type,he,Se,Ne]),ht=r(async e=>{Ve(),he?.announce(`Descargando ${e.length} recortes...`);const t=[],n=[];for(const a of e)try{const e=await mt(a);e&&t.push(e)}catch(r){n.push({crop:Z[a]?.label||`Crop ${a}`,error:r.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)}},[Ve,mt,Z,he]),pt=r(async()=>{if(!_e){const e="No se puede descargar el recorte por restricciones de CORS en la imagen original.";return he?.announceError(e),void alert(e)}Ve(),he?.announce("Preparando descarga del recorte");try{await mt(ne),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)}},[_e,he,Ve,mt,ne]),ft=r(async()=>{const e=Ke();if(-1!==e){const t=Z[e];return alert(`El recorte "${t.label||t||"(sin nombre)"}" debe tener un nombre válido.`),void re(e)}if(Z.length>1){me("download");const e=Z.map((e,t)=>({crop:e,index:t})).filter(({crop:e,index:t})=>e.savedState||t===ne).map(({index:e})=>e);return ue(e),void se(!0)}await pt()},[Ke,Z,pt,ne]),gt=i(()=>!!e.file||(!e.id||!("string"!=typeof e.id||!e.id.startsWith("external"))),[e.file,e.id]),bt=r(async()=>{try{if(e.file&&f){he?.announce("Subiendo imagen original...");const t=await f(e.file);if(!t||!t.id)throw new Error("No se pudo subir la imagen al servidor");return he?.announceSuccess("Imagen guardada correctamente"),void o({asset:t,crops:[]})}if(gt){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 o({crops:[t]})}u()}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),m?.(t)}},[e,$e,f,u,o,m,he,gt]);return n(()=>{v(!1),x(null)},[e]),n(()=>{be.manager&&ve.isReady&&D&&(console.log("[CropperView] Carga inicial completada, centrando imagen y selector..."),setTimeout(()=>{De(),setTimeout(()=>{Oe(),O(!1),console.log("[CropperView] Carga inicial finalizada")},100)},50))},[be.manager,ve.isReady,D,De,Oe]),n(()=>{be.manager&&ve.isReady&&(ie&&xe.setAspectRatio(ie),ke.setBackground(E))},[ie,E,be.manager,ve.isReady,xe,ke]),n(()=>{if(!$e||!ve.isReady||J.mandatoryCrops.length>0)return;const e=Z[0];if(e&&"crop-default-0"===e.id&&(1920===e.width||1080===e.height)){const t=Math.min($e.naturalWidth,5e3),n=Math.min($e.naturalHeight,5e3);ee([{...e,width:t,height:n}]),console.log(`[CropperView] Crop por defecto actualizado a ${t}×${n}px`)}},[$e,ve.isReady,J.mandatoryCrops.length,Z]),n(()=>{if(!y||!_e)return;const e=setTimeout(async()=>{C(e=>!w&&!e||e);try{const e=await et();e&&x(e)}finally{C(!1)}},300);return()=>{clearTimeout(e),C(!1)}},[Ee,ze,y,_e,et,ie,F,w]),n(()=>{const e=Ce.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)}},[Ce]),e?/* @__PURE__ */s("div",{className:"limbo-cropper-view px-2 border-2 border-gray-200/50 rounded-lg max-w-7xl mx-auto w-full min-w-full h-full min-h-full flex flex-col",children:[
229
229
  /* @__PURE__ */s("div",{className:"limbo-cropper-header flex flex-row justify-between items-start flex-wrap mx-2 py-2 border-b border-gray-200 bg-white z-10 shrink-0 lg:gap-2",children:[
230
230
  /* @__PURE__ */s("div",{className:"flex-1 min-w-fit space-y-2 max-w-fit",children:[
231
231
  /* @__PURE__ */s("div",{className:"flex items-center gap-2",children:[
@@ -334,7 +334,7 @@ return s("label",{className:"h-fit flex flex-col p-1.5 rounded border cursor-poi
334
334
  /* @__PURE__ */s("div",{className:"flex flex-row gap-1 lg:gap-2 items-center justify-end",children:[
335
335
  /* @__PURE__ */l("button",{onClick:ft,disabled:fe||!_e,className:"cursor-pointer px-3 py-1.5 text-sm rounded bg-brand-blue-800 hover:bg-brand-blue-1000 text-white transition-colors disabled:opacity-50 disabled:cursor-not-allowed","aria-label":"Descargar",title:"Descargar recorte sin guardar",children:/* @__PURE__ */s("div",{className:"flex items-center gap-1",children:[
336
336
  /* @__PURE__ */l("span",{className:"icon icon-download-white icon--sm"}),
337
- /* @__PURE__ */l("span",{className:"hidden md:inline whitespace-nowrap",children:"Descargar"})]})}),e.file&&/* @__PURE__ */l("button",{onClick:gt,disabled:fe||g,className:"px-3 cursor-pointer py-1.5 text-sm rounded bg-teal-600 hover:bg-teal-700 text-white transition-colors disabled:opacity-50 disabled:cursor-not-allowed","aria-label":"Conservar solo imagen original sin crear recortes",title:"Subir y guardar la imagen original sin crear recortes",children:/* @__PURE__ */s("div",{className:"flex items-center gap-1",children:[
337
+ /* @__PURE__ */l("span",{className:"hidden md:inline whitespace-nowrap",children:"Descargar"})]})}),gt&&/* @__PURE__ */l("button",{onClick:bt,disabled:fe||g,className:"px-3 cursor-pointer py-1.5 text-sm rounded bg-teal-600 hover:bg-teal-700 text-white transition-colors disabled:opacity-50 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__ */s("div",{className:"flex items-center gap-1",children:[
338
338
  /* @__PURE__ */l("span",{className:"icon icon-tick-white icon--sm"}),
339
339
  /* @__PURE__ */l("span",{className:"hidden md:inline whitespace-nowrap",children:"Conservar original"})]})}),
340
340
  /* @__PURE__ */l("button",{onClick:dt,disabled:fe||!Ee||!Te||!_e||!ve.isReady,className:"px-3 cursor-pointer py-1.5 text-sm rounded bg-green-600 hover:bg-green-700 text-white transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Guardar imagen recortada",children:/* @__PURE__ */l("div",{className:"flex items-center gap-1",children:/* @__PURE__ */s(c,fe?{children:[
@@ -464,7 +464,7 @@ return s("label",{className:`flex items-center gap-3 p-3 rounded border transiti
464
464
  /* @__PURE__ */s("div",{className:"limbo-preview-modal-header px-4 py-3 bg-gradient-to-r from-brand-blue-800 to-brand-blue-1000 text-white flex items-center justify-between cursor-grab active:cursor-grabbing select-none",style:{cursor:T?"grabbing":"grab"},children:[
465
465
  /* @__PURE__ */s("div",{className:"flex items-center gap-2",children:[
466
466
  /* @__PURE__ */l("span",{className:"icon icon-search-white icon--sm"}),
467
- /* @__PURE__ */l("h3",{className:"text-sm font-semibold",children:"Vista previa"})]}),
467
+ /* @__PURE__ */l("h3",{className:"text-sm font-semibold text-white",children:"Vista previa"})]}),
468
468
  /* @__PURE__ */l("button",{onClick:()=>{v(!1),x(null)},className:"flex p-1 hover:bg-white/20 rounded transition-colors cursor-pointer aspect-square min-w-fit min-h-fit","aria-label":"Cerrar vista previa",title:"Cerrar vista previa",children:/* @__PURE__ */l("span",{className:"icon icon-close-small-white icon--sm p-0 m-0 py-auto my-auto mx-auto"})})]}),
469
469
  /* @__PURE__ */l("div",{className:"flex-1 overflow-auto bg-gray-50 p-4",children:k?/* @__PURE__ */l("div",{className:"flex items-center justify-center h-full min-h-[200px]",children:/* @__PURE__ */s("div",{className:"text-center",children:[
470
470
  /* @__PURE__ */l("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-3"}),
@@ -501,10 +501,10 @@ return s("div",{className:"flex flex-col items-center justify-center py-8 text-g
501
501
  /* @__PURE__ */l("div",{className:"flex justify-end space-x-3",children:/* @__PURE__ */l("button",{onClick:t,className:"px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors",children:"Recargar Página"})})]})}):null}function tn(){const[e,n]=t(!1),[r,a]=t(null);return{deleteImg:async e=>{if(!e)return a("ID de imagen no proporcionado"),!1;n(!0),a(null);try{const t=await async function(e){try{return await A({endpoint:`/assets/${e}`,method:"DELETE",basePath:R,useJWT:!0})}catch(r){throw O(r)}}(e);return!1!==t.success}catch(t){return a(t.message),!1}finally{n(!1)}},loading:e,error:r,reset:()=>{a(null)}}}const nn=/* @__PURE__ */new Map;function rn(e,r=500){const[a,i]=t(e);return n(()=>{const t=setTimeout(()=>{i(e)},r);return()=>{clearTimeout(t)}},[e,r]),a}function an({apiKey:e,prod:a=!1,url:o=!0,features:u=["gallery","upload","cropper"],modeUI:d="full",ui:m={showActions:["select","download","copy","delete","crop","variants"],hideActions:[],theme:"light",language:"es",compactMode:!1,showTabs:!0},callbacks:h={},instanceId:p=null,itemsPerPage:f=10,_externalImage:g=null,cropperConfig:b=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[y,v]=t({name:"",uploadedBy:"",dateFrom:"",dateTo:""}),w=rn(y.name,500),x=rn(y.uploadedBy,500),k=(()=>{switch(d){case"gallery-only":return["gallery"];case"upload-only":return["upload","cropper"];case"crop-only":return["cropper"];case"ia-only":return["ia"];default:return u}})(),[C,S]=t(k.includes("gallery")?"gallery":k.includes("upload")?"upload":k.includes("cropper")?"cropper":k.includes("ia")?"ia":k[0]||"gallery"),[N,$]=t(null);n(()=>{g&&(console.log("📸 Imagen externa detectada:",g),$(g),S("cropper"))},[g]);const[_,z]=t(1),{isTokenExpired:T,handleTokenExpiredClose:A}=function(){const[e,a]=t(!1),i=r(e=>{if(401===e?.response?.status){const t=e.response.data;if("token_expired"===t?.error||t?.message?.includes("expired")||t?.message?.includes("caducado")||t?.error?.includes("expired"))return a(!0),!0}return!1},[]),o=r(()=>{a(!1),alert("El token ha expirado. La página se recargará para obtener un nuevo token."),window.location.reload()},[]);return n(()=>{const e=e=>{e.detail&&e.detail.error&&i(e.detail.error)};return window.addEventListener("tokenExpiredError",e),()=>{window.removeEventListener("tokenExpiredError",e)}},[i]),{isTokenExpired:e,checkTokenExpiration:i,handleTokenExpiredClose:o}}(),{upload:P,loading:M,error:I,uploadedImage:L,reset:D}=function(){const[e,n]=t(!1),[r,a]=t(null),[i,o]=t(null);return{upload:async(e,t=null)=>{if(!e)return a("No se ha proporcionado ningún archivo"),null;n(!0),a(null),o(null);try{const n=await F(e,t,!1),r=n.result||n;return o(r),r}catch(r){return a(r.message),null}finally{n(!1)}},loading:e,error:r,uploadedImage:i,reset:()=>{a(null),o(null)}}}(),{deleteImg:O,loading:R,error:U,reset:B}=tn(),W={limit:f,page:_,...w&&{name:w},...x&&{uploadedBy:x},...y.dateFrom&&{dateFrom:y.dateFrom},...y.dateTo&&{dateTo:y.dateTo}},V=k.includes("gallery"),{images:H,loading:G,error:Q,pagination:Y,invalidateCache:X,setImages:J}=function(e,r=!1,a={},o=!0){const[l,s]=t([]),[c,u]=t(o),[d,m]=t(null),[h,p]=t(null),[f,g]=t(0),b=i(()=>JSON.stringify(a),[a]);return n(()=>{if(!o)return void u(!1);const e=`${b}`,t=nn.get(e),n=Date.now();if(t&&n-t.timestamp<6e5)return s(t.data),p(t.pagination||null),void u(!1);let r=!0;return(async()=>{if(f>=3)r&&(m("Error de autenticación: Verifica tus credenciales API"),u(!1));else try{const t=await j(a);if(!r)return;const i=t.result||t.data||[],o=t.pagination||null;s(i),p(o),m(null),g(0),nn.set(e,{data:i,pagination:o,timestamp:n})}catch(t){r&&(m(t.message),g(e=>e+1))}finally{r&&u(!1)}})(),()=>{r=!1}},[e,r,b,f,a,o]),{images:l,loading:c,error:d,pagination:h,setImages:s,invalidateCache:()=>{nn.delete(`${b}`)}}}(e,a,W,V),{refreshVariants:Z}=q(),ee=e=>!m.hideActions?.includes(e)&&(!!m.showActions?.includes(e)||!(m.showActions?.length>0)),te=[{id:"gallery",label:"Galería",feature:"gallery"},{id:"upload",label:"Subir nueva",feature:"upload"},{id:"cropper",label:"Recortador",hideNonActive:!0,feature:"cropper"}].filter(e=>k.includes(e.feature)),ne=async e=>{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}),r={file:e,filename:e.name,mime_type:e.type,url:URL.createObjectURL(e),width:n.width,height:n.height};if($(r),k.includes("cropper"))S("cropper");else{const t=await P(e);t&&(X(),z(1),J(e=>[t,...e]),S("gallery"),h.onUpload&&h.onUpload({assetId:t.id,url:t.url,fileName:t.filename,mime:t.mime_type,width:t.width,height:t.height,instanceId:p}))}},re=async e=>{if(!confirm("¿Estás seguro de que deseas eliminar esta imagen? Esta acción también eliminará todos sus recortes."))return;await O(e)&&(X(),z(1),J(t=>t.filter(t=>t.id!==e)),N&&N.id===e&&($(null),S("gallery")))},ae=()=>"crop-only"===d||1===k.length&&"cropper"===k[0]?"crop-only":k.includes("gallery")?"with-gallery":k.includes("upload")&&!k.includes("gallery")?"upload-only":"with-gallery";/* @__PURE__ */
502
502
  return s(c,{children:[m.showTabs&&"cropper"!=C&&/* @__PURE__ */l(E,{tabs:te,active:C,onChange:e=>{S(e),"upload"!==e&&D(),"gallery"!==e&&B()}}),Q&&/* @__PURE__ */s("div",{className:"alert alert-danger",children:["Error al cargar imágenes: ",Q]}),U&&/* @__PURE__ */s("div",{className:"alert alert-danger",children:["Error al eliminar imagen: ",U]}),"gallery"===C&&/* @__PURE__ */s(c,{children:[R&&/* @__PURE__ */l(Zt,{text:"Eliminando imagen..."}),L&&/* @__PURE__ */s("div",{className:"alert alert-success absolute top-0 right-[50px] m-4",children:["✅ Imagen subida correctamente: ",L.filename]}),
503
503
  /* @__PURE__ */l(K,{onSelect: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:e=>{$(e),k.includes("cropper")&&S("cropper")},onDelete:ee("delete")?re:null,deletingId:R,images:H,loading:G,error:Q,filters:y,onFiltersChange:e=>{v(e),z(1)},filterConfig:m.galleryFilters||{},loadingConfig:m.galleryLoading||{},allowedActions:{select:ee("select"),download:ee("download"),copy:ee("copy"),delete:ee("delete"),crop:ee("crop")}}),Y&&!G&&/* @__PURE__ */l(Jt,{currentPage:Y.page||_,totalPages:Y.pages||1,onPageChange:e=>{z(e)},disabled:G||R})]}),"upload"===C&&/* @__PURE__ */s("div",{children:[M&&/* @__PURE__ */l(Zt,{text:"Subiendo imagen..."}),I&&/* @__PURE__ */s("div",{className:"alert alert-danger",children:["Error al subir imagen: ",I]}),L&&/* @__PURE__ */s("div",{className:"alert alert-success absolute top-0 right-[50px] m-4",children:["✅ Imagen subida correctamente: ",L.filename]}),
504
- /* @__PURE__ */l(he,{onSelect:ne,disabled:M,apiKey:e,prod:a})]}),"cropper"===C&&N&&/* @__PURE__ */l(Xt,{image:N,onSave:e=>{const t=ae(),n=window.limboCore?.config?.getGlobal()||{},r=n.mode||"embed",a=n.autoHideOnComplete||!1;let i=[],o=null;e.crops&&e.asset?(i=e.crops,o=e.asset):i=Array.isArray(e)?e:[e],o&&"with-gallery"===t&&(J(e=>[o,...e]),z(1),h.onUpload&&h.onUpload({assetId:o.id,url:o.url,fileName:o.filename,mime:o.mime_type,width:o.width,height:o.height,instanceId:p})),"with-gallery"===t&&X();const l=o||N,s={crops:i,assetId:l?.id,instanceId:p,asset:l?{id:l.id,url:l.url||l.urlSigned,width:l.width,height:l.height,filename:l.filename,mime_type:l.mime_type}:null};switch(h.onCropsSaved&&h.onCropsSaved(s),window.limboCore?.events&&window.limboCore.events.emit("cropsSaved",s),t){case"with-gallery":$(null),S("gallery");break;case"upload-only":"modal"===r?window.limboCore?.modals?.closeAllModals():($(null),S("upload"));break;case"crop-only":if("modal"===r)h.onCropperComplete&&h.onCropperComplete({crops:i,instanceId:p}),window.limboCore?.events&&window.limboCore.events.emit("cropperComplete",{crops:i,instanceId:p}),window.limboCore?.modals?.closeAllModals();else if(h.onCropperComplete&&h.onCropperComplete({crops:i,instanceId:p}),window.limboCore?.events&&window.limboCore.events.emit("cropperComplete",{crops:i,instanceId:p}),a){const e=document.querySelector(`#limbo-instance-${p}`);e&&(e.style.display="none")}}},onCancel:()=>{const e=ae(),t=(window.limboCore?.config?.getGlobal()||{}).mode||"embed";switch(h.onCropperCancelled&&h.onCropperCancelled({assetId:N?.id,instanceId:p}),window.limboCore?.events&&window.limboCore.events.emit("cropperCancelled",{assetId:N?.id,instanceId:p}),e){case"with-gallery":$(null),S("gallery");break;case"upload-only":"modal"===t?window.limboCore?.modals?.closeAllModals():($(null),S("upload"));break;case"crop-only":"modal"===t?window.limboCore?.modals?.closeAllModals():window.limboCore?.events&&window.limboCore.events.emit("cropperClosed",{instanceId:p,reason:"cancelled"})}},onDelete:N?.id&&ee("delete")?()=>re(N.id):null,onError:e=>{h.onCropperError&&h.onCropperError(e,p),window.limboCore?.events&&window.limboCore.events.emit("cropperError",{error:e,assetId:N?.id,instanceId:p}),console.error("Cropper error:",e)},deleting:R,onVariantCreated:(e,t)=>{Z(e)},onUpload:P,uploading:M,cropperConfig:b}),"cropper"===C&&!N&&
504
+ /* @__PURE__ */l(he,{onSelect:ne,disabled:M,apiKey:e,prod:a})]}),"cropper"===C&&N&&/* @__PURE__ */l(Xt,{image:N,onSave:e=>{const t=ae(),n=window.limboCore?.config?.getGlobal()||{},r=n.mode||"embed",a=n.autoHideOnComplete||!1;let i=[],o=null;e.crops&&e.asset?(i=e.crops,o=e.asset):i=Array.isArray(e)?e:[e],o&&"with-gallery"===t&&(J(e=>[o,...e]),z(1),h.onUpload&&h.onUpload({assetId:o.id,url:o.url,fileName:o.filename,mime:o.mime_type,width:o.width,height:o.height,instanceId:p})),"with-gallery"===t&&X();const l=o||N,s={crops:i,assetId:l?.id,instanceId:p,asset:l?{id:l.id,url:l.url||l.urlSigned,width:l.width,height:l.height,filename:l.filename,mime_type:l.mime_type}:null};switch(h.onCropsSaved&&h.onCropsSaved(s),window.limboCore?.events&&window.limboCore.events.emit("cropsSaved",s),t){case"with-gallery":"modal"===r?window.limboCore?.modals?.closeAllModals():($(null),S("gallery"));break;case"upload-only":"modal"===r?window.limboCore?.modals?.closeAllModals():($(null),S("upload"));break;case"crop-only":if("modal"===r)h.onCropperComplete&&h.onCropperComplete({crops:i,instanceId:p}),window.limboCore?.events&&window.limboCore.events.emit("cropperComplete",{crops:i,instanceId:p}),window.limboCore?.modals?.closeAllModals();else if(h.onCropperComplete&&h.onCropperComplete({crops:i,instanceId:p}),window.limboCore?.events&&window.limboCore.events.emit("cropperComplete",{crops:i,instanceId:p}),a){const e=document.querySelector(`#limbo-instance-${p}`);e&&(e.style.display="none")}}},onCancel:()=>{const e=ae(),t=(window.limboCore?.config?.getGlobal()||{}).mode||"embed";switch(h.onCropperCancelled&&h.onCropperCancelled({assetId:N?.id,instanceId:p}),window.limboCore?.events&&window.limboCore.events.emit("cropperCancelled",{assetId:N?.id,instanceId:p}),e){case"with-gallery":$(null),S("gallery");break;case"upload-only":"modal"===t?window.limboCore?.modals?.closeAllModals():($(null),S("upload"));break;case"crop-only":"modal"===t?window.limboCore?.modals?.closeAllModals():window.limboCore?.events&&window.limboCore.events.emit("cropperClosed",{instanceId:p,reason:"cancelled"})}},onDelete:N?.id&&ee("delete")?()=>re(N.id):null,onError:e=>{h.onCropperError&&h.onCropperError(e,p),window.limboCore?.events&&window.limboCore.events.emit("cropperError",{error:e,assetId:N?.id,instanceId:p}),console.error("Cropper error:",e)},deleting:R,onVariantCreated:(e,t)=>{Z(e)},onUpload:P,uploading:M,cropperConfig:b}),"cropper"===C&&!N&&
505
505
  /* @__PURE__ */s("div","crop-only"===d?{children:[M&&/* @__PURE__ */l(Zt,{text:"Subiendo imagen..."}),I&&/* @__PURE__ */s("div",{className:"alert alert-danger",children:["Error al subir imagen: ",I]}),
506
506
  /* @__PURE__ */l(he,{onSelect:ne,disabled:M,apiKey:e,prod:a})]}:{className:"limbo-empty-state flex flex-col items-center justify-center py-12 px-6 text-center",children:[
507
507
  /* @__PURE__ */l("div",{className:"text-gray-400 mb-4",children:/* @__PURE__ */l("svg",{className:"w-16 h-16 mx-auto",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:/* @__PURE__ */l("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"})})}),
508
508
  /* @__PURE__ */l("p",{className:"text-gray-600 mb-4",children:"Selecciona una imagen de la galería para comenzar a recortar."})]}),
509
- /* @__PURE__ */l(en,{isOpen:T,onClose:A})]})}class on{constructor(e,t,n,r){this.id=e,this.config=t,this.eventManager=n,this.modalManager=r,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=C.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=C.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-instance limbo-component-container-wrapper h-full w-full py-2 bg-white rounded-md","data-limbo-id":this.id,"data-limbo-mode":this.config.mode,"data-limbo-version":"2.0","data-limbo-isolated":"true","aria-label":"Limbo Image Manager",role:"region"},e.createElement(an,{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}))}_createCallbacks(){return{onSelect:e=>{const t=this.config?.callbacks?.onSelect,n=this._createStandardPayload(e,"select");t&&t(n),this.destroyed||this._emitDOMEvent("select",n)},onUpload:e=>{const t=this.config?.callbacks?.onUpload,n=this._createStandardPayload(e,"upload");t&&t(n),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)}}}_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(){if(!(this.config.auth?.apiKey||this.config.auth?.publicKey||this.config.auth?.token||this.config.apiKey||this.config.publicKey||this.config.token))throw new Error(`LimboInstance ${this.id}: Authentication is required. Provide either auth.publicKey (recommended) or auth.apiKey (for server-side only)`);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 ln{constructor(){this.instances=/* @__PURE__ */new Map,this.counter=0}create(e,t,n){const r="limbo-"+ ++this.counter,a=new on(r,e,t,n);return this.instances.set(r,a),a}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 sn{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 Imagen",buttonClass:e.buttonClass||"limbo-auto-button",buttonStyle:e.buttonStyle||"primary",showPreview:!1!==e.showPreview,allowMultiple:e.allowMultiple||!1,autoAssign:!1!==e.autoAssign,...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 r=[this.config.buttonClass];return n.buttonClass&&n.buttonClass!==this.config.buttonClass&&r.push(n.buttonClass),t.className=r.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,r=t.theme||this.config.theme,a=t.compact||this.config.compact,i={border:"none",borderRadius:"8px",cursor:"pointer",fontFamily:"inherit",fontSize:a?"12px":"14px",fontWeight:"500",transition:"all 0.2s ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",padding:a?"6px 12px":"8px 16px",textDecoration:"none",userSelect:"none"},o={primary:{backgroundColor:"dark"===r?"#3b82f6":"#001978",color:"white",hoverBg:"dark"===r?"#2563eb":"#334793"},secondary:{backgroundColor:"dark"===r?"#374151":"#f3f4f6",color:"dark"===r?"#f9fafb":"#374151",border:"1px solid "+("dark"===r?"#4b5563":"#d1d5db"),hoverBg:"dark"===r?"#4b5563":"#e5e7eb"},outline:{backgroundColor:"transparent",color:"dark"===r?"#3b82f6":"#001978",border:"2px solid "+("dark"===r?"#3b82f6":"#001978"),hoverBg:"dark"===r?"#3b82f6":"#001978",hoverColor:"white"},ghost:{backgroundColor:"transparent",color:"dark"===r?"#f9fafb":"#374151",hoverBg:"dark"===r?"#374151":"#f3f4f6"}},l=o[n]||o.primary;Object.assign(e.style,{...i,...l});const s=l.backgroundColor,c=l.color;e.addEventListener("mouseenter",()=>{e.style.backgroundColor=l.hoverBg||l.backgroundColor,l.hoverColor&&(e.style.color=l.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);try{const r=await this._formatImageData(t,n);!1!==n.autoAssign&&(e.value=r),e.dispatchEvent(new Event("change",{bubbles:!0})),e.dispatchEvent(new CustomEvent("limbo:resultReady",{detail:{imageData:t,input:e,value:r,config:n,assignment:{format:n.return,smartAssign:!1!==n.smartAssign,autoAssign:!1!==n.autoAssign},legacy:{imageData:t,formatted:this._createFormattedResult(t,n)}},bubbles:!0})),e.dispatchEvent(new CustomEvent("limbo:imageSelected",{detail:{imageData:t,input:e,value:r,config:n,formatted:this._createFormattedResult(t,n)},bubbles:!0})),this.eventManager.emit("autoInputs:imageSelected",{input:e,imageData:t,value:r,config:n})}catch(r){console.error("Error handling image selection:",r),e.dispatchEvent(new CustomEvent("limbo:error",{detail:{error:r.message,input:e,imageData:t,config:n},bubbles:!0})),this._handleImageSelectionLegacy(e,t)}}_handleImageSelectionLegacy(e,t){const n=this._getInputConfig(e),r=this._formatImageData(t,n);!1!==n.autoAssign&&(e.value=r),e.dispatchEvent(new Event("change",{bubbles:!0})),e.dispatchEvent(new CustomEvent("limbo:imageSelected",{detail:{imageData:t,input:e,value:r,config:n,formatted:this._createFormattedResult(t,n)},bubbles:!0})),this.eventManager.emit("autoInputs:imageSelected",{input:e,imageData:t,value:r,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",r=void 0!==e.original;switch(n){case"url":return r?e.images?.[0]?.url||e.original?.url||"":e.url||e.path||"";case"base64":return e.base64||e.dataUrl||"";case"assetId":return r?e.original?.assetId||"":e.assetId||e.id||"";case"fileName":return e.fileName||e.filename||"";default:return r?JSON.stringify(e):JSON.stringify({original:{url:e.url||e.path,width:e.width,height:e.height,assetId:e.assetId||e.id}})}}_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 imagen",cropper:this._getCropperConfig(e),ui:{showActions:this._getUIActions(e),hideActions:[],showTabs:this._shouldShowTabs(e),theme:e.theme||this.config.theme,compact:e.compact||this.config.compact,showPreview:void 0!==e.showPreview?e.showPreview:this.config.showPreview},validation:{maxSize:e.maxSize||this.config.maxSize,formats:e.formats||this.config.formats,minWidth:e.minWidth||this.config.minWidth,minHeight:e.minHeight||this.config.minHeight,maxWidth:e.maxWidth||this.config.maxWidth,maxHeight:e.maxHeight||this.config.maxHeight,required:e.required||!1},behavior:{allowMultiple:e.allowMultiple||this.config.allowMultiple,closeOnSelect:!0,autoAssign:void 0!==e.autoAssign?e.autoAssign:this.config.autoAssign,allowSelectNew:!1!==e.allowSelectNew},initialImageUrl:e.initialImageUrl||null,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};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 r={"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(r[t])return{...n,aspectRatio:r[t],minCropBoxWidth:e.minWidth||this.config.minWidth,minCropBoxHeight:e.minHeight||this.config.minHeight};if("string"==typeof t&&t.includes(":")){const[e,r]=t.split(":").map(Number);if(!isNaN(e)&&!isNaN(r)&&0!==r)return{...n,aspectRatio:e/r}}const a=parseFloat(t);return!isNaN(a)&&a>0?{...n,aspectRatio:a}:"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 r=[];switch(t){case"gallery-only":case"upload-only":r=["select"];break;case"crop-only":r=["select","crop"];break;default:r=["select"],n.includes("cropper")&&r.push("crop"),n.includes("gallery")&&(r.push("download","copy"),this.config.allowDelete&&r.push("delete"))}return r}_getInputId(e){return e.id||e.name||`limbo-auto-${Date.now()}-${Math.random()}`}_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}},r=(e,t=!1)=>null===e?t:"true"===e||"1"===e||""===e,a=e=>e?parseFloat(e):null,i=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return console.warn("[Limbo AutoInputManager] Error parsing JSON attribute:",t),null}},o=i(e.dataset.mandatorycrops)||i(e.dataset.mandatoryCrops)||i(e.getAttribute("data-mandatory-crops"))||i(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:a(e.dataset.quality)||a(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:r(e.dataset.compact,null)??r(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:a(e.getAttribute("data-limbo-min-width"))||this.config.minWidth,minHeight:a(e.getAttribute("data-limbo-min-height"))||this.config.minHeight,maxWidth:a(e.getAttribute("data-limbo-max-width"))||this.config.maxWidth,maxHeight:a(e.getAttribute("data-limbo-max-height"))||this.config.maxHeight,buttonText:e.getAttribute("data-limbo-button-text")||this.config.buttonText,buttonStyle:e.getAttribute("data-limbo-button-style")||this.config.buttonStyle,buttonClass:e.getAttribute("data-limbo-button-class")||this.config.buttonClass,showPreview:r(e.getAttribute("data-limbo-show-preview"),this.config.showPreview),allowMultiple:r(e.getAttribute("data-limbo-allow-multiple"),this.config.allowMultiple),autoAssign:r(e.getAttribute("data-limbo-auto-assign"),this.config.autoAssign),placeholder:e.getAttribute("data-limbo-placeholder"),description:e.getAttribute("data-limbo-description"),required:r(e.getAttribute("data-limbo-required"),!1),disabled:r(e.getAttribute("data-limbo-disabled"),!1),inputId:e.id||e.name||this._generateInputId(e),inputName:e.name,inputType:e.type,mandatoryCrops:o,allowAdditionalCrops:r(e.getAttribute("data-limbo-allow-additional-crops"),!0),maxCrops:a(e.getAttribute("data-limbo-max-crops"))||null,allowSelectNew:r(e.dataset.allowselectnew,null)??r(e.getAttribute("data-limbo-allow-select-new"),!0),initialImageUrl:e.value||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 cn{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(r){console.error(`Error executing listener for ${e}:`,r)}})}getStats(){const e={};return this.listeners.forEach((t,n)=>{e[n]=t.length}),e}}class un{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 dn(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)}_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 r=n[0],a=n[n.length-1];e.shiftKey?document.activeElement===r&&(e.preventDefault(),a.focus()):document.activeElement===a&&(e.preventDefault(),r.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 dn{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-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,r=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=r,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 mn{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 r=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,r),!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 r=n.getAttribute("data-theme")||n.getAttribute("class")?.match(/theme-(\w+)/)||n.getAttribute("class")?.match(/(\w+)-theme/);r&&(e.detectedName=Array.isArray(r)?r[1]:r)}}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 r=`--limbo-${e}`,a=n.getPropertyValue(r).trim();a&&(t[r]=a)});return["--primary-color","--background-color","--text-color","--border-color","--accent-color","--surface-color"].forEach(e=>{const r=n.getPropertyValue(e).trim();if(r){const n=this._mapGenericToLimbo(e,r);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 r=document.querySelector('meta[name="theme-color"]');r||(r=document.createElement("meta"),r.name="theme-color",document.head.appendChild(r)),r.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(r){console.error("Error in theme change callback:",r)}})}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 r=this._getTheme(this.config.inheritance.fallbackTheme);return r&&(n.variables={...r.variables,...n.variables}),this.registerTheme(e,n),n}_darkenColor(e,t){const n=parseInt(e.replace("#",""),16),r=Math.round(2.55*t),a=(n>>16)-r,i=(n>>8&255)-r,o=(255&n)-r;return"#"+(16777216+65536*(a<255?a<1?0:a:255)+256*(i<255?i<1?0:i:255)+(o<255?o<1?0:o:255)).toString(16).slice(1)}_lightenColor(e,t){const n=parseInt(e.replace("#",""),16),r=Math.round(2.55*t),a=(n>>16)+r,i=(n>>8&255)+r,o=(255&n)+r;return"#"+(16777216+65536*(a<255?a<1?0:a:255)+256*(i<255?i<1?0:i:255)+(o<255?o<1?0:o:255)).toString(16).slice(1)}_deepMerge(e,t){const n={...e};return Object.keys(t).forEach(r=>{t[r]&&"object"==typeof t[r]&&!Array.isArray(t[r])?n[r]=this._deepMerge(e[r]||{},t[r]):n[r]=t[r]}),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 hn=new class{constructor(){this.config=new m,this.instances=new ln,this.autoInputs=new sn,this.events=new cn,this.modals=new un,this.theme=new mn,this.containerQueryDetector=S,this._setupInternalListeners(),this._initializeContainerQueries()}configure(e){var t;return this.config.setGlobal(e),t={publicKey:e.publicKey,apiKey:e.apiKey,token:e.token,authMode:e.authMode||"manual",tokenProvider:e.tokenProvider,prod: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 function(e){z.token=e}(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}]`,r=document.querySelectorAll(n);if(0===r.length)return{found:0,processed:0,skipped:0};let a=0,i=0;return r.forEach(e=>{try{this.autoInputs._processInput(e),a++}catch(t){console.warn(`⚠️ Limbo: Error procesando input ${e.id||e.name}:`,t),i++}}),this.events.emit("limbo:scanCompleted",{found:r.length,processed:a,skipped:i,inputs:Array.from(r)}),{found:r.length,processed:a,skipped:i}}_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 r=0;return n.forEach(e=>{if(!this.autoInputs.instances.has(this.autoInputs._getInputId(e)))try{this.autoInputs._processInput(e),r++}catch(t){console.warn("⚠️ Limbo: Error procesando nuevo input:",t)}}),r}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})=>{this._handleAutoInputModalRequest({config:e,callback:t})})}_handleAutoInputModalRequest({config:e,callback:t}){const n=e=>{let n={};if(e.crops&&e.crops.length>0){const t=e.asset||e.original;n.original={url:t?.url||t?.urlSigned||e.originalUrl,width:t?.width||e.originalWidth,height:t?.height||e.originalHeight,assetId:t?.id||e.assetId},n.images=e.crops.map(e=>({url:e.url||e.urlSigned,width:e.width,height:e.height,name:e.name||e.filename}))}else e.asset?n.original={url:e.asset.url||e.asset.urlSigned,width:e.asset.width,height:e.asset.height,assetId:e.asset.id}:e.master?.urlSigned||e.master?.url?n.original={url:e.master.urlSigned||e.master.url,width:e.master.width||e.width,height:e.master.height||e.height,assetId:e.assetId}:e.url||e.urlSigned?n.original={url:e.url||e.urlSigned,width:e.width,height:e.height,assetId:e.assetId||e.id}:(console.warn("[Limbo] handleResult: formato de datos no reconocido",e),n=e);t(n),a.close()},r={...e,mode:"modal",autoDestroy:!0,interaction:{allowSelection:!0,allowCropping:!0,...e.interaction},callbacks:{onSelect:e=>{n(e)},onCropsSaved:e=>{n(e)},onCropperComplete:e=>{n(e)},onUpload:t=>{"upload-only"!==e.modeUI||e.features?.includes("cropper")||n(t)},onClose:()=>{}}};if(e.initialImageUrl){const t=this._extractAssetIdFromUrl(e.initialImageUrl);r._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&&(r.cropper=e.cropper),this.config.setGlobal({interaction:{allowSelection:!0,allowCropping:!0,...e.interaction}});const a=this.create(r);a.open()}_extractAssetIdFromUrl(e){if(!e)return null;try{const t=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,n=e.match(t);return n&&n.length>=2?n[1]:n&&1===n.length?n[0]:null}catch(t){return console.warn("Error extracting asset ID from URL:",t),null}}openGallery(e={}){const t=this.create({mode:"modal",modeUI:"gallery-only",features:["gallery"],autoDestroy:!0,modal:{title:e.title||"Seleccionar Imagen",size:e.size||"large"},callbacks:{onSelect:n=>{e.onSelect?.(n),!1!==e.autoClose&&t.close()}},...e});return t.open(),t}openUploader(e={}){const t=!1!==e.redirectToGallery?["upload","gallery"]:["upload"],n=this.create({mode:"modal",modeUI:!1!==e.redirectToGallery?"full":"upload-only",features:t,autoDestroy:!0,modal:{title:e.title||"Subir Imagen",size:e.size||"medium"},callbacks:{onUpload:t=>{e.onUpload?.(t),!1===e.autoClose||e.redirectToGallery||n.close()}},...e});return n.open(),n}openCropper(e,t={}){if(!e)throw new Error("Limbo.openCropper: imageUrl es requerido");const n={url:e,filename:t.filename||"image.jpg",width:t.width||1920,height:t.height||1080,mime_type:t.mimeType||"image/jpeg",id:t.assetId||`external-${Date.now()}`},r=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&&r.close()},onCropperCancelled:e=>{t.onCancelled?.(e),!1!==t.autoClose&&r.close()},onCropperError:e=>{t.onError?.(e)}},_externalImage:n,...t});return r.open(),r}createInlineGallery(e,t={}){return this.create({container:e,mode:"embed",modeUI:"gallery-only",features:["gallery"],callbacks:{onSelect:t.onSelect,onDelete:t.onDelete},...t})}createInlineUploader(e,t={}){return this.create({container:e,mode:"embed",modeUI:"upload-only",features:["upload"],callbacks:{onUpload:t.onUpload},...t})}createStandaloneCropper(e,t,n={}){if(!e)throw new Error("Limbo.createStandaloneCropper: container es requerido");if(!t)throw new Error("Limbo.createStandaloneCropper: imageUrl es requerido");const r={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:r,...n})}createFullSelector(e,t={}){return this.create({container:e,mode:t.mode||"embed",modeUI:"full",features:["gallery","upload","cropper"],callbacks:{onSelect:t.onSelect,onUpload:t.onUpload,onDelete:t.onDelete,onCropsSaved:t.onCropsSaved},...t})}};"undefined"!=typeof window&&(window.Limbo=hn,window.limboCore=hn);"undefined"!=typeof window&&document.querySelector("#root")&&(hn.configure({prod:!1,publicKey:"pk_e464fd744106b7a8d63d453c4bd02582",authMode:"session"}),hn.create({container:"#root",mode:"embed",modeUI:"full",features:["gallery","upload","cropper"],title:"Limbo Image Manager - Development",url:!0}),hn.configureAutoInputs({dataset:"data-limbo-input-file",return:"json",features:["gallery","upload","cropper"],modeUI:"full",modalSize:"large",title:"Seleccionar imagen",crops:"free",allowDelete:!1}));export{hn as default};
509
+ /* @__PURE__ */l(en,{isOpen:T,onClose:A})]})}class on{constructor(e,t,n,r){this.id=e,this.config=t,this.eventManager=n,this.modalManager=r,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=C.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=C.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-instance limbo-component-container-wrapper h-full w-full py-2 bg-white rounded-md","data-limbo-id":this.id,"data-limbo-mode":this.config.mode,"data-limbo-version":"2.0","data-limbo-isolated":"true","aria-label":"Limbo Image Manager",role:"region"},e.createElement(an,{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}))}_createCallbacks(){return{onSelect:e=>{const t=this.config?.callbacks?.onSelect,n=this._createStandardPayload(e,"select");t&&t(n),this.destroyed||this._emitDOMEvent("select",n)},onUpload:e=>{const t=this.config?.callbacks?.onUpload,n=this._createStandardPayload(e,"upload");t&&t(n),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)}}}_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(){if(!(this.config.auth?.apiKey||this.config.auth?.publicKey||this.config.auth?.token||this.config.apiKey||this.config.publicKey||this.config.token))throw new Error(`LimboInstance ${this.id}: Authentication is required. Provide either auth.publicKey (recommended) or auth.apiKey (for server-side only)`);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 ln{constructor(){this.instances=/* @__PURE__ */new Map,this.counter=0}create(e,t,n){const r="limbo-"+ ++this.counter,a=new on(r,e,t,n);return this.instances.set(r,a),a}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 sn{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 Imagen",buttonClass:e.buttonClass||"limbo-auto-button",buttonStyle:e.buttonStyle||"primary",showPreview:!1!==e.showPreview,allowMultiple:e.allowMultiple||!1,autoAssign:!1!==e.autoAssign,...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 r=[this.config.buttonClass];return n.buttonClass&&n.buttonClass!==this.config.buttonClass&&r.push(n.buttonClass),t.className=r.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,r=t.theme||this.config.theme,a=t.compact||this.config.compact,i={border:"none",borderRadius:"8px",cursor:"pointer",fontFamily:"inherit",fontSize:a?"12px":"14px",fontWeight:"500",transition:"all 0.2s ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",padding:a?"6px 12px":"8px 16px",textDecoration:"none",userSelect:"none"},o={primary:{backgroundColor:"dark"===r?"#3b82f6":"#001978",color:"white",hoverBg:"dark"===r?"#2563eb":"#334793"},secondary:{backgroundColor:"dark"===r?"#374151":"#f3f4f6",color:"dark"===r?"#f9fafb":"#374151",border:"1px solid "+("dark"===r?"#4b5563":"#d1d5db"),hoverBg:"dark"===r?"#4b5563":"#e5e7eb"},outline:{backgroundColor:"transparent",color:"dark"===r?"#3b82f6":"#001978",border:"2px solid "+("dark"===r?"#3b82f6":"#001978"),hoverBg:"dark"===r?"#3b82f6":"#001978",hoverColor:"white"},ghost:{backgroundColor:"transparent",color:"dark"===r?"#f9fafb":"#374151",hoverBg:"dark"===r?"#374151":"#f3f4f6"}},l=o[n]||o.primary;Object.assign(e.style,{...i,...l});const s=l.backgroundColor,c=l.color;e.addEventListener("mouseenter",()=>{e.style.backgroundColor=l.hoverBg||l.backgroundColor,l.hoverColor&&(e.style.color=l.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);try{const r=await this._formatImageData(t,n);!1!==n.autoAssign&&(e.value=r),e.dispatchEvent(new Event("change",{bubbles:!0})),e.dispatchEvent(new CustomEvent("limbo:resultReady",{detail:{imageData:t,input:e,value:r,config:n,assignment:{format:n.return,smartAssign:!1!==n.smartAssign,autoAssign:!1!==n.autoAssign},legacy:{imageData:t,formatted:this._createFormattedResult(t,n)}},bubbles:!0})),e.dispatchEvent(new CustomEvent("limbo:imageSelected",{detail:{imageData:t,input:e,value:r,config:n,formatted:this._createFormattedResult(t,n)},bubbles:!0})),this.eventManager.emit("autoInputs:imageSelected",{input:e,imageData:t,value:r,config:n})}catch(r){console.error("Error handling image selection:",r),e.dispatchEvent(new CustomEvent("limbo:error",{detail:{error:r.message,input:e,imageData:t,config:n},bubbles:!0})),this._handleImageSelectionLegacy(e,t)}}_handleImageSelectionLegacy(e,t){const n=this._getInputConfig(e),r=this._formatImageData(t,n);!1!==n.autoAssign&&(e.value=r),e.dispatchEvent(new Event("change",{bubbles:!0})),e.dispatchEvent(new CustomEvent("limbo:imageSelected",{detail:{imageData:t,input:e,value:r,config:n,formatted:this._createFormattedResult(t,n)},bubbles:!0})),this.eventManager.emit("autoInputs:imageSelected",{input:e,imageData:t,value:r,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",r=void 0!==e.original;switch(n){case"url":return r?e.images?.[0]?.url||e.original?.url||"":e.url||e.path||"";case"base64":return e.base64||e.dataUrl||"";case"assetId":return r?e.original?.assetId||"":e.assetId||e.id||"";case"fileName":return e.fileName||e.filename||"";default:return r?JSON.stringify(e):JSON.stringify({original:{url:e.url||e.path,width:e.width,height:e.height,assetId:e.assetId||e.id}})}}_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 imagen",cropper:this._getCropperConfig(e),ui:{showActions:this._getUIActions(e),hideActions:[],showTabs:this._shouldShowTabs(e),theme:e.theme||this.config.theme,compact:e.compact||this.config.compact,showPreview:void 0!==e.showPreview?e.showPreview:this.config.showPreview},validation:{maxSize:e.maxSize||this.config.maxSize,formats:e.formats||this.config.formats,minWidth:e.minWidth||this.config.minWidth,minHeight:e.minHeight||this.config.minHeight,maxWidth:e.maxWidth||this.config.maxWidth,maxHeight:e.maxHeight||this.config.maxHeight,required:e.required||!1},behavior:{allowMultiple:e.allowMultiple||this.config.allowMultiple,closeOnSelect:!0,autoAssign:void 0!==e.autoAssign?e.autoAssign:this.config.autoAssign,allowSelectNew:!1!==e.allowSelectNew},initialImageUrl:e.initialImageUrl||null,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};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 r={"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(r[t])return{...n,aspectRatio:r[t],minCropBoxWidth:e.minWidth||this.config.minWidth,minCropBoxHeight:e.minHeight||this.config.minHeight};if("string"==typeof t&&t.includes(":")){const[e,r]=t.split(":").map(Number);if(!isNaN(e)&&!isNaN(r)&&0!==r)return{...n,aspectRatio:e/r}}const a=parseFloat(t);return!isNaN(a)&&a>0?{...n,aspectRatio:a}:"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 r=[];switch(t){case"gallery-only":case"upload-only":r=["select"];break;case"crop-only":r=["select","crop"];break;default:r=["select"],n.includes("cropper")&&r.push("crop"),n.includes("gallery")&&(r.push("download","copy"),this.config.allowDelete&&r.push("delete"))}return r}_getInputId(e){return e.id||e.name||`limbo-auto-${Date.now()}-${Math.random()}`}_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}},r=(e,t=!1)=>null===e?t:"true"===e||"1"===e||""===e,a=e=>e?parseFloat(e):null,i=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return console.warn("[Limbo AutoInputManager] Error parsing JSON attribute:",t),null}},o=i(e.dataset.mandatorycrops)||i(e.dataset.mandatoryCrops)||i(e.getAttribute("data-mandatory-crops"))||i(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:a(e.dataset.quality)||a(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:r(e.dataset.compact,null)??r(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:a(e.getAttribute("data-limbo-min-width"))||this.config.minWidth,minHeight:a(e.getAttribute("data-limbo-min-height"))||this.config.minHeight,maxWidth:a(e.getAttribute("data-limbo-max-width"))||this.config.maxWidth,maxHeight:a(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:r(e.getAttribute("data-limbo-show-preview"),this.config.showPreview),allowMultiple:r(e.getAttribute("data-limbo-allow-multiple"),this.config.allowMultiple),autoAssign:r(e.getAttribute("data-limbo-auto-assign"),this.config.autoAssign),placeholder:e.getAttribute("data-limbo-placeholder"),description:e.getAttribute("data-limbo-description"),required:r(e.getAttribute("data-limbo-required"),!1),disabled:r(e.getAttribute("data-limbo-disabled"),!1),inputId:e.id||e.name||this._generateInputId(e),inputName:e.name,inputType:e.type,mandatoryCrops:o,allowAdditionalCrops:r(e.dataset.allowadditionalcrops,null)??r(e.getAttribute("data-limbo-allow-additional-crops"),!0),maxCrops:a(e.dataset.maxcrops)||a(e.getAttribute("data-limbo-max-crops"))||null,allowSelectNew:r(e.dataset.allowselectnew,null)??r(e.getAttribute("data-limbo-allow-select-new"),!0),initialImageUrl:e.value||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 cn{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(r){console.error(`Error executing listener for ${e}:`,r)}})}getStats(){const e={};return this.listeners.forEach((t,n)=>{e[n]=t.length}),e}}class un{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 dn(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)}_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 r=n[0],a=n[n.length-1];e.shiftKey?document.activeElement===r&&(e.preventDefault(),a.focus()):document.activeElement===a&&(e.preventDefault(),r.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 dn{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-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,r=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=r,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 mn{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 r=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,r),!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 r=n.getAttribute("data-theme")||n.getAttribute("class")?.match(/theme-(\w+)/)||n.getAttribute("class")?.match(/(\w+)-theme/);r&&(e.detectedName=Array.isArray(r)?r[1]:r)}}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 r=`--limbo-${e}`,a=n.getPropertyValue(r).trim();a&&(t[r]=a)});return["--primary-color","--background-color","--text-color","--border-color","--accent-color","--surface-color"].forEach(e=>{const r=n.getPropertyValue(e).trim();if(r){const n=this._mapGenericToLimbo(e,r);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 r=document.querySelector('meta[name="theme-color"]');r||(r=document.createElement("meta"),r.name="theme-color",document.head.appendChild(r)),r.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(r){console.error("Error in theme change callback:",r)}})}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 r=this._getTheme(this.config.inheritance.fallbackTheme);return r&&(n.variables={...r.variables,...n.variables}),this.registerTheme(e,n),n}_darkenColor(e,t){const n=parseInt(e.replace("#",""),16),r=Math.round(2.55*t),a=(n>>16)-r,i=(n>>8&255)-r,o=(255&n)-r;return"#"+(16777216+65536*(a<255?a<1?0:a:255)+256*(i<255?i<1?0:i:255)+(o<255?o<1?0:o:255)).toString(16).slice(1)}_lightenColor(e,t){const n=parseInt(e.replace("#",""),16),r=Math.round(2.55*t),a=(n>>16)+r,i=(n>>8&255)+r,o=(255&n)+r;return"#"+(16777216+65536*(a<255?a<1?0:a:255)+256*(i<255?i<1?0:i:255)+(o<255?o<1?0:o:255)).toString(16).slice(1)}_deepMerge(e,t){const n={...e};return Object.keys(t).forEach(r=>{t[r]&&"object"==typeof t[r]&&!Array.isArray(t[r])?n[r]=this._deepMerge(e[r]||{},t[r]):n[r]=t[r]}),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 hn=new class{constructor(){this.config=new m,this.instances=new ln,this.autoInputs=new sn,this.events=new cn,this.modals=new un,this.theme=new mn,this.containerQueryDetector=S,this._setupInternalListeners(),this._initializeContainerQueries()}configure(e){var t;return this.config.setGlobal(e),t={publicKey:e.publicKey,apiKey:e.apiKey,token:e.token,authMode:e.authMode||"manual",tokenProvider:e.tokenProvider,prod: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 function(e){z.token=e}(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}]`,r=document.querySelectorAll(n);if(0===r.length)return{found:0,processed:0,skipped:0};let a=0,i=0;return r.forEach(e=>{try{this.autoInputs._processInput(e),a++}catch(t){console.warn(`⚠️ Limbo: Error procesando input ${e.id||e.name}:`,t),i++}}),this.events.emit("limbo:scanCompleted",{found:r.length,processed:a,skipped:i,inputs:Array.from(r)}),{found:r.length,processed:a,skipped:i}}_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 r=0;return n.forEach(e=>{if(!this.autoInputs.instances.has(this.autoInputs._getInputId(e)))try{this.autoInputs._processInput(e),r++}catch(t){console.warn("⚠️ Limbo: Error procesando nuevo input:",t)}}),r}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})=>{this._handleAutoInputModalRequest({config:e,callback:t})})}_handleAutoInputModalRequest({config:e,callback:t}){const n=e=>{let n={};if(e.crops&&e.crops.length>0){const t=e.asset||e.original;n.original={url:t?.url||t?.urlSigned||e.originalUrl,width:t?.width||e.originalWidth,height:t?.height||e.originalHeight,assetId:t?.id||e.assetId},n.images=e.crops.map(e=>({url:e.url||e.urlSigned,width:e.width,height:e.height,name:e.name||e.filename}))}else e.asset?n.original={url:e.asset.url||e.asset.urlSigned,width:e.asset.width,height:e.asset.height,assetId:e.asset.id}:e.master?.urlSigned||e.master?.url?n.original={url:e.master.urlSigned||e.master.url,width:e.master.width||e.width,height:e.master.height||e.height,assetId:e.assetId}:e.url||e.urlSigned?n.original={url:e.url||e.urlSigned,width:e.width,height:e.height,assetId:e.assetId||e.id}:(console.warn("[Limbo] handleResult: formato de datos no reconocido",e),n=e);t(n),a.close()},r={...e,mode:"modal",autoDestroy:!0,interaction:{allowSelection:!0,allowCropping:!0,...e.interaction},callbacks:{onSelect:e=>{n(e)},onCropsSaved:e=>{n(e)},onCropperComplete:e=>{n(e)},onUpload:t=>{"upload-only"!==e.modeUI||e.features?.includes("cropper")||n(t)},onClose:()=>{}}};if(e.initialImageUrl){const t=this._extractAssetIdFromUrl(e.initialImageUrl);r._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&&(r.cropper=e.cropper),this.config.setGlobal({interaction:{allowSelection:!0,allowCropping:!0,...e.interaction}});const a=this.create(r);a.open()}_extractAssetIdFromUrl(e){if(!e)return null;try{const t=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,n=e.match(t);return n&&n.length>=2?n[1]:n&&1===n.length?n[0]:null}catch(t){return console.warn("Error extracting asset ID from URL:",t),null}}openGallery(e={}){const t=this.create({mode:"modal",modeUI:"gallery-only",features:["gallery"],autoDestroy:!0,modal:{title:e.title||"Seleccionar Imagen",size:e.size||"large"},callbacks:{onSelect:n=>{e.onSelect?.(n),!1!==e.autoClose&&t.close()}},...e});return t.open(),t}openUploader(e={}){const t=!1!==e.redirectToGallery?["upload","gallery"]:["upload"],n=this.create({mode:"modal",modeUI:!1!==e.redirectToGallery?"full":"upload-only",features:t,autoDestroy:!0,modal:{title:e.title||"Subir Imagen",size:e.size||"medium"},callbacks:{onUpload:t=>{e.onUpload?.(t),!1===e.autoClose||e.redirectToGallery||n.close()}},...e});return n.open(),n}openCropper(e,t={}){if(!e)throw new Error("Limbo.openCropper: imageUrl es requerido");const n={url:e,filename:t.filename||"image.jpg",width:t.width||1920,height:t.height||1080,mime_type:t.mimeType||"image/jpeg",id:t.assetId||`external-${Date.now()}`},r=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&&r.close()},onCropperCancelled:e=>{t.onCancelled?.(e),!1!==t.autoClose&&r.close()},onCropperError:e=>{t.onError?.(e)}},_externalImage:n,...t});return r.open(),r}createInlineGallery(e,t={}){return this.create({container:e,mode:"embed",modeUI:"gallery-only",features:["gallery"],callbacks:{onSelect:t.onSelect,onDelete:t.onDelete},...t})}createInlineUploader(e,t={}){return this.create({container:e,mode:"embed",modeUI:"upload-only",features:["upload"],callbacks:{onUpload:t.onUpload},...t})}createStandaloneCropper(e,t,n={}){if(!e)throw new Error("Limbo.createStandaloneCropper: container es requerido");if(!t)throw new Error("Limbo.createStandaloneCropper: imageUrl es requerido");const r={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:r,...n})}createFullSelector(e,t={}){return this.create({container:e,mode:t.mode||"embed",modeUI:"full",features:["gallery","upload","cropper"],callbacks:{onSelect:t.onSelect,onUpload:t.onUpload,onDelete:t.onDelete,onCropsSaved:t.onCropsSaved},...t})}};"undefined"!=typeof window&&(window.Limbo=hn,window.limboCore=hn);"undefined"!=typeof window&&document.querySelector("#root")&&(hn.configure({prod:!1,publicKey:"pk_e464fd744106b7a8d63d453c4bd02582",authMode:"session"}),hn.create({container:"#root",mode:"embed",modeUI:"full",features:["gallery","upload","cropper"],title:"Limbo Image Manager - Development",url:!0}),hn.configureAutoInputs({dataset:"data-limbo-input-file",return:"json",features:["gallery","upload","cropper"],modeUI:"full",modalSize:"large",title:"Seleccionar imagen",crops:"free",allowDelete:!1}));export{hn as default};
510
510
  //# sourceMappingURL=limbo.es.map