limbo-component 1.6.1 → 1.6.3

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.umd.js CHANGED
@@ -52,7 +52,7 @@
52
52
  *
53
53
  * This source code is licensed under the MIT license found in the
54
54
  * LICENSE file in the root directory of this source tree.
55
- */function q(){return W||(W=1,"production"!==process.env.NODE_ENV&&function(){function e(t){if(null==t)return null;if("function"==typeof t)return t.$$typeof===C?null:t.displayName||t.name||null;if("string"==typeof t)return t;switch(t){case p:return"Fragment";case m:return"Profiler";case h:return"StrictMode";case v:return"Suspense";case w:return"SuspenseList";case S:return"Activity"}if("object"==typeof t)switch("number"==typeof t.tag&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),t.$$typeof){case d:return"Portal";case b:return(t.displayName||"Context")+".Provider";case g:return(t._context.displayName||"Context")+".Consumer";case y:var n=t.render;return(t=t.displayName)||(t=""!==(t=n.displayName||n.name||"")?"ForwardRef("+t+")":"ForwardRef"),t;case k:return null!==(n=t.displayName||null)?n:e(t.type)||"Memo";case x:n=t._payload,t=t._init;try{return e(t(n))}catch(r){}}return null}function t(e){return""+e}function n(e){try{t(e);var n=!1}catch(o){n=!0}if(n){var r=(n=console).error,a="function"==typeof Symbol&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return r.call(n,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",a),t(e)}}function r(t){if(t===p)return"<>";if("object"==typeof t&&null!==t&&t.$$typeof===x)return"<...>";try{var n=e(t);return n?"<"+n+">":"<...>"}catch(r){return"<...>"}}function a(){return Error("react-stack-top-frame")}function o(){var t=e(this.type);return P[t]||(P[t]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),void 0!==(t=this.props.ref)?t:null}function i(t,r,a,i,c,d,f,p){var h,m=r.children;if(void 0!==m)if(i)if(T(m)){for(i=0;i<m.length;i++)l(m[i]);Object.freeze&&Object.freeze(m)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else l(m);if(_.call(r,"key")){m=e(t);var g=Object.keys(r).filter(function(e){return"key"!==e});i=0<g.length?"{key: someKey, "+g.join(": ..., ")+": ...}":"{key: someKey}",j[m+i]||(g=0<g.length?"{"+g.join(": ..., ")+": ...}":"{}",console.error('A props object containing a "key" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />',i,m,g,m),j[m+i]=!0)}if(m=null,void 0!==a&&(n(a),m=""+a),function(e){if(_.call(e,"key")){var t=Object.getOwnPropertyDescriptor(e,"key").get;if(t&&t.isReactWarning)return!1}return void 0!==e.key}(r)&&(n(r.key),m=""+r.key),"key"in r)for(var b in a={},r)"key"!==b&&(a[b]=r[b]);else a=r;return m&&function(e,t){function n(){s||(s=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",t))}n.isReactWarning=!0,Object.defineProperty(e,"key",{get:n,configurable:!0})}(a,"function"==typeof t?t.displayName||t.name||"Unknown":t),function(e,t,n,r,a,i,l,s){return n=i.ref,e={$$typeof:u,type:e,key:t,props:i,_owner:a},null!==(void 0!==n?n:null)?Object.defineProperty(e,"ref",{enumerable:!1,get:o}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:l}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:s}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}(t,m,d,0,null===(h=E.A)?null:h.getOwner(),a,f,p)}function l(e){"object"==typeof e&&null!==e&&e.$$typeof===u&&e._store&&(e._store.validated=1)}var s,c=f(),u=Symbol.for("react.transitional.element"),d=Symbol.for("react.portal"),p=Symbol.for("react.fragment"),h=Symbol.for("react.strict_mode"),m=Symbol.for("react.profiler"),g=Symbol.for("react.consumer"),b=Symbol.for("react.context"),y=Symbol.for("react.forward_ref"),v=Symbol.for("react.suspense"),w=Symbol.for("react.suspense_list"),k=Symbol.for("react.memo"),x=Symbol.for("react.lazy"),S=Symbol.for("react.activity"),C=Symbol.for("react.client.reference"),E=c.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,_=Object.prototype.hasOwnProperty,T=Array.isArray,N=console.createTask?console.createTask:function(){return null},P={},R=(c={react_stack_bottom_frame:function(e){return e()}}).react_stack_bottom_frame.bind(c,a)(),z=N(r(a)),j={};V.Fragment=p,V.jsx=function(e,t,n,a,o){var l=1e4>E.recentlyCreatedOwnerStacks++;return i(e,t,n,!1,0,o,l?Error("react-stack-top-frame"):R,l?N(r(e)):z)},V.jsxs=function(e,t,n,a,o){var l=1e4>E.recentlyCreatedOwnerStacks++;return i(e,t,n,!0,0,o,l?Error("react-stack-top-frame"):R,l?N(r(e)):z)}}()),V}var K=(B||(B=1,"production"===process.env.NODE_ENV?U.exports=function(){if($)return H;$=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(t,n,r){var a=null;if(void 0!==r&&(a=""+r),void 0!==n.key&&(a=""+n.key),"key"in n)for(var o in r={},n)"key"!==o&&(r[o]=n[o]);else r=n;return n=r.ref,{$$typeof:e,type:t,key:a,ref:void 0!==n?n:null,props:r}}return H.Fragment=t,H.jsx=n,H.jsxs=n,H}():U.exports=q()),U.exports);const Q=new class{constructor(){this.supportsContainerQueries=this.detectContainerQueries(),this.init()}detectContainerQueries(){if("undefined"==typeof window)return!1;try{if("CSS"in window&&"supports"in window.CSS)return window.CSS.supports("container-type","inline-size");const e=document.createElement("div");return e.style.containerType="inline-size","inline-size"===e.style.containerType}catch{return!1}}init(){"undefined"!=typeof window&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>this.applyClasses()):this.applyClasses())}applyClasses(){document.querySelectorAll(".limbo-component-container-wrapper").forEach(e=>{this.supportsContainerQueries?(e.classList.add("container-queries-supported"),e.classList.remove("container-queries-fallback")):(e.classList.add("container-queries-fallback"),e.classList.remove("container-queries-supported"))}),this.supportsContainerQueries?(document.body.classList.add("container-queries-supported"),document.body.classList.remove("container-queries-fallback")):(document.body.classList.add("container-queries-fallback"),document.body.classList.remove("container-queries-supported"))}getContainerWidth(e){if(!e)return window.innerWidth;let t=e.closest(".limbo-component-container-wrapper");return t||(t=e.closest(".limbo-modal-content")),t||(t=e.closest(".limbo-modal")),t||(t=document.body),t.offsetWidth||t.clientWidth}shouldUseMobileStyles(e,t=768){return this.getContainerWidth(e)<=t}applyResponsiveClasses(e){if(this.supportsContainerQueries)return;const t=this.shouldUseMobileStyles(e),n=this.shouldUseMobileStyles(e,1024)&&!t;e.classList.toggle("limbo-mobile-fallback",t),e.classList.toggle("limbo-tablet-fallback",n),e.classList.toggle("limbo-desktop-fallback",!t&&!n)}observeResize(){if(!this.supportsContainerQueries)if("ResizeObserver"in window){const e=new ResizeObserver(e=>{e.forEach(e=>{this.applyResponsiveClasses(e.target)})});document.querySelectorAll(".limbo-component-container-wrapper").forEach(t=>{e.observe(t)})}else window.addEventListener("resize",()=>{document.querySelectorAll(".limbo-component-container-wrapper").forEach(e=>{this.applyResponsiveClasses(e)})})}};function Y(e={}){const{useContainerQuery:t=!1,containerElement:n=null}=e,[r,a]=p.useState(()=>{const e=t&&n?Q.getContainerWidth(n):"undefined"!=typeof window?window.innerWidth:0,r="undefined"!=typeof window&&(e<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)),a="undefined"!=typeof window&&("ontouchstart"in window||navigator.maxTouchPoints>0);return{isMobile:r,isTouch:a,isTablet:"undefined"!=typeof window&&(e>768&&e<=1024&&a),orientation:"undefined"!=typeof window?window.innerHeight>window.innerWidth?"portrait":"landscape":"portrait",viewport:{width:"undefined"!=typeof window?window.innerWidth:0,height:"undefined"!=typeof window?window.innerHeight:0},container:{width:e,supportsContainerQueries:Q.supportsContainerQueries}}});p.useEffect(()=>{if("undefined"==typeof window)return;const e=()=>{const e=window.innerWidth,r=window.innerHeight,o=t&&n?Q.getContainerWidth(n):e,i=o<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),l="ontouchstart"in window||navigator.maxTouchPoints>0;a({isMobile:i,isTouch:l,isTablet:o>768&&o<=1024&&l,orientation:r>e?"portrait":"landscape",viewport:{width:e,height:r},container:{width:o,supportsContainerQueries:Q.supportsContainerQueries}})};let r;const o=()=>{clearTimeout(r),r=setTimeout(e,150)};return window.addEventListener("resize",o),window.addEventListener("orientationchange",()=>{setTimeout(e,100)}),()=>{clearTimeout(r),window.removeEventListener("resize",o),window.removeEventListener("orientationchange",e)}},[t,n]);const o="portrait"===r.orientation,i="landscape"===r.orientation,l=r.isMobile||r.isTablet&&o;return{...r,isPortrait:o,isLandscape:i,isCompactMode:l,isMobileSize:r.viewport.width<=640,isTabletSize:r.viewport.width>640&&r.viewport.width<=1024,isDesktopSize:r.viewport.width>1024,deviceClass:r.isMobile?"mobile":r.isTablet?"tablet":"desktop"}}function G({tabs:e,active:t,onChange:n}){const{isMobile:r,isTouch:a}=Y();return K.jsx("div",{className:"limbo-tabs "+(r?"limbo-tabs--mobile":""),role:"tablist","aria-label":"Opciones de navegación",style:{...r&&{overflowX:"auto",WebkitOverflowScrolling:"touch",scrollbarWidth:"none",msOverflowStyle:"none"}},children:e.map(o=>{const i=t===o.id;return!i&&o.hideNonActive?null:K.jsx("button",{"data-tab-id":o.id,onClick:()=>n(o.id),onKeyDown:t=>((t,r)=>{const a=e.findIndex(e=>e.id===r);let o=a;switch(t.key){case"ArrowLeft":case"ArrowUp":t.preventDefault(),o=a>0?a-1:e.length-1;break;case"ArrowRight":case"ArrowDown":t.preventDefault(),o=a<e.length-1?a+1:0;break;case"Home":t.preventDefault(),o=0;break;case"End":t.preventDefault(),o=e.length-1;break;case"Enter":case" ":return t.preventDefault(),void n(r);default:return}const i=e[o];i&&!i.hideNonActive&&(n(i.id),setTimeout(()=>{const e=document.querySelector(`[data-tab-id="${i.id}"]`);e&&e.focus()},0))})(t,o.id),className:`limbo-tab ${i?"active":""} ${r?"limbo-tab--mobile":""}`,role:"tab","aria-selected":i,"aria-controls":`tabpanel-${o.id}`,tabIndex:i?0:-1,id:`tab-${o.id}`,style:{...r&&{minWidth:"120px",minHeight:"44px",padding:"12px 16px",flexShrink:0,fontSize:"16px"},...a&&{touchAction:"manipulation",WebkitTapHighlightColor:"transparent"}},children:o.label},o.id)})})}const X="http://localhost",J="https://limbo.lefebvre.com";let Z={publicKey:null,token:null,authMode:null,tokenEndpoint:null,prod:!1};function ee({prod:e=!1}={}){return e?J:X}async function te({endpoint:e,method:t="GET",body:n=null,prod:r=!1,basePath:a="",customHeaders:o={},isFormData:i=!1,useJWT:l=!0}){try{const s=r||Z.prod,c=await async function({isFormData:e=!1,useJWT:t=!0,customHeaders:n={}}={}){const r={};if(e||(r["Content-Type"]="application/json"),t){let e=Z.token;if("session"===Z.authMode&&!e)try{const t=ee(Z),n=Z.tokenEndpoint||"/auth/token",r=await fetch(`${t}${n}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({public_key:Z.publicKey}),credentials:"include"});if(!r.ok)throw new Error(`Session auth failed: ${r.status}`);e=(await r.json()).token,Z.token=e}catch(a){throw console.error("❌ Session authentication failed:",a),new Error("Failed to authenticate with session. User must be logged in.")}e?r.Authorization=`Bearer ${e}`:console.warn("⚠️ No JWT token available:",{authMode:Z.authMode,hasPublicKey:!!Z.publicKey})}return e&&delete r["Content-Type"],{...r,...n}}({isFormData:i,useJWT:l,customHeaders:o});"GET"===t&&!n&&c["Content-Type"]&&delete c["Content-Type"];const u=await fetch(`${ee({prod:s})}${a}${e}`,{method:t,headers:c,body:n?i?n:JSON.stringify(n):void 0,credentials:"include"});if(!u.ok){let e=`HTTP ${u.status}: ${u.statusText}`,t=null;try{const n=await u.json();t=n,n.error?e=`${n.error.code}: ${n.error.message}`:n.message&&(e=n.message)}catch{}throw 401===u.status&&t&&("token_expired"===t.error||t.message&&t.message.includes("expired")||t.message&&t.message.includes("caducado")||t.error&&t.error.includes("expired"))&&window.dispatchEvent(new CustomEvent("tokenExpiredError",{detail:{error:{response:{status:401,data:t}}}})),new Error(e)}return u.json()}catch(s){throw new Error(`API Error: ${s.message}`)}}function ne(){const e={...Z};return e?.prod||!1?"https://limbo.lefebvre.com":"http://localhost"}function re(e){if(!e?.id)return null;return`${ne()}/api/assets/${e.id}/download`}function ae(e){if(!e)return null;if(e.startsWith("http://")||e.startsWith("https://"))return e;if(e.startsWith("/")){return`${ne()}${e}`}return e}function oe(e){if(e.message&&!e.message.includes("API Error:"))return e;let t=e.message||"Unknown API error";return t.startsWith("API Error: ")&&(t=t.substring(11)),new Error(t)}const ie="/api";async function le(e={}){try{const t=new URLSearchParams(e).toString(),n=t?`/assets?${t}`:"/assets";return function(e){if(!e?.success||!Array.isArray(e?.data?.data))return{result:[]};const t={result:e.data.data.map(e=>({id:e.id,filename:e.filename||e.original_filename,mime_type:e.mime_type,file_size:e.file_size,width:e.width,height:e.height,upload_date:e.upload_date||e.created_at,processing_status:e.processing_status||e.status,url:ae(e.master_url||e.master?.url_signed||e.urls?.original||e.url)||re(e),webp_available:e.webp_available||!!e.webp_url,metadata:e.metadata||{},variants_count:e.variants_count||0}))};return e.data.pagination&&(t.pagination={page:e.data.pagination.page,limit:e.data.pagination.limit,total:e.data.pagination.total,pages:e.data.pagination.pages}),t}(await te({endpoint:n,method:"GET",basePath:ie,useJWT:!0}))}catch(t){throw oe(t)}}async function se(e,t=null,n=!1){try{const r=new FormData;r.append("file",e),t&&r.append("uploaded_by",t),n&&r.append("store_original",n.toString());return function(e){if(!e?.success||!e?.data)return{result:null};const t=e.data;return{result:{id:t.id,filename:t.original_filename,mime_type:t.mime_type,file_size:t.file_size,width:t.width,height:t.height,status:t.status,upload_date:t.created_at,url:ae(t.master?.url_signed),master_format:t.master?.format,processing:t.processing||{master_webp:"processing"===t.status?"queued":"completed",variants:"processing"===t.status?"queued":"completed"},checksum:t.checksum,storage_path:t.storage_path_base,metadata:t.metadata||{}}}}(await te({endpoint:"/assets",method:"POST",body:r,basePath:ie,isFormData:!0,useJWT:!0}))}catch(r){throw oe(r)}}async function ce(e){try{const n=await te({endpoint:`/assets/${e}/variants`,method:"GET",basePath:ie,useJWT:!0});return t=n,t?.success&&Array.isArray(t?.data?.variants)?{result:t.data.variants.map(e=>({id:e.id,name:e.filename||e.name||`Variante ${e.id}`,filename:e.filename,mime_type:e.mime_type,format:e.output_format||e.format||(e.mime_type?e.mime_type.split("/")[1]:"jpg"),file_size:e.file_size,width:e.width,height:e.height,upload_date:e.upload_date||e.created_at,processing_status:e.processing_status||e.status,url:ae(e.master_url||e.master?.url_signed||e.urls?.original||e.url)||re(e),webp_available:e.webp_available||!!e.webp_url,metadata:e.metadata||{},crop_data:e.crop_data||{},crop_params:e.crop_params||e.crop_data||{},parent_asset_id:e.parent_asset_id||t.data.asset_id,variant_type:e.variant_type||"crop"}))}:{result:[]}}catch(n){throw oe(n)}var t}function ue(){const[e,t]=p.useState({}),[n,r]=p.useState({}),[a,o]=p.useState({}),i=p.useCallback(async a=>{if(a&&!n[a]){if(e[a])return e[a];r(e=>({...e,[a]:!0})),o(e=>({...e,[a]:null}));try{const e=await ce(a),n=e?.result||[];return t(e=>({...e,[a]:n})),n}catch(i){return console.error("Error loading variants:",i),o(e=>({...e,[a]:i.message})),[]}finally{r(e=>({...e,[a]:!1}))}}},[e,n]),l=p.useCallback(t=>e[t]||[],[e]),s=p.useCallback(e=>n[e]||!1,[n]),c=p.useCallback(e=>a[e]||null,[a]),u=p.useCallback(e=>{t(t=>{const n={...t};return delete n[e],n}),r(t=>{const n={...t};return delete n[e],n}),o(t=>{const n={...t};return delete n[e],n})},[]),d=p.useCallback(async e=>(u(e),await i(e)),[u,i]),f=p.useCallback(async(e,n)=>{try{return await async function(e,t){try{return await te({endpoint:`/assets/${e}/variants/${t}`,method:"DELETE",basePath:ie,useJWT:!0})}catch(n){throw oe(n)}}(e,n),t(t=>{const r=t[e]||[];return{...t,[e]:r.filter(e=>e.id!==n)}}),{success:!0}}catch(r){return console.error("Error deleting variant:",r),{success:!1,error:r.message}}},[]);return{loadVariants:i,getVariants:l,isLoading:s,getError:c,clearVariants:u,refreshVariants:d,removeVariant:f}}function de({image:e,isOpen:t,onClose:n,onSelect:r,onDelete:a,onCrop:o,onVariantDeleted:i,allowedActions:l={select:!0,download:!0,copy:!0,delete:!0,crop:!0}}){const{loadVariants:s,getVariants:c,isLoading:u,getError:d,removeVariant:f}=ue(),m=window.limboCore?.accessibilityManager,[g,b]=h.useState(null),[y,v]=h.useState(null),w=(window.limboCore?.config?.getGlobal()||{}).interaction||{allowSelection:!1,allowCropping:!0},k=w.allowSelection&&l.select&&r,x=w.allowCropping&&l.crop&&o,S=l.copy,C=l.download,E=l.delete,[_,T]=h.useState(new Set),N=h.useMemo(()=>e?.variants||[],[e?.variants]),P=c(e?.id),R=N.length>0?N:P,z=0===N.length&&u(e?.id),j=0===N.length?d(e?.id):null;p.useEffect(()=>{!t||!e?.id||e?.variants&&0!==e.variants.length||s(e.id)},[t,e?.id,e?.variants,s]),h.useEffect(()=>{t&&T(new Set)},[t]);if(!t)return null;return K.jsx("div",{className:"limbo-modal-overlay",onClick:n,role:"dialog","aria-modal":"true","aria-labelledby":"variants-modal-title",children:K.jsxs("div",{className:"limbo-modal-content limbo-variants-modal",onClick:e=>e.stopPropagation(),children:[K.jsxs("div",{className:"limbo-modal-header",children:[K.jsxs("h2",{id:"variants-modal-title",children:["Variantes de ",e?.filename]}),K.jsx("button",{className:"limbo-modal-close",onClick:n,"aria-label":"Cerrar modal de variantes",children:"✕"})]}),g&&K.jsx("div",{className:`limbo-variants-message limbo-variants-message--${y} mt-1`,role:"alert",style:{padding:"12px 20px",margin:"0 20px 15px 20px",borderRadius:"4px",backgroundColor:"success"===y?"#d4edda":"#f8d7da",color:"success"===y?"#155724":"#721c24",border:"1px solid "+("success"===y?"#c3e6cb":"#f5c6cb")},children:g}),K.jsx("div",{className:"limbo-modal-body",children:z?K.jsxs("div",{className:"limbo-variants-loading",children:[K.jsx("div",{className:"limbo-loader"}),K.jsx("p",{children:"Cargando variantes..."})]}):j?K.jsxs("div",{className:"limbo-variants-error",children:[K.jsxs("p",{children:["Error al cargar variantes: ",j]}),K.jsx("button",{onClick:()=>s(e.id),className:"btn btn-primary",children:"Reintentar"})]}):0===R.length?K.jsxs("div",{className:"limbo-variants-empty",children:[K.jsx("p",{children:"Esta imagen no tiene variantes aún."}),K.jsx("small",{children:"Las variantes aparecerán aquí después de hacer recortes o redimensionados."})]}):K.jsxs(K.Fragment,{children:[K.jsxs("div",{className:"limbo-variant-section",children:[K.jsx("h3",{children:"Imagen original"}),K.jsxs("div",{onClick:()=>{m?.announce(`Abriendo imagen original ${e.filename} en nueva pestaña`),window.open(e.url,"_blank")},className:"limbo-variant-card limbo-variant-original cursor-pointer",children:[K.jsx("div",{className:"limbo-variant-preview",children:K.jsx("img",{src:e.url,alt:e.filename,loading:"lazy"})}),K.jsxs("div",{className:"limbo-variant-info",children:[K.jsx("div",{className:"limbo-variant-name",children:e.filename}),K.jsxs("div",{className:"limbo-variant-meta",children:[K.jsxs("span",{children:[e.width,"×",e.height]}),K.jsxs("span",{children:[Math.round(e.file_size/1024)," KB"]})]})]}),K.jsxs("div",{className:"limbo-variant-actions",children:[k&&K.jsx("button",{className:"btn btn-success btn-sm",onClick:t=>{t.stopPropagation(),r?.(e),n?.()},title:"Seleccionar original",children:"Seleccionar"}),x&&K.jsx("button",{className:"btn btn-crop btn-sm",onClick:t=>{t.stopPropagation(),o&&(m?.announce(`Abriendo herramienta de recorte para ${e.filename}`),o(e),n?.())},title:"Recortar imagen",children:K.jsx("span",{className:"icon icon-scissors-white icon--sm"})}),S&&K.jsx("button",{className:"btn btn-secondary btn-sm",onClick:t=>{t.stopPropagation(),(async()=>{try{await navigator.clipboard.writeText(e.url),m?.announce("URL de imagen original copiada")}catch(t){console.error("Error copying original URL:",t),m?.announceError("Error al copiar URL")}})()},title:"Copiar URL",children:K.jsx("span",{className:"icon icon-copy-white icon--sm"})}),C&&K.jsx("button",{className:"btn btn-primary btn-sm",onClick:t=>{t.stopPropagation(),(()=>{m?.announce(`Descargando imagen original ${e.filename}`);const t=document.createElement("a");t.href=e.url,t.download=e.filename,document.body.appendChild(t),t.click(),document.body.removeChild(t)})()},title:"Descargar",children:K.jsx("span",{className:"icon icon-download-white icon--sm"})}),E&&a&&K.jsx("button",{className:"btn btn-danger btn-sm",onClick:t=>{t.stopPropagation(),(async()=>{if(!a)return;window.confirm(`¿Estás seguro de que deseas eliminar "${e.filename}"? Esta acción también eliminará todas sus variantes.`)&&(m?.announce(`Eliminando imagen ${e.filename}`),await a(e.id),n?.())})()},title:"Eliminar imagen",children:K.jsx("span",{className:"icon icon-close-small-white icon--sm m-[0!important]"})})]})]})]}),K.jsxs("div",{className:"limbo-variant-section",children:[K.jsxs("h3",{children:["Variantes (",R.length,")"]}),K.jsx("div",{className:"limbo-variants-grid",children:R.map(t=>{const a=_.has(t.id);return K.jsxs("div",{className:"limbo-variant-card "+(a?"":"cursor-pointer"),onClick:a?void 0:()=>(e=>{m?.announce(`Abriendo variante ${e.name} en nueva pestaña`),window.open(e.url,"_blank")})(t),children:[K.jsxs("div",{className:"limbo-variant-preview",children:[K.jsx("img",{src:t.url,alt:t.name||t.filename||`Variante ${t.id}`,loading:"lazy",onError:()=>{return e=t.id,void T(t=>new Set([...t,e]));var e},style:{display:a?"none":"block"}}),a&&K.jsx("div",{className:"limbo-variant-error",style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100px",backgroundColor:"#f5f5f5",color:"#666"},children:K.jsx("span",{children:"Error al cargar preview"})})]}),K.jsxs("div",{className:"limbo-variant-info",children:[K.jsx("div",{className:"limbo-variant-name",children:t.name||t.filename||`Variante ${t.id}`}),K.jsxs("div",{className:"limbo-variant-meta",children:[K.jsxs("span",{children:[t.width,"×",t.height]}),K.jsx("span",{children:(t.format||"jpg").toUpperCase()}),K.jsxs("span",{children:[Math.round((t.file_size||0)/1024)," KB"]})]}),t.crop_params&&K.jsxs("div",{className:"limbo-variant-crop-badge",children:[K.jsx("span",{className:"icon icon-scissors icon--xs"})," ","Recortada"]})]}),K.jsxs("div",{className:"limbo-variant-actions",children:[k&&K.jsx("button",{className:"btn btn-success btn-sm",onClick:a=>{a.stopPropagation(),(t=>{const a={id:t.id,filename:`${e.filename}_${t.name}`,url:t.url,width:t.width,height:t.height,mime_type:`image/${t.format}`,file_size:t.file_size,upload_date:t.created_at,processing_status:"completed",is_variant:!0,parent_asset_id:e.id,variant_info:t};m?.announce(`Variante seleccionada: ${t.name}`),r?.(a),n?.()})(t)},title:`Seleccionar variante ${t.name||t.filename||t.id}`,children:"Seleccionar"}),S&&K.jsx("button",{className:"btn btn-secondary btn-sm",onClick:e=>{e.stopPropagation(),(async e=>{try{await navigator.clipboard.writeText(e.url),m?.announce(`URL de variante ${e.name} copiada`)}catch(t){console.error("Error copying variant URL:",t),m?.announceError("Error al copiar URL de variante")}})(t)},title:"Copiar URL",children:K.jsx("span",{className:"icon icon-copy-white icon--sm"})}),C&&K.jsx("button",{className:"btn btn-primary btn-sm",onClick:n=>{n.stopPropagation(),(t=>{m?.announce(`Descargando variante ${t.name}`);const n=document.createElement("a");n.href=t.url,n.download=`${e.filename}_${t.name}.${t.format}`,document.body.appendChild(n),n.click(),document.body.removeChild(n)})(t)},title:"Descargar",children:K.jsx("span",{className:"icon icon-download-white icon--sm"})}),E&&K.jsx("button",{className:"btn btn-danger btn-sm",onClick:n=>{n.stopPropagation(),(async t=>{if(window.confirm(`¿Estás seguro de que deseas eliminar la variante "${t.name||t.filename}"?`)){m?.announce(`Eliminando variante ${t.name||t.filename}`);const n=await f(e.id,t.id);n.success?(b("Variante eliminada correctamente"),v("success"),m?.announce("Variante eliminada correctamente"),i?.(),setTimeout(()=>{b(null),v(null)},3e3)):(b(`Error al eliminar variante: ${n.error}`),v("error"),m?.announceError(`Error al eliminar variante: ${n.error}`),setTimeout(()=>{b(null),v(null)},5e3))}})(t)},title:"Eliminar variante",children:K.jsx("span",{className:"icon icon-close-small-white icon--sm m-[0!important]"})})]})]},t.id)})})]})]})})]})})}function fe({image:e,onDelete:t,onCrop:n,onSelect:r,thumbnailSize:a=32,isDeleting:o=!1,allowedActions:i={select:!0,download:!0,copy:!0,delete:!0,crop:!0,variants:!0}}){const[l,s]=p.useState(!1),[c,u]=p.useState(!1),[d,f]=p.useState(e.variants_count||0),{isMobile:m,isTouch:g}=Y(),b=window.limboCore?.accessibilityManager,y=(window.limboCore?.config?.getGlobal()||{}).interaction||{allowSelection:!1,allowCropping:!0},v=n=>{n.stopPropagation(),b?.announce(`Eliminando imagen ${e.filename}`,"assertive"),t?.(e)},w=async t=>{t.stopPropagation();let n=e.url||e.path;try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(n);else{const e=document.createElement("textarea");e.value=n,e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.focus(),e.select(),document.execCommand("copy"),document.body.removeChild(e)}s(!0),b?.announce(`URL de ${e.filename} copiada al portapapeles. Nota: La URL puede tener un tiempo de validez limitado.`),setTimeout(()=>s(!1),2e3)}catch(r){console.error("Error al copiar URL:",r),b?.announce(`Error al copiar URL de ${e.filename}. Inténtalo de nuevo.`),alert(`Error al copiar URL de ${e.filename}. Por favor, inténtalo de nuevo.`)}},k=t=>{t.preventDefault(),t.stopPropagation(),b?.announce(`Descargando ${e.filename}`),fetch(e.url||e.path,{mode:"cors"}).then(e=>e.blob()).then(t=>{const n=window.URL.createObjectURL(t),r=document.createElement("a");r.href=n,r.download=e.filename||"imagen.jpg",document.body.appendChild(r),r.click(),setTimeout(()=>{window.URL.revokeObjectURL(n),document.body.removeChild(r)},100)})},x=t=>{t.stopPropagation(),b?.announce(`Editando imagen ${e.filename}`),n?.(e)},S=e.variants&&e.variants.length>0||d>0,C=d,E=h.useCallback(()=>{f(e=>Math.max(0,e-1))},[]);h.useEffect(()=>{f(e.variants_count||0)},[e.variants_count]);const _=t=>{t.stopPropagation(),b?.announce(`Mostrando variantes de ${e.filename}`),u(!0)},T=y.allowSelection&&i.select&&r,N=y.allowCropping&&i.crop&&n,P=S&&!1!==i.variants,R=()=>{window.open(e.url||e.path,"_blank")};return K.jsxs(K.Fragment,{children:[K.jsxs("div",{className:`limbo-image-card flex flex-col items-center cursor-pointer relative transition ${o?"opacity-50":""} ${m?"limbo-image-card--mobile":""}`,onClick:R,onKeyDown:e=>{switch(e.key){case"Enter":case" ":e.preventDefault(),R();break;case"d":case"D":i.download&&(e.preventDefault(),k(e));break;case"c":case"C":i.copy&&(e.preventDefault(),w(e));break;case"Delete":case"Backspace":i.delete&&t&&(e.preventDefault(),v(e));break;case"x":case"X":i.crop&&n&&(e.preventDefault(),x(e));break;case"v":case"V":i.variants&&(e.preventDefault(),_(e))}},title:m?"Toque para ver imagen":"Haga click en la imagen para ver preview en nueva pestaña (Enter/Space para abrir, D descargar, C copiar, Delete eliminar, X recortar)",role:"button",tabIndex:0,"aria-label":`Imagen ${e.filename}. ${e.width}x${e.height} px`,style:{...g&&{touchAction:"manipulation",WebkitTapHighlightColor:"transparent"}},children:[K.jsxs("div",{className:"limbo-image-actions "+(m?"limbo-image-actions--mobile":""),children:[i.copy&&K.jsx("button",{type:"button",title:l?"¡Copiado!":"Copiar URL",className:"btn btn-copy border border-brand-blue-050/50 "+(m?"btn--touch":""),onClick:w,tabIndex:-1,style:{...m&&{width:"40px",height:"40px"}},children:K.jsx("span",{className:`icon ${l?"icon-copied-white":"icon-copy-white"} icon--sm`,"aria-hidden":"true"})}),T&&K.jsx("button",{type:"button",title:"Seleccionar imagen",className:"btn btn-success border border-brand-blue-050/50 "+(m?"btn--touch":""),onClick:t=>{t.stopPropagation(),b?.announce(`Seleccionando ${e.filename} para el portal`),r?.(e)},tabIndex:-1,style:{...m&&{width:"40px",height:"40px"}},children:K.jsx("span",{className:"icon icon-tick-white icon--sm","aria-hidden":"true"})}),N&&K.jsx("button",{type:"button",title:"Editar imagen",className:"btn btn-crop border border-brand-blue-050/50 "+(m?"btn--touch":""),onClick:x,tabIndex:-1,style:{...m&&{width:"40px",height:"40px"}},children:K.jsx("span",{className:"icon icon-scissors-white icon--sm","aria-hidden":"true"})}),P&&K.jsxs("button",{type:"button",title:`Ver ${C} variante${1!==C?"s":""}`,className:"btn btn-variants border border-brand-blue-050/50 "+(m?"btn--touch":""),onClick:_,tabIndex:-1,style:{...m&&{width:"40px",height:"40px"},position:"relative"},children:[K.jsx("span",{className:"icon icon-album-menu-white icon--sm","aria-hidden":"true"}),C>0&&K.jsx("span",{className:"variants-count-badge",style:{position:"absolute",top:"-8px",right:"-8px",background:"#dc2626",color:"white",borderRadius:"50%",minWidth:"20px",height:"20px",fontSize:"12px",fontWeight:"700",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:"1",border:"2px solid white",boxShadow:"0 2px 8px rgba(0, 0, 0, 0.4)",zIndex:"999"},children:C})]}),i.download&&K.jsx("button",{type:"button",title:"Descargar",className:"btn btn-download border border-brand-blue-050/50 "+(m?"btn--touch":""),onClick:k,tabIndex:-1,style:{...m&&{width:"40px",height:"40px"}},children:K.jsx("span",{className:"icon icon-download-white icon--sm","aria-hidden":"true"})}),i.delete&&t&&K.jsx("button",{onClick:v,disabled:o,className:"btn btn-delete border border-brand-blue-050/50 "+(m?"btn--touch":""),title:"Eliminar imagen",tabIndex:-1,style:{...m&&{width:"40px",height:"40px"}},children:o?"…":K.jsx("span",{className:"icon icon-close-small-white icon--sm","aria-hidden":"true"})})]}),K.jsx("img",{src:e.url||e.path,alt:e.filename,className:"w-full object-cover rounded aspect-square",sizes:`height: ${6*a}px,width: ${6*a}px`,draggable:!1,style:{...m&&{minHeight:`${Math.max(3*a,80)}px`,height:"auto",aspectRatio:"1 / 1",objectFit:"cover"}}}),K.jsx("span",{className:"text-xs mt-1 truncate w-full text-center limbo-image-card-name "+(m?"limbo-image-card-name--mobile":""),style:{...m&&{fontSize:"0.75rem",lineHeight:"1.2",maxWidth:"100%",padding:"2px 4px",backgroundColor:"rgba(255, 255, 255, 0.9)",borderRadius:"4px",color:"#333",fontWeight:"500"}},children:e.filename})]}),K.jsx(de,{image:e,isOpen:c,onClose:()=>u(!1),onSelect:r,onDelete:t,onCrop:n,onVariantDeleted:E,allowedActions:{select:i.select,download:i.download,copy:i.copy,delete:i.delete,crop:i.crop}})]})}function pe({text:e="Cargando..."}){return K.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-gray-600",role:"status","aria-live":"polite","aria-label":e,children:[K.jsxs("svg",{className:"animate-spin h-6 w-6 mb-2 text-blue-500",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24","aria-hidden":"true",children:[K.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),K.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8v8H4z"})]}),K.jsx("p",{className:"text-sm",id:"loader-text",children:e})]})}const he=new Map;function me({apiKey:e,prod:t,onSelect:n,onCrop:r,onDelete:a,deletingId:o,images:i,loading:l,error:s,allowedActions:c={select:!0,download:!0,copy:!0,delete:!0,crop:!0,variants:!0}}){const[u,d]=p.useState({search:"",dateFrom:"",dateTo:"",originPortal:"",uploadedBy:""}),f=p.useRef(null),h=function(){const[e,t]=p.useState(null),[n,r]=p.useState(!0),[a,o]=p.useState(null);return p.useEffect(()=>{const e="auth-status",n=he.get(e),a=Date.now();if(n&&a-n.timestamp<3e5)return t(n.data),void r(!1);let i=!0;return(async()=>{try{const n=!0;if(!i)return;he.set(e,{data:n,timestamp:Date.now()}),t(n)}catch(n){i&&(o(n.message),t(!1))}finally{i&&r(!1)}})(),()=>{i=!1}},[]),{allowed:e,loading:n,error:a,invalidateCache:()=>{he.delete("auth-status")}}}(),m=window.limboCore?.accessibilityManager;p.useEffect(()=>{if(f.current&&window.limboCore?.keyboardManager){const e="gallery-grid";f.current.setAttribute("data-grid-id",e),window.limboCore.keyboardManager.setupGridNavigation(f.current,{itemSelector:".limbo-image-card",gridId:e,columns:"auto"})}},[i]),p.useEffect(()=>{l?m?.announceLoading(!0,"galería"):l||s?s&&m?.announceError(s,"galería"):(m?.announceLoading(!1,"galería"),i.length>0&&m?.announce(`Se encontraron ${i.length} imágenes en la galería`))},[l,s,i.length,m]);const g=e=>{const{name:t,value:n}=e.target;d(e=>({...e,[t]:n}))};return K.jsxs("div",{className:"w-full",children:[K.jsx("div",{className:"limbo-card mb-6 p-4 bg-brand-blue-050 shadow-md",children:K.jsxs("form",{className:"limbo-form-grid flex flex-col sm:flex-row flex-wrap gap-4 items-start sm:items-end justify-between",onSubmit:e=>e.preventDefault(),"aria-label":"Filtrar imágenes",children:[K.jsxs("div",{className:"flex flex-col w-full sm:min-w-[180px] sm:flex-1",children:[K.jsx("label",{htmlFor:"search",className:"form-label mb-1",children:"Nombre"}),K.jsx("input",{type:"text",name:"search",id:"search",placeholder:"Buscar por nombre...",value:u.search,onChange:g,className:"form-control",autoComplete:"off"})]}),K.jsxs("div",{className:"flex flex-col sm:flex-row flex-wrap gap-2 justify-between items-start sm:items-end w-full sm:w-auto",children:[K.jsxs("div",{className:"flex flex-col w-full sm:w-auto",children:[K.jsx("label",{htmlFor:"dateFrom",className:"form-label mb-1",children:"Desde"}),K.jsx("input",{type:"date",name:"dateFrom",id:"dateFrom",value:u.dateFrom,onChange:g,className:"form-control"})]}),K.jsxs("div",{className:"flex flex-col w-full sm:w-auto",children:[K.jsx("label",{htmlFor:"dateTo",className:"form-label mb-1",children:"Hasta"}),K.jsx("input",{type:"date",name:"dateTo",id:"dateTo",value:u.dateTo,onChange:g,className:"form-control"})]}),h&&K.jsxs("div",{className:"flex flex-col w-full sm:w-auto",children:[K.jsx("label",{htmlFor:"originPortal",className:"form-label mb-1",children:"Portal de origen"}),K.jsx("input",{type:"text",name:"originPortal",id:"originPortal",placeholder:"Portal de origen",value:u.originPortal,onChange:g,className:"form-control"})]}),K.jsxs("div",{className:"flex flex-col w-full sm:w-auto",children:[K.jsx("label",{htmlFor:"uploadedBy",className:"form-label mb-1",children:"Subido por"}),K.jsx("input",{type:"text",name:"uploadedBy",id:"uploadedBy",placeholder:"Subido por",value:u.uploadedBy,onChange:g,className:"form-control"})]})]})]})}),l?K.jsx(pe,{text:"Cargando imágenes..."}):s?K.jsx("div",{className:"alert alert-danger text-center",children:s}):K.jsx("div",{ref:f,className:"limbo-gallery mt-4","data-limbo-responsive":!0,"data-grid-id":"gallery-grid",role:"grid","aria-label":"Galería de imágenes. Use las flechas para navegar entre imágenes",children:i.length>0?i.map((e,t)=>K.jsx("div",{role:"gridcell","aria-posinset":t+1,"aria-setsize":i.length,children:K.jsx(fe,{image:e,onSelect:n,onCrop:r,onDelete:c.delete&&a?()=>a(e.id):null,thumbnailSize:32,isDeleting:o===e.id,allowedActions:c})},e.id)):K.jsx("div",{className:"col-span-full text-center text-gray-500 py-8",role:"status","aria-live":"polite",children:K.jsx("p",{children:"No se han encontrado imágenes"})})})]})}function ge({file:e,setFile:t,previewUrl:n,setPreviewUrl:r,fileInputRef:a,onUpload:o,disabled:i}){return K.jsxs("form",{onSubmit:n=>{n.preventDefault(),e&&!i&&(o(e),t(null),r(null),a.current&&(a.current.value=""))},className:"flex flex-col items-center gap-6","aria-label":"Subir imagen desde dispositivo",children:[K.jsxs("label",{htmlFor:"file-input",className:"w-full flex flex-col items-center justify-center border-2 border-dashed border-brand-blue-200 rounded-xl p-8 cursor-pointer hover:border-brand-blue-1000 hover:to-bright-blue-200 hover:from-brand-blue-050 focus-within:border-brand-blue-800 from-bright-blue-050 to-brand-blue-050 bg-linear-to-br transition",tabIndex:0,style:{outline:"none"},children:[K.jsx("span",{className:"icon icon-upload icon--lg mb-2","aria-hidden":"true"}),K.jsx("span",{className:"font-medium text-brand-blue-1000 mb-1",children:"Haz clic o arrastra una imagen aquí"}),K.jsx("span",{className:"text-sm text-neutral-700",children:"Formatos permitidos: JPG, PNG, GIF, SVG, WebP"}),K.jsx("input",{id:"file-input",ref:a,type:"file",accept:"image/jpeg,image/png,image/svg,image/webp,image/gif",onChange:e=>{const n=e.target.files[0];if(t(n),n){const e=URL.createObjectURL(n);r(e)}else r(null)},disabled:i,className:"sr-only","aria-label":"Seleccionar imagen"})]}),n&&K.jsxs("div",{className:"w-full flex flex-col items-center gap-2",children:[K.jsx("img",{src:n,alt:e?.name||"Previsualización",className:"rounded-lg shadow-md border border-brand-blue-200 max-h-64 object-contain bg-white",style:{maxWidth:"100%"}}),K.jsxs("div",{className:"text-sm text-neutral-800 bg-brand-blue-050 p-2 rounded w-full text-center",children:[K.jsxs("p",{children:[K.jsx("span",{className:"font-medium",children:"Archivo:"})," ",e?.name]}),K.jsxs("p",{children:[K.jsx("span",{className:"font-medium",children:"Tamaño:"})," ",e?(e.size/1024/1024).toFixed(2):"--"," MB"]}),K.jsxs("p",{children:[K.jsx("span",{className:"font-medium",children:"Tipo:"})," ",e?.type]})]})]}),K.jsx("button",{type:"submit",disabled:!e||i,title:e?"Subir imagen a la galeria":"Proporcione una imagen antes de continuar",className:"limbo-btn w-full mt-2 "+(e?"limbo-btn-primary":"cursor-not-allowed limbo-btn-disabled"),style:{minHeight:44},children:i?"Subiendo...":"Subir imagen"})]})}const be="/api";const ye=new Map;function ve(e=!1){const[t,n]=p.useState([]),[r,a]=p.useState(!0),[o,i]=p.useState(null);p.useEffect(()=>{const t=`ai-services-${e}`,r=ye.get(t),o=Date.now();if(r&&o-r.timestamp<864e5)return n(r.data),void a(!1);let l=!0;return(async()=>{try{const r=await function(e=!1){return te({endpoint:"/ai/services",prod:e,basePath:be})}(e);if(!l)return;const a=r?.data?.images||[];n(a),ye.set(t,{data:a,timestamp:o})}catch(r){l&&i(r.message)}finally{l&&a(!1)}})(),()=>{l=!1}},[e]);return{services:t,loading:r,error:o,invalidateCache:()=>{ye.delete(`ai-services-${e}`)}}}const we=new Map;function ke(e=!1){const[t,n]=p.useState(null),[r,a]=p.useState(!1),[o,i]=p.useState(null);return{params:t,loading:r,error:o,fetchParams:async t=>{a(!0),i(null);const r=`${e}-${t}`,o=Date.now(),l=we.get(r);if(l&&o-l.timestamp<864e5)return n(l.data),a(!1),l.data;try{const a=await function({services:e=null,form:t=!1}={},n=!1){const r={};return e&&(r.services=e),!1!==t&&(r.form=t),te({endpoint:"/ai/params"+(Object.keys(r).length?"?"+new URLSearchParams(r).toString():""),method:"GET",prod:n,basePath:"/api/atenea"})}({services:t,form:!1},e),i=a?.result?.data||a?.data||a?.result||a;return n(i),we.set(r,{data:i,timestamp:o}),i}catch(s){return i(s.message),n(null),null}finally{a(!1)}},reset:()=>{i(null),n(null)}}}function xe({prod:e,disabled:t,onSelected:n,onGenerated:r}){const a=ve(e),o=ke(e),[i,l]=p.useState(""),[s,c]=p.useState({}),[u,d]=p.useState(!1),[f,m]=p.useState(null),[g,b]=p.useState(null),y={"dall-e-2":"Dalle2","dall-e-3":"Dalle3","freepik-classic":"Freepik Classic","freepik-mystic":"Freepik Mystic","freepik-google":"Freepik Google","freepik-flux":"Freepik Flux",shutterstock:"Shutterstock",freepikstock:"Freepik"},v=e=>y[e]||e;h.useEffect(()=>{if(!a.loading&&1===a.services.length){const e=a.services[0];l(e),o.fetchParams(e,!0)}},[a.loading,a.services]);h.useEffect(()=>{if(!i)return;const e=o.params?.[i]?.parameters;if(e){const t=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default??""]));t.service=i,c(t)}},[i,o.params]);const w=e=>{const{name:t,value:n}=e.target;c(e=>({...e,[t]:n}))},k=async t=>{t.preventDefault(),d(!0),m(null),b(null);try{const t=await function(e,t=!1){return te({endpoint:"/ai/generate",method:"POST",body:e,prod:t,basePath:be})}(s,e);let a=null;if(t?.data?.images&&Array.isArray(t.data.images)&&t.data.images.length>0?a=t.data.images[0]:t?.result?.images&&Array.isArray(t.result.images)&&t.result.images.length>0?a=t.result.images[0]:Array.isArray(t)&&t.length>0?a=t[0]:"string"==typeof t&&(a=t),!a||!r)throw new Error("No se pudo extraer la imagen de la respuesta");if(a.startsWith("http"))try{const e=await fetch(a);if(!e.ok)throw new Error(`Failed to download image: ${e.status}`);const t=await e.blob(),n=new File([t],"ai-image.png",{type:t.type||"image/png"});r(n)}catch(n){throw new Error(`Error downloading image: ${n.message}`)}else{const e=a.replace(/^data:image\/\w+;base64,/,""),t=atob(e),n=new Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);const o=new Uint8Array(n),i=new File([o],"ai-image.webp",{type:"image/webp"});r(i)}b(t?.data?.images||t?.result?.images||null)}catch(a){m(a.message||"Error al generar la imagen")}finally{d(!1)}};return a.loading?K.jsxs("div",{className:"flex items-center justify-center py-8",children:[K.jsx("span",{className:"limbo-loader mr-2"})," Cargando servicios IA..."]}):a.services.length?K.jsxs("div",{className:"flex flex-col gap-4",children:[K.jsx("h3",{id:"aiSelectDescription",className:"text-lg font-semibold text-brand-blue-1000",children:1===a.services.length?`Generación con ${v(i)}`:"Selecciona el modelo IA"}),a.services.length>1&&K.jsxs("select",{name:"aiService","aria-describedby":"aiSelectDescription",title:"Selecciona el servicio IA",value:i,onChange:async e=>{const t=e.target.value;l(t),c({}),b(null),t&&await o.fetchParams(t,!0)},disabled:a.loading||t,className:"limbo-input",children:[K.jsx("option",{value:"",children:"-- Selecciona --"}),a.services.map(e=>K.jsx("option",{value:e,children:v(e)},e))]}),a.error&&K.jsx("div",{className:"alert alert-danger",children:a.error}),o.loading&&K.jsx("div",{children:"Cargando parámetros..."}),o.error&&K.jsx("div",{className:"alert alert-danger",children:o.error}),i&&(()=>{const e=o.params?.[i]?.parameters;if(!e)return null;const n=Object.entries(e).filter(([e,t])=>!t.disabled),r=n.length>3;return K.jsxs("form",{onSubmit:k,"data-type":"ai",className:"flex flex-col gap-3 mt-4 border-t-1 pt-4 border-brand-blue-200","aria-label":"Formulario generación IA",children:[K.jsx("div",{className:r?"grid grid-cols-1 md:grid-cols-2 gap-3":"flex flex-col gap-3",children:n.map(([e,n])=>{let r=n.placeholder||"";return r||(r="integer"===n.type?n.minValue&&n.maxValue?`Entre ${n.minValue} y ${n.maxValue}`:n.minValue?`Mínimo ${n.minValue}`:n.maxValue?`Máximo ${n.maxValue}`:"Introduce un número":e.toLowerCase().includes("prompt")?"Describe la imagen que deseas generar...":e.toLowerCase().includes("negative")?"Elementos a evitar en la imagen...":`Introduce ${(n.label||e).toLowerCase()}`),K.jsxs("div",{className:"flex flex-col gap-1",children:[K.jsxs("label",{htmlFor:`ai-${e}`,className:"text-xs font-medium text-brand-blue-900",children:[n.label||e,n.required&&K.jsx("span",{className:"text-red-600 ml-1",children:"*"})]}),n.options?K.jsx("select",{id:`ai-${e}`,name:e,value:s[e]??"",onChange:w,className:"limbo-input",disabled:t,title:n.label||e,children:n.options.map(e=>K.jsx("option",{value:e,children:e},e))}):K.jsx("input",{id:`ai-${e}`,type:"integer"===n.type?"number":"text",name:e,value:s[e]??"",onChange:w,className:"limbo-input",disabled:t,required:n.required,min:n.minValue,max:n.maxValue,placeholder:r,title:n.label||e})]},e)})}),K.jsx("button",{type:"submit",disabled:u||t,title:u?"Generando imagen...":"Generar imagen",className:"limbo-btn w-full mt-2 "+(u?"cursor-not-allowed limbo-btn-disabled":"limbo-btn-primary"),style:{minHeight:44},children:u?"Generando...":"Generar imagen"})]})})(),f&&K.jsx("div",{className:"alert alert-danger",children:f}),g&&g.map((e,t)=>K.jsxs("div",{className:"mt-6 text-center",children:[K.jsx("img",{src:e.contains("http")?e:`data:image/png;base64, ${e}`,alt:"Imagen generada con IA",className:"rounded-lg shadow-md border border-brand-blue-200 max-h-72 mx-auto"}),K.jsx("button",{className:"limbo-btn limbo-btn-primary mt-4",children:"Aceptar y subir"})]},"img-"+t))]}):K.jsx("div",{className:"alert alert-warning",children:"No hay servicios IA disponibles."})}const Se="/api";const Ce=new Map;function Ee(e=!1){const[t,n]=p.useState([]),[r,a]=p.useState(!0),[o,i]=p.useState(null);p.useEffect(()=>{const t=`stock-services-${e}`,r=Ce.get(t),o=Date.now();if(r&&o-r.timestamp<864e5)return n(r.data),void a(!1);let l=!0;return(async()=>{try{const r=await function(e=!1){return te({endpoint:"/stock/services",prod:e,basePath:Se})}(e);if(!l)return;const a=r?.data?.images||[];n(a),Ce.set(t,{data:a,timestamp:o})}catch(r){l&&i(r.message)}finally{l&&a(!1)}})(),()=>{l=!1}},[e]);return{services:t,loading:r,error:o,invalidateCache:()=>{Ce.delete(`stock-services-${e}`)}}}function _e({prod:e,disabled:t,onSelected:n}){const r=h.useRef(null),a=Ee(e),o=(e,t)=>{try{const n=sessionStorage.getItem(`limbo_stock_${e}`);return n?JSON.parse(n):t}catch{return t}},[i,l]=p.useState(()=>o("selectedService","")),[s,c]=p.useState(()=>o("dynamicForm",{})),[u,d]=p.useState(()=>o("stockImages",[])),[f,m]=p.useState(()=>o("currentPage",1)),[g,b]=p.useState(()=>o("paginationInfo",null)),y=ke(e),[v,w]=p.useState(!1),[k,x]=p.useState(null),[S,C]=p.useState(null);h.useEffect(()=>{sessionStorage.setItem("limbo_stock_selectedService",JSON.stringify(i))},[i]),h.useEffect(()=>{sessionStorage.setItem("limbo_stock_dynamicForm",JSON.stringify(s))},[s]),h.useEffect(()=>{sessionStorage.setItem("limbo_stock_stockImages",JSON.stringify(u))},[u]),h.useEffect(()=>{sessionStorage.setItem("limbo_stock_currentPage",JSON.stringify(f))},[f]),h.useEffect(()=>{sessionStorage.setItem("limbo_stock_paginationInfo",JSON.stringify(g))},[g]);const E={shutterstock:"Shutterstock",freepikstock:"Freepik"},_=e=>E[e]||e;h.useEffect(()=>{if(!a.loading&&1===a.services.length){const e=a.services[0];l(e),y.fetchParams(e,!0)}},[a.loading,a.services]);h.useEffect(()=>{if(!i)return;const e=y.params?.[i]?.parameters;if(e){const t=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default??""]));t.service=i,c(t)}},[i,y.params]);const T=e=>{const{name:t,value:n}=e.target;c(e=>({...e,[t]:n}))},N=async(t=1)=>{w(!0),x(null),1===t&&d([]);try{let n;if(1===t){const e=y.params?.[i]?.parameters,a={...s};Object.entries(e||{}).forEach(([e,t])=>{e in a||(a[e]=t.default??"")}),a.per_page=parseInt(a.per_page),a.service=i,a.page=t,n=a,r.current={...a}}else n={...r.current,page:t};const a=await function(e,t=!1){return te({endpoint:"/stock/search",method:"POST",body:e,prod:t,basePath:Se})}(n,e),o=a?.data?.images||[];let l=a?.data?.pagination||null,c=null;l&&(c={total:l.total_count??l.total??o.length,per_page:l.per_page??(Array.isArray(o)?o.length:0),current_page:l.page??l.current_page??t}),d(P(Array.isArray(o)?o:[])),b(c),m(c?.current_page||t)}catch(n){x(n.message||"Error al buscar imágenes")}finally{w(!1)}},P=e=>{const t=new Set,n=[];return(e||[]).forEach((e,r)=>{const a=e.url||e.preview_url||e.full||e.preview;a&&!t.has(a)&&(t.add(a),n.push({...e,preview:e.preview_url||e.preview||e.url||e.full,full:e.url||e.full||e.preview_url,id:e.id||r,title:e.title||e.filename||`Imagen ${r+1}`,source:e.service||i,sourceTitle:E?.[i]||i}))}),n},R=async e=>{e.preventDefault();(s.query||s.search||s.term||"").trim().length<5?x("La búsqueda debe tener al menos 5 caracteres"):await N(1)},z=e=>{e<1||N(e)},j=async t=>{C(t.id),x(null);try{const r={service:i,image_id:t.id},a=await function(e,t=!1){return te({endpoint:"/stock/download",method:"POST",body:e,prod:t,basePath:Se})}(r,e);if(!a?.result?.url&&!a?.result?.download_url)throw new Error("No se pudo obtener la URL de descarga");{const e=a.result.url||a.result.download_url,r=await fetch(e),o=await r.blob(),i=a.result.filename||`stock-${t.id}.jpg`,l=new File([o],i,{type:o.type||"image/jpeg"});n&&n(l)}}catch(r){x(r.message||"No se pudo recuperar la imagen seleccionada")}finally{C(null)}};return a.loading?K.jsxs("div",{className:"flex items-center justify-center py-8",children:[K.jsx("span",{className:"limbo-loader mr-2"})," Cargando servicios de Stock..."]}):a.services.length?K.jsxs("div",{className:"flex flex-col gap-4",children:[K.jsx("h3",{className:"text-lg font-semibold text-brand-blue-1000",children:1===a.services.length?`Búsqueda en ${_(i)}`:"Selecciona el servicio de Stock"}),a.services.length>1&&K.jsxs("select",{value:i,onChange:async e=>{const t=e.target.value;l(t),c({}),d([]),m(1),t&&await y.fetchParams(t,!0)},disabled:a.loading||t,className:"limbo-input",children:[K.jsx("option",{value:"",children:"-- Selecciona --"}),a.services.map(e=>K.jsx("option",{value:e,children:_(e)},e))]}),a.error&&K.jsx("div",{className:"alert alert-danger",children:a.error}),y.loading&&K.jsx("div",{children:"Cargando parámetros..."}),y.error&&K.jsx("div",{className:"alert alert-danger",children:y.error}),i&&(()=>{const e=y.params?.[i]?.parameters;if(!e)return null;const n=Object.entries(e).filter(([,e])=>!e.disabled),r=n.length>3;return K.jsxs("form",{onSubmit:R,"data-type":"stock",className:"flex flex-col gap-3 mt-4 border-t-1 pt-4 border-brand-blue-200","aria-label":"Formulario búsqueda de imágenes de Stock",children:[K.jsx("div",{className:r?"grid grid-cols-1 md:grid-cols-2 gap-3":"flex flex-col gap-3",children:n.map(([e,n])=>{let r=n.placeholder||"";return r||(r="integer"===n.type?n.minValue&&n.maxValue?`Entre ${n.minValue} y ${n.maxValue}`:n.minValue?`Mínimo ${n.minValue}`:n.maxValue?`Máximo ${n.maxValue}`:"Introduce un número":e.toLowerCase().includes("query")||e.toLowerCase().includes("search")||e.toLowerCase().includes("term")?"Buscar imágenes...":`Introduce ${(n.label||e).toLowerCase()}`),K.jsxs("div",{className:"flex flex-col gap-1",children:[K.jsxs("label",{htmlFor:`stock-${e}`,className:"text-xs font-medium text-brand-blue-900",children:[n.label||e,n.required&&K.jsx("span",{className:"text-red-600 ml-1",children:"*"})]}),n.options&&n.multiple?K.jsx("div",{className:"flex flex-wrap gap-2 min-h-[50px] px-2 justify-between border-2 border-gray-transparent-500 rounded-lg",children:n.options.map(n=>K.jsxs("label",{className:"flex items-center gap-1",children:[K.jsx("input",{type:"checkbox",name:`stock-${e}`,value:n,checked:Array.isArray(s[e])&&s[e].includes(n),onChange:()=>((e,t)=>{c(n=>{const r=Array.isArray(n[e])?n[e]:[];return r.includes(t)?{...n,[e]:r.filter(e=>e!==t)}:{...n,[e]:[...r,t]}})})(e,n),disabled:t}),K.jsx("span",{className:"text-xs",children:n})]},n))}):n.options?K.jsx("select",{id:`stock-${e}`,name:e,value:s[e]??"",onChange:T,className:"limbo-input",disabled:t,title:n.label||e,children:n.options.map(e=>K.jsx("option",{value:e,children:e},e))}):K.jsx("input",{id:`stock-${e}`,type:"integer"===n.type?"number":"text",name:e,value:s[e]??"",onChange:T,className:"limbo-input",disabled:t,required:n.required,min:n.minValue,max:n.maxValue,placeholder:r,title:n.label||e})]},e)})}),K.jsx("button",{type:"submit",disabled:v||t,className:"limbo-btn w-full mt-2 "+(v?"cursor-not-allowed limbo-btn-disabled":"limbo-btn-primary"),style:{minHeight:44},children:v?"Buscando...":"Buscar imágenes"})]})})(),k&&K.jsx("div",{className:"alert alert-danger",children:k}),u.length>0&&K.jsxs(K.Fragment,{children:[K.jsxs("div",{className:"mt-6 grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 relative","aria-live":"polite",children:[v&&K.jsx("div",{className:"absolute inset-0 bg-white/80 z-10 flex items-center justify-center rounded-lg",children:K.jsxs("div",{className:"flex flex-col items-center gap-2",children:[K.jsx("span",{className:"limbo-loader"}),K.jsx("span",{className:"text-sm text-brand-blue-800",children:"Buscando imágenes..."})]})}),u.map((e,n)=>K.jsxs("div",{className:"border border-brand-blue-200 rounded-lg overflow-hidden bg-white shadow-sm hover:shadow-md transition-shadow",children:[K.jsxs("div",{className:"relative aspect-video bg-neutral-100",children:[K.jsx("img",{src:e.preview||e.thumbnail||e.url,alt:e.title||`Resultado ${n+1}`,className:"object-cover w-full h-full",loading:"lazy"}),e.id&&K.jsxs("span",{className:"absolute bottom-1 right-1 bg-black/60 text-white text-xs px-2 py-1 rounded",children:["ID: ",e.id]})]}),K.jsx("div",{className:"p-2",children:K.jsx("button",{className:"limbo-btn w-full text-sm "+(S===e.id?"limbo-btn-disabled cursor-not-allowed":"limbo-btn-primary"),onClick:()=>j(e),disabled:v||t||S===e.id,children:S===e.id?K.jsxs(K.Fragment,{children:[K.jsx("span",{className:"limbo-loader limbo-loader--sm mr-1"}),"Descargando..."]}):"Seleccionar"})})]},e.id||n))]}),g&&K.jsxs("div",{className:"mt-6 flex items-center justify-center gap-2",children:[K.jsxs("button",{onClick:()=>z(g.current_page-1),disabled:g.current_page<=1||v,className:"limbo-btn limbo-btn-secondary px-4 py-2 disabled:opacity-25"+(g.current_page<=1||v?" pointer-events-none cursor-default":" limbo-btn-primary"),children:[K.jsx("span",{className:"icon icon-arrow-left-white icon--sm"})," ","Anterior"]}),K.jsxs("span",{className:"px-4 py-2 text-sm text-neutral-700",children:["Página ",g.current_page," de"," ",Math.max(1,Math.ceil(g.total/g.per_page)),K.jsxs("span",{className:"text-xs text-neutral-500 block",children:["(",g.total," imágenes totales)"]})]}),K.jsxs("button",{onClick:()=>z(g.current_page+1),disabled:v||g.current_page>=Math.ceil(g.total/g.per_page),className:"limbo-btn limbo-btn-secondary px-4 py-2 disabled:opacity-25"+(v||g.current_page>=Math.ceil(g.total/g.per_page)?" pointer-events-none cursor-default":" limbo-btn-primary"),children:["Siguiente"," ",K.jsx("span",{className:"icon icon-arrow-right-white icon--sm"})]})]})]}),!v&&0===u.length&&i&&s.query&&K.jsxs("div",{className:"mt-6 text-center text-neutral-600 py-8 bg-neutral-50 rounded-lg",children:[K.jsx("span",{className:"icon icon-search icon--lg mb-2"}),K.jsxs("p",{children:['No se encontraron imágenes para "',s.query,'"']}),K.jsx("p",{className:"text-sm mt-1",children:"Intenta con otros términos de búsqueda"})]})]}):K.jsx("div",{className:"alert alert-warning",children:"No hay servicios de Stock disponibles."})}const Te="/api";const Ne=new Map;function Pe(e=!1){const[t,n]=p.useState([]),[r,a]=p.useState(!0),[o,i]=p.useState(null);p.useEffect(()=>{const t=`portal-sources-${e}`,r=Ne.get(t),o=Date.now();if(r&&o-r.timestamp<864e5)return n(r.data),void a(!1);let l=!0;return(async()=>{try{const r=await function(e=!1){return te({endpoint:"/external/sources",prod:e,basePath:Te})}(e);if(!l)return;const a=r?.data?.sources||{},i=Object.entries(a).map(([e,t])=>({id:e,...t}));n(i),Ne.set(t,{data:i,timestamp:o})}catch(r){l&&i(r.message)}finally{l&&a(!1)}})(),()=>{l=!1}},[e]);return{sources:t,loading:r,error:o,invalidateCache:()=>{Ne.delete(`portal-sources-${e}`)}}}const Re=({src:e,alt:t,className:n,onError:r})=>{const[a,o]=h.useState("loading");return"error"===a?null:K.jsx("img",{src:e,alt:t,className:n,loading:"lazy",onLoad:()=>{o("loaded")},onError:()=>{o("error"),r&&r()}})};function ze({prod:e,disabled:t,onSelected:n}){const r=h.useRef(null),a=Pe(e),o=(e,t)=>{try{const n=sessionStorage.getItem(`limbo_portals_${e}`);return n?JSON.parse(n):t}catch{return t}},[i,l]=p.useState(()=>o("selectedPortals",[])),[s,c]=p.useState(()=>o("searchName","")),[u,d]=p.useState(()=>o("limit",20)),[f,m]=p.useState(()=>o("currentPage",1)),[g,b]=p.useState(!1),[y,v]=p.useState(null),[w,k]=p.useState(()=>o("images",[])),[x,S]=p.useState(()=>o("portalResults",{})),[C,E]=p.useState(()=>o("paginationInfo",null)),[_,T]=p.useState(null),N=p.useRef({}),[P,R]=p.useState(new Set);h.useEffect(()=>{sessionStorage.setItem("limbo_portals_selectedPortals",JSON.stringify(i))},[i]),h.useEffect(()=>{sessionStorage.setItem("limbo_portals_searchName",JSON.stringify(s))},[s]),h.useEffect(()=>{sessionStorage.setItem("limbo_portals_limit",JSON.stringify(u))},[u]),h.useEffect(()=>{sessionStorage.setItem("limbo_portals_currentPage",JSON.stringify(f))},[f]),h.useEffect(()=>{sessionStorage.setItem("limbo_portals_images",JSON.stringify(w))},[w]),h.useEffect(()=>{sessionStorage.setItem("limbo_portals_portalResults",JSON.stringify(x))},[x]),h.useEffect(()=>{sessionStorage.setItem("limbo_portals_paginationInfo",JSON.stringify(C))},[C]);const z=async(t=1)=>{if(0===i.length)return void v("Selecciona al menos un portal");const n=((e,t,n,r)=>`${e.sort().join(",")}_${t}_${n}_${r}`)(i,s.trim(),u,t),a=N.current[n];if(a)return k(a.images),S(a.portalResults),E(a.paginationInfo),m(t),void v(null);b(!0),v(null),1===t&&(k([]),S({}),E(null));try{let a;1===t?(a={sources:i,limit:u,page:t,name:s.trim()},r.current={...a}):a={...r.current,page:t};const o=await function(e,t=!1){return te({endpoint:"/external/search",method:"POST",body:e,prod:t,basePath:Te})}(a,e),l=o?.data?.sources||{},c=[],d={},f=new Set;let p=null;Object.entries(l).forEach(([e,t])=>{d[e]={title:t.meta?.title||e,status:200,response:"OK",count:t.images?.length||0},Array.isArray(t.images)&&(t.images.forEach(n=>{const r=n.url||n.thumbnail;r&&!f.has(r)&&(f.add(r),c.push({...n,source:e,sourceTitle:t.meta?.title||e,preview:n.thumbnail||n.url,full:n.url}))}),!p&&t.pagination&&(p=t.pagination))}),N.current[n]={images:c,portalResults:d,paginationInfo:p},k(c),S(d),E(p),m(t),R(new Set),0!==c.length||o?.result?.success||v(o?.result?.message||"No se encontraron imágenes")}catch(o){v(o.message||"Error al buscar imágenes en portales")}finally{b(!1)}},j=e=>{e<1||z(e)};return a.loading?K.jsxs("div",{className:"flex items-center justify-center py-8",children:[K.jsx("span",{className:"limbo-loader mr-2"})," Cargando portales disponibles..."]}):a.sources.length?K.jsxs("div",{className:"flex flex-col gap-4",children:[K.jsx("h3",{className:"text-lg font-semibold text-brand-blue-1000",children:"Buscar en Portales Externos"}),K.jsxs("form",{onSubmit:e=>{e.preventDefault(),z(1)},className:"flex flex-col gap-4 border-t-1 pt-4 border-brand-blue-200",children:[K.jsxs("div",{className:"flex flex-col gap-2",children:[K.jsxs("div",{className:"flex items-center justify-between",children:[K.jsxs("label",{className:"text-sm font-medium text-brand-blue-1000",children:["Portales (",i.length," seleccionados)"]}),K.jsx("button",{type:"button",onClick:()=>{i.length===a.sources.length?l([]):l(a.sources.map(e=>e.id))},className:"text-xs text-brand-blue-800 hover:underline",children:i.length===a.sources.length?"Deseleccionar todos":"Seleccionar todos"})]}),K.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2",children:a.sources.map(e=>K.jsxs("label",{className:"flex items-center gap-2 p-2 border border-brand-blue-200 rounded cursor-pointer hover:bg-brand-blue-050 transition",children:[K.jsx("input",{type:"checkbox",checked:i.includes(e.id),onChange:()=>{return t=e.id,void l(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t]);var t},disabled:t,className:"w-4 h-4"}),K.jsx("span",{className:"text-sm",children:e.title})]},e.id))})]}),K.jsxs("div",{className:"flex flex-col gap-1",children:[K.jsx("label",{htmlFor:"portal-search-name",className:"text-sm font-medium text-brand-blue-1000",children:"Buscar por nombre (opcional)"}),K.jsx("input",{id:"portal-search-name",type:"text",value:s,onChange:e=>c(e.target.value),className:"limbo-input",placeholder:"Deja vacío para ver todas las imágenes",disabled:t})]}),K.jsxs("div",{className:"flex flex-col gap-1",children:[K.jsx("label",{htmlFor:"portal-limit",className:"text-sm font-medium text-brand-blue-1000",children:"Imágenes por página"}),K.jsxs("select",{id:"portal-limit",value:u,onChange:e=>d(Number(e.target.value)),className:"limbo-input",disabled:t,children:[K.jsx("option",{value:10,children:"10"}),K.jsx("option",{value:20,children:"20"}),K.jsx("option",{value:50,children:"50"}),K.jsx("option",{value:100,children:"100"})]})]}),K.jsx("button",{type:"submit",disabled:g||t||0===i.length,className:"limbo-btn w-full "+(g||0===i.length?"cursor-not-allowed limbo-btn-disabled":"limbo-btn-primary"),style:{minHeight:44},children:g?"Buscando...":"Buscar imágenes"})]}),a.error&&K.jsx("div",{className:"alert alert-danger",children:a.error}),y&&K.jsx("div",{className:"alert alert-danger",children:y}),Object.keys(x).length>0&&K.jsxs("div",{className:"bg-neutral-50 rounded-lg p-3",children:[K.jsx("h4",{className:"text-sm font-semibold mb-2",children:"Resultados por portal:"}),K.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2 text-sm",children:Object.entries(x).map(([e,t])=>K.jsxs("div",{className:"flex items-center justify-between p-2 rounded "+(200===t.status?"bg-green-50":"bg-red-50"),children:[K.jsx("span",{className:"font-medium",children:t.title}),K.jsx("span",{className:200===t.status?"text-green-700":"text-red-700",children:200===t.status?`${t.count} imágenes`:t.response})]},e))})]}),(w.length>0||g)&&K.jsxs(K.Fragment,{children:[K.jsxs("div",{className:"mt-6 relative","aria-live":"polite",children:[g&&K.jsx("div",{className:"absolute inset-0 bg-white/80 z-10 flex items-center justify-center rounded-lg",children:K.jsxs("div",{className:"flex flex-col items-center gap-2",children:[K.jsx("span",{className:"limbo-loader"}),K.jsx("span",{className:"text-sm text-brand-blue-800",children:"Buscando imágenes..."})]})}),K.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 "+(g?"opacity-50":""),children:w.map((r,a)=>{const o=`${r.source}-${r.id||a}`,i=r.preview||r.thumbnail||r.url||r.full;return P.has(o)?null:K.jsxs("div",{className:"border border-brand-blue-200 rounded-lg overflow-hidden bg-white shadow-sm hover:shadow-md transition-shadow",children:[K.jsxs("div",{className:"relative aspect-video bg-neutral-100",children:[K.jsx(Re,{src:i,alt:r.title||r.filename||`Imagen ${a+1}`,className:"object-cover w-full h-full",onError:()=>{R(e=>{const t=new Set(e);return t.add(o),t})}}),K.jsx("span",{className:"absolute top-1 left-1 bg-black/60 text-white text-xs px-2 py-1 rounded",children:r.sourceTitle}),r.id&&K.jsxs("span",{className:"absolute bottom-1 right-1 bg-black/60 text-white text-xs px-2 py-1 rounded",children:["ID: ",r.id]})]}),K.jsxs("div",{className:"p-2",children:[r.title&&K.jsx("p",{className:"text-xs text-neutral-700 mb-1 truncate",title:r.title,children:r.title}),K.jsx("button",{className:"limbo-btn w-full text-sm "+(_===(r.url||r.full)?"limbo-btn-disabled cursor-not-allowed":"limbo-btn-primary"),onClick:()=>(async t=>{T(t.url||t.full),v(null);try{const r=t.full||t.url||t.preview;if(!r)throw new Error("No se encontró URL de la imagen");const a=`${ee({prod:e})}/api/atenea/proxy?url=${encodeURIComponent(r)}`,o=await fetch(a);if(!o.ok)throw new Error(`Error al descargar: ${o.status}`);const i=await o.blob(),l=t.filename||t.title||`portal-${t.id||Date.now()}.jpg`,s=new File([i],l,{type:i.type||"image/jpeg"});n&&n(s)}catch(r){v(r.message||"No se pudo recuperar la imagen del portal")}finally{T(null)}})(r),disabled:g||t||_===(r.url||r.full),children:_===(r.url||r.full)?K.jsxs(K.Fragment,{children:[K.jsx("span",{className:"limbo-loader limbo-loader--sm mr-1"}),"Descargando..."]}):"Seleccionar"})]})]},o)})})]}),K.jsxs("div",{className:"mt-6 flex items-center justify-center gap-2",children:[K.jsxs("button",{onClick:()=>j(f-1),disabled:1===f||g,className:"limbo-btn limbo-btn-secondary px-4 py-2 disabled:opacity-25"+(1===f||g?" pointer-events-none cursor-default":" limbo-btn-primary"),children:[K.jsx("span",{className:"icon icon-arrow-left-white icon--sm"})," ","Anterior"]}),K.jsxs("span",{className:"px-4 py-2 text-sm text-neutral-700",children:["Página ",f,C&&K.jsxs(K.Fragment,{children:[" ","de ",C.pages,K.jsxs("span",{className:"text-xs text-neutral-500 block",children:["(",C.total," imágenes totales)"]})]})]}),K.jsxs("button",{onClick:()=>j(f+1),disabled:g||C&&f>=C.pages,className:"limbo-btn limbo-btn-secondary px-4 py-2 disabled:opacity-25"+(g||C&&f>=C.pages?" pointer-events-none cursor-default":" limbo-btn-primary"),children:["Siguiente"," ",K.jsx("span",{className:"icon icon-arrow-right-white icon--sm"})]})]})]}),!g&&0===w.length&&Object.keys(x).length>0&&K.jsxs("div",{className:"mt-6 text-center text-neutral-600 py-8 bg-neutral-50 rounded-lg",children:[K.jsx("span",{className:"icon icon-search icon--lg mb-2"}),K.jsx("p",{children:"No se encontraron imágenes en los portales seleccionados"}),s&&K.jsx("p",{className:"text-sm mt-1",children:"Intenta con otros términos o sin filtro de nombre"})]})]}):K.jsx("div",{className:"alert alert-warning",children:"No hay portales externos disponibles."})}const je=[{id:"upload",label:"Subir archivo"},{id:"ai",label:"Generar con IA"},{id:"stock",label:"Buscar en Stock"},{id:"portals",label:"Otros portales"}];function Oe({onUpload:e,disabled:t=!1,apiKey:n,prod:r=!1}){const[a,o]=p.useState("upload"),[i,l]=p.useState(null),[s,c]=p.useState(null),u=p.useRef();return K.jsxs("div",{className:"limbo-upload-form p-4 border-2 border-gray-200/50 rounded-lg min-w-fit max-w-5xl mx-auto",children:[K.jsx("div",{className:"limbo-tabs-container",children:K.jsx("div",{className:"limbo-tabs mb-6 min-w-fit",role:"tablist","aria-label":"Opciones de subida de imagen",children:je.map(e=>K.jsx("button",{type:"button","data-upload-tab-id":e.id,className:"text-nowrap limbo-tab"+(a===e.id?" active":""),"aria-current":a===e.id?"page":void 0,"aria-selected":a===e.id,role:"tab",tabIndex:a===e.id?0:-1,onClick:()=>o(e.id),onKeyDown:t=>((e,t)=>{const n=je.findIndex(e=>e.id===t);let r=n;switch(e.key){case"ArrowLeft":e.preventDefault(),r=n>0?n-1:je.length-1;break;case"ArrowRight":e.preventDefault(),r=n<je.length-1?n+1:0;break;case"Home":e.preventDefault(),r=0;break;case"End":e.preventDefault(),r=je.length-1;break;case"Enter":case" ":return e.preventDefault(),void o(t);default:return}const a=je[r];a&&(o(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}`,children:e.label},e.id))})}),K.jsxs("div",{className:"limbo-tab-content",role:"tabpanel",id:`upload-tabpanel-${a}`,"aria-labelledby":`upload-tab-${a}`,children:["upload"===a&&K.jsx(ge,{file:i,setFile:l,previewUrl:s,setPreviewUrl:c,fileInputRef:u,onUpload:e,disabled:t}),"ai"===a&&K.jsx(xe,{apiKey:n,prod:r,disabled:t,onGenerated:e=>{o("upload"),l(e),c(URL.createObjectURL(e))}}),"stock"===a&&K.jsx(_e,{apiKey:n,prod:r,disabled:t,onSelected:e=>{o("upload"),l(e),c(URL.createObjectURL(e))}}),"portals"===a&&K.jsx(ze,{apiKey:n,prod:r,disabled:t,onSelected:e=>{o("upload"),l(e),c(URL.createObjectURL(e))}})]})]})}const Ae="undefined"!=typeof window&&void 0!==window.document,Le=Ae?window:{},Ie=!!Ae&&"ontouchstart"in Le.document.documentElement,Me=!!Ae&&"PointerEvent"in Le,De="cropper",$e=`${De}-canvas`,Fe=`${De}-crosshair`,Ue=`${De}-grid`,He=`${De}-handle`,We=`${De}-image`,Be=`${De}-selection`,Ve=`${De}-shade`,qe=`${De}-viewer`,Ke="select",Qe="move",Ye="scale",Ge="rotate",Xe="transform",Je="none",Ze="n-resize",et="e-resize",tt="s-resize",nt="w-resize",rt="ne-resize",at="nw-resize",ot="se-resize",it="sw-resize",lt=Me?"pointerdown":Ie?"touchstart":"mousedown",st=Me?"pointermove":Ie?"touchmove":"mousemove",ct=Me?"pointerup pointercancel":Ie?"touchend touchcancel":"mouseup",ut="error",dt="keydown",ft="load",pt="wheel",ht="action",mt="actionend",gt="actionstart",bt="change",yt="transform";const vt=Number.isNaN||Le.isNaN;function wt(e){return"number"==typeof e&&!vt(e)}function kt(e){return wt(e)&&e>0&&e<1/0}function xt(e){return"object"==typeof e&&null!==e}const{hasOwnProperty:St}=Object.prototype;function Ct(e){if(!xt(e))return!1;try{const{constructor:t}=e,{prototype:n}=t;return t&&n&&St.call(n,"isPrototypeOf")}catch(t){return!1}}function Et(e){return"function"==typeof e}function _t(e){return"object"==typeof e&&null!==e&&1===e.nodeType}const Tt=/([a-z\d])([A-Z])/g;function Nt(e){return String(e).replace(Tt,"$1-$2").toLowerCase()}const Pt=/-[A-z\d]/g;function Rt(e){return e.replace(Pt,e=>e.slice(1).toUpperCase())}const zt=/\s\s*/;function jt(e,t,n,r){t.trim().split(zt).forEach(t=>{e.removeEventListener(t,n,r)})}function Ot(e,t,n,r){t.trim().split(zt).forEach(t=>{e.addEventListener(t,n,r)})}function At(e,t,n,r){Ot(e,t,n,Object.assign(Object.assign({},r),{once:!0}))}const Lt={bubbles:!0,cancelable:!0,composed:!0};const It=Promise.resolve();function Mt(e){const{documentElement:t}=e.ownerDocument,n=e.getBoundingClientRect();return{left:n.left+(Le.pageXOffset-t.clientLeft),top:n.top+(Le.pageYOffset-t.clientTop)}}const Dt=/deg|g?rad|turn$/i;function $t(e){const t=parseFloat(e)||0;if(0!==t){const[n="rad"]=String(e).match(Dt)||[];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 Ft="contain";function Ut(e,t=Ft){const{aspectRatio:n}=e;let{width:r,height:a}=e;const o=kt(r),i=kt(a);if(o&&i){const e=a*n;t===Ft&&e>r||"cover"===t&&e<r?a=r/n:r=a*n}else o?a=r/n:i&&(r=a*n);return{width:r,height:a}}function Ht(e,...t){if(0===t.length)return e;const[n,r,a,o,i,l]=e,[s,c,u,d,f,p]=t[0];return Ht(e=[n*s+a*c,r*s+o*c,n*u+a*d,r*u+o*d,n*f+a*p+i,r*f+o*p+l],...t.slice(1))}const Wt=/left|top|width|height/i,Bt="open",Vt=new WeakMap,qt=new WeakMap,Kt=new Map,Qt=Le.document&&Array.isArray(Le.document.adoptedStyleSheets)&&"replaceSync"in Le.CSSStyleSheet.prototype;class Yt extends HTMLElement{get $sharedStyle(){return(this.themeColor?`:host{--theme-color: ${this.themeColor};}`:"")+":host([hidden]){display:none!important}"}constructor(){var e,t;super(),this.shadowRootMode=Bt,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&&Kt.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=Rt(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=qt.get(this),t=this.$sharedStyle;e&&t&&(Qt?e.replaceSync(t):e.textContent=t);break}}}$propertyChangedCallback(e,t,n){if(!Object.is(n,t))switch(e=Nt(e),typeof n){case"boolean":!0===n?this.hasAttribute(e)||this.setAttribute(e,""):this.removeAttribute(e);break;case"number":n=vt(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=Rt(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.attachShadow({mode:this.shadowRootMode||Bt});if(this.shadowRoot||Vt.set(this,e),qt.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(){qt.has(this)&&qt.delete(this),Vt.has(this)&&Vt.delete(this)}$getTagNameOf(e){var t;return null!==(t=Kt.get(e))&&void 0!==t?t:e}$setStyles(e){return Object.keys(e).forEach(t=>{let n=e[t];wt(n)&&(n=0!==n&&Wt.test(t)?`${n}px`:String(n)),this.style[t]=n}),this}$getShadowRoot(){return this.shadowRoot||Vt.get(this)}$addStyles(e){let t;const n=this.$getShadowRoot();return Qt?(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({},Lt),{detail:n}),r)))}(this,e,t,n)}$nextTick(e){return function(e,t){return t?It.then(e?t.bind(e):t):It}(this,e)}static $define(e,t){xt(e)&&(t=e,e=""),e||(e=this.$name||this.name),e=Nt(e),Ae&&Le.customElements&&!Le.customElements.get(e)&&customElements.define(e,this,t)}}Yt.$version="2.0.0";class Gt extends Yt{constructor(){super(...arguments),this.$onPointerDown=null,this.$onPointerMove=null,this.$onPointerUp=null,this.$onWheel=null,this.$wheeling=!1,this.$pointers=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=Je,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),Ot(this,lt,this.$onPointerDown)),this.$onPointerMove||(this.$onPointerMove=this.$handlePointerMove.bind(this),Ot(this.ownerDocument,st,this.$onPointerMove)),this.$onPointerUp||(this.$onPointerUp=this.$handlePointerUp.bind(this),Ot(this.ownerDocument,ct,this.$onPointerUp)),this.$onWheel||(this.$onWheel=this.$handleWheel.bind(this),Ot(this,pt,this.$onWheel,{passive:!1,capture:!0}))}$unbind(){this.$onPointerDown&&(jt(this,lt,this.$onPointerDown),this.$onPointerDown=null),this.$onPointerMove&&(jt(this.ownerDocument,st,this.$onPointerMove),this.$onPointerMove=null),this.$onPointerUp&&(jt(this.ownerDocument,ct,this.$onPointerUp),this.$onPointerUp=null),this.$onWheel&&(jt(this,pt,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)&&(wt(t)&&1!==t||wt(n)&&0!==n||e.ctrlKey))return;const{$pointers:a}=this;let o="";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?o=Xe:_t(e.target)&&(o=e.target.action||e.target.getAttribute("action")||""),!1!==this.$emit(gt,{action:o,relatedEvent:e})&&(e.preventDefault(),this.$action=o,this.style.willChange="transform")}$handlePointerMove(e){const{$action:t,$pointers:n}=this;if(this.disabled||t===Je||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,o=n.get(t);o&&Object.assign(o,{endX:r,endY:a})}const r={action:t,relatedEvent:e};if(t===Xe){const t=new Map(n);let a=0,o=0,i=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,f=0,p=0,h=0,m=0;if(0===n?r<0?h=2*Math.PI:r>0&&(h=Math.PI):n>0?h=Math.PI/2+Math.atan(r/n):n<0&&(h=1.5*Math.PI+Math.atan(r/n)),0===u?d<0?m=2*Math.PI:d>0&&(m=Math.PI):u>0?m=Math.PI/2+Math.atan(d/u):u<0&&(m=1.5*Math.PI+Math.atan(d/u)),m>0||h>0){const n=m-h,r=Math.abs(n);r>a&&(a=r,i=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?f=Math.sqrt(n*n+r*r):n>0?f=n:r>0&&(f=r),u>0&&d>0?p=Math.sqrt(u*u+d*d):u>0?p=u:d>0&&(p=d),f>0&&p>0){const n=(p-f)/f,r=Math.abs(n);r>o&&(o=r,l=n,s=(e.startX+t.startX)/2,c=(e.startY+t.startY)/2)}})});const u=a>0,d=o>0;u&&d?(r.rotate=i,r.scale=l,r.centerX=s,r.centerY=c):u?(r.action=Ge,r.rotate=i,r.centerX=s,r.centerY=c):d?(r.action=Ye,r.scale=l,r.centerX=s,r.centerY=c):r.action=Je}else{const[e]=Array.from(n.values());Object.assign(r,e)}n.forEach(e=>{e.startX=e.endX,e.startY=e.endY}),r.action!==Je&&this.$emit(ht,r,{cancelable:!1})}$handlePointerUp(e){const{$action:t,$pointers:n}=this;if(!this.disabled&&t!==Je&&!1!==this.$emit(mt,{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=Je)}}$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(ht,{action:Ye,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,o=this.offsetHeight,i=1;Ct(e)&&(kt(e.width)||kt(e.height))&&(({width:a,height:o}=Ut({aspectRatio:a/o,width:e.width,height:e.height})),i=a/this.offsetWidth),r.width=a,r.height=o;const l=this.querySelector(this.$getTagNameOf(We));l?l.$ready().then(n=>{const s=r.getContext("2d");if(s){const[t,c,u,d,f,p]=l.$getTransform();let h=f,m=p,g=n.naturalWidth,b=n.naturalHeight;1!==i&&(h*=i,m*=i,g*=i,b*=i);const y=g/2,v=b/2;s.fillStyle="transparent",s.fillRect(0,0,a,o),Ct(e)&&Et(e.beforeDraw)&&e.beforeDraw.call(this,s,r),s.save(),s.translate(y,v),s.transform(t,c,u,d,h,m),s.translate(-y,-v),s.drawImage(n,0,0,g,b),s.restore()}t(r)}).catch(n):t(r)})}}Gt.$name=$e,Gt.$version="2.0.0";const Xt=new WeakMap,Jt=["alt","crossorigin","decoding","importance","loading","referrerpolicy","sizes","src","srcset"];class Zt extends Yt{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}set $canvas(e){Xt.set(this,e)}get $canvas(){return Xt.get(this)}static get observedAttributes(){return super.observedAttributes.concat(Jt,["initial-center-size","rotatable","scalable","skewable","translatable"])}attributeChangedCallback(e,t,n){Object.is(n,t)||(super.attributeChangedCallback(e,t,n),Jt.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($e));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),Ot(t,gt,this.$onCanvasActionStart),Ot(t,mt,this.$onCanvasActionEnd),Ot(t,ht,this.$onCanvasAction)),this.$onLoad=this.$handleLoad.bind(this),Ot(e,ft,this.$onLoad),this.$getShadowRoot().appendChild(e)}disconnectedCallback(){const{$image:e,$canvas:t}=this;t&&(this.$onCanvasActionStart&&(jt(t,gt,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(jt(t,mt,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasAction&&(jt(t,ht,this.$onCanvasAction),this.$onCanvasAction=null)),e&&this.$onLoad&&(jt(e,ft,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!==Xe||this.rotatable&&this.scalable||(r=this.rotatable?Ge:this.scalable?Ye:Je),r){case Qe:if(this.translatable){let r=null;e&&(r=e.target.closest(this.$getTagNameOf(Be))),r||(r=t.querySelector(this.$getTagNameOf(Be))),r&&r.multiple&&!r.active&&(r=t.querySelector(`${this.$getTagNameOf(Be)}[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 Ge: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 Ye:if(this.scalable)if(e){const t=e.target.closest(this.$getTagNameOf(Be));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 Xe: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),o=Math.sin(t),[i,l,s,c]=[a*r,o*r,-o*r,a*r];if(e){const t=this.getBoundingClientRect(),n=e.clientX-t.x,r=e.clientY-t.y,[a,o,u,d]=this.$matrix,f=n-t.width/2,p=r-t.height/2,h=(f*d-u*p)/(a*d-u*o),m=(p*a-o*f)/(a*d-u*o);this.$transform(i,l,s,c,h*(1-i)+m*s,m*(1-c)+h*l)}else this.$transform(i,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=()=>{jt(t,ut,o),e(t)},o=()=>{jt(t,ft,a),n(r)};At(t,ft,a),At(t,ut,o)}});return Et(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:o,y:i,width:l,height:s}=this.getBoundingClientRect(),c=o+l/2,u=i+s/2,d=n.x+r/2,f=n.y+a/2;if(this.$move(d-c,f-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&&wt(e)&&wt(t)){const[n,r,a,o]=this.$matrix,i=(e*o-a*t)/(n*o-a*r),l=(t*n-r*e)/(n*o-a*r);this.$translate(i,l)}return this}$moveTo(e,t=e){if(this.translatable&&wt(e)&&wt(t)){const[n,r,a,o]=this.$matrix,i=(e*o-a*t)/(n*o-a*r),l=(t*n-r*e)/(n*o-a*r);this.$setTransform(n,r,a,o,i,l)}return this}$rotate(e,t,n){if(this.rotatable){const r=$t(e),a=Math.cos(r),o=Math.sin(r),[i,l,s,c]=[a,o,-o,a];if(wt(t)&&wt(n)){const[e,r,a,o]=this.$matrix,{width:u,height:d}=this.getBoundingClientRect(),f=t-u/2,p=n-d/2,h=(f*o-a*p)/(e*o-a*r),m=(p*e-r*f)/(e*o-a*r);this.$transform(i,l,s,c,h*(1-i)-m*s,m*(1-c)-h*l)}else this.$transform(i,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,wt(t)&&wt(n)){const[r,a,o,i]=this.$matrix,{width:l,height:s}=this.getBoundingClientRect(),c=t-l/2,u=n-s/2,d=(c*i-o*u)/(r*i-o*a),f=(u*r-a*c)/(r*i-o*a);this.$transform(e,0,0,e,d*(1-e),f*(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=$t(e),r=$t(t);this.$transform(1,Math.tan(r),Math.tan(n),1,0,0)}return this}$translate(e,t=e){return this.translatable&&wt(e)&&wt(t)&&this.$transform(1,0,0,1,e,t),this}$transform(e,t,n,r,a,o){return wt(e)&&wt(t)&&wt(n)&&wt(r)&&wt(a)&&wt(o)?this.$setTransform(Ht(this.$matrix,[e,t,n,r,a,o])):this}$setTransform(e,t,n,r,a,o){if((this.rotatable||this.scalable||this.skewable||this.translatable)&&(Array.isArray(e)&&([e,t,n,r,a,o]=e),wt(e)&&wt(t)&&wt(n)&&wt(r)&&wt(a)&&wt(o))){const i=[...this.$matrix],l=[e,t,n,r,a,o];if(!1===this.$emit(yt,{matrix:l,oldMatrix:i}))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])}}Zt.$name=We,Zt.$version="2.0.0";const en=new WeakMap;class tn extends Yt{constructor(){super(...arguments),this.$onCanvasChange=null,this.$onCanvasActionEnd=null,this.$onCanvasActionStart=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){en.set(this,e)}get $canvas(){return en.get(this)}static get observedAttributes(){return super.observedAttributes.concat(["height","width","x","y"])}connectedCallback(){super.connectedCallback();const e=this.closest(this.$getTagNameOf($e));if(e){this.$canvas=e,this.style.position="absolute";const t=e.querySelector(this.$getTagNameOf(Be));t&&(this.$onCanvasActionStart=e=>{t.hidden&&e.detail.action===Ke&&(this.hidden=!1)},this.$onCanvasActionEnd=e=>{t.hidden&&e.detail.action===Ke&&(this.hidden=!0)},this.$onCanvasChange=e=>{const{x:n,y:r,width:a,height:o}=e.detail;this.$change(n,r,a,o),(t.hidden||0===n&&0===r&&0===a&&0===o)&&(this.hidden=!0)},Ot(e,gt,this.$onCanvasActionStart),Ot(e,mt,this.$onCanvasActionEnd),Ot(e,bt,this.$onCanvasChange))}this.$render()}disconnectedCallback(){const{$canvas:e}=this;e&&(this.$onCanvasActionStart&&(jt(e,gt,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(jt(e,mt,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasChange&&(jt(e,bt,this.$onCanvasChange),this.$onCanvasChange=null)),super.disconnectedCallback()}$change(e,t,n=this.width,r=this.height){return wt(e)&&wt(t)&&wt(n)&&wt(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:Le.innerWidth})}}tn.$name=Ve,tn.$version="2.0.0";class nn extends Yt{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=Je,this.plain=!1,this.slottable=!1,this.themeColor="rgba(51, 153, 255, 0.5)"}static get observedAttributes(){return super.observedAttributes.concat(["action","plain"])}}nn.$name=He,nn.$version="2.0.0";const rn=new WeakMap;class an extends Yt{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){rn.set(this,e)}get $canvas(){return rn.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(()=>{kt(n)&&n<=1&&this.$initSelection(!0,!0)});break;case"keyboard":this.$nextTick(()=>{this.$canvas&&(n?this.$onDocumentKeyDown||(this.$onDocumentKeyDown=this.$handleKeyDown.bind(this),Ot(this.ownerDocument,dt,this.$onDocumentKeyDown)):this.$onDocumentKeyDown&&(jt(this.ownerDocument,dt,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(bt,{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($e));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),Ot(e,gt,this.$onCanvasActionStart),Ot(e,mt,this.$onCanvasActionEnd),Ot(e,ht,this.$onCanvasAction)):this.$render()}disconnectedCallback(){const{$canvas:e}=this;e&&(this.$onCanvasActionStart&&(jt(e,gt,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(jt(e,mt,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasAction&&(jt(e,ht,this.$onCanvasAction),this.$onCanvasAction=null)),super.disconnectedCallback()}$getSelections(){let e=[];return this.parentElement&&(e=Array.from(this.parentElement.querySelectorAll(this.$getTagNameOf(Be)))),e}$initSelection(e=!1,t=!1){const{initialCoverage:n,parentElement:r}=this;if(kt(n)&&r){const a=this.aspectRatio||this.initialAspectRatio;let o=(t?0:this.width)||r.offsetWidth*n,i=(t?0:this.height)||r.offsetHeight*n;kt(a)&&({width:o,height:i}=Ut({aspectRatio:a,width:o,height:i})),this.$change(this.x,this.y,o,i),e&&this.$center(),this.$initialSelection={x:this.x,y:this.y,width:this.width,height:this.height}}}$createSelection(){const e=this.cloneNode(!0);return this.hasAttribute("id")&&e.removeAttribute("id"),e.initialCoverage=NaN,this.active=!1,this.parentElement&&this.parentElement.insertBefore(e,this.nextSibling),e}$removeSelection(e=this){if(this.parentElement){const t=this.$getSelections();if(t.length>1){const n=t.indexOf(e),r=t[n+1]||t[n-1];r&&(e.active=!1,this.parentElement.removeChild(e),r.active=!0,r.$emit(bt,{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(bt,{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;if(!a&&this.multiple&&(a=this.$action||(null==r?void 0:r.target.action),this.$action=a),!a||this.hidden&&a!==Ke||this.multiple&&!this.active&&a!==Ye)return;const o=n.endX-n.startX,i=n.endY-n.startY,{width:l,height:s}=this;let{aspectRatio:c}=this;switch(!kt(c)&&r.shiftKey&&(c=kt(l)&&kt(s)?l/s:1),a){case Ke:if(0!==o&&0!==i){const{$canvas:e}=this,r=Mt(t);(this.multiple&&!this.hidden?this.$createSelection():this).$change(n.startX-r.left,n.startY-r.top,Math.abs(o),Math.abs(i),c),o<0?i<0?a=at:i>0&&(a=it):o>0&&(i<0?a=rt:i>0&&(a=ot)),e&&(e.$action=a)}break;case Qe:this.movable&&(this.dynamic||this.$actionStartTarget&&this.contains(this.$actionStartTarget))&&this.$move(o,i);break;case Ye:if(r&&this.zoomable&&(this.dynamic||this.contains(r.target))){const e=Mt(t);this.$zoom(n.scale,r.pageX-e.left,r.pageY-e.top)}break;default:this.$resize(a,o,i,c)}}$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=kt(r),{$canvas:o}=this;let{x:i,y:l,width:s,height:c}=this;switch(e){case Ze:l+=n,c-=n,c<0&&(e=tt,c=-c,l-=c),a&&(i+=(t=n*r)/2,s-=t,s<0&&(s=-s,i-=s));break;case et:s+=t,s<0&&(e=nt,s=-s,i-=s),a&&(l-=(n=t/r)/2,c+=n,c<0&&(c=-c,l-=c));break;case tt:c+=n,c<0&&(e=Ze,c=-c,l-=c),a&&(i-=(t=n*r)/2,s+=t,s<0&&(s=-s,i-=s));break;case nt:i+=t,s-=t,s<0&&(e=et,s=-s,i-=s),a&&(l+=(n=t/r)/2,c-=n,c<0&&(c=-c,l-=c));break;case rt:a&&(n=-t/r),l+=n,c-=n,s+=t,s<0&&c<0?(e=it,s=-s,c=-c,i-=s,l-=c):s<0?(e=at,s=-s,i-=s):c<0&&(e=ot,c=-c,l-=c);break;case at:a&&(n=t/r),i+=t,l+=n,s-=t,c-=n,s<0&&c<0?(e=ot,s=-s,c=-c,i-=s,l-=c):s<0?(e=rt,s=-s,i-=s):c<0&&(e=it,c=-c,l-=c);break;case ot:a&&(n=t/r),s+=t,c+=n,s<0&&c<0?(e=at,s=-s,c=-c,i-=s,l-=c):s<0?(e=it,s=-s,i-=s):c<0&&(e=rt,c=-c,l-=c);break;case it:a&&(n=-t/r),i+=t,s-=t,c+=n,s<0&&c<0?(e=rt,s=-s,c=-c,i-=s,l-=c):s<0?(e=ot,s=-s,i-=s):c<0&&(e=at,c=-c,l-=c)}return o&&o.$setAction(e),this.$change(i,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,o=r*e,i=a*e;let l=this.x,s=this.y;return wt(t)&&wt(n)?(l-=(o-r)*((t-this.x)/r),s-=(i-a)*((n-this.y)/a)):(l-=(o-r)/2,s-=(i-a)/2),this.$change(l,s,o,i)}$change(e,t,n=this.width,r=this.height,a=this.aspectRatio,o=!1){return this.$changing||!wt(e)||!wt(t)||!wt(n)||!wt(r)||n<0||r<0?this:(kt(a)&&({width:n,height:r}=Ut({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)&&!o?this:(this.hidden&&(this.hidden=!1),!1===this.$emit(bt,{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:o}=this,i=1;if(Ct(e)&&(kt(e.width)||kt(e.height))&&(({width:a,height:o}=Ut({aspectRatio:a/o,width:e.width,height:e.height})),i=a/this.width),r.width=a,r.height=o,!this.$canvas)return void t(r);const l=this.$canvas.querySelector(this.$getTagNameOf(We));l?l.$ready().then(n=>{const s=r.getContext("2d");if(s){const[t,c,u,d,f,p]=l.$getTransform(),h=-this.x,m=-this.y,g=(h*d-u*m)/(t*d-u*c),b=(m*t-c*h)/(t*d-u*c);let y=t*g+u*b+f,v=c*g+d*b+p,w=n.naturalWidth,k=n.naturalHeight;1!==i&&(y*=i,v*=i,w*=i,k*=i);const x=w/2,S=k/2;s.fillStyle="transparent",s.fillRect(0,0,a,o),Ct(e)&&Et(e.beforeDraw)&&e.beforeDraw.call(this,s,r),s.save(),s.translate(x,S),s.transform(t,c,u,d,y,v),s.translate(-x,-S),s.drawImage(n,0,0,w,k),s.restore()}t(r)}).catch(n):t(r)})}}an.$name=Be,an.$version="2.0.0";class on extends Yt{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))}}on.$name=Ue,on.$version="2.0.0";class ln extends Yt{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"])}}ln.$name=Fe,ln.$version="2.0.0";const sn=new WeakMap,cn=new WeakMap,un=new WeakMap,dn=new WeakMap,fn="vertical";class pn extends Yt{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=fn,this.selection="",this.slottable=!1}set $image(e){cn.set(this,e)}get $image(){return cn.get(this)}set $sourceImage(e){dn.set(this,e)}get $sourceImage(){return dn.get(this)}set $canvas(e){sn.set(this,e)}get $canvas(){return sn.get(this)}set $selection(e){un.set(this,e)}get $selection(){return un.get(this)}static get observedAttributes(){return super.observedAttributes.concat(["resize","selection"])}connectedCallback(){super.connectedCallback();let e=null;if(e=this.selection?this.ownerDocument.querySelector(this.selection):this.closest(this.$getTagNameOf(Be)),_t(e)){this.$selection=e,this.$onSelectionChange=this.$handleSelectionChange.bind(this),Ot(e,bt,this.$onSelectionChange);const t=e.closest(this.$getTagNameOf($e));if(t){this.$canvas=t;const e=t.querySelector(this.$getTagNameOf(We));e&&(this.$sourceImage=e,this.$image=e.cloneNode(!0),this.$getShadowRoot().appendChild(this.$image),this.$onSourceImageLoad=this.$handleSourceImageLoad.bind(this),this.$onSourceImageTransform=this.$handleSourceImageTransform.bind(this),Ot(e.$image,ft,this.$onSourceImageLoad),Ot(e,yt,this.$onSourceImageTransform))}this.$render()}}disconnectedCallback(){const{$selection:e,$sourceImage:t}=this;e&&this.$onSelectionChange&&(jt(e,bt,this.$onSelectionChange),this.$onSelectionChange=null),t&&this.$onSourceImageLoad&&(jt(t.$image,ft,this.$onSourceImageLoad),this.$onSourceImageLoad=null),t&&this.$onSourceImageTransform&&(jt(t,yt,this.$onSourceImageTransform),this.$onSourceImageTransform=null),super.disconnectedCallback()}$handleSelectionChange(e){this.$render(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(()=>{setTimeout(()=>{this.$render()},50)}))}$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:o,width:i,height:l}=e,s={},{clientWidth:c,clientHeight:u}=this;let d=c,f=u,p=NaN;switch(this.resize){case"both":p=1,d=i,f=l,s.width=i,s.height=l;break;case"horizontal":p=l>0?u/l:0,d=i*p,s.width=d;break;case fn:p=i>0?c/i:0,f=l*p,s.height=f;break;default:c>0?p=i>0?c/i:0:u>0&&(p=l>0?u/l:0)}this.$scale=p,this.$setStyles(s),this.$sourceImage&&this.$transformImageByOffset(null!=t?t:this.$sourceImage.$getTransform(),-a,-o)}$transformImageByOffset(e,t,n){const{$image:r,$scale:a,$sourceImage:o}=this;if(o&&r&&a>=0){const[o,i,l,s,c,u]=e,d=(t*s-l*n)/(o*s-l*i),f=(n*o-i*t)/(o*s-l*i),p=o*d+l*f+c,h=i*d+s*f+u;r.$ready(e=>{this.$setStyles.call(r,{width:e.naturalWidth*a,height:e.naturalHeight*a})}),r.$setTransform(o,i,l,s,p*a,h*a)}}}function hn(){const[e,t]=p.useState(!1),[n,r]=p.useState(null),[a,o]=p.useState(null),i=async(e,a)=>{if(!e||!a)return r("ID de asset y configuración de variante son requeridos"),null;t(!0),r(null),o(null);try{const t=await async function(e,{variant_name:t,width:r,height:a,crop_params:o,preset_aspect:i=null,preset_size:l=null,output_format:s="webp"}){try{const n=[{name:t,width:r,height:a,output_format:s,crop_params:o}];return i&&(n[0].preset_aspect=i),l&&(n[0].preset_size=l),function(e){if(!e?.success||!e?.data)return{result:null};const t=e.data;return{result:{job_id:t.job_id,asset_id:t.asset_id,variants_requested:t.variants_requested||[],processing_mode:t.async?"async":"sync",estimated_completion:t.estimated_completion,variant_statuses:(t.variant_statuses||[]).map(e=>({name:e.name,status:e.status,size:e.expected_size,format:e.format}))}}}(await te({endpoint:`/assets/${e}/variants`,method:"POST",body:{variants:n,async:!1},basePath:ie,useJWT:!0}))}catch(n){throw oe(n)}}(e,{variant_name:a.name,width:a.width,height:a.height,crop_params:a.crop_params,preset_aspect:a.preset_aspect,preset_size:a.preset_size,output_format:a.output_format});if(t?.result)return o(t.result),t.result;throw new Error("No se pudo crear la variante")}catch(i){return console.error("Error creating variant:",i),r(i.message||"Error desconocido al crear variante"),null}finally{t(!1)}};return{createVariant:i,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 i(e,r)},loading:e,error:n,createdVariant:a,reset:()=>{r(null),o(null)}}}pn.$name=qe,pn.$version="2.0.0",
55
+ */function q(){return W||(W=1,"production"!==process.env.NODE_ENV&&function(){function e(t){if(null==t)return null;if("function"==typeof t)return t.$$typeof===C?null:t.displayName||t.name||null;if("string"==typeof t)return t;switch(t){case p:return"Fragment";case m:return"Profiler";case h:return"StrictMode";case v:return"Suspense";case w:return"SuspenseList";case S:return"Activity"}if("object"==typeof t)switch("number"==typeof t.tag&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),t.$$typeof){case d:return"Portal";case b:return(t.displayName||"Context")+".Provider";case g:return(t._context.displayName||"Context")+".Consumer";case y:var n=t.render;return(t=t.displayName)||(t=""!==(t=n.displayName||n.name||"")?"ForwardRef("+t+")":"ForwardRef"),t;case k:return null!==(n=t.displayName||null)?n:e(t.type)||"Memo";case x:n=t._payload,t=t._init;try{return e(t(n))}catch(r){}}return null}function t(e){return""+e}function n(e){try{t(e);var n=!1}catch(o){n=!0}if(n){var r=(n=console).error,a="function"==typeof Symbol&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return r.call(n,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",a),t(e)}}function r(t){if(t===p)return"<>";if("object"==typeof t&&null!==t&&t.$$typeof===x)return"<...>";try{var n=e(t);return n?"<"+n+">":"<...>"}catch(r){return"<...>"}}function a(){return Error("react-stack-top-frame")}function o(){var t=e(this.type);return P[t]||(P[t]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),void 0!==(t=this.props.ref)?t:null}function i(t,r,a,i,c,d,f,p){var h,m=r.children;if(void 0!==m)if(i)if(T(m)){for(i=0;i<m.length;i++)l(m[i]);Object.freeze&&Object.freeze(m)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else l(m);if(_.call(r,"key")){m=e(t);var g=Object.keys(r).filter(function(e){return"key"!==e});i=0<g.length?"{key: someKey, "+g.join(": ..., ")+": ...}":"{key: someKey}",j[m+i]||(g=0<g.length?"{"+g.join(": ..., ")+": ...}":"{}",console.error('A props object containing a "key" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />',i,m,g,m),j[m+i]=!0)}if(m=null,void 0!==a&&(n(a),m=""+a),function(e){if(_.call(e,"key")){var t=Object.getOwnPropertyDescriptor(e,"key").get;if(t&&t.isReactWarning)return!1}return void 0!==e.key}(r)&&(n(r.key),m=""+r.key),"key"in r)for(var b in a={},r)"key"!==b&&(a[b]=r[b]);else a=r;return m&&function(e,t){function n(){s||(s=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",t))}n.isReactWarning=!0,Object.defineProperty(e,"key",{get:n,configurable:!0})}(a,"function"==typeof t?t.displayName||t.name||"Unknown":t),function(e,t,n,r,a,i,l,s){return n=i.ref,e={$$typeof:u,type:e,key:t,props:i,_owner:a},null!==(void 0!==n?n:null)?Object.defineProperty(e,"ref",{enumerable:!1,get:o}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:l}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:s}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}(t,m,d,0,null===(h=E.A)?null:h.getOwner(),a,f,p)}function l(e){"object"==typeof e&&null!==e&&e.$$typeof===u&&e._store&&(e._store.validated=1)}var s,c=f(),u=Symbol.for("react.transitional.element"),d=Symbol.for("react.portal"),p=Symbol.for("react.fragment"),h=Symbol.for("react.strict_mode"),m=Symbol.for("react.profiler"),g=Symbol.for("react.consumer"),b=Symbol.for("react.context"),y=Symbol.for("react.forward_ref"),v=Symbol.for("react.suspense"),w=Symbol.for("react.suspense_list"),k=Symbol.for("react.memo"),x=Symbol.for("react.lazy"),S=Symbol.for("react.activity"),C=Symbol.for("react.client.reference"),E=c.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,_=Object.prototype.hasOwnProperty,T=Array.isArray,N=console.createTask?console.createTask:function(){return null},P={},R=(c={react_stack_bottom_frame:function(e){return e()}}).react_stack_bottom_frame.bind(c,a)(),z=N(r(a)),j={};V.Fragment=p,V.jsx=function(e,t,n,a,o){var l=1e4>E.recentlyCreatedOwnerStacks++;return i(e,t,n,!1,0,o,l?Error("react-stack-top-frame"):R,l?N(r(e)):z)},V.jsxs=function(e,t,n,a,o){var l=1e4>E.recentlyCreatedOwnerStacks++;return i(e,t,n,!0,0,o,l?Error("react-stack-top-frame"):R,l?N(r(e)):z)}}()),V}var K=(B||(B=1,"production"===process.env.NODE_ENV?U.exports=function(){if($)return H;$=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(t,n,r){var a=null;if(void 0!==r&&(a=""+r),void 0!==n.key&&(a=""+n.key),"key"in n)for(var o in r={},n)"key"!==o&&(r[o]=n[o]);else r=n;return n=r.ref,{$$typeof:e,type:t,key:a,ref:void 0!==n?n:null,props:r}}return H.Fragment=t,H.jsx=n,H.jsxs=n,H}():U.exports=q()),U.exports);const Q=new class{constructor(){this.supportsContainerQueries=this.detectContainerQueries(),this.init()}detectContainerQueries(){if("undefined"==typeof window)return!1;try{if("CSS"in window&&"supports"in window.CSS)return window.CSS.supports("container-type","inline-size");const e=document.createElement("div");return e.style.containerType="inline-size","inline-size"===e.style.containerType}catch{return!1}}init(){"undefined"!=typeof window&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>this.applyClasses()):this.applyClasses())}applyClasses(){document.querySelectorAll(".limbo-component-container-wrapper").forEach(e=>{this.supportsContainerQueries?(e.classList.add("container-queries-supported"),e.classList.remove("container-queries-fallback")):(e.classList.add("container-queries-fallback"),e.classList.remove("container-queries-supported"))}),this.supportsContainerQueries?(document.body.classList.add("container-queries-supported"),document.body.classList.remove("container-queries-fallback")):(document.body.classList.add("container-queries-fallback"),document.body.classList.remove("container-queries-supported"))}getContainerWidth(e){if(!e)return window.innerWidth;let t=e.closest(".limbo-component-container-wrapper");return t||(t=e.closest(".limbo-modal-content")),t||(t=e.closest(".limbo-modal")),t||(t=document.body),t.offsetWidth||t.clientWidth}shouldUseMobileStyles(e,t=768){return this.getContainerWidth(e)<=t}applyResponsiveClasses(e){if(this.supportsContainerQueries)return;const t=this.shouldUseMobileStyles(e),n=this.shouldUseMobileStyles(e,1024)&&!t;e.classList.toggle("limbo-mobile-fallback",t),e.classList.toggle("limbo-tablet-fallback",n),e.classList.toggle("limbo-desktop-fallback",!t&&!n)}observeResize(){if(!this.supportsContainerQueries)if("ResizeObserver"in window){const e=new ResizeObserver(e=>{e.forEach(e=>{this.applyResponsiveClasses(e.target)})});document.querySelectorAll(".limbo-component-container-wrapper").forEach(t=>{e.observe(t)})}else window.addEventListener("resize",()=>{document.querySelectorAll(".limbo-component-container-wrapper").forEach(e=>{this.applyResponsiveClasses(e)})})}};function Y(e={}){const{useContainerQuery:t=!1,containerElement:n=null}=e,[r,a]=p.useState(()=>{const e=t&&n?Q.getContainerWidth(n):"undefined"!=typeof window?window.innerWidth:0,r="undefined"!=typeof window&&(e<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)),a="undefined"!=typeof window&&("ontouchstart"in window||navigator.maxTouchPoints>0);return{isMobile:r,isTouch:a,isTablet:"undefined"!=typeof window&&(e>768&&e<=1024&&a),orientation:"undefined"!=typeof window?window.innerHeight>window.innerWidth?"portrait":"landscape":"portrait",viewport:{width:"undefined"!=typeof window?window.innerWidth:0,height:"undefined"!=typeof window?window.innerHeight:0},container:{width:e,supportsContainerQueries:Q.supportsContainerQueries}}});p.useEffect(()=>{if("undefined"==typeof window)return;const e=()=>{const e=window.innerWidth,r=window.innerHeight,o=t&&n?Q.getContainerWidth(n):e,i=o<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),l="ontouchstart"in window||navigator.maxTouchPoints>0;a({isMobile:i,isTouch:l,isTablet:o>768&&o<=1024&&l,orientation:r>e?"portrait":"landscape",viewport:{width:e,height:r},container:{width:o,supportsContainerQueries:Q.supportsContainerQueries}})};let r;const o=()=>{clearTimeout(r),r=setTimeout(e,150)};return window.addEventListener("resize",o),window.addEventListener("orientationchange",()=>{setTimeout(e,100)}),()=>{clearTimeout(r),window.removeEventListener("resize",o),window.removeEventListener("orientationchange",e)}},[t,n]);const o="portrait"===r.orientation,i="landscape"===r.orientation,l=r.isMobile||r.isTablet&&o;return{...r,isPortrait:o,isLandscape:i,isCompactMode:l,isMobileSize:r.viewport.width<=640,isTabletSize:r.viewport.width>640&&r.viewport.width<=1024,isDesktopSize:r.viewport.width>1024,deviceClass:r.isMobile?"mobile":r.isTablet?"tablet":"desktop"}}function G({tabs:e,active:t,onChange:n}){const{isMobile:r,isTouch:a}=Y();return K.jsx("div",{className:"limbo-tabs "+(r?"limbo-tabs--mobile":""),role:"tablist","aria-label":"Opciones de navegación",style:{...r&&{overflowX:"auto",WebkitOverflowScrolling:"touch",scrollbarWidth:"none",msOverflowStyle:"none"}},children:e.map(o=>{const i=t===o.id;return!i&&o.hideNonActive?null:K.jsx("button",{"data-tab-id":o.id,onClick:()=>n(o.id),onKeyDown:t=>((t,r)=>{const a=e.findIndex(e=>e.id===r);let o=a;switch(t.key){case"ArrowLeft":case"ArrowUp":t.preventDefault(),o=a>0?a-1:e.length-1;break;case"ArrowRight":case"ArrowDown":t.preventDefault(),o=a<e.length-1?a+1:0;break;case"Home":t.preventDefault(),o=0;break;case"End":t.preventDefault(),o=e.length-1;break;case"Enter":case" ":return t.preventDefault(),void n(r);default:return}const i=e[o];i&&!i.hideNonActive&&(n(i.id),setTimeout(()=>{const e=document.querySelector(`[data-tab-id="${i.id}"]`);e&&e.focus()},0))})(t,o.id),className:`limbo-tab ${i?"active":""} ${r?"limbo-tab--mobile":""}`,role:"tab","aria-selected":i,"aria-controls":`tabpanel-${o.id}`,tabIndex:i?0:-1,id:`tab-${o.id}`,style:{...r&&{minWidth:"120px",minHeight:"44px",padding:"12px 16px",flexShrink:0,fontSize:"16px"},...a&&{touchAction:"manipulation",WebkitTapHighlightColor:"transparent"}},children:o.label},o.id)})})}const X="https://led-dev-limbo-dev.eu.els.local",J="https://limbo.lefebvre.com";let Z={publicKey:null,token:null,authMode:null,tokenEndpoint:null,prod:!1};function ee({prod:e=!1}={}){return e?J:X}async function te({endpoint:e,method:t="GET",body:n=null,prod:r=!1,basePath:a="",customHeaders:o={},isFormData:i=!1,useJWT:l=!0}){try{const s=r||Z.prod,c=await async function({isFormData:e=!1,useJWT:t=!0,customHeaders:n={}}={}){const r={};if(e||(r["Content-Type"]="application/json"),t){let e=Z.token;if("session"===Z.authMode&&!e)try{const t=ee(Z),n=Z.tokenEndpoint||"/auth/token",r=await fetch(`${t}${n}`,{method:"POST",headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"},body:JSON.stringify({public_key:Z.publicKey}),credentials:"include"});if(!r.ok)throw new Error(`Session auth failed: ${r.status}`);e=(await r.json()).token,Z.token=e}catch(a){throw console.error("❌ Session authentication failed:",a),new Error("Failed to authenticate with session. User must be logged in.")}e?r.Authorization=`Bearer ${e}`:console.warn("⚠️ No JWT token available:",{authMode:Z.authMode,hasPublicKey:!!Z.publicKey})}return e&&delete r["Content-Type"],{...r,...n}}({isFormData:i,useJWT:l,customHeaders:o});"GET"===t&&!n&&c["Content-Type"]&&delete c["Content-Type"];const u=await fetch(`${ee({prod:s})}${a}${e}`,{method:t,headers:c,body:n?i?n:JSON.stringify(n):void 0,credentials:"include"});if(!u.ok){let e=`HTTP ${u.status}: ${u.statusText}`,t=null;try{const n=await u.json();t=n,n.error?e=`${n.error.code}: ${n.error.message}`:n.message&&(e=n.message)}catch{}throw 401===u.status&&t&&("token_expired"===t.error||t.message&&t.message.includes("expired")||t.message&&t.message.includes("caducado")||t.error&&t.error.includes("expired"))&&window.dispatchEvent(new CustomEvent("tokenExpiredError",{detail:{error:{response:{status:401,data:t}}}})),new Error(e)}return u.json()}catch(s){throw new Error(`API Error: ${s.message}`)}}function ne(){const e={...Z};return e?.prod||!1?"https://limbo.lefebvre.com":"http://localhost"}function re(e){if(!e?.id)return null;return`${ne()}/api/assets/${e.id}/download`}function ae(e){if(!e)return null;if(e.startsWith("http://")||e.startsWith("https://"))return e;if(e.startsWith("/")){return`${ne()}${e}`}return e}function oe(e){if(e.message&&!e.message.includes("API Error:"))return e;let t=e.message||"Unknown API error";return t.startsWith("API Error: ")&&(t=t.substring(11)),new Error(t)}const ie="/api";async function le(e={}){try{const t=new URLSearchParams(e).toString(),n=t?`/assets?${t}`:"/assets";return function(e){if(!e?.success||!Array.isArray(e?.data?.data))return{result:[]};const t={result:e.data.data.map(e=>({id:e.id,filename:e.filename||e.original_filename,mime_type:e.mime_type,file_size:e.file_size,width:e.width,height:e.height,upload_date:e.upload_date||e.created_at,processing_status:e.processing_status||e.status,url:ae(e.master_url||e.master?.url_signed||e.urls?.original||e.url)||re(e),webp_available:e.webp_available||!!e.webp_url,metadata:e.metadata||{},variants_count:e.variants_count||0}))};return e.data.pagination&&(t.pagination={page:e.data.pagination.page,limit:e.data.pagination.limit,total:e.data.pagination.total,pages:e.data.pagination.pages}),t}(await te({endpoint:n,method:"GET",basePath:ie,useJWT:!0}))}catch(t){throw oe(t)}}async function se(e,t=null,n=!1){try{const r=new FormData;r.append("file",e),t&&r.append("uploaded_by",t),n&&r.append("store_original",n.toString());return function(e){if(!e?.success||!e?.data)return{result:null};const t=e.data;return{result:{id:t.id,filename:t.original_filename,mime_type:t.mime_type,file_size:t.file_size,width:t.width,height:t.height,status:t.status,upload_date:t.created_at,url:ae(t.master?.url_signed),master_format:t.master?.format,processing:t.processing||{master_webp:"processing"===t.status?"queued":"completed",variants:"processing"===t.status?"queued":"completed"},checksum:t.checksum,storage_path:t.storage_path_base,metadata:t.metadata||{}}}}(await te({endpoint:"/assets",method:"POST",body:r,basePath:ie,isFormData:!0,useJWT:!0}))}catch(r){throw oe(r)}}async function ce(e){try{const n=await te({endpoint:`/assets/${e}/variants`,method:"GET",basePath:ie,useJWT:!0});return t=n,t?.success&&Array.isArray(t?.data?.variants)?{result:t.data.variants.map(e=>({id:e.id,name:e.filename||e.name||`Variante ${e.id}`,filename:e.filename,mime_type:e.mime_type,format:e.output_format||e.format||(e.mime_type?e.mime_type.split("/")[1]:"jpg"),file_size:e.file_size,width:e.width,height:e.height,upload_date:e.upload_date||e.created_at,processing_status:e.processing_status||e.status,url:ae(e.master_url||e.master?.url_signed||e.urls?.original||e.url)||re(e),webp_available:e.webp_available||!!e.webp_url,metadata:e.metadata||{},crop_data:e.crop_data||{},crop_params:e.crop_params||e.crop_data||{},parent_asset_id:e.parent_asset_id||t.data.asset_id,variant_type:e.variant_type||"crop"}))}:{result:[]}}catch(n){throw oe(n)}var t}function ue(){const[e,t]=p.useState({}),[n,r]=p.useState({}),[a,o]=p.useState({}),i=p.useCallback(async a=>{if(a&&!n[a]){if(e[a])return e[a];r(e=>({...e,[a]:!0})),o(e=>({...e,[a]:null}));try{const e=await ce(a),n=e?.result||[];return t(e=>({...e,[a]:n})),n}catch(i){return console.error("Error loading variants:",i),o(e=>({...e,[a]:i.message})),[]}finally{r(e=>({...e,[a]:!1}))}}},[e,n]),l=p.useCallback(t=>e[t]||[],[e]),s=p.useCallback(e=>n[e]||!1,[n]),c=p.useCallback(e=>a[e]||null,[a]),u=p.useCallback(e=>{t(t=>{const n={...t};return delete n[e],n}),r(t=>{const n={...t};return delete n[e],n}),o(t=>{const n={...t};return delete n[e],n})},[]),d=p.useCallback(async e=>(u(e),await i(e)),[u,i]),f=p.useCallback(async(e,n)=>{try{return await async function(e,t){try{return await te({endpoint:`/assets/${e}/variants/${t}`,method:"DELETE",basePath:ie,useJWT:!0})}catch(n){throw oe(n)}}(e,n),t(t=>{const r=t[e]||[];return{...t,[e]:r.filter(e=>e.id!==n)}}),{success:!0}}catch(r){return console.error("Error deleting variant:",r),{success:!1,error:r.message}}},[]);return{loadVariants:i,getVariants:l,isLoading:s,getError:c,clearVariants:u,refreshVariants:d,removeVariant:f}}function de({image:e,isOpen:t,onClose:n,onSelect:r,onDelete:a,onCrop:o,onVariantDeleted:i,allowedActions:l={select:!0,download:!0,copy:!0,delete:!0,crop:!0}}){const{loadVariants:s,getVariants:c,isLoading:u,getError:d,removeVariant:f}=ue(),m=window.limboCore?.accessibilityManager,[g,b]=h.useState(null),[y,v]=h.useState(null),w=(window.limboCore?.config?.getGlobal()||{}).interaction||{allowSelection:!1,allowCropping:!0},k=w.allowSelection&&l.select&&r,x=w.allowCropping&&l.crop&&o,S=l.copy,C=l.download,E=l.delete,[_,T]=h.useState(new Set),N=h.useMemo(()=>e?.variants||[],[e?.variants]),P=c(e?.id),R=N.length>0?N:P,z=0===N.length&&u(e?.id),j=0===N.length?d(e?.id):null;p.useEffect(()=>{!t||!e?.id||e?.variants&&0!==e.variants.length||s(e.id)},[t,e?.id,e?.variants,s]),h.useEffect(()=>{t&&T(new Set)},[t]);if(!t)return null;return K.jsx("div",{className:"limbo-modal-overlay",onClick:n,role:"dialog","aria-modal":"true","aria-labelledby":"variants-modal-title",children:K.jsxs("div",{className:"limbo-modal-content limbo-variants-modal",onClick:e=>e.stopPropagation(),children:[K.jsxs("div",{className:"limbo-modal-header",children:[K.jsxs("h2",{id:"variants-modal-title",children:["Variantes de ",e?.filename]}),K.jsx("button",{className:"limbo-modal-close",onClick:n,"aria-label":"Cerrar modal de variantes",children:"✕"})]}),g&&K.jsx("div",{className:`limbo-variants-message limbo-variants-message--${y} mt-1`,role:"alert",style:{padding:"12px 20px",margin:"0 20px 15px 20px",borderRadius:"4px",backgroundColor:"success"===y?"#d4edda":"#f8d7da",color:"success"===y?"#155724":"#721c24",border:"1px solid "+("success"===y?"#c3e6cb":"#f5c6cb")},children:g}),K.jsx("div",{className:"limbo-modal-body",children:z?K.jsxs("div",{className:"limbo-variants-loading",children:[K.jsx("div",{className:"limbo-loader"}),K.jsx("p",{children:"Cargando variantes..."})]}):j?K.jsxs("div",{className:"limbo-variants-error",children:[K.jsxs("p",{children:["Error al cargar variantes: ",j]}),K.jsx("button",{onClick:()=>s(e.id),className:"btn btn-primary",children:"Reintentar"})]}):0===R.length?K.jsxs("div",{className:"limbo-variants-empty",children:[K.jsx("p",{children:"Esta imagen no tiene variantes aún."}),K.jsx("small",{children:"Las variantes aparecerán aquí después de hacer recortes o redimensionados."})]}):K.jsxs(K.Fragment,{children:[K.jsxs("div",{className:"limbo-variant-section",children:[K.jsx("h3",{children:"Imagen original"}),K.jsxs("div",{onClick:()=>{m?.announce(`Abriendo imagen original ${e.filename} en nueva pestaña`),window.open(e.url,"_blank")},className:"limbo-variant-card limbo-variant-original cursor-pointer",children:[K.jsx("div",{className:"limbo-variant-preview",children:K.jsx("img",{src:e.url,alt:e.filename,loading:"lazy"})}),K.jsxs("div",{className:"limbo-variant-info",children:[K.jsx("div",{className:"limbo-variant-name",children:e.filename}),K.jsxs("div",{className:"limbo-variant-meta",children:[K.jsxs("span",{children:[e.width,"×",e.height]}),K.jsxs("span",{children:[Math.round(e.file_size/1024)," KB"]})]})]}),K.jsxs("div",{className:"limbo-variant-actions",children:[k&&K.jsx("button",{className:"btn btn-success btn-sm",onClick:t=>{t.stopPropagation(),r?.(e),n?.()},title:"Seleccionar original",children:"Seleccionar"}),x&&K.jsx("button",{className:"btn btn-crop btn-sm",onClick:t=>{t.stopPropagation(),o&&(m?.announce(`Abriendo herramienta de recorte para ${e.filename}`),o(e),n?.())},title:"Recortar imagen",children:K.jsx("span",{className:"icon icon-scissors-white icon--sm"})}),S&&K.jsx("button",{className:"btn btn-secondary btn-sm",onClick:t=>{t.stopPropagation(),(async()=>{try{await navigator.clipboard.writeText(e.url),m?.announce("URL de imagen original copiada")}catch(t){console.error("Error copying original URL:",t),m?.announceError("Error al copiar URL")}})()},title:"Copiar URL",children:K.jsx("span",{className:"icon icon-copy-white icon--sm"})}),C&&K.jsx("button",{className:"btn btn-primary btn-sm",onClick:t=>{t.stopPropagation(),(()=>{m?.announce(`Descargando imagen original ${e.filename}`);const t=document.createElement("a");t.href=e.url,t.download=e.filename,document.body.appendChild(t),t.click(),document.body.removeChild(t)})()},title:"Descargar",children:K.jsx("span",{className:"icon icon-download-white icon--sm"})}),E&&a&&K.jsx("button",{className:"btn btn-danger btn-sm",onClick:t=>{t.stopPropagation(),(async()=>{if(!a)return;window.confirm(`¿Estás seguro de que deseas eliminar "${e.filename}"? Esta acción también eliminará todas sus variantes.`)&&(m?.announce(`Eliminando imagen ${e.filename}`),await a(e.id),n?.())})()},title:"Eliminar imagen",children:K.jsx("span",{className:"icon icon-close-small-white icon--sm m-[0!important]"})})]})]})]}),K.jsxs("div",{className:"limbo-variant-section",children:[K.jsxs("h3",{children:["Variantes (",R.length,")"]}),K.jsx("div",{className:"limbo-variants-grid",children:R.map(t=>{const a=_.has(t.id);return K.jsxs("div",{className:"limbo-variant-card "+(a?"":"cursor-pointer"),onClick:a?void 0:()=>(e=>{m?.announce(`Abriendo variante ${e.name} en nueva pestaña`),window.open(e.url,"_blank")})(t),children:[K.jsxs("div",{className:"limbo-variant-preview",children:[K.jsx("img",{src:t.url,alt:t.name||t.filename||`Variante ${t.id}`,loading:"lazy",onError:()=>{return e=t.id,void T(t=>new Set([...t,e]));var e},style:{display:a?"none":"block"}}),a&&K.jsx("div",{className:"limbo-variant-error",style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100px",backgroundColor:"#f5f5f5",color:"#666"},children:K.jsx("span",{children:"Error al cargar preview"})})]}),K.jsxs("div",{className:"limbo-variant-info",children:[K.jsx("div",{className:"limbo-variant-name",children:t.name||t.filename||`Variante ${t.id}`}),K.jsxs("div",{className:"limbo-variant-meta",children:[K.jsxs("span",{children:[t.width,"×",t.height]}),K.jsx("span",{children:(t.format||"jpg").toUpperCase()}),K.jsxs("span",{children:[Math.round((t.file_size||0)/1024)," KB"]})]}),t.crop_params&&K.jsxs("div",{className:"limbo-variant-crop-badge",children:[K.jsx("span",{className:"icon icon-scissors icon--xs"})," ","Recortada"]})]}),K.jsxs("div",{className:"limbo-variant-actions",children:[k&&K.jsx("button",{className:"btn btn-success btn-sm",onClick:a=>{a.stopPropagation(),(t=>{const a={id:t.id,filename:`${e.filename}_${t.name}`,url:t.url,width:t.width,height:t.height,mime_type:`image/${t.format}`,file_size:t.file_size,upload_date:t.created_at,processing_status:"completed",is_variant:!0,parent_asset_id:e.id,variant_info:t};m?.announce(`Variante seleccionada: ${t.name}`),r?.(a),n?.()})(t)},title:`Seleccionar variante ${t.name||t.filename||t.id}`,children:"Seleccionar"}),S&&K.jsx("button",{className:"btn btn-secondary btn-sm",onClick:e=>{e.stopPropagation(),(async e=>{try{await navigator.clipboard.writeText(e.url),m?.announce(`URL de variante ${e.name} copiada`)}catch(t){console.error("Error copying variant URL:",t),m?.announceError("Error al copiar URL de variante")}})(t)},title:"Copiar URL",children:K.jsx("span",{className:"icon icon-copy-white icon--sm"})}),C&&K.jsx("button",{className:"btn btn-primary btn-sm",onClick:n=>{n.stopPropagation(),(t=>{m?.announce(`Descargando variante ${t.name}`);const n=document.createElement("a");n.href=t.url,n.download=`${e.filename}_${t.name}.${t.format}`,document.body.appendChild(n),n.click(),document.body.removeChild(n)})(t)},title:"Descargar",children:K.jsx("span",{className:"icon icon-download-white icon--sm"})}),E&&K.jsx("button",{className:"btn btn-danger btn-sm",onClick:n=>{n.stopPropagation(),(async t=>{if(window.confirm(`¿Estás seguro de que deseas eliminar la variante "${t.name||t.filename}"?`)){m?.announce(`Eliminando variante ${t.name||t.filename}`);const n=await f(e.id,t.id);n.success?(b("Variante eliminada correctamente"),v("success"),m?.announce("Variante eliminada correctamente"),i?.(),setTimeout(()=>{b(null),v(null)},3e3)):(b(`Error al eliminar variante: ${n.error}`),v("error"),m?.announceError(`Error al eliminar variante: ${n.error}`),setTimeout(()=>{b(null),v(null)},5e3))}})(t)},title:"Eliminar variante",children:K.jsx("span",{className:"icon icon-close-small-white icon--sm m-[0!important]"})})]})]},t.id)})})]})]})})]})})}function fe({image:e,onDelete:t,onCrop:n,onSelect:r,thumbnailSize:a=32,isDeleting:o=!1,allowedActions:i={select:!0,download:!0,copy:!0,delete:!0,crop:!0,variants:!0}}){const[l,s]=p.useState(!1),[c,u]=p.useState(!1),[d,f]=p.useState(e.variants_count||0),{isMobile:m,isTouch:g}=Y(),b=window.limboCore?.accessibilityManager,y=(window.limboCore?.config?.getGlobal()||{}).interaction||{allowSelection:!1,allowCropping:!0},v=n=>{n.stopPropagation(),b?.announce(`Eliminando imagen ${e.filename}`,"assertive"),t?.(e)},w=async t=>{t.stopPropagation();let n=e.url||e.path;try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(n);else{const e=document.createElement("textarea");e.value=n,e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.focus(),e.select(),document.execCommand("copy"),document.body.removeChild(e)}s(!0),b?.announce(`URL de ${e.filename} copiada al portapapeles. Nota: La URL puede tener un tiempo de validez limitado.`),setTimeout(()=>s(!1),2e3)}catch(r){console.error("Error al copiar URL:",r),b?.announce(`Error al copiar URL de ${e.filename}. Inténtalo de nuevo.`),alert(`Error al copiar URL de ${e.filename}. Por favor, inténtalo de nuevo.`)}},k=t=>{t.preventDefault(),t.stopPropagation(),b?.announce(`Descargando ${e.filename}`),fetch(e.url||e.path,{mode:"cors"}).then(e=>e.blob()).then(t=>{const n=window.URL.createObjectURL(t),r=document.createElement("a");r.href=n,r.download=e.filename||"imagen.jpg",document.body.appendChild(r),r.click(),setTimeout(()=>{window.URL.revokeObjectURL(n),document.body.removeChild(r)},100)})},x=t=>{t.stopPropagation(),b?.announce(`Editando imagen ${e.filename}`),n?.(e)},S=e.variants&&e.variants.length>0||d>0,C=d,E=h.useCallback(()=>{f(e=>Math.max(0,e-1))},[]);h.useEffect(()=>{f(e.variants_count||0)},[e.variants_count]);const _=t=>{t.stopPropagation(),b?.announce(`Mostrando variantes de ${e.filename}`),u(!0)},T=y.allowSelection&&i.select&&r,N=y.allowCropping&&i.crop&&n,P=S&&!1!==i.variants,R=()=>{window.open(e.url||e.path,"_blank")};return K.jsxs(K.Fragment,{children:[K.jsxs("div",{className:`limbo-image-card flex flex-col items-center cursor-pointer relative transition ${o?"opacity-50":""} ${m?"limbo-image-card--mobile":""}`,onClick:R,onKeyDown:e=>{switch(e.key){case"Enter":case" ":e.preventDefault(),R();break;case"d":case"D":i.download&&(e.preventDefault(),k(e));break;case"c":case"C":i.copy&&(e.preventDefault(),w(e));break;case"Delete":case"Backspace":i.delete&&t&&(e.preventDefault(),v(e));break;case"x":case"X":i.crop&&n&&(e.preventDefault(),x(e));break;case"v":case"V":i.variants&&(e.preventDefault(),_(e))}},title:m?"Toque para ver imagen":"Haga click en la imagen para ver preview en nueva pestaña (Enter/Space para abrir, D descargar, C copiar, Delete eliminar, X recortar)",role:"button",tabIndex:0,"aria-label":`Imagen ${e.filename}. ${e.width}x${e.height} px`,style:{...g&&{touchAction:"manipulation",WebkitTapHighlightColor:"transparent"}},children:[K.jsxs("div",{className:"limbo-image-actions "+(m?"limbo-image-actions--mobile":""),children:[P&&K.jsxs("button",{type:"button",title:`Ver ${C} variante${1!==C?"s":""}`,className:"btn btn-variants border border-brand-blue-050/50 "+(m?"btn--touch":""),onClick:_,tabIndex:-1,style:{...m&&{width:"40px",height:"40px"},position:"relative"},children:[K.jsx("span",{className:"icon icon-album-menu-white icon--sm","aria-hidden":"true"}),C>0&&K.jsx("span",{className:"variants-count-badge",style:{position:"absolute",top:"-8px",right:"-8px",background:"#dc2626",color:"white",borderRadius:"50%",minWidth:"20px",height:"20px",fontSize:"12px",fontWeight:"700",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:"1",border:"2px solid white",boxShadow:"0 2px 8px rgba(0, 0, 0, 0.4)",zIndex:"999"},children:C})]}),T&&K.jsx("button",{type:"button",title:"Seleccionar imagen",className:"btn btn-success border border-brand-blue-050/50 "+(m?"btn--touch":""),onClick:t=>{t.stopPropagation(),b?.announce(`Seleccionando ${e.filename} para el portal`),r?.(e)},tabIndex:-1,style:{...m&&{width:"40px",height:"40px"}},children:K.jsx("span",{className:"icon icon-tick-white icon--sm","aria-hidden":"true"})}),N&&K.jsx("button",{type:"button",title:"Editar imagen",className:"btn btn-crop border border-brand-blue-050/50 "+(m?"btn--touch":""),onClick:x,tabIndex:-1,style:{...m&&{width:"40px",height:"40px"}},children:K.jsx("span",{className:"icon icon-scissors-white icon--sm","aria-hidden":"true"})}),i.copy&&K.jsx("button",{type:"button",title:l?"¡Copiado!":"Copiar URL",className:"btn btn-copy border border-brand-blue-050/50 "+(m?"btn--touch":""),onClick:w,tabIndex:-1,style:{...m&&{width:"40px",height:"40px"}},children:K.jsx("span",{className:`icon ${l?"icon-copied-white":"icon-copy-white"} icon--sm`,"aria-hidden":"true"})}),i.download&&K.jsx("button",{type:"button",title:"Descargar",className:"btn btn-download border border-brand-blue-050/50 "+(m?"btn--touch":""),onClick:k,tabIndex:-1,style:{...m&&{width:"40px",height:"40px"}},children:K.jsx("span",{className:"icon icon-download-white icon--sm","aria-hidden":"true"})}),i.delete&&t&&K.jsx("button",{onClick:v,disabled:o,className:"btn btn-delete border border-brand-blue-050/50 "+(m?"btn--touch":""),title:"Eliminar imagen",tabIndex:-1,style:{...m&&{width:"40px",height:"40px"}},children:o?"…":K.jsx("span",{className:"icon icon-close-small-white icon--sm","aria-hidden":"true"})})]}),K.jsx("img",{src:e.url||e.path,alt:e.filename,className:"w-full object-cover rounded aspect-square",sizes:`height: ${6*a}px,width: ${6*a}px`,draggable:!1,style:{...m&&{minHeight:`${Math.max(3*a,80)}px`,height:"auto",aspectRatio:"1 / 1",objectFit:"cover"}}}),K.jsx("span",{className:"text-xs mt-1 truncate w-full text-center limbo-image-card-name "+(m?"limbo-image-card-name--mobile":""),style:{...m&&{fontSize:"0.75rem",lineHeight:"1.2",maxWidth:"100%",padding:"2px 4px",backgroundColor:"rgba(255, 255, 255, 0.9)",borderRadius:"4px",color:"#333",fontWeight:"500"}},children:e.filename})]}),K.jsx(de,{image:e,isOpen:c,onClose:()=>u(!1),onSelect:r,onDelete:t,onCrop:n,onVariantDeleted:E,allowedActions:{select:i.select,download:i.download,copy:i.copy,delete:i.delete,crop:i.crop}})]})}function pe({text:e="Cargando..."}){return K.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-gray-600",role:"status","aria-live":"polite","aria-label":e,children:[K.jsxs("svg",{className:"animate-spin h-6 w-6 mb-2 text-blue-500",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24","aria-hidden":"true",children:[K.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),K.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8v8H4z"})]}),K.jsx("p",{className:"text-sm",id:"loader-text",children:e})]})}const he=new Map;function me({apiKey:e,prod:t,onSelect:n,onCrop:r,onDelete:a,deletingId:o,images:i,loading:l,error:s,allowedActions:c={select:!0,download:!0,copy:!0,delete:!0,crop:!0,variants:!0}}){const[u,d]=p.useState({search:"",dateFrom:"",dateTo:"",originPortal:"",uploadedBy:""}),f=p.useRef(null),h=function(){const[e,t]=p.useState(null),[n,r]=p.useState(!0),[a,o]=p.useState(null);return p.useEffect(()=>{const e="auth-status",n=he.get(e),a=Date.now();if(n&&a-n.timestamp<3e5)return t(n.data),void r(!1);let i=!0;return(async()=>{try{const n=!0;if(!i)return;he.set(e,{data:n,timestamp:Date.now()}),t(n)}catch(n){i&&(o(n.message),t(!1))}finally{i&&r(!1)}})(),()=>{i=!1}},[]),{allowed:e,loading:n,error:a,invalidateCache:()=>{he.delete("auth-status")}}}(),m=window.limboCore?.accessibilityManager;p.useEffect(()=>{if(f.current&&window.limboCore?.keyboardManager){const e="gallery-grid";f.current.setAttribute("data-grid-id",e),window.limboCore.keyboardManager.setupGridNavigation(f.current,{itemSelector:".limbo-image-card",gridId:e,columns:"auto"})}},[i]),p.useEffect(()=>{l?m?.announceLoading(!0,"galería"):l||s?s&&m?.announceError(s,"galería"):(m?.announceLoading(!1,"galería"),i.length>0&&m?.announce(`Se encontraron ${i.length} imágenes en la galería`))},[l,s,i.length,m]);const g=e=>{const{name:t,value:n}=e.target;d(e=>({...e,[t]:n}))};return K.jsxs("div",{className:"w-full",children:[K.jsx("div",{className:"limbo-card mb-6 p-4 bg-brand-blue-050 shadow-md",children:K.jsxs("form",{className:"limbo-form-grid flex flex-col sm:flex-row flex-wrap gap-4 items-start sm:items-end justify-between",onSubmit:e=>e.preventDefault(),"aria-label":"Filtrar imágenes",children:[K.jsxs("div",{className:"flex flex-col w-full sm:min-w-[180px] sm:flex-1",children:[K.jsx("label",{htmlFor:"search",className:"form-label mb-1",children:"Nombre"}),K.jsx("input",{type:"text",name:"search",id:"search",placeholder:"Buscar por nombre...",value:u.search,onChange:g,className:"form-control",autoComplete:"off"})]}),K.jsxs("div",{className:"flex flex-col sm:flex-row flex-wrap gap-2 justify-between items-start sm:items-end w-full sm:w-auto",children:[K.jsxs("div",{className:"flex flex-col w-full sm:w-auto",children:[K.jsx("label",{htmlFor:"dateFrom",className:"form-label mb-1",children:"Desde"}),K.jsx("input",{type:"date",name:"dateFrom",id:"dateFrom",value:u.dateFrom,onChange:g,className:"form-control"})]}),K.jsxs("div",{className:"flex flex-col w-full sm:w-auto",children:[K.jsx("label",{htmlFor:"dateTo",className:"form-label mb-1",children:"Hasta"}),K.jsx("input",{type:"date",name:"dateTo",id:"dateTo",value:u.dateTo,onChange:g,className:"form-control"})]}),h&&K.jsxs("div",{className:"flex flex-col w-full sm:w-auto",children:[K.jsx("label",{htmlFor:"originPortal",className:"form-label mb-1",children:"Portal de origen"}),K.jsx("input",{type:"text",name:"originPortal",id:"originPortal",placeholder:"Portal de origen",value:u.originPortal,onChange:g,className:"form-control"})]}),K.jsxs("div",{className:"flex flex-col w-full sm:w-auto",children:[K.jsx("label",{htmlFor:"uploadedBy",className:"form-label mb-1",children:"Subido por"}),K.jsx("input",{type:"text",name:"uploadedBy",id:"uploadedBy",placeholder:"Subido por",value:u.uploadedBy,onChange:g,className:"form-control"})]})]})]})}),l?K.jsx(pe,{text:"Cargando imágenes..."}):s?K.jsx("div",{className:"alert alert-danger text-center",children:s}):K.jsx("div",{ref:f,className:"limbo-gallery mt-4","data-limbo-responsive":!0,"data-grid-id":"gallery-grid",role:"grid","aria-label":"Galería de imágenes. Use las flechas para navegar entre imágenes",children:i.length>0?i.map((e,t)=>K.jsx("div",{role:"gridcell","aria-posinset":t+1,"aria-setsize":i.length,children:K.jsx(fe,{image:e,onSelect:n,onCrop:r,onDelete:c.delete&&a?()=>a(e.id):null,thumbnailSize:32,isDeleting:o===e.id,allowedActions:c})},e.id)):K.jsx("div",{className:"col-span-full text-center text-gray-500 py-8",role:"status","aria-live":"polite",children:K.jsx("p",{children:"No se han encontrado imágenes"})})})]})}function ge({file:e,setFile:t,previewUrl:n,setPreviewUrl:r,fileInputRef:a,onUpload:o,disabled:i}){return K.jsxs("form",{onSubmit:n=>{n.preventDefault(),e&&!i&&(o(e),t(null),r(null),a.current&&(a.current.value=""))},className:"flex flex-col items-center gap-6","aria-label":"Subir imagen desde dispositivo",children:[K.jsxs("label",{htmlFor:"file-input",className:"w-full flex flex-col items-center justify-center border-2 border-dashed border-brand-blue-200 rounded-xl p-8 cursor-pointer hover:border-brand-blue-1000 hover:to-bright-blue-200 hover:from-brand-blue-050 focus-within:border-brand-blue-800 from-bright-blue-050 to-brand-blue-050 bg-linear-to-br transition",tabIndex:0,style:{outline:"none"},children:[K.jsx("span",{className:"icon icon-upload icon--lg mb-2","aria-hidden":"true"}),K.jsx("span",{className:"font-medium text-brand-blue-1000 mb-1",children:"Haz clic o arrastra una imagen aquí"}),K.jsx("span",{className:"text-sm text-neutral-700",children:"Formatos permitidos: JPG, PNG, GIF, SVG, WebP"}),K.jsx("input",{id:"file-input",ref:a,type:"file",accept:"image/jpeg,image/png,image/svg,image/webp,image/gif",onChange:e=>{const n=e.target.files[0];if(t(n),n){const e=URL.createObjectURL(n);r(e)}else r(null)},disabled:i,className:"sr-only","aria-label":"Seleccionar imagen"})]}),n&&K.jsxs("div",{className:"w-full flex flex-col items-center gap-2",children:[K.jsx("img",{src:n,alt:e?.name||"Previsualización",className:"rounded-lg shadow-md border border-brand-blue-200 max-h-64 object-contain bg-white",style:{maxWidth:"100%"}}),K.jsxs("div",{className:"text-sm text-neutral-800 bg-brand-blue-050 p-2 rounded w-full text-center",children:[K.jsxs("p",{children:[K.jsx("span",{className:"font-medium",children:"Archivo:"})," ",e?.name]}),K.jsxs("p",{children:[K.jsx("span",{className:"font-medium",children:"Tamaño:"})," ",e?(e.size/1024/1024).toFixed(2):"--"," MB"]}),K.jsxs("p",{children:[K.jsx("span",{className:"font-medium",children:"Tipo:"})," ",e?.type]})]})]}),K.jsx("button",{type:"submit",disabled:!e||i,title:e?"Subir imagen a la galeria":"Proporcione una imagen antes de continuar",className:"limbo-btn w-full mt-2 "+(e?"limbo-btn-primary":"cursor-not-allowed limbo-btn-disabled"),style:{minHeight:44},children:i?"Subiendo...":"Subir imagen"})]})}const be="/api";const ye=new Map;function ve(e=!1){const[t,n]=p.useState([]),[r,a]=p.useState(!0),[o,i]=p.useState(null);p.useEffect(()=>{const t=`ai-services-${e}`,r=ye.get(t),o=Date.now();if(r&&o-r.timestamp<864e5)return n(r.data),void a(!1);let l=!0;return(async()=>{try{const r=await function(e=!1){return te({endpoint:"/ai/services",prod:e,basePath:be})}(e);if(!l)return;const a=r?.data?.images||[];n(a),ye.set(t,{data:a,timestamp:o})}catch(r){l&&i(r.message)}finally{l&&a(!1)}})(),()=>{l=!1}},[e]);return{services:t,loading:r,error:o,invalidateCache:()=>{ye.delete(`ai-services-${e}`)}}}const we=new Map;function ke(e=!1){const[t,n]=p.useState(null),[r,a]=p.useState(!1),[o,i]=p.useState(null);return{params:t,loading:r,error:o,fetchParams:async t=>{a(!0),i(null);const r=`${e}-${t}`,o=Date.now(),l=we.get(r);if(l&&o-l.timestamp<864e5)return n(l.data),a(!1),l.data;try{const a=await function({services:e=null,form:t=!1}={},n=!1){const r={};return e&&(r.services=e),!1!==t&&(r.form=t),te({endpoint:"/ai/params"+(Object.keys(r).length?"?"+new URLSearchParams(r).toString():""),method:"GET",prod:n,basePath:"/api/atenea"})}({services:t,form:!1},e),i=a?.result?.data||a?.data||a?.result||a;return n(i),we.set(r,{data:i,timestamp:o}),i}catch(s){return i(s.message),n(null),null}finally{a(!1)}},reset:()=>{i(null),n(null)}}}function xe({prod:e,disabled:t,onSelected:n,onGenerated:r}){const a=ve(e),o=ke(e),[i,l]=p.useState(""),[s,c]=p.useState({}),[u,d]=p.useState(!1),[f,m]=p.useState(null),[g,b]=p.useState(null),y={"dall-e-2":"Dalle2","dall-e-3":"Dalle3","freepik-classic":"Freepik Classic","freepik-mystic":"Freepik Mystic","freepik-google":"Freepik Google","freepik-flux":"Freepik Flux",shutterstock:"Shutterstock",freepikstock:"Freepik"},v=e=>y[e]||e;h.useEffect(()=>{if(!a.loading&&1===a.services.length){const e=a.services[0];l(e),o.fetchParams(e,!0)}},[a.loading,a.services]);h.useEffect(()=>{if(!i)return;const e=o.params?.[i]?.parameters;if(e){const t=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default??""]));t.service=i,c(t)}},[i,o.params]);const w=e=>{const{name:t,value:n}=e.target;c(e=>({...e,[t]:n}))},k=async t=>{t.preventDefault(),d(!0),m(null),b(null);try{const t=await function(e,t=!1){return te({endpoint:"/ai/generate",method:"POST",body:e,prod:t,basePath:be})}(s,e);let a=null;if(t?.data?.images&&Array.isArray(t.data.images)&&t.data.images.length>0?a=t.data.images[0]:t?.result?.images&&Array.isArray(t.result.images)&&t.result.images.length>0?a=t.result.images[0]:Array.isArray(t)&&t.length>0?a=t[0]:"string"==typeof t&&(a=t),!a||!r)throw new Error("No se pudo extraer la imagen de la respuesta");if(a.startsWith("http"))try{const e=await fetch(a);if(!e.ok)throw new Error(`Failed to download image: ${e.status}`);const t=await e.blob(),n=new File([t],"ai-image.png",{type:t.type||"image/png"});r(n)}catch(n){throw new Error(`Error downloading image: ${n.message}`)}else{const e=a.replace(/^data:image\/\w+;base64,/,""),t=atob(e),n=new Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);const o=new Uint8Array(n),i=new File([o],"ai-image.webp",{type:"image/webp"});r(i)}b(t?.data?.images||t?.result?.images||null)}catch(a){m(a.message||"Error al generar la imagen")}finally{d(!1)}};return a.loading?K.jsxs("div",{className:"flex items-center justify-center py-8",children:[K.jsx("span",{className:"limbo-loader mr-2"})," Cargando servicios IA..."]}):a.services.length?K.jsxs("div",{className:"flex flex-col gap-4",children:[K.jsx("h3",{id:"aiSelectDescription",className:"text-lg font-semibold text-brand-blue-1000",children:1===a.services.length?`Generación con ${v(i)}`:"Selecciona el modelo IA"}),a.services.length>1&&K.jsxs("select",{name:"aiService","aria-describedby":"aiSelectDescription",title:"Selecciona el servicio IA",value:i,onChange:async e=>{const t=e.target.value;l(t),c({}),b(null),t&&await o.fetchParams(t,!0)},disabled:a.loading||t,className:"limbo-input",children:[K.jsx("option",{value:"",children:"-- Selecciona --"}),a.services.map(e=>K.jsx("option",{value:e,children:v(e)},e))]}),a.error&&K.jsx("div",{className:"alert alert-danger",children:a.error}),o.loading&&K.jsx("div",{children:"Cargando parámetros..."}),o.error&&K.jsx("div",{className:"alert alert-danger",children:o.error}),i&&(()=>{const e=o.params?.[i]?.parameters;if(!e)return null;const n=Object.entries(e).filter(([e,t])=>!t.disabled),r=n.length>3;return K.jsxs("form",{onSubmit:k,"data-type":"ai",className:"flex flex-col gap-3 mt-4 border-t-1 pt-4 border-brand-blue-200","aria-label":"Formulario generación IA",children:[K.jsx("div",{className:r?"grid grid-cols-1 md:grid-cols-2 gap-3":"flex flex-col gap-3",children:n.map(([e,n])=>{let r=n.placeholder||"";return r||(r="integer"===n.type?n.minValue&&n.maxValue?`Entre ${n.minValue} y ${n.maxValue}`:n.minValue?`Mínimo ${n.minValue}`:n.maxValue?`Máximo ${n.maxValue}`:"Introduce un número":e.toLowerCase().includes("prompt")?"Describe la imagen que deseas generar...":e.toLowerCase().includes("negative")?"Elementos a evitar en la imagen...":`Introduce ${(n.label||e).toLowerCase()}`),K.jsxs("div",{className:"flex flex-col gap-1",children:[K.jsxs("label",{htmlFor:`ai-${e}`,className:"text-xs font-medium text-brand-blue-900",children:[n.label||e,n.required&&K.jsx("span",{className:"text-red-600 ml-1",children:"*"})]}),n.options?K.jsx("select",{id:`ai-${e}`,name:e,value:s[e]??"",onChange:w,className:"limbo-input",disabled:t,title:n.label||e,children:n.options.map(e=>K.jsx("option",{value:e,children:e},e))}):K.jsx("input",{id:`ai-${e}`,type:"integer"===n.type?"number":"text",name:e,value:s[e]??"",onChange:w,className:"limbo-input",disabled:t,required:n.required,min:n.minValue,max:n.maxValue,placeholder:r,title:n.label||e})]},e)})}),K.jsx("button",{type:"submit",disabled:u||t,title:u?"Generando imagen...":"Generar imagen",className:"limbo-btn w-full mt-2 "+(u?"cursor-not-allowed limbo-btn-disabled":"limbo-btn-primary"),style:{minHeight:44},children:u?"Generando...":"Generar imagen"})]})})(),f&&K.jsx("div",{className:"alert alert-danger",children:f}),g&&g.map((e,t)=>K.jsxs("div",{className:"mt-6 text-center",children:[K.jsx("img",{src:e.contains("http")?e:`data:image/png;base64, ${e}`,alt:"Imagen generada con IA",className:"rounded-lg shadow-md border border-brand-blue-200 max-h-72 mx-auto"}),K.jsx("button",{className:"limbo-btn limbo-btn-primary mt-4",children:"Aceptar y subir"})]},"img-"+t))]}):K.jsx("div",{className:"alert alert-warning",children:"No hay servicios IA disponibles."})}const Se="/api";const Ce=new Map;function Ee(e=!1){const[t,n]=p.useState([]),[r,a]=p.useState(!0),[o,i]=p.useState(null);p.useEffect(()=>{const t=`stock-services-${e}`,r=Ce.get(t),o=Date.now();if(r&&o-r.timestamp<864e5)return n(r.data),void a(!1);let l=!0;return(async()=>{try{const r=await function(e=!1){return te({endpoint:"/stock/services",prod:e,basePath:Se})}(e);if(!l)return;const a=r?.data?.images||[];n(a),Ce.set(t,{data:a,timestamp:o})}catch(r){l&&i(r.message)}finally{l&&a(!1)}})(),()=>{l=!1}},[e]);return{services:t,loading:r,error:o,invalidateCache:()=>{Ce.delete(`stock-services-${e}`)}}}function _e({prod:e,disabled:t,onSelected:n}){const r=h.useRef(null),a=Ee(e),o=(e,t)=>{try{const n=sessionStorage.getItem(`limbo_stock_${e}`);return n?JSON.parse(n):t}catch{return t}},[i,l]=p.useState(()=>o("selectedService","")),[s,c]=p.useState(()=>o("dynamicForm",{})),[u,d]=p.useState(()=>o("stockImages",[])),[f,m]=p.useState(()=>o("currentPage",1)),[g,b]=p.useState(()=>o("paginationInfo",null)),y=ke(e),[v,w]=p.useState(!1),[k,x]=p.useState(null),[S,C]=p.useState(null);h.useEffect(()=>{sessionStorage.setItem("limbo_stock_selectedService",JSON.stringify(i))},[i]),h.useEffect(()=>{sessionStorage.setItem("limbo_stock_dynamicForm",JSON.stringify(s))},[s]),h.useEffect(()=>{sessionStorage.setItem("limbo_stock_stockImages",JSON.stringify(u))},[u]),h.useEffect(()=>{sessionStorage.setItem("limbo_stock_currentPage",JSON.stringify(f))},[f]),h.useEffect(()=>{sessionStorage.setItem("limbo_stock_paginationInfo",JSON.stringify(g))},[g]);const E={shutterstock:"Shutterstock",freepikstock:"Freepik"},_=e=>E[e]||e;h.useEffect(()=>{if(!a.loading&&1===a.services.length){const e=a.services[0];l(e),y.fetchParams(e,!0)}},[a.loading,a.services]);h.useEffect(()=>{if(!i)return;const e=y.params?.[i]?.parameters;if(e){const t=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default??""]));t.service=i,c(t)}},[i,y.params]);const T=e=>{const{name:t,value:n}=e.target;c(e=>({...e,[t]:n}))},N=async(t=1)=>{w(!0),x(null),1===t&&d([]);try{let n;if(1===t){const e=y.params?.[i]?.parameters,a={...s};Object.entries(e||{}).forEach(([e,t])=>{e in a||(a[e]=t.default??"")}),a.per_page=parseInt(a.per_page),a.service=i,a.page=t,n=a,r.current={...a}}else n={...r.current,page:t};const a=await function(e,t=!1){return te({endpoint:"/stock/search",method:"POST",body:e,prod:t,basePath:Se})}(n,e),o=a?.data?.images||[];let l=a?.data?.pagination||null,c=null;l&&(c={total:l.total_count??l.total??o.length,per_page:l.per_page??(Array.isArray(o)?o.length:0),current_page:l.page??l.current_page??t}),d(P(Array.isArray(o)?o:[])),b(c),m(c?.current_page||t)}catch(n){x(n.message||"Error al buscar imágenes")}finally{w(!1)}},P=e=>{const t=new Set,n=[];return(e||[]).forEach((e,r)=>{const a=e.url||e.preview_url||e.full||e.preview;a&&!t.has(a)&&(t.add(a),n.push({...e,preview:e.preview_url||e.preview||e.url||e.full,full:e.url||e.full||e.preview_url,id:e.id||r,title:e.title||e.filename||`Imagen ${r+1}`,source:e.service||i,sourceTitle:E?.[i]||i}))}),n},R=async e=>{e.preventDefault();(s.query||s.search||s.term||"").trim().length<5?x("La búsqueda debe tener al menos 5 caracteres"):await N(1)},z=e=>{e<1||N(e)},j=async t=>{C(t.id),x(null);try{const r={service:i,image_id:t.id},a=await function(e,t=!1){return te({endpoint:"/stock/download",method:"POST",body:e,prod:t,basePath:Se})}(r,e);if(!a?.result?.url&&!a?.result?.download_url)throw new Error("No se pudo obtener la URL de descarga");{const e=a.result.url||a.result.download_url,r=await fetch(e),o=await r.blob(),i=a.result.filename||`stock-${t.id}.jpg`,l=new File([o],i,{type:o.type||"image/jpeg"});n&&n(l)}}catch(r){x(r.message||"No se pudo recuperar la imagen seleccionada")}finally{C(null)}};return a.loading?K.jsxs("div",{className:"flex items-center justify-center py-8",children:[K.jsx("span",{className:"limbo-loader mr-2"})," Cargando servicios de Stock..."]}):a.services.length?K.jsxs("div",{className:"flex flex-col gap-4",children:[K.jsx("h3",{className:"text-lg font-semibold text-brand-blue-1000",children:1===a.services.length?`Búsqueda en ${_(i)}`:"Selecciona el servicio de Stock"}),a.services.length>1&&K.jsxs("select",{value:i,onChange:async e=>{const t=e.target.value;l(t),c({}),d([]),m(1),t&&await y.fetchParams(t,!0)},disabled:a.loading||t,className:"limbo-input",children:[K.jsx("option",{value:"",children:"-- Selecciona --"}),a.services.map(e=>K.jsx("option",{value:e,children:_(e)},e))]}),a.error&&K.jsx("div",{className:"alert alert-danger",children:a.error}),y.loading&&K.jsx("div",{children:"Cargando parámetros..."}),y.error&&K.jsx("div",{className:"alert alert-danger",children:y.error}),i&&(()=>{const e=y.params?.[i]?.parameters;if(!e)return null;const n=Object.entries(e).filter(([,e])=>!e.disabled),r=n.length>3;return K.jsxs("form",{onSubmit:R,"data-type":"stock",className:"flex flex-col gap-3 mt-4 border-t-1 pt-4 border-brand-blue-200","aria-label":"Formulario búsqueda de imágenes de Stock",children:[K.jsx("div",{className:r?"grid grid-cols-1 md:grid-cols-2 gap-3":"flex flex-col gap-3",children:n.map(([e,n])=>{let r=n.placeholder||"";return r||(r="integer"===n.type?n.minValue&&n.maxValue?`Entre ${n.minValue} y ${n.maxValue}`:n.minValue?`Mínimo ${n.minValue}`:n.maxValue?`Máximo ${n.maxValue}`:"Introduce un número":e.toLowerCase().includes("query")||e.toLowerCase().includes("search")||e.toLowerCase().includes("term")?"Buscar imágenes...":`Introduce ${(n.label||e).toLowerCase()}`),K.jsxs("div",{className:"flex flex-col gap-1",children:[K.jsxs("label",{htmlFor:`stock-${e}`,className:"text-xs font-medium text-brand-blue-900",children:[n.label||e,n.required&&K.jsx("span",{className:"text-red-600 ml-1",children:"*"})]}),n.options&&n.multiple?K.jsx("div",{className:"flex flex-wrap gap-2 min-h-[50px] px-2 justify-between border-2 border-gray-transparent-500 rounded-lg",children:n.options.map(n=>K.jsxs("label",{className:"flex items-center gap-1",children:[K.jsx("input",{type:"checkbox",name:`stock-${e}`,value:n,checked:Array.isArray(s[e])&&s[e].includes(n),onChange:()=>((e,t)=>{c(n=>{const r=Array.isArray(n[e])?n[e]:[];return r.includes(t)?{...n,[e]:r.filter(e=>e!==t)}:{...n,[e]:[...r,t]}})})(e,n),disabled:t}),K.jsx("span",{className:"text-xs",children:n})]},n))}):n.options?K.jsx("select",{id:`stock-${e}`,name:e,value:s[e]??"",onChange:T,className:"limbo-input",disabled:t,title:n.label||e,children:n.options.map(e=>K.jsx("option",{value:e,children:e},e))}):K.jsx("input",{id:`stock-${e}`,type:"integer"===n.type?"number":"text",name:e,value:s[e]??"",onChange:T,className:"limbo-input",disabled:t,required:n.required,min:n.minValue,max:n.maxValue,placeholder:r,title:n.label||e})]},e)})}),K.jsx("button",{type:"submit",disabled:v||t,className:"limbo-btn w-full mt-2 "+(v?"cursor-not-allowed limbo-btn-disabled":"limbo-btn-primary"),style:{minHeight:44},children:v?"Buscando...":"Buscar imágenes"})]})})(),k&&K.jsx("div",{className:"alert alert-danger",children:k}),u.length>0&&K.jsxs(K.Fragment,{children:[K.jsxs("div",{className:"mt-6 grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 relative","aria-live":"polite",children:[v&&K.jsx("div",{className:"absolute inset-0 bg-white/80 z-10 flex items-center justify-center rounded-lg",children:K.jsxs("div",{className:"flex flex-col items-center gap-2",children:[K.jsx("span",{className:"limbo-loader"}),K.jsx("span",{className:"text-sm text-brand-blue-800",children:"Buscando imágenes..."})]})}),u.map((e,n)=>K.jsxs("div",{className:"border border-brand-blue-200 rounded-lg overflow-hidden bg-white shadow-sm hover:shadow-md transition-shadow",children:[K.jsxs("div",{className:"relative aspect-video bg-neutral-100",children:[K.jsx("img",{src:e.preview||e.thumbnail||e.url,alt:e.title||`Resultado ${n+1}`,className:"object-cover w-full h-full",loading:"lazy"}),e.id&&K.jsxs("span",{className:"absolute bottom-1 right-1 bg-black/60 text-white text-xs px-2 py-1 rounded",children:["ID: ",e.id]})]}),K.jsx("div",{className:"p-2",children:K.jsx("button",{className:"limbo-btn w-full text-sm "+(S===e.id?"limbo-btn-disabled cursor-not-allowed":"limbo-btn-primary"),onClick:()=>j(e),disabled:v||t||S===e.id,children:S===e.id?K.jsxs(K.Fragment,{children:[K.jsx("span",{className:"limbo-loader limbo-loader--sm mr-1"}),"Descargando..."]}):"Seleccionar"})})]},e.id||n))]}),g&&K.jsxs("div",{className:"mt-6 flex items-center justify-center gap-2",children:[K.jsxs("button",{onClick:()=>z(g.current_page-1),disabled:g.current_page<=1||v,className:"limbo-btn limbo-btn-secondary px-4 py-2 disabled:opacity-25"+(g.current_page<=1||v?" pointer-events-none cursor-default":" limbo-btn-primary"),children:[K.jsx("span",{className:"icon icon-arrow-left-white icon--sm"})," ","Anterior"]}),K.jsxs("span",{className:"px-4 py-2 text-sm text-neutral-700",children:["Página ",g.current_page," de"," ",Math.max(1,Math.ceil(g.total/g.per_page)),K.jsxs("span",{className:"text-xs text-neutral-500 block",children:["(",g.total," imágenes totales)"]})]}),K.jsxs("button",{onClick:()=>z(g.current_page+1),disabled:v||g.current_page>=Math.ceil(g.total/g.per_page),className:"limbo-btn limbo-btn-secondary px-4 py-2 disabled:opacity-25"+(v||g.current_page>=Math.ceil(g.total/g.per_page)?" pointer-events-none cursor-default":" limbo-btn-primary"),children:["Siguiente"," ",K.jsx("span",{className:"icon icon-arrow-right-white icon--sm"})]})]})]}),!v&&0===u.length&&i&&s.query&&K.jsxs("div",{className:"mt-6 text-center text-neutral-600 py-8 bg-neutral-50 rounded-lg",children:[K.jsx("span",{className:"icon icon-search icon--lg mb-2"}),K.jsxs("p",{children:['No se encontraron imágenes para "',s.query,'"']}),K.jsx("p",{className:"text-sm mt-1",children:"Intenta con otros términos de búsqueda"})]})]}):K.jsx("div",{className:"alert alert-warning",children:"No hay servicios de Stock disponibles."})}const Te="/api";const Ne=new Map;function Pe(e=!1){const[t,n]=p.useState([]),[r,a]=p.useState(!0),[o,i]=p.useState(null);p.useEffect(()=>{const t=`portal-sources-${e}`,r=Ne.get(t),o=Date.now();if(r&&o-r.timestamp<864e5)return n(r.data),void a(!1);let l=!0;return(async()=>{try{const r=await function(e=!1){return te({endpoint:"/external/sources",prod:e,basePath:Te})}(e);if(!l)return;const a=r?.data?.sources||{},i=Object.entries(a).map(([e,t])=>({id:e,...t}));n(i),Ne.set(t,{data:i,timestamp:o})}catch(r){l&&i(r.message)}finally{l&&a(!1)}})(),()=>{l=!1}},[e]);return{sources:t,loading:r,error:o,invalidateCache:()=>{Ne.delete(`portal-sources-${e}`)}}}const Re=({src:e,alt:t,className:n,onError:r})=>{const[a,o]=h.useState("loading");return"error"===a?null:K.jsx("img",{src:e,alt:t,className:n,loading:"lazy",onLoad:()=>{o("loaded")},onError:()=>{o("error"),r&&r()}})};function ze({prod:e,disabled:t,onSelected:n}){const r=h.useRef(null),a=Pe(e),o=(e,t)=>{try{const n=sessionStorage.getItem(`limbo_portals_${e}`);return n?JSON.parse(n):t}catch{return t}},[i,l]=p.useState(()=>o("selectedPortals",[])),[s,c]=p.useState(()=>o("searchName","")),[u,d]=p.useState(()=>o("limit",20)),[f,m]=p.useState(()=>o("currentPage",1)),[g,b]=p.useState(!1),[y,v]=p.useState(null),[w,k]=p.useState(()=>o("images",[])),[x,S]=p.useState(()=>o("portalResults",{})),[C,E]=p.useState(()=>o("paginationInfo",null)),[_,T]=p.useState(null),N=p.useRef({}),[P,R]=p.useState(new Set);h.useEffect(()=>{sessionStorage.setItem("limbo_portals_selectedPortals",JSON.stringify(i))},[i]),h.useEffect(()=>{sessionStorage.setItem("limbo_portals_searchName",JSON.stringify(s))},[s]),h.useEffect(()=>{sessionStorage.setItem("limbo_portals_limit",JSON.stringify(u))},[u]),h.useEffect(()=>{sessionStorage.setItem("limbo_portals_currentPage",JSON.stringify(f))},[f]),h.useEffect(()=>{sessionStorage.setItem("limbo_portals_images",JSON.stringify(w))},[w]),h.useEffect(()=>{sessionStorage.setItem("limbo_portals_portalResults",JSON.stringify(x))},[x]),h.useEffect(()=>{sessionStorage.setItem("limbo_portals_paginationInfo",JSON.stringify(C))},[C]);const z=async(t=1)=>{if(0===i.length)return void v("Selecciona al menos un portal");const n=((e,t,n,r)=>`${e.sort().join(",")}_${t}_${n}_${r}`)(i,s.trim(),u,t),a=N.current[n];if(a)return k(a.images),S(a.portalResults),E(a.paginationInfo),m(t),void v(null);b(!0),v(null),1===t&&(k([]),S({}),E(null));try{let a;1===t?(a={sources:i,limit:u,page:t,name:s.trim()},r.current={...a}):a={...r.current,page:t};const o=await function(e,t=!1){return te({endpoint:"/external/search",method:"POST",body:e,prod:t,basePath:Te})}(a,e),l=o?.data?.sources||{},c=[],d={},f=new Set;let p=null;Object.entries(l).forEach(([e,t])=>{d[e]={title:t.meta?.title||e,status:200,response:"OK",count:t.images?.length||0},Array.isArray(t.images)&&(t.images.forEach(n=>{const r=n.url||n.thumbnail;r&&!f.has(r)&&(f.add(r),c.push({...n,source:e,sourceTitle:t.meta?.title||e,preview:n.thumbnail||n.url,full:n.url}))}),!p&&t.pagination&&(p=t.pagination))}),N.current[n]={images:c,portalResults:d,paginationInfo:p},k(c),S(d),E(p),m(t),R(new Set),0!==c.length||o?.result?.success||v(o?.result?.message||"No se encontraron imágenes")}catch(o){v(o.message||"Error al buscar imágenes en portales")}finally{b(!1)}},j=e=>{e<1||z(e)};return a.loading?K.jsxs("div",{className:"flex items-center justify-center py-8",children:[K.jsx("span",{className:"limbo-loader mr-2"})," Cargando portales disponibles..."]}):a.sources.length?K.jsxs("div",{className:"flex flex-col gap-4",children:[K.jsx("h3",{className:"text-lg font-semibold text-brand-blue-1000",children:"Buscar en Portales Externos"}),K.jsxs("form",{onSubmit:e=>{e.preventDefault(),z(1)},className:"flex flex-col gap-4 border-t-1 pt-4 border-brand-blue-200",children:[K.jsxs("div",{className:"flex flex-col gap-2",children:[K.jsxs("div",{className:"flex items-center justify-between",children:[K.jsxs("label",{className:"text-sm font-medium text-brand-blue-1000",children:["Portales (",i.length," seleccionados)"]}),K.jsx("button",{type:"button",onClick:()=>{i.length===a.sources.length?l([]):l(a.sources.map(e=>e.id))},className:"text-xs text-brand-blue-800 hover:underline",children:i.length===a.sources.length?"Deseleccionar todos":"Seleccionar todos"})]}),K.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2",children:a.sources.map(e=>K.jsxs("label",{className:"flex items-center gap-2 p-2 border border-brand-blue-200 rounded cursor-pointer hover:bg-brand-blue-050 transition",children:[K.jsx("input",{type:"checkbox",checked:i.includes(e.id),onChange:()=>{return t=e.id,void l(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t]);var t},disabled:t,className:"w-4 h-4"}),K.jsx("span",{className:"text-sm",children:e.title})]},e.id))})]}),K.jsxs("div",{className:"flex flex-col gap-1",children:[K.jsx("label",{htmlFor:"portal-search-name",className:"text-sm font-medium text-brand-blue-1000",children:"Buscar por nombre (opcional)"}),K.jsx("input",{id:"portal-search-name",type:"text",value:s,onChange:e=>c(e.target.value),className:"limbo-input",placeholder:"Deja vacío para ver todas las imágenes",disabled:t})]}),K.jsxs("div",{className:"flex flex-col gap-1",children:[K.jsx("label",{htmlFor:"portal-limit",className:"text-sm font-medium text-brand-blue-1000",children:"Imágenes por página"}),K.jsxs("select",{id:"portal-limit",value:u,onChange:e=>d(Number(e.target.value)),className:"limbo-input",disabled:t,children:[K.jsx("option",{value:10,children:"10"}),K.jsx("option",{value:20,children:"20"}),K.jsx("option",{value:50,children:"50"}),K.jsx("option",{value:100,children:"100"})]})]}),K.jsx("button",{type:"submit",disabled:g||t||0===i.length,className:"limbo-btn w-full "+(g||0===i.length?"cursor-not-allowed limbo-btn-disabled":"limbo-btn-primary"),style:{minHeight:44},children:g?"Buscando...":"Buscar imágenes"})]}),a.error&&K.jsx("div",{className:"alert alert-danger",children:a.error}),y&&K.jsx("div",{className:"alert alert-danger",children:y}),Object.keys(x).length>0&&K.jsxs("div",{className:"bg-neutral-50 rounded-lg p-3",children:[K.jsx("h4",{className:"text-sm font-semibold mb-2",children:"Resultados por portal:"}),K.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2 text-sm",children:Object.entries(x).map(([e,t])=>K.jsxs("div",{className:"flex items-center justify-between p-2 rounded "+(200===t.status?"bg-green-50":"bg-red-50"),children:[K.jsx("span",{className:"font-medium",children:t.title}),K.jsx("span",{className:200===t.status?"text-green-700":"text-red-700",children:200===t.status?`${t.count} imágenes`:t.response})]},e))})]}),(w.length>0||g)&&K.jsxs(K.Fragment,{children:[K.jsxs("div",{className:"mt-6 relative","aria-live":"polite",children:[g&&K.jsx("div",{className:"absolute inset-0 bg-white/80 z-10 flex items-center justify-center rounded-lg",children:K.jsxs("div",{className:"flex flex-col items-center gap-2",children:[K.jsx("span",{className:"limbo-loader"}),K.jsx("span",{className:"text-sm text-brand-blue-800",children:"Buscando imágenes..."})]})}),K.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 "+(g?"opacity-50":""),children:w.map((r,a)=>{const o=`${r.source}-${r.id||a}`,i=r.preview||r.thumbnail||r.url||r.full;return P.has(o)?null:K.jsxs("div",{className:"border border-brand-blue-200 rounded-lg overflow-hidden bg-white shadow-sm hover:shadow-md transition-shadow",children:[K.jsxs("div",{className:"relative aspect-video bg-neutral-100",children:[K.jsx(Re,{src:i,alt:r.title||r.filename||`Imagen ${a+1}`,className:"object-cover w-full h-full",onError:()=>{R(e=>{const t=new Set(e);return t.add(o),t})}}),K.jsx("span",{className:"absolute top-1 left-1 bg-black/60 text-white text-xs px-2 py-1 rounded",children:r.sourceTitle}),r.id&&K.jsxs("span",{className:"absolute bottom-1 right-1 bg-black/60 text-white text-xs px-2 py-1 rounded",children:["ID: ",r.id]})]}),K.jsxs("div",{className:"p-2",children:[r.title&&K.jsx("p",{className:"text-xs text-neutral-700 mb-1 truncate",title:r.title,children:r.title}),K.jsx("button",{className:"limbo-btn w-full text-sm "+(_===(r.url||r.full)?"limbo-btn-disabled cursor-not-allowed":"limbo-btn-primary"),onClick:()=>(async t=>{T(t.url||t.full),v(null);try{const r=t.full||t.url||t.preview;if(!r)throw new Error("No se encontró URL de la imagen");const a=`${ee({prod:e})}/api/atenea/proxy?url=${encodeURIComponent(r)}`,o=await fetch(a);if(!o.ok)throw new Error(`Error al descargar: ${o.status}`);const i=await o.blob(),l=t.filename||t.title||`portal-${t.id||Date.now()}.jpg`,s=new File([i],l,{type:i.type||"image/jpeg"});n&&n(s)}catch(r){v(r.message||"No se pudo recuperar la imagen del portal")}finally{T(null)}})(r),disabled:g||t||_===(r.url||r.full),children:_===(r.url||r.full)?K.jsxs(K.Fragment,{children:[K.jsx("span",{className:"limbo-loader limbo-loader--sm mr-1"}),"Descargando..."]}):"Seleccionar"})]})]},o)})})]}),K.jsxs("div",{className:"mt-6 flex items-center justify-center gap-2",children:[K.jsxs("button",{onClick:()=>j(f-1),disabled:1===f||g,className:"limbo-btn limbo-btn-secondary px-4 py-2 disabled:opacity-25"+(1===f||g?" pointer-events-none cursor-default":" limbo-btn-primary"),children:[K.jsx("span",{className:"icon icon-arrow-left-white icon--sm"})," ","Anterior"]}),K.jsxs("span",{className:"px-4 py-2 text-sm text-neutral-700",children:["Página ",f,C&&K.jsxs(K.Fragment,{children:[" ","de ",C.pages,K.jsxs("span",{className:"text-xs text-neutral-500 block",children:["(",C.total," imágenes totales)"]})]})]}),K.jsxs("button",{onClick:()=>j(f+1),disabled:g||C&&f>=C.pages,className:"limbo-btn limbo-btn-secondary px-4 py-2 disabled:opacity-25"+(g||C&&f>=C.pages?" pointer-events-none cursor-default":" limbo-btn-primary"),children:["Siguiente"," ",K.jsx("span",{className:"icon icon-arrow-right-white icon--sm"})]})]})]}),!g&&0===w.length&&Object.keys(x).length>0&&K.jsxs("div",{className:"mt-6 text-center text-neutral-600 py-8 bg-neutral-50 rounded-lg",children:[K.jsx("span",{className:"icon icon-search icon--lg mb-2"}),K.jsx("p",{children:"No se encontraron imágenes en los portales seleccionados"}),s&&K.jsx("p",{className:"text-sm mt-1",children:"Intenta con otros términos o sin filtro de nombre"})]})]}):K.jsx("div",{className:"alert alert-warning",children:"No hay portales externos disponibles."})}const je=[{id:"upload",label:"Subir archivo"},{id:"ai",label:"Generar con IA"},{id:"stock",label:"Buscar en Stock"},{id:"portals",label:"Otros portales"}];function Oe({onUpload:e,disabled:t=!1,apiKey:n,prod:r=!1}){const[a,o]=p.useState("upload"),[i,l]=p.useState(null),[s,c]=p.useState(null),u=p.useRef();return K.jsxs("div",{className:"limbo-upload-form p-4 border-2 border-gray-200/50 rounded-lg min-w-fit max-w-5xl mx-auto",children:[K.jsx("div",{className:"limbo-tabs-container",children:K.jsx("div",{className:"limbo-tabs mb-6 min-w-fit",role:"tablist","aria-label":"Opciones de subida de imagen",children:je.map(e=>K.jsx("button",{type:"button","data-upload-tab-id":e.id,className:"text-nowrap limbo-tab"+(a===e.id?" active":""),"aria-current":a===e.id?"page":void 0,"aria-selected":a===e.id,role:"tab",tabIndex:a===e.id?0:-1,onClick:()=>o(e.id),onKeyDown:t=>((e,t)=>{const n=je.findIndex(e=>e.id===t);let r=n;switch(e.key){case"ArrowLeft":e.preventDefault(),r=n>0?n-1:je.length-1;break;case"ArrowRight":e.preventDefault(),r=n<je.length-1?n+1:0;break;case"Home":e.preventDefault(),r=0;break;case"End":e.preventDefault(),r=je.length-1;break;case"Enter":case" ":return e.preventDefault(),void o(t);default:return}const a=je[r];a&&(o(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}`,children:e.label},e.id))})}),K.jsxs("div",{className:"limbo-tab-content",role:"tabpanel",id:`upload-tabpanel-${a}`,"aria-labelledby":`upload-tab-${a}`,children:["upload"===a&&K.jsx(ge,{file:i,setFile:l,previewUrl:s,setPreviewUrl:c,fileInputRef:u,onUpload:e,disabled:t}),"ai"===a&&K.jsx(xe,{apiKey:n,prod:r,disabled:t,onGenerated:e=>{o("upload"),l(e),c(URL.createObjectURL(e))}}),"stock"===a&&K.jsx(_e,{apiKey:n,prod:r,disabled:t,onSelected:e=>{o("upload"),l(e),c(URL.createObjectURL(e))}}),"portals"===a&&K.jsx(ze,{apiKey:n,prod:r,disabled:t,onSelected:e=>{o("upload"),l(e),c(URL.createObjectURL(e))}})]})]})}const Ae="undefined"!=typeof window&&void 0!==window.document,Le=Ae?window:{},Ie=!!Ae&&"ontouchstart"in Le.document.documentElement,Me=!!Ae&&"PointerEvent"in Le,De="cropper",$e=`${De}-canvas`,Fe=`${De}-crosshair`,Ue=`${De}-grid`,He=`${De}-handle`,We=`${De}-image`,Be=`${De}-selection`,Ve=`${De}-shade`,qe=`${De}-viewer`,Ke="select",Qe="move",Ye="scale",Ge="rotate",Xe="transform",Je="none",Ze="n-resize",et="e-resize",tt="s-resize",nt="w-resize",rt="ne-resize",at="nw-resize",ot="se-resize",it="sw-resize",lt=Me?"pointerdown":Ie?"touchstart":"mousedown",st=Me?"pointermove":Ie?"touchmove":"mousemove",ct=Me?"pointerup pointercancel":Ie?"touchend touchcancel":"mouseup",ut="error",dt="keydown",ft="load",pt="wheel",ht="action",mt="actionend",gt="actionstart",bt="change",yt="transform";const vt=Number.isNaN||Le.isNaN;function wt(e){return"number"==typeof e&&!vt(e)}function kt(e){return wt(e)&&e>0&&e<1/0}function xt(e){return"object"==typeof e&&null!==e}const{hasOwnProperty:St}=Object.prototype;function Ct(e){if(!xt(e))return!1;try{const{constructor:t}=e,{prototype:n}=t;return t&&n&&St.call(n,"isPrototypeOf")}catch(t){return!1}}function Et(e){return"function"==typeof e}function _t(e){return"object"==typeof e&&null!==e&&1===e.nodeType}const Tt=/([a-z\d])([A-Z])/g;function Nt(e){return String(e).replace(Tt,"$1-$2").toLowerCase()}const Pt=/-[A-z\d]/g;function Rt(e){return e.replace(Pt,e=>e.slice(1).toUpperCase())}const zt=/\s\s*/;function jt(e,t,n,r){t.trim().split(zt).forEach(t=>{e.removeEventListener(t,n,r)})}function Ot(e,t,n,r){t.trim().split(zt).forEach(t=>{e.addEventListener(t,n,r)})}function At(e,t,n,r){Ot(e,t,n,Object.assign(Object.assign({},r),{once:!0}))}const Lt={bubbles:!0,cancelable:!0,composed:!0};const It=Promise.resolve();function Mt(e){const{documentElement:t}=e.ownerDocument,n=e.getBoundingClientRect();return{left:n.left+(Le.pageXOffset-t.clientLeft),top:n.top+(Le.pageYOffset-t.clientTop)}}const Dt=/deg|g?rad|turn$/i;function $t(e){const t=parseFloat(e)||0;if(0!==t){const[n="rad"]=String(e).match(Dt)||[];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 Ft="contain";function Ut(e,t=Ft){const{aspectRatio:n}=e;let{width:r,height:a}=e;const o=kt(r),i=kt(a);if(o&&i){const e=a*n;t===Ft&&e>r||"cover"===t&&e<r?a=r/n:r=a*n}else o?a=r/n:i&&(r=a*n);return{width:r,height:a}}function Ht(e,...t){if(0===t.length)return e;const[n,r,a,o,i,l]=e,[s,c,u,d,f,p]=t[0];return Ht(e=[n*s+a*c,r*s+o*c,n*u+a*d,r*u+o*d,n*f+a*p+i,r*f+o*p+l],...t.slice(1))}const Wt=/left|top|width|height/i,Bt="open",Vt=new WeakMap,qt=new WeakMap,Kt=new Map,Qt=Le.document&&Array.isArray(Le.document.adoptedStyleSheets)&&"replaceSync"in Le.CSSStyleSheet.prototype;class Yt extends HTMLElement{get $sharedStyle(){return(this.themeColor?`:host{--theme-color: ${this.themeColor};}`:"")+":host([hidden]){display:none!important}"}constructor(){var e,t;super(),this.shadowRootMode=Bt,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&&Kt.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=Rt(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=qt.get(this),t=this.$sharedStyle;e&&t&&(Qt?e.replaceSync(t):e.textContent=t);break}}}$propertyChangedCallback(e,t,n){if(!Object.is(n,t))switch(e=Nt(e),typeof n){case"boolean":!0===n?this.hasAttribute(e)||this.setAttribute(e,""):this.removeAttribute(e);break;case"number":n=vt(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=Rt(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.attachShadow({mode:this.shadowRootMode||Bt});if(this.shadowRoot||Vt.set(this,e),qt.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(){qt.has(this)&&qt.delete(this),Vt.has(this)&&Vt.delete(this)}$getTagNameOf(e){var t;return null!==(t=Kt.get(e))&&void 0!==t?t:e}$setStyles(e){return Object.keys(e).forEach(t=>{let n=e[t];wt(n)&&(n=0!==n&&Wt.test(t)?`${n}px`:String(n)),this.style[t]=n}),this}$getShadowRoot(){return this.shadowRoot||Vt.get(this)}$addStyles(e){let t;const n=this.$getShadowRoot();return Qt?(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({},Lt),{detail:n}),r)))}(this,e,t,n)}$nextTick(e){return function(e,t){return t?It.then(e?t.bind(e):t):It}(this,e)}static $define(e,t){xt(e)&&(t=e,e=""),e||(e=this.$name||this.name),e=Nt(e),Ae&&Le.customElements&&!Le.customElements.get(e)&&customElements.define(e,this,t)}}Yt.$version="2.0.0";class Gt extends Yt{constructor(){super(...arguments),this.$onPointerDown=null,this.$onPointerMove=null,this.$onPointerUp=null,this.$onWheel=null,this.$wheeling=!1,this.$pointers=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=Je,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),Ot(this,lt,this.$onPointerDown)),this.$onPointerMove||(this.$onPointerMove=this.$handlePointerMove.bind(this),Ot(this.ownerDocument,st,this.$onPointerMove)),this.$onPointerUp||(this.$onPointerUp=this.$handlePointerUp.bind(this),Ot(this.ownerDocument,ct,this.$onPointerUp)),this.$onWheel||(this.$onWheel=this.$handleWheel.bind(this),Ot(this,pt,this.$onWheel,{passive:!1,capture:!0}))}$unbind(){this.$onPointerDown&&(jt(this,lt,this.$onPointerDown),this.$onPointerDown=null),this.$onPointerMove&&(jt(this.ownerDocument,st,this.$onPointerMove),this.$onPointerMove=null),this.$onPointerUp&&(jt(this.ownerDocument,ct,this.$onPointerUp),this.$onPointerUp=null),this.$onWheel&&(jt(this,pt,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)&&(wt(t)&&1!==t||wt(n)&&0!==n||e.ctrlKey))return;const{$pointers:a}=this;let o="";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?o=Xe:_t(e.target)&&(o=e.target.action||e.target.getAttribute("action")||""),!1!==this.$emit(gt,{action:o,relatedEvent:e})&&(e.preventDefault(),this.$action=o,this.style.willChange="transform")}$handlePointerMove(e){const{$action:t,$pointers:n}=this;if(this.disabled||t===Je||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,o=n.get(t);o&&Object.assign(o,{endX:r,endY:a})}const r={action:t,relatedEvent:e};if(t===Xe){const t=new Map(n);let a=0,o=0,i=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,f=0,p=0,h=0,m=0;if(0===n?r<0?h=2*Math.PI:r>0&&(h=Math.PI):n>0?h=Math.PI/2+Math.atan(r/n):n<0&&(h=1.5*Math.PI+Math.atan(r/n)),0===u?d<0?m=2*Math.PI:d>0&&(m=Math.PI):u>0?m=Math.PI/2+Math.atan(d/u):u<0&&(m=1.5*Math.PI+Math.atan(d/u)),m>0||h>0){const n=m-h,r=Math.abs(n);r>a&&(a=r,i=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?f=Math.sqrt(n*n+r*r):n>0?f=n:r>0&&(f=r),u>0&&d>0?p=Math.sqrt(u*u+d*d):u>0?p=u:d>0&&(p=d),f>0&&p>0){const n=(p-f)/f,r=Math.abs(n);r>o&&(o=r,l=n,s=(e.startX+t.startX)/2,c=(e.startY+t.startY)/2)}})});const u=a>0,d=o>0;u&&d?(r.rotate=i,r.scale=l,r.centerX=s,r.centerY=c):u?(r.action=Ge,r.rotate=i,r.centerX=s,r.centerY=c):d?(r.action=Ye,r.scale=l,r.centerX=s,r.centerY=c):r.action=Je}else{const[e]=Array.from(n.values());Object.assign(r,e)}n.forEach(e=>{e.startX=e.endX,e.startY=e.endY}),r.action!==Je&&this.$emit(ht,r,{cancelable:!1})}$handlePointerUp(e){const{$action:t,$pointers:n}=this;if(!this.disabled&&t!==Je&&!1!==this.$emit(mt,{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=Je)}}$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(ht,{action:Ye,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,o=this.offsetHeight,i=1;Ct(e)&&(kt(e.width)||kt(e.height))&&(({width:a,height:o}=Ut({aspectRatio:a/o,width:e.width,height:e.height})),i=a/this.offsetWidth),r.width=a,r.height=o;const l=this.querySelector(this.$getTagNameOf(We));l?l.$ready().then(n=>{const s=r.getContext("2d");if(s){const[t,c,u,d,f,p]=l.$getTransform();let h=f,m=p,g=n.naturalWidth,b=n.naturalHeight;1!==i&&(h*=i,m*=i,g*=i,b*=i);const y=g/2,v=b/2;s.fillStyle="transparent",s.fillRect(0,0,a,o),Ct(e)&&Et(e.beforeDraw)&&e.beforeDraw.call(this,s,r),s.save(),s.translate(y,v),s.transform(t,c,u,d,h,m),s.translate(-y,-v),s.drawImage(n,0,0,g,b),s.restore()}t(r)}).catch(n):t(r)})}}Gt.$name=$e,Gt.$version="2.0.0";const Xt=new WeakMap,Jt=["alt","crossorigin","decoding","importance","loading","referrerpolicy","sizes","src","srcset"];class Zt extends Yt{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}set $canvas(e){Xt.set(this,e)}get $canvas(){return Xt.get(this)}static get observedAttributes(){return super.observedAttributes.concat(Jt,["initial-center-size","rotatable","scalable","skewable","translatable"])}attributeChangedCallback(e,t,n){Object.is(n,t)||(super.attributeChangedCallback(e,t,n),Jt.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($e));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),Ot(t,gt,this.$onCanvasActionStart),Ot(t,mt,this.$onCanvasActionEnd),Ot(t,ht,this.$onCanvasAction)),this.$onLoad=this.$handleLoad.bind(this),Ot(e,ft,this.$onLoad),this.$getShadowRoot().appendChild(e)}disconnectedCallback(){const{$image:e,$canvas:t}=this;t&&(this.$onCanvasActionStart&&(jt(t,gt,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(jt(t,mt,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasAction&&(jt(t,ht,this.$onCanvasAction),this.$onCanvasAction=null)),e&&this.$onLoad&&(jt(e,ft,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!==Xe||this.rotatable&&this.scalable||(r=this.rotatable?Ge:this.scalable?Ye:Je),r){case Qe:if(this.translatable){let r=null;e&&(r=e.target.closest(this.$getTagNameOf(Be))),r||(r=t.querySelector(this.$getTagNameOf(Be))),r&&r.multiple&&!r.active&&(r=t.querySelector(`${this.$getTagNameOf(Be)}[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 Ge: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 Ye:if(this.scalable)if(e){const t=e.target.closest(this.$getTagNameOf(Be));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 Xe: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),o=Math.sin(t),[i,l,s,c]=[a*r,o*r,-o*r,a*r];if(e){const t=this.getBoundingClientRect(),n=e.clientX-t.x,r=e.clientY-t.y,[a,o,u,d]=this.$matrix,f=n-t.width/2,p=r-t.height/2,h=(f*d-u*p)/(a*d-u*o),m=(p*a-o*f)/(a*d-u*o);this.$transform(i,l,s,c,h*(1-i)+m*s,m*(1-c)+h*l)}else this.$transform(i,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=()=>{jt(t,ut,o),e(t)},o=()=>{jt(t,ft,a),n(r)};At(t,ft,a),At(t,ut,o)}});return Et(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:o,y:i,width:l,height:s}=this.getBoundingClientRect(),c=o+l/2,u=i+s/2,d=n.x+r/2,f=n.y+a/2;if(this.$move(d-c,f-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&&wt(e)&&wt(t)){const[n,r,a,o]=this.$matrix,i=(e*o-a*t)/(n*o-a*r),l=(t*n-r*e)/(n*o-a*r);this.$translate(i,l)}return this}$moveTo(e,t=e){if(this.translatable&&wt(e)&&wt(t)){const[n,r,a,o]=this.$matrix,i=(e*o-a*t)/(n*o-a*r),l=(t*n-r*e)/(n*o-a*r);this.$setTransform(n,r,a,o,i,l)}return this}$rotate(e,t,n){if(this.rotatable){const r=$t(e),a=Math.cos(r),o=Math.sin(r),[i,l,s,c]=[a,o,-o,a];if(wt(t)&&wt(n)){const[e,r,a,o]=this.$matrix,{width:u,height:d}=this.getBoundingClientRect(),f=t-u/2,p=n-d/2,h=(f*o-a*p)/(e*o-a*r),m=(p*e-r*f)/(e*o-a*r);this.$transform(i,l,s,c,h*(1-i)-m*s,m*(1-c)-h*l)}else this.$transform(i,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,wt(t)&&wt(n)){const[r,a,o,i]=this.$matrix,{width:l,height:s}=this.getBoundingClientRect(),c=t-l/2,u=n-s/2,d=(c*i-o*u)/(r*i-o*a),f=(u*r-a*c)/(r*i-o*a);this.$transform(e,0,0,e,d*(1-e),f*(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=$t(e),r=$t(t);this.$transform(1,Math.tan(r),Math.tan(n),1,0,0)}return this}$translate(e,t=e){return this.translatable&&wt(e)&&wt(t)&&this.$transform(1,0,0,1,e,t),this}$transform(e,t,n,r,a,o){return wt(e)&&wt(t)&&wt(n)&&wt(r)&&wt(a)&&wt(o)?this.$setTransform(Ht(this.$matrix,[e,t,n,r,a,o])):this}$setTransform(e,t,n,r,a,o){if((this.rotatable||this.scalable||this.skewable||this.translatable)&&(Array.isArray(e)&&([e,t,n,r,a,o]=e),wt(e)&&wt(t)&&wt(n)&&wt(r)&&wt(a)&&wt(o))){const i=[...this.$matrix],l=[e,t,n,r,a,o];if(!1===this.$emit(yt,{matrix:l,oldMatrix:i}))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])}}Zt.$name=We,Zt.$version="2.0.0";const en=new WeakMap;class tn extends Yt{constructor(){super(...arguments),this.$onCanvasChange=null,this.$onCanvasActionEnd=null,this.$onCanvasActionStart=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){en.set(this,e)}get $canvas(){return en.get(this)}static get observedAttributes(){return super.observedAttributes.concat(["height","width","x","y"])}connectedCallback(){super.connectedCallback();const e=this.closest(this.$getTagNameOf($e));if(e){this.$canvas=e,this.style.position="absolute";const t=e.querySelector(this.$getTagNameOf(Be));t&&(this.$onCanvasActionStart=e=>{t.hidden&&e.detail.action===Ke&&(this.hidden=!1)},this.$onCanvasActionEnd=e=>{t.hidden&&e.detail.action===Ke&&(this.hidden=!0)},this.$onCanvasChange=e=>{const{x:n,y:r,width:a,height:o}=e.detail;this.$change(n,r,a,o),(t.hidden||0===n&&0===r&&0===a&&0===o)&&(this.hidden=!0)},Ot(e,gt,this.$onCanvasActionStart),Ot(e,mt,this.$onCanvasActionEnd),Ot(e,bt,this.$onCanvasChange))}this.$render()}disconnectedCallback(){const{$canvas:e}=this;e&&(this.$onCanvasActionStart&&(jt(e,gt,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(jt(e,mt,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasChange&&(jt(e,bt,this.$onCanvasChange),this.$onCanvasChange=null)),super.disconnectedCallback()}$change(e,t,n=this.width,r=this.height){return wt(e)&&wt(t)&&wt(n)&&wt(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:Le.innerWidth})}}tn.$name=Ve,tn.$version="2.0.0";class nn extends Yt{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=Je,this.plain=!1,this.slottable=!1,this.themeColor="rgba(51, 153, 255, 0.5)"}static get observedAttributes(){return super.observedAttributes.concat(["action","plain"])}}nn.$name=He,nn.$version="2.0.0";const rn=new WeakMap;class an extends Yt{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){rn.set(this,e)}get $canvas(){return rn.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(()=>{kt(n)&&n<=1&&this.$initSelection(!0,!0)});break;case"keyboard":this.$nextTick(()=>{this.$canvas&&(n?this.$onDocumentKeyDown||(this.$onDocumentKeyDown=this.$handleKeyDown.bind(this),Ot(this.ownerDocument,dt,this.$onDocumentKeyDown)):this.$onDocumentKeyDown&&(jt(this.ownerDocument,dt,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(bt,{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($e));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),Ot(e,gt,this.$onCanvasActionStart),Ot(e,mt,this.$onCanvasActionEnd),Ot(e,ht,this.$onCanvasAction)):this.$render()}disconnectedCallback(){const{$canvas:e}=this;e&&(this.$onCanvasActionStart&&(jt(e,gt,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(jt(e,mt,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasAction&&(jt(e,ht,this.$onCanvasAction),this.$onCanvasAction=null)),super.disconnectedCallback()}$getSelections(){let e=[];return this.parentElement&&(e=Array.from(this.parentElement.querySelectorAll(this.$getTagNameOf(Be)))),e}$initSelection(e=!1,t=!1){const{initialCoverage:n,parentElement:r}=this;if(kt(n)&&r){const a=this.aspectRatio||this.initialAspectRatio;let o=(t?0:this.width)||r.offsetWidth*n,i=(t?0:this.height)||r.offsetHeight*n;kt(a)&&({width:o,height:i}=Ut({aspectRatio:a,width:o,height:i})),this.$change(this.x,this.y,o,i),e&&this.$center(),this.$initialSelection={x:this.x,y:this.y,width:this.width,height:this.height}}}$createSelection(){const e=this.cloneNode(!0);return this.hasAttribute("id")&&e.removeAttribute("id"),e.initialCoverage=NaN,this.active=!1,this.parentElement&&this.parentElement.insertBefore(e,this.nextSibling),e}$removeSelection(e=this){if(this.parentElement){const t=this.$getSelections();if(t.length>1){const n=t.indexOf(e),r=t[n+1]||t[n-1];r&&(e.active=!1,this.parentElement.removeChild(e),r.active=!0,r.$emit(bt,{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(bt,{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;if(!a&&this.multiple&&(a=this.$action||(null==r?void 0:r.target.action),this.$action=a),!a||this.hidden&&a!==Ke||this.multiple&&!this.active&&a!==Ye)return;const o=n.endX-n.startX,i=n.endY-n.startY,{width:l,height:s}=this;let{aspectRatio:c}=this;switch(!kt(c)&&r.shiftKey&&(c=kt(l)&&kt(s)?l/s:1),a){case Ke:if(0!==o&&0!==i){const{$canvas:e}=this,r=Mt(t);(this.multiple&&!this.hidden?this.$createSelection():this).$change(n.startX-r.left,n.startY-r.top,Math.abs(o),Math.abs(i),c),o<0?i<0?a=at:i>0&&(a=it):o>0&&(i<0?a=rt:i>0&&(a=ot)),e&&(e.$action=a)}break;case Qe:this.movable&&(this.dynamic||this.$actionStartTarget&&this.contains(this.$actionStartTarget))&&this.$move(o,i);break;case Ye:if(r&&this.zoomable&&(this.dynamic||this.contains(r.target))){const e=Mt(t);this.$zoom(n.scale,r.pageX-e.left,r.pageY-e.top)}break;default:this.$resize(a,o,i,c)}}$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=kt(r),{$canvas:o}=this;let{x:i,y:l,width:s,height:c}=this;switch(e){case Ze:l+=n,c-=n,c<0&&(e=tt,c=-c,l-=c),a&&(i+=(t=n*r)/2,s-=t,s<0&&(s=-s,i-=s));break;case et:s+=t,s<0&&(e=nt,s=-s,i-=s),a&&(l-=(n=t/r)/2,c+=n,c<0&&(c=-c,l-=c));break;case tt:c+=n,c<0&&(e=Ze,c=-c,l-=c),a&&(i-=(t=n*r)/2,s+=t,s<0&&(s=-s,i-=s));break;case nt:i+=t,s-=t,s<0&&(e=et,s=-s,i-=s),a&&(l+=(n=t/r)/2,c-=n,c<0&&(c=-c,l-=c));break;case rt:a&&(n=-t/r),l+=n,c-=n,s+=t,s<0&&c<0?(e=it,s=-s,c=-c,i-=s,l-=c):s<0?(e=at,s=-s,i-=s):c<0&&(e=ot,c=-c,l-=c);break;case at:a&&(n=t/r),i+=t,l+=n,s-=t,c-=n,s<0&&c<0?(e=ot,s=-s,c=-c,i-=s,l-=c):s<0?(e=rt,s=-s,i-=s):c<0&&(e=it,c=-c,l-=c);break;case ot:a&&(n=t/r),s+=t,c+=n,s<0&&c<0?(e=at,s=-s,c=-c,i-=s,l-=c):s<0?(e=it,s=-s,i-=s):c<0&&(e=rt,c=-c,l-=c);break;case it:a&&(n=-t/r),i+=t,s-=t,c+=n,s<0&&c<0?(e=rt,s=-s,c=-c,i-=s,l-=c):s<0?(e=ot,s=-s,i-=s):c<0&&(e=at,c=-c,l-=c)}return o&&o.$setAction(e),this.$change(i,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,o=r*e,i=a*e;let l=this.x,s=this.y;return wt(t)&&wt(n)?(l-=(o-r)*((t-this.x)/r),s-=(i-a)*((n-this.y)/a)):(l-=(o-r)/2,s-=(i-a)/2),this.$change(l,s,o,i)}$change(e,t,n=this.width,r=this.height,a=this.aspectRatio,o=!1){return this.$changing||!wt(e)||!wt(t)||!wt(n)||!wt(r)||n<0||r<0?this:(kt(a)&&({width:n,height:r}=Ut({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)&&!o?this:(this.hidden&&(this.hidden=!1),!1===this.$emit(bt,{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:o}=this,i=1;if(Ct(e)&&(kt(e.width)||kt(e.height))&&(({width:a,height:o}=Ut({aspectRatio:a/o,width:e.width,height:e.height})),i=a/this.width),r.width=a,r.height=o,!this.$canvas)return void t(r);const l=this.$canvas.querySelector(this.$getTagNameOf(We));l?l.$ready().then(n=>{const s=r.getContext("2d");if(s){const[t,c,u,d,f,p]=l.$getTransform(),h=-this.x,m=-this.y,g=(h*d-u*m)/(t*d-u*c),b=(m*t-c*h)/(t*d-u*c);let y=t*g+u*b+f,v=c*g+d*b+p,w=n.naturalWidth,k=n.naturalHeight;1!==i&&(y*=i,v*=i,w*=i,k*=i);const x=w/2,S=k/2;s.fillStyle="transparent",s.fillRect(0,0,a,o),Ct(e)&&Et(e.beforeDraw)&&e.beforeDraw.call(this,s,r),s.save(),s.translate(x,S),s.transform(t,c,u,d,y,v),s.translate(-x,-S),s.drawImage(n,0,0,w,k),s.restore()}t(r)}).catch(n):t(r)})}}an.$name=Be,an.$version="2.0.0";class on extends Yt{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))}}on.$name=Ue,on.$version="2.0.0";class ln extends Yt{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"])}}ln.$name=Fe,ln.$version="2.0.0";const sn=new WeakMap,cn=new WeakMap,un=new WeakMap,dn=new WeakMap,fn="vertical";class pn extends Yt{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=fn,this.selection="",this.slottable=!1}set $image(e){cn.set(this,e)}get $image(){return cn.get(this)}set $sourceImage(e){dn.set(this,e)}get $sourceImage(){return dn.get(this)}set $canvas(e){sn.set(this,e)}get $canvas(){return sn.get(this)}set $selection(e){un.set(this,e)}get $selection(){return un.get(this)}static get observedAttributes(){return super.observedAttributes.concat(["resize","selection"])}connectedCallback(){super.connectedCallback();let e=null;if(e=this.selection?this.ownerDocument.querySelector(this.selection):this.closest(this.$getTagNameOf(Be)),_t(e)){this.$selection=e,this.$onSelectionChange=this.$handleSelectionChange.bind(this),Ot(e,bt,this.$onSelectionChange);const t=e.closest(this.$getTagNameOf($e));if(t){this.$canvas=t;const e=t.querySelector(this.$getTagNameOf(We));e&&(this.$sourceImage=e,this.$image=e.cloneNode(!0),this.$getShadowRoot().appendChild(this.$image),this.$onSourceImageLoad=this.$handleSourceImageLoad.bind(this),this.$onSourceImageTransform=this.$handleSourceImageTransform.bind(this),Ot(e.$image,ft,this.$onSourceImageLoad),Ot(e,yt,this.$onSourceImageTransform))}this.$render()}}disconnectedCallback(){const{$selection:e,$sourceImage:t}=this;e&&this.$onSelectionChange&&(jt(e,bt,this.$onSelectionChange),this.$onSelectionChange=null),t&&this.$onSourceImageLoad&&(jt(t.$image,ft,this.$onSourceImageLoad),this.$onSourceImageLoad=null),t&&this.$onSourceImageTransform&&(jt(t,yt,this.$onSourceImageTransform),this.$onSourceImageTransform=null),super.disconnectedCallback()}$handleSelectionChange(e){this.$render(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(()=>{setTimeout(()=>{this.$render()},50)}))}$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:o,width:i,height:l}=e,s={},{clientWidth:c,clientHeight:u}=this;let d=c,f=u,p=NaN;switch(this.resize){case"both":p=1,d=i,f=l,s.width=i,s.height=l;break;case"horizontal":p=l>0?u/l:0,d=i*p,s.width=d;break;case fn:p=i>0?c/i:0,f=l*p,s.height=f;break;default:c>0?p=i>0?c/i:0:u>0&&(p=l>0?u/l:0)}this.$scale=p,this.$setStyles(s),this.$sourceImage&&this.$transformImageByOffset(null!=t?t:this.$sourceImage.$getTransform(),-a,-o)}$transformImageByOffset(e,t,n){const{$image:r,$scale:a,$sourceImage:o}=this;if(o&&r&&a>=0){const[o,i,l,s,c,u]=e,d=(t*s-l*n)/(o*s-l*i),f=(n*o-i*t)/(o*s-l*i),p=o*d+l*f+c,h=i*d+s*f+u;r.$ready(e=>{this.$setStyles.call(r,{width:e.naturalWidth*a,height:e.naturalHeight*a})}),r.$setTransform(o,i,l,s,p*a,h*a)}}}function hn(){const[e,t]=p.useState(!1),[n,r]=p.useState(null),[a,o]=p.useState(null),i=async(e,a)=>{if(!e||!a)return r("ID de asset y configuración de variante son requeridos"),null;t(!0),r(null),o(null);try{const t=await async function(e,{variant_name:t,width:r,height:a,crop_params:o,preset_aspect:i=null,preset_size:l=null,output_format:s="webp"}){try{const n=[{name:t,width:r,height:a,output_format:s,crop_params:o}];return i&&(n[0].preset_aspect=i),l&&(n[0].preset_size=l),function(e){if(!e?.success||!e?.data)return{result:null};const t=e.data;return{result:{job_id:t.job_id,asset_id:t.asset_id,variants_requested:t.variants_requested||[],processing_mode:t.async?"async":"sync",estimated_completion:t.estimated_completion,variant_statuses:(t.variant_statuses||[]).map(e=>({name:e.name,status:e.status,size:e.expected_size,format:e.format}))}}}(await te({endpoint:`/assets/${e}/variants`,method:"POST",body:{variants:n,async:!1},basePath:ie,useJWT:!0}))}catch(n){throw oe(n)}}(e,{variant_name:a.name,width:a.width,height:a.height,crop_params:a.crop_params,preset_aspect:a.preset_aspect,preset_size:a.preset_size,output_format:a.output_format});if(t?.result)return o(t.result),t.result;throw new Error("No se pudo crear la variante")}catch(i){return console.error("Error creating variant:",i),r(i.message||"Error desconocido al crear variante"),null}finally{t(!1)}};return{createVariant:i,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 i(e,r)},loading:e,error:n,createdVariant:a,reset:()=>{r(null),o(null)}}}pn.$name=qe,pn.$version="2.0.0",
56
56
  /*! Cropper.js v2.0.0 | (c) 2015-present Chen Fengyuan | MIT */
57
- Gt.$define(),ln.$define(),on.$define(),nn.$define(),Zt.$define(),an.$define(),tn.$define(),pn.$define();class mn{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,o)=>{if(!this.image)return!1;try{return this.image.$setTransform(e,t,n,r,a,o),!0}catch(i){return console.warn("Error setting transform:",i),!1}},resetZoom:()=>{if(!this.image)return!1;try{const e=this.image.$getTransform();if(!e)return!1;const[t,n,r,a,o,i]=e,l=Math.sqrt(t*t+n*n),s=Math.sqrt(r*r+a*a),c=t/l,u=n/l,d=r/s,f=a/s;return this.image.$setTransform(c,u,d,f,o,i),!0}catch(e){return console.warn("Error resetting zoom:",e),!1}},setZoom:e=>{if(!this.image||e<=0)return!1;try{const t=this.image.$getTransform();if(!t)return!1;const[n,r,a,o,i,l]=t,s=Math.sqrt(n*n+r*r),c=Math.sqrt(a*a+o*o),u=n/s*e,d=r/s*e,f=a/c*e,p=o/c*e;return this.image.$setTransform(u,d,f,p,i,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,o=t.height*r/n.naturalHeight,i=Math.min(a,o,1);return this.transform.setZoom(i)}catch(t){return console.warn("Error fitting to canvas:",t),!1}}};selection={center:()=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$center(),!0}catch(e){return console.warn("Error centering selection:",e),!1}},reset:()=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$reset(),!0}catch(e){return console.warn("Error resetting selection:",e),!1}},setCoverage:e=>{if(!this.selectionElement||e<0||e>1)return!1;try{return this.selectionElement.initialCoverage=e,this.selectionElement.$reset(),!0}catch(t){return console.warn("Error setting coverage:",t),!1}},setAspectRatio:e=>{if(!this.selectionElement)return!1;try{let t;if(""===e||null==e)t=NaN;else if("number"==typeof e)t=e;else{if("string"!=typeof e)return console.warn("Unsupported aspect ratio type:",typeof e,e),!1;if(e.includes("/")){const[n,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(o){return console.warn("Error changing selection:",o),!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,o,i]=e;return this.transform.setTransform(-t,n,r,a,o,i)},flipVertical:()=>{const e=this.transform.getTransform();if(!e)return!1;const[t,n,r,a,o,i]=e;return this.transform.setTransform(t,n,r,-a,o,i)},setupInitialView:async(e={})=>{const{paspartuFactor:t=.85,retries:n=3,retryDelay:r=200}=e;return new Promise(e=>{const a=(o=0)=>{if(!this.isReady)return o<n?void setTimeout(()=>a(o+1),r):void e(!1);try{const i=this.canvasElement.getBoundingClientRect();let l=this.image.querySelector("img")||this.image;if(!l?.naturalWidth||!l?.naturalHeight)return o<n?void setTimeout(()=>a(o+1),r):(this.transform.center(),void e(!1));if(i.width>0&&i.height>0){const n=i.width*t/l.naturalWidth,r=i.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(i){console.warn("Error in setup:",i),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:o,onActionEnd:i}=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(o){const e=e=>o(e.detail);this.canvasElement.addEventListener("actionmove",e),l.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionmove",e)})}if(i){const e=e=>i(e.detail);this.canvasElement.addEventListener("actionend",e),l.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionend",e)})}}return()=>{l.forEach(e=>e())}}}function gn({image:e,onSave:t,onCancel:n,onDelete:r,deleting:a=!1,onVariantCreated:o=null}){const[i,l]=p.useState(!1),[s,c]=p.useState(null),[u,d]=p.useState(!1),[f,h]=p.useState(""),[m,g]=p.useState(!0),[b,y]=p.useState(!0),[v,w]=p.useState({horizontal:!1,vertical:!1}),[k,x]=p.useState(!1),[S,C]=p.useState({current:1,percentage:100}),E=window.limboCore?.accessibilityManager,_=p.useMemo(()=>{const e=window.limboCore?.config?.getGlobal()||{};return e.cropper?.allowedAspectRatios||[{label:"📐 Libre",value:"",ratio:null},{label:"⬜ 1:1 (Cuadrado)",value:"1",ratio:1},{label:"📺 4:3 (Clásico)",value:"4/3",ratio:4/3},{label:"🖥️ 16:9 (Widescreen)",value:"16/9",ratio:16/9},{label:"📷 3:2 (Foto)",value:"3/2",ratio:1.5},{label:"📱 2:3 (Retrato)",value:"2/3",ratio:2/3},{label:"📲 9:16 (Stories)",value:"9/16",ratio:9/16}]},[]),{createCropVariant:T,loading:N,error:P}=hn(),R=((e,t={})=>{const n=p.useRef(null),r=p.useRef(null),a=p.useRef(null),o=p.useRef(null),[i,l]=p.useState(null),[s,c]=p.useState(null),[u,d]=p.useState(!1),[f,h]=p.useState(!0),[m,g]=p.useState(0),b={aspectRatio:"",shade:!0,paspartuFactor:.85,...t};p.useEffect(()=>{n.current&&r.current&&a.current&&(o.current=new mn(n,r,a),d(!0))},[]),p.useEffect(()=>{if(o.current)return o.current.setupEventListeners({onSelectionChange:e=>{l(e)},onImageTransform:()=>{g(e=>e+1)}})},[u]),p.useEffect(()=>{o.current&&e&&(async()=>{o.current.selection.setAspectRatio(b.aspectRatio),o.current.canvas.setBackground(b.shade),await o.current.utils.setupInitialView({paspartuFactor:b.paspartuFactor});const e=await o.current.utils.checkExportability();h(e);const t=r.current?.querySelector("img")||r.current;t?.naturalWidth&&t?.naturalHeight&&c({naturalWidth:t.naturalWidth,naturalHeight:t.naturalHeight,currentWidth:t.width,currentHeight:t.height})})()},[e,b.aspectRatio,b.shade,b.paspartuFactor]);const y=p.useCallback(()=>({move:(e,t)=>o.current?.transform.move(e,t)||!1,zoom:e=>o.current?.transform.zoom(e)||!1,rotate:e=>o.current?.transform.rotate(e)||!1,center:()=>o.current?.transform.center()||!1,reset:()=>o.current?.transform.reset()||!1,resetZoom:()=>o.current?.transform.resetZoom()||!1,setZoom:e=>o.current?.transform.setZoom(e)||!1,getZoom:()=>o.current?.transform.getZoom()||1,fitToCanvas:e=>o.current?.transform.fitToCanvas(e)||!1,flipHorizontal:()=>o.current?.utils.flipHorizontal()||!1,flipVertical:()=>o.current?.utils.flipVertical()||!1}),[]),v=p.useCallback(()=>({center:()=>o.current?.selection.center()||!1,reset:()=>o.current?.selection.reset()||!1,setCoverage:e=>o.current?.selection.setCoverage(e)||!1,setAspectRatio:e=>o.current?.selection.setAspectRatio(e)||!1,toCanvas:e=>o.current?.selection.toCanvas(e)||Promise.resolve(null)}),[]),w=p.useCallback(()=>({resetAll:()=>{if(o.current){const e=o.current.utils.resetAll();return l(null),e}return!1},setBackground:e=>o.current?.canvas.setBackground(e)||!1,resetZoomOnly:()=>o.current?.utils.resetZoomOnly()||!1,getZoomInfo:()=>o.current?.utils.getZoomInfo()||{current:1,percentage:100,isZoomedIn:!1,isZoomedOut:!1}}),[]);return{refs:{canvasRef:n,imageRef:r,selectionRef:a},state:{cropData:i,imageInfo:s,isReady:u,canExport:f,transformVersion:m},transform:y(),selection:v(),utils:w(),manager:o.current}})(e,{aspectRatio:f,showGrid:m,shade:b,initialCoverage:.5,paspartuFactor:.85}),{refs:z,state:j,transform:O,selection:A,utils:L}=R,{canvasRef:I,imageRef:M,selectionRef:D}=z,{cropData:$,imageInfo:F,canExport:U,transformVersion:H}=j,W=p.useMemo(()=>F||{naturalWidth:e.width||1920,naturalHeight:e.height||1080,currentWidth:e.width||1920,currentHeight:e.height||1080},[F,e.width,e.height]),B=p.useCallback(()=>g(e=>!e),[]),V=p.useCallback(()=>y(e=>!e),[]),q=p.useCallback(()=>x(e=>!e),[]),Q=p.useCallback(()=>O.center(),[O]),Y=p.useCallback(()=>A.center(),[A]),G=p.useCallback(()=>A.reset(),[A]),X=p.useCallback((e,t)=>O.move(e,t),[O]),J=p.useCallback(e=>O.zoom(e),[O]),Z=p.useCallback(e=>O.rotate(e),[O]),ee=p.useCallback(()=>{L.resetAll(),h(""),g(!0),y(!0),w({horizontal:!1,vertical:!1}),l(!1),c(null)},[L]),te=p.useCallback(e=>{A.setCoverage(e)},[A]),ne=p.useCallback(()=>L.resetZoomOnly(),[L]),re=p.useCallback(()=>{w(e=>{const t=!e.horizontal;return O.flipHorizontal(),{...e,horizontal:t}})},[O]),ae=p.useCallback(()=>{w(e=>{const t=!e.vertical;return O.flipVertical(),{...e,vertical:t}})},[O]),oe=p.useCallback(e=>{h(e);const t=_.find(t=>t.value===e),n=t?t.ratio:e;A.setAspectRatio(n)},[A,_]),ie=p.useCallback(async()=>{if(!U)return null;try{const e=await A.toCanvas({width:800,height:600,imageSmoothingEnabled:!0,imageSmoothingQuality:"high"});return e?e.toDataURL("image/jpeg",.9):null}catch(e){return console.warn("Error generating preview:",e),null}},[U,A]),le=p.useCallback(async()=>{if(i)return l(!1),c(null),void d(!1);if(U){l(!0),d(!0);try{const e=await ie();e?c(e):(l(!1),alert("No se puede exportar el recorte por restricciones de CORS en la imagen original."))}finally{d(!1)}}else alert("No se puede exportar el recorte por restricciones de CORS en la imagen original.")},[U,ie,i]),se=p.useCallback(async()=>{if(!U){const e="No se puede exportar el recorte por restricciones de CORS en la imagen original.";return E?.announceError(e),void alert(e)}if(!j.isReady){const e="El cropper aún no está inicializado. Espera un momento e inténtalo de nuevo.";return E?.announceError(e),void alert(e)}E?.announce("Creando variante recortada de la imagen");try{if(!$||!W)throw console.error("❌ Datos faltantes:",{cropData:$,effectiveImageInfo:W}),new Error(`No hay datos de recorte disponibles. CropData: ${!!$}, ImageInfo: ${!!W}`);if(!$.x&&0!==$.x||!$.y&&0!==$.y||!$.width||!$.height)throw console.error("❌ CropData inválido:",$),new Error("Los datos de recorte no tienen las propiedades esperadas");if(!W.naturalWidth||!W.naturalHeight)throw console.error("❌ ImageInfo inválido:",W),new Error("Los datos de imagen no tienen las dimensiones esperadas");const{x:n,y:r,width:a,height:i}=$,{naturalWidth:l,naturalHeight:s}=W,c={x:n/l,y:r/s,width:a/l,height:i/s},u=a/i;let d,f;const p=1200;u>1?(d=Math.min(a,p),f=Math.round(d/u)):(f=Math.min(i,p),d=Math.round(f*u));const h=Date.now(),[m]=e.filename.split("."),g=`${m}_crop_${h}`,b=await T(e.id,c,{name:g,width:d,height:f,format:"webp",quality:90});b&&(E?.announceSuccess(`Variante recortada creada: ${g}`),o?.(e.id,b),t(b))}catch(n){console.warn("Error creating crop variant:",n);const e="No se pudo crear la variante recortada. Inténtalo de nuevo.";E?.announceError(e),alert(e)}},[U,$,F,W,e.filename,e.id,T,t,o,E,j.isReady]);return p.useEffect(()=>{l(!1),c(null)},[e]),p.useEffect(()=>{R.manager&&(A.setAspectRatio(f),L.setBackground(b))},[f,b,R.manager,A,L]),p.useEffect(()=>{if(R.manager&&R.manager.utils)try{const e=R.manager.transform.getZoom(),t={current:e,isZoomedIn:e>1,isZoomedOut:e<1,percentage:Math.round(100*e)};C(t)}catch(e){console.warn("Error updating zoom info:",e)}},[H,R.manager]),p.useEffect(()=>{if(!i||!U)return;const e=setTimeout(async()=>{d(e=>!s&&!e||e);try{const e=await ie();e&&c(e)}finally{d(!1)}},300);return()=>{clearTimeout(e),d(!1)}},[$,H,i,U,ie,f,v,s]),p.useEffect(()=>{const e=I.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)}},[I]),e?K.jsxs("div",{className:"limbo-cropper-view px-2 border-2 border-gray-200/50 rounded-lg min-w-fit max-w-7xl mx-auto h-screen flex flex-col",children:[K.jsxs("div",{className:"limbo-cropper-header flex flex-col sm:flex-row justify-between items-start sm:items-center p-4 sm:p-6 pb-4 border-b border-gray-200 bg-white z-10 flex-shrink-0 gap-4 sm:gap-2",children:[K.jsxs("div",{className:"flex-1 min-w-0",children:[K.jsx("h2",{className:"text-lg sm:text-xl font-bold text-gray-800 truncate",children:"Recortar imagen"}),K.jsx("p",{className:"text-sm text-gray-600 mt-1 truncate",children:e.filename})]}),K.jsxs("div",{className:"flex gap-2 w-full sm:w-auto",children:[K.jsx("button",{onClick:n,disabled:N,className:"limbo-btn limbo-btn-secondary px-4 py-2 flex-1 sm:flex-initial",children:"Cancelar"}),K.jsx("button",{onClick:()=>r?.(e),disabled:a|N,className:"limbo-btn limbo-btn-danger px-4 py-2 flex-1 sm:flex-initial","aria-label":`Eliminar imagen ${e.filename}`,children:a?"Eliminando...":"Eliminar"})]})]}),K.jsxs("div",{className:"limbo-cropper-status bg-white border-gray-100 px-4 sm:px-6 py-2 pb-0 flex-shrink-0",children:[P&&K.jsxs("div",{className:"alert alert-danger mb-2 text-sm",role:"alert",children:[K.jsx("strong",{children:"Error:"})," ",P]}),$&&$.width>0&&K.jsxs("div",{className:"alert alert-info mb-2 text-sm",role:"status",children:[K.jsx("strong",{children:"Área:"})," ",Math.round($.width)," ×"," ",Math.round($.height)," px"]}),F&&K.jsxs("div",{className:"alert alert-secondary mb-2 text-sm",role:"status",children:[K.jsx("strong",{children:"Original:"})," ",F.naturalWidth," ×"," ",F.naturalHeight," px",F.currentWidth!==F.naturalWidth&&K.jsxs("span",{className:"ml-2 sm:ml-3 text-xs block sm:inline",children:["(Mostrada: ",Math.round(F.currentWidth)," ×"," ",Math.round(F.currentHeight)," px)"]})]}),!U&&K.jsx("div",{className:"alert alert-warning mb-2 text-sm",role:"alert",children:"⚠️ No se puede exportar por restricciones CORS"})]}),K.jsxs("div",{className:"flex flex-col md:flex-row flex-1 overflow-hidden rounded-lg gap-4 md:gap-0 cropper-main-content-area",children:[K.jsx("div",{className:"flex-1 relative min-w-0 order-2 md:order-1",children:K.jsxs("div",{className:"limbo-cropper-container absolute inset-2 sm:inset-4 bg-white rounded-lg border-2 border-gray-200 shadow-lg overflow-hidden",children:[i&&K.jsxs("div",{className:"absolute top-2 sm:top-4 right-2 sm:right-4 bg-white rounded-lg border border-gray-300 p-2 sm:p-3 z-50 shadow-xl w-48 sm:w-64 max-w-[calc(50%-1rem)] sm:max-w-[calc(50%-2rem)] md:min-w-1/4",children:[K.jsxs("div",{className:"flex justify-between items-center mb-2",children:[K.jsx("h3",{className:"text-xs font-semibold text-gray-700",children:"Vista previa"}),K.jsx("button",{onClick:()=>{l(!1),c(null)},className:"text-gray-400 hover:text-gray-600 p-1 -m-1","aria-label":"Cerrar vista previa",children:K.jsx("span",{className:"icon icon-close-small text-xs"})})]}),K.jsx("div",{className:"bg-gray-50 rounded p-2 flex justify-center items-center min-h-[80px] relative",children:s?K.jsxs("div",{className:"relative w-full h-full flex justify-center items-center",children:[K.jsx("img",{src:s,alt:"Vista previa del recorte",className:"max-w-full max-h-80 object-contain rounded shadow-sm"}),u&&K.jsx("div",{className:"absolute top-1 right-1 bg-blue-500 rounded-full p-1",children:K.jsx("div",{className:"animate-spin w-3 h-3 border border-white border-t-transparent rounded-full"})})]}):K.jsxs("div",{className:"flex flex-col items-center justify-center",children:[K.jsx("div",{className:"animate-spin w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full mb-2"}),K.jsx("span",{className:"text-xs text-gray-500",children:"Generando..."})]})})]}),K.jsxs("cropper-canvas",{ref:I,style:{width:"100%",height:"100%",display:"block"},background:!!b||void 0,id:"limbo-cropperjs-canvas",tabindex:"-1",onKeyDown:e=>{"Delete"!==e.key&&"Backspace"!==e.key||(e.preventDefault(),e.stopPropagation())},children:[K.jsx("cropper-image",{ref:M,src:e.url||e.path,alt:e.filename,id:"limbo-cropperjs-image",action:"move",crossOrigin:"anonymous",rotatable:!0,scalable:!0,skewable:!0,translatable:!0}),K.jsxs("cropper-selection",{ref:D,"initial-coverage":"0.5",movable:!0,resizable:!0,keyboard:"false",action:"move",style:{cursor:"move"},"data-prevent-delete":"true",tabindex:"-1",children:[m&&K.jsx("cropper-grid",{role:"grid",action:"move",covered:!0,bordered:!0}),K.jsx("cropper-handle",{action:"move",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:"32px",height:"32px",zIndex:"10"}}),K.jsx("cropper-handle",{action:"n-resize"}),K.jsx("cropper-handle",{action:"e-resize"}),K.jsx("cropper-handle",{action:"s-resize"}),K.jsx("cropper-handle",{action:"w-resize"}),K.jsx("cropper-handle",{action:"ne-resize"}),K.jsx("cropper-handle",{action:"nw-resize"}),K.jsx("cropper-handle",{action:"se-resize"}),K.jsx("cropper-handle",{action:"sw-resize"})]})]})]})}),K.jsx("div",{className:"limbo-cropper-controls w-full md:w-80 bg-white border-t md:border-t-0 md:border-l border-gray-200 overflow-y-auto flex-shrink-0 order-1 md:order-2 max-h-96 md:max-h-none",children:K.jsxs("div",{className:"p-3 sm:p-4 space-y-3 sm:space-y-4 relative",children:[K.jsxs("div",{className:"bg-white rounded-lg border border-gray-200 p-4 md:sticky top-0 z-50",children:[K.jsx("h3",{className:"text-sm font-semibold text-gray-700 mb-3",children:"Acciones"}),K.jsxs("div",{className:"space-y-2",children:[K.jsxs("button",{onClick:le,disabled:N||!U,className:"w-full min-h-10 transition-colors "+(i?"limbo-btn limbo-btn-danger":"limbo-btn limbo-btn-primary"),"aria-label":"Generar vista previa del recorte",children:[K.jsx("span",{className:"icon "+(i?"icon-close-small-white":"icon-search-white")}),i?"Cerrar previa":"Vista previa"]}),K.jsx("button",{onClick:se,disabled:N||!$||!W||!U||!j.isReady,className:"w-full limbo-btn limbo-btn-success min-h-10","aria-label":"Guardar imagen recortada",children:N?K.jsxs(K.Fragment,{children:[K.jsx("span",{className:"icon icon-save-white"})," ","Guardando..."]}):K.jsxs(K.Fragment,{children:[K.jsx("span",{className:"icon icon-save-white"})," Guardar recorte"]})}),K.jsxs("button",{onClick:ee,disabled:N,className:"w-full limbo-btn limbo-btn-secondary min-h-10","aria-label":"Reiniciar todas las configuraciones",children:[K.jsx("span",{className:"icon icon-refresh-white"})," Reiniciar todo"]})]})]}),K.jsxs("div",{className:"bg-gradient-to-br from-brand-blue-50 to-green-50 rounded-lg border border-blue-200 shadow-sm",children:[K.jsxs("button",{onClick:q,className:"w-full p-4 flex items-center justify-between cursor-pointer hover:bg-blue-100/50 transition-colors rounded-t-lg","aria-expanded":k,"aria-label":"Mostrar/ocultar guía de uso",children:[K.jsxs("h3",{className:"text-lg font-semibold text-blue-800 flex items-center",children:[K.jsx("span",{className:"icon icon-lightbulb text-yellow-500 mr-2"}),"Guía de uso"]}),K.jsx("span",{className:"icon icon-arrow-down-blue transition-transform duration-200 "+(k?"rotate-180":"")})]}),k&&K.jsxs("div",{className:"px-4 pb-4 space-y-3",children:[K.jsxs("div",{className:"bg-white/60 rounded-md p-3 border-l-4 border-blue-400",children:[K.jsx("h4",{className:"font-semibold text-blue-700 mb-2 text-sm",children:"🖱️ Navegación básica"}),K.jsxs("div",{className:"text-sm text-blue-600 space-y-1",children:[K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Arrastra la imagen:"})," Haz clic fuera del área de selección y arrastra"]}),K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Zoom:"})," Usa la rueda del ratón (fuera del área de selección)"]}),K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Vista completa:"}),' Botón "Reset zoom" para ajustar al tamaño óptimo']})]})]}),K.jsxs("div",{className:"bg-white/60 rounded-md p-3 border-l-4 border-green-400",children:[K.jsx("h4",{className:"font-semibold text-green-700 mb-2 text-sm",children:"✂️ Área de selección"}),K.jsxs("div",{className:"text-sm text-green-600 space-y-1",children:[K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Mover selección:"})," Arrastra desde el centro",K.jsx("span",{className:"icon bg-white icon-move align-[middle!important] mx-1 border border-green-600 rounded-full"})]}),K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Redimensionar:"})," Arrastra desde las esquinas o bordes"]}),K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Tamaños rápidos:"})," Usa los botones 50%, 70%, 90%, 100%"]}),K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Proporciones:"})," Selecciona ratios predefinidos (1:1, 16:9, etc.)"]})]})]}),K.jsxs("div",{className:"bg-white/60 rounded-md p-3 border-l-4 border-purple-400",children:[K.jsx("h4",{className:"font-semibold text-purple-700 mb-2 text-sm",children:"⌨️ Atajos de teclado"}),K.jsxs("div",{className:"text-sm text-purple-600 space-y-1",children:[K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Flechas:"}),K.jsx("span",{className:"icon icon-arrow-right-box rotate-180 mx-1"}),K.jsx("span",{className:"icon icon-arrow-right-box mx-1"}),K.jsx("span",{className:"icon icon-arrow-right-box -rotate-90 mx-1"}),K.jsx("span",{className:"icon icon-arrow-right-box rotate-90 mx-1"}),"Mueven la selección (10px)"]}),K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Shift + Arrastrar:"})," Mantiene proporciones al redimensionar"]}),K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Ctrl + Rueda:"})," Zoom más preciso"]})]})]}),K.jsxs("div",{className:"bg-white/60 rounded-md p-3 border-l-4 border-amber-400",children:[K.jsx("h4",{className:"font-semibold text-amber-700 mb-2 text-sm",children:"💡 Consejos profesionales"}),K.jsxs("div",{className:"text-sm text-amber-600 space-y-1",children:[K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Vista previa:"}),' Usa el botón "Vista previa" antes de guardar']}),K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Grid:"})," Actívalo para aplicar la regla de los tercios"]}),K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Transformaciones:"})," Rota y voltea antes de hacer el recorte final"]}),K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Calidad:"})," Las imágenes se exportan en alta calidad (JPEG 90%)"]})]})]}),K.jsxs("div",{className:"bg-white/60 rounded-md p-3 border-l-4 border-orange-600",children:[K.jsx("h4",{className:"font-semibold text-orange-700 mb-2 text-sm",children:"⚠️ Advertencias"}),K.jsxs("div",{className:"text-sm text-orange-600 space-y-1",children:[K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Recortes grandes:"})," Pueden tardar más en procesarse"]}),K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Calidad de imagen:"})," La calidad puede verse afectada al escalar"]})]})]})]})]}),K.jsxs("div",{className:"bg-white rounded-lg border border-gray-200 p-3 sm:p-4",children:[K.jsx("h3",{className:"text-sm font-semibold text-gray-700 mb-3",children:"Proporción"}),K.jsx("div",{className:"limbo-cropper-aspect-buttons grid grid-cols-2 md:grid-cols-1 gap-2 md:hidden",children:_.map(e=>K.jsx("button",{onClick:()=>oe(e.value),className:"p-2 text-xs rounded border transition-colors cursor-pointer "+(f===e.value?"bg-blue-100 border-blue-300 text-blue-800":"bg-gray-100 border-gray-300 text-gray-700"),disabled:N,title:`Cambiar a proporción ${e.label}`,children:e.label},e.value))}),K.jsx("select",{value:f,onChange:e=>oe(e.target.value),className:"w-full form-control hidden md:block",disabled:N,"aria-label":"Seleccionar proporción de aspecto",children:_.map(e=>K.jsx("option",{value:e.value,children:e.label},e.value))})]}),K.jsxs("div",{className:"bg-white rounded-lg border border-gray-200 p-4",children:[K.jsx("h3",{className:"text-sm font-semibold text-gray-700 mb-3",children:"Visualización"}),K.jsxs("div",{className:"space-y-2",children:[K.jsxs("button",{onClick:B,className:"w-full flex cursor-pointer items-center justify-between p-2 rounded transition-colors "+(m?"bg-blue-100 border border-blue-300 text-blue-800":"bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200"),disabled:N,"aria-pressed":m,"aria-label":"Activar/desactivar grid",children:[K.jsxs("span",{className:"text-sm flex items-center",children:[K.jsx("span",{className:"icon icon-area-blue me-1"})," Grid"]}),K.jsx("span",{className:"text-xs",children:m?K.jsxs(K.Fragment,{children:[K.jsx("span",{className:"icon icon-tick icon--xs align-[middle!important] -mt-0.5"})," ","Activo"]}):"Inactivo"})]}),K.jsxs("button",{onClick:V,className:"w-full flex cursor-pointer items-center justify-between p-2 rounded transition-colors "+(b?"bg-blue-100 border border-blue-300 text-blue-800":"bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200"),disabled:N,"aria-pressed":b,"aria-label":"Activar/desactivar sombreado",children:[K.jsxs("span",{className:"text-sm flex items-center",children:[K.jsx("span",{className:"icon icon-comparison-blue me-1"})," ","Sombreado"]}),K.jsx("span",{className:"text-xs",children:b?K.jsxs(K.Fragment,{children:[K.jsx("span",{className:"icon icon-tick icon--xs align-[middle!important] -mt-0.5"})," ","Activo"]}):"Inactivo"})]})]})]}),K.jsxs("div",{className:"bg-white rounded-lg border border-gray-200 p-4",children:[K.jsx("h3",{className:"text-sm font-semibold text-gray-700 mb-3",children:"Ajustes del selector"}),K.jsxs("div",{className:"space-y-2",children:[K.jsx("button",{onClick:Y,className:"w-full p-2 rounded cursor-pointer transition-colors text-sm bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Centrar selección",disabled:N,"aria-label":"Centrar área de selección",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsxs("span",{children:[K.jsx("span",{className:"icon icon-radio-button icon--sm align-[middle!important] "})," ","Centrar selección"]})})}),K.jsx("button",{onClick:G,className:"w-full p-2 rounded cursor-pointer transition-colors text-sm bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Reiniciar selección",disabled:N,"aria-label":"Reiniciar área de selección",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsxs("span",{children:[K.jsx("span",{className:"icon icon-refresh icon--sm lign-[middle!important] "})," ","Reset selección"]})})})]}),K.jsxs("div",{className:"mt-3",children:[K.jsx("p",{className:"text-xs text-gray-600 mb-2",children:"Tamaños rápidos"}),K.jsxs("div",{className:"grid grid-cols-2 gap-1",children:[K.jsx("button",{onClick:()=>te(.5),className:"p-2 rounded cursor-pointer transition-colors text-xs bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",disabled:N,"aria-label":"Selección 50%",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{children:"50%"})})}),K.jsx("button",{onClick:()=>te(.7),className:"p-2 rounded cursor-pointer transition-colors text-xs bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",disabled:N,"aria-label":"Selección 70%",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{children:"70%"})})}),K.jsx("button",{onClick:()=>te(.9),className:"p-2 rounded cursor-pointer transition-colors text-xs bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",disabled:N,"aria-label":"Selección 90%",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{children:"90%"})})}),K.jsx("button",{onClick:()=>te(1),className:"p-2 rounded cursor-pointer transition-colors text-xs bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",disabled:N,"aria-label":"Selección completa",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{children:"100%"})})})]})]})]}),K.jsxs("div",{className:"bg-white rounded-lg border border-gray-200 p-4",children:[K.jsx("h3",{className:"text-sm font-semibold text-gray-700 mb-3",children:"Transformar imagen"}),K.jsxs("div",{className:"mb-4",children:[K.jsx("p",{className:"text-xs text-gray-600 mb-2",children:"Mover imagen"}),K.jsxs("div",{className:"grid grid-cols-3 gap-1",children:[K.jsx("div",{}),K.jsx("button",{onClick:()=>X(0,-10),className:"p-2 rounded cursor-pointer transition-colors text-sm bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Mover arriba",disabled:N,"aria-label":"Mover imagen hacia arriba",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{className:"icon icon-arrow-up-blue"})})}),K.jsx("div",{}),K.jsx("button",{onClick:()=>X(-10,0),className:"p-2 rounded cursor-pointer transition-colors text-sm bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Mover izquierda",disabled:N,"aria-label":"Mover imagen hacia la izquierda",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{className:"icon icon-arrow-left-blue"})})}),K.jsx("button",{onClick:Q,className:"p-2 rounded cursor-pointer transition-colors text-xs bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Centrar y ajustar imagen",disabled:N,"aria-label":"Centrar y ajustar imagen",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{className:"icon icon-radio-button-blue icon-md"})})}),K.jsx("button",{onClick:()=>X(10,0),className:"p-2 rounded cursor-pointer transition-colors text-sm bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Mover derecha",disabled:N,"aria-label":"Mover imagen hacia la derecha",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{className:"icon icon-arrow-right-blue"})})}),K.jsx("div",{}),K.jsx("button",{onClick:()=>X(0,10),className:"p-2 rounded cursor-pointer transition-colors text-sm bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Mover abajo",disabled:N,"aria-label":"Mover imagen hacia abajo",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{className:"icon icon-arrow-down-blue"})})}),K.jsx("div",{})]})]}),K.jsxs("div",{className:"mb-4",children:[K.jsxs("p",{className:"text-xs text-gray-600 mb-2",children:["Zoom ",S?S.percentage+"%":""]}),K.jsxs("div",{className:"flex gap-1",children:[K.jsx("button",{onClick:()=>J(-.2),className:"flex-1 p-2 rounded cursor-pointer transition-colors text-sm bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Alejar 20%",disabled:N,"aria-label":"Alejar imagen",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{className:"icon icon-zoom-out-blue"})})}),K.jsx("button",{onClick:ne,className:"flex-1 p-2 rounded cursor-pointer transition-colors text-xs bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Restablecer zoom original",disabled:N,"aria-label":"Restablecer el zoom para que la imagen se vea con su resolución original",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{className:"icon icon-screenshot-blue"})})}),K.jsx("button",{onClick:()=>J(.2),className:"flex-1 p-2 rounded cursor-pointer transition-colors text-sm bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Acercar 20%",disabled:N,"aria-label":"Acercar imagen",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{className:"icon icon-zoom-in-blue"})})})]})]}),K.jsxs("div",{className:"mb-4",children:[K.jsx("p",{className:"text-xs text-gray-600 mb-2",children:"Rotación"}),K.jsxs("div",{className:"flex gap-1 *:text-brand-blue-1000 *:text-sm",children:[K.jsx("button",{onClick:()=>Z(-90),className:"flex-1 p-2 rounded cursor-pointer transition-colors text-sm bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Rotar -90°",disabled:N,"aria-label":"Rotar imagen 90 grados a la izquierda",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{className:"icon icon-reply-blue"})})}),K.jsx("button",{onClick:()=>Z(-45),className:"flex-1 p-2 rounded cursor-pointer transition-colors text-xs bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Rotar -45°",disabled:N,"aria-label":"Rotar imagen 45 grados a la izquierda",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{children:"-45°"})})}),K.jsx("button",{onClick:()=>Z(45),className:"flex-1 p-2 rounded cursor-pointer transition-colors text-xs bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Rotar +45°",disabled:N,"aria-label":"Rotar imagen 45 grados a la derecha",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{children:"+45°"})})}),K.jsx("button",{onClick:()=>Z(90),className:"flex-1 p-2 rounded cursor-pointer transition-colors text-sm bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Rotar +90°",disabled:N,"aria-label":"Rotar imagen 90 grados a la derecha",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{className:"icon icon-send-arrow-blue"})})})]})]}),K.jsxs("div",{className:"mb-4",children:[K.jsx("p",{className:"text-xs text-gray-600 mb-2",children:"Voltear"}),K.jsxs("div",{className:"flex gap-1",children:[K.jsx("button",{onClick:re,className:"flex-1 p-2 rounded cursor-pointer transition-colors text-sm "+(v.horizontal?"bg-blue-100 border border-blue-300 text-blue-800":"bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200"),title:"Voltear horizontalmente "+(v.horizontal?"(activo)":""),disabled:N,"aria-label":"Voltear imagen horizontalmente","aria-pressed":v.horizontal,children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{className:"icon icon-arrow-left-right-blue border border-brand-blue-1000 rounded"})})}),K.jsx("button",{onClick:ae,className:"flex-1 p-2 cursor-pointer rounded transition-colors text-sm "+(v.vertical?"bg-blue-100 border border-blue-300 text-blue-800":"bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200"),title:"Voltear verticalmente "+(v.vertical?"(activo)":""),disabled:N,"aria-label":"Voltear imagen verticalmente","aria-pressed":v.vertical,children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{className:"icon icon-arrow-up-down-blue border border-brand-blue-1000 rounded"})})})]})]}),K.jsx("button",{onClick:()=>{O.reset(),w({horizontal:!1,vertical:!1})},className:"w-full p-2 rounded cursor-pointer transition-colors text-sm bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Reiniciar transformaciones",disabled:N,"aria-label":"Reiniciar todas las transformaciones de la imagen",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsxs("span",{children:[K.jsx("span",{className:"icon icon-refresh-blue icon--sm align-[middle!important] "})," ","Reiniciar ajustes"]})})})]})]})})]})]}):null}function bn({currentPage:e,totalPages:t,onPageChange:n,disabled:r=!1}){if(!t||t<=1)return null;const a=(()=>{const n=[],r=[],a=Math.max(1,e-2),o=Math.min(t,e+2);for(let e=a;e<=o;e++)n.push(e);return a>1&&(r.push(1),a>2&&r.push("...")),r.push(...n),o<t&&(o<t-1&&r.push("..."),r.push(t)),r})();return K.jsxs("div",{className:"flex items-center justify-center space-x-2 py-4",children:[K.jsxs("button",{onClick:()=>{e>1&&n(e-1)},disabled:r||e<=1,className:`\n px-3 py-2 text-sm font-medium rounded-md transition-colors disabled:cursor-default cursor-pointer\n ${r||e<=1?"text-gray-400 bg-gray-100 cursor-not-allowed":"text-gray-700 bg-white border border-gray-300 hover:bg-gray-50 focus:ring-2 focus:ring-blue-500"}\n `,children:[K.jsx("span",{className:"icon icon-arrow-left-white icon--sm"})," Anterior"]}),K.jsx("div",{className:"flex space-x-1",children:a.map((t,a)=>K.jsx(h.Fragment,{children:"..."===t?K.jsx("span",{className:"px-3 py-2 text-sm text-gray-500",children:"..."}):K.jsx("button",{onClick:()=>(t=>{t!==e&&n(t)})(t),disabled:r,className:`\n px-3 py-2 text-sm font-medium rounded-md transition-colors disabled:cursor-default cursor-pointer\n ${t===e?"bg-blue-600 text-white border border-blue-600":r?"text-gray-400 bg-gray-100 cursor-not-allowed":"text-gray-700 bg-white border border-gray-300 hover:bg-gray-50 focus:ring-2 focus:ring-blue-500"}\n `,children:t})},`page-${t}-${a}`))}),K.jsxs("button",{onClick:()=>{e<t&&n(e+1)},disabled:r||e>=t,className:`\n px-3 py-2 text-sm font-medium rounded-md transition-colors disabled:cursor-default cursor-pointer\n ${r||e>=t?"text-gray-400 bg-gray-100 cursor-not-allowed":"text-gray-700 bg-white border border-gray-300 hover:bg-gray-50 focus:ring-2 focus:ring-blue-500"}\n `,children:["Siguiente ",K.jsx("span",{className:"icon icon-arrow-right-white icon--sm"})]}),K.jsxs("div",{className:"text-sm text-gray-500 ml-4",children:["Página ",e," de ",t]})]})}function yn({isOpen:e,onClose:t}){return e?K.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",style:{zIndex:9999},children:K.jsxs("div",{className:"bg-white rounded-lg p-6 max-w-md mx-4 shadow-xl",children:[K.jsxs("div",{className:"flex items-center mb-4",children:[K.jsx("svg",{className:"w-6 h-6 text-red-600 mr-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:K.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"})}),K.jsx("h3",{className:"text-lg font-semibold text-gray-900",children:"Sesión Expirada"})]}),K.jsxs("div",{className:"mb-6",children:[K.jsx("p",{className:"text-gray-600 mb-2",children:"Su sesión ha expirado por seguridad."}),K.jsx("p",{className:"text-gray-600",children:"Es necesario recargar la página para obtener un nuevo token de acceso."})]}),K.jsx("div",{className:"flex justify-end space-x-3",children:K.jsx("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 vn(){const[e,t]=p.useState(!1),[n,r]=p.useState(null);return{deleteImg:async e=>{if(!e)return r("ID de imagen no proporcionado"),!1;t(!0),r(null);try{const t=await async function(e){try{return await te({endpoint:`/assets/${e}`,method:"DELETE",basePath:ie,useJWT:!0})}catch(n){throw oe(n)}}(e);return!1!==t.success}catch(a){return r(a.message),!1}finally{t(!1)}},loading:e,error:n,reset:()=>{r(null)}}}const wn=new Map;function kn({apiKey:e,prod:t=!1,url:n=!0,features:r=["gallery","upload","cropper"],modeUI:a="full",ui:o={showActions:["select","download","copy","delete","crop","variants"],hideActions:[],theme:"light",language:"es",compactMode:!1,showTabs:!0},callbacks:i={},instanceId:l=null,itemsPerPage:s=10}){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 c=(()=>{switch(a){case"gallery-only":return["gallery"];case"upload-only":return["upload"];case"crop-only":return["cropper"];case"ia-only":return["ia"];default:return r}})(),[u,d]=p.useState(c.includes("gallery")?"gallery":c.includes("upload")?"upload":c.includes("cropper")?"cropper":c.includes("ia")?"ia":c[0]||"gallery"),[f,h]=p.useState(null),[m,g]=p.useState(1),{isTokenExpired:b,handleTokenExpiredClose:y}=function(){const[e,t]=p.useState(!1),n=p.useCallback(e=>{if(401===e?.response?.status){const n=e.response.data;if("token_expired"===n?.error||n?.message?.includes("expired")||n?.message?.includes("caducado")||n?.error?.includes("expired"))return t(!0),!0}return!1},[]),r=p.useCallback(()=>{t(!1),alert("El token ha expirado. La página se recargará para obtener un nuevo token."),window.location.reload()},[]);return p.useEffect(()=>{const e=e=>{e.detail&&e.detail.error&&n(e.detail.error)};return window.addEventListener("tokenExpiredError",e),()=>{window.removeEventListener("tokenExpiredError",e)}},[n]),{isTokenExpired:e,checkTokenExpiration:n,handleTokenExpiredClose:r}}(),{upload:v,loading:w,error:k,uploadedImage:x,reset:S}=function(){const[e,t]=p.useState(!1),[n,r]=p.useState(null),[a,o]=p.useState(null);return{upload:async(e,n=null)=>{if(!e)return r("No se ha proporcionado ningún archivo"),null;t(!0),r(null),o(null);try{const t=await se(e,n,!1),r=t.result||t;return o(r),r}catch(a){return r(a.message),null}finally{t(!1)}},loading:e,error:n,uploadedImage:a,reset:()=>{r(null),o(null)}}}(),{deleteImg:C,loading:E,error:_,reset:T}=vn(),{images:N,loading:P,error:R,pagination:z,invalidateCache:j,setImages:O}=function(e,t=!1,n={}){const[r,a]=p.useState([]),[o,i]=p.useState(!0),[l,s]=p.useState(null),[c,u]=p.useState(null),[d,f]=p.useState(0),h=p.useMemo(()=>JSON.stringify(n),[n]);return p.useEffect(()=>{const e=`${h}`,t=wn.get(e),r=Date.now();if(t&&r-t.timestamp<6e5)return a(t.data),u(t.pagination||null),void i(!1);let o=!0;return(async()=>{if(d>=3)o&&(s("Error de autenticación: Verifica tus credenciales API"),i(!1));else try{const t=await le(n);if(!o)return;const i=t.result||[],l=t.pagination||null;a(i),u(l),s(null),f(0),wn.set(e,{data:i,pagination:l,timestamp:r})}catch(t){o&&(s(t.message),f(e=>e+1))}finally{o&&i(!1)}})(),()=>{o=!1}},[e,t,h,d,n]),{images:r,loading:o,error:l,pagination:c,setImages:a,invalidateCache:()=>{wn.delete(`${h}`)}}}(e,t,{limit:s,page:m}),{refreshVariants:A}=ue(),L=e=>!o.hideActions?.includes(e)&&(!!o.showActions?.includes(e)||!(o.showActions?.length>0)),I=[{id:"gallery",label:"Galería",feature:"gallery"},{id:"upload",label:"Subir nueva",feature:"upload"},{id:"cropper",label:"Recortador",hideNonActive:!0,feature:"cropper"}].filter(e=>c.includes(e.feature)),M=async e=>{if(!confirm("¿Estás seguro de que quieres eliminar esta imagen?"))return;await C(e)&&(j(),g(1),O(t=>t.filter(t=>t.id!==e)),f&&f.id===e&&(h(null),d("gallery")))};return K.jsxs("div",{className:"limbo-card-parent max-w-7xl mx-auto my-8 p-6 shadow-xl w-full",children:[o.showTabs&&K.jsx(G,{tabs:I,active:u,onChange:e=>{d(e),"upload"!==e&&S(),"gallery"!==e&&T()}}),R&&K.jsxs("div",{className:"alert alert-danger",children:["Error al cargar imágenes: ",R]}),_&&K.jsxs("div",{className:"alert alert-danger",children:["Error al eliminar imagen: ",_]}),"gallery"===u&&K.jsxs(K.Fragment,{children:[E&&K.jsx(pe,{text:"Eliminando imagen..."}),K.jsx(me,{apiKey:e,prod:t,onSelect:e=>{i.onSelect&&i.onSelect({assetId:e.id,url:e.url,fileName:e.filename,mime:e.mime_type,width:e.width,height:e.height,instanceId:l})},onCrop:e=>{h(e),c.includes("cropper")&&d("cropper")},onDelete:L("delete")?M:null,deletingId:E,images:N,loading:P,error:R,allowedActions:{select:L("select"),download:L("download"),copy:L("copy"),delete:L("delete"),crop:L("crop")}}),z&&!P&&K.jsx(bn,{currentPage:z.page||m,totalPages:z.pages||1,onPageChange:e=>{g(e)},disabled:P||E})]}),"upload"===u&&K.jsxs("div",{children:[w&&K.jsx(pe,{text:"Subiendo imagen..."}),k&&K.jsxs("div",{className:"alert alert-danger",children:["Error al subir imagen: ",k]}),x&&K.jsxs("div",{className:"alert alert-success",children:["✅ Imagen subida correctamente: ",x.filename]}),K.jsx(Oe,{onUpload:async e=>{const t=await v(e);t&&(j(),g(1),O(e=>[t,...e]),d("gallery"),i.onUpload&&i.onUpload({assetId:t.id,url:t.url,fileName:t.filename,mime:t.mime_type,width:t.width,height:t.height,instanceId:l}))},disabled:w,apiKey:e,prod:t})]}),"cropper"===u&&K.jsx(gn,{image:f,onSave:()=>{j(),h(null),d("gallery")},onCancel:()=>{h(null),d("gallery")},onDelete:()=>M(f?.id),deleting:E,onVariantCreated:(e,t)=>{A(e)}}),K.jsx(yn,{isOpen:b,onClose:y})]})}class xn{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=F.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.modal.close(),this.eventManager.emit("modal:close",{instance:this})),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=F.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 h.createElement("div",{id:`limbo-component-container-${this.id}`,className:"limbo-instance limbo-component-container-wrapper py-3","data-limbo-id":this.id,"data-limbo-mode":this.config.mode},h.createElement(kn,{apiKey:this.config.apiKey,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}))}_createCallbacks(){return{onSelect:e=>{const t=this._createStandardPayload(e,"select");this.config.callbacks?.onSelect&&this.config.callbacks.onSelect(t),this._emitDOMEvent("select",t)},onUpload:e=>{const t=this._createStandardPayload(e,"upload");this.config.callbacks?.onUpload&&this.config.callbacks.onUpload(t),this._emitDOMEvent("upload",t)},onError:e=>{const t={instance:this,error:{message:e.message||"Unknown error",code:e.code||"UNKNOWN",timestamp:Date.now()}};this.config.callbacks?.onError&&this.config.callbacks.onError(t.error),this._emitDOMEvent("error",t)},onClose:()=>{const e={instance:this,timestamp:Date.now()};this.config.callbacks?.onClose&&this.config.callbacks.onClose(),this._emitDOMEvent("close",e)}}}_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){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.apiKey||this.config.publicKey))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 Sn{constructor(){this.instances=new Map,this.counter=0}create(e,t,n){const r="limbo-"+ ++this.counter,a=new xn(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 Cn{constructor(){this.config=null,this.instances=new Map,this.observer=null,this.initialized=!1}configure(e,t,n){return this.config={dataset:e.dataset||"data-limbo-input-file",return:e.return||"url",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||"medium",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=`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,o={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"},i={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=i[n]||i.primary;Object.assign(e.style,{...o,...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){switch((t||{}).return||this.config.return||"url"){case"url":return e.url||e.path||"";case"base64":return e.base64||e.dataUrl||"";case"assetId":return e.assetId||e.id||"";case"fileName":return e.fileName||e.filename||"";case"object":return 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,created:e.created_at||e.created});default:return 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})}}_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||"medium",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},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;if(!t||"none"===t||"false"===t)return null;if("free"===t)return{aspectRatio:null,quality:e.quality||this.config.quality,format:e.format||this.config.format};const n={"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(n[t])return{aspectRatio:n[t],quality:e.quality||this.config.quality,format:e.format||this.config.format,minCropBoxWidth:e.minWidth||this.config.minWidth,minCropBoxHeight:e.minHeight||this.config.minHeight};if("string"==typeof t&&t.includes(":")){const[n,r]=t.split(":").map(Number);if(!isNaN(n)&&!isNaN(r)&&0!==r)return{aspectRatio:n/r,quality:e.quality||this.config.quality,format:e.format||this.config.format}}const r=parseFloat(t);return!isNaN(r)&&r>0?{aspectRatio:r,quality:e.quality||this.config.quality,format:e.format||this.config.format}:"object"==typeof t?{quality:e.quality||this.config.quality,format:e.format||this.config.format,...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;return{return:e.getAttribute("data-limbo-return")||this.config.return,mode:e.getAttribute("data-limbo-mode")||this.config.mode,features:t(e.getAttribute("data-limbo-features"))||this.config.features,crop:e.getAttribute("data-limbo-crop")||this.config.crop,quality:a(e.getAttribute("data-limbo-quality"))||this.config.quality,format:e.getAttribute("data-limbo-format")||this.config.format,modeUI:e.getAttribute("data-limbo-mode-ui")||this.config.modeUI,modalSize:e.getAttribute("data-limbo-modal-size")||this.config.modalSize,theme:e.getAttribute("data-limbo-theme")||this.config.theme,compact: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}}_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=`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 En{constructor(){this.listeners=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 _n{constructor(){this.activeModals=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 Tn(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 Tn{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: 400px;",medium:e?"width: 100%; height: 100%;":"max-width: 600px;",large:e?"width: 100%; height: 100%;":"max-width: 800px;",xlarge:e?"width: 100%; height: 100%;":"max-width: 1200px;"},n=e?`\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n transform: translateY(100%);\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: 1;\n transition: transform 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=n,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);return requestAnimationFrame(()=>{this.backdrop&&(this.backdrop.style.opacity="1"),this.element.style.opacity="1",this.element.style.transform=e?"translateY(0%)":"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);return this.backdrop&&(this.backdrop.style.opacity="0"),this.element.style.opacity="0",this.element.style.transform=e?"translateY(100%)":"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 Nn{constructor(){this.currentTheme=null,this.customThemes=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=new Map,this.appliedStyles=new Set,this.changeCallbacks=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,o=(n>>8&255)-r,i=(255&n)-r;return"#"+(16777216+65536*(a<255?a<1?0:a:255)+256*(o<255?o<1?0:o:255)+(i<255?i<1?0:i:255)).toString(16).slice(1)}_lightenColor(e,t){const n=parseInt(e.replace("#",""),16),r=Math.round(2.55*t),a=(n>>16)+r,o=(n>>8&255)+r,i=(255&n)+r;return"#"+(16777216+65536*(a<255?a<1?0:a:255)+256*(o<255?o<1?0:o:255)+(i<255?i<1?0:i: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 Pn=new class{constructor(){this.config=new n,this.instances=new Sn,this.autoInputs=new Cn,this.events=new En,this.modals=new _n,this.theme=new Nn,this.containerQueryDetector=Q,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,prod:e.prod||!1},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,o=0;return r.forEach(e=>{try{this.autoInputs._processInput(e),a++}catch(t){console.warn(`⚠️ Limbo: Error procesando input ${e.id||e.name}:`,t),o++}}),this.events.emit("limbo:scanCompleted",{found:r.length,processed:a,skipped:o,inputs:Array.from(r)}),{found:r.length,processed:a,skipped:o}}_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=this.create({...e,mode:"modal",autoDestroy:!0,callbacks:{onSelect:e=>{t(e),n.close()},onClose:()=>{}}});n.open()}};"undefined"!=typeof window&&(window.Limbo=Pn);return"undefined"!=typeof window&&document.querySelector("#root")&&(Pn.configure({prod:!1,publicKey:"pk_9fcfdd91a14755cc68d0e11a14269554",authMode:"session"}),Pn.create({container:"#root",mode:"embed",modeUI:"full",features:["gallery","upload","cropper"],title:"Limbo Image Manager - Development",url:!0}),Pn.configureAutoInputs({dataset:"data-limbo-input-file",return:"url",features:["gallery","upload","cropper"],modeUI:"full",modalSize:"large",title:"Seleccionar imagen",crops:"free",allowDelete:!1})),Pn});
57
+ Gt.$define(),ln.$define(),on.$define(),nn.$define(),Zt.$define(),an.$define(),tn.$define(),pn.$define();class mn{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,o)=>{if(!this.image)return!1;try{return this.image.$setTransform(e,t,n,r,a,o),!0}catch(i){return console.warn("Error setting transform:",i),!1}},resetZoom:()=>{if(!this.image)return!1;try{const e=this.image.$getTransform();if(!e)return!1;const[t,n,r,a,o,i]=e,l=Math.sqrt(t*t+n*n),s=Math.sqrt(r*r+a*a),c=t/l,u=n/l,d=r/s,f=a/s;return this.image.$setTransform(c,u,d,f,o,i),!0}catch(e){return console.warn("Error resetting zoom:",e),!1}},setZoom:e=>{if(!this.image||e<=0)return!1;try{const t=this.image.$getTransform();if(!t)return!1;const[n,r,a,o,i,l]=t,s=Math.sqrt(n*n+r*r),c=Math.sqrt(a*a+o*o),u=n/s*e,d=r/s*e,f=a/c*e,p=o/c*e;return this.image.$setTransform(u,d,f,p,i,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,o=t.height*r/n.naturalHeight,i=Math.min(a,o,1);return this.transform.setZoom(i)}catch(t){return console.warn("Error fitting to canvas:",t),!1}}};selection={center:()=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$center(),!0}catch(e){return console.warn("Error centering selection:",e),!1}},reset:()=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$reset(),!0}catch(e){return console.warn("Error resetting selection:",e),!1}},setCoverage:e=>{if(!this.selectionElement||e<0||e>1)return!1;try{return this.selectionElement.initialCoverage=e,this.selectionElement.$reset(),!0}catch(t){return console.warn("Error setting coverage:",t),!1}},setAspectRatio:e=>{if(!this.selectionElement)return!1;try{let t;if(""===e||null==e)t=NaN;else if("number"==typeof e)t=e;else{if("string"!=typeof e)return console.warn("Unsupported aspect ratio type:",typeof e,e),!1;if(e.includes("/")){const[n,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(o){return console.warn("Error changing selection:",o),!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,o,i]=e;return this.transform.setTransform(-t,n,r,a,o,i)},flipVertical:()=>{const e=this.transform.getTransform();if(!e)return!1;const[t,n,r,a,o,i]=e;return this.transform.setTransform(t,n,r,-a,o,i)},setupInitialView:async(e={})=>{const{paspartuFactor:t=.85,retries:n=3,retryDelay:r=200}=e;return new Promise(e=>{const a=(o=0)=>{if(!this.isReady)return o<n?void setTimeout(()=>a(o+1),r):void e(!1);try{const i=this.canvasElement.getBoundingClientRect();let l=this.image.querySelector("img")||this.image;if(!l?.naturalWidth||!l?.naturalHeight)return o<n?void setTimeout(()=>a(o+1),r):(this.transform.center(),void e(!1));if(i.width>0&&i.height>0){const n=i.width*t/l.naturalWidth,r=i.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(i){console.warn("Error in setup:",i),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:o,onActionEnd:i}=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(o){const e=e=>o(e.detail);this.canvasElement.addEventListener("actionmove",e),l.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionmove",e)})}if(i){const e=e=>i(e.detail);this.canvasElement.addEventListener("actionend",e),l.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionend",e)})}}return()=>{l.forEach(e=>e())}}}function gn({image:e,onSave:t,onCancel:n,onDelete:r,deleting:a=!1,onVariantCreated:o=null}){const[i,l]=p.useState(!1),[s,c]=p.useState(null),[u,d]=p.useState(!1),[f,h]=p.useState(""),[m,g]=p.useState(!0),[b,y]=p.useState(!0),[v,w]=p.useState({horizontal:!1,vertical:!1}),[k,x]=p.useState(!1),[S,C]=p.useState({current:1,percentage:100}),E=window.limboCore?.accessibilityManager,_=p.useMemo(()=>{const e=window.limboCore?.config?.getGlobal()||{};return e.cropper?.allowedAspectRatios||[{label:"📐 Libre",value:"",ratio:null},{label:"⬜ 1:1 (Cuadrado)",value:"1",ratio:1},{label:"📺 4:3 (Clásico)",value:"4/3",ratio:4/3},{label:"🖥️ 16:9 (Widescreen)",value:"16/9",ratio:16/9},{label:"📷 3:2 (Foto)",value:"3/2",ratio:1.5},{label:"📱 2:3 (Retrato)",value:"2/3",ratio:2/3},{label:"📲 9:16 (Stories)",value:"9/16",ratio:9/16}]},[]),{createCropVariant:T,loading:N,error:P}=hn(),R=((e,t={})=>{const n=p.useRef(null),r=p.useRef(null),a=p.useRef(null),o=p.useRef(null),[i,l]=p.useState(null),[s,c]=p.useState(null),[u,d]=p.useState(!1),[f,h]=p.useState(!0),[m,g]=p.useState(0),b={aspectRatio:"",shade:!0,paspartuFactor:.85,...t};p.useEffect(()=>{n.current&&r.current&&a.current&&(o.current=new mn(n,r,a),d(!0))},[]),p.useEffect(()=>{if(o.current)return o.current.setupEventListeners({onSelectionChange:e=>{l(e)},onImageTransform:()=>{g(e=>e+1)}})},[u]),p.useEffect(()=>{o.current&&e&&(async()=>{o.current.selection.setAspectRatio(b.aspectRatio),o.current.canvas.setBackground(b.shade),await o.current.utils.setupInitialView({paspartuFactor:b.paspartuFactor});const e=await o.current.utils.checkExportability();h(e);const t=r.current?.querySelector("img")||r.current;t?.naturalWidth&&t?.naturalHeight&&c({naturalWidth:t.naturalWidth,naturalHeight:t.naturalHeight,currentWidth:t.width,currentHeight:t.height})})()},[e,b.aspectRatio,b.shade,b.paspartuFactor]);const y=p.useCallback(()=>({move:(e,t)=>o.current?.transform.move(e,t)||!1,zoom:e=>o.current?.transform.zoom(e)||!1,rotate:e=>o.current?.transform.rotate(e)||!1,center:()=>o.current?.transform.center()||!1,reset:()=>o.current?.transform.reset()||!1,resetZoom:()=>o.current?.transform.resetZoom()||!1,setZoom:e=>o.current?.transform.setZoom(e)||!1,getZoom:()=>o.current?.transform.getZoom()||1,fitToCanvas:e=>o.current?.transform.fitToCanvas(e)||!1,flipHorizontal:()=>o.current?.utils.flipHorizontal()||!1,flipVertical:()=>o.current?.utils.flipVertical()||!1}),[]),v=p.useCallback(()=>({center:()=>o.current?.selection.center()||!1,reset:()=>o.current?.selection.reset()||!1,setCoverage:e=>o.current?.selection.setCoverage(e)||!1,setAspectRatio:e=>o.current?.selection.setAspectRatio(e)||!1,toCanvas:e=>o.current?.selection.toCanvas(e)||Promise.resolve(null)}),[]),w=p.useCallback(()=>({resetAll:()=>{if(o.current){const e=o.current.utils.resetAll();return l(null),e}return!1},setBackground:e=>o.current?.canvas.setBackground(e)||!1,resetZoomOnly:()=>o.current?.utils.resetZoomOnly()||!1,getZoomInfo:()=>o.current?.utils.getZoomInfo()||{current:1,percentage:100,isZoomedIn:!1,isZoomedOut:!1}}),[]);return{refs:{canvasRef:n,imageRef:r,selectionRef:a},state:{cropData:i,imageInfo:s,isReady:u,canExport:f,transformVersion:m},transform:y(),selection:v(),utils:w(),manager:o.current}})(e,{aspectRatio:f,showGrid:m,shade:b,initialCoverage:.5,paspartuFactor:.85}),{refs:z,state:j,transform:O,selection:A,utils:L}=R,{canvasRef:I,imageRef:M,selectionRef:D}=z,{cropData:$,imageInfo:F,canExport:U,transformVersion:H}=j,W=p.useMemo(()=>F||{naturalWidth:e.width||1920,naturalHeight:e.height||1080,currentWidth:e.width||1920,currentHeight:e.height||1080},[F,e.width,e.height]),B=p.useCallback(()=>g(e=>!e),[]),V=p.useCallback(()=>y(e=>!e),[]),q=p.useCallback(()=>x(e=>!e),[]),Q=p.useCallback(()=>O.center(),[O]),Y=p.useCallback(()=>A.center(),[A]),G=p.useCallback(()=>A.reset(),[A]),X=p.useCallback((e,t)=>O.move(e,t),[O]),J=p.useCallback(e=>O.zoom(e),[O]),Z=p.useCallback(e=>O.rotate(e),[O]),ee=p.useCallback(()=>{L.resetAll(),h(""),g(!0),y(!0),w({horizontal:!1,vertical:!1}),l(!1),c(null)},[L]),te=p.useCallback(e=>{A.setCoverage(e)},[A]),ne=p.useCallback(()=>L.resetZoomOnly(),[L]),re=p.useCallback(()=>{w(e=>{const t=!e.horizontal;return O.flipHorizontal(),{...e,horizontal:t}})},[O]),ae=p.useCallback(()=>{w(e=>{const t=!e.vertical;return O.flipVertical(),{...e,vertical:t}})},[O]),oe=p.useCallback(e=>{h(e);const t=_.find(t=>t.value===e),n=t?t.ratio:e;A.setAspectRatio(n)},[A,_]),ie=p.useCallback(async()=>{if(!U)return null;try{const e=await A.toCanvas({width:800,height:600,imageSmoothingEnabled:!0,imageSmoothingQuality:"high"});return e?e.toDataURL("image/jpeg",.9):null}catch(e){return console.warn("Error generating preview:",e),null}},[U,A]),le=p.useCallback(async()=>{if(i)return l(!1),c(null),void d(!1);if(U){l(!0),d(!0);try{const e=await ie();e?c(e):(l(!1),alert("No se puede exportar el recorte por restricciones de CORS en la imagen original."))}finally{d(!1)}}else alert("No se puede exportar el recorte por restricciones de CORS en la imagen original.")},[U,ie,i]),se=p.useCallback(async()=>{if(!U){const e="No se puede exportar el recorte por restricciones de CORS en la imagen original.";return E?.announceError(e),void alert(e)}if(!j.isReady){const e="El cropper aún no está inicializado. Espera un momento e inténtalo de nuevo.";return E?.announceError(e),void alert(e)}E?.announce("Creando variante recortada de la imagen");try{if(!$||!W)throw console.error("❌ Datos faltantes:",{cropData:$,effectiveImageInfo:W}),new Error(`No hay datos de recorte disponibles. CropData: ${!!$}, ImageInfo: ${!!W}`);if(!$.x&&0!==$.x||!$.y&&0!==$.y||!$.width||!$.height)throw console.error("❌ CropData inválido:",$),new Error("Los datos de recorte no tienen las propiedades esperadas");if(!W.naturalWidth||!W.naturalHeight)throw console.error("❌ ImageInfo inválido:",W),new Error("Los datos de imagen no tienen las dimensiones esperadas");const{x:n,y:r,width:a,height:i}=$,{naturalWidth:l,naturalHeight:s}=W,c={x:n/l,y:r/s,width:a/l,height:i/s},u=a/i;let d,f;const p=1200;u>1?(d=Math.min(a,p),f=Math.round(d/u)):(f=Math.min(i,p),d=Math.round(f*u));const h=Date.now(),[m]=e.filename.split("."),g=`${m}_crop_${h}`,b=await T(e.id,c,{name:g,width:d,height:f,format:"webp",quality:90});b&&(E?.announceSuccess(`Variante recortada creada: ${g}`),o?.(e.id,b),t(b))}catch(n){console.warn("Error creating crop variant:",n);const e="No se pudo crear la variante recortada. Inténtalo de nuevo.";E?.announceError(e),alert(e)}},[U,$,F,W,e.filename,e.id,T,t,o,E,j.isReady]);return p.useEffect(()=>{l(!1),c(null)},[e]),p.useEffect(()=>{R.manager&&(A.setAspectRatio(f),L.setBackground(b))},[f,b,R.manager,A,L]),p.useEffect(()=>{if(R.manager&&R.manager.utils)try{const e=R.manager.transform.getZoom(),t={current:e,isZoomedIn:e>1,isZoomedOut:e<1,percentage:Math.round(100*e)};C(t)}catch(e){console.warn("Error updating zoom info:",e)}},[H,R.manager]),p.useEffect(()=>{if(!i||!U)return;const e=setTimeout(async()=>{d(e=>!s&&!e||e);try{const e=await ie();e&&c(e)}finally{d(!1)}},300);return()=>{clearTimeout(e),d(!1)}},[$,H,i,U,ie,f,v,s]),p.useEffect(()=>{const e=I.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)}},[I]),e?K.jsxs("div",{className:"limbo-cropper-view px-2 border-2 border-gray-200/50 rounded-lg min-w-fit max-w-7xl mx-auto h-screen flex flex-col",children:[K.jsxs("div",{className:"limbo-cropper-header flex flex-col sm:flex-row justify-between items-start sm:items-center p-4 sm:p-6 pb-4 border-b border-gray-200 bg-white z-10 flex-shrink-0 gap-4 sm:gap-2",children:[K.jsxs("div",{className:"flex-1 min-w-0",children:[K.jsx("h2",{className:"text-lg sm:text-xl font-bold text-gray-800 truncate",children:"Recortar imagen"}),K.jsx("p",{className:"text-sm text-gray-600 mt-1 truncate",children:e.filename})]}),K.jsxs("div",{className:"flex gap-2 w-full sm:w-auto",children:[K.jsx("button",{onClick:n,disabled:N,className:"limbo-btn limbo-btn-secondary px-4 py-2 flex-1 sm:flex-initial",children:"Cancelar"}),K.jsx("button",{onClick:()=>r?.(e),disabled:a|N,className:"limbo-btn limbo-btn-danger px-4 py-2 flex-1 sm:flex-initial","aria-label":`Eliminar imagen ${e.filename}`,children:a?"Eliminando...":"Eliminar"})]})]}),K.jsxs("div",{className:"limbo-cropper-status bg-white border-gray-100 px-4 sm:px-6 py-2 pb-0 flex-shrink-0",children:[P&&K.jsxs("div",{className:"alert alert-danger mb-2 text-sm",role:"alert",children:[K.jsx("strong",{children:"Error:"})," ",P]}),$&&$.width>0&&K.jsxs("div",{className:"alert alert-info mb-2 text-sm",role:"status",children:[K.jsx("strong",{children:"Área:"})," ",Math.round($.width)," ×"," ",Math.round($.height)," px"]}),F&&K.jsxs("div",{className:"alert alert-secondary mb-2 text-sm",role:"status",children:[K.jsx("strong",{children:"Original:"})," ",F.naturalWidth," ×"," ",F.naturalHeight," px",F.currentWidth!==F.naturalWidth&&K.jsxs("span",{className:"ml-2 sm:ml-3 text-xs block sm:inline",children:["(Mostrada: ",Math.round(F.currentWidth)," ×"," ",Math.round(F.currentHeight)," px)"]})]}),!U&&K.jsx("div",{className:"alert alert-warning mb-2 text-sm",role:"alert",children:"⚠️ No se puede exportar por restricciones CORS"})]}),K.jsxs("div",{className:"flex flex-col md:flex-row flex-1 overflow-hidden rounded-lg gap-4 md:gap-0 cropper-main-content-area",children:[K.jsx("div",{className:"flex-1 relative min-w-0 order-2 md:order-1",children:K.jsxs("div",{className:"limbo-cropper-container absolute inset-2 sm:inset-4 bg-white rounded-lg border-2 border-gray-200 shadow-lg overflow-hidden",children:[i&&K.jsxs("div",{className:"absolute top-2 sm:top-4 right-2 sm:right-4 bg-white rounded-lg border border-gray-300 p-2 sm:p-3 z-50 shadow-xl w-48 sm:w-64 max-w-[calc(50%-1rem)] sm:max-w-[calc(50%-2rem)] md:min-w-1/4",children:[K.jsxs("div",{className:"flex justify-between items-center mb-2",children:[K.jsx("h3",{className:"text-xs font-semibold text-gray-700",children:"Vista previa"}),K.jsx("button",{onClick:()=>{l(!1),c(null)},className:"text-gray-400 hover:text-gray-600 p-1 -m-1","aria-label":"Cerrar vista previa",children:K.jsx("span",{className:"icon icon-close-small text-xs"})})]}),K.jsx("div",{className:"bg-gray-50 rounded p-2 flex justify-center items-center min-h-[80px] relative",children:s?K.jsxs("div",{className:"relative w-full h-full flex justify-center items-center",children:[K.jsx("img",{src:s,alt:"Vista previa del recorte",className:"max-w-full max-h-80 object-contain rounded shadow-sm"}),u&&K.jsx("div",{className:"absolute top-1 right-1 bg-blue-500 rounded-full p-1",children:K.jsx("div",{className:"animate-spin w-3 h-3 border border-white border-t-transparent rounded-full"})})]}):K.jsxs("div",{className:"flex flex-col items-center justify-center",children:[K.jsx("div",{className:"animate-spin w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full mb-2"}),K.jsx("span",{className:"text-xs text-gray-500",children:"Generando..."})]})})]}),K.jsxs("cropper-canvas",{ref:I,style:{width:"100%",height:"100%",display:"block"},background:!!b||void 0,id:"limbo-cropperjs-canvas",tabindex:"-1",onKeyDown:e=>{"Delete"!==e.key&&"Backspace"!==e.key||(e.preventDefault(),e.stopPropagation())},children:[K.jsx("cropper-image",{ref:M,src:e.url||e.path,alt:e.filename,id:"limbo-cropperjs-image",action:"move",crossOrigin:"anonymous",rotatable:!0,scalable:!0,skewable:!0,translatable:!0}),K.jsxs("cropper-selection",{ref:D,"initial-coverage":"0.5",movable:!0,resizable:!0,keyboard:"false",action:"move",style:{cursor:"move"},"data-prevent-delete":"true",tabindex:"-1",children:[m&&K.jsx("cropper-grid",{role:"grid",action:"move",covered:!0,bordered:!0}),K.jsx("cropper-handle",{action:"move",style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:"32px",height:"32px",zIndex:"10"}}),K.jsx("cropper-handle",{action:"n-resize"}),K.jsx("cropper-handle",{action:"e-resize"}),K.jsx("cropper-handle",{action:"s-resize"}),K.jsx("cropper-handle",{action:"w-resize"}),K.jsx("cropper-handle",{action:"ne-resize"}),K.jsx("cropper-handle",{action:"nw-resize"}),K.jsx("cropper-handle",{action:"se-resize"}),K.jsx("cropper-handle",{action:"sw-resize"})]})]})]})}),K.jsx("div",{className:"limbo-cropper-controls w-full md:w-80 bg-white border-t md:border-t-0 md:border-l border-gray-200 overflow-y-auto flex-shrink-0 order-1 md:order-2 max-h-96 md:max-h-none",children:K.jsxs("div",{className:"p-3 sm:p-4 space-y-3 sm:space-y-4 relative",children:[K.jsxs("div",{className:"bg-white rounded-lg border border-gray-200 p-4 md:sticky top-0 z-50",children:[K.jsx("h3",{className:"text-sm font-semibold text-gray-700 mb-3",children:"Acciones"}),K.jsxs("div",{className:"space-y-2",children:[K.jsxs("button",{onClick:le,disabled:N||!U,className:"w-full min-h-10 transition-colors "+(i?"limbo-btn limbo-btn-danger":"limbo-btn limbo-btn-primary"),"aria-label":"Generar vista previa del recorte",children:[K.jsx("span",{className:"icon "+(i?"icon-close-small-white":"icon-search-white")}),i?"Cerrar previa":"Vista previa"]}),K.jsx("button",{onClick:se,disabled:N||!$||!W||!U||!j.isReady,className:"w-full limbo-btn limbo-btn-success min-h-10","aria-label":"Guardar imagen recortada",children:N?K.jsxs(K.Fragment,{children:[K.jsx("span",{className:"icon icon-save-white"})," ","Guardando..."]}):K.jsxs(K.Fragment,{children:[K.jsx("span",{className:"icon icon-save-white"})," Guardar recorte"]})}),K.jsxs("button",{onClick:ee,disabled:N,className:"w-full limbo-btn limbo-btn-secondary min-h-10","aria-label":"Reiniciar todas las configuraciones",children:[K.jsx("span",{className:"icon icon-refresh-white"})," Reiniciar todo"]})]})]}),K.jsxs("div",{className:"bg-gradient-to-br from-brand-blue-50 to-green-50 rounded-lg border border-blue-200 shadow-sm",children:[K.jsxs("button",{onClick:q,className:"w-full p-4 flex items-center justify-between cursor-pointer hover:bg-blue-100/50 transition-colors rounded-t-lg","aria-expanded":k,"aria-label":"Mostrar/ocultar guía de uso",children:[K.jsxs("h3",{className:"text-lg font-semibold text-blue-800 flex items-center",children:[K.jsx("span",{className:"icon icon-lightbulb text-yellow-500 mr-2"}),"Guía de uso"]}),K.jsx("span",{className:"icon icon-arrow-down-blue transition-transform duration-200 "+(k?"rotate-180":"")})]}),k&&K.jsxs("div",{className:"px-4 pb-4 space-y-3",children:[K.jsxs("div",{className:"bg-white/60 rounded-md p-3 border-l-4 border-blue-400",children:[K.jsx("h4",{className:"font-semibold text-blue-700 mb-2 text-sm",children:"🖱️ Navegación básica"}),K.jsxs("div",{className:"text-sm text-blue-600 space-y-1",children:[K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Arrastra la imagen:"})," Haz clic fuera del área de selección y arrastra"]}),K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Zoom:"})," Usa la rueda del ratón (fuera del área de selección)"]}),K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Vista completa:"}),' Botón "Reset zoom" para ajustar al tamaño óptimo']})]})]}),K.jsxs("div",{className:"bg-white/60 rounded-md p-3 border-l-4 border-green-400",children:[K.jsx("h4",{className:"font-semibold text-green-700 mb-2 text-sm",children:"✂️ Área de selección"}),K.jsxs("div",{className:"text-sm text-green-600 space-y-1",children:[K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Mover selección:"})," Arrastra desde el centro",K.jsx("span",{className:"icon bg-white icon-move align-[middle!important] mx-1 border border-green-600 rounded-full"})]}),K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Redimensionar:"})," Arrastra desde las esquinas o bordes"]}),K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Tamaños rápidos:"})," Usa los botones 50%, 70%, 90%, 100%"]}),K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Proporciones:"})," Selecciona ratios predefinidos (1:1, 16:9, etc.)"]})]})]}),K.jsxs("div",{className:"bg-white/60 rounded-md p-3 border-l-4 border-purple-400",children:[K.jsx("h4",{className:"font-semibold text-purple-700 mb-2 text-sm",children:"⌨️ Atajos de teclado"}),K.jsxs("div",{className:"text-sm text-purple-600 space-y-1",children:[K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Flechas:"}),K.jsx("span",{className:"icon icon-arrow-right-box rotate-180 mx-1"}),K.jsx("span",{className:"icon icon-arrow-right-box mx-1"}),K.jsx("span",{className:"icon icon-arrow-right-box -rotate-90 mx-1"}),K.jsx("span",{className:"icon icon-arrow-right-box rotate-90 mx-1"}),"Mueven la selección (10px)"]}),K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Shift + Arrastrar:"})," Mantiene proporciones al redimensionar"]}),K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Ctrl + Rueda:"})," Zoom más preciso"]})]})]}),K.jsxs("div",{className:"bg-white/60 rounded-md p-3 border-l-4 border-amber-400",children:[K.jsx("h4",{className:"font-semibold text-amber-700 mb-2 text-sm",children:"💡 Consejos profesionales"}),K.jsxs("div",{className:"text-sm text-amber-600 space-y-1",children:[K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Vista previa:"}),' Usa el botón "Vista previa" antes de guardar']}),K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Grid:"})," Actívalo para aplicar la regla de los tercios"]}),K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Transformaciones:"})," Rota y voltea antes de hacer el recorte final"]}),K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Calidad:"})," Las imágenes se exportan en alta calidad (JPEG 90%)"]})]})]}),K.jsxs("div",{className:"bg-white/60 rounded-md p-3 border-l-4 border-orange-600",children:[K.jsx("h4",{className:"font-semibold text-orange-700 mb-2 text-sm",children:"⚠️ Advertencias"}),K.jsxs("div",{className:"text-sm text-orange-600 space-y-1",children:[K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Recortes grandes:"})," Pueden tardar más en procesarse"]}),K.jsxs("div",{children:["• ",K.jsx("strong",{children:"Calidad de imagen:"})," La calidad puede verse afectada al escalar"]})]})]})]})]}),K.jsxs("div",{className:"bg-white rounded-lg border border-gray-200 p-3 sm:p-4",children:[K.jsx("h3",{className:"text-sm font-semibold text-gray-700 mb-3",children:"Proporción"}),K.jsx("div",{className:"limbo-cropper-aspect-buttons grid grid-cols-2 md:grid-cols-1 gap-2 md:hidden",children:_.map(e=>K.jsx("button",{onClick:()=>oe(e.value),className:"p-2 text-xs rounded border transition-colors cursor-pointer "+(f===e.value?"bg-blue-100 border-blue-300 text-blue-800":"bg-gray-100 border-gray-300 text-gray-700"),disabled:N,title:`Cambiar a proporción ${e.label}`,children:e.label},e.value))}),K.jsx("select",{value:f,onChange:e=>oe(e.target.value),className:"w-full form-control hidden md:block",disabled:N,"aria-label":"Seleccionar proporción de aspecto",children:_.map(e=>K.jsx("option",{value:e.value,children:e.label},e.value))})]}),K.jsxs("div",{className:"bg-white rounded-lg border border-gray-200 p-4",children:[K.jsx("h3",{className:"text-sm font-semibold text-gray-700 mb-3",children:"Visualización"}),K.jsxs("div",{className:"space-y-2",children:[K.jsxs("button",{onClick:B,className:"w-full flex cursor-pointer items-center justify-between p-2 rounded transition-colors "+(m?"bg-blue-100 border border-blue-300 text-blue-800":"bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200"),disabled:N,"aria-pressed":m,"aria-label":"Activar/desactivar grid",children:[K.jsxs("span",{className:"text-sm flex items-center",children:[K.jsx("span",{className:"icon icon-area-blue me-1"})," Grid"]}),K.jsx("span",{className:"text-xs",children:m?K.jsxs(K.Fragment,{children:[K.jsx("span",{className:"icon icon-tick icon--xs align-[middle!important] -mt-0.5"})," ","Activo"]}):"Inactivo"})]}),K.jsxs("button",{onClick:V,className:"w-full flex cursor-pointer items-center justify-between p-2 rounded transition-colors "+(b?"bg-blue-100 border border-blue-300 text-blue-800":"bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200"),disabled:N,"aria-pressed":b,"aria-label":"Activar/desactivar sombreado",children:[K.jsxs("span",{className:"text-sm flex items-center",children:[K.jsx("span",{className:"icon icon-comparison-blue me-1"})," ","Sombreado"]}),K.jsx("span",{className:"text-xs",children:b?K.jsxs(K.Fragment,{children:[K.jsx("span",{className:"icon icon-tick icon--xs align-[middle!important] -mt-0.5"})," ","Activo"]}):"Inactivo"})]})]})]}),K.jsxs("div",{className:"bg-white rounded-lg border border-gray-200 p-4",children:[K.jsx("h3",{className:"text-sm font-semibold text-gray-700 mb-3",children:"Ajustes del selector"}),K.jsxs("div",{className:"space-y-2",children:[K.jsx("button",{onClick:Y,className:"w-full p-2 rounded cursor-pointer transition-colors text-sm bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Centrar selección",disabled:N,"aria-label":"Centrar área de selección",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsxs("span",{children:[K.jsx("span",{className:"icon icon-radio-button icon--sm align-[middle!important] "})," ","Centrar selección"]})})}),K.jsx("button",{onClick:G,className:"w-full p-2 rounded cursor-pointer transition-colors text-sm bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Reiniciar selección",disabled:N,"aria-label":"Reiniciar área de selección",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsxs("span",{children:[K.jsx("span",{className:"icon icon-refresh icon--sm lign-[middle!important] "})," ","Reset selección"]})})})]}),K.jsxs("div",{className:"mt-3",children:[K.jsx("p",{className:"text-xs text-gray-600 mb-2",children:"Tamaños rápidos"}),K.jsxs("div",{className:"grid grid-cols-2 gap-1",children:[K.jsx("button",{onClick:()=>te(.5),className:"p-2 rounded cursor-pointer transition-colors text-xs bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",disabled:N,"aria-label":"Selección 50%",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{children:"50%"})})}),K.jsx("button",{onClick:()=>te(.7),className:"p-2 rounded cursor-pointer transition-colors text-xs bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",disabled:N,"aria-label":"Selección 70%",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{children:"70%"})})}),K.jsx("button",{onClick:()=>te(.9),className:"p-2 rounded cursor-pointer transition-colors text-xs bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",disabled:N,"aria-label":"Selección 90%",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{children:"90%"})})}),K.jsx("button",{onClick:()=>te(1),className:"p-2 rounded cursor-pointer transition-colors text-xs bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",disabled:N,"aria-label":"Selección completa",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{children:"100%"})})})]})]})]}),K.jsxs("div",{className:"bg-white rounded-lg border border-gray-200 p-4",children:[K.jsx("h3",{className:"text-sm font-semibold text-gray-700 mb-3",children:"Transformar imagen"}),K.jsxs("div",{className:"mb-4",children:[K.jsx("p",{className:"text-xs text-gray-600 mb-2",children:"Mover imagen"}),K.jsxs("div",{className:"grid grid-cols-3 gap-1",children:[K.jsx("div",{}),K.jsx("button",{onClick:()=>X(0,-10),className:"p-2 rounded cursor-pointer transition-colors text-sm bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Mover arriba",disabled:N,"aria-label":"Mover imagen hacia arriba",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{className:"icon icon-arrow-up-blue"})})}),K.jsx("div",{}),K.jsx("button",{onClick:()=>X(-10,0),className:"p-2 rounded cursor-pointer transition-colors text-sm bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Mover izquierda",disabled:N,"aria-label":"Mover imagen hacia la izquierda",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{className:"icon icon-arrow-left-blue"})})}),K.jsx("button",{onClick:Q,className:"p-2 rounded cursor-pointer transition-colors text-xs bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Centrar y ajustar imagen",disabled:N,"aria-label":"Centrar y ajustar imagen",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{className:"icon icon-radio-button-blue icon-md"})})}),K.jsx("button",{onClick:()=>X(10,0),className:"p-2 rounded cursor-pointer transition-colors text-sm bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Mover derecha",disabled:N,"aria-label":"Mover imagen hacia la derecha",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{className:"icon icon-arrow-right-blue"})})}),K.jsx("div",{}),K.jsx("button",{onClick:()=>X(0,10),className:"p-2 rounded cursor-pointer transition-colors text-sm bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Mover abajo",disabled:N,"aria-label":"Mover imagen hacia abajo",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{className:"icon icon-arrow-down-blue"})})}),K.jsx("div",{})]})]}),K.jsxs("div",{className:"mb-4",children:[K.jsxs("p",{className:"text-xs text-gray-600 mb-2",children:["Zoom ",S?S.percentage+"%":""]}),K.jsxs("div",{className:"flex gap-1",children:[K.jsx("button",{onClick:()=>J(-.2),className:"flex-1 p-2 rounded cursor-pointer transition-colors text-sm bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Alejar 20%",disabled:N,"aria-label":"Alejar imagen",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{className:"icon icon-zoom-out-blue"})})}),K.jsx("button",{onClick:ne,className:"flex-1 p-2 rounded cursor-pointer transition-colors text-xs bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Restablecer zoom original",disabled:N,"aria-label":"Restablecer el zoom para que la imagen se vea con su resolución original",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{className:"icon icon-screenshot-blue"})})}),K.jsx("button",{onClick:()=>J(.2),className:"flex-1 p-2 rounded cursor-pointer transition-colors text-sm bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Acercar 20%",disabled:N,"aria-label":"Acercar imagen",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{className:"icon icon-zoom-in-blue"})})})]})]}),K.jsxs("div",{className:"mb-4",children:[K.jsx("p",{className:"text-xs text-gray-600 mb-2",children:"Rotación"}),K.jsxs("div",{className:"flex gap-1 *:text-brand-blue-1000 *:text-sm",children:[K.jsx("button",{onClick:()=>Z(-90),className:"flex-1 p-2 rounded cursor-pointer transition-colors text-sm bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Rotar -90°",disabled:N,"aria-label":"Rotar imagen 90 grados a la izquierda",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{className:"icon icon-reply-blue"})})}),K.jsx("button",{onClick:()=>Z(-45),className:"flex-1 p-2 rounded cursor-pointer transition-colors text-xs bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Rotar -45°",disabled:N,"aria-label":"Rotar imagen 45 grados a la izquierda",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{children:"-45°"})})}),K.jsx("button",{onClick:()=>Z(45),className:"flex-1 p-2 rounded cursor-pointer transition-colors text-xs bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Rotar +45°",disabled:N,"aria-label":"Rotar imagen 45 grados a la derecha",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{children:"+45°"})})}),K.jsx("button",{onClick:()=>Z(90),className:"flex-1 p-2 rounded cursor-pointer transition-colors text-sm bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Rotar +90°",disabled:N,"aria-label":"Rotar imagen 90 grados a la derecha",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{className:"icon icon-send-arrow-blue"})})})]})]}),K.jsxs("div",{className:"mb-4",children:[K.jsx("p",{className:"text-xs text-gray-600 mb-2",children:"Voltear"}),K.jsxs("div",{className:"flex gap-1",children:[K.jsx("button",{onClick:re,className:"flex-1 p-2 rounded cursor-pointer transition-colors text-sm "+(v.horizontal?"bg-blue-100 border border-blue-300 text-blue-800":"bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200"),title:"Voltear horizontalmente "+(v.horizontal?"(activo)":""),disabled:N,"aria-label":"Voltear imagen horizontalmente","aria-pressed":v.horizontal,children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{className:"icon icon-arrow-left-right-blue border border-brand-blue-1000 rounded"})})}),K.jsx("button",{onClick:ae,className:"flex-1 p-2 cursor-pointer rounded transition-colors text-sm "+(v.vertical?"bg-blue-100 border border-blue-300 text-blue-800":"bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200"),title:"Voltear verticalmente "+(v.vertical?"(activo)":""),disabled:N,"aria-label":"Voltear imagen verticalmente","aria-pressed":v.vertical,children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsx("span",{className:"icon icon-arrow-up-down-blue border border-brand-blue-1000 rounded"})})})]})]}),K.jsx("button",{onClick:()=>{O.reset(),w({horizontal:!1,vertical:!1})},className:"w-full p-2 rounded cursor-pointer transition-colors text-sm bg-gray-100 border border-gray-300 text-gray-700 hover:bg-gray-200",title:"Reiniciar transformaciones",disabled:N,"aria-label":"Reiniciar todas las transformaciones de la imagen",children:K.jsx("div",{className:"flex items-center justify-center",children:K.jsxs("span",{children:[K.jsx("span",{className:"icon icon-refresh-blue icon--sm align-[middle!important] "})," ","Reiniciar ajustes"]})})})]})]})})]})]}):null}function bn({currentPage:e,totalPages:t,onPageChange:n,disabled:r=!1}){if(!t||t<=1)return null;const a=(()=>{const n=[],r=[],a=Math.max(1,e-2),o=Math.min(t,e+2);for(let e=a;e<=o;e++)n.push(e);return a>1&&(r.push(1),a>2&&r.push("...")),r.push(...n),o<t&&(o<t-1&&r.push("..."),r.push(t)),r})();return K.jsxs("div",{className:"flex items-center justify-center space-x-2 py-4",children:[K.jsxs("button",{onClick:()=>{e>1&&n(e-1)},disabled:r||e<=1,className:`\n px-3 py-2 text-sm font-medium rounded-md transition-colors disabled:cursor-default cursor-pointer\n ${r||e<=1?"text-gray-400 bg-gray-100 cursor-not-allowed":"text-gray-700 bg-white border border-gray-300 hover:bg-gray-50 focus:ring-2 focus:ring-blue-500"}\n `,children:[K.jsx("span",{className:"icon icon-arrow-left-white icon--sm"})," Anterior"]}),K.jsx("div",{className:"flex space-x-1",children:a.map((t,a)=>K.jsx(h.Fragment,{children:"..."===t?K.jsx("span",{className:"px-3 py-2 text-sm text-gray-500",children:"..."}):K.jsx("button",{onClick:()=>(t=>{t!==e&&n(t)})(t),disabled:r,className:`\n px-3 py-2 text-sm font-medium rounded-md transition-colors disabled:cursor-default cursor-pointer\n ${t===e?"bg-blue-600 text-white border border-blue-600":r?"text-gray-400 bg-gray-100 cursor-not-allowed":"text-gray-700 bg-white border border-gray-300 hover:bg-gray-50 focus:ring-2 focus:ring-blue-500"}\n `,children:t})},`page-${t}-${a}`))}),K.jsxs("button",{onClick:()=>{e<t&&n(e+1)},disabled:r||e>=t,className:`\n px-3 py-2 text-sm font-medium rounded-md transition-colors disabled:cursor-default cursor-pointer\n ${r||e>=t?"text-gray-400 bg-gray-100 cursor-not-allowed":"text-gray-700 bg-white border border-gray-300 hover:bg-gray-50 focus:ring-2 focus:ring-blue-500"}\n `,children:["Siguiente ",K.jsx("span",{className:"icon icon-arrow-right-white icon--sm"})]}),K.jsxs("div",{className:"text-sm text-gray-500 ml-4",children:["Página ",e," de ",t]})]})}function yn({isOpen:e,onClose:t}){return e?K.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",style:{zIndex:9999},children:K.jsxs("div",{className:"bg-white rounded-lg p-6 max-w-md mx-4 shadow-xl",children:[K.jsxs("div",{className:"flex items-center mb-4",children:[K.jsx("svg",{className:"w-6 h-6 text-red-600 mr-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:K.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"})}),K.jsx("h3",{className:"text-lg font-semibold text-gray-900",children:"Sesión Expirada"})]}),K.jsxs("div",{className:"mb-6",children:[K.jsx("p",{className:"text-gray-600 mb-2",children:"Su sesión ha expirado por seguridad."}),K.jsx("p",{className:"text-gray-600",children:"Es necesario recargar la página para obtener un nuevo token de acceso."})]}),K.jsx("div",{className:"flex justify-end space-x-3",children:K.jsx("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 vn(){const[e,t]=p.useState(!1),[n,r]=p.useState(null);return{deleteImg:async e=>{if(!e)return r("ID de imagen no proporcionado"),!1;t(!0),r(null);try{const t=await async function(e){try{return await te({endpoint:`/assets/${e}`,method:"DELETE",basePath:ie,useJWT:!0})}catch(n){throw oe(n)}}(e);return!1!==t.success}catch(a){return r(a.message),!1}finally{t(!1)}},loading:e,error:n,reset:()=>{r(null)}}}const wn=new Map;function kn({apiKey:e,prod:t=!1,url:n=!0,features:r=["gallery","upload","cropper"],modeUI:a="full",ui:o={showActions:["select","download","copy","delete","crop","variants"],hideActions:[],theme:"light",language:"es",compactMode:!1,showTabs:!0},callbacks:i={},instanceId:l=null,itemsPerPage:s=10}){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 c=(()=>{switch(a){case"gallery-only":return["gallery"];case"upload-only":return["upload"];case"crop-only":return["cropper"];case"ia-only":return["ia"];default:return r}})(),[u,d]=p.useState(c.includes("gallery")?"gallery":c.includes("upload")?"upload":c.includes("cropper")?"cropper":c.includes("ia")?"ia":c[0]||"gallery"),[f,h]=p.useState(null),[m,g]=p.useState(1),{isTokenExpired:b,handleTokenExpiredClose:y}=function(){const[e,t]=p.useState(!1),n=p.useCallback(e=>{if(401===e?.response?.status){const n=e.response.data;if("token_expired"===n?.error||n?.message?.includes("expired")||n?.message?.includes("caducado")||n?.error?.includes("expired"))return t(!0),!0}return!1},[]),r=p.useCallback(()=>{t(!1),alert("El token ha expirado. La página se recargará para obtener un nuevo token."),window.location.reload()},[]);return p.useEffect(()=>{const e=e=>{e.detail&&e.detail.error&&n(e.detail.error)};return window.addEventListener("tokenExpiredError",e),()=>{window.removeEventListener("tokenExpiredError",e)}},[n]),{isTokenExpired:e,checkTokenExpiration:n,handleTokenExpiredClose:r}}(),{upload:v,loading:w,error:k,uploadedImage:x,reset:S}=function(){const[e,t]=p.useState(!1),[n,r]=p.useState(null),[a,o]=p.useState(null);return{upload:async(e,n=null)=>{if(!e)return r("No se ha proporcionado ningún archivo"),null;t(!0),r(null),o(null);try{const t=await se(e,n,!1),r=t.result||t;return o(r),r}catch(a){return r(a.message),null}finally{t(!1)}},loading:e,error:n,uploadedImage:a,reset:()=>{r(null),o(null)}}}(),{deleteImg:C,loading:E,error:_,reset:T}=vn(),{images:N,loading:P,error:R,pagination:z,invalidateCache:j,setImages:O}=function(e,t=!1,n={}){const[r,a]=p.useState([]),[o,i]=p.useState(!0),[l,s]=p.useState(null),[c,u]=p.useState(null),[d,f]=p.useState(0),h=p.useMemo(()=>JSON.stringify(n),[n]);return p.useEffect(()=>{const e=`${h}`,t=wn.get(e),r=Date.now();if(t&&r-t.timestamp<6e5)return a(t.data),u(t.pagination||null),void i(!1);let o=!0;return(async()=>{if(d>=3)o&&(s("Error de autenticación: Verifica tus credenciales API"),i(!1));else try{const t=await le(n);if(!o)return;const i=t.result||[],l=t.pagination||null;a(i),u(l),s(null),f(0),wn.set(e,{data:i,pagination:l,timestamp:r})}catch(t){o&&(s(t.message),f(e=>e+1))}finally{o&&i(!1)}})(),()=>{o=!1}},[e,t,h,d,n]),{images:r,loading:o,error:l,pagination:c,setImages:a,invalidateCache:()=>{wn.delete(`${h}`)}}}(e,t,{limit:s,page:m}),{refreshVariants:A}=ue(),L=e=>!o.hideActions?.includes(e)&&(!!o.showActions?.includes(e)||!(o.showActions?.length>0)),I=[{id:"gallery",label:"Galería",feature:"gallery"},{id:"upload",label:"Subir nueva",feature:"upload"},{id:"cropper",label:"Recortador",hideNonActive:!0,feature:"cropper"}].filter(e=>c.includes(e.feature)),M=async e=>{if(!confirm("¿Estás seguro de que quieres eliminar esta imagen?"))return;await C(e)&&(j(),g(1),O(t=>t.filter(t=>t.id!==e)),f&&f.id===e&&(h(null),d("gallery")))};return K.jsxs("div",{className:"limbo-card-parent max-w-7xl mx-auto my-8 p-6 shadow-xl w-full",children:[o.showTabs&&K.jsx(G,{tabs:I,active:u,onChange:e=>{d(e),"upload"!==e&&S(),"gallery"!==e&&T()}}),R&&K.jsxs("div",{className:"alert alert-danger",children:["Error al cargar imágenes: ",R]}),_&&K.jsxs("div",{className:"alert alert-danger",children:["Error al eliminar imagen: ",_]}),"gallery"===u&&K.jsxs(K.Fragment,{children:[E&&K.jsx(pe,{text:"Eliminando imagen..."}),K.jsx(me,{apiKey:e,prod:t,onSelect:e=>{i.onSelect&&i.onSelect({assetId:e.id,url:e.url,fileName:e.filename,mime:e.mime_type,width:e.width,height:e.height,instanceId:l})},onCrop:e=>{h(e),c.includes("cropper")&&d("cropper")},onDelete:L("delete")?M:null,deletingId:E,images:N,loading:P,error:R,allowedActions:{select:L("select"),download:L("download"),copy:L("copy"),delete:L("delete"),crop:L("crop")}}),z&&!P&&K.jsx(bn,{currentPage:z.page||m,totalPages:z.pages||1,onPageChange:e=>{g(e)},disabled:P||E})]}),"upload"===u&&K.jsxs("div",{children:[w&&K.jsx(pe,{text:"Subiendo imagen..."}),k&&K.jsxs("div",{className:"alert alert-danger",children:["Error al subir imagen: ",k]}),x&&K.jsxs("div",{className:"alert alert-success",children:["✅ Imagen subida correctamente: ",x.filename]}),K.jsx(Oe,{onUpload:async e=>{const t=await v(e);t&&(j(),g(1),O(e=>[t,...e]),d("gallery"),i.onUpload&&i.onUpload({assetId:t.id,url:t.url,fileName:t.filename,mime:t.mime_type,width:t.width,height:t.height,instanceId:l}))},disabled:w,apiKey:e,prod:t})]}),"cropper"===u&&K.jsx(gn,{image:f,onSave:()=>{j(),h(null),d("gallery")},onCancel:()=>{h(null),d("gallery")},onDelete:()=>M(f?.id),deleting:E,onVariantCreated:(e,t)=>{A(e)}}),K.jsx(yn,{isOpen:b,onClose:y})]})}class xn{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=F.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.modal.close(),this.eventManager.emit("modal:close",{instance:this})),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=F.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 h.createElement("div",{id:`limbo-component-container-${this.id}`,className:"limbo-instance limbo-component-container-wrapper py-3","data-limbo-id":this.id,"data-limbo-mode":this.config.mode},h.createElement(kn,{apiKey:this.config.apiKey,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}))}_createCallbacks(){return{onSelect:e=>{const t=this._createStandardPayload(e,"select");this.config.callbacks?.onSelect&&this.config.callbacks.onSelect(t),this._emitDOMEvent("select",t)},onUpload:e=>{const t=this._createStandardPayload(e,"upload");this.config.callbacks?.onUpload&&this.config.callbacks.onUpload(t),this._emitDOMEvent("upload",t)},onError:e=>{const t={instance:this,error:{message:e.message||"Unknown error",code:e.code||"UNKNOWN",timestamp:Date.now()}};this.config.callbacks?.onError&&this.config.callbacks.onError(t.error),this._emitDOMEvent("error",t)},onClose:()=>{const e={instance:this,timestamp:Date.now()};this.config.callbacks?.onClose&&this.config.callbacks.onClose(),this._emitDOMEvent("close",e)}}}_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){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.apiKey||this.config.publicKey))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 Sn{constructor(){this.instances=new Map,this.counter=0}create(e,t,n){const r="limbo-"+ ++this.counter,a=new xn(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 Cn{constructor(){this.config=null,this.instances=new Map,this.observer=null,this.initialized=!1}configure(e,t,n){return this.config={dataset:e.dataset||"data-limbo-input-file",return:e.return||"url",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||"medium",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=`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,o={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"},i={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=i[n]||i.primary;Object.assign(e.style,{...o,...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){switch((t||{}).return||this.config.return||"url"){case"url":return e.url||e.path||"";case"base64":return e.base64||e.dataUrl||"";case"assetId":return e.assetId||e.id||"";case"fileName":return e.fileName||e.filename||"";case"object":return 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,created:e.created_at||e.created});default:return 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})}}_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||"medium",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},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;if(!t||"none"===t||"false"===t)return null;if("free"===t)return{aspectRatio:null,quality:e.quality||this.config.quality,format:e.format||this.config.format};const n={"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(n[t])return{aspectRatio:n[t],quality:e.quality||this.config.quality,format:e.format||this.config.format,minCropBoxWidth:e.minWidth||this.config.minWidth,minCropBoxHeight:e.minHeight||this.config.minHeight};if("string"==typeof t&&t.includes(":")){const[n,r]=t.split(":").map(Number);if(!isNaN(n)&&!isNaN(r)&&0!==r)return{aspectRatio:n/r,quality:e.quality||this.config.quality,format:e.format||this.config.format}}const r=parseFloat(t);return!isNaN(r)&&r>0?{aspectRatio:r,quality:e.quality||this.config.quality,format:e.format||this.config.format}:"object"==typeof t?{quality:e.quality||this.config.quality,format:e.format||this.config.format,...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;return{return:e.getAttribute("data-limbo-return")||this.config.return,mode:e.getAttribute("data-limbo-mode")||this.config.mode,features:t(e.getAttribute("data-limbo-features"))||this.config.features,crop:e.getAttribute("data-limbo-crop")||this.config.crop,quality:a(e.getAttribute("data-limbo-quality"))||this.config.quality,format:e.getAttribute("data-limbo-format")||this.config.format,modeUI:e.getAttribute("data-limbo-mode-ui")||this.config.modeUI,modalSize:e.getAttribute("data-limbo-modal-size")||this.config.modalSize,theme:e.getAttribute("data-limbo-theme")||this.config.theme,compact: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}}_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=`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 En{constructor(){this.listeners=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 _n{constructor(){this.activeModals=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 Tn(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 Tn{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: 400px;",medium:e?"width: 100%; height: 100%;":"max-width: 600px;",large:e?"width: 100%; height: 100%;":"max-width: 800px;",xlarge:e?"width: 100%; height: 100%;":"max-width: 1200px;"},n=e?`\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n transform: translateY(100%);\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: 1;\n transition: transform 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=n,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);return requestAnimationFrame(()=>{this.backdrop&&(this.backdrop.style.opacity="1"),this.element.style.opacity="1",this.element.style.transform=e?"translateY(0%)":"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);return this.backdrop&&(this.backdrop.style.opacity="0"),this.element.style.opacity="0",this.element.style.transform=e?"translateY(100%)":"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 Nn{constructor(){this.currentTheme=null,this.customThemes=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=new Map,this.appliedStyles=new Set,this.changeCallbacks=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,o=(n>>8&255)-r,i=(255&n)-r;return"#"+(16777216+65536*(a<255?a<1?0:a:255)+256*(o<255?o<1?0:o:255)+(i<255?i<1?0:i:255)).toString(16).slice(1)}_lightenColor(e,t){const n=parseInt(e.replace("#",""),16),r=Math.round(2.55*t),a=(n>>16)+r,o=(n>>8&255)+r,i=(255&n)+r;return"#"+(16777216+65536*(a<255?a<1?0:a:255)+256*(o<255?o<1?0:o:255)+(i<255?i<1?0:i: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 Pn=new class{constructor(){this.config=new n,this.instances=new Sn,this.autoInputs=new Cn,this.events=new En,this.modals=new _n,this.theme=new Nn,this.containerQueryDetector=Q,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",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,o=0;return r.forEach(e=>{try{this.autoInputs._processInput(e),a++}catch(t){console.warn(`⚠️ Limbo: Error procesando input ${e.id||e.name}:`,t),o++}}),this.events.emit("limbo:scanCompleted",{found:r.length,processed:a,skipped:o,inputs:Array.from(r)}),{found:r.length,processed:a,skipped:o}}_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=this.create({...e,mode:"modal",autoDestroy:!0,callbacks:{onSelect:e=>{t(e),n.close()},onClose:()=>{}}});n.open()}};return"undefined"!=typeof window&&(window.Limbo=Pn),Pn});
58
58
  //# sourceMappingURL=limbo.umd.map