Files
michaelschiemer/public/assets/js/main-BxMMU_ri.js
Michael Schiemer 55a330b223 Enable Discovery debug logging for production troubleshooting
- Add DISCOVERY_LOG_LEVEL=debug
- Add DISCOVERY_SHOW_PROGRESS=true
- Temporary changes for debugging InitializerProcessor fixes on production
2025-08-11 20:13:26 +02:00

2 lines
147 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
var e=Object.defineProperty,t=(t,n,r)=>((t,n,r)=>n in t?e(t,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[n]=r)(t,"symbol"!=typeof n?n+"":n,r);const n=new Map;let r=!1,i=!1;performance.now();const a=document.createElement("div");a.style.position="fixed",a.style.bottom="0",a.style.left="0",a.style.font="12px monospace",a.style.color="#0f0",a.style.background="rgba(0,0,0,0.75)",a.style.padding="0.25rem 0.5rem",a.style.zIndex="9999",a.style.pointerEvents="none",a.style.display="none";const o=`<div style="width:${Math.min(0,100)}%;height:4px;background:#0f0;margin-top:4px;"></div>`;a.innerHTML+=o,a.style.lineHeight="1.4",document.body.appendChild(a);const s=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 r=Math.min(2*this.fps,100),i=this.logs.slice().reverse().join("\n");this.container.innerHTML=`\nFPS: ${this.fps} | Tasks: ${e.size}\n${n.join("\n")}\n<div style="width:${r}%;height:4px;background:#0f0;margin-top:4px;"></div>\n${i?"\nLogs:\n"+i:""}\n `}}trackTask(e,t){const n=performance.now();t();const r=performance.now()-n;this.taskTimings.set(e,r)}};function c(e,t,a={}){n.set(e,t),a.autoStart&&!r&&function(){if(r)return;function e(){for(const[e,r]of n)try{i?s.trackTask(e,r):r()}catch(t){d.warn("[Frameloop] Fehler in Task:",t)}i&&s.update(n),requestAnimationFrame(e)}r=!0,requestAnimationFrame(e)}()}function l(e){n.delete(e)}window.addEventListener("keydown",e=>{"§"===e.key&&(i=!i,a.style.display=i?"block":"none")});class d{static log(...e){this._write("log","[LOG]",e)}static warn(...e){this._write("warn","[WARN]",e)}static info(...e){this._write("info","[INFO]",e)}static error(...e){this._write("error","[ERROR]",e)}static _write(e,t,n){if(!this.enabled)return;const r=`${t} [${(new Date).toLocaleTimeString("de-DE")}] ${n.map(e=>{if(e instanceof Error)return`${e.name}: ${e.message}\n${e.stack||""}`;if("object"==typeof e&&null!==e)try{return JSON.stringify(e)}catch(t){return"[Circular Object]"}return e}).join(" ")}`;if("function"==typeof console[e]&&console[e](r),s&&"function"==typeof s.log)try{s.log(r)}catch(i){}}}t(d,"enabled",!0);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 r={root:null,rootMargin:"50px",threshold:[0,.1,.5,1],...n},i=this.generateId("intersection"),a=new IntersectionObserver((e,n)=>{const r=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(r,n)},r),o=Array.isArray(e)?e:[e];return o.forEach(e=>{e instanceof Element&&a.observe(e)}),this.observerInstances.set(i,a),this.activeObservers.set(i,{type:"intersection",elements:o,callback:t,options:r}),d.info(`[ObserverManager] IntersectionObserver created: ${i}`),{id:i,observer:a,unobserve:e=>a.unobserve(e),disconnect:()=>this.disconnect(i),updateThreshold:e=>this.updateIntersectionThreshold(i,e)}}resize(e,t,n={}){if(!("ResizeObserver"in window))return d.warn("[ObserverManager] ResizeObserver not supported"),this.createFallbackObserver("resize",e,t);const r=this.generateId("resize"),i=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)}),a=Array.isArray(e)?e:[e];return a.forEach(e=>{e instanceof Element&&i.observe(e)}),this.observerInstances.set(r,i),this.activeObservers.set(r,{type:"resize",elements:a,callback:t,options:n}),d.info(`[ObserverManager] ResizeObserver created: ${r}`),{id:r,observer:i,unobserve:e=>i.unobserve(e),disconnect:()=>this.disconnect(r)}}mutation(e,t,n={}){if(!("MutationObserver"in window))return d.warn("[ObserverManager] MutationObserver not supported"),null;const r={childList:!0,attributes:!0,subtree:!0,attributeOldValue:!0,characterDataOldValue:!0,...n},i=this.generateId("mutation"),a=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 a.observe(e,r),this.observerInstances.set(i,a),this.activeObservers.set(i,{type:"mutation",target:e,callback:t,options:r}),d.info(`[ObserverManager] MutationObserver created: ${i}`),{id:i,observer:a,disconnect:()=>this.disconnect(i),takeRecords:()=>a.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},r=this.generateId("performance"),i=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 i.observe(n),this.observerInstances.set(r,i),this.activeObservers.set(r,{type:"performance",callback:e,options:n}),d.info(`[ObserverManager] PerformanceObserver created: ${r}`),{id:r,observer:i,disconnect:()=>this.disconnect(r),takeRecords:()=>i.takeRecords()}}lazyLoad(e="img[data-src], iframe[data-src]",t={}){const n=document.querySelectorAll(e);return this.intersection(n,e=>{e.forEach(e=>{if(e.isIntersecting){const t=e.element;t.dataset.src&&(t.src=t.dataset.src,delete t.dataset.src),t.dataset.srcset&&(t.srcset=t.dataset.srcset,delete t.dataset.srcset),t.classList.add("loaded"),e.observer.unobserve(t),d.info("[ObserverManager] Lazy loaded:",t.src)}})},{rootMargin:"100px",...t})}scrollTrigger(e,t,n={}){return this.intersection(e,e=>{e.forEach(e=>{const n={element:e.element,progress:e.intersectionRatio,isVisible:e.isIntersecting,direction:e.direction,position:e.position};t(n)})},{threshold:this.createThresholdArray(n.steps||10),...n})}viewport(e,t={}){const n=document.createElement("div");return n.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n pointer-events: none;\n visibility: hidden;\n ",document.body.appendChild(n),this.resize([n],t=>{const n=t[0];e({width:n.dimensions.width,height:n.dimensions.height,aspectRatio:n.dimensions.aspectRatio,orientation:n.dimensions.width>n.dimensions.height?"landscape":"portrait",breakpoint:n.breakpoint})},t)}generateId(e){return`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}disconnect(e){const t=this.observerInstances.get(e);t&&(t.disconnect(),this.observerInstances.delete(e),this.activeObservers.delete(e),d.info(`[ObserverManager] Observer disconnected: ${e}`))}disconnectAll(){this.observerInstances.forEach((e,t)=>{e.disconnect()}),this.observerInstances.clear(),this.activeObservers.clear(),d.info("[ObserverManager] All observers disconnected")}calculateVisibility(e){if(!e.isIntersecting)return 0;const t=e.intersectionRect.width*e.intersectionRect.height,n=e.boundingClientRect.width*e.boundingClientRect.height;return n>0?Math.round(t/n*100):0}getScrollDirection(e){return e.intersectionRatio>.5?"down":"up"}getElementPosition(e){const t=e.boundingClientRect,n=window.innerHeight;return t.top<0&&t.bottom>0?"entering-top":t.top<n&&t.bottom>n?"entering-bottom":t.top>=0&&t.bottom<=n?"visible":"hidden"}calculateDeltaSize(e){return{width:0,height:0}}detectBreakpoint(e){return e<576?"xs":e<768?"sm":e<992?"md":e<1200?"lg":"xl"}summarizeMutation(e){return`${e.type} on ${e.target.tagName}`}assessMutationImpact(e){return"childList"===e.type?e.addedNodes.length+e.removedNodes.length>5?"high":"low":"medium"}enhancePerformanceEntry(e){const t={raw:e};switch(e.entryType){case"navigation":t.loadTime=e.loadEventEnd-e.navigationStart,t.domContentLoaded=e.domContentLoadedEventEnd-e.navigationStart;break;case"paint":t.paintType=e.name;break;case"largest-contentful-paint":t.element=e.element,t.url=e.url}return t}createThresholdArray(e){const t=[];for(let n=0;n<=e;n++)t.push(n/e);return t}createFallbackObserver(e,t,n){d.warn(`[ObserverManager] Creating fallback for ${e}Observer`);const r=this.generateId(`fallback_${e}`);let i;if("intersection"===e)i=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:r,disconnect:()=>{i&&clearInterval(i)}}}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,r=window.innerWidth,i=Math.min(t.bottom,n)-Math.max(t.top,0),a=Math.min(t.right,r)-Math.max(t.left,0);if(i<=0||a<=0)return 0;const o=i*a,s=t.height*t.width;return s>0?o/s: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},r=this.getSupportedMimeType(["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"])||n.mimeType,i=new MediaRecorder(e,{...n,mimeType:r}),a=this.generateId("recording"),o=[];return i.ondataavailable=e=>{e.data.size>0&&o.push(e.data)},i.onstop=()=>{const e=new Blob(o,{type:r});this.onRecordingComplete(a,e)},i.start(),d.info(`[MediaManager] Recording started: ${a}`),{id:a,recorder:i,stop:()=>(i.stop(),new Promise(e=>{i.onstop=()=>{const t=new Blob(o,{type:r});e({blob:t,url:URL.createObjectURL(t),size:t.size,type:t.type,download:(e=`recording-${Date.now()}.webm`)=>{this.downloadBlob(t,e)}})}})),pause:()=>i.pause(),resume:()=>i.resume(),get state(){return i.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 r=n.createMediaStreamSource(e),i=n.createAnalyser();i.fftSize=t.fftSize||256,i.smoothingTimeConstant=t.smoothing||.8,r.connect(i);const a=i.frequencyBinCount,o=new Uint8Array(a);return{analyzer:i,bufferLength:a,dataArray:o,getFrequencyData:()=>(i.getByteFrequencyData(o),Array.from(o)),getTimeDomainData:()=>(i.getByteTimeDomainData(o),Array.from(o)),getAverageVolume:()=>(i.getByteFrequencyData(o),o.reduce((e,t)=>e+t,0)/a)}}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),r=this.generateId("rtc");this.activeConnections.set(r,n);const i={id:r,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(r)},get connectionState(){return n.connectionState},get iceConnectionState(){return n.iceConnectionState}};return d.info(`[MediaManager] Peer connection created: ${r}`),i}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),r=t.createAnalyser();n.connect(r);const i=new Uint8Array(r.frequencyBinCount);return r.getByteFrequencyData(i),i.reduce((e,t)=>e+t,0)/i.length}getSupportedMimeType(e){return e.find(e=>MediaRecorder.isTypeSupported(e))}downloadBlob(e,t){const n=URL.createObjectURL(e),r=document.createElement("a");r.href=n,r.download=t,document.body.appendChild(r),r.click(),document.body.removeChild(r),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 r={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:r[t]||t,apply:e=>{e.style.filter=r[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 m{constructor(e={}){t(this,"db",{set:async(e,t,n=null)=>new Promise((r,i)=>{if(!this.db)return void i(new Error("IndexedDB not available"));const a=this.db.transaction(["keyValue"],"readwrite").objectStore("keyValue"),o={key:e,value:t,timestamp:Date.now(),expiration:n?Date.now()+n:null},s=a.put(o);s.onsuccess=()=>{d.info(`[StorageManager] DB set: ${e}`),r(o)},s.onerror=()=>{d.error(`[StorageManager] DB set failed: ${e}`),i(s.error)}}),get:async e=>new Promise((t,n)=>{if(!this.db)return void n(new Error("IndexedDB not available"));const r=this.db.transaction(["keyValue"],"readonly").objectStore("keyValue").get(e);r.onsuccess=()=>{const n=r.result;if(n)return n.expiration&&Date.now()>n.expiration?(this.db.delete(e),void t(null)):void t(n.value);t(null)},r.onerror=()=>{d.error(`[StorageManager] DB get failed: ${e}`),n(r.error)}}),delete:async e=>new Promise((t,n)=>{if(!this.db)return void n(new Error("IndexedDB not available"));const r=this.db.transaction(["keyValue"],"readwrite").objectStore("keyValue").delete(e);r.onsuccess=()=>{d.info(`[StorageManager] DB deleted: ${e}`),t(!0)},r.onerror=()=>{n(r.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((r,i)=>{if(!this.db)return void i(new Error("IndexedDB not available"));const a=this.db.transaction(["files"],"readwrite").objectStore("files"),o={name:e,file:t,type:t.type,size:t.size,timestamp:Date.now(),metadata:n},s=a.add(o);s.onsuccess=()=>{d.info(`[StorageManager] File stored: ${e}`),r({id:s.result,...o})},s.onerror=()=>{i(s.error)}}),getFile:async e=>new Promise((t,n)=>{if(!this.db)return void n(new Error("IndexedDB not available"));const r=this.db.transaction(["files"],"readonly").objectStore("files").get(e);r.onsuccess=()=>{t(r.result)},r.onerror=()=>{n(r.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 r={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,r),d.info(`[StorageManager] Channel created: ${e}`),r},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 r=await t(n);return d.info(`[StorageManager] Lock released: ${e}`),r})}catch(r){throw d.error(`[StorageManager] Lock failed: ${e}`,r),r}},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 r={value:t,timestamp:Date.now(),expiration:n?Date.now()+n:null};return localStorage.setItem(e,JSON.stringify(r)),!0}catch(r){return d.error("[StorageManager] localStorage set failed:",r),!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:r="indexedDB",expiration:i=null,fallback:a=!0}=n;try{if("indexedDB"===r&&this.db)return await this.db.set(e,t,i);if(a)return this.local.set(e,t,i)}catch(o){if(a)return this.local.set(e,t,i);throw o}},get:async(e,t={})=>{const{storage:n="indexedDB",fallback:r=!0}=t;try{if("indexedDB"===n&&this.db)return await this.db.get(e);if(r)return this.local.get(e)}catch(i){if(r)return this.local.get(e);throw i}},delete:async(e,t={})=>{const{storage:n="indexedDB",fallback:r=!0}=t;try{"indexedDB"===n&&this.db&&await this.db.delete(e),r&&this.local.delete(e)}catch(i){throw r&&this.local.delete(e),i}}}),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),r=JSON.parse(n);r.expiration&&Date.now()>r.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 g{constructor(e={}){t(this,"geolocation",{getCurrent:(e={})=>new Promise((t,n)=>{if(!this.support.geolocation)return void n(new Error("Geolocation not supported"));const r={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)},r)}),watch:(e,t={})=>{if(!this.support.geolocation)throw new Error("Geolocation not supported");const n={enableHighAccuracy:!0,timeout:3e4,maximumAge:1e4,...t},r=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_${r}`,{type:"geolocation",id:r,stop:()=>{navigator.geolocation.clearWatch(r),this.activeWatchers.delete(`geo_${r}`)}}),d.info("[DeviceManager] Location watch started:",r),{id:r,stop:()=>{navigator.geolocation.clearWatch(r),this.activeWatchers.delete(`geo_${r}`),d.info("[DeviceManager] Location watch stopped:",r)}}},distance:(e,t)=>{const n=this.toRadians(t.latitude-e.latitude),r=this.toRadians(t.longitude-e.longitude),i=Math.sin(n/2)*Math.sin(n/2)+Math.cos(this.toRadians(e.latitude))*Math.cos(this.toRadians(t.latitude))*Math.sin(r/2)*Math.sin(r/2),a=6371*(2*Math.atan2(Math.sqrt(i),Math.sqrt(1-i)));return{kilometers:a,miles:.621371*a,meters:1e3*a}}}),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 r=this.generateId("motion");return this.activeWatchers.set(r,{type:"motion",handler:n,stop:()=>{window.removeEventListener("devicemotion",n),this.activeWatchers.delete(r)}}),d.info("[DeviceManager] Motion detection started"),{id:r,stop:()=>{window.removeEventListener("devicemotion",n),this.activeWatchers.delete(r),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 r=this.generateId("orientation");return this.activeWatchers.set(r,{type:"orientation",handler:n,stop:()=>{window.removeEventListener("deviceorientation",n),this.activeWatchers.delete(r)}}),d.info("[DeviceManager] Orientation detection started"),{id:r,stop:()=>{window.removeEventListener("deviceorientation",n),this.activeWatchers.delete(r),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(r=>{const i=()=>{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:r};e(n)};t.addEventListener(r,i),n.push({event:r,handler:i})});const r=this.generateId("battery");return this.activeWatchers.set(r,{type:"battery",battery:t,handlers:n,stop:()=>{n.forEach(({event:e,handler:n})=>{t.removeEventListener(e,n)}),this.activeWatchers.delete(r)}}),d.info("[DeviceManager] Battery watch started"),{id:r,stop:()=>{n.forEach(({event:e,handler:n})=>{t.removeEventListener(e,n)}),this.activeWatchers.delete(r),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 r=this.generateId("network");return this.activeWatchers.set(r,{type:"network",connection:t,handler:n,stop:()=>{t.removeEventListener("change",n),this.activeWatchers.delete(r)}}),d.info("[DeviceManager] Network watch started"),{id:r,stop:()=>{t.removeEventListener("change",n),this.activeWatchers.delete(r),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,r=e.z||0;return Math.sqrt(t*t+n*n+r*r)}detectShake(e){if(!e)return!1;const t=this.sensorData.get("shakeThreshold"),n=Math.abs(e.x||0),r=Math.abs(e.y||0),i=Math.abs(e.z||0);return n>t||r>t||i>t}getDeviceOrientation(e){const t=e.accelerationIncludingGravity;if(!t)return"unknown";const n=t.x||0,r=t.y||0,i=t.z||0;return Math.abs(n)>Math.abs(r)&&Math.abs(n)>Math.abs(i)?n>0?"landscape-right":"landscape-left":Math.abs(r)>Math.abs(i)?r>0?"portrait-upside-down":"portrait":i>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:r}=e,i=Math.abs(n)>10||Math.abs(r)>10;return{isRotating:i,intensity:i?Math.max(Math.abs(n),Math.abs(r)):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 p{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 r={duration:this.defaultDuration,easing:this.defaultEasing,fill:"forwards",...n},i=this.generateId();if(this.supported){const n=e.animate(t,r),a=this.enhanceAnimation(n,i,{element:e,keyframes:t,options:r});return this.activeAnimations.set(i,a),n.addEventListener("finish",()=>{this.activeAnimations.delete(i)}),d.info(`[AnimationManager] Animation started: ${i}`),a}return this.fallbackAnimate(e,t,r,i)}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 r=parseFloat(n.replace("%",""))/100;t.push({...e[n],offset:r})}),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"),r=[];e.forEach(({element:e,keyframes:n,animationOptions:i={}})=>{const a=this.animate(e,n,{...i,...t});a&&a.finished&&r.push(a.finished)});const i={id:n,finished:Promise.all(r),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,i),i}stagger(e,t,n={}){const r=n.staggerDelay||100,i=[];return e.forEach((e,a)=>{const o=a*r,s=this.animate(e,t,{...n,delay:o});i.push({element:e,animation:s})}),this.group(i.map(({element:e,animation:n})=>({element:e,keyframes:t,animation:n})))}timeline(e){const t=this.generateId("timeline");let n=0;const r=[];return e.forEach(e=>{var t;const i=void 0!==e.at?e.at:n,a=this.animate(e.element,e.keyframes,{...e.options,delay:i});r.push(a),void 0===e.at&&(n+=(null==(t=e.options)?void 0:t.duration)||this.defaultDuration)}),{id:t,animations:r,finished:Promise.all(r.map(e=>e.finished)),play:()=>r.forEach(e=>e.play()),pause:()=>r.forEach(e=>e.pause()),reverse:()=>r.forEach(e=>e.reverse()),cancel:()=>r.forEach(e=>e.cancel())}}onScroll(e,t,n={}){const r=n.trigger||e,i=n.start||0,a=n.end||1,o=new IntersectionObserver(r=>{r.forEach(r=>{if(r.isIntersecting){Math.min(Math.max((r.intersectionRatio-i)/(a-i),0),1)>=0&&this.animate(e,t,{...n,duration:n.duration||this.defaultDuration})}})},{threshold:this.createThresholdArray(20)});return o.observe(r),{observer:o,disconnect:()=>o.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,r){d.info("[AnimationManager] Using CSS fallback animation");const i=t[t.length-1];return e.style.transition=`all ${n.duration}ms ${n.easing}`,Object.assign(e.style,i),{id:r,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 r=this.generateId("worker");try{if("string"==typeof e)n=new Worker(e,t);else if("function"==typeof e){const r=this.createWorkerBlob(e);n=new Worker(URL.createObjectURL(r),t)}else{if(!(e instanceof Blob))throw new Error("Invalid script type");n=new Worker(URL.createObjectURL(e),t)}const i={id:r,worker:n,send:(e,t=null)=>{t?n.postMessage(e,t):n.postMessage(e),d.info(`[WorkerManager] Message sent to worker: ${r}`)},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(r),d.info(`[WorkerManager] Worker terminated: ${r}`)},execute:(e,t=null)=>new Promise((r,i)=>{const a=this.generateId("msg"),o=e=>{e.data.id===a&&(n.removeEventListener("message",o),e.data.error?i(new Error(e.data.error)):r(e.data.result))};n.addEventListener("message",o),n.postMessage({id:a,type:"execute",function:e.toString(),data:t}),setTimeout(()=>{n.removeEventListener("message",o),i(new Error("Worker execution timeout"))},3e4)})};return this.activeWorkers.set(r,i),d.info(`[WorkerManager] Web Worker created: ${r}`),i}catch(i){throw d.error("[WorkerManager] Worker creation failed:",i),i}},createPool:(e,t=navigator.hardwareConcurrency||4,n={})=>{const r=[];for(let o=0;o<t;o++)r.push(this.web.create(e,n));let i=0;const a={workers:r,execute:async(e,t=null)=>{const n=r[i];return i=(i+1)%r.length,n.execute(e,t)},broadcast:e=>{r.forEach(t=>{t.send(e)})},terminate:()=>{r.forEach(e=>{e.terminate()}),r.length=0,d.info("[WorkerManager] Worker pool terminated")}};return d.info(`[WorkerManager] Worker pool created with ${t} workers`),a},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),r=n.port,i=this.generateId("shared");r.start();const a={id:i,worker:n,port:r,send:(e,t=null)=>{t?r.postMessage(e,t):r.postMessage(e)},onMessage:e=>{r.addEventListener("message",t=>{e(t.data,t)})},onError:e=>{n.addEventListener("error",e),r.addEventListener("messageerror",e)},close:()=>{r.close(),this.activeWorkers.delete(i),d.info(`[WorkerManager] Shared Worker closed: ${i}`)}};return this.activeWorkers.set(i,a),d.info(`[WorkerManager] Shared Worker created: ${i}`),a}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(),r=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 ",i=this.web.create(r);return i.send({type:"init",canvas:n},[n]),{worker:i,draw:e=>{i.send({type:"draw",data:{operations:e}})},send:e=>i.send(e),onMessage:e=>i.onMessage(e),terminate:()=>i.terminate()}}catch(n){throw d.error("[WorkerManager] Offscreen Canvas creation failed:",n),n}}}),t(this,"utils",{benchmark:async(e,t,n=1e3)=>{const r=this.web.create(()=>{self.addEventListener("message",e=>{const{id:t,function:n,data:r,iterations:i}=e.data;try{const e=new Function("return "+n)(),a=performance.now();for(let t=0;t<i;t++)e(r);const o=performance.now()-a,s=o/i;self.postMessage({id:t,result:{totalTime:o,avgTime:s,iterations:i,opsPerSecond:1e3/s}})}catch(a){self.postMessage({id:t,error:a.message})}})}),i=await r.execute(e,t,n);return r.terminate(),i},parallelMap:async(e,t,n=null)=>{const r=n||Math.ceil(e.length/(navigator.hardwareConcurrency||4)),i=this.web.createPool(()=>{self.addEventListener("message",e=>{const{id:t,data:{chunk:n,function:r}}=e.data;try{const e=new Function("return "+r)(),i=n.map(e);self.postMessage({id:t,result:i})}catch(i){self.postMessage({id:t,error:i.message})}})}),a=[];for(let s=0;s<e.length;s+=r){const n=e.slice(s,s+r);a.push(i.execute(t,n))}const o=await Promise.all(a);return i.terminate(),o.flat()}}),this.config=e,this.activeWorkers=new Map,this.messageHandlers=new Map,this.workerScripts=new Map,this.support={webWorkers:"Worker"in window,serviceWorker:"serviceWorker"in navigator,sharedWorker:"SharedWorker"in window,offscreenCanvas:"OffscreenCanvas"in window},d.info("[WorkerManager] Initialized with support:",this.support)}createWorkerBlob(e){const t=`\n (function() {\n const workerFunction = ${e.toString()};\n \n if (typeof workerFunction === 'function') {\n // If function expects to be called immediately\n if (workerFunction.length === 0) {\n workerFunction();\n }\n }\n \n // Standard worker message handling\n self.addEventListener('message', function(e) {\n if (e.data.type === 'execute' && e.data.function) {\n try {\n const fn = new Function('return ' + e.data.function)();\n const result = fn(e.data.data);\n self.postMessage({ \n id: e.data.id, \n result \n });\n } catch (error) {\n self.postMessage({ \n id: e.data.id, \n error: error.message \n });\n }\n }\n });\n })();\n `;return new Blob([t],{type:"application/javascript"})}generateId(e="worker"){return`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}terminateAll(){this.activeWorkers.forEach(e=>{e.terminate?e.terminate():e.close&&e.close()}),this.activeWorkers.clear(),d.info("[WorkerManager] All workers terminated")}getStats(){const e=Array.from(this.activeWorkers.values());return{total:e.length,byType:e.reduce((e,t)=>{const n=t.id.split("_")[0];return e[n]=(e[n]||0)+1,e},{}),support:this.support,hardwareConcurrency:navigator.hardwareConcurrency||"unknown"}}}class v{constructor(e={}){var n,r,i;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,r={})=>{if(!this.support.userTiming)return d.warn("[PerformanceManager] User Timing not supported"),null;try{performance.measure(e,t,n,r);const i=performance.getEntriesByName(e,"measure")[0],a={name:e,startTime:i.startTime,duration:i.duration,startMark:t,endMark:n,options:r};return this.measures.set(e,a),d.info(`[PerformanceManager] Measure created: ${e} (${a.duration.toFixed(2)}ms)`),a}catch(i){return d.error("[PerformanceManager] Measure creation failed:",i),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 r=0;n.forEach(e=>{e.hadRecentInput||(r+=e.value)}),t.cls=r,this.checkThreshold("cls",r),e&&e("cls",r)}),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 r=document.createElement("link");return r.rel="preload",r.href=e,r.as=t,n&&(r.crossOrigin="anonymous"),document.head.appendChild(r),r},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==(r=PerformanceObserver.supportedEntryTypes)?void 0:r.includes("layout-shift")),longTask:"PerformanceObserver"in window&&(null==(i=PerformanceObserver.supportedEntryTypes)?void 0:i.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,r){return t<n?{rating:"good",message:`Excellent ${e}`}:t<r?{rating:"needs-improvement",message:`${e} needs improvement`}:{rating:"poor",message:`Poor ${e} performance`}}getTransferEfficiency(e){const t=e.decodedBodySize>0?e.encodedBodySize/e.decodedBodySize:1;return{ratio:t,rating:t<.7?"good":t<.9?"fair":"poor"}}getNavigationRecommendations(e){const t=[];return e.ttfb>500&&t.push("Server response time is slow. Consider optimizing backend performance."),e.dns>100&&t.push("DNS lookup time is high. Consider using a faster DNS provider."),e.connect>1e3&&t.push("Connection time is slow. Check network latency."),e.domProcessing>1e3&&t.push("DOM processing is slow. Consider optimizing JavaScript execution."),t}checkThreshold(e,t){const n=this.thresholds[e];n&&t>n&&d.warn(`[PerformanceManager] ${e.toUpperCase()} threshold exceeded: ${t}ms (threshold: ${n}ms)`)}getRating(e,t){const n={fcp:{good:1800,poor:3e3},lcp:{good:2500,poor:4e3},fid:{good:100,poor:300},cls:{good:.1,poor:.25}}[e];return n&&null!=t?t<=n.good?"good":t<=n.poor?"needs-improvement":"poor":"unknown"}setMetric(e,t){this.metrics.set(e,{value:t,timestamp:Date.now()})}getMetric(e){const t=this.metrics.get(e);return t?t.value:null}formatBytes(e){if(0===e)return"0 Bytes";const t=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,t)).toFixed(2))+" "+["Bytes","KB","MB","GB"][t]}generateId(e="perf"){return`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}cleanup(){this.observers.forEach(e=>{e.disconnect()}),this.observers.clear(),this.metrics.clear(),this.marks.clear(),this.measures.clear(),d.info("[PerformanceManager] Cleanup completed")}getReport(){return{support:this.support,navigation:this.navigation.get(),resources:this.resources.getSummary(),vitals:this.vitals.get(),memory:this.memory.get(),marks:this.timing.getMarks(),measures:this.timing.getMeasures(),activeObservers:this.observers.size,timestamp:Date.now()}}}const y={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 m(e.storage||{}),this.device=new g(e.device||{}),this.animation=new p(e.animation||{}),this.worker=new f(e.worker||{}),this.performance=new v(e.performance||{}),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},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}[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,r=Math.round(n/t*100);return{total:t,supported:n,percentage:r,grade:this.getGrade(r)}},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"})},b=y.init.bind(y),w=Object.freeze(Object.defineProperty({__proto__:null,default:y,init:b},Symbol.toStringTag,{value:"Module"})),S=new Map,M={add(e,t,n,{module:r="global",options:i=!1}={}){e.addEventListener(t,n,i),S.has(r)||S.set(r,[]),S.get(r).push([e,t,n,i])},removeModule(e){const t=S.get(e);t&&(t.forEach(([e,t,n,r])=>{e.removeEventListener(t,n,r)}),S.delete(e))},clearAll(){for(const[e,t]of S.entries())t.forEach(([e,t,n,r])=>{e.removeEventListener(t,n,r)});S.clear()},debug(){console.table([...S.entries()].map(([e,t])=>({module:e,listeners:t.length})))}};function k(e,t,n,r=import.meta,i=!1){var a;const o="string"==typeof r?r:(null==(a=r.url)?void 0:a.split("/").slice(-2,-1)[0])||"unknown";return M.add(e,t,n,{module:o,options:i}),()=>{M.removeModule(o)}}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(){k(window,"resize",()=>{this.resize()},"canvas-manager"),k(window,"orientationchange",()=>{setTimeout(()=>this.resize(),100)},"canvas-manager")}resize(){const e=this.canvas.parentElement,t=this.options.pixelRatio;let n,r;e&&"static"!==getComputedStyle(e).position?(n=e.clientWidth,r=e.clientHeight):(n=this.canvas.clientWidth||window.innerWidth,r=this.canvas.clientHeight||window.innerHeight),this.canvas.width=Math.floor(n*t),this.canvas.height=Math.floor(r*t),this.canvas.style.width=n+"px",this.canvas.style.height=r+"px",t>1&&this.ctx.scale(t,t),d.info("[CanvasManager] Resized",{displayWidth:n,displayHeight:r,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 E={initParallax(e,t){const n=new x(e),r=this.createParallaxElements(e,t);let i=!1;const a=()=>{i||(requestAnimationFrame(()=>{this.renderParallax(n,r,t),i=!1}),i=!0)};k(window,"scroll",a,"scroll-parallax"),k(window,"resize",a,"scroll-parallax"),a(),d.info("[ScrollEffects] Parallax initialized with",r.length,"elements")},createParallaxElements(e,t){const n=[],r=t.layers||3,i=t.elements||20;for(let a=0;a<i;a++)n.push({x:Math.random()*e.clientWidth,y:Math.random()*e.clientHeight*2,size:20*Math.random()+5,layer:Math.floor(Math.random()*r),speed:.1+.5*Math.random(),opacity:.7*Math.random()+.3,color:this.getLayerColor(Math.floor(Math.random()*r),t)});return n},getLayerColor(e,t){const n=t.colors||["rgba(100, 150, 255, 0.6)","rgba(150, 100, 255, 0.4)","rgba(200, 100, 150, 0.2)"];return n[e]||n[0]},renderParallax(e,t,n){e.clear();const r=window.pageYOffset,i=(r-(e.canvas.getBoundingClientRect().top+r))/window.innerHeight;t.forEach(t=>{const n=i*t.speed*100,r=t.y-n;r>-t.size&&r<e.canvas.clientHeight+t.size&&(e.ctx.save(),e.ctx.globalAlpha=t.opacity,e.ctx.fillStyle=t.color,e.ctx.beginPath(),e.ctx.arc(t.x,r,t.size,0,2*Math.PI),e.ctx.fill(),e.ctx.restore())})},initScrollAnimation(e,t){const n=new x(e),r=t.animation||"wave";let i=!1;const a=()=>{i||(requestAnimationFrame(()=>{this.renderScrollAnimation(n,r,t),i=!1}),i=!0)};k(window,"scroll",a,"scroll-animation"),k(window,"resize",a,"scroll-animation"),a(),d.info("[ScrollEffects] Scroll animation initialized:",r)},renderScrollAnimation(e,t,n){e.clear();const r=window.pageYOffset,i=r-(e.canvas.getBoundingClientRect().top+r),a=Math.max(0,Math.min(1,i/window.innerHeight));switch(t){case"wave":default:this.renderWaveAnimation(e,a,n);break;case"progress":this.renderProgressAnimation(e,a,n);break;case"morph":this.renderMorphAnimation(e,a,n)}},renderWaveAnimation(e,t,n){const{ctx:r}=e,{width:i,height:a}=e.getSize();r.strokeStyle=n.color||"rgba(100, 150, 255, 0.8)",r.lineWidth=n.lineWidth||3,r.beginPath();const o=(n.amplitude||50)*t,s=n.frequency||.02,c=t*Math.PI*2;for(let l=0;l<=i;l+=2){const e=a/2+Math.sin(l*s+c)*o;0===l?r.moveTo(l,e):r.lineTo(l,e)}r.stroke()},renderProgressAnimation(e,t,n){const{ctx:r}=e,{width:i,height:a}=e.getSize(),o=n.barHeight||10,s=a/2-o/2;r.fillStyle=n.backgroundColor||"rgba(255, 255, 255, 0.2)",r.fillRect(0,s,i,o),r.fillStyle=n.color||"rgba(100, 150, 255, 0.8)",r.fillRect(0,s,i*t,o)},renderMorphAnimation(e,t,n){const{ctx:r}=e,{width:i,height:a}=e.getSize();r.fillStyle=n.color||"rgba(100, 150, 255, 0.6)";const o=i/2,s=a/2,c=Math.min(i,a)/3;r.beginPath();const l=n.points||6;for(let d=0;d<=l;d++){const e=d/l*Math.PI*2,n=c*t*(.3*Math.sin(t*Math.PI*4+3*e)+1),i=o+Math.cos(e)*n,a=s+Math.sin(e)*n;0===d?r.moveTo(i,a):r.lineTo(i,a)}r.closePath(),r.fill()}},A={init(e,t){const n=new x(e),r=t.effect||"ripple",i={mouse:{x:0,y:0,isOver:!1},effects:[],lastTime:0};this.setupInteractionEvents(e,n,i,t),this.startAnimationLoop(n,i,r,t),d.info("[InteractiveEffects] Initialized with effect:",r)},setupInteractionEvents(e,t,n,r){k(e,"mousemove",e=>{const i=t.getMousePosition(e);n.mouse.x=i.x,n.mouse.y=i.y,"trail"===r.effect&&this.addTrailPoint(n,i.x,i.y)},"interactive-effects"),k(e,"mouseenter",()=>{n.mouse.isOver=!0},"interactive-effects"),k(e,"mouseleave",()=>{n.mouse.isOver=!1},"interactive-effects"),k(e,"click",e=>{const i=t.getMousePosition(e);this.addClickEffect(n,i.x,i.y,r)},"interactive-effects"),k(e,"touchstart",e=>{e.preventDefault();const i=e.touches[0],a=t.getMousePosition(i);this.addClickEffect(n,a.x,a.y,r)},"interactive-effects"),k(e,"touchmove",e=>{e.preventDefault();const i=e.touches[0],a=t.getMousePosition(i);n.mouse.x=a.x,n.mouse.y=a.y,n.mouse.isOver=!0,"trail"===r.effect&&this.addTrailPoint(n,a.x,a.y)},"interactive-effects"),k(e,"touchend",()=>{n.mouse.isOver=!1},"interactive-effects")},startAnimationLoop(e,t,n,r){const i=a=>{const o=a-t.lastTime;switch(t.lastTime=a,e.clear(),n){case"ripple":default:this.renderRippleEffect(e,t,r);break;case"trail":this.renderTrailEffect(e,t,r);break;case"particles":this.renderParticleEffect(e,t,r,o);break;case"magnetic":this.renderMagneticEffect(e,t,r)}this.updateEffects(t.effects,o),requestAnimationFrame(i)};requestAnimationFrame(i)},addClickEffect(e,t,n,r){const i={x:t,y:n,age:0,maxAge:r.duration||1e3,type:"click",intensity:r.intensity||1};e.effects.push(i)},addTrailPoint(e,t,n){const r={x:t,y:n,age:0,maxAge:500,type:"trail"};e.effects.push(r);const i=e.effects.filter(e=>"trail"===e.type);if(i.length>20){const t=e.effects.indexOf(i[0]);e.effects.splice(t,1)}},renderRippleEffect(e,t,n){const{ctx:r}=e;t.effects.forEach(t=>{if("click"===t.type){const i=t.age/t.maxAge,a=i*(n.maxRadius||100),o=.8*(1-i);r.save(),r.globalAlpha=o,r.strokeStyle=n.color||"rgba(100, 150, 255, 1)",r.lineWidth=n.lineWidth||3,r.beginPath(),r.arc(t.x/e.options.pixelRatio,t.y/e.options.pixelRatio,a,0,2*Math.PI),r.stroke(),r.restore()}}),t.mouse.isOver&&(r.save(),r.globalAlpha=.3,r.fillStyle=n.hoverColor||"rgba(100, 150, 255, 0.3)",r.beginPath(),r.arc(t.mouse.x/e.options.pixelRatio,t.mouse.y/e.options.pixelRatio,n.hoverRadius||30,0,2*Math.PI),r.fill(),r.restore())},renderTrailEffect(e,t,n){const{ctx:r}=e,i=t.effects.filter(e=>"trail"===e.type);i.length<2||(r.save(),r.strokeStyle=n.color||"rgba(100, 150, 255, 0.8)",r.lineWidth=n.lineWidth||5,r.lineCap="round",r.lineJoin="round",r.beginPath(),i.forEach((t,n)=>{const i=1-t.age/t.maxAge,a=t.x/e.options.pixelRatio,o=t.y/e.options.pixelRatio;r.globalAlpha=.8*i,0===n?r.moveTo(a,o):r.lineTo(a,o)}),r.stroke(),r.restore())},renderParticleEffect(e,t,n,r){const{ctx:i}=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 r=t.age/t.maxAge,a=.8*(1-r);i.save(),i.globalAlpha=a,i.fillStyle=n.color||"rgba(100, 150, 255, 1)",i.beginPath(),i.arc(t.x/e.options.pixelRatio,t.y/e.options.pixelRatio,t.size*(1-.5*r),0,2*Math.PI),i.fill(),i.restore()}})},renderMagneticEffect(e,t,n){const{ctx:r}=e,{width:i,height:a}=e.getSize();if(!t.mouse.isOver)return;const o=i/2,s=a/2,c=t.mouse.x/e.options.pixelRatio,l=t.mouse.y/e.options.pixelRatio;r.save(),r.strokeStyle=n.color||"rgba(100, 150, 255, 0.6)",r.lineWidth=2;for(let d=0;d<8;d++){const e=d/8*Math.PI*2,t=o+50*Math.cos(e),n=s+50*Math.sin(e),i=(t+c)/2+30*Math.sin(e),a=(n+l)/2+30*Math.cos(e);r.beginPath(),r.moveTo(t,n),r.quadraticCurveTo(i,a,c,l),r.stroke()}r.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)}},C={init(e,t){const n=new x(e),r=t.type||"bar",i=this.parseData(e,t);if(i&&0!==i.length){switch(r){case"bar":default:this.createBarChart(n,i,t);break;case"line":this.createLineChart(n,i,t);break;case"pie":this.createPieChart(n,i,t);break;case"progress":this.createProgressChart(n,i,t)}d.info("[DataVisualization] Initialized",r,"chart with",i.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(r){d.warn("[DataVisualization] Failed to parse canvas data",r)}if(!n){const t=e.nextElementSibling;if(t&&"SCRIPT"===t.tagName&&"application/json"===t.type)try{n=JSON.parse(t.textContent)}catch(r){d.warn("[DataVisualization] Failed to parse script data",r)}}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:r}=e,{width:i,height:a}=e.getSize(),o=n.padding||40,s=i-2*o,c=a-2*o,l=s/t.length*.8,d=s/t.length*.2,h=Math.max(...t.map(e=>e.value));let u=0;const m=n.animationDuration||2e3;let g=null;const p=r=>{g||(g=r);const i=r-g;u=Math.min(i/m,1);const a=1-Math.pow(1-u,3);e.clear(),this.renderBarChart(e,t,n,a,{padding:o,chartWidth:s,chartHeight:c,barWidth:l,barSpacing:d,maxValue:h}),u<1&&requestAnimationFrame(p)};requestAnimationFrame(p)},renderBarChart(e,t,n,r,i){const{ctx:a}=e,{padding:o,chartHeight:s,barWidth:c,barSpacing:l,maxValue:d}=i;t.forEach((e,t)=>{const i=o+t*(c+l),h=e.value/d*s*r,u=o+s-h;a.fillStyle=e.color||n.barColor||"rgba(100, 150, 255, 0.8)",a.fillRect(i,u,c,h),!1!==n.showLabels&&(a.fillStyle=n.textColor||"#333",a.font=n.font||"12px Arial",a.textAlign="center",a.fillText(e.label,i+c/2,o+s+20),!1!==n.showValues&&a.fillText(Math.round(e.value*r),i+c/2,u-5))}),!1!==n.showAxes&&(a.strokeStyle=n.axisColor||"#ccc",a.lineWidth=1,a.beginPath(),a.moveTo(o,o),a.lineTo(o,o+s),a.stroke(),a.beginPath(),a.moveTo(o,o+s),a.lineTo(o+i.chartWidth,o+s),a.stroke())},createLineChart(e,t,n){const{ctx:r}=e,{width:i,height:a}=e.getSize(),o=n.padding||40,s=i-2*o,c=a-2*o,l=Math.max(...t.map(e=>e.value)),d=Math.min(...t.map(e=>e.value)),h=l-d;let u=0;const m=n.animationDuration||2e3;let g=null;const p=r=>{g||(g=r);const i=r-g;u=Math.min(i/m,1),e.clear(),this.renderLineChart(e,t,n,u,{padding:o,chartWidth:s,chartHeight:c,maxValue:l,minValue:d,valueRange:h}),u<1&&requestAnimationFrame(p)};requestAnimationFrame(p)},renderLineChart(e,t,n,r,i){const{ctx:a}=e,{padding:o,chartWidth:s,chartHeight:c,minValue:l,valueRange:d}=i,h=Math.floor(t.length*r);a.strokeStyle=n.lineColor||"rgba(100, 150, 255, 0.8)",a.lineWidth=n.lineWidth||3,a.lineCap="round",a.lineJoin="round",a.beginPath();for(let u=0;u<=h&&u<t.length;u++){const e=o+u/(t.length-1)*s,n=o+c-(t[u].value-l)/d*c;0===u?a.moveTo(e,n):a.lineTo(e,n)}if(a.stroke(),!1!==n.showPoints){a.fillStyle=n.pointColor||n.lineColor||"rgba(100, 150, 255, 0.8)";for(let e=0;e<=h&&e<t.length;e++){const r=o+e/(t.length-1)*s,i=o+c-(t[e].value-l)/d*c;a.beginPath(),a.arc(r,i,n.pointSize||4,0,2*Math.PI),a.fill(),!1!==n.showLabels&&t[e].label&&(a.fillStyle=n.textColor||"#333",a.font=n.font||"12px Arial",a.textAlign="center",a.fillText(t[e].label,r,o+c+20))}}},createPieChart(e,t,n){const{ctx:r}=e,{width:i,height:a}=e.getSize(),o=i/2,s=a/2,c=Math.min(i,a)/2*.8,l=t.reduce((e,t)=>e+t.value,0);let d=0;const h=n.animationDuration||2e3;let u=null;const m=r=>{u||(u=r);const i=r-u;d=Math.min(i/h,1),e.clear(),this.renderPieChart(e,t,n,d,{centerX:o,centerY:s,radius:c,total:l}),d<1&&requestAnimationFrame(m)};requestAnimationFrame(m)},renderPieChart(e,t,n,r,i){const{ctx:a}=e,{centerX:o,centerY:s,radius:c,total:l}=i;let d=-Math.PI/2;const h=d+2*Math.PI*r;for(let u=0;u<t.length&&!(d>=h);u++){const e=t[u],r=e.value/l*Math.PI*2,i=Math.min(d+r,h);if(i>d&&(a.fillStyle=e.color||this.getDefaultColor(u),a.beginPath(),a.moveTo(o,s),a.arc(o,s,c,d,i),a.closePath(),a.fill(),!1!==n.showLabels&&i===d+r)){const t=d+r/2,i=o+Math.cos(t)*c*.7,l=s+Math.sin(t)*c*.7;a.fillStyle=n.textColor||"#333",a.font=n.font||"12px Arial",a.textAlign="center",a.fillText(e.label,i,l)}d+=r}},createProgressChart(e,t,n){const{ctx:r}=e,{width:i,height:a}=e.getSize();let o=0;const s=n.animationDuration||1500;let c=null;const l=r=>{c||(c=r);const i=r-c;o=Math.min(i/s,1),e.clear(),this.renderProgressChart(e,t,n,o),o<1&&requestAnimationFrame(l)};requestAnimationFrame(l)},renderProgressChart(e,t,n,r){var i;const{ctx:a}=e,{width:o,height:s}=e.getSize(),c=o/2,l=s/2,d=Math.min(o,s)/2*.8,h=n.lineWidth||20,u=(null==(i=t[0])?void 0:i.value)||0,m=n.maxValue||100,g=u/m*r;a.strokeStyle=n.backgroundColor||"rgba(200, 200, 200, 0.3)",a.lineWidth=h,a.beginPath(),a.arc(c,l,d,0,2*Math.PI),a.stroke(),a.strokeStyle=n.color||"rgba(100, 150, 255, 0.8)",a.lineCap="round",a.beginPath(),a.arc(c,l,d,-Math.PI/2,-Math.PI/2+g/m*Math.PI*2),a.stroke(),!1!==n.showText&&(a.fillStyle=n.textColor||"#333",a.font=n.font||"bold 24px Arial",a.textAlign="center",a.textBaseline="middle",a.fillText(Math.round(g)+"%",c,l))},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]}},I={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,r=this.parseCanvasConfig(e);switch(d.info(`[CanvasAnimations] Initializing canvas type: ${n}`),n){case"interactive":A.init(e,r);break;case"scroll-parallax":E.initParallax(e,r);break;case"scroll-animation":E.initScrollAnimation(e,r);break;case"data-viz":C.init(e,r);break;case"background":this.initBackgroundAnimation(e,r);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 i=n.replace("canvas","").toLowerCase();let a=e.dataset[n];if(a.startsWith("{")&&a.endsWith("}")||a.startsWith("[")&&a.endsWith("]"))try{a=JSON.parse(a)}catch(r){d.warn(`[CanvasAnimations] Failed to parse JSON config: ${n}`,r)}else"true"===a?a=!0:"false"===a?a=!1:isNaN(a)||""===a||(a=parseFloat(a));t[i]=a}}),t},initBackgroundAnimation(e,t){const n=new x(e),r=t.particles||50,i=[];for(let a=0;a<r;a++)i.push({x:Math.random()*e.width,y:Math.random()*e.height,vx:.5*(Math.random()-.5),vy:.5*(Math.random()-.5),size:3*Math.random()+1,opacity:.5*Math.random()+.2});!function r(){n.clear(),n.ctx.fillStyle=t.color||"rgba(100, 150, 255, 0.6)",i.forEach(t=>{t.x+=t.vx,t.y+=t.vy,t.x<0&&(t.x=e.width),t.x>e.width&&(t.x=0),t.y<0&&(t.y=e.height),t.y>e.height&&(t.y=0),n.ctx.save(),n.ctx.globalAlpha=t.opacity,n.ctx.beginPath(),n.ctx.arc(t.x,t.y,t.size,0,2*Math.PI),n.ctx.fill(),n.ctx.restore()}),requestAnimationFrame(r)}()}},P=I.init.bind(I),O=Object.freeze(Object.defineProperty({__proto__:null,default:I,init:P},Symbol.toStringTag,{value:"Module"}));let T="example-module",D=null,L=null;const z=Object.freeze(Object.defineProperty({__proto__:null,destroy:function(){d.info("[example-module] destroy"),D&&(window.removeEventListener("resize",D),D=null),l(T),L&&"function"==typeof L.cleanup&&L.cleanup(),L=null},init:function(e={},t=null){d.info("[example-module] init"),L=t,L&&(L.register("windowSize",{width:window.innerWidth,height:window.innerHeight}),L.register("scrollPosition",{x:0,y:0}),L.register("isVisible",!0)),D=()=>{const e={width:window.innerWidth,height:window.innerHeight};d.info("Fenstergröße geändert:",e),L&&L.set("windowSize",e)},window.addEventListener("resize",D),c(T,()=>{const e=window.scrollY,t=window.scrollX;if(L){const n=L.get("scrollPosition");n.x===t&&n.y===e||L.set("scrollPosition",{x:t,y:e})}},{autoStart:!0})}},Symbol.toStringTag,{value:"Module"}));class ${constructor(e){this.form=e,this.errors=new Map}static create(e){return new $(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 r=e.getAttribute("minlength");if(r&&t.length<parseInt(r))return void this.errors.set(n,this.getErrorMessage(e,"tooShort")||`Mindestens ${r} Zeichen erforderlich`);const i=e.getAttribute("maxlength");if(i&&t.length>parseInt(i))return void this.errors.set(n,this.getErrorMessage(e,"tooLong")||`Maximal ${i} Zeichen erlaubt`);if("number"===e.type){const r=e.getAttribute("min"),i=e.getAttribute("max"),a=parseFloat(t);if(r&&a<parseFloat(r))return void this.errors.set(n,this.getErrorMessage(e,"rangeUnderflow")||`Wert muss mindestens ${r} sein`);if(i&&a>parseFloat(i))return void this.errors.set(n,this.getErrorMessage(e,"rangeOverflow")||`Wert darf maximal ${i} sein`)}const a=e.getAttribute("pattern");if(a){if(!new RegExp(a).test(t))return void this.errors.set(n,this.getErrorMessage(e,"patternMismatch")||"Ungültiges Format")}const o=e.getAttribute("data-validate");if(o){const r=this.runCustomValidation(o,t,e);if(!r.valid)return void this.errors.set(n,r.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 F{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=$.create(e),this.state=R.create(e),this.isSubmitting=!1,this.init()}static create(e,t={}){return new F(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,r=await fetch(t,{method:n.toUpperCase(),body:e,headers:{"X-Requested-With":"XMLHttpRequest"}}),i=await this.parseResponse(r);r.ok?this.handleSuccess(i):this.handleError(i)}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),r=this.getOrCreateErrorElement(e);n?(r.textContent=n,r.style.display="block",e.classList.add("error"),e.setAttribute("aria-invalid","true"),e.setAttribute("aria-describedby",r.id)):(r.textContent="",r.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 r=document.createElement("div");r.className=`form-message ${t}`,r.textContent=e,r.setAttribute("role","error"===t?"alert":"status"),n.innerHTML="",n.appendChild(r),"success"===t&&setTimeout(()=>{r.parentElement&&r.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 W={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},r=F.create(e,n);e._formHandler=r,e._formValidator=r.validator,e._formState=r.state,n.enableUnsavedWarning&&r.state.enableUnsavedChangesWarning(),e.classList.add("form-enhanced");const i=new CustomEvent("form:initialized",{detail:{handler:r,validator:r.validator,state:r.state,config:n},bubbles:!0});return e.dispatchEvent(i),d.info(`[FormHandling] Successfully initialized for form: ${e.id||"unnamed"}`),r},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")}},B=W.init.bind(W),j=W.initElement.bind(W),_=Object.freeze(Object.defineProperty({__proto__:null,FormHandler:F,FormHandlingModule:W,FormState:R,FormValidator:$,default:W,init:B,initElement:j},Symbol.toStringTag,{value:"Module"}));let q,N="inertia-scroll",V=0,H=window.scrollY,U=!1,X=.9,G=.2;function Y(){U=!0,clearTimeout(q),q=setTimeout(()=>{U=!1},50)}const J=Object.freeze(Object.defineProperty({__proto__:null,destroy:function(){window.removeEventListener("scroll",Y),l(N),V=0,H=window.scrollY,U=!1,clearTimeout(q);const e=document.documentElement;delete e.dataset.scrollState,delete e.dataset.scrollDirection,delete e.dataset.scrollSpeed},init:function(e={}){X="number"==typeof e.damping?e.damping:.9,G="number"==typeof e.minVelocity?contig.minVelocity:.1,window.addEventListener("scroll",Y,{passive:!0}),c(N,()=>{const e=document.documentElement,t=window.scrollY,n=t-H,r=n>0?"down":n<0?"up":"none",i=Math.abs(n);!U&&Math.abs(V)>G?(window.scrollTo(0,t+V),V*=X,e.dataset.scrollState="inertia"):U?(V=n,H=t,e.dataset.scrollState="active"):delete e.dataset.scrollState,e.dataset.scrollDirection=r,e.dataset.scrollSpeed=i.toFixed(2)},{autoStart:!0})}},Symbol.toStringTag,{value:"Module"}));class K{constructor({content:e="",className:t="",onClose:n=null}={}){this.onClose=n,this.className=t,this.isOpenState=!1,this.dialog=document.createElement("dialog"),this.dialog.className=t,this.eventCleanup=[],this.updateContent(e),this.bindEvents()}bindEvents(){this.cleanupEvents(),this.clickHandler=e=>{!e.target.closest("."+this.className+"-content")&&this.close()},this.cancelHandler=e=>{e.preventDefault(),this.close()},this.dialog.addEventListener("click",this.clickHandler),this.dialog.addEventListener("cancel",this.cancelHandler),this.eventCleanup=[()=>this.dialog.removeEventListener("click",this.clickHandler),()=>this.dialog.removeEventListener("cancel",this.cancelHandler)]}cleanupEvents(){this.eventCleanup.forEach(e=>e()),this.eventCleanup=[]}updateContent(e){this.dialog.innerHTML=`\n <form method="dialog" class="${this.className}-content">\n ${e}\n <button class="${this.className}-close" value="close">×</button>\n </form>\n `}open(){var e,t,n,r;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==(r=(n=this.dialog).showModal)?void 0:r.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 Q={modal:class extends K{constructor(e){super({...e,className:"modal"})}},lightbox:class extends K{constructor(e){super({...e,className:"lightbox"})}}},Z={},ee={open(e,t={}){const n=Q[e];if(!n)return d.warn(`[UIManager] Unknown type: ${e}`),null;if("lightbox"===e){if(Z.lightbox)return d.info("[UIManager] Reusing existing lightbox instance"),Z.lightbox.updateContent(t.content||""),Z.lightbox.open(),Z.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 Z.lightbox=e,e.open(),e}}const r=new n(t);return r.open(),r},close(e){(null==e?void 0:e.close)&&e.close()},closeByType(e){Z[e]&&this.close(Z[e])},isOpen(e){var t;return(null==(t=Z[e])?void 0:t.isOpen())||!1},destroyAll(){Object.values(Z).forEach(e=>{(null==e?void 0:e.destroy)&&e.destroy()}),Object.keys(Z).forEach(e=>{delete Z[e]})}};function te(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),r=t.alt||t.dataset.caption||t.title||"",i=t.closest("picture");let a;if(i){const e=i.cloneNode(!0);e.querySelector("img").className="lightbox-image",a=`\n <div class="lightbox-content">\n ${e.outerHTML}\n ${r?`<div class="lightbox-caption">${r}</div>`:""}\n </div>\n `,d.info("[Lightbox] Opening responsive image (picture element):",n)}else a=`\n <div class="lightbox-content">\n <img src="${n}" alt="${r}" class="lightbox-image" />\n ${r?`<div class="lightbox-caption">${r}</div>`:""}\n </div>\n `,d.info("[Lightbox] Opening standalone image:",n);const o=ee.open("lightbox",{content:a});ee.isOpen("lightbox")&&o&&d.info("[Lightbox] Reused existing lightbox instance")}const ne=Object.freeze(Object.defineProperty({__proto__:null,destroy:function(){d.info("[lightbox-trigger] destroy"),document.querySelectorAll("img.lightbox-enabled").forEach(e=>{e.classList.remove("lightbox-enabled"),e.style.cursor="","Klicken zum Vergrößern"===e.title&&(e.title="")})},init:function(){d.info("[lightbox-trigger] Auto-enabling lightbox for all images (including picture/srcset)"),d.info('[lightbox-trigger] Use data-lightbox="false" to opt-out'),d.info("[lightbox-trigger] Use data-lightbox-src for custom high-res versions"),k(document,"click",te),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 re=Object.freeze(Object.defineProperty({__proto__:null,init:function(e={}){d.log("Noise Toggle Init",e);const{selector:t=".noise-overlay",toggleKey:n="g",className:r="grainy",enableTransition:i=!0}=e,a=document.body,o=document.querySelector(t);if(!o)return;function s(){i?o.classList.toggle("hidden",!a.classList.contains(r)):o.style.display=a.classList.contains(r)?"block":"none"}s(),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()))||(a.classList.toggle(r),s())})}},Symbol.toStringTag,{value:"Module"}));const ie=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);c("parallax",function(){const e=window.scrollY;n.forEach(n=>{const r=parseFloat(n.getAttribute(t.speedAttr))||t.defaultSpeed,i=e*r;n.style.transform=`translateY(${i}px)`})},{autoStart:!0})}},Symbol.toStringTag,{value:"Module"}));class ae{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=[],r=i=>{if(t.has(i))throw new Error(`Circular dependency detected involving '${i}'`);if(e.has(i))return;const a=this.modules.get(i);a&&(t.add(i),a.dependencies.forEach(e=>{e.optional&&!this.modules.has(e.name)||r(e.name)}),t.delete(i),e.add(i),n.push(i))};return Array.from(this.modules.entries()).sort(([,e],[,t])=>(t.priority||0)-(e.priority||0)).map(([e])=>e).forEach(t=>{e.has(t)||r(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=[],r=[];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?r.push(e.name):n.push(e.name)}),{satisfied:0===n.length,missing:n,optional:r,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},r={depends(e,t="*",r=!1){return n.dependencies.push({name:e,version:t,optional:r}),this},provides(...e){return n.provides.push(...e),this},priority(e){return n.priority=e,this},build:()=>n};return Object.setPrototypeOf(r,n),Object.keys(n).forEach(e=>{e in r||Object.defineProperty(r,e,{get:()=>n[e],set(t){n[e]=t},enumerable:!0,configurable:!0})}),r}}const oe=new ae;"undefined"!=typeof window&&(window.dependencyManager=oe,window.depStatus=()=>oe.getStatus());const se=ae.createDefinition("scroll-dependent","1.0.0").depends("example-module","1.0.0").depends("scrollfx","1.0.0",!0).provides("scroll-coordination").priority(10);let ce=null,le=null;const de=Object.freeze(Object.defineProperty({__proto__:null,definition:se,destroy:function(){d.info("[scroll-dependent] destroy"),ce&&le&&(le.unsubscribe(ce),ce=null),le&&"function"==typeof le.cleanup&&le.cleanup(),le=null},init:function(e={},t=null){d.info("[scroll-dependent] init"),le=t,le&&(le.register("isScrolling",!1),le.register("scrollDirection","none"),ce=le.subscribe("example-module.scrollPosition",(e,t)=>{if(t.y!==e.y){const n=e.y>t.y?"down":"up";le.set("scrollDirection",n),le.set("isScrolling",!0),setTimeout(()=>{le&&le.set("isScrolling",!1)},150),d.info(`[scroll-dependent] Scroll ${n}: ${e.y}`)}}))}},Symbol.toStringTag,{value:"Module"}));const he=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)}}),c("scroll-loop",()=>{const n=window.scrollY,r=window.scrollX;t.forEach(t=>{const i=parseFloat(t.dataset.scrollSpeed||e.speed||.2),a=t.dataset.scrollAxis||"y",o=t.dataset.scrollType||"translate",s="true"===t.dataset.loopPause,c=parseFloat(t.dataset.loopOffset||0),l=parseFloat(t.dataset.loopLimit||0),d="x"===a?r:n;if(l&&d>l)return;if(s&&(t.matches(":hover")||t.matches(":active")))return;const h=(d+c)*i;switch(o){case"translate":{const e=-h%("x"===a?t.offsetWidth:t.offsetHeight),n="x"===a?`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"===a?`${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"})),ue={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 me=Object.freeze(Object.defineProperty({__proto__:null,destroy:function(){l("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}));c("scroll-timeline",function(){const e=window.innerHeight*t.triggerPoint;n.forEach(n=>{var r,i;const a=n.el.getBoundingClientRect(),o=a.top<e&&a.bottom>0;o&&!n.active&&(n.active=!0,n.el.classList.add("active"),d.log(`➡️ ENTER step ${n.index}`),null==(r=ue.onEnter)||r.call(ue,n.index,n.el)),!o&&n.active&&(n.active=!1,n.el.classList.remove("active"),d.log(`⬅️ LEAVE step ${n.index}`),t.once||null==(i=ue.onLeave)||i.call(ue,n.index,n.el))})},{autoStart:!0})}},Symbol.toStringTag,{value:"Module"}));const ge=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 pe{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),r=this.parsePosition(this.end,e)-n,i=t.top-n;return 1-Math.min(Math.max(i/r,0),1)}parsePosition(e,t){const[n,r]=e.split(" ");return("top"===n?0:t)-t*(parseFloat(r)/100)}update(e){const t=this.element.getBoundingClientRect(),n=t.bottom>0&&t.top<e;if(n&&!this._wasVisible&&(this._wasVisible=!0,this.onEnter&&this.onEnter(this.target)),!n&&this._wasVisible&&(this._wasVisible=!1,this.onLeave&&this.onLeave(this.target)),this.scrub&&n){const t=this.getScrollProgress(e);this.onUpdate&&this.onUpdate(this.target,t)}}}const fe=Object.freeze(Object.defineProperty({__proto__:null,createTrigger:function(e){const t="string"==typeof e.element?document.querySelectorAll(e.element):[e.element],n=[];return t.forEach(t=>{const r=new pe({...e,element:t});ge.register(r),n.push(r)}),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:r=.05,once:i=!0}=e,a=Array.from(document.querySelectorAll(t)).map(e=>({el:e,triggered:!1}));requestAnimationFrame(function e(){const t=window.innerHeight*n;a.forEach((e,n)=>{if(e.triggered&&i)return;e.el.getBoundingClientRect().top<t?(e.el.style.transitionDelay=n*r+"s",e.el.classList.add("visible","entered"),e.el.classList.remove("fade-out"),e.triggered=!0):i||(e.el.classList.remove("visible","entered"),e.triggered=!1)}),requestAnimationFrame(e)})}},Symbol.toStringTag,{value:"Module"}));let ve=null,ye=null;const be=Object.freeze(Object.defineProperty({__proto__:null,destroy:function(){var e;e="sidebar",Array.isArray(e)&&e.forEach(e=>{M.removeModule(e)})},init:function(){document.getElementById("sidebar-menu");const e=document.getElementById("menu-toggle"),t=document.getElementById("sidebar"),n=document.querySelector(".backdrop"),r=document.querySelector("footer"),i=document.querySelector("header a");k(e,"click",e=>{t.classList.toggle("show"),t.classList.contains("show")?(n.classList.add("visible"),r.setAttribute("inert","true"),i.setAttribute("inert","true")):(n.classList.remove("visible"),r.removeAttribute("inert"),i.removeAttribute("inert"))}),ve=e=>{"Escape"===e.key&&t.classList.contains("show")&&(t.classList.remove("show"),n.classList.remove("visible"))},k(document,"keydown",ve),ye=e=>{t.classList.remove("show"),n.classList.remove("visible"),r.removeAttribute("inert"),i.removeAttribute("inert")},k(n,"click",ye)}},Symbol.toStringTag,{value:"Module"})),we=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));class Se{constructor(e={}){this.options={containerSelector:"main",linkSelector:'a[href^="/"]',loadingClass:"spa-loading",excludeSelector:'[data-spa="false"], [download], [target="_blank"], [href^="mailto:"], [href^="tel:"], [href^="#"]',enableTransitions:!0,transitionDuration:300,skeletonTemplate:this.createSkeletonTemplate(),...e},this.container=null,this.isLoading=!1,this.currentUrl=window.location.href,this.abortController=null,this.init()}static create(e={}){return new Se(e)}init(){this.container=document.querySelector(this.options.containerSelector),this.container?(this.bindEvents(),this.setupStyles(),this.updateHistoryState(window.location.href,document.title),d.info("[SPARouter] Initialized")):d.error(`[SPARouter] Container "${this.options.containerSelector}" not found`)}bindEvents(){document.addEventListener("click",e=>this.handleLinkClick(e)),window.addEventListener("popstate",e=>this.handlePopState(e)),document.addEventListener("submit",e=>this.handleFormSubmit(e))}handleLinkClick(e){const t=e.target.closest(this.options.linkSelector);if(!t)return;if(t.matches(this.options.excludeSelector))return;if(e.ctrlKey||e.metaKey||e.shiftKey)return;e.preventDefault();const n=t.href,r=t.title||t.textContent.trim();this.navigate(n,r)}handlePopState(e){const t=window.location.href;t!==this.currentUrl&&this.loadContent(t,!1)}handleFormSubmit(e){const t=e.target;t.hasAttribute("data-spa")&&"false"===t.getAttribute("data-spa")||t._moduleInstance}async navigate(e,t=""){var n;if(this.isLoading&&(null==(n=this.abortController)||n.abort()),e!==this.currentUrl){d.info(`[SPARouter] Navigating to: ${e}`);try{await this.loadContent(e,!0,t)}catch(r){"AbortError"!==r.name&&(d.error("[SPARouter] Navigation failed:",r),window.location.href=e)}}}async loadContent(e,t=!0,n=""){if(!this.isLoading){this.isLoading=!0,this.abortController=new AbortController;try{this.showLoadingState();const r=await fetch(e,{headers:{"X-Requested-With":"XMLHttpRequest","X-SPA-Request":"true",Accept:"text/html"},signal:this.abortController.signal});if(!r.ok)throw new Error(`HTTP ${r.status}: ${r.statusText}`);const i=await r.text(),a=this.extractMainContent(i),o=this.extractTitle(i)||n;await this.updateContent(a,o),t&&this.updateHistoryState(e,o),this.currentUrl=e,d.info(`[SPARouter] Successfully loaded: ${e}`)}catch(r){if("AbortError"!==r.name)throw this.hideLoadingState(),r}finally{this.isLoading=!1,this.abortController=null}}}extractMainContent(e){const t=(new DOMParser).parseFromString(e,"text/html"),n=t.querySelector("main");if(n)return n.innerHTML;const r=['[role="main"]',".main-content","#main",".content"];for(const i of r){const e=t.querySelector(i);if(e)return d.warn(`[SPARouter] Using fallback selector: ${i}`),e.innerHTML}return d.warn("[SPARouter] No main element found, using entire body"),t.body.innerHTML}extractTitle(e){const t=(new DOMParser).parseFromString(e,"text/html").querySelector("title");return t?t.textContent.trim():""}async updateContent(e,t){t&&(document.title=t),this.options.enableTransitions&&await this.transitionOut(),this.container.innerHTML=e,this.reinitializeModules(),this.options.enableTransitions&&await this.transitionIn(),this.hideLoadingState(),window.scrollTo({top:0,behavior:"smooth"}),this.triggerNavigationEvent()}showLoadingState(){document.body.classList.add(this.options.loadingClass),this.options.enableTransitions&&this.container.classList.add("spa-transitioning-out")}hideLoadingState(){document.body.classList.remove(this.options.loadingClass)}async transitionOut(){return new Promise(e=>{this.container.style.transition=`opacity ${this.options.transitionDuration}ms ease-out`,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.opacity="1",setTimeout(()=>{this.container.style.transition="",this.container.classList.remove("spa-transitioning-out"),e()},this.options.transitionDuration)},50)})}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 <div class="spa-skeleton">\n <div class="spa-skeleton-header"></div>\n <div class="spa-skeleton-content">\n <div class="spa-skeleton-line"></div>\n <div class="spa-skeleton-line"></div>\n <div class="spa-skeleton-line short"></div>\n </div>\n </div>\n '}setupStyles(){if(document.getElementById("spa-router-styles"))return;const e=document.createElement("style");e.id="spa-router-styles",e.textContent="\n /* SPA Router Transitions */\n .spa-loading {\n cursor: progress;\n }\n \n .spa-transitioning-out {\n pointer-events: none;\n }\n \n /* Skeleton Loading Styles */\n .spa-skeleton {\n animation: spa-pulse 1.5s ease-in-out infinite alternate;\n }\n \n .spa-skeleton-header {\n height: 2rem;\n background: #e5e7eb;\n border-radius: 0.375rem;\n margin-bottom: 1rem;\n width: 60%;\n }\n \n .spa-skeleton-content {\n space-y: 0.75rem;\n }\n \n .spa-skeleton-line {\n height: 1rem;\n background: #e5e7eb;\n border-radius: 0.375rem;\n margin-bottom: 0.75rem;\n }\n \n .spa-skeleton-line.short {\n width: 75%;\n }\n \n @keyframes spa-pulse {\n 0% {\n opacity: 1;\n }\n 100% {\n opacity: 0.4;\n }\n }\n \n /* Dark mode support */\n @media (prefers-color-scheme: dark) {\n .spa-skeleton-header,\n .spa-skeleton-line {\n background: #374151;\n }\n }\n ",document.head.appendChild(e)}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 Me={name:"spa-router",router:null,init(e={}){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^="#"]',enableTransitions:!0,transitionDuration:300,enableSkeletonLoading:!0,...e};return this.router=Se.create(t),"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 r=new CustomEvent("module:reinit-needed",{detail:{element:t,moduleName:n},bubbles:!0});document.dispatchEvent(r)},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),"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")}},ke=Me.init.bind(Me),xe=Object.freeze(Object.defineProperty({__proto__:null,SPARouter:Se,SPARouterModule:Me,default:Me,init:ke},Symbol.toStringTag,{value:"Module"}));let Ee="sticky-fade",Ae=[],Ce=window.scrollY,Ie=new WeakMap,Pe={direction:!1,reset:!1};const Oe=Object.freeze(Object.defineProperty({__proto__:null,destroy:function(){l(Ee),Ae.forEach(e=>{e.style.opacity="",e.style.transform="",e.classList.remove("visible"),delete e.dataset.scrollDir}),Ae=[],Ie=new WeakMap},init:function(e={}){Ae=Array.from(document.querySelectorAll("[data-sticky-fade]")),0!==Ae.length&&(Pe.direction=e.direction??!1,Pe.reset=e.reset??!1,c(Ee,()=>{const e=window.scrollY,t=e>Ce?"down":e<Ce?"up":"none";Ce=e;const n=window.innerHeight;Ae.forEach(e=>{const r=e.getBoundingClientRect(),i=1-Math.min(Math.max(r.top/n,0),1);if(e.style.opacity=i.toFixed(3),e.style.transform=`translateY(${20*(1-i)}px)`,Pe.direction&&(e.dataset.scrollDir=t),Pe.reset){const t=i>=1,n=Ie.get(e)||!1;t&&!n?(e.classList.add("visible"),Ie.set(e,!0)):!t&&n&&(e.classList.remove("visible"),Ie.set(e,!1))}})},{autoStart:!0}))}},Symbol.toStringTag,{value:"Module"}));const Te=Object.freeze(Object.defineProperty({__proto__:null,destroy:function(){l("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),r=e.offsetTop;c(`sticky-steps-${e.dataset.moduleId||Math.random()}`,function(){const i=window.scrollY,a=e.offsetHeight;n.forEach((o,s)=>{const c=r+s*(a/n.length),l=r+(s+1)*(a/n.length),d=i>=c&&i<l;o.classList.toggle(t.activeClass,d),d&&(e.dataset[t.datasetKey]=s)})},{autoStart:!0})})}},Symbol.toStringTag,{value:"Module"}));const De=Object.freeze(Object.defineProperty({__proto__:null,init:function(){}},Symbol.toStringTag,{value:"Module"})),Le=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),ze={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 $e=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,r)=>{const i=e[n];if("function"!=typeof i)return i;const a=Object.getOwnPropertyDescriptor(e,n);return a&&!a.configurable?i:(...r)=>{try{const a=i.apply(e,r);return a&&"function"==typeof a.catch?a.catch(e=>(this.handleModuleError(e,t,n,r),this.getRecoveryValue(t,n))):a}catch(a){return this.handleModuleError(a,t,n,r),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,r){const i=`${t}.${n}`;d.error(`[ErrorBoundary] Module ${t} crashed in ${n}():`,e),this.crashedModules.add(t);const a=this.recoveryAttempts.get(i)||0;this.recoveryAttempts.set(i,a+1),window.dispatchEvent(new CustomEvent("module-error",{detail:{moduleName:t,method:n,error:e.message,args:r,attempts:a+1}})),a<this.maxRecoveryAttempts?this.scheduleRecovery(t,n,r):(d.error(`[ErrorBoundary] Module ${t} exceeded recovery attempts. Marking as permanently failed.`),this.markModuleAsPermanentlyFailed(t))}scheduleRecovery(e,t,n){setTimeout(()=>{try{d.info(`[ErrorBoundary] Attempting recovery for ${e}.${t}()`)}catch(n){d.error(`[ErrorBoundary] Recovery failed for ${e}.${t}():`,n)}},this.recoveryDelay)}getRecoveryValue(e,t){switch(t){case"init":case"destroy":case"update":case"render":return Promise.resolve();case"getData":case"getConfig":return{};case"isEnabled":case"isActive":return!1;default:return}}markModuleAsPermanentlyFailed(e){window.dispatchEvent(new CustomEvent("module-permanent-failure",{detail:{moduleName:e}}))}getHealthStatus(){return{totalCrashedModules:this.crashedModules.size,crashedModules:Array.from(this.crashedModules),recoveryAttempts:Object.fromEntries(this.recoveryAttempts),timestamp:(new Date).toISOString()}}resetModule(e){this.crashedModules.delete(e);for(const[t]of this.recoveryAttempts)t.startsWith(`${e}.`)&&this.recoveryAttempts.delete(t);d.info(`[ErrorBoundary] Reset error tracking for module: ${e}`)}reset(){this.crashedModules.clear(),this.recoveryAttempts.clear(),d.info("[ErrorBoundary] Reset all error tracking")}};window.addEventListener("error",e=>{d.error("[Global] Unhandled error:",e.error||e.message)}),window.addEventListener("unhandledrejection",e=>{d.error("[Global] Unhandled promise rejection:",e.reason)});const Re=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 r=this.stateOwners.get(e);if(!n&&r!==this.currentModule)return d.warn(`[StateManager] Module '${this.currentModule}' cannot modify '${e}' (owned by ${r})`),!1;const i=this.state.get(e);return i===t||(this.state.set(e,t),this.notifySubscribers(e,t,i),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 r=`${n}_${++this.subscriptionCounter}`,i={id:r,callback:t,subscriber:n};return this.subscribers.has(e)||this.subscribers.set(e,[]),this.subscribers.get(e).push(i),d.info(`[StateManager] Subscribed '${n}' to '${e}'`),r}unsubscribe(e){for(const[t,n]of this.subscribers.entries()){const r=n.findIndex(t=>t.id===e);if(-1!==r){const e=n[r];return n.splice(r,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(r=>{try{r.callback(t,n,e)}catch(i){d.error(`[StateManager] Error in subscriber '${r.subscriber}' for '${e}':`,i)}})}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,r]of this.subscribers.entries()){const i=r.filter(t=>t.subscriber!==e);t+=r.length-i.length,this.subscribers.set(n,i)}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=Re,window.stateSnapshot=()=>Re.getSnapshot());const Fe=new Map;function We(){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=Fe.get(t);if(!n||!n.mod)return void d.warn(`[DOMInit] Module "${t}" not found or failed to initialize`);let r={};try{e.dataset.options&&(r=JSON.parse(e.dataset.options))}catch(i){d.warn(`[DOMInit] Invalid JSON in data-options for ${t}:`,i)}try{const i=n.mod;if("function"==typeof i.initElement){const n=i.initElement(e,r);d.info(`[DOMInit] Initialized ${t} on element:`,e),e._moduleInstance=n,e._moduleName=t}else if("function"==typeof i.init){const n=i.init(e,r);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(i){d.error(`[DOMInit] Failed to initialize ${t} on element:`,i,e)}})}function Be(){const e=document.querySelectorAll('form:not([data-form-handling="false"])');if(d.info(`[AutoForms] Found ${e.length} forms for auto-enhancement`),0===e.length)return;const t=Fe.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);let n={};try{e.dataset.formOptions&&(n=JSON.parse(e.dataset.formOptions))}catch(i){d.warn("[AutoForms] Invalid JSON in data-form-options:",i)}const r={validateOnSubmit:!0,validateOnBlur:!1,validateOnInput:!1,showInlineErrors:!0,ajaxSubmit:!0,enableStateTracking:!1,...n};try{const n=t.mod.initElement?t.mod.initElement(e,r):t.mod.init(e,r);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(i){d.error("[AutoForms] Failed to auto-enhance form:",i,e)}}):d.warn("[AutoForms] form-handling module not available, skipping auto-init")}async function je(){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":w,"./canvas-animations/index.js":O,"./example-module/index.js":z,"./form-handling/index.js":_,"./inertia-scroll/index.js":J,"./lightbox-trigger/index.js":ne,"./noise/index.js":re,"./parallax/index.js":ie,"./scroll-dependent/index.js":de,"./scroll-loop/index.js":he,"./scroll-timeline/index.js":me,"./scrollfx/index.js":fe,"./sidebar/index.js":be,"./smooth-scroll/index.js":we,"./spa-router/index.js":xe,"./sticky-fade/index.js":Oe,"./sticky-steps/index.js":Te,"./ui/index.js":De,"./wheel-boost/index.js":Le}),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)),r=new Set(["spa-router","form-handling"]),i=new Set([...n,...r]),a=i.size===r.size&&0===n.size;d.info("[Modules] DOM modules found:",[...n]),d.info("[Modules] Core modules:",[...r]),d.info("[Modules] Used modules:",[...i]),d.info("[Modules] Fallback mode:",a),Object.entries(t).forEach(([e,t])=>{const n=e.split("/").slice(-2,-1)[0];if(a||i.has(n))if("object"==typeof t.definition)oe.register(t.definition);else{const e={name:n,version:"1.0.0",dependencies:[],provides:[],priority:0};oe.register(e)}else d.info(`⏭️ [Module] Skipping unused module: ${n}`)});const o=oe.calculateInitializationOrder();for(const c of o){if(!a&&!i.has(c)){d.info(`⏭️ [Module] Skipped (not used in DOM): ${c}`);continue}const e=Object.keys(t).find(e=>e.split("/").slice(-2,-1)[0]===c);if(!e){d.warn(`⛔ [Module] No implementation found for: ${c}`);continue}const n=t[e],r=ze[c]||{},o=oe.checkDependencies(c);if(o.satisfied)if("function"==typeof n.init)try{oe.markInitializing(c);const e=Re.createScope(c),t=$e.wrapModule(n,c);await t.init(r,e),oe.markInitialized(c),Fe.set(c,{mod:t,config:r,state:e,original:n}),d.info(`✅ [Module] Initialized: ${c}`)}catch(s){d.error(`❌ [Module] Failed to initialize ${c}:`,s),Fe.set(c,{mod:null,config:r,error:s,original:n})}else d.warn(`⛔ [Module] No init() in ${c}`);else d.error(`❌ [Module] Cannot initialize ${c}: ${o.reason}`),Fe.set(c,{mod:null,config:r,error:new Error(o.reason),original:n})}a&&d.info("⚠️ [Module] No data-module usage detected, fallback to full init mode")}(),We(),Be(),function(){const e=Fe.get("spa-router");if(e&&e.mod)try{e.mod.init({containerSelector:"main",enableTransitions:!0,transitionDuration:300}),window.initAutoFormHandling=Be,window.initDataModuleElements=We,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 r=e.dataset.src;let i="480";i="2g"===n||"slow-2g"===n?"480":"3g"===n?t>=1200?"720":"480":t>=1200?"1080":t>=800?"720":"480";const a=`${r}-${i}.webm`,o=document.createElement("video");o.autoplay=!0,o.loop=!0,o.muted=!0,o.playsInline=!0,o.poster=e.getAttribute("poster")||"",o.setAttribute("width",e.getAttribute("width")||"100%");const s=document.createElement("source");s.src=a,s.type="video/webm",o.appendChild(s),e.replaceWith(o)})}()}"undefined"!=typeof window&&(window.moduleHealth=function(){const e={total:Fe.size,active:0,failed:0,modules:{},errorBoundary:$e.getHealthStatus()};for(const[t,{mod:n,error:r}]of Fe.entries())r?(e.failed++,e.modules[t]={status:"failed",error:r.message}):n?(e.active++,e.modules[t]={status:"active"}):e.modules[t]={status:"unknown"};return e}),document.addEventListener("DOMContentLoaded",async()=>{try{console.log("🚀 Starting app initialization..."),await je(),console.log("✅ App initialized successfully!"),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)},500)}catch(e){console.error("❌ App initialization failed:",e),console.error("Stack trace:",e.stack)}});