@je-es/client 0.2.1 → 0.2.2

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.
package/dist/main.d.cts CHANGED
@@ -810,9 +810,10 @@ declare class I18nManager {
810
810
  *
811
811
  * @param key Translation key
812
812
  * @param params Optional parameters for replacement
813
+ * @param defaultValue Optional default translation key
813
814
  * @returns Array of VNode and string elements that can be used as children
814
815
  */
815
- tHtml(key: string, params?: Record<string, string>): (VNode | string)[];
816
+ tHtml(key: string, params?: Record<string, string>, defaultValue?: string): (VNode | string)[];
816
817
  /**
817
818
  * Parse HTML string into VNode and text elements
818
819
  * Converts \n and /n sequences to <br> tags
@@ -898,9 +899,10 @@ declare function tLang(key: string, lang: string, params?: Record<string, string
898
899
  * Useful for multiline translations with formatting like <br>
899
900
  * @param key Translation key
900
901
  * @param params Optional parameters
902
+ * @param defaultValue Optional default translation key
901
903
  * @returns Array of VNode and string elements that can be used as children
902
904
  */
903
- declare function tHtml(key: string, params?: Record<string, string>): (VNode | string)[];
905
+ declare function tHtml(key: string, params?: Record<string, string>, defaultValue?: string): (VNode | string)[];
904
906
  /**
905
907
  * Set the current language globally (synchronous)
906
908
  * @param lang Language code
@@ -1509,8 +1511,10 @@ interface DropdownConfig {
1509
1511
  hideArrow?: boolean;
1510
1512
  asIcon?: boolean;
1511
1513
  className?: string;
1514
+ defaultSelected?: string;
1512
1515
  onOpen?: () => void;
1513
1516
  onClose?: () => void;
1517
+ onSelect?: (item: DropdownItemConfig) => void;
1514
1518
  }
1515
1519
  declare class Dropdown extends Component {
1516
1520
  config: DropdownConfig;
package/dist/main.d.ts CHANGED
@@ -810,9 +810,10 @@ declare class I18nManager {
810
810
  *
811
811
  * @param key Translation key
812
812
  * @param params Optional parameters for replacement
813
+ * @param defaultValue Optional default translation key
813
814
  * @returns Array of VNode and string elements that can be used as children
814
815
  */
815
- tHtml(key: string, params?: Record<string, string>): (VNode | string)[];
816
+ tHtml(key: string, params?: Record<string, string>, defaultValue?: string): (VNode | string)[];
816
817
  /**
817
818
  * Parse HTML string into VNode and text elements
818
819
  * Converts \n and /n sequences to <br> tags
@@ -898,9 +899,10 @@ declare function tLang(key: string, lang: string, params?: Record<string, string
898
899
  * Useful for multiline translations with formatting like <br>
899
900
  * @param key Translation key
900
901
  * @param params Optional parameters
902
+ * @param defaultValue Optional default translation key
901
903
  * @returns Array of VNode and string elements that can be used as children
902
904
  */
903
- declare function tHtml(key: string, params?: Record<string, string>): (VNode | string)[];
905
+ declare function tHtml(key: string, params?: Record<string, string>, defaultValue?: string): (VNode | string)[];
904
906
  /**
905
907
  * Set the current language globally (synchronous)
906
908
  * @param lang Language code
@@ -1509,8 +1511,10 @@ interface DropdownConfig {
1509
1511
  hideArrow?: boolean;
1510
1512
  asIcon?: boolean;
1511
1513
  className?: string;
1514
+ defaultSelected?: string;
1512
1515
  onOpen?: () => void;
1513
1516
  onClose?: () => void;
1517
+ onSelect?: (item: DropdownItemConfig) => void;
1514
1518
  }
1515
1519
  declare class Dropdown extends Component {
1516
1520
  config: DropdownConfig;
package/dist/main.js CHANGED
@@ -1,17 +1,17 @@
1
- import {setConfig,patch,html,createElement,createDOMElement}from'@je-es/vdom';export{createDOMElement,createElement,html,patch}from'@je-es/vdom';import {configureApi,api}from'@je-es/capi';export{api,configureApi,getApiConfig,http,resetApiConfig}from'@je-es/capi';var Ee=Object.defineProperty;var p=(s,t,e,n)=>{for(var r=void 0,i=s.length-1,o;i>=0;i--)(o=s[i])&&(r=(o(t,e,r))||r);return r&&Ee(t,e,r),r};var D=class{static{this.styles=new Map;}static{this.scopeCounter=0;}static inject(t,e){let n=e||`style-${this.scopeCounter++}`;if(this.styles.has(n))return n;let r=document.createElement("style");r.setAttribute("data-component",n);let i=this.scopeStyles(t,n);return r.textContent=i,document.head.appendChild(r),this.styles.set(n,r),n}static remove(t){let e=this.styles.get(t);e&&e.parentElement&&(e.parentElement.removeChild(e),this.styles.delete(t));}static scopeStyles(t,e){let n=t.split(`
1
+ import {setConfig,patch,html,createElement,createDOMElement}from'@je-es/vdom';export{createDOMElement,createElement,html,patch}from'@je-es/vdom';import {configureApi,api}from'@je-es/capi';export{api,configureApi,getApiConfig,http,resetApiConfig}from'@je-es/capi';var Ee=Object.defineProperty;var p=(i,t,e,n)=>{for(var r=void 0,s=i.length-1,o;s>=0;s--)(o=i[s])&&(r=(o(t,e,r))||r);return r&&Ee(t,e,r),r};var D=class{static{this.styles=new Map;}static{this.scopeCounter=0;}static inject(t,e){let n=e||`style-${this.scopeCounter++}`;if(this.styles.has(n))return n;let r=document.createElement("style");r.setAttribute("data-component",n);let s=this.scopeStyles(t,n);return r.textContent=s,document.head.appendChild(r),this.styles.set(n,r),n}static remove(t){let e=this.styles.get(t);e&&e.parentElement&&(e.parentElement.removeChild(e),this.styles.delete(t));}static scopeStyles(t,e){let n=t.split(`
2
2
  `),r=[],o=0;for(let a of n){if(a=a.trim(),a.startsWith("@media")){r.push(a);continue}if(o+=(a.match(/{/g)||[]).length,o-=(a.match(/}/g)||[]).length,a.includes("{")&&!a.startsWith("@")&&!a.startsWith("}")){let l=a.substring(0,a.indexOf("{")).trim(),c=a.substring(a.indexOf("{"));if(l===":root"||l==="*"||a.startsWith("@"))r.push(a);else {let u=`[data-scope="${e}"] ${l}`;r.push(`${u} ${c}`);}}else r.push(a);}return r.join(`
3
- `)}static clear(){for(let[,t]of this.styles)t.parentElement&&t.parentElement.removeChild(t);this.styles.clear();}};function be(s,...t){let e="";for(let n=0;n<s.length;n++)e+=s[n],n<t.length&&(e+=t[n]);return e}var ee=class{constructor(){this.queue=new Set;this.isFlushScheduled=false;this.isFlushing=false;}schedule(t){if(this.isFlushing){requestAnimationFrame(()=>this.schedule(t));return}this.queue.add(t),this.isFlushScheduled||(this.isFlushScheduled=true,Promise.resolve().then(()=>{requestAnimationFrame(()=>this.flush());}));}flushSync(t){t();}flush(){if(this.queue.size===0){this.isFlushScheduled=false;return}this.isFlushing=true,this.isFlushScheduled=false;let t=Array.from(this.queue);this.queue.clear();for(let e of t)try{e();}catch(n){console.error("Error during update:",n);}this.isFlushing=false,this.queue.size>0&&this.schedule(()=>{});}clear(){this.queue.clear(),this.isFlushScheduled=false;}get size(){return this.queue.size}},U=new ee;var m=class{constructor(t,e){this._isMounted=false;this._isUnmounting=false;this._element=null;this._vnode=null;this._styleId=null;this._isScheduledForUpdate=false;this._updateBatch=new Set;this._refs=new Map;this._subscriptions=[];this._memoCache=new Map;this._isInitializing=false;this._skipNextUpdate=false;this._preservedElements=new Map;this._updateInProgress=false;this.props=t||{},this.state=e||{};}setState(t,e){if(this._isInitializing){let o=typeof t=="function"?t(this.state):t;this.state={...this.state,...o};return}if(this._isUnmounting)return;let n={...this.state},r=typeof t=="function"?t(this.state):t,i=false;for(let o in r)if(n[o]!==r[o]){i=true;break}if(!i){e&&U.schedule(e);return}this.state={...this.state,...r},this.onStateChange?.(n,this.state),this.update(),e&&U.schedule(e);}setProps(t){if(this._isUnmounting)return;let e={...this.props},n=false;for(let r in t)if(e[r]!==t[r]){n=true;break}n&&(this.props={...this.props,...t},this.onPropsChange?.(e,this.props),this.update());}batchUpdate(t){let e=this._isScheduledForUpdate;this._isScheduledForUpdate=true;try{t();}finally{e||(this._isScheduledForUpdate=false,this.update());}}update(t){if(this._skipNextUpdate){this._skipNextUpdate=false;return}this._isInitializing||this._isUnmounting||!this._isMounted||this._updateInProgress||(t&&this._updateBatch.add(t),!this._isScheduledForUpdate&&(this._isScheduledForUpdate=true,U.schedule(()=>{this._isScheduledForUpdate=false,this._updateBatch.clear(),this._performUpdate();})));}forceUpdate(){!this._isMounted||this._isUnmounting||this._updateInProgress||U.flushSync(()=>{this._performUpdate();});}skipNextUpdate(){this._skipNextUpdate=true;}beginInitialization(){this._isInitializing=true;}endInitialization(){this._isInitializing=false;}async mount(t){if(this._isMounted){console.warn(`Component ${this.constructor.name} is already mounted`);return}if(!t)throw new Error(`Cannot mount ${this.constructor.name}: container is null or undefined`);try{this._isInitializing=!0,await this.onBeforeMount?.(),this._vnode=this.render(),this._element=this._createElementFromVNode(this._vnode),this.styles&&(this._styleId=D.inject(this.styles(),this.constructor.name),this._element?.setAttribute("data-scope",this.constructor.name)),t.appendChild(this._element),this._isMounted=!0,this._isInitializing=!1,await this.onMount?.();}catch(e){throw this._isInitializing=false,this._isMounted=false,this._handleError(e,{componentStack:this.constructor.name}),e}}unmount(){if(!(!this._isMounted||this._isUnmounting)){this._isUnmounting=true;try{this.onBeforeUnmount?.(),this._isScheduledForUpdate=!1,this._updateBatch.clear(),this._styleId&&(D.remove(this._styleId),this._styleId=null),this._subscriptions.forEach(t=>{try{t();}catch(e){console.error("Error during unsubscribe:",e);}}),this._subscriptions=[],this._element?.parentElement&&this._element.parentElement.removeChild(this._element),this._isMounted=!1,this._element=null,this._vnode=null,this.onUnmount?.(),this._refs.clear(),this._memoCache.clear(),this._preservedElements.clear();}catch(t){this._handleError(t,{componentStack:this.constructor.name});}finally{this._isUnmounting=false;}}}getRef(t){return this._refs.get(t)}createRef(t){return e=>{e?this._refs.set(t,e):this._refs.delete(t);}}memo(t,e,n){let r=this._memoCache.get(t);if(r&&this._areDepsEqual(r.args,n))return r.result;let i=e();return this._memoCache.set(t,{args:n,result:i}),i}subscribe(t){this._subscriptions.push(t);}debounce(t,e){let n=null;return (...r)=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{n=null,t.apply(this,r);},e);}}throttle(t,e){let n=0,r=null;return (...i)=>{let o=Date.now(),a=o-n;a>=e?(n=o,t.apply(this,i)):r||(r=setTimeout(()=>{n=Date.now(),r=null,t.apply(this,i);},e-a));}}get element(){return this._element}get isMounted(){return this._isMounted}get isUnmounting(){return this._isUnmounting}get isInitializing(){return this._isInitializing}async _performUpdate(){if(!this._isMounted||!this._element||this._isUnmounting||this._isInitializing||this._updateInProgress)return;this._updateInProgress=true;let t={...this.props},e={...this.state};try{if(this.shouldUpdate&&!this.shouldUpdate(t,e))return;await this.onBeforeUpdate?.(t,e),this._preserveComponentMounts();let n=this.render(),r=this._element.parentElement;if(this._vnode&&r){let i=Array.from(r.childNodes).indexOf(this._element);if(i===-1){console.warn(`Component ${this.constructor.name} element removed from parent, skipping update`);return}let o=this._convertToVDomNode(this._vnode),a=this._convertToVDomNode(n);patch(r,o,a,i),this._element=r.childNodes[i];}this._vnode=n,this._restoreComponentMounts(),this.onUpdate?.(t,e);}catch(n){this._handleError(n,{componentStack:this.constructor.name});}finally{this._updateInProgress=false;}}_preserveComponentMounts(){if(!this._element)return;this._preservedElements.clear(),["[data-language-dropdown-mount]","[data-user-dropdown-mount]","[data-notifications-dropdown-mount]","[data-dropdown-id]","[data-preserve]","[data-toast-mount]","[data-popup-mount]","[data-loader-mount]","[data-navbar-notifications-list]"].forEach(e=>{this._element.querySelectorAll(e).forEach(r=>{r.children.length>0&&r.parentElement&&this._preservedElements.set(r,{parent:r,children:Array.from(r.childNodes)});});});}_restoreComponentMounts(){this._element&&(this._preservedElements.forEach((t,e)=>{let n=null,r=Array.from(e.attributes);for(let i of r)if(i.name.startsWith("data-")){let o=`[${i.name}="${i.value}"]`;if(n=this._element.querySelector(o),n)break}if(n&&t.children.length>0){for(;n.firstChild;)n.removeChild(n.firstChild);t.children.forEach(i=>{n.appendChild(i);});}}),this._preservedElements.clear());}_convertToVDomNode(t){if(typeof t.type!="string")throw new Error("Component VNodes cannot be converted to VDom nodes");let e={};for(let[r,i]of Object.entries(t.props))r!=="children"&&(e[r]=i);let n=t.children.map(r=>r==null||typeof r=="boolean"?null:typeof r=="string"||typeof r=="number"?r:this._convertToVDomNode(r)).filter(r=>r!==null);return {type:t.type,props:e,children:n}}_createElementFromVNode(t){if(typeof t.type!="string")throw new Error("Component VNodes not supported in _createElementFromVNode");let e=document.createElement(t.type);for(let[n,r]of Object.entries(t.props))n!=="children"&&this._setElementProperty(e,n,r);for(let n of t.children)n==null||n===false||(typeof n=="string"||typeof n=="number"?e.appendChild(document.createTextNode(String(n))):typeof n=="object"&&"type"in n&&e.appendChild(this._createElementFromVNode(n)));return e}_setElementProperty(t,e,n){if(e.startsWith("on")&&typeof n=="function"){let r=e.substring(2).toLowerCase();t.addEventListener(r,n);return}if(e==="className"&&typeof n=="string"){t.className=n;return}if(e==="style"){typeof n=="string"?t.setAttribute("style",n):typeof n=="object"&&n!==null&&Object.assign(t.style,n);return}if(e==="ref"&&typeof n=="function"){n(t);return}if(e==="checked"||e==="disabled"||e==="selected"){(n==="true"||n===true||n==="")&&t.setAttribute(e,"");return}n!=null&&n!==false&&t.setAttribute(e,String(n));}_handleError(t,e){if(console.error(`Error in component ${this.constructor.name}:`,t),console.error("Component stack:",e.componentStack),this.onError)this.onError(t,e);else throw t}_areDepsEqual(t,e){return t.length!==e.length?false:t.every((n,r)=>Object.is(n,e[r]))}_invalidateAllComputed(){for(let t in this)t.startsWith("_computed_dirty_")&&(this[t]=true);}_triggerWatchers(t,e,n){let r=this.constructor.__watchers__;if(r?.[t]){for(let i of r[t])if(typeof this[i]=="function")try{this[i].call(this,e,n);}catch(o){console.error(`Watcher error in ${i}:`,o);}}}setElement(t){this._element=t;}};function g(s,t){if(t&&typeof t=="object"&&"kind"in t){let o=t.name;return t.addInitializer(function(){let a=this;a.constructor.__reactiveProps__||(a.constructor.__reactiveProps__=[]),a.constructor.__reactiveProps__.includes(o)||a.constructor.__reactiveProps__.push(o);}),function(a){let l=this,c=`_state_${o}`;return l[c]=a,Object.defineProperty(this,o,{get(){return this[c]},set(u){let d=this,y=d[c];y!==u&&(d[c]=u,typeof d._invalidateAllComputed=="function"&&d._invalidateAllComputed(),typeof d._triggerWatchers=="function"&&d._triggerWatchers(o,u,y),d._isMounted&&typeof d.update=="function"&&d.update());},enumerable:true,configurable:true}),a}}let e=t,n=s.constructor;n.__reactiveProps__||(n.__reactiveProps__=[]),n.__reactiveProps__.includes(e)||n.__reactiveProps__.push(e);let r=`_state_${e}`,i=`_state_init_${e}`;Object.defineProperty(s,e,{get(){let o=this;if(o[i])return o[r]},set(o){let a=this;if(!a[i]){a[r]=o,a[i]=true;return}let l=a[r];l!==o&&(a[r]=o,typeof a._invalidateAllComputed=="function"&&a._invalidateAllComputed(),typeof a._triggerWatchers=="function"&&a._triggerWatchers(e,o,l),a._isMounted&&typeof a.update=="function"&&a.update());},enumerable:true,configurable:true});}function dt(s,t,e){if(t&&typeof t=="object"&&"kind"in t){let a=t;if(a.kind!=="getter")throw new Error("@computed can only be used on getters");let l=s,c=a.name,u=`_computed_cache_${c}`,d=`_computed_dirty_${c}`;return function(){let y=this;return y[d]===void 0&&(y[d]=true),y[d]===true&&(y[u]=l.call(this),y[d]=false),y[u]}}let n=t;if(!e)throw new Error("@computed requires a property descriptor");let r=e.get;if(!r)throw new Error("@computed can only be used on getters");let i=`_computed_cache_${n}`,o=`_computed_dirty_${n}`;return {get(){let a=this;return a[o]===void 0&&(a[o]=true),a[o]===true&&(a[i]=r.call(this),a[o]=false),a[i]},enumerable:e.enumerable,configurable:e.configurable}}function ht(s){function t(e,n,r){if(n&&typeof n=="object"&&"kind"in n){if(n.kind!=="method")throw new Error("@watch can only be used on methods");let l=n.name;n.addInitializer(function(){let c=this;c.constructor.__watchers__||(c.constructor.__watchers__={}),c.constructor.__watchers__[s]||(c.constructor.__watchers__[s]=[]),c.constructor.__watchers__[s].includes(l)||c.constructor.__watchers__[s].push(l);});return}let i=n;if(!r)throw new Error("@watch requires a property descriptor");let a=e.constructor;return a.__watchers__||(a.__watchers__={}),a.__watchers__[s]||(a.__watchers__[s]=[]),a.__watchers__[s].includes(i)||a.__watchers__[s].push(i),r}return t}var G=class{constructor(t){this._subscribers=new Set;this._value=t,this._defaultValue=t;}get value(){return this._value}set value(t){this._value!==t&&(this._value=t,this._notify());}subscribe(t){this._subscribers.add(t);try{t(this._value);}catch(e){console.error("Context subscriber error:",e);}return ()=>{this._subscribers.delete(t);}}reset(){this.value=this._defaultValue;}update(t){this.value=t(this._value);}_notify(){for(let t of this._subscribers)try{t(this._value);}catch(e){console.error("Context subscriber error:",e);}}get subscriberCount(){return this._subscribers.size}};function mt(s){return new G(s)}var ve=class extends m{onMount(){this.props.context.value=this.props.value;}onUpdate(){this.props.context.value=this.props.value;}onUnmount(){}render(){let t=Array.isArray(this.props.children)?this.props.children:[this.props.children];return html`
3
+ `)}static clear(){for(let[,t]of this.styles)t.parentElement&&t.parentElement.removeChild(t);this.styles.clear();}};function be(i,...t){let e="";for(let n=0;n<i.length;n++)e+=i[n],n<t.length&&(e+=t[n]);return e}var ee=class{constructor(){this.queue=new Set;this.isFlushScheduled=false;this.isFlushing=false;}schedule(t){if(this.isFlushing){requestAnimationFrame(()=>this.schedule(t));return}this.queue.add(t),this.isFlushScheduled||(this.isFlushScheduled=true,Promise.resolve().then(()=>{requestAnimationFrame(()=>this.flush());}));}flushSync(t){t();}flush(){if(this.queue.size===0){this.isFlushScheduled=false;return}this.isFlushing=true,this.isFlushScheduled=false;let t=Array.from(this.queue);this.queue.clear();for(let e of t)try{e();}catch(n){console.error("Error during update:",n);}this.isFlushing=false,this.queue.size>0&&this.schedule(()=>{});}clear(){this.queue.clear(),this.isFlushScheduled=false;}get size(){return this.queue.size}},U=new ee;var m=class{constructor(t,e){this._isMounted=false;this._isUnmounting=false;this._element=null;this._vnode=null;this._styleId=null;this._isScheduledForUpdate=false;this._updateBatch=new Set;this._refs=new Map;this._subscriptions=[];this._memoCache=new Map;this._isInitializing=false;this._skipNextUpdate=false;this._preservedElements=new Map;this._updateInProgress=false;this.props=t||{},this.state=e||{};}setState(t,e){if(this._isInitializing){let o=typeof t=="function"?t(this.state):t;this.state={...this.state,...o};return}if(this._isUnmounting)return;let n={...this.state},r=typeof t=="function"?t(this.state):t,s=false;for(let o in r)if(n[o]!==r[o]){s=true;break}if(!s){e&&U.schedule(e);return}this.state={...this.state,...r},this.onStateChange?.(n,this.state),this.update(),e&&U.schedule(e);}setProps(t){if(this._isUnmounting)return;let e={...this.props},n=false;for(let r in t)if(e[r]!==t[r]){n=true;break}n&&(this.props={...this.props,...t},this.onPropsChange?.(e,this.props),this.update());}batchUpdate(t){let e=this._isScheduledForUpdate;this._isScheduledForUpdate=true;try{t();}finally{e||(this._isScheduledForUpdate=false,this.update());}}update(t){if(this._skipNextUpdate){this._skipNextUpdate=false;return}this._isInitializing||this._isUnmounting||!this._isMounted||this._updateInProgress||(t&&this._updateBatch.add(t),!this._isScheduledForUpdate&&(this._isScheduledForUpdate=true,U.schedule(()=>{this._isScheduledForUpdate=false,this._updateBatch.clear(),this._performUpdate();})));}forceUpdate(){!this._isMounted||this._isUnmounting||this._updateInProgress||U.flushSync(()=>{this._performUpdate();});}skipNextUpdate(){this._skipNextUpdate=true;}beginInitialization(){this._isInitializing=true;}endInitialization(){this._isInitializing=false;}async mount(t){if(this._isMounted){console.warn(`Component ${this.constructor.name} is already mounted`);return}if(!t)throw new Error(`Cannot mount ${this.constructor.name}: container is null or undefined`);try{this._isInitializing=!0,await this.onBeforeMount?.(),this._vnode=this.render(),this._element=this._createElementFromVNode(this._vnode),this.styles&&(this._styleId=D.inject(this.styles(),this.constructor.name),this._element?.setAttribute("data-scope",this.constructor.name)),t.appendChild(this._element),this._isMounted=!0,this._isInitializing=!1,await this.onMount?.();}catch(e){throw this._isInitializing=false,this._isMounted=false,this._handleError(e,{componentStack:this.constructor.name}),e}}unmount(){if(!(!this._isMounted||this._isUnmounting)){this._isUnmounting=true;try{this.onBeforeUnmount?.(),this._isScheduledForUpdate=!1,this._updateBatch.clear(),this._styleId&&(D.remove(this._styleId),this._styleId=null),this._subscriptions.forEach(t=>{try{t();}catch(e){console.error("Error during unsubscribe:",e);}}),this._subscriptions=[],this._element?.parentElement&&this._element.parentElement.removeChild(this._element),this._isMounted=!1,this._element=null,this._vnode=null,this.onUnmount?.(),this._refs.clear(),this._memoCache.clear(),this._preservedElements.clear();}catch(t){this._handleError(t,{componentStack:this.constructor.name});}finally{this._isUnmounting=false;}}}getRef(t){return this._refs.get(t)}createRef(t){return e=>{e?this._refs.set(t,e):this._refs.delete(t);}}memo(t,e,n){let r=this._memoCache.get(t);if(r&&this._areDepsEqual(r.args,n))return r.result;let s=e();return this._memoCache.set(t,{args:n,result:s}),s}subscribe(t){this._subscriptions.push(t);}debounce(t,e){let n=null;return (...r)=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{n=null,t.apply(this,r);},e);}}throttle(t,e){let n=0,r=null;return (...s)=>{let o=Date.now(),a=o-n;a>=e?(n=o,t.apply(this,s)):r||(r=setTimeout(()=>{n=Date.now(),r=null,t.apply(this,s);},e-a));}}get element(){return this._element}get isMounted(){return this._isMounted}get isUnmounting(){return this._isUnmounting}get isInitializing(){return this._isInitializing}async _performUpdate(){if(!this._isMounted||!this._element||this._isUnmounting||this._isInitializing||this._updateInProgress)return;this._updateInProgress=true;let t={...this.props},e={...this.state};try{if(this.shouldUpdate&&!this.shouldUpdate(t,e))return;await this.onBeforeUpdate?.(t,e),this._preserveComponentMounts();let n=this.render(),r=this._element.parentElement;if(this._vnode&&r){let s=Array.from(r.childNodes).indexOf(this._element);if(s===-1){console.warn(`Component ${this.constructor.name} element removed from parent, skipping update`);return}let o=this._convertToVDomNode(this._vnode),a=this._convertToVDomNode(n);patch(r,o,a,s),this._element=r.childNodes[s];}this._vnode=n,this._restoreComponentMounts(),this.onUpdate?.(t,e);}catch(n){this._handleError(n,{componentStack:this.constructor.name});}finally{this._updateInProgress=false;}}_preserveComponentMounts(){if(!this._element)return;this._preservedElements.clear(),["[data-language-dropdown-mount]","[data-user-dropdown-mount]","[data-notifications-dropdown-mount]","[data-dropdown-id]","[data-preserve]","[data-toast-mount]","[data-popup-mount]","[data-loader-mount]","[data-navbar-notifications-list]"].forEach(e=>{this._element.querySelectorAll(e).forEach(r=>{r.children.length>0&&r.parentElement&&this._preservedElements.set(r,{parent:r,children:Array.from(r.childNodes)});});});}_restoreComponentMounts(){this._element&&(this._preservedElements.forEach((t,e)=>{let n=null,r=Array.from(e.attributes);for(let s of r)if(s.name.startsWith("data-")){let o=`[${s.name}="${s.value}"]`;if(n=this._element.querySelector(o),n)break}if(n&&t.children.length>0){for(;n.firstChild;)n.removeChild(n.firstChild);t.children.forEach(s=>{n.appendChild(s);});}}),this._preservedElements.clear());}_convertToVDomNode(t){if(typeof t.type!="string")throw new Error("Component VNodes cannot be converted to VDom nodes");let e={};for(let[r,s]of Object.entries(t.props))r!=="children"&&(e[r]=s);let n=t.children.map(r=>r==null||typeof r=="boolean"?null:typeof r=="string"||typeof r=="number"?r:this._convertToVDomNode(r)).filter(r=>r!==null);return {type:t.type,props:e,children:n}}_createElementFromVNode(t){if(typeof t.type!="string")throw new Error("Component VNodes not supported in _createElementFromVNode");let e=document.createElement(t.type);for(let[n,r]of Object.entries(t.props))n!=="children"&&this._setElementProperty(e,n,r);for(let n of t.children)n==null||n===false||(typeof n=="string"||typeof n=="number"?e.appendChild(document.createTextNode(String(n))):typeof n=="object"&&"type"in n&&e.appendChild(this._createElementFromVNode(n)));return e}_setElementProperty(t,e,n){if(e.startsWith("on")&&typeof n=="function"){let r=e.substring(2).toLowerCase();t.addEventListener(r,n);return}if(e==="className"&&typeof n=="string"){t.className=n;return}if(e==="style"){typeof n=="string"?t.setAttribute("style",n):typeof n=="object"&&n!==null&&Object.assign(t.style,n);return}if(e==="ref"&&typeof n=="function"){n(t);return}if(e==="checked"||e==="disabled"||e==="selected"){(n==="true"||n===true||n==="")&&t.setAttribute(e,"");return}n!=null&&n!==false&&t.setAttribute(e,String(n));}_handleError(t,e){if(console.error(`Error in component ${this.constructor.name}:`,t),console.error("Component stack:",e.componentStack),this.onError)this.onError(t,e);else throw t}_areDepsEqual(t,e){return t.length!==e.length?false:t.every((n,r)=>Object.is(n,e[r]))}_invalidateAllComputed(){for(let t in this)t.startsWith("_computed_dirty_")&&(this[t]=true);}_triggerWatchers(t,e,n){let r=this.constructor.__watchers__;if(r?.[t]){for(let s of r[t])if(typeof this[s]=="function")try{this[s].call(this,e,n);}catch(o){console.error(`Watcher error in ${s}:`,o);}}}setElement(t){this._element=t;}};function g(i,t){if(t&&typeof t=="object"&&"kind"in t){let o=t.name;return t.addInitializer(function(){let a=this;a.constructor.__reactiveProps__||(a.constructor.__reactiveProps__=[]),a.constructor.__reactiveProps__.includes(o)||a.constructor.__reactiveProps__.push(o);}),function(a){let l=this,c=`_state_${o}`;return l[c]=a,Object.defineProperty(this,o,{get(){return this[c]},set(u){let d=this,y=d[c];y!==u&&(d[c]=u,typeof d._invalidateAllComputed=="function"&&d._invalidateAllComputed(),typeof d._triggerWatchers=="function"&&d._triggerWatchers(o,u,y),d._isMounted&&typeof d.update=="function"&&d.update());},enumerable:true,configurable:true}),a}}let e=t,n=i.constructor;n.__reactiveProps__||(n.__reactiveProps__=[]),n.__reactiveProps__.includes(e)||n.__reactiveProps__.push(e);let r=`_state_${e}`,s=`_state_init_${e}`;Object.defineProperty(i,e,{get(){let o=this;if(o[s])return o[r]},set(o){let a=this;if(!a[s]){a[r]=o,a[s]=true;return}let l=a[r];l!==o&&(a[r]=o,typeof a._invalidateAllComputed=="function"&&a._invalidateAllComputed(),typeof a._triggerWatchers=="function"&&a._triggerWatchers(e,o,l),a._isMounted&&typeof a.update=="function"&&a.update());},enumerable:true,configurable:true});}function dt(i,t,e){if(t&&typeof t=="object"&&"kind"in t){let a=t;if(a.kind!=="getter")throw new Error("@computed can only be used on getters");let l=i,c=a.name,u=`_computed_cache_${c}`,d=`_computed_dirty_${c}`;return function(){let y=this;return y[d]===void 0&&(y[d]=true),y[d]===true&&(y[u]=l.call(this),y[d]=false),y[u]}}let n=t;if(!e)throw new Error("@computed requires a property descriptor");let r=e.get;if(!r)throw new Error("@computed can only be used on getters");let s=`_computed_cache_${n}`,o=`_computed_dirty_${n}`;return {get(){let a=this;return a[o]===void 0&&(a[o]=true),a[o]===true&&(a[s]=r.call(this),a[o]=false),a[s]},enumerable:e.enumerable,configurable:e.configurable}}function ht(i){function t(e,n,r){if(n&&typeof n=="object"&&"kind"in n){if(n.kind!=="method")throw new Error("@watch can only be used on methods");let l=n.name;n.addInitializer(function(){let c=this;c.constructor.__watchers__||(c.constructor.__watchers__={}),c.constructor.__watchers__[i]||(c.constructor.__watchers__[i]=[]),c.constructor.__watchers__[i].includes(l)||c.constructor.__watchers__[i].push(l);});return}let s=n;if(!r)throw new Error("@watch requires a property descriptor");let a=e.constructor;return a.__watchers__||(a.__watchers__={}),a.__watchers__[i]||(a.__watchers__[i]=[]),a.__watchers__[i].includes(s)||a.__watchers__[i].push(s),r}return t}var G=class{constructor(t){this._subscribers=new Set;this._value=t,this._defaultValue=t;}get value(){return this._value}set value(t){this._value!==t&&(this._value=t,this._notify());}subscribe(t){this._subscribers.add(t);try{t(this._value);}catch(e){console.error("Context subscriber error:",e);}return ()=>{this._subscribers.delete(t);}}reset(){this.value=this._defaultValue;}update(t){this.value=t(this._value);}_notify(){for(let t of this._subscribers)try{t(this._value);}catch(e){console.error("Context subscriber error:",e);}}get subscriberCount(){return this._subscribers.size}};function mt(i){return new G(i)}var ve=class extends m{onMount(){this.props.context.value=this.props.value;}onUpdate(){this.props.context.value=this.props.value;}onUnmount(){}render(){let t=Array.isArray(this.props.children)?this.props.children:[this.props.children];return html`
4
4
  <div class="context-provider" style="display: contents;">
5
5
  ${t}
6
6
  </div>
7
- `}};function bt(s,t){let e=s.subscribe(()=>{t.isMounted&&t.update();});return t.subscribe(()=>e),s.value}var te=class{constructor(t){this.contexts=new Map;for(let[e,n]of Object.entries(t))this.contexts.set(e,new G(n));}get(t){let e=this.contexts.get(t);if(!e)throw new Error(`Context key "${String(t)}" not found`);return e}set(t,e){let n=this.contexts.get(t);n&&(n.value=e);}subscribe(t,e){let n=this.contexts.get(t);if(!n)throw new Error(`Context key "${String(t)}" not found`);return n.subscribe(e)}reset(){for(let t of this.contexts.values())t.reset();}};function vt(s){return new te(s)}var L=null,A=0,ne=new WeakMap;function Me(s){L=s,A=0;}function Pe(){L=null,A=0;}function J(s){return ne.has(s)||ne.set(s,[]),ne.get(s)}function N(s){if(!L)throw new Error("useState must be called inside a component");let t=L,e=A++,n=J(t);n[e]===void 0&&(n[e]={value:typeof s=="function"?s():s});let r=i=>{let o=n[e],a=typeof i=="function"?i(o.value):i;o.value!==a&&(o.value=a,t.update());};return [n[e].value,r]}function O(s,t){if(!L)throw new Error("useEffect must be called inside a component");let e=L,n=A++,r=J(e),i=r[n];if(!i||!t||!ye(i.deps,t)){if(i?.value&&typeof i.value=="function")try{i.value();}catch(a){console.error("Error in effect cleanup:",a);}Promise.resolve().then(()=>{try{let a=s();r[n]={value:a,deps:t?[...t]:void 0};}catch(a){console.error("Error in effect:",a);}});}}function Ie(s,t){if(!L)throw new Error("useMemo must be called inside a component");let e=A++,n=J(L),r=n[e];return (!r||!ye(r.deps,t))&&(n[e]={value:s(),deps:[...t]}),n[e].value}function re(s,t){return Ie(()=>s,t)}function se(s){if(!L)throw new Error("useRef must be called inside a component");let t=A++,e=J(L);return e[t]===void 0&&(e[t]={value:{current:s}}),e[t].value}function Tt(s,t){let[e,n]=N(t),r=re(i=>{n(o=>s(o,i));},[s]);return [e,r]}function _t(s,t){let[e,n]=N(()=>{try{let i=window.localStorage.getItem(s);return i?JSON.parse(i):t}catch(i){return console.error("Error loading from localStorage:",i),t}});return [e,i=>{n(o=>{let a=i instanceof Function?i(o):i;try{window.localStorage.setItem(s,JSON.stringify(a));}catch(l){console.error("Error saving to localStorage:",l);}return a});}]}function Ct(s,t){let[e,n]=N(s);return O(()=>{let r=setTimeout(()=>{n(s);},t);return ()=>{clearTimeout(r);}},[s,t]),e}function St(s){let t=se(void 0);return O(()=>{t.current=s;}),t.current}function Et(s=false){let[t,e]=N(s),n=re(()=>{e(r=>!r);},[]);return [t,n]}function xt(s,t){let e=se(s);O(()=>{e.current=s;},[s]),O(()=>{if(t===null)return;let n=setInterval(()=>e.current(),t);return ()=>clearInterval(n)},[t]);}function kt(s,t){let[e,n]=N(null),[r,i]=N(true),[o,a]=N(null),l=re(async()=>{i(true),a(null);try{let c=await fetch(s,t);if(!c.ok)throw new Error(`HTTP error! status: ${c.status}`);let u=await c.json();n(u);}catch(c){a(c);}finally{i(false);}},[s]);return O(()=>{l();},[l]),{data:e,loading:r,error:o,refetch:l}}function Lt(){let[s,t]=N({width:window.innerWidth,height:window.innerHeight});return O(()=>{let e=()=>{t({width:window.innerWidth,height:window.innerHeight});};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),s}function Mt(s,t,e=window){let n=se(t);O(()=>{n.current=t;},[t]),O(()=>{if(!(e&&"addEventListener"in e))return;let i=o=>{n.current(o);};return e.addEventListener(s,i),()=>{e.removeEventListener(s,i);}},[s,e]);}function Pt(s,t){class e extends m{render(){Me(this);try{return s(this.props)}finally{Pe();}}}return t&&Object.defineProperty(e,"name",{value:t}),e}function ye(s,t){if(!s||s.length!==t.length)return false;for(let e=0;e<s.length;e++)if(s[e]!==t[e])return false;return true}var ie=class{constructor(){this.routes=[];this.currentRoute=null;this.mode="history";this.base="/";this.beforeEachHooks=[];this.afterEachHooks=[];this.currentComponent=null;this.routerOutlet=null;this.isNavigating=false;this.scrollBehavior="auto";this.notFoundHandler=null;this._internalPath=null;}init(t,e="history",n="/",r="auto"){this.routes=t,this.mode=e,this.base=n.endsWith("/")?n.slice(0,-1):n,this.scrollBehavior=r,this._initializeRouting(),this._handleRoute();}async push(t,e){this.isNavigating&&(this.isNavigating=false),this._internalPath=t,this.mode==="history"?window.history.pushState(e||{},"",this._buildFullPath(t)):window.location.hash=t,await this._handleRoute();}async replace(t,e){return this._internalPath=t,this.mode==="history"?window.history.replaceState(e||{},"",this._buildFullPath(t)):window.location.hash=t,this._handleRoute()}back(){window.history.back();}forward(){window.history.forward();}go(t){window.history.go(t);}beforeEach(t){this.beforeEachHooks.push(t);}afterEach(t){this.afterEachHooks.push(t);}onNotFound(t){this.notFoundHandler=t;}getCurrentRoute(){return this.currentRoute?{...this.currentRoute}:null}isActive(t,e=false){return this.currentRoute?e?this.currentRoute.path===t:this.currentRoute.path.startsWith(t):false}outlet(){return createElement("div",{"data-router-outlet":"true",style:"display: contents;"})}getRoute(t){return this.routes.find(e=>e.name===t)}async pushNamed(t,e){let n=this.getRoute(t);if(!n){console.error(`Route with name "${t}" not found`);return}let r=n.path;if(e)for(let[i,o]of Object.entries(e))r=r.replace(`:${i}`,o);return this.push(r)}resolve(t){let e=this._matchRoute(t);if(!e)return null;let{route:n,params:r}=e;return {path:t,params:r,query:this._parseQuery(t),meta:n.meta||{},hash:t.includes("#")?t.split("#")[1]:"",name:n.name}}_initializeRouting(){window.addEventListener("popstate",()=>{this._internalPath=null,this._handleRoute();}),this.mode==="hash"&&window.addEventListener("hashchange",()=>{this._internalPath=null,this._handleRoute();}),document.addEventListener("click",t=>{let e=t.target.closest("a[href]");if(e&&this._shouldInterceptLink(e)){t.preventDefault();let n=e.getAttribute("href");if(n){let r=this.mode==="hash"&&n.startsWith("#")?n.substring(1):n.replace(this.base,"");this.push(r);}}});}_shouldInterceptLink(t){return !!(t.getAttribute("href")&&t.hostname===window.location.hostname&&t.target!=="_blank"&&!t.hasAttribute("download")&&t.rel!=="external")}async _handleRoute(){if(!this.isNavigating){this.isNavigating=true;try{let t=this._getCurrentPath(),e=this._matchRoute(t);if(!e){this._handleNotFound(t);return}let{route:n,params:r}=e,i=this._buildRouteObject(t,r,n),o=this.currentRoute||this._buildEmptyRoute();if(!await this._runNavigationGuards(n,i,o))return;this.currentRoute=i,await this._renderComponent(n),this._handleScrollBehavior(i,o),n.meta?.title&&typeof n.meta.title=="string"&&(document.title=n.meta.title),this.afterEachHooks.forEach(l=>l(i,o));}catch(t){console.error("Router error:",t);}finally{this.isNavigating=false;}}}_handleNotFound(t){console.warn(`No route matched for path: ${t}`),this.currentRoute={path:t,params:{},query:this._parseQuery(),meta:{},hash:window.location.hash.substring(1)},this.notFoundHandler&&this.notFoundHandler();}_buildRouteObject(t,e,n){return {path:t,params:e,query:this._parseQuery(),meta:n.meta||{},hash:window.location.hash.substring(1),name:n.name}}_buildEmptyRoute(){return {path:"",params:{},query:{},meta:{},hash:""}}async _runNavigationGuards(t,e,n){if(t.beforeEnter&&!await this._runGuard(t.beforeEnter,e,n))return false;for(let r of this.beforeEachHooks)if(!await this._runGuard(r,e,n))return false;return true}_runGuard(t,e,n){return new Promise(r=>{t(e,n,i=>{i===false?r(false):typeof i=="string"?(this.push(i),r(false)):r(true);});})}async _renderComponent(t){if(!this.routerOutlet&&(this.routerOutlet=document.querySelector('[data-router-outlet="true"]'),!this.routerOutlet)){console.warn("Router outlet not found");return}this.currentComponent&&(this.currentComponent.unmount(),this.currentComponent=null),this.routerOutlet.innerHTML="";try{let e=await this._resolveComponent(t.component);if(!e||typeof e!="function")throw new Error("Component is null or not a constructor");let n=e;this.currentComponent=new n,this.currentComponent&&await this.currentComponent.mount(this.routerOutlet);}catch(e){throw this._renderError(t.path,e),e}}async _resolveComponent(t){if(typeof t=="function"){let n="prototype"in t&&t.prototype?t.prototype:null;if(n&&typeof n=="object"&&"constructor"in n&&n.constructor===t)return t;try{let i=await t();return i.HomePage||i.TodoPage||i.default||Object.values(i).find(a=>{if(typeof a!="function")return !1;let c=a.prototype;return c!==null&&typeof c=="object"&&c!==void 0&&"constructor"in c})||null}catch(i){return console.error("Failed to load lazy component:",i),null}}return null}_renderError(t,e){if(this.routerOutlet){let n=e instanceof Error?e.message:String(e);this.routerOutlet.innerHTML=`
7
+ `}};function bt(i,t){let e=i.subscribe(()=>{t.isMounted&&t.update();});return t.subscribe(()=>e),i.value}var te=class{constructor(t){this.contexts=new Map;for(let[e,n]of Object.entries(t))this.contexts.set(e,new G(n));}get(t){let e=this.contexts.get(t);if(!e)throw new Error(`Context key "${String(t)}" not found`);return e}set(t,e){let n=this.contexts.get(t);n&&(n.value=e);}subscribe(t,e){let n=this.contexts.get(t);if(!n)throw new Error(`Context key "${String(t)}" not found`);return n.subscribe(e)}reset(){for(let t of this.contexts.values())t.reset();}};function vt(i){return new te(i)}var L=null,A=0,ne=new WeakMap;function Me(i){L=i,A=0;}function Pe(){L=null,A=0;}function J(i){return ne.has(i)||ne.set(i,[]),ne.get(i)}function N(i){if(!L)throw new Error("useState must be called inside a component");let t=L,e=A++,n=J(t);n[e]===void 0&&(n[e]={value:typeof i=="function"?i():i});let r=s=>{let o=n[e],a=typeof s=="function"?s(o.value):s;o.value!==a&&(o.value=a,t.update());};return [n[e].value,r]}function O(i,t){if(!L)throw new Error("useEffect must be called inside a component");let e=L,n=A++,r=J(e),s=r[n];if(!s||!t||!ye(s.deps,t)){if(s?.value&&typeof s.value=="function")try{s.value();}catch(a){console.error("Error in effect cleanup:",a);}Promise.resolve().then(()=>{try{let a=i();r[n]={value:a,deps:t?[...t]:void 0};}catch(a){console.error("Error in effect:",a);}});}}function Ie(i,t){if(!L)throw new Error("useMemo must be called inside a component");let e=A++,n=J(L),r=n[e];return (!r||!ye(r.deps,t))&&(n[e]={value:i(),deps:[...t]}),n[e].value}function re(i,t){return Ie(()=>i,t)}function ie(i){if(!L)throw new Error("useRef must be called inside a component");let t=A++,e=J(L);return e[t]===void 0&&(e[t]={value:{current:i}}),e[t].value}function Tt(i,t){let[e,n]=N(t),r=re(s=>{n(o=>i(o,s));},[i]);return [e,r]}function _t(i,t){let[e,n]=N(()=>{try{let s=window.localStorage.getItem(i);return s?JSON.parse(s):t}catch(s){return console.error("Error loading from localStorage:",s),t}});return [e,s=>{n(o=>{let a=s instanceof Function?s(o):s;try{window.localStorage.setItem(i,JSON.stringify(a));}catch(l){console.error("Error saving to localStorage:",l);}return a});}]}function Ct(i,t){let[e,n]=N(i);return O(()=>{let r=setTimeout(()=>{n(i);},t);return ()=>{clearTimeout(r);}},[i,t]),e}function St(i){let t=ie(void 0);return O(()=>{t.current=i;}),t.current}function Et(i=false){let[t,e]=N(i),n=re(()=>{e(r=>!r);},[]);return [t,n]}function xt(i,t){let e=ie(i);O(()=>{e.current=i;},[i]),O(()=>{if(t===null)return;let n=setInterval(()=>e.current(),t);return ()=>clearInterval(n)},[t]);}function kt(i,t){let[e,n]=N(null),[r,s]=N(true),[o,a]=N(null),l=re(async()=>{s(true),a(null);try{let c=await fetch(i,t);if(!c.ok)throw new Error(`HTTP error! status: ${c.status}`);let u=await c.json();n(u);}catch(c){a(c);}finally{s(false);}},[i]);return O(()=>{l();},[l]),{data:e,loading:r,error:o,refetch:l}}function Lt(){let[i,t]=N({width:window.innerWidth,height:window.innerHeight});return O(()=>{let e=()=>{t({width:window.innerWidth,height:window.innerHeight});};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),i}function Mt(i,t,e=window){let n=ie(t);O(()=>{n.current=t;},[t]),O(()=>{if(!(e&&"addEventListener"in e))return;let s=o=>{n.current(o);};return e.addEventListener(i,s),()=>{e.removeEventListener(i,s);}},[i,e]);}function Pt(i,t){class e extends m{render(){Me(this);try{return i(this.props)}finally{Pe();}}}return t&&Object.defineProperty(e,"name",{value:t}),e}function ye(i,t){if(!i||i.length!==t.length)return false;for(let e=0;e<i.length;e++)if(i[e]!==t[e])return false;return true}var se=class{constructor(){this.routes=[];this.currentRoute=null;this.mode="history";this.base="/";this.beforeEachHooks=[];this.afterEachHooks=[];this.currentComponent=null;this.routerOutlet=null;this.isNavigating=false;this.scrollBehavior="auto";this.notFoundHandler=null;this._internalPath=null;}init(t,e="history",n="/",r="auto"){this.routes=t,this.mode=e,this.base=n.endsWith("/")?n.slice(0,-1):n,this.scrollBehavior=r,this._initializeRouting(),this._handleRoute();}async push(t,e){this.isNavigating&&(this.isNavigating=false),this._internalPath=t,this.mode==="history"?window.history.pushState(e||{},"",this._buildFullPath(t)):window.location.hash=t,await this._handleRoute();}async replace(t,e){return this._internalPath=t,this.mode==="history"?window.history.replaceState(e||{},"",this._buildFullPath(t)):window.location.hash=t,this._handleRoute()}back(){window.history.back();}forward(){window.history.forward();}go(t){window.history.go(t);}beforeEach(t){this.beforeEachHooks.push(t);}afterEach(t){this.afterEachHooks.push(t);}onNotFound(t){this.notFoundHandler=t;}getCurrentRoute(){return this.currentRoute?{...this.currentRoute}:null}isActive(t,e=false){return this.currentRoute?e?this.currentRoute.path===t:this.currentRoute.path.startsWith(t):false}outlet(){return createElement("div",{"data-router-outlet":"true",style:"display: contents;"})}getRoute(t){return this.routes.find(e=>e.name===t)}async pushNamed(t,e){let n=this.getRoute(t);if(!n){console.error(`Route with name "${t}" not found`);return}let r=n.path;if(e)for(let[s,o]of Object.entries(e))r=r.replace(`:${s}`,o);return this.push(r)}resolve(t){let e=this._matchRoute(t);if(!e)return null;let{route:n,params:r}=e;return {path:t,params:r,query:this._parseQuery(t),meta:n.meta||{},hash:t.includes("#")?t.split("#")[1]:"",name:n.name}}_initializeRouting(){window.addEventListener("popstate",()=>{this._internalPath=null,this._handleRoute();}),this.mode==="hash"&&window.addEventListener("hashchange",()=>{this._internalPath=null,this._handleRoute();}),document.addEventListener("click",t=>{let e=t.target.closest("a[href]");if(e&&this._shouldInterceptLink(e)){t.preventDefault();let n=e.getAttribute("href");if(n){let r=this.mode==="hash"&&n.startsWith("#")?n.substring(1):n.replace(this.base,"");this.push(r);}}});}_shouldInterceptLink(t){return !!(t.getAttribute("href")&&t.hostname===window.location.hostname&&t.target!=="_blank"&&!t.hasAttribute("download")&&t.rel!=="external")}async _handleRoute(){if(!this.isNavigating){this.isNavigating=true;try{let t=this._getCurrentPath(),e=this._matchRoute(t);if(!e){this._handleNotFound(t);return}let{route:n,params:r}=e,s=this._buildRouteObject(t,r,n),o=this.currentRoute||this._buildEmptyRoute();if(!await this._runNavigationGuards(n,s,o))return;this.currentRoute=s,await this._renderComponent(n),this._handleScrollBehavior(s,o),n.meta?.title&&typeof n.meta.title=="string"&&(document.title=n.meta.title),this.afterEachHooks.forEach(l=>l(s,o));}catch(t){console.error("Router error:",t);}finally{this.isNavigating=false;}}}_handleNotFound(t){console.warn(`No route matched for path: ${t}`),this.currentRoute={path:t,params:{},query:this._parseQuery(),meta:{},hash:window.location.hash.substring(1)},this.notFoundHandler&&this.notFoundHandler();}_buildRouteObject(t,e,n){return {path:t,params:e,query:this._parseQuery(),meta:n.meta||{},hash:window.location.hash.substring(1),name:n.name}}_buildEmptyRoute(){return {path:"",params:{},query:{},meta:{},hash:""}}async _runNavigationGuards(t,e,n){if(t.beforeEnter&&!await this._runGuard(t.beforeEnter,e,n))return false;for(let r of this.beforeEachHooks)if(!await this._runGuard(r,e,n))return false;return true}_runGuard(t,e,n){return new Promise(r=>{t(e,n,s=>{s===false?r(false):typeof s=="string"?(this.push(s),r(false)):r(true);});})}async _renderComponent(t){if(!this.routerOutlet&&(this.routerOutlet=document.querySelector('[data-router-outlet="true"]'),!this.routerOutlet)){console.warn("Router outlet not found");return}this.currentComponent&&(this.currentComponent.unmount(),this.currentComponent=null),this.routerOutlet.innerHTML="";try{let e=await this._resolveComponent(t.component);if(!e||typeof e!="function")throw new Error("Component is null or not a constructor");let n=e;this.currentComponent=new n,this.currentComponent&&await this.currentComponent.mount(this.routerOutlet);}catch(e){throw this._renderError(t.path,e),e}}async _resolveComponent(t){if(typeof t=="function"){let n="prototype"in t&&t.prototype?t.prototype:null;if(n&&typeof n=="object"&&"constructor"in n&&n.constructor===t)return t;try{let s=await t();return s.HomePage||s.TodoPage||s.default||Object.values(s).find(a=>{if(typeof a!="function")return !1;let c=a.prototype;return c!==null&&typeof c=="object"&&c!==void 0&&"constructor"in c})||null}catch(s){return console.error("Failed to load lazy component:",s),null}}return null}_renderError(t,e){if(this.routerOutlet){let n=e instanceof Error?e.message:String(e);this.routerOutlet.innerHTML=`
8
8
  <div style="padding: 2rem; background: #121212ff; border: 2px solid #303030ff;
9
9
  border-radius: 8px; margin: 2rem;">
10
10
  <h2 style="color: rgba(208, 31, 31, 1); margin-top: 0;">\u26A0\uFE0F Failed to Load Component</h2>
11
11
  <p style="color: #a3a3a3ff;"><strong>Route:</strong> ${t}</p>
12
12
  <p style="color: #a3a3a3ff;"><strong>Error:</strong> ${n}</p>
13
13
  </div>
14
- `;}}_handleScrollBehavior(t,e){if(t.hash){let n=document.getElementById(t.hash);if(n){n.scrollIntoView({behavior:this.scrollBehavior});return}}t.path!==e.path&&window.scrollTo({top:0,behavior:this.scrollBehavior});}_getCurrentPath(){if(this._internalPath!==null)return this._internalPath;if(this.mode==="hash")return window.location.hash.substring(1).split("?")[0]||"/";let t=window.location.pathname;return (!t||t==="blank"||t==="about:blank")&&(t="/"),this.base&&t.startsWith(this.base)&&(t=t.substring(this.base.length)),t||"/"}_buildFullPath(t){if(t.startsWith("http"))return t;let e=t.startsWith("/")?t:"/"+t;return this.base+e}_matchRoute(t){let e=t.split("?")[0].split("#")[0];for(let n of this.routes){let r=this._matchPath(n.path,e);if(r!==null)return {route:n,params:r}}return null}_matchPath(t,e){if(t==="*")return {};if(t===e)return {};let n=[],r=t.replace(/\*/g,".*").replace(/:([^/]+)/g,(a,l)=>(n.push(l),"([^/]+)")),i=new RegExp(`^${r}$`),o=e.match(i);return o?n.reduce((a,l,c)=>(a[l]=decodeURIComponent(o[c+1]),a),{}):null}_parseQuery(t){let e=t?t.includes("?")?t.split("?")[1].split("#")[0]:"":window.location.search.substring(1);return e?e.split("&").reduce((n,r)=>{let[i,o]=r.split("=").map(decodeURIComponent);return i&&(n[i]=o||""),n},{}):{}}},R=new ie;function we(s,t=false){t?R.replace(s):R.push(s),window.dispatchEvent(new CustomEvent("navigation",{detail:{path:s}}));}function Ot(){R.back();}function Rt(){window.history.forward();}function oe(){return window.location.pathname}function $t(s){return oe()===s}function Vt(s){return oe().startsWith(s)}function Ft(){let s=oe();we(s,true);}function Kt(s,t){let e=new URLSearchParams(t).toString();we(`${s}?${e}`);}function Oe(){return new URLSearchParams(window.location.search)}function At(s){return Oe().get(s)}var ae=class{constructor(t){this._subscribers=new Set;this._storage=null;this._middleware=[];this._isHydrating=false;if(this._persist=t.persist??false,this._storageKey=t.storageKey||`store_${Date.now()}`,this._persist&&typeof window<"u"&&(this._storage=t.storage==="sessionStorage"?sessionStorage:localStorage),this._persist&&this._storage){let e=this._loadFromStorage();this._state=e!==null?e:t.state;}else this._state=t.state;t.middleware&&(this._middleware=t.middleware);}get state(){return {...this._state}}set state(t){this.setState(t);}setState(t,e){let n={...this._state},r=typeof t=="function"?t(n):t;this._state={...n,...r};for(let i of this._middleware)try{i(this._state,e);}catch(o){console.error("Store middleware error:",o);}this._persist&&!this._isHydrating&&this._saveToStorage(),this._notify();}get(t){return this._state[t]}set(t,e,n){this.setState({[t]:e},n);}subscribe(t){return this._subscribers.add(t),t(this._state),()=>{this._subscribers.delete(t);}}subscribeToKey(t,e){let n=this._state[t],r=i=>{let o=i[t];n!==o&&(n=o,e(o));};return this.subscribe(r)}use(t){this._middleware.push(t);}clear(){if(this._state={},this._persist&&this._storage)try{this._storage.removeItem(this._storageKey);}catch(t){console.error("Failed to clear storage:",t);}this._notify();}reset(t){this._state={...t},this._persist&&this._saveToStorage(),this._notify();}hydrate(){if(!this._persist||!this._storage){console.warn("Cannot hydrate: persistence not enabled");return}this._isHydrating=true;let t=this._loadFromStorage();t!==null&&(this._state=t,this._notify()),this._isHydrating=false;}getSnapshot(){return {state:{...this._state},subscribers:this._subscribers.size,storageKey:this._storageKey}}batch(t){let e=this._notify.bind(this),n=false;this._notify=()=>{n=true;};try{t();}finally{this._notify=e,n&&this._notify();}}_notify(){let t={...this._state};for(let e of this._subscribers)try{e(t);}catch(n){console.error("Store subscriber error:",n);}}_loadFromStorage(){if(!this._storage)return null;try{let t=this._storage.getItem(this._storageKey);return t?JSON.parse(t):null}catch(t){return console.error("Failed to load from storage:",t),null}}_saveToStorage(){if(this._storage)try{this._storage.setItem(this._storageKey,JSON.stringify(this._state));}catch(t){console.error("Failed to save to storage:",t),t instanceof DOMException&&t.name==="QuotaExceededError"&&console.warn("Storage quota exceeded");}}destroy(){this._subscribers.clear(),this._middleware=[],this._state={};}};function Re(s){return new ae(s)}function Dt(s,t){let e=Re({state:{value:t(...s.map(n=>n.state))}});for(let n of s)n.subscribe(()=>{e.setState({value:t(...s.map(r=>r.state))});});return e}function Ut(s,t,e){return s.subscribe(r=>{let i=e(r);Object.assign(t,i),typeof t.update=="function"&&t.update();})}function qt(s){let t=s;return {async build(){if(!t.build){console.warn("No build configuration provided");return}console.log("\u{1F528} Building @je-es/client application...");try{await this._buildJS(),await this._buildStyles(),console.log("\u2705 Build completed successfully!");}catch(e){throw console.error("\u274C Build error:",e),e}},async _buildJS(){if(!t.build)return;let e=await Bun.build({entrypoints:[t.build.entry],outdir:t.build.output.substring(0,t.build.output.lastIndexOf("/")),target:"browser",minify:t.build.minify??false,sourcemap:t.build.sourcemap?"external":"none",splitting:t.build.optimization?.splitChunks??false,naming:{entry:t.build.output.substring(t.build.output.lastIndexOf("/")+1)},external:["sass","fs","path","url","util","stream","buffer","events","crypto","os","child_process"]});if(!e.success)throw console.error("\u274C JS Build failed:",e.logs),new Error("JS Build failed")},async _buildStyles(){let e=t.build?.styles?.input||"./app/gui/style",n=t.build?.styles?.output||"./static/client.css",r=await import('sass'),{writeFileSync:i,existsSync:o,mkdirSync:a}=await import('fs'),{join:l,dirname:c}=await import('path'),u=c(n),d=n.split("/").pop()||"client.css",y=l(e,"index.scss");if(!o(y)){console.log("\u26A0\uFE0F No index.scss found, skipping CSS build");return}try{o(u)||a(u,{recursive:!0});let K=r.compile(y,{style:t.build?.minify?"compressed":"expanded",sourceMap:!!t.build?.sourcemap,loadPaths:[e]}),me=l(u,d);i(me,K.css,"utf-8"),t.build?.sourcemap&&K.sourceMap&&i(`${me}.map`,JSON.stringify(K.sourceMap),"utf-8");}catch(K){throw console.error("\u274C CSS Build failed:",K),K}},async _collectScssFiles(e){let{readdirSync:n,statSync:r,existsSync:i}=await import('fs'),{join:o,extname:a}=await import('path'),l=[];if(!i(e))return l;let c=n(e);for(let u of c){let d=o(e,u),y=r(d);y.isDirectory()?l.push(...await this._collectScssFiles(d)):y.isFile()&&a(u)===".scss"&&!u.startsWith("_")&&l.push(d);}return l.sort()},async watch(){console.log("\u{1F440} Watching for changes..."),await this.build();let{watch:e}=await import('fs'),{dirname:n}=await import('path'),{existsSync:r}=await import('fs');if(t.build?.entry){let o=n(t.build.entry);e(o,{recursive:true},async(a,l)=>{if(l&&(l.endsWith(".ts")||l.endsWith(".tsx"))){console.log(`\u{1F504} ${l} changed, rebuilding JS...`);try{await this._buildJS(),console.log("\u2705 JS rebuild complete");}catch(c){console.error("\u274C JS rebuild failed:",c);}}});}let i="./app/style";r(i)&&e(i,{recursive:true},async(o,a)=>{if(a&&a.endsWith(".scss")){console.log(`\u{1F504} ${a} changed, rebuilding CSS...`);try{await this._buildStyles(),console.log("\u2705 CSS rebuild complete");}catch(l){console.error("\u274C CSS rebuild failed:",l);}}});},async init(){if(console.log("\u{1F680} [client] Initializing @je-es/client..."),t.api){let e={baseURL:t.api.baseURL,timeout:t.api.timeout,headers:t.api.headers};t.api.interceptors&&(e.interceptors={request:t.api.interceptors.request||null,response:t.api.interceptors.response||null,error:t.api.interceptors.error||null}),configureApi(e);}t.router&&t.app?.routes&&(R.init(t.app.routes,t.router.mode,t.router.base),t.router.beforeEach&&R.beforeEach(t.router.beforeEach),t.router.afterEach&&R.afterEach(t.router.afterEach)),t.app?.root&&(document.querySelector(t.app.root)||console.error(`\u274C Root element "${t.app.root}" not found`)),t.devTools?.enabled&&this._enableDevTools();},_enableDevTools(){window.__JEES_DEV__={router:R,config:t,version:"0.0.1"};},getConfig(){return t}}}var z=class{constructor(t){this.translations={};this.currentLanguage="en";this.defaultLanguage="en";this.supportedLanguages=new Set(["en"]);this.cachePath="";this.readyListeners=[];t&&(this.defaultLanguage=t.defaultLanguage||"en",this.cachePath=t.staticPath||"static/i18n",this.currentLanguage=this.getStoredLanguage()||t.defaultLanguage||"en",t.supportedLanguages&&(this.supportedLanguages=new Set(t.supportedLanguages)));}loadLanguage(t,e){this.translations[t]||(this.translations[t]={}),this.translations[t]={...this.translations[t],...e},this.supportedLanguages.add(t);}loadTranslations(t){Object.entries(t).forEach(([e,n])=>{this.loadLanguage(e,n);});}setLanguage(t){this.supportedLanguages.has(t)?(this.currentLanguage=t,this.storeLanguage(t),this.dispatchLanguageChangeEvent()):this.supportedLanguages.has(this.defaultLanguage)&&(this.currentLanguage=this.defaultLanguage);}getLanguage(){return this.currentLanguage}getSupportedLanguages(){return Array.from(this.supportedLanguages)}t(t,e,n){let r=this.currentLanguage,i=this.getTranslation(t,n);return e&&Object.entries(e).forEach(([o,a])=>{let l=this.translations[r]?.[a]||this.translations[this.defaultLanguage]?.[a]||a;i=i.replace(new RegExp(`\\{${o}\\}`,"g"),l);}),i}getTranslation(t,e){let n=this.currentLanguage;return this.translations[n]?.[t]?this.translations[n]?.[t]||this.translations[this.defaultLanguage]?.[t]:(console.warn(`Translation key not found: ${t}`),e||t)}tLang(t,e,n){let r=this.currentLanguage;this.currentLanguage=e;let i=this.t(t,n);return this.currentLanguage=r,i}tHtml(t,e){let n=this.t(t,e);return this.parseHtmlString(n)}parseHtmlString(t){let e=t.replace(/\\n|\/n/g,"<br>"),n=[],r=/<([^/>]+)>([^<]*)<\/\1>|<([^/>]+)\s*\/?>|([^<]+)/g,i;for(;(i=r.exec(e))!==null;){let o=i[1],a=i[2],l=i[3],c=i[4];if(c)n.push(c);else if(o){let u=o.split(/\s+/)[0].toLowerCase();n.push(createElement(u,{},a));}else if(l){let u=l.trim().toLowerCase();n.push(createElement(u,{}));}}return n.length>0?n:[t]}getTranslations(){return this.translations[this.currentLanguage]||{}}hasKey(t){return !!(this.translations[this.currentLanguage]?.[t]||this.translations[this.defaultLanguage]?.[t])}createTranslator(t){let e=()=>t();return typeof window<"u"?(window.addEventListener("languagechange",e),()=>window.removeEventListener("languagechange",e)):()=>{}}async loadFromUrl(t){let e=Array.isArray(t)?t:[t],n={};for(let r of e)if(r.includes("*")){let i=r.replace("*.json",""),o=this.supportedLanguages;for(let a of o)try{let l=`${i}${a}.json`;typeof window<"u"&&!l.startsWith("http")&&(l=window.location.origin+(l.startsWith("/")?l:"/"+l));let c=await fetch(l);if(c.ok){let u=await c.json();n[a]=u;}}catch{}}else try{let i=r;typeof window<"u"&&!i.startsWith("http")&&(i=window.location.origin+(i.startsWith("/")?i:"/"+i));let o=await fetch(i);if(o.ok){let a=await o.json(),l=r.match(/([a-z]{2,3})\.json$/i),c=l?l[1].toLowerCase():"en";n[c]=a,this.supportedLanguages.add(c);}}catch{}Object.keys(n).length>0&&(this.loadTranslations(n),this.notifyReady());}onReady(t){Object.keys(this.translations).length>0?t():this.readyListeners.push(t);}notifyReady(){for(let t of this.readyListeners)t();this.readyListeners=[];}getStoredLanguage(){return typeof localStorage<"u"&&localStorage.getItem("app-language")||null}storeLanguage(t){typeof localStorage<"u"&&localStorage.setItem("app-language",t);}dispatchLanguageChangeEvent(){typeof window<"u"&&window.dispatchEvent(new CustomEvent("languagechange",{detail:{language:this.currentLanguage}}));}},B=null;function S(){return B||(B=new z),B}function h(s,t,e){return S().t(s,t,e)}function Jt(s,t,e){return S().tLang(s,t,e)}function le(s,t){return S().tHtml(s,t)}function Qt(s){S().setLanguage(s);}async function Yt(s,t){let e=S(),n=e.getTranslations();if(!(Object.keys(n).length>0)&&t){let i=t.endsWith("/")?t:t+"/";try{await e.loadFromUrl(i+`${s}.json`);}catch(o){console.warn(`Failed to lazy-load language: ${s}`,o);}}e.setLanguage(s);}function Zt(){return S().getLanguage()}function Xt(s,t){S().loadLanguage(s,t);}function en(s){S().loadTranslations(s);}function tn(){return S().getSupportedLanguages()}function nn(s){return S().hasKey(s)}function rn(){return S().getTranslations()}function sn(s){return S().createTranslator(s)}async function on(s){return S().loadFromUrl(s)}function an(s){B=new z(s);}async function ln(s){let t=new z(s);if(B=t,s.staticPath){let e=s.staticPath.endsWith("/")?s.staticPath:s.staticPath+"/",n=t.getLanguage(),r=e+`${n}.json`;await t.loadFromUrl(r);}}async function cn(s,t){let e=S(),n=t||"static/i18n",i=(n.endsWith("/")?n:n+"/")+s+".json";await e.loadFromUrl(i);}var j={toast:"bb_toast",container:"bb_toastContainer",icon:"bb_toastIcon",msg:"bb_toastMsg"},Y=class extends m{constructor(){super(...arguments);this.messages=[];this.nextId=0;}show(e,n="info",r=2e3,i){let o=this.nextId++;this.messages=[...this.messages,{id:o,message:e,type:n,translateKey:i}],setTimeout(()=>{this.messages=this.messages.filter(a=>a.id!==o);},r);}success(e,n,r){this.show(e,"success",n,r);}error(e,n,r){this.show(e,"error",n,r);}info(e,n,r){this.show(e,"info",n,r);}warning(e,n,r){this.show(e,"warning",n,r);}render(){return this.messages.length===0?html``:createElement("div",{className:j.container},...this.messages.map(e=>this.renderToast(e)))}renderToast(e){let n={success:"fas fa-check-circle",error:"fas fa-exclamation-circle",info:"fas fa-info-circle",warning:"fas fa-exclamation-triangle"},r=e.translateKey?h(e.translateKey):e.message;return createElement("div",{key:String(e.id),className:`${j.toast} ${j.toast}--${e.type}`,"data-translate":e.translateKey||void 0},createElement("i",{className:`${n[e.type]} ${j.icon}`}),createElement("span",{className:j.msg},r))}};p([g],Y.prototype,"messages");var $=null;function Fe(s){if($)return $;let t=s||document.createElement("div");return s||document.body.appendChild(t),$=new Y,$.mount(t),$}function q(){return $||($=Fe()),$}var fn={show:(s,t="info",e,n)=>{q().show(s,t,e,n);},success:(s,t,e)=>{q().success(s,t,e);},error:(s,t,e)=>{q().error(s,t,e);},info:(s,t,e)=>{q().info(s,t,e);},warning:(s,t,e)=>{q().warning(s,t,e);}};var T={loader:{container:"bb_loaderContainer",containerOverlay:"bb_loaderContainer--overlay",bg:"bb_loaderBg",loader:"bb_loader"},spinner:{container:"bb_loaderSpinnerContainer",icon:"bb_loaderSpinnerIcon",dot:"bb_loaderSpinnerDot",pulse:"bb_loaderSpinnerPulse",text:"bb_loaderSpinnerText"},progress:{container:"bb_loaderProgressContainer",bar:"bb_loaderProgressBar",text:"bb_loaderProgressText"}},I=class extends m{constructor(){super(...arguments);this.visible=false;this.message="";this.variant="spinner";this.size="medium";this.overlay=true;this.progress=0;this.showProgress=false;this.animationFrame=null;this.hideTimeout=null;this.handleKeyPress=e=>{e.key==="Escape"&&this.visible&&!this.overlay&&this.hide();};}async onMount(){this.setupKeyboardListener(),this.initializeAccessibility(),window.addEventListener("languagechange",()=>{this.message||this.update();});}onUnmount(){this.animationFrame&&cancelAnimationFrame(this.animationFrame),this.hideTimeout&&clearTimeout(this.hideTimeout),document.removeEventListener("keydown",this.handleKeyPress);}render(){let e=[T.loader.container,this.overlay?`${T.loader.containerOverlay}`:"",`${T.loader.container}--${this.size}`].filter(Boolean).join(" ");return createElement("div",{className:e,"data-status":this.visible?"visible":"hidden",role:"status","aria-live":"polite","aria-busy":"true"},createElement("div",{className:T.loader.bg}),createElement("div",{className:T.loader.loader},this.renderSpinner(),this.renderMessage(),this.showProgress?this.renderProgressBar():null))}renderSpinner(){let e=`${T.spinner.container} ${T.spinner.container}--${this.variant}`;switch(this.variant){case "dots":return createElement("div",{className:e},createElement("div",{className:T.spinner.dot}),createElement("div",{className:T.spinner.dot}),createElement("div",{className:T.spinner.dot}));case "pulse":return createElement("div",{className:e},createElement("div",{className:T.spinner.pulse}));case "spinner":default:return createElement("div",{className:e},createElement("div",{className:T.spinner.icon}))}}renderMessage(){let e=this.message||h("global.loading");return createElement("div",{className:T.spinner.text,"data-translate":this.message?void 0:"global.loading"},e)}renderProgressBar(){return createElement("div",{className:T.progress.container},createElement("div",{className:T.progress.bar,style:`width: ${this.progress}%`,"aria-valuenow":this.progress.toString(),"aria-valuemin":"0","aria-valuemax":"100"}),createElement("div",{className:T.progress.text},`${Math.round(this.progress)}%`))}show(e){typeof e=="string"?this.message=e:e&&(this.message=e.message||"",this.variant=e.variant||"spinner",this.size=e.size||"medium",this.overlay=e.overlay!==void 0?e.overlay:true),this.visible=true,this.progress=0,this.showProgress=false,this.applyBodyLock(),this.update();}hide(e=0){this.hideTimeout&&clearTimeout(this.hideTimeout),e>0?this.hideTimeout=window.setTimeout(()=>{this.performHide();},e):this.performHide();}setMessage(e){this.message=e,this.update();}setProgress(e){this.showProgress=true,this.progress=Math.max(0,Math.min(100,e)),this.update();}updateProgress(e){this.setProgress(this.progress+e);}performHide(){this.visible=false,this.message="",this.progress=0,this.showProgress=false,this.removeBodyLock(),this.update();}applyBodyLock(){this.overlay&&(document.body.style.overflow="hidden");}removeBodyLock(){document.body.style.overflow="";}setupKeyboardListener(){this.handleKeyPress=this.handleKeyPress.bind(this),document.addEventListener("keydown",this.handleKeyPress);}initializeAccessibility(){let e=this.element?.querySelector(`.${T.spinner.container}`);e&&e.setAttribute("aria-label",h("loading"));}isVisible(){return this.visible}getStatus(){return {visible:this.visible,message:this.message,progress:this.progress}}};p([g],I.prototype,"visible"),p([g],I.prototype,"message"),p([g],I.prototype,"variant"),p([g],I.prototype,"size"),p([g],I.prototype,"overlay"),p([g],I.prototype,"progress"),p([g],I.prototype,"showProgress");var V=class extends m{constructor(e){super(e);this.fields=[];this.formData={};this.isSubmitting=false;this.submitError="";this.submitSuccess=false;this.fields=this.props.fields.map(n=>({...n,error:void 0,touched:false}));for(let n of this.fields)this.formData[n.name]=n.value||"";}onMount(){}handleChange(e,n){this.formData[e]=n;let r=this.fields.find(i=>i.name===e);r&&this.props.autoValidate&&(r.error=this.validateField(r,n),r.touched=true),this.update();}handleBlur(e){let n=this.fields.find(r=>r.name===e);n&&(n.touched=true,n.error=this.validateField(n,this.formData[e]),this.update());}validateField(e,n){let r=e.validation;if(!r)return;if(r.required&&!n)return r.message||`${e.label||e.name} is required`;if(!n)return;let i=String(n);if(r.minLength&&i.length<r.minLength)return r.message||`Minimum ${r.minLength} characters required`;if(r.maxLength&&i.length>r.maxLength)return r.message||`Maximum ${r.maxLength} characters allowed`;if(r.min!==void 0&&Number(n)<r.min)return r.message||`Minimum value is ${r.min}`;if(r.max!==void 0&&Number(n)>r.max)return r.message||`Maximum value is ${r.max}`;if(r.pattern&&!r.pattern.test(i))return r.message||"Invalid format";if(r.email&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i))return r.message||"Invalid email format";if(r.url&&!/^https?:\/\/.+/.test(i))return r.message||"Invalid URL format";if(r.custom){let o=r.custom(n);if(o!==true)return typeof o=="string"?o:void 0}}validateForm(){let e=true,n={};for(let r of this.fields){let i=this.validateField(r,this.formData[r.name]);r.error=i,r.touched=true,i&&(e=false,n[r.name]=i);}return this.update(),!e&&this.props.onValidationError&&this.props.onValidationError(n),e}async handleSubmit(e){if(e.preventDefault(),!this.validateForm()){let n=this.fields.find(r=>r.error);n&&document.querySelector(`[name="${n.name}"]`)?.focus();return}this.isSubmitting=true,this.submitError="",this.submitSuccess=false,this.update();try{if(this.props.onSubmit)await this.props.onSubmit(this.formData,e);else if(this.props.endpoint){let n=await api({method:this.props.method||"POST",url:this.props.endpoint,data:this.formData});this.submitSuccess=!0,this.props.onSuccess&&this.props.onSuccess(n.data);}}catch(n){let r=n instanceof Error?n.message:h("global.loading");this.submitError=r,this.props.onError&&this.props.onError(n);}finally{this.isSubmitting=false,this.update();}}renderLabel(e){return !e.label&&!e.icon?"":e.icon?html`
14
+ `;}}_handleScrollBehavior(t,e){if(t.hash){let n=document.getElementById(t.hash);if(n){n.scrollIntoView({behavior:this.scrollBehavior});return}}t.path!==e.path&&window.scrollTo({top:0,behavior:this.scrollBehavior});}_getCurrentPath(){if(this._internalPath!==null)return this._internalPath;if(this.mode==="hash")return window.location.hash.substring(1).split("?")[0]||"/";let t=window.location.pathname;return (!t||t==="blank"||t==="about:blank")&&(t="/"),this.base&&t.startsWith(this.base)&&(t=t.substring(this.base.length)),t||"/"}_buildFullPath(t){if(t.startsWith("http"))return t;let e=t.startsWith("/")?t:"/"+t;return this.base+e}_matchRoute(t){let e=t.split("?")[0].split("#")[0];for(let n of this.routes){let r=this._matchPath(n.path,e);if(r!==null)return {route:n,params:r}}return null}_matchPath(t,e){if(t==="*")return {};if(t===e)return {};let n=[],r=t.replace(/\*/g,".*").replace(/:([^/]+)/g,(a,l)=>(n.push(l),"([^/]+)")),s=new RegExp(`^${r}$`),o=e.match(s);return o?n.reduce((a,l,c)=>(a[l]=decodeURIComponent(o[c+1]),a),{}):null}_parseQuery(t){let e=t?t.includes("?")?t.split("?")[1].split("#")[0]:"":window.location.search.substring(1);return e?e.split("&").reduce((n,r)=>{let[s,o]=r.split("=").map(decodeURIComponent);return s&&(n[s]=o||""),n},{}):{}}},R=new se;function we(i,t=false){t?R.replace(i):R.push(i),window.dispatchEvent(new CustomEvent("navigation",{detail:{path:i}}));}function Ot(){R.back();}function Rt(){window.history.forward();}function oe(){return window.location.pathname}function $t(i){return oe()===i}function Vt(i){return oe().startsWith(i)}function Ft(){let i=oe();we(i,true);}function Kt(i,t){let e=new URLSearchParams(t).toString();we(`${i}?${e}`);}function Oe(){return new URLSearchParams(window.location.search)}function At(i){return Oe().get(i)}var ae=class{constructor(t){this._subscribers=new Set;this._storage=null;this._middleware=[];this._isHydrating=false;if(this._persist=t.persist??false,this._storageKey=t.storageKey||`store_${Date.now()}`,this._persist&&typeof window<"u"&&(this._storage=t.storage==="sessionStorage"?sessionStorage:localStorage),this._persist&&this._storage){let e=this._loadFromStorage();this._state=e!==null?e:t.state;}else this._state=t.state;t.middleware&&(this._middleware=t.middleware);}get state(){return {...this._state}}set state(t){this.setState(t);}setState(t,e){let n={...this._state},r=typeof t=="function"?t(n):t;this._state={...n,...r};for(let s of this._middleware)try{s(this._state,e);}catch(o){console.error("Store middleware error:",o);}this._persist&&!this._isHydrating&&this._saveToStorage(),this._notify();}get(t){return this._state[t]}set(t,e,n){this.setState({[t]:e},n);}subscribe(t){return this._subscribers.add(t),t(this._state),()=>{this._subscribers.delete(t);}}subscribeToKey(t,e){let n=this._state[t],r=s=>{let o=s[t];n!==o&&(n=o,e(o));};return this.subscribe(r)}use(t){this._middleware.push(t);}clear(){if(this._state={},this._persist&&this._storage)try{this._storage.removeItem(this._storageKey);}catch(t){console.error("Failed to clear storage:",t);}this._notify();}reset(t){this._state={...t},this._persist&&this._saveToStorage(),this._notify();}hydrate(){if(!this._persist||!this._storage){console.warn("Cannot hydrate: persistence not enabled");return}this._isHydrating=true;let t=this._loadFromStorage();t!==null&&(this._state=t,this._notify()),this._isHydrating=false;}getSnapshot(){return {state:{...this._state},subscribers:this._subscribers.size,storageKey:this._storageKey}}batch(t){let e=this._notify.bind(this),n=false;this._notify=()=>{n=true;};try{t();}finally{this._notify=e,n&&this._notify();}}_notify(){let t={...this._state};for(let e of this._subscribers)try{e(t);}catch(n){console.error("Store subscriber error:",n);}}_loadFromStorage(){if(!this._storage)return null;try{let t=this._storage.getItem(this._storageKey);return t?JSON.parse(t):null}catch(t){return console.error("Failed to load from storage:",t),null}}_saveToStorage(){if(this._storage)try{this._storage.setItem(this._storageKey,JSON.stringify(this._state));}catch(t){console.error("Failed to save to storage:",t),t instanceof DOMException&&t.name==="QuotaExceededError"&&console.warn("Storage quota exceeded");}}destroy(){this._subscribers.clear(),this._middleware=[],this._state={};}};function Re(i){return new ae(i)}function Dt(i,t){let e=Re({state:{value:t(...i.map(n=>n.state))}});for(let n of i)n.subscribe(()=>{e.setState({value:t(...i.map(r=>r.state))});});return e}function Ut(i,t,e){return i.subscribe(r=>{let s=e(r);Object.assign(t,s),typeof t.update=="function"&&t.update();})}function qt(i){let t=i;return {async build(){if(!t.build){console.warn("No build configuration provided");return}console.log("\u{1F528} Building @je-es/client application...");try{await this._buildJS(),await this._buildStyles(),console.log("\u2705 Build completed successfully!");}catch(e){throw console.error("\u274C Build error:",e),e}},async _buildJS(){if(!t.build)return;let e=await Bun.build({entrypoints:[t.build.entry],outdir:t.build.output.substring(0,t.build.output.lastIndexOf("/")),target:"browser",minify:t.build.minify??false,sourcemap:t.build.sourcemap?"external":"none",splitting:t.build.optimization?.splitChunks??false,naming:{entry:t.build.output.substring(t.build.output.lastIndexOf("/")+1)},external:["sass","fs","path","url","util","stream","buffer","events","crypto","os","child_process"]});if(!e.success)throw console.error("\u274C JS Build failed:",e.logs),new Error("JS Build failed")},async _buildStyles(){let e=t.build?.styles?.input||"./app/gui/style",n=t.build?.styles?.output||"./static/client.css",r=await import('sass'),{writeFileSync:s,existsSync:o,mkdirSync:a}=await import('fs'),{join:l,dirname:c}=await import('path'),u=c(n),d=n.split("/").pop()||"client.css",y=l(e,"index.scss");if(!o(y)){console.log("\u26A0\uFE0F No index.scss found, skipping CSS build");return}try{o(u)||a(u,{recursive:!0});let K=r.compile(y,{style:t.build?.minify?"compressed":"expanded",sourceMap:!!t.build?.sourcemap,loadPaths:[e]}),me=l(u,d);s(me,K.css,"utf-8"),t.build?.sourcemap&&K.sourceMap&&s(`${me}.map`,JSON.stringify(K.sourceMap),"utf-8");}catch(K){throw console.error("\u274C CSS Build failed:",K),K}},async _collectScssFiles(e){let{readdirSync:n,statSync:r,existsSync:s}=await import('fs'),{join:o,extname:a}=await import('path'),l=[];if(!s(e))return l;let c=n(e);for(let u of c){let d=o(e,u),y=r(d);y.isDirectory()?l.push(...await this._collectScssFiles(d)):y.isFile()&&a(u)===".scss"&&!u.startsWith("_")&&l.push(d);}return l.sort()},async watch(){console.log("\u{1F440} Watching for changes..."),await this.build();let{watch:e}=await import('fs'),{dirname:n}=await import('path'),{existsSync:r}=await import('fs');if(t.build?.entry){let o=n(t.build.entry);e(o,{recursive:true},async(a,l)=>{if(l&&(l.endsWith(".ts")||l.endsWith(".tsx"))){console.log(`\u{1F504} ${l} changed, rebuilding JS...`);try{await this._buildJS(),console.log("\u2705 JS rebuild complete");}catch(c){console.error("\u274C JS rebuild failed:",c);}}});}let s="./app/style";r(s)&&e(s,{recursive:true},async(o,a)=>{if(a&&a.endsWith(".scss")){console.log(`\u{1F504} ${a} changed, rebuilding CSS...`);try{await this._buildStyles(),console.log("\u2705 CSS rebuild complete");}catch(l){console.error("\u274C CSS rebuild failed:",l);}}});},async init(){if(console.log("\u{1F680} [client] Initializing @je-es/client..."),t.api){let e={baseURL:t.api.baseURL,timeout:t.api.timeout,headers:t.api.headers};t.api.interceptors&&(e.interceptors={request:t.api.interceptors.request||null,response:t.api.interceptors.response||null,error:t.api.interceptors.error||null}),configureApi(e);}t.router&&t.app?.routes&&(R.init(t.app.routes,t.router.mode,t.router.base),t.router.beforeEach&&R.beforeEach(t.router.beforeEach),t.router.afterEach&&R.afterEach(t.router.afterEach)),t.app?.root&&(document.querySelector(t.app.root)||console.error(`\u274C Root element "${t.app.root}" not found`)),t.devTools?.enabled&&this._enableDevTools();},_enableDevTools(){window.__JEES_DEV__={router:R,config:t,version:"0.0.1"};},getConfig(){return t}}}var z=class{constructor(t){this.translations={};this.currentLanguage="en";this.defaultLanguage="en";this.supportedLanguages=new Set(["en"]);this.cachePath="";this.readyListeners=[];t&&(this.defaultLanguage=t.defaultLanguage||"en",this.cachePath=t.staticPath||"static/i18n",this.currentLanguage=this.getStoredLanguage()||t.defaultLanguage||"en",t.supportedLanguages&&(this.supportedLanguages=new Set(t.supportedLanguages)));}loadLanguage(t,e){this.translations[t]||(this.translations[t]={}),this.translations[t]={...this.translations[t],...e},this.supportedLanguages.add(t);}loadTranslations(t){Object.entries(t).forEach(([e,n])=>{this.loadLanguage(e,n);});}setLanguage(t){this.supportedLanguages.has(t)?(this.currentLanguage=t,this.storeLanguage(t),this.dispatchLanguageChangeEvent()):this.supportedLanguages.has(this.defaultLanguage)&&(this.currentLanguage=this.defaultLanguage);}getLanguage(){return this.currentLanguage}getSupportedLanguages(){return Array.from(this.supportedLanguages)}t(t,e,n){let r=this.currentLanguage,s=this.getTranslation(t,n);return e&&Object.entries(e).forEach(([o,a])=>{let l=this.translations[r]?.[a]||this.translations[this.defaultLanguage]?.[a]||a;s=s.replace(new RegExp(`\\{${o}\\}`,"g"),l);}),s}getTranslation(t,e){let n=this.currentLanguage;return this.translations[n]?.[t]?this.translations[n]?.[t]||this.translations[this.defaultLanguage]?.[t]:(console.warn(`Translation key not found: ${t}`),e||t)}tLang(t,e,n){let r=this.currentLanguage;this.currentLanguage=e;let s=this.t(t,n);return this.currentLanguage=r,s}tHtml(t,e,n){let r=this.t(t,e,n);return this.parseHtmlString(r)}parseHtmlString(t){let e=t.replace(/\\n|\/n/g,"<br>"),n=[],r=/<([^/>]+)>([^<]*)<\/\1>|<([^/>]+)\s*\/?>|([^<]+)/g,s;for(;(s=r.exec(e))!==null;){let o=s[1],a=s[2],l=s[3],c=s[4];if(c)n.push(c);else if(o){let u=o.split(/\s+/)[0].toLowerCase();n.push(createElement(u,{},a));}else if(l){let u=l.trim().toLowerCase();n.push(createElement(u,{}));}}return n.length>0?n:[t]}getTranslations(){return this.translations[this.currentLanguage]||{}}hasKey(t){return !!(this.translations[this.currentLanguage]?.[t]||this.translations[this.defaultLanguage]?.[t])}createTranslator(t){let e=()=>t();return typeof window<"u"?(window.addEventListener("languagechange",e),()=>window.removeEventListener("languagechange",e)):()=>{}}async loadFromUrl(t){let e=Array.isArray(t)?t:[t],n={};for(let r of e)if(r.includes("*")){let s=r.replace("*.json",""),o=this.supportedLanguages;for(let a of o)try{let l=`${s}${a}.json`;typeof window<"u"&&!l.startsWith("http")&&(l=window.location.origin+(l.startsWith("/")?l:"/"+l));let c=await fetch(l);if(c.ok){let u=await c.json();n[a]=u;}}catch{}}else try{let s=r;typeof window<"u"&&!s.startsWith("http")&&(s=window.location.origin+(s.startsWith("/")?s:"/"+s));let o=await fetch(s);if(o.ok){let a=await o.json(),l=r.match(/([a-z]{2,3})\.json$/i),c=l?l[1].toLowerCase():"en";n[c]=a,this.supportedLanguages.add(c);}}catch{}Object.keys(n).length>0&&(this.loadTranslations(n),this.notifyReady());}onReady(t){Object.keys(this.translations).length>0?t():this.readyListeners.push(t);}notifyReady(){for(let t of this.readyListeners)t();this.readyListeners=[];}getStoredLanguage(){return typeof localStorage<"u"&&localStorage.getItem("app-language")||null}storeLanguage(t){typeof localStorage<"u"&&localStorage.setItem("app-language",t);}dispatchLanguageChangeEvent(){typeof window<"u"&&window.dispatchEvent(new CustomEvent("languagechange",{detail:{language:this.currentLanguage}}));}},B=null;function S(){return B||(B=new z),B}function h(i,t,e){return S().t(i,t,e)}function Jt(i,t,e){return S().tLang(i,t,e)}function le(i,t,e){return S().tHtml(i,t,e)}function Qt(i){S().setLanguage(i);}async function Yt(i,t){let e=S(),n=e.getTranslations();if(!(Object.keys(n).length>0)&&t){let s=t.endsWith("/")?t:t+"/";try{await e.loadFromUrl(s+`${i}.json`);}catch(o){console.warn(`Failed to lazy-load language: ${i}`,o);}}e.setLanguage(i);}function Zt(){return S().getLanguage()}function Xt(i,t){S().loadLanguage(i,t);}function en(i){S().loadTranslations(i);}function tn(){return S().getSupportedLanguages()}function nn(i){return S().hasKey(i)}function rn(){return S().getTranslations()}function sn(i){return S().createTranslator(i)}async function on(i){return S().loadFromUrl(i)}function an(i){B=new z(i);}async function ln(i){let t=new z(i);if(B=t,i.staticPath){let e=i.staticPath.endsWith("/")?i.staticPath:i.staticPath+"/",n=t.getLanguage(),r=e+`${n}.json`;await t.loadFromUrl(r);}}async function cn(i,t){let e=S(),n=t||"static/i18n",s=(n.endsWith("/")?n:n+"/")+i+".json";await e.loadFromUrl(s);}var j={toast:"bb_toast",container:"bb_toastContainer",icon:"bb_toastIcon",msg:"bb_toastMsg"},Y=class extends m{constructor(){super(...arguments);this.messages=[];this.nextId=0;}show(e,n="info",r=2e3,s){let o=this.nextId++;this.messages=[...this.messages,{id:o,message:e,type:n,translateKey:s}],setTimeout(()=>{this.messages=this.messages.filter(a=>a.id!==o);},r);}success(e,n,r){this.show(e,"success",n,r);}error(e,n,r){this.show(e,"error",n,r);}info(e,n,r){this.show(e,"info",n,r);}warning(e,n,r){this.show(e,"warning",n,r);}render(){return this.messages.length===0?html``:createElement("div",{className:j.container},...this.messages.map(e=>this.renderToast(e)))}renderToast(e){let n={success:"fas fa-check-circle",error:"fas fa-exclamation-circle",info:"fas fa-info-circle",warning:"fas fa-exclamation-triangle"},r=e.translateKey?h(e.translateKey):e.message;return createElement("div",{key:String(e.id),className:`${j.toast} ${j.toast}--${e.type}`,"data-translate":e.translateKey||void 0},createElement("i",{className:`${n[e.type]} ${j.icon}`}),createElement("span",{className:j.msg},r))}};p([g],Y.prototype,"messages");var $=null;function Fe(i){if($)return $;let t=i||document.createElement("div");return i||document.body.appendChild(t),$=new Y,$.mount(t),$}function q(){return $||($=Fe()),$}var fn={show:(i,t="info",e,n)=>{q().show(i,t,e,n);},success:(i,t,e)=>{q().success(i,t,e);},error:(i,t,e)=>{q().error(i,t,e);},info:(i,t,e)=>{q().info(i,t,e);},warning:(i,t,e)=>{q().warning(i,t,e);}};var T={loader:{container:"bb_loaderContainer",containerOverlay:"bb_loaderContainer--overlay",bg:"bb_loaderBg",loader:"bb_loader"},spinner:{container:"bb_loaderSpinnerContainer",icon:"bb_loaderSpinnerIcon",dot:"bb_loaderSpinnerDot",pulse:"bb_loaderSpinnerPulse",text:"bb_loaderSpinnerText"},progress:{container:"bb_loaderProgressContainer",bar:"bb_loaderProgressBar",text:"bb_loaderProgressText"}},I=class extends m{constructor(){super(...arguments);this.visible=false;this.message="";this.variant="spinner";this.size="medium";this.overlay=true;this.progress=0;this.showProgress=false;this.animationFrame=null;this.hideTimeout=null;this.handleKeyPress=e=>{e.key==="Escape"&&this.visible&&!this.overlay&&this.hide();};}async onMount(){this.setupKeyboardListener(),this.initializeAccessibility(),window.addEventListener("languagechange",()=>{this.message||this.update();});}onUnmount(){this.animationFrame&&cancelAnimationFrame(this.animationFrame),this.hideTimeout&&clearTimeout(this.hideTimeout),document.removeEventListener("keydown",this.handleKeyPress);}render(){let e=[T.loader.container,this.overlay?`${T.loader.containerOverlay}`:"",`${T.loader.container}--${this.size}`].filter(Boolean).join(" ");return createElement("div",{className:e,"data-status":this.visible?"visible":"hidden",role:"status","aria-live":"polite","aria-busy":"true"},createElement("div",{className:T.loader.bg}),createElement("div",{className:T.loader.loader},this.renderSpinner(),this.renderMessage(),this.showProgress?this.renderProgressBar():null))}renderSpinner(){let e=`${T.spinner.container} ${T.spinner.container}--${this.variant}`;switch(this.variant){case "dots":return createElement("div",{className:e},createElement("div",{className:T.spinner.dot}),createElement("div",{className:T.spinner.dot}),createElement("div",{className:T.spinner.dot}));case "pulse":return createElement("div",{className:e},createElement("div",{className:T.spinner.pulse}));case "spinner":default:return createElement("div",{className:e},createElement("div",{className:T.spinner.icon}))}}renderMessage(){let e=this.message||h("global.loading");return createElement("div",{className:T.spinner.text,"data-translate":this.message?void 0:"global.loading"},e)}renderProgressBar(){return createElement("div",{className:T.progress.container},createElement("div",{className:T.progress.bar,style:`width: ${this.progress}%`,"aria-valuenow":this.progress.toString(),"aria-valuemin":"0","aria-valuemax":"100"}),createElement("div",{className:T.progress.text},`${Math.round(this.progress)}%`))}show(e){typeof e=="string"?this.message=e:e&&(this.message=e.message||"",this.variant=e.variant||"spinner",this.size=e.size||"medium",this.overlay=e.overlay!==void 0?e.overlay:true),this.visible=true,this.progress=0,this.showProgress=false,this.applyBodyLock(),this.update();}hide(e=0){this.hideTimeout&&clearTimeout(this.hideTimeout),e>0?this.hideTimeout=window.setTimeout(()=>{this.performHide();},e):this.performHide();}setMessage(e){this.message=e,this.update();}setProgress(e){this.showProgress=true,this.progress=Math.max(0,Math.min(100,e)),this.update();}updateProgress(e){this.setProgress(this.progress+e);}performHide(){this.visible=false,this.message="",this.progress=0,this.showProgress=false,this.removeBodyLock(),this.update();}applyBodyLock(){this.overlay&&(document.body.style.overflow="hidden");}removeBodyLock(){document.body.style.overflow="";}setupKeyboardListener(){this.handleKeyPress=this.handleKeyPress.bind(this),document.addEventListener("keydown",this.handleKeyPress);}initializeAccessibility(){let e=this.element?.querySelector(`.${T.spinner.container}`);e&&e.setAttribute("aria-label",h("loading"));}isVisible(){return this.visible}getStatus(){return {visible:this.visible,message:this.message,progress:this.progress}}};p([g],I.prototype,"visible"),p([g],I.prototype,"message"),p([g],I.prototype,"variant"),p([g],I.prototype,"size"),p([g],I.prototype,"overlay"),p([g],I.prototype,"progress"),p([g],I.prototype,"showProgress");var V=class extends m{constructor(e){super(e);this.fields=[];this.formData={};this.isSubmitting=false;this.submitError="";this.submitSuccess=false;this.fields=this.props.fields.map(n=>({...n,error:void 0,touched:false}));for(let n of this.fields)this.formData[n.name]=n.value||"";}onMount(){}handleChange(e,n){this.formData[e]=n;let r=this.fields.find(s=>s.name===e);r&&this.props.autoValidate&&(r.error=this.validateField(r,n),r.touched=true),this.update();}handleBlur(e){let n=this.fields.find(r=>r.name===e);n&&(n.touched=true,n.error=this.validateField(n,this.formData[e]),this.update());}validateField(e,n){let r=e.validation;if(!r)return;if(r.required&&!n)return r.message||`${e.label||e.name} is required`;if(!n)return;let s=String(n);if(r.minLength&&s.length<r.minLength)return r.message||`Minimum ${r.minLength} characters required`;if(r.maxLength&&s.length>r.maxLength)return r.message||`Maximum ${r.maxLength} characters allowed`;if(r.min!==void 0&&Number(n)<r.min)return r.message||`Minimum value is ${r.min}`;if(r.max!==void 0&&Number(n)>r.max)return r.message||`Maximum value is ${r.max}`;if(r.pattern&&!r.pattern.test(s))return r.message||"Invalid format";if(r.email&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s))return r.message||"Invalid email format";if(r.url&&!/^https?:\/\/.+/.test(s))return r.message||"Invalid URL format";if(r.custom){let o=r.custom(n);if(o!==true)return typeof o=="string"?o:void 0}}validateForm(){let e=true,n={};for(let r of this.fields){let s=this.validateField(r,this.formData[r.name]);r.error=s,r.touched=true,s&&(e=false,n[r.name]=s);}return this.update(),!e&&this.props.onValidationError&&this.props.onValidationError(n),e}async handleSubmit(e){if(e.preventDefault(),!this.validateForm()){let n=this.fields.find(r=>r.error);n&&document.querySelector(`[name="${n.name}"]`)?.focus();return}this.isSubmitting=true,this.submitError="",this.submitSuccess=false,this.update();try{if(this.props.onSubmit)await this.props.onSubmit(this.formData,e);else if(this.props.endpoint){let n=await api({method:this.props.method||"POST",url:this.props.endpoint,data:this.formData});this.submitSuccess=!0,this.props.onSuccess&&this.props.onSuccess(n.data);}}catch(n){let r=n instanceof Error?n.message:h("global.loading");this.submitError=r,this.props.onError&&this.props.onError(n);}finally{this.isSubmitting=false,this.update();}}renderLabel(e){return !e.label&&!e.icon?"":e.icon?html`
15
15
  <label for=${e.name}>
16
16
  <i class="fa ${e.icon}"></i>
17
17
  ${e.label?html`<span>${e.label}</span>`:""}
@@ -25,7 +25,7 @@ import {setConfig,patch,html,createElement,createDOMElement}from'@je-es/vdom';ex
25
25
  placeholder=${e.placeholder||""}
26
26
  value=${String(n)}
27
27
  disabled=${String(e.disabled||this.isSubmitting)}
28
- oninput=${i=>{let o=i.target;this.handleChange(e.name,o.value);}}
28
+ oninput=${s=>{let o=s.target;this.handleChange(e.name,o.value);}}
29
29
  onblur=${()=>this.handleBlur(e.name)}
30
30
  class="bb_formFieldTextarea"
31
31
  ></textarea>
@@ -47,7 +47,7 @@ import {setConfig,patch,html,createElement,createDOMElement}from'@je-es/vdom';ex
47
47
  onblur=${()=>this.handleBlur(e.name)}
48
48
  class="bb_formFieldSelect"
49
49
  >
50
- <option value="">Select...</option>
50
+ <option value="">${h("global.please_select",{},"Select...")}</option>
51
51
  ${o}
52
52
  </select>
53
53
  ${e.error&&e.touched?html`
@@ -63,7 +63,7 @@ import {setConfig,patch,html,createElement,createDOMElement}from'@je-es/vdom';ex
63
63
  name=${e.name}
64
64
  checked=${String(n)}
65
65
  disabled=${String(e.disabled||this.isSubmitting)}
66
- onchange=${i=>{let o=i.target;this.handleChange(e.name,o.checked);}}
66
+ onchange=${s=>{let o=s.target;this.handleChange(e.name,o.checked);}}
67
67
  class="bb_formFieldCheckbox"
68
68
  />
69
69
  ${e.icon?html`<i class="fa ${e.icon}"></i>`:""}
@@ -83,7 +83,7 @@ import {setConfig,patch,html,createElement,createDOMElement}from'@je-es/vdom';ex
83
83
  placeholder="${e.placeholder||""}"
84
84
  value="${String(n)}"
85
85
  disabled="${e.disabled||this.isSubmitting}"
86
- oninput=${i=>{let o=i.target;this.handleChange(e.name,o.value);}}
86
+ oninput=${s=>{let o=s.target;this.handleChange(e.name,o.value);}}
87
87
  onblur=${()=>this.handleBlur(e.name)}
88
88
  class="bb_formFieldInput"
89
89
  />
@@ -114,5 +114,5 @@ import {setConfig,patch,html,createElement,createDOMElement}from'@je-es/vdom';ex
114
114
  ${this.isSubmitting?e.loadingLabel||h("global.loading"):e.label||h("global.loading")}
115
115
  </button>
116
116
  </form>
117
- `}styles(){return be``}};p([g],V.prototype,"fields"),p([g],V.prototype,"formData"),p([g],V.prototype,"isSubmitting"),p([g],V.prototype,"submitError"),p([g],V.prototype,"submitSuccess");function _e(s){return new V(s).render()}var w={container:"bb_popupContainer",overlay:"bb_popupOverlay",popup:{base:"bb_popup",close:"bb_popupClose"},header:{container:"bb_popupHeader",icon:"bb_popupHeaderIcon",content:"bb_popupHeaderContent",title:"bb_popupHeaderContentTitle",description:"bb_popupHeaderContentDesc"},body:{container:"bb_popupBody",message:"bb_popupBodyMsg",input:"bb_popupBodyInput",formContainer:"bb_popupBodyFormContainer"},footer:"bb_popupFooter",button:"bb_btn"},Z=class extends m{constructor(){super(...arguments);this.popups=[];this.nextId=0;}async onMount(){this.setupKeyboardListener(),window.addEventListener("languagechange",()=>{this.update();});}onUnmount(){this.handleEscapeKey&&document.removeEventListener("keydown",this.handleEscapeKey);}render(){return this.popups.length===0?createElement("div",{className:w.container}):createElement("div",{className:w.container},...this.popups.map(e=>this.renderPopup(e)))}renderPopup(e){let n=`bb_popup--${e.size||"medium"}`,r=e.variant?`bb_popup--${e.variant}`:"";return createElement("div",{key:String(e.id),className:w.overlay,"data-popup-id":e.id,onClick:i=>{i.target.classList.contains(w.overlay)&&e.closeOnOverlay!==false&&this.closePopup(e.id,false);}},createElement("div",{className:`${w.popup.base} ${n} ${r}`,role:"dialog","aria-modal":"true","aria-labelledby":`popup-title-${e.id}`},e.showCloseButton!==false?createElement("button",{className:w.popup.close,onClick:()=>this.closePopup(e.id,false),"aria-label":"Close"},createElement("i",{className:"fas fa-times"})):null,createElement("div",{className:w.header.container},e.icon?createElement("div",{className:w.header.icon},createElement("i",{className:e.icon})):null,createElement("div",{className:w.header.content},createElement("h2",{id:`popup-title-${e.id}`,className:w.header.title,"data-translate":e.titleTranslateKey},e.titleTranslateKey?h(e.titleTranslateKey):e.title),e.description?createElement("p",{className:w.header.description,"data-translate":e.descriptionTranslateKey},e.descriptionTranslateKey?le(e.descriptionTranslateKey):e.description):null)),createElement("div",{className:w.body.container},e.message?createElement("p",{className:w.body.message,"data-translate":e.messageTranslateKey},e.messageTranslateKey?le(e.messageTranslateKey):e.message):null,e.type==="prompt"?createElement("input",{type:"text",className:w.body.input,value:e.inputValue||"",placeholder:h("popup.prompt.placeholder"),"data-translate":"popup.prompt.placeholder",onInput:i=>{e.inputValue=i.target.value;}}):null,e.type==="form"&&e.formConfig?createElement("div",{className:w.body.formContainer},_e(e.formConfig)):null,e.customContent||null),e.buttons&&e.buttons.length>0&&e.type!=="form"?createElement("div",{className:w.footer},...e.buttons.map(i=>createElement("button",{className:`${w.button} ${i.variant||"secondary"}`,"data-translate":i.translateKey,disabled:i.loading||e.isSubmitting,onClick:async()=>{i.loading||e.isSubmitting||await i.onClick();}},i.icon?createElement("i",{className:i.icon}):null,i.loading||e.isSubmitting?createElement("i",{className:"fas fa-spinner fa-spin"}):null," ",i.translateKey?h(i.translateKey):i.label))):null))}show(e){return new Promise(n=>{let r=this.nextId++,i={...e,id:r,resolve:n,type:e.type||"custom",size:e.size||"medium",closeOnOverlay:e.closeOnOverlay!==false,closeOnEscape:e.closeOnEscape!==false,showCloseButton:e.showCloseButton!==false,isSubmitting:false};this.popups=[...this.popups,i],this.applyBodyLock(),this.update();})}showForm(e){return new Promise((n,r)=>{let i=this.nextId++,o={...e.formConfig,onSubmit:async l=>{let c=this.popups.find(u=>u.id===i);c&&(c.isSubmitting=true,this.update());try{e.formConfig.onSubmit&&await e.formConfig.onSubmit(l,void 0),this.closePopup(i,l),n(l);}catch(u){c&&(c.isSubmitting=false,this.update()),e.formConfig.onError&&e.formConfig.onError(u);}},submitButton:{...e.formConfig.submitButton,className:e.formConfig.submitButton?.className||`${w.button} primary wide`}},a={title:e.title,titleTranslateKey:e.titleTranslateKey,description:e.description,descriptionTranslateKey:e.descriptionTranslateKey,type:"form",variant:e.variant||"default",size:e.size||"medium",icon:e.icon,formConfig:o,closeOnOverlay:e.closeOnOverlay!==false,closeOnEscape:e.closeOnEscape!==false,showCloseButton:e.showCloseButton!==false,id:i,resolve:n,isSubmitting:false};this.popups=[...this.popups,a],this.applyBodyLock(),this.update();})}confirm(e){return new Promise(n=>{let r=this.nextId++,i={id:r,title:e.title,titleTranslateKey:e.titleTranslateKey,message:e.message,messageTranslateKey:e.messageTranslateKey,type:"confirm",variant:e.variant||"default",size:e.size||"small",icon:e.icon,resolve:n,onConfirm:e.onConfirm,onCancel:e.onCancel,buttons:[{label:e.cancelLabel||"Cancel",translateKey:e.cancelTranslateKey||"button.cancel",variant:"secondary",icon:"fas fa-times",onClick:async()=>{e.onCancel&&await e.onCancel(),this.closePopup(r,false);}},{label:e.confirmLabel||"Confirm",translateKey:e.confirmTranslateKey||"button.confirm",variant:e.variant==="danger"?"danger":"primary",icon:"fas fa-check",onClick:async()=>{e.onConfirm&&await e.onConfirm(),this.closePopup(r,true);}}]};this.popups=[...this.popups,i],this.applyBodyLock(),this.update();})}alert(e){return new Promise(n=>{let r=this.nextId++,i={id:r,title:e.title,titleTranslateKey:e.titleTranslateKey,message:e.message,messageTranslateKey:e.messageTranslateKey,type:"alert",variant:e.variant||"info",size:e.size||"small",icon:e.icon,resolve:n,onConfirm:e.onConfirm,buttons:[{label:e.okLabel||"OK",translateKey:e.okTranslateKey||"popup.ok",variant:"primary",icon:"fas fa-check",onClick:async()=>{e.onConfirm&&await e.onConfirm(),this.closePopup(r,true);}}]};this.popups=[...this.popups,i],this.applyBodyLock(),this.update();})}prompt(e){return new Promise(n=>{let r=this.nextId++,i={id:r,title:e.title,titleTranslateKey:e.titleTranslateKey,message:e.message,messageTranslateKey:e.messageTranslateKey,type:"prompt",variant:"default",icon:e.icon,inputValue:e.defaultValue||"",resolve:n,onConfirm:e.onConfirm,onCancel:e.onCancel,buttons:[{label:e.cancelLabel||"Cancel",translateKey:e.cancelTranslateKey||"popup.cancel",variant:"secondary",onClick:async()=>{e.onCancel&&await e.onCancel(),this.closePopup(r,null);}},{label:e.confirmLabel||"OK",translateKey:e.confirmTranslateKey||"popup.ok",variant:"primary",onClick:async()=>{let o=i.inputValue||"";e.onConfirm&&await e.onConfirm(o),this.closePopup(r,o);}}]};this.popups=[...this.popups,i],this.applyBodyLock();})}closePopup(e,n){let r=this.popups.find(i=>i.id===e);r?.resolve&&r.resolve(n),this.popups=this.popups.filter(i=>i.id!==e),this.popups.length===0&&this.removeBodyLock(),this.update();}closeAll(){this.popups.forEach(e=>{e.resolve&&e.resolve(false);}),this.popups=[],this.removeBodyLock(),this.update();}applyBodyLock(){document.body.style.overflow="hidden";}removeBodyLock(){document.body.style.overflow="";}setupKeyboardListener(){this.handleEscapeKey=e=>{if(e.key==="Escape"&&this.popups.length>0){let n=this.popups[this.popups.length-1];n.closeOnEscape!==false&&this.closePopup(n.id,false);}},document.addEventListener("keydown",this.handleEscapeKey);}};p([g],Z.prototype,"popups");var F=null;function Ae(s){if(F)return F;let t=s||document.createElement("div");return s||document.body.appendChild(t),F=new Z,F.mount(t),F}function M(){return F||(F=Ae()),F}var An={show:s=>M().show(s),confirm:s=>M().confirm(s),alert:s=>M().alert(s),prompt:s=>M().prompt(s),showForm:s=>M().showForm(s),closePopup:(s,t)=>M().closePopup(s,t),closeLastPopup:()=>M().closePopup(M().popups.length-1,false),closeFirstPopup:()=>M().closePopup(0,false),closeAll:()=>M().closeAll()};var P={container:"bb_tabbedview",header:"bb_tabbedviewHeader",tab:{base:"bb_tabbedviewTab",active:"bb_tabbedviewTab--active",disabled:"bb_tabbedviewTab--disabled",badge:"bb_tabbedviewBadge"},content:{container:"bb_tabbedviewContent",emptyState:"bb_tabbedviewEmptyState",error:"bb_tabbedviewError"}},x=class extends m{constructor(){super(...arguments);this.activeTabId="";this.tabs=[];this.position="top";this.style="default";this.className="";this.headerClassName="";this.contentClassName="";this.showTabCount=false;this.persistState=false;this.storageKey="tabbedview-active";this.currentTabComponent=null;}async onMount(){window.addEventListener("languagechange",()=>{this.update();});}onUnmount(){this.currentTabComponent&&typeof this.currentTabComponent.onUnmount=="function"&&this.currentTabComponent.onUnmount();}init(e){if(this.tabs=e.tabs,this.position=e.position||"top",this.style=e.style||"default",this.className=e.className||"",this.headerClassName=e.headerClassName||"",this.contentClassName=e.contentClassName||"",this.showTabCount=e.showTabCount||false,this.persistState=e.persistState||false,this.storageKey=e.storageKey||"tabbedview-active",this.onChange=e.onChange,this.persistState){let n=localStorage.getItem(this.storageKey);n&&this.tabs.find(r=>r.id===n)&&(this.activeTabId=n);}return this.activeTabId||(this.activeTabId=e.defaultTab||this.tabs[0]?.id||""),this.update(),this}async setActiveTab(e){let n=this.tabs.find(r=>r.id===e);!n||n.disabled||(this.currentTabComponent&&typeof this.currentTabComponent.onUnmount=="function"&&this.currentTabComponent.onUnmount(),this.currentTabComponent=null,this.activeTabId=e,this.persistState&&localStorage.setItem(this.storageKey,e),n.onActivate&&await n.onActivate(),this.onChange&&await this.onChange(e),this.update());}addTab(e){this.tabs=[...this.tabs,e],this.update();}removeTab(e){this.tabs=this.tabs.filter(n=>n.id!==e),this.activeTabId===e&&this.tabs.length>0&&(this.activeTabId=this.tabs[0].id),this.update();}updateTab(e,n){let r=this.tabs.find(i=>i.id===e);r&&(Object.assign(r,n),this.update());}getActiveTab(){return this.tabs.find(e=>e.id===this.activeTabId)}render(){let e=[P.container,`bb_tabbedview__--${this.position}`,`bb_tabbedview__--${this.style}`,this.className].filter(Boolean).join(" ");return createElement("div",{className:e},this.renderTabList(),this.renderTabContent())}renderTabList(){let e=[P.header,this.headerClassName].filter(Boolean).join(" ");return createElement("div",{className:e},...this.tabs.map(n=>this.renderTab(n)))}renderTab(e){let n=this.activeTabId===e.id,r=[P.tab.base,n?P.tab.active:"",e.disabled?P.tab.disabled:""].filter(Boolean).join(" "),i=e.translateKey?h(e.translateKey):e.label;return createElement("button",{key:e.id,className:r,onclick:()=>this.setActiveTab(e.id),disabled:e.disabled,"data-translate":e.translateKey,"aria-selected":n,role:"tab"},e.icon?createElement("i",{className:e.icon}):null,createElement("span",{},i),e.badge!==void 0&&e.badge!==null&&e.badge!==0?createElement("span",{className:P.tab.badge},typeof e.badge=="number"&&e.badge>99?"99+":String(e.badge)):null)}renderTabContent(){let e=[P.content.container,this.contentClassName].filter(Boolean).join(" "),n=this.getActiveTab();return n?createElement("div",{className:e,role:"tabpanel"},this.renderActiveTabContent(n)):createElement("div",{className:e},createElement("div",{className:P.content.emptyState},createElement("p",{},h("global.loading"))))}renderActiveTabContent(e){if(e.component)try{if(e.component instanceof m){this.currentTabComponent=e.component;let n=this.currentTabComponent.render(),r={...n.props,ref:o=>{o&&this.currentTabComponent&&this.currentTabComponent.setElement(o),typeof n.props.ref=="function"&&n.props.ref(o);}},i={...n,props:r};return typeof this.currentTabComponent.onMount=="function"&&setTimeout(()=>{this.currentTabComponent&&typeof this.currentTabComponent.onMount=="function"&&this.currentTabComponent.onMount();},0),i}if(typeof e.component=="function"){let n=e.component;return n.prototype&&typeof n.prototype.render=="function"?(this.currentTabComponent||(this.currentTabComponent=new n,this.currentTabComponent&&typeof this.currentTabComponent.onMount=="function"&&setTimeout(()=>{this.currentTabComponent&&typeof this.currentTabComponent.onMount=="function"&&this.currentTabComponent.onMount();},0)),this.currentTabComponent.render()):n()}}catch(n){return console.error("Error rendering tab component:",n),createElement("div",{className:P.content.error},h("global.loading"))}return e.content?e.content:createElement("div",{className:P.content.emptyState},createElement("p",{},h("global.loading")))}};p([g],x.prototype,"activeTabId"),p([g],x.prototype,"tabs"),p([g],x.prototype,"position"),p([g],x.prototype,"style"),p([g],x.prototype,"className"),p([g],x.prototype,"headerClassName"),p([g],x.prototype,"contentClassName"),p([g],x.prototype,"showTabCount"),p([g],x.prototype,"persistState"),p([g],x.prototype,"storageKey");function He(s){let t=new x;return t.init(s),t}async function Wn(s,t){let e=He(t);return await e.mount(s),e}var f={container:"bb_itemsLoaderContainer",list:"bb_itemsLoaderList",searchbar:"bb_itemsLoaderSearchbar",loading:"bb_itemsLoaderLoading",error:"bb_itemsLoaderError",trigger:"bb_itemsLoaderTrigger",end:"bb_itemsLoaderEnd",emptyState:"bb_tabbedviewEmptyState",button:"bb_btn",item:"bb_itemsLoader-item",formFieldInput:"bb_formFieldInput"},ue=class extends m{constructor(){super(...arguments);this.items=[];this.loadState={loading:false,error:null,hasMore:true,page:0,total:0};this.filters={};this.scrollContainer=null;this.loadMoreObserver=null;this.currentLoadMoreTrigger=null;this.loadMoreMutationObserver=null;this.visibilityObserver=null;this.viewedItems=new Set;this.dropdownIsOpen=false;this.itemsListContainer=null;this.searchInput=null;this.isUpdating=false;this.searchDebounceTimer=null;this.handleScroll=()=>{if(!this.scrollContainer||this.loadState.loading||!this.loadState.hasMore)return;let{scrollTop:e,scrollHeight:n,clientHeight:r}=this.scrollContainer;n-e-r<this.config.scrollThreshold&&this.loadMore();};this.handleItemClick=(e,n)=>{this.config.onItemClick?.(e,n);};}initialize(e){this.config={pageSize:10,loadMoreText:"Load More",loadingText:"Loading...",errorText:"Failed to load items",containerClassName:f.container,itemClassName:f.item,enableInfiniteScroll:true,scrollThreshold:200,enableSearch:false,searchPlaceholder:"Search...",searchFilterKey:"search",searchDebounceMs:300,enableVisibilityTracking:false,visibilityThreshold:.5,visibilityRootMargin:"0px",extractItems:n=>n.notifications||n.items||n.data||n.logs||[],extractTotal:n=>n.pagination?.total||n.total||n.count||0,...e},this.config.filters&&(this.filters={...this.config.filters}),this.config.initialItems&&(this.items=[...this.config.initialItems]);}async onMount(){this.items.length===0&&await this.loadMore(),this.config.enableInfiniteScroll&&this.setupInfiniteScroll(),this.config.scrollThreshold&&this.setupScrollListener(),this.config.enableVisibilityTracking&&this.setupVisibilityTracking();}onUnmount(){this.disconnectInfiniteScrollObserver(),this.disconnectVisibilityObserver(),this.loadMoreMutationObserver&&(this.loadMoreMutationObserver.disconnect(),this.loadMoreMutationObserver=null),this.scrollContainer&&(this.scrollContainer.removeEventListener("scroll",this.handleScroll),this.scrollContainer=null),this.searchDebounceTimer&&clearTimeout(this.searchDebounceTimer);}async loadMore(){if(!(this.loadState.loading||!this.loadState.hasMore))try{let e=this.scrollContainer||this.findScrollContainer(),n=e?.scrollTop||0,r=e?.scrollHeight||0;this.loadState={...this.loadState,loading:!0,error:null},this.updateLoadingState();let i=this.loadState.page+1,o=this.buildUrl(i),a=await fetch(o,{credentials:"include",headers:this.buildHeaders()});if(!a.ok)throw new Error(`HTTP ${a.status}: ${a.statusText}`);let l=await a.json(),c=this.config.extractItems(l),u=this.config.extractTotal(l);this.items=[...this.items,...c],this.loadState={loading:!1,error:null,hasMore:this.items.length<u,page:i,total:u},this.updateLoadingState(),this.appendNewItems(c),e&&n>0&&(e.scrollTop=n,requestAnimationFrame(()=>{let y=e.scrollHeight-r;Math.abs(y)>10&&(e.scrollTop=n);})),this.reconnectInfiniteScrollObserver(),this.config.onLoadMore?.(i,this.items);}catch(e){this.loadState={...this.loadState,loading:false,error:e instanceof Error?e.message:this.config.errorText},this.updateLoadingState(),this.updateFooter(),this.config.onError?.(e instanceof Error?e:new Error("Unknown error"));}}async reload(){this.items=[],this.loadState={loading:false,error:null,hasMore:true,page:0,total:0},await this.loadMore();}async applyFilters(e){if(!this.isUpdating){this.isUpdating=true,this.filters={...e},this.items=[],this.loadState={loading:true,error:null,hasMore:true,page:0,total:0},this.updateLoadingState();try{let n=this.buildUrl(1),r=await fetch(n,{credentials:"include",headers:this.buildHeaders()});if(!r.ok)throw new Error(`HTTP ${r.status}: ${r.statusText}`);let i=await r.json(),o=this.config.extractItems(i),a=this.config.extractTotal(i);this.items=[...o],this.loadState={loading:!1,error:null,hasMore:this.items.length<a,page:1,total:a},this.itemsListContainer&&(this.itemsListContainer.innerHTML=""),this.element&&this.element.querySelectorAll(`.${f.trigger}, .${f.end}, .${f.error}, .${f.loading}, .${f.emptyState}`).forEach(l=>l.remove()),this.items.length>0?(this.itemsListContainer||(this.itemsListContainer=this.element?.querySelector(`.${f.list}`)),this.itemsListContainer&&this.appendNewItems(this.items)):this.updateFooter(),this.itemsListContainer=this.element?.querySelector(`.${f.list}`),this.reconnectInfiniteScrollObserver(),this.config.onLoadMore?.(1,this.items),this.config.onFiltersChange?.(this.filters);}catch(n){this.loadState={...this.loadState,loading:false,error:n instanceof Error?n.message:this.config.errorText},this.updateLoadingState(),this.config.onError?.(n instanceof Error?n:new Error("Unknown error"));}finally{this.isUpdating=false;}}}async handleSearch(e){this.searchDebounceTimer&&clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{let n={...this.filters};e.trim()?n[this.config.searchFilterKey]=e.trim():delete n[this.config.searchFilterKey],await this.applyFilters(n);},this.config.searchDebounceMs);}updateItems(e){this.items=[...e],this.itemsListContainer&&(this.itemsListContainer.innerHTML="",this.appendNewItems(e));}setupVisibilityTracking(){if(!this.config.enableVisibilityTracking)return;this.visibilityObserver&&this.visibilityObserver.disconnect();let e=this.findScrollContainer();this.visibilityObserver=new IntersectionObserver(n=>{n.forEach(r=>{if(r.isIntersecting&&this.dropdownIsOpen){let i=r.target,o=parseInt(i.getAttribute("data-item-index")||"-1");if(o>=0&&o<this.items.length){let a=this.items[o],l=this.config.getItemId?.(a),c=this.config.shouldTrackItem?.(a)??true;l&&!this.viewedItems.has(l)&&c&&this.viewedItems.add(l);}}});},{root:e,rootMargin:this.config.visibilityRootMargin,threshold:this.config.visibilityThreshold}),this.observeTrackableItems();}observeTrackableItems(){if(!this.visibilityObserver||!this.itemsListContainer)return;this.itemsListContainer.querySelectorAll("[data-item-index]").forEach(n=>{let r=parseInt(n.getAttribute("data-item-index")||"-1");if(r>=0&&r<this.items.length){let i=this.items[r];(this.config.shouldTrackItem?.(i)??true)&&this.visibilityObserver.observe(n);}});}trackAlreadyVisibleItems(){if(!this.itemsListContainer)return;let e=this.findScrollContainer();if(!e)return;let n=this.itemsListContainer.querySelectorAll("[data-item-index]"),r=e.getBoundingClientRect();n.forEach(i=>{let o=parseInt(i.getAttribute("data-item-index")||"-1");if(o<0||o>=this.items.length)return;let a=this.items[o],l=this.config.getItemId?.(a);if(!l||this.viewedItems.has(l)||!(this.config.shouldTrackItem?.(a)??true))return;let u=i.getBoundingClientRect();u.top<r.bottom&&u.bottom>r.top&&u.top>=r.top-100&&u.bottom<=r.bottom+100&&this.viewedItems.add(l);});}disconnectVisibilityObserver(){this.visibilityObserver&&(this.visibilityObserver.disconnect(),this.visibilityObserver=null);}handleDropdownOpen(){this.dropdownIsOpen=true,this.viewedItems.clear(),this.config.enableVisibilityTracking&&(this.trackAlreadyVisibleItems(),this.observeTrackableItems()),this.config.onDropdownOpen?.();}async handleDropdownClose(){if(this.dropdownIsOpen=false,this.viewedItems.size>0&&this.config.onItemsViewed){let e=this.items.filter(n=>{let r=this.config.getItemId?.(n);return r&&this.viewedItems.has(r)});await this.config.onItemsViewed(e);}this.viewedItems.clear(),this.config.onDropdownClose?.();}async performBatchAction(e,n){this.config.onBatchAction&&await this.config.onBatchAction(e,n);}appendNewItems(e){if(this.itemsListContainer||(this.itemsListContainer=this.element?.querySelector(`.${f.list}`)),!this.itemsListContainer)return;let n=document.createDocumentFragment(),r=this.items.length-e.length;e.forEach((i,o)=>{let a=r+o,l=this.config.renderItem(i,a);l.setAttribute("data-item-index",a.toString()),this.config.onItemClick?(l.className=`${l.className} ${this.config.itemClassName} clickable`,l.onclick=()=>this.handleItemClick(i,a)):l.className=`${l.className} ${this.config.itemClassName}`,n.appendChild(l);}),this.itemsListContainer.appendChild(n),this.updateFooter(),this.config.enableVisibilityTracking&&this.dropdownIsOpen&&setTimeout(()=>this.observeTrackableItems(),100);}updateLoadingState(){let e=this.element?.querySelector(`.${f.container}`);if(!e)return;let n=e.querySelector(`.${f.loading}`);if(this.loadState.loading){if(!n){let r=this.renderLoading();n=this.createElementFromVNode(r),e.appendChild(n);}}else n&&n.remove();}updateFooter(){let e=this.element;if(e){if(e.querySelectorAll(`.${f.trigger}, .${f.end}, .${f.emptyState}`).forEach(n=>{n.remove();}),this.items.length===0&&!this.loadState.loading&&this.config.emptyStateConfig){let n=this.renderEmptyState(),r=createDOMElement(n);e.appendChild(r);return}if(this.loadState.hasMore&&!this.loadState.loading&&this.items.length>0){let n=this.renderLoadMoreTrigger(),r=createDOMElement(n);e.appendChild(r);}if(!this.loadState.hasMore&&this.items.length>0){let n=this.renderEndMessage(),r=createDOMElement(n);e.appendChild(r);}}}setupInfiniteScroll(){this.loadMoreObserver&&this.loadMoreObserver.disconnect(),this.loadMoreObserver=new IntersectionObserver(e=>{let[n]=e;n.isIntersecting&&!this.loadState.loading&&this.loadState.hasMore&&this.loadMore();},{threshold:.1,rootMargin:"50px"}),this.reconnectInfiniteScrollObserver();}reconnectInfiniteScrollObserver(){if(!this.config.enableInfiniteScroll||!this.loadMoreObserver)return;this.currentLoadMoreTrigger&&(this.loadMoreObserver.unobserve(this.currentLoadMoreTrigger),this.currentLoadMoreTrigger=null);let e=()=>{let n=this.element?.querySelector('[data-load-more-trigger="true"]');return n?(this.loadMoreObserver.observe(n),this.currentLoadMoreTrigger=n,true):false};e()||(this.loadMoreMutationObserver&&this.loadMoreMutationObserver.disconnect(),this.loadMoreMutationObserver=new MutationObserver(()=>{e()&&this.loadMoreMutationObserver&&(this.loadMoreMutationObserver.disconnect(),this.loadMoreMutationObserver=null);}),this.element&&(this.loadMoreMutationObserver.observe(this.element,{childList:true,subtree:true}),setTimeout(()=>{this.loadMoreMutationObserver&&(this.loadMoreMutationObserver.disconnect(),this.loadMoreMutationObserver=null);},5e3)));}disconnectInfiniteScrollObserver(){this.loadMoreObserver&&this.currentLoadMoreTrigger&&(this.loadMoreObserver.unobserve(this.currentLoadMoreTrigger),this.currentLoadMoreTrigger=null);}setupScrollListener(){requestAnimationFrame(()=>{this.scrollContainer=this.findScrollContainer(),this.scrollContainer&&("scrollRestoration"in history&&(history.scrollRestoration="manual"),this.scrollContainer.addEventListener("scroll",this.handleScroll));});}findScrollContainer(){let e=[this.element?.closest(".bb_notificationsContent"),this.element?.closest(".bb_dropdownMenu"),this.element?.querySelector("[data-notifications-loader]"),this.element?.closest("[data-notifications-loader]"),this.element?.closest(".scrollbar-thin"),this.element?.parentElement,this.element];for(let n of e)if(n){let r=n;if(r.scrollHeight>r.clientHeight||r.classList.contains("scrollbar-thin"))return r}return null}buildUrl(e){if(typeof this.config.fetchUrl=="function")return this.config.fetchUrl(e,this.filters);let n=this.config.fetchUrl.includes("?")?"&":"?",r=new URLSearchParams({page:e.toString(),limit:this.config.pageSize.toString(),...this.filters});return `${this.config.fetchUrl}${n}${r}`}buildHeaders(){let e={"Content-Type":"application/json"},n=this.config.getAuthToken?.();return n&&(e.Authorization=`Bearer ${n}`),e}createElementFromVNode(e){if(typeof e.type!="string")throw new Error("Can only create elements from string types");let n=document.createElement(e.type);return e.props&&Object.entries(e.props).forEach(([r,i])=>{r==="className"?n.className=i:r==="style"?typeof i=="string"?n.setAttribute("style",i):typeof i=="object"&&i!==null&&Object.assign(n.style,i):r==="onclick"&&typeof i=="function"?n.addEventListener("click",i):r!=="children"&&r!=="ref"&&n.setAttribute(r,String(i));}),e.children&&e.children.forEach(r=>{r!=null&&(typeof r=="string"||typeof r=="number"?n.appendChild(document.createTextNode(String(r))):typeof r=="object"&&n.appendChild(this.createElementFromVNode(r)));}),n}render(){return createElement("div",{className:this.config.containerClassName},this.config.enableSearch?this.renderSearchBar():null,createElement("div",{className:f.list,ref:e=>{e&&(this.itemsListContainer=e);}}),this.loadState.error?this.renderError():null,this.loadState.loading?this.renderLoading():null,this.loadState.hasMore&&!this.loadState.loading&&this.items.length>0?this.renderLoadMoreTrigger():null,!this.loadState.hasMore&&this.items.length>0?this.renderEndMessage():null)}renderSearchBar(){return createElement("div",{className:f.searchbar},createElement("div",{className:"row gap-sm"},createElement("i",{className:"fas fa-search"}),createElement("input",{type:"text",className:f.formFieldInput,placeholder:this.config.searchPlaceholder,ref:e=>{e&&(this.searchInput=e,this.searchInput.addEventListener("input",n=>{let r=n.target.value;this.handleSearch(r);}));}})))}renderEmptyState(){let e=this.config.emptyStateConfig;return createElement("div",{className:f.emptyState},createElement("i",{className:`__icon ${e.icon}`}),createElement("h3",{className:"__title"},e.title),createElement("p",{className:"__desc"},e.description))}renderLoading(){return createElement("div",{className:f.loading},createElement("i",{className:"fas fa-spinner fa-spin"}),createElement("p",{},this.config.loadingText))}renderError(){return createElement("div",{className:f.error},createElement("i",{className:"fas fa-exclamation-triangle"}),createElement("p",{},this.loadState.error),createElement("button",{className:`${f.button} secondary`,onclick:()=>this.loadMore()},createElement("i",{className:"fas fa-redo"})," Retry"))}renderLoadMoreTrigger(){return createElement("div",{className:f.trigger,"data-load-more-trigger":"true",style:"height: 1px; visibility: hidden;"})}renderEndMessage(){return createElement("div",{className:f.end},createElement("i",{className:"fas fa-check-circle"}),h("All loaded",{count:String(this.loadState.total)}))}};function tr(s){let t=new ue;return t.initialize(s),t}var de=class s{constructor(){this.dropdowns=new Map;this.hierarchy=new Map;this.setupGlobalClickHandler();}static getInstance(){return s.instance||(s.instance=new s),s.instance}register(t){this.dropdowns.set(t.config.id,t),t.config.parentId&&this.hierarchy.set(t.config.id,t.config.parentId);}unregister(t){this.dropdowns.delete(t),this.hierarchy.delete(t);}open(t){let e=this.dropdowns.get(t);e&&(this.closeSiblings(t),e.setOpen(true));}close(t){let e=this.dropdowns.get(t);e&&(e.setOpen(false),this.closeChildren(t));}closeAll(){Array.from(this.dropdowns.values()).filter(e=>!e.config.parentId).forEach(e=>this.close(e.config.id));}destroy(){this.clickHandler&&typeof window<"u"&&document.removeEventListener("click",this.clickHandler,true),this.dropdowns.clear(),this.hierarchy.clear();}isAncestor(t,e){let n=e;for(;n;){if(n===t)return true;n=this.hierarchy.get(n);}return false}isDescendant(t,e){return this.isAncestor(e,t)}getAncestors(t){let e=new Set,n=t;for(;n;){let r=this.hierarchy.get(n);if(r)e.add(r),n=r;else break}return e}getDescendants(t){let e=new Set,n=r=>{Array.from(this.hierarchy.entries()).filter(([o,a])=>a===r).map(([o,a])=>o).forEach(o=>{e.add(o),n(o);});};return n(t),e}closeSiblings(t){let e=this.dropdowns.get(t);if(!e)return;let n=e.config.parentId;Array.from(this.dropdowns.values()).filter(i=>i.config.parentId===n&&i.config.id!==t).forEach(i=>this.close(i.config.id));}closeChildren(t){Array.from(this.dropdowns.values()).filter(n=>n.config.parentId===t).forEach(n=>this.close(n.config.id));}hasOpenDropdowns(){return Array.from(this.dropdowns.values()).some(t=>t.isOpen)}findDropdownForElement(t){let e=t;for(;e&&e!==document.body;){let n=e.getAttribute("data-dropdown-id");if(n)return n;e=e.parentElement;}return null}setupGlobalClickHandler(){typeof window>"u"||(this.clickHandler=t=>{let e=t.target;if(!this.hasOpenDropdowns())return;let n=this.findDropdownForElement(e);if(!n){this.closeAll();return}if(this.dropdowns.get(n)?.config.preventAutoClose||e.closest(".bb_dropdownTrigger"))return;if(e.closest(".bb_dropdownMenu")){let a=this.getAncestors(n),l=this.getDescendants(n);Array.from(this.dropdowns.values()).filter(u=>!u.config.parentId).forEach(u=>{let d=u.config.id;d===n||a.has(d)||l.has(d)||this.isDescendant(n,d)||this.close(d);});}},document.addEventListener("click",this.clickHandler,true));}},W=de.getInstance(),he=class extends m{constructor(e){super();this.isOpen=false;this.mounted=false;this.config={closeOnItemClick:true,preventAutoClose:false,...e};}onMount(){this.mounted=true,W.register(this);}onUnmount(){this.mounted=false,W.unregister(this.config.id);}setOpen(e){this.isOpen!==e&&(this.isOpen=e,e?this.config.onOpen?.():this.config.onClose?.(),this.updateDOM());}toggle(e){e.preventDefault(),e.stopPropagation(),this.isOpen?W.close(this.config.id):W.open(this.config.id);}handleItemClick(e,n){if(e.disabled){n.preventDefault(),n.stopPropagation();return}this.config.closeOnItemClick&&(n.preventDefault(),n.stopPropagation(),W.close(this.config.id)),e.onclick?.(n);}render(){let e=this.renderTrigger(),n=this.isOpen?this.renderMenu():null,r=["bb_dropdown",`bb_dropdown--${this.config.position||"left"}`,this.isOpen?"bb_dropdown--open":"",this.config.asIcon?"bb_dropdown--asIcon":"",this.config.className||""].filter(Boolean).join(" ");return createElement("div",{className:r,"data-dropdown-id":this.config.id},e,n)}updateDOM(){if(!this.mounted||!this.element)return;this.isOpen?this.element.classList.add("bb_dropdown--open"):this.element.classList.remove("bb_dropdown--open");let n=this.element.querySelector(".bb_dropdownTrigger")?.nextElementSibling;if(this.isOpen){if(!n||!n.classList.contains("bb_dropdownMenu")){let r=this.renderMenu(),i=this.createElementFromVNode(r);this.element.appendChild(i);}}else n&&n.classList.contains("bb_dropdownMenu")&&n.remove();}createElementFromVNode(e){if(typeof e.type=="string"){let n=document.createElement(e.type);return e.props&&Object.entries(e.props).forEach(([r,i])=>{r==="className"?n.className=i:r==="onclick"&&typeof i=="function"?n.addEventListener("click",i):r!=="children"&&r!=="key"&&n.setAttribute(r,String(i));}),e.children&&e.children.forEach(r=>{r!=null&&(typeof r=="string"||typeof r=="number"?n.appendChild(document.createTextNode(String(r))):typeof r=="object"&&n.appendChild(this.createElementFromVNode(r)));}),n}return document.createElement("div")}renderTrigger(){let e=this.config.trigger.element?.(),n=["bb_dropdownTrigger",this.config.trigger.className||""].filter(Boolean).join(" ");if(e)return createElement("button",{className:n,onclick:i=>this.toggle(i)},e);let r=["bb_dropdownArrow","fas","fa-chevron-down",this.isOpen?"bb_dropdownArrow--open":"",this.config.hideArrow?"hidden":""].filter(Boolean).join(" ");return createElement("button",{className:n,onclick:i=>this.toggle(i)},this.config.trigger.icon?createElement("i",{className:this.config.trigger.icon}):null,this.config.trigger.text?createElement("span",{},this.config.trigger.text):null,createElement("i",{className:r}))}renderMenu(){return createElement("div",{className:"bb_dropdownMenu",onclick:e=>{this.config.preventAutoClose&&e.stopPropagation();}},this.config.items.map((e,n)=>{if(e==="divider")return createElement("div",{className:"bb_dropdown__divider",key:`divider-${n}`});let r=["bb_dropdownItem",e.className||"",e.disabled?"bb_dropdownItem--disabled":"",e.selected?"bb_dropdownItem--selected":""].filter(Boolean).join(" "),i={key:e.id||`item-${n}`,className:r,onclick:o=>this.handleItemClick(e,o)};return e.disabled&&(i.disabled=true),createElement("button",i,e.icon?createElement("i",{className:e.icon}):null,createElement("span",{},e.label))}))}};function ar(s){return new he(s)}function De(s,t){let e=null;return (...n)=>{e!==null&&clearTimeout(e),e=setTimeout(()=>{e=null,s(...n);},t);}}function Ue(s,t){let e=0,n=null;return (...r)=>{let i=Date.now(),o=i-e;o>=t?(e=i,s(...r)):n||(n=setTimeout(()=>{e=Date.now(),n=null,s(...r);},t-o));}}function Be(...s){let t=[];for(let e of s)if(e){if(typeof e=="string")t.push(e);else if(typeof e=="object")for(let[n,r]of Object.entries(e))r&&t.push(n);}return t.join(" ")}function ze(s,t="YYYY-MM-DD"){let e=s instanceof Date?s:new Date(s);if(isNaN(e.getTime()))throw new Error("Invalid date provided to formatDate");let n=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0"),o=String(e.getHours()).padStart(2,"0"),a=String(e.getMinutes()).padStart(2,"0"),l=String(e.getSeconds()).padStart(2,"0");return t.replace("YYYY",String(n)).replace("MM",r).replace("DD",i).replace("HH",o).replace("mm",a).replace("ss",l)}function H(s){if(s===null||typeof s!="object")return s;if(s instanceof Date)return new Date(s.getTime());if(Array.isArray(s))return s.map(t=>H(t));if(s instanceof RegExp)return new RegExp(s.source,s.flags);if(s instanceof Map){let t=new Map;return s.forEach((e,n)=>{t.set(H(n),H(e));}),t}if(s instanceof Set){let t=new Set;return s.forEach(e=>{t.add(H(e));}),t}if(Object.prototype.toString.call(s)==="[object Object]"){let t={};for(let e in s)Object.prototype.hasOwnProperty.call(s,e)&&(t[e]=H(s[e]));return t}return s}function ge(s,...t){if(!t.length)return s;let e=t.shift();if(!e)return s;if(X(s)&&X(e)){for(let n in e)if(Object.prototype.hasOwnProperty.call(e,n)){let r=e[n],i=s[n];r!==void 0&&(X(r)&&!Array.isArray(r)?((!i||!X(i))&&(s[n]={}),ge(s[n],r)):s[n]=r);}}return ge(s,...t)}function X(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}var pe=0;function je(s="id"){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,11);pe=(pe||0)+1;let n=pe.toString(36);return `${s}_${t}_${e}_${n}`}function qe(s){if(s<0)throw new Error("Sleep duration must be non-negative");return new Promise(t=>setTimeout(t,s))}function We(s){return s==null?true:typeof s=="string"?s.trim().length===0:Array.isArray(s)?s.length===0:s instanceof Map||s instanceof Set?s.size===0:typeof s=="object"?Object.keys(s).length===0:false}function Ge(s){return s?s.charAt(0).toUpperCase()+s.slice(1):""}function Je(s){return s?s.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[\s_]+/g,"-").toLowerCase():""}function Ce(s){return s?s.replace(/[-_\s]+(.)?/g,(t,e)=>e?e.toUpperCase():"").replace(/^[A-Z]/,t=>t.toLowerCase()):""}function Qe(s){if(!s)return "";let t=Ce(s);return t.charAt(0).toUpperCase()+t.slice(1)}function Ye(s,t,e="..."){return !s||s.length<=t?s:s.substring(0,t-e.length)+e}function Ze(s){let t={},e=s.replace(/^\?/,"");if(!e)return t;let n=e.split("&");for(let r of n){let[i,o]=r.split("=").map(decodeURIComponent);if(!i)continue;let a=o||"";if(i.endsWith("[]")){let l=i.slice(0,-2);t[l]||(t[l]=[]),t[l].push(a);}else t[i]=a;}return t}function Xe(s){let t=[];for(let[e,n]of Object.entries(s))if(n!=null)if(Array.isArray(n))for(let r of n)r!=null&&t.push(`${encodeURIComponent(e)}[]=${encodeURIComponent(String(r))}`);else t.push(`${encodeURIComponent(e)}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}function et(s,t,e){return Math.min(Math.max(s,t),e)}function tt(){return typeof window<"u"&&typeof document<"u"}function nt(s,t){try{return JSON.parse(s)}catch{return t}}var cr={debounce:De,throttle:Ue,classNames:Be,formatDate:ze,deepClone:H,deepMerge:ge,uniqueId:je,sleep:qe,isEmpty:We,capitalize:Ge,kebabCase:Je,camelCase:Ce,pascalCase:Qe,truncate:Ye,parseQuery:Ze,stringifyQuery:Xe,clamp:et,isBrowser:tt,safeJsonParse:nt};var Se=class{constructor(t){this.observer=null;this.observedElements=new Map;this.observer=new IntersectionObserver(e=>{e.forEach(n=>{let r=this.observedElements.get(n.target)??false,i=n.isIntersecting;i&&!r?(this.observedElements.set(n.target,true),t.onEnter?.(n),t.once&&this.unobserve(n.target)):!i&&r&&(this.observedElements.set(n.target,false),t.onExit?.(n));});},{root:t.root||null,rootMargin:t.rootMargin||"0px",threshold:t.threshold??.1});}observe(t){this.observer&&(this.observer.observe(t),this.observedElements.set(t,false));}unobserve(t){this.observer&&(this.observer.unobserve(t),this.observedElements.delete(t));}disconnect(){this.observer&&(this.observer.disconnect(),this.observedElements.clear());}};function dr(s,t){let e=new IntersectionObserver(n=>{n.forEach(r=>{r.isIntersecting&&(t(r),e.unobserve(s));});},{threshold:.1});return e.observe(s),()=>e.disconnect()}function fe(s){let t=typeof s=="string"?new Date(s):s,n=new Date().getTime()-t.getTime(),r=Math.floor(n/1e3),i=Math.floor(r/60),o=Math.floor(i/60),a=Math.floor(o/24),l=Math.floor(a/7),c=Math.floor(a/30),u=Math.floor(a/365),d="";return r<0?d=h("time.just_now"):r<60?d=h("time.just_now"):i<2?d=h("time.minute_ago"):i<60?d=h("time.minutes_ago",{count:i.toString()}):o<2?d=h("time.hour_ago"):o<24?d=h("time.hours_ago",{count:o.toString()}):a<2?d=h("time.day_ago"):a<7?d=h("time.days_ago",{count:a.toString()}):l<2?d=h("time.week_ago"):l<4?d=h("time.weeks_ago",{count:l.toString()}):c<2?d=h("time.month_ago"):c<12?d=h("time.months_ago",{count:c.toString()}):u<2?d=h("time.year_ago"):d=h("time.years_ago",{count:u.toString()}),{formatted:d,originalDate:t.toISOString(),title:t.toLocaleString()}}function gr(s){let{formatted:t,title:e}=fe(s);return {text:t,title:e}}function fr(s){return fe(s).formatted}function mr(s){return fe(s).title}setConfig({devMode:false,sanitizeHTML:true});export{te as CombinedContext,m as Component,G as Context,he as Dropdown,z as I18nManager,ue as ItemsLoader,I as Loader,Z as Popup,ve as Provider,ie as Router,_e as SmartForm,V as SmartFormComponent,ae as Store,D as StyleManager,x as TabbedView,Y as Toast,Se as VisibilityObserver,Ce as camelCase,Ge as capitalize,et as clamp,Be as classNames,Pe as clearHookContext,qt as client,dt as computed,Ut as connect,vt as createCombinedContext,Dt as createComputedStore,mt as createContext,ar as createDropdown,Pt as createFunctionalComponent,tr as createItemsLoader,Re as createStore,He as createTabbedView,sn as createTranslator,be as css,De as debounce,H as deepClone,ge as deepMerge,ze as formatDate,fe as formatRelativeTime,fr as formatTimeAgo,Zt as getCurrentLanguage,oe as getCurrentPath,S as getI18n,M as getPopup,At as getQueryParam,Oe as getQueryParams,tn as getSupportedLanguages,gr as getTimeDisplay,mr as getTimeTitle,q as getToast,rn as getTranslations,Ot as goBack,Rt as goForward,nn as hasKey,Ae as initPopup,Fe as initToast,an as initializeI18n,tt as isBrowser,$t as isCurrentPath,Vt as isCurrentPathPrefix,We as isEmpty,Je as kebabCase,on as loadFromUrl,Xt as loadLanguage,cn as loadLanguageFile,en as loadTranslations,Wn as mountTabbedView,we as navigate,Kt as navigateWithQuery,dr as observeVisibility,Ze as parseQuery,Qe as pascalCase,An as popup,Ft as reloadRoute,R as router,nt as safeJsonParse,U as scheduler,Me as setHookContext,Qt as setLanguage,Yt as setLanguageAsync,ln as setupI18n,qe as sleep,g as state,Xe as stringifyQuery,h as t,le as tHtml,Jt as tLang,Ue as throttle,fn as toast,Ye as truncate,je as uniqueId,re as useCallback,bt as useContext,Ct as useDebounce,O as useEffect,Mt as useEventListener,kt as useFetch,xt as useInterval,_t as useLocalStorage,Ie as useMemo,St as usePrevious,Tt as useReducer,se as useRef,N as useState,Et as useToggle,Lt as useWindowSize,cr as utils,ht as watch};//# sourceMappingURL=main.js.map
117
+ `}styles(){return be``}};p([g],V.prototype,"fields"),p([g],V.prototype,"formData"),p([g],V.prototype,"isSubmitting"),p([g],V.prototype,"submitError"),p([g],V.prototype,"submitSuccess");function _e(i){return new V(i).render()}var w={container:"bb_popupContainer",overlay:"bb_popupOverlay",popup:{base:"bb_popup",close:"bb_popupClose"},header:{container:"bb_popupHeader",icon:"bb_popupHeaderIcon",content:"bb_popupHeaderContent",title:"bb_popupHeaderContentTitle",description:"bb_popupHeaderContentDesc"},body:{container:"bb_popupBody",message:"bb_popupBodyMsg",input:"bb_popupBodyInput",formContainer:"bb_popupBodyFormContainer"},footer:"bb_popupFooter",button:"bb_btn"},Z=class extends m{constructor(){super(...arguments);this.popups=[];this.nextId=0;}async onMount(){this.setupKeyboardListener(),window.addEventListener("languagechange",()=>{this.update();});}onUnmount(){this.handleEscapeKey&&document.removeEventListener("keydown",this.handleEscapeKey);}render(){return this.popups.length===0?createElement("div",{className:w.container}):createElement("div",{className:w.container},...this.popups.map(e=>this.renderPopup(e)))}renderPopup(e){let n=`bb_popup--${e.size||"medium"}`,r=e.variant?`bb_popup--${e.variant}`:"";return createElement("div",{key:String(e.id),className:w.overlay,"data-popup-id":e.id,onClick:s=>{s.target.classList.contains(w.overlay)&&e.closeOnOverlay!==false&&this.closePopup(e.id,false);}},createElement("div",{className:`${w.popup.base} ${n} ${r}`,role:"dialog","aria-modal":"true","aria-labelledby":`popup-title-${e.id}`},e.showCloseButton!==false?createElement("button",{className:w.popup.close,onClick:()=>this.closePopup(e.id,false),"aria-label":"Close"},createElement("i",{className:"fas fa-times"})):null,createElement("div",{className:w.header.container},e.icon?createElement("div",{className:w.header.icon},createElement("i",{className:e.icon})):null,createElement("div",{className:w.header.content},createElement("h2",{id:`popup-title-${e.id}`,className:w.header.title,"data-translate":e.titleTranslateKey},e.titleTranslateKey?h(e.titleTranslateKey):e.title),e.description?createElement("p",{className:w.header.description,"data-translate":e.descriptionTranslateKey},e.descriptionTranslateKey?le(e.descriptionTranslateKey):e.description):null)),createElement("div",{className:w.body.container},e.message?createElement("p",{className:w.body.message,"data-translate":e.messageTranslateKey},e.messageTranslateKey?le(e.messageTranslateKey):e.message):null,e.type==="prompt"?createElement("input",{type:"text",className:w.body.input,value:e.inputValue||"",placeholder:h("popup.prompt.placeholder"),"data-translate":"popup.prompt.placeholder",onInput:s=>{e.inputValue=s.target.value;}}):null,e.type==="form"&&e.formConfig?createElement("div",{className:w.body.formContainer},_e(e.formConfig)):null,e.customContent||null),e.buttons&&e.buttons.length>0&&e.type!=="form"?createElement("div",{className:w.footer},...e.buttons.map(s=>createElement("button",{className:`${w.button} ${s.variant||"secondary"}`,"data-translate":s.translateKey,disabled:s.loading||e.isSubmitting,onClick:async()=>{s.loading||e.isSubmitting||await s.onClick();}},s.icon?createElement("i",{className:s.icon}):null,s.loading||e.isSubmitting?createElement("i",{className:"fas fa-spinner fa-spin"}):null," ",s.translateKey?h(s.translateKey):s.label))):null))}show(e){return new Promise(n=>{let r=this.nextId++,s={...e,id:r,resolve:n,type:e.type||"custom",size:e.size||"medium",closeOnOverlay:e.closeOnOverlay!==false,closeOnEscape:e.closeOnEscape!==false,showCloseButton:e.showCloseButton!==false,isSubmitting:false};this.popups=[...this.popups,s],this.applyBodyLock(),this.update();})}showForm(e){return new Promise((n,r)=>{let s=this.nextId++,o={...e.formConfig,onSubmit:async l=>{let c=this.popups.find(u=>u.id===s);c&&(c.isSubmitting=true,this.update());try{e.formConfig.onSubmit&&await e.formConfig.onSubmit(l,void 0),this.closePopup(s,l),n(l);}catch(u){c&&(c.isSubmitting=false,this.update()),e.formConfig.onError&&e.formConfig.onError(u);}},submitButton:{...e.formConfig.submitButton,className:e.formConfig.submitButton?.className||`${w.button} primary wide`}},a={title:e.title,titleTranslateKey:e.titleTranslateKey,description:e.description,descriptionTranslateKey:e.descriptionTranslateKey,type:"form",variant:e.variant||"default",size:e.size||"medium",icon:e.icon,formConfig:o,closeOnOverlay:e.closeOnOverlay!==false,closeOnEscape:e.closeOnEscape!==false,showCloseButton:e.showCloseButton!==false,id:s,resolve:n,isSubmitting:false};this.popups=[...this.popups,a],this.applyBodyLock(),this.update();})}confirm(e){return new Promise(n=>{let r=this.nextId++,s={id:r,title:e.title,titleTranslateKey:e.titleTranslateKey,message:e.message,messageTranslateKey:e.messageTranslateKey,type:"confirm",variant:e.variant||"default",size:e.size||"small",icon:e.icon,resolve:n,onConfirm:e.onConfirm,onCancel:e.onCancel,buttons:[{label:e.cancelLabel||"Cancel",translateKey:e.cancelTranslateKey||"button.cancel",variant:"secondary",icon:"fas fa-times",onClick:async()=>{e.onCancel&&await e.onCancel(),this.closePopup(r,false);}},{label:e.confirmLabel||"Confirm",translateKey:e.confirmTranslateKey||"button.confirm",variant:e.variant==="danger"?"danger":"primary",icon:"fas fa-check",onClick:async()=>{e.onConfirm&&await e.onConfirm(),this.closePopup(r,true);}}]};this.popups=[...this.popups,s],this.applyBodyLock(),this.update();})}alert(e){return new Promise(n=>{let r=this.nextId++,s={id:r,title:e.title,titleTranslateKey:e.titleTranslateKey,message:e.message,messageTranslateKey:e.messageTranslateKey,type:"alert",variant:e.variant||"info",size:e.size||"small",icon:e.icon,resolve:n,onConfirm:e.onConfirm,buttons:[{label:e.okLabel||"OK",translateKey:e.okTranslateKey||"popup.ok",variant:"primary",icon:"fas fa-check",onClick:async()=>{e.onConfirm&&await e.onConfirm(),this.closePopup(r,true);}}]};this.popups=[...this.popups,s],this.applyBodyLock(),this.update();})}prompt(e){return new Promise(n=>{let r=this.nextId++,s={id:r,title:e.title,titleTranslateKey:e.titleTranslateKey,message:e.message,messageTranslateKey:e.messageTranslateKey,type:"prompt",variant:"default",icon:e.icon,inputValue:e.defaultValue||"",resolve:n,onConfirm:e.onConfirm,onCancel:e.onCancel,buttons:[{label:e.cancelLabel||"Cancel",translateKey:e.cancelTranslateKey||"popup.cancel",variant:"secondary",onClick:async()=>{e.onCancel&&await e.onCancel(),this.closePopup(r,null);}},{label:e.confirmLabel||"OK",translateKey:e.confirmTranslateKey||"popup.ok",variant:"primary",onClick:async()=>{let o=s.inputValue||"";e.onConfirm&&await e.onConfirm(o),this.closePopup(r,o);}}]};this.popups=[...this.popups,s],this.applyBodyLock();})}closePopup(e,n){let r=this.popups.find(s=>s.id===e);r?.resolve&&r.resolve(n),this.popups=this.popups.filter(s=>s.id!==e),this.popups.length===0&&this.removeBodyLock(),this.update();}closeAll(){this.popups.forEach(e=>{e.resolve&&e.resolve(false);}),this.popups=[],this.removeBodyLock(),this.update();}applyBodyLock(){document.body.style.overflow="hidden";}removeBodyLock(){document.body.style.overflow="";}setupKeyboardListener(){this.handleEscapeKey=e=>{if(e.key==="Escape"&&this.popups.length>0){let n=this.popups[this.popups.length-1];n.closeOnEscape!==false&&this.closePopup(n.id,false);}},document.addEventListener("keydown",this.handleEscapeKey);}};p([g],Z.prototype,"popups");var F=null;function Ae(i){if(F)return F;let t=i||document.createElement("div");return i||document.body.appendChild(t),F=new Z,F.mount(t),F}function M(){return F||(F=Ae()),F}var An={show:i=>M().show(i),confirm:i=>M().confirm(i),alert:i=>M().alert(i),prompt:i=>M().prompt(i),showForm:i=>M().showForm(i),closePopup:(i,t)=>M().closePopup(i,t),closeLastPopup:()=>M().closePopup(M().popups.length-1,false),closeFirstPopup:()=>M().closePopup(0,false),closeAll:()=>M().closeAll()};var P={container:"bb_tabbedview",header:"bb_tabbedviewHeader",tab:{base:"bb_tabbedviewTab",active:"bb_tabbedviewTab--active",disabled:"bb_tabbedviewTab--disabled",badge:"bb_tabbedviewBadge"},content:{container:"bb_tabbedviewContent",emptyState:"bb_tabbedviewEmptyState",error:"bb_tabbedviewError"}},x=class extends m{constructor(){super(...arguments);this.activeTabId="";this.tabs=[];this.position="top";this.style="default";this.className="";this.headerClassName="";this.contentClassName="";this.showTabCount=false;this.persistState=false;this.storageKey="tabbedview-active";this.currentTabComponent=null;}async onMount(){window.addEventListener("languagechange",()=>{this.update();});}onUnmount(){this.currentTabComponent&&typeof this.currentTabComponent.onUnmount=="function"&&this.currentTabComponent.onUnmount();}init(e){if(this.tabs=e.tabs,this.position=e.position||"top",this.style=e.style||"default",this.className=e.className||"",this.headerClassName=e.headerClassName||"",this.contentClassName=e.contentClassName||"",this.showTabCount=e.showTabCount||false,this.persistState=e.persistState||false,this.storageKey=e.storageKey||"tabbedview-active",this.onChange=e.onChange,this.persistState){let n=localStorage.getItem(this.storageKey);n&&this.tabs.find(r=>r.id===n)&&(this.activeTabId=n);}return this.activeTabId||(this.activeTabId=e.defaultTab||this.tabs[0]?.id||""),this.update(),this}async setActiveTab(e){let n=this.tabs.find(r=>r.id===e);!n||n.disabled||(this.currentTabComponent&&typeof this.currentTabComponent.onUnmount=="function"&&this.currentTabComponent.onUnmount(),this.currentTabComponent=null,this.activeTabId=e,this.persistState&&localStorage.setItem(this.storageKey,e),n.onActivate&&await n.onActivate(),this.onChange&&await this.onChange(e),this.update());}addTab(e){this.tabs=[...this.tabs,e],this.update();}removeTab(e){this.tabs=this.tabs.filter(n=>n.id!==e),this.activeTabId===e&&this.tabs.length>0&&(this.activeTabId=this.tabs[0].id),this.update();}updateTab(e,n){let r=this.tabs.find(s=>s.id===e);r&&(Object.assign(r,n),this.update());}getActiveTab(){return this.tabs.find(e=>e.id===this.activeTabId)}render(){let e=[P.container,`bb_tabbedview__--${this.position}`,`bb_tabbedview__--${this.style}`,this.className].filter(Boolean).join(" ");return createElement("div",{className:e},this.renderTabList(),this.renderTabContent())}renderTabList(){let e=[P.header,this.headerClassName].filter(Boolean).join(" ");return createElement("div",{className:e},...this.tabs.map(n=>this.renderTab(n)))}renderTab(e){let n=this.activeTabId===e.id,r=[P.tab.base,n?P.tab.active:"",e.disabled?P.tab.disabled:""].filter(Boolean).join(" "),s=e.translateKey?h(e.translateKey):e.label;return createElement("button",{key:e.id,className:r,onclick:()=>this.setActiveTab(e.id),disabled:e.disabled,"data-translate":e.translateKey,"aria-selected":n,role:"tab"},e.icon?createElement("i",{className:e.icon}):null,createElement("span",{},s),e.badge!==void 0&&e.badge!==null&&e.badge!==0?createElement("span",{className:P.tab.badge},typeof e.badge=="number"&&e.badge>99?"99+":String(e.badge)):null)}renderTabContent(){let e=[P.content.container,this.contentClassName].filter(Boolean).join(" "),n=this.getActiveTab();return n?createElement("div",{className:e,role:"tabpanel"},this.renderActiveTabContent(n)):createElement("div",{className:e},createElement("div",{className:P.content.emptyState},createElement("p",{},h("global.loading"))))}renderActiveTabContent(e){if(e.component)try{if(e.component instanceof m){this.currentTabComponent=e.component;let n=this.currentTabComponent.render(),r={...n.props,ref:o=>{o&&this.currentTabComponent&&this.currentTabComponent.setElement(o),typeof n.props.ref=="function"&&n.props.ref(o);}},s={...n,props:r};return typeof this.currentTabComponent.onMount=="function"&&setTimeout(()=>{this.currentTabComponent&&typeof this.currentTabComponent.onMount=="function"&&this.currentTabComponent.onMount();},0),s}if(typeof e.component=="function"){let n=e.component;return n.prototype&&typeof n.prototype.render=="function"?(this.currentTabComponent||(this.currentTabComponent=new n,this.currentTabComponent&&typeof this.currentTabComponent.onMount=="function"&&setTimeout(()=>{this.currentTabComponent&&typeof this.currentTabComponent.onMount=="function"&&this.currentTabComponent.onMount();},0)),this.currentTabComponent.render()):n()}}catch(n){return console.error("Error rendering tab component:",n),createElement("div",{className:P.content.error},h("global.loading"))}return e.content?e.content:createElement("div",{className:P.content.emptyState},createElement("p",{},h("global.loading")))}};p([g],x.prototype,"activeTabId"),p([g],x.prototype,"tabs"),p([g],x.prototype,"position"),p([g],x.prototype,"style"),p([g],x.prototype,"className"),p([g],x.prototype,"headerClassName"),p([g],x.prototype,"contentClassName"),p([g],x.prototype,"showTabCount"),p([g],x.prototype,"persistState"),p([g],x.prototype,"storageKey");function He(i){let t=new x;return t.init(i),t}async function Wn(i,t){let e=He(t);return await e.mount(i),e}var f={container:"bb_itemsLoaderContainer",list:"bb_itemsLoaderList",searchbar:"bb_itemsLoaderSearchbar",loading:"bb_itemsLoaderLoading",error:"bb_itemsLoaderError",trigger:"bb_itemsLoaderTrigger",end:"bb_itemsLoaderEnd",emptyState:"bb_tabbedviewEmptyState",button:"bb_btn",item:"bb_itemsLoader-item",formFieldInput:"bb_formFieldInput"},ue=class extends m{constructor(){super(...arguments);this.items=[];this.loadState={loading:false,error:null,hasMore:true,page:0,total:0};this.filters={};this.scrollContainer=null;this.loadMoreObserver=null;this.currentLoadMoreTrigger=null;this.loadMoreMutationObserver=null;this.visibilityObserver=null;this.viewedItems=new Set;this.dropdownIsOpen=false;this.itemsListContainer=null;this.searchInput=null;this.isUpdating=false;this.searchDebounceTimer=null;this.handleScroll=()=>{if(!this.scrollContainer||this.loadState.loading||!this.loadState.hasMore)return;let{scrollTop:e,scrollHeight:n,clientHeight:r}=this.scrollContainer;n-e-r<this.config.scrollThreshold&&this.loadMore();};this.handleItemClick=(e,n)=>{this.config.onItemClick?.(e,n);};}initialize(e){this.config={pageSize:10,loadMoreText:"Load More",loadingText:"Loading...",errorText:"Failed to load items",containerClassName:f.container,itemClassName:f.item,enableInfiniteScroll:true,scrollThreshold:200,enableSearch:false,searchPlaceholder:"Search...",searchFilterKey:"search",searchDebounceMs:300,enableVisibilityTracking:false,visibilityThreshold:.5,visibilityRootMargin:"0px",extractItems:n=>n.notifications||n.items||n.data||n.logs||[],extractTotal:n=>n.pagination?.total||n.total||n.count||0,...e},this.config.filters&&(this.filters={...this.config.filters}),this.config.initialItems&&(this.items=[...this.config.initialItems]);}async onMount(){this.items.length===0&&await this.loadMore(),this.config.enableInfiniteScroll&&this.setupInfiniteScroll(),this.config.scrollThreshold&&this.setupScrollListener(),this.config.enableVisibilityTracking&&this.setupVisibilityTracking();}onUnmount(){this.disconnectInfiniteScrollObserver(),this.disconnectVisibilityObserver(),this.loadMoreMutationObserver&&(this.loadMoreMutationObserver.disconnect(),this.loadMoreMutationObserver=null),this.scrollContainer&&(this.scrollContainer.removeEventListener("scroll",this.handleScroll),this.scrollContainer=null),this.searchDebounceTimer&&clearTimeout(this.searchDebounceTimer);}async loadMore(){if(!(this.loadState.loading||!this.loadState.hasMore))try{let e=this.scrollContainer||this.findScrollContainer(),n=e?.scrollTop||0,r=e?.scrollHeight||0;this.loadState={...this.loadState,loading:!0,error:null},this.updateLoadingState();let s=this.loadState.page+1,o=this.buildUrl(s),a=await fetch(o,{credentials:"include",headers:this.buildHeaders()});if(!a.ok)throw new Error(`HTTP ${a.status}: ${a.statusText}`);let l=await a.json(),c=this.config.extractItems(l),u=this.config.extractTotal(l);this.items=[...this.items,...c],this.loadState={loading:!1,error:null,hasMore:this.items.length<u,page:s,total:u},this.updateLoadingState(),this.appendNewItems(c),e&&n>0&&(e.scrollTop=n,requestAnimationFrame(()=>{let y=e.scrollHeight-r;Math.abs(y)>10&&(e.scrollTop=n);})),this.reconnectInfiniteScrollObserver(),this.config.onLoadMore?.(s,this.items);}catch(e){this.loadState={...this.loadState,loading:false,error:e instanceof Error?e.message:this.config.errorText},this.updateLoadingState(),this.updateFooter(),this.config.onError?.(e instanceof Error?e:new Error("Unknown error"));}}async reload(){this.items=[],this.loadState={loading:false,error:null,hasMore:true,page:0,total:0},await this.loadMore();}async applyFilters(e){if(!this.isUpdating){this.isUpdating=true,this.filters={...e},this.items=[],this.loadState={loading:true,error:null,hasMore:true,page:0,total:0},this.updateLoadingState();try{let n=this.buildUrl(1),r=await fetch(n,{credentials:"include",headers:this.buildHeaders()});if(!r.ok)throw new Error(`HTTP ${r.status}: ${r.statusText}`);let s=await r.json(),o=this.config.extractItems(s),a=this.config.extractTotal(s);this.items=[...o],this.loadState={loading:!1,error:null,hasMore:this.items.length<a,page:1,total:a},this.itemsListContainer&&(this.itemsListContainer.innerHTML=""),this.element&&this.element.querySelectorAll(`.${f.trigger}, .${f.end}, .${f.error}, .${f.loading}, .${f.emptyState}`).forEach(l=>l.remove()),this.items.length>0?(this.itemsListContainer||(this.itemsListContainer=this.element?.querySelector(`.${f.list}`)),this.itemsListContainer&&this.appendNewItems(this.items)):this.updateFooter(),this.itemsListContainer=this.element?.querySelector(`.${f.list}`),this.reconnectInfiniteScrollObserver(),this.config.onLoadMore?.(1,this.items),this.config.onFiltersChange?.(this.filters);}catch(n){this.loadState={...this.loadState,loading:false,error:n instanceof Error?n.message:this.config.errorText},this.updateLoadingState(),this.config.onError?.(n instanceof Error?n:new Error("Unknown error"));}finally{this.isUpdating=false;}}}async handleSearch(e){this.searchDebounceTimer&&clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{let n={...this.filters};e.trim()?n[this.config.searchFilterKey]=e.trim():delete n[this.config.searchFilterKey],await this.applyFilters(n);},this.config.searchDebounceMs);}updateItems(e){this.items=[...e],this.itemsListContainer&&(this.itemsListContainer.innerHTML="",this.appendNewItems(e));}setupVisibilityTracking(){if(!this.config.enableVisibilityTracking)return;this.visibilityObserver&&this.visibilityObserver.disconnect();let e=this.findScrollContainer();this.visibilityObserver=new IntersectionObserver(n=>{n.forEach(r=>{if(r.isIntersecting&&this.dropdownIsOpen){let s=r.target,o=parseInt(s.getAttribute("data-item-index")||"-1");if(o>=0&&o<this.items.length){let a=this.items[o],l=this.config.getItemId?.(a),c=this.config.shouldTrackItem?.(a)??true;l&&!this.viewedItems.has(l)&&c&&this.viewedItems.add(l);}}});},{root:e,rootMargin:this.config.visibilityRootMargin,threshold:this.config.visibilityThreshold}),this.observeTrackableItems();}observeTrackableItems(){if(!this.visibilityObserver||!this.itemsListContainer)return;this.itemsListContainer.querySelectorAll("[data-item-index]").forEach(n=>{let r=parseInt(n.getAttribute("data-item-index")||"-1");if(r>=0&&r<this.items.length){let s=this.items[r];(this.config.shouldTrackItem?.(s)??true)&&this.visibilityObserver.observe(n);}});}trackAlreadyVisibleItems(){if(!this.itemsListContainer)return;let e=this.findScrollContainer();if(!e)return;let n=this.itemsListContainer.querySelectorAll("[data-item-index]"),r=e.getBoundingClientRect();n.forEach(s=>{let o=parseInt(s.getAttribute("data-item-index")||"-1");if(o<0||o>=this.items.length)return;let a=this.items[o],l=this.config.getItemId?.(a);if(!l||this.viewedItems.has(l)||!(this.config.shouldTrackItem?.(a)??true))return;let u=s.getBoundingClientRect();u.top<r.bottom&&u.bottom>r.top&&u.top>=r.top-100&&u.bottom<=r.bottom+100&&this.viewedItems.add(l);});}disconnectVisibilityObserver(){this.visibilityObserver&&(this.visibilityObserver.disconnect(),this.visibilityObserver=null);}handleDropdownOpen(){this.dropdownIsOpen=true,this.viewedItems.clear(),this.config.enableVisibilityTracking&&(this.trackAlreadyVisibleItems(),this.observeTrackableItems()),this.config.onDropdownOpen?.();}async handleDropdownClose(){if(this.dropdownIsOpen=false,this.viewedItems.size>0&&this.config.onItemsViewed){let e=this.items.filter(n=>{let r=this.config.getItemId?.(n);return r&&this.viewedItems.has(r)});await this.config.onItemsViewed(e);}this.viewedItems.clear(),this.config.onDropdownClose?.();}async performBatchAction(e,n){this.config.onBatchAction&&await this.config.onBatchAction(e,n);}appendNewItems(e){if(this.itemsListContainer||(this.itemsListContainer=this.element?.querySelector(`.${f.list}`)),!this.itemsListContainer)return;let n=document.createDocumentFragment(),r=this.items.length-e.length;e.forEach((s,o)=>{let a=r+o,l=this.config.renderItem(s,a);l.setAttribute("data-item-index",a.toString()),this.config.onItemClick?(l.className=`${l.className} ${this.config.itemClassName} clickable`,l.onclick=()=>this.handleItemClick(s,a)):l.className=`${l.className} ${this.config.itemClassName}`,n.appendChild(l);}),this.itemsListContainer.appendChild(n),this.updateFooter(),this.config.enableVisibilityTracking&&this.dropdownIsOpen&&setTimeout(()=>this.observeTrackableItems(),100);}updateLoadingState(){let e=this.element?.querySelector(`.${f.container}`);if(!e)return;let n=e.querySelector(`.${f.loading}`);if(this.loadState.loading){if(!n){let r=this.renderLoading();n=this.createElementFromVNode(r),e.appendChild(n);}}else n&&n.remove();}updateFooter(){let e=this.element;if(e){if(e.querySelectorAll(`.${f.trigger}, .${f.end}, .${f.emptyState}`).forEach(n=>{n.remove();}),this.items.length===0&&!this.loadState.loading&&this.config.emptyStateConfig){let n=this.renderEmptyState(),r=createDOMElement(n);e.appendChild(r);return}if(this.loadState.hasMore&&!this.loadState.loading&&this.items.length>0){let n=this.renderLoadMoreTrigger(),r=createDOMElement(n);e.appendChild(r);}if(!this.loadState.hasMore&&this.items.length>0){let n=this.renderEndMessage(),r=createDOMElement(n);e.appendChild(r);}}}setupInfiniteScroll(){this.loadMoreObserver&&this.loadMoreObserver.disconnect(),this.loadMoreObserver=new IntersectionObserver(e=>{let[n]=e;n.isIntersecting&&!this.loadState.loading&&this.loadState.hasMore&&this.loadMore();},{threshold:.1,rootMargin:"50px"}),this.reconnectInfiniteScrollObserver();}reconnectInfiniteScrollObserver(){if(!this.config.enableInfiniteScroll||!this.loadMoreObserver)return;this.currentLoadMoreTrigger&&(this.loadMoreObserver.unobserve(this.currentLoadMoreTrigger),this.currentLoadMoreTrigger=null);let e=()=>{let n=this.element?.querySelector('[data-load-more-trigger="true"]');return n?(this.loadMoreObserver.observe(n),this.currentLoadMoreTrigger=n,true):false};e()||(this.loadMoreMutationObserver&&this.loadMoreMutationObserver.disconnect(),this.loadMoreMutationObserver=new MutationObserver(()=>{e()&&this.loadMoreMutationObserver&&(this.loadMoreMutationObserver.disconnect(),this.loadMoreMutationObserver=null);}),this.element&&(this.loadMoreMutationObserver.observe(this.element,{childList:true,subtree:true}),setTimeout(()=>{this.loadMoreMutationObserver&&(this.loadMoreMutationObserver.disconnect(),this.loadMoreMutationObserver=null);},5e3)));}disconnectInfiniteScrollObserver(){this.loadMoreObserver&&this.currentLoadMoreTrigger&&(this.loadMoreObserver.unobserve(this.currentLoadMoreTrigger),this.currentLoadMoreTrigger=null);}setupScrollListener(){requestAnimationFrame(()=>{this.scrollContainer=this.findScrollContainer(),this.scrollContainer&&("scrollRestoration"in history&&(history.scrollRestoration="manual"),this.scrollContainer.addEventListener("scroll",this.handleScroll));});}findScrollContainer(){let e=[this.element?.closest(".bb_notificationsContent"),this.element?.closest(".bb_dropdownMenu"),this.element?.querySelector("[data-notifications-loader]"),this.element?.closest("[data-notifications-loader]"),this.element?.closest(".scrollbar-thin"),this.element?.parentElement,this.element];for(let n of e)if(n){let r=n;if(r.scrollHeight>r.clientHeight||r.classList.contains("scrollbar-thin"))return r}return null}buildUrl(e){if(typeof this.config.fetchUrl=="function")return this.config.fetchUrl(e,this.filters);let n=this.config.fetchUrl.includes("?")?"&":"?",r=new URLSearchParams({page:e.toString(),limit:this.config.pageSize.toString(),...this.filters});return `${this.config.fetchUrl}${n}${r}`}buildHeaders(){let e={"Content-Type":"application/json"},n=this.config.getAuthToken?.();return n&&(e.Authorization=`Bearer ${n}`),e}createElementFromVNode(e){if(typeof e.type!="string")throw new Error("Can only create elements from string types");let n=document.createElement(e.type);return e.props&&Object.entries(e.props).forEach(([r,s])=>{r==="className"?n.className=s:r==="style"?typeof s=="string"?n.setAttribute("style",s):typeof s=="object"&&s!==null&&Object.assign(n.style,s):r==="onclick"&&typeof s=="function"?n.addEventListener("click",s):r!=="children"&&r!=="ref"&&n.setAttribute(r,String(s));}),e.children&&e.children.forEach(r=>{r!=null&&(typeof r=="string"||typeof r=="number"?n.appendChild(document.createTextNode(String(r))):typeof r=="object"&&n.appendChild(this.createElementFromVNode(r)));}),n}render(){return createElement("div",{className:this.config.containerClassName},this.config.enableSearch?this.renderSearchBar():null,createElement("div",{className:f.list,ref:e=>{e&&(this.itemsListContainer=e);}}),this.loadState.error?this.renderError():null,this.loadState.loading?this.renderLoading():null,this.loadState.hasMore&&!this.loadState.loading&&this.items.length>0?this.renderLoadMoreTrigger():null,!this.loadState.hasMore&&this.items.length>0?this.renderEndMessage():null)}renderSearchBar(){return createElement("div",{className:f.searchbar},createElement("div",{className:"row gap-sm"},createElement("i",{className:"fas fa-search"}),createElement("input",{type:"text",className:f.formFieldInput,placeholder:this.config.searchPlaceholder,ref:e=>{e&&(this.searchInput=e,this.searchInput.addEventListener("input",n=>{let r=n.target.value;this.handleSearch(r);}));}})))}renderEmptyState(){let e=this.config.emptyStateConfig;return createElement("div",{className:f.emptyState},createElement("i",{className:`__icon ${e.icon}`}),createElement("h3",{className:"__title"},e.title),createElement("p",{className:"__desc"},e.description))}renderLoading(){return createElement("div",{className:f.loading},createElement("i",{className:"fas fa-spinner fa-spin"}),createElement("p",{},this.config.loadingText))}renderError(){return createElement("div",{className:f.error},createElement("i",{className:"fas fa-exclamation-triangle"}),createElement("p",{},this.loadState.error),createElement("button",{className:`${f.button} secondary`,onclick:()=>this.loadMore()},createElement("i",{className:"fas fa-redo"})," Retry"))}renderLoadMoreTrigger(){return createElement("div",{className:f.trigger,"data-load-more-trigger":"true",style:"height: 1px; visibility: hidden;"})}renderEndMessage(){return createElement("div",{className:f.end},createElement("i",{className:"fas fa-check-circle"}),h("All loaded",{count:String(this.loadState.total)}))}};function tr(i){let t=new ue;return t.initialize(i),t}var de=class i{constructor(){this.dropdowns=new Map;this.hierarchy=new Map;this.setupGlobalClickHandler();}static getInstance(){return i.instance||(i.instance=new i),i.instance}register(t){this.dropdowns.set(t.config.id,t),t.config.parentId&&this.hierarchy.set(t.config.id,t.config.parentId);}unregister(t){this.dropdowns.delete(t),this.hierarchy.delete(t);}open(t){let e=this.dropdowns.get(t);e&&(this.closeSiblings(t),e.setOpen(true));}close(t){let e=this.dropdowns.get(t);e&&(e.setOpen(false),this.closeChildren(t));}closeAll(){Array.from(this.dropdowns.values()).filter(e=>!e.config.parentId).forEach(e=>this.close(e.config.id));}destroy(){this.clickHandler&&typeof window<"u"&&document.removeEventListener("click",this.clickHandler,true),this.dropdowns.clear(),this.hierarchy.clear();}isAncestor(t,e){let n=e;for(;n;){if(n===t)return true;n=this.hierarchy.get(n);}return false}isDescendant(t,e){return this.isAncestor(e,t)}getAncestors(t){let e=new Set,n=t;for(;n;){let r=this.hierarchy.get(n);if(r)e.add(r),n=r;else break}return e}getDescendants(t){let e=new Set,n=r=>{Array.from(this.hierarchy.entries()).filter(([o,a])=>a===r).map(([o,a])=>o).forEach(o=>{e.add(o),n(o);});};return n(t),e}closeSiblings(t){let e=this.dropdowns.get(t);if(!e)return;let n=e.config.parentId;Array.from(this.dropdowns.values()).filter(s=>s.config.parentId===n&&s.config.id!==t).forEach(s=>this.close(s.config.id));}closeChildren(t){Array.from(this.dropdowns.values()).filter(n=>n.config.parentId===t).forEach(n=>this.close(n.config.id));}hasOpenDropdowns(){return Array.from(this.dropdowns.values()).some(t=>t.isOpen)}findDropdownForElement(t){let e=t;for(;e&&e!==document.body;){let n=e.getAttribute("data-dropdown-id");if(n)return n;e=e.parentElement;}return null}setupGlobalClickHandler(){typeof window>"u"||(this.clickHandler=t=>{let e=t.target;if(!this.hasOpenDropdowns())return;let n=this.findDropdownForElement(e);if(!n){this.closeAll();return}if(this.dropdowns.get(n)?.config.preventAutoClose||e.closest(".bb_dropdownTrigger"))return;if(e.closest(".bb_dropdownMenu")){let a=this.getAncestors(n),l=this.getDescendants(n);Array.from(this.dropdowns.values()).filter(u=>!u.config.parentId).forEach(u=>{let d=u.config.id;d===n||a.has(d)||l.has(d)||this.isDescendant(n,d)||this.close(d);});}},document.addEventListener("click",this.clickHandler,true));}},W=de.getInstance(),he=class extends m{constructor(e){super();this.isOpen=false;this.mounted=false;this.config={closeOnItemClick:true,preventAutoClose:false,...e};}onMount(){this.mounted=true,W.register(this);}onUnmount(){this.mounted=false,W.unregister(this.config.id);}setOpen(e){this.isOpen!==e&&(this.isOpen=e,e?this.config.onOpen?.():this.config.onClose?.(),this.updateDOM());}toggle(e){e.preventDefault(),e.stopPropagation(),this.isOpen?W.close(this.config.id):W.open(this.config.id);}handleItemClick(e,n){if(e.disabled){n.preventDefault(),n.stopPropagation();return}this.config.closeOnItemClick&&(n.preventDefault(),n.stopPropagation(),W.close(this.config.id)),e.onclick?.(n),this.config.onSelect?.(e);}render(){let e=this.renderTrigger(),n=this.isOpen?this.renderMenu():null,r=["bb_dropdown",`bb_dropdown--${this.config.position||"left"}`,this.isOpen?"bb_dropdown--open":"",this.config.asIcon?"bb_dropdown--asIcon":"",this.config.className||""].filter(Boolean).join(" ");return createElement("div",{className:r,"data-dropdown-id":this.config.id},e,n)}updateDOM(){if(!this.mounted||!this.element)return;this.isOpen?this.element.classList.add("bb_dropdown--open"):this.element.classList.remove("bb_dropdown--open");let n=this.element.querySelector(".bb_dropdownTrigger")?.nextElementSibling;if(this.isOpen){if(!n||!n.classList.contains("bb_dropdownMenu")){let r=this.renderMenu(),s=this.createElementFromVNode(r);this.element.appendChild(s);}}else n&&n.classList.contains("bb_dropdownMenu")&&n.remove();}createElementFromVNode(e){if(typeof e.type=="string"){let n=document.createElement(e.type);return e.props&&Object.entries(e.props).forEach(([r,s])=>{r==="className"?n.className=s:r==="onclick"&&typeof s=="function"?n.addEventListener("click",s):r!=="children"&&r!=="key"&&n.setAttribute(r,String(s));}),e.children&&e.children.forEach(r=>{r!=null&&(typeof r=="string"||typeof r=="number"?n.appendChild(document.createTextNode(String(r))):typeof r=="object"&&n.appendChild(this.createElementFromVNode(r)));}),n}return document.createElement("div")}renderTrigger(){let e=this.config.trigger.element?.(),n=["bb_dropdownTrigger",this.config.trigger.className||""].filter(Boolean).join(" ");if(e)return createElement("button",{className:n,onclick:s=>this.toggle(s)},e);let r=["bb_dropdownArrow","fas","fa-chevron-down",this.isOpen?"bb_dropdownArrow--open":"",this.config.hideArrow?"hidden":""].filter(Boolean).join(" ");return createElement("button",{className:n,onclick:s=>this.toggle(s)},this.config.trigger.icon?createElement("i",{className:this.config.trigger.icon}):null,this.config.trigger.text?createElement("span",{},this.config.trigger.text):null,createElement("i",{className:r}))}renderMenu(){return createElement("div",{className:"bb_dropdownMenu",onclick:e=>{this.config.preventAutoClose&&e.stopPropagation();}},this.config.items.map((e,n)=>{if(e==="divider")return createElement("div",{className:"bb_dropdown__divider",key:`divider-${n}`});let r=e.selected||this.config.defaultSelected&&e.id===this.config.defaultSelected,s=["bb_dropdownItem",e.className||"",e.disabled?"bb_dropdownItem--disabled":"",r?"bb_dropdownItem--selected":""].filter(Boolean).join(" "),o={key:e.id||`item-${n}`,className:s,onclick:a=>this.handleItemClick(e,a)};return e.disabled&&(o.disabled=true),createElement("button",o,e.icon?createElement("i",{className:e.icon}):null,createElement("span",{},e.label))}))}};function ar(i){return new he(i)}function De(i,t){let e=null;return (...n)=>{e!==null&&clearTimeout(e),e=setTimeout(()=>{e=null,i(...n);},t);}}function Ue(i,t){let e=0,n=null;return (...r)=>{let s=Date.now(),o=s-e;o>=t?(e=s,i(...r)):n||(n=setTimeout(()=>{e=Date.now(),n=null,i(...r);},t-o));}}function Be(...i){let t=[];for(let e of i)if(e){if(typeof e=="string")t.push(e);else if(typeof e=="object")for(let[n,r]of Object.entries(e))r&&t.push(n);}return t.join(" ")}function ze(i,t="YYYY-MM-DD"){let e=i instanceof Date?i:new Date(i);if(isNaN(e.getTime()))throw new Error("Invalid date provided to formatDate");let n=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0"),o=String(e.getHours()).padStart(2,"0"),a=String(e.getMinutes()).padStart(2,"0"),l=String(e.getSeconds()).padStart(2,"0");return t.replace("YYYY",String(n)).replace("MM",r).replace("DD",s).replace("HH",o).replace("mm",a).replace("ss",l)}function H(i){if(i===null||typeof i!="object")return i;if(i instanceof Date)return new Date(i.getTime());if(Array.isArray(i))return i.map(t=>H(t));if(i instanceof RegExp)return new RegExp(i.source,i.flags);if(i instanceof Map){let t=new Map;return i.forEach((e,n)=>{t.set(H(n),H(e));}),t}if(i instanceof Set){let t=new Set;return i.forEach(e=>{t.add(H(e));}),t}if(Object.prototype.toString.call(i)==="[object Object]"){let t={};for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=H(i[e]));return t}return i}function ge(i,...t){if(!t.length)return i;let e=t.shift();if(!e)return i;if(X(i)&&X(e)){for(let n in e)if(Object.prototype.hasOwnProperty.call(e,n)){let r=e[n],s=i[n];r!==void 0&&(X(r)&&!Array.isArray(r)?((!s||!X(s))&&(i[n]={}),ge(i[n],r)):i[n]=r);}}return ge(i,...t)}function X(i){return i!==null&&typeof i=="object"&&!Array.isArray(i)}var pe=0;function je(i="id"){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,11);pe=(pe||0)+1;let n=pe.toString(36);return `${i}_${t}_${e}_${n}`}function qe(i){if(i<0)throw new Error("Sleep duration must be non-negative");return new Promise(t=>setTimeout(t,i))}function We(i){return i==null?true:typeof i=="string"?i.trim().length===0:Array.isArray(i)?i.length===0:i instanceof Map||i instanceof Set?i.size===0:typeof i=="object"?Object.keys(i).length===0:false}function Ge(i){return i?i.charAt(0).toUpperCase()+i.slice(1):""}function Je(i){return i?i.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[\s_]+/g,"-").toLowerCase():""}function Ce(i){return i?i.replace(/[-_\s]+(.)?/g,(t,e)=>e?e.toUpperCase():"").replace(/^[A-Z]/,t=>t.toLowerCase()):""}function Qe(i){if(!i)return "";let t=Ce(i);return t.charAt(0).toUpperCase()+t.slice(1)}function Ye(i,t,e="..."){return !i||i.length<=t?i:i.substring(0,t-e.length)+e}function Ze(i){let t={},e=i.replace(/^\?/,"");if(!e)return t;let n=e.split("&");for(let r of n){let[s,o]=r.split("=").map(decodeURIComponent);if(!s)continue;let a=o||"";if(s.endsWith("[]")){let l=s.slice(0,-2);t[l]||(t[l]=[]),t[l].push(a);}else t[s]=a;}return t}function Xe(i){let t=[];for(let[e,n]of Object.entries(i))if(n!=null)if(Array.isArray(n))for(let r of n)r!=null&&t.push(`${encodeURIComponent(e)}[]=${encodeURIComponent(String(r))}`);else t.push(`${encodeURIComponent(e)}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}function et(i,t,e){return Math.min(Math.max(i,t),e)}function tt(){return typeof window<"u"&&typeof document<"u"}function nt(i,t){try{return JSON.parse(i)}catch{return t}}var cr={debounce:De,throttle:Ue,classNames:Be,formatDate:ze,deepClone:H,deepMerge:ge,uniqueId:je,sleep:qe,isEmpty:We,capitalize:Ge,kebabCase:Je,camelCase:Ce,pascalCase:Qe,truncate:Ye,parseQuery:Ze,stringifyQuery:Xe,clamp:et,isBrowser:tt,safeJsonParse:nt};var Se=class{constructor(t){this.observer=null;this.observedElements=new Map;this.observer=new IntersectionObserver(e=>{e.forEach(n=>{let r=this.observedElements.get(n.target)??false,s=n.isIntersecting;s&&!r?(this.observedElements.set(n.target,true),t.onEnter?.(n),t.once&&this.unobserve(n.target)):!s&&r&&(this.observedElements.set(n.target,false),t.onExit?.(n));});},{root:t.root||null,rootMargin:t.rootMargin||"0px",threshold:t.threshold??.1});}observe(t){this.observer&&(this.observer.observe(t),this.observedElements.set(t,false));}unobserve(t){this.observer&&(this.observer.unobserve(t),this.observedElements.delete(t));}disconnect(){this.observer&&(this.observer.disconnect(),this.observedElements.clear());}};function dr(i,t){let e=new IntersectionObserver(n=>{n.forEach(r=>{r.isIntersecting&&(t(r),e.unobserve(i));});},{threshold:.1});return e.observe(i),()=>e.disconnect()}function fe(i){let t=typeof i=="string"?new Date(i):i,n=new Date().getTime()-t.getTime(),r=Math.floor(n/1e3),s=Math.floor(r/60),o=Math.floor(s/60),a=Math.floor(o/24),l=Math.floor(a/7),c=Math.floor(a/30),u=Math.floor(a/365),d="";return r<0?d=h("time.just_now"):r<60?d=h("time.just_now"):s<2?d=h("time.minute_ago"):s<60?d=h("time.minutes_ago",{count:s.toString()}):o<2?d=h("time.hour_ago"):o<24?d=h("time.hours_ago",{count:o.toString()}):a<2?d=h("time.day_ago"):a<7?d=h("time.days_ago",{count:a.toString()}):l<2?d=h("time.week_ago"):l<4?d=h("time.weeks_ago",{count:l.toString()}):c<2?d=h("time.month_ago"):c<12?d=h("time.months_ago",{count:c.toString()}):u<2?d=h("time.year_ago"):d=h("time.years_ago",{count:u.toString()}),{formatted:d,originalDate:t.toISOString(),title:t.toLocaleString()}}function gr(i){let{formatted:t,title:e}=fe(i);return {text:t,title:e}}function fr(i){return fe(i).formatted}function mr(i){return fe(i).title}setConfig({devMode:false,sanitizeHTML:true});export{te as CombinedContext,m as Component,G as Context,he as Dropdown,z as I18nManager,ue as ItemsLoader,I as Loader,Z as Popup,ve as Provider,se as Router,_e as SmartForm,V as SmartFormComponent,ae as Store,D as StyleManager,x as TabbedView,Y as Toast,Se as VisibilityObserver,Ce as camelCase,Ge as capitalize,et as clamp,Be as classNames,Pe as clearHookContext,qt as client,dt as computed,Ut as connect,vt as createCombinedContext,Dt as createComputedStore,mt as createContext,ar as createDropdown,Pt as createFunctionalComponent,tr as createItemsLoader,Re as createStore,He as createTabbedView,sn as createTranslator,be as css,De as debounce,H as deepClone,ge as deepMerge,ze as formatDate,fe as formatRelativeTime,fr as formatTimeAgo,Zt as getCurrentLanguage,oe as getCurrentPath,S as getI18n,M as getPopup,At as getQueryParam,Oe as getQueryParams,tn as getSupportedLanguages,gr as getTimeDisplay,mr as getTimeTitle,q as getToast,rn as getTranslations,Ot as goBack,Rt as goForward,nn as hasKey,Ae as initPopup,Fe as initToast,an as initializeI18n,tt as isBrowser,$t as isCurrentPath,Vt as isCurrentPathPrefix,We as isEmpty,Je as kebabCase,on as loadFromUrl,Xt as loadLanguage,cn as loadLanguageFile,en as loadTranslations,Wn as mountTabbedView,we as navigate,Kt as navigateWithQuery,dr as observeVisibility,Ze as parseQuery,Qe as pascalCase,An as popup,Ft as reloadRoute,R as router,nt as safeJsonParse,U as scheduler,Me as setHookContext,Qt as setLanguage,Yt as setLanguageAsync,ln as setupI18n,qe as sleep,g as state,Xe as stringifyQuery,h as t,le as tHtml,Jt as tLang,Ue as throttle,fn as toast,Ye as truncate,je as uniqueId,re as useCallback,bt as useContext,Ct as useDebounce,O as useEffect,Mt as useEventListener,kt as useFetch,xt as useInterval,_t as useLocalStorage,Ie as useMemo,St as usePrevious,Tt as useReducer,ie as useRef,N as useState,Et as useToggle,Lt as useWindowSize,cr as utils,ht as watch};//# sourceMappingURL=main.js.map
118
118
  //# sourceMappingURL=main.js.map