Files
michaelschiemer/public/assets/js/main-B16uFSy7.js
Michael Schiemer fc3d7e6357 feat(Production): Complete production deployment infrastructure
- Add comprehensive health check system with multiple endpoints
- Add Prometheus metrics endpoint
- Add production logging configurations (5 strategies)
- Add complete deployment documentation suite:
  * QUICKSTART.md - 30-minute deployment guide
  * DEPLOYMENT_CHECKLIST.md - Printable verification checklist
  * DEPLOYMENT_WORKFLOW.md - Complete deployment lifecycle
  * PRODUCTION_DEPLOYMENT.md - Comprehensive technical reference
  * production-logging.md - Logging configuration guide
  * ANSIBLE_DEPLOYMENT.md - Infrastructure as Code automation
  * README.md - Navigation hub
  * DEPLOYMENT_SUMMARY.md - Executive summary
- Add deployment scripts and automation
- Add DEPLOYMENT_PLAN.md - Concrete plan for immediate deployment
- Update README with production-ready features

All production infrastructure is now complete and ready for deployment.
2025-10-25 19:18:37 +02:00

2 lines
248 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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,i)=>((t,n,i)=>n in t?e(t,n,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[n]=i)(t,"symbol"!=typeof n?n+"":n,i);const n=new Map;let i=!1,r=!1;performance.now();const o=document.createElement("div");o.style.position="fixed",o.style.bottom="0",o.style.left="0",o.style.font="12px monospace",o.style.color="#0f0",o.style.background="rgba(0,0,0,0.75)",o.style.padding="0.25rem 0.5rem",o.style.zIndex="9999",o.style.pointerEvents="none",o.style.display="none";const a=`<div style="width:${Math.min(0,100)}%;height:4px;background:#0f0;margin-top:4px;"></div>`;o.innerHTML+=a,o.style.lineHeight="1.4",document.body.appendChild(o);const 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 i=Math.min(2*this.fps,100),r=this.logs.slice().reverse().join("\n");this.container.innerHTML=`\nFPS: ${this.fps} | Tasks: ${e.size}\n${n.join("\n")}\n<div style="width:${i}%;height:4px;background:#0f0;margin-top:4px;"></div>\n${r?"\nLogs:\n"+r:""}\n `}}trackTask(e,t){const n=performance.now();t();const i=performance.now()-n;this.taskTimings.set(e,i)}};function c(e,t,o={}){n.set(e,t),o.autoStart&&!i&&function(){if(i)return;function e(){for(const[e,i]of n)try{r?s.trackTask(e,i):i()}catch(t){d.warn("[Frameloop] Fehler in Task:",t)}r&&s.update(n),requestAnimationFrame(e)}i=!0,requestAnimationFrame(e)}()}function l(e){n.delete(e)}window.addEventListener("keydown",e=>{"§"===e.key&&(r=!r,o.style.display=r?"block":"none")});class d{static debug(...e){this._write("log","[DEBUG]",e,"debug")}static log(...e){this._write("log","[LOG]",e,"info")}static info(...e){this._write("info","[INFO]",e,"info")}static warn(...e){this._write("warn","[WARN]",e,"warn")}static error(...e){this._write("error","[ERROR]",e,"error")}static _write(e,t,n,i="info"){if(!this.enabled)return;const r=this.levels[this.level]||this.levels.info;if((this.levels[i]||this.levels.info)<r)return;const o=`${t} [${(new Date).toLocaleTimeString("de-DE")}] ${n.map(e=>{if(e instanceof Error)return`${e.name}: ${e.message}\n${e.stack||""}`;if("object"==typeof e&&null!==e)try{return JSON.stringify(e)}catch(t){return"[Circular Object]"}return e}).join(" ")}`;if("function"==typeof console[e]&&console[e](o),s&&"function"==typeof s.log)try{s.log(o)}catch(a){}}static setLevel(e){this.levels.hasOwnProperty(e)?(this.level=e,this.info(`[Logger] Log level set to: ${e}`)):this.warn(`[Logger] Invalid log level: ${e}. Valid levels:`,Object.keys(this.levels))}static setEnabled(e){this.enabled=!!e,e&&console.log("[Logger] Logging enabled")}}t(d,"enabled",!1),t(d,"level","error"),t(d,"levels",{debug:0,info:1,warn:2,error:3,none:99});class h{constructor(e={}){this.config=e,this.activeObservers=new Map,this.observerInstances=new Map,d.info("[ObserverManager] Initialized with support:",{intersection:"IntersectionObserver"in window,resize:"ResizeObserver"in window,mutation:"MutationObserver"in window,performance:"PerformanceObserver"in window})}intersection(e,t,n={}){if(!("IntersectionObserver"in window))return d.warn("[ObserverManager] IntersectionObserver not supported"),this.createFallbackObserver("intersection",e,t);const i={root:null,rootMargin:"50px",threshold:[0,.1,.5,1],...n},r=this.generateId("intersection"),o=new IntersectionObserver((e,n)=>{const i=e.map(e=>({element:e.target,isIntersecting:e.isIntersecting,intersectionRatio:e.intersectionRatio,boundingClientRect:e.boundingClientRect,rootBounds:e.rootBounds,intersectionRect:e.intersectionRect,time:e.time,visibility:this.calculateVisibility(e),direction:this.getScrollDirection(e),position:this.getElementPosition(e)}));t(i,n)},i),a=Array.isArray(e)?e:[e];return a.forEach(e=>{e instanceof Element&&o.observe(e)}),this.observerInstances.set(r,o),this.activeObservers.set(r,{type:"intersection",elements:a,callback:t,options:i}),d.info(`[ObserverManager] IntersectionObserver created: ${r}`),{id:r,observer:o,unobserve:e=>o.unobserve(e),disconnect:()=>this.disconnect(r),updateThreshold:e=>this.updateIntersectionThreshold(r,e)}}resize(e,t,n={}){if(!("ResizeObserver"in window))return d.warn("[ObserverManager] ResizeObserver not supported"),this.createFallbackObserver("resize",e,t);const i=this.generateId("resize"),r=new ResizeObserver(e=>{const n=e.map(e=>({element:e.target,contentRect:e.contentRect,borderBoxSize:e.borderBoxSize,contentBoxSize:e.contentBoxSize,devicePixelContentBoxSize:e.devicePixelContentBoxSize,dimensions:{width:e.contentRect.width,height:e.contentRect.height,aspectRatio:e.contentRect.width/e.contentRect.height},deltaSize:this.calculateDeltaSize(e),breakpoint:this.detectBreakpoint(e.contentRect.width)}));t(n)}),o=Array.isArray(e)?e:[e];return o.forEach(e=>{e instanceof Element&&r.observe(e)}),this.observerInstances.set(i,r),this.activeObservers.set(i,{type:"resize",elements:o,callback:t,options:n}),d.info(`[ObserverManager] ResizeObserver created: ${i}`),{id:i,observer:r,unobserve:e=>r.unobserve(e),disconnect:()=>this.disconnect(i)}}mutation(e,t,n={}){if(!("MutationObserver"in window))return d.warn("[ObserverManager] MutationObserver not supported"),null;const i={childList:!0,attributes:!0,subtree:!0,attributeOldValue:!0,characterDataOldValue:!0,...n},r=this.generateId("mutation"),o=new MutationObserver(e=>{const n=e.map(e=>({type:e.type,target:e.target,addedNodes:Array.from(e.addedNodes),removedNodes:Array.from(e.removedNodes),attributeName:e.attributeName,attributeNamespace:e.attributeNamespace,oldValue:e.oldValue,summary:this.summarizeMutation(e),impact:this.assessMutationImpact(e)}));t(n)});return o.observe(e,i),this.observerInstances.set(r,o),this.activeObservers.set(r,{type:"mutation",target:e,callback:t,options:i}),d.info(`[ObserverManager] MutationObserver created: ${r}`),{id:r,observer:o,disconnect:()=>this.disconnect(r),takeRecords:()=>o.takeRecords()}}performance(e,t={}){if(!("PerformanceObserver"in window))return d.warn("[ObserverManager] PerformanceObserver not supported"),null;const n={entryTypes:["measure","navigation","paint","largest-contentful-paint"],buffered:!0,...t},i=this.generateId("performance"),r=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 r.observe(n),this.observerInstances.set(i,r),this.activeObservers.set(i,{type:"performance",callback:e,options:n}),d.info(`[ObserverManager] PerformanceObserver created: ${i}`),{id:i,observer:r,disconnect:()=>this.disconnect(i),takeRecords:()=>r.takeRecords()}}lazyLoad(e="img[data-src], iframe[data-src]",t={}){const n=document.querySelectorAll(e);return this.intersection(n,e=>{e.forEach(e=>{if(e.isIntersecting){const t=e.element;t.dataset.src&&(t.src=t.dataset.src,delete t.dataset.src),t.dataset.srcset&&(t.srcset=t.dataset.srcset,delete t.dataset.srcset),t.classList.add("loaded"),e.observer.unobserve(t),d.info("[ObserverManager] Lazy loaded:",t.src)}})},{rootMargin:"100px",...t})}scrollTrigger(e,t,n={}){return this.intersection(e,e=>{e.forEach(e=>{const n={element:e.element,progress:e.intersectionRatio,isVisible:e.isIntersecting,direction:e.direction,position:e.position};t(n)})},{threshold:this.createThresholdArray(n.steps||10),...n})}viewport(e,t={}){const n=document.createElement("div");return n.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n pointer-events: none;\n visibility: hidden;\n ",document.body.appendChild(n),this.resize([n],t=>{const n=t[0];e({width:n.dimensions.width,height:n.dimensions.height,aspectRatio:n.dimensions.aspectRatio,orientation:n.dimensions.width>n.dimensions.height?"landscape":"portrait",breakpoint:n.breakpoint})},t)}generateId(e){return`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}disconnect(e){const t=this.observerInstances.get(e);t&&(t.disconnect(),this.observerInstances.delete(e),this.activeObservers.delete(e),d.info(`[ObserverManager] Observer disconnected: ${e}`))}disconnectAll(){this.observerInstances.forEach((e,t)=>{e.disconnect()}),this.observerInstances.clear(),this.activeObservers.clear(),d.info("[ObserverManager] All observers disconnected")}calculateVisibility(e){if(!e.isIntersecting)return 0;const t=e.intersectionRect.width*e.intersectionRect.height,n=e.boundingClientRect.width*e.boundingClientRect.height;return n>0?Math.round(t/n*100):0}getScrollDirection(e){return e.intersectionRatio>.5?"down":"up"}getElementPosition(e){const t=e.boundingClientRect,n=window.innerHeight;return t.top<0&&t.bottom>0?"entering-top":t.top<n&&t.bottom>n?"entering-bottom":t.top>=0&&t.bottom<=n?"visible":"hidden"}calculateDeltaSize(e){return{width:0,height:0}}detectBreakpoint(e){return e<576?"xs":e<768?"sm":e<992?"md":e<1200?"lg":"xl"}summarizeMutation(e){return`${e.type} on ${e.target.tagName}`}assessMutationImpact(e){return"childList"===e.type?e.addedNodes.length+e.removedNodes.length>5?"high":"low":"medium"}enhancePerformanceEntry(e){const t={raw:e};switch(e.entryType){case"navigation":t.loadTime=e.loadEventEnd-e.navigationStart,t.domContentLoaded=e.domContentLoadedEventEnd-e.navigationStart;break;case"paint":t.paintType=e.name;break;case"largest-contentful-paint":t.element=e.element,t.url=e.url}return t}createThresholdArray(e){const t=[];for(let n=0;n<=e;n++)t.push(n/e);return t}createFallbackObserver(e,t,n){d.warn(`[ObserverManager] Creating fallback for ${e}Observer`);const i=this.generateId(`fallback_${e}`);let r;if("intersection"===e)r=setInterval(()=>{const e=(Array.isArray(t)?t:[t]).map(e=>({element:e,isIntersecting:this.isElementInViewport(e),intersectionRatio:this.calculateIntersectionRatio(e)}));n(e)},100);return{id:i,disconnect:()=>{r&&clearInterval(r)}}}isElementInViewport(e){const t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=window.innerHeight&&t.right<=window.innerWidth}calculateIntersectionRatio(e){const t=e.getBoundingClientRect(),n=window.innerHeight,i=window.innerWidth,r=Math.min(t.bottom,n)-Math.max(t.top,0),o=Math.min(t.right,i)-Math.max(t.left,0);if(r<=0||o<=0)return 0;const a=r*o,s=t.height*t.width;return s>0?a/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},i=this.getSupportedMimeType(["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"])||n.mimeType,r=new MediaRecorder(e,{...n,mimeType:i}),o=this.generateId("recording"),a=[];return r.ondataavailable=e=>{e.data.size>0&&a.push(e.data)},r.onstop=()=>{const e=new Blob(a,{type:i});this.onRecordingComplete(o,e)},r.start(),d.info(`[MediaManager] Recording started: ${o}`),{id:o,recorder:r,stop:()=>(r.stop(),new Promise(e=>{r.onstop=()=>{const t=new Blob(a,{type:i});e({blob:t,url:URL.createObjectURL(t),size:t.size,type:t.type,download:(e=`recording-${Date.now()}.webm`)=>{this.downloadBlob(t,e)}})}})),pause:()=>r.pause(),resume:()=>r.resume(),get state(){return r.state}}}takePhoto(e,t){const n=document.createElement("video");return n.srcObject=e,n.autoplay=!0,n.muted=!0,new Promise(e=>{n.onloadedmetadata=()=>{t||(t=document.createElement("canvas")),t.width=n.videoWidth,t.height=n.videoHeight;t.getContext("2d").drawImage(n,0,0),t.toBlob(n=>{e({canvas:t,blob:n,url:URL.createObjectURL(n),dataURL:t.toDataURL("image/jpeg",.9),download:(e=`photo-${Date.now()}.jpg`)=>{this.downloadBlob(n,e)}})},"image/jpeg",.9),n.remove()}})}getAudioContext(){if(!this.audioContext){if(!this.support.webAudio)return d.warn("[MediaManager] Web Audio API not supported"),null;this.audioContext=new(window.AudioContext||window.webkitAudioContext),d.info("[MediaManager] Audio context created")}return this.audioContext}createAudioAnalyzer(e,t={}){const n=this.getAudioContext();if(!n)return null;const i=n.createMediaStreamSource(e),r=n.createAnalyser();r.fftSize=t.fftSize||256,r.smoothingTimeConstant=t.smoothing||.8,i.connect(r);const o=r.frequencyBinCount,a=new Uint8Array(o);return{analyzer:r,bufferLength:o,dataArray:a,getFrequencyData:()=>(r.getByteFrequencyData(a),Array.from(a)),getTimeDomainData:()=>(r.getByteTimeDomainData(a),Array.from(a)),getAverageVolume:()=>(r.getByteFrequencyData(a),a.reduce((e,t)=>e+t,0)/o)}}async createPeerConnection(e={}){if(!this.support.webRTC)throw new Error("WebRTC not supported");const t={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],...e},n=new RTCPeerConnection(t),i=this.generateId("rtc");this.activeConnections.set(i,n);const r={id:i,connection:n,onTrack:e=>n.addEventListener("track",e),onIceCandidate:e=>n.addEventListener("icecandidate",e),onConnectionStateChange:e=>n.addEventListener("connectionstatechange",e),addStream:e=>{e.getTracks().forEach(t=>{n.addTrack(t,e)})},createOffer:()=>n.createOffer(),createAnswer:()=>n.createAnswer(),setLocalDescription:e=>n.setLocalDescription(e),setRemoteDescription:e=>n.setRemoteDescription(e),addIceCandidate:e=>n.addIceCandidate(e),close:()=>{n.close(),this.activeConnections.delete(i)},get connectionState(){return n.connectionState},get iceConnectionState(){return n.iceConnectionState}};return d.info(`[MediaManager] Peer connection created: ${i}`),r}async getDevices(){if(!this.support.mediaDevices)return{cameras:[],microphones:[],speakers:[]};try{const e=await navigator.mediaDevices.enumerateDevices();return{cameras:e.filter(e=>"videoinput"===e.kind),microphones:e.filter(e=>"audioinput"===e.kind),speakers:e.filter(e=>"audiooutput"===e.kind),all:e}}catch(e){return d.warn("[MediaManager] Device enumeration failed:",e),{cameras:[],microphones:[],speakers:[]}}}async checkPermissions(){const e={};try{if(navigator.permissions){const t=await navigator.permissions.query({name:"camera"}),n=await navigator.permissions.query({name:"microphone"});e.camera=t.state,e.microphone=n.state}}catch(t){d.warn("[MediaManager] Permission check failed:",t)}return e}stopStream(e){const t=this.activeStreams.get(e);t&&(t.tracks.forEach(e=>e.stop()),this.activeStreams.delete(e),d.info(`[MediaManager] Stream stopped: ${e}`))}stopAllStreams(){this.activeStreams.forEach((e,t)=>{e.tracks.forEach(e=>e.stop())}),this.activeStreams.clear(),d.info("[MediaManager] All streams stopped")}async switchCamera(e){const t=this.activeStreams.get(e);if(!t||"camera"!==t.type)return null;const n="user"===t.constraints.video.facingMode?"environment":"user";return this.stopStream(e),this.getUserCamera({video:{...t.constraints.video,facingMode:n}})}getAudioLevel(e){const t=this.getAudioContext();if(!t)return 0;const n=t.createMediaStreamSource(e),i=t.createAnalyser();n.connect(i);const r=new Uint8Array(i.frequencyBinCount);return i.getByteFrequencyData(r),r.reduce((e,t)=>e+t,0)/r.length}getSupportedMimeType(e){return e.find(e=>MediaRecorder.isTypeSupported(e))}downloadBlob(e,t){const n=URL.createObjectURL(e),i=document.createElement("a");i.href=n,i.download=t,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(n)}generateId(e="media"){return`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}onRecordingComplete(e,t){d.info(`[MediaManager] Recording completed: ${e}, size: ${t.size} bytes`)}applyVideoFilter(e,t){const n=this.activeStreams.get(e);if(!n||"camera"!==n.type)return;const i={none:"none",blur:"blur(2px)",brightness:"brightness(1.2)",contrast:"contrast(1.3)",grayscale:"grayscale(1)",sepia:"sepia(1)",invert:"invert(1)",vintage:"sepia(0.8) contrast(1.4) brightness(1.1)",cool:"hue-rotate(180deg) saturate(1.5)",warm:"hue-rotate(25deg) saturate(1.2)"};return{filter:i[t]||t,apply:e=>{e.style.filter=i[t]||t}}}getStatus(){var e;return{activeStreams:this.activeStreams.size,activeConnections:this.activeConnections.size,audioContextState:(null==(e=this.audioContext)?void 0:e.state)||"none",support:this.support,streams:Array.from(this.activeStreams.entries()).map(([e,t])=>({id:e,type:t.type,tracks:t.tracks.length,active:t.tracks.some(e=>"live"===e.readyState)}))}}}class m{constructor(e={}){t(this,"db",{set:async(e,t,n=null)=>new Promise((i,r)=>{if(!this.db)return void r(new Error("IndexedDB not available"));const o=this.db.transaction(["keyValue"],"readwrite").objectStore("keyValue"),a={key:e,value:t,timestamp:Date.now(),expiration:n?Date.now()+n:null},s=o.put(a);s.onsuccess=()=>{d.info(`[StorageManager] DB set: ${e}`),i(a)},s.onerror=()=>{d.error(`[StorageManager] DB set failed: ${e}`),r(s.error)}}),get:async e=>new Promise((t,n)=>{if(!this.db)return void n(new Error("IndexedDB not available"));const i=this.db.transaction(["keyValue"],"readonly").objectStore("keyValue").get(e);i.onsuccess=()=>{const n=i.result;if(n)return n.expiration&&Date.now()>n.expiration?(this.db.delete(e),void t(null)):void t(n.value);t(null)},i.onerror=()=>{d.error(`[StorageManager] DB get failed: ${e}`),n(i.error)}}),delete:async e=>new Promise((t,n)=>{if(!this.db)return void n(new Error("IndexedDB not available"));const i=this.db.transaction(["keyValue"],"readwrite").objectStore("keyValue").delete(e);i.onsuccess=()=>{d.info(`[StorageManager] DB deleted: ${e}`),t(!0)},i.onerror=()=>{n(i.error)}}),keys:async()=>new Promise((e,t)=>{if(!this.db)return void t(new Error("IndexedDB not available"));const n=this.db.transaction(["keyValue"],"readonly").objectStore("keyValue").getAllKeys();n.onsuccess=()=>{e(n.result)},n.onerror=()=>{t(n.error)}}),clear:async()=>new Promise((e,t)=>{if(!this.db)return void t(new Error("IndexedDB not available"));const n=this.db.transaction(["keyValue"],"readwrite").objectStore("keyValue").clear();n.onsuccess=()=>{d.info("[StorageManager] DB cleared"),e(!0)},n.onerror=()=>{t(n.error)}}),storeFile:async(e,t,n={})=>new Promise((i,r)=>{if(!this.db)return void r(new Error("IndexedDB not available"));const o=this.db.transaction(["files"],"readwrite").objectStore("files"),a={name:e,file:t,type:t.type,size:t.size,timestamp:Date.now(),metadata:n},s=o.add(a);s.onsuccess=()=>{d.info(`[StorageManager] File stored: ${e}`),i({id:s.result,...a})},s.onerror=()=>{r(s.error)}}),getFile:async e=>new Promise((t,n)=>{if(!this.db)return void n(new Error("IndexedDB not available"));const i=this.db.transaction(["files"],"readonly").objectStore("files").get(e);i.onsuccess=()=>{t(i.result)},i.onerror=()=>{n(i.error)}})}),t(this,"cache",{add:async(e,t=null)=>{if(!this.cache)throw new Error("Cache API not available");try{t?await this.cache.put(e,t):await this.cache.add(e),d.info(`[StorageManager] Cache add: ${e}`)}catch(n){throw d.error("[StorageManager] Cache add failed:",n),n}},get:async e=>{if(!this.cache)throw new Error("Cache API not available");try{const t=await this.cache.match(e);return t?d.info(`[StorageManager] Cache hit: ${e}`):d.info(`[StorageManager] Cache miss: ${e}`),t}catch(t){throw d.error("[StorageManager] Cache get failed:",t),t}},delete:async e=>{if(!this.cache)throw new Error("Cache API not available");try{const t=await this.cache.delete(e);return t&&d.info(`[StorageManager] Cache deleted: ${e}`),t}catch(t){throw d.error("[StorageManager] Cache delete failed:",t),t}},keys:async()=>{if(!this.cache)throw new Error("Cache API not available");try{return await this.cache.keys()}catch(e){throw d.error("[StorageManager] Cache keys failed:",e),e}},clear:async()=>{if(!this.cache)throw new Error("Cache API not available");try{const e=await this.cache.keys();await Promise.all(e.map(e=>this.cache.delete(e))),d.info("[StorageManager] Cache cleared")}catch(e){throw d.error("[StorageManager] Cache clear failed:",e),e}}}),t(this,"channel",{create:(e,t=null)=>{if(!this.support.broadcastChannel)return d.warn("[StorageManager] BroadcastChannel not supported"),null;if(this.channels.has(e))return this.channels.get(e);const n=new BroadcastChannel(e);t&&n.addEventListener("message",t);const i={name:e,channel:n,send:t=>{n.postMessage({data:t,timestamp:Date.now(),sender:"current-tab"}),d.info(`[StorageManager] Broadcast sent to ${e}`)},onMessage:e=>{n.addEventListener("message",t=>{e(t.data)})},close:()=>{n.close(),this.channels.delete(e),d.info(`[StorageManager] Channel closed: ${e}`)}};return this.channels.set(e,i),d.info(`[StorageManager] Channel created: ${e}`),i},get:e=>this.channels.get(e)||null,close:e=>{const t=this.channels.get(e);t&&t.close()},closeAll:()=>{this.channels.forEach(e=>e.close()),this.channels.clear(),d.info("[StorageManager] All channels closed")}}),t(this,"locks",{acquire:async(e,t,n={})=>{if(!this.support.webLocks)return d.warn("[StorageManager] Web Locks not supported, executing without lock"),await t();try{return await navigator.locks.request(e,n,async n=>{d.info(`[StorageManager] Lock acquired: ${e}`);const i=await t(n);return d.info(`[StorageManager] Lock released: ${e}`),i})}catch(i){throw d.error(`[StorageManager] Lock failed: ${e}`,i),i}},query:async()=>{if(!this.support.webLocks)return{held:[],pending:[]};try{return await navigator.locks.query()}catch(e){throw d.error("[StorageManager] Lock query failed:",e),e}}}),t(this,"local",{set:(e,t,n=null)=>{if(!this.support.localStorage)return!1;try{const i={value:t,timestamp:Date.now(),expiration:n?Date.now()+n:null};return localStorage.setItem(e,JSON.stringify(i)),!0}catch(i){return d.error("[StorageManager] localStorage set failed:",i),!1}},get:e=>{if(!this.support.localStorage)return null;try{const t=localStorage.getItem(e);if(!t)return null;const n=JSON.parse(t);return n.expiration&&Date.now()>n.expiration?(localStorage.removeItem(e),null):n.value}catch(t){return d.error("[StorageManager] localStorage get failed:",t),null}},delete:e=>!!this.support.localStorage&&(localStorage.removeItem(e),!0),clear:()=>!!this.support.localStorage&&(localStorage.clear(),!0),keys:()=>this.support.localStorage?Object.keys(localStorage):[]}),t(this,"session",{set:(e,t)=>{if(!this.support.sessionStorage)return!1;try{return sessionStorage.setItem(e,JSON.stringify(t)),!0}catch(n){return d.error("[StorageManager] sessionStorage set failed:",n),!1}},get:e=>{if(!this.support.sessionStorage)return null;try{const t=sessionStorage.getItem(e);return t?JSON.parse(t):null}catch(t){return d.error("[StorageManager] sessionStorage get failed:",t),null}},delete:e=>!!this.support.sessionStorage&&(sessionStorage.removeItem(e),!0),clear:()=>!!this.support.sessionStorage&&(sessionStorage.clear(),!0)}),t(this,"smartCache",{set:async(e,t,n={})=>{const{storage:i="indexedDB",expiration:r=null,fallback:o=!0}=n;try{if("indexedDB"===i&&this.db)return await this.db.set(e,t,r);if(o)return this.local.set(e,t,r)}catch(a){if(o)return this.local.set(e,t,r);throw a}},get:async(e,t={})=>{const{storage:n="indexedDB",fallback:i=!0}=t;try{if("indexedDB"===n&&this.db)return await this.db.get(e);if(i)return this.local.get(e)}catch(r){if(i)return this.local.get(e);throw r}},delete:async(e,t={})=>{const{storage:n="indexedDB",fallback:i=!0}=t;try{"indexedDB"===n&&this.db&&await this.db.delete(e),i&&this.local.delete(e)}catch(r){throw i&&this.local.delete(e),r}}}),this.config=e,this.dbName=e.dbName||"AppDatabase",this.dbVersion=e.dbVersion||1,this.db=null,this.cache=null,this.channels=new Map,this.support={indexedDB:"indexedDB"in window,cacheAPI:"caches"in window,webLocks:"locks"in navigator,broadcastChannel:"BroadcastChannel"in window,localStorage:"localStorage"in window,sessionStorage:"sessionStorage"in window},d.info("[StorageManager] Initialized with support:",this.support),this.initializeDB(),this.initializeCache()}async initializeDB(){if(this.support.indexedDB)try{const e=indexedDB.open(this.dbName,this.dbVersion);e.onerror=()=>{d.error("[StorageManager] IndexedDB failed to open")},e.onupgradeneeded=e=>{const t=e.target.result;if(!t.objectStoreNames.contains("keyValue")){t.createObjectStore("keyValue",{keyPath:"key"}).createIndex("timestamp","timestamp",{unique:!1})}if(t.objectStoreNames.contains("cache")||t.createObjectStore("cache",{keyPath:"key"}),!t.objectStoreNames.contains("files")){const e=t.createObjectStore("files",{keyPath:"id",autoIncrement:!0});e.createIndex("name","name",{unique:!1}),e.createIndex("type","type",{unique:!1})}d.info("[StorageManager] IndexedDB schema updated")},e.onsuccess=e=>{this.db=e.target.result,d.info("[StorageManager] IndexedDB connected")}}catch(e){d.error("[StorageManager] IndexedDB initialization failed:",e)}else d.warn("[StorageManager] IndexedDB not supported")}async initializeCache(){if(this.support.cacheAPI)try{this.cache=await caches.open(this.config.cacheName||"app-cache-v1"),d.info("[StorageManager] Cache API initialized")}catch(e){d.error("[StorageManager] Cache API initialization failed:",e)}else d.warn("[StorageManager] Cache API not supported")}async getStorageUsage(){const e={quota:0,usage:0,available:0,percentage:0};if("storage"in navigator&&"estimate"in navigator.storage)try{const t=await navigator.storage.estimate();e.quota=t.quota||0,e.usage=t.usage||0,e.available=e.quota-e.usage,e.percentage=e.quota>0?Math.round(e.usage/e.quota*100):0}catch(t){d.error("[StorageManager] Storage estimate failed:",t)}return e}async cleanup(){d.info("[StorageManager] Starting cleanup...");try{if(this.db){const e=this.db.transaction(["keyValue"],"readwrite").objectStore("keyValue"),t=e.index("timestamp").openCursor();let n=0;t.onsuccess=e=>{const t=e.target.result;if(t){const e=t.value;e.expiration&&Date.now()>e.expiration&&(t.delete(),n++),t.continue()}else d.info(`[StorageManager] Cleanup completed: ${n} expired entries removed`)}}if(this.support.localStorage){const e=Object.keys(localStorage);let t=0;e.forEach(e=>{try{const n=localStorage.getItem(e),i=JSON.parse(n);i.expiration&&Date.now()>i.expiration&&(localStorage.removeItem(e),t++)}catch(n){}}),t>0&&d.info(`[StorageManager] LocalStorage cleanup: ${t} expired entries removed`)}}catch(e){d.error("[StorageManager] Cleanup failed:",e)}}async getStatus(){const e=await this.getStorageUsage();return{support:this.support,usage:e,activeChannels:this.channels.size,dbConnected:!!this.db,cacheConnected:!!this.cache,channelNames:Array.from(this.channels.keys())}}}class p{constructor(e={}){t(this,"geolocation",{getCurrent:(e={})=>new Promise((t,n)=>{if(!this.support.geolocation)return void n(new Error("Geolocation not supported"));const i={enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4,...e};navigator.geolocation.getCurrentPosition(e=>{const n=this.enhanceLocationData(e);d.info("[DeviceManager] Location acquired:",{lat:n.latitude,lng:n.longitude,accuracy:n.accuracy}),t(n)},e=>{d.error("[DeviceManager] Geolocation failed:",e.message),n(e)},i)}),watch:(e,t={})=>{if(!this.support.geolocation)throw new Error("Geolocation not supported");const n={enableHighAccuracy:!0,timeout:3e4,maximumAge:1e4,...t},i=navigator.geolocation.watchPosition(t=>{const n=this.enhanceLocationData(t);e(n)},t=>{d.error("[DeviceManager] Location watch failed:",t.message),e({error:t})},n);return this.activeWatchers.set(`geo_${i}`,{type:"geolocation",id:i,stop:()=>{navigator.geolocation.clearWatch(i),this.activeWatchers.delete(`geo_${i}`)}}),d.info("[DeviceManager] Location watch started:",i),{id:i,stop:()=>{navigator.geolocation.clearWatch(i),this.activeWatchers.delete(`geo_${i}`),d.info("[DeviceManager] Location watch stopped:",i)}}},distance:(e,t)=>{const n=this.toRadians(t.latitude-e.latitude),i=this.toRadians(t.longitude-e.longitude),r=Math.sin(n/2)*Math.sin(n/2)+Math.cos(this.toRadians(e.latitude))*Math.cos(this.toRadians(t.latitude))*Math.sin(i/2)*Math.sin(i/2),o=6371*(2*Math.atan2(Math.sqrt(r),Math.sqrt(1-r)));return{kilometers:o,miles:.621371*o,meters:1e3*o}}}),t(this,"motion",{start:(e,t={})=>{if(!this.support.deviceMotion)throw new Error("Device Motion not supported");const n=t=>{const n={acceleration:t.acceleration,accelerationIncludingGravity:t.accelerationIncludingGravity,rotationRate:t.rotationRate,interval:t.interval,timestamp:t.timeStamp,totalAcceleration:this.calculateTotalAcceleration(t.acceleration),shake:this.detectShake(t.accelerationIncludingGravity),orientation:this.getDeviceOrientation(t)};e(n)};"function"==typeof DeviceMotionEvent.requestPermission?DeviceMotionEvent.requestPermission().then(e=>{"granted"===e&&window.addEventListener("devicemotion",n)}):window.addEventListener("devicemotion",n);const i=this.generateId("motion");return this.activeWatchers.set(i,{type:"motion",handler:n,stop:()=>{window.removeEventListener("devicemotion",n),this.activeWatchers.delete(i)}}),d.info("[DeviceManager] Motion detection started"),{id:i,stop:()=>{window.removeEventListener("devicemotion",n),this.activeWatchers.delete(i),d.info("[DeviceManager] Motion detection stopped")}}},startOrientation:(e,t={})=>{if(!this.support.deviceOrientation)throw new Error("Device Orientation not supported");const n=t=>{const n={alpha:t.alpha,beta:t.beta,gamma:t.gamma,absolute:t.absolute,timestamp:t.timeStamp,compass:this.calculateCompass(t.alpha),tilt:this.calculateTilt(t.beta,t.gamma),rotation:this.getRotationState(t)};e(n)};"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then(e=>{"granted"===e&&window.addEventListener("deviceorientation",n)}):window.addEventListener("deviceorientation",n);const i=this.generateId("orientation");return this.activeWatchers.set(i,{type:"orientation",handler:n,stop:()=>{window.removeEventListener("deviceorientation",n),this.activeWatchers.delete(i)}}),d.info("[DeviceManager] Orientation detection started"),{id:i,stop:()=>{window.removeEventListener("deviceorientation",n),this.activeWatchers.delete(i),d.info("[DeviceManager] Orientation detection stopped")}}}}),t(this,"vibration",{vibrate:e=>{if(!this.support.vibration)return d.warn("[DeviceManager] Vibration not supported"),!1;try{return navigator.vibrate(e),d.info("[DeviceManager] Vibration triggered:",e),!0}catch(t){return d.error("[DeviceManager] Vibration failed:",t),!1}},patterns:{short:200,long:600,double:[200,100,200],triple:[200,100,200,100,200],sos:[100,30,100,30,100,200,200,30,200,30,200,200,100,30,100,30,100],heartbeat:[100,30,100,130,40,30,40,30,100],notification:[200,100,200],success:[100],error:[300,100,300],warning:[200,100,200,100,200]},stop:()=>{this.support.vibration&&(navigator.vibrate(0),d.info("[DeviceManager] Vibration stopped"))},success:()=>this.vibration.vibrate(this.vibration.patterns.success),error:()=>this.vibration.vibrate(this.vibration.patterns.error),warning:()=>this.vibration.vibrate(this.vibration.patterns.warning),notification:()=>this.vibration.vibrate(this.vibration.patterns.notification)}),t(this,"battery",{get:async()=>{if(!this.support.battery)return d.warn("[DeviceManager] Battery API not supported"),null;try{const e=await navigator.getBattery(),t={level:Math.round(100*e.level),charging:e.charging,chargingTime:e.chargingTime,dischargingTime:e.dischargingTime,status:this.getBatteryStatus(e),timeRemaining:this.formatBatteryTime(e)};return d.info("[DeviceManager] Battery status:",t),t}catch(e){return d.error("[DeviceManager] Battery status failed:",e),null}},watch:async e=>{if(!this.support.battery)throw new Error("Battery API not supported");try{const t=await navigator.getBattery(),n=[];["chargingchange","levelchange","chargingtimechange","dischargingtimechange"].forEach(i=>{const r=()=>{const n={level:Math.round(100*t.level),charging:t.charging,chargingTime:t.chargingTime,dischargingTime:t.dischargingTime,status:this.getBatteryStatus(t),timeRemaining:this.formatBatteryTime(t),event:i};e(n)};t.addEventListener(i,r),n.push({event:i,handler:r})});const i=this.generateId("battery");return this.activeWatchers.set(i,{type:"battery",battery:t,handlers:n,stop:()=>{n.forEach(({event:e,handler:n})=>{t.removeEventListener(e,n)}),this.activeWatchers.delete(i)}}),d.info("[DeviceManager] Battery watch started"),{id:i,stop:()=>{n.forEach(({event:e,handler:n})=>{t.removeEventListener(e,n)}),this.activeWatchers.delete(i),d.info("[DeviceManager] Battery watch stopped")}}}catch(t){throw d.error("[DeviceManager] Battery watch failed:",t),t}}}),t(this,"network",{get:()=>{if(!this.support.networkInfo)return d.warn("[DeviceManager] Network Information not supported"),null;const e=navigator.connection||navigator.mozConnection||navigator.webkitConnection;return{effectiveType:e.effectiveType,downlink:e.downlink,rtt:e.rtt,saveData:e.saveData,speed:this.getConnectionSpeed(e),quality:this.getConnectionQuality(e),recommendation:this.getNetworkRecommendation(e)}},watch:e=>{if(!this.support.networkInfo)throw new Error("Network Information not supported");const t=navigator.connection||navigator.mozConnection||navigator.webkitConnection,n=()=>{const n={effectiveType:t.effectiveType,downlink:t.downlink,rtt:t.rtt,saveData:t.saveData,speed:this.getConnectionSpeed(t),quality:this.getConnectionQuality(t),recommendation:this.getNetworkRecommendation(t)};e(n)};t.addEventListener("change",n);const i=this.generateId("network");return this.activeWatchers.set(i,{type:"network",connection:t,handler:n,stop:()=>{t.removeEventListener("change",n),this.activeWatchers.delete(i)}}),d.info("[DeviceManager] Network watch started"),{id:i,stop:()=>{t.removeEventListener("change",n),this.activeWatchers.delete(i),d.info("[DeviceManager] Network watch stopped")}}}}),t(this,"wakeLock",{request:async(e="screen")=>{if(!this.support.wakeLock)return d.warn("[DeviceManager] Wake Lock not supported"),null;try{const t=await navigator.wakeLock.request(e);return d.info(`[DeviceManager] Wake lock acquired: ${e}`),{type:t.type,release:()=>{t.release(),d.info(`[DeviceManager] Wake lock released: ${e}`)}}}catch(t){throw d.error("[DeviceManager] Wake lock failed:",t),t}}}),this.config=e,this.activeWatchers=new Map,this.sensorData=new Map,this.support={geolocation:"geolocation"in navigator,deviceMotion:"DeviceMotionEvent"in window,deviceOrientation:"DeviceOrientationEvent"in window,vibration:"vibrate"in navigator,battery:"getBattery"in navigator,networkInfo:"connection"in navigator||"mozConnection"in navigator||"webkitConnection"in navigator,wakeLock:"wakeLock"in navigator,bluetooth:"bluetooth"in navigator,usb:"usb"in navigator,serial:"serial"in navigator},d.info("[DeviceManager] Initialized with support:",this.support),this.initializeSensors()}initializeSensors(){(this.support.deviceMotion||this.support.deviceOrientation)&&(this.sensorData.set("motionBaseline",{x:0,y:0,z:0}),this.sensorData.set("shakeThreshold",this.config.shakeThreshold||15))}enhanceLocationData(e){return{latitude:e.coords.latitude,longitude:e.coords.longitude,accuracy:e.coords.accuracy,altitude:e.coords.altitude,altitudeAccuracy:e.coords.altitudeAccuracy,heading:e.coords.heading,speed:e.coords.speed,timestamp:e.timestamp,coordinates:`${e.coords.latitude},${e.coords.longitude}`,accuracyLevel:this.getAccuracyLevel(e.coords.accuracy),mapUrl:`https://maps.google.com/?q=${e.coords.latitude},${e.coords.longitude}`}}getAccuracyLevel(e){return e<=5?"excellent":e<=10?"good":e<=50?"fair":"poor"}calculateTotalAcceleration(e){if(!e)return 0;const t=e.x||0,n=e.y||0,i=e.z||0;return Math.sqrt(t*t+n*n+i*i)}detectShake(e){if(!e)return!1;const t=this.sensorData.get("shakeThreshold"),n=Math.abs(e.x||0),i=Math.abs(e.y||0),r=Math.abs(e.z||0);return n>t||i>t||r>t}getDeviceOrientation(e){const t=e.accelerationIncludingGravity;if(!t)return"unknown";const n=t.x||0,i=t.y||0,r=t.z||0;return Math.abs(n)>Math.abs(i)&&Math.abs(n)>Math.abs(r)?n>0?"landscape-right":"landscape-left":Math.abs(i)>Math.abs(r)?i>0?"portrait-upside-down":"portrait":r>0?"face-down":"face-up"}calculateCompass(e){if(null===e)return null;const t=Math.round(e/45)%8;return{degrees:Math.round(e),direction:["N","NE","E","SE","S","SW","W","NW"][t],cardinal:this.getCardinalDirection(e)}}getCardinalDirection(e){return e>=337.5||e<22.5?"North":e>=22.5&&e<67.5?"Northeast":e>=67.5&&e<112.5?"East":e>=112.5&&e<157.5?"Southeast":e>=157.5&&e<202.5?"South":e>=202.5&&e<247.5?"Southwest":e>=247.5&&e<292.5?"West":e>=292.5&&e<337.5?"Northwest":"Unknown"}calculateTilt(e,t){return{x:Math.round(e||0),y:Math.round(t||0),magnitude:Math.round(Math.sqrt((e||0)**2+(t||0)**2))}}getRotationState(e){const{alpha:t,beta:n,gamma:i}=e,r=Math.abs(n)>10||Math.abs(i)>10;return{isRotating:r,intensity:r?Math.max(Math.abs(n),Math.abs(i)):0}}getBatteryStatus(e){const t=100*e.level;return e.charging?"charging":t<=10?"critical":t<=20?"low":t<=50?"medium":"high"}formatBatteryTime(e){const t=e.charging?e.chargingTime:e.dischargingTime;if(t===1/0||isNaN(t))return"Unknown";return`${Math.floor(t/3600)}h ${Math.floor(t%3600/60)}m`}getConnectionSpeed(e){const t=e.downlink;return t>=10?"fast":t>=1.5?"good":t>=.5?"slow":"very-slow"}getConnectionQuality(e){switch(e.effectiveType){case"4g":return"excellent";case"3g":return"good";case"2g":return"poor";case"slow-2g":return"very-poor";default:return"unknown"}}getNetworkRecommendation(e){switch(this.getConnectionQuality(e)){case"excellent":return"Full quality content recommended";case"good":return"Moderate quality content recommended";case"poor":return"Light content only, avoid large files";case"very-poor":return"Text-only content recommended";default:return"Monitor connection quality"}}toRadians(e){return e*(Math.PI/180)}generateId(e="device"){return`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}stopAllWatchers(){this.activeWatchers.forEach(e=>{e.stop()}),this.activeWatchers.clear(),d.info("[DeviceManager] All watchers stopped")}getCapabilities(){return{support:this.support,activeWatchers:this.activeWatchers.size,watcherTypes:Array.from(this.activeWatchers.values()).map(e=>e.type)}}}class g{constructor(e={}){t(this,"effects",{fadeIn:(e=300)=>[{opacity:0},{opacity:1}],slideInLeft:(e="100px",t=300)=>[{transform:`translateX(-${e})`,opacity:0},{transform:"translateX(0)",opacity:1}],slideInRight:(e="100px",t=300)=>[{transform:`translateX(${e})`,opacity:0},{transform:"translateX(0)",opacity:1}],slideInUp:(e="100px",t=300)=>[{transform:`translateY(${e})`,opacity:0},{transform:"translateY(0)",opacity:1}],slideInDown:(e="100px",t=300)=>[{transform:`translateY(-${e})`,opacity:0},{transform:"translateY(0)",opacity:1}],scaleIn:(e=.8,t=300)=>[{transform:`scale(${e})`,opacity:0},{transform:"scale(1)",opacity:1}],rotateIn:(e="-180deg",t=600)=>[{transform:`rotate(${e})`,opacity:0},{transform:"rotate(0deg)",opacity:1}],fadeOut:(e=300)=>[{opacity:1},{opacity:0}],slideOutLeft:(e="100px",t=300)=>[{transform:"translateX(0)",opacity:1},{transform:`translateX(-${e})`,opacity:0}],slideOutRight:(e="100px",t=300)=>[{transform:"translateX(0)",opacity:1},{transform:`translateX(${e})`,opacity:0}],scaleOut:(e=.8,t=300)=>[{transform:"scale(1)",opacity:1},{transform:`scale(${e})`,opacity:0}],bounce:(e="20px",t=600)=>[{transform:"translateY(0)"},{transform:`translateY(-${e})`,offset:.25},{transform:"translateY(0)",offset:.5},{transform:`translateY(-${e})`,offset:.75},{transform:"translateY(0)"}],pulse:(e=1.1,t=600)=>[{transform:"scale(1)"},{transform:`scale(${e})`,offset:.5},{transform:"scale(1)"}],shake:(e="10px",t=600)=>[{transform:"translateX(0)"},{transform:`translateX(-${e})`,offset:.1},{transform:`translateX(${e})`,offset:.2},{transform:`translateX(-${e})`,offset:.3},{transform:`translateX(${e})`,offset:.4},{transform:`translateX(-${e})`,offset:.5},{transform:`translateX(${e})`,offset:.6},{transform:`translateX(-${e})`,offset:.7},{transform:`translateX(${e})`,offset:.8},{transform:`translateX(-${e})`,offset:.9},{transform:"translateX(0)"}],rubberBand:(e=1e3)=>[{transform:"scale(1)"},{transform:"scale(1.25, 0.75)",offset:.3},{transform:"scale(0.75, 1.25)",offset:.4},{transform:"scale(1.15, 0.85)",offset:.5},{transform:"scale(0.95, 1.05)",offset:.65},{transform:"scale(1.05, 0.95)",offset:.75},{transform:"scale(1)"}],spin:(e=1e3)=>[{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],heartbeat:(e=1.3,t=1e3)=>[{transform:"scale(1)"},{transform:`scale(${e})`,offset:.14},{transform:"scale(1)",offset:.28},{transform:`scale(${e})`,offset:.42},{transform:"scale(1)",offset:.7}]}),t(this,"easings",{linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",easeInQuad:"cubic-bezier(0.25, 0.46, 0.45, 0.94)",easeOutQuad:"cubic-bezier(0.25, 0.46, 0.45, 0.94)",easeInOutQuad:"cubic-bezier(0.455, 0.03, 0.515, 0.955)",easeInCubic:"cubic-bezier(0.32, 0, 0.67, 0)",easeOutCubic:"cubic-bezier(0.33, 1, 0.68, 1)",easeInOutCubic:"cubic-bezier(0.65, 0, 0.35, 1)",easeInQuart:"cubic-bezier(0.5, 0, 0.75, 0)",easeOutQuart:"cubic-bezier(0.25, 1, 0.5, 1)",easeInOutQuart:"cubic-bezier(0.76, 0, 0.24, 1)",easeOutBack:"cubic-bezier(0.34, 1.56, 0.64, 1)",easeInBack:"cubic-bezier(0.36, 0, 0.66, -0.56)",easeInOutBack:"cubic-bezier(0.68, -0.6, 0.32, 1.6)"}),this.config=e,this.activeAnimations=new Map,this.animationGroups=new Map,this.defaultEasing=e.easing||"ease-out",this.defaultDuration=e.duration||300,this.supported="animate"in Element.prototype,this.supported?d.info("[AnimationManager] Initialized with Web Animations API support"):d.warn("[AnimationManager] Web Animations API not supported, using fallbacks")}animate(e,t,n={}){if(!e||!t)return d.warn("[AnimationManager] Missing element or keyframes"),null;const i={duration:this.defaultDuration,easing:this.defaultEasing,fill:"forwards",...n},r=this.generateId();if(this.supported){const n=e.animate(t,i),o=this.enhanceAnimation(n,r,{element:e,keyframes:t,options:i});return this.activeAnimations.set(r,o),n.addEventListener("finish",()=>{this.activeAnimations.delete(r)}),d.info(`[AnimationManager] Animation started: ${r}`),o}return this.fallbackAnimate(e,t,i,r)}keyframes(e){if(Array.isArray(e))return e;if("object"==typeof e){const t=[];return Object.keys(e).sort((e,t)=>parseFloat(e.replace("%",""))-parseFloat(t.replace("%",""))).forEach(n=>{const i=parseFloat(n.replace("%",""))/100;t.push({...e[n],offset:i})}),t}return e}fadeIn(e,t={}){return this.animate(e,this.effects.fadeIn(),{duration:300,easing:this.easings.easeOut,...t})}fadeOut(e,t={}){return this.animate(e,this.effects.fadeOut(),{duration:300,easing:this.easings.easeIn,...t})}slideIn(e,t="up",n={}){return this.animate(e,this.effects[{up:"slideInUp",down:"slideInDown",left:"slideInLeft",right:"slideInRight"}[t]](),{duration:400,easing:this.easings.easeOutBack,...n})}bounce(e,t={}){return this.animate(e,this.effects.bounce(),{duration:600,easing:this.easings.easeInOut,...t})}pulse(e,t={}){return this.animate(e,this.effects.pulse(),{duration:600,easing:this.easings.easeInOut,iterations:1/0,...t})}group(e,t={}){const n=this.generateId("group"),i=[];e.forEach(({element:e,keyframes:n,animationOptions:r={}})=>{const o=this.animate(e,n,{...r,...t});o&&o.finished&&i.push(o.finished)});const r={id:n,finished:Promise.all(i),play:()=>{e.forEach(e=>{e.animation&&e.animation.play()})},pause:()=>{e.forEach(e=>{e.animation&&e.animation.pause()})},reverse:()=>{e.forEach(e=>{e.animation&&e.animation.reverse()})},cancel:()=>{e.forEach(e=>{e.animation&&e.animation.cancel()})}};return this.animationGroups.set(n,r),r}stagger(e,t,n={}){const i=n.staggerDelay||100,r=[];return e.forEach((e,o)=>{const a=o*i,s=this.animate(e,t,{...n,delay:a});r.push({element:e,animation:s})}),this.group(r.map(({element:e,animation:n})=>({element:e,keyframes:t,animation:n})))}timeline(e){const t=this.generateId("timeline");let n=0;const i=[];return e.forEach(e=>{var t;const r=void 0!==e.at?e.at:n,o=this.animate(e.element,e.keyframes,{...e.options,delay:r});i.push(o),void 0===e.at&&(n+=(null==(t=e.options)?void 0:t.duration)||this.defaultDuration)}),{id:t,animations:i,finished:Promise.all(i.map(e=>e.finished)),play:()=>i.forEach(e=>e.play()),pause:()=>i.forEach(e=>e.pause()),reverse:()=>i.forEach(e=>e.reverse()),cancel:()=>i.forEach(e=>e.cancel())}}onScroll(e,t,n={}){const i=n.trigger||e,r=n.start||0,o=n.end||1,a=new IntersectionObserver(i=>{i.forEach(i=>{if(i.isIntersecting){Math.min(Math.max((i.intersectionRatio-r)/(o-r),0),1)>=0&&this.animate(e,t,{...n,duration:n.duration||this.defaultDuration})}})},{threshold:this.createThresholdArray(20)});return a.observe(i),{observer:a,disconnect:()=>a.disconnect()}}enhanceAnimation(e,t,n){return{id:t,animation:e,metadata:n,play:()=>e.play(),pause:()=>e.pause(),reverse:()=>e.reverse(),cancel:()=>e.cancel(),finish:()=>e.finish(),get currentTime(){return e.currentTime},set currentTime(t){e.currentTime=t},get playbackRate(){return e.playbackRate},set playbackRate(t){e.playbackRate=t},get playState(){return e.playState},get finished(){return e.finished},seek(t){e.currentTime=e.effect.getTiming().duration*t},setProgress(e){this.seek(Math.max(0,Math.min(1,e)))},onFinish(t){e.addEventListener("finish",t)},onCancel(t){e.addEventListener("cancel",t)}}}fallbackAnimate(e,t,n,i){d.info("[AnimationManager] Using CSS fallback animation");const r=t[t.length-1];return e.style.transition=`all ${n.duration}ms ${n.easing}`,Object.assign(e.style,r),{id:i,finished:new Promise(e=>setTimeout(e,n.duration)),play:()=>{},pause:()=>{},cancel:()=>{e.style.transition=""}}}generateId(e="anim"){return`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}createThresholdArray(e){const t=[];for(let n=0;n<=e;n++)t.push(n/e);return t}getActiveAnimations(){return Array.from(this.activeAnimations.entries()).map(([e,t])=>({id:e,playState:t.playState,currentTime:t.currentTime,metadata:t.metadata}))}cancelAll(){this.activeAnimations.forEach(e=>{e.cancel()}),this.activeAnimations.clear(),d.info("[AnimationManager] All animations cancelled")}pauseAll(){this.activeAnimations.forEach(e=>{e.pause()}),d.info("[AnimationManager] All animations paused")}resumeAll(){this.activeAnimations.forEach(e=>{"paused"===e.playState&&e.play()}),d.info("[AnimationManager] All animations resumed")}}class f{constructor(e={}){t(this,"web",{create:(e,t={})=>{if(!this.support.webWorkers)throw new Error("Web Workers not supported");let n;const i=this.generateId("worker");try{if("string"==typeof e)n=new Worker(e,t);else if("function"==typeof e){const i=this.createWorkerBlob(e);n=new Worker(URL.createObjectURL(i),t)}else{if(!(e instanceof Blob))throw new Error("Invalid script type");n=new Worker(URL.createObjectURL(e),t)}const r={id:i,worker:n,send:(e,t=null)=>{t?n.postMessage(e,t):n.postMessage(e),d.info(`[WorkerManager] Message sent to worker: ${i}`)},onMessage:e=>{n.addEventListener("message",t=>{e(t.data,t)})},onError:e=>{n.addEventListener("error",e),n.addEventListener("messageerror",e)},terminate:()=>{n.terminate(),this.activeWorkers.delete(i),d.info(`[WorkerManager] Worker terminated: ${i}`)},execute:(e,t=null)=>new Promise((i,r)=>{const o=this.generateId("msg"),a=e=>{e.data.id===o&&(n.removeEventListener("message",a),e.data.error?r(new Error(e.data.error)):i(e.data.result))};n.addEventListener("message",a),n.postMessage({id:o,type:"execute",function:e.toString(),data:t}),setTimeout(()=>{n.removeEventListener("message",a),r(new Error("Worker execution timeout"))},3e4)})};return this.activeWorkers.set(i,r),d.info(`[WorkerManager] Web Worker created: ${i}`),r}catch(r){throw d.error("[WorkerManager] Worker creation failed:",r),r}},createPool:(e,t=navigator.hardwareConcurrency||4,n={})=>{const i=[];for(let a=0;a<t;a++)i.push(this.web.create(e,n));let r=0;const o={workers:i,execute:async(e,t=null)=>{const n=i[r];return r=(r+1)%i.length,n.execute(e,t)},broadcast:e=>{i.forEach(t=>{t.send(e)})},terminate:()=>{i.forEach(e=>{e.terminate()}),i.length=0,d.info("[WorkerManager] Worker pool terminated")}};return d.info(`[WorkerManager] Worker pool created with ${t} workers`),o},tasks:{compute:(e,t)=>this.web.create("\n self.addEventListener('message', function(e) {\n const { id, function: fnString, data } = e.data;\n \n try {\n const fn = new Function('return ' + fnString)();\n const result = fn(data);\n self.postMessage({ id, result });\n } catch (error) {\n self.postMessage({ id, error: error.message });\n }\n });\n ").execute(e,t),processImage:(e,t)=>this.web.create("\n self.addEventListener('message', function(e) {\n const { id, data: { imageData, filters } } = e.data;\n \n try {\n const pixels = imageData.data;\n \n for (let i = 0; i < pixels.length; i += 4) {\n // Apply filters\n if (filters.brightness) {\n pixels[i] *= filters.brightness; // R\n pixels[i + 1] *= filters.brightness; // G\n pixels[i + 2] *= filters.brightness; // B\n }\n \n if (filters.contrast) {\n const factor = (259 * (filters.contrast * 255 + 255)) / (255 * (259 - filters.contrast * 255));\n pixels[i] = factor * (pixels[i] - 128) + 128;\n pixels[i + 1] = factor * (pixels[i + 1] - 128) + 128;\n pixels[i + 2] = factor * (pixels[i + 2] - 128) + 128;\n }\n \n if (filters.grayscale) {\n const gray = 0.299 * pixels[i] + 0.587 * pixels[i + 1] + 0.114 * pixels[i + 2];\n pixels[i] = gray;\n pixels[i + 1] = gray;\n pixels[i + 2] = gray;\n }\n }\n \n self.postMessage({ id, result: imageData }, [imageData.data.buffer]);\n } catch (error) {\n self.postMessage({ id, error: error.message });\n }\n });\n ").execute(null,{imageData:e,filters:t}),processData:(e,t)=>this.web.create("\n self.addEventListener('message', function(e) {\n const { id, data, function: processorString } = e.data;\n \n try {\n const processor = new Function('return ' + processorString)();\n const result = data.map(processor);\n self.postMessage({ id, result });\n } catch (error) {\n self.postMessage({ id, error: error.message });\n }\n });\n ").execute(t,e)}}),t(this,"service",{register:async(e,t={})=>{if(!this.support.serviceWorker)throw new Error("Service Worker not supported");try{const n=await navigator.serviceWorker.register(e,t);return d.info("[WorkerManager] Service Worker registered:",e),{registration:n,scope:n.scope,update:()=>n.update(),unregister:()=>n.unregister(),postMessage:e=>{n.active&&n.active.postMessage(e)},onUpdate:e=>{n.addEventListener("updatefound",()=>{const t=n.installing;t.addEventListener("statechange",()=>{"installed"===t.state&&navigator.serviceWorker.controller&&e(t)})})},checkForUpdates:()=>n.update()}}catch(n){throw d.error("[WorkerManager] Service Worker registration failed:",n),n}},getRegistration:async(e="/")=>{if(!this.support.serviceWorker)return null;try{return await navigator.serviceWorker.getRegistration(e)}catch(t){return d.error("[WorkerManager] Get registration failed:",t),null}},getRegistrations:async()=>{if(!this.support.serviceWorker)return[];try{return await navigator.serviceWorker.getRegistrations()}catch(e){return d.error("[WorkerManager] Get registrations failed:",e),[]}}}),t(this,"shared",{create:(e,t={})=>{if(!this.support.sharedWorker)throw new Error("Shared Worker not supported");try{const n=new SharedWorker(e,t),i=n.port,r=this.generateId("shared");i.start();const o={id:r,worker:n,port:i,send:(e,t=null)=>{t?i.postMessage(e,t):i.postMessage(e)},onMessage:e=>{i.addEventListener("message",t=>{e(t.data,t)})},onError:e=>{n.addEventListener("error",e),i.addEventListener("messageerror",e)},close:()=>{i.close(),this.activeWorkers.delete(r),d.info(`[WorkerManager] Shared Worker closed: ${r}`)}};return this.activeWorkers.set(r,o),d.info(`[WorkerManager] Shared Worker created: ${r}`),o}catch(n){throw d.error("[WorkerManager] Shared Worker creation failed:",n),n}}}),t(this,"offscreen",{create:(e,t=null)=>{if(!this.support.offscreenCanvas)throw new Error("Offscreen Canvas not supported");try{const n=e.transferControlToOffscreen(),i=t||"\n self.addEventListener('message', function(e) {\n const { canvas, type, data } = e.data;\n \n if (type === 'init') {\n self.canvas = canvas;\n self.ctx = canvas.getContext('2d');\n }\n \n if (type === 'draw' && self.ctx) {\n // Basic drawing operations\n const { operations } = data;\n \n operations.forEach(op => {\n switch (op.type) {\n case 'fillRect':\n self.ctx.fillRect(...op.args);\n break;\n case 'strokeRect':\n self.ctx.strokeRect(...op.args);\n break;\n case 'fillText':\n self.ctx.fillText(...op.args);\n break;\n case 'setFillStyle':\n self.ctx.fillStyle = op.value;\n break;\n case 'setStrokeStyle':\n self.ctx.strokeStyle = op.value;\n break;\n }\n });\n }\n });\n ",r=this.web.create(i);return r.send({type:"init",canvas:n},[n]),{worker:r,draw:e=>{r.send({type:"draw",data:{operations:e}})},send:e=>r.send(e),onMessage:e=>r.onMessage(e),terminate:()=>r.terminate()}}catch(n){throw d.error("[WorkerManager] Offscreen Canvas creation failed:",n),n}}}),t(this,"utils",{benchmark:async(e,t,n=1e3)=>{const i=this.web.create(()=>{self.addEventListener("message",e=>{const{id:t,function:n,data:i,iterations:r}=e.data;try{const e=new Function("return "+n)(),o=performance.now();for(let t=0;t<r;t++)e(i);const a=performance.now()-o,s=a/r;self.postMessage({id:t,result:{totalTime:a,avgTime:s,iterations:r,opsPerSecond:1e3/s}})}catch(o){self.postMessage({id:t,error:o.message})}})}),r=await i.execute(e,t,n);return i.terminate(),r},parallelMap:async(e,t,n=null)=>{const i=n||Math.ceil(e.length/(navigator.hardwareConcurrency||4)),r=this.web.createPool(()=>{self.addEventListener("message",e=>{const{id:t,data:{chunk:n,function:i}}=e.data;try{const e=new Function("return "+i)(),r=n.map(e);self.postMessage({id:t,result:r})}catch(r){self.postMessage({id:t,error:r.message})}})}),o=[];for(let s=0;s<e.length;s+=i){const n=e.slice(s,s+i);o.push(r.execute(t,n))}const a=await Promise.all(o);return r.terminate(),a.flat()}}),this.config=e,this.activeWorkers=new Map,this.messageHandlers=new Map,this.workerScripts=new Map,this.support={webWorkers:"Worker"in window,serviceWorker:"serviceWorker"in navigator,sharedWorker:"SharedWorker"in window,offscreenCanvas:"OffscreenCanvas"in window},d.info("[WorkerManager] Initialized with support:",this.support)}createWorkerBlob(e){const t=`\n (function() {\n const workerFunction = ${e.toString()};\n \n if (typeof workerFunction === 'function') {\n // If function expects to be called immediately\n if (workerFunction.length === 0) {\n workerFunction();\n }\n }\n \n // Standard worker message handling\n self.addEventListener('message', function(e) {\n if (e.data.type === 'execute' && e.data.function) {\n try {\n const fn = new Function('return ' + e.data.function)();\n const result = fn(e.data.data);\n self.postMessage({ \n id: e.data.id, \n result \n });\n } catch (error) {\n self.postMessage({ \n id: e.data.id, \n error: error.message \n });\n }\n }\n });\n })();\n `;return new Blob([t],{type:"application/javascript"})}generateId(e="worker"){return`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}terminateAll(){this.activeWorkers.forEach(e=>{e.terminate?e.terminate():e.close&&e.close()}),this.activeWorkers.clear(),d.info("[WorkerManager] All workers terminated")}getStats(){const e=Array.from(this.activeWorkers.values());return{total:e.length,byType:e.reduce((e,t)=>{const n=t.id.split("_")[0];return e[n]=(e[n]||0)+1,e},{}),support:this.support,hardwareConcurrency:navigator.hardwareConcurrency||"unknown"}}}class y{constructor(e={}){var n,i,r;t(this,"timing",{mark:(e,t={})=>{if(!this.support.userTiming)return d.warn("[PerformanceManager] User Timing not supported"),null;try{return performance.mark(e,t),this.marks.set(e,{name:e,timestamp:performance.now(),options:t}),d.info(`[PerformanceManager] Mark created: ${e}`),this.marks.get(e)}catch(n){return d.error("[PerformanceManager] Mark creation failed:",n),null}},measure:(e,t,n,i={})=>{if(!this.support.userTiming)return d.warn("[PerformanceManager] User Timing not supported"),null;try{performance.measure(e,t,n,i);const r=performance.getEntriesByName(e,"measure")[0],o={name:e,startTime:r.startTime,duration:r.duration,startMark:t,endMark:n,options:i};return this.measures.set(e,o),d.info(`[PerformanceManager] Measure created: ${e} (${o.duration.toFixed(2)}ms)`),o}catch(r){return d.error("[PerformanceManager] Measure creation failed:",r),null}},clear:(e=null)=>{if(this.support.userTiming)try{e?(performance.clearMarks(e),performance.clearMeasures(e),this.marks.delete(e),this.measures.delete(e)):(performance.clearMarks(),performance.clearMeasures(),this.marks.clear(),this.measures.clear()),d.info(`[PerformanceManager] Cleared: ${e||"all"}`)}catch(t){d.error("[PerformanceManager] Clear failed:",t)}},getMarks:()=>this.support.userTiming?Array.from(this.marks.values()):[],getMeasures:()=>this.support.userTiming?Array.from(this.measures.values()):[]}),t(this,"navigation",{get:()=>{if(!this.support.navigation)return this.getLegacyNavigationTiming();try{const e=performance.getEntriesByType("navigation")[0];return e?{redirect:e.redirectEnd-e.redirectStart,dns:e.domainLookupEnd-e.domainLookupStart,connect:e.connectEnd-e.connectStart,ssl:e.connectEnd-e.secureConnectionStart,ttfb:e.responseStart-e.requestStart,download:e.responseEnd-e.responseStart,domProcessing:e.domContentLoadedEventStart-e.responseEnd,domComplete:e.domComplete-e.domContentLoadedEventStart,loadComplete:e.loadEventEnd-e.loadEventStart,totalTime:e.loadEventEnd-e.startTime,navigationStart:e.startTime,unloadTime:e.unloadEventEnd-e.unloadEventStart,redirectCount:e.redirectCount,transferSize:e.transferSize,encodedBodySize:e.encodedBodySize,decodedBodySize:e.decodedBodySize,connectionInfo:{nextHopProtocol:e.nextHopProtocol,renderBlockingStatus:e.renderBlockingStatus}}:null}catch(e){return d.error("[PerformanceManager] Navigation timing failed:",e),null}},getInsights:()=>{const e=this.navigation.get();return e?{insights:{serverResponseTime:this.getInsight("ttfb",e.ttfb,200,500),domProcessing:this.getInsight("domProcessing",e.domProcessing,500,1e3),totalLoadTime:this.getInsight("totalTime",e.totalTime,2e3,4e3),transferEfficiency:this.getTransferEfficiency(e)},recommendations:this.getNavigationRecommendations(e)}:null}}),t(this,"resources",{get:(e=null)=>{if(!this.support.resourceTiming)return d.warn("[PerformanceManager] Resource Timing not supported"),[];try{const t=performance.getEntriesByType("resource").map(e=>({name:e.name,type:this.getResourceType(e),startTime:e.startTime,duration:e.duration,size:{transfer:e.transferSize,encoded:e.encodedBodySize,decoded:e.decodedBodySize},timing:{redirect:e.redirectEnd-e.redirectStart,dns:e.domainLookupEnd-e.domainLookupStart,connect:e.connectEnd-e.connectStart,ssl:e.connectEnd-e.secureConnectionStart,ttfb:e.responseStart-e.requestStart,download:e.responseEnd-e.responseStart},protocol:e.nextHopProtocol,cached:0===e.transferSize&&e.decodedBodySize>0}));return e?t.filter(t=>t.type===e):t}catch(t){return d.error("[PerformanceManager] Resource timing failed:",t),[]}},getSummary:()=>{const e=this.resources.get(),t={total:e.length,types:{},totalSize:0,totalDuration:0,cached:0,slowResources:[]};return e.forEach(e=>{const n=e.type;t.types[n]||(t.types[n]={count:0,size:0,duration:0}),t.types[n].count++,t.types[n].size+=e.size.transfer,t.types[n].duration+=e.duration,t.totalSize+=e.size.transfer,t.totalDuration+=e.duration,e.cached&&t.cached++,e.duration>1e3&&t.slowResources.push(e)}),t}}),t(this,"vitals",{start:(e=null)=>{const t={};return this.observePaint(n=>{n.forEach(n=>{"first-contentful-paint"===n.name&&(t.fcp=n.startTime,this.checkThreshold("fcp",n.startTime),e&&e("fcp",n.startTime))})}),this.observeLCP(n=>{n.forEach(n=>{t.lcp=n.startTime,this.checkThreshold("lcp",n.startTime),e&&e("lcp",n.startTime)})}),this.observeFID(n=>{n.forEach(n=>{t.fid=n.processingStart-n.startTime,this.checkThreshold("fid",t.fid),e&&e("fid",t.fid)})}),this.observeCLS(n=>{let i=0;n.forEach(e=>{e.hadRecentInput||(i+=e.value)}),t.cls=i,this.checkThreshold("cls",i),e&&e("cls",i)}),t},get:()=>({fcp:this.getMetric("fcp"),lcp:this.getMetric("lcp"),fid:this.getMetric("fid"),cls:this.getMetric("cls"),ratings:{fcp:this.getRating("fcp",this.getMetric("fcp")),lcp:this.getRating("lcp",this.getMetric("lcp")),fid:this.getRating("fid",this.getMetric("fid")),cls:this.getRating("cls",this.getMetric("cls"))}})}),t(this,"memory",{get:()=>{if(!this.support.memory)return d.warn("[PerformanceManager] Memory API not supported"),null;try{const e=performance.memory;return{used:e.usedJSHeapSize,total:e.totalJSHeapSize,limit:e.jsHeapSizeLimit,percentage:e.usedJSHeapSize/e.jsHeapSizeLimit*100,formatted:{used:this.formatBytes(e.usedJSHeapSize),total:this.formatBytes(e.totalJSHeapSize),limit:this.formatBytes(e.jsHeapSizeLimit)}}}catch(e){return d.error("[PerformanceManager] Memory get failed:",e),null}},monitor:(e,t=5e3)=>{if(!this.support.memory)return null;const n=setInterval(()=>{const t=this.memory.get();t&&(e(t),t.percentage>80&&d.warn("[PerformanceManager] High memory usage detected:",t.percentage.toFixed(1)+"%"))},t);return{stop:()=>clearInterval(n)}}}),t(this,"longTasks",{start:(e=null)=>{if(!this.support.longTask)return d.warn("[PerformanceManager] Long Task API not supported"),null;try{const t=new PerformanceObserver(t=>{t.getEntries().forEach(t=>{const n={duration:t.duration,startTime:t.startTime,name:t.name,attribution:t.attribution||[]};d.warn("[PerformanceManager] Long task detected:",n),e&&e(n)})});t.observe({entryTypes:["longtask"]});const n=this.generateId("longtask");return this.observers.set(n,t),{id:n,stop:()=>{t.disconnect(),this.observers.delete(n)}}}catch(t){return d.error("[PerformanceManager] Long task monitoring failed:",t),null}}}),t(this,"optimize",{deferScript:(e,t=null)=>{const n=document.createElement("script");return n.src=e,n.defer=!0,t&&(n.onload=t),document.head.appendChild(n),n},preload:(e,t,n=!1)=>{const i=document.createElement("link");return i.rel="preload",i.href=e,i.as=t,n&&(i.crossOrigin="anonymous"),document.head.appendChild(i),i},prefetch:e=>{const t=document.createElement("link");return t.rel="prefetch",t.href=e,document.head.appendChild(t),t},lazyImages:(e="img[data-src]")=>{if("IntersectionObserver"in window){const t=document.querySelectorAll(e),n=new IntersectionObserver(e=>{e.forEach(e=>{if(e.isIntersecting){const t=e.target;t.src=t.dataset.src,t.classList.remove("lazy"),n.unobserve(t)}})});return t.forEach(e=>n.observe(e)),n}document.querySelectorAll(e).forEach(e=>{e.src=e.dataset.src,e.classList.remove("lazy")})},analyzeBundles:()=>{const e=Array.from(document.querySelectorAll("script[src]")),t=Array.from(document.querySelectorAll('link[rel="stylesheet"]')),n={scripts:e.map(e=>({src:e.src,async:e.async,defer:e.defer})),styles:t.map(e=>({href:e.href,media:e.media})),recommendations:[]};return e.length>10&&n.recommendations.push("Consider bundling JavaScript files"),t.length>5&&n.recommendations.push("Consider bundling CSS files"),n}}),this.config=e,this.marks=new Map,this.measures=new Map,this.observers=new Map,this.metrics=new Map,this.thresholds={fcp:2e3,lcp:2500,fid:100,cls:.1,...e.thresholds},this.support={performance:"performance"in window,timing:"timing"in(window.performance||{}),navigation:"navigation"in(window.performance||{}),observer:"PerformanceObserver"in window,memory:"memory"in(window.performance||{}),userTiming:"mark"in(window.performance||{}),resourceTiming:"getEntriesByType"in(window.performance||{}),paintTiming:"PerformanceObserver"in window&&(null==(n=PerformanceObserver.supportedEntryTypes)?void 0:n.includes("paint")),layoutInstability:"PerformanceObserver"in window&&(null==(i=PerformanceObserver.supportedEntryTypes)?void 0:i.includes("layout-shift")),longTask:"PerformanceObserver"in window&&(null==(r=PerformanceObserver.supportedEntryTypes)?void 0:r.includes("longtask"))},d.info("[PerformanceManager] Initialized with support:",this.support),this.startCoreMetrics()}startCoreMetrics(){this.vitals.start((e,t)=>{this.setMetric(e,t)}),this.support.memory&&this.memory.monitor(e=>{this.setMetric("memory",e)})}observePaint(e){if(this.support.paintTiming)try{const t=new PerformanceObserver(t=>{e(t.getEntries())});return t.observe({entryTypes:["paint"]}),t}catch(t){d.error("[PerformanceManager] Paint observer failed:",t)}}observeLCP(e){if(this.support.observer)try{const t=new PerformanceObserver(t=>{e(t.getEntries())});return t.observe({entryTypes:["largest-contentful-paint"]}),t}catch(t){d.error("[PerformanceManager] LCP observer failed:",t)}}observeFID(e){if(this.support.observer)try{const t=new PerformanceObserver(t=>{e(t.getEntries())});return t.observe({entryTypes:["first-input"]}),t}catch(t){d.error("[PerformanceManager] FID observer failed:",t)}}observeCLS(e){if(this.support.layoutInstability)try{const t=new PerformanceObserver(t=>{e(t.getEntries())});return t.observe({entryTypes:["layout-shift"]}),t}catch(t){d.error("[PerformanceManager] CLS observer failed:",t)}}getLegacyNavigationTiming(){if(!this.support.timing)return null;const e=performance.timing,t=e.navigationStart;return{redirect:e.redirectEnd-e.redirectStart,dns:e.domainLookupEnd-e.domainLookupStart,connect:e.connectEnd-e.connectStart,ssl:e.connectEnd-e.secureConnectionStart,ttfb:e.responseStart-e.requestStart,download:e.responseEnd-e.responseStart,domProcessing:e.domContentLoadedEventStart-e.responseEnd,domComplete:e.domComplete-e.domContentLoadedEventStart,loadComplete:e.loadEventEnd-e.loadEventStart,totalTime:e.loadEventEnd-t}}getResourceType(e){return{js:"script",css:"stylesheet",png:"image",jpg:"image",jpeg:"image",gif:"image",svg:"image",webp:"image",woff:"font",woff2:"font",ttf:"font",eot:"font",json:"fetch",xml:"fetch"}[new URL(e.name).pathname.split(".").pop().toLowerCase()]||e.initiatorType||"other"}getInsight(e,t,n,i){return t<n?{rating:"good",message:`Excellent ${e}`}:t<i?{rating:"needs-improvement",message:`${e} needs improvement`}:{rating:"poor",message:`Poor ${e} performance`}}getTransferEfficiency(e){const t=e.decodedBodySize>0?e.encodedBodySize/e.decodedBodySize:1;return{ratio:t,rating:t<.7?"good":t<.9?"fair":"poor"}}getNavigationRecommendations(e){const t=[];return e.ttfb>500&&t.push("Server response time is slow. Consider optimizing backend performance."),e.dns>100&&t.push("DNS lookup time is high. Consider using a faster DNS provider."),e.connect>1e3&&t.push("Connection time is slow. Check network latency."),e.domProcessing>1e3&&t.push("DOM processing is slow. Consider optimizing JavaScript execution."),t}checkThreshold(e,t){const n=this.thresholds[e];n&&t>n&&d.warn(`[PerformanceManager] ${e.toUpperCase()} threshold exceeded: ${t}ms (threshold: ${n}ms)`)}getRating(e,t){const n={fcp:{good:1800,poor:3e3},lcp:{good:2500,poor:4e3},fid:{good:100,poor:300},cls:{good:.1,poor:.25}}[e];return n&&null!=t?t<=n.good?"good":t<=n.poor?"needs-improvement":"poor":"unknown"}setMetric(e,t){this.metrics.set(e,{value:t,timestamp:Date.now()})}getMetric(e){const t=this.metrics.get(e);return t?t.value:null}formatBytes(e){if(0===e)return"0 Bytes";const t=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,t)).toFixed(2))+" "+["Bytes","KB","MB","GB"][t]}generateId(e="perf"){return`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}cleanup(){this.observers.forEach(e=>{e.disconnect()}),this.observers.clear(),this.metrics.clear(),this.marks.clear(),this.measures.clear(),d.info("[PerformanceManager] Cleanup completed")}getReport(){return{support:this.support,navigation:this.navigation.get(),resources:this.resources.getSummary(),vitals:this.vitals.get(),memory:this.memory.get(),marks:this.timing.getMarks(),measures:this.timing.getMeasures(),activeObservers:this.observers.size,timestamp:Date.now()}}}class v{constructor(e={}){var t;this.config=e,this.permissionCache=new Map,this.permissionWatchers=new Map,this.requestQueue=new Map,this.support={permissions:"permissions"in navigator,query:void 0!==(null==(t=navigator.permissions)?void 0:t.query),request:"requestPermission"in Notification||"getUserMedia"in(navigator.mediaDevices||{}),geolocation:"geolocation"in navigator,notifications:"Notification"in window,camera:void 0!==navigator.mediaDevices,microphone:void 0!==navigator.mediaDevices,clipboard:"clipboard"in navigator,vibration:"vibrate"in navigator},this.permissionMap={camera:{name:"camera",api:"mediaDevices"},microphone:{name:"microphone",api:"mediaDevices"},geolocation:{name:"geolocation",api:"geolocation"},notifications:{name:"notifications",api:"notification"},"clipboard-read":{name:"clipboard-read",api:"clipboard"},"clipboard-write":{name:"clipboard-write",api:"clipboard"},"background-sync":{name:"background-sync",api:"serviceWorker"},"persistent-storage":{name:"persistent-storage",api:"storage"},push:{name:"push",api:"serviceWorker"},midi:{name:"midi",api:"midi"},"payment-handler":{name:"payment-handler",api:"payment"}},d.info("[PermissionManager] Initialized with support:",this.support),this.cacheCurrentPermissions()}async check(e){if(!this.support.permissions||!this.support.query)return d.warn("[PermissionManager] Permissions API not supported, using fallback"),this.checkFallback(e);try{const t=this.permissionCache.get(e);if(t&&Date.now()-t.timestamp<3e4)return t.status;const n=this.getPermissionDescriptor(e),i=await navigator.permissions.query(n),r={name:e,state:i.state,timestamp:Date.now(),supported:!0};return this.permissionCache.set(e,r),i.addEventListener("change",()=>{this.onPermissionChange(e,i.state)}),d.info(`[PermissionManager] Permission checked: ${e} = ${i.state}`),r}catch(t){return d.warn(`[PermissionManager] Permission check failed for ${e}:`,t.message),this.checkFallback(e)}}async request(e,t={}){const{showRationale:n=!0,fallbackMessage:i=null,timeout:r=3e4}=t;try{const t=await this.check(e);if("granted"===t.state)return{granted:!0,state:"granted",fromCache:!0};if("denied"===t.state)return n&&await this.showPermissionRationale(e,i),{granted:!1,state:"denied",reason:"previously-denied"};const o=e;if(this.requestQueue.has(o))return d.info(`[PermissionManager] Permission request already in progress: ${e}`),this.requestQueue.get(o);const a=this.executePermissionRequest(e,r);this.requestQueue.set(o,a);const s=await a;return this.requestQueue.delete(o),this.permissionCache.set(e,{name:e,state:s.state,timestamp:Date.now(),supported:!0}),s}catch(o){return d.error(`[PermissionManager] Permission request failed: ${e}`,o),this.requestQueue.delete(e),{granted:!1,state:"error",error:o.message}}}async requestMultiple(e,t={}){const n={};if(t.sequential){for(const r of e)if(n[r]=await this.request(r,t),t.requireAll&&!n[r].granted)break}else{const i=e.map(e=>this.request(e,t).then(t=>[e,t]));(await Promise.allSettled(i)).forEach(e=>{if("fulfilled"===e.status){const[t,i]=e.value;n[t]=i}else d.error("[PermissionManager] Batch permission request failed:",e.reason)})}const i={results:n,granted:Object.values(n).filter(e=>e.granted).length,denied:Object.values(n).filter(e=>!e.granted).length,total:Object.keys(n).length};return d.info(`[PermissionManager] Batch permissions: ${i.granted}/${i.total} granted`),i}async checkRequired(e){const t={},n=[];for(const i of e){const e=await this.check(i);t[i]=e,"granted"!==e.state&&n.push(i)}return{allGranted:0===n.length,granted:Object.keys(t).filter(e=>"granted"===t[e].state),missing:n,statuses:t}}watch(e,t){const n=this.generateId("watcher");return this.permissionWatchers.set(n,{permission:e,callback:t,active:!0}),this.setupPermissionWatcher(e,t),d.info(`[PermissionManager] Permission watcher created: ${e}`),{id:n,stop:()=>{const t=this.permissionWatchers.get(n);t&&(t.active=!1,this.permissionWatchers.delete(n),d.info(`[PermissionManager] Permission watcher stopped: ${e}`))}}}getRecommendations(e=[]){const t={essential:[],recommended:[],optional:[]},n={camera:{permissions:["camera"],priority:"essential"},microphone:{permissions:["microphone"],priority:"essential"},location:{permissions:["geolocation"],priority:"recommended"},notifications:{permissions:["notifications"],priority:"recommended"},clipboard:{permissions:["clipboard-read","clipboard-write"],priority:"optional"},offline:{permissions:["persistent-storage"],priority:"recommended"},background:{permissions:["background-sync","push"],priority:"optional"}};return e.forEach(e=>{const i=n[e];i&&t[i.priority].push(...i.permissions)}),Object.keys(t).forEach(e=>{t[e]=[...new Set(t[e])]}),t}createOnboardingFlow(e,t={}){const{title:n="Permissions Required",descriptions:i={},onComplete:r=null,onSkip:o=null}=t;return{permissions:e,title:n,descriptions:i,async start(){d.info("[PermissionManager] Starting onboarding flow");const t=[];for(const r of e){const e=i[r]||this.getDefaultDescription(r),n=await this.showPermissionDialog(r,e);if("grant"===n){const e=await this.request(r);t.push({permission:r,...e})}else{if("skip"!==n)return o&&o(t),{cancelled:!0,results:t};t.push({permission:r,granted:!1,skipped:!0})}}const n={completed:!0,granted:t.filter(e=>e.granted).length,total:t.length,results:t};return r&&r(n),n},getDefaultDescription:e=>({camera:"Take photos and record videos for enhanced functionality",microphone:"Record audio for voice features and communication",geolocation:"Provide location-based services and content",notifications:"Send you important updates and reminders","clipboard-read":"Access clipboard content for convenience features","clipboard-write":"Copy content to clipboard for easy sharing"}[e]||`Allow access to ${e} functionality`),async showPermissionDialog(e,t){return new Promise(n=>{const i=document.createElement("div");i.className="permission-dialog-modal",i.innerHTML=`\n <div class="permission-dialog-backdrop" style="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0,0,0,0.5);\n z-index: 10000;\n display: flex;\n align-items: center;\n justify-content: center;\n ">\n <div class="permission-dialog" style="\n background: white;\n border-radius: 8px;\n padding: 2rem;\n max-width: 400px;\n margin: 1rem;\n box-shadow: 0 4px 20px rgba(0,0,0,0.3);\n ">\n <h3 style="margin: 0 0 1rem 0; color: #333;">\n ${this.getPermissionIcon(e)} ${this.getPermissionTitle(e)}\n </h3>\n <p style="margin: 0 0 2rem 0; color: #666; line-height: 1.5;">\n ${t}\n </p>\n <div style="display: flex; gap: 1rem; justify-content: flex-end;">\n <button class="btn-skip" style="\n background: #f5f5f5;\n border: 1px solid #ddd;\n padding: 0.5rem 1rem;\n border-radius: 4px;\n cursor: pointer;\n ">Skip</button>\n <button class="btn-grant" style="\n background: #007bff;\n color: white;\n border: none;\n padding: 0.5rem 1rem;\n border-radius: 4px;\n cursor: pointer;\n ">Allow</button>\n </div>\n </div>\n </div>\n `,document.body.appendChild(i);const r=i.querySelector(".btn-skip"),o=i.querySelector(".btn-grant"),a=()=>document.body.removeChild(i);r.onclick=()=>{a(),n("skip")},o.onclick=()=>{a(),n("grant")},i.querySelector(".permission-dialog-backdrop").onclick=e=>{e.target===e.currentTarget&&(a(),n("cancel"))}})},getPermissionIcon:e=>({camera:"📷",microphone:"🎤",geolocation:"📍",notifications:"🔔","clipboard-read":"📋","clipboard-write":"📋"}[e]||"🔐"),getPermissionTitle:e=>({camera:"Camera Access",microphone:"Microphone Access",geolocation:"Location Access",notifications:"Notifications","clipboard-read":"Clipboard Access","clipboard-write":"Clipboard Access"}[e]||`${e} Permission`)}}async cacheCurrentPermissions(){if(!this.support.permissions)return;const e=["camera","microphone","geolocation","notifications"];for(const n of e)try{await this.check(n)}catch(t){}}getPermissionDescriptor(e){switch(e){case"camera":return{name:"camera"};case"microphone":return{name:"microphone"};case"geolocation":return{name:"geolocation"};case"notifications":return{name:"notifications"};case"clipboard-read":return{name:"clipboard-read"};case"clipboard-write":return{name:"clipboard-write"};case"persistent-storage":return{name:"persistent-storage"};case"background-sync":return{name:"background-sync"};case"push":return{name:"push",userVisibleOnly:!0};default:return{name:e}}}async checkFallback(e){const t={camera:()=>void 0!==navigator.mediaDevices,microphone:()=>void 0!==navigator.mediaDevices,geolocation:()=>"geolocation"in navigator,notifications:()=>"Notification"in window,"clipboard-read":()=>"clipboard"in navigator,"clipboard-write":()=>"clipboard"in navigator}[e],n=!!t&&t();return{name:e,state:n?"prompt":"unsupported",timestamp:Date.now(),supported:n,fallback:!0}}async executePermissionRequest(e,t){return new Promise(async(n,i)=>{const r=setTimeout(()=>{i(new Error("Permission request timeout"))},t);try{let t;switch(e){case"notifications":if("Notification"in window){const e=await Notification.requestPermission();t={granted:"granted"===e,state:e}}else t={granted:!1,state:"unsupported"};break;case"camera":case"microphone":try{const n={};n["camera"===e?"video":"audio"]=!0;(await navigator.mediaDevices.getUserMedia(n)).getTracks().forEach(e=>e.stop()),t={granted:!0,state:"granted"}}catch(o){t={granted:!1,state:"NotAllowedError"===o.name?"denied":"error",error:o.message}}break;case"geolocation":try{await new Promise((e,t)=>{navigator.geolocation.getCurrentPosition(e,t,{timeout:1e4,maximumAge:0})}),t={granted:!0,state:"granted"}}catch(o){t={granted:!1,state:1===o.code?"denied":"error",error:o.message}}break;default:if(this.support.permissions){const n=await navigator.permissions.query(this.getPermissionDescriptor(e));t={granted:"granted"===n.state,state:n.state}}else t={granted:!1,state:"unsupported"}}clearTimeout(r),n(t)}catch(o){clearTimeout(r),i(o)}})}async setupPermissionWatcher(e,t){if(this.support.permissions)try{const n=await navigator.permissions.query(this.getPermissionDescriptor(e));n.addEventListener("change",()=>{t({permission:e,state:n.state,timestamp:Date.now()})})}catch(n){d.warn(`[PermissionManager] Could not set up watcher for ${e}:`,n)}}onPermissionChange(e,t){d.info(`[PermissionManager] Permission changed: ${e}${t}`),this.permissionCache.set(e,{name:e,state:t,timestamp:Date.now(),supported:!0}),this.permissionWatchers.forEach(n=>{n.permission===e&&n.active&&n.callback({permission:e,state:t,timestamp:Date.now()})})}async showPermissionRationale(e,t=null){const n=t||{camera:"Camera access is needed to take photos and record videos. You can enable this in your browser settings.",microphone:"Microphone access is needed for audio recording and voice features. Please check your browser settings.",geolocation:"Location access helps provide relevant local content. You can manage this in your browser settings.",notifications:"Notifications keep you updated with important information. You can change this anytime in settings."}[e]||`${e} permission was denied. Please enable it in your browser settings to use this feature.`;return!("undefined"==typeof window||!window.confirm)&&window.confirm(n+"\n\nWould you like to try again?")}generateId(e="perm"){return`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}async getPermissionReport(){return{support:this.support,cached:Array.from(this.permissionCache.entries()).map(([e,t])=>({name:e,...t})),watchers:Array.from(this.permissionWatchers.keys()),timestamp:Date.now()}}clearCache(){this.permissionCache.clear(),d.info("[PermissionManager] Permission cache cleared")}cleanup(){this.permissionWatchers.forEach(e=>{e.active=!1}),this.permissionWatchers.clear(),this.requestQueue.clear(),this.permissionCache.clear(),d.info("[PermissionManager] Cleanup completed")}}class b{constructor(e={}){this.config={rpName:e.rpName||"Custom PHP Framework",rpId:e.rpId||window.location.hostname,timeout:e.timeout||6e4,userVerification:e.userVerification||"preferred",authenticatorSelection:{authenticatorAttachment:"platform",userVerification:"preferred",requireResidentKey:!1,...e.authenticatorSelection},...e},this.credentials=new Map,this.authSessions=new Map,this.support={webAuthn:"credentials"in navigator&&"create"in navigator.credentials,conditionalUI:"conditional"in window.PublicKeyCredential||!1,userVerifyingPlatformAuthenticator:!1,residentKey:!1},this.detectFeatures(),d.info("[BiometricAuthManager] Initialized with support:",this.support)}async detectFeatures(){if(this.support.webAuthn)try{const e=await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();this.support.userVerifyingPlatformAuthenticator=e,window.PublicKeyCredential.isConditionalMediationAvailable&&(this.support.conditionalUI=await window.PublicKeyCredential.isConditionalMediationAvailable()),d.info("[BiometricAuthManager] Enhanced features detected:",{platform:this.support.userVerifyingPlatformAuthenticator,conditional:this.support.conditionalUI})}catch(e){d.warn("[BiometricAuthManager] Feature detection failed:",e)}}async register(e,t={}){var n,i;if(!this.support.webAuthn)throw new Error("WebAuthn not supported");const{challenge:r=null,excludeCredentials:o=[],extensions:a={}}=t;try{const t=r?this.base64ToArrayBuffer(r):crypto.getRandomValues(new Uint8Array(32)),s={rp:{name:this.config.rpName,id:this.config.rpId},user:{id:this.stringToArrayBuffer(e.id||e.username),name:e.username||e.email,displayName:e.displayName||e.name||e.username},challenge:t,pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-35},{type:"public-key",alg:-36},{type:"public-key",alg:-257},{type:"public-key",alg:-258},{type:"public-key",alg:-259}],authenticatorSelection:this.config.authenticatorSelection,timeout:this.config.timeout,attestation:"direct",extensions:{credProps:!0,...a}};o.length>0&&(s.excludeCredentials=o.map(e=>({type:"public-key",id:"string"==typeof e?this.base64ToArrayBuffer(e):e,transports:["internal","hybrid"]}))),d.info("[BiometricAuthManager] Starting registration...");const c=await navigator.credentials.create({publicKey:s});if(!c)throw new Error("Credential creation failed");const l=this.processCredential(c,"registration"),h={id:l.id,rawId:l.rawId,userId:e.id||e.username,userDisplayName:e.displayName||e.name,createdAt:Date.now(),lastUsed:null,counter:l.response.counter||0,transports:(null==(i=(n=c.response).getTransports)?void 0:i.call(n))||["internal"]};return this.credentials.set(l.id,h),d.info("[BiometricAuthManager] Registration successful:",{id:l.id,user:e.username,authenticator:h.transports}),{success:!0,credential:l,info:h,attestation:this.parseAttestation(c.response)}}catch(s){return d.error("[BiometricAuthManager] Registration failed:",s),{success:!1,error:s.message,name:s.name}}}async authenticate(e={}){if(!this.support.webAuthn)throw new Error("WebAuthn not supported");const{challenge:t=null,allowCredentials:n=[],userVerification:i=this.config.userVerification,conditional:r=!1,extensions:o={}}=e;try{const e={challenge:t?this.base64ToArrayBuffer(t):crypto.getRandomValues(new Uint8Array(32)),timeout:this.config.timeout,userVerification:i,extensions:{credProps:!0,...o}};n.length>0&&(e.allowCredentials=n.map(e=>({type:"public-key",id:"string"==typeof e?this.base64ToArrayBuffer(e):e,transports:["internal","hybrid","usb","nfc","ble"]}))),d.info("[BiometricAuthManager] Starting authentication...",{conditional:r});const a=r&&this.support.conditionalUI?await navigator.credentials.get({publicKey:e,mediation:"conditional"}):await navigator.credentials.get({publicKey:e});if(!a)throw new Error("Authentication failed");const s=this.processCredential(a,"authentication"),c=this.credentials.get(s.id);c&&(c.lastUsed=Date.now(),c.counter=s.response.counter||0);const l=this.generateSessionId(),h={id:l,credentialId:s.id,userId:null==c?void 0:c.userId,authenticatedAt:Date.now(),userAgent:navigator.userAgent,ipAddress:await this.getClientIP().catch(()=>"unknown")};return this.authSessions.set(l,h),d.info("[BiometricAuthManager] Authentication successful:",{sessionId:l,credentialId:s.id,userId:null==c?void 0:c.userId}),{success:!0,credential:s,session:h,info:c}}catch(a){return d.error("[BiometricAuthManager] Authentication failed:",a),{success:!1,error:a.message,name:a.name}}}async isAvailable(){const e={webAuthn:this.support.webAuthn,platform:this.support.userVerifyingPlatformAuthenticator,conditional:this.support.conditionalUI,hasCredentials:this.credentials.size>0,recommended:!1};return e.recommended=e.webAuthn&&(e.platform||e.hasCredentials),e}async setupConditionalUI(e='input[type="email"], input[type="text"]',t={}){if(!this.support.conditionalUI)return d.warn("[BiometricAuthManager] Conditional UI not supported"),null;const n=document.querySelectorAll(e);if(0===n.length)return d.warn("[BiometricAuthManager] No suitable inputs found for conditional UI"),null;try{return n.forEach(e=>{e.addEventListener("focus",async()=>{var n;d.info("[BiometricAuthManager] Setting up conditional authentication");try{const i=await this.authenticate({...t,conditional:!0});if(i.success){const t=new CustomEvent("biometric-auth-success",{detail:i});e.dispatchEvent(t),(null==(n=i.info)?void 0:n.userDisplayName)&&(e.value=i.info.userDisplayName)}}catch(i){d.warn("[BiometricAuthManager] Conditional auth failed:",i)}})}),d.info("[BiometricAuthManager] Conditional UI setup complete"),{inputs:n.length,selector:e}}catch(i){return d.error("[BiometricAuthManager] Conditional UI setup failed:",i),null}}createLoginFlow(e={}){const{registerSelector:t="#register-biometric",loginSelector:n="#login-biometric",statusSelector:i="#biometric-status",onRegister:r=null,onLogin:o=null,onError:a=null}=e;return{async init(){const e=await this.isAvailable(),r=document.querySelector(i);r&&(r.innerHTML=this.createStatusHTML(e));const o=document.querySelector(t);o&&(o.style.display=e.webAuthn?"block":"none",o.onclick=()=>this.handleRegister());const a=document.querySelector(n);return a&&(a.style.display=e.hasCredentials?"block":"none",a.onclick=()=>this.handleLogin()),e.conditional&&await this.setupConditionalUI(),e},async handleRegister(){try{const e=await this.getUserInfo();if(!e)return;const t=await this.register(e);t.success?(r&&r(t),this.showSuccess("Biometric authentication registered successfully!")):(a&&a(t),this.showError(t.error))}catch(e){a&&a({error:e.message}),this.showError(e.message)}},async handleLogin(){try{const e=await this.authenticate();e.success?(o&&o(e),this.showSuccess("Biometric authentication successful!")):(a&&a(e),this.showError(e.error))}catch(e){a&&a({error:e.message}),this.showError(e.message)}},async getUserInfo(){const e=document.querySelector('input[name="username"], input[name="email"]'),t=document.querySelector('input[name="name"], input[name="display_name"]');if(null==e?void 0:e.value)return{id:e.value,username:e.value,displayName:(null==t?void 0:t.value)||e.value};const n=prompt("Please enter your username or email:");if(!n)return null;return{id:n,username:n,displayName:prompt("Please enter your display name:")||n}},createStatusHTML:e=>e.webAuthn?e.platform||e.hasCredentials?e.hasCredentials?'<div class="alert alert-success">✅ Biometric authentication available</div>':'<div class="alert alert-info">🔐 Biometric authentication can be set up</div>':'<div class="alert alert-info"> No biometric authenticators available</div>':'<div class="alert alert-warning">⚠️ Biometric authentication not supported in this browser</div>',showSuccess(e){this.showMessage(e,"success")},showError(e){this.showMessage(e,"error")},showMessage(e,t="info"){const n=document.createElement("div");n.className=`biometric-toast toast-${t}`,n.style.cssText=`\n position: fixed;\n top: 20px;\n right: 20px;\n background: ${"error"===t?"#f44336":"success"===t?"#4caf50":"#2196f3"};\n color: white;\n padding: 1rem;\n border-radius: 4px;\n box-shadow: 0 2px 10px rgba(0,0,0,0.3);\n z-index: 10001;\n max-width: 300px;\n `,n.textContent=e,document.body.appendChild(n),setTimeout(()=>{n.parentNode&&document.body.removeChild(n)},5e3)}}}processCredential(e,t){var n,i;const r={id:this.arrayBufferToBase64(e.rawId),rawId:this.arrayBufferToBase64(e.rawId),type:e.type,response:{}};return r.response="registration"===t?{attestationObject:this.arrayBufferToBase64(e.response.attestationObject),clientDataJSON:this.arrayBufferToBase64(e.response.clientDataJSON),transports:(null==(i=(n=e.response).getTransports)?void 0:i.call(n))||[]}:{authenticatorData:this.arrayBufferToBase64(e.response.authenticatorData),clientDataJSON:this.arrayBufferToBase64(e.response.clientDataJSON),signature:this.arrayBufferToBase64(e.response.signature),userHandle:e.response.userHandle?this.arrayBufferToBase64(e.response.userHandle):null},r}parseAttestation(e){try{const t=JSON.parse(this.arrayBufferToString(e.clientDataJSON));return{format:"packed",clientData:t,origin:t.origin,challenge:t.challenge}}catch(t){return d.warn("[BiometricAuthManager] Attestation parsing failed:",t),null}}async getClientIP(){try{const e=await fetch("https://api.ipify.org?format=json");return(await e.json()).ip}catch(e){return"unknown"}}generateSessionId(){return`biometric_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}arrayBufferToBase64(e){const t=new Uint8Array(e);let n="";for(let i=0;i<t.byteLength;i++)n+=String.fromCharCode(t[i]);return btoa(n)}base64ToArrayBuffer(e){const t=atob(e),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);return n.buffer}stringToArrayBuffer(e){return(new TextEncoder).encode(e)}arrayBufferToString(e){return(new TextDecoder).decode(e)}getCredentials(){return Array.from(this.credentials.values())}getActiveSessions(){return Array.from(this.authSessions.values())}revokeCredential(e){const t=this.credentials.delete(e);return t&&d.info(`[BiometricAuthManager] Credential revoked: ${e}`),t}endSession(e){const t=this.authSessions.delete(e);return t&&d.info(`[BiometricAuthManager] Session ended: ${e}`),t}cleanupSessions(e=864e5){const t=Date.now();let n=0;for(const[i,r]of this.authSessions.entries())t-r.authenticatedAt>e&&(this.authSessions.delete(i),n++);return n>0&&d.info(`[BiometricAuthManager] Cleaned up ${n} expired sessions`),n}async getStatusReport(){return{availability:await this.isAvailable(),credentials:this.credentials.size,sessions:this.authSessions.size,support:this.support,config:{rpName:this.config.rpName,rpId:this.config.rpId,timeout:this.config.timeout},timestamp:Date.now()}}}const w={name:"api-manager",init(e={},t=null){return d.info("[APIManager] Module initialized - All Web APIs available"),this.initializeAPIManagers(e),this.exposeGlobalAPI(),this},initializeAPIManagers(e){this.observers=new h(e.observers||{}),this.media=new u(e.media||{}),this.storage=new m(e.storage||{}),this.device=new p(e.device||{}),this.animation=new g(e.animation||{}),this.worker=new f(e.worker||{}),this.performance=new y(e.performance||{}),this.permissions=new v(e.permissions||{}),this.biometric=new b(e.biometric||{}),d.info("[APIManager] All API managers initialized")},exposeGlobalAPI(){"undefined"!=typeof window&&(window.API={observers:this.observers,media:this.media,storage:this.storage,device:this.device,animation:this.animation,worker:this.worker,performance:this.performance,permissions:this.permissions,biometric:this.biometric},d.info("[APIManager] Global API exposed at window.API"))},getAPI(e){return this[e]||null},isSupported:e=>({IntersectionObserver:"IntersectionObserver"in window,ResizeObserver:"ResizeObserver"in window,MutationObserver:"MutationObserver"in window,PerformanceObserver:"PerformanceObserver"in window,MediaDevices:void 0!==navigator.mediaDevices,WebRTC:"RTCPeerConnection"in window,WebAudio:"AudioContext"in window||"webkitAudioContext"in window,MediaRecorder:"MediaRecorder"in window,IndexedDB:"indexedDB"in window,CacheAPI:"caches"in window,WebLocks:"locks"in navigator,BroadcastChannel:"BroadcastChannel"in window,Geolocation:"geolocation"in navigator,DeviceMotion:"DeviceMotionEvent"in window,DeviceOrientation:"DeviceOrientationEvent"in window,Vibration:"vibrate"in navigator,Battery:"getBattery"in navigator,NetworkInfo:"connection"in navigator,WebAnimations:"animate"in Element.prototype,VisualViewport:"visualViewport"in window,WebWorkers:"Worker"in window,ServiceWorker:"serviceWorker"in navigator,SharedWorker:"SharedWorker"in window,PerformanceAPI:"performance"in window,NavigationTiming:"getEntriesByType"in performance,Permissions:"permissions"in navigator,WebAuthn:"credentials"in navigator&&"create"in navigator.credentials}[e]||!1),getCapabilities(){const e={};return Object.keys(this.getSupportMap()).forEach(t=>{e[t]=this.isSupported(t)}),{capabilities:e,modernBrowser:this.isModernBrowser(),recommendedAPIs:this.getRecommendedAPIs(),summary:this.getCapabilitySummary(e)}},isModernBrowser(){return["IntersectionObserver","ResizeObserver","WebAnimations","IndexedDB"].every(e=>this.isSupported(e))},getRecommendedAPIs(){const e=[];return this.isSupported("IntersectionObserver")&&e.push({api:"IntersectionObserver",use:"Lazy loading, scroll triggers, viewport detection",example:"API.observers.intersection(elements, callback)"}),this.isSupported("WebAnimations")&&e.push({api:"Web Animations",use:"High-performance animations with timeline control",example:"API.animation.animate(element, keyframes, options)"}),this.isSupported("IndexedDB")&&e.push({api:"IndexedDB",use:"Client-side database for complex data",example:"API.storage.db.set(key, value)"}),this.isSupported("MediaDevices")&&e.push({api:"Media Devices",use:"Camera, microphone, screen sharing",example:"API.media.getUserCamera()"}),e},getCapabilitySummary(e){const t=Object.keys(e).length,n=Object.values(e).filter(Boolean).length,i=Math.round(n/t*100);return{total:t,supported:n,percentage:i,grade:this.getGrade(i)}},getGrade:e=>e>=90?"A+":e>=80?"A":e>=70?"B":e>=60?"C":"D",getSupportMap:()=>({IntersectionObserver:"Viewport intersection detection",ResizeObserver:"Element resize detection",MutationObserver:"DOM change detection",PerformanceObserver:"Performance metrics monitoring",MediaDevices:"Camera and microphone access",WebRTC:"Real-time communication",WebAudio:"Audio processing and synthesis",MediaRecorder:"Audio/video recording",IndexedDB:"Client-side database",CacheAPI:"HTTP cache management",WebLocks:"Resource locking",BroadcastChannel:"Cross-tab communication",Geolocation:"GPS and location services",DeviceMotion:"Accelerometer and gyroscope",DeviceOrientation:"Device orientation",Vibration:"Haptic feedback",Battery:"Battery status",NetworkInfo:"Network connection info",WebAnimations:"High-performance animations",VisualViewport:"Viewport information",WebWorkers:"Background processing",ServiceWorker:"Background sync and caching",SharedWorker:"Shared background processing",PerformanceAPI:"Performance measurement",NavigationTiming:"Navigation timing metrics",Permissions:"Browser permission management",WebAuthn:"Biometric authentication"})},S=w.init.bind(w),M=Object.freeze(Object.defineProperty({__proto__:null,default:w,init:S},Symbol.toStringTag,{value:"Module"})),C=new Map,E={add(e,t,n,{module:i="global",options:r=!1}={}){e.addEventListener(t,n,r),C.has(i)||C.set(i,[]),C.get(i).push([e,t,n,r])},removeModule(e){const t=C.get(e);t&&(t.forEach(([e,t,n,i])=>{e.removeEventListener(t,n,i)}),C.delete(e))},clearAll(){for(const[e,t]of C.entries())t.forEach(([e,t,n,i])=>{e.removeEventListener(t,n,i)});C.clear()},debug(){console.table([...C.entries()].map(([e,t])=>({module:e,listeners:t.length})))}};function k(e,t,n,i=import.meta,r=!1){var o;const a="string"==typeof i?i:(null==(o=i.url)?void 0:o.split("/").slice(-2,-1)[0])||"unknown";return E.add(e,t,n,{module:a,options:r}),()=>{E.removeModule(a)}}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,i;e&&"static"!==getComputedStyle(e).position?(n=e.clientWidth,i=e.clientHeight):(n=this.canvas.clientWidth||window.innerWidth,i=this.canvas.clientHeight||window.innerHeight),this.canvas.width=Math.floor(n*t),this.canvas.height=Math.floor(i*t),this.canvas.style.width=n+"px",this.canvas.style.height=i+"px",t>1&&this.ctx.scale(t,t),d.info("[CanvasManager] Resized",{displayWidth:n,displayHeight:i,canvasWidth:this.canvas.width,canvasHeight:this.canvas.height})}clear(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}getSize(){return{width:this.canvas.clientWidth,height:this.canvas.clientHeight,pixelWidth:this.canvas.width,pixelHeight:this.canvas.height}}getMousePosition(e){const t=this.canvas.getBoundingClientRect();return{x:(e.clientX-t.left)*this.options.pixelRatio,y:(e.clientY-t.top)*this.options.pixelRatio}}startAnimation(e){this.isAnimating&&this.stopAnimation(),this.isAnimating=!0;const t=n=>{this.isAnimating&&(e(n),this.animationId=requestAnimationFrame(t))};this.animationId=requestAnimationFrame(t),d.info("[CanvasManager] Animation started")}stopAnimation(){this.animationId&&(cancelAnimationFrame(this.animationId),this.animationId=null),this.isAnimating=!1,d.info("[CanvasManager] Animation stopped")}destroy(){this.stopAnimation(),d.info("[CanvasManager] Destroyed")}}const A={initParallax(e,t){const n=new x(e),i=this.createParallaxElements(e,t);let r=!1;const o=()=>{r||(requestAnimationFrame(()=>{this.renderParallax(n,i,t),r=!1}),r=!0)};k(window,"scroll",o,"scroll-parallax"),k(window,"resize",o,"scroll-parallax"),o(),d.info("[ScrollEffects] Parallax initialized with",i.length,"elements")},createParallaxElements(e,t){const n=[],i=t.layers||3,r=t.elements||20;for(let o=0;o<r;o++)n.push({x:Math.random()*e.clientWidth,y:Math.random()*e.clientHeight*2,size:20*Math.random()+5,layer:Math.floor(Math.random()*i),speed:.1+.5*Math.random(),opacity:.7*Math.random()+.3,color:this.getLayerColor(Math.floor(Math.random()*i),t)});return n},getLayerColor(e,t){const n=t.colors||["rgba(100, 150, 255, 0.6)","rgba(150, 100, 255, 0.4)","rgba(200, 100, 150, 0.2)"];return n[e]||n[0]},renderParallax(e,t,n){e.clear();const i=window.pageYOffset,r=(i-(e.canvas.getBoundingClientRect().top+i))/window.innerHeight;t.forEach(t=>{const n=r*t.speed*100,i=t.y-n;i>-t.size&&i<e.canvas.clientHeight+t.size&&(e.ctx.save(),e.ctx.globalAlpha=t.opacity,e.ctx.fillStyle=t.color,e.ctx.beginPath(),e.ctx.arc(t.x,i,t.size,0,2*Math.PI),e.ctx.fill(),e.ctx.restore())})},initScrollAnimation(e,t){const n=new x(e),i=t.animation||"wave";let r=!1;const o=()=>{r||(requestAnimationFrame(()=>{this.renderScrollAnimation(n,i,t),r=!1}),r=!0)};k(window,"scroll",o,"scroll-animation"),k(window,"resize",o,"scroll-animation"),o(),d.info("[ScrollEffects] Scroll animation initialized:",i)},renderScrollAnimation(e,t,n){e.clear();const i=window.pageYOffset,r=i-(e.canvas.getBoundingClientRect().top+i),o=Math.max(0,Math.min(1,r/window.innerHeight));switch(t){case"wave":default:this.renderWaveAnimation(e,o,n);break;case"progress":this.renderProgressAnimation(e,o,n);break;case"morph":this.renderMorphAnimation(e,o,n)}},renderWaveAnimation(e,t,n){const{ctx:i}=e,{width:r,height:o}=e.getSize();i.strokeStyle=n.color||"rgba(100, 150, 255, 0.8)",i.lineWidth=n.lineWidth||3,i.beginPath();const a=(n.amplitude||50)*t,s=n.frequency||.02,c=t*Math.PI*2;for(let l=0;l<=r;l+=2){const e=o/2+Math.sin(l*s+c)*a;0===l?i.moveTo(l,e):i.lineTo(l,e)}i.stroke()},renderProgressAnimation(e,t,n){const{ctx:i}=e,{width:r,height:o}=e.getSize(),a=n.barHeight||10,s=o/2-a/2;i.fillStyle=n.backgroundColor||"rgba(255, 255, 255, 0.2)",i.fillRect(0,s,r,a),i.fillStyle=n.color||"rgba(100, 150, 255, 0.8)",i.fillRect(0,s,r*t,a)},renderMorphAnimation(e,t,n){const{ctx:i}=e,{width:r,height:o}=e.getSize();i.fillStyle=n.color||"rgba(100, 150, 255, 0.6)";const a=r/2,s=o/2,c=Math.min(r,o)/3;i.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),r=a+Math.cos(e)*n,o=s+Math.sin(e)*n;0===d?i.moveTo(r,o):i.lineTo(r,o)}i.closePath(),i.fill()}},I={init(e,t){const n=new x(e),i=t.effect||"ripple",r={mouse:{x:0,y:0,isOver:!1},effects:[],lastTime:0};this.setupInteractionEvents(e,n,r,t),this.startAnimationLoop(n,r,i,t),d.info("[InteractiveEffects] Initialized with effect:",i)},setupInteractionEvents(e,t,n,i){k(e,"mousemove",e=>{const r=t.getMousePosition(e);n.mouse.x=r.x,n.mouse.y=r.y,"trail"===i.effect&&this.addTrailPoint(n,r.x,r.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 r=t.getMousePosition(e);this.addClickEffect(n,r.x,r.y,i)},"interactive-effects"),k(e,"touchstart",e=>{e.preventDefault();const r=e.touches[0],o=t.getMousePosition(r);this.addClickEffect(n,o.x,o.y,i)},"interactive-effects"),k(e,"touchmove",e=>{e.preventDefault();const r=e.touches[0],o=t.getMousePosition(r);n.mouse.x=o.x,n.mouse.y=o.y,n.mouse.isOver=!0,"trail"===i.effect&&this.addTrailPoint(n,o.x,o.y)},"interactive-effects"),k(e,"touchend",()=>{n.mouse.isOver=!1},"interactive-effects")},startAnimationLoop(e,t,n,i){const r=o=>{const a=o-t.lastTime;switch(t.lastTime=o,e.clear(),n){case"ripple":default:this.renderRippleEffect(e,t,i);break;case"trail":this.renderTrailEffect(e,t,i);break;case"particles":this.renderParticleEffect(e,t,i,a);break;case"magnetic":this.renderMagneticEffect(e,t,i)}this.updateEffects(t.effects,a),requestAnimationFrame(r)};requestAnimationFrame(r)},addClickEffect(e,t,n,i){const r={x:t,y:n,age:0,maxAge:i.duration||1e3,type:"click",intensity:i.intensity||1};e.effects.push(r)},addTrailPoint(e,t,n){const i={x:t,y:n,age:0,maxAge:500,type:"trail"};e.effects.push(i);const r=e.effects.filter(e=>"trail"===e.type);if(r.length>20){const t=e.effects.indexOf(r[0]);e.effects.splice(t,1)}},renderRippleEffect(e,t,n){const{ctx:i}=e;t.effects.forEach(t=>{if("click"===t.type){const r=t.age/t.maxAge,o=r*(n.maxRadius||100),a=.8*(1-r);i.save(),i.globalAlpha=a,i.strokeStyle=n.color||"rgba(100, 150, 255, 1)",i.lineWidth=n.lineWidth||3,i.beginPath(),i.arc(t.x/e.options.pixelRatio,t.y/e.options.pixelRatio,o,0,2*Math.PI),i.stroke(),i.restore()}}),t.mouse.isOver&&(i.save(),i.globalAlpha=.3,i.fillStyle=n.hoverColor||"rgba(100, 150, 255, 0.3)",i.beginPath(),i.arc(t.mouse.x/e.options.pixelRatio,t.mouse.y/e.options.pixelRatio,n.hoverRadius||30,0,2*Math.PI),i.fill(),i.restore())},renderTrailEffect(e,t,n){const{ctx:i}=e,r=t.effects.filter(e=>"trail"===e.type);r.length<2||(i.save(),i.strokeStyle=n.color||"rgba(100, 150, 255, 0.8)",i.lineWidth=n.lineWidth||5,i.lineCap="round",i.lineJoin="round",i.beginPath(),r.forEach((t,n)=>{const r=1-t.age/t.maxAge,o=t.x/e.options.pixelRatio,a=t.y/e.options.pixelRatio;i.globalAlpha=.8*r,0===n?i.moveTo(o,a):i.lineTo(o,a)}),i.stroke(),i.restore())},renderParticleEffect(e,t,n,i){const{ctx:r}=e;if(t.mouse.isOver&&Math.random()<.1){const e={x:t.mouse.x,y:t.mouse.y,vx:4*(Math.random()-.5),vy:4*(Math.random()-.5),age:0,maxAge:1e3,size:5*Math.random()+2,type:"particle"};t.effects.push(e)}t.effects.forEach(t=>{if("particle"===t.type){t.x+=t.vx,t.y+=t.vy,t.vy+=.1;const i=t.age/t.maxAge,o=.8*(1-i);r.save(),r.globalAlpha=o,r.fillStyle=n.color||"rgba(100, 150, 255, 1)",r.beginPath(),r.arc(t.x/e.options.pixelRatio,t.y/e.options.pixelRatio,t.size*(1-.5*i),0,2*Math.PI),r.fill(),r.restore()}})},renderMagneticEffect(e,t,n){const{ctx:i}=e,{width:r,height:o}=e.getSize();if(!t.mouse.isOver)return;const a=r/2,s=o/2,c=t.mouse.x/e.options.pixelRatio,l=t.mouse.y/e.options.pixelRatio;i.save(),i.strokeStyle=n.color||"rgba(100, 150, 255, 0.6)",i.lineWidth=2;for(let d=0;d<8;d++){const e=d/8*Math.PI*2,t=a+50*Math.cos(e),n=s+50*Math.sin(e),r=(t+c)/2+30*Math.sin(e),o=(n+l)/2+30*Math.cos(e);i.beginPath(),i.moveTo(t,n),i.quadraticCurveTo(r,o,c,l),i.stroke()}i.restore()},updateEffects(e,t){for(let n=e.length-1;n>=0;n--)e[n].age+=t,e[n].age>=e[n].maxAge&&e.splice(n,1)}},L={init(e,t){const n=new x(e),i=t.type||"bar",r=this.parseData(e,t);if(r&&0!==r.length){switch(i){case"bar":default:this.createBarChart(n,r,t);break;case"line":this.createLineChart(n,r,t);break;case"pie":this.createPieChart(n,r,t);break;case"progress":this.createProgressChart(n,r,t)}d.info("[DataVisualization] Initialized",i,"chart with",r.length,"data points")}else d.warn("[DataVisualization] No data provided for canvas")},parseData(e,t){let n=t.data;if(!n&&e.dataset.canvasData)try{n=JSON.parse(e.dataset.canvasData)}catch(i){d.warn("[DataVisualization] Failed to parse canvas data",i)}if(!n){const t=e.nextElementSibling;if(t&&"SCRIPT"===t.tagName&&"application/json"===t.type)try{n=JSON.parse(t.textContent)}catch(i){d.warn("[DataVisualization] Failed to parse script data",i)}}if(!n)return d.warn("[DataVisualization] No data found"),[];if(!Array.isArray(n))if("number"==typeof n)n=[{value:n,label:"Progress"}];else{if("object"!=typeof n)return d.warn("[DataVisualization] Data format not recognized:",n),[];n=Object.entries(n).map(([e,t])=>({label:e,value:"object"==typeof t&&t.value||t}))}return n},createBarChart(e,t,n){const{ctx:i}=e,{width:r,height:o}=e.getSize(),a=n.padding||40,s=r-2*a,c=o-2*a,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 p=null;const g=i=>{p||(p=i);const r=i-p;u=Math.min(r/m,1);const o=1-Math.pow(1-u,3);e.clear(),this.renderBarChart(e,t,n,o,{padding:a,chartWidth:s,chartHeight:c,barWidth:l,barSpacing:d,maxValue:h}),u<1&&requestAnimationFrame(g)};requestAnimationFrame(g)},renderBarChart(e,t,n,i,r){const{ctx:o}=e,{padding:a,chartHeight:s,barWidth:c,barSpacing:l,maxValue:d}=r;t.forEach((e,t)=>{const r=a+t*(c+l),h=e.value/d*s*i,u=a+s-h;o.fillStyle=e.color||n.barColor||"rgba(100, 150, 255, 0.8)",o.fillRect(r,u,c,h),!1!==n.showLabels&&(o.fillStyle=n.textColor||"#333",o.font=n.font||"12px Arial",o.textAlign="center",o.fillText(e.label,r+c/2,a+s+20),!1!==n.showValues&&o.fillText(Math.round(e.value*i),r+c/2,u-5))}),!1!==n.showAxes&&(o.strokeStyle=n.axisColor||"#ccc",o.lineWidth=1,o.beginPath(),o.moveTo(a,a),o.lineTo(a,a+s),o.stroke(),o.beginPath(),o.moveTo(a,a+s),o.lineTo(a+r.chartWidth,a+s),o.stroke())},createLineChart(e,t,n){const{ctx:i}=e,{width:r,height:o}=e.getSize(),a=n.padding||40,s=r-2*a,c=o-2*a,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 p=null;const g=i=>{p||(p=i);const r=i-p;u=Math.min(r/m,1),e.clear(),this.renderLineChart(e,t,n,u,{padding:a,chartWidth:s,chartHeight:c,maxValue:l,minValue:d,valueRange:h}),u<1&&requestAnimationFrame(g)};requestAnimationFrame(g)},renderLineChart(e,t,n,i,r){const{ctx:o}=e,{padding:a,chartWidth:s,chartHeight:c,minValue:l,valueRange:d}=r,h=Math.floor(t.length*i);o.strokeStyle=n.lineColor||"rgba(100, 150, 255, 0.8)",o.lineWidth=n.lineWidth||3,o.lineCap="round",o.lineJoin="round",o.beginPath();for(let u=0;u<=h&&u<t.length;u++){const e=a+u/(t.length-1)*s,n=a+c-(t[u].value-l)/d*c;0===u?o.moveTo(e,n):o.lineTo(e,n)}if(o.stroke(),!1!==n.showPoints){o.fillStyle=n.pointColor||n.lineColor||"rgba(100, 150, 255, 0.8)";for(let e=0;e<=h&&e<t.length;e++){const i=a+e/(t.length-1)*s,r=a+c-(t[e].value-l)/d*c;o.beginPath(),o.arc(i,r,n.pointSize||4,0,2*Math.PI),o.fill(),!1!==n.showLabels&&t[e].label&&(o.fillStyle=n.textColor||"#333",o.font=n.font||"12px Arial",o.textAlign="center",o.fillText(t[e].label,i,a+c+20))}}},createPieChart(e,t,n){const{ctx:i}=e,{width:r,height:o}=e.getSize(),a=r/2,s=o/2,c=Math.min(r,o)/2*.8,l=t.reduce((e,t)=>e+t.value,0);let d=0;const h=n.animationDuration||2e3;let u=null;const m=i=>{u||(u=i);const r=i-u;d=Math.min(r/h,1),e.clear(),this.renderPieChart(e,t,n,d,{centerX:a,centerY:s,radius:c,total:l}),d<1&&requestAnimationFrame(m)};requestAnimationFrame(m)},renderPieChart(e,t,n,i,r){const{ctx:o}=e,{centerX:a,centerY:s,radius:c,total:l}=r;let d=-Math.PI/2;const h=d+2*Math.PI*i;for(let u=0;u<t.length&&!(d>=h);u++){const e=t[u],i=e.value/l*Math.PI*2,r=Math.min(d+i,h);if(r>d&&(o.fillStyle=e.color||this.getDefaultColor(u),o.beginPath(),o.moveTo(a,s),o.arc(a,s,c,d,r),o.closePath(),o.fill(),!1!==n.showLabels&&r===d+i)){const t=d+i/2,r=a+Math.cos(t)*c*.7,l=s+Math.sin(t)*c*.7;o.fillStyle=n.textColor||"#333",o.font=n.font||"12px Arial",o.textAlign="center",o.fillText(e.label,r,l)}d+=i}},createProgressChart(e,t,n){const{ctx:i}=e,{width:r,height:o}=e.getSize();let a=0;const s=n.animationDuration||1500;let c=null;const l=i=>{c||(c=i);const r=i-c;a=Math.min(r/s,1),e.clear(),this.renderProgressChart(e,t,n,a),a<1&&requestAnimationFrame(l)};requestAnimationFrame(l)},renderProgressChart(e,t,n,i){var r;const{ctx:o}=e,{width:a,height:s}=e.getSize(),c=a/2,l=s/2,d=Math.min(a,s)/2*.8,h=n.lineWidth||20,u=(null==(r=t[0])?void 0:r.value)||0,m=n.maxValue||100,p=u/m*i;o.strokeStyle=n.backgroundColor||"rgba(200, 200, 200, 0.3)",o.lineWidth=h,o.beginPath(),o.arc(c,l,d,0,2*Math.PI),o.stroke(),o.strokeStyle=n.color||"rgba(100, 150, 255, 0.8)",o.lineCap="round",o.beginPath(),o.arc(c,l,d,-Math.PI/2,-Math.PI/2+p/m*Math.PI*2),o.stroke(),!1!==n.showText&&(o.fillStyle=n.textColor||"#333",o.font=n.font||"bold 24px Arial",o.textAlign="center",o.textBaseline="middle",o.fillText(Math.round(p)+"%",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]}},T={name:"canvas-animations",init(e={},t=null){return d.info("[CanvasAnimations] Module initialized"),this.initializeCanvasElements(),this},initializeCanvasElements(){const e=document.querySelectorAll("canvas[data-canvas-type]");e.forEach(e=>{this.initElement(e)}),d.info(`[CanvasAnimations] Initialized ${e.length} canvas elements`)},initElement(e,t={}){const n=e.dataset.canvasType,i=this.parseCanvasConfig(e);switch(d.info(`[CanvasAnimations] Initializing canvas type: ${n}`),n){case"interactive":I.init(e,i);break;case"scroll-parallax":A.initParallax(e,i);break;case"scroll-animation":A.initScrollAnimation(e,i);break;case"data-viz":L.init(e,i);break;case"background":this.initBackgroundAnimation(e,i);break;default:d.warn(`[CanvasAnimations] Unknown canvas type: ${n}`)}},parseCanvasConfig(e){const t={};return Object.keys(e.dataset).forEach(n=>{if(n.startsWith("canvas")){const r=n.replace("canvas","").toLowerCase();let o=e.dataset[n];if(o.startsWith("{")&&o.endsWith("}")||o.startsWith("[")&&o.endsWith("]"))try{o=JSON.parse(o)}catch(i){d.warn(`[CanvasAnimations] Failed to parse JSON config: ${n}`,i)}else"true"===o?o=!0:"false"===o?o=!1:isNaN(o)||""===o||(o=parseFloat(o));t[r]=o}}),t},initBackgroundAnimation(e,t){const n=new x(e),i=t.particles||50,r=[];for(let o=0;o<i;o++)r.push({x:Math.random()*e.width,y:Math.random()*e.height,vx:.5*(Math.random()-.5),vy:.5*(Math.random()-.5),size:3*Math.random()+1,opacity:.5*Math.random()+.2});!function i(){n.clear(),n.ctx.fillStyle=t.color||"rgba(100, 150, 255, 0.6)",r.forEach(t=>{t.x+=t.vx,t.y+=t.vy,t.x<0&&(t.x=e.width),t.x>e.width&&(t.x=0),t.y<0&&(t.y=e.height),t.y>e.height&&(t.y=0),n.ctx.save(),n.ctx.globalAlpha=t.opacity,n.ctx.beginPath(),n.ctx.arc(t.x,t.y,t.size,0,2*Math.PI),n.ctx.fill(),n.ctx.restore()}),requestAnimationFrame(i)}()}},P=T.init.bind(T),$=Object.freeze(Object.defineProperty({__proto__:null,default:T,init:P},Symbol.toStringTag,{value:"Module"}));let D="example-module",_=null,O=null;const z=Object.freeze(Object.defineProperty({__proto__:null,destroy:function(){d.info("[example-module] destroy"),_&&(window.removeEventListener("resize",_),_=null),l(D),O&&"function"==typeof O.cleanup&&O.cleanup(),O=null},init:function(e={},t=null){d.info("[example-module] init"),O=t,O&&(O.register("windowSize",{width:window.innerWidth,height:window.innerHeight}),O.register("scrollPosition",{x:0,y:0}),O.register("isVisible",!0)),_=()=>{const e={width:window.innerWidth,height:window.innerHeight};d.info("Fenstergröße geändert:",e),O&&O.set("windowSize",e)},window.addEventListener("resize",_),c(D,()=>{const e=window.scrollY,t=window.scrollX;if(O){const n=O.get("scrollPosition");n.x===t&&n.y===e||O.set("scrollPosition",{x:t,y:e})}},{autoStart:!0})}},Symbol.toStringTag,{value:"Module"}));class R{constructor(e){this.form=e,this.errors=new Map}static create(e){return new R(e)}validate(){this.errors.clear();const e=this.form.querySelectorAll("input, textarea, select");for(const t of e)"hidden"===t.type||t.disabled||this.validateField(t);return 0===this.errors.size}validateField(e){const t=e.value,n=e.name;if(e.hasAttribute("required")&&(!t||""===t.trim()))return void this.errors.set(n,this.getErrorMessage(e,"valueMissing")||`${this.getFieldLabel(e)} ist erforderlich`);if(!t||""===t.trim())return;if("email"===e.type&&!this.isValidEmail(t))return void this.errors.set(n,this.getErrorMessage(e,"typeMismatch")||"Bitte geben Sie eine gültige E-Mail-Adresse ein");if("url"===e.type&&!this.isValidUrl(t))return void this.errors.set(n,this.getErrorMessage(e,"typeMismatch")||"Bitte geben Sie eine gültige URL ein");const i=e.getAttribute("minlength");if(i&&t.length<parseInt(i))return void this.errors.set(n,this.getErrorMessage(e,"tooShort")||`Mindestens ${i} Zeichen erforderlich`);const r=e.getAttribute("maxlength");if(r&&t.length>parseInt(r))return void this.errors.set(n,this.getErrorMessage(e,"tooLong")||`Maximal ${r} Zeichen erlaubt`);if("number"===e.type){const i=e.getAttribute("min"),r=e.getAttribute("max"),o=parseFloat(t);if(i&&o<parseFloat(i))return void this.errors.set(n,this.getErrorMessage(e,"rangeUnderflow")||`Wert muss mindestens ${i} sein`);if(r&&o>parseFloat(r))return void this.errors.set(n,this.getErrorMessage(e,"rangeOverflow")||`Wert darf maximal ${r} sein`)}const o=e.getAttribute("pattern");if(o){if(!new RegExp(o).test(t))return void this.errors.set(n,this.getErrorMessage(e,"patternMismatch")||"Ungültiges Format")}const a=e.getAttribute("data-validate");if(a){const i=this.runCustomValidation(a,t,e);if(!i.valid)return void this.errors.set(n,i.message)}}runCustomValidation(e,t,n){switch(e){case"phone":return{valid:/^[\+]?[0-9\s\-\(\)]{10,}$/.test(t),message:"Bitte geben Sie eine gültige Telefonnummer ein"};case"postal-code-de":return{valid:/^[0-9]{5}$/.test(t),message:"Bitte geben Sie eine gültige Postleitzahl ein"};case"no-html":return{valid:!/<[^>]*>/g.test(t),message:"HTML-Code ist nicht erlaubt"};default:return d.warn(`Unknown custom validation: ${e}`),{valid:!0,message:""}}}isValidEmail(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}isValidUrl(e){try{return new URL(e),!0}catch{return!1}}getFieldLabel(e){const t=this.form.querySelector(`label[for="${e.id}"]`)||this.form.querySelector(`label:has([name="${e.name}"])`);return t?t.textContent.trim().replace(":",""):e.name}getErrorMessage(e,t){return e.getAttribute(`data-error-${t}`)||e.getAttribute("data-error")}getErrors(){return Object.fromEntries(this.errors)}getFieldError(e){return this.errors.get(e)}hasErrors(){return this.errors.size>0}clearErrors(){this.errors.clear()}validateWithHTML5(){const e=this.form.checkValidity();if(!e){const e=this.form.querySelectorAll("input, textarea, select");for(const t of e)t.validity.valid||this.errors.set(t.name,t.validationMessage)}return e}}class F{constructor(e){this.form=e,this.pristineValues=new Map,this.touchedFields=new Set,this.dirtyFields=new Set,this.init()}static create(e){return new F(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 N{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=R.create(e),this.state=F.create(e),this.isSubmitting=!1,this.init()}static create(e,t={}){return new N(e,t)}init(){this.bindEvents(),this.setupErrorDisplay(),this.form.setAttribute("data-enhanced","true"),d.info(`[FormHandler] Initialized for form: ${this.form.id||"unnamed"}`)}bindEvents(){if(this.form.addEventListener("submit",e=>this.handleSubmit(e)),this.options.validateOnBlur||this.options.validateOnInput){this.form.querySelectorAll("input, textarea, select").forEach(e=>{this.options.validateOnBlur&&e.addEventListener("blur",()=>this.validateSingleField(e)),this.options.validateOnInput&&e.addEventListener("input",()=>this.validateSingleField(e))})}}async handleSubmit(e){if(this.isSubmitting)e.preventDefault();else{if(this.options.validateOnSubmit){if(!this.validator.validate())return e.preventDefault(),void this.displayErrors()}this.options.ajaxSubmit&&(e.preventDefault(),await this.submitViaAjax())}}async submitViaAjax(){try{this.setSubmitState(!0),this.clearErrors();const e=new FormData(this.form),t=this.form.action||window.location.href,n=this.form.method||this.options.submitMethod,i=await fetch(t,{method:n.toUpperCase(),body:e,headers:{"X-Requested-With":"XMLHttpRequest"}}),r=await this.parseResponse(i);i.ok?this.handleSuccess(r):this.handleError(r)}catch(e){d.error("[FormHandler] Submit error:",e),this.handleError({message:"Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.",errors:{}})}finally{this.setSubmitState(!1)}}async parseResponse(e){const t=e.headers.get("content-type");if(null==t?void 0:t.includes("application/json"))return await e.json();const n=await e.text();try{return JSON.parse(n)}catch{return{message:n}}}handleSuccess(e){d.info("[FormHandler] Form submitted successfully"),!1!==e.clearForm&&(this.form.reset(),this.state.reset()),this.showMessage(e.message||"Formular erfolgreich gesendet!","success"),this.triggerEvent("form:success",{data:e})}handleError(e){if(d.warn("[FormHandler] Form submission error:",e),e.errors&&"object"==typeof e.errors){for(const[t,n]of Object.entries(e.errors))this.validator.errors.set(t,n);this.displayErrors()}this.showMessage(e.message||"Ein Fehler ist aufgetreten.","error"),this.triggerEvent("form:error",{data:e})}validateSingleField(e){this.validator.errors.delete(e.name),this.validator.validateField(e),this.displayFieldError(e)}displayErrors(){if(!this.options.showInlineErrors)return;const e=this.validator.getErrors();for(const[t,n]of Object.entries(e)){const e=this.form.querySelector(`[name="${t}"]`);e&&this.displayFieldError(e,n)}}displayFieldError(e,t=null){const n=t||this.validator.getFieldError(e.name),i=this.getOrCreateErrorElement(e);n?(i.textContent=n,i.style.display="block",e.classList.add("error"),e.setAttribute("aria-invalid","true"),e.setAttribute("aria-describedby",i.id)):(i.textContent="",i.style.display="none",e.classList.remove("error"),e.removeAttribute("aria-invalid"),e.removeAttribute("aria-describedby"))}getOrCreateErrorElement(e){const t=`error-${e.name}`;let n=document.getElementById(t);if(!n){n=document.createElement("div"),n.id=t,n.className="form-error",n.setAttribute("role","alert"),n.style.display="none";(e.closest(".form-group")||e.parentElement).appendChild(n)}return n}setupErrorDisplay(){if(!document.getElementById("form-handler-styles")){const e=document.createElement("style");e.id="form-handler-styles",e.textContent="\n .form-error {\n color: #dc2626;\n font-size: 0.875rem;\n margin-top: 0.25rem;\n }\n input.error, textarea.error, select.error {\n border-color: #dc2626;\n box-shadow: 0 0 0 1px #dc2626;\n }\n .form-message {\n padding: 0.75rem;\n border-radius: 0.375rem;\n margin: 1rem 0;\n }\n .form-message.success {\n background-color: #dcfce7;\n color: #166534;\n border: 1px solid #bbf7d0;\n }\n .form-message.error {\n background-color: #fef2f2;\n color: #dc2626;\n border: 1px solid #fecaca;\n }\n ",document.head.appendChild(e)}}showMessage(e,t="info"){let n=this.form.querySelector(".form-messages");n||(n=document.createElement("div"),n.className="form-messages",this.form.prepend(n));const i=document.createElement("div");i.className=`form-message ${t}`,i.textContent=e,i.setAttribute("role","error"===t?"alert":"status"),n.innerHTML="",n.appendChild(i),"success"===t&&setTimeout(()=>{i.parentElement&&i.remove()},5e3)}clearErrors(){this.validator.clearErrors();this.form.querySelectorAll(".error").forEach(e=>{e.classList.remove("error"),e.removeAttribute("aria-invalid"),e.removeAttribute("aria-describedby")});this.form.querySelectorAll(".form-error").forEach(e=>{e.style.display="none",e.textContent=""});const e=this.form.querySelector(".form-messages");e&&(e.innerHTML="")}setSubmitState(e){this.isSubmitting=e;this.form.querySelectorAll('button[type="submit"], input[type="submit"]').forEach(t=>{if(t.disabled=e,e)t.setAttribute("data-original-text",t.textContent),t.textContent="Wird gesendet...";else{const e=t.getAttribute("data-original-text");e&&(t.textContent=e,t.removeAttribute("data-original-text"))}})}triggerEvent(e,t={}){const n=new CustomEvent(e,{detail:t,bubbles:!0,cancelable:!0});this.form.dispatchEvent(n)}destroy(){this.form.removeAttribute("data-enhanced"),d.info("[FormHandler] Destroyed")}}const B={name:"form-handling",init(e={},t=null){return d.info("[FormHandling] Module initialized (ready for DOM elements)"),this},initElement(e,t={}){d.info(`[FormHandling] Initializing on form: ${e.id||"unnamed"}`);const n={validateOnSubmit:!0,validateOnBlur:!1,validateOnInput:!1,showInlineErrors:!0,preventSubmitOnError:!0,ajaxSubmit:!0,submitMethod:"POST",enableStateTracking:!0,enableUnsavedWarning:!1,...t},i=N.create(e,n);e._formHandler=i,e._formValidator=i.validator,e._formState=i.state,n.enableUnsavedWarning&&i.state.enableUnsavedChangesWarning(),e.classList.add("form-enhanced");const r=new CustomEvent("form:initialized",{detail:{handler:i,validator:i.validator,state:i.state,config:n},bubbles:!0});return e.dispatchEvent(r),d.info(`[FormHandling] Successfully initialized for form: ${e.id||"unnamed"}`),i},destroyElement(e){e._formHandler&&(e._formHandler.destroy(),delete e._formHandler,delete e._formValidator,delete e._formState),e.classList.remove("form-enhanced"),e.removeAttribute("data-enhanced"),d.info(`[FormHandling] Destroyed for form: ${e.id||"unnamed"}`)},destroy(){d.info("[FormHandling] Module destroyed")}},q=B.init.bind(B),W=B.initElement.bind(B),j=Object.freeze(Object.defineProperty({__proto__:null,FormHandler:N,FormHandlingModule:B,FormState:F,FormValidator:R,default:B,init:q,initElement:W},Symbol.toStringTag,{value:"Module"})),H={name:"image-manager",activeGalleries:new Map,activeUploaders:new Map,async init(e={},t){return d.info("[ImageManager] Module initialized"),this.initializeGalleries(),this.initializeUploaders(),this.initializeModal(),this},initializeGalleries(){const e=document.querySelectorAll("[data-image-gallery]");d.info(`[ImageManager] Found ${e.length} gallery elements`),e.forEach((e,t)=>{const n=`gallery-${t}`,i=new V(e,{listEndpoint:e.dataset.listEndpoint||"/api/images",pageSize:parseInt(e.dataset.pageSize)||20,columns:parseInt(e.dataset.columns)||4});this.activeGalleries.set(n,i),d.info(`[ImageManager] Initialized gallery: ${n}`)})},initializeUploaders(){const e=document.querySelectorAll("[data-image-uploader]");d.info(`[ImageManager] Found ${e.length} uploader elements`),e.forEach((e,t)=>{var n;const i=`uploader-${t}`,r=new U(e,{uploadUrl:e.dataset.uploadUrl||"/api/images",maxFileSize:parseInt(e.dataset.maxFileSize)||10485760,allowedTypes:(null==(n=e.dataset.allowedTypes)?void 0:n.split(","))||["image/jpeg","image/png","image/gif","image/webp"],maxFiles:parseInt(e.dataset.maxFiles)||10});this.activeUploaders.set(i,r),d.info(`[ImageManager] Initialized uploader: ${i}`)})},initializeModal(){const e=new J;window.ImageModal=e,d.info("[ImageManager] Modal initialized")},destroy(){this.activeGalleries.forEach((e,t)=>{e.destroy(),d.info(`[ImageManager] Destroyed gallery: ${t}`)}),this.activeGalleries.clear(),this.activeUploaders.forEach((e,t)=>{e.destroy(),d.info(`[ImageManager] Destroyed uploader: ${t}`)}),this.activeUploaders.clear(),window.ImageModal&&(window.ImageModal.destroy(),delete window.ImageModal),d.info("[ImageManager] Module destroyed")}};class V{constructor(e,t){this.element=e,this.config=t,this.currentPage=1,this.images=[],this.loading=!1,this.init()}async init(){d.info("[ImageGallery] Initializing gallery"),this.element.innerHTML="",this.buildGalleryUI(),await this.loadImages()}buildGalleryUI(){this.element.innerHTML=`\n <div class="image-gallery">\n <div class="gallery__controls">\n <div class="gallery__search-wrapper">\n <input type="text" class="gallery__search" placeholder="Search images...">\n <button type="button" class="gallery__search-clear">&times;</button>\n </div>\n <div class="gallery__sort-wrapper">\n <label>Sort:</label>\n <select class="gallery__sort">\n <option value="created_desc">Newest First</option>\n <option value="created_asc">Oldest First</option>\n <option value="name_asc">Name A-Z</option>\n <option value="name_desc">Name Z-A</option>\n </select>\n </div>\n </div>\n <div class="gallery__grid" style="--columns: ${this.config.columns}"></div>\n <div class="gallery__pagination">\n <button type="button" class="gallery__load-more" style="display: none;">Load More</button>\n </div>\n <div class="gallery__loading">\n <div class="loading-spinner"></div>\n <p>Loading images...</p>\n </div>\n </div>\n `,this.setupEventListeners()}setupEventListeners(){const e=this.element.querySelector(".gallery__search"),t=this.element.querySelector(".gallery__search-clear"),n=this.element.querySelector(".gallery__sort"),i=this.element.querySelector(".gallery__load-more");let r;e.addEventListener("input",e=>{clearTimeout(r),r=setTimeout(()=>{this.searchImages(e.target.value)},300)}),t.addEventListener("click",()=>{e.value="",this.searchImages("")}),n.addEventListener("change",e=>{this.sortImages(e.target.value)}),i.addEventListener("click",()=>{this.loadMoreImages()})}async loadImages(){if(!this.loading){this.loading=!0,this.showLoading();try{d.info("[ImageGallery] Loading images from:",this.config.listEndpoint);const e=await fetch(`${this.config.listEndpoint}?page=${this.currentPage}&limit=${this.config.pageSize}`);if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);const t=await e.json();d.info("[ImageGallery] API Response:",t);let n=[],i={};t.data&&Array.isArray(t.data)?(n=t.data,i=t.meta||{}):t.images&&Array.isArray(t.images)?(n=t.images,i=t):Array.isArray(t)?(n=t,i={}):(d.warn("[ImageGallery] Unexpected API response format:",t),n=[],i={}),d.info("[ImageGallery] Processed images:",n.length),1===this.currentPage?this.images=n:this.images=[...this.images,...n],this.renderImages(),this.updateLoadMoreButton(i)}catch(e){d.error("[ImageGallery] Failed to load images:",e),this.showError(`Failed to load images: ${e.message}`)}finally{this.loading=!1,this.hideLoading()}}}renderImages(){const e=this.element.querySelector(".gallery__grid");0!==this.images.length?(e.innerHTML=this.images.map(e=>this.renderImageItem(e)).join(""),e.querySelectorAll(".gallery__item").forEach((e,t)=>{e.addEventListener("click",()=>{this.showImageModal(this.images[t])})})):e.innerHTML='\n <div class="gallery__empty">\n <div class="empty-state__icon">\n <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1">\n <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>\n <circle cx="8.5" cy="8.5" r="1.5"></circle>\n <polyline points="21,15 16,10 5,21"></polyline>\n </svg>\n </div>\n <h3>No images found</h3>\n <p>Upload some images to get started</p>\n </div>\n '}renderImageItem(e){let t="0 B",n="0 × 0";return e.file_size&&("object"==typeof e.file_size&&e.file_size.bytes?t=this.formatFileSize(e.file_size.bytes):"number"==typeof e.file_size&&(t=this.formatFileSize(e.file_size))),e.dimensions&&e.dimensions.width&&e.dimensions.height?n=`${e.dimensions.width} × ${e.dimensions.height}`:e.width&&e.height&&(n=`${e.width} × ${e.height}`),`\n <div class="gallery__item" data-image-id="${e.ulid}">\n <div class="gallery__item-inner">\n <div class="gallery__item-image">\n <img src="${e.url}" alt="${e.alt_text||e.filename}" loading="lazy">\n <div class="gallery__item-overlay">\n <div class="gallery__item-actions">\n <button type="button" class="action-btn" title="View Details">👁</button>\n <button type="button" class="action-btn" title="Edit">✏️</button>\n <button type="button" class="action-btn" title="Delete">🗑</button>\n </div>\n </div>\n </div>\n <div class="gallery__item-info">\n <div class="gallery__item-name" title="${e.original_filename||e.filename}">\n ${e.original_filename||e.filename}\n </div>\n <div class="gallery__item-meta">\n <span class="meta-item">${n}</span>\n <span class="meta-item">${t}</span>\n <span class="meta-item">${(e.mime_type||"").replace("image/","")}</span>\n </div>\n </div>\n </div>\n </div>\n `}showImageModal(e){window.ImageModal&&window.ImageModal.show(e)}formatFileSize(e){if(0===e)return"0 B";const t=Math.floor(Math.log(e)/Math.log(1024));return`${Math.round(e/Math.pow(1024,t)*100)/100} ${["B","KB","MB","GB"][t]}`}showLoading(){const e=this.element.querySelector(".gallery__loading");e&&(e.style.display="flex")}hideLoading(){const e=this.element.querySelector(".gallery__loading");e&&(e.style.display="none")}showError(e){this.element.querySelector(".gallery__grid").innerHTML=`\n <div class="gallery__error">\n <div class="error-message">\n <span>⚠️</span>\n <span>${e}</span>\n <button type="button" class="error-close" onclick="this.parentElement.parentElement.remove()">&times;</button>\n </div>\n </div>\n `}updateLoadMoreButton(e){var t;const n=this.element.querySelector(".gallery__load-more");e.has_more||e.hasMore||(null==(t=e.pagination)?void 0:t.hasMore)||!1?(n.style.display="block",n.disabled=!1):n.style.display="none"}async loadMoreImages(){this.currentPage++,await this.loadImages()}searchImages(e){const t=this.images.filter(t=>(t.filename||"").toLowerCase().includes(e.toLowerCase())||(t.original_filename||"").toLowerCase().includes(e.toLowerCase())||(t.alt_text||"").toLowerCase().includes(e.toLowerCase()));this.element.querySelector(".gallery__grid").innerHTML=t.map(e=>this.renderImageItem(e)).join("")}sortImages(e){const t=[...this.images];switch(e){case"created_desc":t.sort((e,t)=>new Date(t.created_at)-new Date(e.created_at));break;case"created_asc":t.sort((e,t)=>new Date(e.created_at)-new Date(t.created_at));break;case"name_asc":t.sort((e,t)=>(e.filename||"").localeCompare(t.filename||""));break;case"name_desc":t.sort((e,t)=>(t.filename||"").localeCompare(e.filename||""))}this.images=t,this.renderImages()}destroy(){this.element.innerHTML="",d.info("[ImageGallery] Gallery destroyed")}}class U{constructor(e,t){this.element=e,this.config=t,d.info("[ImageUploader] Uploader placeholder initialized")}destroy(){d.info("[ImageUploader] Uploader destroyed")}}class J{constructor(){d.info("[ImageModal] Modal placeholder initialized")}show(e){d.info("[ImageModal] Would show modal for image:",e)}destroy(){d.info("[ImageModal] Modal destroyed")}}const G=H.init.bind(H),K=H.destroy.bind(H),Q=Object.freeze(Object.defineProperty({__proto__:null,default:H,definition:{name:"image-manager",version:"1.0.0",dependencies:[],provides:["image-upload","image-gallery","image-modal"],priority:5},destroy:K,init:G},Symbol.toStringTag,{value:"Module"}));let X,Y="inertia-scroll",Z=0,ee=window.scrollY,te=!1,ne=.9,ie=.2;function re(){te=!0,clearTimeout(X),X=setTimeout(()=>{te=!1},50)}const oe=Object.freeze(Object.defineProperty({__proto__:null,destroy:function(){window.removeEventListener("scroll",re),l(Y),Z=0,ee=window.scrollY,te=!1,clearTimeout(X);const e=document.documentElement;delete e.dataset.scrollState,delete e.dataset.scrollDirection,delete e.dataset.scrollSpeed},init:function(e={}){ne="number"==typeof e.damping?e.damping:.9,ie="number"==typeof e.minVelocity?contig.minVelocity:.1,window.addEventListener("scroll",re,{passive:!0}),c(Y,()=>{const e=document.documentElement,t=window.scrollY,n=t-ee,i=n>0?"down":n<0?"up":"none",r=Math.abs(n);!te&&Math.abs(Z)>ie?(window.scrollTo(0,t+Z),Z*=ne,e.dataset.scrollState="inertia"):te?(Z=n,ee=t,e.dataset.scrollState="active"):delete e.dataset.scrollState,e.dataset.scrollDirection=i,e.dataset.scrollSpeed=r.toFixed(2)},{autoStart:!0})}},Symbol.toStringTag,{value:"Module"}));class ae{constructor({content:e="",className:t="",onClose:n=null}={}){this.onClose=n,this.className=t,this.isOpenState=!1,this.dialog=document.createElement("dialog"),this.dialog.className=t,this.eventCleanup=[],this.updateContent(e),this.bindEvents()}bindEvents(){this.cleanupEvents(),this.clickHandler=e=>{!e.target.closest("."+this.className+"-content")&&this.close()},this.cancelHandler=e=>{e.preventDefault(),this.close()},this.dialog.addEventListener("click",this.clickHandler),this.dialog.addEventListener("cancel",this.cancelHandler),this.eventCleanup=[()=>this.dialog.removeEventListener("click",this.clickHandler),()=>this.dialog.removeEventListener("cancel",this.cancelHandler)]}cleanupEvents(){this.eventCleanup.forEach(e=>e()),this.eventCleanup=[]}updateContent(e){this.dialog.innerHTML=`\n <form method="dialog" class="${this.className}-content">\n ${e}\n <button class="${this.className}-close" value="close">×</button>\n </form>\n `}open(){var e,t,n,i;this.dialog.parentElement||document.body.appendChild(this.dialog),(this.dialog.hasAttribute("open")||this.dialog.open)&&((null==(t=(e=this.dialog).close)?void 0:t.call(e))||this.dialog.removeAttribute("open")),(null==(i=(n=this.dialog).showModal)?void 0:i.call(n))||this.dialog.setAttribute("open",""),document.documentElement.dataset[`${this.dialog.className}Open`]="true",this.isOpenState=!0}close(){var e,t,n;this.isOpenState&&((null==(t=(e=this.dialog).close)?void 0:t.call(e))||this.dialog.removeAttribute("open"),delete document.documentElement.dataset[`${this.dialog.className}Open`],this.isOpenState=!1,null==(n=this.onClose)||n.call(this))}isOpen(){const e=this.dialog&&(this.dialog.hasAttribute("open")||this.dialog.open);return e!==this.isOpenState&&(this.isOpenState=e),this.isOpenState}destroy(){this.isOpenState&&this.close(),this.cleanupEvents(),this.dialog.parentElement&&this.dialog.remove()}}const se={modal:class extends ae{constructor(e){super({...e,className:"modal"})}},lightbox:class extends ae{constructor(e){super({...e,className:"lightbox"})}}},ce={},le={open(e,t={}){const n=se[e];if(!n)return d.warn(`[UIManager] Unknown type: ${e}`),null;if("lightbox"===e){if(ce.lightbox)return d.info("[UIManager] Reusing existing lightbox instance"),ce.lightbox.updateContent(t.content||""),ce.lightbox.open(),ce.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 ce.lightbox=e,e.open(),e}}const i=new n(t);return i.open(),i},close(e){(null==e?void 0:e.close)&&e.close()},closeByType(e){ce[e]&&this.close(ce[e])},isOpen(e){var t;return(null==(t=ce[e])?void 0:t.isOpen())||!1},destroyAll(){Object.values(ce).forEach(e=>{(null==e?void 0:e.destroy)&&e.destroy()}),Object.keys(ce).forEach(e=>{delete ce[e]})}};function de(e){let t=null;if(t="IMG"===e.target.tagName?e.target:e.target.querySelector("img"),!t)return;if("false"===t.dataset.lightbox)return;if(t.naturalWidth<200||t.naturalHeight<200)return;if(t.closest("nav, header, footer, .no-lightbox"))return;e.preventDefault();const n=function(e){if(e.dataset.lightboxSrc)return e.dataset.lightboxSrc;if(e.currentSrc)return e.currentSrc;return e.src}(t),i=t.alt||t.dataset.caption||t.title||"",r=t.closest("picture");let o;if(r){const e=r.cloneNode(!0);e.querySelector("img").className="lightbox-image",o=`\n <div class="lightbox-content">\n ${e.outerHTML}\n ${i?`<div class="lightbox-caption">${i}</div>`:""}\n </div>\n `,d.info("[Lightbox] Opening responsive image (picture element):",n)}else o=`\n <div class="lightbox-content">\n <img src="${n}" alt="${i}" class="lightbox-image" />\n ${i?`<div class="lightbox-caption">${i}</div>`:""}\n </div>\n `,d.info("[Lightbox] Opening standalone image:",n);const a=le.open("lightbox",{content:o});le.isOpen("lightbox")&&a&&d.info("[Lightbox] Reused existing lightbox instance")}const he=Object.freeze(Object.defineProperty({__proto__:null,destroy:function(){d.info("[lightbox-trigger] destroy"),document.querySelectorAll("img.lightbox-enabled").forEach(e=>{e.classList.remove("lightbox-enabled"),e.style.cursor="","Klicken zum Vergrößern"===e.title&&(e.title="")})},init:function(){d.info("[lightbox-trigger] Auto-enabling lightbox for all images (including picture/srcset)"),d.info('[lightbox-trigger] Use data-lightbox="false" to opt-out'),d.info("[lightbox-trigger] Use data-lightbox-src for custom high-res versions"),k(document,"click",de),function(){const e=document.querySelectorAll('img:not([data-lightbox="false"])');let t=0;e.forEach(e=>{e.naturalWidth<200||e.naturalHeight<200||e.closest("nav, header, footer, .no-lightbox")||(e.classList.add("lightbox-enabled"),e.style.cursor="zoom-in",e.title||e.alt||(e.title="Klicken zum Vergrößern"),t++)}),d.info(`[Lightbox] Enhanced ${t} images with lightbox functionality`)}()}},Symbol.toStringTag,{value:"Module"}));const ue=new class{patchFragment(e,t,n){const i=e.querySelector(`[data-lc-fragment="${t}"]`);if(!i)return console.warn(`[DomPatcher] Fragment not found: ${t}`),!1;const r=document.createElement("div");r.innerHTML=n;const o=r.firstElementChild;return o?o.getAttribute("data-lc-fragment")!==t?(console.warn(`[DomPatcher] Fragment name mismatch: expected ${t}, got ${o.getAttribute("data-lc-fragment")}`),!1):(this.patchElement(i,o),!0):(console.warn(`[DomPatcher] Invalid HTML for fragment: ${t}`),!1)}patchFragments(e,t){const n={};for(const[i,r]of Object.entries(t))n[i]=this.patchFragment(e,i,r);return n}patchElement(e,t){this.patchAttributes(e,t),this.patchChildren(e,t)}patchAttributes(e,t){const n=new Map,i=new Map;for(const r of e.attributes)n.set(r.name,r.value);for(const r of t.attributes)i.set(r.name,r.value);for(const[r,o]of n)i.has(r)||e.removeAttribute(r);for(const[r,o]of i)n.get(r)!==o&&e.setAttribute(r,o)}patchChildren(e,t){const n=Array.from(e.childNodes),i=Array.from(t.childNodes),r=Math.max(n.length,i.length);for(let o=0;o<r;o++){const t=n[o],r=i[o];!t&&r?e.appendChild(r.cloneNode(!0)):t&&!r?e.removeChild(t):t&&r&&(this.shouldPatch(t,r)?t.nodeType===Node.ELEMENT_NODE?this.patchElement(t,r):t.nodeType===Node.TEXT_NODE&&t.nodeValue!==r.nodeValue&&(t.nodeValue=r.nodeValue):e.replaceChild(r.cloneNode(!0),t))}}shouldPatch(e,t){if(e.nodeType!==t.nodeType)return!1;if(e.nodeType===Node.TEXT_NODE)return!0;if(e.nodeType===Node.ELEMENT_NODE){if(e.tagName!==t.tagName)return!1;const n=e.getAttribute("data-lc-key")||e.getAttribute("id"),i=t.getAttribute("data-lc-key")||t.getAttribute("id");return!n||!i||n===i}return!1}preserveFocus(e){const t=document.activeElement;if(!t||!e.contains(t))return()=>{};const n=this.getElementSelector(t),i=t.selectionStart,r=t.selectionEnd;return()=>{try{if(n){const t=e.querySelector(n);t&&t.focus&&(t.focus(),t.setSelectionRange&&"number"==typeof i&&"number"==typeof r&&t.setSelectionRange(i,r))}}catch(t){console.debug("[DomPatcher] Could not restore focus:",t)}}}getElementSelector(e){if(e.id)return`#${e.id}`;if(e.name)return`[name="${e.name}"]`;const t=e.getAttribute("data-lc-key");return t?`[data-lc-key="${t}"]`:e.tagName.toLowerCase()}},me={DISCONNECTED:"disconnected",CONNECTING:"connecting",CONNECTED:"connected",ERROR:"error"};class pe{constructor(){this.attempt=0,this.baseDelay=1e3,this.maxDelay=3e4,this.maxAttempts=10}getDelay(){const e=Math.min(this.baseDelay*Math.pow(2,this.attempt),this.maxDelay),t=.25*e*(Math.random()-.5);return Math.floor(e+t)}shouldRetry(){return this.attempt<this.maxAttempts}recordAttempt(){this.attempt++}reset(){this.attempt=0}}class ge{constructor(e=[],t={}){this.channels=e,this.options={autoReconnect:!0,heartbeatTimeout:45e3,...t},this.eventSource=null,this.state=me.DISCONNECTED,this.reconnectionStrategy=new pe,this.reconnectTimer=null,this.heartbeatTimer=null,this.lastHeartbeat=null,this.eventHandlers=new Map,this.stateChangeHandlers=new Set,this.connectionId=null}connect(){if(this.state===me.CONNECTING||this.state===me.CONNECTED)return void console.warn("[SSE] Already connecting or connected");this.setState(me.CONNECTING);const e=this.buildUrl();try{this.eventSource=new EventSource(e),this.eventSource.addEventListener("open",()=>{console.log("[SSE] Connection opened"),this.setState(me.CONNECTED),this.reconnectionStrategy.reset(),this.startHeartbeatMonitoring()}),this.eventSource.addEventListener("error",e=>{console.error("[SSE] Connection error",e),this.eventSource.readyState===EventSource.CLOSED&&this.handleDisconnect()}),this.eventSource.addEventListener("connected",e=>{const t=JSON.parse(e.data);this.connectionId=t.connection_id,console.log("[SSE] Connected with ID:",this.connectionId)}),this.eventSource.addEventListener("heartbeat",e=>{this.lastHeartbeat=Date.now()}),this.eventSource.addEventListener("disconnected",()=>{console.log("[SSE] Server initiated disconnect"),this.disconnect()}),this.eventSource.addEventListener("error",e=>{const t=JSON.parse(e.data);console.error("[SSE] Server error:",t)})}catch(t){console.error("[SSE] Failed to create EventSource",t),this.setState(me.ERROR),this.scheduleReconnect()}}disconnect(){this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.stopHeartbeatMonitoring(),this.clearReconnectTimer(),this.setState(me.DISCONNECTED),this.connectionId=null}handleDisconnect(){this.setState(me.ERROR),this.stopHeartbeatMonitoring(),this.options.autoReconnect&&this.reconnectionStrategy.shouldRetry()?this.scheduleReconnect():this.setState(me.DISCONNECTED)}scheduleReconnect(){const e=this.reconnectionStrategy.getDelay();console.log(`[SSE] Reconnecting in ${e}ms (attempt ${this.reconnectionStrategy.attempt+1})`),this.reconnectTimer=setTimeout(()=>{this.reconnectionStrategy.recordAttempt(),this.connect()},e)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}startHeartbeatMonitoring(){this.lastHeartbeat=Date.now(),this.heartbeatTimer=setInterval(()=>{Date.now()-this.lastHeartbeat>this.options.heartbeatTimeout&&(console.warn("[SSE] Heartbeat timeout - connection appears dead"),this.handleDisconnect())},5e3)}stopHeartbeatMonitoring(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}buildUrl(){const e=this.channels.join(",");return`/sse/stream?channels=${encodeURIComponent(e)}`}on(e,t){return this.eventHandlers.has(e)||(this.eventHandlers.set(e,new Set),this.eventSource&&this.eventSource.addEventListener(e,t=>{this.handleEvent(e,t)})),this.eventHandlers.get(e).add(t),()=>this.off(e,t)}off(e,t){const n=this.eventHandlers.get(e);n&&n.delete(t)}handleEvent(e,t){const n=this.eventHandlers.get(e);if(!n||0===n.size)return;let i;try{i=JSON.parse(t.data)}catch(r){return void console.error("[SSE] Failed to parse event data",r)}n.forEach(e=>{try{e(i,t)}catch(r){console.error("[SSE] Event handler error",r)}})}setState(e){const t=this.state;this.state=e,t!==e&&this.stateChangeHandlers.forEach(n=>{try{n(e,t)}catch(i){console.error("[SSE] State change handler error",i)}})}onStateChange(e){return this.stateChangeHandlers.add(e),()=>this.stateChangeHandlers.delete(e)}getState(){return this.state}isConnected(){return this.state===me.CONNECTED}getConnectionId(){return this.connectionId}addChannels(...e){const t=e.filter(e=>!this.channels.includes(e));t.length>0&&(this.channels.push(...t),this.isConnected()&&(console.log("[SSE] Reconnecting with new channels:",t),this.disconnect(),this.connect()))}removeChannels(...e){const t=this.channels.length;this.channels=this.channels.filter(t=>!e.includes(t)),this.channels.length!==t&&this.isConnected()&&(console.log("[SSE] Reconnecting with removed channels"),this.disconnect(),this.connect())}}let fe=null;function ye(e=[]){return fe||(fe=new ge(e)),fe}function ve(e=[],t=!0){return fe=new ge(e),t&&fe.connect(),fe}const be={SseClient:ge,getGlobalSseClient:ye,initSse:ve,ConnectionState:me},we=Object.freeze(Object.defineProperty({__proto__:null,SseClient:ge,default:be,getGlobalSseClient:ye,initSse:ve},Symbol.toStringTag,{value:"Module"}));class Se{constructor(e){this.liveComponentManager=e,this.observer=null,this.lazyComponents=new Map,this.loadingQueue=[],this.isProcessingQueue=!1,this.defaultOptions={rootMargin:"50px",threshold:.1}}init(){this.observer=new IntersectionObserver(e=>this.handleIntersection(e),this.defaultOptions),this.scanLazyComponents(),console.log(`[LazyLoader] Initialized with ${this.lazyComponents.size} lazy components`)}scanLazyComponents(){document.querySelectorAll("[data-live-component-lazy]").forEach(e=>{this.registerLazyComponent(e)})}registerLazyComponent(e){const t=e.dataset.liveComponentLazy;if(!t)return void console.warn("[LazyLoader] Lazy component missing componentId:",e);const n={element:e,componentId:t,threshold:parseFloat(e.dataset.lazyThreshold)||this.defaultOptions.threshold,priority:e.dataset.lazyPriority||"normal",placeholder:e.dataset.lazyPlaceholder||null,loaded:!1,loading:!1};n.placeholder&&this.showPlaceholder(e,n.placeholder),this.lazyComponents.set(e,n),this.observer.observe(e),console.log(`[LazyLoader] Registered lazy component: ${t}`)}handleIntersection(e){e.forEach(e=>{if(e.isIntersecting){const t=this.lazyComponents.get(e.target);!t||t.loaded||t.loading||this.queueComponentLoad(t)}})}queueComponentLoad(e){const t=this.getPriorityWeight(e.priority);this.loadingQueue.push({config:e,priority:t,timestamp:Date.now()}),this.loadingQueue.sort((e,t)=>t.priority!==e.priority?t.priority-e.priority:e.timestamp-t.timestamp),console.log(`[LazyLoader] Queued: ${e.componentId} (priority: ${e.priority})`),this.processLoadingQueue()}getPriorityWeight(e){return{high:3,normal:2,low:1}[e]||2}async processLoadingQueue(){if(!this.isProcessingQueue&&0!==this.loadingQueue.length){for(this.isProcessingQueue=!0;this.loadingQueue.length>0;){const{config:e}=this.loadingQueue.shift();e.loaded||e.loading||await this.loadComponent(e)}this.isProcessingQueue=!1}}async loadComponent(e){e.loading=!0;try{console.log(`[LazyLoader] Loading: ${e.componentId}`),this.showLoadingIndicator(e.element);const t=await fetch(`/live-component/${e.componentId}/lazy-load`,{method:"GET",headers:{"X-Requested-With":"XMLHttpRequest",Accept:"application/json"}});if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);const n=await t.json();if(!n.success)throw new Error(n.error||"Failed to load component");e.element.innerHTML=n.html,e.element.setAttribute("data-live-component",e.componentId),e.element.removeAttribute("data-live-component-lazy"),n.csrf_token&&(e.element.dataset.csrfToken=n.csrf_token),n.state&&(e.element.dataset.state=JSON.stringify(n.state)),this.liveComponentManager.init(e.element),e.loaded=!0,e.loading=!1,this.observer.unobserve(e.element),console.log(`[LazyLoader] Loaded: ${e.componentId}`),e.element.dispatchEvent(new CustomEvent("livecomponent:lazy:loaded",{detail:{componentId:e.componentId}}))}catch(t){console.error(`[LazyLoader] Failed to load ${e.componentId}:`,t),e.loading=!1,this.showError(e.element,t.message),e.element.dispatchEvent(new CustomEvent("livecomponent:lazy:error",{detail:{componentId:e.componentId,error:t.message}}))}}showPlaceholder(e,t){e.innerHTML=`\n <div class="livecomponent-lazy-placeholder" style="\n padding: 2rem;\n text-align: center;\n color: #666;\n background: #f5f5f5;\n border-radius: 8px;\n border: 1px dashed #ddd;\n ">\n <div style="font-size: 1.5rem; margin-bottom: 0.5rem;">⏳</div>\n <div>${t}</div>\n </div>\n `}showLoadingIndicator(e){e.innerHTML='\n <div class="livecomponent-lazy-loading" style="\n padding: 2rem;\n text-align: center;\n color: #2196F3;\n background: #f5f5f5;\n border-radius: 8px;\n border: 1px solid #e3f2fd;\n ">\n <div class="spinner" style="\n width: 40px;\n height: 40px;\n margin: 0 auto 1rem;\n border: 4px solid #e3f2fd;\n border-top: 4px solid #2196F3;\n border-radius: 50%;\n animation: spin 1s linear infinite;\n "></div>\n <div>Loading component...</div>\n </div>\n <style>\n @keyframes spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n </style>\n '}showError(e,t){e.innerHTML=`\n <div class="livecomponent-lazy-error" style="\n padding: 2rem;\n text-align: center;\n color: #d32f2f;\n background: #ffebee;\n border-radius: 8px;\n border: 1px solid #ef9a9a;\n ">\n <div style="font-size: 1.5rem; margin-bottom: 0.5rem;">❌</div>\n <div><strong>Failed to load component</strong></div>\n <div style="margin-top: 0.5rem; font-size: 0.9rem; color: #c62828;">\n ${t}\n </div>\n </div>\n `}unregister(e){const t=this.lazyComponents.get(e);t&&(this.observer.unobserve(e),this.lazyComponents.delete(e),console.log(`[LazyLoader] Unregistered: ${t.componentId}`))}destroy(){this.observer&&(this.observer.disconnect(),this.observer=null),this.loadingQueue=[],this.lazyComponents.clear(),console.log("[LazyLoader] Destroyed")}getStats(){let e=0,t=0,n=0;return this.lazyComponents.forEach(i=>{i.loaded?e++:i.loading?t++:n++}),{total:this.lazyComponents.size,loaded:e,loading:t,pending:n,queued:this.loadingQueue.length}}}class Me{constructor(e){this.liveComponentManager=e,this.hierarchyRegistry=new Map,this.childrenRegistry=new Map,this.bubbleCallbacks=new Map}init(){this.scanNestedComponents(),console.log(`[NestedComponents] Initialized with ${this.hierarchyRegistry.size} components`)}scanNestedComponents(){document.querySelectorAll("[data-parent-component]").forEach(e=>{const t=e.dataset.liveComponent,n=e.dataset.parentComponent,i=parseInt(e.dataset.nestingDepth)||1;t&&n&&this.registerHierarchy(t,n,i)});document.querySelectorAll("[data-live-component]:not([data-parent-component])").forEach(e=>{const t=e.dataset.liveComponent;t&&!this.hierarchyRegistry.has(t)&&this.registerRoot(t)})}registerRoot(e){this.hierarchyRegistry.set(e,{parentId:null,childIds:[],depth:0,path:[e]}),console.log(`[NestedComponents] Registered root: ${e}`)}registerHierarchy(e,t,n=1){const i=this.hierarchyRegistry.get(t),r=i?i.path:[t];this.hierarchyRegistry.set(e,{parentId:t,childIds:[],depth:n,path:[...r,e]}),this.childrenRegistry.has(t)||this.childrenRegistry.set(t,[]);const o=this.childrenRegistry.get(t);o.includes(e)||o.push(e),console.log(`[NestedComponents] Registered child: ${e} (parent: ${t}, depth: ${n})`)}registerDynamicChild(e,t){const n=this.hierarchyRegistry.get(t);if(!n)return void console.warn(`[NestedComponents] Cannot register child - parent not found: ${t}`);const i=n.depth+1;this.registerHierarchy(e,t,i)}getHierarchy(e){return this.hierarchyRegistry.get(e)||null}getParentId(e){const t=this.getHierarchy(e);return t?t.parentId:null}getChildIds(e){return this.childrenRegistry.get(e)||[]}hasChildren(e){return this.getChildIds(e).length>0}isRoot(e){const t=this.getHierarchy(e);return!t||null===t.parentId}getDepth(e){const t=this.getHierarchy(e);return t?t.depth:0}getAncestors(e){const t=this.getHierarchy(e);if(!t||!t.path)return[];const n=[...t.path];return n.pop(),n.reverse()}bubbleEvent(e,t,n){console.log(`[NestedComponents] Bubbling event: ${t} from ${e}`,n);let i=e,r=0;for(;;){const o=this.getParentId(i);if(null===o)return console.log(`[NestedComponents] Event bubbled to root (${r} levels)`),!0;const a=document.querySelector(`[data-live-component="${o}"]`);if(!a)return console.warn(`[NestedComponents] Parent element not found: ${o}`),!1;const s=new CustomEvent(`livecomponent:child:${t}`,{detail:{sourceId:e,eventName:t,payload:n,currentLevel:r},bubbles:!1,cancelable:!0});if(!a.dispatchEvent(s))return console.log(`[NestedComponents] Event bubbling stopped at ${o}`),!1;const c=this.bubbleCallbacks.get(o);if(c)for(const i of c){if(!1===i(e,t,n))return console.log(`[NestedComponents] Event bubbling stopped by callback at ${o}`),!1}i=o,r++}}onChildEvent(e,t){this.bubbleCallbacks.has(e)||this.bubbleCallbacks.set(e,[]),this.bubbleCallbacks.get(e).push(t),console.log(`[NestedComponents] Registered child event callback for ${e}`)}syncStateToChildren(e,t){const n=this.getChildIds(e);console.log(`[NestedComponents] Syncing state to ${n.length} children of ${e}`),n.forEach(n=>{const i=document.querySelector(`[data-live-component="${n}"]`);i&&i.dispatchEvent(new CustomEvent("livecomponent:parent:state-sync",{detail:{parentId:e,sharedState:t}}))})}async updateChildren(e,t){const n=this.getChildIds(e);console.log(`[NestedComponents] Updating ${n.length} children of ${e}`);const i=n.map(async n=>{const i=document.querySelector(`[data-live-component="${n}"]`);i&&i.dispatchEvent(new CustomEvent("livecomponent:parent:update",{detail:{parentId:e,updates:t}}))});await Promise.all(i)}unregister(e){const t=this.hierarchyRegistry.get(e);if(this.hierarchyRegistry.delete(e),t&&t.parentId){const n=this.childrenRegistry.get(t.parentId);if(n){const t=n.indexOf(e);-1!==t&&n.splice(t,1)}}this.childrenRegistry.delete(e),this.bubbleCallbacks.delete(e),console.log(`[NestedComponents] Unregistered: ${e}`)}getStats(){let e=0,t=0;return this.hierarchyRegistry.forEach(n=>{null===n.parentId&&e++,t=Math.max(t,n.depth)}),{total_components:this.hierarchyRegistry.size,root_components:e,child_components:this.hierarchyRegistry.size-e,max_nesting_depth:t,parents_with_children:this.childrenRegistry.size}}destroy(){this.hierarchyRegistry.clear(),this.childrenRegistry.clear(),this.bubbleCallbacks.clear(),console.log("[NestedComponents] Destroyed")}}const Ce=new class{constructor(){this.components=new Map,this.eventHandlers=new Map,this.debounceTimers=new Map,this.domPatcher=ue,this.sseClients=new Map,this.componentChannels=new Map,this.lazyLoader=null,this.nestedHandler=null}initLazyLoading(){this.lazyLoader?console.warn("[LiveComponent] Lazy loading already initialized"):(this.lazyLoader=new Se(this),this.lazyLoader.init(),console.log("[LiveComponent] Lazy loading system initialized"))}initNestedComponents(){this.nestedHandler?console.warn("[LiveComponent] Nested components already initialized"):(this.nestedHandler=new Me(this),this.nestedHandler.init(),console.log("[LiveComponent] Nested components system initialized"))}init(e){const t=e.dataset.liveComponent;if(!t)return;const n={id:t,element:e,pollInterval:parseInt(e.dataset.pollInterval)||null,pollTimer:null,observer:null};this.components.set(t,n),this.setupActionHandlers(e),this.setupFileUploadHandlers(e),n.pollInterval&&this.startPolling(t),this.setupLifecycleObserver(e,t),this.setupSseConnection(e,t),console.log(`[LiveComponent] Initialized: ${t}`)}setupLifecycleObserver(e,t){const n=this.components.get(t);if(!n)return;const i=new MutationObserver(n=>{document.contains(e)||(console.log(`[LiveComponent] Element removed from DOM: ${t}`),this.callDestroyHook(t),i.disconnect())});e.parentNode&&i.observe(e.parentNode,{childList:!0,subtree:!1}),n.observer=i}setupSseConnection(e,t){const n=e.dataset.sseChannel;if(!n)return;console.log(`[LiveComponent] Setting up SSE for ${t} on channel: ${n}`),this.componentChannels.set(t,n);let i=this.sseClients.get(n);i||(i=new ge([n],{autoReconnect:!0,heartbeatTimeout:45e3}),this.registerSseHandlers(i,n),i.connect(),this.sseClients.set(n,i),console.log(`[LiveComponent] Created SSE client for channel: ${n}`)),console.log(`[LiveComponent] SSE connection established for ${t}`)}registerSseHandlers(e,t){e.on("component-update",e=>{this.handleSseComponentUpdate(e,t)}),e.on("component-fragments",e=>{this.handleSseComponentFragments(e,t)}),e.on("connected",()=>{console.log(`[LiveComponent] SSE connected to channel: ${t}`),this.updateSseConnectionStatus(t,"connected")}),e.on("disconnected",()=>{console.log(`[LiveComponent] SSE disconnected from channel: ${t}`),this.updateSseConnectionStatus(t,"disconnected")}),e.on("reconnecting",e=>{console.log(`[LiveComponent] SSE reconnecting to channel ${t} (attempt ${e})`),this.updateSseConnectionStatus(t,"reconnecting")}),e.on("error",e=>{console.error(`[LiveComponent] SSE error on channel ${t}:`,e),this.updateSseConnectionStatus(t,"error")})}handleSseComponentUpdate(e,t){const{componentId:n,state:i,html:r,events:o}=e;console.log(`[LiveComponent] SSE update for ${n}:`,{state:i,html:r,events:o});const a=this.components.get(n);if(a)try{r&&(a.element.innerHTML=r,this.setupActionHandlers(a.element),this.setupFileUploadHandlers(a.element)),i&&(a.element.dataset.state=JSON.stringify(i)),o&&Array.isArray(o)&&this.handleServerEvents(o),console.log(`[LiveComponent] SSE update applied to ${n}`)}catch(s){console.error(`[LiveComponent] Failed to apply SSE update for ${n}:`,s)}else console.warn(`[LiveComponent] Received SSE update for unknown component: ${n}`)}handleSseComponentFragments(e,t){const{componentId:n,fragments:i}=e;console.log(`[LiveComponent] SSE fragments for ${n}:`,i);const r=this.components.get(n);if(r)try{this.updateFragments(r.element,i),console.log(`[LiveComponent] SSE fragments applied to ${n}`)}catch(o){console.error(`[LiveComponent] Failed to apply SSE fragments for ${n}:`,o)}else console.warn(`[LiveComponent] Received SSE fragments for unknown component: ${n}`)}updateSseConnectionStatus(e,t){this.componentChannels.forEach((n,i)=>{if(n===e){const n=this.components.get(i);if(!n)return;n.element.dataset.sseStatus=t,n.element.dispatchEvent(new CustomEvent("livecomponent:sse:status",{detail:{channel:e,status:t}}))}})}async callDestroyHook(e){const t=this.components.get(e);if(t){try{const n=t.element.dataset.state||"{}",i=JSON.parse(n),r=t.element.dataset.csrfToken,o=JSON.stringify({state:i,_csrf_token:r}),a=`/live-component/${e}/destroy`,s=new Blob([o],{type:"application/json"});navigator.sendBeacon&&navigator.sendBeacon(a,s)?console.log(`[LiveComponent] onDestroy() called via sendBeacon: ${e}`):(await fetch(a,{method:"POST",headers:{"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"},body:o}),console.log(`[LiveComponent] onDestroy() called via fetch: ${e}`))}catch(n){console.warn(`[LiveComponent] onDestroy() hook failed: ${e}`,n)}this.destroy(e)}}setupActionHandlers(e){e.querySelectorAll("[data-live-action]").forEach(t=>{if("INPUT"===t.tagName||"TEXTAREA"===t.tagName||"SELECT"===t.tagName){const n="text"===t.type||"email"===t.type||"url"===t.type||"tel"===t.type||"TEXTAREA"===t.tagName?300:0,i=parseInt(t.dataset.liveDebounce)??n;t.addEventListener("input",async n=>{const r=e.dataset.liveComponent,o=t.dataset.liveAction,a=this.extractParams(t);"checkbox"===t.type?a[t.name||"value"]=t.checked?"yes":"no":(t.type,a[t.name||"value"]=t.value);const s=this.extractFragments(t);i>0?this.debouncedAction(r,o,a,i,s):await this.executeAction(r,o,a,s)}),"radio"!==t.type&&"checkbox"!==t.type||t.addEventListener("change",async n=>{const i=e.dataset.liveComponent,r=t.dataset.liveAction,o=this.extractParams(t);"checkbox"===t.type?o[t.name||"value"]=t.checked?"yes":"no":"radio"===t.type&&(o[t.name||"value"]=t.value),await this.executeAction(i,r,o)})}else t.addEventListener("click",async n=>{n.preventDefault();const i=e.dataset.liveComponent,r=t.dataset.liveAction;let o=this.extractParams(t);if("submit"===r||"nextStep"===r||"previousStep"===r){const t=this.collectFormValues(e);console.log("[LiveComponent] Collected form values:",t),o={...t,...o},console.log("[LiveComponent] Final params:",o)}const a=this.extractFragments(t);await this.executeAction(i,r,o,a)})})}debouncedAction(e,t,n,i,r=null){const o=`${e}_${t}`;this.debounceTimers.has(o)&&clearTimeout(this.debounceTimers.get(o));const a=setTimeout(async()=>{await this.executeAction(e,t,n,r),this.debounceTimers.delete(o)},i);this.debounceTimers.set(o,a)}extractParams(e){const t={};return Object.keys(e.dataset).forEach(n=>{if(n.startsWith("param")){const i=n.replace("param","");if(i.endsWith("From")){const r=i.replace(/From$/,"").toLowerCase(),o=e.dataset[n];t[r]="value"===o?e.value:e[o]||e.getAttribute(o)}else{const r=i.toLowerCase();t[r]=e.dataset[n]}}}),t}extractFragments(e){const t=e.dataset.lcFragments;return t?t.split(",").map(e=>e.trim()).filter(Boolean):null}collectFormValues(e){const t={};return e.querySelectorAll("input, textarea, select").forEach(e=>{const n=e.name;n&&("checkbox"===e.type?t[n]=e.checked?"yes":"no":"radio"===e.type?e.checked&&(t[n]=e.value):t[n]=e.value)}),t}async executeAction(e,t,n={},i=null){const r=this.components.get(e);if(r)try{const a=r.element.dataset.state||"{}",s=JSON.parse(a),c=s.data||s,l=r.element.dataset.csrfToken;if(!l)throw console.error(`[LiveComponent] Missing CSRF token for component: ${e}`),new Error("CSRF token is required for component actions");const d={method:t,params:n,state:c,_csrf_token:l};i&&Array.isArray(i)&&i.length>0&&(d.fragments=i);const h=await fetch(`/live-component/${e}`,{method:"POST",headers:{"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"},body:JSON.stringify(d)});if(!h.ok){const e=await h.text();throw console.error("[LiveComponent] Server error response:",e),new Error(`HTTP ${h.status}: ${h.statusText}`)}const u=await h.text();let m;console.log("[LiveComponent] Raw response:",u.substring(0,200));try{m=JSON.parse(u)}catch(o){throw console.error("[LiveComponent] JSON parse error:",o),console.error("[LiveComponent] Response text:",u),new Error(`Failed to parse JSON response: ${o.message}`)}m.fragments?this.updateFragments(r.element,m.fragments):m.html&&(r.element.innerHTML=m.html,this.setupActionHandlers(r.element)),m.state&&(r.element.dataset.state=JSON.stringify(m.state)),m.events&&m.events.length>0&&this.handleServerEvents(m.events),console.log(`[LiveComponent] Action executed: ${e}.${t}`,m)}catch(a){console.error("[LiveComponent] Action failed:",a),this.handleError(e,a)}else console.error(`[LiveComponent] Unknown component: ${e}`)}updateFragments(e,t){const n=this.domPatcher.preserveFocus(e),i=this.domPatcher.patchFragments(e,t);n(),Object.keys(t).forEach(t=>{if(i[t]){const n=e.querySelector(`[data-lc-fragment="${t}"]`);n&&this.setupActionHandlers(n)}});const r=Object.values(i).filter(Boolean).length;console.log(`[LiveComponent] Patched ${r}/${Object.keys(t).length} fragments`,i)}handleServerEvents(e){e.forEach(e=>{const{name:t,payload:n,target:i}=e;console.log("[LiveComponent] Server event:",{name:t,payload:n,target:i}),i?this.dispatchToComponent(i,t,n):this.broadcast(t,n)})}dispatchToComponent(e,t,n){(this.eventHandlers.get(t)||[]).forEach(t=>{t.componentId===e&&t.callback(n)})}broadcast(e,t){(this.eventHandlers.get(e)||[]).forEach(e=>{e.callback(t)}),document.dispatchEvent(new CustomEvent(`livecomponent:${e}`,{detail:t}))}on(e,t,n){this.eventHandlers.has(t)||this.eventHandlers.set(t,[]),this.eventHandlers.get(t).push({componentId:e,callback:n}),console.log(`[LiveComponent] Event listener registered: ${e} -> ${t}`)}startPolling(e){const t=this.components.get(e);t&&t.pollInterval&&(t.pollTimer&&clearInterval(t.pollTimer),t.pollTimer=setInterval(async()=>{await this.executeAction(e,"poll",{})},t.pollInterval),console.log(`[LiveComponent] Polling started: ${e} (${t.pollInterval}ms)`))}stopPolling(e){const t=this.components.get(e);t&&t.pollTimer&&(clearInterval(t.pollTimer),t.pollTimer=null,console.log(`[LiveComponent] Polling stopped: ${e}`))}handleError(e,t){const n=this.components.get(e);if(!n)return;const i=`\n <div class="livecomponent-error" style="padding: 1rem; background: #fee; color: #c00; border: 1px solid #faa; border-radius: 4px;">\n <strong>LiveComponent Error:</strong> ${t.message}\n </div>\n `;n.element.insertAdjacentHTML("beforeend",i),setTimeout(()=>{var e;null==(e=n.element.querySelector(".livecomponent-error"))||e.remove()},5e3)}setupFileUploadHandlers(e){const t=e.dataset.liveComponent;e.querySelectorAll('input[type="file"][data-live-upload]').forEach(e=>{e.addEventListener("change",async e=>{const n=e.target.files;n.length>0&&await this.uploadFile(t,n[0])})}),e.querySelectorAll("[data-live-dropzone]").forEach(e=>{this.setupDropzone(t,e)})}setupDropzone(e,t){["dragenter","dragover","dragleave","drop"].forEach(e=>{t.addEventListener(e,e=>{e.preventDefault(),e.stopPropagation()})}),["dragenter","dragover"].forEach(e=>{t.addEventListener(e,()=>{t.classList.add("drag-over")})}),["dragleave","drop"].forEach(e=>{t.addEventListener(e,()=>{t.classList.remove("drag-over")})}),t.addEventListener("drop",async t=>{const n=t.dataTransfer.files;n.length>0&&await this.uploadFile(e,n[0])})}async uploadFile(e,t,n={}){const i=this.components.get(e);if(i)try{const r=i.element.dataset.state||"{}",o=JSON.parse(r),a=new FormData;a.append("file",t),a.append("state",JSON.stringify(o)),a.append("params",JSON.stringify(n));const s=i.element.dataset.csrfToken;if(!s)throw console.error(`[LiveComponent] Missing CSRF token for upload: ${e}`),new Error("CSRF token is required for file uploads");a.append("_csrf_token",s),this.showUploadProgress(e,0);const c=await fetch(`/live-component/${e}/upload`,{method:"POST",headers:{"X-Requested-With":"XMLHttpRequest"},body:a});if(!c.ok){const e=await c.json();throw new Error(e.error||"Upload failed")}const l=await c.json();if(!l.success)throw new Error(l.error||"Upload failed");l.html&&(i.element.innerHTML=l.html,this.setupActionHandlers(i.element),this.setupFileUploadHandlers(i.element)),l.state&&(i.element.dataset.state=JSON.stringify(l.state)),l.events&&l.events.length>0&&this.handleServerEvents(l.events),this.hideUploadProgress(e),console.log(`[LiveComponent] File uploaded: ${e}`,l.file),document.dispatchEvent(new CustomEvent("livecomponent:upload:success",{detail:{componentId:e,file:l.file}}))}catch(r){console.error("[LiveComponent] Upload failed:",r),this.hideUploadProgress(e),this.handleError(e,r),document.dispatchEvent(new CustomEvent("livecomponent:upload:error",{detail:{componentId:e,error:r.message}}))}else console.error(`[LiveComponent] Unknown component: ${e}`)}showUploadProgress(e,t){const n=this.components.get(e);if(!n)return;let i=n.element.querySelector(".livecomponent-upload-progress");if(i){i.querySelector(".progress-bar").style.width=`${t}%`}else{i=document.createElement("div"),i.className="livecomponent-upload-progress",i.style.cssText="\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n height: 3px;\n background: #e0e0e0;\n z-index: 1000;\n ";const e=document.createElement("div");e.className="progress-bar",e.style.cssText=`\n height: 100%;\n background: #2196F3;\n transition: width 0.3s ease;\n width: ${t}%;\n `,i.appendChild(e),n.element.style.position="relative",n.element.appendChild(i)}}hideUploadProgress(e){const t=this.components.get(e);if(!t)return;const n=t.element.querySelector(".livecomponent-upload-progress");n&&n.remove()}destroy(e){const t=this.components.get(e);this.stopPolling(e),t&&t.observer&&t.observer.disconnect(),this.cleanupSseConnection(e),this.components.delete(e),this.eventHandlers.forEach((t,n)=>{const i=t.filter(t=>t.componentId!==e);this.eventHandlers.set(n,i)}),console.log(`[LiveComponent] Destroyed: ${e}`)}cleanupSseConnection(e){const t=this.componentChannels.get(e);if(!t)return;this.componentChannels.delete(e);let n=!1;for(const[,i]of this.componentChannels)if(i===t){n=!0;break}if(!n){const e=this.sseClients.get(t);e&&(e.disconnect(),this.sseClients.delete(t),console.log(`[LiveComponent] Disconnected SSE client for channel: ${t}`))}}async executeBatch(e,t={}){if(!Array.isArray(e)||0===e.length)throw new Error("Operations must be a non-empty array");const n={operations:e.map(e=>({componentId:e.componentId,method:e.method,params:e.params||{},fragments:e.fragments||null,operationId:e.operationId||null}))};console.log(`[LiveComponent] Executing batch with ${e.length} operations`,n);try{const e=await fetch("/live-component/batch",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n)});if(!e.ok){const t=await e.json();throw new Error(t.error||"Batch request failed")}const i=await e.json();return console.log(`[LiveComponent] Batch completed: ${i.success_count} succeeded, ${i.failure_count} failed`),!1!==t.autoApply&&await this.applyBatchResults(i.results),i}catch(i){throw console.error("[LiveComponent] Batch execution failed:",i),i}}async applyBatchResults(e){for(const n of e){if(!n.success){console.warn("[LiveComponent] Batch operation failed:",n);continue}const e=n.componentId||this.extractComponentIdFromResult(n);if(!e)continue;const i=this.components.get(e);if(i)try{n.fragments?this.updateFragments(i.element,n.fragments):n.html&&(i.element.innerHTML=n.html,this.setupActionHandlers(i.element)),n.state&&(i.element.dataset.state=JSON.stringify(n.state)),n.events&&Array.isArray(n.events)&&n.events.forEach(t=>{this.dispatchComponentEvent(e,t.name,t.payload||{})})}catch(t){console.error(`[LiveComponent] Failed to apply batch result for ${e}:`,t)}}}extractComponentIdFromResult(e){return e.componentId||null}queueBatchOperation(e,t={}){this.batchQueue||(this.batchQueue=[],this.batchQueueTimer=null),this.batchQueue.push(e),this.batchQueueTimer&&clearTimeout(this.batchQueueTimer);const n=t.flushDelay||50;this.batchQueueTimer=setTimeout(()=>{this.flushBatchQueue()},n)}async flushBatchQueue(){if(!this.batchQueue||0===this.batchQueue.length)return;const e=[...this.batchQueue];this.batchQueue=[],this.batchQueueTimer=null;try{await this.executeBatch(e)}catch(t){console.error("[LiveComponent] Batch queue flush failed:",t)}}};window.LiveComponent=Ce,"loading"===document.readyState&&document.addEventListener("DOMContentLoaded",()=>{document.querySelectorAll("[data-livecomponent]").forEach(e=>{Ce.init(e)})});const Ee=Object.freeze(Object.defineProperty({__proto__:null,ComponentPlayground:class{constructor(e){if(this.container=document.querySelector(e),!this.container)throw new Error(`Container not found: ${e}`);this.components=[],this.selectedComponent=null,this.componentMetadata=null,this.currentState={},this.previewInstanceId=`playground-${Date.now()}`,this.componentList=null,this.componentSearch=null,this.stateEditor=null,this.previewContainer=null,this.actionTester=null,this.metricsDisplay=null,this.metrics={renderTime:0,stateSize:0,actionExecutions:0}}async init(){this.buildUI(),await this.loadComponents(),this.attachEventListeners()}buildUI(){this.container.innerHTML='\n <div class="playground">\n \x3c!-- Header --\x3e\n <header class="playground__header">\n <h1 class="playground__title">LiveComponent Playground</h1>\n <p class="playground__subtitle">Interactive development tool for testing LiveComponents</p>\n </header>\n\n \x3c!-- Main Layout --\x3e\n <div class="playground__layout">\n \x3c!-- Sidebar: Component Selector --\x3e\n <aside class="playground__sidebar">\n <div class="playground__search">\n <input\n type="text"\n id="component-search"\n class="playground__search-input"\n placeholder="Search components..."\n autocomplete="off"\n />\n </div>\n <div id="component-list" class="playground__component-list">\n <div class="playground__loading">Loading components...</div>\n </div>\n </aside>\n\n \x3c!-- Main Content --\x3e\n <main class="playground__main">\n \x3c!-- State Editor --\x3e\n <section class="playground__section">\n <h2 class="playground__section-title">Component State</h2>\n <div class="playground__state-editor">\n <textarea\n id="state-editor"\n class="playground__textarea"\n placeholder=\'{\n "property": "value"\n}\'\n rows="10"\n ></textarea>\n <div class="playground__editor-actions">\n <button id="apply-state" class="playground__button playground__button--primary">\n Apply State\n </button>\n <button id="reset-state" class="playground__button">\n Reset\n </button>\n <button id="format-json" class="playground__button">\n Format JSON\n </button>\n </div>\n <div id="state-validation" class="playground__validation"></div>\n </div>\n </section>\n\n \x3c!-- Live Preview --\x3e\n <section class="playground__section">\n <h2 class="playground__section-title">Live Preview</h2>\n <div id="preview-container" class="playground__preview">\n <div class="playground__empty">\n Select a component to preview\n </div>\n </div>\n <div id="metrics-display" class="playground__metrics"></div>\n </section>\n\n \x3c!-- Action Tester --\x3e\n <section class="playground__section">\n <h2 class="playground__section-title">Actions</h2>\n <div id="action-tester" class="playground__actions">\n <div class="playground__empty">\n Select a component to test actions\n </div>\n </div>\n </section>\n\n \x3c!-- Code Generator --\x3e\n <section class="playground__section">\n <h2 class="playground__section-title">Template Code</h2>\n <div class="playground__code-generator">\n <pre id="generated-code" class="playground__code"><code>Select a component to generate code</code></pre>\n <button id="copy-code" class="playground__button">\n Copy to Clipboard\n </button>\n </div>\n </section>\n </main>\n </div>\n </div>\n ',this.componentList=this.container.querySelector("#component-list"),this.componentSearch=this.container.querySelector("#component-search"),this.stateEditor=this.container.querySelector("#state-editor"),this.previewContainer=this.container.querySelector("#preview-container"),this.actionTester=this.container.querySelector("#action-tester"),this.metricsDisplay=this.container.querySelector("#metrics-display")}async loadComponents(){try{const e=await fetch("/playground/api/components"),t=await e.json();this.components=t.components||[],this.renderComponentList(this.components)}catch(e){this.componentList.innerHTML=`\n <div class="playground__error">\n Failed to load components: ${e.message}\n </div>\n `}}renderComponentList(e){0!==e.length?this.componentList.innerHTML=e.map(e=>`\n <div class="playground__component-item" data-component="${e.name}">\n <div class="playground__component-name">${e.name}</div>\n <div class="playground__component-meta">\n <span class="playground__badge">${e.properties} props</span>\n <span class="playground__badge">${e.actions} actions</span>\n ${e.has_cache?'<span class="playground__badge playground__badge--cache">cached</span>':""}\n </div>\n </div>\n `).join(""):this.componentList.innerHTML='<div class="playground__empty">No components found</div>'}attachEventListeners(){this.componentList.addEventListener("click",e=>{const t=e.target.closest(".playground__component-item");t&&this.selectComponent(t.dataset.component)}),this.componentSearch.addEventListener("input",e=>{this.filterComponents(e.target.value)}),this.container.querySelector("#apply-state").addEventListener("click",()=>{this.applyState()}),this.container.querySelector("#reset-state").addEventListener("click",()=>{this.resetState()}),this.container.querySelector("#format-json").addEventListener("click",()=>{this.formatJSON()}),this.container.querySelector("#copy-code").addEventListener("click",()=>{this.copyCode()})}filterComponents(e){const t=e.toLowerCase().trim();if(!t)return void this.renderComponentList(this.components);const n=this.components.filter(e=>e.name.toLowerCase().includes(t)||e.class.toLowerCase().includes(t));this.renderComponentList(n)}async selectComponent(e){this.componentList.querySelectorAll(".playground__component-item").forEach(e=>{e.classList.remove("playground__component-item--active")});const t=this.componentList.querySelector(`[data-component="${e}"]`);t&&t.classList.add("playground__component-item--active"),this.selectedComponent=e,await this.loadComponentMetadata(e),this.resetState(),this.renderActions(),this.updateGeneratedCode()}async loadComponentMetadata(e){try{const t=await fetch(`/playground/api/component/${e}`),n=await t.json();n.success?this.componentMetadata=n.data:console.error("Failed to load metadata:",n.error)}catch(t){console.error("Error loading metadata:",t)}}async applyState(){const e=this.stateEditor.value.trim(),t=this.container.querySelector("#state-validation");try{const n=e?JSON.parse(e):{};this.currentState=n,t.innerHTML='<span class="playground__success">✓ Valid JSON</span>',await this.previewComponent()}catch(n){t.innerHTML=`<span class="playground__error">✗ Invalid JSON: ${n.message}</span>`}}resetState(){this.currentState={},this.stateEditor.value="{}",this.container.querySelector("#state-validation").innerHTML="",this.selectedComponent&&this.previewComponent()}formatJSON(){try{const e=JSON.parse(this.stateEditor.value||"{}");this.stateEditor.value=JSON.stringify(e,null,2),this.container.querySelector("#state-validation").innerHTML='<span class="playground__success">✓ Formatted</span>'}catch(e){this.container.querySelector("#state-validation").innerHTML='<span class="playground__error">✗ Invalid JSON</span>'}}async previewComponent(){if(this.selectedComponent){this.previewContainer.innerHTML='<div class="playground__loading">Loading preview...</div>';try{performance.now();const e=await fetch("/playground/api/preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({component_name:this.selectedComponent,state:this.currentState,instance_id:this.previewInstanceId})}),t=await e.json();performance.now();t.success?(this.previewContainer.innerHTML=t.html,this.metrics.renderTime=t.render_time_ms,this.metrics.stateSize=JSON.stringify(t.state).length,this.updateMetrics(),window.LiveComponent&&window.LiveComponent.initComponent(this.previewContainer.firstElementChild)):this.previewContainer.innerHTML=`\n <div class="playground__error">\n Preview failed: ${t.error}\n </div>\n `}catch(e){this.previewContainer.innerHTML=`\n <div class="playground__error">\n Error: ${e.message}\n </div>\n `}}}renderActions(){if(!this.componentMetadata||!this.componentMetadata.actions)return void(this.actionTester.innerHTML='<div class="playground__empty">No actions available</div>');const e=this.componentMetadata.actions.filter(e=>!["onMount","onUpdated","onDestroy"].includes(e.name));0!==e.length?(this.actionTester.innerHTML=e.map(e=>`\n <div class="playground__action">\n <button\n class="playground__button playground__button--action"\n data-action="${e.name}"\n >\n ${e.name}()\n </button>\n ${e.parameters.length>0?`\n <div class="playground__action-params">\n ${e.parameters.map(e=>`\n <label>\n ${e.name} (${e.type}):\n <input type="text" data-param="${e.name}" placeholder="${e.type}" />\n </label>\n `).join("")}\n </div>\n `:""}\n </div>\n `).join(""),this.actionTester.querySelectorAll("[data-action]").forEach(e=>{e.addEventListener("click",()=>{this.executeAction(e.dataset.action,e.closest(".playground__action"))})})):this.actionTester.innerHTML='<div class="playground__empty">No actions available</div>'}async executeAction(e,t){const n={};t&&t.querySelectorAll("[data-param]").forEach(e=>{const t=e.dataset.param;let i=e.value;"true"===i?i=!0:"false"===i?i=!1:isNaN(i)||""===i||(i=Number(i)),n[t]=i});try{const t=await fetch("/playground/api/action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({component_id:`${this.selectedComponent}:${this.previewInstanceId}`,action_name:e,parameters:n,current_state:this.currentState})}),i=await t.json();i.success?(this.currentState=i.new_state,this.stateEditor.value=JSON.stringify(this.currentState,null,2),this.previewContainer.innerHTML=i.html,this.metrics.actionExecutions++,this.updateMetrics(),window.LiveComponent&&window.LiveComponent.initComponent(this.previewContainer.firstElementChild)):alert(`Action failed: ${i.error}`)}catch(i){alert(`Error executing action: ${i.message}`)}}updateMetrics(){this.metricsDisplay.innerHTML=`\n <div class="playground__metrics-grid">\n <div class="playground__metric">\n <span class="playground__metric-label">Render Time</span>\n <span class="playground__metric-value">${this.metrics.renderTime.toFixed(2)}ms</span>\n </div>\n <div class="playground__metric">\n <span class="playground__metric-label">State Size</span>\n <span class="playground__metric-value">${this.metrics.stateSize} bytes</span>\n </div>\n <div class="playground__metric">\n <span class="playground__metric-label">Actions Executed</span>\n <span class="playground__metric-value">${this.metrics.actionExecutions}</span>\n </div>\n </div>\n `}updateGeneratedCode(){if(!this.selectedComponent)return;const e=`\x3c!-- Use in your template --\x3e\n{{{ ${this.selectedComponent} }}}`;this.container.querySelector("#generated-code code").textContent=e}async copyCode(){const e=this.container.querySelector("#generated-code code").textContent;try{await navigator.clipboard.writeText(e);const t=this.container.querySelector("#copy-code"),n=t.textContent;t.textContent="✓ Copied!",setTimeout(()=>{t.textContent=n},2e3)}catch(t){alert("Failed to copy code to clipboard")}}},LiveComponent:Ce,default:Ce,definition:{name:"livecomponent",version:"1.0.0",dependencies:[],provides:["LiveComponent"],priority:0},init:async function(e={},t={}){console.log("[LiveComponent] Module initializing..."),Ce.initLazyLoading(),Ce.initNestedComponents();const n=document.querySelectorAll("[data-live-component]");console.log(`[LiveComponent] Found ${n.length} regular components to initialize`),n.forEach(e=>{Ce.init(e)});const i=document.querySelectorAll("[data-live-component-lazy]");if(console.log(`[LiveComponent] Found ${i.length} lazy components (will load on demand)`),Ce.nestedHandler){const e=Ce.nestedHandler.getStats();console.log(`[LiveComponent] Nested components: ${e.child_components} children across ${e.root_components} roots (max depth: ${e.max_nesting_depth})`)}return console.log("[LiveComponent] Module initialized"),{manager:Ce,state:t}},initElement:function(e,t={}){console.log("[LiveComponent] Initializing element with data-module:",e);const n=e.querySelectorAll("[data-live-component]");return 0===n.length&&e.hasAttribute("data-live-component")?Ce.init(e):n.forEach(e=>Ce.init(e)),Ce}},Symbol.toStringTag,{value:"Module"}));const ke=Object.freeze(Object.defineProperty({__proto__:null,init:function(e={}){d.log("Noise Toggle Init",e);const{selector:t=".noise-overlay",toggleKey:n="g",className:i="grainy",enableTransition:r=!0}=e,o=document.body,a=document.querySelector(t);if(!a)return;function s(){r?a.classList.toggle("hidden",!o.classList.contains(i)):a.style.display=o.classList.contains(i)?"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()))||(o.classList.toggle(i),s())})}},Symbol.toStringTag,{value:"Module"}));const xe=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 i=parseFloat(n.getAttribute(t.speedAttr))||t.defaultSpeed,r=e*i;n.style.transform=`translateY(${r}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=[],i=r=>{if(t.has(r))throw new Error(`Circular dependency detected involving '${r}'`);if(e.has(r))return;const o=this.modules.get(r);o&&(t.add(r),o.dependencies.forEach(e=>{e.optional&&!this.modules.has(e.name)||i(e.name)}),t.delete(r),e.add(r),n.push(r))};return Array.from(this.modules.entries()).sort(([,e],[,t])=>(t.priority||0)-(e.priority||0)).map(([e])=>e).forEach(t=>{e.has(t)||i(t)}),this.initializationOrder=n,d.info(`[DependencyManager] Initialization order: ${n.join(" → ")}`),n}checkDependencies(e){const t=this.modules.get(e);if(!t)return{satisfied:!1,missing:[],reason:`Module '${e}' not registered`};const n=[],i=[];return t.dependencies.forEach(e=>{this.modules.get(e.name)?this.initialized.has(e.name)||e.optional||n.push(`${e.name} (not initialized)`):e.optional?i.push(e.name):n.push(e.name)}),{satisfied:0===n.length,missing:n,optional:i,reason:n.length>0?`Missing: ${n.join(", ")}`:"OK"}}markInitialized(e){this.initialized.add(e),this.initializing.delete(e),d.info(`[DependencyManager] '${e}' initialized`)}markInitializing(e){this.initializing.add(e)}getDependents(e){return this.dependents.get(e)||[]}getModule(e){return this.modules.get(e)}isReadyToInitialize(e){if(this.initialized.has(e)||this.initializing.has(e))return!1;return this.checkDependencies(e).satisfied}getStatus(){const e=this.modules.size,t=this.initialized.size,n=this.initializing.size;return{total:e,initialized:t,initializing:n,pending:e-t-n,modules:{initialized:Array.from(this.initialized),initializing:Array.from(this.initializing),pending:Array.from(this.modules.keys()).filter(e=>!this.initialized.has(e)&&!this.initializing.has(e))}}}validateDefinition(e){if(!e.name||"string"!=typeof e.name)return d.error("[DependencyManager] Module name is required and must be string"),!1;if(!e.version||"string"!=typeof e.version)return d.error(`[DependencyManager] Version is required for module '${e.name}'`),!1;if(!Array.isArray(e.dependencies))return d.error(`[DependencyManager] Dependencies must be array for module '${e.name}'`),!1;for(const t of e.dependencies)if(!t.name||"string"!=typeof t.name)return d.error(`[DependencyManager] Invalid dependency in module '${e.name}': missing name`),!1;return!0}reset(){this.modules.clear(),this.dependents.clear(),this.initialized.clear(),this.initializing.clear(),this.initializationOrder=[],d.info("[DependencyManager] Reset complete")}static createDefinition(e,t){const n={name:e,version:t,dependencies:[],provides:[],priority:0},i={depends(e,t="*",i=!1){return n.dependencies.push({name:e,version:t,optional:i}),this},provides(...e){return n.provides.push(...e),this},priority(e){return n.priority=e,this},build:()=>n};return Object.setPrototypeOf(i,n),Object.keys(n).forEach(e=>{e in i||Object.defineProperty(i,e,{get:()=>n[e],set(t){n[e]=t},enumerable:!0,configurable:!0})}),i}}const Ie=new Ae;"undefined"!=typeof window&&(window.dependencyManager=Ie,window.depStatus=()=>Ie.getStatus());const Le=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 Te=null,Pe=null;const $e=Object.freeze(Object.defineProperty({__proto__:null,definition:Le,destroy:function(){d.info("[scroll-dependent] destroy"),Te&&Pe&&(Pe.unsubscribe(Te),Te=null),Pe&&"function"==typeof Pe.cleanup&&Pe.cleanup(),Pe=null},init:function(e={},t=null){d.info("[scroll-dependent] init"),Pe=t,Pe&&(Pe.register("isScrolling",!1),Pe.register("scrollDirection","none"),Te=Pe.subscribe("example-module.scrollPosition",(e,t)=>{if(t.y!==e.y){const n=e.y>t.y?"down":"up";Pe.set("scrollDirection",n),Pe.set("isScrolling",!0),setTimeout(()=>{Pe&&Pe.set("isScrolling",!1)},150),d.info(`[scroll-dependent] Scroll ${n}: ${e.y}`)}}))}},Symbol.toStringTag,{value:"Module"}));const De=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,i=window.scrollX;t.forEach(t=>{const r=parseFloat(t.dataset.scrollSpeed||e.speed||.2),o=t.dataset.scrollAxis||"y",a=t.dataset.scrollType||"translate",s="true"===t.dataset.loopPause,c=parseFloat(t.dataset.loopOffset||0),l=parseFloat(t.dataset.loopLimit||0),d="x"===o?i:n;if(l&&d>l)return;if(s&&(t.matches(":hover")||t.matches(":active")))return;const h=(d+c)*r;switch(a){case"translate":{const e=-h%("x"===o?t.offsetWidth:t.offsetHeight),n="x"===o?`translateX(${e}px)`:`translateY(${e}px)`;t.style.transform=n;break}case"rotate":{const e=h%360;t.style.transform=`rotate(${e}deg)`;break}case"background":{const e=h%100;t.style.backgroundPosition="x"===o?`${e}% center`:`center ${e}%`;break}case"scale":{const e=1+.1*Math.sin(.01*h);t.style.transform=`scale(${e.toFixed(3)})`;break}}})},{autoStart:!0})}},Symbol.toStringTag,{value:"Module"})),_e={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 Oe=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 i,r;const o=n.el.getBoundingClientRect(),a=o.top<e&&o.bottom>0;a&&!n.active&&(n.active=!0,n.el.classList.add("active"),d.log(`➡️ ENTER step ${n.index}`),null==(i=_e.onEnter)||i.call(_e,n.index,n.el)),!a&&n.active&&(n.active=!1,n.el.classList.remove("active"),d.log(`⬅️ LEAVE step ${n.index}`),t.once||null==(r=_e.onLeave)||r.call(_e,n.index,n.el))})},{autoStart:!0})}},Symbol.toStringTag,{value:"Module"}));const ze=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 Re{constructor(e){if(this.element=this.resolveElement(e.element),this.target=e.target?this.element.querySelector(e.target):this.element,e.target&&!this.target)throw new Error(`Target selector '${e.target}' not found inside element '${e.element}'.`);this.start=e.start||"top 80%",this.end=e.end||"bottom 20%",this.scrub=e.scrub||!1,this.onEnter=e.onEnter||null,this.onLeave=e.onLeave||null,this.onUpdate=e.onUpdate||null,this._wasVisible=!1,this._progress=0}resolveElement(e){if("string"==typeof e){const t=document.querySelectorAll(e);if(1===t.length)return t[0];throw new Error(`Selector '${e}' matched ${t.length} elements, expected exactly 1.`)}return e}getScrollProgress(e){const t=this.element.getBoundingClientRect(),n=this.parsePosition(this.start,e),i=this.parsePosition(this.end,e)-n,r=t.top-n;return 1-Math.min(Math.max(r/i,0),1)}parsePosition(e,t){const[n,i]=e.split(" ");return("top"===n?0:t)-t*(parseFloat(i)/100)}update(e){const t=this.element.getBoundingClientRect(),n=t.bottom>0&&t.top<e;if(n&&!this._wasVisible&&(this._wasVisible=!0,this.onEnter&&this.onEnter(this.target)),!n&&this._wasVisible&&(this._wasVisible=!1,this.onLeave&&this.onLeave(this.target)),this.scrub&&n){const t=this.getScrollProgress(e);this.onUpdate&&this.onUpdate(this.target,t)}}}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 i=new Re({...e,element:t});ze.register(i),n.push(i)}),1===n.length?n[0]:n},init:function(e={}){const{selector:t=".fade-in-on-scroll, .zoom-in, .fade-out, .fade",offset:n=.85,baseDelay:i=.05,once:r=!0}=e,o=Array.from(document.querySelectorAll(t)).map(e=>({el:e,triggered:!1}));requestAnimationFrame(function e(){const t=window.innerHeight*n;o.forEach((e,n)=>{if(e.triggered&&r)return;e.el.getBoundingClientRect().top<t?(e.el.style.transitionDelay=n*i+"s",e.el.classList.add("visible","entered"),e.el.classList.remove("fade-out"),e.triggered=!0):r||(e.el.classList.remove("visible","entered"),e.triggered=!1)}),requestAnimationFrame(e)})}},Symbol.toStringTag,{value:"Module"})),Ne=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));class Be{constructor(e={}){this.options={containerSelector:"main",linkSelector:'a[href^="/"]',loadingClass:"spa-loading",excludeSelector:'[data-spa="false"], [download], [target="_blank"], [href^="mailto:"], [href^="tel:"], [href^="#"]',enableTransitions:!0,transitionDuration:100,skeletonTemplate:this.createSkeletonTemplate(),...e},this.container=null,this.isLoading=!1,this.currentUrl=window.location.href,this.abortController=null,this.handleLinkClick=this.handleLinkClick.bind(this),this.handlePopState=this.handlePopState.bind(this),this.handleFormSubmit=this.handleFormSubmit.bind(this),this.init()}static create(e={}){return new Be(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",this.handleLinkClick),window.addEventListener("popstate",this.handlePopState),document.addEventListener("submit",this.handleFormSubmit)}handleLinkClick(e){const t=e.target.closest(this.options.linkSelector);if(!t)return;if(t.matches(this.options.excludeSelector))return;if(e.ctrlKey||e.metaKey||e.shiftKey)return;e.preventDefault();const n=t.href,i=t.title||t.textContent.trim();this.navigate(n,i)}handlePopState(e){const t=window.location.href;t!==this.currentUrl&&this.loadContent(t,!1)}handleFormSubmit(e){const t=e.target;t.hasAttribute("data-spa")&&"false"===t.getAttribute("data-spa")||t._moduleInstance}async navigate(e,t=""){var n;if(this.isLoading&&(d.warn("[SPARouter] Already loading, aborting previous request"),null==(n=this.abortController)||n.abort()),e!==this.currentUrl){d.info(`[SPARouter] Navigating to: ${e}`);try{await this.loadContent(e,!0,t)}catch(i){"AbortError"!==i.name&&(d.error("[SPARouter] Navigation failed:",i),window.location.href=e)}}else d.info(`[SPARouter] Already at ${e}, skipping navigation`)}async loadContent(e,t=!0,n=""){var i;if(e!==this.currentUrl||t){this.isLoading&&(null==(i=this.abortController)||i.abort()),this.isLoading=!0,this.abortController=new AbortController;try{this.showLoadingState();const i=await fetch(e,{headers:{"X-Requested-With":"XMLHttpRequest","X-SPA-Request":"true",Accept:"application/json, text/html"},signal:this.abortController.signal});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);const r=i.headers.get("content-type");let o,a;if(null==r?void 0:r.includes("application/json")){const e=await i.json();o=e.html,a=e.title||n,e.meta&&this.updateMetaTags(e.meta)}else{const e=await i.text();o=this.extractMainContent(e),a=this.extractTitle(e)||n}await this.updateContent(o,a),t&&this.updateHistoryState(e,a),this.currentUrl=e,d.info(`[SPARouter] Successfully loaded: ${e}`)}catch(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 i=['[role="main"]',".main-content","#main",".content"];for(const r of i){const e=t.querySelector(r);if(e)return d.warn(`[SPARouter] Using fallback selector: ${r}`),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 cubic-bezier(0.4, 0, 1, 1)`,this.container.style.opacity="0",setTimeout(()=>{e()},this.options.transitionDuration)})}async transitionIn(){return new Promise(e=>{this.container.style.opacity="0",setTimeout(()=>{this.container.style.transition=`opacity ${this.options.transitionDuration}ms cubic-bezier(0, 0, 0.2, 1)`,this.container.style.opacity="1",setTimeout(()=>{this.container.style.transition="",this.container.classList.remove("spa-transitioning-out"),e()},this.options.transitionDuration)},10)})}updateHistoryState(e,t){const n={url:e,title:t,timestamp:Date.now()};e!==window.location.href?history.pushState(n,t,e):history.replaceState(n,t,e)}reinitializeModules(){window.initAutoFormHandling&&window.initAutoFormHandling();this.container.querySelectorAll("[data-module]").forEach(e=>{const t=e.dataset.module;d.info(`[SPARouter] Re-initializing module "${t}" on new content`);const n=new CustomEvent("spa:reinit-module",{detail:{element:e,moduleName:t},bubbles:!0});e.dispatchEvent(n)})}createSkeletonTemplate(){return'\n <div class="spa-skeleton">\n <div class="spa-skeleton-header"></div>\n <div class="spa-skeleton-content">\n <div class="spa-skeleton-line"></div>\n <div class="spa-skeleton-line"></div>\n <div class="spa-skeleton-line short"></div>\n </div>\n </div>\n '}setupStyles(){if(document.getElementById("spa-router-styles"))return;const e=document.createElement("style");e.id="spa-router-styles",e.textContent="\n /* SPA Router Transitions */\n .spa-loading {\n cursor: progress;\n }\n \n .spa-transitioning-out {\n pointer-events: none;\n }\n \n /* Skeleton Loading Styles */\n .spa-skeleton {\n animation: spa-pulse 1.5s ease-in-out infinite alternate;\n }\n \n .spa-skeleton-header {\n height: 2rem;\n background: #e5e7eb;\n border-radius: 0.375rem;\n margin-bottom: 1rem;\n width: 60%;\n }\n \n .spa-skeleton-content {\n space-y: 0.75rem;\n }\n \n .spa-skeleton-line {\n height: 1rem;\n background: #e5e7eb;\n border-radius: 0.375rem;\n margin-bottom: 0.75rem;\n }\n \n .spa-skeleton-line.short {\n width: 75%;\n }\n \n @keyframes spa-pulse {\n 0% {\n opacity: 1;\n }\n 100% {\n opacity: 0.4;\n }\n }\n \n /* Dark mode support */\n @media (prefers-color-scheme: dark) {\n .spa-skeleton-header,\n .spa-skeleton-line {\n background: #374151;\n }\n }\n ",document.head.appendChild(e)}updateMetaTags(e){if(e.description){let t=document.querySelector('meta[name="description"]');t?t.content=e.description:(t=document.createElement("meta"),t.name="description",t.content=e.description,document.head.appendChild(t))}Object.entries(e).forEach(([e,t])=>{if("description"!==e&&t){let n=document.querySelector(`meta[name="${e}"]`);n?n.content=t:(n=document.createElement("meta"),n.name=e,n.content=t,document.head.appendChild(n))}})}triggerNavigationEvent(){const e=new CustomEvent("spa:navigated",{detail:{url:this.currentUrl,container:this.container,timestamp:Date.now()},bubbles:!0});document.dispatchEvent(e)}navigateTo(e,t){return this.navigate(e,t)}getCurrentUrl(){return this.currentUrl}isNavigating(){return this.isLoading}destroy(){var e;null==(e=this.abortController)||e.abort(),document.removeEventListener("click",this.handleLinkClick),window.removeEventListener("popstate",this.handlePopState),document.removeEventListener("submit",this.handleFormSubmit);const t=document.getElementById("spa-router-styles");t&&t.remove(),d.info("[SPARouter] Destroyed")}}const qe={enableTransitions:!0,transitionDuration:50},We={enableTransitions:!0,transitionDuration:100},je={enableTransitions:!1,transitionDuration:0};function He(){if(window.matchMedia("(prefers-reduced-motion: reduce)").matches)return je;const e=navigator.connection||navigator.mozConnection||navigator.webkitConnection;if(e){if("4g"===e.effectiveType)return qe;if("3g"===e.effectiveType)return We}/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);return We}const Ve={name:"spa-router",router:null,initialized:!1,init(e={}){if(this.initialized&&this.router)return d.warn("[SPARouterModule] SPA Router already initialized, returning existing instance"),this.router;d.info("[SPARouterModule] Initializing SPA Router");const t={...{containerSelector:"main",linkSelector:'a[href^="/"]',excludeSelector:'[data-spa="false"], [download], [target="_blank"], [href^="mailto:"], [href^="tel:"], [href^="#"]',enableSkeletonLoading:!0,...We,...He()},...e};return this.router=Be.create(t),this.initialized=!0,"undefined"!=typeof window&&(window.spaRouter=this.router),document.addEventListener("spa:reinit-module",this.handleModuleReinit.bind(this)),document.addEventListener("spa:navigated",this.handleNavigation.bind(this)),d.info("[SPARouterModule] SPA Router initialized successfully"),this.router},handleModuleReinit(e){const{element:t,moduleName:n}=e.detail;d.info(`[SPARouterModule] Re-initializing module: ${n}`,t);const i=new CustomEvent("module:reinit-needed",{detail:{element:t,moduleName:n},bubbles:!0});document.dispatchEvent(i)},handleNavigation(e){const{url:t,timestamp:n}=e.detail;d.info(`[SPARouterModule] Navigation completed to: ${t}`),"function"==typeof window.initAutoFormHandling&&setTimeout(()=>{window.initAutoFormHandling()},100),"function"==typeof window.gtag&&window.gtag("config","GA_TRACKING_ID",{page_path:new URL(t).pathname})},navigateTo(e,t){if(this.router)return this.router.navigateTo(e,t);d.warn("[SPARouterModule] Router not initialized")},getCurrentUrl(){var e;return(null==(e=this.router)?void 0:e.getCurrentUrl())||window.location.href},isNavigating(){var e;return(null==(e=this.router)?void 0:e.isNavigating())||!1},destroy(){this.router&&(this.router.destroy(),this.router=null),this.initialized=!1,"undefined"!=typeof window&&window.spaRouter&&delete window.spaRouter,document.removeEventListener("spa:reinit-module",this.handleModuleReinit),document.removeEventListener("spa:navigated",this.handleNavigation),d.info("[SPARouterModule] SPA Router destroyed")}},Ue=Ve.init.bind(Ve),Je=Object.freeze(Object.defineProperty({__proto__:null,SPARouter:Be,SPARouterModule:Ve,default:Ve,init:Ue},Symbol.toStringTag,{value:"Module"}));let Ge="sticky-fade",Ke=[],Qe=window.scrollY,Xe=new WeakMap,Ye={direction:!1,reset:!1};const Ze=Object.freeze(Object.defineProperty({__proto__:null,destroy:function(){l(Ge),Ke.forEach(e=>{e.style.opacity="",e.style.transform="",e.classList.remove("visible"),delete e.dataset.scrollDir}),Ke=[],Xe=new WeakMap},init:function(e={}){Ke=Array.from(document.querySelectorAll("[data-sticky-fade]")),0!==Ke.length&&(Ye.direction=e.direction??!1,Ye.reset=e.reset??!1,c(Ge,()=>{const e=window.scrollY,t=e>Qe?"down":e<Qe?"up":"none";Qe=e;const n=window.innerHeight;Ke.forEach(e=>{const i=e.getBoundingClientRect(),r=1-Math.min(Math.max(i.top/n,0),1);if(e.style.opacity=r.toFixed(3),e.style.transform=`translateY(${20*(1-r)}px)`,Ye.direction&&(e.dataset.scrollDir=t),Ye.reset){const t=r>=1,n=Xe.get(e)||!1;t&&!n?(e.classList.add("visible"),Xe.set(e,!0)):!t&&n&&(e.classList.remove("visible"),Xe.set(e,!1))}})},{autoStart:!0}))}},Symbol.toStringTag,{value:"Module"}));const et=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),i=e.offsetTop;c(`sticky-steps-${e.dataset.moduleId||Math.random()}`,function(){const r=window.scrollY,o=e.offsetHeight;n.forEach((a,s)=>{const c=i+s*(o/n.length),l=i+(s+1)*(o/n.length),d=r>=c&&r<l;a.classList.toggle(t.activeClass,d),d&&(e.dataset[t.datasetKey]=s)})},{autoStart:!0})})}},Symbol.toStringTag,{value:"Module"}));const tt=Object.freeze(Object.defineProperty({__proto__:null,init:function(){}},Symbol.toStringTag,{value:"Module"}));const nt=Object.freeze(Object.defineProperty({__proto__:null,WebPushManager:class{constructor(e={}){this.apiBase=e.apiBase||"/api/push",this.serviceWorkerUrl=e.serviceWorkerUrl||"/js/sw-push.js",this.vapidPublicKey=e.vapidPublicKey||null,this.onSubscriptionChange=e.onSubscriptionChange||null}async init(){if(!("serviceWorker"in navigator))throw new Error("Service Workers are not supported in this browser");if(!("PushManager"in window))throw new Error("Push API is not supported in this browser");await this.registerServiceWorker(),this.vapidPublicKey||await this.fetchVapidPublicKey();const e=await this.getSubscription();return this.onSubscriptionChange&&this.onSubscriptionChange(e),null!==e}async registerServiceWorker(){try{const e=await navigator.serviceWorker.register(this.serviceWorkerUrl);return console.log("[WebPush] Service Worker registered",e),e}catch(e){throw console.error("[WebPush] Service Worker registration failed",e),e}}async fetchVapidPublicKey(){try{const e=await fetch(`${this.apiBase}/vapid-key`),t=await e.json();if(!t.public_key)throw new Error("VAPID public key not available");this.vapidPublicKey=t.public_key,console.log("[WebPush] VAPID public key fetched")}catch(e){throw console.error("[WebPush] Failed to fetch VAPID public key",e),e}}async requestPermission(){const e=await Notification.requestPermission();if(console.log("[WebPush] Permission:",e),"granted"!==e)throw new Error("Notification permission denied");return e}async subscribe(){try{await this.requestPermission();const e=await navigator.serviceWorker.ready;let t=await e.pushManager.getSubscription();return t?console.log("[WebPush] Already subscribed",t):(t=await e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:this.urlBase64ToUint8Array(this.vapidPublicKey)}),console.log("[WebPush] Subscribed",t)),await this.sendSubscriptionToServer(t),this.onSubscriptionChange&&this.onSubscriptionChange(t),t}catch(e){throw console.error("[WebPush] Subscription failed",e),e}}async unsubscribe(){try{const e=await navigator.serviceWorker.ready,t=await e.pushManager.getSubscription();if(!t)return console.log("[WebPush] Not subscribed"),!1;const n=await t.unsubscribe();return n&&(console.log("[WebPush] Unsubscribed from browser"),await this.removeSubscriptionFromServer(t),this.onSubscriptionChange&&this.onSubscriptionChange(null)),n}catch(e){throw console.error("[WebPush] Unsubscribe failed",e),e}}async getSubscription(){try{const e=await navigator.serviceWorker.ready;return await e.pushManager.getSubscription()}catch(e){return console.error("[WebPush] Failed to get subscription",e),null}}async isSubscribed(){return null!==await this.getSubscription()}async sendTestNotification(e,t){try{const n=await this.getSubscription();if(!n)throw new Error("Not subscribed");const i=await fetch(`${this.apiBase}/test`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({endpoint:n.endpoint,title:e||"Test Notification",body:t||"This is a test notification!"})}),r=await i.json();return console.log("[WebPush] Test notification sent",r),r}catch(n){throw console.error("[WebPush] Test notification failed",n),n}}async sendSubscriptionToServer(e){try{const t=e.toJSON(),n=await fetch(`${this.apiBase}/subscribe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw new Error(`Server returned ${n.status}`);const i=await n.json();return console.log("[WebPush] Subscription sent to server",i),i}catch(t){throw console.error("[WebPush] Failed to send subscription to server",t),t}}async removeSubscriptionFromServer(e){try{const t=await fetch(`${this.apiBase}/unsubscribe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({endpoint:e.endpoint})});if(!t.ok)throw new Error(`Server returned ${t.status}`);const n=await t.json();return console.log("[WebPush] Subscription removed from server",n),n}catch(t){throw console.error("[WebPush] Failed to remove subscription from server",t),t}}urlBase64ToUint8Array(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),n=window.atob(t),i=new Uint8Array(n.length);for(let r=0;r<n.length;++r)i[r]=n.charCodeAt(r);return i}getPermissionStatus(){return Notification.permission}static isSupported(){return"serviceWorker"in navigator&&"PushManager"in window}}},Symbol.toStringTag,{value:"Module"})),it=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),rt={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 ot=new class{constructor(){this.crashedModules=new Set,this.recoveryAttempts=new Map,this.maxRecoveryAttempts=3,this.recoveryDelay=1e3}wrapModule(e,t){return e&&"object"==typeof e?new Proxy(e,{get:(e,n,i)=>{const r=e[n];if("function"!=typeof r)return r;const o=Object.getOwnPropertyDescriptor(e,n);return o&&!o.configurable?r:(...i)=>{try{const o=r.apply(e,i);return o&&"function"==typeof o.catch?o.catch(e=>(this.handleModuleError(e,t,n,i),this.getRecoveryValue(t,n))):o}catch(o){return this.handleModuleError(o,t,n,i),this.getRecoveryValue(t,n)}}},getOwnPropertyDescriptor:(e,t)=>{const n=Object.getOwnPropertyDescriptor(e,t);return n&&n.configurable,n},has:(e,t)=>t in e,ownKeys:e=>Object.getOwnPropertyNames(e)}):(d.warn(`[ErrorBoundary] Cannot wrap non-object module: ${t}`),e)}handleModuleError(e,t,n,i){const r=`${t}.${n}`;d.error(`[ErrorBoundary] Module ${t} crashed in ${n}():`,e),this.crashedModules.add(t);const o=this.recoveryAttempts.get(r)||0;this.recoveryAttempts.set(r,o+1),window.dispatchEvent(new CustomEvent("module-error",{detail:{moduleName:t,method:n,error:e.message,args:i,attempts:o+1}})),o<this.maxRecoveryAttempts?this.scheduleRecovery(t,n,i):(d.error(`[ErrorBoundary] Module ${t} exceeded recovery attempts. Marking as permanently failed.`),this.markModuleAsPermanentlyFailed(t))}scheduleRecovery(e,t,n){setTimeout(()=>{try{d.info(`[ErrorBoundary] Attempting recovery for ${e}.${t}()`)}catch(n){d.error(`[ErrorBoundary] Recovery failed for ${e}.${t}():`,n)}},this.recoveryDelay)}getRecoveryValue(e,t){switch(t){case"init":case"destroy":case"update":case"render":return Promise.resolve();case"getData":case"getConfig":return{};case"isEnabled":case"isActive":return!1;default:return}}markModuleAsPermanentlyFailed(e){window.dispatchEvent(new CustomEvent("module-permanent-failure",{detail:{moduleName:e}}))}getHealthStatus(){return{totalCrashedModules:this.crashedModules.size,crashedModules:Array.from(this.crashedModules),recoveryAttempts:Object.fromEntries(this.recoveryAttempts),timestamp:(new Date).toISOString()}}resetModule(e){this.crashedModules.delete(e);for(const[t]of this.recoveryAttempts)t.startsWith(`${e}.`)&&this.recoveryAttempts.delete(t);d.info(`[ErrorBoundary] Reset error tracking for module: ${e}`)}reset(){this.crashedModules.clear(),this.recoveryAttempts.clear(),d.info("[ErrorBoundary] Reset all error tracking")}};window.addEventListener("error",e=>{d.error("[Global] Unhandled error:",e.error||e.message)}),window.addEventListener("unhandledrejection",e=>{d.error("[Global] Unhandled promise rejection:",e.reason)});const at=new class{constructor(){this.state=new Map,this.subscribers=new Map,this.stateOwners=new Map,this.defaultValues=new Map,this.currentModule="unknown",this.subscriptionCounter=0}setContext(e){this.currentModule=e}register(e,t,n=this.currentModule){this.state.has(e)?d.warn(`[StateManager] State key '${e}' already registered by ${this.stateOwners.get(e)}`):(this.state.set(e,t),this.defaultValues.set(e,t),this.stateOwners.set(e,n),this.subscribers.set(e,[]),d.info(`[StateManager] Registered '${e}' (owner: ${n})`))}get(e){if(this.state.has(e))return this.state.get(e);d.warn(`[StateManager] Unknown state key: '${e}'`)}set(e,t,n=!1){if(!this.state.has(e))return d.warn(`[StateManager] Cannot set unknown state key: '${e}'`),!1;const i=this.stateOwners.get(e);if(!n&&i!==this.currentModule)return d.warn(`[StateManager] Module '${this.currentModule}' cannot modify '${e}' (owned by ${i})`),!1;const r=this.state.get(e);return r===t||(this.state.set(e,t),this.notifySubscribers(e,t,r),d.info(`[StateManager] Updated '${e}' by ${this.currentModule}`)),!0}subscribe(e,t,n=this.currentModule){if(!this.state.has(e))return d.warn(`[StateManager] Cannot subscribe to unknown state key: '${e}'`),null;const i=`${n}_${++this.subscriptionCounter}`,r={id:i,callback:t,subscriber:n};return this.subscribers.has(e)||this.subscribers.set(e,[]),this.subscribers.get(e).push(r),d.info(`[StateManager] Subscribed '${n}' to '${e}'`),i}unsubscribe(e){for(const[t,n]of this.subscribers.entries()){const i=n.findIndex(t=>t.id===e);if(-1!==i){const e=n[i];return n.splice(i,1),void d.info(`[StateManager] Unsubscribed '${e.subscriber}' from '${t}'`)}}d.warn(`[StateManager] Subscription ID not found: ${e}`)}notifySubscribers(e,t,n){(this.subscribers.get(e)||[]).forEach(i=>{try{i.callback(t,n,e)}catch(r){d.error(`[StateManager] Error in subscriber '${i.subscriber}' for '${e}':`,r)}})}reset(e){if(!this.state.has(e))return d.warn(`[StateManager] Cannot reset unknown state key: '${e}'`),!1;const t=this.defaultValues.get(e);return this.set(e,t,!0)}clearModuleSubscriptions(e){let t=0;for(const[n,i]of this.subscribers.entries()){const r=i.filter(t=>t.subscriber!==e);t+=i.length-r.length,this.subscribers.set(n,r)}t>0&&d.info(`[StateManager] Cleared ${t} subscriptions for module '${e}'`)}getSnapshot(){const e={state:Object.fromEntries(this.state),owners:Object.fromEntries(this.stateOwners),subscriptions:{}};for(const[t,n]of this.subscribers.entries())e.subscriptions[t]=n.map(e=>({id:e.id,subscriber:e.subscriber}));return e}resetAll(){this.state.clear(),this.subscribers.clear(),this.stateOwners.clear(),this.defaultValues.clear(),this.subscriptionCounter=0,d.info("[StateManager] Reset complete")}createScope(e){return{register:(t,n)=>(this.setContext(e),this.register(t,n,e)),get:e=>this.get(e),set:(t,n)=>(this.setContext(e),this.set(t,n)),subscribe:(t,n)=>(this.setContext(e),this.subscribe(t,n,e)),unsubscribe:e=>this.unsubscribe(e),reset:e=>this.reset(e),cleanup:()=>this.clearModuleSubscriptions(e)}}};"undefined"!=typeof window&&(window.stateManager=at,window.stateSnapshot=()=>at.getSnapshot());const st=new Map;function ct(){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=st.get(t);if(!n||!n.mod)return void d.warn(`[DOMInit] Module "${t}" not found or failed to initialize`);let i={};try{e.dataset.options&&(i=JSON.parse(e.dataset.options))}catch(r){d.warn(`[DOMInit] Invalid JSON in data-options for ${t}:`,r)}try{const r=n.mod;if("function"==typeof r.initElement){const n=r.initElement(e,i);d.info(`[DOMInit] Initialized ${t} on element:`,e),e._moduleInstance=n,e._moduleName=t}else if("function"==typeof r.init){const n=r.init(e,i);d.info(`[DOMInit] Initialized ${t} on element:`,e),e._moduleInstance=n,e._moduleName=t}else d.warn(`[DOMInit] Module ${t} has no init method for DOM elements`)}catch(r){d.error(`[DOMInit] Failed to initialize ${t} on element:`,r,e)}})}function lt(){const e=document.querySelectorAll('form:not([data-form-handling="false"]):not([data-auto-enhanced])');if(d.info(`[AutoForms] Found ${e.length} forms for auto-enhancement`),0===e.length)return;const t=st.get("form-handling");t&&t.mod?e.forEach(e=>{if(e.hasAttribute("data-module"))return void d.info("[AutoForms] Skipping form with explicit data-module:",e);if(e.hasAttribute("data-auto-enhanced"))return;let n={};try{e.dataset.formOptions&&(n=JSON.parse(e.dataset.formOptions))}catch(r){d.warn("[AutoForms] Invalid JSON in data-form-options:",r)}const i={validateOnSubmit:!0,validateOnBlur:!1,validateOnInput:!1,showInlineErrors:!0,ajaxSubmit:!0,enableStateTracking:!1,...n};try{const n=t.mod.initElement?t.mod.initElement(e,i):t.mod.init(e,i);d.info("[AutoForms] Auto-enhanced form:",{id:e.id||"unnamed",action:e.action||"none",method:e.method||"get",elements:e.elements.length}),e.setAttribute("data-auto-enhanced","true"),e._moduleInstance=n,e._moduleName="form-handling"}catch(r){d.error("[AutoForms] Failed to auto-enhance form:",r,e)}}):d.warn("[AutoForms] form-handling module not available, skipping auto-init")}async function dt(){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":M,"./canvas-animations/index.js":$,"./example-module/index.js":z,"./form-handling/index.js":j,"./image-manager/index.js":Q,"./inertia-scroll/index.js":oe,"./lightbox-trigger/index.js":he,"./livecomponent/index.js":Ee,"./noise/index.js":ke,"./parallax/index.js":xe,"./scroll-dependent/index.js":$e,"./scroll-loop/index.js":De,"./scroll-timeline/index.js":Oe,"./scrollfx/index.js":Fe,"./smooth-scroll/index.js":Ne,"./spa-router/index.js":Je,"./sse/index.js":we,"./sticky-fade/index.js":Ze,"./sticky-steps/index.js":et,"./ui/index.js":tt,"./webpush/index.js":nt,"./wheel-boost/index.js":it}),d.info("[Modules] Found modules:",Object.keys(t));const n=new Set(Array.from(document.querySelectorAll("[data-module]")).map(e=>e.dataset.module).filter(Boolean)),i=new Set(["spa-router","form-handling","api-manager","image-manager","livecomponent"]),r=new Set([...n,...i]),o=r.size===i.size&&0===n.size;d.info("[Modules] DOM modules found:",[...n]),d.info("[Modules] Core modules:",[...i]),d.info("[Modules] Used modules:",[...r]),d.info("[Modules] Fallback mode:",o),console.log("🔍 [Modules] Starting Phase 1 - Module Registration"),console.log("🔍 [Modules] All discovered modules:",Object.keys(t)),console.log("🔍 [Modules] Used modules:",[...r]),console.log("🔍 [Modules] Fallback mode:",o),Object.entries(t).forEach(([e,t])=>{const n=e.split("/").slice(-2,-1)[0];if(console.log(`🔍 [Module] Processing: ${n} from ${e}`),console.log(`🔍 [Module] Used modules has ${n}:`,r.has(n)),o||r.has(n))if(console.log(`✅ [Module] Registering ${n} with dependency manager`),"object"==typeof t.definition)d.info(`📋 [Module] Using definition for ${n}:`,t.definition),Ie.register(t.definition);else{const e={name:n,version:"1.0.0",dependencies:[],provides:[],priority:0};d.info(`📋 [Module] Using default definition for ${n}:`,e),Ie.register(e)}else console.log(`⏭️ [Module] Skipping unused module: ${n}`)});const a=Ie.calculateInitializationOrder();console.log("🔍 [Modules] Phase 2 - Initialization Order:",a);for(const c of a){if(console.log(`🔍 [Module] Phase 3 - Processing ${c} for initialization`),console.log(`🔍 [Module] Used modules has ${c}:`,r.has(c)),console.log("🔍 [Module] Fallback mode:",o),!o&&!r.has(c)){console.log(`⏭️ [Module] Skipped (not used in DOM): ${c}`);continue}const e=Object.keys(t).find(e=>e.split("/").slice(-2,-1)[0]===c);if(console.log(`🔍 [Module] Looking for module path for ${c}, found:`,e),!e){console.log(`⛔ [Module] No implementation found for: ${c}`);continue}const n=t[e],i=rt[c]||{};console.log(`🔍 [Module] Module ${c} object:`,n),console.log(`🔍 [Module] Config for ${c}:`,i);const a=Ie.checkDependencies(c);if(console.log(`🔍 [Module] Dependency check for ${c}:`,a),a.satisfied)if(console.log(`🔍 [Module] Checking init function for ${c}:`,typeof n.init,n.init),console.log(`🔍 [Module] Module object keys for ${c}:`,Object.keys(n)),console.log(`🔍 [Module] Full module object for ${c}:`,n),"function"==typeof n.init)try{d.info(`🚀 [Module] Starting initialization for ${c}`),Ie.markInitializing(c);const e=at.createScope(c),t=ot.wrapModule(n,c);await t.init(i,e),Ie.markInitialized(c),st.set(c,{mod:t,config:i,state:e,original:n}),d.info(`✅ [Module] Initialized: ${c}`)}catch(s){d.error(`❌ [Module] Failed to initialize ${c}:`,s),st.set(c,{mod:null,config:i,error:s,original:n})}else d.warn(`⛔ [Module] No init() in ${c} - typeof:`,typeof n.init),d.warn("⛔ [Module] Available properties:",Object.getOwnPropertyNames(n));else console.log(`❌ [Module] Cannot initialize ${c}: ${a.reason}`),st.set(c,{mod:null,config:i,error:new Error(a.reason),original:n})}o&&d.info("⚠️ [Module] No data-module usage detected, fallback to full init mode")}(),ct(),lt(),function(){const e=st.get("spa-router");if(e&&e.mod)try{e.mod.init({containerSelector:"main",enableTransitions:!0,transitionDuration:300}),window.initAutoFormHandling=lt,window.initDataModuleElements=ct,d.info("[Init] SPA Router initialized successfully")}catch(t){d.error("[Init] Failed to initialize SPA Router:",t)}else d.info("[Init] SPA Router module not available, skipping")}(),function(){const e=document.querySelectorAll("video[data-src]"),t=window.innerWidth,n=(navigator.connection||{}).effectiveType||"4g";e.forEach(e=>{const i=e.dataset.src;let r="480";r="2g"===n||"slow-2g"===n?"480":"3g"===n?t>=1200?"720":"480":t>=1200?"1080":t>=800?"720":"480";const o=`${i}-${r}.webm`,a=document.createElement("video");a.autoplay=!0,a.loop=!0,a.muted=!0,a.playsInline=!0,a.poster=e.getAttribute("poster")||"",a.setAttribute("width",e.getAttribute("width")||"100%");const s=document.createElement("source");s.src=o,s.type="video/webm",a.appendChild(s),e.replaceWith(a)})}()}"undefined"!=typeof window&&(window.moduleHealth=function(){const e={total:st.size,active:0,failed:0,modules:{},errorBoundary:ot.getHealthStatus()};for(const[t,{mod:n,error:i}]of st.entries())i?(e.failed++,e.modules[t]={status:"failed",error:i.message}):n?(e.active++,e.modules[t]={status:"active"}):e.modules[t]={status:"unknown"};return e},window.activeModules=st);const ht=class e{constructor(t={}){this.config={...e.DEFAULT_CONFIG,...t},this.intervalId=null,this.isActive=!1,this.retryCount=0,this.lastRefreshTime=null,this.isPageVisible=!document.hidden,this.log("CSRF Auto-Refresh initialized",this.config),this.setupEventListeners(),this.isPageVisible&&this.start()}setupEventListeners(){this.config.pauseWhenHidden&&document.addEventListener("visibilitychange",()=>{this.isPageVisible=!document.hidden,this.isPageVisible?(this.log("Page became visible, resuming CSRF refresh"),this.start()):(this.log("Page became hidden, pausing CSRF refresh"),this.stop())}),window.addEventListener("beforeunload",()=>{this.stop()})}start(){this.isActive?this.log("Auto-refresh already active"):(this.isActive=!0,this.intervalId=setInterval(()=>{this.refreshToken()},this.config.refreshInterval),this.log(`Auto-refresh started. Next refresh in ${this.config.refreshInterval/1e3/60} minutes`),this.config.enableVisualFeedback)}stop(){this.isActive&&(this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.isActive=!1,this.log("Auto-refresh stopped"))}async refreshToken(){if(this.isPageVisible||!this.config.pauseWhenHidden)try{this.log("Refreshing CSRF token...");const e=await fetch(`${this.config.apiEndpoint}?form_id=${encodeURIComponent(this.config.formId)}`,{method:"GET",headers:{Accept:"application/json","X-Requested-With":"XMLHttpRequest"}});if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);const t=await e.json();if(!t.success||!t.token)throw new Error(t.error||"Invalid response from server");this.updateTokenInForms(t.token),this.lastRefreshTime=new Date,this.retryCount=0,this.log("CSRF token refreshed successfully",{token:t.token.substring(0,8)+"...",formId:t.form_id,expiresIn:t.expires_in}),this.config.enableVisualFeedback}catch(e){this.handleRefreshError(e)}else this.log("Page not visible, skipping refresh")}updateTokenInForms(e){const t=document.querySelectorAll(this.config.tokenSelector);let n=0;return t.forEach(t=>{const i=t.closest("form");if(i){const r=i.querySelector(this.config.formIdSelector);r&&r.value===this.config.formId&&(t.value=e,n++)}}),this.log(`Updated ${n} token input(s)`),0===n&&console.warn("CsrfAutoRefresh: No token inputs found to update. Check your selectors."),n}handleRefreshError(e){this.retryCount++,console.error("CSRF token refresh failed:",e),this.retryCount<=this.config.maxRetries?(this.log(`Retrying in ${this.config.retryDelay/1e3}s (attempt ${this.retryCount}/${this.config.maxRetries})`),setTimeout(()=>{this.refreshToken()},this.config.retryDelay),this.config.enableVisualFeedback):(this.log("Max retries reached, stopping auto-refresh"),this.stop(),this.config.enableVisualFeedback)}showStatusMessage(e,t="info"){let n=document.getElementById("csrf-status-message");n||(n=document.createElement("div"),n.id="csrf-status-message",n.style.cssText="\n position: fixed;\n top: 20px;\n right: 20px;\n padding: 12px 16px;\n border-radius: 6px;\n font-size: 14px;\n z-index: 10000;\n max-width: 300px;\n box-shadow: 0 4px 12px rgba(0,0,0,0.1);\n transition: opacity 0.3s ease;\n ",document.body.appendChild(n)),n.textContent=e,n.className=`csrf-status-${t}`;const i={info:"background: #e3f2fd; color: #1976d2; border-left: 4px solid #2196f3;",success:"background: #e8f5e8; color: #2e7d32; border-left: 4px solid #4caf50;",warning:"background: #fff3e0; color: #f57c00; border-left: 4px solid #ff9800;",error:"background: #ffebee; color: #d32f2f; border-left: 4px solid #f44336;"};n.style.cssText+=i[t]||i.info,n.style.opacity="1","error"!==t&&setTimeout(()=>{n&&(n.style.opacity="0",setTimeout(()=>{n&&n.parentNode&&n.parentNode.removeChild(n)},300))},"success"===t?3e3:5e3)}log(e,t=null){if(this.config.enableConsoleLogging){const n=(new Date).toLocaleTimeString();t?console.log(`[${n}] CsrfAutoRefresh: ${e}`,t):console.log(`[${n}] CsrfAutoRefresh: ${e}`)}}getStatus(){var e;return{isActive:this.isActive,formId:this.config.formId,lastRefreshTime:this.lastRefreshTime,retryCount:this.retryCount,isPageVisible:this.isPageVisible,nextRefreshIn:this.isActive?Math.max(0,this.config.refreshInterval-(Date.now()-((null==(e=this.lastRefreshTime)?void 0:e.getTime())||Date.now()))):null}}async manualRefresh(){this.log("Manual refresh triggered"),await this.refreshToken()}static initializeAll(){const t=document.querySelectorAll('input[name="_token"]'),n=new Set;t.forEach(e=>{const t=e.closest("form");if(t){const e=t.querySelector('input[name="_form_id"]');e&&e.value&&n.add(e.value)}});const i=[];return n.forEach(t=>{const n=new e({formId:t});i.push(n)}),console.log(`CsrfAutoRefresh: Initialized for ${i.length} forms:`,Array.from(n)),i}};t(ht,"DEFAULT_CONFIG",{formId:"contact_form",refreshInterval:63e5,apiEndpoint:"/api/csrf/refresh",tokenSelector:'input[name="_token"]',formIdSelector:'input[name="_form_id"]',enableVisualFeedback:!1,enableConsoleLogging:!0,pauseWhenHidden:!0,maxRetries:3,retryDelay:5e3});let ut=ht;"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{ut.initializeAll()}):ut.initializeAll();const mt=class e{constructor(t={}){this.config={...e.DEFAULT_CONFIG,...t},this.form=null,this.storageKey=null,this.saveTimer=null,this.lastSaveTime=null,this.hasChanges=!1,this.isInitialized=!1,this.fieldValues=new Map,this.log("FormAutoSave initializing",this.config),this.initialize()}initialize(){this.form=document.querySelector(this.config.formSelector),this.form?(this.storageKey=this.config.storageKey||this.config.storagePrefix+this.generateFormId(),this.log("Form found, storage key:",this.storageKey),this.config.cleanupOnInit&&this.cleanupExpiredDrafts(),this.setupEventListeners(),this.storeInitialValues(),this.restoreDraft(),this.startAutoSave(),this.isInitialized=!0,this.log("FormAutoSave initialized successfully"),this.config.enableVisualFeedback&&this.showStatus("Auto-save enabled","info",3e3)):this.log("Form not found with selector:",this.config.formSelector)}generateFormId(){var e;return(this.form.id||this.form.getAttribute("data-form-id")||(null==(e=this.form.querySelector('input[name="_form_id"]'))?void 0:e.value)||"form_"+Date.now()).replace(/[^a-zA-Z0-9_-]/g,"_")}setupEventListeners(){this.form.addEventListener("input",e=>{this.onFieldChange(e)}),this.form.addEventListener("change",e=>{this.onFieldChange(e)}),this.form.addEventListener("submit",()=>{this.onFormSubmit()}),window.addEventListener("beforeunload",()=>{this.hasChanges&&this.saveDraft()}),document.addEventListener("visibilitychange",()=>{document.hidden&&this.hasChanges&&this.saveDraft()})}storeInitialValues(){const e=this.getFormFields();e.forEach(e=>{const t=this.getFieldKey(e),n=this.getFieldValue(e);this.fieldValues.set(t,n)}),this.log(`Stored initial values for ${e.length} fields`)}onFieldChange(e){const t=e.target;if(this.isFieldExcluded(t))return;const n=this.getFieldKey(t),i=this.getFieldValue(t);i!==this.fieldValues.get(n)&&(this.fieldValues.set(n,i),this.hasChanges=!0,this.log(`Field changed: ${n} = "${i}"`),this.isImmediateField(t)&&this.saveDraft())}onFormSubmit(){this.log("Form submitted, clearing draft"),this.clearDraft(),this.stopAutoSave(),this.config.enableVisualFeedback&&this.showStatus("Form submitted, draft cleared","success",2e3)}startAutoSave(){this.saveTimer||(this.saveTimer=setInterval(()=>{this.hasChanges&&this.saveDraft()},this.config.saveInterval),this.log(`Auto-save started, interval: ${this.config.saveInterval}ms`))}stopAutoSave(){this.saveTimer&&(clearInterval(this.saveTimer),this.saveTimer=null,this.log("Auto-save stopped"))}saveDraft(){if(this.form&&this.hasChanges)try{const e=this.extractFormData(),t={data:e,timestamp:Date.now(),formId:this.generateFormId(),url:window.location.href,version:"1.0"};localStorage.setItem(this.storageKey,JSON.stringify(t)),this.lastSaveTime=new Date,this.hasChanges=!1,this.log("Draft saved",{fields:Object.keys(e).length,size:JSON.stringify(t).length+" chars"}),this.config.enableVisualFeedback&&this.showStatus("Draft saved","success",1500)}catch(e){console.error("Failed to save form draft:",e),this.config.enableVisualFeedback&&this.showStatus("Failed to save draft","error",3e3)}}restoreDraft(){try{const e=localStorage.getItem(this.storageKey);if(!e)return void this.log("No draft found");const t=JSON.parse(e);if(this.isDraftExpired(t))return this.log("Draft expired, removing"),void localStorage.removeItem(this.storageKey);if(t.url&&t.url!==window.location.href)return void this.log("Draft from different URL, skipping restore");this.restoreFormData(t.data);const n=this.formatDuration(Date.now()-t.timestamp);this.log(`Draft restored (age: ${n})`,t.data),this.config.enableVisualFeedback&&this.showStatus(`Draft restored from ${n} ago`,"info",4e3)}catch(e){console.error("Failed to restore draft:",e),localStorage.removeItem(this.storageKey)}}extractFormData(){const e=this.getFormFields(),t={};return e.forEach(e=>{if(!this.isFieldExcluded(e)){const n=this.getFieldKey(e),i=this.getFieldValue(e);null!=i&&""!==i&&(t[n]=i)}}),t}restoreFormData(e){let t=0;Object.entries(e).forEach(([e,n])=>{const i=this.findFieldByKey(e);i&&!this.isFieldExcluded(i)&&(this.setFieldValue(i,n),this.fieldValues.set(e,n),t++)}),this.log(`Restored ${t} field values`);return this.getFormFields().forEach(e=>{this.isFieldExcluded(e)||e.dispatchEvent(new Event("change",{bubbles:!0}))}),t}getFormFields(){return Array.from(this.form.querySelectorAll('input:not([type="submit"]):not([type="button"]):not([type="reset"]), textarea, select'))}isFieldExcluded(e){return this.config.excludeFields.some(t=>e.matches(t))}isImmediateField(e){return this.config.immediateFields.some(t=>e.matches(t))}getFieldKey(e){return e.name||e.id||`field_${e.type}_${Date.now()}`}getFieldValue(e){switch(e.type){case"checkbox":return e.checked;case"radio":return e.checked?e.value:null;case"file":return null;default:return e.value}}setFieldValue(e,t){switch(e.type){case"checkbox":e.checked=Boolean(t);break;case"radio":e.checked=e.value===t;break;case"file":break;default:e.value=t}}findFieldByKey(e){return this.form.querySelector(`[name="${e}"], #${e}`)}isDraftExpired(e){return Date.now()-e.timestamp>this.config.retentionPeriod}clearDraft(){localStorage.removeItem(this.storageKey),this.hasChanges=!1,this.log("Draft cleared")}cleanupExpiredDrafts(){let e=0;const t=this.config.storagePrefix;for(let i=localStorage.length-1;i>=0;i--){const r=localStorage.key(i);if(r&&r.startsWith(t))try{const t=JSON.parse(localStorage.getItem(r));Date.now()-t.timestamp>this.config.maxDraftAge&&(localStorage.removeItem(r),e++)}catch(n){localStorage.removeItem(r),e++}}e>0&&this.log(`Cleaned up ${e} expired drafts`)}formatDuration(e){const t=Math.floor(e/1e3),n=Math.floor(t/60),i=Math.floor(n/60);return i>0?`${i}h ${n%60}m`:n>0?`${n}m`:`${t}s`}showStatus(e,t="info",n=3e3){let i=document.getElementById("form-autosave-status");i||(i=document.createElement("div"),i.id="form-autosave-status",i.style.cssText="\n position: fixed;\n bottom: 20px;\n right: 20px;\n padding: 8px 12px;\n border-radius: 4px;\n font-size: 12px;\n z-index: 9999;\n max-width: 250px;\n box-shadow: 0 2px 8px rgba(0,0,0,0.1);\n transition: opacity 0.3s ease;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n ",document.body.appendChild(i)),i.textContent=e,i.className=`autosave-status-${t}`;const r={info:"background: #e3f2fd; color: #1565c0; border: 1px solid #bbdefb;",success:"background: #e8f5e8; color: #2e7d32; border: 1px solid #c8e6c9;",error:"background: #ffebee; color: #c62828; border: 1px solid #ffcdd2;"};i.style.cssText+=r[t]||r.info,i.style.opacity="1",setTimeout(()=>{i&&(i.style.opacity="0",setTimeout(()=>{i&&i.parentNode&&i.parentNode.removeChild(i)},300))},n)}log(e,t=null){if(this.config.enableConsoleLogging){const n=`[${(new Date).toLocaleTimeString()}] FormAutoSave`;t?console.log(`${n}: ${e}`,t):console.log(`${n}: ${e}`)}}getStatus(){return{isInitialized:this.isInitialized,formId:this.generateFormId(),storageKey:this.storageKey,hasChanges:this.hasChanges,lastSaveTime:this.lastSaveTime,fieldCount:this.fieldValues.size,draftExists:!!localStorage.getItem(this.storageKey)}}forceSave(){this.hasChanges=!0,this.saveDraft()}destroy(){this.stopAutoSave(),this.isInitialized=!1,this.log("FormAutoSave destroyed")}static initializeAll(){const t=document.querySelectorAll('form[data-autosave], form:has(input[name="_token"])'),n=[];return t.forEach((t,i)=>{var r;const o=t.id||t.getAttribute("data-form-id")||(null==(r=t.querySelector('input[name="_form_id"]'))?void 0:r.value)||`form_${i}`,a=new e({formSelector:`#${t.id||"form_"+i}`,storageKey:`form_draft_${o}`});t.id||(t.id=`form_${i}`),n.push(a)}),console.log(`FormAutoSave: Initialized for ${n.length} forms`),n}};t(mt,"DEFAULT_CONFIG",{formSelector:"form[data-autosave]",saveInterval:3e4,retentionPeriod:864e5,storagePrefix:"form_draft_",enableVisualFeedback:!0,enableConsoleLogging:!0,excludeFields:['input[type="password"]','input[type="hidden"][name="_token"]','input[type="hidden"][name="_form_id"]','input[name*="password"]','input[name*="confirm"]','input[name*="honeypot"]','input[name="email_confirm"]','input[name="website_url"]','input[name="user_name"]','input[name="company_name"]'],immediateFields:["textarea",'input[type="email"]','input[type="text"]',"select"],maxDraftAge:6048e5,cleanupOnInit:!0});let pt=mt;document.addEventListener("DOMContentLoaded",async()=>{try{console.log("🚀 Starting app initialization..."),await dt(),console.log("✅ App initialized successfully!");const e=ut.initializeAll();console.log(`🔒 CSRF Auto-Refresh initialized for ${e.length} forms`);const t=pt.initializeAll();console.log(`💾 Form Auto-Save initialized for ${t.length} forms`),setTimeout(()=>{console.log("📊 Debug Info:"),console.log("- Forms found:",document.querySelectorAll("form").length),console.log("- Links found:",document.querySelectorAll('a[href^="/"]').length),console.log("- SPA Router:",window.spaRouter?"Active":"Missing"),console.log("- Enhanced forms:",document.querySelectorAll("form[data-auto-enhanced]").length),console.log("- CSRF protected forms:",document.querySelectorAll('input[name="_token"]').length)},500)}catch(e){console.error("❌ App initialization failed:",e),console.error("Stack trace:",e.stack)}});