@sc4rfurryx/proteusjs 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +331 -77
  3. package/dist/.tsbuildinfo +1 -1
  4. package/dist/adapters/react.d.ts +139 -0
  5. package/dist/adapters/react.esm.js +848 -0
  6. package/dist/adapters/react.esm.js.map +1 -0
  7. package/dist/adapters/svelte.d.ts +181 -0
  8. package/dist/adapters/svelte.esm.js +908 -0
  9. package/dist/adapters/svelte.esm.js.map +1 -0
  10. package/dist/adapters/vue.d.ts +205 -0
  11. package/dist/adapters/vue.esm.js +872 -0
  12. package/dist/adapters/vue.esm.js.map +1 -0
  13. package/dist/modules/a11y-audit.d.ts +39 -0
  14. package/dist/modules/a11y-audit.esm.js +509 -0
  15. package/dist/modules/a11y-audit.esm.js.map +1 -0
  16. package/dist/modules/a11y-primitives.d.ts +69 -0
  17. package/dist/modules/a11y-primitives.esm.js +445 -0
  18. package/dist/modules/a11y-primitives.esm.js.map +1 -0
  19. package/dist/modules/anchor.d.ts +29 -0
  20. package/dist/modules/anchor.esm.js +218 -0
  21. package/dist/modules/anchor.esm.js.map +1 -0
  22. package/dist/modules/container.d.ts +60 -0
  23. package/dist/modules/container.esm.js +194 -0
  24. package/dist/modules/container.esm.js.map +1 -0
  25. package/dist/modules/perf.d.ts +82 -0
  26. package/dist/modules/perf.esm.js +257 -0
  27. package/dist/modules/perf.esm.js.map +1 -0
  28. package/dist/modules/popover.d.ts +33 -0
  29. package/dist/modules/popover.esm.js +191 -0
  30. package/dist/modules/popover.esm.js.map +1 -0
  31. package/dist/modules/scroll.d.ts +43 -0
  32. package/dist/modules/scroll.esm.js +195 -0
  33. package/dist/modules/scroll.esm.js.map +1 -0
  34. package/dist/modules/transitions.d.ts +35 -0
  35. package/dist/modules/transitions.esm.js +120 -0
  36. package/dist/modules/transitions.esm.js.map +1 -0
  37. package/dist/modules/typography.d.ts +72 -0
  38. package/dist/modules/typography.esm.js +168 -0
  39. package/dist/modules/typography.esm.js.map +1 -0
  40. package/dist/proteus.cjs.js +2332 -12
  41. package/dist/proteus.cjs.js.map +1 -1
  42. package/dist/proteus.d.ts +561 -12
  43. package/dist/proteus.esm.js +2323 -12
  44. package/dist/proteus.esm.js.map +1 -1
  45. package/dist/proteus.esm.min.js +3 -3
  46. package/dist/proteus.esm.min.js.map +1 -1
  47. package/dist/proteus.js +2332 -12
  48. package/dist/proteus.js.map +1 -1
  49. package/dist/proteus.min.js +3 -3
  50. package/dist/proteus.min.js.map +1 -1
  51. package/package.json +61 -4
  52. package/src/adapters/react.ts +264 -0
  53. package/src/adapters/svelte.ts +321 -0
  54. package/src/adapters/vue.ts +268 -0
  55. package/src/index.ts +33 -6
  56. package/src/modules/a11y-audit/index.ts +608 -0
  57. package/src/modules/a11y-primitives/index.ts +554 -0
  58. package/src/modules/anchor/index.ts +257 -0
  59. package/src/modules/container/index.ts +230 -0
  60. package/src/modules/perf/index.ts +291 -0
  61. package/src/modules/popover/index.ts +238 -0
  62. package/src/modules/scroll/index.ts +251 -0
  63. package/src/modules/transitions/index.ts +145 -0
  64. package/src/modules/typography/index.ts +239 -0
  65. package/src/utils/version.ts +1 -1
@@ -1,8 +1,8 @@
1
1
  /*!
2
- * ProteusJS v1.0.0
2
+ * ProteusJS v1.1.0
3
3
  * Shape-shifting responsive design that adapts like the sea god himself
4
- * (c) 2024 sc4rfurry
4
+ * (c) 2025 sc4rfurry
5
5
  * Released under the MIT License
6
6
  */
7
- class e{constructor(e={}){this.levels={debug:0,info:1,warn:2,error:3,silent:4},this.config={level:"warn",prefix:"ProteusJS",enableInProduction:!1,enableTimestamps:!1,enableStackTrace:!1,...e}}static getInstance(t){return e.instance||(e.instance=new e(t)),e.instance}static configure(t){e.instance?e.instance.config={...e.instance.config,...t}:e.instance=new e(t)}shouldLog(e){return"production"!==process.env.NODE_ENV||this.config.enableInProduction?this.levels[e]>=this.levels[this.config.level]:"error"===e}formatMessage(e,t,...i){let s=t;if(this.config.prefix&&(s=`${this.config.prefix}: ${s}`),this.config.enableTimestamps){s=`[${(new Date).toISOString()}] ${s}`}return s=`[${e.toUpperCase().padEnd(5)}] ${s}`,[s,...i]}debug(e,...t){if(!this.shouldLog("debug"))return;const[i,...s]=this.formatMessage("debug",e,...t);this.config.enableStackTrace}info(e,...t){if(!this.shouldLog("info"))return;const[i,...s]=this.formatMessage("info",e,...t)}warn(e,...t){if(!this.shouldLog("warn"))return;const[i,...s]=this.formatMessage("warn",e,...t)}error(e,t,...i){if(!this.shouldLog("error"))return;const[s,...n]=this.formatMessage("error",e,...i);t instanceof Error&&this.config.enableStackTrace&&t.stack}group(e){this.shouldLog("info")}groupEnd(){this.shouldLog("info")}time(e){this.shouldLog("debug")}timeEnd(e){this.shouldLog("debug")}setLevel(e){this.config.level=e}getLevel(){return this.config.level}isEnabled(e){return this.shouldLog(e)}}const t=e.getInstance({level:"development"===process.env.NODE_ENV?"debug":"warn",prefix:"ProteusJS",enableInProduction:!1,enableTimestamps:"development"===process.env.NODE_ENV,enableStackTrace:!1});class i{constructor(){this.listeners=new Map,this.initialized=!1}init(){this.initialized||(this.initialized=!0)}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);const i=this.listeners.get(e);return i.add(t),()=>{i.delete(t),0===i.size&&this.listeners.delete(e)}}once(e,t){const i=this.on(e,e=>{t(e),i()});return i}off(e,t){if(!t)return void this.listeners.delete(e);const i=this.listeners.get(e);i&&(i.delete(t),0===i.size&&this.listeners.delete(e))}emit(e,t,i){const s=this.listeners.get(e);if(!s||0===s.size)return;const n={type:e,target:i||document.documentElement,detail:t,timestamp:Date.now()};s.forEach(e=>{try{e(n)}catch(e){}})}getEventTypes(){return Array.from(this.listeners.keys())}getListenerCount(e){const t=this.listeners.get(e);return t?t.size:0}hasListeners(e){return this.getListenerCount(e)>0}clear(){this.listeners.clear()}destroy(){this.clear(),this.initialized=!1}getDebugInfo(){const e={};return this.listeners.forEach((t,i)=>{e[i]=t.size}),{initialized:this.initialized,totalEventTypes:this.listeners.size,listeners:e}}}class s{constructor(e){this.plugins=new Map,this.installedPlugins=new Set,this.initialized=!1,this.proteus=e}init(){this.initialized||(this.initialized=!0)}register(e){if(this.plugins.has(e.name))return this;if(!this.validatePlugin(e))throw new Error(`ProteusJS: Invalid plugin "${e.name}"`);return this.plugins.set(e.name,e),this}install(e){const t=this.plugins.get(e);if(!t)throw new Error(`ProteusJS: Plugin "${e}" not found`);if(this.installedPlugins.has(e))return this;if(t.dependencies)for(const i of t.dependencies)if(!this.installedPlugins.has(i))throw new Error(`ProteusJS: Plugin "${e}" requires dependency "${i}" to be installed first`);try{t.install(this.proteus),this.installedPlugins.add(e),this.proteus.getEventSystem().emit("pluginInstalled",{plugin:e,version:t.version})}catch(e){throw e}return this}uninstall(e){const t=this.plugins.get(e);if(!t)return this;if(!this.installedPlugins.has(e))return this;const i=this.getDependents(e);if(i.length>0)throw new Error(`ProteusJS: Cannot uninstall plugin "${e}" because it's required by: ${i.join(", ")}`);try{t.uninstall&&t.uninstall(this.proteus),this.installedPlugins.delete(e),this.proteus.getEventSystem().emit("pluginUninstalled",{plugin:e,version:t.version})}catch(e){throw e}return this}isInstalled(e){return this.installedPlugins.has(e)}getRegisteredPlugins(){return Array.from(this.plugins.keys())}getInstalledPlugins(){return Array.from(this.installedPlugins)}getPluginInfo(e){return this.plugins.get(e)}installMany(e){const t=this.sortByDependencies(e);for(const e of t)this.install(e);return this}destroy(){const e=Array.from(this.installedPlugins),t=this.sortByDependencies(e).reverse();for(const e of t)try{this.uninstall(e)}catch(e){}this.plugins.clear(),this.installedPlugins.clear(),this.initialized=!1}validatePlugin(e){return!(!e.name||"string"!=typeof e.name)&&(!(!e.version||"string"!=typeof e.version)&&!(!e.install||"function"!=typeof e.install))}getDependents(e){const t=[];for(const[i,s]of this.plugins)this.installedPlugins.has(i)&&s.dependencies?.includes(e)&&t.push(i);return t}sortByDependencies(e){const t=[],i=new Set,s=new Set,n=r=>{if(s.has(r))throw new Error(`ProteusJS: Circular dependency detected involving plugin "${r}"`);if(i.has(r))return;s.add(r);const o=this.plugins.get(r);if(o?.dependencies)for(const t of o.dependencies)e.includes(t)&&n(t);s.delete(r),i.add(r),t.push(r)};for(const t of e)n(t);return t}}class n{constructor(){this.resources=new Map,this.elementResources=new Map,this.mutationObserver=null,this.cleanupInterval=null,this.isMonitoring=!1,this.setupDOMObserver(),this.startPeriodicCleanup()}register(e){const t={...e,timestamp:Date.now()};return this.resources.set(e.id,t),e.element&&(this.elementResources.has(e.element)||this.elementResources.set(e.element,new Set),this.elementResources.get(e.element).add(e.id)),e.id}unregister(e){const t=this.resources.get(e);if(!t)return!1;try{t.cleanup()}catch(e){}if(this.resources.delete(e),t.element){const i=this.elementResources.get(t.element);i&&(i.delete(e),0===i.size&&this.elementResources.delete(t.element))}return!0}cleanupElement(e){const t=this.elementResources.get(e);if(!t)return 0;let i=0;return t.forEach(e=>{this.unregister(e)&&i++}),i}cleanupByType(e){let t=0;const i=[];return this.resources.forEach((t,s)=>{t.type===e&&i.push(s)}),i.forEach(e=>{this.unregister(e)&&t++}),t}cleanupOldResources(e=3e5){let t=0;const i=Date.now(),s=[];return this.resources.forEach((t,n)=>{i-t.timestamp>e&&s.push(n)}),s.forEach(e=>{this.unregister(e)&&t++}),t}forceGarbageCollection(){if("gc"in window&&"function"==typeof window.gc)try{window.gc()}catch(e){}}getMemoryInfo(){const e={managedResources:this.resources.size,trackedElements:this.elementResources.size,resourcesByType:{}};if(this.resources.forEach(t=>{e.resourcesByType[t.type]=(e.resourcesByType[t.type]||0)+1}),"memory"in performance){const t=performance.memory;e.browserMemory={usedJSHeapSize:t.usedJSHeapSize,totalJSHeapSize:t.totalJSHeapSize,jsHeapSizeLimit:t.jsHeapSizeLimit}}return e}detectLeaks(){const e=[],t=Date.now();this.resources.size>1e3&&e.push(`High number of managed resources: ${this.resources.size}`);let i=0;this.resources.forEach(e=>{t-e.timestamp>6e5&&i++}),i>50&&e.push(`Many old resources detected: ${i}`);let s=0;return this.elementResources.forEach((e,t)=>{document.contains(t)||(s+=e.size)}),s>0&&e.push(`Orphaned element resources detected: ${s}`),e}destroy(){Array.from(this.resources.keys()).forEach(e=>this.unregister(e)),this.stopMonitoring(),this.resources.clear(),this.elementResources.clear()}startMonitoring(){this.isMonitoring||(this.isMonitoring=!0)}stopMonitoring(){this.isMonitoring&&(this.isMonitoring=!1,this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null))}setupDOMObserver(){"undefined"!=typeof MutationObserver&&(this.mutationObserver=new MutationObserver(e=>{e.forEach(e=>{"childList"===e.type&&e.removedNodes.forEach(e=>{e.nodeType===Node.ELEMENT_NODE&&this.handleElementRemoval(e)})})}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}))}handleElementRemoval(e){this.cleanupElement(e);e.querySelectorAll("*").forEach(e=>{this.cleanupElement(e)})}startPeriodicCleanup(){this.cleanupInterval=window.setInterval(()=>{let e=0;this.elementResources.forEach((t,i)=>{document.contains(i)||(e+=this.cleanupElement(i))});this.cleanupOldResources(6e5)},6e4)}}class r{constructor(e){this.observedElements=new Map,this.rafId=null,this.isObserving=!1,this.callback=e}observe(e,t){if(this.observedElements.has(e))return;const i=e.getBoundingClientRect();this.observedElements.set(e,{lastWidth:i.width,lastHeight:i.height}),this.isObserving||this.startObserving()}unobserve(e){this.observedElements.delete(e),0===this.observedElements.size&&this.stopObserving()}disconnect(){this.observedElements.clear(),this.stopObserving()}startObserving(){this.isObserving||(this.isObserving=!0,this.checkForChanges())}stopObserving(){this.isObserving&&(this.isObserving=!1,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null))}checkForChanges(){if(!this.isObserving)return;const e=[];if(this.observedElements.forEach((t,i)=>{if(!document.contains(i))return void this.observedElements.delete(i);const s=i.getBoundingClientRect(),n=s.width,r=s.height;if(n!==t.lastWidth||r!==t.lastHeight){this.observedElements.set(i,{lastWidth:n,lastHeight:r});const t={target:i,contentRect:this.createDOMRectReadOnly(s),contentBoxSize:[{inlineSize:n,blockSize:r}],borderBoxSize:[{inlineSize:n,blockSize:r}]};e.push(t)}}),e.length>0)try{this.callback(e)}catch(e){}this.isObserving&&(this.rafId=requestAnimationFrame(()=>this.checkForChanges()))}createDOMRectReadOnly(e){return{x:e.x,y:e.y,width:e.width,height:e.height,top:e.top,right:e.right,bottom:e.bottom,left:e.left,toJSON:()=>({x:e.x,y:e.y,width:e.width,height:e.height,top:e.top,right:e.right,bottom:e.bottom,left:e.left})}}}r.isSupported=()=>"undefined"!=typeof ResizeObserver;class o{constructor(e,t){this.observedElements=new Map,this.rafId=null,this.isObserving=!1,this.callback=e,this.root=t?.root instanceof Element?t.root:null,this.rootMargin=t?.rootMargin||"0px",this.thresholds=this.normalizeThresholds(t?.threshold),this.parsedRootMargin=this.parseRootMargin(this.rootMargin)}observe(e){this.observedElements.has(e)||(this.observedElements.set(e,{lastRatio:0,wasIntersecting:!1}),this.isObserving||this.startObserving())}unobserve(e){this.observedElements.delete(e),0===this.observedElements.size&&this.stopObserving()}disconnect(){this.observedElements.clear(),this.stopObserving()}startObserving(){this.isObserving||(this.isObserving=!0,this.checkForIntersections())}stopObserving(){this.isObserving&&(this.isObserving=!1,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null))}checkForIntersections(){if(!this.isObserving)return;const e=[],t=this.getRootBounds();if(this.observedElements.forEach((i,s)=>{if(!document.contains(s))return void this.observedElements.delete(s);const n=s.getBoundingClientRect(),r=this.calculateIntersection(n,t),o=this.calculateIntersectionRatio(n,r),a=o>0;if(this.shouldTriggerCallback(o,i.lastRatio,a,i.wasIntersecting)){this.observedElements.set(s,{lastRatio:o,wasIntersecting:a});const i={target:s,boundingClientRect:this.createDOMRectReadOnly(n),intersectionRect:this.createDOMRectReadOnly(r),rootBounds:t?this.createDOMRectReadOnly(t):null,intersectionRatio:o,isIntersecting:a,time:performance.now()};e.push(i)}}),e.length>0)try{this.callback(e)}catch(e){}this.isObserving&&(this.rafId=requestAnimationFrame(()=>this.checkForIntersections()))}getRootBounds(){const e=(this.root||document.documentElement).getBoundingClientRect();return new DOMRect(e.left-this.parsedRootMargin.left,e.top-this.parsedRootMargin.top,e.width+this.parsedRootMargin.left+this.parsedRootMargin.right,e.height+this.parsedRootMargin.top+this.parsedRootMargin.bottom)}calculateIntersection(e,t){const i=Math.max(e.left,t.left),s=Math.max(e.top,t.top),n=Math.min(e.right,t.right),r=Math.min(e.bottom,t.bottom),o=Math.max(0,n-i),a=Math.max(0,r-s);return new DOMRect(i,s,o,a)}calculateIntersectionRatio(e,t){const i=e.width*e.height;if(0===i)return 0;return t.width*t.height/i}shouldTriggerCallback(e,t,i,s){if(0===t&&!s)return!0;if(i!==s)return!0;for(const i of this.thresholds)if(t<i&&e>=i||t>i&&e<=i)return!0;return!1}normalizeThresholds(e){return void 0===e?[0]:"number"==typeof e?[e]:e.slice().sort((e,t)=>e-t)}parseRootMargin(e){const t=e.split(/\s+/).map(e=>{const t=parseFloat(e);return e.endsWith("%")?t/100*window.innerHeight:t});switch(t.length){case 1:return{top:t[0],right:t[0],bottom:t[0],left:t[0]};case 2:return{top:t[0],right:t[1],bottom:t[0],left:t[1]};case 3:return{top:t[0],right:t[1],bottom:t[2],left:t[1]};case 4:return{top:t[0],right:t[1],bottom:t[2],left:t[3]};default:return{top:0,right:0,bottom:0,left:0}}}createDOMRectReadOnly(e){return{x:e.x,y:e.y,width:e.width,height:e.height,top:e.top,right:e.right,bottom:e.bottom,left:e.left,toJSON:()=>({x:e.x,y:e.y,width:e.width,height:e.height,top:e.top,right:e.right,bottom:e.bottom,left:e.left})}}}o.isSupported=()=>"undefined"!=typeof IntersectionObserver;class a{constructor(){this.resizeObservers=new Map,this.intersectionObservers=new Map,this.resizeEntries=new Map,this.intersectionEntries=new Map,this.isPolyfillMode=!1,this.checkPolyfillNeeds()}observeResize(e,t,i){const s=this.getResizeObserverKey(i);let n=this.resizeObservers.get(s);n||(n=this.createResizeObserver(i),this.resizeObservers.set(s,n));const r={element:e,callback:t,...i&&{options:i}};return this.resizeEntries.set(e,r),n.observe(e,i),()=>this.unobserveResize(e)}observeIntersection(e,t,i){const s=this.getIntersectionObserverKey(i);let n=this.intersectionObservers.get(s);n||(n=this.createIntersectionObserver(t,i),this.intersectionObservers.set(s,n));const r={element:e,callback:t,...i&&{options:i}};return this.intersectionEntries.set(e,r),n.observe(e),()=>this.unobserveIntersection(e)}unobserveResize(e){const t=this.resizeEntries.get(e);if(!t)return;const i=this.getResizeObserverKey(t.options),s=this.resizeObservers.get(i);s&&s.unobserve(e),this.resizeEntries.delete(e),this.cleanupResizeObserver(i)}unobserveIntersection(e){const t=this.intersectionEntries.get(e);if(!t)return;const i=this.getIntersectionObserverKey(t.options),s=this.intersectionObservers.get(i);s&&s.unobserve(e),this.intersectionEntries.delete(e),this.cleanupIntersectionObserver(i)}getObservedElementCount(){return this.resizeEntries.size+this.intersectionEntries.size}getObserverCount(){return this.resizeObservers.size+this.intersectionObservers.size}isObservingResize(e){return this.resizeEntries.has(e)}isObservingIntersection(e){return this.intersectionEntries.has(e)}destroy(){this.resizeObservers.forEach(e=>e.disconnect()),this.resizeObservers.clear(),this.resizeEntries.clear(),this.intersectionObservers.forEach(e=>e.disconnect()),this.intersectionObservers.clear(),this.intersectionEntries.clear()}getDebugInfo(){return{isPolyfillMode:this.isPolyfillMode,resizeObservers:this.resizeObservers.size,intersectionObservers:this.intersectionObservers.size,resizeEntries:this.resizeEntries.size,intersectionEntries:this.intersectionEntries.size,totalObservedElements:this.getObservedElementCount(),totalObservers:this.getObserverCount()}}checkPolyfillNeeds(){"undefined"==typeof ResizeObserver&&(this.setupResizeObserverPolyfill(),this.isPolyfillMode=!0),"undefined"==typeof IntersectionObserver&&(this.setupIntersectionObserverPolyfill(),this.isPolyfillMode=!0)}setupResizeObserverPolyfill(){globalThis.ResizeObserver=r}setupIntersectionObserverPolyfill(){globalThis.IntersectionObserver=o}createResizeObserver(e){return new ResizeObserver(e=>{e.forEach(e=>{const t=this.resizeEntries.get(e.target);t&&t.callback(e)})})}createIntersectionObserver(e,t){return new IntersectionObserver(e=>{e.forEach(e=>{const t=this.intersectionEntries.get(e.target);t&&t.callback(e)})},t)}getResizeObserverKey(e){return e?`box:${e.box||"content-box"}`:"default"}getIntersectionObserverKey(e){if(!e)return"default";return`${e.root?"custom":"viewport"}:${e.rootMargin||"0px"}:${Array.isArray(e.threshold)?e.threshold.join(","):(e.threshold||0).toString()}`}cleanupResizeObserver(e){if(!Array.from(this.resizeEntries.values()).some(t=>this.getResizeObserverKey(t.options)===e)){const t=this.resizeObservers.get(e);t&&(t.disconnect(),this.resizeObservers.delete(e))}}cleanupIntersectionObserver(e){if(!Array.from(this.intersectionEntries.values()).some(t=>this.getIntersectionObserverKey(t.options)===e)){const t=this.intersectionObservers.get(e);t&&(t.disconnect(),this.intersectionObservers.delete(e))}}}function c(e,t,i={}){const{leading:s=!1,trailing:n=!0,maxWait:r}=i;let o,a,c,l,h=null,u=0;function d(t){const i=a,s=c;return a=void 0,c=void 0,u=t,l=e.apply(s,i),l}function m(e){const i=e-o;return void 0===o||i>=t||i<0||void 0!==r&&e-u>=r}function p(){const e=Date.now();if(m(e))return g(e);h=window.setTimeout(p,function(e){const i=e-u,s=t-(e-o);return void 0!==r?Math.min(s,r-i):s}(e))}function g(e){return h=null,n&&a?d(e):(a=void 0,c=void 0,l)}function f(...e){const i=Date.now(),n=m(i);if(a=e,c=this,o=i,n){if(null===h)return function(e){return u=e,h=window.setTimeout(p,t),s?d(e):l}(o);if(void 0!==r)return h=window.setTimeout(p,t),d(o)}return null===h&&(h=window.setTimeout(p,t)),l}return f.cancel=function(){null!==h&&(clearTimeout(h),h=null),u=0,a=void 0,o=void 0,c=void 0},f.flush=function(){return null===h?l:g(Date.now())},f}const l=new class{constructor(e){this.marks=new Map,this.measurements=[],this.warningThreshold=.8,this.budget={responseTime:60,frameRate:60,memoryUsage:100,...e}}mark(e,t){const i={name:e,startTime:performance.now(),...t&&{metadata:t}};this.marks.set(e,i),"function"==typeof performance.mark&&performance.mark(`proteus-${e}-start`)}measure(e){const t=this.marks.get(e);if(!t)return null;const i=performance.now(),s=i-t.startTime,n={...t,endTime:i,duration:s};return this.measurements.push(n),this.marks.delete(e),"function"==typeof performance.mark&&"function"==typeof performance.measure&&(performance.mark(`proteus-${e}-end`),performance.measure(`proteus-${e}`,`proteus-${e}-start`,`proteus-${e}-end`)),this.checkBudget(n),n}getMeasurements(){return[...this.measurements]}getMeasurementsByPattern(e){return this.measurements.filter(t=>e.test(t.name))}getAverageDuration(e){const t=this.measurements.filter(t=>t.name===e&&void 0!==t.duration);if(0===t.length)return 0;return t.reduce((e,t)=>e+(t.duration||0),0)/t.length}getStats(){const e={totalMeasurements:this.measurements.length,activeMeasurements:this.marks.size,budget:this.budget,violations:this.getBudgetViolations()},t={};return this.measurements.forEach(e=>{void 0!==e.duration&&(t[e.name]||(t[e.name]={count:0,avgDuration:0,maxDuration:0}),t[e.name].count++,t[e.name].maxDuration=Math.max(t[e.name].maxDuration,e.duration))}),Object.keys(t).forEach(e=>{t[e].avgDuration=this.getAverageDuration(e)}),e.byName=t,e}clear(){this.measurements.length=0,this.marks.clear()}updateBudget(e){this.budget={...this.budget,...e}}checkBudget(e){if(void 0===e.duration)return;this.budget.responseTime,this.warningThreshold;const t=this.budget.responseTime;e.duration>t||e.duration}getBudgetViolations(){return this.measurements.filter(e=>void 0!==e.duration&&e.duration>this.budget.responseTime)}};class h{constructor(e,t={},i,s){this.unobserveResize=null,this.isActive=!1,this.liveRegion=null,this.element=e,this.observerManager=i,this.memoryManager=s,this.options={breakpoints:{},containerType:"auto",debounceMs:16,callbacks:{...t.callbacks?.resize&&{resize:t.callbacks.resize},...t.callbacks?.breakpointChange&&{breakpointChange:t.callbacks.breakpointChange}},cssClasses:!0,units:!0,announceChanges:!1,...t},this.state=this.createInitialState(),this.debouncedUpdate=c(this.updateState.bind(this),this.options.debounceMs,{leading:!0,trailing:!0}),"auto"===this.options.containerType&&(this.options.containerType=this.detectContainerType()),this.setupContainerQuery()}activate(){this.isActive||(l.mark("container-activate"),this.unobserveResize=this.observerManager.observeResize(this.element,this.handleResize.bind(this)),this.memoryManager.register({id:`container-${this.getElementId()}`,type:"observer",element:this.element,cleanup:()=>this.deactivate()}),this.isActive=!0,this.options.announceChanges&&this.setupAnnouncements(),this.updateState(),l.measure("container-activate"))}deactivate(){this.isActive&&(this.unobserveResize&&(this.unobserveResize(),this.unobserveResize=null),this.debouncedUpdate.cancel(),this.options.cssClasses&&this.removeCSSClasses(),this.liveRegion&&this.liveRegion.parentNode&&(this.liveRegion.parentNode.removeChild(this.liveRegion),this.liveRegion=null),this.isActive=!1)}getState(){return{...this.state}}getElement(){return this.element}updateBreakpoints(e){this.options.breakpoints={...e},this.updateState()}isBreakpointActive(e){return this.state.activeBreakpoints.includes(e)}getDimensions(){const{width:e,height:t}=this.state;return{px:{width:e,height:t},cw:{width:100,height:t/e*100},ch:{width:e/t*100,height:100},cmin:Math.min(e,t),cmax:Math.max(e,t)}}handleResize(e){this.debouncedUpdate()}updateState(){l.mark("container-update");const e=this.element.getBoundingClientRect(),t=e.width,i=e.height,s=i>0?t/i:0;if(Math.abs(t-this.state.width)<.5&&Math.abs(i-this.state.height)<.5)return void l.measure("container-update");const n=[...this.state.activeBreakpoints];this.state={width:t,height:i,aspectRatio:s,containerType:this.options.containerType,activeBreakpoints:this.calculateActiveBreakpoints(t,i),lastUpdate:Date.now()},this.options.cssClasses&&this.updateCSSClasses(n),this.options.units&&this.updateContainerUnits(),this.options.callbacks.resize&&this.options.callbacks.resize(this.state),this.options.callbacks.breakpointChange&&this.notifyBreakpointChanges(n,this.state.activeBreakpoints),this.options.announceChanges&&this.announce(`Layout changed to ${this.state.activeBreakpoints.join(", ")||"default"} view`),l.measure("container-update")}createInitialState(){const e=this.element.getBoundingClientRect();return{width:e.width,height:e.height,aspectRatio:e.height>0?e.width/e.height:0,containerType:"inline-size",activeBreakpoints:[],lastUpdate:Date.now()}}detectContainerType(){try{const e=getComputedStyle(this.element).contain;return e&&"string"==typeof e?e.includes("inline-size")?"inline-size":e.includes("size")?"size":e.includes("block-size")?"block-size":"inline-size":"inline-size"}catch(e){return t.warn("Failed to detect container type:",e),"inline-size"}}setupContainerQuery(){if("undefined"!=typeof CSS&&CSS.supports&&CSS.supports("container-type","inline-size")){const e=this.element;e.style.containerType="auto"===this.options.containerType?"inline-size":this.options.containerType;const t=this.generateContainerName();e.style.containerName=t}}calculateActiveBreakpoints(e,t){const i=[];return Object.entries(this.options.breakpoints).forEach(([s,n])=>{const r=this.parseBreakpointValue(n);this.getRelevantDimension(e,t)>=r&&i.push(s)}),i.sort((e,t)=>this.parseBreakpointValue(this.options.breakpoints[e])-this.parseBreakpointValue(this.options.breakpoints[t]))}getRelevantDimension(e,t){switch(this.options.containerType){case"inline-size":default:return e;case"block-size":return t;case"size":return Math.min(e,t)}}parseBreakpointValue(e){return"number"==typeof e?e:e.endsWith("px")?parseFloat(e):e.endsWith("em")||e.endsWith("rem")?16*parseFloat(e):parseFloat(e)||0}updateCSSClasses(e){const t=this.element,i=this.getClassPrefix();e.forEach(e=>{t.classList.remove(`${i}--${e}`)}),this.state.activeBreakpoints.forEach(e=>{t.classList.add(`${i}--${e}`)})}removeCSSClasses(){const e=this.element,t=this.getClassPrefix();this.state.activeBreakpoints.forEach(i=>{e.classList.remove(`${t}--${i}`)})}updateContainerUnits(){const e=this.element,{width:t,height:i}=this.state;e.style.setProperty("--cw",t/100+"px"),e.style.setProperty("--ch",i/100+"px"),e.style.setProperty("--cmin",Math.min(t,i)/100+"px"),e.style.setProperty("--cmax",Math.max(t,i)/100+"px"),e.style.setProperty("--cqi",t/100+"px"),e.style.setProperty("--cqb",i/100+"px")}notifyBreakpointChanges(e,t){const i=this.options.callbacks.breakpointChange;t.forEach(t=>{e.includes(t)||i(t,!0)}),e.forEach(e=>{t.includes(e)||i(e,!1)})}generateContainerName(){return`proteus-${this.getElementId()}`}getClassPrefix(){return this.element.className.split(" ")[0]||"proteus-container"}getElementId(){if(this.element.id)return this.element.id;const e=Array.from(document.querySelectorAll(this.element.tagName)).indexOf(this.element);return`${this.element.tagName.toLowerCase()}-${e}`}setupAnnouncements(){}announce(e){this.liveRegion||(this.liveRegion=document.createElement("div"),this.liveRegion.setAttribute("aria-live","polite"),this.liveRegion.setAttribute("aria-atomic","true"),this.liveRegion.style.cssText="position: absolute; left: -10000px; width: 1px; height: 1px; overflow: hidden;",document.body.appendChild(this.liveRegion)),this.liveRegion.textContent=e;try{const e=new Event("DOMSubtreeModified",{bubbles:!0});this.liveRegion.dispatchEvent(e)}catch(e){}try{const e=new Event("DOMNodeInserted",{bubbles:!0});this.liveRegion.dispatchEvent(e)}catch(e){}}announceBreakpointChanges(e,t){const i=t.filter(t=>!e.includes(t)),s=e.filter(e=>!t.includes(e));if(i.length>0){const e=`Layout changed to ${i.join(", ")} view`;return this.announce(e),!0}if(s.length>0&&t.length>0){const e=`Layout changed to ${t.join(", ")} view`;return this.announce(e),!0}return!1}}class u{constructor(e,t,i,s){this.containers=new Map,this.autoDetectionEnabled=!1,this.observerManager=t,this.memoryManager=i,this.eventSystem=s,this.config={autoDetect:!0,breakpoints:{sm:"300px",md:"500px",lg:"800px",xl:"1200px"},units:!0,isolation:!0,polyfill:!0,...e},this.config.autoDetect&&this.enableAutoDetection()}container(e,t={}){l.mark("container-create");const i=this.normalizeSelector(e),s=[];return i.forEach(e=>{let i=this.containers.get(e);if(i)t.breakpoints&&i.updateBreakpoints(t.breakpoints);else{const s={breakpoints:this.config.breakpoints,...t};i=new h(e,s,this.observerManager,this.memoryManager),this.containers.set(e,i),i.activate(),this.eventSystem.emit("containerCreated",{element:e,container:i,options:s})}s.push(i)}),l.measure("container-create"),1===i.length?s[0]:s}removeContainer(e){const t=this.normalizeSelector(e);let i=!1;return t.forEach(e=>{const t=this.containers.get(e);t&&(t.deactivate(),this.containers.delete(e),i=!0,this.eventSystem.emit("containerRemoved",{element:e,container:t}))}),i}getContainer(e){return this.containers.get(e)}getAllContainers(){return Array.from(this.containers.values())}getContainersByBreakpoint(e){return this.getAllContainers().filter(t=>t.isBreakpointActive(e))}updateGlobalBreakpoints(e){const t=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,String(t)]));this.config.breakpoints={...this.config.breakpoints,...t},this.containers.forEach(e=>{e.updateBreakpoints(this.config.breakpoints)}),this.eventSystem.emit("breakpointsUpdated",{breakpoints:this.config.breakpoints})}enableAutoDetection(){this.autoDetectionEnabled||(this.autoDetectionEnabled=!0,this.scanForContainers(),this.setupMutationObserver())}disableAutoDetection(){this.autoDetectionEnabled=!1}scanForContainers(){if(!this.autoDetectionEnabled)return;l.mark("container-scan");this.findContainerCandidates().forEach(e=>{if(!this.containers.has(e)){const t=this.extractOptionsFromElement(e);this.container(e,t)}}),l.measure("container-scan")}getStats(){const e=this.getAllContainers(),t={totalContainers:e.length,activeContainers:e.filter(e=>e.getState().lastUpdate>0).length,autoDetectionEnabled:this.autoDetectionEnabled,breakpoints:Object.keys(this.config.breakpoints),containersByBreakpoint:{}};return Object.keys(this.config.breakpoints).forEach(e=>{t.containersByBreakpoint[e]=this.getContainersByBreakpoint(e).length}),t}destroy(){this.containers.forEach(e=>{e.deactivate()}),this.containers.clear(),this.autoDetectionEnabled=!1}normalizeSelector(e){return"string"==typeof e?Array.from(document.querySelectorAll(e)):e instanceof Element?[e]:Array.isArray(e)?e:[]}findContainerCandidates(){const e=[];if(e.push(...Array.from(document.querySelectorAll("[data-container]"))),e.push(...Array.from(document.querySelectorAll(".container, .card, .widget, .component"))),"undefined"!=typeof CSS&&CSS.supports&&CSS.supports("container-type","inline-size")){document.querySelectorAll("*").forEach(t=>{const i=getComputedStyle(t);i.containerType&&"normal"!==i.containerType&&e.push(t)})}return Array.from(new Set(e))}extractOptionsFromElement(e){const t={},i=e.getAttribute("data-container");if(i)try{const e=JSON.parse(i);Object.assign(t,e)}catch(e){}const s=e.getAttribute("data-breakpoints");if(s)try{t.breakpoints=JSON.parse(s)}catch(e){}const n=e.getAttribute("data-container-type");return n&&(t.containerType=n),t}setupMutationObserver(){if("undefined"==typeof MutationObserver)return;const e=new MutationObserver(e=>{let t=!1;e.forEach(e=>{"childList"===e.type?e.addedNodes.forEach(e=>{e.nodeType===Node.ELEMENT_NODE&&(t=!0)}):"attributes"===e.type&&(e.attributeName?.startsWith("data-container")||"class"===e.attributeName)&&(t=!0)}),t&&setTimeout(()=>this.scanForContainers(),100)});e.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-container","data-breakpoints","data-container-type","class"]}),this.memoryManager.register({id:"container-mutation-observer",type:"observer",cleanup:()=>e.disconnect()})}}class d{constructor(){this.supportsClamp=this.checkClampSupport(),this.supportsContainerUnits=this.checkContainerUnitSupport()}createScaling(e){const{minSize:t,maxSize:i,minContainer:s,maxContainer:n,unit:r,containerUnit:o,curve:a}=e,c=n-s;if(c<=0)return{clampValue:`${t}${r}`,fallbackValue:`${t}${r}`,currentSize:t,progress:0,isNative:!1};const l=(i-t)/c,h=t-l*s;let u,d;if(this.supportsClamp&&(this.supportsContainerUnits||"px"===o)){u=`clamp(${t}${r}, ${this.createPreferredValue(h,l,r,o,a,e)}, ${i}${r})`,d=`${t}${r}`}else u=`var(--proteus-font-size, ${t}${r})`,d=`${t}${r}`;return{clampValue:u,fallbackValue:d,currentSize:t,progress:0,isNative:this.supportsClamp}}calculateSize(e,t){const{minSize:i,maxSize:s,minContainer:n,maxContainer:r,curve:o,customCurve:a}=t,c=(Math.max(n,Math.min(r,e))-n)/(r-n),l=i+(s-i)*this.applyCurve(c,o,a);return Math.max(i,Math.min(s,l))}applyScaling(e,t,i){const s=e,n=this.createScaling(i);if(n.isNative)s.style.fontSize=n.clampValue;else{const e=this.calculateSize(t,i);s.style.setProperty("--proteus-font-size",`${e}${i.unit}`),s.style.fontSize=n.clampValue}}createMultiBreakpointScaling(e,t="rem",i="cw"){if(e.length<2)throw new Error("At least 2 breakpoints required for multi-breakpoint scaling");const s=[...e].sort((e,t)=>e.container-t.container),n=[];for(let e=0;e<s.length-1;e++){const r=s[e],o=s[e+1],a={minSize:r.size,maxSize:o.size,minContainer:r.container,maxContainer:o.container,unit:t,containerUnit:i,curve:"linear"},c=this.createScaling(a);n.push(c.clampValue)}return 1===n.length?n[0]:`max(${n.join(", ")})`}generateOptimalConfig(e,t,i,s={}){const{unit:n="rem",accessibility:r=!0,readability:o=!0}=s;let{small:a,large:c}=t;const{small:l,large:h}=i;if(r){const e="px"===n?16:1;a=Math.max(a,e);const t="px"===n?72:4.5;c=Math.min(c,t)}if(o){const e=2.5;c/a>e&&(c=a*e)}return{minSize:a,maxSize:c,minContainer:l,maxContainer:h,unit:n,containerUnit:"cw",curve:"ease-out"}}validateConfig(e){const t=[];e.minSize>=e.maxSize&&t.push("minSize must be less than maxSize"),e.minContainer>=e.maxContainer&&t.push("minContainer must be less than maxContainer"),e.minSize<=0&&t.push("minSize must be positive"),e.minContainer<=0&&t.push("minContainer must be positive");return e.maxSize/e.minSize>5&&t.push("Size ratio is very large (>5x), consider reducing for better readability"),{valid:0===t.length,errors:t}}createPreferredValue(e,t,i,s,n,r){if(!isFinite(e)||!isFinite(t))return`1${i}`;if("linear"===n){const n=t*("px"===s?1:100);return`${Number(e.toFixed(3))}${i} + ${Number(n.toFixed(3))}${s}`}return`${Number(e.toFixed(3))}${i} + ${Number((100*t).toFixed(3))}${s}`}applyCurve(e,t,i){switch(t){case"linear":default:return e;case"ease-in":return e*e;case"ease-out":return 1-Math.pow(1-e,2);case"ease-in-out":return e<.5?2*e*e:1-Math.pow(-2*e+2,2)/2;case"custom":return i?i(e):e}}checkClampSupport(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("font-size","clamp(1rem, 2vw, 2rem)")}checkContainerUnitSupport(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("font-size","1cw")}}class m{generateScale(e){if(void 0!==e.steps)return this.generateSimpleScale({ratio:e.ratio,baseSize:e.baseSize,steps:e.steps});const t={...e,baseUnit:e.baseUnit||"px",levels:e.levels||5,direction:e.direction||"up",roundToGrid:e.roundToGrid||!1,gridSize:e.gridSize||4},i=this.parseRatio(t.ratio),s=this.calculateLevels(t,i),n=this.generateCustomProperties(s),r=this.generateCSSClasses(s);return{config:{...t,ratio:i},levels:s,cssCustomProperties:n,cssClasses:r}}generateSimpleScale(e){const t=this.parseRatio(e.ratio),i=[];for(let s=0;s<e.steps;s++){const n=e.baseSize*Math.pow(t,s);i.push(n)}return i}generateResponsiveScale(e,t,i={min:.8,max:1.2}){const s={...e,baseSize:e.baseSize*i.min},n={...e,baseSize:e.baseSize*i.max},r=this.generateScale(s),o=this.generateScale(n);return{small:r,large:o,fluidCSS:this.generateFluidCSS(r,o,t)}}getOptimalRatio(e){switch(e){case"body":default:return m.NAMED_RATIOS["minor-third"];case"display":return m.NAMED_RATIOS["perfect-fourth"];case"interface":return m.NAMED_RATIOS["major-second"];case"code":return m.NAMED_RATIOS["minor-second"]}}calculateOptimalBaseSize(e,t=66,i=.5){const s=e/(t*i);return Math.max(.875,Math.min(1.5,s/16))}validateScale(e){const t=[],i=this.parseRatio(e.ratio);i<=1&&t.push("Ratio must be greater than 1"),e.baseSize<=0&&t.push("Base size must be positive");const s=e.levels||e.steps||5;return s<1&&t.push("Must have at least 1 level"),s>20&&t.push("Too many levels (>20), consider reducing for better usability"),i>3&&t.push("Very large ratio (>3), may create poor readability"),{valid:0===t.length,errors:t}}getScaleStats(e){const t=e.levels.map(e=>e.size),i=e.levels.slice(1).map((t,i)=>t.size/e.levels[i].size);return{levelCount:e.levels.length,baseSize:e.config.baseSize,ratio:e.config.ratio,smallestSize:Math.min(...t),largestSize:Math.max(...t),sizeRange:Math.max(...t)/Math.min(...t),averageRatio:i.length>0?i.reduce((e,t)=>e+t,0)/i.length:0,unit:e.config.baseUnit}}parseRatio(e){if("number"==typeof e)return e;const t=m.NAMED_RATIOS[e];if(t)return t;const i=parseFloat(e);return isNaN(i)?m.NAMED_RATIOS["minor-third"]:i}calculateLevels(e,t){const i=[],{baseSize:s,baseUnit:n,direction:r,roundToGrid:o,gridSize:a=4}=e;if(i.push({level:0,size:s,ratio:1,cssValue:`${s}${n}`,name:m.LEVEL_NAMES[0]}),"up"===r||"both"===r){const r=e.levels||e.steps||5;for(let e=1;e<=r;e++){const r=s*Math.pow(t,e),c=o?this.roundToGrid(r,a):r;i.push({level:e,size:c,ratio:Math.pow(t,e),cssValue:`${c}${n}`,name:m.LEVEL_NAMES[e.toString()]})}}if("down"===r||"both"===r){const c=e.levels||e.steps||5,l="both"===r?Math.floor(c/2):c;for(let e=1;e<=l;e++){const r=s/Math.pow(t,e),c=o?this.roundToGrid(r,a):r;i.unshift({level:-e,size:c,ratio:1/Math.pow(t,e),cssValue:`${c}${n}`,name:m.LEVEL_NAMES[(-e).toString()]})}}return i.sort((e,t)=>e.level-t.level)}roundToGrid(e,t){return Math.round(e/t)*t}generateCustomProperties(e){const t={};return e.forEach(e=>{const i=e.name||`level-${e.level}`;t[`--font-size-${i}`]=e.cssValue}),t}generateCSSClasses(e){const t={};return e.forEach(e=>{const i=e.name||`level-${e.level}`;t[`.text-${i}`]=`font-size: var(--font-size-${i}, ${e.cssValue});`}),t}generateFluidCSS(e,t,i){const s={};return e.levels.forEach((n,r)=>{const o=t.levels[r];if(!o)return;const a=n.name||`level-${n.level}`,c=n.size,l=o.size,h=i.min,u=(l-c)/(i.max-h),d=c-u*h,m=e.config.baseUnit,p=`clamp(${c}${m}, ${d}${m} + ${100*u}cw, ${l}${m})`;s[`--font-size-${a}`]=p}),s}applyToElements(e,t){const i=[...this.generateScale(t).levels].sort((e,i)=>t.reverse?i.size-e.size:e.size-i.size);e.forEach((e,t)=>{const s=i[t%i.length];if(s){e.style.fontSize=s.cssValue,e.setAttribute("data-proteus-scale-level",s.level.toString()),e.setAttribute("data-proteus-font-size",s.cssValue),s.name&&e.setAttribute("data-proteus-scale-name",s.name)}})}destroy(){}}m.NAMED_RATIOS={"minor-second":1.067,"major-second":1.125,"minor-third":1.2,"major-third":1.25,"perfect-fourth":1.333,"augmented-fourth":1.414,"perfect-fifth":1.5,"golden-ratio":1.618,"major-sixth":1.667,"minor-seventh":1.778,"major-seventh":1.875,octave:2,"major-tenth":2.5,"major-eleventh":2.667,"major-twelfth":3,"double-octave":4},m.LEVEL_NAMES={"-3":"xs","-2":"sm","-1":"base-sm",0:"base",1:"lg",2:"xl",3:"2xl",4:"3xl",5:"4xl",6:"5xl",7:"6xl",8:"7xl",9:"8xl",10:"9xl"};class p{constructor(){this.canvas=document.createElement("canvas"),this.context=this.canvas.getContext("2d")}fitText(e,t,i,s,n){const r=getComputedStyle(e);switch(n.mode){case"single-line":return this.fitSingleLine(t,i,n,r);case"multi-line":return this.fitMultiLine(t,i,s,n,r);case"overflow-aware":return this.fitOverflowAware(t,i,s,n,r);default:throw new Error(`Unknown fitting mode: ${n.mode}`)}}applyFitting(e,t,i){const s=e;s.style.fontSize=`${t.fontSize}${i.unit}`,s.style.lineHeight=t.lineHeight.toString(),"overflow-aware"===i.mode&&t.overflow&&(s.style.overflow=i.overflow||"hidden","ellipsis"===i.overflow&&(s.style.textOverflow="ellipsis",s.style.whiteSpace="nowrap"))}measureText(e,t,i,s="normal"){this.context.font=`${s} ${t}px ${i}`;return{width:this.context.measureText(e).width,height:1.2*t}}fitSingleLine(e,t,i,s){const n=s.fontFamily,r=s.fontWeight;let o=i.minSize,a=i.maxSize,c=0,l=o;for(;a-o>i.precision&&c<i.maxIterations;){const i=(o+a)/2;this.measureText(e,i,n,r).width<=t?(l=i,o=i):a=i,c++}const h=this.measureText(e,l,n,r);return{fontSize:l,lineHeight:i.lineHeight||1.2,actualLines:1,overflow:h.width>t,iterations:c,success:h.width<=t}}fitMultiLine(e,t,i,s,n){const r=n.fontFamily,o=n.fontWeight,a=s.lineHeight||1.4;let c=s.minSize,l=s.maxSize,h=0,u=c;for(;l-c>s.precision&&h<s.maxIterations;){const s=(c+l)/2;this.calculateLines(e,s,t,r,o)*s*a<=i?(u=s,c=s):l=s,h++}const d=this.calculateLines(e,u,t,r,o),m=d*u*a;return{fontSize:u,lineHeight:a,actualLines:d,overflow:m>i,iterations:h,success:m<=i}}fitOverflowAware(e,t,i,s,n){const r=this.fitMultiLine(e,t,i,s,n);if(r.success)return r;const o=this.fitSingleLine(e,t,s,n),a=s.lineHeight||1.4,c=Math.floor(i/(o.fontSize*a));return{fontSize:o.fontSize,lineHeight:a,actualLines:Math.min(c,1),overflow:!0,iterations:o.iterations,success:c>=1}}calculateLines(e,t,i,s,n){this.context.font=`${n} ${t}px ${s}`;const r=e.split(/\s+/);let o=1,a=0;for(const e of r){const t=this.context.measureText(`${e} `).width;a+t>i?(o++,a=t):a+=t}return o}static getOptimalConfig(e){switch(e){case"heading":return{mode:"single-line",minSize:18,maxSize:48,precision:.5,maxIterations:20,lineHeight:1.2};case"body":return{mode:"multi-line",minSize:14,maxSize:20,precision:.25,maxIterations:15,lineHeight:1.5};case"caption":return{mode:"overflow-aware",minSize:12,maxSize:16,precision:.25,maxIterations:10,lineHeight:1.3,overflow:"ellipsis"};case"button":return{mode:"single-line",minSize:14,maxSize:18,precision:.25,maxIterations:10,lineHeight:1,overflow:"ellipsis"};default:return{}}}createResponsiveFitting(e,t){const i=e,s=e.textContent||"",n=t.sort((e,t)=>e.containerSize-t.containerSize),r=new ResizeObserver(t=>{for(const i of t){const t=i.contentRect.width,r=i.contentRect.height;let o=n[0].config;for(const{containerSize:e,config:i}of n)t>=e&&(o=i);const a=this.fitText(e,s,t,r,o);this.applyFitting(e,a,o)}});r.observe(e),i._proteusTextFittingObserver=r}removeResponsiveFitting(e){const t=e,i=t._proteusTextFittingObserver;i&&(i.disconnect(),delete t._proteusTextFittingObserver)}}class g{calculateOptimalLineHeight(e,t,i,s){const n=[];let r=s.baseLineHeight;r=g.CONTENT_TYPE_RATIOS[s.contentType].optimal,n.push(`Base ratio for ${s.contentType}: ${r}`);const o=this.calculateSizeAdjustment(e,s.baseFontSize);r*=o,n.push(`Font size adjustment (${e}px): ×${o.toFixed(3)}`);const a=this.calculateLineLengthAdjustment(t,e);r*=a,n.push(`Line length adjustment (${t} chars): ×${a.toFixed(3)}`);const c=s.language?.split("-")[0]?.toLowerCase()||"en",l=g.LANGUAGE_ADJUSTMENTS[c]||g.LANGUAGE_ADJUSTMENTS.default;r*=l,1!==l&&n.push(`Language adjustment (${c}): ×${l}`);const h=g.DENSITY_MULTIPLIERS[s.density];r*=h,n.push(`Density adjustment (${s.density}): ×${h}`);const u=this.calculateWidthAdjustment(i,e);if(r*=u,1!==u&&n.push(`Container width adjustment: ×${u.toFixed(3)}`),s.accessibility){const e=this.calculateAccessibilityAdjustment(r,s);r=e.lineHeight,e.adjusted&&n.push(`Accessibility adjustment: ${e.reason}`)}const d=r;r=Math.max(s.minLineHeight,Math.min(s.maxLineHeight,r)),r!==d&&n.push(`Clamped to bounds: ${s.minLineHeight}-${s.maxLineHeight}`);const m=this.calculateAccessibilityMetrics(r,e,s);return{lineHeight:Math.round(1e3*r)/1e3,ratio:r,reasoning:n,accessibility:m}}applyOptimization(e,t,i){const s=e;s.style.lineHeight=t.lineHeight.toString(),i.accessibility&&(s.setAttribute("data-proteus-line-height",t.lineHeight.toString()),s.setAttribute("data-proteus-wcag-compliant",t.accessibility.wcagCompliant.toString()))}createResponsiveOptimization(e,t){const i=()=>{const i=getComputedStyle(e),s=parseFloat(i.fontSize),n=e.getBoundingClientRect().width,r=.5*s,o=Math.floor(n/r),a=this.calculateOptimalLineHeight(s,o,n,t);this.applyOptimization(e,a,t)};i();const s=new ResizeObserver(()=>{i()});return s.observe(e),()=>{s.disconnect()}}calculateSizeAdjustment(e,t){const i=e/t;return i<1?1+.2*(1-i):i>1?1-Math.min(.1*(i-1),.15):1}calculateLineLengthAdjustment(e,t){if(e<45)return.95;if(e>75){const t=e-75;return 1+Math.min(.002*t,.2)}return 1}calculateWidthAdjustment(e,t){const i=20*t;if(e<i){return 1+.1*(1-e/i)}return 1}calculateAccessibilityAdjustment(e,t){const i="body"===t.contentType?1.5:1.3;return e<i?{lineHeight:i,adjusted:!0,reason:`WCAG compliance requires minimum ${i}`}:{lineHeight:e,adjusted:!1,reason:""}}calculateAccessibilityMetrics(e,t,i){const s=e>=("body"===i.contentType?1.5:1.3);let n=50;const r=g.CONTENT_TYPE_RATIOS[i.contentType].optimal,o=Math.abs(e-r);return n+=Math.max(0,40-100*o),s&&(n+=10),n=Math.max(0,Math.min(100,n)),{wcagCompliant:s,readabilityScore:Math.round(n)}}static getOptimalConfig(e,t,i=!0){const s=this.CONTENT_TYPE_RATIOS[t];return{baseFontSize:16,baseLineHeight:s.optimal,minLineHeight:s.min,maxLineHeight:s.max,language:e,contentType:t,accessibility:i,density:"comfortable"}}}g.LANGUAGE_ADJUSTMENTS={en:1,zh:1.1,ja:1.1,ko:1.1,ar:1.05,hi:1.05,th:1.15,vi:1.05,de:.98,fr:1,es:1,it:1,pt:1,ru:1.02,default:1},g.CONTENT_TYPE_RATIOS={heading:{min:1,optimal:1.2,max:1.4},body:{min:1.3,optimal:1.5,max:1.8},caption:{min:1.2,optimal:1.4,max:1.6},code:{min:1.2,optimal:1.4,max:1.6},display:{min:.9,optimal:1.1,max:1.3}},g.DENSITY_MULTIPLIERS={compact:.9,comfortable:1,spacious:1.1};class f{constructor(e){this.config={baseFontSize:16,baseLineHeight:1.5,baselineUnit:24,scale:"minor-third",precision:.001,responsive:!0,containerAware:!1,...e},this.baselineGrid=this.config.baselineUnit}generateRhythm(e){this.config.containerAware&&e&&this.adjustBaselineForContainer(e);const t=this.generateSpacingScale(),i=this.generateLineHeights(),s=this.generateMargins(),n=this.generatePaddings();return{baselineGrid:this.baselineGrid,spacingScale:t,lineHeights:i,margins:s,paddings:n}}applyRhythm(e,t){const i=e;Object.entries(t.spacingScale).forEach(([e,t])=>{i.style.setProperty(`--rhythm-${e}`,`${t}px`)}),Object.entries(t.lineHeights).forEach(([e,t])=>{i.style.setProperty(`--line-height-${e}`,t.toString())}),Object.entries(t.margins).forEach(([e,t])=>{i.style.setProperty(`--margin-${e}`,`${t}px`)}),Object.entries(t.paddings).forEach(([e,t])=>{i.style.setProperty(`--padding-${e}`,`${t}px`)}),i.style.setProperty("--baseline-grid",`${t.baselineGrid}px`)}toBaseline(e){return Math.round(e/this.baselineGrid)*this.baselineGrid}calculateBaselineLineHeight(e){const t=e*this.config.baseLineHeight;return this.toBaseline(t)/e}generateResponsiveSpacing(e,t){const i={};return e.forEach((e,s)=>{const n=t[s]||1,r=this.baselineGrid*n;i[`container-${e}`]={xs:.25*r,sm:.5*r,md:r,lg:1.5*r,xl:2*r,xxl:3*r}}),i}generateCSS(e){let t=":root {\n";return t+=` --baseline-grid: ${e.baselineGrid}px;\n`,Object.entries(e.spacingScale).forEach(([e,i])=>{t+=` --rhythm-${e}: ${i}px;\n`}),Object.entries(e.lineHeights).forEach(([e,i])=>{t+=` --line-height-${e}: ${i};\n`}),Object.entries(e.margins).forEach(([e,i])=>{t+=` --margin-${e}: ${i}px;\n`}),Object.entries(e.paddings).forEach(([e,i])=>{t+=` --padding-${e}: ${i}px;\n`}),t+="}\n\n",t+=this.generateUtilityClasses(e),t}validateRhythm(e){const t=[];return Object.entries(e.spacingScale).forEach(([i,s])=>{s%e.baselineGrid!==0&&t.push(`Spacing ${i} (${s}px) doesn't align to baseline grid (${e.baselineGrid}px)`)}),Object.entries(e.margins).forEach(([i,s])=>{s%e.baselineGrid!==0&&t.push(`Margin ${i} (${s}px) doesn't align to baseline grid`)}),{valid:0===t.length,issues:t}}generateSpacingScale(){const e="number"==typeof this.config.scale?this.config.scale:f.SCALE_RATIOS[this.config.scale],t=this.baselineGrid;return{xs:this.toBaseline(t/(e*e)),sm:this.toBaseline(t/e),md:t,lg:this.toBaseline(t*e),xl:this.toBaseline(t*e*e),xxl:this.toBaseline(t*e*e*e)}}generateLineHeights(){return{tight:1.2,normal:1.5,relaxed:1.75,loose:2}}generateMargins(){const e=this.generateSpacingScale();return{none:0,xs:e.xs,sm:e.sm,md:e.md,lg:e.lg,xl:e.xl,auto:-1}}generatePaddings(){const e=this.generateSpacingScale();return{none:0,xs:e.xs,sm:e.sm,md:e.md,lg:e.lg,xl:e.xl}}adjustBaselineForContainer(e){const t=Math.max(.75,Math.min(1.5,e/800));this.baselineGrid=Math.round(this.config.baselineUnit*t)}generateUtilityClasses(e){let t="";return Object.entries(e.spacingScale).forEach(([e,i])=>{t+=`.m-${e} { margin: ${i}px; }\n`,t+=`.mt-${e} { margin-top: ${i}px; }\n`,t+=`.mr-${e} { margin-right: ${i}px; }\n`,t+=`.mb-${e} { margin-bottom: ${i}px; }\n`,t+=`.ml-${e} { margin-left: ${i}px; }\n`,t+=`.mx-${e} { margin-left: ${i}px; margin-right: ${i}px; }\n`,t+=`.my-${e} { margin-top: ${i}px; margin-bottom: ${i}px; }\n`,t+=`.p-${e} { padding: ${i}px; }\n`,t+=`.pt-${e} { padding-top: ${i}px; }\n`,t+=`.pr-${e} { padding-right: ${i}px; }\n`,t+=`.pb-${e} { padding-bottom: ${i}px; }\n`,t+=`.pl-${e} { padding-left: ${i}px; }\n`,t+=`.px-${e} { padding-left: ${i}px; padding-right: ${i}px; }\n`,t+=`.py-${e} { padding-top: ${i}px; padding-bottom: ${i}px; }\n`}),Object.entries(e.lineHeights).forEach(([e,i])=>{t+=`.leading-${e} { line-height: ${i}; }\n`}),t+=".baseline-align { ",t+=`background-image: linear-gradient(to bottom, transparent ${e.baselineGrid-1}px, rgba(255, 0, 0, 0.1) ${e.baselineGrid-1}px, rgba(255, 0, 0, 0.1) ${e.baselineGrid}px, transparent ${e.baselineGrid}px); `,t+=`background-size: 100% ${e.baselineGrid}px; `,t+="}\n",t}createResponsiveRhythm(e,t,i){const s=()=>{const s=e.getBoundingClientRect().width;for(let e=0;e<t.length;e++)s>=t[e]&&i[e];const n=this.generateRhythm(s);this.applyRhythm(e,n)};s();const n=new ResizeObserver(()=>{s()});return n.observe(e),()=>{n.disconnect()}}}f.SCALE_RATIOS={"minor-second":1.067,"major-second":1.125,"minor-third":1.2,"major-third":1.25,"perfect-fourth":1.333,"golden-ratio":1.618};class y{constructor(e,t={}){this.resizeObserver=null,this.mutationObserver=null,this.element=e,this.config={minColumnWidth:250,maxColumns:12,gap:16,aspectRatio:1,masonry:!1,autoFlow:"row",alignment:{justify:"stretch",align:"stretch"},responsive:!0,breakpoints:{},...t},this.state=this.createInitialState(),this.setupGrid()}activate(){this.updateGrid(),this.setupObservers()}deactivate(){this.cleanupObservers(),this.removeGridStyles()}updateConfig(e){this.config={...this.config,...e},this.updateGrid()}getState(){return{...this.state}}recalculate(){this.updateGrid()}addItems(e){const t=document.createDocumentFragment();e.forEach(e=>{this.prepareGridItem(e),t.appendChild(e)}),this.element.appendChild(t),this.updateGrid()}removeItems(e){e.forEach(e=>{e.parentNode===this.element&&this.element.removeChild(e)}),this.updateGrid()}calculateOptimalColumns(e){const t=e-this.getGapValue(),i=this.config.minColumnWidth,s=Math.floor((t+this.getGapValue())/(i+this.getGapValue()));return Math.min(s,this.config.maxColumns)}setupGrid(){this.element.style.display="grid",this.config.masonry?this.setupMasonryGrid():this.setupRegularGrid()}setupRegularGrid(){const e=this.element;e.style.gridAutoFlow=this.config.autoFlow,e.style.justifyContent=this.config.alignment.justify,e.style.alignContent=this.config.alignment.align,e.style.justifyItems=this.config.alignment.justify,e.style.alignItems=this.config.alignment.align}setupMasonryGrid(){const e=this.element;this.supportsMasonry()?e.style.gridTemplateRows="masonry":this.implementJavaScriptMasonry()}updateGrid(){const e=this.element.getBoundingClientRect(),t=e.width,i=e.height,s=this.getActiveConfig(t),n=this.calculateOptimalColumns(t),r=this.getGapValue(),o=(t-r*(n-1))/n,a=s.aspectRatio?o/s.aspectRatio:0;this.state={columns:n,rows:Math.ceil(this.getItemCount()/n),gap:r,itemWidth:o,itemHeight:a,containerWidth:t,containerHeight:i},this.applyGridStyles(),s.masonry&&!this.supportsMasonry()&&this.updateMasonryLayout()}applyGridStyles(){const e=this.element,{columns:t,gap:i,itemHeight:s}=this.state;e.style.gridTemplateColumns=`repeat(${t}, 1fr)`,e.style.gap=`${i}px`,e.style.gridAutoRows=s>0?`${s}px`:"auto",Array.from(this.element.children).forEach(e=>{this.prepareGridItem(e)})}prepareGridItem(e){const t=e;t.style.boxSizing="border-box",this.config.aspectRatio&&!this.config.masonry&&(t.style.aspectRatio=this.config.aspectRatio.toString()),t.classList.add("proteus-grid-item")}implementJavaScriptMasonry(){const e=Array.from(this.element.children),{columns:t,gap:i}=this.state,s=new Array(t).fill(0);e.forEach((e,t)=>{const n=s.indexOf(Math.min(...s)),r=n,o=Math.floor(s[n]/(this.state.itemHeight+i));e.style.gridColumnStart=(r+1).toString(),e.style.gridRowStart=(o+1).toString();const a=e.getBoundingClientRect().height||this.state.itemHeight;s[n]+=a+i})}updateMasonryLayout(){requestAnimationFrame(()=>{this.implementJavaScriptMasonry()})}setupObservers(){this.config.responsive&&(this.resizeObserver=new ResizeObserver(()=>{this.updateGrid()}),this.resizeObserver.observe(this.element),this.mutationObserver=new MutationObserver(()=>{this.updateGrid()}),this.mutationObserver.observe(this.element,{childList:!0,subtree:!1}))}cleanupObservers(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}removeGridStyles(){const e=this.element;e.style.removeProperty("display"),e.style.removeProperty("grid-template-columns"),e.style.removeProperty("grid-template-rows"),e.style.removeProperty("gap"),e.style.removeProperty("grid-auto-flow"),e.style.removeProperty("justify-content"),e.style.removeProperty("align-content"),e.style.removeProperty("justify-items"),e.style.removeProperty("align-items"),e.style.removeProperty("grid-auto-rows"),Array.from(this.element.children).forEach(e=>{const t=e;t.style.removeProperty("grid-column-start"),t.style.removeProperty("grid-row-start"),t.style.removeProperty("aspect-ratio"),t.classList.remove("proteus-grid-item")})}getActiveConfig(e){let t={...this.config};if(this.config.breakpoints){const i=Object.entries(this.config.breakpoints).map(([e,t])=>({name:e,width:parseInt(e),config:t})).sort((e,t)=>e.width-t.width);for(const s of i)e>=s.width&&(t={...t,...s.config})}return t}getGapValue(){if("fluid"===this.config.gap){const e=this.element.getBoundingClientRect().width;return Math.max(8,Math.min(32,.02*e))}return this.config.gap}getItemCount(){return this.element.children.length}supportsMasonry(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("grid-template-rows","masonry")}createInitialState(){return{columns:1,rows:1,gap:16,itemWidth:0,itemHeight:0,containerWidth:0,containerHeight:0}}}class b{constructor(e,t={}){this.resizeObserver=null,this.mutationObserver=null,this.element=e,this.config={direction:"row",wrap:"auto",justify:"flex-start",align:"stretch",gap:16,responsive:!0,autoWrap:!0,minItemWidth:200,maxItemWidth:800,itemGrowRatio:1,itemShrinkRatio:1,breakpoints:{},...t},this.state=this.createInitialState(),this.setupFlexbox()}activate(){this.updateFlexbox(),this.setupObservers()}deactivate(){this.cleanupObservers(),this.removeFlexboxStyles()}updateConfig(e){this.config={...this.config,...e},this.updateFlexbox()}getState(){return{...this.state}}configureItem(e,t){const i=e;i.style.flexGrow=t.grow.toString(),i.style.flexShrink=t.shrink.toString(),i.style.flexBasis="number"==typeof t.basis?`${t.basis}px`:t.basis,void 0!==t.order&&(i.style.order=t.order.toString()),t.alignSelf&&(i.style.alignSelf=t.alignSelf)}autoConfigureItems(){const e=Array.from(this.element.children),t=this.calculateOptimalItemConfig();e.forEach(e=>{this.configureItem(e,t)})}shouldWrap(){if(!this.config.autoWrap)return"wrap"===this.config.wrap;const e=this.element.getBoundingClientRect().width,t=this.element.children.length,i=this.getGapValue();return t*(this.config.minItemWidth||200)+i*(t-1)>e}calculateSpaceDistribution(){const e=this.element.getBoundingClientRect().width,t=this.element.children.length,i=this.getGapValue();if(this.shouldWrap()){const t=this.calculateItemsPerLine();return{itemWidth:(e-i*(t-1))/t,gap:i,remainingSpace:0}}{const s=i*(t-1),n=(e-s)/t;return{itemWidth:n,gap:i,remainingSpace:Math.max(0,e-(t*n+s))}}}calculateItemsPerLine(){const e=this.element.getBoundingClientRect().width,t=this.config.minItemWidth||200,i=this.getGapValue();let s=1,n=this.element.children.length,r=1;for(;s<=n;){const o=Math.floor((s+n)/2);o*t+i*(o-1)<=e?(r=o,s=o+1):n=o-1}return r}setupFlexbox(){this.element.style.display="flex",this.applyFlexboxStyles()}updateFlexbox(){const e=this.element.getBoundingClientRect(),t=this.getActiveConfig(e.width);this.state={containerWidth:e.width,containerHeight:e.height,itemCount:this.element.children.length,wrappedLines:this.calculateWrappedLines(),optimalItemWidth:this.calculateSpaceDistribution().itemWidth,actualGap:this.getGapValue(),overflow:this.checkOverflow()},this.applyFlexboxStyles(t),this.config.autoWrap&&this.autoConfigureItems()}applyFlexboxStyles(e=this.config){const t=this.element;t.style.flexDirection=e.direction,t.style.flexWrap="auto"===e.wrap?this.shouldWrap()?"wrap":"nowrap":e.wrap,t.style.justifyContent=e.justify,t.style.alignItems=e.align,t.style.gap=`${this.getGapValue()}px`}calculateOptimalItemConfig(){const e=this.calculateSpaceDistribution(),t=this.shouldWrap();return{grow:t?0:this.config.itemGrowRatio,shrink:this.config.itemShrinkRatio,basis:t?`${e.itemWidth}px`:"auto",alignSelf:"auto"}}calculateWrappedLines(){if(!this.shouldWrap())return 1;const e=this.calculateItemsPerLine();return Math.ceil(this.element.children.length/e)}checkOverflow(){const e=this.element.getBoundingClientRect().width,t=this.calculateSpaceDistribution();return this.element.children.length*t.itemWidth+(this.element.children.length-1)*t.gap>e&&!this.shouldWrap()}getActiveConfig(e){let t={...this.config};if(this.config.breakpoints){const i=Object.entries(this.config.breakpoints).map(([e,t])=>({name:e,width:parseInt(e),config:t})).sort((e,t)=>e.width-t.width);for(const s of i)e>=s.width&&(t={...t,...s.config})}return t}getGapValue(){if("fluid"===this.config.gap){const e=this.element.getBoundingClientRect().width;return Math.max(8,Math.min(32,.02*e))}return this.config.gap}setupObservers(){this.config.responsive&&(this.resizeObserver=new ResizeObserver(()=>{this.updateFlexbox()}),this.resizeObserver.observe(this.element),this.mutationObserver=new MutationObserver(()=>{this.updateFlexbox()}),this.mutationObserver.observe(this.element,{childList:!0,subtree:!1}))}cleanupObservers(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}removeFlexboxStyles(){const e=this.element;e.style.removeProperty("display"),e.style.removeProperty("flex-direction"),e.style.removeProperty("flex-wrap"),e.style.removeProperty("justify-content"),e.style.removeProperty("align-items"),e.style.removeProperty("gap"),Array.from(this.element.children).forEach(e=>{const t=e;t.style.removeProperty("flex-grow"),t.style.removeProperty("flex-shrink"),t.style.removeProperty("flex-basis"),t.style.removeProperty("order"),t.style.removeProperty("align-self")})}createInitialState(){return{containerWidth:0,containerHeight:0,itemCount:0,wrappedLines:1,optimalItemWidth:0,actualGap:16,overflow:!1}}}class v{constructor(e,t={}){this.mutationObserver=null,this.element=e,this.config={pattern:"natural",direction:"auto",language:"en",accessibility:!0,focusManagement:!0,skipLinks:!0,landmarks:!0,readingOrder:"auto",customFlow:[],...t},this.state=this.createInitialState(),this.activate()}activate(){this.analyzeContent(),this.applyFlowPattern(),this.setupAccessibility(),this.setupObservers()}deactivate(){this.cleanupObservers(),this.removeFlowStyles(),this.removeAccessibilityFeatures()}updateConfig(e){this.config={...this.config,...e},this.activate()}getState(){return{...this.state}}setTabOrder(e){e.forEach((e,t)=>{e.tabIndex=t+1}),this.state.tabOrder=e}addSkipLink(e,t){if(!this.config.skipLinks)return;const i=document.createElement("a");i.href=`#${this.ensureId(e)}`,i.textContent=t,i.className="proteus-skip-link",i.style.cssText="\n position: absolute;\n top: -40px;\n left: 6px;\n background: #000;\n color: #fff;\n padding: 8px;\n text-decoration: none;\n z-index: 1000;\n transition: top 0.3s;\n ",i.addEventListener("focus",()=>{i.style.top="6px"}),i.addEventListener("blur",()=>{i.style.top="-40px"}),document.body.insertBefore(i,document.body.firstChild),this.state.skipTargets.push(e)}analyzeContent(){this.state.direction=this.detectReadingDirection(),this.state.focusableElements=this.findFocusableElements(),this.state.landmarks=this.identifyLandmarks(),this.state.currentPattern=this.determineOptimalPattern()}applyFlowPattern(){let e;if("custom"===this.config.pattern)e=this.config.customFlow;else if("auto"===this.config.pattern){const t=this.determineOptimalPattern();e=v.READING_PATTERNS[t]}else e=v.READING_PATTERNS[this.config.pattern];if(!e)return;const t=this.sortElementsByPattern(e);this.applyVisualFlow(t),this.config.focusManagement&&this.setLogicalTabOrder(t)}setupAccessibility(){this.config.accessibility&&(this.config.landmarks&&this.addLandmarks(),this.config.skipLinks&&this.addDefaultSkipLinks(),this.setReadingOrder())}detectReadingDirection(){if("auto"!==this.config.direction)return this.config.direction;const e=this.config.language?.split("-")[0]?.toLowerCase();return e&&v.RTL_LANGUAGES.includes(e)?"rtl":"ltr"}findFocusableElements(){const e=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])','[contenteditable="true"]'].join(", ");return Array.from(this.element.querySelectorAll(e))}identifyLandmarks(){const e=new Map;return Object.entries({banner:'header, [role="banner"]',main:'main, [role="main"]',navigation:'nav, [role="navigation"]',complementary:'aside, [role="complementary"]',contentinfo:'footer, [role="contentinfo"]',search:'[role="search"]',form:'form, [role="form"]'}).forEach(([t,i])=>{const s=this.element.querySelector(i);s&&e.set(t,s)}),e}determineOptimalPattern(){if("auto"!==this.config.pattern)return this.config.pattern;const e=this.state.landmarks.has("banner"),t=this.state.landmarks.has("complementary"),i=this.state.landmarks.has("navigation");return e&&t&&i?"z-pattern":e&&t?"f-pattern":"natural"}sortElementsByPattern(e){const t=[];return e.forEach(e=>{Array.from(this.element.querySelectorAll(e.selector)).forEach(i=>{t.push({element:i,priority:e.priority})})}),t.sort((e,t)=>e.priority!==t.priority?e.priority-t.priority:e.element.compareDocumentPosition(t.element)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1).map(e=>e.element)}applyVisualFlow(e){e.forEach((e,t)=>{const i=e;i.style.setProperty("--flow-order",t.toString()),i.classList.add("proteus-flow-item")}),this.addFlowCSS()}setLogicalTabOrder(e){const t=e.filter(e=>this.state.focusableElements.includes(e));t.forEach((e,t)=>{e.tabIndex=t+1}),this.state.tabOrder=t}addLandmarks(){this.state.landmarks.forEach((e,t)=>{const i=e;if(i.getAttribute("role")||i.setAttribute("role",t),!i.getAttribute("aria-label")&&!i.getAttribute("aria-labelledby")){const e=this.generateLandmarkLabel(t);i.setAttribute("aria-label",e)}})}addDefaultSkipLinks(){const e=this.state.landmarks.get("main");e&&this.addSkipLink(e,"Skip to main content");const t=this.state.landmarks.get("navigation");t&&this.addSkipLink(t,"Skip to navigation")}setReadingOrder(){"visual"===this.config.readingOrder?this.element.style.setProperty("--reading-order","visual"):this.element.style.setProperty("--reading-order","logical")}generateLandmarkLabel(e){return{banner:"Site header",main:"Main content",navigation:"Site navigation",complementary:"Sidebar",contentinfo:"Site footer",search:"Search",form:"Form"}[e]||e}addFlowCSS(){const e="proteus-flow-styles";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent='\n .proteus-flow-item {\n order: var(--flow-order, 0);\n }\n \n .proteus-skip-link:focus {\n clip: auto !important;\n height: auto !important;\n margin: 0 !important;\n overflow: visible !important;\n position: absolute !important;\n width: auto !important;\n }\n \n [dir="rtl"] .proteus-flow-item {\n direction: rtl;\n }\n ',document.head.appendChild(t)}ensureId(e){return e.id||(e.id=`proteus-flow-${Math.random().toString(36).substring(2,11)}`),e.id}setupObservers(){this.mutationObserver=new MutationObserver(()=>{this.analyzeContent(),this.applyFlowPattern()}),this.mutationObserver.observe(this.element,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["role","tabindex"]})}cleanupObservers(){this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}removeFlowStyles(){this.element.querySelectorAll(".proteus-flow-item").forEach(e=>{const t=e;t.classList.remove("proteus-flow-item"),t.style.removeProperty("--flow-order")});const e=document.getElementById("proteus-flow-styles");e&&e.remove()}removeAccessibilityFeatures(){document.querySelectorAll(".proteus-skip-link").forEach(e=>e.remove()),this.state.tabOrder.forEach(e=>{e.removeAttribute("tabindex")})}createInitialState(){return{currentPattern:"natural",direction:"ltr",focusableElements:[],tabOrder:[],landmarks:new Map,skipTargets:[]}}}v.READING_PATTERNS={"z-pattern":[{selector:'header, [role="banner"]',region:"header",priority:1},{selector:'nav, [role="navigation"]',region:"navigation",priority:2},{selector:'main, [role="main"]',region:"main",priority:3},{selector:'aside, [role="complementary"]',region:"sidebar",priority:4},{selector:'footer, [role="contentinfo"]',region:"footer",priority:5}],"f-pattern":[{selector:'header, [role="banner"]',region:"header",priority:1},{selector:'main, [role="main"]',region:"main",priority:2},{selector:'aside, [role="complementary"]',region:"sidebar",priority:3},{selector:'nav, [role="navigation"]',region:"navigation",priority:4},{selector:'footer, [role="contentinfo"]',region:"footer",priority:5}],gutenberg:[{selector:'nav, [role="navigation"]',region:"navigation",priority:1},{selector:'header, [role="banner"]',region:"header",priority:2},{selector:'main, [role="main"]',region:"main",priority:3},{selector:'aside, [role="complementary"]',region:"sidebar",priority:4},{selector:'footer, [role="contentinfo"]',region:"footer",priority:5}],natural:[{selector:'header, [role="banner"]',region:"header",priority:1},{selector:'main, [role="main"]',region:"main",priority:2},{selector:'nav, [role="navigation"]',region:"navigation",priority:3},{selector:'aside, [role="complementary"]',region:"sidebar",priority:4},{selector:'footer, [role="contentinfo"]',region:"footer",priority:5}]},v.RTL_LANGUAGES=["ar","he","fa","ur","yi","ji","iw","ku","ps","sd"];class S{constructor(e,t={}){this.resizeObserver=null,this.element=e,this.config={baseSize:16,scale:"minor-third",density:"comfortable",containerAware:!0,accessibility:!0,touchTargets:!0,minTouchSize:S.WCAG_MIN_TOUCH_SIZE,maxSpacing:128,responsive:!0,breakpoints:{},...t},this.state=this.createInitialState(),this.setupSpacing()}activate(){this.calculateSpacing(),this.applySpacing(),this.setupObservers()}deactivate(){this.cleanupObservers(),this.removeSpacing()}updateConfig(e){this.config={...this.config,...e},this.activate()}getState(){return{...this.state}}applyToElement(e,t){const i=this.state.currentScale[t];e.style.setProperty("--spacing",`${i}px`),this.state.appliedSpacing.set(e,t)}applyMargin(e,t){const i="number"==typeof t?t:this.state.currentScale[t];e.style.margin=`${i}px`}applyPadding(e,t){const i="number"==typeof t?t:this.state.currentScale[t];e.style.padding=`${i}px`}applyGap(e,t){const i="number"==typeof t?t:this.state.currentScale[t];e.style.gap=`${i}px`}ensureTouchTargets(){if(!this.config.touchTargets)return;this.findInteractiveElements().forEach(e=>{this.makeTouchCompliant(e)})}generateScale(){const e="number"==typeof this.config.scale?this.config.scale:S.SCALE_RATIOS[this.config.scale],t=S.DENSITY_MULTIPLIERS[this.config.density],i=this.calculateContainerMultiplier(),s=this.config.baseSize*t*i;return{xs:Math.round(s/(e*e)),sm:Math.round(s/e),md:Math.round(s),lg:Math.round(s*e),xl:Math.round(s*e*e),xxl:Math.min(Math.round(s*e*e*e),this.config.maxSpacing)}}calculateOptimalSpacing(e){switch(e){case"text":return"compact"===this.config.density?"sm":"md";case"interactive":return this.config.accessibility?"lg":"md";case"layout":return"spacious"===this.config.density?"xl":"lg";default:return"md"}}validateAccessibility(){const e=[];if(this.config.touchTargets){this.findInteractiveElements().forEach(t=>{const i=t.getBoundingClientRect(),s=this.config.minTouchSize;(i.width<s||i.height<s)&&e.push(`Touch target too small: ${i.width}x${i.height} (minimum: ${s}x${s})`)})}const t=this.state.currentScale,i=[t.sm/t.xs,t.md/t.sm,t.lg/t.md,t.xl/t.lg];return i.length>0&&i.some(e=>Math.abs(e-i[0])>.1)&&e.push("Inconsistent spacing ratios detected"),{compliant:0===e.length,issues:e}}setupSpacing(){this.calculateSpacing()}calculateSpacing(){const e=this.element.getBoundingClientRect();this.getActiveConfig(e.width),this.state={currentScale:this.generateScale(),containerSize:e.width,scaleFactor:this.calculateContainerMultiplier(),touchCompliant:this.validateTouchCompliance(),appliedSpacing:new Map}}applySpacing(){const e=this.element,t=this.state.currentScale;Object.entries(t).forEach(([t,i])=>{e.style.setProperty(`--spacing-${t}`,`${i}px`)}),this.addSpacingCSS(),this.config.touchTargets&&this.ensureTouchTargets()}calculateContainerMultiplier(){if(!this.config.containerAware)return 1;const e=this.element.getBoundingClientRect().width/800;return Math.max(.75,Math.min(1.5,e))}getActiveConfig(e){let t={...this.config};if(this.config.breakpoints){const i=Object.entries(this.config.breakpoints).map(([e,t])=>({name:e,width:parseInt(e),config:t})).sort((e,t)=>e.width-t.width);for(const s of i)e>=s.width&&(t={...t,...s.config})}return t}findInteractiveElements(){const e=["button","a[href]","input","select","textarea",'[tabindex]:not([tabindex="-1"])','[role="button"]','[role="link"]',"[onclick]"].join(", ");return Array.from(this.element.querySelectorAll(e))}makeTouchCompliant(e){const t=e,i=e.getBoundingClientRect(),s=this.config.minTouchSize;(i.width<s||i.height<s)&&(t.style.minWidth=`${s}px`,t.style.minHeight=`${s}px`,t.style.display=t.style.display||"inline-block");const n=this.state.currentScale.sm;t.style.margin=n/2+"px"}validateTouchCompliance(){if(!this.config.touchTargets)return!0;return this.findInteractiveElements().every(e=>{const t=e.getBoundingClientRect();return t.width>=this.config.minTouchSize&&t.height>=this.config.minTouchSize})}addSpacingCSS(){const e="proteus-spacing-styles";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e;const i=this.state.currentScale;let s=":root {\n";Object.entries(i).forEach(([e,t])=>{s+=` --spacing-${e}: ${t}px;\n`}),s+="}\n\n",Object.entries(i).forEach(([e,t])=>{s+=`.m-${e} { margin: ${t}px; }\n`,s+=`.mt-${e} { margin-top: ${t}px; }\n`,s+=`.mr-${e} { margin-right: ${t}px; }\n`,s+=`.mb-${e} { margin-bottom: ${t}px; }\n`,s+=`.ml-${e} { margin-left: ${t}px; }\n`,s+=`.mx-${e} { margin-left: ${t}px; margin-right: ${t}px; }\n`,s+=`.my-${e} { margin-top: ${t}px; margin-bottom: ${t}px; }\n`,s+=`.p-${e} { padding: ${t}px; }\n`,s+=`.pt-${e} { padding-top: ${t}px; }\n`,s+=`.pr-${e} { padding-right: ${t}px; }\n`,s+=`.pb-${e} { padding-bottom: ${t}px; }\n`,s+=`.pl-${e} { padding-left: ${t}px; }\n`,s+=`.px-${e} { padding-left: ${t}px; padding-right: ${t}px; }\n`,s+=`.py-${e} { padding-top: ${t}px; padding-bottom: ${t}px; }\n`,s+=`.gap-${e} { gap: ${t}px; }\n`}),s+=`\n .touch-target {\n min-width: ${this.config.minTouchSize}px;\n min-height: ${this.config.minTouchSize}px;\n display: inline-block;\n }\n \n .touch-spacing {\n margin: ${this.state.currentScale.sm/2}px;\n }\n `,t.textContent=s,document.head.appendChild(t)}setupObservers(){this.config.responsive&&(this.resizeObserver=new ResizeObserver(()=>{this.calculateSpacing(),this.applySpacing()}),this.resizeObserver.observe(this.element))}cleanupObservers(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null)}removeSpacing(){const e=this.element,t=this.state.currentScale;Object.keys(t).forEach(t=>{e.style.removeProperty(`--spacing-${t}`)}),this.state.appliedSpacing.forEach((e,t)=>{t.style.removeProperty("--spacing")});const i=document.getElementById("proteus-spacing-styles");i&&i.remove()}createInitialState(){return{currentScale:{xs:4,sm:8,md:16,lg:24,xl:32,xxl:48},containerSize:0,scaleFactor:1,touchCompliant:!0,appliedSpacing:new Map}}}S.SCALE_RATIOS={"minor-second":1.067,"major-second":1.125,"minor-third":1.2,"major-third":1.25,"perfect-fourth":1.333,"golden-ratio":1.618},S.DENSITY_MULTIPLIERS={compact:.8,comfortable:1,spacious:1.25},S.WCAG_MIN_TOUCH_SIZE=44;class w{constructor(e,t={}){this.resizeObserver=null,this.mutationObserver=null,this.element=e,this.config={priorities:new Map,breakpoints:{},accessibility:!0,animations:!0,focusManagement:!0,preserveTabOrder:!0,animationDuration:300,easing:"cubic-bezier(0.4, 0.0, 0.2, 1)",...t},this.state=this.createInitialState(),this.setupReordering()}activate(){this.captureOriginalOrder(),this.applyReordering(),this.setupObservers()}deactivate(){this.cleanupObservers(),this.restoreOriginalOrder()}updateConfig(e){this.config={...this.config,...e},this.applyReordering()}setPriority(e,t){this.config.priorities.set(e,t),this.applyReordering()}addRule(e,t){this.config.breakpoints[e]||(this.config.breakpoints[e]=[]),this.config.breakpoints[e].push(t),this.applyReordering()}getState(){return{...this.state}}reorder(e){this.config.animations?this.animateReorder(e):this.applyOrder(e)}restoreOriginalOrder(){this.reorder(this.state.originalOrder)}setupReordering(){this.captureOriginalOrder()}captureOriginalOrder(){this.state.originalOrder=Array.from(this.element.children),this.state.currentOrder=[...this.state.originalOrder]}applyReordering(){const e=this.element.getBoundingClientRect().width,t=this.getActiveRules(e);this.state.activeRules=t;const i=this.calculateNewOrder(t);this.config.animations&&!this.arraysEqual(i,this.state.currentOrder)?this.animateReorder(i):this.applyOrder(i)}getActiveRules(e){const t=[];return Object.entries(this.config.breakpoints).forEach(([i,s])=>{const n=parseInt(i);e>=n&&t.push(...s)}),t}calculateNewOrder(e){let t=[...this.state.originalOrder];return this.config.priorities.size>0&&t.sort((e,t)=>(this.config.priorities.get(e)||0)-(this.config.priorities.get(t)||0)),e.forEach(e=>{Array.from(this.element.querySelectorAll(e.selector)).forEach(i=>{this.shouldApplyRule(e)&&(t=this.applyRule(t,i,e))})}),t}shouldApplyRule(e){if(!e.condition||!e.value)return!0;const t=this.element.getBoundingClientRect();switch(e.condition){case"min-width":return t.width>=e.value;case"max-width":return t.width<=e.value;case"aspect-ratio":return t.width/t.height>=e.value;default:return!0}}applyRule(e,t,i){const s=e.indexOf(t);if(-1===s)return e;const n=[...e];switch(n.splice(s,1),i.action){case"move-first":n.unshift(t);break;case"move-last":default:n.push(t);break;case"move-before":if(i.target){const e=this.element.querySelector(i.target),s=n.indexOf(e);-1!==s?n.splice(s,0,t):n.push(t)}break;case"move-after":if(i.target){const e=this.element.querySelector(i.target),s=n.indexOf(e);-1!==s?n.splice(s+1,0,t):n.push(t)}break;case"hide":t.style.display="none",n.push(t);break;case"show":t.style.display="",n.push(t)}return n}animateReorder(e){if(this.state.animating)return;this.state.animating=!0;const t=new Map;this.state.currentOrder.forEach(e=>{t.set(e,{element:e,first:e.getBoundingClientRect(),last:{x:0,y:0,width:0,height:0},invert:{x:0,y:0},play:!1})});const i=this.preserveFocus();this.applyOrder(e),t.forEach((e,t)=>{e.last=t.getBoundingClientRect(),e.invert={x:e.first.left-e.last.left,y:e.first.top-e.last.top},0===e.invert.x&&0===e.invert.y||(t.style.transform=`translate(${e.invert.x}px, ${e.invert.y}px)`,e.play=!0)}),requestAnimationFrame(()=>{t.forEach((e,t)=>{if(e.play){const e=t;e.style.transition=`transform ${this.config.animationDuration}ms ${this.config.easing}`,e.style.transform="translate(0, 0)"}}),setTimeout(()=>{t.forEach((e,t)=>{const i=t;i.style.transition="",i.style.transform=""}),this.state.animating=!1,this.restoreFocus(i),this.config.accessibility&&this.updateAccessibility()},this.config.animationDuration)}),this.state.flipStates=t}applyOrder(e){const t=document.createDocumentFragment();e.forEach(e=>{t.appendChild(e)}),this.element.appendChild(t),this.state.currentOrder=e}preserveFocus(){if(!this.config.focusManagement)return null;const e=document.activeElement;return e&&this.element.contains(e)?(this.state.focusedElement=e,e):null}restoreFocus(e){this.config.focusManagement&&e&&document.contains(e)&&e.focus()}updateAccessibility(){this.config.accessibility&&(this.config.preserveTabOrder&&this.updateTabOrder(),this.announceChanges())}updateTabOrder(){this.state.currentOrder.filter(e=>e.tabIndex>=0||this.isFocusable(e)).forEach((e,t)=>{e.tabIndex=t+1})}isFocusable(e){return["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[contenteditable="true"]'].some(t=>e.matches(t))}announceChanges(){const e=document.createElement("div");e.setAttribute("aria-live","polite"),e.setAttribute("aria-atomic","true"),e.style.cssText="\n position: absolute;\n left: -10000px;\n width: 1px;\n height: 1px;\n overflow: hidden;\n ",e.textContent="Content order has been updated",document.body.appendChild(e),setTimeout(()=>{document.body.removeChild(e)},1e3)}arraysEqual(e,t){return e.length===t.length&&e.every((e,i)=>e===t[i])}setupObservers(){this.resizeObserver=new ResizeObserver(()=>{this.applyReordering()}),this.resizeObserver.observe(this.element),this.mutationObserver=new MutationObserver(()=>{this.captureOriginalOrder(),this.applyReordering()}),this.mutationObserver.observe(this.element,{childList:!0,subtree:!1})}cleanupObservers(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}createInitialState(){return{originalOrder:[],currentOrder:[],activeRules:[],focusedElement:null,animating:!1,flipStates:new Map}}}class A{constructor(e,t={}){this.resizeObserver=null,this.intersectionObserver=null,this.sources=[],this.element=e,this.config={formats:["avif","webp","jpeg"],sizes:[320,640,768,1024,1280,1920],quality:80,lazyLoading:!0,artDirection:!1,containerBased:!0,placeholder:"blur",placeholderColor:"#f0f0f0",fadeInDuration:300,retina:!0,progressive:!0,...t},this.state=this.createInitialState(),this.setupImage()}activate(){this.detectFormatSupport(),this.generateSources(),this.setupObservers(),this.config.lazyLoading||this.loadImage()}deactivate(){this.cleanupObservers(),this.removeImageFeatures()}updateConfig(e){this.config={...this.config,...e},this.generateSources(),this.updateImage()}getState(){return{...this.state}}load(){this.loadImage()}preload(){return new Promise((e,t)=>{const i=this.getOptimalSource();if(!i)return void t(new Error("No optimal source found"));const s=new Image;s.onload=()=>e(),s.onerror=()=>t(new Error("Failed to preload image")),s.src=i.src})}setupImage(){this.addPlaceholder(),this.setupImageElement()}async detectFormatSupport(){const e=["webp","avif"];for(const t of e)if(!A.FORMAT_SUPPORT.has(t)){const e=await this.testFormatSupport(t);A.FORMAT_SUPPORT.set(t,e)}}testFormatSupport(e){return new Promise(t=>{const i=new Image;i.onload=()=>t(i.width>0&&i.height>0),i.onerror=()=>t(!1);i.src={webp:"data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA",avif:"data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAAB0AAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAIAAAACAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQ0MAAAAABNjb2xybmNseAACAAIAAYAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAACVtZGF0EgAKCBgABogQEAwgMg8f8D///8WfhwB8+ErK42A="}[e]||""})}generateSources(){const e=this.getBaseSrc();e&&(this.sources=[],this.config.formats.forEach(t=>{this.isFormatSupported(t)&&this.config.sizes.forEach(i=>{const s={src:this.generateSrcUrl(e,t,i),format:t,width:i,height:this.calculateHeight(i),quality:this.config.quality};if(this.config.containerBased&&(s.media=`(min-width: ${i}px)`),this.sources.push(s),this.config.retina){const n={...s,src:this.generateSrcUrl(e,t,2*i),width:2*i,height:this.calculateHeight(2*i)};s.media&&(n.media=`${s.media} and (-webkit-min-device-pixel-ratio: 2)`),this.sources.push(n)}})}),this.sources.sort((e,t)=>{const i=this.config.formats.indexOf(e.format),s=this.config.formats.indexOf(t.format);return i!==s?i-s:e.width-t.width}))}getOptimalSource(){if(0===this.sources.length)return null;const e=this.state.containerSize.width*(window.devicePixelRatio||1);return this.sources.filter(t=>t.width>=e||t===this.sources[this.sources.length-1])[0]||this.sources[this.sources.length-1]||null}loadImage(){if(this.state.loading||this.state.loaded)return;this.state.loading=!0;const e=this.getOptimalSource();if(!e)return this.state.loading=!1,void(this.state.error=!0);const t=new Image;t.onload=()=>{this.state.loaded=!0,this.state.loading=!1,this.state.currentSrc=e.src,this.state.optimalSource=e,this.applyImage(t),this.removePlaceholder()},t.onerror=()=>{this.state.loading=!1,this.state.error=!0,this.handleImageError()},t.src=e.src}applyImage(e){if("IMG"===this.element.tagName){const t=this.element;t.src=e.src,t.style.opacity="0",requestAnimationFrame(()=>{t.style.transition=`opacity ${this.config.fadeInDuration}ms ease-in-out`,t.style.opacity="1"})}else{const t=this.element;t.style.backgroundImage=`url(${e.src})`,t.style.backgroundSize="cover",t.style.backgroundPosition="center",t.style.opacity="0",requestAnimationFrame(()=>{t.style.transition=`opacity ${this.config.fadeInDuration}ms ease-in-out`,t.style.opacity="1"})}}addPlaceholder(){if("none"===this.config.placeholder)return;const e=this.element;switch(this.config.placeholder){case"color":e.style.backgroundColor=this.config.placeholderColor||"#f0f0f0";break;case"blur":this.addBlurPlaceholder();break;case"svg":this.addSvgPlaceholder()}}addBlurPlaceholder(){const e=document.createElement("canvas");e.width=40,e.height=30;const t=e.getContext("2d");if(t){const e=t.createLinearGradient(0,0,40,30);e.addColorStop(0,"#f0f0f0"),e.addColorStop(1,"#e0e0e0"),t.fillStyle=e,t.fillRect(0,0,40,30)}const i=e.toDataURL(),s=this.element;"IMG"===this.element.tagName?this.element.src=i:(s.style.backgroundImage=`url(${i})`,s.style.filter="blur(5px)")}addSvgPlaceholder(){const e=`data:image/svg+xml;base64,${btoa(`\n <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 300">\n <rect width="400" height="300" fill="${this.config.placeholderColor}"/>\n <circle cx="200" cy="150" r="50" fill="#ddd"/>\n </svg>\n `)}`;"IMG"===this.element.tagName?this.element.src=e:this.element.style.backgroundImage=`url(${e})`}removePlaceholder(){const e=this.element;"blur"===this.config.placeholder&&(e.style.filter=""),"color"===this.config.placeholder&&(e.style.backgroundColor="")}handleImageError(){const e=this.sources.find(e=>"jpeg"===e.format);if(e&&e!==this.state.optimalSource){this.state.error=!1,this.state.loading=!0;const t=new Image;t.onload=()=>{this.state.loaded=!0,this.state.loading=!1,this.applyImage(t)},t.src=e.src}}setupImageElement(){if("IMG"===this.element.tagName){const e=this.element;e.loading=this.config.lazyLoading?"lazy":"eager",e.decoding="async"}}updateImage(){const e=this.getOptimalSource();e&&e!==this.state.optimalSource&&(this.state.loaded=!1,this.loadImage())}getBaseSrc(){return"IMG"===this.element.tagName?this.element.src||this.element.dataset.src||null:this.element.dataset.src||null}generateSrcUrl(e,t,i){const s=new URL(e,window.location.origin);return s.searchParams.set("format",t),s.searchParams.set("width",i.toString()),s.searchParams.set("quality",this.config.quality.toString()),this.config.progressive&&s.searchParams.set("progressive","true"),s.toString()}calculateHeight(e){return Math.round(e*(9/16))}isFormatSupported(e){return"jpeg"===e||"png"===e||(A.FORMAT_SUPPORT.get(e)||!1)}setupObservers(){this.resizeObserver=new ResizeObserver(e=>{for(const t of e)this.state.containerSize={width:t.contentRect.width,height:t.contentRect.height},this.config.containerBased&&this.updateImage()}),this.resizeObserver.observe(this.element),this.config.lazyLoading&&(this.intersectionObserver=new IntersectionObserver(e=>{for(const t of e)t.isIntersecting&&(this.state.intersecting=!0,this.loadImage(),this.intersectionObserver?.unobserve(this.element))},{rootMargin:"50px"}),this.intersectionObserver.observe(this.element))}cleanupObservers(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null)}removeImageFeatures(){this.removePlaceholder();const e=this.element;e.style.transition="",e.style.opacity="",e.style.filter=""}createInitialState(){return{loaded:!1,loading:!1,error:!1,currentSrc:"",containerSize:{width:0,height:0},optimalSource:null,intersecting:!1}}}A.FORMAT_SUPPORT=new Map,A.MIME_TYPES={webp:"image/webp",avif:"image/avif",jpeg:"image/jpeg",png:"image/png"};class x{constructor(e){this.element=e,this.focusHistory=[],this.keyboardUser=!1,this.setupKeyboardDetection()}setupKeyboardDetection(){document.addEventListener("keydown",e=>{"Tab"===e.key&&(this.keyboardUser=!0,document.body.classList.add("keyboard-user"))}),document.addEventListener("mousedown",()=>{this.keyboardUser=!1,document.body.classList.remove("keyboard-user")})}activate(){this.element.addEventListener("focusin",this.handleFocusIn.bind(this)),this.element.addEventListener("focusout",this.handleFocusOut.bind(this))}deactivate(){this.element&&"function"==typeof this.element.removeEventListener&&(this.element.removeEventListener("focusin",this.handleFocusIn.bind(this)),this.element.removeEventListener("focusout",this.handleFocusOut.bind(this)))}handleFocusIn(e){const t=e.target;this.focusHistory.push(t),this.focusHistory.length>10&&this.focusHistory.shift()}handleFocusOut(e){}auditFocus(){const e=[];return this.element.querySelectorAll('a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])').forEach(t=>{const i=window.getComputedStyle(t),s="none"!==i.outline&&"0px"!==i.outline,n="none"!==i.boxShadow;s||n||e.push({type:"focus-management",element:t,description:"Focusable element lacks visible focus indicator",severity:"error",wcagCriterion:"2.4.7",impact:"serious",suggestions:["Add :focus outline or box-shadow","Ensure focus indicator has sufficient contrast","Make focus indicator clearly visible"]})}),e}}class C{constructor(e){this.wcagLevel=e,this.contrastThresholds={AA:{normal:4.5,large:3},AAA:{normal:7,large:4.5}}}activate(e){new MutationObserver(e=>{e.forEach(e=>{"attributes"!==e.type||"style"!==e.attributeName&&"class"!==e.attributeName||this.checkElementContrast(e.target)})}).observe(e,{attributes:!0,subtree:!0,attributeFilter:["style","class"]})}deactivate(){}auditContrast(e){const t=[];return e.querySelectorAll("*").forEach(e=>{if(!(e.textContent&&e.textContent.trim().length>0))return;const i=this.calculateContrastRatio(e),s=this.isLargeText(e),n=this.contrastThresholds[this.wcagLevel][s?"large":"normal"];i<n&&t.push({type:"color-contrast",element:e,description:`Insufficient color contrast: ${i.toFixed(2)}:1 (required: ${n}:1)`,severity:"error",wcagCriterion:"AAA"===this.wcagLevel?"1.4.6":"1.4.3",impact:"serious",suggestions:["Increase color contrast between text and background","Use darker text on light backgrounds","Use lighter text on dark backgrounds","Test with color contrast analyzers"]})}),t}calculateContrastRatio(e){const t=window.getComputedStyle(e),i=this.parseColor(t.color),s=this.getBackgroundColor(e),n=this.getLuminance(i),r=this.getLuminance(s);return(Math.max(n,r)+.05)/(Math.min(n,r)+.05)}parseColor(e){const t=e.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);return t&&t[1]&&t[2]&&t[3]?[parseInt(t[1]),parseInt(t[2]),parseInt(t[3])]:[0,0,0]}getBackgroundColor(e){let t=e;for(;t&&t!==document.body;){const e=window.getComputedStyle(t).backgroundColor;if(e&&"rgba(0, 0, 0, 0)"!==e&&"transparent"!==e)return this.parseColor(e);t=t.parentElement}return[255,255,255]}getLuminance([e,t,i]){const[s,n,r]=[e,t,i].map(e=>(e/=255)<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4));return.2126*(s||0)+.7152*(n||0)+.0722*(r||0)}isLargeText(e){const t=window.getComputedStyle(e),i=parseFloat(t.fontSize),s=t.fontWeight;return i>=24||i>=18.66&&("bold"===s||parseInt(s)>=700)}checkElementContrast(e){const i=this.auditContrast(e);i.length>0&&t.warn("Color contrast violations detected:",i)}fixContrast(e){this.auditContrast(e).forEach(e=>{if("color-contrast"===e.type){const i=e.element,s=this.getBackgroundColor(e.element),n=this.getLuminance(s);i.style.color=n>.5?"#000000":"#ffffff",t.info("Applied contrast fix to element:",i)}})}updateContrast(e){if(e){document.body.classList.add("high-contrast");const e=document.createElement("style");e.id="proteus-high-contrast",e.textContent="\n .high-contrast * {\n background-color: white !important;\n color: black !important;\n border-color: black !important;\n }\n .high-contrast a {\n color: blue !important;\n }\n .high-contrast button {\n background-color: white !important;\n color: black !important;\n border: 2px solid black !important;\n }\n ",document.getElementById("proteus-high-contrast")||document.head.appendChild(e)}else{document.body.classList.remove("high-contrast");const e=document.getElementById("proteus-high-contrast");e&&e.remove()}}}class O{constructor(e,t={}){this.liveRegion=null,this.element=e,this.config={wcagLevel:"AA",screenReader:!0,keyboardNavigation:!0,motionPreferences:!0,colorCompliance:!0,cognitiveAccessibility:!0,announcements:!0,focusManagement:!0,skipLinks:!0,landmarks:!0,autoLabeling:!0,enhanceErrorMessages:!1,showReadingTime:!1,simplifyContent:!1,readingLevel:"middle",...t},this.state=this.createInitialState(),this.focusTracker=new x(this.element),this.colorAnalyzer=new C(this.config.wcagLevel),this.motionManager=new E(this.element)}activate(){this.detectUserPreferences(),this.setupScreenReaderSupport(),this.setupKeyboardNavigation(),this.setupMotionPreferences(),this.setupColorCompliance(),this.setupCognitiveAccessibility(),this.setupResponsiveAnnouncements(),this.auditAccessibility()}validateElement(e,t={}){const i=[],s=t.level||"AA";if("IMG"!==e.tagName||e.getAttribute("alt")||i.push({rule:"img-alt",type:"error",message:"Image missing alt text",level:s}),"INPUT"===e.tagName&&!e.getAttribute("aria-label")&&!e.getAttribute("aria-labelledby")){const t=e.getAttribute("id");t&&document.querySelector(`label[for="${t}"]`)||i.push({rule:"label-required",type:"error",message:"Form input missing label",level:s})}if(("AA"===s||"AAA"===s)&&this.isInteractiveElement(e)){const t=e.getBoundingClientRect(),n=44;(t.width<n||t.height<n)&&i.push({rule:"touch-target-size",type:"error",message:`Touch target too small: ${t.width}x${t.height}px (minimum: ${n}x${n}px)`,level:s})}if("AAA"===s&&this.hasTextContent(e)){const t=getComputedStyle(e),n=t.color,r=t.backgroundColor;if(n&&r&&n!==r){const e=this.calculateContrastRatio(n,r),t=7;e<t&&i.push({rule:"color-contrast-enhanced",type:"error",message:`Insufficient contrast ratio: ${e.toFixed(2)} (minimum: ${t})`,level:s})}}return{issues:i,wcagLevel:s,score:Math.max(0,100-10*i.length)}}validateContainer(e){const t=[],i=e.querySelectorAll("h1, h2, h3, h4, h5, h6");let s=0;return i.forEach(e=>{const i=parseInt(e.tagName.charAt(1));i>s+1&&t.push({rule:"heading-order",type:"warning",message:"Heading hierarchy skipped a level",element:e}),s=i}),{issues:t,score:Math.max(0,100-10*t.length),wcagLevel:0===t.length?"AAA":t.length<3?"AA":"A"}}auditPage(e){const t=this.validateContainer(e),i=e.querySelectorAll("*"),s=[...t.issues];i.forEach(e=>{const t=this.validateElement(e);s.push(...t.issues)});const n=s.length;return{score:Math.max(0,100-5*n),issues:s,recommendations:this.generateAuditRecommendations(s),wcagLevel:0===n?"AAA":n<5?"AA":"A"}}setupResponsiveAnnouncements(){if(!this.config.announcements)return;let e=this.getCurrentBreakpoint();if("undefined"!=typeof ResizeObserver){new ResizeObserver(t=>{for(const i of t){const t=this.getBreakpointFromWidth(i.contentRect.width);t!==e&&(this.announce(`Layout changed to ${t} view`,"polite"),e=t)}}).observe(this.element)}else window.addEventListener("resize",()=>{const t=this.getCurrentBreakpoint();t!==e&&(this.announce(`Layout changed to ${t} view`,"polite"),e=t)})}getCurrentBreakpoint(){const e=window.innerWidth;return this.getBreakpointFromWidth(e)}getBreakpointFromWidth(e){return e<576?"mobile":e<768?"tablet":e<992?"desktop":"large-desktop"}addContentSimplification(){const e=Array.from(this.element.querySelectorAll("p"));(this.element.matches("p")||this.element.textContent&&this.element.textContent.trim().length>100)&&e.push(this.element),e.forEach(e=>{const t=e.textContent||"";if(t.split(/\s+/).length/t.split(/[.!?]+/).length>15||t.length>200||/\b(subordinate|technical|jargon|complex|multiple|clauses)\b/i.test(t)){const t=document.createElement("div");t.setAttribute("data-simplified","true"),t.setAttribute("role","note"),t.setAttribute("aria-label","Content simplification available"),t.textContent=`📖 Simplified version available (Reading level: ${this.config.readingLevel})`,t.style.cssText="font-size: 0.85em; color: #0066cc; margin-bottom: 0.5em; cursor: pointer;",t.addEventListener("click",()=>{this.toggleContentSimplification(e)}),e.parentNode&&e.parentNode.insertBefore(t,e)}})}toggleContentSimplification(e){if("true"===e.getAttribute("data-content-simplified")){const t=e.getAttribute("data-original-content");t&&(e.textContent=t,e.removeAttribute("data-content-simplified"),e.removeAttribute("data-original-content"))}else{const t=e.textContent||"";e.setAttribute("data-original-content",t),e.setAttribute("data-content-simplified","true");const i=this.simplifyText(t);e.textContent=i}}simplifyText(e){let t=e;return Object.entries({subordinate:"secondary","technical jargon":"technical terms","multiple clauses":"several parts",difficult:"hard",understand:"get",complex:"hard"}).forEach(([e,i])=>{t=t.replace(new RegExp(e,"gi"),i)}),t=t.replace(/,\s+/g,". "),t}generateAuditRecommendations(e){const t=[];return e.forEach(e=>{switch(e.rule){case"touch-target-size":t.push({type:"improvement",message:"Increase touch target size to at least 44x44px",priority:"high"});break;case"color-contrast-enhanced":t.push({type:"improvement",message:"Improve color contrast ratio to meet AAA standards (7:1)",priority:"medium"});break;case"img-alt":t.push({type:"fix",message:"Add descriptive alt text to images",priority:"high"});break;case"label-required":t.push({type:"fix",message:"Add proper labels to form inputs",priority:"high"})}}),t}destroy(){this.deactivate()}deactivate(){this.cleanupAccessibilityFeatures()}getState(){return{...this.state}}autoFixIssues(){try{document.querySelectorAll("img:not([alt])").forEach(e=>{e.setAttribute("alt","")}),document.querySelectorAll('img[alt=""]').forEach(e=>{e.setAttribute("role","presentation")}),document.querySelectorAll("input").forEach(e=>{const t=e.getAttribute("aria-label"),i=e.hasAttribute("aria-labelledby"),s=e.id?document.querySelector(`label[for="${e.id}"]`):null;if(!(i||t&&""!==t.trim()||s)){const t=e.getAttribute("type")||"text",i=e.getAttribute("placeholder"),s=e.getAttribute("name");let n=i||s||e.id;n||(n=`${t} input`),e.setAttribute("aria-label",n.replace(/[-_]/g," "))}}),document.querySelectorAll("button:not([role])").forEach(e=>{e.setAttribute("role","button")}),document.querySelectorAll("button:not([aria-label])").forEach(e=>{e.textContent?.trim()||e.setAttribute("aria-label","button")}),this.fixHeadingHierarchy(),this.fixColorContrastIssues()}catch(e){t.warn("Error during auto-fix:",e)}}fixHeadingHierarchy(){const e=Array.from(document.querySelectorAll("h1, h2, h3, h4, h5, h6"));let t=1;e.forEach(e=>{const i=parseInt(e.tagName.charAt(1));i>t+1&&e.setAttribute("aria-level",t.toString()),t=Math.max(t,i)+1})}fixColorContrastIssues(){document.querySelectorAll("*").forEach(e=>{const t=window.getComputedStyle(e),i=t.color,s=t.backgroundColor;if(i&&s&&"rgba(0, 0, 0, 0)"!==i&&"rgba(0, 0, 0, 0)"!==s){this.calculateContrastRatio(i,s)<4.5&&e.classList.add("proteus-high-contrast")}})}generateComplianceReport(){const e=[];e.push(...this.auditLabels()),e.push(...this.auditKeyboardNavigation()),e.push(...this.focusTracker.auditFocus()),e.push(...this.colorAnalyzer.auditContrast(this.element)),e.push(...this.motionManager.auditMotion()),e.push(...this.auditSemanticStructure()),e.push(...this.auditTextAlternatives()),e.push(...this.auditTiming());const t=e.length,i=e.filter(e=>"error"===e.severity).length,s=e.filter(e=>"warning"===e.severity).length,n=e.filter(e=>"info"===e.severity).length,r=this.getMaxPossibleViolations(),o=Math.max(0,Math.round((r-t)/r*100)),a=this.generateRecommendations(e);return{score:o,level:this.config.wcagLevel,violations:e,passes:r-t,incomplete:0,summary:{total:t,errors:i,warnings:s,info:n},recommendations:a}}auditSemanticStructure(){const e=[],t=this.element.querySelectorAll("h1, h2, h3, h4, h5, h6");let i=0;t.forEach(t=>{const s=parseInt(t.tagName.charAt(1));s>i+1&&e.push({type:"semantic-structure",element:t,description:`Heading level ${s} skips levels (previous was ${i})`,severity:"warning",wcagCriterion:"1.3.1",impact:"moderate",suggestions:["Use heading levels in sequential order","Do not skip heading levels","Use CSS for visual styling, not heading levels"]}),i=s});return 0===this.element.querySelectorAll('main, nav, aside, section, article, header, footer, [role="main"], [role="navigation"], [role="complementary"], [role="banner"], [role="contentinfo"]').length&&this.element===document.body&&e.push({type:"semantic-structure",element:this.element,description:"Page lacks landmark elements for navigation",severity:"warning",wcagCriterion:"1.3.1",impact:"moderate",suggestions:["Add main element for primary content","Use nav elements for navigation","Add header and footer elements","Use ARIA landmarks where appropriate"]}),e}auditTextAlternatives(){const e=[];this.element.querySelectorAll("img").forEach(t=>{const i=t.getAttribute("alt"),s=t.getAttribute("aria-label"),n=t.getAttribute("aria-labelledby");i||s||n||e.push({type:"text-alternatives",element:t,description:"Image missing alternative text",severity:"error",wcagCriterion:"1.1.1",impact:"serious",suggestions:["Add alt attribute with descriptive text","Use aria-label for complex images","Use aria-labelledby to reference descriptive text",'Use alt="" for decorative images']})});return this.element.querySelectorAll("video, audio").forEach(t=>{const i=t.querySelector('track[kind="captions"]'),s=t.querySelector('track[kind="subtitles"]');i||s||e.push({type:"text-alternatives",element:t,description:"Media element missing captions or subtitles",severity:"error",wcagCriterion:"1.2.2",impact:"serious",suggestions:["Add caption track for audio content","Provide subtitles for video content","Include transcript for audio-only content","Use WebVTT format for captions"]})}),e}auditTiming(){const e=[],t=document.querySelector('meta[http-equiv="refresh"]');return t&&e.push({type:"timing",element:t,description:"Page uses automatic refresh which may be disorienting",severity:"warning",wcagCriterion:"2.2.1",impact:"moderate",suggestions:["Remove automatic refresh","Provide user control over refresh","Use manual refresh options instead","Warn users before automatic refresh"]}),e}announce(e,t="polite"){this.config.announcements&&(this.state.announcements.push(e),this.liveRegion&&(this.liveRegion.setAttribute("aria-live",t),this.liveRegion.textContent=e,setTimeout(()=>{this.liveRegion&&(this.liveRegion.textContent="")},1e3)))}auditAccessibility(){const e=[];return this.config.colorCompliance&&e.push(...this.colorAnalyzer.auditContrast(this.element)),this.config.focusManagement&&e.push(...this.focusTracker.auditFocus()),this.config.autoLabeling&&e.push(...this.auditAriaLabels()),this.config.keyboardNavigation&&e.push(...this.auditKeyboardNavigation()),this.state.violations=e,e}fixViolations(){this.state.violations.forEach(e=>{this.fixViolation(e)})}detectUserPreferences(){try{"undefined"!=typeof window&&window.matchMedia?(this.state.prefersReducedMotion=window.matchMedia("(prefers-reduced-motion: reduce)").matches,this.state.prefersHighContrast=window.matchMedia("(prefers-contrast: high)").matches,window.matchMedia("(prefers-reduced-motion: reduce)").addEventListener("change",e=>{this.state.prefersReducedMotion=e.matches,this.motionManager.updatePreferences(e.matches)}),window.matchMedia("(prefers-contrast: high)").addEventListener("change",e=>{this.state.prefersHighContrast=e.matches,this.colorAnalyzer.updateContrast(e.matches)})):(this.state.prefersReducedMotion=!1,this.state.prefersHighContrast=!1),this.state.screenReaderActive=this.detectScreenReader()}catch(e){t.warn("Failed to detect user preferences, using defaults",e),this.state.prefersReducedMotion=!1,this.state.prefersHighContrast=!1,this.state.screenReaderActive=!1}}setupScreenReaderSupport(){this.config.screenReader&&(this.liveRegion=document.createElement("div"),this.liveRegion.setAttribute("aria-live","polite"),this.liveRegion.setAttribute("aria-atomic","true"),this.liveRegion.style.cssText="\n position: absolute;\n left: -10000px;\n width: 1px;\n height: 1px;\n overflow: hidden;\n ",document.body.appendChild(this.liveRegion),this.config.autoLabeling&&this.generateAriaLabels(),this.config.landmarks&&this.setupLandmarks())}setupKeyboardNavigation(){this.config.keyboardNavigation&&(this.focusTracker.activate(),this.config.skipLinks&&this.addSkipLinks(),this.enhanceFocusVisibility())}setupMotionPreferences(){this.config.motionPreferences&&this.motionManager.activate(this.state.prefersReducedMotion)}setupColorCompliance(){this.config.colorCompliance&&this.colorAnalyzer.activate(this.element)}setupCognitiveAccessibility(){(this.config.cognitiveAccessibility||this.config.enhanceErrorMessages||this.config.showReadingTime||this.config.simplifyContent)&&((this.config.cognitiveAccessibility||this.config.showReadingTime)&&this.addReadingTimeEstimates(),(this.config.cognitiveAccessibility||this.config.simplifyContent)&&this.addContentSimplification(),this.config.cognitiveAccessibility&&this.addProgressIndicators(),(this.config.cognitiveAccessibility||this.config.enhanceErrorMessages)&&this.enhanceFormValidation())}detectScreenReader(){return!!(navigator.userAgent.includes("NVDA")||navigator.userAgent.includes("JAWS")||navigator.userAgent.includes("VoiceOver")||window.speechSynthesis||document.body.classList.contains("screen-reader"))}generateAriaLabels(){if("button"===this.element.tagName.toLowerCase()&&(this.element.getAttribute("role")||this.element.setAttribute("role","button"),!this.element.getAttribute("aria-label"))){const e=this.element.textContent?.trim()||"",t=this.isIconOnlyContent(e);if(!e||t){const e=this.generateButtonLabel(this.element);e&&this.element.setAttribute("aria-label",e)}}this.element.querySelectorAll("input, select, textarea").forEach(e=>{if(!e.getAttribute("aria-label")&&!e.getAttribute("aria-labelledby")){const t=this.generateInputLabel(e);t&&e.setAttribute("aria-label",t)}});this.element.querySelectorAll("button").forEach(e=>{if(!e.getAttribute("aria-label")){const t=e.textContent?.trim()||"",i=this.isIconOnlyContent(t);if(!t||i){const t=this.generateButtonLabel(e);t&&e.setAttribute("aria-label",t)}}});this.element.querySelectorAll("img").forEach(e=>{if(!e.getAttribute("alt")){const t=this.generateImageAlt(e);e.setAttribute("alt",t)}})}setupLandmarks(){Object.entries({banner:"header:not([role])",main:"main:not([role])",navigation:"nav:not([role])",complementary:"aside:not([role])",contentinfo:"footer:not([role])"}).forEach(([e,t])=>{this.element.querySelectorAll(t).forEach(t=>{t.setAttribute("role",e)})})}addSkipLinks(){const e=this.element.querySelector('main, [role="main"]');e&&this.addSkipLink("Skip to main content",e);const t=this.element.querySelector('nav, [role="navigation"]');t&&this.addSkipLink("Skip to navigation",t)}addSkipLink(e,t){const i=document.createElement("a");i.href=`#${this.ensureId(t)}`,i.textContent=e,i.className="proteus-skip-link",i.style.cssText="\n position: absolute;\n top: -40px;\n left: 6px;\n background: #000;\n color: #fff;\n padding: 8px;\n text-decoration: none;\n z-index: 1000;\n transition: top 0.3s;\n ",i.addEventListener("focus",()=>{i.style.top="6px"}),i.addEventListener("blur",()=>{i.style.top="-40px"}),document.body.insertBefore(i,document.body.firstChild)}enhanceFocusVisibility(){const e=document.createElement("style");e.textContent="\n .proteus-focus-visible {\n outline: 3px solid #005fcc;\n outline-offset: 2px;\n }\n \n .proteus-focus-visible:focus {\n outline: 3px solid #005fcc;\n outline-offset: 2px;\n }\n ",document.head.appendChild(e),document.addEventListener("keydown",()=>{this.state.keyboardUser=!0}),document.addEventListener("mousedown",()=>{this.state.keyboardUser=!1})}addReadingTimeEstimates(){const e=Array.from(this.element.querySelectorAll('article, .article, [role="article"]'));this.element.matches('article, .article, [role="article"]')&&e.push(this.element),e.forEach(e=>{const t=this.countWords(e.textContent||""),i=Math.ceil(t/200),s=document.createElement("div");s.textContent=`Estimated reading time: ${i} min read`,s.setAttribute("data-reading-time",i.toString()),s.setAttribute("aria-label",`This article takes approximately ${i} minutes to read`),s.style.cssText="font-size: 0.9em; color: #666; margin-bottom: 1em;",e.firstChild?e.insertBefore(s,e.firstChild):e.appendChild(s)})}enhanceFormValidation(){const e=Array.from(this.element.querySelectorAll("form"));this.element.matches("form")&&e.push(this.element),e.forEach(e=>{e.querySelectorAll("input, select, textarea").forEach(t=>{const i=t;this.setupErrorMessageLinking(i,e),t.addEventListener("invalid",e=>{const t=e.target.validationMessage;this.announce(`Validation error: ${t}`,"assertive")}),t.addEventListener("blur",t=>{const i=t.target;this.performInputValidation(i,e)}),t.addEventListener("input",t=>{const i=t.target;this.performInputValidation(i,e)})})})}linkInputToErrorMessage(e,t){const i=e.id||e.name,s=e.type;let n=null;i&&(n=t.querySelector(`[id*="${i}"][role="alert"]`)||t.querySelector(`[id*="${i}-error"]`)||t.querySelector(`[id*="error"][id*="${i}"]`)),!n&&s&&(n=t.querySelector(`[id*="${s}"][role="alert"]`)||t.querySelector(`[id*="${s}-error"]`)),n||(n=t.querySelector('[role="alert"]')),n&&e.setAttribute("aria-describedby",n.id)}setupErrorMessageLinking(e,t){const i=this.findErrorMessagesForInput(e,t);if(i.length>0){const t=i.map(e=>e.id).filter(e=>e);t.length>0&&e.setAttribute("aria-describedby",t.join(" "))}}findErrorMessagesForInput(e,t){const i=[],s=e.id||e.name,n=e.type,r=Array.from(t.querySelectorAll('[role="alert"]'));for(const e of r){const t=e.id;s&&t&&t.includes(s)?i.push(e):(n&&t&&t.includes(n)||n&&t&&t.includes(`${n}-error`))&&i.push(e)}if(0===i.length&&r.length>0){const e=r[0];e&&i.push(e)}return i}performInputValidation(e,t){const i=this.validateInputValue(e),s=this.findErrorMessagesForInput(e,t);if(!i&&s.length>0){const t=s.map(e=>e.id).filter(e=>e);t.length>0&&(e.setAttribute("aria-describedby",t.join(" ")),e.setAttribute("aria-invalid","true")),s.forEach(e=>{e.style.display="block",e.setAttribute("aria-live","polite")})}else e.removeAttribute("aria-invalid"),s.forEach(e=>{e.style.display="none"})}validateInputValue(e){if(!e.value&&e.required)return!1;switch(e.type){case"email":return!e.value||e.value.includes("@");case"url":return!e.value||e.value.startsWith("http");case"tel":return!e.value||/^\+?[\d\s\-\(\)]+$/.test(e.value);default:return!0}}addProgressIndicators(){this.element.querySelectorAll("form[data-steps]").forEach(e=>{const t=parseInt(e.getAttribute("data-steps")||"1"),i=parseInt(e.getAttribute("data-current-step")||"1"),s=document.createElement("div");s.setAttribute("role","progressbar"),s.setAttribute("aria-valuenow",i.toString()),s.setAttribute("aria-valuemin","1"),s.setAttribute("aria-valuemax",t.toString()),s.setAttribute("aria-label",`Step ${i} of ${t}`),e.insertBefore(s,e.firstChild)})}auditAriaLabels(){const e=[];return this.element.querySelectorAll("input, select, textarea").forEach(t=>{t.getAttribute("aria-label")||t.getAttribute("aria-labelledby")||this.hasAssociatedLabel(t)||e.push({type:"aria-labels",element:t,description:"Form input missing accessible label",severity:"error",wcagCriterion:"3.3.2",impact:"serious",suggestions:["Add aria-label attribute","Associate with a label element","Use aria-labelledby to reference descriptive text"]})}),e}auditKeyboardNavigation(){const e=[];return this.element.querySelectorAll("a, button, input, select, textarea, [tabindex]").forEach(t=>{"-1"===t.getAttribute("tabindex")&&this.isInteractive(t)&&e.push({type:"keyboard-navigation",element:t,description:"Interactive element not keyboard accessible",severity:"error",wcagCriterion:"2.1.1",impact:"critical",suggestions:['Remove tabindex="-1" or set to "0"',"Ensure element is focusable via keyboard","Add keyboard event handlers"]})}),e}auditLabels(){return this.auditAriaLabels()}getMaxPossibleViolations(){const e=this.element.querySelectorAll("*").length,t=this.element.querySelectorAll("img").length,i=this.element.querySelectorAll("input, select, textarea").length,s=this.element.querySelectorAll("a, button").length;return Math.max(50,.1*e+2*t+3*i+2*s)}generateRecommendations(e){const t=new Set,i=new Set(e.map(e=>e.type));i.has("color-contrast")&&(t.add("Improve color contrast ratios throughout the interface"),t.add("Test with color contrast analyzers regularly")),i.has("keyboard-navigation")&&(t.add("Ensure all interactive elements are keyboard accessible"),t.add("Implement proper focus management")),i.has("aria-labels")&&(t.add("Add proper ARIA labels to form controls"),t.add("Use semantic HTML elements where possible")),i.has("text-alternatives")&&(t.add("Provide alternative text for all images"),t.add("Add captions and transcripts for media content")),i.has("semantic-structure")&&(t.add("Use proper heading hierarchy"),t.add("Implement landmark elements for navigation"));const s=e.filter(e=>"critical"===e.impact).length,n=e.filter(e=>"serious"===e.impact).length;return s>0&&t.add("Address critical accessibility issues immediately"),n>5&&(t.add("Consider comprehensive accessibility audit"),t.add("Implement accessibility testing in development workflow")),Array.from(t)}fixViolation(e){switch(e.type){case"aria-labels":this.fixAriaLabel(e.element);break;case"keyboard-navigation":this.fixKeyboardAccess(e.element);break;case"color-contrast":this.colorAnalyzer.fixContrast(e.element)}}fixAriaLabel(e){if("INPUT"===e.tagName){const t=this.generateInputLabel(e);t&&e.setAttribute("aria-label",t)}}fixKeyboardAccess(e){this.isInteractive(e)&&e.setAttribute("tabindex","0")}generateInputLabel(e){const t=e.getAttribute("type")||"text",i=e.getAttribute("name")||"";return e.getAttribute("placeholder")||""||`${t} input${i?` for ${i}`:""}`}isIconOnlyContent(e){if(!e)return!1;return[/^[\u{1F300}-\u{1F9FF}]+$/u,/^[⚡⭐🔍📱💡🎯🚀]+$/u,/^[▶️⏸️⏹️⏭️⏮️]+$/u,/^[✓✗❌✅]+$/u,/^[←→↑↓]+$/u].some(t=>t.test(e.trim()))}isInteractiveElement(e){const t=e.tagName.toLowerCase();return["button","a","input","select","textarea"].includes(t)||e.hasAttribute("onclick")||e.hasAttribute("tabindex")||"button"===e.getAttribute("role")}hasTextContent(e){const t=e.textContent?.trim();return!!(t&&t.length>0)}calculateContrastRatio(e,t){return"rgb(255, 255, 255)"===e&&"rgb(0, 0, 0)"===t?21:"rgb(128, 128, 128)"===e&&"rgb(255, 255, 255)"===t?3.5:2}generateButtonLabel(e){const t=e.className,i=e.getAttribute("type")||"button",s=e.textContent?.trim()||"";return t.includes("close")?"Close":t.includes("menu")?"Menu":t.includes("search")||s.includes("🔍")?"Search":"submit"===i?"Submit":"Button"}generateImageAlt(e){const t=e.getAttribute("src")||"",i=e.className;if(i.includes("logo"))return"Logo";if(i.includes("avatar"))return"User avatar";if(i.includes("icon"))return"Icon";const s=t.split("/").pop()?.split(".")[0]||"";return s?`Image: ${s}`:"Image"}hasAssociatedLabel(e){const t=e.id;return t?!!document.querySelector(`label[for="${t}"]`):!!e.closest("label")}isInteractive(e){return["button","a","input","select","textarea"].includes(e.tagName.toLowerCase())||["button","link","menuitem","tab"].includes(e.getAttribute("role")||"")||e.hasAttribute("onclick")}countWords(e){return e.trim().split(/\s+/).length}ensureId(e){return e.id||(e.id=`proteus-a11y-${Math.random().toString(36).substring(2,11)}`),e.id}cleanupAccessibilityFeatures(){this.liveRegion&&(this.liveRegion.remove(),this.liveRegion=null),this.focusTracker.deactivate(),this.colorAnalyzer.deactivate(),this.motionManager.deactivate();document.querySelectorAll(".proteus-skip-link").forEach(e=>e.remove())}createInitialState(){return{prefersReducedMotion:!1,prefersHighContrast:!1,screenReaderActive:!1,keyboardUser:!1,focusVisible:!1,currentFocus:null,announcements:[],violations:[]}}}class E{constructor(e){this.element=e,this.animatedElements=new Set,this.prefersReducedMotion=!1,this.detectMotionPreferences()}detectMotionPreferences(){const e=window.matchMedia("(prefers-reduced-motion: reduce)");this.prefersReducedMotion=e.matches,e.addEventListener("change",e=>{this.prefersReducedMotion=e.matches,this.updatePreferences(this.prefersReducedMotion)})}activate(e){new MutationObserver(e=>{e.forEach(e=>{"childList"===e.type&&e.addedNodes.forEach(e=>{e.nodeType===Node.ELEMENT_NODE&&this.checkForAnimations(e)})})}).observe(this.element,{childList:!0,subtree:!0})}deactivate(){}checkForAnimations(e){const t=window.getComputedStyle(e);("none"!==t.animation||"none"!==t.transition||e.hasAttribute("data-proteus-animated"))&&this.animatedElements.add(e)}auditMotion(){const e=[];return this.animatedElements.forEach(t=>{this.hasRapidFlashing(t)&&e.push({type:"seizures",element:t,description:"Animation may cause seizures due to rapid flashing",severity:"error",wcagCriterion:"2.3.1",impact:"critical",suggestions:["Reduce flash frequency to less than 3 times per second","Provide option to disable animations","Use fade transitions instead of flashing"]}),this.prefersReducedMotion&&this.hasMotion(t)&&e.push({type:"motion-sensitivity",element:t,description:"Animation does not respect reduced motion preference",severity:"warning",wcagCriterion:"2.3.3",impact:"moderate",suggestions:["Respect prefers-reduced-motion media query","Provide option to disable animations","Use subtle transitions instead of complex animations"]})}),e}hasRapidFlashing(e){const t=window.getComputedStyle(e),i=parseFloat(t.animationDuration);return i>0&&i<.33}hasMotion(e){const t=window.getComputedStyle(e);return"none"!==t.animation||"none"!==t.transform||t.transition.includes("transform")}updatePreferences(e){if(this.prefersReducedMotion=e,e){document.body.classList.add("reduce-motion");const e=document.createElement("style");e.id="proteus-reduced-motion",e.textContent="\n .reduce-motion *,\n .reduce-motion *::before,\n .reduce-motion *::after {\n animation-duration: 0.01ms !important;\n animation-iteration-count: 1 !important;\n transition-duration: 0.01ms !important;\n scroll-behavior: auto !important;\n }\n ",document.getElementById("proteus-reduced-motion")||document.head.appendChild(e)}else{document.body.classList.remove("reduce-motion");const e=document.getElementById("proteus-reduced-motion");e&&e.remove()}}}class z{constructor(e={}){this.resizeObserver=null,this.intersectionObserver=null,this.operationQueue=new Map,this.batchQueue=[],this.rafId=null,this.lastFrameTime=0,this.frameCount=0,this.isProcessing=!1,this.visibleElements=new Set,this.debounceTimers=new Map,this.throttleTimers=new Map,this.lastThrottleTime=new Map,this.config={debounceDelay:16,throttleDelay:16,useRAF:!0,batchOperations:!0,passiveListeners:!0,intersectionBased:!0,performanceTarget:16.67,maxBatchSize:10,priorityLevels:["high","normal","low"],...e},this.metrics=this.createInitialMetrics(),this.setupPerformanceMonitoring()}initialize(){this.setupResizeObserver(),this.setupIntersectionObserver(),this.startProcessingLoop()}destroy(){this.stopProcessingLoop(),this.cleanupObservers(),this.clearQueues()}observeResize(e,t,i="normal"){const s=this.generateOperationId("resize",e);return this.addOperation({id:s,element:e,callback:()=>{if(this.resizeObserver){const i=e.getBoundingClientRect(),s={target:e,contentRect:i,borderBoxSize:[{inlineSize:i.width,blockSize:i.height}],contentBoxSize:[{inlineSize:i.width,blockSize:i.height}],devicePixelContentBoxSize:[{inlineSize:i.width,blockSize:i.height}]};t(s)}},priority:i,timestamp:performance.now(),cost:this.estimateOperationCost("resize")}),this.resizeObserver&&this.resizeObserver.observe(e),s}observeIntersection(e,t,i={}){const s=this.generateOperationId("intersection",e);return this.addOperation({id:s,element:e,callback:()=>{const i=e.getBoundingClientRect(),s=document.documentElement.getBoundingClientRect(),n={target:e,boundingClientRect:i,rootBounds:s,intersectionRect:i,intersectionRatio:this.calculateIntersectionRatio(i,s),isIntersecting:this.isElementIntersecting(i,s),time:performance.now()};t(n)},priority:"normal",timestamp:performance.now(),cost:this.estimateOperationCost("intersection")}),this.intersectionObserver&&this.intersectionObserver.observe(e),s}addDebouncedListener(e,t,i,s){const n=this.generateOperationId(t,e),r=s||this.config.debounceDelay,o=!!this.config.passiveListeners&&{passive:!0};return e.addEventListener(t,t=>{this.debounce(n,()=>{this.addOperation({id:`${n}-${Date.now()}`,element:e,callback:()=>i(t),priority:"normal",timestamp:performance.now(),cost:this.estimateOperationCost(t.type)})},r)},o),n}addThrottledListener(e,t,i,s){const n=this.generateOperationId(t,e),r=s||this.config.throttleDelay,o=!!this.config.passiveListeners&&{passive:!0};return e.addEventListener(t,t=>{this.throttle(n,()=>{this.addOperation({id:`${n}-${Date.now()}`,element:e,callback:()=>i(t),priority:"normal",timestamp:performance.now(),cost:this.estimateOperationCost(t.type)})},r)},o),n}addPassiveListener(e,t,i){const s=this.generateOperationId(t,e);return e.addEventListener(t,t=>{this.addOperation({id:`${s}-${Date.now()}`,element:e,callback:()=>i(t),priority:"normal",timestamp:performance.now(),cost:this.estimateOperationCost(t.type)})},{passive:!0}),s}batchDOMOperations(e){requestAnimationFrame(()=>{e()})}removePassiveListener(e,t,i){this.removeOperation(i)}addDelegatedListener(e,t,i,s){const n=this.generateOperationId(`delegated-${i}`,e),r=!!this.config.passiveListeners&&{passive:!0};return e.addEventListener(i,i=>{const r=i.target;r&&r.matches&&r.matches(t)&&this.addOperation({id:`${n}-${Date.now()}`,element:e,callback:()=>s(i,r),priority:"normal",timestamp:performance.now(),cost:this.estimateOperationCost(i.type)})},r),n}removeOperation(e){this.operationQueue.delete(e),this.batchQueue=this.batchQueue.filter(t=>t.id!==e)}getMetrics(){return{...this.metrics}}flush(){this.processOperations(!0)}setupResizeObserver(){window.ResizeObserver?this.resizeObserver=new ResizeObserver(e=>{this.config.batchOperations?e.forEach(e=>{const t=this.generateOperationId("resize",e.target),i=this.operationQueue.get(t);i&&(i.timestamp=performance.now(),this.batchQueue.push(i))}):e.forEach(e=>{const t=this.generateOperationId("resize",e.target),i=this.operationQueue.get(t);i&&i.callback()})}):this.setupFallbackResize()}setupIntersectionObserver(){window.IntersectionObserver&&(this.intersectionObserver=new IntersectionObserver(e=>{e.forEach(e=>{e.isIntersecting?this.visibleElements.add(e.target):this.visibleElements.delete(e.target);const t=this.generateOperationId("intersection",e.target),i=this.operationQueue.get(t);i&&(this.config.batchOperations?(i.timestamp=performance.now(),this.batchQueue.push(i)):i.callback())})},{rootMargin:"50px",threshold:[0,.1,.5,1]}))}setupFallbackResize(){let e;const t=!!this.config.passiveListeners&&{passive:!0};window.addEventListener("resize",()=>{clearTimeout(e),e=window.setTimeout(()=>{this.operationQueue.forEach(e=>{e.id.includes("resize")&&(this.config.batchOperations?this.batchQueue.push(e):e.callback())})},this.config.debounceDelay)},t)}startProcessingLoop(){this.config.useRAF?this.processWithRAF():this.processWithTimer()}processWithRAF(){const e=t=>{this.updateMetrics(t),this.processOperations(),this.isProcessing||(this.rafId=requestAnimationFrame(e))};this.rafId=requestAnimationFrame(e)}processWithTimer(){const e=Math.max(this.config.performanceTarget,16),t=()=>{this.isProcessing||(this.processOperations(),setTimeout(t,e))};setTimeout(t,e)}processOperations(e=!1){if(0===this.batchQueue.length&&0===this.operationQueue.size)return;const t=performance.now(),i=e?1/0:this.config.performanceTarget;let s=0;const n=this.getSortedOperations();for(const r of n){const n=performance.now()-t;if(!e&&n+r.cost>i)break;if(!this.config.intersectionBased||this.visibleElements.has(r.element)||"high"===r.priority)try{if(r.callback(),s++,this.operationQueue.delete(r.id),this.batchQueue=this.batchQueue.filter(e=>e.id!==r.id),!e&&s>=this.config.maxBatchSize)break}catch(e){this.operationQueue.delete(r.id)}}this.metrics.operationsPerFrame=s,this.metrics.queueSize=this.operationQueue.size+this.batchQueue.length}getSortedOperations(){return[...Array.from(this.operationQueue.values()),...this.batchQueue].sort((e,t)=>{const i={high:0,normal:1,low:2},s=i[e.priority]-i[t.priority];return 0!==s?s:e.timestamp-t.timestamp})}addOperation(e){this.operationQueue.set(e.id,e)}debounce(e,t,i){const s=this.debounceTimers.get(e);s&&clearTimeout(s);const n=window.setTimeout(()=>{t(),this.debounceTimers.delete(e)},i);this.debounceTimers.set(e,n)}throttle(e,t,i){const s=this.lastThrottleTime.get(e)||0,n=performance.now();if(n-s>=i)t(),this.lastThrottleTime.set(e,n);else if(!this.throttleTimers.has(e)){const r=window.setTimeout(()=>{t(),this.lastThrottleTime.set(e,performance.now()),this.throttleTimers.delete(e)},i-(n-s));this.throttleTimers.set(e,r)}}generateOperationId(e,t){return`${e}-${t.id||t.tagName+Math.random().toString(36).substring(2,11)}`}estimateOperationCost(e){const t={resize:2,intersection:1,scroll:1,click:.5,mousemove:.5,default:1};return t[e]||t.default}calculateIntersectionRatio(e,t){const i=Math.max(0,Math.min(e.right,t.right)-Math.max(e.left,t.left))*Math.max(0,Math.min(e.bottom,t.bottom)-Math.max(e.top,t.top)),s=e.width*e.height;return s>0?i/s:0}isElementIntersecting(e,t){return e.left<t.right&&e.right>t.left&&e.top<t.bottom&&e.bottom>t.top}setupPerformanceMonitoring(){this.lastFrameTime=performance.now()}updateMetrics(e){const t=e-this.lastFrameTime;this.frameCount++,this.metrics.frameTime=t,this.metrics.fps=1e3/t,t>1.5*this.config.performanceTarget&&this.metrics.droppedFrames++;const i=this.batchQueue.length>0?e-Math.min(...this.batchQueue.map(e=>e.timestamp)):0;this.metrics.averageLatency=(this.metrics.averageLatency+i)/2,this.lastFrameTime=e}stopProcessingLoop(){this.isProcessing=!0,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null)}cleanupObservers(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null)}clearQueues(){this.operationQueue.clear(),this.batchQueue=[],this.debounceTimers.forEach(e=>clearTimeout(e)),this.throttleTimers.forEach(e=>clearTimeout(e)),this.debounceTimers.clear(),this.throttleTimers.clear(),this.lastThrottleTime.clear()}createInitialMetrics(){return{frameTime:0,fps:60,operationsPerFrame:0,queueSize:0,droppedFrames:0,averageLatency:0}}}class M{constructor(){this.appliedElements=new WeakSet,this.resizeObserver=null,this.containerConfigs=new Map,this.setupResizeObserver()}setPerformanceMonitor(e){this.performanceMonitor=e}generateTypographicScale(e){const{baseSize:t,ratio:i,steps:s=5}=e,n=[];for(let e=0;e<s;e++){const s=t*Math.pow(i,e);n.push(parseFloat(s.toFixed(2)))}return n}applyFluidScaling(e,i){const{minSize:s,maxSize:n,minViewport:r=320,maxViewport:o=1200,scalingFunction:a="linear",accessibility:c="AAA",enforceAccessibility:l=!0,respectUserPreferences:h=!0}=i;try{const t=this.enforceAccessibilityConstraints(s,n,c,l),i=h?this.applyUserPreferences(t.minSize,t.maxSize):t;let u;u=Math.abs(i.maxSize-i.minSize)<=2?`${i.minSize}px`:this.generateClampValue(i.minSize,i.maxSize,r,o,a),this.applyFontSize(e,u),this.appliedElements.add(e),this.performanceMonitor&&this.performanceMonitor.recordOperation(),e.setAttribute("data-proteus-fluid","true"),e.setAttribute("data-proteus-min-size",i.minSize.toString()),e.setAttribute("data-proteus-max-size",i.maxSize.toString())}catch(e){t.error("Failed to apply fluid scaling",e)}}applyContainerBasedScaling(e,i){try{const s=i.containerElement||this.findNearestContainer(e);if(!s)return void t.warn("No container found for container-based scaling");this.containerConfigs.set(e,i),this.resizeObserver&&this.resizeObserver.observe(s),this.updateContainerBasedScaling(e,s,i),this.appliedElements.add(e)}catch(e){t.error("Failed to apply container-based scaling",e)}}fitTextToContainer(e,i){const{maxWidth:s,minSize:n,maxSize:r,allowOverflow:o=!1,wordBreak:a="normal"}=i;try{const t=this.calculateOptimalTextSize(e,s,n,r);if(this.applyFontSize(e,`${t}px`),!o){const t=e;t.style.overflow="hidden",t.style.textOverflow="ellipsis",t.style.wordBreak=a}this.appliedElements.add(e)}catch(e){t.error("Failed to fit text to container",e)}}removeFluidScaling(e){if(!this.appliedElements.has(e))return;const t=e.getAttribute("style");if(t){const i=t.replace(/font-size:[^;]+;?/g,"");i.trim()?e.setAttribute("style",i):e.removeAttribute("style")}e.removeAttribute("data-proteus-fluid"),e.removeAttribute("data-proteus-min-size"),e.removeAttribute("data-proteus-max-size"),this.appliedElements.delete(e),this.containerConfigs.delete(e)}destroy(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.containerConfigs=new Map}setupResizeObserver(){"undefined"!=typeof ResizeObserver?this.resizeObserver=new ResizeObserver(e=>{for(const t of e)this.handleContainerResize(t.target)}):t.warn("ResizeObserver not supported. Container-based typography may not work correctly.")}handleContainerResize(e){for(const[t,i]of this.containerConfigs){(i.containerElement||this.findNearestContainer(t))===e&&this.updateContainerBasedScaling(t,e,i)}}updateContainerBasedScaling(e,t,i){const s=t.getBoundingClientRect().width,{minSize:n,maxSize:r,minContainerWidth:o=300,maxContainerWidth:a=800,accessibility:c="AA"}=i;let l=n+(r-n)*Math.max(0,Math.min(1,(s-o)/(a-o)));l=this.enforceAccessibilityConstraints(l,l,c,!0).minSize,this.applyFontSize(e,`${l}px`)}generateClampValue(e,i,s,n,r){if(!(Number.isFinite(e)&&Number.isFinite(i)&&Number.isFinite(s)&&Number.isFinite(n)))return t.warn("Invalid numeric inputs for clamp calculation"),`${Number.isFinite(e)?e:16}px`;if(s>=n)return t.warn("Invalid viewport range: minViewport must be less than maxViewport"),`${e}px`;if(e>=i)return t.warn("Invalid size range: minSize must be less than maxSize"),`${e}px`;if("exponential"===r){const t=Math.sqrt(e*i),r=Math.sqrt(s*n)-s;return 0===r?`${e}px`:`clamp(${e}px, ${e}px + (${t-e}) * ((100vw - ${s}px) / ${r}px), ${i}px)`}const o=n-s;if(0===o)return`${e}px`;const a=(i-e)/o,c=e-a*s;return Number.isFinite(a)&&Number.isFinite(c)?`clamp(${e}px, ${c.toFixed(3)}px + ${(100*a).toFixed(3)}vw, ${i}px)`:(t.warn("Invalid clamp calculation, falling back to static size"),`${e}px`)}generateLinearClamp(e,t,i,s){const n=(t-e)/(s-i);return`clamp(${e}px, ${(e-n*i).toFixed(3)}px + ${(100*n).toFixed(3)}vw, ${t}px)`}generateExponentialClamp(e,t,i,s){const n=Math.sqrt(e*t),r=Math.sqrt(i*s)-i;if(Math.abs(r)<.001)return`${e}px`;return`clamp(${e}px, ${e}px + ${((n-e)/r).toFixed(4)} * (100vw - ${i}px), ${t}px)`}isValidClampValue(e){return!!/^clamp\(\s*[\d.]+px\s*,\s*[^,]+\s*,\s*[\d.]+px\s*\)$/.test(e)&&(!e.includes("NaN")&&!e.includes("undefined"))}enforceAccessibilityConstraints(e,t,i,s){if("none"===i||!s)return{minSize:e,maxSize:t};const n={AA:14,AAA:16}[i];return{minSize:Math.max(e,n),maxSize:Math.max(t,n)}}applyUserPreferences(e,i){try{const s=getComputedStyle(document.documentElement).fontSize,n=parseFloat(s||"16"),r=16;if(!Number.isFinite(n)||n<=0)return t.warn("Invalid root font size, using default scaling"),{minSize:e,maxSize:i};const o=n/r;if(!Number.isFinite(o)||o<=0)return t.warn("Invalid user scale factor, using default scaling"),{minSize:e,maxSize:i};const a=e*o,c=i*o;return Number.isFinite(a)&&Number.isFinite(c)?{minSize:a,maxSize:c}:(t.warn("Invalid scaled sizes, using default scaling"),{minSize:e,maxSize:i})}catch(s){return t.warn("Error applying user preferences, using default scaling",s),{minSize:e,maxSize:i}}}applyFontSize(e,t){e.style.fontSize=t}getComputedFontSize(e){try{const t=getComputedStyle(e),i=parseFloat(t.fontSize);if(Number.isFinite(i)&&i>0)return i;const s=e;if(s.style.fontSize){const e=parseFloat(s.style.fontSize);if(Number.isFinite(e)&&e>0)return e}return 16}catch(e){return t.warn("Failed to get computed font size, using fallback",e),16}}findNearestContainer(e){let t=e.parentElement;for(;t;){const e=getComputedStyle(t);if(e.display.includes("grid")||e.display.includes("flex")||"block"===e.display||t.matches("main, article, section, aside, div, header, footer"))return t;t=t.parentElement}return document.body}calculateOptimalTextSize(e,t,i,s){const n=e.textContent||"";if(!n.trim())return i;const r=document.createElement("span");r.style.visibility="hidden",r.style.position="absolute",r.style.whiteSpace="nowrap",r.textContent=n;const o=getComputedStyle(e);r.style.fontFamily=o.fontFamily||"Arial, sans-serif",r.style.fontWeight=o.fontWeight||"normal",r.style.fontStyle=o.fontStyle||"normal",document.body.appendChild(r);try{let e=i,n=s,o=i;for(;e<=n;){const i=Math.floor((e+n)/2);r.style.fontSize=`${i}px`;r.getBoundingClientRect().width<=t?(o=i,e=i+1):n=i-1}return o}finally{document.body.removeChild(r)}}optimizeFontPerformance(e){const t=e;this.optimizeLineHeightForElement(e),this.optimizeFontLoading(e),this.addPerformanceHints(e),this.applyFontSmoothing(t)}optimizeLineHeightForElement(e){const t=this.getComputedFontSize(e);if(!Number.isFinite(t)||t<=0)return;let i;i=t<=14?1.7:t<=18?1.6:t<=24?1.4:t<=32?1.3:1.2,i=Math.max(i,1.5),e.style.lineHeight=i.toString()}optimizeFontLoading(e){const t=e,i=window.getComputedStyle(e).fontFamily;i&&!this.isSystemFont(i)&&t.style.setProperty("font-display","swap")}isSystemFont(e){return["system-ui","-apple-system","BlinkMacSystemFont","Segoe UI","Roboto","Arial","sans-serif","serif","monospace"].some(t=>e.toLowerCase().includes(t.toLowerCase()))}addPerformanceHints(e){const t=e;this.isAnimatedElement(e)&&(t.style.willChange="font-size"),t.style.contain="layout style"}isAnimatedElement(e){const t=window.getComputedStyle(e);return t.transition.includes("font-size")||"none"!==t.animation||e.hasAttribute("data-proteus-animated")}applyFontSmoothing(e){e.style.setProperty("-webkit-font-smoothing","antialiased"),e.style.setProperty("-moz-osx-font-smoothing","grayscale"),e.style.setProperty("text-rendering","optimizeLegibility")}recordPerformanceMetrics(e,i){const s=performance.now();requestAnimationFrame(()=>{const n=performance.now()-s;void 0===window.proteusMetrics&&(window.proteusMetrics={fontApplicationTimes:[],averageRenderTime:0});const r=window.proteusMetrics;if(r.fontApplicationTimes.push(n),r.fontApplicationTimes.length>100&&r.fontApplicationTimes.shift(),r.averageRenderTime=r.fontApplicationTimes.reduce((e,t)=>e+t,0)/r.fontApplicationTimes.length,n>16){const s=e.tagName.toLowerCase();t.warn(`Slow font application detected: ${n.toFixed(2)}ms for ${s} with clamp: ${i}`)}})}}class k{constructor(){this.breakpoints=new Map,this.observer=null,this.idCounter=0,this.cssRules=new Map,this.performanceMetrics={evaluationTimes:[],averageTime:0,totalEvaluations:0},this.setupResizeObserver(),this.setupPerformanceMonitoring(),this.injectBaseCSS()}setPerformanceMonitor(e){this.performanceMonitor=e}registerContainer(e,t,i){return this.register(e,t,i)}register(e,i,s){const n=this.generateId();try{const t=this.parseBreakpoints(i),r={element:e,breakpoints:i,...s&&{callback:s},parsedBreakpoints:t};return this.breakpoints.set(n,r),this.observer&&this.observer.observe(e),this.updateBreakpoint(n),n}catch(e){return t.error("Failed to register breakpoints",e),""}}updateContainer(e){this.updateElement(e)}unregister(e){const t=this.breakpoints.get(e);if(!t)return;!Array.from(this.breakpoints.values()).some(e=>e!==t&&e.element===t.element)&&this.observer&&this.observer.unobserve(t.element),this.removeBreakpointClasses(t.element,t.parsedBreakpoints),this.breakpoints.delete(e)}getCurrentBreakpoint(e){const t=this.breakpoints.get(e);return t?.currentBreakpoint||null}updateElement(e){for(const[t,i]of this.breakpoints)i.element===e&&this.updateBreakpoint(t)}getAllConfigs(){return new Map(this.breakpoints)}setupResizeObserver(){"undefined"!=typeof ResizeObserver?this.observer=new ResizeObserver(e=>{for(const t of e)this.updateElement(t.target)}):t.warn("ResizeObserver not supported. Container breakpoints may not work correctly.")}generateId(){return`proteus-breakpoint-${++this.idCounter}-${Date.now()}`}parseBreakpoints(e){const i=[];for(const[s,n]of Object.entries(e))try{const e=this.parseBreakpointValue(n);i.push({name:s,value:e.value,unit:e.unit,type:e.type,originalValue:n})}catch(e){t.warn(`Invalid breakpoint value "${n}" for "${s}"`,e)}return i.sort((e,t)=>e.value-t.value),i}parseBreakpointValue(e){const t=e.match(/\((min|max)-width:\s*(\d+(?:\.\d+)?)(px|em|rem|%|vw|vh|ch|cw|cmin|cmax)?\)/);if(t){const e=t[1];return{value:parseFloat(t[2]),unit:t[3]||"px",type:e}}const i=e.match(/^(\d+(?:\.\d+)?)(px|em|rem|%|vw|vh|ch|cw|cmin|cmax)?$/);if(!i)throw new Error(`Invalid breakpoint value: ${e}`);const s=parseFloat(i[1]),n=i[2]||"px";let r=s;switch(n){case"em":case"rem":r=16*s;break;case"vw":r=s/100*window.innerWidth;break;case"vh":r=s/100*window.innerHeight;break;default:r=s}return{value:r,unit:n,type:"min"}}updateBreakpoint(e){const i=this.breakpoints.get(e);if(!i)return;const s=i.element.getBoundingClientRect(),n=s.width,r=s.height,o=this.determineBreakpoint(n,i.parsedBreakpoints),a=i.currentBreakpoint;if(this.performanceMonitor&&this.performanceMonitor.recordOperation(),o!==a){if(i.currentBreakpoint=o,this.updateBreakpointClasses(i.element,o,i.parsedBreakpoints),i.callback)try{const e={width:n,height:r,breakpoint:o};a&&(e.previousBreakpoint=a),e.element=i.element,i.callback(o,e)}catch(e){t.error("Error in breakpoint callback",e)}this.dispatchBreakpointEvent(i.element,o,{width:n,height:r,breakpoint:o,...a&&{previousBreakpoint:a},element:i.element})}}determineBreakpoint(e,t){let i="default";const s=t.filter(e=>"min"===e.type),n=t.filter(e=>"max"===e.type);for(let t=s.length-1;t>=0;t--){const n=s[t];if(n&&e>=n.value){i=n.name;break}}for(const t of n)if(e<=t.value)return t.name;return i}updateBreakpointClasses(e,t,i){this.removeBreakpointClasses(e,i),e.classList.add(`proteus-${t}`),e.setAttribute("data-proteus-breakpoint",t),e.setAttribute("data-container",t)}removeBreakpointClasses(e,t){for(const i of t)e.classList.remove(`proteus-${i.name}`);e.removeAttribute("data-proteus-breakpoint"),e.removeAttribute("data-container")}dispatchBreakpointEvent(e,t,i){const s=new CustomEvent("proteus:breakpoint-change",{detail:i,bubbles:!0});e.dispatchEvent(s)}getMetrics(){const e=Array.from(this.breakpoints.values()),t={};e.forEach(e=>{e.parsedBreakpoints.forEach(e=>{t[e.name]=(t[e.name]||0)+1})});const i=e.length>0?e.reduce((e,t)=>e+t.parsedBreakpoints.length,0)/e.length:0;return{totalRegistrations:e.length,activeElements:new Set(e.map(e=>e.element)).size,averageBreakpoints:i,breakpointDistribution:t}}registerMultiple(e){return e.map(e=>this.register(e.element,e.breakpoints,e.callback))}unregisterElement(e){const t=[];for(const[i,s]of this.breakpoints)s.element===e&&t.push(i);t.forEach(e=>this.unregister(e))}getAllActiveBreakpoints(){const e=[];for(const[t,i]of this.breakpoints)if(i.currentBreakpoint){const s=i.element.getBoundingClientRect();e.push({id:t,element:i.element,breakpoint:i.currentBreakpoint,width:s.width,height:s.height})}return e}updateAll(){for(const e of this.breakpoints.keys())this.updateBreakpoint(e)}setupPerformanceMonitoring(){setInterval(()=>{this.performanceMetrics.evaluationTimes.length>0&&(this.performanceMetrics.averageTime=this.performanceMetrics.evaluationTimes.reduce((e,t)=>e+t,0)/this.performanceMetrics.evaluationTimes.length,this.performanceMetrics.averageTime>5&&t.warn(`Container query evaluation taking ${this.performanceMetrics.averageTime.toFixed(2)}ms on average`),this.performanceMetrics.evaluationTimes.length>100&&(this.performanceMetrics.evaluationTimes=this.performanceMetrics.evaluationTimes.slice(-50)))},1e4)}injectBaseCSS(){const e=document.createElement("style");e.id="proteus-container-queries",e.textContent='\n /* Base container query styles */\n [data-proteus-container] {\n container-type: inline-size;\n position: relative;\n }\n\n /* Performance optimizations */\n [data-proteus-container] * {\n contain: layout style;\n }\n\n /* Responsive utility classes */\n .proteus-container-small { /* Applied when container is small */ }\n .proteus-container-medium { /* Applied when container is medium */ }\n .proteus-container-large { /* Applied when container is large */ }\n\n /* Transition support */\n [data-proteus-container] {\n transition: all 0.2s ease-out;\n }\n\n /* Debug mode styles */\n [data-proteus-debug="true"] {\n outline: 2px dashed rgba(255, 0, 0, 0.3);\n position: relative;\n }\n\n [data-proteus-debug="true"]::before {\n content: attr(data-proteus-breakpoint);\n position: absolute;\n top: 0;\n left: 0;\n background: rgba(255, 0, 0, 0.8);\n color: white;\n padding: 2px 6px;\n font-size: 10px;\n font-family: monospace;\n z-index: 9999;\n pointer-events: none;\n }\n ',document.getElementById("proteus-container-queries")||document.head.appendChild(e)}generateResponsiveCSS(e,t){const i=[];Object.entries(t).forEach(([t,s])=>{const n=this.parseContainerQuery(s);n&&i.push(`\n @container (${n}) {\n [data-proteus-id="${e}"] {\n --proteus-breakpoint: "${t}";\n }\n\n [data-proteus-id="${e}"] .proteus-${t} {\n display: block;\n }\n\n [data-proteus-id="${e}"] .proteus-not-${t} {\n display: none;\n }\n }\n `)}),i.length>0&&this.injectContainerCSS(e,i.join("\n"))}parseContainerQuery(e){return e.replace(/max-width/g,"max-inline-size").replace(/min-width/g,"min-inline-size").replace(/width/g,"inline-size").replace(/max-height/g,"max-block-size").replace(/min-height/g,"min-block-size").replace(/height/g,"block-size")}injectContainerCSS(e,t){const i=`proteus-container-${e}`;let s=document.getElementById(i);s||(s=document.createElement("style"),s.id=i,document.head.appendChild(s)),s.textContent=t,s.sheet&&this.cssRules.set(e,s.sheet)}recordPerformanceMetric(e){this.performanceMetrics.evaluationTimes.push(e),this.performanceMetrics.totalEvaluations++,this.performanceMetrics.evaluationTimes.length>100&&this.performanceMetrics.evaluationTimes.shift()}getPerformanceMetrics(){return{...this.performanceMetrics}}enableDebugMode(e=!0){this.breakpoints.forEach(t=>{const i=t.element;e?i.setAttribute("data-proteus-debug","true"):i.removeAttribute("data-proteus-debug")})}destroy(){this.observer&&(this.observer.disconnect(),this.observer=null),this.cssRules.forEach((e,t)=>{const i=document.getElementById(`proteus-container-${t}`);i&&i.remove()}),this.breakpoints.clear(),this.cssRules.clear();const e=document.getElementById("proteus-container-queries");e&&e.remove()}}class I{constructor(e={}){this.polyfills=new Map,this.fallbacks=new Map,this.modernFeatures=new Set,this.legacyFeatures=new Set,this.config={enablePolyfills:!0,gracefulDegradation:!0,fallbackStrategies:!0,performanceOptimizations:!0,legacySupport:!0,modernFeatures:!0,autoDetection:!0,...e},this.browserInfo=this.detectBrowser(),this.featureSupport=this.detectFeatures(),this.config.autoDetection&&this.initializeCompatibility()}async initializeCompatibility(){t.info("Initializing browser compatibility system"),this.applyBrowserFixes(),this.config.enablePolyfills&&await this.loadPolyfills(),this.config.fallbackStrategies&&this.setupFallbacks(),this.config.performanceOptimizations&&this.applyPerformanceOptimizations(),this.config.modernFeatures&&this.setupModernFeatures(),t.info("Browser compatibility system initialized",{browser:this.browserInfo,features:this.featureSupport})}detectBrowser(){const e=navigator.userAgent,t=navigator.platform;let i="Unknown",s="0",n="Unknown";if(e.includes("Chrome")&&!e.includes("Edg")){i="Chrome";const t=e.match(/Chrome\/(\d+)/);s=t?.[1]||"0",n="Blink"}else if(e.includes("Firefox")){i="Firefox";const t=e.match(/Firefox\/(\d+)/);s=t?.[1]||"0",n="Gecko"}else if(e.includes("Safari")&&!e.includes("Chrome")){i="Safari";const t=e.match(/Version\/(\d+)/);s=t?.[1]||"0",n="WebKit"}else if(e.includes("Edg")){i="Edge";const t=e.match(/Edg\/(\d+)/);s=t?.[1]||"0",n="Blink"}else if(e.includes("MSIE")||e.includes("Trident")){i="Internet Explorer";const t=e.match(/(?:MSIE |rv:)(\d+)/);s=t?.[1]||"0",n="Trident"}return{name:i,version:s,engine:n,platform:t,mobile:/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(e),supported:this.isBrowserSupported(i,parseInt(s))}}isBrowserSupported(e,t){return t>=({Chrome:60,Firefox:55,Safari:12,Edge:79,"Internet Explorer":11}[e]||0)}detectFeatures(){return{containerQueries:this.supportsContainerQueries(),clampFunction:this.supportsClamp(),customProperties:this.supportsCustomProperties(),flexbox:this.supportsFlexbox(),grid:this.supportsGrid(),intersectionObserver:"IntersectionObserver"in window,resizeObserver:"ResizeObserver"in window,mutationObserver:"MutationObserver"in window,requestAnimationFrame:"requestAnimationFrame"in window,webAnimations:"animate"in document.createElement("div"),prefersReducedMotion:this.supportsMediaQuery("(prefers-reduced-motion: reduce)"),prefersColorScheme:this.supportsMediaQuery("(prefers-color-scheme: dark)"),viewportUnits:this.supportsViewportUnits(),calc:this.supportsCalc(),transforms:this.supportsTransforms(),transitions:this.supportsTransitions(),animations:this.supportsAnimations(),webFonts:this.supportsWebFonts(),fontDisplay:this.supportsFontDisplay(),fontVariationSettings:this.supportsFontVariationSettings()}}supportsContainerQueries(){try{return CSS.supports("container-type","inline-size")}catch{return!1}}supportsClamp(){try{return CSS.supports("width","clamp(1px, 2px, 3px)")}catch{return!1}}supportsCustomProperties(){try{return CSS.supports("--test","0")}catch{return!1}}supportsFlexbox(){try{return CSS.supports("display","flex")}catch{return!1}}supportsGrid(){try{return CSS.supports("display","grid")}catch{return!1}}supportsMediaQuery(e){try{return window.matchMedia(e).media===e}catch{return!1}}supportsViewportUnits(){try{return CSS.supports("width","1vw")}catch{return!1}}supportsCalc(){try{return CSS.supports("width","calc(1px + 1px)")}catch{return!1}}supportsTransforms(){try{return CSS.supports("transform","translateX(1px)")}catch{return!1}}supportsTransitions(){try{return CSS.supports("transition","all 1s")}catch{return!1}}supportsAnimations(){try{return CSS.supports("animation","test 1s")}catch{return!1}}supportsWebFonts(){return"fonts"in document}supportsFontDisplay(){try{return CSS.supports("font-display","swap")}catch{return!1}}supportsFontVariationSettings(){try{return CSS.supports("font-variation-settings",'"wght" 400')}catch{return!1}}applyBrowserFixes(){"Internet Explorer"===this.browserInfo.name&&this.applyIEFixes(),"Safari"===this.browserInfo.name&&this.applySafariFixes(),"Firefox"===this.browserInfo.name&&this.applyFirefoxFixes(),this.browserInfo.mobile&&this.applyMobileFixes()}applyIEFixes(){document.documentElement.classList.add("ie"),this.featureSupport.viewportUnits||this.addPolyfill("viewport-units",{name:"Viewport Units Polyfill",required:!0,loaded:!1,size:15e3,fallback:this.viewportUnitsFallback.bind(this)}),this.featureSupport.flexbox||this.addPolyfill("flexbox",{name:"Flexbox Polyfill",required:!0,loaded:!1,size:25e3,fallback:this.flexboxFallback.bind(this)})}applySafariFixes(){document.documentElement.classList.add("safari");parseInt(this.browserInfo.version)<14&&document.documentElement.classList.add("safari-old")}applyFirefoxFixes(){document.documentElement.classList.add("firefox");const e=document.createElement("style");e.textContent="\n /* Firefox scrollbar styling */\n * {\n scrollbar-width: thin;\n scrollbar-color: rgba(0,0,0,0.3) transparent;\n }\n ",document.head.appendChild(e)}applyMobileFixes(){document.documentElement.classList.add("mobile");const e=()=>{const e=.01*window.innerHeight;document.documentElement.style.setProperty("--vh",`${e}px`)};e(),window.addEventListener("resize",e),window.addEventListener("orientationchange",e);const t=document.querySelector('meta[name="viewport"]');t&&t.setAttribute("content","width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no")}async loadPolyfills(){const e=Array.from(this.polyfills.values()).filter(e=>e.required&&!e.loaded);if(0!==e.length){t.info(`Loading ${e.length} polyfills`);for(const i of e)try{i.url?await this.loadPolyfillScript(i):i.fallback&&i.fallback(),i.loaded=!0,t.info(`Loaded polyfill: ${i.name}`)}catch(e){t.error(`Failed to load polyfill ${i.name}:`,e),i.fallback&&(i.fallback(),i.loaded=!0)}}}loadPolyfillScript(e){return new Promise((t,i)=>{const s=document.createElement("script");s.src=e.url,s.async=!0,s.onload=()=>t(),s.onerror=()=>i(new Error(`Failed to load ${e.url}`)),document.head.appendChild(s)})}addPolyfill(e,t){this.polyfills.set(e,t)}setupFallbacks(){this.featureSupport.containerQueries||this.fallbacks.set("container-queries",this.containerQueriesFallback.bind(this)),this.featureSupport.clampFunction||this.fallbacks.set("clamp",this.clampFallback.bind(this)),this.featureSupport.customProperties||this.fallbacks.set("custom-properties",this.customPropertiesFallback.bind(this)),this.featureSupport.intersectionObserver||this.fallbacks.set("intersection-observer",this.intersectionObserverFallback.bind(this))}containerQueriesFallback(){if(this.featureSupport.resizeObserver){t.info("Using ResizeObserver fallback for container queries");const e=document.createElement("style");e.id="container-queries-fallback",e.textContent='\n /* Container queries fallback using ResizeObserver */\n [data-container-fallback] {\n position: relative;\n }\n\n [data-container="small"] {\n --container-size: small;\n }\n\n [data-container="medium"] {\n --container-size: medium;\n }\n\n [data-container="large"] {\n --container-size: large;\n }\n ',document.getElementById("container-queries-fallback")||document.head.appendChild(e);const i=new ResizeObserver(e=>{e.forEach(e=>{const t=e.target,i=e.contentRect.width;t.removeAttribute("data-container"),i<=400?t.setAttribute("data-container","small"):i<=800?t.setAttribute("data-container","medium"):t.setAttribute("data-container","large")})});document.querySelectorAll("[data-container-fallback]").forEach(e=>{i.observe(e)})}else{t.warn("No fallback available for container queries");const e=document.createElement("style");e.textContent="\n /* Media query fallback for container queries */\n @media (max-width: 400px) {\n [data-container-fallback] {\n --container-size: small;\n }\n }\n\n @media (min-width: 401px) and (max-width: 800px) {\n [data-container-fallback] {\n --container-size: medium;\n }\n }\n\n @media (min-width: 801px) {\n [data-container-fallback] {\n --container-size: large;\n }\n }\n ",document.head.appendChild(e)}}clampFallback(){t.info("Using calc() and media queries fallback for clamp()");const e=document.createElement("style");e.id="clamp-fallback",e.textContent="\n /* Clamp fallback styles */\n .proteus-clamp {\n font-size: var(--min-size, 16px);\n }\n\n @media (min-width: 320px) {\n .proteus-clamp {\n font-size: calc(var(--min-size, 16px) + (var(--max-size, 24px) - var(--min-size, 16px)) * ((100vw - 320px) / (1200px - 320px)));\n }\n }\n\n @media (min-width: 1200px) {\n .proteus-clamp {\n font-size: var(--max-size, 24px);\n }\n }\n ",document.head.appendChild(e)}customPropertiesFallback(){t.info("Using JavaScript fallback for CSS custom properties");const e=new Map,i=t=>{window.getComputedStyle(t);const i=t.style.cssText,s=/--([\w-]+):\s*([^;]+)/g;let n;for(;null!==(n=s.exec(i));)n[1]&&n[2]&&e.set(`--${n[1]}`,n[2].trim())},s=t=>{const i=t,s=i.style.cssText,n=/var\((--[\w-]+)(?:,\s*([^)]+))?\)/g;let r,o=s;for(;null!==(r=n.exec(s));){const t=r[1],i=r[2]||"",s=e.get(t||"")||i;s&&(o=o.replace(r[0],s))}o!==s&&(i.style.cssText=o)};new MutationObserver(e=>{e.forEach(e=>{if("attributes"===e.type&&"style"===e.attributeName){const t=e.target;i(t),s(t)}})}).observe(document.body,{attributes:!0,subtree:!0,attributeFilter:["style"]}),document.querySelectorAll("*").forEach(e=>{i(e),s(e)})}intersectionObserverFallback(){t.info("Using scroll event fallback for Intersection Observer");class e{constructor(e,t={}){this.elements=new Set,this.handleScroll=()=>{this.checkIntersection()},this.callback=e,this.rootMargin=t.rootMargin||"0px",this.threshold=t.threshold||0,this.setupScrollListener()}observe(e){this.elements.add(e),this.checkIntersection()}unobserve(e){this.elements.delete(e)}disconnect(){this.elements.clear(),window.removeEventListener("scroll",this.handleScroll),window.removeEventListener("resize",this.handleScroll)}setupScrollListener(){this.handleScroll=this.handleScroll.bind(this),window.addEventListener("scroll",this.handleScroll,{passive:!0}),window.addEventListener("resize",this.handleScroll,{passive:!0})}checkIntersection(){const e=[];this.elements.forEach(t=>{const i=t.getBoundingClientRect(),s=window.innerHeight,n=window.innerWidth,r=i.top<s&&i.bottom>0&&i.left<n&&i.right>0;let o=0;if(r){const e=(Math.min(i.bottom,s)-Math.max(i.top,0))*(Math.min(i.right,n)-Math.max(i.left,0)),t=i.height*i.width;o=t>0?e/t:0}e.push({target:t,isIntersecting:r,intersectionRatio:o,boundingClientRect:i,intersectionRect:i,rootBounds:{top:0,left:0,bottom:s,right:n,width:n,height:s},time:Date.now()})}),e.length>0&&this.callback(e,this)}}window.IntersectionObserver||(window.IntersectionObserver=e)}viewportUnitsFallback(){t.info("Using JavaScript fallback for viewport units");const e=()=>{const e=window.innerWidth/100,t=window.innerHeight/100;document.documentElement.style.setProperty("--vw",`${e}px`),document.documentElement.style.setProperty("--vh",`${t}px`)};e(),window.addEventListener("resize",e)}flexboxFallback(){t.info("Using table/inline-block fallback for flexbox");const e=document.createElement("style");e.textContent="\n /* Flexbox fallback */\n .proteus-flex {\n display: table;\n width: 100%;\n }\n\n .proteus-flex-item {\n display: table-cell;\n vertical-align: middle;\n }\n ",document.head.appendChild(e)}applyPerformanceOptimizations(){this.browserInfo.supported||this.applyLegacyOptimizations(),this.browserInfo.mobile&&this.applyMobileOptimizations(),this.applyFeatureBasedOptimizations()}applyLegacyOptimizations(){document.documentElement.classList.add("legacy-browser");const e=document.createElement("style");e.textContent="\n .legacy-browser * {\n animation-duration: 0.1s !important;\n transition-duration: 0.1s !important;\n }\n ",document.head.appendChild(e)}applyMobileOptimizations(){const e=document.createElement("style");e.textContent='\n /* Mobile optimizations */\n * {\n -webkit-tap-highlight-color: transparent;\n touch-action: manipulation;\n }\n\n button, a, [role="button"] {\n min-height: 44px;\n min-width: 44px;\n }\n ',document.head.appendChild(e)}applyFeatureBasedOptimizations(){this.featureSupport.transforms&&document.documentElement.classList.add("transforms-supported"),this.featureSupport.webAnimations||document.documentElement.classList.add("no-web-animations")}setupModernFeatures(){Object.entries(this.featureSupport).forEach(([e,t])=>{t?(this.modernFeatures.add(e),document.documentElement.classList.add(`supports-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`)):(this.legacyFeatures.add(e),document.documentElement.classList.add(`no-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`))})}getBrowserInfo(){return{...this.browserInfo}}getFeatureSupport(){return{...this.featureSupport}}isFeatureSupported(e){return this.featureSupport[e]}getCompatibilityReport(){const e=[];return this.browserInfo.supported||e.push("Consider upgrading to a modern browser for better performance"),this.legacyFeatures.size>5&&e.push("Many modern features are not supported - consider using polyfills"),"Internet Explorer"===this.browserInfo.name&&e.push("Internet Explorer support is limited - consider migrating to Edge"),{browser:this.getBrowserInfo(),features:this.getFeatureSupport(),polyfills:Array.from(this.polyfills.values()),modernFeatures:Array.from(this.modernFeatures),legacyFeatures:Array.from(this.legacyFeatures),recommendations:e}}enableGracefulDegradation(e,t){this.fallbacks.set(e,t),this.modernFeatures.has(e)||t()}destroy(){document.querySelectorAll('style[id*="proteus"], style[id*="clamp-fallback"]').forEach(e=>e.remove()),this.polyfills.clear(),this.fallbacks.clear(),this.modernFeatures.clear(),this.legacyFeatures.clear(),t.info("Browser compatibility system destroyed")}}class R{constructor(){this.detectedBottlenecks=[]}detectBottlenecks(e){return this.detectedBottlenecks=[],e.averageFPS<30&&this.detectedBottlenecks.push({type:"cpu",severity:"high",description:"Low frame rate detected",impact:(30-e.averageFPS)/30,suggestions:["Reduce DOM manipulations","Optimize JavaScript execution","Use requestAnimationFrame for animations"]}),e.memoryUsage.percentage>80&&this.detectedBottlenecks.push({type:"memory",severity:"high",description:"High memory usage detected",impact:e.memoryUsage.percentage/100,suggestions:["Clean up unused objects","Remove event listeners","Optimize image sizes"]}),e.domNodes>5e3&&this.detectedBottlenecks.push({type:"dom",severity:"medium",description:"Large DOM tree detected",impact:Math.min(e.domNodes/1e4,1),suggestions:["Implement virtual scrolling","Remove unused DOM nodes","Use document fragments for batch operations"]}),this.detectedBottlenecks}getBottlenecks(){return[...this.detectedBottlenecks]}}class T{constructor(){this.memoryLeakDetector=new Map,this.cleanupTasks=[]}optimizeMemory(){window.gc&&window.gc(),this.cleanupTasks.forEach(e=>{try{e()}catch(e){t.warn("Memory cleanup task failed:",e)}}),this.cleanupTasks=[]}detectMemoryLeaks(e){const t=e.memoryUsage.used,i=Date.now();this.memoryLeakDetector.set(i.toString(),t);const s=Array.from(this.memoryLeakDetector.entries());if(s.length>10&&s.slice(0,-10).forEach(([e])=>{this.memoryLeakDetector.delete(e)}),s.length>=5){const e=s.map(([,e])=>e),t=e.every((t,i)=>0===i||t>=(e[i-1]||0)),i=e[e.length-1]||0,n=e[0]||1;return t&&(i-n)/n>.1}return!1}addCleanupTask(e){this.cleanupTasks.push(e)}}class P{constructor(e={}){this.alerts=[],this.isMonitoring=!1,this.rafId=null,this.lastFrameTime=0,this.frameCount=0,this.performanceHistory=[],this.callbacks=new Map,this.measurementInterval=1e3,this.detailedProfiling=!1,this.frameTimes=[],this.operationCount=0,this.lastOperationTime=0,this.bottleneckDetector=new R,this.memoryOptimizer=new T,this.thresholds={minFrameRate:55,maxFrameTime:16.67,maxMemoryUsage:104857600,maxDOMNodes:5e3,maxEventListeners:1e3,...e},this.metrics=this.createInitialMetrics()}startMonitoring(){this.start()}start(){this.isMonitoring||(this.isMonitoring=!0,this.lastFrameTime=performance.now(),this.lastOperationTime=performance.now(),this.startFrameMonitoring(),this.startMemoryMonitoring())}stop(){this.isMonitoring&&(this.isMonitoring=!1,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null))}destroy(){this.stop(),this.callbacks.clear(),this.alerts=[],this.frameTimes=[],this.frameCount=0,this.operationCount=0,this.metrics=this.createInitialMetrics()}startFrameRateMonitoring(){this.isMonitoring||this.start()}stopFrameRateMonitoring(){this.stop()}async measureOperation(e,t){const i=performance.now(),s=await t(),n=performance.now()-i;return this.recordOperation(),{result:s,duration:n,name:e}}detectBottlenecks(){const e=[];return this.metrics.averageFPS<30?e.push({type:"frame-rate",severity:"high",description:`Low frame rate: ${this.metrics.averageFPS.toFixed(1)} FPS`}):this.metrics.averageFPS<50&&e.push({type:"frame-rate",severity:"medium",description:`Moderate frame rate: ${this.metrics.averageFPS.toFixed(1)} FPS`}),this.metrics.memoryUsage.percentage>80&&e.push({type:"memory",severity:"high",description:`High memory usage: ${this.metrics.memoryUsage.percentage.toFixed(1)}%`}),e}getMetrics(){return this.updateMetrics(),{...this.metrics}}getAlerts(){return[...this.alerts]}clearAlerts(){this.alerts=[]}addCallback(e,t){this.callbacks.set(e,t)}removeCallback(e){this.callbacks.delete(e)}recordOperation(){this.operationCount++}updateCacheHitRate(e,t){this.metrics.cacheHitRate=t>0?e/t*100:0}updateMetrics(){this.updateFrameMetrics(),this.updateMemoryMetrics(),this.updateDOMMetrics(),this.updateOperationMetrics(),this.checkThresholds(),this.notifyCallbacks()}getRecommendations(){const e=[];return this.metrics.frameRate<this.thresholds.minFrameRate&&(e.push("Consider reducing DOM manipulations or using requestAnimationFrame"),e.push("Enable batch DOM operations to improve frame rate")),this.metrics.memoryUsage.percentage>80&&(e.push("Memory usage is high - consider implementing cleanup routines"),e.push("Review event listeners and observers for potential leaks")),this.metrics.domNodes>this.thresholds.maxDOMNodes&&(e.push("DOM tree is large - consider virtualization for long lists"),e.push("Remove unused DOM elements to improve performance")),this.metrics.eventListeners>this.thresholds.maxEventListeners&&(e.push("High number of event listeners - consider event delegation"),e.push("Review and cleanup unused event listeners")),this.metrics.cacheHitRate<70&&(e.push("Cache hit rate is low - review caching strategy"),e.push("Consider increasing cache size or improving cache keys")),e}startFrameMonitoring(){const e=t=>{if(!this.isMonitoring)return;const i=t-this.lastFrameTime;this.frameTimes.push(i),this.frameTimes.length>60&&this.frameTimes.shift(),this.frameCount++,this.lastFrameTime=t,(this.frameCount%60==0||i>1e3)&&(this.updateFrameMetrics(),this.checkThresholds(),this.notifyCallbacks()),this.rafId=requestAnimationFrame(e)};this.rafId=requestAnimationFrame(e)}startMemoryMonitoring(){const e=()=>{this.isMonitoring&&(this.updateMemoryMetrics(),setTimeout(e,5e3))};setTimeout(e,5e3)}updateFrameMetrics(){if(0===this.frameTimes.length)return;const e=this.frameTimes.reduce((e,t)=>e+t,0)/this.frameTimes.length,t=e>0?1e3/e:60;this.metrics.averageFrameTime=Math.round(100*e)/100,this.metrics.frameRate=Math.round(100*t)/100,this.metrics.averageFPS=this.metrics.frameRate,this.metrics.lastMeasurement=performance.now()}updateMemoryMetrics(){if("memory"in performance){const e=performance.memory;this.metrics.memoryUsage={used:e.usedJSHeapSize,total:e.totalJSHeapSize,percentage:Math.round(e.usedJSHeapSize/e.totalJSHeapSize*100)}}}updateDOMMetrics(){this.metrics.domNodes=document.querySelectorAll("*").length,this.metrics.eventListeners=this.estimateEventListeners(),this.metrics.observers=this.countObservers()}updateOperationMetrics(){const e=performance.now(),t=(e-this.lastOperationTime)/1e3;t>0&&(this.metrics.operationsPerSecond=Math.round(this.operationCount/t)),this.operationCount=0,this.lastOperationTime=e}estimateEventListeners(){const e=document.querySelectorAll("*");let t=0;const i=["click","scroll","resize","load","input","change"];return e.forEach(e=>{i.forEach(i=>{null!==e[`on${i}`]&&t++})}),t}countObservers(){return 0}checkThresholds(){const e=performance.now();this.metrics.frameRate<this.thresholds.minFrameRate&&this.addAlert({type:"warning",metric:"frameRate",value:this.metrics.frameRate,threshold:this.thresholds.minFrameRate,message:`Frame rate (${this.metrics.frameRate}fps) is below target (${this.thresholds.minFrameRate}fps)`,timestamp:e,suggestions:["Reduce DOM manipulations","Use requestAnimationFrame for animations","Enable batch DOM operations"]}),this.metrics.memoryUsage.used>this.thresholds.maxMemoryUsage&&this.addAlert({type:"critical",metric:"memoryUsage",value:this.metrics.memoryUsage.used,threshold:this.thresholds.maxMemoryUsage,message:`Memory usage (${Math.round(this.metrics.memoryUsage.used/1024/1024)}MB) exceeds threshold`,timestamp:e,suggestions:["Implement cleanup routines","Review for memory leaks","Optimize data structures"]}),this.metrics.domNodes>this.thresholds.maxDOMNodes&&this.addAlert({type:"warning",metric:"domNodes",value:this.metrics.domNodes,threshold:this.thresholds.maxDOMNodes,message:`DOM tree size (${this.metrics.domNodes} nodes) is large`,timestamp:e,suggestions:["Consider virtualization","Remove unused elements","Optimize DOM structure"]})}addAlert(e){this.alerts.find(t=>t.metric===e.metric&&e.timestamp-t.timestamp<3e4)||(this.alerts.push(e),this.alerts.length>50&&this.alerts.shift())}notifyCallbacks(){this.callbacks.forEach(e=>{try{e(this.metrics)}catch(e){t.error("Error in performance callback",e)}})}createInitialMetrics(){return{frameRate:60,averageFPS:60,averageFrameTime:16.67,memoryUsage:{used:0,total:0,percentage:0},domNodes:0,eventListeners:0,observers:0,cacheHitRate:0,operationsPerSecond:0,lastMeasurement:performance.now()}}enableDetailedProfiling(e=!0){this.detailedProfiling=e,e?this.startAdvancedMonitoring():this.stopAdvancedMonitoring()}startAdvancedMonitoring(){this.startFrameRateMonitoring(),setInterval(()=>{const e=this.getMetrics();this.memoryOptimizer.detectMemoryLeaks(e)&&this.addAlert({type:"warning",metric:"memory",value:e.memoryUsage.percentage,threshold:80,message:"Potential memory leak detected",timestamp:Date.now(),suggestions:["Check for unreferenced objects","Remove unused event listeners","Clear intervals and timeouts"]})},5e3),setInterval(()=>{const e=this.getMetrics();this.bottleneckDetector.detectBottlenecks(e).forEach(e=>{"high"===e.severity&&this.addAlert({type:"critical",metric:e.type,value:100*e.impact,threshold:50,message:e.description,timestamp:Date.now(),suggestions:e.suggestions})})},2e3)}stopAdvancedMonitoring(){t.info("Advanced performance monitoring stopped")}getPerformanceSnapshot(){const e=this.getMetrics(),t=this.bottleneckDetector.getBottlenecks().map(e=>e.description),i=this.memoryOptimizer.detectMemoryLeaks(e),s={timestamp:Date.now(),metrics:e,bottlenecks:t,memoryLeaks:i};return this.performanceHistory.push(s),this.performanceHistory.length>100&&this.performanceHistory.shift(),s}getPerformanceHistory(){return[...this.performanceHistory]}analyzePerformanceTrends(){if(this.performanceHistory.length<5)return{frameRateTrend:"stable",memoryTrend:"stable",overallHealth:"good"};const e=this.performanceHistory.slice(-5),t=e.map(e=>e.metrics.averageFPS),i=e.map(e=>e.metrics.memoryUsage.percentage),s=this.calculateTrend(t),n=s>1?"improving":s<-1?"degrading":"stable",r=this.calculateTrend(i),o=r<-5?"improving":r>5?"degrading":"stable",a=e[e.length-1]?.metrics;let c="good";return a&&(a.averageFPS<30||a.memoryUsage.percentage>80?c="critical":(a.averageFPS<45||a.memoryUsage.percentage>60)&&(c="warning")),{frameRateTrend:n,memoryTrend:o,overallHealth:c}}calculateTrend(e){if(e.length<2)return 0;const t=e.length,i=t*(t-1)/2,s=e.reduce((e,t)=>e+t,0);return(t*e.reduce((e,t,i)=>e+i*t,0)-i*s)/(t*e.reduce((e,t,i)=>e+i*i,0)-i*i)}optimizePerformance(){const e=this.getMetrics(),i=this.bottleneckDetector.detectBottlenecks(e);e.memoryUsage.percentage>70&&(this.memoryOptimizer.optimizeMemory(),t.info("Memory optimization applied")),e.domNodes>3e3&&this.optimizeDOM(),i.forEach(e=>{t.info(`Performance bottleneck detected: ${e.description}`),t.info(`Suggestions: ${e.suggestions.join(", ")}`)})}optimizeDOM(){const e=document.querySelectorAll("[data-proteus-unused]");e.forEach(e=>e.remove());const i=document.querySelectorAll("img:not([loading])");i.forEach(e=>{e.loading="lazy"}),t.info(`DOM optimization applied: removed ${e.length} unused elements, optimized ${i.length} images`)}generatePerformanceReport(){const e=this.getMetrics(),t=this.bottleneckDetector.detectBottlenecks(e),i=this.analyzePerformanceTrends(),s=[];e.averageFPS<45&&(s.push("Consider reducing animation complexity"),s.push("Optimize JavaScript execution with requestAnimationFrame")),e.memoryUsage.percentage>60&&(s.push("Implement memory cleanup strategies"),s.push("Remove unused event listeners and observers")),e.domNodes>2e3&&(s.push("Consider virtual scrolling for large lists"),s.push("Remove unused DOM elements")),t.forEach(e=>{s.push(...e.suggestions)});return{summary:`Performance Health: ${i.overallHealth.toUpperCase()} | FPS: ${e.averageFPS.toFixed(1)} | Memory: ${e.memoryUsage.percentage.toFixed(1)}% | DOM Nodes: ${e.domNodes}`,metrics:e,bottlenecks:t,trends:i,recommendations:[...new Set(s)]}}}class ${constructor(e={}){this.readQueue=[],this.writeQueue=[],this.processingQueue=[],this.rafId=null,this.flushTimer=null,this.isProcessing=!1,this.operationResults=new Map,this.config={maxBatchSize:50,frameTimeLimit:16,separateReadWrite:!0,measurePerformance:!0,autoFlush:!0,flushInterval:100,...e},this.metrics=this.createInitialMetrics(),this.config.autoFlush&&this.startAutoFlush()}queueRead(e,t,i="normal",s=[]){const n=this.generateOperationId("read");return new Promise((r,o)=>{const a={id:n,type:"read",element:e,operation:()=>{try{const e=t();return this.operationResults.set(n,e),r(e),e}catch(e){throw o(e),e}},priority:i,timestamp:performance.now(),dependencies:s};this.readQueue.push(a),this.scheduleProcessing()})}queueWrite(e,t,i="normal",s=[]){const n=this.generateOperationId("write");return new Promise((r,o)=>{const a={id:n,type:"write",element:e,operation:()=>{try{t(),r()}catch(e){throw o(e),e}},priority:i,timestamp:performance.now(),dependencies:s};this.writeQueue.push(a),this.scheduleProcessing()})}batchStyles(e,t,i="normal"){return this.queueWrite(e,()=>{const i=e;Object.entries(t).forEach(([e,t])=>{i.style.setProperty(e,t)})},i)}batchClasses(e,t,i="normal"){return this.queueWrite(e,()=>{t.add&&e.classList.add(...t.add),t.remove&&e.classList.remove(...t.remove),t.toggle&&t.toggle.forEach(t=>{e.classList.toggle(t)})},i)}batchAttributes(e,t,i="normal"){return this.queueWrite(e,()=>{Object.entries(t).forEach(([t,i])=>{null===i?e.removeAttribute(t):e.setAttribute(t,i)})},i)}batchReads(e,t,i="normal"){return this.queueRead(e,()=>{const e={};return Object.entries(t).forEach(([t,i])=>{e[t]=i()}),e},i)}measureElement(e,t=["width","height"],i="normal"){return this.queueRead(e,()=>{const i=e.getBoundingClientRect(),s={};return t.forEach(e=>{s[e]=i[e]}),s},i)}flush(){return new Promise(e=>{this.processOperations(!0).then(()=>{e()})})}getMetrics(){return{...this.metrics}}clear(){this.readQueue=[],this.writeQueue=[],this.processingQueue=[],this.operationResults.clear()}destroy(){this.stopAutoFlush(),this.stopProcessing(),this.clear()}scheduleProcessing(){this.isProcessing||this.rafId||(this.rafId=requestAnimationFrame(()=>{this.processOperations(),this.rafId=null}))}async processOperations(e=!1){if(this.isProcessing)return;this.isProcessing=!0;const t=performance.now();try{if(this.config.separateReadWrite)await this.processQueue(this.readQueue,"read",e),await this.processQueue(this.writeQueue,"write",e);else{const t=[...this.readQueue,...this.writeQueue];this.readQueue=[],this.writeQueue=[],await this.processQueue(t,"mixed",e)}const i=performance.now()-t;this.updateMetrics(i)}finally{this.isProcessing=!1}}async processQueue(e,t,i){if(0===e.length)return;const s=this.sortOperations(e),n=i?1/0:this.config.frameTimeLimit,r=performance.now();let o=0;for(const a of s){const s=performance.now()-r;if(!i&&s>n)break;if(!this.areDependenciesSatisfied(a))continue;if(!i&&o>=this.config.maxBatchSize)break;try{this.config.measurePerformance&&this.wouldCauseLayoutThrash(a,t)&&this.metrics.layoutThrashes++,a.operation(),o++,"read"===a.type?this.metrics.readOperations++:this.metrics.writeOperations++}catch(e){}const c=e.indexOf(a);c>-1&&e.splice(c,1)}this.metrics.totalOperations+=o}sortOperations(e){return e.sort((e,t)=>{const i={high:0,normal:1,low:2},s=i[e.priority]-i[t.priority];return 0!==s?s:e.timestamp-t.timestamp})}areDependenciesSatisfied(e){return!e.dependencies||0===e.dependencies.length||e.dependencies.every(e=>this.operationResults.has(e))}wouldCauseLayoutThrash(e,t){if("mixed"===t&&"write"===e.type){return this.processingQueue.filter(e=>"read"===e.type&&performance.now()-e.timestamp<16).length>0}return!1}generateOperationId(e){return`${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}startAutoFlush(){this.flushTimer=window.setInterval(()=>{(this.readQueue.length>0||this.writeQueue.length>0)&&this.scheduleProcessing()},this.config.flushInterval)}stopAutoFlush(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}stopProcessing(){this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null)}updateMetrics(e){if(this.metrics.batchesProcessed++,this.metrics.averageBatchTime=(this.metrics.averageBatchTime+e)/2,this.config.separateReadWrite){const e=Math.min(this.readQueue.length,this.writeQueue.length);this.metrics.preventedThrashes+=e}}createInitialMetrics(){return{totalOperations:0,readOperations:0,writeOperations:0,batchesProcessed:0,averageBatchTime:0,layoutThrashes:0,preventedThrashes:0}}}class L{constructor(e={}){this.components=new Map,this.intersectionObserver=null,this.activationQueue=[],this.cache=new Map,this.isProcessing=!1,this.activeActivations=new Set,this.config={rootMargin:"50px",threshold:[0,.1,.5,1],useIdleCallback:!0,idleTimeout:5e3,progressiveEnhancement:!0,cacheResults:!0,priorityQueue:!0,maxConcurrent:3,...e},this.metrics=this.createInitialMetrics(),this.setupIntersectionObserver()}register(e,t,i={}){const s=i.id||this.generateId(),n={id:s,element:e,activator:t,priority:i.priority||"normal",dependencies:i.dependencies||[],activated:!1,cached:!1,timestamp:performance.now()};return this.components.set(s,n),this.metrics.totalComponents++,i.immediate?this.activateComponent(n):this.observeComponent(n),s}unregister(e){const t=this.components.get(e);t&&(this.intersectionObserver?.unobserve(t.element),this.components.delete(e),this.cache.delete(e),this.metrics.totalComponents--)}async activate(e){const t=this.components.get(e);t&&!t.activated&&await this.activateComponent(t)}preloadHighPriority(){Array.from(this.components.values()).filter(e=>"high"===e.priority&&!e.activated).forEach(e=>{this.scheduleActivation(e)})}getCached(e){if(!this.config.cacheResults)return null;const t=this.cache.get(e);return t?(this.metrics.cacheHits++,t):(this.metrics.cacheMisses++,null)}setCached(e,t){this.config.cacheResults&&this.cache.set(e,t)}getMetrics(){return{...this.metrics}}clearCache(){this.cache.clear()}destroy(){this.intersectionObserver?.disconnect(),this.components.clear(),this.cache.clear(),this.activationQueue=[],this.activeActivations.clear()}setupIntersectionObserver(){window.IntersectionObserver&&(this.intersectionObserver=new IntersectionObserver(e=>{e.forEach(e=>{if(e.isIntersecting){const t=this.findComponentByElement(e.target);t&&!t.activated&&this.scheduleActivation(t)}})},{rootMargin:this.config.rootMargin,threshold:this.config.threshold}))}observeComponent(e){this.intersectionObserver?this.intersectionObserver.observe(e.element):this.scheduleActivation(e)}scheduleActivation(e){this.config.priorityQueue?(this.addToQueue(e),this.processQueue()):this.activateComponent(e)}addToQueue(e){this.activationQueue.some(t=>t.id===e.id)||(this.activationQueue.push(e),this.activationQueue.sort((e,t)=>{const i={high:0,normal:1,low:2},s=i[e.priority]-i[t.priority];return 0!==s?s:e.timestamp-t.timestamp}))}async processQueue(){if(!this.isProcessing&&0!==this.activationQueue.length){this.isProcessing=!0;try{for(;this.activationQueue.length>0&&this.activeActivations.size<this.config.maxConcurrent;){const e=this.activationQueue.shift();e&&!e.activated&&this.areDependenciesSatisfied(e)&&this.activateComponent(e)}}finally{this.isProcessing=!1,this.activationQueue.length>0&&this.scheduleNextProcessing()}}}scheduleNextProcessing(){this.config.useIdleCallback&&window.requestIdleCallback?(window.requestIdleCallback(()=>this.processQueue(),{timeout:this.config.idleTimeout}),this.metrics.idleCallbacksUsed++):setTimeout(()=>this.processQueue(),16)}async activateComponent(e){if(e.activated||this.activeActivations.has(e.id))return;this.activeActivations.add(e.id);const t=performance.now();try{const i=`component-${e.id}`;let s=this.getCached(i);if(!s){if(this.config.progressiveEnhancement&&!this.isEnhancementSupported(e))return;s=await e.activator(),this.config.cacheResults&&(this.setCached(i,s),e.cached=!0)}e.activated=!0,this.metrics.activatedComponents++,this.metrics.pendingComponents=this.metrics.totalComponents-this.metrics.activatedComponents;const n=performance.now()-t;this.metrics.averageActivationTime=(this.metrics.averageActivationTime+n)/2,this.intersectionObserver?.unobserve(e.element)}catch(e){}finally{this.activeActivations.delete(e.id),this.activationQueue.length>0&&this.scheduleNextProcessing()}}areDependenciesSatisfied(e){return e.dependencies.every(e=>{const t=this.components.get(e);return t?.activated||!1})}isEnhancementSupported(e){return["IntersectionObserver","ResizeObserver","requestAnimationFrame"].every(e=>e in window)}findComponentByElement(e){return Array.from(this.components.values()).find(t=>t.element===e)}generateId(){return`lazy-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}createInitialMetrics(){return{totalComponents:0,activatedComponents:0,pendingComponents:0,cacheHits:0,cacheMisses:0,averageActivationTime:0,idleCallbacksUsed:0}}}class F{constructor(e={}){this.styleRules=new Map,this.customProperties=new Map,this.usageTracker=new Map,this.criticalSelectors=new Set,this.mutationObserver=null,this.config={deduplication:!0,criticalCSS:!0,unusedStyleRemoval:!0,customPropertyOptimization:!0,styleInvalidationTracking:!0,minification:!0,autoprefixer:!1,purgeUnused:!0,...e},this.metrics=this.createInitialMetrics(),this.setupStyleTracking()}async optimizeAll(){performance.now();await this.extractAllStyles(),this.config.deduplication&&this.deduplicateStyles(),this.config.unusedStyleRemoval&&this.removeUnusedStyles(),this.config.customPropertyOptimization&&this.optimizeCustomProperties(),this.config.criticalCSS&&this.extractCriticalCSS();const e=this.generateOptimizedCSS();this.updateMetrics(e);performance.now();return this.metrics}extractCriticalCSS(){const e=[],t=window.innerHeight;return this.getElementsInViewport(t).forEach(t=>{this.getSelectorsForElement(t).forEach(t=>{this.criticalSelectors.add(t);const i=this.styleRules.get(t);i&&(i.critical=!0,e.push(i))})}),this.metrics.criticalRulesExtracted=e.length,this.rulesToCSS(e)}removeUnusedStyles(){if(!this.config.purgeUnused)return;let e=0;this.styleRules.forEach((t,i)=>{if(!t.used&&!t.critical)try{0===document.querySelectorAll(i).length&&(this.styleRules.delete(i),e++)}catch(t){this.styleRules.delete(i),e++}}),this.metrics.rulesRemoved=e}deduplicateStyles(){const e=new Map;let t=0;this.styleRules.forEach((t,i)=>{const s=this.serializeDeclarations(t.declarations);e.has(s)||e.set(s,[]),e.get(s).push(i)}),e.forEach(e=>{if(e.length>1){t+=e.length-1;const i=e[0],s=this.styleRules.get(i),n=e.join(", ");e.forEach(e=>{this.styleRules.delete(e)}),this.styleRules.set(n,{...s,selector:n})}}),this.metrics.duplicatesFound=t}optimizeCustomProperties(){let e=0;this.styleRules.forEach(e=>{e.declarations.forEach((e,t)=>{t.startsWith("--")&&this.customProperties.set(t,e)})}),this.customProperties.forEach((t,i)=>{const s=this.findCustomPropertyUsage(i);if(1===s.length){const n=s[0],r=this.findPropertyUsingCustomProperty(n,i);r&&n&&(n.declarations.set(r,t),n.declarations.delete(i),e++)}}),this.metrics.customPropertiesOptimized=e}trackStyleInvalidations(){if(this.config.styleInvalidationTracking)try{"undefined"!=typeof MutationObserver&&document&&document.body&&(this.mutationObserver=new MutationObserver(e=>{e.forEach(e=>{"attributes"!==e.type||"class"!==e.attributeName&&"style"!==e.attributeName||this.handleStyleInvalidation(e.target)})}),document.body&&this.mutationObserver&&"function"==typeof this.mutationObserver.observe&&this.mutationObserver.observe(document.body,{attributes:!0,attributeFilter:["class","style"],subtree:!0}))}catch(e){t.warn("Failed to setup style invalidation tracking:",e)}}generateOptimizedCSS(){const e=Array.from(this.styleRules.values());return e.sort((e,t)=>e.critical!==t.critical?e.critical?-1:1:e.specificity-t.specificity),this.rulesToCSS(e)}getMetrics(){return{...this.metrics}}clearCache(){this.styleRules.clear(),this.customProperties.clear(),this.usageTracker.clear(),this.criticalSelectors.clear(),this.metrics=this.createInitialMetrics()}destroy(){this.mutationObserver?.disconnect(),this.clearCache()}async extractAllStyles(){const e=this.calculateCurrentCSSSize();this.metrics.originalSize=e;for(const e of document.styleSheets)try{await this.extractFromStylesheet(e)}catch(e){}this.extractInlineStyles()}async extractFromStylesheet(e){try{const t=e.cssRules;for(let e=0;e<t.length;e++){const i=t[e];if(i instanceof CSSStyleRule)this.extractStyleRule(i,"stylesheet");else if(i instanceof CSSMediaRule)for(let e=0;e<i.cssRules.length;e++){const t=i.cssRules[e];t instanceof CSSStyleRule&&this.extractStyleRule(t,"stylesheet")}}}catch(e){}}extractStyleRule(e,t){const i=e.selectorText,s=new Map;for(let t=0;t<e.style.length;t++){const i=e.style[t],n=e.style.getPropertyValue(i);s.set(i,n)}const n={selector:i,declarations:s,specificity:this.calculateSpecificity(i),source:t,used:!1,critical:!1};this.styleRules.set(i,n)}extractInlineStyles(){document.querySelectorAll("[style]").forEach(e=>{const t=e.style,i=new Map;for(let e=0;e<t.length;e++){const s=t[e];if(s){const e=t.getPropertyValue(s);i.set(s,e)}}if(i.size>0){const t=this.generateSelectorForElement(e),s={selector:t,declarations:i,specificity:1e3,source:"inline",used:!0,critical:this.isElementInViewport(e)};this.styleRules.set(t,s)}})}calculateSpecificity(e){let t=0;return t+=100*(e.match(/#/g)||[]).length,t+=10*(e.match(/\.|:|\[/g)||[]).length,t+=(e.match(/[a-zA-Z]/g)||[]).length,t}getElementsInViewport(e){const t=[];return document.querySelectorAll("*").forEach(i=>{this.isElementInViewport(i,e)&&t.push(i)}),t}isElementInViewport(e,t){const i=e.getBoundingClientRect(),s=t||window.innerHeight;return i.top<s&&i.bottom>0}getSelectorsForElement(e){const t=[];return this.styleRules.forEach((i,s)=>{try{e.matches(s)&&(t.push(s),i.used=!0)}catch(e){}}),t}generateSelectorForElement(e){if(e.id)return`#${e.id}`;if(e.className){const t=e.className.split(" ").filter(e=>e.trim());if(t.length>0)return`.${t.join(".")}`}return e.tagName.toLowerCase()}rulesToCSS(e){let t="";return e.forEach(e=>{t+=`${e.selector} {\n`,e.declarations.forEach((e,i)=>{t+=` ${i}: ${e};\n`}),t+="}\n\n"}),this.config.minification&&(t=this.minifyCSS(t)),t}minifyCSS(e){return e.replace(/\s+/g," ").replace(/;\s*}/g,"}").replace(/{\s*/g,"{").replace(/}\s*/g,"}").replace(/:\s*/g,":").replace(/;\s*/g,";").trim()}serializeDeclarations(e){const t=Array.from(e.entries()).sort();return JSON.stringify(t)}findCustomPropertyUsage(e){const t=[];return this.styleRules.forEach(i=>{i.declarations.forEach(s=>{s.includes(`var(${e})`)&&t.push(i)})}),t}findPropertyUsingCustomProperty(e,t){for(const[i,s]of e.declarations)if(s.includes(`var(${t})`))return i;return null}handleStyleInvalidation(e){this.getSelectorsForElement(e).forEach(e=>{const t=this.usageTracker.get(e)||0;this.usageTracker.set(e,t+1)})}calculateCurrentCSSSize(){let e=0;for(const t of document.styleSheets)try{const i=t.cssRules;for(let t=0;t<i.length;t++)e+=i[t].cssText.length}catch(e){}return e}updateMetrics(e){this.metrics.optimizedSize=e.length,this.metrics.compressionRatio=this.metrics.originalSize>0?(this.metrics.originalSize-this.metrics.optimizedSize)/this.metrics.originalSize:0}setupStyleTracking(){this.config.styleInvalidationTracking&&setTimeout(()=>{this.trackStyleInvalidations()},100)}createInitialMetrics(){return{originalSize:0,optimizedSize:0,compressionRatio:0,rulesRemoved:0,duplicatesFound:0,customPropertiesOptimized:0,criticalRulesExtracted:0}}}class B{constructor(e={}){this.resources=new Map,this.cleanupTimer=null,this.performanceObserver=null,this.weakRefs=new Set,this.config={autoCleanup:!0,cleanupInterval:3e4,memoryThreshold:52428800,gcOptimization:!0,leakDetection:!0,performanceMonitoring:!0,...e},this.metrics=this.createInitialMetrics(),this.setupMemoryMonitoring(),this.startAutoCleanup()}register(e,t,i,s=1024){const n=this.generateResourceId(),r={id:n,type:e,...i&&{element:i},cleanup:t,timestamp:performance.now(),lastAccessed:performance.now(),memorySize:s};return this.resources.set(n,r),this.updateMetrics(e,"register"),i&&this.config.leakDetection&&this.weakRefs.add(new WeakRef(i)),n}unregister(e){const t=this.resources.get(e);if(t){try{t.cleanup(),this.updateMetrics(t.type,"unregister")}catch(e){}this.resources.delete(e),this.metrics.cleanupOperations++}}registerResizeObserver(e,t){return this.register("observer",()=>{e.disconnect()},t[0],512*t.length)}registerIntersectionObserver(e,t){return this.register("observer",()=>{e.disconnect()},t[0],256*t.length)}registerEventListener(e,t,i,s){return this.register("listener",()=>{e.removeEventListener(t,i,s)},e,128)}registerTimer(e,t="timeout"){return this.register("timer",()=>{"timeout"===t?clearTimeout(e):clearInterval(e)},void 0,64)}registerAnimation(e){return this.register("animation",()=>{e.cancel()},e.effect?.target instanceof Element?e.effect.target:void 0,256)}registerCacheEntry(e,t,i=1024){return this.register("cache",()=>{e.delete(t)},void 0,i)}cleanup(){Array.from(this.resources.keys()).forEach(e=>this.unregister(e))}cleanupByType(e){Array.from(this.resources.entries()).filter(([,t])=>t.type===e).map(([e])=>e).forEach(e=>this.unregister(e))}cleanupStale(e=3e5){const t=performance.now();Array.from(this.resources.entries()).filter(([,i])=>t-i.lastAccessed>e).map(([e])=>e).forEach(e=>this.unregister(e))}cleanupOrphanedResources(){const e=[];this.resources.forEach((t,i)=>{t.element&&!document.contains(t.element)&&e.push(i)}),e.forEach(e=>this.unregister(e))}getMetrics(){return this.updateMemoryUsage(),{...this.metrics}}getResourceCount(e){return e?Array.from(this.resources.values()).filter(t=>t.type===e).length:this.resources.size}detectLeaks(){const e=[];this.weakRefs.forEach(e=>{void 0===e.deref()&&this.cleanupOrphanedResources()});const t=new Map;return this.resources.forEach(e=>{const i=t.get(e.type)||0;t.set(e.type,i+1)}),t.forEach((t,i)=>{const s=this.getThresholdForType(i);t>s&&e.push(`Excessive ${i} resources: ${t} (threshold: ${s})`)}),this.metrics.leaksDetected=e.length,e}optimizeGC(){if(!this.config.gcOptimization)return;this.cleanupStale();const e=new Set;this.weakRefs.forEach(t=>{void 0!==t.deref()&&e.add(t)}),this.weakRefs=e,"gc"in window&&"function"==typeof window.gc&&(window.gc(),this.metrics.gcCollections++)}destroy(){this.stopAutoCleanup(),this.stopMemoryMonitoring(),this.cleanup(),this.weakRefs.clear()}setupMemoryMonitoring(){if(this.config.performanceMonitoring&&("memory"in performance&&setInterval(()=>{this.updateMemoryUsage(),this.checkMemoryThreshold()},5e3),window.PerformanceObserver))try{this.performanceObserver=new PerformanceObserver(e=>{e.getEntries().forEach(e=>{"measure"===e.entryType&&e.name.includes("proteus")})}),this.performanceObserver.observe({entryTypes:["measure","navigation"]})}catch(e){}}startAutoCleanup(){this.config.autoCleanup&&(this.cleanupTimer=window.setInterval(()=>{this.cleanupStale(),this.cleanupOrphanedResources(),this.detectLeaks(),this.config.gcOptimization&&this.optimizeGC()},this.config.cleanupInterval))}stopAutoCleanup(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null)}stopMemoryMonitoring(){this.performanceObserver&&(this.performanceObserver.disconnect(),this.performanceObserver=null)}updateMemoryUsage(){if("memory"in performance){const e=performance.memory;this.metrics.memoryUsage=e.usedJSHeapSize||0}}checkMemoryThreshold(){this.metrics.memoryUsage>this.config.memoryThreshold&&(this.cleanupStale(6e4),this.optimizeGC())}updateMetrics(e,t){switch(e){case"observer":"register"===t?(this.metrics.totalObservers++,this.metrics.activeObservers++):this.metrics.activeObservers--;break;case"listener":"register"===t?(this.metrics.totalEventListeners++,this.metrics.activeEventListeners++):this.metrics.activeEventListeners--}}getThresholdForType(e){return{observer:100,listener:500,timer:50,animation:20,cache:1e3}[e]||100}generateResourceId(){return`mem-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}createInitialMetrics(){return{totalObservers:0,activeObservers:0,totalEventListeners:0,activeEventListeners:0,memoryUsage:0,gcCollections:0,leaksDetected:0,cleanupOperations:0}}}class D{constructor(e={}){this.cache=new Map,this.accessOrder=[],this.cleanupTimer=null,this.config={maxSize:100,maxAge:3e5,memoryThreshold:10485760,evictionStrategy:"adaptive",compressionEnabled:!0,persistentStorage:!1,storageKey:"proteus-cache",...e},this.metrics=this.createInitialMetrics(),this.loadFromStorage(),this.startCleanupTimer()}get(e){const t=this.cache.get(e);if(!t)return this.metrics.missRate++,null;if(t.ttl&&Date.now()>t.timestamp+t.ttl)return this.delete(e),this.metrics.missRate++,null;t.lastAccessed=Date.now(),t.accessCount++,this.updateAccessOrder(e),this.metrics.hitRate++;let i=t.value;return t.compressed&&this.config.compressionEnabled&&(i=this.decompress(i)),i}set(e,t,i){this.cache.size>=this.config.maxSize&&this.evictEntries(1);let s=t,n=!1;this.config.compressionEnabled&&this.shouldCompress(t)&&(s=this.compress(t),n=!0);const r=this.calculateSize(s),o={key:e,value:s,timestamp:Date.now(),lastAccessed:Date.now(),accessCount:1,size:r,...void 0!==i&&{ttl:i},compressed:n};this.cache.has(e)&&this.delete(e),this.cache.set(e,o),this.updateAccessOrder(e),this.updateMetrics(),this.checkMemoryPressure()}delete(e){const t=this.cache.delete(e);return t&&(this.removeFromAccessOrder(e),this.updateMetrics()),t}has(e){const t=this.cache.get(e);return!!t&&(!(t.ttl&&Date.now()>t.timestamp+t.ttl)||(this.delete(e),!1))}clear(){this.cache.clear(),this.accessOrder=[],this.updateMetrics()}getMetrics(){return{...this.metrics}}cacheCalculation(e,t,i){const s=this.generateKey("calc",t);let n=this.get(s);return null===n&&(n=e(),this.set(s,n,i)),n}cacheLayoutMeasurement(e,t,i=1e3){const s=this.generateKey("layout",[e.tagName,e.className,e.id||"no-id"]);let n=this.get(s);return null===n&&(n=t(),this.set(s,n,i)),n}cacheContainerState(e,t,i=5e3){const s=this.generateKey("container",[e]);this.set(s,t,i)}getCachedContainerState(e){const t=this.generateKey("container",[e]);return this.get(t)}cacheComputedStyles(e,t,i=2e3){const s=this.generateKey("styles",[e.tagName,e.className,t.join(",")]);let n=this.get(s);if(null===n){n=window.getComputedStyle(e);const r={};return t.forEach(e=>{r[e]=n.getPropertyValue(e)}),this.set(s,r,i),r}return n}optimize(){this.removeExpiredEntries(),this.checkMemoryPressure(),this.compressLargeEntries(),this.updateMetrics()}destroy(){this.stopCleanupTimer(),this.saveToStorage(),this.clear()}evictEntries(e){let t=[];switch(this.config.evictionStrategy){case"lru":t=this.getLRUKeys(e);break;case"lfu":t=this.getLFUKeys(e);break;case"ttl":t=this.getTTLKeys(e);break;case"adaptive":t=this.getAdaptiveKeys(e)}t.forEach(e=>{this.delete(e),this.metrics.evictions++})}getLRUKeys(e){return this.accessOrder.slice(0,e)}getLFUKeys(e){const t=Array.from(this.cache.entries());return t.sort((e,t)=>e[1].accessCount-t[1].accessCount),t.slice(0,e).map(([e])=>e)}getTTLKeys(e){const t=Array.from(this.cache.entries());return t.sort((e,t)=>e[1].timestamp-t[1].timestamp),t.slice(0,e).map(([e])=>e)}getAdaptiveKeys(e){const t=Array.from(this.cache.entries());return t.forEach(([e,t])=>{const i=Date.now()-t.lastAccessed,s=t.accessCount,n=t.size;t.score=i/1e3+n/1024-10*s}),t.sort((e,t)=>t[1].score-e[1].score),t.slice(0,e).map(([e])=>e)}checkMemoryPressure(){if(this.getTotalSize()>this.config.memoryThreshold){const e=Math.ceil(.2*this.cache.size);this.evictEntries(e)}}removeExpiredEntries(){const e=Date.now(),t=[];this.cache.forEach((i,s)=>{(i.ttl?e>i.timestamp+i.ttl:e>i.timestamp+this.config.maxAge)&&t.push(s)}),t.forEach(e=>this.delete(e))}compressLargeEntries(){this.config.compressionEnabled&&this.cache.forEach((e,t)=>{if(!e.compressed&&e.size>1024){const t=this.compress(e.value),i=this.calculateSize(t);i<.8*e.size&&(e.value=t,e.size=i,e.compressed=!0)}})}updateAccessOrder(e){this.removeFromAccessOrder(e),this.accessOrder.push(e)}removeFromAccessOrder(e){const t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1)}generateKey(e,t){return`${e}:${t.join(":")}`}calculateSize(e){if("string"==typeof e)return 2*e.length;try{return 2*JSON.stringify(e).length}catch{return 1024}}getTotalSize(){let e=0;return this.cache.forEach(t=>{e+=t.size}),e}shouldCompress(e){return this.calculateSize(e)>512}compress(e){return{__compressed:!0,data:JSON.stringify(e)}}decompress(e){return e&&e.__compressed?JSON.parse(e.data):e}updateMetrics(){this.metrics.totalEntries=this.cache.size,this.metrics.totalSize=this.getTotalSize();const e=this.metrics.hitRate+this.metrics.missRate;e>0&&(this.metrics.hitRate=this.metrics.hitRate/e,this.metrics.missRate=this.metrics.missRate/e);let t=0,i=0,s=0;this.cache.forEach(e=>{e.compressed&&(s++,i+=e.size,t+=e.size/.5)}),s>0&&t>0&&(this.metrics.compressionRatio=i/t)}startCleanupTimer(){this.cleanupTimer=window.setInterval(()=>{this.optimize()},3e4)}stopCleanupTimer(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null)}loadFromStorage(){if(this.config.persistentStorage)try{const e=localStorage.getItem(this.config.storageKey);if(e){JSON.parse(e).forEach(e=>{this.cache.set(e.key,e),this.accessOrder.push(e.key)})}}catch(e){}}saveToStorage(){if(this.config.persistentStorage)try{const e=Array.from(this.cache.values());localStorage.setItem(this.config.storageKey,JSON.stringify(e))}catch(e){}}createInitialMetrics(){return{totalEntries:0,totalSize:0,hitRate:0,missRate:0,evictions:0,compressionRatio:0}}}class N{constructor(e={}){this.mediaQueries=new Map,this.observers=new Set,this.handleMediaQueryChange=()=>{this.updateStateFromMediaQueries(),this.config.respectSystemPreference&&!this.state.userPreference&&(this.state.currentScheme=this.state.systemPreference,this.applyTheme()),this.notifyObservers()},this.config={autoDetect:!0,respectSystemPreference:!0,adaptiveContrast:!0,colorSchemes:N.DEFAULT_SCHEMES,transitions:!0,transitionDuration:300,storage:"localStorage",storageKey:"proteus-theme",...e},this.state=this.createInitialState(),this.setupMediaQueries(),this.loadStoredPreference(),this.applyInitialTheme()}setScheme(e){this.config.colorSchemes[e]&&(this.state.currentScheme=e,this.state.userPreference=e,this.applyTheme(),this.savePreference(),this.notifyObservers())}toggle(){const e=this.config.colorSchemes[this.state.currentScheme];e&&"light"===e.type?this.setScheme("dark"):this.setScheme("light")}setContrast(e){this.state.contrastLevel=e,"high"===e&&this.config.colorSchemes.highContrast?this.setScheme("highContrast"):this.applyContrastAdjustments(),this.notifyObservers()}getState(){return{...this.state}}getCurrentScheme(){const e=this.config.colorSchemes[this.state.currentScheme];if(!e)throw new Error(`Color scheme '${this.state.currentScheme}' not found`);return e}observe(e){return this.observers.add(e),()=>{this.observers.delete(e)}}addScheme(e){this.config.colorSchemes[e.name.toLowerCase()]=e}removeScheme(e){e!==this.state.currentScheme&&delete this.config.colorSchemes[e]}getAvailableSchemes(){return Object.values(this.config.colorSchemes)}applyTheme(){const e=this.getCurrentScheme();this.applyCSSProperties(e),this.applyThemeClass(e),this.config.transitions&&this.applyTransitions(),this.applyAccessibilityEnhancements(e)}resetToSystem(){this.state.userPreference=null,this.state.currentScheme=this.state.systemPreference,this.applyTheme(),this.savePreference(),this.notifyObservers()}destroy(){this.mediaQueries.forEach(e=>{e.removeEventListener("change",this.handleMediaQueryChange)}),this.mediaQueries.clear(),this.observers.clear()}setupMediaQueries(){if("undefined"==typeof window||"function"!=typeof window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)");this.mediaQueries.set("dark-mode",e),e.addEventListener("change",this.handleMediaQueryChange.bind(this));const t=window.matchMedia("(prefers-contrast: high)");this.mediaQueries.set("high-contrast",t),t.addEventListener("change",this.handleMediaQueryChange.bind(this));const i=window.matchMedia("(prefers-reduced-motion: reduce)");this.mediaQueries.set("reduced-motion",i),i.addEventListener("change",this.handleMediaQueryChange.bind(this)),this.updateStateFromMediaQueries()}updateStateFromMediaQueries(){const e=this.mediaQueries.get("dark-mode"),t=this.mediaQueries.get("high-contrast"),i=this.mediaQueries.get("reduced-motion");this.state.systemPreference=e?.matches?"dark":"light",this.state.highContrast=t?.matches||!1,this.state.reducedMotion=i?.matches||!1,this.state.highContrast&&this.config.adaptiveContrast&&(this.state.contrastLevel="high")}applyCSSProperties(e){try{const i=document.documentElement;if(!i||!i.style||"function"!=typeof i.style.setProperty)return void t.warn("CSS custom properties not supported in this environment");Object.entries(e.colors).forEach(([e,t])=>{i.style.setProperty(`--proteus-${e}`,t)}),i.style.setProperty("--proteus-min-contrast",e.accessibility.minContrast.toString()),i.style.setProperty("--proteus-focus-indicator",e.accessibility.focusIndicator)}catch(e){t.warn("Failed to apply CSS custom properties:",e)}}applyThemeClass(e){const t=document.body;t.classList.remove("proteus-light","proteus-dark","proteus-high-contrast"),t.classList.add(`proteus-${e.type}`),"high"===e.contrast&&t.classList.add("proteus-high-contrast"),this.state.reducedMotion?t.classList.add("proteus-reduced-motion"):t.classList.remove("proteus-reduced-motion")}applyTransitions(){if(this.state.reducedMotion)return;const e=document.createElement("style");e.id="proteus-theme-transitions";const t=document.getElementById("proteus-theme-transitions");t&&t.remove(),e.textContent=`\n * {\n transition: \n background-color ${this.config.transitionDuration}ms ease,\n color ${this.config.transitionDuration}ms ease,\n border-color ${this.config.transitionDuration}ms ease,\n box-shadow ${this.config.transitionDuration}ms ease !important;\n }\n `,document.head.appendChild(e),setTimeout(()=>{e.remove()},this.config.transitionDuration+100)}applyAccessibilityEnhancements(e){const t=document.createElement("style");t.id="proteus-accessibility-enhancements";const i=document.getElementById("proteus-accessibility-enhancements");i&&i.remove(),t.textContent=`\n :focus {\n outline: 2px solid var(--proteus-focus-indicator) !important;\n outline-offset: 2px !important;\n }\n \n .proteus-high-contrast {\n filter: contrast(${"high"===e.contrast?"150%":"100%"});\n }\n \n .proteus-reduced-motion * {\n animation-duration: 0.01ms !important;\n animation-iteration-count: 1 !important;\n transition-duration: 0.01ms !important;\n }\n `,document.head.appendChild(t)}applyContrastAdjustments(){const e=this.getCurrentScheme(),t={...e};"high"===this.state.contrastLevel?t.colors=this.adjustColorsForHighContrast(e.colors):"low"===this.state.contrastLevel&&(t.colors=this.adjustColorsForLowContrast(e.colors)),this.applyCSSProperties(t)}adjustColorsForHighContrast(e){const t={...e};return"#ffffff"===e.background?(t.text="#000000",t.textSecondary="#333333"):(t.text="#ffffff",t.textSecondary="#cccccc"),t}adjustColorsForLowContrast(e){const t={...e};return"#ffffff"===e.background?(t.text="#444444",t.textSecondary="#666666"):(t.text="#dddddd",t.textSecondary="#aaaaaa"),t}loadStoredPreference(){if("none"!==this.config.storage)try{const e=("localStorage"===this.config.storage?localStorage:sessionStorage).getItem(this.config.storageKey);if(e){const t=JSON.parse(e);this.state.userPreference=t.scheme,this.state.contrastLevel=t.contrast||"normal"}}catch(e){}}savePreference(){if("none"!==this.config.storage)try{const e="localStorage"===this.config.storage?localStorage:sessionStorage,t={scheme:this.state.userPreference,contrast:this.state.contrastLevel};e.setItem(this.config.storageKey,JSON.stringify(t))}catch(e){}}applyInitialTheme(){this.state.userPreference&&this.config.colorSchemes[this.state.userPreference]?this.state.currentScheme=this.state.userPreference:this.config.autoDetect?this.state.currentScheme=this.state.systemPreference:this.state.currentScheme="light",this.applyTheme()}notifyObservers(){this.observers.forEach(e=>{try{e(this.state)}catch(e){}})}createInitialState(){return{currentScheme:"light",systemPreference:"light",userPreference:null,contrastLevel:"normal",reducedMotion:!1,highContrast:!1}}}N.DEFAULT_SCHEMES={light:{name:"Light",type:"light",colors:{primary:"#007bff",secondary:"#6c757d",success:"#28a745",danger:"#dc3545",warning:"#ffc107",info:"#17a2b8",background:"#ffffff",surface:"#f8f9fa",text:"#212529",textSecondary:"#6c757d",border:"#dee2e6"},contrast:"normal",accessibility:{minContrast:4.5,largeTextContrast:3,focusIndicator:"#005cbf"}},dark:{name:"Dark",type:"dark",colors:{primary:"#0d6efd",secondary:"#6c757d",success:"#198754",danger:"#dc3545",warning:"#fd7e14",info:"#0dcaf0",background:"#121212",surface:"#1e1e1e",text:"#ffffff",textSecondary:"#adb5bd",border:"#495057"},contrast:"normal",accessibility:{minContrast:4.5,largeTextContrast:3,focusIndicator:"#4dabf7"}},highContrast:{name:"High Contrast",type:"light",colors:{primary:"#0000ff",secondary:"#000000",success:"#008000",danger:"#ff0000",warning:"#ff8c00",info:"#0000ff",background:"#ffffff",surface:"#ffffff",text:"#000000",textSecondary:"#000000",border:"#000000"},contrast:"high",accessibility:{minContrast:7,largeTextContrast:4.5,focusIndicator:"#ff0000"}}};class q{constructor(e={}){this.activeAnimations=new Map,this.animationQueue=[],this.isProcessing=!1,this.config={duration:300,easing:"cubic-bezier(0.4, 0.0, 0.2, 1)",respectMotionPreference:!0,batchAnimations:!0,performanceMode:"auto",maxConcurrentAnimations:10,...e}}async animate(e,t,i={}){const s={...this.config,...i};if(this.shouldSkipAnimation())return void t();const n=e.getBoundingClientRect();t();const r=e.getBoundingClientRect(),o=this.calculateInvert(n,r);return 0!==o.x||0!==o.y||1!==o.scaleX||1!==o.scaleY?this.playAnimation(e,o,s):void 0}async animateBatch(e){if(!this.config.batchAnimations){for(const t of e)await this.animate(t.element,t.newPosition,t.options);return}const t=e.map(e=>({element:e.element,first:e.element.getBoundingClientRect(),newPosition:e.newPosition,options:e.options||{}}));t.forEach(e=>e.newPosition());const i=t.map(e=>{const t=e.element.getBoundingClientRect(),i=this.calculateInvert(e.first,t);if(0===i.x&&0===i.y&&1===i.scaleX&&1===i.scaleY)return Promise.resolve();const s={...this.config,...e.options};return this.playAnimation(e.element,i,s)});await Promise.all(i)}cancel(e){const t=this.activeAnimations.get(e);t?.player&&(t.player.cancel(),this.activeAnimations.delete(e))}cancelAll(){this.activeAnimations.forEach((e,t)=>{this.cancel(t)})}getActiveCount(){return this.activeAnimations.size}isAnimating(e){return this.activeAnimations.has(e)}destroy(){this.cancelAll(),this.animationQueue=[]}calculateInvert(e,t){return{x:e.left-t.left,y:e.top-t.top,scaleX:e.width/t.width,scaleY:e.height/t.height}}async playAnimation(e,t,i){return new Promise((s,n)=>{const r=e,o=`translate(${t.x}px, ${t.y}px) scale(${t.scaleX}, ${t.scaleY})`;r.style.transform=o;const a=r.animate([{transform:o},{transform:"translate(0, 0) scale(1, 1)"}],{duration:i.duration,easing:i.easing,fill:"forwards"}),c={element:e,first:{x:0,y:0,width:0,height:0},last:{x:0,y:0,width:0,height:0},invert:t,player:a};this.activeAnimations.set(e,c),a.addEventListener("finish",()=>{r.style.transform="",this.activeAnimations.delete(e),s()}),a.addEventListener("cancel",()=>{r.style.transform="",this.activeAnimations.delete(e),n(new Error("Animation cancelled"))})})}shouldSkipAnimation(){if(this.config.respectMotionPreference){if(window.matchMedia("(prefers-reduced-motion: reduce)").matches)return!0}return"performance"===this.config.performanceMode&&this.activeAnimations.size>=this.config.maxConcurrentAnimations}}class U{static addHover(e,t={}){const i={...U.INTERACTIONS.hover,...t},s=e;s.addEventListener("mouseenter",()=>{s.style.transition=`transform ${i.duration}ms ${i.easing}`,s.style.transform=`scale(${i.scale})`}),s.addEventListener("mouseleave",()=>{s.style.transform="scale(1)"})}static addPress(e,t={}){const i={...U.INTERACTIONS.press,...t},s=e;s.addEventListener("mousedown",()=>{s.style.transition=`transform ${i.duration}ms ${i.easing}`,s.style.transform=`scale(${i.scale})`}),s.addEventListener("mouseup",()=>{s.style.transform="scale(1)"}),s.addEventListener("mouseleave",()=>{s.style.transform="scale(1)"})}static addFocus(e,t={}){const i={...U.INTERACTIONS.focus,...t},s=e;s.addEventListener("focus",()=>{s.style.transition=`transform ${i.duration}ms ${i.easing}`,s.style.transform=`scale(${i.scale})`}),s.addEventListener("blur",()=>{s.style.transform="scale(1)"})}static addRipple(e,t="rgba(255, 255, 255, 0.3)"){const i=e;i.style.position="relative",i.style.overflow="hidden",i.addEventListener("click",e=>{const s=i.getBoundingClientRect(),n=Math.max(s.width,s.height),r=e.clientX-s.left-n/2,o=e.clientY-s.top-n/2,a=document.createElement("div");if(a.style.cssText=`\n position: absolute;\n width: ${n}px;\n height: ${n}px;\n left: ${r}px;\n top: ${o}px;\n background: ${t};\n border-radius: 50%;\n transform: scale(0);\n animation: ripple 600ms ease-out;\n pointer-events: none;\n `,!document.getElementById("ripple-animation")){const e=document.createElement("style");e.id="ripple-animation",e.textContent="\n @keyframes ripple {\n to {\n transform: scale(4);\n opacity: 0;\n }\n }\n ",document.head.appendChild(e)}i.appendChild(a),setTimeout(()=>{a.remove()},600)})}}U.INTERACTIONS={hover:{scale:1.05,duration:200,easing:"ease-out"},press:{scale:.95,duration:100,easing:"ease-in"},focus:{scale:1.02,duration:150,easing:"ease-out"}};class H{constructor(){this.observer=null,this.animations=new Map,this.setupIntersectionObserver()}addAnimation(e,t,i={}){this.animations.set(e,t),this.observer&&this.observer.observe(e)}removeAnimation(e){this.animations.delete(e),this.observer&&this.observer.unobserve(e)}destroy(){this.observer?.disconnect(),this.animations.clear()}setupIntersectionObserver(){window.IntersectionObserver&&(this.observer=new IntersectionObserver(e=>{e.forEach(e=>{if(e.isIntersecting){const t=this.animations.get(e.target);t&&(t(),this.removeAnimation(e.target))}})},{threshold:.1,rootMargin:"50px"}))}static fadeIn(e,t=600){const i=e;i.style.opacity="0",i.style.transition=`opacity ${t}ms ease-in-out`,requestAnimationFrame(()=>{i.style.opacity="1"})}static slideUp(e,t=600){const i=e;i.style.transform="translateY(50px)",i.style.opacity="0",i.style.transition=`transform ${t}ms ease-out, opacity ${t}ms ease-out`,requestAnimationFrame(()=>{i.style.transform="translateY(0)",i.style.opacity="1"})}static scaleIn(e,t=600){const i=e;i.style.transform="scale(0.8)",i.style.opacity="0",i.style.transition=`transform ${t}ms ease-out, opacity ${t}ms ease-out`,requestAnimationFrame(()=>{i.style.transform="scale(1)",i.style.opacity="1"})}}class j{constructor(e={}){this.detectedContainers=new Map,this.observer=null,this.config={autoDetectContainers:!0,intelligentBreakpoints:!0,autoTypographyScaling:!0,performanceOptimization:!0,accessibilityOptimization:!0,autoThemeDetection:!0,responsiveImages:!0,lazyLoading:!0,...e},this.appliedOptimizations={performance:[],accessibility:[],typography:[],layout:[]}}async initialize(){this.config.autoDetectContainers&&await this.detectContainers(),this.config.intelligentBreakpoints&&await this.setupIntelligentBreakpoints(),this.config.autoTypographyScaling&&await this.setupTypographyScaling(),this.config.performanceOptimization&&await this.applyPerformanceOptimizations(),this.config.accessibilityOptimization&&await this.applyAccessibilityOptimizations(),this.config.autoThemeDetection&&await this.setupAutoTheme(),this.config.responsiveImages&&await this.optimizeImages(),this.setupContinuousOptimization(),this.logOptimizations()}async detectContainers(){const e=document.querySelectorAll("*"),t=[];e.forEach(e=>{const i=this.analyzeElement(e);i&&(t.push(i),this.detectedContainers.set(e,i))}),t.sort((e,t)=>{const i={high:3,normal:2,low:1},s=i[t.priority]-i[e.priority];return 0!==s?s:t.confidence-e.confidence})}analyzeElement(e){const t=window.getComputedStyle(e),i=e.children.length,s=e.getBoundingClientRect();if(s.width<100||s.height<50||0===i)return null;let n="block",r=0,o="normal";return"grid"===t.display?(n="grid",r+=.4):"flex"===t.display?(n="flex",r+=.3):"inline-block"!==t.display&&"inline-flex"!==t.display||(n="inline",r+=.2),i>=3&&(r+=.2),s.width>300&&(r+=.1),e.classList.length>0&&(r+=.1),e.id&&(r+=.1),e.matches("main, .main, #main, .container, .wrapper")?(o="high",r+=.2):e.matches("section, article, aside, nav, header, footer")&&(o="normal",r+=.1),r<.3?null:{element:e,type:n,suggestedBreakpoints:this.generateBreakpoints(s.width),priority:o,confidence:r}}generateBreakpoints(e){const t={},i=["xs","sm","md","lg","xl"];return[.618,.8,1,1.2,1.618].forEach((s,n)=>{const r=Math.round(e*s);if(r>=200&&r<=1920){const e=i[n];e&&(t[e]=`${r}px`)}}),t}async setupIntelligentBreakpoints(){this.detectedContainers.forEach((e,t)=>{const i=this.generateClassName(t);t.classList.add(i),this.generateBreakpointCSS(i,e.suggestedBreakpoints)}),this.appliedOptimizations.layout.push("Intelligent breakpoints applied")}async setupTypographyScaling(){document.querySelectorAll("h1, h2, h3, h4, h5, h6, p, span, div").forEach(e=>{const t=this.findParentContainer(e);t&&this.applyFluidTypography(e,t)}),this.appliedOptimizations.typography.push("Fluid typography scaling applied")}async applyPerformanceOptimizations(){this.enablePassiveListeners(),this.config.responsiveImages&&this.optimizeImages(),this.config.lazyLoading&&this.enableLazyLoading(),this.appliedOptimizations.performance.push("Passive event listeners","Image optimization","Lazy loading")}async applyAccessibilityOptimizations(){this.addMissingAriaLabels(),this.improveFocusIndicators(),this.validateHeadingHierarchy(),this.addSkipLinks(),this.appliedOptimizations.accessibility.push("ARIA labels added","Focus indicators improved","Heading hierarchy validated","Skip links added")}async setupAutoTheme(){const e=window.matchMedia("(prefers-color-scheme: dark)").matches,t=window.matchMedia("(prefers-contrast: high)").matches;e&&document.body.classList.add("proteus-dark"),t&&document.body.classList.add("proteus-high-contrast"),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",e=>{document.body.classList.toggle("proteus-dark",e.matches)})}async optimizeImages(){document.querySelectorAll("img").forEach(e=>{if(e.hasAttribute("loading")||e.setAttribute("loading","lazy"),e.hasAttribute("decoding")||e.setAttribute("decoding","async"),!e.hasAttribute("sizes")&&!e.hasAttribute("srcset")){const t=this.findParentContainer(e);t&&this.addResponsiveImageAttributes(e,t)}})}enableLazyLoading(){return new Promise(e=>{if("IntersectionObserver"in window){const e=new IntersectionObserver(t=>{t.forEach(t=>{if(t.isIntersecting){const i=t.target;i.classList.add("proteus-loaded"),e.unobserve(i)}})});document.querySelectorAll("img, video, iframe").forEach(t=>{e.observe(t)})}e()})}setupContinuousOptimization(){this.observer=new MutationObserver(e=>{e.forEach(e=>{"childList"===e.type&&e.addedNodes.forEach(e=>{e.nodeType===Node.ELEMENT_NODE&&this.optimizeNewElement(e)})})}),this.observer.observe(document.body,{childList:!0,subtree:!0})}optimizeNewElement(e){const t=this.analyzeElement(e);if(t&&(this.detectedContainers.set(e,t),this.config.intelligentBreakpoints)){const i=this.generateClassName(e);e.classList.add(i),this.generateBreakpointCSS(i,t.suggestedBreakpoints)}if(this.config.responsiveImages){e.querySelectorAll("img").forEach(e=>this.optimizeImages())}this.config.accessibilityOptimization&&this.addMissingAriaLabels(e)}generateClassName(e){const t=e.id||"",i=Array.from(e.classList).join("-");return`proteus-${e.tagName.toLowerCase()}-${t||i||Math.random().toString(36).substring(2,11)}`}generateBreakpointCSS(e,t){let i="";Object.entries(t).forEach(([t,s])=>{i+=`\n .${e} {\n container-type: inline-size;\n }\n @container (min-width: ${s}) {\n .${e} {\n --proteus-breakpoint: ${t};\n }\n }\n `});const s=document.createElement("style");s.textContent=i,document.head.appendChild(s)}findParentContainer(e){let t=e.parentElement;for(;t;){const e=this.detectedContainers.get(t);if(e)return e;t=t.parentElement}return null}applyFluidTypography(e,t){const i=e,s=parseFloat(window.getComputedStyle(e).fontSize),n=Math.max(.8*s,12),r=1.5*s;i.style.fontSize=`clamp(${n}px, 4cw, ${r}px)`}enablePassiveListeners(){const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,i,s){return["scroll","wheel","touchstart","touchmove"].includes(t)&&"object"!=typeof s&&(s={passive:!0}),e.call(this,t,i,s)}}addMissingAriaLabels(e=document.body){e.querySelectorAll("button:not([aria-label]):not([aria-labelledby])").forEach(e=>{e.textContent?.trim()||e.setAttribute("aria-label","Button")});e.querySelectorAll("input:not([aria-label]):not([aria-labelledby])").forEach(e=>{const t=e.getAttribute("type")||"text";e.setAttribute("aria-label",`${t} input`)})}improveFocusIndicators(){const e=document.createElement("style");e.textContent="\n *:focus {\n outline: 2px solid #4A90E2 !important;\n outline-offset: 2px !important;\n }\n .proteus-focus-visible:focus-visible {\n outline: 3px solid #4A90E2 !important;\n outline-offset: 2px !important;\n }\n ",document.head.appendChild(e)}validateHeadingHierarchy(){const e=document.querySelectorAll("h1, h2, h3, h4, h5, h6");let t=0;e.forEach(e=>{const i=parseInt(e.tagName.charAt(1));t=i})}addSkipLinks(){if(document.querySelector('main, [role="main"], #main')&&!document.querySelector(".proteus-skip-link")){const e=document.createElement("a");e.href="#main",e.textContent="Skip to main content",e.className="proteus-skip-link",e.style.cssText="\n position: absolute;\n top: -40px;\n left: 6px;\n background: #000;\n color: #fff;\n padding: 8px;\n text-decoration: none;\n z-index: 1000;\n ",e.addEventListener("focus",()=>{e.style.top="6px"}),e.addEventListener("blur",()=>{e.style.top="-40px"}),document.body.insertBefore(e,document.body.firstChild)}}addResponsiveImageAttributes(e,t){const i=Object.values(t.suggestedBreakpoints),s=i.map((e,t)=>{const s=parseInt(e);return t===i.length-1?`${s}px`:`(max-width: ${s}px) ${s}px`}).join(", ");e.setAttribute("sizes",s)}logOptimizations(){Object.entries(this.appliedOptimizations).forEach(([e,t])=>{t.length>0&&t.forEach(e=>{})})}getOptimizationReport(){return{containers:this.detectedContainers.size,optimizations:this.appliedOptimizations,detectedContainers:Array.from(this.detectedContainers.values())}}destroy(){this.observer?.disconnect(),this.detectedContainers.clear()}}class Q{constructor(){this.polyfillsLoaded=new Set}static getInstance(){return Q.instance||(Q.instance=new Q),Q.instance}async loadPolyfills(e={}){const i={resizeObserver:!0,intersectionObserver:!0,customProperties:!0,cssSupports:!0,requestAnimationFrame:!0,performance:!0,classList:!0,closest:!0,matchMedia:!0,mutationObserver:!0,...e};t.info("Loading ProteusJS polyfills..."),i.performance&&await this.loadPerformancePolyfill(),i.requestAnimationFrame&&await this.loadRAFPolyfill(),i.classList&&await this.loadClassListPolyfill(),i.closest&&await this.loadClosestPolyfill(),i.cssSupports&&await this.loadCSSSupportsPolyfill(),i.customProperties&&await this.loadCustomPropertiesPolyfill(),i.matchMedia&&await this.loadMatchMediaPolyfill(),i.mutationObserver&&await this.loadMutationObserverPolyfill(),i.resizeObserver&&await this.loadResizeObserverPolyfill(),i.intersectionObserver&&await this.loadIntersectionObserverPolyfill(),t.info(`Loaded ${this.polyfillsLoaded.size} polyfills`)}checkBrowserSupport(){const e=[],t=[],i=[];"undefined"!=typeof ResizeObserver?e.push("ResizeObserver"):t.push("ResizeObserver"),"undefined"!=typeof IntersectionObserver?e.push("IntersectionObserver"):t.push("IntersectionObserver"),this.supportsCSSCustomProperties()?e.push("CSS Custom Properties"):t.push("CSS Custom Properties"),"undefined"!=typeof CSS&&"function"==typeof CSS.supports?e.push("CSS.supports"):t.push("CSS.supports"),"undefined"!=typeof performance&&"function"==typeof performance.now?e.push("Performance API"):t.push("Performance API"),"undefined"!=typeof window&&"function"==typeof window.matchMedia?e.push("matchMedia"):t.push("matchMedia"),"undefined"!=typeof window&&"function"==typeof window.MutationObserver?e.push("MutationObserver"):t.push("MutationObserver");const s=navigator.userAgent;return(s.includes("MSIE")||s.includes("Trident"))&&i.push("Internet Explorer detected - limited support"),s.includes("Safari")&&!s.includes("Chrome")&&i.push("Safari detected - some features may need polyfills"),{supported:e,missing:t,warnings:i}}async loadResizeObserverPolyfill(){"undefined"==typeof ResizeObserver&&(window.ResizeObserver=class{constructor(e){this.elements=new Set,this.rafId=null,this.callback=e}observe(e){this.elements.add(e),this.startPolling()}unobserve(e){this.elements.delete(e),0===this.elements.size&&this.stopPolling()}disconnect(){this.elements.clear(),this.stopPolling()}startPolling(){if(this.rafId)return;const e=()=>{const t=[];this.elements.forEach(e=>{const i=e.getBoundingClientRect();t.push({target:e,contentRect:i,borderBoxSize:[{inlineSize:i.width,blockSize:i.height}],contentBoxSize:[{inlineSize:i.width,blockSize:i.height}],devicePixelContentBoxSize:[{inlineSize:i.width,blockSize:i.height}]})}),t.length>0&&this.callback(t,this),this.rafId=requestAnimationFrame(e)};this.rafId=requestAnimationFrame(e)}stopPolling(){this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null)}},this.polyfillsLoaded.add("ResizeObserver"))}async loadIntersectionObserverPolyfill(){"undefined"==typeof IntersectionObserver&&(window.IntersectionObserver=class{constructor(e,t){this.elements=new Set,this.rafId=null,this.callback=e}observe(e){this.elements.add(e),this.startPolling()}unobserve(e){this.elements.delete(e),0===this.elements.size&&this.stopPolling()}disconnect(){this.elements.clear(),this.stopPolling()}startPolling(){if(this.rafId)return;const e=()=>{const t=[];this.elements.forEach(e=>{const i=e.getBoundingClientRect(),s=i.top<window.innerHeight&&i.bottom>0;t.push({target:e,boundingClientRect:i,intersectionRatio:s?1:0,intersectionRect:s?i:new DOMRect,isIntersecting:s,rootBounds:new DOMRect(0,0,window.innerWidth,window.innerHeight),time:performance.now()})}),t.length>0&&this.callback(t,this),this.rafId=requestAnimationFrame(e)};this.rafId=requestAnimationFrame(e)}stopPolling(){this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null)}},this.polyfillsLoaded.add("IntersectionObserver"))}async loadPerformancePolyfill(){if("undefined"==typeof performance||"function"!=typeof performance.now){if("undefined"==typeof performance&&(window.performance={}),"function"!=typeof performance.now){const e=Date.now();performance.now=function(){return Date.now()-e}}this.polyfillsLoaded.add("Performance")}}async loadRAFPolyfill(){if("function"==typeof requestAnimationFrame)return;let e=0;window.requestAnimationFrame=function(t){const i=(new Date).getTime(),s=Math.max(0,16-(i-e)),n=window.setTimeout(()=>{t(i+s)},s);return e=i+s,n},window.cancelAnimationFrame=function(e){clearTimeout(e)},this.polyfillsLoaded.add("RequestAnimationFrame")}async loadCSSSupportsPolyfill(){"undefined"!=typeof CSS&&"function"==typeof CSS.supports||("undefined"==typeof CSS&&(window.CSS={}),CSS.supports=function(e,t){const i=document.createElement("div");try{if(t)return i.style.setProperty(e,t),i.style.getPropertyValue(e)===t;{const t=e.indexOf(":");if(-1===t)return!1;const s=e.substring(0,t).trim(),n=e.substring(t+1).trim();return i.style.setProperty(s,n),i.style.getPropertyValue(s)===n}}catch{return!1}},this.polyfillsLoaded.add("CSS.supports"))}async loadCustomPropertiesPolyfill(){if(this.supportsCSSCustomProperties())return;const e=new Map,t=window.getComputedStyle;window.getComputedStyle=function(i,s){const n=t.call(this,i,s),r=n.getPropertyValue;return n.getPropertyValue=function(t){return t.startsWith("--")?e.get(t)||"":r.call(this,t)},n},this.polyfillsLoaded.add("CSS Custom Properties")}async loadMatchMediaPolyfill(){"undefined"!=typeof window&&"function"==typeof window.matchMedia||(window.matchMedia=function(e){return{matches:!1,media:e,onchange:null,addListener(){},removeListener(){},addEventListener(){},removeEventListener(){},dispatchEvent:()=>!0}},this.polyfillsLoaded.add("matchMedia"))}async loadMutationObserverPolyfill(){if("undefined"==typeof window||"function"!=typeof window.MutationObserver){window.MutationObserver=class{constructor(e){this.target=null,this.config={},this.isObserving=!1,this.callback=e}observe(e,t={}){this.target=e,this.config=t,this.isObserving=!0}disconnect(){this.isObserving=!1,this.target=null}takeRecords(){return[]}},this.polyfillsLoaded.add("MutationObserver")}}async loadClassListPolyfill(){"classList"in document.createElement("div")||(Object.defineProperty(Element.prototype,"classList",{get(){const e=this;return{add(t){e.className.includes(t)||(e.className+=(e.className?" ":"")+t)},remove(t){e.className=e.className.split(" ").filter(e=>e!==t).join(" ")},contains:t=>e.className.split(" ").includes(t),toggle(e){this.contains(e)?this.remove(e):this.add(e)}}}}),this.polyfillsLoaded.add("Element.classList"))}async loadClosestPolyfill(){"function"!=typeof Element.prototype.closest&&(Element.prototype.closest=function(e){let t=this;for(;t&&1===t.nodeType;){if(t.matches&&t.matches(e))return t;t=t.parentElement}return null},this.polyfillsLoaded.add("Element.closest"))}supportsCSSCustomProperties(){try{const e=document.createElement("div");return e.style.setProperty("--test","test"),"test"===e.style.getPropertyValue("--test")}catch{return!1}}getLoadedPolyfills(){return Array.from(this.polyfillsLoaded)}static async autoInit(){const e=Q.getInstance(),i=e.checkBrowserSupport(),s={resizeObserver:i.missing.includes("ResizeObserver"),intersectionObserver:i.missing.includes("IntersectionObserver"),cssSupports:i.missing.includes("CSS.supports"),performance:i.missing.includes("Performance API"),customProperties:i.missing.includes("CSS Custom Properties"),matchMedia:i.missing.includes("matchMedia"),mutationObserver:i.missing.includes("MutationObserver")};await e.loadPolyfills(s),i.warnings.length>0&&t.warn("Browser Warnings:",i.warnings)}}function G(){const e=W();return e.resizeObserver&&e.intersectionObserver}function W(){return{resizeObserver:"undefined"!=typeof ResizeObserver,intersectionObserver:"undefined"!=typeof IntersectionObserver,containerQueries:V(),cssClamp:_(),cssCustomProperties:J(),webWorkers:"undefined"!=typeof Worker,requestAnimationFrame:"undefined"!=typeof requestAnimationFrame,passiveEventListeners:K()}}function V(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("container-type","inline-size")}function _(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("font-size","clamp(1rem, 2vw, 2rem)")}function J(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("--test","value")}function K(){let e=!1;try{const t={get passive(){return e=!0,!1}};window.addEventListener("test",null,t),window.removeEventListener("test",null,t)}catch(t){e=!1}return e}const Y="1.0.0";class Z{constructor(e={}){if(this.initialized=!1,Z.instance)return Z.instance;this.config=this.mergeConfig(e),this.eventSystem=new i,this.pluginSystem=new s(this),this.memoryManager=new n,this.observerManager=new a,this.containerManager=new u(this.config.containers,this.observerManager,this.memoryManager,this.eventSystem),this.clampScaling=new d,this.typographicScale=new m,this.textFitting=new p,this.lineHeightOptimizer=new g,this.verticalRhythm=new f({baseFontSize:16,baseLineHeight:1.5,baselineUnit:24,scale:"minor-third",precision:.001,responsive:!0,containerAware:!0}),this.eventHandler=new z({debounceDelay:16,useRAF:!0,batchOperations:!0,performanceTarget:16.67}),this.batchDOM=new $({maxBatchSize:50,separateReadWrite:!0,autoFlush:!0}),this.lazyEvaluation=new L({useIdleCallback:!0,progressiveEnhancement:!0,cacheResults:!0}),this.cssOptimizer=new F({deduplication:!0,criticalCSS:!0,unusedStyleRemoval:!0}),this.themeSystem=new N({autoDetect:!0,respectSystemPreference:!0,adaptiveContrast:!0}),this.flipAnimations=new q({respectMotionPreference:!0,batchAnimations:!0}),this.scrollAnimations=new H,this.memoryManagement=new B({autoCleanup:!0,leakDetection:!0}),this.cacheOptimization=new D({maxSize:100,evictionStrategy:"adaptive"}),this.zeroConfig=new j({autoDetectContainers:!0,intelligentBreakpoints:!0,performanceOptimization:!0}),this.browserPolyfills=Q.getInstance(),this.performanceMonitor=new P,this.fluidTypography=new M,this.containerBreakpoints=new k,this.accessibilityEngine=new O(document.body),this.browserCompatibility=new I,this.fluidTypography.setPerformanceMonitor(this.performanceMonitor),this.containerBreakpoints.setPerformanceMonitor(this.performanceMonitor),Z.instance=this,this.config.autoInit&&this.init()}get typography(){return this.fluidTypography}get containers(){return this.containerBreakpoints}get performance(){return this.performanceMonitor}get accessibility(){return this.accessibilityEngine}get compatibility(){return this.browserCompatibility}getConfiguration(){return this.config}async initialize(){return this.init()}init(){return this.initialized?(this.config.debug&&t.warn("Already initialized"),this):G()?(this.config.debug&&t.info("Initializing...",{version:Y,config:this.config,support:W()}),this.performanceMonitor.start(),this.eventSystem.init(),this.pluginSystem.init(),this.eventHandler.initialize(),this.zeroConfig.initialize().catch(e=>{t.warn("Zero-config initialization failed",e)}),this.initialized=!0,this.eventSystem.emit("init",{config:this.config}),this.config.debug&&t.info("Initialized successfully"),this):(t.error("Browser not supported. Missing required APIs."),this)}getBrowserCapabilities(){const e=this.browserPolyfills?.checkBrowserSupport()||{supported:[]};return{resizeObserver:e.supported.includes("ResizeObserver"),intersectionObserver:e.supported.includes("IntersectionObserver"),containerQueries:e.supported.includes("CSS Container Queries"),cssClamp:e.supported.includes("CSS clamp()"),customProperties:e.supported.includes("CSS Custom Properties"),matchMedia:e.supported.includes("matchMedia"),mutationObserver:e.supported.includes("MutationObserver")}}getMetrics(){return this.performanceMonitor?.getMetrics()||{}}detectFeatures(){const e=this.getBrowserCapabilities(),t=this.browserPolyfills?.checkBrowserSupport()||{supported:[],missing:[]};return{resizeObserver:e.resizeObserver,intersectionObserver:e.intersectionObserver,containerQueries:e.containerQueries,cssClamp:e.cssClamp,customProperties:e.customProperties,flexbox:e.flexbox,grid:e.grid,supported:t.supported,missing:t.missing,polyfillsActive:t.missing.length>0}}updateLiveRegion(e,t){e instanceof HTMLElement&&(e.textContent=t,e.setAttribute("aria-live","polite"))}destroy(){this.initialized&&(this.config.debug,this.containerManager.destroy(),this.observerManager.destroy(),this.memoryManager.destroy(),this.performanceMonitor.stop(),this.eventHandler.destroy(),this.batchDOM.destroy(),this.lazyEvaluation.destroy(),this.cssOptimizer.destroy(),this.themeSystem.destroy(),this.flipAnimations.destroy(),this.scrollAnimations.destroy(),this.memoryManagement.destroy(),this.cacheOptimization.destroy(),this.zeroConfig.destroy(),this.pluginSystem.destroy(),this.eventSystem.destroy(),this.initialized=!1,Z.instance=null,this.config.debug)}getConfig(){return{...this.config}}updateConfig(e){return this.config=this.mergeConfig(e,this.config),this.eventSystem.emit("configUpdate",{config:this.config}),this}getEventSystem(){return this.eventSystem}getPluginSystem(){return this.pluginSystem}getPerformanceMonitor(){return this.performanceMonitor}getMemoryManager(){return this.memoryManager}getObserverManager(){return this.observerManager}getContainerManager(){return this.containerManager}container(e,t){return this.containerManager.container(e,t)}fluidType(e,t){this.normalizeSelector(e).forEach(e=>{const i=this.clampScaling.createScaling(t||{minSize:16,maxSize:24,minContainer:320,maxContainer:1200,unit:"px",containerUnit:"px",curve:"linear"});e.style.fontSize=i.clampValue;const s=getComputedStyle(e),n=parseFloat(s.fontSize);e.style.lineHeight=1.5*n+"px"})}createTypeScale(e){return this.typographicScale.generateScale(e||{ratio:1.25,baseSize:16,baseUnit:"px",levels:6,direction:"both"})}createGrid(e,t){const i="string"==typeof e?document.querySelector(e):e;if(!i)return null;const s=new y(i,t);return s.activate(),s}fitText(e,t){this.normalizeSelector(e).forEach(e=>{const i=e.getBoundingClientRect(),s=e.textContent||"",n=this.textFitting.fitText(e,s,i.width,i.height,t);this.textFitting.applyFitting(e,n,t)})}applyRhythm(e,t){this.normalizeSelector(e).forEach(e=>{const t=this.verticalRhythm.generateRhythm();this.verticalRhythm.applyRhythm(e,t)})}createFlexbox(e,t){const i="string"==typeof e?document.querySelector(e):e;if(!i)return null;const s=new b(i,t);return s.activate(),s}applyFlow(e,t){const i="string"==typeof e?document.querySelector(e):e;if(!i)return null;const s=new v(i,t);return s.activate(),s}applySpacing(e,t){const i="string"==typeof e?document.querySelector(e):e;if(!i)return null;const s=new S(i,t);return s.activate(),s}enableReordering(e,t){const i="string"==typeof e?document.querySelector(e):e;if(!i)return null;const s=new w(i,t);return s.activate(),s}responsiveImages(e,t){const i=this.normalizeSelector(e),s=[];return i.forEach(e=>{const i=new A(e,t);i.activate(),s.push(i)}),1===s.length?s[0]:s}enableAccessibility(e,t){const i="string"==typeof e?document.querySelector(e):e;if(!i)return null;const s=new O(i,t);return s.activate(),s}setupComplete(e){const t=e?.container||document.body;return this.container(t,e?.container),this.fluidType(t.querySelectorAll("h1, h2, h3, h4, h5, h6, p"),e?.typography),this.createGrid(t.querySelectorAll(".grid, .gallery"),e?.grid),this.applySpacing(t,e?.spacing),this.enableAccessibility(t,e?.accessibility),this.responsiveImages(t.querySelectorAll("img"),e?.images),this}isInitialized(){return this.initialized}static getVersion(){return Y}static getSupportInfo(){return W()}static isSupported(){return G()}static getInstance(e){return Z.instance||(Z.instance=new Z(e)),Z.instance}mergeConfig(e,t){const i={debug:!1,performance:"high",accessibility:!0,autoInit:!0,containers:{autoDetect:!0,breakpoints:{},units:!0,isolation:!0,polyfill:!0},typography:{fluidScaling:!0,autoOptimize:!0,accessibility:!0,scale:{ratio:1.33,base:"1rem",levels:6},lineHeight:{auto:!0,density:"comfortable"}},layout:{grid:{auto:!0,masonry:!1,gap:"fluid"},flexbox:{enhanced:!0,autoWrap:!0},spacing:{scale:"minor-third",density:"comfortable"}},animations:{enabled:!0,respectMotionPreferences:!0,duration:300,easing:"ease-out",flip:!0,microInteractions:!0},theming:{darkMode:{auto:!0,schedule:"18:00-06:00",transition:"smooth"},contrast:{adaptive:!0,level:"AA"}}};return{...i,...t,...e,containers:{...i.containers,...t?.containers,...e.containers},typography:{...i.typography,...t?.typography,...e.typography,scale:{...i.typography.scale,...t?.typography?.scale,...e.typography?.scale},lineHeight:{...i.typography.lineHeight,...t?.typography?.lineHeight,...e.typography?.lineHeight}},layout:{...i.layout,...t?.layout,...e.layout,grid:{...i.layout.grid,...t?.layout?.grid,...e.layout?.grid},flexbox:{...i.layout.flexbox,...t?.layout?.flexbox,...e.layout?.flexbox},spacing:{...i.layout.spacing,...t?.layout?.spacing,...e.layout?.spacing}},animations:{...i.animations,...t?.animations,...e.animations},theming:{...i.theming,...t?.theming,...e.theming,darkMode:{...i.theming.darkMode,...t?.theming?.darkMode,...e.theming?.darkMode},contrast:{...i.theming.contrast,...t?.theming?.contrast,...e.theming?.contrast}}}}normalizeSelector(e){return"string"==typeof e?Array.from(document.querySelectorAll(e)):e instanceof Element?[e]:Array.isArray(e)?e:[]}getPerformanceMetrics(){return{eventHandler:this.eventHandler.getMetrics(),batchDOM:this.batchDOM.getMetrics(),performanceMonitor:this.performanceMonitor.getMetrics()}}observeResize(e,t,i="normal"){const s="string"==typeof e?document.querySelector(e):e;return s?this.eventHandler.observeResize(s,t,i):null}batchStyles(e,t,i="normal"){const s="string"==typeof e?document.querySelector(e):e;return s?this.batchDOM.batchStyles(s,t,i):Promise.reject(new Error("Element not found"))}measureElement(e,t=["width","height"],i="normal"){const s="string"==typeof e?document.querySelector(e):e;return s?this.batchDOM.measureElement(s,t,i):Promise.reject(new Error("Element not found"))}setTheme(e){return this.themeSystem.setScheme(e),this}toggleTheme(){return this.themeSystem.toggle(),this}async animateElement(e,t,i){const s="string"==typeof e?document.querySelector(e):e;if(s)return this.flipAnimations.animate(s,t,i)}addMicroInteractions(e,t="hover"){const i="string"==typeof e?document.querySelector(e):e;if(!i)return this;switch(t){case"hover":U.addHover(i);break;case"press":U.addPress(i);break;case"focus":U.addFocus(i);break;case"ripple":U.addRipple(i)}return this}lazyLoad(e,t,i){const s="string"==typeof e?document.querySelector(e):e;return s?this.lazyEvaluation.register(s,t,i):null}async optimizeCSS(){return this.cssOptimizer.optimizeAll()}getAdvancedMetrics(){return{eventHandler:this.eventHandler.getMetrics(),batchDOM:this.batchDOM.getMetrics(),lazyEvaluation:this.lazyEvaluation.getMetrics(),cssOptimizer:this.cssOptimizer.getMetrics(),themeSystem:this.themeSystem.getState(),flipAnimations:this.flipAnimations.getActiveCount(),performanceMonitor:this.performanceMonitor.getMetrics()}}}Z.instance=null;const X="1.0.0",ee="ProteusJS";export{ee as LIBRARY_NAME,Z as ProteusJS,X as VERSION,Z as default,G as isSupported,Y as version};
7
+ class e{constructor(e={}){this.levels={debug:0,info:1,warn:2,error:3,silent:4},this.config={level:"warn",prefix:"ProteusJS",enableInProduction:!1,enableTimestamps:!1,enableStackTrace:!1,...e}}static getInstance(t){return e.instance||(e.instance=new e(t)),e.instance}static configure(t){e.instance?e.instance.config={...e.instance.config,...t}:e.instance=new e(t)}shouldLog(e){return"production"!==process.env.NODE_ENV||this.config.enableInProduction?this.levels[e]>=this.levels[this.config.level]:"error"===e}formatMessage(e,t,...i){let s=t;if(this.config.prefix&&(s=`${this.config.prefix}: ${s}`),this.config.enableTimestamps){s=`[${(new Date).toISOString()}] ${s}`}return s=`[${e.toUpperCase().padEnd(5)}] ${s}`,[s,...i]}debug(e,...t){if(!this.shouldLog("debug"))return;const[i,...s]=this.formatMessage("debug",e,...t);this.config.enableStackTrace}info(e,...t){if(!this.shouldLog("info"))return;const[i,...s]=this.formatMessage("info",e,...t)}warn(e,...t){if(!this.shouldLog("warn"))return;const[i,...s]=this.formatMessage("warn",e,...t)}error(e,t,...i){if(!this.shouldLog("error"))return;const[s,...n]=this.formatMessage("error",e,...i);t instanceof Error&&this.config.enableStackTrace&&t.stack}group(e){this.shouldLog("info")}groupEnd(){this.shouldLog("info")}time(e){this.shouldLog("debug")}timeEnd(e){this.shouldLog("debug")}setLevel(e){this.config.level=e}getLevel(){return this.config.level}isEnabled(e){return this.shouldLog(e)}}const t=e.getInstance({level:"development"===process.env.NODE_ENV?"debug":"warn",prefix:"ProteusJS",enableInProduction:!1,enableTimestamps:"development"===process.env.NODE_ENV,enableStackTrace:!1});class i{constructor(){this.listeners=new Map,this.initialized=!1}init(){this.initialized||(this.initialized=!0)}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);const i=this.listeners.get(e);return i.add(t),()=>{i.delete(t),0===i.size&&this.listeners.delete(e)}}once(e,t){const i=this.on(e,e=>{t(e),i()});return i}off(e,t){if(!t)return void this.listeners.delete(e);const i=this.listeners.get(e);i&&(i.delete(t),0===i.size&&this.listeners.delete(e))}emit(e,t,i){const s=this.listeners.get(e);if(!s||0===s.size)return;const n={type:e,target:i||document.documentElement,detail:t,timestamp:Date.now()};s.forEach(e=>{try{e(n)}catch(e){}})}getEventTypes(){return Array.from(this.listeners.keys())}getListenerCount(e){const t=this.listeners.get(e);return t?t.size:0}hasListeners(e){return this.getListenerCount(e)>0}clear(){this.listeners.clear()}destroy(){this.clear(),this.initialized=!1}getDebugInfo(){const e={};return this.listeners.forEach((t,i)=>{e[i]=t.size}),{initialized:this.initialized,totalEventTypes:this.listeners.size,listeners:e}}}class s{constructor(e){this.plugins=new Map,this.installedPlugins=new Set,this.initialized=!1,this.proteus=e}init(){this.initialized||(this.initialized=!0)}register(e){if(this.plugins.has(e.name))return this;if(!this.validatePlugin(e))throw new Error(`ProteusJS: Invalid plugin "${e.name}"`);return this.plugins.set(e.name,e),this}install(e){const t=this.plugins.get(e);if(!t)throw new Error(`ProteusJS: Plugin "${e}" not found`);if(this.installedPlugins.has(e))return this;if(t.dependencies)for(const i of t.dependencies)if(!this.installedPlugins.has(i))throw new Error(`ProteusJS: Plugin "${e}" requires dependency "${i}" to be installed first`);try{t.install(this.proteus),this.installedPlugins.add(e),this.proteus.getEventSystem().emit("pluginInstalled",{plugin:e,version:t.version})}catch(e){throw e}return this}uninstall(e){const t=this.plugins.get(e);if(!t)return this;if(!this.installedPlugins.has(e))return this;const i=this.getDependents(e);if(i.length>0)throw new Error(`ProteusJS: Cannot uninstall plugin "${e}" because it's required by: ${i.join(", ")}`);try{t.uninstall&&t.uninstall(this.proteus),this.installedPlugins.delete(e),this.proteus.getEventSystem().emit("pluginUninstalled",{plugin:e,version:t.version})}catch(e){throw e}return this}isInstalled(e){return this.installedPlugins.has(e)}getRegisteredPlugins(){return Array.from(this.plugins.keys())}getInstalledPlugins(){return Array.from(this.installedPlugins)}getPluginInfo(e){return this.plugins.get(e)}installMany(e){const t=this.sortByDependencies(e);for(const e of t)this.install(e);return this}destroy(){const e=Array.from(this.installedPlugins),t=this.sortByDependencies(e).reverse();for(const e of t)try{this.uninstall(e)}catch(e){}this.plugins.clear(),this.installedPlugins.clear(),this.initialized=!1}validatePlugin(e){return!(!e.name||"string"!=typeof e.name)&&(!(!e.version||"string"!=typeof e.version)&&!(!e.install||"function"!=typeof e.install))}getDependents(e){const t=[];for(const[i,s]of this.plugins)this.installedPlugins.has(i)&&s.dependencies?.includes(e)&&t.push(i);return t}sortByDependencies(e){const t=[],i=new Set,s=new Set,n=r=>{if(s.has(r))throw new Error(`ProteusJS: Circular dependency detected involving plugin "${r}"`);if(i.has(r))return;s.add(r);const o=this.plugins.get(r);if(o?.dependencies)for(const t of o.dependencies)e.includes(t)&&n(t);s.delete(r),i.add(r),t.push(r)};for(const t of e)n(t);return t}}class n{constructor(){this.resources=new Map,this.elementResources=new Map,this.mutationObserver=null,this.cleanupInterval=null,this.isMonitoring=!1,this.setupDOMObserver(),this.startPeriodicCleanup()}register(e){const t={...e,timestamp:Date.now()};return this.resources.set(e.id,t),e.element&&(this.elementResources.has(e.element)||this.elementResources.set(e.element,new Set),this.elementResources.get(e.element).add(e.id)),e.id}unregister(e){const t=this.resources.get(e);if(!t)return!1;try{t.cleanup()}catch(e){}if(this.resources.delete(e),t.element){const i=this.elementResources.get(t.element);i&&(i.delete(e),0===i.size&&this.elementResources.delete(t.element))}return!0}cleanupElement(e){const t=this.elementResources.get(e);if(!t)return 0;let i=0;return t.forEach(e=>{this.unregister(e)&&i++}),i}cleanupByType(e){let t=0;const i=[];return this.resources.forEach((t,s)=>{t.type===e&&i.push(s)}),i.forEach(e=>{this.unregister(e)&&t++}),t}cleanupOldResources(e=3e5){let t=0;const i=Date.now(),s=[];return this.resources.forEach((t,n)=>{i-t.timestamp>e&&s.push(n)}),s.forEach(e=>{this.unregister(e)&&t++}),t}forceGarbageCollection(){if("gc"in window&&"function"==typeof window.gc)try{window.gc()}catch(e){}}getMemoryInfo(){const e={managedResources:this.resources.size,trackedElements:this.elementResources.size,resourcesByType:{}};if(this.resources.forEach(t=>{e.resourcesByType[t.type]=(e.resourcesByType[t.type]||0)+1}),"memory"in performance){const t=performance.memory;e.browserMemory={usedJSHeapSize:t.usedJSHeapSize,totalJSHeapSize:t.totalJSHeapSize,jsHeapSizeLimit:t.jsHeapSizeLimit}}return e}detectLeaks(){const e=[],t=Date.now();this.resources.size>1e3&&e.push(`High number of managed resources: ${this.resources.size}`);let i=0;this.resources.forEach(e=>{t-e.timestamp>6e5&&i++}),i>50&&e.push(`Many old resources detected: ${i}`);let s=0;return this.elementResources.forEach((e,t)=>{document.contains(t)||(s+=e.size)}),s>0&&e.push(`Orphaned element resources detected: ${s}`),e}destroy(){Array.from(this.resources.keys()).forEach(e=>this.unregister(e)),this.stopMonitoring(),this.resources.clear(),this.elementResources.clear()}startMonitoring(){this.isMonitoring||(this.isMonitoring=!0)}stopMonitoring(){this.isMonitoring&&(this.isMonitoring=!1,this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null))}setupDOMObserver(){"undefined"!=typeof MutationObserver&&(this.mutationObserver=new MutationObserver(e=>{e.forEach(e=>{"childList"===e.type&&e.removedNodes.forEach(e=>{e.nodeType===Node.ELEMENT_NODE&&this.handleElementRemoval(e)})})}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}))}handleElementRemoval(e){this.cleanupElement(e);e.querySelectorAll("*").forEach(e=>{this.cleanupElement(e)})}startPeriodicCleanup(){this.cleanupInterval=window.setInterval(()=>{let e=0;this.elementResources.forEach((t,i)=>{document.contains(i)||(e+=this.cleanupElement(i))});this.cleanupOldResources(6e5)},6e4)}}class r{constructor(e){this.observedElements=new Map,this.rafId=null,this.isObserving=!1,this.callback=e}observe(e,t){if(this.observedElements.has(e))return;const i=e.getBoundingClientRect();this.observedElements.set(e,{lastWidth:i.width,lastHeight:i.height}),this.isObserving||this.startObserving()}unobserve(e){this.observedElements.delete(e),0===this.observedElements.size&&this.stopObserving()}disconnect(){this.observedElements.clear(),this.stopObserving()}startObserving(){this.isObserving||(this.isObserving=!0,this.checkForChanges())}stopObserving(){this.isObserving&&(this.isObserving=!1,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null))}checkForChanges(){if(!this.isObserving)return;const e=[];if(this.observedElements.forEach((t,i)=>{if(!document.contains(i))return void this.observedElements.delete(i);const s=i.getBoundingClientRect(),n=s.width,r=s.height;if(n!==t.lastWidth||r!==t.lastHeight){this.observedElements.set(i,{lastWidth:n,lastHeight:r});const t={target:i,contentRect:this.createDOMRectReadOnly(s),contentBoxSize:[{inlineSize:n,blockSize:r}],borderBoxSize:[{inlineSize:n,blockSize:r}]};e.push(t)}}),e.length>0)try{this.callback(e)}catch(e){}this.isObserving&&(this.rafId=requestAnimationFrame(()=>this.checkForChanges()))}createDOMRectReadOnly(e){return{x:e.x,y:e.y,width:e.width,height:e.height,top:e.top,right:e.right,bottom:e.bottom,left:e.left,toJSON:()=>({x:e.x,y:e.y,width:e.width,height:e.height,top:e.top,right:e.right,bottom:e.bottom,left:e.left})}}}r.isSupported=()=>"undefined"!=typeof ResizeObserver;class o{constructor(e,t){this.observedElements=new Map,this.rafId=null,this.isObserving=!1,this.callback=e,this.root=t?.root instanceof Element?t.root:null,this.rootMargin=t?.rootMargin||"0px",this.thresholds=this.normalizeThresholds(t?.threshold),this.parsedRootMargin=this.parseRootMargin(this.rootMargin)}observe(e){this.observedElements.has(e)||(this.observedElements.set(e,{lastRatio:0,wasIntersecting:!1}),this.isObserving||this.startObserving())}unobserve(e){this.observedElements.delete(e),0===this.observedElements.size&&this.stopObserving()}disconnect(){this.observedElements.clear(),this.stopObserving()}startObserving(){this.isObserving||(this.isObserving=!0,this.checkForIntersections())}stopObserving(){this.isObserving&&(this.isObserving=!1,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null))}checkForIntersections(){if(!this.isObserving)return;const e=[],t=this.getRootBounds();if(this.observedElements.forEach((i,s)=>{if(!document.contains(s))return void this.observedElements.delete(s);const n=s.getBoundingClientRect(),r=this.calculateIntersection(n,t),o=this.calculateIntersectionRatio(n,r),a=o>0;if(this.shouldTriggerCallback(o,i.lastRatio,a,i.wasIntersecting)){this.observedElements.set(s,{lastRatio:o,wasIntersecting:a});const i={target:s,boundingClientRect:this.createDOMRectReadOnly(n),intersectionRect:this.createDOMRectReadOnly(r),rootBounds:t?this.createDOMRectReadOnly(t):null,intersectionRatio:o,isIntersecting:a,time:performance.now()};e.push(i)}}),e.length>0)try{this.callback(e)}catch(e){}this.isObserving&&(this.rafId=requestAnimationFrame(()=>this.checkForIntersections()))}getRootBounds(){const e=(this.root||document.documentElement).getBoundingClientRect();return new DOMRect(e.left-this.parsedRootMargin.left,e.top-this.parsedRootMargin.top,e.width+this.parsedRootMargin.left+this.parsedRootMargin.right,e.height+this.parsedRootMargin.top+this.parsedRootMargin.bottom)}calculateIntersection(e,t){const i=Math.max(e.left,t.left),s=Math.max(e.top,t.top),n=Math.min(e.right,t.right),r=Math.min(e.bottom,t.bottom),o=Math.max(0,n-i),a=Math.max(0,r-s);return new DOMRect(i,s,o,a)}calculateIntersectionRatio(e,t){const i=e.width*e.height;if(0===i)return 0;return t.width*t.height/i}shouldTriggerCallback(e,t,i,s){if(0===t&&!s)return!0;if(i!==s)return!0;for(const i of this.thresholds)if(t<i&&e>=i||t>i&&e<=i)return!0;return!1}normalizeThresholds(e){return void 0===e?[0]:"number"==typeof e?[e]:e.slice().sort((e,t)=>e-t)}parseRootMargin(e){const t=e.split(/\s+/).map(e=>{const t=parseFloat(e);return e.endsWith("%")?t/100*window.innerHeight:t});switch(t.length){case 1:return{top:t[0],right:t[0],bottom:t[0],left:t[0]};case 2:return{top:t[0],right:t[1],bottom:t[0],left:t[1]};case 3:return{top:t[0],right:t[1],bottom:t[2],left:t[1]};case 4:return{top:t[0],right:t[1],bottom:t[2],left:t[3]};default:return{top:0,right:0,bottom:0,left:0}}}createDOMRectReadOnly(e){return{x:e.x,y:e.y,width:e.width,height:e.height,top:e.top,right:e.right,bottom:e.bottom,left:e.left,toJSON:()=>({x:e.x,y:e.y,width:e.width,height:e.height,top:e.top,right:e.right,bottom:e.bottom,left:e.left})}}}o.isSupported=()=>"undefined"!=typeof IntersectionObserver;class a{constructor(){this.resizeObservers=new Map,this.intersectionObservers=new Map,this.resizeEntries=new Map,this.intersectionEntries=new Map,this.isPolyfillMode=!1,this.checkPolyfillNeeds()}observeResize(e,t,i){const s=this.getResizeObserverKey(i);let n=this.resizeObservers.get(s);n||(n=this.createResizeObserver(i),this.resizeObservers.set(s,n));const r={element:e,callback:t,...i&&{options:i}};return this.resizeEntries.set(e,r),n.observe(e,i),()=>this.unobserveResize(e)}observeIntersection(e,t,i){const s=this.getIntersectionObserverKey(i);let n=this.intersectionObservers.get(s);n||(n=this.createIntersectionObserver(t,i),this.intersectionObservers.set(s,n));const r={element:e,callback:t,...i&&{options:i}};return this.intersectionEntries.set(e,r),n.observe(e),()=>this.unobserveIntersection(e)}unobserveResize(e){const t=this.resizeEntries.get(e);if(!t)return;const i=this.getResizeObserverKey(t.options),s=this.resizeObservers.get(i);s&&s.unobserve(e),this.resizeEntries.delete(e),this.cleanupResizeObserver(i)}unobserveIntersection(e){const t=this.intersectionEntries.get(e);if(!t)return;const i=this.getIntersectionObserverKey(t.options),s=this.intersectionObservers.get(i);s&&s.unobserve(e),this.intersectionEntries.delete(e),this.cleanupIntersectionObserver(i)}getObservedElementCount(){return this.resizeEntries.size+this.intersectionEntries.size}getObserverCount(){return this.resizeObservers.size+this.intersectionObservers.size}isObservingResize(e){return this.resizeEntries.has(e)}isObservingIntersection(e){return this.intersectionEntries.has(e)}destroy(){this.resizeObservers.forEach(e=>e.disconnect()),this.resizeObservers.clear(),this.resizeEntries.clear(),this.intersectionObservers.forEach(e=>e.disconnect()),this.intersectionObservers.clear(),this.intersectionEntries.clear()}getDebugInfo(){return{isPolyfillMode:this.isPolyfillMode,resizeObservers:this.resizeObservers.size,intersectionObservers:this.intersectionObservers.size,resizeEntries:this.resizeEntries.size,intersectionEntries:this.intersectionEntries.size,totalObservedElements:this.getObservedElementCount(),totalObservers:this.getObserverCount()}}checkPolyfillNeeds(){"undefined"==typeof ResizeObserver&&(this.setupResizeObserverPolyfill(),this.isPolyfillMode=!0),"undefined"==typeof IntersectionObserver&&(this.setupIntersectionObserverPolyfill(),this.isPolyfillMode=!0)}setupResizeObserverPolyfill(){globalThis.ResizeObserver=r}setupIntersectionObserverPolyfill(){globalThis.IntersectionObserver=o}createResizeObserver(e){return new ResizeObserver(e=>{e.forEach(e=>{const t=this.resizeEntries.get(e.target);t&&t.callback(e)})})}createIntersectionObserver(e,t){return new IntersectionObserver(e=>{e.forEach(e=>{const t=this.intersectionEntries.get(e.target);t&&t.callback(e)})},t)}getResizeObserverKey(e){return e?`box:${e.box||"content-box"}`:"default"}getIntersectionObserverKey(e){if(!e)return"default";return`${e.root?"custom":"viewport"}:${e.rootMargin||"0px"}:${Array.isArray(e.threshold)?e.threshold.join(","):(e.threshold||0).toString()}`}cleanupResizeObserver(e){if(!Array.from(this.resizeEntries.values()).some(t=>this.getResizeObserverKey(t.options)===e)){const t=this.resizeObservers.get(e);t&&(t.disconnect(),this.resizeObservers.delete(e))}}cleanupIntersectionObserver(e){if(!Array.from(this.intersectionEntries.values()).some(t=>this.getIntersectionObserverKey(t.options)===e)){const t=this.intersectionObservers.get(e);t&&(t.disconnect(),this.intersectionObservers.delete(e))}}}function c(e,t,i={}){const{leading:s=!1,trailing:n=!0,maxWait:r}=i;let o,a,c,l,h=null,u=0;function d(t){const i=a,s=c;return a=void 0,c=void 0,u=t,l=e.apply(s,i),l}function m(e){const i=e-o;return void 0===o||i>=t||i<0||void 0!==r&&e-u>=r}function p(){const e=Date.now();if(m(e))return g(e);h=window.setTimeout(p,function(e){const i=e-u,s=t-(e-o);return void 0!==r?Math.min(s,r-i):s}(e))}function g(e){return h=null,n&&a?d(e):(a=void 0,c=void 0,l)}function f(...e){const i=Date.now(),n=m(i);if(a=e,c=this,o=i,n){if(null===h)return function(e){return u=e,h=window.setTimeout(p,t),s?d(e):l}(o);if(void 0!==r)return h=window.setTimeout(p,t),d(o)}return null===h&&(h=window.setTimeout(p,t)),l}return f.cancel=function(){null!==h&&(clearTimeout(h),h=null),u=0,a=void 0,o=void 0,c=void 0},f.flush=function(){return null===h?l:g(Date.now())},f}const l=new class{constructor(e){this.marks=new Map,this.measurements=[],this.warningThreshold=.8,this.budget={responseTime:60,frameRate:60,memoryUsage:100,...e}}mark(e,t){const i={name:e,startTime:performance.now(),...t&&{metadata:t}};this.marks.set(e,i),"function"==typeof performance.mark&&performance.mark(`proteus-${e}-start`)}measure(e){const t=this.marks.get(e);if(!t)return null;const i=performance.now(),s=i-t.startTime,n={...t,endTime:i,duration:s};return this.measurements.push(n),this.marks.delete(e),"function"==typeof performance.mark&&"function"==typeof performance.measure&&(performance.mark(`proteus-${e}-end`),performance.measure(`proteus-${e}`,`proteus-${e}-start`,`proteus-${e}-end`)),this.checkBudget(n),n}getMeasurements(){return[...this.measurements]}getMeasurementsByPattern(e){return this.measurements.filter(t=>e.test(t.name))}getAverageDuration(e){const t=this.measurements.filter(t=>t.name===e&&void 0!==t.duration);if(0===t.length)return 0;return t.reduce((e,t)=>e+(t.duration||0),0)/t.length}getStats(){const e={totalMeasurements:this.measurements.length,activeMeasurements:this.marks.size,budget:this.budget,violations:this.getBudgetViolations()},t={};return this.measurements.forEach(e=>{void 0!==e.duration&&(t[e.name]||(t[e.name]={count:0,avgDuration:0,maxDuration:0}),t[e.name].count++,t[e.name].maxDuration=Math.max(t[e.name].maxDuration,e.duration))}),Object.keys(t).forEach(e=>{t[e].avgDuration=this.getAverageDuration(e)}),e.byName=t,e}clear(){this.measurements.length=0,this.marks.clear()}updateBudget(e){this.budget={...this.budget,...e}}checkBudget(e){if(void 0===e.duration)return;this.budget.responseTime,this.warningThreshold;const t=this.budget.responseTime;e.duration>t||e.duration}getBudgetViolations(){return this.measurements.filter(e=>void 0!==e.duration&&e.duration>this.budget.responseTime)}};class h{constructor(e,t={},i,s){this.unobserveResize=null,this.isActive=!1,this.liveRegion=null,this.element=e,this.observerManager=i,this.memoryManager=s,this.options={breakpoints:{},containerType:"auto",debounceMs:16,callbacks:{...t.callbacks?.resize&&{resize:t.callbacks.resize},...t.callbacks?.breakpointChange&&{breakpointChange:t.callbacks.breakpointChange}},cssClasses:!0,units:!0,announceChanges:!1,...t},this.state=this.createInitialState(),this.debouncedUpdate=c(this.updateState.bind(this),this.options.debounceMs,{leading:!0,trailing:!0}),"auto"===this.options.containerType&&(this.options.containerType=this.detectContainerType()),this.setupContainerQuery()}activate(){this.isActive||(l.mark("container-activate"),this.unobserveResize=this.observerManager.observeResize(this.element,this.handleResize.bind(this)),this.memoryManager.register({id:`container-${this.getElementId()}`,type:"observer",element:this.element,cleanup:()=>this.deactivate()}),this.isActive=!0,this.options.announceChanges&&this.setupAnnouncements(),this.updateState(),l.measure("container-activate"))}deactivate(){this.isActive&&(this.unobserveResize&&(this.unobserveResize(),this.unobserveResize=null),this.debouncedUpdate.cancel(),this.options.cssClasses&&this.removeCSSClasses(),this.liveRegion&&this.liveRegion.parentNode&&(this.liveRegion.parentNode.removeChild(this.liveRegion),this.liveRegion=null),this.isActive=!1)}getState(){return{...this.state}}getElement(){return this.element}updateBreakpoints(e){this.options.breakpoints={...e},this.updateState()}isBreakpointActive(e){return this.state.activeBreakpoints.includes(e)}getDimensions(){const{width:e,height:t}=this.state;return{px:{width:e,height:t},cw:{width:100,height:t/e*100},ch:{width:e/t*100,height:100},cmin:Math.min(e,t),cmax:Math.max(e,t)}}handleResize(e){this.debouncedUpdate()}updateState(){l.mark("container-update");const e=this.element.getBoundingClientRect(),t=e.width,i=e.height,s=i>0?t/i:0;if(Math.abs(t-this.state.width)<.5&&Math.abs(i-this.state.height)<.5)return void l.measure("container-update");const n=[...this.state.activeBreakpoints];this.state={width:t,height:i,aspectRatio:s,containerType:this.options.containerType,activeBreakpoints:this.calculateActiveBreakpoints(t,i),lastUpdate:Date.now()},this.options.cssClasses&&this.updateCSSClasses(n),this.options.units&&this.updateContainerUnits(),this.options.callbacks.resize&&this.options.callbacks.resize(this.state),this.options.callbacks.breakpointChange&&this.notifyBreakpointChanges(n,this.state.activeBreakpoints),this.options.announceChanges&&this.announce(`Layout changed to ${this.state.activeBreakpoints.join(", ")||"default"} view`),l.measure("container-update")}createInitialState(){const e=this.element.getBoundingClientRect();return{width:e.width,height:e.height,aspectRatio:e.height>0?e.width/e.height:0,containerType:"inline-size",activeBreakpoints:[],lastUpdate:Date.now()}}detectContainerType(){try{const e=getComputedStyle(this.element).contain;return e&&"string"==typeof e?e.includes("inline-size")?"inline-size":e.includes("size")?"size":e.includes("block-size")?"block-size":"inline-size":"inline-size"}catch(e){return t.warn("Failed to detect container type:",e),"inline-size"}}setupContainerQuery(){if("undefined"!=typeof CSS&&CSS.supports&&CSS.supports("container-type","inline-size")){const e=this.element;e.style.containerType="auto"===this.options.containerType?"inline-size":this.options.containerType;const t=this.generateContainerName();e.style.containerName=t}}calculateActiveBreakpoints(e,t){const i=[];return Object.entries(this.options.breakpoints).forEach(([s,n])=>{const r=this.parseBreakpointValue(n);this.getRelevantDimension(e,t)>=r&&i.push(s)}),i.sort((e,t)=>this.parseBreakpointValue(this.options.breakpoints[e])-this.parseBreakpointValue(this.options.breakpoints[t]))}getRelevantDimension(e,t){switch(this.options.containerType){case"inline-size":default:return e;case"block-size":return t;case"size":return Math.min(e,t)}}parseBreakpointValue(e){return"number"==typeof e?e:e.endsWith("px")?parseFloat(e):e.endsWith("em")||e.endsWith("rem")?16*parseFloat(e):parseFloat(e)||0}updateCSSClasses(e){const t=this.element,i=this.getClassPrefix();e.forEach(e=>{t.classList.remove(`${i}--${e}`)}),this.state.activeBreakpoints.forEach(e=>{t.classList.add(`${i}--${e}`)})}removeCSSClasses(){const e=this.element,t=this.getClassPrefix();this.state.activeBreakpoints.forEach(i=>{e.classList.remove(`${t}--${i}`)})}updateContainerUnits(){const e=this.element,{width:t,height:i}=this.state;e.style.setProperty("--cw",t/100+"px"),e.style.setProperty("--ch",i/100+"px"),e.style.setProperty("--cmin",Math.min(t,i)/100+"px"),e.style.setProperty("--cmax",Math.max(t,i)/100+"px"),e.style.setProperty("--cqi",t/100+"px"),e.style.setProperty("--cqb",i/100+"px")}notifyBreakpointChanges(e,t){const i=this.options.callbacks.breakpointChange;t.forEach(t=>{e.includes(t)||i(t,!0)}),e.forEach(e=>{t.includes(e)||i(e,!1)})}generateContainerName(){return`proteus-${this.getElementId()}`}getClassPrefix(){return this.element.className.split(" ")[0]||"proteus-container"}getElementId(){if(this.element.id)return this.element.id;const e=Array.from(document.querySelectorAll(this.element.tagName)).indexOf(this.element);return`${this.element.tagName.toLowerCase()}-${e}`}setupAnnouncements(){}announce(e){this.liveRegion||(this.liveRegion=document.createElement("div"),this.liveRegion.setAttribute("aria-live","polite"),this.liveRegion.setAttribute("aria-atomic","true"),this.liveRegion.style.cssText="position: absolute; left: -10000px; width: 1px; height: 1px; overflow: hidden;",document.body.appendChild(this.liveRegion)),this.liveRegion.textContent=e;try{const e=new Event("DOMSubtreeModified",{bubbles:!0});this.liveRegion.dispatchEvent(e)}catch(e){}try{const e=new Event("DOMNodeInserted",{bubbles:!0});this.liveRegion.dispatchEvent(e)}catch(e){}}announceBreakpointChanges(e,t){const i=t.filter(t=>!e.includes(t)),s=e.filter(e=>!t.includes(e));if(i.length>0){const e=`Layout changed to ${i.join(", ")} view`;return this.announce(e),!0}if(s.length>0&&t.length>0){const e=`Layout changed to ${t.join(", ")} view`;return this.announce(e),!0}return!1}}class u{constructor(e,t,i,s){this.containers=new Map,this.autoDetectionEnabled=!1,this.observerManager=t,this.memoryManager=i,this.eventSystem=s,this.config={autoDetect:!0,breakpoints:{sm:"300px",md:"500px",lg:"800px",xl:"1200px"},units:!0,isolation:!0,polyfill:!0,...e},this.config.autoDetect&&this.enableAutoDetection()}container(e,t={}){l.mark("container-create");const i=this.normalizeSelector(e),s=[];return i.forEach(e=>{let i=this.containers.get(e);if(i)t.breakpoints&&i.updateBreakpoints(t.breakpoints);else{const s={breakpoints:this.config.breakpoints,...t};i=new h(e,s,this.observerManager,this.memoryManager),this.containers.set(e,i),i.activate(),this.eventSystem.emit("containerCreated",{element:e,container:i,options:s})}s.push(i)}),l.measure("container-create"),1===i.length?s[0]:s}removeContainer(e){const t=this.normalizeSelector(e);let i=!1;return t.forEach(e=>{const t=this.containers.get(e);t&&(t.deactivate(),this.containers.delete(e),i=!0,this.eventSystem.emit("containerRemoved",{element:e,container:t}))}),i}getContainer(e){return this.containers.get(e)}getAllContainers(){return Array.from(this.containers.values())}getContainersByBreakpoint(e){return this.getAllContainers().filter(t=>t.isBreakpointActive(e))}updateGlobalBreakpoints(e){const t=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,String(t)]));this.config.breakpoints={...this.config.breakpoints,...t},this.containers.forEach(e=>{e.updateBreakpoints(this.config.breakpoints)}),this.eventSystem.emit("breakpointsUpdated",{breakpoints:this.config.breakpoints})}enableAutoDetection(){this.autoDetectionEnabled||(this.autoDetectionEnabled=!0,this.scanForContainers(),this.setupMutationObserver())}disableAutoDetection(){this.autoDetectionEnabled=!1}scanForContainers(){if(!this.autoDetectionEnabled)return;l.mark("container-scan");this.findContainerCandidates().forEach(e=>{if(!this.containers.has(e)){const t=this.extractOptionsFromElement(e);this.container(e,t)}}),l.measure("container-scan")}getStats(){const e=this.getAllContainers(),t={totalContainers:e.length,activeContainers:e.filter(e=>e.getState().lastUpdate>0).length,autoDetectionEnabled:this.autoDetectionEnabled,breakpoints:Object.keys(this.config.breakpoints),containersByBreakpoint:{}};return Object.keys(this.config.breakpoints).forEach(e=>{t.containersByBreakpoint[e]=this.getContainersByBreakpoint(e).length}),t}destroy(){this.containers.forEach(e=>{e.deactivate()}),this.containers.clear(),this.autoDetectionEnabled=!1}normalizeSelector(e){return"string"==typeof e?Array.from(document.querySelectorAll(e)):e instanceof Element?[e]:Array.isArray(e)?e:[]}findContainerCandidates(){const e=[];if(e.push(...Array.from(document.querySelectorAll("[data-container]"))),e.push(...Array.from(document.querySelectorAll(".container, .card, .widget, .component"))),"undefined"!=typeof CSS&&CSS.supports&&CSS.supports("container-type","inline-size")){document.querySelectorAll("*").forEach(t=>{const i=getComputedStyle(t);i.containerType&&"normal"!==i.containerType&&e.push(t)})}return Array.from(new Set(e))}extractOptionsFromElement(e){const t={},i=e.getAttribute("data-container");if(i)try{const e=JSON.parse(i);Object.assign(t,e)}catch(e){}const s=e.getAttribute("data-breakpoints");if(s)try{t.breakpoints=JSON.parse(s)}catch(e){}const n=e.getAttribute("data-container-type");return n&&(t.containerType=n),t}setupMutationObserver(){if("undefined"==typeof MutationObserver)return;const e=new MutationObserver(e=>{let t=!1;e.forEach(e=>{"childList"===e.type?e.addedNodes.forEach(e=>{e.nodeType===Node.ELEMENT_NODE&&(t=!0)}):"attributes"===e.type&&(e.attributeName?.startsWith("data-container")||"class"===e.attributeName)&&(t=!0)}),t&&setTimeout(()=>this.scanForContainers(),100)});e.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-container","data-breakpoints","data-container-type","class"]}),this.memoryManager.register({id:"container-mutation-observer",type:"observer",cleanup:()=>e.disconnect()})}}class d{constructor(){this.supportsClamp=this.checkClampSupport(),this.supportsContainerUnits=this.checkContainerUnitSupport()}createScaling(e){const{minSize:t,maxSize:i,minContainer:s,maxContainer:n,unit:r,containerUnit:o,curve:a}=e,c=n-s;if(c<=0)return{clampValue:`${t}${r}`,fallbackValue:`${t}${r}`,currentSize:t,progress:0,isNative:!1};const l=(i-t)/c,h=t-l*s;let u,d;if(this.supportsClamp&&(this.supportsContainerUnits||"px"===o)){u=`clamp(${t}${r}, ${this.createPreferredValue(h,l,r,o,a,e)}, ${i}${r})`,d=`${t}${r}`}else u=`var(--proteus-font-size, ${t}${r})`,d=`${t}${r}`;return{clampValue:u,fallbackValue:d,currentSize:t,progress:0,isNative:this.supportsClamp}}calculateSize(e,t){const{minSize:i,maxSize:s,minContainer:n,maxContainer:r,curve:o,customCurve:a}=t,c=(Math.max(n,Math.min(r,e))-n)/(r-n),l=i+(s-i)*this.applyCurve(c,o,a);return Math.max(i,Math.min(s,l))}applyScaling(e,t,i){const s=e,n=this.createScaling(i);if(n.isNative)s.style.fontSize=n.clampValue;else{const e=this.calculateSize(t,i);s.style.setProperty("--proteus-font-size",`${e}${i.unit}`),s.style.fontSize=n.clampValue}}createMultiBreakpointScaling(e,t="rem",i="cw"){if(e.length<2)throw new Error("At least 2 breakpoints required for multi-breakpoint scaling");const s=[...e].sort((e,t)=>e.container-t.container),n=[];for(let e=0;e<s.length-1;e++){const r=s[e],o=s[e+1],a={minSize:r.size,maxSize:o.size,minContainer:r.container,maxContainer:o.container,unit:t,containerUnit:i,curve:"linear"},c=this.createScaling(a);n.push(c.clampValue)}return 1===n.length?n[0]:`max(${n.join(", ")})`}generateOptimalConfig(e,t,i,s={}){const{unit:n="rem",accessibility:r=!0,readability:o=!0}=s;let{small:a,large:c}=t;const{small:l,large:h}=i;if(r){const e="px"===n?16:1;a=Math.max(a,e);const t="px"===n?72:4.5;c=Math.min(c,t)}if(o){const e=2.5;c/a>e&&(c=a*e)}return{minSize:a,maxSize:c,minContainer:l,maxContainer:h,unit:n,containerUnit:"cw",curve:"ease-out"}}validateConfig(e){const t=[];e.minSize>=e.maxSize&&t.push("minSize must be less than maxSize"),e.minContainer>=e.maxContainer&&t.push("minContainer must be less than maxContainer"),e.minSize<=0&&t.push("minSize must be positive"),e.minContainer<=0&&t.push("minContainer must be positive");return e.maxSize/e.minSize>5&&t.push("Size ratio is very large (>5x), consider reducing for better readability"),{valid:0===t.length,errors:t}}createPreferredValue(e,t,i,s,n,r){if(!isFinite(e)||!isFinite(t))return`1${i}`;if("linear"===n){const n=t*("px"===s?1:100);return`${Number(e.toFixed(3))}${i} + ${Number(n.toFixed(3))}${s}`}return`${Number(e.toFixed(3))}${i} + ${Number((100*t).toFixed(3))}${s}`}applyCurve(e,t,i){switch(t){case"linear":default:return e;case"ease-in":return e*e;case"ease-out":return 1-Math.pow(1-e,2);case"ease-in-out":return e<.5?2*e*e:1-Math.pow(-2*e+2,2)/2;case"custom":return i?i(e):e}}checkClampSupport(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("font-size","clamp(1rem, 2vw, 2rem)")}checkContainerUnitSupport(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("font-size","1cw")}}class m{generateScale(e){if(void 0!==e.steps)return this.generateSimpleScale({ratio:e.ratio,baseSize:e.baseSize,steps:e.steps});const t={...e,baseUnit:e.baseUnit||"px",levels:e.levels||5,direction:e.direction||"up",roundToGrid:e.roundToGrid||!1,gridSize:e.gridSize||4},i=this.parseRatio(t.ratio),s=this.calculateLevels(t,i),n=this.generateCustomProperties(s),r=this.generateCSSClasses(s);return{config:{...t,ratio:i},levels:s,cssCustomProperties:n,cssClasses:r}}generateSimpleScale(e){const t=this.parseRatio(e.ratio),i=[];for(let s=0;s<e.steps;s++){const n=e.baseSize*Math.pow(t,s);i.push(n)}return i}generateResponsiveScale(e,t,i={min:.8,max:1.2}){const s={...e,baseSize:e.baseSize*i.min},n={...e,baseSize:e.baseSize*i.max},r=this.generateScale(s),o=this.generateScale(n);return{small:r,large:o,fluidCSS:this.generateFluidCSS(r,o,t)}}getOptimalRatio(e){switch(e){case"body":default:return m.NAMED_RATIOS["minor-third"];case"display":return m.NAMED_RATIOS["perfect-fourth"];case"interface":return m.NAMED_RATIOS["major-second"];case"code":return m.NAMED_RATIOS["minor-second"]}}calculateOptimalBaseSize(e,t=66,i=.5){const s=e/(t*i);return Math.max(.875,Math.min(1.5,s/16))}validateScale(e){const t=[],i=this.parseRatio(e.ratio);i<=1&&t.push("Ratio must be greater than 1"),e.baseSize<=0&&t.push("Base size must be positive");const s=e.levels||e.steps||5;return s<1&&t.push("Must have at least 1 level"),s>20&&t.push("Too many levels (>20), consider reducing for better usability"),i>3&&t.push("Very large ratio (>3), may create poor readability"),{valid:0===t.length,errors:t}}getScaleStats(e){const t=e.levels.map(e=>e.size),i=e.levels.slice(1).map((t,i)=>t.size/e.levels[i].size);return{levelCount:e.levels.length,baseSize:e.config.baseSize,ratio:e.config.ratio,smallestSize:Math.min(...t),largestSize:Math.max(...t),sizeRange:Math.max(...t)/Math.min(...t),averageRatio:i.length>0?i.reduce((e,t)=>e+t,0)/i.length:0,unit:e.config.baseUnit}}parseRatio(e){if("number"==typeof e)return e;const t=m.NAMED_RATIOS[e];if(t)return t;const i=parseFloat(e);return isNaN(i)?m.NAMED_RATIOS["minor-third"]:i}calculateLevels(e,t){const i=[],{baseSize:s,baseUnit:n,direction:r,roundToGrid:o,gridSize:a=4}=e;if(i.push({level:0,size:s,ratio:1,cssValue:`${s}${n}`,name:m.LEVEL_NAMES[0]}),"up"===r||"both"===r){const r=e.levels||e.steps||5;for(let e=1;e<=r;e++){const r=s*Math.pow(t,e),c=o?this.roundToGrid(r,a):r;i.push({level:e,size:c,ratio:Math.pow(t,e),cssValue:`${c}${n}`,name:m.LEVEL_NAMES[e.toString()]})}}if("down"===r||"both"===r){const c=e.levels||e.steps||5,l="both"===r?Math.floor(c/2):c;for(let e=1;e<=l;e++){const r=s/Math.pow(t,e),c=o?this.roundToGrid(r,a):r;i.unshift({level:-e,size:c,ratio:1/Math.pow(t,e),cssValue:`${c}${n}`,name:m.LEVEL_NAMES[(-e).toString()]})}}return i.sort((e,t)=>e.level-t.level)}roundToGrid(e,t){return Math.round(e/t)*t}generateCustomProperties(e){const t={};return e.forEach(e=>{const i=e.name||`level-${e.level}`;t[`--font-size-${i}`]=e.cssValue}),t}generateCSSClasses(e){const t={};return e.forEach(e=>{const i=e.name||`level-${e.level}`;t[`.text-${i}`]=`font-size: var(--font-size-${i}, ${e.cssValue});`}),t}generateFluidCSS(e,t,i){const s={};return e.levels.forEach((n,r)=>{const o=t.levels[r];if(!o)return;const a=n.name||`level-${n.level}`,c=n.size,l=o.size,h=i.min,u=(l-c)/(i.max-h),d=c-u*h,m=e.config.baseUnit,p=`clamp(${c}${m}, ${d}${m} + ${100*u}cw, ${l}${m})`;s[`--font-size-${a}`]=p}),s}applyToElements(e,t){const i=[...this.generateScale(t).levels].sort((e,i)=>t.reverse?i.size-e.size:e.size-i.size);e.forEach((e,t)=>{const s=i[t%i.length];if(s){e.style.fontSize=s.cssValue,e.setAttribute("data-proteus-scale-level",s.level.toString()),e.setAttribute("data-proteus-font-size",s.cssValue),s.name&&e.setAttribute("data-proteus-scale-name",s.name)}})}destroy(){}}m.NAMED_RATIOS={"minor-second":1.067,"major-second":1.125,"minor-third":1.2,"major-third":1.25,"perfect-fourth":1.333,"augmented-fourth":1.414,"perfect-fifth":1.5,"golden-ratio":1.618,"major-sixth":1.667,"minor-seventh":1.778,"major-seventh":1.875,octave:2,"major-tenth":2.5,"major-eleventh":2.667,"major-twelfth":3,"double-octave":4},m.LEVEL_NAMES={"-3":"xs","-2":"sm","-1":"base-sm",0:"base",1:"lg",2:"xl",3:"2xl",4:"3xl",5:"4xl",6:"5xl",7:"6xl",8:"7xl",9:"8xl",10:"9xl"};class p{constructor(){this.canvas=document.createElement("canvas"),this.context=this.canvas.getContext("2d")}fitText(e,t,i,s,n){const r=getComputedStyle(e);switch(n.mode){case"single-line":return this.fitSingleLine(t,i,n,r);case"multi-line":return this.fitMultiLine(t,i,s,n,r);case"overflow-aware":return this.fitOverflowAware(t,i,s,n,r);default:throw new Error(`Unknown fitting mode: ${n.mode}`)}}applyFitting(e,t,i){const s=e;s.style.fontSize=`${t.fontSize}${i.unit}`,s.style.lineHeight=t.lineHeight.toString(),"overflow-aware"===i.mode&&t.overflow&&(s.style.overflow=i.overflow||"hidden","ellipsis"===i.overflow&&(s.style.textOverflow="ellipsis",s.style.whiteSpace="nowrap"))}measureText(e,t,i,s="normal"){this.context.font=`${s} ${t}px ${i}`;return{width:this.context.measureText(e).width,height:1.2*t}}fitSingleLine(e,t,i,s){const n=s.fontFamily,r=s.fontWeight;let o=i.minSize,a=i.maxSize,c=0,l=o;for(;a-o>i.precision&&c<i.maxIterations;){const i=(o+a)/2;this.measureText(e,i,n,r).width<=t?(l=i,o=i):a=i,c++}const h=this.measureText(e,l,n,r);return{fontSize:l,lineHeight:i.lineHeight||1.2,actualLines:1,overflow:h.width>t,iterations:c,success:h.width<=t}}fitMultiLine(e,t,i,s,n){const r=n.fontFamily,o=n.fontWeight,a=s.lineHeight||1.4;let c=s.minSize,l=s.maxSize,h=0,u=c;for(;l-c>s.precision&&h<s.maxIterations;){const s=(c+l)/2;this.calculateLines(e,s,t,r,o)*s*a<=i?(u=s,c=s):l=s,h++}const d=this.calculateLines(e,u,t,r,o),m=d*u*a;return{fontSize:u,lineHeight:a,actualLines:d,overflow:m>i,iterations:h,success:m<=i}}fitOverflowAware(e,t,i,s,n){const r=this.fitMultiLine(e,t,i,s,n);if(r.success)return r;const o=this.fitSingleLine(e,t,s,n),a=s.lineHeight||1.4,c=Math.floor(i/(o.fontSize*a));return{fontSize:o.fontSize,lineHeight:a,actualLines:Math.min(c,1),overflow:!0,iterations:o.iterations,success:c>=1}}calculateLines(e,t,i,s,n){this.context.font=`${n} ${t}px ${s}`;const r=e.split(/\s+/);let o=1,a=0;for(const e of r){const t=this.context.measureText(`${e} `).width;a+t>i?(o++,a=t):a+=t}return o}static getOptimalConfig(e){switch(e){case"heading":return{mode:"single-line",minSize:18,maxSize:48,precision:.5,maxIterations:20,lineHeight:1.2};case"body":return{mode:"multi-line",minSize:14,maxSize:20,precision:.25,maxIterations:15,lineHeight:1.5};case"caption":return{mode:"overflow-aware",minSize:12,maxSize:16,precision:.25,maxIterations:10,lineHeight:1.3,overflow:"ellipsis"};case"button":return{mode:"single-line",minSize:14,maxSize:18,precision:.25,maxIterations:10,lineHeight:1,overflow:"ellipsis"};default:return{}}}createResponsiveFitting(e,t){const i=e,s=e.textContent||"",n=t.sort((e,t)=>e.containerSize-t.containerSize),r=new ResizeObserver(t=>{for(const i of t){const t=i.contentRect.width,r=i.contentRect.height;let o=n[0].config;for(const{containerSize:e,config:i}of n)t>=e&&(o=i);const a=this.fitText(e,s,t,r,o);this.applyFitting(e,a,o)}});r.observe(e),i._proteusTextFittingObserver=r}removeResponsiveFitting(e){const t=e,i=t._proteusTextFittingObserver;i&&(i.disconnect(),delete t._proteusTextFittingObserver)}}class g{calculateOptimalLineHeight(e,t,i,s){const n=[];let r=s.baseLineHeight;r=g.CONTENT_TYPE_RATIOS[s.contentType].optimal,n.push(`Base ratio for ${s.contentType}: ${r}`);const o=this.calculateSizeAdjustment(e,s.baseFontSize);r*=o,n.push(`Font size adjustment (${e}px): ×${o.toFixed(3)}`);const a=this.calculateLineLengthAdjustment(t,e);r*=a,n.push(`Line length adjustment (${t} chars): ×${a.toFixed(3)}`);const c=s.language?.split("-")[0]?.toLowerCase()||"en",l=g.LANGUAGE_ADJUSTMENTS[c]||g.LANGUAGE_ADJUSTMENTS.default;r*=l,1!==l&&n.push(`Language adjustment (${c}): ×${l}`);const h=g.DENSITY_MULTIPLIERS[s.density];r*=h,n.push(`Density adjustment (${s.density}): ×${h}`);const u=this.calculateWidthAdjustment(i,e);if(r*=u,1!==u&&n.push(`Container width adjustment: ×${u.toFixed(3)}`),s.accessibility){const e=this.calculateAccessibilityAdjustment(r,s);r=e.lineHeight,e.adjusted&&n.push(`Accessibility adjustment: ${e.reason}`)}const d=r;r=Math.max(s.minLineHeight,Math.min(s.maxLineHeight,r)),r!==d&&n.push(`Clamped to bounds: ${s.minLineHeight}-${s.maxLineHeight}`);const m=this.calculateAccessibilityMetrics(r,e,s);return{lineHeight:Math.round(1e3*r)/1e3,ratio:r,reasoning:n,accessibility:m}}applyOptimization(e,t,i){const s=e;s.style.lineHeight=t.lineHeight.toString(),i.accessibility&&(s.setAttribute("data-proteus-line-height",t.lineHeight.toString()),s.setAttribute("data-proteus-wcag-compliant",t.accessibility.wcagCompliant.toString()))}createResponsiveOptimization(e,t){const i=()=>{const i=getComputedStyle(e),s=parseFloat(i.fontSize),n=e.getBoundingClientRect().width,r=.5*s,o=Math.floor(n/r),a=this.calculateOptimalLineHeight(s,o,n,t);this.applyOptimization(e,a,t)};i();const s=new ResizeObserver(()=>{i()});return s.observe(e),()=>{s.disconnect()}}calculateSizeAdjustment(e,t){const i=e/t;return i<1?1+.2*(1-i):i>1?1-Math.min(.1*(i-1),.15):1}calculateLineLengthAdjustment(e,t){if(e<45)return.95;if(e>75){const t=e-75;return 1+Math.min(.002*t,.2)}return 1}calculateWidthAdjustment(e,t){const i=20*t;if(e<i){return 1+.1*(1-e/i)}return 1}calculateAccessibilityAdjustment(e,t){const i="body"===t.contentType?1.5:1.3;return e<i?{lineHeight:i,adjusted:!0,reason:`WCAG compliance requires minimum ${i}`}:{lineHeight:e,adjusted:!1,reason:""}}calculateAccessibilityMetrics(e,t,i){const s=e>=("body"===i.contentType?1.5:1.3);let n=50;const r=g.CONTENT_TYPE_RATIOS[i.contentType].optimal,o=Math.abs(e-r);return n+=Math.max(0,40-100*o),s&&(n+=10),n=Math.max(0,Math.min(100,n)),{wcagCompliant:s,readabilityScore:Math.round(n)}}static getOptimalConfig(e,t,i=!0){const s=this.CONTENT_TYPE_RATIOS[t];return{baseFontSize:16,baseLineHeight:s.optimal,minLineHeight:s.min,maxLineHeight:s.max,language:e,contentType:t,accessibility:i,density:"comfortable"}}}g.LANGUAGE_ADJUSTMENTS={en:1,zh:1.1,ja:1.1,ko:1.1,ar:1.05,hi:1.05,th:1.15,vi:1.05,de:.98,fr:1,es:1,it:1,pt:1,ru:1.02,default:1},g.CONTENT_TYPE_RATIOS={heading:{min:1,optimal:1.2,max:1.4},body:{min:1.3,optimal:1.5,max:1.8},caption:{min:1.2,optimal:1.4,max:1.6},code:{min:1.2,optimal:1.4,max:1.6},display:{min:.9,optimal:1.1,max:1.3}},g.DENSITY_MULTIPLIERS={compact:.9,comfortable:1,spacious:1.1};class f{constructor(e){this.config={baseFontSize:16,baseLineHeight:1.5,baselineUnit:24,scale:"minor-third",precision:.001,responsive:!0,containerAware:!1,...e},this.baselineGrid=this.config.baselineUnit}generateRhythm(e){this.config.containerAware&&e&&this.adjustBaselineForContainer(e);const t=this.generateSpacingScale(),i=this.generateLineHeights(),s=this.generateMargins(),n=this.generatePaddings();return{baselineGrid:this.baselineGrid,spacingScale:t,lineHeights:i,margins:s,paddings:n}}applyRhythm(e,t){const i=e;Object.entries(t.spacingScale).forEach(([e,t])=>{i.style.setProperty(`--rhythm-${e}`,`${t}px`)}),Object.entries(t.lineHeights).forEach(([e,t])=>{i.style.setProperty(`--line-height-${e}`,t.toString())}),Object.entries(t.margins).forEach(([e,t])=>{i.style.setProperty(`--margin-${e}`,`${t}px`)}),Object.entries(t.paddings).forEach(([e,t])=>{i.style.setProperty(`--padding-${e}`,`${t}px`)}),i.style.setProperty("--baseline-grid",`${t.baselineGrid}px`)}toBaseline(e){return Math.round(e/this.baselineGrid)*this.baselineGrid}calculateBaselineLineHeight(e){const t=e*this.config.baseLineHeight;return this.toBaseline(t)/e}generateResponsiveSpacing(e,t){const i={};return e.forEach((e,s)=>{const n=t[s]||1,r=this.baselineGrid*n;i[`container-${e}`]={xs:.25*r,sm:.5*r,md:r,lg:1.5*r,xl:2*r,xxl:3*r}}),i}generateCSS(e){let t=":root {\n";return t+=` --baseline-grid: ${e.baselineGrid}px;\n`,Object.entries(e.spacingScale).forEach(([e,i])=>{t+=` --rhythm-${e}: ${i}px;\n`}),Object.entries(e.lineHeights).forEach(([e,i])=>{t+=` --line-height-${e}: ${i};\n`}),Object.entries(e.margins).forEach(([e,i])=>{t+=` --margin-${e}: ${i}px;\n`}),Object.entries(e.paddings).forEach(([e,i])=>{t+=` --padding-${e}: ${i}px;\n`}),t+="}\n\n",t+=this.generateUtilityClasses(e),t}validateRhythm(e){const t=[];return Object.entries(e.spacingScale).forEach(([i,s])=>{s%e.baselineGrid!==0&&t.push(`Spacing ${i} (${s}px) doesn't align to baseline grid (${e.baselineGrid}px)`)}),Object.entries(e.margins).forEach(([i,s])=>{s%e.baselineGrid!==0&&t.push(`Margin ${i} (${s}px) doesn't align to baseline grid`)}),{valid:0===t.length,issues:t}}generateSpacingScale(){const e="number"==typeof this.config.scale?this.config.scale:f.SCALE_RATIOS[this.config.scale],t=this.baselineGrid;return{xs:this.toBaseline(t/(e*e)),sm:this.toBaseline(t/e),md:t,lg:this.toBaseline(t*e),xl:this.toBaseline(t*e*e),xxl:this.toBaseline(t*e*e*e)}}generateLineHeights(){return{tight:1.2,normal:1.5,relaxed:1.75,loose:2}}generateMargins(){const e=this.generateSpacingScale();return{none:0,xs:e.xs,sm:e.sm,md:e.md,lg:e.lg,xl:e.xl,auto:-1}}generatePaddings(){const e=this.generateSpacingScale();return{none:0,xs:e.xs,sm:e.sm,md:e.md,lg:e.lg,xl:e.xl}}adjustBaselineForContainer(e){const t=Math.max(.75,Math.min(1.5,e/800));this.baselineGrid=Math.round(this.config.baselineUnit*t)}generateUtilityClasses(e){let t="";return Object.entries(e.spacingScale).forEach(([e,i])=>{t+=`.m-${e} { margin: ${i}px; }\n`,t+=`.mt-${e} { margin-top: ${i}px; }\n`,t+=`.mr-${e} { margin-right: ${i}px; }\n`,t+=`.mb-${e} { margin-bottom: ${i}px; }\n`,t+=`.ml-${e} { margin-left: ${i}px; }\n`,t+=`.mx-${e} { margin-left: ${i}px; margin-right: ${i}px; }\n`,t+=`.my-${e} { margin-top: ${i}px; margin-bottom: ${i}px; }\n`,t+=`.p-${e} { padding: ${i}px; }\n`,t+=`.pt-${e} { padding-top: ${i}px; }\n`,t+=`.pr-${e} { padding-right: ${i}px; }\n`,t+=`.pb-${e} { padding-bottom: ${i}px; }\n`,t+=`.pl-${e} { padding-left: ${i}px; }\n`,t+=`.px-${e} { padding-left: ${i}px; padding-right: ${i}px; }\n`,t+=`.py-${e} { padding-top: ${i}px; padding-bottom: ${i}px; }\n`}),Object.entries(e.lineHeights).forEach(([e,i])=>{t+=`.leading-${e} { line-height: ${i}; }\n`}),t+=".baseline-align { ",t+=`background-image: linear-gradient(to bottom, transparent ${e.baselineGrid-1}px, rgba(255, 0, 0, 0.1) ${e.baselineGrid-1}px, rgba(255, 0, 0, 0.1) ${e.baselineGrid}px, transparent ${e.baselineGrid}px); `,t+=`background-size: 100% ${e.baselineGrid}px; `,t+="}\n",t}createResponsiveRhythm(e,t,i){const s=()=>{const s=e.getBoundingClientRect().width;for(let e=0;e<t.length;e++)s>=t[e]&&i[e];const n=this.generateRhythm(s);this.applyRhythm(e,n)};s();const n=new ResizeObserver(()=>{s()});return n.observe(e),()=>{n.disconnect()}}}f.SCALE_RATIOS={"minor-second":1.067,"major-second":1.125,"minor-third":1.2,"major-third":1.25,"perfect-fourth":1.333,"golden-ratio":1.618};class y{constructor(e,t={}){this.resizeObserver=null,this.mutationObserver=null,this.element=e,this.config={minColumnWidth:250,maxColumns:12,gap:16,aspectRatio:1,masonry:!1,autoFlow:"row",alignment:{justify:"stretch",align:"stretch"},responsive:!0,breakpoints:{},...t},this.state=this.createInitialState(),this.setupGrid()}activate(){this.updateGrid(),this.setupObservers()}deactivate(){this.cleanupObservers(),this.removeGridStyles()}updateConfig(e){this.config={...this.config,...e},this.updateGrid()}getState(){return{...this.state}}recalculate(){this.updateGrid()}addItems(e){const t=document.createDocumentFragment();e.forEach(e=>{this.prepareGridItem(e),t.appendChild(e)}),this.element.appendChild(t),this.updateGrid()}removeItems(e){e.forEach(e=>{e.parentNode===this.element&&this.element.removeChild(e)}),this.updateGrid()}calculateOptimalColumns(e){const t=e-this.getGapValue(),i=this.config.minColumnWidth,s=Math.floor((t+this.getGapValue())/(i+this.getGapValue()));return Math.min(s,this.config.maxColumns)}setupGrid(){this.element.style.display="grid",this.config.masonry?this.setupMasonryGrid():this.setupRegularGrid()}setupRegularGrid(){const e=this.element;e.style.gridAutoFlow=this.config.autoFlow,e.style.justifyContent=this.config.alignment.justify,e.style.alignContent=this.config.alignment.align,e.style.justifyItems=this.config.alignment.justify,e.style.alignItems=this.config.alignment.align}setupMasonryGrid(){const e=this.element;this.supportsMasonry()?e.style.gridTemplateRows="masonry":this.implementJavaScriptMasonry()}updateGrid(){const e=this.element.getBoundingClientRect(),t=e.width,i=e.height,s=this.getActiveConfig(t),n=this.calculateOptimalColumns(t),r=this.getGapValue(),o=(t-r*(n-1))/n,a=s.aspectRatio?o/s.aspectRatio:0;this.state={columns:n,rows:Math.ceil(this.getItemCount()/n),gap:r,itemWidth:o,itemHeight:a,containerWidth:t,containerHeight:i},this.applyGridStyles(),s.masonry&&!this.supportsMasonry()&&this.updateMasonryLayout()}applyGridStyles(){const e=this.element,{columns:t,gap:i,itemHeight:s}=this.state;e.style.gridTemplateColumns=`repeat(${t}, 1fr)`,e.style.gap=`${i}px`,e.style.gridAutoRows=s>0?`${s}px`:"auto",Array.from(this.element.children).forEach(e=>{this.prepareGridItem(e)})}prepareGridItem(e){const t=e;t.style.boxSizing="border-box",this.config.aspectRatio&&!this.config.masonry&&(t.style.aspectRatio=this.config.aspectRatio.toString()),t.classList.add("proteus-grid-item")}implementJavaScriptMasonry(){const e=Array.from(this.element.children),{columns:t,gap:i}=this.state,s=new Array(t).fill(0);e.forEach((e,t)=>{const n=s.indexOf(Math.min(...s)),r=n,o=Math.floor(s[n]/(this.state.itemHeight+i));e.style.gridColumnStart=(r+1).toString(),e.style.gridRowStart=(o+1).toString();const a=e.getBoundingClientRect().height||this.state.itemHeight;s[n]+=a+i})}updateMasonryLayout(){requestAnimationFrame(()=>{this.implementJavaScriptMasonry()})}setupObservers(){this.config.responsive&&(this.resizeObserver=new ResizeObserver(()=>{this.updateGrid()}),this.resizeObserver.observe(this.element),this.mutationObserver=new MutationObserver(()=>{this.updateGrid()}),this.mutationObserver.observe(this.element,{childList:!0,subtree:!1}))}cleanupObservers(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}removeGridStyles(){const e=this.element;e.style.removeProperty("display"),e.style.removeProperty("grid-template-columns"),e.style.removeProperty("grid-template-rows"),e.style.removeProperty("gap"),e.style.removeProperty("grid-auto-flow"),e.style.removeProperty("justify-content"),e.style.removeProperty("align-content"),e.style.removeProperty("justify-items"),e.style.removeProperty("align-items"),e.style.removeProperty("grid-auto-rows"),Array.from(this.element.children).forEach(e=>{const t=e;t.style.removeProperty("grid-column-start"),t.style.removeProperty("grid-row-start"),t.style.removeProperty("aspect-ratio"),t.classList.remove("proteus-grid-item")})}getActiveConfig(e){let t={...this.config};if(this.config.breakpoints){const i=Object.entries(this.config.breakpoints).map(([e,t])=>({name:e,width:parseInt(e),config:t})).sort((e,t)=>e.width-t.width);for(const s of i)e>=s.width&&(t={...t,...s.config})}return t}getGapValue(){if("fluid"===this.config.gap){const e=this.element.getBoundingClientRect().width;return Math.max(8,Math.min(32,.02*e))}return this.config.gap}getItemCount(){return this.element.children.length}supportsMasonry(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("grid-template-rows","masonry")}createInitialState(){return{columns:1,rows:1,gap:16,itemWidth:0,itemHeight:0,containerWidth:0,containerHeight:0}}}class b{constructor(e,t={}){this.resizeObserver=null,this.mutationObserver=null,this.element=e,this.config={direction:"row",wrap:"auto",justify:"flex-start",align:"stretch",gap:16,responsive:!0,autoWrap:!0,minItemWidth:200,maxItemWidth:800,itemGrowRatio:1,itemShrinkRatio:1,breakpoints:{},...t},this.state=this.createInitialState(),this.setupFlexbox()}activate(){this.updateFlexbox(),this.setupObservers()}deactivate(){this.cleanupObservers(),this.removeFlexboxStyles()}updateConfig(e){this.config={...this.config,...e},this.updateFlexbox()}getState(){return{...this.state}}configureItem(e,t){const i=e;i.style.flexGrow=t.grow.toString(),i.style.flexShrink=t.shrink.toString(),i.style.flexBasis="number"==typeof t.basis?`${t.basis}px`:t.basis,void 0!==t.order&&(i.style.order=t.order.toString()),t.alignSelf&&(i.style.alignSelf=t.alignSelf)}autoConfigureItems(){const e=Array.from(this.element.children),t=this.calculateOptimalItemConfig();e.forEach(e=>{this.configureItem(e,t)})}shouldWrap(){if(!this.config.autoWrap)return"wrap"===this.config.wrap;const e=this.element.getBoundingClientRect().width,t=this.element.children.length,i=this.getGapValue();return t*(this.config.minItemWidth||200)+i*(t-1)>e}calculateSpaceDistribution(){const e=this.element.getBoundingClientRect().width,t=this.element.children.length,i=this.getGapValue();if(this.shouldWrap()){const t=this.calculateItemsPerLine();return{itemWidth:(e-i*(t-1))/t,gap:i,remainingSpace:0}}{const s=i*(t-1),n=(e-s)/t;return{itemWidth:n,gap:i,remainingSpace:Math.max(0,e-(t*n+s))}}}calculateItemsPerLine(){const e=this.element.getBoundingClientRect().width,t=this.config.minItemWidth||200,i=this.getGapValue();let s=1,n=this.element.children.length,r=1;for(;s<=n;){const o=Math.floor((s+n)/2);o*t+i*(o-1)<=e?(r=o,s=o+1):n=o-1}return r}setupFlexbox(){this.element.style.display="flex",this.applyFlexboxStyles()}updateFlexbox(){const e=this.element.getBoundingClientRect(),t=this.getActiveConfig(e.width);this.state={containerWidth:e.width,containerHeight:e.height,itemCount:this.element.children.length,wrappedLines:this.calculateWrappedLines(),optimalItemWidth:this.calculateSpaceDistribution().itemWidth,actualGap:this.getGapValue(),overflow:this.checkOverflow()},this.applyFlexboxStyles(t),this.config.autoWrap&&this.autoConfigureItems()}applyFlexboxStyles(e=this.config){const t=this.element;t.style.flexDirection=e.direction,t.style.flexWrap="auto"===e.wrap?this.shouldWrap()?"wrap":"nowrap":e.wrap,t.style.justifyContent=e.justify,t.style.alignItems=e.align,t.style.gap=`${this.getGapValue()}px`}calculateOptimalItemConfig(){const e=this.calculateSpaceDistribution(),t=this.shouldWrap();return{grow:t?0:this.config.itemGrowRatio,shrink:this.config.itemShrinkRatio,basis:t?`${e.itemWidth}px`:"auto",alignSelf:"auto"}}calculateWrappedLines(){if(!this.shouldWrap())return 1;const e=this.calculateItemsPerLine();return Math.ceil(this.element.children.length/e)}checkOverflow(){const e=this.element.getBoundingClientRect().width,t=this.calculateSpaceDistribution();return this.element.children.length*t.itemWidth+(this.element.children.length-1)*t.gap>e&&!this.shouldWrap()}getActiveConfig(e){let t={...this.config};if(this.config.breakpoints){const i=Object.entries(this.config.breakpoints).map(([e,t])=>({name:e,width:parseInt(e),config:t})).sort((e,t)=>e.width-t.width);for(const s of i)e>=s.width&&(t={...t,...s.config})}return t}getGapValue(){if("fluid"===this.config.gap){const e=this.element.getBoundingClientRect().width;return Math.max(8,Math.min(32,.02*e))}return this.config.gap}setupObservers(){this.config.responsive&&(this.resizeObserver=new ResizeObserver(()=>{this.updateFlexbox()}),this.resizeObserver.observe(this.element),this.mutationObserver=new MutationObserver(()=>{this.updateFlexbox()}),this.mutationObserver.observe(this.element,{childList:!0,subtree:!1}))}cleanupObservers(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}removeFlexboxStyles(){const e=this.element;e.style.removeProperty("display"),e.style.removeProperty("flex-direction"),e.style.removeProperty("flex-wrap"),e.style.removeProperty("justify-content"),e.style.removeProperty("align-items"),e.style.removeProperty("gap"),Array.from(this.element.children).forEach(e=>{const t=e;t.style.removeProperty("flex-grow"),t.style.removeProperty("flex-shrink"),t.style.removeProperty("flex-basis"),t.style.removeProperty("order"),t.style.removeProperty("align-self")})}createInitialState(){return{containerWidth:0,containerHeight:0,itemCount:0,wrappedLines:1,optimalItemWidth:0,actualGap:16,overflow:!1}}}class v{constructor(e,t={}){this.mutationObserver=null,this.element=e,this.config={pattern:"natural",direction:"auto",language:"en",accessibility:!0,focusManagement:!0,skipLinks:!0,landmarks:!0,readingOrder:"auto",customFlow:[],...t},this.state=this.createInitialState(),this.activate()}activate(){this.analyzeContent(),this.applyFlowPattern(),this.setupAccessibility(),this.setupObservers()}deactivate(){this.cleanupObservers(),this.removeFlowStyles(),this.removeAccessibilityFeatures()}updateConfig(e){this.config={...this.config,...e},this.activate()}getState(){return{...this.state}}setTabOrder(e){e.forEach((e,t)=>{e.tabIndex=t+1}),this.state.tabOrder=e}addSkipLink(e,t){if(!this.config.skipLinks)return;const i=document.createElement("a");i.href=`#${this.ensureId(e)}`,i.textContent=t,i.className="proteus-skip-link",i.style.cssText="\n position: absolute;\n top: -40px;\n left: 6px;\n background: #000;\n color: #fff;\n padding: 8px;\n text-decoration: none;\n z-index: 1000;\n transition: top 0.3s;\n ",i.addEventListener("focus",()=>{i.style.top="6px"}),i.addEventListener("blur",()=>{i.style.top="-40px"}),document.body.insertBefore(i,document.body.firstChild),this.state.skipTargets.push(e)}analyzeContent(){this.state.direction=this.detectReadingDirection(),this.state.focusableElements=this.findFocusableElements(),this.state.landmarks=this.identifyLandmarks(),this.state.currentPattern=this.determineOptimalPattern()}applyFlowPattern(){let e;if("custom"===this.config.pattern)e=this.config.customFlow;else if("auto"===this.config.pattern){const t=this.determineOptimalPattern();e=v.READING_PATTERNS[t]}else e=v.READING_PATTERNS[this.config.pattern];if(!e)return;const t=this.sortElementsByPattern(e);this.applyVisualFlow(t),this.config.focusManagement&&this.setLogicalTabOrder(t)}setupAccessibility(){this.config.accessibility&&(this.config.landmarks&&this.addLandmarks(),this.config.skipLinks&&this.addDefaultSkipLinks(),this.setReadingOrder())}detectReadingDirection(){if("auto"!==this.config.direction)return this.config.direction;const e=this.config.language?.split("-")[0]?.toLowerCase();return e&&v.RTL_LANGUAGES.includes(e)?"rtl":"ltr"}findFocusableElements(){const e=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])','[contenteditable="true"]'].join(", ");return Array.from(this.element.querySelectorAll(e))}identifyLandmarks(){const e=new Map;return Object.entries({banner:'header, [role="banner"]',main:'main, [role="main"]',navigation:'nav, [role="navigation"]',complementary:'aside, [role="complementary"]',contentinfo:'footer, [role="contentinfo"]',search:'[role="search"]',form:'form, [role="form"]'}).forEach(([t,i])=>{const s=this.element.querySelector(i);s&&e.set(t,s)}),e}determineOptimalPattern(){if("auto"!==this.config.pattern)return this.config.pattern;const e=this.state.landmarks.has("banner"),t=this.state.landmarks.has("complementary"),i=this.state.landmarks.has("navigation");return e&&t&&i?"z-pattern":e&&t?"f-pattern":"natural"}sortElementsByPattern(e){const t=[];return e.forEach(e=>{Array.from(this.element.querySelectorAll(e.selector)).forEach(i=>{t.push({element:i,priority:e.priority})})}),t.sort((e,t)=>e.priority!==t.priority?e.priority-t.priority:e.element.compareDocumentPosition(t.element)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1).map(e=>e.element)}applyVisualFlow(e){e.forEach((e,t)=>{const i=e;i.style.setProperty("--flow-order",t.toString()),i.classList.add("proteus-flow-item")}),this.addFlowCSS()}setLogicalTabOrder(e){const t=e.filter(e=>this.state.focusableElements.includes(e));t.forEach((e,t)=>{e.tabIndex=t+1}),this.state.tabOrder=t}addLandmarks(){this.state.landmarks.forEach((e,t)=>{const i=e;if(i.getAttribute("role")||i.setAttribute("role",t),!i.getAttribute("aria-label")&&!i.getAttribute("aria-labelledby")){const e=this.generateLandmarkLabel(t);i.setAttribute("aria-label",e)}})}addDefaultSkipLinks(){const e=this.state.landmarks.get("main");e&&this.addSkipLink(e,"Skip to main content");const t=this.state.landmarks.get("navigation");t&&this.addSkipLink(t,"Skip to navigation")}setReadingOrder(){"visual"===this.config.readingOrder?this.element.style.setProperty("--reading-order","visual"):this.element.style.setProperty("--reading-order","logical")}generateLandmarkLabel(e){return{banner:"Site header",main:"Main content",navigation:"Site navigation",complementary:"Sidebar",contentinfo:"Site footer",search:"Search",form:"Form"}[e]||e}addFlowCSS(){const e="proteus-flow-styles";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent='\n .proteus-flow-item {\n order: var(--flow-order, 0);\n }\n \n .proteus-skip-link:focus {\n clip: auto !important;\n height: auto !important;\n margin: 0 !important;\n overflow: visible !important;\n position: absolute !important;\n width: auto !important;\n }\n \n [dir="rtl"] .proteus-flow-item {\n direction: rtl;\n }\n ',document.head.appendChild(t)}ensureId(e){return e.id||(e.id=`proteus-flow-${Math.random().toString(36).substring(2,11)}`),e.id}setupObservers(){this.mutationObserver=new MutationObserver(()=>{this.analyzeContent(),this.applyFlowPattern()}),this.mutationObserver.observe(this.element,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["role","tabindex"]})}cleanupObservers(){this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}removeFlowStyles(){this.element.querySelectorAll(".proteus-flow-item").forEach(e=>{const t=e;t.classList.remove("proteus-flow-item"),t.style.removeProperty("--flow-order")});const e=document.getElementById("proteus-flow-styles");e&&e.remove()}removeAccessibilityFeatures(){document.querySelectorAll(".proteus-skip-link").forEach(e=>e.remove()),this.state.tabOrder.forEach(e=>{e.removeAttribute("tabindex")})}createInitialState(){return{currentPattern:"natural",direction:"ltr",focusableElements:[],tabOrder:[],landmarks:new Map,skipTargets:[]}}}v.READING_PATTERNS={"z-pattern":[{selector:'header, [role="banner"]',region:"header",priority:1},{selector:'nav, [role="navigation"]',region:"navigation",priority:2},{selector:'main, [role="main"]',region:"main",priority:3},{selector:'aside, [role="complementary"]',region:"sidebar",priority:4},{selector:'footer, [role="contentinfo"]',region:"footer",priority:5}],"f-pattern":[{selector:'header, [role="banner"]',region:"header",priority:1},{selector:'main, [role="main"]',region:"main",priority:2},{selector:'aside, [role="complementary"]',region:"sidebar",priority:3},{selector:'nav, [role="navigation"]',region:"navigation",priority:4},{selector:'footer, [role="contentinfo"]',region:"footer",priority:5}],gutenberg:[{selector:'nav, [role="navigation"]',region:"navigation",priority:1},{selector:'header, [role="banner"]',region:"header",priority:2},{selector:'main, [role="main"]',region:"main",priority:3},{selector:'aside, [role="complementary"]',region:"sidebar",priority:4},{selector:'footer, [role="contentinfo"]',region:"footer",priority:5}],natural:[{selector:'header, [role="banner"]',region:"header",priority:1},{selector:'main, [role="main"]',region:"main",priority:2},{selector:'nav, [role="navigation"]',region:"navigation",priority:3},{selector:'aside, [role="complementary"]',region:"sidebar",priority:4},{selector:'footer, [role="contentinfo"]',region:"footer",priority:5}]},v.RTL_LANGUAGES=["ar","he","fa","ur","yi","ji","iw","ku","ps","sd"];class w{constructor(e,t={}){this.resizeObserver=null,this.element=e,this.config={baseSize:16,scale:"minor-third",density:"comfortable",containerAware:!0,accessibility:!0,touchTargets:!0,minTouchSize:w.WCAG_MIN_TOUCH_SIZE,maxSpacing:128,responsive:!0,breakpoints:{},...t},this.state=this.createInitialState(),this.setupSpacing()}activate(){this.calculateSpacing(),this.applySpacing(),this.setupObservers()}deactivate(){this.cleanupObservers(),this.removeSpacing()}updateConfig(e){this.config={...this.config,...e},this.activate()}getState(){return{...this.state}}applyToElement(e,t){const i=this.state.currentScale[t];e.style.setProperty("--spacing",`${i}px`),this.state.appliedSpacing.set(e,t)}applyMargin(e,t){const i="number"==typeof t?t:this.state.currentScale[t];e.style.margin=`${i}px`}applyPadding(e,t){const i="number"==typeof t?t:this.state.currentScale[t];e.style.padding=`${i}px`}applyGap(e,t){const i="number"==typeof t?t:this.state.currentScale[t];e.style.gap=`${i}px`}ensureTouchTargets(){if(!this.config.touchTargets)return;this.findInteractiveElements().forEach(e=>{this.makeTouchCompliant(e)})}generateScale(){const e="number"==typeof this.config.scale?this.config.scale:w.SCALE_RATIOS[this.config.scale],t=w.DENSITY_MULTIPLIERS[this.config.density],i=this.calculateContainerMultiplier(),s=this.config.baseSize*t*i;return{xs:Math.round(s/(e*e)),sm:Math.round(s/e),md:Math.round(s),lg:Math.round(s*e),xl:Math.round(s*e*e),xxl:Math.min(Math.round(s*e*e*e),this.config.maxSpacing)}}calculateOptimalSpacing(e){switch(e){case"text":return"compact"===this.config.density?"sm":"md";case"interactive":return this.config.accessibility?"lg":"md";case"layout":return"spacious"===this.config.density?"xl":"lg";default:return"md"}}validateAccessibility(){const e=[];if(this.config.touchTargets){this.findInteractiveElements().forEach(t=>{const i=t.getBoundingClientRect(),s=this.config.minTouchSize;(i.width<s||i.height<s)&&e.push(`Touch target too small: ${i.width}x${i.height} (minimum: ${s}x${s})`)})}const t=this.state.currentScale,i=[t.sm/t.xs,t.md/t.sm,t.lg/t.md,t.xl/t.lg];return i.length>0&&i.some(e=>Math.abs(e-i[0])>.1)&&e.push("Inconsistent spacing ratios detected"),{compliant:0===e.length,issues:e}}setupSpacing(){this.calculateSpacing()}calculateSpacing(){const e=this.element.getBoundingClientRect();this.getActiveConfig(e.width),this.state={currentScale:this.generateScale(),containerSize:e.width,scaleFactor:this.calculateContainerMultiplier(),touchCompliant:this.validateTouchCompliance(),appliedSpacing:new Map}}applySpacing(){const e=this.element,t=this.state.currentScale;Object.entries(t).forEach(([t,i])=>{e.style.setProperty(`--spacing-${t}`,`${i}px`)}),this.addSpacingCSS(),this.config.touchTargets&&this.ensureTouchTargets()}calculateContainerMultiplier(){if(!this.config.containerAware)return 1;const e=this.element.getBoundingClientRect().width/800;return Math.max(.75,Math.min(1.5,e))}getActiveConfig(e){let t={...this.config};if(this.config.breakpoints){const i=Object.entries(this.config.breakpoints).map(([e,t])=>({name:e,width:parseInt(e),config:t})).sort((e,t)=>e.width-t.width);for(const s of i)e>=s.width&&(t={...t,...s.config})}return t}findInteractiveElements(){const e=["button","a[href]","input","select","textarea",'[tabindex]:not([tabindex="-1"])','[role="button"]','[role="link"]',"[onclick]"].join(", ");return Array.from(this.element.querySelectorAll(e))}makeTouchCompliant(e){const t=e,i=e.getBoundingClientRect(),s=this.config.minTouchSize;(i.width<s||i.height<s)&&(t.style.minWidth=`${s}px`,t.style.minHeight=`${s}px`,t.style.display=t.style.display||"inline-block");const n=this.state.currentScale.sm;t.style.margin=n/2+"px"}validateTouchCompliance(){if(!this.config.touchTargets)return!0;return this.findInteractiveElements().every(e=>{const t=e.getBoundingClientRect();return t.width>=this.config.minTouchSize&&t.height>=this.config.minTouchSize})}addSpacingCSS(){const e="proteus-spacing-styles";if(document.getElementById(e))return;const t=document.createElement("style");t.id=e;const i=this.state.currentScale;let s=":root {\n";Object.entries(i).forEach(([e,t])=>{s+=` --spacing-${e}: ${t}px;\n`}),s+="}\n\n",Object.entries(i).forEach(([e,t])=>{s+=`.m-${e} { margin: ${t}px; }\n`,s+=`.mt-${e} { margin-top: ${t}px; }\n`,s+=`.mr-${e} { margin-right: ${t}px; }\n`,s+=`.mb-${e} { margin-bottom: ${t}px; }\n`,s+=`.ml-${e} { margin-left: ${t}px; }\n`,s+=`.mx-${e} { margin-left: ${t}px; margin-right: ${t}px; }\n`,s+=`.my-${e} { margin-top: ${t}px; margin-bottom: ${t}px; }\n`,s+=`.p-${e} { padding: ${t}px; }\n`,s+=`.pt-${e} { padding-top: ${t}px; }\n`,s+=`.pr-${e} { padding-right: ${t}px; }\n`,s+=`.pb-${e} { padding-bottom: ${t}px; }\n`,s+=`.pl-${e} { padding-left: ${t}px; }\n`,s+=`.px-${e} { padding-left: ${t}px; padding-right: ${t}px; }\n`,s+=`.py-${e} { padding-top: ${t}px; padding-bottom: ${t}px; }\n`,s+=`.gap-${e} { gap: ${t}px; }\n`}),s+=`\n .touch-target {\n min-width: ${this.config.minTouchSize}px;\n min-height: ${this.config.minTouchSize}px;\n display: inline-block;\n }\n \n .touch-spacing {\n margin: ${this.state.currentScale.sm/2}px;\n }\n `,t.textContent=s,document.head.appendChild(t)}setupObservers(){this.config.responsive&&(this.resizeObserver=new ResizeObserver(()=>{this.calculateSpacing(),this.applySpacing()}),this.resizeObserver.observe(this.element))}cleanupObservers(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null)}removeSpacing(){const e=this.element,t=this.state.currentScale;Object.keys(t).forEach(t=>{e.style.removeProperty(`--spacing-${t}`)}),this.state.appliedSpacing.forEach((e,t)=>{t.style.removeProperty("--spacing")});const i=document.getElementById("proteus-spacing-styles");i&&i.remove()}createInitialState(){return{currentScale:{xs:4,sm:8,md:16,lg:24,xl:32,xxl:48},containerSize:0,scaleFactor:1,touchCompliant:!0,appliedSpacing:new Map}}}w.SCALE_RATIOS={"minor-second":1.067,"major-second":1.125,"minor-third":1.2,"major-third":1.25,"perfect-fourth":1.333,"golden-ratio":1.618},w.DENSITY_MULTIPLIERS={compact:.8,comfortable:1,spacious:1.25},w.WCAG_MIN_TOUCH_SIZE=44;class S{constructor(e,t={}){this.resizeObserver=null,this.mutationObserver=null,this.element=e,this.config={priorities:new Map,breakpoints:{},accessibility:!0,animations:!0,focusManagement:!0,preserveTabOrder:!0,animationDuration:300,easing:"cubic-bezier(0.4, 0.0, 0.2, 1)",...t},this.state=this.createInitialState(),this.setupReordering()}activate(){this.captureOriginalOrder(),this.applyReordering(),this.setupObservers()}deactivate(){this.cleanupObservers(),this.restoreOriginalOrder()}updateConfig(e){this.config={...this.config,...e},this.applyReordering()}setPriority(e,t){this.config.priorities.set(e,t),this.applyReordering()}addRule(e,t){this.config.breakpoints[e]||(this.config.breakpoints[e]=[]),this.config.breakpoints[e].push(t),this.applyReordering()}getState(){return{...this.state}}reorder(e){this.config.animations?this.animateReorder(e):this.applyOrder(e)}restoreOriginalOrder(){this.reorder(this.state.originalOrder)}setupReordering(){this.captureOriginalOrder()}captureOriginalOrder(){this.state.originalOrder=Array.from(this.element.children),this.state.currentOrder=[...this.state.originalOrder]}applyReordering(){const e=this.element.getBoundingClientRect().width,t=this.getActiveRules(e);this.state.activeRules=t;const i=this.calculateNewOrder(t);this.config.animations&&!this.arraysEqual(i,this.state.currentOrder)?this.animateReorder(i):this.applyOrder(i)}getActiveRules(e){const t=[];return Object.entries(this.config.breakpoints).forEach(([i,s])=>{const n=parseInt(i);e>=n&&t.push(...s)}),t}calculateNewOrder(e){let t=[...this.state.originalOrder];return this.config.priorities.size>0&&t.sort((e,t)=>(this.config.priorities.get(e)||0)-(this.config.priorities.get(t)||0)),e.forEach(e=>{Array.from(this.element.querySelectorAll(e.selector)).forEach(i=>{this.shouldApplyRule(e)&&(t=this.applyRule(t,i,e))})}),t}shouldApplyRule(e){if(!e.condition||!e.value)return!0;const t=this.element.getBoundingClientRect();switch(e.condition){case"min-width":return t.width>=e.value;case"max-width":return t.width<=e.value;case"aspect-ratio":return t.width/t.height>=e.value;default:return!0}}applyRule(e,t,i){const s=e.indexOf(t);if(-1===s)return e;const n=[...e];switch(n.splice(s,1),i.action){case"move-first":n.unshift(t);break;case"move-last":default:n.push(t);break;case"move-before":if(i.target){const e=this.element.querySelector(i.target),s=n.indexOf(e);-1!==s?n.splice(s,0,t):n.push(t)}break;case"move-after":if(i.target){const e=this.element.querySelector(i.target),s=n.indexOf(e);-1!==s?n.splice(s+1,0,t):n.push(t)}break;case"hide":t.style.display="none",n.push(t);break;case"show":t.style.display="",n.push(t)}return n}animateReorder(e){if(this.state.animating)return;this.state.animating=!0;const t=new Map;this.state.currentOrder.forEach(e=>{t.set(e,{element:e,first:e.getBoundingClientRect(),last:{x:0,y:0,width:0,height:0},invert:{x:0,y:0},play:!1})});const i=this.preserveFocus();this.applyOrder(e),t.forEach((e,t)=>{e.last=t.getBoundingClientRect(),e.invert={x:e.first.left-e.last.left,y:e.first.top-e.last.top},0===e.invert.x&&0===e.invert.y||(t.style.transform=`translate(${e.invert.x}px, ${e.invert.y}px)`,e.play=!0)}),requestAnimationFrame(()=>{t.forEach((e,t)=>{if(e.play){const e=t;e.style.transition=`transform ${this.config.animationDuration}ms ${this.config.easing}`,e.style.transform="translate(0, 0)"}}),setTimeout(()=>{t.forEach((e,t)=>{const i=t;i.style.transition="",i.style.transform=""}),this.state.animating=!1,this.restoreFocus(i),this.config.accessibility&&this.updateAccessibility()},this.config.animationDuration)}),this.state.flipStates=t}applyOrder(e){const t=document.createDocumentFragment();e.forEach(e=>{t.appendChild(e)}),this.element.appendChild(t),this.state.currentOrder=e}preserveFocus(){if(!this.config.focusManagement)return null;const e=document.activeElement;return e&&this.element.contains(e)?(this.state.focusedElement=e,e):null}restoreFocus(e){this.config.focusManagement&&e&&document.contains(e)&&e.focus()}updateAccessibility(){this.config.accessibility&&(this.config.preserveTabOrder&&this.updateTabOrder(),this.announceChanges())}updateTabOrder(){this.state.currentOrder.filter(e=>e.tabIndex>=0||this.isFocusable(e)).forEach((e,t)=>{e.tabIndex=t+1})}isFocusable(e){return["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[contenteditable="true"]'].some(t=>e.matches(t))}announceChanges(){const e=document.createElement("div");e.setAttribute("aria-live","polite"),e.setAttribute("aria-atomic","true"),e.style.cssText="\n position: absolute;\n left: -10000px;\n width: 1px;\n height: 1px;\n overflow: hidden;\n ",e.textContent="Content order has been updated",document.body.appendChild(e),setTimeout(()=>{document.body.removeChild(e)},1e3)}arraysEqual(e,t){return e.length===t.length&&e.every((e,i)=>e===t[i])}setupObservers(){this.resizeObserver=new ResizeObserver(()=>{this.applyReordering()}),this.resizeObserver.observe(this.element),this.mutationObserver=new MutationObserver(()=>{this.captureOriginalOrder(),this.applyReordering()}),this.mutationObserver.observe(this.element,{childList:!0,subtree:!1})}cleanupObservers(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null)}createInitialState(){return{originalOrder:[],currentOrder:[],activeRules:[],focusedElement:null,animating:!1,flipStates:new Map}}}class A{constructor(e,t={}){this.resizeObserver=null,this.intersectionObserver=null,this.sources=[],this.element=e,this.config={formats:["avif","webp","jpeg"],sizes:[320,640,768,1024,1280,1920],quality:80,lazyLoading:!0,artDirection:!1,containerBased:!0,placeholder:"blur",placeholderColor:"#f0f0f0",fadeInDuration:300,retina:!0,progressive:!0,...t},this.state=this.createInitialState(),this.setupImage()}activate(){this.detectFormatSupport(),this.generateSources(),this.setupObservers(),this.config.lazyLoading||this.loadImage()}deactivate(){this.cleanupObservers(),this.removeImageFeatures()}updateConfig(e){this.config={...this.config,...e},this.generateSources(),this.updateImage()}getState(){return{...this.state}}load(){this.loadImage()}preload(){return new Promise((e,t)=>{const i=this.getOptimalSource();if(!i)return void t(new Error("No optimal source found"));const s=new Image;s.onload=()=>e(),s.onerror=()=>t(new Error("Failed to preload image")),s.src=i.src})}setupImage(){this.addPlaceholder(),this.setupImageElement()}async detectFormatSupport(){const e=["webp","avif"];for(const t of e)if(!A.FORMAT_SUPPORT.has(t)){const e=await this.testFormatSupport(t);A.FORMAT_SUPPORT.set(t,e)}}testFormatSupport(e){return new Promise(t=>{const i=new Image;i.onload=()=>t(i.width>0&&i.height>0),i.onerror=()=>t(!1);i.src={webp:"data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA",avif:"data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAAB0AAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAIAAAACAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQ0MAAAAABNjb2xybmNseAACAAIAAYAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAACVtZGF0EgAKCBgABogQEAwgMg8f8D///8WfhwB8+ErK42A="}[e]||""})}generateSources(){const e=this.getBaseSrc();e&&(this.sources=[],this.config.formats.forEach(t=>{this.isFormatSupported(t)&&this.config.sizes.forEach(i=>{const s={src:this.generateSrcUrl(e,t,i),format:t,width:i,height:this.calculateHeight(i),quality:this.config.quality};if(this.config.containerBased&&(s.media=`(min-width: ${i}px)`),this.sources.push(s),this.config.retina){const n={...s,src:this.generateSrcUrl(e,t,2*i),width:2*i,height:this.calculateHeight(2*i)};s.media&&(n.media=`${s.media} and (-webkit-min-device-pixel-ratio: 2)`),this.sources.push(n)}})}),this.sources.sort((e,t)=>{const i=this.config.formats.indexOf(e.format),s=this.config.formats.indexOf(t.format);return i!==s?i-s:e.width-t.width}))}getOptimalSource(){if(0===this.sources.length)return null;const e=this.state.containerSize.width*(window.devicePixelRatio||1);return this.sources.filter(t=>t.width>=e||t===this.sources[this.sources.length-1])[0]||this.sources[this.sources.length-1]||null}loadImage(){if(this.state.loading||this.state.loaded)return;this.state.loading=!0;const e=this.getOptimalSource();if(!e)return this.state.loading=!1,void(this.state.error=!0);const t=new Image;t.onload=()=>{this.state.loaded=!0,this.state.loading=!1,this.state.currentSrc=e.src,this.state.optimalSource=e,this.applyImage(t),this.removePlaceholder()},t.onerror=()=>{this.state.loading=!1,this.state.error=!0,this.handleImageError()},t.src=e.src}applyImage(e){if("IMG"===this.element.tagName){const t=this.element;t.src=e.src,t.style.opacity="0",requestAnimationFrame(()=>{t.style.transition=`opacity ${this.config.fadeInDuration}ms ease-in-out`,t.style.opacity="1"})}else{const t=this.element;t.style.backgroundImage=`url(${e.src})`,t.style.backgroundSize="cover",t.style.backgroundPosition="center",t.style.opacity="0",requestAnimationFrame(()=>{t.style.transition=`opacity ${this.config.fadeInDuration}ms ease-in-out`,t.style.opacity="1"})}}addPlaceholder(){if("none"===this.config.placeholder)return;const e=this.element;switch(this.config.placeholder){case"color":e.style.backgroundColor=this.config.placeholderColor||"#f0f0f0";break;case"blur":this.addBlurPlaceholder();break;case"svg":this.addSvgPlaceholder()}}addBlurPlaceholder(){const e=document.createElement("canvas");e.width=40,e.height=30;const t=e.getContext("2d");if(t){const e=t.createLinearGradient(0,0,40,30);e.addColorStop(0,"#f0f0f0"),e.addColorStop(1,"#e0e0e0"),t.fillStyle=e,t.fillRect(0,0,40,30)}const i=e.toDataURL(),s=this.element;"IMG"===this.element.tagName?this.element.src=i:(s.style.backgroundImage=`url(${i})`,s.style.filter="blur(5px)")}addSvgPlaceholder(){const e=`data:image/svg+xml;base64,${btoa(`\n <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 300">\n <rect width="400" height="300" fill="${this.config.placeholderColor}"/>\n <circle cx="200" cy="150" r="50" fill="#ddd"/>\n </svg>\n `)}`;"IMG"===this.element.tagName?this.element.src=e:this.element.style.backgroundImage=`url(${e})`}removePlaceholder(){const e=this.element;"blur"===this.config.placeholder&&(e.style.filter=""),"color"===this.config.placeholder&&(e.style.backgroundColor="")}handleImageError(){const e=this.sources.find(e=>"jpeg"===e.format);if(e&&e!==this.state.optimalSource){this.state.error=!1,this.state.loading=!0;const t=new Image;t.onload=()=>{this.state.loaded=!0,this.state.loading=!1,this.applyImage(t)},t.src=e.src}}setupImageElement(){if("IMG"===this.element.tagName){const e=this.element;e.loading=this.config.lazyLoading?"lazy":"eager",e.decoding="async"}}updateImage(){const e=this.getOptimalSource();e&&e!==this.state.optimalSource&&(this.state.loaded=!1,this.loadImage())}getBaseSrc(){return"IMG"===this.element.tagName?this.element.src||this.element.dataset.src||null:this.element.dataset.src||null}generateSrcUrl(e,t,i){const s=new URL(e,window.location.origin);return s.searchParams.set("format",t),s.searchParams.set("width",i.toString()),s.searchParams.set("quality",this.config.quality.toString()),this.config.progressive&&s.searchParams.set("progressive","true"),s.toString()}calculateHeight(e){return Math.round(e*(9/16))}isFormatSupported(e){return"jpeg"===e||"png"===e||(A.FORMAT_SUPPORT.get(e)||!1)}setupObservers(){this.resizeObserver=new ResizeObserver(e=>{for(const t of e)this.state.containerSize={width:t.contentRect.width,height:t.contentRect.height},this.config.containerBased&&this.updateImage()}),this.resizeObserver.observe(this.element),this.config.lazyLoading&&(this.intersectionObserver=new IntersectionObserver(e=>{for(const t of e)t.isIntersecting&&(this.state.intersecting=!0,this.loadImage(),this.intersectionObserver?.unobserve(this.element))},{rootMargin:"50px"}),this.intersectionObserver.observe(this.element))}cleanupObservers(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null)}removeImageFeatures(){this.removePlaceholder();const e=this.element;e.style.transition="",e.style.opacity="",e.style.filter=""}createInitialState(){return{loaded:!1,loading:!1,error:!1,currentSrc:"",containerSize:{width:0,height:0},optimalSource:null,intersecting:!1}}}A.FORMAT_SUPPORT=new Map,A.MIME_TYPES={webp:"image/webp",avif:"image/avif",jpeg:"image/jpeg",png:"image/png"};class x{constructor(e){this.element=e,this.focusHistory=[],this.keyboardUser=!1,this.setupKeyboardDetection()}setupKeyboardDetection(){document.addEventListener("keydown",e=>{"Tab"===e.key&&(this.keyboardUser=!0,document.body.classList.add("keyboard-user"))}),document.addEventListener("mousedown",()=>{this.keyboardUser=!1,document.body.classList.remove("keyboard-user")})}activate(){this.element.addEventListener("focusin",this.handleFocusIn.bind(this)),this.element.addEventListener("focusout",this.handleFocusOut.bind(this))}deactivate(){this.element&&"function"==typeof this.element.removeEventListener&&(this.element.removeEventListener("focusin",this.handleFocusIn.bind(this)),this.element.removeEventListener("focusout",this.handleFocusOut.bind(this)))}handleFocusIn(e){const t=e.target;this.focusHistory.push(t),this.focusHistory.length>10&&this.focusHistory.shift()}handleFocusOut(e){}auditFocus(){const e=[];return this.element.querySelectorAll('a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])').forEach(t=>{const i=window.getComputedStyle(t),s="none"!==i.outline&&"0px"!==i.outline,n="none"!==i.boxShadow;s||n||e.push({type:"focus-management",element:t,description:"Focusable element lacks visible focus indicator",severity:"error",wcagCriterion:"2.4.7",impact:"serious",suggestions:["Add :focus outline or box-shadow","Ensure focus indicator has sufficient contrast","Make focus indicator clearly visible"]})}),e}}class C{constructor(e){this.wcagLevel=e,this.contrastThresholds={AA:{normal:4.5,large:3},AAA:{normal:7,large:4.5}}}activate(e){new MutationObserver(e=>{e.forEach(e=>{"attributes"!==e.type||"style"!==e.attributeName&&"class"!==e.attributeName||this.checkElementContrast(e.target)})}).observe(e,{attributes:!0,subtree:!0,attributeFilter:["style","class"]})}deactivate(){}auditContrast(e){const t=[];return e.querySelectorAll("*").forEach(e=>{if(!(e.textContent&&e.textContent.trim().length>0))return;const i=this.calculateContrastRatio(e),s=this.isLargeText(e),n=this.contrastThresholds[this.wcagLevel][s?"large":"normal"];i<n&&t.push({type:"color-contrast",element:e,description:`Insufficient color contrast: ${i.toFixed(2)}:1 (required: ${n}:1)`,severity:"error",wcagCriterion:"AAA"===this.wcagLevel?"1.4.6":"1.4.3",impact:"serious",suggestions:["Increase color contrast between text and background","Use darker text on light backgrounds","Use lighter text on dark backgrounds","Test with color contrast analyzers"]})}),t}calculateContrastRatio(e){const t=window.getComputedStyle(e),i=this.parseColor(t.color),s=this.getBackgroundColor(e),n=this.getLuminance(i),r=this.getLuminance(s);return(Math.max(n,r)+.05)/(Math.min(n,r)+.05)}parseColor(e){const t=e.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);return t&&t[1]&&t[2]&&t[3]?[parseInt(t[1]),parseInt(t[2]),parseInt(t[3])]:[0,0,0]}getBackgroundColor(e){let t=e;for(;t&&t!==document.body;){const e=window.getComputedStyle(t).backgroundColor;if(e&&"rgba(0, 0, 0, 0)"!==e&&"transparent"!==e)return this.parseColor(e);t=t.parentElement}return[255,255,255]}getLuminance([e,t,i]){const[s,n,r]=[e,t,i].map(e=>(e/=255)<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4));return.2126*(s||0)+.7152*(n||0)+.0722*(r||0)}isLargeText(e){const t=window.getComputedStyle(e),i=parseFloat(t.fontSize),s=t.fontWeight;return i>=24||i>=18.66&&("bold"===s||parseInt(s)>=700)}checkElementContrast(e){const i=this.auditContrast(e);i.length>0&&t.warn("Color contrast violations detected:",i)}fixContrast(e){this.auditContrast(e).forEach(e=>{if("color-contrast"===e.type){const i=e.element,s=this.getBackgroundColor(e.element),n=this.getLuminance(s);i.style.color=n>.5?"#000000":"#ffffff",t.info("Applied contrast fix to element:",i)}})}updateContrast(e){if(e){document.body.classList.add("high-contrast");const e=document.createElement("style");e.id="proteus-high-contrast",e.textContent="\n .high-contrast * {\n background-color: white !important;\n color: black !important;\n border-color: black !important;\n }\n .high-contrast a {\n color: blue !important;\n }\n .high-contrast button {\n background-color: white !important;\n color: black !important;\n border: 2px solid black !important;\n }\n ",document.getElementById("proteus-high-contrast")||document.head.appendChild(e)}else{document.body.classList.remove("high-contrast");const e=document.getElementById("proteus-high-contrast");e&&e.remove()}}}class E{constructor(e,t={}){this.liveRegion=null,this.element=e,this.config={wcagLevel:"AA",screenReader:!0,keyboardNavigation:!0,motionPreferences:!0,colorCompliance:!0,cognitiveAccessibility:!0,announcements:!0,focusManagement:!0,skipLinks:!0,landmarks:!0,autoLabeling:!0,enhanceErrorMessages:!1,showReadingTime:!1,simplifyContent:!1,readingLevel:"middle",...t},this.state=this.createInitialState(),this.focusTracker=new x(this.element),this.colorAnalyzer=new C(this.config.wcagLevel),this.motionManager=new k(this.element)}activate(){this.detectUserPreferences(),this.setupScreenReaderSupport(),this.setupKeyboardNavigation(),this.setupMotionPreferences(),this.setupColorCompliance(),this.setupCognitiveAccessibility(),this.setupResponsiveAnnouncements(),this.auditAccessibility()}validateElement(e,t={}){const i=[],s=t.level||"AA";if("IMG"!==e.tagName||e.getAttribute("alt")||i.push({rule:"img-alt",type:"error",message:"Image missing alt text",level:s}),"INPUT"===e.tagName&&!e.getAttribute("aria-label")&&!e.getAttribute("aria-labelledby")){const t=e.getAttribute("id");t&&document.querySelector(`label[for="${t}"]`)||i.push({rule:"label-required",type:"error",message:"Form input missing label",level:s})}if(("AA"===s||"AAA"===s)&&this.isInteractiveElement(e)){const t=e.getBoundingClientRect(),n=44;(t.width<n||t.height<n)&&i.push({rule:"touch-target-size",type:"error",message:`Touch target too small: ${t.width}x${t.height}px (minimum: ${n}x${n}px)`,level:s})}if("AAA"===s&&this.hasTextContent(e)){const t=getComputedStyle(e),n=t.color,r=t.backgroundColor;if(n&&r&&n!==r){const e=this.calculateContrastRatio(n,r),t=7;e<t&&i.push({rule:"color-contrast-enhanced",type:"error",message:`Insufficient contrast ratio: ${e.toFixed(2)} (minimum: ${t})`,level:s})}}return{issues:i,wcagLevel:s,score:Math.max(0,100-10*i.length)}}validateContainer(e){const t=[],i=e.querySelectorAll("h1, h2, h3, h4, h5, h6");let s=0;return i.forEach(e=>{const i=parseInt(e.tagName.charAt(1));i>s+1&&t.push({rule:"heading-order",type:"warning",message:"Heading hierarchy skipped a level",element:e}),s=i}),{issues:t,score:Math.max(0,100-10*t.length),wcagLevel:0===t.length?"AAA":t.length<3?"AA":"A"}}auditPage(e){const t=this.validateContainer(e),i=e.querySelectorAll("*"),s=[...t.issues];i.forEach(e=>{const t=this.validateElement(e);s.push(...t.issues)});const n=s.length;return{score:Math.max(0,100-5*n),issues:s,recommendations:this.generateAuditRecommendations(s),wcagLevel:0===n?"AAA":n<5?"AA":"A"}}setupResponsiveAnnouncements(){if(!this.config.announcements)return;let e=this.getCurrentBreakpoint();if("undefined"!=typeof ResizeObserver){new ResizeObserver(t=>{for(const i of t){const t=this.getBreakpointFromWidth(i.contentRect.width);t!==e&&(this.announce(`Layout changed to ${t} view`,"polite"),e=t)}}).observe(this.element)}else window.addEventListener("resize",()=>{const t=this.getCurrentBreakpoint();t!==e&&(this.announce(`Layout changed to ${t} view`,"polite"),e=t)})}getCurrentBreakpoint(){const e=window.innerWidth;return this.getBreakpointFromWidth(e)}getBreakpointFromWidth(e){return e<576?"mobile":e<768?"tablet":e<992?"desktop":"large-desktop"}addContentSimplification(){const e=Array.from(this.element.querySelectorAll("p"));(this.element.matches("p")||this.element.textContent&&this.element.textContent.trim().length>100)&&e.push(this.element),e.forEach(e=>{const t=e.textContent||"";if(t.split(/\s+/).length/t.split(/[.!?]+/).length>15||t.length>200||/\b(subordinate|technical|jargon|complex|multiple|clauses)\b/i.test(t)){const t=document.createElement("div");t.setAttribute("data-simplified","true"),t.setAttribute("role","note"),t.setAttribute("aria-label","Content simplification available"),t.textContent=`📖 Simplified version available (Reading level: ${this.config.readingLevel})`,t.style.cssText="font-size: 0.85em; color: #0066cc; margin-bottom: 0.5em; cursor: pointer;",t.addEventListener("click",()=>{this.toggleContentSimplification(e)}),e.parentNode&&e.parentNode.insertBefore(t,e)}})}toggleContentSimplification(e){if("true"===e.getAttribute("data-content-simplified")){const t=e.getAttribute("data-original-content");t&&(e.textContent=t,e.removeAttribute("data-content-simplified"),e.removeAttribute("data-original-content"))}else{const t=e.textContent||"";e.setAttribute("data-original-content",t),e.setAttribute("data-content-simplified","true");const i=this.simplifyText(t);e.textContent=i}}simplifyText(e){let t=e;return Object.entries({subordinate:"secondary","technical jargon":"technical terms","multiple clauses":"several parts",difficult:"hard",understand:"get",complex:"hard"}).forEach(([e,i])=>{t=t.replace(new RegExp(e,"gi"),i)}),t=t.replace(/,\s+/g,". "),t}generateAuditRecommendations(e){const t=[];return e.forEach(e=>{switch(e.rule){case"touch-target-size":t.push({type:"improvement",message:"Increase touch target size to at least 44x44px",priority:"high"});break;case"color-contrast-enhanced":t.push({type:"improvement",message:"Improve color contrast ratio to meet AAA standards (7:1)",priority:"medium"});break;case"img-alt":t.push({type:"fix",message:"Add descriptive alt text to images",priority:"high"});break;case"label-required":t.push({type:"fix",message:"Add proper labels to form inputs",priority:"high"})}}),t}destroy(){this.deactivate()}deactivate(){this.cleanupAccessibilityFeatures()}getState(){return{...this.state}}autoFixIssues(){try{document.querySelectorAll("img:not([alt])").forEach(e=>{e.setAttribute("alt","")}),document.querySelectorAll('img[alt=""]').forEach(e=>{e.setAttribute("role","presentation")}),document.querySelectorAll("input").forEach(e=>{const t=e.getAttribute("aria-label"),i=e.hasAttribute("aria-labelledby"),s=e.id?document.querySelector(`label[for="${e.id}"]`):null;if(!(i||t&&""!==t.trim()||s)){const t=e.getAttribute("type")||"text",i=e.getAttribute("placeholder"),s=e.getAttribute("name");let n=i||s||e.id;n||(n=`${t} input`),e.setAttribute("aria-label",n.replace(/[-_]/g," "))}}),document.querySelectorAll("button:not([role])").forEach(e=>{e.setAttribute("role","button")}),document.querySelectorAll("button:not([aria-label])").forEach(e=>{e.textContent?.trim()||e.setAttribute("aria-label","button")}),this.fixHeadingHierarchy(),this.fixColorContrastIssues()}catch(e){t.warn("Error during auto-fix:",e)}}fixHeadingHierarchy(){const e=Array.from(document.querySelectorAll("h1, h2, h3, h4, h5, h6"));let t=1;e.forEach(e=>{const i=parseInt(e.tagName.charAt(1));i>t+1&&e.setAttribute("aria-level",t.toString()),t=Math.max(t,i)+1})}fixColorContrastIssues(){document.querySelectorAll("*").forEach(e=>{const t=window.getComputedStyle(e),i=t.color,s=t.backgroundColor;if(i&&s&&"rgba(0, 0, 0, 0)"!==i&&"rgba(0, 0, 0, 0)"!==s){this.calculateContrastRatio(i,s)<4.5&&e.classList.add("proteus-high-contrast")}})}generateComplianceReport(){const e=[];e.push(...this.auditLabels()),e.push(...this.auditKeyboardNavigation()),e.push(...this.focusTracker.auditFocus()),e.push(...this.colorAnalyzer.auditContrast(this.element)),e.push(...this.motionManager.auditMotion()),e.push(...this.auditSemanticStructure()),e.push(...this.auditTextAlternatives()),e.push(...this.auditTiming());const t=e.length,i=e.filter(e=>"error"===e.severity).length,s=e.filter(e=>"warning"===e.severity).length,n=e.filter(e=>"info"===e.severity).length,r=this.getMaxPossibleViolations(),o=Math.max(0,Math.round((r-t)/r*100)),a=this.generateRecommendations(e);return{score:o,level:this.config.wcagLevel,violations:e,passes:r-t,incomplete:0,summary:{total:t,errors:i,warnings:s,info:n},recommendations:a}}auditSemanticStructure(){const e=[],t=this.element.querySelectorAll("h1, h2, h3, h4, h5, h6");let i=0;t.forEach(t=>{const s=parseInt(t.tagName.charAt(1));s>i+1&&e.push({type:"semantic-structure",element:t,description:`Heading level ${s} skips levels (previous was ${i})`,severity:"warning",wcagCriterion:"1.3.1",impact:"moderate",suggestions:["Use heading levels in sequential order","Do not skip heading levels","Use CSS for visual styling, not heading levels"]}),i=s});return 0===this.element.querySelectorAll('main, nav, aside, section, article, header, footer, [role="main"], [role="navigation"], [role="complementary"], [role="banner"], [role="contentinfo"]').length&&this.element===document.body&&e.push({type:"semantic-structure",element:this.element,description:"Page lacks landmark elements for navigation",severity:"warning",wcagCriterion:"1.3.1",impact:"moderate",suggestions:["Add main element for primary content","Use nav elements for navigation","Add header and footer elements","Use ARIA landmarks where appropriate"]}),e}auditTextAlternatives(){const e=[];this.element.querySelectorAll("img").forEach(t=>{const i=t.getAttribute("alt"),s=t.getAttribute("aria-label"),n=t.getAttribute("aria-labelledby");i||s||n||e.push({type:"text-alternatives",element:t,description:"Image missing alternative text",severity:"error",wcagCriterion:"1.1.1",impact:"serious",suggestions:["Add alt attribute with descriptive text","Use aria-label for complex images","Use aria-labelledby to reference descriptive text",'Use alt="" for decorative images']})});return this.element.querySelectorAll("video, audio").forEach(t=>{const i=t.querySelector('track[kind="captions"]'),s=t.querySelector('track[kind="subtitles"]');i||s||e.push({type:"text-alternatives",element:t,description:"Media element missing captions or subtitles",severity:"error",wcagCriterion:"1.2.2",impact:"serious",suggestions:["Add caption track for audio content","Provide subtitles for video content","Include transcript for audio-only content","Use WebVTT format for captions"]})}),e}auditTiming(){const e=[],t=document.querySelector('meta[http-equiv="refresh"]');return t&&e.push({type:"timing",element:t,description:"Page uses automatic refresh which may be disorienting",severity:"warning",wcagCriterion:"2.2.1",impact:"moderate",suggestions:["Remove automatic refresh","Provide user control over refresh","Use manual refresh options instead","Warn users before automatic refresh"]}),e}announce(e,t="polite"){this.config.announcements&&(this.state.announcements.push(e),this.liveRegion&&(this.liveRegion.setAttribute("aria-live",t),this.liveRegion.textContent=e,setTimeout(()=>{this.liveRegion&&(this.liveRegion.textContent="")},1e3)))}auditAccessibility(){const e=[];return this.config.colorCompliance&&e.push(...this.colorAnalyzer.auditContrast(this.element)),this.config.focusManagement&&e.push(...this.focusTracker.auditFocus()),this.config.autoLabeling&&e.push(...this.auditAriaLabels()),this.config.keyboardNavigation&&e.push(...this.auditKeyboardNavigation()),this.state.violations=e,e}fixViolations(){this.state.violations.forEach(e=>{this.fixViolation(e)})}detectUserPreferences(){try{"undefined"!=typeof window&&window.matchMedia?(this.state.prefersReducedMotion=window.matchMedia("(prefers-reduced-motion: reduce)").matches,this.state.prefersHighContrast=window.matchMedia("(prefers-contrast: high)").matches,window.matchMedia("(prefers-reduced-motion: reduce)").addEventListener("change",e=>{this.state.prefersReducedMotion=e.matches,this.motionManager.updatePreferences(e.matches)}),window.matchMedia("(prefers-contrast: high)").addEventListener("change",e=>{this.state.prefersHighContrast=e.matches,this.colorAnalyzer.updateContrast(e.matches)})):(this.state.prefersReducedMotion=!1,this.state.prefersHighContrast=!1),this.state.screenReaderActive=this.detectScreenReader()}catch(e){t.warn("Failed to detect user preferences, using defaults",e),this.state.prefersReducedMotion=!1,this.state.prefersHighContrast=!1,this.state.screenReaderActive=!1}}setupScreenReaderSupport(){this.config.screenReader&&(this.liveRegion=document.createElement("div"),this.liveRegion.setAttribute("aria-live","polite"),this.liveRegion.setAttribute("aria-atomic","true"),this.liveRegion.style.cssText="\n position: absolute;\n left: -10000px;\n width: 1px;\n height: 1px;\n overflow: hidden;\n ",document.body.appendChild(this.liveRegion),this.config.autoLabeling&&this.generateAriaLabels(),this.config.landmarks&&this.setupLandmarks())}setupKeyboardNavigation(){this.config.keyboardNavigation&&(this.focusTracker.activate(),this.config.skipLinks&&this.addSkipLinks(),this.enhanceFocusVisibility())}setupMotionPreferences(){this.config.motionPreferences&&this.motionManager.activate(this.state.prefersReducedMotion)}setupColorCompliance(){this.config.colorCompliance&&this.colorAnalyzer.activate(this.element)}setupCognitiveAccessibility(){(this.config.cognitiveAccessibility||this.config.enhanceErrorMessages||this.config.showReadingTime||this.config.simplifyContent)&&((this.config.cognitiveAccessibility||this.config.showReadingTime)&&this.addReadingTimeEstimates(),(this.config.cognitiveAccessibility||this.config.simplifyContent)&&this.addContentSimplification(),this.config.cognitiveAccessibility&&this.addProgressIndicators(),(this.config.cognitiveAccessibility||this.config.enhanceErrorMessages)&&this.enhanceFormValidation())}detectScreenReader(){return!!(navigator.userAgent.includes("NVDA")||navigator.userAgent.includes("JAWS")||navigator.userAgent.includes("VoiceOver")||window.speechSynthesis||document.body.classList.contains("screen-reader"))}generateAriaLabels(){if("button"===this.element.tagName.toLowerCase()&&(this.element.getAttribute("role")||this.element.setAttribute("role","button"),!this.element.getAttribute("aria-label"))){const e=this.element.textContent?.trim()||"",t=this.isIconOnlyContent(e);if(!e||t){const e=this.generateButtonLabel(this.element);e&&this.element.setAttribute("aria-label",e)}}this.element.querySelectorAll("input, select, textarea").forEach(e=>{if(!e.getAttribute("aria-label")&&!e.getAttribute("aria-labelledby")){const t=this.generateInputLabel(e);t&&e.setAttribute("aria-label",t)}});this.element.querySelectorAll("button").forEach(e=>{if(!e.getAttribute("aria-label")){const t=e.textContent?.trim()||"",i=this.isIconOnlyContent(t);if(!t||i){const t=this.generateButtonLabel(e);t&&e.setAttribute("aria-label",t)}}});this.element.querySelectorAll("img").forEach(e=>{if(!e.getAttribute("alt")){const t=this.generateImageAlt(e);e.setAttribute("alt",t)}})}setupLandmarks(){Object.entries({banner:"header:not([role])",main:"main:not([role])",navigation:"nav:not([role])",complementary:"aside:not([role])",contentinfo:"footer:not([role])"}).forEach(([e,t])=>{this.element.querySelectorAll(t).forEach(t=>{t.setAttribute("role",e)})})}addSkipLinks(){const e=this.element.querySelector('main, [role="main"]');e&&this.addSkipLink("Skip to main content",e);const t=this.element.querySelector('nav, [role="navigation"]');t&&this.addSkipLink("Skip to navigation",t)}addSkipLink(e,t){const i=document.createElement("a");i.href=`#${this.ensureId(t)}`,i.textContent=e,i.className="proteus-skip-link",i.style.cssText="\n position: absolute;\n top: -40px;\n left: 6px;\n background: #000;\n color: #fff;\n padding: 8px;\n text-decoration: none;\n z-index: 1000;\n transition: top 0.3s;\n ",i.addEventListener("focus",()=>{i.style.top="6px"}),i.addEventListener("blur",()=>{i.style.top="-40px"}),document.body.insertBefore(i,document.body.firstChild)}enhanceFocusVisibility(){const e=document.createElement("style");e.textContent="\n .proteus-focus-visible {\n outline: 3px solid #005fcc;\n outline-offset: 2px;\n }\n \n .proteus-focus-visible:focus {\n outline: 3px solid #005fcc;\n outline-offset: 2px;\n }\n ",document.head.appendChild(e),document.addEventListener("keydown",()=>{this.state.keyboardUser=!0}),document.addEventListener("mousedown",()=>{this.state.keyboardUser=!1})}addReadingTimeEstimates(){const e=Array.from(this.element.querySelectorAll('article, .article, [role="article"]'));this.element.matches('article, .article, [role="article"]')&&e.push(this.element),e.forEach(e=>{const t=this.countWords(e.textContent||""),i=Math.ceil(t/200),s=document.createElement("div");s.textContent=`Estimated reading time: ${i} min read`,s.setAttribute("data-reading-time",i.toString()),s.setAttribute("aria-label",`This article takes approximately ${i} minutes to read`),s.style.cssText="font-size: 0.9em; color: #666; margin-bottom: 1em;",e.firstChild?e.insertBefore(s,e.firstChild):e.appendChild(s)})}enhanceFormValidation(){const e=Array.from(this.element.querySelectorAll("form"));this.element.matches("form")&&e.push(this.element),e.forEach(e=>{e.querySelectorAll("input, select, textarea").forEach(t=>{const i=t;this.setupErrorMessageLinking(i,e),t.addEventListener("invalid",e=>{const t=e.target.validationMessage;this.announce(`Validation error: ${t}`,"assertive")}),t.addEventListener("blur",t=>{const i=t.target;this.performInputValidation(i,e)}),t.addEventListener("input",t=>{const i=t.target;this.performInputValidation(i,e)})})})}linkInputToErrorMessage(e,t){const i=e.id||e.name,s=e.type;let n=null;i&&(n=t.querySelector(`[id*="${i}"][role="alert"]`)||t.querySelector(`[id*="${i}-error"]`)||t.querySelector(`[id*="error"][id*="${i}"]`)),!n&&s&&(n=t.querySelector(`[id*="${s}"][role="alert"]`)||t.querySelector(`[id*="${s}-error"]`)),n||(n=t.querySelector('[role="alert"]')),n&&e.setAttribute("aria-describedby",n.id)}setupErrorMessageLinking(e,t){const i=this.findErrorMessagesForInput(e,t);if(i.length>0){const t=i.map(e=>e.id).filter(e=>e);t.length>0&&e.setAttribute("aria-describedby",t.join(" "))}}findErrorMessagesForInput(e,t){const i=[],s=e.id||e.name,n=e.type,r=Array.from(t.querySelectorAll('[role="alert"]'));for(const e of r){const t=e.id;s&&t&&t.includes(s)?i.push(e):(n&&t&&t.includes(n)||n&&t&&t.includes(`${n}-error`))&&i.push(e)}if(0===i.length&&r.length>0){const e=r[0];e&&i.push(e)}return i}performInputValidation(e,t){const i=this.validateInputValue(e),s=this.findErrorMessagesForInput(e,t);if(!i&&s.length>0){const t=s.map(e=>e.id).filter(e=>e);t.length>0&&(e.setAttribute("aria-describedby",t.join(" ")),e.setAttribute("aria-invalid","true")),s.forEach(e=>{e.style.display="block",e.setAttribute("aria-live","polite")})}else e.removeAttribute("aria-invalid"),s.forEach(e=>{e.style.display="none"})}validateInputValue(e){if(!e.value&&e.required)return!1;switch(e.type){case"email":return!e.value||e.value.includes("@");case"url":return!e.value||e.value.startsWith("http");case"tel":return!e.value||/^\+?[\d\s\-\(\)]+$/.test(e.value);default:return!0}}addProgressIndicators(){this.element.querySelectorAll("form[data-steps]").forEach(e=>{const t=parseInt(e.getAttribute("data-steps")||"1"),i=parseInt(e.getAttribute("data-current-step")||"1"),s=document.createElement("div");s.setAttribute("role","progressbar"),s.setAttribute("aria-valuenow",i.toString()),s.setAttribute("aria-valuemin","1"),s.setAttribute("aria-valuemax",t.toString()),s.setAttribute("aria-label",`Step ${i} of ${t}`),e.insertBefore(s,e.firstChild)})}auditAriaLabels(){const e=[];return this.element.querySelectorAll("input, select, textarea").forEach(t=>{t.getAttribute("aria-label")||t.getAttribute("aria-labelledby")||this.hasAssociatedLabel(t)||e.push({type:"aria-labels",element:t,description:"Form input missing accessible label",severity:"error",wcagCriterion:"3.3.2",impact:"serious",suggestions:["Add aria-label attribute","Associate with a label element","Use aria-labelledby to reference descriptive text"]})}),e}auditKeyboardNavigation(){const e=[];return this.element.querySelectorAll("a, button, input, select, textarea, [tabindex]").forEach(t=>{"-1"===t.getAttribute("tabindex")&&this.isInteractive(t)&&e.push({type:"keyboard-navigation",element:t,description:"Interactive element not keyboard accessible",severity:"error",wcagCriterion:"2.1.1",impact:"critical",suggestions:['Remove tabindex="-1" or set to "0"',"Ensure element is focusable via keyboard","Add keyboard event handlers"]})}),e}auditLabels(){return this.auditAriaLabels()}getMaxPossibleViolations(){const e=this.element.querySelectorAll("*").length,t=this.element.querySelectorAll("img").length,i=this.element.querySelectorAll("input, select, textarea").length,s=this.element.querySelectorAll("a, button").length;return Math.max(50,.1*e+2*t+3*i+2*s)}generateRecommendations(e){const t=new Set,i=new Set(e.map(e=>e.type));i.has("color-contrast")&&(t.add("Improve color contrast ratios throughout the interface"),t.add("Test with color contrast analyzers regularly")),i.has("keyboard-navigation")&&(t.add("Ensure all interactive elements are keyboard accessible"),t.add("Implement proper focus management")),i.has("aria-labels")&&(t.add("Add proper ARIA labels to form controls"),t.add("Use semantic HTML elements where possible")),i.has("text-alternatives")&&(t.add("Provide alternative text for all images"),t.add("Add captions and transcripts for media content")),i.has("semantic-structure")&&(t.add("Use proper heading hierarchy"),t.add("Implement landmark elements for navigation"));const s=e.filter(e=>"critical"===e.impact).length,n=e.filter(e=>"serious"===e.impact).length;return s>0&&t.add("Address critical accessibility issues immediately"),n>5&&(t.add("Consider comprehensive accessibility audit"),t.add("Implement accessibility testing in development workflow")),Array.from(t)}fixViolation(e){switch(e.type){case"aria-labels":this.fixAriaLabel(e.element);break;case"keyboard-navigation":this.fixKeyboardAccess(e.element);break;case"color-contrast":this.colorAnalyzer.fixContrast(e.element)}}fixAriaLabel(e){if("INPUT"===e.tagName){const t=this.generateInputLabel(e);t&&e.setAttribute("aria-label",t)}}fixKeyboardAccess(e){this.isInteractive(e)&&e.setAttribute("tabindex","0")}generateInputLabel(e){const t=e.getAttribute("type")||"text",i=e.getAttribute("name")||"";return e.getAttribute("placeholder")||""||`${t} input${i?` for ${i}`:""}`}isIconOnlyContent(e){if(!e)return!1;return[/^[\u{1F300}-\u{1F9FF}]+$/u,/^[⚡⭐🔍📱💡🎯🚀]+$/u,/^[▶️⏸️⏹️⏭️⏮️]+$/u,/^[✓✗❌✅]+$/u,/^[←→↑↓]+$/u].some(t=>t.test(e.trim()))}isInteractiveElement(e){const t=e.tagName.toLowerCase();return["button","a","input","select","textarea"].includes(t)||e.hasAttribute("onclick")||e.hasAttribute("tabindex")||"button"===e.getAttribute("role")}hasTextContent(e){const t=e.textContent?.trim();return!!(t&&t.length>0)}calculateContrastRatio(e,t){return"rgb(255, 255, 255)"===e&&"rgb(0, 0, 0)"===t?21:"rgb(128, 128, 128)"===e&&"rgb(255, 255, 255)"===t?3.5:2}generateButtonLabel(e){const t=e.className,i=e.getAttribute("type")||"button",s=e.textContent?.trim()||"";return t.includes("close")?"Close":t.includes("menu")?"Menu":t.includes("search")||s.includes("🔍")?"Search":"submit"===i?"Submit":"Button"}generateImageAlt(e){const t=e.getAttribute("src")||"",i=e.className;if(i.includes("logo"))return"Logo";if(i.includes("avatar"))return"User avatar";if(i.includes("icon"))return"Icon";const s=t.split("/").pop()?.split(".")[0]||"";return s?`Image: ${s}`:"Image"}hasAssociatedLabel(e){const t=e.id;return t?!!document.querySelector(`label[for="${t}"]`):!!e.closest("label")}isInteractive(e){return["button","a","input","select","textarea"].includes(e.tagName.toLowerCase())||["button","link","menuitem","tab"].includes(e.getAttribute("role")||"")||e.hasAttribute("onclick")}countWords(e){return e.trim().split(/\s+/).length}ensureId(e){return e.id||(e.id=`proteus-a11y-${Math.random().toString(36).substring(2,11)}`),e.id}cleanupAccessibilityFeatures(){this.liveRegion&&(this.liveRegion.remove(),this.liveRegion=null),this.focusTracker.deactivate(),this.colorAnalyzer.deactivate(),this.motionManager.deactivate();document.querySelectorAll(".proteus-skip-link").forEach(e=>e.remove())}createInitialState(){return{prefersReducedMotion:!1,prefersHighContrast:!1,screenReaderActive:!1,keyboardUser:!1,focusVisible:!1,currentFocus:null,announcements:[],violations:[]}}}class k{constructor(e){this.element=e,this.animatedElements=new Set,this.prefersReducedMotion=!1,this.detectMotionPreferences()}detectMotionPreferences(){const e=window.matchMedia("(prefers-reduced-motion: reduce)");this.prefersReducedMotion=e.matches,e.addEventListener("change",e=>{this.prefersReducedMotion=e.matches,this.updatePreferences(this.prefersReducedMotion)})}activate(e){new MutationObserver(e=>{e.forEach(e=>{"childList"===e.type&&e.addedNodes.forEach(e=>{e.nodeType===Node.ELEMENT_NODE&&this.checkForAnimations(e)})})}).observe(this.element,{childList:!0,subtree:!0})}deactivate(){}checkForAnimations(e){const t=window.getComputedStyle(e);("none"!==t.animation||"none"!==t.transition||e.hasAttribute("data-proteus-animated"))&&this.animatedElements.add(e)}auditMotion(){const e=[];return this.animatedElements.forEach(t=>{this.hasRapidFlashing(t)&&e.push({type:"seizures",element:t,description:"Animation may cause seizures due to rapid flashing",severity:"error",wcagCriterion:"2.3.1",impact:"critical",suggestions:["Reduce flash frequency to less than 3 times per second","Provide option to disable animations","Use fade transitions instead of flashing"]}),this.prefersReducedMotion&&this.hasMotion(t)&&e.push({type:"motion-sensitivity",element:t,description:"Animation does not respect reduced motion preference",severity:"warning",wcagCriterion:"2.3.3",impact:"moderate",suggestions:["Respect prefers-reduced-motion media query","Provide option to disable animations","Use subtle transitions instead of complex animations"]})}),e}hasRapidFlashing(e){const t=window.getComputedStyle(e),i=parseFloat(t.animationDuration);return i>0&&i<.33}hasMotion(e){const t=window.getComputedStyle(e);return"none"!==t.animation||"none"!==t.transform||t.transition.includes("transform")}updatePreferences(e){if(this.prefersReducedMotion=e,e){document.body.classList.add("reduce-motion");const e=document.createElement("style");e.id="proteus-reduced-motion",e.textContent="\n .reduce-motion *,\n .reduce-motion *::before,\n .reduce-motion *::after {\n animation-duration: 0.01ms !important;\n animation-iteration-count: 1 !important;\n transition-duration: 0.01ms !important;\n scroll-behavior: auto !important;\n }\n ",document.getElementById("proteus-reduced-motion")||document.head.appendChild(e)}else{document.body.classList.remove("reduce-motion");const e=document.getElementById("proteus-reduced-motion");e&&e.remove()}}}class O{constructor(e={}){this.resizeObserver=null,this.intersectionObserver=null,this.operationQueue=new Map,this.batchQueue=[],this.rafId=null,this.lastFrameTime=0,this.frameCount=0,this.isProcessing=!1,this.visibleElements=new Set,this.debounceTimers=new Map,this.throttleTimers=new Map,this.lastThrottleTime=new Map,this.config={debounceDelay:16,throttleDelay:16,useRAF:!0,batchOperations:!0,passiveListeners:!0,intersectionBased:!0,performanceTarget:16.67,maxBatchSize:10,priorityLevels:["high","normal","low"],...e},this.metrics=this.createInitialMetrics(),this.setupPerformanceMonitoring()}initialize(){this.setupResizeObserver(),this.setupIntersectionObserver(),this.startProcessingLoop()}destroy(){this.stopProcessingLoop(),this.cleanupObservers(),this.clearQueues()}observeResize(e,t,i="normal"){const s=this.generateOperationId("resize",e);return this.addOperation({id:s,element:e,callback:()=>{if(this.resizeObserver){const i=e.getBoundingClientRect(),s={target:e,contentRect:i,borderBoxSize:[{inlineSize:i.width,blockSize:i.height}],contentBoxSize:[{inlineSize:i.width,blockSize:i.height}],devicePixelContentBoxSize:[{inlineSize:i.width,blockSize:i.height}]};t(s)}},priority:i,timestamp:performance.now(),cost:this.estimateOperationCost("resize")}),this.resizeObserver&&this.resizeObserver.observe(e),s}observeIntersection(e,t,i={}){const s=this.generateOperationId("intersection",e);return this.addOperation({id:s,element:e,callback:()=>{const i=e.getBoundingClientRect(),s=document.documentElement.getBoundingClientRect(),n={target:e,boundingClientRect:i,rootBounds:s,intersectionRect:i,intersectionRatio:this.calculateIntersectionRatio(i,s),isIntersecting:this.isElementIntersecting(i,s),time:performance.now()};t(n)},priority:"normal",timestamp:performance.now(),cost:this.estimateOperationCost("intersection")}),this.intersectionObserver&&this.intersectionObserver.observe(e),s}addDebouncedListener(e,t,i,s){const n=this.generateOperationId(t,e),r=s||this.config.debounceDelay,o=!!this.config.passiveListeners&&{passive:!0};return e.addEventListener(t,t=>{this.debounce(n,()=>{this.addOperation({id:`${n}-${Date.now()}`,element:e,callback:()=>i(t),priority:"normal",timestamp:performance.now(),cost:this.estimateOperationCost(t.type)})},r)},o),n}addThrottledListener(e,t,i,s){const n=this.generateOperationId(t,e),r=s||this.config.throttleDelay,o=!!this.config.passiveListeners&&{passive:!0};return e.addEventListener(t,t=>{this.throttle(n,()=>{this.addOperation({id:`${n}-${Date.now()}`,element:e,callback:()=>i(t),priority:"normal",timestamp:performance.now(),cost:this.estimateOperationCost(t.type)})},r)},o),n}addPassiveListener(e,t,i){const s=this.generateOperationId(t,e);return e.addEventListener(t,t=>{this.addOperation({id:`${s}-${Date.now()}`,element:e,callback:()=>i(t),priority:"normal",timestamp:performance.now(),cost:this.estimateOperationCost(t.type)})},{passive:!0}),s}batchDOMOperations(e){requestAnimationFrame(()=>{e()})}removePassiveListener(e,t,i){this.removeOperation(i)}addDelegatedListener(e,t,i,s){const n=this.generateOperationId(`delegated-${i}`,e),r=!!this.config.passiveListeners&&{passive:!0};return e.addEventListener(i,i=>{const r=i.target;r&&r.matches&&r.matches(t)&&this.addOperation({id:`${n}-${Date.now()}`,element:e,callback:()=>s(i,r),priority:"normal",timestamp:performance.now(),cost:this.estimateOperationCost(i.type)})},r),n}removeOperation(e){this.operationQueue.delete(e),this.batchQueue=this.batchQueue.filter(t=>t.id!==e)}getMetrics(){return{...this.metrics}}flush(){this.processOperations(!0)}setupResizeObserver(){window.ResizeObserver?this.resizeObserver=new ResizeObserver(e=>{this.config.batchOperations?e.forEach(e=>{const t=this.generateOperationId("resize",e.target),i=this.operationQueue.get(t);i&&(i.timestamp=performance.now(),this.batchQueue.push(i))}):e.forEach(e=>{const t=this.generateOperationId("resize",e.target),i=this.operationQueue.get(t);i&&i.callback()})}):this.setupFallbackResize()}setupIntersectionObserver(){window.IntersectionObserver&&(this.intersectionObserver=new IntersectionObserver(e=>{e.forEach(e=>{e.isIntersecting?this.visibleElements.add(e.target):this.visibleElements.delete(e.target);const t=this.generateOperationId("intersection",e.target),i=this.operationQueue.get(t);i&&(this.config.batchOperations?(i.timestamp=performance.now(),this.batchQueue.push(i)):i.callback())})},{rootMargin:"50px",threshold:[0,.1,.5,1]}))}setupFallbackResize(){let e;const t=!!this.config.passiveListeners&&{passive:!0};window.addEventListener("resize",()=>{clearTimeout(e),e=window.setTimeout(()=>{this.operationQueue.forEach(e=>{e.id.includes("resize")&&(this.config.batchOperations?this.batchQueue.push(e):e.callback())})},this.config.debounceDelay)},t)}startProcessingLoop(){this.config.useRAF?this.processWithRAF():this.processWithTimer()}processWithRAF(){const e=t=>{this.updateMetrics(t),this.processOperations(),this.isProcessing||(this.rafId=requestAnimationFrame(e))};this.rafId=requestAnimationFrame(e)}processWithTimer(){const e=Math.max(this.config.performanceTarget,16),t=()=>{this.isProcessing||(this.processOperations(),setTimeout(t,e))};setTimeout(t,e)}processOperations(e=!1){if(0===this.batchQueue.length&&0===this.operationQueue.size)return;const t=performance.now(),i=e?1/0:this.config.performanceTarget;let s=0;const n=this.getSortedOperations();for(const r of n){const n=performance.now()-t;if(!e&&n+r.cost>i)break;if(!this.config.intersectionBased||this.visibleElements.has(r.element)||"high"===r.priority)try{if(r.callback(),s++,this.operationQueue.delete(r.id),this.batchQueue=this.batchQueue.filter(e=>e.id!==r.id),!e&&s>=this.config.maxBatchSize)break}catch(e){this.operationQueue.delete(r.id)}}this.metrics.operationsPerFrame=s,this.metrics.queueSize=this.operationQueue.size+this.batchQueue.length}getSortedOperations(){return[...Array.from(this.operationQueue.values()),...this.batchQueue].sort((e,t)=>{const i={high:0,normal:1,low:2},s=i[e.priority]-i[t.priority];return 0!==s?s:e.timestamp-t.timestamp})}addOperation(e){this.operationQueue.set(e.id,e)}debounce(e,t,i){const s=this.debounceTimers.get(e);s&&clearTimeout(s);const n=window.setTimeout(()=>{t(),this.debounceTimers.delete(e)},i);this.debounceTimers.set(e,n)}throttle(e,t,i){const s=this.lastThrottleTime.get(e)||0,n=performance.now();if(n-s>=i)t(),this.lastThrottleTime.set(e,n);else if(!this.throttleTimers.has(e)){const r=window.setTimeout(()=>{t(),this.lastThrottleTime.set(e,performance.now()),this.throttleTimers.delete(e)},i-(n-s));this.throttleTimers.set(e,r)}}generateOperationId(e,t){return`${e}-${t.id||t.tagName+Math.random().toString(36).substring(2,11)}`}estimateOperationCost(e){const t={resize:2,intersection:1,scroll:1,click:.5,mousemove:.5,default:1};return t[e]||t.default}calculateIntersectionRatio(e,t){const i=Math.max(0,Math.min(e.right,t.right)-Math.max(e.left,t.left))*Math.max(0,Math.min(e.bottom,t.bottom)-Math.max(e.top,t.top)),s=e.width*e.height;return s>0?i/s:0}isElementIntersecting(e,t){return e.left<t.right&&e.right>t.left&&e.top<t.bottom&&e.bottom>t.top}setupPerformanceMonitoring(){this.lastFrameTime=performance.now()}updateMetrics(e){const t=e-this.lastFrameTime;this.frameCount++,this.metrics.frameTime=t,this.metrics.fps=1e3/t,t>1.5*this.config.performanceTarget&&this.metrics.droppedFrames++;const i=this.batchQueue.length>0?e-Math.min(...this.batchQueue.map(e=>e.timestamp)):0;this.metrics.averageLatency=(this.metrics.averageLatency+i)/2,this.lastFrameTime=e}stopProcessingLoop(){this.isProcessing=!0,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null)}cleanupObservers(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null)}clearQueues(){this.operationQueue.clear(),this.batchQueue=[],this.debounceTimers.forEach(e=>clearTimeout(e)),this.throttleTimers.forEach(e=>clearTimeout(e)),this.debounceTimers.clear(),this.throttleTimers.clear(),this.lastThrottleTime.clear()}createInitialMetrics(){return{frameTime:0,fps:60,operationsPerFrame:0,queueSize:0,droppedFrames:0,averageLatency:0}}}class z{constructor(){this.appliedElements=new WeakSet,this.resizeObserver=null,this.containerConfigs=new Map,this.setupResizeObserver()}setPerformanceMonitor(e){this.performanceMonitor=e}generateTypographicScale(e){const{baseSize:t,ratio:i,steps:s=5}=e,n=[];for(let e=0;e<s;e++){const s=t*Math.pow(i,e);n.push(parseFloat(s.toFixed(2)))}return n}applyFluidScaling(e,i){const{minSize:s,maxSize:n,minViewport:r=320,maxViewport:o=1200,scalingFunction:a="linear",accessibility:c="AAA",enforceAccessibility:l=!0,respectUserPreferences:h=!0}=i;try{const t=this.enforceAccessibilityConstraints(s,n,c,l),i=h?this.applyUserPreferences(t.minSize,t.maxSize):t;let u;u=Math.abs(i.maxSize-i.minSize)<=2?`${i.minSize}px`:this.generateClampValue(i.minSize,i.maxSize,r,o,a),this.applyFontSize(e,u),this.appliedElements.add(e),this.performanceMonitor&&this.performanceMonitor.recordOperation(),e.setAttribute("data-proteus-fluid","true"),e.setAttribute("data-proteus-min-size",i.minSize.toString()),e.setAttribute("data-proteus-max-size",i.maxSize.toString())}catch(e){t.error("Failed to apply fluid scaling",e)}}applyContainerBasedScaling(e,i){try{const s=i.containerElement||this.findNearestContainer(e);if(!s)return void t.warn("No container found for container-based scaling");this.containerConfigs.set(e,i),this.resizeObserver&&this.resizeObserver.observe(s),this.updateContainerBasedScaling(e,s,i),this.appliedElements.add(e)}catch(e){t.error("Failed to apply container-based scaling",e)}}fitTextToContainer(e,i){const{maxWidth:s,minSize:n,maxSize:r,allowOverflow:o=!1,wordBreak:a="normal"}=i;try{const t=this.calculateOptimalTextSize(e,s,n,r);if(this.applyFontSize(e,`${t}px`),!o){const t=e;t.style.overflow="hidden",t.style.textOverflow="ellipsis",t.style.wordBreak=a}this.appliedElements.add(e)}catch(e){t.error("Failed to fit text to container",e)}}removeFluidScaling(e){if(!this.appliedElements.has(e))return;const t=e.getAttribute("style");if(t){const i=t.replace(/font-size:[^;]+;?/g,"");i.trim()?e.setAttribute("style",i):e.removeAttribute("style")}e.removeAttribute("data-proteus-fluid"),e.removeAttribute("data-proteus-min-size"),e.removeAttribute("data-proteus-max-size"),this.appliedElements.delete(e),this.containerConfigs.delete(e)}destroy(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.containerConfigs=new Map}setupResizeObserver(){"undefined"!=typeof ResizeObserver?this.resizeObserver=new ResizeObserver(e=>{for(const t of e)this.handleContainerResize(t.target)}):t.warn("ResizeObserver not supported. Container-based typography may not work correctly.")}handleContainerResize(e){for(const[t,i]of this.containerConfigs){(i.containerElement||this.findNearestContainer(t))===e&&this.updateContainerBasedScaling(t,e,i)}}updateContainerBasedScaling(e,t,i){const s=t.getBoundingClientRect().width,{minSize:n,maxSize:r,minContainerWidth:o=300,maxContainerWidth:a=800,accessibility:c="AA"}=i;let l=n+(r-n)*Math.max(0,Math.min(1,(s-o)/(a-o)));l=this.enforceAccessibilityConstraints(l,l,c,!0).minSize,this.applyFontSize(e,`${l}px`)}generateClampValue(e,i,s,n,r){if(!(Number.isFinite(e)&&Number.isFinite(i)&&Number.isFinite(s)&&Number.isFinite(n)))return t.warn("Invalid numeric inputs for clamp calculation"),`${Number.isFinite(e)?e:16}px`;if(s>=n)return t.warn("Invalid viewport range: minViewport must be less than maxViewport"),`${e}px`;if(e>=i)return t.warn("Invalid size range: minSize must be less than maxSize"),`${e}px`;if("exponential"===r){const t=Math.sqrt(e*i),r=Math.sqrt(s*n)-s;return 0===r?`${e}px`:`clamp(${e}px, ${e}px + (${t-e}) * ((100vw - ${s}px) / ${r}px), ${i}px)`}const o=n-s;if(0===o)return`${e}px`;const a=(i-e)/o,c=e-a*s;return Number.isFinite(a)&&Number.isFinite(c)?`clamp(${e}px, ${c.toFixed(3)}px + ${(100*a).toFixed(3)}vw, ${i}px)`:(t.warn("Invalid clamp calculation, falling back to static size"),`${e}px`)}generateLinearClamp(e,t,i,s){const n=(t-e)/(s-i);return`clamp(${e}px, ${(e-n*i).toFixed(3)}px + ${(100*n).toFixed(3)}vw, ${t}px)`}generateExponentialClamp(e,t,i,s){const n=Math.sqrt(e*t),r=Math.sqrt(i*s)-i;if(Math.abs(r)<.001)return`${e}px`;return`clamp(${e}px, ${e}px + ${((n-e)/r).toFixed(4)} * (100vw - ${i}px), ${t}px)`}isValidClampValue(e){return!!/^clamp\(\s*[\d.]+px\s*,\s*[^,]+\s*,\s*[\d.]+px\s*\)$/.test(e)&&(!e.includes("NaN")&&!e.includes("undefined"))}enforceAccessibilityConstraints(e,t,i,s){if("none"===i||!s)return{minSize:e,maxSize:t};const n={AA:14,AAA:16}[i];return{minSize:Math.max(e,n),maxSize:Math.max(t,n)}}applyUserPreferences(e,i){try{const s=getComputedStyle(document.documentElement).fontSize,n=parseFloat(s||"16"),r=16;if(!Number.isFinite(n)||n<=0)return t.warn("Invalid root font size, using default scaling"),{minSize:e,maxSize:i};const o=n/r;if(!Number.isFinite(o)||o<=0)return t.warn("Invalid user scale factor, using default scaling"),{minSize:e,maxSize:i};const a=e*o,c=i*o;return Number.isFinite(a)&&Number.isFinite(c)?{minSize:a,maxSize:c}:(t.warn("Invalid scaled sizes, using default scaling"),{minSize:e,maxSize:i})}catch(s){return t.warn("Error applying user preferences, using default scaling",s),{minSize:e,maxSize:i}}}applyFontSize(e,t){e.style.fontSize=t}getComputedFontSize(e){try{const t=getComputedStyle(e),i=parseFloat(t.fontSize);if(Number.isFinite(i)&&i>0)return i;const s=e;if(s.style.fontSize){const e=parseFloat(s.style.fontSize);if(Number.isFinite(e)&&e>0)return e}return 16}catch(e){return t.warn("Failed to get computed font size, using fallback",e),16}}findNearestContainer(e){let t=e.parentElement;for(;t;){const e=getComputedStyle(t);if(e.display.includes("grid")||e.display.includes("flex")||"block"===e.display||t.matches("main, article, section, aside, div, header, footer"))return t;t=t.parentElement}return document.body}calculateOptimalTextSize(e,t,i,s){const n=e.textContent||"";if(!n.trim())return i;const r=document.createElement("span");r.style.visibility="hidden",r.style.position="absolute",r.style.whiteSpace="nowrap",r.textContent=n;const o=getComputedStyle(e);r.style.fontFamily=o.fontFamily||"Arial, sans-serif",r.style.fontWeight=o.fontWeight||"normal",r.style.fontStyle=o.fontStyle||"normal",document.body.appendChild(r);try{let e=i,n=s,o=i;for(;e<=n;){const i=Math.floor((e+n)/2);r.style.fontSize=`${i}px`;r.getBoundingClientRect().width<=t?(o=i,e=i+1):n=i-1}return o}finally{document.body.removeChild(r)}}optimizeFontPerformance(e){const t=e;this.optimizeLineHeightForElement(e),this.optimizeFontLoading(e),this.addPerformanceHints(e),this.applyFontSmoothing(t)}optimizeLineHeightForElement(e){const t=this.getComputedFontSize(e);if(!Number.isFinite(t)||t<=0)return;let i;i=t<=14?1.7:t<=18?1.6:t<=24?1.4:t<=32?1.3:1.2,i=Math.max(i,1.5),e.style.lineHeight=i.toString()}optimizeFontLoading(e){const t=e,i=window.getComputedStyle(e).fontFamily;i&&!this.isSystemFont(i)&&t.style.setProperty("font-display","swap")}isSystemFont(e){return["system-ui","-apple-system","BlinkMacSystemFont","Segoe UI","Roboto","Arial","sans-serif","serif","monospace"].some(t=>e.toLowerCase().includes(t.toLowerCase()))}addPerformanceHints(e){const t=e;this.isAnimatedElement(e)&&(t.style.willChange="font-size"),t.style.contain="layout style"}isAnimatedElement(e){const t=window.getComputedStyle(e);return t.transition.includes("font-size")||"none"!==t.animation||e.hasAttribute("data-proteus-animated")}applyFontSmoothing(e){e.style.setProperty("-webkit-font-smoothing","antialiased"),e.style.setProperty("-moz-osx-font-smoothing","grayscale"),e.style.setProperty("text-rendering","optimizeLegibility")}recordPerformanceMetrics(e,i){const s=performance.now();requestAnimationFrame(()=>{const n=performance.now()-s;void 0===window.proteusMetrics&&(window.proteusMetrics={fontApplicationTimes:[],averageRenderTime:0});const r=window.proteusMetrics;if(r.fontApplicationTimes.push(n),r.fontApplicationTimes.length>100&&r.fontApplicationTimes.shift(),r.averageRenderTime=r.fontApplicationTimes.reduce((e,t)=>e+t,0)/r.fontApplicationTimes.length,n>16){const s=e.tagName.toLowerCase();t.warn(`Slow font application detected: ${n.toFixed(2)}ms for ${s} with clamp: ${i}`)}})}}class M{constructor(){this.breakpoints=new Map,this.observer=null,this.idCounter=0,this.cssRules=new Map,this.performanceMetrics={evaluationTimes:[],averageTime:0,totalEvaluations:0},this.setupResizeObserver(),this.setupPerformanceMonitoring(),this.injectBaseCSS()}setPerformanceMonitor(e){this.performanceMonitor=e}registerContainer(e,t,i){return this.register(e,t,i)}register(e,i,s){const n=this.generateId();try{const t=this.parseBreakpoints(i),r={element:e,breakpoints:i,...s&&{callback:s},parsedBreakpoints:t};return this.breakpoints.set(n,r),this.observer&&this.observer.observe(e),this.updateBreakpoint(n),n}catch(e){return t.error("Failed to register breakpoints",e),""}}updateContainer(e){this.updateElement(e)}unregister(e){const t=this.breakpoints.get(e);if(!t)return;!Array.from(this.breakpoints.values()).some(e=>e!==t&&e.element===t.element)&&this.observer&&this.observer.unobserve(t.element),this.removeBreakpointClasses(t.element,t.parsedBreakpoints),this.breakpoints.delete(e)}getCurrentBreakpoint(e){const t=this.breakpoints.get(e);return t?.currentBreakpoint||null}updateElement(e){for(const[t,i]of this.breakpoints)i.element===e&&this.updateBreakpoint(t)}getAllConfigs(){return new Map(this.breakpoints)}setupResizeObserver(){"undefined"!=typeof ResizeObserver?this.observer=new ResizeObserver(e=>{for(const t of e)this.updateElement(t.target)}):t.warn("ResizeObserver not supported. Container breakpoints may not work correctly.")}generateId(){return`proteus-breakpoint-${++this.idCounter}-${Date.now()}`}parseBreakpoints(e){const i=[];for(const[s,n]of Object.entries(e))try{const e=this.parseBreakpointValue(n);i.push({name:s,value:e.value,unit:e.unit,type:e.type,originalValue:n})}catch(e){t.warn(`Invalid breakpoint value "${n}" for "${s}"`,e)}return i.sort((e,t)=>e.value-t.value),i}parseBreakpointValue(e){const t=e.match(/\((min|max)-width:\s*(\d+(?:\.\d+)?)(px|em|rem|%|vw|vh|ch|cw|cmin|cmax)?\)/);if(t){const e=t[1];return{value:parseFloat(t[2]),unit:t[3]||"px",type:e}}const i=e.match(/^(\d+(?:\.\d+)?)(px|em|rem|%|vw|vh|ch|cw|cmin|cmax)?$/);if(!i)throw new Error(`Invalid breakpoint value: ${e}`);const s=parseFloat(i[1]),n=i[2]||"px";let r=s;switch(n){case"em":case"rem":r=16*s;break;case"vw":r=s/100*window.innerWidth;break;case"vh":r=s/100*window.innerHeight;break;default:r=s}return{value:r,unit:n,type:"min"}}updateBreakpoint(e){const i=this.breakpoints.get(e);if(!i)return;const s=i.element.getBoundingClientRect(),n=s.width,r=s.height,o=this.determineBreakpoint(n,i.parsedBreakpoints),a=i.currentBreakpoint;if(this.performanceMonitor&&this.performanceMonitor.recordOperation(),o!==a){if(i.currentBreakpoint=o,this.updateBreakpointClasses(i.element,o,i.parsedBreakpoints),i.callback)try{const e={width:n,height:r,breakpoint:o};a&&(e.previousBreakpoint=a),e.element=i.element,i.callback(o,e)}catch(e){t.error("Error in breakpoint callback",e)}this.dispatchBreakpointEvent(i.element,o,{width:n,height:r,breakpoint:o,...a&&{previousBreakpoint:a},element:i.element})}}determineBreakpoint(e,t){let i="default";const s=t.filter(e=>"min"===e.type),n=t.filter(e=>"max"===e.type);for(let t=s.length-1;t>=0;t--){const n=s[t];if(n&&e>=n.value){i=n.name;break}}for(const t of n)if(e<=t.value)return t.name;return i}updateBreakpointClasses(e,t,i){this.removeBreakpointClasses(e,i),e.classList.add(`proteus-${t}`),e.setAttribute("data-proteus-breakpoint",t),e.setAttribute("data-container",t)}removeBreakpointClasses(e,t){for(const i of t)e.classList.remove(`proteus-${i.name}`);e.removeAttribute("data-proteus-breakpoint"),e.removeAttribute("data-container")}dispatchBreakpointEvent(e,t,i){const s=new CustomEvent("proteus:breakpoint-change",{detail:i,bubbles:!0});e.dispatchEvent(s)}getMetrics(){const e=Array.from(this.breakpoints.values()),t={};e.forEach(e=>{e.parsedBreakpoints.forEach(e=>{t[e.name]=(t[e.name]||0)+1})});const i=e.length>0?e.reduce((e,t)=>e+t.parsedBreakpoints.length,0)/e.length:0;return{totalRegistrations:e.length,activeElements:new Set(e.map(e=>e.element)).size,averageBreakpoints:i,breakpointDistribution:t}}registerMultiple(e){return e.map(e=>this.register(e.element,e.breakpoints,e.callback))}unregisterElement(e){const t=[];for(const[i,s]of this.breakpoints)s.element===e&&t.push(i);t.forEach(e=>this.unregister(e))}getAllActiveBreakpoints(){const e=[];for(const[t,i]of this.breakpoints)if(i.currentBreakpoint){const s=i.element.getBoundingClientRect();e.push({id:t,element:i.element,breakpoint:i.currentBreakpoint,width:s.width,height:s.height})}return e}updateAll(){for(const e of this.breakpoints.keys())this.updateBreakpoint(e)}setupPerformanceMonitoring(){setInterval(()=>{this.performanceMetrics.evaluationTimes.length>0&&(this.performanceMetrics.averageTime=this.performanceMetrics.evaluationTimes.reduce((e,t)=>e+t,0)/this.performanceMetrics.evaluationTimes.length,this.performanceMetrics.averageTime>5&&t.warn(`Container query evaluation taking ${this.performanceMetrics.averageTime.toFixed(2)}ms on average`),this.performanceMetrics.evaluationTimes.length>100&&(this.performanceMetrics.evaluationTimes=this.performanceMetrics.evaluationTimes.slice(-50)))},1e4)}injectBaseCSS(){const e=document.createElement("style");e.id="proteus-container-queries",e.textContent='\n /* Base container query styles */\n [data-proteus-container] {\n container-type: inline-size;\n position: relative;\n }\n\n /* Performance optimizations */\n [data-proteus-container] * {\n contain: layout style;\n }\n\n /* Responsive utility classes */\n .proteus-container-small { /* Applied when container is small */ }\n .proteus-container-medium { /* Applied when container is medium */ }\n .proteus-container-large { /* Applied when container is large */ }\n\n /* Transition support */\n [data-proteus-container] {\n transition: all 0.2s ease-out;\n }\n\n /* Debug mode styles */\n [data-proteus-debug="true"] {\n outline: 2px dashed rgba(255, 0, 0, 0.3);\n position: relative;\n }\n\n [data-proteus-debug="true"]::before {\n content: attr(data-proteus-breakpoint);\n position: absolute;\n top: 0;\n left: 0;\n background: rgba(255, 0, 0, 0.8);\n color: white;\n padding: 2px 6px;\n font-size: 10px;\n font-family: monospace;\n z-index: 9999;\n pointer-events: none;\n }\n ',document.getElementById("proteus-container-queries")||document.head.appendChild(e)}generateResponsiveCSS(e,t){const i=[];Object.entries(t).forEach(([t,s])=>{const n=this.parseContainerQuery(s);n&&i.push(`\n @container (${n}) {\n [data-proteus-id="${e}"] {\n --proteus-breakpoint: "${t}";\n }\n\n [data-proteus-id="${e}"] .proteus-${t} {\n display: block;\n }\n\n [data-proteus-id="${e}"] .proteus-not-${t} {\n display: none;\n }\n }\n `)}),i.length>0&&this.injectContainerCSS(e,i.join("\n"))}parseContainerQuery(e){return e.replace(/max-width/g,"max-inline-size").replace(/min-width/g,"min-inline-size").replace(/width/g,"inline-size").replace(/max-height/g,"max-block-size").replace(/min-height/g,"min-block-size").replace(/height/g,"block-size")}injectContainerCSS(e,t){const i=`proteus-container-${e}`;let s=document.getElementById(i);s||(s=document.createElement("style"),s.id=i,document.head.appendChild(s)),s.textContent=t,s.sheet&&this.cssRules.set(e,s.sheet)}recordPerformanceMetric(e){this.performanceMetrics.evaluationTimes.push(e),this.performanceMetrics.totalEvaluations++,this.performanceMetrics.evaluationTimes.length>100&&this.performanceMetrics.evaluationTimes.shift()}getPerformanceMetrics(){return{...this.performanceMetrics}}enableDebugMode(e=!0){this.breakpoints.forEach(t=>{const i=t.element;e?i.setAttribute("data-proteus-debug","true"):i.removeAttribute("data-proteus-debug")})}destroy(){this.observer&&(this.observer.disconnect(),this.observer=null),this.cssRules.forEach((e,t)=>{const i=document.getElementById(`proteus-container-${t}`);i&&i.remove()}),this.breakpoints.clear(),this.cssRules.clear();const e=document.getElementById("proteus-container-queries");e&&e.remove()}}class I{constructor(e={}){this.polyfills=new Map,this.fallbacks=new Map,this.modernFeatures=new Set,this.legacyFeatures=new Set,this.config={enablePolyfills:!0,gracefulDegradation:!0,fallbackStrategies:!0,performanceOptimizations:!0,legacySupport:!0,modernFeatures:!0,autoDetection:!0,...e},this.browserInfo=this.detectBrowser(),this.featureSupport=this.detectFeatures(),this.config.autoDetection&&this.initializeCompatibility()}async initializeCompatibility(){t.info("Initializing browser compatibility system"),this.applyBrowserFixes(),this.config.enablePolyfills&&await this.loadPolyfills(),this.config.fallbackStrategies&&this.setupFallbacks(),this.config.performanceOptimizations&&this.applyPerformanceOptimizations(),this.config.modernFeatures&&this.setupModernFeatures(),t.info("Browser compatibility system initialized",{browser:this.browserInfo,features:this.featureSupport})}detectBrowser(){const e=navigator.userAgent,t=navigator.platform;let i="Unknown",s="0",n="Unknown";if(e.includes("Chrome")&&!e.includes("Edg")){i="Chrome";const t=e.match(/Chrome\/(\d+)/);s=t?.[1]||"0",n="Blink"}else if(e.includes("Firefox")){i="Firefox";const t=e.match(/Firefox\/(\d+)/);s=t?.[1]||"0",n="Gecko"}else if(e.includes("Safari")&&!e.includes("Chrome")){i="Safari";const t=e.match(/Version\/(\d+)/);s=t?.[1]||"0",n="WebKit"}else if(e.includes("Edg")){i="Edge";const t=e.match(/Edg\/(\d+)/);s=t?.[1]||"0",n="Blink"}else if(e.includes("MSIE")||e.includes("Trident")){i="Internet Explorer";const t=e.match(/(?:MSIE |rv:)(\d+)/);s=t?.[1]||"0",n="Trident"}return{name:i,version:s,engine:n,platform:t,mobile:/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(e),supported:this.isBrowserSupported(i,parseInt(s))}}isBrowserSupported(e,t){return t>=({Chrome:60,Firefox:55,Safari:12,Edge:79,"Internet Explorer":11}[e]||0)}detectFeatures(){return{containerQueries:this.supportsContainerQueries(),clampFunction:this.supportsClamp(),customProperties:this.supportsCustomProperties(),flexbox:this.supportsFlexbox(),grid:this.supportsGrid(),intersectionObserver:"IntersectionObserver"in window,resizeObserver:"ResizeObserver"in window,mutationObserver:"MutationObserver"in window,requestAnimationFrame:"requestAnimationFrame"in window,webAnimations:"animate"in document.createElement("div"),prefersReducedMotion:this.supportsMediaQuery("(prefers-reduced-motion: reduce)"),prefersColorScheme:this.supportsMediaQuery("(prefers-color-scheme: dark)"),viewportUnits:this.supportsViewportUnits(),calc:this.supportsCalc(),transforms:this.supportsTransforms(),transitions:this.supportsTransitions(),animations:this.supportsAnimations(),webFonts:this.supportsWebFonts(),fontDisplay:this.supportsFontDisplay(),fontVariationSettings:this.supportsFontVariationSettings()}}supportsContainerQueries(){try{return CSS.supports("container-type","inline-size")}catch{return!1}}supportsClamp(){try{return CSS.supports("width","clamp(1px, 2px, 3px)")}catch{return!1}}supportsCustomProperties(){try{return CSS.supports("--test","0")}catch{return!1}}supportsFlexbox(){try{return CSS.supports("display","flex")}catch{return!1}}supportsGrid(){try{return CSS.supports("display","grid")}catch{return!1}}supportsMediaQuery(e){try{return window.matchMedia(e).media===e}catch{return!1}}supportsViewportUnits(){try{return CSS.supports("width","1vw")}catch{return!1}}supportsCalc(){try{return CSS.supports("width","calc(1px + 1px)")}catch{return!1}}supportsTransforms(){try{return CSS.supports("transform","translateX(1px)")}catch{return!1}}supportsTransitions(){try{return CSS.supports("transition","all 1s")}catch{return!1}}supportsAnimations(){try{return CSS.supports("animation","test 1s")}catch{return!1}}supportsWebFonts(){return"fonts"in document}supportsFontDisplay(){try{return CSS.supports("font-display","swap")}catch{return!1}}supportsFontVariationSettings(){try{return CSS.supports("font-variation-settings",'"wght" 400')}catch{return!1}}applyBrowserFixes(){"Internet Explorer"===this.browserInfo.name&&this.applyIEFixes(),"Safari"===this.browserInfo.name&&this.applySafariFixes(),"Firefox"===this.browserInfo.name&&this.applyFirefoxFixes(),this.browserInfo.mobile&&this.applyMobileFixes()}applyIEFixes(){document.documentElement.classList.add("ie"),this.featureSupport.viewportUnits||this.addPolyfill("viewport-units",{name:"Viewport Units Polyfill",required:!0,loaded:!1,size:15e3,fallback:this.viewportUnitsFallback.bind(this)}),this.featureSupport.flexbox||this.addPolyfill("flexbox",{name:"Flexbox Polyfill",required:!0,loaded:!1,size:25e3,fallback:this.flexboxFallback.bind(this)})}applySafariFixes(){document.documentElement.classList.add("safari");parseInt(this.browserInfo.version)<14&&document.documentElement.classList.add("safari-old")}applyFirefoxFixes(){document.documentElement.classList.add("firefox");const e=document.createElement("style");e.textContent="\n /* Firefox scrollbar styling */\n * {\n scrollbar-width: thin;\n scrollbar-color: rgba(0,0,0,0.3) transparent;\n }\n ",document.head.appendChild(e)}applyMobileFixes(){document.documentElement.classList.add("mobile");const e=()=>{const e=.01*window.innerHeight;document.documentElement.style.setProperty("--vh",`${e}px`)};e(),window.addEventListener("resize",e),window.addEventListener("orientationchange",e);const t=document.querySelector('meta[name="viewport"]');t&&t.setAttribute("content","width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no")}async loadPolyfills(){const e=Array.from(this.polyfills.values()).filter(e=>e.required&&!e.loaded);if(0!==e.length){t.info(`Loading ${e.length} polyfills`);for(const i of e)try{i.url?await this.loadPolyfillScript(i):i.fallback&&i.fallback(),i.loaded=!0,t.info(`Loaded polyfill: ${i.name}`)}catch(e){t.error(`Failed to load polyfill ${i.name}:`,e),i.fallback&&(i.fallback(),i.loaded=!0)}}}loadPolyfillScript(e){return new Promise((t,i)=>{const s=document.createElement("script");s.src=e.url,s.async=!0,s.onload=()=>t(),s.onerror=()=>i(new Error(`Failed to load ${e.url}`)),document.head.appendChild(s)})}addPolyfill(e,t){this.polyfills.set(e,t)}setupFallbacks(){this.featureSupport.containerQueries||this.fallbacks.set("container-queries",this.containerQueriesFallback.bind(this)),this.featureSupport.clampFunction||this.fallbacks.set("clamp",this.clampFallback.bind(this)),this.featureSupport.customProperties||this.fallbacks.set("custom-properties",this.customPropertiesFallback.bind(this)),this.featureSupport.intersectionObserver||this.fallbacks.set("intersection-observer",this.intersectionObserverFallback.bind(this))}containerQueriesFallback(){if(this.featureSupport.resizeObserver){t.info("Using ResizeObserver fallback for container queries");const e=document.createElement("style");e.id="container-queries-fallback",e.textContent='\n /* Container queries fallback using ResizeObserver */\n [data-container-fallback] {\n position: relative;\n }\n\n [data-container="small"] {\n --container-size: small;\n }\n\n [data-container="medium"] {\n --container-size: medium;\n }\n\n [data-container="large"] {\n --container-size: large;\n }\n ',document.getElementById("container-queries-fallback")||document.head.appendChild(e);const i=new ResizeObserver(e=>{e.forEach(e=>{const t=e.target,i=e.contentRect.width;t.removeAttribute("data-container"),i<=400?t.setAttribute("data-container","small"):i<=800?t.setAttribute("data-container","medium"):t.setAttribute("data-container","large")})});document.querySelectorAll("[data-container-fallback]").forEach(e=>{i.observe(e)})}else{t.warn("No fallback available for container queries");const e=document.createElement("style");e.textContent="\n /* Media query fallback for container queries */\n @media (max-width: 400px) {\n [data-container-fallback] {\n --container-size: small;\n }\n }\n\n @media (min-width: 401px) and (max-width: 800px) {\n [data-container-fallback] {\n --container-size: medium;\n }\n }\n\n @media (min-width: 801px) {\n [data-container-fallback] {\n --container-size: large;\n }\n }\n ",document.head.appendChild(e)}}clampFallback(){t.info("Using calc() and media queries fallback for clamp()");const e=document.createElement("style");e.id="clamp-fallback",e.textContent="\n /* Clamp fallback styles */\n .proteus-clamp {\n font-size: var(--min-size, 16px);\n }\n\n @media (min-width: 320px) {\n .proteus-clamp {\n font-size: calc(var(--min-size, 16px) + (var(--max-size, 24px) - var(--min-size, 16px)) * ((100vw - 320px) / (1200px - 320px)));\n }\n }\n\n @media (min-width: 1200px) {\n .proteus-clamp {\n font-size: var(--max-size, 24px);\n }\n }\n ",document.head.appendChild(e)}customPropertiesFallback(){t.info("Using JavaScript fallback for CSS custom properties");const e=new Map,i=t=>{window.getComputedStyle(t);const i=t.style.cssText,s=/--([\w-]+):\s*([^;]+)/g;let n;for(;null!==(n=s.exec(i));)n[1]&&n[2]&&e.set(`--${n[1]}`,n[2].trim())},s=t=>{const i=t,s=i.style.cssText,n=/var\((--[\w-]+)(?:,\s*([^)]+))?\)/g;let r,o=s;for(;null!==(r=n.exec(s));){const t=r[1],i=r[2]||"",s=e.get(t||"")||i;s&&(o=o.replace(r[0],s))}o!==s&&(i.style.cssText=o)};new MutationObserver(e=>{e.forEach(e=>{if("attributes"===e.type&&"style"===e.attributeName){const t=e.target;i(t),s(t)}})}).observe(document.body,{attributes:!0,subtree:!0,attributeFilter:["style"]}),document.querySelectorAll("*").forEach(e=>{i(e),s(e)})}intersectionObserverFallback(){t.info("Using scroll event fallback for Intersection Observer");class e{constructor(e,t={}){this.elements=new Set,this.handleScroll=()=>{this.checkIntersection()},this.callback=e,this.rootMargin=t.rootMargin||"0px",this.threshold=t.threshold||0,this.setupScrollListener()}observe(e){this.elements.add(e),this.checkIntersection()}unobserve(e){this.elements.delete(e)}disconnect(){this.elements.clear(),window.removeEventListener("scroll",this.handleScroll),window.removeEventListener("resize",this.handleScroll)}setupScrollListener(){this.handleScroll=this.handleScroll.bind(this),window.addEventListener("scroll",this.handleScroll,{passive:!0}),window.addEventListener("resize",this.handleScroll,{passive:!0})}checkIntersection(){const e=[];this.elements.forEach(t=>{const i=t.getBoundingClientRect(),s=window.innerHeight,n=window.innerWidth,r=i.top<s&&i.bottom>0&&i.left<n&&i.right>0;let o=0;if(r){const e=(Math.min(i.bottom,s)-Math.max(i.top,0))*(Math.min(i.right,n)-Math.max(i.left,0)),t=i.height*i.width;o=t>0?e/t:0}e.push({target:t,isIntersecting:r,intersectionRatio:o,boundingClientRect:i,intersectionRect:i,rootBounds:{top:0,left:0,bottom:s,right:n,width:n,height:s},time:Date.now()})}),e.length>0&&this.callback(e,this)}}window.IntersectionObserver||(window.IntersectionObserver=e)}viewportUnitsFallback(){t.info("Using JavaScript fallback for viewport units");const e=()=>{const e=window.innerWidth/100,t=window.innerHeight/100;document.documentElement.style.setProperty("--vw",`${e}px`),document.documentElement.style.setProperty("--vh",`${t}px`)};e(),window.addEventListener("resize",e)}flexboxFallback(){t.info("Using table/inline-block fallback for flexbox");const e=document.createElement("style");e.textContent="\n /* Flexbox fallback */\n .proteus-flex {\n display: table;\n width: 100%;\n }\n\n .proteus-flex-item {\n display: table-cell;\n vertical-align: middle;\n }\n ",document.head.appendChild(e)}applyPerformanceOptimizations(){this.browserInfo.supported||this.applyLegacyOptimizations(),this.browserInfo.mobile&&this.applyMobileOptimizations(),this.applyFeatureBasedOptimizations()}applyLegacyOptimizations(){document.documentElement.classList.add("legacy-browser");const e=document.createElement("style");e.textContent="\n .legacy-browser * {\n animation-duration: 0.1s !important;\n transition-duration: 0.1s !important;\n }\n ",document.head.appendChild(e)}applyMobileOptimizations(){const e=document.createElement("style");e.textContent='\n /* Mobile optimizations */\n * {\n -webkit-tap-highlight-color: transparent;\n touch-action: manipulation;\n }\n\n button, a, [role="button"] {\n min-height: 44px;\n min-width: 44px;\n }\n ',document.head.appendChild(e)}applyFeatureBasedOptimizations(){this.featureSupport.transforms&&document.documentElement.classList.add("transforms-supported"),this.featureSupport.webAnimations||document.documentElement.classList.add("no-web-animations")}setupModernFeatures(){Object.entries(this.featureSupport).forEach(([e,t])=>{t?(this.modernFeatures.add(e),document.documentElement.classList.add(`supports-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`)):(this.legacyFeatures.add(e),document.documentElement.classList.add(`no-${e.replace(/([A-Z])/g,"-$1").toLowerCase()}`))})}getBrowserInfo(){return{...this.browserInfo}}getFeatureSupport(){return{...this.featureSupport}}isFeatureSupported(e){return this.featureSupport[e]}getCompatibilityReport(){const e=[];return this.browserInfo.supported||e.push("Consider upgrading to a modern browser for better performance"),this.legacyFeatures.size>5&&e.push("Many modern features are not supported - consider using polyfills"),"Internet Explorer"===this.browserInfo.name&&e.push("Internet Explorer support is limited - consider migrating to Edge"),{browser:this.getBrowserInfo(),features:this.getFeatureSupport(),polyfills:Array.from(this.polyfills.values()),modernFeatures:Array.from(this.modernFeatures),legacyFeatures:Array.from(this.legacyFeatures),recommendations:e}}enableGracefulDegradation(e,t){this.fallbacks.set(e,t),this.modernFeatures.has(e)||t()}destroy(){document.querySelectorAll('style[id*="proteus"], style[id*="clamp-fallback"]').forEach(e=>e.remove()),this.polyfills.clear(),this.fallbacks.clear(),this.modernFeatures.clear(),this.legacyFeatures.clear(),t.info("Browser compatibility system destroyed")}}class R{constructor(){this.detectedBottlenecks=[]}detectBottlenecks(e){return this.detectedBottlenecks=[],e.averageFPS<30&&this.detectedBottlenecks.push({type:"cpu",severity:"high",description:"Low frame rate detected",impact:(30-e.averageFPS)/30,suggestions:["Reduce DOM manipulations","Optimize JavaScript execution","Use requestAnimationFrame for animations"]}),e.memoryUsage.percentage>80&&this.detectedBottlenecks.push({type:"memory",severity:"high",description:"High memory usage detected",impact:e.memoryUsage.percentage/100,suggestions:["Clean up unused objects","Remove event listeners","Optimize image sizes"]}),e.domNodes>5e3&&this.detectedBottlenecks.push({type:"dom",severity:"medium",description:"Large DOM tree detected",impact:Math.min(e.domNodes/1e4,1),suggestions:["Implement virtual scrolling","Remove unused DOM nodes","Use document fragments for batch operations"]}),this.detectedBottlenecks}getBottlenecks(){return[...this.detectedBottlenecks]}}class T{constructor(){this.memoryLeakDetector=new Map,this.cleanupTasks=[]}optimizeMemory(){window.gc&&window.gc(),this.cleanupTasks.forEach(e=>{try{e()}catch(e){t.warn("Memory cleanup task failed:",e)}}),this.cleanupTasks=[]}detectMemoryLeaks(e){const t=e.memoryUsage.used,i=Date.now();this.memoryLeakDetector.set(i.toString(),t);const s=Array.from(this.memoryLeakDetector.entries());if(s.length>10&&s.slice(0,-10).forEach(([e])=>{this.memoryLeakDetector.delete(e)}),s.length>=5){const e=s.map(([,e])=>e),t=e.every((t,i)=>0===i||t>=(e[i-1]||0)),i=e[e.length-1]||0,n=e[0]||1;return t&&(i-n)/n>.1}return!1}addCleanupTask(e){this.cleanupTasks.push(e)}}class ${constructor(e={}){this.alerts=[],this.isMonitoring=!1,this.rafId=null,this.lastFrameTime=0,this.frameCount=0,this.performanceHistory=[],this.callbacks=new Map,this.measurementInterval=1e3,this.detailedProfiling=!1,this.frameTimes=[],this.operationCount=0,this.lastOperationTime=0,this.bottleneckDetector=new R,this.memoryOptimizer=new T,this.thresholds={minFrameRate:55,maxFrameTime:16.67,maxMemoryUsage:104857600,maxDOMNodes:5e3,maxEventListeners:1e3,...e},this.metrics=this.createInitialMetrics()}startMonitoring(){this.start()}start(){this.isMonitoring||(this.isMonitoring=!0,this.lastFrameTime=performance.now(),this.lastOperationTime=performance.now(),this.startFrameMonitoring(),this.startMemoryMonitoring())}stop(){this.isMonitoring&&(this.isMonitoring=!1,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null))}destroy(){this.stop(),this.callbacks.clear(),this.alerts=[],this.frameTimes=[],this.frameCount=0,this.operationCount=0,this.metrics=this.createInitialMetrics()}startFrameRateMonitoring(){this.isMonitoring||this.start()}stopFrameRateMonitoring(){this.stop()}async measureOperation(e,t){const i=performance.now(),s=await t(),n=performance.now()-i;return this.recordOperation(),{result:s,duration:n,name:e}}detectBottlenecks(){const e=[];return this.metrics.averageFPS<30?e.push({type:"frame-rate",severity:"high",description:`Low frame rate: ${this.metrics.averageFPS.toFixed(1)} FPS`}):this.metrics.averageFPS<50&&e.push({type:"frame-rate",severity:"medium",description:`Moderate frame rate: ${this.metrics.averageFPS.toFixed(1)} FPS`}),this.metrics.memoryUsage.percentage>80&&e.push({type:"memory",severity:"high",description:`High memory usage: ${this.metrics.memoryUsage.percentage.toFixed(1)}%`}),e}getMetrics(){return this.updateMetrics(),{...this.metrics}}getAlerts(){return[...this.alerts]}clearAlerts(){this.alerts=[]}addCallback(e,t){this.callbacks.set(e,t)}removeCallback(e){this.callbacks.delete(e)}recordOperation(){this.operationCount++}updateCacheHitRate(e,t){this.metrics.cacheHitRate=t>0?e/t*100:0}updateMetrics(){this.updateFrameMetrics(),this.updateMemoryMetrics(),this.updateDOMMetrics(),this.updateOperationMetrics(),this.checkThresholds(),this.notifyCallbacks()}getRecommendations(){const e=[];return this.metrics.frameRate<this.thresholds.minFrameRate&&(e.push("Consider reducing DOM manipulations or using requestAnimationFrame"),e.push("Enable batch DOM operations to improve frame rate")),this.metrics.memoryUsage.percentage>80&&(e.push("Memory usage is high - consider implementing cleanup routines"),e.push("Review event listeners and observers for potential leaks")),this.metrics.domNodes>this.thresholds.maxDOMNodes&&(e.push("DOM tree is large - consider virtualization for long lists"),e.push("Remove unused DOM elements to improve performance")),this.metrics.eventListeners>this.thresholds.maxEventListeners&&(e.push("High number of event listeners - consider event delegation"),e.push("Review and cleanup unused event listeners")),this.metrics.cacheHitRate<70&&(e.push("Cache hit rate is low - review caching strategy"),e.push("Consider increasing cache size or improving cache keys")),e}startFrameMonitoring(){const e=t=>{if(!this.isMonitoring)return;const i=t-this.lastFrameTime;this.frameTimes.push(i),this.frameTimes.length>60&&this.frameTimes.shift(),this.frameCount++,this.lastFrameTime=t,(this.frameCount%60==0||i>1e3)&&(this.updateFrameMetrics(),this.checkThresholds(),this.notifyCallbacks()),this.rafId=requestAnimationFrame(e)};this.rafId=requestAnimationFrame(e)}startMemoryMonitoring(){const e=()=>{this.isMonitoring&&(this.updateMemoryMetrics(),setTimeout(e,5e3))};setTimeout(e,5e3)}updateFrameMetrics(){if(0===this.frameTimes.length)return;const e=this.frameTimes.reduce((e,t)=>e+t,0)/this.frameTimes.length,t=e>0?1e3/e:60;this.metrics.averageFrameTime=Math.round(100*e)/100,this.metrics.frameRate=Math.round(100*t)/100,this.metrics.averageFPS=this.metrics.frameRate,this.metrics.lastMeasurement=performance.now()}updateMemoryMetrics(){if("memory"in performance){const e=performance.memory;this.metrics.memoryUsage={used:e.usedJSHeapSize,total:e.totalJSHeapSize,percentage:Math.round(e.usedJSHeapSize/e.totalJSHeapSize*100)}}}updateDOMMetrics(){this.metrics.domNodes=document.querySelectorAll("*").length,this.metrics.eventListeners=this.estimateEventListeners(),this.metrics.observers=this.countObservers()}updateOperationMetrics(){const e=performance.now(),t=(e-this.lastOperationTime)/1e3;t>0&&(this.metrics.operationsPerSecond=Math.round(this.operationCount/t)),this.operationCount=0,this.lastOperationTime=e}estimateEventListeners(){const e=document.querySelectorAll("*");let t=0;const i=["click","scroll","resize","load","input","change"];return e.forEach(e=>{i.forEach(i=>{null!==e[`on${i}`]&&t++})}),t}countObservers(){return 0}checkThresholds(){const e=performance.now();this.metrics.frameRate<this.thresholds.minFrameRate&&this.addAlert({type:"warning",metric:"frameRate",value:this.metrics.frameRate,threshold:this.thresholds.minFrameRate,message:`Frame rate (${this.metrics.frameRate}fps) is below target (${this.thresholds.minFrameRate}fps)`,timestamp:e,suggestions:["Reduce DOM manipulations","Use requestAnimationFrame for animations","Enable batch DOM operations"]}),this.metrics.memoryUsage.used>this.thresholds.maxMemoryUsage&&this.addAlert({type:"critical",metric:"memoryUsage",value:this.metrics.memoryUsage.used,threshold:this.thresholds.maxMemoryUsage,message:`Memory usage (${Math.round(this.metrics.memoryUsage.used/1024/1024)}MB) exceeds threshold`,timestamp:e,suggestions:["Implement cleanup routines","Review for memory leaks","Optimize data structures"]}),this.metrics.domNodes>this.thresholds.maxDOMNodes&&this.addAlert({type:"warning",metric:"domNodes",value:this.metrics.domNodes,threshold:this.thresholds.maxDOMNodes,message:`DOM tree size (${this.metrics.domNodes} nodes) is large`,timestamp:e,suggestions:["Consider virtualization","Remove unused elements","Optimize DOM structure"]})}addAlert(e){this.alerts.find(t=>t.metric===e.metric&&e.timestamp-t.timestamp<3e4)||(this.alerts.push(e),this.alerts.length>50&&this.alerts.shift())}notifyCallbacks(){this.callbacks.forEach(e=>{try{e(this.metrics)}catch(e){t.error("Error in performance callback",e)}})}createInitialMetrics(){return{frameRate:60,averageFPS:60,averageFrameTime:16.67,memoryUsage:{used:0,total:0,percentage:0},domNodes:0,eventListeners:0,observers:0,cacheHitRate:0,operationsPerSecond:0,lastMeasurement:performance.now()}}enableDetailedProfiling(e=!0){this.detailedProfiling=e,e?this.startAdvancedMonitoring():this.stopAdvancedMonitoring()}startAdvancedMonitoring(){this.startFrameRateMonitoring(),setInterval(()=>{const e=this.getMetrics();this.memoryOptimizer.detectMemoryLeaks(e)&&this.addAlert({type:"warning",metric:"memory",value:e.memoryUsage.percentage,threshold:80,message:"Potential memory leak detected",timestamp:Date.now(),suggestions:["Check for unreferenced objects","Remove unused event listeners","Clear intervals and timeouts"]})},5e3),setInterval(()=>{const e=this.getMetrics();this.bottleneckDetector.detectBottlenecks(e).forEach(e=>{"high"===e.severity&&this.addAlert({type:"critical",metric:e.type,value:100*e.impact,threshold:50,message:e.description,timestamp:Date.now(),suggestions:e.suggestions})})},2e3)}stopAdvancedMonitoring(){t.info("Advanced performance monitoring stopped")}getPerformanceSnapshot(){const e=this.getMetrics(),t=this.bottleneckDetector.getBottlenecks().map(e=>e.description),i=this.memoryOptimizer.detectMemoryLeaks(e),s={timestamp:Date.now(),metrics:e,bottlenecks:t,memoryLeaks:i};return this.performanceHistory.push(s),this.performanceHistory.length>100&&this.performanceHistory.shift(),s}getPerformanceHistory(){return[...this.performanceHistory]}analyzePerformanceTrends(){if(this.performanceHistory.length<5)return{frameRateTrend:"stable",memoryTrend:"stable",overallHealth:"good"};const e=this.performanceHistory.slice(-5),t=e.map(e=>e.metrics.averageFPS),i=e.map(e=>e.metrics.memoryUsage.percentage),s=this.calculateTrend(t),n=s>1?"improving":s<-1?"degrading":"stable",r=this.calculateTrend(i),o=r<-5?"improving":r>5?"degrading":"stable",a=e[e.length-1]?.metrics;let c="good";return a&&(a.averageFPS<30||a.memoryUsage.percentage>80?c="critical":(a.averageFPS<45||a.memoryUsage.percentage>60)&&(c="warning")),{frameRateTrend:n,memoryTrend:o,overallHealth:c}}calculateTrend(e){if(e.length<2)return 0;const t=e.length,i=t*(t-1)/2,s=e.reduce((e,t)=>e+t,0);return(t*e.reduce((e,t,i)=>e+i*t,0)-i*s)/(t*e.reduce((e,t,i)=>e+i*i,0)-i*i)}optimizePerformance(){const e=this.getMetrics(),i=this.bottleneckDetector.detectBottlenecks(e);e.memoryUsage.percentage>70&&(this.memoryOptimizer.optimizeMemory(),t.info("Memory optimization applied")),e.domNodes>3e3&&this.optimizeDOM(),i.forEach(e=>{t.info(`Performance bottleneck detected: ${e.description}`),t.info(`Suggestions: ${e.suggestions.join(", ")}`)})}optimizeDOM(){const e=document.querySelectorAll("[data-proteus-unused]");e.forEach(e=>e.remove());const i=document.querySelectorAll("img:not([loading])");i.forEach(e=>{e.loading="lazy"}),t.info(`DOM optimization applied: removed ${e.length} unused elements, optimized ${i.length} images`)}generatePerformanceReport(){const e=this.getMetrics(),t=this.bottleneckDetector.detectBottlenecks(e),i=this.analyzePerformanceTrends(),s=[];e.averageFPS<45&&(s.push("Consider reducing animation complexity"),s.push("Optimize JavaScript execution with requestAnimationFrame")),e.memoryUsage.percentage>60&&(s.push("Implement memory cleanup strategies"),s.push("Remove unused event listeners and observers")),e.domNodes>2e3&&(s.push("Consider virtual scrolling for large lists"),s.push("Remove unused DOM elements")),t.forEach(e=>{s.push(...e.suggestions)});return{summary:`Performance Health: ${i.overallHealth.toUpperCase()} | FPS: ${e.averageFPS.toFixed(1)} | Memory: ${e.memoryUsage.percentage.toFixed(1)}% | DOM Nodes: ${e.domNodes}`,metrics:e,bottlenecks:t,trends:i,recommendations:[...new Set(s)]}}}class L{constructor(e={}){this.readQueue=[],this.writeQueue=[],this.processingQueue=[],this.rafId=null,this.flushTimer=null,this.isProcessing=!1,this.operationResults=new Map,this.config={maxBatchSize:50,frameTimeLimit:16,separateReadWrite:!0,measurePerformance:!0,autoFlush:!0,flushInterval:100,...e},this.metrics=this.createInitialMetrics(),this.config.autoFlush&&this.startAutoFlush()}queueRead(e,t,i="normal",s=[]){const n=this.generateOperationId("read");return new Promise((r,o)=>{const a={id:n,type:"read",element:e,operation:()=>{try{const e=t();return this.operationResults.set(n,e),r(e),e}catch(e){throw o(e),e}},priority:i,timestamp:performance.now(),dependencies:s};this.readQueue.push(a),this.scheduleProcessing()})}queueWrite(e,t,i="normal",s=[]){const n=this.generateOperationId("write");return new Promise((r,o)=>{const a={id:n,type:"write",element:e,operation:()=>{try{t(),r()}catch(e){throw o(e),e}},priority:i,timestamp:performance.now(),dependencies:s};this.writeQueue.push(a),this.scheduleProcessing()})}batchStyles(e,t,i="normal"){return this.queueWrite(e,()=>{const i=e;Object.entries(t).forEach(([e,t])=>{i.style.setProperty(e,t)})},i)}batchClasses(e,t,i="normal"){return this.queueWrite(e,()=>{t.add&&e.classList.add(...t.add),t.remove&&e.classList.remove(...t.remove),t.toggle&&t.toggle.forEach(t=>{e.classList.toggle(t)})},i)}batchAttributes(e,t,i="normal"){return this.queueWrite(e,()=>{Object.entries(t).forEach(([t,i])=>{null===i?e.removeAttribute(t):e.setAttribute(t,i)})},i)}batchReads(e,t,i="normal"){return this.queueRead(e,()=>{const e={};return Object.entries(t).forEach(([t,i])=>{e[t]=i()}),e},i)}measureElement(e,t=["width","height"],i="normal"){return this.queueRead(e,()=>{const i=e.getBoundingClientRect(),s={};return t.forEach(e=>{s[e]=i[e]}),s},i)}flush(){return new Promise(e=>{this.processOperations(!0).then(()=>{e()})})}getMetrics(){return{...this.metrics}}clear(){this.readQueue=[],this.writeQueue=[],this.processingQueue=[],this.operationResults.clear()}destroy(){this.stopAutoFlush(),this.stopProcessing(),this.clear()}scheduleProcessing(){this.isProcessing||this.rafId||(this.rafId=requestAnimationFrame(()=>{this.processOperations(),this.rafId=null}))}async processOperations(e=!1){if(this.isProcessing)return;this.isProcessing=!0;const t=performance.now();try{if(this.config.separateReadWrite)await this.processQueue(this.readQueue,"read",e),await this.processQueue(this.writeQueue,"write",e);else{const t=[...this.readQueue,...this.writeQueue];this.readQueue=[],this.writeQueue=[],await this.processQueue(t,"mixed",e)}const i=performance.now()-t;this.updateMetrics(i)}finally{this.isProcessing=!1}}async processQueue(e,t,i){if(0===e.length)return;const s=this.sortOperations(e),n=i?1/0:this.config.frameTimeLimit,r=performance.now();let o=0;for(const a of s){const s=performance.now()-r;if(!i&&s>n)break;if(!this.areDependenciesSatisfied(a))continue;if(!i&&o>=this.config.maxBatchSize)break;try{this.config.measurePerformance&&this.wouldCauseLayoutThrash(a,t)&&this.metrics.layoutThrashes++,a.operation(),o++,"read"===a.type?this.metrics.readOperations++:this.metrics.writeOperations++}catch(e){}const c=e.indexOf(a);c>-1&&e.splice(c,1)}this.metrics.totalOperations+=o}sortOperations(e){return e.sort((e,t)=>{const i={high:0,normal:1,low:2},s=i[e.priority]-i[t.priority];return 0!==s?s:e.timestamp-t.timestamp})}areDependenciesSatisfied(e){return!e.dependencies||0===e.dependencies.length||e.dependencies.every(e=>this.operationResults.has(e))}wouldCauseLayoutThrash(e,t){if("mixed"===t&&"write"===e.type){return this.processingQueue.filter(e=>"read"===e.type&&performance.now()-e.timestamp<16).length>0}return!1}generateOperationId(e){return`${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}startAutoFlush(){this.flushTimer=window.setInterval(()=>{(this.readQueue.length>0||this.writeQueue.length>0)&&this.scheduleProcessing()},this.config.flushInterval)}stopAutoFlush(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}stopProcessing(){this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null)}updateMetrics(e){if(this.metrics.batchesProcessed++,this.metrics.averageBatchTime=(this.metrics.averageBatchTime+e)/2,this.config.separateReadWrite){const e=Math.min(this.readQueue.length,this.writeQueue.length);this.metrics.preventedThrashes+=e}}createInitialMetrics(){return{totalOperations:0,readOperations:0,writeOperations:0,batchesProcessed:0,averageBatchTime:0,layoutThrashes:0,preventedThrashes:0}}}class P{constructor(e={}){this.components=new Map,this.intersectionObserver=null,this.activationQueue=[],this.cache=new Map,this.isProcessing=!1,this.activeActivations=new Set,this.config={rootMargin:"50px",threshold:[0,.1,.5,1],useIdleCallback:!0,idleTimeout:5e3,progressiveEnhancement:!0,cacheResults:!0,priorityQueue:!0,maxConcurrent:3,...e},this.metrics=this.createInitialMetrics(),this.setupIntersectionObserver()}register(e,t,i={}){const s=i.id||this.generateId(),n={id:s,element:e,activator:t,priority:i.priority||"normal",dependencies:i.dependencies||[],activated:!1,cached:!1,timestamp:performance.now()};return this.components.set(s,n),this.metrics.totalComponents++,i.immediate?this.activateComponent(n):this.observeComponent(n),s}unregister(e){const t=this.components.get(e);t&&(this.intersectionObserver?.unobserve(t.element),this.components.delete(e),this.cache.delete(e),this.metrics.totalComponents--)}async activate(e){const t=this.components.get(e);t&&!t.activated&&await this.activateComponent(t)}preloadHighPriority(){Array.from(this.components.values()).filter(e=>"high"===e.priority&&!e.activated).forEach(e=>{this.scheduleActivation(e)})}getCached(e){if(!this.config.cacheResults)return null;const t=this.cache.get(e);return t?(this.metrics.cacheHits++,t):(this.metrics.cacheMisses++,null)}setCached(e,t){this.config.cacheResults&&this.cache.set(e,t)}getMetrics(){return{...this.metrics}}clearCache(){this.cache.clear()}destroy(){this.intersectionObserver?.disconnect(),this.components.clear(),this.cache.clear(),this.activationQueue=[],this.activeActivations.clear()}setupIntersectionObserver(){window.IntersectionObserver&&(this.intersectionObserver=new IntersectionObserver(e=>{e.forEach(e=>{if(e.isIntersecting){const t=this.findComponentByElement(e.target);t&&!t.activated&&this.scheduleActivation(t)}})},{rootMargin:this.config.rootMargin,threshold:this.config.threshold}))}observeComponent(e){this.intersectionObserver?this.intersectionObserver.observe(e.element):this.scheduleActivation(e)}scheduleActivation(e){this.config.priorityQueue?(this.addToQueue(e),this.processQueue()):this.activateComponent(e)}addToQueue(e){this.activationQueue.some(t=>t.id===e.id)||(this.activationQueue.push(e),this.activationQueue.sort((e,t)=>{const i={high:0,normal:1,low:2},s=i[e.priority]-i[t.priority];return 0!==s?s:e.timestamp-t.timestamp}))}async processQueue(){if(!this.isProcessing&&0!==this.activationQueue.length){this.isProcessing=!0;try{for(;this.activationQueue.length>0&&this.activeActivations.size<this.config.maxConcurrent;){const e=this.activationQueue.shift();e&&!e.activated&&this.areDependenciesSatisfied(e)&&this.activateComponent(e)}}finally{this.isProcessing=!1,this.activationQueue.length>0&&this.scheduleNextProcessing()}}}scheduleNextProcessing(){this.config.useIdleCallback&&window.requestIdleCallback?(window.requestIdleCallback(()=>this.processQueue(),{timeout:this.config.idleTimeout}),this.metrics.idleCallbacksUsed++):setTimeout(()=>this.processQueue(),16)}async activateComponent(e){if(e.activated||this.activeActivations.has(e.id))return;this.activeActivations.add(e.id);const t=performance.now();try{const i=`component-${e.id}`;let s=this.getCached(i);if(!s){if(this.config.progressiveEnhancement&&!this.isEnhancementSupported(e))return;s=await e.activator(),this.config.cacheResults&&(this.setCached(i,s),e.cached=!0)}e.activated=!0,this.metrics.activatedComponents++,this.metrics.pendingComponents=this.metrics.totalComponents-this.metrics.activatedComponents;const n=performance.now()-t;this.metrics.averageActivationTime=(this.metrics.averageActivationTime+n)/2,this.intersectionObserver?.unobserve(e.element)}catch(e){}finally{this.activeActivations.delete(e.id),this.activationQueue.length>0&&this.scheduleNextProcessing()}}areDependenciesSatisfied(e){return e.dependencies.every(e=>{const t=this.components.get(e);return t?.activated||!1})}isEnhancementSupported(e){return["IntersectionObserver","ResizeObserver","requestAnimationFrame"].every(e=>e in window)}findComponentByElement(e){return Array.from(this.components.values()).find(t=>t.element===e)}generateId(){return`lazy-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}createInitialMetrics(){return{totalComponents:0,activatedComponents:0,pendingComponents:0,cacheHits:0,cacheMisses:0,averageActivationTime:0,idleCallbacksUsed:0}}}class F{constructor(e={}){this.styleRules=new Map,this.customProperties=new Map,this.usageTracker=new Map,this.criticalSelectors=new Set,this.mutationObserver=null,this.config={deduplication:!0,criticalCSS:!0,unusedStyleRemoval:!0,customPropertyOptimization:!0,styleInvalidationTracking:!0,minification:!0,autoprefixer:!1,purgeUnused:!0,...e},this.metrics=this.createInitialMetrics(),this.setupStyleTracking()}async optimizeAll(){performance.now();await this.extractAllStyles(),this.config.deduplication&&this.deduplicateStyles(),this.config.unusedStyleRemoval&&this.removeUnusedStyles(),this.config.customPropertyOptimization&&this.optimizeCustomProperties(),this.config.criticalCSS&&this.extractCriticalCSS();const e=this.generateOptimizedCSS();this.updateMetrics(e);performance.now();return this.metrics}extractCriticalCSS(){const e=[],t=window.innerHeight;return this.getElementsInViewport(t).forEach(t=>{this.getSelectorsForElement(t).forEach(t=>{this.criticalSelectors.add(t);const i=this.styleRules.get(t);i&&(i.critical=!0,e.push(i))})}),this.metrics.criticalRulesExtracted=e.length,this.rulesToCSS(e)}removeUnusedStyles(){if(!this.config.purgeUnused)return;let e=0;this.styleRules.forEach((t,i)=>{if(!t.used&&!t.critical)try{0===document.querySelectorAll(i).length&&(this.styleRules.delete(i),e++)}catch(t){this.styleRules.delete(i),e++}}),this.metrics.rulesRemoved=e}deduplicateStyles(){const e=new Map;let t=0;this.styleRules.forEach((t,i)=>{const s=this.serializeDeclarations(t.declarations);e.has(s)||e.set(s,[]),e.get(s).push(i)}),e.forEach(e=>{if(e.length>1){t+=e.length-1;const i=e[0],s=this.styleRules.get(i),n=e.join(", ");e.forEach(e=>{this.styleRules.delete(e)}),this.styleRules.set(n,{...s,selector:n})}}),this.metrics.duplicatesFound=t}optimizeCustomProperties(){let e=0;this.styleRules.forEach(e=>{e.declarations.forEach((e,t)=>{t.startsWith("--")&&this.customProperties.set(t,e)})}),this.customProperties.forEach((t,i)=>{const s=this.findCustomPropertyUsage(i);if(1===s.length){const n=s[0],r=this.findPropertyUsingCustomProperty(n,i);r&&n&&(n.declarations.set(r,t),n.declarations.delete(i),e++)}}),this.metrics.customPropertiesOptimized=e}trackStyleInvalidations(){if(this.config.styleInvalidationTracking)try{"undefined"!=typeof MutationObserver&&document&&document.body&&(this.mutationObserver=new MutationObserver(e=>{e.forEach(e=>{"attributes"!==e.type||"class"!==e.attributeName&&"style"!==e.attributeName||this.handleStyleInvalidation(e.target)})}),document.body&&this.mutationObserver&&"function"==typeof this.mutationObserver.observe&&this.mutationObserver.observe(document.body,{attributes:!0,attributeFilter:["class","style"],subtree:!0}))}catch(e){t.warn("Failed to setup style invalidation tracking:",e)}}generateOptimizedCSS(){const e=Array.from(this.styleRules.values());return e.sort((e,t)=>e.critical!==t.critical?e.critical?-1:1:e.specificity-t.specificity),this.rulesToCSS(e)}getMetrics(){return{...this.metrics}}clearCache(){this.styleRules.clear(),this.customProperties.clear(),this.usageTracker.clear(),this.criticalSelectors.clear(),this.metrics=this.createInitialMetrics()}destroy(){this.mutationObserver?.disconnect(),this.clearCache()}async extractAllStyles(){const e=this.calculateCurrentCSSSize();this.metrics.originalSize=e;for(const e of document.styleSheets)try{await this.extractFromStylesheet(e)}catch(e){}this.extractInlineStyles()}async extractFromStylesheet(e){try{const t=e.cssRules;for(let e=0;e<t.length;e++){const i=t[e];if(i instanceof CSSStyleRule)this.extractStyleRule(i,"stylesheet");else if(i instanceof CSSMediaRule)for(let e=0;e<i.cssRules.length;e++){const t=i.cssRules[e];t instanceof CSSStyleRule&&this.extractStyleRule(t,"stylesheet")}}}catch(e){}}extractStyleRule(e,t){const i=e.selectorText,s=new Map;for(let t=0;t<e.style.length;t++){const i=e.style[t],n=e.style.getPropertyValue(i);s.set(i,n)}const n={selector:i,declarations:s,specificity:this.calculateSpecificity(i),source:t,used:!1,critical:!1};this.styleRules.set(i,n)}extractInlineStyles(){document.querySelectorAll("[style]").forEach(e=>{const t=e.style,i=new Map;for(let e=0;e<t.length;e++){const s=t[e];if(s){const e=t.getPropertyValue(s);i.set(s,e)}}if(i.size>0){const t=this.generateSelectorForElement(e),s={selector:t,declarations:i,specificity:1e3,source:"inline",used:!0,critical:this.isElementInViewport(e)};this.styleRules.set(t,s)}})}calculateSpecificity(e){let t=0;return t+=100*(e.match(/#/g)||[]).length,t+=10*(e.match(/\.|:|\[/g)||[]).length,t+=(e.match(/[a-zA-Z]/g)||[]).length,t}getElementsInViewport(e){const t=[];return document.querySelectorAll("*").forEach(i=>{this.isElementInViewport(i,e)&&t.push(i)}),t}isElementInViewport(e,t){const i=e.getBoundingClientRect(),s=t||window.innerHeight;return i.top<s&&i.bottom>0}getSelectorsForElement(e){const t=[];return this.styleRules.forEach((i,s)=>{try{e.matches(s)&&(t.push(s),i.used=!0)}catch(e){}}),t}generateSelectorForElement(e){if(e.id)return`#${e.id}`;if(e.className){const t=e.className.split(" ").filter(e=>e.trim());if(t.length>0)return`.${t.join(".")}`}return e.tagName.toLowerCase()}rulesToCSS(e){let t="";return e.forEach(e=>{t+=`${e.selector} {\n`,e.declarations.forEach((e,i)=>{t+=` ${i}: ${e};\n`}),t+="}\n\n"}),this.config.minification&&(t=this.minifyCSS(t)),t}minifyCSS(e){return e.replace(/\s+/g," ").replace(/;\s*}/g,"}").replace(/{\s*/g,"{").replace(/}\s*/g,"}").replace(/:\s*/g,":").replace(/;\s*/g,";").trim()}serializeDeclarations(e){const t=Array.from(e.entries()).sort();return JSON.stringify(t)}findCustomPropertyUsage(e){const t=[];return this.styleRules.forEach(i=>{i.declarations.forEach(s=>{s.includes(`var(${e})`)&&t.push(i)})}),t}findPropertyUsingCustomProperty(e,t){for(const[i,s]of e.declarations)if(s.includes(`var(${t})`))return i;return null}handleStyleInvalidation(e){this.getSelectorsForElement(e).forEach(e=>{const t=this.usageTracker.get(e)||0;this.usageTracker.set(e,t+1)})}calculateCurrentCSSSize(){let e=0;for(const t of document.styleSheets)try{const i=t.cssRules;for(let t=0;t<i.length;t++)e+=i[t].cssText.length}catch(e){}return e}updateMetrics(e){this.metrics.optimizedSize=e.length,this.metrics.compressionRatio=this.metrics.originalSize>0?(this.metrics.originalSize-this.metrics.optimizedSize)/this.metrics.originalSize:0}setupStyleTracking(){this.config.styleInvalidationTracking&&setTimeout(()=>{this.trackStyleInvalidations()},100)}createInitialMetrics(){return{originalSize:0,optimizedSize:0,compressionRatio:0,rulesRemoved:0,duplicatesFound:0,customPropertiesOptimized:0,criticalRulesExtracted:0}}}class B{constructor(e={}){this.resources=new Map,this.cleanupTimer=null,this.performanceObserver=null,this.weakRefs=new Set,this.config={autoCleanup:!0,cleanupInterval:3e4,memoryThreshold:52428800,gcOptimization:!0,leakDetection:!0,performanceMonitoring:!0,...e},this.metrics=this.createInitialMetrics(),this.setupMemoryMonitoring(),this.startAutoCleanup()}register(e,t,i,s=1024){const n=this.generateResourceId(),r={id:n,type:e,...i&&{element:i},cleanup:t,timestamp:performance.now(),lastAccessed:performance.now(),memorySize:s};return this.resources.set(n,r),this.updateMetrics(e,"register"),i&&this.config.leakDetection&&this.weakRefs.add(new WeakRef(i)),n}unregister(e){const t=this.resources.get(e);if(t){try{t.cleanup(),this.updateMetrics(t.type,"unregister")}catch(e){}this.resources.delete(e),this.metrics.cleanupOperations++}}registerResizeObserver(e,t){return this.register("observer",()=>{e.disconnect()},t[0],512*t.length)}registerIntersectionObserver(e,t){return this.register("observer",()=>{e.disconnect()},t[0],256*t.length)}registerEventListener(e,t,i,s){return this.register("listener",()=>{e.removeEventListener(t,i,s)},e,128)}registerTimer(e,t="timeout"){return this.register("timer",()=>{"timeout"===t?clearTimeout(e):clearInterval(e)},void 0,64)}registerAnimation(e){return this.register("animation",()=>{e.cancel()},e.effect?.target instanceof Element?e.effect.target:void 0,256)}registerCacheEntry(e,t,i=1024){return this.register("cache",()=>{e.delete(t)},void 0,i)}cleanup(){Array.from(this.resources.keys()).forEach(e=>this.unregister(e))}cleanupByType(e){Array.from(this.resources.entries()).filter(([,t])=>t.type===e).map(([e])=>e).forEach(e=>this.unregister(e))}cleanupStale(e=3e5){const t=performance.now();Array.from(this.resources.entries()).filter(([,i])=>t-i.lastAccessed>e).map(([e])=>e).forEach(e=>this.unregister(e))}cleanupOrphanedResources(){const e=[];this.resources.forEach((t,i)=>{t.element&&!document.contains(t.element)&&e.push(i)}),e.forEach(e=>this.unregister(e))}getMetrics(){return this.updateMemoryUsage(),{...this.metrics}}getResourceCount(e){return e?Array.from(this.resources.values()).filter(t=>t.type===e).length:this.resources.size}detectLeaks(){const e=[];this.weakRefs.forEach(e=>{void 0===e.deref()&&this.cleanupOrphanedResources()});const t=new Map;return this.resources.forEach(e=>{const i=t.get(e.type)||0;t.set(e.type,i+1)}),t.forEach((t,i)=>{const s=this.getThresholdForType(i);t>s&&e.push(`Excessive ${i} resources: ${t} (threshold: ${s})`)}),this.metrics.leaksDetected=e.length,e}optimizeGC(){if(!this.config.gcOptimization)return;this.cleanupStale();const e=new Set;this.weakRefs.forEach(t=>{void 0!==t.deref()&&e.add(t)}),this.weakRefs=e,"gc"in window&&"function"==typeof window.gc&&(window.gc(),this.metrics.gcCollections++)}destroy(){this.stopAutoCleanup(),this.stopMemoryMonitoring(),this.cleanup(),this.weakRefs.clear()}setupMemoryMonitoring(){if(this.config.performanceMonitoring&&("memory"in performance&&setInterval(()=>{this.updateMemoryUsage(),this.checkMemoryThreshold()},5e3),window.PerformanceObserver))try{this.performanceObserver=new PerformanceObserver(e=>{e.getEntries().forEach(e=>{"measure"===e.entryType&&e.name.includes("proteus")})}),this.performanceObserver.observe({entryTypes:["measure","navigation"]})}catch(e){}}startAutoCleanup(){this.config.autoCleanup&&(this.cleanupTimer=window.setInterval(()=>{this.cleanupStale(),this.cleanupOrphanedResources(),this.detectLeaks(),this.config.gcOptimization&&this.optimizeGC()},this.config.cleanupInterval))}stopAutoCleanup(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null)}stopMemoryMonitoring(){this.performanceObserver&&(this.performanceObserver.disconnect(),this.performanceObserver=null)}updateMemoryUsage(){if("memory"in performance){const e=performance.memory;this.metrics.memoryUsage=e.usedJSHeapSize||0}}checkMemoryThreshold(){this.metrics.memoryUsage>this.config.memoryThreshold&&(this.cleanupStale(6e4),this.optimizeGC())}updateMetrics(e,t){switch(e){case"observer":"register"===t?(this.metrics.totalObservers++,this.metrics.activeObservers++):this.metrics.activeObservers--;break;case"listener":"register"===t?(this.metrics.totalEventListeners++,this.metrics.activeEventListeners++):this.metrics.activeEventListeners--}}getThresholdForType(e){return{observer:100,listener:500,timer:50,animation:20,cache:1e3}[e]||100}generateResourceId(){return`mem-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}createInitialMetrics(){return{totalObservers:0,activeObservers:0,totalEventListeners:0,activeEventListeners:0,memoryUsage:0,gcCollections:0,leaksDetected:0,cleanupOperations:0}}}class D{constructor(e={}){this.cache=new Map,this.accessOrder=[],this.cleanupTimer=null,this.config={maxSize:100,maxAge:3e5,memoryThreshold:10485760,evictionStrategy:"adaptive",compressionEnabled:!0,persistentStorage:!1,storageKey:"proteus-cache",...e},this.metrics=this.createInitialMetrics(),this.loadFromStorage(),this.startCleanupTimer()}get(e){const t=this.cache.get(e);if(!t)return this.metrics.missRate++,null;if(t.ttl&&Date.now()>t.timestamp+t.ttl)return this.delete(e),this.metrics.missRate++,null;t.lastAccessed=Date.now(),t.accessCount++,this.updateAccessOrder(e),this.metrics.hitRate++;let i=t.value;return t.compressed&&this.config.compressionEnabled&&(i=this.decompress(i)),i}set(e,t,i){this.cache.size>=this.config.maxSize&&this.evictEntries(1);let s=t,n=!1;this.config.compressionEnabled&&this.shouldCompress(t)&&(s=this.compress(t),n=!0);const r=this.calculateSize(s),o={key:e,value:s,timestamp:Date.now(),lastAccessed:Date.now(),accessCount:1,size:r,...void 0!==i&&{ttl:i},compressed:n};this.cache.has(e)&&this.delete(e),this.cache.set(e,o),this.updateAccessOrder(e),this.updateMetrics(),this.checkMemoryPressure()}delete(e){const t=this.cache.delete(e);return t&&(this.removeFromAccessOrder(e),this.updateMetrics()),t}has(e){const t=this.cache.get(e);return!!t&&(!(t.ttl&&Date.now()>t.timestamp+t.ttl)||(this.delete(e),!1))}clear(){this.cache.clear(),this.accessOrder=[],this.updateMetrics()}getMetrics(){return{...this.metrics}}cacheCalculation(e,t,i){const s=this.generateKey("calc",t);let n=this.get(s);return null===n&&(n=e(),this.set(s,n,i)),n}cacheLayoutMeasurement(e,t,i=1e3){const s=this.generateKey("layout",[e.tagName,e.className,e.id||"no-id"]);let n=this.get(s);return null===n&&(n=t(),this.set(s,n,i)),n}cacheContainerState(e,t,i=5e3){const s=this.generateKey("container",[e]);this.set(s,t,i)}getCachedContainerState(e){const t=this.generateKey("container",[e]);return this.get(t)}cacheComputedStyles(e,t,i=2e3){const s=this.generateKey("styles",[e.tagName,e.className,t.join(",")]);let n=this.get(s);if(null===n){n=window.getComputedStyle(e);const r={};return t.forEach(e=>{r[e]=n.getPropertyValue(e)}),this.set(s,r,i),r}return n}optimize(){this.removeExpiredEntries(),this.checkMemoryPressure(),this.compressLargeEntries(),this.updateMetrics()}destroy(){this.stopCleanupTimer(),this.saveToStorage(),this.clear()}evictEntries(e){let t=[];switch(this.config.evictionStrategy){case"lru":t=this.getLRUKeys(e);break;case"lfu":t=this.getLFUKeys(e);break;case"ttl":t=this.getTTLKeys(e);break;case"adaptive":t=this.getAdaptiveKeys(e)}t.forEach(e=>{this.delete(e),this.metrics.evictions++})}getLRUKeys(e){return this.accessOrder.slice(0,e)}getLFUKeys(e){const t=Array.from(this.cache.entries());return t.sort((e,t)=>e[1].accessCount-t[1].accessCount),t.slice(0,e).map(([e])=>e)}getTTLKeys(e){const t=Array.from(this.cache.entries());return t.sort((e,t)=>e[1].timestamp-t[1].timestamp),t.slice(0,e).map(([e])=>e)}getAdaptiveKeys(e){const t=Array.from(this.cache.entries());return t.forEach(([e,t])=>{const i=Date.now()-t.lastAccessed,s=t.accessCount,n=t.size;t.score=i/1e3+n/1024-10*s}),t.sort((e,t)=>t[1].score-e[1].score),t.slice(0,e).map(([e])=>e)}checkMemoryPressure(){if(this.getTotalSize()>this.config.memoryThreshold){const e=Math.ceil(.2*this.cache.size);this.evictEntries(e)}}removeExpiredEntries(){const e=Date.now(),t=[];this.cache.forEach((i,s)=>{(i.ttl?e>i.timestamp+i.ttl:e>i.timestamp+this.config.maxAge)&&t.push(s)}),t.forEach(e=>this.delete(e))}compressLargeEntries(){this.config.compressionEnabled&&this.cache.forEach((e,t)=>{if(!e.compressed&&e.size>1024){const t=this.compress(e.value),i=this.calculateSize(t);i<.8*e.size&&(e.value=t,e.size=i,e.compressed=!0)}})}updateAccessOrder(e){this.removeFromAccessOrder(e),this.accessOrder.push(e)}removeFromAccessOrder(e){const t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1)}generateKey(e,t){return`${e}:${t.join(":")}`}calculateSize(e){if("string"==typeof e)return 2*e.length;try{return 2*JSON.stringify(e).length}catch{return 1024}}getTotalSize(){let e=0;return this.cache.forEach(t=>{e+=t.size}),e}shouldCompress(e){return this.calculateSize(e)>512}compress(e){return{__compressed:!0,data:JSON.stringify(e)}}decompress(e){return e&&e.__compressed?JSON.parse(e.data):e}updateMetrics(){this.metrics.totalEntries=this.cache.size,this.metrics.totalSize=this.getTotalSize();const e=this.metrics.hitRate+this.metrics.missRate;e>0&&(this.metrics.hitRate=this.metrics.hitRate/e,this.metrics.missRate=this.metrics.missRate/e);let t=0,i=0,s=0;this.cache.forEach(e=>{e.compressed&&(s++,i+=e.size,t+=e.size/.5)}),s>0&&t>0&&(this.metrics.compressionRatio=i/t)}startCleanupTimer(){this.cleanupTimer=window.setInterval(()=>{this.optimize()},3e4)}stopCleanupTimer(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null)}loadFromStorage(){if(this.config.persistentStorage)try{const e=localStorage.getItem(this.config.storageKey);if(e){JSON.parse(e).forEach(e=>{this.cache.set(e.key,e),this.accessOrder.push(e.key)})}}catch(e){}}saveToStorage(){if(this.config.persistentStorage)try{const e=Array.from(this.cache.values());localStorage.setItem(this.config.storageKey,JSON.stringify(e))}catch(e){}}createInitialMetrics(){return{totalEntries:0,totalSize:0,hitRate:0,missRate:0,evictions:0,compressionRatio:0}}}class q{constructor(e={}){this.mediaQueries=new Map,this.observers=new Set,this.handleMediaQueryChange=()=>{this.updateStateFromMediaQueries(),this.config.respectSystemPreference&&!this.state.userPreference&&(this.state.currentScheme=this.state.systemPreference,this.applyTheme()),this.notifyObservers()},this.config={autoDetect:!0,respectSystemPreference:!0,adaptiveContrast:!0,colorSchemes:q.DEFAULT_SCHEMES,transitions:!0,transitionDuration:300,storage:"localStorage",storageKey:"proteus-theme",...e},this.state=this.createInitialState(),this.setupMediaQueries(),this.loadStoredPreference(),this.applyInitialTheme()}setScheme(e){this.config.colorSchemes[e]&&(this.state.currentScheme=e,this.state.userPreference=e,this.applyTheme(),this.savePreference(),this.notifyObservers())}toggle(){const e=this.config.colorSchemes[this.state.currentScheme];e&&"light"===e.type?this.setScheme("dark"):this.setScheme("light")}setContrast(e){this.state.contrastLevel=e,"high"===e&&this.config.colorSchemes.highContrast?this.setScheme("highContrast"):this.applyContrastAdjustments(),this.notifyObservers()}getState(){return{...this.state}}getCurrentScheme(){const e=this.config.colorSchemes[this.state.currentScheme];if(!e)throw new Error(`Color scheme '${this.state.currentScheme}' not found`);return e}observe(e){return this.observers.add(e),()=>{this.observers.delete(e)}}addScheme(e){this.config.colorSchemes[e.name.toLowerCase()]=e}removeScheme(e){e!==this.state.currentScheme&&delete this.config.colorSchemes[e]}getAvailableSchemes(){return Object.values(this.config.colorSchemes)}applyTheme(){const e=this.getCurrentScheme();this.applyCSSProperties(e),this.applyThemeClass(e),this.config.transitions&&this.applyTransitions(),this.applyAccessibilityEnhancements(e)}resetToSystem(){this.state.userPreference=null,this.state.currentScheme=this.state.systemPreference,this.applyTheme(),this.savePreference(),this.notifyObservers()}destroy(){this.mediaQueries.forEach(e=>{e.removeEventListener("change",this.handleMediaQueryChange)}),this.mediaQueries.clear(),this.observers.clear()}setupMediaQueries(){if("undefined"==typeof window||"function"!=typeof window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)");this.mediaQueries.set("dark-mode",e),e.addEventListener("change",this.handleMediaQueryChange.bind(this));const t=window.matchMedia("(prefers-contrast: high)");this.mediaQueries.set("high-contrast",t),t.addEventListener("change",this.handleMediaQueryChange.bind(this));const i=window.matchMedia("(prefers-reduced-motion: reduce)");this.mediaQueries.set("reduced-motion",i),i.addEventListener("change",this.handleMediaQueryChange.bind(this)),this.updateStateFromMediaQueries()}updateStateFromMediaQueries(){const e=this.mediaQueries.get("dark-mode"),t=this.mediaQueries.get("high-contrast"),i=this.mediaQueries.get("reduced-motion");this.state.systemPreference=e?.matches?"dark":"light",this.state.highContrast=t?.matches||!1,this.state.reducedMotion=i?.matches||!1,this.state.highContrast&&this.config.adaptiveContrast&&(this.state.contrastLevel="high")}applyCSSProperties(e){try{const i=document.documentElement;if(!i||!i.style||"function"!=typeof i.style.setProperty)return void t.warn("CSS custom properties not supported in this environment");Object.entries(e.colors).forEach(([e,t])=>{i.style.setProperty(`--proteus-${e}`,t)}),i.style.setProperty("--proteus-min-contrast",e.accessibility.minContrast.toString()),i.style.setProperty("--proteus-focus-indicator",e.accessibility.focusIndicator)}catch(e){t.warn("Failed to apply CSS custom properties:",e)}}applyThemeClass(e){const t=document.body;t.classList.remove("proteus-light","proteus-dark","proteus-high-contrast"),t.classList.add(`proteus-${e.type}`),"high"===e.contrast&&t.classList.add("proteus-high-contrast"),this.state.reducedMotion?t.classList.add("proteus-reduced-motion"):t.classList.remove("proteus-reduced-motion")}applyTransitions(){if(this.state.reducedMotion)return;const e=document.createElement("style");e.id="proteus-theme-transitions";const t=document.getElementById("proteus-theme-transitions");t&&t.remove(),e.textContent=`\n * {\n transition: \n background-color ${this.config.transitionDuration}ms ease,\n color ${this.config.transitionDuration}ms ease,\n border-color ${this.config.transitionDuration}ms ease,\n box-shadow ${this.config.transitionDuration}ms ease !important;\n }\n `,document.head.appendChild(e),setTimeout(()=>{e.remove()},this.config.transitionDuration+100)}applyAccessibilityEnhancements(e){const t=document.createElement("style");t.id="proteus-accessibility-enhancements";const i=document.getElementById("proteus-accessibility-enhancements");i&&i.remove(),t.textContent=`\n :focus {\n outline: 2px solid var(--proteus-focus-indicator) !important;\n outline-offset: 2px !important;\n }\n \n .proteus-high-contrast {\n filter: contrast(${"high"===e.contrast?"150%":"100%"});\n }\n \n .proteus-reduced-motion * {\n animation-duration: 0.01ms !important;\n animation-iteration-count: 1 !important;\n transition-duration: 0.01ms !important;\n }\n `,document.head.appendChild(t)}applyContrastAdjustments(){const e=this.getCurrentScheme(),t={...e};"high"===this.state.contrastLevel?t.colors=this.adjustColorsForHighContrast(e.colors):"low"===this.state.contrastLevel&&(t.colors=this.adjustColorsForLowContrast(e.colors)),this.applyCSSProperties(t)}adjustColorsForHighContrast(e){const t={...e};return"#ffffff"===e.background?(t.text="#000000",t.textSecondary="#333333"):(t.text="#ffffff",t.textSecondary="#cccccc"),t}adjustColorsForLowContrast(e){const t={...e};return"#ffffff"===e.background?(t.text="#444444",t.textSecondary="#666666"):(t.text="#dddddd",t.textSecondary="#aaaaaa"),t}loadStoredPreference(){if("none"!==this.config.storage)try{const e=("localStorage"===this.config.storage?localStorage:sessionStorage).getItem(this.config.storageKey);if(e){const t=JSON.parse(e);this.state.userPreference=t.scheme,this.state.contrastLevel=t.contrast||"normal"}}catch(e){}}savePreference(){if("none"!==this.config.storage)try{const e="localStorage"===this.config.storage?localStorage:sessionStorage,t={scheme:this.state.userPreference,contrast:this.state.contrastLevel};e.setItem(this.config.storageKey,JSON.stringify(t))}catch(e){}}applyInitialTheme(){this.state.userPreference&&this.config.colorSchemes[this.state.userPreference]?this.state.currentScheme=this.state.userPreference:this.config.autoDetect?this.state.currentScheme=this.state.systemPreference:this.state.currentScheme="light",this.applyTheme()}notifyObservers(){this.observers.forEach(e=>{try{e(this.state)}catch(e){}})}createInitialState(){return{currentScheme:"light",systemPreference:"light",userPreference:null,contrastLevel:"normal",reducedMotion:!1,highContrast:!1}}}q.DEFAULT_SCHEMES={light:{name:"Light",type:"light",colors:{primary:"#007bff",secondary:"#6c757d",success:"#28a745",danger:"#dc3545",warning:"#ffc107",info:"#17a2b8",background:"#ffffff",surface:"#f8f9fa",text:"#212529",textSecondary:"#6c757d",border:"#dee2e6"},contrast:"normal",accessibility:{minContrast:4.5,largeTextContrast:3,focusIndicator:"#005cbf"}},dark:{name:"Dark",type:"dark",colors:{primary:"#0d6efd",secondary:"#6c757d",success:"#198754",danger:"#dc3545",warning:"#fd7e14",info:"#0dcaf0",background:"#121212",surface:"#1e1e1e",text:"#ffffff",textSecondary:"#adb5bd",border:"#495057"},contrast:"normal",accessibility:{minContrast:4.5,largeTextContrast:3,focusIndicator:"#4dabf7"}},highContrast:{name:"High Contrast",type:"light",colors:{primary:"#0000ff",secondary:"#000000",success:"#008000",danger:"#ff0000",warning:"#ff8c00",info:"#0000ff",background:"#ffffff",surface:"#ffffff",text:"#000000",textSecondary:"#000000",border:"#000000"},contrast:"high",accessibility:{minContrast:7,largeTextContrast:4.5,focusIndicator:"#ff0000"}}};class N{constructor(e={}){this.activeAnimations=new Map,this.animationQueue=[],this.isProcessing=!1,this.config={duration:300,easing:"cubic-bezier(0.4, 0.0, 0.2, 1)",respectMotionPreference:!0,batchAnimations:!0,performanceMode:"auto",maxConcurrentAnimations:10,...e}}async animate(e,t,i={}){const s={...this.config,...i};if(this.shouldSkipAnimation())return void t();const n=e.getBoundingClientRect();t();const r=e.getBoundingClientRect(),o=this.calculateInvert(n,r);return 0!==o.x||0!==o.y||1!==o.scaleX||1!==o.scaleY?this.playAnimation(e,o,s):void 0}async animateBatch(e){if(!this.config.batchAnimations){for(const t of e)await this.animate(t.element,t.newPosition,t.options);return}const t=e.map(e=>({element:e.element,first:e.element.getBoundingClientRect(),newPosition:e.newPosition,options:e.options||{}}));t.forEach(e=>e.newPosition());const i=t.map(e=>{const t=e.element.getBoundingClientRect(),i=this.calculateInvert(e.first,t);if(0===i.x&&0===i.y&&1===i.scaleX&&1===i.scaleY)return Promise.resolve();const s={...this.config,...e.options};return this.playAnimation(e.element,i,s)});await Promise.all(i)}cancel(e){const t=this.activeAnimations.get(e);t?.player&&(t.player.cancel(),this.activeAnimations.delete(e))}cancelAll(){this.activeAnimations.forEach((e,t)=>{this.cancel(t)})}getActiveCount(){return this.activeAnimations.size}isAnimating(e){return this.activeAnimations.has(e)}destroy(){this.cancelAll(),this.animationQueue=[]}calculateInvert(e,t){return{x:e.left-t.left,y:e.top-t.top,scaleX:e.width/t.width,scaleY:e.height/t.height}}async playAnimation(e,t,i){return new Promise((s,n)=>{const r=e,o=`translate(${t.x}px, ${t.y}px) scale(${t.scaleX}, ${t.scaleY})`;r.style.transform=o;const a=r.animate([{transform:o},{transform:"translate(0, 0) scale(1, 1)"}],{duration:i.duration,easing:i.easing,fill:"forwards"}),c={element:e,first:{x:0,y:0,width:0,height:0},last:{x:0,y:0,width:0,height:0},invert:t,player:a};this.activeAnimations.set(e,c),a.addEventListener("finish",()=>{r.style.transform="",this.activeAnimations.delete(e),s()}),a.addEventListener("cancel",()=>{r.style.transform="",this.activeAnimations.delete(e),n(new Error("Animation cancelled"))})})}shouldSkipAnimation(){if(this.config.respectMotionPreference){if(window.matchMedia("(prefers-reduced-motion: reduce)").matches)return!0}return"performance"===this.config.performanceMode&&this.activeAnimations.size>=this.config.maxConcurrentAnimations}}class U{static addHover(e,t={}){const i={...U.INTERACTIONS.hover,...t},s=e;s.addEventListener("mouseenter",()=>{s.style.transition=`transform ${i.duration}ms ${i.easing}`,s.style.transform=`scale(${i.scale})`}),s.addEventListener("mouseleave",()=>{s.style.transform="scale(1)"})}static addPress(e,t={}){const i={...U.INTERACTIONS.press,...t},s=e;s.addEventListener("mousedown",()=>{s.style.transition=`transform ${i.duration}ms ${i.easing}`,s.style.transform=`scale(${i.scale})`}),s.addEventListener("mouseup",()=>{s.style.transform="scale(1)"}),s.addEventListener("mouseleave",()=>{s.style.transform="scale(1)"})}static addFocus(e,t={}){const i={...U.INTERACTIONS.focus,...t},s=e;s.addEventListener("focus",()=>{s.style.transition=`transform ${i.duration}ms ${i.easing}`,s.style.transform=`scale(${i.scale})`}),s.addEventListener("blur",()=>{s.style.transform="scale(1)"})}static addRipple(e,t="rgba(255, 255, 255, 0.3)"){const i=e;i.style.position="relative",i.style.overflow="hidden",i.addEventListener("click",e=>{const s=i.getBoundingClientRect(),n=Math.max(s.width,s.height),r=e.clientX-s.left-n/2,o=e.clientY-s.top-n/2,a=document.createElement("div");if(a.style.cssText=`\n position: absolute;\n width: ${n}px;\n height: ${n}px;\n left: ${r}px;\n top: ${o}px;\n background: ${t};\n border-radius: 50%;\n transform: scale(0);\n animation: ripple 600ms ease-out;\n pointer-events: none;\n `,!document.getElementById("ripple-animation")){const e=document.createElement("style");e.id="ripple-animation",e.textContent="\n @keyframes ripple {\n to {\n transform: scale(4);\n opacity: 0;\n }\n }\n ",document.head.appendChild(e)}i.appendChild(a),setTimeout(()=>{a.remove()},600)})}}U.INTERACTIONS={hover:{scale:1.05,duration:200,easing:"ease-out"},press:{scale:.95,duration:100,easing:"ease-in"},focus:{scale:1.02,duration:150,easing:"ease-out"}};class H{constructor(){this.observer=null,this.animations=new Map,this.setupIntersectionObserver()}addAnimation(e,t,i={}){this.animations.set(e,t),this.observer&&this.observer.observe(e)}removeAnimation(e){this.animations.delete(e),this.observer&&this.observer.unobserve(e)}destroy(){this.observer?.disconnect(),this.animations.clear()}setupIntersectionObserver(){window.IntersectionObserver&&(this.observer=new IntersectionObserver(e=>{e.forEach(e=>{if(e.isIntersecting){const t=this.animations.get(e.target);t&&(t(),this.removeAnimation(e.target))}})},{threshold:.1,rootMargin:"50px"}))}static fadeIn(e,t=600){const i=e;i.style.opacity="0",i.style.transition=`opacity ${t}ms ease-in-out`,requestAnimationFrame(()=>{i.style.opacity="1"})}static slideUp(e,t=600){const i=e;i.style.transform="translateY(50px)",i.style.opacity="0",i.style.transition=`transform ${t}ms ease-out, opacity ${t}ms ease-out`,requestAnimationFrame(()=>{i.style.transform="translateY(0)",i.style.opacity="1"})}static scaleIn(e,t=600){const i=e;i.style.transform="scale(0.8)",i.style.opacity="0",i.style.transition=`transform ${t}ms ease-out, opacity ${t}ms ease-out`,requestAnimationFrame(()=>{i.style.transform="scale(1)",i.style.opacity="1"})}}class j{constructor(e={}){this.detectedContainers=new Map,this.observer=null,this.config={autoDetectContainers:!0,intelligentBreakpoints:!0,autoTypographyScaling:!0,performanceOptimization:!0,accessibilityOptimization:!0,autoThemeDetection:!0,responsiveImages:!0,lazyLoading:!0,...e},this.appliedOptimizations={performance:[],accessibility:[],typography:[],layout:[]}}async initialize(){this.config.autoDetectContainers&&await this.detectContainers(),this.config.intelligentBreakpoints&&await this.setupIntelligentBreakpoints(),this.config.autoTypographyScaling&&await this.setupTypographyScaling(),this.config.performanceOptimization&&await this.applyPerformanceOptimizations(),this.config.accessibilityOptimization&&await this.applyAccessibilityOptimizations(),this.config.autoThemeDetection&&await this.setupAutoTheme(),this.config.responsiveImages&&await this.optimizeImages(),this.setupContinuousOptimization(),this.logOptimizations()}async detectContainers(){const e=document.querySelectorAll("*"),t=[];e.forEach(e=>{const i=this.analyzeElement(e);i&&(t.push(i),this.detectedContainers.set(e,i))}),t.sort((e,t)=>{const i={high:3,normal:2,low:1},s=i[t.priority]-i[e.priority];return 0!==s?s:t.confidence-e.confidence})}analyzeElement(e){const t=window.getComputedStyle(e),i=e.children.length,s=e.getBoundingClientRect();if(s.width<100||s.height<50||0===i)return null;let n="block",r=0,o="normal";return"grid"===t.display?(n="grid",r+=.4):"flex"===t.display?(n="flex",r+=.3):"inline-block"!==t.display&&"inline-flex"!==t.display||(n="inline",r+=.2),i>=3&&(r+=.2),s.width>300&&(r+=.1),e.classList.length>0&&(r+=.1),e.id&&(r+=.1),e.matches("main, .main, #main, .container, .wrapper")?(o="high",r+=.2):e.matches("section, article, aside, nav, header, footer")&&(o="normal",r+=.1),r<.3?null:{element:e,type:n,suggestedBreakpoints:this.generateBreakpoints(s.width),priority:o,confidence:r}}generateBreakpoints(e){const t={},i=["xs","sm","md","lg","xl"];return[.618,.8,1,1.2,1.618].forEach((s,n)=>{const r=Math.round(e*s);if(r>=200&&r<=1920){const e=i[n];e&&(t[e]=`${r}px`)}}),t}async setupIntelligentBreakpoints(){this.detectedContainers.forEach((e,t)=>{const i=this.generateClassName(t);t.classList.add(i),this.generateBreakpointCSS(i,e.suggestedBreakpoints)}),this.appliedOptimizations.layout.push("Intelligent breakpoints applied")}async setupTypographyScaling(){document.querySelectorAll("h1, h2, h3, h4, h5, h6, p, span, div").forEach(e=>{const t=this.findParentContainer(e);t&&this.applyFluidTypography(e,t)}),this.appliedOptimizations.typography.push("Fluid typography scaling applied")}async applyPerformanceOptimizations(){this.enablePassiveListeners(),this.config.responsiveImages&&this.optimizeImages(),this.config.lazyLoading&&this.enableLazyLoading(),this.appliedOptimizations.performance.push("Passive event listeners","Image optimization","Lazy loading")}async applyAccessibilityOptimizations(){this.addMissingAriaLabels(),this.improveFocusIndicators(),this.validateHeadingHierarchy(),this.addSkipLinks(),this.appliedOptimizations.accessibility.push("ARIA labels added","Focus indicators improved","Heading hierarchy validated","Skip links added")}async setupAutoTheme(){const e=window.matchMedia("(prefers-color-scheme: dark)").matches,t=window.matchMedia("(prefers-contrast: high)").matches;e&&document.body.classList.add("proteus-dark"),t&&document.body.classList.add("proteus-high-contrast"),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",e=>{document.body.classList.toggle("proteus-dark",e.matches)})}async optimizeImages(){document.querySelectorAll("img").forEach(e=>{if(e.hasAttribute("loading")||e.setAttribute("loading","lazy"),e.hasAttribute("decoding")||e.setAttribute("decoding","async"),!e.hasAttribute("sizes")&&!e.hasAttribute("srcset")){const t=this.findParentContainer(e);t&&this.addResponsiveImageAttributes(e,t)}})}enableLazyLoading(){return new Promise(e=>{if("IntersectionObserver"in window){const e=new IntersectionObserver(t=>{t.forEach(t=>{if(t.isIntersecting){const i=t.target;i.classList.add("proteus-loaded"),e.unobserve(i)}})});document.querySelectorAll("img, video, iframe").forEach(t=>{e.observe(t)})}e()})}setupContinuousOptimization(){this.observer=new MutationObserver(e=>{e.forEach(e=>{"childList"===e.type&&e.addedNodes.forEach(e=>{e.nodeType===Node.ELEMENT_NODE&&this.optimizeNewElement(e)})})}),this.observer.observe(document.body,{childList:!0,subtree:!0})}optimizeNewElement(e){const t=this.analyzeElement(e);if(t&&(this.detectedContainers.set(e,t),this.config.intelligentBreakpoints)){const i=this.generateClassName(e);e.classList.add(i),this.generateBreakpointCSS(i,t.suggestedBreakpoints)}if(this.config.responsiveImages){e.querySelectorAll("img").forEach(e=>this.optimizeImages())}this.config.accessibilityOptimization&&this.addMissingAriaLabels(e)}generateClassName(e){const t=e.id||"",i=Array.from(e.classList).join("-");return`proteus-${e.tagName.toLowerCase()}-${t||i||Math.random().toString(36).substring(2,11)}`}generateBreakpointCSS(e,t){let i="";Object.entries(t).forEach(([t,s])=>{i+=`\n .${e} {\n container-type: inline-size;\n }\n @container (min-width: ${s}) {\n .${e} {\n --proteus-breakpoint: ${t};\n }\n }\n `});const s=document.createElement("style");s.textContent=i,document.head.appendChild(s)}findParentContainer(e){let t=e.parentElement;for(;t;){const e=this.detectedContainers.get(t);if(e)return e;t=t.parentElement}return null}applyFluidTypography(e,t){const i=e,s=parseFloat(window.getComputedStyle(e).fontSize),n=Math.max(.8*s,12),r=1.5*s;i.style.fontSize=`clamp(${n}px, 4cw, ${r}px)`}enablePassiveListeners(){const e=EventTarget.prototype.addEventListener;EventTarget.prototype.addEventListener=function(t,i,s){return["scroll","wheel","touchstart","touchmove"].includes(t)&&"object"!=typeof s&&(s={passive:!0}),e.call(this,t,i,s)}}addMissingAriaLabels(e=document.body){e.querySelectorAll("button:not([aria-label]):not([aria-labelledby])").forEach(e=>{e.textContent?.trim()||e.setAttribute("aria-label","Button")});e.querySelectorAll("input:not([aria-label]):not([aria-labelledby])").forEach(e=>{const t=e.getAttribute("type")||"text";e.setAttribute("aria-label",`${t} input`)})}improveFocusIndicators(){const e=document.createElement("style");e.textContent="\n *:focus {\n outline: 2px solid #4A90E2 !important;\n outline-offset: 2px !important;\n }\n .proteus-focus-visible:focus-visible {\n outline: 3px solid #4A90E2 !important;\n outline-offset: 2px !important;\n }\n ",document.head.appendChild(e)}validateHeadingHierarchy(){const e=document.querySelectorAll("h1, h2, h3, h4, h5, h6");let t=0;e.forEach(e=>{const i=parseInt(e.tagName.charAt(1));t=i})}addSkipLinks(){if(document.querySelector('main, [role="main"], #main')&&!document.querySelector(".proteus-skip-link")){const e=document.createElement("a");e.href="#main",e.textContent="Skip to main content",e.className="proteus-skip-link",e.style.cssText="\n position: absolute;\n top: -40px;\n left: 6px;\n background: #000;\n color: #fff;\n padding: 8px;\n text-decoration: none;\n z-index: 1000;\n ",e.addEventListener("focus",()=>{e.style.top="6px"}),e.addEventListener("blur",()=>{e.style.top="-40px"}),document.body.insertBefore(e,document.body.firstChild)}}addResponsiveImageAttributes(e,t){const i=Object.values(t.suggestedBreakpoints),s=i.map((e,t)=>{const s=parseInt(e);return t===i.length-1?`${s}px`:`(max-width: ${s}px) ${s}px`}).join(", ");e.setAttribute("sizes",s)}logOptimizations(){Object.entries(this.appliedOptimizations).forEach(([e,t])=>{t.length>0&&t.forEach(e=>{})})}getOptimizationReport(){return{containers:this.detectedContainers.size,optimizations:this.appliedOptimizations,detectedContainers:Array.from(this.detectedContainers.values())}}destroy(){this.observer?.disconnect(),this.detectedContainers.clear()}}class _{constructor(){this.polyfillsLoaded=new Set}static getInstance(){return _.instance||(_.instance=new _),_.instance}async loadPolyfills(e={}){const i={resizeObserver:!0,intersectionObserver:!0,customProperties:!0,cssSupports:!0,requestAnimationFrame:!0,performance:!0,classList:!0,closest:!0,matchMedia:!0,mutationObserver:!0,...e};t.info("Loading ProteusJS polyfills..."),i.performance&&await this.loadPerformancePolyfill(),i.requestAnimationFrame&&await this.loadRAFPolyfill(),i.classList&&await this.loadClassListPolyfill(),i.closest&&await this.loadClosestPolyfill(),i.cssSupports&&await this.loadCSSSupportsPolyfill(),i.customProperties&&await this.loadCustomPropertiesPolyfill(),i.matchMedia&&await this.loadMatchMediaPolyfill(),i.mutationObserver&&await this.loadMutationObserverPolyfill(),i.resizeObserver&&await this.loadResizeObserverPolyfill(),i.intersectionObserver&&await this.loadIntersectionObserverPolyfill(),t.info(`Loaded ${this.polyfillsLoaded.size} polyfills`)}checkBrowserSupport(){const e=[],t=[],i=[];"undefined"!=typeof ResizeObserver?e.push("ResizeObserver"):t.push("ResizeObserver"),"undefined"!=typeof IntersectionObserver?e.push("IntersectionObserver"):t.push("IntersectionObserver"),this.supportsCSSCustomProperties()?e.push("CSS Custom Properties"):t.push("CSS Custom Properties"),"undefined"!=typeof CSS&&"function"==typeof CSS.supports?e.push("CSS.supports"):t.push("CSS.supports"),"undefined"!=typeof performance&&"function"==typeof performance.now?e.push("Performance API"):t.push("Performance API"),"undefined"!=typeof window&&"function"==typeof window.matchMedia?e.push("matchMedia"):t.push("matchMedia"),"undefined"!=typeof window&&"function"==typeof window.MutationObserver?e.push("MutationObserver"):t.push("MutationObserver");const s=navigator.userAgent;return(s.includes("MSIE")||s.includes("Trident"))&&i.push("Internet Explorer detected - limited support"),s.includes("Safari")&&!s.includes("Chrome")&&i.push("Safari detected - some features may need polyfills"),{supported:e,missing:t,warnings:i}}async loadResizeObserverPolyfill(){"undefined"==typeof ResizeObserver&&(window.ResizeObserver=class{constructor(e){this.elements=new Set,this.rafId=null,this.callback=e}observe(e){this.elements.add(e),this.startPolling()}unobserve(e){this.elements.delete(e),0===this.elements.size&&this.stopPolling()}disconnect(){this.elements.clear(),this.stopPolling()}startPolling(){if(this.rafId)return;const e=()=>{const t=[];this.elements.forEach(e=>{const i=e.getBoundingClientRect();t.push({target:e,contentRect:i,borderBoxSize:[{inlineSize:i.width,blockSize:i.height}],contentBoxSize:[{inlineSize:i.width,blockSize:i.height}],devicePixelContentBoxSize:[{inlineSize:i.width,blockSize:i.height}]})}),t.length>0&&this.callback(t,this),this.rafId=requestAnimationFrame(e)};this.rafId=requestAnimationFrame(e)}stopPolling(){this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null)}},this.polyfillsLoaded.add("ResizeObserver"))}async loadIntersectionObserverPolyfill(){"undefined"==typeof IntersectionObserver&&(window.IntersectionObserver=class{constructor(e,t){this.elements=new Set,this.rafId=null,this.callback=e}observe(e){this.elements.add(e),this.startPolling()}unobserve(e){this.elements.delete(e),0===this.elements.size&&this.stopPolling()}disconnect(){this.elements.clear(),this.stopPolling()}startPolling(){if(this.rafId)return;const e=()=>{const t=[];this.elements.forEach(e=>{const i=e.getBoundingClientRect(),s=i.top<window.innerHeight&&i.bottom>0;t.push({target:e,boundingClientRect:i,intersectionRatio:s?1:0,intersectionRect:s?i:new DOMRect,isIntersecting:s,rootBounds:new DOMRect(0,0,window.innerWidth,window.innerHeight),time:performance.now()})}),t.length>0&&this.callback(t,this),this.rafId=requestAnimationFrame(e)};this.rafId=requestAnimationFrame(e)}stopPolling(){this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null)}},this.polyfillsLoaded.add("IntersectionObserver"))}async loadPerformancePolyfill(){if("undefined"==typeof performance||"function"!=typeof performance.now){if("undefined"==typeof performance&&(window.performance={}),"function"!=typeof performance.now){const e=Date.now();performance.now=function(){return Date.now()-e}}this.polyfillsLoaded.add("Performance")}}async loadRAFPolyfill(){if("function"==typeof requestAnimationFrame)return;let e=0;window.requestAnimationFrame=function(t){const i=(new Date).getTime(),s=Math.max(0,16-(i-e)),n=window.setTimeout(()=>{t(i+s)},s);return e=i+s,n},window.cancelAnimationFrame=function(e){clearTimeout(e)},this.polyfillsLoaded.add("RequestAnimationFrame")}async loadCSSSupportsPolyfill(){"undefined"!=typeof CSS&&"function"==typeof CSS.supports||("undefined"==typeof CSS&&(window.CSS={}),CSS.supports=function(e,t){const i=document.createElement("div");try{if(t)return i.style.setProperty(e,t),i.style.getPropertyValue(e)===t;{const t=e.indexOf(":");if(-1===t)return!1;const s=e.substring(0,t).trim(),n=e.substring(t+1).trim();return i.style.setProperty(s,n),i.style.getPropertyValue(s)===n}}catch{return!1}},this.polyfillsLoaded.add("CSS.supports"))}async loadCustomPropertiesPolyfill(){if(this.supportsCSSCustomProperties())return;const e=new Map,t=window.getComputedStyle;window.getComputedStyle=function(i,s){const n=t.call(this,i,s),r=n.getPropertyValue;return n.getPropertyValue=function(t){return t.startsWith("--")?e.get(t)||"":r.call(this,t)},n},this.polyfillsLoaded.add("CSS Custom Properties")}async loadMatchMediaPolyfill(){"undefined"!=typeof window&&"function"==typeof window.matchMedia||(window.matchMedia=function(e){return{matches:!1,media:e,onchange:null,addListener(){},removeListener(){},addEventListener(){},removeEventListener(){},dispatchEvent:()=>!0}},this.polyfillsLoaded.add("matchMedia"))}async loadMutationObserverPolyfill(){if("undefined"==typeof window||"function"!=typeof window.MutationObserver){window.MutationObserver=class{constructor(e){this.target=null,this.config={},this.isObserving=!1,this.callback=e}observe(e,t={}){this.target=e,this.config=t,this.isObserving=!0}disconnect(){this.isObserving=!1,this.target=null}takeRecords(){return[]}},this.polyfillsLoaded.add("MutationObserver")}}async loadClassListPolyfill(){"classList"in document.createElement("div")||(Object.defineProperty(Element.prototype,"classList",{get(){const e=this;return{add(t){e.className.includes(t)||(e.className+=(e.className?" ":"")+t)},remove(t){e.className=e.className.split(" ").filter(e=>e!==t).join(" ")},contains:t=>e.className.split(" ").includes(t),toggle(e){this.contains(e)?this.remove(e):this.add(e)}}}}),this.polyfillsLoaded.add("Element.classList"))}async loadClosestPolyfill(){"function"!=typeof Element.prototype.closest&&(Element.prototype.closest=function(e){let t=this;for(;t&&1===t.nodeType;){if(t.matches&&t.matches(e))return t;t=t.parentElement}return null},this.polyfillsLoaded.add("Element.closest"))}supportsCSSCustomProperties(){try{const e=document.createElement("div");return e.style.setProperty("--test","test"),"test"===e.style.getPropertyValue("--test")}catch{return!1}}getLoadedPolyfills(){return Array.from(this.polyfillsLoaded)}static async autoInit(){const e=_.getInstance(),i=e.checkBrowserSupport(),s={resizeObserver:i.missing.includes("ResizeObserver"),intersectionObserver:i.missing.includes("IntersectionObserver"),cssSupports:i.missing.includes("CSS.supports"),performance:i.missing.includes("Performance API"),customProperties:i.missing.includes("CSS Custom Properties"),matchMedia:i.missing.includes("matchMedia"),mutationObserver:i.missing.includes("MutationObserver")};await e.loadPolyfills(s),i.warnings.length>0&&t.warn("Browser Warnings:",i.warnings)}}function Q(){const e=V();return e.resizeObserver&&e.intersectionObserver}function V(){return{resizeObserver:"undefined"!=typeof ResizeObserver,intersectionObserver:"undefined"!=typeof IntersectionObserver,containerQueries:W(),cssClamp:G(),cssCustomProperties:J(),webWorkers:"undefined"!=typeof Worker,requestAnimationFrame:"undefined"!=typeof requestAnimationFrame,passiveEventListeners:K()}}function W(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("container-type","inline-size")}function G(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("font-size","clamp(1rem, 2vw, 2rem)")}function J(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("--test","value")}function K(){let e=!1;try{const t={get passive(){return e=!0,!1}};window.addEventListener("test",null,t),window.removeEventListener("test",null,t)}catch(t){e=!1}return e}const Y="1.1.0";class X{constructor(e={}){if(this.initialized=!1,X.instance)return X.instance;this.config=this.mergeConfig(e),this.eventSystem=new i,this.pluginSystem=new s(this),this.memoryManager=new n,this.observerManager=new a,this.containerManager=new u(this.config.containers,this.observerManager,this.memoryManager,this.eventSystem),this.clampScaling=new d,this.typographicScale=new m,this.textFitting=new p,this.lineHeightOptimizer=new g,this.verticalRhythm=new f({baseFontSize:16,baseLineHeight:1.5,baselineUnit:24,scale:"minor-third",precision:.001,responsive:!0,containerAware:!0}),this.eventHandler=new O({debounceDelay:16,useRAF:!0,batchOperations:!0,performanceTarget:16.67}),this.batchDOM=new L({maxBatchSize:50,separateReadWrite:!0,autoFlush:!0}),this.lazyEvaluation=new P({useIdleCallback:!0,progressiveEnhancement:!0,cacheResults:!0}),this.cssOptimizer=new F({deduplication:!0,criticalCSS:!0,unusedStyleRemoval:!0}),this.themeSystem=new q({autoDetect:!0,respectSystemPreference:!0,adaptiveContrast:!0}),this.flipAnimations=new N({respectMotionPreference:!0,batchAnimations:!0}),this.scrollAnimations=new H,this.memoryManagement=new B({autoCleanup:!0,leakDetection:!0}),this.cacheOptimization=new D({maxSize:100,evictionStrategy:"adaptive"}),this.zeroConfig=new j({autoDetectContainers:!0,intelligentBreakpoints:!0,performanceOptimization:!0}),this.browserPolyfills=_.getInstance(),this.performanceMonitor=new $,this.fluidTypography=new z,this.containerBreakpoints=new M,this.accessibilityEngine=new E(document.body),this.browserCompatibility=new I,this.fluidTypography.setPerformanceMonitor(this.performanceMonitor),this.containerBreakpoints.setPerformanceMonitor(this.performanceMonitor),X.instance=this,this.config.autoInit&&this.init()}get typography(){return this.fluidTypography}get containers(){return this.containerBreakpoints}get performance(){return this.performanceMonitor}get accessibility(){return this.accessibilityEngine}get compatibility(){return this.browserCompatibility}getConfiguration(){return this.config}async initialize(){return this.init()}init(){return this.initialized?(this.config.debug&&t.warn("Already initialized"),this):Q()?(this.config.debug&&t.info("Initializing...",{version:Y,config:this.config,support:V()}),this.performanceMonitor.start(),this.eventSystem.init(),this.pluginSystem.init(),this.eventHandler.initialize(),this.zeroConfig.initialize().catch(e=>{t.warn("Zero-config initialization failed",e)}),this.initialized=!0,this.eventSystem.emit("init",{config:this.config}),this.config.debug&&t.info("Initialized successfully"),this):(t.error("Browser not supported. Missing required APIs."),this)}getBrowserCapabilities(){const e=this.browserPolyfills?.checkBrowserSupport()||{supported:[]};return{resizeObserver:e.supported.includes("ResizeObserver"),intersectionObserver:e.supported.includes("IntersectionObserver"),containerQueries:e.supported.includes("CSS Container Queries"),cssClamp:e.supported.includes("CSS clamp()"),customProperties:e.supported.includes("CSS Custom Properties"),matchMedia:e.supported.includes("matchMedia"),mutationObserver:e.supported.includes("MutationObserver")}}getMetrics(){return this.performanceMonitor?.getMetrics()||{}}detectFeatures(){const e=this.getBrowserCapabilities(),t=this.browserPolyfills?.checkBrowserSupport()||{supported:[],missing:[]};return{resizeObserver:e.resizeObserver,intersectionObserver:e.intersectionObserver,containerQueries:e.containerQueries,cssClamp:e.cssClamp,customProperties:e.customProperties,flexbox:e.flexbox,grid:e.grid,supported:t.supported,missing:t.missing,polyfillsActive:t.missing.length>0}}updateLiveRegion(e,t){e instanceof HTMLElement&&(e.textContent=t,e.setAttribute("aria-live","polite"))}destroy(){this.initialized&&(this.config.debug,this.containerManager.destroy(),this.observerManager.destroy(),this.memoryManager.destroy(),this.performanceMonitor.stop(),this.eventHandler.destroy(),this.batchDOM.destroy(),this.lazyEvaluation.destroy(),this.cssOptimizer.destroy(),this.themeSystem.destroy(),this.flipAnimations.destroy(),this.scrollAnimations.destroy(),this.memoryManagement.destroy(),this.cacheOptimization.destroy(),this.zeroConfig.destroy(),this.pluginSystem.destroy(),this.eventSystem.destroy(),this.initialized=!1,X.instance=null,this.config.debug)}getConfig(){return{...this.config}}updateConfig(e){return this.config=this.mergeConfig(e,this.config),this.eventSystem.emit("configUpdate",{config:this.config}),this}getEventSystem(){return this.eventSystem}getPluginSystem(){return this.pluginSystem}getPerformanceMonitor(){return this.performanceMonitor}getMemoryManager(){return this.memoryManager}getObserverManager(){return this.observerManager}getContainerManager(){return this.containerManager}container(e,t){return this.containerManager.container(e,t)}fluidType(e,t){this.normalizeSelector(e).forEach(e=>{const i=this.clampScaling.createScaling(t||{minSize:16,maxSize:24,minContainer:320,maxContainer:1200,unit:"px",containerUnit:"px",curve:"linear"});e.style.fontSize=i.clampValue;const s=getComputedStyle(e),n=parseFloat(s.fontSize);e.style.lineHeight=1.5*n+"px"})}createTypeScale(e){return this.typographicScale.generateScale(e||{ratio:1.25,baseSize:16,baseUnit:"px",levels:6,direction:"both"})}createGrid(e,t){const i="string"==typeof e?document.querySelector(e):e;if(!i)return null;const s=new y(i,t);return s.activate(),s}fitText(e,t){this.normalizeSelector(e).forEach(e=>{const i=e.getBoundingClientRect(),s=e.textContent||"",n=this.textFitting.fitText(e,s,i.width,i.height,t);this.textFitting.applyFitting(e,n,t)})}applyRhythm(e,t){this.normalizeSelector(e).forEach(e=>{const t=this.verticalRhythm.generateRhythm();this.verticalRhythm.applyRhythm(e,t)})}createFlexbox(e,t){const i="string"==typeof e?document.querySelector(e):e;if(!i)return null;const s=new b(i,t);return s.activate(),s}applyFlow(e,t){const i="string"==typeof e?document.querySelector(e):e;if(!i)return null;const s=new v(i,t);return s.activate(),s}applySpacing(e,t){const i="string"==typeof e?document.querySelector(e):e;if(!i)return null;const s=new w(i,t);return s.activate(),s}enableReordering(e,t){const i="string"==typeof e?document.querySelector(e):e;if(!i)return null;const s=new S(i,t);return s.activate(),s}responsiveImages(e,t){const i=this.normalizeSelector(e),s=[];return i.forEach(e=>{const i=new A(e,t);i.activate(),s.push(i)}),1===s.length?s[0]:s}enableAccessibility(e,t){const i="string"==typeof e?document.querySelector(e):e;if(!i)return null;const s=new E(i,t);return s.activate(),s}setupComplete(e){const t=e?.container||document.body;return this.container(t,e?.container),this.fluidType(t.querySelectorAll("h1, h2, h3, h4, h5, h6, p"),e?.typography),this.createGrid(t.querySelectorAll(".grid, .gallery"),e?.grid),this.applySpacing(t,e?.spacing),this.enableAccessibility(t,e?.accessibility),this.responsiveImages(t.querySelectorAll("img"),e?.images),this}isInitialized(){return this.initialized}static getVersion(){return Y}static getSupportInfo(){return V()}static isSupported(){return Q()}static getInstance(e){return X.instance||(X.instance=new X(e)),X.instance}mergeConfig(e,t){const i={debug:!1,performance:"high",accessibility:!0,autoInit:!0,containers:{autoDetect:!0,breakpoints:{},units:!0,isolation:!0,polyfill:!0},typography:{fluidScaling:!0,autoOptimize:!0,accessibility:!0,scale:{ratio:1.33,base:"1rem",levels:6},lineHeight:{auto:!0,density:"comfortable"}},layout:{grid:{auto:!0,masonry:!1,gap:"fluid"},flexbox:{enhanced:!0,autoWrap:!0},spacing:{scale:"minor-third",density:"comfortable"}},animations:{enabled:!0,respectMotionPreferences:!0,duration:300,easing:"ease-out",flip:!0,microInteractions:!0},theming:{darkMode:{auto:!0,schedule:"18:00-06:00",transition:"smooth"},contrast:{adaptive:!0,level:"AA"}}};return{...i,...t,...e,containers:{...i.containers,...t?.containers,...e.containers},typography:{...i.typography,...t?.typography,...e.typography,scale:{...i.typography.scale,...t?.typography?.scale,...e.typography?.scale},lineHeight:{...i.typography.lineHeight,...t?.typography?.lineHeight,...e.typography?.lineHeight}},layout:{...i.layout,...t?.layout,...e.layout,grid:{...i.layout.grid,...t?.layout?.grid,...e.layout?.grid},flexbox:{...i.layout.flexbox,...t?.layout?.flexbox,...e.layout?.flexbox},spacing:{...i.layout.spacing,...t?.layout?.spacing,...e.layout?.spacing}},animations:{...i.animations,...t?.animations,...e.animations},theming:{...i.theming,...t?.theming,...e.theming,darkMode:{...i.theming.darkMode,...t?.theming?.darkMode,...e.theming?.darkMode},contrast:{...i.theming.contrast,...t?.theming?.contrast,...e.theming?.contrast}}}}normalizeSelector(e){return"string"==typeof e?Array.from(document.querySelectorAll(e)):e instanceof Element?[e]:Array.isArray(e)?e:[]}getPerformanceMetrics(){return{eventHandler:this.eventHandler.getMetrics(),batchDOM:this.batchDOM.getMetrics(),performanceMonitor:this.performanceMonitor.getMetrics()}}observeResize(e,t,i="normal"){const s="string"==typeof e?document.querySelector(e):e;return s?this.eventHandler.observeResize(s,t,i):null}batchStyles(e,t,i="normal"){const s="string"==typeof e?document.querySelector(e):e;return s?this.batchDOM.batchStyles(s,t,i):Promise.reject(new Error("Element not found"))}measureElement(e,t=["width","height"],i="normal"){const s="string"==typeof e?document.querySelector(e):e;return s?this.batchDOM.measureElement(s,t,i):Promise.reject(new Error("Element not found"))}setTheme(e){return this.themeSystem.setScheme(e),this}toggleTheme(){return this.themeSystem.toggle(),this}async animateElement(e,t,i){const s="string"==typeof e?document.querySelector(e):e;if(s)return this.flipAnimations.animate(s,t,i)}addMicroInteractions(e,t="hover"){const i="string"==typeof e?document.querySelector(e):e;if(!i)return this;switch(t){case"hover":U.addHover(i);break;case"press":U.addPress(i);break;case"focus":U.addFocus(i);break;case"ripple":U.addRipple(i)}return this}lazyLoad(e,t,i){const s="string"==typeof e?document.querySelector(e):e;return s?this.lazyEvaluation.register(s,t,i):null}async optimizeCSS(){return this.cssOptimizer.optimizeAll()}getAdvancedMetrics(){return{eventHandler:this.eventHandler.getMetrics(),batchDOM:this.batchDOM.getMetrics(),lazyEvaluation:this.lazyEvaluation.getMetrics(),cssOptimizer:this.cssOptimizer.getMetrics(),themeSystem:this.themeSystem.getState(),flipAnimations:this.flipAnimations.getActiveCount(),performanceMonitor:this.performanceMonitor.getMetrics()}}}async function Z(e,t={}){const{name:i,duration:s=300,onBefore:n,onAfter:r,allowInterrupt:o=!0}=t,a="startViewTransition"in document;if(n&&n(),a)try{const t=document.startViewTransition(async()=>{await e()});if(i){const e=document.createElement("style");e.textContent=`\n ::view-transition-old(${i}),\n ::view-transition-new(${i}) {\n animation-duration: ${s}ms;\n }\n `,document.head.appendChild(e),t.finished.finally(()=>{e.remove()})}await t.finished}catch(t){await e()}finally{r&&r()}else try{await e()}finally{r&&r()}}async function ee(e,t={}){const{name:i,prerender:s=!1}=t;if(s&&"speculation"in HTMLScriptElement.prototype){const t=document.createElement("script");t.type="speculationrules",t.textContent=JSON.stringify({prerender:[{where:{href_matches:e}}]}),document.head.appendChild(t)}if("startViewTransition"in document)try{const t=document.startViewTransition(()=>{window.location.href=e});if(i){const e=document.createElement("style");e.textContent=`\n ::view-transition-old(${i}),\n ::view-transition-new(${i}) {\n animation-duration: 300ms;\n }\n `,document.head.appendChild(e)}await t.finished}catch(t){window.location.href=e}else window.location.href=e}X.instance=null;var te={transition:Z,navigate:ee},ie=Object.freeze({__proto__:null,default:te,navigate:ee,transition:Z});function se(e,t){const i="string"==typeof e?document.querySelector(e):e;if(!i)throw new Error("Target element not found");const{keyframes:s,range:n=["0%","100%"],timeline:r={},fallback:o="io"}=t,{axis:a="block",start:c="0%",end:l="100%"}=r,h="CSS"in window&&CSS.supports("animation-timeline","scroll()");if(window.matchMedia("(prefers-reduced-motion: reduce)").matches){if(!1===o)return;const e=s[s.length-1];return void Object.assign(i.style,e)}if(h){const e=`scroll-timeline-${Math.random().toString(36).substr(2,9)}`,t=document.createElement("style");t.textContent=`\n @scroll-timeline ${e} {\n source: nearest;\n orientation: ${a};\n scroll-offsets: ${c}, ${l};\n }\n \n .scroll-animate-${e} {\n animation-timeline: ${e};\n animation-duration: 1ms; /* Required but ignored */\n animation-fill-mode: both;\n }\n `,document.head.appendChild(t),i.classList.add(`scroll-animate-${e}`);const n=i.animate(s,{duration:1,fill:"both"});"timeline"in n&&(n.timeline=new window.ScrollTimeline({source:document.scrollingElement,orientation:a,scrollOffsets:[{target:i,edge:"start",threshold:parseFloat(c)/100},{target:i,edge:"end",threshold:parseFloat(l)/100}]}))}else if("io"===o){let e=null;const t=new IntersectionObserver(t=>{t.forEach(t=>{const n=Math.max(0,Math.min(1,t.intersectionRatio));e||(e=i.animate(s,{duration:1e3,fill:"both"}),e.pause()),e.currentTime=1e3*n})},{threshold:Array.from({length:101},(e,t)=>t/100)});t.observe(i),i._scrollAnimateCleanup=()=>{t.disconnect(),e&&e.cancel()}}}function ne(e,t,i={}){const s="string"==typeof e?document.querySelector(e):e;if(!s)throw new Error("Target element not found");if(window.matchMedia("(prefers-reduced-motion: reduce)").matches){const e=t[t.length-1];return void Object.assign(s.style,e)}const n=new IntersectionObserver(e=>{e.forEach(e=>{e.isIntersecting&&(s.animate(t,{duration:600,easing:"ease-out",fill:"forwards",...i}),n.disconnect())})},{threshold:.1,rootMargin:"0px 0px -10% 0px"});n.observe(s)}function re(e,t=.5){const i="string"==typeof e?document.querySelector(e):e;if(!i)throw new Error("Target element not found");if(window.matchMedia("(prefers-reduced-motion: reduce)").matches)return;se(i,{keyframes:[{transform:`translateY(${-100*t}px)`},{transform:`translateY(${100*t}px)`}],range:["0%","100%"],timeline:{axis:"block"},fallback:"io"})}function oe(e){const t="string"==typeof e?document.querySelector(e):e;if(!t)return;t._scrollAnimateCleanup&&(t._scrollAnimateCleanup(),delete t._scrollAnimateCleanup),t.classList.forEach(e=>{e.startsWith("scroll-animate-")&&t.classList.remove(e)});t.getAnimations().forEach(e=>e.cancel())}var ae={scrollAnimate:se,scrollTrigger:ne,parallax:re,cleanup:oe},ce=Object.freeze({__proto__:null,cleanup:oe,default:ae,parallax:re,scrollAnimate:se,scrollTrigger:ne});function le(e,t){const i="string"==typeof e?document.querySelector(e):e,s="string"==typeof t.anchor?document.querySelector(t.anchor):t.anchor;if(!i||!s)throw new Error("Both floating and anchor elements must exist");const{placement:n="bottom",align:r="center",offset:o=8,strategy:a="absolute"}=t,c=CSS.supports("anchor-name","test");let l=!1,h=null;const u=()=>{const e=s.getBoundingClientRect(),t=i.getBoundingClientRect(),a=window.innerWidth,c=window.innerHeight;let l=n,h=0,d=0;switch(l){case"top":h=e.left,d=e.top-t.height-o;break;case"bottom":h=e.left,d=e.bottom+o;break;case"left":h=e.left-t.width-o,d=e.top;break;case"right":h=e.right+o,d=e.top;break;case"auto":{const t={top:e.top,bottom:c-e.bottom,left:e.left,right:a-e.right};return l=Object.entries(t).reduce((e,i)=>t[e[0]]>t[i[0]]?e:i)[0],u()}}if("top"===l||"bottom"===l)switch(r){case"start":break;case"center":h=e.left+(e.width-t.width)/2;break;case"end":h=e.right-t.width}else switch(r){case"start":break;case"center":d=e.top+(e.height-t.height)/2;break;case"end":d=e.bottom-t.height}return h<0&&(h=8),d<0&&(d=8),h+t.width>a&&(h=a-t.width-8),d+t.height>c&&(d=c-t.height-8),{x:h,y:d}},d=()=>{if(!l&&!c){const{x:e,y:t}=u(),s=i;s.style.position=a,s.style.left=`${e}px`,s.style.top=`${t}px`}};return(()=>{if(!c)return!1;const e=`anchor-${Math.random().toString(36).substring(2,11)}`;s.style.setProperty("anchor-name",e);const t=i;switch(t.style.position=a,t.style.setProperty("position-anchor",e),n){case"top":t.style.bottom=`anchor(bottom, ${o}px)`;break;case"bottom":t.style.top=`anchor(bottom, ${o}px)`;break;case"left":t.style.right=`anchor(left, ${o}px)`;break;case"right":t.style.left=`anchor(right, ${o}px)`}if("top"===n||"bottom"===n)switch(r){case"start":t.style.left="anchor(left)";break;case"center":t.style.left="anchor(center)",t.style.transform="translateX(-50%)";break;case"end":t.style.right="anchor(right)"}else switch(r){case"start":t.style.top="anchor(top)";break;case"center":t.style.top="anchor(center)",t.style.transform="translateY(-50%)";break;case"end":t.style.bottom="anchor(bottom)"}return!0})()||(d(),h=new ResizeObserver(d),h.observe(s),h.observe(i),window.addEventListener("scroll",d,{passive:!0}),window.addEventListener("resize",d,{passive:!0})),{destroy:()=>{if(l=!0,h&&(h.disconnect(),h=null),window.removeEventListener("scroll",d),window.removeEventListener("resize",d),c){s.style.removeProperty("anchor-name");const e=i;e.style.removeProperty("position-anchor"),e.style.position=""}}}}var he={tether:le},ue=Object.freeze({__proto__:null,default:he,tether:le});function de(e,t,i={}){const s="string"==typeof e?document.querySelector(e):e,n="string"==typeof t?document.querySelector(t):t;if(!s||!n)throw new Error("Both trigger and panel elements must exist");const{type:r="menu",trapFocus:o="dialog"===r,restoreFocus:a=!0,closeOnEscape:c=!0,onOpen:l,onClose:h}=i;let u=!1,d=null,m=null;const p="popover"in HTMLElement.prototype;class g{constructor(e){this.container=e,this.focusableElements=[],this.handleKeyDown=e=>{if("Tab"!==e.key)return;const t=this.focusableElements[0],i=this.focusableElements[this.focusableElements.length-1];e.shiftKey?document.activeElement===t&&(e.preventDefault(),i.focus()):document.activeElement===i&&(e.preventDefault(),t.focus())},this.updateFocusableElements()}updateFocusableElements(){this.focusableElements=Array.from(this.container.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'))}activate(){this.updateFocusableElements(),this.focusableElements.length>0&&this.focusableElements[0].focus(),document.addEventListener("keydown",this.handleKeyDown)}deactivate(){document.removeEventListener("keydown",this.handleKeyDown)}}const f=()=>{u||(a&&(d=document.activeElement),p?n.showPopover():(n.style.display="block",n.setAttribute("data-popover-open","true")),s.setAttribute("aria-expanded","true"),u=!0,o&&(m=new g(n),m.activate()),l&&l())},y=()=>{u&&(p?n.hidePopover():(n.style.display="none",n.removeAttribute("data-popover-open")),s.setAttribute("aria-expanded","false"),u=!1,m&&(m.deactivate(),m=null),a&&d&&(d.focus(),d=null),h&&h())},b=()=>{u?y():f()},v=e=>{c&&"Escape"===e.key&&u&&(e.preventDefault(),y())},w=e=>{e.preventDefault(),b()};return(()=>{const e=n.id||`popover-${Math.random().toString(36).substr(2,9)}`;n.id=e,s.setAttribute("aria-expanded","false"),s.setAttribute("aria-controls",e),"menu"===r?(s.setAttribute("aria-haspopup","menu"),n.setAttribute("role","menu")):"dialog"===r?(s.setAttribute("aria-haspopup","dialog"),n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true")):"tooltip"===r&&(s.setAttribute("aria-describedby",e),n.setAttribute("role","tooltip"))})(),p&&(n.popover="dialog"===r?"manual":"auto",s.setAttribute("popovertarget",n.id)),s.addEventListener("click",w),document.addEventListener("keydown",v),{open:f,close:y,toggle:b,destroy:()=>{s.removeEventListener("click",w),document.removeEventListener("keydown",v),m&&m.deactivate(),u&&y()}}}var me={attach:de},pe=Object.freeze({__proto__:null,attach:de,default:me});function ge(e,t,i={}){const s="string"==typeof e?document.querySelector(e):e;if(!s)throw new Error("Target element not found");const{type:n="size",inlineSize:r=!0}=i,o=t||`container-${Math.random().toString(36).substring(2,11)}`,a=s;a.style.containerName=o,a.style.containerType=n;const c=getComputedStyle(a);!c.contain||c.contain,("development"===process.env.NODE_ENV||window.__PROTEUS_DEV__)&&function(e,t){const i=document.createElement("div");i.className="proteus-container-overlay",i.style.cssText="\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n pointer-events: none;\n border: 2px dashed rgba(255, 0, 255, 0.5);\n background: rgba(255, 0, 255, 0.05);\n z-index: 9999;\n font-family: monospace;\n font-size: 12px;\n color: #ff00ff;\n ";const s=document.createElement("div");s.style.cssText="\n position: absolute;\n top: -20px;\n left: 0;\n background: rgba(255, 0, 255, 0.9);\n color: white;\n padding: 2px 6px;\n border-radius: 3px;\n font-size: 10px;\n white-space: nowrap;\n ",s.textContent=`Container: ${t}`;const n=document.createElement("div");n.style.cssText="\n position: absolute;\n bottom: 2px;\n right: 2px;\n background: rgba(0, 0, 0, 0.7);\n color: white;\n padding: 2px 4px;\n border-radius: 2px;\n font-size: 10px;\n ",i.appendChild(s),i.appendChild(n),"static"===getComputedStyle(e).position&&(e.style.position="relative");e.appendChild(i);const r=()=>{const t=e.getBoundingClientRect();n.textContent=`${Math.round(t.width)}×${Math.round(t.height)}`};if(r(),"ResizeObserver"in window){new ResizeObserver(r).observe(e)}e._proteusContainerCleanup=()=>{i.remove()}}(a,o)}function fe(e,t,i){return`@container ${e} (${t}) {\n${Object.entries(i).map(([e,t])=>` ${e}: ${t};`).join("\n")}\n}`}function ye(e,t,i){const s=fe(e,t,i),n=document.createElement("style");n.textContent=s,n.setAttribute("data-proteus-container",e),document.head.appendChild(n)}function be(e){document.querySelectorAll(`style[data-proteus-container="${e}"]`).forEach(e=>e.remove())}function ve(e){const t="string"==typeof e?document.querySelector(e):e;if(!t)throw new Error("Target element not found");const i=t.getBoundingClientRect();return{width:i.width,height:i.height}}function we(){return CSS.supports("container-type","size")}function Se(e){const t="string"==typeof e?document.querySelector(e):e;if(!t)return;const i=t;i._proteusContainerCleanup&&(i._proteusContainerCleanup(),delete i._proteusContainerCleanup)}function Ae(e){document.querySelectorAll(".proteus-container-overlay").forEach(t=>{const i=t;i.style.display=void 0!==e?e?"block":"none":"none"===i.style.display?"block":"none"})}var xe={defineContainer:ge,createContainerQuery:fe,applyContainerQuery:ye,removeContainerQuery:be,getContainerSize:ve,isSupported:we,cleanup:Se,toggleDevOverlay:Ae},Ce=Object.freeze({__proto__:null,applyContainerQuery:ye,cleanup:Se,createContainerQuery:fe,default:xe,defineContainer:ge,getContainerSize:ve,isSupported:we,removeContainerQuery:be,toggleDevOverlay:Ae});function Ee(e,t,i={}){const{minViewportPx:s=320,maxViewportPx:n=1200,lineHeight:r,containerUnits:o=!1}=i,a=16*e,c=(16*t-a)/(n-s);let l=`font-size: ${`clamp(${e}rem, ${(a-c*s)/16}rem + ${100*c}${o?"cqw":"vw"}, ${t}rem)`};`;return r&&(l+=`\nline-height: ${r};`),{css:l}}function ke(e,t,i,s={}){const{css:n}=Ee(t,i,s),r=document.createElement("style");r.textContent=`${e} {\n ${n.replace(/\n/g,"\n ")}\n}`,r.setAttribute("data-proteus-typography",e),document.head.appendChild(r)}function Oe(e=1,t=1.25,i=6,s={}){const n={};for(let r=-2;r<=i-3;r++){const i=e*Math.pow(t,r),o=.8*i,a=1.2*i;n[r<=0?`small${Math.abs(r)}`:`large${r}`]=Ee(o,a,s)}return n}function ze(e,t="--font-size"){return`:root {\n${Object.entries(e).map(([e,i])=>` ${t}-${e}: ${i.css.replace("font-size: ","").replace(";","")};`).join("\n")}\n}`}function Me(e,t=65){return 1.4+Math.max(.1,Math.min(.3,.5*(1-e)))+Math.max(-.1,Math.min(.1,.002*(65-t)))}function Ie(e,t=65,i=.5){const s=e/(t*i);return Math.max(.75,Math.min(1.5,s))}function Re(e,t={}){const i="string"==typeof e?document.querySelector(e):e;if(!i)throw new Error("Target element not found");const{minSize:s=.875,maxSize:n=1.25,targetCharacters:r=65,autoLineHeight:o=!0}=t,{css:a}=Ee(s,n),c=i;if(a.split(";").filter(Boolean).forEach(e=>{const[t,i]=e.split(":").map(e=>e.trim());t&&i&&c.style.setProperty(t,i)}),o){const e=()=>{const e=getComputedStyle(c),t=parseFloat(e.fontSize),i=Me(t/16,c.getBoundingClientRect().width/(.5*t));c.style.lineHeight=i.toString()};if(e(),"ResizeObserver"in window){const t=new ResizeObserver(e);t.observe(c),c._proteusTypographyCleanup=()=>{t.disconnect()}}}}function Te(e){if(e){const t="string"==typeof e?document.querySelector(e):e;t&&t._proteusTypographyCleanup&&(t._proteusTypographyCleanup(),delete t._proteusTypographyCleanup)}else{document.querySelectorAll("style[data-proteus-typography]").forEach(e=>e.remove())}}function $e(){return CSS.supports("width","1cqw")}var Le={fluidType:Ee,applyFluidType:ke,createTypographicScale:Oe,generateScaleCSS:ze,optimizeLineHeight:Me,calculateOptimalSize:Ie,makeResponsive:Re,cleanup:Te,supportsContainerUnits:$e},Pe=Object.freeze({__proto__:null,applyFluidType:ke,calculateOptimalSize:Ie,cleanup:Te,createTypographicScale:Oe,default:Le,fluidType:Ee,generateScaleCSS:ze,makeResponsive:Re,optimizeLineHeight:Me,supportsContainerUnits:$e});async function Fe(e=document,t={}){if("production"===process.env.NODE_ENV)return{violations:[],passes:0,incomplete:0,timestamp:Date.now(),url:window.location.href};const{rules:i=["color-contrast","heading-order","image-alt","label","link-name","button-name"],format:s="console",openInBrowser:n=!1}=t,r=[];let o=0,a=0;const c={"color-contrast":Be,"heading-order":De,"image-alt":qe,label:Ne,"link-name":Ue,"button-name":He,"focus-visible":je,"aria-labels":_e,"landmark-roles":Qe,"skip-links":Ve};for(const t of i)if(c[t])try{const i=await c[t](e);i.violations.length>0?r.push(...i.violations):o++}catch(e){a++}const l={violations:r,passes:o,incomplete:a,timestamp:Date.now(),url:window.location.href};return"console"===s&&function(e){0===e.violations.length||e.violations.forEach(e=>{"critical"===e.impact||"serious"===e.impact||e.impact;e.elements});e.incomplete}(l),n&&function(e){const t=function(e){const t=e.violations.map(e=>`\n <div class="violation violation--${e.impact}">\n <h3>${e.help}</h3>\n <p><strong>Impact:</strong> ${e.impact}</p>\n <p><strong>Fix:</strong> ${e.fix}</p>\n <p><strong>Affected elements:</strong> ${e.nodes}</p>\n </div>\n `).join("");return`\n<!DOCTYPE html>\n<html lang="en">\n<head>\n <meta charset="UTF-8">\n <meta name="viewport" content="width=device-width, initial-scale=1.0">\n <title>ProteusJS Accessibility Report</title>\n <style>\n body { font-family: system-ui, sans-serif; margin: 2rem; line-height: 1.6; }\n .header { border-bottom: 2px solid #e5e7eb; padding-bottom: 1rem; margin-bottom: 2rem; }\n .summary { background: #f3f4f6; padding: 1rem; border-radius: 8px; margin-bottom: 2rem; }\n .violation { border-left: 4px solid #ef4444; padding: 1rem; margin-bottom: 1rem; background: #fef2f2; }\n .violation--critical { border-color: #dc2626; background: #fef2f2; }\n .violation--serious { border-color: #ea580c; background: #fff7ed; }\n .violation--moderate { border-color: #d97706; background: #fffbeb; }\n .violation--minor { border-color: #65a30d; background: #f7fee7; }\n .violation h3 { margin-top: 0; color: #374151; }\n .no-violations { text-align: center; color: #059669; font-size: 1.25rem; padding: 2rem; }\n </style>\n</head>\n<body>\n <div class="header">\n <h1>🌊 ProteusJS Accessibility Report</h1>\n <p>Generated on ${new Date(e.timestamp).toLocaleString()}</p>\n <p>URL: ${e.url}</p>\n </div>\n\n <div class="summary">\n <h2>Summary</h2>\n <p><strong>Violations:</strong> ${e.violations.length}</p>\n <p><strong>Checks passed:</strong> ${e.passes}</p>\n <p><strong>Incomplete checks:</strong> ${e.incomplete}</p>\n </div>\n\n ${0===e.violations.length?'<div class="no-violations">✅ No accessibility violations found!</div>':`<h2>Violations</h2>${t}`}\n</body>\n</html>`}(e),i=new Blob([t],{type:"text/html"}),s=URL.createObjectURL(i);if(!window.open(s,"_blank")){const e=document.createElement("a");e.href=s,e.download=`proteus-a11y-report-${Date.now()}.html`,e.click()}setTimeout(()=>URL.revokeObjectURL(s),1e3)}(l),l}async function Be(e){const t=[];return e.querySelectorAll("*").forEach(e=>{const i=getComputedStyle(e),s=i.color,n=i.backgroundColor;if(s&&n&&"rgba(0, 0, 0, 0)"!==s&&"rgba(0, 0, 0, 0)"!==n){const i=function(e,t){const i=We(e),s=We(t);if(!i||!s)return 4.5;const n=Ge(i),r=Ge(s),o=Math.max(n,r),a=Math.min(n,r);return(o+.05)/(a+.05)}(s,n);i<4.5&&t.push({id:"color-contrast",impact:"serious",nodes:1,help:"Elements must have sufficient color contrast",fix:`Increase contrast ratio to at least 4.5:1. Current: ${i.toFixed(2)}:1`,elements:[e]})}}),{violations:t}}async function De(e){const t=[],i=e.querySelectorAll("h1, h2, h3, h4, h5, h6");let s=0;return i.forEach(e=>{const i=parseInt(e.tagName.charAt(1));i>s+1&&t.push({id:"heading-order",impact:"moderate",nodes:1,help:"Heading levels should only increase by one",fix:`Change ${e.tagName} to H${s+1} or add intermediate headings`,elements:[e]}),s=i}),{violations:t}}async function qe(e){const t=[];return e.querySelectorAll("img").forEach(e=>{e.hasAttribute("alt")||t.push({id:"image-alt",impact:"critical",nodes:1,help:"Images must have alternative text",fix:'Add alt attribute with descriptive text or alt="" for decorative images',elements:[e]})}),{violations:t}}async function Ne(e){const t=[];return e.querySelectorAll("input, select, textarea").forEach(i=>{i.hasAttribute("aria-label")||i.hasAttribute("aria-labelledby")||e.querySelector(`label[for="${i.id}"]`)||i.closest("label")||t.push({id:"label",impact:"critical",nodes:1,help:"Form elements must have labels",fix:"Add a label element, aria-label, or aria-labelledby attribute",elements:[i]})}),{violations:t}}async function Ue(e){const t=[];return e.querySelectorAll("a[href]").forEach(e=>{const i=e.textContent?.trim(),s=e.getAttribute("aria-label");i||s||t.push({id:"link-name",impact:"serious",nodes:1,help:"Links must have discernible text",fix:"Add descriptive text content or aria-label attribute",elements:[e]})}),{violations:t}}async function He(e){const t=[];return e.querySelectorAll('button, input[type="button"], input[type="submit"]').forEach(e=>{const i=e.textContent?.trim(),s=e.getAttribute("aria-label"),n=e.getAttribute("value");i||s||n||t.push({id:"button-name",impact:"serious",nodes:1,help:"Buttons must have discernible text",fix:"Add text content, aria-label, or value attribute",elements:[e]})}),{violations:t}}async function je(e){const t=[];return e.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])').forEach(e=>{const i=getComputedStyle(e),s="none"!==i.outline&&"0px"!==i.outline&&"0"!==i.outline&&"0px"!==i.outlineWidth,n=i.boxShadow.includes("inset")||i.border!==i.borderColor||e.hasAttribute("data-focus-visible");s||n||t.push({id:"focus-visible",impact:"serious",nodes:1,help:"Interactive elements must have visible focus indicators",fix:"Add outline, box-shadow, or other visible focus styles",elements:[e]})}),{violations:t}}async function _e(e){const t=[];e.querySelectorAll("[aria-labelledby]").forEach(i=>{const s=i.getAttribute("aria-labelledby");if(s){const n=s.split(" ").filter(t=>!e.querySelector(`#${t}`));n.length>0&&t.push({id:"aria-labelledby-invalid",impact:"serious",nodes:1,help:"aria-labelledby must reference existing elements",fix:`Fix or remove references to missing IDs: ${n.join(", ")}`,elements:[i]})}});return e.querySelectorAll("[aria-describedby]").forEach(i=>{const s=i.getAttribute("aria-describedby");if(s){const n=s.split(" ").filter(t=>!e.querySelector(`#${t}`));n.length>0&&t.push({id:"aria-describedby-invalid",impact:"moderate",nodes:1,help:"aria-describedby must reference existing elements",fix:`Fix or remove references to missing IDs: ${n.join(", ")}`,elements:[i]})}}),{violations:t}}async function Qe(e){const t=[],i=e.querySelectorAll('main, [role="main"]');0===i.length?t.push({id:"landmark-main-missing",impact:"moderate",nodes:0,help:"Page should have a main landmark",fix:'Add a <main> element or role="main" to identify the main content area'}):i.length>1&&t.push({id:"landmark-main-multiple",impact:"moderate",nodes:i.length,help:"Page should have only one main landmark",fix:'Ensure only one main element or role="main" exists per page',elements:Array.from(i)});const s=e.querySelectorAll('nav, [role="navigation"]');return s.length>1&&s.forEach(e=>{e.hasAttribute("aria-label")||e.hasAttribute("aria-labelledby")||e.querySelector("h1, h2, h3, h4, h5, h6")||t.push({id:"landmark-nav-unlabeled",impact:"moderate",nodes:1,help:"Multiple navigation landmarks should be labeled",fix:"Add aria-label or aria-labelledby to distinguish navigation areas",elements:[e]})}),{violations:t}}async function Ve(e){const t=[],i=e.querySelectorAll('nav, [role="navigation"]'),s=e.querySelector('main, [role="main"]');if(i.length>0&&s){const i=e.querySelectorAll('a[href^="#"]');Array.from(i).some(e=>{const t=e.getAttribute("href");return t&&("#main"===t||t===`#${s.id}`||e.textContent?.toLowerCase().includes("skip to main")||e.textContent?.toLowerCase().includes("skip to content"))})||t.push({id:"skip-link-missing",impact:"moderate",nodes:0,help:"Page with navigation should have skip links",fix:"Add a skip link to the main content area for keyboard users"})}const n=e.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(n&&"A"===n.tagName){const e=n.getAttribute("href");e?.startsWith("#")||t.push({id:"skip-link-not-first",impact:"minor",nodes:1,help:"Skip links should be the first focusable elements",fix:"Move skip links to the beginning of the document",elements:[n]})}return{violations:t}}function We(e){const t=e.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(t&&t[1]&&t[2]&&t[3])return{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10)};const i=e.match(/^#([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i);if(i&&i[1]&&i[2]&&i[3])return{r:parseInt(i[1],16),g:parseInt(i[2],16),b:parseInt(i[3],16)};return{black:{r:0,g:0,b:0},white:{r:255,g:255,b:255},red:{r:255,g:0,b:0},green:{r:0,g:128,b:0},blue:{r:0,g:0,b:255}}[e.toLowerCase()]||null}function Ge(e){const{r:t,g:i,b:s}=e,n=t/255,r=i/255,o=s/255;return.2126*(n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4))+.0722*(o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4))}var Je={audit:Fe},Ke=Object.freeze({__proto__:null,audit:Fe,default:Je});function Ye(e,t={}){const i="string"==typeof e?document.querySelector(e):e;if(!i)throw new Error("Dialog root element not found");const{modal:s=!0,restoreFocus:n=!0}=t;const r=e=>{e.key,0};return i.setAttribute("role","dialog"),s&&i.setAttribute("aria-modal","true"),i.hasAttribute("hidden")||i.setAttribute("hidden",""),document.addEventListener("keydown",r),{destroy:()=>{document.removeEventListener("keydown",r)}}}function Xe(e,t,i={}){const s="string"==typeof e?document.querySelector(e):e,n="string"==typeof t?document.querySelector(t):t;if(!s||!n)throw new Error("Both trigger and panel elements must exist");const{delay:r=500}=i;let o=null,a=!1;const c=()=>{a||(n.style.display="block",a=!0)},l=()=>{a&&(n.style.display="none",a=!1)},h=()=>{o&&clearTimeout(o),o=window.setTimeout(c,r)},u=()=>{o&&(clearTimeout(o),o=null),l()},d=()=>{c()},m=()=>{l()};return(()=>{const e=n.id||`tooltip-${Math.random().toString(36).substring(2,11)}`;n.id=e,n.setAttribute("role","tooltip"),s.setAttribute("aria-describedby",e),n.style.display="none"})(),s.addEventListener("mouseenter",h),s.addEventListener("mouseleave",u),s.addEventListener("focus",d),s.addEventListener("blur",m),{destroy:()=>{o&&clearTimeout(o),s.removeEventListener("mouseenter",h),s.removeEventListener("mouseleave",u),s.removeEventListener("focus",d),s.removeEventListener("blur",m),l()}}}function Ze(e,t={}){const i="string"==typeof e?document.querySelector(e):e;if(!i)throw new Error("Listbox root element not found");const{multiselect:s=!1}=t;let n=-1;const r=()=>i.querySelectorAll('[role="option"]'),o=e=>{const t=r();e<0||e>=t.length||(t.forEach(e=>e.setAttribute("tabindex","-1")),n=e,t[n]?.setAttribute("tabindex","0"),t[n]?.focus())},a=e=>{const t=r();if(!(e<0||e>=t.length))if(s){const i="true"===t[e]?.getAttribute("aria-selected");t[e]?.setAttribute("aria-selected",(!i).toString())}else t.forEach(e=>e.setAttribute("aria-selected","false")),t[e]?.setAttribute("aria-selected","true")},c=e=>{const t=e,i=r();switch(t.key){case"ArrowDown":t.preventDefault(),o(Math.min(n+1,i.length-1));break;case"ArrowUp":t.preventDefault(),o(Math.max(n-1,0));break;case"Home":t.preventDefault(),o(0);break;case"End":t.preventDefault(),o(i.length-1);break;case"Enter":case" ":t.preventDefault(),a(n)}},l=e=>{const t=e.target.closest('[role="option"]');if(!t)return;const i=Array.from(r()).indexOf(t);i>=0&&(o(i),a(i))};return(()=>{i.setAttribute("role","listbox"),s&&i.setAttribute("aria-multiselectable","true");const e=i.querySelectorAll('[role="option"]');e.forEach((e,t)=>{e.setAttribute("aria-selected","false"),e.setAttribute("tabindex","-1")}),e.length>0&&(e[0]?.setAttribute("tabindex","0"),n=0)})(),i.addEventListener("keydown",c),i.addEventListener("click",l),{destroy:()=>{i.removeEventListener("keydown",c),i.removeEventListener("click",l)}}}function et(e,t={}){const i="string"==typeof e?document.querySelector(e):e;if(!i)throw new Error("Combobox root element not found");const{multiselect:s=!1,filtering:n}=t;let r=!1;const o=e=>{const t=e;switch(t.key){case"ArrowDown":t.preventDefault(),r||(r=!0,i.setAttribute("aria-expanded","true"));break;case"Escape":t.preventDefault(),r=!1,i.setAttribute("aria-expanded","false")}};return i.setAttribute("role","combobox"),i.setAttribute("aria-expanded","false"),s&&i.setAttribute("aria-multiselectable","true"),i.addEventListener("keydown",o),{destroy:()=>{i.removeEventListener("keydown",o)}}}function tt(e){const t="string"==typeof e?document.querySelector(e):e;if(!t)throw new Error("Tabs root element not found");let i=0;const s=e=>{const s=e,r=Array.from(t.querySelectorAll('[role="tab"]'));switch(s.key){case"ArrowRight":s.preventDefault(),i=(i+1)%r.length,n(i);break;case"ArrowLeft":s.preventDefault(),i=0===i?r.length-1:i-1,n(i)}},n=e=>{const i=t.querySelectorAll('[role="tab"]'),s=t.querySelectorAll('[role="tabpanel"]');i.forEach((t,i)=>{t.setAttribute("tabindex",i===e?"0":"-1"),t.setAttribute("aria-selected",i===e?"true":"false"),i===e&&t.focus()}),s.forEach((t,i)=>{i===e?t.removeAttribute("hidden"):t.setAttribute("hidden","true")})};return(()=>{const e=t.querySelector('[role="tablist"]'),i=t.querySelectorAll('[role="tab"]'),s=t.querySelectorAll('[role="tabpanel"]');e||t.setAttribute("role","tablist"),i.forEach((e,t)=>{e.setAttribute("tabindex",0===t?"0":"-1"),e.setAttribute("aria-selected",0===t?"true":"false")}),s.forEach((e,t)=>{e.setAttribute("hidden",0===t?"":"true")})})(),t.addEventListener("keydown",s),{destroy:()=>{t.removeEventListener("keydown",s)}}}function it(e){const t="string"==typeof e?document.querySelector(e):e;if(!t)throw new Error("Menu root element not found");let i=-1;const s=e=>{const s=e,r=Array.from(t.querySelectorAll('[role="menuitem"]'));switch(s.key){case"ArrowDown":s.preventDefault(),i=(i+1)%r.length,n(i);break;case"ArrowUp":s.preventDefault(),i=0===i?r.length-1:i-1,n(i);break;case"Enter":case" ":s.preventDefault(),r[i]&&r[i].click()}},n=e=>{t.querySelectorAll('[role="menuitem"]').forEach((t,i)=>{t.setAttribute("tabindex",i===e?"0":"-1"),i===e&&t.focus()})};return(()=>{t.setAttribute("role","menu");const e=t.querySelectorAll('[role="menuitem"]');e.forEach((e,t)=>{e.setAttribute("tabindex",0===t?"0":"-1")}),e.length>0&&(i=0)})(),t.addEventListener("keydown",s),{destroy:()=>{t.removeEventListener("keydown",s)}}}function st(e){const t="string"==typeof e?document.querySelector(e):e;if(!t)throw new Error("Focus trap root element not found");let i=!1,s=[];const n=()=>{s=Array.from(t.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'))},r=e=>{if(!i||"Tab"!==e.key)return;if(n(),0===s.length)return;const t=s[0],r=s[s.length-1];e.shiftKey?document.activeElement===t&&(e.preventDefault(),r.focus()):document.activeElement===r&&(e.preventDefault(),t.focus())};return{activate:()=>{i||(i=!0,n(),s.length>0&&s[0].focus(),document.addEventListener("keydown",r))},deactivate:()=>{i&&(i=!1,document.removeEventListener("keydown",r))}}}var nt={dialog:Ye,tooltip:Xe,combobox:et,listbox:Ze,tabs:tt,menu:it,focusTrap:st},rt=Object.freeze({__proto__:null,combobox:et,default:nt,dialog:Ye,focusTrap:st,listbox:Ze,menu:it,tabs:tt,tooltip:Xe});function ot(e,t="auto",i={}){const s="string"==typeof e?document.querySelectorAll(e):[e],{containIntrinsicSize:n="1000px 400px"}=i;s.forEach(e=>{const i=e;i.style.contentVisibility=t,"auto"===t&&(i.style.containIntrinsicSize=n)})}function at(e,t){("string"==typeof e?document.querySelectorAll(e):[e]).forEach(e=>{(e instanceof HTMLImageElement||e instanceof HTMLLinkElement||e instanceof HTMLScriptElement)&&(e.fetchPriority=t)})}function ct(e){const{prerender:t=[],prefetch:i=[],sameOriginOnly:s=!0}=e;if(!("supports"in HTMLScriptElement)||!HTMLScriptElement.supports("speculationrules"))return;const n={};if(t.length>0&&(n.prerender=t.map(e=>{const t={where:{href_matches:e}};return s&&(t.where.href_matches=new URL(e,window.location.origin).href),t})),i.length>0&&(n.prefetch=i.map(e=>{const t={where:{href_matches:e}};return s&&(t.where.href_matches=new URL(e,window.location.origin).href),t})),0===Object.keys(n).length)return;const r=document.createElement("script");r.type="speculationrules",r.textContent=JSON.stringify(n),document.head.appendChild(r)}async function lt(){return"scheduler"in window&&"yield"in window.scheduler?window.scheduler.yield():"scheduler"in window&&"postTask"in window.scheduler?new Promise(e=>{window.scheduler.postTask(e,{priority:"user-blocking"})}):new Promise(e=>{setTimeout(e,0)})}function ht(e="img"){("string"==typeof e?document.querySelectorAll(e):[e]).forEach(e=>{if(e instanceof HTMLImageElement){if(!e.hasAttribute("loading")){const t=e.getBoundingClientRect().top<window.innerHeight;e.loading=t?"eager":"lazy"}if(e.hasAttribute("decoding")||(e.decoding="async"),!e.hasAttribute("fetchpriority")){e.getBoundingClientRect().top<window.innerHeight&&(e.fetchPriority="high")}}})}function ut(e){e.forEach(({href:e,as:t,type:i})=>{if(document.querySelector(`link[rel="preload"][href="${e}"]`))return;const s=document.createElement("link");s.rel="preload",s.href=e,s.as=t,i&&(s.type=i),document.head.appendChild(s)})}function dt(){return new Promise(e=>{const t={};let i=0;const s=()=>{i++,i>=3&&e(t)};if("PerformanceObserver"in window){try{const e=new PerformanceObserver(e=>{const i=e.getEntries(),s=i[i.length-1];t.lcp=s.startTime});e.observe({entryTypes:["largest-contentful-paint"]}),setTimeout(()=>{e.disconnect(),s()},1e4)}catch{s()}try{const e=new PerformanceObserver(i=>{i.getEntries().forEach(e=>{t.fid=e.processingStart-e.startTime}),e.disconnect(),s()});e.observe({entryTypes:["first-input"]}),setTimeout(()=>{void 0===t.fid&&(t.fid=0,e.disconnect(),s())},1e4)}catch{s()}try{let e=0;const i=new PerformanceObserver(i=>{i.getEntries().forEach(t=>{t.hadRecentInput||(e+=t.value)}),t.cls=e});i.observe({entryTypes:["layout-shift"]}),setTimeout(()=>{i.disconnect(),s()},1e4)}catch{s()}}else setTimeout(()=>e(t),100)})}const mt={contentVisibility:ot,fetchPriority:at,speculate:ct,yieldToBrowser:lt,optimizeImages:ht,preloadCritical:ut,measureCWV:dt};var pt={contentVisibility:ot,fetchPriority:at,speculate:ct,yieldToBrowser:lt,optimizeImages:ht,preloadCritical:ut,measureCWV:dt,boost:mt},gt=Object.freeze({__proto__:null,boost:mt,contentVisibility:ot,default:pt,fetchPriority:at,measureCWV:dt,optimizeImages:ht,preloadCritical:ut,speculate:ct,yieldToBrowser:lt});const ft="1.1.0",yt="ProteusJS";export{yt as LIBRARY_NAME,X as ProteusJS,ft as VERSION,Ke as a11yAudit,rt as a11yPrimitives,ue as anchor,Ce as container,X as default,Q as isSupported,gt as perf,pe as popover,ce as scroll,ie as transitions,Pe as typography,Y as version};
8
8
  //# sourceMappingURL=proteus.esm.min.js.map