limbo-component 4.0.0 → 4.0.2
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/CHANGELOG.md +41 -0
- package/dist/limbo.cjs.js +1 -1
- package/dist/limbo.cjs.map +1 -1
- package/dist/limbo.css +1 -1
- package/dist/limbo.es.js +136 -136
- package/dist/limbo.es.map +1 -1
- package/dist/limbo.min.js +1 -1
- package/dist/limbo.min.js.map +1 -1
- package/dist/limbo.umd.js +1 -1
- package/dist/limbo.umd.js.map +1 -1
- package/dist/types/src/App.d.ts +1 -2
- package/dist/types/src/App.d.ts.map +1 -1
- package/dist/types/src/hooks/useTokenExpiration.d.ts.map +1 -1
- package/dist/types/src/services/apiClient.d.ts +1 -1
- package/dist/types/src/services/apiClient.d.ts.map +1 -1
- package/package.json +2 -1
package/dist/limbo.es.js
CHANGED
|
@@ -11,21 +11,21 @@ return s("div",{className:a,role:"tablist","aria-label":"Opciones de navegación
|
|
|
11
11
|
/* @__PURE__ */s("li",{children:"Recarga la página para continuar con tu trabajo."}),
|
|
12
12
|
/* @__PURE__ */s("li",{children:"Si el problema persiste, cierra sesión y vuelve a entrar."})]})]}),
|
|
13
13
|
/* @__PURE__ */c("div",{className:"lb:flex lb:justify-end lb:gap-2",children:[n&&/* @__PURE__ */s("button",{type:"button",onClick:n,className:"lb:px-4 lb:py-2 lb:text-sm lb:font-medium lb:text-gray-700 lb:border lb:border-gray-300 lb:rounded-md lb:hover:bg-gray-50 lb:transition-colors",children:"Ignorar"}),
|
|
14
|
-
/* @__PURE__ */s("button",{type:"button",onClick:t,className:"lb:px-4 lb:py-2 lb:text-sm lb:font-medium lb:bg-brand-blue-800 lb:text-white lb:rounded-md lb:hover:bg-brand-blue-1000 lb:transition-colors",children:"Recargar página"})]})]})}):null}const F="https://led-dev-limbo-dev.eu.els.local",j="https://limbo.lefebvre.es";let U={publicKey:null,token:null,authMode:null,tokenEndpoint:null,tokenProvider:null,prod:!1},B=!1;function W({prod:e=!1}={}){return e?j:F}function q(e){e!==U.token&&(B=!1),U.token=e}function V(){return{...U}}async function H({endpoint:e,method:t="GET",body:n=null,prod:l=!1,basePath:r="",customHeaders:a={},isFormData:i=!1,useJWT:o=!0,_isRetry:s=!1}){try{const c=l||U.prod,u=await async function({isFormData:e=!1,useJWT:t=!0,customHeaders:n={}}={}){const l={};e||(l["Content-Type"]="application/json");let r=U.token;if(t){if("jwt"===U.authMode&&U.tokenProvider&&!r)try{console.log("🔑 Calling tokenProvider..."),r=await U.tokenProvider(),console.log("✅ Token obtained from tokenProvider"),U.token=r}catch(a){throw console.error("❌ tokenProvider failed:",a),new Error("Failed to obtain token from tokenProvider: "+a.message)}else if("session"===U.authMode&&!r)try{const e=W(U),t=U.tokenEndpoint||"/auth/token",n=await fetch(`${e}${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({public_key:U.publicKey}),credentials:"include"});if(!n.ok)throw new Error(`Session auth failed: ${n.status}`);r=(await n.json()).token,U.token=r}catch(a){throw console.error("❌ Session authentication failed:",a),new Error("Failed to authenticate with session. User must be logged in.")}r?l.Authorization=`Bearer ${r}`:console.warn("⚠️ No JWT token available:",{authMode:U.authMode,hasPublicKey:!!U.publicKey,hasTokenProvider:!!U.tokenProvider})}return e&&delete l["Content-Type"],{...l,...n}}({isFormData:i,useJWT:o,customHeaders:a});"GET"===t&&!n&&u["Content-Type"]&&delete u["Content-Type"];const d=await fetch(`${W({prod:c})}${r}${e}`,{method:t,headers:u,body:n?i?n:JSON.stringify(n):void 0,credentials:"include"});if(204===d.status)return{success:!0,data:null,message:"No content",httpCode:204,timestamp:/* @__PURE__ */(new Date).toISOString()};if(!d.ok){let c=`HTTP ${d.status}: ${d.statusText}`,u=null;try{const e=await d.json();u=e,e.error?c=`${e.error.code}: ${e.error.message}`:e.message&&(c=e.message)}catch{}if(401===d.status){if("jwt"===U.authMode&&U.tokenProvider&&!s&&B){U.token=null;try{const s=await U.tokenProvider();return U.token=s,H({endpoint:e,method:t,body:n,prod:l,basePath:r,isFormData:i,useJWT:o,customHeaders:a,_isRetry:!0})}catch{}}window.dispatchEvent(new CustomEvent("tokenExpiredError",{detail:{error:{response:{status:401,data:u}}}}))}throw new Error(c)}return o&&(B=!0),d.json()}catch(c){throw new Error(`API Error: ${c.message}`)}}function K(){const e=V();return e?.prod||!1?"https://limbo.lefebvre.es":"https://led-dev-limbo-dev.eu.els.local"}function G(e){if(!e?.id)return null;return`${K()}/api/assets/${e.id}/download`}function Q(e){if(!e)return null;if(e.startsWith("http://")||e.startsWith("https://"))return e;if(e.startsWith("/")){return`${K()}${e}`}return e}function X(e){if(!e?.success||!e?.data)return{result:null};const t=e.data;return{result:{id:t.id,filename:t.filename||t.original_filename,mime_type:t.mime_type,file_size:t.file_size,width:t.width,height:t.height,upload_date:t.upload_date||t.created_at,processed_date:t.processed_date,processing_status:t.processing_status||t.status,url:Q(t.url)||G(t),url_webp:Q(t.url_webp),url_original:Q(t.url_original),format:t.format,format_original:t.format_original,permanent:t.permanent??!0,expires_at:t.expires_at,metadata:t.metadata||{},asset_type:t.asset_type||null,asset_subtype:t.asset_subtype||null,thumbnail_url:Q(t.thumbnail_url)||null,folder:t.folder||null,variants:Y(t.variants||[]),variants_count:t.variants_count||t.variants?.length||0}}}function Y(e){return Array.isArray(e)?e.map(e=>({id:e.id,name:e.name,width:e.width,height:e.height,format:e.format||e.output_format,file_size:e.file_size,crop_params:e.crop_params,url:Q(e.url),permanent:e.permanent??!0,expires_at:e.expires_at,created_at:e.created_at})):[]}function J(e){if(!e?.success||!e?.data)return{result:null};const t=e.data;if(t.id&&t.url&&t.name&&!t.processing_mode&&!t.variants)return console.log("[adaptVariantGenerationFromV2] Detectado formato de /variants/upload"),{result:{id:t.id,name:t.name,width:t.width,height:t.height,format:t.format,file_size:t.file_size,url:t.url,urlSigned:t.url,status:"completed",created_at:t.created_at||/* @__PURE__ */(new Date).toISOString()}};if("sync"===t.processing_mode&&t.variants&&t.variants.length>0){const e=t.variants[0];return{result:{id:e.id||null,name:e.name,width:parseInt(e.size?.split("x")[0])||e.width,height:parseInt(e.size?.split("x")[1])||e.height,format:e.format,file_size:e.file_size,url:e.url,urlSigned:e.url,status:e.status,asset_id:t.asset_id,created_at:e.created_at||/* @__PURE__ */(new Date).toISOString(),all_variants:t.variants}}}return{result:{job_id:t.job_id,asset_id:t.asset_id,variants_requested:t.variants_requested||[],processing_mode:t.processing_mode||"async",estimated_completion:t.estimated_completion,variant_statuses:(t.variant_statuses||t.variants||[]).map(e=>({name:e.name,status:e.status,size:e.expected_size||e.size,format:e.format}))}}}function Z(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 ee="/api";async function te(e={}){try{const t={url_expires:"0",...e},n=`/assets?${new URLSearchParams(t).toString()}`;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,variants:e.variants_count&&(Y(e.variants)||Y(e.image_variants))||[],url:Q(e.url)||G(e),url_webp:Q(e.url_webp),format:e.format,permanent:e.permanent??!0,expires_at:e.expires_at,folder:e.folder||null,asset_type:e.asset_type||null,asset_subtype:e.asset_subtype||null,thumbnail_url:Q(e.thumbnail_url)||null,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 H({endpoint:n,method:"GET",basePath:ee,useJWT:!0}))}catch(t){throw Z(t)}}async function ne(e,t=null,n=!1,l=null){try{const r=new FormData;r.append("file",e),t&&r.append("uploaded_by",t),n&&r.append("store_original",n.toString()),l&&r.append("folder",l);return function(e){if(!e?.success||!e?.data)return{result:null};const t=e.data;return{result:{id:t.id,filename:t.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:Q(t.url),url_webp:Q(t.url_webp),url_original:Q(t.url_original),format:t.format,format_original:t.format_original,permanent:t.permanent??!0,folder:t.folder||null,processing:t.processing||{master_webp:"processing"===t.status?"queued":"completed",variants:"processing"===t.status?"queued":"completed"},asset_type:t.asset_type||null,asset_subtype:t.asset_subtype||null,thumbnail_url:Q(t.thumbnail_url)||null,checksum:t.checksum,storage_path:t.storage_path_base,metadata:t.metadata||{}}}}(await H({endpoint:"/assets",method:"POST",body:r,basePath:ee,isFormData:!0,useJWT:!0}))}catch(r){throw Z(r)}}async function le(e,t){try{return X(await H({endpoint:`/assets/${e}`,method:"PATCH",body:t,basePath:ee,useJWT:!0}))}catch(n){throw Z(n)}}async function re(e,t=0){try{const l=new URLSearchParams({url_expires:t.toString()}),r=await H({endpoint:`/assets/${e}/variants?${l}`,method:"GET",basePath:ee,useJWT:!0});return n=r,n?.success&&Array.isArray(n?.data?.variants)?{result:n.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.format||e.output_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:Q(e.url)||G(e),permanent:e.permanent??!0,expires_at:e.expires_at,metadata:e.metadata||{},crop_data:e.crop_data||{},crop_params:e.crop_params||e.crop_data||{},parent_asset_id:e.parent_asset_id||n.data.asset_id,variant_type:e.variant_type||"crop"}))}:{result:[]}}catch(l){throw Z(l)}var n}function ae(){const[e,n]=t(!1),[l,r]=t(null);return{deleteImg:async e=>{if(!e)return r("ID de imagen no proporcionado"),!1;n(!0),r(null);try{const t=await async function(e){try{return await H({endpoint:`/assets/${e}`,method:"DELETE",basePath:ee,useJWT:!0})}catch(l){throw Z(l)}}(e);return!1!==t.success}catch(t){return r(t.message),!1}finally{n(!1)}},loading:e,error:l,reset:()=>{r(null)}}}const ie=/* @__PURE__ */new Map,oe=6e5,se="limbo_gallery_cache";(()=>{try{const e=sessionStorage.getItem(se);if(e){const t=JSON.parse(e),n=Date.now();let l=!1;if(Object.entries(t).forEach(([e,t])=>{t.timestamp&&n-t.timestamp<oe?ie.set(e,t):l=!0}),l)if(0===ie.size)sessionStorage.removeItem(se);else{const e={};ie.forEach((t,n)=>{e[n]=t}),sessionStorage.setItem(se,JSON.stringify(e))}}}catch{}})();const ce=()=>{ie.clear();try{sessionStorage.removeItem(se)}catch{}};function ue(e,a=!1,i={},o=!0){const s=l(()=>JSON.stringify(i),[i]),c=r((()=>{const e=s,t=ie.get(e),n=Date.now();return t&&n-t.timestamp<oe?{images:t.data,pagination:t.pagination||null,loading:!1}:{images:[],pagination:null,loading:o}})()),[u,d]=t(c.current.images),[b,m]=t(c.current.loading),[h,p]=t(null),[f,g]=t(c.current.pagination),[v,y]=t(0),[w,x]=t(0);n(()=>{if(!o)return void m(!1);const e=`${s}`,t=ie.get(e),n=Date.now();if(t&&n-t.timestamp<oe)return d(t.data),g(t.pagination||null),void m(!1);m(!0);let l=!0;return(async()=>{if(v>=3)l&&(p("Error de autenticación: Verifica tus credenciales API"),m(!1));else try{const t=await te(i);if(!l)return;const r=t.result||t.data||[],a=t.pagination||null;d(r),g(a),p(null),y(0),ie.set(e,{data:r,pagination:a,timestamp:n}),(()=>{try{const e={};ie.forEach((t,n)=>{e[n]=t}),sessionStorage.setItem(se,JSON.stringify(e))}catch{}})()}catch(t){l&&(p(t.message),y(e=>e+1))}finally{l&&m(!1)}})(),()=>{l=!1}},[e,a,s,v,o,w]);return{images:u,loading:b,error:h,pagination:f,setImages:d,invalidateCache:()=>{ie.clear();try{sessionStorage.removeItem(se)}catch{}},refetch:()=>{ie.clear();try{sessionStorage.removeItem(se)}catch{}m(!0),x(e=>e+1)}}}function de(){const[e,n]=t({}),[l,r]=t({}),[i,o]=t({});return{loadVariants:a(async(t,a=!1)=>{if(t&&!l[t]){if(!a&&e[t])return e[t];r(e=>({...e,[t]:!0})),o(e=>({...e,[t]:null}));try{const e=await re(t),l=e?.result||[];return n(e=>({...e,[t]:l})),l}catch(i){return console.error("Error loading variants:",i),o(e=>({...e,[t]:i.message})),[]}finally{r(e=>({...e,[t]:!1}))}}},[e,l]),getVariants:a(t=>e[t]||[],[e]),isLoading:a(e=>l[e]||!1,[l]),getError:a(e=>i[e]||null,[i]),clearVariants:a(e=>{n(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})},[]),refreshVariants:a(async e=>{if(e){r(t=>({...t,[e]:!0})),o(t=>({...t,[e]:null}));try{const t=await re(e),l=t?.result||[];return n(t=>({...t,[e]:l})),l}catch(t){return console.error("Error refreshing variants:",t),o(n=>({...n,[e]:t.message})),[]}finally{r(t=>({...t,[e]:!1}))}}},[]),removeVariant:a(async(e,t)=>{try{return await async function(e,t){try{return await H({endpoint:`/assets/${e}/variants/${t}`,method:"DELETE",basePath:ee,useJWT:!0})}catch(n){throw Z(n)}}(e,t),n(n=>{const l=n[e]||[];return{...n,[e]:l.filter(e=>e.id!==t)}}),{success:!0}}catch(l){return console.error("Error deleting variant:",l),{success:!1,error:l.message}}},[])}}function be(e,l=500){const[r,a]=t(e);return n(()=>{const t=setTimeout(()=>{a(e)},l);return()=>{clearTimeout(t)}},[e,l]),r}function me(){/* @__PURE__ */
|
|
14
|
+
/* @__PURE__ */s("button",{type:"button",onClick:t,className:"lb:px-4 lb:py-2 lb:text-sm lb:font-medium lb:bg-brand-blue-800 lb:text-white lb:rounded-md lb:hover:bg-brand-blue-1000 lb:transition-colors",children:"Recargar página"})]})]})}):null}const F="https://led-dev-limbo-dev.eu.els.local",j="https://limbo.lefebvre.es";let U={publicKey:null,token:null,authMode:null,tokenEndpoint:null,tokenProvider:null,prod:!1},B=!1,W=null,q=null;function V(e){W="number"==typeof e&&e>0?Date.now()+1e3*e-3e4:null}async function H(){if(q)return q;q=(async()=>{if("jwt"===U.authMode&&U.tokenProvider){console.log("🔑 Calling tokenProvider...");const e=await U.tokenProvider(),t="string"==typeof e?e:e?.token,n="object"==typeof e?e?.expires_in:null;if(!t)throw new Error("tokenProvider returned no token");return U.token=t,V(n),console.log("✅ Token obtained from tokenProvider"),t}if("session"===U.authMode){const e=K(U),t=U.tokenEndpoint||"/auth/token",n=await fetch(`${e}${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({public_key:U.publicKey}),credentials:"include"});if(!n.ok)throw new Error(`Session auth failed: ${n.status}`);const l=await n.json();if(!l.token)throw new Error("Session auth returned no token");return U.token=l.token,V(l.expires_in),l.token}throw new Error(`Cannot refresh token in authMode='${U.authMode}'`)})();try{return await q}finally{q=null}}function K({prod:e=!1}={}){return e?j:F}async function G({isFormData:e=!1,useJWT:t=!0,customHeaders:n={}}={}){const l={};if(e||(l["Content-Type"]="application/json"),t){U.token&&null!==W&&Date.now()>=W&&(console.log("⏰ Token caducado por TTL, refrescando proactivamente"),U.token=null,W=null);let e=U.token;if(!e&&("jwt"===U.authMode&&U.tokenProvider||"session"===U.authMode))try{e=await H()}catch(r){throw console.error("❌ Token acquisition failed:",r),new Error("Failed to obtain token: "+r.message)}e?l.Authorization=`Bearer ${e}`:console.warn("⚠️ No JWT token available:",{authMode:U.authMode,hasPublicKey:!!U.publicKey,hasTokenProvider:!!U.tokenProvider})}return e&&delete l["Content-Type"],{...l,...n}}function Q(e,t=null){e!==U.token&&(B=!1),U.token=e,V(t)}function X(){return{...U}}async function Y({endpoint:e,method:t="GET",body:n=null,prod:l=!1,basePath:r="",customHeaders:a={},isFormData:i=!1,useJWT:o=!0,_isRetry:s=!1}){try{const c=l||U.prod,u=await G({isFormData:i,useJWT:o,customHeaders:a});"GET"===t&&!n&&u["Content-Type"]&&delete u["Content-Type"];const d=await fetch(`${K({prod:c})}${r}${e}`,{method:t,headers:u,body:n?i?n:JSON.stringify(n):void 0,credentials:"include"});if(204===d.status)return{success:!0,data:null,message:"No content",httpCode:204,timestamp:/* @__PURE__ */(new Date).toISOString()};if(!d.ok){let c=`HTTP ${d.status}: ${d.statusText}`,u=null;try{const e=await d.json();u=e,e.error?c=`${e.error.code}: ${e.error.message}`:e.message&&(c=e.message)}catch{}if(401===d.status){let c=!1;if("jwt"===U.authMode&&U.tokenProvider&&!s&&B){c=!0,U.token=null,W=null;try{return await H(),Y({endpoint:e,method:t,body:n,prod:l,basePath:r,isFormData:i,useJWT:o,customHeaders:a,_isRetry:!0})}catch{}}window.dispatchEvent(new CustomEvent("tokenExpiredError",{detail:{error:{response:{status:401,data:u}},refreshAttempted:c}}))}throw new Error(c)}return o&&(B=!0),d.json()}catch(c){throw new Error(`API Error: ${c.message}`)}}function J(){const e=X();return e?.prod||!1?"https://limbo.lefebvre.es":"https://led-dev-limbo-dev.eu.els.local"}function Z(e){if(!e?.id)return null;return`${J()}/api/assets/${e.id}/download`}function ee(e){if(!e)return null;if(e.startsWith("http://")||e.startsWith("https://"))return e;if(e.startsWith("/")){return`${J()}${e}`}return e}function te(e){if(!e?.success||!e?.data)return{result:null};const t=e.data;return{result:{id:t.id,filename:t.filename||t.original_filename,mime_type:t.mime_type,file_size:t.file_size,width:t.width,height:t.height,upload_date:t.upload_date||t.created_at,processed_date:t.processed_date,processing_status:t.processing_status||t.status,url:ee(t.url)||Z(t),url_webp:ee(t.url_webp),url_original:ee(t.url_original),format:t.format,format_original:t.format_original,permanent:t.permanent??!0,expires_at:t.expires_at,metadata:t.metadata||{},asset_type:t.asset_type||null,asset_subtype:t.asset_subtype||null,thumbnail_url:ee(t.thumbnail_url)||null,folder:t.folder||null,variants:ne(t.variants||[]),variants_count:t.variants_count||t.variants?.length||0}}}function ne(e){return Array.isArray(e)?e.map(e=>({id:e.id,name:e.name,width:e.width,height:e.height,format:e.format||e.output_format,file_size:e.file_size,crop_params:e.crop_params,url:ee(e.url),permanent:e.permanent??!0,expires_at:e.expires_at,created_at:e.created_at})):[]}function le(e){if(!e?.success||!e?.data)return{result:null};const t=e.data;if(t.id&&t.url&&t.name&&!t.processing_mode&&!t.variants)return console.log("[adaptVariantGenerationFromV2] Detectado formato de /variants/upload"),{result:{id:t.id,name:t.name,width:t.width,height:t.height,format:t.format,file_size:t.file_size,url:t.url,urlSigned:t.url,status:"completed",created_at:t.created_at||/* @__PURE__ */(new Date).toISOString()}};if("sync"===t.processing_mode&&t.variants&&t.variants.length>0){const e=t.variants[0];return{result:{id:e.id||null,name:e.name,width:parseInt(e.size?.split("x")[0])||e.width,height:parseInt(e.size?.split("x")[1])||e.height,format:e.format,file_size:e.file_size,url:e.url,urlSigned:e.url,status:e.status,asset_id:t.asset_id,created_at:e.created_at||/* @__PURE__ */(new Date).toISOString(),all_variants:t.variants}}}return{result:{job_id:t.job_id,asset_id:t.asset_id,variants_requested:t.variants_requested||[],processing_mode:t.processing_mode||"async",estimated_completion:t.estimated_completion,variant_statuses:(t.variant_statuses||t.variants||[]).map(e=>({name:e.name,status:e.status,size:e.expected_size||e.size,format:e.format}))}}}function re(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 ae="/api";async function ie(e={}){try{const t={url_expires:"0",...e},n=`/assets?${new URLSearchParams(t).toString()}`;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,variants:e.variants_count&&(ne(e.variants)||ne(e.image_variants))||[],url:ee(e.url)||Z(e),url_webp:ee(e.url_webp),format:e.format,permanent:e.permanent??!0,expires_at:e.expires_at,folder:e.folder||null,asset_type:e.asset_type||null,asset_subtype:e.asset_subtype||null,thumbnail_url:ee(e.thumbnail_url)||null,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 Y({endpoint:n,method:"GET",basePath:ae,useJWT:!0}))}catch(t){throw re(t)}}async function oe(e,t=null,n=!1,l=null){try{const r=new FormData;r.append("file",e),t&&r.append("uploaded_by",t),n&&r.append("store_original",n.toString()),l&&r.append("folder",l);return function(e){if(!e?.success||!e?.data)return{result:null};const t=e.data;return{result:{id:t.id,filename:t.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:ee(t.url),url_webp:ee(t.url_webp),url_original:ee(t.url_original),format:t.format,format_original:t.format_original,permanent:t.permanent??!0,folder:t.folder||null,processing:t.processing||{master_webp:"processing"===t.status?"queued":"completed",variants:"processing"===t.status?"queued":"completed"},asset_type:t.asset_type||null,asset_subtype:t.asset_subtype||null,thumbnail_url:ee(t.thumbnail_url)||null,checksum:t.checksum,storage_path:t.storage_path_base,metadata:t.metadata||{}}}}(await Y({endpoint:"/assets",method:"POST",body:r,basePath:ae,isFormData:!0,useJWT:!0}))}catch(r){throw re(r)}}async function se(e,t){try{return te(await Y({endpoint:`/assets/${e}`,method:"PATCH",body:t,basePath:ae,useJWT:!0}))}catch(n){throw re(n)}}async function ce(e,t=0){try{const l=new URLSearchParams({url_expires:t.toString()}),r=await Y({endpoint:`/assets/${e}/variants?${l}`,method:"GET",basePath:ae,useJWT:!0});return n=r,n?.success&&Array.isArray(n?.data?.variants)?{result:n.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.format||e.output_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:ee(e.url)||Z(e),permanent:e.permanent??!0,expires_at:e.expires_at,metadata:e.metadata||{},crop_data:e.crop_data||{},crop_params:e.crop_params||e.crop_data||{},parent_asset_id:e.parent_asset_id||n.data.asset_id,variant_type:e.variant_type||"crop"}))}:{result:[]}}catch(l){throw re(l)}var n}function ue(){const[e,n]=t(!1),[l,r]=t(null);return{deleteImg:async e=>{if(!e)return r("ID de imagen no proporcionado"),!1;n(!0),r(null);try{const t=await async function(e){try{return await Y({endpoint:`/assets/${e}`,method:"DELETE",basePath:ae,useJWT:!0})}catch(l){throw re(l)}}(e);return!1!==t.success}catch(t){return r(t.message),!1}finally{n(!1)}},loading:e,error:l,reset:()=>{r(null)}}}const de=/* @__PURE__ */new Map,be=6e5,me="limbo_gallery_cache";(()=>{try{const e=sessionStorage.getItem(me);if(e){const t=JSON.parse(e),n=Date.now();let l=!1;if(Object.entries(t).forEach(([e,t])=>{t.timestamp&&n-t.timestamp<be?de.set(e,t):l=!0}),l)if(0===de.size)sessionStorage.removeItem(me);else{const e={};de.forEach((t,n)=>{e[n]=t}),sessionStorage.setItem(me,JSON.stringify(e))}}}catch{}})();const he=()=>{de.clear();try{sessionStorage.removeItem(me)}catch{}};function pe(e,a=!1,i={},o=!0){const s=l(()=>JSON.stringify(i),[i]),c=r((()=>{const e=s,t=de.get(e),n=Date.now();return t&&n-t.timestamp<be?{images:t.data,pagination:t.pagination||null,loading:!1}:{images:[],pagination:null,loading:o}})()),[u,d]=t(c.current.images),[b,m]=t(c.current.loading),[h,p]=t(null),[f,g]=t(c.current.pagination),[v,y]=t(0),[w,x]=t(0);n(()=>{if(!o)return void m(!1);const e=`${s}`,t=de.get(e),n=Date.now();if(t&&n-t.timestamp<be)return d(t.data),g(t.pagination||null),void m(!1);m(!0);let l=!0;return(async()=>{if(v>=3)l&&(p("Error de autenticación: Verifica tus credenciales API"),m(!1));else try{const t=await ie(i);if(!l)return;const r=t.result||t.data||[],a=t.pagination||null;d(r),g(a),p(null),y(0),de.set(e,{data:r,pagination:a,timestamp:n}),(()=>{try{const e={};de.forEach((t,n)=>{e[n]=t}),sessionStorage.setItem(me,JSON.stringify(e))}catch{}})()}catch(t){l&&(p(t.message),y(e=>e+1))}finally{l&&m(!1)}})(),()=>{l=!1}},[e,a,s,v,o,w]);return{images:u,loading:b,error:h,pagination:f,setImages:d,invalidateCache:()=>{de.clear();try{sessionStorage.removeItem(me)}catch{}},refetch:()=>{de.clear();try{sessionStorage.removeItem(me)}catch{}m(!0),x(e=>e+1)}}}function fe(){const[e,n]=t({}),[l,r]=t({}),[i,o]=t({});return{loadVariants:a(async(t,a=!1)=>{if(t&&!l[t]){if(!a&&e[t])return e[t];r(e=>({...e,[t]:!0})),o(e=>({...e,[t]:null}));try{const e=await ce(t),l=e?.result||[];return n(e=>({...e,[t]:l})),l}catch(i){return console.error("Error loading variants:",i),o(e=>({...e,[t]:i.message})),[]}finally{r(e=>({...e,[t]:!1}))}}},[e,l]),getVariants:a(t=>e[t]||[],[e]),isLoading:a(e=>l[e]||!1,[l]),getError:a(e=>i[e]||null,[i]),clearVariants:a(e=>{n(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})},[]),refreshVariants:a(async e=>{if(e){r(t=>({...t,[e]:!0})),o(t=>({...t,[e]:null}));try{const t=await ce(e),l=t?.result||[];return n(t=>({...t,[e]:l})),l}catch(t){return console.error("Error refreshing variants:",t),o(n=>({...n,[e]:t.message})),[]}finally{r(t=>({...t,[e]:!1}))}}},[]),removeVariant:a(async(e,t)=>{try{return await async function(e,t){try{return await Y({endpoint:`/assets/${e}/variants/${t}`,method:"DELETE",basePath:ae,useJWT:!0})}catch(n){throw re(n)}}(e,t),n(n=>{const l=n[e]||[];return{...n,[e]:l.filter(e=>e.id!==t)}}),{success:!0}}catch(l){return console.error("Error deleting variant:",l),{success:!1,error:l.message}}},[])}}function ge(e,l=500){const[r,a]=t(e);return n(()=>{const t=setTimeout(()=>{a(e)},l);return()=>{clearTimeout(t)}},[e,l]),r}function ve(){/* @__PURE__ */
|
|
15
15
|
return c("div",{className:"lb:flex lb:items-center lb:justify-center lb:gap-2 lb:py-2 lb:px-4 lb:border-t lb:h-8 lb:border-brand-purple-200 lb:bg-brand-purple-50 lb:rounded-b-md lb:mt-3",style:{background:"linear-gradient(90deg,#001978,#2134f1 50%,#f81bbd 95%)",color:"white"},children:[
|
|
16
16
|
/* @__PURE__ */c("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 48 52",fill:"currentColor",className:"lb:w-5 lb:h-5 lb:text-white","aria-hidden":"true",children:[
|
|
17
17
|
/* @__PURE__ */s("path",{d:"M29.0863 15.2704H24.9419V36.7321H37.5259V33.1048H29.0863V15.2704Z"}),
|
|
18
18
|
/* @__PURE__ */s("path",{d:"M18.1601 33.1048H9.72056V36.7321H22.3045V15.2704H18.1601V33.1048Z"}),
|
|
19
19
|
/* @__PURE__ */s("path",{d:"M44.0063 51.846L3.16483 50.1834C1.35636 50.1834 0 48.5965 0 46.8584V4.99294C0 3.33041 1.65777 1.8946 3.31554 1.81903L44.157 0.1565C46.2669 0.0809304 48 1.74346 48 3.8594V47.8408C48 50.0323 46.1915 51.846 43.9309 51.7704H44.0063V51.846ZM4.89796 46.405L42.9513 47.4629C43.4788 47.4629 44.0063 47.0095 44.0063 46.4805V5.21965C44.0063 4.69066 43.6295 4.31282 43.102 4.31282L4.82261 5.67307C4.14443 5.67307 3.61695 6.27762 3.61695 6.95775V45.1203C3.61695 45.8004 4.14443 46.3294 4.82261 46.405H4.89796Z"})]}),
|
|
20
20
|
/* @__PURE__ */c("span",{className:"lb:text-xs lb:text-neutral-50",children:["Powered by ",
|
|
21
|
-
/* @__PURE__ */s("span",{className:"lb:font-semibold lb:text-white",children:"Limbo"})]})]})}function
|
|
21
|
+
/* @__PURE__ */s("span",{className:"lb:font-semibold lb:text-white",children:"Limbo"})]})]})}function ye({variant:e="info",toast:l=!1,fixed:r=!1,onClose:a,className:i="",children:o,role:u}){const[d,b]=t(!1);if(n(()=>{b(!1)},[o]),d)return null;/* @__PURE__ */
|
|
22
22
|
return c("div",{className:`${l||r?`${r?"lb:fixed lb:top-4 lb:right-4 lb:z-10000":l?"lb:absolute lb:top-5 lb:right-5 lb:w-fit lb:m-4 lb:z-50":""} ${{success:"lb:bg-green-600",danger:"lb:bg-red-500",warning:"lb:bg-yellow-500",info:"lb:bg-blue-500"}[e]||"lb:bg-gray-600"} lb:text-white lb:px-5 lb:py-3 lb:rounded-lg lb:shadow-lg lb:transition-all lb:duration-300 lb:animate-fade-in`:`limbo-alert limbo-alert-${e}`} lb:pr-8 ${i}`,role:u||"alert",children:[o,
|
|
23
|
-
/* @__PURE__ */s("button",{type:"button",onClick:e=>{e.stopPropagation(),a?a():b(!0)},className:"lb:absolute lb:top-1/2 lb:-translate-y-1/2 lb:right-2 lb:p-1 lb:rounded-full lb:opacity-60 lb:hover:opacity-100 lb:transition-opacity lb:cursor-pointer","aria-label":"Cerrar",children:/* @__PURE__ */s("span",{className:"icon icon-close-small-white icon--sm","aria-hidden":"true"})})]})}"undefined"!=typeof window&&window.addEventListener("pageshow",e=>{e.persisted&&
|
|
23
|
+
/* @__PURE__ */s("button",{type:"button",onClick:e=>{e.stopPropagation(),a?a():b(!0)},className:"lb:absolute lb:top-1/2 lb:-translate-y-1/2 lb:right-2 lb:p-1 lb:rounded-full lb:opacity-60 lb:hover:opacity-100 lb:transition-opacity lb:cursor-pointer","aria-label":"Cerrar",children:/* @__PURE__ */s("span",{className:"icon icon-close-small-white icon--sm","aria-hidden":"true"})})]})}"undefined"!=typeof window&&window.addEventListener("pageshow",e=>{e.persisted&&he()});const we=/* @__PURE__ */new Map,xe=/* @__PURE__ */new Map,ke=18e5;if("undefined"!=typeof document){const e=18e5;let t=null;document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState?t=Date.now():"visible"===document.visibilityState&&null!==t&&(Date.now()-t>e&&(we.forEach(({blobUrl:e})=>{try{URL.revokeObjectURL(e)}catch{}}),we.clear(),xe.clear()),t=null)}),window.addEventListener("pageshow",e=>{e.persisted&&(we.forEach(({blobUrl:e})=>{try{URL.revokeObjectURL(e)}catch{}}),we.clear(),xe.clear())})}const Ce=async(e,{bypassHttpCache:t=!1}={})=>{if(!e)return Promise.reject(new Error("No URL provided"));const n=we.get(e);if(n&&Date.now()-n.timestamp<ke)return n.blobUrl;if(xe.has(e))return xe.get(e);const l=(async()=>{try{let l,r,a=0;const i=t?{cache:"reload"}:{};for(;a<2;)try{if(l=await fetch(e,i),!l.ok)throw new Error(`Failed to fetch image: ${l.status}`);break}catch(n){if(r=n,a+=1,a>=2)throw r}const o=await l.blob(),s=URL.createObjectURL(o);return we.set(e,{blobUrl:s,timestamp:Date.now(),size:o.size}),s}finally{xe.delete(e)}})();return xe.set(e,l),l},Se=e=>{const t=we.get(e);return t&&Date.now()-t.timestamp<ke?t.blobUrl:e},Ne=e=>{const t=we.get(e);return t&&Date.now()-t.timestamp<ke},Ee=async(e,t=4)=>{const n=/* @__PURE__ */new Map,l=e.filter(e=>!Ne(e));if(0===l.length)return e.forEach(e=>{n.set(e,Se(e))}),n;const r=[];for(let a=0;a<l.length;a+=t)r.push(l.slice(a,a+t));for(const a of r){(await Promise.allSettled(a.map(async e=>({url:e,blobUrl:await Ce(e)})))).forEach(e=>{"fulfilled"===e.status&&n.set(e.value.url,e.value.blobUrl)})}return n},$e=e=>{if(!e)return;const t=we.get(e);if(t){try{URL.revokeObjectURL(t.blobUrl)}catch{}we.delete(e)}xe.delete(e)},_e=()=>{we.forEach(({blobUrl:e})=>{try{URL.revokeObjectURL(e)}catch{}}),we.clear(),xe.clear()};const ze={DEV:"https://led-dev-limbo-dev.eu.els.local",PROD:"https://limbo.lefebvre.es"};function Te(e,t=!1){if(!e)return"";if(e.startsWith("/files/")){return(t?ze.PROD:ze.DEV)+e}return e}function Ae(e){return"string"!=typeof e?e:e.replace(/"/g,'"').replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/'/g,"'").replace(/'/g,"'")}function Le(e){return!(!e||"string"!=typeof e)&&!e.startsWith("blob:")}function Ie(e,t={}){if(!e)return"";const{prefer:n="crop",isProd:l=!1}=t,r=Ae(e);try{const e=JSON.parse(r),t=()=>{if(e.images&&Array.isArray(e.images))for(const t of e.images)if(t&&Le(t.url))return t.url;return null},a=e.original?.url,i=t();if("crop"===n){if(i)return Te(i,l);if(Le(a))return Te(a,l)}else{if(Le(a))return Te(a,l);if(i)return Te(i,l)}return Le(e.url)?Te(e.url,l):""}catch{if("string"==typeof r){if(r.startsWith("blob:"))return"";if(r.startsWith("/files/"))return Te(r,l);if(r.startsWith("http")||r.startsWith("/"))return r}}return"string"==typeof e&&(e.startsWith("{")||e.startsWith("["))?"":e}function Pe(e,t={}){const{isProd:n=!1}=t;if(!e)return{original:null,images:[],url:""};try{const t=JSON.parse(Ae(e)),l=t.original?{...t.original,url:Te(t.original.url,n)}:null,r=(t.images||[]).map(e=>({...e,url:Te(e.url,n)}));return{original:l,images:r,url:r[0]?.url||l?.url||Te(t.url,n)||""}}catch{return{original:null,images:[],url:Te(e,n)}}}const Me=[{regex:/^php/i,reason:'El nombre no puede empezar por "php"'},{regex:/\.(php\d?|phtml|phar)$/i,reason:"Extensión no permitida (.php)"},{regex:/\.(asp|aspx|ashx|asmx)$/i,reason:"Extensión no permitida (.asp)"},{regex:/\.(jsp|jspx|jspf)$/i,reason:"Extensión no permitida (.jsp)"},{regex:/\.(exe|bat|cmd|sh|ps1|vbs|cgi)$/i,reason:"Extensión ejecutable no permitida"},{regex:/<script/i,reason:"El nombre contiene código no permitido"},{regex:/\.\./,reason:"El nombre contiene rutas relativas no permitidas"}];function De(e){if(!e||"string"!=typeof e)return{valid:!1,error:"El nombre no puede estar vacío"};const t=e.trim();if(0===t.length)return{valid:!1,error:"El nombre no puede estar vacío"};if(t.length>255)return{valid:!1,error:"El nombre es demasiado largo (máx. 255 caracteres)"};for(const{regex:n,reason:l}of Me)if(n.test(t))return{valid:!1,error:l};return{valid:!0}}function Re(e){if(!e||"string"!=typeof e)return"file";let t=e.normalize("NFD").replace(/[\u0300-\u036f]/g,"");return t=t.toLowerCase(),t=t.replace(/[^a-z0-9_]+/g,"-"),t=t.replace(/-+/g,"-").replace(/^-|-$/g,""),t||"file"}function Oe(e,t={}){const{isProd:n=!1}=t;if(!e?.fields)return e;const l=e.fields.map(e=>{if("image"===e.type&&"string"==typeof e.example_value){const t=Ie(e.example_value,{isProd:n});return{...e,example_value:t||e.example_value}}return e});return{...e,fields:l}}function Fe({isOpen:e=!1,onClose:t,title:l="",subtitle:i="",headerActions:o=null,footerHints:u=null,ariaLabel:d="Visor de archivo",children:b}){const m=r(null),h=a(e=>{"Escape"===e.key&&(e.preventDefault(),t?.())},[t]);return n(()=>{if(e)return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[e,h]),n(()=>(document.body.style.overflow=e?"hidden":"",()=>{document.body.style.overflow=""}),[e]),e?/* @__PURE__ */c("div",{className:"lb:fixed lb:inset-0 lb:bg-black/95 lb:z-[10000] lb:flex lb:flex-col",role:"dialog","aria-modal":"true","aria-label":d,children:[
|
|
24
24
|
/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:justify-between lb:px-4 lb:py-3 lb:bg-black/50 lb:backdrop-blur-sm",children:[
|
|
25
25
|
/* @__PURE__ */c("div",{className:"lb:flex-1 lb:min-w-0",children:[l&&/* @__PURE__ */s("h2",{className:"lb:text-white lb:font-medium lb:text-sm lb:truncate",children:l.includes(".")?l.split(".").slice(0,-1).join("."):l}),i&&/* @__PURE__ */s("p",{className:"lb:text-gray-400 lb:text-xs lb:mt-0.5 lb:truncate",children:i})]}),o&&/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:gap-2 lb:mx-4",children:o}),
|
|
26
26
|
/* @__PURE__ */s("button",{type:"button",onClick:t,className:"lb:w-10 lb:h-10 lb:flex lb:items-center lb:justify-center lb:rounded-lg lb:bg-white/10 lb:hover:bg-red-1000/80 lb:text-white lb:transition-colors","aria-label":"Cerrar visor (ESC)",title:"Cerrar (ESC)",children:/* @__PURE__ */s("svg",{className:"lb:w-6 lb:h-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),
|
|
27
|
-
/* @__PURE__ */s("div",{ref:m,className:"lb:flex-1 lb:overflow-hidden lb:flex lb:items-center lb:justify-center",onClick:e=>{e.target===m.current&&t?.()},children:b}),u&&/* @__PURE__ */s("div",{className:"lb:px-4 lb:py-2 lb:bg-black/50 lb:backdrop-blur-sm lb:text-center",children:/* @__PURE__ */s("p",{className:"lb:text-gray-400 lb:text-xs",children:u})})]}):null}function
|
|
28
|
-
return s(
|
|
27
|
+
/* @__PURE__ */s("div",{ref:m,className:"lb:flex-1 lb:overflow-hidden lb:flex lb:items-center lb:justify-center",onClick:e=>{e.target===m.current&&t?.()},children:b}),u&&/* @__PURE__ */s("div",{className:"lb:px-4 lb:py-2 lb:bg-black/50 lb:backdrop-blur-sm lb:text-center",children:/* @__PURE__ */s("p",{className:"lb:text-gray-400 lb:text-xs",children:u})})]}):null}function je({isOpen:e=!1,src:l,title:i="",subtitle:o="",onClose:u}){const[d,b]=t(!1),[m,h]=t(!0),p=r(null);n(()=>{e&&(b(!1),h(!0))},[e]);const f=a(e=>{" "===e.key&&p.current&&(e.preventDefault(),p.current.paused?p.current.play():p.current.pause())},[]);n(()=>{if(e)return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[e,f]);/* @__PURE__ */
|
|
28
|
+
return s(Fe,{isOpen:e,onClose:u,title:i,subtitle:o,ariaLabel:"Visor de video",headerActions:/* @__PURE__ */c("button",{type:"button",onClick:async()=>{if(l)try{const e=await fetch(l,{mode:"cors"});if(!e.ok)throw new Error(`HTTP ${e.status}`);const t=await e.blob(),n=URL.createObjectURL(t),r=document.createElement("a");r.href=n,r.download=i||"video",r.style.display="none",document.body.appendChild(r),r.click(),setTimeout(()=>{URL.revokeObjectURL(n),document.body.removeChild(r)},100)}catch{window.open(l,"_blank")}},className:"lb:flex lb:items-center lb:gap-2 lb:px-3 lb:py-1.5 lb:rounded-lg lb:bg-white/10 lb:hover:bg-white/20 lb:text-white lb:text-sm lb:transition-colors","aria-label":"Descargar video",title:"Descargar video",children:[
|
|
29
29
|
/* @__PURE__ */s("svg",{className:"lb:w-4 lb:h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})}),
|
|
30
30
|
/* @__PURE__ */s("span",{className:"lb:hidden lb:sm:inline",children:"Descargar"})]}),footerHints:/* @__PURE__ */c("span",{children:[
|
|
31
31
|
/* @__PURE__ */c("span",{className:"lb:hidden lb:sm:inline",children:[
|
|
@@ -34,8 +34,8 @@ return s(Pe,{isOpen:e,onClose:u,title:i,subtitle:o,ariaLabel:"Visor de video",he
|
|
|
34
34
|
/* @__PURE__ */s("svg",{className:"lb:w-16 lb:h-16 lb:mx-auto lb:mb-4 lb:text-red-800",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),
|
|
35
35
|
/* @__PURE__ */s("p",{className:"lb:text-lg lb:font-medium",children:"No se puede reproducir el video"}),
|
|
36
36
|
/* @__PURE__ */s("p",{className:"lb:text-gray-400 lb:text-sm lb:mt-2",children:i})]}:{className:"lb:relative lb:w-full lb:max-w-5xl lb:max-h-full lb:flex lb:items-center lb:justify-center lb:px-4",children:[m&&/* @__PURE__ */s("div",{className:"lb:absolute lb:inset-0 lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("div",{className:"lb:w-12 lb:h-12 lb:border-4 lb:border-white/20 lb:border-t-white lb:rounded-full lb:animate-spin"})}),
|
|
37
|
-
/* @__PURE__ */s("video",{ref:p,src:l,className:"lb:max-w-full lb:max-h-[calc(100vh-140px)] lb:h-full lb:w-full lb:rounded-lg",controls:!0,autoPlay:!0,preload:"metadata",onCanPlay:()=>h(!1),onError:()=>{b(!0),h(!1)},children:"Tu navegador no soporta la reproduccion de video."})]})})}function
|
|
38
|
-
return s(
|
|
37
|
+
/* @__PURE__ */s("video",{ref:p,src:l,className:"lb:max-w-full lb:max-h-[calc(100vh-140px)] lb:h-full lb:w-full lb:rounded-lg",controls:!0,autoPlay:!0,preload:"metadata",onCanPlay:()=>h(!1),onError:()=>{b(!0),h(!1)},children:"Tu navegador no soporta la reproduccion de video."})]})})}function Ue({isOpen:e=!1,src:l,title:i="",subtitle:o="",onClose:u}){const[d,b]=t(!1),[m,h]=t(!1),[p,f]=t(0),[g,v]=t(0),y=r(null);n(()=>{e&&(h(!1),b(!1),f(0),v(0))},[e]);const w=a(()=>{y.current&&(y.current.paused?y.current.play():y.current.pause())},[]),x=a(e=>{" "===e.key&&(e.preventDefault(),w())},[w]);n(()=>{if(e)return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[e,x]);const k=e=>{if(!e||isNaN(e))return"0:00";return`${Math.floor(e/60)}:${Math.floor(e%60).toString().padStart(2,"0")}`};/* @__PURE__ */
|
|
38
|
+
return s(Fe,{isOpen:e,onClose:u,title:i,subtitle:o,ariaLabel:"Visor de audio",headerActions:/* @__PURE__ */c("button",{type:"button",onClick:async()=>{if(l)try{const e=await fetch(l,{mode:"cors"});if(!e.ok)throw new Error(`HTTP ${e.status}`);const t=await e.blob(),n=URL.createObjectURL(t),r=document.createElement("a");r.href=n,r.download=i||"audio",r.style.display="none",document.body.appendChild(r),r.click(),setTimeout(()=>{URL.revokeObjectURL(n),document.body.removeChild(r)},100)}catch{window.open(l,"_blank")}},className:"lb:flex lb:items-center lb:gap-2 lb:px-3 lb:py-1.5 lb:rounded-lg lb:bg-white/10 lb:hover:bg-white/20 lb:text-white lb:text-sm lb:transition-colors","aria-label":"Descargar audio",title:"Descargar audio",children:[
|
|
39
39
|
/* @__PURE__ */s("svg",{className:"lb:w-4 lb:h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})}),
|
|
40
40
|
/* @__PURE__ */s("span",{className:"lb:hidden lb:sm:inline",children:"Descargar"})]}),footerHints:/* @__PURE__ */c("span",{children:[
|
|
41
41
|
/* @__PURE__ */c("span",{className:"lb:hidden lb:sm:inline",children:[
|
|
@@ -51,31 +51,31 @@ return s(Pe,{isOpen:e,onClose:u,title:i,subtitle:o,ariaLabel:"Visor de audio",he
|
|
|
51
51
|
/* @__PURE__ */s("span",{className:"lb:font-mono lb:min-w-[3ch] lb:text-right",children:k(g)}),
|
|
52
52
|
/* @__PURE__ */s("div",{className:"lb:w-64 lb:h-2 lb:bg-white/20 lb:rounded-full lb:cursor-pointer lb:relative",onClick:e=>{if(!y.current||!p)return;const t=e.currentTarget.getBoundingClientRect(),n=(e.clientX-t.left)/t.width;y.current.currentTime=n*p},role:"slider","aria-label":"Progreso de audio","aria-valuenow":g,"aria-valuemin":0,"aria-valuemax":p,tabIndex:0,children:/* @__PURE__ */s("div",{className:"lb:h-full lb:bg-purple-500 lb:rounded-full lb:transition-all lb:duration-100",style:{width:p>0?g/p*100+"%":"0%"}})}),
|
|
53
53
|
/* @__PURE__ */s("span",{className:"lb:font-mono lb:min-w-[3ch] lb:text-gray-400",children:k(p)})]}),
|
|
54
|
-
/* @__PURE__ */s("audio",{ref:y,src:l,onPlay:()=>b(!0),onPause:()=>b(!1),onTimeUpdate:()=>v(y.current?.currentTime||0),onLoadedMetadata:()=>f(y.current?.duration||0),onEnded:()=>{b(!1),v(0)},onError:()=>h(!0),preload:"metadata"})]})})}function
|
|
55
|
-
return s(
|
|
54
|
+
/* @__PURE__ */s("audio",{ref:y,src:l,onPlay:()=>b(!0),onPause:()=>b(!1),onTimeUpdate:()=>v(y.current?.currentTime||0),onLoadedMetadata:()=>f(y.current?.duration||0),onEnded:()=>{b(!1),v(0)},onError:()=>h(!0),preload:"metadata"})]})})}function Be({isOpen:e=!1,src:l,title:a="",subtitle:i="",onClose:o}){const[u,d]=t(!0),[b,m]=t(!1),[h,p]=t(null),f=r(null);n(()=>{if(!e||!l)return;let t=!1;return d(!0),m(!1),fetch(l).then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.blob()}).then(e=>{if(t)return;f.current&&URL.revokeObjectURL(f.current);const n=URL.createObjectURL(e);f.current=n,p(n)}).catch(()=>{t||(m(!0),d(!1))}),()=>{t=!0}},[l,e]),n(()=>()=>{f.current&&(URL.revokeObjectURL(f.current),f.current=null)},[]);const g=()=>{if(!l)return;const e=document.createElement("a");e.href=l,e.download=a||"document.pdf",e.target="_blank",document.body.appendChild(e),e.click(),document.body.removeChild(e)};/* @__PURE__ */
|
|
55
|
+
return s(Fe,{isOpen:e,onClose:o,title:a,subtitle:i,ariaLabel:"Visor de PDF",headerActions:/* @__PURE__ */c("button",{type:"button",onClick:g,className:"lb:flex lb:items-center lb:gap-2 lb:px-3 lb:py-1.5 lb:rounded-lg lb:bg-white/10 lb:hover:bg-white/20 lb:text-white lb:text-sm lb:transition-colors","aria-label":"Abrir PDF en nueva pestaña",title:"Abrir PDF en nueva pestaña",children:[
|
|
56
56
|
/* @__PURE__ */s("span",{className:"icon icon-arrow-left-white lb:rotate-40 lb:me-0 lb:pe-0 icon--sm"}),
|
|
57
57
|
/* @__PURE__ */s("span",{className:"lb:hidden lb:sm:inline",children:"Abrir en nueva pestaña"})]}),footerHints:/* @__PURE__ */c("span",{children:[
|
|
58
58
|
/* @__PURE__ */s("kbd",{className:"lb:px-1.5 lb:py-0.5 lb:bg-white/10 lb:rounded lb:text-white",children:"ESC"})," ","cerrar"]}),children:/* @__PURE__ */c("div",b?{className:"lb:text-center lb:text-white",children:[
|
|
59
59
|
/* @__PURE__ */s("svg",{className:"lb:w-16 lb:h-16 lb:mx-auto lb:mb-4 lb:text-red-800",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),
|
|
60
60
|
/* @__PURE__ */s("p",{className:"lb:text-lg lb:font-medium",children:"No se puede mostrar el PDF"}),
|
|
61
61
|
/* @__PURE__ */s("p",{className:"lb:text-gray-400 lb:text-sm lb:mt-2",children:a}),
|
|
62
|
-
/* @__PURE__ */s("button",{type:"button",onClick:g,className:"lb:mt-4 lb:px-6 lb:py-2.5 lb:bg-white lb:text-gray-900 lb:rounded-lg lb:font-medium lb:text-sm lb:hover:bg-gray-100 lb:transition-colors",children:"Descargar PDF"})]}:{className:"lb:relative lb:w-full lb:h-full lb:px-4 lb:py-2",children:[u&&/* @__PURE__ */s("div",{className:"lb:absolute lb:inset-0 lb:flex lb:items-center lb:justify-center lb:z-10",children:/* @__PURE__ */s("div",{className:"lb:w-12 lb:h-12 lb:border-4 lb:border-white/20 lb:border-t-white lb:rounded-full lb:animate-spin"})}),h&&/* @__PURE__ */s("iframe",{src:h,title:a||"PDF Viewer",className:"lb:w-full lb:h-full lb:rounded-lg lb:bg-white",onLoad:()=>d(!1),onError:()=>{m(!0),d(!1)}})]})})}const
|
|
62
|
+
/* @__PURE__ */s("button",{type:"button",onClick:g,className:"lb:mt-4 lb:px-6 lb:py-2.5 lb:bg-white lb:text-gray-900 lb:rounded-lg lb:font-medium lb:text-sm lb:hover:bg-gray-100 lb:transition-colors",children:"Descargar PDF"})]}:{className:"lb:relative lb:w-full lb:h-full lb:px-4 lb:py-2",children:[u&&/* @__PURE__ */s("div",{className:"lb:absolute lb:inset-0 lb:flex lb:items-center lb:justify-center lb:z-10",children:/* @__PURE__ */s("div",{className:"lb:w-12 lb:h-12 lb:border-4 lb:border-white/20 lb:border-t-white lb:rounded-full lb:animate-spin"})}),h&&/* @__PURE__ */s("iframe",{src:h,title:a||"PDF Viewer",className:"lb:w-full lb:h-full lb:rounded-lg lb:bg-white",onLoad:()=>d(!1),onError:()=>{m(!0),d(!1)}})]})})}const We={"application/pdf":{symbol:"icon-doc-pdf",label:"PDF",color:"#dc2626"},"application/msword":{symbol:"icon-doc-word",label:"DOC",color:"#2563eb"},"application/vnd.openxmlformats-officedocument.wordprocessingml.document":{symbol:"icon-doc-word",label:"DOCX",color:"#2563eb"},"application/vnd.ms-excel":{symbol:"icon-doc-xls",label:"XLS",color:"#16a34a"},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":{symbol:"icon-doc-xls",label:"XLSX",color:"#16a34a"},"application/vnd.ms-powerpoint":{symbol:"icon-doc-ppt",label:"PPT",color:"#ea580c"},"application/vnd.openxmlformats-officedocument.presentationml.presentation":{symbol:"icon-doc-ppt",label:"PPTX",color:"#ea580c"},"text/plain":{symbol:"icon-doc-text",label:"TXT",color:"#6b7280"},"text/csv":{symbol:"icon-doc-report",label:"CSV",color:"#16a34a"},"audio/mp3":{symbol:"icon-support-person",label:"MP3",color:"#0891b2"},"audio/mpeg":{symbol:"icon-support-person",label:"MP3",color:"#0891b2"},"audio/wav":{symbol:"icon-support-person",label:"WAV",color:"#0891b2"},"audio/ogg":{symbol:"icon-support-person",label:"OGG",color:"#0891b2"},"video/mp4":{symbol:"icon-video",label:"MP4",color:"#7c3aed"},"video/x-msvideo":{symbol:"icon-video",label:"AVI",color:"#7c3aed"},"video/x-matroska":{symbol:"icon-video",label:"MKV",color:"#7c3aed"},default:{symbol:"icon-clip",label:"FILE",color:"#6b7280"}},qe={video:{symbol:"🎬",label:"VIDEO",color:"#7c3aed"},audio:{symbol:"🎵",label:"AUDIO",color:"#0891b2"},document:{symbol:"📄",label:"DOC",color:"#6b7280"},image:{symbol:"🖼️",label:"IMG",color:"#0ea5e9"}};function Ve(e,t){return We[e]?We[e]:t&&qe[t]?qe[t]:e?.startsWith("video/")?qe.video:e?.startsWith("audio/")?qe.audio:e?.startsWith("image/")?qe.image:We.default}function He(e){if(!e||0===e)return"0 Bytes";const t=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,t)*100)/100+" "+["Bytes","KB","MB","GB"][t]}function Ke({file:e,mimeType:t,category:n}){const l=Ve(t,n),r=e?.name||"archivo",a=He(e?.size);/* @__PURE__ */
|
|
63
63
|
return c("div",{className:"lb:flex lb:flex-col lb:items-center lb:justify-center lb:min-h-50",children:[
|
|
64
64
|
/* @__PURE__ */s("div",{className:"lb:w-24 lb:h-24 lb:flex lb:items-center lb:justify-center lb:bg-gray-100 lb:rounded-xl lb:mb-4",children:/* @__PURE__ */s("span",{className:`icon ${l.symbol} lb:h-[55%] lb:w-[55%] lb:max-h-50 lb:max-w-50`,"aria-hidden":"true"})}),
|
|
65
65
|
/* @__PURE__ */s("p",{className:"lb:text-sm lb:font-medium lb:text-gray-800 lb:text-center lb:max-w-full lb:truncate lb:px-4",children:r}),
|
|
66
66
|
/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-2 lb:mt-3",children:[
|
|
67
67
|
/* @__PURE__ */s("span",{className:"lb:text-xs lb:text-gray-500",children:a}),
|
|
68
|
-
/* @__PURE__ */s("span",{className:"lb:text-xs lb:font-bold lb:uppercase lb:px-2 lb:py-0.5 lb:rounded",style:{backgroundColor:l.color,color:"white"},children:l.label})]})]})}function
|
|
69
|
-
return s(
|
|
68
|
+
/* @__PURE__ */s("span",{className:"lb:text-xs lb:font-bold lb:uppercase lb:px-2 lb:py-0.5 lb:rounded",style:{backgroundColor:l.color,color:"white"},children:l.label})]})]})}function Ge({isOpen:e=!1,src:t,title:n="",subtitle:l="",mimeType:r="",fileSize:a=0,onClose:i}){const o=Ve(r);/* @__PURE__ */
|
|
69
|
+
return s(Fe,{isOpen:e,onClose:i,title:n,subtitle:l,ariaLabel:"Visor de documento",footerHints:/* @__PURE__ */c("span",{children:[
|
|
70
70
|
/* @__PURE__ */s("kbd",{className:"lb:px-1.5 lb:py-0.5 lb:bg-white/10 lb:rounded lb:text-white",children:"ESC"})," ","cerrar"]}),children:/* @__PURE__ */c("div",{className:"lb:flex lb:flex-col lb:items-center lb:gap-6 lb:text-center lb:px-4",children:[
|
|
71
71
|
/* @__PURE__ */s("div",{className:"lb:w-32 lb:h-32 lb:flex lb:items-center lb:justify-center lb:bg-white/5 lb:rounded-2xl lb:border lb:border-white/10",children:/* @__PURE__ */s("span",{className:`icon ${o.symbol}-white lb:min-w-16 lb:min-h-16`,"aria-hidden":"true"})}),
|
|
72
72
|
/* @__PURE__ */s("span",{className:"lb:text-sm lb:font-bold lb:uppercase lb:px-4 lb:py-1.5 lb:rounded-full",style:{backgroundColor:o.color,color:"white"},children:o.label}),
|
|
73
73
|
/* @__PURE__ */c("div",{children:[
|
|
74
|
-
/* @__PURE__ */s("p",{className:"lb:text-white lb:font-medium lb:text-lg lb:max-w-md lb:truncate",children:n}),a>0&&/* @__PURE__ */s("p",{className:"lb:text-gray-400 lb:text-sm lb:mt-1",children:
|
|
74
|
+
/* @__PURE__ */s("p",{className:"lb:text-white lb:font-medium lb:text-lg lb:max-w-md lb:truncate",children:n}),a>0&&/* @__PURE__ */s("p",{className:"lb:text-gray-400 lb:text-sm lb:mt-1",children:He(a)})]}),
|
|
75
75
|
/* @__PURE__ */s("p",{className:"lb:text-gray-500 lb:text-sm",children:"Este tipo de archivo no se puede previsualizar"}),
|
|
76
76
|
/* @__PURE__ */c("button",{type:"button",onClick:async()=>{if(t)try{const e=await fetch(t,{mode:"cors"});if(!e.ok)throw new Error(`HTTP ${e.status}`);const l=await e.blob(),r=URL.createObjectURL(l),a=document.createElement("a");a.href=r,a.download=n||"document",a.style.display="none",document.body.appendChild(a),a.click(),setTimeout(()=>{URL.revokeObjectURL(r),document.body.removeChild(a)},100)}catch{window.open(t,"_blank")}},className:"lb:flex lb:items-center lb:gap-2 lb:px-8 lb:py-3 lb:bg-white lb:text-gray-900 lb:rounded-lg lb:font-medium lb:text-sm lb:hover:bg-gray-100 lb:transition-colors lb:shadow-lg","aria-label":"Descargar archivo",children:[
|
|
77
|
-
/* @__PURE__ */s("svg",{className:"lb:w-5 lb:h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})}),"Descargar archivo"]})]})})}const
|
|
78
|
-
return s(
|
|
77
|
+
/* @__PURE__ */s("svg",{className:"lb:w-5 lb:h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})}),"Descargar archivo"]})]})})}const Qe=2097152;function Xe({isOpen:e=!1,src:l,title:r="",subtitle:a="",mimeType:i="",fileSize:o=0,onClose:u}){const[d,b]=t(!0),[m,h]=t(!1),[p,f]=t(""),[g,v]=t(!1);n(()=>{if(!e||!l)return;let t=!1;return b(!0),h(!1),f(""),v(!1),fetch(l).then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.blob()}).then(e=>{if(t)return;const n=e.size>Qe?e.slice(0,Qe):e;return e.size>Qe&&v(!0),n.text()}).then(e=>{if(!t){if("application/json"===i||r.endsWith(".json"))try{const t=JSON.parse(e);e=JSON.stringify(t,null,2)}catch{}f(e),b(!1)}}).catch(()=>{t||(h(!0),b(!1))}),()=>{t=!0}},[l,e,i,r]);const y=async()=>{if(l)try{const e=await fetch(l,{mode:"cors"});if(!e.ok)throw new Error(`HTTP ${e.status}`);const t=await e.blob(),n=URL.createObjectURL(t),a=document.createElement("a");a.href=n,a.download=r||"file.txt",a.style.display="none",document.body.appendChild(a),a.click(),setTimeout(()=>{URL.revokeObjectURL(n),document.body.removeChild(a)},100)}catch{window.open(l,"_blank")}},w=p?p.split("\n").length:0;/* @__PURE__ */
|
|
78
|
+
return s(Fe,{isOpen:e,onClose:u,title:r,subtitle:a,ariaLabel:"Visor de texto",headerActions:/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-2",children:[w>0&&/* @__PURE__ */c("span",{className:"lb:text-gray-400 lb:text-xs",children:[w," ",1===w?"linea":"lineas"]}),
|
|
79
79
|
/* @__PURE__ */c("button",{type:"button",onClick:y,className:"lb:flex lb:items-center lb:gap-2 lb:px-3 lb:py-1.5 lb:rounded-lg lb:bg-white/10 lb:hover:bg-white/20 lb:text-white lb:text-sm lb:transition-colors","aria-label":"Descargar archivo",title:"Descargar archivo",children:[
|
|
80
80
|
/* @__PURE__ */s("svg",{className:"lb:w-4 lb:h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})}),
|
|
81
81
|
/* @__PURE__ */s("span",{className:"lb:hidden lb:sm:inline",children:"Descargar"})]})]}),footerHints:/* @__PURE__ */c("span",{children:[
|
|
@@ -86,8 +86,8 @@ return s(Pe,{isOpen:e,onClose:u,title:r,subtitle:a,ariaLabel:"Visor de texto",he
|
|
|
86
86
|
/* @__PURE__ */s("button",{type:"button",onClick:y,className:"lb:mt-4 lb:px-6 lb:py-2.5 lb:bg-white lb:text-gray-900 lb:rounded-lg lb:font-medium lb:text-sm lb:hover:bg-gray-100 lb:transition-colors",children:"Descargar archivo"})]}):d?/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("div",{className:"lb:w-12 lb:h-12 lb:border-4 lb:border-white/20 lb:border-t-white lb:rounded-full lb:animate-spin"})}):/* @__PURE__ */c("div",{className:"lb:relative lb:w-full lb:h-full lb:px-4 lb:py-2 lb:overflow-hidden lb:flex lb:flex-col",children:[g&&/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-2 lb:px-4 lb:py-2 lb:bg-yellow-900/50 lb:border lb:border-yellow-700/50 lb:rounded-lg lb:mb-2 lb:shrink-0",children:[
|
|
87
87
|
/* @__PURE__ */s("svg",{className:"lb:w-4 lb:h-4 lb:text-yellow-400 lb:shrink-0",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01"})}),
|
|
88
88
|
/* @__PURE__ */s("span",{className:"lb:text-yellow-300 lb:text-xs",children:"Archivo truncado (mostrando primeros 2MB). Descarga el archivo completo para ver todo el contenido."})]}),
|
|
89
|
-
/* @__PURE__ */s("div",{className:"lb:flex-1 lb:overflow-auto lb:rounded-lg lb:bg-gray-900/80 lb:border lb:border-white/10",children:/* @__PURE__ */s("pre",{className:"lb:p-4 lb:text-sm lb:text-gray-200 lb:font-mono lb:whitespace-pre-wrap lb:break-words lb:leading-relaxed lb:m-0",children:p})})]})})}function
|
|
90
|
-
return s(
|
|
89
|
+
/* @__PURE__ */s("div",{className:"lb:flex-1 lb:overflow-auto lb:rounded-lg lb:bg-gray-900/80 lb:border lb:border-white/10",children:/* @__PURE__ */s("pre",{className:"lb:p-4 lb:text-sm lb:text-gray-200 lb:font-mono lb:whitespace-pre-wrap lb:break-words lb:leading-relaxed lb:m-0",children:p})})]})})}function Ye({src:e,alt:l="Imagen",title:i="",subtitle:o="",onClose:d,isOpen:b=!1}){const[m,h]=t(1),[p,f]=t({x:0,y:0}),[g,v]=t(!1),[y,w]=t(!1),[x,k]=t({x:0,y:0}),[C,S]=t(!1),[N,E]=t(!1),$=r(null),_=r(null);n(()=>{b&&(h(1),f({x:0,y:0}),S(!1),E(!1))},[b]);const z=a(()=>{h(e=>Math.min(e+.25,5)),f({x:0,y:0})},[]),T=a(()=>{h(e=>Math.max(e-.25,.25)),f({x:0,y:0})},[]),A=a(()=>{h(1),f({x:0,y:0})},[]),L=a(()=>{h(1),f({x:0,y:0})},[]),I=a(e=>{if((e.ctrlKey||e.metaKey)&&("+"===e.key||"="===e.key))return e.preventDefault(),void z();if((e.ctrlKey||e.metaKey)&&"-"===e.key)return e.preventDefault(),void T();if((e.ctrlKey||e.metaKey)&&"0"===e.key)return e.preventDefault(),void A();if(m>1){const t=50;switch(e.key){case"ArrowUp":e.preventDefault(),f(e=>({...e,y:e.y+t}));break;case"ArrowDown":e.preventDefault(),f(e=>({...e,y:e.y-t}));break;case"ArrowLeft":e.preventDefault(),f(e=>({...e,x:e.x+t}));break;case"ArrowRight":e.preventDefault(),f(e=>({...e,x:e.x-t}))}}},[z,T,A,m]),P=a(e=>{(e.ctrlKey||e.metaKey)&&(e.preventDefault(),e.deltaY<0?z():T())},[z,T]),M=a(e=>{m>1&&0===e.button&&(e.preventDefault(),v(!0),w(!1),k({x:e.clientX-p.x,y:e.clientY-p.y}))},[m,p]),D=a(e=>{g&&(w(!0),f({x:e.clientX-x.x,y:e.clientY-x.y}))},[g,x]),R=a(()=>{v(!1)},[]),O=a(e=>{e.stopPropagation(),1!==m||y||(h(2),f({x:0,y:0})),w(!1)},[m,y]),F=a(e=>{e.stopPropagation(),1===m?(h(2),f({x:0,y:0})):A()},[m,A]);n(()=>{if(!b)return;document.addEventListener("keydown",I),document.addEventListener("mouseup",R),document.addEventListener("mousemove",D);const e=e=>{!e.ctrlKey&&!e.metaKey||"+"!==e.key&&"-"!==e.key&&"="!==e.key&&"0"!==e.key||e.preventDefault()};return document.addEventListener("keydown",e),()=>{document.removeEventListener("keydown",I),document.removeEventListener("mouseup",R),document.removeEventListener("mousemove",D),document.removeEventListener("keydown",e)}},[b,I,R,D]);const j=Math.round(100*m);/* @__PURE__ */
|
|
90
|
+
return s(Fe,{isOpen:b,onClose:d,title:i,subtitle:o,ariaLabel:"Visor de imagen",headerActions:/* @__PURE__ */c(u,{children:[
|
|
91
91
|
/* @__PURE__ */s("button",{type:"button",onClick:T,disabled:m<=.25,className:"lb:w-8 lb:h-8 lb:flex lb:items-center lb:justify-center lb:rounded-lg lb:bg-white/10 lb:hover:bg-white/20 lb:text-white lb:disabled:opacity-30 lb:disabled:cursor-not-allowed lb:transition-colors","aria-label":"Reducir zoom",title:"Reducir zoom (Ctrl -)",children:/* @__PURE__ */s("svg",{className:"lb:w-5 lb:h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20 12H4"})})}),
|
|
92
92
|
/* @__PURE__ */c("div",{className:"lb:w-20 lb:text-center lb:text-white lb:text-sm lb:font-medium lb:bg-white/10 lb:rounded-lg lb:px-2 lb:py-1.5 lb:cursor-pointer lb:hover:bg-white/20 lb:transition-colors",onClick:A,title:"Click para restablecer zoom",role:"button",tabIndex:0,onKeyDown:e=>"Enter"===e.key&&A(),children:[j,"%"]}),
|
|
93
93
|
/* @__PURE__ */s("button",{type:"button",onClick:z,disabled:m>=5,className:"lb:w-8 lb:h-8 lb:flex lb:items-center lb:justify-center lb:rounded-lg lb:bg-white/10 lb:hover:bg-white/20 lb:text-white lb:disabled:opacity-30 lb:disabled:cursor-not-allowed lb:transition-colors","aria-label":"Aumentar zoom",title:"Aumentar zoom (Ctrl +)",children:/* @__PURE__ */s("svg",{className:"lb:w-5 lb:h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}),
|
|
@@ -102,7 +102,7 @@ return s(Pe,{isOpen:b,onClose:d,title:i,subtitle:o,ariaLabel:"Visor de imagen",h
|
|
|
102
102
|
/* @__PURE__ */s("svg",{className:"lb:w-16 lb:h-16 lb:mx-auto lb:mb-4 lb:text-red-800",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),
|
|
103
103
|
/* @__PURE__ */s("p",{className:"lb:text-lg lb:font-medium",children:"Error al cargar la imagen"}),
|
|
104
104
|
/* @__PURE__ */s("p",{className:"lb:text-gray-400 lb:text-sm lb:mt-2",children:"No se pudo cargar la imagen"})]}),
|
|
105
|
-
/* @__PURE__ */s("img",{ref:_,src:e,alt:l,className:"lb:max-w-full lb:max-h-full lb:object-contain lb:transition-opacity lb:duration-200 lb:select-none "+(C?"lb:opacity-100":"lb:opacity-0"),style:{transform:`scale(${m}) translate(${p.x/m}px, ${p.y/m}px)`,transition:g?"none":"transform 0.2s ease-out"},onLoad:()=>S(!0),onError:()=>E(!0),onClick:O,onDoubleClick:F,draggable:!1})]})})}function
|
|
105
|
+
/* @__PURE__ */s("img",{ref:_,src:e,alt:l,className:"lb:max-w-full lb:max-h-full lb:object-contain lb:transition-opacity lb:duration-200 lb:select-none "+(C?"lb:opacity-100":"lb:opacity-0"),style:{transform:`scale(${m}) translate(${p.x/m}px, ${p.y/m}px)`,transition:g?"none":"transform 0.2s ease-out"},onLoad:()=>S(!0),onError:()=>E(!0),onClick:O,onDoubleClick:F,draggable:!1})]})})}function Je({image:l,isOpen:i,onClose:o,onSelect:d,onDelete:b,onCrop:m,onVariantDeleted:h,allowedActions:p={select:!0,download:!0,copy:!0,delete:!0,crop:!0}}){const{loadVariants:f,getVariants:g,isLoading:v,getError:y,removeVariant:w}=fe(),x=window.limboCore?.accessibilityManager,[k,C]=e.useState(null),[S,N]=e.useState(null),[E,$]=t(null),[_,z]=t(null),[T,A]=t({}),[L,I]=t({}),P=(window.limboCore?.config?.getGlobal()||{}).interaction||{allowSelection:!1,allowCropping:!0},M=P.allowSelection&&p.select&&d,D=P.allowCropping&&p.crop&&m,R=p.download,O=p.copy,F=p.delete,[j,U]=e.useState(/* @__PURE__ */new Set),[B,W]=e.useState(/* @__PURE__ */new Set),[q,V]=t({}),[H,K]=t(!1),G=r(null),Q=r(null),X=a(e=>{if("Escape"===e.key){if(E)return;e.preventDefault(),o?.()}if("Tab"===e.key&&G.current){const t=G.current.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'),n=t[0],l=t[t.length-1];e.shiftKey&&document.activeElement===n?(e.preventDefault(),l?.focus()):e.shiftKey||document.activeElement!==l||(e.preventDefault(),n?.focus())}},[o,E]);n(()=>{if(i)return Q.current?.focus(),document.addEventListener("keydown",X),()=>document.removeEventListener("keydown",X)},[i,X]);const Y=e.useMemo(()=>l?.variants||[],[l?.variants]),J=g(l?.id),Z=(J.length>0?J:Y).filter(e=>!B.has(e.id)),ee=v(l?.id),te=y(l?.id);n(()=>{i&&l?.id&&f(l.id,!0)},[i,l?.id]),e.useEffect(()=>{i&&(U(/* @__PURE__ */new Set),W(/* @__PURE__ */new Set),V({}),A({}),I({}))},[i]),e.useEffect(()=>{if(i&&B.size>0&&0===Z.length){const e=setTimeout(()=>{document.dispatchEvent(new CustomEvent("limbo:variantsCleared",{detail:{assetId:l?.id}})),o?.()},1200);return()=>clearTimeout(e)}},[i,B.size,Z.length,l?.id,o]);const ne=Z.map(e=>e.id).join(",");n(()=>{if(!i||!l?.url)return;let e=!1;return(async()=>{const t={},n={},r={},a="original",i=Ne(l.url);if(i?(n[a]=!0,t[a]=!1,r.original=Se(l.url)):(t[a]=!0,n[a]=!1),Z.forEach(e=>{Ne(e.url)?(n[e.id]=!0,t[e.id]=!1,r[e.id]=Se(e.url)):(t[e.id]=!0,n[e.id]=!1)}),A(t),I(n),Object.keys(r).length>0&&V(r),!i){const t=await Ce(l.url);if(e)return;t&&(V(e=>({...e,original:t})),A(e=>({...e,[a]:!1})),I(e=>({...e,[a]:!0})))}if(Z.length>0){const t=Z.filter(e=>!Ne(e.url));if(t.length>0){const n=t.map(e=>e.url),l=await Ee(n,4);if(e)return;const r={},a={},i={};t.forEach((e,t)=>{l[t]&&(r[e.id]=l[t],a[e.id]=!1,i[e.id]=!0)}),Object.keys(r).length>0&&(V(e=>({...e,...r})),A(e=>({...e,...a})),I(e=>({...e,...i})))}}})(),()=>{e=!0}},[i,l?.url,ne]);if(!i)return null;const le=e=>{x?.announce(`Abriendo visor de imagen: ${e.name}`);const t=q[e.id]||Se(e.url);$({src:t,title:e.name||e.filename||"Recorte",subtitle:`${e.width}×${e.height} · ${Math.round((e.file_size||0)/1024)}KB`})},re=()=>{x?.announce(`Abriendo visor de imagen: ${l.filename}`);const e=q.original||Se(l.url);$({src:e,title:l.filename||"Original",subtitle:`${l.width}×${l.height} · ${Math.round((l.file_size||0)/1024)}KB`})},ae=[{...l,isOriginal:!0},...Z.map(e=>({...e,isOriginal:!1}))];/* @__PURE__ */
|
|
106
106
|
return c("div",{className:"lb:fixed lb:inset-0 lb:bg-black/85 lb:flex lb:items-center lb:justify-center lb:z-[1000] lb:p-4",onClick:()=>{E||o?.()},role:"dialog","aria-modal":"true","aria-labelledby":"variants-modal-title","aria-describedby":"variants-modal-description",children:[
|
|
107
107
|
/* @__PURE__ */c("div",{ref:G,className:"lb:relative lb:bg-white lb:rounded-xl lb:max-w-[95vw] lb:max-h-[90vh] lb:overflow-hidden lb:shadow-2xl lb:flex lb:flex-col lb:w-[900px]",onClick:e=>e.stopPropagation(),children:[
|
|
108
108
|
/* @__PURE__ */c("div",{className:"lb:px-5 lb:py-4 lb:border-b lb:border-gray-200 lb:flex lb:justify-between lb:items-center lb:bg-gray-50",children:[
|
|
@@ -119,7 +119,7 @@ return c("div",{className:"lb:fixed lb:inset-0 lb:bg-black/85 lb:flex lb:items-c
|
|
|
119
119
|
/* @__PURE__ */c("p",{className:"lb:text-base lb:font-medium",children:["Error: ",te]}),
|
|
120
120
|
/* @__PURE__ */s("button",{onClick:()=>f(l.id,!0),className:"lb:mt-4 lb:text-sm lb:px-5 lb:py-2.5 lb:rounded-lg lb:bg-brand-blue-800 lb:text-white lb:hover:bg-brand-blue-1000 lb:focus:outline-none lb:focus:ring-2 lb:focus:ring-brand-blue-400 lb:focus:ring-offset-2",children:"Reintentar"})]}):0===Z.length?/* @__PURE__ */c("div",{className:"lb:text-center lb:py-16 lb:text-gray-500",children:[
|
|
121
121
|
/* @__PURE__ */s("svg",{className:"lb:w-12 lb:h-12 lb:mx-auto lb:mb-4 lb:text-gray-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})}),
|
|
122
|
-
/* @__PURE__ */s("p",{className:"lb:text-base",children:"No hay recortes disponibles"})]}):/* @__PURE__ */s("div",{className:"lb:grid lb:grid-cols-2 lb:lg:grid-cols-3 lb:gap-5",role:"list","aria-label":"Lista de imágenes",children:ae.map((e,t)=>{const n=e.isOriginal,r=!n&&j.has(e.id);e.url;const a=n?q.original||
|
|
122
|
+
/* @__PURE__ */s("p",{className:"lb:text-base",children:"No hay recortes disponibles"})]}):/* @__PURE__ */s("div",{className:"lb:grid lb:grid-cols-2 lb:lg:grid-cols-3 lb:gap-5",role:"list","aria-label":"Lista de imágenes",children:ae.map((e,t)=>{const n=e.isOriginal,r=!n&&j.has(e.id);e.url;const a=n?q.original||Se(e.url):q[e.id]||Se(e.url),i=n?"Original":e.name||e.filename||`Recorte ${t}`,p=n?l.width:e.width,f=n?l.height:e.height,g=n?l.file_size:e.file_size||0,v=n?"original":e.id,y=T[v]&&!r,k=L[v];/* @__PURE__ */
|
|
123
123
|
return c("article",{role:"listitem","aria-label":`${i} - ${p}×${f} píxeles`,className:`lb:rounded-xl lb:overflow-hidden lb:transition-all lb:shadow-sm lb:hover:shadow-lg ${n?"lb:ring-2 lb:ring-brand-blue-800 lb:ring-offset-2 lb:bg-white":"lb:border lb:border-gray-200 lb:bg-white lb:hover:border-brand-blue-400"} lb:focus-within:ring-2 lb:focus-within:ring-brand-blue-400`,children:[
|
|
124
124
|
/* @__PURE__ */c("button",{type:"button",title:M?"Click para seleccionar":"Click para ampliar con zoom",className:"lb:relative lb:w-full lb:cursor-pointer lb:aspect-square lb:flex lb:items-center lb:justify-center lb:overflow-hidden lb:bg-gray-100 lb:focus:outline-none lb:group",onClick:r?void 0:()=>{M?n?(d?.(l),o?.()):(e=>{const t={id:e.id,filename:`${l.filename}_${e.name}`,url:e.url,width:e.width,height:e.height,mime_type:`image/${e.format}`,file_size:e.file_size,upload_date:e.created_at,processing_status:"completed",is_variant:!0,parent_asset_id:l.id,variant_info:e};x?.announce(`Recorte seleccionado: ${e.name}`),d?.(t),o?.()})(e):n?re():le(e)},"aria-label":M?`Seleccionar ${i}`:`Ver ${i} en tamaño completo con zoom`,disabled:r,children:[y&&!r&&/* @__PURE__ */s("div",{className:"lb:w-full lb:aspect-square lb:rounded lb:bg-neutral-gray-200 lb:animate-pulse lb:flex lb:items-center lb:justify-center lb:absolute lb:inset-0 lb:z-10",children:/* @__PURE__ */s("span",{className:"icon icon-spinner lb:w-8 lb:h-8 lb:animate-spin"})}),r?/* @__PURE__ */c("div",{className:"lb:text-center lb:text-gray-400",children:[
|
|
125
125
|
/* @__PURE__ */s("svg",{className:"lb:w-10 lb:h-10 lb:mx-auto lb:mb-2",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),
|
|
@@ -132,8 +132,8 @@ return c("article",{role:"listitem","aria-label":`${i} - ${p}×${f} píxeles`,cl
|
|
|
132
132
|
/* @__PURE__ */s("h3",{className:"lb:text-sm lb:font-semibold lb:text-gray-900 lb:truncate lb:mb-2",title:i,children:i}),
|
|
133
133
|
/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:justify-between",children:[
|
|
134
134
|
/* @__PURE__ */c("span",{className:"lb:text-xs lb:text-gray-500 lb:font-medium",children:[p,"×",f," ·"," ",Math.round(g/1024),"KB"]}),
|
|
135
|
-
/* @__PURE__ */c("div",{className:"lb:flex lb:gap-2",role:"group","aria-label":`Acciones para ${i}`,children:[n&&D&&/* @__PURE__ */s("button",{type:"button",className:"lb:w-8 lb:h-8 lb:rounded-lg lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:cursor-pointer lb:text-white lb:flex lb:items-center lb:justify-center lb:focus:outline-none lb:focus:ring-2 lb:focus:ring-brand-blue-400 lb:focus:ring-offset-1 lb:transition-colors lb:shadow-sm",onClick:e=>{e.stopPropagation(),m&&(x?.announce(`Abriendo herramienta de recorte para ${l.filename}`),m(l),o?.())},"aria-label":"Crear nuevo recorte",title:"Recortar",children:/* @__PURE__ */s("span",{className:"icon icon-scissors-white icon--sm"})}),O&&/* @__PURE__ */s("button",{type:"button",className:"lb:w-8 lb:h-8 lb:rounded-lg lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:cursor-pointer lb:text-white lb:flex lb:items-center lb:justify-center lb:focus:outline-none lb:focus:ring-2 lb:focus:ring-brand-blue-400 lb:focus:ring-offset-1 lb:transition-colors lb:shadow-sm",onClick:t=>{t.stopPropagation();(async(e,t,n)=>{try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t);else{const e=document.createElement("textarea");e.value=t,e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.focus(),e.select(),document.execCommand("copy"),document.body.removeChild(e)}z(e),x?.announce(`URL de ${n} copiada al portapapeles`),setTimeout(()=>z(null),2e3)}catch(l){console.error("Error al copiar URL:",l),x?.announceError(`Error al copiar URL de ${n}. Inténtalo de nuevo.`)}})(n?"original":e.id,n?l.url||l.path:e.url,i)},"aria-label":_===(n?"original":e.id)?"¡Copiado!":`Copiar URL de ${i}`,title:_===(n?"original":e.id)?"¡Copiado!":"Copiar URL",children:/* @__PURE__ */s("span",{className:`icon ${_===(n?"original":e.id)?"icon-copied-white":"icon-copy-white"} icon--sm`})}),R&&/* @__PURE__ */s("button",{type:"button",className:"lb:w-8 lb:h-8 lb:rounded-lg lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:cursor-pointer lb:text-white lb:flex lb:items-center lb:justify-center lb:focus:outline-none lb:focus:ring-2 lb:focus:ring-brand-blue-400 lb:focus:ring-offset-1 lb:transition-colors lb:shadow-sm",onClick:t=>{t.stopPropagation(),n?(async()=>{const{downloadImage:e}=await Promise.resolve().then(()
|
|
136
|
-
/* @__PURE__ */s(
|
|
135
|
+
/* @__PURE__ */c("div",{className:"lb:flex lb:gap-2",role:"group","aria-label":`Acciones para ${i}`,children:[n&&D&&/* @__PURE__ */s("button",{type:"button",className:"lb:w-8 lb:h-8 lb:rounded-lg lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:cursor-pointer lb:text-white lb:flex lb:items-center lb:justify-center lb:focus:outline-none lb:focus:ring-2 lb:focus:ring-brand-blue-400 lb:focus:ring-offset-1 lb:transition-colors lb:shadow-sm",onClick:e=>{e.stopPropagation(),m&&(x?.announce(`Abriendo herramienta de recorte para ${l.filename}`),m(l),o?.())},"aria-label":"Crear nuevo recorte",title:"Recortar",children:/* @__PURE__ */s("span",{className:"icon icon-scissors-white icon--sm"})}),O&&/* @__PURE__ */s("button",{type:"button",className:"lb:w-8 lb:h-8 lb:rounded-lg lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:cursor-pointer lb:text-white lb:flex lb:items-center lb:justify-center lb:focus:outline-none lb:focus:ring-2 lb:focus:ring-brand-blue-400 lb:focus:ring-offset-1 lb:transition-colors lb:shadow-sm",onClick:t=>{t.stopPropagation();(async(e,t,n)=>{try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t);else{const e=document.createElement("textarea");e.value=t,e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.focus(),e.select(),document.execCommand("copy"),document.body.removeChild(e)}z(e),x?.announce(`URL de ${n} copiada al portapapeles`),setTimeout(()=>z(null),2e3)}catch(l){console.error("Error al copiar URL:",l),x?.announceError(`Error al copiar URL de ${n}. Inténtalo de nuevo.`)}})(n?"original":e.id,n?l.url||l.path:e.url,i)},"aria-label":_===(n?"original":e.id)?"¡Copiado!":`Copiar URL de ${i}`,title:_===(n?"original":e.id)?"¡Copiado!":"Copiar URL",children:/* @__PURE__ */s("span",{className:`icon ${_===(n?"original":e.id)?"icon-copied-white":"icon-copy-white"} icon--sm`})}),R&&/* @__PURE__ */s("button",{type:"button",className:"lb:w-8 lb:h-8 lb:rounded-lg lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:cursor-pointer lb:text-white lb:flex lb:items-center lb:justify-center lb:focus:outline-none lb:focus:ring-2 lb:focus:ring-brand-blue-400 lb:focus:ring-offset-1 lb:transition-colors lb:shadow-sm",onClick:t=>{t.stopPropagation(),n?(async()=>{const{downloadImage:e}=await Promise.resolve().then(()=>Ll);await e(l.url||l.path,l.filename||"limbo-image",{originalFormat:l.format,accessibilityManager:x})})():(async e=>{const{downloadImage:t}=await Promise.resolve().then(()=>Ll);await t(e.url,e.name||"limbo-variant",{originalFormat:e.format||e.output_format,accessibilityManager:x})})(e)},"aria-label":`Descargar ${i}`,title:"Descargar",children:/* @__PURE__ */s("span",{className:"icon icon-download-white icon--sm"})}),F&&(!n||b)&&/* @__PURE__ */s("button",{type:"button",className:"lb:w-8 lb:h-8 lb:rounded-lg lb:bg-red-1000 lb:hover:bg-red-800 lb:cursor-pointer lb:text-white lb:flex lb:items-center lb:justify-center lb:focus:outline-none lb:focus:ring-2 lb:focus:ring-red-800 lb:focus:ring-offset-1 lb:transition-colors lb:shadow-sm",onClick:t=>{t.stopPropagation(),n?(async()=>{if(!b)return;window.confirm(`¿Estás seguro de que deseas eliminar "${l.filename}"? Esta acción también eliminará todos sus recortes.`)&&(x?.announce(`Eliminando imagen ${l.filename}`),await b(l.id),o?.())})():(async e=>{if(window.confirm(`¿Estás seguro de que deseas eliminar el recorte "${e.name||e.filename}"?`)){K(!0),x?.announce(`Eliminando recorte ${e.name||e.filename}`);try{const t=await w(l.id,e.id);t.success?(W(t=>/* @__PURE__ */new Set([...t,e.id])),e.url&&$e(e.url),C("Recorte eliminado correctamente"),N("success"),x?.announce("Recorte eliminado correctamente"),h?.(),document.dispatchEvent(new CustomEvent("limbo:variantDeleted",{detail:{assetId:l?.id,variantId:e.id}})),setTimeout(()=>{C(null),N(null)},3e3)):(C(`Error al eliminar recorte: ${t.error}`),N("error"),x?.announceError(`Error al eliminar recorte: ${t.error}`),setTimeout(()=>{C(null),N(null)},5e3))}finally{K(!1)}}})(e)},"aria-label":`Eliminar ${i}`,title:"Eliminar",children:/* @__PURE__ */s("span",{className:"icon icon-delete-white icon--2sm"})}),M&&/* @__PURE__ */s("button",{type:"button",className:"lb:w-8 lb:h-8 lb:cursor-pointer lb:rounded-lg lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:text-white lb:flex lb:items-center lb:justify-center lb:focus:outline-none lb:focus:ring-2 lb:focus:ring-brand-blue-400 lb:focus:ring-offset-1 lb:transition-colors lb:shadow-sm",onClick:t=>{t.stopPropagation(),n?re():le(e)},"aria-label":`Ampliar ${i}`,title:"Ampliar",children:/* @__PURE__ */s("svg",{className:"lb:w-4 lb:h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM10 7v3m0 0v3m0-3h3m-3 0H7"})})})]})]})]})]},n?"original":e.id)})})})]}),
|
|
136
|
+
/* @__PURE__ */s(Ye,{isOpen:!!E,src:E?.src||"",alt:E?.title||"Imagen",title:E?.title,subtitle:E?.subtitle,onClose:()=>$(null)})]})}const Ze="/api";let et={data:null,timestamp:0,pending:null};const tt=/* @__PURE__ */new Set;function nt(){et.data=null,et.timestamp=0,et.pending=null,tt.forEach(e=>e())}async function lt(e={}){return et.data&&Date.now()-et.timestamp<3e5?et.data:(et.pending||(et.pending=async function(e={}){try{const t={include_counts:"true",...e},n=`/folders?${new URLSearchParams(t).toString()}`;return function(e){if(!e?.success||!e?.data)return{folders:[],total:0};const t=(e.data.folders||[]).map(e=>({id:e.id,name:e.name,slug:e.slug,description:e.description,visibility:e.visibility||"public",sort_order:e.sort_order||0,assets_count:e.assets_count||0,created_at:e.created_at,updated_at:e.updated_at}));return{folders:t,total:e.data.total||t.length}}(await Y({endpoint:n,method:"GET",basePath:Ze,useJWT:!0}))}catch(t){throw re(t)}}(e).then(e=>(et.data=e,et.timestamp=Date.now(),et.pending=null,e)).catch(e=>{throw et.pending=null,e})),et.pending)}function rt(e={}){const{autoFetch:l=!0,visibility:i=null,allowedSlugs:o=null,excludeSlugs:s=null}=e,[c,u]=t([]),[d,b]=t(!1),[m,h]=t(null),[p,f]=t(!1),g=r(null),v=a(e=>{let t=[...e];return o&&o.length>0&&(t=t.filter(e=>o.includes(e.slug))),s&&s.length>0&&(t=t.filter(e=>!s.includes(e.slug))),t.sort((e,t)=>e.sort_order!==t.sort_order?e.sort_order-t.sort_order:e.name.localeCompare(t.name)),t},[o,s]),y=a(async(e={})=>{b(!0),h(null);try{const t={...i&&{visibility:i},...e},n=await lt(t),l=v(n.folders||[]);return u(l),l}catch(t){return h(t.message),[]}finally{b(!1)}},[i,v]),w=a(()=>(nt(),y()),[y]),x=a(async e=>{f(!0),h(null);try{const t=await async function(e){try{return function(e){if(!e?.success||!e?.data)return{folder:null};const t=e.data;return{folder:{id:t.id,name:t.name,slug:t.slug,description:t.description,visibility:t.visibility||"public",sort_order:t.sort_order||0,assets_count:t.assets_count||0,created_at:t.created_at,updated_at:t.updated_at}}}(await Y({endpoint:"/folders",method:"POST",body:{name:e.name,...e.slug&&{slug:e.slug},...e.description&&{description:e.description},...e.visibility&&{visibility:e.visibility}},basePath:Ze,useJWT:!0}))}catch(m){throw re(m)}}(e),n=t.folder;return n&&(nt(),u(e=>{const t=[...e,n];return t.sort((e,t)=>e.sort_order!==t.sort_order?e.sort_order-t.sort_order:e.name.localeCompare(t.name)),t})),n}catch(t){return h(t.message),null}finally{f(!1)}},[]),k=a(e=>c.find(t=>t.slug===e)||null,[c]),C=a(e=>c.find(t=>t.id===e)||null,[c]);return g.current=y,n(()=>{const e=()=>g.current?.();return tt.add(e),()=>tt.delete(e)},[]),n(()=>{l&&y()},[l,y]),{folders:c,loading:d,error:m,creating:p,fetchFolders:y,create:x,refresh:w,findBySlug:k,findById:C,hasLoaded:!d&&c.length>=0}}function at({value:e=null,onChange:n,allowCreate:l=!0,placeholder:r="Sin carpeta",label:a=null,disabled:o=!1,className:d="",showAssetCount:b=!1,includeNoFolder:m=!0,allowedSlugs:h=null,excludeSlugs:p=null,mode:f="upload"}){const g=i(),[v,y]=t(!1),[w,x]=t(""),[k,C]=t(null),{folders:S,loading:N,error:E,creating:$,create:_,refresh:z}=rt({autoFetch:!0,allowedSlugs:h,excludeSlugs:p}),T=async e=>{if(e.preventDefault(),C(null),!w.trim())return void C("El nombre es requerido");const t=await _({name:w.trim()});t?(n?.(t),y(!1),x("")):C("Error al crear la carpeta")},A=()=>{y(!1),x(""),C(null)};if(v)/* @__PURE__ */
|
|
137
137
|
return c("div",{className:`limbo-folder-selector limbo-folder-selector--creating ${d}`,children:[a&&/* @__PURE__ */c("label",{className:"limbo-filter-label lb:block lb:mb-1",children:[a," ",$&&/* @__PURE__ */s("span",{className:"limbo-filter-searching","aria-hidden":"true",children:/* @__PURE__ */s("span",{className:"icon icon-spinner lb:animate-spin lb:w-3 lb:h-3"})})]}),
|
|
138
138
|
/* @__PURE__ */c("form",{onSubmit:T,className:"lb:flex lb:gap-2 lb:items-center lb:flex-col",children:[
|
|
139
139
|
/* @__PURE__ */s("div",{children:/* @__PURE__ */s("input",{type:"text",value:w,onChange:e=>x(e.target.value),placeholder:"Nombre de la carpeta...",className:"limbo-filter-input lb:flex-1",autoFocus:!0,disabled:$})}),
|
|
@@ -145,13 +145,13 @@ return c("div",{className:`limbo-folder-selector ${d}`,children:[a&&/* @__PURE__
|
|
|
145
145
|
/* @__PURE__ */s("option",{disabled:!0,children:"──────────────"}),
|
|
146
146
|
/* @__PURE__ */s("option",{value:"__create__",children:"+ Crear nueva carpeta..."})]})]})}),E&&/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-2 lb:mt-1",children:[
|
|
147
147
|
/* @__PURE__ */s("p",{className:"lb:text-red-600 lb:text-xs",children:E}),
|
|
148
|
-
/* @__PURE__ */s("button",{type:"button",onClick:z,className:"lb:text-xs lb:text-brand-blue-1000 lb:underline lb:cursor-pointer",children:"Reintentar"})]})]})}const
|
|
148
|
+
/* @__PURE__ */s("button",{type:"button",onClick:z,className:"lb:text-xs lb:text-brand-blue-1000 lb:underline lb:cursor-pointer",children:"Reintentar"})]})]})}const it={pdf:{symbol:"icon-doc-pdf",color:"#dc2626"},doc:{symbol:"icon-doc-word",color:"#2563eb"},docx:{symbol:"icon-doc-word",color:"#2563eb"},xls:{symbol:"icon-doc-xls",color:"#16a34a"},xlsx:{symbol:"icon-doc-xls",color:"#16a34a"},ppt:{symbol:"icon-doc-ppt",color:"#ea580c"},pptx:{symbol:"icon-doc-ppt",color:"#ea580c"},txt:{symbol:"icon-doc-text",color:"#6b7280"},csv:{symbol:"icon-doc-report",color:"#16a34a"},mp4:{symbol:"icon-video",color:"#7c3aed"},webm:{symbol:"icon-video",color:"#7c3aed"},mov:{symbol:"icon-video",color:"#7c3aed"},avi:{symbol:"icon-video",color:"#7c3aed"},mkv:{symbol:"icon-video",color:"#7c3aed"},gif:{symbol:"icon-video",color:"#7a3f2d"},mp3:{symbol:"icon-support-person",color:"#0891b2"},mpeg:{symbol:"icon-support-person",color:"#0891b2"},wav:{symbol:"icon-support-person",color:"#0891b2"},ogg:{symbol:"icon-support-person",color:"#0891b2"},aac:{symbol:"icon-support-person",color:"#0891b2"},flac:{symbol:"icon-support-person",color:"#0891b2"},default:{symbol:"icon-clip",color:"#6b7280"}},ot=(e,t)=>0===t?e:ot(t,e%t),st=/* @__PURE__ */new Set(["text/plain","text/csv","text/html","text/xml","text/css","text/javascript","text/markdown","application/json","application/xml","application/javascript"]);const ct=e.memo(function({image:i,onDelete:o,onCrop:d,onSelect:b,onFolderChange:m,thumbnailSize:h=32,isDeleting:p=!1,showFolderInfo:f=!0,allowMoveFolder:g=!0,allowedFolderSlugs:v=null,excludedFolderSlugs:y=null,allowCreateFolder:w=!1,allowedActions:x={select:!0,download:!0,copy:!0,delete:!0,crop:!0,variants:!0,rename:!0},onRename:C=null}){const[S,N]=t(!1),[E,$]=t(!1),[_,z]=t(!1),[T,A]=t(i.variants_count||0),[L,I]=t(!1),[P,M]=t(!1),[R,O]=t(!1),[F,j]=t(""),[U,B]=t(null),[W,q]=t(!1),V=r(null);n(()=>{if(!L)return;const e=e=>{e.target.closest(".limbo-image-card-wrapper")||I(!1)},t=e=>{e.detail?.id!==i.id&&I(!1)};return document.addEventListener("click",e),document.addEventListener("limbo:folder-dropdown-open",t),()=>{document.removeEventListener("click",e),document.removeEventListener("limbo:folder-dropdown-open",t)}},[L,i.id]);const H=l(()=>(e=>{if(e.asset_type)return e.asset_type;const t=e.mime_type||e.original_mime||"";return"image/gif"===t?"video":t.startsWith("image/")?"image":t.startsWith("video/")?"video":t.startsWith("audio/")?"audio":t.includes("pdf")||t.includes("document")||t.includes("spreadsheet")||t.includes("presentation")||t.includes("text/")?"document":"unknown"})(i),[i]),K="image"===H,G=(i.mime_type||i.original_mime||"").includes("image/gif"),Q=K||G,X=l(()=>(e=>{if(!e)return"";const t=e.split(".");return t.length>1?t.pop().toLowerCase():""})(i.filename),[i.filename]),Y=it[X]||it.default,J=l(()=>((e,t)=>{if(!e||!t||e<=0||t<=0)return null;const n=ot(Math.round(e),Math.round(t)),l=Math.round(e)/n,r=Math.round(t)/n;return l>20||r>20?null:`${l}:${r}`})(i.width,i.height),[i.width,i.height]),Z=i.url||i.path,ee=Q&&i.thumbnail_url?i.thumbnail_url:Z,[te,ne]=t(()=>Se(ee)),[le,re]=t(()=>!Ne(ee)),[ae,ie]=t(!1),[oe,se]=t(()=>Ne(ee)),ce=r(null),{isMobile:ue,isTouch:de}=D(),be=window.limboCore?.accessibilityManager,me=(window.limboCore?.config?.getGlobal()||{}).interaction||{allowSelection:!1,allowCropping:!0},he=e=>{e.stopPropagation(),be?.announce(`Eliminando imagen ${i.filename}`,"assertive"),o?.(i)},pe=async e=>{e.stopPropagation();let t=i.url||i.path;try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t);else{const e=document.createElement("textarea");e.value=t,e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.focus(),e.select(),document.execCommand("copy"),document.body.removeChild(e)}N(!0),be?.announce(`URL de ${i.filename} copiada al portapapeles. Nota: La URL puede tener un tiempo de validez limitado.`),setTimeout(()=>N(!1),2e3)}catch(n){console.error("Error al copiar URL:",n),be?.announce(`Error al copiar URL de ${i.filename}. Inténtalo de nuevo.`),alert(`Error al copiar URL de ${i.filename}. Por favor, inténtalo de nuevo.`)}},fe=async e=>{e.preventDefault(),e.stopPropagation();const t=i.url||i.path,n=i.filename||"limbo-file";if(!K){try{be?.announce(`Descargando ${n}`);const e=await fetch(t,{mode:"cors"});if(!e.ok)throw new Error(`HTTP error: ${e.status}`);const l=await e.blob(),r=window.URL.createObjectURL(l),a=document.createElement("a");a.href=r,a.download=n,a.style.display="none",document.body.appendChild(a),a.click(),setTimeout(()=>{window.URL.revokeObjectURL(r),document.body.removeChild(a)},100),be?.announce(`${n} descargado correctamente`)}catch(r){console.error("Error downloading file:",r),be?.announce(`Error al descargar ${n}`)}return}const{downloadImage:l}=await Promise.resolve().then(()=>Ll);await l(t,n,{originalFormat:i.format,accessibilityManager:be})},ge=e=>{e.stopPropagation(),be?.announce(`Editando imagen ${i.filename}`),d?.(i)},ve=a(e=>{e.stopPropagation();const t=i.filename.replace(/\.[^.]+$/,"");j(t),B(null),O(!0),setTimeout(()=>V.current?.select(),0)},[i.filename]),ye=a(e=>{e?.stopPropagation(),O(!1),B(null)},[]),we=a(e=>{const t=e.target.value;j(t);const n=De(t||"_");B(n.valid?null:n.error)},[]),xe=a(async e=>{e?.preventDefault(),e?.stopPropagation();const t=F.trim(),n=De(t);if(!n.valid)return void B(n.error);const l=t+(i.filename.includes(".")?"."+i.filename.split(".").pop():"");if(l!==i.filename){q(!0);try{await(C?.(i,l)),O(!1)}catch{B("Error al renombrar. Inténtalo de nuevo.")}finally{q(!1)}}else O(!1)},[F,i,C]),ke=K&&(i.variants&&i.variants.length>0||T>0),Ee=T,$e=e.useCallback(()=>{A(e=>Math.max(0,e-1))},[]);e.useEffect(()=>{A(i.variants_count||0)},[i.variants_count]),n(()=>{if(!Q)return re(!1),void se(!0);if(i.thumbnail_url){if(Ne(i.thumbnail_url)){const e=Se(i.thumbnail_url);return ne(e),re(!1),ie(!1),void se(!0)}return ne(i.thumbnail_url),re(!0),ie(!1),void se(!1)}const e=i.url||i.path;if(Ne(e))return ne(Se(e)),re(!1),ie(!1),void se(!0);re(!0),ie(!1),se(!1),Ce(e).then(e=>{ne(e),re(!1),se(!0)}).catch(()=>{ne(e),re(!1),ie(!0)})},[i.url,i.path,i.thumbnail_url,Q]),n(()=>{if(!Q||!le)return;const e=ce.current;e&&e.complete&&e.naturalWidth>0&&(re(!1),se(!0),ie(!1))},[Q,le,te]);const _e=me.allowSelection&&x.select&&b,ze=G?Z:null,Te=K&&!G&&me.allowCropping&&x.crop&&d,Ae=()=>{ke?(be?.announce(`Mostrando recortes de ${i.filename}`),$(!0)):_e?(be?.announce(`Seleccionando ${i.filename} para el portal`),b?.(i)):(be?.announce(`Abriendo visor de ${i.filename}`),z(!0))};/* @__PURE__ */
|
|
149
149
|
return c(u,{children:[
|
|
150
|
-
/* @__PURE__ */c("div",{className:`limbo-image-card-wrapper lb:relative lb:cursor-pointer lb:focus:outline-0 ${p?"lb:opacity-50":""} ${ue?"limbo-image-card-wrapper--mobile":""} ${L?"limbo-image-card-wrapper--has-active-dropdown":""}`,onClick:
|
|
150
|
+
/* @__PURE__ */c("div",{className:`limbo-image-card-wrapper lb:relative lb:cursor-pointer lb:focus:outline-0 ${p?"lb:opacity-50":""} ${ue?"limbo-image-card-wrapper--mobile":""} ${L?"limbo-image-card-wrapper--has-active-dropdown":""}`,onClick:Ae,onKeyDown:e=>{if("INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName)switch(e.key){case"Enter":case" ":e.preventDefault(),Ae();break;case"d":case"D":x.download&&(e.preventDefault(),fe(e));break;case"c":case"C":x.copy&&(e.preventDefault(),pe(e));break;case"Delete":case"Backspace":x.delete&&o&&(e.preventDefault(),he(e));break;case"x":case"X":x.crop&&d&&(e.preventDefault(),ge(e));break;case"v":case"V":x.variants&&(e.preventDefault(),(e=>{e.stopPropagation(),be?.announce(`Mostrando recortes de ${i.filename}`),$(!0)})(e))}},onMouseEnter:ze?()=>{ze&&i.thumbnail_url&&ne(ze)}:void 0,onMouseLeave:ze?()=>{ze&&i.thumbnail_url&&ne(i.thumbnail_url)}:void 0,title:ke?`Ver ${Ee} recorte${1!==Ee?"s":""} de ${i.filename}`:Q?ue?"Toque para ampliar imagen":"Click para ampliar imagen con zoom":ue?"Toque para previsualizar":"Click para previsualizar",role:"button",tabIndex:0,"aria-label":Q?`${G?"GIF":"Imagen"} ${i.filename}. ${i.width}x${i.height} px`:`Archivo ${i.filename}. Tipo: ${H}`,style:{...de&&{touchAction:"manipulation",WebkitTapHighlightColor:"transparent"}},children:[P&&/* @__PURE__ */c("div",{className:"limbo-moving-overlay",children:[
|
|
151
151
|
/* @__PURE__ */s("span",{className:"icon icon-spinner lb:animate-spin lb:w-6 lb:h-6"}),
|
|
152
152
|
/* @__PURE__ */s("span",{className:"lb:text-xs lb:text-gray-600 lb:font-medium",children:"Moviendo..."})]}),
|
|
153
153
|
/* @__PURE__ */c("div",{className:`limbo-image-actions ${L?"limbo-image-actions--expanded":""} ${ue?"limbo-image-actions--mobile":""}`,children:[
|
|
154
|
-
/* @__PURE__ */c("div",{className:"limbo-image-actions__buttons",children:[(_e||!Q)&&/* @__PURE__ */s("button",{type:"button",title:
|
|
154
|
+
/* @__PURE__ */c("div",{className:"limbo-image-actions__buttons",children:[(_e||!Q)&&/* @__PURE__ */s("button",{type:"button",title:ke?`Ver ${Ee} recortes`:Q?"Ampliar imagen":"Previsualizar archivo","aria-label":ke?k("imageCard.aria.zoomWithCrops",{n:Ee,filename:i.filename}):k(Q?"imageCard.aria.zoom":"imageCard.aria.zoomPreview",{filename:i.filename}),className:"limbo-action-btn lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:border lb:border-brand-blue-1000 "+(ue?"lb:btn--touch":""),onClick:e=>{e?.stopPropagation(),be?.announce(`Abriendo visor de ${i.filename}`),z(!0)},tabIndex:0,children:/* @__PURE__ */s("span",{className:`icon ${Q?"icon-zoom-in-white":"icon-search-white"} icon--sm`,"aria-hidden":"true"})}),Te&&/* @__PURE__ */s("button",{type:"button",title:"Nuevo recorte","aria-label":k("imageCard.aria.crop",{filename:i.filename}),className:"limbo-action-btn limbo-btn-crop lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:border lb:border-brand-blue-1000 "+(ue?"lb:btn--touch":""),onClick:ge,tabIndex:0,children:/* @__PURE__ */s("span",{className:"icon icon-scissors-white icon--sm","aria-hidden":"true"})}),x.copy&&/* @__PURE__ */s("button",{type:"button",title:S?"¡Copiado!":"Copiar URL","aria-label":S?k("imageCard.aria.copied"):k("imageCard.aria.copyUrl",{filename:i.filename}),className:"limbo-action-btn limbo-btn-copy lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:border lb:border-brand-blue-1000 "+(ue?"lb:btn--touch":""),onClick:pe,tabIndex:0,children:/* @__PURE__ */s("span",{className:`icon ${S?"icon-copied-white":"icon-copy-white"} icon--sm`,"aria-hidden":"true"})}),x.download&&/* @__PURE__ */s("button",{type:"button",title:"Descargar","aria-label":k("imageCard.aria.download",{filename:i.filename}),className:"limbo-action-btn limbo-btn-download lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:border lb:border-brand-blue-1000 "+(ue?"lb:btn--touch":""),onClick:fe,tabIndex:0,children:/* @__PURE__ */s("span",{className:"icon icon-download-white icon--sm","aria-hidden":"true"})}),g&&m&&/* @__PURE__ */s("button",{type:"button",title:i.folder?`Mover de carpeta (${i.folder?.name||i.folder?.slug||""})`:"Asignar a carpeta",className:`limbo-action-btn limbo-btn-folder lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:border lb:border-brand-blue-1000 ${ue?"lb:btn--touch":""} ${L?"limbo-action-btn--active":""}`,onClick:e=>{e.stopPropagation();const t=!L;I(t),t&&document.dispatchEvent(new CustomEvent("limbo:folder-dropdown-open",{detail:{id:i.id}}))},"aria-expanded":L,"aria-label":L?"Cerrar selector de carpeta":i.folder?`Mover de carpeta (${i.folder?.name||i.folder?.slug||""})`:"Asignar a carpeta",tabIndex:0,children:/* @__PURE__ */s("span",{className:"icon icon-folder-white icon--sm","aria-hidden":"true"})}),x.rename&&C&&/* @__PURE__ */s("button",{type:"button",title:"Renombrar archivo","aria-label":k("imageCard.aria.rename",{filename:i.filename}),className:"limbo-action-btn limbo-btn-rename lb:bg-brand-blue-400 lb:hover:bg-brand-blue-800 lb:border lb:border-brand-blue-1000 "+(ue?"lb:btn--touch":""),onClick:ve,tabIndex:0,children:/* @__PURE__ */s("span",{className:"icon icon-edit-white icon--sm","aria-hidden":"true"})}),x.delete&&o&&/* @__PURE__ */s("button",{onClick:he,disabled:p,className:"limbo-action-btn limbo-btn-delete lb:bg-red-800 lb:hover:bg-red-700 lb:border lb:border-red-700 "+(ue?"lb:btn--touch lb:active:lb:bg-red-800":""),title:"Eliminar archivo","aria-label":k("imageCard.aria.delete",{filename:i.filename}),tabIndex:0,children:p?"…":/* @__PURE__ */s("span",{className:"icon icon-delete-white icon--1sm","aria-hidden":"true"})})]}),L&&g&&m&&/* @__PURE__ */s("div",{className:"limbo-image-actions__folder",onClick:e=>e.stopPropagation(),children:/* @__PURE__ */s(at,{value:i.folder?.slug||null,onChange:async e=>{if(!P){M(!0);try{await(m?.(i,e??null)),nt(),be?.announce(e?`${i.filename} movido a carpeta ${e.name}`:`${i.filename} movido a Sin carpeta`)}catch(t){console.error("Error moving to folder:",t),be?.announce(`Error al mover ${i.filename}`)}finally{M(!1),I(!1)}}},allowCreate:w,placeholder:"Sin carpeta",label:"Mover a carpeta",includeNoFolder:!0,allowedSlugs:v,excludeSlugs:y,disabled:P,mode:"upload"})})]}),
|
|
155
155
|
/* @__PURE__ */c("div",{className:"limbo-image-card "+(ue?"limbo-image-card--mobile":""),children:[!Q&&(i.thumbnail_url?
|
|
156
156
|
/* @__PURE__ */c("div",{className:"lb:relative lb:w-full lb:h-full lb:rounded lb:overflow-hidden lb:border lb:border-neutral-300",style:{...ue&&{minHeight:`${Math.max(3*h,80)}px`}},children:[
|
|
157
157
|
/* @__PURE__ */s("img",{src:i.thumbnail_url,alt:i.name||i.filename,className:"lb:w-full lb:h-full lb:object-cover lb:aspect-square",loading:"lazy",decoding:"async",draggable:!1,onError:e=>{e.target.style.display="none",e.target.nextElementSibling?.classList.remove("lb:hidden")}}),
|
|
@@ -159,27 +159,27 @@ return c(u,{children:[
|
|
|
159
159
|
/* @__PURE__ */s("span",{className:"lb:absolute lb:bottom-1.5 lb:right-1.5 lb:text-[10px] lb:uppercase lb:font-bold lb:tracking-wide lb:px-1.5 lb:py-0.5 lb:rounded lb:shadow-sm",style:{backgroundColor:Y.color,color:"white"},children:X||H})]}):
|
|
160
160
|
/* @__PURE__ */c("div",{className:"lb:w-full lb:h-full lb:rounded lb:bg-linear-to-br lb:from-neutral-100 lb:to-neutral-200 lb:flex lb:flex-col lb:items-center lb:justify-center lb:border lb:border-neutral-300",style:{...ue&&{minHeight:`${Math.max(3*h,80)}px`}},children:[
|
|
161
161
|
/* @__PURE__ */s("span",{className:"lb:mb-2 lb:h-[25%] lb:w-[25%]","aria-hidden":"true",children:/* @__PURE__ */s("span",{className:`icon ${Y.symbol} lb:min-w-full lb:min-h-full`})}),
|
|
162
|
-
/* @__PURE__ */s("span",{className:"lb:text-xs lb:uppercase lb:font-bold lb:tracking-wide lb:px-2 lb:py-0.5 lb:rounded",style:{backgroundColor:Y.color,color:"white"},children:X||H})]})),Q&&/* @__PURE__ */c(u,{children:[le&&!ae&&/* @__PURE__ */s("div",{className:"lb:w-full lb:aspect-square lb:rounded lb:bg-neutral-200 lb:animate-pulse lb:flex lb:items-center lb:justify-center lb:absolute lb:inset-0 lb:z-10 "+(
|
|
162
|
+
/* @__PURE__ */s("span",{className:"lb:text-xs lb:uppercase lb:font-bold lb:tracking-wide lb:px-2 lb:py-0.5 lb:rounded",style:{backgroundColor:Y.color,color:"white"},children:X||H})]})),Q&&/* @__PURE__ */c(u,{children:[le&&!ae&&/* @__PURE__ */s("div",{className:"lb:w-full lb:aspect-square lb:rounded lb:bg-neutral-200 lb:animate-pulse lb:flex lb:items-center lb:justify-center lb:absolute lb:inset-0 lb:z-10 "+(ke?"lb:ring-2 lb:ring-brand-blue-400 lb:ring-offset-2":""),style:{...ue&&{minHeight:`${Math.max(3*h,80)}px`}},children:/* @__PURE__ */s("span",{className:"icon icon-spinner lb:w-8 lb:h-8 lb:animate-spin"})}),ae&&!oe&&/* @__PURE__ */c("div",{className:"lb:z-0 lb:absolute lb:top-0 lb:left-0 lb:w-full lb:aspect-square lb:rounded lb:bg-neutral-100 lb:flex lb:flex-col lb:items-center lb:justify-center lb:text-neutral-400",style:{...ue&&{minHeight:`${Math.max(3*h,80)}px`}},children:[
|
|
163
163
|
/* @__PURE__ */s("span",{className:"icon icon-close icon--lg lb:mb-1","aria-hidden":"true"}),
|
|
164
164
|
/* @__PURE__ */s("span",{className:"lb:text-xs",children:"Error al cargar"})]}),
|
|
165
|
-
/* @__PURE__ */s("img",{ref:ce,src:te,loading:"lazy",decoding:"async",alt:i.name||(i.filename.split(".")[0]??i.filename),className:`lb:z-1 lb:w-full lb:object-cover lb:rounded lb:aspect-square lb:transition-opacity lb:duration-300 ${
|
|
165
|
+
/* @__PURE__ */s("img",{ref:ce,src:te,loading:"lazy",decoding:"async",alt:i.name||(i.filename.split(".")[0]??i.filename),className:`lb:z-1 lb:w-full lb:object-cover lb:rounded lb:aspect-square lb:transition-opacity lb:duration-300 ${ke?"lb:ring-2 lb:ring-brand-blue-400 lb:ring-offset-2":""} ${oe?"lb:opacity-100":"lb:opacity-0"}`,sizes:`height: ${6*h}px,width: ${6*h}px`,draggable:!1,onLoad:()=>{re(!1),se(!0),ie(!1)},onError:()=>{re(!1),ie(!0)},style:{...ue&&{minHeight:`${Math.max(3*h,80)}px`,height:"auto",aspectRatio:"1 / 1",objectFit:"cover"}}}),G&&/* @__PURE__ */s("span",{className:"lb:absolute lb:bottom-1.5 lb:right-1.5 lb:text-[10px] lb:uppercase lb:font-bold lb:tracking-wide lb:px-1.5 lb:py-0.5 lb:rounded lb:shadow-sm",style:{backgroundColor:Y.color,color:"white"},children:X||H}),K&&!ke&&i.width&&i.height&&/* @__PURE__ */c("span",{className:"lb:absolute lb:bottom-1.5 lb:right-1.5 lb:text-[10px] lb:font-bold lb:tracking-wide lb:px-1.5 lb:py-0.5 lb:rounded lb:shadow-sm lb:leading-tight lb:text-center lb:flex lb:flex-col lb:items-center",style:{backgroundColor:"rgba(15,23,42,0.72)",color:"white"},title:`${i.width} × ${i.height} px`,children:[
|
|
166
166
|
/* @__PURE__ */c("span",{children:[i.width,"×",i.height]}),J&&/* @__PURE__ */s("span",{style:{opacity:.85},children:J})]})]}),
|
|
167
|
-
/* @__PURE__ */c("div",{className:"limbo-card-info-overlay lb:z-
|
|
167
|
+
/* @__PURE__ */c("div",{className:"limbo-card-info-overlay lb:z-9 "+(ue?"limbo-card-info-overlay--mobile":""),style:R?{pointerEvents:"auto"}:void 0,children:[R?/* @__PURE__ */c("form",{className:"lb:flex lb:flex-col lb:w-full lb:gap-1",onSubmit:xe,onClick:e=>e.stopPropagation(),children:[
|
|
168
168
|
/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-1 lb:w-full",children:[
|
|
169
|
-
/* @__PURE__ */s("input",{ref:V,type:"text",value:F,onChange:
|
|
169
|
+
/* @__PURE__ */s("input",{ref:V,type:"text",value:F,onChange:we,onKeyDown:e=>"Escape"===e.key&&ye(e),className:`lb:flex-1 lb:min-w-0 lb:px-1 lb:py-0.5 lb:text-xs lb:rounded lb:border ${U?"lb:border-red-400":"lb:border-gray-400"} lb:bg-white lb:text-gray-900 lb:outline-none`,placeholder:"Nuevo nombre",disabled:W,autoFocus:!0}),
|
|
170
170
|
/* @__PURE__ */s("button",{type:"submit",disabled:W||!!U,className:"lb:px-1.5 lb:py-0.5 lb:text-xs lb:bg-brand-blue-400 lb:text-white lb:rounded lb:shrink-0 lb:disabled:opacity-40 lb:hover:outline-brand-blue-400/50 lb:hover:outline-2",title:"Guardar nombre",children:W?"…":"✓"}),
|
|
171
|
-
/* @__PURE__ */s("button",{type:"button",onClick:
|
|
171
|
+
/* @__PURE__ */s("button",{type:"button",onClick:ye,className:"lb:px-1.5 lb:py-0.5 lb:text-xs lb:bg-gray-500 lb:hover:outline-gray-500/50 lb:hover:outline-2 lb:text-white lb:rounded lb:shrink-0",title:"Cancelar",children:"✕"})]}),U&&/* @__PURE__ */s("span",{className:"lb:text-xs lb:text-red-300 lb:leading-tight",children:U})]}):/* @__PURE__ */c("span",{className:"limbo-card-info-name lb:truncate lb:max-w-full",children:[i.filename.split(".")[0]??i.filename,ke&&/* @__PURE__ */s("span",{className:"limbo-variants-indicator",style:{marginLeft:"4px",padding:"1px 6px",backgroundColor:"#dc2626",color:"white",borderRadius:"10px",fontSize:"10px",fontWeight:"700",display:"inline-block"},title:`${Ee} recorte${1!==Ee?"s":""}`,children:Ee})]}),f&&i.folder&&/* @__PURE__ */c("span",{className:"limbo-card-info-folder lb:flex lb:items-center lb:gap-1 lb:bg-brand-blue-50 lb:rounded-md lb:px-1",title:`Carpeta: ${i.folder?.name||i.folder?.slug||i.folder}`,children:[
|
|
172
172
|
/* @__PURE__ */s("span",{className:"icon icon-folder icon--sm"}),
|
|
173
173
|
/* @__PURE__ */s("span",{className:"lb:truncate lb:max-w-20",children:i.folder?.name||i.folder?.slug||("string"==typeof i.folder?i.folder:"Sin carpeta")})]})]})]})]}),
|
|
174
|
-
/* @__PURE__ */s(
|
|
174
|
+
/* @__PURE__ */s(Je,{image:i,isOpen:E,onClose:()=>$(!1),onSelect:b,onDelete:o,onCrop:d,onVariantDeleted:$e,allowedActions:{select:x.select,download:x.download,copy:x.copy,delete:x.delete,crop:x.crop}}),_&&(()=>{const e=i.url||i.path,t=()=>z(!1),n=i.file_size?`${Math.round(i.file_size/1024)}KB`:"",l=i.mime_type||"";return Q?/* @__PURE__ */s(Ye,{isOpen:!0,src:e,alt:i.name||i.filename,title:i.filename,subtitle:`${i.width||"?"}×${i.height||"?"} · ${n}`,onClose:t}):"video"===H?/* @__PURE__ */s(je,{isOpen:!0,src:e,title:i.filename,subtitle:`${X.toUpperCase()} · ${n}`,onClose:t}):"audio"===H?/* @__PURE__ */s(Ue,{isOpen:!0,src:e,title:i.filename,subtitle:`${X.toUpperCase()} · ${n}`,onClose:t}):l.includes("pdf")?/* @__PURE__ */s(Be,{isOpen:!0,src:e,title:i.filename,subtitle:n,onClose:t}):(e=>!(!e||!st.has(e)&&!e.startsWith("text/")))(l)?/* @__PURE__ */s(Xe,{isOpen:!0,src:e,title:i.filename,subtitle:`${X.toUpperCase()} · ${n}`,mimeType:l,fileSize:i.file_size||0,onClose:t}):/* @__PURE__ */s(Ge,{isOpen:!0,src:e,title:i.filename,subtitle:`${X.toUpperCase()} · ${n}`,mimeType:l,fileSize:i.file_size||0,onClose:t})})()]})});function ut(){/* @__PURE__ */
|
|
175
175
|
return c("div",{className:"limbo-image-card lb:animate-pulse",role:"status","aria-label":"Cargando imágen...",children:[
|
|
176
176
|
/* @__PURE__ */s("div",{className:"lb:w-full lb:aspect-square lb:bg-neutral-gray-200 lb:rounded-md lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-spinner"})}),
|
|
177
177
|
/* @__PURE__ */s("div",{className:"limbo-image-card-name lb:opacity-100 position-relative lb:bottom-0 lb:p-2",children:/* @__PURE__ */s("div",{className:"lb:h-4 lb:bg-neutral-gray-200 lb:rounded lb:w-3/4"})}),
|
|
178
|
-
/* @__PURE__ */s("span",{className:"sr-only",children:"Cargando imágen..."})]})}const
|
|
178
|
+
/* @__PURE__ */s("span",{className:"sr-only",children:"Cargando imágen..."})]})}const dt=[{value:"",label:"Todos los tipos"},{value:"image",label:"Imágenes"},{value:"video",label:"Videos"},{value:"document",label:"Documentos"},{value:"audio",label:"Audio"}];function bt({onSelect:e,onCrop:a,onDelete:i,deletingId:o,images:u,loading:m,error:h,filters:p={name:"",dateFrom:"",dateTo:"",uploadedBy:"",assetType:"",folder:""},debouncedFilters:f=null,onFiltersChange:g,filterConfig:v={showNameFilter:!0,showUploadedByFilter:!1,showDateFilter:!0,showTypeFilter:!1},loadingConfig:y={showPlaceholders:!0,placeholderCount:10,showSpinner:!0},allowedActions:w={select:!0,download:!0,copy:!0,delete:!0,crop:!0,variants:!0},allowedCategories:x=null,resolvedAccept:k=null,folderConfig:C=null,onFolderChange:S=null,onRename:N=null}){const{isSearching:E,searchPending:$}=function(e,l,a){const[i,o]=t(!1),s=r(null);return n(()=>(Object.keys(e).some(t=>e[t]!==l[t])?s.current=setTimeout(()=>{o(!0)},150):(s.current&&clearTimeout(s.current),o(!1)),()=>{s.current&&clearTimeout(s.current)}),[e,l]),{isSearching:i||a,searchPending:i}}(p,f||p,m),_=!1!==v.showNameFilter,z=!0===v.showUploadedByFilter,T=!1!==v.showDateFilter,A=!1!==v.showTypeFilter,L=!0===C?.showFolderFilter,I=C?.include?.length>0?C.include:null,P=C?.exclude?.length>0?C.exclude:null,M=!1!==C?.showFolderInfo,D=!1!==C?.allowMoveFolder&&!!S,R=!0===C?.allowCreateFolder,O=l(()=>{const e=k&&!k.isAllTypes?function(e){if(!e||e.isAllTypes)return null;const t=new Set(e.categories);for(const n of e.extensions){const e=d[n]||[];for(const n of e)for(const[e,l]of Object.entries(b))l.includes(n)&&t.add(e)}for(const n of e.mimeTypes)for(const[e,l]of Object.entries(b))(l.includes(n)||n.startsWith(e+"/"))&&t.add(e);return t.size>0?[...t]:null}(k):x;return e?dt.filter(t=>""===t.value||e.includes(t.value)):dt},[k,x]),F=r(null),j=window.limboCore?.accessibilityManager;n(()=>{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"})}},[u]),n(()=>{if(!m&&u.length>0){const e=u.slice(0,12).map(e=>e.url||e.path).filter(Boolean);e.length>0&&Ee(e,4)}},[m,u]);const U=l(()=>{if(!p.assetType)return"archivos";return{image:"imágenes",video:"videos",document:"documentos",audio:"archivos de audio"}[p.assetType]||"archivos"},[p.assetType]);n(()=>{m?j?.announceLoading(!0,"galería"):m||h?h&&j?.announceError(h,"galería"):(j?.announceLoading(!1,"galería"),u.length>0&&j?.announce(`Se encontraron ${u.length} ${U} en la galería`))},[m,h,u.length,j,U]),n(()=>{$&&j?.announce("Buscando...","polite")},[$,j]);const B=e=>{const{name:t,value:n}=e.target;g&&g({...p,[t]:n})},W=p.name||p.dateFrom||p.dateTo||p.uploadedBy||p.assetType||p.folder,q=E&&u.length>0&&!m;/* @__PURE__ */
|
|
179
179
|
return c("div",{className:"lb:w-full lb:max-w-full lb:py-2 lb:overflow-x-hidden lb:box-border",children:[
|
|
180
180
|
/* @__PURE__ */s("div",{className:"lb:px-2 lb:mb-3 lb:mx-2 lb:max-w-full lb:overflow-x-hidden lb:box-border",children:/* @__PURE__ */c("form",{className:"limbo-filters flex items-stretch content-stretch flex-row",onSubmit:e=>e.preventDefault(),role:"search","aria-label":"Filtrar archivos",children:[_&&/* @__PURE__ */c("div",{className:"limbo-filter-group limbo-filter-group--name",children:[
|
|
181
181
|
/* @__PURE__ */c("label",{htmlFor:"name",className:"limbo-filter-label",children:["Nombre",$&&/* @__PURE__ */s("span",{className:"limbo-filter-searching","aria-hidden":"true",children:/* @__PURE__ */s("span",{className:"icon icon-spinner lb:animate-spin lb:w-3 lb:h-3"})})]}),
|
|
182
|
-
/* @__PURE__ */s("input",{type:"text",name:"name",id:"name",placeholder:"Buscar...",value:p.name,onChange:B,className:"limbo-filter-input",autoComplete:"off"})]}),T&&/* @__PURE__ */c("div",{className:"limbo-filter-dates",children:[
|
|
182
|
+
/* @__PURE__ */s("input",{type:"text",name:"name",id:"name",placeholder:"Buscar...",value:p.name,onChange:B,className:"limbo-filter-input",autoComplete:"off"})]}),T&&/* @__PURE__ */c("div",{className:"limbo-filter-dates lb:flex-row lb:md:flex ",children:[
|
|
183
183
|
/* @__PURE__ */c("div",{className:"limbo-filter-group limbo-filter-group--date",children:[
|
|
184
184
|
/* @__PURE__ */s("label",{htmlFor:"dateFrom",className:"limbo-filter-label",children:"Desde"}),
|
|
185
185
|
/* @__PURE__ */s("input",{type:"date",name:"dateFrom",id:"dateFrom",value:p.dateFrom,onChange:B,className:"limbo-filter-input"})]}),
|
|
@@ -187,7 +187,7 @@ return c("div",{className:"lb:w-full lb:max-w-full lb:py-2 lb:overflow-x-hidden
|
|
|
187
187
|
/* @__PURE__ */s("label",{htmlFor:"dateTo",className:"limbo-filter-label",children:"Hasta"}),
|
|
188
188
|
/* @__PURE__ */s("input",{type:"date",name:"dateTo",id:"dateTo",value:p.dateTo,onChange:B,className:"limbo-filter-input"})]})]}),A&&O.length>1&&/* @__PURE__ */c("div",{className:"limbo-filter-group limbo-filter-group--type",children:[
|
|
189
189
|
/* @__PURE__ */s("label",{htmlFor:"assetType",className:"limbo-filter-label",children:"Tipo"}),
|
|
190
|
-
/* @__PURE__ */s("select",{name:"assetType",id:"assetType",value:p.assetType||"",onChange:B,className:"limbo-filter-input limbo-filter-select",children:O.map(e=>/* @__PURE__ */s("option",{value:e.value,children:e.label},e.value))})]}),L&&/* @__PURE__ */s("div",{className:"limbo-filter-group limbo-filter-group--folder",children:/* @__PURE__ */s(
|
|
190
|
+
/* @__PURE__ */s("select",{name:"assetType",id:"assetType",value:p.assetType||"",onChange:B,className:"limbo-filter-input limbo-filter-select",children:O.map(e=>/* @__PURE__ */s("option",{value:e.value,children:e.label},e.value))})]}),L&&/* @__PURE__ */s("div",{className:"limbo-filter-group limbo-filter-group--folder",children:/* @__PURE__ */s(at,{value:p.folder||"",onChange:e=>B({target:{name:"folder",value:e?.slug||""}}),allowCreate:!1,label:"Carpeta",showAssetCount:!0,includeNoFolder:!0,allowedSlugs:I,excludeSlugs:P,mode:"filter"})}),z&&/* @__PURE__ */c("div",{className:"limbo-filter-group",children:[
|
|
191
191
|
/* @__PURE__ */s("label",{htmlFor:"uploadedBy",className:"limbo-filter-label",children:"Subido por"}),
|
|
192
192
|
/* @__PURE__ */s("input",{type:"text",name:"uploadedBy",id:"uploadedBy",placeholder:"Usuario...",value:p.uploadedBy,onChange:B,className:"limbo-filter-input",style:{minWidth:"100px",maxWidth:"140px"}})]}),
|
|
193
193
|
/* @__PURE__ */c("div",{children:[
|
|
@@ -196,22 +196,22 @@ return c("div",{className:"lb:w-full lb:max-w-full lb:py-2 lb:overflow-x-hidden
|
|
|
196
196
|
/* @__PURE__ */s("span",{className:"icon icon-close-small"}),"Limpiar"]})]})]})}),m?/* @__PURE__ */c("div",{className:"lb:relative",children:[
|
|
197
197
|
/* @__PURE__ */s("div",{className:"lb:relative lb:inset-0 lb:flex lb:items-center lb:justify-center lb:bg-white/80 lb:z-10 lb:min-h-75",children:/* @__PURE__ */c("div",{className:"lb:flex lb:flex-col lb:items-center lb:gap-3",children:[
|
|
198
198
|
/* @__PURE__ */s("span",{className:"icon icon-spinner lb:p-4 lb:animate-spin"}),
|
|
199
|
-
/* @__PURE__ */c("span",{className:"lb:text-sm lb:text-gray-600 lb:font-medium",children:["Cargando ",U,"..."]})]})}),y.showPlaceholders&&/* @__PURE__ */s("div",{ref:F,className:"limbo-gallery lb:opacity-30","data-limbo-responsive":!0,role:"grid","aria-label":`Cargando ${U} de la galería`,"aria-busy":"true",children:Array.from({length:y.placeholderCount}).map((e,t)=>/* @__PURE__ */s("div",{role:"gridcell","aria-posinset":t+1,"aria-setsize":y.placeholderCount,className:"lb:min-w-0",children:/* @__PURE__ */s(
|
|
199
|
+
/* @__PURE__ */c("span",{className:"lb:text-sm lb:text-gray-600 lb:font-medium",children:["Cargando ",U,"..."]})]})}),y.showPlaceholders&&/* @__PURE__ */s("div",{ref:F,className:"limbo-gallery lb:opacity-30","data-limbo-responsive":!0,role:"grid","aria-label":`Cargando ${U} de la galería`,"aria-busy":"true",children:Array.from({length:y.placeholderCount}).map((e,t)=>/* @__PURE__ */s("div",{role:"gridcell","aria-posinset":t+1,"aria-setsize":y.placeholderCount,className:"lb:min-w-0",children:/* @__PURE__ */s(ut,{})},`skeleton-${t}`))})]}):h?/* @__PURE__ */s(ye,{variant:"danger",className:"lb:text-center",children:h}):/* @__PURE__ */c("div",{className:"lb:relative",children:[q&&/* @__PURE__ */s("div",{className:"limbo-search-overlay",role:"status","aria-live":"polite","aria-label":"Buscando archivos",children:/* @__PURE__ */c("div",{className:"limbo-search-overlay__content",children:[
|
|
200
200
|
/* @__PURE__ */s("span",{className:"icon icon-spinner lb:animate-spin"}),
|
|
201
201
|
/* @__PURE__ */s("span",{children:"Buscando..."})]})}),
|
|
202
|
-
/* @__PURE__ */s("div",{ref:F,className:"limbo-gallery lb:px-3 lb:pt-4 lb:box-border lb:max-w-full "+(q?"lb:opacity-50 lb:pointer-events-none":""),"data-limbo-responsive":!0,"data-grid-id":"gallery-grid",role:"grid","aria-label":`Galería de ${U}. Use las flechas para navegar`,"aria-busy":q,children:u.length>0?u.map((t,n)=>/* @__PURE__ */s("div",{role:"gridcell","aria-posinset":n+1,"aria-setsize":u.length,className:"lb:min-w-0",children:/* @__PURE__ */s(
|
|
202
|
+
/* @__PURE__ */s("div",{ref:F,className:"limbo-gallery lb:px-3 lb:pt-4 lb:box-border lb:max-w-full "+(q?"lb:opacity-50 lb:pointer-events-none":""),"data-limbo-responsive":!0,"data-grid-id":"gallery-grid",role:"grid","aria-label":`Galería de ${U}. Use las flechas para navegar`,"aria-busy":q,children:u.length>0?u.map((t,n)=>/* @__PURE__ */s("div",{role:"gridcell","aria-posinset":n+1,"aria-setsize":u.length,className:"lb:min-w-0",children:/* @__PURE__ */s(ct,{image:t,onSelect:e,onCrop:a,onDelete:w.delete&&i?()=>i(t.id):null,onFolderChange:S,onRename:N,thumbnailSize:32,isDeleting:o===t.id,showFolderInfo:M,allowMoveFolder:D,allowedFolderSlugs:I,excludedFolderSlugs:P,allowCreateFolder:R,allowedActions:w})},t.id)):/* @__PURE__ */s("div",{className:"lb:col-span-full lb:text-center lb:text-gray-500 lb:py-8",role:"status","aria-live":"polite",children:/* @__PURE__ */c("p",{children:["No se han encontrado ",U]})})})]})]})}function mt({currentPage:t,totalPages:n,onPageChange:l,disabled:r=!1}){if(!n||n<=1)return null;const a=(()=>{const e=[],l=[],r=Math.max(1,t-2),a=Math.min(n,t+2);for(let t=r;t<=a;t++)e.push(t);return r>1&&(l.push(1),r>2&&l.push("...")),l.push(...e),a<n&&(a<n-1&&l.push("..."),l.push(n)),l})();/* @__PURE__ */
|
|
203
203
|
return s("div",{className:"lb:flex lb:flex-col lb:items-center lb:justify-center lb:space-x-2 lb:py-4",children:/* @__PURE__ */c("div",{className:"lb:flex lb:space-x-2 lb:mt-2",children:[
|
|
204
204
|
/* @__PURE__ */c("button",{onClick:()=>{t>1&&l(t-1)},disabled:r||t<=1,className:` lb:px-3 lb:py-2 lb:text-sm lb:font-medium lb:rounded-md lb:transition-colors lb:disabled:cursor-default lb:cursor-pointer ${r||t<=1?"lb:text-gray-400 lb:bg-gray-100 lb:cursor-not-allowed":"lb:text-gray-700 lb:bg-white lb:border lb:border-gray-300 lb:hover:bg-gray-50 lb:focus:ring-2 lb:focus:ring-blue-500"} `,children:[
|
|
205
205
|
/* @__PURE__ */s("span",{className:"icon icon-arrow-left icon--sm"})," Anterior"]}),
|
|
206
206
|
/* @__PURE__ */s("div",{className:"lb:flex lb:space-x-1",children:a.map((n,a)=>/* @__PURE__ */s(e.Fragment,{children:"..."===n?/* @__PURE__ */s("span",{className:"lb:px-3 lb:py-2 lb:text-sm lb:text-gray-500",children:"..."}):/* @__PURE__ */s("button",{onClick:()=>(e=>{e!==t&&l(e)})(n),disabled:r,className:` lb:px-3 lb:py-2 lb:text-sm lb:font-medium lb:rounded-md lb:transition-colors lb:disabled:cursor-default lb:cursor-pointer ${n===t?"lb:bg-brand-blue-800 lb:text-white lb:border lb:border-brand-blue-1000":r?"lb:text-gray-400 lb:bg-gray-100 lb:cursor-not-allowed":"lb:text-gray-700 lb:bg-white lb:border lb:border-gray-300 lb:hover:bg-gray-50 lb:focus:ring-2 lb:focus:ring-blue-500"} `,children:n})},`page-${n}-${a}`))}),
|
|
207
207
|
/* @__PURE__ */c("button",{onClick:()=>{t<n&&l(t+1)},disabled:r||t>=n,className:` lb:px-3 lb:py-2 lb:text-sm lb:font-medium lb:rounded-md lb:transition-colors lb:disabled:cursor-default lb:cursor-pointer ${r||t>=n?"lb:text-gray-400 lb:bg-gray-100 lb:cursor-not-allowed":"lb:text-gray-700 lb:bg-white lb:border lb:border-gray-300 lb:hover:bg-gray-50 lb:focus:ring-2 lb:focus:ring-blue-500"} `,children:["Siguiente ",
|
|
208
|
-
/* @__PURE__ */s("span",{className:"icon icon-arrow-right icon--sm"})]})]})})}function
|
|
208
|
+
/* @__PURE__ */s("span",{className:"icon icon-arrow-right icon--sm"})]})]})})}function ht({text:e="Cargando..."}){/* @__PURE__ */
|
|
209
209
|
return c("div",{className:"lb:absolute lb:inset-0 lb:bg-neutral-gray-1000/20 lb:z-10 lb:flex lb:flex-col lb:items-center lb:justify-center lb:py-8 lb:text-gray-600",role:"status","aria-live":"polite","aria-label":e,children:[
|
|
210
210
|
/* @__PURE__ */s("span",{className:"limbo-filter-searching","aria-hidden":"true",children:/* @__PURE__ */s("span",{className:"icon icon-spinner lb:animate-spin lb:min-w-7 lb:min-h-7"})}),
|
|
211
|
-
/* @__PURE__ */s("p",{className:"lb:text-sm",id:"loader-text",children:e})]})}function
|
|
212
|
-
return c(u,{children:[m&&/* @__PURE__ */s(
|
|
211
|
+
/* @__PURE__ */s("p",{className:"lb:text-sm",id:"loader-text",children:e})]})}function pt({onSelect:e,onCrop:t,onDelete:n,onFolderChange:l,onRename:r,onPageChange:a,onFiltersChange:i,images:o,loadingImages:d,imagesError:b,deleting:m,uploadedImage:h,pagination:p,currentPage:f,galleryFilters:g,debouncedFilters:v,allowedActions:y,resolvedAccept:w,allowedCategories:x,folderConfig:k,filterConfig:C,loadingConfig:S,resetUpload:N}){/* @__PURE__ */
|
|
212
|
+
return c(u,{children:[m&&/* @__PURE__ */s(ht,{text:"Eliminando archivo..."}),h&&/* @__PURE__ */c(ye,{variant:"success",toast:!0,onClose:N,children:[
|
|
213
213
|
/* @__PURE__ */s("span",{className:"icon icon-tick-white icon--2sm"})," Archivo subido correctamente: ",h.filename]}),
|
|
214
|
-
/* @__PURE__ */s(
|
|
214
|
+
/* @__PURE__ */s(bt,{onSelect:e,onCrop:t,onDelete:n,deletingId:m,images:o,loading:d,error:b,filters:g,debouncedFilters:v,onFiltersChange:i,filterConfig:C,loadingConfig:S,allowedActions:y,resolvedAccept:w,allowedCategories:x,folderConfig:k,onFolderChange:l,onRename:r}),p&&!d&&/* @__PURE__ */s(mt,{currentPage:p.page||f,totalPages:p.pages||1,onPageChange:a,disabled:d||m})]})}function ft({previewUrl:e,fileName:n}){const[l,a]=t(!1),[i,o]=t(!1),u=r(null);/* @__PURE__ */
|
|
215
215
|
return c("div",i?{className:"lb:flex lb:flex-col lb:items-center lb:justify-center lb:p-8 lb:min-h-[200px] lb:bg-gray-100 lb:rounded-lg",children:[
|
|
216
216
|
/* @__PURE__ */s("span",{className:"icon icon-video icon--xl lb:text-gray-400 lb:mb-4"}),
|
|
217
217
|
/* @__PURE__ */s("p",{className:"lb:text-sm lb:text-gray-600",children:"No se puede reproducir el video"}),
|
|
@@ -219,7 +219,7 @@ return c("div",i?{className:"lb:flex lb:flex-col lb:items-center lb:justify-cent
|
|
|
219
219
|
/* @__PURE__ */s("video",{ref:u,src:e,className:"lb:absolute lb:inset-0 lb:w-full lb:h-full lb:object-contain",onEnded:()=>{a(!1)},onError:()=>{o(!0)},onPlay:()=>a(!0),onPause:()=>a(!1),controls:!0,preload:"metadata",children:"Tu navegador no soporta la reproduccion de video."}),!l&&/* @__PURE__ */s("button",{type:"button",onClick:()=>{u.current&&(l?u.current.pause():u.current.play(),a(!l))},className:"lb:absolute lb:inset-0 lb:flex lb:items-center lb:justify-center lb:bg-black/30 lb:hover:bg-black/40 lb:transition-colors lb:cursor-pointer","aria-label":"Reproducir video",children:/* @__PURE__ */s("div",{className:"lb:w-16 lb:h-16 lb:rounded-full lb:bg-white/90 lb:flex lb:items-center lb:justify-center lb:shadow-lg",children:/* @__PURE__ */s("span",{className:"icon icon-play icon--lg lb:text-gray-800 lb:ml-1"})})}),
|
|
220
220
|
/* @__PURE__ */c("div",{className:"lb:absolute lb:top-2 lb:right-2 lb:bg-black/60 lb:text-white lb:px-2 lb:py-1 lb:rounded lb:text-xs lb:flex lb:items-center lb:gap-1",children:[
|
|
221
221
|
/* @__PURE__ */s("span",{className:"icon icon-video icon--xs"}),
|
|
222
|
-
/* @__PURE__ */s("span",{children:"VIDEO"})]})]})}function
|
|
222
|
+
/* @__PURE__ */s("span",{children:"VIDEO"})]})]})}function gt({previewUrl:e,fileName:n,fileSize:l}){const[a,i]=t(!1),[o,d]=t(!1),[b,m]=t(0),[h,p]=t(0),f=r(null),g=e=>{if(!e||isNaN(e))return"0:00";return`${Math.floor(e/60)}:${Math.floor(e%60).toString().padStart(2,"0")}`};/* @__PURE__ */
|
|
223
223
|
return c("div",o?{className:"lb:flex lb:flex-col lb:items-center lb:justify-center lb:p-8 lb:min-h-50 lb:bg-gray-100 lb:rounded-lg",children:[
|
|
224
224
|
/* @__PURE__ */s("span",{className:"icon icon-audio icon--xl lb:text-gray-400 lb:mb-4"}),
|
|
225
225
|
/* @__PURE__ */s("p",{className:"lb:text-sm lb:text-gray-600",children:"No se puede reproducir el audio"}),
|
|
@@ -233,20 +233,20 @@ return c("div",o?{className:"lb:flex lb:flex-col lb:items-center lb:justify-cent
|
|
|
233
233
|
/* @__PURE__ */s("span",{children:"/"}),
|
|
234
234
|
/* @__PURE__ */s("span",{children:g(b)}),l&&/* @__PURE__ */c(u,{children:[
|
|
235
235
|
/* @__PURE__ */s("span",{children:"•"}),
|
|
236
|
-
/* @__PURE__ */s("span",{children:
|
|
236
|
+
/* @__PURE__ */s("span",{children:He(l)})]})]}),
|
|
237
237
|
/* @__PURE__ */s("div",{className:"lb:w-full lb:max-w-xs lb:mt-3",children:/* @__PURE__ */s("div",{className:"lb:h-1.5 lb:bg-gray-200 lb:rounded-full lb:overflow-hidden lb:cursor-pointer",onClick:e=>{if(!f.current||!b)return;const t=e.currentTarget.getBoundingClientRect(),n=e.clientX-t.left;f.current.currentTime=n/t.width*b},role:"slider","aria-label":"Progreso de audio","aria-valuenow":h,"aria-valuemin":0,"aria-valuemax":b,tabIndex:0,children:/* @__PURE__ */s("div",{className:"lb:h-full lb:bg-purple-500 lb:rounded-full lb:transition-all lb:duration-100 lb:pointer-events-none",style:{width:b>0?h/b*100+"%":"0%"}})})}),
|
|
238
|
-
/* @__PURE__ */s("audio",{ref:f,src:e,onPlay:()=>i(!0),onPause:()=>i(!1),onTimeUpdate:()=>{f.current&&p(f.current.currentTime)},onLoadedMetadata:()=>{f.current&&m(f.current.duration)},onEnded:()=>{i(!1),p(0)},onError:()=>{d(!0)},preload:"metadata"})]})}function
|
|
238
|
+
/* @__PURE__ */s("audio",{ref:f,src:e,onPlay:()=>i(!0),onPause:()=>i(!1),onTimeUpdate:()=>{f.current&&p(f.current.currentTime)},onLoadedMetadata:()=>{f.current&&m(f.current.duration)},onEnded:()=>{i(!1),p(0)},onError:()=>{d(!0)},preload:"metadata"})]})}function vt({file:e,image:l,onDiscard:r,onRetry:a,onDownload:i,onSelect:o,showRetry:u=!1,disabled:d=!1,showCropButton:b,selectedFolder:m=null,onFolderChange:h=null,folderConfig:p=null}){const f=e||l,[g,v]=t(null),[y,w]=t({name:"",size:"",type:"",category:"unknown"}),[x,k]=t(!1),[C,S]=t(!1),[N,E]=t(""),$="image"===y.category,_="video"===y.category,z="audio"===y.category,T=void 0!==b?b:$;n(()=>{if(!f)return void v(null);const e=URL.createObjectURL(f);v(e);const t=f.name||"archivo",n=f.type||"",l=(e=>e?e.startsWith("image/")?"image":e.startsWith("video/")?"video":e.startsWith("audio/")?"audio":"application/pdf"===e||e.includes("document")||e.includes("msword")||e.includes("spreadsheet")||e.includes("presentation")||e.startsWith("text/")?"document":"unknown":"unknown")(n),r=(e=>{const t=e?.split(".")[0]?.toLowerCase()||"";return["ai-image","ai_image","generated","imagen-ia","imagen_ia"].some(e=>t.startsWith(e))})(t);if(w({name:t,size:He(f.size||0),type:n,category:l}),r)E(""),S(!1);else{const e=t.split(".")[0];E(e)}return()=>{URL.revokeObjectURL(e)}},[f]);if(!f||!g)return null;/* @__PURE__ */
|
|
239
239
|
return c("div",{className:"lb:w-full lb:max-w-full lb:bg-white lb:border lb:border-gray-200 lb:rounded-lg lb:px-1 lb:sm:px-3 lb:py-2 lb:m-0 lb:shadow-sm lb:overflow-hidden lb:box-border",children:[
|
|
240
240
|
/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:justify-between lb:mb-4 lb:px-1",children:[
|
|
241
241
|
/* @__PURE__ */s("h3",{className:"lb:text-sm lb:font-medium lb:text-gray-700",children:(()=>{switch(y.category){case"image":return"Vista previa de imagen";case"video":return"Vista previa de video";case"audio":return"Vista previa de audio";case"document":return"Vista previa de documento";default:return"Vista previa de archivo"}})()}),
|
|
242
242
|
/* @__PURE__ */s("button",{type:"button",onClick:r,disabled:d,className:"lb:p-1.5 lb:text-gray-400 lb:cursor-pointer lb:hover:text-gray-600 lb:hover:bg-red-300 lb:rounded lb:transition-colors lb:disabled:opacity-50 lb:disabled:cursor-not-allowed","aria-label":"Descartar archivo",title:"Descartar archivo",children:/* @__PURE__ */s("span",{className:"icon icon-close-small icon--md"})})]}),
|
|
243
|
-
/* @__PURE__ */s("div",{className:"lb:flex lb:justify-center lb:content-stretch lb:items-stretch",children:/* @__PURE__ */c("div",{className:"lb:flex lb:flex-col lb:justify-stretch lb:content-stretch",children:[p?.showFolderSelector&&h&&/* @__PURE__ */s("div",{className:"lb:mb-4 lb:px-1 lb:flex lb:items-stretch lb:justify-stretch",children:/* @__PURE__ */s(
|
|
243
|
+
/* @__PURE__ */s("div",{className:"lb:flex lb:justify-center lb:content-stretch lb:items-stretch",children:/* @__PURE__ */c("div",{className:"lb:flex lb:flex-col lb:justify-stretch lb:content-stretch",children:[p?.showFolderSelector&&h&&/* @__PURE__ */s("div",{className:"lb:mb-4 lb:px-1 lb:flex lb:items-stretch lb:justify-stretch",children:/* @__PURE__ */s(at,{value:m?.slug||m,onChange:h,allowCreate:!1!==p?.allowCreateFolder,label:"Guardar en carpeta",showAssetCount:!0,className:"lb:w-full",allowedSlugs:p?.include?.length>0?p.include:null,mode:"upload",disabled:d})}),
|
|
244
244
|
/* @__PURE__ */c("div",{className:"lb:flex lb:flex-col lb:justify-center lb:md:flex-row lb:gap-2 lb:md:gap-6",children:[
|
|
245
245
|
/* @__PURE__ */c("div",{className:"lb:flex-1 lb:flex lb:flex-col lb:items-center lb:justify-center"+($?" lb:min-w-100":""),children:[$?/* @__PURE__ */c("div",{className:"lb:relative lb:w-full lb:max-w-md lb:aspect-video lb:bg-gray-100 lb:rounded-lg lb:overflow-hidden lb:cursor-zoom-in lb:hover:ring-2 lb:hover:ring-brand-blue-800 lb:transition-all",onClick:()=>k(!0),role:"button",tabIndex:0,onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),k(!0))},"aria-label":"Click para ver imagen en tamano completo",title:"Click para ver en tamano completo",children:[
|
|
246
246
|
/* @__PURE__ */s("img",{src:g,alt:"Vista previa",className:"lb:absolute lb:inset-0 lb:w-full lb:h-full lb:object-contain"}),
|
|
247
247
|
/* @__PURE__ */c("div",{className:"lb:absolute lb:top-2 lb:right-2 lb:bg-black/50 lb:text-white lb:px-2 lb:py-1 lb:rounded lb:text-xs lb:flex lb:items-center lb:gap-1",children:[
|
|
248
248
|
/* @__PURE__ */s("span",{className:"icon icon-search-white icon--xs"}),
|
|
249
|
-
/* @__PURE__ */s("span",{className:"lb:hidden lb:sm:inline",children:"Ampliar"})]})]}):_?/* @__PURE__ */s(
|
|
249
|
+
/* @__PURE__ */s("span",{className:"lb:hidden lb:sm:inline",children:"Ampliar"})]})]}):_?/* @__PURE__ */s(ft,{previewUrl:g,fileName:y.name}):z?/* @__PURE__ */s(gt,{previewUrl:g,fileName:y.name,fileSize:f?.size}):/* @__PURE__ */s(Ke,{file:f,mimeType:y.type,category:y.category}),$&&/* @__PURE__ */s("div",{className:"lb:mt-3 lb:text-center lb:space-y-1 lb:w-full",children:/* @__PURE__ */s("div",{className:"lb:rounded-sm lb:w-fit lb:gap-0.5 lb:p-0.5 lb:min-w-fit lb:mx-auto",children:/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:justify-center lb:gap-3 lb:text-xs lb:text-gray-500",children:[
|
|
250
250
|
/* @__PURE__ */s("span",{children:y.size}),
|
|
251
251
|
/* @__PURE__ */s("span",{children:"•"}),
|
|
252
252
|
/* @__PURE__ */s("span",{children:y.type.split("/")[1]?.toUpperCase()||"FILE"})]})})})]}),
|
|
@@ -263,19 +263,19 @@ return c("div",{className:"lb:w-full lb:max-w-full lb:bg-white lb:border lb:bord
|
|
|
263
263
|
/* @__PURE__ */s("span",{children:"Descargar"})]}),
|
|
264
264
|
/* @__PURE__ */c("button",{type:"button",onClick:()=>{N.trim()?(S(!1),o&&o(y.name)):S(!0)},disabled:d,className:"lb:flex-1 lb:md:flex-none lb:flex lb:items-center lb:justify-center lb:gap-2 lb:px-4 lb:py-2.5 lb:bg-brand-blue-800 lb:border lb:border-brand-blue-800 lb:text-white lb:rounded-lg lb:hover:bg-brand-blue-1000 lb:cursor-pointer lb:hover:border-brand-blue-1000 lb:transition-colors lb:disabled:opacity-50 lb:disabled:cursor-not-allowed lb:text-sm lb:font-medium lb:shadow-sm","aria-label":T?"Seleccionar para recortar":"Seleccionar archivo",children:[
|
|
265
265
|
/* @__PURE__ */s("span",{className:"icon icon-tick-white icon--sm"}),
|
|
266
|
-
/* @__PURE__ */s("span",{children:"Seleccionar"})]})]})]})]})}),$&&/* @__PURE__ */s(
|
|
266
|
+
/* @__PURE__ */s("span",{children:"Seleccionar"})]})]})]})]})}),$&&/* @__PURE__ */s(Ye,{isOpen:x,src:g,alt:y.name,title:y.name,subtitle:`${y.size} • ${y.type.split("/")[1]?.toUpperCase()||"IMAGE"}`,onClose:()=>k(!1)})]})}const yt={image:["image/jpeg","image/png","image/webp","image/svg+xml"],video:["image/gif","video/mp4","video/webm","video/quicktime","video/x-msvideo"],document:["application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","text/plain","text/csv","application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation"],audio:["audio/mpeg","audio/wav","audio/ogg","audio/webm"]},wt={image:"JPG, PNG, SVG, WebP, GIF",video:"GIF, MP4, WebM, MOV, AVI",document:"PDF, DOC, DOCX, XLS, XLSX, TXT, PPT, PPTX",audio:"MP3, WAV, OGG"},xt=["image","video","document","audio"];function kt({file:e,setFile:n,previewUrl:r,setPreviewUrl:a,fileInputRef:i,onSelect:o,disabled:u,allowedCategories:d=null,resolvedAccept:b=null,selectedFolder:m=null,onFolderChange:h=null,folderConfig:p=null}){const[f,v]=t(!1),{acceptAttribute:y,allowedMimeTypes:w,formatLabels:x,categories:k}=l(()=>{if(b&&!b.isAllTypes)return{acceptAttribute:b.acceptString,allowedMimeTypes:new Set(b.mimeTypes),formatLabels:g(b),categories:b.categories.length>0?b.categories:xt};const e=null===d?xt:d,t=[],n=[];return e.forEach(e=>{yt[e]&&(t.push(...yt[e]),wt[e]&&n.push(wt[e]))}),{acceptAttribute:t.join(","),allowedMimeTypes:new Set(t),formatLabels:n.join(", "),categories:e}},[d,b]),C=b&&!b.isAllTypes?b.includesImages&&1===b.categories.length&&"image"===b.categories[0]:1===k.length&&"image"===k[0],S=e=>{if(n(e),e){const t=URL.createObjectURL(e);a(t)}else a(null)};/* @__PURE__ */
|
|
267
267
|
return c("div",{className:"lb:flex lb:flex-col lb:items-center lb:gap-6","aria-label":C?"Subir imagen desde dispositivo":"Subir archivo desde dispositivo",children:[
|
|
268
268
|
/* @__PURE__ */c("label",{htmlFor:"file-input",className:"lb:w-full lb:max-w-full lb:flex lb:flex-col lb:items-center lb:justify-center lb:border-2 lb:border-dashed lb:rounded-xl lb:p-8 lb:cursor-pointer lb:transition lb:box-border "+(f?"lb:border-brand-blue-1000 lb:bg-brand-blue-100 lb:scale-[1.02]":"lb:border-brand-blue-200 lb:hover:border-brand-blue-1000 lb:hover:to-bright-blue-200 lb:hover:from-brand-blue-50 lb:focus-within:border-brand-blue-800 lb:from-bright-blue-50 lb:to-brand-blue-50 lb:bg-linear-to-br"),tabIndex:0,style:{outline:"none"},onDragOver:e=>{e.preventDefault(),e.stopPropagation()},onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),u||v(!0)},onDragLeave:e=>{e.preventDefault(),e.stopPropagation(),e.currentTarget.contains(e.relatedTarget)||v(!1)},onDrop:e=>{if(e.preventDefault(),e.stopPropagation(),v(!1),u)return;const t=e.dataTransfer?.files;if(t&&t.length>0){const e=t[0];(e=>{if(!e||!e.type)return!1;if(b&&!b.isAllTypes)return function(e,t){if(!t||t.isAllTypes)return!0;if(!e)return!1;if(t.mimeTypes.includes(e))return!0;for(const n of t.categories)if(e.startsWith(n+"/"))return!0;return!1}(e.type,b);if(w.has(e.type))return!0;for(const t of k)if("image"===t&&e.type.startsWith("image/")||"video"===t&&e.type.startsWith("video/")||"audio"===t&&e.type.startsWith("audio/"))return!0;return!1})(e)&&S(e)}},children:[
|
|
269
269
|
/* @__PURE__ */s("span",{className:"icon icon-upload icon--lg lb:mb-2","aria-hidden":"true"}),
|
|
270
270
|
/* @__PURE__ */s("span",{className:"lb:font-medium lb:text-brand-blue-1000 lb:mb-1",children:C?"Haz clic o arrastra una imagen aqui":"Haz clic o arrastra un archivo aqui"}),
|
|
271
271
|
/* @__PURE__ */c("span",{className:"lb:text-sm lb:text-neutral-700",children:["Formatos permitidos: ",
|
|
272
272
|
/* @__PURE__ */s("span",{className:"lb:truncate lb:wrap-",children:x})]}),
|
|
273
|
-
/* @__PURE__ */s("input",{id:"file-input",ref:i,type:"file",accept:y,onChange:e=>{const t=e.target.files[0];S(t)},disabled:u,className:"lb:sr-only","aria-label":C?"Seleccionar imagen":"Seleccionar archivo"})]}),e&&/* @__PURE__ */s(
|
|
273
|
+
/* @__PURE__ */s("input",{id:"file-input",ref:i,type:"file",accept:y,onChange:e=>{const t=e.target.files[0];S(t)},disabled:u,className:"lb:sr-only","aria-label":C?"Seleccionar imagen":"Seleccionar archivo"})]}),e&&/* @__PURE__ */s(vt,{file:e,onDiscard:()=>{n(null),a(null),i.current&&(i.current.value="")},onDownload:()=>{},onSelect:t=>{if(e&&!u&&o)if(t&&t!==e.name){const n=new File([e],t,{type:e.type});o(n)}else o(e)},showRetry:!1,disabled:u,selectedFolder:m,onFolderChange:h,folderConfig:p})]})}const Ct="/api";const St=/* @__PURE__ */new Map;function Nt(e=!1){const[l,r]=t([]),[a,i]=t(!0),[o,s]=t(null);n(()=>{const t=`ai-services-${e}`,n=St.get(t),l=Date.now();if(n&&l-n.timestamp<864e5)return r(n.data),void i(!1);let a=!0;return(async()=>{try{const n=await function(e=!1){return Y({endpoint:"/ai/services",prod:e,basePath:Ct})}(e);if(!a)return;const i=n?.data||n?.result||[],o=Array.isArray(i)?i.map(e=>({label:e.name||e.label,slug:e.slug,type:e.type,description:e.description,image:e.image,costInfo:e.cost_info||null,supportsImageInput:e.supports_image_input||!1})):Object.entries(i).map(([e,t])=>({label:e,slug:t,type:"image_generation",description:null,image:null,costInfo:null,supportsImageInput:!1}));r(o),St.set(t,{data:o,timestamp:l})}catch(n){a&&s(n.message)}finally{a&&i(!1)}})(),()=>{a=!1}},[e]);return{services:l,loading:a,error:o,invalidateCache:()=>{St.delete(`ai-services-${e}`)}}}const Et=/* @__PURE__ */new Map;function $t(e=!1){const[n,l]=t(null),[r,a]=t(!1),[i,o]=t(null);return{params:n,loading:r,error:i,fetchParams:async t=>{a(!0),o(null);const n=`${e}-${t}`,r=Date.now(),i=Et.get(n);if(i&&r-i.timestamp<864e5)return l(i.data),a(!1),i.data;try{const a=await function({services:e=null,form:t=!1}={},n=!1){const l={};return e&&(l.services=e),!1!==t&&(l.form=t),Y({endpoint:"/ai/params"+(Object.keys(l).length?"?"+new URLSearchParams(l).toString():""),method:"GET",prod:n,basePath:"/api/atenea"})}({services:t,form:!1},e),i=a?.result?.data||a?.data||a?.result||a;return l(i),Et.set(n,{data:i,timestamp:r}),i}catch(s){return o(s.message),l(null),null}finally{a(!1)}},reset:()=>{o(null),l(null)}}}function _t({show:e=!1,message:t="Cargando...",className:n=""}){return e?/* @__PURE__ */s("div",{className:`lb:absolute lb:inset-0 lb:min-h-50 lb:bg-white/80 lb:backdrop-blur-sm lb:z-50 lb:flex lb:flex-col lb:items-center lb:justify-center ${n}`,"aria-live":"polite","aria-busy":"true",role:"status",children:/* @__PURE__ */c("div",{className:"lb:flex lb:flex-col lb:items-center lb:gap-4",children:[
|
|
274
274
|
/* @__PURE__ */s("span",{className:"icon icon-spinner lb:p-4 lb:animate-spin"}),
|
|
275
|
-
/* @__PURE__ */s("p",{className:"lb:text-brand-blue-1000 lb:font-medium lb:text-lg",children:t})]})}):null}function
|
|
275
|
+
/* @__PURE__ */s("p",{className:"lb:text-brand-blue-1000 lb:font-medium lb:text-lg",children:t})]})}):null}function zt({image:e,onDiscard:l,onRetry:r,onDownload:a,onSelect:i,showRetry:o=!1,disabled:u=!1,selectedFolder:d=null,onFolderChange:b=null,folderConfig:m=null}){const[h,p]=t(null),[f,g]=t({name:"",size:"",type:""}),[v,y]=t(!1),[w,x]=t(!1),[k,C]=t("");n(()=>{if(!e)return void p(null);const t=URL.createObjectURL(e);p(t);const n=e.name||"imagen.webp",l=(e=>{const t=e?.split(".")[0]?.toLowerCase()||"";return["ai-image","ai_image","generated","imagen-ia","imagen_ia"].some(e=>t.startsWith(e))})(n);return g({name:n,size:S(e.size||0),type:e.type||"image/webp"}),l?(C(""),x(!1)):C(n.split(".")[0]),()=>{URL.revokeObjectURL(t)}},[e]);const S=e=>{if(0===e)return"0 Bytes";const t=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,t)*100)/100+" "+["Bytes","KB","MB","GB"][t]};return e&&h?/* @__PURE__ */c("div",{className:"lb:w-full lb:max-w-full lb:bg-white lb:border lb:border-gray-200 lb:rounded-lg lb:px-1 lb:sm:px-3 lb:py-2 lb:m-0 lb:shadow-sm lb:overflow-hidden lb:box-border",children:[
|
|
276
276
|
/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:justify-between lb:mb-4 lb:px-1",children:[
|
|
277
277
|
/* @__PURE__ */s("h3",{className:"lb:text-sm lb:font-medium lb:text-gray-700",children:"Vista previa de imagen"}),
|
|
278
|
-
/* @__PURE__ */s("button",{type:"button",onClick:l,disabled:u,className:"lb:p-1.5 lb:text-gray-400 lb:cursor-pointer lb:hover:text-gray-600 lb:hover:bg-red-300 lb:rounded lb:transition-colors lb:disabled:opacity-50 lb:disabled:cursor-not-allowed","aria-label":"Descartar imagen",title:"Descartar imagen",children:/* @__PURE__ */s("span",{className:"icon icon-close-small icon--md"})})]}),m?.showFolderSelector&&b&&/* @__PURE__ */s("div",{className:"lb:mb-4 lb:px-1",children:/* @__PURE__ */s(
|
|
278
|
+
/* @__PURE__ */s("button",{type:"button",onClick:l,disabled:u,className:"lb:p-1.5 lb:text-gray-400 lb:cursor-pointer lb:hover:text-gray-600 lb:hover:bg-red-300 lb:rounded lb:transition-colors lb:disabled:opacity-50 lb:disabled:cursor-not-allowed","aria-label":"Descartar imagen",title:"Descartar imagen",children:/* @__PURE__ */s("span",{className:"icon icon-close-small icon--md"})})]}),m?.showFolderSelector&&b&&/* @__PURE__ */s("div",{className:"lb:mb-4 lb:px-1",children:/* @__PURE__ */s(at,{value:d?.slug||d,onChange:b,allowCreate:!1!==m?.allowCreateFolder,label:"Guardar en carpeta",showAssetCount:!0,allowedSlugs:m?.include?.length>0?m.include:null,mode:"upload",disabled:u})}),
|
|
279
279
|
/* @__PURE__ */c("div",{className:"lb:flex lb:flex-col lb:justify-center lb:md:flex-row lb:gap-2 lb:md:gap-6",children:[
|
|
280
280
|
/* @__PURE__ */c("div",{className:"lb:flex-1 lb:md:flex-[0.4] lb:flex lb:flex-col lb:items-center lb:justify-center",children:[
|
|
281
281
|
/* @__PURE__ */c("div",{className:"lb:relative lb:w-full lb:max-w-md lb:aspect-video lb:bg-gray-100 lb:rounded-lg lb:overflow-hidden lb:cursor-zoom-in lb:hover:ring-2 lb:hover:ring-brand-blue-800 lb:transition-all",onClick:()=>y(!0),role:"button",tabIndex:0,onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),y(!0))},"aria-label":"Click para ver imagen en tamaño completo",title:"Click para ver en tamaño completo",children:[
|
|
@@ -291,19 +291,19 @@ return c("div",{className:"lb:flex lb:flex-col lb:items-center lb:gap-6","aria-l
|
|
|
291
291
|
/* @__PURE__ */c("div",{className:"lb:flex lb:flex-col lb:gap-1",children:[
|
|
292
292
|
/* @__PURE__ */c("label",{htmlFor:"uploadImageId",className:"lb:flex lb:items-center lb:w-fit",children:[
|
|
293
293
|
/* @__PURE__ */s("span",{className:"lb:me-1 lb:text-sm",children:"Nombre:"}),
|
|
294
|
-
/* @__PURE__ */s("input",{id:"uploadImageId",onChange:e=>(e=>{const t=e.target.value.trim();C(e.target.value);const n=
|
|
294
|
+
/* @__PURE__ */s("input",{id:"uploadImageId",onChange:e=>(e=>{const t=e.target.value.trim();C(e.target.value);const n=De(t||"_");n.valid?t.length>0&&x(!1):x(n.error);const l=f.name,r=l.lastIndexOf("."),a=-1!==r?l.substring(r):".webp";g(e=>({...e,name:t?t+a:a}))})(e),value:k,className:"limbo-input-image-name lb:w-fit lb:px-1 lb:text-sm lb:font-medium lb:text-gray-800 lb:border lb:rounded lb:truncate lb:focus:outline lb:focus:outline-neutral-gray-100 lb:focus:transform-none lb:focus:shadow-none lb:focus:opacity-100 "+(w?"lb:border-red-1000 lb:bg-red-50":"lb:border-gray-300"),placeholder:"Escribe un nombre...",title:"El nombre es obligatorio",required:!0})]}),w&&/* @__PURE__ */s("span",{className:"lb:text-xs lb:text-red-1000 lb:ml-1",children:"string"==typeof w?w:"El nombre es obligatorio"})]}),o&&r&&/* @__PURE__ */c("button",{type:"button",onClick:r,disabled:u,className:"lb:flex-1 lb:md:flex-none lb:flex lb:items-center lb:justify-center lb:gap-2 lb:px-4 lb:py-2.5 lb:bg-white lb:border lb:border-gray-300 lb:text-gray-700 lb:rounded-lg lb:hover:bg-gray-50 lb:cursor-pointer lb:hover:border-gray-400 lb:transition-colors lb:disabled:opacity-50 lb:disabled:cursor-not-allowed lb:text-sm lb:font-medium","aria-label":"Intentarlo de nuevo",title:"Generar de nuevo con el mismo prompt",children:[
|
|
295
295
|
/* @__PURE__ */s("span",{className:"icon icon-refresh icon--sm"}),
|
|
296
296
|
/* @__PURE__ */s("span",{className:"lb:hidden lb:sm:inline",children:"Reintentar"}),
|
|
297
297
|
/* @__PURE__ */s("span",{className:"lb:sm:hidden",children:"Retry"})]}),
|
|
298
298
|
/* @__PURE__ */c("button",{type:"button",onClick:()=>{if(!h||u)return;const e=document.createElement("a");e.href=h,e.download=f.name,document.body.appendChild(e),e.click(),document.body.removeChild(e),a&&a()},disabled:u,className:"lb:flex-1 lb:cursor-pointer lb:md:flex-none lb:flex lb:items-center lb:justify-center lb:gap-2 lb:px-4 lb:py-2.5 lb:bg-white lb:border lb:border-gray-300 lb:text-gray-700 lb:rounded-lg lb:hover:bg-gray-50 lb:hover:border-gray-400 lb:transition-colors lb:disabled:opacity-50 lb:disabled:cursor-not-allowed lb:text-sm lb:font-medium","aria-label":"Descargar imagen",children:[
|
|
299
299
|
/* @__PURE__ */s("span",{className:"icon icon-download icon--sm"}),
|
|
300
300
|
/* @__PURE__ */s("span",{children:"Descargar"})]}),
|
|
301
|
-
/* @__PURE__ */c("button",{type:"button",onClick:()=>{const e=k.trim();if(!e)return void x("El nombre no puede estar vacío");const t=
|
|
301
|
+
/* @__PURE__ */c("button",{type:"button",onClick:()=>{const e=k.trim();if(!e)return void x("El nombre no puede estar vacío");const t=De(e);t.valid?(x(!1),i&&i(f.name)):x(t.error)},disabled:u,className:"lb:flex-1 lb:md:flex-none lb:flex lb:items-center lb:justify-center lb:gap-2 lb:px-4 lb:py-2.5 lb:bg-brand-blue-800 lb:border lb:border-brand-blue-800 lb:text-white lb:rounded-lg lb:hover:bg-brand-blue-1000 lb:cursor-pointer lb:hover:border-brand-blue-1000 lb:transition-colors lb:disabled:opacity-50 lb:disabled:cursor-not-allowed lb:text-sm lb:font-medium lb:shadow-sm","aria-label":"Seleccionar imagen para recortar",children:[
|
|
302
302
|
/* @__PURE__ */s("span",{className:"icon icon-tick-white icon--sm"}),
|
|
303
303
|
/* @__PURE__ */s("span",{children:"Seleccionar"})]})]})]}),
|
|
304
|
-
/* @__PURE__ */s(
|
|
304
|
+
/* @__PURE__ */s(Ye,{isOpen:v,src:h,alt:f.name,title:f.name,subtitle:`${f.size} • ${f.type.split("/")[1]?.toUpperCase()||"IMAGE"}`,onClose:()=>y(!1)})]}):null}function Tt(e){return new Promise((t,n)=>{const l=new FileReader;l.onload=()=>t(l.result),l.onerror=n,l.readAsDataURL(e)})}function At({prod:n,disabled:l,onSelect:r,selectedFolder:a,onFolderChange:i,folderConfig:o}){const d=Nt(n),b=$t(n),[m,h]=t(""),[p,f]=t(""),[g,v]=t({}),[y,w]=t(!1),[x,k]=t(null),[C,S]=t(null),[N,E]=t(null),[$,_]=t(!0),[z,T]=t(!1),[A,L]=t([null,null]),[I,P]=t([null,null]),[M,D]=t(null),R=[e.useRef(null),e.useRef(null)],O=e.useRef([0,0]);e.useEffect(()=>{if(!d.loading&&1===d.services.length){const e=d.services[0];f(e.slug),_(!1),b.fetchParams(e.slug,!0)}},[d.loading,d.services]),e.useEffect(()=>{if(!p)return;const e=b.params?.[p]?.parameters;if(e){const t=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default??""]));t.service=p,v(t)}},[p,b.params]);const F=e.useMemo(()=>{const e=d.services.find(e=>e.slug===p);if(e?.supportsImageInput)return!0;const t=b.params?.[p]?.parameters;return!!t&&Object.entries(t).some(([e,t])=>"image"===t.type||"file"===t.type||"image_data"===e||"image"===e||"reference_image"===e)},[p,d.services,b.params]),j=(e,t)=>{e&&(["image/jpeg","image/png","image/webp","image/svg+xml"].includes(e.type)?e.size>4194304?k("La imagen de referencia no puede superar los 4MB."):(L(n=>{const l=[...n];return l[t]=e,l}),P(n=>{const l=[...n];return l[t]&&URL.revokeObjectURL(l[t]),l[t]=URL.createObjectURL(e),l}),k(null)):k("Formato no soportado. Usa JPG, PNG, SVG o WebP."))},U=e=>t=>{j(t.target.files?.[0],e)},B=e=>t=>{t.preventDefault(),t.stopPropagation(),O.current[e]++,D(e)},W=e=>t=>{t.preventDefault(),t.stopPropagation(),O.current[e]--,0===O.current[e]&&D(null)},q=e=>{e.preventDefault(),e.stopPropagation()},V=e=>t=>{t.preventDefault(),t.stopPropagation(),O.current[e]=0,D(null),j(t.dataTransfer?.files?.[0],e)},H=e=>{L(t=>{const n=[...t];return n[e]=null,n}),P(t=>{const n=[...t];return n[e]&&URL.revokeObjectURL(n[e]),n[e]=null,n}),R[e]?.current&&(R[e].current.value="")};e.useEffect(()=>{const e=I;return()=>{e.forEach(e=>{e&&URL.revokeObjectURL(e)})}},[]);const K=e=>{const{name:t,value:n}=e.target;v(e=>({...e,[t]:n}))},G=async(e,t=!1)=>{e.preventDefault(),w(!0),k(null),S(null);try{t?g.prompt=m:h(g.prompt||"");const{image_data:e,...r}=g;let a={...r};A[0]&&(a.image=await Tt(A[0])),A[1]&&(a.image2=await Tt(A[1]));const i=await function(e,t=!1){return Y({endpoint:"/ai/generate",method:"POST",body:e,prod:t,basePath:Ct})}(a,n);let o=null;if(i?.data?.images&&Array.isArray(i.data.images)&&i.data.images.length>0?o=i.data.images[0]:i?.result?.images&&Array.isArray(i.result.images)&&i.result.images.length>0?o=i.result.images[0]:Array.isArray(i)&&i.length>0?o=i[0]:"string"==typeof i&&(o=i),!o)throw new Error("No se pudo extraer la imagen de la respuesta");if(o.startsWith("http"))try{const e=`${window.limboCore?.config?.getGlobal()?.prod?"https://limbo.lefebvre.es":"https://led-dev-limbo-dev.eu.els.local"}/api/atenea/proxy?url=${encodeURIComponent(o)}`,t=await fetch(e,{credentials:"include",headers:{Authorization:`Bearer ${window.limboCore?.apiClient?.token||""}`}});if(!t.ok)throw new Error(`Failed to download image: ${t.status}`);const n=await t.blob(),l=new File([n],"ai-image.webp",{type:n.type||"image/webp"});E(l)}catch(l){throw new Error(`Error downloading image via proxy: ${l.message}`)}else{const e=o.replace(/^data:image\/\w+;base64,/,""),t=atob(e),n=new Array(t.length);for(let a=0;a<t.length;a++)n[a]=t.charCodeAt(a);const l=new Uint8Array(n),r=new File([l],"ai-image.webp",{type:"image/webp"});E(r)}S(i?.data?.images||i?.result?.images||null)}catch(r){k(r.message||"Error al generar la imagen")}finally{w(!1)}};return d.loading?/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:justify-center lb:py-8",children:[
|
|
305
305
|
/* @__PURE__ */s("span",{className:"limbo-loader lb:mr-2"})," Cargando servicios IA..."]}):d.services.length?/* @__PURE__ */s("div",{className:"lb:flex lb:flex-col lb:mx-4 lb:pb-2",children:/* @__PURE__ */c(u,$?{children:[
|
|
306
|
-
/* @__PURE__ */s("h3",{id:"aiSelectDescription",className:"lb:text-2xl lb:font-semibold lb:text-brand-blue-1000 lb:mb-3",children:"Selecciona el modelo IA"}),d.error&&/* @__PURE__ */s(
|
|
306
|
+
/* @__PURE__ */s("h3",{id:"aiSelectDescription",className:"lb:text-2xl lb:font-semibold lb:text-brand-blue-1000 lb:mb-3",children:"Selecciona el modelo IA"}),d.error&&/* @__PURE__ */s(ye,{variant:"danger",children:d.error}),
|
|
307
307
|
/* @__PURE__ */s("div",{className:"lb:flex lb:flex-row lb:flex-wrap lb:justify-around lb:items-stretch lb:justify-items-stretch lb:content-stretch lb:gap-3 lb:w-full lb:max-w-7xl",children:d.services.map(e=>/* @__PURE__ */c("button",{type:"button",onClick:()=>{f(e.slug),_(!1),v({}),S(null),k(null),E(null),b.fetchParams(e.slug,!0)},disabled:d.loading||l,className:`lb:group lb:relative lb:p-4 lb:rounded-lg lb:border-2 lb:transition-all lb:duration-200 lb:overflow-hidden lb:flex lb:flex-col lb:items-center lb:justify-center lb:min-h-30 lb:grow basis-sm lb:min-w-70 lb:border-gray-200 lb:hover:border-brand-blue-800 lb:hover:shadow-md lb:hover:text-black lb:lg:w-min ${d.loading||l?"lb:opacity-50 lb:cursor-not-allowed":"lb:cursor-pointer"} `,style:{position:"relative"},children:[e.image&&/* @__PURE__ */s("div",{className:"lb:absolute lb:inset-0 lb:bg-cover lb:bg-center lb:transition-opacity lb:duration-200 lb:group-hover:opacity-35",style:{backgroundImage:`url(${e.image})`,opacity:.2}}),
|
|
308
308
|
/* @__PURE__ */c("div",{className:"lb:relative lb:z-10 lb:flex lb:flex-col lb:items-center lb:justify-center lb:gap-2 lb:text-center",children:[
|
|
309
309
|
/* @__PURE__ */s("span",{className:"lb:text-base lb:font-semibold lb:text-neutral-black-000",children:e.label}),e.description&&/* @__PURE__ */s("span",{className:"lb:text-sm lb:text-gray-950 lb:line-clamp-2 lb:drop-shadow lb:drop-shadow-neutral-white-000",children:e.description})]}),e.costInfo&&/* @__PURE__ */s("span",{className:"lb:absolute lb:top-0 lb:left-1 lb:inline-flex lb:items-center lb:gap-1 lb:py-0 lb:px-1 lb:mt-1 lb:text-xs lb:font-medium lb:text-warning-1000 lb:rounded-md lb:group-hover:bg-white/90",style:{zoom:"82%"},children:e.costInfo})]},e.slug))})]}:{children:[
|
|
@@ -311,13 +311,13 @@ return c("div",{className:"lb:flex lb:flex-col lb:items-center lb:gap-6","aria-l
|
|
|
311
311
|
/* @__PURE__ */s("h3",{className:"lb:text-2xl lb:font-semibold lb:text-brand-blue-1000",children:d.services.find(e=>e.slug===p)?.label||"Generación IA"}),d.services.find(e=>e.slug===p)?.costInfo&&/* @__PURE__ */c("div",{title:"Coste estimado por imagen que le cuesta a la empresa, este coste depende de la calidad de la imagen generada y puede variar según el proveedor IA, ten en cuenta este coste para hacer un uso más responsable del servicio IA",className:"lb:flex lb:items-center lb:gap-1","aria-description":"Coste estimado por imagen que le cuesta a la empresa, este coste depende de la calidad de la imagen generada y puede variar según el proveedor IA, ten en cuenta este coste para hacer un uso más responsable del servicio IA",children:[
|
|
312
312
|
/* @__PURE__ */c("span",{className:"lb:inline-flex lb:items-center lb:gap-1 lb:px-2 lb:py-0.5 lb:text-xs lb:font-medium lb:text-warning-1000 lb:bg-yellow-200/60 lb:rounded-full lb:border lb:border-warning-1000 lb:select-none",children:[
|
|
313
313
|
/* @__PURE__ */s("span",{className:"icon icon-euro-blue icon--2sm icon--warning",style:{filter:"var(--limbo-icon-warning-dark)"}}),"Coste:"," ",d.services.find(e=>e.slug===p)?.costInfo]}),
|
|
314
|
-
/* @__PURE__ */s("span",{className:"icon icon-info lb:cursor-help"})]})]}),b.loading&&/* @__PURE__ */s("div",{children:"Cargando parámetros..."}),b.error&&/* @__PURE__ */s(
|
|
314
|
+
/* @__PURE__ */s("span",{className:"icon icon-info lb:cursor-help"})]})]}),b.loading&&/* @__PURE__ */s("div",{children:"Cargando parámetros..."}),b.error&&/* @__PURE__ */s(ye,{variant:"danger",children:b.error}),p&&(()=>{const e=b.params?.[p]?.parameters;if(!e)return null;const t=Object.entries(e).filter(([e,t])=>!t.hidden&&"image"!==t.type&&"file"!==t.type),n=t.filter(([e])=>e.toLowerCase().includes("prompt")||e.toLowerCase().includes("query")),r=t.filter(([e])=>!e.toLowerCase().includes("prompt")&&!e.toLowerCase().includes("query")),a=(e,t)=>{let n=t.placeholder||"";n||(n="integer"===t.type?t.minValue&&t.maxValue?`Entre ${t.minValue} y ${t.maxValue}`:t.minValue?`Mínimo ${t.minValue}`:t.maxValue?`Máximo ${t.maxValue}`:"Introduce un número":e.toLowerCase().includes("prompt")?"Describe la imagen que deseas generar...":e.toLowerCase().includes("negative")?"Elementos a evitar en la imagen...":`Introduce ${(t.label||e).toLowerCase()}`);const r=e.toLowerCase().includes("prompt")||e.toLowerCase().includes("query");/* @__PURE__ */
|
|
315
315
|
return c("div",{className:"lb:flex lb:flex-col lb:gap-1",children:[
|
|
316
|
-
/* @__PURE__ */c("label",{htmlFor:`ai-${e}`,className:"lb:text-xs lb:font-medium lb:text-brand-blue-1000",children:[t.label||e,t.required&&/* @__PURE__ */s("span",{className:"lb:text-red-1000 lb:ml-1",children:"*"})]}),t.options?/* @__PURE__ */s("select",{id:`ai-${e}`,name:e,value:g[e]??"",onChange:
|
|
317
|
-
return c("div",{className:"lb:h-fit lb:w-full",children:[d.services.length>1&&/* @__PURE__ */c("button",{type:"button",onClick:()=>{_(!0),f(""),v({}),S(null),k(null),E(null),
|
|
316
|
+
/* @__PURE__ */c("label",{htmlFor:`ai-${e}`,className:"lb:text-xs lb:font-medium lb:text-brand-blue-1000",children:[t.label||e,t.required&&/* @__PURE__ */s("span",{className:"lb:text-red-1000 lb:ml-1",children:"*"})]}),t.options?/* @__PURE__ */s("select",{id:`ai-${e}`,name:e,value:g[e]??"",onChange:K,className:"limbo-input",disabled:l,title:t.label||e,children:t.options.map(e=>/* @__PURE__ */s("option",{value:e,children:e},e))}):r?/* @__PURE__ */s("textarea",{id:`ai-${e}`,name:e,value:g[e]??"",onChange:K,className:"limbo-input lb:resize-none lb:overflow-y-auto",disabled:l,required:t.required,placeholder:n,title:t.label||e,rows:3,style:{maxHeight:"9rem",minHeight:"3rem"},onInput:e=>{e.target.style.height="auto";const t=Math.min(e.target.scrollHeight,144);e.target.style.height=`${t}px`}}):/* @__PURE__ */s("input",{id:`ai-${e}`,type:"integer"===t.type?"number":"text",name:e,value:g[e]??"",onChange:K,className:"limbo-input",disabled:l,required:t.required,min:t.minValue,max:t.maxValue,placeholder:n,title:t.label||e})]},e)};/* @__PURE__ */
|
|
317
|
+
return c("div",{className:"lb:h-fit lb:w-full",children:[d.services.length>1&&/* @__PURE__ */c("button",{type:"button",onClick:()=>{_(!0),f(""),v({}),S(null),k(null),E(null),H()},className:"lb:flex lb:cursor-pointer lb:items-center lb:gap-2 lb:text-brand-blue-800 lb:hover:text-brand-blue-1000 lb:mb-4 lb:font-medium",children:[
|
|
318
318
|
/* @__PURE__ */s("span",{className:"icon icon-arrow-left"}),"Volver al menú de servicios"]}),
|
|
319
319
|
/* @__PURE__ */c("div",{className:"lb:relative",children:[
|
|
320
|
-
/* @__PURE__ */c("form",{onSubmit:
|
|
320
|
+
/* @__PURE__ */c("form",{onSubmit:G,"data-type":"ai",className:"lb:flex lb:flex-col lb:gap-3 lb:mt-4 lb:border-t lb:pt-4 lb:border-brand-blue-200","aria-label":"Formulario generación IA",children:[x&&/* @__PURE__ */s(ye,{variant:"danger",className:"lb:mb-2",children:x}),
|
|
321
321
|
/* @__PURE__ */s("div",{className:"lb:flex lb:flex-col lb:gap-3",children:n.map(([e,t])=>a(e,t))}),F&&/* @__PURE__ */c("div",{className:"lb:flex lb:flex-col lb:gap-2 lb:mt-1",children:[
|
|
322
322
|
/* @__PURE__ */c("label",{className:"lb:text-xs lb:font-medium lb:text-brand-blue-1000",children:["Imágenes de referencia",
|
|
323
323
|
/* @__PURE__ */s("span",{className:"lb:text-neutral-gray-500 lb:ml-1 lb:font-normal",children:"(opcional, máx. 2)"})]}),
|
|
@@ -327,7 +327,7 @@ return c("div",{className:"lb:h-fit lb:w-full",children:[d.services.length>1&&/*
|
|
|
327
327
|
/* @__PURE__ */c("p",{className:"lb:text-xs lb:text-neutral-gray-500 lb:mb-0.5",children:["Imagen ",e+1]}),
|
|
328
328
|
/* @__PURE__ */s("p",{className:"lb:text-sm lb:text-neutral-gray-700 lb:truncate",children:A[e].name}),
|
|
329
329
|
/* @__PURE__ */c("p",{className:"lb:text-xs lb:text-neutral-gray-500",children:[(A[e].size/1024).toFixed(0)," KB"]})]}),
|
|
330
|
-
/* @__PURE__ */s("button",{type:"button",onClick:()=>
|
|
330
|
+
/* @__PURE__ */s("button",{type:"button",onClick:()=>H(e),disabled:l||y,className:"lb:p-1.5 lb:text-neutral-gray-500 lb:cursor-pointer lb:hover:text-red-1000 lb:hover:bg-red-50 lb:rounded lb:transition-colors",title:`Quitar imagen ${e+1}`,children:/* @__PURE__ */c("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[
|
|
331
331
|
/* @__PURE__ */s("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),
|
|
332
332
|
/* @__PURE__ */s("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},e):(0===e||A[0])&&/* @__PURE__ */c("label",{className:"lb:flex lb:items-center lb:justify-center lb:gap-2 lb:px-3 lb:py-2.5 lb:border lb:border-dashed lb:rounded-lg lb:cursor-pointer lb:transition-colors lb:text-sm "+(M===e?"lb:border-brand-blue-800 lb:bg-brand-blue-50/50 lb:text-brand-blue-800":"lb:border-neutral-gray-300 lb:text-neutral-gray-700 lb:hover:border-brand-blue-800 lb:hover:bg-brand-blue-50/30"),onDragEnter:B(e),onDragLeave:W(e),onDragOver:q,onDrop:V(e),children:[
|
|
333
333
|
/* @__PURE__ */c("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[
|
|
@@ -338,21 +338,21 @@ return c("div",{className:"lb:h-fit lb:w-full",children:[d.services.length>1&&/*
|
|
|
338
338
|
/* @__PURE__ */c("button",{type:"button",onClick:()=>T(!z),className:"lb:flex lb:items-center lb:gap-2 lb:text-sm lb:font-medium lb:text-brand-blue-800 lb:hover:text-brand-blue-1000 lb:mb-3 lb:transition-colors",children:[
|
|
339
339
|
/* @__PURE__ */s("svg",{className:"lb:w-4 lb:h-4 lb:transition-transform "+(z?"lb:rotate-90":""),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),"Opciones avanzadas",!z&&/* @__PURE__ */c("span",{className:"lb:text-xs lb:text-gray-500",children:["(",r.length," opciones)"]})]}),z&&/* @__PURE__ */s("div",{className:"lb:grid lb:grid-cols-2 lb:lg:grid-cols-3 lb:xl:grid-cols-4 lb:gap-3 lb:animate-fadeIn",children:r.map(([e,t])=>a(e,t))})]}),
|
|
340
340
|
/* @__PURE__ */s("button",{type:"submit",disabled:y||l,title:y?"Generando imagen...":N?"Generar otra imagen":"Generar imagen",className:"limbo-btn lb:w-full lb:mt-2 "+(y?"lb:cursor-not-allowed limbo-btn-disabled":"limbo-btn-primary"),style:{minHeight:44},children:y?"Generando imagen...":N?"Generar otra imagen":"Generar imagen"})]}),
|
|
341
|
-
/* @__PURE__ */s(
|
|
341
|
+
/* @__PURE__ */s(_t,{show:y,message:"Generando imagen con IA..."})]})]})})(),N&&/* @__PURE__ */s("div",{className:"lb:mt-6 lb:md:w-full lb:mx-auto",children:/* @__PURE__ */s(zt,{image:N,onDiscard:()=>{E(null),S(null),k(null)},onRetry:e=>G(e,!0),onDownload:()=>{},onSelect:e=>{if(r){const t=N||C;if(e&&t&&e!==t.name){const n=new File([t],e,{type:t.type});r(n)}else r(t)}},showRetry:!0,disabled:y||l,selectedFolder:a,onFolderChange:i,folderConfig:o})})]})}):/* @__PURE__ */s(ye,{variant:"warning",children:"No hay servicios IA disponibles."})}const Lt="/api";const It=/* @__PURE__ */new Map;function Pt(e=!1){const[l,r]=t([]),[a,i]=t(!0),[o,s]=t(null);n(()=>{const t=`stock-services-${e}`,n=It.get(t),l=Date.now();if(n&&l-n.timestamp<864e5)return r(n.data),void i(!1);let a=!0;return(async()=>{try{const n=await function(e=!1){return Y({endpoint:"/stock/services",prod:e,basePath:Lt})}(e);if(!a)return;if(204===n?.httpCode||null===n?.data)return r([]),s("No hay servicios de stock disponibles en este momento"),void It.set(t,{data:[],timestamp:l});const i=n?.data||n?.result||[],o=Array.isArray(i)?i.map(e=>({label:e.name||e.label,slug:e.slug,type:e.type,description:e.description,image:e.image})):Object.entries(i).map(([e,t])=>({label:e,slug:t,type:"stock_image",description:null,image:null}));r(o),It.set(t,{data:o,timestamp:l})}catch(n){a&&s(n.message)}finally{a&&i(!1)}})(),()=>{a=!1}},[e]);return{services:l,loading:a,error:o,invalidateCache:()=>{It.delete(`stock-services-${e}`)}}}function Mt({isOpen:e,image:l,onSelect:r,onCancel:a}){const[i,o]=t(null),[d,b]=t(!1),[m,h]=t(!1),[p,f]=t(!1);n(()=>{e&&l&&(o(l.previewUrl),b(!1),h(!1),f(!1))},[e,l]);const g=/* @__PURE__ */c("div",{className:"lb:flex lb:gap-2 lb:ml-4 lb:shrink-0",children:[
|
|
342
342
|
/* @__PURE__ */s("button",{type:"button",onClick:a,className:"lb:px-4 lb:py-2 lb:text-sm lb:font-medium lb:text-white lb:border lb:border-white/30 lb:rounded-md lb:hover:bg-white/10 lb:transition-colors lb:cursor-pointer",children:"Cancelar"}),
|
|
343
343
|
/* @__PURE__ */s("button",{type:"button",onClick:r,className:"lb:px-4 lb:py-2 lb:text-sm lb:font-medium lb:bg-brand-blue-800 lb:text-white lb:rounded-md lb:hover:bg-brand-blue-1000 lb:transition-colors lb:cursor-pointer",children:"Seleccionar"})]});/* @__PURE__ */
|
|
344
|
-
return s(
|
|
344
|
+
return s(Fe,{isOpen:e,onClose:a,title:l?.title||"Previsualizar imagen",ariaLabel:"Previsualización de imagen externa",headerActions:g,children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center lb:w-full lb:h-full lb:p-4",children:p?/* @__PURE__ */c("div",{className:"lb:text-white/70 lb:text-sm lb:text-center",children:[
|
|
345
345
|
/* @__PURE__ */s("p",{children:"No se pudo cargar la imagen."}),
|
|
346
346
|
/* @__PURE__ */s("p",{className:"lb:text-xs lb:mt-1 lb:text-white/50",children:"Puedes seleccionarla igualmente para continuar."})]}):/* @__PURE__ */c(u,{children:[!m&&/* @__PURE__ */s("div",{className:"lb:absolute lb:inset-0 lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"limbo-loader"})}),
|
|
347
|
-
/* @__PURE__ */s("img",{src:i,alt:l?.title||"Imagen",onLoad:()=>h(!0),onError:()=>{!d&&l?.proxyUrl&&l.proxyUrl!==i?(b(!0),o(l.proxyUrl)):f(!0)},className:"lb:max-w-full lb:object-contain lb:rounded lb:transition-opacity lb:duration-300 "+(m?"lb:opacity-100":"lb:opacity-0"),style:{maxHeight:"calc(100vh - 130px)"}},i)]})})})}function
|
|
347
|
+
/* @__PURE__ */s("img",{src:i,alt:l?.title||"Imagen",onLoad:()=>h(!0),onError:()=>{!d&&l?.proxyUrl&&l.proxyUrl!==i?(b(!0),o(l.proxyUrl)):f(!0)},className:"lb:max-w-full lb:object-contain lb:rounded lb:transition-opacity lb:duration-300 "+(m?"lb:opacity-100":"lb:opacity-0"),style:{maxHeight:"calc(100vh - 130px)"}},i)]})})})}function Dt({src:t,fallbackSrc:n,alt:l}){const[r,a]=e.useState(t),[i,o]=e.useState(!1),[u,d]=e.useState(!1);e.useEffect(()=>{a(t),o(!1),d(!1)},[t]);/* @__PURE__ */
|
|
348
348
|
return c("div",{className:"lb:relative lb:w-full lb:h-full",children:[!u&&/* @__PURE__ */s("div",{className:"lb:absolute lb:inset-0 lb:bg-linear-to-r lb:from-gray-200 lb:via-gray-100 lb:to-gray-200 lb:animate-pulse"}),
|
|
349
|
-
/* @__PURE__ */s("img",{src:r,alt:l,onLoad:()=>d(!0),onError:()=>{!i&&n&&n!==r&&(o(!0),a(n))},className:"lb:object-cover lb:w-full lb:h-full lb:transition-opacity lb:duration-300 "+(u?"lb:opacity-100":"lb:opacity-0"),loading:"lazy"})]})}function
|
|
349
|
+
/* @__PURE__ */s("img",{src:r,alt:l,onLoad:()=>d(!0),onError:()=>{!i&&n&&n!==r&&(o(!0),a(n))},className:"lb:object-cover lb:w-full lb:h-full lb:transition-opacity lb:duration-300 "+(u?"lb:opacity-100":"lb:opacity-0"),loading:"lazy"})]})}function Rt({prod:n,disabled:l,onSelect:r,selectedFolder:a,onFolderChange:i,folderConfig:o}){const d=e.useRef(null),b=Pt(n),m=(e,t)=>{try{const n=sessionStorage.getItem(`limbo_stock_${e}`);return n?JSON.parse(n):t}catch{return t}},[h,p]=t(()=>m("selectedService","")),[f,g]=t(()=>m("dynamicForm",{})),[v,y]=t(()=>m("stockImages",[])),[w,x]=t(()=>m("currentPage",1)),[k,C]=t(()=>m("paginationInfo",null)),[S,N]=t(null),E=$t(n),[$,_]=t(!1),[z,T]=t(null),[A,L]=t(null),[I,P]=t(!0),[M,D]=t(!1),[R,O]=t(null),[F,j]=t(null);e.useEffect(()=>{sessionStorage.setItem("limbo_stock_selectedService",JSON.stringify(h))},[h]),e.useEffect(()=>{sessionStorage.setItem("limbo_stock_dynamicForm",JSON.stringify(f))},[f]),e.useEffect(()=>{sessionStorage.setItem("limbo_stock_stockImages",JSON.stringify(v))},[v]),e.useEffect(()=>{sessionStorage.setItem("limbo_stock_currentPage",JSON.stringify(w))},[w]),e.useEffect(()=>{sessionStorage.setItem("limbo_stock_paginationInfo",JSON.stringify(k))},[k]),e.useEffect(()=>{if(!b.loading&&1===b.services.length){const e=b.services[0];p(e.slug),P(!1),E.fetchParams(e.slug,!0)}},[b.loading,b.services]),e.useEffect(()=>{if(!h)return;const e=E.params?.[h]?.parameters;if(e){const t=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default??""]));t.service=h,g(t)}},[h,E.params]);const U=e=>{const{name:t,value:n}=e.target;g(e=>({...e,[t]:n}))},B=async(e=1)=>{_(!0),T(null),1===e&&y([]);try{let t;if(1===e){const n=E.params?.[h]?.parameters,l={...f};Object.entries(n||{}).forEach(([e,t])=>{e in l||(l[e]=t.default??"")}),l.per_page=parseInt(l.per_page),l.service=h,l.page=e,t=l,d.current={...l}}else t={...d.current,page:e};const l=await function(e,t=!1){return Y({endpoint:"/stock/search",method:"POST",body:e,prod:t,basePath:Lt})}(t,n),r=l?.data?.images||[];let a=l?.data?.pagination||null,i=null;a&&(i={total:a.total_count??a.total??r.length,per_page:a.per_page??(Array.isArray(r)?r.length:0),current_page:a.page??a.current_page??e}),y(W(Array.isArray(r)?r:[])),C(i),x(i?.current_page||e)}catch(t){T(t.message||"Error al buscar imágenes")}finally{_(!1)}},W=e=>{const t=/* @__PURE__ */new Set,n=[];return(e||[]).forEach((e,l)=>{const r=e.url||e.preview_url||e.full||e.preview;r&&!t.has(r)&&(t.add(r),n.push({...e,preview:e.preview_url||e.preview||e.url||e.full,full:e.url||e.full||e.preview_url,id:e.id||l,title:e.title||e.filename||`Imagen ${l+1}`,source:e.service||h,sourceTitle:b.services.find(e=>e.slug===h)?.label||h}))}),n},q=async e=>{e.preventDefault();const t=f.query||f.search||f.term||"";t.trim().length<5?T("La búsqueda debe tener al menos 5 caracteres"):(N(t),await B(1))},V=e=>{e<1||B(e)},H=async e=>{L(e.id),T(null);try{const t={service:h,image_id:e.id},l=await function(e,t=!1){return Y({endpoint:"/stock/download",method:"POST",body:e,prod:t,basePath:Lt})}(t,n),r=l?.result?.url||l?.result?.download_url||l?.data?.images?.url||l?.data?.url||l?.images?.url||l?.url;if(!r)throw console.error("Download response structure:",l),new Error("No se pudo obtener la URL de descarga");{const t=`${K({prod:n})}/api/atenea/proxy?url=${encodeURIComponent(r)}`,a=await fetch(t,{credentials:"include",headers:{Authorization:`Bearer ${X().token||""}`}});if(!a.ok)throw new Error(`Error al descargar imagen: ${a.status}`);const i=await a.blob(),o=l?.result?.filename||l?.data?.images?.filename||l?.data?.filename||`stock-${e.id}.jpg`,s=new File([i],o,{type:i.type||"image/jpeg"});O(s)}}catch(t){T(t.message||"No se pudo recuperar la imagen seleccionada")}finally{L(null)}};return b.loading?/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:justify-center lb:py-8",children:[
|
|
350
350
|
/* @__PURE__ */s("span",{className:"limbo-loader lb:mr-2"})," Cargando servicios de Stock..."]}):b.services.length?/* @__PURE__ */s("div",{className:"lb:flex lb:flex-col lb:mx-4 lb:pb-2",children:/* @__PURE__ */c(u,I?{children:[
|
|
351
|
-
/* @__PURE__ */s("h3",{className:"lb:text-2xl lb:font-semibold lb:text-brand-blue-1000 lb:mb-3",children:"Selecciona el servicio de Stock"}),b.error&&/* @__PURE__ */s(
|
|
351
|
+
/* @__PURE__ */s("h3",{className:"lb:text-2xl lb:font-semibold lb:text-brand-blue-1000 lb:mb-3",children:"Selecciona el servicio de Stock"}),b.error&&/* @__PURE__ */s(ye,{variant:"danger",children:b.error}),
|
|
352
352
|
/* @__PURE__ */s("div",{className:"lb:grid lb:grid-cols-2 lb:md:grid-cols-3 lb:gap-3",children:b.services.map(e=>/* @__PURE__ */c("button",{type:"button",onClick:()=>{p(e.slug),P(!1),g({}),y([]),x(1),C(null),T(null),E.fetchParams(e.slug,!0)},disabled:b.loading||l,className:`lb:group lb:relative lb:p-4 lb:rounded-lg lb:border-2 lb:transition-all lb:duration-200 lb:overflow-hidden lb:flex lb:flex-col lb:items-center lb:justify-center lb:min-h-30 lb:border-gray-200 lb:hover:border-brand-blue-300 lb:hover:shadow-md lb:lg:w-min ${b.loading||l?"lb:opacity-50 lb:cursor-not-allowed":"lb:cursor-pointer"} `,style:{position:"relative"},children:[e.image&&/* @__PURE__ */s("div",{className:"lb:absolute lb:inset-0 lb:bg-cover lb:bg-center lb:transition-opacity lb:duration-200 lb:group-hover:opacity-35",style:{backgroundImage:`url(${e.image})`,opacity:.2}}),
|
|
353
353
|
/* @__PURE__ */c("div",{className:"lb:relative lb:z-10 lb:flex lb:flex-col lb:items-center lb:justify-center lb:gap-2 lb:text-center",children:[
|
|
354
354
|
/* @__PURE__ */s("span",{className:"lb:text-base lb:font-semibold lb:text-neutral-black-000",children:e.label}),e.description&&/* @__PURE__ */s("span",{className:"lb:text-sm lb:text-gray-950 lb:line-clamp-2 lb:drop-shadow lb:drop-shadow-neutral-white-000",children:e.description})]})]},e.slug))})]}:{children:[
|
|
355
|
-
/* @__PURE__ */s("h3",{className:"lb:text-2xl lb:font-semibold lb:text-brand-blue-1000",children:b.services.find(e=>e.slug===h)?.label||"Búsqueda Stock"}),E.loading&&/* @__PURE__ */s("div",{children:"Cargando parámetros..."}),E.error&&/* @__PURE__ */s(
|
|
355
|
+
/* @__PURE__ */s("h3",{className:"lb:text-2xl lb:font-semibold lb:text-brand-blue-1000",children:b.services.find(e=>e.slug===h)?.label||"Búsqueda Stock"}),E.loading&&/* @__PURE__ */s("div",{children:"Cargando parámetros..."}),E.error&&/* @__PURE__ */s(ye,{variant:"danger",children:E.error}),h&&(()=>{const e=E.params?.[h]?.parameters;if(!e)return null;const t=Object.entries(e).filter(([,e])=>!e.hidden),n=t.filter(([e])=>e.toLowerCase().includes("query")||e.toLowerCase().includes("search")||e.toLowerCase().includes("term")),r=t.filter(([e])=>!e.toLowerCase().includes("query")&&!e.toLowerCase().includes("search")&&!e.toLowerCase().includes("term")),a=(e,t)=>{let n=t.placeholder||"";n||(n="integer"===t.type?t.minValue&&t.maxValue?`Entre ${t.minValue} y ${t.maxValue}`:t.minValue?`Mínimo ${t.minValue}`:t.maxValue?`Máximo ${t.maxValue}`:"Introduce un número":e.toLowerCase().includes("query")||e.toLowerCase().includes("search")||e.toLowerCase().includes("term")?"Buscar imágenes...":`Introduce ${(t.label||e).toLowerCase()}`);const r=e.toLowerCase().includes("query")||e.toLowerCase().includes("search")||e.toLowerCase().includes("term");/* @__PURE__ */
|
|
356
356
|
return c("div",{className:"lb:flex lb:flex-col lb:gap-1",children:[
|
|
357
357
|
/* @__PURE__ */c("label",{htmlFor:`stock-${e}`,className:"lb:text-xs lb:font-medium lb:text-brand-blue-1000",children:[t.label||e,t.required&&/* @__PURE__ */s("span",{className:"lb:text-red-1000 lb:ml-1",children:"*"})]}),t.options&&t.multiple?/* @__PURE__ */s("div",{className:"lb:flex lb:flex-wrap lb:gap-2 lb:min-h-[50px] lb:px-2 lb:justify-between lb:border-2 lb:border-gray-transparent-500 lb:rounded-lg",children:t.options.map(t=>/* @__PURE__ */c("label",{className:"lb:flex lb:items-center lb:gap-1",children:[
|
|
358
358
|
/* @__PURE__ */s("input",{type:"checkbox",name:`stock-${e}`,value:t,checked:Array.isArray(f[e])&&f[e].includes(t),onChange:()=>((e,t)=>{g(n=>{const l=Array.isArray(n[e])?n[e]:[];return l.includes(t)?{...n,[e]:l.filter(e=>e!==t)}:{...n,[e]:[...l,t]}})})(e,t),disabled:l}),
|
|
@@ -360,30 +360,30 @@ return c("div",{className:"lb:flex lb:flex-col lb:gap-1",children:[
|
|
|
360
360
|
return c("div",{children:[b.services.length>1&&/* @__PURE__ */c("button",{type:"button",onClick:()=>{P(!0),p(""),g({}),y([]),x(1),C(null),T(null)},className:"lb:flex lb:cursor-pointer lb:items-center lb:gap-2 lb:text-brand-blue-800 lb:hover:text-brand-blue-1000 lb:mb-4 lb:font-medium",children:[
|
|
361
361
|
/* @__PURE__ */s("span",{className:"icon icon-arrow-left"}),"Volver al menú de servicios"]}),
|
|
362
362
|
/* @__PURE__ */c("div",{className:"lb:relative",children:[
|
|
363
|
-
/* @__PURE__ */c("form",{onSubmit:
|
|
363
|
+
/* @__PURE__ */c("form",{onSubmit:q,"data-type":"stock",className:"lb:flex lb:flex-col lb:gap-3 lb:mt-4 lb:border-t-1 lb:pt-4 lb:border-brand-blue-200","aria-label":"Formulario búsqueda de imágenes de Stock",children:[z&&/* @__PURE__ */s(ye,{variant:"danger",className:"lb:mt-4",children:z}),
|
|
364
364
|
/* @__PURE__ */s("div",{className:"lb:flex lb:flex-col lb:gap-3",children:n.map(([e,t])=>a(e,t))}),r.length>0&&/* @__PURE__ */c("div",{className:"lb:border-t lb:border-gray-200 lb:pt-3",children:[
|
|
365
365
|
/* @__PURE__ */c("button",{type:"button",onClick:()=>D(!M),className:"lb:flex lb:items-center lb:gap-2 lb:text-sm lb:font-medium lb:text-brand-blue-800 lb:hover:text-brand-blue-1000 lb:mb-3 lb:transition-colors",children:[
|
|
366
366
|
/* @__PURE__ */s("svg",{className:"lb:w-4 lb:h-4 lb:transition-transform "+(M?"lb:rotate-90":""),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),"Opciones avanzadas",!M&&/* @__PURE__ */c("span",{className:"lb:text-xs lb:text-gray-500",children:["(",r.length," opciones)"]})]}),M&&/* @__PURE__ */s("div",{className:"lb:grid lb:grid-cols-1 lb:md:grid-cols-2 lb:gap-3 lb:animate-fadeIn",children:r.map(([e,t])=>a(e,t))})]}),
|
|
367
367
|
/* @__PURE__ */s("button",{type:"submit",disabled:$||l,className:"limbo-btn lb:w-full lb:mt-2 "+($?"lb:cursor-not-allowed limbo-btn-disabled":"limbo-btn-primary"),style:{minHeight:44},children:$?"Buscando...":"Buscar imágenes"})]}),
|
|
368
|
-
/* @__PURE__ */s(
|
|
368
|
+
/* @__PURE__ */s(_t,{show:$&&!v.length,message:"Buscando imágenes..."})]})]})})(),R&&/* @__PURE__ */s("div",{className:"lb:mt-6 lb:md:w-full lb:mx-auto",children:/* @__PURE__ */s(zt,{image:R,onDiscard:()=>{O(null),T(null)},onDownload:()=>{},onSelect:e=>{if(r)if(e&&R&&e!==R.name){const t=new File([R],e,{type:R.type});r(t)}else r(R)},showRetry:!1,disabled:l,selectedFolder:a,onFolderChange:i,folderConfig:o})}),!R&&v.length>0&&/* @__PURE__ */c(u,{children:[
|
|
369
369
|
/* @__PURE__ */c("div",{className:"lb:mt-6 lb:grid lb:grid-cols-2 lb:md:grid-cols-3 lb:lg:grid-cols-4 lb:gap-1 lb:relative","aria-live":"polite",children:[
|
|
370
|
-
/* @__PURE__ */s(
|
|
370
|
+
/* @__PURE__ */s(_t,{show:$,message:"Cargando imágenes..."}),v.map((e,t)=>{const r=K({prod:n}),a=e.preview||e.thumbnail||e.url,i=a?`${r}/api/atenea/proxy?url=${encodeURIComponent(a)}`:null;/* @__PURE__ */
|
|
371
371
|
return s("div",{className:"lb:border lb:border-brand-blue-200 lb:rounded-sm lb:overflow-hidden lb:bg-white lb:shadow-sm lb:hover:shadow-md lb:transition-all lb:duration-200 lb:cursor-pointer",title:"Ver imagen",onClick:()=>{A||$||l||j(e)},children:/* @__PURE__ */c("div",{className:"lb:relative lb:aspect-video lb:bg-neutral-100",children:[
|
|
372
|
-
/* @__PURE__ */s(
|
|
372
|
+
/* @__PURE__ */s(Dt,{src:a,fallbackSrc:i,alt:e.title||`Resultado ${t+1}`}),A===e.id&&/* @__PURE__ */c("div",{className:"lb:absolute lb:inset-0 lb:bg-white/90 lb:flex lb:flex-col lb:items-center lb:justify-center lb:gap-2",children:[
|
|
373
373
|
/* @__PURE__ */c("div",{className:"lb:relative lb:w-10 lb:h-10",children:[
|
|
374
374
|
/* @__PURE__ */s("div",{className:"lb:absolute lb:inset-0 lb:border-4 lb:border-brand-blue-200 lb:rounded-full"}),
|
|
375
375
|
/* @__PURE__ */s("div",{className:"lb:absolute lb:inset-0 lb:border-4 lb:border-brand-blue-800 lb:rounded-full lb:border-t-transparent lb:animate-spin"})]}),
|
|
376
376
|
/* @__PURE__ */s("span",{className:"lb:text-sm lb:font-medium lb:text-brand-blue-1000",children:"Descargando..."})]})]})},e.id||t)})]}),k&&/* @__PURE__ */c("div",{className:"lb:mt-6 lb:flex lb:items-center lb:justify-center lb:gap-2",children:[
|
|
377
|
-
/* @__PURE__ */c("button",{onClick:()=>
|
|
377
|
+
/* @__PURE__ */c("button",{onClick:()=>V(k.current_page-1),disabled:k.current_page<=1||$,className:"limbo-btn limbo-btn-secondary px-4 py-2 disabled:opacity-25"+(k.current_page<=1||$?" pointer-events-none cursor-default":" limbo-btn-primary"),children:[
|
|
378
378
|
/* @__PURE__ */s("span",{className:"icon icon-arrow-left-white icon--sm"})," ","Anterior"]}),
|
|
379
379
|
/* @__PURE__ */c("span",{className:"lb:px-4 lb:py-2 lb:text-sm lb:text-neutral-700",children:["Página ",k.current_page," de"," ",Math.max(1,Math.ceil(k.total/k.per_page)),
|
|
380
380
|
/* @__PURE__ */c("span",{className:"lb:text-xs lb:text-neutral-500 lb:block",children:["(",k.total," imágenes totales)"]})]}),
|
|
381
|
-
/* @__PURE__ */c("button",{onClick:()=>
|
|
381
|
+
/* @__PURE__ */c("button",{onClick:()=>V(k.current_page+1),disabled:$||k.current_page>=Math.ceil(k.total/k.per_page),className:"limbo-btn limbo-btn-secondary px-4 py-2 disabled:opacity-25"+($||k.current_page>=Math.ceil(k.total/k.per_page)?" pointer-events-none cursor-default":" limbo-btn-primary"),children:["Siguiente"," ",
|
|
382
382
|
/* @__PURE__ */s("span",{className:"icon icon-arrow-right-white icon--sm"})]})]})]}),!$&&0===v.length&&h&&S&&/* @__PURE__ */c("div",{className:"lb:mt-6 lb:text-center lb:text-neutral-600 lb:py-8 lb:bg-neutral-50 lb:rounded-lg",children:[
|
|
383
383
|
/* @__PURE__ */s("span",{className:"icon icon-search icon--lg lb:mb-2"}),
|
|
384
384
|
/* @__PURE__ */c("p",{children:['No se encontraron imágenes para "',f.query,'"']}),
|
|
385
|
-
/* @__PURE__ */s("p",{className:"lb:text-sm lb:mt-1",children:"Intenta con otros términos de búsqueda"})]}),F&&(()=>{const e=
|
|
386
|
-
return s(
|
|
385
|
+
/* @__PURE__ */s("p",{className:"lb:text-sm lb:mt-1",children:"Intenta con otros términos de búsqueda"})]}),F&&(()=>{const e=K({prod:n}),t=F.preview||F.thumbnail||F.url,l=t?`${e}/api/atenea/proxy?url=${encodeURIComponent(t)}`:null;/* @__PURE__ */
|
|
386
|
+
return s(Mt,{isOpen:!!F,image:{previewUrl:t,proxyUrl:l,title:F.title||F.filename||"Imagen"},onCancel:()=>j(null),onSelect:()=>{const e=F;j(null),H(e)}})})()]})}):/* @__PURE__ */s(ye,{variant:"warning",children:"No hay servicios de Stock disponibles."})}const Ot="/api";function Ft(e,t=!1){const n=new URLSearchParams;return e.portal&&n.set("portal",e.portal),e.media_type&&n.set("media_type",e.media_type),e.page&&n.set("page",String(e.page)),n.set("per_page",String(e.per_page)),e.search&&n.set("search",e.search),e.order&&n.set("order",e.order),Y({endpoint:`/external/media?${n.toString()}`,method:"GET",prod:t,basePath:Ot})}const jt=/* @__PURE__ */new Map;function Ut(e=!1){const[l,r]=t([]),[a,i]=t(!0),[o,s]=t(null);n(()=>{const t=`portal-sources-${e}`,n=jt.get(t),l=Date.now();if(n&&l-n.timestamp<864e5)return r(n.data),void i(!1);let a=!0;return(async()=>{try{const n=await function(e=!1,t=!0){const n=new URLSearchParams;return n.set("active",t?"true":"false"),Y({endpoint:`/external/portals?${n.toString()}`,method:"GET",prod:e,basePath:Ot})}(e,!0);if(!a)return;let i=n?.data||[];Array.isArray(i)||(i=[]);const o=i.map(e=>({id:e.slug||e.id,numericId:e.id,name:e.name,title:e.name,slug:e.slug,url:e.website_url,image:e.logo_url,isActive:e.is_active}));r(o),jt.set(t,{data:o,timestamp:l})}catch(n){a&&s(n.message)}finally{a&&i(!1)}})(),()=>{a=!1}},[e]);return{sources:l,loading:a,error:o,invalidateCache:()=>{jt.delete(`portal-sources-${e}`)}}}function Bt({isOpen:e=!1,video:n,onClose:r,onSelect:i=null}){const[o,d]=t(!1),b=l(()=>n?"youtube"===n.platform&&n.video_id?`https://www.youtube.com/embed/${n.video_id}?autoplay=1&rel=0`:"vimeo"===n.platform&&n.video_id?`https://player.vimeo.com/video/${n.video_id}?autoplay=1`:n.embed_url||null:null,[n]),m=l(()=>n&&(n.player_url||n.embed_url||n.post_url)||"",[n]),h=a(async()=>{if(m)try{await navigator.clipboard.writeText(m),d(!0),setTimeout(()=>d(!1),2e3)}catch{const e=document.createElement("textarea");e.value=m,e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e),d(!0),setTimeout(()=>d(!1),2e3)}},[m]),p=a(()=>{i&&n&&i(n)},[i,n]);if(!n)return null;const f=[n.portal_name,n.platform].filter(Boolean).join(" · "),g=i?/* @__PURE__ */c("button",{type:"button",onClick:p,className:"lb:flex lb:items-center lb:gap-2 lb:px-4 lb:py-1.5 lb:rounded-lg lb:bg-brand-blue-800 lb:hover:bg-brand-blue-900 lb:text-white lb:text-sm lb:font-medium lb:transition-colors","aria-label":"Seleccionar video",children:[
|
|
387
387
|
/* @__PURE__ */s("svg",{className:"lb:w-4 lb:h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),
|
|
388
388
|
/* @__PURE__ */s("span",{children:"Seleccionar"})]}):/* @__PURE__ */s("button",{type:"button",onClick:h,disabled:!m,className:"lb:flex lb:items-center lb:gap-2 lb:px-4 lb:py-1.5 lb:rounded-lg lb:text-sm lb:font-medium lb:transition-colors "+(o?"lb:bg-green-600 lb:text-white":"lb:bg-white/10 lb:hover:bg-white/20 lb:text-white"),"aria-label":"Copiar URL del video",children:/* @__PURE__ */c(u,o?{children:[
|
|
389
389
|
/* @__PURE__ */s("svg",{className:"lb:w-4 lb:h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),
|
|
@@ -391,21 +391,21 @@ return s(Tt,{isOpen:!!F,image:{previewUrl:t,proxyUrl:l,title:F.title||F.filename
|
|
|
391
391
|
/* @__PURE__ */s("svg",{className:"lb:w-4 lb:h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3"})}),
|
|
392
392
|
/* @__PURE__ */s("span",{children:"Copiar URL"})]})}),v=/* @__PURE__ */c("span",{children:[
|
|
393
393
|
/* @__PURE__ */s("kbd",{className:"lb:px-1.5 lb:py-0.5 lb:bg-white/10 lb:rounded lb:text-white",children:"ESC"})," ","cerrar"]});/* @__PURE__ */
|
|
394
|
-
return s(
|
|
394
|
+
return s(Fe,{isOpen:e,onClose:r,title:n.title||"Video",subtitle:f,ariaLabel:"Vista previa de video externo",headerActions:g,footerHints:v,children:/* @__PURE__ */c("div",{className:"lb:flex lb:flex-col lb:items-center lb:gap-3 lb:w-full lb:max-w-5xl lb:px-4",children:[
|
|
395
395
|
/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-2 lb:px-4 lb:py-2 lb:bg-amber-500/20 lb:border lb:border-amber-500/40 lb:rounded-lg lb:text-amber-200 lb:text-sm",children:[
|
|
396
396
|
/* @__PURE__ */s("svg",{className:"lb:w-5 lb:h-5 lb:shrink-0",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),
|
|
397
397
|
/* @__PURE__ */c("span",{children:["Este video no se puede guardar en Limbo — alojado en"," ",
|
|
398
398
|
/* @__PURE__ */s("strong",{className:"lb:capitalize",children:n.platform||"plataforma externa"})]})]}),
|
|
399
399
|
/* @__PURE__ */s("div",{className:"lb:relative lb:w-full lb:aspect-video lb:bg-black lb:rounded-lg lb:overflow-hidden",children:b?/* @__PURE__ */s("iframe",{src:b,className:"lb:absolute lb:inset-0 lb:w-full lb:h-full",allow:"autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0,title:n.title||"Video"}):/* @__PURE__ */c("div",{className:"lb:absolute lb:inset-0 lb:flex lb:flex-col lb:items-center lb:justify-center lb:text-white lb:gap-3",children:[
|
|
400
400
|
/* @__PURE__ */s("svg",{className:"lb:w-16 lb:h-16 lb:text-gray-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"})}),
|
|
401
|
-
/* @__PURE__ */s("p",{className:"lb:text-sm lb:text-gray-400",children:"No se puede previsualizar este video"}),m&&/* @__PURE__ */s("a",{href:m,target:"_blank",rel:"noopener noreferrer",className:"lb:text-sm lb:text-brand-blue-400 lb:hover:text-brand-blue-300 lb:underline",children:"Abrir en nueva pestaña"})]})}),m&&/* @__PURE__ */s("p",{className:"lb:text-xs lb:text-gray-500 lb:truncate lb:max-w-full lb:px-2",children:m})]})})}const
|
|
402
|
-
/* @__PURE__ */s("img",{src:u,alt:l,className:`${r} ${"loading"===i?"lb:opacity-0":"lb:opacity-100"} lb:transition-opacity lb:duration-300`,loading:"lazy",onLoad:()=>{o("loaded")},onError:()=>{n&&!b?(m(!0),d(n),o("loading")):(o("error"),a&&a())}})]})};function
|
|
401
|
+
/* @__PURE__ */s("p",{className:"lb:text-sm lb:text-gray-400",children:"No se puede previsualizar este video"}),m&&/* @__PURE__ */s("a",{href:m,target:"_blank",rel:"noopener noreferrer",className:"lb:text-sm lb:text-brand-blue-400 lb:hover:text-brand-blue-300 lb:underline",children:"Abrir en nueva pestaña"})]})}),m&&/* @__PURE__ */s("p",{className:"lb:text-xs lb:text-gray-500 lb:truncate lb:max-w-full lb:px-2",children:m})]})})}const Wt=({src:t,fallbackSrc:n,alt:l,className:r,onError:a})=>{const[i,o]=e.useState("loading"),[u,d]=e.useState(t),[b,m]=e.useState(!1);return"error"===i?null:/* @__PURE__ */c("div",{className:"lb:relative lb:w-full lb:h-full",children:["loading"===i&&/* @__PURE__ */s("div",{className:"lb:absolute lb:inset-0 lb:bg-linear-to-r lb:from-gray-200 lb:via-gray-100 lb:to-gray-200 lb:animate-pulse lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-spinner lb:w-8 lb:h-8 lb:text-gray-400 lb:animate-spin"})}),
|
|
402
|
+
/* @__PURE__ */s("img",{src:u,alt:l,className:`${r} ${"loading"===i?"lb:opacity-0":"lb:opacity-100"} lb:transition-opacity lb:duration-300`,loading:"lazy",onLoad:()=>{o("loaded")},onError:()=>{n&&!b?(m(!0),d(n),o("loading")):(o("error"),a&&a())}})]})};function qt({prod:e,disabled:n,onSelect:i,onVideoSelect:o,selectedFolder:d,onFolderChange:b,folderConfig:m,resolvedAccept:h=null,returnConfig:p=null}){const{sources:f,loading:g,error:v}=Ut(e),y=l(()=>{if(!h||h.isAllTypes)return[{value:"images",label:"Imágenes"},{value:"videos",label:"Vídeos"},{value:"all",label:"Todo"}];const e=[];return h.includesImages&&e.push({value:"images",label:"Imágenes"}),h.includesVideos&&e.push({value:"videos",label:"Vídeos"}),e.length>1&&e.push({value:"all",label:"Todo"}),e.length>0?e:[{value:"images",label:"Imágenes"}]},[h]),w=y[0]?.value||"images",[x,k]=t(null),[C,S]=t(w),[N,E]=t(""),[$,_]=t([]),[z,T]=t(1),[A,L]=t(null),[I,P]=t(!1),[M,D]=t(null),[R,O]=t(null),[F,j]=t(null),[U,B]=t(/* @__PURE__ */new Set),[W,q]=t(!1),[V,H]=t(null),[G,Q]=t(null),X=!!p&&"url"===p.format,Y=r({}),J=a((e,t,n,l)=>`${e}_${t}_${n}_${l}`,[]),Z=a(async(t,n,l,r)=>{const a=J(t,n,l,r),i=Y.current[a];if(i)return _(i.items),L(i.pagination),T(r),D(null),void q(!0);P(!0),D(null);try{const i={portal:t,media_type:n,page:r,per_page:20};l.trim()&&(i.search=l.trim());const o=new Promise((e,t)=>setTimeout(()=>t(new Error("__timeout__")),25e3)),s=await Promise.race([Ft(i,e),o]),c=s?.data||{},u=c.items||[],d=c.pagination||{total_items:u.length,total_pages:1,current_page:r,per_page:20};Y.current[a]={items:u,pagination:d},_(u),L(d),T(r),B(/* @__PURE__ */new Set),q(!0),0===u.length&&D("No se encontraron resultados para este portal.")}catch(o){const e="__timeout__"===o.message;D(e?"El portal tardó demasiado en responder. Puede estar temporalmente no disponible. Inténtalo de nuevo.":o.message||"Error al cargar media del portal"),_([]),L(null),q(!0)}finally{P(!1)}},[e,J]),ee=a(e=>{e!==x&&(k(e),E(""),S(w),_([]),L(null),D(null),O(null),H(null),B(/* @__PURE__ */new Set),q(!1),Y.current={},Z(e,w,"",1))},[x,w,Z]),te=a(()=>{k(null),_([]),L(null),D(null),E(""),O(null),H(null),B(/* @__PURE__ */new Set),q(!1),Y.current={}},[]),ne=a(()=>{x&&(Y.current={},Z(x,C,N,1))},[x,C,N,Z]),le=a(e=>{"Enter"===e.key&&(e.preventDefault(),ne())},[ne]),re=a(e=>{e<1||!x||Z(x,C,N,e)},[x,C,N,Z]),ae=a(e=>{H(null),o?o(e):i&&i(e)},[o,i]),ie=a(async t=>{if("video"===t.type){const e={type:"video",source:"portal",title:t.title||"",thumbnail:t.thumbnail||t.url,embed_url:t.embed_url||null,player_url:t.player_url||null,post_url:t.post_url||null,platform:t.platform||null,video_id:t.video_id||null,portal_slug:t.portal_slug||x,portal_name:t.portal_name||f.find(e=>e.slug===x)?.name||null,date_published:t.date_published||null,author:t.author||null};return void H(e)}const n=t.url||t.thumbnail;if(n){j(n),D(null);try{let l=null;try{const e=await fetch(n,{mode:"cors"});e.ok&&(l=await e.blob())}catch{}if(!l){const t=`${K({prod:e})}/api/external/proxy?url=${encodeURIComponent(n)}`,r=await fetch(t);if(!r.ok)throw new Error(`Error al descargar: ${r.status}`);l=await r.blob()}const r=t.title?`${t.title.substring(0,80)}.${"image/png"===t.mime_type?"png":"jpg"}`:`portal-${Date.now()}.jpg`,a=new File([l],r,{type:l.type||t.mime_type||"image/jpeg"});O(a)}catch(l){D(l.message||"No se pudo recuperar la imagen del portal")}finally{j(null)}}else D("No se encontró URL de la imagen")},[e,x,f]);if(g)/* @__PURE__ */
|
|
403
403
|
return c("div",{className:"lb:flex lb:items-center lb:justify-center lb:py-8",children:[
|
|
404
404
|
/* @__PURE__ */s("span",{className:"limbo-loader lb:mr-2"})," Cargando portales disponibles..."]});if(!f.length)/* @__PURE__ */
|
|
405
|
-
return s(
|
|
405
|
+
return s(ye,{variant:"warning",children:"No hay portales externos disponibles."});if(!x)/* @__PURE__ */
|
|
406
406
|
return c("div",{className:"lb:flex lb:flex-col lb:gap-4",children:[
|
|
407
|
-
/* @__PURE__ */s("h3",{className:"lb:text-lg lb:font-semibold lb:text-brand-blue-1000",children:"Selecciona un Portal"}),v&&/* @__PURE__ */s(
|
|
408
|
-
/* @__PURE__ */s("div",{className:"lb:grid lb:grid-cols-2 lb:md:grid-cols-3 lb:gap-3",children:f.map(e=>/* @__PURE__ */s("button",{type:"button",onClick:()=>ee(e.slug),disabled:n,className:"lb:relative lb:p-4 lb:rounded-lg lb:border-2 lb:transition-all lb:duration-200 lb:flex lb:flex-col lb:items-center lb:justify-center lb:min-h-25 lb:gap-2 lb:max-h-27.5 lb:box-border lb:border-gray-200 lb:bg-white lb:hover:border-brand-blue-350 lb:hover:shadow-md "+(n?"lb:opacity-50 lb:cursor-not-allowed":"lb:cursor-pointer"),children:e.image?/* @__PURE__ */s("img",{className:"lb:object-auto lb:bg-no-repeat lb:bg-center lb:max-h-full lb:object-contain lb:h-full lb:px-16",src:e.image,alt:e.title}):/* @__PURE__ */s("span",{className:"lb:text-sm lb:font-medium lb:text-brand-blue-800",children:e.name})},e.slug))})]});const oe=f.find(e=>e.slug===x),se=
|
|
407
|
+
/* @__PURE__ */s("h3",{className:"lb:text-lg lb:font-semibold lb:text-brand-blue-1000",children:"Selecciona un Portal"}),v&&/* @__PURE__ */s(ye,{variant:"danger",children:v}),
|
|
408
|
+
/* @__PURE__ */s("div",{className:"lb:grid lb:grid-cols-2 lb:md:grid-cols-3 lb:gap-3",children:f.map(e=>/* @__PURE__ */s("button",{type:"button",onClick:()=>ee(e.slug),disabled:n,className:"lb:relative lb:p-4 lb:rounded-lg lb:border-2 lb:transition-all lb:duration-200 lb:flex lb:flex-col lb:items-center lb:justify-center lb:min-h-25 lb:gap-2 lb:max-h-27.5 lb:box-border lb:border-gray-200 lb:bg-white lb:hover:border-brand-blue-350 lb:hover:shadow-md "+(n?"lb:opacity-50 lb:cursor-not-allowed":"lb:cursor-pointer"),children:e.image?/* @__PURE__ */s("img",{className:"lb:object-auto lb:bg-no-repeat lb:bg-center lb:max-h-full lb:object-contain lb:h-full lb:px-16",src:e.image,alt:e.title}):/* @__PURE__ */s("span",{className:"lb:text-sm lb:font-medium lb:text-brand-blue-800",children:e.name})},e.slug))})]});const oe=f.find(e=>e.slug===x),se=K({prod:e});/* @__PURE__ */
|
|
409
409
|
return c("div",{className:"lb:flex lb:flex-col lb:gap-3",children:[
|
|
410
410
|
/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-3",children:[
|
|
411
411
|
/* @__PURE__ */c("button",{type:"button",onClick:te,className:"lb:flex lb:items-center lb:gap-1 lb:text-sm lb:text-brand-blue-800 lb:hover:text-brand-blue-1000 lb:font-medium lb:transition-colors",children:[
|
|
@@ -415,23 +415,23 @@ return c("div",{className:"lb:flex lb:flex-col lb:gap-3",children:[
|
|
|
415
415
|
/* @__PURE__ */c("div",{className:"lb:flex lb:flex-col lb:gap-3 lb:border-t lb:pt-3 lb:border-brand-blue-200",children:[y.length>1&&/* @__PURE__ */s("div",{className:"lb:flex lb:gap-2",children:y.map(({value:e,label:t})=>/* @__PURE__ */s("button",{type:"button",onClick:()=>S(e),disabled:n||I,className:"lb:px-3 lb:py-1.5 lb:text-sm lb:rounded-md lb:font-medium lb:transition-colors "+(C===e?"lb:bg-brand-blue-800 lb:text-white":"lb:bg-gray-100 lb:text-gray-700 lb:hover:bg-gray-200"),children:t},e))}),
|
|
416
416
|
/* @__PURE__ */c("div",{className:"lb:flex lb:gap-2",children:[
|
|
417
417
|
/* @__PURE__ */s("input",{type:"text",value:N,onChange:e=>E(e.target.value),onKeyDown:le,className:"limbo-input lb:flex-1",placeholder:"Buscar en el portal...",disabled:n||I}),
|
|
418
|
-
/* @__PURE__ */c("button",{type:"button",onClick:ne,disabled:n||I,className:"limbo-btn limbo-btn-primary lb:px-4 lb:py-2 lb:text-sm lb:font-medium lb:whitespace-nowrap lb:flex lb:items-center lb:gap-1.5",children:[/* @__PURE__ */s("span",I?{className:"limbo-loader limbo-loader--sm"}:{className:"icon icon-search-white icon--sm"}),"Buscar"]})]})]}),M&&!I&&/* @__PURE__ */s(
|
|
418
|
+
/* @__PURE__ */c("button",{type:"button",onClick:ne,disabled:n||I,className:"limbo-btn limbo-btn-primary lb:px-4 lb:py-2 lb:text-sm lb:font-medium lb:whitespace-nowrap lb:flex lb:items-center lb:gap-1.5",children:[/* @__PURE__ */s("span",I?{className:"limbo-loader limbo-loader--sm"}:{className:"icon icon-search-white icon--sm"}),"Buscar"]})]})]}),M&&!I&&/* @__PURE__ */s(ye,{variant:"warning",children:M}),R&&/* @__PURE__ */s("div",{className:"lb:mt-2 lb:md:w-full lb:mx-auto",children:/* @__PURE__ */s(zt,{image:R,onDiscard:()=>{O(null),D(null)},onDownload:()=>{},onSelect:e=>{if(i)if(e&&R&&e!==R.name){const t=new File([R],e,{type:R.type});i(t)}else i(R)},showRetry:!1,disabled:n,selectedFolder:d,onFolderChange:b,folderConfig:m})}),!R&&/* @__PURE__ */c(u,{children:[
|
|
419
419
|
/* @__PURE__ */c("div",{className:"lb:relative lb:min-h-50","aria-live":"polite",children:[I&&/* @__PURE__ */s("div",{className:"lb:absolute lb:inset-0 lb:bg-white/80 lb:z-10 lb:flex lb:items-center lb:justify-center lb:rounded-lg",children:/* @__PURE__ */c("div",{className:"lb:flex lb:flex-col lb:items-center lb:gap-2",children:[
|
|
420
420
|
/* @__PURE__ */s("span",{className:"limbo-loader"}),
|
|
421
421
|
/* @__PURE__ */s("span",{className:"lb:text-sm lb:text-brand-blue-800",children:"Cargando media..."})]})}),$.length>0&&/* @__PURE__ */c("div",{className:"lb:relative lb:grid lb:grid-cols-2 lb:md:grid-cols-3 lb:lg:grid-cols-4 lb:gap-2",children:[
|
|
422
|
-
/* @__PURE__ */s(
|
|
422
|
+
/* @__PURE__ */s(_t,{show:I,message:"Cargando media..."}),$.map((e,t)=>{const l=`${e.portal_slug}-${e.id||t}`,r=e.thumbnail||e.url;if(U.has(l)||!r)return null;const a=`${se}/api/external/proxy?url=${encodeURIComponent(r)}`,i="video"===e.type;/* @__PURE__ */
|
|
423
423
|
return c("div",{className:"lb:group lb:border lb:border-brand-blue-200 lb:rounded-lg lb:overflow-hidden lb:bg-white lb:shadow-sm lb:hover:shadow-md lb:transition-all lb:duration-200 lb:cursor-pointer",onClick:()=>{F||I||n||(i?ie(e):Q(e))},children:[
|
|
424
424
|
/* @__PURE__ */c("div",{className:"lb:relative lb:aspect-video lb:bg-neutral-100",children:[
|
|
425
|
-
/* @__PURE__ */s(
|
|
425
|
+
/* @__PURE__ */s(Wt,{src:r,fallbackSrc:a,alt:e.alt||e.title||`Media ${t+1}`,className:"lb:object-cover lb:w-full lb:h-full",onError:()=>{B(e=>{const t=new Set(e);return t.add(l),t})}}),i&&/* @__PURE__ */s("span",{className:"lb:absolute lb:top-1 lb:left-1 lb:bg-black/60 lb:text-white lb:text-xs lb:px-2 lb:py-1 lb:rounded",children:"Video"}),F===(e.url||e.thumbnail)?/* @__PURE__ */c("div",{className:"lb:absolute lb:inset-0 lb:bg-white/90 lb:flex lb:flex-col lb:items-center lb:justify-center lb:gap-2",children:[
|
|
426
426
|
/* @__PURE__ */c("div",{className:"lb:relative lb:w-10 lb:h-10",children:[
|
|
427
427
|
/* @__PURE__ */s("div",{className:"lb:absolute lb:inset-0 lb:border-4 lb:border-brand-blue-200 lb:rounded-full"}),
|
|
428
428
|
/* @__PURE__ */s("div",{className:"lb:absolute lb:inset-0 lb:border-4 lb:border-brand-blue-800 lb:rounded-full lb:border-t-transparent lb:animate-spin"})]}),
|
|
429
429
|
/* @__PURE__ */s("span",{className:"lb:text-sm lb:font-medium lb:text-brand-blue-1000",children:"Descargando..."})]}):i?
|
|
430
430
|
/* @__PURE__ */c("div",{className:"lb:absolute lb:inset-0 lb:bg-black/0 lb:group-hover:bg-black/60 lb:transition-colors lb:duration-200 lb:flex lb:items-center lb:justify-center lb:flex-col lb:gap-1",children:[
|
|
431
431
|
/* @__PURE__ */s("svg",{className:"lb:w-10 lb:h-10 lb:opacity-0 lb:group-hover:opacity-100 lb:transition-opacity lb:duration-200 lb:text-white",viewBox:"0 0 24 24",fill:"currentColor",children:/* @__PURE__ */s("path",{d:"M8 5v14l11-7z"})}),
|
|
432
|
-
/* @__PURE__ */s("span",{className:"lb:text-sm lb:font-medium lb:text-white lb:opacity-0 lb:group-hover:opacity-100 lb:transition-opacity lb:duration-200",children:"Seleccionar vídeo"})]}):null]}),e.title&&/* @__PURE__ */s("div",{className:"lb:px-2 lb:pb-2 lb:pt-1",children:/* @__PURE__ */s("p",{className:"lb:text-xs lb:text-gray-600 lb:truncate",title:e.title,children:e.title})})]},l)})]}),!
|
|
432
|
+
/* @__PURE__ */s("span",{className:"lb:text-sm lb:font-medium lb:text-white lb:opacity-0 lb:group-hover:opacity-100 lb:transition-opacity lb:duration-200",children:"Seleccionar vídeo"})]}):null]}),e.title&&/* @__PURE__ */s("div",{className:"lb:px-2 lb:pb-2 lb:pt-1",children:/* @__PURE__ */s("p",{className:"lb:text-xs lb:text-gray-600 lb:truncate",title:e.title,children:e.title})})]},l)})]}),!W&&!I&&0===$.length&&!M&&/* @__PURE__ */c("div",{className:"lb:text-center lb:text-neutral-600 lb:py-10 lb:bg-neutral-50 lb:rounded-lg",children:[
|
|
433
433
|
/* @__PURE__ */s("p",{className:"lb:font-medium lb:text-brand-blue-800",children:"Cargando contenido del portal..."}),
|
|
434
|
-
/* @__PURE__ */s("p",{className:"lb:text-sm lb:mt-1 lb:text-neutral-500",children:"También puedes buscar por término específico"})]}),
|
|
434
|
+
/* @__PURE__ */s("p",{className:"lb:text-sm lb:mt-1 lb:text-neutral-500",children:"También puedes buscar por término específico"})]}),W&&!I&&0===$.length&&!M&&/* @__PURE__ */c("div",{className:"lb:text-center lb:text-neutral-600 lb:py-8 lb:bg-neutral-50 lb:rounded-lg",children:[
|
|
435
435
|
/* @__PURE__ */s("span",{className:"icon icon-search icon--lg lb:mb-2"}),
|
|
436
436
|
/* @__PURE__ */s("p",{children:"No se encontraron resultados"}),N&&/* @__PURE__ */s("p",{className:"lb:text-sm lb:mt-1",children:"Intenta con otros términos de búsqueda"})]})]}),A&&A.total_pages>1&&/* @__PURE__ */c("div",{className:"lb:mt-4 lb:flex lb:items-center lb:justify-center lb:gap-2",children:[
|
|
437
437
|
/* @__PURE__ */c("button",{onClick:()=>re(z-1),disabled:1===z||I,className:"limbo-btn limbo-btn-secondary px-4 py-2 disabled:opacity-25"+(1===z||I?" pointer-events-none cursor-default":" limbo-btn-primary"),children:[
|
|
@@ -440,14 +440,14 @@ return c("div",{className:"lb:group lb:border lb:border-brand-blue-200 lb:rounde
|
|
|
440
440
|
/* @__PURE__ */c("span",{className:"lb:text-xs lb:text-neutral-500 lb:block",children:["(",A.total_items," resultados)"]})]}),
|
|
441
441
|
/* @__PURE__ */c("button",{onClick:()=>re(z+1),disabled:I||z>=A.total_pages,className:"limbo-btn limbo-btn-secondary px-4 py-2 disabled:opacity-25"+(I||z>=A.total_pages?" pointer-events-none cursor-default":" limbo-btn-primary"),children:["Siguiente"," ",
|
|
442
442
|
/* @__PURE__ */s("span",{className:"icon icon-arrow-right-white icon--sm"})]})]})]}),
|
|
443
|
-
/* @__PURE__ */s(
|
|
444
|
-
return s(
|
|
443
|
+
/* @__PURE__ */s(Bt,{isOpen:!!V,video:V,onClose:()=>H(null),onSelect:X?ae:null}),G&&(()=>{const e=G.thumbnail||G.url,t=`${se}/api/external/proxy?url=${encodeURIComponent(e)}`;/* @__PURE__ */
|
|
444
|
+
return s(Mt,{isOpen:!!G,image:{previewUrl:e,proxyUrl:t,title:G.title||G.alt||"Imagen"},onCancel:()=>Q(null),onSelect:()=>{const e=G;Q(null),ie(e)}})})()]})}const Vt=[{id:"upload",label:"Subir archivo"},{id:"ai",label:"Generar"},{id:"stock",label:"Buscar en Stock"},{id:"portals",label:"Otros portales"}];function Ht({onSelect:e,onVideoSelect:n,disabled:a=!1,apiKey:i,prod:o=!1,allowedCategories:u=null,resolvedAccept:d=null,returnConfig:b=null,folderConfig:m=null,selectedFolder:h=null,onFolderChange:p=null}){const{isMobile:f,isTouch:g}=D(),v=l(()=>!d||d.isAllTypes||d.includesImages?Vt:d.includesVideos?Vt.filter(e=>"upload"===e.id||"portals"===e.id):Vt.filter(e=>"upload"===e.id),[d]),[y,w]=t("upload"),[x,k]=t(null),[C,S]=t(null),N=r(),E=["limbo-tabs","lb:flex","lb:gap-4","lb:border-b-2","lb:border-brand-blue-200","lb:mb-4",f&&"lb:overflow-x-auto lb:scrollbar-none"].filter(Boolean).join(" "),$=e=>{const t=["limbo-tab","lb:relative","lb:px-4","lb:py-2","lb:font-medium","lb:text-brand-blue-1000","lb:bg-transparent","lb:border-0","lb:border-b-2","lb:cursor-pointer","lb:transition-all","lb:duration-200","lb:hover:text-pink-1000","lb:focus:outline-none","lb:focus-visible:ring-2","lb:focus-visible:ring-brand-blue-400","lb:focus-visible:ring-offset-2","lb:text-nowrap"];return e?t.push("lb:border-b-brand-blue-1000","lb:font-semibold","limbo-active"):t.push("lb:border-b-transparent"),f&&t.push("lb:min-w-[100px]","lb:min-h-[44px]","lb:text-sm","lb:shrink-0"),g&&t.push("lb:touch-manipulation"),t.join(" ")};/* @__PURE__ */
|
|
445
445
|
return c("div",{className:"limbo-upload-form lb:py-4 lb:min-w-fit lb:max-w-7xl lb:mx-auto",children:[v.length>1&&/* @__PURE__ */s("div",{className:E,role:"tablist","aria-label":"Opciones de subida",style:f?{WebkitOverflowScrolling:"touch",scrollbarWidth:"none",msOverflowStyle:"none"}:void 0,children:v.map(e=>{const t=y===e.id;/* @__PURE__ */
|
|
446
446
|
return c("button",{type:"button","data-upload-tab-id":e.id,className:$(t),"aria-current":t?"page":void 0,"aria-selected":t,role:"tab",tabIndex:t?0:-1,onClick:()=>w(e.id),onKeyDown:t=>((e,t)=>{const n=v.findIndex(e=>e.id===t);let l=n;switch(e.key){case"ArrowLeft":e.preventDefault(),l=n>0?n-1:v.length-1;break;case"ArrowRight":e.preventDefault(),l=n<v.length-1?n+1:0;break;case"Home":e.preventDefault(),l=0;break;case"End":e.preventDefault(),l=v.length-1;break;case"Enter":case" ":return e.preventDefault(),void w(t);default:return}const r=v[l];r&&(w(r.id),setTimeout(()=>{const e=document.querySelector(`[data-upload-tab-id="${r.id}"]`);e&&e.focus()},0))})(t,e.id),id:`upload-tab-${e.id}`,"aria-controls":`upload-tabpanel-${e.id}`,style:g?{WebkitTapHighlightColor:"transparent"}:void 0,children:["ai"===e.id?/* @__PURE__ */s("span",{className:"icon icon-ia lb:me-1"}):null,e.label]},e.id)})}),
|
|
447
|
-
/* @__PURE__ */c("div",{className:"limbo-tab-content lb:px-2 lb:py-2",role:"tabpanel",id:`upload-tabpanel-${y}`,"aria-labelledby":`upload-tab-${y}`,children:["upload"===y&&/* @__PURE__ */s(
|
|
448
|
-
return c("div",{children:[l&&/* @__PURE__ */s(
|
|
447
|
+
/* @__PURE__ */c("div",{className:"limbo-tab-content lb:px-2 lb:py-2",role:"tabpanel",id:`upload-tabpanel-${y}`,"aria-labelledby":`upload-tab-${y}`,children:["upload"===y&&/* @__PURE__ */s(kt,{file:x,setFile:k,previewUrl:C,setPreviewUrl:S,fileInputRef:N,onSelect:e,disabled:a,allowedCategories:u,resolvedAccept:d,selectedFolder:h,onFolderChange:p,folderConfig:m}),"ai"===y&&/* @__PURE__ */s(At,{apiKey:i,prod:o,disabled:a,onSelect:e,selectedFolder:h,onFolderChange:p,folderConfig:m}),"stock"===y&&/* @__PURE__ */s(Rt,{apiKey:i,prod:o,disabled:a,onSelect:e,selectedFolder:h,onFolderChange:p,folderConfig:m}),"portals"===y&&/* @__PURE__ */s(qt,{apiKey:i,prod:o,disabled:a,onSelect:e,onVideoSelect:n,resolvedAccept:d,returnConfig:b,selectedFolder:h,onFolderChange:p,folderConfig:m})]})]})}function Kt({onSelect:e,onVideoSelect:t,onFolderChange:n,uploading:l,uploadError:r,uploadedImage:a,selectedUploadFolder:i,apiKey:o,prod:u,allowedCategories:d,resolvedAccept:b,returnConfig:m,folderConfig:h,resetUpload:p}){/* @__PURE__ */
|
|
448
|
+
return c("div",{children:[l&&/* @__PURE__ */s(ht,{text:"Subiendo archivo..."}),r&&/* @__PURE__ */c(ye,{variant:"danger",toast:!0,onClose:p,children:["Error al subir archivo: ",r]}),a&&/* @__PURE__ */c(ye,{variant:"success",toast:!0,onClose:p,children:[
|
|
449
449
|
/* @__PURE__ */s("span",{className:"icon icon-tick-white icon--2sm"})," Archivo subido correctamente: ",a.filename]}),
|
|
450
|
-
/* @__PURE__ */s(Ut,{onSelect:e,onVideoSelect:t,disabled:l,apiKey:o,prod:u,allowedCategories:d,resolvedAccept:b,returnConfig:m,folderConfig:h,selectedFolder:i,onFolderChange:n})]})}const Wt="undefined"!=typeof window&&void 0!==window.document,qt=Wt?window:{},Vt=!!Wt&&"ontouchstart"in qt.document.documentElement,Ht=!!Wt&&"PointerEvent"in qt,Kt="cropper",Gt=`${Kt}-canvas`,Qt=`${Kt}-crosshair`,Xt=`${Kt}-grid`,Yt=`${Kt}-handle`,Jt=`${Kt}-image`,Zt=`${Kt}-selection`,en=`${Kt}-shade`,tn=`${Kt}-viewer`,nn="select",ln="move",rn="scale",an="rotate",on="transform",sn="none",cn="n-resize",un="e-resize",dn="s-resize",bn="w-resize",mn="ne-resize",hn="nw-resize",pn="se-resize",fn="sw-resize",gn=Ht?"pointerdown":Vt?"touchstart":"mousedown",vn=Ht?"pointermove":Vt?"touchmove":"mousemove",yn=Ht?"pointerup pointercancel":Vt?"touchend touchcancel":"mouseup",wn="error",xn="keydown",kn="load",Cn="resize",Sn="wheel",Nn="action",En="actionend",$n="actionstart",_n="change",zn="transform";const Tn=Number.isNaN||qt.isNaN;function An(e){return"number"==typeof e&&!Tn(e)}function Ln(e){return An(e)&&e>0&&e<1/0}function In(e){return"object"==typeof e&&null!==e}const{hasOwnProperty:Pn}=Object.prototype;function Mn(e){if(!In(e))return!1;try{const{constructor:t}=e,{prototype:n}=t;return t&&n&&Pn.call(n,"isPrototypeOf")}catch(t){return!1}}function Dn(e){return"function"==typeof e}function Rn(e){return"object"==typeof e&&null!==e&&1===e.nodeType}const On=/([a-z\d])([A-Z])/g;function Fn(e){return String(e).replace(On,"$1-$2").toLowerCase()}const jn=/-[A-z\d]/g;function Un(e){return e.replace(jn,e=>e.slice(1).toUpperCase())}const Bn=/\s\s*/;function Wn(e,t,n,l){t.trim().split(Bn).forEach(t=>{e.removeEventListener(t,n,l)})}function qn(e,t,n,l){t.trim().split(Bn).forEach(t=>{e.addEventListener(t,n,l)})}function Vn(e,t,n,l){qn(e,t,n,Object.assign(Object.assign({},l),{once:!0}))}const Hn={bubbles:!0,cancelable:!0,composed:!0};const Kn=Promise.resolve();function Gn(e){const{documentElement:t}=e.ownerDocument,n=e.getBoundingClientRect();return{left:n.left+(qt.pageXOffset-t.clientLeft),top:n.top+(qt.pageYOffset-t.clientTop)}}const Qn=/deg|g?rad|turn$/i;function Xn(e){const t=parseFloat(e)||0;if(0!==t){const[n="rad"]=String(e).match(Qn)||[];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 Yn="contain";function Jn(e,t=Yn){const{aspectRatio:n}=e;let{width:l,height:r}=e;const a=Ln(l),i=Ln(r);if(a&&i){const e=r*n;t===Yn&&e>l||"cover"===t&&e<l?r=l/n:l=r*n}else a?r=l/n:i&&(l=r*n);return{width:l,height:r}}function Zn(e,...t){if(0===t.length)return e;const[n,l,r,a,i,o]=e,[s,c,u,d,b,m]=t[0];return Zn(e=[n*s+r*c,l*s+a*c,n*u+r*d,l*u+a*d,n*b+r*m+i,l*b+a*m+o],...t.slice(1))}const el=/left|top|width|height/i,tl="open",nl=/* @__PURE__ */new WeakMap,ll=/* @__PURE__ */new WeakMap,rl=/* @__PURE__ */new Map,al=qt.document&&Array.isArray(qt.document.adoptedStyleSheets)&&"replaceSync"in qt.CSSStyleSheet.prototype;class il extends HTMLElement{get $sharedStyle(){return(this.themeColor?`:host{--theme-color: ${this.themeColor};}`:"")+":host([hidden]){display:none!important}"}constructor(){var e,t;super(),this.shadowRootMode=tl,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&&rl.set(n,this.tagName.toLowerCase())}static get observedAttributes(){return["shadow-root-mode","slottable","theme-color"]}attributeChangedCallback(e,t,n){if(Object.is(n,t))return;const l=Un(e);let r=n;switch(typeof this[l]){case"boolean":r=null!==n&&"false"!==n;break;case"number":r=Number(n)}switch(this[l]=r,e){case"theme-color":{const e=ll.get(this),t=this.$sharedStyle;e&&t&&(al?e.replaceSync(t):e.textContent=t);break}}}$propertyChangedCallback(e,t,n){if(!Object.is(n,t))switch(e=Fn(e),typeof n){case"boolean":!0===n?this.hasAttribute(e)||this.setAttribute(e,""):this.removeAttribute(e);break;case"number":n=Tn(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=Un(e);let n=this[t];(function(e){return void 0===e})(n)||this.$propertyChangedCallback(t,void 0,n),Object.defineProperty(this,t,{enumerable:!0,configurable:!0,get:()=>n,set(e){const l=n;n=e,this.$propertyChangedCallback(t,l,e)}})});const e=this.shadowRoot||this.attachShadow({mode:this.shadowRootMode||tl});if(nl.set(this,e),ll.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(){ll.has(this)&&ll.delete(this),nl.has(this)&&nl.delete(this)}$getTagNameOf(e){var t;return null!==(t=rl.get(e))&&void 0!==t?t:e}$setStyles(e){return Object.keys(e).forEach(t=>{let n=e[t];An(n)&&(n=0!==n&&el.test(t)?`${n}px`:String(n)),this.style[t]=n}),this}$getShadowRoot(){return this.shadowRoot||nl.get(this)}$addStyles(e){let t;const n=this.$getShadowRoot();return al?(t=new CSSStyleSheet,t.replaceSync(e),n.adoptedStyleSheets=n.adoptedStyleSheets.concat(t)):(t=document.createElement("style"),t.textContent=e,n.appendChild(t)),t}$emit(e,t,n){return function(e,t,n,l){return e.dispatchEvent(new CustomEvent(t,Object.assign(Object.assign(Object.assign({},Hn),{detail:n}),l)))}(this,e,t,n)}$nextTick(e){return function(e,t){return t?Kn.then(e?t.bind(e):t):Kn}(this,e)}static $define(e,t){In(e)&&(t=e,e=""),e||(e=this.$name||this.name),e=Fn(e),Wt&&qt.customElements&&!qt.customElements.get(e)&&customElements.define(e,this,t)}}il.$version="2.1.1";class ol extends il{constructor(){super(...arguments),this.$onPointerDown=null,this.$onPointerMove=null,this.$onPointerUp=null,this.$onWheel=null,this.$wheeling=!1,this.$pointers=/* @__PURE__ */new Map,this.$style=':host{display:block;min-height:100px;min-width:200px;overflow:hidden;position:relative;touch-action:none;-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}:host([background]){background-color:#fff;background-image:repeating-linear-gradient(45deg,#ccc 25%,transparent 0,transparent 75%,#ccc 0,#ccc),repeating-linear-gradient(45deg,#ccc 25%,transparent 0,transparent 75%,#ccc 0,#ccc);background-image:repeating-conic-gradient(#ccc 0 25%,#fff 0 50%);background-position:0 0,.5rem .5rem;background-size:1rem 1rem}:host([disabled]){pointer-events:none}:host([disabled]):after{bottom:0;content:"";cursor:not-allowed;display:block;left:0;pointer-events:none;position:absolute;right:0;top:0}',this.$action=sn,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),qn(this,gn,this.$onPointerDown)),this.$onPointerMove||(this.$onPointerMove=this.$handlePointerMove.bind(this),qn(this.ownerDocument,vn,this.$onPointerMove)),this.$onPointerUp||(this.$onPointerUp=this.$handlePointerUp.bind(this),qn(this.ownerDocument,yn,this.$onPointerUp)),this.$onWheel||(this.$onWheel=this.$handleWheel.bind(this),qn(this,Sn,this.$onWheel,{passive:!1,capture:!0}))}$unbind(){this.$onPointerDown&&(Wn(this,gn,this.$onPointerDown),this.$onPointerDown=null),this.$onPointerMove&&(Wn(this.ownerDocument,vn,this.$onPointerMove),this.$onPointerMove=null),this.$onPointerUp&&(Wn(this.ownerDocument,yn,this.$onPointerUp),this.$onPointerUp=null),this.$onWheel&&(Wn(this,Sn,this.$onWheel,{capture:!0}),this.$onWheel=null)}$handlePointerDown(e){const{buttons:t,button:n,type:l}=e;if(this.disabled||("pointerdown"===l&&"mouse"===e.pointerType||"mousedown"===l)&&(An(t)&&1!==t||An(n)&&0!==n||e.ctrlKey))return;const{$pointers:r}=this;let a="";if(e.changedTouches)Array.from(e.changedTouches).forEach(({identifier:e,pageX:t,pageY:n})=>{r.set(e,{startX:t,startY:n,endX:t,endY:n})});else{const{pointerId:t=0,pageX:n,pageY:l}=e;r.set(t,{startX:n,startY:l,endX:n,endY:l})}r.size>1?a=on:Rn(e.target)&&(a=e.target.action||e.target.getAttribute("action")||""),!1!==this.$emit($n,{action:a,relatedEvent:e})&&(e.preventDefault(),this.$action=a,this.style.willChange="transform")}$handlePointerMove(e){const{$action:t,$pointers:n}=this;if(this.disabled||t===sn||0===n.size)return;if(!1===this.$emit("actionmove",{action:t,relatedEvent:e}))return;if(e.preventDefault(),e.changedTouches)Array.from(e.changedTouches).forEach(({identifier:e,pageX:t,pageY:l})=>{const r=n.get(e);r&&Object.assign(r,{endX:t,endY:l})});else{const{pointerId:t=0,pageX:l,pageY:r}=e,a=n.get(t);a&&Object.assign(a,{endX:l,endY:r})}const l={action:t,relatedEvent:e};if(t===on){const t=new Map(n);let r=0,a=0,i=0,o=0,s=e.pageX,c=e.pageY;n.forEach((e,n)=>{t.delete(n),t.forEach(t=>{let n=t.startX-e.startX,l=t.startY-e.startY,u=t.endX-e.endX,d=t.endY-e.endY,b=0,m=0,h=0,p=0;if(0===n?l<0?h=2*Math.PI:l>0&&(h=Math.PI):n>0?h=Math.PI/2+Math.atan(l/n):n<0&&(h=1.5*Math.PI+Math.atan(l/n)),0===u?d<0?p=2*Math.PI:d>0&&(p=Math.PI):u>0?p=Math.PI/2+Math.atan(d/u):u<0&&(p=1.5*Math.PI+Math.atan(d/u)),p>0||h>0){const n=p-h,l=Math.abs(n);l>r&&(r=l,i=n,s=(e.startX+t.startX)/2,c=(e.startY+t.startY)/2)}if(n=Math.abs(n),l=Math.abs(l),u=Math.abs(u),d=Math.abs(d),n>0&&l>0?b=Math.sqrt(n*n+l*l):n>0?b=n:l>0&&(b=l),u>0&&d>0?m=Math.sqrt(u*u+d*d):u>0?m=u:d>0&&(m=d),b>0&&m>0){const n=(m-b)/b,l=Math.abs(n);l>a&&(a=l,o=n,s=(e.startX+t.startX)/2,c=(e.startY+t.startY)/2)}})});const u=r>0,d=a>0;u&&d?(l.rotate=i,l.scale=o,l.centerX=s,l.centerY=c):u?(l.action=an,l.rotate=i,l.centerX=s,l.centerY=c):d?(l.action=rn,l.scale=o,l.centerX=s,l.centerY=c):l.action=sn}else{const[e]=Array.from(n.values());Object.assign(l,e)}n.forEach(e=>{e.startX=e.endX,e.startY=e.endY}),l.action!==sn&&this.$emit(Nn,l,{cancelable:!1})}$handlePointerUp(e){const{$action:t,$pointers:n}=this;if(!this.disabled&&t!==sn&&!1!==this.$emit(En,{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=sn)}}$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(Nn,{action:rn,scale:t,relatedEvent:e},{cancelable:!1})}$setAction(e){return"string"==typeof e&&(this.$action=e),this}$toCanvas(e){return new Promise((t,n)=>{if(!this.isConnected)return void n(new Error("The current element is not connected to the DOM."));const l=document.createElement("canvas");let r=this.offsetWidth,a=this.offsetHeight,i=1;Mn(e)&&(Ln(e.width)||Ln(e.height))&&(({width:r,height:a}=Jn({aspectRatio:r/a,width:e.width,height:e.height})),i=r/this.offsetWidth),l.width=r,l.height=a;const o=this.querySelector(this.$getTagNameOf(Jt));o?o.$ready().then(n=>{const s=l.getContext("2d");if(s){const[t,c,u,d,b,m]=o.$getTransform();let h=b,p=m,f=n.naturalWidth,g=n.naturalHeight;1!==i&&(h*=i,p*=i,f*=i,g*=i);const v=f/2,y=g/2;s.fillStyle="transparent",s.fillRect(0,0,r,a),Mn(e)&&Dn(e.beforeDraw)&&e.beforeDraw.call(this,s,l),s.save(),s.translate(v,y),s.transform(t,c,u,d,h,p),s.translate(-v,-y),s.drawImage(n,0,0,f,g),s.restore()}t(l)}).catch(n):t(l)})}}ol.$name=Gt,ol.$version="2.1.1";const sl=/* @__PURE__ */new WeakMap,cl=["alt","crossorigin","decoding","elementtiming","fetchpriority","loading","referrerpolicy","sizes","src","srcset"];class ul extends il{constructor(){super(...arguments),this.$isReady=!1,this.$matrix=[1,0,0,1,0,0],this.$onLoad=null,this.$onCanvasAction=null,this.$onCanvasActionEnd=null,this.$onCanvasActionStart=null,this.$actionStartTarget=null,this.$style=":host{display:inline-block}img{display:block;height:100%;max-height:none!important;max-width:none!important;min-height:0!important;min-width:0!important;width:100%}",this.$image=new Image,this.initialCenterSize="contain",this.rotatable=!1,this.scalable=!1,this.skewable=!1,this.slottable=!1,this.translatable=!1,this.alt="",this.crossorigin="",this.decoding="",this.elementtiming="",this.fetchpriority="",this.loading="",this.referrerpolicy="",this.sizes="",this.src="",this.srcset=""}set $canvas(e){sl.set(this,e)}get $canvas(){return sl.get(this)}static get observedAttributes(){return super.observedAttributes.concat(cl,["initial-center-size","rotatable","scalable","skewable","translatable"])}attributeChangedCallback(e,t,n){Object.is(n,t)||(super.attributeChangedCallback(e,t,n),cl.includes(e)&&this.$image.setAttribute(e,n))}$propertyChangedCallback(e,t,n){if(!Object.is(n,t))switch(super.$propertyChangedCallback(e,t,n),e){case"initialCenterSize":this.$nextTick(()=>{this.$center(n)});break;case"src":this.$isReady=!1}}connectedCallback(){super.connectedCallback();const{$image:e}=this,t=this.closest(this.$getTagNameOf(Gt));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),qn(t,$n,this.$onCanvasActionStart),qn(t,En,this.$onCanvasActionEnd),qn(t,Nn,this.$onCanvasAction)),this.$onLoad=this.$handleLoad.bind(this),qn(e,kn,this.$onLoad),this.$getShadowRoot().appendChild(e)}disconnectedCallback(){const{$image:e,$canvas:t}=this;t&&(this.$onCanvasActionStart&&(Wn(t,$n,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(Wn(t,En,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasAction&&(Wn(t,Nn,this.$onCanvasAction),this.$onCanvasAction=null)),e&&this.$onLoad&&(Wn(e,kn,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),this.$isReady=!0}$handleAction(e){if(this.hidden||!(this.rotatable||this.scalable||this.translatable))return;const{$canvas:t}=this,{detail:n}=e;if(n){const{relatedEvent:e}=n;let{action:l}=n;switch(l!==on||this.rotatable&&this.scalable||(l=this.rotatable?an:this.scalable?rn:sn),l){case ln:if(this.translatable){let l=null;e&&(l=e.target.closest(this.$getTagNameOf(Zt))),l||(l=t.querySelector(this.$getTagNameOf(Zt))),l&&l.multiple&&!l.active&&(l=t.querySelector(`${this.$getTagNameOf(Zt)}[active]`)),l&&!l.hidden&&l.movable&&!l.dynamic&&this.$actionStartTarget&&l.contains(this.$actionStartTarget)||this.$move(n.endX-n.startX,n.endY-n.startY)}break;case an:if(this.rotatable)if(e){const{x:t,y:l}=this.getBoundingClientRect();this.$rotate(n.rotate,e.clientX-t,e.clientY-l)}else this.$rotate(n.rotate);break;case rn:if(this.scalable)if(e){const t=e.target.closest(this.$getTagNameOf(Zt));if(!t||!t.zoomable||t.zoomable&&t.dynamic){const{x:t,y:l}=this.getBoundingClientRect();this.$zoom(n.scale,e.clientX-t,e.clientY-l)}}else this.$zoom(n.scale);break;case on:if(this.rotatable&&this.scalable){const{rotate:t}=n;let{scale:l}=n;l<0?l=1/(1-l):l+=1;const r=Math.cos(t),a=Math.sin(t),[i,o,s,c]=[r*l,a*l,-a*l,r*l];if(e){const t=this.getBoundingClientRect(),n=e.clientX-t.x,l=e.clientY-t.y,[r,a,u,d]=this.$matrix,b=n-t.width/2,m=l-t.height/2,h=(b*d-u*m)/(r*d-u*a),p=(m*r-a*b)/(r*d-u*a);this.$transform(i,o,s,c,h*(1-i)+p*s,p*(1-c)+h*o)}else this.$transform(i,o,s,c,0,0)}}}}$ready(e){const{$image:t}=this,n=new Promise((e,n)=>{const l=new Error("Failed to load the image source");if(t.complete)t.naturalWidth>0&&t.naturalHeight>0?e(t):n(l);else{const r=()=>{Wn(t,wn,a),setTimeout(()=>{e(t)})},a=()=>{Wn(t,kn,r),n(l)};Vn(t,kn,r),Vn(t,wn,a)}});return Dn(e)&&n.then(t=>(e(t),t)),n}$center(e){const{parentElement:t}=this;if(!t)return this;const n=t.getBoundingClientRect(),l=n.width,r=n.height,{x:a,y:i,width:o,height:s}=this.getBoundingClientRect(),c=a+o/2,u=i+s/2,d=n.x+l/2,b=n.y+r/2,{translatable:m}=this;if(m||this.$isReady||(this.translatable=!0,this.$nextTick(()=>{this.translatable=m})),this.$move(d-c,b-u),e&&(o!==l||s!==r)){const t=l/o,n=r/s,{scalable:a}=this;switch(!e||a||this.$isReady||(this.scalable=!0,this.$nextTick(()=>{this.scalable=a})),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&&An(e)&&An(t)){const[n,l,r,a]=this.$matrix,i=(e*a-r*t)/(n*a-r*l),o=(t*n-l*e)/(n*a-r*l);this.$translate(i,o)}return this}$moveTo(e,t=e){if(this.translatable&&An(e)&&An(t)){const[n,l,r,a]=this.$matrix,i=(e*a-r*t)/(n*a-r*l),o=(t*n-l*e)/(n*a-r*l);this.$setTransform(n,l,r,a,i,o)}return this}$rotate(e,t,n){if(this.rotatable){const l=Xn(e),r=Math.cos(l),a=Math.sin(l),[i,o,s,c]=[r,a,-a,r];if(An(t)&&An(n)){const[e,l,r,a]=this.$matrix,{width:u,height:d}=this.getBoundingClientRect(),b=t-u/2,m=n-d/2,h=(b*a-r*m)/(e*a-r*l),p=(m*e-l*b)/(e*a-r*l);this.$transform(i,o,s,c,h*(1-i)-p*s,p*(1-c)-h*o)}else this.$transform(i,o,s,c,0,0)}return this}$zoom(e,t,n){if(!this.scalable||0===e)return this;if(e<0?e=1/(1-e):e+=1,An(t)&&An(n)){const[l,r,a,i]=this.$matrix,{width:o,height:s}=this.getBoundingClientRect(),c=t-o/2,u=n-s/2,d=(c*i-a*u)/(l*i-a*r),b=(u*l-r*c)/(l*i-a*r);this.$transform(e,0,0,e,d*(1-e),b*(1-e))}else this.$scale(e);return this}$scale(e,t=e){return this.scalable&&this.$transform(e,0,0,t,0,0),this}$skew(e,t=0){if(this.skewable){const n=Xn(e),l=Xn(t);this.$transform(1,Math.tan(l),Math.tan(n),1,0,0)}return this}$translate(e,t=e){return this.translatable&&An(e)&&An(t)&&this.$transform(1,0,0,1,e,t),this}$transform(e,t,n,l,r,a){return An(e)&&An(t)&&An(n)&&An(l)&&An(r)&&An(a)?this.$setTransform(Zn(this.$matrix,[e,t,n,l,r,a])):this}$setTransform(e,t,n,l,r,a){if((this.rotatable||this.scalable||this.skewable||this.translatable)&&(Array.isArray(e)&&([e,t,n,l,r,a]=e),An(e)&&An(t)&&An(n)&&An(l)&&An(r)&&An(a))){const i=[...this.$matrix],o=[e,t,n,l,r,a];if(!1===this.$emit(zn,{matrix:o,oldMatrix:i}))return this;this.$matrix=o,this.style.transform=`matrix(${o.join(", ")})`}return this}$getTransform(){return this.$matrix.slice()}$resetTransform(){return this.$setTransform([1,0,0,1,0,0])}}ul.$name=Jt,ul.$version="2.1.1";const dl=/* @__PURE__ */new WeakMap;class bl extends il{constructor(){super(...arguments),this.$onWindowResize=null,this.$onCanvasActionEnd=null,this.$onCanvasActionStart=null,this.$onSelectionChange=null,this.$style=":host{display:block;height:0;left:0;outline:var(--theme-color) solid 1px;position:relative;top:0;width:0}:host([transparent]){outline-color:transparent}",this.x=0,this.y=0,this.width=0,this.height=0,this.slottable=!1,this.themeColor="rgba(0, 0, 0, 0.65)"}set $canvas(e){dl.set(this,e)}get $canvas(){return dl.get(this)}static get observedAttributes(){return super.observedAttributes.concat(["height","width","x","y"])}connectedCallback(){super.connectedCallback();const e=this.closest(this.$getTagNameOf(Gt));if(e){this.$canvas=e,this.style.position="absolute";const t=e.querySelector(this.$getTagNameOf(Zt));t&&(this.$onWindowResize=this.$render.bind(this),this.$onCanvasActionStart=e=>{t.hidden&&e.detail.action===nn&&(this.hidden=!1)},this.$onCanvasActionEnd=e=>{t.hidden&&e.detail.action===nn&&(this.hidden=!0)},this.$onSelectionChange=e=>{const{x:n,y:l,width:r,height:a}=e.defaultPrevented?t:e.detail;this.$change(n,l,r,a),(t.hidden||0===n&&0===l&&0===r&&0===a)&&(this.hidden=!0)},qn(window,Cn,this.$onWindowResize),qn(e,$n,this.$onCanvasActionStart),qn(e,En,this.$onCanvasActionEnd),qn(e,_n,this.$onSelectionChange))}this.$render()}disconnectedCallback(){const{$canvas:e}=this;e&&(this.$onWindowResize&&(Wn(window,Cn,this.$onWindowResize),this.$onWindowResize=null),this.$onCanvasActionStart&&(Wn(e,$n,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(Wn(e,En,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onSelectionChange&&(Wn(e,_n,this.$onSelectionChange),this.$onSelectionChange=null)),super.disconnectedCallback()}$change(e,t,n=this.width,l=this.height){return An(e)&&An(t)&&An(n)&&An(l)&&(e!==this.x||t!==this.y||n!==this.width||l!==this.height)?(this.hidden&&(this.hidden=!1),this.x=e,this.y=t,this.width=n,this.height=l,this.$render()):this}$reset(){return this.$change(0,0,0,0)}$render(){return this.$setStyles({transform:`translate(${this.x}px, ${this.y}px)`,width:this.width,height:this.height,outlineWidth:qt.innerWidth*qt.devicePixelRatio})}}bl.$name=en,bl.$version="2.1.1";class ml extends il{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=sn,this.plain=!1,this.slottable=!1,this.themeColor="rgba(51, 153, 255, 0.5)"}static get observedAttributes(){return super.observedAttributes.concat(["action","plain"])}}ml.$name=Yt,ml.$version="2.1.1";const hl=/* @__PURE__ */new WeakMap;class pl extends il{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){hl.set(this,e)}get $canvas(){return hl.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(()=>{Ln(n)&&n<=1&&this.$initSelection(!0,!0)});break;case"keyboard":this.$nextTick(()=>{this.$canvas&&(n?this.$onDocumentKeyDown||(this.$onDocumentKeyDown=this.$handleKeyDown.bind(this),qn(this.ownerDocument,xn,this.$onDocumentKeyDown)):this.$onDocumentKeyDown&&(Wn(this.ownerDocument,xn,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(_n,{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(Gt));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),qn(e,$n,this.$onCanvasActionStart),qn(e,En,this.$onCanvasActionEnd),qn(e,Nn,this.$onCanvasAction)):this.$render()}disconnectedCallback(){const{$canvas:e}=this;e&&(this.$onCanvasActionStart&&(Wn(e,$n,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(Wn(e,En,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasAction&&(Wn(e,Nn,this.$onCanvasAction),this.$onCanvasAction=null)),super.disconnectedCallback()}$getSelections(){let e=[];return this.parentElement&&(e=Array.from(this.parentElement.querySelectorAll(this.$getTagNameOf(Zt)))),e}$initSelection(e=!1,t=!1){const{initialCoverage:n,parentElement:l}=this;if(Ln(n)&&l){const r=this.aspectRatio||this.initialAspectRatio;let a=(t?0:this.width)||l.offsetWidth*n,i=(t?0:this.height)||l.offsetHeight*n;Ln(r)&&({width:a,height:i}=Jn({aspectRatio:r,width:a,height:i})),this.$change(this.x,this.y,a,i),e&&this.$center(),this.$initialSelection={x:this.x,y:this.y,width:this.width,height:this.height}}}$createSelection(){const e=this.cloneNode(!0);return this.hasAttribute("id")&&e.removeAttribute("id"),e.initialCoverage=NaN,this.active=!1,this.parentElement&&this.parentElement.insertBefore(e,this.nextSibling),e}$removeSelection(e=this){if(this.parentElement){const t=this.$getSelections();if(t.length>1){const n=t.indexOf(e),l=t[n+1]||t[n-1];l&&(e.active=!1,this.parentElement.removeChild(e),l.active=!0,l.$emit(_n,{x:l.x,y:l.y,width:l.width,height:l.height}))}else this.$clear()}}$handleActionStart(e){var t,n;const l=null===(n=null===(t=e.detail)||void 0===t?void 0:t.relatedEvent)||void 0===n?void 0:n.target;this.$action="",this.$actionStartTarget=l,!this.hidden&&this.multiple&&!this.active&&l===this&&this.parentElement&&(this.$getSelections().forEach(e=>{e.active=!1}),this.active=!0,this.$emit(_n,{x:this.x,y:this.y,width:this.width,height:this.height}))}$handleAction(e){const{currentTarget:t,detail:n}=e;if(!t||!n)return;const{relatedEvent:l}=n;let{action:r}=n;const a=l?function(e){if("function"==typeof e.composedPath)return e.composedPath().find(Rn)||e.target;return e.target}(l):null;if(!r&&this.multiple&&(r=this.$action||(null==a?void 0:a.action),this.$action=r),!r||this.hidden&&r!==nn||this.multiple&&!this.active&&r!==rn)return;const{width:i,height:o}=this;let s=n.endX-n.startX,c=n.endY-n.startY,{aspectRatio:u}=this;switch(!Ln(u)&&l.shiftKey&&(u=Ln(i)&&Ln(o)?i/o:1),r){case nn:if(0!==s||0!==c){0===s?s=c:0===c&&(c=s);const{$canvas:e}=this,l=Gn(t);(this.multiple&&!this.hidden?this.$createSelection():this).$change(n.startX-l.left,n.startY-l.top,Math.abs(s),Math.abs(c),u),s<0?c<0?r=hn:c>0&&(r=fn):s>0&&(c<0?r=mn:c>0&&(r=pn)),e&&(e.$action=r)}break;case ln:this.movable&&(this.dynamic||this.$actionStartTarget&&this.contains(this.$actionStartTarget))&&this.$move(s,c);break;case rn:if(l&&this.zoomable&&(this.dynamic||this.contains(l.target))){const e=Gn(t);this.$zoom(n.scale,l.pageX-e.left,l.pageY-e.top)}break;default:this.$resize(r,s,c,u)}}$handleActionEnd(){this.$action="",this.$actionStartTarget=null}$handleKeyDown(e){if(this.hidden||!this.keyboard||this.multiple&&!this.active||e.defaultPrevented)return;const{activeElement:t}=document;if(!t||!["INPUT","TEXTAREA"].includes(t.tagName)&&!["true","plaintext-only"].includes(t.contentEditable))switch(e.key){case"Backspace":e.metaKey&&(e.preventDefault(),this.$removeSelection());break;case"Delete":e.preventDefault(),this.$removeSelection();break;case"ArrowLeft":e.preventDefault(),this.$move(-1,0);break;case"ArrowRight":e.preventDefault(),this.$move(1,0);break;case"ArrowUp":e.preventDefault(),this.$move(0,-1);break;case"ArrowDown":e.preventDefault(),this.$move(0,1);break;case"+":e.preventDefault(),this.$zoom(.1);break;case"-":e.preventDefault(),this.$zoom(-.1)}}$center(){const{parentElement:e}=this;if(!e)return this;const t=(e.offsetWidth-this.width)/2,n=(e.offsetHeight-this.height)/2;return this.$change(t,n)}$move(e,t=e){return this.$moveTo(this.x+e,this.y+t)}$moveTo(e,t=e){return this.movable?this.$change(e,t):this}$resize(e,t=0,n=0,l=this.aspectRatio){if(!this.resizable)return this;const r=Ln(l),{$canvas:a}=this;let{x:i,y:o,width:s,height:c}=this;switch(e){case cn:o+=n,c-=n,c<0&&(e=dn,c=-c,o-=c),r&&(i+=(t=n*l)/2,s-=t,s<0&&(s=-s,i-=s));break;case un:s+=t,s<0&&(e=bn,s=-s,i-=s),r&&(o-=(n=t/l)/2,c+=n,c<0&&(c=-c,o-=c));break;case dn:c+=n,c<0&&(e=cn,c=-c,o-=c),r&&(i-=(t=n*l)/2,s+=t,s<0&&(s=-s,i-=s));break;case bn:i+=t,s-=t,s<0&&(e=un,s=-s,i-=s),r&&(o+=(n=t/l)/2,c-=n,c<0&&(c=-c,o-=c));break;case mn:r&&(n=-t/l),o+=n,c-=n,s+=t,s<0&&c<0?(e=fn,s=-s,c=-c,i-=s,o-=c):s<0?(e=hn,s=-s,i-=s):c<0&&(e=pn,c=-c,o-=c);break;case hn:r&&(n=t/l),i+=t,o+=n,s-=t,c-=n,s<0&&c<0?(e=pn,s=-s,c=-c,i-=s,o-=c):s<0?(e=mn,s=-s,i-=s):c<0&&(e=fn,c=-c,o-=c);break;case pn:r&&(n=t/l),s+=t,c+=n,s<0&&c<0?(e=hn,s=-s,c=-c,i-=s,o-=c):s<0?(e=fn,s=-s,i-=s):c<0&&(e=mn,c=-c,o-=c);break;case fn:r&&(n=-t/l),i+=t,s-=t,c+=n,s<0&&c<0?(e=mn,s=-s,c=-c,i-=s,o-=c):s<0?(e=pn,s=-s,i-=s):c<0&&(e=hn,c=-c,o-=c)}return a&&a.$setAction(e),this.$change(i,o,s,c)}$zoom(e,t,n){if(!this.zoomable||0===e)return this;e<0?e=1/(1-e):e+=1;const{width:l,height:r}=this,a=l*e,i=r*e;let o=this.x,s=this.y;return An(t)&&An(n)?(o-=(a-l)*((t-this.x)/l),s-=(i-r)*((n-this.y)/r)):(o-=(a-l)/2,s-=(i-r)/2),this.$change(o,s,a,i)}$change(e,t,n=this.width,l=this.height,r=this.aspectRatio,a=!1){return this.$changing||!An(e)||!An(t)||!An(n)||!An(l)||n<0||l<0?this:(Ln(r)&&({width:n,height:l}=Jn({aspectRatio:r,width:n,height:l},"cover")),this.precise||(e=Math.round(e),t=Math.round(t),n=Math.round(n),l=Math.round(l)),e===this.x&&t===this.y&&n===this.width&&l===this.height&&Object.is(r,this.aspectRatio)&&!a?this:(this.hidden&&(this.hidden=!1),!1===this.$emit(_n,{x:e,y:t,width:n,height:l})?this:(this.$changing=!0,this.x=e,this.y=t,this.width=n,this.height=l,this.$changing=!1,this.$render())))}$reset(){const{x:e,y:t,width:n,height:l}=this.$initialSelection;return this.$change(e,t,n,l)}$clear(){return this.$change(0,0,0,0,NaN,!0),this.hidden=!0,this}$render(){return this.$setStyles({transform:`translate(${this.x}px, ${this.y}px)`,width:this.width,height:this.height})}$toCanvas(e){return new Promise((t,n)=>{if(!this.isConnected)return void n(new Error("The current element is not connected to the DOM."));const l=document.createElement("canvas");let{width:r,height:a}=this,i=1;if(Mn(e)&&(Ln(e.width)||Ln(e.height))&&(({width:r,height:a}=Jn({aspectRatio:r/a,width:e.width,height:e.height})),i=r/this.width),l.width=r,l.height=a,!this.$canvas)return void t(l);const o=this.$canvas.querySelector(this.$getTagNameOf(Jt));o?o.$ready().then(n=>{const s=l.getContext("2d");if(s){const[t,c,u,d,b,m]=o.$getTransform(),h=-this.x,p=-this.y,f=(h*d-u*p)/(t*d-u*c),g=(p*t-c*h)/(t*d-u*c);let v=t*f+u*g+b,y=c*f+d*g+m,w=n.naturalWidth,x=n.naturalHeight;1!==i&&(v*=i,y*=i,w*=i,x*=i);const k=w/2,C=x/2;s.fillStyle="transparent",s.fillRect(0,0,r,a),Mn(e)&&Dn(e.beforeDraw)&&e.beforeDraw.call(this,s,l),s.save(),s.translate(k,C),s.transform(t,c,u,d,v,y),s.translate(-k,-C),s.drawImage(n,0,0,w,x),s.restore()}t(l)}).catch(n):t(l)})}}pl.$name=Zt,pl.$version="2.1.1";class fl extends il{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))}}fl.$name=Xt,fl.$version="2.1.1";class gl extends il{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"])}}gl.$name=Qt,gl.$version="2.1.1";const vl=/* @__PURE__ */new WeakMap,yl=/* @__PURE__ */new WeakMap,wl=/* @__PURE__ */new WeakMap,xl=/* @__PURE__ */new WeakMap,kl="vertical";class Cl extends il{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=kl,this.selection="",this.slottable=!1}set $image(e){yl.set(this,e)}get $image(){return yl.get(this)}set $sourceImage(e){xl.set(this,e)}get $sourceImage(){return xl.get(this)}set $canvas(e){vl.set(this,e)}get $canvas(){return vl.get(this)}set $selection(e){wl.set(this,e)}get $selection(){return wl.get(this)}static get observedAttributes(){return super.observedAttributes.concat(["resize","selection"])}connectedCallback(){var e,t;super.connectedCallback();let n=null;if(n=this.selection?null!==(t=null===(e=function(e){const t=e.getRootNode();switch(t.nodeType){case 1:return t.ownerDocument;case 9:case 11:return t}return null}(this))||void 0===e?void 0:e.querySelector(this.selection))&&void 0!==t?t:null:this.closest(this.$getTagNameOf(Zt)),Rn(n)){this.$selection=n,this.$onSelectionChange=this.$handleSelectionChange.bind(this),qn(n,_n,this.$onSelectionChange);const e=n.closest(this.$getTagNameOf(Gt));if(e){this.$canvas=e;const t=e.querySelector(this.$getTagNameOf(Jt));t&&(this.$sourceImage=t,this.$image=t.cloneNode(!0),this.$getShadowRoot().appendChild(this.$image),this.$onSourceImageLoad=this.$handleSourceImageLoad.bind(this),this.$onSourceImageTransform=this.$handleSourceImageTransform.bind(this),qn(t.$image,kn,this.$onSourceImageLoad),qn(t,zn,this.$onSourceImageTransform))}this.$render()}}disconnectedCallback(){const{$selection:e,$sourceImage:t}=this;e&&this.$onSelectionChange&&(Wn(e,_n,this.$onSelectionChange),this.$onSelectionChange=null),t&&this.$onSourceImageLoad&&(Wn(t.$image,kn,this.$onSourceImageLoad),this.$onSourceImageLoad=null),t&&this.$onSourceImageTransform&&(Wn(t,zn,this.$onSourceImageTransform),this.$onSourceImageTransform=null),super.disconnectedCallback()}$handleSelectionChange(e){this.$render(e.defaultPrevented?this.$selection:e.detail)}$handleSourceImageLoad(){const{$image:e,$sourceImage:t}=this,n=e.getAttribute("src"),l=t.getAttribute("src");l&&l!==n&&(e.setAttribute("src",l),e.$ready(()=>{this.$render()}))}$handleSourceImageTransform(e){this.$render(void 0,e.detail.matrix)}$render(e,t){const{$canvas:n,$selection:l}=this;e||l.hidden||(e=l),(!e||0===e.x&&0===e.y&&0===e.width&&0===e.height)&&(e={x:0,y:0,width:n.offsetWidth,height:n.offsetHeight});const{x:r,y:a,width:i,height:o}=e,s={},{clientWidth:c,clientHeight:u}=this;let d=c,b=u,m=NaN;switch(this.resize){case"both":m=1,d=i,b=o,s.width=i,s.height=o;break;case"horizontal":m=o>0?u/o:0,d=i*m,s.width=d;break;case kl:m=i>0?c/i:0,b=o*m,s.height=b;break;default:c>0?m=i>0?c/i:0:u>0&&(m=o>0?u/o:0)}this.$scale=m,this.$setStyles(s),this.$sourceImage&&setTimeout(()=>{this.$transformImageByOffset(null!=t?t:this.$sourceImage.$getTransform(),-r,-a)})}$transformImageByOffset(e,t,n){const{$image:l,$scale:r,$sourceImage:a}=this;if(a&&l&&r>=0){const[i,o,s,c,u,d]=e,b=(t*c-s*n)/(i*c-s*o),m=(n*i-o*t)/(i*c-s*o),h=i*b+s*m+u,p=o*b+c*m+d;a.$ready(e=>{this.$setStyles.call(l,{width:e.naturalWidth*r,height:e.naturalHeight*r})}),l.$setTransform(i,o,s,c,h*r,p*r)}}}function Sl(){const[e,n]=t(!1),[l,r]=t(null),[a,i]=t(null),o=async(e,t)=>{if(!e||!t)return r("ID de asset y configuración de variante son requeridos"),null;n(!0),r(null),i(null);try{const n=await async function(e,{variant_name:t,width:n,height:r,crop_params:a,preset_aspect:i=null,preset_size:o=null,output_format:s="webp"}){try{const l=[{name:t,width:n,height:r,output_format:s,crop_params:a}];return i&&(l[0].preset_aspect=i),o&&(l[0].preset_size=o),J(await H({endpoint:`/assets/${e}/variants`,method:"POST",body:{variants:l,async:!1},basePath:ee,useJWT:!0}))}catch(l){throw Z(l)}}(e,{variant_name:t.name,width:t.width,height:t.height,crop_params:t.crop_params,preset_aspect:t.preset_aspect,preset_size:t.preset_size,output_format:t.output_format});if(n?.result)return i(n.result),n.result;throw new Error("No se pudo crear la variante")}catch(a){return console.error("Error creating variant:",a),r(a.message||"Error desconocido al crear variante"),null}finally{n(!1)}};return{createVariant:o,createCropVariant:async(e,t,n={})=>{const l={name:n.name||`crop_${Date.now()}`,width:n.width||800,height:n.height||600,output_format:n.format||"webp",crop_params:{x:t.x||0,y:t.y||0,width:t.width||1,height:t.height||1}};return await o(e,l)},createVariantFromBlob:async(e,t,a={})=>{if(!e||!t)return r("ID de asset y blob son requeridos"),null;n(!0),r(null),i(null);try{const n=await async function(e,t,n={}){try{const l=new FormData,r=n.format||"webp",a=`${n.name||"variant"}.${r}`;return l.append("file",t,a),l.append("variant_name",n.name||"variant"),l.append("width",String(n.width||0)),l.append("height",String(n.height||0)),l.append("output_format",n.format||"webp"),l.append("permanent_url",!1!==n.permanentUrl?"true":"false"),J(await H({endpoint:`/assets/${e}/variants/upload`,method:"POST",body:l,basePath:ee,isFormData:!0,useJWT:!0}))}catch(l){throw Z(l)}}(e,t,{name:a.name||`crop_${Date.now()}`,width:a.width||0,height:a.height||0,format:a.format||"webp"});if(n?.result)return i(n.result),n.result;throw new Error("No se pudo crear la variante")}catch(o){return console.error("Error creating variant from blob:",o),r(o.message||"Error desconocido al crear variante"),null}finally{n(!1)}},loading:e,error:l,createdVariant:a,reset:()=>{r(null),i(null)}}}Cl.$name=tn,Cl.$version="2.1.1",ol.$define(),gl.$define(),fl.$define(),ml.$define(),ul.$define(),pl.$define(),bl.$define(),Cl.$define();class Nl{constructor(e,t,n){this.canvasRef=e,this.imageRef=t,this.selectionRef=n}get canvasElement(){return this.canvasRef?.current}get image(){return this.imageRef?.current}get selectionElement(){return this.selectionRef?.current}get isReady(){return!!(this.canvasElement&&this.image&&this.selectionElement)}transform={move:(e,t)=>{if(!this.image)return!1;try{return this.image.$move(e,t),!0}catch(n){return console.warn("Error moving image:",n),!1}},moveTo:(e,t)=>{if(!this.image)return!1;try{return this.image.$moveTo(e,t),!0}catch(n){return console.warn("Error moving image to position:",n),!1}},zoom:e=>{if(!this.image)return!1;try{return this.image.$zoom(e),!0}catch(t){return console.warn("Error zooming image:",t),!1}},rotate:e=>{if(!this.image)return!1;try{const t=e*Math.PI/180;return this.image.$rotate(t),!0}catch(t){return console.warn("Error rotating image:",t),!1}},scale:(e,t=e)=>{if(!this.image)return!1;try{return this.image.$scale(e,t),!0}catch(n){return console.warn("Error scaling image:",n),!1}},center:(e="contain")=>{if(!this.image)return!1;try{return this.image.$center(e),!0}catch(t){return console.warn("Error centering image:",t),!1}},reset:()=>{if(!this.image)return!1;try{return this.image.$resetTransform(),!0}catch(e){return console.warn("Error resetting transform:",e),!1}},getTransform:()=>{if(!this.image)return null;try{return this.image.$getTransform()}catch(e){return console.warn("Error getting transform:",e),null}},setTransform:(e,t,n,l,r,a)=>{if(!this.image)return!1;try{return this.image.$setTransform(e,t,n,l,r,a),!0}catch(i){return console.warn("Error setting transform:",i),!1}},resetZoom:()=>{if(!this.image)return!1;try{const e=this.image.$getTransform();if(!e)return!1;const[t,n,l,r,a,i]=e,o=Math.sqrt(t*t+n*n),s=Math.sqrt(l*l+r*r),c=t/o,u=n/o,d=l/s,b=r/s;return this.image.$setTransform(c,u,d,b,a,i),!0}catch(e){return console.warn("Error resetting zoom:",e),!1}},setZoom:e=>{if(!this.image||e<=0)return!1;try{const t=this.image.$getTransform();if(!t)return!1;const[n,l,r,a,i,o]=t,s=Math.sqrt(n*n+l*l),c=Math.sqrt(r*r+a*a),u=n/s*e,d=l/s*e,b=r/c*e,m=a/c*e;return this.image.$setTransform(u,d,b,m,i,o),!0}catch(t){return console.warn("Error setting zoom level:",t),!1}},getZoom:()=>{if(!this.image)return 1;try{const e=this.image.$getTransform();if(!e)return 1;const[t,n]=e;return Math.sqrt(t*t+n*n)}catch(e){return console.warn("Error getting zoom level:",e),1}},fitToCanvas:(e=.1)=>{if(!this.image||!this.canvasElement)return!1;try{const t=this.canvasElement.getBoundingClientRect();let n=this.image.querySelector("img")||this.image;if(!n?.naturalWidth||!n?.naturalHeight)return!1;const l=1-e,r=t.width*l/n.naturalWidth,a=t.height*l/n.naturalHeight,i=Math.min(r,a,1);return this.transform.setZoom(i)}catch(t){return console.warn("Error fitting to canvas:",t),!1}}};selection={center:()=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$center(),!0}catch(e){return console.warn("Error centering selection:",e),!1}},reset:()=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$reset(),!0}catch(e){return console.warn("Error resetting selection:",e),!1}},setCoverage:e=>{if(!this.selectionElement||e<0||e>1)return!1;try{return this.selectionElement.initialCoverage=e,this.selectionElement.$reset(),!0}catch(t){return console.warn("Error setting coverage:",t),!1}},setAspectRatio:e=>{if(!this.selectionElement)return!1;try{let t;if(""===e||null==e)t=NaN;else if("number"==typeof e)t=e;else{if("string"!=typeof e)return console.warn("Unsupported aspect ratio type:",typeof e,e),!1;if(e.includes("/")){const[n,l]=e.split("/").map(e=>parseFloat(e.trim()));if(isNaN(n)||isNaN(l)||0===l)return console.warn("Invalid aspect ratio format:",e),!1;t=n/l}else if(t=parseFloat(e),isNaN(t))return console.warn("Invalid aspect ratio format:",e),!1}return this.selectionElement.aspectRatio=t,this.selectionElement.$render(),!0}catch(t){return console.warn("Error setting aspect ratio:",t),!1}},move:(e,t)=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$move(e,t),!0}catch(n){return console.warn("Error moving selection:",n),!1}},zoom:e=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$zoom(e),!0}catch(t){return console.warn("Error zooming selection:",t),!1}},change:(e,t,n,l,r)=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$change(e,t,n,l,r),!0}catch(a){return console.warn("Error changing selection:",a),!1}},set:(e,t,n,l)=>{if(!this.selectionElement)return!1;try{return this.selectionElement.x=e,this.selectionElement.y=t,this.selectionElement.width=n,this.selectionElement.height=l,this.selectionElement.$render(),!0}catch(r){return console.warn("Error setting selection:",r),!1}},toCanvas:async(e={})=>{if(!this.selectionElement)return null;try{const t={width:800,height:600,imageSmoothingEnabled:!0,imageSmoothingQuality:"high",...e};return await this.selectionElement.$toCanvas(t)}catch(t){return console.warn("Error exporting to canvas:",t),null}},getData:()=>{if(!this.selectionElement)return null;try{return{x:this.selectionElement.x,y:this.selectionElement.y,width:this.selectionElement.width,height:this.selectionElement.height,aspectRatio:this.selectionElement.aspectRatio}}catch(e){return console.warn("Error getting selection data:",e),null}}};canvas={setBackground:e=>{if(!this.canvasElement)return!1;try{return this.canvasElement.background=e,!0}catch(t){return console.warn("Error setting background:",t),!1}},setScaleStep:e=>{if(!this.canvasElement)return!1;try{return this.canvasElement.scaleStep=e,!0}catch(t){return console.warn("Error setting scale step:",t),!1}},setDisabled:e=>{if(!this.canvasElement)return!1;try{return this.canvasElement.disabled=e,!0}catch(t){return console.warn("Error setting disabled state:",t),!1}}};utils={flipHorizontal:()=>{const e=this.transform.getTransform();if(!e)return!1;const[t,n,l,r,a,i]=e;return this.transform.setTransform(-t,n,l,r,a,i)},flipVertical:()=>{const e=this.transform.getTransform();if(!e)return!1;const[t,n,l,r,a,i]=e;return this.transform.setTransform(t,n,l,-r,a,i)},setupInitialView:async(e={})=>{const{paspartuFactor:t=.85,retries:n=3,retryDelay:l=200}=e;return new Promise(e=>{const r=(a=0)=>{if(!this.isReady)return a<n?void setTimeout(()=>r(a+1),l):void e(!1);try{const i=this.canvasElement.getBoundingClientRect();let o=this.image.querySelector("img")||this.image;if(!o?.naturalWidth||!o?.naturalHeight)return a<n?void setTimeout(()=>r(a+1),l):(this.transform.center(),void e(!1));if(i.width>0&&i.height>0){const n=i.width*t/o.naturalWidth,l=i.height*t/o.naturalHeight,r=Math.min(n,l,1);this.transform.setTransform(r,0,0,r,0,0)?setTimeout(()=>{this.transform.center(),this.selection.center(),e(!0)},100):(this.transform.reset(),setTimeout(()=>{r<1&&this.transform.scale(r),setTimeout(()=>{this.transform.center(),this.selection.center(),e(!0)},100)},100))}else this.transform.center(),e(!1)}catch(i){console.warn("Error in setup:",i),this.transform.center(),e(!1)}};r()})},resetAll:()=>{const e={transform:this.transform.reset(),selection:this.selection.reset(),center:!1};return setTimeout(()=>{e.center=this.transform.center()&&this.selection.center()},100),e},checkExportability:async()=>{try{return!!(await this.selection.toCanvas({width:1,height:1}))}catch{return!1}},resetZoomOnly:()=>this.transform.resetZoom(),getZoomInfo:()=>{const e=this.transform.getZoom();return{current:e,isZoomedIn:e>1,isZoomedOut:e<1,percentage:Math.round(100*e)}},setBackground:e=>this.canvas.setBackground(e)};setupEventListeners(e={}){const{onSelectionChange:t,onImageTransform:n,onAction:l,onActionStart:r,onActionMove:a,onActionEnd:i}=e,o=[];if(t&&this.selectionElement){const e=e=>{t({x:e.detail.x,y:e.detail.y,width:e.detail.width,height:e.detail.height})};this.selectionElement.addEventListener("change",e),o.push(()=>{this.selectionElement&&this.selectionElement.removeEventListener("change",e)})}if(n&&this.image){const e=e=>{n({matrix:e.detail.matrix,oldMatrix:e.detail.oldMatrix})};this.image.addEventListener("transform",e),o.push(()=>{this.image&&this.image.removeEventListener("transform",e)})}if(this.canvasElement){if(l){const e=e=>l(e.detail);this.canvasElement.addEventListener("action",e),o.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("action",e)})}if(r){const e=e=>r(e.detail);this.canvasElement.addEventListener("actionstart",e),o.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionstart",e)})}if(a){const e=e=>a(e.detail);this.canvasElement.addEventListener("actionmove",e),o.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionmove",e)})}if(i){const e=e=>i(e.detail);this.canvasElement.addEventListener("actionend",e),o.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionend",e)})}}return()=>{o.forEach(e=>e())}}}async function El(e,t,n={}){const{format:l=null,originalFormat:r="webp",onSuccess:a=null,onError:i=null,accessibilityManager:o=null}=n;try{const n=window.limboCore?.config?.getGlobal(),i=l||n?.downloadFormat||r||"webp",c=`${t.split(".")[0]}.${i}`;if(o&&o.announce(`Descargando ${c}`),e.startsWith("data:image/"))return function(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.style.display="none",document.body.appendChild(n),n.click(),setTimeout(()=>{document.body.removeChild(n)},100)}(e,c),a&&a(c),o&&o.announce(`${c} descargado correctamente`),!0;let u;try{if(u=await fetch(e,{mode:"cors"}),!u.ok)throw new Error(`HTTP error! status: ${u.status}`)}catch(s){if(!e.startsWith("http"))throw s;{const t=(window.limboCore?.config?.getGlobal()||{}).prod?"https://limbo.lefebvre.es":"https://led-dev-limbo-dev.eu.els.local",n=window.limboCore?.apiClient?.token||"",l=`${t}/api/atenea/proxy?url=${encodeURIComponent(e)}`;if(u=await fetch(l,{credentials:"include",headers:{Authorization:`Bearer ${n}`}}),!u.ok)throw new Error(`Proxy error: ${u.status}`)}}const d=await u.blob();let b=d;const m=d.type;m!==`image/${"jpg"===i?"jpeg":i}`&&function(e){return["webp","jpeg","jpg","svg","png"].includes(e.toLowerCase())}(i)&&(b=await async function(e,t){return new Promise((n,l)=>{const r=new Image,a=URL.createObjectURL(e);r.onload=()=>{try{const l=document.createElement("canvas");l.width=r.width,l.height=r.height;l.getContext("2d").drawImage(r,0,0);const i=`image/${"jpg"===t?"jpeg":t}`,o="png"===t?void 0:.92;l.toBlob(t=>{URL.revokeObjectURL(a),n(t||e)},i,o)}catch(l){URL.revokeObjectURL(a),n(e)}},r.onerror=()=>{URL.revokeObjectURL(a),n(e)},r.src=a})}(d,i));const h=window.URL.createObjectURL(b),p=document.createElement("a");return p.href=h,p.download=c,p.style.display="none",document.body.appendChild(p),p.click(),setTimeout(()=>{window.URL.revokeObjectURL(h),document.body.removeChild(p)},100),a&&a(c),o&&o.announce(`${c} descargado correctamente`),!0}catch(c){return console.error("Error downloading image:",c),i&&i(c),o&&o.announce(`Error al descargar la imagen: ${c.message}`),!1}}const $l=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:El,downloadImage:El},Symbol.toStringTag,{value:"Module"}));function _l({image:e,onSave:i,onCancel:o,onDelete:d,onError:b=null,deleting:m=!1,onVariantCreated:h=null,onUpload:p=null,uploading:f=!1,cropperConfig:g=null}){const[v,y]=t(!1),[w,x]=t(null),[k,C]=t(!1),[S,N]=t(!0),[E,$]=t(!0),[_,z]=t(e.url||e.path||null);n(()=>{const t=e.url||e.path;if(!t||t.startsWith("blob:")||t.startsWith("data:"))return void z(t);let n=!1;return ve(t,{bypassHttpCache:!0}).then(e=>{n||z(e)}).catch(()=>{n||z(t)}),()=>{n=!0}},[e.url,e.path]);const[T,A]=t({x:20,y:100}),[L,I]=t(!1),[P,M]=t({x:0,y:0}),[D,R]=t(!1),[O,F]=t(!0),[j,U]=t(!1),[B,W]=t({horizontal:!1,vertical:!1}),[q,V]=t(!1),[H,K]=t(!1),[G,Q]=t(!1),[X,Y]=t(!1),[J]=t(()=>{if(!e||!e.filename)return"image";const[t]=e.filename.split(".");return t}),Z=l(()=>{if(g)return{mandatoryCrops:g.mandatoryCrops||[],allowCustomCrops:!1!==g.allowAdditionalCrops,showDimensionInputs:!0===g.showDimensionInputs,maxCrops:g.maxCrops||null,localCropsOnly:!0===g.localCropsOnly,existingCrops:g.existingCrops||null};const e=window.limboCore?.config?.getGlobal()||{};return{mandatoryCrops:e.cropper?.mandatoryCrops||[],allowCustomCrops:!1!==e.cropper?.allowCustomCrops,showDimensionInputs:!0===e.cropper?.showDimensionInputs,maxCrops:e.cropper?.maxCrops||null,localCropsOnly:!0===e.cropper?.localCropsOnly,existingCrops:e.cropper?.existingCrops||null}},[g]),[ee,te]=t(()=>Z.mandatoryCrops.length>0?Z.mandatoryCrops.map((e,t)=>({id:`crop-${t}`,label:e.label,width:e.width,height:e.height,required:!1!==e.required,isCustom:!1,confirmed:!1,lockDimensions:!(!e.width||!e.height),format:e.format||null,savedState:null})):[{id:"crop-default-0",label:J,width:e.width||1920,height:e.height||1080,required:!1,isCustom:!0,confirmed:!1,savedState:null}]),[ne,le]=t(0),re=ee[ne],ae=l(()=>re&&re.width&&re.height?re.width/re.height:"",[re]),ie=l(()=>{const e=50;if(!ae||""===ae)return{minWidth:e,minHeight:e};if(ae>=1){return{minWidth:e,minHeight:e/ae}}return{minWidth:e*ae,minHeight:e}},[ae]),[oe,se]=t(!1),[ce,ue]=t([]),[de,be]=t(null),me=window.limboCore?.accessibilityManager,{createVariantFromBlob:pe,loading:fe,error:ge}=Sl(),ye=((e,a={})=>{const i=r(null),o=r(null),s=r(null),c=r(null),[u,d]=t(null),[b,m]=t(null),[h,p]=t(!1),[f,g]=t(!0),[v,y]=t(0),w={aspectRatio:"",shade:!0,paspartuFactor:.85,...a};n(()=>{i.current&&o.current&&s.current&&(c.current=new Nl(i,o,s),p(!0))},[]),n(()=>{if(c.current)return c.current.setupEventListeners({onSelectionChange:e=>{d(e)},onImageTransform:()=>{y(e=>e+1)}})},[h]),n(()=>{c.current&&e&&(async()=>{c.current.selection.setAspectRatio(w.aspectRatio),c.current.canvas.setBackground(w.shade),await c.current.utils.setupInitialView({paspartuFactor:w.paspartuFactor});const e=await c.current.utils.checkExportability();g(e);const t=o.current?.querySelector("img")||o.current;t?.naturalWidth&&t?.naturalHeight&&m({naturalWidth:t.naturalWidth,naturalHeight:t.naturalHeight,currentWidth:t.width,currentHeight:t.height})})()},[e]),n(()=>{c.current&&h&&c.current.selection.setAspectRatio(w.aspectRatio)},[w.aspectRatio,h]),n(()=>{c.current&&h&&c.current.canvas.setBackground(w.shade)},[w.shade,h]);const x=l(()=>({move:(e,t)=>c.current?.transform.move(e,t)||!1,zoom:e=>c.current?.transform.zoom(e)||!1,rotate:e=>c.current?.transform.rotate(e)||!1,center:()=>c.current?.transform.center()||!1,reset:()=>c.current?.transform.reset()||!1,resetZoom:()=>c.current?.transform.resetZoom()||!1,setZoom:e=>c.current?.transform.setZoom(e)||!1,getZoom:()=>c.current?.transform.getZoom()||1,fitToCanvas:e=>c.current?.transform.fitToCanvas(e)||!1,flipHorizontal:()=>c.current?.utils.flipHorizontal()||!1,flipVertical:()=>c.current?.utils.flipVertical()||!1}),[]),k=l(()=>({center:()=>c.current?.selection.center()||!1,reset:()=>c.current?.selection.reset()||!1,setCoverage:e=>c.current?.selection.setCoverage(e)||!1,setAspectRatio:e=>c.current?.selection.setAspectRatio(e)||!1,toCanvas:e=>c.current?.selection.toCanvas(e)||Promise.resolve(null)}),[]),C=l(()=>({resetAll:()=>{if(c.current){const e=c.current.utils.resetAll();return d(null),e}return!1},setBackground:e=>c.current?.canvas.setBackground(e)||!1,resetZoomOnly:()=>c.current?.utils.resetZoomOnly()||!1,getZoomInfo:()=>c.current?.utils.getZoomInfo()||{current:1,percentage:100,isZoomedIn:!1,isZoomedOut:!1}}),[]);return{refs:{canvasRef:i,imageRef:o,selectionRef:s},state:{cropData:u,imageInfo:b,isReady:h,canExport:f,transformVersion:v},transform:x,selection:k,utils:C,manager:c.current}})(e,{aspectRatio:ae||null,showGrid:S,shade:E,initialCoverage:.5,paspartuFactor:.85}),{refs:we,state:xe,transform:ke,selection:Ce,utils:Se}=ye,{canvasRef:Ne,imageRef:Ee,selectionRef:$e}=we,{cropData:_e,imageInfo:ze,canExport:Te,transformVersion:Ae}=xe,Ie=l(()=>ze||{naturalWidth:e.width||1920,naturalHeight:e.height||1080,currentWidth:e.width||1920,currentHeight:e.height||1080},[ze,e.width,e.height]),Pe=a(()=>N(e=>!e),[]),Me=a(()=>$(e=>!e),[]),De=a(()=>K(e=>!e),[]),Re=a(()=>Q(e=>!e),[]),Oe=a(()=>Y(e=>!e),[]),Fe=a(()=>ke.center(),[ke]),je=a(()=>Ce.center(),[Ce]),Ue=a(()=>Ce.reset(),[Ce]),Be=a((e,t)=>ke.move(e,t),[ke]),We=a(e=>ke.zoom(e),[ke]),qe=a(e=>ke.rotate(e),[ke]),Ve=a(e=>{Ce.setCoverage(e)},[Ce]),Ke=a(()=>{W(e=>{const t=!e.horizontal;return ke.flipHorizontal(),{...e,horizontal:t}})},[ke]),Ge=a(()=>{W(e=>{const t=!e.vertical;return ke.flipVertical(),{...e,vertical:t}})},[ke]),Qe=a(()=>{if(!ye.manager||!xe.isReady)return null;try{const e=_e?{..._e}:null;let t=null;if($e.current){const e=$e.current;t={x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0}}let n=null;if(Ee.current){const e=Ee.current.$getTransform?.();e&&Array.isArray(e)&&(n=[...e])}const l={cropData:e,selectorState:t,imageTransform:n,flipState:{horizontal:B.horizontal,vertical:B.vertical}};return te(e=>e.map((e,t)=>t===ne?{...e,savedState:l}:e)),l}catch(e){return console.warn("Error saving crop state:",e),null}},[ye.manager,xe.isReady,_e,B,ne,Ee,$e]),Xe=a(e=>{const t=ee[e];if(t&&t.savedState)if(ye.manager&&xe.isReady)try{const{savedState:e}=t;if(e.imageTransform&&Ee.current&&Array.isArray(e.imageTransform)&&setTimeout(()=>{if(Ee.current&&Ee.current.$setTransform){const[t,n,l,r,a,i]=e.imageTransform;Ee.current.$setTransform(t,n,l,r,a,i)}},100),e.selectorState&&$e.current){const{x:t,y:n,width:l,height:r}=e.selectorState;setTimeout(()=>{$e.current&&($e.current.x=t,$e.current.y=n,$e.current.width=l,$e.current.height=r,$e.current.$render&&$e.current.$render())},150)}e.flipState&&W({horizontal:e.flipState.horizontal??!1,vertical:e.flipState.vertical??!1})}catch(n){console.error("Error restoring crop state:",n),setTimeout(()=>{Fe(),setTimeout(()=>je(),100)},100)}else console.warn("Cropper not ready for state restoration");else setTimeout(()=>{Fe(),setTimeout(()=>je(),100)},100)},[ee,ye.manager,xe.isReady,Fe,je,$e,Ee]),Ye=a(()=>{for(let e=0;e<ee.length;e++){const t=ee[e];if(!t.label||""===t.label.trim())return e}return-1},[ee]),Je=a(async e=>{e!==ne&&(U(!0),Qe(),await new Promise(e=>setTimeout(e,100)),le(e),await new Promise(e=>setTimeout(e,250)),Xe(e),await new Promise(e=>setTimeout(e,200)),U(!1))},[ne,Qe,Xe]),Ze=a(()=>{if(!Z.allowCustomCrops)return void alert("No se pueden añadir recortes personalizados en este modo.");const t={id:`crop-custom-${Date.now()}`,label:`Recorte ${ee.length+1}`,width:e.width||1920,height:e.height||1080,required:!1,isCustom:!0,confirmed:!1,savedState:null};te(e=>[...e,t]),me?.announce(`Nuevo recorte personalizado añadido: ${t.label}. Selecciónalo para editarlo.`)},[Z.allowCustomCrops,ee.length,e.width,e.height,me]),et=a((e,t)=>{const n=parseInt(t,10);""===t||isNaN(n)||te(t=>t.map((t,l)=>l===ne?{...t,[e]:n}:t))},[ne]),tt=a(e=>{const t=re[e];let n=100;if(Ne.current&&ze){const e=Ne.current.getBoundingClientRect(),t=Math.min(e.width,e.height);n=Math.max(100,Math.round(.05*t))}const l=Math.max(n,Math.min(3500,t));l!==t&&te(t=>t.map((t,n)=>n===ne?{...t,[e]:l}:t));const r={...re,[e]:l},a=r.width/r.height,i=Ce.getData?.();Ce.setAspectRatio(a),i&&void 0!==i.x&&setTimeout(()=>{Ce.set?.(i.x,i.y,i.width,i.height)},50)},[ne,re,Ce,Ne,ze]),nt=a(e=>{te(t=>t.map((t,n)=>n===ne?{...t,label:e}:t))},[ne]),lt=a((e,t=null)=>{t=t||ee[e].label;if(!window.confirm(`¿Estás seguro de que deseas eliminar "${t||"este recorte"}"? Esta acción también eliminará todos sus recortes.`))return;const n=ee[e];if(n.required)alert("No se puede eliminar un recorte obligatorio.");else if(1!==ee.length){if(te(t=>t.filter((t,n)=>n!==e)),e===ne){const t=Math.max(0,e-1);le(t)}else e<ne&&le(e=>e-1);me?.announce(`Recorte ${n.label} eliminado`)}else alert("Debe haber al menos un recorte.")},[ee,ne,me]),rt=a(async()=>{if(!Te)return null;try{const t=await Ce.toCanvas({width:800,height:600,imageSmoothingEnabled:!0,imageSmoothingQuality:"high"});return t?t.toDataURL(`image/${globalThis.downloadFormat||e.mime_type.split("/")[1]||"webp"}`,.9):null}catch(t){return console.warn("Error generating preview:",t),null}},[Te,e.mime_type,Ce]),at=a(async()=>{if(v)return y(!1),x(null),void C(!1);if(Te){y(!0),C(!0);try{const e=await rt();e?x(e):(y(!1),alert("No se puede exportar el recorte por restricciones de CORS en la imagen original."))}finally{C(!1)}}else alert("No se puede exportar el recorte por restricciones de CORS en la imagen original.")},[Te,rt,v]),it=a(e=>{e.target.closest(".limbo-preview-modal-header")&&(I(!0),M({x:e.clientX-T.x,y:e.clientY-T.y}))},[T]),ot=a(e=>{L&&(e.preventDefault(),A({x:e.clientX-P.x,y:e.clientY-P.y}))},[L,P]),st=a(()=>{I(!1)},[]),ct=a(e=>{if(!e.target.closest(".limbo-preview-modal-header"))return;const t=e.touches[0];I(!0),M({x:t.clientX-T.x,y:t.clientY-T.y})},[T]),ut=a(e=>{if(!L)return;e.preventDefault();const t=e.touches[0];A({x:t.clientX-P.x,y:t.clientY-P.y})},[L,P]),dt=a(()=>{I(!1)},[]);n(()=>{if(L)return document.addEventListener("mousemove",ot),document.addEventListener("mouseup",st),document.addEventListener("touchmove",ut,{passive:!1}),document.addEventListener("touchend",dt),()=>{document.removeEventListener("mousemove",ot),document.removeEventListener("mouseup",st),document.removeEventListener("touchmove",ut),document.removeEventListener("touchend",dt)}},[L,ot,st,ut,dt]),n(()=>{if(!D)return;const e=e=>{"Escape"===e.key&&R(!1)};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[D]);const bt=a(async(t,n=null)=>{const l=ee[t];if(!l)throw new Error(`Crop ${t} no encontrado`);if(!l.savedState&&t!==ne)throw new Error(`El recorte "${l.label}" aún no ha sido configurado`);const r={imageTransform:Ee.current?.$getTransform?.(),selectorState:$e.current?{x:$e.current.x,y:$e.current.y,width:$e.current.width,height:$e.current.height}:null};try{if(t!==ne&&l.savedState){if(l.savedState.imageTransform&&Ee.current?.$setTransform){const[e,t,n,r,a,i]=l.savedState.imageTransform;Ee.current.$setTransform(e,t,n,r,a,i)}if(l.savedState.selectorState&&$e.current?.$change){const{x:e,y:t,width:n,height:r}=l.savedState.selectorState;$e.current.$change(e,t,n,r,NaN,!0)}await new Promise(e=>setTimeout(e,100))}const r=Math.min(l.width,3500),i=Math.min(l.height,3500);let o=await Ce.toCanvas({width:r,height:i,imageSmoothingEnabled:!0,imageSmoothingQuality:"high"});if(!o)throw new Error(`No se pudo generar el canvas para "${l.label}"`);if(o.width!==r||o.height!==i){const e=document.createElement("canvas");e.width=r,e.height=i;const t=e.getContext("2d");t.imageSmoothingEnabled=!0,t.imageSmoothingQuality="high",t.drawImage(o,0,0,r,i),o=e}const s=l.format||globalThis.downloadFormat||"webp",c="webp"===s?"image/webp":"png"===s?"image/png":"image/jpeg",u=.9,d=await new Promise((e,t)=>{o.toBlob(n=>{n?e(n):t(new Error("No se pudo convertir el canvas a blob"))},c,u)}),b=`${Le(l.label||"crop")}_${r}_${i}`,m=n||e.id,f=!m||"string"==typeof m&&m.startsWith("external"),g=(f||Z.localCropsOnly)&&!p;if(f&&p&&!Z.localCropsOnly)try{const e=new File([d],`${b}.${s}`,{type:c}),t=await p(e);if(t&&(t.id||t.url)){const e=l.savedState||{selectorState:$e.current?{x:$e.current.x,y:$e.current.y,width:$e.current.width,height:$e.current.height}:null,imageTransform:Ee.current?.$getTransform?.()||null,flipState:{horizontal:B.horizontal,vertical:B.vertical}},n={id:t.id||`uploaded-${Date.now()}`,name:b,filename:`${b}.${s}`,url:t.urlSigned||t.url,urlSigned:t.urlSigned||t.url,width:r,height:i,format:s,size:d.size,mime_type:c,isLocal:!1,originalAssetId:null,uploadedAssetId:t.id,cropState:e};return me?.announceSuccess(`Recorte guardado: ${b}`),n}}catch(a){console.error("[CropperView] ❌ Error subiendo crop, fallback a local:",a)}if(g){const e=URL.createObjectURL(d),t=l.savedState||{selectorState:$e.current?{x:$e.current.x,y:$e.current.y,width:$e.current.width,height:$e.current.height}:null,imageTransform:Ee.current?.$getTransform?.()||null,flipState:{horizontal:B.horizontal,vertical:B.vertical}},n={id:`local-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:b,filename:`${b}.${s}`,url:e,urlSigned:e,width:r,height:i,format:s,size:d.size,mime_type:c,blob:d,isLocal:!0,originalAssetId:m||null,cropState:t};return me?.announceSuccess(`Recorte creado localmente: ${b}`),n}const v=l.savedState||{selectorState:$e.current?{x:$e.current.x,y:$e.current.y,width:$e.current.width,height:$e.current.height}:null,imageTransform:Ee.current?.$getTransform?.()||null,flipState:{horizontal:B.horizontal,vertical:B.vertical}},y=await pe(m,d,{name:b,width:r,height:i,format:s});if(y)return y.cropState=v,me?.announceSuccess(`Recorte creado: ${b}`),h?.(m,y),y;throw new Error("No se pudo crear la variante")}finally{if(t!==ne&&r.imageTransform&&Ee.current?.$setTransform){const[e,t,n,l,a,i]=r.imageTransform;if(Ee.current.$setTransform(e,t,n,l,a,i),r.selectorState&&$e.current?.$change){const{x:e,y:t,width:n,height:l}=r.selectorState;$e.current.$change(e,t,n,l,NaN,!0)}}}},[ee,ne,Ce,pe,e.id,h,me,Ee,$e]),mt=a(async()=>{if(!Te){const e="No se puede exportar el recorte por restricciones de CORS en la imagen original.";return me?.announceError(e),void alert(e)}if(!xe.isReady){const e="El cropper aún no está inicializado. Espera un momento e inténtalo de nuevo.";return me?.announceError(e),void alert(e)}Qe(),me?.announce("Creando recorte de la imagen");try{let t=e.id,n=null;if(e.file&&p){me?.announce("Subiendo imagen...");const l=await p(e.file);if(!l||!l.id)throw new Error("No se pudo subir la imagen al servidor");t=l.id,n=l,me?.announceSuccess("Imagen subida correctamente")}const l=await bt(ne,t);l&&i(n?{crops:[l],asset:n}:l)}catch(t){console.warn("Error creating crop variant:",t);const e=t.message||"No se pudo crear el recorte. Inténtalo de nuevo.";me?.announceError(e),alert(e),b?.(t)}},[Te,xe.isReady,me,Qe,bt,ne,i,b,e.file,e.id,p]),ht=a(async t=>{Qe(),me?.announce(`Guardando ${t.length} recortes...`);try{let l=e.id,r=null;if(e.file&&p){me?.announce("Subiendo imagen...");const t=await p(e.file);if(!t||!t.id)throw new Error("No se pudo subir la imagen al servidor");l=t.id,r=t,me?.announceSuccess("Imagen subida correctamente")}const a=[],o=[];for(const e of t)try{const t=await bt(e,l);t&&a.push(t)}catch(n){o.push({crop:ee[e]?.label||`Crop ${e}`,error:n.message})}if(a.length>0&&(me?.announceSuccess(`${a.length} recorte(s) guardado(s) correctamente`),i(r?{crops:a,asset:r}:a)),o.length>0){const e=`Errores al guardar algunos recortes:\n${o.map(e=>`- ${e.crop}: ${e.error}`).join("\n")}`;me?.announceError(e),alert(e)}}catch(n){const e=n.message||"Error al procesar los recortes";me?.announceError(e),alert(e),b?.(n)}},[Qe,bt,ee,me,i,e.file,e.id,p,b]),pt=a(async()=>{(re.width>3500||re.height>3500)&&alert("Las dimensiones máximas permitidas son 3500x3500 píxeles. Por favor, ajusta el tamaño del recorte."),re.width=Math.min(re.width,3500),re.height=Math.min(re.height,3500);const e=Ye();if(-1!==e){const t=ee[e];return alert(`El recorte "${t.label||t||"(sin nombre)"}" debe tener un nombre válido.`),void le(e)}const t=ee.findIndex((e,t)=>e.required&&!e.savedState&&t!==ne);if(-1!==t){const e=ee[t];return alert(`El recorte obligatorio "${e.label}" aún no ha sido configurado.\n\nPor favor, configura todos los recortes obligatorios antes de guardar.`),le(t),void me?.announce(`Recorte obligatorio "${e.label}" sin configurar. Por favor, configúralo.`,"assertive")}if(ee.length>1){be("save");const e=ee.map((e,t)=>({crop:e,index:t})).filter(({crop:e,index:t})=>e.required||e.savedState||t===ne).map(({index:e})=>e);return ue(e),void se(!0)}await mt()},[Ye,ee,mt,ne,me]),ft=a(async t=>{const n=ee[t];if(!n)throw new Error(`Crop ${t} no encontrado`);if(!n.savedState&&t!==ne)throw new Error(`El recorte "${n.label}" aún no ha sido configurado`);const l={imageTransform:Ee.current?.$getTransform?.(),selectorState:$e.current?{x:$e.current.x,y:$e.current.y,width:$e.current.width,height:$e.current.height}:null};try{if(t!==ne&&n.savedState){if(n.savedState.imageTransform&&Ee.current?.$setTransform){const[e,t,l,r,a,i]=n.savedState.imageTransform;Ee.current.$setTransform(e,t,l,r,a,i)}if(n.savedState.selectorState&&$e.current?.$change){const{x:e,y:t,width:l,height:r}=n.savedState.selectorState;$e.current.$change(e,t,l,r,NaN,!0)}await new Promise(e=>setTimeout(e,100))}const l=await Ce.toCanvas({width:n.width,height:n.height,imageSmoothingEnabled:!0,imageSmoothingQuality:"high"});if(!l)throw new Error(`No se pudo generar el canvas para "${n.label}"`);const r=l.toDataURL(`image/${globalThis.downloadFormat||e.mime_type?.split("/")[1]||"webp"}`,.9),a=`${Le(n.label||"crop")}_${n.width}_${n.height}`;return await El(r,a,{accessibilityManager:me,onSuccess:e=>{console.log(`✅ Descargado: ${e}`)},onError:e=>{throw new Error(`Error al descargar "${n.label}": ${e.message}`)}}),{crop:n.label,filename:a}}finally{if(t!==ne&&l.imageTransform&&Ee.current?.$setTransform){const[e,t,n,r,a,i]=l.imageTransform;if(Ee.current.$setTransform(e,t,n,r,a,i),l.selectorState&&$e.current?.$change){const{x:e,y:t,width:n,height:r}=l.selectorState;$e.current.$change(e,t,n,r,NaN,!0)}}}},[ee,ne,Ce,e.mime_type,me,Ee,$e]),gt=a(async e=>{Qe(),me?.announce(`Descargando ${e.length} recortes...`);const t=[],n=[];for(const r of e)try{const e=await ft(r);e&&t.push(e)}catch(l){n.push({crop:ee[r]?.label||`Crop ${r}`,error:l.message})}if(t.length>0&&me?.announceSuccess(`${t.length} recorte(s) descargado(s) correctamente`),n.length>0){const e=`Errores al descargar algunos recortes:\n${n.map(e=>`- ${e.crop}: ${e.error}`).join("\n")}`;me?.announceError(e),alert(e)}},[Qe,ft,ee,me]),vt=a(async()=>{if(!Te){const e="No se puede descargar el recorte por restricciones de CORS en la imagen original.";return me?.announceError(e),void alert(e)}Qe(),me?.announce("Preparando descarga del recorte");try{await ft(ne),me?.announceSuccess("Recorte descargado correctamente")}catch(e){console.error("Error downloading crop:",e);const t=e.message||"Error al descargar el recorte";me?.announceError(t),alert(t)}},[Te,me,Qe,ft,ne]),yt=a(async()=>{const e=Ye();if(-1!==e){const t=ee[e];return alert(`El recorte "${t.label||t||"(sin nombre)"}" debe tener un nombre válido.`),void le(e)}if(ee.length>1){be("download");const e=ee.map((e,t)=>({crop:e,index:t})).filter(({crop:e,index:t})=>e.savedState||t===ne).map(({index:e})=>e);return ue(e),void se(!0)}await vt()},[Ye,ee,vt,ne]),wt=l(()=>!!e.file||(!e.id||!("string"!=typeof e.id||!e.id.startsWith("external"))),[e.file,e.id]),xt=a(async()=>{try{if(e.file&&p){me?.announce("Subiendo imagen original...");const t=await p(e.file);if(!t||!t.id)throw new Error("No se pudo subir la imagen al servidor");return me?.announceSuccess("Imagen guardada correctamente"),void i({asset:t,crops:[]})}if(wt){me?.announce("Conservando imagen original...");const t={id:`local-original-${Date.now()}`,name:e.filename||"original",filename:e.filename||"image.jpg",url:e.url,urlSigned:e.url,width:e.width||ze?.naturalWidth||1920,height:e.height||ze?.naturalHeight||1080,mime_type:e.mime_type||"image/jpeg",isLocal:!0,isOriginal:!0};return me?.announceSuccess("Imagen original conservada"),void i({crops:[t]})}if(e.id&&!e.id.startsWith("external")){me?.announce("Seleccionando imagen original...");const t={id:e.id,name:e.filename||"original",filename:e.filename||"image.jpg",url:e.url,urlSigned:e.urlSigned||e.url,width:e.width||ze?.naturalWidth||1920,height:e.height||ze?.naturalHeight||1080,mime_type:e.mime_type||"image/jpeg",isOriginal:!0};return me?.announceSuccess("Imagen original seleccionada"),void i({crops:[t],assetId:e.id})}o()}catch(t){console.error("Error guardando imagen original:",t);const e=t.message||"No se pudo guardar la imagen. Inténtalo de nuevo.";me?.announceError(e),alert(e),b?.(t)}},[e,ze,p,o,i,b,me,wt]);return n(()=>{y(!1),x(null)},[e]),n(()=>{if(!ye.manager||!xe.isReady||!O)return;const e=Z.existingCrops?.[0],t=e?.cropState;setTimeout(()=>{Fe(),setTimeout(()=>{if(t){if(t.imageTransform&&Ee.current?.$setTransform){const[e,n,l,r,a,i]=t.imageTransform;Ee.current.$setTransform(e,n,l,r,a,i)}if(t.selectorState&&$e.current){const{x:e,y:n,width:l,height:r}=t.selectorState;$e.current.x=e,$e.current.y=n,$e.current.width=l,$e.current.height=r,$e.current.$render?.()}t.flipState&&W(t.flipState)}else je();F(!1)},100)},50)},[ye.manager,xe.isReady,O,Fe,je,Z.existingCrops]),n(()=>{ye.manager&&xe.isReady&&(ae&&Ce.setAspectRatio(ae),Se.setBackground(E))},[ae,E,ye.manager,xe.isReady,Ce,Se]),n(()=>{if(!ze||!xe.isReady||Z.mandatoryCrops.length>0)return;const e=ee[0];if(e&&"crop-default-0"===e.id&&(1920===e.width||1080===e.height)){const t=Math.min(ze.naturalWidth,3500),n=Math.min(ze.naturalHeight,3500);te([{...e,width:t,height:n}])}},[ze,xe.isReady,Z.mandatoryCrops.length,ee]),n(()=>{if(!v||!Te)return;const e=setTimeout(async()=>{C(e=>!w&&!e||e);try{const e=await rt();e&&x(e)}finally{C(!1)}},300);return()=>{clearTimeout(e),C(!1)}},[_e,Ae,v,Te,rt,ae,B,w]),n(()=>{const e=Ne.current,t=t=>{if("Delete"===t.key||"Backspace"===t.key||"Backspace"===t.key&&t.metaKey||"Backspace"===t.key&&t.ctrlKey){const n=t.target;if(e&&(n===e||n===document.body||n===document.documentElement||"CROPPER-CANVAS"===n.tagName||"CROPPER-SELECTION"===n.tagName||"CROPPER-IMAGE"===n.tagName||"CROPPER-HANDLE"===n.tagName||"CROPPER-GRID"===n.tagName||n.closest("cropper-canvas")||e.contains(n)))return t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),!1}};return document.addEventListener("keydown",t,!0),document.addEventListener("keyup",t,!0),window.addEventListener("keydown",t,!0),e&&e.addEventListener("keydown",t,!0),()=>{document.removeEventListener("keydown",t,!0),document.removeEventListener("keyup",t,!0),window.removeEventListener("keydown",t,!0),e&&e.removeEventListener("keydown",t,!0)}},[Ne]),e?/* @__PURE__ */c("div",{className:"limbo-cropper-view lb:px-2 lb:border-2 lb:border-gray-200/50 lb:rounded-lg lb:max-w-7xl lb:mx-auto lb:w-full lb:min-w-full lb:h-full lb:min-h-full lb:flex lb:flex-col",children:[
|
|
450
|
+
/* @__PURE__ */s(Ht,{onSelect:e,onVideoSelect:t,disabled:l,apiKey:o,prod:u,allowedCategories:d,resolvedAccept:b,returnConfig:m,folderConfig:h,selectedFolder:i,onFolderChange:n})]})}const Gt="undefined"!=typeof window&&void 0!==window.document,Qt=Gt?window:{},Xt=!!Gt&&"ontouchstart"in Qt.document.documentElement,Yt=!!Gt&&"PointerEvent"in Qt,Jt="cropper",Zt=`${Jt}-canvas`,en=`${Jt}-crosshair`,tn=`${Jt}-grid`,nn=`${Jt}-handle`,ln=`${Jt}-image`,rn=`${Jt}-selection`,an=`${Jt}-shade`,on=`${Jt}-viewer`,sn="select",cn="move",un="scale",dn="rotate",bn="transform",mn="none",hn="n-resize",pn="e-resize",fn="s-resize",gn="w-resize",vn="ne-resize",yn="nw-resize",wn="se-resize",xn="sw-resize",kn=Yt?"pointerdown":Xt?"touchstart":"mousedown",Cn=Yt?"pointermove":Xt?"touchmove":"mousemove",Sn=Yt?"pointerup pointercancel":Xt?"touchend touchcancel":"mouseup",Nn="error",En="keydown",$n="load",_n="resize",zn="wheel",Tn="action",An="actionend",Ln="actionstart",In="change",Pn="transform";const Mn=Number.isNaN||Qt.isNaN;function Dn(e){return"number"==typeof e&&!Mn(e)}function Rn(e){return Dn(e)&&e>0&&e<1/0}function On(e){return"object"==typeof e&&null!==e}const{hasOwnProperty:Fn}=Object.prototype;function jn(e){if(!On(e))return!1;try{const{constructor:t}=e,{prototype:n}=t;return t&&n&&Fn.call(n,"isPrototypeOf")}catch(t){return!1}}function Un(e){return"function"==typeof e}function Bn(e){return"object"==typeof e&&null!==e&&1===e.nodeType}const Wn=/([a-z\d])([A-Z])/g;function qn(e){return String(e).replace(Wn,"$1-$2").toLowerCase()}const Vn=/-[A-z\d]/g;function Hn(e){return e.replace(Vn,e=>e.slice(1).toUpperCase())}const Kn=/\s\s*/;function Gn(e,t,n,l){t.trim().split(Kn).forEach(t=>{e.removeEventListener(t,n,l)})}function Qn(e,t,n,l){t.trim().split(Kn).forEach(t=>{e.addEventListener(t,n,l)})}function Xn(e,t,n,l){Qn(e,t,n,Object.assign(Object.assign({},l),{once:!0}))}const Yn={bubbles:!0,cancelable:!0,composed:!0};const Jn=Promise.resolve();function Zn(e){const{documentElement:t}=e.ownerDocument,n=e.getBoundingClientRect();return{left:n.left+(Qt.pageXOffset-t.clientLeft),top:n.top+(Qt.pageYOffset-t.clientTop)}}const el=/deg|g?rad|turn$/i;function tl(e){const t=parseFloat(e)||0;if(0!==t){const[n="rad"]=String(e).match(el)||[];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 nl="contain";function ll(e,t=nl){const{aspectRatio:n}=e;let{width:l,height:r}=e;const a=Rn(l),i=Rn(r);if(a&&i){const e=r*n;t===nl&&e>l||"cover"===t&&e<l?r=l/n:l=r*n}else a?r=l/n:i&&(l=r*n);return{width:l,height:r}}function rl(e,...t){if(0===t.length)return e;const[n,l,r,a,i,o]=e,[s,c,u,d,b,m]=t[0];return rl(e=[n*s+r*c,l*s+a*c,n*u+r*d,l*u+a*d,n*b+r*m+i,l*b+a*m+o],...t.slice(1))}const al=/left|top|width|height/i,il="open",ol=/* @__PURE__ */new WeakMap,sl=/* @__PURE__ */new WeakMap,cl=/* @__PURE__ */new Map,ul=Qt.document&&Array.isArray(Qt.document.adoptedStyleSheets)&&"replaceSync"in Qt.CSSStyleSheet.prototype;class dl extends HTMLElement{get $sharedStyle(){return(this.themeColor?`:host{--theme-color: ${this.themeColor};}`:"")+":host([hidden]){display:none!important}"}constructor(){var e,t;super(),this.shadowRootMode=il,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&&cl.set(n,this.tagName.toLowerCase())}static get observedAttributes(){return["shadow-root-mode","slottable","theme-color"]}attributeChangedCallback(e,t,n){if(Object.is(n,t))return;const l=Hn(e);let r=n;switch(typeof this[l]){case"boolean":r=null!==n&&"false"!==n;break;case"number":r=Number(n)}switch(this[l]=r,e){case"theme-color":{const e=sl.get(this),t=this.$sharedStyle;e&&t&&(ul?e.replaceSync(t):e.textContent=t);break}}}$propertyChangedCallback(e,t,n){if(!Object.is(n,t))switch(e=qn(e),typeof n){case"boolean":!0===n?this.hasAttribute(e)||this.setAttribute(e,""):this.removeAttribute(e);break;case"number":n=Mn(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=Hn(e);let n=this[t];(function(e){return void 0===e})(n)||this.$propertyChangedCallback(t,void 0,n),Object.defineProperty(this,t,{enumerable:!0,configurable:!0,get:()=>n,set(e){const l=n;n=e,this.$propertyChangedCallback(t,l,e)}})});const e=this.shadowRoot||this.attachShadow({mode:this.shadowRootMode||il});if(ol.set(this,e),sl.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(){sl.has(this)&&sl.delete(this),ol.has(this)&&ol.delete(this)}$getTagNameOf(e){var t;return null!==(t=cl.get(e))&&void 0!==t?t:e}$setStyles(e){return Object.keys(e).forEach(t=>{let n=e[t];Dn(n)&&(n=0!==n&&al.test(t)?`${n}px`:String(n)),this.style[t]=n}),this}$getShadowRoot(){return this.shadowRoot||ol.get(this)}$addStyles(e){let t;const n=this.$getShadowRoot();return ul?(t=new CSSStyleSheet,t.replaceSync(e),n.adoptedStyleSheets=n.adoptedStyleSheets.concat(t)):(t=document.createElement("style"),t.textContent=e,n.appendChild(t)),t}$emit(e,t,n){return function(e,t,n,l){return e.dispatchEvent(new CustomEvent(t,Object.assign(Object.assign(Object.assign({},Yn),{detail:n}),l)))}(this,e,t,n)}$nextTick(e){return function(e,t){return t?Jn.then(e?t.bind(e):t):Jn}(this,e)}static $define(e,t){On(e)&&(t=e,e=""),e||(e=this.$name||this.name),e=qn(e),Gt&&Qt.customElements&&!Qt.customElements.get(e)&&customElements.define(e,this,t)}}dl.$version="2.1.1";class bl extends dl{constructor(){super(...arguments),this.$onPointerDown=null,this.$onPointerMove=null,this.$onPointerUp=null,this.$onWheel=null,this.$wheeling=!1,this.$pointers=/* @__PURE__ */new Map,this.$style=':host{display:block;min-height:100px;min-width:200px;overflow:hidden;position:relative;touch-action:none;-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}:host([background]){background-color:#fff;background-image:repeating-linear-gradient(45deg,#ccc 25%,transparent 0,transparent 75%,#ccc 0,#ccc),repeating-linear-gradient(45deg,#ccc 25%,transparent 0,transparent 75%,#ccc 0,#ccc);background-image:repeating-conic-gradient(#ccc 0 25%,#fff 0 50%);background-position:0 0,.5rem .5rem;background-size:1rem 1rem}:host([disabled]){pointer-events:none}:host([disabled]):after{bottom:0;content:"";cursor:not-allowed;display:block;left:0;pointer-events:none;position:absolute;right:0;top:0}',this.$action=mn,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),Qn(this,kn,this.$onPointerDown)),this.$onPointerMove||(this.$onPointerMove=this.$handlePointerMove.bind(this),Qn(this.ownerDocument,Cn,this.$onPointerMove)),this.$onPointerUp||(this.$onPointerUp=this.$handlePointerUp.bind(this),Qn(this.ownerDocument,Sn,this.$onPointerUp)),this.$onWheel||(this.$onWheel=this.$handleWheel.bind(this),Qn(this,zn,this.$onWheel,{passive:!1,capture:!0}))}$unbind(){this.$onPointerDown&&(Gn(this,kn,this.$onPointerDown),this.$onPointerDown=null),this.$onPointerMove&&(Gn(this.ownerDocument,Cn,this.$onPointerMove),this.$onPointerMove=null),this.$onPointerUp&&(Gn(this.ownerDocument,Sn,this.$onPointerUp),this.$onPointerUp=null),this.$onWheel&&(Gn(this,zn,this.$onWheel,{capture:!0}),this.$onWheel=null)}$handlePointerDown(e){const{buttons:t,button:n,type:l}=e;if(this.disabled||("pointerdown"===l&&"mouse"===e.pointerType||"mousedown"===l)&&(Dn(t)&&1!==t||Dn(n)&&0!==n||e.ctrlKey))return;const{$pointers:r}=this;let a="";if(e.changedTouches)Array.from(e.changedTouches).forEach(({identifier:e,pageX:t,pageY:n})=>{r.set(e,{startX:t,startY:n,endX:t,endY:n})});else{const{pointerId:t=0,pageX:n,pageY:l}=e;r.set(t,{startX:n,startY:l,endX:n,endY:l})}r.size>1?a=bn:Bn(e.target)&&(a=e.target.action||e.target.getAttribute("action")||""),!1!==this.$emit(Ln,{action:a,relatedEvent:e})&&(e.preventDefault(),this.$action=a,this.style.willChange="transform")}$handlePointerMove(e){const{$action:t,$pointers:n}=this;if(this.disabled||t===mn||0===n.size)return;if(!1===this.$emit("actionmove",{action:t,relatedEvent:e}))return;if(e.preventDefault(),e.changedTouches)Array.from(e.changedTouches).forEach(({identifier:e,pageX:t,pageY:l})=>{const r=n.get(e);r&&Object.assign(r,{endX:t,endY:l})});else{const{pointerId:t=0,pageX:l,pageY:r}=e,a=n.get(t);a&&Object.assign(a,{endX:l,endY:r})}const l={action:t,relatedEvent:e};if(t===bn){const t=new Map(n);let r=0,a=0,i=0,o=0,s=e.pageX,c=e.pageY;n.forEach((e,n)=>{t.delete(n),t.forEach(t=>{let n=t.startX-e.startX,l=t.startY-e.startY,u=t.endX-e.endX,d=t.endY-e.endY,b=0,m=0,h=0,p=0;if(0===n?l<0?h=2*Math.PI:l>0&&(h=Math.PI):n>0?h=Math.PI/2+Math.atan(l/n):n<0&&(h=1.5*Math.PI+Math.atan(l/n)),0===u?d<0?p=2*Math.PI:d>0&&(p=Math.PI):u>0?p=Math.PI/2+Math.atan(d/u):u<0&&(p=1.5*Math.PI+Math.atan(d/u)),p>0||h>0){const n=p-h,l=Math.abs(n);l>r&&(r=l,i=n,s=(e.startX+t.startX)/2,c=(e.startY+t.startY)/2)}if(n=Math.abs(n),l=Math.abs(l),u=Math.abs(u),d=Math.abs(d),n>0&&l>0?b=Math.sqrt(n*n+l*l):n>0?b=n:l>0&&(b=l),u>0&&d>0?m=Math.sqrt(u*u+d*d):u>0?m=u:d>0&&(m=d),b>0&&m>0){const n=(m-b)/b,l=Math.abs(n);l>a&&(a=l,o=n,s=(e.startX+t.startX)/2,c=(e.startY+t.startY)/2)}})});const u=r>0,d=a>0;u&&d?(l.rotate=i,l.scale=o,l.centerX=s,l.centerY=c):u?(l.action=dn,l.rotate=i,l.centerX=s,l.centerY=c):d?(l.action=un,l.scale=o,l.centerX=s,l.centerY=c):l.action=mn}else{const[e]=Array.from(n.values());Object.assign(l,e)}n.forEach(e=>{e.startX=e.endX,e.startY=e.endY}),l.action!==mn&&this.$emit(Tn,l,{cancelable:!1})}$handlePointerUp(e){const{$action:t,$pointers:n}=this;if(!this.disabled&&t!==mn&&!1!==this.$emit(An,{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=mn)}}$handleWheel(e){if(this.disabled)return;if(e.preventDefault(),this.$wheeling)return;this.$wheeling=!0,setTimeout(()=>{this.$wheeling=!1},50);const t=(e.deltaY>0?-1:1)*this.scaleStep;this.$emit(Tn,{action:un,scale:t,relatedEvent:e},{cancelable:!1})}$setAction(e){return"string"==typeof e&&(this.$action=e),this}$toCanvas(e){return new Promise((t,n)=>{if(!this.isConnected)return void n(new Error("The current element is not connected to the DOM."));const l=document.createElement("canvas");let r=this.offsetWidth,a=this.offsetHeight,i=1;jn(e)&&(Rn(e.width)||Rn(e.height))&&(({width:r,height:a}=ll({aspectRatio:r/a,width:e.width,height:e.height})),i=r/this.offsetWidth),l.width=r,l.height=a;const o=this.querySelector(this.$getTagNameOf(ln));o?o.$ready().then(n=>{const s=l.getContext("2d");if(s){const[t,c,u,d,b,m]=o.$getTransform();let h=b,p=m,f=n.naturalWidth,g=n.naturalHeight;1!==i&&(h*=i,p*=i,f*=i,g*=i);const v=f/2,y=g/2;s.fillStyle="transparent",s.fillRect(0,0,r,a),jn(e)&&Un(e.beforeDraw)&&e.beforeDraw.call(this,s,l),s.save(),s.translate(v,y),s.transform(t,c,u,d,h,p),s.translate(-v,-y),s.drawImage(n,0,0,f,g),s.restore()}t(l)}).catch(n):t(l)})}}bl.$name=Zt,bl.$version="2.1.1";const ml=/* @__PURE__ */new WeakMap,hl=["alt","crossorigin","decoding","elementtiming","fetchpriority","loading","referrerpolicy","sizes","src","srcset"];class pl extends dl{constructor(){super(...arguments),this.$isReady=!1,this.$matrix=[1,0,0,1,0,0],this.$onLoad=null,this.$onCanvasAction=null,this.$onCanvasActionEnd=null,this.$onCanvasActionStart=null,this.$actionStartTarget=null,this.$style=":host{display:inline-block}img{display:block;height:100%;max-height:none!important;max-width:none!important;min-height:0!important;min-width:0!important;width:100%}",this.$image=new Image,this.initialCenterSize="contain",this.rotatable=!1,this.scalable=!1,this.skewable=!1,this.slottable=!1,this.translatable=!1,this.alt="",this.crossorigin="",this.decoding="",this.elementtiming="",this.fetchpriority="",this.loading="",this.referrerpolicy="",this.sizes="",this.src="",this.srcset=""}set $canvas(e){ml.set(this,e)}get $canvas(){return ml.get(this)}static get observedAttributes(){return super.observedAttributes.concat(hl,["initial-center-size","rotatable","scalable","skewable","translatable"])}attributeChangedCallback(e,t,n){Object.is(n,t)||(super.attributeChangedCallback(e,t,n),hl.includes(e)&&this.$image.setAttribute(e,n))}$propertyChangedCallback(e,t,n){if(!Object.is(n,t))switch(super.$propertyChangedCallback(e,t,n),e){case"initialCenterSize":this.$nextTick(()=>{this.$center(n)});break;case"src":this.$isReady=!1}}connectedCallback(){super.connectedCallback();const{$image:e}=this,t=this.closest(this.$getTagNameOf(Zt));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),Qn(t,Ln,this.$onCanvasActionStart),Qn(t,An,this.$onCanvasActionEnd),Qn(t,Tn,this.$onCanvasAction)),this.$onLoad=this.$handleLoad.bind(this),Qn(e,$n,this.$onLoad),this.$getShadowRoot().appendChild(e)}disconnectedCallback(){const{$image:e,$canvas:t}=this;t&&(this.$onCanvasActionStart&&(Gn(t,Ln,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(Gn(t,An,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasAction&&(Gn(t,Tn,this.$onCanvasAction),this.$onCanvasAction=null)),e&&this.$onLoad&&(Gn(e,$n,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),this.$isReady=!0}$handleAction(e){if(this.hidden||!(this.rotatable||this.scalable||this.translatable))return;const{$canvas:t}=this,{detail:n}=e;if(n){const{relatedEvent:e}=n;let{action:l}=n;switch(l!==bn||this.rotatable&&this.scalable||(l=this.rotatable?dn:this.scalable?un:mn),l){case cn:if(this.translatable){let l=null;e&&(l=e.target.closest(this.$getTagNameOf(rn))),l||(l=t.querySelector(this.$getTagNameOf(rn))),l&&l.multiple&&!l.active&&(l=t.querySelector(`${this.$getTagNameOf(rn)}[active]`)),l&&!l.hidden&&l.movable&&!l.dynamic&&this.$actionStartTarget&&l.contains(this.$actionStartTarget)||this.$move(n.endX-n.startX,n.endY-n.startY)}break;case dn:if(this.rotatable)if(e){const{x:t,y:l}=this.getBoundingClientRect();this.$rotate(n.rotate,e.clientX-t,e.clientY-l)}else this.$rotate(n.rotate);break;case un:if(this.scalable)if(e){const t=e.target.closest(this.$getTagNameOf(rn));if(!t||!t.zoomable||t.zoomable&&t.dynamic){const{x:t,y:l}=this.getBoundingClientRect();this.$zoom(n.scale,e.clientX-t,e.clientY-l)}}else this.$zoom(n.scale);break;case bn:if(this.rotatable&&this.scalable){const{rotate:t}=n;let{scale:l}=n;l<0?l=1/(1-l):l+=1;const r=Math.cos(t),a=Math.sin(t),[i,o,s,c]=[r*l,a*l,-a*l,r*l];if(e){const t=this.getBoundingClientRect(),n=e.clientX-t.x,l=e.clientY-t.y,[r,a,u,d]=this.$matrix,b=n-t.width/2,m=l-t.height/2,h=(b*d-u*m)/(r*d-u*a),p=(m*r-a*b)/(r*d-u*a);this.$transform(i,o,s,c,h*(1-i)+p*s,p*(1-c)+h*o)}else this.$transform(i,o,s,c,0,0)}}}}$ready(e){const{$image:t}=this,n=new Promise((e,n)=>{const l=new Error("Failed to load the image source");if(t.complete)t.naturalWidth>0&&t.naturalHeight>0?e(t):n(l);else{const r=()=>{Gn(t,Nn,a),setTimeout(()=>{e(t)})},a=()=>{Gn(t,$n,r),n(l)};Xn(t,$n,r),Xn(t,Nn,a)}});return Un(e)&&n.then(t=>(e(t),t)),n}$center(e){const{parentElement:t}=this;if(!t)return this;const n=t.getBoundingClientRect(),l=n.width,r=n.height,{x:a,y:i,width:o,height:s}=this.getBoundingClientRect(),c=a+o/2,u=i+s/2,d=n.x+l/2,b=n.y+r/2,{translatable:m}=this;if(m||this.$isReady||(this.translatable=!0,this.$nextTick(()=>{this.translatable=m})),this.$move(d-c,b-u),e&&(o!==l||s!==r)){const t=l/o,n=r/s,{scalable:a}=this;switch(!e||a||this.$isReady||(this.scalable=!0,this.$nextTick(()=>{this.scalable=a})),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&&Dn(e)&&Dn(t)){const[n,l,r,a]=this.$matrix,i=(e*a-r*t)/(n*a-r*l),o=(t*n-l*e)/(n*a-r*l);this.$translate(i,o)}return this}$moveTo(e,t=e){if(this.translatable&&Dn(e)&&Dn(t)){const[n,l,r,a]=this.$matrix,i=(e*a-r*t)/(n*a-r*l),o=(t*n-l*e)/(n*a-r*l);this.$setTransform(n,l,r,a,i,o)}return this}$rotate(e,t,n){if(this.rotatable){const l=tl(e),r=Math.cos(l),a=Math.sin(l),[i,o,s,c]=[r,a,-a,r];if(Dn(t)&&Dn(n)){const[e,l,r,a]=this.$matrix,{width:u,height:d}=this.getBoundingClientRect(),b=t-u/2,m=n-d/2,h=(b*a-r*m)/(e*a-r*l),p=(m*e-l*b)/(e*a-r*l);this.$transform(i,o,s,c,h*(1-i)-p*s,p*(1-c)-h*o)}else this.$transform(i,o,s,c,0,0)}return this}$zoom(e,t,n){if(!this.scalable||0===e)return this;if(e<0?e=1/(1-e):e+=1,Dn(t)&&Dn(n)){const[l,r,a,i]=this.$matrix,{width:o,height:s}=this.getBoundingClientRect(),c=t-o/2,u=n-s/2,d=(c*i-a*u)/(l*i-a*r),b=(u*l-r*c)/(l*i-a*r);this.$transform(e,0,0,e,d*(1-e),b*(1-e))}else this.$scale(e);return this}$scale(e,t=e){return this.scalable&&this.$transform(e,0,0,t,0,0),this}$skew(e,t=0){if(this.skewable){const n=tl(e),l=tl(t);this.$transform(1,Math.tan(l),Math.tan(n),1,0,0)}return this}$translate(e,t=e){return this.translatable&&Dn(e)&&Dn(t)&&this.$transform(1,0,0,1,e,t),this}$transform(e,t,n,l,r,a){return Dn(e)&&Dn(t)&&Dn(n)&&Dn(l)&&Dn(r)&&Dn(a)?this.$setTransform(rl(this.$matrix,[e,t,n,l,r,a])):this}$setTransform(e,t,n,l,r,a){if((this.rotatable||this.scalable||this.skewable||this.translatable)&&(Array.isArray(e)&&([e,t,n,l,r,a]=e),Dn(e)&&Dn(t)&&Dn(n)&&Dn(l)&&Dn(r)&&Dn(a))){const i=[...this.$matrix],o=[e,t,n,l,r,a];if(!1===this.$emit(Pn,{matrix:o,oldMatrix:i}))return this;this.$matrix=o,this.style.transform=`matrix(${o.join(", ")})`}return this}$getTransform(){return this.$matrix.slice()}$resetTransform(){return this.$setTransform([1,0,0,1,0,0])}}pl.$name=ln,pl.$version="2.1.1";const fl=/* @__PURE__ */new WeakMap;class gl extends dl{constructor(){super(...arguments),this.$onWindowResize=null,this.$onCanvasActionEnd=null,this.$onCanvasActionStart=null,this.$onSelectionChange=null,this.$style=":host{display:block;height:0;left:0;outline:var(--theme-color) solid 1px;position:relative;top:0;width:0}:host([transparent]){outline-color:transparent}",this.x=0,this.y=0,this.width=0,this.height=0,this.slottable=!1,this.themeColor="rgba(0, 0, 0, 0.65)"}set $canvas(e){fl.set(this,e)}get $canvas(){return fl.get(this)}static get observedAttributes(){return super.observedAttributes.concat(["height","width","x","y"])}connectedCallback(){super.connectedCallback();const e=this.closest(this.$getTagNameOf(Zt));if(e){this.$canvas=e,this.style.position="absolute";const t=e.querySelector(this.$getTagNameOf(rn));t&&(this.$onWindowResize=this.$render.bind(this),this.$onCanvasActionStart=e=>{t.hidden&&e.detail.action===sn&&(this.hidden=!1)},this.$onCanvasActionEnd=e=>{t.hidden&&e.detail.action===sn&&(this.hidden=!0)},this.$onSelectionChange=e=>{const{x:n,y:l,width:r,height:a}=e.defaultPrevented?t:e.detail;this.$change(n,l,r,a),(t.hidden||0===n&&0===l&&0===r&&0===a)&&(this.hidden=!0)},Qn(window,_n,this.$onWindowResize),Qn(e,Ln,this.$onCanvasActionStart),Qn(e,An,this.$onCanvasActionEnd),Qn(e,In,this.$onSelectionChange))}this.$render()}disconnectedCallback(){const{$canvas:e}=this;e&&(this.$onWindowResize&&(Gn(window,_n,this.$onWindowResize),this.$onWindowResize=null),this.$onCanvasActionStart&&(Gn(e,Ln,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(Gn(e,An,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onSelectionChange&&(Gn(e,In,this.$onSelectionChange),this.$onSelectionChange=null)),super.disconnectedCallback()}$change(e,t,n=this.width,l=this.height){return Dn(e)&&Dn(t)&&Dn(n)&&Dn(l)&&(e!==this.x||t!==this.y||n!==this.width||l!==this.height)?(this.hidden&&(this.hidden=!1),this.x=e,this.y=t,this.width=n,this.height=l,this.$render()):this}$reset(){return this.$change(0,0,0,0)}$render(){return this.$setStyles({transform:`translate(${this.x}px, ${this.y}px)`,width:this.width,height:this.height,outlineWidth:Qt.innerWidth*Qt.devicePixelRatio})}}gl.$name=an,gl.$version="2.1.1";class vl extends dl{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=mn,this.plain=!1,this.slottable=!1,this.themeColor="rgba(51, 153, 255, 0.5)"}static get observedAttributes(){return super.observedAttributes.concat(["action","plain"])}}vl.$name=nn,vl.$version="2.1.1";const yl=/* @__PURE__ */new WeakMap;class wl extends dl{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){yl.set(this,e)}get $canvas(){return yl.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(()=>{Rn(n)&&n<=1&&this.$initSelection(!0,!0)});break;case"keyboard":this.$nextTick(()=>{this.$canvas&&(n?this.$onDocumentKeyDown||(this.$onDocumentKeyDown=this.$handleKeyDown.bind(this),Qn(this.ownerDocument,En,this.$onDocumentKeyDown)):this.$onDocumentKeyDown&&(Gn(this.ownerDocument,En,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(In,{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(Zt));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),Qn(e,Ln,this.$onCanvasActionStart),Qn(e,An,this.$onCanvasActionEnd),Qn(e,Tn,this.$onCanvasAction)):this.$render()}disconnectedCallback(){const{$canvas:e}=this;e&&(this.$onCanvasActionStart&&(Gn(e,Ln,this.$onCanvasActionStart),this.$onCanvasActionStart=null),this.$onCanvasActionEnd&&(Gn(e,An,this.$onCanvasActionEnd),this.$onCanvasActionEnd=null),this.$onCanvasAction&&(Gn(e,Tn,this.$onCanvasAction),this.$onCanvasAction=null)),super.disconnectedCallback()}$getSelections(){let e=[];return this.parentElement&&(e=Array.from(this.parentElement.querySelectorAll(this.$getTagNameOf(rn)))),e}$initSelection(e=!1,t=!1){const{initialCoverage:n,parentElement:l}=this;if(Rn(n)&&l){const r=this.aspectRatio||this.initialAspectRatio;let a=(t?0:this.width)||l.offsetWidth*n,i=(t?0:this.height)||l.offsetHeight*n;Rn(r)&&({width:a,height:i}=ll({aspectRatio:r,width:a,height:i})),this.$change(this.x,this.y,a,i),e&&this.$center(),this.$initialSelection={x:this.x,y:this.y,width:this.width,height:this.height}}}$createSelection(){const e=this.cloneNode(!0);return this.hasAttribute("id")&&e.removeAttribute("id"),e.initialCoverage=NaN,this.active=!1,this.parentElement&&this.parentElement.insertBefore(e,this.nextSibling),e}$removeSelection(e=this){if(this.parentElement){const t=this.$getSelections();if(t.length>1){const n=t.indexOf(e),l=t[n+1]||t[n-1];l&&(e.active=!1,this.parentElement.removeChild(e),l.active=!0,l.$emit(In,{x:l.x,y:l.y,width:l.width,height:l.height}))}else this.$clear()}}$handleActionStart(e){var t,n;const l=null===(n=null===(t=e.detail)||void 0===t?void 0:t.relatedEvent)||void 0===n?void 0:n.target;this.$action="",this.$actionStartTarget=l,!this.hidden&&this.multiple&&!this.active&&l===this&&this.parentElement&&(this.$getSelections().forEach(e=>{e.active=!1}),this.active=!0,this.$emit(In,{x:this.x,y:this.y,width:this.width,height:this.height}))}$handleAction(e){const{currentTarget:t,detail:n}=e;if(!t||!n)return;const{relatedEvent:l}=n;let{action:r}=n;const a=l?function(e){if("function"==typeof e.composedPath)return e.composedPath().find(Bn)||e.target;return e.target}(l):null;if(!r&&this.multiple&&(r=this.$action||(null==a?void 0:a.action),this.$action=r),!r||this.hidden&&r!==sn||this.multiple&&!this.active&&r!==un)return;const{width:i,height:o}=this;let s=n.endX-n.startX,c=n.endY-n.startY,{aspectRatio:u}=this;switch(!Rn(u)&&l.shiftKey&&(u=Rn(i)&&Rn(o)?i/o:1),r){case sn:if(0!==s||0!==c){0===s?s=c:0===c&&(c=s);const{$canvas:e}=this,l=Zn(t);(this.multiple&&!this.hidden?this.$createSelection():this).$change(n.startX-l.left,n.startY-l.top,Math.abs(s),Math.abs(c),u),s<0?c<0?r=yn:c>0&&(r=xn):s>0&&(c<0?r=vn:c>0&&(r=wn)),e&&(e.$action=r)}break;case cn:this.movable&&(this.dynamic||this.$actionStartTarget&&this.contains(this.$actionStartTarget))&&this.$move(s,c);break;case un:if(l&&this.zoomable&&(this.dynamic||this.contains(l.target))){const e=Zn(t);this.$zoom(n.scale,l.pageX-e.left,l.pageY-e.top)}break;default:this.$resize(r,s,c,u)}}$handleActionEnd(){this.$action="",this.$actionStartTarget=null}$handleKeyDown(e){if(this.hidden||!this.keyboard||this.multiple&&!this.active||e.defaultPrevented)return;const{activeElement:t}=document;if(!t||!["INPUT","TEXTAREA"].includes(t.tagName)&&!["true","plaintext-only"].includes(t.contentEditable))switch(e.key){case"Backspace":e.metaKey&&(e.preventDefault(),this.$removeSelection());break;case"Delete":e.preventDefault(),this.$removeSelection();break;case"ArrowLeft":e.preventDefault(),this.$move(-1,0);break;case"ArrowRight":e.preventDefault(),this.$move(1,0);break;case"ArrowUp":e.preventDefault(),this.$move(0,-1);break;case"ArrowDown":e.preventDefault(),this.$move(0,1);break;case"+":e.preventDefault(),this.$zoom(.1);break;case"-":e.preventDefault(),this.$zoom(-.1)}}$center(){const{parentElement:e}=this;if(!e)return this;const t=(e.offsetWidth-this.width)/2,n=(e.offsetHeight-this.height)/2;return this.$change(t,n)}$move(e,t=e){return this.$moveTo(this.x+e,this.y+t)}$moveTo(e,t=e){return this.movable?this.$change(e,t):this}$resize(e,t=0,n=0,l=this.aspectRatio){if(!this.resizable)return this;const r=Rn(l),{$canvas:a}=this;let{x:i,y:o,width:s,height:c}=this;switch(e){case hn:o+=n,c-=n,c<0&&(e=fn,c=-c,o-=c),r&&(i+=(t=n*l)/2,s-=t,s<0&&(s=-s,i-=s));break;case pn:s+=t,s<0&&(e=gn,s=-s,i-=s),r&&(o-=(n=t/l)/2,c+=n,c<0&&(c=-c,o-=c));break;case fn:c+=n,c<0&&(e=hn,c=-c,o-=c),r&&(i-=(t=n*l)/2,s+=t,s<0&&(s=-s,i-=s));break;case gn:i+=t,s-=t,s<0&&(e=pn,s=-s,i-=s),r&&(o+=(n=t/l)/2,c-=n,c<0&&(c=-c,o-=c));break;case vn:r&&(n=-t/l),o+=n,c-=n,s+=t,s<0&&c<0?(e=xn,s=-s,c=-c,i-=s,o-=c):s<0?(e=yn,s=-s,i-=s):c<0&&(e=wn,c=-c,o-=c);break;case yn:r&&(n=t/l),i+=t,o+=n,s-=t,c-=n,s<0&&c<0?(e=wn,s=-s,c=-c,i-=s,o-=c):s<0?(e=vn,s=-s,i-=s):c<0&&(e=xn,c=-c,o-=c);break;case wn:r&&(n=t/l),s+=t,c+=n,s<0&&c<0?(e=yn,s=-s,c=-c,i-=s,o-=c):s<0?(e=xn,s=-s,i-=s):c<0&&(e=vn,c=-c,o-=c);break;case xn:r&&(n=-t/l),i+=t,s-=t,c+=n,s<0&&c<0?(e=vn,s=-s,c=-c,i-=s,o-=c):s<0?(e=wn,s=-s,i-=s):c<0&&(e=yn,c=-c,o-=c)}return a&&a.$setAction(e),this.$change(i,o,s,c)}$zoom(e,t,n){if(!this.zoomable||0===e)return this;e<0?e=1/(1-e):e+=1;const{width:l,height:r}=this,a=l*e,i=r*e;let o=this.x,s=this.y;return Dn(t)&&Dn(n)?(o-=(a-l)*((t-this.x)/l),s-=(i-r)*((n-this.y)/r)):(o-=(a-l)/2,s-=(i-r)/2),this.$change(o,s,a,i)}$change(e,t,n=this.width,l=this.height,r=this.aspectRatio,a=!1){return this.$changing||!Dn(e)||!Dn(t)||!Dn(n)||!Dn(l)||n<0||l<0?this:(Rn(r)&&({width:n,height:l}=ll({aspectRatio:r,width:n,height:l},"cover")),this.precise||(e=Math.round(e),t=Math.round(t),n=Math.round(n),l=Math.round(l)),e===this.x&&t===this.y&&n===this.width&&l===this.height&&Object.is(r,this.aspectRatio)&&!a?this:(this.hidden&&(this.hidden=!1),!1===this.$emit(In,{x:e,y:t,width:n,height:l})?this:(this.$changing=!0,this.x=e,this.y=t,this.width=n,this.height=l,this.$changing=!1,this.$render())))}$reset(){const{x:e,y:t,width:n,height:l}=this.$initialSelection;return this.$change(e,t,n,l)}$clear(){return this.$change(0,0,0,0,NaN,!0),this.hidden=!0,this}$render(){return this.$setStyles({transform:`translate(${this.x}px, ${this.y}px)`,width:this.width,height:this.height})}$toCanvas(e){return new Promise((t,n)=>{if(!this.isConnected)return void n(new Error("The current element is not connected to the DOM."));const l=document.createElement("canvas");let{width:r,height:a}=this,i=1;if(jn(e)&&(Rn(e.width)||Rn(e.height))&&(({width:r,height:a}=ll({aspectRatio:r/a,width:e.width,height:e.height})),i=r/this.width),l.width=r,l.height=a,!this.$canvas)return void t(l);const o=this.$canvas.querySelector(this.$getTagNameOf(ln));o?o.$ready().then(n=>{const s=l.getContext("2d");if(s){const[t,c,u,d,b,m]=o.$getTransform(),h=-this.x,p=-this.y,f=(h*d-u*p)/(t*d-u*c),g=(p*t-c*h)/(t*d-u*c);let v=t*f+u*g+b,y=c*f+d*g+m,w=n.naturalWidth,x=n.naturalHeight;1!==i&&(v*=i,y*=i,w*=i,x*=i);const k=w/2,C=x/2;s.fillStyle="transparent",s.fillRect(0,0,r,a),jn(e)&&Un(e.beforeDraw)&&e.beforeDraw.call(this,s,l),s.save(),s.translate(k,C),s.transform(t,c,u,d,v,y),s.translate(-k,-C),s.drawImage(n,0,0,w,x),s.restore()}t(l)}).catch(n):t(l)})}}wl.$name=rn,wl.$version="2.1.1";class xl extends dl{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))}}xl.$name=tn,xl.$version="2.1.1";class kl extends dl{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"])}}kl.$name=en,kl.$version="2.1.1";const Cl=/* @__PURE__ */new WeakMap,Sl=/* @__PURE__ */new WeakMap,Nl=/* @__PURE__ */new WeakMap,El=/* @__PURE__ */new WeakMap,$l="vertical";class _l extends dl{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=$l,this.selection="",this.slottable=!1}set $image(e){Sl.set(this,e)}get $image(){return Sl.get(this)}set $sourceImage(e){El.set(this,e)}get $sourceImage(){return El.get(this)}set $canvas(e){Cl.set(this,e)}get $canvas(){return Cl.get(this)}set $selection(e){Nl.set(this,e)}get $selection(){return Nl.get(this)}static get observedAttributes(){return super.observedAttributes.concat(["resize","selection"])}connectedCallback(){var e,t;super.connectedCallback();let n=null;if(n=this.selection?null!==(t=null===(e=function(e){const t=e.getRootNode();switch(t.nodeType){case 1:return t.ownerDocument;case 9:case 11:return t}return null}(this))||void 0===e?void 0:e.querySelector(this.selection))&&void 0!==t?t:null:this.closest(this.$getTagNameOf(rn)),Bn(n)){this.$selection=n,this.$onSelectionChange=this.$handleSelectionChange.bind(this),Qn(n,In,this.$onSelectionChange);const e=n.closest(this.$getTagNameOf(Zt));if(e){this.$canvas=e;const t=e.querySelector(this.$getTagNameOf(ln));t&&(this.$sourceImage=t,this.$image=t.cloneNode(!0),this.$getShadowRoot().appendChild(this.$image),this.$onSourceImageLoad=this.$handleSourceImageLoad.bind(this),this.$onSourceImageTransform=this.$handleSourceImageTransform.bind(this),Qn(t.$image,$n,this.$onSourceImageLoad),Qn(t,Pn,this.$onSourceImageTransform))}this.$render()}}disconnectedCallback(){const{$selection:e,$sourceImage:t}=this;e&&this.$onSelectionChange&&(Gn(e,In,this.$onSelectionChange),this.$onSelectionChange=null),t&&this.$onSourceImageLoad&&(Gn(t.$image,$n,this.$onSourceImageLoad),this.$onSourceImageLoad=null),t&&this.$onSourceImageTransform&&(Gn(t,Pn,this.$onSourceImageTransform),this.$onSourceImageTransform=null),super.disconnectedCallback()}$handleSelectionChange(e){this.$render(e.defaultPrevented?this.$selection:e.detail)}$handleSourceImageLoad(){const{$image:e,$sourceImage:t}=this,n=e.getAttribute("src"),l=t.getAttribute("src");l&&l!==n&&(e.setAttribute("src",l),e.$ready(()=>{this.$render()}))}$handleSourceImageTransform(e){this.$render(void 0,e.detail.matrix)}$render(e,t){const{$canvas:n,$selection:l}=this;e||l.hidden||(e=l),(!e||0===e.x&&0===e.y&&0===e.width&&0===e.height)&&(e={x:0,y:0,width:n.offsetWidth,height:n.offsetHeight});const{x:r,y:a,width:i,height:o}=e,s={},{clientWidth:c,clientHeight:u}=this;let d=c,b=u,m=NaN;switch(this.resize){case"both":m=1,d=i,b=o,s.width=i,s.height=o;break;case"horizontal":m=o>0?u/o:0,d=i*m,s.width=d;break;case $l:m=i>0?c/i:0,b=o*m,s.height=b;break;default:c>0?m=i>0?c/i:0:u>0&&(m=o>0?u/o:0)}this.$scale=m,this.$setStyles(s),this.$sourceImage&&setTimeout(()=>{this.$transformImageByOffset(null!=t?t:this.$sourceImage.$getTransform(),-r,-a)})}$transformImageByOffset(e,t,n){const{$image:l,$scale:r,$sourceImage:a}=this;if(a&&l&&r>=0){const[i,o,s,c,u,d]=e,b=(t*c-s*n)/(i*c-s*o),m=(n*i-o*t)/(i*c-s*o),h=i*b+s*m+u,p=o*b+c*m+d;a.$ready(e=>{this.$setStyles.call(l,{width:e.naturalWidth*r,height:e.naturalHeight*r})}),l.$setTransform(i,o,s,c,h*r,p*r)}}}function zl(){const[e,n]=t(!1),[l,r]=t(null),[a,i]=t(null),o=async(e,t)=>{if(!e||!t)return r("ID de asset y configuración de variante son requeridos"),null;n(!0),r(null),i(null);try{const n=await async function(e,{variant_name:t,width:n,height:r,crop_params:a,preset_aspect:i=null,preset_size:o=null,output_format:s="webp"}){try{const l=[{name:t,width:n,height:r,output_format:s,crop_params:a}];return i&&(l[0].preset_aspect=i),o&&(l[0].preset_size=o),le(await Y({endpoint:`/assets/${e}/variants`,method:"POST",body:{variants:l,async:!1},basePath:ae,useJWT:!0}))}catch(l){throw re(l)}}(e,{variant_name:t.name,width:t.width,height:t.height,crop_params:t.crop_params,preset_aspect:t.preset_aspect,preset_size:t.preset_size,output_format:t.output_format});if(n?.result)return i(n.result),n.result;throw new Error("No se pudo crear la variante")}catch(a){return console.error("Error creating variant:",a),r(a.message||"Error desconocido al crear variante"),null}finally{n(!1)}};return{createVariant:o,createCropVariant:async(e,t,n={})=>{const l={name:n.name||`crop_${Date.now()}`,width:n.width||800,height:n.height||600,output_format:n.format||"webp",crop_params:{x:t.x||0,y:t.y||0,width:t.width||1,height:t.height||1}};return await o(e,l)},createVariantFromBlob:async(e,t,a={})=>{if(!e||!t)return r("ID de asset y blob son requeridos"),null;n(!0),r(null),i(null);try{const n=await async function(e,t,n={}){try{const l=new FormData,r=n.format||"webp",a=`${n.name||"variant"}.${r}`;return l.append("file",t,a),l.append("variant_name",n.name||"variant"),l.append("width",String(n.width||0)),l.append("height",String(n.height||0)),l.append("output_format",n.format||"webp"),l.append("permanent_url",!1!==n.permanentUrl?"true":"false"),le(await Y({endpoint:`/assets/${e}/variants/upload`,method:"POST",body:l,basePath:ae,isFormData:!0,useJWT:!0}))}catch(l){throw re(l)}}(e,t,{name:a.name||`crop_${Date.now()}`,width:a.width||0,height:a.height||0,format:a.format||"webp"});if(n?.result)return i(n.result),n.result;throw new Error("No se pudo crear la variante")}catch(o){return console.error("Error creating variant from blob:",o),r(o.message||"Error desconocido al crear variante"),null}finally{n(!1)}},loading:e,error:l,createdVariant:a,reset:()=>{r(null),i(null)}}}_l.$name=on,_l.$version="2.1.1",bl.$define(),kl.$define(),xl.$define(),vl.$define(),pl.$define(),wl.$define(),gl.$define(),_l.$define();class Tl{constructor(e,t,n){this.canvasRef=e,this.imageRef=t,this.selectionRef=n}get canvasElement(){return this.canvasRef?.current}get image(){return this.imageRef?.current}get selectionElement(){return this.selectionRef?.current}get isReady(){return!!(this.canvasElement&&this.image&&this.selectionElement)}transform={move:(e,t)=>{if(!this.image)return!1;try{return this.image.$move(e,t),!0}catch(n){return console.warn("Error moving image:",n),!1}},moveTo:(e,t)=>{if(!this.image)return!1;try{return this.image.$moveTo(e,t),!0}catch(n){return console.warn("Error moving image to position:",n),!1}},zoom:e=>{if(!this.image)return!1;try{return this.image.$zoom(e),!0}catch(t){return console.warn("Error zooming image:",t),!1}},rotate:e=>{if(!this.image)return!1;try{const t=e*Math.PI/180;return this.image.$rotate(t),!0}catch(t){return console.warn("Error rotating image:",t),!1}},scale:(e,t=e)=>{if(!this.image)return!1;try{return this.image.$scale(e,t),!0}catch(n){return console.warn("Error scaling image:",n),!1}},center:(e="contain")=>{if(!this.image)return!1;try{return this.image.$center(e),!0}catch(t){return console.warn("Error centering image:",t),!1}},reset:()=>{if(!this.image)return!1;try{return this.image.$resetTransform(),!0}catch(e){return console.warn("Error resetting transform:",e),!1}},getTransform:()=>{if(!this.image)return null;try{return this.image.$getTransform()}catch(e){return console.warn("Error getting transform:",e),null}},setTransform:(e,t,n,l,r,a)=>{if(!this.image)return!1;try{return this.image.$setTransform(e,t,n,l,r,a),!0}catch(i){return console.warn("Error setting transform:",i),!1}},resetZoom:()=>{if(!this.image)return!1;try{const e=this.image.$getTransform();if(!e)return!1;const[t,n,l,r,a,i]=e,o=Math.sqrt(t*t+n*n),s=Math.sqrt(l*l+r*r),c=t/o,u=n/o,d=l/s,b=r/s;return this.image.$setTransform(c,u,d,b,a,i),!0}catch(e){return console.warn("Error resetting zoom:",e),!1}},setZoom:e=>{if(!this.image||e<=0)return!1;try{const t=this.image.$getTransform();if(!t)return!1;const[n,l,r,a,i,o]=t,s=Math.sqrt(n*n+l*l),c=Math.sqrt(r*r+a*a),u=n/s*e,d=l/s*e,b=r/c*e,m=a/c*e;return this.image.$setTransform(u,d,b,m,i,o),!0}catch(t){return console.warn("Error setting zoom level:",t),!1}},getZoom:()=>{if(!this.image)return 1;try{const e=this.image.$getTransform();if(!e)return 1;const[t,n]=e;return Math.sqrt(t*t+n*n)}catch(e){return console.warn("Error getting zoom level:",e),1}},fitToCanvas:(e=.1)=>{if(!this.image||!this.canvasElement)return!1;try{const t=this.canvasElement.getBoundingClientRect();let n=this.image.querySelector("img")||this.image;if(!n?.naturalWidth||!n?.naturalHeight)return!1;const l=1-e,r=t.width*l/n.naturalWidth,a=t.height*l/n.naturalHeight,i=Math.min(r,a,1);return this.transform.setZoom(i)}catch(t){return console.warn("Error fitting to canvas:",t),!1}}};selection={center:()=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$center(),!0}catch(e){return console.warn("Error centering selection:",e),!1}},reset:()=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$reset(),!0}catch(e){return console.warn("Error resetting selection:",e),!1}},setCoverage:e=>{if(!this.selectionElement||e<0||e>1)return!1;try{return this.selectionElement.initialCoverage=e,this.selectionElement.$reset(),!0}catch(t){return console.warn("Error setting coverage:",t),!1}},setAspectRatio:e=>{if(!this.selectionElement)return!1;try{let t;if(""===e||null==e)t=NaN;else if("number"==typeof e)t=e;else{if("string"!=typeof e)return console.warn("Unsupported aspect ratio type:",typeof e,e),!1;if(e.includes("/")){const[n,l]=e.split("/").map(e=>parseFloat(e.trim()));if(isNaN(n)||isNaN(l)||0===l)return console.warn("Invalid aspect ratio format:",e),!1;t=n/l}else if(t=parseFloat(e),isNaN(t))return console.warn("Invalid aspect ratio format:",e),!1}return this.selectionElement.aspectRatio=t,this.selectionElement.$render(),!0}catch(t){return console.warn("Error setting aspect ratio:",t),!1}},move:(e,t)=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$move(e,t),!0}catch(n){return console.warn("Error moving selection:",n),!1}},zoom:e=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$zoom(e),!0}catch(t){return console.warn("Error zooming selection:",t),!1}},change:(e,t,n,l,r)=>{if(!this.selectionElement)return!1;try{return this.selectionElement.$change(e,t,n,l,r),!0}catch(a){return console.warn("Error changing selection:",a),!1}},set:(e,t,n,l)=>{if(!this.selectionElement)return!1;try{return this.selectionElement.x=e,this.selectionElement.y=t,this.selectionElement.width=n,this.selectionElement.height=l,this.selectionElement.$render(),!0}catch(r){return console.warn("Error setting selection:",r),!1}},toCanvas:async(e={})=>{if(!this.selectionElement)return null;try{const t={width:800,height:600,imageSmoothingEnabled:!0,imageSmoothingQuality:"high",...e};return await this.selectionElement.$toCanvas(t)}catch(t){return console.warn("Error exporting to canvas:",t),null}},getData:()=>{if(!this.selectionElement)return null;try{return{x:this.selectionElement.x,y:this.selectionElement.y,width:this.selectionElement.width,height:this.selectionElement.height,aspectRatio:this.selectionElement.aspectRatio}}catch(e){return console.warn("Error getting selection data:",e),null}}};canvas={setBackground:e=>{if(!this.canvasElement)return!1;try{return this.canvasElement.background=e,!0}catch(t){return console.warn("Error setting background:",t),!1}},setScaleStep:e=>{if(!this.canvasElement)return!1;try{return this.canvasElement.scaleStep=e,!0}catch(t){return console.warn("Error setting scale step:",t),!1}},setDisabled:e=>{if(!this.canvasElement)return!1;try{return this.canvasElement.disabled=e,!0}catch(t){return console.warn("Error setting disabled state:",t),!1}}};utils={flipHorizontal:()=>{const e=this.transform.getTransform();if(!e)return!1;const[t,n,l,r,a,i]=e;return this.transform.setTransform(-t,n,l,r,a,i)},flipVertical:()=>{const e=this.transform.getTransform();if(!e)return!1;const[t,n,l,r,a,i]=e;return this.transform.setTransform(t,n,l,-r,a,i)},setupInitialView:async(e={})=>{const{paspartuFactor:t=.85,retries:n=3,retryDelay:l=200}=e;return new Promise(e=>{const r=(a=0)=>{if(!this.isReady)return a<n?void setTimeout(()=>r(a+1),l):void e(!1);try{const i=this.canvasElement.getBoundingClientRect();let o=this.image.querySelector("img")||this.image;if(!o?.naturalWidth||!o?.naturalHeight)return a<n?void setTimeout(()=>r(a+1),l):(this.transform.center(),void e(!1));if(i.width>0&&i.height>0){const n=i.width*t/o.naturalWidth,l=i.height*t/o.naturalHeight,r=Math.min(n,l,1);this.transform.setTransform(r,0,0,r,0,0)?setTimeout(()=>{this.transform.center(),this.selection.center(),e(!0)},100):(this.transform.reset(),setTimeout(()=>{r<1&&this.transform.scale(r),setTimeout(()=>{this.transform.center(),this.selection.center(),e(!0)},100)},100))}else this.transform.center(),e(!1)}catch(i){console.warn("Error in setup:",i),this.transform.center(),e(!1)}};r()})},resetAll:()=>{const e={transform:this.transform.reset(),selection:this.selection.reset(),center:!1};return setTimeout(()=>{e.center=this.transform.center()&&this.selection.center()},100),e},checkExportability:async()=>{try{return!!(await this.selection.toCanvas({width:1,height:1}))}catch{return!1}},resetZoomOnly:()=>this.transform.resetZoom(),getZoomInfo:()=>{const e=this.transform.getZoom();return{current:e,isZoomedIn:e>1,isZoomedOut:e<1,percentage:Math.round(100*e)}},setBackground:e=>this.canvas.setBackground(e)};setupEventListeners(e={}){const{onSelectionChange:t,onImageTransform:n,onAction:l,onActionStart:r,onActionMove:a,onActionEnd:i}=e,o=[];if(t&&this.selectionElement){const e=e=>{t({x:e.detail.x,y:e.detail.y,width:e.detail.width,height:e.detail.height})};this.selectionElement.addEventListener("change",e),o.push(()=>{this.selectionElement&&this.selectionElement.removeEventListener("change",e)})}if(n&&this.image){const e=e=>{n({matrix:e.detail.matrix,oldMatrix:e.detail.oldMatrix})};this.image.addEventListener("transform",e),o.push(()=>{this.image&&this.image.removeEventListener("transform",e)})}if(this.canvasElement){if(l){const e=e=>l(e.detail);this.canvasElement.addEventListener("action",e),o.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("action",e)})}if(r){const e=e=>r(e.detail);this.canvasElement.addEventListener("actionstart",e),o.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionstart",e)})}if(a){const e=e=>a(e.detail);this.canvasElement.addEventListener("actionmove",e),o.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionmove",e)})}if(i){const e=e=>i(e.detail);this.canvasElement.addEventListener("actionend",e),o.push(()=>{this.canvasElement&&this.canvasElement.removeEventListener("actionend",e)})}}return()=>{o.forEach(e=>e())}}}async function Al(e,t,n={}){const{format:l=null,originalFormat:r="webp",onSuccess:a=null,onError:i=null,accessibilityManager:o=null}=n;try{const n=window.limboCore?.config?.getGlobal(),i=l||n?.downloadFormat||r||"webp",c=`${t.split(".")[0]}.${i}`;if(o&&o.announce(`Descargando ${c}`),e.startsWith("data:image/"))return function(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.style.display="none",document.body.appendChild(n),n.click(),setTimeout(()=>{document.body.removeChild(n)},100)}(e,c),a&&a(c),o&&o.announce(`${c} descargado correctamente`),!0;let u;try{if(u=await fetch(e,{mode:"cors"}),!u.ok)throw new Error(`HTTP error! status: ${u.status}`)}catch(s){if(!e.startsWith("http"))throw s;{const t=(window.limboCore?.config?.getGlobal()||{}).prod?"https://limbo.lefebvre.es":"https://led-dev-limbo-dev.eu.els.local",n=window.limboCore?.apiClient?.token||"",l=`${t}/api/atenea/proxy?url=${encodeURIComponent(e)}`;if(u=await fetch(l,{credentials:"include",headers:{Authorization:`Bearer ${n}`}}),!u.ok)throw new Error(`Proxy error: ${u.status}`)}}const d=await u.blob();let b=d;const m=d.type;m!==`image/${"jpg"===i?"jpeg":i}`&&function(e){return["webp","jpeg","jpg","svg","png"].includes(e.toLowerCase())}(i)&&(b=await async function(e,t){return new Promise((n,l)=>{const r=new Image,a=URL.createObjectURL(e);r.onload=()=>{try{const l=document.createElement("canvas");l.width=r.width,l.height=r.height;l.getContext("2d").drawImage(r,0,0);const i=`image/${"jpg"===t?"jpeg":t}`,o="png"===t?void 0:.92;l.toBlob(t=>{URL.revokeObjectURL(a),n(t||e)},i,o)}catch(l){URL.revokeObjectURL(a),n(e)}},r.onerror=()=>{URL.revokeObjectURL(a),n(e)},r.src=a})}(d,i));const h=window.URL.createObjectURL(b),p=document.createElement("a");return p.href=h,p.download=c,p.style.display="none",document.body.appendChild(p),p.click(),setTimeout(()=>{window.URL.revokeObjectURL(h),document.body.removeChild(p)},100),a&&a(c),o&&o.announce(`${c} descargado correctamente`),!0}catch(c){return console.error("Error downloading image:",c),i&&i(c),o&&o.announce(`Error al descargar la imagen: ${c.message}`),!1}}const Ll=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:Al,downloadImage:Al},Symbol.toStringTag,{value:"Module"}));function Il({image:e,onSave:i,onCancel:o,onDelete:d,onError:b=null,deleting:m=!1,onVariantCreated:h=null,onUpload:p=null,uploading:f=!1,cropperConfig:g=null}){const[v,y]=t(!1),[w,x]=t(null),[k,C]=t(!1),[S,N]=t(!0),[E,$]=t(!0),[_,z]=t(e.url||e.path||null);n(()=>{const t=e.url||e.path;if(!t||t.startsWith("blob:")||t.startsWith("data:"))return void z(t);let n=!1;return Ce(t,{bypassHttpCache:!0}).then(e=>{n||z(e)}).catch(()=>{n||z(t)}),()=>{n=!0}},[e.url,e.path]);const[T,A]=t({x:20,y:100}),[L,I]=t(!1),[P,M]=t({x:0,y:0}),[D,R]=t(!1),[O,F]=t(!0),[j,U]=t(!1),[B,W]=t({horizontal:!1,vertical:!1}),[q,V]=t(!1),[H,K]=t(!1),[G,Q]=t(!1),[X,Y]=t(!1),[J]=t(()=>{if(!e||!e.filename)return"image";const[t]=e.filename.split(".");return t}),Z=l(()=>{if(g)return{mandatoryCrops:g.mandatoryCrops||[],allowCustomCrops:!1!==g.allowAdditionalCrops,showDimensionInputs:!0===g.showDimensionInputs,maxCrops:g.maxCrops||null,localCropsOnly:!0===g.localCropsOnly,existingCrops:g.existingCrops||null};const e=window.limboCore?.config?.getGlobal()||{};return{mandatoryCrops:e.cropper?.mandatoryCrops||[],allowCustomCrops:!1!==e.cropper?.allowCustomCrops,showDimensionInputs:!0===e.cropper?.showDimensionInputs,maxCrops:e.cropper?.maxCrops||null,localCropsOnly:!0===e.cropper?.localCropsOnly,existingCrops:e.cropper?.existingCrops||null}},[g]),[ee,te]=t(()=>Z.mandatoryCrops.length>0?Z.mandatoryCrops.map((e,t)=>({id:`crop-${t}`,label:e.label,width:e.width,height:e.height,required:!1!==e.required,isCustom:!1,confirmed:!1,lockDimensions:!(!e.width||!e.height),format:e.format||null,savedState:null})):[{id:"crop-default-0",label:J,width:e.width||1920,height:e.height||1080,required:!1,isCustom:!0,confirmed:!1,savedState:null}]),[ne,le]=t(0),re=ee[ne],ae=l(()=>re&&re.width&&re.height?re.width/re.height:"",[re]),ie=l(()=>{const e=50;if(!ae||""===ae)return{minWidth:e,minHeight:e};if(ae>=1){return{minWidth:e,minHeight:e/ae}}return{minWidth:e*ae,minHeight:e}},[ae]),[oe,se]=t(!1),[ce,ue]=t([]),[de,be]=t(null),me=window.limboCore?.accessibilityManager,{createVariantFromBlob:he,loading:pe,error:fe}=zl(),ge=((e,a={})=>{const i=r(null),o=r(null),s=r(null),c=r(null),[u,d]=t(null),[b,m]=t(null),[h,p]=t(!1),[f,g]=t(!0),[v,y]=t(0),w={aspectRatio:"",shade:!0,paspartuFactor:.85,...a};n(()=>{i.current&&o.current&&s.current&&(c.current=new Tl(i,o,s),p(!0))},[]),n(()=>{if(c.current)return c.current.setupEventListeners({onSelectionChange:e=>{d(e)},onImageTransform:()=>{y(e=>e+1)}})},[h]),n(()=>{c.current&&e&&(async()=>{c.current.selection.setAspectRatio(w.aspectRatio),c.current.canvas.setBackground(w.shade),await c.current.utils.setupInitialView({paspartuFactor:w.paspartuFactor});const e=await c.current.utils.checkExportability();g(e);const t=o.current?.querySelector("img")||o.current;t?.naturalWidth&&t?.naturalHeight&&m({naturalWidth:t.naturalWidth,naturalHeight:t.naturalHeight,currentWidth:t.width,currentHeight:t.height})})()},[e]),n(()=>{c.current&&h&&c.current.selection.setAspectRatio(w.aspectRatio)},[w.aspectRatio,h]),n(()=>{c.current&&h&&c.current.canvas.setBackground(w.shade)},[w.shade,h]);const x=l(()=>({move:(e,t)=>c.current?.transform.move(e,t)||!1,zoom:e=>c.current?.transform.zoom(e)||!1,rotate:e=>c.current?.transform.rotate(e)||!1,center:()=>c.current?.transform.center()||!1,reset:()=>c.current?.transform.reset()||!1,resetZoom:()=>c.current?.transform.resetZoom()||!1,setZoom:e=>c.current?.transform.setZoom(e)||!1,getZoom:()=>c.current?.transform.getZoom()||1,fitToCanvas:e=>c.current?.transform.fitToCanvas(e)||!1,flipHorizontal:()=>c.current?.utils.flipHorizontal()||!1,flipVertical:()=>c.current?.utils.flipVertical()||!1}),[]),k=l(()=>({center:()=>c.current?.selection.center()||!1,reset:()=>c.current?.selection.reset()||!1,setCoverage:e=>c.current?.selection.setCoverage(e)||!1,setAspectRatio:e=>c.current?.selection.setAspectRatio(e)||!1,toCanvas:e=>c.current?.selection.toCanvas(e)||Promise.resolve(null)}),[]),C=l(()=>({resetAll:()=>{if(c.current){const e=c.current.utils.resetAll();return d(null),e}return!1},setBackground:e=>c.current?.canvas.setBackground(e)||!1,resetZoomOnly:()=>c.current?.utils.resetZoomOnly()||!1,getZoomInfo:()=>c.current?.utils.getZoomInfo()||{current:1,percentage:100,isZoomedIn:!1,isZoomedOut:!1}}),[]);return{refs:{canvasRef:i,imageRef:o,selectionRef:s},state:{cropData:u,imageInfo:b,isReady:h,canExport:f,transformVersion:v},transform:x,selection:k,utils:C,manager:c.current}})(e,{aspectRatio:ae||null,showGrid:S,shade:E,initialCoverage:.5,paspartuFactor:.85}),{refs:ve,state:we,transform:xe,selection:ke,utils:Se}=ge,{canvasRef:Ne,imageRef:Ee,selectionRef:$e}=ve,{cropData:_e,imageInfo:ze,canExport:Te,transformVersion:Ae}=we,Le=l(()=>ze||{naturalWidth:e.width||1920,naturalHeight:e.height||1080,currentWidth:e.width||1920,currentHeight:e.height||1080},[ze,e.width,e.height]),Ie=a(()=>N(e=>!e),[]),Pe=a(()=>$(e=>!e),[]),Me=a(()=>K(e=>!e),[]),De=a(()=>Q(e=>!e),[]),Oe=a(()=>Y(e=>!e),[]),Fe=a(()=>xe.center(),[xe]),je=a(()=>ke.center(),[ke]),Ue=a(()=>ke.reset(),[ke]),Be=a((e,t)=>xe.move(e,t),[xe]),We=a(e=>xe.zoom(e),[xe]),qe=a(e=>xe.rotate(e),[xe]),Ve=a(e=>{ke.setCoverage(e)},[ke]),He=a(()=>{W(e=>{const t=!e.horizontal;return xe.flipHorizontal(),{...e,horizontal:t}})},[xe]),Ke=a(()=>{W(e=>{const t=!e.vertical;return xe.flipVertical(),{...e,vertical:t}})},[xe]),Ge=a(()=>{if(!ge.manager||!we.isReady)return null;try{const e=_e?{..._e}:null;let t=null;if($e.current){const e=$e.current;t={x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0}}let n=null;if(Ee.current){const e=Ee.current.$getTransform?.();e&&Array.isArray(e)&&(n=[...e])}const l={cropData:e,selectorState:t,imageTransform:n,flipState:{horizontal:B.horizontal,vertical:B.vertical}};return te(e=>e.map((e,t)=>t===ne?{...e,savedState:l}:e)),l}catch(e){return console.warn("Error saving crop state:",e),null}},[ge.manager,we.isReady,_e,B,ne,Ee,$e]),Qe=a(e=>{const t=ee[e];if(t&&t.savedState)if(ge.manager&&we.isReady)try{const{savedState:e}=t;if(e.imageTransform&&Ee.current&&Array.isArray(e.imageTransform)&&setTimeout(()=>{if(Ee.current&&Ee.current.$setTransform){const[t,n,l,r,a,i]=e.imageTransform;Ee.current.$setTransform(t,n,l,r,a,i)}},100),e.selectorState&&$e.current){const{x:t,y:n,width:l,height:r}=e.selectorState;setTimeout(()=>{$e.current&&($e.current.x=t,$e.current.y=n,$e.current.width=l,$e.current.height=r,$e.current.$render&&$e.current.$render())},150)}e.flipState&&W({horizontal:e.flipState.horizontal??!1,vertical:e.flipState.vertical??!1})}catch(n){console.error("Error restoring crop state:",n),setTimeout(()=>{Fe(),setTimeout(()=>je(),100)},100)}else console.warn("Cropper not ready for state restoration");else setTimeout(()=>{Fe(),setTimeout(()=>je(),100)},100)},[ee,ge.manager,we.isReady,Fe,je,$e,Ee]),Xe=a(()=>{for(let e=0;e<ee.length;e++){const t=ee[e];if(!t.label||""===t.label.trim())return e}return-1},[ee]),Je=a(async e=>{e!==ne&&(U(!0),Ge(),await new Promise(e=>setTimeout(e,100)),le(e),await new Promise(e=>setTimeout(e,250)),Qe(e),await new Promise(e=>setTimeout(e,200)),U(!1))},[ne,Ge,Qe]),Ze=a(()=>{if(!Z.allowCustomCrops)return void alert("No se pueden añadir recortes personalizados en este modo.");const t={id:`crop-custom-${Date.now()}`,label:`Recorte ${ee.length+1}`,width:e.width||1920,height:e.height||1080,required:!1,isCustom:!0,confirmed:!1,savedState:null};te(e=>[...e,t]),me?.announce(`Nuevo recorte personalizado añadido: ${t.label}. Selecciónalo para editarlo.`)},[Z.allowCustomCrops,ee.length,e.width,e.height,me]),et=a((e,t)=>{const n=parseInt(t,10);""===t||isNaN(n)||te(t=>t.map((t,l)=>l===ne?{...t,[e]:n}:t))},[ne]),tt=a(e=>{const t=re[e];let n=100;if(Ne.current&&ze){const e=Ne.current.getBoundingClientRect(),t=Math.min(e.width,e.height);n=Math.max(100,Math.round(.05*t))}const l=Math.max(n,Math.min(3500,t));l!==t&&te(t=>t.map((t,n)=>n===ne?{...t,[e]:l}:t));const r={...re,[e]:l},a=r.width/r.height,i=ke.getData?.();ke.setAspectRatio(a),i&&void 0!==i.x&&setTimeout(()=>{ke.set?.(i.x,i.y,i.width,i.height)},50)},[ne,re,ke,Ne,ze]),nt=a(e=>{te(t=>t.map((t,n)=>n===ne?{...t,label:e}:t))},[ne]),lt=a((e,t=null)=>{t=t||ee[e].label;if(!window.confirm(`¿Estás seguro de que deseas eliminar "${t||"este recorte"}"? Esta acción también eliminará todos sus recortes.`))return;const n=ee[e];if(n.required)alert("No se puede eliminar un recorte obligatorio.");else if(1!==ee.length){if(te(t=>t.filter((t,n)=>n!==e)),e===ne){const t=Math.max(0,e-1);le(t)}else e<ne&&le(e=>e-1);me?.announce(`Recorte ${n.label} eliminado`)}else alert("Debe haber al menos un recorte.")},[ee,ne,me]),rt=a(async()=>{if(!Te)return null;try{const t=await ke.toCanvas({width:800,height:600,imageSmoothingEnabled:!0,imageSmoothingQuality:"high"});return t?t.toDataURL(`image/${globalThis.downloadFormat||e.mime_type.split("/")[1]||"webp"}`,.9):null}catch(t){return console.warn("Error generating preview:",t),null}},[Te,e.mime_type,ke]),at=a(async()=>{if(v)return y(!1),x(null),void C(!1);if(Te){y(!0),C(!0);try{const e=await rt();e?x(e):(y(!1),alert("No se puede exportar el recorte por restricciones de CORS en la imagen original."))}finally{C(!1)}}else alert("No se puede exportar el recorte por restricciones de CORS en la imagen original.")},[Te,rt,v]),it=a(e=>{e.target.closest(".limbo-preview-modal-header")&&(I(!0),M({x:e.clientX-T.x,y:e.clientY-T.y}))},[T]),ot=a(e=>{L&&(e.preventDefault(),A({x:e.clientX-P.x,y:e.clientY-P.y}))},[L,P]),st=a(()=>{I(!1)},[]),ct=a(e=>{if(!e.target.closest(".limbo-preview-modal-header"))return;const t=e.touches[0];I(!0),M({x:t.clientX-T.x,y:t.clientY-T.y})},[T]),ut=a(e=>{if(!L)return;e.preventDefault();const t=e.touches[0];A({x:t.clientX-P.x,y:t.clientY-P.y})},[L,P]),dt=a(()=>{I(!1)},[]);n(()=>{if(L)return document.addEventListener("mousemove",ot),document.addEventListener("mouseup",st),document.addEventListener("touchmove",ut,{passive:!1}),document.addEventListener("touchend",dt),()=>{document.removeEventListener("mousemove",ot),document.removeEventListener("mouseup",st),document.removeEventListener("touchmove",ut),document.removeEventListener("touchend",dt)}},[L,ot,st,ut,dt]),n(()=>{if(!D)return;const e=e=>{"Escape"===e.key&&R(!1)};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[D]);const bt=a(async(t,n=null)=>{const l=ee[t];if(!l)throw new Error(`Crop ${t} no encontrado`);if(!l.savedState&&t!==ne)throw new Error(`El recorte "${l.label}" aún no ha sido configurado`);const r={imageTransform:Ee.current?.$getTransform?.(),selectorState:$e.current?{x:$e.current.x,y:$e.current.y,width:$e.current.width,height:$e.current.height}:null};try{if(t!==ne&&l.savedState){if(l.savedState.imageTransform&&Ee.current?.$setTransform){const[e,t,n,r,a,i]=l.savedState.imageTransform;Ee.current.$setTransform(e,t,n,r,a,i)}if(l.savedState.selectorState&&$e.current?.$change){const{x:e,y:t,width:n,height:r}=l.savedState.selectorState;$e.current.$change(e,t,n,r,NaN,!0)}await new Promise(e=>setTimeout(e,100))}const r=Math.min(l.width,3500),i=Math.min(l.height,3500);let o=await ke.toCanvas({width:r,height:i,imageSmoothingEnabled:!0,imageSmoothingQuality:"high"});if(!o)throw new Error(`No se pudo generar el canvas para "${l.label}"`);if(o.width!==r||o.height!==i){const e=document.createElement("canvas");e.width=r,e.height=i;const t=e.getContext("2d");t.imageSmoothingEnabled=!0,t.imageSmoothingQuality="high",t.drawImage(o,0,0,r,i),o=e}const s=l.format||globalThis.downloadFormat||"webp",c="webp"===s?"image/webp":"png"===s?"image/png":"image/jpeg",u=.9,d=await new Promise((e,t)=>{o.toBlob(n=>{n?e(n):t(new Error("No se pudo convertir el canvas a blob"))},c,u)}),b=`${Re(l.label||"crop")}_${r}_${i}`,m=n||e.id,f=!m||"string"==typeof m&&m.startsWith("external"),g=(f||Z.localCropsOnly)&&!p;if(f&&p&&!Z.localCropsOnly)try{const e=new File([d],`${b}.${s}`,{type:c}),t=await p(e);if(t&&(t.id||t.url)){const e=l.savedState||{selectorState:$e.current?{x:$e.current.x,y:$e.current.y,width:$e.current.width,height:$e.current.height}:null,imageTransform:Ee.current?.$getTransform?.()||null,flipState:{horizontal:B.horizontal,vertical:B.vertical}},n={id:t.id||`uploaded-${Date.now()}`,name:b,filename:`${b}.${s}`,url:t.urlSigned||t.url,urlSigned:t.urlSigned||t.url,width:r,height:i,format:s,size:d.size,mime_type:c,isLocal:!1,originalAssetId:null,uploadedAssetId:t.id,cropState:e};return me?.announceSuccess(`Recorte guardado: ${b}`),n}}catch(a){console.error("[CropperView] ❌ Error subiendo crop, fallback a local:",a)}if(g){const e=URL.createObjectURL(d),t=l.savedState||{selectorState:$e.current?{x:$e.current.x,y:$e.current.y,width:$e.current.width,height:$e.current.height}:null,imageTransform:Ee.current?.$getTransform?.()||null,flipState:{horizontal:B.horizontal,vertical:B.vertical}},n={id:`local-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:b,filename:`${b}.${s}`,url:e,urlSigned:e,width:r,height:i,format:s,size:d.size,mime_type:c,blob:d,isLocal:!0,originalAssetId:m||null,cropState:t};return me?.announceSuccess(`Recorte creado localmente: ${b}`),n}const v=l.savedState||{selectorState:$e.current?{x:$e.current.x,y:$e.current.y,width:$e.current.width,height:$e.current.height}:null,imageTransform:Ee.current?.$getTransform?.()||null,flipState:{horizontal:B.horizontal,vertical:B.vertical}},y=await he(m,d,{name:b,width:r,height:i,format:s});if(y)return y.cropState=v,me?.announceSuccess(`Recorte creado: ${b}`),h?.(m,y),y;throw new Error("No se pudo crear la variante")}finally{if(t!==ne&&r.imageTransform&&Ee.current?.$setTransform){const[e,t,n,l,a,i]=r.imageTransform;if(Ee.current.$setTransform(e,t,n,l,a,i),r.selectorState&&$e.current?.$change){const{x:e,y:t,width:n,height:l}=r.selectorState;$e.current.$change(e,t,n,l,NaN,!0)}}}},[ee,ne,ke,he,e.id,h,me,Ee,$e]),mt=a(async()=>{if(!Te){const e="No se puede exportar el recorte por restricciones de CORS en la imagen original.";return me?.announceError(e),void alert(e)}if(!we.isReady){const e="El cropper aún no está inicializado. Espera un momento e inténtalo de nuevo.";return me?.announceError(e),void alert(e)}Ge(),me?.announce("Creando recorte de la imagen");try{let t=e.id,n=null;if(e.file&&p){me?.announce("Subiendo imagen...");const l=await p(e.file);if(!l||!l.id)throw new Error("No se pudo subir la imagen al servidor");t=l.id,n=l,me?.announceSuccess("Imagen subida correctamente")}const l=await bt(ne,t);l&&i(n?{crops:[l],asset:n}:l)}catch(t){console.warn("Error creating crop variant:",t);const e=t.message||"No se pudo crear el recorte. Inténtalo de nuevo.";me?.announceError(e),alert(e),b?.(t)}},[Te,we.isReady,me,Ge,bt,ne,i,b,e.file,e.id,p]),ht=a(async t=>{Ge(),me?.announce(`Guardando ${t.length} recortes...`);try{let l=e.id,r=null;if(e.file&&p){me?.announce("Subiendo imagen...");const t=await p(e.file);if(!t||!t.id)throw new Error("No se pudo subir la imagen al servidor");l=t.id,r=t,me?.announceSuccess("Imagen subida correctamente")}const a=[],o=[];for(const e of t)try{const t=await bt(e,l);t&&a.push(t)}catch(n){o.push({crop:ee[e]?.label||`Crop ${e}`,error:n.message})}if(a.length>0&&(me?.announceSuccess(`${a.length} recorte(s) guardado(s) correctamente`),i(r?{crops:a,asset:r}:a)),o.length>0){const e=`Errores al guardar algunos recortes:\n${o.map(e=>`- ${e.crop}: ${e.error}`).join("\n")}`;me?.announceError(e),alert(e)}}catch(n){const e=n.message||"Error al procesar los recortes";me?.announceError(e),alert(e),b?.(n)}},[Ge,bt,ee,me,i,e.file,e.id,p,b]),pt=a(async()=>{(re.width>3500||re.height>3500)&&alert("Las dimensiones máximas permitidas son 3500x3500 píxeles. Por favor, ajusta el tamaño del recorte."),re.width=Math.min(re.width,3500),re.height=Math.min(re.height,3500);const e=Xe();if(-1!==e){const t=ee[e];return alert(`El recorte "${t.label||t||"(sin nombre)"}" debe tener un nombre válido.`),void le(e)}const t=ee.findIndex((e,t)=>e.required&&!e.savedState&&t!==ne);if(-1!==t){const e=ee[t];return alert(`El recorte obligatorio "${e.label}" aún no ha sido configurado.\n\nPor favor, configura todos los recortes obligatorios antes de guardar.`),le(t),void me?.announce(`Recorte obligatorio "${e.label}" sin configurar. Por favor, configúralo.`,"assertive")}if(ee.length>1){be("save");const e=ee.map((e,t)=>({crop:e,index:t})).filter(({crop:e,index:t})=>e.required||e.savedState||t===ne).map(({index:e})=>e);return ue(e),void se(!0)}await mt()},[Xe,ee,mt,ne,me]),ft=a(async t=>{const n=ee[t];if(!n)throw new Error(`Crop ${t} no encontrado`);if(!n.savedState&&t!==ne)throw new Error(`El recorte "${n.label}" aún no ha sido configurado`);const l={imageTransform:Ee.current?.$getTransform?.(),selectorState:$e.current?{x:$e.current.x,y:$e.current.y,width:$e.current.width,height:$e.current.height}:null};try{if(t!==ne&&n.savedState){if(n.savedState.imageTransform&&Ee.current?.$setTransform){const[e,t,l,r,a,i]=n.savedState.imageTransform;Ee.current.$setTransform(e,t,l,r,a,i)}if(n.savedState.selectorState&&$e.current?.$change){const{x:e,y:t,width:l,height:r}=n.savedState.selectorState;$e.current.$change(e,t,l,r,NaN,!0)}await new Promise(e=>setTimeout(e,100))}const l=await ke.toCanvas({width:n.width,height:n.height,imageSmoothingEnabled:!0,imageSmoothingQuality:"high"});if(!l)throw new Error(`No se pudo generar el canvas para "${n.label}"`);const r=l.toDataURL(`image/${globalThis.downloadFormat||e.mime_type?.split("/")[1]||"webp"}`,.9),a=`${Re(n.label||"crop")}_${n.width}_${n.height}`;return await Al(r,a,{accessibilityManager:me,onSuccess:e=>{console.log(`✅ Descargado: ${e}`)},onError:e=>{throw new Error(`Error al descargar "${n.label}": ${e.message}`)}}),{crop:n.label,filename:a}}finally{if(t!==ne&&l.imageTransform&&Ee.current?.$setTransform){const[e,t,n,r,a,i]=l.imageTransform;if(Ee.current.$setTransform(e,t,n,r,a,i),l.selectorState&&$e.current?.$change){const{x:e,y:t,width:n,height:r}=l.selectorState;$e.current.$change(e,t,n,r,NaN,!0)}}}},[ee,ne,ke,e.mime_type,me,Ee,$e]),gt=a(async e=>{Ge(),me?.announce(`Descargando ${e.length} recortes...`);const t=[],n=[];for(const r of e)try{const e=await ft(r);e&&t.push(e)}catch(l){n.push({crop:ee[r]?.label||`Crop ${r}`,error:l.message})}if(t.length>0&&me?.announceSuccess(`${t.length} recorte(s) descargado(s) correctamente`),n.length>0){const e=`Errores al descargar algunos recortes:\n${n.map(e=>`- ${e.crop}: ${e.error}`).join("\n")}`;me?.announceError(e),alert(e)}},[Ge,ft,ee,me]),vt=a(async()=>{if(!Te){const e="No se puede descargar el recorte por restricciones de CORS en la imagen original.";return me?.announceError(e),void alert(e)}Ge(),me?.announce("Preparando descarga del recorte");try{await ft(ne),me?.announceSuccess("Recorte descargado correctamente")}catch(e){console.error("Error downloading crop:",e);const t=e.message||"Error al descargar el recorte";me?.announceError(t),alert(t)}},[Te,me,Ge,ft,ne]),yt=a(async()=>{const e=Xe();if(-1!==e){const t=ee[e];return alert(`El recorte "${t.label||t||"(sin nombre)"}" debe tener un nombre válido.`),void le(e)}if(ee.length>1){be("download");const e=ee.map((e,t)=>({crop:e,index:t})).filter(({crop:e,index:t})=>e.savedState||t===ne).map(({index:e})=>e);return ue(e),void se(!0)}await vt()},[Xe,ee,vt,ne]),wt=l(()=>!!e.file||(!e.id||!("string"!=typeof e.id||!e.id.startsWith("external"))),[e.file,e.id]),xt=a(async()=>{try{if(e.file&&p){me?.announce("Subiendo imagen original...");const t=await p(e.file);if(!t||!t.id)throw new Error("No se pudo subir la imagen al servidor");return me?.announceSuccess("Imagen guardada correctamente"),void i({asset:t,crops:[]})}if(wt){me?.announce("Conservando imagen original...");const t={id:`local-original-${Date.now()}`,name:e.filename||"original",filename:e.filename||"image.jpg",url:e.url,urlSigned:e.url,width:e.width||ze?.naturalWidth||1920,height:e.height||ze?.naturalHeight||1080,mime_type:e.mime_type||"image/jpeg",isLocal:!0,isOriginal:!0};return me?.announceSuccess("Imagen original conservada"),void i({crops:[t]})}if(e.id&&!e.id.startsWith("external")){me?.announce("Seleccionando imagen original...");const t={id:e.id,name:e.filename||"original",filename:e.filename||"image.jpg",url:e.url,urlSigned:e.urlSigned||e.url,width:e.width||ze?.naturalWidth||1920,height:e.height||ze?.naturalHeight||1080,mime_type:e.mime_type||"image/jpeg",isOriginal:!0};return me?.announceSuccess("Imagen original seleccionada"),void i({crops:[t],assetId:e.id})}o()}catch(t){console.error("Error guardando imagen original:",t);const e=t.message||"No se pudo guardar la imagen. Inténtalo de nuevo.";me?.announceError(e),alert(e),b?.(t)}},[e,ze,p,o,i,b,me,wt]);return n(()=>{y(!1),x(null)},[e]),n(()=>{if(!ge.manager||!we.isReady||!O)return;const e=Z.existingCrops?.[0],t=e?.cropState;setTimeout(()=>{Fe(),setTimeout(()=>{if(t){if(t.imageTransform&&Ee.current?.$setTransform){const[e,n,l,r,a,i]=t.imageTransform;Ee.current.$setTransform(e,n,l,r,a,i)}if(t.selectorState&&$e.current){const{x:e,y:n,width:l,height:r}=t.selectorState;$e.current.x=e,$e.current.y=n,$e.current.width=l,$e.current.height=r,$e.current.$render?.()}t.flipState&&W(t.flipState)}else je();F(!1)},100)},50)},[ge.manager,we.isReady,O,Fe,je,Z.existingCrops]),n(()=>{ge.manager&&we.isReady&&(ae&&ke.setAspectRatio(ae),Se.setBackground(E))},[ae,E,ge.manager,we.isReady,ke,Se]),n(()=>{if(!ze||!we.isReady||Z.mandatoryCrops.length>0)return;const e=ee[0];if(e&&"crop-default-0"===e.id&&(1920===e.width||1080===e.height)){const t=Math.min(ze.naturalWidth,3500),n=Math.min(ze.naturalHeight,3500);te([{...e,width:t,height:n}])}},[ze,we.isReady,Z.mandatoryCrops.length,ee]),n(()=>{if(!v||!Te)return;const e=setTimeout(async()=>{C(e=>!w&&!e||e);try{const e=await rt();e&&x(e)}finally{C(!1)}},300);return()=>{clearTimeout(e),C(!1)}},[_e,Ae,v,Te,rt,ae,B,w]),n(()=>{const e=Ne.current,t=t=>{if("Delete"===t.key||"Backspace"===t.key||"Backspace"===t.key&&t.metaKey||"Backspace"===t.key&&t.ctrlKey){const n=t.target;if(e&&(n===e||n===document.body||n===document.documentElement||"CROPPER-CANVAS"===n.tagName||"CROPPER-SELECTION"===n.tagName||"CROPPER-IMAGE"===n.tagName||"CROPPER-HANDLE"===n.tagName||"CROPPER-GRID"===n.tagName||n.closest("cropper-canvas")||e.contains(n)))return t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),!1}};return document.addEventListener("keydown",t,!0),document.addEventListener("keyup",t,!0),window.addEventListener("keydown",t,!0),e&&e.addEventListener("keydown",t,!0),()=>{document.removeEventListener("keydown",t,!0),document.removeEventListener("keyup",t,!0),window.removeEventListener("keydown",t,!0),e&&e.removeEventListener("keydown",t,!0)}},[Ne]),e?/* @__PURE__ */c("div",{className:"limbo-cropper-view lb:px-2 lb:border-2 lb:border-gray-200/50 lb:rounded-lg lb:max-w-7xl lb:mx-auto lb:w-full lb:min-w-full lb:h-full lb:min-h-full lb:flex lb:flex-col",children:[
|
|
451
451
|
/* @__PURE__ */c("div",{className:"limbo-cropper-header lb:flex lb:flex-row lb:justify-between lb:items-start lb:flex-wrap lb:mx-2 lb:py-2 lb:border-b lb:border-gray-200 lb:bg-white lb:z-10 lb:shrink-0 lb:lg:gap-2",children:[
|
|
452
452
|
/* @__PURE__ */c("div",{className:"lb:flex-1 lb:min-w-fit lb:space-y-2 lb:max-w-fit",children:[
|
|
453
453
|
/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-2",children:[
|
|
@@ -455,28 +455,28 @@ return c("div",{children:[l&&/* @__PURE__ */s(ct,{text:"Subiendo archivo..."}),r
|
|
|
455
455
|
/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-2",children:[
|
|
456
456
|
/* @__PURE__ */s("label",{className:"lb:text-xs lb:text-gray-500 lb:whitespace-nowrap lb:w-fit",children:"Nombre:"}),
|
|
457
457
|
/* @__PURE__ */s("div",{className:"",children:J+"."+(globalThis.downloadFormat||e.mime_type.split("/")[1]||"webp")})]})]}),
|
|
458
|
-
/* @__PURE__ */s("div",{className:"lb:flex lb:flex-row lb:self-end lb:gap-2 lb:w-full lb:max-w-fit lb:sm:w-auto lb:flex-wrap",children:/* @__PURE__ */c("button",{onClick:()=>{window.confirm("Si cancelas, perderás todos los cambios realizados. ¿Deseas continuar?")&&o()},disabled:
|
|
458
|
+
/* @__PURE__ */s("div",{className:"lb:flex lb:flex-row lb:self-end lb:gap-2 lb:w-full lb:max-w-fit lb:sm:w-auto lb:flex-wrap",children:/* @__PURE__ */c("button",{onClick:()=>{window.confirm("Si cancelas, perderás todos los cambios realizados. ¿Deseas continuar?")&&o()},disabled:pe,className:"lb:flex lb:flex-row lb:items-center lb:gap-1 lb:self-end lb:w-full lb:max-w-fit lb:sm:w-auto lb:px-3 lb:cursor-pointer lb:py-1.5 lb:text-sm lb:rounded lb:bg-neutral-gray-500 lb:hover:bg-neutral-gray-700 lb:transition-colors lb:text-white lb:disabled:opacity-50 lb:disabled:cursor-not-allowed","aria-label":"Cancelar y volver",title:"Cancelar y volver",children:[
|
|
459
459
|
/* @__PURE__ */s("span",{className:"icon icon-arrow-left-white icon--sm lb:m-0 lb:p-0"})," ","Volver"]})})]}),
|
|
460
|
-
/* @__PURE__ */c("div",{className:"limbo-cropper-status lb:bg-white lb:border-gray-100 lb:py-0 lb:pb-0 lb:flex-shrink-0",children:[
|
|
461
|
-
/* @__PURE__ */s("strong",{children:"Error:"})," ",
|
|
462
|
-
/* @__PURE__ */s("strong",{children:"Original:"})," ",ze.naturalWidth," ×"," ",ze.naturalHeight," px",ze.currentWidth!==ze.naturalWidth&&/* @__PURE__ */c("span",{className:"lb:ml-2 lb:sm:ml-3 lb:text-xs lb:block lb:sm:inline",children:["(Mostrada: ",Math.round(ze.currentWidth)," ×"," ",Math.round(ze.currentHeight)," px)"]})]}),!Te&&/* @__PURE__ */s(
|
|
460
|
+
/* @__PURE__ */c("div",{className:"limbo-cropper-status lb:bg-white lb:border-gray-100 lb:py-0 lb:pb-0 lb:flex-shrink-0",children:[fe&&/* @__PURE__ */c(ye,{variant:"danger",className:"lb:mb-2 lb:text-sm",children:[
|
|
461
|
+
/* @__PURE__ */s("strong",{children:"Error:"})," ",fe]}),ze&&/* @__PURE__ */c(ye,{variant:"info",className:"lb:mb-2 lb:text-sm",role:"status",children:[
|
|
462
|
+
/* @__PURE__ */s("strong",{children:"Original:"})," ",ze.naturalWidth," ×"," ",ze.naturalHeight," px",ze.currentWidth!==ze.naturalWidth&&/* @__PURE__ */c("span",{className:"lb:ml-2 lb:sm:ml-3 lb:text-xs lb:block lb:sm:inline",children:["(Mostrada: ",Math.round(ze.currentWidth)," ×"," ",Math.round(ze.currentHeight)," px)"]})]}),!Te&&/* @__PURE__ */s(ye,{variant:"warning",className:"lb:mb-2 lb:text-sm",children:"No se puede exportar por restricciones CORS"}),
|
|
463
463
|
/* @__PURE__ */c("div",{className:"lb:bg-white lb:border-b lb:border-gray-200 lb:py-2 lb:mx-2 lb:shrink-0 lb:sticky lb:top-0 lb:z-10 lb:mb-1",children:[
|
|
464
464
|
/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:justify-between lb:mb-2",children:[
|
|
465
|
-
/* @__PURE__ */c("h3",{className:"lb:text-sm lb:font-semibold lb:text-gray-700",children:["Recortes ",ee.length>1&&`(${ee.length})`]}),Z.allowCustomCrops&&/* @__PURE__ */c("button",{onClick:Ze,disabled:
|
|
465
|
+
/* @__PURE__ */c("h3",{className:"lb:text-sm lb:font-semibold lb:text-gray-700",children:["Recortes ",ee.length>1&&`(${ee.length})`]}),Z.allowCustomCrops&&/* @__PURE__ */c("button",{onClick:Ze,disabled:pe,className:"lb:text-xs lb:cursor-pointer lb:px-2 lb:py-1 lb:bg-brand-blue-50 lb:hover:bg-brand-blue-200 lb:text-brand-blue-1000 lb:rounded lb:border lb:border-brand-blue-200 lb:transition-colors lb:flex lb:items-center lb:gap-1",title:"Añadir recorte personalizado",children:[
|
|
466
466
|
/* @__PURE__ */s("span",{className:"icon icon-add icon--sm",style:{filter:"var(--limbo-icon-blue)"}}),"Añadir recorte"]})]}),
|
|
467
467
|
/* @__PURE__ */s("div",{className:"lb:grid lb:grid-cols-2 lb:md:grid-cols-3 lb:lg:grid-cols-4 lb:xl:grid-cols-5 lb:gap-1.5 lb:max-h-48 lb:overflow-y-auto",children:ee.map((e,t)=>{const n=e.savedState||t===ne;/* @__PURE__ */
|
|
468
468
|
return c("label",{className:"lb:h-fit lb:flex lb:flex-col lb:p-1.5 lb:rounded lb:border lb:cursor-pointer lb:transition-colors lb:min-h-17.5 lb:w-full "+(ne===t?"lb:bg-blue-50 lb:border-blue-300":n?"lb:bg-gray-50 lb:border-gray-200 lb:hover:bg-gray-100":"lb:bg-orange-50 lb:border-orange-300 lb:hover:bg-orange-100"),children:[
|
|
469
|
-
/* @__PURE__ */s("input",{type:"radio",name:"active-crop",checked:ne===t,onChange:()=>Je(t),disabled:
|
|
469
|
+
/* @__PURE__ */s("input",{type:"radio",name:"active-crop",checked:ne===t,onChange:()=>Je(t),disabled:pe,className:"lb:hidden"}),
|
|
470
470
|
/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-1 lb:mb-1",children:[
|
|
471
|
-
/* @__PURE__ */s("div",{className:"lb:flex-1 lb:min-w-0",children:/* @__PURE__ */c("div",{className:"lb:flex lb:flex-wrap lb:items-center lb:gap-1 lb:min-h-",children:[ne!==t||e.required?/* @__PURE__ */s("span",{className:"lb:text-xs lb:font-medium lb:text-gray-800 lb:truncate",children:e.label}):/* @__PURE__ */s("input",{type:"text",value:e.label,onChange:e=>nt(e.target.value),disabled:
|
|
471
|
+
/* @__PURE__ */s("div",{className:"lb:flex-1 lb:min-w-0",children:/* @__PURE__ */c("div",{className:"lb:flex lb:flex-wrap lb:items-center lb:gap-1 lb:min-h-",children:[ne!==t||e.required?/* @__PURE__ */s("span",{className:"lb:text-xs lb:font-medium lb:text-gray-800 lb:truncate",children:e.label}):/* @__PURE__ */s("input",{type:"text",value:e.label,onChange:e=>nt(e.target.value),disabled:pe,className:"lb:w-full lb:max-h-fit lb:text-xs lb:px-1 lb:py-0.5 lb:border lb:border-gray-300 lb:rounded lb:focus:outline-none lb:focus:ring-1 lb:focus:ring-blue-500 lb:h-1",placeholder:"Nombre",maxLength:25,onClick:e=>e.stopPropagation()}),e.required&&/* @__PURE__ */s("span",{className:"lb:text-[10px] lb:px-1 lb:py-0.5 lb:bg-red-200 lb:text-red-1000 lb:rounded lb:whitespace-nowrap lb:truncate",children:"Obligatorio"})]})}),!e.required&&ee.length>1&&/* @__PURE__ */s("button",{onClick:n=>{n.preventDefault(),n.stopPropagation(),lt(t,e.label)},className:"lb:shrink-0 lb:hover:bg-red-500/70 lb:text-red-1000 lb:p-1 lb:rounded lb:max-h-fit lb:aspect-square lb:cursor-pointer lb:flex",title:"Eliminar",children:/* @__PURE__ */s("span",{className:"icon icon-close-small icon--xs"})})]}),
|
|
472
472
|
/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:gap-1 lb:mt-auto",children:ne===t?/* @__PURE__ */c(u,{children:[
|
|
473
|
-
/* @__PURE__ */s("input",{type:"number",min:"100",max:"3500",value:Math.min(e.width,3500),onChange:e=>et("width",e.target.value),onBlur:()=>tt("width"),disabled:
|
|
473
|
+
/* @__PURE__ */s("input",{type:"number",min:"100",max:"3500",value:Math.min(e.width,3500),onChange:e=>et("width",e.target.value),onBlur:()=>tt("width"),disabled:pe||e.lockDimensions,className:"lb:max-h-fit lb:flex-1 lb:text-xs lb:px-1 lb:py-0.5 lb:border lb:rounded lb:focus:outline-none lb:focus:ring-1 lb:focus:ring-blue-500 "+(e.lockDimensions?"lb:border-gray-200 lb:bg-gray-100 lb:text-gray-500 lb:cursor-not-allowed":"lb:border-gray-300"),placeholder:"Ancho",onClick:e=>e.stopPropagation(),title:e.lockDimensions?"Dimensiones bloqueadas (recorte obligatorio)":"Ancho en píxeles"}),
|
|
474
474
|
/* @__PURE__ */s("span",{className:"lb:text-gray-400 lb:text-xs",children:"×"}),
|
|
475
|
-
/* @__PURE__ */s("input",{type:"number",min:"100",max:"3500",value:Math.min(e.height,3500),onChange:e=>et("height",e.target.value),onBlur:()=>tt("height"),disabled:
|
|
475
|
+
/* @__PURE__ */s("input",{type:"number",min:"100",max:"3500",value:Math.min(e.height,3500),onChange:e=>et("height",e.target.value),onBlur:()=>tt("height"),disabled:pe||e.lockDimensions,className:"lb:max-h-fit lb:flex-1 lb:text-xs lb:px-1 lb:py-0.5 lb:border lb:rounded lb:focus:outline-none lb:focus:ring-1 lb:focus:ring-blue-500 "+(e.lockDimensions?"lb:border-gray-200 lb:bg-gray-100 lb:text-gray-500 lb:cursor-not-allowed":"lb:border-gray-300"),placeholder:"Alto",onClick:e=>e.stopPropagation(),title:e.lockDimensions?"Dimensiones bloqueadas (recorte obligatorio)":"Alto en píxeles"})]}):/* @__PURE__ */c("span",{className:"lb:text-xs lb:text-gray-500",children:[e.width," × ",e.height," px"]})}),!n&&/* @__PURE__ */s("div",{className:"lb:text-xs lb:px-1 lb:py-0.5 lb:bg-orange-300 lb:text-neutral-gray-25 lb:text-shadow-xs lb:font-semibold lb:rounded lb:text-center lb:mt-1",children:"Sin configurar"})]},e.id)})})]})]}),
|
|
476
476
|
/* @__PURE__ */c("div",{className:"lb:flex lb:flex-col lb:lg:flex-row lb:flex-1 lb:w-full lb:overflow-hidden lb:lg:max-h-130 lb:mx-2 lb:py-1",children:[
|
|
477
477
|
/* @__PURE__ */s("div",{className:"lb:relative lb:flex-1 lg:flex-2 lb:h-full lb:shrink-0 lb:grow-1 lb:order-0 lb:min-h-100 lb:lg:min-h-130",children:/* @__PURE__ */c("div",{className:"lb:absolute lb:inset-0 lb:bg-white lb:rounded-lg lb:border-2 lb:border-gray-200 lb:overflow-hidden",children:[
|
|
478
|
-
/* @__PURE__ */s(
|
|
479
|
-
/* @__PURE__ */s(
|
|
478
|
+
/* @__PURE__ */s(_t,{show:O,message:"Cargando recortador..."}),
|
|
479
|
+
/* @__PURE__ */s(_t,{show:j,message:`Cambiando a: ${ee[ne]?.label||"recorte"}...`}),
|
|
480
480
|
/* @__PURE__ */c("cropper-canvas",{ref:Ne,style:{width:"100%",height:"100%",display:"block"},background:!!E||void 0,id:"limbo-cropperjs-canvas",tabindex:"-1",onKeyDown:e=>{"Delete"!==e.key&&"Backspace"!==e.key||(e.preventDefault(),e.stopPropagation())},children:[
|
|
481
481
|
/* @__PURE__ */s("cropper-image",{ref:Ee,src:_,alt:e.filename,id:"limbo-cropperjs-image",action:"move",crossOrigin:"anonymous",rotatable:!0,scalable:!0,skewable:!0,translatable:!0}),
|
|
482
482
|
/* @__PURE__ */c("cropper-selection",{ref:$e,"initial-coverage":"0.5",movable:!0,resizable:!0,keyboard:"true",action:"move",style:{cursor:"move",minWidth:`${ie.minWidth}px`,minHeight:`${ie.minHeight}px`},"data-prevent-delete":"true",tabindex:"-1",children:[S&&/* @__PURE__ */s("cropper-grid",{role:"grid",action:"move",covered:!0,bordered:!0}),
|
|
@@ -496,49 +496,49 @@ return c("label",{className:"lb:h-fit lb:flex lb:flex-col lb:p-1.5 lb:rounded lb
|
|
|
496
496
|
/* @__PURE__ */s("div",{className:"lb:text-center",children:/* @__PURE__ */s("span",{className:`icon ${X?"icon-chevron-up":"icon-chevron-down"} lb:text-center icon--xs`})})]})}),
|
|
497
497
|
/* @__PURE__ */c("div",{className:"lb:p-2 lb:space-y-2 lb:justify-items-stretch lb:static "+(X?"lb:block":"lb:sm:hidden"),children:[
|
|
498
498
|
/* @__PURE__ */s("div",{className:"lb:mb-3 lb:block",children:/* @__PURE__ */c("div",{className:"lb:grid lb:grid-cols-5 lb:gap-1 lb:content-center lb:h-fit lb:mx-auto",children:[
|
|
499
|
-
/* @__PURE__ */s("button",{onClick:()=>We(-.2),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Alejar",disabled:
|
|
500
|
-
/* @__PURE__ */s("button",{onClick:()=>Be(-10,-10),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Mover arriba-izquierda",disabled:
|
|
501
|
-
/* @__PURE__ */s("button",{onClick:()=>Be(0,-10),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Mover arriba",disabled:
|
|
502
|
-
/* @__PURE__ */s("button",{onClick:()=>Be(10,-10),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Mover arriba-derecha",disabled:
|
|
503
|
-
/* @__PURE__ */s("button",{onClick:()=>We(.2),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Acercar 20%",disabled:
|
|
504
|
-
/* @__PURE__ */s("button",{onClick:()=>qe(-45),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Rotar -45°",disabled:
|
|
505
|
-
/* @__PURE__ */s("button",{onClick:()=>Be(-10,0),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Mover izquierda",disabled:
|
|
506
|
-
/* @__PURE__ */s("button",{onClick:Fe,className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Centrar y ajustar imagen",disabled:
|
|
507
|
-
/* @__PURE__ */s("button",{onClick:()=>Be(10,0),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Mover derecha",disabled:
|
|
508
|
-
/* @__PURE__ */s("button",{onClick:()=>qe(45),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Rotar +45°",disabled:
|
|
509
|
-
/* @__PURE__ */s("button",{onClick:
|
|
510
|
-
/* @__PURE__ */s("button",{onClick:()=>Be(-10,10),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Mover abajo-izquierda",disabled:
|
|
511
|
-
/* @__PURE__ */s("button",{onClick:()=>Be(0,10),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Mover abajo",disabled:
|
|
512
|
-
/* @__PURE__ */s("button",{onClick:()=>Be(10,10),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Mover abajo-derecha",disabled:
|
|
513
|
-
/* @__PURE__ */s("button",{onClick:
|
|
514
|
-
/* @__PURE__ */s("div",{className:"lb:flex lb:flex-col lb:gap-2",children:/* @__PURE__ */s("button",{onClick:()=>{
|
|
499
|
+
/* @__PURE__ */s("button",{onClick:()=>We(-.2),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Alejar",disabled:pe,"aria-label":"Alejar imagen",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-zoom-out-blue"})})}),
|
|
500
|
+
/* @__PURE__ */s("button",{onClick:()=>Be(-10,-10),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Mover arriba-izquierda",disabled:pe,"aria-label":"Mover imagen hacia arriba-izquierda",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-arrow-up-blue icon--md lb:-rotate-45"})})}),
|
|
501
|
+
/* @__PURE__ */s("button",{onClick:()=>Be(0,-10),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Mover arriba",disabled:pe,"aria-label":"Mover imagen hacia arriba",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-arrow-up-blue icon--md"})})}),
|
|
502
|
+
/* @__PURE__ */s("button",{onClick:()=>Be(10,-10),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Mover arriba-derecha",disabled:pe,"aria-label":"Mover imagen hacia arriba-derecha",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-arrow-up-blue icon--md lb:rotate-45"})})}),
|
|
503
|
+
/* @__PURE__ */s("button",{onClick:()=>We(.2),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Acercar 20%",disabled:pe,"aria-label":"Acercar imagen",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-zoom-in-blue"})})}),
|
|
504
|
+
/* @__PURE__ */s("button",{onClick:()=>qe(-45),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Rotar -45°",disabled:pe,"aria-label":"Rotar imagen 45 grados a la izquierda",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"lb:text-brand-blue-1000 lb:font-medium",children:"-45°"})})}),
|
|
505
|
+
/* @__PURE__ */s("button",{onClick:()=>Be(-10,0),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Mover izquierda",disabled:pe,"aria-label":"Mover imagen hacia la izquierda",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-arrow-left-blue"})})}),
|
|
506
|
+
/* @__PURE__ */s("button",{onClick:Fe,className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Centrar y ajustar imagen",disabled:pe,"aria-label":"Centrar y ajustar imagen",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-radio-button-blue icon-md"})})}),
|
|
507
|
+
/* @__PURE__ */s("button",{onClick:()=>Be(10,0),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Mover derecha",disabled:pe,"aria-label":"Mover imagen hacia la derecha",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-arrow-right-blue"})})}),
|
|
508
|
+
/* @__PURE__ */s("button",{onClick:()=>qe(45),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Rotar +45°",disabled:pe,"aria-label":"Rotar imagen 45 grados a la derecha",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"lb:text-brand-blue-1000 lb:font-medium",children:"+45°"})})}),
|
|
509
|
+
/* @__PURE__ */s("button",{onClick:He,className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:aspect-square "+(B.horizontal?"lb:bg-blue-100 lb:border lb:border-blue-300 lb:text-blue-800":"lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200"),title:"Voltear horizontalmente "+(B.horizontal?"(activo)":""),disabled:pe,"aria-label":"Voltear imagen horizontalmente","aria-pressed":B.horizontal,children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center lb:gap-2",children:/* @__PURE__ */s("span",{className:"icon icon-arrow-left-right-blue lb:border lb:border-brand-blue-1000 lb:rounded"})})}),
|
|
510
|
+
/* @__PURE__ */s("button",{onClick:()=>Be(-10,10),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Mover abajo-izquierda",disabled:pe,"aria-label":"Mover imagen hacia abajo-izquierda",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-arrow-up-blue icon--md lb:-rotate-145"})})}),
|
|
511
|
+
/* @__PURE__ */s("button",{onClick:()=>Be(0,10),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Mover abajo",disabled:pe,"aria-label":"Mover imagen hacia abajo",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-arrow-down-blue"})})}),
|
|
512
|
+
/* @__PURE__ */s("button",{onClick:()=>Be(10,10),className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200 lb:aspect-square",title:"Mover abajo-derecha",disabled:pe,"aria-label":"Mover imagen hacia abajo-derecha",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-arrow-up-blue icon--md lb:rotate-145"})})}),
|
|
513
|
+
/* @__PURE__ */s("button",{onClick:Ke,className:"lb:px-0 lb:rounded lb:cursor-pointer lb:transition-colors lb:aspect-square lb:text-sm "+(B.vertical?"lb:bg-blue-100 lb:border lb:border-blue-300 lb:text-blue-800":"lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200"),title:"Voltear verticalmente "+(B.vertical?"(activo)":""),disabled:pe,"aria-label":"Voltear imagen verticalmente","aria-pressed":B.vertical,children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{className:"icon icon-arrow-up-down-blue lb:border lb:border-brand-blue-1000 lb:rounded"})})})]})}),
|
|
514
|
+
/* @__PURE__ */s("div",{className:"lb:flex lb:flex-col lb:gap-2",children:/* @__PURE__ */s("button",{onClick:()=>{xe.reset(),W({horizontal:!1,vertical:!1})},className:"lb:w-full lb:p-2 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200",title:"Reiniciar transformaciones",disabled:pe,"aria-label":"Reiniciar todas las transformaciones de la imagen",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */c("span",{children:[
|
|
515
515
|
/* @__PURE__ */s("span",{className:"icon icon-refresh-blue icon--sm lb:align-[middle!important] "})," ","Reiniciar ajustes"]})})})})]})]}),
|
|
516
516
|
/* @__PURE__ */c("div",{className:"lb:bg-white lb:rounded lb:border lb:border-gray-200 lb:w-full"+(G?"":" lb:bg-neutral-gray-50/50"),children:[
|
|
517
|
-
/* @__PURE__ */s("button",{onClick:
|
|
517
|
+
/* @__PURE__ */s("button",{onClick:De,className:"lb:hidden lb:sm:block lb:w-full lb:cursor-pointer lb:hover:bg-neutral-gray-050/50 lb:p-2 lb:mb-05 lb:transition-colors lb:rounded-t-sm","aria-expanded":G,"aria-label":"Mostrar/ocultar opciones de visualizción",children:/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:justify-between",children:[
|
|
518
518
|
/* @__PURE__ */s("h3",{className:"lb:text-sm lb:font-semibold lb:text-gray-700",children:"Ajustes del selector"}),
|
|
519
519
|
/* @__PURE__ */s("div",{className:"lb:text-center",children:/* @__PURE__ */s("span",{className:`icon ${G?"icon-chevron-up":"icon-chevron-down"} lb:text-center icon--xs`})})]})}),
|
|
520
520
|
/* @__PURE__ */c("div",{className:"lb:p-2 lb:space-y-2 lb:justify-items-stretch lb:static "+(G?"lb:block":"lb:sm:hidden"),children:[
|
|
521
521
|
/* @__PURE__ */s("div",{children:/* @__PURE__ */c("div",{className:"lb:grid lb:grid-cols-2 lb:gap-2",children:[
|
|
522
|
-
/* @__PURE__ */s("button",{onClick:()=>Ve(.5),className:"lb:p-1 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-xs lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200",disabled:
|
|
523
|
-
/* @__PURE__ */s("button",{onClick:()=>Ve(.7),className:"lb:p-1 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-xs lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200",disabled:
|
|
524
|
-
/* @__PURE__ */s("button",{onClick:()=>Ve(.9),className:"lb:p-1 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-xs lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200",disabled:
|
|
525
|
-
/* @__PURE__ */s("button",{onClick:()=>Ve(1),className:"lb:p-1 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-xs lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200",disabled:
|
|
522
|
+
/* @__PURE__ */s("button",{onClick:()=>Ve(.5),className:"lb:p-1 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-xs lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200",disabled:pe,"aria-label":"Selección 50%",title:"Tamaño de selector 50%",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{children:"50%"})})}),
|
|
523
|
+
/* @__PURE__ */s("button",{onClick:()=>Ve(.7),className:"lb:p-1 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-xs lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200",disabled:pe,"aria-label":"Selección 70%",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{children:"70%"})})}),
|
|
524
|
+
/* @__PURE__ */s("button",{onClick:()=>Ve(.9),className:"lb:p-1 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-xs lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200",disabled:pe,"aria-label":"Selección 90%",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{children:"90%"})})}),
|
|
525
|
+
/* @__PURE__ */s("button",{onClick:()=>Ve(1),className:"lb:p-1 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-xs lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200",disabled:pe,"aria-label":"Selección completa",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */s("span",{children:"100%"})})})]})}),
|
|
526
526
|
/* @__PURE__ */c("div",{className:"lb:space-y-2 lb:pt-2",children:[
|
|
527
|
-
/* @__PURE__ */s("button",{onClick:je,className:"lb:w-full lb:p-1 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200",title:"Centrar selección",disabled:
|
|
527
|
+
/* @__PURE__ */s("button",{onClick:je,className:"lb:w-full lb:p-1 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200",title:"Centrar selección",disabled:pe,"aria-label":"Centrar área de selección",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */c("span",{children:[
|
|
528
528
|
/* @__PURE__ */s("span",{className:"icon icon-radio-button icon--sm lb:align-[middle!important] "})," ","Centrar selección"]})})}),
|
|
529
|
-
/* @__PURE__ */s("button",{onClick:Ue,className:"lb:w-full lb:p-1 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200",title:"Reiniciar selección",disabled:
|
|
529
|
+
/* @__PURE__ */s("button",{onClick:Ue,className:"lb:w-full lb:p-1 lb:rounded lb:cursor-pointer lb:transition-colors lb:text-sm lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200",title:"Reiniciar selección",disabled:pe,"aria-label":"Reiniciar área de selección",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center",children:/* @__PURE__ */c("span",{children:[
|
|
530
530
|
/* @__PURE__ */s("span",{className:"icon icon-refresh icon--sm lb:align-[middle!important]"})," ","Reset selección"]})})})]})]})]}),
|
|
531
531
|
/* @__PURE__ */c("div",{className:"lb:bg-white lb:rounded lb:border lb:border-gray-200 lb:w-full",children:[
|
|
532
|
-
/* @__PURE__ */s("button",{onClick:
|
|
532
|
+
/* @__PURE__ */s("button",{onClick:Me,className:"lb:hidden lb:sm:block lb:w-full lb:cursor-pointer lb:hover:bg-neutral-gray-050/50 lb:transition-colors lb:rounded-t-sm lb:mb-05 lb:p-2","aria-expanded":H,"aria-label":"Mostrar/ocultar opciones de visualización",children:/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:justify-between",children:[
|
|
533
533
|
/* @__PURE__ */s("h3",{className:"lb:text-sm lb:font-semibold lb:text-gray-700",children:"Visualización"}),
|
|
534
534
|
/* @__PURE__ */s("div",{className:"lb:text-center",children:/* @__PURE__ */s("span",{className:`icon ${H?"icon-chevron-up":"icon-chevron-down"} lb:text-center icon--xs`})})]})}),
|
|
535
535
|
/* @__PURE__ */c("div",{className:"lb:py-2 lb:space-y-2 lb:justify-items-stretch lb:static "+(H?"lb:block":"lb:sm:hidden"),children:[
|
|
536
|
-
/* @__PURE__ */c("button",{onClick:
|
|
536
|
+
/* @__PURE__ */c("button",{onClick:Ie,className:"lb:w-auto lb:flex lb:cursor-pointer lb:items-center lb:justify-between lb:mx-2 lb:p-1 lb:rounded lb:transition-colors "+(S?"lb:bg-blue-100 lb:border lb:border-blue-300 lb:text-blue-800":"lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200"),disabled:pe,"aria-pressed":S,title:"Mostrar/ocultar cuadrícula de la regla de los tercios en el selector","aria-label":"Activar/desactivar grid",children:[
|
|
537
537
|
/* @__PURE__ */c("span",{className:"lb:text-sm lb:flex lb:items-center",children:[
|
|
538
538
|
/* @__PURE__ */s("span",{className:"icon icon-area-blue lb:me-1"})," ","Cuadrícula"]}),
|
|
539
539
|
/* @__PURE__ */s("span",{className:"lb:text-xs",children:S?/* @__PURE__ */c(u,{children:[
|
|
540
540
|
/* @__PURE__ */s("span",{className:"icon icon-tick icon--xs lb:align-[middle!important] lb:-mt-0.5"})," ","Activo"]}):"Inactivo"})]}),
|
|
541
|
-
/* @__PURE__ */c("button",{onClick:
|
|
541
|
+
/* @__PURE__ */c("button",{onClick:Pe,className:"lb:w-auto lb:flex lb:cursor-pointer lb:items-center lb:justify-between lb:mx-2 lb:p-1 lb:rounded lb:transition-colors "+(E?"lb:bg-blue-100 lb:border lb:border-blue-300 lb:text-blue-800":"lb:bg-gray-100 lb:border lb:border-gray-300 lb:text-gray-700 lb:hover:bg-gray-200"),disabled:pe,"aria-pressed":E,"aria-label":"Activar/desactivar sombreado",children:[
|
|
542
542
|
/* @__PURE__ */c("span",{className:"lb:text-sm lb:flex lb:items-center",children:[
|
|
543
543
|
/* @__PURE__ */s("span",{className:"icon icon-comparison-blue lb:me-1"})," ","Tablero"]}),
|
|
544
544
|
/* @__PURE__ */s("span",{className:"lb:text-xs",children:E?/* @__PURE__ */c(u,{children:[
|
|
@@ -548,16 +548,16 @@ return c("label",{className:"lb:h-fit lb:flex lb:flex-col lb:p-1.5 lb:rounded lb
|
|
|
548
548
|
/* @__PURE__ */s("span",{className:"icon icon-lightbulb lb:text-yellow-500"}),
|
|
549
549
|
/* @__PURE__ */s("span",{className:"lb:text-sm lb:font-semibold lb:text-blue-800",children:"Guía de uso"}),
|
|
550
550
|
/* @__PURE__ */s("span",{className:"icon icon-arrow-down lb:scale-75 lb:-rotate-145"})]}),
|
|
551
|
-
/* @__PURE__ */s("button",{onClick:at,disabled:
|
|
551
|
+
/* @__PURE__ */s("button",{onClick:at,disabled:pe||!Te,className:`lb:px-3 lb:cursor-pointer lb:py-1.5 lb:text-sm lb:rounded lb:transition-colors ${v?"lb:bg-red-1000 lb:hover:bg-red-800 lb:text-white":"lb:bg-brand-blue-800 lb:hover:bg-brand-blue-1000 lb:text-white"} lb:disabled:opacity-50 lb:disabled:cursor-not-allowed`,"aria-label":"Vista previa",title:"Mostrar/Ocultar vista previa",children:/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-1",children:[
|
|
552
552
|
/* @__PURE__ */s("span",{className:"icon icon-search-white icon--sm"}),
|
|
553
553
|
/* @__PURE__ */s("span",{className:"lb:hidden lb:sm:inline lb:whitespace-nowrap",children:v?"Cerrar previa":"Vista previa"})]})}),
|
|
554
554
|
/* @__PURE__ */c("div",{className:"lb:flex lb:flex-row lb:gap-1 lb:lg:gap-2 lb:items-center lb:justify-end",children:[
|
|
555
|
-
/* @__PURE__ */s("button",{onClick:yt,disabled:
|
|
555
|
+
/* @__PURE__ */s("button",{onClick:yt,disabled:pe||!Te,className:"lb:cursor-pointer lb:px-3 lb:py-1.5 lb:text-sm lb:rounded lb:bg-brand-blue-800 lb:hover:bg-brand-blue-1000 lb:text-white lb:transition-colors lb:disabled:opacity-50 lb:disabled:cursor-not-allowed","aria-label":"Descargar",title:"Descargar recorte sin guardar",children:/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-1",children:[
|
|
556
556
|
/* @__PURE__ */s("span",{className:"icon icon-download-white icon--sm"}),
|
|
557
|
-
/* @__PURE__ */s("span",{className:"lb:hidden lb:md:inline lb:whitespace-nowrap",children:"Descargar"})]})}),e.file&&/* @__PURE__ */s("button",{onClick:xt,disabled:
|
|
557
|
+
/* @__PURE__ */s("span",{className:"lb:hidden lb:md:inline lb:whitespace-nowrap",children:"Descargar"})]})}),e.file&&/* @__PURE__ */s("button",{onClick:xt,disabled:pe||f,className:"lb:px-3 lb:cursor-pointer lb:py-1.5 lb:text-sm lb:rounded lb:bg-teal-600 lb:hover:bg-teal-700 lb:text-white lb:transition-colors lb:disabled:opacity-50 lb:disabled:cursor-not-allowed","aria-label":"Conservar solo imagen original sin crear recortes",title:"Subir y guardar la imagen original sin crear recortes",children:/* @__PURE__ */c("div",{className:"lb:flex lb:items-center lb:gap-1",children:[
|
|
558
558
|
/* @__PURE__ */s("span",{className:"icon icon-tick-white icon--sm"}),
|
|
559
559
|
/* @__PURE__ */s("span",{className:"lb:hidden lb:md:inline lb:whitespace-nowrap",children:"Guardar sin recortar"})]})}),
|
|
560
|
-
/* @__PURE__ */s("button",{onClick:pt,disabled:
|
|
560
|
+
/* @__PURE__ */s("button",{onClick:pt,disabled:pe||!_e||!Le||!Te||!we.isReady,className:"lb:px-3 lb:cursor-pointer lb:py-1.5 lb:text-sm lb:rounded lb:bg-green-600 lb:hover:bg-green-700 lb:text-white lb:transition-colors lb:disabled:opacity-50 lb:disabled:cursor-not-allowed",title:"Guardar imagen recortada",children:/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:gap-1",children:/* @__PURE__ */c(u,pe?{children:[
|
|
561
561
|
/* @__PURE__ */s("span",{className:"icon icon-save-white icon--sm"}),
|
|
562
562
|
/* @__PURE__ */s("span",{children:"Guardando..."})]}:{children:[
|
|
563
563
|
/* @__PURE__ */s("span",{className:"icon icon-save-white icon--sm"}),
|
|
@@ -699,13 +699,13 @@ return c("label",{className:`lb:flex lb:items-center lb:gap-3 lb:p-3 lb:rounded
|
|
|
699
699
|
/* @__PURE__ */c("p",{children:[re?.width," × ",re?.height," px"]})]})]}):/* @__PURE__ */s("div",{className:"lb:flex lb:items-center lb:justify-center lb:h-full lb:min-h-[200px]",children:/* @__PURE__ */s("p",{className:"lb:text-sm lb:text-gray-500",children:"No se pudo generar la vista previa"})})}),
|
|
700
700
|
/* @__PURE__ */s("div",{className:"lb:px-4 lb:py-2 lb:bg-gray-100 lb:border-t lb:border-gray-200",children:/* @__PURE__ */c("p",{className:"lb:text-xs lb:text-gray-600 lb:text-center",children:[
|
|
701
701
|
/* @__PURE__ */c("span",{className:"lb:hidden lb:md:inline",children:["Arrastra desde el título para mover •"," "]}),"Actualización automática al editar"]})})]})}),
|
|
702
|
-
/* @__PURE__ */s(
|
|
703
|
-
return c(u,{children:[m&&/* @__PURE__ */s(
|
|
704
|
-
/* @__PURE__ */c("div","crop-only"===v?{children:[h&&/* @__PURE__ */s(
|
|
705
|
-
/* @__PURE__ */s(
|
|
702
|
+
/* @__PURE__ */s(Ye,{src:w,alt:"Vista previa del recorte",title:re?.label||"Recorte",subtitle:`${re?.width||0} × ${re?.height||0} px`,isOpen:D&&!!w,onClose:()=>R(!1)})]}):null}function Pl({onSave:e,onCancel:t,onError:n,onVariantCreated:l,onUploadAndCrop:r,onVideoSelect:a,onUploadWithFolder:i,onFolderChange:o,onDelete:d,isActionAllowed:b,selectedImage:m,uploading:h,uploadError:p,deleting:f,selectedUploadFolder:g,modeUI:v,apiKey:y,prod:w,allowedCategories:x,resolvedAccept:k,returnConfig:C,folderConfig:S,cropperConfig:N,resetUpload:E}){/* @__PURE__ */
|
|
703
|
+
return c(u,{children:[m&&/* @__PURE__ */s(Il,{image:m,onSave:e,onCancel:t,onDelete:m?.id&&b("delete")?()=>d(m.id):null,onError:n,deleting:f,onVariantCreated:l,onUpload:i,uploading:h,cropperConfig:N}),!m&&
|
|
704
|
+
/* @__PURE__ */c("div","crop-only"===v?{children:[h&&/* @__PURE__ */s(ht,{text:"Subiendo archivo..."}),p&&/* @__PURE__ */c(ye,{variant:"danger",toast:!0,onClose:E,children:["Error al subir archivo: ",p]}),
|
|
705
|
+
/* @__PURE__ */s(Ht,{onSelect:r,onVideoSelect:a,disabled:h,apiKey:y,prod:w,allowedCategories:x,resolvedAccept:k,returnConfig:C,folderConfig:S,selectedFolder:g,onFolderChange:o})]}:{className:"limbo-empty-state lb:flex lb:flex-col lb:items-center lb:justify-center lb:py-12 lb:px-6 lb:text-center",children:[
|
|
706
706
|
/* @__PURE__ */s("div",{className:"lb:text-gray-400 lb:mb-4",children:/* @__PURE__ */s("svg",{className:"lb:w-16 lb:h-16 lb:mx-auto",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:/* @__PURE__ */s("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),
|
|
707
|
-
/* @__PURE__ */s("p",{className:"lb:text-gray-600 lb:mb-4",children:"Selecciona una imagen de la galería para comenzar a recortar."})]})]})}const Tl=["button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"]):not([disabled])',"a[href]"].join(", "),Al=e=>{if("true"===e.getAttribute("aria-hidden"))return!1;if(e.hasAttribute("inert"))return!1;if(e.hasAttribute("hidden"))return!1;let t=e.parentElement;for(;t;){if(t.hasAttribute("inert"))return!1;if("true"===t.getAttribute("aria-hidden"))return!1;t=t.parentElement}return!0};function Ll(e,{onClose:t,isActive:l=!0}={}){n(()=>{if(!l)return;const n=e?.current;if(!n)return;const r=e=>{if("Escape"===e.key)return e.preventDefault(),void t?.();if("Tab"!==e.key)return;const l=(r=n,Array.from(r.querySelectorAll(Tl)).filter(Al));var r;if(0===l.length)return void e.preventDefault();const a=l[0],i=l[l.length-1],o=document.activeElement;e.shiftKey?o!==a&&n.contains(o)||(e.preventDefault(),i.focus()):o===i&&(e.preventDefault(),a.focus())};return n.addEventListener("keydown",r),()=>n.removeEventListener("keydown",r)},[e,t,l])}function Il({apiKey:i,onClose:o,prod:u=!1,url:d=!0,features:b=["gallery","upload","cropper"],modeUI:m="full",ui:h={showActions:["select","download","copy","delete","crop","variants","rename"],hideActions:[],theme:"light",language:"es",compactMode:!1,showTabs:!0},callbacks:p={},instanceId:g=null,itemsPerPage:v=30,_externalImage:y=null,cropperConfig:w=null,folderConfig:x={include:[],exclude:[],includeNoFolder:!0,showFolderSelector:!0,showFolderFilter:!0,showFolderInfo:!0,allowMoveFolder:!0,allowCreateFolder:!0,defaultFolder:null},allowedCategories:k=null,accept:C=null,returnConfig:S=null}){const N=r(p);n(()=>{N.current=p},[p]);const E=r(null);Ll(E,{onClose:o}),n(()=>{Ce(),["limbo_stock_selectedService","limbo_stock_dynamicForm","limbo_stock_stockImages","limbo_stock_currentPage","limbo_stock_paginationInfo","limbo_portals_searchName","limbo_portals_limit","limbo_portals_currentPage","limbo_portals_images","limbo_portals_portalResults","limbo_portals_paginationInfo"].forEach(e=>sessionStorage.removeItem(e))},[]),n(()=>{const e=()=>{["limbo_stock_selectedService","limbo_stock_dynamicForm","limbo_stock_stockImages","limbo_stock_currentPage","limbo_stock_paginationInfo","limbo_portals_searchName","limbo_portals_limit","limbo_portals_currentPage","limbo_portals_images","limbo_portals_portalResults","limbo_portals_paginationInfo"].forEach(e=>sessionStorage.removeItem(e)),ce(),Ce()},t=t=>{t.persisted&&e()};let n=null;const l=()=>{"hidden"===document.visibilityState?n=Date.now():"visible"===document.visibilityState&&null!==n&&(Date.now()-n>18e5&&e(),n=null)};return window.addEventListener("pageshow",t),document.addEventListener("visibilitychange",l),()=>{window.removeEventListener("pageshow",t),document.removeEventListener("visibilitychange",l)}},[]);const[$,_]=t({name:"",uploadedBy:"",dateFrom:"",dateTo:"",assetType:"",folder:""}),[z,T]=t(x?.defaultFolder||null),A=be($.name,400),L=be($.uploadedBy,400),I=e.useMemo(()=>f(C||(k?k.map(e=>`${e}/*`).join(","):null)),[C,k]),P=e=>!!e&&(e.startsWith("image/")&&"image/gif"!==e),M=(()=>{let e;switch(m){case"gallery-only":e=["gallery"];break;case"upload-only":e=["upload","cropper"];break;case"crop-only":e=["cropper"];break;case"ia-only":e=["ia"];break;default:e=[...b]}return I.isAllTypes||I.includesImages||(e=e.filter(e=>"cropper"!==e)),e})(),D=()=>M.includes("gallery")?"gallery":M.includes("upload")?"upload":M.includes("cropper")?"cropper":M.includes("ia")?"ia":M[0]||"gallery",[F,j]=t(D()),[U,B]=t(null),W=r(null);n(()=>{!U&&W.current&&(URL.revokeObjectURL(W.current),W.current=null)},[U]);const[H,K]=t(null);n(()=>{y&&(console.log("📸 Imagen externa detectada:",y),B(y),j("cropper"))},[y]),n(()=>{const e=()=>{console.log("[App] Modal cerrado, reseteando estado..."),B(null),j(D())};return window.limboCore?.events&&window.limboCore.events.on("modal:closed",e),()=>{window.limboCore?.events&&window.limboCore.events.off("modal:closed",e)}},[]);const[G,Q]=t(1),{isTokenExpired:X,handleTokenExpiredClose:Y,handleTokenExpiredReload:J}=function(){const[e,l]=t(!1),[r,i]=t(!1),o=a(async()=>{const e=V();if("jwt"!==e.authMode||!e.tokenProvider)return!1;i(!0);try{return q(await e.tokenProvider()),l(!1),!0}catch{return!1}finally{i(!1)}},[]),s=a(e=>{if(401===e?.response?.status){const t=e.response.data;if("token_expired"===t?.error||t?.message?.includes("expired")||t?.message?.includes("caducado")||"string"==typeof t?.error&&t.error.includes("expired"))return l(!0),!0}return!1},[]),c=a(()=>{l(!1)},[]),u=a(()=>{l(!1),window.location.reload()},[]);return n(()=>{const e=e=>{if(!e.detail?.error)return;const t=V();s(e.detail.error)&&("jwt"===t.authMode&&t.tokenProvider?o().then(e=>{e||l(!0)}):l(!0))};return window.addEventListener("tokenExpiredError",e),()=>window.removeEventListener("tokenExpiredError",e)},[s,o]),{isTokenExpired:e,isRefreshing:r,checkTokenExpiration:s,handleTokenExpiredClose:c,handleTokenExpiredReload:u,tryRefreshToken:o}}(),{upload:Z,loading:ee,error:te,uploadedImage:re,reset:ie}=function(){const[e,n]=t(!1),[l,r]=t(null),[a,i]=t(null);return{upload:async(e,t=null,l=null)=>{if(!e)return r("No se ha proporcionado ningún archivo"),null;n(!0),r(null),i(null);try{const n="object"==typeof l?l?.slug:l,r=await ne(e,t,!1,n),a=r.result||r;return i(a),a}catch(a){return r(a.message),null}finally{n(!1)}},loading:e,error:l,uploadedImage:a,reset:()=>{r(null),i(null)}}}(),{deleteImg:oe,loading:se,error:pe,reset:fe}=ae(),ge=l(()=>({limit:v,page:G,...A&&{name:A},...L&&{uploadedBy:L},...$.dateFrom&&{dateFrom:$.dateFrom},...$.dateTo&&{dateTo:$.dateTo},...$.assetType&&{asset_type:$.assetType},...!I.isAllTypes&&I.raw&&{accept:I.raw},...$.folder&&{folder:$.folder},...x.include?.length>0&&{folders_include:x.include.join(",")},...0===x.include?.length&&x.exclude?.length>0&&{folders_exclude:x.exclude.join(",")},...(x.include?.length>0||x.exclude?.length>0)&&void 0!==x.includeNoFolder&&{include_no_folder:x.includeNoFolder?"1":"0"}}),[v,G,A,L,$.dateFrom,$.dateTo,$.assetType,$.folder,I.isAllTypes,I.raw,x.include,x.exclude,x.includeNoFolder]),ve=M.includes("gallery"),{images:ye,loading:we,error:xe,pagination:Se,invalidateCache:Ne,setImages:Ee,refetch:$e}=ue(i,u,ge,ve);n(()=>{const e=()=>{$e()};return document.addEventListener("limbo:variantsCleared",e),document.addEventListener("limbo:variantDeleted",e),()=>{document.removeEventListener("limbo:variantsCleared",e),document.removeEventListener("limbo:variantDeleted",e)}},[$e]);const{refreshVariants:_e}=de(),ze=a((e,t=null)=>Z(e,t,z?.slug||z),[Z,z]),{handleDelete:Te,handleAssetFolderChange:Ae,handleRenameAsset:Le,handleVariantCreated:Ie}=function({callbacksRef:e,deleteImg:t,evictFromCache:n,invalidateCache:l,refreshVariants:r,images:i,setImages:o,setCurrentPage:s,selectedImage:c,setSelectedImage:u,setActiveTab:d}){return{handleDelete:async r=>{if(!confirm("¿Estás seguro de que deseas eliminar este archivo? Esta acción también eliminará todos sus recortes."))return;const a=i.find(e=>e.id===r);await t(r)&&(a?.url&&n(a.url),l(),s(1),o(e=>e.filter(e=>e.id!==r)),c&&c.id===r&&(u(null),d("gallery")),e.current.onDelete&&e.current.onDelete({assetId:r}))},handleAssetFolderChange:async(e,t)=>{const n=t?.slug||null;try{return await le(e.id,{folder:n}),l(),o(n=>n.map(n=>n.id===e.id?{...n,folder:t??null}:n)),t}catch(r){throw console.error("Error al cambiar carpeta:",r),r}},handleRenameAsset:a(async(e,t)=>{const n=await le(e.id,{original_filename:t}),r=n?.result||{};return l(),o(n=>n.map(n=>n.id!==e.id?n:{...n,filename:r.filename??t,...r.url&&{url:r.url},...void 0!==r.url_webp&&{url_webp:r.url_webp}})),n},[l,o]),handleVariantCreated:(e,t)=>{r(e),o(t=>t.map(t=>t.id===e?{...t,variants_count:(t.variants_count||0)+1}:t)),l()}}}({callbacksRef:N,deleteImg:oe,evictFromCache:ke,invalidateCache:Ne,refreshVariants:_e,images:ye,setImages:Ee,setCurrentPage:Q,selectedImage:U,setSelectedImage:B,setActiveTab:j}),{handleUploadAndCrop:Pe,handleVideoSelect:Me}=function({callbacksRef:e,upload:t,refetch:n,activeFeatures:l,setActiveTab:r,setSelectedImage:i,setCurrentPage:o,setSuccessMessage:s,instanceId:c,selectedUploadFolder:u,tempBlobUrlRef:d}){return{handleUploadAndCrop:async a=>{if(!a.type?.startsWith("image/")||"image/gif"===a.type){const i=u?.slug||u,s=await t(a,null,i);return void(s&&(n(),o(1),l.includes("gallery")&&r("gallery"),e.current.onUpload&&e.current.onUpload({assetId:s.id,url:s.url,fileName:s.filename,mime:s.mime_type,width:s.width,height:s.height,instanceId:c})))}const s=URL.createObjectURL(a),b=await new Promise(e=>{const t=new Image;t.onload=()=>{e({width:t.naturalWidth,height:t.naturalHeight}),URL.revokeObjectURL(s)},t.onerror=()=>{e({width:1920,height:1080}),URL.revokeObjectURL(s)},t.src=s}),m={file:a,filename:a.name,mime_type:a.type,url:(()=>{const e=URL.createObjectURL(a);return d.current=e,e})(),width:b.width,height:b.height};if(i(m),l.includes("cropper"))r("cropper");else{const l=u?.slug||u,i=await t(a,null,l);i&&(n(),o(1),r("gallery"),e.current.onUpload&&e.current.onUpload({assetId:i.id,url:i.url,fileName:i.filename,mime:i.mime_type,width:i.width,height:i.height,instanceId:c}))}},handleVideoSelect:a(t=>{const n={...t,instanceId:c};e.current.onSelect&&e.current.onSelect(n),window.limboCore?.events&&window.limboCore.events.emit("select",n),"modal"===((window.limboCore?.config?.getGlobal()||{}).mode||"embed")&&window.limboCore?.modals?.closeAllModals(),s(`Vídeo seleccionado: ${t.title||"Sin título"}`),setTimeout(()=>s(null),3e3)},[c,s])}}({callbacksRef:N,upload:Z,refetch:$e,activeFeatures:M,setActiveTab:j,setSelectedImage:B,setCurrentPage:Q,setSuccessMessage:K,instanceId:g,selectedUploadFolder:z,tempBlobUrlRef:W}),{handleCropSave:De,handleCropCancel:Re,handleCropError:Oe}=function({callbacksRef:e,selectedImage:t,setSelectedImage:n,setActiveTab:l,setImages:r,setCurrentPage:a,setSuccessMessage:i,invalidateCache:o,refetch:s,evictFromCache:c,instanceId:u,activeFeatures:d,modeUI:b}){const m=()=>"crop-only"===b||1===d.length&&"cropper"===d[0]?"crop-only":d.includes("gallery")?"with-gallery":d.includes("upload")&&!d.includes("gallery")?"upload-only":"with-gallery";return{handleCropSave:d=>{const b=m(),h=window.limboCore?.config?.getGlobal()||{},p=h.mode||"embed",f=h.autoHideOnComplete||!1;let g=[],v=null;d.crops&&d.asset?(g=d.crops,v=d.asset):g=d.crops&&Array.isArray(d.crops)?d.crops:Array.isArray(d)?d:[d],v&&"with-gallery"===b&&(r(e=>[v,...e]),a(1),e.current.onUpload&&e.current.onUpload({assetId:v.id,url:v.url,fileName:v.filename,mime:v.mime_type,width:v.width,height:v.height,instanceId:u})),t?.url&&c(t.url),"with-gallery"===b&&(v?s():o());const y=v||t,w=g.some(e=>!0===e.isLocal),x={crops:g,assetId:y?.id,instanceId:u,localCrops:w,asset:y?{id:y.id,url:y.url||y.urlSigned,width:y.width,height:y.height,filename:y.filename,mime_type:y.mime_type}:null};console.log("[App] handleCropSave - callbackPayload:",x),console.log("[App] handleCropSave - crops:",g),console.log("[App] handleCropSave - crops[0]?.url:",g[0]?.url),console.log("[App] handleCropSave - asset:",x.asset),console.log("[App] handleCropSave - callbacksRef.current.onCropsSaved existe:",!!e.current.onCropsSaved),e.current.onCropsSaved?(console.log("[App] Llamando callbacksRef.current.onCropsSaved..."),e.current.onCropsSaved(x),console.log("[App] callbacksRef.current.onCropsSaved ejecutado")):console.warn("[App] ⚠️ callbacksRef.current.onCropsSaved NO existe"),window.limboCore?.events&&window.limboCore.events.emit("cropsSaved",x);const k=g.length;switch(i(`✅ ${k} recorte${1!==k?"s":""} guardado${1!==k?"s":""} correctamente`),setTimeout(()=>i(null),3e3),b){case"with-gallery":"modal"===p?e.current.onCropsSaved||(window.limboCore?.modals?.closeAllModals(),n(null),l("gallery")):(n(null),l("gallery"));break;case"upload-only":"modal"===p?e.current.onCropsSaved||(window.limboCore?.modals?.closeAllModals(),n(null),l("upload")):(n(null),l("upload"));break;case"crop-only":if("modal"===p)e.current.onCropperComplete&&e.current.onCropperComplete({crops:g,instanceId:u}),window.limboCore?.events&&window.limboCore.events.emit("cropperComplete",{crops:g,instanceId:u}),window.limboCore?.modals?.closeAllModals();else if(e.current.onCropperComplete&&e.current.onCropperComplete({crops:g,instanceId:u}),window.limboCore?.events&&window.limboCore.events.emit("cropperComplete",{crops:g,instanceId:u}),f){const e=document.querySelector(`#limbo-instance-${u}`);e&&(e.style.display="none")}}},handleCropCancel:()=>{const r=m(),a=(window.limboCore?.config?.getGlobal()||{}).mode||"embed";switch(e.current.onCropperCancelled&&e.current.onCropperCancelled({assetId:t?.id,instanceId:u}),window.limboCore?.events&&window.limboCore.events.emit("cropperCancelled",{assetId:t?.id,instanceId:u}),r){case"with-gallery":n(null),l("gallery");break;case"upload-only":"modal"===a?window.limboCore?.modals?.closeAllModals():(n(null),l("upload"));break;case"crop-only":"modal"===a?window.limboCore?.modals?.closeAllModals():window.limboCore?.events&&window.limboCore.events.emit("cropperClosed",{instanceId:u,reason:"cancelled"})}},handleCropError:n=>{e.current.onCropperError&&e.current.onCropperError(n,u),window.limboCore?.events&&window.limboCore.events.emit("cropperError",{error:n,assetId:t?.id,instanceId:u}),console.error("Cropper error:",n)}}}({callbacksRef:N,selectedImage:U,setSelectedImage:B,setActiveTab:j,setImages:Ee,setCurrentPage:Q,setSuccessMessage:K,invalidateCache:Ne,evictFromCache:ke,refetch:$e,instanceId:g,activeFeatures:M,modeUI:m}),Fe=e=>!h.hideActions?.includes(e)&&(!!h.showActions?.includes(e)||!(h.showActions?.length>0)),je=[{id:"gallery",label:"Galería",feature:"gallery"},{id:"upload",label:"Subir",feature:"upload"},{id:"cropper",label:"Recortador",hideNonActive:!0,feature:"cropper"}].filter(e=>M.includes(e.feature)),Ue=e=>{P(e.mime_type||e.original_mime)?(B(e),M.includes("cropper")&&j("cropper")):console.log("[App] ⚠️ Archivo no recortable:",e.mime_type||e.original_mime,"- saltando cropper")};/* @__PURE__ */
|
|
708
|
-
return c("div",{ref:
|
|
709
|
-
/* @__PURE__ */s(
|
|
710
|
-
/* @__PURE__ */s(O,{isOpen:X,onClose:Y,onReload:J})]})}class Pl{constructor(e,t,n,l){this.id=e,this.config=t,this.eventManager=n,this.modalManager=l,this.root=null,this.container=null,this.modal=null,this.mounted=!1,this.destroyed=!1,this.button=null,this._handleAppClose=()=>{this.modal&&"function"==typeof this.modal.close&&this.modal.close()},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=P.createRoot(this.container),this.root.render(this._renderApp()),this.mounted=!0,this.eventManager.emit("ready",{instance:this})}catch(e){this.eventManager.emit("error",{instanceId:this.id,error:e.message})}return this}unmount(){return this.mounted?(this.root&&(this.root.unmount(),this.root=null),"button"===this.config.mode&&this.button,this.mounted=!1,this):this}open(){return"modal"!==this.config.mode&&"button"!==this.config.mode||(this.modal||this._createModal(),this.modal&&!this.modal.isOpened()&&(this.modal.open(),this.eventManager.emit("modal:open",{instance:this}))),this}close(){return this.modal&&this.modal.isOpened()&&(this.eventManager?.emit("modal:close",{instance:this}),this.modal.close()),this}updateConfig(e){return this.config={...this.config,...e},this.mounted&&this.root.render(this._renderApp()),this.eventManager.emit("config:updated",{instance:this,newConfig:e}),this}destroy(){this.destroyed||(this.unmount(),this.modal&&(this.modal.destroy(),this.modal=null),this.button&&this.button.parentNode&&(this.button.parentNode.removeChild(this.button),this.button=null),this.eventManager.emit("destroy",{instance:this}),this.container=null,this.config=null,this.eventManager=null,this.modalManager=null,this.destroyed=!0)}getId(){return this.id}getMode(){return this.config.mode}isMounted(){return this.mounted}isDestroyed(){return this.destroyed}getContainer(){return this.container}getConfig(){return{...this.config}}isContainerInDOM(){return this.container&&document.contains(this.container)}_createModal(){if(this.modalManager&&"modal"===this.config.mode&&(this.modal=this.modalManager.createModal({title:this.config.title||"Limbo Image Manager",size:this.config.modalSize||this.config.modal?.size||"large",usesReactFocusTrap:!0,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=P.createRoot(e),this.root.render(this._renderApp()),this.mounted=!0}}_createButton(){if(this.container||(this.container=this._resolveContainer()),!this.container)return void this.eventManager.emit("error",{instanceId:this.id,error:"Container not found for button mode"});const e=document.createElement("button");e.type="button",e.className="limbo-trigger-button",e.textContent=this.config.buttonText||"Abrir Limbo",e.style.cssText="\n background: #001978;\n color: white;\n border: none;\n padding: 10px 20px;\n border-radius: 6px;\n cursor: pointer;\n font-family: inherit;\n font-size: 14px;\n font-weight: 500;\n transition: all 0.2s ease;\n ",e.addEventListener("mouseenter",()=>{e.style.backgroundColor="#334793",e.style.transform="translateY(-1px)"}),e.addEventListener("mouseleave",()=>{e.style.backgroundColor="#001978",e.style.transform="translateY(0)"}),e.addEventListener("click",()=>{this.open()}),this.container.appendChild(e),this.button=e,this.mounted=!0}_resolveContainer(){const{container:e}=this.config;return e?"string"==typeof e?document.querySelector(e):e instanceof Element?e:null:null}_renderApp(){return e.createElement("div",{id:`limbo-component-container-${this.id}`,className:"limbo-scope limbo-instance limbo-component-container-wrapper lb:h-full lb:w-full lb:py-2 lb:pb-0 lb:bg-white","data-limbo-id":this.id,"data-limbo-mode":this.config.mode,"data-limbo-version":"4.0.0","data-limbo-isolated":"true","aria-label":"Limbo Image Manager",role:"region"},e.createElement(Il,{onClose:"modal"===this.config.mode?this._handleAppClose:void 0,apiKey:this.config.apiKey||null,publicKey:this.config.publicKey||null,token:this.config.token||null,prod:this.config.prod||!1,url:this.config.url,features:this.config.features,modeUI:this.config.modeUI||"full",ui:this.config.ui,callbacks:this._createCallbacks(),instanceId:this.id,authMode:this.config.authMode||(this.config.publicKey?"session":"manual"),_externalImage:this.config._externalImage||null,cropperConfig:this.config.cropper||null,allowedCategories:this.config.validation?.allowedCategories||null,accept:this.config.validation?.accept||null,returnConfig:this.config.returnConfig||null,folderConfig:this.config.folders||{include:[],exclude:[],includeNoFolder:!0},itemsPerPage:this.config.itemsPerPage||30}))}_createCallbacks(){return{onSelect:e=>{const t=this.config?.callbacks?.onSelect,n=this._createStandardPayload(e,"select");t&&Promise.resolve(t(n)).catch(e=>{console.error("[LimboInstance] Error en onSelect callback:",e)}),this.destroyed||this._emitDOMEvent("select",n)},onUpload:e=>{const t=this.config?.callbacks?.onUpload,n=this._createStandardPayload(e,"upload");t&&Promise.resolve(t(n)).catch(e=>{console.error("[LimboInstance] Error en onUpload callback:",e)}),this.destroyed||this._emitDOMEvent("upload",n)},onError:e=>{const t=this.config?.callbacks?.onError,n={instance:this,error:{message:e.message||"Unknown error",code:e.code||"UNKNOWN",timestamp:Date.now()}};t&&t(n.error),this.destroyed||this._emitDOMEvent("error",n)},onClose:()=>{const e=this.config?.callbacks?.onClose,t={instance:this,timestamp:Date.now()};e&&e(),this.destroyed||this._emitDOMEvent("close",t)},onCropsSaved:e=>{console.log("[LimboInstance] onCropsSaved recibido:",e),console.log("[LimboInstance] this.config?.callbacks:",this.config?.callbacks);const t=this.config?.callbacks?.onCropsSaved;console.log("[LimboInstance] userCallback existe:",!!t);const n={instance:this,eventType:"cropsSaved",timestamp:Date.now(),instanceId:this.id,...e};if(console.log("[LimboInstance] payload.crops:",n.crops),t){console.log("[LimboInstance] Llamando userCallback onCropsSaved");try{t(n),console.log("[LimboInstance] userCallback ejecutado correctamente")}catch(l){console.error("[LimboInstance] Error en userCallback:",l)}}else console.warn("[LimboInstance] ⚠️ userCallback onCropsSaved NO existe");this.destroyed||this._emitDOMEvent("cropsSaved",n)},onCropperComplete:e=>{console.log("[LimboInstance] onCropperComplete recibido:",e);const t=this.config?.callbacks?.onCropperComplete,n={instance:this,eventType:"cropperComplete",timestamp:Date.now(),instanceId:this.id,...e};t&&(console.log("[LimboInstance] Llamando userCallback onCropperComplete"),t(n)),this.destroyed||this._emitDOMEvent("cropperComplete",n)}}}_createStandardPayload(e,t){const n={instance:this,eventType:t,timestamp:Date.now(),instanceId:this.id,mode:this.config?.mode,features:this.config?.features};return e&&(e.assetId||e.id?(n.assetId=e.assetId||e.id,n.variants=e.variants||[],n.master=e.master||{urlSigned:e.url||e.urlSigned,width:e.width,height:e.height,mime:e.mime||e.mimeType},n.fileName=e.fileName||e.name,n.mime=e.mime||e.mimeType,n.width=e.width,n.height=e.height,n.fileBlob=e.fileBlob||e.file,n.metadata={uploadedBy:e.uploadedBy,uploadedAt:e.uploadedAt||e.timestamp,size:e.size,...e.metadata}):Object.assign(n,e)),n}_emitDOMEvent(e,t){if(this.destroyed)return;const n=new CustomEvent(`limbo:${e}`,{detail:t,bubbles:!0,cancelable:!0});(this.getContainer()||document).dispatchEvent(n),this.eventManager?.emit(e,t)}_validateConfig(){const e=V();if(!(this.config.auth?.apiKey||this.config.auth?.publicKey||this.config.auth?.token||this.config.apiKey||this.config.publicKey||this.config.token||this.config.tokenProvider||this.config.auth?.tokenProvider||e.token||e.publicKey||e.tokenProvider))throw new Error(`LimboInstance ${this.id}: Authentication is required. Provide either auth.publicKey (recommended), auth.apiKey (for server-side only), token, or tokenProvider`);if((this.config.auth?.apiKey||this.config.apiKey)&&"undefined"!=typeof window&&console.warn("⚠️ SECURITY WARNING: API Key detected in client-side code.\nThis is a security risk! Use publicKey instead for client applications.\nAPI Keys should only be used in server-side environments."),!["embed","modal","button"].includes(this.config.mode))throw new Error(`LimboInstance ${this.id}: invalid mode ${this.config.mode}`);if("embed"===this.config.mode&&!this.config.container)throw new Error(`LimboInstance ${this.id}: container is required for embed mode`);if("button"===this.config.mode&&!this.config.container)throw new Error(`LimboInstance ${this.id}: container is required for button mode`)}}class Ml{constructor(){this.instances=/* @__PURE__ */new Map,this.counter=0}create(e,t,n){const l="limbo-"+ ++this.counter,r=new Pl(l,e,t,n);return this.instances.set(l,r),r}get(e){return this.instances.get(e)}getAll(){return Array.from(this.instances.values())}getActive(){return this.getAll().filter(e=>e.isMounted())}destroy(e){const t=this.instances.get(e);return!!t&&(t.destroy(),this.instances.delete(e),!0)}destroyAll(){this.instances.forEach(e=>e.destroy()),this.instances.clear()}cleanupOrphans(){const e=[];return this.instances.forEach((t,n)=>{t.isContainerInDOM()||e.push(n)}),e.forEach(e=>this.destroy(e)),e.length}getStats(){const e=this.getAll();return{total:e.length,active:e.filter(e=>e.isMounted()).length,embed:e.filter(e=>"embed"===e.getMode()).length,modal:e.filter(e=>"modal"===e.getMode()).length,button:e.filter(e=>"button"===e.getMode()).length}}}class Dl{constructor(){this.config=null,this.instances=/* @__PURE__ */new Map,this.observer=null,this.initialized=!1}configure(e,t,n){return this.config={selector:e.selector||null,dataset:e.dataset||"data-limbo-input-file",return:e.return||e.returnType||"json",mode:e.mode||"modal",features:e.features||["gallery","upload","cropper"],crop:e.crop||"free",quality:e.quality||.9,format:e.format||"webp",modeUI:e.modeUI||"full",modalSize:e.modalSize||"fullscreen",theme:e.theme||"light",compact:e.compact||!1,maxSize:e.maxSize||"10MB",formats:e.formats||["jpg","jpeg","png","svg","webp"],minWidth:e.minWidth||null,minHeight:e.minHeight||null,maxWidth:e.maxWidth||null,maxHeight:e.maxHeight||null,buttonText:e.buttonText||"Seleccionar archivo",buttonClass:e.buttonClass||"limbo-auto-button",buttonStyle:e.buttonStyle||"primary",showPreview:!1!==e.showPreview,allowMultiple:e.allowMultiple||!1,autoAssign:!1!==e.autoAssign,localCropsOnly:e.localCropsOnly||!1,...e},this.configManager=t,this.eventManager=n,this._initialize(),this}cleanup(){this.observer&&(this.observer.disconnect(),this.observer=null),this.instances.forEach(({input:e,button:t})=>{this._restoreInput(e,t)}),this.instances.clear(),this.config=null,this.initialized=!1}getStats(){return{configured:null!==this.config,totalInputs:this.instances.size,dataset:this.config?.dataset,returnType:this.config?.return}}_initialize(){this.initialized||(this._scanExistingInputs(),this._setupObserver(),this.initialized=!0,this.eventManager.emit("autoInputs:initialized",{config:this.config,inputsFound:this.instances.size}))}_scanExistingInputs(){const e=this.config.selector||`input[${this.config.dataset}]`;document.querySelectorAll(e).forEach(e=>this._processInput(e))}_processInput(e){const t=this._getInputId(e);if(this.instances.has(t))return;if(!this._validateInput(e))return;const n=this._createButton(e);this._hideInput(e),this._insertButton(e,n),this.instances.set(t,{input:e,button:n,config:this._getInputConfig(e)}),this.eventManager.emit("autoInputs:processed",{inputId:t,input:e,button:n})}_createButton(e){const t=document.createElement("button"),n=this._getInputConfig(e);t.type="button";const l=e.dataset.buttontext||e.getAttribute("data-limbo-button-text")||null;t.textContent=l||v(n.accept||null,!1);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,l=t.theme||this.config.theme,r=t.compact||this.config.compact,a={border:"none",borderRadius:"8px",cursor:"pointer",fontFamily:"inherit",fontSize:r?"12px":"14px",fontWeight:"500",transition:"all 0.2s ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",padding:r?"6px 12px":"8px 16px",textDecoration:"none",userSelect:"none"},i={primary:{backgroundColor:"dark"===l?"#3b82f6":"#001978",color:"white",hoverBg:"dark"===l?"#2563eb":"#334793"},secondary:{backgroundColor:"dark"===l?"#374151":"#f3f4f6",color:"dark"===l?"#f9fafb":"#374151",border:"1px solid "+("dark"===l?"#4b5563":"#d1d5db"),hoverBg:"dark"===l?"#4b5563":"#e5e7eb"},outline:{backgroundColor:"transparent",color:"dark"===l?"#3b82f6":"#001978",border:"2px solid "+("dark"===l?"#3b82f6":"#001978"),hoverBg:"dark"===l?"#3b82f6":"#001978",hoverColor:"white"},ghost:{backgroundColor:"transparent",color:"dark"===l?"#f9fafb":"#374151",hoverBg:"dark"===l?"#374151":"#f3f4f6"}},o=i[n]||i.primary;Object.assign(e.style,{...a,...o});const s=o.backgroundColor,c=o.color;e.addEventListener("mouseenter",()=>{e.style.backgroundColor=o.hoverBg||o.backgroundColor,o.hoverColor&&(e.style.color=o.hoverColor),e.style.transform="translateY(-1px)",e.style.boxShadow="0 4px 12px rgba(0, 0, 0, 0.15)"}),e.addEventListener("mouseleave",()=>{e.style.backgroundColor=s,e.style.color=c,e.style.transform="translateY(0)",e.style.boxShadow="none"}),t.disabled&&(e.style.opacity="0.5",e.style.cursor="not-allowed")}_attachButtonEvents(e,t){e.addEventListener("click",e=>{e.preventDefault(),this._handleButtonClick(t)})}_handleButtonClick(e){const t=this._getInputConfig(e),n=this._createModalConfig(t);this.eventManager.emit("autoInputs:modalRequest",{input:e,config:n,callback:async t=>await this._handleImageSelection(e,t)})}async _handleImageSelection(e,t){const n=this._getInputConfig(e);let l=t;try{if(!t.original&&!t.images&&(t.id||t.assetId)){console.log("[AutoInputManager] 🔗 Selección directa detectada, obteniendo URL permanente...");const e=t.id||t.assetId;try{const n=await async function(e,t=!0,n=!0,l=0){try{const r=new URLSearchParams({include_variants:t.toString(),include_metadata:n.toString(),url_expires:l.toString()});return X(await H({endpoint:`/assets/${e}?${r}`,method:"GET",basePath:ee,useJWT:!0}))}catch(r){throw Z(r)}}(e,!1,!1,!0);n?.result?.url?(console.log("[AutoInputManager] ✅ URL permanente obtenida:",n.result.url),l={original:{url:n.result.url,width:n.result.width||t.width,height:n.result.height||t.height,assetId:e},images:[]}):(console.warn("[AutoInputManager] ⚠️ No se pudo obtener URL permanente, usando URL temporal"),l={original:{url:t.url||t.path,width:t.width,height:t.height,assetId:e},images:[]})}catch(r){console.error("[AutoInputManager] Error obteniendo URL permanente:",r),l={original:{url:t.url||t.path,width:t.width,height:t.height,assetId:e},images:[]}}}const a=await this._formatImageData(l,n);console.log("[AutoInputManager] Valor formateado:",a),console.log("[AutoInputManager] Tipo de valor:",typeof a),!1!==n.autoAssign&&(e.value=a,console.log("[AutoInputManager] Valor asignado al input:",e.value)),this._updateButtonFeedback(e,l),e.dispatchEvent(new Event("change",{bubbles:!0})),e.dispatchEvent(new CustomEvent("limbo:resultReady",{detail:{imageData:l,input:e,value:a,config:n,assignment:{format:n.return,smartAssign:!1!==n.smartAssign,autoAssign:!1!==n.autoAssign},legacy:{imageData:l,formatted:this._createFormattedResult(l,n)}},bubbles:!0})),e.dispatchEvent(new CustomEvent("limbo:imageSelected",{detail:{imageData:l,input:e,value:a,config:n,formatted:this._createFormattedResult(l,n)},bubbles:!0})),this.eventManager.emit("autoInputs:imageSelected",{input:e,imageData:l,value:a,config:n})}catch(a){console.error("Error handling image selection:",a),e.dispatchEvent(new CustomEvent("limbo:error",{detail:{error:a.message,input:e,imageData:l,config:n},bubbles:!0})),this._handleImageSelectionLegacy(e,t)}}_updateButtonFeedback(e,t){const n=this._getInputId(e),l=this.instances.get(n);if(!l||!l.button)return;const r=l.button,a=r.nextElementSibling;a&&a.classList.contains("limbo-button-feedback")&&a.remove();const i=document.createElement("span");i.className="limbo-button-feedback",i.style.cssText="\n display: inline-flex;\n align-items: center;\n gap: 6px;\n margin-left: 8px;\n padding: 4px 8px;\n background: #10b981;\n color: white;\n border-radius: 6px;\n font-size: 12px;\n font-weight: 500;\n animation: limbo-fade-in 0.3s ease-out;\n ";const o=t.images&&t.images.length>0,s=o?t.images.length:0;for(;i.firstChild;)i.removeChild(i.firstChild);i.appendChild(function(){const e="http://www.w3.org/2000/svg",t=document.createElementNS(e,"svg");t.setAttribute("width","14"),t.setAttribute("height","14"),t.setAttribute("viewBox","0 0 20 20"),t.setAttribute("fill","currentColor");const n=document.createElementNS(e,"path");return n.setAttribute("fill-rule","evenodd"),n.setAttribute("d","M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"),n.setAttribute("clip-rule","evenodd"),t.appendChild(n),t}());const c=document.createElement("span");c.textContent=o?`${s} recorte${1!==s?"s":""} configurado${1!==s?"s":""}`:"Archivo seleccionado",i.appendChild(c),r.parentNode.insertBefore(i,r.nextSibling);let u=r.parentNode.querySelector(".limbo-powered-by");if(!u){u=document.createElement("div"),u.className="limbo-powered-by";const e=document.createElement("span");e.style.cssText="display:block;margin-top:2px;font-size:10px;color:#aaa;text-align:left;font-family:inherit;opacity:0.7;",e.textContent="Powered by ";const t=document.createElement("b");t.textContent="Limbo",e.appendChild(t),u.appendChild(e),r.parentNode.insertBefore(u,i.nextSibling)}r.style.backgroundColor="#10b981";const d=l.config?.accept||null;r.textContent=v(d,!0)}async _handleImageSelectionLegacy(e,t){const n=this._getInputConfig(e),l=await this._formatImageData(t,n);!1!==n.autoAssign&&(e.value=l),e.dispatchEvent(new Event("change",{bubbles:!0})),e.dispatchEvent(new CustomEvent("limbo:imageSelected",{detail:{imageData:t,input:e,value:l,config:n,formatted:this._createFormattedResult(t,n)},bubbles:!0})),this.eventManager.emit("autoInputs:imageSelected",{input:e,imageData:t,value:l,config:n})}_createFormattedResult(e,t){return{url:e.url||e.path||"",base64:e.base64||e.dataUrl||"",assetId:e.assetId||e.id||"",fileName:e.fileName||e.filename||"",object:{url:e.url||e.path,assetId:e.assetId||e.id,fileName:e.fileName||e.filename,mime:e.mime||e.mime_type,width:e.width,height:e.height,size:e.size||e.file_size,created:e.created_at||e.created,metadata:e.metadata||{}},json:JSON.stringify({url:e.url||e.path,assetId:e.assetId||e.id,fileName:e.fileName||e.filename,mime:e.mime||e.mime_type,width:e.width,height:e.height,size:e.size||e.file_size}),metadata:{width:e.width,height:e.height,size:e.size||e.file_size,format:e.format||e.mime_type,quality:t.quality||this.config.quality,aspectRatio:e.width&&e.height?e.width/e.height:null}}}async _formatImageData(e,t=null){const n=(t||{}).return||this.config.return||"json",l=void 0!==e.original;switch(n){case"url":return l?e.images?.[0]?.url||e.original?.url||"":e.url||e.path||"";case"base64":return e.base64||e.dataUrl||"";case"assetId":return l?e.original?.assetId||"":e.assetId||e.id||"";case"fileName":return e.fileName||e.filename||"";default:try{if(l){const t={original:e.original?{url:e.original.url||e.original.urlSigned,width:e.original.width,height:e.original.height,assetId:e.original.assetId||e.original.id}:null,images:Array.isArray(e.images)?e.images.map(e=>{const t={url:e.url||e.urlSigned,width:e.width,height:e.height,name:e.name||e.filename||e.label};return e.cropState&&(t.cropState={selectorState:e.cropState.selectorState||null,imageTransform:e.cropState.imageTransform||null,flipState:e.cropState.flipState||null}),t}):[]};console.log("[AutoInputManager] Datos limpios para JSON:",t);const n=JSON.stringify(t);return console.log("[AutoInputManager] JSON generado:",n),n}const t={original:{url:e.url||e.path,width:e.width,height:e.height,assetId:e.assetId||e.id}};return console.log("[AutoInputManager] Datos legacy para JSON:",t),JSON.stringify(t)}catch(r){return console.error("[AutoInputManager] Error al serializar JSON:",r),console.error("[AutoInputManager] imageData problemático:",e),"{}"}}}_createModalConfig(e){return{mode:e.mode||this.config.mode||"modal",modeUI:e.modeUI||this.config.modeUI||"full",features:e.features||this.config.features,modalSize:e.modalSize||this.config.modalSize||"fullscreen",title:e.description||this.config.title||"Seleccionar archivo",cropper:this._getCropperConfig(e),ui:{showActions:this._getUIActions(e),hideActions:[],showTabs:this._shouldShowTabs(e),theme:e.theme||this.config.theme,compact:e.compact||this.config.compact,showPreview:void 0!==e.showPreview?e.showPreview:this.config.showPreview},validation:{accept:e.accept||null,maxSize:e.maxSize||this.config.maxSize,formats:e.formats||this.config.formats,minWidth:e.minWidth||this.config.minWidth,minHeight:e.minHeight||this.config.minHeight,maxWidth:e.maxWidth||this.config.maxWidth,maxHeight:e.maxHeight||this.config.maxHeight,required:e.required||!1},behavior:{allowMultiple:e.allowMultiple||this.config.allowMultiple,closeOnSelect:!0,autoAssign:void 0!==e.autoAssign?e.autoAssign:this.config.autoAssign,allowSelectNew:!1!==e.allowSelectNew},initialImageUrl:e.initialImageUrl||null,existingCrops:e.existingCrops||null,existingData:e.existingData||null,returnConfig:{format:e.return||this.config.return,quality:e.quality||this.config.quality,outputFormat:e.format||this.config.format},inputMeta:{inputId:e.inputId,inputName:e.inputName,inputType:e.inputType,placeholder:e.placeholder}}}_getCropperConfig(e){const t=e.crop||this.config.crop,n={quality:e.quality||this.config.quality,format:e.format||this.config.format,mandatoryCrops:e.mandatoryCrops||[],allowAdditionalCrops:!1!==e.allowAdditionalCrops,maxCrops:e.maxCrops||null,localCropsOnly:e.localCropsOnly??this.config.localCropsOnly??!1,existingCrops:e.existingCrops||null};if(e.mandatoryCrops&&e.mandatoryCrops.length>0)return{...n,aspectRatio:null};if(!t||"none"===t||"false"===t)return null;if("free"===t)return{...n,aspectRatio:null};const l={"1:1":1,"16:9":16/9,"4:3":4/3,"3:2":1.5,"2:1":2,square:1,landscape:16/9,portrait:3/4};if(l[t])return{...n,aspectRatio:l[t],minCropBoxWidth:e.minWidth||this.config.minWidth,minCropBoxHeight:e.minHeight||this.config.minHeight};if("string"==typeof t&&t.includes(":")){const[e,l]=t.split(":").map(Number);if(!isNaN(e)&&!isNaN(l)&&0!==l)return{...n,aspectRatio:e/l}}const r=parseFloat(t);return!isNaN(r)&&r>0?{...n,aspectRatio:r}:"object"==typeof t?{...n,...t}:null}_shouldShowTabs(e){const t=e.modeUI||this.config.modeUI||"full",n=e.features||this.config.features;return!["gallery-only","upload-only","crop-only","ia-only"].includes(t)&&(n&&n.length>1)}_getUIActions(e){const t=e.modeUI||this.config.modeUI||"full",n=e.features||this.config.features;let l=[];switch(t){case"gallery-only":case"upload-only":l=["select"];break;case"crop-only":l=["select","crop"];break;default:l=["select"],n.includes("cropper")&&l.push("crop"),n.includes("gallery")&&(l.push("download","copy","rename"),this.config.allowDelete&&l.push("delete"))}return l}_getInputId(e){if(e.id)return e.id;if(e.name)return e.name;let t=e.getAttribute("data-limbo-uid");return t||(t=`limbo-auto-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,e.setAttribute("data-limbo-uid",t)),t}_validateInput(e){return e instanceof HTMLInputElement}_getInputConfig(e){const t=e=>e?e.split(",").map(e=>e.trim()):null,n=e=>{if(!e)return null;const t=e.match(/^(\d+(?:\.\d+)?)(MB|KB|B)?$/i);if(!t)return null;const n=parseFloat(t[1]);switch((t[2]||"B").toUpperCase()){case"MB":return 1024*n*1024;case"KB":return 1024*n;default:return n}},l=(e,t=!1)=>null===e?t:"true"===e||"1"===e||""===e,r=e=>e?parseFloat(e):null,a=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return console.warn("[Limbo AutoInputManager] Error parsing JSON attribute:",t),null}},i=a(e.dataset.mandatorycrops)||a(e.dataset.mandatoryCrops)||a(e.getAttribute("data-mandatory-crops"))||a(e.getAttribute("data-limbo-mandatory-crops"))||null;return{return:e.dataset.returntype||e.getAttribute("data-limbo-return")||this.config.return,mode:e.dataset.mode||e.getAttribute("data-limbo-mode")||this.config.mode,features:t(e.dataset.features)||t(e.getAttribute("data-limbo-features"))||this.config.features,crop:e.dataset.crop||e.getAttribute("data-limbo-crop")||this.config.crop,quality:r(e.dataset.quality)||r(e.getAttribute("data-limbo-quality"))||this.config.quality,format:e.dataset.format||e.getAttribute("data-limbo-format")||this.config.format,modeUI:e.dataset.modeui||e.dataset.modeUI||e.getAttribute("data-limbo-mode-ui")||this.config.modeUI,modalSize:e.dataset.modalsize||e.getAttribute("data-limbo-modal-size")||this.config.modalSize,theme:e.dataset.theme||e.getAttribute("data-limbo-theme")||this.config.theme,compact:l(e.dataset.compact,null)??l(e.getAttribute("data-limbo-compact"),this.config.compact),maxSize:n(e.getAttribute("data-limbo-max-size"))||n(this.config.maxSize),formats:t(e.getAttribute("data-limbo-formats"))||this.config.formats,minWidth:r(e.getAttribute("data-limbo-min-width"))||this.config.minWidth,minHeight:r(e.getAttribute("data-limbo-min-height"))||this.config.minHeight,maxWidth:r(e.getAttribute("data-limbo-max-width"))||this.config.maxWidth,maxHeight:r(e.getAttribute("data-limbo-max-height"))||this.config.maxHeight,buttonText:e.dataset.buttontext||e.getAttribute("data-limbo-button-text")||this.config.buttonText,buttonStyle:e.dataset.buttonstyle||e.getAttribute("data-limbo-button-style")||this.config.buttonStyle,buttonClass:e.dataset.buttonclass||e.getAttribute("data-limbo-button-class")||this.config.buttonClass,showPreview:l(e.getAttribute("data-limbo-show-preview"),this.config.showPreview),allowMultiple:l(e.getAttribute("data-limbo-allow-multiple"),this.config.allowMultiple),autoAssign:l(e.getAttribute("data-limbo-auto-assign"),this.config.autoAssign),placeholder:e.getAttribute("data-limbo-placeholder"),description:e.getAttribute("data-limbo-description"),required:l(e.getAttribute("data-limbo-required"),!1),disabled:l(e.getAttribute("data-limbo-disabled"),!1),inputId:this._getInputId(e),inputName:e.name,inputType:e.type,mandatoryCrops:i,allowAdditionalCrops:l(e.dataset.allowadditionalcrops,null)??l(e.getAttribute("data-limbo-allow-additional-crops"),!0),maxCrops:r(e.dataset.maxcrops)||r(e.getAttribute("data-limbo-max-crops"))||null,accept:e.dataset.accept||e.getAttribute("data-limbo-accept")||null,allowSelectNew:l(e.dataset.allowselectnew,null)??l(e.getAttribute("data-limbo-allow-select-new"),!0),...this._parseExistingInputValue(e.value)}}_parseExistingInputValue(e){if(!e||""===e.trim())return{initialImageUrl:null,existingCrops:null,existingData:null};try{const t=JSON.parse(e);return t.original&&t.original.url?(console.log("[AutoInputManager] Valor existente parseado:",t),{initialImageUrl:t.original.url,existingCrops:t.images||null,existingData:t}):t.url?{initialImageUrl:t.url,existingCrops:null,existingData:t}:{initialImageUrl:null,existingCrops:null,existingData:t}}catch(t){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?{initialImageUrl:e,existingCrops:null,existingData:null}:{initialImageUrl:null,existingCrops:null,existingData:null}}}_generateInputId(){return`limbo-auto-input-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}_hideInput(e){e.style.display="none"}_insertButton(e,t){e.parentNode.insertBefore(t,e.nextSibling)}_restoreInput(e,t){e.style.display="",t&&t.parentNode&&t.parentNode.removeChild(t)}_setupObserver(){this.observer=new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e.nodeType===Node.ELEMENT_NODE&&this._scanNodeForInputs(e)})})}),this.observer.observe(document.body,{childList:!0,subtree:!0})}_scanNodeForInputs(e){const t=this.config.selector||`input[${this.config.dataset}]`;e.matches&&e.matches(t)&&this._processInput(e);const n=e.querySelectorAll&&e.querySelectorAll(t);n&&n.forEach(e=>this._processInput(e))}}class Rl{constructor(){this.listeners=/* @__PURE__ */new Map}emit(e,t={}){this._emitDOMEvent(e,t),this._executeListeners(e,t)}on(e,t){return this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t),()=>this.off(e,t)}off(e,t){const n=this.listeners.get(e);if(n){const e=n.indexOf(t);e>-1&&n.splice(e,1)}}cleanup(){this.listeners.clear()}_emitDOMEvent(e,t){const n=new CustomEvent(`limbo:${e}`,{detail:{...t,timestamp:Date.now()},bubbles:!0,cancelable:!0});(t.instance?.getContainer()||document).dispatchEvent(n)}_executeListeners(e,t){const n=this.listeners.get(e);n&&n.forEach(n=>{try{n(t)}catch(l){console.error(`Error executing listener for ${e}:`,l)}})}getStats(){const e={};return this.listeners.forEach((t,n)=>{e[n]=t.length}),e}}class Ol{constructor(){this.activeModals=/* @__PURE__ */new Set,this.zIndexBase=1e4,this.focusableSelectors=["button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"]):not([disabled])',"a[href]"].join(", "),this.initialized=!1,this._initGlobalListeners()}createModal(e){const t=new Fl(this._generateModalId(),e,this);return this.activeModals.add(t),t}closeModal(e){const t=this._findModal(e);return!!t&&(t.close(),!0)}closeAllModals(){this.activeModals.forEach(e=>e.close()),this.activeModals.clear()}getActiveModal(){return Array.from(this.activeModals).pop()||null}getStats(){return{active:this.activeModals.size,nextZIndex:this._getNextZIndex()}}_generateModalId(){return`limbo-modal-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}_findModal(e){return Array.from(this.activeModals).find(t=>t.getId()===e)}_getNextZIndex(){return this.zIndexBase+10*this.activeModals.size}_removeModal(e){this.activeModals.delete(e),window.limboCore?.events&&window.limboCore.events.emit("modal:closed",{modalId:e.getId(),remainingModals:this.activeModals.size})}_handleGlobalKeydown(e){const t=this.getActiveModal();t&&(t.config&&t.config.usesReactFocusTrap||("Escape"===e.key&&(e.preventDefault(),t.close()),"Tab"===e.key&&this._handleTabTrap(e,t)))}_handleTabTrap(e,t){const n=t.getFocusableElements();if(0===n.length)return;const l=n[0],r=n[n.length-1];e.shiftKey?document.activeElement===l&&(e.preventDefault(),r.focus()):document.activeElement===r&&(e.preventDefault(),l.focus())}_initGlobalListeners(){this.initialized||(this.globalKeydownHandler=e=>this._handleGlobalKeydown(e),document.addEventListener("keydown",this.globalKeydownHandler),this.initialized=!0)}destroy(){this.closeAllModals(),this.initialized&&this.globalKeydownHandler&&(document.removeEventListener("keydown",this.globalKeydownHandler),this.initialized=!1,this.globalKeydownHandler=null)}}class Fl{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,usesReactFocusTrap:t.usesReactFocusTrap||!1},this.manager=n,this.element=null,this.backdrop=null,this.isOpen=!1,this.previousFocus=null,this._previousInertSiblings=[],this._create()}_create(){this._createBackdrop(),this._createModal(),this._attachEvents()}_createBackdrop(){this.config.backdrop&&(this.backdrop=document.createElement("div"),this.backdrop.className="limbo-modal-backdrop",this.backdrop.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: rgba(0, 0, 0, 0.5);\n z-index: ${this.manager._getNextZIndex()};\n opacity: 0;\n transition: opacity 0.3s ease;\n `,this.backdrop.addEventListener("click",e=>{e.target===this.backdrop&&this.close()}))}_createModal(){this.element=document.createElement("div"),this.element.className=`limbo-scope limbo-modal limbo-modal--${this.config.size}`,this.element.id=this.id,this.element.setAttribute("role","dialog"),this.element.setAttribute("aria-modal","true"),this.element.setAttribute("aria-labelledby",`${this.id}-title`),this.element.tabIndex=-1;const e=window.innerWidth<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),t={small:e?"width: 100%; height: 100%;":"max-width: 500px; min-height: 400px;",medium:e?"width: 100%; height: 100%;":"max-width: 800px; min-height: 500px;",large:e?"width: 100%; height: 100%;":"max-width: 1400px; min-height: 700px;",xlarge:e?"width: 100%; height: 100%;":"max-width: 95dvw; min-height: 85vh;",fullscreen:"width: 100%; height: 100%; max-width: 100%; max-height: 100%; border-radius: 0;"},n="fullscreen"===this.config.size,l=e||n?`\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n transform: ${e?"translateY(100%)":"scale(0.95)"};\n width: 100%;\n height: 100%;\n max-width: none;\n max-height: none;\n border-radius: 0;\n background: white;\n z-index: ${this.manager._getNextZIndex()+1};\n opacity: ${e?"1":"0"};\n transition: ${e?"transform":"all"} 0.3s cubic-bezier(0.4, 0, 0.2, 1);\n overflow: hidden;\n display: flex;\n flex-direction: column;\n padding-top: env(safe-area-inset-top);\n padding-left: env(safe-area-inset-left);\n padding-right: env(safe-area-inset-right);\n padding-bottom: env(safe-area-inset-bottom);\n `:`\n position: fixed;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%) scale(0.8);\n ${t[this.config.size]}\n width: 90%;\n max-height: 90vh;\n background: white;\n border-radius: 16px;\n box-shadow: 0 25px 50px rgba(0, 0, 0, 0.25);\n z-index: ${this.manager._getNextZIndex()+1};\n opacity: 0;\n transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);\n overflow: hidden;\n display: flex;\n flex-direction: column;\n `;this.element.style.cssText=l,this._createHeader(),this._createBody(),document.body.appendChild(this.backdrop),document.body.appendChild(this.element)}_createHeader(){const e=document.createElement("div");e.className="limbo-modal-header";const t=window.innerWidth<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);e.style.cssText=`\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: ${t?"16px 20px":"20px 24px"};\n border-bottom: 1px solid #e9ecef;\n background: #f8f9fa;\n ${t?"position: sticky; top: 0; z-index: 10;":""}\n min-height: ${t?"60px":"auto"};\n `;const n=document.createElement("h2");if(n.id=`${this.id}-title`,n.className="limbo-modal-title",n.textContent=this.config.title,n.style.cssText="\n margin: 0;\n font-size: 18px;\n font-weight: 600;\n color: #001978;\n flex: 1;\n margin-right: 16px;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n ",e.appendChild(n),this.config.showCloseButton){const n=document.createElement("button");n.type="button",n.className="limbo-modal-close",n.textContent="✕",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 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",this._applyInertToSiblings();const e=window.innerWidth<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),t="fullscreen"===this.config.size;return requestAnimationFrame(()=>{this.backdrop&&(this.backdrop.style.opacity="1"),this.element.style.opacity="1",this.element.style.transform=e?"translateY(0%)":t?"scale(1)":"translate(-50%, -50%) scale(1)"}),this.isOpen=!0,this.config.focus&&setTimeout(()=>{if(window.limbo&&window.limbo.core&&window.limbo.core.keyboard)window.limbo.core.keyboard.focusFirst(this.element);else{const e=this.getFocusableElements()[0];e&&e.focus()}},300),this.config.onOpen&&this.config.onOpen(this),this}close(){if(!this.isOpen)return this;const e=window.innerWidth<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),t="fullscreen"===this.config.size;return this.backdrop&&(this.backdrop.style.opacity="0"),this.element.style.opacity="0",this.element.style.transform=e?"translateY(100%)":t?"scale(0.95)":"translate(-50%, -50%) scale(0.8)",setTimeout(()=>{this._cleanup()},300),this.isOpen=!1,window.limbo&&window.limbo.core&&window.limbo.core.keyboard&&(window.limbo.core.keyboard.setActiveModal(null),window.limbo.core.keyboard.releaseFocus()),this.config.onClose&&this.config.onClose(this),this}destroy(){this.close(),this.manager._removeModal(this),this.config.onDestroy&&this.config.onDestroy(this)}getBodyContainer(){return this.element.querySelector(".limbo-modal-body")}getFocusableElements(){return Array.from(this.element.querySelectorAll(this.manager.focusableSelectors))}getId(){return this.id}isOpened(){return this.isOpen}getConfig(){return{...this.config}}_applyInertToSiblings(){const e=Array.from(document.body.children).filter(e=>e!==this.element&&e!==this.backdrop);this._previousInertSiblings=e.map(e=>({node:e,hadInert:e.hasAttribute("inert")})),e.forEach(e=>e.setAttribute("inert",""))}_restoreInertSiblings(){this._previousInertSiblings.forEach(({node:e,hadInert:t})=>{!t&&e.isConnected&&e.removeAttribute("inert")}),this._previousInertSiblings=[]}_cleanup(){document.body.style.overflow=this._originalBodyOverflow||"",this._restoreInertSiblings(),this.previousFocus&&"function"==typeof this.previousFocus.focus&&!1!==this.previousFocus.isConnected&&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 jl{constructor(){this.currentTheme=null,this.customThemes=/* @__PURE__ */new Map,this.config=this._getDefaultConfig(),this.isInitialized=!1,this.isCompactMode=!1,this.compactBreakpoint=null,this.compactObserver=null,this.mediaQueryObserver=null,this.mutationObserver=null,this.storageListener=null,this.themeCache=/* @__PURE__ */new Map,this.appliedStyles=/* @__PURE__ */new Set,this.changeCallbacks=/* @__PURE__ */new Set}_getDefaultConfig(){return{theme:{auto:!0,storage:!0,inherit:!0,smooth:!0,detectSystem:!0},compact:{enabled:!1,auto:!0,breakpoint:768,forceOnMobile:!0,persistPreference:!0},presets:{light:{name:"light",displayName:"Claro",variables:{"--limbo-primary":"#3b82f6","--limbo-primary-hover":"#2563eb","--limbo-primary-light":"#dbeafe","--limbo-primary-dark":"#1e40af","--limbo-bg-primary":"#ffffff","--limbo-bg-secondary":"#f8fafc","--limbo-bg-tertiary":"#f1f5f9","--limbo-bg-overlay":"rgba(0, 0, 0, 0.5)","--limbo-bg-card":"#ffffff","--limbo-bg-input":"#ffffff","--limbo-text-primary":"#0f172a","--limbo-text-secondary":"#475569","--limbo-text-tertiary":"#64748b","--limbo-text-inverse":"#ffffff","--limbo-text-muted":"#94a3b8","--limbo-border-light":"#e2e8f0","--limbo-border-medium":"#cbd5e1","--limbo-border-strong":"#94a3b8","--limbo-border-focus":"#3b82f6","--limbo-success":"#10b981","--limbo-success-light":"#d1fae5","--limbo-error":"#ef4444","--limbo-error-light":"#fee2e2","--limbo-warning":"#f59e0b","--limbo-warning-light":"#fef3c7","--limbo-info":"#3b82f6","--limbo-info-light":"#dbeafe","--limbo-shadow-sm":"0 1px 2px 0 rgba(0, 0, 0, 0.05)","--limbo-shadow-md":"0 4px 6px -1px rgba(0, 0, 0, 0.1)","--limbo-shadow-lg":"0 10px 15px -3px rgba(0, 0, 0, 0.1)","--limbo-shadow-xl":"0 20px 25px -5px rgba(0, 0, 0, 0.1)","--limbo-radius-sm":"4px","--limbo-radius-md":"6px","--limbo-radius-lg":"8px","--limbo-radius-xl":"12px","--limbo-font-family":"system-ui, -apple-system, sans-serif","--limbo-font-size-xs":"12px","--limbo-font-size-sm":"14px","--limbo-font-size-md":"16px","--limbo-font-size-lg":"18px","--limbo-font-size-xl":"20px","--limbo-z-dropdown":"1000","--limbo-z-sticky":"1020","--limbo-z-fixed":"1030","--limbo-z-modal":"1050","--limbo-z-tooltip":"1070","--limbo-transition-fast":"150ms cubic-bezier(0.4, 0, 0.2, 1)","--limbo-transition-normal":"300ms cubic-bezier(0.4, 0, 0.2, 1)","--limbo-transition-slow":"500ms cubic-bezier(0.4, 0, 0.2, 1)","--limbo-spacing-compact":"0.5rem","--limbo-spacing-compact-sm":"0.25rem","--limbo-spacing-compact-lg":"0.75rem","--limbo-font-size-compact-xs":"11px","--limbo-font-size-compact-sm":"12px","--limbo-font-size-compact-md":"14px","--limbo-font-size-compact-lg":"16px","--limbo-radius-compact":"4px","--limbo-radius-compact-sm":"3px","--limbo-radius-compact-lg":"6px","--limbo-button-height-compact":"32px","--limbo-input-height-compact":"36px","--limbo-modal-padding-compact":"12px","--limbo-card-padding-compact":"12px","--limbo-gap-compact":"8px","--limbo-gap-compact-sm":"4px","--limbo-gap-compact-lg":"12px"}},dark:{name:"dark",displayName:"Oscuro",variables:{"--limbo-primary":"#60a5fa","--limbo-primary-hover":"#3b82f6","--limbo-primary-light":"#1e293b","--limbo-primary-dark":"#93c5fd","--limbo-bg-primary":"#0f172a","--limbo-bg-secondary":"#1e293b","--limbo-bg-tertiary":"#334155","--limbo-bg-overlay":"rgba(0, 0, 0, 0.8)","--limbo-bg-card":"#1e293b","--limbo-bg-input":"#334155","--limbo-text-primary":"#f8fafc","--limbo-text-secondary":"#cbd5e1","--limbo-text-tertiary":"#94a3b8","--limbo-text-inverse":"#0f172a","--limbo-text-muted":"#64748b","--limbo-border-light":"#334155","--limbo-border-medium":"#475569","--limbo-border-strong":"#64748b","--limbo-border-focus":"#60a5fa","--limbo-success":"#34d399","--limbo-success-light":"#064e3b","--limbo-error":"#f87171","--limbo-error-light":"#7f1d1d","--limbo-warning":"#fbbf24","--limbo-warning-light":"#78350f","--limbo-info":"#60a5fa","--limbo-info-light":"#1e3a8a","--limbo-shadow-sm":"0 1px 2px 0 rgba(0, 0, 0, 0.2)","--limbo-shadow-md":"0 4px 6px -1px rgba(0, 0, 0, 0.3)","--limbo-shadow-lg":"0 10px 15px -3px rgba(0, 0, 0, 0.4)","--limbo-shadow-xl":"0 20px 25px -5px rgba(0, 0, 0, 0.5)","--limbo-radius-sm":"4px","--limbo-radius-md":"6px","--limbo-radius-lg":"8px","--limbo-radius-xl":"12px","--limbo-font-family":"system-ui, -apple-system, sans-serif","--limbo-font-size-xs":"12px","--limbo-font-size-sm":"14px","--limbo-font-size-md":"16px","--limbo-font-size-lg":"18px","--limbo-font-size-xl":"20px","--limbo-z-dropdown":"1000","--limbo-z-sticky":"1020","--limbo-z-fixed":"1030","--limbo-z-modal":"1050","--limbo-z-tooltip":"1070","--limbo-transition-fast":"150ms cubic-bezier(0.4, 0, 0.2, 1)","--limbo-transition-normal":"300ms cubic-bezier(0.4, 0, 0.2, 1)","--limbo-transition-slow":"500ms cubic-bezier(0.4, 0, 0.2, 1)","--limbo-spacing-compact":"0.5rem","--limbo-spacing-compact-sm":"0.25rem","--limbo-spacing-compact-lg":"0.75rem","--limbo-font-size-compact-xs":"11px","--limbo-font-size-compact-sm":"12px","--limbo-font-size-compact-md":"14px","--limbo-font-size-compact-lg":"16px","--limbo-radius-compact":"4px","--limbo-radius-compact-sm":"3px","--limbo-radius-compact-lg":"6px","--limbo-button-height-compact":"32px","--limbo-input-height-compact":"36px","--limbo-modal-padding-compact":"12px","--limbo-card-padding-compact":"12px","--limbo-gap-compact":"8px","--limbo-gap-compact-sm":"4px","--limbo-gap-compact-lg":"12px"}},auto:{name:"auto",displayName:"Automático",variables:{}}},inheritance:{portalSelectors:["body","[data-theme]",".theme-light",".theme-dark",".light-theme",".dark-theme"],variablePrefix:"--",fallbackTheme:"light"},transitions:{duration:"300ms",easing:"cubic-bezier(0.4, 0, 0.2, 1)",properties:["background-color","border-color","color","fill","stroke","box-shadow"]}}}initialize(e={}){this.isInitialized?console.warn("ThemeManager already initialized"):(this.config=this._deepMerge(this.config,e),this._loadCustomThemes(),this.config.theme.inherit&&this._inheritPortalTheme(),this._applyInitialTheme(),this._applyInitialCompactMode(),this._setupObservers(),this._injectBaseStyles(),this.isInitialized=!0)}_injectBaseStyles(){if(document.getElementById("limbo-theme-styles"))return;const e=`\n :root {\n /* Variables de transición para cambios de tema */\n color-scheme: light dark;\n }\n \n [data-limbo-theme] {\n transition: ${this.config.transitions.properties.map(e=>`${e} ${this.config.transitions.duration} ${this.config.transitions.easing}`).join(", ")};\n }\n \n /* Clases de utilidad para temas */\n .limbo-theme-light {\n color-scheme: light;\n }\n \n .limbo-theme-dark {\n color-scheme: dark;\n }\n \n .limbo-theme-auto {\n color-scheme: light dark;\n }\n \n /* Estilos para elementos del componente con variables CSS */\n .limbo-component {\n background-color: var(--limbo-bg-primary);\n color: var(--limbo-text-primary);\n border-color: var(--limbo-border-light);\n border-radius: var(--limbo-radius-md);\n font-family: var(--limbo-font-family);\n font-size: var(--limbo-font-size-md);\n transition: var(--limbo-transition-normal);\n }\n \n .limbo-card {\n background-color: var(--limbo-bg-card);\n border: 1px solid var(--limbo-border-light);\n border-radius: var(--limbo-radius-lg);\n box-shadow: var(--limbo-shadow-md);\n color: var(--limbo-text-primary);\n }\n \n .limbo-input {\n background-color: var(--limbo-bg-input);\n border: 1px solid var(--limbo-border-medium);\n border-radius: var(--limbo-radius-md);\n color: var(--limbo-text-primary);\n font-family: var(--limbo-font-family);\n font-size: var(--limbo-font-size-md);\n transition: var(--limbo-transition-fast);\n }\n \n .limbo-input:focus {\n border-color: var(--limbo-border-focus);\n box-shadow: 0 0 0 3px var(--limbo-primary-light);\n outline: none;\n }\n \n .limbo-button {\n background-color: var(--limbo-primary);\n border: 1px solid var(--limbo-primary);\n border-radius: var(--limbo-radius-md);\n color: var(--limbo-text-inverse);\n font-family: var(--limbo-font-family);\n font-size: var(--limbo-font-size-md);\n transition: var(--limbo-transition-fast);\n cursor: pointer;\n }\n \n .limbo-button:hover {\n background-color: var(--limbo-primary-hover);\n border-color: var(--limbo-primary-hover);\n }\n \n .limbo-button.secondary {\n background-color: var(--limbo-bg-secondary);\n border-color: var(--limbo-border-medium);\n color: var(--limbo-text-primary);\n }\n \n .limbo-button.secondary:hover {\n background-color: var(--limbo-bg-tertiary);\n }\n \n /* Estados de feedback con variables */\n .limbo-state-success {\n background-color: var(--limbo-success-light);\n border-color: var(--limbo-success);\n color: var(--limbo-success);\n }\n \n .limbo-state-error {\n background-color: var(--limbo-error-light);\n border-color: var(--limbo-error);\n color: var(--limbo-error);\n }\n \n .limbo-state-warning {\n background-color: var(--limbo-warning-light);\n border-color: var(--limbo-warning);\n color: var(--limbo-warning);\n }\n \n .limbo-state-info {\n background-color: var(--limbo-info-light);\n border-color: var(--limbo-info);\n color: var(--limbo-info);\n }\n \n /* Overlay y modal con variables */\n .limbo-overlay {\n background-color: var(--limbo-bg-overlay);\n backdrop-filter: blur(4px);\n }\n \n .limbo-modal {\n background-color: var(--limbo-bg-card);\n border-radius: var(--limbo-radius-xl);\n box-shadow: var(--limbo-shadow-xl);\n color: var(--limbo-text-primary);\n }\n \n /* Responsive design con variables */\n @media (max-width: 640px) {\n .limbo-component {\n font-size: var(--limbo-font-size-sm);\n }\n }\n \n /* Modo reducido de movimiento */\n @media (prefers-reduced-motion: reduce) {\n [data-limbo-theme] {\n transition: none;\n }\n \n .limbo-component,\n .limbo-input,\n .limbo-button {\n transition: none;\n }\n }\n \n /* Esquemas de color automático */\n @media (prefers-color-scheme: dark) {\n :root:not([data-limbo-theme]) {\n color-scheme: dark;\n }\n }\n \n @media (prefers-color-scheme: light) {\n :root:not([data-limbo-theme]) {\n color-scheme: light;\n }\n }\n \n /* ===================================\n MODO COMPACTO - ESTILOS ESPECÍFICOS \n =================================== */\n \n /* Activación del modo compacto por atributo o clase */\n [data-limbo-compact="true"],\n .limbo-compact-mode {\n /* Componentes base más pequeños */\n --limbo-font-size-md: var(--limbo-font-size-compact-md);\n --limbo-font-size-sm: var(--limbo-font-size-compact-sm);\n --limbo-font-size-lg: var(--limbo-font-size-compact-lg);\n --limbo-spacing: var(--limbo-spacing-compact);\n --limbo-radius-md: var(--limbo-radius-compact);\n --limbo-gap: var(--limbo-gap-compact);\n }\n \n /* Botones compactos */\n [data-limbo-compact="true"] .limbo-button,\n .limbo-compact-mode .limbo-button {\n height: var(--limbo-button-height-compact);\n padding: var(--limbo-spacing-compact-sm) var(--limbo-spacing-compact);\n font-size: var(--limbo-font-size-compact-sm);\n border-radius: var(--limbo-radius-compact);\n min-width: auto;\n }\n \n /* Inputs compactos */\n [data-limbo-compact="true"] .limbo-input,\n .limbo-compact-mode .limbo-input {\n height: var(--limbo-input-height-compact);\n padding: var(--limbo-spacing-compact-sm) var(--limbo-spacing-compact);\n font-size: var(--limbo-font-size-compact-md);\n border-radius: var(--limbo-radius-compact);\n }\n \n /* Cards compactas */\n [data-limbo-compact="true"] .limbo-card,\n .limbo-compact-mode .limbo-card {\n padding: var(--limbo-card-padding-compact);\n border-radius: var(--limbo-radius-compact-lg);\n }\n \n /* Modales compactos */\n [data-limbo-compact="true"] .limbo-modal,\n .limbo-compact-mode .limbo-modal {\n padding: var(--limbo-modal-padding-compact);\n border-radius: var(--limbo-radius-compact-lg);\n max-width: 90vw;\n max-height: 90vh;\n }\n \n /* Tabs compactas */\n [data-limbo-compact="true"] .limbo-tabs,\n .limbo-compact-mode .limbo-tabs {\n gap: var(--limbo-gap-compact-sm);\n }\n \n [data-limbo-compact="true"] .limbo-tab,\n .limbo-compact-mode .limbo-tab {\n padding: var(--limbo-spacing-compact-sm) var(--limbo-spacing-compact);\n font-size: var(--limbo-font-size-compact-sm);\n border-radius: var(--limbo-radius-compact-sm);\n }\n \n /* Gallery compacta */\n [data-limbo-compact="true"] .limbo-gallery,\n .limbo-compact-mode .limbo-gallery {\n gap: var(--limbo-gap-compact-sm);\n }\n \n [data-limbo-compact="true"] .limbo-gallery-item,\n .limbo-compact-mode .limbo-gallery-item {\n border-radius: var(--limbo-radius-compact);\n min-height: 120px; /* Más pequeño para móviles */\n }\n \n /* Notificaciones compactas */\n [data-limbo-compact="true"] .limbo-notification,\n .limbo-compact-mode .limbo-notification {\n padding: var(--limbo-spacing-compact-sm) var(--limbo-spacing-compact);\n font-size: var(--limbo-font-size-compact-sm);\n border-radius: var(--limbo-radius-compact);\n }\n \n /* Progress indicators compactos */\n [data-limbo-compact="true"] .limbo-progress,\n .limbo-compact-mode .limbo-progress {\n height: 3px; /* Más delgado */\n }\n \n [data-limbo-compact="true"] .limbo-progress-circular,\n .limbo-compact-mode .limbo-progress-circular {\n width: 20px;\n height: 20px;\n }\n \n /* Auto-activación en pantallas pequeñas */\n @media (max-width: 768px) {\n :root[data-limbo-compact="auto"],\n .limbo-component[data-limbo-compact="auto"] {\n /* Aplicar automáticamente estilos compactos */\n --limbo-font-size-md: var(--limbo-font-size-compact-md);\n --limbo-font-size-sm: var(--limbo-font-size-compact-sm);\n --limbo-spacing: var(--limbo-spacing-compact);\n --limbo-radius-md: var(--limbo-radius-compact);\n --limbo-gap: var(--limbo-gap-compact);\n }\n \n /* Modal full-screen en móvil cuando es compacto */\n [data-limbo-compact="auto"] .limbo-modal,\n [data-limbo-compact="true"] .limbo-modal {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n width: 100vw;\n height: 100vh;\n max-width: 100vw;\n max-height: 100vh;\n border-radius: 0;\n margin: 0;\n }\n \n /* Tabs en accordion en móvil */\n [data-limbo-compact="auto"] .limbo-tabs,\n [data-limbo-compact="true"] .limbo-tabs {\n flex-direction: column;\n width: 100%;\n }\n \n /* Gallery de 2 columnas en móvil */\n [data-limbo-compact="auto"] .limbo-gallery,\n [data-limbo-compact="true"] .limbo-gallery {\n grid-template-columns: 1fr 1fr;\n gap: var(--limbo-gap-compact);\n }\n }\n \n /* Touch targets más grandes en móviles */\n @media (max-width: 768px) and (pointer: coarse) {\n [data-limbo-compact="auto"] .limbo-button,\n [data-limbo-compact="true"] .limbo-button {\n min-height: 44px; /* Tamaño mínimo de toque recomendado */\n padding: var(--limbo-spacing-compact) var(--limbo-spacing-compact-lg);\n }\n \n [data-limbo-compact="auto"] .limbo-tab,\n [data-limbo-compact="true"] .limbo-tab {\n min-height: 44px;\n }\n }\n `,t=document.createElement("style");t.id="limbo-theme-styles",t.textContent=e,document.head.appendChild(t)}applyTheme(e,t={}){const n=this._getTheme(e);if(!n)return console.warn(`Theme '${e}' not found`),!1;const l=this.currentTheme;return this._applyThemeVariables(n,t.scope),this._updateThemeAttributes(n.name),this.config.theme.storage&&!t.temporary&&this._saveThemePreference(n.name),this.currentTheme=n.name,this._triggerChangeCallbacks(n.name,l),!0}toggleTheme(e="light",t="dark"){const n=this.currentTheme===e?t:e;return this.applyTheme(n)}applyAutoTheme(){const e=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";return this.applyTheme(e)}registerTheme(e,t){const n={name:e,displayName:t.displayName||e,variables:t.variables||{},extends:t.extends||null,...t};if(n.extends){const e=this._getTheme(n.extends);e&&(n.variables={...e.variables,...n.variables})}return this.customThemes.set(e,n),this}removeTheme(e){if(this.config.presets[e])return console.warn(`Cannot remove predefined theme: ${e}`),!1;const t=this.customThemes.delete(e);return t&&this.currentTheme===e&&this.applyTheme(this.config.inheritance.fallbackTheme),t}getAvailableThemes(){const e=Object.keys(this.config.presets),t=Array.from(this.customThemes.keys());return{presets:e,custom:t,all:[...e,...t]}}getCurrentTheme(){return{name:this.currentTheme,theme:this._getTheme(this.currentTheme),isCustom:this.customThemes.has(this.currentTheme),variables:this._getCurrentVariables()}}enableCompactMode(e={}){const t={element:document.documentElement,persist:!0,...e};return t.element.setAttribute("data-limbo-compact","true"),t.element.classList.add("limbo-compact-mode"),this.isCompactMode=!0,t.persist&&this.config.compact.persistPreference&&this._saveCompactPreference(!0),this._triggerCompactChange(!0),this}disableCompactMode(e={}){const t={element:document.documentElement,persist:!0,...e};return t.element.setAttribute("data-limbo-compact","false"),t.element.classList.remove("limbo-compact-mode"),this.isCompactMode=!1,t.persist&&this.config.compact.persistPreference&&this._saveCompactPreference(!1),this._triggerCompactChange(!1),this}toggleCompactMode(e={}){return this.isCompactMode?this.disableCompactMode(e):this.enableCompactMode(e)}applyAutoCompactMode(){const e=this._shouldUseCompactMode();return e&&!this.isCompactMode?this.enableCompactMode({persist:!1}):!e&&this.isCompactMode&&this.disableCompactMode({persist:!1}),this}getCompactState(){return{isEnabled:this.isCompactMode,isAuto:this.config.compact.auto,breakpoint:this.config.compact.breakpoint,currentViewport:window.innerWidth,shouldBeCompact:this._shouldUseCompactMode()}}_shouldUseCompactMode(){if(!this.config.compact.auto)return this.config.compact.enabled;const e=window.innerWidth<=this.config.compact.breakpoint,t=/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),n="ontouchstart"in window||navigator.maxTouchPoints>0;return!(!this.config.compact.forceOnMobile||!t&&!n)||e}_saveCompactPreference(e){try{localStorage.setItem("limbo-compact-preference",e.toString())}catch(t){console.warn("Could not save compact preference:",t)}}_loadCompactPreference(){try{return"true"===localStorage.getItem("limbo-compact-preference")}catch(e){return console.warn("Could not load compact preference:",e),null}}_triggerCompactChange(e){this.changeCallbacks.forEach(t=>{try{t({type:"compact",isCompact:e,viewport:window.innerWidth,timestamp:Date.now()})}catch(n){console.error("Error in compact mode change callback:",n)}})}_inheritPortalTheme(){const e=this._detectPortalTheme();return e?(this.registerTheme("portal-inherited",e),"portal-inherited"):null}_detectPortalTheme(){const e={name:"portal-detected",displayName:"Tema del Portal",variables:{}};for(const t of this.config.inheritance.portalSelectors){const n=document.querySelector(t);if(n){const t=this._extractCSSVariables(n);Object.keys(t).length>0&&(e.variables={...e.variables,...t});const l=n.getAttribute("data-theme")||n.getAttribute("class")?.match(/theme-(\w+)/)||n.getAttribute("class")?.match(/(\w+)-theme/);l&&(e.detectedName=Array.isArray(l)?l[1]:l)}}return Object.keys(e.variables).length>0?e:null}_extractCSSVariables(e){const t={},n=getComputedStyle(e);["primary","primary-hover","primary-light","primary-dark","bg-primary","bg-secondary","bg-tertiary","bg-card","bg-input","text-primary","text-secondary","text-tertiary","text-inverse","border-light","border-medium","border-strong","border-focus","success","error","warning","info","shadow-sm","shadow-md","shadow-lg","shadow-xl","radius-sm","radius-md","radius-lg","radius-xl"].forEach(e=>{const l=`--limbo-${e}`,r=n.getPropertyValue(l).trim();r&&(t[l]=r)});return["--primary-color","--background-color","--text-color","--border-color","--accent-color","--surface-color"].forEach(e=>{const l=n.getPropertyValue(e).trim();if(l){const n=this._mapGenericToLimbo(e,l);n&&Object.assign(t,n)}}),t}_mapGenericToLimbo(e,t){return{"--primary-color":{"--limbo-primary":t},"--background-color":{"--limbo-bg-primary":t},"--text-color":{"--limbo-text-primary":t},"--border-color":{"--limbo-border-light":t},"--accent-color":{"--limbo-primary":t},"--surface-color":{"--limbo-bg-card":t}}[e]||null}_applyInitialTheme(){let e=this.config.inheritance.fallbackTheme;if(this.config.theme.storage){const t=this._loadThemePreference();t&&this._getTheme(t)&&(e=t)}const t=document.documentElement.getAttribute("data-limbo-theme");t&&this._getTheme(t)&&(e=t);const n=this._inheritPortalTheme();n&&(e=n),this.config.theme.auto&&"auto"===e&&(e=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),this.applyTheme(e,{temporary:!1})}_applyInitialCompactMode(){let e=!1;if(this.config.compact.persistPreference){const t=this._loadCompactPreference();null!==t&&(e=t)}const t=document.documentElement.getAttribute("data-limbo-compact");"true"===t?e=!0:"false"===t&&(e=!1),("auto"===t||this.config.compact.auto)&&(e=this._shouldUseCompactMode()),e?this.enableCompactMode({persist:!1}):this.disableCompactMode({persist:!1})}_applyThemeVariables(e,t=document.documentElement){const n="string"==typeof t?document.querySelector(t):t;n?(Object.entries(e.variables).forEach(([e,t])=>{n.style.setProperty(e,t),this.appliedStyles.add(`${n.tagName}:${e}`)}),this.themeCache.set(e.name,{theme:e,appliedAt:Date.now(),scope:n})):console.warn("Theme scope element not found")}_updateThemeAttributes(e){document.documentElement.setAttribute("data-limbo-theme",e),document.documentElement.classList.remove("limbo-theme-light","limbo-theme-dark","limbo-theme-auto"),document.documentElement.classList.add(`limbo-theme-${e}`),this._updateMetaThemeColor(e)}_updateMetaThemeColor(e){const t=this._getTheme(e);if(!t)return;const n=t.variables["--limbo-primary"]||"#3b82f6";let l=document.querySelector('meta[name="theme-color"]');l||(l=document.createElement("meta"),l.name="theme-color",document.head.appendChild(l)),l.content=n}_getTheme(e){return this.config.presets[e]?this.config.presets[e]:this.customThemes.has(e)?this.customThemes.get(e):null}_getCurrentVariables(){const e=this._getTheme(this.currentTheme);if(!e)return{};const t=getComputedStyle(document.documentElement),n={};return Object.keys(e.variables).forEach(e=>{n[e]=t.getPropertyValue(e).trim()}),n}_saveThemePreference(e){try{localStorage.setItem("limbo-theme-preference",e)}catch(t){console.warn("Could not save theme preference:",t)}}_loadThemePreference(){try{return localStorage.getItem("limbo-theme-preference")}catch(e){return console.warn("Could not load theme preference:",e),null}}_loadCustomThemes(){try{const e=localStorage.getItem("limbo-custom-themes");if(e){const t=JSON.parse(e);Object.entries(t).forEach(([e,t])=>{this.customThemes.set(e,t)})}}catch(e){console.warn("Could not load custom themes:",e)}}_saveCustomThemes(){try{const e=Object.fromEntries(this.customThemes);localStorage.setItem("limbo-custom-themes",JSON.stringify(e))}catch(e){console.warn("Could not save custom themes:",e)}}_setupObservers(){this.config.theme.detectSystem&&this._setupSystemObserver(),this.config.theme.storage&&this._setupStorageObserver(),this._setupMutationObserver(),this.config.compact.auto&&this._setupViewportObserver()}_setupSystemObserver(){const e=window.matchMedia("(prefers-color-scheme: dark)");e.addEventListener("change",e=>{if("auto"===this.currentTheme||this.config.theme.auto){const t=e.matches?"dark":"light";this.applyTheme(t,{temporary:!0})}}),this.mediaQueryObserver=e}_setupStorageObserver(){const e=e=>{"limbo-theme-preference"===e.key&&e.newValue!==this.currentTheme&&this._getTheme(e.newValue)&&this.applyTheme(e.newValue)};window.addEventListener("storage",e),this.storageListener=e}_setupMutationObserver(){const e=new MutationObserver(e=>{e.forEach(e=>{if("attributes"===e.type&&"data-limbo-theme"===e.attributeName){const t=e.target.getAttribute("data-limbo-theme");t&&t!==this.currentTheme&&this._getTheme(t)&&this.applyTheme(t)}})});e.observe(document.documentElement,{attributes:!0,attributeFilter:["data-limbo-theme"]}),this.mutationObserver=e}_setupViewportObserver(){const e=`(max-width: ${this.config.compact.breakpoint}px)`,t=window.matchMedia(e);t.addEventListener("change",()=>{("auto"===document.documentElement.getAttribute("data-limbo-compact")||this.config.compact.auto)&&this.applyAutoCompactMode()}),this.compactObserver=t,window.addEventListener("orientationchange",()=>{setTimeout(()=>{("auto"===document.documentElement.getAttribute("data-limbo-compact")||this.config.compact.auto)&&this.applyAutoCompactMode()},100)})}onThemeChange(e){return this.changeCallbacks.add(e),()=>this.changeCallbacks.delete(e)}_triggerChangeCallbacks(e,t){this.changeCallbacks.forEach(n=>{try{n({theme:e,previousTheme:t,themeData:this._getTheme(e),variables:this._getCurrentVariables()})}catch(l){console.error("Error in theme change callback:",l)}})}generateThemeFromColors(e,t){const n={name:e,displayName:e,variables:{}};t.primary&&(n.variables["--limbo-primary"]=t.primary,n.variables["--limbo-primary-hover"]=this._darkenColor(t.primary,10),n.variables["--limbo-primary-light"]=this._lightenColor(t.primary,40),n.variables["--limbo-primary-dark"]=this._darkenColor(t.primary,20)),t.background&&(n.variables["--limbo-bg-primary"]=t.background,n.variables["--limbo-bg-secondary"]=this._lightenColor(t.background,5),n.variables["--limbo-bg-tertiary"]=this._lightenColor(t.background,10),n.variables["--limbo-bg-card"]=t.background),t.text&&(n.variables["--limbo-text-primary"]=t.text,n.variables["--limbo-text-secondary"]=this._lightenColor(t.text,20),n.variables["--limbo-text-tertiary"]=this._lightenColor(t.text,40));const l=this._getTheme(this.config.inheritance.fallbackTheme);return l&&(n.variables={...l.variables,...n.variables}),this.registerTheme(e,n),n}_darkenColor(e,t){const n=parseInt(e.replace("#",""),16),l=Math.round(2.55*t),r=(n>>16)-l,a=(n>>8&255)-l,i=(255&n)-l;return"#"+(16777216+65536*(r<255?r<1?0:r:255)+256*(a<255?a<1?0:a:255)+(i<255?i<1?0:i:255)).toString(16).slice(1)}_lightenColor(e,t){const n=parseInt(e.replace("#",""),16),l=Math.round(2.55*t),r=(n>>16)+l,a=(n>>8&255)+l,i=(255&n)+l;return"#"+(16777216+65536*(r<255?r<1?0:r:255)+256*(a<255?a<1?0:a:255)+(i<255?i<1?0:i:255)).toString(16).slice(1)}_deepMerge(e,t){const n={...e};return Object.keys(t).forEach(l=>{t[l]&&"object"==typeof t[l]&&!Array.isArray(t[l])?n[l]=this._deepMerge(e[l]||{},t[l]):n[l]=t[l]}),n}getThemeInfo(){return{current:this.getCurrentTheme(),available:this.getAvailableThemes(),compact:this.getCompactState(),config:this.config,isInitialized:this.isInitialized,cache:{themes:this.themeCache.size,applied:this.appliedStyles.size},observers:{system:!!this.mediaQueryObserver,storage:!!this.storageListener,mutation:!!this.mutationObserver,viewport:!!this.compactObserver}}}debug(){return console.table(this.getThemeInfo()),this.getThemeInfo()}destroy(){this.mediaQueryObserver&&this.mediaQueryObserver.removeEventListener("change",this._setupSystemObserver),this.storageListener&&window.removeEventListener("storage",this.storageListener),this.mutationObserver&&this.mutationObserver.disconnect(),this.compactObserver&&this.compactObserver.removeEventListener("change",this._setupViewportObserver),this.changeCallbacks.clear(),this.themeCache.clear(),this.appliedStyles.clear(),this._saveCustomThemes();const e=document.getElementById("limbo-theme-styles");e&&e.remove(),this.isInitialized=!1}}const Ul={border:"none",borderRadius:"6px",cursor:"pointer",fontFamily:"inherit",fontWeight:"500",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"6px",transition:"background 0.2s ease, transform 0.1s ease",userSelect:"none",textDecoration:"none",lineHeight:"1.25"},Bl={bg:"#001978",hover:"#334793"},Wl={bg:"#10b981",hover:"#059669"},ql={bg:"#9ca3af",hover:"#9ca3af"};class Vl extends HTMLElement{constructor(){super(),this._btn=null,this._limboInstance=null}connectedCallback(){this._ensureButton(),this._syncButton()}disconnectedCallback(){this._destroyLimboInstance()}static get observedAttributes(){return["accept","has-file","disabled","compact","label-select","label-change","return-format","button-class","existing-url","mandatory-crops","public-key","token","auth-mode"]}attributeChangedCallback(){this._btn&&this._syncButton()}markSelected(e){this.setAttribute("has-file",""),e&&this.setAttribute("existing-url",e),this._syncButton()}clearSelection(){this.removeAttribute("has-file"),this.removeAttribute("existing-url"),this._syncButton()}open(){this._open()}_ensureButton(){this._btn||(this._btn=document.createElement("button"),this._btn.type="button",this._btn.classList.add("limbo-selector-btn","limbo-trigger-button","mecano:my-2"),this._btn.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),this._open()}),this.appendChild(this._btn))}_syncButton(){if(!this._btn)return;const e=this.getAttribute("accept")||null,t=this.hasAttribute("has-file"),n=this.hasAttribute("disabled"),l=this.hasAttribute("compact"),r=this.getAttribute("label-select")||null,a=this.getAttribute("label-change")||null,i=this.getAttribute("button-class")||null;this._btn.textContent=t?a||v(e,!0):r||v(e,!1),this._btn.disabled=n,i&&i.split(/\s+/).filter(Boolean).forEach(e=>this._btn.classList.add(e));const o=n?ql:t?Wl:Bl;Object.assign(this._btn.style,{...Ul,fontSize:l?"12px":"14px",padding:l?"6px 12px":"8px 16px",background:o.bg,color:"white",opacity:n?"0.55":"1",cursor:n?"not-allowed":"pointer"}),this._btn.onmouseenter=()=>{n||(this._btn.style.background=o.hover,this._btn.style.transform="translateY(-1px)",this._btn.style.boxShadow="0 4px 10px rgba(0,0,0,0.18)")},this._btn.onmouseleave=()=>{this._btn.style.background=o.bg,this._btn.style.transform="translateY(0)",this._btn.style.boxShadow="none"}}_open(){const e=window.Limbo||window.limboCore;if(!e)return void console.warn("[LimboSelector] window.Limbo no encontrado. Asegúrate de que el script de Limbo está cargado antes de usar <limbo-selector>.");const t=this.getAttribute("accept")||null,n=this.getAttribute("return-format")||"url",l=this.getAttribute("existing-url")||null,r=this.getAttribute("public-key")||null,a=this.getAttribute("token")||null,i=this.getAttribute("auth-mode")||null;(r||a)&&e.configure({...r&&{publicKey:r},...a&&{token:a},authMode:i||(a?"manual":"session")}),e.config?.setGlobal&&e.config.setGlobal({interaction:{allowSelection:!0,allowCropping:!0,selectionMode:"direct"}});let o=null;const s=this.getAttribute("mandatory-crops");if(s)try{o=JSON.parse(s)}catch{}this._destroyLimboInstance();try{const r={mode:"modal",modeUI:"full",modalSize:"fullscreen",features:["gallery","upload","cropper"],title:"Seleccionar archivo",validation:{accept:t},returnConfig:{format:n},initialImageUrl:l,interaction:{allowSelection:!0,allowCropping:!0},cropper:o?.length>0?{mandatoryCrops:o,allowAdditionalCrops:!0,maxCrops:10}:null},a=async e=>{const t="string"==typeof e?e:e?.images?.[0]?.url||e?.original?.url||e?.url||"";this.setAttribute("has-file",""),t&&this.setAttribute("existing-url",t),this._syncButton(),this.dispatchEvent(new CustomEvent("limbo:change",{detail:{data:e,url:t},bubbles:!0,composed:!0}))};e.events.emit("autoInputs:modalRequest",{config:r,input:null,callback:a})}catch(c){console.error("[LimboSelector] Error al abrir modal de Limbo:",c)}}_handleResult(e,t){if(this._limboInstance!==t)return;const n="string"==typeof e?e:e?.url||e?.master?.urlSigned||e?.master?.url||e?.asset?.url||e?.original?.url||e?.crops?.[0]?.url||e?.images?.[0]?.url||"";this.setAttribute("has-file",""),n&&this.setAttribute("existing-url",n),this._syncButton(),this.dispatchEvent(new CustomEvent("limbo:change",{detail:{data:e,url:n},bubbles:!0,composed:!0}));try{t?.close?.()}catch{}this._limboInstance=null}_destroyLimboInstance(){if(this._limboInstance){try{this._limboInstance.destroy?.()}catch{}this._limboInstance=null}}}function Hl(e="limbo-selector"){"undefined"==typeof customElements||customElements.get(e)||customElements.define(e,Vl)}const Kl=new class{constructor(){this.config=new C,this.instances=new Ml,this.autoInputs=new Dl,this.events=new Rl,this.modals=new Ol,this.theme=new jl,this.containerQueryDetector=M,this._setupInternalListeners(),this._initializeContainerQueries()}configure(e){this.config.setGlobal(e);const t={};var n;return"publicKey"in e&&(t.publicKey=e.publicKey),"apiKey"in e&&(t.apiKey=e.apiKey),"token"in e&&(t.token=e.token),"authMode"in e&&(t.authMode=e.authMode),"tokenProvider"in e&&(t.tokenProvider=e.tokenProvider),"prod"in e&&(t.prod=Boolean(e.prod)),"mode"in e&&(t.mode=e.mode),"callbacks"in e&&(t.callbacks=e.callbacks),"token"in(n=t)&&n.token!==U.token&&(B=!1),U={...U,...n},U.authMode||(U.token?U.authMode="manual":U.authMode="session"),this.config}setToken(e){return q(e),this.config.setGlobal({token:e}),this}create(e){const t=this.config.merge(e);return this.instances.create(t,this.events,this.modals)}configureAutoInputs(e){return this.autoInputs.configure(e,this.config,this.events)}setTheme(e){return e&&(this.config.set("theme",e),this.theme.setTheme(e),this.events.emit("theme:changed",{theme:e})),this}getTheme(){return this.theme.getCurrentTheme()}scanAndActivate(e=null){const t=this.autoInputs.config?.dataset||"data-limbo-input-file",n=e||`[${t}]`,l=document.querySelectorAll(n);if(0===l.length)return{found:0,processed:0,skipped:0};let r=0,a=0;return l.forEach(e=>{try{this.autoInputs._processInput(e),r++}catch(t){console.warn(`⚠️ Limbo: Error procesando input ${e.id||e.name}:`,t),a++}}),this.events.emit("limbo:scanCompleted",{found:l.length,processed:r,skipped:a,inputs:Array.from(l)}),{found:l.length,processed:r,skipped:a}}_initializeContainerQueries(){this.containerQueryDetector.observeResize(),setTimeout(()=>{document.querySelectorAll(".limbo-component-container-wrapper").forEach(e=>{this.containerQueryDetector.applyResponsiveClasses(e)})},100)}rescan(e=document){const t=this.autoInputs.config?.dataset||"data-limbo-input-file",n=e.querySelectorAll(`[${t}]`);let l=0;return n.forEach(e=>{if(!this.autoInputs.instances.has(this.autoInputs._getInputId(e)))try{this.autoInputs._processInput(e),l++}catch(t){console.warn("⚠️ Limbo: Error procesando nuevo input:",t)}}),l}init(e){const t=this._mapLegacyOptions(e);return this.create(t)}getInstances(){return this.instances.getAll()}destroy(){this.instances.destroyAll(),this.autoInputs.cleanup(),this.events.cleanup(),this.theme.removeTheme()}_mapLegacyOptions(e){return{container:e.container||"#image-manager",mode:"embed",features:["gallery","upload","cropper"],apiKey:e.apiKey,prod:e.prod||!1,url:void 0===e.url||e.url}}_setupInternalListeners(){this.events.on("autoInputs:modalRequest",({config:e,callback:t,input:n})=>{this._handleAutoInputModalRequest({config:e,callback:t,input:n})})}_handleAutoInputModalRequest({config:e,callback:t,input:n}){const l=n,r=async n=>{let r={};if(n.crops&&n.crops.length>0){const e=n.asset||n.original;r.original={url:e?.url||e?.urlSigned||n.originalUrl,width:e?.width||n.originalWidth,height:e?.height||n.originalHeight,assetId:e?.id||n.assetId},r.images=n.crops.map(e=>({url:e.url||e.urlSigned,width:e.width,height:e.height,name:e.name||e.filename}))}else n.asset?r.original={url:n.asset.url||n.asset.urlSigned,width:n.asset.width,height:n.asset.height,assetId:n.asset.id}:n.master?.urlSigned||n.master?.url?r.original={url:n.master.urlSigned||n.master.url,width:n.master.width||n.width,height:n.master.height||n.height,assetId:n.assetId}:n.url||n.urlSigned?r.original={url:n.url||n.urlSigned,width:n.width,height:n.height,assetId:n.assetId||n.id}:(console.warn("[Limbo] handleResult: formato de datos no reconocido",n),r=n);if(l){var a=e?.returnConfig?.format||"json",i="";i="url"===a?r.images?.[0]?.url||r.original?.url||"":"assetId"===a?r.original?.assetId||"":JSON.stringify(r),l.value=i,l.dispatchEvent(new Event("change",{bubbles:!0})),console.log("[Limbo] ✅ Valor asignado al input:",l.value?.substring(0,80))}try{await t(r)}catch(o){}c.close()},a={...e,mode:"modal",autoDestroy:!0,interaction:{allowSelection:!0,allowCropping:!0,...e.interaction},callbacks:{onSelect:e=>{r(e)},onCropsSaved:e=>{r(e)},onCropperComplete:e=>{r(e)},onUpload:t=>{"upload-only"!==e.modeUI||e.features?.includes("cropper")||r(t)},onClose:()=>{}}},i=e.validation?.accept||null,o=i?f(i):null,s=!o||o.isAllTypes||o.includesImages;if(e.initialImageUrl&&s){const t=this._extractAssetIdFromUrl(e.initialImageUrl)||e.existingData?.original?.assetId||null;t&&(a._externalImage={url:e.initialImageUrl,filename:e.initialImageUrl.split("/").pop()?.split("?")[0]||"image.jpg",width:1920,height:1080,mime_type:"image/jpeg",id:t})}e.cropper&&(a.cropper=e.cropper),this.config.setGlobal({interaction:{allowSelection:!0,allowCropping:!0,...e.interaction}});const c=this.create(a);c.open()}_extractAssetIdFromUrl(e){if(!e)return null;try{const t=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,n=e.match(t);return n&&n.length>=2?n[1]:n&&1===n.length?n[0]:null}catch(t){return console.warn("Error extracting asset ID from URL:",t),null}}openGallery(e={}){const t=this.create({mode:"modal",modeUI:"gallery-only",features:["gallery"],autoDestroy:!0,modal:{title:e.title||"Seleccionar Imagen",size:e.size||"large"},validation:{accept:e.accept||null},callbacks:{onSelect:n=>{e.onSelect?.(n),!1!==e.autoClose&&t.close()}},...e});return t.open(),t}openUploader(e={}){const t=!1!==e.redirectToGallery?["upload","gallery"]:["upload"],n=this.create({mode:"modal",modeUI:!1!==e.redirectToGallery?"full":"upload-only",features:t,autoDestroy:!0,modal:{title:e.title||"Subir Imagen",size:e.size||"medium"},validation:{accept:e.accept||null},callbacks:{onUpload:t=>{e.onUpload?.(t),!1===e.autoClose||e.redirectToGallery||n.close()}},...e});return n.open(),n}openCropper(e,t={}){if(!e)throw new Error("Limbo.openCropper: imageUrl es requerido");const n={url:e,filename:t.filename||"image.jpg",width:t.width||1920,height:t.height||1080,mime_type:t.mimeType||"image/jpeg",id:t.assetId||`external-${Date.now()}`},l=this.create({mode:"modal",modeUI:"crop-only",features:["cropper"],autoDestroy:!0,modal:{title:t.title||"Recortar Imagen",size:"xlarge"},cropper:{mandatoryCrops:t.mandatoryCrops||[],allowCustomCrops:!1!==t.allowCustomCrops,enforceRequiredCrops:!1!==t.enforceRequiredCrops},callbacks:{onCropperComplete:e=>{t.onComplete?.(e),!1!==t.autoClose&&l.close()},onCropperCancelled:e=>{t.onCancelled?.(e),!1!==t.autoClose&&l.close()},onCropperError:e=>{t.onError?.(e)}},_externalImage:n,...t});return l.open(),l}createInlineGallery(e,t={}){return this.create({container:e,mode:"embed",modeUI:"gallery-only",features:["gallery"],validation:{accept:t.accept||null},callbacks:{onSelect:t.onSelect,onDelete:t.onDelete},...t})}createInlineUploader(e,t={}){return this.create({container:e,mode:"embed",modeUI:"upload-only",features:["upload"],validation:{accept:t.accept||null},callbacks:{onUpload:t.onUpload},...t})}createStandaloneCropper(e,t,n={}){if(!e)throw new Error("Limbo.createStandaloneCropper: container es requerido");if(!t)throw new Error("Limbo.createStandaloneCropper: imageUrl es requerido");const l={url:t,filename:n.filename||"image.jpg",width:n.width||1920,height:n.height||1080,mime_type:n.mimeType||"image/jpeg",id:n.assetId||`external-${Date.now()}`};return this.create({container:e,mode:"embed",modeUI:"crop-only",features:["cropper"],autoHideOnComplete:!1!==n.autoHideOnComplete,cropper:{mandatoryCrops:n.mandatoryCrops||[],allowCustomCrops:!1!==n.allowCustomCrops,enforceRequiredCrops:!1!==n.enforceRequiredCrops},callbacks:{onCropperComplete:n.onComplete,onCropperCancelled:n.onCancelled,onCropperError:n.onError},_externalImage:l,...n})}createFullSelector(e,t={}){return this.create({container:e,mode:t.mode||"embed",modeUI:"full",features:["gallery","upload","cropper"],validation:{accept:t.accept||null},callbacks:{onSelect:t.onSelect,onUpload:t.onUpload,onDelete:t.onDelete,onCropsSaved:t.onCropsSaved},...t})}};"undefined"!=typeof window&&(window.Limbo=Kl,window.limboCore=Kl,Hl());"undefined"!=typeof window&&document.querySelector("#root")&&(Kl.configure({prod:!1,publicKey:"pk_e464fd744106b7a8d63d453c4bd02582",authMode:"session"}),Kl.create({container:"#root",mode:"embed",modeUI:"full",features:["gallery","upload","cropper"],title:"Limbo Image Manager - Development",url:!0}),Kl.configureAutoInputs({dataset:"data-limbo-input-file",return:"json",features:["gallery","upload","cropper"],modeUI:"full",modalSize:"large",title:"Seleccionar archivo",crops:"free",allowDelete:!1}));export{Se as LIMBO_BASE_URL,Vl as LimboSelector,Ee as decodeHtmlEntities,Kl as default,_e as extractImageUrl,v as getButtonLabel,$e as isValidImageUrl,ze as parseImageData,Ie as prepareImageFieldsForPreview,Hl as registerLimboSelector,Ne as resolveUrl};
|
|
707
|
+
/* @__PURE__ */s("p",{className:"lb:text-gray-600 lb:mb-4",children:"Selecciona una imagen de la galería para comenzar a recortar."})]})]})}const Ml=["button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"]):not([disabled])',"a[href]"].join(", "),Dl=e=>{if("true"===e.getAttribute("aria-hidden"))return!1;if(e.hasAttribute("inert"))return!1;if(e.hasAttribute("hidden"))return!1;let t=e.parentElement;for(;t;){if(t.hasAttribute("inert"))return!1;if("true"===t.getAttribute("aria-hidden"))return!1;t=t.parentElement}return!0};function Rl(e,{onClose:t,isActive:l=!0}={}){n(()=>{if(!l)return;const n=e?.current;if(!n)return;const r=e=>{if("Escape"===e.key)return e.preventDefault(),void t?.();if("Tab"!==e.key)return;const l=(r=n,Array.from(r.querySelectorAll(Ml)).filter(Dl));var r;if(0===l.length)return void e.preventDefault();const a=l[0],i=l[l.length-1],o=document.activeElement;e.shiftKey?o!==a&&n.contains(o)||(e.preventDefault(),i.focus()):o===i&&(e.preventDefault(),a.focus())};return n.addEventListener("keydown",r),()=>n.removeEventListener("keydown",r)},[e,t,l])}function Ol({apiKey:i,onClose:o,prod:u=!1,features:d=["gallery","upload","cropper"],modeUI:b="full",ui:m={showActions:["select","download","copy","delete","crop","variants","rename"],hideActions:[],theme:"light",language:"es",compactMode:!1,showTabs:!0},callbacks:h={},instanceId:p=null,itemsPerPage:g=30,_externalImage:v=null,cropperConfig:y=null,folderConfig:w={include:[],exclude:[],includeNoFolder:!0,showFolderSelector:!0,showFolderFilter:!0,showFolderInfo:!0,allowMoveFolder:!0,allowCreateFolder:!0,defaultFolder:null},allowedCategories:x=null,accept:k=null,returnConfig:C=null}){const S=r(h);n(()=>{S.current=h},[h]);const N=r(null);Rl(N,{onClose:o}),n(()=>{_e(),["limbo_stock_selectedService","limbo_stock_dynamicForm","limbo_stock_stockImages","limbo_stock_currentPage","limbo_stock_paginationInfo","limbo_portals_searchName","limbo_portals_limit","limbo_portals_currentPage","limbo_portals_images","limbo_portals_portalResults","limbo_portals_paginationInfo"].forEach(e=>sessionStorage.removeItem(e))},[]),n(()=>{const e=()=>{["limbo_stock_selectedService","limbo_stock_dynamicForm","limbo_stock_stockImages","limbo_stock_currentPage","limbo_stock_paginationInfo","limbo_portals_searchName","limbo_portals_limit","limbo_portals_currentPage","limbo_portals_images","limbo_portals_portalResults","limbo_portals_paginationInfo"].forEach(e=>sessionStorage.removeItem(e)),he(),_e()},t=t=>{t.persisted&&e()};let n=null;const l=()=>{"hidden"===document.visibilityState?n=Date.now():"visible"===document.visibilityState&&null!==n&&(Date.now()-n>18e5&&e(),n=null)};return window.addEventListener("pageshow",t),document.addEventListener("visibilitychange",l),()=>{window.removeEventListener("pageshow",t),document.removeEventListener("visibilitychange",l)}},[]);const[E,$]=t({name:"",uploadedBy:"",dateFrom:"",dateTo:"",assetType:"",folder:""}),[_,z]=t(w?.defaultFolder||null),T=ge(E.name,400),A=ge(E.uploadedBy,400),L=e.useMemo(()=>f(k||(x?x.map(e=>`${e}/*`).join(","):null)),[k,x]),I=e=>!!e&&(e.startsWith("image/")&&"image/gif"!==e),P=(()=>{let e;switch(b){case"gallery-only":e=["gallery"];break;case"upload-only":e=["upload","cropper"];break;case"crop-only":e=["cropper"];break;case"ia-only":e=["ia"];break;default:e=[...d]}return L.isAllTypes||L.includesImages||(e=e.filter(e=>"cropper"!==e)),e})(),M=()=>P.includes("gallery")?"gallery":P.includes("upload")?"upload":P.includes("cropper")?"cropper":P.includes("ia")?"ia":P[0]||"gallery",[D,F]=t(M()),[j,U]=t(null),B=r(null);n(()=>{!j&&B.current&&(URL.revokeObjectURL(B.current),B.current=null)},[j]);const[W,q]=t(null);n(()=>{v&&(console.log("📸 Imagen externa detectada:",v),U(v),F("cropper"))},[v]),n(()=>{const e=()=>{console.log("[App] Modal cerrado, reseteando estado..."),U(null),F(M())};return window.limboCore?.events&&window.limboCore.events.on("modal:closed",e),()=>{window.limboCore?.events&&window.limboCore.events.off("modal:closed",e)}},[]);const[V,H]=t(1),{isTokenExpired:K,handleTokenExpiredClose:G,handleTokenExpiredReload:Y}=function(){const[e,l]=t(!1),[r,i]=t(!1),o=a(async()=>{const e=X();if("jwt"!==e.authMode||!e.tokenProvider)return!1;i(!0);try{return Q(await e.tokenProvider()),l(!1),!0}catch{return!1}finally{i(!1)}},[]),s=a(e=>{if(401===e?.response?.status){const t=e.response.data;if("token_expired"===t?.error||t?.message?.includes("expired")||t?.message?.includes("caducado")||"string"==typeof t?.error&&t.error.includes("expired"))return l(!0),!0}return!1},[]),c=a(()=>{l(!1)},[]),u=a(()=>{l(!1),window.location.reload()},[]);return n(()=>{const e=e=>{if(!e.detail?.error)return;const t=X();s(e.detail.error)&&("jwt"===t.authMode&&t.tokenProvider&&!e.detail.refreshAttempted?o().then(e=>{e||l(!0)}):l(!0))};return window.addEventListener("tokenExpiredError",e),()=>window.removeEventListener("tokenExpiredError",e)},[s,o]),{isTokenExpired:e,isRefreshing:r,checkTokenExpiration:s,handleTokenExpiredClose:c,handleTokenExpiredReload:u,tryRefreshToken:o}}(),{upload:J,loading:Z,error:ee,uploadedImage:te,reset:ne}=function(){const[e,n]=t(!1),[l,r]=t(null),[a,i]=t(null);return{upload:async(e,t=null,l=null)=>{if(!e)return r("No se ha proporcionado ningún archivo"),null;n(!0),r(null),i(null);try{const n="object"==typeof l?l?.slug:l,r=await oe(e,t,!1,n),a=r.result||r;return i(a),a}catch(a){return r(a.message),null}finally{n(!1)}},loading:e,error:l,uploadedImage:a,reset:()=>{r(null),i(null)}}}(),{deleteImg:le,loading:re,error:ae,reset:ie}=ue(),ce=l(()=>({limit:g,page:V,...T&&{name:T},...A&&{uploadedBy:A},...E.dateFrom&&{dateFrom:E.dateFrom},...E.dateTo&&{dateTo:E.dateTo},...E.assetType&&{asset_type:E.assetType},...!L.isAllTypes&&L.raw&&{accept:L.raw},...E.folder&&{folder:E.folder},...w.include?.length>0&&{folders_include:w.include.join(",")},...0===w.include?.length&&w.exclude?.length>0&&{folders_exclude:w.exclude.join(",")},...(w.include?.length>0||w.exclude?.length>0)&&void 0!==w.includeNoFolder&&{include_no_folder:w.includeNoFolder?"1":"0"}}),[g,V,T,A,E.dateFrom,E.dateTo,E.assetType,E.folder,L.isAllTypes,L.raw,w.include,w.exclude,w.includeNoFolder]),de=P.includes("gallery"),{images:be,loading:me,error:we,pagination:xe,invalidateCache:ke,setImages:Ce,refetch:Se}=pe(i,u,ce,de);n(()=>{const e=()=>{Se()};return document.addEventListener("limbo:variantsCleared",e),document.addEventListener("limbo:variantDeleted",e),()=>{document.removeEventListener("limbo:variantsCleared",e),document.removeEventListener("limbo:variantDeleted",e)}},[Se]);const{refreshVariants:Ne}=fe(),Ee=a((e,t=null)=>J(e,t,_?.slug||_),[J,_]),{handleDelete:ze,handleAssetFolderChange:Te,handleRenameAsset:Ae,handleVariantCreated:Le}=function({callbacksRef:e,deleteImg:t,evictFromCache:n,invalidateCache:l,refreshVariants:r,images:i,setImages:o,setCurrentPage:s,selectedImage:c,setSelectedImage:u,setActiveTab:d}){return{handleDelete:async r=>{if(!confirm("¿Estás seguro de que deseas eliminar este archivo? Esta acción también eliminará todos sus recortes."))return;const a=i.find(e=>e.id===r);await t(r)&&(a?.url&&n(a.url),l(),s(1),o(e=>e.filter(e=>e.id!==r)),c&&c.id===r&&(u(null),d("gallery")),e.current.onDelete&&e.current.onDelete({assetId:r}))},handleAssetFolderChange:async(e,t)=>{const n=t?.slug||null;try{return await se(e.id,{folder:n}),l(),o(n=>n.map(n=>n.id===e.id?{...n,folder:t??null}:n)),t}catch(r){throw console.error("Error al cambiar carpeta:",r),r}},handleRenameAsset:a(async(e,t)=>{const n=await se(e.id,{original_filename:t}),r=n?.result||{};return l(),o(n=>n.map(n=>n.id!==e.id?n:{...n,filename:r.filename??t,...r.url&&{url:r.url},...void 0!==r.url_webp&&{url_webp:r.url_webp}})),n},[l,o]),handleVariantCreated:(e,t)=>{r(e),o(t=>t.map(t=>t.id===e?{...t,variants_count:(t.variants_count||0)+1}:t)),l()}}}({callbacksRef:S,deleteImg:le,evictFromCache:$e,invalidateCache:ke,refreshVariants:Ne,images:be,setImages:Ce,setCurrentPage:H,selectedImage:j,setSelectedImage:U,setActiveTab:F}),{handleUploadAndCrop:Ie,handleVideoSelect:Pe}=function({callbacksRef:e,upload:t,refetch:n,activeFeatures:l,setActiveTab:r,setSelectedImage:i,setCurrentPage:o,setSuccessMessage:s,instanceId:c,selectedUploadFolder:u,tempBlobUrlRef:d}){return{handleUploadAndCrop:async a=>{if(!a.type?.startsWith("image/")||"image/gif"===a.type){const i=u?.slug||u,s=await t(a,null,i);return void(s&&(n(),o(1),l.includes("gallery")&&r("gallery"),e.current.onUpload&&e.current.onUpload({assetId:s.id,url:s.url,fileName:s.filename,mime:s.mime_type,width:s.width,height:s.height,instanceId:c})))}const s=URL.createObjectURL(a),b=await new Promise(e=>{const t=new Image;t.onload=()=>{e({width:t.naturalWidth,height:t.naturalHeight}),URL.revokeObjectURL(s)},t.onerror=()=>{e({width:1920,height:1080}),URL.revokeObjectURL(s)},t.src=s}),m={file:a,filename:a.name,mime_type:a.type,url:(()=>{const e=URL.createObjectURL(a);return d.current=e,e})(),width:b.width,height:b.height};if(i(m),l.includes("cropper"))r("cropper");else{const l=u?.slug||u,i=await t(a,null,l);i&&(n(),o(1),r("gallery"),e.current.onUpload&&e.current.onUpload({assetId:i.id,url:i.url,fileName:i.filename,mime:i.mime_type,width:i.width,height:i.height,instanceId:c}))}},handleVideoSelect:a(t=>{const n={...t,instanceId:c};e.current.onSelect&&e.current.onSelect(n),window.limboCore?.events&&window.limboCore.events.emit("select",n),"modal"===((window.limboCore?.config?.getGlobal()||{}).mode||"embed")&&window.limboCore?.modals?.closeAllModals(),s(`Vídeo seleccionado: ${t.title||"Sin título"}`),setTimeout(()=>s(null),3e3)},[c,s])}}({callbacksRef:S,upload:J,refetch:Se,activeFeatures:P,setActiveTab:F,setSelectedImage:U,setCurrentPage:H,setSuccessMessage:q,instanceId:p,selectedUploadFolder:_,tempBlobUrlRef:B}),{handleCropSave:Me,handleCropCancel:De,handleCropError:Re}=function({callbacksRef:e,selectedImage:t,setSelectedImage:n,setActiveTab:l,setImages:r,setCurrentPage:a,setSuccessMessage:i,invalidateCache:o,refetch:s,evictFromCache:c,instanceId:u,activeFeatures:d,modeUI:b}){const m=()=>"crop-only"===b||1===d.length&&"cropper"===d[0]?"crop-only":d.includes("gallery")?"with-gallery":d.includes("upload")&&!d.includes("gallery")?"upload-only":"with-gallery";return{handleCropSave:d=>{const b=m(),h=window.limboCore?.config?.getGlobal()||{},p=h.mode||"embed",f=h.autoHideOnComplete||!1;let g=[],v=null;d.crops&&d.asset?(g=d.crops,v=d.asset):g=d.crops&&Array.isArray(d.crops)?d.crops:Array.isArray(d)?d:[d],v&&"with-gallery"===b&&(r(e=>[v,...e]),a(1),e.current.onUpload&&e.current.onUpload({assetId:v.id,url:v.url,fileName:v.filename,mime:v.mime_type,width:v.width,height:v.height,instanceId:u})),t?.url&&c(t.url),"with-gallery"===b&&(v?s():o());const y=v||t,w=g.some(e=>!0===e.isLocal),x={crops:g,assetId:y?.id,instanceId:u,localCrops:w,asset:y?{id:y.id,url:y.url||y.urlSigned,width:y.width,height:y.height,filename:y.filename,mime_type:y.mime_type}:null};console.log("[App] handleCropSave - callbackPayload:",x),console.log("[App] handleCropSave - crops:",g),console.log("[App] handleCropSave - crops[0]?.url:",g[0]?.url),console.log("[App] handleCropSave - asset:",x.asset),console.log("[App] handleCropSave - callbacksRef.current.onCropsSaved existe:",!!e.current.onCropsSaved),e.current.onCropsSaved?(console.log("[App] Llamando callbacksRef.current.onCropsSaved..."),e.current.onCropsSaved(x),console.log("[App] callbacksRef.current.onCropsSaved ejecutado")):console.warn("[App] ⚠️ callbacksRef.current.onCropsSaved NO existe"),window.limboCore?.events&&window.limboCore.events.emit("cropsSaved",x);const k=g.length;switch(i(`✅ ${k} recorte${1!==k?"s":""} guardado${1!==k?"s":""} correctamente`),setTimeout(()=>i(null),3e3),b){case"with-gallery":"modal"===p?e.current.onCropsSaved||(window.limboCore?.modals?.closeAllModals(),n(null),l("gallery")):(n(null),l("gallery"));break;case"upload-only":"modal"===p?e.current.onCropsSaved||(window.limboCore?.modals?.closeAllModals(),n(null),l("upload")):(n(null),l("upload"));break;case"crop-only":if("modal"===p)e.current.onCropperComplete&&e.current.onCropperComplete({crops:g,instanceId:u}),window.limboCore?.events&&window.limboCore.events.emit("cropperComplete",{crops:g,instanceId:u}),window.limboCore?.modals?.closeAllModals();else if(e.current.onCropperComplete&&e.current.onCropperComplete({crops:g,instanceId:u}),window.limboCore?.events&&window.limboCore.events.emit("cropperComplete",{crops:g,instanceId:u}),f){const e=document.querySelector(`#limbo-instance-${u}`);e&&(e.style.display="none")}}},handleCropCancel:()=>{const r=m(),a=(window.limboCore?.config?.getGlobal()||{}).mode||"embed";switch(e.current.onCropperCancelled&&e.current.onCropperCancelled({assetId:t?.id,instanceId:u}),window.limboCore?.events&&window.limboCore.events.emit("cropperCancelled",{assetId:t?.id,instanceId:u}),r){case"with-gallery":n(null),l("gallery");break;case"upload-only":"modal"===a?window.limboCore?.modals?.closeAllModals():(n(null),l("upload"));break;case"crop-only":"modal"===a?window.limboCore?.modals?.closeAllModals():window.limboCore?.events&&window.limboCore.events.emit("cropperClosed",{instanceId:u,reason:"cancelled"})}},handleCropError:n=>{e.current.onCropperError&&e.current.onCropperError(n,u),window.limboCore?.events&&window.limboCore.events.emit("cropperError",{error:n,assetId:t?.id,instanceId:u}),console.error("Cropper error:",n)}}}({callbacksRef:S,selectedImage:j,setSelectedImage:U,setActiveTab:F,setImages:Ce,setCurrentPage:H,setSuccessMessage:q,invalidateCache:ke,evictFromCache:$e,refetch:Se,instanceId:p,activeFeatures:P,modeUI:b}),Oe=e=>!m.hideActions?.includes(e)&&(!!m.showActions?.includes(e)||!(m.showActions?.length>0)),Fe=[{id:"gallery",label:"Galería",feature:"gallery"},{id:"upload",label:"Subir",feature:"upload"},{id:"cropper",label:"Recortador",hideNonActive:!0,feature:"cropper"}].filter(e=>P.includes(e.feature)),je=e=>{I(e.mime_type||e.original_mime)?(U(e),P.includes("cropper")&&F("cropper")):console.log("[App] ⚠️ Archivo no recortable:",e.mime_type||e.original_mime,"- saltando cropper")};/* @__PURE__ */
|
|
708
|
+
return c("div",{ref:N,className:"limbo-app-root",children:[m.showTabs&&"cropper"!=D&&/* @__PURE__ */s(R,{tabs:Fe,active:D,onChange:e=>{F(e),"upload"!==e&&ne(),"gallery"!==e&&ie()}}),we&&/* @__PURE__ */c(ye,{variant:"danger",children:["Error al cargar archivos: ",we]}),ae&&/* @__PURE__ */c(ye,{variant:"danger",children:["Error al eliminar archivo: ",ae]}),W&&/* @__PURE__ */s(ye,{variant:"success",fixed:!0,onClose:()=>q(null),children:W}),"gallery"===D&&/* @__PURE__ */s(pt,{onSelect:e=>{const t=y?.mandatoryCrops?.length>0,n=I(e.mime_type||e.original_mime);if(t&&n&&P.includes("cropper"))return console.log("[App] 📐 MandatoryCrops detectados, navegando al cropper primero"),void je(e);h.onSelect&&h.onSelect({assetId:e.id,url:e.url,fileName:e.filename,mime:e.mime_type,width:e.width,height:e.height,instanceId:p})},onCrop:je,onDelete:Oe("delete")?ze:null,onFolderChange:Te,onRename:Ae,onPageChange:e=>{H(e)},onFiltersChange:e=>{$(e),H(1)},images:be,loadingImages:me,imagesError:we,deleting:re,uploadedImage:te,pagination:xe,currentPage:V,galleryFilters:E,debouncedFilters:{name:T,uploadedBy:A,dateFrom:E.dateFrom,dateTo:E.dateTo,assetType:E.assetType,folder:E.folder},allowedActions:{select:Oe("select"),download:Oe("download"),copy:Oe("copy"),delete:Oe("delete"),crop:Oe("crop"),rename:Oe("rename")},resolvedAccept:L,allowedCategories:x,folderConfig:w,filterConfig:m.galleryFilters||{},loadingConfig:m.galleryLoading||{},resetUpload:ne}),"upload"===D&&/* @__PURE__ */s(Kt,{onSelect:Ie,onVideoSelect:Pe,onFolderChange:z,uploading:Z,uploadError:ee,uploadedImage:te,selectedUploadFolder:_,apiKey:i,prod:u,allowedCategories:x,resolvedAccept:L,returnConfig:C,folderConfig:w,resetUpload:ne}),"cropper"===D&&/* @__PURE__ */s(Pl,{onSave:Me,onCancel:De,onError:Re,onVariantCreated:Le,onUploadAndCrop:Ie,onVideoSelect:Pe,onUploadWithFolder:Ee,onFolderChange:z,onDelete:ze,isActionAllowed:Oe,selectedImage:j,uploading:Z,uploadError:ee,uploadedImage:te,deleting:re,selectedUploadFolder:_,modeUI:b,apiKey:i,prod:u,allowedCategories:x,resolvedAccept:L,returnConfig:C,folderConfig:w,cropperConfig:y,resetUpload:ne}),
|
|
709
|
+
/* @__PURE__ */s(ve,{}),
|
|
710
|
+
/* @__PURE__ */s(O,{isOpen:K,onClose:G,onReload:Y})]})}class Fl{constructor(e,t,n,l){this.id=e,this.config=t,this.eventManager=n,this.modalManager=l,this.root=null,this.container=null,this.modal=null,this.mounted=!1,this.destroyed=!1,this.button=null,this._handleAppClose=()=>{this.modal&&"function"==typeof this.modal.close&&this.modal.close()},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=P.createRoot(this.container),this.root.render(this._renderApp()),this.mounted=!0,this.eventManager.emit("ready",{instance:this})}catch(e){this.eventManager.emit("error",{instanceId:this.id,error:e.message})}return this}unmount(){return this.mounted?(this.root&&(this.root.unmount(),this.root=null),"button"===this.config.mode&&this.button,this.mounted=!1,this):this}open(){return"modal"!==this.config.mode&&"button"!==this.config.mode||(this.modal||this._createModal(),this.modal&&!this.modal.isOpened()&&(this.modal.open(),this.eventManager.emit("modal:open",{instance:this}))),this}close(){return this.modal&&this.modal.isOpened()&&(this.eventManager?.emit("modal:close",{instance:this}),this.modal.close()),this}updateConfig(e){return this.config={...this.config,...e},this.mounted&&this.root.render(this._renderApp()),this.eventManager.emit("config:updated",{instance:this,newConfig:e}),this}destroy(){this.destroyed||(this.unmount(),this.modal&&(this.modal.destroy(),this.modal=null),this.button&&this.button.parentNode&&(this.button.parentNode.removeChild(this.button),this.button=null),this.eventManager.emit("destroy",{instance:this}),this.container=null,this.config=null,this.eventManager=null,this.modalManager=null,this.destroyed=!0)}getId(){return this.id}getMode(){return this.config.mode}isMounted(){return this.mounted}isDestroyed(){return this.destroyed}getContainer(){return this.container}getConfig(){return{...this.config}}isContainerInDOM(){return this.container&&document.contains(this.container)}_createModal(){if(this.modalManager&&"modal"===this.config.mode&&(this.modal=this.modalManager.createModal({title:this.config.title||"Limbo Image Manager",size:this.config.modalSize||this.config.modal?.size||"large",usesReactFocusTrap:!0,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=P.createRoot(e),this.root.render(this._renderApp()),this.mounted=!0}}_createButton(){if(this.container||(this.container=this._resolveContainer()),!this.container)return void this.eventManager.emit("error",{instanceId:this.id,error:"Container not found for button mode"});const e=document.createElement("button");e.type="button",e.className="limbo-trigger-button",e.textContent=this.config.buttonText||"Abrir Limbo",e.style.cssText="\n background: #001978;\n color: white;\n border: none;\n padding: 10px 20px;\n border-radius: 6px;\n cursor: pointer;\n font-family: inherit;\n font-size: 14px;\n font-weight: 500;\n transition: all 0.2s ease;\n ",e.addEventListener("mouseenter",()=>{e.style.backgroundColor="#334793",e.style.transform="translateY(-1px)"}),e.addEventListener("mouseleave",()=>{e.style.backgroundColor="#001978",e.style.transform="translateY(0)"}),e.addEventListener("click",()=>{this.open()}),this.container.appendChild(e),this.button=e,this.mounted=!0}_resolveContainer(){const{container:e}=this.config;return e?"string"==typeof e?document.querySelector(e):e instanceof Element?e:null:null}_renderApp(){return e.createElement("div",{id:`limbo-component-container-${this.id}`,className:"limbo-scope limbo-instance limbo-component-container-wrapper lb:h-full lb:w-full lb:py-2 lb:pb-0 lb:bg-white","data-limbo-id":this.id,"data-limbo-mode":this.config.mode,"data-limbo-version":"4.0.2","data-limbo-isolated":"true","aria-label":"Limbo Image Manager",role:"region"},e.createElement(Ol,{onClose:"modal"===this.config.mode?this._handleAppClose:void 0,apiKey:this.config.apiKey||null,publicKey:this.config.publicKey||null,token:this.config.token||null,prod:this.config.prod||!1,url:this.config.url,features:this.config.features,modeUI:this.config.modeUI||"full",ui:this.config.ui,callbacks:this._createCallbacks(),instanceId:this.id,authMode:this.config.authMode||(this.config.publicKey?"session":"manual"),_externalImage:this.config._externalImage||null,cropperConfig:this.config.cropper||null,allowedCategories:this.config.validation?.allowedCategories||null,accept:this.config.validation?.accept||null,returnConfig:this.config.returnConfig||null,folderConfig:this.config.folders||{include:[],exclude:[],includeNoFolder:!0},itemsPerPage:this.config.itemsPerPage||30}))}_createCallbacks(){return{onSelect:e=>{const t=this.config?.callbacks?.onSelect,n=this._createStandardPayload(e,"select");t&&Promise.resolve(t(n)).catch(e=>{console.error("[LimboInstance] Error en onSelect callback:",e)}),this.destroyed||this._emitDOMEvent("select",n)},onUpload:e=>{const t=this.config?.callbacks?.onUpload,n=this._createStandardPayload(e,"upload");t&&Promise.resolve(t(n)).catch(e=>{console.error("[LimboInstance] Error en onUpload callback:",e)}),this.destroyed||this._emitDOMEvent("upload",n)},onError:e=>{const t=this.config?.callbacks?.onError,n={instance:this,error:{message:e.message||"Unknown error",code:e.code||"UNKNOWN",timestamp:Date.now()}};t&&t(n.error),this.destroyed||this._emitDOMEvent("error",n)},onClose:()=>{const e=this.config?.callbacks?.onClose,t={instance:this,timestamp:Date.now()};e&&e(),this.destroyed||this._emitDOMEvent("close",t)},onCropsSaved:e=>{console.log("[LimboInstance] onCropsSaved recibido:",e),console.log("[LimboInstance] this.config?.callbacks:",this.config?.callbacks);const t=this.config?.callbacks?.onCropsSaved;console.log("[LimboInstance] userCallback existe:",!!t);const n={instance:this,eventType:"cropsSaved",timestamp:Date.now(),instanceId:this.id,...e};if(console.log("[LimboInstance] payload.crops:",n.crops),t){console.log("[LimboInstance] Llamando userCallback onCropsSaved");try{t(n),console.log("[LimboInstance] userCallback ejecutado correctamente")}catch(l){console.error("[LimboInstance] Error en userCallback:",l)}}else console.warn("[LimboInstance] ⚠️ userCallback onCropsSaved NO existe");this.destroyed||this._emitDOMEvent("cropsSaved",n)},onCropperComplete:e=>{console.log("[LimboInstance] onCropperComplete recibido:",e);const t=this.config?.callbacks?.onCropperComplete,n={instance:this,eventType:"cropperComplete",timestamp:Date.now(),instanceId:this.id,...e};t&&(console.log("[LimboInstance] Llamando userCallback onCropperComplete"),t(n)),this.destroyed||this._emitDOMEvent("cropperComplete",n)}}}_createStandardPayload(e,t){const n={instance:this,eventType:t,timestamp:Date.now(),instanceId:this.id,mode:this.config?.mode,features:this.config?.features};return e&&(e.assetId||e.id?(n.assetId=e.assetId||e.id,n.variants=e.variants||[],n.master=e.master||{urlSigned:e.url||e.urlSigned,width:e.width,height:e.height,mime:e.mime||e.mimeType},n.fileName=e.fileName||e.name,n.mime=e.mime||e.mimeType,n.width=e.width,n.height=e.height,n.fileBlob=e.fileBlob||e.file,n.metadata={uploadedBy:e.uploadedBy,uploadedAt:e.uploadedAt||e.timestamp,size:e.size,...e.metadata}):Object.assign(n,e)),n}_emitDOMEvent(e,t){if(this.destroyed)return;const n=new CustomEvent(`limbo:${e}`,{detail:t,bubbles:!0,cancelable:!0});(this.getContainer()||document).dispatchEvent(n),this.eventManager?.emit(e,t)}_validateConfig(){const e=X();if(!(this.config.auth?.apiKey||this.config.auth?.publicKey||this.config.auth?.token||this.config.apiKey||this.config.publicKey||this.config.token||this.config.tokenProvider||this.config.auth?.tokenProvider||e.token||e.publicKey||e.tokenProvider))throw new Error(`LimboInstance ${this.id}: Authentication is required. Provide either auth.publicKey (recommended), auth.apiKey (for server-side only), token, or tokenProvider`);if((this.config.auth?.apiKey||this.config.apiKey)&&"undefined"!=typeof window&&console.warn("⚠️ SECURITY WARNING: API Key detected in client-side code.\nThis is a security risk! Use publicKey instead for client applications.\nAPI Keys should only be used in server-side environments."),!["embed","modal","button"].includes(this.config.mode))throw new Error(`LimboInstance ${this.id}: invalid mode ${this.config.mode}`);if("embed"===this.config.mode&&!this.config.container)throw new Error(`LimboInstance ${this.id}: container is required for embed mode`);if("button"===this.config.mode&&!this.config.container)throw new Error(`LimboInstance ${this.id}: container is required for button mode`)}}class jl{constructor(){this.instances=/* @__PURE__ */new Map,this.counter=0}create(e,t,n){const l="limbo-"+ ++this.counter,r=new Fl(l,e,t,n);return this.instances.set(l,r),r}get(e){return this.instances.get(e)}getAll(){return Array.from(this.instances.values())}getActive(){return this.getAll().filter(e=>e.isMounted())}destroy(e){const t=this.instances.get(e);return!!t&&(t.destroy(),this.instances.delete(e),!0)}destroyAll(){this.instances.forEach(e=>e.destroy()),this.instances.clear()}cleanupOrphans(){const e=[];return this.instances.forEach((t,n)=>{t.isContainerInDOM()||e.push(n)}),e.forEach(e=>this.destroy(e)),e.length}getStats(){const e=this.getAll();return{total:e.length,active:e.filter(e=>e.isMounted()).length,embed:e.filter(e=>"embed"===e.getMode()).length,modal:e.filter(e=>"modal"===e.getMode()).length,button:e.filter(e=>"button"===e.getMode()).length}}}class Ul{constructor(){this.config=null,this.instances=/* @__PURE__ */new Map,this.observer=null,this.initialized=!1}configure(e,t,n){return this.config={selector:e.selector||null,dataset:e.dataset||"data-limbo-input-file",return:e.return||e.returnType||"json",mode:e.mode||"modal",features:e.features||["gallery","upload","cropper"],crop:e.crop||"free",quality:e.quality||.9,format:e.format||"webp",modeUI:e.modeUI||"full",modalSize:e.modalSize||"fullscreen",theme:e.theme||"light",compact:e.compact||!1,maxSize:e.maxSize||"10MB",formats:e.formats||["jpg","jpeg","png","svg","webp"],minWidth:e.minWidth||null,minHeight:e.minHeight||null,maxWidth:e.maxWidth||null,maxHeight:e.maxHeight||null,buttonText:e.buttonText||"Seleccionar archivo",buttonClass:e.buttonClass||"limbo-auto-button",buttonStyle:e.buttonStyle||"primary",showPreview:!1!==e.showPreview,allowMultiple:e.allowMultiple||!1,autoAssign:!1!==e.autoAssign,localCropsOnly:e.localCropsOnly||!1,...e},this.configManager=t,this.eventManager=n,this._initialize(),this}cleanup(){this.observer&&(this.observer.disconnect(),this.observer=null),this.instances.forEach(({input:e,button:t})=>{this._restoreInput(e,t)}),this.instances.clear(),this.config=null,this.initialized=!1}getStats(){return{configured:null!==this.config,totalInputs:this.instances.size,dataset:this.config?.dataset,returnType:this.config?.return}}_initialize(){this.initialized||(this._scanExistingInputs(),this._setupObserver(),this.initialized=!0,this.eventManager.emit("autoInputs:initialized",{config:this.config,inputsFound:this.instances.size}))}_scanExistingInputs(){const e=this.config.selector||`input[${this.config.dataset}]`;document.querySelectorAll(e).forEach(e=>this._processInput(e))}_processInput(e){const t=this._getInputId(e);if(this.instances.has(t))return;if(!this._validateInput(e))return;const n=this._createButton(e);this._hideInput(e),this._insertButton(e,n),this.instances.set(t,{input:e,button:n,config:this._getInputConfig(e)}),this.eventManager.emit("autoInputs:processed",{inputId:t,input:e,button:n})}_createButton(e){const t=document.createElement("button"),n=this._getInputConfig(e);t.type="button";const l=e.dataset.buttontext||e.getAttribute("data-limbo-button-text")||null;t.textContent=l||v(n.accept||null,!1);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,l=t.theme||this.config.theme,r=t.compact||this.config.compact,a={border:"none",borderRadius:"8px",cursor:"pointer",fontFamily:"inherit",fontSize:r?"12px":"14px",fontWeight:"500",transition:"all 0.2s ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",padding:r?"6px 12px":"8px 16px",textDecoration:"none",userSelect:"none"},i={primary:{backgroundColor:"dark"===l?"#3b82f6":"#001978",color:"white",hoverBg:"dark"===l?"#2563eb":"#334793"},secondary:{backgroundColor:"dark"===l?"#374151":"#f3f4f6",color:"dark"===l?"#f9fafb":"#374151",border:"1px solid "+("dark"===l?"#4b5563":"#d1d5db"),hoverBg:"dark"===l?"#4b5563":"#e5e7eb"},outline:{backgroundColor:"transparent",color:"dark"===l?"#3b82f6":"#001978",border:"2px solid "+("dark"===l?"#3b82f6":"#001978"),hoverBg:"dark"===l?"#3b82f6":"#001978",hoverColor:"white"},ghost:{backgroundColor:"transparent",color:"dark"===l?"#f9fafb":"#374151",hoverBg:"dark"===l?"#374151":"#f3f4f6"}},o=i[n]||i.primary;Object.assign(e.style,{...a,...o});const s=o.backgroundColor,c=o.color;e.addEventListener("mouseenter",()=>{e.style.backgroundColor=o.hoverBg||o.backgroundColor,o.hoverColor&&(e.style.color=o.hoverColor),e.style.transform="translateY(-1px)",e.style.boxShadow="0 4px 12px rgba(0, 0, 0, 0.15)"}),e.addEventListener("mouseleave",()=>{e.style.backgroundColor=s,e.style.color=c,e.style.transform="translateY(0)",e.style.boxShadow="none"}),t.disabled&&(e.style.opacity="0.5",e.style.cursor="not-allowed")}_attachButtonEvents(e,t){e.addEventListener("click",e=>{e.preventDefault(),this._handleButtonClick(t)})}_handleButtonClick(e){const t=this._getInputConfig(e),n=this._createModalConfig(t);this.eventManager.emit("autoInputs:modalRequest",{input:e,config:n,callback:async t=>await this._handleImageSelection(e,t)})}async _handleImageSelection(e,t){const n=this._getInputConfig(e);let l=t;try{if(!t.original&&!t.images&&(t.id||t.assetId)){console.log("[AutoInputManager] 🔗 Selección directa detectada, obteniendo URL permanente...");const e=t.id||t.assetId;try{const n=await async function(e,t=!0,n=!0,l=0){try{const r=new URLSearchParams({include_variants:t.toString(),include_metadata:n.toString(),url_expires:l.toString()});return te(await Y({endpoint:`/assets/${e}?${r}`,method:"GET",basePath:ae,useJWT:!0}))}catch(r){throw re(r)}}(e,!1,!1,!0);n?.result?.url?(console.log("[AutoInputManager] ✅ URL permanente obtenida:",n.result.url),l={original:{url:n.result.url,width:n.result.width||t.width,height:n.result.height||t.height,assetId:e},images:[]}):(console.warn("[AutoInputManager] ⚠️ No se pudo obtener URL permanente, usando URL temporal"),l={original:{url:t.url||t.path,width:t.width,height:t.height,assetId:e},images:[]})}catch(r){console.error("[AutoInputManager] Error obteniendo URL permanente:",r),l={original:{url:t.url||t.path,width:t.width,height:t.height,assetId:e},images:[]}}}const a=await this._formatImageData(l,n);console.log("[AutoInputManager] Valor formateado:",a),console.log("[AutoInputManager] Tipo de valor:",typeof a),!1!==n.autoAssign&&(e.value=a,console.log("[AutoInputManager] Valor asignado al input:",e.value)),this._updateButtonFeedback(e,l),e.dispatchEvent(new Event("change",{bubbles:!0})),e.dispatchEvent(new CustomEvent("limbo:resultReady",{detail:{imageData:l,input:e,value:a,config:n,assignment:{format:n.return,smartAssign:!1!==n.smartAssign,autoAssign:!1!==n.autoAssign},legacy:{imageData:l,formatted:this._createFormattedResult(l,n)}},bubbles:!0})),e.dispatchEvent(new CustomEvent("limbo:imageSelected",{detail:{imageData:l,input:e,value:a,config:n,formatted:this._createFormattedResult(l,n)},bubbles:!0})),this.eventManager.emit("autoInputs:imageSelected",{input:e,imageData:l,value:a,config:n})}catch(a){console.error("Error handling image selection:",a),e.dispatchEvent(new CustomEvent("limbo:error",{detail:{error:a.message,input:e,imageData:l,config:n},bubbles:!0})),this._handleImageSelectionLegacy(e,t)}}_updateButtonFeedback(e,t){const n=this._getInputId(e),l=this.instances.get(n);if(!l||!l.button)return;const r=l.button,a=r.nextElementSibling;a&&a.classList.contains("limbo-button-feedback")&&a.remove();const i=document.createElement("span");i.className="limbo-button-feedback",i.style.cssText="\n display: inline-flex;\n align-items: center;\n gap: 6px;\n margin-left: 8px;\n padding: 4px 8px;\n background: #10b981;\n color: white;\n border-radius: 6px;\n font-size: 12px;\n font-weight: 500;\n animation: limbo-fade-in 0.3s ease-out;\n ";const o=t.images&&t.images.length>0,s=o?t.images.length:0;for(;i.firstChild;)i.removeChild(i.firstChild);i.appendChild(function(){const e="http://www.w3.org/2000/svg",t=document.createElementNS(e,"svg");t.setAttribute("width","14"),t.setAttribute("height","14"),t.setAttribute("viewBox","0 0 20 20"),t.setAttribute("fill","currentColor");const n=document.createElementNS(e,"path");return n.setAttribute("fill-rule","evenodd"),n.setAttribute("d","M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"),n.setAttribute("clip-rule","evenodd"),t.appendChild(n),t}());const c=document.createElement("span");c.textContent=o?`${s} recorte${1!==s?"s":""} configurado${1!==s?"s":""}`:"Archivo seleccionado",i.appendChild(c),r.parentNode.insertBefore(i,r.nextSibling);let u=r.parentNode.querySelector(".limbo-powered-by");if(!u){u=document.createElement("div"),u.className="limbo-powered-by";const e=document.createElement("span");e.style.cssText="display:block;margin-top:2px;font-size:10px;color:#aaa;text-align:left;font-family:inherit;opacity:0.7;",e.textContent="Powered by ";const t=document.createElement("b");t.textContent="Limbo",e.appendChild(t),u.appendChild(e),r.parentNode.insertBefore(u,i.nextSibling)}r.style.backgroundColor="#10b981";const d=l.config?.accept||null;r.textContent=v(d,!0)}async _handleImageSelectionLegacy(e,t){const n=this._getInputConfig(e),l=await this._formatImageData(t,n);!1!==n.autoAssign&&(e.value=l),e.dispatchEvent(new Event("change",{bubbles:!0})),e.dispatchEvent(new CustomEvent("limbo:imageSelected",{detail:{imageData:t,input:e,value:l,config:n,formatted:this._createFormattedResult(t,n)},bubbles:!0})),this.eventManager.emit("autoInputs:imageSelected",{input:e,imageData:t,value:l,config:n})}_createFormattedResult(e,t){return{url:e.url||e.path||"",base64:e.base64||e.dataUrl||"",assetId:e.assetId||e.id||"",fileName:e.fileName||e.filename||"",object:{url:e.url||e.path,assetId:e.assetId||e.id,fileName:e.fileName||e.filename,mime:e.mime||e.mime_type,width:e.width,height:e.height,size:e.size||e.file_size,created:e.created_at||e.created,metadata:e.metadata||{}},json:JSON.stringify({url:e.url||e.path,assetId:e.assetId||e.id,fileName:e.fileName||e.filename,mime:e.mime||e.mime_type,width:e.width,height:e.height,size:e.size||e.file_size}),metadata:{width:e.width,height:e.height,size:e.size||e.file_size,format:e.format||e.mime_type,quality:t.quality||this.config.quality,aspectRatio:e.width&&e.height?e.width/e.height:null}}}async _formatImageData(e,t=null){const n=(t||{}).return||this.config.return||"json",l=void 0!==e.original;switch(n){case"url":return l?e.images?.[0]?.url||e.original?.url||"":e.url||e.path||"";case"base64":return e.base64||e.dataUrl||"";case"assetId":return l?e.original?.assetId||"":e.assetId||e.id||"";case"fileName":return e.fileName||e.filename||"";default:try{if(l){const t={original:e.original?{url:e.original.url||e.original.urlSigned,width:e.original.width,height:e.original.height,assetId:e.original.assetId||e.original.id}:null,images:Array.isArray(e.images)?e.images.map(e=>{const t={url:e.url||e.urlSigned,width:e.width,height:e.height,name:e.name||e.filename||e.label};return e.cropState&&(t.cropState={selectorState:e.cropState.selectorState||null,imageTransform:e.cropState.imageTransform||null,flipState:e.cropState.flipState||null}),t}):[]};console.log("[AutoInputManager] Datos limpios para JSON:",t);const n=JSON.stringify(t);return console.log("[AutoInputManager] JSON generado:",n),n}const t={original:{url:e.url||e.path,width:e.width,height:e.height,assetId:e.assetId||e.id}};return console.log("[AutoInputManager] Datos legacy para JSON:",t),JSON.stringify(t)}catch(r){return console.error("[AutoInputManager] Error al serializar JSON:",r),console.error("[AutoInputManager] imageData problemático:",e),"{}"}}}_createModalConfig(e){return{mode:e.mode||this.config.mode||"modal",modeUI:e.modeUI||this.config.modeUI||"full",features:e.features||this.config.features,modalSize:e.modalSize||this.config.modalSize||"fullscreen",title:e.description||this.config.title||"Seleccionar archivo",cropper:this._getCropperConfig(e),ui:{showActions:this._getUIActions(e),hideActions:[],showTabs:this._shouldShowTabs(e),theme:e.theme||this.config.theme,compact:e.compact||this.config.compact,showPreview:void 0!==e.showPreview?e.showPreview:this.config.showPreview},validation:{accept:e.accept||null,maxSize:e.maxSize||this.config.maxSize,formats:e.formats||this.config.formats,minWidth:e.minWidth||this.config.minWidth,minHeight:e.minHeight||this.config.minHeight,maxWidth:e.maxWidth||this.config.maxWidth,maxHeight:e.maxHeight||this.config.maxHeight,required:e.required||!1},behavior:{allowMultiple:e.allowMultiple||this.config.allowMultiple,closeOnSelect:!0,autoAssign:void 0!==e.autoAssign?e.autoAssign:this.config.autoAssign,allowSelectNew:!1!==e.allowSelectNew},initialImageUrl:e.initialImageUrl||null,existingCrops:e.existingCrops||null,existingData:e.existingData||null,returnConfig:{format:e.return||this.config.return,quality:e.quality||this.config.quality,outputFormat:e.format||this.config.format},inputMeta:{inputId:e.inputId,inputName:e.inputName,inputType:e.inputType,placeholder:e.placeholder}}}_getCropperConfig(e){const t=e.crop||this.config.crop,n={quality:e.quality||this.config.quality,format:e.format||this.config.format,mandatoryCrops:e.mandatoryCrops||[],allowAdditionalCrops:!1!==e.allowAdditionalCrops,maxCrops:e.maxCrops||null,localCropsOnly:e.localCropsOnly??this.config.localCropsOnly??!1,existingCrops:e.existingCrops||null};if(e.mandatoryCrops&&e.mandatoryCrops.length>0)return{...n,aspectRatio:null};if(!t||"none"===t||"false"===t)return null;if("free"===t)return{...n,aspectRatio:null};const l={"1:1":1,"16:9":16/9,"4:3":4/3,"3:2":1.5,"2:1":2,square:1,landscape:16/9,portrait:3/4};if(l[t])return{...n,aspectRatio:l[t],minCropBoxWidth:e.minWidth||this.config.minWidth,minCropBoxHeight:e.minHeight||this.config.minHeight};if("string"==typeof t&&t.includes(":")){const[e,l]=t.split(":").map(Number);if(!isNaN(e)&&!isNaN(l)&&0!==l)return{...n,aspectRatio:e/l}}const r=parseFloat(t);return!isNaN(r)&&r>0?{...n,aspectRatio:r}:"object"==typeof t?{...n,...t}:null}_shouldShowTabs(e){const t=e.modeUI||this.config.modeUI||"full",n=e.features||this.config.features;return!["gallery-only","upload-only","crop-only","ia-only"].includes(t)&&(n&&n.length>1)}_getUIActions(e){const t=e.modeUI||this.config.modeUI||"full",n=e.features||this.config.features;let l=[];switch(t){case"gallery-only":case"upload-only":l=["select"];break;case"crop-only":l=["select","crop"];break;default:l=["select"],n.includes("cropper")&&l.push("crop"),n.includes("gallery")&&(l.push("download","copy","rename"),this.config.allowDelete&&l.push("delete"))}return l}_getInputId(e){if(e.id)return e.id;if(e.name)return e.name;let t=e.getAttribute("data-limbo-uid");return t||(t=`limbo-auto-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,e.setAttribute("data-limbo-uid",t)),t}_validateInput(e){return e instanceof HTMLInputElement}_getInputConfig(e){const t=e=>e?e.split(",").map(e=>e.trim()):null,n=e=>{if(!e)return null;const t=e.match(/^(\d+(?:\.\d+)?)(MB|KB|B)?$/i);if(!t)return null;const n=parseFloat(t[1]);switch((t[2]||"B").toUpperCase()){case"MB":return 1024*n*1024;case"KB":return 1024*n;default:return n}},l=(e,t=!1)=>null===e?t:"true"===e||"1"===e||""===e,r=e=>e?parseFloat(e):null,a=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return console.warn("[Limbo AutoInputManager] Error parsing JSON attribute:",t),null}},i=a(e.dataset.mandatorycrops)||a(e.dataset.mandatoryCrops)||a(e.getAttribute("data-mandatory-crops"))||a(e.getAttribute("data-limbo-mandatory-crops"))||null;return{return:e.dataset.returntype||e.getAttribute("data-limbo-return")||this.config.return,mode:e.dataset.mode||e.getAttribute("data-limbo-mode")||this.config.mode,features:t(e.dataset.features)||t(e.getAttribute("data-limbo-features"))||this.config.features,crop:e.dataset.crop||e.getAttribute("data-limbo-crop")||this.config.crop,quality:r(e.dataset.quality)||r(e.getAttribute("data-limbo-quality"))||this.config.quality,format:e.dataset.format||e.getAttribute("data-limbo-format")||this.config.format,modeUI:e.dataset.modeui||e.dataset.modeUI||e.getAttribute("data-limbo-mode-ui")||this.config.modeUI,modalSize:e.dataset.modalsize||e.getAttribute("data-limbo-modal-size")||this.config.modalSize,theme:e.dataset.theme||e.getAttribute("data-limbo-theme")||this.config.theme,compact:l(e.dataset.compact,null)??l(e.getAttribute("data-limbo-compact"),this.config.compact),maxSize:n(e.getAttribute("data-limbo-max-size"))||n(this.config.maxSize),formats:t(e.getAttribute("data-limbo-formats"))||this.config.formats,minWidth:r(e.getAttribute("data-limbo-min-width"))||this.config.minWidth,minHeight:r(e.getAttribute("data-limbo-min-height"))||this.config.minHeight,maxWidth:r(e.getAttribute("data-limbo-max-width"))||this.config.maxWidth,maxHeight:r(e.getAttribute("data-limbo-max-height"))||this.config.maxHeight,buttonText:e.dataset.buttontext||e.getAttribute("data-limbo-button-text")||this.config.buttonText,buttonStyle:e.dataset.buttonstyle||e.getAttribute("data-limbo-button-style")||this.config.buttonStyle,buttonClass:e.dataset.buttonclass||e.getAttribute("data-limbo-button-class")||this.config.buttonClass,showPreview:l(e.getAttribute("data-limbo-show-preview"),this.config.showPreview),allowMultiple:l(e.getAttribute("data-limbo-allow-multiple"),this.config.allowMultiple),autoAssign:l(e.getAttribute("data-limbo-auto-assign"),this.config.autoAssign),placeholder:e.getAttribute("data-limbo-placeholder"),description:e.getAttribute("data-limbo-description"),required:l(e.getAttribute("data-limbo-required"),!1),disabled:l(e.getAttribute("data-limbo-disabled"),!1),inputId:this._getInputId(e),inputName:e.name,inputType:e.type,mandatoryCrops:i,allowAdditionalCrops:l(e.dataset.allowadditionalcrops,null)??l(e.getAttribute("data-limbo-allow-additional-crops"),!0),maxCrops:r(e.dataset.maxcrops)||r(e.getAttribute("data-limbo-max-crops"))||null,accept:e.dataset.accept||e.getAttribute("data-limbo-accept")||null,allowSelectNew:l(e.dataset.allowselectnew,null)??l(e.getAttribute("data-limbo-allow-select-new"),!0),...this._parseExistingInputValue(e.value)}}_parseExistingInputValue(e){if(!e||""===e.trim())return{initialImageUrl:null,existingCrops:null,existingData:null};try{const t=JSON.parse(e);return t.original&&t.original.url?(console.log("[AutoInputManager] Valor existente parseado:",t),{initialImageUrl:t.original.url,existingCrops:t.images||null,existingData:t}):t.url?{initialImageUrl:t.url,existingCrops:null,existingData:t}:{initialImageUrl:null,existingCrops:null,existingData:t}}catch(t){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?{initialImageUrl:e,existingCrops:null,existingData:null}:{initialImageUrl:null,existingCrops:null,existingData:null}}}_generateInputId(){return`limbo-auto-input-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}_hideInput(e){e.style.display="none"}_insertButton(e,t){e.parentNode.insertBefore(t,e.nextSibling)}_restoreInput(e,t){e.style.display="",t&&t.parentNode&&t.parentNode.removeChild(t)}_setupObserver(){this.observer=new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e.nodeType===Node.ELEMENT_NODE&&this._scanNodeForInputs(e)})})}),this.observer.observe(document.body,{childList:!0,subtree:!0})}_scanNodeForInputs(e){const t=this.config.selector||`input[${this.config.dataset}]`;e.matches&&e.matches(t)&&this._processInput(e);const n=e.querySelectorAll&&e.querySelectorAll(t);n&&n.forEach(e=>this._processInput(e))}}class Bl{constructor(){this.listeners=/* @__PURE__ */new Map}emit(e,t={}){this._emitDOMEvent(e,t),this._executeListeners(e,t)}on(e,t){return this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t),()=>this.off(e,t)}off(e,t){const n=this.listeners.get(e);if(n){const e=n.indexOf(t);e>-1&&n.splice(e,1)}}cleanup(){this.listeners.clear()}_emitDOMEvent(e,t){const n=new CustomEvent(`limbo:${e}`,{detail:{...t,timestamp:Date.now()},bubbles:!0,cancelable:!0});(t.instance?.getContainer()||document).dispatchEvent(n)}_executeListeners(e,t){const n=this.listeners.get(e);n&&n.forEach(n=>{try{n(t)}catch(l){console.error(`Error executing listener for ${e}:`,l)}})}getStats(){const e={};return this.listeners.forEach((t,n)=>{e[n]=t.length}),e}}class Wl{constructor(){this.activeModals=/* @__PURE__ */new Set,this.zIndexBase=1e4,this.focusableSelectors=["button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"]):not([disabled])',"a[href]"].join(", "),this.initialized=!1,this._initGlobalListeners()}createModal(e){const t=new ql(this._generateModalId(),e,this);return this.activeModals.add(t),t}closeModal(e){const t=this._findModal(e);return!!t&&(t.close(),!0)}closeAllModals(){this.activeModals.forEach(e=>e.close()),this.activeModals.clear()}getActiveModal(){return Array.from(this.activeModals).pop()||null}getStats(){return{active:this.activeModals.size,nextZIndex:this._getNextZIndex()}}_generateModalId(){return`limbo-modal-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}_findModal(e){return Array.from(this.activeModals).find(t=>t.getId()===e)}_getNextZIndex(){return this.zIndexBase+10*this.activeModals.size}_removeModal(e){this.activeModals.delete(e),window.limboCore?.events&&window.limboCore.events.emit("modal:closed",{modalId:e.getId(),remainingModals:this.activeModals.size})}_handleGlobalKeydown(e){const t=this.getActiveModal();t&&(t.config&&t.config.usesReactFocusTrap||("Escape"===e.key&&(e.preventDefault(),t.close()),"Tab"===e.key&&this._handleTabTrap(e,t)))}_handleTabTrap(e,t){const n=t.getFocusableElements();if(0===n.length)return;const l=n[0],r=n[n.length-1];e.shiftKey?document.activeElement===l&&(e.preventDefault(),r.focus()):document.activeElement===r&&(e.preventDefault(),l.focus())}_initGlobalListeners(){this.initialized||(this.globalKeydownHandler=e=>this._handleGlobalKeydown(e),document.addEventListener("keydown",this.globalKeydownHandler),this.initialized=!0)}destroy(){this.closeAllModals(),this.initialized&&this.globalKeydownHandler&&(document.removeEventListener("keydown",this.globalKeydownHandler),this.initialized=!1,this.globalKeydownHandler=null)}}class ql{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,usesReactFocusTrap:t.usesReactFocusTrap||!1},this.manager=n,this.element=null,this.backdrop=null,this.isOpen=!1,this.previousFocus=null,this._previousInertSiblings=[],this._create()}_create(){this._createBackdrop(),this._createModal(),this._attachEvents()}_createBackdrop(){this.config.backdrop&&(this.backdrop=document.createElement("div"),this.backdrop.className="limbo-modal-backdrop",this.backdrop.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: rgba(0, 0, 0, 0.5);\n z-index: ${this.manager._getNextZIndex()};\n opacity: 0;\n transition: opacity 0.3s ease;\n `,this.backdrop.addEventListener("click",e=>{e.target===this.backdrop&&this.close()}))}_createModal(){this.element=document.createElement("div"),this.element.className=`limbo-scope limbo-modal limbo-modal--${this.config.size}`,this.element.id=this.id,this.element.setAttribute("role","dialog"),this.element.setAttribute("aria-modal","true"),this.element.setAttribute("aria-labelledby",`${this.id}-title`),this.element.tabIndex=-1;const e=window.innerWidth<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),t={small:e?"width: 100%; height: 100%;":"max-width: 500px; min-height: 400px;",medium:e?"width: 100%; height: 100%;":"max-width: 800px; min-height: 500px;",large:e?"width: 100%; height: 100%;":"max-width: 1400px; min-height: 700px;",xlarge:e?"width: 100%; height: 100%;":"max-width: 95dvw; min-height: 85vh;",fullscreen:"width: 100%; height: 100%; max-width: 100%; max-height: 100%; border-radius: 0;"},n="fullscreen"===this.config.size,l=e||n?`\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n transform: ${e?"translateY(100%)":"scale(0.95)"};\n width: 100%;\n height: 100%;\n max-width: none;\n max-height: none;\n border-radius: 0;\n background: white;\n z-index: ${this.manager._getNextZIndex()+1};\n opacity: ${e?"1":"0"};\n transition: ${e?"transform":"all"} 0.3s cubic-bezier(0.4, 0, 0.2, 1);\n overflow: hidden;\n display: flex;\n flex-direction: column;\n padding-top: env(safe-area-inset-top);\n padding-left: env(safe-area-inset-left);\n padding-right: env(safe-area-inset-right);\n padding-bottom: env(safe-area-inset-bottom);\n `:`\n position: fixed;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%) scale(0.8);\n ${t[this.config.size]}\n width: 90%;\n max-height: 90vh;\n background: white;\n border-radius: 16px;\n box-shadow: 0 25px 50px rgba(0, 0, 0, 0.25);\n z-index: ${this.manager._getNextZIndex()+1};\n opacity: 0;\n transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);\n overflow: hidden;\n display: flex;\n flex-direction: column;\n `;this.element.style.cssText=l,this._createHeader(),this._createBody(),document.body.appendChild(this.backdrop),document.body.appendChild(this.element)}_createHeader(){const e=document.createElement("div");e.className="limbo-modal-header";const t=window.innerWidth<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);e.style.cssText=`\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: ${t?"16px 20px":"20px 24px"};\n border-bottom: 1px solid #e9ecef;\n background: #f8f9fa;\n ${t?"position: sticky; top: 0; z-index: 10;":""}\n min-height: ${t?"60px":"auto"};\n `;const n=document.createElement("h2");if(n.id=`${this.id}-title`,n.className="limbo-modal-title",n.textContent=this.config.title,n.style.cssText="\n margin: 0;\n font-size: 18px;\n font-weight: 600;\n color: #001978;\n flex: 1;\n margin-right: 16px;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n ",e.appendChild(n),this.config.showCloseButton){const n=document.createElement("button");n.type="button",n.className="limbo-modal-close",n.textContent="✕",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 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",this._applyInertToSiblings();const e=window.innerWidth<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),t="fullscreen"===this.config.size;return requestAnimationFrame(()=>{this.backdrop&&(this.backdrop.style.opacity="1"),this.element.style.opacity="1",this.element.style.transform=e?"translateY(0%)":t?"scale(1)":"translate(-50%, -50%) scale(1)"}),this.isOpen=!0,this.config.focus&&setTimeout(()=>{if(window.limbo&&window.limbo.core&&window.limbo.core.keyboard)window.limbo.core.keyboard.focusFirst(this.element);else{const e=this.getFocusableElements()[0];e&&e.focus()}},300),this.config.onOpen&&this.config.onOpen(this),this}close(){if(!this.isOpen)return this;const e=window.innerWidth<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),t="fullscreen"===this.config.size;return this.backdrop&&(this.backdrop.style.opacity="0"),this.element.style.opacity="0",this.element.style.transform=e?"translateY(100%)":t?"scale(0.95)":"translate(-50%, -50%) scale(0.8)",setTimeout(()=>{this._cleanup()},300),this.isOpen=!1,window.limbo&&window.limbo.core&&window.limbo.core.keyboard&&(window.limbo.core.keyboard.setActiveModal(null),window.limbo.core.keyboard.releaseFocus()),this.config.onClose&&this.config.onClose(this),this}destroy(){this.close(),this.manager._removeModal(this),this.config.onDestroy&&this.config.onDestroy(this)}getBodyContainer(){return this.element.querySelector(".limbo-modal-body")}getFocusableElements(){return Array.from(this.element.querySelectorAll(this.manager.focusableSelectors))}getId(){return this.id}isOpened(){return this.isOpen}getConfig(){return{...this.config}}_applyInertToSiblings(){const e=Array.from(document.body.children).filter(e=>e!==this.element&&e!==this.backdrop);this._previousInertSiblings=e.map(e=>({node:e,hadInert:e.hasAttribute("inert")})),e.forEach(e=>e.setAttribute("inert",""))}_restoreInertSiblings(){this._previousInertSiblings.forEach(({node:e,hadInert:t})=>{!t&&e.isConnected&&e.removeAttribute("inert")}),this._previousInertSiblings=[]}_cleanup(){document.body.style.overflow=this._originalBodyOverflow||"",this._restoreInertSiblings(),this.previousFocus&&"function"==typeof this.previousFocus.focus&&!1!==this.previousFocus.isConnected&&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 Vl{constructor(){this.currentTheme=null,this.customThemes=/* @__PURE__ */new Map,this.config=this._getDefaultConfig(),this.isInitialized=!1,this.isCompactMode=!1,this.compactBreakpoint=null,this.compactObserver=null,this.mediaQueryObserver=null,this.mutationObserver=null,this.storageListener=null,this.themeCache=/* @__PURE__ */new Map,this.appliedStyles=/* @__PURE__ */new Set,this.changeCallbacks=/* @__PURE__ */new Set}_getDefaultConfig(){return{theme:{auto:!0,storage:!0,inherit:!0,smooth:!0,detectSystem:!0},compact:{enabled:!1,auto:!0,breakpoint:768,forceOnMobile:!0,persistPreference:!0},presets:{light:{name:"light",displayName:"Claro",variables:{"--limbo-primary":"#3b82f6","--limbo-primary-hover":"#2563eb","--limbo-primary-light":"#dbeafe","--limbo-primary-dark":"#1e40af","--limbo-bg-primary":"#ffffff","--limbo-bg-secondary":"#f8fafc","--limbo-bg-tertiary":"#f1f5f9","--limbo-bg-overlay":"rgba(0, 0, 0, 0.5)","--limbo-bg-card":"#ffffff","--limbo-bg-input":"#ffffff","--limbo-text-primary":"#0f172a","--limbo-text-secondary":"#475569","--limbo-text-tertiary":"#64748b","--limbo-text-inverse":"#ffffff","--limbo-text-muted":"#94a3b8","--limbo-border-light":"#e2e8f0","--limbo-border-medium":"#cbd5e1","--limbo-border-strong":"#94a3b8","--limbo-border-focus":"#3b82f6","--limbo-success":"#10b981","--limbo-success-light":"#d1fae5","--limbo-error":"#ef4444","--limbo-error-light":"#fee2e2","--limbo-warning":"#f59e0b","--limbo-warning-light":"#fef3c7","--limbo-info":"#3b82f6","--limbo-info-light":"#dbeafe","--limbo-shadow-sm":"0 1px 2px 0 rgba(0, 0, 0, 0.05)","--limbo-shadow-md":"0 4px 6px -1px rgba(0, 0, 0, 0.1)","--limbo-shadow-lg":"0 10px 15px -3px rgba(0, 0, 0, 0.1)","--limbo-shadow-xl":"0 20px 25px -5px rgba(0, 0, 0, 0.1)","--limbo-radius-sm":"4px","--limbo-radius-md":"6px","--limbo-radius-lg":"8px","--limbo-radius-xl":"12px","--limbo-font-family":"system-ui, -apple-system, sans-serif","--limbo-font-size-xs":"12px","--limbo-font-size-sm":"14px","--limbo-font-size-md":"16px","--limbo-font-size-lg":"18px","--limbo-font-size-xl":"20px","--limbo-z-dropdown":"1000","--limbo-z-sticky":"1020","--limbo-z-fixed":"1030","--limbo-z-modal":"1050","--limbo-z-tooltip":"1070","--limbo-transition-fast":"150ms cubic-bezier(0.4, 0, 0.2, 1)","--limbo-transition-normal":"300ms cubic-bezier(0.4, 0, 0.2, 1)","--limbo-transition-slow":"500ms cubic-bezier(0.4, 0, 0.2, 1)","--limbo-spacing-compact":"0.5rem","--limbo-spacing-compact-sm":"0.25rem","--limbo-spacing-compact-lg":"0.75rem","--limbo-font-size-compact-xs":"11px","--limbo-font-size-compact-sm":"12px","--limbo-font-size-compact-md":"14px","--limbo-font-size-compact-lg":"16px","--limbo-radius-compact":"4px","--limbo-radius-compact-sm":"3px","--limbo-radius-compact-lg":"6px","--limbo-button-height-compact":"32px","--limbo-input-height-compact":"36px","--limbo-modal-padding-compact":"12px","--limbo-card-padding-compact":"12px","--limbo-gap-compact":"8px","--limbo-gap-compact-sm":"4px","--limbo-gap-compact-lg":"12px"}},dark:{name:"dark",displayName:"Oscuro",variables:{"--limbo-primary":"#60a5fa","--limbo-primary-hover":"#3b82f6","--limbo-primary-light":"#1e293b","--limbo-primary-dark":"#93c5fd","--limbo-bg-primary":"#0f172a","--limbo-bg-secondary":"#1e293b","--limbo-bg-tertiary":"#334155","--limbo-bg-overlay":"rgba(0, 0, 0, 0.8)","--limbo-bg-card":"#1e293b","--limbo-bg-input":"#334155","--limbo-text-primary":"#f8fafc","--limbo-text-secondary":"#cbd5e1","--limbo-text-tertiary":"#94a3b8","--limbo-text-inverse":"#0f172a","--limbo-text-muted":"#64748b","--limbo-border-light":"#334155","--limbo-border-medium":"#475569","--limbo-border-strong":"#64748b","--limbo-border-focus":"#60a5fa","--limbo-success":"#34d399","--limbo-success-light":"#064e3b","--limbo-error":"#f87171","--limbo-error-light":"#7f1d1d","--limbo-warning":"#fbbf24","--limbo-warning-light":"#78350f","--limbo-info":"#60a5fa","--limbo-info-light":"#1e3a8a","--limbo-shadow-sm":"0 1px 2px 0 rgba(0, 0, 0, 0.2)","--limbo-shadow-md":"0 4px 6px -1px rgba(0, 0, 0, 0.3)","--limbo-shadow-lg":"0 10px 15px -3px rgba(0, 0, 0, 0.4)","--limbo-shadow-xl":"0 20px 25px -5px rgba(0, 0, 0, 0.5)","--limbo-radius-sm":"4px","--limbo-radius-md":"6px","--limbo-radius-lg":"8px","--limbo-radius-xl":"12px","--limbo-font-family":"system-ui, -apple-system, sans-serif","--limbo-font-size-xs":"12px","--limbo-font-size-sm":"14px","--limbo-font-size-md":"16px","--limbo-font-size-lg":"18px","--limbo-font-size-xl":"20px","--limbo-z-dropdown":"1000","--limbo-z-sticky":"1020","--limbo-z-fixed":"1030","--limbo-z-modal":"1050","--limbo-z-tooltip":"1070","--limbo-transition-fast":"150ms cubic-bezier(0.4, 0, 0.2, 1)","--limbo-transition-normal":"300ms cubic-bezier(0.4, 0, 0.2, 1)","--limbo-transition-slow":"500ms cubic-bezier(0.4, 0, 0.2, 1)","--limbo-spacing-compact":"0.5rem","--limbo-spacing-compact-sm":"0.25rem","--limbo-spacing-compact-lg":"0.75rem","--limbo-font-size-compact-xs":"11px","--limbo-font-size-compact-sm":"12px","--limbo-font-size-compact-md":"14px","--limbo-font-size-compact-lg":"16px","--limbo-radius-compact":"4px","--limbo-radius-compact-sm":"3px","--limbo-radius-compact-lg":"6px","--limbo-button-height-compact":"32px","--limbo-input-height-compact":"36px","--limbo-modal-padding-compact":"12px","--limbo-card-padding-compact":"12px","--limbo-gap-compact":"8px","--limbo-gap-compact-sm":"4px","--limbo-gap-compact-lg":"12px"}},auto:{name:"auto",displayName:"Automático",variables:{}}},inheritance:{portalSelectors:["body","[data-theme]",".theme-light",".theme-dark",".light-theme",".dark-theme"],variablePrefix:"--",fallbackTheme:"light"},transitions:{duration:"300ms",easing:"cubic-bezier(0.4, 0, 0.2, 1)",properties:["background-color","border-color","color","fill","stroke","box-shadow"]}}}initialize(e={}){this.isInitialized?console.warn("ThemeManager already initialized"):(this.config=this._deepMerge(this.config,e),this._loadCustomThemes(),this.config.theme.inherit&&this._inheritPortalTheme(),this._applyInitialTheme(),this._applyInitialCompactMode(),this._setupObservers(),this._injectBaseStyles(),this.isInitialized=!0)}_injectBaseStyles(){if(document.getElementById("limbo-theme-styles"))return;const e=`\n :root {\n /* Variables de transición para cambios de tema */\n color-scheme: light dark;\n }\n \n [data-limbo-theme] {\n transition: ${this.config.transitions.properties.map(e=>`${e} ${this.config.transitions.duration} ${this.config.transitions.easing}`).join(", ")};\n }\n \n /* Clases de utilidad para temas */\n .limbo-theme-light {\n color-scheme: light;\n }\n \n .limbo-theme-dark {\n color-scheme: dark;\n }\n \n .limbo-theme-auto {\n color-scheme: light dark;\n }\n \n /* Estilos para elementos del componente con variables CSS */\n .limbo-component {\n background-color: var(--limbo-bg-primary);\n color: var(--limbo-text-primary);\n border-color: var(--limbo-border-light);\n border-radius: var(--limbo-radius-md);\n font-family: var(--limbo-font-family);\n font-size: var(--limbo-font-size-md);\n transition: var(--limbo-transition-normal);\n }\n \n .limbo-card {\n background-color: var(--limbo-bg-card);\n border: 1px solid var(--limbo-border-light);\n border-radius: var(--limbo-radius-lg);\n box-shadow: var(--limbo-shadow-md);\n color: var(--limbo-text-primary);\n }\n \n .limbo-input {\n background-color: var(--limbo-bg-input);\n border: 1px solid var(--limbo-border-medium);\n border-radius: var(--limbo-radius-md);\n color: var(--limbo-text-primary);\n font-family: var(--limbo-font-family);\n font-size: var(--limbo-font-size-md);\n transition: var(--limbo-transition-fast);\n }\n \n .limbo-input:focus {\n border-color: var(--limbo-border-focus);\n box-shadow: 0 0 0 3px var(--limbo-primary-light);\n outline: none;\n }\n \n .limbo-button {\n background-color: var(--limbo-primary);\n border: 1px solid var(--limbo-primary);\n border-radius: var(--limbo-radius-md);\n color: var(--limbo-text-inverse);\n font-family: var(--limbo-font-family);\n font-size: var(--limbo-font-size-md);\n transition: var(--limbo-transition-fast);\n cursor: pointer;\n }\n \n .limbo-button:hover {\n background-color: var(--limbo-primary-hover);\n border-color: var(--limbo-primary-hover);\n }\n \n .limbo-button.secondary {\n background-color: var(--limbo-bg-secondary);\n border-color: var(--limbo-border-medium);\n color: var(--limbo-text-primary);\n }\n \n .limbo-button.secondary:hover {\n background-color: var(--limbo-bg-tertiary);\n }\n \n /* Estados de feedback con variables */\n .limbo-state-success {\n background-color: var(--limbo-success-light);\n border-color: var(--limbo-success);\n color: var(--limbo-success);\n }\n \n .limbo-state-error {\n background-color: var(--limbo-error-light);\n border-color: var(--limbo-error);\n color: var(--limbo-error);\n }\n \n .limbo-state-warning {\n background-color: var(--limbo-warning-light);\n border-color: var(--limbo-warning);\n color: var(--limbo-warning);\n }\n \n .limbo-state-info {\n background-color: var(--limbo-info-light);\n border-color: var(--limbo-info);\n color: var(--limbo-info);\n }\n \n /* Overlay y modal con variables */\n .limbo-overlay {\n background-color: var(--limbo-bg-overlay);\n backdrop-filter: blur(4px);\n }\n \n .limbo-modal {\n background-color: var(--limbo-bg-card);\n border-radius: var(--limbo-radius-xl);\n box-shadow: var(--limbo-shadow-xl);\n color: var(--limbo-text-primary);\n }\n \n /* Responsive design con variables */\n @media (max-width: 640px) {\n .limbo-component {\n font-size: var(--limbo-font-size-sm);\n }\n }\n \n /* Modo reducido de movimiento */\n @media (prefers-reduced-motion: reduce) {\n [data-limbo-theme] {\n transition: none;\n }\n \n .limbo-component,\n .limbo-input,\n .limbo-button {\n transition: none;\n }\n }\n \n /* Esquemas de color automático */\n @media (prefers-color-scheme: dark) {\n :root:not([data-limbo-theme]) {\n color-scheme: dark;\n }\n }\n \n @media (prefers-color-scheme: light) {\n :root:not([data-limbo-theme]) {\n color-scheme: light;\n }\n }\n \n /* ===================================\n MODO COMPACTO - ESTILOS ESPECÍFICOS \n =================================== */\n \n /* Activación del modo compacto por atributo o clase */\n [data-limbo-compact="true"],\n .limbo-compact-mode {\n /* Componentes base más pequeños */\n --limbo-font-size-md: var(--limbo-font-size-compact-md);\n --limbo-font-size-sm: var(--limbo-font-size-compact-sm);\n --limbo-font-size-lg: var(--limbo-font-size-compact-lg);\n --limbo-spacing: var(--limbo-spacing-compact);\n --limbo-radius-md: var(--limbo-radius-compact);\n --limbo-gap: var(--limbo-gap-compact);\n }\n \n /* Botones compactos */\n [data-limbo-compact="true"] .limbo-button,\n .limbo-compact-mode .limbo-button {\n height: var(--limbo-button-height-compact);\n padding: var(--limbo-spacing-compact-sm) var(--limbo-spacing-compact);\n font-size: var(--limbo-font-size-compact-sm);\n border-radius: var(--limbo-radius-compact);\n min-width: auto;\n }\n \n /* Inputs compactos */\n [data-limbo-compact="true"] .limbo-input,\n .limbo-compact-mode .limbo-input {\n height: var(--limbo-input-height-compact);\n padding: var(--limbo-spacing-compact-sm) var(--limbo-spacing-compact);\n font-size: var(--limbo-font-size-compact-md);\n border-radius: var(--limbo-radius-compact);\n }\n \n /* Cards compactas */\n [data-limbo-compact="true"] .limbo-card,\n .limbo-compact-mode .limbo-card {\n padding: var(--limbo-card-padding-compact);\n border-radius: var(--limbo-radius-compact-lg);\n }\n \n /* Modales compactos */\n [data-limbo-compact="true"] .limbo-modal,\n .limbo-compact-mode .limbo-modal {\n padding: var(--limbo-modal-padding-compact);\n border-radius: var(--limbo-radius-compact-lg);\n max-width: 90vw;\n max-height: 90vh;\n }\n \n /* Tabs compactas */\n [data-limbo-compact="true"] .limbo-tabs,\n .limbo-compact-mode .limbo-tabs {\n gap: var(--limbo-gap-compact-sm);\n }\n \n [data-limbo-compact="true"] .limbo-tab,\n .limbo-compact-mode .limbo-tab {\n padding: var(--limbo-spacing-compact-sm) var(--limbo-spacing-compact);\n font-size: var(--limbo-font-size-compact-sm);\n border-radius: var(--limbo-radius-compact-sm);\n }\n \n /* Gallery compacta */\n [data-limbo-compact="true"] .limbo-gallery,\n .limbo-compact-mode .limbo-gallery {\n gap: var(--limbo-gap-compact-sm);\n }\n \n [data-limbo-compact="true"] .limbo-gallery-item,\n .limbo-compact-mode .limbo-gallery-item {\n border-radius: var(--limbo-radius-compact);\n min-height: 120px; /* Más pequeño para móviles */\n }\n \n /* Notificaciones compactas */\n [data-limbo-compact="true"] .limbo-notification,\n .limbo-compact-mode .limbo-notification {\n padding: var(--limbo-spacing-compact-sm) var(--limbo-spacing-compact);\n font-size: var(--limbo-font-size-compact-sm);\n border-radius: var(--limbo-radius-compact);\n }\n \n /* Progress indicators compactos */\n [data-limbo-compact="true"] .limbo-progress,\n .limbo-compact-mode .limbo-progress {\n height: 3px; /* Más delgado */\n }\n \n [data-limbo-compact="true"] .limbo-progress-circular,\n .limbo-compact-mode .limbo-progress-circular {\n width: 20px;\n height: 20px;\n }\n \n /* Auto-activación en pantallas pequeñas */\n @media (max-width: 768px) {\n :root[data-limbo-compact="auto"],\n .limbo-component[data-limbo-compact="auto"] {\n /* Aplicar automáticamente estilos compactos */\n --limbo-font-size-md: var(--limbo-font-size-compact-md);\n --limbo-font-size-sm: var(--limbo-font-size-compact-sm);\n --limbo-spacing: var(--limbo-spacing-compact);\n --limbo-radius-md: var(--limbo-radius-compact);\n --limbo-gap: var(--limbo-gap-compact);\n }\n \n /* Modal full-screen en móvil cuando es compacto */\n [data-limbo-compact="auto"] .limbo-modal,\n [data-limbo-compact="true"] .limbo-modal {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n width: 100vw;\n height: 100vh;\n max-width: 100vw;\n max-height: 100vh;\n border-radius: 0;\n margin: 0;\n }\n \n /* Tabs en accordion en móvil */\n [data-limbo-compact="auto"] .limbo-tabs,\n [data-limbo-compact="true"] .limbo-tabs {\n flex-direction: column;\n width: 100%;\n }\n \n /* Gallery de 2 columnas en móvil */\n [data-limbo-compact="auto"] .limbo-gallery,\n [data-limbo-compact="true"] .limbo-gallery {\n grid-template-columns: 1fr 1fr;\n gap: var(--limbo-gap-compact);\n }\n }\n \n /* Touch targets más grandes en móviles */\n @media (max-width: 768px) and (pointer: coarse) {\n [data-limbo-compact="auto"] .limbo-button,\n [data-limbo-compact="true"] .limbo-button {\n min-height: 44px; /* Tamaño mínimo de toque recomendado */\n padding: var(--limbo-spacing-compact) var(--limbo-spacing-compact-lg);\n }\n \n [data-limbo-compact="auto"] .limbo-tab,\n [data-limbo-compact="true"] .limbo-tab {\n min-height: 44px;\n }\n }\n `,t=document.createElement("style");t.id="limbo-theme-styles",t.textContent=e,document.head.appendChild(t)}applyTheme(e,t={}){const n=this._getTheme(e);if(!n)return console.warn(`Theme '${e}' not found`),!1;const l=this.currentTheme;return this._applyThemeVariables(n,t.scope),this._updateThemeAttributes(n.name),this.config.theme.storage&&!t.temporary&&this._saveThemePreference(n.name),this.currentTheme=n.name,this._triggerChangeCallbacks(n.name,l),!0}toggleTheme(e="light",t="dark"){const n=this.currentTheme===e?t:e;return this.applyTheme(n)}applyAutoTheme(){const e=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";return this.applyTheme(e)}registerTheme(e,t){const n={name:e,displayName:t.displayName||e,variables:t.variables||{},extends:t.extends||null,...t};if(n.extends){const e=this._getTheme(n.extends);e&&(n.variables={...e.variables,...n.variables})}return this.customThemes.set(e,n),this}removeTheme(e){if(this.config.presets[e])return console.warn(`Cannot remove predefined theme: ${e}`),!1;const t=this.customThemes.delete(e);return t&&this.currentTheme===e&&this.applyTheme(this.config.inheritance.fallbackTheme),t}getAvailableThemes(){const e=Object.keys(this.config.presets),t=Array.from(this.customThemes.keys());return{presets:e,custom:t,all:[...e,...t]}}getCurrentTheme(){return{name:this.currentTheme,theme:this._getTheme(this.currentTheme),isCustom:this.customThemes.has(this.currentTheme),variables:this._getCurrentVariables()}}enableCompactMode(e={}){const t={element:document.documentElement,persist:!0,...e};return t.element.setAttribute("data-limbo-compact","true"),t.element.classList.add("limbo-compact-mode"),this.isCompactMode=!0,t.persist&&this.config.compact.persistPreference&&this._saveCompactPreference(!0),this._triggerCompactChange(!0),this}disableCompactMode(e={}){const t={element:document.documentElement,persist:!0,...e};return t.element.setAttribute("data-limbo-compact","false"),t.element.classList.remove("limbo-compact-mode"),this.isCompactMode=!1,t.persist&&this.config.compact.persistPreference&&this._saveCompactPreference(!1),this._triggerCompactChange(!1),this}toggleCompactMode(e={}){return this.isCompactMode?this.disableCompactMode(e):this.enableCompactMode(e)}applyAutoCompactMode(){const e=this._shouldUseCompactMode();return e&&!this.isCompactMode?this.enableCompactMode({persist:!1}):!e&&this.isCompactMode&&this.disableCompactMode({persist:!1}),this}getCompactState(){return{isEnabled:this.isCompactMode,isAuto:this.config.compact.auto,breakpoint:this.config.compact.breakpoint,currentViewport:window.innerWidth,shouldBeCompact:this._shouldUseCompactMode()}}_shouldUseCompactMode(){if(!this.config.compact.auto)return this.config.compact.enabled;const e=window.innerWidth<=this.config.compact.breakpoint,t=/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),n="ontouchstart"in window||navigator.maxTouchPoints>0;return!(!this.config.compact.forceOnMobile||!t&&!n)||e}_saveCompactPreference(e){try{localStorage.setItem("limbo-compact-preference",e.toString())}catch(t){console.warn("Could not save compact preference:",t)}}_loadCompactPreference(){try{return"true"===localStorage.getItem("limbo-compact-preference")}catch(e){return console.warn("Could not load compact preference:",e),null}}_triggerCompactChange(e){this.changeCallbacks.forEach(t=>{try{t({type:"compact",isCompact:e,viewport:window.innerWidth,timestamp:Date.now()})}catch(n){console.error("Error in compact mode change callback:",n)}})}_inheritPortalTheme(){const e=this._detectPortalTheme();return e?(this.registerTheme("portal-inherited",e),"portal-inherited"):null}_detectPortalTheme(){const e={name:"portal-detected",displayName:"Tema del Portal",variables:{}};for(const t of this.config.inheritance.portalSelectors){const n=document.querySelector(t);if(n){const t=this._extractCSSVariables(n);Object.keys(t).length>0&&(e.variables={...e.variables,...t});const l=n.getAttribute("data-theme")||n.getAttribute("class")?.match(/theme-(\w+)/)||n.getAttribute("class")?.match(/(\w+)-theme/);l&&(e.detectedName=Array.isArray(l)?l[1]:l)}}return Object.keys(e.variables).length>0?e:null}_extractCSSVariables(e){const t={},n=getComputedStyle(e);["primary","primary-hover","primary-light","primary-dark","bg-primary","bg-secondary","bg-tertiary","bg-card","bg-input","text-primary","text-secondary","text-tertiary","text-inverse","border-light","border-medium","border-strong","border-focus","success","error","warning","info","shadow-sm","shadow-md","shadow-lg","shadow-xl","radius-sm","radius-md","radius-lg","radius-xl"].forEach(e=>{const l=`--limbo-${e}`,r=n.getPropertyValue(l).trim();r&&(t[l]=r)});return["--primary-color","--background-color","--text-color","--border-color","--accent-color","--surface-color"].forEach(e=>{const l=n.getPropertyValue(e).trim();if(l){const n=this._mapGenericToLimbo(e,l);n&&Object.assign(t,n)}}),t}_mapGenericToLimbo(e,t){return{"--primary-color":{"--limbo-primary":t},"--background-color":{"--limbo-bg-primary":t},"--text-color":{"--limbo-text-primary":t},"--border-color":{"--limbo-border-light":t},"--accent-color":{"--limbo-primary":t},"--surface-color":{"--limbo-bg-card":t}}[e]||null}_applyInitialTheme(){let e=this.config.inheritance.fallbackTheme;if(this.config.theme.storage){const t=this._loadThemePreference();t&&this._getTheme(t)&&(e=t)}const t=document.documentElement.getAttribute("data-limbo-theme");t&&this._getTheme(t)&&(e=t);const n=this._inheritPortalTheme();n&&(e=n),this.config.theme.auto&&"auto"===e&&(e=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),this.applyTheme(e,{temporary:!1})}_applyInitialCompactMode(){let e=!1;if(this.config.compact.persistPreference){const t=this._loadCompactPreference();null!==t&&(e=t)}const t=document.documentElement.getAttribute("data-limbo-compact");"true"===t?e=!0:"false"===t&&(e=!1),("auto"===t||this.config.compact.auto)&&(e=this._shouldUseCompactMode()),e?this.enableCompactMode({persist:!1}):this.disableCompactMode({persist:!1})}_applyThemeVariables(e,t=document.documentElement){const n="string"==typeof t?document.querySelector(t):t;n?(Object.entries(e.variables).forEach(([e,t])=>{n.style.setProperty(e,t),this.appliedStyles.add(`${n.tagName}:${e}`)}),this.themeCache.set(e.name,{theme:e,appliedAt:Date.now(),scope:n})):console.warn("Theme scope element not found")}_updateThemeAttributes(e){document.documentElement.setAttribute("data-limbo-theme",e),document.documentElement.classList.remove("limbo-theme-light","limbo-theme-dark","limbo-theme-auto"),document.documentElement.classList.add(`limbo-theme-${e}`),this._updateMetaThemeColor(e)}_updateMetaThemeColor(e){const t=this._getTheme(e);if(!t)return;const n=t.variables["--limbo-primary"]||"#3b82f6";let l=document.querySelector('meta[name="theme-color"]');l||(l=document.createElement("meta"),l.name="theme-color",document.head.appendChild(l)),l.content=n}_getTheme(e){return this.config.presets[e]?this.config.presets[e]:this.customThemes.has(e)?this.customThemes.get(e):null}_getCurrentVariables(){const e=this._getTheme(this.currentTheme);if(!e)return{};const t=getComputedStyle(document.documentElement),n={};return Object.keys(e.variables).forEach(e=>{n[e]=t.getPropertyValue(e).trim()}),n}_saveThemePreference(e){try{localStorage.setItem("limbo-theme-preference",e)}catch(t){console.warn("Could not save theme preference:",t)}}_loadThemePreference(){try{return localStorage.getItem("limbo-theme-preference")}catch(e){return console.warn("Could not load theme preference:",e),null}}_loadCustomThemes(){try{const e=localStorage.getItem("limbo-custom-themes");if(e){const t=JSON.parse(e);Object.entries(t).forEach(([e,t])=>{this.customThemes.set(e,t)})}}catch(e){console.warn("Could not load custom themes:",e)}}_saveCustomThemes(){try{const e=Object.fromEntries(this.customThemes);localStorage.setItem("limbo-custom-themes",JSON.stringify(e))}catch(e){console.warn("Could not save custom themes:",e)}}_setupObservers(){this.config.theme.detectSystem&&this._setupSystemObserver(),this.config.theme.storage&&this._setupStorageObserver(),this._setupMutationObserver(),this.config.compact.auto&&this._setupViewportObserver()}_setupSystemObserver(){const e=window.matchMedia("(prefers-color-scheme: dark)");e.addEventListener("change",e=>{if("auto"===this.currentTheme||this.config.theme.auto){const t=e.matches?"dark":"light";this.applyTheme(t,{temporary:!0})}}),this.mediaQueryObserver=e}_setupStorageObserver(){const e=e=>{"limbo-theme-preference"===e.key&&e.newValue!==this.currentTheme&&this._getTheme(e.newValue)&&this.applyTheme(e.newValue)};window.addEventListener("storage",e),this.storageListener=e}_setupMutationObserver(){const e=new MutationObserver(e=>{e.forEach(e=>{if("attributes"===e.type&&"data-limbo-theme"===e.attributeName){const t=e.target.getAttribute("data-limbo-theme");t&&t!==this.currentTheme&&this._getTheme(t)&&this.applyTheme(t)}})});e.observe(document.documentElement,{attributes:!0,attributeFilter:["data-limbo-theme"]}),this.mutationObserver=e}_setupViewportObserver(){const e=`(max-width: ${this.config.compact.breakpoint}px)`,t=window.matchMedia(e);t.addEventListener("change",()=>{("auto"===document.documentElement.getAttribute("data-limbo-compact")||this.config.compact.auto)&&this.applyAutoCompactMode()}),this.compactObserver=t,window.addEventListener("orientationchange",()=>{setTimeout(()=>{("auto"===document.documentElement.getAttribute("data-limbo-compact")||this.config.compact.auto)&&this.applyAutoCompactMode()},100)})}onThemeChange(e){return this.changeCallbacks.add(e),()=>this.changeCallbacks.delete(e)}_triggerChangeCallbacks(e,t){this.changeCallbacks.forEach(n=>{try{n({theme:e,previousTheme:t,themeData:this._getTheme(e),variables:this._getCurrentVariables()})}catch(l){console.error("Error in theme change callback:",l)}})}generateThemeFromColors(e,t){const n={name:e,displayName:e,variables:{}};t.primary&&(n.variables["--limbo-primary"]=t.primary,n.variables["--limbo-primary-hover"]=this._darkenColor(t.primary,10),n.variables["--limbo-primary-light"]=this._lightenColor(t.primary,40),n.variables["--limbo-primary-dark"]=this._darkenColor(t.primary,20)),t.background&&(n.variables["--limbo-bg-primary"]=t.background,n.variables["--limbo-bg-secondary"]=this._lightenColor(t.background,5),n.variables["--limbo-bg-tertiary"]=this._lightenColor(t.background,10),n.variables["--limbo-bg-card"]=t.background),t.text&&(n.variables["--limbo-text-primary"]=t.text,n.variables["--limbo-text-secondary"]=this._lightenColor(t.text,20),n.variables["--limbo-text-tertiary"]=this._lightenColor(t.text,40));const l=this._getTheme(this.config.inheritance.fallbackTheme);return l&&(n.variables={...l.variables,...n.variables}),this.registerTheme(e,n),n}_darkenColor(e,t){const n=parseInt(e.replace("#",""),16),l=Math.round(2.55*t),r=(n>>16)-l,a=(n>>8&255)-l,i=(255&n)-l;return"#"+(16777216+65536*(r<255?r<1?0:r:255)+256*(a<255?a<1?0:a:255)+(i<255?i<1?0:i:255)).toString(16).slice(1)}_lightenColor(e,t){const n=parseInt(e.replace("#",""),16),l=Math.round(2.55*t),r=(n>>16)+l,a=(n>>8&255)+l,i=(255&n)+l;return"#"+(16777216+65536*(r<255?r<1?0:r:255)+256*(a<255?a<1?0:a:255)+(i<255?i<1?0:i:255)).toString(16).slice(1)}_deepMerge(e,t){const n={...e};return Object.keys(t).forEach(l=>{t[l]&&"object"==typeof t[l]&&!Array.isArray(t[l])?n[l]=this._deepMerge(e[l]||{},t[l]):n[l]=t[l]}),n}getThemeInfo(){return{current:this.getCurrentTheme(),available:this.getAvailableThemes(),compact:this.getCompactState(),config:this.config,isInitialized:this.isInitialized,cache:{themes:this.themeCache.size,applied:this.appliedStyles.size},observers:{system:!!this.mediaQueryObserver,storage:!!this.storageListener,mutation:!!this.mutationObserver,viewport:!!this.compactObserver}}}debug(){return console.table(this.getThemeInfo()),this.getThemeInfo()}destroy(){this.mediaQueryObserver&&this.mediaQueryObserver.removeEventListener("change",this._setupSystemObserver),this.storageListener&&window.removeEventListener("storage",this.storageListener),this.mutationObserver&&this.mutationObserver.disconnect(),this.compactObserver&&this.compactObserver.removeEventListener("change",this._setupViewportObserver),this.changeCallbacks.clear(),this.themeCache.clear(),this.appliedStyles.clear(),this._saveCustomThemes();const e=document.getElementById("limbo-theme-styles");e&&e.remove(),this.isInitialized=!1}}const Hl={border:"none",borderRadius:"6px",cursor:"pointer",fontFamily:"inherit",fontWeight:"500",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"6px",transition:"background 0.2s ease, transform 0.1s ease",userSelect:"none",textDecoration:"none",lineHeight:"1.25"},Kl={bg:"#001978",hover:"#334793"},Gl={bg:"#10b981",hover:"#059669"},Ql={bg:"#9ca3af",hover:"#9ca3af"};class Xl extends HTMLElement{constructor(){super(),this._btn=null,this._limboInstance=null}connectedCallback(){this._ensureButton(),this._syncButton()}disconnectedCallback(){this._destroyLimboInstance()}static get observedAttributes(){return["accept","has-file","disabled","compact","label-select","label-change","return-format","button-class","existing-url","mandatory-crops","public-key","token","auth-mode"]}attributeChangedCallback(){this._btn&&this._syncButton()}markSelected(e){this.setAttribute("has-file",""),e&&this.setAttribute("existing-url",e),this._syncButton()}clearSelection(){this.removeAttribute("has-file"),this.removeAttribute("existing-url"),this._syncButton()}open(){this._open()}_ensureButton(){this._btn||(this._btn=document.createElement("button"),this._btn.type="button",this._btn.classList.add("limbo-selector-btn","limbo-trigger-button","mecano:my-2"),this._btn.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),this._open()}),this.appendChild(this._btn))}_syncButton(){if(!this._btn)return;const e=this.getAttribute("accept")||null,t=this.hasAttribute("has-file"),n=this.hasAttribute("disabled"),l=this.hasAttribute("compact"),r=this.getAttribute("label-select")||null,a=this.getAttribute("label-change")||null,i=this.getAttribute("button-class")||null;this._btn.textContent=t?a||v(e,!0):r||v(e,!1),this._btn.disabled=n,i&&i.split(/\s+/).filter(Boolean).forEach(e=>this._btn.classList.add(e));const o=n?Ql:t?Gl:Kl;Object.assign(this._btn.style,{...Hl,fontSize:l?"12px":"14px",padding:l?"6px 12px":"8px 16px",background:o.bg,color:"white",opacity:n?"0.55":"1",cursor:n?"not-allowed":"pointer"}),this._btn.onmouseenter=()=>{n||(this._btn.style.background=o.hover,this._btn.style.transform="translateY(-1px)",this._btn.style.boxShadow="0 4px 10px rgba(0,0,0,0.18)")},this._btn.onmouseleave=()=>{this._btn.style.background=o.bg,this._btn.style.transform="translateY(0)",this._btn.style.boxShadow="none"}}_open(){const e=window.Limbo||window.limboCore;if(!e)return void console.warn("[LimboSelector] window.Limbo no encontrado. Asegúrate de que el script de Limbo está cargado antes de usar <limbo-selector>.");const t=this.getAttribute("accept")||null,n=this.getAttribute("return-format")||"url",l=this.getAttribute("existing-url")||null,r=this.getAttribute("public-key")||null,a=this.getAttribute("token")||null,i=this.getAttribute("auth-mode")||null;(r||a)&&e.configure({...r&&{publicKey:r},...a&&{token:a},authMode:i||(a?"manual":"session")}),e.config?.setGlobal&&e.config.setGlobal({interaction:{allowSelection:!0,allowCropping:!0,selectionMode:"direct"}});let o=null;const s=this.getAttribute("mandatory-crops");if(s)try{o=JSON.parse(s)}catch{}this._destroyLimboInstance();try{const r={mode:"modal",modeUI:"full",modalSize:"fullscreen",features:["gallery","upload","cropper"],title:"Seleccionar archivo",validation:{accept:t},returnConfig:{format:n},initialImageUrl:l,interaction:{allowSelection:!0,allowCropping:!0},cropper:o?.length>0?{mandatoryCrops:o,allowAdditionalCrops:!0,maxCrops:10}:null},a=async e=>{const t="string"==typeof e?e:e?.images?.[0]?.url||e?.original?.url||e?.url||"";this.setAttribute("has-file",""),t&&this.setAttribute("existing-url",t),this._syncButton(),this.dispatchEvent(new CustomEvent("limbo:change",{detail:{data:e,url:t},bubbles:!0,composed:!0}))};e.events.emit("autoInputs:modalRequest",{config:r,input:null,callback:a})}catch(c){console.error("[LimboSelector] Error al abrir modal de Limbo:",c)}}_handleResult(e,t){if(this._limboInstance!==t)return;const n="string"==typeof e?e:e?.url||e?.master?.urlSigned||e?.master?.url||e?.asset?.url||e?.original?.url||e?.crops?.[0]?.url||e?.images?.[0]?.url||"";this.setAttribute("has-file",""),n&&this.setAttribute("existing-url",n),this._syncButton(),this.dispatchEvent(new CustomEvent("limbo:change",{detail:{data:e,url:n},bubbles:!0,composed:!0}));try{t?.close?.()}catch{}this._limboInstance=null}_destroyLimboInstance(){if(this._limboInstance){try{this._limboInstance.destroy?.()}catch{}this._limboInstance=null}}}function Yl(e="limbo-selector"){"undefined"==typeof customElements||customElements.get(e)||customElements.define(e,Xl)}const Jl=new class{constructor(){this.config=new C,this.instances=new jl,this.autoInputs=new Ul,this.events=new Bl,this.modals=new Wl,this.theme=new Vl,this.containerQueryDetector=M,this._setupInternalListeners(),this._initializeContainerQueries()}configure(e){this.config.setGlobal(e);const t={};var n;return"publicKey"in e&&(t.publicKey=e.publicKey),"apiKey"in e&&(t.apiKey=e.apiKey),"token"in e&&(t.token=e.token),"authMode"in e&&(t.authMode=e.authMode),"tokenProvider"in e&&(t.tokenProvider=e.tokenProvider),"prod"in e&&(t.prod=Boolean(e.prod)),"mode"in e&&(t.mode=e.mode),"callbacks"in e&&(t.callbacks=e.callbacks),"token"in(n=t)&&n.token!==U.token&&(B=!1,W=null),U={...U,...n},U.authMode||(U.token?U.authMode="manual":U.authMode="session"),this.config}setToken(e){return Q(e),this.config.setGlobal({token:e}),this}create(e){const t=this.config.merge(e);return this.instances.create(t,this.events,this.modals)}configureAutoInputs(e){return this.autoInputs.configure(e,this.config,this.events)}setTheme(e){return e&&(this.config.set("theme",e),this.theme.setTheme(e),this.events.emit("theme:changed",{theme:e})),this}getTheme(){return this.theme.getCurrentTheme()}scanAndActivate(e=null){const t=this.autoInputs.config?.dataset||"data-limbo-input-file",n=e||`[${t}]`,l=document.querySelectorAll(n);if(0===l.length)return{found:0,processed:0,skipped:0};let r=0,a=0;return l.forEach(e=>{try{this.autoInputs._processInput(e),r++}catch(t){console.warn(`⚠️ Limbo: Error procesando input ${e.id||e.name}:`,t),a++}}),this.events.emit("limbo:scanCompleted",{found:l.length,processed:r,skipped:a,inputs:Array.from(l)}),{found:l.length,processed:r,skipped:a}}_initializeContainerQueries(){this.containerQueryDetector.observeResize(),setTimeout(()=>{document.querySelectorAll(".limbo-component-container-wrapper").forEach(e=>{this.containerQueryDetector.applyResponsiveClasses(e)})},100)}rescan(e=document){const t=this.autoInputs.config?.dataset||"data-limbo-input-file",n=e.querySelectorAll(`[${t}]`);let l=0;return n.forEach(e=>{if(!this.autoInputs.instances.has(this.autoInputs._getInputId(e)))try{this.autoInputs._processInput(e),l++}catch(t){console.warn("⚠️ Limbo: Error procesando nuevo input:",t)}}),l}init(e){const t=this._mapLegacyOptions(e);return this.create(t)}getInstances(){return this.instances.getAll()}destroy(){this.instances.destroyAll(),this.autoInputs.cleanup(),this.events.cleanup(),this.theme.removeTheme()}_mapLegacyOptions(e){return{container:e.container||"#image-manager",mode:"embed",features:["gallery","upload","cropper"],apiKey:e.apiKey,prod:e.prod||!1,url:void 0===e.url||e.url}}_setupInternalListeners(){this.events.on("autoInputs:modalRequest",({config:e,callback:t,input:n})=>{this._handleAutoInputModalRequest({config:e,callback:t,input:n})})}_handleAutoInputModalRequest({config:e,callback:t,input:n}){const l=n,r=async n=>{let r={};if(n.crops&&n.crops.length>0){const e=n.asset||n.original;r.original={url:e?.url||e?.urlSigned||n.originalUrl,width:e?.width||n.originalWidth,height:e?.height||n.originalHeight,assetId:e?.id||n.assetId},r.images=n.crops.map(e=>({url:e.url||e.urlSigned,width:e.width,height:e.height,name:e.name||e.filename}))}else n.asset?r.original={url:n.asset.url||n.asset.urlSigned,width:n.asset.width,height:n.asset.height,assetId:n.asset.id}:n.master?.urlSigned||n.master?.url?r.original={url:n.master.urlSigned||n.master.url,width:n.master.width||n.width,height:n.master.height||n.height,assetId:n.assetId}:n.url||n.urlSigned?r.original={url:n.url||n.urlSigned,width:n.width,height:n.height,assetId:n.assetId||n.id}:(console.warn("[Limbo] handleResult: formato de datos no reconocido",n),r=n);if(l){var a=e?.returnConfig?.format||"json",i="";i="url"===a?r.images?.[0]?.url||r.original?.url||"":"assetId"===a?r.original?.assetId||"":JSON.stringify(r),l.value=i,l.dispatchEvent(new Event("change",{bubbles:!0})),console.log("[Limbo] ✅ Valor asignado al input:",l.value?.substring(0,80))}try{await t(r)}catch(o){}c.close()},a={...e,mode:"modal",autoDestroy:!0,interaction:{allowSelection:!0,allowCropping:!0,...e.interaction},callbacks:{onSelect:e=>{r(e)},onCropsSaved:e=>{r(e)},onCropperComplete:e=>{r(e)},onUpload:t=>{"upload-only"!==e.modeUI||e.features?.includes("cropper")||r(t)},onClose:()=>{}}},i=e.validation?.accept||null,o=i?f(i):null,s=!o||o.isAllTypes||o.includesImages;if(e.initialImageUrl&&s){const t=this._extractAssetIdFromUrl(e.initialImageUrl)||e.existingData?.original?.assetId||null;t&&(a._externalImage={url:e.initialImageUrl,filename:e.initialImageUrl.split("/").pop()?.split("?")[0]||"image.jpg",width:1920,height:1080,mime_type:"image/jpeg",id:t})}e.cropper&&(a.cropper=e.cropper),this.config.setGlobal({interaction:{allowSelection:!0,allowCropping:!0,...e.interaction}});const c=this.create(a);c.open()}_extractAssetIdFromUrl(e){if(!e)return null;try{const t=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,n=e.match(t);return n&&n.length>=2?n[1]:n&&1===n.length?n[0]:null}catch(t){return console.warn("Error extracting asset ID from URL:",t),null}}openGallery(e={}){const t=this.create({mode:"modal",modeUI:"gallery-only",features:["gallery"],autoDestroy:!0,modal:{title:e.title||"Seleccionar Imagen",size:e.size||"large"},validation:{accept:e.accept||null},callbacks:{onSelect:n=>{e.onSelect?.(n),!1!==e.autoClose&&t.close()}},...e});return t.open(),t}openUploader(e={}){const t=!1!==e.redirectToGallery?["upload","gallery"]:["upload"],n=this.create({mode:"modal",modeUI:!1!==e.redirectToGallery?"full":"upload-only",features:t,autoDestroy:!0,modal:{title:e.title||"Subir Imagen",size:e.size||"medium"},validation:{accept:e.accept||null},callbacks:{onUpload:t=>{e.onUpload?.(t),!1===e.autoClose||e.redirectToGallery||n.close()}},...e});return n.open(),n}openCropper(e,t={}){if(!e)throw new Error("Limbo.openCropper: imageUrl es requerido");const n={url:e,filename:t.filename||"image.jpg",width:t.width||1920,height:t.height||1080,mime_type:t.mimeType||"image/jpeg",id:t.assetId||`external-${Date.now()}`},l=this.create({mode:"modal",modeUI:"crop-only",features:["cropper"],autoDestroy:!0,modal:{title:t.title||"Recortar Imagen",size:"xlarge"},cropper:{mandatoryCrops:t.mandatoryCrops||[],allowCustomCrops:!1!==t.allowCustomCrops,enforceRequiredCrops:!1!==t.enforceRequiredCrops},callbacks:{onCropperComplete:e=>{t.onComplete?.(e),!1!==t.autoClose&&l.close()},onCropperCancelled:e=>{t.onCancelled?.(e),!1!==t.autoClose&&l.close()},onCropperError:e=>{t.onError?.(e)}},_externalImage:n,...t});return l.open(),l}createInlineGallery(e,t={}){return this.create({container:e,mode:"embed",modeUI:"gallery-only",features:["gallery"],validation:{accept:t.accept||null},callbacks:{onSelect:t.onSelect,onDelete:t.onDelete},...t})}createInlineUploader(e,t={}){return this.create({container:e,mode:"embed",modeUI:"upload-only",features:["upload"],validation:{accept:t.accept||null},callbacks:{onUpload:t.onUpload},...t})}createStandaloneCropper(e,t,n={}){if(!e)throw new Error("Limbo.createStandaloneCropper: container es requerido");if(!t)throw new Error("Limbo.createStandaloneCropper: imageUrl es requerido");const l={url:t,filename:n.filename||"image.jpg",width:n.width||1920,height:n.height||1080,mime_type:n.mimeType||"image/jpeg",id:n.assetId||`external-${Date.now()}`};return this.create({container:e,mode:"embed",modeUI:"crop-only",features:["cropper"],autoHideOnComplete:!1!==n.autoHideOnComplete,cropper:{mandatoryCrops:n.mandatoryCrops||[],allowCustomCrops:!1!==n.allowCustomCrops,enforceRequiredCrops:!1!==n.enforceRequiredCrops},callbacks:{onCropperComplete:n.onComplete,onCropperCancelled:n.onCancelled,onCropperError:n.onError},_externalImage:l,...n})}createFullSelector(e,t={}){return this.create({container:e,mode:t.mode||"embed",modeUI:"full",features:["gallery","upload","cropper"],validation:{accept:t.accept||null},callbacks:{onSelect:t.onSelect,onUpload:t.onUpload,onDelete:t.onDelete,onCropsSaved:t.onCropsSaved},...t})}};"undefined"!=typeof window&&(window.Limbo=Jl,window.limboCore=Jl,Yl());"undefined"!=typeof window&&document.querySelector("#root")&&(Jl.configure({prod:!1,publicKey:"pk_e464fd744106b7a8d63d453c4bd02582",authMode:"session"}),Jl.create({container:"#root",mode:"embed",modeUI:"full",features:["gallery","upload","cropper"],title:"Limbo Image Manager - Development",url:!0}),Jl.configureAutoInputs({dataset:"data-limbo-input-file",return:"json",features:["gallery","upload","cropper"],modeUI:"full",modalSize:"large",title:"Seleccionar archivo",crops:"free",allowDelete:!1}));export{ze as LIMBO_BASE_URL,Xl as LimboSelector,Ae as decodeHtmlEntities,Jl as default,Ie as extractImageUrl,v as getButtonLabel,Le as isValidImageUrl,Pe as parseImageData,Oe as prepareImageFieldsForPreview,Yl as registerLimboSelector,Te as resolveUrl};
|
|
711
711
|
//# sourceMappingURL=limbo.es.map
|