Some checks failed
Deploy Application / deploy (push) Has been cancelled
2 lines
465 KiB
JavaScript
2 lines
465 KiB
JavaScript
var e=Object.defineProperty,t=(t,n,i)=>((t,n,i)=>n in t?e(t,n,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[n]=i)(t,"symbol"!=typeof n?n+"":n,i);const n=new Map;let i=!1,s=!1;performance.now();const o=document.createElement("div");o.style.position="fixed",o.style.bottom="0",o.style.left="0",o.style.font="12px monospace",o.style.color="#0f0",o.style.background="rgba(0,0,0,0.75)",o.style.padding="0.25rem 0.5rem",o.style.zIndex="9999",o.style.pointerEvents="none",o.style.display="none";const a=`<div style="width:${Math.min(0,100)}%;height:4px;background:#0f0;margin-top:4px;"></div>`;o.innerHTML+=a,o.style.lineHeight="1.4",document.body.appendChild(o);const r=new class{constructor({fps:e=!0}={}){this.fpsEnabled=e,this.fps=0,this.frameCount=0,this.lastTime=performance.now(),this.visible=!1,this.taskTimings=new Map,this.logs=[],this.container=document.createElement("div"),this.container.style.position="fixed",this.container.style.bottom="0",this.container.style.left="0",this.container.style.font="12px Consolas, monospace",this.container.style.color="#0f0",this.container.style.background="rgba(0,0,0,0.75)",this.container.style.padding="0.5rem",this.container.style.zIndex="9999",this.container.style.pointerEvents="none",this.container.style.lineHeight="1.4",this.container.style.whiteSpace="pre",this.container.style.display="none",document.body.appendChild(this.container),window.addEventListener("keydown",e=>{"§"===e.key&&(this.visible=!this.visible,this.container.style.display=this.visible?"block":"none")})}log(e){const t=(new Date).toLocaleTimeString();this.logs.push(`[${t}] ${e}`),this.logs.length>5&&this.logs.shift()}update(e=new Map){this.frameCount++;const t=performance.now();if(t-this.lastTime>=1e3){this.fps=this.frameCount,this.frameCount=0,this.lastTime=t;const n=[];for(const[e,t]of this.taskTimings.entries())n.push(`${e}: ${t.toFixed(2)}ms`);const i=Math.min(2*this.fps,100),s=this.logs.slice().reverse().join("\n");this.container.innerHTML=`\nFPS: ${this.fps} | Tasks: ${e.size}\n${n.join("\n")}\n<div style="width:${i}%;height:4px;background:#0f0;margin-top:4px;"></div>\n${s?"\nLogs:\n"+s:""}\n `}}trackTask(e,t){const n=performance.now();t();const i=performance.now()-n;this.taskTimings.set(e,i)}};function l(e,t,o={}){n.set(e,t),o.autoStart&&!i&&function(){if(i)return;function e(){for(const[e,i]of n)try{s?r.trackTask(e,i):i()}catch(t){d.warn("[Frameloop] Fehler in Task:",t)}s&&r.update(n),requestAnimationFrame(e)}i=!0,requestAnimationFrame(e)}()}function c(e){n.delete(e)}window.addEventListener("keydown",e=>{"§"===e.key&&(s=!s,o.style.display=s?"block":"none")});class d{static debug(...e){this._write("log","[DEBUG]",e,"debug")}static log(...e){this._write("log","[LOG]",e,"info")}static info(...e){this._write("info","[INFO]",e,"info")}static warn(...e){this._write("warn","[WARN]",e,"warn")}static error(...e){this._write("error","[ERROR]",e,"error")}static _write(e,t,n,i="info"){if(!this.enabled)return;const s=this.levels[this.level]||this.levels.info;if((this.levels[i]||this.levels.info)<s)return;const o=`${t} [${(new Date).toLocaleTimeString("de-DE")}] ${n.map(e=>{if(e instanceof Error)return`${e.name}: ${e.message}\n${e.stack||""}`;if("object"==typeof e&&null!==e)try{return JSON.stringify(e)}catch(t){return"[Circular Object]"}return e}).join(" ")}`;if("function"==typeof console[e]&&console[e](o),r&&"function"==typeof r.log)try{r.log(o)}catch(a){}}static setLevel(e){this.levels.hasOwnProperty(e)?(this.level=e,this.info(`[Logger] Log level set to: ${e}`)):this.warn(`[Logger] Invalid log level: ${e}. Valid levels:`,Object.keys(this.levels))}static setEnabled(e){this.enabled=!!e,e&&console.log("[Logger] Logging enabled")}}t(d,"enabled",!1),t(d,"level","error"),t(d,"levels",{debug:0,info:1,warn:2,error:3,none:99});class h{constructor(e={}){this.config=e,this.enabled=e.enabled??!0}async track(e,t={}){this.enabled}async pageView(e,t={}){this.enabled}async identify(e,t={}){this.enabled}}class u extends h{constructor(e={}){super(e),this.measurementId=e.measurementId||e.gaId}async track(e,t={}){"undefined"!=typeof gtag&>ag("event",e,t)}async pageView(e,t={}){"undefined"!=typeof gtag&>ag("config",this.measurementId,{page_path:e,...t})}}class p extends h{constructor(e={}){super(e),this.endpoint=e.endpoint||"/api/analytics"}async track(e,t={}){try{await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"},body:JSON.stringify({type:"event",name:e,properties:t,timestamp:Date.now()})})}catch(n){d.error("[Analytics] Failed to track event",n)}}async pageView(e,t={}){try{await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"},body:JSON.stringify({type:"page_view",path:e,properties:t,timestamp:Date.now()})})}catch(n){d.error("[Analytics] Failed to track page view",n)}}}class m{constructor(e={}){this.config={enabled:e.enabled??!0,providers:e.providers||[],gdprCompliant:e.gdprCompliant??!0,requireConsent:e.requireConsent??!1,consentGiven:e.consentGiven??!1,anonymizeIp:e.anonymizeIp??!0,...e},this.providers=[],this.eventQueue=[],this.userId=null,this.userTraits={},this.initProviders(),this.config.enabled&&this.hasConsent()&&this.trackPageView(),d.info("[Analytics] Initialized",{enabled:this.config.enabled,providers:this.providers.length,gdprCompliant:this.config.gdprCompliant})}static create(e={}){return new m(e)}initProviders(){for(const e of this.config.providers){let t;"string"==typeof e?"google-analytics"===e||"ga"===e?t=new u({}):"custom"===e&&(t=new p({})):"object"==typeof e&&("google-analytics"===e.type||"ga"===e.type?t=new u(e):"custom"===e.type?t=new p(e):e instanceof h&&(t=e)),t&&this.providers.push(t)}}hasConsent(){return!this.config.requireConsent||this.config.consentGiven}giveConsent(){this.config.consentGiven=!0,this.processEventQueue(),d.info("[Analytics] Consent given")}revokeConsent(){this.config.consentGiven=!1,d.info("[Analytics] Consent revoked")}async track(e,t={}){if(!this.config.enabled||!this.hasConsent())return void(this.config.requireConsent&&!this.config.consentGiven&&this.eventQueue.push({type:"event",name:e,properties:t}));const n={name:e,properties:this.anonymizeData(t),timestamp:Date.now(),userId:this.userId};for(const s of this.providers)try{await s.track(e,n.properties)}catch(i){d.error("[Analytics] Provider error",i)}d.debug("[Analytics] Event tracked",n),this.triggerAnalyticsEvent("track",n)}async trackPageView(e=null,t={}){if(!this.config.enabled||!this.hasConsent())return;const n=e||window.location.pathname,i={path:n,title:document.title,properties:this.anonymizeData(t),timestamp:Date.now()};for(const o of this.providers)try{await o.pageView(n,i.properties)}catch(s){d.error("[Analytics] Provider error",s)}d.debug("[Analytics] Page view tracked",i),this.triggerAnalyticsEvent("page_view",i)}async identify(e,t={}){if(this.config.enabled&&this.hasConsent()){this.userId=e,this.userTraits={...this.userTraits,...t};for(const t of this.providers)try{"function"==typeof t.identify&&await t.identify(e,this.userTraits)}catch(n){d.error("[Analytics] Provider error",n)}d.debug("[Analytics] User identified",{userId:e,traits:this.userTraits})}}async trackBehavior(e,t,n={}){await this.track("user_behavior",{action:e,target:t,...n})}anonymizeData(e){if(!this.config.gdprCompliant)return e;const t={...e};this.config.anonymizeIp&&t.ip&&(t.ip=t.ip.split(".").slice(0,3).join(".")+".0");return["email","phone","address","ssn","credit_card"].forEach(e=>{t[e]&&delete t[e]}),t}processEventQueue(){for(;this.eventQueue.length>0;){const e=this.eventQueue.shift();"event"===e.type&&this.track(e.name,e.properties)}}triggerAnalyticsEvent(e,t){const n=new CustomEvent(`analytics:${e}`,{detail:t,bubbles:!0});window.dispatchEvent(n)}enable(){this.config.enabled=!0,d.info("[Analytics] Enabled")}disable(){this.config.enabled=!1,d.info("[Analytics] Disabled")}destroy(){this.providers=[],this.eventQueue=[],this.userId=null,this.userTraits={},d.info("[Analytics] Destroyed")}}const g={name:"analytics",analytics:null,init(e={},t=null){return d.info("[AnalyticsModule] Module initialized"),this.analytics=m.create(e),"undefined"!=typeof window&&(window.Analytics=this.analytics),this},getAnalytics(){return this.analytics||m.create()},async track(e,t={}){const n=this.getAnalytics();return await n.track(e,t)},async trackPageView(e=null,t={}){const n=this.getAnalytics();return await n.trackPageView(e,t)},destroy(){this.analytics&&(this.analytics.destroy(),this.analytics=null),"undefined"!=typeof window&&window.Analytics&&delete window.Analytics,d.info("[AnalyticsModule] Module destroyed")}},f=g.init.bind(g),y=Object.freeze(Object.defineProperty({__proto__:null,Analytics:m,AnalyticsProvider:h,CustomProvider:p,GoogleAnalyticsProvider:u,default:g,init:f},Symbol.toStringTag,{value:"Module"}));class v{constructor(e,t={}){this.element=e,this.config={type:t.type||"fade-in",offset:t.offset||.85,delay:t.delay||0,once:!1!==t.once,speed:t.speed||.5,fadeStart:t.fadeStart||0,fadeEnd:t.fadeEnd||1,steps:t.steps||3,...t},this.triggered=!1,this.needsUpdate=!0,this.init()}init(){switch(this.config.type){case"fade-in":case"zoom-in":this.initFadeIn();break;case"parallax":this.initParallax();break;case"sticky-fade":this.initStickyFade();break;case"sticky-steps":this.initStickySteps()}}initFadeIn(){this.element.style.opacity="0",this.element.style.transition="opacity 0.6s ease, transform 0.6s ease",this.element.style.transitionDelay=`${this.config.delay}s`,"zoom-in"===this.config.type&&(this.element.style.transform="scale(0.9)")}initParallax(){this.needsUpdate=!0}initStickyFade(){this.element.style.position="sticky",this.element.style.top="0"}initStickySteps(){this.element.style.position="sticky",this.element.style.top="0"}enter(){if(!this.triggered||!this.config.once)switch(this.triggered=!0,this.config.type){case"fade-in":this.element.style.opacity="1",this.element.classList.add("visible","entered");break;case"zoom-in":this.element.style.opacity="1",this.element.style.transform="scale(1)",this.element.classList.add("visible","entered")}}exit(){if(!this.config.once)switch(this.triggered=!1,this.config.type){case"fade-in":this.element.style.opacity="0",this.element.classList.remove("visible","entered");break;case"zoom-in":this.element.style.opacity="0",this.element.style.transform="scale(0.9)",this.element.classList.remove("visible","entered")}}update(){const e=this.element.getBoundingClientRect(),t=window.innerHeight,n=window.scrollY;switch(this.config.type){case"parallax":this.updateParallax(e,n);break;case"sticky-fade":this.updateStickyFade(e,t);break;case"sticky-steps":this.updateStickySteps(e,t,n)}}updateParallax(e,t){const n=(t-(e.top+t))*this.config.speed;this.element.style.transform=`translateY(${n}px)`}updateStickyFade(e,t){const n=Math.max(0,Math.min(1,(t-e.top)/t)),i=this.config.fadeStart+(this.config.fadeEnd-this.config.fadeStart)*n;this.element.style.opacity=i.toString()}updateStickySteps(e,t,n){e.top;const i=Math.max(0,Math.min(1,n/(e.height+t))),s=Math.floor(i*this.config.steps);this.element.setAttribute("data-step",s.toString()),this.element.classList.remove("step-0","step-1","step-2","step-3","step-4","step-5"),this.element.classList.add(`step-${s}`)}destroy(){this.element.style.opacity="",this.element.style.transform="",this.element.style.transition="",this.element.style.transitionDelay="",this.element.style.position="",this.element.style.top="",this.element.classList.remove("visible","entered"),this.triggered=!1}}class b{constructor(e,t={}){this.element=e,this.config={steps:t.steps||null,triggerPoint:t.triggerPoint||.4,loop:t.loop??!1,...t},this.currentStep=0,this.triggered=!1,this.init()}init(){this.element.setAttribute("data-scroll-step","0"),this.element.classList.add("scroll-timeline")}enter(){this.triggered&&!this.config.loop||(this.triggered=!0,this.update())}exit(){this.config.loop&&(this.currentStep=0,this.update())}update(){const e=this.element.getBoundingClientRect(),t=window.innerHeight,n=t*this.config.triggerPoint;if(e.top<n&&e.bottom>0){const i=Math.max(0,Math.min(1,(n-e.top)/(e.height+t)));if(this.config.steps){const e=Math.floor(i*this.config.steps);this.setStep(e)}else this.setProgress(i)}}setStep(e){if(e!==this.currentStep){this.currentStep=e,this.element.setAttribute("data-scroll-step",e.toString());for(let e=0;e<=this.config.steps;e++)this.element.classList.remove(`step-${e}`);this.element.classList.add(`step-${e}`),this.triggerStepEvent(e)}}setProgress(e){this.element.setAttribute("data-scroll-progress",e.toString()),this.element.style.setProperty("--scroll-progress",e.toString()),this.triggerProgressEvent(e)}triggerStepEvent(e){const t=new CustomEvent("scroll-timeline:step",{detail:{step:e,element:this.element},bubbles:!0});this.element.dispatchEvent(t)}triggerProgressEvent(e){const t=new CustomEvent("scroll-timeline:progress",{detail:{progress:e,element:this.element},bubbles:!0});this.element.dispatchEvent(t)}destroy(){this.element.removeAttribute("data-scroll-step"),this.element.removeAttribute("data-scroll-progress"),this.element.style.removeProperty("--scroll-progress"),this.element.classList.remove("scroll-timeline");for(let e=0;e<=10;e++)this.element.classList.remove(`step-${e}`);this.currentStep=0,this.triggered=!1}}class w{constructor(e={}){this.config={enabled:e.enabled??!0,useIntersectionObserver:e.useIntersectionObserver??!0,throttleDelay:e.throttleDelay||16,...e},this.animations=new Map,this.observers=new Map,this.scrollHandler=null,this.isScrolling=!1,this.config.enabled&&this.init(),d.info("[AnimationSystem] Initialized",{enabled:this.config.enabled,useIntersectionObserver:this.config.useIntersectionObserver})}static create(e={}){return new w(e)}init(){this.config.useIntersectionObserver||this.setupScrollHandler(),this.autoInitialize()}setupScrollHandler(){let e=!1;this.scrollHandler=()=>{e||(window.requestAnimationFrame(()=>{this.updateAnimations(),e=!1}),e=!0)},window.addEventListener("scroll",this.scrollHandler,{passive:!0})}autoInitialize(){this.initializeFadeIn(),this.initializeParallax(),this.initializeTimeline(),this.initializeStickyFade(),this.initializeStickySteps()}initializeFadeIn(){document.querySelectorAll('.fade-in-on-scroll, .zoom-in, [data-animate="fade-in"]').forEach(e=>{this.registerAnimation(e,{type:"fade-in",offset:parseFloat(e.dataset.offset)||.85,delay:parseFloat(e.dataset.delay)||0,once:"false"!==e.dataset.once})})}initializeParallax(){document.querySelectorAll("[data-parallax], .parallax").forEach(e=>{const t=parseFloat(e.dataset.parallax||e.dataset.speed)||.5;this.registerAnimation(e,{type:"parallax",speed:t})})}initializeTimeline(){document.querySelectorAll("[data-scroll-timeline], [data-scroll-step]").forEach(e=>{this.registerAnimation(e,{type:"timeline",steps:e.dataset.scrollSteps?parseInt(e.dataset.scrollSteps):null,triggerPoint:parseFloat(e.dataset.triggerPoint)||.4})})}initializeStickyFade(){document.querySelectorAll("[data-sticky-fade], .sticky-fade").forEach(e=>{this.registerAnimation(e,{type:"sticky-fade",fadeStart:parseFloat(e.dataset.fadeStart)||0,fadeEnd:parseFloat(e.dataset.fadeEnd)||1})})}initializeStickySteps(){document.querySelectorAll("[data-sticky-steps], .sticky-steps").forEach(e=>{const t=e.dataset.stickySteps?parseInt(e.dataset.stickySteps):3;this.registerAnimation(e,{type:"sticky-steps",steps:t})})}registerAnimation(e,t){if(this.animations.has(e))return void d.warn("[AnimationSystem] Animation already registered for element",e);let n;switch(t.type){case"fade-in":case"zoom-in":n=new v(e,{type:t.type,offset:t.offset||.85,delay:t.delay||0,once:!1!==t.once});break;case"parallax":n=new v(e,{type:"parallax",speed:t.speed||.5});break;case"timeline":n=new b(e,{steps:t.steps,triggerPoint:t.triggerPoint||.4});break;case"sticky-fade":n=new v(e,{type:"sticky-fade",fadeStart:t.fadeStart||0,fadeEnd:t.fadeEnd||1});break;case"sticky-steps":n=new v(e,{type:"sticky-steps",steps:t.steps||3});break;default:return void d.warn("[AnimationSystem] Unknown animation type",t.type)}this.animations.set(e,n),this.config.useIntersectionObserver&&this.setupObserver(e,n),d.debug("[AnimationSystem] Animation registered",{element:e,type:t.type})}setupObserver(e,t){const n=new IntersectionObserver(e=>{e.forEach(e=>{e.isIntersecting?t.enter():t.config.once||t.exit()})},{threshold:t.config.offset||.85,rootMargin:"0px"});n.observe(e),this.observers.set(e,n)}updateAnimations(){this.animations.forEach((e,t)=>{e.needsUpdate&&e.update()})}removeAnimation(e){const t=this.animations.get(e);t&&(t.destroy(),this.animations.delete(e));const n=this.observers.get(e);n&&(n.disconnect(),this.observers.delete(e))}destroy(){this.animations.forEach((e,t)=>{this.removeAnimation(t)}),this.scrollHandler&&window.removeEventListener("scroll",this.scrollHandler),d.info("[AnimationSystem] Destroyed")}}const S=new class{constructor(){this.triggers=new Set,this.viewportHeight=window.innerHeight,this._loop=this._loop.bind(this),window.addEventListener("resize",()=>{this.viewportHeight=window.innerHeight}),requestAnimationFrame(this._loop)}register(e){this.triggers.add(e)}unregister(e){this.triggers.delete(e)}clear(){this.triggers.clear()}_loop(){this.triggers.forEach(e=>{e.update(this.viewportHeight)}),requestAnimationFrame(this._loop)}};class E{constructor(e){if(this.element=this.resolveElement(e.element),this.target=e.target?this.element.querySelector(e.target):this.element,e.target&&!this.target)throw new Error(`Target selector '${e.target}' not found inside element '${e.element}'.`);this.start=e.start||"top 80%",this.end=e.end||"bottom 20%",this.scrub=e.scrub||!1,this.onEnter=e.onEnter||null,this.onLeave=e.onLeave||null,this.onUpdate=e.onUpdate||null,this._wasVisible=!1,this._progress=0}resolveElement(e){if("string"==typeof e){const t=document.querySelectorAll(e);if(1===t.length)return t[0];throw new Error(`Selector '${e}' matched ${t.length} elements, expected exactly 1.`)}return e}getScrollProgress(e){const t=this.element.getBoundingClientRect(),n=this.parsePosition(this.start,e),i=this.parsePosition(this.end,e)-n,s=t.top-n;return 1-Math.min(Math.max(s/i,0),1)}parsePosition(e,t){const[n,i]=e.split(" ");return("top"===n?0:t)-t*(parseFloat(i)/100)}update(e){const t=this.element.getBoundingClientRect(),n=t.bottom>0&&t.top<e;if(n&&!this._wasVisible&&(this._wasVisible=!0,this.onEnter&&this.onEnter(this.target)),!n&&this._wasVisible&&(this._wasVisible=!1,this.onLeave&&this.onLeave(this.target)),this.scrub&&n){const t=this.getScrollProgress(e);this.onUpdate&&this.onUpdate(this.target,t)}}}function C(e){const t="string"==typeof e.element?document.querySelectorAll(e.element):[e.element],n=[];return t.forEach(t=>{const i=new E({...e,element:t});S.register(i),n.push(i)}),1===n.length?n[0]:n}const k=Object.freeze(Object.defineProperty({__proto__:null,createTrigger:C,init:function(e={}){const{selector:t=".fade-in-on-scroll, .zoom-in, .fade-out, .fade",offset:n=.85,baseDelay:i=.05,once:s=!0}=e,o=Array.from(document.querySelectorAll(t)).map(e=>({el:e,triggered:!1}));requestAnimationFrame(function e(){const t=window.innerHeight*n;o.forEach((e,n)=>{if(e.triggered&&s)return;e.el.getBoundingClientRect().top<t?(e.el.style.transitionDelay=n*i+"s",e.el.classList.add("visible","entered"),e.el.classList.remove("fade-out"),e.triggered=!0):s||(e.el.classList.remove("visible","entered"),e.triggered=!1)}),requestAnimationFrame(e)})}},Symbol.toStringTag,{value:"Module"})),M={name:"animation-system",animationSystem:null,init(e={},t=null){return d.info("[AnimationSystemModule] Module initialized"),this.animationSystem=w.create(e),"undefined"!=typeof window&&(window.AnimationSystem=this.animationSystem),this},getAnimationSystem(){return this.animationSystem||w.create()},registerAnimation(e,t){this.getAnimationSystem().registerAnimation(e,t)},destroy(){this.animationSystem&&(this.animationSystem.destroy(),this.animationSystem=null),"undefined"!=typeof window&&window.AnimationSystem&&delete window.AnimationSystem,d.info("[AnimationSystemModule] Module destroyed")}},x=M.init.bind(M),T=Object.freeze(Object.defineProperty({__proto__:null,AnimationSystem:w,ScrollAnimation:v,TimelineAnimation:b,createTrigger:C,default:M,init:x},Symbol.toStringTag,{value:"Module"}));class A{constructor(e={}){this.config=e,this.activeObservers=new Map,this.observerInstances=new Map,d.info("[ObserverManager] Initialized with support:",{intersection:"IntersectionObserver"in window,resize:"ResizeObserver"in window,mutation:"MutationObserver"in window,performance:"PerformanceObserver"in window})}intersection(e,t,n={}){if(!("IntersectionObserver"in window))return d.warn("[ObserverManager] IntersectionObserver not supported"),this.createFallbackObserver("intersection",e,t);const i={root:null,rootMargin:"50px",threshold:[0,.1,.5,1],...n},s=this.generateId("intersection"),o=new IntersectionObserver((e,n)=>{const i=e.map(e=>({element:e.target,isIntersecting:e.isIntersecting,intersectionRatio:e.intersectionRatio,boundingClientRect:e.boundingClientRect,rootBounds:e.rootBounds,intersectionRect:e.intersectionRect,time:e.time,visibility:this.calculateVisibility(e),direction:this.getScrollDirection(e),position:this.getElementPosition(e)}));t(i,n)},i),a=Array.isArray(e)?e:[e];return a.forEach(e=>{e instanceof Element&&o.observe(e)}),this.observerInstances.set(s,o),this.activeObservers.set(s,{type:"intersection",elements:a,callback:t,options:i}),d.info(`[ObserverManager] IntersectionObserver created: ${s}`),{id:s,observer:o,unobserve:e=>o.unobserve(e),disconnect:()=>this.disconnect(s),updateThreshold:e=>this.updateIntersectionThreshold(s,e)}}resize(e,t,n={}){if(!("ResizeObserver"in window))return d.warn("[ObserverManager] ResizeObserver not supported"),this.createFallbackObserver("resize",e,t);const i=this.generateId("resize"),s=new ResizeObserver(e=>{const n=e.map(e=>({element:e.target,contentRect:e.contentRect,borderBoxSize:e.borderBoxSize,contentBoxSize:e.contentBoxSize,devicePixelContentBoxSize:e.devicePixelContentBoxSize,dimensions:{width:e.contentRect.width,height:e.contentRect.height,aspectRatio:e.contentRect.width/e.contentRect.height},deltaSize:this.calculateDeltaSize(e),breakpoint:this.detectBreakpoint(e.contentRect.width)}));t(n)}),o=Array.isArray(e)?e:[e];return o.forEach(e=>{e instanceof Element&&s.observe(e)}),this.observerInstances.set(i,s),this.activeObservers.set(i,{type:"resize",elements:o,callback:t,options:n}),d.info(`[ObserverManager] ResizeObserver created: ${i}`),{id:i,observer:s,unobserve:e=>s.unobserve(e),disconnect:()=>this.disconnect(i)}}mutation(e,t,n={}){if(!("MutationObserver"in window))return d.warn("[ObserverManager] MutationObserver not supported"),null;const i={childList:!0,attributes:!0,subtree:!0,attributeOldValue:!0,characterDataOldValue:!0,...n},s=this.generateId("mutation"),o=new MutationObserver(e=>{const n=e.map(e=>({type:e.type,target:e.target,addedNodes:Array.from(e.addedNodes),removedNodes:Array.from(e.removedNodes),attributeName:e.attributeName,attributeNamespace:e.attributeNamespace,oldValue:e.oldValue,summary:this.summarizeMutation(e),impact:this.assessMutationImpact(e)}));t(n)});return o.observe(e,i),this.observerInstances.set(s,o),this.activeObservers.set(s,{type:"mutation",target:e,callback:t,options:i}),d.info(`[ObserverManager] MutationObserver created: ${s}`),{id:s,observer:o,disconnect:()=>this.disconnect(s),takeRecords:()=>o.takeRecords()}}performance(e,t={}){if(!("PerformanceObserver"in window))return d.warn("[ObserverManager] PerformanceObserver not supported"),null;const n={entryTypes:["measure","navigation","paint","largest-contentful-paint"],buffered:!0,...t},i=this.generateId("performance"),s=new PerformanceObserver(t=>{const n=t.getEntries().map(e=>({name:e.name,entryType:e.entryType,startTime:e.startTime,duration:e.duration,details:this.enhancePerformanceEntry(e),timestamp:Date.now()}));e(n)});return s.observe(n),this.observerInstances.set(i,s),this.activeObservers.set(i,{type:"performance",callback:e,options:n}),d.info(`[ObserverManager] PerformanceObserver created: ${i}`),{id:i,observer:s,disconnect:()=>this.disconnect(i),takeRecords:()=>s.takeRecords()}}lazyLoad(e="img[data-src], iframe[data-src]",t={}){const n=document.querySelectorAll(e);return this.intersection(n,e=>{e.forEach(e=>{if(e.isIntersecting){const t=e.element;t.dataset.src&&(t.src=t.dataset.src,delete t.dataset.src),t.dataset.srcset&&(t.srcset=t.dataset.srcset,delete t.dataset.srcset),t.classList.add("loaded"),e.observer.unobserve(t),d.info("[ObserverManager] Lazy loaded:",t.src)}})},{rootMargin:"100px",...t})}scrollTrigger(e,t,n={}){return this.intersection(e,e=>{e.forEach(e=>{const n={element:e.element,progress:e.intersectionRatio,isVisible:e.isIntersecting,direction:e.direction,position:e.position};t(n)})},{threshold:this.createThresholdArray(n.steps||10),...n})}viewport(e,t={}){const n=document.createElement("div");return n.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n pointer-events: none;\n visibility: hidden;\n ",document.body.appendChild(n),this.resize([n],t=>{const n=t[0];e({width:n.dimensions.width,height:n.dimensions.height,aspectRatio:n.dimensions.aspectRatio,orientation:n.dimensions.width>n.dimensions.height?"landscape":"portrait",breakpoint:n.breakpoint})},t)}generateId(e){return`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}disconnect(e){const t=this.observerInstances.get(e);t&&(t.disconnect(),this.observerInstances.delete(e),this.activeObservers.delete(e),d.info(`[ObserverManager] Observer disconnected: ${e}`))}disconnectAll(){this.observerInstances.forEach((e,t)=>{e.disconnect()}),this.observerInstances.clear(),this.activeObservers.clear(),d.info("[ObserverManager] All observers disconnected")}calculateVisibility(e){if(!e.isIntersecting)return 0;const t=e.intersectionRect.width*e.intersectionRect.height,n=e.boundingClientRect.width*e.boundingClientRect.height;return n>0?Math.round(t/n*100):0}getScrollDirection(e){return e.intersectionRatio>.5?"down":"up"}getElementPosition(e){const t=e.boundingClientRect,n=window.innerHeight;return t.top<0&&t.bottom>0?"entering-top":t.top<n&&t.bottom>n?"entering-bottom":t.top>=0&&t.bottom<=n?"visible":"hidden"}calculateDeltaSize(e){return{width:0,height:0}}detectBreakpoint(e){return e<576?"xs":e<768?"sm":e<992?"md":e<1200?"lg":"xl"}summarizeMutation(e){return`${e.type} on ${e.target.tagName}`}assessMutationImpact(e){return"childList"===e.type?e.addedNodes.length+e.removedNodes.length>5?"high":"low":"medium"}enhancePerformanceEntry(e){const t={raw:e};switch(e.entryType){case"navigation":t.loadTime=e.loadEventEnd-e.navigationStart,t.domContentLoaded=e.domContentLoadedEventEnd-e.navigationStart;break;case"paint":t.paintType=e.name;break;case"largest-contentful-paint":t.element=e.element,t.url=e.url}return t}createThresholdArray(e){const t=[];for(let n=0;n<=e;n++)t.push(n/e);return t}createFallbackObserver(e,t,n){d.warn(`[ObserverManager] Creating fallback for ${e}Observer`);const i=this.generateId(`fallback_${e}`);let s;if("intersection"===e)s=setInterval(()=>{const e=(Array.isArray(t)?t:[t]).map(e=>({element:e,isIntersecting:this.isElementInViewport(e),intersectionRatio:this.calculateIntersectionRatio(e)}));n(e)},100);return{id:i,disconnect:()=>{s&&clearInterval(s)}}}isElementInViewport(e){const t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=window.innerHeight&&t.right<=window.innerWidth}calculateIntersectionRatio(e){const t=e.getBoundingClientRect(),n=window.innerHeight,i=window.innerWidth,s=Math.min(t.bottom,n)-Math.max(t.top,0),o=Math.min(t.right,i)-Math.max(t.left,0);if(s<=0||o<=0)return 0;const a=s*o,r=t.height*t.width;return r>0?a/r:0}getActiveObservers(){return Array.from(this.activeObservers.entries()).map(([e,t])=>({id:e,...t}))}}class L{constructor(e={}){var t;this.config=e,this.activeStreams=new Map,this.activeConnections=new Map,this.audioContext=null,this.support={mediaDevices:void 0!==navigator.mediaDevices,webRTC:"RTCPeerConnection"in window,webAudio:"AudioContext"in window||"webkitAudioContext"in window,mediaRecorder:"MediaRecorder"in window,screenShare:void 0!==(null==(t=navigator.mediaDevices)?void 0:t.getDisplayMedia)},d.info("[MediaManager] Initialized with support:",this.support)}async getUserCamera(e={}){if(!this.support.mediaDevices)throw new Error("MediaDevices API not supported");const t={video:{width:{ideal:1280},height:{ideal:720},facingMode:"user"},audio:!1,...e};try{const e=await navigator.mediaDevices.getUserMedia(t),n=this.generateId("camera");return this.activeStreams.set(n,{stream:e,type:"camera",constraints:t,tracks:e.getTracks()}),d.info(`[MediaManager] Camera stream acquired: ${n}`),{id:n,stream:e,video:e.getVideoTracks()[0],audio:e.getAudioTracks()[0],stop:()=>this.stopStream(n),switchCamera:()=>this.switchCamera(n),takePhoto:t=>this.takePhoto(e,t),applyFilter:e=>this.applyVideoFilter(n,e)}}catch(n){throw d.warn("[MediaManager] Camera access failed:",n.message),n}}async getUserMicrophone(e={}){if(!this.support.mediaDevices)throw new Error("MediaDevices API not supported");const t={audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,...e.audio},video:!1,...e};try{const e=await navigator.mediaDevices.getUserMedia(t),n=this.generateId("microphone");return this.activeStreams.set(n,{stream:e,type:"microphone",constraints:t,tracks:e.getTracks()}),d.info(`[MediaManager] Microphone stream acquired: ${n}`),{id:n,stream:e,audio:e.getAudioTracks()[0],stop:()=>this.stopStream(n),getVolume:()=>this.getAudioLevel(e),startRecording:t=>this.startRecording(e,t)}}catch(n){throw d.warn("[MediaManager] Microphone access failed:",n.message),n}}async getScreenShare(e={}){if(!this.support.screenShare)throw new Error("Screen sharing not supported");const t={video:{cursor:"always"},audio:!1,...e};try{const e=await navigator.mediaDevices.getDisplayMedia(t),n=this.generateId("screen");return this.activeStreams.set(n,{stream:e,type:"screen",constraints:t,tracks:e.getTracks()}),e.getTracks().forEach(e=>{e.addEventListener("ended",()=>{this.stopStream(n)})}),d.info(`[MediaManager] Screen share acquired: ${n}`),{id:n,stream:e,video:e.getVideoTracks()[0],audio:e.getAudioTracks()[0],stop:()=>this.stopStream(n)}}catch(n){throw d.warn("[MediaManager] Screen share failed:",n.message),n}}async startRecording(e,t={}){if(!this.support.mediaRecorder)throw new Error("MediaRecorder API not supported");const n={mimeType:"video/webm;codecs=vp9",videoBitsPerSecond:2e6,audioBitsPerSecond:128e3,...t},i=this.getSupportedMimeType(["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"])||n.mimeType,s=new MediaRecorder(e,{...n,mimeType:i}),o=this.generateId("recording"),a=[];return s.ondataavailable=e=>{e.data.size>0&&a.push(e.data)},s.onstop=()=>{const e=new Blob(a,{type:i});this.onRecordingComplete(o,e)},s.start(),d.info(`[MediaManager] Recording started: ${o}`),{id:o,recorder:s,stop:()=>(s.stop(),new Promise(e=>{s.onstop=()=>{const t=new Blob(a,{type:i});e({blob:t,url:URL.createObjectURL(t),size:t.size,type:t.type,download:(e=`recording-${Date.now()}.webm`)=>{this.downloadBlob(t,e)}})}})),pause:()=>s.pause(),resume:()=>s.resume(),get state(){return s.state}}}takePhoto(e,t){const n=document.createElement("video");return n.srcObject=e,n.autoplay=!0,n.muted=!0,new Promise(e=>{n.onloadedmetadata=()=>{t||(t=document.createElement("canvas")),t.width=n.videoWidth,t.height=n.videoHeight;t.getContext("2d").drawImage(n,0,0),t.toBlob(n=>{e({canvas:t,blob:n,url:URL.createObjectURL(n),dataURL:t.toDataURL("image/jpeg",.9),download:(e=`photo-${Date.now()}.jpg`)=>{this.downloadBlob(n,e)}})},"image/jpeg",.9),n.remove()}})}getAudioContext(){if(!this.audioContext){if(!this.support.webAudio)return d.warn("[MediaManager] Web Audio API not supported"),null;this.audioContext=new(window.AudioContext||window.webkitAudioContext),d.info("[MediaManager] Audio context created")}return this.audioContext}createAudioAnalyzer(e,t={}){const n=this.getAudioContext();if(!n)return null;const i=n.createMediaStreamSource(e),s=n.createAnalyser();s.fftSize=t.fftSize||256,s.smoothingTimeConstant=t.smoothing||.8,i.connect(s);const o=s.frequencyBinCount,a=new Uint8Array(o);return{analyzer:s,bufferLength:o,dataArray:a,getFrequencyData:()=>(s.getByteFrequencyData(a),Array.from(a)),getTimeDomainData:()=>(s.getByteTimeDomainData(a),Array.from(a)),getAverageVolume:()=>(s.getByteFrequencyData(a),a.reduce((e,t)=>e+t,0)/o)}}async createPeerConnection(e={}){if(!this.support.webRTC)throw new Error("WebRTC not supported");const t={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],...e},n=new RTCPeerConnection(t),i=this.generateId("rtc");this.activeConnections.set(i,n);const s={id:i,connection:n,onTrack:e=>n.addEventListener("track",e),onIceCandidate:e=>n.addEventListener("icecandidate",e),onConnectionStateChange:e=>n.addEventListener("connectionstatechange",e),addStream:e=>{e.getTracks().forEach(t=>{n.addTrack(t,e)})},createOffer:()=>n.createOffer(),createAnswer:()=>n.createAnswer(),setLocalDescription:e=>n.setLocalDescription(e),setRemoteDescription:e=>n.setRemoteDescription(e),addIceCandidate:e=>n.addIceCandidate(e),close:()=>{n.close(),this.activeConnections.delete(i)},get connectionState(){return n.connectionState},get iceConnectionState(){return n.iceConnectionState}};return d.info(`[MediaManager] Peer connection created: ${i}`),s}async getDevices(){if(!this.support.mediaDevices)return{cameras:[],microphones:[],speakers:[]};try{const e=await navigator.mediaDevices.enumerateDevices();return{cameras:e.filter(e=>"videoinput"===e.kind),microphones:e.filter(e=>"audioinput"===e.kind),speakers:e.filter(e=>"audiooutput"===e.kind),all:e}}catch(e){return d.warn("[MediaManager] Device enumeration failed:",e),{cameras:[],microphones:[],speakers:[]}}}async checkPermissions(){const e={};try{if(navigator.permissions){const t=await navigator.permissions.query({name:"camera"}),n=await navigator.permissions.query({name:"microphone"});e.camera=t.state,e.microphone=n.state}}catch(t){d.warn("[MediaManager] Permission check failed:",t)}return e}stopStream(e){const t=this.activeStreams.get(e);t&&(t.tracks.forEach(e=>e.stop()),this.activeStreams.delete(e),d.info(`[MediaManager] Stream stopped: ${e}`))}stopAllStreams(){this.activeStreams.forEach((e,t)=>{e.tracks.forEach(e=>e.stop())}),this.activeStreams.clear(),d.info("[MediaManager] All streams stopped")}async switchCamera(e){const t=this.activeStreams.get(e);if(!t||"camera"!==t.type)return null;const n="user"===t.constraints.video.facingMode?"environment":"user";return this.stopStream(e),this.getUserCamera({video:{...t.constraints.video,facingMode:n}})}getAudioLevel(e){const t=this.getAudioContext();if(!t)return 0;const n=t.createMediaStreamSource(e),i=t.createAnalyser();n.connect(i);const s=new Uint8Array(i.frequencyBinCount);return i.getByteFrequencyData(s),s.reduce((e,t)=>e+t,0)/s.length}getSupportedMimeType(e){return e.find(e=>MediaRecorder.isTypeSupported(e))}downloadBlob(e,t){const n=URL.createObjectURL(e),i=document.createElement("a");i.href=n,i.download=t,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(n)}generateId(e="media"){return`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}onRecordingComplete(e,t){d.info(`[MediaManager] Recording completed: ${e}, size: ${t.size} bytes`)}applyVideoFilter(e,t){const n=this.activeStreams.get(e);if(!n||"camera"!==n.type)return;const i={none:"none",blur:"blur(2px)",brightness:"brightness(1.2)",contrast:"contrast(1.3)",grayscale:"grayscale(1)",sepia:"sepia(1)",invert:"invert(1)",vintage:"sepia(0.8) contrast(1.4) brightness(1.1)",cool:"hue-rotate(180deg) saturate(1.5)",warm:"hue-rotate(25deg) saturate(1.2)"};return{filter:i[t]||t,apply:e=>{e.style.filter=i[t]||t}}}getStatus(){var e;return{activeStreams:this.activeStreams.size,activeConnections:this.activeConnections.size,audioContextState:(null==(e=this.audioContext)?void 0:e.state)||"none",support:this.support,streams:Array.from(this.activeStreams.entries()).map(([e,t])=>({id:e,type:t.type,tracks:t.tracks.length,active:t.tracks.some(e=>"live"===e.readyState)}))}}}class I{constructor(e={}){t(this,"db",{set:async(e,t,n=null)=>new Promise((i,s)=>{if(!this.db)return void s(new Error("IndexedDB not available"));const o=this.db.transaction(["keyValue"],"readwrite").objectStore("keyValue"),a={key:e,value:t,timestamp:Date.now(),expiration:n?Date.now()+n:null},r=o.put(a);r.onsuccess=()=>{d.info(`[StorageManager] DB set: ${e}`),i(a)},r.onerror=()=>{d.error(`[StorageManager] DB set failed: ${e}`),s(r.error)}}),get:async e=>new Promise((t,n)=>{if(!this.db)return void n(new Error("IndexedDB not available"));const i=this.db.transaction(["keyValue"],"readonly").objectStore("keyValue").get(e);i.onsuccess=()=>{const n=i.result;if(n)return n.expiration&&Date.now()>n.expiration?(this.db.delete(e),void t(null)):void t(n.value);t(null)},i.onerror=()=>{d.error(`[StorageManager] DB get failed: ${e}`),n(i.error)}}),delete:async e=>new Promise((t,n)=>{if(!this.db)return void n(new Error("IndexedDB not available"));const i=this.db.transaction(["keyValue"],"readwrite").objectStore("keyValue").delete(e);i.onsuccess=()=>{d.info(`[StorageManager] DB deleted: ${e}`),t(!0)},i.onerror=()=>{n(i.error)}}),keys:async()=>new Promise((e,t)=>{if(!this.db)return void t(new Error("IndexedDB not available"));const n=this.db.transaction(["keyValue"],"readonly").objectStore("keyValue").getAllKeys();n.onsuccess=()=>{e(n.result)},n.onerror=()=>{t(n.error)}}),clear:async()=>new Promise((e,t)=>{if(!this.db)return void t(new Error("IndexedDB not available"));const n=this.db.transaction(["keyValue"],"readwrite").objectStore("keyValue").clear();n.onsuccess=()=>{d.info("[StorageManager] DB cleared"),e(!0)},n.onerror=()=>{t(n.error)}}),storeFile:async(e,t,n={})=>new Promise((i,s)=>{if(!this.db)return void s(new Error("IndexedDB not available"));const o=this.db.transaction(["files"],"readwrite").objectStore("files"),a={name:e,file:t,type:t.type,size:t.size,timestamp:Date.now(),metadata:n},r=o.add(a);r.onsuccess=()=>{d.info(`[StorageManager] File stored: ${e}`),i({id:r.result,...a})},r.onerror=()=>{s(r.error)}}),getFile:async e=>new Promise((t,n)=>{if(!this.db)return void n(new Error("IndexedDB not available"));const i=this.db.transaction(["files"],"readonly").objectStore("files").get(e);i.onsuccess=()=>{t(i.result)},i.onerror=()=>{n(i.error)}})}),t(this,"cache",{add:async(e,t=null)=>{if(!this.cache)throw new Error("Cache API not available");try{t?await this.cache.put(e,t):await this.cache.add(e),d.info(`[StorageManager] Cache add: ${e}`)}catch(n){throw d.error("[StorageManager] Cache add failed:",n),n}},get:async e=>{if(!this.cache)throw new Error("Cache API not available");try{const t=await this.cache.match(e);return t?d.info(`[StorageManager] Cache hit: ${e}`):d.info(`[StorageManager] Cache miss: ${e}`),t}catch(t){throw d.error("[StorageManager] Cache get failed:",t),t}},delete:async e=>{if(!this.cache)throw new Error("Cache API not available");try{const t=await this.cache.delete(e);return t&&d.info(`[StorageManager] Cache deleted: ${e}`),t}catch(t){throw d.error("[StorageManager] Cache delete failed:",t),t}},keys:async()=>{if(!this.cache)throw new Error("Cache API not available");try{return await this.cache.keys()}catch(e){throw d.error("[StorageManager] Cache keys failed:",e),e}},clear:async()=>{if(!this.cache)throw new Error("Cache API not available");try{const e=await this.cache.keys();await Promise.all(e.map(e=>this.cache.delete(e))),d.info("[StorageManager] Cache cleared")}catch(e){throw d.error("[StorageManager] Cache clear failed:",e),e}}}),t(this,"channel",{create:(e,t=null)=>{if(!this.support.broadcastChannel)return d.warn("[StorageManager] BroadcastChannel not supported"),null;if(this.channels.has(e))return this.channels.get(e);const n=new BroadcastChannel(e);t&&n.addEventListener("message",t);const i={name:e,channel:n,send:t=>{n.postMessage({data:t,timestamp:Date.now(),sender:"current-tab"}),d.info(`[StorageManager] Broadcast sent to ${e}`)},onMessage:e=>{n.addEventListener("message",t=>{e(t.data)})},close:()=>{n.close(),this.channels.delete(e),d.info(`[StorageManager] Channel closed: ${e}`)}};return this.channels.set(e,i),d.info(`[StorageManager] Channel created: ${e}`),i},get:e=>this.channels.get(e)||null,close:e=>{const t=this.channels.get(e);t&&t.close()},closeAll:()=>{this.channels.forEach(e=>e.close()),this.channels.clear(),d.info("[StorageManager] All channels closed")}}),t(this,"locks",{acquire:async(e,t,n={})=>{if(!this.support.webLocks)return d.warn("[StorageManager] Web Locks not supported, executing without lock"),await t();try{return await navigator.locks.request(e,n,async n=>{d.info(`[StorageManager] Lock acquired: ${e}`);const i=await t(n);return d.info(`[StorageManager] Lock released: ${e}`),i})}catch(i){throw d.error(`[StorageManager] Lock failed: ${e}`,i),i}},query:async()=>{if(!this.support.webLocks)return{held:[],pending:[]};try{return await navigator.locks.query()}catch(e){throw d.error("[StorageManager] Lock query failed:",e),e}}}),t(this,"local",{set:(e,t,n=null)=>{if(!this.support.localStorage)return!1;try{const i={value:t,timestamp:Date.now(),expiration:n?Date.now()+n:null};return localStorage.setItem(e,JSON.stringify(i)),!0}catch(i){return d.error("[StorageManager] localStorage set failed:",i),!1}},get:e=>{if(!this.support.localStorage)return null;try{const t=localStorage.getItem(e);if(!t)return null;const n=JSON.parse(t);return n.expiration&&Date.now()>n.expiration?(localStorage.removeItem(e),null):n.value}catch(t){return d.error("[StorageManager] localStorage get failed:",t),null}},delete:e=>!!this.support.localStorage&&(localStorage.removeItem(e),!0),clear:()=>!!this.support.localStorage&&(localStorage.clear(),!0),keys:()=>this.support.localStorage?Object.keys(localStorage):[]}),t(this,"session",{set:(e,t)=>{if(!this.support.sessionStorage)return!1;try{return sessionStorage.setItem(e,JSON.stringify(t)),!0}catch(n){return d.error("[StorageManager] sessionStorage set failed:",n),!1}},get:e=>{if(!this.support.sessionStorage)return null;try{const t=sessionStorage.getItem(e);return t?JSON.parse(t):null}catch(t){return d.error("[StorageManager] sessionStorage get failed:",t),null}},delete:e=>!!this.support.sessionStorage&&(sessionStorage.removeItem(e),!0),clear:()=>!!this.support.sessionStorage&&(sessionStorage.clear(),!0)}),t(this,"smartCache",{set:async(e,t,n={})=>{const{storage:i="indexedDB",expiration:s=null,fallback:o=!0}=n;try{if("indexedDB"===i&&this.db)return await this.db.set(e,t,s);if(o)return this.local.set(e,t,s)}catch(a){if(o)return this.local.set(e,t,s);throw a}},get:async(e,t={})=>{const{storage:n="indexedDB",fallback:i=!0}=t;try{if("indexedDB"===n&&this.db)return await this.db.get(e);if(i)return this.local.get(e)}catch(s){if(i)return this.local.get(e);throw s}},delete:async(e,t={})=>{const{storage:n="indexedDB",fallback:i=!0}=t;try{"indexedDB"===n&&this.db&&await this.db.delete(e),i&&this.local.delete(e)}catch(s){throw i&&this.local.delete(e),s}}}),t(this,"storage",{set:async(e,t,n={})=>{const{type:i="auto",expiration:s=null,...o}=n;try{let n=i;if("auto"===i){n=JSON.stringify(t).length>5242880?"indexedDB":"localStorage"}switch(n){case"localStorage":return this.local.set(e,t,s);case"sessionStorage":return this.session.set(e,t);case"indexedDB":return await this.db.set(e,t,s);default:throw new Error(`Unknown storage type: ${n}`)}}catch(a){if("indexedDB"===i||"auto"===i)return d.warn("[StorageManager] Falling back to localStorage",a),this.local.set(e,t,s);throw a}finally{this.config.enableAnalytics&&this.analytics.operations.set++}},get:async(e,t={})=>{const{type:n="auto",...i}=t;try{if("auto"===n){const t=this.local.get(e);if(null!==t)return this.config.enableAnalytics&&this.analytics.operations.get++,t;const n=this.session.get(e);if(null!==n)return this.config.enableAnalytics&&this.analytics.operations.get++,n;if(this.db){const t=await this.db.get(e);if(null!==t)return this.config.enableAnalytics&&this.analytics.operations.get++,t}return null}switch(n){case"localStorage":const t=this.local.get(e);return this.config.enableAnalytics&&this.analytics.operations.get++,t;case"sessionStorage":const i=this.session.get(e);return this.config.enableAnalytics&&this.analytics.operations.get++,i;case"indexedDB":const s=await this.db.get(e);return this.config.enableAnalytics&&this.analytics.operations.get++,s;default:throw new Error(`Unknown storage type: ${n}`)}}catch(s){throw d.error("[StorageManager] Storage get failed",s),this.config.enableAnalytics&&this.analytics.errors++,s}},delete:async(e,t={})=>{const{type:n="all",...i}=t;try{if("all"===n)this.local.delete(e),this.session.delete(e),this.db&&await this.db.delete(e);else switch(n){case"localStorage":this.local.delete(e);break;case"sessionStorage":this.session.delete(e);break;case"indexedDB":this.db&&await this.db.delete(e)}this.config.enableAnalytics&&this.analytics.operations.delete++}catch(s){throw d.error("[StorageManager] Storage delete failed",s),this.config.enableAnalytics&&this.analytics.errors++,s}},clear:async(e={})=>{const{type:t="all",...n}=e;try{if("all"===t)this.local.clear(),this.session.clear(),this.db&&await this.db.clear(),this.cache&&await this.cache.clear();else switch(t){case"localStorage":this.local.clear();break;case"sessionStorage":this.session.clear();break;case"indexedDB":this.db&&await this.db.clear();break;case"cache":this.cache&&await this.cache.clear()}this.config.enableAnalytics&&this.analytics.operations.clear++}catch(i){throw d.error("[StorageManager] Storage clear failed",i),this.config.enableAnalytics&&this.analytics.errors++,i}}}),this.config={dbName:e.dbName||"AppDatabase",dbVersion:e.dbVersion||1,enableAnalytics:e.enableAnalytics??!0,enableQuotaMonitoring:e.enableQuotaMonitoring??!0,quotaWarningThreshold:e.quotaWarningThreshold||.8,...e},this.db=null,this.cache=null,this.channels=new Map,this.analytics={operations:{get:0,set:0,delete:0,clear:0},errors:0,quotaWarnings:0},this.support={indexedDB:"indexedDB"in window,cacheAPI:"caches"in window,webLocks:"locks"in navigator,broadcastChannel:"BroadcastChannel"in window,localStorage:"localStorage"in window,sessionStorage:"sessionStorage"in window,storageEstimate:"storage"in navigator&&"estimate"in navigator.storage},d.info("[StorageManager] Initialized with support:",this.support),this.initializeDB(),this.initializeCache(),this.config.enableQuotaMonitoring&&this.startQuotaMonitoring()}async initializeDB(){if(this.support.indexedDB)try{const e=indexedDB.open(this.dbName,this.dbVersion);e.onerror=()=>{d.error("[StorageManager] IndexedDB failed to open")},e.onupgradeneeded=e=>{const t=e.target.result;if(!t.objectStoreNames.contains("keyValue")){t.createObjectStore("keyValue",{keyPath:"key"}).createIndex("timestamp","timestamp",{unique:!1})}if(t.objectStoreNames.contains("cache")||t.createObjectStore("cache",{keyPath:"key"}),!t.objectStoreNames.contains("files")){const e=t.createObjectStore("files",{keyPath:"id",autoIncrement:!0});e.createIndex("name","name",{unique:!1}),e.createIndex("type","type",{unique:!1})}d.info("[StorageManager] IndexedDB schema updated")},e.onsuccess=e=>{this.db=e.target.result,d.info("[StorageManager] IndexedDB connected")}}catch(e){d.error("[StorageManager] IndexedDB initialization failed:",e)}else d.warn("[StorageManager] IndexedDB not supported")}async initializeCache(){if(this.support.cacheAPI)try{this.cache=await caches.open(this.config.cacheName||"app-cache-v1"),d.info("[StorageManager] Cache API initialized")}catch(e){d.error("[StorageManager] Cache API initialization failed:",e)}else d.warn("[StorageManager] Cache API not supported")}async getStorageUsage(){const e={quota:0,usage:0,available:0,percentage:0};if("storage"in navigator&&"estimate"in navigator.storage)try{const t=await navigator.storage.estimate();e.quota=t.quota||0,e.usage=t.usage||0,e.available=e.quota-e.usage,e.percentage=e.quota>0?Math.round(e.usage/e.quota*100):0}catch(t){d.error("[StorageManager] Storage estimate failed:",t)}return e}async cleanup(){d.info("[StorageManager] Starting cleanup...");try{if(this.db){const e=this.db.transaction(["keyValue"],"readwrite").objectStore("keyValue"),t=e.index("timestamp").openCursor();let n=0;t.onsuccess=e=>{const t=e.target.result;if(t){const e=t.value;e.expiration&&Date.now()>e.expiration&&(t.delete(),n++),t.continue()}else d.info(`[StorageManager] Cleanup completed: ${n} expired entries removed`)}}if(this.support.localStorage){const e=Object.keys(localStorage);let t=0;e.forEach(e=>{try{const n=localStorage.getItem(e),i=JSON.parse(n);i.expiration&&Date.now()>i.expiration&&(localStorage.removeItem(e),t++)}catch(n){}}),t>0&&d.info(`[StorageManager] LocalStorage cleanup: ${t} expired entries removed`)}}catch(e){d.error("[StorageManager] Cleanup failed:",e)}}async getStatus(){const e=await this.getStorageUsage();return{support:this.support,usage:e,activeChannels:this.channels.size,dbConnected:!!this.db,cacheConnected:!!this.cache,channelNames:Array.from(this.channels.keys()),analytics:this.config.enableAnalytics?this.getAnalytics():null}}startQuotaMonitoring(){setInterval(async()=>{try{const e=await this.getStorageUsage();if(e.percentage>=100*this.config.quotaWarningThreshold){this.analytics.quotaWarnings++,d.warn("[StorageManager] Storage quota warning",{usage:e.percentage+"%",available:this.formatBytes(e.available)});const t=new CustomEvent("storage:quota-warning",{detail:e,bubbles:!0});window.dispatchEvent(t)}}catch(e){d.error("[StorageManager] Quota monitoring error",e)}},6e4)}async migrate(e,t,n=null){d.info("[StorageManager] Starting migration",{fromType:e,toType:t});let i=n;if(!i)switch(e){case"localStorage":i=this.local.keys();break;case"sessionStorage":i=Object.keys(sessionStorage);break;case"indexedDB":this.db&&(i=await this.db.keys())}if(!i||0===i.length)return void d.info("[StorageManager] No keys to migrate");let s=0,o=0;for(const r of i)try{let n=null;switch(e){case"localStorage":n=this.local.get(r);break;case"sessionStorage":n=this.session.get(r);break;case"indexedDB":this.db&&(n=await this.db.get(r))}if(null===n)continue;switch(t){case"localStorage":this.local.set(r,n);break;case"sessionStorage":this.session.set(r,n);break;case"indexedDB":this.db&&await this.db.set(r,n)}s++}catch(a){d.error(`[StorageManager] Failed to migrate key: ${r}`,a),o++}return d.info("[StorageManager] Migration completed",{migrated:s,failed:o}),{migrated:s,failed:o}}getAnalytics(){return{...this.analytics,totalOperations:Object.values(this.analytics.operations).reduce((e,t)=>e+t,0),errorRate:this.analytics.errors/(this.analytics.operations.get+this.analytics.operations.set||1)}}resetAnalytics(){this.analytics={operations:{get:0,set:0,delete:0,clear:0},errors:0,quotaWarnings:0}}formatBytes(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","TB"][t]}}class P{constructor(e={}){t(this,"geolocation",{getCurrent:(e={})=>new Promise((t,n)=>{if(!this.support.geolocation)return void n(new Error("Geolocation not supported"));const i={enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4,...e};navigator.geolocation.getCurrentPosition(e=>{const n=this.enhanceLocationData(e);d.info("[DeviceManager] Location acquired:",{lat:n.latitude,lng:n.longitude,accuracy:n.accuracy}),t(n)},e=>{d.error("[DeviceManager] Geolocation failed:",e.message),n(e)},i)}),watch:(e,t={})=>{if(!this.support.geolocation)throw new Error("Geolocation not supported");const n={enableHighAccuracy:!0,timeout:3e4,maximumAge:1e4,...t},i=navigator.geolocation.watchPosition(t=>{const n=this.enhanceLocationData(t);e(n)},t=>{d.error("[DeviceManager] Location watch failed:",t.message),e({error:t})},n);return this.activeWatchers.set(`geo_${i}`,{type:"geolocation",id:i,stop:()=>{navigator.geolocation.clearWatch(i),this.activeWatchers.delete(`geo_${i}`)}}),d.info("[DeviceManager] Location watch started:",i),{id:i,stop:()=>{navigator.geolocation.clearWatch(i),this.activeWatchers.delete(`geo_${i}`),d.info("[DeviceManager] Location watch stopped:",i)}}},distance:(e,t)=>{const n=this.toRadians(t.latitude-e.latitude),i=this.toRadians(t.longitude-e.longitude),s=Math.sin(n/2)*Math.sin(n/2)+Math.cos(this.toRadians(e.latitude))*Math.cos(this.toRadians(t.latitude))*Math.sin(i/2)*Math.sin(i/2),o=6371*(2*Math.atan2(Math.sqrt(s),Math.sqrt(1-s)));return{kilometers:o,miles:.621371*o,meters:1e3*o}}}),t(this,"motion",{start:(e,t={})=>{if(!this.support.deviceMotion)throw new Error("Device Motion not supported");const n=t=>{const n={acceleration:t.acceleration,accelerationIncludingGravity:t.accelerationIncludingGravity,rotationRate:t.rotationRate,interval:t.interval,timestamp:t.timeStamp,totalAcceleration:this.calculateTotalAcceleration(t.acceleration),shake:this.detectShake(t.accelerationIncludingGravity),orientation:this.getDeviceOrientation(t)};e(n)};"function"==typeof DeviceMotionEvent.requestPermission?DeviceMotionEvent.requestPermission().then(e=>{"granted"===e&&window.addEventListener("devicemotion",n)}):window.addEventListener("devicemotion",n);const i=this.generateId("motion");return this.activeWatchers.set(i,{type:"motion",handler:n,stop:()=>{window.removeEventListener("devicemotion",n),this.activeWatchers.delete(i)}}),d.info("[DeviceManager] Motion detection started"),{id:i,stop:()=>{window.removeEventListener("devicemotion",n),this.activeWatchers.delete(i),d.info("[DeviceManager] Motion detection stopped")}}},startOrientation:(e,t={})=>{if(!this.support.deviceOrientation)throw new Error("Device Orientation not supported");const n=t=>{const n={alpha:t.alpha,beta:t.beta,gamma:t.gamma,absolute:t.absolute,timestamp:t.timeStamp,compass:this.calculateCompass(t.alpha),tilt:this.calculateTilt(t.beta,t.gamma),rotation:this.getRotationState(t)};e(n)};"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then(e=>{"granted"===e&&window.addEventListener("deviceorientation",n)}):window.addEventListener("deviceorientation",n);const i=this.generateId("orientation");return this.activeWatchers.set(i,{type:"orientation",handler:n,stop:()=>{window.removeEventListener("deviceorientation",n),this.activeWatchers.delete(i)}}),d.info("[DeviceManager] Orientation detection started"),{id:i,stop:()=>{window.removeEventListener("deviceorientation",n),this.activeWatchers.delete(i),d.info("[DeviceManager] Orientation detection stopped")}}}}),t(this,"vibration",{vibrate:e=>{if(!this.support.vibration)return d.warn("[DeviceManager] Vibration not supported"),!1;try{return navigator.vibrate(e),d.info("[DeviceManager] Vibration triggered:",e),!0}catch(t){return d.error("[DeviceManager] Vibration failed:",t),!1}},patterns:{short:200,long:600,double:[200,100,200],triple:[200,100,200,100,200],sos:[100,30,100,30,100,200,200,30,200,30,200,200,100,30,100,30,100],heartbeat:[100,30,100,130,40,30,40,30,100],notification:[200,100,200],success:[100],error:[300,100,300],warning:[200,100,200,100,200]},stop:()=>{this.support.vibration&&(navigator.vibrate(0),d.info("[DeviceManager] Vibration stopped"))},success:()=>this.vibration.vibrate(this.vibration.patterns.success),error:()=>this.vibration.vibrate(this.vibration.patterns.error),warning:()=>this.vibration.vibrate(this.vibration.patterns.warning),notification:()=>this.vibration.vibrate(this.vibration.patterns.notification)}),t(this,"battery",{get:async()=>{if(!this.support.battery)return d.warn("[DeviceManager] Battery API not supported"),null;try{const e=await navigator.getBattery(),t={level:Math.round(100*e.level),charging:e.charging,chargingTime:e.chargingTime,dischargingTime:e.dischargingTime,status:this.getBatteryStatus(e),timeRemaining:this.formatBatteryTime(e)};return d.info("[DeviceManager] Battery status:",t),t}catch(e){return d.error("[DeviceManager] Battery status failed:",e),null}},watch:async e=>{if(!this.support.battery)throw new Error("Battery API not supported");try{const t=await navigator.getBattery(),n=[];["chargingchange","levelchange","chargingtimechange","dischargingtimechange"].forEach(i=>{const s=()=>{const n={level:Math.round(100*t.level),charging:t.charging,chargingTime:t.chargingTime,dischargingTime:t.dischargingTime,status:this.getBatteryStatus(t),timeRemaining:this.formatBatteryTime(t),event:i};e(n)};t.addEventListener(i,s),n.push({event:i,handler:s})});const i=this.generateId("battery");return this.activeWatchers.set(i,{type:"battery",battery:t,handlers:n,stop:()=>{n.forEach(({event:e,handler:n})=>{t.removeEventListener(e,n)}),this.activeWatchers.delete(i)}}),d.info("[DeviceManager] Battery watch started"),{id:i,stop:()=>{n.forEach(({event:e,handler:n})=>{t.removeEventListener(e,n)}),this.activeWatchers.delete(i),d.info("[DeviceManager] Battery watch stopped")}}}catch(t){throw d.error("[DeviceManager] Battery watch failed:",t),t}}}),t(this,"network",{get:()=>{if(!this.support.networkInfo)return d.warn("[DeviceManager] Network Information not supported"),null;const e=navigator.connection||navigator.mozConnection||navigator.webkitConnection;return{effectiveType:e.effectiveType,downlink:e.downlink,rtt:e.rtt,saveData:e.saveData,speed:this.getConnectionSpeed(e),quality:this.getConnectionQuality(e),recommendation:this.getNetworkRecommendation(e)}},watch:e=>{if(!this.support.networkInfo)throw new Error("Network Information not supported");const t=navigator.connection||navigator.mozConnection||navigator.webkitConnection,n=()=>{const n={effectiveType:t.effectiveType,downlink:t.downlink,rtt:t.rtt,saveData:t.saveData,speed:this.getConnectionSpeed(t),quality:this.getConnectionQuality(t),recommendation:this.getNetworkRecommendation(t)};e(n)};t.addEventListener("change",n);const i=this.generateId("network");return this.activeWatchers.set(i,{type:"network",connection:t,handler:n,stop:()=>{t.removeEventListener("change",n),this.activeWatchers.delete(i)}}),d.info("[DeviceManager] Network watch started"),{id:i,stop:()=>{t.removeEventListener("change",n),this.activeWatchers.delete(i),d.info("[DeviceManager] Network watch stopped")}}}}),t(this,"wakeLock",{request:async(e="screen")=>{if(!this.support.wakeLock)return d.warn("[DeviceManager] Wake Lock not supported"),null;try{const t=await navigator.wakeLock.request(e);return d.info(`[DeviceManager] Wake lock acquired: ${e}`),{type:t.type,release:()=>{t.release(),d.info(`[DeviceManager] Wake lock released: ${e}`)}}}catch(t){throw d.error("[DeviceManager] Wake lock failed:",t),t}}}),this.config=e,this.activeWatchers=new Map,this.sensorData=new Map,this.support={geolocation:"geolocation"in navigator,deviceMotion:"DeviceMotionEvent"in window,deviceOrientation:"DeviceOrientationEvent"in window,vibration:"vibrate"in navigator,battery:"getBattery"in navigator,networkInfo:"connection"in navigator||"mozConnection"in navigator||"webkitConnection"in navigator,wakeLock:"wakeLock"in navigator,bluetooth:"bluetooth"in navigator,usb:"usb"in navigator,serial:"serial"in navigator},d.info("[DeviceManager] Initialized with support:",this.support),this.initializeSensors()}initializeSensors(){(this.support.deviceMotion||this.support.deviceOrientation)&&(this.sensorData.set("motionBaseline",{x:0,y:0,z:0}),this.sensorData.set("shakeThreshold",this.config.shakeThreshold||15))}enhanceLocationData(e){return{latitude:e.coords.latitude,longitude:e.coords.longitude,accuracy:e.coords.accuracy,altitude:e.coords.altitude,altitudeAccuracy:e.coords.altitudeAccuracy,heading:e.coords.heading,speed:e.coords.speed,timestamp:e.timestamp,coordinates:`${e.coords.latitude},${e.coords.longitude}`,accuracyLevel:this.getAccuracyLevel(e.coords.accuracy),mapUrl:`https://maps.google.com/?q=${e.coords.latitude},${e.coords.longitude}`}}getAccuracyLevel(e){return e<=5?"excellent":e<=10?"good":e<=50?"fair":"poor"}calculateTotalAcceleration(e){if(!e)return 0;const t=e.x||0,n=e.y||0,i=e.z||0;return Math.sqrt(t*t+n*n+i*i)}detectShake(e){if(!e)return!1;const t=this.sensorData.get("shakeThreshold"),n=Math.abs(e.x||0),i=Math.abs(e.y||0),s=Math.abs(e.z||0);return n>t||i>t||s>t}getDeviceOrientation(e){const t=e.accelerationIncludingGravity;if(!t)return"unknown";const n=t.x||0,i=t.y||0,s=t.z||0;return Math.abs(n)>Math.abs(i)&&Math.abs(n)>Math.abs(s)?n>0?"landscape-right":"landscape-left":Math.abs(i)>Math.abs(s)?i>0?"portrait-upside-down":"portrait":s>0?"face-down":"face-up"}calculateCompass(e){if(null===e)return null;const t=Math.round(e/45)%8;return{degrees:Math.round(e),direction:["N","NE","E","SE","S","SW","W","NW"][t],cardinal:this.getCardinalDirection(e)}}getCardinalDirection(e){return e>=337.5||e<22.5?"North":e>=22.5&&e<67.5?"Northeast":e>=67.5&&e<112.5?"East":e>=112.5&&e<157.5?"Southeast":e>=157.5&&e<202.5?"South":e>=202.5&&e<247.5?"Southwest":e>=247.5&&e<292.5?"West":e>=292.5&&e<337.5?"Northwest":"Unknown"}calculateTilt(e,t){return{x:Math.round(e||0),y:Math.round(t||0),magnitude:Math.round(Math.sqrt((e||0)**2+(t||0)**2))}}getRotationState(e){const{alpha:t,beta:n,gamma:i}=e,s=Math.abs(n)>10||Math.abs(i)>10;return{isRotating:s,intensity:s?Math.max(Math.abs(n),Math.abs(i)):0}}getBatteryStatus(e){const t=100*e.level;return e.charging?"charging":t<=10?"critical":t<=20?"low":t<=50?"medium":"high"}formatBatteryTime(e){const t=e.charging?e.chargingTime:e.dischargingTime;if(t===1/0||isNaN(t))return"Unknown";return`${Math.floor(t/3600)}h ${Math.floor(t%3600/60)}m`}getConnectionSpeed(e){const t=e.downlink;return t>=10?"fast":t>=1.5?"good":t>=.5?"slow":"very-slow"}getConnectionQuality(e){switch(e.effectiveType){case"4g":return"excellent";case"3g":return"good";case"2g":return"poor";case"slow-2g":return"very-poor";default:return"unknown"}}getNetworkRecommendation(e){switch(this.getConnectionQuality(e)){case"excellent":return"Full quality content recommended";case"good":return"Moderate quality content recommended";case"poor":return"Light content only, avoid large files";case"very-poor":return"Text-only content recommended";default:return"Monitor connection quality"}}toRadians(e){return e*(Math.PI/180)}generateId(e="device"){return`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}stopAllWatchers(){this.activeWatchers.forEach(e=>{e.stop()}),this.activeWatchers.clear(),d.info("[DeviceManager] All watchers stopped")}getCapabilities(){return{support:this.support,activeWatchers:this.activeWatchers.size,watcherTypes:Array.from(this.activeWatchers.values()).map(e=>e.type)}}}class ${constructor(e={}){t(this,"effects",{fadeIn:(e=300)=>[{opacity:0},{opacity:1}],slideInLeft:(e="100px",t=300)=>[{transform:`translateX(-${e})`,opacity:0},{transform:"translateX(0)",opacity:1}],slideInRight:(e="100px",t=300)=>[{transform:`translateX(${e})`,opacity:0},{transform:"translateX(0)",opacity:1}],slideInUp:(e="100px",t=300)=>[{transform:`translateY(${e})`,opacity:0},{transform:"translateY(0)",opacity:1}],slideInDown:(e="100px",t=300)=>[{transform:`translateY(-${e})`,opacity:0},{transform:"translateY(0)",opacity:1}],scaleIn:(e=.8,t=300)=>[{transform:`scale(${e})`,opacity:0},{transform:"scale(1)",opacity:1}],rotateIn:(e="-180deg",t=600)=>[{transform:`rotate(${e})`,opacity:0},{transform:"rotate(0deg)",opacity:1}],fadeOut:(e=300)=>[{opacity:1},{opacity:0}],slideOutLeft:(e="100px",t=300)=>[{transform:"translateX(0)",opacity:1},{transform:`translateX(-${e})`,opacity:0}],slideOutRight:(e="100px",t=300)=>[{transform:"translateX(0)",opacity:1},{transform:`translateX(${e})`,opacity:0}],scaleOut:(e=.8,t=300)=>[{transform:"scale(1)",opacity:1},{transform:`scale(${e})`,opacity:0}],bounce:(e="20px",t=600)=>[{transform:"translateY(0)"},{transform:`translateY(-${e})`,offset:.25},{transform:"translateY(0)",offset:.5},{transform:`translateY(-${e})`,offset:.75},{transform:"translateY(0)"}],pulse:(e=1.1,t=600)=>[{transform:"scale(1)"},{transform:`scale(${e})`,offset:.5},{transform:"scale(1)"}],shake:(e="10px",t=600)=>[{transform:"translateX(0)"},{transform:`translateX(-${e})`,offset:.1},{transform:`translateX(${e})`,offset:.2},{transform:`translateX(-${e})`,offset:.3},{transform:`translateX(${e})`,offset:.4},{transform:`translateX(-${e})`,offset:.5},{transform:`translateX(${e})`,offset:.6},{transform:`translateX(-${e})`,offset:.7},{transform:`translateX(${e})`,offset:.8},{transform:`translateX(-${e})`,offset:.9},{transform:"translateX(0)"}],rubberBand:(e=1e3)=>[{transform:"scale(1)"},{transform:"scale(1.25, 0.75)",offset:.3},{transform:"scale(0.75, 1.25)",offset:.4},{transform:"scale(1.15, 0.85)",offset:.5},{transform:"scale(0.95, 1.05)",offset:.65},{transform:"scale(1.05, 0.95)",offset:.75},{transform:"scale(1)"}],spin:(e=1e3)=>[{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],heartbeat:(e=1.3,t=1e3)=>[{transform:"scale(1)"},{transform:`scale(${e})`,offset:.14},{transform:"scale(1)",offset:.28},{transform:`scale(${e})`,offset:.42},{transform:"scale(1)",offset:.7}]}),t(this,"easings",{linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",easeInQuad:"cubic-bezier(0.25, 0.46, 0.45, 0.94)",easeOutQuad:"cubic-bezier(0.25, 0.46, 0.45, 0.94)",easeInOutQuad:"cubic-bezier(0.455, 0.03, 0.515, 0.955)",easeInCubic:"cubic-bezier(0.32, 0, 0.67, 0)",easeOutCubic:"cubic-bezier(0.33, 1, 0.68, 1)",easeInOutCubic:"cubic-bezier(0.65, 0, 0.35, 1)",easeInQuart:"cubic-bezier(0.5, 0, 0.75, 0)",easeOutQuart:"cubic-bezier(0.25, 1, 0.5, 1)",easeInOutQuart:"cubic-bezier(0.76, 0, 0.24, 1)",easeOutBack:"cubic-bezier(0.34, 1.56, 0.64, 1)",easeInBack:"cubic-bezier(0.36, 0, 0.66, -0.56)",easeInOutBack:"cubic-bezier(0.68, -0.6, 0.32, 1.6)"}),this.config=e,this.activeAnimations=new Map,this.animationGroups=new Map,this.defaultEasing=e.easing||"ease-out",this.defaultDuration=e.duration||300,this.supported="animate"in Element.prototype,this.supported?d.info("[AnimationManager] Initialized with Web Animations API support"):d.warn("[AnimationManager] Web Animations API not supported, using fallbacks")}animate(e,t,n={}){if(!e||!t)return d.warn("[AnimationManager] Missing element or keyframes"),null;const i={duration:this.defaultDuration,easing:this.defaultEasing,fill:"forwards",...n},s=this.generateId();if(this.supported){const n=e.animate(t,i),o=this.enhanceAnimation(n,s,{element:e,keyframes:t,options:i});return this.activeAnimations.set(s,o),n.addEventListener("finish",()=>{this.activeAnimations.delete(s)}),d.info(`[AnimationManager] Animation started: ${s}`),o}return this.fallbackAnimate(e,t,i,s)}keyframes(e){if(Array.isArray(e))return e;if("object"==typeof e){const t=[];return Object.keys(e).sort((e,t)=>parseFloat(e.replace("%",""))-parseFloat(t.replace("%",""))).forEach(n=>{const i=parseFloat(n.replace("%",""))/100;t.push({...e[n],offset:i})}),t}return e}fadeIn(e,t={}){return this.animate(e,this.effects.fadeIn(),{duration:300,easing:this.easings.easeOut,...t})}fadeOut(e,t={}){return this.animate(e,this.effects.fadeOut(),{duration:300,easing:this.easings.easeIn,...t})}slideIn(e,t="up",n={}){return this.animate(e,this.effects[{up:"slideInUp",down:"slideInDown",left:"slideInLeft",right:"slideInRight"}[t]](),{duration:400,easing:this.easings.easeOutBack,...n})}bounce(e,t={}){return this.animate(e,this.effects.bounce(),{duration:600,easing:this.easings.easeInOut,...t})}pulse(e,t={}){return this.animate(e,this.effects.pulse(),{duration:600,easing:this.easings.easeInOut,iterations:1/0,...t})}group(e,t={}){const n=this.generateId("group"),i=[];e.forEach(({element:e,keyframes:n,animationOptions:s={}})=>{const o=this.animate(e,n,{...s,...t});o&&o.finished&&i.push(o.finished)});const s={id:n,finished:Promise.all(i),play:()=>{e.forEach(e=>{e.animation&&e.animation.play()})},pause:()=>{e.forEach(e=>{e.animation&&e.animation.pause()})},reverse:()=>{e.forEach(e=>{e.animation&&e.animation.reverse()})},cancel:()=>{e.forEach(e=>{e.animation&&e.animation.cancel()})}};return this.animationGroups.set(n,s),s}stagger(e,t,n={}){const i=n.staggerDelay||100,s=[];return e.forEach((e,o)=>{const a=o*i,r=this.animate(e,t,{...n,delay:a});s.push({element:e,animation:r})}),this.group(s.map(({element:e,animation:n})=>({element:e,keyframes:t,animation:n})))}timeline(e){const t=this.generateId("timeline");let n=0;const i=[];return e.forEach(e=>{var t;const s=void 0!==e.at?e.at:n,o=this.animate(e.element,e.keyframes,{...e.options,delay:s});i.push(o),void 0===e.at&&(n+=(null==(t=e.options)?void 0:t.duration)||this.defaultDuration)}),{id:t,animations:i,finished:Promise.all(i.map(e=>e.finished)),play:()=>i.forEach(e=>e.play()),pause:()=>i.forEach(e=>e.pause()),reverse:()=>i.forEach(e=>e.reverse()),cancel:()=>i.forEach(e=>e.cancel())}}onScroll(e,t,n={}){const i=n.trigger||e,s=n.start||0,o=n.end||1,a=new IntersectionObserver(i=>{i.forEach(i=>{if(i.isIntersecting){Math.min(Math.max((i.intersectionRatio-s)/(o-s),0),1)>=0&&this.animate(e,t,{...n,duration:n.duration||this.defaultDuration})}})},{threshold:this.createThresholdArray(20)});return a.observe(i),{observer:a,disconnect:()=>a.disconnect()}}enhanceAnimation(e,t,n){return{id:t,animation:e,metadata:n,play:()=>e.play(),pause:()=>e.pause(),reverse:()=>e.reverse(),cancel:()=>e.cancel(),finish:()=>e.finish(),get currentTime(){return e.currentTime},set currentTime(t){e.currentTime=t},get playbackRate(){return e.playbackRate},set playbackRate(t){e.playbackRate=t},get playState(){return e.playState},get finished(){return e.finished},seek(t){e.currentTime=e.effect.getTiming().duration*t},setProgress(e){this.seek(Math.max(0,Math.min(1,e)))},onFinish(t){e.addEventListener("finish",t)},onCancel(t){e.addEventListener("cancel",t)}}}fallbackAnimate(e,t,n,i){d.info("[AnimationManager] Using CSS fallback animation");const s=t[t.length-1];return e.style.transition=`all ${n.duration}ms ${n.easing}`,Object.assign(e.style,s),{id:i,finished:new Promise(e=>setTimeout(e,n.duration)),play:()=>{},pause:()=>{},cancel:()=>{e.style.transition=""}}}generateId(e="anim"){return`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}createThresholdArray(e){const t=[];for(let n=0;n<=e;n++)t.push(n/e);return t}getActiveAnimations(){return Array.from(this.activeAnimations.entries()).map(([e,t])=>({id:e,playState:t.playState,currentTime:t.currentTime,metadata:t.metadata}))}cancelAll(){this.activeAnimations.forEach(e=>{e.cancel()}),this.activeAnimations.clear(),d.info("[AnimationManager] All animations cancelled")}pauseAll(){this.activeAnimations.forEach(e=>{e.pause()}),d.info("[AnimationManager] All animations paused")}resumeAll(){this.activeAnimations.forEach(e=>{"paused"===e.playState&&e.play()}),d.info("[AnimationManager] All animations resumed")}}class D{constructor(e={}){t(this,"web",{create:(e,t={})=>{if(!this.support.webWorkers)throw new Error("Web Workers not supported");let n;const i=this.generateId("worker");try{if("string"==typeof e)n=new Worker(e,t);else if("function"==typeof e){const i=this.createWorkerBlob(e);n=new Worker(URL.createObjectURL(i),t)}else{if(!(e instanceof Blob))throw new Error("Invalid script type");n=new Worker(URL.createObjectURL(e),t)}const s={id:i,worker:n,send:(e,t=null)=>{t?n.postMessage(e,t):n.postMessage(e),d.info(`[WorkerManager] Message sent to worker: ${i}`)},onMessage:e=>{n.addEventListener("message",t=>{e(t.data,t)})},onError:e=>{n.addEventListener("error",e),n.addEventListener("messageerror",e)},terminate:()=>{n.terminate(),this.activeWorkers.delete(i),d.info(`[WorkerManager] Worker terminated: ${i}`)},execute:(e,t=null)=>new Promise((i,s)=>{const o=this.generateId("msg"),a=e=>{e.data.id===o&&(n.removeEventListener("message",a),e.data.error?s(new Error(e.data.error)):i(e.data.result))};n.addEventListener("message",a),n.postMessage({id:o,type:"execute",function:e.toString(),data:t}),setTimeout(()=>{n.removeEventListener("message",a),s(new Error("Worker execution timeout"))},3e4)})};return this.activeWorkers.set(i,s),d.info(`[WorkerManager] Web Worker created: ${i}`),s}catch(s){throw d.error("[WorkerManager] Worker creation failed:",s),s}},createPool:(e,t=navigator.hardwareConcurrency||4,n={})=>{const i=[];for(let a=0;a<t;a++)i.push(this.web.create(e,n));let s=0;const o={workers:i,execute:async(e,t=null)=>{const n=i[s];return s=(s+1)%i.length,n.execute(e,t)},broadcast:e=>{i.forEach(t=>{t.send(e)})},terminate:()=>{i.forEach(e=>{e.terminate()}),i.length=0,d.info("[WorkerManager] Worker pool terminated")}};return d.info(`[WorkerManager] Worker pool created with ${t} workers`),o},tasks:{compute:(e,t)=>this.web.create("\n self.addEventListener('message', function(e) {\n const { id, function: fnString, data } = e.data;\n \n try {\n const fn = new Function('return ' + fnString)();\n const result = fn(data);\n self.postMessage({ id, result });\n } catch (error) {\n self.postMessage({ id, error: error.message });\n }\n });\n ").execute(e,t),processImage:(e,t)=>this.web.create("\n self.addEventListener('message', function(e) {\n const { id, data: { imageData, filters } } = e.data;\n \n try {\n const pixels = imageData.data;\n \n for (let i = 0; i < pixels.length; i += 4) {\n // Apply filters\n if (filters.brightness) {\n pixels[i] *= filters.brightness; // R\n pixels[i + 1] *= filters.brightness; // G\n pixels[i + 2] *= filters.brightness; // B\n }\n \n if (filters.contrast) {\n const factor = (259 * (filters.contrast * 255 + 255)) / (255 * (259 - filters.contrast * 255));\n pixels[i] = factor * (pixels[i] - 128) + 128;\n pixels[i + 1] = factor * (pixels[i + 1] - 128) + 128;\n pixels[i + 2] = factor * (pixels[i + 2] - 128) + 128;\n }\n \n if (filters.grayscale) {\n const gray = 0.299 * pixels[i] + 0.587 * pixels[i + 1] + 0.114 * pixels[i + 2];\n pixels[i] = gray;\n pixels[i + 1] = gray;\n pixels[i + 2] = gray;\n }\n }\n \n self.postMessage({ id, result: imageData }, [imageData.data.buffer]);\n } catch (error) {\n self.postMessage({ id, error: error.message });\n }\n });\n ").execute(null,{imageData:e,filters:t}),processData:(e,t)=>this.web.create("\n self.addEventListener('message', function(e) {\n const { id, data, function: processorString } = e.data;\n \n try {\n const processor = new Function('return ' + processorString)();\n const result = data.map(processor);\n self.postMessage({ id, result });\n } catch (error) {\n self.postMessage({ id, error: error.message });\n }\n });\n ").execute(t,e)}}),t(this,"service",{register:async(e,t={})=>{if(!this.support.serviceWorker)throw new Error("Service Worker not supported");try{const n=await navigator.serviceWorker.register(e,t);return d.info("[WorkerManager] Service Worker registered:",e),{registration:n,scope:n.scope,update:()=>n.update(),unregister:()=>n.unregister(),postMessage:e=>{n.active&&n.active.postMessage(e)},onUpdate:e=>{n.addEventListener("updatefound",()=>{const t=n.installing;t.addEventListener("statechange",()=>{"installed"===t.state&&navigator.serviceWorker.controller&&e(t)})})},checkForUpdates:()=>n.update()}}catch(n){throw d.error("[WorkerManager] Service Worker registration failed:",n),n}},getRegistration:async(e="/")=>{if(!this.support.serviceWorker)return null;try{return await navigator.serviceWorker.getRegistration(e)}catch(t){return d.error("[WorkerManager] Get registration failed:",t),null}},getRegistrations:async()=>{if(!this.support.serviceWorker)return[];try{return await navigator.serviceWorker.getRegistrations()}catch(e){return d.error("[WorkerManager] Get registrations failed:",e),[]}}}),t(this,"shared",{create:(e,t={})=>{if(!this.support.sharedWorker)throw new Error("Shared Worker not supported");try{const n=new SharedWorker(e,t),i=n.port,s=this.generateId("shared");i.start();const o={id:s,worker:n,port:i,send:(e,t=null)=>{t?i.postMessage(e,t):i.postMessage(e)},onMessage:e=>{i.addEventListener("message",t=>{e(t.data,t)})},onError:e=>{n.addEventListener("error",e),i.addEventListener("messageerror",e)},close:()=>{i.close(),this.activeWorkers.delete(s),d.info(`[WorkerManager] Shared Worker closed: ${s}`)}};return this.activeWorkers.set(s,o),d.info(`[WorkerManager] Shared Worker created: ${s}`),o}catch(n){throw d.error("[WorkerManager] Shared Worker creation failed:",n),n}}}),t(this,"offscreen",{create:(e,t=null)=>{if(!this.support.offscreenCanvas)throw new Error("Offscreen Canvas not supported");try{const n=e.transferControlToOffscreen(),i=t||"\n self.addEventListener('message', function(e) {\n const { canvas, type, data } = e.data;\n \n if (type === 'init') {\n self.canvas = canvas;\n self.ctx = canvas.getContext('2d');\n }\n \n if (type === 'draw' && self.ctx) {\n // Basic drawing operations\n const { operations } = data;\n \n operations.forEach(op => {\n switch (op.type) {\n case 'fillRect':\n self.ctx.fillRect(...op.args);\n break;\n case 'strokeRect':\n self.ctx.strokeRect(...op.args);\n break;\n case 'fillText':\n self.ctx.fillText(...op.args);\n break;\n case 'setFillStyle':\n self.ctx.fillStyle = op.value;\n break;\n case 'setStrokeStyle':\n self.ctx.strokeStyle = op.value;\n break;\n }\n });\n }\n });\n ",s=this.web.create(i);return s.send({type:"init",canvas:n},[n]),{worker:s,draw:e=>{s.send({type:"draw",data:{operations:e}})},send:e=>s.send(e),onMessage:e=>s.onMessage(e),terminate:()=>s.terminate()}}catch(n){throw d.error("[WorkerManager] Offscreen Canvas creation failed:",n),n}}}),t(this,"utils",{benchmark:async(e,t,n=1e3)=>{const i=this.web.create(()=>{self.addEventListener("message",e=>{const{id:t,function:n,data:i,iterations:s}=e.data;try{const e=new Function("return "+n)(),o=performance.now();for(let t=0;t<s;t++)e(i);const a=performance.now()-o,r=a/s;self.postMessage({id:t,result:{totalTime:a,avgTime:r,iterations:s,opsPerSecond:1e3/r}})}catch(o){self.postMessage({id:t,error:o.message})}})}),s=await i.execute(e,t,n);return i.terminate(),s},parallelMap:async(e,t,n=null)=>{const i=n||Math.ceil(e.length/(navigator.hardwareConcurrency||4)),s=this.web.createPool(()=>{self.addEventListener("message",e=>{const{id:t,data:{chunk:n,function:i}}=e.data;try{const e=new Function("return "+i)(),s=n.map(e);self.postMessage({id:t,result:s})}catch(s){self.postMessage({id:t,error:s.message})}})}),o=[];for(let r=0;r<e.length;r+=i){const n=e.slice(r,r+i);o.push(s.execute(t,n))}const a=await Promise.all(o);return s.terminate(),a.flat()}}),this.config=e,this.activeWorkers=new Map,this.messageHandlers=new Map,this.workerScripts=new Map,this.support={webWorkers:"Worker"in window,serviceWorker:"serviceWorker"in navigator,sharedWorker:"SharedWorker"in window,offscreenCanvas:"OffscreenCanvas"in window},d.info("[WorkerManager] Initialized with support:",this.support)}createWorkerBlob(e){const t=`\n (function() {\n const workerFunction = ${e.toString()};\n \n if (typeof workerFunction === 'function') {\n // If function expects to be called immediately\n if (workerFunction.length === 0) {\n workerFunction();\n }\n }\n \n // Standard worker message handling\n self.addEventListener('message', function(e) {\n if (e.data.type === 'execute' && e.data.function) {\n try {\n const fn = new Function('return ' + e.data.function)();\n const result = fn(e.data.data);\n self.postMessage({ \n id: e.data.id, \n result \n });\n } catch (error) {\n self.postMessage({ \n id: e.data.id, \n error: error.message \n });\n }\n }\n });\n })();\n `;return new Blob([t],{type:"application/javascript"})}generateId(e="worker"){return`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}terminateAll(){this.activeWorkers.forEach(e=>{e.terminate?e.terminate():e.close&&e.close()}),this.activeWorkers.clear(),d.info("[WorkerManager] All workers terminated")}getStats(){const e=Array.from(this.activeWorkers.values());return{total:e.length,byType:e.reduce((e,t)=>{const n=t.id.split("_")[0];return e[n]=(e[n]||0)+1,e},{}),support:this.support,hardwareConcurrency:navigator.hardwareConcurrency||"unknown"}}}class O{constructor(e={}){var n,i,s;t(this,"timing",{mark:(e,t={})=>{if(!this.support.userTiming)return d.warn("[PerformanceManager] User Timing not supported"),null;try{return performance.mark(e,t),this.marks.set(e,{name:e,timestamp:performance.now(),options:t}),d.info(`[PerformanceManager] Mark created: ${e}`),this.marks.get(e)}catch(n){return d.error("[PerformanceManager] Mark creation failed:",n),null}},measure:(e,t,n,i={})=>{if(!this.support.userTiming)return d.warn("[PerformanceManager] User Timing not supported"),null;try{performance.measure(e,t,n,i);const s=performance.getEntriesByName(e,"measure")[0],o={name:e,startTime:s.startTime,duration:s.duration,startMark:t,endMark:n,options:i};return this.measures.set(e,o),d.info(`[PerformanceManager] Measure created: ${e} (${o.duration.toFixed(2)}ms)`),o}catch(s){return d.error("[PerformanceManager] Measure creation failed:",s),null}},clear:(e=null)=>{if(this.support.userTiming)try{e?(performance.clearMarks(e),performance.clearMeasures(e),this.marks.delete(e),this.measures.delete(e)):(performance.clearMarks(),performance.clearMeasures(),this.marks.clear(),this.measures.clear()),d.info(`[PerformanceManager] Cleared: ${e||"all"}`)}catch(t){d.error("[PerformanceManager] Clear failed:",t)}},getMarks:()=>this.support.userTiming?Array.from(this.marks.values()):[],getMeasures:()=>this.support.userTiming?Array.from(this.measures.values()):[]}),t(this,"navigation",{get:()=>{if(!this.support.navigation)return this.getLegacyNavigationTiming();try{const e=performance.getEntriesByType("navigation")[0];return e?{redirect:e.redirectEnd-e.redirectStart,dns:e.domainLookupEnd-e.domainLookupStart,connect:e.connectEnd-e.connectStart,ssl:e.connectEnd-e.secureConnectionStart,ttfb:e.responseStart-e.requestStart,download:e.responseEnd-e.responseStart,domProcessing:e.domContentLoadedEventStart-e.responseEnd,domComplete:e.domComplete-e.domContentLoadedEventStart,loadComplete:e.loadEventEnd-e.loadEventStart,totalTime:e.loadEventEnd-e.startTime,navigationStart:e.startTime,unloadTime:e.unloadEventEnd-e.unloadEventStart,redirectCount:e.redirectCount,transferSize:e.transferSize,encodedBodySize:e.encodedBodySize,decodedBodySize:e.decodedBodySize,connectionInfo:{nextHopProtocol:e.nextHopProtocol,renderBlockingStatus:e.renderBlockingStatus}}:null}catch(e){return d.error("[PerformanceManager] Navigation timing failed:",e),null}},getInsights:()=>{const e=this.navigation.get();return e?{insights:{serverResponseTime:this.getInsight("ttfb",e.ttfb,200,500),domProcessing:this.getInsight("domProcessing",e.domProcessing,500,1e3),totalLoadTime:this.getInsight("totalTime",e.totalTime,2e3,4e3),transferEfficiency:this.getTransferEfficiency(e)},recommendations:this.getNavigationRecommendations(e)}:null}}),t(this,"resources",{get:(e=null)=>{if(!this.support.resourceTiming)return d.warn("[PerformanceManager] Resource Timing not supported"),[];try{const t=performance.getEntriesByType("resource").map(e=>({name:e.name,type:this.getResourceType(e),startTime:e.startTime,duration:e.duration,size:{transfer:e.transferSize,encoded:e.encodedBodySize,decoded:e.decodedBodySize},timing:{redirect:e.redirectEnd-e.redirectStart,dns:e.domainLookupEnd-e.domainLookupStart,connect:e.connectEnd-e.connectStart,ssl:e.connectEnd-e.secureConnectionStart,ttfb:e.responseStart-e.requestStart,download:e.responseEnd-e.responseStart},protocol:e.nextHopProtocol,cached:0===e.transferSize&&e.decodedBodySize>0}));return e?t.filter(t=>t.type===e):t}catch(t){return d.error("[PerformanceManager] Resource timing failed:",t),[]}},getSummary:()=>{const e=this.resources.get(),t={total:e.length,types:{},totalSize:0,totalDuration:0,cached:0,slowResources:[]};return e.forEach(e=>{const n=e.type;t.types[n]||(t.types[n]={count:0,size:0,duration:0}),t.types[n].count++,t.types[n].size+=e.size.transfer,t.types[n].duration+=e.duration,t.totalSize+=e.size.transfer,t.totalDuration+=e.duration,e.cached&&t.cached++,e.duration>1e3&&t.slowResources.push(e)}),t}}),t(this,"vitals",{start:(e=null)=>{const t={};return this.observePaint(n=>{n.forEach(n=>{"first-contentful-paint"===n.name&&(t.fcp=n.startTime,this.checkThreshold("fcp",n.startTime),e&&e("fcp",n.startTime))})}),this.observeLCP(n=>{n.forEach(n=>{t.lcp=n.startTime,this.checkThreshold("lcp",n.startTime),e&&e("lcp",n.startTime)})}),this.observeFID(n=>{n.forEach(n=>{t.fid=n.processingStart-n.startTime,this.checkThreshold("fid",t.fid),e&&e("fid",t.fid)})}),this.observeCLS(n=>{let i=0;n.forEach(e=>{e.hadRecentInput||(i+=e.value)}),t.cls=i,this.checkThreshold("cls",i),e&&e("cls",i)}),t},get:()=>({fcp:this.getMetric("fcp"),lcp:this.getMetric("lcp"),fid:this.getMetric("fid"),cls:this.getMetric("cls"),ratings:{fcp:this.getRating("fcp",this.getMetric("fcp")),lcp:this.getRating("lcp",this.getMetric("lcp")),fid:this.getRating("fid",this.getMetric("fid")),cls:this.getRating("cls",this.getMetric("cls"))}})}),t(this,"memory",{get:()=>{if(!this.support.memory)return d.warn("[PerformanceManager] Memory API not supported"),null;try{const e=performance.memory;return{used:e.usedJSHeapSize,total:e.totalJSHeapSize,limit:e.jsHeapSizeLimit,percentage:e.usedJSHeapSize/e.jsHeapSizeLimit*100,formatted:{used:this.formatBytes(e.usedJSHeapSize),total:this.formatBytes(e.totalJSHeapSize),limit:this.formatBytes(e.jsHeapSizeLimit)}}}catch(e){return d.error("[PerformanceManager] Memory get failed:",e),null}},monitor:(e,t=5e3)=>{if(!this.support.memory)return null;const n=setInterval(()=>{const t=this.memory.get();t&&(e(t),t.percentage>80&&d.warn("[PerformanceManager] High memory usage detected:",t.percentage.toFixed(1)+"%"))},t);return{stop:()=>clearInterval(n)}}}),t(this,"longTasks",{start:(e=null)=>{if(!this.support.longTask)return d.warn("[PerformanceManager] Long Task API not supported"),null;try{const t=new PerformanceObserver(t=>{t.getEntries().forEach(t=>{const n={duration:t.duration,startTime:t.startTime,name:t.name,attribution:t.attribution||[]};d.warn("[PerformanceManager] Long task detected:",n),e&&e(n)})});t.observe({entryTypes:["longtask"]});const n=this.generateId("longtask");return this.observers.set(n,t),{id:n,stop:()=>{t.disconnect(),this.observers.delete(n)}}}catch(t){return d.error("[PerformanceManager] Long task monitoring failed:",t),null}}}),t(this,"optimize",{deferScript:(e,t=null)=>{const n=document.createElement("script");return n.src=e,n.defer=!0,t&&(n.onload=t),document.head.appendChild(n),n},preload:(e,t,n=!1)=>{const i=document.createElement("link");return i.rel="preload",i.href=e,i.as=t,n&&(i.crossOrigin="anonymous"),document.head.appendChild(i),i},prefetch:e=>{const t=document.createElement("link");return t.rel="prefetch",t.href=e,document.head.appendChild(t),t},lazyImages:(e="img[data-src]")=>{if("IntersectionObserver"in window){const t=document.querySelectorAll(e),n=new IntersectionObserver(e=>{e.forEach(e=>{if(e.isIntersecting){const t=e.target;t.src=t.dataset.src,t.classList.remove("lazy"),n.unobserve(t)}})});return t.forEach(e=>n.observe(e)),n}document.querySelectorAll(e).forEach(e=>{e.src=e.dataset.src,e.classList.remove("lazy")})},analyzeBundles:()=>{const e=Array.from(document.querySelectorAll("script[src]")),t=Array.from(document.querySelectorAll('link[rel="stylesheet"]')),n={scripts:e.map(e=>({src:e.src,async:e.async,defer:e.defer})),styles:t.map(e=>({href:e.href,media:e.media})),recommendations:[]};return e.length>10&&n.recommendations.push("Consider bundling JavaScript files"),t.length>5&&n.recommendations.push("Consider bundling CSS files"),n}}),this.config=e,this.marks=new Map,this.measures=new Map,this.observers=new Map,this.metrics=new Map,this.thresholds={fcp:2e3,lcp:2500,fid:100,cls:.1,...e.thresholds},this.support={performance:"performance"in window,timing:"timing"in(window.performance||{}),navigation:"navigation"in(window.performance||{}),observer:"PerformanceObserver"in window,memory:"memory"in(window.performance||{}),userTiming:"mark"in(window.performance||{}),resourceTiming:"getEntriesByType"in(window.performance||{}),paintTiming:"PerformanceObserver"in window&&(null==(n=PerformanceObserver.supportedEntryTypes)?void 0:n.includes("paint")),layoutInstability:"PerformanceObserver"in window&&(null==(i=PerformanceObserver.supportedEntryTypes)?void 0:i.includes("layout-shift")),longTask:"PerformanceObserver"in window&&(null==(s=PerformanceObserver.supportedEntryTypes)?void 0:s.includes("longtask"))},d.info("[PerformanceManager] Initialized with support:",this.support),this.startCoreMetrics()}startCoreMetrics(){this.vitals.start((e,t)=>{this.setMetric(e,t)}),this.support.memory&&this.memory.monitor(e=>{this.setMetric("memory",e)})}observePaint(e){if(this.support.paintTiming)try{const t=new PerformanceObserver(t=>{e(t.getEntries())});return t.observe({entryTypes:["paint"]}),t}catch(t){d.error("[PerformanceManager] Paint observer failed:",t)}}observeLCP(e){if(this.support.observer)try{const t=new PerformanceObserver(t=>{e(t.getEntries())});return t.observe({entryTypes:["largest-contentful-paint"]}),t}catch(t){d.error("[PerformanceManager] LCP observer failed:",t)}}observeFID(e){if(this.support.observer)try{const t=new PerformanceObserver(t=>{e(t.getEntries())});return t.observe({entryTypes:["first-input"]}),t}catch(t){d.error("[PerformanceManager] FID observer failed:",t)}}observeCLS(e){if(this.support.layoutInstability)try{const t=new PerformanceObserver(t=>{e(t.getEntries())});return t.observe({entryTypes:["layout-shift"]}),t}catch(t){d.error("[PerformanceManager] CLS observer failed:",t)}}getLegacyNavigationTiming(){if(!this.support.timing)return null;const e=performance.timing,t=e.navigationStart;return{redirect:e.redirectEnd-e.redirectStart,dns:e.domainLookupEnd-e.domainLookupStart,connect:e.connectEnd-e.connectStart,ssl:e.connectEnd-e.secureConnectionStart,ttfb:e.responseStart-e.requestStart,download:e.responseEnd-e.responseStart,domProcessing:e.domContentLoadedEventStart-e.responseEnd,domComplete:e.domComplete-e.domContentLoadedEventStart,loadComplete:e.loadEventEnd-e.loadEventStart,totalTime:e.loadEventEnd-t}}getResourceType(e){return{js:"script",css:"stylesheet",png:"image",jpg:"image",jpeg:"image",gif:"image",svg:"image",webp:"image",woff:"font",woff2:"font",ttf:"font",eot:"font",json:"fetch",xml:"fetch"}[new URL(e.name).pathname.split(".").pop().toLowerCase()]||e.initiatorType||"other"}getInsight(e,t,n,i){return t<n?{rating:"good",message:`Excellent ${e}`}:t<i?{rating:"needs-improvement",message:`${e} needs improvement`}:{rating:"poor",message:`Poor ${e} performance`}}getTransferEfficiency(e){const t=e.decodedBodySize>0?e.encodedBodySize/e.decodedBodySize:1;return{ratio:t,rating:t<.7?"good":t<.9?"fair":"poor"}}getNavigationRecommendations(e){const t=[];return e.ttfb>500&&t.push("Server response time is slow. Consider optimizing backend performance."),e.dns>100&&t.push("DNS lookup time is high. Consider using a faster DNS provider."),e.connect>1e3&&t.push("Connection time is slow. Check network latency."),e.domProcessing>1e3&&t.push("DOM processing is slow. Consider optimizing JavaScript execution."),t}checkThreshold(e,t){const n=this.thresholds[e];n&&t>n&&d.warn(`[PerformanceManager] ${e.toUpperCase()} threshold exceeded: ${t}ms (threshold: ${n}ms)`)}getRating(e,t){const n={fcp:{good:1800,poor:3e3},lcp:{good:2500,poor:4e3},fid:{good:100,poor:300},cls:{good:.1,poor:.25}}[e];return n&&null!=t?t<=n.good?"good":t<=n.poor?"needs-improvement":"poor":"unknown"}setMetric(e,t){this.metrics.set(e,{value:t,timestamp:Date.now()})}getMetric(e){const t=this.metrics.get(e);return t?t.value:null}formatBytes(e){if(0===e)return"0 Bytes";const t=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,t)).toFixed(2))+" "+["Bytes","KB","MB","GB"][t]}generateId(e="perf"){return`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}cleanup(){this.observers.forEach(e=>{e.disconnect()}),this.observers.clear(),this.metrics.clear(),this.marks.clear(),this.measures.clear(),d.info("[PerformanceManager] Cleanup completed")}getReport(){return{support:this.support,navigation:this.navigation.get(),resources:this.resources.getSummary(),vitals:this.vitals.get(),memory:this.memory.get(),marks:this.timing.getMarks(),measures:this.timing.getMeasures(),activeObservers:this.observers.size,timestamp:Date.now()}}}class z{constructor(e={}){var t;this.config=e,this.permissionCache=new Map,this.permissionWatchers=new Map,this.requestQueue=new Map,this.support={permissions:"permissions"in navigator,query:void 0!==(null==(t=navigator.permissions)?void 0:t.query),request:"requestPermission"in Notification||"getUserMedia"in(navigator.mediaDevices||{}),geolocation:"geolocation"in navigator,notifications:"Notification"in window,camera:void 0!==navigator.mediaDevices,microphone:void 0!==navigator.mediaDevices,clipboard:"clipboard"in navigator,vibration:"vibrate"in navigator},this.permissionMap={camera:{name:"camera",api:"mediaDevices"},microphone:{name:"microphone",api:"mediaDevices"},geolocation:{name:"geolocation",api:"geolocation"},notifications:{name:"notifications",api:"notification"},"clipboard-read":{name:"clipboard-read",api:"clipboard"},"clipboard-write":{name:"clipboard-write",api:"clipboard"},"background-sync":{name:"background-sync",api:"serviceWorker"},"persistent-storage":{name:"persistent-storage",api:"storage"},push:{name:"push",api:"serviceWorker"},midi:{name:"midi",api:"midi"},"payment-handler":{name:"payment-handler",api:"payment"}},d.info("[PermissionManager] Initialized with support:",this.support),this.cacheCurrentPermissions()}async check(e){if(!this.support.permissions||!this.support.query)return d.warn("[PermissionManager] Permissions API not supported, using fallback"),this.checkFallback(e);try{const t=this.permissionCache.get(e);if(t&&Date.now()-t.timestamp<3e4)return t.status;const n=this.getPermissionDescriptor(e),i=await navigator.permissions.query(n),s={name:e,state:i.state,timestamp:Date.now(),supported:!0};return this.permissionCache.set(e,s),i.addEventListener("change",()=>{this.onPermissionChange(e,i.state)}),d.info(`[PermissionManager] Permission checked: ${e} = ${i.state}`),s}catch(t){return d.warn(`[PermissionManager] Permission check failed for ${e}:`,t.message),this.checkFallback(e)}}async request(e,t={}){const{showRationale:n=!0,fallbackMessage:i=null,timeout:s=3e4}=t;try{const t=await this.check(e);if("granted"===t.state)return{granted:!0,state:"granted",fromCache:!0};if("denied"===t.state)return n&&await this.showPermissionRationale(e,i),{granted:!1,state:"denied",reason:"previously-denied"};const o=e;if(this.requestQueue.has(o))return d.info(`[PermissionManager] Permission request already in progress: ${e}`),this.requestQueue.get(o);const a=this.executePermissionRequest(e,s);this.requestQueue.set(o,a);const r=await a;return this.requestQueue.delete(o),this.permissionCache.set(e,{name:e,state:r.state,timestamp:Date.now(),supported:!0}),r}catch(o){return d.error(`[PermissionManager] Permission request failed: ${e}`,o),this.requestQueue.delete(e),{granted:!1,state:"error",error:o.message}}}async requestMultiple(e,t={}){const n={};if(t.sequential){for(const s of e)if(n[s]=await this.request(s,t),t.requireAll&&!n[s].granted)break}else{const i=e.map(e=>this.request(e,t).then(t=>[e,t]));(await Promise.allSettled(i)).forEach(e=>{if("fulfilled"===e.status){const[t,i]=e.value;n[t]=i}else d.error("[PermissionManager] Batch permission request failed:",e.reason)})}const i={results:n,granted:Object.values(n).filter(e=>e.granted).length,denied:Object.values(n).filter(e=>!e.granted).length,total:Object.keys(n).length};return d.info(`[PermissionManager] Batch permissions: ${i.granted}/${i.total} granted`),i}async checkRequired(e){const t={},n=[];for(const i of e){const e=await this.check(i);t[i]=e,"granted"!==e.state&&n.push(i)}return{allGranted:0===n.length,granted:Object.keys(t).filter(e=>"granted"===t[e].state),missing:n,statuses:t}}watch(e,t){const n=this.generateId("watcher");return this.permissionWatchers.set(n,{permission:e,callback:t,active:!0}),this.setupPermissionWatcher(e,t),d.info(`[PermissionManager] Permission watcher created: ${e}`),{id:n,stop:()=>{const t=this.permissionWatchers.get(n);t&&(t.active=!1,this.permissionWatchers.delete(n),d.info(`[PermissionManager] Permission watcher stopped: ${e}`))}}}getRecommendations(e=[]){const t={essential:[],recommended:[],optional:[]},n={camera:{permissions:["camera"],priority:"essential"},microphone:{permissions:["microphone"],priority:"essential"},location:{permissions:["geolocation"],priority:"recommended"},notifications:{permissions:["notifications"],priority:"recommended"},clipboard:{permissions:["clipboard-read","clipboard-write"],priority:"optional"},offline:{permissions:["persistent-storage"],priority:"recommended"},background:{permissions:["background-sync","push"],priority:"optional"}};return e.forEach(e=>{const i=n[e];i&&t[i.priority].push(...i.permissions)}),Object.keys(t).forEach(e=>{t[e]=[...new Set(t[e])]}),t}createOnboardingFlow(e,t={}){const{title:n="Permissions Required",descriptions:i={},onComplete:s=null,onSkip:o=null}=t;return{permissions:e,title:n,descriptions:i,async start(){d.info("[PermissionManager] Starting onboarding flow");const t=[];for(const s of e){const e=i[s]||this.getDefaultDescription(s),n=await this.showPermissionDialog(s,e);if("grant"===n){const e=await this.request(s);t.push({permission:s,...e})}else{if("skip"!==n)return o&&o(t),{cancelled:!0,results:t};t.push({permission:s,granted:!1,skipped:!0})}}const n={completed:!0,granted:t.filter(e=>e.granted).length,total:t.length,results:t};return s&&s(n),n},getDefaultDescription:e=>({camera:"Take photos and record videos for enhanced functionality",microphone:"Record audio for voice features and communication",geolocation:"Provide location-based services and content",notifications:"Send you important updates and reminders","clipboard-read":"Access clipboard content for convenience features","clipboard-write":"Copy content to clipboard for easy sharing"}[e]||`Allow access to ${e} functionality`),async showPermissionDialog(e,t){return new Promise(n=>{const i=document.createElement("div");i.className="permission-dialog-modal",i.innerHTML=`\n <div class="permission-dialog-backdrop" style="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0,0,0,0.5);\n z-index: 10000;\n display: flex;\n align-items: center;\n justify-content: center;\n ">\n <div class="permission-dialog" style="\n background: white;\n border-radius: 8px;\n padding: 2rem;\n max-width: 400px;\n margin: 1rem;\n box-shadow: 0 4px 20px rgba(0,0,0,0.3);\n ">\n <h3 style="margin: 0 0 1rem 0; color: #333;">\n ${this.getPermissionIcon(e)} ${this.getPermissionTitle(e)}\n </h3>\n <p style="margin: 0 0 2rem 0; color: #666; line-height: 1.5;">\n ${t}\n </p>\n <div style="display: flex; gap: 1rem; justify-content: flex-end;">\n <button class="btn-skip" style="\n background: #f5f5f5;\n border: 1px solid #ddd;\n padding: 0.5rem 1rem;\n border-radius: 4px;\n cursor: pointer;\n ">Skip</button>\n <button class="btn-grant" style="\n background: #007bff;\n color: white;\n border: none;\n padding: 0.5rem 1rem;\n border-radius: 4px;\n cursor: pointer;\n ">Allow</button>\n </div>\n </div>\n </div>\n `,document.body.appendChild(i);const s=i.querySelector(".btn-skip"),o=i.querySelector(".btn-grant"),a=()=>document.body.removeChild(i);s.onclick=()=>{a(),n("skip")},o.onclick=()=>{a(),n("grant")},i.querySelector(".permission-dialog-backdrop").onclick=e=>{e.target===e.currentTarget&&(a(),n("cancel"))}})},getPermissionIcon:e=>({camera:"📷",microphone:"🎤",geolocation:"📍",notifications:"🔔","clipboard-read":"📋","clipboard-write":"📋"}[e]||"🔐"),getPermissionTitle:e=>({camera:"Camera Access",microphone:"Microphone Access",geolocation:"Location Access",notifications:"Notifications","clipboard-read":"Clipboard Access","clipboard-write":"Clipboard Access"}[e]||`${e} Permission`)}}async cacheCurrentPermissions(){if(!this.support.permissions)return;const e=["camera","microphone","geolocation","notifications"];for(const n of e)try{await this.check(n)}catch(t){}}getPermissionDescriptor(e){switch(e){case"camera":return{name:"camera"};case"microphone":return{name:"microphone"};case"geolocation":return{name:"geolocation"};case"notifications":return{name:"notifications"};case"clipboard-read":return{name:"clipboard-read"};case"clipboard-write":return{name:"clipboard-write"};case"persistent-storage":return{name:"persistent-storage"};case"background-sync":return{name:"background-sync"};case"push":return{name:"push",userVisibleOnly:!0};default:return{name:e}}}async checkFallback(e){const t={camera:()=>void 0!==navigator.mediaDevices,microphone:()=>void 0!==navigator.mediaDevices,geolocation:()=>"geolocation"in navigator,notifications:()=>"Notification"in window,"clipboard-read":()=>"clipboard"in navigator,"clipboard-write":()=>"clipboard"in navigator}[e],n=!!t&&t();return{name:e,state:n?"prompt":"unsupported",timestamp:Date.now(),supported:n,fallback:!0}}async executePermissionRequest(e,t){return new Promise(async(n,i)=>{const s=setTimeout(()=>{i(new Error("Permission request timeout"))},t);try{let t;switch(e){case"notifications":if("Notification"in window){const e=await Notification.requestPermission();t={granted:"granted"===e,state:e}}else t={granted:!1,state:"unsupported"};break;case"camera":case"microphone":try{const n={};n["camera"===e?"video":"audio"]=!0;(await navigator.mediaDevices.getUserMedia(n)).getTracks().forEach(e=>e.stop()),t={granted:!0,state:"granted"}}catch(o){t={granted:!1,state:"NotAllowedError"===o.name?"denied":"error",error:o.message}}break;case"geolocation":try{await new Promise((e,t)=>{navigator.geolocation.getCurrentPosition(e,t,{timeout:1e4,maximumAge:0})}),t={granted:!0,state:"granted"}}catch(o){t={granted:!1,state:1===o.code?"denied":"error",error:o.message}}break;default:if(this.support.permissions){const n=await navigator.permissions.query(this.getPermissionDescriptor(e));t={granted:"granted"===n.state,state:n.state}}else t={granted:!1,state:"unsupported"}}clearTimeout(s),n(t)}catch(o){clearTimeout(s),i(o)}})}async setupPermissionWatcher(e,t){if(this.support.permissions)try{const n=await navigator.permissions.query(this.getPermissionDescriptor(e));n.addEventListener("change",()=>{t({permission:e,state:n.state,timestamp:Date.now()})})}catch(n){d.warn(`[PermissionManager] Could not set up watcher for ${e}:`,n)}}onPermissionChange(e,t){d.info(`[PermissionManager] Permission changed: ${e} → ${t}`),this.permissionCache.set(e,{name:e,state:t,timestamp:Date.now(),supported:!0}),this.permissionWatchers.forEach(n=>{n.permission===e&&n.active&&n.callback({permission:e,state:t,timestamp:Date.now()})})}async showPermissionRationale(e,t=null){const n=t||{camera:"Camera access is needed to take photos and record videos. You can enable this in your browser settings.",microphone:"Microphone access is needed for audio recording and voice features. Please check your browser settings.",geolocation:"Location access helps provide relevant local content. You can manage this in your browser settings.",notifications:"Notifications keep you updated with important information. You can change this anytime in settings."}[e]||`${e} permission was denied. Please enable it in your browser settings to use this feature.`;return!("undefined"==typeof window||!window.confirm)&&window.confirm(n+"\n\nWould you like to try again?")}generateId(e="perm"){return`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}async getPermissionReport(){return{support:this.support,cached:Array.from(this.permissionCache.entries()).map(([e,t])=>({name:e,...t})),watchers:Array.from(this.permissionWatchers.keys()),timestamp:Date.now()}}clearCache(){this.permissionCache.clear(),d.info("[PermissionManager] Permission cache cleared")}cleanup(){this.permissionWatchers.forEach(e=>{e.active=!1}),this.permissionWatchers.clear(),this.requestQueue.clear(),this.permissionCache.clear(),d.info("[PermissionManager] Cleanup completed")}}class _{constructor(e={}){this.config={rpName:e.rpName||"Custom PHP Framework",rpId:e.rpId||window.location.hostname,timeout:e.timeout||6e4,userVerification:e.userVerification||"preferred",authenticatorSelection:{authenticatorAttachment:"platform",userVerification:"preferred",requireResidentKey:!1,...e.authenticatorSelection},...e},this.credentials=new Map,this.authSessions=new Map,this.support={webAuthn:"credentials"in navigator&&"create"in navigator.credentials,conditionalUI:"conditional"in window.PublicKeyCredential||!1,userVerifyingPlatformAuthenticator:!1,residentKey:!1},this.detectFeatures(),d.info("[BiometricAuthManager] Initialized with support:",this.support)}async detectFeatures(){if(this.support.webAuthn)try{const e=await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();this.support.userVerifyingPlatformAuthenticator=e,window.PublicKeyCredential.isConditionalMediationAvailable&&(this.support.conditionalUI=await window.PublicKeyCredential.isConditionalMediationAvailable()),d.info("[BiometricAuthManager] Enhanced features detected:",{platform:this.support.userVerifyingPlatformAuthenticator,conditional:this.support.conditionalUI})}catch(e){d.warn("[BiometricAuthManager] Feature detection failed:",e)}}async register(e,t={}){var n,i;if(!this.support.webAuthn)throw new Error("WebAuthn not supported");const{challenge:s=null,excludeCredentials:o=[],extensions:a={}}=t;try{const t=s?this.base64ToArrayBuffer(s):crypto.getRandomValues(new Uint8Array(32)),r={rp:{name:this.config.rpName,id:this.config.rpId},user:{id:this.stringToArrayBuffer(e.id||e.username),name:e.username||e.email,displayName:e.displayName||e.name||e.username},challenge:t,pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-35},{type:"public-key",alg:-36},{type:"public-key",alg:-257},{type:"public-key",alg:-258},{type:"public-key",alg:-259}],authenticatorSelection:this.config.authenticatorSelection,timeout:this.config.timeout,attestation:"direct",extensions:{credProps:!0,...a}};o.length>0&&(r.excludeCredentials=o.map(e=>({type:"public-key",id:"string"==typeof e?this.base64ToArrayBuffer(e):e,transports:["internal","hybrid"]}))),d.info("[BiometricAuthManager] Starting registration...");const l=await navigator.credentials.create({publicKey:r});if(!l)throw new Error("Credential creation failed");const c=this.processCredential(l,"registration"),h={id:c.id,rawId:c.rawId,userId:e.id||e.username,userDisplayName:e.displayName||e.name,createdAt:Date.now(),lastUsed:null,counter:c.response.counter||0,transports:(null==(i=(n=l.response).getTransports)?void 0:i.call(n))||["internal"]};return this.credentials.set(c.id,h),d.info("[BiometricAuthManager] Registration successful:",{id:c.id,user:e.username,authenticator:h.transports}),{success:!0,credential:c,info:h,attestation:this.parseAttestation(l.response)}}catch(r){return d.error("[BiometricAuthManager] Registration failed:",r),{success:!1,error:r.message,name:r.name}}}async authenticate(e={}){if(!this.support.webAuthn)throw new Error("WebAuthn not supported");const{challenge:t=null,allowCredentials:n=[],userVerification:i=this.config.userVerification,conditional:s=!1,extensions:o={}}=e;try{const e={challenge:t?this.base64ToArrayBuffer(t):crypto.getRandomValues(new Uint8Array(32)),timeout:this.config.timeout,userVerification:i,extensions:{credProps:!0,...o}};n.length>0&&(e.allowCredentials=n.map(e=>({type:"public-key",id:"string"==typeof e?this.base64ToArrayBuffer(e):e,transports:["internal","hybrid","usb","nfc","ble"]}))),d.info("[BiometricAuthManager] Starting authentication...",{conditional:s});const a=s&&this.support.conditionalUI?await navigator.credentials.get({publicKey:e,mediation:"conditional"}):await navigator.credentials.get({publicKey:e});if(!a)throw new Error("Authentication failed");const r=this.processCredential(a,"authentication"),l=this.credentials.get(r.id);l&&(l.lastUsed=Date.now(),l.counter=r.response.counter||0);const c=this.generateSessionId(),h={id:c,credentialId:r.id,userId:null==l?void 0:l.userId,authenticatedAt:Date.now(),userAgent:navigator.userAgent,ipAddress:await this.getClientIP().catch(()=>"unknown")};return this.authSessions.set(c,h),d.info("[BiometricAuthManager] Authentication successful:",{sessionId:c,credentialId:r.id,userId:null==l?void 0:l.userId}),{success:!0,credential:r,session:h,info:l}}catch(a){return d.error("[BiometricAuthManager] Authentication failed:",a),{success:!1,error:a.message,name:a.name}}}async isAvailable(){const e={webAuthn:this.support.webAuthn,platform:this.support.userVerifyingPlatformAuthenticator,conditional:this.support.conditionalUI,hasCredentials:this.credentials.size>0,recommended:!1};return e.recommended=e.webAuthn&&(e.platform||e.hasCredentials),e}async setupConditionalUI(e='input[type="email"], input[type="text"]',t={}){if(!this.support.conditionalUI)return d.warn("[BiometricAuthManager] Conditional UI not supported"),null;const n=document.querySelectorAll(e);if(0===n.length)return d.warn("[BiometricAuthManager] No suitable inputs found for conditional UI"),null;try{return n.forEach(e=>{e.addEventListener("focus",async()=>{var n;d.info("[BiometricAuthManager] Setting up conditional authentication");try{const i=await this.authenticate({...t,conditional:!0});if(i.success){const t=new CustomEvent("biometric-auth-success",{detail:i});e.dispatchEvent(t),(null==(n=i.info)?void 0:n.userDisplayName)&&(e.value=i.info.userDisplayName)}}catch(i){d.warn("[BiometricAuthManager] Conditional auth failed:",i)}})}),d.info("[BiometricAuthManager] Conditional UI setup complete"),{inputs:n.length,selector:e}}catch(i){return d.error("[BiometricAuthManager] Conditional UI setup failed:",i),null}}createLoginFlow(e={}){const{registerSelector:t="#register-biometric",loginSelector:n="#login-biometric",statusSelector:i="#biometric-status",onRegister:s=null,onLogin:o=null,onError:a=null}=e;return{async init(){const e=await this.isAvailable(),s=document.querySelector(i);s&&(s.innerHTML=this.createStatusHTML(e));const o=document.querySelector(t);o&&(o.style.display=e.webAuthn?"block":"none",o.onclick=()=>this.handleRegister());const a=document.querySelector(n);return a&&(a.style.display=e.hasCredentials?"block":"none",a.onclick=()=>this.handleLogin()),e.conditional&&await this.setupConditionalUI(),e},async handleRegister(){try{const e=await this.getUserInfo();if(!e)return;const t=await this.register(e);t.success?(s&&s(t),this.showSuccess("Biometric authentication registered successfully!")):(a&&a(t),this.showError(t.error))}catch(e){a&&a({error:e.message}),this.showError(e.message)}},async handleLogin(){try{const e=await this.authenticate();e.success?(o&&o(e),this.showSuccess("Biometric authentication successful!")):(a&&a(e),this.showError(e.error))}catch(e){a&&a({error:e.message}),this.showError(e.message)}},async getUserInfo(){const e=document.querySelector('input[name="username"], input[name="email"]'),t=document.querySelector('input[name="name"], input[name="display_name"]');if(null==e?void 0:e.value)return{id:e.value,username:e.value,displayName:(null==t?void 0:t.value)||e.value};const n=prompt("Please enter your username or email:");if(!n)return null;return{id:n,username:n,displayName:prompt("Please enter your display name:")||n}},createStatusHTML:e=>e.webAuthn?e.platform||e.hasCredentials?e.hasCredentials?'<div class="alert alert-success">✅ Biometric authentication available</div>':'<div class="alert alert-info">🔐 Biometric authentication can be set up</div>':'<div class="alert alert-info">ℹ️ No biometric authenticators available</div>':'<div class="alert alert-warning">⚠️ Biometric authentication not supported in this browser</div>',showSuccess(e){this.showMessage(e,"success")},showError(e){this.showMessage(e,"error")},showMessage(e,t="info"){const n=document.createElement("div");n.className=`biometric-toast toast-${t}`,n.style.cssText=`\n position: fixed;\n top: 20px;\n right: 20px;\n background: ${"error"===t?"#f44336":"success"===t?"#4caf50":"#2196f3"};\n color: white;\n padding: 1rem;\n border-radius: 4px;\n box-shadow: 0 2px 10px rgba(0,0,0,0.3);\n z-index: 10001;\n max-width: 300px;\n `,n.textContent=e,document.body.appendChild(n),setTimeout(()=>{n.parentNode&&document.body.removeChild(n)},5e3)}}}processCredential(e,t){var n,i;const s={id:this.arrayBufferToBase64(e.rawId),rawId:this.arrayBufferToBase64(e.rawId),type:e.type,response:{}};return s.response="registration"===t?{attestationObject:this.arrayBufferToBase64(e.response.attestationObject),clientDataJSON:this.arrayBufferToBase64(e.response.clientDataJSON),transports:(null==(i=(n=e.response).getTransports)?void 0:i.call(n))||[]}:{authenticatorData:this.arrayBufferToBase64(e.response.authenticatorData),clientDataJSON:this.arrayBufferToBase64(e.response.clientDataJSON),signature:this.arrayBufferToBase64(e.response.signature),userHandle:e.response.userHandle?this.arrayBufferToBase64(e.response.userHandle):null},s}parseAttestation(e){try{const t=JSON.parse(this.arrayBufferToString(e.clientDataJSON));return{format:"packed",clientData:t,origin:t.origin,challenge:t.challenge}}catch(t){return d.warn("[BiometricAuthManager] Attestation parsing failed:",t),null}}async getClientIP(){try{const e=await fetch("https://api.ipify.org?format=json");return(await e.json()).ip}catch(e){return"unknown"}}generateSessionId(){return`biometric_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}arrayBufferToBase64(e){const t=new Uint8Array(e);let n="";for(let i=0;i<t.byteLength;i++)n+=String.fromCharCode(t[i]);return btoa(n)}base64ToArrayBuffer(e){const t=atob(e),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);return n.buffer}stringToArrayBuffer(e){return(new TextEncoder).encode(e)}arrayBufferToString(e){return(new TextDecoder).decode(e)}getCredentials(){return Array.from(this.credentials.values())}getActiveSessions(){return Array.from(this.authSessions.values())}revokeCredential(e){const t=this.credentials.delete(e);return t&&d.info(`[BiometricAuthManager] Credential revoked: ${e}`),t}endSession(e){const t=this.authSessions.delete(e);return t&&d.info(`[BiometricAuthManager] Session ended: ${e}`),t}cleanupSessions(e=864e5){const t=Date.now();let n=0;for(const[i,s]of this.authSessions.entries())t-s.authenticatedAt>e&&(this.authSessions.delete(i),n++);return n>0&&d.info(`[BiometricAuthManager] Cleaned up ${n} expired sessions`),n}async getStatusReport(){return{availability:await this.isAvailable(),credentials:this.credentials.size,sessions:this.authSessions.size,support:this.support,config:{rpName:this.config.rpName,rpId:this.config.rpId,timeout:this.config.timeout},timestamp:Date.now()}}}const R={name:"api-manager",init(e={},t=null){return d.info("[APIManager] Module initialized - All Web APIs available"),this.initializeAPIManagers(e),this.exposeGlobalAPI(),this},initializeAPIManagers(e){this.observers=new A(e.observers||{}),this.media=new L(e.media||{}),this.storage=new I(e.storage||{}),this.device=new P(e.device||{}),this.animation=new $(e.animation||{}),this.worker=new D(e.worker||{}),this.performance=new O(e.performance||{}),this.permissions=new z(e.permissions||{}),this.biometric=new _(e.biometric||{}),d.info("[APIManager] All API managers initialized")},exposeGlobalAPI(){"undefined"!=typeof window&&(window.API={observers:this.observers,media:this.media,storage:this.storage,device:this.device,animation:this.animation,worker:this.worker,performance:this.performance,permissions:this.permissions,biometric:this.biometric},d.info("[APIManager] Global API exposed at window.API"))},getAPI(e){return this[e]||null},isSupported:e=>({IntersectionObserver:"IntersectionObserver"in window,ResizeObserver:"ResizeObserver"in window,MutationObserver:"MutationObserver"in window,PerformanceObserver:"PerformanceObserver"in window,MediaDevices:void 0!==navigator.mediaDevices,WebRTC:"RTCPeerConnection"in window,WebAudio:"AudioContext"in window||"webkitAudioContext"in window,MediaRecorder:"MediaRecorder"in window,IndexedDB:"indexedDB"in window,CacheAPI:"caches"in window,WebLocks:"locks"in navigator,BroadcastChannel:"BroadcastChannel"in window,Geolocation:"geolocation"in navigator,DeviceMotion:"DeviceMotionEvent"in window,DeviceOrientation:"DeviceOrientationEvent"in window,Vibration:"vibrate"in navigator,Battery:"getBattery"in navigator,NetworkInfo:"connection"in navigator,WebAnimations:"animate"in Element.prototype,VisualViewport:"visualViewport"in window,WebWorkers:"Worker"in window,ServiceWorker:"serviceWorker"in navigator,SharedWorker:"SharedWorker"in window,PerformanceAPI:"performance"in window,NavigationTiming:"getEntriesByType"in performance,Permissions:"permissions"in navigator,WebAuthn:"credentials"in navigator&&"create"in navigator.credentials}[e]||!1),getCapabilities(){const e={};return Object.keys(this.getSupportMap()).forEach(t=>{e[t]=this.isSupported(t)}),{capabilities:e,modernBrowser:this.isModernBrowser(),recommendedAPIs:this.getRecommendedAPIs(),summary:this.getCapabilitySummary(e)}},isModernBrowser(){return["IntersectionObserver","ResizeObserver","WebAnimations","IndexedDB"].every(e=>this.isSupported(e))},getRecommendedAPIs(){const e=[];return this.isSupported("IntersectionObserver")&&e.push({api:"IntersectionObserver",use:"Lazy loading, scroll triggers, viewport detection",example:"API.observers.intersection(elements, callback)"}),this.isSupported("WebAnimations")&&e.push({api:"Web Animations",use:"High-performance animations with timeline control",example:"API.animation.animate(element, keyframes, options)"}),this.isSupported("IndexedDB")&&e.push({api:"IndexedDB",use:"Client-side database for complex data",example:"API.storage.db.set(key, value)"}),this.isSupported("MediaDevices")&&e.push({api:"Media Devices",use:"Camera, microphone, screen sharing",example:"API.media.getUserCamera()"}),e},getCapabilitySummary(e){const t=Object.keys(e).length,n=Object.values(e).filter(Boolean).length,i=Math.round(n/t*100);return{total:t,supported:n,percentage:i,grade:this.getGrade(i)}},getGrade:e=>e>=90?"A+":e>=80?"A":e>=70?"B":e>=60?"C":"D",getSupportMap:()=>({IntersectionObserver:"Viewport intersection detection",ResizeObserver:"Element resize detection",MutationObserver:"DOM change detection",PerformanceObserver:"Performance metrics monitoring",MediaDevices:"Camera and microphone access",WebRTC:"Real-time communication",WebAudio:"Audio processing and synthesis",MediaRecorder:"Audio/video recording",IndexedDB:"Client-side database",CacheAPI:"HTTP cache management",WebLocks:"Resource locking",BroadcastChannel:"Cross-tab communication",Geolocation:"GPS and location services",DeviceMotion:"Accelerometer and gyroscope",DeviceOrientation:"Device orientation",Vibration:"Haptic feedback",Battery:"Battery status",NetworkInfo:"Network connection info",WebAnimations:"High-performance animations",VisualViewport:"Viewport information",WebWorkers:"Background processing",ServiceWorker:"Background sync and caching",SharedWorker:"Shared background processing",PerformanceAPI:"Performance measurement",NavigationTiming:"Navigation timing metrics",Permissions:"Browser permission management",WebAuthn:"Biometric authentication"})},F=R.init.bind(R),q=Object.freeze(Object.defineProperty({__proto__:null,default:R,init:F},Symbol.toStringTag,{value:"Module"})),N={NO_CACHE:"no-cache",CACHE_FIRST:"cache-first",NETWORK_FIRST:"network-first",STALE_WHILE_REVALIDATE:"stale-while-revalidate",NETWORK_ONLY:"network-only",CACHE_ONLY:"cache-only"};class B{constructor(e={}){this.config={defaultStrategy:e.defaultStrategy||N.STALE_WHILE_REVALIDATE,defaultTTL:e.defaultTTL||36e5,maxMemorySize:e.maxMemorySize||50,enableIndexedDB:e.enableIndexedDB??!0,indexedDBName:e.indexedDBName||"app-cache",indexedDBVersion:e.indexedDBVersion||1,enableAnalytics:e.enableAnalytics??!1,...e},this.memoryCache=new Map,this.indexedDBCache=null,this.analytics={hits:0,misses:0,sets:0,deletes:0},this.init()}static create(e={}){return new B(e)}async init(){if(this.config.enableIndexedDB&&"indexedDB"in window)try{await this.initIndexedDB()}catch(e){d.error("[CacheManager] Failed to initialize IndexedDB",e),this.config.enableIndexedDB=!1}d.info("[CacheManager] Initialized",{strategy:this.config.defaultStrategy,memoryCache:!0,indexedDB:this.config.enableIndexedDB})}async initIndexedDB(){return new Promise((e,t)=>{const n=indexedDB.open(this.config.indexedDBName,this.config.indexedDBVersion);n.onerror=()=>t(n.error),n.onsuccess=()=>{this.indexedDBCache=n.result,e()},n.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains("cache")||t.createObjectStore("cache",{keyPath:"key"})}})}async get(e,t={}){t.strategy||this.config.defaultStrategy;const n=t.ttl||this.config.defaultTTL,i=this.memoryCache.get(e);if(i&&!this.isExpired(i,n))return this.analytics.hits++,d.debug("[CacheManager] Cache hit (memory)",e),i.value;if(this.config.enableIndexedDB&&this.indexedDBCache)try{const t=await this.getFromIndexedDB(e);if(t&&!this.isExpired(t,n))return this.memoryCache.set(e,t),this.analytics.hits++,d.debug("[CacheManager] Cache hit (IndexedDB)",e),t.value}catch(s){d.error("[CacheManager] IndexedDB get error",s)}return this.analytics.misses++,d.debug("[CacheManager] Cache miss",e),null}async set(e,t,n={}){const i=n.ttl||this.config.defaultTTL,s=n.strategy||this.config.defaultStrategy,o={key:e,value:t,timestamp:Date.now(),ttl:i,strategy:s};if(this.memoryCache.set(e,o),this.memoryCache.size>this.config.maxMemorySize){const e=this.memoryCache.keys().next().value;this.memoryCache.delete(e)}if(this.config.enableIndexedDB&&this.indexedDBCache)try{await this.setInIndexedDB(o)}catch(a){d.error("[CacheManager] IndexedDB set error",a)}this.analytics.sets++,d.debug("[CacheManager] Cache set",e)}async getOrSet(e,t,n={}){const i=n.strategy||this.config.defaultStrategy;if(i!==N.NETWORK_ONLY){const t=await this.get(e,n);if(null!==t)return t}const s=await t();return i!==N.NO_CACHE&&await this.set(e,s,n),s}async delete(e){if(this.memoryCache.delete(e),this.config.enableIndexedDB&&this.indexedDBCache)try{await this.deleteFromIndexedDB(e)}catch(t){d.error("[CacheManager] IndexedDB delete error",t)}this.analytics.deletes++,d.debug("[CacheManager] Cache delete",e)}async clear(){if(this.memoryCache.clear(),this.config.enableIndexedDB&&this.indexedDBCache)try{await this.clearIndexedDB()}catch(e){d.error("[CacheManager] IndexedDB clear error",e)}d.info("[CacheManager] Cache cleared")}async invalidate(e){const t=[];for(const n of this.memoryCache.keys())this.matchesPattern(n,e)&&t.push(n);for(const n of t)await this.delete(n);d.info("[CacheManager] Invalidated cache",{pattern:e,count:t.length})}matchesPattern(e,t){return"string"==typeof t?e.includes(t):t instanceof RegExp?t.test(e):"function"==typeof t&&t(e)}isExpired(e,t){if(!e||!e.timestamp)return!0;return Date.now()-e.timestamp>(e.ttl||t)}async getFromIndexedDB(e){return new Promise((t,n)=>{const i=this.indexedDBCache.transaction(["cache"],"readonly").objectStore("cache").get(e);i.onsuccess=()=>t(i.result),i.onerror=()=>n(i.error)})}async setInIndexedDB(e){return new Promise((t,n)=>{const i=this.indexedDBCache.transaction(["cache"],"readwrite").objectStore("cache").put(e);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)})}async deleteFromIndexedDB(e){return new Promise((t,n)=>{const i=this.indexedDBCache.transaction(["cache"],"readwrite").objectStore("cache").delete(e);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)})}async clearIndexedDB(){return new Promise((e,t)=>{const n=this.indexedDBCache.transaction(["cache"],"readwrite").objectStore("cache").clear();n.onsuccess=()=>e(),n.onerror=()=>t(n.error)})}async warm(e,t){d.info("[CacheManager] Warming cache",{count:e.length});for(const i of e)try{await this.getOrSet(i,()=>t(i))}catch(n){d.error(`[CacheManager] Failed to warm cache for ${i}`,n)}}getAnalytics(){const e=this.analytics.hits+this.analytics.misses,t=e>0?this.analytics.hits/e*100:0;return{...this.analytics,total:e,hitRate:Math.round(100*t)/100,memorySize:this.memoryCache.size,memoryMaxSize:this.config.maxMemorySize}}resetAnalytics(){this.analytics={hits:0,misses:0,sets:0,deletes:0}}destroy(){this.memoryCache.clear(),this.indexedDBCache=null,d.info("[CacheManager] Destroyed")}}const H="cache-first",U="stale-while-revalidate",j="network-only",W="cache-only";const V={name:"cache-manager",cacheManager:null,init(e={},t=null){return d.info("[CacheManagerModule] Module initialized"),this.cacheManager=B.create(e),"undefined"!=typeof window&&(window.CacheManager=this.cacheManager,window.CacheStrategy=N),this},getCacheManager(){return this.cacheManager||B.create()},async get(e,t={}){const n=this.getCacheManager();return await n.get(e,t)},async set(e,t,n={}){const i=this.getCacheManager();return await i.set(e,t,n)},async getOrSet(e,t,n={}){const i=this.getCacheManager();return await i.getOrSet(e,t,n)},destroy(){this.cacheManager&&(this.cacheManager.destroy(),this.cacheManager=null),"undefined"!=typeof window&&(delete window.CacheManager,delete window.CacheStrategy),d.info("[CacheManagerModule] Module destroyed")}},G=V.init.bind(V),J=Object.freeze(Object.defineProperty({__proto__:null,CacheManager:B,CacheStrategy:N,default:V,getStrategyForUseCase:function(e){return{"api-response":U,"user-data":H,"real-time":j,"static-content":W,"computed-value":H}[e]||U},init:G},Symbol.toStringTag,{value:"Module"})),X=new Map,Q={add(e,t,n,{module:i="global",options:s=!1}={}){e.addEventListener(t,n,s),X.has(i)||X.set(i,[]),X.get(i).push([e,t,n,s])},removeModule(e){const t=X.get(e);t&&(t.forEach(([e,t,n,i])=>{e.removeEventListener(t,n,i)}),X.delete(e))},clearAll(){for(const[e,t]of X.entries())t.forEach(([e,t,n,i])=>{e.removeEventListener(t,n,i)});X.clear()},debug(){console.table([...X.entries()].map(([e,t])=>({module:e,listeners:t.length})))}};function K(e,t,n,i=import.meta,s=!1){var o;const a="string"==typeof i?i:(null==(o=i.url)?void 0:o.split("/").slice(-2,-1)[0])||"unknown";return Q.add(e,t,n,{module:a,options:s}),()=>{Q.removeModule(a)}}class Y{constructor(e,t={}){this.canvas=e,this.ctx=e.getContext("2d"),this.options={responsive:!0,pixelRatio:window.devicePixelRatio||1,...t},this.animationId=null,this.isAnimating=!1,this.init()}init(){this.setupCanvas(),this.options.responsive&&this.setupResponsive(),d.info("[CanvasManager] Initialized",{width:this.canvas.width,height:this.canvas.height,pixelRatio:this.options.pixelRatio})}setupCanvas(){this.resize(),this.canvas.style.width=this.canvas.width+"px",this.canvas.style.height=this.canvas.height+"px",this.options.pixelRatio>1&&this.ctx.scale(this.options.pixelRatio,this.options.pixelRatio)}setupResponsive(){K(window,"resize",()=>{this.resize()},"canvas-manager"),K(window,"orientationchange",()=>{setTimeout(()=>this.resize(),100)},"canvas-manager")}resize(){const e=this.canvas.parentElement,t=this.options.pixelRatio;let n,i;e&&"static"!==getComputedStyle(e).position?(n=e.clientWidth,i=e.clientHeight):(n=this.canvas.clientWidth||window.innerWidth,i=this.canvas.clientHeight||window.innerHeight),this.canvas.width=Math.floor(n*t),this.canvas.height=Math.floor(i*t),this.canvas.style.width=n+"px",this.canvas.style.height=i+"px",t>1&&this.ctx.scale(t,t),d.info("[CanvasManager] Resized",{displayWidth:n,displayHeight:i,canvasWidth:this.canvas.width,canvasHeight:this.canvas.height})}clear(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}getSize(){return{width:this.canvas.clientWidth,height:this.canvas.clientHeight,pixelWidth:this.canvas.width,pixelHeight:this.canvas.height}}getMousePosition(e){const t=this.canvas.getBoundingClientRect();return{x:(e.clientX-t.left)*this.options.pixelRatio,y:(e.clientY-t.top)*this.options.pixelRatio}}startAnimation(e){this.isAnimating&&this.stopAnimation(),this.isAnimating=!0;const t=n=>{this.isAnimating&&(e(n),this.animationId=requestAnimationFrame(t))};this.animationId=requestAnimationFrame(t),d.info("[CanvasManager] Animation started")}stopAnimation(){this.animationId&&(cancelAnimationFrame(this.animationId),this.animationId=null),this.isAnimating=!1,d.info("[CanvasManager] Animation stopped")}destroy(){this.stopAnimation(),d.info("[CanvasManager] Destroyed")}}const Z={initParallax(e,t){const n=new Y(e),i=this.createParallaxElements(e,t);let s=!1;const o=()=>{s||(requestAnimationFrame(()=>{this.renderParallax(n,i,t),s=!1}),s=!0)};K(window,"scroll",o,"scroll-parallax"),K(window,"resize",o,"scroll-parallax"),o(),d.info("[ScrollEffects] Parallax initialized with",i.length,"elements")},createParallaxElements(e,t){const n=[],i=t.layers||3,s=t.elements||20;for(let o=0;o<s;o++)n.push({x:Math.random()*e.clientWidth,y:Math.random()*e.clientHeight*2,size:20*Math.random()+5,layer:Math.floor(Math.random()*i),speed:.1+.5*Math.random(),opacity:.7*Math.random()+.3,color:this.getLayerColor(Math.floor(Math.random()*i),t)});return n},getLayerColor(e,t){const n=t.colors||["rgba(100, 150, 255, 0.6)","rgba(150, 100, 255, 0.4)","rgba(200, 100, 150, 0.2)"];return n[e]||n[0]},renderParallax(e,t,n){e.clear();const i=window.pageYOffset,s=(i-(e.canvas.getBoundingClientRect().top+i))/window.innerHeight;t.forEach(t=>{const n=s*t.speed*100,i=t.y-n;i>-t.size&&i<e.canvas.clientHeight+t.size&&(e.ctx.save(),e.ctx.globalAlpha=t.opacity,e.ctx.fillStyle=t.color,e.ctx.beginPath(),e.ctx.arc(t.x,i,t.size,0,2*Math.PI),e.ctx.fill(),e.ctx.restore())})},initScrollAnimation(e,t){const n=new Y(e),i=t.animation||"wave";let s=!1;const o=()=>{s||(requestAnimationFrame(()=>{this.renderScrollAnimation(n,i,t),s=!1}),s=!0)};K(window,"scroll",o,"scroll-animation"),K(window,"resize",o,"scroll-animation"),o(),d.info("[ScrollEffects] Scroll animation initialized:",i)},renderScrollAnimation(e,t,n){e.clear();const i=window.pageYOffset,s=i-(e.canvas.getBoundingClientRect().top+i),o=Math.max(0,Math.min(1,s/window.innerHeight));switch(t){case"wave":default:this.renderWaveAnimation(e,o,n);break;case"progress":this.renderProgressAnimation(e,o,n);break;case"morph":this.renderMorphAnimation(e,o,n)}},renderWaveAnimation(e,t,n){const{ctx:i}=e,{width:s,height:o}=e.getSize();i.strokeStyle=n.color||"rgba(100, 150, 255, 0.8)",i.lineWidth=n.lineWidth||3,i.beginPath();const a=(n.amplitude||50)*t,r=n.frequency||.02,l=t*Math.PI*2;for(let c=0;c<=s;c+=2){const e=o/2+Math.sin(c*r+l)*a;0===c?i.moveTo(c,e):i.lineTo(c,e)}i.stroke()},renderProgressAnimation(e,t,n){const{ctx:i}=e,{width:s,height:o}=e.getSize(),a=n.barHeight||10,r=o/2-a/2;i.fillStyle=n.backgroundColor||"rgba(255, 255, 255, 0.2)",i.fillRect(0,r,s,a),i.fillStyle=n.color||"rgba(100, 150, 255, 0.8)",i.fillRect(0,r,s*t,a)},renderMorphAnimation(e,t,n){const{ctx:i}=e,{width:s,height:o}=e.getSize();i.fillStyle=n.color||"rgba(100, 150, 255, 0.6)";const a=s/2,r=o/2,l=Math.min(s,o)/3;i.beginPath();const c=n.points||6;for(let d=0;d<=c;d++){const e=d/c*Math.PI*2,n=l*t*(.3*Math.sin(t*Math.PI*4+3*e)+1),s=a+Math.cos(e)*n,o=r+Math.sin(e)*n;0===d?i.moveTo(s,o):i.lineTo(s,o)}i.closePath(),i.fill()}},ee={init(e,t){const n=new Y(e),i=t.effect||"ripple",s={mouse:{x:0,y:0,isOver:!1},effects:[],lastTime:0};this.setupInteractionEvents(e,n,s,t),this.startAnimationLoop(n,s,i,t),d.info("[InteractiveEffects] Initialized with effect:",i)},setupInteractionEvents(e,t,n,i){K(e,"mousemove",e=>{const s=t.getMousePosition(e);n.mouse.x=s.x,n.mouse.y=s.y,"trail"===i.effect&&this.addTrailPoint(n,s.x,s.y)},"interactive-effects"),K(e,"mouseenter",()=>{n.mouse.isOver=!0},"interactive-effects"),K(e,"mouseleave",()=>{n.mouse.isOver=!1},"interactive-effects"),K(e,"click",e=>{const s=t.getMousePosition(e);this.addClickEffect(n,s.x,s.y,i)},"interactive-effects"),K(e,"touchstart",e=>{e.preventDefault();const s=e.touches[0],o=t.getMousePosition(s);this.addClickEffect(n,o.x,o.y,i)},"interactive-effects"),K(e,"touchmove",e=>{e.preventDefault();const s=e.touches[0],o=t.getMousePosition(s);n.mouse.x=o.x,n.mouse.y=o.y,n.mouse.isOver=!0,"trail"===i.effect&&this.addTrailPoint(n,o.x,o.y)},"interactive-effects"),K(e,"touchend",()=>{n.mouse.isOver=!1},"interactive-effects")},startAnimationLoop(e,t,n,i){const s=o=>{const a=o-t.lastTime;switch(t.lastTime=o,e.clear(),n){case"ripple":default:this.renderRippleEffect(e,t,i);break;case"trail":this.renderTrailEffect(e,t,i);break;case"particles":this.renderParticleEffect(e,t,i,a);break;case"magnetic":this.renderMagneticEffect(e,t,i)}this.updateEffects(t.effects,a),requestAnimationFrame(s)};requestAnimationFrame(s)},addClickEffect(e,t,n,i){const s={x:t,y:n,age:0,maxAge:i.duration||1e3,type:"click",intensity:i.intensity||1};e.effects.push(s)},addTrailPoint(e,t,n){const i={x:t,y:n,age:0,maxAge:500,type:"trail"};e.effects.push(i);const s=e.effects.filter(e=>"trail"===e.type);if(s.length>20){const t=e.effects.indexOf(s[0]);e.effects.splice(t,1)}},renderRippleEffect(e,t,n){const{ctx:i}=e;t.effects.forEach(t=>{if("click"===t.type){const s=t.age/t.maxAge,o=s*(n.maxRadius||100),a=.8*(1-s);i.save(),i.globalAlpha=a,i.strokeStyle=n.color||"rgba(100, 150, 255, 1)",i.lineWidth=n.lineWidth||3,i.beginPath(),i.arc(t.x/e.options.pixelRatio,t.y/e.options.pixelRatio,o,0,2*Math.PI),i.stroke(),i.restore()}}),t.mouse.isOver&&(i.save(),i.globalAlpha=.3,i.fillStyle=n.hoverColor||"rgba(100, 150, 255, 0.3)",i.beginPath(),i.arc(t.mouse.x/e.options.pixelRatio,t.mouse.y/e.options.pixelRatio,n.hoverRadius||30,0,2*Math.PI),i.fill(),i.restore())},renderTrailEffect(e,t,n){const{ctx:i}=e,s=t.effects.filter(e=>"trail"===e.type);s.length<2||(i.save(),i.strokeStyle=n.color||"rgba(100, 150, 255, 0.8)",i.lineWidth=n.lineWidth||5,i.lineCap="round",i.lineJoin="round",i.beginPath(),s.forEach((t,n)=>{const s=1-t.age/t.maxAge,o=t.x/e.options.pixelRatio,a=t.y/e.options.pixelRatio;i.globalAlpha=.8*s,0===n?i.moveTo(o,a):i.lineTo(o,a)}),i.stroke(),i.restore())},renderParticleEffect(e,t,n,i){const{ctx:s}=e;if(t.mouse.isOver&&Math.random()<.1){const e={x:t.mouse.x,y:t.mouse.y,vx:4*(Math.random()-.5),vy:4*(Math.random()-.5),age:0,maxAge:1e3,size:5*Math.random()+2,type:"particle"};t.effects.push(e)}t.effects.forEach(t=>{if("particle"===t.type){t.x+=t.vx,t.y+=t.vy,t.vy+=.1;const i=t.age/t.maxAge,o=.8*(1-i);s.save(),s.globalAlpha=o,s.fillStyle=n.color||"rgba(100, 150, 255, 1)",s.beginPath(),s.arc(t.x/e.options.pixelRatio,t.y/e.options.pixelRatio,t.size*(1-.5*i),0,2*Math.PI),s.fill(),s.restore()}})},renderMagneticEffect(e,t,n){const{ctx:i}=e,{width:s,height:o}=e.getSize();if(!t.mouse.isOver)return;const a=s/2,r=o/2,l=t.mouse.x/e.options.pixelRatio,c=t.mouse.y/e.options.pixelRatio;i.save(),i.strokeStyle=n.color||"rgba(100, 150, 255, 0.6)",i.lineWidth=2;for(let d=0;d<8;d++){const e=d/8*Math.PI*2,t=a+50*Math.cos(e),n=r+50*Math.sin(e),s=(t+l)/2+30*Math.sin(e),o=(n+c)/2+30*Math.cos(e);i.beginPath(),i.moveTo(t,n),i.quadraticCurveTo(s,o,l,c),i.stroke()}i.restore()},updateEffects(e,t){for(let n=e.length-1;n>=0;n--)e[n].age+=t,e[n].age>=e[n].maxAge&&e.splice(n,1)}},te={init(e,t){const n=new Y(e),i=t.type||"bar",s=this.parseData(e,t);if(s&&0!==s.length){switch(i){case"bar":default:this.createBarChart(n,s,t);break;case"line":this.createLineChart(n,s,t);break;case"pie":this.createPieChart(n,s,t);break;case"progress":this.createProgressChart(n,s,t)}d.info("[DataVisualization] Initialized",i,"chart with",s.length,"data points")}else d.warn("[DataVisualization] No data provided for canvas")},parseData(e,t){let n=t.data;if(!n&&e.dataset.canvasData)try{n=JSON.parse(e.dataset.canvasData)}catch(i){d.warn("[DataVisualization] Failed to parse canvas data",i)}if(!n){const t=e.nextElementSibling;if(t&&"SCRIPT"===t.tagName&&"application/json"===t.type)try{n=JSON.parse(t.textContent)}catch(i){d.warn("[DataVisualization] Failed to parse script data",i)}}if(!n)return d.warn("[DataVisualization] No data found"),[];if(!Array.isArray(n))if("number"==typeof n)n=[{value:n,label:"Progress"}];else{if("object"!=typeof n)return d.warn("[DataVisualization] Data format not recognized:",n),[];n=Object.entries(n).map(([e,t])=>({label:e,value:"object"==typeof t&&t.value||t}))}return n},createBarChart(e,t,n){const{ctx:i}=e,{width:s,height:o}=e.getSize(),a=n.padding||40,r=s-2*a,l=o-2*a,c=r/t.length*.8,d=r/t.length*.2,h=Math.max(...t.map(e=>e.value));let u=0;const p=n.animationDuration||2e3;let m=null;const g=i=>{m||(m=i);const s=i-m;u=Math.min(s/p,1);const o=1-Math.pow(1-u,3);e.clear(),this.renderBarChart(e,t,n,o,{padding:a,chartWidth:r,chartHeight:l,barWidth:c,barSpacing:d,maxValue:h}),u<1&&requestAnimationFrame(g)};requestAnimationFrame(g)},renderBarChart(e,t,n,i,s){const{ctx:o}=e,{padding:a,chartHeight:r,barWidth:l,barSpacing:c,maxValue:d}=s;t.forEach((e,t)=>{const s=a+t*(l+c),h=e.value/d*r*i,u=a+r-h;o.fillStyle=e.color||n.barColor||"rgba(100, 150, 255, 0.8)",o.fillRect(s,u,l,h),!1!==n.showLabels&&(o.fillStyle=n.textColor||"#333",o.font=n.font||"12px Arial",o.textAlign="center",o.fillText(e.label,s+l/2,a+r+20),!1!==n.showValues&&o.fillText(Math.round(e.value*i),s+l/2,u-5))}),!1!==n.showAxes&&(o.strokeStyle=n.axisColor||"#ccc",o.lineWidth=1,o.beginPath(),o.moveTo(a,a),o.lineTo(a,a+r),o.stroke(),o.beginPath(),o.moveTo(a,a+r),o.lineTo(a+s.chartWidth,a+r),o.stroke())},createLineChart(e,t,n){const{ctx:i}=e,{width:s,height:o}=e.getSize(),a=n.padding||40,r=s-2*a,l=o-2*a,c=Math.max(...t.map(e=>e.value)),d=Math.min(...t.map(e=>e.value)),h=c-d;let u=0;const p=n.animationDuration||2e3;let m=null;const g=i=>{m||(m=i);const s=i-m;u=Math.min(s/p,1),e.clear(),this.renderLineChart(e,t,n,u,{padding:a,chartWidth:r,chartHeight:l,maxValue:c,minValue:d,valueRange:h}),u<1&&requestAnimationFrame(g)};requestAnimationFrame(g)},renderLineChart(e,t,n,i,s){const{ctx:o}=e,{padding:a,chartWidth:r,chartHeight:l,minValue:c,valueRange:d}=s,h=Math.floor(t.length*i);o.strokeStyle=n.lineColor||"rgba(100, 150, 255, 0.8)",o.lineWidth=n.lineWidth||3,o.lineCap="round",o.lineJoin="round",o.beginPath();for(let u=0;u<=h&&u<t.length;u++){const e=a+u/(t.length-1)*r,n=a+l-(t[u].value-c)/d*l;0===u?o.moveTo(e,n):o.lineTo(e,n)}if(o.stroke(),!1!==n.showPoints){o.fillStyle=n.pointColor||n.lineColor||"rgba(100, 150, 255, 0.8)";for(let e=0;e<=h&&e<t.length;e++){const i=a+e/(t.length-1)*r,s=a+l-(t[e].value-c)/d*l;o.beginPath(),o.arc(i,s,n.pointSize||4,0,2*Math.PI),o.fill(),!1!==n.showLabels&&t[e].label&&(o.fillStyle=n.textColor||"#333",o.font=n.font||"12px Arial",o.textAlign="center",o.fillText(t[e].label,i,a+l+20))}}},createPieChart(e,t,n){const{ctx:i}=e,{width:s,height:o}=e.getSize(),a=s/2,r=o/2,l=Math.min(s,o)/2*.8,c=t.reduce((e,t)=>e+t.value,0);let d=0;const h=n.animationDuration||2e3;let u=null;const p=i=>{u||(u=i);const s=i-u;d=Math.min(s/h,1),e.clear(),this.renderPieChart(e,t,n,d,{centerX:a,centerY:r,radius:l,total:c}),d<1&&requestAnimationFrame(p)};requestAnimationFrame(p)},renderPieChart(e,t,n,i,s){const{ctx:o}=e,{centerX:a,centerY:r,radius:l,total:c}=s;let d=-Math.PI/2;const h=d+2*Math.PI*i;for(let u=0;u<t.length&&!(d>=h);u++){const e=t[u],i=e.value/c*Math.PI*2,s=Math.min(d+i,h);if(s>d&&(o.fillStyle=e.color||this.getDefaultColor(u),o.beginPath(),o.moveTo(a,r),o.arc(a,r,l,d,s),o.closePath(),o.fill(),!1!==n.showLabels&&s===d+i)){const t=d+i/2,s=a+Math.cos(t)*l*.7,c=r+Math.sin(t)*l*.7;o.fillStyle=n.textColor||"#333",o.font=n.font||"12px Arial",o.textAlign="center",o.fillText(e.label,s,c)}d+=i}},createProgressChart(e,t,n){const{ctx:i}=e,{width:s,height:o}=e.getSize();let a=0;const r=n.animationDuration||1500;let l=null;const c=i=>{l||(l=i);const s=i-l;a=Math.min(s/r,1),e.clear(),this.renderProgressChart(e,t,n,a),a<1&&requestAnimationFrame(c)};requestAnimationFrame(c)},renderProgressChart(e,t,n,i){var s;const{ctx:o}=e,{width:a,height:r}=e.getSize(),l=a/2,c=r/2,d=Math.min(a,r)/2*.8,h=n.lineWidth||20,u=(null==(s=t[0])?void 0:s.value)||0,p=n.maxValue||100,m=u/p*i;o.strokeStyle=n.backgroundColor||"rgba(200, 200, 200, 0.3)",o.lineWidth=h,o.beginPath(),o.arc(l,c,d,0,2*Math.PI),o.stroke(),o.strokeStyle=n.color||"rgba(100, 150, 255, 0.8)",o.lineCap="round",o.beginPath(),o.arc(l,c,d,-Math.PI/2,-Math.PI/2+m/p*Math.PI*2),o.stroke(),!1!==n.showText&&(o.fillStyle=n.textColor||"#333",o.font=n.font||"bold 24px Arial",o.textAlign="center",o.textBaseline="middle",o.fillText(Math.round(m)+"%",l,c))},getDefaultColor(e){const t=["rgba(100, 150, 255, 0.8)","rgba(255, 100, 150, 0.8)","rgba(150, 255, 100, 0.8)","rgba(255, 200, 100, 0.8)","rgba(200, 100, 255, 0.8)","rgba(100, 255, 200, 0.8)"];return t[e%t.length]}},ne={name:"canvas-animations",init(e={},t=null){return d.info("[CanvasAnimations] Module initialized"),this.initializeCanvasElements(),this},initializeCanvasElements(){const e=document.querySelectorAll("canvas[data-canvas-type]");e.forEach(e=>{this.initElement(e)}),d.info(`[CanvasAnimations] Initialized ${e.length} canvas elements`)},initElement(e,t={}){const n=e.dataset.canvasType,i=this.parseCanvasConfig(e);switch(d.info(`[CanvasAnimations] Initializing canvas type: ${n}`),n){case"interactive":ee.init(e,i);break;case"scroll-parallax":Z.initParallax(e,i);break;case"scroll-animation":Z.initScrollAnimation(e,i);break;case"data-viz":te.init(e,i);break;case"background":this.initBackgroundAnimation(e,i);break;default:d.warn(`[CanvasAnimations] Unknown canvas type: ${n}`)}},parseCanvasConfig(e){const t={};return Object.keys(e.dataset).forEach(n=>{if(n.startsWith("canvas")){const s=n.replace("canvas","").toLowerCase();let o=e.dataset[n];if(o.startsWith("{")&&o.endsWith("}")||o.startsWith("[")&&o.endsWith("]"))try{o=JSON.parse(o)}catch(i){d.warn(`[CanvasAnimations] Failed to parse JSON config: ${n}`,i)}else"true"===o?o=!0:"false"===o?o=!1:isNaN(o)||""===o||(o=parseFloat(o));t[s]=o}}),t},initBackgroundAnimation(e,t){const n=new Y(e),i=t.particles||50,s=[];for(let o=0;o<i;o++)s.push({x:Math.random()*e.width,y:Math.random()*e.height,vx:.5*(Math.random()-.5),vy:.5*(Math.random()-.5),size:3*Math.random()+1,opacity:.5*Math.random()+.2});!function i(){n.clear(),n.ctx.fillStyle=t.color||"rgba(100, 150, 255, 0.6)",s.forEach(t=>{t.x+=t.vx,t.y+=t.vy,t.x<0&&(t.x=e.width),t.x>e.width&&(t.x=0),t.y<0&&(t.y=e.height),t.y>e.height&&(t.y=0),n.ctx.save(),n.ctx.globalAlpha=t.opacity,n.ctx.beginPath(),n.ctx.arc(t.x,t.y,t.size,0,2*Math.PI),n.ctx.fill(),n.ctx.restore()}),requestAnimationFrame(i)}()}},ie=ne.init.bind(ne),se=Object.freeze(Object.defineProperty({__proto__:null,default:ne,init:ie},Symbol.toStringTag,{value:"Module"}));class oe{constructor(e,t={}){this.containerSelector=e,this.container=null,this.options={csrfTokenSelector:t.csrfTokenSelector||"[data-live-component]",toastHandler:t.toastHandler||null,confirmationHandler:t.confirmationHandler||null,loadingTexts:t.loadingTexts||{},autoRefresh:!1!==t.autoRefresh,refreshHandler:t.refreshHandler||null,...t},this.handlers=new Map,this.init()}init(){"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>this.setupEventDelegation()):this.setupEventDelegation()}setupEventDelegation(){this.container=document.querySelector(this.containerSelector),this.container?this.container.addEventListener("click",e=>{const t=e.target.closest("[data-action]");if(!t)return;const n=t.dataset.action;n&&(e.preventDefault(),this.handleAction(n,t))}):console.warn(`[ActionHandler] Container not found: ${this.containerSelector}`)}registerHandler(e,t){this.handlers.set(e,t)}async handleAction(e,t){var n,i,s;const o=t.dataset.actionHandler||"default",a=this.handlers.get(o),r=this.getActionConfig(e,t,a);if(!r.url&&(null==a?void 0:a.urlTemplate)&&(r.url=a.urlTemplate),!r.url)return void console.warn(`[ActionHandler] No URL found for action: ${e}`,{element:t,handlerName:o,config:r});if(r.confirm){if(!(await this.showConfirmation(r.confirm)))return}const l=r.loadingText||this.options.loadingTexts[e]||"Processing...";this.showLoading(t,l);try{let o=this.processUrlTemplate(r.url,t);if("window"===r.type)return o.startsWith("http://")||o.startsWith("https://")||(o=`${window.location.origin}${o}`),window.open(o,r.windowTarget||"_blank"),void this.resetLoading(t);if("inline"===r.type){const e=t.dataset.actionParamId,i=document.querySelector(`[data-logs-container="${e}"]`),s=null==i?void 0:i.querySelector(`[data-logs-content="${e}"]`);if(!i||!s)return console.warn(`[ActionHandler] Logs row not found for container: ${e}`),void this.resetLoading(t);if("none"!==i.style.display){i.style.display="none";const e=t.querySelector(".logs-icon");return e&&(e.textContent="📋"),t.classList.remove("active"),void this.resetLoading(t)}i.style.display="";const a=t.querySelector(".logs-icon");if(a&&(a.textContent="📖"),t.classList.add("active"),"true"===s.dataset.loaded)return void this.resetLoading(t);o.startsWith("http://")||o.startsWith("https://")||(o=`${window.location.origin}${o}`);try{const e=await fetch(o,{method:"GET",headers:{Accept:"application/json",...r.headers}});if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);const i=await e.json();this.resetLoading(t),i.success&&(null==(n=i.data)?void 0:n.logs)?(s.innerHTML=`<pre class="docker-logs"><code>${this.escapeHtml(i.data.logs)}</code></pre>`,s.dataset.loaded="true"):s.innerHTML='<div class="alert alert-error">Failed to load logs</div>'}catch(c){this.resetLoading(t),s.innerHTML=`<div class="alert alert-error">Error loading logs: ${this.escapeHtml(c.message)}</div>`}return}const{token:l,formId:d}=this.getCsrfToken(t),h=await fetch(o,{method:r.method||"POST",headers:{"Content-Type":"application/json","X-CSRF-Token":l,...r.headers},body:JSON.stringify({_form_id:d,_token:l,...r.body})}),u=await h.json();if(!1!==u.success){const t=r.successToast||r.successMessage||(null==(i=null==a?void 0:a.successMessages)?void 0:i[e])||`Action ${e} completed successfully`;this.showToast(t,"success"),this.options.autoRefresh&&!1!==r.autoRefresh&&this.refresh()}else{const n=r.errorToast||r.errorMessage||(null==(s=null==a?void 0:a.errorMessages)?void 0:s[e])||u.message||`Failed to ${e}`;this.showToast(n,"error"),this.resetLoading(t)}}catch(c){this.handleError(c,t,r)}}getActionConfig(e,t,n){var i,s,o,a;const r={action:e,url:t.dataset.actionUrl,handler:t.dataset.actionHandler,method:t.dataset.actionMethod||"POST",confirm:t.dataset.actionConfirm,loadingText:t.dataset.actionLoadingText,successToast:t.dataset.actionSuccessToast,errorToast:t.dataset.actionErrorToast,type:t.dataset.actionType,windowTarget:t.dataset.actionWindowTarget,autoRefresh:"false"!==t.dataset.actionAutoRefresh,headers:{},body:{}};return n&&(!r.url&&n.urlTemplate&&(r.url=n.urlTemplate),(null==(i=n.confirmations)?void 0:i[e])&&(r.confirm=r.confirm||n.confirmations[e]),(null==(s=n.loadingTexts)?void 0:s[e])&&(r.loadingText=r.loadingText||n.loadingTexts[e]),(null==(o=n.successMessages)?void 0:o[e])&&(r.successToast=r.successToast||n.successMessages[e]),(null==(a=n.errorMessages)?void 0:a[e])&&(r.errorToast=r.errorToast||n.errorMessages[e])),Object.keys(t.dataset).forEach(e=>{if(e.startsWith("actionParam")){const n=e.replace(/^actionParam/,"").replace(/([A-Z])/g,"-$1").toLowerCase();r.body[n]=t.dataset[e]}}),r}processUrlTemplate(e,t){if(!e)return e;if((e=e.replace("{action}",t.dataset.action||"")).includes("{id}")){const n=t.dataset.actionParamId||t.dataset.containerId||t.dataset.id||t.dataset.actionId||t.getAttribute("data-action-param-id");n?e=e.replace(/\{id\}/g,n):console.warn(`[ActionHandler] Missing ID for URL template: ${e}`,t)}return e=(e=e.replace(/\{param:(\w+)\}/g,(e,n)=>{const i=`actionParam${n.charAt(0).toUpperCase()+n.slice(1)}`;return t.dataset[i]||t.dataset[`actionParam${n}`]||t.dataset[n]||t.getAttribute(`data-action-param-${n}`)||e})).replace(/\{data:(\w+)\}/g,(e,n)=>{const i=n.replace(/-([a-z])/g,e=>e[1].toUpperCase());return t.dataset[i]||t.dataset[n]||t.getAttribute(`data-${n}`)||e})}getCsrfToken(e){var t;if(e.dataset.csrfToken)return{token:e.dataset.csrfToken,formId:this.getFormId(e)};const n=e.closest(this.options.csrfTokenSelector);if(null==n?void 0:n.dataset.csrfToken)return{token:n.dataset.csrfToken,formId:n.dataset.liveComponent?`livecomponent:${n.dataset.liveComponent}`:this.getFormId(e)};if(null==(t=this.container)?void 0:t.dataset.csrfToken)return{token:this.container.dataset.csrfToken,formId:this.getFormId(e)};const i=document.querySelector('meta[name="csrf-token"]');return i?{token:i.content,formId:this.getFormId(e)}:{token:"",formId:this.getFormId(e)}}getFormId(e){const t=e.closest("[data-live-component]");if(null==t?void 0:t.dataset.liveComponent)return`livecomponent:${t.dataset.liveComponent}`;const n=e.dataset.actionUrl;if(n){return`action:${n.split("?")[0]}`}return`action:${e.dataset.action}`}showLoading(e,t){e.dataset.originalText=e.textContent,e.disabled=!0,e.textContent=t,e.style.opacity="0.6",e.style.cursor="not-allowed",e.classList.add("action-loading")}resetLoading(e){e.disabled=!1,e.textContent=e.dataset.originalText||e.textContent,e.style.opacity="1",e.style.cursor="pointer",e.classList.remove("action-loading")}async showConfirmation(e){return this.options.confirmationHandler?await this.options.confirmationHandler(e):confirm(e)}showToast(e,t="info"){if(this.options.toastHandler)this.options.toastHandler(e,t);else{if(window.LiveComponentUIHelper){const n=document.querySelector(this.options.csrfTokenSelector),i=(null==n?void 0:n.dataset.liveComponent)||"global";return void window.LiveComponentUIHelper.showNotification(i,{message:e,type:t,duration:5e3})}"function"!=typeof window.showToast?"error"===t?alert(`Error: ${e}`):console.log(`[${t.toUpperCase()}] ${e}`):window.showToast(e,t)}}refresh(){if(this.options.refreshHandler)return void this.options.refreshHandler();const e=document.querySelector(this.options.csrfTokenSelector);if(null==e?void 0:e.dataset.liveComponent){const t=e.dataset.liveComponent;if(window.LiveComponent&&"function"==typeof window.LiveComponent.refresh)return void window.LiveComponent.refresh(t)}setTimeout(()=>window.location.reload(),1e3)}handleError(e,t,n){console.error("[ActionHandler] Error:",e);const i=n.errorToast||n.errorMessage||`Error: ${e.message}`;this.showToast(i,"error"),this.resetLoading(t)}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}}const ae={urlTemplate:"/admin/infrastructure/docker/api/containers/{id}/{action}",method:"POST",confirmations:{stop:"Are you sure you want to stop this container?",restart:"Are you sure you want to restart this container?"},loadingTexts:{start:"Starting...",stop:"Stopping...",restart:"Restarting...",reload:"Reloading...",logs:"Loading logs..."},successMessages:{start:"Container started successfully",stop:"Container stopped successfully",restart:"Container restarted successfully",reload:"Container reloaded successfully"},errorMessages:{start:"Failed to start container",stop:"Failed to stop container",restart:"Failed to restart container",reload:"Failed to reload container"}},re={urlTemplate:"/api/{entity}/{id}/{action}",method:"POST",confirmations:{delete:"Are you sure you want to delete this item?"},loadingTexts:{delete:"Deleting...",update:"Updating...",create:"Creating..."},successMessages:{delete:"Item deleted successfully",update:"Item updated successfully",create:"Item created successfully"},errorMessages:{delete:"Failed to delete item",update:"Failed to update item",create:"Failed to create item"}},le={urlTemplate:"/admin/api/{entity}/bulk/{action}",method:"POST",confirmations:{delete:"Are you sure you want to delete the selected items?",publish:"Are you sure you want to publish the selected items?",unpublish:"Are you sure you want to unpublish the selected items?"},loadingTexts:{delete:"Deleting...",publish:"Publishing...",unpublish:"Unpublishing...",tag:"Tagging..."},successMessages:{delete:"Items deleted successfully",publish:"Items published successfully",unpublish:"Items unpublished successfully",tag:"Items tagged successfully"},errorMessages:{delete:"Failed to delete items",publish:"Failed to publish items",unpublish:"Failed to unpublish items",tag:"Failed to tag items"}},ce={method:"POST",loadingTexts:{default:"Processing..."}};"undefined"!=typeof window&&(window.ActionHandler=oe,window.ActionHandlers={dockerContainer:ae,genericApi:re,bulkOperations:le,default:ce});const de=Object.freeze(Object.defineProperty({__proto__:null,ActionHandler:oe,bulkOperationsHandler:le,defaultHandler:ce,definition:{name:"common",version:"1.0.0",dependencies:[],provides:["ActionHandler"],priority:0},dockerContainerHandler:ae,genericApiHandler:re,init:async function(e={},t={}){return console.log("[Common] Module initialized"),document.addEventListener("DOMContentLoaded",()=>{document.querySelectorAll("[data-action-handler-container]").forEach(e=>{const t=e.dataset.actionHandlerContainer||e.className.split(" ")[0],n=e.dataset.actionHandler||"default",i=new oe(t,{csrfTokenSelector:"[data-live-component]",autoRefresh:!0});window.ActionHandlers[n]&&i.registerHandler(n,window.ActionHandlers[n]),e.actionHandler=i})}),{ActionHandler:oe,handlers:{dockerContainer:ae,genericApi:re,bulkOperations:le,default:ce},state:t}},initElement:function(e,t={}){var n;if(e.hasAttribute("data-action-handler-container")){const i=e.dataset.actionHandlerContainer||`.${e.className.split(" ")[0]}`,s=e.dataset.actionHandler||"default",o=new oe(i,{csrfTokenSelector:"[data-live-component]",autoRefresh:!0,...t});return(null==(n=window.ActionHandlers)?void 0:n[s])&&o.registerHandler(s,window.ActionHandlers[s]),e.actionHandler=o,o}return null}},Symbol.toStringTag,{value:"Module"}));class he{constructor(e={}){this.config={endpoint:e.endpoint||"/api/errors",enabled:e.enabled??!0,sampleRate:e.sampleRate??1,maxErrors:e.maxErrors||100,groupingWindow:e.groupingWindow||6e4,includeStack:e.includeStack??!0,includeContext:e.includeContext??!0,includeUserAgent:e.includeUserAgent??!0,includeUrl:e.includeUrl??!0,filters:e.filters||[],beforeSend:e.beforeSend||null,...e},this.errors=[],this.errorGroups=new Map,this.reportQueue=[],this.isReporting=!1,this.config.enabled&&this.init(),d.info("[ErrorTracker] Initialized",{enabled:this.config.enabled,endpoint:this.config.endpoint,sampleRate:this.config.sampleRate})}static create(e={}){return new he(e)}init(){window.addEventListener("error",e=>{this.captureException(e.error||new Error(e.message),{type:"unhandled",filename:e.filename,lineno:e.lineno,colno:e.colno})}),window.addEventListener("unhandledrejection",e=>{this.captureException(e.reason,{type:"unhandledrejection"})}),this.startReporting()}captureException(e,t={}){if(!this.config.enabled)return;if(Math.random()>this.config.sampleRate)return void d.debug("[ErrorTracker] Error sampled out");if(this.shouldFilter(e,t))return void d.debug("[ErrorTracker] Error filtered out");const n=this.createErrorData(e,t);if(this.config.beforeSend){const e=this.config.beforeSend(n);if(null===e||!1===e)return;e&&Object.assign(n,e)}this.errors.push(n),this.errors.length>this.config.maxErrors&&this.errors.shift(),this.groupError(n),this.reportQueue.push(n),d.debug("[ErrorTracker] Error captured",n),this.triggerErrorEvent(n)}createErrorData(e,t={}){const n={message:(null==e?void 0:e.message)||String(e),name:(null==e?void 0:e.name)||"Error",stack:this.config.includeStack?this.getStackTrace(e):void 0,timestamp:Date.now(),type:t.type||"error",context:this.config.includeContext?{...t,userAgent:this.config.includeUserAgent?navigator.userAgent:void 0,url:this.config.includeUrl?window.location.href:void 0,referrer:document.referrer||void 0,viewport:{width:window.innerWidth,height:window.innerHeight}}:t};return e&&"object"==typeof e&&Object.keys(e).forEach(t=>{["message","name","stack"].includes(t)||(n[t]=e[t])}),n}getStackTrace(e){if(null==e?void 0:e.stack)return e.stack;try{throw new Error}catch(t){return t.stack||"No stack trace available"}}generateFingerprint(e){const t=e.message||"",n=(e.stack||"").split("\n").slice(0,3).join("\n");return`${e.name}:${t}:${n}`}groupError(e){const t=this.generateFingerprint(e),n=Date.now();this.errorGroups.has(t)||this.errorGroups.set(t,{fingerprint:t,count:0,firstSeen:n,lastSeen:n,errors:[]});const i=this.errorGroups.get(t);i.count++,i.lastSeen=n,i.errors.push(e),i.errors.length>10&&i.errors.shift(),this.cleanupGroups(n)}cleanupGroups(e){const t=e-this.config.groupingWindow;for(const[n,i]of this.errorGroups.entries())i.lastSeen<t&&this.errorGroups.delete(n)}shouldFilter(e,t){for(const n of this.config.filters)if("function"==typeof n){if(!1===n(e,t))return!0}else if(n instanceof RegExp){const t=(null==e?void 0:e.message)||String(e);if(n.test(t))return!0}return!1}startReporting(){setInterval(()=>{this.flushReports()},5e3)}async flushReports(){if(!this.isReporting&&0!==this.reportQueue.length){this.isReporting=!0;try{const e=[...this.reportQueue];if(this.reportQueue=[],0===e.length)return;const t=await fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"},body:JSON.stringify({errors:e,errorGroups:Array.from(this.errorGroups.values()).map(e=>({fingerprint:e.fingerprint,count:e.count,firstSeen:e.firstSeen,lastSeen:e.lastSeen}))})});if(!t.ok)throw new Error(`Error reporting failed: ${t.status}`);d.debug("[ErrorTracker] Errors reported",{count:e.length})}catch(e){d.error("[ErrorTracker] Failed to report errors",e)}finally{this.isReporting=!1}}}async report(){await this.flushReports()}getErrorGroups(){return Array.from(this.errorGroups.values())}getErrors(){return[...this.errors]}clearErrors(){this.errors=[],this.errorGroups.clear(),this.reportQueue=[]}triggerErrorEvent(e){const t=new CustomEvent("error-tracker:error",{detail:e,bubbles:!0});window.dispatchEvent(t)}destroy(){this.flushReports(),this.clearErrors(),d.info("[ErrorTracker] Destroyed")}}let ue=null;function pe(e={}){return ue||(ue=he.create(e)),ue}const me={name:"error-tracking",errorTracker:null,init(e={},t=null){return d.info("[ErrorTrackingModule] Module initialized"),this.errorTracker=pe(e),"undefined"!=typeof window&&(window.ErrorTracker=this.errorTracker),this},getErrorTracker(){return this.errorTracker||pe()},captureException(e,t={}){this.getErrorTracker().captureException(e,t)},destroy(){this.errorTracker&&(this.errorTracker.destroy(),this.errorTracker=null),"undefined"!=typeof window&&window.ErrorTracker&&delete window.ErrorTracker,d.info("[ErrorTrackingModule] Module destroyed")}},ge=me.init.bind(me),fe=Object.freeze(Object.defineProperty({__proto__:null,ErrorTracker:he,default:me,getGlobalErrorTracker:pe,init:ge},Symbol.toStringTag,{value:"Module"}));class ye{constructor(e={}){this.config={enableHistory:e.enableHistory??!1,maxHistorySize:e.maxHistorySize||100,enableWildcards:e.enableWildcards??!0,...e},this.subscribers=new Map,this.history=[],this.middleware=[],d.info("[EventBus] Initialized",{enableHistory:this.config.enableHistory,enableWildcards:this.config.enableWildcards})}static create(e={}){return new ye(e)}on(e,t,n={}){if("function"!=typeof t)throw new Error("Callback must be a function");this.subscribers.has(e)||this.subscribers.set(e,new Set);const i={callback:t,once:n.once??!1,priority:n.priority||0,filter:n.filter||null};this.subscribers.get(e).add(i);const s=Array.from(this.subscribers.get(e));return s.sort((e,t)=>t.priority-e.priority),this.subscribers.set(e,new Set(s)),()=>{const t=this.subscribers.get(e);t&&(t.delete(i),0===t.size&&this.subscribers.delete(e))}}once(e,t,n={}){return this.on(e,t,{...n,once:!0})}off(e,t){if(!this.subscribers.has(e))return;const n=this.subscribers.get(e);for(const i of n)if(i.callback===t){n.delete(i);break}0===n.size&&this.subscribers.delete(e)}emit(e,t=null,n={}){let i=t;for(const o of this.middleware){const t=o(e,i,n);if(null===t||!1===t)return;void 0!==t&&(i=t)}this.config.enableHistory&&this.addToHistory(e,i,n);const s=this.subscribers.get(e);s&&this.notifySubscribers(s,e,i,n),this.config.enableWildcards&&this.handleWildcards(e,i,n),this.handleNamespacedEvents(e,i,n),d.debug("[EventBus] Event emitted",{eventName:e,data:i})}notifySubscribers(e,t,n,i){const s=Array.from(e);for(const a of s)if(!a.filter||a.filter(n,i)){try{a.callback(n,t,i)}catch(o){d.error("[EventBus] Subscriber error",o)}a.once&&e.delete(a)}}handleWildcards(e,t,n){const i=this.subscribers.get("*");i&&this.notifySubscribers(i,e,t,n);for(const[s,o]of this.subscribers.entries())s.includes("*")&&this.matchesPattern(e,s)&&this.notifySubscribers(o,e,t,n)}handleNamespacedEvents(e,t,n){const i=e.split(":");if(i.length>1){const s=i[0]+":*",o=this.subscribers.get(s);o&&this.notifySubscribers(o,e,t,n)}}matchesPattern(e,t){return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e)}use(e){if("function"!=typeof e)throw new Error("Middleware must be a function");this.middleware.push(e)}addToHistory(e,t,n){this.history.push({eventName:e,data:t,options:n,timestamp:Date.now()}),this.history.length>this.config.maxHistorySize&&this.history.shift()}getHistory(e=null){return e?"string"==typeof e?this.history.filter(t=>t.eventName===e):"function"==typeof e?this.history.filter(e):[]:[...this.history]}clearHistory(){this.history=[]}getEventNames(){return Array.from(this.subscribers.keys())}getSubscriberCount(e){const t=this.subscribers.get(e);return t?t.size:0}removeAllListeners(e=null){e?this.subscribers.delete(e):this.subscribers.clear()}destroy(){this.subscribers.clear(),this.history=[],this.middleware=[],d.info("[EventBus] Destroyed")}}let ve=null;function be(e={}){return ve||(ve=ye.create(e)),ve}const we={name:"event-bus",eventBus:null,init(e={},t=null){return d.info("[EventBusModule] Module initialized"),this.eventBus=be(e),"undefined"!=typeof window&&(window.EventBus=this.eventBus),this},getEventBus(){return this.eventBus||be()},emit(e,t=null,n={}){this.getEventBus().emit(e,t,n)},on(e,t,n={}){return this.getEventBus().on(e,t,n)},off(e,t){this.getEventBus().off(e,t)},destroy(){this.eventBus&&(this.eventBus.destroy(),this.eventBus=null),"undefined"!=typeof window&&window.EventBus&&delete window.EventBus,d.info("[EventBusModule] Module destroyed")}},Se=we.init.bind(we),Ee=Object.freeze(Object.defineProperty({__proto__:null,EventBus:ye,default:we,getGlobalEventBus:be,init:Se},Symbol.toStringTag,{value:"Module"}));let Ce="example-module",ke=null,Me=null;const xe=Object.freeze(Object.defineProperty({__proto__:null,destroy:function(){d.info("[example-module] destroy"),ke&&(window.removeEventListener("resize",ke),ke=null),c(Ce),Me&&"function"==typeof Me.cleanup&&Me.cleanup(),Me=null},init:function(e={},t=null){d.info("[example-module] init"),Me=t,Me&&(Me.register("windowSize",{width:window.innerWidth,height:window.innerHeight}),Me.register("scrollPosition",{x:0,y:0}),Me.register("isVisible",!0)),ke=()=>{const e={width:window.innerWidth,height:window.innerHeight};d.info("Fenstergröße geändert:",e),Me&&Me.set("windowSize",e)},window.addEventListener("resize",ke),l(Ce,()=>{const e=window.scrollY,t=window.scrollX;if(Me){const n=Me.get("scrollPosition");n.x===t&&n.y===e||Me.set("scrollPosition",{x:t,y:e})}},{autoStart:!0})}},Symbol.toStringTag,{value:"Module"}));class Te{constructor(e){this.form=e,this.errors=new Map}static create(e){return new Te(e)}validate(){this.errors.clear();const e=this.form.querySelectorAll("input, textarea, select");for(const t of e)"hidden"===t.type||t.disabled||this.validateField(t);return 0===this.errors.size}validateField(e){const t=e.value,n=e.name;if(e.hasAttribute("required")&&(!t||""===t.trim()))return void this.errors.set(n,this.getErrorMessage(e,"valueMissing")||`${this.getFieldLabel(e)} ist erforderlich`);if(!t||""===t.trim())return;if("email"===e.type&&!this.isValidEmail(t))return void this.errors.set(n,this.getErrorMessage(e,"typeMismatch")||"Bitte geben Sie eine gültige E-Mail-Adresse ein");if("url"===e.type&&!this.isValidUrl(t))return void this.errors.set(n,this.getErrorMessage(e,"typeMismatch")||"Bitte geben Sie eine gültige URL ein");const i=e.getAttribute("minlength");if(i&&t.length<parseInt(i))return void this.errors.set(n,this.getErrorMessage(e,"tooShort")||`Mindestens ${i} Zeichen erforderlich`);const s=e.getAttribute("maxlength");if(s&&t.length>parseInt(s))return void this.errors.set(n,this.getErrorMessage(e,"tooLong")||`Maximal ${s} Zeichen erlaubt`);if("number"===e.type){const i=e.getAttribute("min"),s=e.getAttribute("max"),o=parseFloat(t);if(i&&o<parseFloat(i))return void this.errors.set(n,this.getErrorMessage(e,"rangeUnderflow")||`Wert muss mindestens ${i} sein`);if(s&&o>parseFloat(s))return void this.errors.set(n,this.getErrorMessage(e,"rangeOverflow")||`Wert darf maximal ${s} sein`)}const o=e.getAttribute("pattern");if(o){if(!new RegExp(o).test(t))return void this.errors.set(n,this.getErrorMessage(e,"patternMismatch")||"Ungültiges Format")}const a=e.getAttribute("data-validate");if(a){const i=this.runCustomValidation(a,t,e);if(!i.valid)return void this.errors.set(n,i.message)}}runCustomValidation(e,t,n){switch(e){case"phone":return{valid:/^[\+]?[0-9\s\-\(\)]{10,}$/.test(t),message:"Bitte geben Sie eine gültige Telefonnummer ein"};case"postal-code-de":return{valid:/^[0-9]{5}$/.test(t),message:"Bitte geben Sie eine gültige Postleitzahl ein"};case"no-html":return{valid:!/<[^>]*>/g.test(t),message:"HTML-Code ist nicht erlaubt"};default:return d.warn(`Unknown custom validation: ${e}`),{valid:!0,message:""}}}isValidEmail(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}isValidUrl(e){try{return new URL(e),!0}catch{return!1}}getFieldLabel(e){const t=this.form.querySelector(`label[for="${e.id}"]`)||this.form.querySelector(`label:has([name="${e.name}"])`);return t?t.textContent.trim().replace(":",""):e.name}getErrorMessage(e,t){return e.getAttribute(`data-error-${t}`)||e.getAttribute("data-error")}getErrors(){return Object.fromEntries(this.errors)}getFieldError(e){return this.errors.get(e)}hasErrors(){return this.errors.size>0}clearErrors(){this.errors.clear()}validateWithHTML5(){const e=this.form.checkValidity();if(!e){const e=this.form.querySelectorAll("input, textarea, select");for(const t of e)t.validity.valid||this.errors.set(t.name,t.validationMessage)}return e}}class Ae{constructor(e){this.form=e,this.pristineValues=new Map,this.touchedFields=new Set,this.dirtyFields=new Set,this.init()}static create(e){return new Ae(e)}init(){this.captureInitialValues(),this.bindEvents(),d.info(`[FormState] Initialized for form: ${this.form.id||"unnamed"}`)}captureInitialValues(){this.form.querySelectorAll("input, textarea, select").forEach(e=>{let t;switch(e.type){case"checkbox":case"radio":t=e.checked;break;default:t=e.value}this.pristineValues.set(e.name,t)})}bindEvents(){this.form.querySelectorAll("input, textarea, select").forEach(e=>{"hidden"!==e.type&&(e.addEventListener("focus",()=>{this.markAsTouched(e.name)}),e.addEventListener("input",()=>{this.checkDirtyState(e)}),e.addEventListener("change",()=>{this.checkDirtyState(e)}))})}markAsTouched(e){this.touchedFields.add(e),this.updateFormClasses()}checkDirtyState(e){const t=e.name;this.getFieldValue(e)!==this.pristineValues.get(t)?this.dirtyFields.add(t):this.dirtyFields.delete(t),this.updateFormClasses()}getFieldValue(e){switch(e.type){case"checkbox":case"radio":return e.checked;default:return e.value}}updateFormClasses(){this.isDirty()?(this.form.classList.add("form-dirty"),this.form.classList.remove("form-pristine")):(this.form.classList.add("form-pristine"),this.form.classList.remove("form-dirty")),this.hasTouchedFields()?this.form.classList.add("form-touched"):this.form.classList.remove("form-touched")}isPristine(){return 0===this.dirtyFields.size}isDirty(){return this.dirtyFields.size>0}hasTouchedFields(){return this.touchedFields.size>0}isFieldTouched(e){return this.touchedFields.has(e)}isFieldDirty(e){return this.dirtyFields.has(e)}isFieldPristine(e){return!this.dirtyFields.has(e)}getFieldState(e){return{pristine:this.isFieldPristine(e),dirty:this.isFieldDirty(e),touched:this.isFieldTouched(e),pristineValue:this.pristineValues.get(e),currentValue:this.getCurrentFieldValue(e)}}getCurrentFieldValue(e){const t=this.form.querySelector(`[name="${e}"]`);return t?this.getFieldValue(t):void 0}getFormState(){return{pristine:this.isPristine(),dirty:this.isDirty(),touched:this.hasTouchedFields(),dirtyFields:Array.from(this.dirtyFields),touchedFields:Array.from(this.touchedFields),totalFields:this.pristineValues.size}}reset(){this.touchedFields.clear(),this.dirtyFields.clear(),setTimeout(()=>{this.captureInitialValues(),this.updateFormClasses()},0),d.info("[FormState] State reset")}resetField(e){this.touchedFields.delete(e),this.dirtyFields.delete(e);const t=this.form.querySelector(`[name="${e}"]`),n=this.pristineValues.get(e);if(t&&void 0!==n)switch(t.type){case"checkbox":case"radio":t.checked=n;break;default:t.value=n}this.updateFormClasses(),d.info(`[FormState] Field "${e}" reset to pristine state`)}triggerStateEvent(e,t={}){const n=new CustomEvent(e,{detail:{...t,formState:this.getFormState()},bubbles:!0,cancelable:!0});this.form.dispatchEvent(n)}hasChanges(){return this.isDirty()}getChangedFields(){const e={};return this.dirtyFields.forEach(t=>{e[t]={pristineValue:this.pristineValues.get(t),currentValue:this.getCurrentFieldValue(t)}}),e}enableUnsavedChangesWarning(){window.addEventListener("beforeunload",e=>{if(this.isDirty())return e.preventDefault(),e.returnValue="Sie haben ungespeicherte Änderungen. Möchten Sie die Seite wirklich verlassen?",e.returnValue})}destroy(){this.pristineValues.clear(),this.touchedFields.clear(),this.dirtyFields.clear(),d.info("[FormState] Destroyed")}}class Le{constructor(e,t={}){this.form=e,this.options={validateOnSubmit:!0,validateOnBlur:!1,validateOnInput:!1,showInlineErrors:!0,preventSubmitOnError:!0,submitMethod:"POST",ajaxSubmit:!0,enableAutosave:t.enableAutosave??e.hasAttribute("data-autosave"),autosaveInterval:t.autosaveInterval||3e4,autosaveRetentionPeriod:t.autosaveRetentionPeriod||864e5,autosaveStorageKey:t.autosaveStorageKey||null,autosaveStoragePrefix:t.autosaveStoragePrefix||"form_draft_",autosaveVisualFeedback:t.autosaveVisualFeedback??!0,autosaveExcludeFields:t.autosaveExcludeFields||['input[type="password"]','input[type="hidden"][name="_token"]','input[type="hidden"][name="_form_id"]','input[name*="password"]','input[name*="confirm"]','input[name*="honeypot"]'],autosaveImmediateFields:t.autosaveImmediateFields||["textarea",'input[type="email"]','input[type="text"]',"select"],...t},this.validator=Te.create(e),this.state=Ae.create(e),this.isSubmitting=!1,this.autosaveTimer=null,this.lastAutosaveTime=null,this.autosaveStorageKey=null,this.init()}static create(e,t={}){return new Le(e,t)}init(){this.bindEvents(),this.setupErrorDisplay(),this.options.enableAutosave&&this.initAutosave(),this.form.setAttribute("data-enhanced","true"),d.info(`[FormHandler] Initialized for form: ${this.form.id||"unnamed"}`)}bindEvents(){if(this.form.addEventListener("submit",e=>this.handleSubmit(e)),this.options.validateOnBlur||this.options.validateOnInput){this.form.querySelectorAll("input, textarea, select").forEach(e=>{this.options.validateOnBlur&&e.addEventListener("blur",()=>this.validateSingleField(e)),this.options.validateOnInput&&e.addEventListener("input",()=>this.validateSingleField(e))})}this.options.enableAutosave&&(this.form.addEventListener("input",e=>this.onAutosaveFieldChange(e)),this.form.addEventListener("change",e=>this.onAutosaveFieldChange(e)),window.addEventListener("beforeunload",()=>{this.state.isDirty()&&this.saveAutosaveDraft()}),document.addEventListener("visibilitychange",()=>{document.hidden&&this.state.isDirty()&&this.saveAutosaveDraft()}))}async handleSubmit(e){if(this.isSubmitting)e.preventDefault();else{if(this.options.validateOnSubmit){if(!this.validator.validate())return e.preventDefault(),void this.displayErrors()}this.options.ajaxSubmit&&(e.preventDefault(),await this.submitViaAjax())}}async submitViaAjax(){try{this.setSubmitState(!0),this.clearErrors();const e=new FormData(this.form),t=this.form.action||window.location.href,n=this.form.method||this.options.submitMethod,i=await fetch(t,{method:n.toUpperCase(),body:e,headers:{"X-Requested-With":"XMLHttpRequest"}}),s=await this.parseResponse(i);i.ok?this.handleSuccess(s):this.handleError(s)}catch(e){d.error("[FormHandler] Submit error:",e),this.handleError({message:"Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.",errors:{}})}finally{this.setSubmitState(!1)}}async parseResponse(e){const t=e.headers.get("content-type");if(null==t?void 0:t.includes("application/json"))return await e.json();const n=await e.text();try{return JSON.parse(n)}catch{return{message:n}}}handleSuccess(e){d.info("[FormHandler] Form submitted successfully"),this.options.enableAutosave&&this.clearAutosaveDraft(),!1!==e.clearForm&&(this.form.reset(),this.state.reset()),this.showMessage(e.message||"Formular erfolgreich gesendet!","success"),this.triggerEvent("form:success",{data:e})}handleError(e){if(d.warn("[FormHandler] Form submission error:",e),e.errors&&"object"==typeof e.errors){for(const[t,n]of Object.entries(e.errors))this.validator.errors.set(t,n);this.displayErrors()}this.showMessage(e.message||"Ein Fehler ist aufgetreten.","error"),this.triggerEvent("form:error",{data:e})}validateSingleField(e){this.validator.errors.delete(e.name),this.validator.validateField(e),this.displayFieldError(e)}displayErrors(){if(!this.options.showInlineErrors)return;const e=this.validator.getErrors();for(const[t,n]of Object.entries(e)){const e=this.form.querySelector(`[name="${t}"]`);e&&this.displayFieldError(e,n)}}displayFieldError(e,t=null){const n=t||this.validator.getFieldError(e.name),i=this.getOrCreateErrorElement(e);n?(i.textContent=n,i.style.display="block",e.classList.add("error"),e.setAttribute("aria-invalid","true"),e.setAttribute("aria-describedby",i.id)):(i.textContent="",i.style.display="none",e.classList.remove("error"),e.removeAttribute("aria-invalid"),e.removeAttribute("aria-describedby"))}getOrCreateErrorElement(e){const t=`error-${e.name}`;let n=document.getElementById(t);if(!n){n=document.createElement("div"),n.id=t,n.className="form-error",n.setAttribute("role","alert"),n.style.display="none";(e.closest(".form-group")||e.parentElement).appendChild(n)}return n}setupErrorDisplay(){if(!document.getElementById("form-handler-styles")){const e=document.createElement("style");e.id="form-handler-styles",e.textContent="\n .form-error {\n color: #dc2626;\n font-size: 0.875rem;\n margin-top: 0.25rem;\n }\n input.error, textarea.error, select.error {\n border-color: #dc2626;\n box-shadow: 0 0 0 1px #dc2626;\n }\n .form-message {\n padding: 0.75rem;\n border-radius: 0.375rem;\n margin: 1rem 0;\n }\n .form-message.success {\n background-color: #dcfce7;\n color: #166534;\n border: 1px solid #bbf7d0;\n }\n .form-message.error {\n background-color: #fef2f2;\n color: #dc2626;\n border: 1px solid #fecaca;\n }\n ",document.head.appendChild(e)}}showMessage(e,t="info"){let n=this.form.querySelector(".form-messages");n||(n=document.createElement("div"),n.className="form-messages",this.form.prepend(n));const i=document.createElement("div");i.className=`form-message ${t}`,i.textContent=e,i.setAttribute("role","error"===t?"alert":"status"),n.innerHTML="",n.appendChild(i),"success"===t&&setTimeout(()=>{i.parentElement&&i.remove()},5e3)}clearErrors(){this.validator.clearErrors();this.form.querySelectorAll(".error").forEach(e=>{e.classList.remove("error"),e.removeAttribute("aria-invalid"),e.removeAttribute("aria-describedby")});this.form.querySelectorAll(".form-error").forEach(e=>{e.style.display="none",e.textContent=""});const e=this.form.querySelector(".form-messages");e&&(e.innerHTML="")}setSubmitState(e){this.isSubmitting=e;this.form.querySelectorAll('button[type="submit"], input[type="submit"]').forEach(t=>{if(t.disabled=e,e)t.setAttribute("data-original-text",t.textContent),t.textContent="Wird gesendet...";else{const e=t.getAttribute("data-original-text");e&&(t.textContent=e,t.removeAttribute("data-original-text"))}})}triggerEvent(e,t={}){const n=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});this.form.dispatchEvent(n)}initAutosave(){this.autosaveStorageKey=this.options.autosaveStorageKey||this.options.autosaveStoragePrefix+this.generateFormId(),this.restoreAutosaveDraft(),this.startAutosave(),d.info("[FormHandler] Autosave initialized",{storageKey:this.autosaveStorageKey})}generateFormId(){var e;return(this.form.id||this.form.getAttribute("data-form-id")||(null==(e=this.form.querySelector('input[name="_form_id"]'))?void 0:e.value)||"form_"+Date.now()).replace(/[^a-zA-Z0-9_-]/g,"_")}onAutosaveFieldChange(e){const t=e.target;this.isAutosaveFieldExcluded(t)||this.isAutosaveImmediateField(t)&&this.saveAutosaveDraft()}isAutosaveFieldExcluded(e){return this.options.autosaveExcludeFields.some(t=>e.matches(t))}isAutosaveImmediateField(e){return this.options.autosaveImmediateFields.some(t=>e.matches(t))}startAutosave(){this.autosaveTimer||(this.autosaveTimer=setInterval(()=>{this.state.isDirty()&&this.saveAutosaveDraft()},this.options.autosaveInterval),d.debug("[FormHandler] Autosave started",{interval:this.options.autosaveInterval}))}stopAutosave(){this.autosaveTimer&&(clearInterval(this.autosaveTimer),this.autosaveTimer=null)}saveAutosaveDraft(){if(this.form&&this.state.isDirty())try{const e=this.extractAutosaveFormData(),t={data:e,timestamp:Date.now(),formId:this.generateFormId(),url:window.location.href,version:"1.0"};localStorage.setItem(this.autosaveStorageKey,JSON.stringify(t)),this.lastAutosaveTime=new Date,d.debug("[FormHandler] Draft saved",{fields:Object.keys(e).length,storageKey:this.autosaveStorageKey}),this.options.autosaveVisualFeedback&&this.showAutosaveStatus("Draft saved","success",1500),this.triggerEvent("form:autosave",{draft:t})}catch(e){d.error("[FormHandler] Failed to save draft",e),this.options.autosaveVisualFeedback&&this.showAutosaveStatus("Failed to save draft","error",3e3)}}restoreAutosaveDraft(){try{const e=localStorage.getItem(this.autosaveStorageKey);if(!e)return;const t=JSON.parse(e),n=Date.now()-t.timestamp;if(n>this.options.autosaveRetentionPeriod)return void localStorage.removeItem(this.autosaveStorageKey);if(this.restoreAutosaveFormData(t.data),d.info("[FormHandler] Draft restored",{age:Math.floor(n/1e3)+"s",fields:Object.keys(t.data).length}),this.options.autosaveVisualFeedback){const e=this.formatDuration(n);this.showAutosaveStatus(`Draft restored from ${e} ago`,"info",4e3)}this.triggerEvent("form:autosave-restored",{draft:t})}catch(e){d.error("[FormHandler] Failed to restore draft",e),localStorage.removeItem(this.autosaveStorageKey)}}extractAutosaveFormData(){const e=this.getFormFields(),t={};return e.forEach(e=>{if(!this.isAutosaveFieldExcluded(e)){const n=e.name||e.id,i=this.getAutosaveFieldValue(e);n&&null!=i&&""!==i&&(t[n]=i)}}),t}restoreAutosaveFormData(e){let t=0;return Object.entries(e).forEach(([e,n])=>{const i=this.form.querySelector(`[name="${e}"], #${e}`);i&&!this.isAutosaveFieldExcluded(i)&&(this.setAutosaveFieldValue(i,n),t++)}),this.state.captureInitialValues(),t}getFormFields(){return Array.from(this.form.querySelectorAll('input:not([type="submit"]):not([type="button"]):not([type="reset"]), textarea, select'))}getAutosaveFieldValue(e){switch(e.type){case"checkbox":return e.checked;case"radio":return e.checked?e.value:null;case"file":return null;default:return e.value}}setAutosaveFieldValue(e,t){switch(e.type){case"checkbox":e.checked=Boolean(t);break;case"radio":e.checked=e.value===t;break;case"file":break;default:e.value=t}}clearAutosaveDraft(){this.autosaveStorageKey&&localStorage.removeItem(this.autosaveStorageKey),d.debug("[FormHandler] Draft cleared")}formatDuration(e){const t=Math.floor(e/1e3),n=Math.floor(t/60),i=Math.floor(n/60);return i>0?`${i}h ${n%60}m`:n>0?`${n}m`:`${t}s`}showAutosaveStatus(e,t="info",n=3e3){let i=document.getElementById("form-autosave-status");i||(i=document.createElement("div"),i.id="form-autosave-status",i.style.cssText="\n position: fixed;\n bottom: 20px;\n right: 20px;\n padding: 8px 12px;\n border-radius: 4px;\n font-size: 12px;\n z-index: 9999;\n max-width: 250px;\n box-shadow: 0 2px 8px rgba(0,0,0,0.1);\n transition: opacity 0.3s ease;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n ",document.body.appendChild(i)),i.textContent=e;const s={info:"background: #e3f2fd; color: #1565c0; border: 1px solid #bbdefb;",success:"background: #e8f5e8; color: #2e7d32; border: 1px solid #c8e6c9;",error:"background: #ffebee; color: #c62828; border: 1px solid #ffcdd2;"};i.style.cssText+=s[t]||s.info,i.style.opacity="1",setTimeout(()=>{i&&(i.style.opacity="0",setTimeout(()=>{i&&i.parentNode&&i.parentNode.removeChild(i)},300))},n)}destroy(){this.options.enableAutosave&&this.stopAutosave(),this.form.removeAttribute("data-enhanced"),d.info("[FormHandler] Destroyed")}}const Ie={name:"form-handling",init(e={},t=null){return d.info("[FormHandling] Module initialized (ready for DOM elements)"),this},initElement(e,t={}){d.info(`[FormHandling] Initializing on form: ${e.id||"unnamed"}`);const n={validateOnSubmit:!0,validateOnBlur:!1,validateOnInput:!1,showInlineErrors:!0,preventSubmitOnError:!0,ajaxSubmit:!0,submitMethod:"POST",enableStateTracking:!0,enableUnsavedWarning:!1,...t},i=Le.create(e,n);e._formHandler=i,e._formValidator=i.validator,e._formState=i.state,n.enableUnsavedWarning&&i.state.enableUnsavedChangesWarning(),e.classList.add("form-enhanced");const s=new CustomEvent("form:initialized",{detail:{handler:i,validator:i.validator,state:i.state,config:n},bubbles:!0});return e.dispatchEvent(s),d.info(`[FormHandling] Successfully initialized for form: ${e.id||"unnamed"}`),i},destroyElement(e){e._formHandler&&(e._formHandler.destroy(),delete e._formHandler,delete e._formValidator,delete e._formState),e.classList.remove("form-enhanced"),e.removeAttribute("data-enhanced"),d.info(`[FormHandling] Destroyed for form: ${e.id||"unnamed"}`)},destroy(){d.info("[FormHandling] Module destroyed")}},Pe=Ie.init.bind(Ie),$e=Ie.initElement.bind(Ie),De=Object.freeze(Object.defineProperty({__proto__:null,FormHandler:Le,FormHandlingModule:Ie,FormState:Ae,FormValidator:Te,default:Ie,init:Pe,initElement:$e},Symbol.toStringTag,{value:"Module"})),Oe={name:"image-manager",activeGalleries:new Map,activeUploaders:new Map,async init(e={},t){return d.info("[ImageManager] Module initialized"),this.initializeGalleries(),this.initializeUploaders(),this.initializeModal(),this},initializeGalleries(){const e=document.querySelectorAll("[data-image-gallery]");d.info(`[ImageManager] Found ${e.length} gallery elements`),e.forEach((e,t)=>{const n=`gallery-${t}`,i=new ze(e,{listEndpoint:e.dataset.listEndpoint||"/api/images",pageSize:parseInt(e.dataset.pageSize)||20,columns:parseInt(e.dataset.columns)||4});this.activeGalleries.set(n,i),d.info(`[ImageManager] Initialized gallery: ${n}`)})},initializeUploaders(){const e=document.querySelectorAll("[data-image-uploader]");d.info(`[ImageManager] Found ${e.length} uploader elements`),e.forEach((e,t)=>{var n;const i=`uploader-${t}`,s=new _e(e,{uploadUrl:e.dataset.uploadUrl||"/api/images",maxFileSize:parseInt(e.dataset.maxFileSize)||10485760,allowedTypes:(null==(n=e.dataset.allowedTypes)?void 0:n.split(","))||["image/jpeg","image/png","image/gif","image/webp"],maxFiles:parseInt(e.dataset.maxFiles)||10});this.activeUploaders.set(i,s),d.info(`[ImageManager] Initialized uploader: ${i}`)})},initializeModal(){const e=new Re;window.ImageModal=e,d.info("[ImageManager] Modal initialized")},destroy(){this.activeGalleries.forEach((e,t)=>{e.destroy(),d.info(`[ImageManager] Destroyed gallery: ${t}`)}),this.activeGalleries.clear(),this.activeUploaders.forEach((e,t)=>{e.destroy(),d.info(`[ImageManager] Destroyed uploader: ${t}`)}),this.activeUploaders.clear(),window.ImageModal&&(window.ImageModal.destroy(),delete window.ImageModal),d.info("[ImageManager] Module destroyed")}};class ze{constructor(e,t){this.element=e,this.config=t,this.currentPage=1,this.images=[],this.loading=!1,this.init()}async init(){d.info("[ImageGallery] Initializing gallery"),this.element.innerHTML="",this.buildGalleryUI(),await this.loadImages()}buildGalleryUI(){this.element.innerHTML=`\n <div class="image-gallery">\n <div class="gallery__controls">\n <div class="gallery__search-wrapper">\n <input type="text" class="gallery__search" placeholder="Search images...">\n <button type="button" class="gallery__search-clear">×</button>\n </div>\n <div class="gallery__sort-wrapper">\n <label>Sort:</label>\n <select class="gallery__sort">\n <option value="created_desc">Newest First</option>\n <option value="created_asc">Oldest First</option>\n <option value="name_asc">Name A-Z</option>\n <option value="name_desc">Name Z-A</option>\n </select>\n </div>\n </div>\n <div class="gallery__grid" style="--columns: ${this.config.columns}"></div>\n <div class="gallery__pagination">\n <button type="button" class="gallery__load-more" style="display: none;">Load More</button>\n </div>\n <div class="gallery__loading">\n <div class="loading-spinner"></div>\n <p>Loading images...</p>\n </div>\n </div>\n `,this.setupEventListeners()}setupEventListeners(){const e=this.element.querySelector(".gallery__search"),t=this.element.querySelector(".gallery__search-clear"),n=this.element.querySelector(".gallery__sort"),i=this.element.querySelector(".gallery__load-more");let s;e.addEventListener("input",e=>{clearTimeout(s),s=setTimeout(()=>{this.searchImages(e.target.value)},300)}),t.addEventListener("click",()=>{e.value="",this.searchImages("")}),n.addEventListener("change",e=>{this.sortImages(e.target.value)}),i.addEventListener("click",()=>{this.loadMoreImages()})}async loadImages(){if(!this.loading){this.loading=!0,this.showLoading();try{d.info("[ImageGallery] Loading images from:",this.config.listEndpoint);const e=await fetch(`${this.config.listEndpoint}?page=${this.currentPage}&limit=${this.config.pageSize}`);if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);const t=await e.json();d.info("[ImageGallery] API Response:",t);let n=[],i={};t.data&&Array.isArray(t.data)?(n=t.data,i=t.meta||{}):t.images&&Array.isArray(t.images)?(n=t.images,i=t):Array.isArray(t)?(n=t,i={}):(d.warn("[ImageGallery] Unexpected API response format:",t),n=[],i={}),d.info("[ImageGallery] Processed images:",n.length),1===this.currentPage?this.images=n:this.images=[...this.images,...n],this.renderImages(),this.updateLoadMoreButton(i)}catch(e){d.error("[ImageGallery] Failed to load images:",e),this.showError(`Failed to load images: ${e.message}`)}finally{this.loading=!1,this.hideLoading()}}}renderImages(){const e=this.element.querySelector(".gallery__grid");0!==this.images.length?(e.innerHTML=this.images.map(e=>this.renderImageItem(e)).join(""),e.querySelectorAll(".gallery__item").forEach((e,t)=>{e.addEventListener("click",()=>{this.showImageModal(this.images[t])})})):e.innerHTML='\n <div class="gallery__empty">\n <div class="empty-state__icon">\n <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1">\n <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>\n <circle cx="8.5" cy="8.5" r="1.5"></circle>\n <polyline points="21,15 16,10 5,21"></polyline>\n </svg>\n </div>\n <h3>No images found</h3>\n <p>Upload some images to get started</p>\n </div>\n '}renderImageItem(e){let t="0 B",n="0 × 0";return e.file_size&&("object"==typeof e.file_size&&e.file_size.bytes?t=this.formatFileSize(e.file_size.bytes):"number"==typeof e.file_size&&(t=this.formatFileSize(e.file_size))),e.dimensions&&e.dimensions.width&&e.dimensions.height?n=`${e.dimensions.width} × ${e.dimensions.height}`:e.width&&e.height&&(n=`${e.width} × ${e.height}`),`\n <div class="gallery__item" data-image-id="${e.ulid}">\n <div class="gallery__item-inner">\n <div class="gallery__item-image">\n <img src="${e.url}" alt="${e.alt_text||e.filename}" loading="lazy">\n <div class="gallery__item-overlay">\n <div class="gallery__item-actions">\n <button type="button" class="action-btn" title="View Details">👁</button>\n <button type="button" class="action-btn" title="Edit">✏️</button>\n <button type="button" class="action-btn" title="Delete">🗑</button>\n </div>\n </div>\n </div>\n <div class="gallery__item-info">\n <div class="gallery__item-name" title="${e.original_filename||e.filename}">\n ${e.original_filename||e.filename}\n </div>\n <div class="gallery__item-meta">\n <span class="meta-item">${n}</span>\n <span class="meta-item">${t}</span>\n <span class="meta-item">${(e.mime_type||"").replace("image/","")}</span>\n </div>\n </div>\n </div>\n </div>\n `}showImageModal(e){window.ImageModal&&window.ImageModal.show(e)}formatFileSize(e){if(0===e)return"0 B";const t=Math.floor(Math.log(e)/Math.log(1024));return`${Math.round(e/Math.pow(1024,t)*100)/100} ${["B","KB","MB","GB"][t]}`}showLoading(){const e=this.element.querySelector(".gallery__loading");e&&(e.style.display="flex")}hideLoading(){const e=this.element.querySelector(".gallery__loading");e&&(e.style.display="none")}showError(e){this.element.querySelector(".gallery__grid").innerHTML=`\n <div class="gallery__error">\n <div class="error-message">\n <span>⚠️</span>\n <span>${e}</span>\n <button type="button" class="error-close" onclick="this.parentElement.parentElement.remove()">×</button>\n </div>\n </div>\n `}updateLoadMoreButton(e){var t;const n=this.element.querySelector(".gallery__load-more");e.has_more||e.hasMore||(null==(t=e.pagination)?void 0:t.hasMore)||!1?(n.style.display="block",n.disabled=!1):n.style.display="none"}async loadMoreImages(){this.currentPage++,await this.loadImages()}searchImages(e){const t=this.images.filter(t=>(t.filename||"").toLowerCase().includes(e.toLowerCase())||(t.original_filename||"").toLowerCase().includes(e.toLowerCase())||(t.alt_text||"").toLowerCase().includes(e.toLowerCase()));this.element.querySelector(".gallery__grid").innerHTML=t.map(e=>this.renderImageItem(e)).join("")}sortImages(e){const t=[...this.images];switch(e){case"created_desc":t.sort((e,t)=>new Date(t.created_at)-new Date(e.created_at));break;case"created_asc":t.sort((e,t)=>new Date(e.created_at)-new Date(t.created_at));break;case"name_asc":t.sort((e,t)=>(e.filename||"").localeCompare(t.filename||""));break;case"name_desc":t.sort((e,t)=>(t.filename||"").localeCompare(e.filename||""))}this.images=t,this.renderImages()}destroy(){this.element.innerHTML="",d.info("[ImageGallery] Gallery destroyed")}}class _e{constructor(e,t){this.element=e,this.config=t,d.info("[ImageUploader] Uploader placeholder initialized")}destroy(){d.info("[ImageUploader] Uploader destroyed")}}class Re{constructor(){d.info("[ImageModal] Modal placeholder initialized")}show(e){d.info("[ImageModal] Would show modal for image:",e)}destroy(){d.info("[ImageModal] Modal destroyed")}}const Fe=Oe.init.bind(Oe),qe=Oe.destroy.bind(Oe),Ne=Object.freeze(Object.defineProperty({__proto__:null,default:Oe,definition:{name:"image-manager",version:"1.0.0",dependencies:[],provides:["image-upload","image-gallery","image-modal"],priority:5},destroy:qe,init:Fe},Symbol.toStringTag,{value:"Module"}));let Be,He="inertia-scroll",Ue=0,je=window.scrollY,We=!1,Ve=.9,Ge=.2;function Je(){We=!0,clearTimeout(Be),Be=setTimeout(()=>{We=!1},50)}const Xe=Object.freeze(Object.defineProperty({__proto__:null,destroy:function(){window.removeEventListener("scroll",Je),c(He),Ue=0,je=window.scrollY,We=!1,clearTimeout(Be);const e=document.documentElement;delete e.dataset.scrollState,delete e.dataset.scrollDirection,delete e.dataset.scrollSpeed},init:function(e={}){Ve="number"==typeof e.damping?e.damping:.9,Ge="number"==typeof e.minVelocity?contig.minVelocity:.1,window.addEventListener("scroll",Je,{passive:!0}),l(He,()=>{const e=document.documentElement,t=window.scrollY,n=t-je,i=n>0?"down":n<0?"up":"none",s=Math.abs(n);!We&&Math.abs(Ue)>Ge?(window.scrollTo(0,t+Ue),Ue*=Ve,e.dataset.scrollState="inertia"):We?(Ue=n,je=t,e.dataset.scrollState="active"):delete e.dataset.scrollState,e.dataset.scrollDirection=i,e.dataset.scrollSpeed=s.toFixed(2)},{autoStart:!0})}},Symbol.toStringTag,{value:"Module"}));class Qe{constructor({content:e="",className:t="",onClose:n=null}={}){this.onClose=n,this.className=t,this.isOpenState=!1,this.dialog=document.createElement("dialog"),this.dialog.className=t,this.eventCleanup=[],this.updateContent(e),this.bindEvents()}bindEvents(){this.cleanupEvents(),this.clickHandler=e=>{!e.target.closest("."+this.className+"-content")&&this.close()},this.cancelHandler=e=>{e.preventDefault(),this.close()},this.dialog.addEventListener("click",this.clickHandler),this.dialog.addEventListener("cancel",this.cancelHandler),this.eventCleanup=[()=>this.dialog.removeEventListener("click",this.clickHandler),()=>this.dialog.removeEventListener("cancel",this.cancelHandler)]}cleanupEvents(){this.eventCleanup.forEach(e=>e()),this.eventCleanup=[]}updateContent(e){this.dialog.innerHTML=`\n <form method="dialog" class="${this.className}-content">\n ${e}\n <button class="${this.className}-close" value="close">×</button>\n </form>\n `}open(){var e,t,n,i;this.dialog.parentElement||document.body.appendChild(this.dialog),(this.dialog.hasAttribute("open")||this.dialog.open)&&((null==(t=(e=this.dialog).close)?void 0:t.call(e))||this.dialog.removeAttribute("open")),(null==(i=(n=this.dialog).showModal)?void 0:i.call(n))||this.dialog.setAttribute("open",""),document.documentElement.dataset[`${this.dialog.className}Open`]="true",this.isOpenState=!0}close(){var e,t,n;this.isOpenState&&((null==(t=(e=this.dialog).close)?void 0:t.call(e))||this.dialog.removeAttribute("open"),delete document.documentElement.dataset[`${this.dialog.className}Open`],this.isOpenState=!1,null==(n=this.onClose)||n.call(this))}isOpen(){const e=this.dialog&&(this.dialog.hasAttribute("open")||this.dialog.open);return e!==this.isOpenState&&(this.isOpenState=e),this.isOpenState}destroy(){this.isOpenState&&this.close(),this.cleanupEvents(),this.dialog.parentElement&&this.dialog.remove()}}const Ke={modal:class extends Qe{constructor(e){super({...e,className:"modal"})}},lightbox:class extends Qe{constructor(e){super({...e,className:"lightbox"})}}},Ye={},Ze={open(e,t={}){const n=Ke[e];if(!n)return d.warn(`[UIManager] Unknown type: ${e}`),null;if("lightbox"===e){if(Ye.lightbox)return d.info("[UIManager] Reusing existing lightbox instance"),Ye.lightbox.updateContent(t.content||""),Ye.lightbox.open(),Ye.lightbox;{d.info("[UIManager] Creating new lightbox instance");const e=new n({...t,onClose:()=>{d.info("[UIManager] Lightbox closed, instance kept for reuse"),t.onClose&&t.onClose()}});return Ye.lightbox=e,e.open(),e}}const i=new n(t);return i.open(),i},close(e){(null==e?void 0:e.close)&&e.close()},closeByType(e){Ye[e]&&this.close(Ye[e])},isOpen(e){var t;return(null==(t=Ye[e])?void 0:t.isOpen())||!1},destroyAll(){Object.values(Ye).forEach(e=>{(null==e?void 0:e.destroy)&&e.destroy()}),Object.keys(Ye).forEach(e=>{delete Ye[e]})}};function et(e){let t=null;if(t="IMG"===e.target.tagName?e.target:e.target.querySelector("img"),!t)return;if("false"===t.dataset.lightbox)return;if(t.naturalWidth<200||t.naturalHeight<200)return;if(t.closest("nav, header, footer, .no-lightbox"))return;e.preventDefault();const n=function(e){if(e.dataset.lightboxSrc)return e.dataset.lightboxSrc;if(e.currentSrc)return e.currentSrc;return e.src}(t),i=t.alt||t.dataset.caption||t.title||"",s=t.closest("picture");let o;if(s){const e=s.cloneNode(!0);e.querySelector("img").className="lightbox-image",o=`\n <div class="lightbox-content">\n ${e.outerHTML}\n ${i?`<div class="lightbox-caption">${i}</div>`:""}\n </div>\n `,d.info("[Lightbox] Opening responsive image (picture element):",n)}else o=`\n <div class="lightbox-content">\n <img src="${n}" alt="${i}" class="lightbox-image" />\n ${i?`<div class="lightbox-caption">${i}</div>`:""}\n </div>\n `,d.info("[Lightbox] Opening standalone image:",n);const a=Ze.open("lightbox",{content:o});Ze.isOpen("lightbox")&&a&&d.info("[Lightbox] Reused existing lightbox instance")}const tt=Object.freeze(Object.defineProperty({__proto__:null,destroy:function(){d.info("[lightbox-trigger] destroy"),document.querySelectorAll("img.lightbox-enabled").forEach(e=>{e.classList.remove("lightbox-enabled"),e.style.cursor="","Klicken zum Vergrößern"===e.title&&(e.title="")})},init:function(){d.info("[lightbox-trigger] Auto-enabling lightbox for all images (including picture/srcset)"),d.info('[lightbox-trigger] Use data-lightbox="false" to opt-out'),d.info("[lightbox-trigger] Use data-lightbox-src for custom high-res versions"),K(document,"click",et),function(){const e=document.querySelectorAll('img:not([data-lightbox="false"])');let t=0;e.forEach(e=>{e.naturalWidth<200||e.naturalHeight<200||e.closest("nav, header, footer, .no-lightbox")||(e.classList.add("lightbox-enabled"),e.style.cursor="zoom-in",e.title||e.alt||(e.title="Klicken zum Vergrößern"),t++)}),d.info(`[Lightbox] Enhanced ${t} images with lightbox functionality`)}()}},Symbol.toStringTag,{value:"Module"}));const nt=new class{patchFragment(e,t,n){const i=e.querySelector(`[data-lc-fragment="${t}"]`);if(!i)return console.warn(`[DomPatcher] Fragment not found: ${t}`),!1;const s=document.createElement("div");s.innerHTML=n;const o=s.firstElementChild;return o?o.getAttribute("data-lc-fragment")!==t?(console.warn(`[DomPatcher] Fragment name mismatch: expected ${t}, got ${o.getAttribute("data-lc-fragment")}`),!1):(this.patchElement(i,o),!0):(console.warn(`[DomPatcher] Invalid HTML for fragment: ${t}`),!1)}patchFragments(e,t){const n={};for(const[i,s]of Object.entries(t))n[i]=this.patchFragment(e,i,s);return n}patchElement(e,t){this.patchAttributes(e,t),this.patchChildren(e,t)}patchAttributes(e,t){const n=new Map,i=new Map;for(const s of e.attributes)n.set(s.name,s.value);for(const s of t.attributes)i.set(s.name,s.value);for(const[s,o]of n)i.has(s)||e.removeAttribute(s);for(const[s,o]of i)n.get(s)!==o&&e.setAttribute(s,o)}patchChildren(e,t){const n=Array.from(e.childNodes),i=Array.from(t.childNodes),s=Math.max(n.length,i.length);for(let o=0;o<s;o++){const t=n[o],s=i[o];!t&&s?e.appendChild(s.cloneNode(!0)):t&&!s?e.removeChild(t):t&&s&&(this.shouldPatch(t,s)?t.nodeType===Node.ELEMENT_NODE?this.patchElement(t,s):t.nodeType===Node.TEXT_NODE&&t.nodeValue!==s.nodeValue&&(t.nodeValue=s.nodeValue):e.replaceChild(s.cloneNode(!0),t))}}shouldPatch(e,t){if(e.nodeType!==t.nodeType)return!1;if(e.nodeType===Node.TEXT_NODE)return!0;if(e.nodeType===Node.ELEMENT_NODE){if(e.tagName!==t.tagName)return!1;const n=e.getAttribute("data-lc-key")||e.getAttribute("id"),i=t.getAttribute("data-lc-key")||t.getAttribute("id");return!n||!i||n===i}return!1}preserveFocus(e){const t=document.activeElement;if(!t||!e.contains(t))return()=>{};const n=this.getElementSelector(t),i=t.selectionStart,s=t.selectionEnd;return()=>{try{if(n){const t=e.querySelector(n);t&&t.focus&&(t.focus(),t.setSelectionRange&&"number"==typeof i&&"number"==typeof s&&t.setSelectionRange(i,s))}}catch(t){console.debug("[DomPatcher] Could not restore focus:",t)}}}getElementSelector(e){if(e.id)return`#${e.id}`;if(e.name)return`[name="${e.name}"]`;const t=e.getAttribute("data-lc-key");return t?`[data-lc-key="${t}"]`:e.tagName.toLowerCase()}swapElement(e,t,n="innerHTML",i=null,s=null){if(!e||!e.parentNode)return console.warn("[DomPatcher] Invalid target element for swap"),!1;const o=this.preserveFocus(e);i&&"none"!==i&&this.applyTransition(e,i,n);const a=document.createElement("div");a.innerHTML=t;const r=a.firstElementChild||a;try{switch(n){case"innerHTML":e.innerHTML=t;break;case"outerHTML":if(r.nodeType===Node.ELEMENT_NODE)e.parentNode.replaceChild(r.cloneNode(!0),e);else{const n=document.createElement("div");for(n.innerHTML=t;n.firstChild;)e.parentNode.insertBefore(n.firstChild,e);e.parentNode.removeChild(e)}break;case"beforebegin":if(r.nodeType===Node.ELEMENT_NODE)e.parentNode.insertBefore(r.cloneNode(!0),e);else{const n=document.createElement("div");for(n.innerHTML=t;n.firstChild;)e.parentNode.insertBefore(n.firstChild,e)}break;case"afterbegin":if(r.nodeType===Node.ELEMENT_NODE)e.insertBefore(r.cloneNode(!0),e.firstChild);else{const n=document.createElement("div");for(n.innerHTML=t;n.firstChild;)e.insertBefore(n.firstChild,e.firstChild)}break;case"afterend":if(r.nodeType===Node.ELEMENT_NODE)e.parentNode.insertBefore(r.cloneNode(!0),e.nextSibling);else{const n=document.createElement("div");n.innerHTML=t;const i=e.nextSibling;for(;n.firstChild;)e.parentNode.insertBefore(n.firstChild,i)}break;case"beforeend":if(r.nodeType===Node.ELEMENT_NODE)e.appendChild(r.cloneNode(!0));else{const n=document.createElement("div");for(n.innerHTML=t;n.firstChild;)e.appendChild(n.firstChild)}break;case"none":return!0;default:console.warn(`[DomPatcher] Unknown swap strategy: ${n}, falling back to innerHTML`),e.innerHTML=t}return"outerHTML"!==n&&"none"!==n&&o(),s&&s.enabled&&this.scrollToTarget(s.target||e,s.behavior||"smooth"),!0}catch(l){return console.error("[DomPatcher] Error during swap:",l),!1}}applyTransition(e,t,n){const i=`lc-transition-${t}`;e.classList.add(i),e.offsetWidth,requestAnimationFrame(()=>{e.classList.add("lc-transition-active")});const s=t=>{t.target===e&&(e.classList.remove(i),e.classList.remove("lc-transition-active"),e.removeEventListener("transitionend",s))};e.addEventListener("transitionend",s,{once:!0})}scrollToTarget(e,t="smooth"){let n=e;"string"==typeof e&&(n=document.querySelector(e)),n&&n instanceof HTMLElement?n.scrollIntoView({behavior:"smooth"===t?"smooth":"auto",block:"start",inline:"nearest"}):console.warn("[DomPatcher] Scroll target not found:",e)}},it={DISCONNECTED:"disconnected",CONNECTING:"connecting",CONNECTED:"connected",ERROR:"error"};class st{constructor(){this.attempt=0,this.baseDelay=1e3,this.maxDelay=3e4,this.maxAttempts=10}getDelay(){const e=Math.min(this.baseDelay*Math.pow(2,this.attempt),this.maxDelay),t=.25*e*(Math.random()-.5);return Math.floor(e+t)}shouldRetry(){return this.attempt<this.maxAttempts}recordAttempt(){this.attempt++}reset(){this.attempt=0}}class ot{constructor(e=[],t={}){this.channels=e,this.options={autoReconnect:!0,heartbeatTimeout:45e3,...t},this.eventSource=null,this.state=it.DISCONNECTED,this.reconnectionStrategy=new st,this.reconnectTimer=null,this.heartbeatTimer=null,this.lastHeartbeat=null,this.eventHandlers=new Map,this.stateChangeHandlers=new Set,this.connectionId=null}connect(){if(this.state===it.CONNECTING||this.state===it.CONNECTED)return void console.warn("[SSE] Already connecting or connected");this.setState(it.CONNECTING);const e=this.buildUrl();try{this.eventSource=new EventSource(e),this.eventSource.addEventListener("open",()=>{console.log("[SSE] Connection opened"),this.setState(it.CONNECTED),this.reconnectionStrategy.reset(),this.startHeartbeatMonitoring()}),this.eventSource.addEventListener("error",e=>{console.error("[SSE] Connection error",e),this.eventSource.readyState===EventSource.CLOSED&&this.handleDisconnect()}),this.eventSource.addEventListener("connected",e=>{const t=JSON.parse(e.data);this.connectionId=t.connection_id,console.log("[SSE] Connected with ID:",this.connectionId)}),this.eventSource.addEventListener("heartbeat",e=>{this.lastHeartbeat=Date.now()}),this.eventSource.addEventListener("disconnected",()=>{console.log("[SSE] Server initiated disconnect"),this.disconnect()}),this.eventSource.addEventListener("error",e=>{const t=JSON.parse(e.data);console.error("[SSE] Server error:",t)})}catch(t){console.error("[SSE] Failed to create EventSource",t),this.setState(it.ERROR),this.scheduleReconnect()}}disconnect(){this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.stopHeartbeatMonitoring(),this.clearReconnectTimer(),this.setState(it.DISCONNECTED),this.connectionId=null}handleDisconnect(){this.setState(it.ERROR),this.stopHeartbeatMonitoring(),this.options.autoReconnect&&this.reconnectionStrategy.shouldRetry()?this.scheduleReconnect():this.setState(it.DISCONNECTED)}scheduleReconnect(){const e=this.reconnectionStrategy.getDelay();console.log(`[SSE] Reconnecting in ${e}ms (attempt ${this.reconnectionStrategy.attempt+1})`),this.reconnectTimer=setTimeout(()=>{this.reconnectionStrategy.recordAttempt(),this.connect()},e)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}startHeartbeatMonitoring(){this.lastHeartbeat=Date.now(),this.heartbeatTimer=setInterval(()=>{Date.now()-this.lastHeartbeat>this.options.heartbeatTimeout&&(console.warn("[SSE] Heartbeat timeout - connection appears dead"),this.handleDisconnect())},5e3)}stopHeartbeatMonitoring(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}buildUrl(){const e=this.channels.join(",");return`/sse/stream?channels=${encodeURIComponent(e)}`}on(e,t){return this.eventHandlers.has(e)||(this.eventHandlers.set(e,new Set),this.eventSource&&this.eventSource.addEventListener(e,t=>{this.handleEvent(e,t)})),this.eventHandlers.get(e).add(t),()=>this.off(e,t)}off(e,t){const n=this.eventHandlers.get(e);n&&n.delete(t)}handleEvent(e,t){const n=this.eventHandlers.get(e);if(!n||0===n.size)return;let i;try{i=JSON.parse(t.data)}catch(s){return void console.error("[SSE] Failed to parse event data",s)}n.forEach(e=>{try{e(i,t)}catch(s){console.error("[SSE] Event handler error",s)}})}setState(e){const t=this.state;this.state=e,t!==e&&this.stateChangeHandlers.forEach(n=>{try{n(e,t)}catch(i){console.error("[SSE] State change handler error",i)}})}onStateChange(e){return this.stateChangeHandlers.add(e),()=>this.stateChangeHandlers.delete(e)}getState(){return this.state}isConnected(){return this.state===it.CONNECTED}getConnectionId(){return this.connectionId}addChannels(...e){const t=e.filter(e=>!this.channels.includes(e));t.length>0&&(this.channels.push(...t),this.isConnected()&&(console.log("[SSE] Reconnecting with new channels:",t),this.disconnect(),this.connect()))}removeChannels(...e){const t=this.channels.length;this.channels=this.channels.filter(t=>!e.includes(t)),this.channels.length!==t&&this.isConnected()&&(console.log("[SSE] Reconnecting with removed channels"),this.disconnect(),this.connect())}}let at=null;function rt(e=[]){return at||(at=new ot(e)),at}function lt(e=[],t=!0){return at=new ot(e),t&&at.connect(),at}const ct={SseClient:ot,getGlobalSseClient:rt,initSse:lt,ConnectionState:it},dt=Object.freeze(Object.defineProperty({__proto__:null,SseClient:ot,default:ct,getGlobalSseClient:rt,initSse:lt},Symbol.toStringTag,{value:"Module"}));class ht{constructor(e){this.liveComponentManager=e,this.observer=null,this.lazyComponents=new Map,this.loadingQueue=[],this.isProcessingQueue=!1,this.defaultOptions={rootMargin:"50px",threshold:.1}}init(){this.observer=new IntersectionObserver(e=>this.handleIntersection(e),this.defaultOptions),this.scanLazyComponents(),console.log(`[LazyLoader] Initialized with ${this.lazyComponents.size} lazy components`)}scanLazyComponents(){document.querySelectorAll("[data-live-component-lazy]").forEach(e=>{this.registerLazyComponent(e)});document.querySelectorAll("[data-island-component]").forEach(e=>{e.dataset.liveComponentLazy?this.registerLazyComponent(e):e.dataset.liveComponentIsland&&this.loadIslandComponentImmediately(e)})}registerLazyComponent(e){const t=e.dataset.liveComponentLazy;if(!t)return void console.warn("[LazyLoader] Lazy component missing componentId:",e);const n={element:e,componentId:t,threshold:parseFloat(e.dataset.lazyThreshold)||this.defaultOptions.threshold,priority:e.dataset.lazyPriority||"normal",placeholder:e.dataset.lazyPlaceholder||null,loaded:!1,loading:!1};n.placeholder&&this.showPlaceholder(e,n.placeholder),this.lazyComponents.set(e,n),this.observer.observe(e),console.log(`[LazyLoader] Registered lazy component: ${t}`)}handleIntersection(e){e.forEach(e=>{if(e.isIntersecting){const t=this.lazyComponents.get(e.target);!t||t.loaded||t.loading||this.queueComponentLoad(t)}})}queueComponentLoad(e){const t=this.getPriorityWeight(e.priority);this.loadingQueue.push({config:e,priority:t,timestamp:Date.now()}),this.loadingQueue.sort((e,t)=>t.priority!==e.priority?t.priority-e.priority:e.timestamp-t.timestamp),console.log(`[LazyLoader] Queued: ${e.componentId} (priority: ${e.priority})`),this.processLoadingQueue()}getPriorityWeight(e){return{high:3,normal:2,low:1}[e]||2}async processLoadingQueue(){if(!this.isProcessingQueue&&0!==this.loadingQueue.length){for(this.isProcessingQueue=!0;this.loadingQueue.length>0;){const{config:e}=this.loadingQueue.shift();e.loaded||e.loading||await this.loadComponent(e)}this.isProcessingQueue=!1}}async loadComponent(e){e.loading=!0;try{console.log(`[LazyLoader] Loading: ${e.componentId}`),this.showLoadingIndicator(e.element);const t="true"===e.element.dataset.islandComponent,n=t?`/live-component/${e.componentId}/island`:`/live-component/${e.componentId}/lazy-load`,i=await fetch(n,{method:"GET",headers:{"X-Requested-With":"XMLHttpRequest",Accept:"application/json"}});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);const s=await i.json();if(!s.success)throw new Error(s.error||"Failed to load component");if(e.element.innerHTML=s.html,e.element.setAttribute("data-live-component",e.componentId),e.element.removeAttribute("data-live-component-lazy"),t&&e.element.setAttribute("data-island-component","true"),s.csrf_token&&(e.element.dataset.csrfToken=s.csrf_token),s.state){const t=JSON.stringify(s.state);e.element.dataset.state=t}this.liveComponentManager.init(e.element,{isolated:t}),e.loaded=!0,e.loading=!1,this.observer.unobserve(e.element),console.log(`[LazyLoader] Loaded: ${e.componentId}${t?" (Island)":""}`),e.element.dispatchEvent(new CustomEvent("livecomponent:lazy:loaded",{detail:{componentId:e.componentId,isIsland:t}}))}catch(t){console.error(`[LazyLoader] Failed to load ${e.componentId}:`,t),e.loading=!1,this.showError(e.element,t.message),e.element.dispatchEvent(new CustomEvent("livecomponent:lazy:error",{detail:{componentId:e.componentId,error:t.message}}))}}async loadIslandComponentImmediately(e){const t=e.dataset.liveComponentIsland;if(t)try{console.log(`[LazyLoader] Loading Island immediately: ${t}`),this.showLoadingIndicator(e);const n=await fetch(`/live-component/${t}/island`,{method:"GET",headers:{"X-Requested-With":"XMLHttpRequest",Accept:"application/json"}});if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`);const i=await n.json();if(!i.success)throw new Error(i.error||"Failed to load Island component");if(e.innerHTML=i.html,e.setAttribute("data-live-component",t),e.setAttribute("data-island-component","true"),e.removeAttribute("data-live-component-island"),i.csrf_token&&(e.dataset.csrfToken=i.csrf_token),i.state){const t=JSON.stringify(i.state);e.dataset.state=t}this.liveComponentManager.init(e,{isolated:!0}),console.log(`[LazyLoader] Loaded Island: ${t}`),e.dispatchEvent(new CustomEvent("livecomponent:island:loaded",{detail:{componentId:t}}))}catch(n){console.error(`[LazyLoader] Failed to load Island ${t}:`,n),this.showError(e,n.message),e.dispatchEvent(new CustomEvent("livecomponent:island:error",{detail:{componentId:t,error:n.message}}))}else console.warn("[LazyLoader] Island component missing componentId:",e)}showPlaceholder(e,t){e.innerHTML=`\n <div class="livecomponent-lazy-placeholder" style="\n padding: 2rem;\n text-align: center;\n color: #666;\n background: #f5f5f5;\n border-radius: 8px;\n border: 1px dashed #ddd;\n ">\n <div style="font-size: 1.5rem; margin-bottom: 0.5rem;">⏳</div>\n <div>${t}</div>\n </div>\n `}showLoadingIndicator(e){e.innerHTML='\n <div class="livecomponent-lazy-loading" style="\n padding: 2rem;\n text-align: center;\n color: #2196F3;\n background: #f5f5f5;\n border-radius: 8px;\n border: 1px solid #e3f2fd;\n ">\n <div class="spinner" style="\n width: 40px;\n height: 40px;\n margin: 0 auto 1rem;\n border: 4px solid #e3f2fd;\n border-top: 4px solid #2196F3;\n border-radius: 50%;\n animation: spin 1s linear infinite;\n "></div>\n <div>Loading component...</div>\n </div>\n <style>\n @keyframes spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n </style>\n '}showError(e,t){e.innerHTML=`\n <div class="livecomponent-lazy-error" style="\n padding: 2rem;\n text-align: center;\n color: #d32f2f;\n background: #ffebee;\n border-radius: 8px;\n border: 1px solid #ef9a9a;\n ">\n <div style="font-size: 1.5rem; margin-bottom: 0.5rem;">❌</div>\n <div><strong>Failed to load component</strong></div>\n <div style="margin-top: 0.5rem; font-size: 0.9rem; color: #c62828;">\n ${t}\n </div>\n </div>\n `}unregister(e){const t=this.lazyComponents.get(e);t&&(this.observer.unobserve(e),this.lazyComponents.delete(e),console.log(`[LazyLoader] Unregistered: ${t.componentId}`))}destroy(){this.observer&&(this.observer.disconnect(),this.observer=null),this.loadingQueue=[],this.lazyComponents.clear(),console.log("[LazyLoader] Destroyed")}getStats(){let e=0,t=0,n=0;return this.lazyComponents.forEach(i=>{i.loaded?e++:i.loading?t++:n++}),{total:this.lazyComponents.size,loaded:e,loading:t,pending:n,queued:this.loadingQueue.length}}}class ut{constructor(e){this.liveComponentManager=e,this.hierarchyRegistry=new Map,this.childrenRegistry=new Map,this.bubbleCallbacks=new Map}init(){this.scanNestedComponents(),console.log(`[NestedComponents] Initialized with ${this.hierarchyRegistry.size} components`)}scanNestedComponents(){document.querySelectorAll("[data-parent-component]").forEach(e=>{const t=e.dataset.liveComponent,n=e.dataset.parentComponent,i=parseInt(e.dataset.nestingDepth)||1;t&&n&&this.registerHierarchy(t,n,i)});document.querySelectorAll("[data-live-component]:not([data-parent-component])").forEach(e=>{const t=e.dataset.liveComponent;t&&!this.hierarchyRegistry.has(t)&&this.registerRoot(t)})}registerRoot(e){this.hierarchyRegistry.set(e,{parentId:null,childIds:[],depth:0,path:[e]}),console.log(`[NestedComponents] Registered root: ${e}`)}registerHierarchy(e,t,n=1){const i=this.hierarchyRegistry.get(t),s=i?i.path:[t];this.hierarchyRegistry.set(e,{parentId:t,childIds:[],depth:n,path:[...s,e]}),this.childrenRegistry.has(t)||this.childrenRegistry.set(t,[]);const o=this.childrenRegistry.get(t);o.includes(e)||o.push(e),console.log(`[NestedComponents] Registered child: ${e} (parent: ${t}, depth: ${n})`)}registerDynamicChild(e,t){const n=this.hierarchyRegistry.get(t);if(!n)return void console.warn(`[NestedComponents] Cannot register child - parent not found: ${t}`);const i=n.depth+1;this.registerHierarchy(e,t,i)}getHierarchy(e){return this.hierarchyRegistry.get(e)||null}getParentId(e){const t=this.getHierarchy(e);return t?t.parentId:null}getChildIds(e){return this.childrenRegistry.get(e)||[]}hasChildren(e){return this.getChildIds(e).length>0}isRoot(e){const t=this.getHierarchy(e);return!t||null===t.parentId}getDepth(e){const t=this.getHierarchy(e);return t?t.depth:0}getAncestors(e){const t=this.getHierarchy(e);if(!t||!t.path)return[];const n=[...t.path];return n.pop(),n.reverse()}bubbleEvent(e,t,n){console.log(`[NestedComponents] Bubbling event: ${t} from ${e}`,n);let i=e,s=0;for(;;){const o=this.getParentId(i);if(null===o)return console.log(`[NestedComponents] Event bubbled to root (${s} levels)`),!0;const a=document.querySelector(`[data-live-component="${o}"]`);if(!a)return console.warn(`[NestedComponents] Parent element not found: ${o}`),!1;const r=new CustomEvent(`livecomponent:child:${t}`,{detail:{sourceId:e,eventName:t,payload:n,currentLevel:s},bubbles:!1,cancelable:!0});if(!a.dispatchEvent(r))return console.log(`[NestedComponents] Event bubbling stopped at ${o}`),!1;const l=this.bubbleCallbacks.get(o);if(l)for(const i of l){if(!1===i(e,t,n))return console.log(`[NestedComponents] Event bubbling stopped by callback at ${o}`),!1}i=o,s++}}onChildEvent(e,t){this.bubbleCallbacks.has(e)||this.bubbleCallbacks.set(e,[]),this.bubbleCallbacks.get(e).push(t),console.log(`[NestedComponents] Registered child event callback for ${e}`)}syncStateToChildren(e,t){const n=this.getChildIds(e);console.log(`[NestedComponents] Syncing state to ${n.length} children of ${e}`),n.forEach(n=>{const i=document.querySelector(`[data-live-component="${n}"]`);i&&i.dispatchEvent(new CustomEvent("livecomponent:parent:state-sync",{detail:{parentId:e,sharedState:t}}))})}async updateChildren(e,t){const n=this.getChildIds(e);console.log(`[NestedComponents] Updating ${n.length} children of ${e}`);const i=n.map(async n=>{const i=document.querySelector(`[data-live-component="${n}"]`);i&&i.dispatchEvent(new CustomEvent("livecomponent:parent:update",{detail:{parentId:e,updates:t}}))});await Promise.all(i)}unregister(e){const t=this.hierarchyRegistry.get(e);if(this.hierarchyRegistry.delete(e),t&&t.parentId){const n=this.childrenRegistry.get(t.parentId);if(n){const t=n.indexOf(e);-1!==t&&n.splice(t,1)}}this.childrenRegistry.delete(e),this.bubbleCallbacks.delete(e),console.log(`[NestedComponents] Unregistered: ${e}`)}getStats(){let e=0,t=0;return this.hierarchyRegistry.forEach(n=>{null===n.parentId&&e++,t=Math.max(t,n.depth)}),{total_components:this.hierarchyRegistry.size,root_components:e,child_components:this.hierarchyRegistry.size-e,max_nesting_depth:t,parents_with_children:this.childrenRegistry.size}}destroy(){this.hierarchyRegistry.clear(),this.childrenRegistry.clear(),this.bubbleCallbacks.clear(),console.log("[NestedComponents] Destroyed")}}class pt{constructor(e,t){this.file=e,this.fileId=t,this.uploadedBytes=0,this.totalBytes=e.size,this.status="pending",this.error=null,this.xhr=null,this.startTime=null,this.endTime=null}get percentage(){return 0===this.totalBytes?100:Math.round(this.uploadedBytes/this.totalBytes*100)}get isComplete(){return"complete"===this.status}get hasError(){return"error"===this.status}get isUploading(){return"uploading"===this.status}get uploadSpeed(){if(!this.startTime||!this.isUploading)return 0;const e=(Date.now()-this.startTime)/1e3;return e>0?this.uploadedBytes/e:0}get remainingTime(){const e=this.uploadSpeed;if(0===e)return 0;return(this.totalBytes-this.uploadedBytes)/e}updateProgress(e,t){this.uploadedBytes=e,this.totalBytes=t}setStatus(e,t=null){this.status=e,this.error=t,"uploading"!==e||this.startTime||(this.startTime=Date.now()),"complete"!==e&&"error"!==e||(this.endTime=Date.now())}abort(){this.xhr&&(this.xhr.abort(),this.setStatus("error","Upload cancelled"))}toObject(){return{fileId:this.fileId,fileName:this.file.name,fileSize:this.totalBytes,uploadedBytes:this.uploadedBytes,percentage:this.percentage,status:this.status,error:this.error,uploadSpeed:this.uploadSpeed,remainingTime:this.remainingTime}}}class mt{constructor(e={}){this.maxFileSize=e.maxFileSize||10485760,this.allowedMimeTypes=e.allowedMimeTypes||[],this.allowedExtensions=e.allowedExtensions||[],this.minFileSize=e.minFileSize||1}validate(e){const t=[];if(e.size>this.maxFileSize&&t.push(`File size (${this.formatBytes(e.size)}) exceeds maximum allowed size (${this.formatBytes(this.maxFileSize)})`),e.size<this.minFileSize&&t.push(`File size is too small (minimum: ${this.formatBytes(this.minFileSize)})`),this.allowedMimeTypes.length>0&&!this.allowedMimeTypes.includes(e.type)&&t.push(`File type "${e.type}" is not allowed. Allowed types: ${this.allowedMimeTypes.join(", ")}`),this.allowedExtensions.length>0){const n=e.name.split(".").pop().toLowerCase();this.allowedExtensions.includes(n)||t.push(`File extension ".${n}" is not allowed. Allowed extensions: ${this.allowedExtensions.join(", ")}`)}return e.name.length>255&&t.push("File name is too long (maximum 255 characters)"),t}isValid(e){return 0===this.validate(e).length}formatBytes(e){if(0===e)return"0 B";const t=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,t)*100)/100+" "+["B","KB","MB","GB"][t]}}class gt{constructor(e,t={}){this.element=e,this.onFilesDropped=t.onFilesDropped||(()=>{}),this.onDragEnter=t.onDragEnter||(()=>{}),this.onDragLeave=t.onDragLeave||(()=>{}),this.dragCounter=0,this.isActive=!1,this.bindEvents()}bindEvents(){["dragenter","dragover","dragleave","drop"].forEach(e=>{this.element.addEventListener(e,e=>{e.preventDefault(),e.stopPropagation()})}),this.element.addEventListener("dragenter",e=>{this.dragCounter++,1===this.dragCounter&&(this.isActive=!0,this.element.classList.add("drag-over"),this.onDragEnter(e))}),this.element.addEventListener("dragleave",e=>{this.dragCounter--,0===this.dragCounter&&(this.isActive=!1,this.element.classList.remove("drag-over"),this.onDragLeave(e))}),this.element.addEventListener("dragover",e=>{}),this.element.addEventListener("drop",e=>{var t;this.dragCounter=0,this.isActive=!1,this.element.classList.remove("drag-over");const n=Array.from((null==(t=e.dataTransfer)?void 0:t.files)||[]);n.length>0&&this.onFilesDropped(n)})}destroy(){this.element.classList.remove("drag-over")}}class ft{constructor(e,t={}){this.componentElement=e,this.componentId=e.dataset.liveId,this.maxFileSize=t.maxFileSize||10485760,this.allowedMimeTypes=t.allowedMimeTypes||[],this.allowedExtensions=t.allowedExtensions||[],this.maxFiles=t.maxFiles||10,this.autoUpload=!1!==t.autoUpload,this.multiple=!1!==t.multiple,this.endpoint=t.endpoint||`/live-component/${this.componentId}/upload`,this.onFileAdded=t.onFileAdded||(()=>{}),this.onFileRemoved=t.onFileRemoved||(()=>{}),this.onUploadStart=t.onUploadStart||(()=>{}),this.onUploadProgress=t.onUploadProgress||(()=>{}),this.onUploadComplete=t.onUploadComplete||(()=>{}),this.onUploadError=t.onUploadError||(()=>{}),this.onAllUploadsComplete=t.onAllUploadsComplete||(()=>{}),this.files=new Map,this.uploadQueue=[],this.activeUploads=0,this.maxConcurrentUploads=t.maxConcurrentUploads||2,this.validator=new mt({maxFileSize:this.maxFileSize,allowedMimeTypes:this.allowedMimeTypes,allowedExtensions:this.allowedExtensions}),this.dropZoneElement=t.dropZone,this.fileInputElement=t.fileInput,this.initialize()}initialize(){this.dropZoneElement&&(this.dragDropZone=new gt(this.dropZoneElement,{onFilesDropped:e=>this.addFiles(e),onDragEnter:()=>this.dropZoneElement.classList.add("drag-active"),onDragLeave:()=>this.dropZoneElement.classList.remove("drag-active")})),this.fileInputElement&&this.fileInputElement.addEventListener("change",e=>{const t=Array.from(e.target.files||[]);this.addFiles(t),e.target.value=""})}addFiles(e){const t=Array.isArray(e)?e:[e];if(this.files.size+t.length>this.maxFiles){const e=`Cannot add files. Maximum ${this.maxFiles} files allowed.`;return void this.onUploadError({error:e,fileCount:t.length})}for(const n of t){const e=this.generateFileId(n),t=this.validator.validate(n),i=new pt(n,e);t.length>0?(i.setStatus("error",t.join(", ")),this.files.set(e,i),this.onUploadError({fileId:e,file:n,errors:t})):(this.files.set(e,i),this.uploadQueue.push(e),this.onFileAdded({fileId:e,file:n,progress:i.toObject()}))}this.autoUpload&&this.processQueue()}removeFile(e){const t=this.files.get(e);if(!t)return;t.isUploading&&t.abort();const n=this.uploadQueue.indexOf(e);-1!==n&&this.uploadQueue.splice(n,1),this.files.delete(e),this.onFileRemoved({fileId:e,file:t.file})}uploadAll(){this.processQueue()}async processQueue(){for(;this.uploadQueue.length>0&&this.activeUploads<this.maxConcurrentUploads;){const e=this.uploadQueue.shift(),t=this.files.get(e);t&&"pending"===t.status&&(this.activeUploads++,this.uploadFile(e).finally(()=>{this.activeUploads--,this.processQueue(),0===this.activeUploads&&0===this.uploadQueue.length&&this.onAllUploadsComplete({totalFiles:this.files.size,successCount:Array.from(this.files.values()).filter(e=>e.isComplete).length,errorCount:Array.from(this.files.values()).filter(e=>e.hasError).length})}))}}async uploadFile(e){const t=this.files.get(e);if(t)try{const n=this.getComponentState(),i=await this.getCsrfTokens(),s=new FormData;s.append("file",t.file),s.append("state",JSON.stringify(n)),s.append("params",JSON.stringify({fileId:e}));const o=new XMLHttpRequest;t.xhr=o,o.upload.addEventListener("progress",n=>{n.lengthComputable&&(t.updateProgress(n.loaded,n.total),this.onUploadProgress({fileId:e,...t.toObject()}))});const a=new Promise((n,i)=>{o.addEventListener("load",()=>{if(o.status>=200&&o.status<300)try{const i=JSON.parse(o.responseText);if(!i.success)throw new Error(i.error||"Upload failed");t.setStatus("complete"),i.state&&this.updateComponentState(i.state),i.html&&this.updateComponentHtml(i.html),this.onUploadComplete({fileId:e,file:t.file,response:i}),n(i)}catch(s){i(s)}else i(new Error(`Upload failed with status ${o.status}`))}),o.addEventListener("error",()=>{i(new Error("Network error during upload"))}),o.addEventListener("abort",()=>{i(new Error("Upload cancelled"))})});t.setStatus("uploading"),this.onUploadStart({fileId:e,file:t.file}),o.open("POST",this.endpoint),o.setRequestHeader("X-CSRF-Form-ID",i.form_id),o.setRequestHeader("X-CSRF-Token",i.token),o.setRequestHeader("Accept","application/json"),o.setRequestHeader("User-Agent",navigator.userAgent),o.send(s),await a}catch(n){t.setStatus("error",n.message),this.onUploadError({fileId:e,file:t.file,error:n.message})}}cancelAll(){this.uploadQueue=[],this.files.forEach(e=>{e.isUploading&&e.abort()})}clearAll(){this.cancelAll(),this.files.clear()}getOverallProgress(){if(0===this.files.size)return 100;const e=Array.from(this.files.values()).reduce((e,t)=>e+t.totalBytes,0),t=Array.from(this.files.values()).reduce((e,t)=>e+t.uploadedBytes,0);return e>0?Math.round(t/e*100):0}getStats(){const e=Array.from(this.files.values());return{total:e.length,pending:e.filter(e=>"pending"===e.status).length,uploading:e.filter(e=>"uploading"===e.status).length,complete:e.filter(e=>"complete"===e.status).length,error:e.filter(e=>"error"===e.status).length,overallProgress:this.getOverallProgress()}}generateFileId(e){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}-${e.name}`}async getCsrfTokens(){try{const e=await fetch(`/api/csrf/token?action=${encodeURIComponent(this.endpoint)}&method=post`,{headers:{Accept:"application/json","User-Agent":navigator.userAgent}});if(!e.ok)throw new Error(`CSRF token request failed: ${e.status}`);return await e.json()}catch(e){throw console.error("Failed to get CSRF tokens:",e),e}}getComponentState(){const e=this.componentElement.querySelector("[data-live-state]");if(e)try{return JSON.parse(e.textContent||"{}")}catch(t){console.warn("Failed to parse component state:",t)}return{}}updateComponentState(e){const t=this.componentElement.querySelector("[data-live-state]");t&&(t.textContent=JSON.stringify(e))}updateComponentHtml(e){const t=this.componentElement.querySelector("[data-live-content]")||this.componentElement;t&&(t.innerHTML=e)}destroy(){this.cancelAll(),this.clearAll(),this.dragDropZone&&this.dragDropZone.destroy()}}const yt=new class{constructor(){this.pendingOperations=new Map,this.snapshots=new Map,this.conflictHandlers=new Map,this.operationIdCounter=0}applyOptimisticUpdate(e,t,n,i={}){this.snapshots.has(e)||this.createSnapshot(e,t);const s=t.version||1,o={...n(t),version:s+1},a={id:this.generateOperationId(),componentId:e,metadata:i,expectedVersion:s,optimisticState:o,timestamp:Date.now(),status:"pending"};return this.addPendingOperation(e,a),console.log(`[OptimisticUI] Applied optimistic update for ${e}`,{version:`${s} → ${s+1}`,operationId:a.id,pendingCount:this.getPendingOperationsCount(e)}),o}confirmOperation(e,t,n){const i=this.getPendingOperation(e,t);return i?(i.status="confirmed",this.removePendingOperation(e,t),console.log(`[OptimisticUI] Confirmed operation ${t} for ${e}`,{pendingCount:this.getPendingOperationsCount(e)}),this.hasPendingOperations(e)||this.clearSnapshot(e),n):(console.warn(`[OptimisticUI] Cannot confirm unknown operation: ${t}`),n)}handleConflict(e,t,n,i={}){const s=this.getPendingOperation(e,t);if(!s)return console.warn(`[OptimisticUI] Cannot handle conflict for unknown operation: ${t}`),{state:n,notification:null};s.status="failed";const o=this.snapshots.get(e);console.warn(`[OptimisticUI] Version conflict detected for ${e}`,{operationId:t,expectedVersion:s.expectedVersion,serverVersion:n.version,metadata:s.metadata,pendingOperationsCount:this.getPendingOperationsCount(e)}),this.clearPendingOperations(e),this.clearSnapshot(e);const a=this.conflictHandlers.get(e);a&&a({operation:s,serverState:n,snapshotState:null==o?void 0:o.state,conflict:i});return{state:n,notification:{type:"conflict",title:"Update Conflict",message:"Your changes conflicted with another update. The latest version has been loaded.",action:s.metadata.action||"unknown",canRetry:!0,operation:s}}}createSnapshot(e,t){this.snapshots.set(e,{state:JSON.parse(JSON.stringify(t)),timestamp:Date.now()}),console.log(`[OptimisticUI] Created snapshot for ${e}`,{version:t.version})}clearSnapshot(e){this.snapshots.get(e)&&(this.snapshots.delete(e),console.log(`[OptimisticUI] Cleared snapshot for ${e}`))}getSnapshot(e){const t=this.snapshots.get(e);return t?t.state:null}addPendingOperation(e,t){this.pendingOperations.has(e)||this.pendingOperations.set(e,[]),this.pendingOperations.get(e).push(t)}removePendingOperation(e,t){const n=this.pendingOperations.get(e);if(!n)return;const i=n.findIndex(e=>e.id===t);-1!==i&&n.splice(i,1),0===n.length&&this.pendingOperations.delete(e)}getPendingOperation(e,t){const n=this.pendingOperations.get(e);return n&&n.find(e=>e.id===t)||null}getPendingOperations(e){return this.pendingOperations.get(e)||[]}getPendingOperationsCount(e){const t=this.pendingOperations.get(e);return t?t.length:0}hasPendingOperations(e){return this.getPendingOperationsCount(e)>0}clearPendingOperations(e){this.pendingOperations.delete(e)}registerConflictHandler(e,t){this.conflictHandlers.set(e,t)}unregisterConflictHandler(e){this.conflictHandlers.delete(e)}generateOperationId(){return`op-${++this.operationIdCounter}-${Date.now()}`}async retryOperation(e,t,n){console.log(`[OptimisticUI] Retrying operation ${t.id} for ${e}`);try{const e=await n(t.metadata);return console.log(`[OptimisticUI] Retry succeeded for ${t.id}`),e}catch(i){throw console.error(`[OptimisticUI] Retry failed for ${t.id}:`,i),i}}getStats(){const e={total_components:this.pendingOperations.size,total_pending_operations:0,total_snapshots:this.snapshots.size,components:{}};return this.pendingOperations.forEach((t,n)=>{e.total_pending_operations+=t.length,e.components[n]={pending:t.length,has_snapshot:this.snapshots.has(n)}}),e}clear(){this.pendingOperations.clear(),this.snapshots.clear(),this.conflictHandlers.clear(),this.operationIdCounter=0,console.log("[OptimisticUI] Cleared all state")}};const vt=new class{constructor(){this.liveRegion=null,this.componentLiveRegions=new Map,this.focusStates=new Map,this.announcementQueue=[],this.announceTimer=null,this.throttleDelay=500}initialize(){this.liveRegion||(this.liveRegion=this.createLiveRegion("livecomponent-announcer","polite"),document.body.appendChild(this.liveRegion)),console.log("[AccessibilityManager] Initialized with ARIA live regions")}createLiveRegion(e,t="polite"){const n=document.createElement("div");return n.id=e,n.setAttribute("role","status"),n.setAttribute("aria-live",t),n.setAttribute("aria-atomic","true"),n.className="sr-only",n.style.position="absolute",n.style.left="-10000px",n.style.width="1px",n.style.height="1px",n.style.overflow="hidden",n}createComponentLiveRegion(e,t,n="polite"){let i=this.componentLiveRegions.get(e);return i||(i=this.createLiveRegion(`livecomponent-${e}-announcer`,n),t.appendChild(i),this.componentLiveRegions.set(e,i)),i}announce(e,t="polite",n=null){this.announcementQueue.push({message:e,priority:t,componentId:n}),this.announceTimer&&clearTimeout(this.announceTimer),this.announceTimer=setTimeout(()=>{this.flushAnnouncements()},this.throttleDelay)}flushAnnouncements(){if(0===this.announcementQueue.length)return;const e=this.announcementQueue[this.announcementQueue.length-1];this.announcementQueue=[];let t=this.liveRegion;if(e.componentId){const n=this.componentLiveRegions.get(e.componentId);n&&(t=n)}t?("assertive"===e.priority?t.setAttribute("aria-live","assertive"):t.setAttribute("aria-live","polite"),t.textContent="",setTimeout(()=>{t.textContent=e.message},100),console.log(`[AccessibilityManager] Announced: "${e.message}" (${e.priority})`)):console.warn("[AccessibilityManager] No live region available for announcement")}captureFocusState(e,t){const n=document.activeElement;if(!n||!t.contains(n))return null;const i={selector:this.getElementSelector(n,t),tagName:n.tagName,name:n.name||null,id:n.id||null,selectionStart:n.selectionStart||null,selectionEnd:n.selectionEnd||null,scrollTop:n.scrollTop||0,scrollLeft:n.scrollLeft||0,keepFocus:n.hasAttribute("data-lc-keep-focus")};return this.focusStates.set(e,i),console.log(`[AccessibilityManager] Captured focus state for ${e}`,i),i}restoreFocus(e,t){const n=this.focusStates.get(e);if(!n)return!1;try{let e=null;if(n.keepFocus&&(e=t.querySelector("[data-lc-keep-focus]")),!e&&n.selector&&(e=t.querySelector(n.selector)),!e&&n.id&&(e=t.querySelector(`#${n.id}`)),!e&&n.name&&(e=t.querySelector(`[name="${n.name}"]`)),e&&e.focus)return e.focus(),e.setSelectionRange&&null!==n.selectionStart&&null!==n.selectionEnd&&e.setSelectionRange(n.selectionStart,n.selectionEnd),n.scrollTop>0&&(e.scrollTop=n.scrollTop),n.scrollLeft>0&&(e.scrollLeft=n.scrollLeft),console.log(`[AccessibilityManager] Restored focus to ${n.selector}`),!0}catch(i){console.debug("[AccessibilityManager] Could not restore focus:",i)}finally{this.focusStates.delete(e)}return!1}getElementSelector(e,t){if(e.id)return`#${e.id}`;if(e.name)return`[name="${e.name}"]`;const n=e.getAttribute("data-lc-key");if(n)return`[data-lc-key="${n}"]`;const i=[];let s=e;for(;s&&s!==t&&s!==document.body;){let e=s.tagName.toLowerCase();if(s.className&&"string"==typeof s.className){const t=s.className.split(" ").filter(e=>e.trim());t.length>0&&(e+="."+t.join("."))}if(s.parentElement){const t=Array.from(s.parentElement.children),n=t.indexOf(s)+1;t.length>1&&(e+=`:nth-child(${n})`)}i.unshift(e),s=s.parentElement}return i.length>0?i.join(" > "):null}announceUpdate(e,t,n={}){let i="";switch(t){case"fragment":i=`Updated ${n.fragmentName||"content"}`;break;case"full":i="Component updated";break;case"action":i=n.actionMessage||"Action completed";break;default:i="Content updated"}this.announce(i,"polite",e)}shouldPreserveKeyboardNav(e){if(["INPUT","TEXTAREA","SELECT","BUTTON","A"].includes(e.tagName))return!0;if(e.hasAttribute("tabindex"))return!0;const t=e.getAttribute("role");return!(!t||!["button","link","textbox","searchbox","combobox","listbox","option","tab"].includes(t))}cleanup(e){const t=this.componentLiveRegions.get(e);t&&t.parentElement&&t.parentElement.removeChild(t),this.componentLiveRegions.delete(e),this.focusStates.delete(e),console.log(`[AccessibilityManager] Cleaned up accessibility for ${e}`)}getStats(){return{has_global_live_region:null!==this.liveRegion,component_live_regions:this.componentLiveRegions.size,tracked_focus_states:this.focusStates.size,pending_announcements:this.announcementQueue.length}}};class bt{constructor(e){this.manager=e,this.retryStrategies=new Map,this.errorHandlers=new Map,this.maxRetries=3,this.retryDelays=[1e3,2e3,5e3]}async handleError(e,t,n,i={}){console.error(`[ErrorBoundary] Error in ${e}.${t}:`,n);const s=this.standardizeError(n,e,t),o=this.errorHandlers.get(e);if(o)try{if(await o(s,i))return!0}catch(a){console.error("[ErrorBoundary] Error handler failed:",a)}if(this.isRetryable(s)){if(await this.retryOperation(e,t,i,s))return!0}return this.showError(e,s),this.dispatchErrorEvent(e,s),!1}standardizeError(e,t,n){return e&&"object"==typeof e&&"code"in e&&"message"in e?{code:e.code,message:e.message,details:e.details||{},componentId:e.componentId||t,action:e.action||n,timestamp:e.timestamp||Date.now()}:e instanceof Error?{code:"INTERNAL_ERROR",message:e.message,details:{stack:e.stack,name:e.name},componentId:t,action:n,timestamp:Date.now()}:"string"==typeof e?{code:"INTERNAL_ERROR",message:e,componentId:t,action:n,timestamp:Date.now()}:{code:"INTERNAL_ERROR",message:"An unknown error occurred",details:{original:e},componentId:t,action:n,timestamp:Date.now()}}isRetryable(e){return["RATE_LIMIT_EXCEEDED","STATE_CONFLICT","INTERNAL_ERROR"].includes(e.code)}async retryOperation(e,t,n,i){const s=`${e}:${t}`,o=this.retryStrategies.get(s)||0;if(o>=this.maxRetries)return console.warn(`[ErrorBoundary] Max retries exceeded for ${s}`),this.retryStrategies.delete(s),!1;const a=this.retryDelays[o]||this.retryDelays[this.retryDelays.length-1];console.log(`[ErrorBoundary] Retrying ${s} in ${a}ms (attempt ${o+1}/${this.maxRetries})`),this.retryStrategies.set(s,o+1),await new Promise(e=>setTimeout(e,a));try{await this.manager.executeAction(e,t,n.params||{},n.fragments||null);return this.retryStrategies.delete(s),console.log(`[ErrorBoundary] Retry succeeded for ${s}`),!0}catch(r){return console.warn(`[ErrorBoundary] Retry failed for ${s}:`,r),!1}}showError(e,t){const n=this.manager.components.get(e);if(!n)return;const i=n.element.querySelector(".livecomponent-error-boundary");i&&i.remove();const s=document.createElement("div");s.className="livecomponent-error-boundary",s.style.cssText="\n padding: 1rem;\n background: #fee;\n color: #c00;\n border: 1px solid #faa;\n border-radius: 4px;\n margin-bottom: 1rem;\n ";const o=document.createElement("div");if(o.style.fontWeight="bold",o.textContent=t.message,s.appendChild(o),"INTERNAL_ERROR"!==t.code){const e=document.createElement("div");e.style.fontSize="0.875rem",e.style.marginTop="0.5rem",e.style.color="#666",e.textContent=`Error Code: ${t.code}`,s.appendChild(e)}if(this.isRetryable(t)){const n=document.createElement("button");n.textContent="Retry",n.style.cssText="\n margin-top: 0.5rem;\n padding: 0.5rem 1rem;\n background: #c00;\n color: white;\n border: none;\n border-radius: 4px;\n cursor: pointer;\n ",n.addEventListener("click",async()=>{s.remove(),await this.retryOperation(e,t.action||"",{},t)}),s.appendChild(n)}const a=document.createElement("button");a.textContent="×",a.style.cssText="\n float: right;\n background: transparent;\n border: none;\n font-size: 1.5rem;\n cursor: pointer;\n color: #c00;\n ",a.addEventListener("click",()=>{s.remove()}),s.appendChild(a),n.element.insertAdjacentElement("afterbegin",s),setTimeout(()=>{s.parentNode&&s.remove()},1e4)}dispatchErrorEvent(e,t){const n=new CustomEvent("livecomponent:error",{detail:{componentId:e,error:t},bubbles:!0}),i=this.manager.components.get(e);i&&i.element.dispatchEvent(n),document.dispatchEvent(n)}registerErrorHandler(e,t){if("function"!=typeof t)throw new Error("Error handler must be a function");this.errorHandlers.set(e,t)}clearErrorHandler(e){this.errorHandlers.delete(e)}clearRetryStrategy(e,t){const n=`${e}:${t}`;this.retryStrategies.delete(n)}resetRetryStrategies(){this.retryStrategies.clear()}}class wt{constructor(){this.pendingRequests=new Map,this.requestCache=new Map,this.cacheTimeout=1e3}generateKey(e,t,n){const i=Object.keys(n).sort().reduce((e,t)=>(e[t]=n[t],e),{});return`${e}:${t}:${JSON.stringify(i)}`}getPendingRequest(e,t,n){const i=this.generateKey(e,t,n);return this.pendingRequests.get(i)||null}registerPendingRequest(e,t,n,i){const s=this.generateKey(e,t,n);return this.pendingRequests.set(s,i),i.then(()=>{this.pendingRequests.delete(s)}).catch(()=>{this.pendingRequests.delete(s)}),i}getCachedResult(e,t,n){const i=this.generateKey(e,t,n),s=this.requestCache.get(i);if(!s)return null;return Date.now()-s.timestamp>this.cacheTimeout?(this.requestCache.delete(i),null):s.result}cacheResult(e,t,n,i){const s=this.generateKey(e,t,n);this.requestCache.set(s,{result:i,timestamp:Date.now()}),this.cleanupCache()}cleanupCache(){const e=Date.now();for(const[t,n]of this.requestCache.entries())e-n.timestamp>this.cacheTimeout&&this.requestCache.delete(t)}clearPendingRequests(){this.pendingRequests.clear()}clearCache(){this.requestCache.clear()}clearComponent(e){for(const[t]of this.pendingRequests.entries())t.startsWith(`${e}:`)&&this.pendingRequests.delete(t);for(const[t]of this.requestCache.entries())t.startsWith(`${e}:`)&&this.requestCache.delete(t)}getStats(){return{pendingRequests:this.pendingRequests.size,cachedResults:this.requestCache.size}}}function St(e){const t=e.dataset.state;if(!t)return null;try{return function(e){if("string"!=typeof e)throw new Error("State JSON must be a string");if(""===e.trim())return{id:"",component:"",data:{},version:1};try{const t=JSON.parse(e);if(!t||"object"!=typeof t)throw new Error("Invalid state structure");const n=t.id||"",i=t.component||"",s=t.data||{},o="number"==typeof t.version?t.version:1;if("object"!=typeof s||Array.isArray(s))throw new Error("State data must be an object");return{id:n,component:i,data:s,version:o}}catch(t){if(t instanceof SyntaxError)throw new Error(`Invalid JSON format: ${t.message}`);throw t}}(t)}catch(n){return console.error("[StateSerializer] Failed to deserialize state from element:",n),null}}function Et(e,t){if(!function(e){return!(!e||"object"!=typeof e||!e.id||"string"!=typeof e.id||!e.component||"string"!=typeof e.component||"number"!=typeof e.version||e.version<1||e.data&&("object"!=typeof e.data||Array.isArray(e.data)))}(t))throw new Error("Invalid state structure");const n=function(e){if(!e||"object"!=typeof e)throw new Error("State must be an object");if(!e.id||"string"!=typeof e.id)throw new Error("State must have a valid id");if(!e.component||"string"!=typeof e.component)throw new Error("State must have a valid component name");if("number"!=typeof e.version||e.version<1)throw new Error("State must have a valid version number");const t=e.data||{};if("object"!=typeof t||Array.isArray(t))throw new Error("State data must be an object");const n={id:e.id,component:e.component,data:t,version:e.version};try{return JSON.stringify(n)}catch(i){throw new Error(`Failed to serialize state: ${i.message}`)}}(t);e.dataset.state=n}const Ct={},kt=function(e,t,n){let i=Promise.resolve();if(t&&t.length>0){let e=function(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))};document.getElementsByTagName("link");const n=document.querySelector("meta[property=csp-nonce]"),s=(null==n?void 0:n.nonce)||(null==n?void 0:n.getAttribute("nonce"));i=e(t.map(e=>{if((e=function(e){return"/"+e}(e))in Ct)return;Ct[e]=!0;const t=e.endsWith(".css"),n=t?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${e}"]${n}`))return;const i=document.createElement("link");return i.rel=t?"stylesheet":"modulepreload",t||(i.as="script"),i.crossOrigin="",i.href=e,s&&i.setAttribute("nonce",s),document.head.appendChild(i),t?new Promise((t,n)=>{i.addEventListener("load",t),i.addEventListener("error",()=>n(new Error(`Unable to preload CSS for ${e}`)))}):void 0}))}function s(e){const t=new Event("vite:preloadError",{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return i.then(t=>{for(const e of t||[])"rejected"===e.status&&s(e.reason);return e().catch(s)})};class Mt{constructor(e=5){this.maxToasts=e,this.queue=[],this.activeToasts=new Map,this.positionOffsets=new Map}add(e,t={}){const{message:n="",type:i="info",duration:s=5e3,position:o="top-right"}=t;this.activeToasts.has(e)&&this.remove(e);this.getPositionCount(o)>=this.maxToasts&&this.removeOldestAtPosition(o);const a=this.createToastElement(n,i,o,e),r=this.getNextOffset(o);this.setToastPosition(a,o,r),document.body.appendChild(a),requestAnimationFrame(()=>{a.style.opacity="1",a.style.transform="translateY(0)"}),this.activeToasts.set(e,a),this.updatePositionOffset(o,r),s>0&&setTimeout(()=>{this.remove(e)},s);const l=a.querySelector(".toast-close");return l&&l.addEventListener("click",()=>{this.remove(e)}),a}remove(e){const t=this.activeToasts.get(e);if(!t)return;t.style.opacity="0";const n=this.getToastPosition(t);t.style.transform=`translateY(${n.includes("top")?"-20px":"20px"})`,setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),this.activeToasts.delete(e),this.recalculateOffsets(n)},300)}clear(){for(const e of this.activeToasts.keys())this.remove(e)}removeOldestAtPosition(e){let t=null,n=1/0;for(const[i,s]of this.activeToasts.entries())if(this.getToastPosition(s)===e){const e=parseInt(s.dataset.timestamp||"0");e<n&&(n=e,t=i)}t&&this.remove(t)}getPositionCount(e){let t=0;for(const n of this.activeToasts.values())this.getToastPosition(n)===e&&t++;return t}getNextOffset(e){return(this.positionOffsets.get(e)||0)+80}updatePositionOffset(e,t){this.positionOffsets.set(e,t)}recalculateOffsets(e){const t=[];for(const[i,s]of this.activeToasts.entries())this.getToastPosition(s)===e&&t.push({componentId:i,toast:s});t.sort((e,t)=>e.toast.compareDocumentPosition(t.toast)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1);let n=0;for(const{toast:i}of t)this.setToastPosition(i,e,n),n+=80;this.positionOffsets.set(e,n)}createToastElement(e,t,n,i){const s=document.createElement("div");s.className=`toast-queue-toast toast-queue-toast--${t} toast-queue-toast--${n}`,s.setAttribute("role","alert"),s.setAttribute("aria-live","polite"),s.dataset.componentId=i,s.dataset.timestamp=Date.now().toString();const o={info:"#3b82f6",success:"#10b981",warning:"#f59e0b",error:"#ef4444"};return s.innerHTML=`\n <div class="toast-content">\n <span class="toast-message">${e}</span>\n <button class="toast-close" aria-label="Close">×</button>\n </div>\n `,s.style.cssText=`\n position: fixed;\n ${n.includes("top")?"top":"bottom"}: 1rem;\n ${n.includes("left")?"left":"right"}: 1rem;\n max-width: 400px;\n padding: 1rem;\n background: ${o[t]||o.info};\n color: white;\n border-radius: 0.5rem;\n box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);\n z-index: 10000;\n opacity: 0;\n transform: translateY(${n.includes("top")?"-20px":"20px"});\n transition: opacity 0.3s ease, transform 0.3s ease;\n `,s}setToastPosition(e,t,n){t.includes("top")?e.style.top=1+n/16+"rem":e.style.bottom=1+n/16+"rem"}getToastPosition(e){return e.classList.contains("toast-queue-toast--top-right")?"top-right":e.classList.contains("toast-queue-toast--top-left")?"top-left":e.classList.contains("toast-queue-toast--bottom-right")?"bottom-right":e.classList.contains("toast-queue-toast--bottom-left")?"bottom-left":"top-right"}}class xt{constructor(){this.modalStack=[],this.baseZIndex=1050,this.zIndexIncrement=10}open(e,t={}){const{title:n="",content:i="",size:s="medium",buttons:o=[],closeOnBackdrop:a=!0,closeOnEscape:r=!0}=t,l=this.baseZIndex+this.modalStack.length*this.zIndexIncrement,c=document.createElement("dialog");c.className=`livecomponent-modal livecomponent-modal--${s}`,c.id=`modal-${e}`,c.style.zIndex=l.toString(),c.innerHTML=this.createModalContent(n,i,o),document.body.appendChild(c),this.setupDialogHandlers(c,e,a,r,o),c.showModal();const d={componentId:e,dialogElement:c,zIndex:l,closeOnEscape:r,closeOnBackdrop:a};return this.modalStack.push(d),this.focusModal(c),{dialog:c,close:()=>this.close(e),isOpen:()=>c.open}}setupDialogHandlers(e,t,n,i,s){e.addEventListener("cancel",e=>{e.preventDefault(),i&&this.close(t)}),n&&e.addEventListener("click",n=>{n.target===e&&this.close(t)});const o=e.querySelector(".modal-close");o&&o.addEventListener("click",()=>{this.close(t)}),e.querySelectorAll("[data-modal-action]").forEach((e,n)=>{e.addEventListener("click",()=>{const e=s[n];e&&e.action&&"close"===e.action&&this.close(t)})})}close(e){const t=this.modalStack.findIndex(t=>t.componentId===e);if(-1===t)return;const{dialogElement:n}=this.modalStack[t];if(n&&n.open&&n.close(),n.parentNode&&n.parentNode.removeChild(n),this.modalStack.splice(t,1),this.modalStack.length>0){const e=this.modalStack[this.modalStack.length-1];this.focusModal(e.dialogElement)}else{const e=document.activeElement;e&&e!==document.body&&e.blur(),document.body.focus()}}closeAll(){for(;this.modalStack.length>0;){const{componentId:e}=this.modalStack[this.modalStack.length-1];this.close(e)}}getTopModal(){return 0===this.modalStack.length?null:this.modalStack[this.modalStack.length-1]}isOpen(e){return this.modalStack.some(t=>t.componentId===e)}focusModal(e){if(!e)return;const t=["button:not([disabled])","[href]","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(", "),n=e.querySelector(t);n?requestAnimationFrame(()=>{n.focus()}):requestAnimationFrame(()=>{e.focus()})}createModalContent(e,t,n){const i=n.map((e,t)=>`<button class="btn ${e.class||e.className||"btn-secondary"}" data-modal-action="${t}">${e.text||"Button"}</button>`).join("");return`\n <div class="livecomponent-modal-content">\n ${e?`<div class="modal-header">\n <h3 class="modal-title">${e}</h3>\n <button class="modal-close" aria-label="Close">×</button>\n </div>`:""}\n <div class="modal-body">${t}</div>\n ${n.length>0?`<div class="modal-footer">${i}</div>`:""}\n </div>\n `}destroy(){this.closeAll()}}class Tt{constructor(e){this.manager=e,this.uiManager=Ze,this.activeDialogs=new Map,this.activeNotifications=new Map,this.toastQueue=new Mt(5),this.modalManager=new xt}showDialog(e,t={}){const{title:n="",content:i="",size:s="medium",buttons:o=[],closeOnBackdrop:a=!0,closeOnEscape:r=!0,onClose:l=null,onConfirm:c=null}=t,d=this.modalManager.open(e,{title:n,content:i,size:s,buttons:o,closeOnBackdrop:a,closeOnEscape:r});if(this.activeDialogs.set(e,d),l&&d.dialog){const t=d.close;d.close=()=>{t.call(d),l(),this.activeDialogs.delete(e)}}return d}showConfirm(e,t={}){return new Promise(n=>{const{title:i="Confirm",message:s="Are you sure?",confirmText:o="Confirm",cancelText:a="Cancel",confirmClass:r="btn-primary",cancelClass:l="btn-secondary"}=t,c=[{text:a,class:l,action:()=>{this.closeDialog(e),n(!1)}},{text:o,class:r,action:()=>{this.closeDialog(e),n(!0)}}];this.showDialog(e,{title:i,content:`<p>${s}</p>`,buttons:c,size:"small"})})}showAlert(e,t={}){const{title:n="Alert",message:i="",buttonText:s="OK",type:o="info"}=t,a=[{text:s,class:`btn-${o}`,action:()=>{this.closeDialog(e)}}];return this.showDialog(e,{title:n,content:`<p class="alert-message alert-message--${o}">${i}</p>`,buttons:a,size:"small"})}closeDialog(e){this.modalManager.close(e),this.activeDialogs.delete(e)}showNotification(e,t={}){const{message:n="",type:i="info",duration:s=5e3,position:o="top-right",action:a=null}=t,r=this.toastQueue.add(e,{message:n,type:i,duration:s,position:o});return r&&this.activeNotifications.set(e,r),r}hideNotification(e){var t;const n="string"==typeof e?e:null==(t=e.dataset)?void 0:t.componentId;n&&(this.toastQueue.remove(n),this.activeNotifications.delete(n))}createDialogContent(e,t,n,i){const s=n.map((e,t)=>{const n=e.class||"btn-secondary";return e.action,`<button class="btn ${n}" data-dialog-action="${t}">${e.text||"Button"}</button>`}).join("");return`\n <div class="livecomponent-dialog-content">\n ${e?`<div class="dialog-header"><h3>${e}</h3></div>`:""}\n <div class="dialog-body">${t}</div>\n ${n.length>0?`<div class="dialog-footer">${s}</div>`:""}\n </div>\n `}getNotificationColor(e){const t={info:"#3b82f6",success:"#10b981",warning:"#f59e0b",error:"#ef4444"};return t[e]||t.info}showLoadingDialog(e,t="Loading..."){return this.showDialog(e,{title:"",content:`\n <div class="loading-dialog">\n <div class="spinner"></div>\n <p>${t}</p>\n </div>\n `,size:"small",buttons:[],closeOnBackdrop:!1,closeOnEscape:!1})}cleanup(e){this.closeDialog(e),this.hideNotification(e)}}class At{constructor(e){this.manager=e,this.uiHelper=e.uiHelper||new Tt(e),this.eventListeners=new Map,this.isInitialized=!1,this.drawerManager=null,this.popoverManager=null}init(){this.isInitialized||(this.addEventListener("toast:show",e=>this.handleToastShow(e)),this.addEventListener("toast:hide",e=>this.handleToastHide(e)),this.addEventListener("modal:show",e=>this.handleModalShow(e)),this.addEventListener("modal:close",e=>this.handleModalClose(e)),this.addEventListener("modal:confirm",e=>this.handleModalConfirm(e)),this.addEventListener("modal:alert",e=>this.handleModalAlert(e)),this.addEventListener("livecomponent:toast:show",e=>this.handleToastShow(e)),this.addEventListener("livecomponent:toast:hide",e=>this.handleToastHide(e)),this.addEventListener("livecomponent:modal:show",e=>this.handleModalShow(e)),this.addEventListener("livecomponent:modal:close",e=>this.handleModalClose(e)),this.addEventListener("livecomponent:modal:confirm",e=>this.handleModalConfirm(e)),this.addEventListener("livecomponent:modal:alert",e=>this.handleModalAlert(e)),this.addEventListener("drawer:open",e=>this.handleDrawerOpen(e)),this.addEventListener("drawer:close",e=>this.handleDrawerClose(e)),this.addEventListener("drawer:toggle",e=>this.handleDrawerToggle(e)),this.addEventListener("livecomponent:drawer:open",e=>this.handleDrawerOpen(e)),this.addEventListener("livecomponent:drawer:close",e=>this.handleDrawerClose(e)),this.addEventListener("livecomponent:drawer:toggle",e=>this.handleDrawerToggle(e)),this.addEventListener("popover:show",e=>this.handlePopoverShow(e)),this.addEventListener("popover:hide",e=>this.handlePopoverHide(e)),this.addEventListener("popover:toggle",e=>this.handlePopoverToggle(e)),this.addEventListener("livecomponent:popover:show",e=>this.handlePopoverShow(e)),this.addEventListener("livecomponent:popover:hide",e=>this.handlePopoverHide(e)),this.addEventListener("livecomponent:popover:toggle",e=>this.handlePopoverToggle(e)),this.isInitialized=!0,console.log("[UIEventHandler] Initialized"))}addEventListener(e,t){const n=n=>{try{t(n)}catch(i){console.error(`[UIEventHandler] Error handling event ${e}:`,i)}};document.addEventListener(e,n),this.eventListeners.set(e,n)}removeEventListener(e){const t=this.eventListeners.get(e);t&&(document.removeEventListener(e,t),this.eventListeners.delete(e))}handleToastShow(e){const t=e.detail||{},{message:n="",type:i="info",duration:s=5e3,position:o="top-right",componentId:a="global"}=t;n?(console.log(`[UIEventHandler] Showing toast: ${n} (${i})`),this.uiHelper.showNotification(a,{message:n,type:i,duration:s,position:o})):console.warn("[UIEventHandler] toast:show event missing message")}handleToastHide(e){const t=e.detail||{},{componentId:n="global"}=t;console.log(`[UIEventHandler] Hiding toast for component: ${n}`),this.uiHelper.hideNotification(n)}handleModalShow(e){const t=e.detail||{},{componentId:n,title:i="",content:s="",size:o="medium",buttons:a=[],closeOnBackdrop:r=!0,closeOnEscape:l=!0,onClose:c=null,onConfirm:d=null}=t;n?(console.log(`[UIEventHandler] Showing modal for component: ${n}`),this.uiHelper.showDialog(n,{title:i,content:s,size:o,buttons:a,closeOnBackdrop:r,closeOnEscape:l,onClose:c,onConfirm:d})):console.warn("[UIEventHandler] modal:show event missing componentId")}handleModalClose(e){const t=e.detail||{},{componentId:n}=t;n?(console.log(`[UIEventHandler] Closing modal for component: ${n}`),this.uiHelper.closeDialog(n)):console.warn("[UIEventHandler] modal:close event missing componentId")}async handleModalConfirm(e){const t=e.detail||{},{componentId:n,title:i="Confirm",message:s="Are you sure?",confirmText:o="Confirm",cancelText:a="Cancel",confirmClass:r="btn-primary",cancelClass:l="btn-secondary",confirmAction:c=null,confirmParams:d=null,onConfirm:h=null,onCancel:u=null}=t;if(n){console.log(`[UIEventHandler] Showing confirmation dialog for component: ${n}`);try{const e=await this.uiHelper.showConfirm(n,{title:i,message:s,confirmText:o,cancelText:a,confirmClass:r,cancelClass:l});e&&c&&(console.log(`[UIEventHandler] User confirmed, calling action: ${c}`,d),this.manager&&"function"==typeof this.manager.callAction?await this.manager.callAction(n,c,d||{}):this.manager&&"function"==typeof this.manager.executeAction?await this.manager.executeAction(n,c,d||{}):console.warn("[UIEventHandler] Cannot execute confirmAction: manager.callAction/executeAction not available")),e&&h?h():!e&&u&&u(),document.dispatchEvent(new CustomEvent("modal:confirm:result",{detail:{componentId:n,confirmed:e}}))}catch(p){console.error("[UIEventHandler] Error showing confirmation dialog:",p)}}else console.warn("[UIEventHandler] modal:confirm event missing componentId")}handleModalAlert(e){const t=e.detail||{},{componentId:n,title:i="Alert",message:s="",buttonText:o="OK",type:a="info",onClose:r=null}=t;n?(console.log(`[UIEventHandler] Showing alert dialog for component: ${n}`),this.uiHelper.showAlert(n,{title:i,message:s,buttonText:o,type:a}),r&&setTimeout(()=>{r()},100)):console.warn("[UIEventHandler] modal:alert event missing componentId")}async handleDrawerOpen(e){const t=e.detail||{},{componentId:n,title:i="",content:s="",position:o="left",width:a="400px",showOverlay:r=!0,closeOnOverlay:l=!0,closeOnEscape:c=!0,animation:d="slide"}=t;if(n){if(console.log(`[UIEventHandler] Opening drawer for component: ${n}`),!this.drawerManager){const{DrawerManager:e}=await kt(async()=>{const{DrawerManager:e}=await import("./DrawerManager-CjES72V0.js");return{DrawerManager:e}},[]);this.drawerManager=new e}this.drawerManager.open(n,{title:i,content:s,position:o,width:a,showOverlay:r,closeOnOverlay:l,closeOnEscape:c,animation:d})}else console.warn("[UIEventHandler] drawer:open event missing componentId")}handleDrawerClose(e){const t=e.detail||{},{componentId:n}=t;n?(console.log(`[UIEventHandler] Closing drawer for component: ${n}`),this.drawerManager&&this.drawerManager.close(n)):console.warn("[UIEventHandler] drawer:close event missing componentId")}handleDrawerToggle(e){const t=e.detail||{},{componentId:n}=t;if(n){if(console.log(`[UIEventHandler] Toggling drawer for component: ${n}`),this.drawerManager){this.drawerManager.isOpen(n)?this.drawerManager.close(n):console.warn("[UIEventHandler] drawer:toggle requires full options - use drawer:open/close instead")}}else console.warn("[UIEventHandler] drawer:toggle event missing componentId")}async handlePopoverShow(e){const t=e.detail||{},{componentId:n,anchorId:i,content:s="",title:o="",position:a="top",showArrow:r=!0,offset:l=8,closeOnOutsideClick:c=!0}=t;if(n&&i){if(console.log(`[UIEventHandler] Showing popover for component: ${n}`),!this.popoverManager){const{PopoverManager:e}=await kt(async()=>{const{PopoverManager:e}=await import("./PopoverManager-B_gZSa1e.js");return{PopoverManager:e}},[]);this.popoverManager=new e}this.popoverManager.show(n,{anchorId:i,content:s,title:o,position:a,showArrow:r,offset:l,closeOnOutsideClick:c})}else console.warn("[UIEventHandler] popover:show event missing componentId or anchorId")}handlePopoverHide(e){const t=e.detail||{},{componentId:n}=t;n?(console.log(`[UIEventHandler] Hiding popover for component: ${n}`),this.popoverManager&&this.popoverManager.hide(n)):console.warn("[UIEventHandler] popover:hide event missing componentId")}async handlePopoverToggle(e){const t=e.detail||{},{componentId:n,anchorId:i,content:s="",title:o="",position:a="top",showArrow:r=!0,offset:l=8,closeOnOutsideClick:c=!0}=t;if(!n||!i)return void console.warn("[UIEventHandler] popover:toggle event missing componentId or anchorId");if(!this.popoverManager){const{PopoverManager:e}=await kt(async()=>{const{PopoverManager:e}=await import("./PopoverManager-B_gZSa1e.js");return{PopoverManager:e}},[]);this.popoverManager=new e}this.popoverManager.popovers.has(n)?this.popoverManager.hide(n):this.popoverManager.show(n,{anchorId:i,content:s,title:o,position:a,showArrow:r,offset:l,closeOnOutsideClick:c})}destroy(){for(const[e,t]of this.eventListeners.entries())document.removeEventListener(e,t);this.eventListeners.clear(),this.drawerManager&&this.drawerManager.destroy(),this.popoverManager&&this.popoverManager.destroy(),this.isInitialized=!1,console.log("[UIEventHandler] Destroyed")}}const Lt=new class{constructor(){this.triggeredOnce=new Set,this.throttleTimers=new Map,this.lastValues=new Map,this.loadHandled=new Set}setupTrigger(e,t,n,i,s="click"){const o=this.parseDelay(e.dataset.lcTriggerDelay),a=this.parseThrottle(e.dataset.lcTriggerThrottle),r="true"===e.dataset.lcTriggerOnce,l="true"===e.dataset.lcTriggerChanged,c=e.dataset.lcTriggerFrom,d="true"===e.dataset.lcTriggerLoad;if(r){const i=`${t}_${n}_${this.getElementKey(e)}`;if(this.triggeredOnce.has(i))return}if(d){const s=`${t}_${n}_${this.getElementKey(e)}`;this.loadHandled.has(s)||(this.loadHandled.add(s),"complete"===document.readyState||"interactive"===document.readyState?this.executeWithOptions(e,t,n,i,o,a,l):window.addEventListener("load",()=>{this.executeWithOptions(e,t,n,i,o,a,l)},{once:!0}))}if(c){const r=document.querySelector(c);if(r)return void this.setupDelegatedTrigger(r,e,t,n,i,s,o,a,l);console.warn(`[TriggerManager] Source element not found for trigger-from: ${c}`)}const h=this.getEventType(e,s);e.addEventListener(h,s=>{if(r){const i=`${t}_${n}_${this.getElementKey(e)}`;if(this.triggeredOnce.has(i))return;this.triggeredOnce.add(i)}this.executeWithOptions(e,t,n,i,o,a,l,s)})}setupDelegatedTrigger(e,t,n,i,s,o,a,r,l){e.addEventListener(o,e=>{this.executeWithOptions(t,n,i,s,a,r,l,e)})}executeWithOptions(e,t,n,i,s,o,a,r){if(a){const i=this.getElementValue(e),s=`${t}_${n}_${this.getElementKey(e)}`;if(i===this.lastValues.get(s))return;this.lastValues.set(s,i)}if(o>0){const i=`${t}_${n}_${this.getElementKey(e)}`,s=this.throttleTimers.get(i);if(s&&Date.now()-s<o)return;this.throttleTimers.set(i,Date.now())}s>0?setTimeout(()=>{i(r)},s):i(r)}parseDelay(e){if(!e)return 0;const t=e.match(/^(\d+)(ms|s)?$/);if(!t)return 0;const n=parseInt(t[1]);return"s"===(t[2]||"ms")?1e3*n:n}parseThrottle(e){if(!e)return 0;const t=e.match(/^(\d+)(ms|s)?$/);if(!t)return 0;const n=parseInt(t[1]);return"s"===(t[2]||"ms")?1e3*n:n}getEventType(e,t){return"FORM"===e.tagName?"submit":"SELECT"===e.tagName?"change":"INPUT"===e.tagName||"TEXTAREA"===e.tagName?"checkbox"===e.type||"radio"===e.type?"change":"input":t}getElementValue(e){return"INPUT"===e.tagName?"checkbox"===e.type||"radio"===e.type?e.checked?"true":"false":e.value||"":"TEXTAREA"===e.tagName||"SELECT"===e.tagName?e.value||"":e.textContent||""}getElementKey(e){return e.id||e.name||`${e.tagName}_${e.className}`||"unknown"}cleanup(e){const t=[];for(const o of this.triggeredOnce)o.startsWith(`${e}_`)&&t.push(o);t.forEach(e=>this.triggeredOnce.delete(e));const n=[];for(const o of this.throttleTimers.keys())o.startsWith(`${e}_`)&&n.push(o);n.forEach(e=>this.throttleTimers.delete(e));const i=[];for(const o of this.lastValues.keys())o.startsWith(`${e}_`)&&i.push(o);i.forEach(e=>this.lastValues.delete(e));const s=[];for(const o of this.loadHandled)o.startsWith(`${e}_`)&&s.push(o);s.forEach(e=>this.loadHandled.delete(e))}};const It=new class{constructor(){this.config={requestTimeout:3e4,retryAttempts:3,retryDelays:[1e3,2e3,5e3],stateVersioning:!0,stateValidation:!0,requestDeduplication:!0,requestCacheTimeout:1e3,batchFlushDelay:50,errorBoundary:!0,autoRetry:!0,showErrorUI:!0,devToolsEnabled:!1}}loadFromServer(e){e&&"object"==typeof e&&(this.config={...this.config,...e})}loadFromDOM(){const e=(document.querySelector("[data-livecomponent-config]")||document.body).dataset.livecomponentConfig;if(e)try{const t=JSON.parse(e);this.loadFromServer(t)}catch(t){console.warn("[SharedConfig] Failed to parse config from DOM:",t)}}get(e,t=null){return this.config[e]??t}set(e,t){this.config[e]=t}getAll(){return{...this.config}}merge(e){this.config={...this.config,...e}}};"undefined"!=typeof document&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{It.loadFromDOM()}):It.loadFromDOM());const Pt=new class{constructor(){this.tooltips=new Map,this.activeTooltip=null,this.config={delay:300,hideDelay:100,maxWidth:300,offset:8,animationDuration:200,zIndex:1e4}}init(e,t={}){const n=t.content||e.dataset.tooltip||e.getAttribute("title")||e.getAttribute("aria-label")||"";if(!n)return;e.hasAttribute("title")&&(e.dataset.originalTitle=e.getAttribute("title"),e.removeAttribute("title"));const i=t.position||e.dataset.tooltipPosition||"top";this.setupEventListeners(e,n,i,t)}setupEventListeners(e,t,n,i){let s,o;const a=()=>{clearTimeout(o),s=setTimeout(()=>{this.show(e,t,n,i)},this.config.delay)},r=()=>{clearTimeout(s),o=setTimeout(()=>{this.hide(e)},this.config.hideDelay)};e.addEventListener("mouseenter",a),e.addEventListener("mouseleave",r),e.addEventListener("focus",a),e.addEventListener("blur",r),e.addEventListener("touchstart",a,{passive:!0}),e.addEventListener("touchend",r,{passive:!0}),e._tooltipCleanup=()=>{clearTimeout(s),clearTimeout(o),e.removeEventListener("mouseenter",a),e.removeEventListener("mouseleave",r),e.removeEventListener("focus",a),e.removeEventListener("blur",r),e.removeEventListener("touchstart",a),e.removeEventListener("touchend",r)}}show(e,t,n,i={}){this.activeTooltip&&this.hide();const s=document.createElement("div");s.className="livecomponent-tooltip",s.setAttribute("role","tooltip"),s.setAttribute("aria-hidden","false"),s.textContent=t,s.style.cssText=`\n position: absolute;\n max-width: ${this.config.maxWidth}px;\n padding: 0.5rem 0.75rem;\n background: #1f2937;\n color: white;\n border-radius: 0.375rem;\n font-size: 0.875rem;\n line-height: 1.4;\n z-index: ${this.config.zIndex};\n pointer-events: none;\n opacity: 0;\n transition: opacity ${this.config.animationDuration}ms ease;\n word-wrap: break-word;\n box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);\n `,document.body.appendChild(s),this.positionTooltip(s,e,n),requestAnimationFrame(()=>{s.style.opacity="1"}),this.tooltips.set(e,s),this.activeTooltip=s;const o=`tooltip-${Date.now()}`;s.id=o,e.setAttribute("aria-describedby",o)}positionTooltip(e,t,n){const i=t.getBoundingClientRect(),s=e.getBoundingClientRect(),o=window.scrollX||window.pageXOffset,a=window.scrollY||window.pageYOffset,r=this.config.offset;let l,c;switch(n){case"top":default:l=i.top+a-s.height-r,c=i.left+o+i.width/2-s.width/2;break;case"bottom":l=i.bottom+a+r,c=i.left+o+i.width/2-s.width/2;break;case"left":l=i.top+a+i.height/2-s.height/2,c=i.left+o-s.width-r;break;case"right":l=i.top+a+i.height/2-s.height/2,c=i.right+o+r}const d=window.innerWidth,h=window.innerHeight;c<o?c=o+8:c+s.width>o+d&&(c=o+d-s.width-8),l<a?l=a+8:l+s.height>a+h&&(l=a+h-s.height-8),e.style.top=`${l}px`,e.style.left=`${c}px`}hide(e=null){const t=e?this.tooltips.get(e):this.activeTooltip;t&&(t.style.opacity="0",setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),e&&e.removeAttribute("aria-describedby"),e&&this.tooltips.delete(e),this.activeTooltip===t&&(this.activeTooltip=null)},this.config.animationDuration))}showValidationError(e,t){this.hideValidationError(e);const n=document.createElement("div");n.className="livecomponent-tooltip livecomponent-tooltip--error",n.setAttribute("role","alert"),n.textContent=t,n.style.cssText=`\n position: absolute;\n max-width: ${this.config.maxWidth}px;\n padding: 0.5rem 0.75rem;\n background: #dc2626;\n color: white;\n border-radius: 0.375rem;\n font-size: 0.875rem;\n line-height: 1.4;\n z-index: ${this.config.zIndex};\n pointer-events: none;\n opacity: 0;\n transition: opacity ${this.config.animationDuration}ms ease;\n word-wrap: break-word;\n box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);\n `,document.body.appendChild(n),this.positionTooltip(n,e,"top"),requestAnimationFrame(()=>{n.style.opacity="1"}),e._validationTooltip=n,e.classList.add("livecomponent-error")}hideValidationError(e){const t=e._validationTooltip;t&&(t.style.opacity="0",setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),delete e._validationTooltip,e.classList.remove("livecomponent-error")},this.config.animationDuration))}initComponent(e){e.querySelectorAll("[data-tooltip], [title], [aria-label]").forEach(e=>{this.init(e)})}cleanupComponent(e){e.querySelectorAll("[data-tooltip], [title], [aria-label]").forEach(e=>{this.hide(e),e._tooltipCleanup&&(e._tooltipCleanup(),delete e._tooltipCleanup),e.dataset.originalTitle&&(e.setAttribute("title",e.dataset.originalTitle),delete e.dataset.originalTitle)})}updateConfig(e){this.config={...this.config,...e}}};const $t=new class{constructor(){this.loadingStates=new Map,this.skeletonTemplates=new Map,this.config={showDelay:150,transitionDuration:200,preserveContent:!0,opacity:.6}}showLoading(e,t,n={}){if(this.loadingStates.has(e))return;const i=n.showDelay??this.config.showDelay,s=n.fragments||null,o=setTimeout(()=>{this.createSkeletonOverlay(e,t,s,n)},i);this.loadingStates.set(e,{timeoutId:o,element:t,fragments:s,options:n})}createSkeletonOverlay(e,t,n,i){const s=this.getSkeletonTemplate(e,t,n),o=document.createElement("div");o.className="livecomponent-loading-overlay",o.setAttribute("data-component-id",e),o.setAttribute("aria-busy","true"),o.setAttribute("aria-label","Loading..."),o.style.cssText=`\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(255, 255, 255, ${this.config.opacity});\n z-index: 10;\n display: flex;\n align-items: center;\n justify-content: center;\n opacity: 0;\n transition: opacity ${this.config.transitionDuration}ms ease;\n pointer-events: none;\n `,o.innerHTML=s;const a=t.style.position;"static"===getComputedStyle(t).position&&(t.style.position="relative"),t.appendChild(o),requestAnimationFrame(()=>{o.style.opacity="1"});const r=this.loadingStates.get(e);r&&(r.overlay=o,r.originalPosition=a)}getSkeletonTemplate(e,t,n){const i=this.skeletonTemplates.get(e);return i?"function"==typeof i?i(t,n):i:n&&n.length>0?this.createFragmentSkeletons(n):this.createDefaultSkeleton(t)}createDefaultSkeleton(e){const t=e.offsetHeight||200;return`\n <div class="skeleton-container" style="width: ${e.offsetWidth||"100%"}; height: ${t}px; padding: 1.5rem;">\n <div class="skeleton skeleton-text skeleton-text--full" style="margin-bottom: 1rem;"></div>\n <div class="skeleton skeleton-text skeleton-text--80" style="margin-bottom: 0.75rem;"></div>\n <div class="skeleton skeleton-text skeleton-text--60" style="margin-bottom: 0.75rem;"></div>\n <div class="skeleton skeleton-text skeleton-text--full" style="margin-bottom: 1rem;"></div>\n <div class="skeleton skeleton-text skeleton-text--80"></div>\n </div>\n `}createFragmentSkeletons(e){return e.map(e=>`\n <div class="skeleton-fragment" data-fragment="${e}">\n <div class="skeleton skeleton-text skeleton-text--full" style="margin-bottom: 0.75rem;"></div>\n <div class="skeleton skeleton-text skeleton-text--80"></div>\n </div>\n `).join("")}hideLoading(e){const t=this.loadingStates.get(e);t&&(t.timeoutId&&clearTimeout(t.timeoutId),t.overlay&&(t.overlay.style.opacity="0",setTimeout(()=>{t.overlay&&t.overlay.parentNode&&t.overlay.parentNode.removeChild(t.overlay)},this.config.transitionDuration)),void 0!==t.originalPosition&&(t.element.style.position=t.originalPosition),this.loadingStates.delete(e))}registerTemplate(e,t){this.skeletonTemplates.set(e,t)}unregisterTemplate(e){this.skeletonTemplates.delete(e)}isLoading(e){return this.loadingStates.has(e)}updateConfig(e){this.config={...this.config,...e}}};class Dt{constructor(e,t){this.actionLoadingManager=e,this.optimisticStateManager=t,this.loadingConfigs=new Map,this.config={defaultType:"skeleton",showDelay:150,hideDelay:0}}configure(e,t){this.loadingConfigs.set(e,{type:t.type||this.config.defaultType,showDelay:t.showDelay??this.config.showDelay,hideDelay:t.hideDelay??this.config.hideDelay,template:t.template||null,...t})}showLoading(e,t,n={},i=null){const s=this.loadingConfigs.get(e)||{type:this.config.defaultType,showDelay:this.config.showDelay};if(null==i?void 0:i.dataset.lcIndicator){const e=i.dataset.lcIndicator;return void document.querySelectorAll(e).forEach(e=>{e instanceof HTMLElement&&(e.style.display="",e.setAttribute("aria-busy","true"),e.classList.add("lc-indicator-active"))})}const o=n.type||s.type;if("none"===o)return;if(!(this.optimisticStateManager.getPendingOperations(e).length>0&&!1!==n.optimistic))switch(o){case"skeleton":this.actionLoadingManager.showLoading(e,t,{...n,showDelay:s.showDelay});break;case"spinner":this.showSpinner(e,t,s);break;case"progress":this.showProgress(e,t,s);break;default:this.actionLoadingManager.showLoading(e,t,n)}}hideLoading(e,t=null){if(null==t?void 0:t.dataset.lcIndicator){const e=t.dataset.lcIndicator;document.querySelectorAll(e).forEach(e=>{e instanceof HTMLElement&&(e.removeAttribute("aria-busy"),e.classList.remove("lc-indicator-active"))})}this.actionLoadingManager.hideLoading(e),this.hideSpinner(e),this.hideProgress(e)}showSpinner(e,t,n){this.hideSpinner(e);const i=document.createElement("div");i.className="livecomponent-loading-spinner",i.setAttribute("data-component-id",e),i.setAttribute("aria-busy","true"),i.setAttribute("aria-label","Loading..."),i.innerHTML='\n <div class="spinner"></div>\n <span class="spinner-text">Loading...</span>\n ',i.style.cssText=`\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(255, 255, 255, 0.8);\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: 1rem;\n z-index: 10;\n opacity: 0;\n transition: opacity ${this.config.showDelay}ms ease;\n `,"static"===getComputedStyle(t).position&&(t.style.position="relative"),t.appendChild(i),requestAnimationFrame(()=>{i.style.opacity="1"});const s=this.loadingConfigs.get(e)||{};s.spinner=i,this.loadingConfigs.set(e,s)}hideSpinner(e){const t=this.loadingConfigs.get(e);if(!t||!t.spinner)return;const n=t.spinner;n.style.opacity="0",setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),delete t.spinner},200)}showProgress(e,t,n){this.hideProgress(e);const i=document.createElement("div");i.className="livecomponent-loading-progress",i.setAttribute("data-component-id",e),i.setAttribute("aria-busy","true"),i.innerHTML='\n <div class="progress-bar" style="width: 0%;"></div>\n ',i.style.cssText=`\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n height: 3px;\n background: #e0e0e0;\n z-index: 10;\n opacity: 0;\n transition: opacity ${this.config.showDelay}ms ease;\n `;i.querySelector(".progress-bar").style.cssText="\n height: 100%;\n background: #2196F3;\n transition: width 0.3s ease;\n ","static"===getComputedStyle(t).position&&(t.style.position="relative"),t.appendChild(i),requestAnimationFrame(()=>{i.style.opacity="1",this.updateProgress(e,30)});const s=this.loadingConfigs.get(e)||{};s.progress=i,this.loadingConfigs.set(e,s)}updateProgress(e,t){const n=this.loadingConfigs.get(e);if(!n||!n.progress)return;const i=n.progress.querySelector(".progress-bar");i&&(i.style.width=`${Math.min(100,Math.max(0,t))}%`)}hideProgress(e){const t=this.loadingConfigs.get(e);if(!t||!t.progress)return;const n=t.progress;this.updateProgress(e,100),setTimeout(()=>{n.style.opacity="0",setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),delete t.progress},200)},300)}getConfig(e){return this.loadingConfigs.get(e)||{type:this.config.defaultType,showDelay:this.config.showDelay}}clearConfig(e){this.hideLoading(e),this.loadingConfigs.delete(e)}}class Ot{constructor(e){this.liveComponentManager=e,this.boostContainers=new Set,this.initialized=!1}init(){this.initialized?console.warn("[ProgressiveEnhancement] Already initialized"):(this.findBoostContainers(),this.setupMutationObserver(),document.addEventListener("click",e=>this.handleLinkClick(e),!0),document.addEventListener("submit",e=>this.handleFormSubmit(e),!0),this.initialized=!0,console.log("[ProgressiveEnhancement] Initialized"))}findBoostContainers(){document.querySelectorAll('[data-lc-boost="true"]').forEach(e=>{this.setupBoostContainer(e)})}setupBoostContainer(e){this.boostContainers.has(e)||(this.boostContainers.add(e),e.querySelectorAll("a[href], form[action]").forEach(e=>{e.hasAttribute("data-lc-boost")||e.setAttribute("data-lc-boost","true")}))}setupMutationObserver(){new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{var t,n;if(e.nodeType===Node.ELEMENT_NODE){e.hasAttribute&&e.hasAttribute("data-lc-boost")&&"true"===e.getAttribute("data-lc-boost")&&this.setupBoostContainer(e);const i=null==(t=e.querySelectorAll)?void 0:t.call(e,'[data-lc-boost="true"]');i&&i.forEach(e=>{this.setupBoostContainer(e)});const s=null==(n=e.querySelectorAll)?void 0:n.call(e,"a[href], form[action]");s&&s.forEach(e=>{e.closest('[data-lc-boost="true"]')&&!e.hasAttribute("data-lc-boost")&&e.setAttribute("data-lc-boost","true")})}})})}).observe(document.body,{childList:!0,subtree:!0})}handleLinkClick(e){const t=e.target.closest("a[href]");if(!t)return;if(!t.closest('[data-lc-boost="true"]'))return;if(t.hasAttribute("data-lc-boost")&&"false"===t.getAttribute("data-lc-boost"))return;const n=t.getAttribute("href");!n||"#"===n||n.startsWith("javascript:")||n.startsWith("mailto:")||n.startsWith("tel:")||"_blank"!==t.getAttribute("target")&&(e.preventDefault(),window.SPARouter&&"function"==typeof window.SPARouter.navigate?window.SPARouter.navigate(n):this.loadContentViaAjax(n,t))}handleFormSubmit(e){const t=e.target;if(!t||"FORM"!==t.tagName)return;t.closest('[data-lc-boost="true"]')&&(t.hasAttribute("data-lc-boost")&&"false"===t.getAttribute("data-lc-boost")||t.hasAttribute("data-live-action")||(e.preventDefault(),this.submitFormViaAjax(t)))}async loadContentViaAjax(e,t){try{t.setAttribute("aria-busy","true"),t.classList.add("lc-loading");const n=await fetch(e,{method:"GET",headers:{"X-Requested-With":"XMLHttpRequest",Accept:"text/html"}});if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`);const i=await n.text(),s=(new DOMParser).parseFromString(i,"text/html"),o=s.querySelector("main")||s.body,a=document.querySelector("main")||document.body;if(a?a.innerHTML=o.innerHTML:document.body.innerHTML=o.innerHTML,window.history.pushState({},"",e),this.liveComponentManager){document.querySelectorAll("[data-live-component]").forEach(e=>{this.liveComponentManager.init(e)})}window.dispatchEvent(new CustomEvent("lc:boost:navigated",{detail:{url:e,link:t}}))}catch(n){console.error("[ProgressiveEnhancement] Failed to load content:",n),window.location.href=e}finally{t.removeAttribute("aria-busy"),t.classList.remove("lc-loading")}}async submitFormViaAjax(e){try{e.setAttribute("aria-busy","true"),e.classList.add("lc-loading");const t=new FormData(e),n=e.method.toUpperCase()||"POST",i=e.action||window.location.href,s=await fetch(i,{method:n,body:t,headers:{"X-Requested-With":"XMLHttpRequest",Accept:"text/html"}});if(!s.ok)throw new Error(`HTTP ${s.status}: ${s.statusText}`);const o=await s.text();if(s.redirected)return void(await this.loadContentViaAjax(s.url,e));const a=(new DOMParser).parseFromString(o,"text/html"),r=a.querySelector("main")||a.body,l=document.querySelector("main")||document.body;if(l?l.innerHTML=r.innerHTML:document.body.innerHTML=r.innerHTML,e.action&&e.action!==window.location.href&&window.history.pushState({},"",e.action),this.liveComponentManager){document.querySelectorAll("[data-live-component]").forEach(e=>{this.liveComponentManager.init(e)})}window.dispatchEvent(new CustomEvent("lc:boost:submitted",{detail:{form:e,action:i}}))}catch(t){console.error("[ProgressiveEnhancement] Failed to submit form:",t),e.submit()}finally{e.removeAttribute("aria-busy"),e.classList.remove("lc-loading")}}}const zt=new class{constructor(){this.initialized=!1,this.popStateHandler=null}init(){this.initialized?console.warn("[UrlManager] Already initialized"):(this.popStateHandler=e=>{this.handlePopState(e)},window.addEventListener("popstate",this.popStateHandler),this.initialized=!0,console.log("[UrlManager] Initialized"))}pushUrl(e,t=""){try{window.history.pushState({url:e,title:t},t||document.title,e),t&&(document.title=t),window.dispatchEvent(new CustomEvent("lc:url:pushed",{detail:{url:e,title:t}})),console.log(`[UrlManager] Pushed URL: ${e}`)}catch(n){console.error("[UrlManager] Failed to push URL:",n)}}replaceUrl(e,t=""){try{window.history.replaceState({url:e,title:t},t||document.title,e),t&&(document.title=t),window.dispatchEvent(new CustomEvent("lc:url:replaced",{detail:{url:e,title:t}})),console.log(`[UrlManager] Replaced URL: ${e}`)}catch(n){console.error("[UrlManager] Failed to replace URL:",n)}}handlePopState(e){const t=e.state;if(t&&t.url){if(window.dispatchEvent(new CustomEvent("lc:url:popstate",{detail:{url:t.url,state:t}})),window.SPARouter&&"function"==typeof window.SPARouter.navigate)return void window.SPARouter.navigate(t.url);console.log("[UrlManager] PopState detected, URL:",t.url)}}getCurrentUrl(){return window.location.href}getCurrentPath(){return window.location.pathname}cleanup(){this.popStateHandler&&(window.removeEventListener("popstate",this.popStateHandler),this.popStateHandler=null),this.initialized=!1}},_t="pending",Rt="hashing",Ft="uploading",qt="complete",Nt="error",Bt="initializing",Ht="initialized",Ut="uploading",jt="assembling",Wt="complete",Vt="aborted",Gt="error";class Jt{constructor(e,t,n){this.index=e,this.size=t,this.status=_t,this.hash=null,this.uploadedBytes=0,this.retries=0,this.error=null,this.xhr=null,this.file=n}get progress(){return this.size>0?this.uploadedBytes/this.size*100:0}reset(){this.status=_t,this.uploadedBytes=0,this.error=null,this.xhr=null}abort(){this.xhr&&(this.xhr.abort(),this.xhr=null)}}class Xt{constructor(e,t){this.file=e,this.sessionId=null,this.totalChunks=0,this.chunkSize=t.chunkSize,this.chunks=[],this.status=Bt,this.uploadedChunks=0,this.expectedFileHash=null,this.error=null,this.startTime=null,this.endTime=null,this.expiresAt=null}get progress(){return 0===this.totalChunks?0:this.uploadedChunks/this.totalChunks*100}get uploadedBytes(){return this.chunks.reduce((e,t)=>e+t.uploadedBytes,0)}get totalBytes(){return this.file.size}get isComplete(){return this.status===Wt}get isError(){return this.status===Gt}get isAborted(){return this.status===Vt}get canResume(){return null!==this.sessionId&&!this.isComplete&&!this.isAborted}getChunk(e){return this.chunks[e]}getPendingChunks(){return this.chunks.filter(e=>e.status===_t||e.status===Nt)}getUploadingChunks(){return this.chunks.filter(e=>e.status===Ft)}}const Qt=new class{constructor(){this.components=new Map,this.eventHandlers=new Map,this.debounceTimers=new Map,this.domPatcher=nt,this.accessibilityManager=vt,this.sseClients=new Map,this.componentChannels=new Map,this.lazyLoader=null,this.nestedHandler=null,this.devTools=null,this.errorBoundary=new bt(this),this.requestDeduplicator=new wt,this.config=It,this.tooltipManager=Pt,this.actionLoadingManager=$t,this.uiHelper=new Tt(this),this.uiEventHandler=new At(this),this.uiEventHandler.init(),this.loadingStateManager=new Dt(this.actionLoadingManager,yt),this.progressiveEnhancement=new Ot(this),zt.init()}enableDevTools(e){this.devTools=e,console.log("[LiveComponent] DevTools integration enabled")}logActionToDevTools(e,t,n,i,s,o,a=null){this.devTools&&this.devTools.logAction(e,t,n,i,s,o,a)}logEventToDevTools(e,t,n="server"){this.devTools&&this.devTools.logEvent(e,t,n)}initLazyLoading(){this.lazyLoader?console.warn("[LiveComponent] Lazy loading already initialized"):(this.lazyLoader=new ht(this),this.lazyLoader.init(),console.log("[LiveComponent] Lazy loading system initialized"))}initNestedComponents(){this.nestedHandler?console.warn("[LiveComponent] Nested components already initialized"):(this.nestedHandler=new ut(this),this.nestedHandler.init(),console.log("[LiveComponent] Nested components system initialized"))}init(e,t={}){const n=e.dataset.liveComponent;if(!n)return;const i=!0===t.isolated||"true"===e.dataset.islandComponent,s={id:n,element:e,pollInterval:parseInt(e.dataset.pollInterval)||null,pollTimer:null,observer:null,isolated:i};this.components.set(n,s),this.setupActionHandlers(e),this.setupFileUploadHandlers(e),s.pollInterval&&this.startPolling(n),this.setupLifecycleObserver(e,n),this.setupSseConnection(e,n,{isolated:i}),this.setupAccessibility(n,e),this.tooltipManager.initComponent(e),this.progressiveEnhancement.initialized||this.progressiveEnhancement.init(),console.log(`[LiveComponent] Initialized: ${n}${i?" (Island)":""}`)}setupAccessibility(e,t){const n="assertive"===t.dataset.livePolite?"assertive":"polite";this.accessibilityManager.createComponentLiveRegion(e,t,n),console.log(`[LiveComponent] Accessibility features enabled for ${e}`)}setupLifecycleObserver(e,t){const n=this.components.get(t);if(!n)return;const i=new MutationObserver(n=>{document.contains(e)||(console.log(`[LiveComponent] Element removed from DOM: ${t}`),this.callDestroyHook(t),i.disconnect())});e.parentNode&&i.observe(e.parentNode,{childList:!0,subtree:!1}),n.observer=i}setupSseConnection(e,t,n={}){const i=e.dataset.sseChannel;if(!i)return;console.log(`[LiveComponent] Setting up SSE for ${t} on channel: ${i}`),this.componentChannels.set(t,i);let s=this.sseClients.get(i);s||(s=new ot([i],{autoReconnect:!0,heartbeatTimeout:45e3}),this.registerSseHandlers(s,i),s.connect(),this.sseClients.set(i,s),console.log(`[LiveComponent] Created SSE client for channel: ${i}`)),console.log(`[LiveComponent] SSE connection established for ${t}`)}registerSseHandlers(e,t){e.on("component-update",e=>{this.handleSseComponentUpdate(e,t)}),e.on("component-fragments",e=>{this.handleSseComponentFragments(e,t)}),e.on("connected",()=>{console.log(`[LiveComponent] SSE connected to channel: ${t}`),this.updateSseConnectionStatus(t,"connected")}),e.on("disconnected",()=>{console.log(`[LiveComponent] SSE disconnected from channel: ${t}`),this.updateSseConnectionStatus(t,"disconnected")}),e.on("reconnecting",e=>{console.log(`[LiveComponent] SSE reconnecting to channel ${t} (attempt ${e})`),this.updateSseConnectionStatus(t,"reconnecting")}),e.on("error",e=>{console.error(`[LiveComponent] SSE error on channel ${t}:`,e),this.updateSseConnectionStatus(t,"error")})}handleSseComponentUpdate(e,t){const{componentId:n,state:i,html:s,events:o}=e;console.log(`[LiveComponent] SSE update for ${n}:`,{state:i,html:s,events:o});const a=this.components.get(n);if(a)try{this.accessibilityManager.captureFocusState(n,a.element),s&&(a.element.innerHTML=s,this.setupActionHandlers(a.element),this.setupFileUploadHandlers(a.element)),i&&Et(a.element,i),this.accessibilityManager.restoreFocus(n,a.element),this.accessibilityManager.announceUpdate(n,"full"),o&&Array.isArray(o)&&this.handleServerEvents(o),console.log(`[LiveComponent] SSE update applied to ${n}`)}catch(r){console.error(`[LiveComponent] Failed to apply SSE update for ${n}:`,r)}else console.warn(`[LiveComponent] Received SSE update for unknown component: ${n}`)}handleSseComponentFragments(e,t){const{componentId:n,fragments:i}=e;console.log(`[LiveComponent] SSE fragments for ${n}:`,i);const s=this.components.get(n);if(s)try{this.updateFragments(s.element,i),console.log(`[LiveComponent] SSE fragments applied to ${n}`)}catch(o){console.error(`[LiveComponent] Failed to apply SSE fragments for ${n}:`,o)}else console.warn(`[LiveComponent] Received SSE fragments for unknown component: ${n}`)}updateSseConnectionStatus(e,t){this.componentChannels.forEach((n,i)=>{if(n===e){const n=this.components.get(i);if(!n)return;n.element.dataset.sseStatus=t,n.element.dispatchEvent(new CustomEvent("livecomponent:sse:status",{detail:{channel:e,status:t}}))}})}async callDestroyHook(e){const t=this.components.get(e);if(t){try{const n=t.element.dataset.state||"{}",i=JSON.parse(n),s=t.element.dataset.csrfToken,o=JSON.stringify({state:i,_csrf_token:s}),a=`/live-component/${e}/destroy`,r=new Blob([o],{type:"application/json"});navigator.sendBeacon&&navigator.sendBeacon(a,r)?console.log(`[LiveComponent] onDestroy() called via sendBeacon: ${e}`):(await fetch(a,{method:"POST",headers:{"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"},body:o}),console.log(`[LiveComponent] onDestroy() called via fetch: ${e}`))}catch(n){console.warn(`[LiveComponent] onDestroy() hook failed: ${e}`,n)}this.destroy(e)}}setupActionHandlers(e){e.querySelectorAll("[data-live-action]").forEach(t=>{let n=t.dataset.liveComponent;if(!n){let e=t.parentElement;const i=[];for(;e&&e!==document.body;)e.hasAttribute&&e.hasAttribute("data-live-component")&&i.push(e),e=e.parentElement;if(i.length>0)n=i[0].dataset.liveComponent;else{const e=t.closest("[data-live-component]");e&&(n=e.dataset.liveComponent)}}if(!n)return void console.warn("[LiveComponent] No component found for action:",t,t.dataset.liveAction);const i=t.dataset.lcTriggerDelay||t.dataset.lcTriggerThrottle||"true"===t.dataset.lcTriggerOnce||"true"===t.dataset.lcTriggerChanged||t.dataset.lcTriggerFrom||"true"===t.dataset.lcTriggerLoad,s=async(i,s={})=>{const o=t.dataset.liveAction;let a={...this.extractParams(t),...s};if("submit"===o||"nextStep"===o||"previousStep"===o){a={...this.collectFormValues(e),...a}}const r=this.extractFragments(t);await this.executeAction(n,o,a,r,t)};if(i)Lt.setupTrigger(t,n,t.dataset.liveAction,async e=>{if("FORM"===t.tagName&&e){e.preventDefault();const n={},i=new FormData(t);for(const[e,t]of i.entries())n[e]=t;await s(0,n)}else e&&e.preventDefault(),await s()},"FORM"===t.tagName?"submit":"click");else if("FORM"===t.tagName)t.addEventListener("submit",async e=>{e.preventDefault();const i=t.dataset.liveAction,s={},o=new FormData(t);for(const[t,n]of o.entries())s[t]=n;const a=this.extractFragments(t);await this.executeAction(n,i,s,a,t)});else if("INPUT"===t.tagName||"TEXTAREA"===t.tagName||"SELECT"===t.tagName){const e="text"===t.type||"email"===t.type||"url"===t.type||"tel"===t.type||"TEXTAREA"===t.tagName?300:0,i=parseInt(t.dataset.liveDebounce)??e;"SELECT"===t.tagName?t.addEventListener("change",async e=>{const i=t.dataset.liveAction,s=this.extractParams(t),o=t.name||"content_type_id",a=o.replace(/_([a-z])/g,(e,t)=>t.toUpperCase());s[a]=t.value,o!==a&&(s[o]=t.value),console.log("[LiveComponent] SELECT change:",{action:i,name:o,camelCaseName:a,value:t.value,params:s});const r=this.extractFragments(t);await this.executeAction(n,i,s,r,t)}):t.addEventListener("input",async e=>{const s=t.dataset.liveAction,o=this.extractParams(t);"checkbox"===t.type?o[t.name||"value"]=t.checked?"yes":"no":(t.type,o[t.name||"value"]=t.value);const a=this.extractFragments(t);i>0?this.debouncedAction(n,s,o,i,a,t):await this.executeAction(n,s,o,a,t)}),"radio"!==t.type&&"checkbox"!==t.type||t.addEventListener("change",async e=>{const i=t.dataset.liveAction,s=this.extractParams(t);"checkbox"===t.type?s[t.name||"value"]=t.checked?"yes":"no":"radio"===t.type&&(s[t.name||"value"]=t.value),await this.executeAction(n,i,s,null,t)})}else t.addEventListener("click",async i=>{i.preventDefault();const s=t.dataset.liveAction;let o=this.extractParams(t);if("submit"===s||"nextStep"===s||"previousStep"===s){const t=this.collectFormValues(e);console.log("[LiveComponent] Collected form values:",t),o={...t,...o},console.log("[LiveComponent] Final params:",o)}const a=this.extractFragments(t);await this.executeAction(n,s,o,a,t)})})}debouncedAction(e,t,n,i,s=null,o=null){const a=`${e}_${t}`;this.debounceTimers.has(a)&&clearTimeout(this.debounceTimers.get(a));const r=setTimeout(async()=>{await this.executeAction(e,t,n,s,o),this.debounceTimers.delete(a)},i);this.debounceTimers.set(a,r)}extractParams(e){const t={};return Object.keys(e.dataset).forEach(n=>{if(n.startsWith("param")){const i=n.replace("param","");if(i.endsWith("From")){const s=i.replace(/From$/,"").toLowerCase(),o=e.dataset[n];t[s]="value"===o?e.value:e[o]||e.getAttribute(o)}else{const s=i.toLowerCase();t[s]=e.dataset[n]}}}),t}extractFragments(e){const t=e.dataset.lcFragments;return t?t.split(",").map(e=>e.trim()).filter(Boolean):null}collectFormValues(e){const t={};return e.querySelectorAll("input, textarea, select").forEach(e=>{const n=e.name;n&&("checkbox"===e.type?t[n]=e.checked?"yes":"no":"radio"===e.type?e.checked&&(t[n]=e.value):t[n]=e.value)}),t}async executeAction(e,t,n={},i=null,s=null){const o=this.components.get(e);if(!o)return void console.error(`[LiveComponent] Unknown component: ${e}`);const a=this.requestDeduplicator.getPendingRequest(e,t,n);if(a)return console.log(`[LiveComponent] Deduplicating request: ${e}.${t}`),await a;const r=this.requestDeduplicator.getCachedResult(e,t,n);if(r)return console.log(`[LiveComponent] Using cached result: ${e}.${t}`),r;let l=null;const c=performance.now();let d=o.element;if(d.dataset.liveComponent!==e&&(d=document.querySelector(`[data-live-component="${e}"]`),!d))return void console.error(`[LiveComponent] Component element not found: ${e}`);const h=this.loadingStateManager.getConfig(e);this.loadingStateManager.showLoading(e,d,{fragments:i,type:h.type,optimistic:!0},s);const u=(async()=>{var a,r;try{if(d.dataset.liveComponent!==e&&(d=document.querySelector(`[data-live-component="${e}"]`),!d))throw console.error(`[LiveComponent] Component element not found: ${e}`),new Error(`Component element ${e} not found in DOM`);const p=St(d)||{id:e,component:"",data:{},version:1},m=yt.getPendingOperations(e);let g=1;if(p&&"number"==typeof p.version&&(g=p.version),m.length>0){const e=m[m.length-1];e.optimisticState&&"number"==typeof e.optimisticState.version&&(g=e.optimisticState.version)}if(console.error("[LiveComponent] VERSION DEBUG START",{stateWrapperVersion:null==p?void 0:p.version,stateWrapperVersionType:typeof(null==p?void 0:p.version),currentVersion:g,pendingOpsCount:m.length,hasStateWrapper:!!p,stateWrapperKeys:p?Object.keys(p):[]}),m.length>0){const e=m[m.length-1];e.optimisticState&&e.optimisticState.version&&(g=e.optimisticState.version)}const f=p.data||{};yt.applyOptimisticUpdate(e,p,e=>({...e,data:{...e.data,_optimistic:!0}}),{action:t,params:n});l=null==(a=yt.getPendingOperations(e)[0])?void 0:a.id;const y=d.dataset.csrfToken;if(!y)throw console.error(`[LiveComponent] Missing CSRF token for component: ${e}`),console.error("[LiveComponent] Component element:",d),console.error("[LiveComponent] Component element dataset:",null==d?void 0:d.dataset),console.error("[LiveComponent] Component element HTML:",null==(r=null==d?void 0:d.outerHTML)?void 0:r.substring(0,500)),new Error("CSRF token is required for component actions");0;let v=1;if(p&&"number"==typeof p.version&&(v=p.version),m.length>0){const e=m[m.length-1];e.optimisticState&&"number"==typeof e.optimisticState.version&&(v=e.optimisticState.version)}("number"!=typeof v||isNaN(v))&&(v=1),console.error("[LiveComponent] VERSION DEBUG",{stateWrapperVersion:null==p?void 0:p.version,currentVersion:g,versionToSend:v,pendingOpsCount:m.length,hasStateWrapper:!!p});const b={};b.method=t,b.params=n,b.state=f,b.version=v,b._csrf_token=y,i&&Array.isArray(i)&&i.length>0&&(b.fragments=i),("number"!=typeof b.version||isNaN(b.version))&&(b.version=v||1);const w=JSON.stringify(b);let S=w;if(!w.includes('"version"')){console.error("[LiveComponent] ERROR: Version missing in JSON! Forcing version...",{jsonPreview:w.substring(0,300),versionToSend:v,requestBodyKeys:Object.keys(b)});try{const e=JSON.parse(w);e.version=v||1,S=JSON.stringify(e),console.error("[LiveComponent] Corrected JSON preview:",S.substring(0,300))}catch(h){console.error("[LiveComponent] Failed to parse/correct JSON:",h);const e=JSON.parse(w);e.version=v||1,S=JSON.stringify(e)}}S.includes('"version"')||console.error("[LiveComponent] CRITICAL ERROR: Version still missing after correction!");const E=await fetch(`/live-component/${e}`,{method:"POST",headers:{"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"},body:S});if(!E.ok){const e=await E.text();throw console.error("[LiveComponent] Server error response:",e),new Error(`HTTP ${E.status}: ${E.statusText}`)}const C=await E.text();let k;console.log("[LiveComponent] Raw response:",C.substring(0,200));try{k=JSON.parse(C)}catch(u){throw console.error("[LiveComponent] JSON parse error:",u),console.error("[LiveComponent] Response text:",C),new Error(`Failed to parse JSON response: ${u.message}`)}const M=k.state||{},x=M.version||1;if(x!==g+1){if(console.warn(`[LiveComponent] Version conflict: expected ${g+1}, got ${x}`),l){const t=yt.handleConflict(e,l,M,{expectedVersion:g+1,actualVersion:x});t.notification&&this.showConflictNotification(e,t.notification),k.state=t.state}}else l&&yt.confirmOperation(e,l,M);const T=this.resolveTarget(s,e);if(!T)throw new Error(`[LiveComponent] Could not resolve target element for component: ${e}`);const A=(null==s?void 0:s.dataset.lcSwap)||"innerHTML";if(k.fragments)this.updateFragments(o.element,k.fragments);else if(k.html){if("innerHTML"===A)T.innerHTML=k.html;else{this.domPatcher.swapElement(T,k.html,A,transition,scrollOptions)||(console.warn("[LiveComponent] Swap failed, falling back to innerHTML"),T.innerHTML=k.html)}if("outerHTML"===A){const t=document.querySelector(`[data-live-component="${e}"]`);t?this.setupActionHandlers(t):this.setupActionHandlers(T.parentElement||document.body)}else this.setupActionHandlers(T)}this.tooltipManager.initComponent(T),k.state&&Et(o.element,k.state),k.events&&k.events.length>0&&this.handleServerEvents(k.events);const L=null==s?void 0:s.dataset.lcPushUrl,I=null==s?void 0:s.dataset.lcReplaceUrl;L?zt.pushUrl(L,k.title):I&&zt.replaceUrl(I,k.title),console.log(`[LiveComponent] Action executed: ${e}.${t}`,k);const P=performance.now();return this.logActionToDevTools(e,t,n,c,P,!0),this.requestDeduplicator.cacheResult(e,t,n,k),this.loadingStateManager.hideLoading(e,s),k}catch(p){console.error("[LiveComponent] Action failed:",p);const s=performance.now();if(this.logActionToDevTools(e,t,n,c,s,!1,p.message),l){const t=yt.getSnapshot(e);t&&(Et(o.element,t),yt.clearPendingOperations(e),yt.clearSnapshot(e))}throw this.loadingStateManager.hideLoading(e,null),await this.errorBoundary.handleError(e,t,p,{params:n,fragments:i}),p}})();return this.requestDeduplicator.registerPendingRequest(e,t,n,u)}resolveTarget(e,t){const n=null==e?void 0:e.dataset.lcTarget;if(!n){const e=this.components.get(t);return(null==e?void 0:e.element)||null}let i=null;if(i=document.querySelector(n),!i&&e){const t=e.closest("[data-live-component]");t&&(i=t.querySelector(n))}if(!i){console.warn(`[LiveComponent] Target element not found: ${n}, falling back to component element`);const e=this.components.get(t);return(null==e?void 0:e.element)||null}return i}updateFragments(e,t){const n=e.dataset.liveComponent;n&&this.accessibilityManager.captureFocusState(n,e);const i=this.domPatcher.patchFragments(e,t);if(n&&this.accessibilityManager.restoreFocus(n,e),Object.keys(t).forEach(t=>{if(i[t]){const n=e.querySelector(`[data-lc-fragment="${t}"]`);n&&this.setupActionHandlers(n)}}),n){const e=Object.keys(t).filter(e=>i[e]);e.length>0&&this.accessibilityManager.announceUpdate(n,"fragment",{fragmentName:e.join(", ")})}const s=Object.values(i).filter(Boolean).length;console.log(`[LiveComponent] Patched ${s}/${Object.keys(t).length} fragments`,i)}handleServerEvents(e){e.forEach(e=>{const{name:t,payload:n,target:i}=e;console.log("[LiveComponent] Server event:",{name:t,payload:n,target:i}),this.logEventToDevTools(t,{payload:n,target:i},"server");const s=Array.isArray(n)?n:n||{};i?this.dispatchToComponent(i,t,s):this.broadcast(t,s)})}dispatchToComponent(e,t,n){(this.eventHandlers.get(t)||[]).forEach(t=>{t.componentId===e&&t.callback(n)}),document.dispatchEvent(new CustomEvent(`livecomponent:${t}`,{detail:n})),this.isUIEvent(t)&&document.dispatchEvent(new CustomEvent(t,{detail:n}))}dispatchComponentEvent(e,t,n){const i=Array.isArray(n)?n:n||{};this.dispatchToComponent(e,t,i),this.isUIEvent(t)&&this.broadcast(t,i)}broadcast(e,t){(this.eventHandlers.get(e)||[]).forEach(e=>{e.callback(t)}),document.dispatchEvent(new CustomEvent(`livecomponent:${e}`,{detail:t})),this.isUIEvent(e)&&document.dispatchEvent(new CustomEvent(e,{detail:t}))}isUIEvent(e){return["toast:","modal:"].some(t=>e.startsWith(t))}on(e,t,n){this.eventHandlers.has(t)||this.eventHandlers.set(t,[]),this.eventHandlers.get(t).push({componentId:e,callback:n}),console.log(`[LiveComponent] Event listener registered: ${e} -> ${t}`)}startPolling(e){const t=this.components.get(e);t&&t.pollInterval&&(t.pollTimer&&clearInterval(t.pollTimer),t.pollTimer=setInterval(async()=>{await this.executeAction(e,"poll",{})},t.pollInterval),console.log(`[LiveComponent] Polling started: ${e} (${t.pollInterval}ms)`))}stopPolling(e){const t=this.components.get(e);t&&t.pollTimer&&(clearInterval(t.pollTimer),t.pollTimer=null,console.log(`[LiveComponent] Polling stopped: ${e}`))}handleError(e,t){const n=this.components.get(e);if(!n)return;const i=`\n <div class="livecomponent-error" style="padding: 1rem; background: #fee; color: #c00; border: 1px solid #faa; border-radius: 4px;">\n <strong>LiveComponent Error:</strong> ${t.message}\n </div>\n `;n.element.insertAdjacentHTML("beforeend",i),setTimeout(()=>{var e;null==(e=n.element.querySelector(".livecomponent-error"))||e.remove()},5e3)}showConflictNotification(e,t){const n=this.components.get(e);if(!n)return;const i=`\n <div class="livecomponent-conflict" style="\n padding: 1rem;\n background: #fff3cd;\n color: #856404;\n border: 1px solid #ffc107;\n border-radius: 4px;\n margin-bottom: 1rem;\n display: flex;\n align-items: center;\n justify-content: space-between;\n ">\n <div>\n <strong>${t.title}</strong>\n <p style="margin: 0.5rem 0 0 0;">${t.message}</p>\n </div>\n ${t.canRetry?`\n <button\n class="livecomponent-retry"\n style="\n padding: 0.5rem 1rem;\n background: #ffc107;\n color: #000;\n border: none;\n border-radius: 4px;\n cursor: pointer;\n margin-left: 1rem;\n "\n data-operation-id="${t.operation.id}"\n data-action="${t.operation.metadata.action}"\n >\n Retry\n </button>\n `:""}\n </div>\n `;if(n.element.insertAdjacentHTML("afterbegin",i),t.canRetry){const i=n.element.querySelector(".livecomponent-retry");i&&i.addEventListener("click",async()=>{var i;null==(i=n.element.querySelector(".livecomponent-conflict"))||i.remove(),await yt.retryOperation(e,t.operation,async t=>await this.executeAction(e,t.action,t.params))})}setTimeout(()=>{var e;null==(e=n.element.querySelector(".livecomponent-conflict"))||e.remove()},8e3),console.log(`[LiveComponent] Conflict notification shown for ${e}`,t)}setupFileUploadHandlers(e){const t=e.dataset.liveComponent;e.querySelectorAll('input[type="file"][data-live-upload]').forEach(e=>{e.addEventListener("change",async e=>{const n=e.target.files;n.length>0&&await this.uploadFile(t,n[0])})}),e.querySelectorAll("[data-live-dropzone]").forEach(e=>{this.setupDropzone(t,e)})}setupDropzone(e,t){["dragenter","dragover","dragleave","drop"].forEach(e=>{t.addEventListener(e,e=>{e.preventDefault(),e.stopPropagation()})}),["dragenter","dragover"].forEach(e=>{t.addEventListener(e,()=>{t.classList.add("drag-over")})}),["dragleave","drop"].forEach(e=>{t.addEventListener(e,()=>{t.classList.remove("drag-over")})}),t.addEventListener("drop",async t=>{const n=t.dataTransfer.files;n.length>0&&await this.uploadFile(e,n[0])})}async uploadFile(e,t,n={}){const i=this.components.get(e);if(i)try{const s=i.element.dataset.state||"{}",o=JSON.parse(s),a=new FormData;a.append("file",t),a.append("state",JSON.stringify(o)),a.append("params",JSON.stringify(n));const r=i.element.dataset.csrfToken;if(!r)throw console.error(`[LiveComponent] Missing CSRF token for upload: ${e}`),new Error("CSRF token is required for file uploads");a.append("_csrf_token",r),this.showUploadProgress(e,0);const l=await fetch(`/live-component/${e}/upload`,{method:"POST",headers:{"X-Requested-With":"XMLHttpRequest"},body:a});if(!l.ok){const e=await l.json();throw new Error(e.error||"Upload failed")}const c=await l.json();if(!c.success)throw new Error(c.error||"Upload failed");c.html&&(i.element.innerHTML=c.html,this.setupActionHandlers(i.element),this.setupFileUploadHandlers(i.element)),c.state&&Et(i.element,c.state),c.events&&c.events.length>0&&this.handleServerEvents(c.events),this.hideUploadProgress(e),console.log(`[LiveComponent] File uploaded: ${e}`,c.file),document.dispatchEvent(new CustomEvent("livecomponent:upload:success",{detail:{componentId:e,file:c.file}}))}catch(s){console.error("[LiveComponent] Upload failed:",s),this.hideUploadProgress(e),this.handleError(e,s),document.dispatchEvent(new CustomEvent("livecomponent:upload:error",{detail:{componentId:e,error:s.message}}))}else console.error(`[LiveComponent] Unknown component: ${e}`)}showUploadProgress(e,t){const n=this.components.get(e);if(!n)return;let i=n.element.querySelector(".livecomponent-upload-progress");if(i){i.querySelector(".progress-bar").style.width=`${t}%`}else{i=document.createElement("div"),i.className="livecomponent-upload-progress",i.style.cssText="\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n height: 3px;\n background: #e0e0e0;\n z-index: 1000;\n ";const e=document.createElement("div");e.className="progress-bar",e.style.cssText=`\n height: 100%;\n background: #2196F3;\n transition: width 0.3s ease;\n width: ${t}%;\n `,i.appendChild(e),n.element.style.position="relative",n.element.appendChild(i)}}hideUploadProgress(e){const t=this.components.get(e);if(!t)return;const n=t.element.querySelector(".livecomponent-upload-progress");n&&n.remove()}destroy(e){const t=this.components.get(e);this.stopPolling(e),t&&t.observer&&t.observer.disconnect(),this.cleanupSseConnection(e),this.accessibilityManager.cleanup(e),this.errorBoundary.clearErrorHandler(e),this.requestDeduplicator.clearComponent(e),this.tooltipManager.cleanupComponent(t.element),this.loadingStateManager.hideLoading(e,null),this.loadingStateManager.clearConfig(e),this.uiHelper.cleanup(e),this.components.delete(e),this.eventHandlers.forEach((t,n)=>{const i=t.filter(t=>t.componentId!==e);this.eventHandlers.set(n,i)}),console.log(`[LiveComponent] Destroyed: ${e}`)}cleanupSseConnection(e){const t=this.componentChannels.get(e);if(!t)return;this.componentChannels.delete(e);let n=!1;for(const[,i]of this.componentChannels)if(i===t){n=!0;break}if(!n){const e=this.sseClients.get(t);e&&(e.disconnect(),this.sseClients.delete(t),console.log(`[LiveComponent] Disconnected SSE client for channel: ${t}`))}}async executeBatch(e,t={}){if(!Array.isArray(e)||0===e.length)throw new Error("Operations must be a non-empty array");const n={operations:e.map(e=>({componentId:e.componentId,method:e.method,params:e.params||{},fragments:e.fragments||null,operationId:e.operationId||null}))};console.log(`[LiveComponent] Executing batch with ${e.length} operations`,n);try{const e=await fetch("/live-component/batch",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n)});if(!e.ok){const t=await e.json();throw new Error(t.error||"Batch request failed")}const i=await e.json();return console.log(`[LiveComponent] Batch completed: ${i.success_count} succeeded, ${i.failure_count} failed`),!1!==t.autoApply&&await this.applyBatchResults(i.results),i}catch(i){throw console.error("[LiveComponent] Batch execution failed:",i),i}}async applyBatchResults(e){for(const n of e){if(!n.success){console.warn("[LiveComponent] Batch operation failed:",n);continue}const e=n.componentId||this.extractComponentIdFromResult(n);if(!e)continue;const i=this.components.get(e);if(i)try{n.fragments?this.updateFragments(i.element,n.fragments):n.html&&(i.element.innerHTML=n.html,this.setupActionHandlers(i.element)),n.state&&Et(i.element,n.state),n.events&&Array.isArray(n.events)&&n.events.forEach(t=>{this.dispatchComponentEvent(e,t.name,t.payload||{})})}catch(t){console.error(`[LiveComponent] Failed to apply batch result for ${e}:`,t)}}}extractComponentIdFromResult(e){return e.componentId||null}queueBatchOperation(e,t={}){this.batchQueue||(this.batchQueue=[],this.batchQueueTimer=null),this.batchQueue.push(e),this.batchQueueTimer&&clearTimeout(this.batchQueueTimer);const n=t.flushDelay||50;this.batchQueueTimer=setTimeout(()=>{this.flushBatchQueue()},n)}async flushBatchQueue(){if(!this.batchQueue||0===this.batchQueue.length)return;const e=[...this.batchQueue];this.batchQueue=[],this.batchQueueTimer=null;try{await this.executeBatch(e)}catch(t){console.error("[LiveComponent] Batch queue flush failed:",t)}}};window.LiveComponent=Qt,"loading"===document.readyState&&document.addEventListener("DOMContentLoaded",()=>{document.querySelectorAll("[data-live-component]").forEach(e=>{Qt.init(e)})});const Kt=Object.freeze(Object.defineProperty({__proto__:null,ChunkedUploader:class{constructor(e,t={}){this.componentId=e,this.chunkSize=t.chunkSize||524288,this.maxConcurrentChunks=t.maxConcurrentChunks||3,this.maxRetries=t.maxRetries||3,this.retryDelay=t.retryDelay||1e3,this.enableSSE=!1!==t.enableSSE,this.apiBase=t.apiBase||"/live-component/upload",this.onInitialized=t.onInitialized||(()=>{}),this.onChunkProgress=t.onChunkProgress||(()=>{}),this.onProgress=t.onProgress||(()=>{}),this.onComplete=t.onComplete||(()=>{}),this.onError=t.onError||(()=>{}),this.onAborted=t.onAborted||(()=>{}),this.onSSEProgress=t.onSSEProgress||(()=>{}),this.sessions=new Map,this.activeSession=null,this.sseClient=null,this.userId=null,this.enableSSE&&this.initializeSSE()}initializeSSE(){try{this.userId=this.getUserId(),this.userId&&(this.sseClient=rt([`user:${this.userId}`]),this.sseClient.on("progress",e=>{this.handleSSEProgress(e)}),this.sseClient.isConnected()||this.sseClient.connect())}catch(e){console.warn("[ChunkedUploader] Failed to initialize SSE:",e)}}getUserId(){const e=document.querySelector('meta[name="user-id"]');return e?e.content:document.body.dataset.userId?document.body.dataset.userId:null}handleSSEProgress(e){var t,n;const i=e.session_id,s=this.sessions.get(i);if(s&&e.taskId===i){if(void 0!==(null==(t=e.data)?void 0:t.uploaded_chunks)&&(s.uploadedChunks=e.data.uploaded_chunks),null==(n=e.data)?void 0:n.phase)switch(e.data.phase){case"initialized":s.status=Ht;break;case"uploading":s.status=Ut;break;case"completed":s.status=Wt;break;case"aborted":s.status=Vt;break;case"error":s.status=Gt}this.onSSEProgress({sessionId:i,percent:e.percent,message:e.message,data:e.data})}}async upload(e,t){const n=new Xt(e,{chunkSize:this.chunkSize});this.activeSession=n;try{n.totalChunks=Math.ceil(e.size/this.chunkSize);for(let t=0;t<n.totalChunks;t++){const i=t*this.chunkSize,s=Math.min(i+this.chunkSize,e.size)-i;n.chunks.push(new Jt(t,s,e))}return await this.initializeSession(n),this.sessions.set(n.sessionId,n),n.status=Ut,n.startTime=Date.now(),await this.uploadChunks(n),await this.completeUpload(n,t),n.status=Wt,n.endTime=Date.now(),this.onComplete({sessionId:n.sessionId,file:n.file,totalBytes:n.totalBytes,duration:n.endTime-n.startTime}),n}catch(i){throw n.status=Gt,n.error=i.message,this.onError({sessionId:n.sessionId,file:n.file,error:i.message}),i}}async initializeSession(e){const t=await fetch(`${this.apiBase}/init`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","User-Agent":navigator.userAgent},body:JSON.stringify({componentId:this.componentId,fileName:e.file.name,totalSize:e.file.size,chunkSize:this.chunkSize})});if(!t.ok)throw new Error(`Failed to initialize upload session: ${t.status}`);const n=await t.json();if(!n.success)throw new Error(n.error||"Failed to initialize upload session");e.sessionId=n.session_id,e.totalChunks=n.total_chunks,e.expiresAt=new Date(n.expires_at),e.status=Ht,this.onInitialized({sessionId:e.sessionId,totalChunks:e.totalChunks,expiresAt:e.expiresAt})}async uploadChunks(e){const t=e.getPendingChunks();for(;t.length>0;){const n=t.splice(0,this.maxConcurrentChunks);await Promise.all(n.map(t=>this.uploadChunk(e,t)))}}async uploadChunk(e,t){let n=0;for(;n<=this.maxRetries;)try{t.status=Rt;const n=await this.readChunk(e.file,t),i=await this.hashChunk(n);return t.hash=i,t.status=Ft,await this.uploadChunkData(e,t,n,i),t.status=qt,e.uploadedChunks++,void this.onProgress({sessionId:e.sessionId,progress:e.progress,uploadedChunks:e.uploadedChunks,totalChunks:e.totalChunks,uploadedBytes:e.uploadedBytes,totalBytes:e.totalBytes})}catch(i){if(n++,n>this.maxRetries)throw t.status=Nt,t.error=i.message,new Error(`Chunk ${t.index} failed after ${this.maxRetries} retries: ${i.message}`);const e=this.retryDelay*Math.pow(2,n-1);await this.sleep(e),t.reset()}}readChunk(e,t){return new Promise((n,i)=>{const s=t.index*this.chunkSize,o=Math.min(s+t.size,e.size),a=e.slice(s,o),r=new FileReader;r.onload=e=>n(e.target.result),r.onerror=e=>i(new Error("Failed to read chunk")),r.readAsArrayBuffer(a)})}async hashChunk(e){const t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")}uploadChunkData(e,t,n,i){return new Promise((s,o)=>{const a=new FormData;a.append("sessionId",e.sessionId),a.append("chunkIndex",t.index),a.append("chunkHash",i),a.append("chunk",new Blob([n]));const r=new XMLHttpRequest;t.xhr=r,r.upload.addEventListener("progress",n=>{n.lengthComputable&&(t.uploadedBytes=n.loaded,this.onChunkProgress({sessionId:e.sessionId,chunkIndex:t.index,uploadedBytes:n.loaded,totalBytes:n.total,progress:n.loaded/n.total*100}))}),r.addEventListener("load",()=>{if(r.status>=200&&r.status<300)try{const e=JSON.parse(r.responseText);e.success?s(e):o(new Error(e.error||"Chunk upload failed"))}catch(e){o(e)}else o(new Error(`Chunk upload failed with status ${r.status}`))}),r.addEventListener("error",()=>{o(new Error("Network error during chunk upload"))}),r.addEventListener("abort",()=>{o(new Error("Chunk upload cancelled"))}),r.open("POST",`${this.apiBase}/chunk`),r.setRequestHeader("Accept","application/json"),r.setRequestHeader("User-Agent",navigator.userAgent),r.send(a)})}async completeUpload(e,t){e.status=jt;const n=await fetch(`${this.apiBase}/complete`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","User-Agent":navigator.userAgent},body:JSON.stringify({sessionId:e.sessionId,targetPath:t})});if(!n.ok)throw new Error(`Failed to complete upload: ${n.status}`);const i=await n.json();if(!i.success)throw new Error(i.error||"Failed to complete upload");return i}async abort(e){const t=this.sessions.get(e);if(!t)throw new Error("Session not found");t.chunks.forEach(e=>e.abort());try{await fetch(`${this.apiBase}/abort`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","User-Agent":navigator.userAgent},body:JSON.stringify({sessionId:e,reason:"User cancelled"})})}catch(n){console.warn("[ChunkedUploader] Failed to notify server of abort:",n)}t.status=Vt,this.onAborted({sessionId:e,uploadedChunks:t.uploadedChunks,totalChunks:t.totalChunks})}async getStatus(e){const t=await fetch(`${this.apiBase}/status/${e}`,{headers:{Accept:"application/json","User-Agent":navigator.userAgent}});if(!t.ok)throw new Error(`Failed to get upload status: ${t.status}`);const n=await t.json();if(!n.success)throw new Error(n.error||"Failed to get upload status");return n}async resume(e,t,n){const i=await this.getStatus(e),s=new Xt(t,{chunkSize:this.chunkSize});s.sessionId=e,s.totalChunks=i.total_chunks,s.uploadedChunks=i.uploaded_chunks,s.status=Ut;for(let o=0;o<s.totalChunks;o++){const e=o*this.chunkSize,n=Math.min(e+this.chunkSize,t.size),a=new Jt(o,n-e,t);o<i.uploaded_chunks&&(a.status=qt,a.uploadedBytes=a.size),s.chunks.push(a)}return this.sessions.set(e,s),this.activeSession=s,s.startTime=Date.now(),await this.uploadChunks(s),await this.completeUpload(s,n),s.status=Wt,s.endTime=Date.now(),this.onComplete({sessionId:s.sessionId,file:s.file,totalBytes:s.totalBytes,duration:s.endTime-s.startTime,resumed:!0}),s}sleep(e){return new Promise(t=>setTimeout(t,e))}destroy(){this.sessions.forEach(e=>{e.canResume&&e.chunks.forEach(e=>e.abort())}),this.sessions.clear(),this.activeSession=null}},ComponentFileUploader:ft,ComponentPlayground:class{constructor(e){if(this.container=document.querySelector(e),!this.container)throw new Error(`Container not found: ${e}`);this.components=[],this.selectedComponent=null,this.componentMetadata=null,this.currentState={},this.previewInstanceId=`playground-${Date.now()}`,this.componentList=null,this.componentSearch=null,this.stateEditor=null,this.previewContainer=null,this.actionTester=null,this.metricsDisplay=null,this.metrics={renderTime:0,stateSize:0,actionExecutions:0}}async init(){this.buildUI(),await this.loadComponents(),this.attachEventListeners()}buildUI(){this.container.innerHTML='\n <div class="playground">\n \x3c!-- Header --\x3e\n <header class="playground__header">\n <h1 class="playground__title">LiveComponent Playground</h1>\n <p class="playground__subtitle">Interactive development tool for testing LiveComponents</p>\n </header>\n\n \x3c!-- Main Layout --\x3e\n <div class="playground__layout">\n \x3c!-- Sidebar: Component Selector --\x3e\n <aside class="playground__sidebar">\n <div class="playground__search">\n <input\n type="text"\n id="component-search"\n class="playground__search-input"\n placeholder="Search components..."\n autocomplete="off"\n />\n </div>\n <div id="component-list" class="playground__component-list">\n <div class="playground__loading">Loading components...</div>\n </div>\n </aside>\n\n \x3c!-- Main Content --\x3e\n <main class="playground__main">\n \x3c!-- State Editor --\x3e\n <section class="playground__section">\n <h2 class="playground__section-title">Component State</h2>\n <div class="playground__state-editor">\n <textarea\n id="state-editor"\n class="playground__textarea"\n placeholder=\'{\n "property": "value"\n}\'\n rows="10"\n ></textarea>\n <div class="playground__editor-actions">\n <button id="apply-state" class="playground__button playground__button--primary">\n Apply State\n </button>\n <button id="reset-state" class="playground__button">\n Reset\n </button>\n <button id="format-json" class="playground__button">\n Format JSON\n </button>\n </div>\n <div id="state-validation" class="playground__validation"></div>\n </div>\n </section>\n\n \x3c!-- Live Preview --\x3e\n <section class="playground__section">\n <h2 class="playground__section-title">Live Preview</h2>\n <div id="preview-container" class="playground__preview">\n <div class="playground__empty">\n Select a component to preview\n </div>\n </div>\n <div id="metrics-display" class="playground__metrics"></div>\n </section>\n\n \x3c!-- Action Tester --\x3e\n <section class="playground__section">\n <h2 class="playground__section-title">Actions</h2>\n <div id="action-tester" class="playground__actions">\n <div class="playground__empty">\n Select a component to test actions\n </div>\n </div>\n </section>\n\n \x3c!-- Code Generator --\x3e\n <section class="playground__section">\n <h2 class="playground__section-title">Template Code</h2>\n <div class="playground__code-generator">\n <pre id="generated-code" class="playground__code"><code>Select a component to generate code</code></pre>\n <button id="copy-code" class="playground__button">\n Copy to Clipboard\n </button>\n </div>\n </section>\n </main>\n </div>\n </div>\n ',this.componentList=this.container.querySelector("#component-list"),this.componentSearch=this.container.querySelector("#component-search"),this.stateEditor=this.container.querySelector("#state-editor"),this.previewContainer=this.container.querySelector("#preview-container"),this.actionTester=this.container.querySelector("#action-tester"),this.metricsDisplay=this.container.querySelector("#metrics-display")}async loadComponents(){try{const e=await fetch("/playground/api/components"),t=await e.json();this.components=t.components||[],this.renderComponentList(this.components)}catch(e){this.componentList.innerHTML=`\n <div class="playground__error">\n Failed to load components: ${e.message}\n </div>\n `}}renderComponentList(e){0!==e.length?this.componentList.innerHTML=e.map(e=>`\n <div class="playground__component-item" data-component="${e.name}">\n <div class="playground__component-name">${e.name}</div>\n <div class="playground__component-meta">\n <span class="playground__badge">${e.properties} props</span>\n <span class="playground__badge">${e.actions} actions</span>\n ${e.has_cache?'<span class="playground__badge playground__badge--cache">cached</span>':""}\n </div>\n </div>\n `).join(""):this.componentList.innerHTML='<div class="playground__empty">No components found</div>'}attachEventListeners(){this.componentList.addEventListener("click",e=>{const t=e.target.closest(".playground__component-item");t&&this.selectComponent(t.dataset.component)}),this.componentSearch.addEventListener("input",e=>{this.filterComponents(e.target.value)}),this.container.querySelector("#apply-state").addEventListener("click",()=>{this.applyState()}),this.container.querySelector("#reset-state").addEventListener("click",()=>{this.resetState()}),this.container.querySelector("#format-json").addEventListener("click",()=>{this.formatJSON()}),this.container.querySelector("#copy-code").addEventListener("click",()=>{this.copyCode()})}filterComponents(e){const t=e.toLowerCase().trim();if(!t)return void this.renderComponentList(this.components);const n=this.components.filter(e=>e.name.toLowerCase().includes(t)||e.class.toLowerCase().includes(t));this.renderComponentList(n)}async selectComponent(e){this.componentList.querySelectorAll(".playground__component-item").forEach(e=>{e.classList.remove("playground__component-item--active")});const t=this.componentList.querySelector(`[data-component="${e}"]`);t&&t.classList.add("playground__component-item--active"),this.selectedComponent=e,await this.loadComponentMetadata(e),this.resetState(),this.renderActions(),this.updateGeneratedCode()}async loadComponentMetadata(e){try{const t=await fetch(`/playground/api/component/${e}`),n=await t.json();n.success?this.componentMetadata=n.data:console.error("Failed to load metadata:",n.error)}catch(t){console.error("Error loading metadata:",t)}}async applyState(){const e=this.stateEditor.value.trim(),t=this.container.querySelector("#state-validation");try{const n=e?JSON.parse(e):{};this.currentState=n,t.innerHTML='<span class="playground__success">✓ Valid JSON</span>',await this.previewComponent()}catch(n){t.innerHTML=`<span class="playground__error">✗ Invalid JSON: ${n.message}</span>`}}resetState(){this.currentState={},this.stateEditor.value="{}",this.container.querySelector("#state-validation").innerHTML="",this.selectedComponent&&this.previewComponent()}formatJSON(){try{const e=JSON.parse(this.stateEditor.value||"{}");this.stateEditor.value=JSON.stringify(e,null,2),this.container.querySelector("#state-validation").innerHTML='<span class="playground__success">✓ Formatted</span>'}catch(e){this.container.querySelector("#state-validation").innerHTML='<span class="playground__error">✗ Invalid JSON</span>'}}async previewComponent(){if(this.selectedComponent){this.previewContainer.innerHTML='<div class="playground__loading">Loading preview...</div>';try{performance.now();const e=await fetch("/playground/api/preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({component_name:this.selectedComponent,state:this.currentState,instance_id:this.previewInstanceId})}),t=await e.json();performance.now();t.success?(this.previewContainer.innerHTML=t.html,this.metrics.renderTime=t.render_time_ms,this.metrics.stateSize=JSON.stringify(t.state).length,this.updateMetrics(),window.LiveComponent&&window.LiveComponent.initComponent(this.previewContainer.firstElementChild)):this.previewContainer.innerHTML=`\n <div class="playground__error">\n Preview failed: ${t.error}\n </div>\n `}catch(e){this.previewContainer.innerHTML=`\n <div class="playground__error">\n Error: ${e.message}\n </div>\n `}}}renderActions(){if(!this.componentMetadata||!this.componentMetadata.actions)return void(this.actionTester.innerHTML='<div class="playground__empty">No actions available</div>');const e=this.componentMetadata.actions.filter(e=>!["onMount","onUpdated","onDestroy"].includes(e.name));0!==e.length?(this.actionTester.innerHTML=e.map(e=>`\n <div class="playground__action">\n <button\n class="playground__button playground__button--action"\n data-action="${e.name}"\n >\n ${e.name}()\n </button>\n ${e.parameters.length>0?`\n <div class="playground__action-params">\n ${e.parameters.map(e=>`\n <label>\n ${e.name} (${e.type}):\n <input type="text" data-param="${e.name}" placeholder="${e.type}" />\n </label>\n `).join("")}\n </div>\n `:""}\n </div>\n `).join(""),this.actionTester.querySelectorAll("[data-action]").forEach(e=>{e.addEventListener("click",()=>{this.executeAction(e.dataset.action,e.closest(".playground__action"))})})):this.actionTester.innerHTML='<div class="playground__empty">No actions available</div>'}async executeAction(e,t){const n={};t&&t.querySelectorAll("[data-param]").forEach(e=>{const t=e.dataset.param;let i=e.value;"true"===i?i=!0:"false"===i?i=!1:isNaN(i)||""===i||(i=Number(i)),n[t]=i});try{const t=await fetch("/playground/api/action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({component_id:`${this.selectedComponent}:${this.previewInstanceId}`,action_name:e,parameters:n,current_state:this.currentState})}),i=await t.json();i.success?(this.currentState=i.new_state,this.stateEditor.value=JSON.stringify(this.currentState,null,2),this.previewContainer.innerHTML=i.html,this.metrics.actionExecutions++,this.updateMetrics(),window.LiveComponent&&window.LiveComponent.initComponent(this.previewContainer.firstElementChild)):alert(`Action failed: ${i.error}`)}catch(i){alert(`Error executing action: ${i.message}`)}}updateMetrics(){this.metricsDisplay.innerHTML=`\n <div class="playground__metrics-grid">\n <div class="playground__metric">\n <span class="playground__metric-label">Render Time</span>\n <span class="playground__metric-value">${this.metrics.renderTime.toFixed(2)}ms</span>\n </div>\n <div class="playground__metric">\n <span class="playground__metric-label">State Size</span>\n <span class="playground__metric-value">${this.metrics.stateSize} bytes</span>\n </div>\n <div class="playground__metric">\n <span class="playground__metric-label">Actions Executed</span>\n <span class="playground__metric-value">${this.metrics.actionExecutions}</span>\n </div>\n </div>\n `}updateGeneratedCode(){if(!this.selectedComponent)return;const e=`\x3c!-- Use in your template --\x3e\n{{{ ${this.selectedComponent} }}}`;this.container.querySelector("#generated-code code").textContent=e}async copyCode(){const e=this.container.querySelector("#generated-code code").textContent;try{await navigator.clipboard.writeText(e);const t=this.container.querySelector("#copy-code"),n=t.textContent;t.textContent="✓ Copied!",setTimeout(()=>{t.textContent=n},2e3)}catch(t){alert("Failed to copy code to clipboard")}}},FileUploadWidget:class{constructor(e,t={}){if(this.container=e,this.componentElement=e.closest("[data-live-id]"),!this.componentElement)throw new Error("FileUploadWidget must be used inside a LiveComponent");this.options={maxFileSize:t.maxFileSize||10485760,allowedMimeTypes:t.allowedMimeTypes||[],allowedExtensions:t.allowedExtensions||[],maxFiles:t.maxFiles||10,showPreviews:!1!==t.showPreviews,showProgress:!1!==t.showProgress,showFileList:!1!==t.showFileList,autoUpload:!1!==t.autoUpload,multiple:!1!==t.multiple,dropZoneText:t.dropZoneText||"Drag & drop files here or click to browse",browseButtonText:t.browseButtonText||"Browse Files",uploadButtonText:t.uploadButtonText||"Upload All",...t},this.files=new Map,this.buildUI(),this.initializeUploader()}buildUI(){var e,t,n;this.container.innerHTML=`\n <div class="file-upload-widget">\n \x3c!-- Drop Zone --\x3e\n <div class="file-upload-dropzone" data-dropzone>\n <div class="dropzone-content">\n <svg class="dropzone-icon" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor">\n <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>\n <polyline points="17 8 12 3 7 8"></polyline>\n <line x1="12" y1="3" x2="12" y2="15"></line>\n </svg>\n <p class="dropzone-text">${this.options.dropZoneText}</p>\n <button type="button" class="btn btn-primary dropzone-button" data-browse-button>\n ${this.options.browseButtonText}\n </button>\n <input\n type="file"\n class="dropzone-input"\n data-file-input\n ${this.options.multiple?"multiple":""}\n ${this.options.allowedMimeTypes.length>0?`accept="${this.options.allowedMimeTypes.join(",")}"`:""}\n style="display: none;"\n />\n </div>\n </div>\n\n \x3c!-- File List --\x3e\n ${this.options.showFileList?`\n <div class="file-upload-list" data-file-list style="display: none;">\n <div class="file-list-header">\n <h4>Files (0)</h4>\n <div class="file-list-actions">\n ${this.options.autoUpload?"":`<button type="button" class="btn btn-primary btn-sm" data-upload-all>${this.options.uploadButtonText}</button>`}\n <button type="button" class="btn btn-secondary btn-sm" data-clear-all>Clear All</button>\n </div>\n </div>\n <div class="file-list-items" data-file-items></div>\n </div>\n `:""}\n\n \x3c!-- Overall Progress (shown when uploading) --\x3e\n ${this.options.showProgress?'\n <div class="file-upload-progress" data-overall-progress style="display: none;">\n <div class="progress-info">\n <span class="progress-label">Uploading files...</span>\n <span class="progress-percentage" data-progress-text>0%</span>\n </div>\n <div class="progress-bar">\n <div class="progress-fill" data-progress-fill style="width: 0%"></div>\n </div>\n </div>\n ':""}\n </div>\n `,this.dropZone=this.container.querySelector("[data-dropzone]"),this.fileInput=this.container.querySelector("[data-file-input]"),this.browseButton=this.container.querySelector("[data-browse-button]"),this.fileList=this.container.querySelector("[data-file-list]"),this.fileItems=this.container.querySelector("[data-file-items]"),this.overallProgress=this.container.querySelector("[data-overall-progress]"),this.progressFill=this.container.querySelector("[data-progress-fill]"),this.progressText=this.container.querySelector("[data-progress-text]"),this.uploadAllButton=this.container.querySelector("[data-upload-all]"),this.clearAllButton=this.container.querySelector("[data-clear-all]"),null==(e=this.browseButton)||e.addEventListener("click",()=>this.fileInput.click()),null==(t=this.uploadAllButton)||t.addEventListener("click",()=>this.uploader.uploadAll()),null==(n=this.clearAllButton)||n.addEventListener("click",()=>this.clearAll())}initializeUploader(){this.uploader=new ft(this.componentElement,{...this.options,dropZone:this.dropZone,fileInput:this.fileInput,onFileAdded:e=>this.handleFileAdded(e),onFileRemoved:e=>this.handleFileRemoved(e),onUploadStart:e=>this.handleUploadStart(e),onUploadProgress:e=>this.handleUploadProgress(e),onUploadComplete:e=>this.handleUploadComplete(e),onUploadError:e=>this.handleUploadError(e),onAllUploadsComplete:e=>this.handleAllUploadsComplete(e)})}handleFileAdded({fileId:e,file:t,progress:n}){if(!this.options.showFileList)return;this.fileList&&(this.fileList.style.display="block");const i=this.createFileElement(e,t,n);this.fileItems.appendChild(i),this.files.set(e,i),this.updateFileCount()}handleFileRemoved({fileId:e}){const t=this.files.get(e);t&&(t.remove(),this.files.delete(e)),this.updateFileCount(),0===this.files.size&&this.fileList&&(this.fileList.style.display="none")}handleUploadStart({fileId:e}){this.updateFileStatus(e,"uploading"),this.overallProgress&&(this.overallProgress.style.display="block")}handleUploadProgress({fileId:e,percentage:t,uploadedBytes:n,totalBytes:i,uploadSpeed:s,remainingTime:o}){const a=this.files.get(e);if(a){const e=a.querySelector(".file-progress-fill"),n=a.querySelector(".file-progress-text");e&&(e.style.width=`${t}%`),n&&(n.textContent=`${t}%`)}const r=this.uploader.getStats();this.progressFill&&(this.progressFill.style.width=`${r.overallProgress}%`),this.progressText&&(this.progressText.textContent=`${r.overallProgress}%`)}handleUploadComplete({fileId:e,response:t}){this.updateFileStatus(e,"complete")}handleUploadError({fileId:e,error:t}){this.updateFileStatus(e,"error",t)}handleAllUploadsComplete({totalFiles:e,successCount:t,errorCount:n}){setTimeout(()=>{this.overallProgress&&(this.overallProgress.style.display="none")},2e3)}createFileElement(e,t,n){const i=document.createElement("div");i.className="file-item",i.dataset.fileId=e;const s=n.error?"error":"pending";i.innerHTML=`\n <div class="file-preview">\n ${this.options.showPreviews&&t.type.startsWith("image/")?`<img class="file-thumbnail" src="${URL.createObjectURL(t)}" alt="${t.name}" />`:this.getFileIconSvg(t.type)}\n </div>\n <div class="file-info">\n <div class="file-name" title="${t.name}">${this.truncateFileName(t.name,40)}</div>\n <div class="file-meta">\n <span class="file-size">${this.formatBytes(t.size)}</span>\n <span class="file-status" data-status="${s}">${n.error||"Pending"}</span>\n </div>\n ${this.options.showProgress?'\n <div class="file-progress" style="display: none;">\n <div class="file-progress-bar">\n <div class="file-progress-fill" style="width: 0%"></div>\n </div>\n <span class="file-progress-text">0%</span>\n </div>\n ':""}\n ${n.error?`\n <div class="file-error">${n.error}</div>\n `:""}\n </div>\n <div class="file-actions">\n <button type="button" class="btn-icon" data-remove-file title="Remove">\n <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">\n <line x1="18" y1="6" x2="6" y2="18"></line>\n <line x1="6" y1="6" x2="18" y2="18"></line>\n </svg>\n </button>\n </div>\n `;return i.querySelector("[data-remove-file]").addEventListener("click",()=>this.uploader.removeFile(e)),i}updateFileStatus(e,t,n=null){const i=this.files.get(e);if(!i)return;const s=i.querySelector(".file-status"),o=i.querySelector(".file-progress"),a=i.querySelector(".file-error");if(s){s.dataset.status=t;const e={pending:"Pending",uploading:"Uploading...",complete:"Complete",error:"Error"}[t]||t;s.textContent=e}o&&(o.style.display="uploading"===t?"flex":"none"),"error"===t&&n&&a&&(a.textContent=n,a.style.display="block"),i.classList.remove("file-uploading","file-complete","file-error"),"uploading"===t&&i.classList.add("file-uploading"),"complete"===t&&i.classList.add("file-complete"),"error"===t&&i.classList.add("file-error")}updateFileCount(){const e=this.container.querySelector(".file-list-header h4");e&&(e.textContent=`Files (${this.files.size})`)}clearAll(){this.uploader.clearAll(),this.fileItems.innerHTML="",this.files.clear(),this.fileList&&(this.fileList.style.display="none"),this.updateFileCount()}formatBytes(e){if(0===e)return"0 B";const t=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,t)*100)/100+" "+["B","KB","MB","GB"][t]}truncateFileName(e,t){if(e.length<=t)return e;const n=e.split(".").pop();return`${e.substring(0,e.length-n.length-1).substring(0,t-n.length-4)}...${n}`}getFileIconSvg(e){return'\n <svg class="file-icon" width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor">\n <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>\n <polyline points="14 2 14 8 20 8"></polyline>\n </svg>\n '}destroy(){this.uploader.destroy(),this.container.innerHTML="",this.files.clear()}},LiveComponent:Qt,LiveComponentUIHelper:Tt,LoadingStateManager:Dt,UIEventHandler:At,actionLoadingManager:$t,default:Qt,definition:{name:"livecomponent",version:"1.0.0",dependencies:[],provides:["LiveComponent"],priority:0},init:async function(e={},t={}){console.log("[LiveComponent] Module initializing..."),vt.initialize(),Qt.initLazyLoading(),Qt.initNestedComponents();const n=document.querySelectorAll("[data-live-component]");console.log(`[LiveComponent] Found ${n.length} regular components to initialize`),n.forEach(e=>{Qt.init(e)});const i=document.querySelectorAll("[data-live-component-lazy]");if(console.log(`[LiveComponent] Found ${i.length} lazy components (will load on demand)`),Qt.nestedHandler){const e=Qt.nestedHandler.getStats();console.log(`[LiveComponent] Nested components: ${e.child_components} children across ${e.root_components} roots (max depth: ${e.max_nesting_depth})`)}const s=vt.getStats();return console.log(`[LiveComponent] Accessibility: ${s.component_live_regions} component regions, ${s.tracked_focus_states} tracked focus states`),console.log("[LiveComponent] Module initialized"),{manager:Qt,state:t}},initElement:function(e,t={}){console.log("[LiveComponent] Initializing element with data-module:",e);const n=e.querySelectorAll("[data-live-component]");return 0===n.length&&e.hasAttribute("data-live-component")?Qt.init(e):n.forEach(e=>Qt.init(e)),Qt},tooltipManager:Pt},Symbol.toStringTag,{value:"Module"}));const Yt=Object.freeze(Object.defineProperty({__proto__:null,init:function(e={}){d.log("Noise Toggle Init",e);const{selector:t=".noise-overlay",toggleKey:n="g",className:i="grainy",enableTransition:s=!0}=e,o=document.body,a=document.querySelector(t);if(!a)return;function r(){s?a.classList.toggle("hidden",!o.classList.contains(i)):a.style.display=o.classList.contains(i)?"block":"none"}r(),document.addEventListener("keydown",e=>{var t;e.key.toLowerCase()!==n||e.ctrlKey||e.metaKey||e.altKey||(t=e.target,["input","textarea"].includes(t.tagName.toLowerCase()))||(o.classList.toggle(i),r())})}},Symbol.toStringTag,{value:"Module"}));const Zt=Object.freeze(Object.defineProperty({__proto__:null,init:function(e={}){d.info("Parallax init");const t={selector:"[data-parallax]",speedAttr:"data-parallax-speed",defaultSpeed:.5,...e},n=document.querySelectorAll(t.selector);l("parallax",function(){const e=window.scrollY;n.forEach(n=>{const i=parseFloat(n.getAttribute(t.speedAttr))||t.defaultSpeed,s=e*i;n.style.transform=`translateY(${s}px)`})},{autoStart:!0})}},Symbol.toStringTag,{value:"Module"}));class en{constructor(e={}){this.enabled=e.enabled??!1,this.maxSamples=e.maxSamples??1e3,this.samplingInterval=e.samplingInterval??10,this.autoStart=e.autoStart??!1,this.samples=[],this.timeline=[],this.marks=new Map,this.measures=new Map,this.isRecording=!1,this.recordingStartTime=null,this.autoStart&&this.enabled&&this.start()}start(){this.isRecording?console.warn("[PerformanceProfiler] Already recording"):(this.isRecording=!0,this.recordingStartTime=performance.now(),this.samples=[],this.timeline=[],console.log("[PerformanceProfiler] Started recording"))}stop(){if(!this.isRecording)return console.warn("[PerformanceProfiler] Not recording"),null;this.isRecording=!1;const e={duration:performance.now()-this.recordingStartTime,samples:this.samples,timeline:this.timeline,marks:Array.from(this.marks.entries()),measures:Array.from(this.measures.entries()),summary:this.generateSummary()};return console.log("[PerformanceProfiler] Stopped recording",e),e}mark(e,t={}){if(!this.isRecording&&!this.enabled)return;const n=performance.now(),i={name:e,timestamp:n,relativeTime:n-this.recordingStartTime,metadata:t};this.marks.set(e,i),performance.mark&&performance.mark(e),this.timeline.push({type:"mark",...i})}measure(e,t,n=null){var i;if(!this.isRecording&&!this.enabled)return;const s=this.marks.get(t);if(!s)return void console.warn(`[PerformanceProfiler] Start mark "${t}" not found`);const o=n?null==(i=this.marks.get(n))?void 0:i.timestamp:performance.now();if(!o)return void console.warn(`[PerformanceProfiler] End mark "${n}" not found`);const a={name:e,startMark:t,endMark:n,duration:o-s.timestamp,startTime:s.timestamp,endTime:o,relativeStartTime:s.relativeTime,relativeEndTime:o-this.recordingStartTime};if(this.measures.set(e,a),performance.measure&&n)try{performance.measure(e,t,n)}catch(r){}this.timeline.push({type:"measure",...a})}sample(e,t=[],n=0){this.isRecording&&(this.samples.length>=this.maxSamples?console.warn("[PerformanceProfiler] Max samples reached"):this.samples.push({timestamp:performance.now(),relativeTime:performance.now()-this.recordingStartTime,functionName:e,stackTrace:t,duration:n}))}generateFlamegraph(){if(0===this.samples.length)return null;const e={name:"(root)",value:0,children:[]};for(const t of this.samples){let n=e;const i=[t.functionName,...t.stackTrace].reverse();for(const e of i){let i=n.children.find(t=>t.name===e);i||(i={name:e,value:0,children:[]},n.children.push(i)),i.value+=t.duration||1,n=i}}return e}generateTimeline(){return this.timeline.map(e=>({...e,category:this.categorizeEvent(e),color:this.getEventColor(e)}))}generateSummary(){const e=Array.from(this.measures.values()).map(e=>e.duration);if(0===e.length)return{totalMeasures:0,totalSamples:this.samples.length,totalDuration:0};const t=e.reduce((e,t)=>e+t,0),n=t/e.length,i=Math.max(...e),s=Math.min(...e),o=[...e].sort((e,t)=>e-t),a=o[Math.floor(.5*o.length)],r=o[Math.floor(.9*o.length)],l=o[Math.floor(.99*o.length)];return{totalMeasures:this.measures.size,totalSamples:this.samples.length,totalDuration:t,avgDuration:n,maxDuration:i,minDuration:s,percentiles:{p50:a,p90:r,p99:l}}}exportToChromeTrace(){const e=[];for(const[t,n]of this.marks.entries())e.push({name:t,cat:"mark",ph:"R",ts:1e3*n.timestamp,pid:1,tid:1,args:n.metadata});for(const[t,n]of this.measures.entries())e.push({name:t,cat:"measure",ph:"B",ts:1e3*n.startTime,pid:1,tid:1}),e.push({name:t,cat:"measure",ph:"E",ts:1e3*n.endTime,pid:1,tid:1});for(const t of this.samples)e.push({name:t.functionName,cat:"sample",ph:"X",ts:1e3*t.timestamp,dur:1e3*(t.duration||1),pid:1,tid:1,args:{stackTrace:t.stackTrace}});return{traceEvents:e.sort((e,t)=>e.ts-t.ts),displayTimeUnit:"ms",metadata:{"clock-domain":"PERFORMANCE_NOW"}}}categorizeEvent(e){return"mark"===e.type?e.name.includes("action")?"action":e.name.includes("render")?"render":e.name.includes("state")?"state":"other":"measure"===e.type?e.duration>100?"slow":e.duration>16?"normal":"fast":"unknown"}getEventColor(e){return{action:"#4CAF50",render:"#2196F3",state:"#FF9800",slow:"#F44336",normal:"#FFC107",fast:"#8BC34A",other:"#9E9E9E",unknown:"#607D8B"}[this.categorizeEvent(e)]||"#607D8B"}clear(){this.samples=[],this.timeline=[],this.marks.clear(),this.measures.clear(),this.recordingStartTime=null,performance.clearMarks&&performance.clearMarks(),performance.clearMeasures&&performance.clearMeasures()}getStatus(){return{enabled:this.enabled,isRecording:this.isRecording,samplesCount:this.samples.length,marksCount:this.marks.size,measuresCount:this.measures.size,timelineEventsCount:this.timeline.length,recordingDuration:this.isRecording?performance.now()-this.recordingStartTime:0}}}class tn extends en{constructor(e,t={}){super(t),this.component=e,this.actionCallDepth=0,this.enabled&&this.instrumentComponent()}instrumentComponent(){const e=this.component.call.bind(this.component);if(this.component.call=(t,n,i)=>{this.actionCallDepth++;const s=`action:${t}:${this.actionCallDepth}`;this.mark(`${s}:start`,{actionName:t,params:n,depth:this.actionCallDepth});const o=e(t,n,i);return o instanceof Promise?o.finally(()=>{this.mark(`${s}:end`),this.measure(`action:${t}`,`${s}:start`,`${s}:end`),this.actionCallDepth--}):(this.mark(`${s}:end`),this.measure(`action:${t}`,`${s}:start`,`${s}:end`),this.actionCallDepth--,o)},this.component.state){const e=this.component.state.set.bind(this.component.state);this.component.state.set=(t,n)=>(this.mark(`state:set:${t}`,{key:t,value:n}),e(t,n))}if(this.component.render){const e=this.component.render.bind(this.component);this.component.render=()=>{this.mark("render:start");const t=e();return t instanceof Promise?t.finally(()=>{this.mark("render:end"),this.measure("render","render:start","render:end")}):(this.mark("render:end"),this.measure("render","render:start","render:end"),t)}}}}class nn{constructor(e,t={}){if(this.container="string"==typeof e?document.querySelector(e):e,!this.container)throw new Error("Container element not found");this.options={width:t.width??this.container.clientWidth,height:t.height??400,barHeight:t.barHeight??20,barPadding:t.barPadding??2,colorScheme:t.colorScheme??"category",minWidth:t.minWidth??.5,...t},this.data=null,this.svg=null,this.tooltip=null,this.selectedNode=null,this.init()}init(){this.svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.svg.setAttribute("width",this.options.width),this.svg.setAttribute("height",this.options.height),this.svg.style.fontFamily="monospace",this.svg.style.fontSize="12px",this.tooltip=document.createElement("div"),this.tooltip.style.position="absolute",this.tooltip.style.padding="8px",this.tooltip.style.background="rgba(0, 0, 0, 0.8)",this.tooltip.style.color="white",this.tooltip.style.borderRadius="4px",this.tooltip.style.pointerEvents="none",this.tooltip.style.display="none",this.tooltip.style.zIndex="1000",this.tooltip.style.fontSize="12px",this.container.style.position="relative",this.container.appendChild(this.svg),this.container.appendChild(this.tooltip)}render(e){if(this.data=e,this.clear(),!e)return;const t=this.calculateTotalValue(e);this.renderNode(e,0,0,this.options.width,t)}renderNode(e,t,n,i,s){const{barHeight:o,barPadding:a,minWidth:r}=this.options;if(i<r)return;const l=document.createElementNS("http://www.w3.org/2000/svg","rect");l.setAttribute("x",t),l.setAttribute("y",n),l.setAttribute("width",i),l.setAttribute("height",o-a),l.setAttribute("fill",this.getColor(e)),l.setAttribute("stroke","#fff"),l.setAttribute("stroke-width","0.5"),l.style.cursor="pointer",l.addEventListener("mouseenter",t=>this.showTooltip(t,e)),l.addEventListener("mouseleave",()=>this.hideTooltip()),l.addEventListener("click",()=>this.selectNode(e)),this.svg.appendChild(l);const c=document.createElementNS("http://www.w3.org/2000/svg","text");if(c.setAttribute("x",t+4),c.setAttribute("y",n+o/2+4),c.setAttribute("fill",this.getTextColor(e)),c.setAttribute("pointer-events","none"),c.textContent=this.truncateText(e.name,i),this.svg.appendChild(c),e.children&&e.children.length>0){let a=t;const r=n+o;for(const t of e.children){const n=t.value/e.value*i;this.renderNode(t,a,r,n,s),a+=n}}}calculateTotalValue(e){return e.children&&0!==e.children.length?e.children.reduce((e,t)=>e+this.calculateTotalValue(t),0):e.value}getColor(e){if("monochrome"===this.options.colorScheme)return"#3b82f6";if("duration"===this.options.colorScheme){const t=Math.min(e.value/100,1);return`rgb(${Math.floor(255*t)}, ${Math.floor(255*(1-t))}, 100)`}const t={action:"#4CAF50",render:"#2196F3",state:"#FF9800",network:"#9C27B0",dom:"#F44336",compute:"#00BCD4"};for(const[n,i]of Object.entries(t))if(e.name.toLowerCase().includes(n))return i;return this.hashColor(e.name)}getTextColor(e){return"#fff"}hashColor(e){let t=0;for(let n=0;n<e.length;n++)t=e.charCodeAt(n)+((t<<5)-t);return`hsl(${t%360}, 70%, 50%)`}truncateText(e,t){const n=Math.floor(t/7)-2;return e.length<=n?e:e.substring(0,n)+"…"}showTooltip(e,t){const n=this.data?(t.value/this.calculateTotalValue(this.data)*100).toFixed(2):"0";this.tooltip.innerHTML=`\n <strong>${t.name}</strong><br>\n Time: ${t.value.toFixed(2)}ms<br>\n ${n}% of total<br>\n ${t.children?`${t.children.length} child(ren)`:"Leaf node"}\n `,this.tooltip.style.display="block",this.tooltip.style.left=`${e.pageX+10}px`,this.tooltip.style.top=`${e.pageY+10}px`}hideTooltip(){this.tooltip.style.display="none"}selectNode(e){this.selectedNode=e,console.log("[Flamegraph] Selected node:",e)}clear(){for(;this.svg.firstChild;)this.svg.removeChild(this.svg.firstChild)}exportSVG(){return this.svg.outerHTML}async exportPNG(){const e=(new XMLSerializer).serializeToString(this.svg),t=document.createElement("canvas");t.width=this.options.width,t.height=this.options.height;const n=t.getContext("2d"),i=new Image;return new Promise((s,o)=>{i.onload=()=>{n.drawImage(i,0,0),t.toBlob(s,"image/png")},i.onerror=o,i.src="data:image/svg+xml;base64,"+btoa(e)})}}class sn{constructor(e,t={}){if(this.container="string"==typeof e?document.querySelector(e):e,!this.container)throw new Error("Container element not found");this.options={width:t.width??this.container.clientWidth,height:t.height??200,trackHeight:t.trackHeight??30,padding:t.padding??{top:20,right:20,bottom:30,left:60},...t},this.events=[],this.canvas=null,this.ctx=null,this.tooltip=null,this.scale={x:1,y:1},this.offset={x:0,y:0},this.init()}init(){this.canvas=document.createElement("canvas"),this.canvas.width=this.options.width,this.canvas.height=this.options.height,this.canvas.style.cursor="crosshair",this.ctx=this.canvas.getContext("2d"),this.tooltip=document.createElement("div"),this.tooltip.style.position="absolute",this.tooltip.style.padding="8px",this.tooltip.style.background="rgba(0, 0, 0, 0.8)",this.tooltip.style.color="white",this.tooltip.style.borderRadius="4px",this.tooltip.style.pointerEvents="none",this.tooltip.style.display="none",this.tooltip.style.zIndex="1000",this.tooltip.style.fontSize="12px",this.container.style.position="relative",this.container.appendChild(this.canvas),this.container.appendChild(this.tooltip),this.canvas.addEventListener("mousemove",this.handleMouseMove.bind(this)),this.canvas.addEventListener("mouseleave",this.handleMouseLeave.bind(this))}render(e){if(this.events=e,this.clear(),!e||0===e.length)return;const t=e.map(e=>e.timestamp||e.relativeTime||0),n=Math.min(...t),i=Math.max(...t),s=i-n,{padding:o}=this.options,a=this.options.width-o.left-o.right,r=this.options.height-o.top-o.bottom;this.scale.x=a/s,this.drawAxes(n,i,s);const l=this.organizeIntoTracks(e);this.scale.y=r/l.length,l.forEach((e,t)=>{e.forEach(e=>{this.drawEvent(e,t,n)})})}organizeIntoTracks(e){const t=[],n=[...e].sort((e,t)=>(e.timestamp||e.relativeTime||0)-(t.timestamp||t.relativeTime||0));for(const i of n){const e=i.timestamp||i.relativeTime||0,n="measure"===i.type?e+i.duration:e+.1;let s=!1;for(const o of t){if(!o.some(t=>{const i=t.timestamp||t.relativeTime||0,s="measure"===t.type?i+t.duration:i+.1;return e<s&&n>i})){o.push(i),s=!0;break}}s||t.push([i])}return t}drawAxes(e,t,n){const{padding:i}=this.options,{ctx:s}=this;s.strokeStyle="#ccc",s.lineWidth=1,s.beginPath(),s.moveTo(i.left,i.top),s.lineTo(i.left,this.options.height-i.bottom),s.stroke(),s.beginPath(),s.moveTo(i.left,this.options.height-i.bottom),s.lineTo(this.options.width-i.right,this.options.height-i.bottom),s.stroke(),s.fillStyle="#666",s.font="10px monospace",s.textAlign="center";for(let o=0;o<=5;o++){const t=e+n/5*o,a=i.left+(t-e)*this.scale.x,r=this.options.height-i.bottom+15;s.fillText(`${t.toFixed(1)}ms`,a,r)}}drawEvent(e,t,n){const{padding:i}=this.options,{ctx:s}=this,o=e.timestamp||e.relativeTime||0,a=i.left+(o-n)*this.scale.x,r=i.top+t*this.scale.y,l=this.scale.y-4;if("mark"===e.type)s.strokeStyle=e.color||"#2196F3",s.lineWidth=2,s.beginPath(),s.moveTo(a,r),s.lineTo(a,r+l),s.stroke(),s.fillStyle=e.color||"#2196F3",s.beginPath(),s.arc(a,r+l/2,4,0,2*Math.PI),s.fill();else if("measure"===e.type){const t=Math.max(e.duration*this.scale.x,2);s.fillStyle=e.color||"#4CAF50",s.fillRect(a,r,t,l),s.strokeStyle="#fff",s.lineWidth=.5,s.strokeRect(a,r,t,l),t>30&&(s.fillStyle="#fff",s.font="10px monospace",s.textAlign="left",s.fillText(e.name,a+4,r+l/2+4))}e._bounds={x:a,y:r,width:"measure"===e.type?e.duration*this.scale.x:8,height:l}}handleMouseMove(e){const t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left,i=e.clientY-t.top,s=this.events.find(e=>{if(!e._bounds)return!1;const{x:t,y:s,width:o,height:a}=e._bounds;return n>=t&&n<=t+o&&i>=s&&i<=s+a});s?this.showTooltip(e,s):this.hideTooltip()}handleMouseLeave(){this.hideTooltip()}showTooltip(e,t){const n=t.timestamp||t.relativeTime||0;this.tooltip.innerHTML=`\n <strong>${t.name}</strong><br>\n Type: ${t.type}<br>\n Time: ${n.toFixed(2)}ms<br>\n ${t.duration?`Duration: ${t.duration.toFixed(2)}ms`:""}\n `,this.tooltip.style.display="block",this.tooltip.style.left=`${e.pageX+10}px`,this.tooltip.style.top=`${e.pageY+10}px`}hideTooltip(){this.tooltip.style.display="none"}clear(){this.ctx.clearRect(0,0,this.options.width,this.options.height)}async exportPNG(){return new Promise(e=>{this.canvas.toBlob(e,"image/png")})}}const on={name:"performance-profiler",version:"1.0.0",dependencies:[],provides:["performance-profiling","flamegraph","timeline"],priority:0};let an=null,rn=null,ln=null;async function cn(e={},t){console.log("[PerformanceProfiler] Initializing performance profiler module");const n=e.enabled??!1;if(an=new en({enabled:n,maxSamples:e.maxSamples??1e3,samplingInterval:e.samplingInterval??10,autoStart:e.autoStart??!1}),e.flamegraphContainer){const t=document.querySelector(e.flamegraphContainer);t&&(rn=new nn(t,e.flamegraph??{}),console.log("[PerformanceProfiler] Flamegraph visualizer initialized"))}if(e.timelineContainer){const t=document.querySelector(e.timelineContainer);t&&(ln=new sn(t,e.timeline??{}),console.log("[PerformanceProfiler] Timeline visualizer initialized"))}"undefined"!=typeof window&&(window.PerformanceProfiler={profiler:an,flamegraph:rn,timeline:ln,start:()=>an.start(),stop:()=>{const e=an.stop();if(e){if(console.log("[PerformanceProfiler] Profiling results:",e),rn){const e=an.generateFlamegraph();rn.render(e)}if(ln){const e=an.generateTimeline();ln.render(e)}}return e},mark:(e,t)=>an.mark(e,t),measure:(e,t,n)=>an.measure(e,t,n),exportChromeTrace:()=>an.exportToChromeTrace(),createComponentProfiler:(e,t)=>new tn(e,{...t,enabled:n||(null==t?void 0:t.enabled)})},console.log("[PerformanceProfiler] Global API available at window.PerformanceProfiler")),"undefined"!=typeof window&&window.LiveComponents&&!1!==e.autoInstrument&&function(){const e=window.LiveComponents;if(!e||!e.registry)return void console.warn("[PerformanceProfiler] LiveComponents not available for instrumentation");for(const[n,i]of e.registry.entries()){const e=new tn(i,{enabled:!0});i._profiler=e,console.log(`[PerformanceProfiler] Instrumented component: ${n}`)}const t=e.register.bind(e);e.register=(e,n)=>{const i=t(e,n),s=new tn(n,{enabled:!0});return n._profiler=s,console.log(`[PerformanceProfiler] Instrumented component: ${e}`),i},console.log("[PerformanceProfiler] LiveComponents instrumentation enabled")}(),console.log("[PerformanceProfiler] Module initialized")}function dn(){an&&an.clear(),rn&&rn.clear(),ln&&ln.clear(),"undefined"!=typeof window&&delete window.PerformanceProfiler,console.log("[PerformanceProfiler] Module destroyed")}const hn={init:cn,destroy:dn,definition:on},un=Object.freeze(Object.defineProperty({__proto__:null,FlamegraphVisualizer:nn,LiveComponentsProfiler:tn,PerformanceProfiler:en,TimelineVisualizer:sn,default:hn,definition:on,destroy:dn,init:cn},Symbol.toStringTag,{value:"Module"}));class pn{constructor(e,t){this.name=e,this.guardFn=t}static create(e,t){return new pn(e,t)}async execute(e,t,n={}){try{const i=await this.guardFn(e,t,n);return{allowed:!1!==i&&null!==i,redirect:"string"==typeof i?i:null,reason:"object"==typeof i&&i.reason?i.reason:null}}catch(i){return d.error(`[RouteGuard] Guard "${this.name}" error:`,i),{allowed:!1,redirect:null,reason:i.message}}}}const mn={auth:pn.create("auth",async(e,t)=>"/login"),guest:pn.create("guest",async(e,t)=>!0),role:e=>pn.create("role",async(t,n)=>null===e||"/unauthorized"),permission:e=>pn.create("permission",async(e,t)=>"/unauthorized")};class gn{constructor(e,t){this.name=e,this.middlewareFn=t}static create(e,t){return new gn(e,t)}async execute(e,t,n,i={}){try{await this.middlewareFn(e,t,n,i)}catch(s){d.error(`[RouteMiddleware] Middleware "${this.name}" error:`,s),n(!1)}}}const fn={analytics:gn.create("analytics",async(e,t,n)=>{"undefined"!=typeof window&&window.analytics&&window.analytics.track("page_view",{path:e.path,title:e.title}),n()}),loading:gn.create("loading",async(e,t,n)=>{document.body.classList.add("route-loading"),n(),setTimeout(()=>{document.body.classList.remove("route-loading")},100)}),scrollToTop:gn.create("scroll-to-top",async(e,t,n)=>{n(),window.scrollTo({top:0,behavior:"smooth"})})};class yn{constructor(e={}){this.config={mode:e.mode||"history",base:e.base||"/",enableAnalytics:e.enableAnalytics??!0,...e},this.routes=new Map,this.guards=new Map,this.middleware=[],this.beforeEachHooks=[],this.afterEachHooks=[],this.currentRoute=null,this.analytics={navigations:[],errors:[]},this.init()}static create(e={}){return new yn(e)}init(){window.addEventListener("popstate",e=>{this.handlePopState(e)}),d.info("[Router] Initialized",{mode:this.config.mode,base:this.config.base})}route(e,t){const n={path:this.normalizePath(e),component:t.component,name:t.name||e,title:t.title||null,meta:t.meta||{},guards:t.guards||[],middleware:t.middleware||[],lazy:t.lazy??!1,...t};return this.routes.set(n.path,n),d.debug("[Router] Route registered",n),this}routes(e){return e.forEach(e=>{this.route(e.path,e)}),this}guard(e,t){const n=pn.create(e,t);return this.guards.set(e,n),this}use(e){return"function"==typeof e?this.middleware.push(gn.create("anonymous",e)):e instanceof gn?this.middleware.push(e):"string"==typeof e&&fn[e]&&this.middleware.push(fn[e]),this}beforeEach(e){return this.beforeEachHooks.push(e),this}afterEach(e){return this.afterEachHooks.push(e),this}async navigate(e,t={}){const n=this.normalizePath(e),i=this.routes.get(n);if(!i)return d.warn("[Router] Route not found",n),!1;const s=this.currentRoute,o={path:n,name:i.name,title:i.title,meta:i.meta,component:i.component};for(const l of this.beforeEachHooks){const e=await l(o,s);if(!1===e||"string"==typeof e)return"string"==typeof e&&await this.navigate(e)}for(const l of i.guards){const e=this.guards.get(l)||mn[l];if(!e){d.warn("[Router] Guard not found",l);continue}const t=await e.execute(o,s);if(!t.allowed)return t.redirect?await this.navigate(t.redirect):(d.warn("[Router] Navigation blocked by guard",l),!1)}let a=!1;for(const l of[...this.middleware,...i.middleware])if(await new Promise(e=>{l.execute(o,s,t=>{!1===t&&(a=!0),e()})}),a)return!1;if(i.lazy&&"function"==typeof i.component)try{i.component=await i.component()}catch(r){return d.error("[Router] Failed to load lazy component",r),!1}this.currentRoute=o,"history"===this.config.mode?history.pushState({route:o},i.title||"",n):window.location.hash=n,i.title&&(document.title=i.title),this.config.enableAnalytics&&this.trackNavigation(o,s);for(const l of this.afterEachHooks)await l(o,s);return await this.renderComponent(i,t),d.info("[Router] Navigated",{to:n}),!0}async renderComponent(e,t={}){const n=t.container||document.querySelector("main");if(n){if("function"==typeof e.component){const i=await e.component(e,t);"string"==typeof i?n.innerHTML=i:i instanceof HTMLElement&&(n.innerHTML="",n.appendChild(i))}else if("string"==typeof e.component){const t=document.querySelector(e.component);t?(n.innerHTML="",n.appendChild(t.cloneNode(!0))):n.innerHTML=e.component}this.reinitializeModules(n)}else d.error("[Router] Container not found")}reinitializeModules(e){const t=new CustomEvent("router:content-updated",{detail:{container:e},bubbles:!0});document.dispatchEvent(t)}handlePopState(e){const t="history"===this.config.mode?window.location.pathname:window.location.hash.slice(1);this.navigate(t,{updateHistory:!1})}normalizePath(e){return e.startsWith(this.config.base)&&(e=e.slice(this.config.base.length)),e.startsWith("/")||(e="/"+e),"/"!==e&&e.endsWith("/")&&(e=e.slice(0,-1)),e}trackNavigation(e,t){const n={to:e.path,from:(null==t?void 0:t.path)||null,timestamp:Date.now(),duration:t?Date.now()-(t.timestamp||Date.now()):0};this.analytics.navigations.push(n),this.analytics.navigations.length>100&&this.analytics.navigations.shift();const i=new CustomEvent("router:navigation",{detail:n,bubbles:!0});window.dispatchEvent(i)}getCurrentRoute(){return this.currentRoute}getAnalytics(){return{...this.analytics,totalNavigations:this.analytics.navigations.length,totalErrors:this.analytics.errors.length}}destroy(){this.routes.clear(),this.guards.clear(),this.middleware=[],this.beforeEachHooks=[],this.afterEachHooks=[],this.currentRoute=null,d.info("[Router] Destroyed")}}const vn={name:"router",router:null,init(e={},t=null){return d.info("[RouterModule] Module initialized"),this.router=yn.create(e),"undefined"!=typeof window&&(window.Router=this.router),this},getRouter(){return this.router||yn.create()},routes(e){return this.getRouter().routes(e),this},async navigate(e,t={}){const n=this.getRouter();return await n.navigate(e,t)},destroy(){this.router&&(this.router.destroy(),this.router=null),"undefined"!=typeof window&&window.Router&&delete window.Router,d.info("[RouterModule] Module destroyed")}},bn=vn.init.bind(vn),wn=Object.freeze(Object.defineProperty({__proto__:null,BuiltInGuards:mn,BuiltInMiddleware:fn,RouteGuard:pn,RouteMiddleware:gn,Router:yn,default:vn,init:bn},Symbol.toStringTag,{value:"Module"}));class Sn{constructor(){this.modules=new Map,this.dependents=new Map,this.initialized=new Set,this.initializing=new Set,this.initializationOrder=[]}register(e){this.modules.has(e.name)?d.warn(`[DependencyManager] Module '${e.name}' already registered`):this.validateDefinition(e)&&(this.modules.set(e.name,e),e.dependencies.forEach(t=>{this.dependents.has(t.name)||this.dependents.set(t.name,[]),this.dependents.get(t.name).push(e.name)}),d.info(`[DependencyManager] Registered '${e.name}' v${e.version}`))}calculateInitializationOrder(){const e=new Set,t=new Set,n=[],i=s=>{if(t.has(s))throw new Error(`Circular dependency detected involving '${s}'`);if(e.has(s))return;const o=this.modules.get(s);o&&(t.add(s),o.dependencies.forEach(e=>{e.optional&&!this.modules.has(e.name)||i(e.name)}),t.delete(s),e.add(s),n.push(s))};return Array.from(this.modules.entries()).sort(([,e],[,t])=>(t.priority||0)-(e.priority||0)).map(([e])=>e).forEach(t=>{e.has(t)||i(t)}),this.initializationOrder=n,d.info(`[DependencyManager] Initialization order: ${n.join(" → ")}`),n}checkDependencies(e){const t=this.modules.get(e);if(!t)return{satisfied:!1,missing:[],reason:`Module '${e}' not registered`};const n=[],i=[];return t.dependencies.forEach(e=>{this.modules.get(e.name)?this.initialized.has(e.name)||e.optional||n.push(`${e.name} (not initialized)`):e.optional?i.push(e.name):n.push(e.name)}),{satisfied:0===n.length,missing:n,optional:i,reason:n.length>0?`Missing: ${n.join(", ")}`:"OK"}}markInitialized(e){this.initialized.add(e),this.initializing.delete(e),d.info(`[DependencyManager] '${e}' initialized`)}markInitializing(e){this.initializing.add(e)}getDependents(e){return this.dependents.get(e)||[]}getModule(e){return this.modules.get(e)}isReadyToInitialize(e){if(this.initialized.has(e)||this.initializing.has(e))return!1;return this.checkDependencies(e).satisfied}getStatus(){const e=this.modules.size,t=this.initialized.size,n=this.initializing.size;return{total:e,initialized:t,initializing:n,pending:e-t-n,modules:{initialized:Array.from(this.initialized),initializing:Array.from(this.initializing),pending:Array.from(this.modules.keys()).filter(e=>!this.initialized.has(e)&&!this.initializing.has(e))}}}validateDefinition(e){if(!e.name||"string"!=typeof e.name)return d.error("[DependencyManager] Module name is required and must be string"),!1;if(!e.version||"string"!=typeof e.version)return d.error(`[DependencyManager] Version is required for module '${e.name}'`),!1;if(!Array.isArray(e.dependencies))return d.error(`[DependencyManager] Dependencies must be array for module '${e.name}'`),!1;for(const t of e.dependencies)if(!t.name||"string"!=typeof t.name)return d.error(`[DependencyManager] Invalid dependency in module '${e.name}': missing name`),!1;return!0}reset(){this.modules.clear(),this.dependents.clear(),this.initialized.clear(),this.initializing.clear(),this.initializationOrder=[],d.info("[DependencyManager] Reset complete")}static createDefinition(e,t){const n={name:e,version:t,dependencies:[],provides:[],priority:0},i={depends(e,t="*",i=!1){return n.dependencies.push({name:e,version:t,optional:i}),this},provides(...e){return n.provides.push(...e),this},priority(e){return n.priority=e,this},build:()=>n};return Object.setPrototypeOf(i,n),Object.keys(n).forEach(e=>{e in i||Object.defineProperty(i,e,{get:()=>n[e],set(t){n[e]=t},enumerable:!0,configurable:!0})}),i}}const En=new Sn;"undefined"!=typeof window&&(window.dependencyManager=En,window.depStatus=()=>En.getStatus());const Cn=Sn.createDefinition("scroll-dependent","1.0.0").depends("example-module","1.0.0").depends("scrollfx","1.0.0",!0).provides("scroll-coordination").priority(10);let kn=null,Mn=null;const xn=Object.freeze(Object.defineProperty({__proto__:null,definition:Cn,destroy:function(){d.info("[scroll-dependent] destroy"),kn&&Mn&&(Mn.unsubscribe(kn),kn=null),Mn&&"function"==typeof Mn.cleanup&&Mn.cleanup(),Mn=null},init:function(e={},t=null){d.info("[scroll-dependent] init"),Mn=t,Mn&&(Mn.register("isScrolling",!1),Mn.register("scrollDirection","none"),kn=Mn.subscribe("example-module.scrollPosition",(e,t)=>{if(t.y!==e.y){const n=e.y>t.y?"down":"up";Mn.set("scrollDirection",n),Mn.set("isScrolling",!0),setTimeout(()=>{Mn&&Mn.set("isScrolling",!1)},150),d.info(`[scroll-dependent] Scroll ${n}: ${e.y}`)}}))}},Symbol.toStringTag,{value:"Module"}));const Tn=Object.freeze(Object.defineProperty({__proto__:null,init:function(e={}){const t=document.querySelectorAll("[data-scroll-loop]");t.forEach(e=>{if("translate"===(e.dataset.scrollType||"translate")&&1===e.children.length){const t=e.firstElementChild.cloneNode(!0);t.setAttribute("aria-hidden","true"),e.appendChild(t)}}),l("scroll-loop",()=>{const n=window.scrollY,i=window.scrollX;t.forEach(t=>{const s=parseFloat(t.dataset.scrollSpeed||e.speed||.2),o=t.dataset.scrollAxis||"y",a=t.dataset.scrollType||"translate",r="true"===t.dataset.loopPause,l=parseFloat(t.dataset.loopOffset||0),c=parseFloat(t.dataset.loopLimit||0),d="x"===o?i:n;if(c&&d>c)return;if(r&&(t.matches(":hover")||t.matches(":active")))return;const h=(d+l)*s;switch(a){case"translate":{const e=-h%("x"===o?t.offsetWidth:t.offsetHeight),n="x"===o?`translateX(${e}px)`:`translateY(${e}px)`;t.style.transform=n;break}case"rotate":{const e=h%360;t.style.transform=`rotate(${e}deg)`;break}case"background":{const e=h%100;t.style.backgroundPosition="x"===o?`${e}% center`:`center ${e}%`;break}case"scale":{const e=1+.1*Math.sin(.01*h);t.style.transform=`scale(${e.toFixed(3)})`;break}}})},{autoStart:!0})}},Symbol.toStringTag,{value:"Module"})),An={onEnter(e,t){t.classList.add("active"),document.body.dataset.activeScrollStep=e,d.info(`[ScrollStep] Enter: ${e}`),1===e&&d.info("Intro sichtbar"),2===e&&d.info("Chart aktiviert"),3===e&&d.info("Zitat eingeblendet")},onLeave(e,t){t.classList.remove("active"),t.style.transitionDelay="",d.info(`[ScrollStep] Leave: ${e}`),document.body.dataset.activeScrollStep===String(e)&&delete document.body.dataset.activeScrollStep,1===e&&d.info("Intro ausgeblendet"),2===e&&d.info("Chart deaktiviert"),3===e&&d.info("Zitat ausgeblendet")}};const Ln=Object.freeze(Object.defineProperty({__proto__:null,destroy:function(){c("scroll-timeline")},init:function(e={}){d.info("ScrollTimeline init");const t={attribute:"data-scroll-step",triggerPoint:.4,once:!0,...e},n=Array.from(document.querySelectorAll(`[${t.attribute}]`)).map(e=>({el:e,index:parseInt(e.getAttribute(t.attribute),10),active:!1}));l("scroll-timeline",function(){const e=window.innerHeight*t.triggerPoint;n.forEach(n=>{var i,s;const o=n.el.getBoundingClientRect(),a=o.top<e&&o.bottom>0;a&&!n.active&&(n.active=!0,n.el.classList.add("active"),d.log(`➡️ ENTER step ${n.index}`),null==(i=An.onEnter)||i.call(An,n.index,n.el)),!a&&n.active&&(n.active=!1,n.el.classList.remove("active"),d.log(`⬅️ LEAVE step ${n.index}`),t.once||null==(s=An.onLeave)||s.call(An,n.index,n.el))})},{autoStart:!0})}},Symbol.toStringTag,{value:"Module"}));class In{constructor(e={}){this.config={tokenName:e.tokenName||"_token",headerName:e.headerName||"X-CSRF-TOKEN",refreshInterval:e.refreshInterval||18e5,autoRefresh:e.autoRefresh??!0,endpoint:e.endpoint||"/api/csrf-token",...e},this.currentToken=null,this.refreshTimer=null,this.isRefreshing=!1,this.init()}static create(e={}){return new In(e)}init(){this.currentToken=this.getTokenFromPage(),this.currentToken?d.info("[CsrfManager] Initialized with token"):d.warn("[CsrfManager] No CSRF token found on page"),this.config.autoRefresh&&this.startAutoRefresh(),this.updateAllTokens()}getTokenFromPage(){const e=document.querySelector('meta[name="csrf-token"]');if(e)return e.getAttribute("content");const t=document.querySelector(`input[name="${this.config.tokenName}"]`);return t?t.value:null}getToken(){return this.currentToken}async refreshToken(){if(this.isRefreshing)d.debug("[CsrfManager] Token refresh already in progress");else{this.isRefreshing=!0;try{const e=await fetch(this.config.endpoint,{method:"GET",headers:{"X-Requested-With":"XMLHttpRequest",Accept:"application/json"}});if(!e.ok)throw new Error(`Failed to refresh token: ${e.status}`);const t=await e.json(),n=t.token||t.csrf_token||t._token;if(!n)throw new Error("No token in response");this.currentToken=n,this.updateAllTokens(),d.info("[CsrfManager] Token refreshed"),this.triggerTokenRefreshedEvent(n)}catch(e){throw d.error("[CsrfManager] Failed to refresh token",e),e}finally{this.isRefreshing=!1}}}updateAllTokens(){if(!this.currentToken)return;const e=document.querySelector('meta[name="csrf-token"]');e&&e.setAttribute("content",this.currentToken);document.querySelectorAll(`input[name="${this.config.tokenName}"]`).forEach(e=>{e.value=this.currentToken});document.querySelectorAll("[data-live-component]").forEach(e=>{const t=e.querySelector(`input[name="${this.config.tokenName}"]`);t&&(t.value=this.currentToken)})}startAutoRefresh(){this.refreshTimer||(this.refreshTimer=setInterval(()=>{this.refreshToken().catch(e=>{d.error("[CsrfManager] Auto-refresh failed",e)})},this.config.refreshInterval),d.debug("[CsrfManager] Auto-refresh started",{interval:this.config.refreshInterval}))}stopAutoRefresh(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null)}getTokenHeader(){return{[this.config.headerName]:this.currentToken}}triggerTokenRefreshedEvent(e){const t=new CustomEvent("csrf:token-refreshed",{detail:{token:e},bubbles:!0});window.dispatchEvent(t)}destroy(){this.stopAutoRefresh(),this.currentToken=null,d.info("[CsrfManager] Destroyed")}}class Pn{constructor(e={}){var t,n,i,s;this.config={csrf:e.csrf||{},xss:{enabled:(null==(t=e.xss)?void 0:t.enabled)??!0,sanitizeOnInput:(null==(n=e.xss)?void 0:n.sanitizeOnInput)??!1},csp:{enabled:(null==(i=e.csp)?void 0:i.enabled)??!1,reportOnly:(null==(s=e.csp)?void 0:s.reportOnly)??!1},...e},this.csrfManager=null,this.init()}static create(e={}){return new Pn(e)}init(){this.csrfManager=In.create(this.config.csrf),this.config.xss.enabled&&this.initXssProtection(),this.config.csp.enabled&&this.initCsp(),d.info("[SecurityManager] Initialized",{csrf:!!this.csrfManager,xss:this.config.xss.enabled,csp:this.config.csp.enabled})}initXssProtection(){this.config.xss.sanitizeOnInput&&document.addEventListener("input",e=>{"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName||this.sanitizeInput(e.target)},!0)}sanitizeInput(e){const t=e.value,n=this.sanitizeHtml(t);n!==t&&(e.value=n,d.warn("[SecurityManager] Sanitized potentially dangerous input",{field:e.name||e.id}))}sanitizeHtml(e){return"string"!=typeof e?e:e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/on\w+\s*=\s*["'][^"']*["']/gi,"").replace(/javascript:/gi,"").replace(/data:text\/html/gi,"")}initCsp(){const e=this.getCspHeader();e?(d.debug("[SecurityManager] CSP header found",e),this.validateCsp(e)):d.warn("[SecurityManager] No CSP header found")}getCspHeader(){const e=document.querySelector('meta[http-equiv="Content-Security-Policy"]');return e?e.getAttribute("content"):null}validateCsp(e){const t=e.split(";").map(e=>e.trim().split(" ")[0]),n=["default-src","script-src","style-src"].filter(e=>!t.some(t=>t.toLowerCase()===e.toLowerCase()));n.length>0&&d.warn("[SecurityManager] CSP missing recommended directives",n)}getCsrfToken(){var e;return(null==(e=this.csrfManager)?void 0:e.getToken())||null}getCsrfTokenHeader(){var e;return(null==(e=this.csrfManager)?void 0:e.getTokenHeader())||{}}async refreshCsrfToken(){if(this.csrfManager)return await this.csrfManager.refreshToken()}validateSecurityHeaders(){const e=[];return"https:"!==location.protocol&&"localhost"!==location.hostname&&e.push("Not using HTTPS"),this.getCspHeader()||e.push("No Content Security Policy header"),{valid:0===e.length,issues:e}}escapeHtml(e){if("string"!=typeof e)return e;const t={"&":"&","<":"<",">":">",'"':""","'":"'"};return e.replace(/[&<>"']/g,e=>t[e])}validateUrl(e){try{const t=new URL(e,window.location.origin);return"javascript:"!==t.protocol&&"data:"!==t.protocol}catch{return!1}}destroy(){this.csrfManager&&(this.csrfManager.destroy(),this.csrfManager=null),d.info("[SecurityManager] Destroyed")}}const $n={name:"security",securityManager:null,init(e={},t=null){return d.info("[SecurityModule] Module initialized"),this.securityManager=Pn.create(e),"undefined"!=typeof window&&(window.SecurityManager=this.securityManager,window.CsrfManager=this.securityManager.csrfManager),this},getSecurityManager(){return this.securityManager||Pn.create()},getCsrfToken(){var e;return(null==(e=this.securityManager)?void 0:e.getCsrfToken())||null},async refreshCsrfToken(){if(this.securityManager)return await this.securityManager.refreshCsrfToken()},destroy(){this.securityManager&&(this.securityManager.destroy(),this.securityManager=null),"undefined"!=typeof window&&(delete window.SecurityManager,delete window.CsrfManager),d.info("[SecurityModule] Module destroyed")}},Dn=$n.init.bind($n),On=Object.freeze(Object.defineProperty({__proto__:null,CsrfManager:In,SecurityManager:Pn,default:$n,init:Dn},Symbol.toStringTag,{value:"Module"})),zn=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));class _n{constructor(e={}){this.options={containerSelector:"main",linkSelector:'a[href^="/"]',loadingClass:"spa-loading",excludeSelector:'[data-spa="false"], [download], [target="_blank"], [href^="mailto:"], [href^="tel:"], [href^="#"]',enableTransitions:!0,transitionDuration:100,skeletonTemplate:this.createSkeletonTemplate(),enableLiveComponentIntegration:e.enableLiveComponentIntegration??!0,preserveLiveComponentState:e.preserveLiveComponentState??!1,...e},this.container=null,this.isLoading=!1,this.currentUrl=window.location.href,this.abortController=null,this.liveComponentManager=null,this.handleLinkClick=this.handleLinkClick.bind(this),this.handlePopState=this.handlePopState.bind(this),this.handleFormSubmit=this.handleFormSubmit.bind(this),this.init()}static create(e={}){return new _n(e)}init(){this.container=document.querySelector(this.options.containerSelector),this.container?(this.options.enableLiveComponentIntegration&&this.initLiveComponentIntegration(),this.bindEvents(),this.setupStyles(),this.updateHistoryState(window.location.href,document.title),d.info("[SPARouter] Initialized",{liveComponentIntegration:this.options.enableLiveComponentIntegration})):d.error(`[SPARouter] Container "${this.options.containerSelector}" not found`)}initLiveComponentIntegration(){"undefined"!=typeof window&&window.LiveComponent?this.liveComponentManager=window.LiveComponent:kt(()=>Promise.resolve().then(()=>Kt),void 0).then(e=>{e.LiveComponent?this.liveComponentManager=e.LiveComponent:e.default&&(this.liveComponentManager=e.default)}).catch(e=>{d.warn("[SPARouter] LiveComponent not available",e)}),d.debug("[SPARouter] LiveComponent integration initialized")}bindEvents(){document.addEventListener("click",this.handleLinkClick),window.addEventListener("popstate",this.handlePopState),document.addEventListener("submit",this.handleFormSubmit)}handleLinkClick(e){const t=e.target.closest(this.options.linkSelector);if(!t)return;if(t.matches(this.options.excludeSelector))return;if(e.ctrlKey||e.metaKey||e.shiftKey)return;e.preventDefault();const n=t.href,i=t.title||t.textContent.trim();this.navigate(n,i)}handlePopState(e){const t=window.location.href;t!==this.currentUrl&&this.loadContent(t,!1)}handleFormSubmit(e){const t=e.target;t.hasAttribute("data-spa")&&"false"===t.getAttribute("data-spa")||t._moduleInstance}async navigate(e,t=""){var n;if(this.isLoading&&(d.warn("[SPARouter] Already loading, aborting previous request"),null==(n=this.abortController)||n.abort()),e!==this.currentUrl){d.info(`[SPARouter] Navigating to: ${e}`);try{await this.loadContent(e,!0,t)}catch(i){"AbortError"!==i.name&&(d.error("[SPARouter] Navigation failed:",i),window.location.href=e)}}else d.info(`[SPARouter] Already at ${e}, skipping navigation`)}async loadContent(e,t=!0,n=""){var i;if(e!==this.currentUrl||t){this.isLoading&&(null==(i=this.abortController)||i.abort()),this.isLoading=!0,this.abortController=new AbortController;try{this.showLoadingState();const i=await fetch(e,{headers:{"X-Requested-With":"XMLHttpRequest","X-SPA-Request":"true",Accept:"application/json, text/html"},signal:this.abortController.signal});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);const s=i.headers.get("content-type");let o,a;if(null==s?void 0:s.includes("application/json")){const e=await i.json();o=e.html,a=e.title||n,e.meta&&this.updateMetaTags(e.meta)}else{const e=await i.text();o=this.extractMainContent(e),a=this.extractTitle(e)||n}await this.updateContent(o,a),t&&this.updateHistoryState(e,a),this.currentUrl=e,d.info(`[SPARouter] Successfully loaded: ${e}`)}catch(s){if("AbortError"!==s.name)throw this.hideLoadingState(),s}finally{this.isLoading=!1,this.abortController=null}}}extractMainContent(e){const t=(new DOMParser).parseFromString(e,"text/html"),n=t.querySelector("main");if(n)return n.innerHTML;const i=['[role="main"]',".main-content","#main",".content"];for(const s of i){const e=t.querySelector(s);if(e)return d.warn(`[SPARouter] Using fallback selector: ${s}`),e.innerHTML}return d.warn("[SPARouter] No main element found, using entire body"),t.body.innerHTML}extractTitle(e){const t=(new DOMParser).parseFromString(e,"text/html").querySelector("title");return t?t.textContent.trim():""}async updateContent(e,t){let n=null;this.options.enableLiveComponentIntegration&&this.options.preserveLiveComponentState&&this.liveComponentManager&&(n=this.saveLiveComponentStates()),t&&(document.title=t),this.options.enableTransitions&&await this.transitionOut(),this.container.innerHTML=e,this.reinitializeModules(),this.options.enableLiveComponentIntegration&&await this.initializeLiveComponents(n),this.options.enableTransitions&&await this.transitionIn(),this.hideLoadingState(),window.scrollTo({top:0,behavior:"smooth"}),this.triggerNavigationEvent()}saveLiveComponentStates(){if(!this.liveComponentManager)return null;const e={};return this.container.querySelectorAll("[data-live-component]").forEach(t=>{const n=t.getAttribute("data-live-component");if(n&&this.liveComponentManager.components){if(this.liveComponentManager.components.get(n)){const s=t.dataset.state;if(s)try{e[n]=JSON.parse(s)}catch(i){d.warn(`[SPARouter] Failed to parse state for ${n}`,i)}}}}),d.debug("[SPARouter] Saved LiveComponent states",Object.keys(e)),e}async initializeLiveComponents(e=null){if(!this.liveComponentManager&&(this.initLiveComponentIntegration(),await new Promise(e=>setTimeout(e,100)),!this.liveComponentManager))return void d.warn("[SPARouter] LiveComponentManager not available, skipping initialization");const t=this.container.querySelectorAll("[data-live-component]");if(0!==t.length){d.info(`[SPARouter] Initializing ${t.length} LiveComponents`);for(const i of t)try{if(e){const t=i.getAttribute("data-live-component");if(t&&e[t]){const n=JSON.stringify(e[t]);i.dataset.state=n}}this.liveComponentManager&&"function"==typeof this.liveComponentManager.init&&this.liveComponentManager.init(i)}catch(n){d.error("[SPARouter] Failed to initialize LiveComponent",n)}d.debug("[SPARouter] LiveComponents initialized")}}showLoadingState(){document.body.classList.add(this.options.loadingClass),this.options.enableTransitions&&this.container.classList.add("spa-transitioning-out")}hideLoadingState(){document.body.classList.remove(this.options.loadingClass)}async transitionOut(){return new Promise(e=>{this.container.style.transition=`opacity ${this.options.transitionDuration}ms cubic-bezier(0.4, 0, 1, 1)`,this.container.style.opacity="0",setTimeout(()=>{e()},this.options.transitionDuration)})}async transitionIn(){return new Promise(e=>{this.container.style.opacity="0",setTimeout(()=>{this.container.style.transition=`opacity ${this.options.transitionDuration}ms cubic-bezier(0, 0, 0.2, 1)`,this.container.style.opacity="1",setTimeout(()=>{this.container.style.transition="",this.container.classList.remove("spa-transitioning-out"),e()},this.options.transitionDuration)},10)})}updateHistoryState(e,t){const n={url:e,title:t,timestamp:Date.now()};e!==window.location.href?history.pushState(n,t,e):history.replaceState(n,t,e)}reinitializeModules(){window.initAutoFormHandling&&window.initAutoFormHandling();this.container.querySelectorAll("[data-module]").forEach(e=>{const t=e.dataset.module;if("livecomponent"===t)return;d.info(`[SPARouter] Re-initializing module "${t}" on new content`);const n=new CustomEvent("spa:reinit-module",{detail:{element:e,moduleName:t},bubbles:!0});e.dispatchEvent(n)})}createSkeletonTemplate(){return'\n <div class="spa-skeleton">\n <div class="spa-skeleton-header"></div>\n <div class="spa-skeleton-content">\n <div class="spa-skeleton-line"></div>\n <div class="spa-skeleton-line"></div>\n <div class="spa-skeleton-line short"></div>\n </div>\n </div>\n '}setupStyles(){if(document.getElementById("spa-router-styles"))return;const e=document.createElement("style");e.id="spa-router-styles",e.textContent="\n /* SPA Router Transitions */\n .spa-loading {\n cursor: progress;\n }\n \n .spa-transitioning-out {\n pointer-events: none;\n }\n \n /* Skeleton Loading Styles */\n .spa-skeleton {\n animation: spa-pulse 1.5s ease-in-out infinite alternate;\n }\n \n .spa-skeleton-header {\n height: 2rem;\n background: #e5e7eb;\n border-radius: 0.375rem;\n margin-bottom: 1rem;\n width: 60%;\n }\n \n .spa-skeleton-content {\n space-y: 0.75rem;\n }\n \n .spa-skeleton-line {\n height: 1rem;\n background: #e5e7eb;\n border-radius: 0.375rem;\n margin-bottom: 0.75rem;\n }\n \n .spa-skeleton-line.short {\n width: 75%;\n }\n \n @keyframes spa-pulse {\n 0% {\n opacity: 1;\n }\n 100% {\n opacity: 0.4;\n }\n }\n \n /* Dark mode support */\n @media (prefers-color-scheme: dark) {\n .spa-skeleton-header,\n .spa-skeleton-line {\n background: #374151;\n }\n }\n ",document.head.appendChild(e)}updateMetaTags(e){if(e.description){let t=document.querySelector('meta[name="description"]');t?t.content=e.description:(t=document.createElement("meta"),t.name="description",t.content=e.description,document.head.appendChild(t))}Object.entries(e).forEach(([e,t])=>{if("description"!==e&&t){let n=document.querySelector(`meta[name="${e}"]`);n?n.content=t:(n=document.createElement("meta"),n.name=e,n.content=t,document.head.appendChild(n))}})}triggerNavigationEvent(){const e=new CustomEvent("spa:navigated",{detail:{url:this.currentUrl,container:this.container,timestamp:Date.now()},bubbles:!0});document.dispatchEvent(e)}navigateTo(e,t){return this.navigate(e,t)}getCurrentUrl(){return this.currentUrl}isNavigating(){return this.isLoading}destroy(){var e;null==(e=this.abortController)||e.abort(),document.removeEventListener("click",this.handleLinkClick),window.removeEventListener("popstate",this.handlePopState),document.removeEventListener("submit",this.handleFormSubmit);const t=document.getElementById("spa-router-styles");t&&t.remove(),d.info("[SPARouter] Destroyed")}}const Rn={enableTransitions:!0,transitionDuration:50},Fn={enableTransitions:!0,transitionDuration:100},qn={enableTransitions:!1,transitionDuration:0};function Nn(){if(window.matchMedia("(prefers-reduced-motion: reduce)").matches)return qn;const e=navigator.connection||navigator.mozConnection||navigator.webkitConnection;if(e){if("4g"===e.effectiveType)return Rn;if("3g"===e.effectiveType)return Fn}/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);return Fn}const Bn={name:"spa-router",router:null,initialized:!1,init(e={}){if(this.initialized&&this.router)return d.warn("[SPARouterModule] SPA Router already initialized, returning existing instance"),this.router;d.info("[SPARouterModule] Initializing SPA Router");const t={...{containerSelector:"main",linkSelector:'a[href^="/"]',excludeSelector:'[data-spa="false"], [download], [target="_blank"], [href^="mailto:"], [href^="tel:"], [href^="#"]',enableSkeletonLoading:!0,...Fn,...Nn()},...e};return this.router=_n.create(t),this.initialized=!0,"undefined"!=typeof window&&(window.spaRouter=this.router),document.addEventListener("spa:reinit-module",this.handleModuleReinit.bind(this)),document.addEventListener("spa:navigated",this.handleNavigation.bind(this)),d.info("[SPARouterModule] SPA Router initialized successfully"),this.router},handleModuleReinit(e){const{element:t,moduleName:n}=e.detail;d.info(`[SPARouterModule] Re-initializing module: ${n}`,t);const i=new CustomEvent("module:reinit-needed",{detail:{element:t,moduleName:n},bubbles:!0});document.dispatchEvent(i)},handleNavigation(e){const{url:t,timestamp:n}=e.detail;d.info(`[SPARouterModule] Navigation completed to: ${t}`),"function"==typeof window.initAutoFormHandling&&setTimeout(()=>{window.initAutoFormHandling()},100),"function"==typeof window.gtag&&window.gtag("config","GA_TRACKING_ID",{page_path:new URL(t).pathname})},navigateTo(e,t){if(this.router)return this.router.navigateTo(e,t);d.warn("[SPARouterModule] Router not initialized")},getCurrentUrl(){var e;return(null==(e=this.router)?void 0:e.getCurrentUrl())||window.location.href},isNavigating(){var e;return(null==(e=this.router)?void 0:e.isNavigating())||!1},destroy(){this.router&&(this.router.destroy(),this.router=null),this.initialized=!1,"undefined"!=typeof window&&window.spaRouter&&delete window.spaRouter,document.removeEventListener("spa:reinit-module",this.handleModuleReinit),document.removeEventListener("spa:navigated",this.handleNavigation),d.info("[SPARouterModule] SPA Router destroyed")}},Hn=Bn.init.bind(Bn),Un=Object.freeze(Object.defineProperty({__proto__:null,SPARouter:_n,SPARouterModule:Bn,default:Bn,init:Hn},Symbol.toStringTag,{value:"Module"}));let jn=class e{constructor(e={}){var t,n,i,s,o;this.state=e.initialState||{},this.subscribers=new Map,this.middleware=[],this.history=[],this.maxHistorySize=e.maxHistorySize||50,this.enableHistory=e.enableHistory??!1,this.persistence={enabled:(null==(t=e.persistence)?void 0:t.enabled)??!1,storage:(null==(n=e.persistence)?void 0:n.storage)||"localStorage",key:(null==(i=e.persistence)?void 0:i.key)||"app-state",paths:(null==(s=e.persistence)?void 0:s.paths)||[]},this.sync={enabled:(null==(o=e.sync)?void 0:o.enabled)??!1,channel:null},this.persistence.enabled&&this.loadPersistedState(),this.sync.enabled&&"undefined"!=typeof BroadcastChannel&&this.initCrossTabSync(),d.info("[StateManager] Initialized",{persistence:this.persistence.enabled,sync:this.sync.enabled,history:this.enableHistory})}static create(t={}){return new e(t)}getState(){return this.state}get(e,t=void 0){const n=e.split(".");let i=this.state;for(const s of n){if(null==i||"object"!=typeof i)return t;i=i[s]}return void 0!==i?i:t}set(e,t){const n=e.split("."),i={...this.state};let s=i;for(let l=0;l<n.length-1;l++){const e=n[l];e in s&&"object"==typeof s[e]&&null!==s[e]?s[e]={...s[e]}:s[e]={},s=s[e]}const o=n[n.length-1],a=this.get(e);s[o]=t;const r={type:"SET",path:e,value:t,oldValue:a};null!==this.applyMiddleware(r)&&(this.state=i,this.enableHistory&&this.addToHistory(r),this.persistence.enabled&&this.shouldPersist(e)&&this.persistState(),this.sync.enabled&&this.broadcastStateChange(r),this.notifySubscribers(e,t,a),d.debug("[StateManager] State updated",{path:e,value:t}))}dispatch(e){if("function"==typeof e)return e(this.dispatch.bind(this),this.getState.bind(this));if(!e.type)throw new Error("Action must have a type property");const t=this.applyMiddleware(e);if(null===t)return;const n=this.reducer(this.state,t);n!==this.state&&(this.state,this.state=n,this.enableHistory&&this.addToHistory(t),this.persistence.enabled&&this.persistState(),this.sync.enabled&&this.broadcastStateChange(t),this.notifyAllSubscribers()),d.debug("[StateManager] Action dispatched",t)}reducer(e,t){if("SET"===t.type&&t.path){const n=t.path.split("."),i={...e};let s=i;for(let e=0;e<n.length-1;e++){const t=n[e];t in s&&"object"==typeof s[t]&&null!==s[t]?s[t]={...s[t]}:s[t]={},s=s[t]}return s[n[n.length-1]]=t.value,i}return e}subscribe(e,t){return this.subscribers.has(e)||this.subscribers.set(e,new Set),this.subscribers.get(e).add(t),()=>{const n=this.subscribers.get(e);n&&(n.delete(t),0===n.size&&this.subscribers.delete(e))}}subscribeAll(e){return this.subscribe("*",e)}notifySubscribers(e,t,n){const i=this.subscribers.get(e);i&&i.forEach(i=>{try{i(t,n,e)}catch(s){d.error("[StateManager] Subscriber error",s)}});const s=this.subscribers.get("*");s&&s.forEach(t=>{try{t(this.state,e)}catch(n){d.error("[StateManager] Subscriber error",n)}});const o=e.split(".");for(let a=o.length-1;a>0;a--){const e=o.slice(0,a).join("."),t=this.subscribers.get(e);t&&t.forEach(t=>{try{t(this.get(e),e)}catch(n){d.error("[StateManager] Subscriber error",n)}})}}notifyAllSubscribers(){this.subscribers.forEach((e,t)=>{e.forEach(e=>{try{if("*"===t)e(this.state);else{e(this.get(t),t)}}catch(n){d.error("[StateManager] Subscriber error",n)}})})}use(e){if("function"!=typeof e)throw new Error("Middleware must be a function");this.middleware.push(e)}applyMiddleware(e){let t=e;for(const n of this.middleware)if(t=n(t,this.getState.bind(this)),null===t)return null;return t}loadPersistedState(){try{const e=("sessionStorage"===this.persistence.storage?sessionStorage:localStorage).getItem(this.persistence.key);if(e){const t=JSON.parse(e);this.state={...this.state,...t},d.info("[StateManager] Loaded persisted state")}}catch(e){d.error("[StateManager] Failed to load persisted state",e)}}persistState(){try{const e="sessionStorage"===this.persistence.storage?sessionStorage:localStorage,t=this.persistence.paths.length>0?this.getPersistedPaths():this.state;e.setItem(this.persistence.key,JSON.stringify(t)),d.debug("[StateManager] State persisted")}catch(e){d.error("[StateManager] Failed to persist state",e)}}getPersistedPaths(){const e={};for(const t of this.persistence.paths){const n=this.get(t);if(void 0!==n){const i=t.split(".");let s=e;for(let e=0;e<i.length-1;e++)i[e]in s||(s[i[e]]={}),s=s[i[e]];s[i[i.length-1]]=n}}return e}shouldPersist(e){return 0===this.persistence.paths.length||this.persistence.paths.some(t=>e.startsWith(t))}initCrossTabSync(){try{this.sync.channel=new BroadcastChannel("state-manager-sync"),this.sync.channel.addEventListener("message",e=>{"STATE_CHANGE"===e.data.type&&this.handleRemoteStateChange(e.data.action)}),d.info("[StateManager] Cross-tab sync initialized")}catch(e){d.error("[StateManager] Failed to initialize cross-tab sync",e),this.sync.enabled=!1}}broadcastStateChange(e){if(this.sync.channel)try{this.sync.channel.postMessage({type:"STATE_CHANGE",action:e,timestamp:Date.now()})}catch(t){d.error("[StateManager] Failed to broadcast state change",t)}}handleRemoteStateChange(e){const t=this.sync.enabled;this.sync.enabled=!1,"SET"===e.type&&e.path?this.set(e.path,e.value):this.dispatch(e),this.sync.enabled=t}addToHistory(e){this.history.push({action:e,state:JSON.parse(JSON.stringify(this.state)),timestamp:Date.now()}),this.history.length>this.maxHistorySize&&this.history.shift()}getHistory(){return[...this.history]}timeTravel(e){if(e<0||e>=this.history.length)throw new Error("Invalid history index");const t=this.history[e];this.state=JSON.parse(JSON.stringify(t.state)),this.notifyAllSubscribers(),d.info("[StateManager] Time-traveled to history point",e)}reset(){if(this.state={},this.history=[],this.notifyAllSubscribers(),this.persistence.enabled){("sessionStorage"===this.persistence.storage?sessionStorage:localStorage).removeItem(this.persistence.key)}d.info("[StateManager] State reset")}destroy(){this.subscribers.clear(),this.sync.channel&&(this.sync.channel.close(),this.sync.channel=null),this.history=[],d.info("[StateManager] Destroyed")}},Wn=null;function Vn(e={}){return Wn||(Wn=jn.create(e)),Wn}function Gn(e={}){return jn.create(e)}const Jn={name:"state-manager",stateManager:null,init(e={},t=null){return d.info("[StateManagerModule] Module initialized"),this.stateManager=Vn(e),"undefined"!=typeof window&&(window.StateManager=this.stateManager),this},getStateManager(){return this.stateManager||Vn()},createScoped:(e={})=>Gn(e),destroy(){this.stateManager&&(this.stateManager.destroy(),this.stateManager=null),"undefined"!=typeof window&&window.StateManager&&delete window.StateManager,d.info("[StateManagerModule] Module destroyed")}},Xn=Jn.init.bind(Jn),Qn=Object.freeze(Object.defineProperty({__proto__:null,StateManager:jn,createScopedStateManager:Gn,default:Jn,getGlobalStateManager:Vn,init:Xn},Symbol.toStringTag,{value:"Module"}));let Kn="sticky-fade",Yn=[],Zn=window.scrollY,ei=new WeakMap,ti={direction:!1,reset:!1};const ni=Object.freeze(Object.defineProperty({__proto__:null,destroy:function(){c(Kn),Yn.forEach(e=>{e.style.opacity="",e.style.transform="",e.classList.remove("visible"),delete e.dataset.scrollDir}),Yn=[],ei=new WeakMap},init:function(e={}){Yn=Array.from(document.querySelectorAll("[data-sticky-fade]")),0!==Yn.length&&(ti.direction=e.direction??!1,ti.reset=e.reset??!1,l(Kn,()=>{const e=window.scrollY,t=e>Zn?"down":e<Zn?"up":"none";Zn=e;const n=window.innerHeight;Yn.forEach(e=>{const i=e.getBoundingClientRect(),s=1-Math.min(Math.max(i.top/n,0),1);if(e.style.opacity=s.toFixed(3),e.style.transform=`translateY(${20*(1-s)}px)`,ti.direction&&(e.dataset.scrollDir=t),ti.reset){const t=s>=1,n=ei.get(e)||!1;t&&!n?(e.classList.add("visible"),ei.set(e,!0)):!t&&n&&(e.classList.remove("visible"),ei.set(e,!1))}})},{autoStart:!0}))}},Symbol.toStringTag,{value:"Module"}));const ii=Object.freeze(Object.defineProperty({__proto__:null,destroy:function(){c("sticky-steps")},init:function(e={}){d.info("StickySteps init");const t={containerSelector:"[data-sticky-container]",stepSelector:"[data-sticky-step]",activeClass:"is-sticky-active",datasetKey:"activeStickyStep",...e};document.querySelectorAll(t.containerSelector).forEach(e=>{const n=e.querySelectorAll(t.stepSelector),i=e.offsetTop;l(`sticky-steps-${e.dataset.moduleId||Math.random()}`,function(){const s=window.scrollY,o=e.offsetHeight;n.forEach((a,r)=>{const l=i+r*(o/n.length),c=i+(r+1)*(o/n.length),d=s>=l&&s<c;a.classList.toggle(t.activeClass,d),d&&(e.dataset[t.datasetKey]=r)})},{autoStart:!0})})}},Symbol.toStringTag,{value:"Module"}));const si=Object.freeze(Object.defineProperty({__proto__:null,init:function(){}},Symbol.toStringTag,{value:"Module"})),oi={required:(e,t={})=>null!=e&&""!==e||(t.message||"This field is required"),email:(e,t={})=>{if(!e)return!0;return!!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)||(t.message||"Invalid email address")},url:(e,t={})=>{if(!e)return!0;try{return new URL(e),!0}catch{return t.message||"Invalid URL"}},min:(e,t={})=>{if(!e&&0!==e)return!0;const n=parseFloat(t.value),i="string"==typeof e?parseFloat(e):e;return!(isNaN(i)||i<n)||(t.message||`Value must be at least ${n}`)},max:(e,t={})=>{if(!e&&0!==e)return!0;const n=parseFloat(t.value),i="string"==typeof e?parseFloat(e):e;return!(isNaN(i)||i>n)||(t.message||`Value must be at most ${n}`)},minLength:(e,t={})=>{if(!e)return!0;const n=parseInt(t.value,10);return!("string"!=typeof e||e.length<n)||(t.message||`Must be at least ${n} characters`)},maxLength:(e,t={})=>{if(!e)return!0;const n=parseInt(t.value,10);return!("string"!=typeof e||e.length>n)||(t.message||`Must be at most ${n} characters`)},pattern:(e,t={})=>{if(!e)return!0;return!!new RegExp(t.value).test(e)||(t.message||"Invalid format")},number:(e,t={})=>!e&&0!==e||(!isNaN(parseFloat(e))||(t.message||"Must be a number")),integer:(e,t={})=>!e&&0!==e||(!!Number.isInteger(parseFloat(e))||(t.message||"Must be an integer")),phone:(e,t={})=>{if(!e)return!0;return!!/^[\d\s\-\+\(\)]+$/.test(e)||(t.message||"Invalid phone number")},postalCode:(e,t={})=>{if(!e)return!0;const n=t.country||"DE",i={DE:/^\d{5}$/,US:/^\d{5}(-\d{4})?$/,UK:/^[A-Z]{1,2}\d{1,2}[A-Z]?\s?\d[A-Z]{2}$/i,FR:/^\d{5}$/};return!!(i[n]||i.DE).test(e)||(t.message||`Invalid postal code for ${n}`)},custom:(e,t={})=>t.validator&&"function"==typeof t.validator?t.validator(e,t):"Custom validator function required"};class ai{constructor(e={}){this.schema=e,this.customRules=new Map,this.errors={},this.validatedFields=new Set}static create(e={}){return new ai(e)}registerRule(e,t){if("function"!=typeof t)throw new Error("Validation rule must be a function");this.customRules.set(e,t)}async validateField(e,t,n=null){const i=n||this.schema[e];if(!i)return{valid:!0,errors:[]};const s=[],o=Array.isArray(i)?i:[i];for(const a of o){const e=await this.validateRule(t,a);!0!==e&&s.push(e)}return s.length>0?this.errors[e]=s:delete this.errors[e],this.validatedFields.add(e),{valid:0===s.length,errors:s}}async validateRule(e,t){if("function"==typeof t){const n=await t(e);return!0===n||(n||"Validation failed")}if("string"==typeof t)return this.executeRule(t,e,{});if("object"==typeof t&&null!==t){const n=t.rule||t.type||Object.keys(t)[0],i=t.options||t[n]||{};if(t.async&&"function"==typeof t.validator){const n=await t.validator(e,i);return!0===n||(n||i.message||"Validation failed")}return this.executeRule(n,e,i)}return!0}executeRule(e,t,n){if(this.customRules.has(e)){const i=this.customRules.get(e)(t,n);return!0===i||(i||n.message||"Validation failed")}if(oi[e]){const i=oi[e](t,n);return!0===i||(i||n.message||"Validation failed")}return d.warn(`[Validator] Unknown validation rule: ${e}`),!0}async validate(e){this.errors={},this.validatedFields.clear();const t={};let n=!0;for(const i in this.schema){const s=e[i],o=await this.validateField(i,s);t[i]=o,o.valid||(n=!1)}return{valid:n,errors:this.errors,results:t}}async validateFields(e,t){this.errors={};const n={};let i=!0;for(const s of t){if(!(s in this.schema))continue;const t=e[s],o=await this.validateField(s,t);n[s]=o,o.valid||(i=!1)}return{valid:i,errors:this.errors,results:n}}getFieldErrors(e){return this.errors[e]||[]}getErrors(){return{...this.errors}}isFieldValid(e){return!this.errors[e]||0===this.errors[e].length}isValid(){return 0===Object.keys(this.errors).length}clearErrors(e=null){e?delete this.errors[e]:this.errors={}}reset(){this.errors={},this.validatedFields.clear()}static fromForm(e){const t={};return e.querySelectorAll("input, textarea, select").forEach(e=>{if(!e.name)return;const n=[];if(e.hasAttribute("required")&&n.push("required"),"email"===e.type?n.push("email"):"url"===e.type?n.push("url"):"number"===e.type&&n.push("number"),e.hasAttribute("minlength")&&n.push({rule:"minLength",options:{value:e.getAttribute("minlength")}}),e.hasAttribute("maxlength")&&n.push({rule:"maxLength",options:{value:e.getAttribute("maxlength")}}),e.hasAttribute("min")&&n.push({rule:"min",options:{value:e.getAttribute("min")}}),e.hasAttribute("max")&&n.push({rule:"max",options:{value:e.getAttribute("max")}}),e.hasAttribute("pattern")&&n.push({rule:"pattern",options:{value:e.getAttribute("pattern"),message:e.getAttribute("data-error-pattern")||"Invalid format"}}),e.hasAttribute("data-validate")){const t=e.getAttribute("data-validate");try{const e=JSON.parse(t);n.push(e)}catch{n.push(t)}}n.length>0&&(t[e.name]=n)}),new ai(t)}}class ri{constructor(e,t,n={}){this.name=e,this.validator=t,this.options=n}async validate(e){if("function"==typeof this.validator){const t=await this.validator(e,this.options);return!0===t||(t||this.options.message||"Validation failed")}return!0}getName(){return this.name}getOptions(){return{...this.options}}static create(e,t,n={}){return new ri(e,t,n)}}const li={name:"validation",init(e={},t=null){return d.info("[ValidationModule] Module initialized"),"undefined"!=typeof window&&(window.Validator=ai,window.ValidationRule=ri),this},create:(e={})=>ai.create(e),fromForm:e=>ai.fromForm(e),destroy(){"undefined"!=typeof window&&(delete window.Validator,delete window.ValidationRule),d.info("[ValidationModule] Module destroyed")}},ci=li.init.bind(li),di=Object.freeze(Object.defineProperty({__proto__:null,ValidationRule:ri,Validator:ai,default:li,init:ci},Symbol.toStringTag,{value:"Module"}));class hi{constructor(e={}){this.apiBase=e.apiBase||"/api/push",this.serviceWorkerUrl=e.serviceWorkerUrl||"/js/sw-push.js",this.vapidPublicKey=e.vapidPublicKey||null,this.onSubscriptionChange=e.onSubscriptionChange||null}async init(){if(!("serviceWorker"in navigator))throw new Error("Service Workers are not supported in this browser");if(!("PushManager"in window))throw new Error("Push API is not supported in this browser");await this.registerServiceWorker(),this.vapidPublicKey||await this.fetchVapidPublicKey();const e=await this.getSubscription();return this.onSubscriptionChange&&this.onSubscriptionChange(e),null!==e}async registerServiceWorker(){try{const e=await navigator.serviceWorker.register(this.serviceWorkerUrl);return console.log("[WebPush] Service Worker registered",e),e}catch(e){throw console.error("[WebPush] Service Worker registration failed",e),e}}async fetchVapidPublicKey(){try{const e=await fetch(`${this.apiBase}/vapid-key`),t=await e.json();if(!t.public_key)throw new Error("VAPID public key not available");this.vapidPublicKey=t.public_key,console.log("[WebPush] VAPID public key fetched")}catch(e){throw console.error("[WebPush] Failed to fetch VAPID public key",e),e}}async requestPermission(){const e=await Notification.requestPermission();if(console.log("[WebPush] Permission:",e),"granted"!==e)throw new Error("Notification permission denied");return e}async subscribe(){try{await this.requestPermission();const e=await navigator.serviceWorker.ready;let t=await e.pushManager.getSubscription();return t?console.log("[WebPush] Already subscribed",t):(t=await e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:this.urlBase64ToUint8Array(this.vapidPublicKey)}),console.log("[WebPush] Subscribed",t)),await this.sendSubscriptionToServer(t),this.onSubscriptionChange&&this.onSubscriptionChange(t),t}catch(e){throw console.error("[WebPush] Subscription failed",e),e}}async unsubscribe(){try{const e=await navigator.serviceWorker.ready,t=await e.pushManager.getSubscription();if(!t)return console.log("[WebPush] Not subscribed"),!1;const n=await t.unsubscribe();return n&&(console.log("[WebPush] Unsubscribed from browser"),await this.removeSubscriptionFromServer(t),this.onSubscriptionChange&&this.onSubscriptionChange(null)),n}catch(e){throw console.error("[WebPush] Unsubscribe failed",e),e}}async getSubscription(){try{const e=await navigator.serviceWorker.ready;return await e.pushManager.getSubscription()}catch(e){return console.error("[WebPush] Failed to get subscription",e),null}}async isSubscribed(){return null!==await this.getSubscription()}async sendTestNotification(e,t){try{const n=await this.getSubscription();if(!n)throw new Error("Not subscribed");const i=await fetch(`${this.apiBase}/test`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({endpoint:n.endpoint,title:e||"Test Notification",body:t||"This is a test notification!"})}),s=await i.json();return console.log("[WebPush] Test notification sent",s),s}catch(n){throw console.error("[WebPush] Test notification failed",n),n}}async sendSubscriptionToServer(e){try{const t=e.toJSON(),n=await fetch(`${this.apiBase}/subscribe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw new Error(`Server returned ${n.status}`);const i=await n.json();return console.log("[WebPush] Subscription sent to server",i),i}catch(t){throw console.error("[WebPush] Failed to send subscription to server",t),t}}async removeSubscriptionFromServer(e){try{const t=await fetch(`${this.apiBase}/unsubscribe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({endpoint:e.endpoint})});if(!t.ok)throw new Error(`Server returned ${t.status}`);const n=await t.json();return console.log("[WebPush] Subscription removed from server",n),n}catch(t){throw console.error("[WebPush] Failed to remove subscription from server",t),t}}urlBase64ToUint8Array(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),n=window.atob(t),i=new Uint8Array(n.length);for(let s=0;s<n.length;++s)i[s]=n.charCodeAt(s);return i}getPermissionStatus(){return Notification.permission}static isSupported(){return"serviceWorker"in navigator&&"PushManager"in window}}const ui=Object.freeze(Object.defineProperty({__proto__:null,WebPushManager:hi,init:function(e={},t=null){const n=e.apiBase||"/api/push",i=e.serviceWorkerUrl||"/js/sw-push.js";if(!hi.isSupported())return console.warn("⚠️ WebPush not supported in this browser"),console.warn("Service Worker support:","serviceWorker"in navigator),console.warn("Push Manager support:","PushManager"in window),null;try{return window.webPushManager=new hi({apiBase:n,serviceWorkerUrl:i,onSubscriptionChange:e=>{console.log("🔔 Push subscription changed:",e?"Subscribed":"Unsubscribed")}}),console.log("🔔 WebPush Manager initialized (use window.webPushManager)"),console.log("Service Worker URL:",i),console.log("API Base:",n),console.log(""),console.log("💡 Usage:"),console.log(" await window.webPushManager.init() // Initialize and register service worker"),console.log(" await window.webPushManager.subscribe() // Subscribe to notifications"),console.log(" await window.webPushManager.unsubscribe() // Unsubscribe"),console.log(" await window.webPushManager.sendTestNotification() // Send test"),window.webPushManager}catch(s){return console.error("❌ Failed to initialize WebPush Manager:",s),null}}},Symbol.toStringTag,{value:"Module"})),pi=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),mi={noise:{selector:".noise-overlay",toggleKey:"g",className:"grainy",enableTransition:!0},"shortcut-handler.js":{debug:!1},scrollfx:{selector:".fade-in-on-scroll, .zoom-in",offset:.8,baseDelay:.075,once:!0},"scroll-timeline":{attribute:"data-scroll-step",triggerPoint:.4,once:!1},"smooth-scroll":{speed:.2},"performance-profiler":{enabled:!1,maxSamples:1e3,samplingInterval:10,autoStart:!1,autoInstrument:!0,flamegraphContainer:"#flamegraph-container",timelineContainer:"#timeline-container",flamegraph:{width:1200,height:400,barHeight:20,barPadding:2,colorScheme:"category",minWidth:.5},timeline:{width:1200,height:200,trackHeight:30,padding:{top:20,right:20,bottom:30,left:60}}}};const gi=new class{constructor(){this.crashedModules=new Set,this.recoveryAttempts=new Map,this.maxRecoveryAttempts=3,this.recoveryDelay=1e3}wrapModule(e,t){return e&&"object"==typeof e?new Proxy(e,{get:(e,n,i)=>{const s=e[n];if("function"!=typeof s)return s;const o=Object.getOwnPropertyDescriptor(e,n);return o&&!o.configurable?s:(...i)=>{try{const o=s.apply(e,i);return o&&"function"==typeof o.catch?o.catch(e=>(this.handleModuleError(e,t,n,i),this.getRecoveryValue(t,n))):o}catch(o){return this.handleModuleError(o,t,n,i),this.getRecoveryValue(t,n)}}},getOwnPropertyDescriptor:(e,t)=>{const n=Object.getOwnPropertyDescriptor(e,t);return n&&n.configurable,n},has:(e,t)=>t in e,ownKeys:e=>Object.getOwnPropertyNames(e)}):(d.warn(`[ErrorBoundary] Cannot wrap non-object module: ${t}`),e)}handleModuleError(e,t,n,i){const s=`${t}.${n}`;d.error(`[ErrorBoundary] Module ${t} crashed in ${n}():`,e),this.crashedModules.add(t);const o=this.recoveryAttempts.get(s)||0;this.recoveryAttempts.set(s,o+1),window.dispatchEvent(new CustomEvent("module-error",{detail:{moduleName:t,method:n,error:e.message,args:i,attempts:o+1}})),o<this.maxRecoveryAttempts?this.scheduleRecovery(t,n,i):(d.error(`[ErrorBoundary] Module ${t} exceeded recovery attempts. Marking as permanently failed.`),this.markModuleAsPermanentlyFailed(t))}scheduleRecovery(e,t,n){setTimeout(()=>{try{d.info(`[ErrorBoundary] Attempting recovery for ${e}.${t}()`)}catch(n){d.error(`[ErrorBoundary] Recovery failed for ${e}.${t}():`,n)}},this.recoveryDelay)}getRecoveryValue(e,t){switch(t){case"init":case"destroy":case"update":case"render":return Promise.resolve();case"getData":case"getConfig":return{};case"isEnabled":case"isActive":return!1;default:return}}markModuleAsPermanentlyFailed(e){window.dispatchEvent(new CustomEvent("module-permanent-failure",{detail:{moduleName:e}}))}getHealthStatus(){return{totalCrashedModules:this.crashedModules.size,crashedModules:Array.from(this.crashedModules),recoveryAttempts:Object.fromEntries(this.recoveryAttempts),timestamp:(new Date).toISOString()}}resetModule(e){this.crashedModules.delete(e);for(const[t]of this.recoveryAttempts)t.startsWith(`${e}.`)&&this.recoveryAttempts.delete(t);d.info(`[ErrorBoundary] Reset error tracking for module: ${e}`)}reset(){this.crashedModules.clear(),this.recoveryAttempts.clear(),d.info("[ErrorBoundary] Reset all error tracking")}};window.addEventListener("error",e=>{d.error("[Global] Unhandled error:",e.error||e.message)}),window.addEventListener("unhandledrejection",e=>{d.error("[Global] Unhandled promise rejection:",e.reason)});const fi=new class{constructor(){this.state=new Map,this.subscribers=new Map,this.stateOwners=new Map,this.defaultValues=new Map,this.currentModule="unknown",this.subscriptionCounter=0}setContext(e){this.currentModule=e}register(e,t,n=this.currentModule){this.state.has(e)?d.warn(`[StateManager] State key '${e}' already registered by ${this.stateOwners.get(e)}`):(this.state.set(e,t),this.defaultValues.set(e,t),this.stateOwners.set(e,n),this.subscribers.set(e,[]),d.info(`[StateManager] Registered '${e}' (owner: ${n})`))}get(e){if(this.state.has(e))return this.state.get(e);d.warn(`[StateManager] Unknown state key: '${e}'`)}set(e,t,n=!1){if(!this.state.has(e))return d.warn(`[StateManager] Cannot set unknown state key: '${e}'`),!1;const i=this.stateOwners.get(e);if(!n&&i!==this.currentModule)return d.warn(`[StateManager] Module '${this.currentModule}' cannot modify '${e}' (owned by ${i})`),!1;const s=this.state.get(e);return s===t||(this.state.set(e,t),this.notifySubscribers(e,t,s),d.info(`[StateManager] Updated '${e}' by ${this.currentModule}`)),!0}subscribe(e,t,n=this.currentModule){if(!this.state.has(e))return d.warn(`[StateManager] Cannot subscribe to unknown state key: '${e}'`),null;const i=`${n}_${++this.subscriptionCounter}`,s={id:i,callback:t,subscriber:n};return this.subscribers.has(e)||this.subscribers.set(e,[]),this.subscribers.get(e).push(s),d.info(`[StateManager] Subscribed '${n}' to '${e}'`),i}unsubscribe(e){for(const[t,n]of this.subscribers.entries()){const i=n.findIndex(t=>t.id===e);if(-1!==i){const e=n[i];return n.splice(i,1),void d.info(`[StateManager] Unsubscribed '${e.subscriber}' from '${t}'`)}}d.warn(`[StateManager] Subscription ID not found: ${e}`)}notifySubscribers(e,t,n){(this.subscribers.get(e)||[]).forEach(i=>{try{i.callback(t,n,e)}catch(s){d.error(`[StateManager] Error in subscriber '${i.subscriber}' for '${e}':`,s)}})}reset(e){if(!this.state.has(e))return d.warn(`[StateManager] Cannot reset unknown state key: '${e}'`),!1;const t=this.defaultValues.get(e);return this.set(e,t,!0)}clearModuleSubscriptions(e){let t=0;for(const[n,i]of this.subscribers.entries()){const s=i.filter(t=>t.subscriber!==e);t+=i.length-s.length,this.subscribers.set(n,s)}t>0&&d.info(`[StateManager] Cleared ${t} subscriptions for module '${e}'`)}getSnapshot(){const e={state:Object.fromEntries(this.state),owners:Object.fromEntries(this.stateOwners),subscriptions:{}};for(const[t,n]of this.subscribers.entries())e.subscriptions[t]=n.map(e=>({id:e.id,subscriber:e.subscriber}));return e}resetAll(){this.state.clear(),this.subscribers.clear(),this.stateOwners.clear(),this.defaultValues.clear(),this.subscriptionCounter=0,d.info("[StateManager] Reset complete")}createScope(e){return{register:(t,n)=>(this.setContext(e),this.register(t,n,e)),get:e=>this.get(e),set:(t,n)=>(this.setContext(e),this.set(t,n)),subscribe:(t,n)=>(this.setContext(e),this.subscribe(t,n,e)),unsubscribe:e=>this.unsubscribe(e),reset:e=>this.reset(e),cleanup:()=>this.clearModuleSubscriptions(e)}}};"undefined"!=typeof window&&(window.stateManager=fi,window.stateSnapshot=()=>fi.getSnapshot());const yi=new Map;function vi(){const e=document.querySelectorAll("[data-module]");d.info(`[DOMInit] Found ${e.length} elements with data-module attributes`),e.forEach(e=>{const t=e.dataset.module,n=yi.get(t);if(!n||!n.mod)return void d.warn(`[DOMInit] Module "${t}" not found or failed to initialize`);let i={};try{e.dataset.options&&(i=JSON.parse(e.dataset.options))}catch(s){d.warn(`[DOMInit] Invalid JSON in data-options for ${t}:`,s)}try{const s=n.mod;if("function"==typeof s.initElement){const n=s.initElement(e,i);d.info(`[DOMInit] Initialized ${t} on element:`,e),e._moduleInstance=n,e._moduleName=t}else if("function"==typeof s.init){const n=s.init(e,i);d.info(`[DOMInit] Initialized ${t} on element:`,e),e._moduleInstance=n,e._moduleName=t}else d.warn(`[DOMInit] Module ${t} has no init method for DOM elements`)}catch(s){d.error(`[DOMInit] Failed to initialize ${t} on element:`,s,e)}})}function bi(){const e=document.querySelectorAll('form:not([data-form-handling="false"]):not([data-auto-enhanced])');if(d.info(`[AutoForms] Found ${e.length} forms for auto-enhancement`),0===e.length)return;const t=yi.get("form-handling");t&&t.mod?e.forEach(e=>{if(e.hasAttribute("data-module"))return void d.info("[AutoForms] Skipping form with explicit data-module:",e);if(e.hasAttribute("data-auto-enhanced"))return;let n={};try{e.dataset.formOptions&&(n=JSON.parse(e.dataset.formOptions))}catch(s){d.warn("[AutoForms] Invalid JSON in data-form-options:",s)}const i={validateOnSubmit:!0,validateOnBlur:!1,validateOnInput:!1,showInlineErrors:!0,ajaxSubmit:!0,enableStateTracking:!1,...n};try{const n=t.mod.initElement?t.mod.initElement(e,i):t.mod.init(e,i);d.info("[AutoForms] Auto-enhanced form:",{id:e.id||"unnamed",action:e.action||"none",method:e.method||"get",elements:e.elements.length}),e.setAttribute("data-auto-enhanced","true"),e._moduleInstance=n,e._moduleName="form-handling"}catch(s){d.error("[AutoForms] Failed to auto-enhance form:",s,e)}}):d.warn("[AutoForms] form-handling module not available, skipping auto-init")}async function wi(){await async function(){var e;let t;t="undefined"!=typeof global&&(null==(e=global.importMeta)?void 0:e.glob)?global.importMeta.glob("./*/index.js",{eager:!0}):Object.assign({"./analytics/index.js":y,"./animation-system/index.js":T,"./api-manager/index.js":q,"./cache-manager/index.js":J,"./canvas-animations/index.js":se,"./common/index.js":de,"./error-tracking/index.js":fe,"./event-bus/index.js":Ee,"./example-module/index.js":xe,"./form-handling/index.js":De,"./image-manager/index.js":Ne,"./inertia-scroll/index.js":Xe,"./lightbox-trigger/index.js":tt,"./livecomponent/index.js":Kt,"./noise/index.js":Yt,"./parallax/index.js":Zt,"./performance-profiler/index.js":un,"./router/index.js":wn,"./scroll-dependent/index.js":xn,"./scroll-loop/index.js":Tn,"./scroll-timeline/index.js":Ln,"./scrollfx/index.js":k,"./security/index.js":On,"./smooth-scroll/index.js":zn,"./spa-router/index.js":Un,"./sse/index.js":dt,"./state-manager/index.js":Qn,"./sticky-fade/index.js":ni,"./sticky-steps/index.js":ii,"./ui/index.js":si,"./validation/index.js":di,"./webpush/index.js":ui,"./wheel-boost/index.js":pi}),d.info("[Modules] Found modules:",Object.keys(t));const n=new Set(Array.from(document.querySelectorAll("[data-module]")).map(e=>e.dataset.module).filter(Boolean)),i=new Set(["spa-router","form-handling","api-manager","image-manager","livecomponent"]),s=new Set([...n,...i]),o=s.size===i.size&&0===n.size;d.info("[Modules] DOM modules found:",[...n]),d.info("[Modules] Core modules:",[...i]),d.info("[Modules] Used modules:",[...s]),d.info("[Modules] Fallback mode:",o),console.log("🔍 [Modules] Starting Phase 1 - Module Registration"),console.log("🔍 [Modules] All discovered modules:",Object.keys(t)),console.log("🔍 [Modules] Used modules:",[...s]),console.log("🔍 [Modules] Fallback mode:",o),Object.entries(t).forEach(([e,t])=>{const n=e.split("/").slice(-2,-1)[0];if(console.log(`🔍 [Module] Processing: ${n} from ${e}`),console.log(`🔍 [Module] Used modules has ${n}:`,s.has(n)),o||s.has(n))if(console.log(`✅ [Module] Registering ${n} with dependency manager`),"object"==typeof t.definition)d.info(`📋 [Module] Using definition for ${n}:`,t.definition),En.register(t.definition);else{const e={name:n,version:"1.0.0",dependencies:[],provides:[],priority:0};d.info(`📋 [Module] Using default definition for ${n}:`,e),En.register(e)}else console.log(`⏭️ [Module] Skipping unused module: ${n}`)});const a=En.calculateInitializationOrder();console.log("🔍 [Modules] Phase 2 - Initialization Order:",a);for(const l of a){if(console.log(`🔍 [Module] Phase 3 - Processing ${l} for initialization`),console.log(`🔍 [Module] Used modules has ${l}:`,s.has(l)),console.log("🔍 [Module] Fallback mode:",o),!o&&!s.has(l)){console.log(`⏭️ [Module] Skipped (not used in DOM): ${l}`);continue}const e=Object.keys(t).find(e=>e.split("/").slice(-2,-1)[0]===l);if(console.log(`🔍 [Module] Looking for module path for ${l}, found:`,e),!e){console.log(`⛔ [Module] No implementation found for: ${l}`);continue}const n=t[e],i=mi[l]||{};console.log(`🔍 [Module] Module ${l} object:`,n),console.log(`🔍 [Module] Config for ${l}:`,i);const a=En.checkDependencies(l);if(console.log(`🔍 [Module] Dependency check for ${l}:`,a),a.satisfied)if(console.log(`🔍 [Module] Checking init function for ${l}:`,typeof n.init,n.init),console.log(`🔍 [Module] Module object keys for ${l}:`,Object.keys(n)),console.log(`🔍 [Module] Full module object for ${l}:`,n),"function"==typeof n.init)try{d.info(`🚀 [Module] Starting initialization for ${l}`),En.markInitializing(l);const e=fi.createScope(l),t=gi.wrapModule(n,l);await t.init(i,e),En.markInitialized(l),yi.set(l,{mod:t,config:i,state:e,original:n}),d.info(`✅ [Module] Initialized: ${l}`)}catch(r){d.error(`❌ [Module] Failed to initialize ${l}:`,r),yi.set(l,{mod:null,config:i,error:r,original:n})}else d.warn(`⛔ [Module] No init() in ${l} - typeof:`,typeof n.init),d.warn("⛔ [Module] Available properties:",Object.getOwnPropertyNames(n));else console.log(`❌ [Module] Cannot initialize ${l}: ${a.reason}`),yi.set(l,{mod:null,config:i,error:new Error(a.reason),original:n})}o&&d.info("⚠️ [Module] No data-module usage detected, fallback to full init mode")}(),vi(),bi(),function(){const e=yi.get("spa-router");if(e&&e.mod)try{e.mod.init({containerSelector:"main",enableTransitions:!0,transitionDuration:300}),window.initAutoFormHandling=bi,window.initDataModuleElements=vi,d.info("[Init] SPA Router initialized successfully")}catch(t){d.error("[Init] Failed to initialize SPA Router:",t)}else d.info("[Init] SPA Router module not available, skipping")}(),function(){const e=document.querySelectorAll("video[data-src]"),t=window.innerWidth,n=(navigator.connection||{}).effectiveType||"4g";e.forEach(e=>{const i=e.dataset.src;let s="480";s="2g"===n||"slow-2g"===n?"480":"3g"===n?t>=1200?"720":"480":t>=1200?"1080":t>=800?"720":"480";const o=`${i}-${s}.webm`,a=document.createElement("video");a.autoplay=!0,a.loop=!0,a.muted=!0,a.playsInline=!0,a.poster=e.getAttribute("poster")||"",a.setAttribute("width",e.getAttribute("width")||"100%");const r=document.createElement("source");r.src=o,r.type="video/webm",a.appendChild(r),e.replaceWith(a)})}()}"undefined"!=typeof window&&(window.moduleHealth=function(){const e={total:yi.size,active:0,failed:0,modules:{},errorBoundary:gi.getHealthStatus()};for(const[t,{mod:n,error:i}]of yi.entries())i?(e.failed++,e.modules[t]={status:"failed",error:i.message}):n?(e.active++,e.modules[t]={status:"active"}):e.modules[t]={status:"unknown"};return e},window.activeModules=yi);class Si{static initializeAll(e={}){const t=document.querySelectorAll("form[data-autosave]"),n=[];return t.forEach(t=>{try{const i=Le.create(t,{enableAutosave:!0,...e});n.push(i)}catch(i){d.error("[FormAutoSave] Failed to initialize autosave for form",{form:t.id||"unnamed",error:i})}}),d.info(`[FormAutoSave] Initialized autosave for ${n.length} forms`),n}static initialize(e,t={}){return Le.create(e,{enableAutosave:!0,...t})}}!function(){function e(){document.querySelectorAll("[data-live-dropzone]").forEach(e=>{const n=e.querySelector('input[type="file"]');n&&(["dragenter","dragover","dragleave","drop"].forEach(n=>{e.addEventListener(n,t,!1),document.body.addEventListener(n,t,!1)}),["dragenter","dragover"].forEach(t=>{e.addEventListener(t,()=>{e.classList.add("admin-upload-zone--dragover")},!1)}),["dragleave","drop"].forEach(t=>{e.addEventListener(t,()=>{e.classList.remove("admin-upload-zone--dragover")},!1)}),e.addEventListener("drop",e=>{const t=e.dataTransfer.files;t.length>0&&(n.files=t,n.dispatchEvent(new Event("change",{bubbles:!0})))},!1),e.addEventListener("click",()=>{n&&n.click()},!1))})}function t(e){e.preventDefault(),e.stopPropagation()}function n(){document.querySelectorAll('input[type="file"][data-live-upload]').forEach(e=>{e.addEventListener("change",t=>{const n=t.target.files[0];if(!n||!n.type.startsWith("image/"))return;const i=new FileReader;i.onload=t=>{const n=e.closest("[data-live-component]");if(!n)return;const i=n.querySelector(".admin-file-preview");if(!i)return;const s=i.querySelector(".admin-file-preview__image");if(s)s.src=t.target.result;else{const e=document.createElement("img");e.src=t.target.result,e.className="admin-file-preview__image",e.alt="Preview",i.insertBefore(e,i.firstChild)}},i.readAsDataURL(n)})})}function i(){document.querySelectorAll(".admin-textarea--code").forEach(e=>{e.style.height="auto",e.style.height=e.scrollHeight+"px",e.addEventListener("input",()=>{e.style.height="auto",e.style.height=e.scrollHeight+"px"}),e.addEventListener("paste",()=>{setTimeout(()=>{e.style.height="auto",e.style.height=e.scrollHeight+"px"},10)})})}const s={show(e,t="info",n=5e3){const i=document.createElement("div");i.className=`admin-toast admin-toast--${t}`;const s=document.createElement("p");s.className="admin-toast__message",s.textContent=e,i.appendChild(s);const o=document.createElement("button");return o.className="admin-toast__close",o.innerHTML="×",o.setAttribute("aria-label","Close"),o.addEventListener("click",()=>this.hide(i)),i.appendChild(o),document.body.appendChild(i),n>0&&setTimeout(()=>this.hide(i),n),i},hide(e){e&&e.parentNode&&(e.style.animation="admin-toast-slide-out 0.3s ease-out",setTimeout(()=>{e.parentNode&&e.parentNode.removeChild(e)},300))},success(e,t=5e3){return this.show(e,"success",t)},error(e,t=7e3){return this.show(e,"error",t)},info(e,t=5e3){return this.show(e,"info",t)},warning(e,t=6e3){return this.show(e,"warning",t)}};document.addEventListener("livecomponent:upload:success",e=>{const t=e.detail||{};s.success(t.message||"File uploaded successfully!"),t.redirect_url&&setTimeout(()=>{window.location.href=t.redirect_url},1500)}),document.addEventListener("livecomponent:upload:error",e=>{var t;const n=(null==(t=e.detail)?void 0:t.error)||"Upload failed";s.error(n)}),document.addEventListener("livecomponent:draft:saved",e=>{s.info("Draft saved")}),document.addEventListener("livecomponent:form:submitted",e=>{const t=e.detail||{};t.success&&t.redirect_url?(s.success(t.message||"Content created successfully!"),setTimeout(()=>{window.location.href=t.redirect_url},1e3)):s.error(t.message||"Failed to submit form")}),function t(){"loading"!==document.readyState?(e(),n(),i(),document.addEventListener("keydown",e=>{if((e.ctrlKey||e.metaKey)&&"s"===e.key){e.preventDefault();const t=document.querySelector('[data-live-action="autoSave"]');t&&t.click()}if("Escape"===e.key){const e=document.querySelector('a[href*="/admin/"]');e&&"cancel"===e.textContent.trim().toLowerCase()&&e.click()}}),document.querySelectorAll("[data-live-component]").forEach(e=>{const t=e.querySelectorAll("input, textarea, select");let n=null;t.forEach(t=>{t.addEventListener("input",()=>{n&&clearTimeout(n),n=setTimeout(()=>{const t=e.querySelector('[data-live-action="autoSave"]');t&&t.click()},3e4)})})}),window.AdminToast=s):document.addEventListener("DOMContentLoaded",t)}(),document.addEventListener("livecomponent:loaded",()=>{e(),n(),i()})}();class Ei{constructor(e){var t,n;this.table=e,this.resource=e.dataset.resource,this.bulkActions=JSON.parse(e.dataset.bulkActions||"[]"),this.selectedIds=new Set,this.toolbar=document.querySelector(`[data-bulk-toolbar="${this.resource}"]`),this.countElement=null==(t=this.toolbar)?void 0:t.querySelector("[data-bulk-count]"),this.buttonsContainer=null==(n=this.toolbar)?void 0:n.querySelector("[data-bulk-buttons]"),this.init()}init(){this.table.dataset.bulkOperations&&"true"===this.table.dataset.bulkOperations&&(this.setupCheckboxes(),this.setupSelectAll(),this.setupBulkActions(),this.updateToolbar())}setupCheckboxes(){this.table.querySelectorAll(".bulk-select-item").forEach(e=>{e.addEventListener("change",e=>{const t=e.target.dataset.bulkItemId;e.target.checked?this.selectedIds.add(t):this.selectedIds.delete(t),this.updateToolbar(),this.updateSelectAllState()})})}setupSelectAll(){const e=this.table.querySelector("[data-bulk-select-all]");e&&e.addEventListener("change",e=>{const t=e.target.checked;this.table.querySelectorAll(".bulk-select-item").forEach(e=>{e.checked=t;const n=e.dataset.bulkItemId;t?this.selectedIds.add(n):this.selectedIds.delete(n)}),this.updateToolbar()})}setupBulkActions(){this.buttonsContainer&&0!==this.bulkActions.length&&(this.buttonsContainer.innerHTML="",this.bulkActions.forEach(e=>{const t=document.createElement("button");t.className=`btn btn--${e.style||"secondary"} btn--sm`,t.textContent=e.label,t.dataset.bulkAction=e.action,t.dataset.bulkMethod=e.method||"POST",e.confirm&&(t.dataset.bulkConfirm=e.confirm),t.addEventListener("click",t=>{t.preventDefault(),this.executeBulkAction(e)}),this.buttonsContainer.appendChild(t)}))}async executeBulkAction(e){var t,n;if(0!==this.selectedIds.size){if("tag"===e.action&&!1===e.confirm)return this.showBulkTagModal(e);if(e.confirm){if(!(await this.showConfirmationDialog(e.confirm,`This will affect ${this.selectedIds.size} item(s).`)))return}try{this.setLoadingState(!0);Array.from(this.selectedIds).map(e=>this.table.querySelector(`tr[data-id="${e}"]`)).filter(Boolean).map(e=>{const t=e.style.display;return e.style.display="none",e.classList.add("optimistic-delete"),()=>{e.style.display=t,e.classList.remove("optimistic-delete")}});const n=Array.from(this.selectedIds),i=e.method||"POST",s={assets:{delete:"/api/v1/assets/bulk/delete",tag:"/api/v1/assets/bulk/tags"},contents:{delete:"/admin/api/contents/bulk/delete",publish:"/admin/api/contents/bulk/publish"}},o=e.endpoint||(null==(t=s[this.resource])?void 0:t[e.action])||`/admin/api/${this.resource}/bulk/${e.action}`,a=window.safeFetch||(async(e,t)=>{const n=await fetch(e,t);if(!n.ok){const e=await n.json().catch(()=>({error:"Unknown error"}));throw new Error(e.error||`HTTP ${n.status}`)}return await n.json()});let r={ids:Array.from(this.selectedIds)};"tag"===e.action&&e.tags&&(r.tags=e.tags);const l=await a(o,{method:i,headers:{"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"},body:JSON.stringify(r)}),c=l.total_deleted||l.total_published||l.total_tagged||n.length,d="tag"===e.action?"tagged":e.label.toLowerCase();this.showToast(`Successfully ${d} ${c} item(s)`,"success"),this.clearSelection();const h=this.table.adminDataTable;h&&"function"==typeof h.loadData?h.loadData():window.location.reload()}catch(i){console.error("Bulk action failed:",i),window.rollbackRows&&window.rollbackRows.forEach(e=>e());const t=i.message||"Unknown error occurred";if(this.showToast(`Failed to ${e.label.toLowerCase()}: ${t}`,"error"),this.toolbar){const t=document.createElement("button");t.className="retry-button",t.textContent="Retry",t.onclick=()=>{t.remove(),this.executeBulkAction(e)},null==(n=this.buttonsContainer)||n.appendChild(t)}}finally{this.setLoadingState(!1)}}}updateToolbar(){if(!this.toolbar)return;const e=this.selectedIds.size;e>0?(this.toolbar.style.display="flex",this.countElement&&(this.countElement.textContent=e)):this.toolbar.style.display="none"}updateSelectAllState(){const e=this.table.querySelector("[data-bulk-select-all]");if(!e)return;const t=this.table.querySelectorAll(".bulk-select-item"),n=Array.from(t).filter(e=>e.checked).length;0===n?(e.checked=!1,e.indeterminate=!1):n===t.length?(e.checked=!0,e.indeterminate=!1):(e.checked=!1,e.indeterminate=!0)}clearSelection(){this.selectedIds.clear();this.table.querySelectorAll(".bulk-select-item").forEach(e=>{e.checked=!1});const e=this.table.querySelector("[data-bulk-select-all]");e&&(e.checked=!1,e.indeterminate=!1),this.updateToolbar()}setLoadingState(e){var t;const n=null==(t=this.buttonsContainer)?void 0:t.querySelectorAll("button");n&&n.forEach(t=>{t.disabled=e,e?(t.dataset.originalText=t.textContent,t.textContent="Processing..."):t.textContent=t.dataset.originalText||t.textContent})}async showConfirmationDialog(e,t){return new Promise(n=>{const i=document.createElement("div");i.className="bulk-confirm-dialog",i.innerHTML=`\n <div class="bulk-confirm-dialog__overlay"></div>\n <div class="bulk-confirm-dialog__content">\n <h3>${e}</h3>\n <p>${t}</p>\n <div class="bulk-confirm-dialog__actions">\n <button class="btn btn--secondary" data-confirm-cancel>Cancel</button>\n <button class="btn btn--danger" data-confirm-ok>Confirm</button>\n </div>\n </div>\n `,document.body.appendChild(i);const s=()=>{document.body.removeChild(i)};i.querySelector("[data-confirm-ok]").addEventListener("click",()=>{s(),n(!0)}),i.querySelector("[data-confirm-cancel]").addEventListener("click",()=>{s(),n(!1)}),i.querySelector(".bulk-confirm-dialog__overlay").addEventListener("click",()=>{s(),n(!1)})})}showToast(e,t="info"){window.Toast?window.Toast[t](e):alert(e)}async showBulkTagModal(e){let t=document.getElementById("bulk-tag-modal");t||(t=document.createElement("div"),t.id="bulk-tag-modal",t.innerHTML=await fetch("/admin/templates/bulk-tag-modal").then(e=>e.text()).catch(()=>""),document.body.appendChild(t));const n=t.querySelector("#bulk-tag-count");n&&(n.textContent=this.selectedIds.size),t.style.display="block";const i=t.querySelector("#bulk-tag-input"),s=t.querySelector("#bulk-tag-suggestions"),o=t.querySelector(".bulk-tag-suggestions-list");let a=[];const r=async(e="")=>{try{const t=await fetch("/api/v1/tags/suggestions"+(e?"?search="+encodeURIComponent(e):"")),n=await t.json();a=n.tags||[],a.length>0?(s.style.display="block",o.innerHTML=a.slice(0,10).map(e=>`<button type="button" class="bulk-tag-suggestion" data-tag="${e}">${e}</button>`).join(""),o.querySelectorAll(".bulk-tag-suggestion").forEach(e=>{e.addEventListener("click",()=>{const t=e.dataset.tag,n=i.value.split(",").map(e=>e.trim()).filter(Boolean);n.includes(t)||(n.push(t),i.value=n.join(", "))})})):s.style.display="none"}catch(t){console.error("Failed to load tag suggestions:",t)}};if(await r(),i){let e;i.addEventListener("input",t=>{clearTimeout(e),e=setTimeout(()=>{const e=t.target.value.split(",").pop().trim();e.length>1?r(e):r()},300)})}const l=t.querySelector("#bulk-tag-submit"),c=()=>{t.style.display="none",i&&(i.value=""),s.style.display="none"};null==l||l.addEventListener("click",async()=>{const t=null==i?void 0:i.value.trim();if(!t)return void this.showToast("Please enter at least one tag","error");const n=t.split(",").map(e=>e.trim()).filter(Boolean),s={...e,tags:n};c(),await this.executeBulkAction(s)}),t.querySelectorAll("[data-close-modal]").forEach(e=>{e.addEventListener("click",c)})}}document.addEventListener("DOMContentLoaded",()=>{document.querySelectorAll('[data-bulk-operations="true"]').forEach(e=>{new Ei(e)})});class Ci{constructor(){this.init()}init(){this.setupLoadingStates(),this.setupOptimisticUpdates(),this.setupErrorHandling(),this.setupFormEnhancements()}setupLoadingStates(){document.addEventListener("click",e=>{const t=e.target.closest("button[data-loading]");if(t&&!t.disabled){const e=t.textContent;t.dataset.originalText=e,t.disabled=!0,t.classList.add("loading");const n=document.createElement("span");n.className="button-spinner",n.innerHTML="⏳",t.prepend(n),t.textContent=t.dataset.loadingText||"Loading...",setTimeout(()=>{this.resetButton(t)},1e4)}})}resetButton(e){e.dataset.originalText&&(e.textContent=e.dataset.originalText,delete e.dataset.originalText),e.disabled=!1,e.classList.remove("loading");const t=e.querySelector(".button-spinner");t&&t.remove()}setupOptimisticUpdates(){window.optimisticUpdate=(e,t,n)=>{const i=this.captureState(e);try{return t(e),()=>{this.restoreState(e,i),n&&n()}}catch(s){return console.error("Optimistic update failed:",s),null}},document.addEventListener("click",e=>{const t=e.target.closest("tr[data-id]");if(!t)return;const n=e.target.closest("[data-optimistic]");if(!n)return;const i=n.dataset.optimistic,s=this.optimisticTableUpdate(t,i);n.dataset.rollback="true",n.addEventListener("error",()=>{s&&s()},{once:!0})})}optimisticTableUpdate(e,t){const n=e.className,i=e.style.opacity;switch(t){case"delete":return e.style.opacity="0.5",e.style.textDecoration="line-through",e.classList.add("optimistic-delete"),()=>{e.className=n,e.style.opacity=i,e.style.textDecoration="",e.classList.remove("optimistic-delete")};case"update":return e.classList.add("optimistic-update"),()=>{e.classList.remove("optimistic-update")};default:return null}}captureState(e){return{className:e.className,style:e.style.cssText,innerHTML:e.innerHTML}}restoreState(e,t){e.className=t.className,e.style.cssText=t.style,e.innerHTML=t.innerHTML}setupErrorHandling(){window.addEventListener("error",e=>{this.showErrorNotification("An unexpected error occurred",e.error)}),window.addEventListener("unhandledrejection",e=>{this.showErrorNotification("Request failed",e.reason)}),window.safeFetch=async(e,t={})=>{try{const n=await fetch(e,t);if(!n.ok){const e=await n.json().catch(()=>({error:"Unknown error"}));throw new Error(e.error||`HTTP ${n.status}: ${n.statusText}`)}return await n.json()}catch(n){throw this.showErrorNotification("Request failed",n.message),n}}}showErrorNotification(e,t){if(window.Toast)window.Toast.error(`${e}: ${t}`);else{console.error(e,t);const n=document.createElement("div");n.className="error-notification",n.innerHTML=`\n <strong>${e}</strong>\n <p>${t}</p>\n <button onclick="this.parentElement.remove()">Close</button>\n `,document.body.appendChild(n),setTimeout(()=>{n.parentNode&&n.remove()},5e3)}}setupFormEnhancements(){document.addEventListener("submit",e=>{const t=e.target;if("FORM"!==t.tagName)return;const n=t.querySelector('button[type="submit"], input[type="submit"]');if(n){n.disabled=!0,n.classList.add("loading");const e=n.value||n.textContent;n.dataset.originalText=e,n.value=n.value?"Submitting...":n.value,n.textContent=n.textContent?"Submitting...":n.textContent}t.addEventListener("error",()=>{n&&(n.disabled=!1,n.classList.remove("loading"),n.value=n.dataset.originalText||n.value,n.textContent=n.dataset.originalText||n.textContent)},{once:!0})}),window.retryRequest=async(e,t=3,n=1e3)=>{let i;for(let o=0;o<t;o++)try{return await e()}catch(s){i=s,o<t-1&&await new Promise(e=>setTimeout(e,n*(o+1)))}throw i}}}document.addEventListener("DOMContentLoaded",()=>{new Ci});class ki{constructor(){this.lightbox=null,this.init()}init(){this.setupThumbnailClicks(),this.setupLightbox(),this.setupCopyUrl(),this.setupVariantDeletion()}setupThumbnailClicks(){document.addEventListener("click",e=>{const t=e.target.closest(".asset-preview-thumbnail");if(!t)return;const n=t.dataset.assetId;n&&(window.location.href=`/admin/assets/${n}`)})}setupLightbox(){document.getElementById("asset-lightbox")||document.body.insertAdjacentHTML("beforeend",'\n <div class="asset-lightbox" id="asset-lightbox" style="display: none;">\n <div class="asset-lightbox__content">\n <img class="asset-lightbox__image" src="" alt="Asset Preview" />\n <button class="asset-lightbox__close" data-close-lightbox>×</button>\n <div class="asset-lightbox__info">\n <p class="asset-lightbox__filename"></p>\n <p class="asset-lightbox__size"></p>\n </div>\n </div>\n </div>\n '),this.lightbox=document.getElementById("asset-lightbox"),document.addEventListener("click",e=>{const t=e.target.closest("img[data-lightbox]");t&&(e.preventDefault(),this.openLightbox(t.src,t.alt,t.dataset.filename,t.dataset.size))}),document.addEventListener("click",e=>{(e.target.closest("[data-close-lightbox]")||e.target===this.lightbox)&&this.closeLightbox()}),document.addEventListener("keydown",e=>{"Escape"===e.key&&this.lightbox&&"none"!==this.lightbox.style.display&&this.closeLightbox()})}openLightbox(e,t,n,i){if(!this.lightbox)return;const s=this.lightbox.querySelector(".asset-lightbox__image"),o=this.lightbox.querySelector(".asset-lightbox__filename"),a=this.lightbox.querySelector(".asset-lightbox__size");s.src=e,s.alt=t,o&&(o.textContent=n||t),a&&(a.textContent=i||""),this.lightbox.style.display="flex",document.body.style.overflow="hidden"}closeLightbox(){this.lightbox&&(this.lightbox.style.display="none",document.body.style.overflow="")}setupCopyUrl(){document.addEventListener("click",async e=>{const t=e.target.closest("[data-copy-url]");if(t){e.preventDefault();try{const e=t.href,n=await fetch(e),i=(await n.json()).url||e;await navigator.clipboard.writeText(i);const s=t.textContent;t.textContent="Copied!",t.classList.add("copied"),setTimeout(()=>{t.textContent=s,t.classList.remove("copied")},2e3)}catch(n){console.error("Failed to copy URL:",n),alert("Failed to copy URL")}}})}setupVariantDeletion(){document.addEventListener("click",async e=>{var t,n;const i=e.target.closest("[data-delete-variant]");if(!i)return;e.preventDefault();const s=i.dataset.variant,o=(null==(t=i.closest("[data-asset-id]"))?void 0:t.dataset.assetId)||window.location.pathname.split("/").pop();if(confirm(`Are you sure you want to delete variant "${s}"?`))try{i.disabled=!0,i.textContent="Deleting...";const e=await fetch(`/api/v1/assets/${o}/variants/${s}`,{method:"DELETE",headers:{"X-Requested-With":"XMLHttpRequest"}});if(!e.ok)throw new Error(`HTTP ${e.status}`);null==(n=i.closest(".variant-item"))||n.remove(),window.Toast&&window.Toast.success(`Variant "${s}" deleted successfully`)}catch(a){console.error("Failed to delete variant:",a),i.disabled=!1,i.textContent="Delete",window.Toast?window.Toast.error(`Failed to delete variant: ${a.message}`):alert(`Failed to delete variant: ${a.message}`)}})}}document.addEventListener("DOMContentLoaded",()=>{new ki});class Mi{constructor(e){this.resource=e,this.filters={mime:[],bucket:[],date_from:null,date_to:null,tags:[]},this.init()}init(){this.setupToggle(),this.setupFilters(),this.setupApply(),this.setupClear()}setupToggle(){const e=document.querySelector("[data-toggle-filters]"),t=document.querySelector(`[data-filters-panel="${this.resource}"]`);e&&t&&e.addEventListener("click",()=>{const n="none"!==t.style.display;t.style.display=n?"none":"block",e.classList.toggle("active",!n)})}setupFilters(){const e=document.querySelector(`[data-filters-panel="${this.resource}"] [data-filter="mime"]`);e&&e.addEventListener("change",e=>{this.filters.mime=Array.from(e.target.selectedOptions).map(e=>e.value)});const t=document.querySelector(`[data-filters-panel="${this.resource}"] [data-filter="bucket"]`);t&&t.addEventListener("change",e=>{this.filters.bucket=Array.from(e.target.selectedOptions).map(e=>e.value)});const n=document.querySelector(`[data-filters-panel="${this.resource}"] [data-filter="date_from"]`);n&&n.addEventListener("change",e=>{this.filters.date_from=e.target.value||null});const i=document.querySelector(`[data-filters-panel="${this.resource}"] [data-filter="date_to"]`);i&&i.addEventListener("change",e=>{this.filters.date_to=e.target.value||null});const s=document.querySelector(`[data-filters-panel="${this.resource}"] [data-filter="tags"]`);s&&s.addEventListener("input",e=>{const t=e.target.value.trim();this.filters.tags=t?t.split(",").map(e=>e.trim()).filter(Boolean):[]})}setupApply(){const e=document.querySelector(`[data-filters-panel="${this.resource}"] [data-apply-filters]`);e&&e.addEventListener("click",()=>{this.applyFilters()})}setupClear(){const e=document.querySelector(`[data-filters-panel="${this.resource}"] [data-clear-filters]`);e&&e.addEventListener("click",()=>{this.clearFilters()})}applyFilters(){const e=new URLSearchParams;this.filters.mime.length>0&&e.append("mime",this.filters.mime.join(",")),this.filters.bucket.length>0&&e.append("bucket",this.filters.bucket.join(",")),this.filters.date_from&&e.append("date_from",this.filters.date_from),this.filters.date_to&&e.append("date_to",this.filters.date_to),this.filters.tags.length>0&&e.append("tags",this.filters.tags.join(","));if(document.querySelector(`[data-resource="${this.resource}"]`)&&window.adminDataTables&&window.adminDataTables.get(this.resource)){const t=window.adminDataTables.get(this.resource);"function"==typeof t.loadData&&t.loadData(e.toString())}else{const t=new URL(window.location.href);e.forEach((e,n)=>{t.searchParams.set(n,e)}),window.location.href=t.toString()}}clearFilters(){this.filters={mime:[],bucket:[],date_from:null,date_to:null,tags:[]};const e=document.querySelector(`[data-filters-panel="${this.resource}"]`);e&&e.querySelectorAll("select, input").forEach(e=>{"SELECT"===e.tagName?e.selectedIndex=-1:e.value=""});const t=new URL(window.location.href);["mime","bucket","date_from","date_to","tags"].forEach(e=>{t.searchParams.delete(e)}),window.location.href=t.toString()}}document.addEventListener("DOMContentLoaded",()=>{document.querySelector('[data-resource="assets"]')&&(window.assetFilters=new Mi("assets"))});class xi{constructor(){this.modal=null,this.assetId=null,this.init()}init(){this.setupCreateButtons(),this.setupModal(),this.setupPresets(),this.setupSubmit()}setupCreateButtons(){document.addEventListener("click",e=>{var t;const n=e.target.closest("[data-create-variant]");n&&(e.preventDefault(),this.assetId=(null==(t=n.closest("[data-asset-id]"))?void 0:t.dataset.assetId)||window.location.pathname.split("/").pop(),this.showModal())})}setupModal(){if(this.modal=document.getElementById("variant-create-modal"),!this.modal)return void console.warn("Variant creation modal not found");this.modal.querySelectorAll("[data-close-variant-modal]").forEach(e=>{e.addEventListener("click",()=>this.closeModal())});const e=this.modal.querySelector("#variant-quality"),t=this.modal.querySelector("#quality-value");e&&t&&e.addEventListener("input",e=>{t.textContent=e.target.value})}setupPresets(){var e;const t={"1200w":{variant:"1200w",width:1200,quality:85},"800w":{variant:"800w",width:800,quality:85},"thumb@1x":{variant:"thumb@1x",width:200,quality:80},"thumb@2x":{variant:"thumb@2x",width:400,quality:80}};null==(e=this.modal)||e.querySelectorAll("[data-preset]").forEach(e=>{e.addEventListener("click",()=>{const n=t[e.dataset.preset];n&&(this.modal.querySelector("#variant-name").value=n.variant,this.modal.querySelector("#variant-width").value=n.width,this.modal.querySelector("#variant-quality").value=n.quality,this.modal.querySelector("#quality-value").textContent=n.quality)})})}setupSubmit(){var e;const t=null==(e=this.modal)?void 0:e.querySelector("#variant-create-submit");t&&t.addEventListener("click",async()=>{await this.createVariant()})}showModal(){if(!this.modal)return;const e=this.modal.querySelector("#variant-create-form");e&&(e.reset(),this.modal.querySelector("#variant-quality").value=85,this.modal.querySelector("#quality-value").textContent="85"),this.modal.style.display="block"}closeModal(){this.modal&&(this.modal.style.display="none")}async createVariant(){if(!this.assetId)return void console.error("Asset ID not set");const e=this.modal.querySelector("#variant-create-form");if(!e)return;const t=new FormData(e),n={variant:t.get("variant"),width:t.get("width")?parseInt(t.get("width")):null,height:t.get("height")?parseInt(t.get("height")):null,quality:t.get("quality")?parseInt(t.get("quality")):null};if(!n.variant)return void(window.Toast?window.Toast.error("Variant name is required"):alert("Variant name is required"));const i=this.modal.querySelector("#variant-create-submit"),s=i.textContent;i.disabled=!0,i.textContent="Creating...";try{const e=await fetch(`/api/v1/assets/${this.assetId}/variants`,{method:"POST",headers:{"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"},body:JSON.stringify(n)});if(!e.ok){const t=await e.json().catch(()=>({error:"Unknown error"}));throw new Error(t.error||`HTTP ${e.status}`)}await e.json();window.Toast?window.Toast.success("Variant creation queued. It will be processed shortly."):alert("Variant creation queued successfully"),this.closeModal(),setTimeout(()=>{window.location.reload()},1500)}catch(o){console.error("Failed to create variant:",o),window.Toast?window.Toast.error(`Failed to create variant: ${o.message}`):alert(`Failed to create variant: ${o.message}`)}finally{i.disabled=!1,i.textContent=s}}}document.addEventListener("DOMContentLoaded",()=>{new xi});class Ti{constructor(){this.init()}init(){this.setupDeleteDuplicate(),this.setupDeleteGroup(),this.setupMergeGroup(),this.setupRefresh()}setupDeleteDuplicate(){document.addEventListener("click",async e=>{const t=e.target.closest("[data-delete-duplicate]");if(!t)return;e.preventDefault();const n=t.dataset.assetId;confirm("Are you sure you want to delete this duplicate asset?")&&await this.deleteAsset(n,t)})}setupDeleteGroup(){document.addEventListener("click",async e=>{const t=e.target.closest("[data-delete-group]");if(!t)return;e.preventDefault();const n=t.dataset.sha256,i=t.closest(".duplicate-group"),s=(null==i?void 0:i.querySelectorAll(".duplicate-asset-card").length)||0;confirm(`Are you sure you want to delete all ${s} duplicate assets in this group?`)&&await this.deleteGroup(n,t)})}setupMergeGroup(){document.addEventListener("click",async e=>{const t=e.target.closest("[data-merge-group]");if(!t)return;e.preventDefault();const n=t.dataset.sha256,i=t.closest(".duplicate-group"),s=Array.from((null==i?void 0:i.querySelectorAll("[data-asset-id]"))||[]).map(e=>e.dataset.assetId);if(s.length<2)return void(window.Toast?window.Toast.warning("Need at least 2 assets to merge"):alert("Need at least 2 assets to merge"));const o=await this.showMergeDialog(s);o&&await this.mergeGroup(n,s,o,t)})}setupRefresh(){document.addEventListener("click",e=>{e.target.closest("[data-refresh-duplicates]")&&(e.preventDefault(),window.location.reload())})}async deleteAsset(e,t){var n;const i=t.textContent;t.disabled=!0,t.textContent="Deleting...";try{const i=await fetch(`/admin/api/assets/${e}`,{method:"DELETE",headers:{"X-Requested-With":"XMLHttpRequest"}});if(!i.ok)throw new Error(`HTTP ${i.status}`);window.Toast&&window.Toast.success("Duplicate asset deleted"),null==(n=t.closest(".duplicate-asset-card"))||n.remove();const s=t.closest(".duplicate-group");((null==s?void 0:s.querySelectorAll(".duplicate-asset-card").length)||0)<=1&&(null==s||s.remove())}catch(s){console.error("Failed to delete asset:",s),window.Toast?window.Toast.error(`Failed to delete asset: ${s.message}`):alert(`Failed to delete asset: ${s.message}`)}finally{t.disabled=!1,t.textContent=i}}async deleteGroup(e,t){const n=t.closest(".duplicate-group"),i=(null==n?void 0:n.querySelectorAll(".duplicate-asset-card"))||[],s=Array.from(i).map(e=>{var t;return null==(t=e.querySelector("[data-asset-id]"))?void 0:t.dataset.assetId}).filter(Boolean);t.disabled=!0,t.textContent="Deleting...";try{const e=s.map(e=>fetch(`/admin/api/assets/${e}`,{method:"DELETE",headers:{"X-Requested-With":"XMLHttpRequest"}}));await Promise.all(e),window.Toast&&window.Toast.success(`Deleted ${s.length} duplicate assets`),null==n||n.remove()}catch(o){console.error("Failed to delete group:",o),window.Toast?window.Toast.error(`Failed to delete group: ${o.message}`):alert(`Failed to delete group: ${o.message}`)}finally{t.disabled=!1,t.textContent="Delete All"}}async showMergeDialog(e){return new Promise(t=>{const n=document.createElement("div");n.className="merge-dialog",n.innerHTML='\n <div class="merge-dialog__overlay"></div>\n <div class="merge-dialog__content">\n <h3>Merge Duplicate Assets</h3>\n <p>Select which asset to keep. All other duplicates will be deleted.</p>\n <div class="merge-dialog__assets" id="merge-assets-list"></div>\n <div class="merge-dialog__actions">\n <button class="btn btn--secondary" data-merge-cancel>Cancel</button>\n <button class="btn btn--primary" data-merge-confirm disabled>Merge</button>\n </div>\n </div>\n ',document.body.appendChild(n);const i=n.querySelector("#merge-assets-list");let s=null;e.forEach(e=>{var t,o;const a=null==(t=document.querySelector(`[data-asset-id="${e}"]`))?void 0:t.closest(".duplicate-asset-card");if(!a)return;const r=a.querySelector(".asset-id code"),l=a.querySelector(".asset-bucket"),c=null==(o=a.querySelector(".asset-preview-small"))?void 0:o.innerHTML,d=document.createElement("div");d.className="merge-asset-option",d.innerHTML=`\n <input type="radio" name="keep-asset" value="${e}" id="asset-${e}">\n <label for="asset-${e}">\n <div class="merge-asset-preview">${c||""}</div>\n <div class="merge-asset-info">\n <strong>${(null==r?void 0:r.textContent)||e}</strong>\n <small>${(null==l?void 0:l.textContent)||""}</small>\n </div>\n </label>\n `,d.querySelector("input").addEventListener("change",e=>{e.target.checked&&(s=e.target.value,n.querySelector("[data-merge-confirm]").disabled=!1)}),i.appendChild(d)});const o=()=>{document.body.removeChild(n)};n.querySelector("[data-merge-confirm]").addEventListener("click",()=>{o(),t(s)}),n.querySelector("[data-merge-cancel]").addEventListener("click",()=>{o(),t(null)}),n.querySelector(".merge-dialog__overlay").addEventListener("click",()=>{o(),t(null)})})}async mergeGroup(e,t,n,i){var s;i.disabled=!0,i.textContent="Merging...";try{const e=t.filter(e=>e!==n),o=e.map(e=>fetch(`/admin/api/assets/${e}`,{method:"DELETE",headers:{"X-Requested-With":"XMLHttpRequest"}}));await Promise.all(o),window.Toast&&window.Toast.success(`Merged ${e.length} duplicates into one asset`),null==(s=i.closest(".duplicate-group"))||s.remove()}catch(o){console.error("Failed to merge group:",o),window.Toast?window.Toast.error(`Failed to merge group: ${o.message}`):alert(`Failed to merge group: ${o.message}`)}finally{i.disabled=!1,i.textContent="Merge Group"}}}document.addEventListener("DOMContentLoaded",()=>{document.querySelector(".duplicates-list")&&new Ti});class Ai{constructor(e){this.container=e,this.blocksContainer=e.querySelector('[data-sortable="blocks"]'),this.draggedElement=null,this.dragOverIndex=null,this.componentId=null;const t=e.closest("[data-live-component]");t&&(this.componentId=t.dataset.liveComponent),this.init()}init(){this.blocksContainer&&(this.updateDraggableElements(),this.observeBlockChanges())}updateDraggableElements(){this.blocksContainer.querySelectorAll(".admin-block-card").forEach((e,t)=>{e.draggable=!0,e.dataset.blockIndex=t;const n=e.cloneNode(!0);e.parentNode.replaceChild(n,e),n.addEventListener("dragstart",e=>this.handleDragStart(e,n)),n.addEventListener("dragend",e=>this.handleDragEnd(e,n)),n.addEventListener("dragover",e=>this.handleDragOver(e,n)),n.addEventListener("dragenter",e=>this.handleDragEnter(e,n)),n.addEventListener("dragleave",e=>this.handleDragLeave(e,n)),n.addEventListener("drop",e=>this.handleDrop(e,n));n.querySelectorAll("button, input, textarea, select, a").forEach(e=>{e.closest('[data-drag-handle="true"]')||e.addEventListener("mousedown",e=>{e.stopPropagation()})})})}observeBlockChanges(){new MutationObserver(()=>{this.updateDraggableElements()}).observe(this.blocksContainer,{childList:!0,subtree:!1})}handleDragStart(e,t){e.target.closest("button, input, textarea, select")?e.preventDefault():(this.draggedElement=t,t.classList.add("admin-block-card--dragging"),e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/html",t.outerHTML),e.dataTransfer.setData("text/plain",t.dataset.blockId),e.dataTransfer.setDragImage(t,0,0),this.blocksContainer.classList.add("admin-block-editor__blocks--dragging"))}handleDragEnd(e,t){t.classList.remove("admin-block-card--dragging"),this.blocksContainer.classList.remove("admin-block-editor__blocks--dragging");this.blocksContainer.querySelectorAll(".admin-block-card").forEach(e=>{e.classList.remove("admin-block-card--drag-over"),e.classList.remove("admin-block-card--drag-over-before"),e.classList.remove("admin-block-card--drag-over-after")}),this.draggedElement=null,this.dragOverIndex=null}handleDragOver(e,t){if(this.draggedElement===t)return;e.preventDefault(),e.dataTransfer.dropEffect="move";const n=t.getBoundingClientRect(),i=e.clientY<n.top+n.height/2;this.blocksContainer.querySelectorAll(".admin-block-card").forEach(e=>{e.classList.remove("admin-block-card--drag-over"),e.classList.remove("admin-block-card--drag-over-before"),e.classList.remove("admin-block-card--drag-over-after")}),i?t.classList.add("admin-block-card--drag-over-before"):t.classList.add("admin-block-card--drag-over-after")}handleDragEnter(e,t){this.draggedElement!==t&&e.preventDefault()}handleDragLeave(e,t){t.contains(e.relatedTarget)||(t.classList.remove("admin-block-card--drag-over"),t.classList.remove("admin-block-card--drag-over-before"),t.classList.remove("admin-block-card--drag-over-after"))}handleDrop(e,t){if(e.preventDefault(),e.stopPropagation(),this.draggedElement===t||!this.draggedElement)return;const n=Array.from(this.blocksContainer.querySelectorAll(".admin-block-card")),i=n.indexOf(this.draggedElement),s=n.indexOf(t),o=t.getBoundingClientRect(),a=e.clientY<o.top+o.height/2;let r=s;r=a&&i>s?s:!a&&i<s?s+1:a&&i<s?s:s+1;const l=n.map(e=>e.dataset.blockId);l.splice(i,1),l.splice(r,0,this.draggedElement.dataset.blockId),this.reorderBlocks(l),this.handleDragEnd(e,t)}reorderBlocks(e){if(!this.componentId)return void console.error("BlockEditorDnD: No component ID found");const t=document.querySelector(`[data-live-component="${this.componentId}"]`);if(!t)return void console.error("BlockEditorDnD: LiveComponent element not found");if(window.liveComponentManager){const t=window.liveComponentManager.getComponent(this.componentId);if(t)return void t.executeAction("reorderBlocks",{blockIds:e})}const n=document.createElement("button");n.type="button",n.dataset.liveAction="reorderBlocks",n.dataset.liveComponent=this.componentId,n.style.display="none",n.dataset.paramBlockIds=JSON.stringify(e),t.appendChild(n),n.click(),setTimeout(()=>{n.remove()},100)}static initializeAll(){const e=document.querySelectorAll(".admin-block-editor"),t=[];return e.forEach(e=>{t.push(new Ai(e))}),t}}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{Ai.initializeAll()}):Ai.initializeAll(),document.addEventListener("livecomponent:loaded",()=>{Ai.initializeAll()});class Li{constructor(e,t){this.blockEditorElement=e,this.contentFormComponentId=t,this.syncDebounceTimer=null,this.SYNC_DEBOUNCE_MS=500,this.init()}init(){this.blockEditorElement.addEventListener("livecomponent:updated",e=>{this.handleBlockEditorUpdate(e)}),document.addEventListener("livecomponent:event",e=>{const t=e.detail;if(t&&t.component_id){const e=this.blockEditorElement.dataset.liveComponent;t.component_id===e&&t.event_name&&(t.event_name.includes("block:")||t.event_name.includes("blocks:"))&&this.scheduleSync()}})}handleBlockEditorUpdate(e){this.scheduleSync()}scheduleSync(){this.syncDebounceTimer&&clearTimeout(this.syncDebounceTimer),this.syncDebounceTimer=setTimeout(()=>{this.syncBlocks()},this.SYNC_DEBOUNCE_MS)}async syncBlocks(){var e,t;if(!this.contentFormComponentId)return void console.warn("BlockEditorSync: No content form component ID");if(!document.querySelector(`[data-live-component="${this.contentFormComponentId}"]`))return void console.warn("BlockEditorSync: ContentFormComponent not found");const n=null==(t=null==(e=window.LiveComponents)?void 0:e.getComponent)?void 0:t.call(e,this.contentFormComponentId);if(n)try{await n.action("syncBlocksFromBlockEditor")}catch(i){console.error("BlockEditorSync: Failed to sync blocks",i)}else console.warn("BlockEditorSync: LiveComponent instance not found")}static initializeAll(){const e=[];return document.querySelectorAll('[data-live-component^="admin-block-editor:"]').forEach(t=>{const n=t.closest('[data-live-component^="admin-content-form:"]');if(n){const i=n.dataset.liveComponent;e.push(new Li(t,i))}}),e}}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{Li.initializeAll()}):Li.initializeAll(),document.addEventListener("livecomponent:loaded",()=>{Li.initializeAll()});class Ii{constructor(e,t){this.blockEditorElement=e,this.blockEditorComponentId=t,this.init()}init(){document.addEventListener("livecomponent:event",e=>{const t=e.detail;if(t&&"asset:selected"===t.event_name){const n=e.target.closest('[data-live-component^="admin-asset-picker:"]');n&&this.handleAssetSelected(t,n)}}),this.blockEditorElement.addEventListener("click",e=>{const t=e.target.closest('[data-live-action="selectAsset"]');if(t){const e=t.dataset.assetId;if(e){const n=t.closest(".admin-asset-picker-wrapper");if(n){const t=n.querySelector("input[data-param-field-path]");if(t){const n=t.dataset.paramBlockId,i=t.dataset.paramFieldPath;n&&i&&this.selectAssetForBlock(n,i,e)}}}}})}handleAssetSelected(e,t){const n=t.closest(".admin-asset-picker-wrapper");if(!n)return;const i=n.querySelector("input[data-param-field-path]");if(!i)return;const s=i.dataset.paramBlockId,o=i.dataset.paramFieldPath,a=e.asset_id||e.selected_asset_id;s&&o&&a&&this.selectAssetForBlock(s,o,a)}async selectAssetForBlock(e,t,n){var i,s;const o=null==(s=null==(i=window.LiveComponents)?void 0:i.getComponent)?void 0:s.call(i,this.blockEditorComponentId);if(o)try{await o.action("selectAssetForBlock",{blockId:e,fieldPath:t,assetId:n})}catch(a){console.error("BlockEditorAssetPicker: Failed to select asset",a)}else console.warn("BlockEditorAssetPicker: LiveComponent instance not found")}static initializeAll(){const e=[];return document.querySelectorAll('[data-live-component^="admin-block-editor:"]').forEach(t=>{const n=t.dataset.liveComponent;n&&e.push(new Ii(t,n))}),e}}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{Ii.initializeAll()}):Ii.initializeAll(),document.addEventListener("livecomponent:loaded",()=>{Ii.initializeAll()});class Pi{constructor(e,t){this.metaDataFormElement=e,this.contentFormComponentId=t,this.syncDebounceTimer=null,this.SYNC_DEBOUNCE_MS=500,this.init()}init(){this.metaDataFormElement.addEventListener("livecomponent:updated",e=>{this.handleMetaDataFormUpdate(e)}),document.addEventListener("livecomponent:event",e=>{const t=e.detail;if(t&&t.component_id){const e=this.metaDataFormElement.dataset.liveComponent;t.component_id===e&&t.event_name&&t.event_name.includes("metadata:")&&this.scheduleSync()}})}handleMetaDataFormUpdate(e){this.scheduleSync()}scheduleSync(){this.syncDebounceTimer&&clearTimeout(this.syncDebounceTimer),this.syncDebounceTimer=setTimeout(()=>{this.syncMetaData()},this.SYNC_DEBOUNCE_MS)}async syncMetaData(){var e,t;if(!this.contentFormComponentId)return void console.warn("MetaDataFormSync: No content form component ID");if(!document.querySelector(`[data-live-component="${this.contentFormComponentId}"]`))return void console.warn("MetaDataFormSync: ContentFormComponent not found");const n=null==(t=null==(e=window.LiveComponents)?void 0:e.getComponent)?void 0:t.call(e,this.contentFormComponentId);if(n)try{await n.action("syncMetaDataFromForm")}catch(i){console.error("MetaDataFormSync: Failed to sync metadata",i)}else console.warn("MetaDataFormSync: LiveComponent instance not found")}static initializeAll(){const e=[];return document.querySelectorAll('[data-live-component^="admin-metadata-form:"]').forEach(t=>{const n=t.closest('[data-live-component^="admin-content-form:"]');if(n){const i=n.dataset.liveComponent;e.push(new Pi(t,i))}}),e}}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{Pi.initializeAll()}):Pi.initializeAll(),document.addEventListener("livecomponent:loaded",()=>{Pi.initializeAll()}),document.addEventListener("DOMContentLoaded",async()=>{try{console.log("🚀 Starting app initialization..."),await wi(),console.log("✅ App initialized successfully!");const e=Si.initializeAll();console.log(`💾 Form Auto-Save initialized for ${e.length} forms`),setTimeout(()=>{console.log("📊 Debug Info:"),console.log("- Forms found:",document.querySelectorAll("form").length),console.log("- Links found:",document.querySelectorAll('a[href^="/"]').length),console.log("- SPA Router:",window.spaRouter?"Active":"Missing"),console.log("- Enhanced forms:",document.querySelectorAll("form[data-auto-enhanced]").length),console.log("- CSRF protected forms:",document.querySelectorAll('input[name="_token"]').length)},500)}catch(e){console.error("❌ App initialization failed:",e),console.error("Stack trace:",e.stack)}});
|