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 r=`
`;o.innerHTML+=r,o.style.lineHeight="1.4",document.body.appendChild(o);const a=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
\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?a.trackTask(e,i):i()}catch(t){d.warn("[Frameloop] Fehler in Task:",t)}s&&a.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){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),a&&"function"==typeof a.log)try{a.log(o)}catch(r){}}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.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),r=Array.isArray(e)?e:[e];return r.forEach(e=>{e instanceof Element&&o.observe(e)}),this.observerInstances.set(s,o),this.activeObservers.set(s,{type:"intersection",elements:r,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.topn?"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 r=s*o,a=t.height*t.width;return a>0?r/a:0}getActiveObservers(){return Array.from(this.activeObservers.entries()).map(([e,t])=>({id:e,...t}))}}class u{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"),r=[];return s.ondataavailable=e=>{e.data.size>0&&r.push(e.data)},s.onstop=()=>{const e=new Blob(r,{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(r,{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,r=new Uint8Array(o);return{analyzer:s,bufferLength:o,dataArray:r,getFrequencyData:()=>(s.getByteFrequencyData(r),Array.from(r)),getTimeDomainData:()=>(s.getByteTimeDomainData(r),Array.from(r)),getAverageVolume:()=>(s.getByteFrequencyData(r),r.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 p{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"),r={key:e,value:t,timestamp:Date.now(),expiration:n?Date.now()+n:null},a=o.put(r);a.onsuccess=()=>{d.info(`[StorageManager] DB set: ${e}`),i(r)},a.onerror=()=>{d.error(`[StorageManager] DB set failed: ${e}`),s(a.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"),r={name:e,file:t,type:t.type,size:t.size,timestamp:Date.now(),metadata:n},a=o.add(r);a.onsuccess=()=>{d.info(`[StorageManager] File stored: ${e}`),i({id:a.result,...r})},a.onerror=()=>{s(a.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(r){if(o)return this.local.set(e,t,s);throw r}},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}}}),this.config=e,this.dbName=e.dbName||"AppDatabase",this.dbVersion=e.dbVersion||1,this.db=null,this.cache=null,this.channels=new Map,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},d.info("[StorageManager] Initialized with support:",this.support),this.initializeDB(),this.initializeCache()}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())}}}class m{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 g{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 r=o*i,a=this.animate(e,t,{...n,delay:r});s.push({element:e,animation:a})}),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,r=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 r.observe(i),{observer:r,disconnect:()=>r.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 f{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"),r=e=>{e.data.id===o&&(n.removeEventListener("message",r),e.data.error?s(new Error(e.data.error)):i(e.data.result))};n.addEventListener("message",r),n.postMessage({id:o,type:"execute",function:e.toString(),data:t}),setTimeout(()=>{n.removeEventListener("message",r),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 r=0;r{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{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 a=0;a{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 v{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 t0?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 y{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 r=this.executePermissionRequest(e,s);this.requestQueue.set(o,r);const a=await r;return this.requestQueue.delete(o),this.permissionCache.set(e,{name:e,state:a.state,timestamp:Date.now(),supported:!0}),a}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
\n
\n

\n ${this.getPermissionIcon(e)} ${this.getPermissionTitle(e)}\n

\n

\n ${t}\n

\n
\n \n \n
\n
\n
\n `,document.body.appendChild(i);const s=i.querySelector(".btn-skip"),o=i.querySelector(".btn-grant"),r=()=>document.body.removeChild(i);s.onclick=()=>{r(),n("skip")},o.onclick=()=>{r(),n("grant")},i.querySelector(".permission-dialog-backdrop").onclick=e=>{e.target===e.currentTarget&&(r(),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 b{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:r={}}=t;try{const t=s?this.base64ToArrayBuffer(s):crypto.getRandomValues(new Uint8Array(32)),a={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,...r}};o.length>0&&(a.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:a});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(a){return d.error("[BiometricAuthManager] Registration failed:",a),{success:!1,error:a.message,name:a.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 r=s&&this.support.conditionalUI?await navigator.credentials.get({publicKey:e,mediation:"conditional"}):await navigator.credentials.get({publicKey:e});if(!r)throw new Error("Authentication failed");const a=this.processCredential(r,"authentication"),l=this.credentials.get(a.id);l&&(l.lastUsed=Date.now(),l.counter=a.response.counter||0);const c=this.generateSessionId(),h={id:c,credentialId:a.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:a.id,userId:null==l?void 0:l.userId}),{success:!0,credential:a,session:h,info:l}}catch(r){return d.error("[BiometricAuthManager] Authentication failed:",r),{success:!1,error:r.message,name:r.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:r=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 r=document.querySelector(n);return r&&(r.style.display=e.hasCredentials?"block":"none",r.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!")):(r&&r(t),this.showError(t.error))}catch(e){r&&r({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!")):(r&&r(e),this.showError(e.error))}catch(e){r&&r({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?'
✅ Biometric authentication available
':'
🔐 Biometric authentication can be set up
':'
ℹ️ No biometric authenticators available
':'
⚠️ Biometric authentication not supported in this browser
',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;ie&&(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 w={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 h(e.observers||{}),this.media=new u(e.media||{}),this.storage=new p(e.storage||{}),this.device=new m(e.device||{}),this.animation=new g(e.animation||{}),this.worker=new f(e.worker||{}),this.performance=new v(e.performance||{}),this.permissions=new y(e.permissions||{}),this.biometric=new b(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"})},S=w.init.bind(w),C=Object.freeze(Object.defineProperty({__proto__:null,default:w,init:S},Symbol.toStringTag,{value:"Module"})),M=new Map,k={add(e,t,n,{module:i="global",options:s=!1}={}){e.addEventListener(t,n,s),M.has(i)||M.set(i,[]),M.get(i).push([e,t,n,s])},removeModule(e){const t=M.get(e);t&&(t.forEach(([e,t,n,i])=>{e.removeEventListener(t,n,i)}),M.delete(e))},clearAll(){for(const[e,t]of M.entries())t.forEach(([e,t,n,i])=>{e.removeEventListener(t,n,i)});M.clear()},debug(){console.table([...M.entries()].map(([e,t])=>({module:e,listeners:t.length})))}};function E(e,t,n,i=import.meta,s=!1){var o;const r="string"==typeof i?i:(null==(o=i.url)?void 0:o.split("/").slice(-2,-1)[0])||"unknown";return k.add(e,t,n,{module:r,options:s}),()=>{k.removeModule(r)}}class x{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(){E(window,"resize",()=>{this.resize()},"canvas-manager"),E(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 A={initParallax(e,t){const n=new x(e),i=this.createParallaxElements(e,t);let s=!1;const o=()=>{s||(requestAnimationFrame(()=>{this.renderParallax(n,i,t),s=!1}),s=!0)};E(window,"scroll",o,"scroll-parallax"),E(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{const n=s*t.speed*100,i=t.y-n;i>-t.size&&i{s||(requestAnimationFrame(()=>{this.renderScrollAnimation(n,i,t),s=!1}),s=!0)};E(window,"scroll",o,"scroll-animation"),E(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 r=(n.amplitude||50)*t,a=n.frequency||.02,l=t*Math.PI*2;for(let c=0;c<=s;c+=2){const e=o/2+Math.sin(c*a+l)*r;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(),r=n.barHeight||10,a=o/2-r/2;i.fillStyle=n.backgroundColor||"rgba(255, 255, 255, 0.2)",i.fillRect(0,a,s,r),i.fillStyle=n.color||"rgba(100, 150, 255, 0.8)",i.fillRect(0,a,s*t,r)},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 r=s/2,a=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=r+Math.cos(e)*n,o=a+Math.sin(e)*n;0===d?i.moveTo(s,o):i.lineTo(s,o)}i.closePath(),i.fill()}},I={init(e,t){const n=new x(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){E(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"),E(e,"mouseenter",()=>{n.mouse.isOver=!0},"interactive-effects"),E(e,"mouseleave",()=>{n.mouse.isOver=!1},"interactive-effects"),E(e,"click",e=>{const s=t.getMousePosition(e);this.addClickEffect(n,s.x,s.y,i)},"interactive-effects"),E(e,"touchstart",e=>{e.preventDefault();const s=e.touches[0],o=t.getMousePosition(s);this.addClickEffect(n,o.x,o.y,i)},"interactive-effects"),E(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"),E(e,"touchend",()=>{n.mouse.isOver=!1},"interactive-effects")},startAnimationLoop(e,t,n,i){const s=o=>{const r=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,r);break;case"magnetic":this.renderMagneticEffect(e,t,i)}this.updateEffects(t.effects,r),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),r=.8*(1-s);i.save(),i.globalAlpha=r,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,r=t.y/e.options.pixelRatio;i.globalAlpha=.8*s,0===n?i.moveTo(o,r):i.lineTo(o,r)}),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 r=s/2,a=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=r+50*Math.cos(e),n=a+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)}},T={init(e,t){const n=new x(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(),r=n.padding||40,a=s-2*r,l=o-2*r,c=a/t.length*.8,d=a/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:r,chartWidth:a,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:r,chartHeight:a,barWidth:l,barSpacing:c,maxValue:d}=s;t.forEach((e,t)=>{const s=r+t*(l+c),h=e.value/d*a*i,u=r+a-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,r+a+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(r,r),o.lineTo(r,r+a),o.stroke(),o.beginPath(),o.moveTo(r,r+a),o.lineTo(r+s.chartWidth,r+a),o.stroke())},createLineChart(e,t,n){const{ctx:i}=e,{width:s,height:o}=e.getSize(),r=n.padding||40,a=s-2*r,l=o-2*r,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:r,chartWidth:a,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:r,chartWidth:a,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&&ue+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:r,centerY:a,radius:l,total:c}),d<1&&requestAnimationFrame(p)};requestAnimationFrame(p)},renderPieChart(e,t,n,i,s){const{ctx:o}=e,{centerX:r,centerY:a,radius:l,total:c}=s;let d=-Math.PI/2;const h=d+2*Math.PI*i;for(let u=0;u=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(r,a),o.arc(r,a,l,d,s),o.closePath(),o.fill(),!1!==n.showLabels&&s===d+i)){const t=d+i/2,s=r+Math.cos(t)*l*.7,c=a+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 r=0;const a=n.animationDuration||1500;let l=null;const c=i=>{l||(l=i);const s=i-l;r=Math.min(s/a,1),e.clear(),this.renderProgressChart(e,t,n,r),r<1&&requestAnimationFrame(c)};requestAnimationFrame(c)},renderProgressChart(e,t,n,i){var s;const{ctx:o}=e,{width:r,height:a}=e.getSize(),l=r/2,c=a/2,d=Math.min(r,a)/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]}},L={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":I.init(e,i);break;case"scroll-parallax":A.initParallax(e,i);break;case"scroll-animation":A.initScrollAnimation(e,i);break;case"data-viz":T.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 x(e),i=t.particles||50,s=[];for(let o=0;o{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)}()}},$=L.init.bind(L),P=Object.freeze(Object.defineProperty({__proto__:null,default:L,init:$},Symbol.toStringTag,{value:"Module"}));let z="example-module",O=null,D=null;const _=Object.freeze(Object.defineProperty({__proto__:null,destroy:function(){d.info("[example-module] destroy"),O&&(window.removeEventListener("resize",O),O=null),c(z),D&&"function"==typeof D.cleanup&&D.cleanup(),D=null},init:function(e={},t=null){d.info("[example-module] init"),D=t,D&&(D.register("windowSize",{width:window.innerWidth,height:window.innerHeight}),D.register("scrollPosition",{x:0,y:0}),D.register("isVisible",!0)),O=()=>{const e={width:window.innerWidth,height:window.innerHeight};d.info("Fenstergröße geändert:",e),D&&D.set("windowSize",e)},window.addEventListener("resize",O),l(z,()=>{const e=window.scrollY,t=window.scrollX;if(D){const n=D.get("scrollPosition");n.x===t&&n.y===e||D.set("scrollPosition",{x:t,y:e})}},{autoStart:!0})}},Symbol.toStringTag,{value:"Module"}));class F{constructor(e){this.form=e,this.errors=new Map}static create(e){return new F(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.lengthparseInt(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&&oparseFloat(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 r=e.getAttribute("data-validate");if(r){const i=this.runCustomValidation(r,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 R{constructor(e){this.form=e,this.pristineValues=new Map,this.touchedFields=new Set,this.dirtyFields=new Set,this.init()}static create(e){return new R(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 B{constructor(e,t={}){this.form=e,this.options={validateOnSubmit:!0,validateOnBlur:!1,validateOnInput:!1,showInlineErrors:!0,preventSubmitOnError:!0,submitMethod:"POST",ajaxSubmit:!0,...t},this.validator=F.create(e),this.state=R.create(e),this.isSubmitting=!1,this.init()}static create(e,t={}){return new B(e,t)}init(){this.bindEvents(),this.setupErrorDisplay(),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))})}}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"),!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)}destroy(){this.form.removeAttribute("data-enhanced"),d.info("[FormHandler] Destroyed")}}const N={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=B.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")}},q=N.init.bind(N),U=N.initElement.bind(N),j=Object.freeze(Object.defineProperty({__proto__:null,FormHandler:B,FormHandlingModule:N,FormState:R,FormValidator:F,default:N,init:q,initElement:U},Symbol.toStringTag,{value:"Module"})),W={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 H(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 V(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 J;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 H{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 \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 \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 \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 \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 V{constructor(e,t){this.element=e,this.config=t,d.info("[ImageUploader] Uploader placeholder initialized")}destroy(){d.info("[ImageUploader] Uploader destroyed")}}class J{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 Q=W.init.bind(W),G=W.destroy.bind(W),K=Object.freeze(Object.defineProperty({__proto__:null,default:W,definition:{name:"image-manager",version:"1.0.0",dependencies:[],provides:["image-upload","image-gallery","image-modal"],priority:5},destroy:G,init:Q},Symbol.toStringTag,{value:"Module"}));let X,Y="inertia-scroll",Z=0,ee=window.scrollY,te=!1,ne=.9,ie=.2;function se(){te=!0,clearTimeout(X),X=setTimeout(()=>{te=!1},50)}const oe=Object.freeze(Object.defineProperty({__proto__:null,destroy:function(){window.removeEventListener("scroll",se),c(Y),Z=0,ee=window.scrollY,te=!1,clearTimeout(X);const e=document.documentElement;delete e.dataset.scrollState,delete e.dataset.scrollDirection,delete e.dataset.scrollSpeed},init:function(e={}){ne="number"==typeof e.damping?e.damping:.9,ie="number"==typeof e.minVelocity?contig.minVelocity:.1,window.addEventListener("scroll",se,{passive:!0}),l(Y,()=>{const e=document.documentElement,t=window.scrollY,n=t-ee,i=n>0?"down":n<0?"up":"none",s=Math.abs(n);!te&&Math.abs(Z)>ie?(window.scrollTo(0,t+Z),Z*=ne,e.dataset.scrollState="inertia"):te?(Z=n,ee=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 re{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
\n ${e}\n \n
\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 ae={modal:class extends re{constructor(e){super({...e,className:"modal"})}},lightbox:class extends re{constructor(e){super({...e,className:"lightbox"})}}},le={},ce={open(e,t={}){const n=ae[e];if(!n)return d.warn(`[UIManager] Unknown type: ${e}`),null;if("lightbox"===e){if(le.lightbox)return d.info("[UIManager] Reusing existing lightbox instance"),le.lightbox.updateContent(t.content||""),le.lightbox.open(),le.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 le.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){le[e]&&this.close(le[e])},isOpen(e){var t;return(null==(t=le[e])?void 0:t.isOpen())||!1},destroyAll(){Object.values(le).forEach(e=>{(null==e?void 0:e.destroy)&&e.destroy()}),Object.keys(le).forEach(e=>{delete le[e]})}};function de(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 \n `,d.info("[Lightbox] Opening responsive image (picture element):",n)}else o=`\n \n `,d.info("[Lightbox] Opening standalone image:",n);const r=ce.open("lightbox",{content:o});ce.isOpen("lightbox")&&r&&d.info("[Lightbox] Reused existing lightbox instance")}const he=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"),E(document,"click",de),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 ue=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{};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()}},pe={DISCONNECTED:"disconnected",CONNECTING:"connecting",CONNECTED:"connected",ERROR:"error"};class me{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{console.log("[SSE] Connection opened"),this.setState(pe.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(pe.ERROR),this.scheduleReconnect()}}disconnect(){this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.stopHeartbeatMonitoring(),this.clearReconnectTimer(),this.setState(pe.DISCONNECTED),this.connectionId=null}handleDisconnect(){this.setState(pe.ERROR),this.stopHeartbeatMonitoring(),this.options.autoReconnect&&this.reconnectionStrategy.shouldRetry()?this.scheduleReconnect():this.setState(pe.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===pe.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 fe=null;function ve(e=[]){return fe||(fe=new ge(e)),fe}function ye(e=[],t=!0){return fe=new ge(e),t&&fe.connect(),fe}const be={SseClient:ge,getGlobalSseClient:ve,initSse:ye,ConnectionState:pe},we=Object.freeze(Object.defineProperty({__proto__:null,SseClient:ge,default:be,getGlobalSseClient:ve,initSse:ye},Symbol.toStringTag,{value:"Module"}));class Se{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)})}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=await fetch(`/live-component/${e.componentId}/lazy-load`,{method:"GET",headers:{"X-Requested-With":"XMLHttpRequest",Accept:"application/json"}});if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);const n=await t.json();if(!n.success)throw new Error(n.error||"Failed to load component");e.element.innerHTML=n.html,e.element.setAttribute("data-live-component",e.componentId),e.element.removeAttribute("data-live-component-lazy"),n.csrf_token&&(e.element.dataset.csrfToken=n.csrf_token),n.state&&(e.element.dataset.state=JSON.stringify(n.state)),this.liveComponentManager.init(e.element),e.loaded=!0,e.loading=!1,this.observer.unobserve(e.element),console.log(`[LazyLoader] Loaded: ${e.componentId}`),e.element.dispatchEvent(new CustomEvent("livecomponent:lazy:loaded",{detail:{componentId:e.componentId}}))}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}}))}}showPlaceholder(e,t){e.innerHTML=`\n
\n
\n
${t}
\n
\n `}showLoadingIndicator(e){e.innerHTML='\n
\n
\n
Loading component...
\n
\n \n '}showError(e,t){e.innerHTML=`\n
\n
\n
Failed to load component
\n
\n ${t}\n
\n
\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 Ce{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 r=document.querySelector(`[data-live-component="${o}"]`);if(!r)return console.warn(`[NestedComponents] Parent element not found: ${o}`),!1;const a=new CustomEvent(`livecomponent:child:${t}`,{detail:{sourceId:e,eventName:t,payload:n,currentLevel:s},bubbles:!1,cancelable:!0});if(!r.dispatchEvent(a))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 Me{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 ke{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.size0&&!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 Ee{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 xe{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 ke({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 Ee(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 Me(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.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 r=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 r}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 Ae=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},r={id:this.generateOperationId(),componentId:e,metadata:i,expectedVersion:s,optimisticState:o,timestamp:Date.now(),status:"pending"};return this.addPendingOperation(e,r),console.log(`[OptimisticUI] Applied optimistic update for ${e}`,{version:`${s} → ${s+1}`,operationId:r.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 r=this.conflictHandlers.get(e);r&&r({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 Ie=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}}},Te="pending",Le="hashing",$e="uploading",Pe="complete",ze="error",Oe="initializing",De="initialized",_e="uploading",Fe="assembling",Re="complete",Be="aborted",Ne="error";class qe{constructor(e,t,n){this.index=e,this.size=t,this.status=Te,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=Te,this.uploadedBytes=0,this.error=null,this.xhr=null}abort(){this.xhr&&(this.xhr.abort(),this.xhr=null)}}class Ue{constructor(e,t){this.file=e,this.sessionId=null,this.totalChunks=0,this.chunkSize=t.chunkSize,this.chunks=[],this.status=Oe,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===Re}get isError(){return this.status===Ne}get isAborted(){return this.status===Be}get canResume(){return null!==this.sessionId&&!this.isComplete&&!this.isAborted}getChunk(e){return this.chunks[e]}getPendingChunks(){return this.chunks.filter(e=>e.status===Te||e.status===ze)}getUploadingChunks(){return this.chunks.filter(e=>e.status===$e)}}const je=new class{constructor(){this.components=new Map,this.eventHandlers=new Map,this.debounceTimers=new Map,this.domPatcher=ue,this.accessibilityManager=Ie,this.sseClients=new Map,this.componentChannels=new Map,this.lazyLoader=null,this.nestedHandler=null,this.devTools=null}enableDevTools(e){this.devTools=e,console.log("[LiveComponent] DevTools integration enabled")}logActionToDevTools(e,t,n,i,s,o,r=null){this.devTools&&this.devTools.logAction(e,t,n,i,s,o,r)}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 Se(this),this.lazyLoader.init(),console.log("[LiveComponent] Lazy loading system initialized"))}initNestedComponents(){this.nestedHandler?console.warn("[LiveComponent] Nested components already initialized"):(this.nestedHandler=new Ce(this),this.nestedHandler.init(),console.log("[LiveComponent] Nested components system initialized"))}init(e){const t=e.dataset.liveComponent;if(!t)return;const n={id:t,element:e,pollInterval:parseInt(e.dataset.pollInterval)||null,pollTimer:null,observer:null};this.components.set(t,n),this.setupActionHandlers(e),this.setupFileUploadHandlers(e),n.pollInterval&&this.startPolling(t),this.setupLifecycleObserver(e,t),this.setupSseConnection(e,t),this.setupAccessibility(t,e),console.log(`[LiveComponent] Initialized: ${t}`)}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){const n=e.dataset.sseChannel;if(!n)return;console.log(`[LiveComponent] Setting up SSE for ${t} on channel: ${n}`),this.componentChannels.set(t,n);let i=this.sseClients.get(n);i||(i=new ge([n],{autoReconnect:!0,heartbeatTimeout:45e3}),this.registerSseHandlers(i,n),i.connect(),this.sseClients.set(n,i),console.log(`[LiveComponent] Created SSE client for channel: ${n}`)),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 r=this.components.get(n);if(r)try{this.accessibilityManager.captureFocusState(n,r.element),s&&(r.element.innerHTML=s,this.setupActionHandlers(r.element),this.setupFileUploadHandlers(r.element)),i&&(r.element.dataset.state=JSON.stringify(i)),this.accessibilityManager.restoreFocus(n,r.element),this.accessibilityManager.announceUpdate(n,"full"),o&&Array.isArray(o)&&this.handleServerEvents(o),console.log(`[LiveComponent] SSE update applied to ${n}`)}catch(a){console.error(`[LiveComponent] Failed to apply SSE update for ${n}:`,a)}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}),r=`/live-component/${e}/destroy`,a=new Blob([o],{type:"application/json"});navigator.sendBeacon&&navigator.sendBeacon(r,a)?console.log(`[LiveComponent] onDestroy() called via sendBeacon: ${e}`):(await fetch(r,{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=>{if("FORM"===t.tagName)t.addEventListener("submit",async n=>{n.preventDefault();const i=e.dataset.liveComponent,s=t.dataset.liveAction,o={},r=new FormData(t);for(const[e,t]of r.entries())o[e]=t;const a=this.extractFragments(t);await this.executeAction(i,s,o,a)});else if("INPUT"===t.tagName||"TEXTAREA"===t.tagName||"SELECT"===t.tagName){const n="text"===t.type||"email"===t.type||"url"===t.type||"tel"===t.type||"TEXTAREA"===t.tagName?300:0,i=parseInt(t.dataset.liveDebounce)??n;t.addEventListener("input",async n=>{const s=e.dataset.liveComponent,o=t.dataset.liveAction,r=this.extractParams(t);"checkbox"===t.type?r[t.name||"value"]=t.checked?"yes":"no":(t.type,r[t.name||"value"]=t.value);const a=this.extractFragments(t);i>0?this.debouncedAction(s,o,r,i,a):await this.executeAction(s,o,r,a)}),"radio"!==t.type&&"checkbox"!==t.type||t.addEventListener("change",async n=>{const i=e.dataset.liveComponent,s=t.dataset.liveAction,o=this.extractParams(t);"checkbox"===t.type?o[t.name||"value"]=t.checked?"yes":"no":"radio"===t.type&&(o[t.name||"value"]=t.value),await this.executeAction(i,s,o)})}else t.addEventListener("click",async n=>{n.preventDefault();const i=e.dataset.liveComponent,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 r=this.extractFragments(t);await this.executeAction(i,s,o,r)})})}debouncedAction(e,t,n,i,s=null){const o=`${e}_${t}`;this.debounceTimers.has(o)&&clearTimeout(this.debounceTimers.get(o));const r=setTimeout(async()=>{await this.executeAction(e,t,n,s),this.debounceTimers.delete(o)},i);this.debounceTimers.set(o,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){var s;const o=this.components.get(e);if(!o)return void console.error(`[LiveComponent] Unknown component: ${e}`);let r=null;const a=performance.now();try{const c=o.element.dataset.state||"{}",d=JSON.parse(c),h=d.data||d;Ae.applyOptimisticUpdate(e,d,e=>({...e,data:{...e.data,_optimistic:!0}}),{action:t,params:n});r=null==(s=Ae.getPendingOperations(e)[0])?void 0:s.id;const u=o.element.dataset.csrfToken;if(!u)throw console.error(`[LiveComponent] Missing CSRF token for component: ${e}`),new Error("CSRF token is required for component actions");const p={method:t,params:n,state:h,_csrf_token:u};i&&Array.isArray(i)&&i.length>0&&(p.fragments=i);const m=await fetch(`/live-component/${e}`,{method:"POST",headers:{"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"},body:JSON.stringify(p)});if(!m.ok){const e=await m.text();throw console.error("[LiveComponent] Server error response:",e),new Error(`HTTP ${m.status}: ${m.statusText}`)}const g=await m.text();let f;console.log("[LiveComponent] Raw response:",g.substring(0,200));try{f=JSON.parse(g)}catch(l){throw console.error("[LiveComponent] JSON parse error:",l),console.error("[LiveComponent] Response text:",g),new Error(`Failed to parse JSON response: ${l.message}`)}const v=f.state||{},y=d.version||1,b=v.version||1;if(b!==y+1){if(console.warn(`[LiveComponent] Version conflict: expected ${y+1}, got ${b}`),r){const t=Ae.handleConflict(e,r,v,{expectedVersion:y+1,actualVersion:b});t.notification&&this.showConflictNotification(e,t.notification),f.state=t.state}}else r&&Ae.confirmOperation(e,r,v);f.fragments?this.updateFragments(o.element,f.fragments):f.html&&(o.element.innerHTML=f.html,this.setupActionHandlers(o.element)),f.state&&(o.element.dataset.state=JSON.stringify(f.state)),f.events&&f.events.length>0&&this.handleServerEvents(f.events),console.log(`[LiveComponent] Action executed: ${e}.${t}`,f);const w=performance.now();this.logActionToDevTools(e,t,n,a,w,!0)}catch(c){console.error("[LiveComponent] Action failed:",c);const i=performance.now();if(this.logActionToDevTools(e,t,n,a,i,!1,c.message),r){const t=Ae.getSnapshot(e);t&&(o.element.dataset.state=JSON.stringify(t),Ae.clearPendingOperations(e),Ae.clearSnapshot(e))}this.handleError(e,c)}}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"),i?this.dispatchToComponent(i,t,n):this.broadcast(t,n)})}dispatchToComponent(e,t,n){(this.eventHandlers.get(t)||[]).forEach(t=>{t.componentId===e&&t.callback(n)})}broadcast(e,t){(this.eventHandlers.get(e)||[]).forEach(e=>{e.callback(t)}),document.dispatchEvent(new CustomEvent(`livecomponent:${e}`,{detail: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
\n LiveComponent Error: ${t.message}\n
\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
\n
\n ${t.title}\n

${t.message}

\n
\n ${t.canRetry?`\n \n Retry\n \n `:""}\n
\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 Ae.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),r=new FormData;r.append("file",t),r.append("state",JSON.stringify(o)),r.append("params",JSON.stringify(n));const a=i.element.dataset.csrfToken;if(!a)throw console.error(`[LiveComponent] Missing CSRF token for upload: ${e}`),new Error("CSRF token is required for file uploads");r.append("_csrf_token",a),this.showUploadProgress(e,0);const l=await fetch(`/live-component/${e}/upload`,{method:"POST",headers:{"X-Requested-With":"XMLHttpRequest"},body:r});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&&(i.element.dataset.state=JSON.stringify(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.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&&(i.element.dataset.state=JSON.stringify(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=je,"loading"===document.readyState&&document.addEventListener("DOMContentLoaded",()=>{document.querySelectorAll("[data-live-component]").forEach(e=>{je.init(e)})});const We=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=ve([`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=De;break;case"uploading":s.status=_e;break;case"completed":s.status=Re;break;case"aborted":s.status=Be;break;case"error":s.status=Ne}this.onSSEProgress({sessionId:i,percent:e.percent,message:e.message,data:e.data})}}async upload(e,t){const n=new Ue(e,{chunkSize:this.chunkSize});this.activeSession=n;try{n.totalChunks=Math.ceil(e.size/this.chunkSize);for(let t=0;t0;){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=Le;const n=await this.readChunk(e.file,t),i=await this.hashChunk(n);return t.hash=i,t.status=$e,await this.uploadChunkData(e,t,n,i),t.status=Pe,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=ze,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),r=e.slice(s,o),a=new FileReader;a.onload=e=>n(e.target.result),a.onerror=e=>i(new Error("Failed to read chunk")),a.readAsArrayBuffer(r)})}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 r=new FormData;r.append("sessionId",e.sessionId),r.append("chunkIndex",t.index),r.append("chunkHash",i),r.append("chunk",new Blob([n]));const a=new XMLHttpRequest;t.xhr=a,a.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}))}),a.addEventListener("load",()=>{if(a.status>=200&&a.status<300)try{const e=JSON.parse(a.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 ${a.status}`))}),a.addEventListener("error",()=>{o(new Error("Network error during chunk upload"))}),a.addEventListener("abort",()=>{o(new Error("Chunk upload cancelled"))}),a.open("POST",`${this.apiBase}/chunk`),a.setRequestHeader("Accept","application/json"),a.setRequestHeader("User-Agent",navigator.userAgent),a.send(r)})}async completeUpload(e,t){e.status=Fe;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=Be,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 Ue(t,{chunkSize:this.chunkSize});s.sessionId=e,s.totalChunks=i.total_chunks,s.uploadedChunks=i.uploaded_chunks,s.status=_e;for(let o=0;osetTimeout(t,e))}destroy(){this.sessions.forEach(e=>{e.canResume&&e.chunks.forEach(e=>e.abort())}),this.sessions.clear(),this.activeSession=null}},ComponentFileUploader:xe,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
\n \x3c!-- Header --\x3e\n
\n

LiveComponent Playground

\n

Interactive development tool for testing LiveComponents

\n
\n\n \x3c!-- Main Layout --\x3e\n
\n \x3c!-- Sidebar: Component Selector --\x3e\n \n\n \x3c!-- Main Content --\x3e\n
\n \x3c!-- State Editor --\x3e\n
\n

Component State

\n
\n \n
\n \n \n \n
\n
\n
\n
\n\n \x3c!-- Live Preview --\x3e\n
\n

Live Preview

\n
\n
\n Select a component to preview\n
\n
\n
\n
\n\n \x3c!-- Action Tester --\x3e\n
\n

Actions

\n
\n
\n Select a component to test actions\n
\n
\n
\n\n \x3c!-- Code Generator --\x3e\n
\n

Template Code

\n
\n
Select a component to generate code
\n \n
\n
\n
\n
\n
\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
\n Failed to load components: ${e.message}\n
\n `}}renderComponentList(e){0!==e.length?this.componentList.innerHTML=e.map(e=>`\n
\n
${e.name}
\n
\n ${e.properties} props\n ${e.actions} actions\n ${e.has_cache?'cached':""}\n
\n
\n `).join(""):this.componentList.innerHTML='
No components found
'}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='✓ Valid JSON',await this.previewComponent()}catch(n){t.innerHTML=`✗ Invalid JSON: ${n.message}`}}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='✓ Formatted'}catch(e){this.container.querySelector("#state-validation").innerHTML='✗ Invalid JSON'}}async previewComponent(){if(this.selectedComponent){this.previewContainer.innerHTML='
Loading preview...
';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
\n Preview failed: ${t.error}\n
\n `}catch(e){this.previewContainer.innerHTML=`\n
\n Error: ${e.message}\n
\n `}}}renderActions(){if(!this.componentMetadata||!this.componentMetadata.actions)return void(this.actionTester.innerHTML='
No actions available
');const e=this.componentMetadata.actions.filter(e=>!["onMount","onUpdated","onDestroy"].includes(e.name));0!==e.length?(this.actionTester.innerHTML=e.map(e=>`\n
\n \n ${e.name}()\n \n ${e.parameters.length>0?`\n
\n ${e.parameters.map(e=>`\n \n `).join("")}\n
\n `:""}\n
\n `).join(""),this.actionTester.querySelectorAll("[data-action]").forEach(e=>{e.addEventListener("click",()=>{this.executeAction(e.dataset.action,e.closest(".playground__action"))})})):this.actionTester.innerHTML='
No actions available
'}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
\n
\n Render Time\n ${this.metrics.renderTime.toFixed(2)}ms\n
\n
\n State Size\n ${this.metrics.stateSize} bytes\n
\n
\n Actions Executed\n ${this.metrics.actionExecutions}\n
\n
\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
\n \x3c!-- Drop Zone --\x3e\n
\n
\n \n \n \n \n \n

${this.options.dropZoneText}

\n \n 0?`accept="${this.options.allowedMimeTypes.join(",")}"`:""}\n style="display: none;"\n />\n
\n
\n\n \x3c!-- File List --\x3e\n ${this.options.showFileList?`\n \n `:""}\n\n \x3c!-- Overall Progress (shown when uploading) --\x3e\n ${this.options.showProgress?'\n \n ':""}\n
\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 xe(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 r=this.files.get(e);if(r){const e=r.querySelector(".file-progress-fill"),n=r.querySelector(".file-progress-text");e&&(e.style.width=`${t}%`),n&&(n.textContent=`${t}%`)}const a=this.uploader.getStats();this.progressFill&&(this.progressFill.style.width=`${a.overallProgress}%`),this.progressText&&(this.progressText.textContent=`${a.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
\n ${this.options.showPreviews&&t.type.startsWith("image/")?`${t.name}`:this.getFileIconSvg(t.type)}\n
\n
\n
${this.truncateFileName(t.name,40)}
\n
\n ${this.formatBytes(t.size)}\n ${n.error||"Pending"}\n
\n ${this.options.showProgress?'\n \n ':""}\n ${n.error?`\n
${n.error}
\n `:""}\n
\n
\n \n
\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"),r=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&&r&&(r.textContent=n,r.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 \n \n \n \n '}destroy(){this.uploader.destroy(),this.container.innerHTML="",this.files.clear()}},LiveComponent:je,default:je,definition:{name:"livecomponent",version:"1.0.0",dependencies:[],provides:["LiveComponent"],priority:0},init:async function(e={},t={}){console.log("[LiveComponent] Module initializing..."),Ie.initialize(),je.initLazyLoading(),je.initNestedComponents();const n=document.querySelectorAll("[data-live-component]");console.log(`[LiveComponent] Found ${n.length} regular components to initialize`),n.forEach(e=>{je.init(e)});const i=document.querySelectorAll("[data-live-component-lazy]");if(console.log(`[LiveComponent] Found ${i.length} lazy components (will load on demand)`),je.nestedHandler){const e=je.nestedHandler.getStats();console.log(`[LiveComponent] Nested components: ${e.child_components} children across ${e.root_components} roots (max depth: ${e.max_nesting_depth})`)}const s=Ie.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:je,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")?je.init(e):n.forEach(e=>je.init(e)),je}},Symbol.toStringTag,{value:"Module"}));const He=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,r=document.querySelector(t);if(!r)return;function a(){s?r.classList.toggle("hidden",!o.classList.contains(i)):r.style.display=o.classList.contains(i)?"block":"none"}a(),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),a())})}},Symbol.toStringTag,{value:"Module"}));const Ve=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 Je{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 Qe=new Je;"undefined"!=typeof window&&(window.dependencyManager=Qe,window.depStatus=()=>Qe.getStatus());const Ge=Je.createDefinition("scroll-dependent","1.0.0").depends("example-module","1.0.0").depends("scrollfx","1.0.0",!0).provides("scroll-coordination").priority(10);let Ke=null,Xe=null;const Ye=Object.freeze(Object.defineProperty({__proto__:null,definition:Ge,destroy:function(){d.info("[scroll-dependent] destroy"),Ke&&Xe&&(Xe.unsubscribe(Ke),Ke=null),Xe&&"function"==typeof Xe.cleanup&&Xe.cleanup(),Xe=null},init:function(e={},t=null){d.info("[scroll-dependent] init"),Xe=t,Xe&&(Xe.register("isScrolling",!1),Xe.register("scrollDirection","none"),Ke=Xe.subscribe("example-module.scrollPosition",(e,t)=>{if(t.y!==e.y){const n=e.y>t.y?"down":"up";Xe.set("scrollDirection",n),Xe.set("isScrolling",!0),setTimeout(()=>{Xe&&Xe.set("isScrolling",!1)},150),d.info(`[scroll-dependent] Scroll ${n}: ${e.y}`)}}))}},Symbol.toStringTag,{value:"Module"}));const Ze=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",r=t.dataset.scrollType||"translate",a="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(a&&(t.matches(":hover")||t.matches(":active")))return;const h=(d+l)*s;switch(r){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"})),et={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 tt=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(),r=o.top0;r&&!n.active&&(n.active=!0,n.el.classList.add("active"),d.log(`➡️ ENTER step ${n.index}`),null==(i=et.onEnter)||i.call(et,n.index,n.el)),!r&&n.active&&(n.active=!1,n.el.classList.remove("active"),d.log(`⬅️ LEAVE step ${n.index}`),t.once||null==(s=et.onLeave)||s.call(et,n.index,n.el))})},{autoStart:!0})}},Symbol.toStringTag,{value:"Module"}));const nt=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 it{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{const i=new it({...e,element:t});nt.register(i),n.push(i)}),1===n.length?n[0]:n},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{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;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
\n
\n
\n
\n
\n
\n
\n
\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 at={enableTransitions:!0,transitionDuration:50},lt={enableTransitions:!0,transitionDuration:100},ct={enableTransitions:!1,transitionDuration:0};function dt(){if(window.matchMedia("(prefers-reduced-motion: reduce)").matches)return ct;const e=navigator.connection||navigator.mozConnection||navigator.webkitConnection;if(e){if("4g"===e.effectiveType)return at;if("3g"===e.effectiveType)return lt}/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);return lt}const ht={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,...lt,...dt()},...e};return this.router=rt.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")}},ut=ht.init.bind(ht),pt=Object.freeze(Object.defineProperty({__proto__:null,SPARouter:rt,SPARouterModule:ht,default:ht,init:ut},Symbol.toStringTag,{value:"Module"}));let mt="sticky-fade",gt=[],ft=window.scrollY,vt=new WeakMap,yt={direction:!1,reset:!1};const bt=Object.freeze(Object.defineProperty({__proto__:null,destroy:function(){c(mt),gt.forEach(e=>{e.style.opacity="",e.style.transform="",e.classList.remove("visible"),delete e.dataset.scrollDir}),gt=[],vt=new WeakMap},init:function(e={}){gt=Array.from(document.querySelectorAll("[data-sticky-fade]")),0!==gt.length&&(yt.direction=e.direction??!1,yt.reset=e.reset??!1,l(mt,()=>{const e=window.scrollY,t=e>ft?"down":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)`,yt.direction&&(e.dataset.scrollDir=t),yt.reset){const t=s>=1,n=vt.get(e)||!1;t&&!n?(e.classList.add("visible"),vt.set(e,!0)):!t&&n&&(e.classList.remove("visible"),vt.set(e,!1))}})},{autoStart:!0}))}},Symbol.toStringTag,{value:"Module"}));const wt=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((r,a)=>{const l=i+a*(o/n.length),c=i+(a+1)*(o/n.length),d=s>=l&&s{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"})),kt=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),Et={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}};const xt=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{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 At=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=At,window.stateSnapshot=()=>At.getSnapshot());const It=new Map;function Tt(){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=It.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 Lt(){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=It.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 $t(){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({"./api-manager/index.js":C,"./canvas-animations/index.js":P,"./example-module/index.js":_,"./form-handling/index.js":j,"./image-manager/index.js":K,"./inertia-scroll/index.js":oe,"./lightbox-trigger/index.js":he,"./livecomponent/index.js":We,"./noise/index.js":He,"./parallax/index.js":Ve,"./scroll-dependent/index.js":Ye,"./scroll-loop/index.js":Ze,"./scroll-timeline/index.js":tt,"./scrollfx/index.js":st,"./smooth-scroll/index.js":ot,"./spa-router/index.js":pt,"./sse/index.js":we,"./sticky-fade/index.js":bt,"./sticky-steps/index.js":wt,"./ui/index.js":St,"./webpush/index.js":Mt,"./wheel-boost/index.js":kt}),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),Qe.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),Qe.register(e)}else console.log(`⏭️ [Module] Skipping unused module: ${n}`)});const r=Qe.calculateInitializationOrder();console.log("🔍 [Modules] Phase 2 - Initialization Order:",r);for(const l of r){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=Et[l]||{};console.log(`🔍 [Module] Module ${l} object:`,n),console.log(`🔍 [Module] Config for ${l}:`,i);const r=Qe.checkDependencies(l);if(console.log(`🔍 [Module] Dependency check for ${l}:`,r),r.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}`),Qe.markInitializing(l);const e=At.createScope(l),t=xt.wrapModule(n,l);await t.init(i,e),Qe.markInitialized(l),It.set(l,{mod:t,config:i,state:e,original:n}),d.info(`✅ [Module] Initialized: ${l}`)}catch(a){d.error(`❌ [Module] Failed to initialize ${l}:`,a),It.set(l,{mod:null,config:i,error:a,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}: ${r.reason}`),It.set(l,{mod:null,config:i,error:new Error(r.reason),original:n})}o&&d.info("⚠️ [Module] No data-module usage detected, fallback to full init mode")}(),Tt(),Lt(),function(){const e=It.get("spa-router");if(e&&e.mod)try{e.mod.init({containerSelector:"main",enableTransitions:!0,transitionDuration:300}),window.initAutoFormHandling=Lt,window.initDataModuleElements=Tt,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`,r=document.createElement("video");r.autoplay=!0,r.loop=!0,r.muted=!0,r.playsInline=!0,r.poster=e.getAttribute("poster")||"",r.setAttribute("width",e.getAttribute("width")||"100%");const a=document.createElement("source");a.src=o,a.type="video/webm",r.appendChild(a),e.replaceWith(r)})}()}"undefined"!=typeof window&&(window.moduleHealth=function(){const e={total:It.size,active:0,failed:0,modules:{},errorBoundary:xt.getHealthStatus()};for(const[t,{mod:n,error:i}]of It.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=It);const Pt=class e{constructor(t={}){this.config={...e.DEFAULT_CONFIG,...t},this.intervalId=null,this.isActive=!1,this.retryCount=0,this.lastRefreshTime=null,this.isPageVisible=!document.hidden,this.log("CSRF Auto-Refresh initialized",this.config),this.setupEventListeners(),this.isPageVisible&&this.start()}setupEventListeners(){this.config.pauseWhenHidden&&document.addEventListener("visibilitychange",()=>{this.isPageVisible=!document.hidden,this.isPageVisible?(this.log("Page became visible, resuming CSRF refresh"),this.start()):(this.log("Page became hidden, pausing CSRF refresh"),this.stop())}),window.addEventListener("beforeunload",()=>{this.stop()})}start(){this.isActive?this.log("Auto-refresh already active"):(this.isActive=!0,this.intervalId=setInterval(()=>{this.refreshToken()},this.config.refreshInterval),this.log(`Auto-refresh started. Next refresh in ${this.config.refreshInterval/1e3/60} minutes`),this.config.enableVisualFeedback)}stop(){this.isActive&&(this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.isActive=!1,this.log("Auto-refresh stopped"))}async refreshToken(){if(this.isPageVisible||!this.config.pauseWhenHidden)try{this.log("Refreshing CSRF token...");const e=await fetch(`${this.config.apiEndpoint}?form_id=${encodeURIComponent(this.config.formId)}`,{method:"GET",headers:{Accept:"application/json","X-Requested-With":"XMLHttpRequest"}});if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);const t=await e.json();if(!t.success||!t.token)throw new Error(t.error||"Invalid response from server");this.updateTokenInForms(t.token),this.lastRefreshTime=new Date,this.retryCount=0,this.log("CSRF token refreshed successfully",{token:t.token.substring(0,8)+"...",formId:t.form_id,expiresIn:t.expires_in}),this.config.enableVisualFeedback}catch(e){this.handleRefreshError(e)}else this.log("Page not visible, skipping refresh")}updateTokenInForms(e){let t=0;document.querySelectorAll(this.config.tokenSelector).forEach(n=>{const i=n.closest("form");if(i){const s=i.querySelector(this.config.formIdSelector);s&&s.value===this.config.formId&&(n.value=e,t++)}});const n="livecomponent:"+this.config.formId.replace(/^livecomponent:/,"");return document.querySelectorAll("[data-live-component][data-csrf-token]").forEach(i=>{const s=i.dataset.liveComponent;"livecomponent:"+s!==n&&this.config.formId!==s||(i.dataset.csrfToken=e,t++,this.log(`Updated LiveComponent token: ${s}`))}),this.log(`Updated ${t} token(s) (forms + LiveComponents)`),0===t&&console.warn("CsrfAutoRefresh: No tokens found to update. Check your selectors and formId."),t}handleRefreshError(e){this.retryCount++,console.error("CSRF token refresh failed:",e),this.retryCount<=this.config.maxRetries?(this.log(`Retrying in ${this.config.retryDelay/1e3}s (attempt ${this.retryCount}/${this.config.maxRetries})`),setTimeout(()=>{this.refreshToken()},this.config.retryDelay),this.config.enableVisualFeedback):(this.log("Max retries reached, stopping auto-refresh"),this.stop(),this.config.enableVisualFeedback)}showStatusMessage(e,t="info"){let n=document.getElementById("csrf-status-message");n||(n=document.createElement("div"),n.id="csrf-status-message",n.style.cssText="\n position: fixed;\n top: 20px;\n right: 20px;\n padding: 12px 16px;\n border-radius: 6px;\n font-size: 14px;\n z-index: 10000;\n max-width: 300px;\n box-shadow: 0 4px 12px rgba(0,0,0,0.1);\n transition: opacity 0.3s ease;\n ",document.body.appendChild(n)),n.textContent=e,n.className=`csrf-status-${t}`;const i={info:"background: #e3f2fd; color: #1976d2; border-left: 4px solid #2196f3;",success:"background: #e8f5e8; color: #2e7d32; border-left: 4px solid #4caf50;",warning:"background: #fff3e0; color: #f57c00; border-left: 4px solid #ff9800;",error:"background: #ffebee; color: #d32f2f; border-left: 4px solid #f44336;"};n.style.cssText+=i[t]||i.info,n.style.opacity="1","error"!==t&&setTimeout(()=>{n&&(n.style.opacity="0",setTimeout(()=>{n&&n.parentNode&&n.parentNode.removeChild(n)},300))},"success"===t?3e3:5e3)}log(e,t=null){if(this.config.enableConsoleLogging){const n=(new Date).toLocaleTimeString();t?console.log(`[${n}] CsrfAutoRefresh: ${e}`,t):console.log(`[${n}] CsrfAutoRefresh: ${e}`)}}getStatus(){var e;return{isActive:this.isActive,formId:this.config.formId,lastRefreshTime:this.lastRefreshTime,retryCount:this.retryCount,isPageVisible:this.isPageVisible,nextRefreshIn:this.isActive?Math.max(0,this.config.refreshInterval-(Date.now()-((null==(e=this.lastRefreshTime)?void 0:e.getTime())||Date.now()))):null}}async manualRefresh(){this.log("Manual refresh triggered"),await this.refreshToken()}static initializeAll(){const t=new Set;document.querySelectorAll('input[name="_token"]').forEach(e=>{const n=e.closest("form");if(n){const e=n.querySelector('input[name="_form_id"]');e&&e.value&&t.add(e.value)}});document.querySelectorAll("[data-live-component][data-csrf-token]").forEach(e=>{const n=e.dataset.liveComponent;n&&t.add(n)});const n=[];return t.forEach(t=>{const i=new e({formId:t});n.push(i)}),console.log(`CsrfAutoRefresh: Initialized for ${n.length} forms/components:`,Array.from(t)),n}};t(Pt,"DEFAULT_CONFIG",{formId:"contact_form",refreshInterval:63e5,apiEndpoint:"/api/csrf/refresh",tokenSelector:'input[name="_token"]',formIdSelector:'input[name="_form_id"]',enableVisualFeedback:!1,enableConsoleLogging:!0,pauseWhenHidden:!0,maxRetries:3,retryDelay:5e3});let zt=Pt;"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{zt.initializeAll()}):zt.initializeAll();const Ot=class e{constructor(t={}){this.config={...e.DEFAULT_CONFIG,...t},this.form=null,this.storageKey=null,this.saveTimer=null,this.lastSaveTime=null,this.hasChanges=!1,this.isInitialized=!1,this.fieldValues=new Map,this.log("FormAutoSave initializing",this.config),this.initialize()}initialize(){this.form=document.querySelector(this.config.formSelector),this.form?(this.storageKey=this.config.storageKey||this.config.storagePrefix+this.generateFormId(),this.log("Form found, storage key:",this.storageKey),this.config.cleanupOnInit&&this.cleanupExpiredDrafts(),this.setupEventListeners(),this.storeInitialValues(),this.restoreDraft(),this.startAutoSave(),this.isInitialized=!0,this.log("FormAutoSave initialized successfully"),this.config.enableVisualFeedback&&this.showStatus("Auto-save enabled","info",3e3)):this.log("Form not found with selector:",this.config.formSelector)}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,"_")}setupEventListeners(){this.form.addEventListener("input",e=>{this.onFieldChange(e)}),this.form.addEventListener("change",e=>{this.onFieldChange(e)}),this.form.addEventListener("submit",()=>{this.onFormSubmit()}),window.addEventListener("beforeunload",()=>{this.hasChanges&&this.saveDraft()}),document.addEventListener("visibilitychange",()=>{document.hidden&&this.hasChanges&&this.saveDraft()})}storeInitialValues(){const e=this.getFormFields();e.forEach(e=>{const t=this.getFieldKey(e),n=this.getFieldValue(e);this.fieldValues.set(t,n)}),this.log(`Stored initial values for ${e.length} fields`)}onFieldChange(e){const t=e.target;if(this.isFieldExcluded(t))return;const n=this.getFieldKey(t),i=this.getFieldValue(t);i!==this.fieldValues.get(n)&&(this.fieldValues.set(n,i),this.hasChanges=!0,this.log(`Field changed: ${n} = "${i}"`),this.isImmediateField(t)&&this.saveDraft())}onFormSubmit(){this.log("Form submitted, clearing draft"),this.clearDraft(),this.stopAutoSave(),this.config.enableVisualFeedback&&this.showStatus("Form submitted, draft cleared","success",2e3)}startAutoSave(){this.saveTimer||(this.saveTimer=setInterval(()=>{this.hasChanges&&this.saveDraft()},this.config.saveInterval),this.log(`Auto-save started, interval: ${this.config.saveInterval}ms`))}stopAutoSave(){this.saveTimer&&(clearInterval(this.saveTimer),this.saveTimer=null,this.log("Auto-save stopped"))}saveDraft(){if(this.form&&this.hasChanges)try{const e=this.extractFormData(),t={data:e,timestamp:Date.now(),formId:this.generateFormId(),url:window.location.href,version:"1.0"};localStorage.setItem(this.storageKey,JSON.stringify(t)),this.lastSaveTime=new Date,this.hasChanges=!1,this.log("Draft saved",{fields:Object.keys(e).length,size:JSON.stringify(t).length+" chars"}),this.config.enableVisualFeedback&&this.showStatus("Draft saved","success",1500)}catch(e){console.error("Failed to save form draft:",e),this.config.enableVisualFeedback&&this.showStatus("Failed to save draft","error",3e3)}}restoreDraft(){try{const e=localStorage.getItem(this.storageKey);if(!e)return void this.log("No draft found");const t=JSON.parse(e);if(this.isDraftExpired(t))return this.log("Draft expired, removing"),void localStorage.removeItem(this.storageKey);if(t.url&&t.url!==window.location.href)return void this.log("Draft from different URL, skipping restore");this.restoreFormData(t.data);const n=this.formatDuration(Date.now()-t.timestamp);this.log(`Draft restored (age: ${n})`,t.data),this.config.enableVisualFeedback&&this.showStatus(`Draft restored from ${n} ago`,"info",4e3)}catch(e){console.error("Failed to restore draft:",e),localStorage.removeItem(this.storageKey)}}extractFormData(){const e=this.getFormFields(),t={};return e.forEach(e=>{if(!this.isFieldExcluded(e)){const n=this.getFieldKey(e),i=this.getFieldValue(e);null!=i&&""!==i&&(t[n]=i)}}),t}restoreFormData(e){let t=0;Object.entries(e).forEach(([e,n])=>{const i=this.findFieldByKey(e);i&&!this.isFieldExcluded(i)&&(this.setFieldValue(i,n),this.fieldValues.set(e,n),t++)}),this.log(`Restored ${t} field values`);return this.getFormFields().forEach(e=>{this.isFieldExcluded(e)||e.dispatchEvent(new Event("change",{bubbles:!0}))}),t}getFormFields(){return Array.from(this.form.querySelectorAll('input:not([type="submit"]):not([type="button"]):not([type="reset"]), textarea, select'))}isFieldExcluded(e){return this.config.excludeFields.some(t=>e.matches(t))}isImmediateField(e){return this.config.immediateFields.some(t=>e.matches(t))}getFieldKey(e){return e.name||e.id||`field_${e.type}_${Date.now()}`}getFieldValue(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}}setFieldValue(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}}findFieldByKey(e){return this.form.querySelector(`[name="${e}"], #${e}`)}isDraftExpired(e){return Date.now()-e.timestamp>this.config.retentionPeriod}clearDraft(){localStorage.removeItem(this.storageKey),this.hasChanges=!1,this.log("Draft cleared")}cleanupExpiredDrafts(){let e=0;const t=this.config.storagePrefix;for(let i=localStorage.length-1;i>=0;i--){const s=localStorage.key(i);if(s&&s.startsWith(t))try{const t=JSON.parse(localStorage.getItem(s));Date.now()-t.timestamp>this.config.maxDraftAge&&(localStorage.removeItem(s),e++)}catch(n){localStorage.removeItem(s),e++}}e>0&&this.log(`Cleaned up ${e} expired drafts`)}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`}showStatus(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,i.className=`autosave-status-${t}`;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)}log(e,t=null){if(this.config.enableConsoleLogging){const n=`[${(new Date).toLocaleTimeString()}] FormAutoSave`;t?console.log(`${n}: ${e}`,t):console.log(`${n}: ${e}`)}}getStatus(){return{isInitialized:this.isInitialized,formId:this.generateFormId(),storageKey:this.storageKey,hasChanges:this.hasChanges,lastSaveTime:this.lastSaveTime,fieldCount:this.fieldValues.size,draftExists:!!localStorage.getItem(this.storageKey)}}forceSave(){this.hasChanges=!0,this.saveDraft()}destroy(){this.stopAutoSave(),this.isInitialized=!1,this.log("FormAutoSave destroyed")}static initializeAll(){const t=document.querySelectorAll('form[data-autosave], form:has(input[name="_token"])'),n=[];return t.forEach((t,i)=>{var s;const o=t.id||t.getAttribute("data-form-id")||(null==(s=t.querySelector('input[name="_form_id"]'))?void 0:s.value)||`form_${i}`,r=new e({formSelector:`#${t.id||"form_"+i}`,storageKey:`form_draft_${o}`});t.id||(t.id=`form_${i}`),n.push(r)}),console.log(`FormAutoSave: Initialized for ${n.length} forms`),n}};t(Ot,"DEFAULT_CONFIG",{formSelector:"form[data-autosave]",saveInterval:3e4,retentionPeriod:864e5,storagePrefix:"form_draft_",enableVisualFeedback:!0,enableConsoleLogging:!0,excludeFields:['input[type="password"]','input[type="hidden"][name="_token"]','input[type="hidden"][name="_form_id"]','input[name*="password"]','input[name*="confirm"]','input[name*="honeypot"]','input[name="email_confirm"]','input[name="website_url"]','input[name="user_name"]','input[name="company_name"]'],immediateFields:["textarea",'input[type="email"]','input[type="text"]',"select"],maxDraftAge:6048e5,cleanupOnInit:!0});let Dt=Ot;document.addEventListener("DOMContentLoaded",async()=>{try{console.log("🚀 Starting app initialization..."),await $t(),console.log("✅ App initialized successfully!");const e=zt.initializeAll();console.log(`🔒 CSRF Auto-Refresh initialized for ${e.length} forms`);const t=Dt.initializeAll();console.log(`💾 Form Auto-Save initialized for ${t.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)}});