@smilodon/core 1.11.1 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -1,2 +1,2 @@
1
- const createRendererHelpers=e=>({onSelect:e,getIndex:e=>{const t=e?.closest?.("[data-selectable]");if(!t)return null;const i=Number(t.dataset.index);return Number.isFinite(i)?i:null},keyboardFocus:e=>{const t=document.querySelector(`[data-selectable][data-index="${e}"]`);t?.focus?.()}});function renderTemplate(e,t,i){const n=document.createDocumentFragment();for(let e=0;e<t.length;e++){const o=t[e],s=document.createElement("div");s.innerHTML=i(o,e);let r=s.firstElementChild;if(!r){const t=document.createElement("div");for(t.setAttribute("data-selectable",""),t.setAttribute("data-index",String(e));s.firstChild;)t.appendChild(s.firstChild);n.appendChild(t);continue}r.hasAttribute("data-smilodon-handled")||(r.setAttribute("data-selectable",""),r.setAttribute("data-index",String(e))),n.appendChild(r)}e.replaceChildren(n)}const objectKeyCache=new WeakMap;let generatedObjectKeyId=0;function isObjectRecord(e){return null!==e&&("object"==typeof e||"function"==typeof e)}function readField(e,t){if(t&&isObjectRecord(e))return e[t]}function toSelectKey(e){return"string"==typeof e||"number"==typeof e?e:"boolean"==typeof e||"bigint"==typeof e||"symbol"==typeof e?String(e):null}function objectIdentityKey(e){const t=objectKeyCache.get(e);if(t)return t;generatedObjectKeyId+=1;const i=`__smilodon-object-${generatedObjectKeyId}`;return objectKeyCache.set(e,i),i}function indexFallbackKey(e,t){const i=globalThis.process?.env?.NODE_ENV;if("production"!==i){const e="[Smilodon Phase2] Using index as key is unstable under filtering/sorting. Provide getKey/valueField for stable selection.";t?t(e):console.warn(e)}return`__smilodon-index-${e}`}function createDefaultItemAdapter(e={}){return{getKey(t,i){if(e.getKey)return e.getKey(t,i);if(isObjectRecord(t)){const n=toSelectKey(t.id)??toSelectKey(t.key)??toSelectKey(t.value)??toSelectKey(readField(t,e.valueField));if(null!==n)return n;if(e.getValue){const n=toSelectKey(e.getValue(t,i));if(null!==n)return n}return"index"===e.keyFallback?indexFallbackKey(i,e.onIndexFallback):objectIdentityKey(t)}return String(t)},getValue(t,i){if(e.getValue)return e.getValue(t,i);const n=readField(t,e.valueField);return void 0!==n?n:isObjectRecord(t)&&void 0!==t.value?t.value:t},getLabel(t,i){if(e.getLabel)return e.getLabel(t,i);const n=readField(t,e.labelField);return void 0!==n?String(n):isObjectRecord(t)&&void 0!==t.label?String(t.label):isObjectRecord(t)&&void 0!==t.text?String(t.text):String(t)},isDisabled:(t,i)=>e.isDisabled?e.isDisabled(t,i):Boolean(isObjectRecord(t)&&t.disabled),getGroupKey:(t,i)=>e.getGroupKey?e.getGroupKey(t,i):isObjectRecord(t)&&void 0!==t.group?null==t.group?null:String(t.group):null}}function getDefaultDuplicateKeyPolicy(){const e=globalThis.process?.env?.NODE_ENV;return"production"===e?"warn":"throw"}function createItemRegistry(e,t,i={}){const n=i.duplicateKeyPolicy??getDefaultDuplicateKeyPolicy(),o=[],s=new Map,r=new Map,a=new Map,l=new Map,c=[];return e.forEach((e,d)=>{const h=t.getKey(e,d),u=l.get(h),p={key:h,item:e,index:d,label:t.getLabel(e,d),value:t.getValue(e,d),disabled:!0===t.isDisabled?.(e,d),groupKey:t.getGroupKey?.(e,d)??null};if(o.push(p),r.set(d,h),void 0!==u){const e={key:h,firstIndex:u,duplicateIndex:d};if(c.push(e),"throw"===n)throw new Error(duplicateKeyMessage(e));if("warn"===n)return void(i.onDuplicateKey?i.onDuplicateKey(e):console.warn(duplicateKeyMessage(e)));if("first-wins"===n)return}else l.set(h,d);s.set(h,p),a.set(h,d)}),{records:o,keyToRecord:s,indexToKey:r,keyToIndex:a,duplicateKeys:c}}function duplicateKeyMessage(e){return`[Smilodon Phase2] Duplicate item key "${String(e.key)}" at indexes ${e.firstIndex} and ${e.duplicateIndex}. Provide stable unique keys for selection.`}function applySelectionRequest(e,t,i){let n;switch(t.type){case"select":n=selectKey(e,t.key,i);break;case"deselect":n=deselectKey(e,t.key,i);break;case"toggle":n=e.has(t.key)?i.multiple||i.allowDeselect?deselectKey(e,t.key,i):e:selectKey(e,t.key,i);break;case"clear":n=i.required&&e.size>0?e:new Set;break;case"replace":n=replaceKeys(e,t.keys,i)}return n.size===e.size&&[...n].every(t=>e.has(t))?e:n}function selectKey(e,t,i){if(i.disabledKeys.has(t))return e;if(!i.multiple)return new Set([t]);if(e.has(t))return e;const n=i.maxSelections??0;return n>0&&e.size>=n?e:new Set([...e,t])}function deselectKey(e,t,i){if(!e.has(t)||i.disabledKeys.has(t))return e;if(i.required&&e.size<=1)return e;const n=new Set(e);return n.delete(t),n}function replaceKeys(e,t,i){const n=normalizeKeys(t,i);return i.required&&0===n.size&&e.size>0?normalizeKeys(e,i):n}function normalizeKeys(e,t){const i=new Set,n=t.maxSelections??0;for(const o of e)if(!t.disabledKeys.has(o)&&!i.has(o)&&(i.add(o),!t.multiple||n>0&&i.size>=n))break;return i}function transition(e,t){switch(t.type){case"CONNECT":return{state:{...e,lifecycle:"connected"},effects:[]};case"DISCONNECT":{const t="open"===e.popup?[{type:"POPUP_CLOSED",reason:"disconnect"},{type:"SYNC_ARIA"}]:[];return{state:{...e,lifecycle:"disconnected",popup:"closed",focused:!1},effects:t}}case"OPEN_REQUEST":return"connected"!==e.lifecycle||e.disabled||"open"===e.popup?{state:enforceInvariants(e),effects:[]}:{state:{...e,popup:"open"},effects:[{type:"POPUP_OPENED"},{type:"FOCUS_TRIGGER"},{type:"SYNC_ARIA"}]};case"CLOSE_REQUEST":return"closed"===e.popup?{state:e,effects:[]}:{state:{...e,popup:"closed"},effects:[{type:"POPUP_CLOSED",reason:t.reason},{type:"SYNC_ARIA"}]};case"TOGGLE_REQUEST":return transition(e,"open"===e.popup?{type:"CLOSE_REQUEST",reason:"programmatic"}:{type:"OPEN_REQUEST"});case"FOCUS_GAINED":return e.focused?{state:e,effects:[]}:{state:{...e,focused:!0},effects:[{type:"SYNC_ARIA"}]};case"FOCUS_LOST":return e.focused?{state:{...e,focused:!1},effects:[{type:"SYNC_ARIA"}]}:{state:e,effects:[]};case"DISABLED_CHANGED":{if(e.disabled===t.disabled)return{state:enforceInvariants(e),effects:[]};const i=enforceInvariants({...e,disabled:t.disabled}),n=[];return t.disabled&&"open"===e.popup&&n.push({type:"POPUP_CLOSED",reason:"disabled"}),n.push({type:"SYNC_ARIA"}),{state:i,effects:n}}case"ITEMS_REGISTERED":{const i=new Set(t.keys),n=new Set(t.disabledKeys??[]),o={...e.selection,disabledKeys:n},s=resolveActiveKey(e.activeKey,i,n),r=applySelectionRequest(e.selectedKeys,{type:"replace",keys:Array.from(e.selectedKeys)},o),a={...e,activeKey:s,selectedKeys:r,registeredKeys:i,selection:o},l=[];return keysEqual(s,e.activeKey)||l.push({type:"ACTIVE_KEY_CHANGED",activeKey:s,reason:"programmatic"}),setsEqual(r,e.selectedKeys)||l.push({type:"SELECTION_CHANGED",selectedKeys:Array.from(r),reason:"programmatic"}),l.length>0&&l.push({type:"SYNC_ARIA"}),{state:a,effects:l}}case"SELECTION_CONFIG_CHANGED":{const i={...e.selection,multiple:t.multiple??e.selection.multiple,required:t.required??e.selection.required,allowDeselect:t.allowDeselect??e.selection.allowDeselect,maxSelections:t.maxSelections??e.selection.maxSelections,disabledKeys:t.disabledKeys?new Set(t.disabledKeys):e.selection.disabledKeys},n=applySelectionRequest(e.selectedKeys,{type:"replace",keys:Array.from(e.selectedKeys)},i),o=resolveActiveKey(e.activeKey,e.registeredKeys,i.disabledKeys),s={...e,selection:i,selectedKeys:n,activeKey:o},r=[];return keysEqual(o,e.activeKey)||r.push({type:"ACTIVE_KEY_CHANGED",activeKey:o,reason:"programmatic"}),setsEqual(n,e.selectedKeys)||r.push({type:"SELECTION_CHANGED",selectedKeys:Array.from(n),reason:"programmatic"}),r.length>0&&r.push({type:"SYNC_ARIA"}),{state:s,effects:r}}case"ACTIVE_KEY_CHANGED":return null===t.key||e.registeredKeys.has(t.key)&&!e.selection.disabledKeys.has(t.key)?keysEqual(e.activeKey,t.key)?{state:e,effects:[]}:{state:{...e,activeKey:t.key},effects:[{type:"ACTIVE_KEY_CHANGED",activeKey:t.key,reason:t.reason},{type:"SYNC_ARIA"}]}:{state:e,effects:[]};case"SELECT_KEY_REQUEST":case"DESELECT_KEY_REQUEST":case"TOGGLE_KEY_REQUEST":case"CLEAR_SELECTION_REQUEST":case"REPLACE_SELECTION_REQUEST":{const i=applySelectionRequest(e.selectedKeys,selectionRequestFromEvent(t),e.selection);return setsEqual(i,e.selectedKeys)?{state:e,effects:[]}:{state:{...e,selectedKeys:i},effects:[{type:"SELECTION_CHANGED",selectedKeys:Array.from(i),reason:t.reason},{type:"SYNC_ARIA"}]}}default:return{state:e,effects:[]}}}function selectionRequestFromEvent(e){switch(e.type){case"SELECT_KEY_REQUEST":return{type:"select",key:e.key,reason:e.reason};case"DESELECT_KEY_REQUEST":return{type:"deselect",key:e.key,reason:e.reason};case"TOGGLE_KEY_REQUEST":return{type:"toggle",key:e.key,reason:e.reason};case"CLEAR_SELECTION_REQUEST":return{type:"clear",reason:e.reason};case"REPLACE_SELECTION_REQUEST":return{type:"replace",keys:e.keys,reason:e.reason}}}function enforceInvariants(e){return"disconnected"===e.lifecycle||e.disabled?"closed"===e.popup?e:{...e,popup:"closed"}:e}function resolveActiveKey(e,t,i){return null!==e&&t.has(e)&&!i.has(e)?e:null}function setsEqual(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function keysEqual(e,t){return e===t||Object.is(e,t)}function createInitialSelectState(){return{lifecycle:"disconnected",popup:"closed",disabled:!1,focused:!1,query:"",activeKey:null,selectedKeys:new Set,registeredKeys:new Set,selection:{multiple:!1,required:!1,allowDeselect:!1,disabledKeys:new Set,maxSelections:0},dataStatus:"idle"}}function isOpen(e){return"open"===e.popup}function isDisabled(e){return e.disabled}function isFocused(e){return e.focused}function hasSelection(e){return e.selectedKeys.size>0}function isSelected(e,t){return e.selectedKeys.has(t)}function getSelectedKeys(e){return Array.from(e.selectedKeys)}function getActiveKey(e){return e.activeKey}function isRegisteredKey(e,t){return e.registeredKeys.has(t)}class SelectEngineBridge{constructor(e=createInitialSelectState()){this._state=e}get state(){return this._state}dispatch(e){const t=transition(this._state,e);return this._state=t.state,t.effects}}class DefaultSelectEffectRunner{run(e,t){for(const i of e)switch(i.type){case"FOCUS_TRIGGER":t.focusTrigger?.();break;case"SYNC_ARIA":t.syncAria?.();break;case"POPUP_OPENED":t.onPopupOpened?.();break;case"POPUP_CLOSED":t.onPopupClosed?.(i.reason)}}}class FenwickTree{constructor(e){this.size=e,this.tree=new Float64Array(e+1)}add(e,t){let i=e+1;for(;i<=this.size;)this.tree[i]+=t,i+=i&-i}sum(e){if(e<0)return 0;let t=e+1,i=0;for(;t>0;)i+=this.tree[t],t-=t&-t;return i}rangeSum(e,t){return e>t?0:this.sum(t)-(e>0?this.sum(e-1):0)}update(e,t,i){this.add(e,i-t)}lowerBound(e){if(e<=0)return 0;let t=0,i=0,n=1<<Math.floor(Math.log2(this.size));for(;n>0;){if(t+n<=this.size){const o=i+this.tree[t+n];o<e&&(t+=n,i=o)}n>>=1}return t}reset(){this.tree.fill(0)}resize(e){if(e===this.size)return;const t=this.tree,i=this.size;this.size=e,this.tree=new Float64Array(e+1);const n=Math.min(i,e);for(let e=1;e<=n;e++)this.tree[e]=t[e]}getSize(){return this.size}exportState(){return{size:this.size,tree:Array.from(this.tree)}}static fromState(e){const t=new FenwickTree(e.size);return t.tree=new Float64Array(e.tree),t}}class DOMPool{constructor(e){this.pool=[],this.hits=0,this.misses=0,this.evictions=0,this.factory=e.factory,this.reset=e.reset||this.defaultReset.bind(this),this.maxSize=e.maxSize||64,this.telemetry=e.telemetry||!1}acquire(){const e=performance.now();for(let t=0;t<this.pool.length;t++){const i=this.pool[t];if(!i.inUse)return i.inUse=!0,i.lastUsed=e,this.reset(i.node),this.telemetry&&this.hits++,i.node}const t=this.factory();return this.pool.push({node:t,lastUsed:e,inUse:!0}),this.telemetry&&this.misses++,this.pool.length>this.maxSize&&this.evictLRU(),t}release(e){const t=this.pool.find(t=>t.node===e);if(t){if(t.inUse=!1,t.lastUsed=performance.now(),this.pool.length>this.maxSize)return void this.removePoolNode(t);this.reset(t.node)}}evictLRU(){let e=-1,t=1/0;for(let i=0;i<this.pool.length;i++){const n=this.pool[i];!n.inUse&&n.lastUsed<t&&(e=i,t=n.lastUsed)}return e>=0&&(this.removePoolNode(this.pool[e]),this.telemetry&&this.evictions++,!0)}removePoolNode(e){const t=this.pool.indexOf(e);if(t<0)return;const[i]=this.pool.splice(t,1);this.deepCleanup(i.node)}defaultReset(e){e.textContent="",e.removeAttribute("style");const t=Array.from(e.attributes);for(const i of t)i.name.startsWith("data-")&&"data-index"!==i.name&&"data-selectable"!==i.name&&e.removeAttribute(i.name);["aria-selected","aria-checked","aria-disabled"].forEach(t=>e.removeAttribute(t))}deepCleanup(e){const t=e.cloneNode(!0);e.parentNode?.replaceChild(t,e),e.textContent=""}clear(){for(const e of this.pool)this.deepCleanup(e.node);this.pool=[],this.resetTelemetry()}setMaxSize(e){for(this.maxSize=e;this.pool.length>this.maxSize&&this.evictLRU(););}getStats(){const e=this.pool.filter(e=>!e.inUse).length,t=this.hits+this.misses>0?this.hits/(this.hits+this.misses):0;return{total:this.pool.length,available:e,inUse:this.pool.length-e,maxSize:this.maxSize,hits:this.hits,misses:this.misses,evictions:this.evictions,hitRate:t}}resetTelemetry(){this.hits=0,this.misses=0,this.evictions=0}}class Virtualizer{constructor(e,t,i,n){this.measuredHeights=new Map,this.measuredHeightTotal=0,this.activeNodes=new Map,this.destroyed=!1,this.recycleRafId=0,this.intendedScrollTop=0,this.currentWindow=null,this.container=e,this.itemsLength=t,this.itemGetter=i,this.options=n,this.estimatedItemHeight=n.estimatedItemHeight,this.averageHeight=n.estimatedItemHeight;const o=Math.ceil(1.5*(2*n.buffer+10))+(n.maxPoolExtra??32);this.pool=new DOMPool({maxSize:o,factory:()=>{const e=document.createElement("div");return e.setAttribute("data-selectable",""),e},reset:e=>{e.textContent="",e.removeAttribute("style"),e.removeAttribute("aria-selected"),e.removeAttribute("aria-checked")},telemetry:n.enableTelemetry||!1}),this.fenwick=this.createFenwickTree(t),this.container.style.willChange="transform"}computeWindow(e,t){const{buffer:i}=this.options,n=this.indexAtOffset(e),o=n-i,s=this.itemsLength>0?Math.max(0,Math.min(this.itemsLength-1,o)):0,r=Math.max(0,e+t);let a=this.indexAtOffset(r);t>0&&a>n&&this.cumulativeOffset(a)===r&&(a-=1);const l=Math.max(n,a)+i,c=this.itemsLength>0?Math.max(0,Math.min(this.itemsLength-1,l)):-1,d=Math.max(0,c-s+1),h=d+(this.options.maxPoolExtra??32);return this.pool.setMaxSize(h),{startIndex:s,endIndex:c,windowSize:d}}updateWindow(e,t){if(this.destroyed)return null;const i=Number.isFinite(e)?Math.max(0,e):0,n=Number.isFinite(t)&&t>=0?t:0,o=this.computeWindow(i,n),s=null===this.currentWindow||this.currentWindow.startIndex!==o.startIndex||this.currentWindow.endIndex!==o.endIndex||this.currentWindow.windowSize!==o.windowSize;return this.currentWindow={...o},{window:{...o},changed:s,scrollTop:i,viewportHeight:n}}getCurrentWindow(){return this.currentWindow?{...this.currentWindow}:null}indexAtOffset(e){if(this.itemsLength<=0)return 0;const t=Math.max(0,e);let i=Math.max(0,Math.min(this.itemsLength-1,this.fenwick.lowerBound(t)));for(;i<this.itemsLength-1&&this.cumulativeOffset(i+1)<=t;)i+=1;return i}cumulativeOffset(e){if(!Number.isFinite(e))return e===Number.POSITIVE_INFINITY&&this.itemsLength>0?this.fenwick.sum(this.itemsLength-1):0;const t=Math.max(0,Math.min(this.itemsLength,Math.trunc(e)));return 0===t?0:this.fenwick.sum(t-1)}scrollToIndex(e){if(this.destroyed||this.itemsLength<=0)return null;const t=Number.isFinite(e)?Math.trunc(e):0,i=Math.max(0,Math.min(this.itemsLength-1,t)),n=this.cumulativeOffset(i);return this.intendedScrollTop=n,{index:i,offset:n,scrollTop:n}}scrollToKey(e,t){if(this.destroyed||this.itemsLength<=0)return null;const i=t(e);return"number"!=typeof i||!Number.isInteger(i)||i<0||i>=this.itemsLength?null:this.scrollToIndex(i)}getIntendedScrollTop(){return this.intendedScrollTop}acquireNode(e){const t=this.activeNodes.get(e);if(t)return t;const i=this.pool.acquire();return i.setAttribute("data-index",String(e)),this.activeNodes.set(e,i),i}releaseNode(e){const t=this.activeNodes.get(e);t&&(this.pool.release(t),this.activeNodes.delete(e))}releaseExcess(e){for(const[t,i]of this.activeNodes)e.has(t)||(this.pool.release(i),this.activeNodes.delete(t))}render(e,t,i){if(this.destroyed)return;const n=document.createDocumentFragment(),o=new Set;for(let s=e;s<=t;s++){const e=this.acquireNode(s);i(e,this.itemGetter(s),s),n.appendChild(e),o.add(s),queueMicrotask(()=>{this.destroyed||this.measureOnAppear(e,s)})}const s=this.cumulativeOffset(e);this.container.style.transform=`translate3d(0, ${Math.round(100*s)/100}px, 0)`,this.container.replaceChildren(n),this.recycleRafId&&cancelAnimationFrame(this.recycleRafId),this.recycleRafId=requestAnimationFrame(()=>{this.recycleRafId=0,this.destroyed||this.releaseExcess(o)})}measureOnAppear(e,t){this.measureItem(t,e.offsetHeight)}measureItem(e,t){if(this.destroyed||!Number.isInteger(e)||e<0||e>=this.itemsLength||!Number.isFinite(t)||t<=0)return!1;const i=this.measuredHeights.get(e),n=this.options.measurementThreshold??5;if(void 0===i||Math.abs(i-t)>n){const n=i??this.estimatedItemHeight;return this.measuredHeights.set(e,t),this.measuredHeightTotal+=t-(i??0),this.fenwick.update(e,n,t),this.updateAverageHeight(),!0}return!1}getPoolStats(){return this.pool.getStats()}setItemsLength(e){const t=this.itemsLength;this.itemsLength=e,e!==t&&(this.currentWindow=null);let i=!1;for(const[t,n]of this.measuredHeights)t>=e&&(this.measuredHeightTotal-=n,this.measuredHeights.delete(t),i=!0);i&&this.updateAverageHeight();for(const t of Array.from(this.activeNodes.keys()))t>=e&&this.releaseNode(t);e!==t&&(this.fenwick=this.createFenwickTree(e))}destroy(){this.destroyed=!0,this.recycleRafId&&(cancelAnimationFrame(this.recycleRafId),this.recycleRafId=0),this.pool.clear(),this.activeNodes.clear(),this.measuredHeights.clear(),this.measuredHeightTotal=0,this.averageHeight=this.estimatedItemHeight,this.currentWindow=null,this.fenwick.reset()}updateAverageHeight(){const e=this.measuredHeights.size;this.averageHeight=e>0?Math.round(this.measuredHeightTotal/e*100)/100:this.estimatedItemHeight}createFenwickTree(e){const t=new FenwickTree(e);for(let i=0;i<e;i++)t.add(i,this.estimatedItemHeight);for(const[i,n]of this.measuredHeights)i<e&&t.update(i,this.estimatedItemHeight,n);return t}}class CustomOptionPool{constructor(e=50){this._pool=new Map,this._activeComponents=new Map,this._maxPoolSize=e}acquire(e,t,i,n,o){this.release(i);const s=this._findAvailableComponent(e);let r;if(s)r=s.instance;else try{r=e(t,i)}catch(e){throw console.error("[CustomOptionPool] Failed to create component:",e),e}try{r.mountOption(o,n),s?(s.inUse=!0,s.lastUsedIndex=i):this._addToPool(e,r,i),this._activeComponents.set(i,r)}catch(e){s&&(s.inUse=!1);try{r.unmountOption()}catch{}throw console.error(`[CustomOptionPool] Failed to mount component at index ${i}:`,e),e}return r}release(e){const t=this._activeComponents.get(e);if(t){try{t.unmountOption()}catch(t){console.error(`[CustomOptionPool] Failed to unmount component at index ${e}:`,t)}this._activeComponents.delete(e);for(const e of this._pool.values()){const i=e.find(e=>e.instance===t);if(i){i.inUse=!1;break}}}}releaseAll(){Array.from(this._activeComponents.keys()).forEach(e=>this.release(e))}updateSelection(e,t){const i=this._activeComponents.get(e);i&&i.updateSelected(t)}updateFocused(e,t){const i=this._activeComponents.get(e);i&&i.updateFocused&&i.updateFocused(t)}getComponent(e){return this._activeComponents.get(e)}clear(){this.releaseAll(),this._pool.clear()}getStats(){let e=0,t=0;for(const i of this._pool.values())e+=i.length,t+=i.filter(e=>!e.inUse).length;return{totalPooled:e,activeComponents:this._activeComponents.size,availableComponents:t}}_findAvailableComponent(e){const t=this._pool.get(e);if(t)return t.find(e=>!e.inUse)}_addToPool(e,t,i){for(;this._getTotalPooled()>=this._maxPoolSize;)if(!this._evictAvailableComponent())return;const n=this._pool.get(e)||[];n.push({instance:t,inUse:!0,lastUsedIndex:i}),this._pool.set(e,n)}_evictAvailableComponent(){for(const[e,t]of this._pool.entries()){const i=t.findIndex(e=>!e.inUse);if(!(i<0))return t.splice(i,1),0===t.length&&this._pool.delete(e),!0}return!1}_getTotalPooled(){let e=0;for(const t of this._pool.values())e+=t.length;return e}}class OptionRenderer{constructor(e){this._mountedElements=new Map,this._config=e,this._pool=new CustomOptionPool(e.maxPoolSize)}render(e,t,i,n,o){const s=e,r=this._config.getValue(e),a=this._config.getLabel(e),l=!!this._config.getDisabled&&this._config.getDisabled(e);this.unmount(t);return s.optionComponent&&"function"==typeof s.optionComponent?this._renderCustomComponent(e,t,r,a,i,n,l,o,s.optionComponent):this._renderLightweightOption(e,t,r,a,i,n,l,o)}updateSelection(e,t){const i=this._mountedElements.get(e);if(!i)return;const n=this._pool.getComponent(e);n?n.updateSelected(t):t?(i.classList.add("selected"),i.setAttribute("aria-selected","true")):(i.classList.remove("selected"),i.setAttribute("aria-selected","false"))}updateFocused(e,t){const i=this._mountedElements.get(e);if(!i)return;const n=this._pool.getComponent(e);n?(n.updateFocused&&n.updateFocused(t),i.classList.toggle("focused",t)):i.classList.toggle("focused",t)}unmount(e){this._pool.release(e),this._mountedElements.delete(e)}unmountAll(){this._pool.releaseAll(),this._mountedElements.clear()}getStats(){return this._pool.getStats()}_renderLightweightOption(e,t,i,n,o,s,r,a){const l=document.createElement("div");return l.className="option",o&&l.classList.add("selected"),s&&l.classList.add("focused"),r&&l.classList.add("disabled"),l.id=`${a}-option-${t}`,l.textContent=n,l.dataset.value=String(i),l.dataset.index=String(t),l.dataset.mode="lightweight",l.setAttribute("role","option"),l.setAttribute("aria-selected",String(o)),r&&l.setAttribute("aria-disabled","true"),r||l.addEventListener("click",()=>{this._config.onSelect(t)}),this._mountedElements.set(t,l),l}_renderCustomComponent(e,t,i,n,o,s,r,a,l){const c=document.createElement("div");c.className="option option-custom",o&&c.classList.add("selected"),s&&c.classList.add("focused"),r&&c.classList.add("disabled"),c.id=`${a}-option-${t}`,c.dataset.value=String(i),c.dataset.index=String(t),c.dataset.mode="component",c.setAttribute("role","option"),c.setAttribute("aria-selected",String(o)),c.setAttribute("aria-label",n),r&&c.setAttribute("aria-disabled","true");const d={item:e,index:t,value:i,label:n,isSelected:o,isFocused:s,isDisabled:r,onSelect:e=>{r||this._config.onSelect(e)},onCustomEvent:(e,i)=>{this._config.onCustomEvent&&this._config.onCustomEvent(t,e,i)}};try{this._pool.acquire(l,e,t,d,c).getElement();r||c.addEventListener("click",e=>{c.contains(e.target)&&this._config.onSelect(t)})}catch(e){console.error(`[OptionRenderer] Failed to render custom component at index ${t}:`,e),c.innerHTML="",c.textContent=n,c.classList.add("component-error"),this._config.onError&&this._config.onError(t,e)}return this._mountedElements.set(t,c),c}}class NativeSelectElement extends HTMLElement{static get observedAttributes(){return["placement","strategy","portal"]}constructor(){super(),this._options={},this._items=[],this._selectedSet=new Set,this._selectedItems=new Map,this._activeIndex=-1,this._multi=!1,this._typeBuffer="",this._shadow=this.attachShadow({mode:"open"}),this._listRoot=document.createElement("div"),this._listRoot.setAttribute("role","listbox"),this._listRoot.setAttribute("tabindex","0"),this._shadow.appendChild(this._listRoot),this._liveRegion=document.createElement("div"),this._liveRegion.setAttribute("role","status"),this._liveRegion.setAttribute("aria-live","polite"),this._liveRegion.style.cssText="position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden;",this._shadow.appendChild(this._liveRegion),this._helpers=createRendererHelpers((e,t)=>this._onSelect(e,t)),this._listRoot.addEventListener("click",e=>{const t=e.target.closest("[data-selectable]");if(!t)return;const i=Number(t.dataset.index),n=this._items[i];this._onSelect(n,i)}),this._listRoot.addEventListener("keydown",e=>this._onKeydown(e))}connectedCallback(){this._listRoot.setAttribute("role","listbox"),this._listRoot.setAttribute("aria-label","Options list"),this._multi&&this._listRoot.setAttribute("aria-multiselectable","true"),this._initializeOptionRenderer(),this._emit("open",{})}disconnectedCallback(){this._emit("close",{}),this._unifiedRenderer&&this._unifiedRenderer.unmountAll(),this._virtualizer?.destroy(),this._virtualizer=void 0,this._typeTimeout&&window.clearTimeout(this._typeTimeout),this._announceTimeout&&window.clearTimeout(this._announceTimeout)}_initializeOptionRenderer(){this._unifiedRenderer?.unmountAll();const e={enableRecycling:!0,maxPoolSize:100,getValue:e=>e?.value??e,getLabel:e=>e?.label??String(e),getDisabled:e=>e?.disabled??!1,onSelect:e=>{const t=this._items[e];this._onSelect(t,e)},onCustomEvent:(e,t,i)=>{this.dispatchEvent(new CustomEvent("option:custom-event",{detail:{index:e,eventName:t,data:i},bubbles:!0,composed:!0}))},onError:(e,t)=>{console.error(`[NativeSelect] Error in option ${e}:`,t),this.dispatchEvent(new CustomEvent("option:mount-error",{detail:{index:e,error:t},bubbles:!0,composed:!0}))}};this._unifiedRenderer=new OptionRenderer(e)}attributeChangedCallback(e,t,i){switch(e){case"placement":this._options.placement=i??void 0;break;case"strategy":this._options.strategy=i??void 0;break;case"portal":this._options.portal="true"===i||"false"!==i&&void 0}}set items(e){this._items=e??[],this._virtualizer?.destroy(),this._virtualizer=new Virtualizer(this._listRoot,this._items.length,e=>this._items[e],{estimatedItemHeight:48,buffer:5}),this.render()}get items(){return this._items}set multi(e){this._multi=e,e?this._listRoot.setAttribute("aria-multiselectable","true"):this._listRoot.removeAttribute("aria-multiselectable")}get multi(){return this._multi}get selectedIndices(){return Array.from(this._selectedSet)}get selectedItems(){return Array.from(this._selectedItems.values())}set optionTemplate(e){this._options.optionTemplate=e,this.render()}set optionRenderer(e){this._options.optionRenderer=e,this.render()}setItems(e){this.items=e??[]}setValue(e){if(null==e||""===e)return this._selectedSet.clear(),this._selectedItems.clear(),this._activeIndex=-1,void this.render();const t=this._items.findIndex(t=>"object"==typeof t&&null!==t&&"value"in t?t.value===e:t===e);if(t>=0){const e=this._items[t];this._multi||(this._selectedSet.clear(),this._selectedItems.clear()),this._selectedSet.add(t),this._selectedItems.set(t,e),this._activeIndex=t,this.render()}}getValue(){const e=[];for(const t of this._selectedItems.values())"object"==typeof t&&null!==t&&"value"in t?e.push(t.value):e.push(t);return this._multi?e:e[0]??null}render(){const{optionTemplate:e,optionRenderer:t}=this._options,i=this.getBoundingClientRect().height||300,n=this.scrollTop||0;this._activeIndex>=0?this._listRoot.setAttribute("aria-activedescendant",`option-${this._activeIndex}`):this._listRoot.removeAttribute("aria-activedescendant");if(this._items.some(e=>"object"==typeof e&&null!==e&&Object.prototype.hasOwnProperty.call(e,"optionComponent")&&"function"==typeof e.optionComponent)&&this._unifiedRenderer){this._listRoot.replaceChildren();const e=document.createDocumentFragment();for(let t=0;t<this._items.length;t++){const i=this._items[t],n=this._selectedSet.has(t),o=this._activeIndex===t,s=this._unifiedRenderer.render(i,t,n,o,`native-${this.getAttribute("id")||"default"}`);e.appendChild(s)}return void this._listRoot.appendChild(e)}if(this._virtualizer){const{startIndex:o,endIndex:s}=this._virtualizer.computeWindow(n,i);return void this._virtualizer.render(o,s,(i,n,o)=>{if(this._applyOptionAttrs(i,o),t){const e=t(n,o,this._helpers);i.replaceChildren(e)}else if(e){const t=document.createElement("div");t.innerHTML=e(n,o);const s=t.firstElementChild;i.replaceChildren(s??document.createTextNode(String(n)))}else{const e=String("object"==typeof n&&null!==n&&"label"in n?n.label:n);i.textContent=e}})}const o=document.createDocumentFragment();for(let i=0;i<this._items.length;i++){const n=this._items[i];if(t){const e=t(n,i,this._helpers);e.hasAttribute("data-selectable")||(e.setAttribute("data-selectable",""),e.setAttribute("data-index",String(i))),this._applyOptionAttrs(e,i),o.appendChild(e)}else{if(e)return renderTemplate(this._listRoot,this._items,e),void this._applyAriaToAll();{const e=document.createElement("div"),t=String("object"==typeof n&&null!==n&&"label"in n?n.label:n);e.textContent=t,e.setAttribute("data-selectable",""),e.setAttribute("data-index",String(i)),this._applyOptionAttrs(e,i),o.appendChild(e)}}}this._listRoot.replaceChildren(o)}_applyOptionAttrs(e,t){e.setAttribute("role","option"),e.id=`option-${t}`,this._selectedSet.has(t)?e.setAttribute("aria-selected","true"):e.setAttribute("aria-selected","false")}_applyAriaToAll(){const e=Array.from(this._listRoot.children);for(const t of e){const e=Number(t.dataset.index);Number.isFinite(e)&&this._applyOptionAttrs(t,e)}}_emit(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0}))}_onSelect(e,t){this._multi?this._selectedSet.has(t)?(this._selectedSet.delete(t),this._selectedItems.delete(t)):(this._selectedSet.add(t),this._selectedItems.set(t,e)):(this._selectedSet.clear(),this._selectedItems.clear(),this._selectedSet.add(t),this._selectedItems.set(t,e)),this._activeIndex=t,this.render();const i=this._selectedSet.has(t),n=e?.value??e,o=e?.label??String(e);this._emit("select",{item:e,index:t,value:n,label:o,selected:i,multi:this._multi});const s=[],r=[];for(const e of this._selectedItems.values())s.push(e),r.push(e?.value??e);this._emit("change",{selectedItems:s,selectedValues:r,selectedIndices:Array.from(this._selectedSet)}),this._announce(`Selected ${o}`)}_onKeydown(e){switch(e.key){case"ArrowDown":e.preventDefault(),this._moveActive(1);break;case"ArrowUp":e.preventDefault(),this._moveActive(-1);break;case"Home":e.preventDefault(),this._setActive(0);break;case"End":e.preventDefault(),this._setActive(this._items.length-1);break;case"PageDown":e.preventDefault(),this._moveActive(10);break;case"PageUp":e.preventDefault(),this._moveActive(-10);break;case"Enter":case" ":if(e.preventDefault(),this._activeIndex>=0){const e=this._items[this._activeIndex];this._onSelect(e,this._activeIndex)}break;case"Escape":e.preventDefault(),this._emit("close",{});break;default:1!==e.key.length||e.ctrlKey||e.altKey||e.metaKey||this._onType(e.key)}}_moveActive(e){const t=Math.max(0,Math.min(this._items.length-1,this._activeIndex+e));this._setActive(t)}_setActive(e){this._activeIndex=e,this.render(),this._scrollToActive(),this._announce(`Navigated to ${String(this._items[e])}`)}_scrollToActive(){const e=this._shadow.getElementById(`option-${this._activeIndex}`);e?.scrollIntoView({block:"nearest",inline:"nearest"})}_onType(e){this._typeTimeout&&window.clearTimeout(this._typeTimeout),this._typeBuffer+=e.toLowerCase(),this._typeTimeout=window.setTimeout(()=>{this._typeBuffer=""},400);const t=this._items.findIndex(e=>String(e).toLowerCase().startsWith(this._typeBuffer));t>=0&&this._setActive(t)}_announce(e){this._liveRegion&&(this._liveRegion.textContent=e,this._announceTimeout&&window.clearTimeout(this._announceTimeout),this._announceTimeout=window.setTimeout(()=>{this._announceTimeout=void 0,this._liveRegion&&(this._liveRegion.textContent="")},1e3))}focus(){this._listRoot.focus()}}customElements.get("smilodon-select")||customElements.define("smilodon-select",NativeSelectElement);const defaultConfig={selection:{mode:"single",allowDeselect:!1,disabledOptionBehavior:{selectable:!1,hoverable:!1,focusable:!1},maxSelections:0,showRemoveButton:!0,showSelectedIndicator:!0,removeButtonIcon:"×",closeOnSelect:!0,toggleOnTriggerClick:!0},direction:"ltr",dropdownPlacement:{mode:"bottom"},multiSelectDisplay:{mode:"wrap",maxHeight:"160px",overflowX:"hidden",overflowY:"auto",dragScroll:!0},scrollToSelected:{enabled:!0,multiSelectTarget:"first",behavior:"smooth",block:"nearest"},loadMore:{enabled:!1,itemsPerLoad:3,threshold:100,showLoader:!0},busyBucket:{enabled:!0,showSpinner:!0,message:"Loading...",minDisplayTime:200},styles:{classNames:{}},serverSide:{enabled:!1,getValueFromItem:e=>e?.value??e,getLabelFromItem:e=>e?.label??String(e)},infiniteScroll:{enabled:!1,pageSize:20,initialPage:1,cachePages:!0,maxCachedPages:10,preloadAdjacent:!0,scrollRestoration:"auto"},expandable:{enabled:!1,collapsedHeight:"300px",expandedHeight:"500px",expandLabel:"Show more",collapseLabel:"Show less"},clearControl:{enabled:!1,clearSelection:!0,clearSearch:!0,hideWhenEmpty:!0,ariaLabel:"Clear selection and search",icon:"×"},callbacks:{},tracking:{enabled:!1,events:!0,styling:!0,limitations:!0,emitDiagnostics:!1,maxEntries:200},limitations:{policies:{},autoMitigateRuntimeModeSwitch:!0},enabled:!0,searchable:!1,placeholder:"Select an option...",virtualize:!0,estimatedItemHeight:48};class SelectConfigManager{constructor(){this.config=this.deepClone(defaultConfig)}getConfig(){return this.config}updateConfig(e){this.config=this.deepMerge(this.config,e)}resetConfig(){this.config=this.deepClone(defaultConfig)}mergeWithComponentConfig(e){return this.deepMerge(this.deepClone(this.config),e)}deepClone(e){return JSON.parse(JSON.stringify(e))}deepMerge(e,t){const i={...e},n=Object.keys(t);for(let e=0;e<n.length;e++){const o=n[e];if(Object.prototype.hasOwnProperty.call(t,o)){const e=t[o],n=i[o];e&&"object"==typeof e&&!Array.isArray(e)?i[o]=this.deepMerge(n&&"object"==typeof n?n:{},e):i[o]=e}}return i}}const selectConfig=new SelectConfigManager;function configureSelect(e){selectConfig.updateConfig(e)}function resetSelectConfig(){selectConfig.resetConfig()}const DEFAULT_CONFIG={protocol:"legacy",searchMode:"local",paginationMode:"page",firstPage:1},ALLOWED_FIELDS=new Set(["protocol","searchMode","paginationMode","firstPage","fetchLimit"]);function issue(e,t,i){return{path:e,code:t,message:i}}function isRecord$1(e){if(null===e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function validatePositiveSafeInteger(e,t,i){const n=e[t];void 0!==n&&("number"==typeof n?(!Number.isSafeInteger(n)||n<=0)&&i.push(issue(t,"invalid-positive-integer",`${t} must be a positive safe integer.`)):i.push(issue(t,"invalid-type",`${t} must be a number.`)))}function validateDataLoadingConfig(e){if(!isRecord$1(e))return{valid:!1,issues:[issue("dataLoading","invalid-type","dataLoading must be a plain object.")]};const t=[];for(const i of Object.keys(e).filter(e=>!ALLOWED_FIELDS.has(e)).sort())t.push(issue(i,"unknown-field",`Unknown dataLoading field: ${i}.`));const i=e.protocol,n=void 0===i?DEFAULT_CONFIG.protocol:i;"string"!=typeof n?t.push(issue("protocol","invalid-type","protocol must be a string.")):"legacy"!==n&&"acknowledged"!==n&&t.push(issue("protocol","invalid-value","protocol must be legacy or acknowledged."));const o=e.searchMode,s=void 0===o?DEFAULT_CONFIG.searchMode:o;"string"!=typeof s?t.push(issue("searchMode","invalid-type","searchMode must be a string.")):"local"!==s&&"remote"!==s&&"hybrid"!==s&&t.push(issue("searchMode","invalid-value","searchMode must be local, remote, or hybrid."));const r=e.paginationMode,a=void 0===r?DEFAULT_CONFIG.paginationMode:r;if("string"!=typeof a?t.push(issue("paginationMode","invalid-type","paginationMode must be a string.")):"page"!==a&&"cursor"!==a&&t.push(issue("paginationMode","invalid-value","paginationMode must be page or cursor.")),validatePositiveSafeInteger(e,"firstPage",t),validatePositiveSafeInteger(e,"fetchLimit",t),"legacy"!==n||"remote"!==s&&"hybrid"!==s||t.push(issue("searchMode","requires-acknowledged-protocol","Remote and hybrid search require the acknowledged protocol.")),"legacy"===n&&"cursor"===a&&t.push(issue("paginationMode","requires-acknowledged-protocol","Cursor pagination requires the acknowledged protocol.")),t.length>0)return{valid:!1,issues:t};return{valid:!0,value:{protocol:n,searchMode:s,paginationMode:a,firstPage:void 0===e.firstPage?DEFAULT_CONFIG.firstPage:e.firstPage,...void 0===e.fetchLimit?{}:{fetchLimit:e.fetchLimit}}}}function computeWindowKeys(e,t,i){const n=Math.max(0,Math.min(e.length,Math.trunc(t))),o=Math.max(n,Math.min(e.length,Math.trunc(i)));return e.slice(n,o)}function deriveAccessibilityState(e,t={}){const i=e.selection.required,n=t.invalid??!1;return{expanded:"open"===e.popup,disabled:e.disabled,readonly:t.readonly??!1,searchable:t.searchable??!1,multiple:e.selection.multiple,required:i,invalid:n,busy:"loading"===e.dataStatus,activeKey:e.activeKey,selectedKeys:e.selectedKeys,disabledKeys:e.selection.disabledKeys,popupRole:"listbox",label:t.label??{},validation:{required:i,invalid:n,errorMessage:t.errorMessage??null,errorDescriptionId:t.errorDescriptionId??null}}}function uniqueIds(e){return[...new Set(e.filter(e=>Boolean(e)))]}function getLabelledBy(e){return uniqueIds([e.labelId,...e.labelledBy??[]])}function getDescribedBy(e){return uniqueIds([...e.label.describedBy??[],e.validation.errorDescriptionId])}function computeComboboxAccessibility(e,t=null){return{role:"combobox",expanded:e.expanded,disabled:e.disabled,readonly:e.readonly,autocomplete:e.searchable?"list":"none",multiple:e.multiple,required:e.required,invalid:e.invalid,activeKey:e.activeKey,controlsId:t,labelledBy:getLabelledBy(e.label),describedBy:getDescribedBy(e),ariaLabel:e.label.ariaLabel??null,ariaDescription:e.label.ariaDescription??null}}function computeListboxAccessibility(e){return{role:e.popupRole,multiple:e.multiple,busy:e.busy,labelledBy:getLabelledBy(e.label),ariaLabel:e.label.ariaLabel??null}}function computeOptionAccessibility(e,t){const i=e.disabled||e.disabledKeys.has(t);return{key:t,selected:e.selectedKeys.has(t),disabled:i,active:!i&&e.activeKey===t}}function computeAccessibilityEffects(e,t){return[{type:"SYNC_COMBOBOX_ARIA",...computeComboboxAccessibility(e,t.controlsId??null)},{type:"SYNC_LISTBOX_ARIA",...computeListboxAccessibility(e)},...t.optionKeys.map(t=>({type:"SYNC_OPTION_ARIA",...computeOptionAccessibility(e,t)})),...(t.announcements??[]).map(e=>({type:"ANNOUNCE",...e})),...(t.focusIntents??[]).map(e=>({type:"FOCUS_INTENT",...e}))]}function setBooleanAttribute(e,t,i){e.setAttribute(t,String(i))}function setOptionalAttribute(e,t,i){i?e.setAttribute(t,i):e.removeAttribute(t)}function setIdListAttribute(e,t,i){setOptionalAttribute(e,t,i.length>0?i.join(" "):null)}function applyCombobox(e,t){const i=t.combobox;if(!i)return;i.setAttribute("role",e.role),setBooleanAttribute(i,"aria-expanded",e.expanded),setBooleanAttribute(i,"aria-disabled",e.disabled),setBooleanAttribute(i,"aria-readonly",e.readonly),setBooleanAttribute(i,"aria-required",e.required),setBooleanAttribute(i,"aria-invalid",e.invalid),i.setAttribute("aria-autocomplete",e.autocomplete),setOptionalAttribute(i,"aria-controls",e.controlsId),setIdListAttribute(i,"aria-labelledby",e.labelledBy),setIdListAttribute(i,"aria-describedby",e.describedBy),setOptionalAttribute(i,"aria-label",e.ariaLabel),setOptionalAttribute(i,"aria-description",e.ariaDescription);const n=null==e.activeKey?null:t.getOptionByKey?.(e.activeKey)??null;setOptionalAttribute(i,"aria-activedescendant",n?.id||null)}function applyListbox(e,t){const i=t.listbox;i&&(i.setAttribute("role",e.role),e.multiple?i.setAttribute("aria-multiselectable","true"):i.removeAttribute("aria-multiselectable"),e.busy?i.setAttribute("aria-busy","true"):i.removeAttribute("aria-busy"),setIdListAttribute(i,"aria-labelledby",e.labelledBy),setOptionalAttribute(i,"aria-label",e.ariaLabel))}function applyOption(e,t){const i=t.getOptionByKey?.(e.key);i&&(i.setAttribute("role","option"),setBooleanAttribute(i,"aria-selected",e.selected),e.disabled?i.setAttribute("aria-disabled","true"):i.removeAttribute("aria-disabled"))}function applyFocusIntent(e,t,i){if(!i.applyFocus||"none"===e)return;const n="input"===e?t.focusTargets?.input:"clear-button"===e?t.focusTargets?.clearButton:t.focusTargets?.getActiveOption?.();n?.focus()}function applyAccessibilityEffects(e,t,i={}){for(const n of e)switch(n.type){case"SYNC_COMBOBOX_ARIA":applyCombobox(n,t);break;case"SYNC_LISTBOX_ARIA":applyListbox(n,t);break;case"SYNC_OPTION_ARIA":applyOption(n,t);break;case"ANNOUNCE":t.liveRegion&&(t.liveRegion.setAttribute("aria-live",n.politeness),t.liveRegion.setAttribute("aria-atomic","true"),t.liveRegion.textContent=n.message);break;case"FOCUS_INTENT":applyFocusIntent(n.target,t,i)}}class SelectOption extends HTMLElement{constructor(e){super(),this._hasRendered=!1,this._config=e,this._shadow=this.attachShadow({mode:"open"}),this._container=document.createElement("div"),this._container.className="option-container",this._initializeStyles(),this._attachEventListeners(),this._shadow.appendChild(this._container)}connectedCallback(){this._ensureRendered()}_ensureRendered(){this._hasRendered||(this._render(),this._hasRendered=!0)}ensureRendered(){this._ensureRendered()}_initializeStyles(){const e=document.createElement("style");e.textContent='\n :host {\n display: block;\n position: relative;\n font: inherit;\n color: var(--select-option-color, var(--select-text-color, #1f2937));\n background: var(--select-option-bg, var(--select-dropdown-bg, var(--select-bg, white)));\n border: var(--select-option-border, none);\n border-bottom: var(--select-option-border-bottom, none);\n border-radius: var(--select-option-border-radius, var(--select-radius-sm, 6px));\n box-shadow: var(--select-option-shadow, none);\n transform: var(--select-option-transform, none);\n transition: var(--select-option-transition, background-color 0.2s ease);\n }\n\n :host(:hover:not(.smilodon-option--disabled):not([aria-disabled="true"])),\n :host(.smilodon-option--disabled-hoverable:hover) {\n background: var(--select-option-hover-bg, #f0f0f0);\n color: var(--select-option-hover-color, var(--select-option-color, var(--select-text-color, #1f2937)));\n outline: var(--select-option-hover-border, none);\n outline-offset: -1px;\n box-shadow: var(--select-option-hover-shadow, var(--select-option-shadow, none));\n }\n\n /* Keep the visual surface on the host so external utility classes applied\n through classMap can override selected/active/disabled styles in both\n light and dark themes. */\n :host([aria-selected="true"]),\n :host(.smilodon-option--selected) {\n background: var(--select-option-selected-bg, #e3f2fd);\n color: var(--select-option-selected-color, #1976d2);\n border: var(--select-option-selected-border, var(--select-option-border, none));\n border-bottom: var(--select-option-selected-border-bottom, var(--select-option-border-bottom, none));\n border-radius: var(--select-option-selected-border-radius, var(--select-option-border-radius, 0));\n box-shadow: var(--select-option-selected-shadow, var(--select-option-shadow, none));\n transform: var(--select-option-selected-transform, var(--select-option-transform, none));\n }\n\n :host([aria-selected="true"]:hover),\n :host(.smilodon-option--selected:hover) {\n background: var(--select-option-selected-hover-bg, var(--select-option-selected-bg, #e3f2fd));\n color: var(--select-option-selected-hover-color, var(--select-option-selected-color, #1976d2));\n outline: var(--select-option-selected-hover-border, var(--select-option-hover-border, none));\n outline-offset: -1px;\n box-shadow: var(--select-option-selected-hover-shadow, var(--select-option-selected-shadow, var(--select-option-shadow, none)));\n }\n\n :host(.smilodon-option--active):not(.smilodon-option--disabled):not([aria-disabled="true"]),\n :host(.smilodon-option--active.smilodon-option--disabled-focusable) {\n background: var(--select-option-active-bg, var(--select-option-hover-bg, #f0f0f0));\n color: var(--select-option-active-color, var(--select-option-hover-color, var(--select-option-color, var(--select-text-color, #1f2937))));\n border: var(--select-option-active-border, var(--select-option-hover-border, var(--select-option-border, none)));\n box-shadow: var(--select-option-active-shadow, var(--select-option-shadow, none));\n transform: var(--select-option-active-transform, var(--select-option-transform, none));\n outline: var(--select-option-active-outline, none);\n outline-offset: var(--select-option-active-outline-offset, -2px);\n }\n\n :host(.smilodon-option--disabled),\n :host([aria-disabled="true"]) {\n background: var(--select-option-disabled-bg, var(--select-option-bg, var(--select-dropdown-bg, var(--select-bg, white))));\n color: var(--select-option-disabled-color, var(--select-option-color, var(--select-text-color, #1f2937)));\n border: var(--select-option-disabled-border, var(--select-option-border, none));\n border-bottom: var(--select-option-disabled-border-bottom, var(--select-option-border-bottom, none));\n opacity: var(--select-option-disabled-opacity, 0.5);\n cursor: var(--select-option-disabled-cursor, not-allowed);\n pointer-events: none;\n }\n\n :host(.smilodon-option--disabled-interactive) {\n pointer-events: auto;\n }\n \n .option-container {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: var(--select-option-padding, 10px 14px);\n cursor: pointer;\n user-select: none;\n color: inherit;\n background: inherit;\n transition: inherit;\n border: inherit;\n border-bottom: inherit;\n border-radius: inherit;\n box-shadow: inherit;\n transform: inherit;\n font: inherit;\n }\n \n .option-container:hover {\n background: inherit;\n color: inherit;\n border: inherit;\n border-bottom: inherit;\n box-shadow: inherit;\n transform: inherit;\n }\n \n .option-container.selected {\n background: inherit;\n color: inherit;\n border: inherit;\n border-bottom: inherit;\n border-radius: inherit;\n box-shadow: inherit;\n transform: inherit;\n }\n\n .option-container.selected:hover {\n background: inherit;\n color: inherit;\n border: inherit;\n border-bottom: inherit;\n box-shadow: inherit;\n transform: inherit;\n }\n \n .option-container.active:not(.disabled) {\n background: inherit;\n color: inherit;\n border: inherit;\n box-shadow: inherit;\n transform: inherit;\n outline: none;\n outline-offset: 0;\n }\n \n .option-container.disabled {\n background: inherit;\n color: inherit;\n border: inherit;\n border-bottom: inherit;\n opacity: inherit;\n cursor: inherit;\n pointer-events: none;\n }\n \n .option-content {\n flex: 1;\n overflow: var(--select-option-content-overflow, hidden);\n text-overflow: var(--select-option-content-text-overflow, ellipsis);\n white-space: var(--select-option-content-white-space, nowrap);\n }\n\n .checkmark-icon {\n display: none;\n margin-left: var(--select-checkmark-margin-left, 8px);\n color: var(--select-checkmark-color, currentColor);\n }\n\n :host([dir="rtl"]) .checkmark-icon,\n :host-context([dir="rtl"]) .checkmark-icon {\n margin-left: 0;\n margin-right: var(--select-checkmark-margin-left, 8px);\n }\n\n :host([aria-selected="true"]) .checkmark-icon,\n .option-container.selected .checkmark-icon {\n display: inline-flex;\n }\n \n .remove-button {\n margin-left: 8px;\n width: var(--select-badge-remove-size, 18px);\n height: var(--select-badge-remove-size, 18px);\n min-width: var(--select-badge-remove-min-width, var(--select-badge-remove-size, 18px));\n min-height: var(--select-badge-remove-min-height, var(--select-badge-remove-size, 18px));\n padding: 0;\n border: none;\n background-color: var(--select-badge-remove-bg, rgba(255, 255, 255, 0.2));\n color: var(--select-badge-remove-color, currentColor);\n cursor: pointer;\n border-radius: var(--select-badge-remove-radius, 50%);\n font-size: var(--select-badge-remove-font-size, 0.7333em);\n font-weight: var(--select-badge-remove-font-weight, 600);\n line-height: 1;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n transition: all 0.2s ease;\n }\n\n :host([dir="rtl"]) .remove-button,\n :host-context([dir="rtl"]) .remove-button {\n margin-left: 0;\n margin-right: 8px;\n }\n\n .remove-button-icon {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: var(--select-badge-remove-icon-size, 10px);\n height: var(--select-badge-remove-icon-size, 10px);\n color: var(--select-badge-remove-icon-color, currentColor);\n font-size: var(--select-badge-remove-icon-font-size, inherit);\n line-height: var(--select-badge-remove-icon-line-height, 1);\n transform: var(--select-badge-remove-icon-transform, none);\n opacity: var(--select-badge-remove-icon-opacity, 1);\n pointer-events: none;\n }\n\n .remove-button-icon svg {\n width: 100%;\n height: 100%;\n display: block;\n }\n \n .remove-button:hover {\n background-color: var(--select-badge-remove-hover-bg, #ffebee);\n color: var(--select-badge-remove-hover-color, #c62828);\n }\n \n .remove-button:focus {\n outline: 2px solid var(--select-remove-btn-focus-outline, #1976d2);\n outline-offset: 2px;\n }\n ',this._shadow.appendChild(e)}_getDisabledBehavior(){const e=this._config.disabledBehavior??{};return{selectable:!0===e.selectable,hoverable:!0===e.hoverable,focusable:!0===e.focusable}}_isDisabledSelectionBlocked(){return Boolean(this._config.disabled)&&!this._getDisabledBehavior().selectable}_render(){const{item:e,index:t,selected:i,disabled:n,active:o,render:s,showRemoveButton:r,classMap:a}=this._config,l=this._getDisabledBehavior();this._container.innerHTML="",this._container.setAttribute("part","option"),this._container.classList.add("smilodon-option");const c=(a?.selected??"selected sm-selected").split(" ").filter(Boolean),d=(a?.active??"active sm-active").split(" ").filter(Boolean),h=(a?.disabled??"disabled sm-disabled").split(" ").filter(Boolean),u=(e,t,i)=>{i?e.classList.add(...t):e.classList.remove(...t)};i?(u(this._container,[...c,"smilodon-option--selected"],!0),u(this,[...c,"smilodon-option--selected"],!0)):(u(this._container,[...c,"smilodon-option--selected"],!1),u(this,[...c,"smilodon-option--selected"],!1)),!o||n&&!l.focusable?(u(this._container,[...d,"smilodon-option--active"],!1),u(this,[...d,"smilodon-option--active"],!1)):(u(this._container,[...d,"smilodon-option--active"],!0),u(this,[...d,"smilodon-option--active"],!0)),n?(u(this._container,[...h,"smilodon-option--disabled"],!0),u(this,[...h,"smilodon-option--disabled"],!0)):(u(this._container,[...h,"smilodon-option--disabled"],!1),u(this,[...h,"smilodon-option--disabled"],!1));const p=(e,t)=>{u(this._container,[e],t),u(this,[e],t)};if(p("smilodon-option--disabled-interactive",Boolean(n&&(l.hoverable||l.selectable))),p("smilodon-option--disabled-hoverable",Boolean(n&&l.hoverable)),p("smilodon-option--disabled-focusable",Boolean(n&&l.focusable)),p("smilodon-option--disabled-selectable",Boolean(n&&l.selectable)),this._config.className){const e=this._config.className.split(" ").filter(Boolean);this._container.classList.add(...e)}this._config.style&&Object.assign(this._container.style,this._config.style);const g=document.createElement("div");if(g.className="option-content",s){const i=s(e,t);"string"==typeof i?g.innerHTML=i:i instanceof HTMLElement&&g.appendChild(i)}else{const e=this._getLabel();g.textContent=e}if(this._container.appendChild(g),r&&i){this._removeButton=document.createElement("button"),this._removeButton.className="remove-button",this._removeButton.setAttribute("part","chip-remove"),this._removeButton.setAttribute("aria-label","Remove option"),this._removeButton.setAttribute("type","button");const e=document.createElement("span");e.className="remove-button-icon",e.setAttribute("part","chip-remove-icon");const t=this._config.removeButtonIcon&&this._config.removeButtonIcon.trim()?this._config.removeButtonIcon:"×";t.trim().startsWith("<")?e.innerHTML=t:e.textContent=t,this._removeButton.appendChild(e),this._container.appendChild(this._removeButton)}if(this.setAttribute("role","option"),this.setAttribute("aria-selected",String(i)),n&&!l.selectable?this.setAttribute("aria-disabled","true"):this.removeAttribute("aria-disabled"),this.id=this._config.id||`select-option-${t}`,!r){const e=document.createElement("div");e.setAttribute("part","checkmark"),e.className="checkmark-icon",e.innerHTML='\n <svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" style="width:1em;height:1em;">\n <path d="M4 8.5L6.5 11L12 5.5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n ',this._container.appendChild(e)}const m=[];i&&m.push("selected"),!o||n&&!l.focusable||m.push("active"),m.length?this.dataset.smState=m.join(" "):delete this.dataset.smState,this.dataset.smIndex=String(t),this.hasAttribute("data-sm-selectable")||this.toggleAttribute("data-sm-selectable",!0)}_attachEventListeners(){this._container.addEventListener("click",e=>{e.target!==this._removeButton&&(this._isDisabledSelectionBlocked()||this._handleSelect())}),this._removeButton&&this._removeButton.addEventListener("click",e=>{e.stopPropagation(),this._handleRemove()}),this.addEventListener("keydown",e=>{this._isDisabledSelectionBlocked()||("Enter"===e.key||" "===e.key?(e.preventDefault(),this._handleSelect()):"Delete"!==e.key&&"Backspace"!==e.key||this._config.selected&&this._config.showRemoveButton&&(e.preventDefault(),this._handleRemove()))})}_handleSelect(){const e={item:this._config.item,index:this._config.index,value:this._getValue(),label:this._getLabel(),selected:!this._config.selected};this.dispatchEvent(new CustomEvent("optionSelect",{detail:e,bubbles:!0,composed:!0}))}_handleRemove(){const e={item:this._config.item,index:this._config.index,value:this._getValue(),label:this._getLabel(),selected:!1};this.dispatchEvent(new CustomEvent("optionRemove",{detail:e,bubbles:!0,composed:!0}))}_getValue(){return this._config.getValue?this._config.getValue(this._config.item):this._config.item?.value??this._config.item}_getLabel(){return this._config.getLabel?this._config.getLabel(this._config.item):this._config.item?.label??String(this._config.item)}updateConfig(e){this._config={...this._config,...e},this._render(),this._attachEventListeners()}getConfig(){return this._config}getValue(){return this._getValue()}getLabel(){return this._getLabel()}setSelected(e){this._config.selected=e,this._hasRendered&&this._render()}setActive(e){this._config.active=e&&(!this._config.disabled||this._getDisabledBehavior().focusable),this._hasRendered&&this._render()}setDisabled(e){this._config.disabled=e,this._hasRendered&&this._render()}}function valuesEqual(e,t){return!!Object.is(e,t)||null!=e&&null!=t&&("string"==typeof e&&"number"==typeof t?e===String(t):"number"==typeof e&&"string"==typeof t&&String(e)===t)}function arrayIncludesValue(e,t){for(let i=0;i<e.length;i+=1)if(valuesEqual(e[i],t))return!0;return!1}function arraysEqualByValue(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i+=1)if(!valuesEqual(e[i],t[i]))return!1;return!0}customElements.get("select-option")||customElements.define("select-option",SelectOption);const DEFAULT_MAX_CURSOR_PAGES=256,HARD_MAX_CURSOR_PAGES=4096,DEFAULT_MAX_CURSOR_TOKEN_BYTES=1024,HARD_MAX_CURSOR_TOKEN_BYTES=4096;let coordinatorInstanceSequence=0;function isRecord(e){if(null===e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function isPositiveSafeInteger(e){return Number.isSafeInteger(e)&&e>0}function isNonNegativeSafeInteger(e){return Number.isSafeInteger(e)&&e>=0}function isCursor(e){return"string"==typeof e||"number"==typeof e&&Number.isFinite(e)}function cursorTokenByteLength(e){const t=String(e);let i=0;for(const e of t){const t=e.codePointAt(0);i+=t<=127?1:t<=2047?2:t<=65535?3:4}return i}function parseRequestId(e){const t=/^data-(\d+)-generation-(\d+)-request-(\d+)-([a-z0-9]+)$/.exec(e);if(!t)return null;const[,i,n,o,s]=t,r=Number(i),a=Number(n),l=Number(o);return!Number.isSafeInteger(r)||r<1||!Number.isSafeInteger(a)||a<0||!Number.isSafeInteger(l)||l<1?null:Object.freeze({instanceId:r,queryGeneration:a,sequence:l,check:s})}function requestIdCheck(e,t,i,n){let o=14695981039346656037n;const s=(1n<<64n)-1n,r=`${e}:${t}:${i}:${n}`;for(let e=0;e<r.length;e+=1)o^=BigInt(r.charCodeAt(e)),o=1099511628211n*o&s;return o.toString(36)}function isQueryMode(e){return"local"===e||"remote"===e||"hybrid"===e}function isPaginationMode(e){return"page"===e||"cursor"===e}function frozenPosition(e){return Object.freeze({...e})}function exactKeys(e,t){return Object.keys(e).every(e=>t.includes(e))}function asFrozenItems(e){return Object.freeze(Array.from(e))}function immutableActions(e){return Object.freeze(e.slice())}function configInput(e={}){const t=isRecord(e)?e:{},i=isRecord(t.dataLoading)?t.dataLoading:{},n=isRecord(t.infiniteScroll)?t.infiniteScroll:{};return{protocol:void 0===i.protocol?"legacy":i.protocol,searchMode:void 0===i.searchMode?"local":i.searchMode,paginationMode:void 0===i.paginationMode?"page":i.paginationMode,firstPage:void 0===i.firstPage?1:i.firstPage,initialPage:void 0===n.initialPage?1:n.initialPage,fetchLimit:i.fetchLimit,maxCursorPages:void 0===i.maxCursorPages?DEFAULT_MAX_CURSOR_PAGES:i.maxCursorPages,maxCursorTokenBytes:void 0===i.maxCursorTokenBytes?DEFAULT_MAX_CURSOR_TOKEN_BYTES:i.maxCursorTokenBytes,pageSize:n.pageSize}}function validateDataCoordinatorConfig(e={}){const t=configInput(e),i=[],n=(e,t)=>i.push(Object.freeze({field:e,message:t})),o=e;isRecord(o)?(void 0===o.dataLoading||isRecord(o.dataLoading)||n("dataLoading","must be a plain object when supplied"),void 0===o.infiniteScroll||isRecord(o.infiniteScroll)||n("infiniteScroll","must be a plain object when supplied")):n("config","must be a plain object"),"legacy"!==t.protocol&&"acknowledged"!==t.protocol&&n("dataLoading.protocol","must be legacy or acknowledged"),isQueryMode(t.searchMode)||n("dataLoading.searchMode","must be local, remote, or hybrid"),isPaginationMode(t.paginationMode)||n("dataLoading.paginationMode","must be page or cursor"),isPositiveSafeInteger(t.firstPage)||n("dataLoading.firstPage","must be a positive safe integer"),isPositiveSafeInteger(t.initialPage)||n("infiniteScroll.initialPage","must be a positive safe integer"),"acknowledged"===t.protocol&&"local"===t.searchMode&&"page"===t.paginationMode&&t.initialPage===Number.MAX_SAFE_INTEGER&&n("infiniteScroll.initialPage","must leave room for the next acknowledged page number"),void 0===t.fetchLimit||isPositiveSafeInteger(t.fetchLimit)||n("dataLoading.fetchLimit","must be a positive safe integer when supplied"),(!isPositiveSafeInteger(t.maxCursorPages)||t.maxCursorPages>HARD_MAX_CURSOR_PAGES)&&n("dataLoading.maxCursorPages",`must be a positive safe integer no greater than ${HARD_MAX_CURSOR_PAGES}`),(!isPositiveSafeInteger(t.maxCursorTokenBytes)||t.maxCursorTokenBytes>HARD_MAX_CURSOR_TOKEN_BYTES)&&n("dataLoading.maxCursorTokenBytes",`must be a positive safe integer no greater than ${HARD_MAX_CURSOR_TOKEN_BYTES}`),void 0===t.pageSize||isPositiveSafeInteger(t.pageSize)||n("infiniteScroll.pageSize","must be a positive safe integer when supplied"),"legacy"!==t.protocol||"remote"!==t.searchMode&&"hybrid"!==t.searchMode&&"cursor"!==t.paginationMode||n("dataLoading.protocol","remote/hybrid search and cursor pagination require acknowledged protocol");const s="number"==typeof t.fetchLimit?t.fetchLimit:"number"==typeof t.pageSize?t.pageSize:void 0;return"acknowledged"===t.protocol&&void 0===s&&n("dataLoading.fetchLimit","acknowledged requests require fetchLimit or an effective infiniteScroll.pageSize"),i.length>0?Object.freeze({valid:!1,errors:Object.freeze(i)}):Object.freeze({valid:!0,value:Object.freeze({protocol:t.protocol,searchMode:t.searchMode,paginationMode:t.paginationMode,firstPage:t.firstPage,initialPage:t.initialPage,fetchLimit:s,maxCursorPages:t.maxCursorPages,maxCursorTokenBytes:t.maxCursorTokenBytes})})}function copyCoordinatorConfig(e={}){return{dataLoading:e.dataLoading?{...e.dataLoading}:{},infiniteScroll:e.infiniteScroll?{...e.infiniteScroll}:{}}}function mergeCoordinatorConfig(e,t){return{dataLoading:{...e.dataLoading??{},...t.dataLoading??{}},infiniteScroll:{...e.infiniteScroll??{},...t.infiniteScroll??{}}}}class DataRequestCoordinator{constructor(e={}){this.instanceId=++coordinatorInstanceSequence,this.requestIdSecret=Math.random().toString(36).slice(2)||"0",this.requestSequence=0,this.connected=!1,this.hasConnected=!1,this.queryGeneration=0,this.active=null,this.status="idle",this.committedCursors=new Set,this.generationHasAcceptedResult=!1,this.retryAvailable=!1,this.error=null,this.resourceLimit=null,this.sentinelBlocked=!1,this.sentinelIntersecting=!1;const t=void 0===e.config?{}:e.config,i=validateDataCoordinatorConfig(t);if(!i.valid)throw new TypeError(i.errors.map(({field:e,message:t})=>`${e}: ${t}`).join("; "));this.rawConfig=copyCoordinatorConfig(t),this.config=i.value,this.query=e.initialQuery??"",this.items=asFrozenItems(e.initialItems??[]);const n=this.isRemoteMode();this.hasMore=!n&&(e.hasMore??!1),this.nextEligiblePosition=this.initialPosition(),this.lastCommittedPage="page"!==this.config.paginationMode||n?void 0:this.config.initialPage,this.needsInitialRemoteSearch=n}getSnapshot(){const e=this.active?.request??null,t=frozenPosition(this.nextEligiblePosition);return Object.freeze({status:this.status,connected:this.connected,busy:null!==this.active,query:this.query,normalizedQuery:this.query.trim(),queryGeneration:this.queryGeneration,items:asFrozenItems(this.items),hasMore:this.hasMore,activeRequest:e,lastCommittedPage:this.lastCommittedPage,nextEligiblePosition:t,error:this.error?Object.freeze({...this.error}):null,resourceLimit:this.resourceLimit,sentinelBlocked:this.sentinelBlocked,sentinelIntersecting:this.sentinelIntersecting})}connect(e=this.query){if(this.connected)return immutableActions([]);const t=[];if(e!==this.query&&t.push(...this.setQuery(e)),this.hasConnected&&(this.queryGeneration+=1),this.connected=!0,this.hasConnected=!0,this.isRemoteMode()&&this.needsInitialRemoteSearch){this.resetPaginationForRemoteQuery(!0);const e=this.createSearchRequest();e&&t.push(Object.freeze({type:"request",request:e}))}return immutableActions(t)}markNotificationsDispatched(e){return!(!this.active||this.active.request.requestId!==e||"requested"!==this.active.phase)&&(this.active.phase="loading",this.status="loading",!0)}setQuery(e){if("string"!=typeof e||e===this.query)return immutableActions([]);const t=[],i=this.invalidateActive("query-changed");if(i&&t.push(i),this.query=e,this.queryGeneration+=1,this.error=null,this.status="idle",this.generationHasAcceptedResult=!1,this.retryAvailable=!1,this.retryPosition=void 0,this.retryKind=void 0,this.committedCursors.clear(),this.resourceLimit=null,this.sentinelBlocked=!1,this.isRemoteMode()){if(this.resetPaginationForRemoteQuery(!0),this.needsInitialRemoteSearch=!0,this.connected){const e=this.createSearchRequest();e&&t.push(Object.freeze({type:"request",request:e}))}}else this.lastCommittedPage="page"===this.config.paginationMode?this.config.initialPage:void 0,this.nextEligiblePosition=this.initialPosition(),this.needsInitialRemoteSearch=!1;return immutableActions(t)}updateConfig(e){const t=e;if(!isRecord(t)||void 0!==t.dataLoading&&!isRecord(t.dataLoading)||void 0!==t.infiniteScroll&&!isRecord(t.infiniteScroll))return Object.freeze({status:"invalid",errors:Object.freeze([Object.freeze({field:"config",message:"update and nested config groups must be plain objects"})])});const i=mergeCoordinatorConfig(this.rawConfig,e),n=validateDataCoordinatorConfig(i);if(!n.valid)return Object.freeze({status:"invalid",errors:n.errors});const o=this.config,s=n.value,r=o.protocol!==s.protocol||o.searchMode!==s.searchMode||o.paginationMode!==s.paginationMode;if(this.rawConfig=copyCoordinatorConfig(i),this.config=s,!r)return this.refreshCursorDepthLimit(),Object.freeze({status:"accepted",actions:immutableActions([])});const a=[],l=this.invalidateActive("config-changed");if(l&&a.push(l),this.queryGeneration+=1,this.error=null,this.status="idle",this.generationHasAcceptedResult=!1,this.retryAvailable=!1,this.retryPosition=void 0,this.retryKind=void 0,this.committedCursors.clear(),this.resourceLimit=null,this.sentinelBlocked=!1,this.hasMore=!this.isRemoteMode()&&this.hasMore,this.lastCommittedPage="page"!==this.config.paginationMode||this.isRemoteMode()?void 0:this.config.initialPage,this.nextEligiblePosition=this.initialPosition(),this.needsInitialRemoteSearch=this.isRemoteMode(),this.connected&&this.isRemoteMode()){const e=this.createSearchRequest();e&&a.push(Object.freeze({type:"request",request:e}))}return Object.freeze({status:"accepted",actions:immutableActions(a)})}requestLoadMore(e="manual"){if("acknowledged"!==this.config.protocol||!this.connected||this.active)return immutableActions([]);if("sentinel"===e&&this.sentinelBlocked)return immutableActions([]);if(!this.hasMore&&!this.retryAvailable)return immutableActions([]);const t=this.retryAvailable&&this.retryPosition?this.retryPosition:this.nextEligiblePosition;if("cursor"===this.config.paginationMode&&"cursor"===t.mode&&t.ordinal>this.config.maxCursorPages)return this.resourceLimit=Object.freeze({reason:"cursor-depth",maxCursorPages:this.config.maxCursorPages}),this.status="resource-limited",this.sentinelBlocked=!0,immutableActions([]);"manual"===e&&(this.sentinelBlocked=!1);const i=this.retryAvailable?this.retryKind:void 0;this.retryAvailable=!1,this.retryPosition=void 0,this.retryKind=void 0;const n="search"===i&&this.isRemoteMode()?this.createSearchRequest(t):this.createLoadMoreRequest(t);return immutableActions(n?[Object.freeze({type:"request",request:n})]:[])}setSentinelIntersecting(e){return e?this.sentinelIntersecting?immutableActions([]):(this.sentinelIntersecting=!0,this.requestLoadMore("sentinel")):(this.sentinelIntersecting=!1,this.sentinelBlocked=!1,immutableActions([]))}disconnect(){if(!this.connected)return immutableActions([]);const e=this.active?.request,t=[];if(e){"search"!==e.kind||this.generationHasAcceptedResult||(this.needsInitialRemoteSearch=!0);const i=this.invalidateActive("disconnected");i&&t.push(i),this.resourceLimit=null,this.status="cancelled",this.sentinelBlocked=!0,this.queryGeneration+=1}return this.sentinelIntersecting=!1,this.connected=!1,immutableActions(t)}completeDataRequest(e){if(!isRecord(e)||!this.hasValidCompletionEnvelope(e))return"invalid";const t=e.requestId,i=e.queryGeneration;if(this.active?.request.requestId!==t)return this.classifyInactiveRequest(t,i);if(i!==this.active.request.queryGeneration||"loading"!==this.active.phase)return"invalid";const n=this.validateCompletionPayload(e,this.active.request);if(!n.valid){if("cursor-token-size"===n.resourceLimit){const i=cursorTokenByteLength(e.nextCursor);return this.resourceLimit=Object.freeze({reason:"cursor-token-size",maxCursorTokenBytes:this.config.maxCursorTokenBytes,actualCursorTokenBytes:i,requestId:t}),"resource-limit"}return"invalid"}const o=this.active.request,s=e.status,r="succeeded"===s||"exhausted"===s?asFrozenItems(e.items):this.items;let a,l,c,d=this.nextEligiblePosition,h=this.lastCommittedPage,u=this.hasMore,p=!1,g=null,m=!1,f=null;if("succeeded"===s){const t=this.advanceFrom(o,e);d=t.position,h=t.lastCommittedPage,c=t.cursorToCommit,u=!0}else if("exhausted"===s)h="page"===o.position.mode?o.position.page:this.lastCommittedPage,u=!1;else if("empty"===s)if(u=!0,m=!0,"next"===e.advance){const t=this.advanceFrom(o,e);d=t.position,h=t.lastCommittedPage,c=t.cursorToCommit}else p=!0,a=o.position,l=o.kind;else"failed"===s?(p=!0,a=o.position,l=o.kind,g=Object.freeze({...e.error}),m=!0):"cancelled"===s&&(p=!0,a=o.position,l=o.kind,m=!0);return"cursor"===this.config.paginationMode&&u&&"cursor"===d.mode&&d.ordinal>this.config.maxCursorPages&&(f=Object.freeze({reason:"cursor-depth",maxCursorPages:this.config.maxCursorPages,requestId:t}),m=!0),this.items=r,this.nextEligiblePosition=d,this.lastCommittedPage=h,this.hasMore=u,this.retryAvailable=p,this.retryPosition=a,this.retryKind=l,this.error=g,this.resourceLimit=f,this.sentinelBlocked=m,void 0!==c&&this.committedCursors.add(c),"succeeded"!==s&&"exhausted"!==s||(this.generationHasAcceptedResult=!0),this.active=null,this.status=f?"resource-limited":s,"accepted"}isRemoteMode(){return"remote"===this.config.searchMode||"hybrid"===this.config.searchMode}initialPosition(){if("cursor"===this.config.paginationMode)return Object.freeze({mode:"cursor",ordinal:1});const e=this.isRemoteMode()?this.config.firstPage:this.config.initialPage+1;return Object.freeze({mode:"page",page:e})}resetPaginationForRemoteQuery(e){this.hasMore=!1,this.lastCommittedPage=void 0,this.nextEligiblePosition=this.initialPosition(),this.committedCursors.clear(),this.retryAvailable=!1,this.retryPosition=void 0,this.retryKind=void 0,this.resourceLimit=null,this.sentinelBlocked=!1,this.error=null,e&&(this.items=asFrozenItems([]))}refreshCursorDepthLimit(){if("acknowledged"!==this.config.protocol||"cursor"!==this.config.paginationMode)return;const e=this.retryAvailable&&this.retryPosition?this.retryPosition:this.nextEligiblePosition;if((this.hasMore||this.retryAvailable)&&"cursor"===e.mode&&e.ordinal>this.config.maxCursorPages)return this.resourceLimit=Object.freeze({reason:"cursor-depth",maxCursorPages:this.config.maxCursorPages}),this.active||(this.status="resource-limited"),void(this.sentinelBlocked=!0);"cursor-depth"===this.resourceLimit?.reason&&(this.resourceLimit=null,this.active||"resource-limited"!==this.status||(this.status="idle"))}createSearchRequest(e=this.nextEligiblePosition){if(!this.connected||!this.isRemoteMode()||"acknowledged"!==this.config.protocol)return null;const t=this.createRequest({kind:"search",mode:this.config.searchMode},e);return t&&(this.needsInitialRemoteSearch=!1,this.status="requested"),t}createLoadMoreRequest(e){if(!this.connected||"acknowledged"!==this.config.protocol)return null;const t=this.createRequest({kind:"loadMore"},e);return t&&(this.status="requested"),t}createRequest(e,t){const i=this.config.fetchLimit;if(void 0===i||this.active)return null;this.requestSequence+=1;const n=requestIdCheck(this.requestIdSecret,this.instanceId,this.queryGeneration,this.requestSequence),o=`data-${this.instanceId}-generation-${this.queryGeneration}-request-${this.requestSequence}-${n}`,s=Object.freeze({requestId:o,queryGeneration:this.queryGeneration,query:this.query,normalizedQuery:this.query.trim(),fetchLimit:i,position:frozenPosition(t)}),r="search"===e.kind?Object.freeze({...s,kind:"search",mode:e.mode}):Object.freeze({...s,kind:"loadMore"});return this.active={request:r,phase:"requested"},this.status="requested",this.error=null,r}invalidateActive(e){if(!this.active)return null;const{request:t}=this.active;this.active=null,this.status="cancelled";const i=Object.freeze({requestId:t.requestId,queryGeneration:t.queryGeneration,reason:e});return Object.freeze({type:"cancel",notification:i})}classifyInactiveRequest(e,t){const i=parseRequestId(e);return!i||i.instanceId!==this.instanceId||i.check!==requestIdCheck(this.requestIdSecret,i.instanceId,i.queryGeneration,i.sequence)||i.sequence>this.requestSequence?"unknown-request":i.queryGeneration!==t?"invalid":i.queryGeneration<this.queryGeneration?"stale":"unknown-request"}hasValidCompletionEnvelope(e){return"string"==typeof e.requestId&&e.requestId.length>0&&isNonNegativeSafeInteger(e.queryGeneration)&&"string"==typeof e.status&&["succeeded","empty","exhausted","failed","cancelled"].includes(e.status)}validateCompletionPayload(e,t){const i=["requestId","queryGeneration","status"];switch(e.status){case"succeeded":{const n=[...i,"items","hasMore"];if("cursor"===t.position.mode&&n.push("nextCursor"),!exactKeys(e,n)||!Array.isArray(e.items)||!0!==e.hasMore)return{valid:!1};if("cursor"===t.position.mode){if(t.position.ordinal>=Number.MAX_SAFE_INTEGER||!isCursor(e.nextCursor))return{valid:!1};if(cursorTokenByteLength(e.nextCursor)>this.config.maxCursorTokenBytes)return{valid:!1,resourceLimit:"cursor-token-size"};if(this.hasCommittedCursor(e.nextCursor))return{valid:!1}}else{if("nextCursor"in e)return{valid:!1};if(t.position.page>=Number.MAX_SAFE_INTEGER)return{valid:!1}}return{valid:!0}}case"empty":{const n=[...i,"hasMore","advance"];if("cursor"===t.position.mode&&"next"===e.advance&&n.push("nextCursor"),!exactKeys(e,n)||!0!==e.hasMore)return{valid:!1};if("next"!==e.advance&&"retry"!==e.advance)return{valid:!1};if("cursor"===t.position.mode){if("next"===e.advance){if(t.position.ordinal>=Number.MAX_SAFE_INTEGER||!isCursor(e.nextCursor))return{valid:!1};if(cursorTokenByteLength(e.nextCursor)>this.config.maxCursorTokenBytes)return{valid:!1,resourceLimit:"cursor-token-size"};if(this.hasCommittedCursor(e.nextCursor))return{valid:!1}}else if("nextCursor"in e)return{valid:!1}}else{if("nextCursor"in e)return{valid:!1};if("next"===e.advance&&t.position.page>=Number.MAX_SAFE_INTEGER)return{valid:!1}}return{valid:!0}}case"exhausted":return exactKeys(e,[...i,"items","hasMore"])&&Array.isArray(e.items)&&!1===e.hasMore?{valid:!0}:{valid:!1};case"failed":{if(!exactKeys(e,[...i,"error"])||!isRecord(e.error))return{valid:!1};const t=e.error;return!exactKeys(t,["message","code","retryable"])||"string"!=typeof t.message||0===t.message.trim().length||void 0!==t.code&&"string"!=typeof t.code||void 0!==t.retryable&&"boolean"!=typeof t.retryable?{valid:!1}:{valid:!0}}case"cancelled":{const t="reason"in e;return!exactKeys(e,t?[...i,"reason"]:i)||t&&void 0!==e.reason&&"host-cancelled"!==e.reason?{valid:!1}:{valid:!0}}default:return{valid:!1}}}hasCommittedCursor(e){return this.committedCursors.has(e)||"cursor"===this.nextEligiblePosition.mode&&this.nextEligiblePosition.cursor===e}advanceFrom(e,t){if("page"===e.position.mode){const t=e.position.page;return{position:Object.freeze({mode:"page",page:t+1}),lastCommittedPage:t}}const i=t.nextCursor;return{position:Object.freeze({mode:"cursor",cursor:i,ordinal:e.position.ordinal+1}),lastCommittedPage:this.lastCommittedPage,cursorToCommit:i}}}const LEGACY_DATA_LOADING_CONFIG={protocol:"legacy",searchMode:"local",paginationMode:"page",firstPage:1},DATA_LOADING_CONFIG_FIELDS=["protocol","searchMode","paginationMode","firstPage","fetchLimit"],INVALID_OBJECT_VALUE=Object.freeze({kind:"object"}),INVALID_ARRAY_VALUE=Object.freeze({kind:"array"}),INVALID_FUNCTION_VALUE=Object.freeze({kind:"function"});function invalidConfigValueSignature(e){return null===e||"object"!=typeof e&&"function"!=typeof e?e:"function"==typeof e?INVALID_FUNCTION_VALUE:Array.isArray(e)?INVALID_ARRAY_VALUE:INVALID_OBJECT_VALUE}function createInvalidDataLoadingCandidateSignature(e,t){const i=null!==e&&"object"==typeof e?Object.getPrototypeOf(e):void 0,n=null!==e&&"object"==typeof e&&!Array.isArray(e)&&(i===Object.prototype||null===i),o=n?e:void 0;return{rootKind:n?"record":null===e?"null":Array.isArray(e)?"array":typeof e,rootValue:null===e||"object"!=typeof e?e:void 0,fieldValues:o?DATA_LOADING_CONFIG_FIELDS.map(e=>invalidConfigValueSignature(o[e])):[],issues:t.map(({path:e,code:t,message:i})=>[e,t,i])}}function invalidDataLoadingSignaturesEqual(e,t){if(e.rootKind!==t.rootKind||!Object.is(e.rootValue,t.rootValue))return!1;if(e.fieldValues.length!==t.fieldValues.length||e.issues.length!==t.issues.length)return!1;for(let i=0;i<e.fieldValues.length;i+=1)if(!Object.is(e.fieldValues[i],t.fieldValues[i]))return!1;for(let i=0;i<e.issues.length;i+=1){const n=e.issues[i],o=t.issues[i];if(n[0]!==o[0]||n[1]!==o[1]||n[2]!==o[2])return!1}return!0}class EnhancedSelect extends HTMLElement{static get observedAttributes(){return["aria-label","aria-description","aria-busy"]}get classMap(){return this._classMap}set classMap(e){this._areClassMapsEqual(this._classMap,e)||(this._invalidateGuardedMeasurements(),this._classMap=e,this._setGlobalStylesMirroring(Boolean(this._optionRenderer||e||this._groupHeaderRenderer)),this._track("style","classMapChanged",{hasClassMap:Boolean(e),keys:e?Object.keys(e):[]}),this.isConnected&&this._renderOptions())}get groupHeaderRenderer(){return this._groupHeaderRenderer}set groupHeaderRenderer(e){this._groupHeaderRenderer!==e&&(this._groupHeaderRenderer=e,this._setGlobalStylesMirroring(Boolean(this._optionRenderer||this._classMap||e)),this._track("style","groupHeaderRendererChanged",{enabled:Boolean(e)}),this.isConnected&&this._renderOptions())}constructor(){super(),this._dataLoadingConfig={...LEGACY_DATA_LOADING_CONFIG},this._hasLastInvalidDataLoadingCandidate=!1,this._engine=new SelectEngineBridge,this._virtualizationScope={dataKeys:[],filteredKeys:[],registeredKeys:[],windowKeys:[],mountedKeys:[],selectedKeys:new Set,activeKey:null},this._renderPlan={mode:"legacy-full",filteredIndices:[],filteredKeys:[],intendedRenderKeys:[],filteredIndexByKey:new Map},this._guardedVirtualWindow=null,this._guardedVirtualizer=null,this._guardedVirtualizationRequested=!1,this._guardedVirtualizerKeys=[],this._guardedMeasurementQuery=null,this._guardedOptionResizeObserver=null,this._guardedObservedOptions=new Set,this._guardedObserverSeenOptions=new WeakSet,this._guardedOptionMeasurements=new WeakMap,this._guardedMeasurementGeneration=0,this._guardedVirtualScrollTop=0,this._guardedVirtualViewportHeight=0,this._guardedVirtualOverscan=0,this._guardedVirtualWindowRafId=null,this._guardedScrollListenerAttached=!1,this._onGuardedVirtualScroll=()=>this._scheduleGuardedVirtualWindowUpdate(),this._effectRunner=new DefaultSelectEffectRunner,this._itemAdapter=this._createEngineItemAdapter(),this._itemRegistry=createItemRegistry([],this._itemAdapter),this._selectedRecordsByKey=new Map,this._registryItemsRef=[],this._pageCache={},this._dataRequestCoordinator=null,this._acknowledgedSearchMode=null,this._acknowledgedReady=!1,this._acknowledgedDeferredStart=!1,this._hasEverConnected=!1,this._acknowledgedStartTask=null,this._clearAcknowledgedCoordinatorAfterProjection=!1,this._acknowledgedConfigUpdatePending=!1,this._acknowledgedDeferredModeChange=!1,this._acknowledgedProjectionPending=!1,this._acknowledgedProjectionSettling=!1,this._acknowledgedPendingSearchQuery=null,this._acknowledgedProjectionFailureStageForTest=null,this._acknowledgedProjectionRunning=!1,this._acknowledgedProjectionTask=null,this._acknowledgedProjectionScrollTop=0,this._acknowledgedLastRequest=null,this._acknowledgedProjectionCommitsPosition=!1,this._acknowledgedProjectionRequest=null,this._acknowledgedProjectionAttempt=0,this._acknowledgedProjectionDiagnostic=null,this._typeBuffer="",this._hasError=!1,this._errorMessage="",this._boundArrowClick=null,this._pendingFirstRenderMark=!1,this._pendingSearchRenderMark=!1,this._rangeAnchorIndex=null,this._customOptionBoundElements=new WeakSet,this._customOptionManagedActiveClasses=new WeakMap,this._customOptionNormalizedIds=new WeakMap,this._customOptionNormalizedLabels=new WeakMap,this._mirrorGlobalStylesForCustomOptions=!1,this._globalStylesObserver=null,this._globalStylesContainer=null,this._themeContextObserver=null,this._globalStylesSyncToken=0,this._asyncGeneration=0,this._lifecycleTimers=new Set,this._lifecycleRafs=new Set,this._keyboardActiveChangeGeneration=0,this._tracking={events:[],styles:[],limitations:[]},this._suppressBlurClose=!1,this._renderCycleId=0,this._completedRenderCycleId=0,this._renderCycleWaiters=new Map,this._renderCycleWaiterTimeouts=new Map,this._suppressNextOpenClick=!1,this._resolvedDropdownPlacement="bottom",this._multiScrollDrag={active:!1,moved:!1,pointerId:-1,startX:0,startScrollLeft:0},this._liftedAncestors=[],this._onDocumentPointerDown=e=>{const t=e.composedPath&&e.composedPath()||[];let i=!1;for(const e of t){if(e===this||e===this._container){i=!0;break}if(e instanceof Node)try{if(this._shadow&&this._shadow.contains(e)){i=!0;break}}catch(e){}if(e instanceof Element)try{if(e.matches("[data-sm-selectable], [data-selectable], [data-sm-state], .input-container, .select-container, .dropdown-arrow-container, .clear-control-button")){i=!0;break}}catch(e){}}i||this._handleClose("outside-pointer")},this._shadow=this.attachShadow({mode:"open"}),this._uniqueId=`enhanced-select-${Math.random().toString(36).substr(2,9)}`,this._rendererHelpers=this._buildRendererHelpers(),this._config=selectConfig.getConfig(),this._engine.dispatch({type:"DISABLED_CHANGED",disabled:!this._config.enabled}),this._syncEngineSelectionConfig();const e=this;this._state={get isOpen(){return"open"===e._engine.state.popup},isBusy:!1,isSearching:!1,currentPage:this._config.infiniteScroll.initialPage||1,totalPages:1,selectedIndices:new Set,selectedItems:new Map,activeIndex:-1,searchQuery:"",loadedItems:[],groupedItems:[],preserveScrollPosition:!1,lastScrollPosition:0,lastNotifiedQuery:null,lastNotifiedResultCount:0,isExpanded:!1},this._container=this._createContainer(),this._inputContainer=this._createInputContainer(),this._inputContent=this._createInputContent(),this._input=this._createInput(),this._arrowContainer=this._createArrowContainer(),this._clearControl=this._createClearControl(),this._dropdown=this._createDropdown(),this._optionsContainer=this._createOptionsContainer(),this._liveRegion=this._createLiveRegion(),this._errorDescription=this._createErrorDescription(),this._initializeStyles(),this._syncStyleConfigVariables(),this._assembleDOM(),this._attachEventListeners(),this._initializeObservers(),this._syncComboboxAccessibility(),this._syncListboxAccessibility()}connectedCallback(){this._hasEverConnected=!0,EnhancedSelect._instances.add(this),this._runEngineEffects(this._engine.dispatch({type:"CONNECT"})),this._runEngineEffects(this._engine.dispatch({type:"DISABLED_CHANGED",disabled:!this._config.enabled})),this._connectionController?.abort(),this._connectionController=new AbortController,document.addEventListener("pointerdown",this._onDocumentPointerDown,{signal:this._connectionController.signal}),this.style.display="block",this._syncDirectionConfig(),this._syncComboboxAccessibility(),(this._dataRequestCoordinator||"acknowledged"===this._dataLoadingConfig.protocol)&&this._initializeObservers(),(this._optionRenderer||this._classMap||this._groupHeaderRenderer)&&this._setGlobalStylesMirroring(!0),this._config.serverSide.enabled&&this._config.serverSide.initialSelectedValues&&this._loadInitialSelectedItems(),(this._state.loadedItems.length>0||this._state.groupedItems.length>0)&&(this._renderOptions(),this._updateInputDisplay()),this._config.callbacks.onOpen&&this._config.callbacks.onOpen(),this._acknowledgedDeferredStart&&(this._acknowledgedDeferredStart=!1,this.startDataLoading())}attributeChangedCallback(e,t,i){t!==i&&("aria-busy"!==e?"aria-label"!==e&&"aria-description"!==e||(this._syncComboboxAccessibility(),"aria-label"===e&&this._syncListboxAccessibility()):this._syncListboxAccessibility())}disconnectedCallback(){if(this._dataRequestCoordinator){const e=this._dataRequestCoordinator.disconnect();this._acknowledgedReady=!1,this._dispatchAcknowledgedActions(e),this._state.isBusy=!1,this._state.isSearching=!1,this._state.preserveScrollPosition=!1}EnhancedSelect._instances.delete(this),this._state.isOpen&&this._handleClose("disconnect"),this._runEngineEffects(this._engine.dispatch({type:"DISCONNECT"})),this._connectionController?.abort(),this._connectionController=void 0,this._asyncGeneration+=1,this._cancelGuardedVirtualWindowUpdate(),this._clearLifecycleTasks(),this._destroyGuardedVirtualizer(!0),this._virtualizationScope={...this._virtualizationScope,mountedKeys:[]},Array.from(this._optionsContainer.children).filter(e=>e.hasAttribute("data-index")||e.hasAttribute("data-virtual-spacer")).forEach(e=>e.remove()),this._resizeObserver?.disconnect(),this._intersectionObserver?.disconnect(),this._busyTimeout&&clearTimeout(this._busyTimeout),this._typeTimeout&&clearTimeout(this._typeTimeout),this._searchTimeout&&clearTimeout(this._searchTimeout),this._endMultiScrollDrag(),this._boundArrowClick&&this._arrowContainer&&this._arrowContainer.removeEventListener("click",this._boundArrowClick),this._renderCycleId+=1,this._resolvePendingRenderCycles(!1),this._teardownGlobalStylesMirroring()}_setGlobalStylesMirroring(e){this._mirrorGlobalStylesForCustomOptions!==e?(this._mirrorGlobalStylesForCustomOptions=e,this._track("style","globalStylesMirroringChanged",{enabled:e}),e?this._setupGlobalStylesMirroring():this._teardownGlobalStylesMirroring()):e&&this.isConnected&&!this._globalStylesObserver&&this._setupGlobalStylesMirroring()}_setLifecycleTimeout(e,t=0){const i=window.setTimeout(()=>{this._lifecycleTimers.delete(i),this.isConnected&&e()},t);return this._lifecycleTimers.add(i),i}_requestLifecycleFrame(e){const t=requestAnimationFrame(()=>{this._lifecycleRafs.delete(t),this.isConnected&&e()});return this._lifecycleRafs.add(t),t}_clearLifecycleTasks(){for(const e of this._lifecycleTimers)clearTimeout(e);this._lifecycleTimers.clear();for(const e of this._lifecycleRafs)cancelAnimationFrame(e);this._lifecycleRafs.clear()}_setupGlobalStylesMirroring(){"undefined"!=typeof document&&this._mirrorGlobalStylesForCustomOptions&&(this._setupThemeContextMirroring(),this._mirrorDocumentStylesIntoShadow(),this._globalStylesObserver||(this._globalStylesObserver=new MutationObserver(()=>{this._mirrorDocumentStylesIntoShadow()}),this._globalStylesObserver.observe(document.head,{childList:!0,subtree:!0,attributes:!0,characterData:!0})))}_teardownGlobalStylesMirroring(){this._globalStylesObserver&&(this._globalStylesObserver.disconnect(),this._globalStylesObserver=null),this._themeContextObserver&&(this._themeContextObserver.disconnect(),this._themeContextObserver=null),this._globalStylesContainer&&(this._globalStylesContainer.remove(),this._globalStylesContainer=null)}_mirrorDocumentStylesIntoShadow(){if("undefined"==typeof document)return;if(!this._mirrorGlobalStylesForCustomOptions)return;this._globalStylesContainer||(this._globalStylesContainer=document.createElement("div"),this._globalStylesContainer.setAttribute("data-smilodon-global-styles",""),this._shadow.appendChild(this._globalStylesContainer));const e=this._globalStylesContainer,t=++this._globalStylesSyncToken,i=Array.from(document.querySelectorAll('style,link[rel="stylesheet"]'));Promise.all(i.map((e,t)=>this._createScopedGlobalStyleNode(e,t))).then(i=>{this._globalStylesContainer&&t===this._globalStylesSyncToken&&(e.replaceChildren(...i.filter(e=>Boolean(e))),this._syncMirroredThemeContext())})}_setupThemeContextMirroring(){if("undefined"==typeof document)return;if(this._syncMirroredThemeContext(),this._themeContextObserver)return;this._themeContextObserver=new MutationObserver(()=>{this._syncMirroredThemeContext()});const e=new Set([this,document.documentElement]);document.body&&e.add(document.body);let t=this.parentElement;for(;t;)e.add(t),t=t.parentElement;e.forEach(e=>{this._themeContextObserver?.observe(e,{attributes:!0,attributeFilter:["class","dark-mode","darkmode","data-theme","theme"]})})}_syncMirroredThemeContext(){const e=this._optionsContainer;if(!e)return;const t=[".dark-mode",".dark","[dark-mode]","[darkmode]",'[data-theme="dark"]','[theme="dark"]'].some(e=>this.matches(e)||Boolean(this.closest(e)))||document.documentElement.matches('.dark-mode, .dark, [dark-mode], [darkmode], [data-theme="dark"], [theme="dark"]')||Boolean(document.body?.matches('.dark-mode, .dark, [dark-mode], [darkmode], [data-theme="dark"], [theme="dark"]'));e.classList.toggle("dark",t),e.classList.toggle("dark-mode",t),t?(e.setAttribute("dark-mode",""),e.setAttribute("data-theme","dark"),e.setAttribute("theme","dark")):(e.removeAttribute("dark-mode"),e.removeAttribute("data-theme"),e.removeAttribute("theme"))}async _createScopedGlobalStyleNode(e,t){if(e instanceof HTMLStyleElement)return this._buildScopedStyleElement(e.textContent||"",String(t));if(e instanceof HTMLLinkElement&&e.href){const i="use-credentials"===e.crossOrigin?"include":"same-origin",n=`${e.href}|${i}`;let o=EnhancedSelect._mirroredStylesheetTextCache.get(n);o?o.lastUsed=Date.now():(o={promise:fetch(e.href,{credentials:i,mode:"cors"}).then(e=>e.ok?e.text():null).catch(()=>null),lastUsed:Date.now()},EnhancedSelect._mirroredStylesheetTextCache.set(n,o),EnhancedSelect._pruneMirroredStylesheetTextCache());const s=await o.promise;return null===s?(EnhancedSelect._mirroredStylesheetTextCache.delete(n),null):this._buildScopedStyleElement(s,String(t))}return null}static _pruneMirroredStylesheetTextCache(){for(;EnhancedSelect._mirroredStylesheetTextCache.size>EnhancedSelect._MIRRORED_STYLESHEET_CACHE_LIMIT;){let e,t=1/0;for(const[i,n]of EnhancedSelect._mirroredStylesheetTextCache.entries())n.lastUsed<t&&(t=n.lastUsed,e=i);if(!e)return;EnhancedSelect._mirroredStylesheetTextCache.delete(e)}}_areClassMapsEqual(e,t){if(e===t)return!0;if(!e||!t)return!1;const i=Object.keys(e),n=Object.keys(t);return i.length===n.length&&i.every(i=>e[i]===t[i])}_buildScopedStyleElement(e,t){const i=this._scopeMirroredCssText(e);if(!i.trim())return null;const n=document.createElement("style");return n.setAttribute("data-smilodon-global-style",t),n.textContent=i,n}_scopeMirroredCssText(e){if(!e.trim())return"";try{if("undefined"!=typeof CSSStyleSheet&&"replaceSync"in CSSStyleSheet.prototype){const t=new CSSStyleSheet;return t.replaceSync(e),this._serializeScopedCssRules(Array.from(t.cssRules))}}catch(t){return this._scopeMirroredCssTextFallback(e)}return this._scopeMirroredCssTextFallback(e)}_scopeMirroredCssTextFallback(e){if(!e.trim())return"";const t=[],i=/([^{}]+)\{([^{}]+)\}/g;let n;for(;null!==(n=i.exec(e));){const e=n[1].trim(),i=n[2].trim();if(e.startsWith("@"))continue;const o=this._splitSelectorList(e).map(e=>this._scopeMirroredSelector(e)).filter(Boolean);o.length>0&&t.push(`${o.join(", ")} { ${i} }`)}return t.join("\n")}_serializeScopedCssRules(e){return e.map(e=>this._serializeScopedCssRule(e)).filter(Boolean).join("\n")}_serializeScopedCssRule(e){if(e instanceof CSSStyleRule){const t=this._splitSelectorList(e.selectorText).map(e=>this._scopeMirroredSelector(e)).filter(Boolean);return 0===t.length?"":`${t.join(", ")} { ${e.style.cssText} }`}if(e instanceof CSSMediaRule){const t=this._serializeScopedCssRules(Array.from(e.cssRules));return t?`@media ${e.conditionText} { ${t} }`:""}if("undefined"!=typeof CSSSupportsRule&&e instanceof CSSSupportsRule){const t=this._serializeScopedCssRules(Array.from(e.cssRules));return t?`@supports ${e.conditionText} { ${t} }`:""}if(e instanceof CSSFontFaceRule||e instanceof CSSKeyframesRule)return e.cssText;const t=e;if(t.cssRules){const e=this._serializeScopedCssRules(Array.from(t.cssRules));if(!e)return"";const i=t.constructor?.name??"";if(i.includes("Layer"))return`@layer ${t.name??""} { ${e} }`;if(i.includes("Container"))return`@container ${t.conditionText??""} { ${e} }`}return""}_splitSelectorList(e){const t=[];let i="",n=0,o=0;for(const s of e)"("===s&&(n+=1),")"===s&&(n=Math.max(0,n-1)),"["===s&&(o+=1),"]"===s&&(o=Math.max(0,o-1)),","!==s||0!==n||0!==o?i+=s:(i.trim()&&t.push(i.trim()),i="");return i.trim()&&t.push(i.trim()),t}_scopeMirroredSelector(e){const t=`.${EnhancedSelect._MIRRORED_STYLES_SCOPE_CLASS}`;let i=e.replace(/(^|\s|>|\+|~)(:root|html|body)(?=\b|\s|[.#[:>+~]|$)/g,`$1${t}`);let n=!1;return[/\.dark-mode(?![\w-]|\\:)/g,/\.dark(?![\w-]|\\:)/g,/\[dark-mode\]/g,/\[darkmode\]/g,/\[data-theme=(?:"dark"|'dark'|dark)\]/g,/\[theme=(?:"dark"|'dark'|dark)\]/g].forEach(e=>{i=i.replace(e,e=>(n=!0,`${e}${t}`))}),i.includes(EnhancedSelect._MIRRORED_STYLES_SCOPE_CLASS)||n||(i=`${t} ${i}`),i}_normalizeCustomOptionAccessibility(e,t){const i=this._customOptionNormalizedLabels.get(e),n=e.getAttribute("aria-label"),o=void 0!==i&&n===i;e.hasAttribute("aria-labelledby")||n&&!o?this._customOptionNormalizedLabels.delete(e):(e.setAttribute("aria-label",t.label),this._customOptionNormalizedLabels.set(e,t.label));const s=["a[href]","button","input","select","textarea","summary","[tabindex]",'[contenteditable=""]','[contenteditable="true"]','[role="button"]','[role="link"]','[role="checkbox"]','[role="switch"]','[role="radio"]','[role="textbox"]'].join(", ");e.querySelectorAll(s).forEach(i=>{i!==e&&(i.tabIndex=-1,i.hasAttribute("data-smilodon-keep-role")||i.setAttribute("role","presentation"),!t.disabled&&!i.matches("button, input, select, textarea, summary, a[href]")||i.hasAttribute("data-smilodon-keep-aria")||i.setAttribute("aria-hidden","true"))})}_createContainer(){const e=document.createElement("div");return e.className="select-container",this._config.styles.classNames?.container&&(e.className+=" "+this._config.styles.classNames.container),this._config.styles.container&&Object.assign(e.style,this._config.styles.container),e}_createInputContainer(){const e=document.createElement("div");e.className="input-container",e.setAttribute("part","button");const t=this._config.styles.input;if(t&&!this._config.styles.container){const i=["background","backgroundColor","border","borderColor","borderStyle","borderWidth","borderRadius","boxShadow","padding","height","minHeight","maxHeight"];for(const n of i){const i=t[n];null!=i&&""!==i&&(e.style[n]=i)}}return e}_createInputContent(){const e=document.createElement("div");return e.className="input-content",e}_setCssVariable(e,t){null!=t&&""!==t?this.style.setProperty(e,String(t)):this.style.removeProperty(e)}_applyStyleVariableMap(e,t){Object.entries(t).forEach(([t,i])=>{this._setCssVariable(i,e?.[t])})}_getDisabledOptionBehavior(){const e=this._config.selection.disabledOptionBehavior??{};return{selectable:!0===e.selectable,hoverable:!0===e.hoverable,focusable:!0===e.focusable}}_isDisabledOptionSelectable(e){return Boolean(e?.disabled)&&this._getDisabledOptionBehavior().selectable}_isOptionSelectionBlocked(e){return Boolean(e?.disabled)&&!this._isDisabledOptionSelectable(e)}_isPhase2DevRuntime(){const e=globalThis.process?.env?.NODE_ENV;return"production"!==e}_getDuplicateKeyPolicy(){return this._isPhase2DevRuntime()?"throw":"warn"}_warnPhase2(e){this._isPhase2DevRuntime()&&"undefined"!=typeof console&&console.warn(e)}_getItemValue(e){return this._config.serverSide.getValueFromItem?.(e)??e?.value??e}_getItemLabel(e){return this._config.serverSide.getLabelFromItem?.(e)??e?.label??String(e)}_createEngineItemAdapter(){return createDefaultItemAdapter({getValue:e=>this._getItemValue(e),getLabel:e=>this._getItemLabel(e),isDisabled:e=>Boolean(e?.disabled),getGroupKey:e=>{const t=e?.group;return null==t?null:String(t)},onIndexFallback:e=>this._warnPhase2(e)})}_getBlockedDisabledKeys(){const e=this._itemRegistry.records.filter(e=>e.disabled&&this._isOptionSelectionBlocked(e.item)).map(e=>e.key);for(const t of this._getSelectedEntries())this._isOptionSelectionBlocked(t.item)&&e.push(t.key);return e}_syncEngineSelectionConfig(){const e=Boolean(this._input?.hasAttribute("required")),t=this._getBlockedDisabledKeys();this._engine.dispatch({type:"SELECTION_CONFIG_CHANGED",multiple:"multi"===this._config.selection.mode,required:e,allowDeselect:!0===this._config.selection.allowDeselect,maxSelections:this._config.selection.maxSelections??0,disabledKeys:t}),this._state&&(this._syncLegacySelectionFromEngine(),this._syncLegacyActiveFromEngine(),this._assertSelectionProjection("selection config"),this._assertActiveProjection("selection config"))}_rebuildItemRegistry(e=this._state.loadedItems,t){const i=t??createItemRegistry(e,this._itemAdapter,{duplicateKeyPolicy:this._getDuplicateKeyPolicy()}),n=this._engine.state.activeKey,o=null===this._rangeAnchorIndex?void 0:this._itemRegistry.indexToKey.get(this._rangeAnchorIndex);this._itemRegistry=i,this._state.loadedItems=e,this._registryItemsRef=e;const s=this._getBlockedDisabledKeys();this._rangeAnchorIndex=void 0===o?null:i.keyToIndex.get(o)??null,this._engine.dispatch({type:"ITEMS_REGISTERED",keys:i.records.map(e=>e.key),disabledKeys:s}),null!==n&&i.keyToRecord.get(n)?.disabled?this._dispatchActiveKey(null,"programmatic","items registered with disabled active key"):this._syncLegacyActiveFromEngine(),this._syncLegacySelectionFromEngine(),this._syncEngineSelectionConfig(),this._assertSelectionProjection("items registered")}_ensureRegistryCurrent(){this._registryItemsRef!==this._state.loadedItems||this._itemRegistry.records.length!==this._state.loadedItems.length||this._itemRegistry.records.some((e,t)=>e.item!==this._state.loadedItems[t])?this._rebuildItemRegistry():(this._syncLegacySelectionFromEngine(),this._syncLegacyActiveFromEngine(),this._assertSelectionProjection("registry read"),this._assertActiveProjection("registry read"))}_getRecordByIndex(e){const t=this._itemRegistry.indexToKey.get(e);return void 0===t?null:this._itemRegistry.keyToRecord.get(t)??null}_getSelectedEntries(){const e=[];if(!this._state)return e;for(const t of this._engine.state.selectedKeys){const i=this._itemRegistry.keyToRecord.get(t)??this._selectedRecordsByKey.get(t);i&&e.push({key:t,index:i.index,item:i.item})}return e}_syncLegacySelectionFromEngine(){const e=new Set,t=new Map,i=this._engine.state.selectedKeys;for(const e of[...this._selectedRecordsByKey.keys()])i.has(e)||this._selectedRecordsByKey.delete(e);for(const n of i){const i=this._itemRegistry.keyToRecord.get(n);i&&this._selectedRecordsByKey.set(n,i),i&&(e.add(i.index),t.set(i.index,i.item))}this._state.selectedIndices=e,this._state.selectedItems=t}_projectedSelectedKeysSnapshot(){return new Set([...this._state.selectedIndices].map(e=>this._itemRegistry.indexToKey.get(e)).filter(e=>void 0!==e))}_assertSelectionProjection(e){if(!this._isPhase2DevRuntime())return;const t=this._projectedSelectedKeysSnapshot(),i=this._engine.state.selectedKeys;if(this._state.selectedItems.size!==this._state.selectedIndices.size||[...this._state.selectedIndices].some(e=>!this._state.selectedItems.has(e))||[...i].some(e=>this._itemRegistry.keyToRecord.has(e)&&!t.has(e))||[...t].some(e=>!i.has(e)))throw new Error(`[Smilodon Phase2] Selection projection failed in ${e}: compatibility=${JSON.stringify([...t])}, engine=${JSON.stringify([...i])}`)}_projectedActiveKeySnapshot(){return this._state.activeIndex<0?null:this._itemRegistry.indexToKey.get(this._state.activeIndex)??null}_syncLegacyActiveFromEngine(){const e=this._engine.state.activeKey;this._state.activeIndex=null===e?-1:this._itemRegistry.keyToIndex.get(e)??-1,this._syncLegacyActiveAria()}_assertActiveProjection(e){if(!this._isPhase2DevRuntime())return;const t=this._projectedActiveKeySnapshot(),i=this._engine.state.activeKey;if(t!==i&&!Object.is(t,i))throw new Error(`[Smilodon Phase2] Active projection failed in ${e}: compatibility=${String(t)}, engine=${String(i)}`)}_dispatchActiveKey(e,t,i){const n=this._engine.dispatch({type:"ACTIVE_KEY_CHANGED",key:e,reason:t});this._runEngineEffects(n),this._syncLegacyActiveFromEngine(),this._assertActiveProjection(i)}_clearDisabledEngineActive(e){const t=this._engine.state.activeKey;null!==t&&this._itemRegistry.keyToRecord.get(t)?.disabled?this._dispatchActiveKey(null,"programmatic",e):(this._syncLegacyActiveFromEngine(),this._assertActiveProjection(e))}_mirrorLegacyActive(e,t){this._dispatchActiveKey(this._projectedActiveKeySnapshot(),e,t)}_dispatchSelection(e,t){this._engine.dispatch(e),this._syncLegacySelectionFromEngine(),this._assertSelectionProjection(t)}_mirrorLegacySelection(e,t){this._dispatchSelection(e,t)}_requestSelectionReplacement(e,t,i){for(const t of e){const e=this._itemRegistry.keyToRecord.get(t.key)??this._selectedRecordsByKey.get(t.key);this._selectedRecordsByKey.set(t.key,e??{key:t.key,item:t.item,index:t.index,label:this._getItemLabel(t.item),value:this._getItemValue(t.item),disabled:Boolean(t.item?.disabled),groupKey:null==t.item?.group?null:String(t.item.group)})}this._dispatchSelection({type:"REPLACE_SELECTION_REQUEST",keys:e.map(({key:e})=>e),reason:t},i)}_registerShadowItems(e){const t=e.map(e=>this._itemRegistry.indexToKey.get(e)).filter(e=>void 0!==e);this._engine.dispatch({type:"ITEMS_REGISTERED",keys:t,disabledKeys:this._getBlockedDisabledKeys()}),this._clearDisabledEngineActive("visible items"),this._assertSelectionProjection("visible items")}_syncLegacyActiveAria(){this._syncComboboxAccessibility()}_syncStyleConfigVariables(){const e=this._config.styles;e&&(this._applyStyleVariableMap(e.option,{background:"--select-option-bg",backgroundColor:"--select-option-bg",color:"--select-option-color",border:"--select-option-border",borderBottom:"--select-option-border-bottom",borderRadius:"--select-option-border-radius",boxShadow:"--select-option-shadow",transform:"--select-option-transform",padding:"--select-option-padding",margin:"--select-option-margin",fontSize:"--select-option-font-size",fontWeight:"--select-option-font-weight",lineHeight:"--select-option-line-height",textAlign:"--select-option-text-align"}),this._applyStyleVariableMap(e.selectedOption,{background:"--select-option-selected-bg",backgroundColor:"--select-option-selected-bg",color:"--select-option-selected-color",border:"--select-option-selected-border",borderBottom:"--select-option-selected-border-bottom",borderRadius:"--select-option-selected-border-radius",boxShadow:"--select-option-selected-shadow",transform:"--select-option-selected-transform",fontWeight:"--select-option-selected-weight"}),this._applyStyleVariableMap(e.hoverOption,{background:"--select-option-hover-bg",backgroundColor:"--select-option-hover-bg",color:"--select-option-hover-color",border:"--select-option-hover-border",borderBottom:"--select-option-hover-border-bottom",boxShadow:"--select-option-hover-shadow",transform:"--select-option-hover-transform"}),this._applyStyleVariableMap(e.activeOption,{background:"--select-option-active-bg",backgroundColor:"--select-option-active-bg",color:"--select-option-active-color",border:"--select-option-active-border",outline:"--select-option-active-outline",outlineOffset:"--select-option-active-outline-offset",boxShadow:"--select-option-active-shadow",transform:"--select-option-active-transform"}),this._applyStyleVariableMap(e.disabledOption,{background:"--select-option-disabled-bg",backgroundColor:"--select-option-disabled-bg",color:"--select-option-disabled-color",border:"--select-option-disabled-border",borderBottom:"--select-option-disabled-border-bottom",opacity:"--select-option-disabled-opacity",cursor:"--select-option-disabled-cursor"}),this._applyStyleVariableMap(e.selectedIndicator,{width:"--select-option-selected-indicator-width",height:"--select-option-selected-indicator-height",background:"--select-option-selected-indicator-bg",backgroundColor:"--select-option-selected-indicator-bg",borderRadius:"--select-option-selected-indicator-radius",left:"--select-option-selected-indicator-left",right:"--select-option-selected-indicator-right",top:"--select-option-selected-indicator-top",transform:"--select-option-selected-indicator-transform",animation:"--select-option-selected-indicator-animation"}),this._setCssVariable("--select-option-selected-indicator-display",!1===this._config.selection.showSelectedIndicator?"none":e.selectedIndicator?.display),this._applyStyleVariableMap(e.badge,{width:"--select-badge-width",minWidth:"--select-badge-min-width",maxWidth:"--select-badge-max-width",height:"--select-badge-height",minHeight:"--select-badge-min-height",padding:"--select-badge-padding",margin:"--select-badge-margin",gap:"--select-badge-gap",background:"--select-badge-bg",backgroundColor:"--select-badge-bg",color:"--select-badge-color",border:"--select-badge-border",borderRadius:"--select-badge-border-radius",boxShadow:"--select-badge-shadow",fontSize:"--select-badge-font-size",fontWeight:"--select-badge-font-weight",lineHeight:"--select-badge-line-height",letterSpacing:"--select-badge-letter-spacing"}),this._applyStyleVariableMap(e.badgeHover,{background:"--select-badge-hover-bg",backgroundColor:"--select-badge-hover-bg",color:"--select-badge-hover-color",border:"--select-badge-hover-border",boxShadow:"--select-badge-hover-shadow",transform:"--select-badge-hover-transform"}),this._applyStyleVariableMap(e.badgeActive,{background:"--select-badge-active-bg",backgroundColor:"--select-badge-active-bg",color:"--select-badge-active-color",border:"--select-badge-active-border",boxShadow:"--select-badge-active-shadow",transform:"--select-badge-active-transform"}),this._applyStyleVariableMap(e.badgeLabel,{color:"--select-badge-label-color",fontSize:"--select-badge-label-font-size",fontWeight:"--select-badge-label-font-weight",lineHeight:"--select-badge-label-line-height",letterSpacing:"--select-badge-label-letter-spacing",textAlign:"--select-badge-label-text-align"}),this._applyStyleVariableMap(e.badgeRemove,{width:"--select-badge-remove-size",height:"--select-badge-remove-size",minWidth:"--select-badge-remove-min-width",minHeight:"--select-badge-remove-min-height",marginLeft:"--select-badge-remove-margin-left",background:"--select-badge-remove-bg",backgroundColor:"--select-badge-remove-bg",border:"--select-badge-remove-border",borderRadius:"--select-badge-remove-radius",color:"--select-badge-remove-color",fontSize:"--select-badge-remove-font-size",fontWeight:"--select-badge-remove-font-weight"}),this._applyStyleVariableMap(e.badgeRemoveIcon,{width:"--select-badge-remove-icon-size",height:"--select-badge-remove-icon-size",color:"--select-badge-remove-icon-color",fontSize:"--select-badge-remove-icon-font-size",lineHeight:"--select-badge-remove-icon-line-height",transform:"--select-badge-remove-icon-transform",opacity:"--select-badge-remove-icon-opacity"}),this._applyStyleVariableMap(e.badgeRemoveHover,{background:"--select-badge-remove-hover-bg",backgroundColor:"--select-badge-remove-hover-bg",color:"--select-badge-remove-hover-color",border:"--select-badge-remove-hover-border",boxShadow:"--select-badge-remove-hover-shadow",transform:"--select-badge-remove-hover-transform"}),this._applyStyleVariableMap(e.badgeRemoveActive,{background:"--select-badge-remove-active-bg",backgroundColor:"--select-badge-remove-active-bg",color:"--select-badge-remove-active-color",border:"--select-badge-remove-active-border",boxShadow:"--select-badge-remove-active-shadow",transform:"--select-badge-remove-active-transform"}),this._applyStyleVariableMap(e.groupHeader,{padding:"--select-group-header-padding",margin:"--select-group-header-margin",color:"--select-group-header-color",background:"--select-group-header-bg",backgroundColor:"--select-group-header-bg",border:"--select-group-header-border",borderBottom:"--select-group-header-border-bottom",borderRadius:"--select-group-header-border-radius",boxShadow:"--select-group-header-shadow",textAlign:"--select-group-header-text-align",fontSize:"--select-group-header-font-size",fontWeight:"--select-group-header-weight",textTransform:"--select-group-header-text-transform",letterSpacing:"--select-group-header-letter-spacing"}))}_resolveDropdownPlacement(){const e=this._config.dropdownPlacement?.mode??"bottom";if("bottom"===e||"top"===e)return e;const t=this._container.getBoundingClientRect(),i=window.innerHeight-t.bottom,n=window.getComputedStyle(this._dropdown),o=Number.parseFloat(n.maxHeight||"0");return i>=(Number.isFinite(o)&&o>0?Math.min(this._dropdown.scrollHeight,o):this._dropdown.scrollHeight)?"bottom":"top"}_syncDropdownPlacement(){this._dropdown&&(this._resolvedDropdownPlacement=this._resolveDropdownPlacement(),this._dropdown.setAttribute("data-placement",this._resolvedDropdownPlacement))}_syncDirectionConfig(){this.isConnected&&this.setAttribute("dir",this._config.direction??"ltr")}_setIconContent(e,t,i){const n=t&&t.trim()?t:i;e.innerHTML="",n.trim().startsWith("<")?e.innerHTML=n:e.textContent=n}_syncInputContainerMode(){if(!this._inputContainer||!this._input)return;const e="multi"===this._config.selection.mode;this._inputContainer.classList.toggle("input-container--multi",e),this._inputContainer.classList.toggle("input-container--single",!e),e?(this._input.style.flex="1 0 var(--select-multi-input-min-width, 96px)",this._input.style.width="auto",this._input.style.minWidth="var(--select-multi-input-min-width, 96px)"):(this._input.style.flex="1 1 auto",this._input.style.width="100%",this._input.style.minWidth="0"),this._syncMultiSelectDisplayConfig()}_syncMultiSelectDisplayConfig(){if(!this._inputContainer||!this._input)return;const e="multi"===this._config.selection.mode,t=this._config.multiSelectDisplay?.mode??"wrap",i=!1!==this._config.multiSelectDisplay?.dragScroll;if(!e)return this._inputContainer.removeAttribute("data-multi-scroll-mode"),this._inputContainer.removeAttribute("data-drag-scroll"),this._inputContainer.classList.remove("is-dragging-scroll"),this._inputContainer.style.removeProperty("--select-multi-input-max-height-config"),this._inputContainer.style.removeProperty("--select-multi-input-overflow-x-config"),this._inputContainer.style.removeProperty("--select-multi-input-overflow-y-config"),this._inputContainer.style.removeProperty("--select-multi-input-flex-wrap-config"),void this._inputContainer.style.removeProperty("--select-multi-input-align-content-config");const n=this._config.multiSelectDisplay?.maxHeight,o="160px";let s=n??"none",r=this._config.multiSelectDisplay?.overflowX??"hidden",a=this._config.multiSelectDisplay?.overflowY??"hidden",l="wrap",c="flex-start";"vertical"===t?(s=n??o,a=this._config.multiSelectDisplay?.overflowY??"auto"):"horizontal"===t&&(s=n??o,r=this._config.multiSelectDisplay?.overflowX??"auto",a=this._config.multiSelectDisplay?.overflowY??"hidden",l="nowrap",c="center"),this._inputContainer.setAttribute("data-multi-scroll-mode",t),this._inputContainer.setAttribute("data-drag-scroll",String(i&&"horizontal"===t)),this._inputContainer.style.setProperty("--select-multi-input-max-height-config",s),this._inputContainer.style.setProperty("--select-multi-input-overflow-x-config",r),this._inputContainer.style.setProperty("--select-multi-input-overflow-y-config",a),this._inputContainer.style.setProperty("--select-multi-input-flex-wrap-config",l),this._inputContainer.style.setProperty("--select-multi-input-align-content-config",c)}_canUseHorizontalMultiScroll(e){return"multi"===this._config.selection.mode&&("horizontal"===(this._config.multiSelectDisplay?.mode??"wrap")&&(!1!==this._config.multiSelectDisplay?.dragScroll&&(!e||!e.closest(".dropdown-arrow-container, .clear-control-button, .badge-remove")&&!e.matches(".select-input"))))}_isScrollableMultiSelectMode(){if("multi"!==this._config.selection.mode)return!1;const e=this._config.multiSelectDisplay?.mode??"wrap";return"vertical"===e||"horizontal"===e}_isPointerOnInputScrollbar(e){if(!this._isScrollableMultiSelectMode())return!1;const t=this._inputContent.getBoundingClientRect(),i=this._inputContent.offsetWidth-this._inputContent.clientWidth,n=this._inputContent.offsetHeight-this._inputContent.clientHeight;return i>0&&e.clientX>=t.right-i&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom||n>0&&e.clientY>=t.bottom-n&&e.clientY<=t.bottom&&e.clientX>=t.left&&e.clientX<=t.right}_beginMultiScrollDrag(e){const t=this._inputContent;this._multiScrollDrag.active=!0,this._multiScrollDrag.moved=!1,this._multiScrollDrag.pointerId=e.pointerId,this._multiScrollDrag.startX=e.clientX,this._multiScrollDrag.startScrollLeft=t.scrollLeft,this._inputContainer.classList.add("is-dragging-scroll");try{t.setPointerCapture(e.pointerId)}catch(e){}}_updateMultiScrollDrag(e){if(!this._multiScrollDrag.active||this._multiScrollDrag.pointerId!==e.pointerId)return;const t=e.clientX-this._multiScrollDrag.startX;Math.abs(t)>3&&(this._multiScrollDrag.moved=!0),this._inputContent.scrollLeft=this._multiScrollDrag.startScrollLeft-t}_endMultiScrollDrag(e){if(this._multiScrollDrag.active&&(null==e||this._multiScrollDrag.pointerId===e)){try{this._multiScrollDrag.pointerId>=0&&this._inputContent.releasePointerCapture(this._multiScrollDrag.pointerId)}catch(e){}this._multiScrollDrag.active=!1,this._multiScrollDrag.pointerId=-1,this._inputContainer.classList.remove("is-dragging-scroll")}}_createInput(){const e=document.createElement("input");if(e.setAttribute("part","input"),e.type="text",e.className="select-input",e.id=`${this._uniqueId}-input`,e.placeholder=this._config.placeholder||"Select an option...",e.disabled=!this._config.enabled,e.readOnly=!this._config.searchable,e.style.all="unset",e.style.display="block",e.style.flex="1 1 auto",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.minInlineSize="0",e.style.minHeight="0",e.style.padding="0",e.style.margin="0",e.style.border="0",e.style.background="transparent",e.style.boxSizing="border-box",e.style.outline="none",e.style.font="inherit",e.style.fontFamily="inherit",e.style.lineHeight="inherit",e.style.color="inherit",e.style.alignSelf="center",e.style.appearance="none",e.style.webkitAppearance="none",e.style.boxShadow="none",e.style.borderRadius="0",e.style.overflow="hidden",e.style.textOverflow="ellipsis",e.style.whiteSpace="nowrap",e.style.cursor=this._config.searchable?"text":"default",e.addEventListener("focus",()=>{this._config.searchable&&(e.readOnly=!1)}),this._config.styles.classNames?.input&&(e.className+=" "+this._config.styles.classNames.input),this._config.styles.input){const t={...this._config.styles.input};delete t.background,delete t.backgroundColor,delete t.border,delete t.borderColor,delete t.borderStyle,delete t.borderWidth,delete t.borderRadius,delete t.boxShadow,delete t.padding,delete t.height,delete t.minHeight,delete t.maxHeight,Object.assign(e.style,t)}return e.setAttribute("aria-haspopup","listbox"),e}_createDropdown(){const e=document.createElement("div");return e.className="select-dropdown",e.setAttribute("part","listbox"),e.style.display="none",this._config.styles.classNames?.dropdown&&(e.className+=" "+this._config.styles.classNames.dropdown),this._config.styles.dropdown&&Object.assign(e.style,this._config.styles.dropdown),e}_createOptionsContainer(){const e=document.createElement("div");return e.className=`options-container ${EnhancedSelect._MIRRORED_STYLES_SCOPE_CLASS}`,e}_createLiveRegion(){const e=document.createElement("div");return e.setAttribute("role","status"),e.setAttribute("aria-live","polite"),e.setAttribute("aria-atomic","true"),e.style.cssText="position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0;",e}_createErrorDescription(){const e=document.createElement("div");return e.id=`${this._uniqueId}-error`,e.style.cssText="position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0;",e}_createArrowContainer(){const e=document.createElement("div");e.className="dropdown-arrow-container",e.innerHTML='\n <slot name="arrow">\n <svg class="dropdown-arrow" part="arrow" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">\n <path d="M4 6L8 10L12 6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n </slot>\n ';const t=e.querySelector('slot[name="arrow"]');return t?.addEventListener("slotchange",()=>{t.assignedElements({flatten:!0}).length>0?this.setAttribute("data-custom-arrow","true"):this.removeAttribute("data-custom-arrow")}),e}_createClearControl(){const e=document.createElement("button");e.type="button",e.className="clear-control-button",e.setAttribute("part","clear-button");const t=document.createElement("span");return t.className="clear-control-icon",t.setAttribute("part","clear-icon"),this._config.clearControl.icon?t.textContent=this._config.clearControl.icon:t.innerHTML='<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 4L4 12M4 4L12 12" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',e.setAttribute("aria-label",this._config.clearControl.ariaLabel||"Clear selection and search"),e.appendChild(t),this._clearControlIcon=t,e}_assembleDOM(){this._inputContent.appendChild(this._input),this._inputContainer.appendChild(this._inputContent),this._clearControl&&this._inputContainer.appendChild(this._clearControl),this._arrowContainer&&this._inputContainer.appendChild(this._arrowContainer),this._container.appendChild(this._inputContainer),this._dropdown.appendChild(this._optionsContainer),this._container.appendChild(this._dropdown),this._shadow.appendChild(this._container),this._liveRegion&&this._shadow.appendChild(this._liveRegion),this._errorDescription&&this._shadow.appendChild(this._errorDescription);const e=`${this._uniqueId}-listbox`;this._dropdown.id=e,this._input.setAttribute("aria-owns",e),this._syncInputContainerMode(),this._syncClearControlState()}_initializeStyles(){const e=document.createElement("style");e.textContent='\n /* ═══════════════════════════════════════════════════════════════════════════\n ELEGANT SELECT COMPONENT — Refined Design System\n Formal aesthetics with sophisticated microinteractions\n ═══════════════════════════════════════════════════════════════════════════ */\n \n :host {\n --select-primary: #1a1a2e;\n --select-primary-light: #16213e;\n --select-accent: #0f3460;\n --select-accent-hover: #e94560;\n --select-surface: #ffffff;\n --select-surface-elevated: rgba(0, 0, 0, 0.04);\n --select-border: #e1e5eb;\n --select-border-focus: #0f3460;\n --select-text: #1a1a2e;\n --select-text-muted: #6b7280;\n --select-text-placeholder: #9ca3af;\n --select-shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.04);\n --select-shadow-md: 0 4px 12px rgba(0, 0, 0, 0.08);\n --select-shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.12);\n --select-shadow-focus: 0 0 0 3px rgba(15, 52, 96, 0.12);\n --select-radius-sm: 6px;\n --select-radius-md: 10px;\n --select-radius-lg: 14px;\n --select-transition-fast: 150ms cubic-bezier(0.4, 0, 0.2, 1);\n --select-transition-smooth: 250ms cubic-bezier(0.4, 0, 0.2, 1);\n --select-transition-bounce: 350ms cubic-bezier(0.34, 1.56, 0.64, 1);\n --select-badge-animation: badgeEnter 300ms cubic-bezier(0.34, 1.56, 0.64, 1) forwards;\n --select-badge-enter-from-opacity: 0;\n --select-badge-enter-from-transform: scale(0.8) translateY(-4px);\n --select-badge-enter-to-opacity: 1;\n --select-badge-enter-to-transform: scale(1) translateY(0);\n --select-badge-active-transform: scale(0.98);\n --select-badge-hover-transform: scale(1.02);\n --select-badge-letter-spacing: 0.01em;\n --select-badge-hover-shadow: var(--select-shadow-md), inset 0 1px 0 rgba(255, 255, 255, 0.15);\n --select-badge-remove-icon-size: 10px;\n --select-badge-remove-icon-color: currentColor;\n --select-badge-remove-icon-font-size: inherit;\n --select-badge-remove-icon-line-height: 1;\n --select-badge-remove-icon-transform: none;\n --select-badge-remove-icon-opacity: 1;\n --select-badge-remove-focus-outline: 2px solid rgba(255, 255, 255, 0.5);\n --select-badge-remove-focus-offset: 1px;\n --select-badge-remove-hover-transform: scale(1.15) rotate(90deg);\n --select-badge-remove-active-transform: scale(0.95) rotate(90deg);\n --select-input-hover-border: var(--select-border-focus);\n --select-input-hover-shadow: var(--select-shadow-sm), 0 0 0 1px rgba(15, 52, 96, 0.05);\n --select-input-font-weight: 450;\n --select-input-letter-spacing: 0.01em;\n --select-input-disabled-opacity: 0.6;\n --select-input-overflow-x: hidden;\n --select-input-align-items: center;\n --select-input-align-content: center;\n --select-input-align-self: center;\n --select-multi-input-max-height: 160px;\n --select-multi-input-overflow-x: hidden;\n --select-multi-input-overflow-y: auto;\n --select-multi-input-flex-wrap: wrap;\n --select-multi-input-align-content: flex-start;\n --select-multi-input-horizontal-height: var(--select-input-min-height, 48px);\n --select-multi-input-horizontal-input-flex: 0 0 var(--select-multi-input-min-width, 96px);\n --select-multi-input-horizontal-cursor: grab;\n --select-multi-input-horizontal-active-cursor: grabbing;\n --select-multi-input-end-gap: 12px;\n --select-multi-separator-inset-block: 10px;\n --select-multi-separator-height: auto;\n --select-multi-action-surface-bg: var(--select-input-bg, var(--select-surface));\n --select-multi-action-divider: 1px solid var(--select-border);\n --select-separator-width: 1px;\n --select-separator-inset-block: 10px;\n --select-separator-height: auto;\n --select-separator-display: block;\n --select-separator-opacity: 0.6;\n --select-separator-active-opacity: 1;\n --select-separator-position: var(--select-arrow-width, 42px);\n --select-separator-position-with-clear: calc(var(--select-arrow-right-with-clear, 34px) + var(--select-arrow-width, 42px));\n --select-separator-dark-bg: linear-gradient(\n to bottom,\n transparent 0%,\n var(--select-border) 20%,\n var(--select-border) 80%,\n transparent 100%\n );\n --select-arrow-open-transform: rotate(180deg);\n --select-clear-button-hover-transform: translateY(-50%) scale(1.1);\n --select-clear-button-active-transform: translateY(-50%) scale(0.95);\n --select-clear-button-focus-offset: 2px;\n --select-clear-icon-size: 14px;\n --select-dropdown-top: calc(100% + 6px);\n --select-dropdown-bottom: calc(100% + 6px);\n --select-dropdown-animation: dropdownEnter 200ms cubic-bezier(0.4, 0, 0.2, 1) forwards;\n --select-dropdown-enter-from-opacity: 0;\n --select-dropdown-enter-from-transform: translateY(-8px) scale(0.98);\n --select-dropdown-enter-to-opacity: 1;\n --select-dropdown-enter-to-transform: translateY(0) scale(1);\n --select-dropdown-top-transform-origin: bottom center;\n --select-dropdown-top-enter-from-transform: translateY(8px) scale(0.98);\n --select-dropdown-padding: 6px;\n --select-dropdown-scroll-behavior: smooth;\n --select-dropdown-transform-origin: top center;\n --select-scrollbar-width: 6px;\n --select-scrollbar-thumb-radius: 3px;\n --select-option-hover-enabled: 1;\n --select-option-hover-transform: none;\n --select-option-font-weight: 450;\n --select-option-margin: 2px 0;\n --select-input-font-size: inherit;\n --select-input-font-weight: 400;\n --select-multi-container-padding: 6px;\n --select-input-font-size: inherit;\n --select-input-font-weight: 400;\n --select-multi-container-padding: 6px;\n --select-option-disabled-opacity: 0.5;\n --select-option-disabled-cursor: not-allowed;\n --select-option-active-outline: none;\n --select-option-active-outline-offset: -2px;\n --select-option-selected-active-bg: var(--select-option-selected-hover-bg, var(--select-option-selected-bg, linear-gradient(135deg, rgba(15, 52, 96, 0.12) 0%, rgba(15, 52, 96, 0.06) 100%)));\n --select-option-selected-active-color: var(--select-option-selected-hover-color, var(--select-option-selected-color, var(--select-accent)));\n --select-option-selected-active-border: var(--select-option-selected-hover-border, var(--select-option-selected-border, var(--select-option-border, none)));\n --select-option-selected-active-shadow: var(--select-option-active-shadow, none);\n --select-option-selected-active-transform: var(--select-option-active-transform, none);\n --select-option-selected-active-outline: none;\n --select-option-selected-active-outline-offset: -2px;\n --select-option-selected-indicator-display: block;\n --select-option-selected-indicator-width: 3px;\n --select-option-selected-indicator-height: 60%;\n --select-option-selected-indicator-bg: var(--select-accent);\n --select-option-selected-indicator-radius: 0 2px 2px 0;\n --select-option-selected-indicator-left: 0;\n --select-option-selected-indicator-top: 50%;\n --select-option-selected-indicator-transform: translateY(-50%);\n --select-option-selected-indicator-animation: selectedIndicator 200ms cubic-bezier(0.34, 1.56, 0.64, 1) forwards;\n --select-option-selected-indicator-from-height: 0;\n --select-option-selected-indicator-to-height: 60%;\n --select-option-selected-indicator-from-opacity: 0;\n --select-option-selected-indicator-to-opacity: 1;\n --select-option-pressed-transform: none;\n --select-option-selected-pressed-transform: none;\n --select-button-hover-transform: translateY(-1px);\n --select-button-active-transform: translateY(0) scale(0.98);\n --select-button-font-weight: 550;\n --select-button-letter-spacing: 0.02em;\n --select-spinner-animation: spin 0.8s cubic-bezier(0.4, 0, 0.2, 1) infinite;\n --select-searching-spinner-active-color: var(--select-accent);\n --select-badge-remove-margin-left: 2px;\n --select-badge-remove-radius: 50%;\n --select-badge-remove-font-weight: 600;\n --select-empty-gap: 8px;\n --select-searching-gap: 8px;\n --select-searching-spinner-size: 24px;\n --select-searching-spinner-border: 2px solid var(--select-border);\n --select-searching-spinner-animation: var(--select-spinner-animation);\n --select-group-header-separator-margin-top: 0;\n --select-group-header-separator-padding-top: 0;\n --select-group-header-separator-border-top: none;\n --select-reduced-motion-duration: 0.01ms;\n --select-reduced-motion-iteration-count: 1;\n --select-high-contrast-border-width: 2px;\n --select-high-contrast-indicator-width: 4px;\n --select-high-contrast-focus-outline-width: 3px;\n --select-high-contrast-focus-outline-color: Highlight;\n --select-touch-target-min-height: 44px;\n --select-badge-dark-bg: linear-gradient(135deg, var(--select-accent) 0%, #4f46e5 100%);\n --select-host-z-index: auto;\n --select-host-open-z-index: var(--select-dropdown-z-index, 1000);\n --select-ancestor-open-z-index: var(--select-host-open-z-index, var(--select-dropdown-z-index, 1000));\n \n display: block;\n position: relative;\n z-index: var(--select-host-z-index, auto);\n width: var(--select-width, 100%);\n height: var(--select-height, auto);\n font-family: var(--select-font-family, inherit);\n font-size: var(--select-font-size, inherit);\n line-height: var(--select-line-height, inherit);\n color: var(--select-color, inherit);\n }\n\n :host([data-open="true"]) {\n z-index: var(--select-host-open-z-index, var(--select-dropdown-z-index, 1000));\n }\n\n :host([dir="ltr"]) {\n direction: ltr;\n }\n\n :host([dir="rtl"]) {\n direction: rtl;\n }\n\n /* ─────────────────────────────────────────────────────────────────────────\n Selection Badges — Refined pill design with elegant interactions\n ───────────────────────────────────────────────────────────────────────── */\n \n .selection-badge {\n display: inline-flex;\n align-items: center;\n gap: var(--select-badge-gap, 6px);\n flex: 0 1 auto;\n width: var(--select-badge-width, auto);\n min-width: var(--select-badge-min-width, 0);\n height: var(--select-badge-height, auto);\n min-height: var(--select-badge-min-height, 26px);\n padding: var(--select-badge-padding, 4px 10px 4px 12px);\n margin: var(--select-badge-margin, 3px);\n background: var(--select-badge-bg, linear-gradient(135deg, var(--select-accent) 0%, var(--select-primary-light) 100%));\n color: var(--select-badge-color, #ffffff);\n border: var(--select-badge-border, none);\n border-radius: var(--select-badge-border-radius, 999px);\n box-shadow: var(--select-badge-shadow, var(--select-shadow-sm), inset 0 1px 0 rgba(255, 255, 255, 0.1));\n box-sizing: border-box;\n font-size: var(--select-badge-font-size, 0.8667em);\n font-weight: var(--select-badge-font-weight, 500);\n line-height: var(--select-badge-line-height, 1.2);\n letter-spacing: var(--select-badge-letter-spacing);\n max-width: var(--select-badge-max-width, 100%);\n overflow: hidden;\n transform: scale(1);\n transition: \n transform var(--select-transition-bounce),\n box-shadow var(--select-transition-fast),\n background var(--select-transition-fast);\n animation: var(--select-badge-animation);\n }\n \n @keyframes badgeEnter {\n 0% {\n opacity: var(--select-badge-enter-from-opacity);\n transform: var(--select-badge-enter-from-transform);\n }\n 100% {\n opacity: var(--select-badge-enter-to-opacity);\n transform: var(--select-badge-enter-to-transform);\n }\n }\n \n .selection-badge:hover {\n background: var(--select-badge-hover-bg, var(--select-badge-bg, linear-gradient(135deg, var(--select-accent) 0%, var(--select-primary-light) 100%)));\n color: var(--select-badge-hover-color, var(--select-badge-color, #ffffff));\n border: var(--select-badge-hover-border, var(--select-badge-border, none));\n box-shadow: var(--select-badge-hover-shadow);\n transform: var(--select-badge-hover-transform);\n }\n\n .selection-badge:active {\n background: var(--select-badge-active-bg, var(--select-badge-hover-bg, var(--select-badge-bg, linear-gradient(135deg, var(--select-accent) 0%, var(--select-primary-light) 100%))));\n color: var(--select-badge-active-color, var(--select-badge-hover-color, var(--select-badge-color, #ffffff)));\n border: var(--select-badge-active-border, var(--select-badge-hover-border, var(--select-badge-border, none)));\n box-shadow: var(--select-badge-active-shadow, var(--select-badge-hover-shadow));\n transform: var(--select-badge-active-transform);\n }\n\n .selection-badge-label {\n display: block;\n min-width: 0;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n color: var(--select-badge-label-color, inherit);\n font-size: var(--select-badge-label-font-size, inherit);\n font-weight: var(--select-badge-label-font-weight, inherit);\n line-height: var(--select-badge-label-line-height, var(--select-badge-line-height, 1.2));\n letter-spacing: var(--select-badge-label-letter-spacing, inherit);\n text-align: var(--select-badge-label-text-align, start);\n }\n\n .badge-remove {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: var(--select-badge-remove-size, 18px);\n height: var(--select-badge-remove-size, 18px);\n min-width: var(--select-badge-remove-min-width, var(--select-badge-remove-size, 18px));\n min-height: var(--select-badge-remove-min-height, var(--select-badge-remove-size, 18px));\n padding: 0;\n margin-left: var(--select-badge-remove-margin-left);\n background: var(--select-badge-remove-bg, rgba(255, 255, 255, 0.2));\n border: var(--select-badge-remove-border, none);\n border-radius: var(--select-badge-remove-radius);\n color: var(--select-badge-remove-color, #ffffff);\n font-size: var(--select-badge-remove-font-size, 0.7333em);\n font-weight: var(--select-badge-remove-font-weight);\n line-height: 1;\n cursor: pointer;\n flex: 0 0 auto;\n transition: \n background var(--select-transition-fast),\n color var(--select-transition-fast),\n border-color var(--select-transition-fast),\n box-shadow var(--select-transition-fast),\n transform var(--select-transition-bounce);\n }\n\n .badge-remove-icon {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: var(--select-badge-remove-icon-size, 10px);\n height: var(--select-badge-remove-icon-size, 10px);\n color: var(--select-badge-remove-icon-color, currentColor);\n font-size: var(--select-badge-remove-icon-font-size, inherit);\n line-height: var(--select-badge-remove-icon-line-height, 1);\n transform: var(--select-badge-remove-icon-transform, none);\n opacity: var(--select-badge-remove-icon-opacity, 1);\n pointer-events: none;\n }\n\n .badge-remove-icon svg {\n width: 100%;\n height: 100%;\n display: block;\n }\n \n .badge-remove:hover {\n background: var(--select-badge-remove-hover-bg, rgba(233, 69, 96, 0.9));\n color: var(--select-badge-remove-hover-color, var(--select-badge-remove-color, #ffffff));\n border: var(--select-badge-remove-hover-border, var(--select-badge-remove-border, none));\n box-shadow: var(--select-badge-remove-hover-shadow, none);\n transform: var(--select-badge-remove-hover-transform);\n }\n\n .badge-remove:focus-visible {\n outline: var(--select-badge-remove-focus-outline);\n outline-offset: var(--select-badge-remove-focus-offset);\n }\n \n .badge-remove:active {\n background: var(--select-badge-remove-active-bg, var(--select-badge-remove-hover-bg, rgba(233, 69, 96, 0.9)));\n color: var(--select-badge-remove-active-color, var(--select-badge-remove-hover-color, var(--select-badge-remove-color, #ffffff)));\n border: var(--select-badge-remove-active-border, var(--select-badge-remove-hover-border, var(--select-badge-remove-border, none)));\n box-shadow: var(--select-badge-remove-active-shadow, var(--select-badge-remove-hover-shadow, none));\n transform: var(--select-badge-remove-active-transform);\n }\n\n :host([dir="rtl"]) .badge-remove {\n margin-left: 0;\n margin-right: var(--select-badge-remove-margin-left);\n }\n \n /* ─────────────────────────────────────────────────────────────────────────\n Input Container — Sophisticated control shell\n ───────────��───────────────────────────────────────────────────────────── */\n \n .select-container {\n position: relative;\n width: 100%;\n }\n \n .input-container {\n position: relative;\n width: 100%;\n display: flex;\n align-items: var(--select-input-align-items, center);\n flex-wrap: nowrap;\n justify-content: var(--select-input-justify-content, flex-start);\n gap: var(--select-input-gap, 6px);\n padding: var(--select-input-padding, 10px 52px 10px 14px);\n height: var(--select-input-height, auto);\n min-height: var(--select-input-min-height, 48px);\n max-height: var(--select-input-max-height, 160px);\n overflow: hidden;\n padding: var(--select-multi-container-padding, 6px);\n align-content: var(--select-input-align-content, center);\n text-align: var(--select-input-text-align, start);\n background: var(--select-input-bg, var(--select-surface));\n font-size: var(--select-input-font-size, inherit);\n font-weight: var(--select-input-font-weight, 400);\n font-weight: var(--select-input-font-weight, 400);\n border: var(--select-input-border, 1.5px solid var(--select-border));\n border-radius: var(--select-input-border-radius, var(--select-radius-md));\n box-shadow: var(--select-shadow-sm);\n box-sizing: border-box;\n transition: \n border-color var(--select-transition-fast),\n box-shadow var(--select-transition-smooth),\n transform var(--select-transition-fast);\n }\n\n .input-content {\n position: relative;\n display: flex;\n flex: 1 1 auto;\n width: 100%;\n min-width: 0;\n min-height: 0;\n align-self: stretch;\n align-items: var(--select-input-align-items, center);\n align-content: var(--select-input-align-content, center);\n justify-content: var(--select-input-justify-content, flex-start);\n flex-wrap: nowrap;\n gap: var(--select-input-gap, 6px);\n overflow-x: var(--select-input-overflow-x, hidden);\n overflow-y: var(--select-input-overflow-y, hidden);\n scrollbar-width: thin;\n box-sizing: border-box;\n }\n \n .input-container:hover {\n border-color: var(--select-input-hover-border);\n box-shadow: var(--select-input-hover-shadow);\n }\n\n .input-container.input-container--single {\n flex-wrap: nowrap;\n align-content: center;\n }\n\n .input-container.input-container--multi {\n max-height: var(--select-multi-input-max-height, var(--select-multi-input-max-height-config, var(--select-input-max-height, 160px)));\n --select-multi-action-area-width: var(--select-arrow-width, 42px);\n }\n\n .input-container.input-container--multi .input-content {\n flex: 1 1 calc(100% - var(--select-multi-action-area-width, var(--select-arrow-width, 42px)));\n width: calc(100% - var(--select-multi-action-area-width, var(--select-arrow-width, 42px)));\n max-width: calc(100% - var(--select-multi-action-area-width, var(--select-arrow-width, 42px)));\n flex-wrap: var(--select-multi-input-flex-wrap, var(--select-multi-input-flex-wrap-config, wrap));\n align-content: var(--select-multi-input-align-content, var(--select-multi-input-align-content-config, flex-start));\n overflow-x: var(--select-multi-input-overflow-x, var(--select-multi-input-overflow-x-config, hidden));\n overflow-y: var(--select-multi-input-overflow-y, var(--select-multi-input-overflow-y-config, auto));\n padding-inline-end: var(--select-multi-input-end-gap, 12px);\n }\n\n .input-container.input-container--multi .input-content .selection-badge {\n flex: 0 0 auto;\n }\n\n .input-container.input-container--multi.has-clear-control .input-content {\n --select-multi-action-area-width: calc(var(--select-arrow-right-with-clear, 34px) + var(--select-arrow-width, 42px));\n }\n\n .input-container.input-container--multi::after {\n top: var(--select-multi-separator-inset-block, var(--select-separator-inset-block, 10px));\n bottom: var(--select-multi-separator-inset-block, var(--select-separator-inset-block, 10px));\n height: var(--select-multi-separator-height, auto);\n }\n\n .input-container.input-container--multi[data-multi-scroll-mode="horizontal"] {\n align-items: stretch;\n height: var(--select-multi-input-horizontal-height, var(--select-input-min-height, 48px));\n min-height: var(--select-multi-input-horizontal-height, var(--select-input-min-height, 48px));\n max-height: var(--select-multi-input-horizontal-height, var(--select-input-min-height, 48px));\n overflow: hidden;\n }\n\n .input-container.input-container--multi[data-multi-scroll-mode="horizontal"] .input-content {\n flex: 1 1 100%;\n width: 100%;\n max-width: 100%;\n min-height: 0;\n height: 100%;\n cursor: var(--select-multi-input-horizontal-cursor, grab);\n align-items: center;\n align-content: center;\n flex-wrap: nowrap;\n overflow-y: hidden;\n overscroll-behavior-x: contain;\n overscroll-behavior-y: none;\n padding-inline-end: 0;\n scroll-padding-inline-end: var(--select-multi-action-area-width, var(--select-arrow-width, 42px));\n }\n\n .input-container.input-container--multi[data-multi-scroll-mode="horizontal"].has-clear-control .input-content {\n --select-multi-action-area-width: calc(var(--select-arrow-right-with-clear, 34px) + var(--select-arrow-width, 42px));\n }\n\n .input-container.input-container--multi[data-multi-scroll-mode="horizontal"]::after {\n display: none;\n }\n\n .input-container.input-container--multi[data-multi-scroll-mode="horizontal"].is-dragging-scroll .input-content {\n cursor: var(--select-multi-input-horizontal-active-cursor, grabbing);\n user-select: none;\n }\n\n .input-container.input-container--multi[data-multi-scroll-mode="horizontal"] .selection-badge {\n flex: 0 0 auto;\n margin-top: 0;\n margin-bottom: 0;\n }\n\n .input-container.input-container--multi[data-multi-scroll-mode="horizontal"] .input-content > .select-input,\n .input-container.input-container--multi[data-multi-scroll-mode="horizontal"] .input-content > input.select-input,\n .input-container.input-container--multi[data-multi-scroll-mode="horizontal"] .input-content > .select-input[type="text"] {\n flex: var(--select-multi-input-horizontal-input-flex, 0 0 var(--select-multi-input-min-width, 96px));\n }\n\n .input-container.input-container--multi[data-multi-scroll-mode="horizontal"] .dropdown-arrow-container {\n background: var(--select-multi-action-surface-bg, var(--select-input-bg, var(--select-surface)));\n border-left: var(--select-multi-action-divider, 1px solid var(--select-border));\n z-index: 4;\n }\n\n .input-container.input-container--multi[data-multi-scroll-mode="horizontal"] .dropdown-arrow-container.with-clear-control {\n right: var(--select-arrow-right-with-clear, 34px);\n }\n\n :host([dir="rtl"]) .input-container.input-container--multi[data-multi-scroll-mode="horizontal"] .dropdown-arrow-container {\n border-left: none;\n border-right: var(--select-multi-action-divider, 1px solid var(--select-border));\n }\n\n :host([dir="rtl"]) .input-container.input-container--multi[data-multi-scroll-mode="horizontal"] .dropdown-arrow-container.with-clear-control {\n right: auto;\n left: var(--select-arrow-right-with-clear, 34px);\n }\n\n .input-container.input-container--multi[data-multi-scroll-mode="horizontal"] .clear-control-button {\n background: var(--select-multi-action-surface-bg, var(--select-input-bg, var(--select-surface)));\n z-index: 4;\n }\n \n .input-container:focus-within {\n border-color: var(--select-input-focus-border, var(--select-border-focus));\n box-shadow: var(--select-shadow-focus), var(--select-shadow-sm);\n }\n \n /* Elegant separator line before arrow */\n .input-container::after {\n content: \'\';\n display: var(--select-separator-display, block);\n position: absolute;\n top: var(--select-separator-inset-block, 10px);\n bottom: var(--select-separator-inset-block, 10px);\n right: var(--select-separator-position, var(--select-arrow-width, 42px));\n width: var(--select-separator-width, 1px);\n height: var(--select-separator-height, auto);\n background: var(--select-separator-bg, linear-gradient(\n to bottom,\n transparent 0%,\n var(--select-border) 20%,\n var(--select-border) 80%,\n transparent 100%\n ));\n pointer-events: none;\n z-index: 1;\n opacity: var(--select-separator-opacity);\n transition: opacity var(--select-transition-fast);\n }\n \n .input-container:hover::after,\n .input-container:focus-within::after {\n opacity: var(--select-separator-active-opacity);\n }\n\n :host([dir="rtl"]) .input-container::after {\n right: auto;\n left: var(--select-separator-position, var(--select-arrow-width, 42px));\n }\n \n /* ─────────────────────────────────────────────────────────────────────────\n Dropdown Arrow — Smooth rotation with refined styling\n ───────────────────────────────────────────────────────────────────────── */\n \n .dropdown-arrow-container {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n width: var(--select-arrow-width, var(--select-arrow-size, 42px));\n height: var(--select-arrow-height, var(--select-arrow-size, auto));\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n border-radius: var(--select-arrow-border-radius, 0 var(--select-radius-md) var(--select-radius-md) 0);\n z-index: 2;\n transition: background-color var(--select-transition-fast);\n }\n\n .input-container.has-clear-control {\n padding: var(--select-input-padding-with-clear, 10px 84px 10px 14px);\n }\n\n .input-container.has-clear-control::after {\n right: var(--select-separator-position-with-clear, calc(var(--select-arrow-right-with-clear, 34px) + var(--select-arrow-width, 42px)));\n }\n\n .dropdown-arrow-container.with-clear-control {\n right: var(--select-arrow-right-with-clear, 34px);\n }\n\n :host([dir="rtl"]) .dropdown-arrow-container {\n right: auto;\n left: 0;\n border-radius: var(--select-arrow-border-radius-rtl, var(--select-radius-md) 0 0 var(--select-radius-md));\n }\n\n :host([dir="rtl"]) .input-container.has-clear-control::after {\n right: auto;\n left: var(--select-separator-position-with-clear, calc(var(--select-arrow-right-with-clear, 34px) + var(--select-arrow-width, 42px)));\n }\n\n :host([dir="rtl"]) .dropdown-arrow-container.with-clear-control {\n right: auto;\n left: var(--select-arrow-right-with-clear, 34px);\n }\n\n /* ─────────────────────────────────────────────────────────────────────────\n Clear Control — Minimal and elegant dismiss button\n ───────────────────────────────────────────────────────────────────────── */\n\n .clear-control-button {\n position: absolute;\n top: 50%;\n right: var(--select-clear-button-right, 8px);\n transform: translateY(-50%);\n width: var(--select-clear-button-size, 26px);\n height: var(--select-clear-button-size, 26px);\n border: var(--select-clear-button-border, none);\n border-radius: var(--select-clear-button-radius, 50%);\n background: var(--select-clear-button-bg, transparent);\n color: var(--select-clear-button-color, var(--select-text-muted));\n display: inline-flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n z-index: 3;\n transition: \n background var(--select-transition-fast),\n color var(--select-transition-fast),\n transform var(--select-transition-bounce);\n }\n\n .clear-control-button:hover {\n background: var(--select-clear-button-hover-bg, rgba(233, 69, 96, 0.1));\n color: var(--select-clear-button-hover-color, var(--select-accent-hover));\n transform: var(--select-clear-button-hover-transform);\n }\n \n .clear-control-button:active {\n transform: var(--select-clear-button-active-transform);\n }\n\n .clear-control-button:focus-visible {\n outline: var(--select-clear-button-focus-outline, 2px solid var(--select-border-focus));\n outline-offset: var(--select-clear-button-focus-offset);\n }\n\n .clear-control-button[hidden] {\n display: none;\n }\n\n :host([dir="rtl"]) .clear-control-button {\n right: auto;\n left: var(--select-clear-button-right, 8px);\n }\n\n .clear-control-icon {\n width: var(--select-clear-icon-size);\n height: var(--select-clear-icon-size);\n pointer-events: none;\n }\n \n .clear-control-icon svg {\n width: 100%;\n height: 100%;\n }\n \n .dropdown-arrow-container:hover {\n background-color: var(--select-arrow-hover-bg, rgba(15, 52, 96, 0.05));\n }\n\n :host([data-custom-arrow="true"]) .dropdown-arrow-container:hover {\n background-color: transparent;\n }\n \n .dropdown-arrow {\n width: var(--select-arrow-width, var(--select-arrow-size, 16px));\n height: var(--select-arrow-height, var(--select-arrow-size, 16px));\n color: var(--select-arrow-color, var(--select-text-muted));\n transition: \n transform var(--select-transition-smooth),\n color var(--select-transition-fast);\n transform-origin: center;\n }\n \n .dropdown-arrow path {\n stroke-width: var(--select-arrow-stroke-width, 1.5);\n }\n \n .dropdown-arrow-container:hover .dropdown-arrow {\n color: var(--select-arrow-hover, var(--select-arrow-hover-color, #667eea));\n }\n \n .dropdown-arrow.open {\n transform: var(--select-arrow-open-transform);\n }\n \n /* ─────────────────────────────────────────────────────────────────────────\n Input Field — Clean text entry\n ───────────────────────────────────────────────────────────────────────── */\n \n .input-container > .select-input,\n input.select-input,\n .select-input[type="text"] {\n display: block;\n flex: 1 1 auto;\n width: var(--select-input-width, 100%);\n max-width: 100%;\n min-width: var(--select-input-min-width, 0);\n min-inline-size: 0;\n min-height: 0;\n padding: var(--select-input-field-padding, 0) !important;\n margin: 0 !important;\n border: 0 !important;\n font-size: var(--select-input-font-size, inherit);\n line-height: var(--select-input-line-height, 1.5);\n color: var(--select-input-color, var(--select-text));\n background: transparent !important;\n box-sizing: border-box;\n outline: none !important;\n font-weight: var(--select-input-font-weight);\n letter-spacing: var(--select-input-letter-spacing);\n font-family: var(--select-input-font-family, inherit);\n font-style: var(--select-input-font-style, normal);\n align-self: var(--select-input-align-self, center);\n appearance: none !important;\n -webkit-appearance: none !important;\n box-shadow: none !important;\n border-radius: 0 !important;\n overflow: hidden;\n text-overflow: ellipsis;\n text-align: var(--select-input-text-align, inherit);\n white-space: nowrap;\n }\n \n .select-input::placeholder {\n color: var(--select-input-placeholder-color, var(--select-text-placeholder));\n font-weight: 400;\n }\n\n :host([dir="rtl"]) .input-container {\n padding: var(--select-input-padding-rtl, 10px 14px 10px 52px);\n }\n\n :host([dir="rtl"]) .input-container.has-clear-control {\n padding: var(--select-input-padding-with-clear-rtl, 10px 14px 10px 84px);\n }\n\n .input-container.input-container--multi > .select-input,\n .input-container.input-container--multi > input.select-input,\n .input-container.input-container--multi > .select-input[type="text"] {\n width: auto;\n min-width: var(--select-multi-input-min-width, 96px);\n flex: 1 0 var(--select-multi-input-min-width, 96px);\n }\n\n .input-container.input-container--single > .select-input,\n .input-container.input-container--single > input.select-input,\n .input-container.input-container--single > .select-input[type="text"] {\n width: var(--select-input-width, 100%);\n min-width: 0;\n flex: 1 1 auto;\n }\n \n .select-input:disabled {\n background-color: var(--select-disabled-bg, #f5f5f5);\n cursor: not-allowed;\n opacity: var(--select-input-disabled-opacity);\n }\n \n /* ─────────────────────────────────────────────────────────────────────────\n Dropdown Panel — Elegant floating container\n ───────────────────────────────────────────────────────────────────────── */\n \n .select-dropdown {\n position: absolute;\n scroll-behavior: var(--select-dropdown-scroll-behavior);\n top: var(--select-dropdown-top);\n bottom: auto;\n left: 0;\n right: 0;\n max-height: var(--select-dropdown-max-height, 320px);\n overflow: hidden;\n box-sizing: border-box;\n background: var(--select-dropdown-bg, var(--select-surface));\n border: 1px solid var(--select-dropdown-border, var(--select-border));\n border-radius: var(--select-dropdown-border-radius, var(--select-radius-lg));\n box-shadow: var(--select-dropdown-shadow, var(--select-shadow-lg));\n z-index: var(--select-dropdown-z-index, 1000);\n transform-origin: var(--select-dropdown-transform-origin);\n animation: var(--select-dropdown-animation);\n }\n\n .select-dropdown[data-placement="top"] {\n top: auto;\n bottom: var(--select-dropdown-bottom, calc(100% + 6px));\n transform-origin: var(--select-dropdown-top-transform-origin, bottom center);\n }\n\n .select-dropdown[data-placement="top"] {\n --select-dropdown-enter-from-transform: var(--select-dropdown-top-enter-from-transform, translateY(8px) scale(0.98));\n }\n \n @keyframes dropdownEnter {\n 0% {\n opacity: var(--select-dropdown-enter-from-opacity);\n transform: var(--select-dropdown-enter-from-transform);\n }\n 100% {\n opacity: var(--select-dropdown-enter-to-opacity);\n transform: var(--select-dropdown-enter-to-transform);\n }\n }\n \n .options-container {\n position: relative;\n max-height: var(--select-options-max-height, 320px);\n overflow: auto;\n box-sizing: border-box;\n padding: var(--select-options-padding, var(--select-dropdown-padding, 6px));\n background: var(--select-options-bg, var(--select-dropdown-bg, var(--select-surface)));\n \n /* Custom scrollbar styling */\n scrollbar-width: thin;\n scrollbar-color: var(--select-border) transparent;\n }\n \n .options-container::-webkit-scrollbar {\n width: var(--select-scrollbar-width);\n }\n \n .options-container::-webkit-scrollbar-track {\n background: transparent;\n }\n \n .options-container::-webkit-scrollbar-thumb {\n background: var(--select-border);\n border-radius: var(--select-scrollbar-thumb-radius);\n }\n \n .options-container::-webkit-scrollbar-thumb:hover {\n background: var(--select-text-muted);\n }\n\n /* ─────────────────────────────────────────────────────────────────────────\n Group Headers — Refined section dividers\n ───────────────────────────────────────────────────────────────────────── */\n\n .group-header {\n padding: var(--select-group-header-padding, 10px 12px 8px 12px);\n margin: var(--select-group-header-margin, 0 calc(var(--select-options-padding, 6px) * -1));\n font-weight: var(--select-group-header-weight, 600);\n color: var(--select-group-header-color, var(--select-text-muted));\n background: var(--select-group-header-bg, #f3f4f6);\n text-align: var(--select-group-header-text-align, left);\n font-size: var(--select-group-header-font-size, 0.7333em);\n text-transform: var(--select-group-header-text-transform, uppercase);\n letter-spacing: var(--select-group-header-letter-spacing, 0.08em);\n position: sticky;\n top: calc(var(--select-options-padding, 6px) * -1);\n left: 0;\n right: 0;\n z-index: 100;\n border: var(--select-group-header-border, none);\n border-bottom: var(--select-group-header-border-bottom, 1px solid rgba(0, 0, 0, 0.08));\n border-radius: var(--select-group-header-border-radius, 0);\n box-shadow: var(--select-group-header-shadow, 0 1px 2px rgba(0, 0, 0, 0.04));\n /* Force solid background to prevent option bleed-through */\n isolation: isolate;\n }\n \n .group-header:not(:first-child) {\n margin-top: calc(\n var(--select-group-header-separator-margin-top, 0px) +\n var(--select-group-header-separator-padding-top, 0px)\n );\n border-top: var(--select-group-header-separator-border-top);\n }\n\n /* ─────────────────────────────────────────────────────────────────────────\n Options — Elegant hover and selection states\n ───────────────────────────────────────────────────────────────────────── */\n\n .option {\n position: relative;\n padding: var(--select-option-padding, 10px 14px);\n cursor: pointer;\n color: var(--select-option-color, var(--select-text));\n background: var(--select-option-bg, transparent);\n border: var(--select-option-border, none);\n box-sizing: border-box;\n text-align: var(--select-option-text-align, start);\n transition: var(--select-option-transition, \n background var(--select-transition-fast),\n color var(--select-transition-fast),\n outline-color var(--select-transition-fast),\n box-shadow var(--select-transition-fast)\n );\n user-select: none;\n font-size: var(--select-option-font-size, inherit);\n font-weight: var(--select-option-font-weight);\n line-height: var(--select-option-line-height, 1.5);\n border-radius: var(--select-option-border-radius, var(--select-radius-sm));\n margin: var(--select-option-margin);\n }\n\n .option:hover:not(.disabled):not(.smilodon-option--disabled),\n .option.smilodon-option--disabled-hoverable:hover {\n background: var(--select-option-hover-bg, var(--select-surface-elevated));\n /* Hover decoration must not resize or translate the pointer hit target. */\n outline: var(--select-option-hover-border, none);\n outline-offset: -1px;\n color: var(--select-option-hover-color, var(--select-text));\n }\n\n .option.selected {\n background: var(--select-option-selected-bg, linear-gradient(135deg, rgba(15, 52, 96, 0.08) 0%, rgba(15, 52, 96, 0.04) 100%));\n border: var(--select-option-selected-border, var(--select-option-border, none));\n color: var(--select-option-selected-color, var(--select-accent));\n font-weight: var(--select-option-selected-weight, 550);\n }\n \n .option.selected::before {\n content: var(--select-option-selected-indicator-content, \'\');\n display: var(--select-option-selected-indicator-display, block);\n position: absolute;\n left: var(--select-option-selected-indicator-left);\n top: var(--select-option-selected-indicator-top);\n transform: var(--select-option-selected-indicator-transform);\n width: var(--select-option-selected-indicator-width);\n height: var(--select-option-selected-indicator-height);\n background: var(--select-option-selected-indicator-bg);\n border-radius: var(--select-option-selected-indicator-radius);\n animation: var(--select-option-selected-indicator-animation);\n }\n\n :host([dir="rtl"]) .option.selected::before {\n left: auto;\n right: var(--select-option-selected-indicator-right, var(--select-option-selected-indicator-left));\n border-radius: var(--select-option-selected-indicator-radius-rtl, 2px 0 0 2px);\n }\n \n @keyframes selectedIndicator {\n 0% {\n height: var(--select-option-selected-indicator-from-height);\n opacity: var(--select-option-selected-indicator-from-opacity);\n }\n 100% {\n height: var(--select-option-selected-indicator-to-height);\n opacity: var(--select-option-selected-indicator-to-opacity);\n }\n }\n\n .option.selected:hover {\n background: var(--select-option-selected-hover-bg, var(--select-option-selected-bg, linear-gradient(135deg, rgba(15, 52, 96, 0.12) 0%, rgba(15, 52, 96, 0.06) 100%)));\n outline: var(--select-option-selected-hover-border, var(--select-option-hover-border, none));\n outline-offset: -1px;\n color: var(--select-option-selected-hover-color, var(--select-option-selected-color, var(--select-accent)));\n }\n\n .option.active:not(.selected):not(.disabled):not(.smilodon-option--disabled),\n .option.active.smilodon-option--disabled-focusable:not(.selected) {\n background: var(--select-option-active-bg, var(--select-surface-elevated));\n color: var(--select-option-active-color, var(--select-option-hover-color, var(--select-option-color, var(--select-text))));\n border: var(--select-option-active-border, var(--select-option-hover-border, var(--select-option-border, none)));\n outline: var(--select-option-active-outline, none);\n outline-offset: var(--select-option-active-outline-offset);\n box-shadow: var(--select-option-active-shadow, none);\n transform: var(--select-option-active-transform, none);\n }\n\n .option.selected.active:not(.disabled):not(.smilodon-option--disabled),\n .option.selected.active.smilodon-option--disabled-focusable {\n background: var(--select-option-selected-active-bg, var(--select-option-selected-hover-bg, var(--select-option-selected-bg, linear-gradient(135deg, rgba(15, 52, 96, 0.12) 0%, rgba(15, 52, 96, 0.06) 100%))));\n color: var(--select-option-selected-active-color, var(--select-option-selected-hover-color, var(--select-option-selected-color, var(--select-accent))));\n border: var(--select-option-selected-active-border, var(--select-option-selected-hover-border, var(--select-option-selected-border, var(--select-option-border, none))));\n outline: var(--select-option-selected-active-outline, var(--select-option-active-outline, none));\n outline-offset: var(--select-option-selected-active-outline-offset);\n box-shadow: var(--select-option-selected-active-shadow, var(--select-option-active-shadow, none));\n transform: var(--select-option-selected-active-transform, var(--select-option-active-transform, none));\n }\n\n .option.disabled,\n .option.smilodon-option--disabled {\n background: var(--select-option-disabled-bg, var(--select-option-bg, transparent));\n color: var(--select-option-disabled-color, var(--select-text-muted));\n border: var(--select-option-disabled-border, var(--select-option-border, none));\n opacity: var(--select-option-disabled-opacity, 0.5);\n cursor: var(--select-option-disabled-cursor, not-allowed);\n pointer-events: var(--select-option-disabled-pointer-events, none);\n }\n\n .option.smilodon-option--disabled-interactive {\n pointer-events: auto;\n }\n\n .option:active:not(.selected):not(.disabled):not(.smilodon-option--disabled),\n .option.smilodon-option--disabled-selectable:active:not(.selected) {\n background: var(--select-option-pressed-bg, rgba(15, 52, 96, 0.08));\n transform: var(--select-option-pressed-transform);\n }\n\n .option.selected:active:not(.disabled):not(.smilodon-option--disabled),\n .option.selected.smilodon-option--disabled-selectable:active {\n transform: var(--select-option-selected-pressed-transform);\n }\n \n /* ─────────────────────────────────────────────────────────────────────────\n Load More & Busy States — Refined feedback indicators\n ───────────────────────────────────────────────────────────────────────── */\n \n .load-more-container {\n padding: var(--select-load-more-padding, 12px);\n text-align: center;\n }\n \n .load-more-button {\n padding: var(--select-button-padding, 10px 20px);\n border: var(--select-button-border, 1.5px solid var(--select-border));\n background: var(--select-button-bg, transparent);\n color: var(--select-button-color, var(--select-accent));\n border-radius: var(--select-button-border-radius, var(--select-radius-md));\n cursor: pointer;\n font-size: var(--select-button-font-size, 0.8667em);\n font-weight: var(--select-button-font-weight);\n letter-spacing: var(--select-button-letter-spacing);\n transition: \n background var(--select-transition-fast),\n border-color var(--select-transition-fast),\n color var(--select-transition-fast),\n transform var(--select-transition-bounce);\n }\n \n .load-more-button:hover {\n background: var(--select-button-hover-bg, var(--select-accent));\n border-color: var(--select-accent);\n color: var(--select-button-hover-color, white);\n transform: var(--select-button-hover-transform);\n }\n \n .load-more-button:active {\n transform: var(--select-button-active-transform);\n }\n \n .load-more-button:disabled {\n opacity: var(--select-button-disabled-opacity, 0.5);\n cursor: not-allowed;\n transform: none;\n }\n \n .busy-bucket {\n padding: var(--select-busy-padding, 20px);\n text-align: center;\n color: var(--select-busy-color, var(--select-text-muted));\n background: var(--select-busy-bg, transparent);\n font-size: var(--select-busy-font-size, 0.8667em);\n }\n \n .spinner {\n display: inline-block;\n width: var(--select-spinner-size, 22px);\n height: var(--select-spinner-size, 22px);\n border: var(--select-spinner-border, 2px solid var(--select-border));\n border-top-color: var(--select-spinner-active-color, var(--select-accent));\n border-radius: 50%;\n animation: var(--select-spinner-animation);\n }\n \n @keyframes spin {\n to { transform: rotate(360deg); }\n }\n \n .empty-state {\n padding: var(--select-empty-padding, 32px 24px);\n text-align: center;\n color: var(--select-empty-color, var(--select-text-muted));\n font-size: var(--select-empty-font-size, 0.9333em);\n background: var(--select-empty-bg, transparent);\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: var(--select-empty-gap);\n }\n \n .searching-state {\n padding: var(--select-searching-padding, 32px 24px);\n text-align: center;\n color: var(--select-searching-color, var(--select-accent));\n font-size: var(--select-searching-font-size, 0.9333em);\n background: var(--select-searching-bg, transparent);\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: var(--select-searching-gap);\n }\n \n .searching-state::before {\n content: \'\';\n width: var(--select-searching-spinner-size);\n height: var(--select-searching-spinner-size);\n border: var(--select-searching-spinner-border);\n border-top-color: var(--select-searching-spinner-active-color);\n border-radius: 50%;\n animation: var(--select-searching-spinner-animation);\n }\n \n /* ─────────────────────────────────────────────────────────────────────────\n Error States — Clear visual feedback\n ───────────────────────────────────────────────────────────────────────── */\n \n .select-input[aria-invalid="true"] {\n border-color: var(--select-error-border, #e94560);\n }\n \n .select-input[aria-invalid="true"]:focus {\n border-color: var(--select-error-border, #e94560);\n box-shadow: 0 0 0 3px var(--select-error-shadow, rgba(233, 69, 96, 0.15));\n }\n \n /* ──────────────────────────────────────────────────��──────────────────────\n Accessibility — Reduced motion & High contrast\n ───────────────────────────────────────────────────────────────────────── */\n \n @media (prefers-reduced-motion: reduce) {\n *,\n *::before,\n *::after {\n animation-duration: var(--select-reduced-motion-duration) !important;\n animation-iteration-count: var(--select-reduced-motion-iteration-count) !important;\n transition-duration: var(--select-reduced-motion-duration) !important;\n }\n \n .dropdown-arrow.open {\n transform: var(--select-arrow-open-transform);\n }\n }\n \n @media (prefers-contrast: high) {\n .select-input:focus {\n outline-width: var(--select-high-contrast-focus-outline-width);\n outline-color: var(--select-high-contrast-focus-outline-color);\n }\n \n .input-container {\n border-width: var(--select-high-contrast-border-width);\n }\n \n .option.selected::before {\n width: var(--select-high-contrast-indicator-width);\n }\n }\n \n /* Touch targets (WCAG 2.5.5) */\n .load-more-button,\n select-option {\n min-height: var(--select-touch-target-min-height);\n }\n \n /* ─────────────────────────────────────────────────────────────────────────\n Dark Mode — Elegant dark theme\n ───────────────────────────────────────────────────────────────────────── */\n \n :host(.dark-mode),\n :host([dark-mode]),\n :host([darkmode]),\n :host([data-theme="dark"]),\n :host([theme="dark"]),\n :host-context(.dark-mode),\n :host-context(.dark),\n :host-context([dark-mode]),\n :host-context([darkmode]),\n :host-context([data-theme="dark"]),\n :host-context([theme="dark"]) {\n --select-primary: #e5e5e5;\n --select-primary-light: #2a2a3e;\n --select-accent: #6366f1;\n --select-accent-hover: #f43f5e;\n --select-surface: var(--select-dark-bg, #1a1a2e);\n --select-surface-elevated: #252540;\n --select-border: var(--select-dark-border, #3f3f5a);\n --select-border-focus: #6366f1;\n --select-text: var(--select-dark-text, #f5f5f5);\n --select-text-muted: #9ca3af;\n --select-text-placeholder: #6b7280;\n --select-shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.2);\n --select-shadow-md: 0 4px 12px rgba(0, 0, 0, 0.3);\n --select-shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.4);\n --select-shadow-focus: 0 0 0 3px rgba(99, 102, 241, 0.25);\n\n --select-dropdown-bg: var(--select-dark-dropdown-bg, var(--select-surface));\n \n --select-arrow-color: var(--select-dark-arrow-color, #9ca3af);\n --select-arrow-hover-color: var(--select-dark-arrow-hover-color, #f5f5f5);\n --select-arrow-bg: var(--select-dark-arrow-bg, transparent);\n --select-arrow-hover-bg: var(--select-dark-arrow-hover-bg, rgba(156, 163, 175, 0.15));\n \n --select-separator-bg: var(--select-dark-separator-bg, var(--select-separator-dark-bg));\n --select-separator-width: var(--select-dark-separator-width, 1px);\n \n --select-badge-bg: var(--select-dark-badge-bg, rgba(99, 102, 241, 0.2));\n --select-badge-color: var(--select-dark-badge-color, #e0e7ff);\n --select-badge-border: var(--select-dark-badge-border, var(--select-badge-border, none));\n --select-badge-hover-border: var(--select-dark-badge-hover-border, var(--select-badge-hover-border, var(--select-badge-border, none)));\n --select-badge-active-border: var(--select-dark-badge-active-border, var(--select-badge-active-border, var(--select-badge-hover-border, var(--select-badge-border, none))));\n \n --select-group-header-bg: var(--select-group-header-dark-bg, #1a1a2e);\n --select-group-header-color: var(--select-group-header-dark-color, #9ca3af);\n \n --select-empty-color: var(--select-dark-empty-color, #9ca3af);\n \n --select-option-bg: var(--select-dark-option-bg, transparent);\n --select-option-color: var(--select-dark-option-color, var(--select-text));\n --select-option-border: var(--select-dark-option-border, none);\n --select-option-hover-bg: var(--select-dark-option-hover-bg, var(--select-surface-elevated));\n --select-option-hover-color: var(--select-dark-option-hover-color, var(--select-text));\n --select-option-hover-border: var(--select-dark-option-hover-border, var(--select-option-border, none));\n --select-option-selected-bg: var(--select-dark-option-selected-bg, linear-gradient(135deg, rgba(99, 102, 241, 0.15) 0%, rgba(99, 102, 241, 0.08) 100%));\n --select-option-selected-color: var(--select-dark-option-selected-color, #a5b4fc);\n --select-option-selected-border: var(--select-dark-option-selected-border, var(--select-option-border, none));\n --select-option-selected-hover-bg: var(--select-dark-option-selected-hover-bg, var(--select-option-selected-bg));\n --select-option-selected-hover-color: var(--select-dark-option-selected-hover-color, var(--select-option-selected-color));\n --select-option-selected-hover-border: var(--select-dark-option-selected-hover-border, var(--select-option-selected-border, var(--select-option-hover-border, var(--select-option-border, none))));\n }\n\n :host(.dark-mode) .input-container,\n :host([dark-mode]) .input-container,\n :host([darkmode]) .input-container,\n :host([data-theme="dark"]) .input-container,\n :host([theme="dark"]) .input-container,\n :host-context(.dark-mode) .input-container,\n :host-context(.dark) .input-container,\n :host-context([dark-mode]) .input-container,\n :host-context([darkmode]) .input-container,\n :host-context([data-theme="dark"]) .input-container,\n :host-context([theme="dark"]) .input-container {\n background: var(--select-surface);\n border-color: var(--select-border);\n }\n\n :host(.dark-mode) .input-container:hover,\n :host([dark-mode]) .input-container:hover,\n :host([darkmode]) .input-container:hover,\n :host([data-theme="dark"]) .input-container:hover,\n :host([theme="dark"]) .input-container:hover,\n :host-context(.dark-mode) .input-container:hover,\n :host-context(.dark) .input-container:hover,\n :host-context([dark-mode]) .input-container:hover,\n :host-context([darkmode]) .input-container:hover,\n :host-context([data-theme="dark"]) .input-container:hover,\n :host-context([theme="dark"]) .input-container:hover {\n border-color: var(--select-dark-input-hover-border, var(--select-input-hover-border, var(--select-dark-border-focus, var(--select-border-focus, #6366f1))));\n box-shadow: var(--select-dark-input-hover-shadow, var(--select-input-hover-shadow, var(--select-shadow-sm), 0 0 0 1px rgba(99, 102, 241, 0.12)));\n }\n\n :host(.dark-mode) .input-container:focus-within,\n :host([dark-mode]) .input-container:focus-within,\n :host([darkmode]) .input-container:focus-within,\n :host([data-theme="dark"]) .input-container:focus-within,\n :host([theme="dark"]) .input-container:focus-within,\n :host-context(.dark-mode) .input-container:focus-within,\n :host-context(.dark) .input-container:focus-within,\n :host-context([dark-mode]) .input-container:focus-within,\n :host-context([darkmode]) .input-container:focus-within,\n :host-context([data-theme="dark"]) .input-container:focus-within,\n :host-context([theme="dark"]) .input-container:focus-within {\n border-color: var(--select-dark-border-focus, var(--select-border-focus, #6366f1));\n box-shadow: var(--select-dark-shadow-focus, var(--select-shadow-focus, 0 0 0 3px rgba(99, 102, 241, 0.25))), var(--select-shadow-sm);\n }\n\n :host(.dark-mode) .input-container::after,\n :host([dark-mode]) .input-container::after,\n :host([darkmode]) .input-container::after,\n :host([data-theme="dark"]) .input-container::after,\n :host([theme="dark"]) .input-container::after,\n :host-context(.dark-mode) .input-container::after,\n :host-context(.dark) .input-container::after,\n :host-context([dark-mode]) .input-container::after,\n :host-context([darkmode]) .input-container::after,\n :host-context([data-theme="dark"]) .input-container::after,\n :host-context([theme="dark"]) .input-container::after {\n background: var(--select-separator-dark-bg);\n }\n\n :host(.dark-mode) .select-dropdown,\n :host([dark-mode]) .select-dropdown,\n :host([darkmode]) .select-dropdown,\n :host([data-theme="dark"]) .select-dropdown,\n :host([theme="dark"]) .select-dropdown,\n :host-context(.dark-mode) .select-dropdown,\n :host-context(.dark) .select-dropdown,\n :host-context([dark-mode]) .select-dropdown,\n :host-context([darkmode]) .select-dropdown,\n :host-context([data-theme="dark"]) .select-dropdown,\n :host-context([theme="dark"]) .select-dropdown {\n background: var(--select-dropdown-bg, var(--select-surface));\n border-color: var(--select-border);\n }\n\n :host(.dark-mode) .options-container,\n :host([dark-mode]) .options-container,\n :host([darkmode]) .options-container,\n :host([data-theme="dark"]) .options-container,\n :host([theme="dark"]) .options-container,\n :host-context(.dark-mode) .options-container,\n :host-context(.dark) .options-container,\n :host-context([dark-mode]) .options-container,\n :host-context([darkmode]) .options-container,\n :host-context([data-theme="dark"]) .options-container,\n :host-context([theme="dark"]) .options-container {\n background: var(--select-dropdown-bg, var(--select-surface));\n scrollbar-color: var(--select-border) transparent;\n }\n\n :host(.dark-mode) .selection-badge,\n :host([dark-mode]) .selection-badge,\n :host([darkmode]) .selection-badge,\n :host([data-theme="dark"]) .selection-badge,\n :host([theme="dark"]) .selection-badge,\n :host-context(.dark-mode) .selection-badge,\n :host-context(.dark) .selection-badge,\n :host-context([dark-mode]) .selection-badge,\n :host-context([darkmode]) .selection-badge,\n :host-context([data-theme="dark"]) .selection-badge,\n :host-context([theme="dark"]) .selection-badge {\n background: var(--select-dark-badge-bg, var(--select-badge-bg, var(--select-badge-dark-bg)));\n color: var(--select-dark-badge-color, var(--select-badge-color, #e0e7ff));\n }\n\n :host(.dark-mode) .group-header:not(:first-child),\n :host([dark-mode]) .group-header:not(:first-child),\n :host([darkmode]) .group-header:not(:first-child),\n :host([data-theme="dark"]) .group-header:not(:first-child),\n :host([theme="dark"]) .group-header:not(:first-child),\n :host-context(.dark-mode) .group-header:not(:first-child),\n :host-context(.dark) .group-header:not(:first-child),\n :host-context([dark-mode]) .group-header:not(:first-child),\n :host-context([darkmode]) .group-header:not(:first-child),\n :host-context([data-theme="dark"]) .group-header:not(:first-child),\n :host-context([theme="dark"]) .group-header:not(:first-child) {\n border-top-color: var(--select-border);\n }\n\n :host(.dark-mode) .group-header,\n :host([dark-mode]) .group-header,\n :host([darkmode]) .group-header,\n :host([data-theme="dark"]) .group-header,\n :host([theme="dark"]) .group-header,\n :host-context(.dark-mode) .group-header,\n :host-context(.dark) .group-header,\n :host-context([dark-mode]) .group-header,\n :host-context([darkmode]) .group-header,\n :host-context([data-theme="dark"]) .group-header,\n :host-context([theme="dark"]) .group-header {\n color: var(--select-dark-group-header-color, var(--select-group-header-color, inherit));\n background: var(--select-dark-group-header-bg, var(--select-group-header-bg, #1a1a2e));\n border-bottom: var(--select-group-header-border-bottom, 1px solid rgba(255, 255, 255, 0.08));\n box-shadow: var(--select-group-header-shadow, 0 1px 2px rgba(0, 0, 0, 0.3));\n }\n\n :host(.dark-mode) .group-header,\n :host([dark-mode]) .group-header,\n :host([darkmode]) .group-header,\n :host([data-theme="dark"]) .group-header,\n :host([theme="dark"]) .group-header {\n color: var(--select-dark-group-header-color, var(--select-group-header-dark-color, #9ca3af));\n background: var(--select-dark-group-header-bg, var(--select-group-header-dark-bg, #1a1a2e));\n border-bottom: var(--select-group-header-border-bottom, 1px solid rgba(255, 255, 255, 0.08));\n box-shadow: var(--select-group-header-shadow, 0 1px 2px rgba(0, 0, 0, 0.3));\n }\n\n :host(.dark-mode) .group-header:not(:first-child),\n :host([dark-mode]) .group-header:not(:first-child),\n :host([darkmode]) .group-header:not(:first-child),\n :host([data-theme="dark"]) .group-header:not(:first-child),\n :host([theme="dark"]) .group-header:not(:first-child) {\n border-top-color: var(--select-border);\n }\n\n :host(.dark-mode) .option.selected::before,\n :host([dark-mode]) .option.selected::before,\n :host([darkmode]) .option.selected::before,\n :host([data-theme="dark"]) .option.selected::before,\n :host([theme="dark"]) .option.selected::before,\n :host-context(.dark-mode) .option.selected::before,\n :host-context(.dark) .option.selected::before,\n :host-context([dark-mode]) .option.selected::before,\n :host-context([darkmode]) .option.selected::before,\n :host-context([data-theme="dark"]) .option.selected::before,\n :host-context([theme="dark"]) .option.selected::before {\n background: var(--select-accent);\n }\n ',this._shadow.firstChild?this._shadow.insertBefore(e,this._shadow.firstChild):this._shadow.appendChild(e)}_attachEventListeners(){this._arrowContainer&&(this._boundArrowClick=e=>{e.stopPropagation(),e.preventDefault(),this._state.isOpen&&!1!==this._config.selection.toggleOnTriggerClick?this._handleClose():this._state.isOpen||this._handleOpen()},this._arrowContainer.addEventListener("click",this._boundArrowClick)),this._clearControl&&(this._clearControl.addEventListener("pointerdown",e=>{e.stopPropagation(),e.preventDefault()}),this._clearControl.addEventListener("click",e=>{e.stopPropagation(),e.preventDefault(),this._handleClearControlClick()})),this._inputContainer.addEventListener("pointerdown",e=>{const t=e.target;if(!this._config.enabled)return;if(t&&t.closest(".dropdown-arrow-container"))return;if(t&&t.closest(".clear-control-button"))return;if(this._isPointerOnInputScrollbar(e))return void(this._suppressNextOpenClick=!0);const i="multi"===this._config.selection.mode&&"horizontal"===(this._config.multiSelectDisplay?.mode??"wrap"),n=this._canUseHorizontalMultiScroll(t);if(n&&0===e.button)return this._beginMultiScrollDrag(e),this._suppressNextOpenClick=!1,void e.preventDefault();t&&!t.matches(".select-input")&&e.preventDefault();const o=Boolean(t&&t.matches(".select-input"));if(this._state.isOpen&&!1!==this._config.selection.toggleOnTriggerClick&&!i&&!n&&(!o||!this._config.searchable))return void this._handleClose();const s=!this._state.isOpen;if(s&&this._handleOpen(),this._applyFocusIntent("input","input-container-trigger"),s&&this._optionsContainer&&"number"==typeof e.pointerId)try{this._optionsContainer.setPointerCapture(e.pointerId)}catch(e){}}),this._inputContainer.addEventListener("click",e=>{const t=e.target,i="multi"===this._config.selection.mode&&"horizontal"===(this._config.multiSelectDisplay?.mode??"wrap");return this._config.enabled&&i?t&&t.closest(".dropdown-arrow-container, .clear-control-button")||this._suppressNextOpenClick||this._multiScrollDrag.moved||this._isPointerOnInputScrollbar(e)?(this._suppressNextOpenClick=!1,void(this._multiScrollDrag.moved=!1)):(this._suppressNextOpenClick=!1,this._multiScrollDrag.moved=!1,this._state.isOpen||this._handleOpen(),void this._applyFocusIntent("input","input-container-activation")):(this._suppressNextOpenClick=!1,void(this._multiScrollDrag.moved=!1))}),this._inputContent.addEventListener("pointermove",e=>{this._updateMultiScrollDrag(e)}),this._inputContent.addEventListener("pointerup",e=>{this._endMultiScrollDrag(e.pointerId)}),this._inputContent.addEventListener("pointercancel",e=>{this._endMultiScrollDrag(e.pointerId)}),this._inputContent.addEventListener("wheel",e=>{if("multi"===this._config.selection.mode&&"horizontal"===(this._config.multiSelectDisplay?.mode??"wrap")){const t=Math.abs(e.deltaX)>Math.abs(e.deltaY)?e.deltaX:e.deltaY;0!==t&&(this._inputContent.scrollLeft+=t),e.preventDefault()}},{passive:!1}),this._container.addEventListener("click",e=>{e.stopPropagation()}),this._input.addEventListener("focus",()=>{this._runEngineEffects(this._engine.dispatch({type:"FOCUS_GAINED"})),this._handleOpen()}),this._input.addEventListener("blur",e=>{this._runEngineEffects(this._engine.dispatch({type:"FOCUS_LOST"}));const t=e.relatedTarget;t&&(this._shadow.contains(t)||this._container.contains(t))||this._setLifecycleTimeout(()=>{if(this._suppressBlurClose)return;const e=document.activeElement;e&&(this._shadow.contains(e)||this._container.contains(e))||this._handleClose("blur")},150)}),this._input.addEventListener("input",e=>{if(!this._config.searchable)return;const t=e.target.value;this._handleSearch(t)}),this._optionsContainer.addEventListener("pointerdown",()=>{this._suppressBlurClose=!0,this._setLifecycleTimeout(()=>{this._suppressBlurClose=!1},150)});this._optionsContainer.addEventListener("click",e=>{const t=e.composedPath&&e.composedPath()||[e.target];let i=null;for(const e of t)if(e instanceof Element)try{if(e.matches("[data-sm-selectable], [data-selectable], [data-sm-state]")){i=e;break}}catch(e){continue}if(i&&(!i.hasAttribute("aria-disabled")||i.classList.contains("smilodon-option--disabled-selectable"))){const t=i.getAttribute("data-sm-index")??i.getAttribute("data-index"),n=Number(t);Number.isNaN(n)||this._selectOption(n,{shiftKey:e.shiftKey,toggleKey:e.ctrlKey||e.metaKey})}}),this._input.addEventListener("keydown",e=>this._handleKeydown(e))}_initializeObservers(){if(this._intersectionObserver&&(this._intersectionObserver.disconnect(),this._intersectionObserver=void 0),("acknowledged"!==this._dataLoadingConfig.protocol||this._dataRequestCoordinator&&this._acknowledgedReady)&&this._config.infiniteScroll.enabled){const e=Boolean(this._dataRequestCoordinator&&"acknowledged"===this._dataLoadingConfig.protocol);if(e&&"undefined"==typeof IntersectionObserver)return;let t;try{t=new IntersectionObserver(i=>{this._intersectionObserver===t&&i.forEach(t=>{if(e){if(!this._acknowledgedReady||!this.isConnected||t.target!==this._loadMoreTrigger)return;if(!t.isIntersecting)return void this._dataRequestCoordinator?.setSentinelIntersecting(!1);if(this._acknowledgedProjectionPending||this._acknowledgedProjectionSettling)return;const e=this._dataRequestCoordinator?.setSentinelIntersecting(!0)??[];return void this._dispatchAcknowledgedActions(e)}t.isIntersecting&&!this._state.isBusy&&this._loadMoreItems()})},e?{root:this._optionsContainer,threshold:.1}:{threshold:.1}),this._intersectionObserver=t}catch(t){if(this._intersectionObserver=void 0,!e)throw t}}}async _loadInitialSelectedItems(){if(!this._config.serverSide.fetchSelectedItems||!this._config.serverSide.initialSelectedValues)return;this._setBusy(!0);const e=++this._asyncGeneration;try{const t=await this._config.serverSide.fetchSelectedItems(this._config.serverSide.initialSelectedValues);if(e!==this._asyncGeneration||!this.isConnected)return;const i=createItemRegistry(t,this._itemAdapter,{duplicateKeyPolicy:this._getDuplicateKeyPolicy()});this._requestSelectionReplacement(i.records,"external-value-sync","initial selected items"),this._updateInputDisplay()}catch(t){if(e!==this._asyncGeneration||!this.isConnected)return;this._handleError(t)}finally{e===this._asyncGeneration&&this.isConnected&&this._setBusy(!1)}}_runEngineEffects(e){this._effectRunner.run(e,{focusTrigger:()=>{this._applyFocusIntent("input","engine-focus-trigger")},syncAria:()=>{this._syncPopupAria()}})}_syncPopupAria(){this._input&&this._syncComboboxAccessibility()}_syncComboboxAccessibility(){if(!this._input||!this._engine||!this._state)return;applyAccessibilityEffects(computeAccessibilityEffects(deriveAccessibilityState(this._engine.state,{searchable:this._config.searchable,readonly:!this._config.searchable,invalid:this._hasError,label:{ariaLabel:this.getAttribute("aria-label")?.trim()||null,ariaDescription:this.getAttribute("aria-description")?.trim()||null},errorMessage:this._errorMessage,errorDescriptionId:this._hasError&&this._errorMessage?this._errorDescription?.id??null:null}),{controlsId:this._dropdown?.id||null,optionKeys:[]}).filter(e=>"SYNC_COMBOBOX_ARIA"===e.type),{combobox:this._input,getOptionByKey:e=>{if(!this._state.isOpen)return null;const t=this._itemRegistry.keyToIndex.get(e);return void 0===t?null:this._getOptionElementByIndex(t)}})}_syncListboxAccessibility(){if(!this._dropdown||!this._engine||!this._state)return;applyAccessibilityEffects(computeAccessibilityEffects({...deriveAccessibilityState(this._engine.state,{label:{ariaLabel:this.getAttribute("aria-label")?.trim()||null}}),busy:this._state.isBusy||"acknowledged"===this._dataLoadingConfig.protocol&&"true"===this.getAttribute("aria-busy")},{controlsId:this._dropdown.id||null,optionKeys:[]}).filter(e=>"SYNC_LISTBOX_ARIA"===e.type),{listbox:this._dropdown})}_syncRenderedOptionAccessibility(){if(!this._optionsContainer||!this._engine||!this._state)return;const e=new Map;if(this._optionsContainer.querySelectorAll("[data-index]").forEach(t=>{const i=Number(t.getAttribute("data-index"));if(!Number.isFinite(i))return;const n=this._itemRegistry.indexToKey.get(i);void 0!==n&&e.set(n,t)}),0===e.size)return;applyAccessibilityEffects(computeAccessibilityEffects(deriveAccessibilityState(this._engine.state),{controlsId:this._dropdown?.id||null,optionKeys:[...e.keys()]}).filter(e=>"SYNC_OPTION_ARIA"===e.type),{getOptionByKey:t=>e.get(t)??null})}_applyFocusIntent(e,t,i){applyAccessibilityEffects(computeAccessibilityEffects(deriveAccessibilityState(this._engine.state),{optionKeys:[],focusIntents:[{target:e,reason:t}]}).filter(e=>"FOCUS_INTENT"===e.type),{focusTargets:{input:"input"===e?this._input:null,clearButton:"clear-button"===e?this._clearControl:null,getActiveOption:()=>"active-option"===e?i??null:null}},{applyFocus:!0})}_handleOpen(){if(!this._config.enabled)return void this._runEngineEffects(this._engine.dispatch({type:"DISABLED_CHANGED",disabled:!0}));if(this._state.isOpen)return;EnhancedSelect._instances.forEach(e=>{e!==this&&e._handleClose()});const e=this._engine.dispatch({type:"OPEN_REQUEST"});if(e.some(e=>"POPUP_OPENED"===e.type)&&(this._runEngineEffects(e),this._markOpenStart(),this.setAttribute("data-open","true"),this._liftStackingAncestors(),this._dropdown.style.display="block",this._updateArrowRotation(),this._renderOptions(),this._syncDropdownPlacement(),this._setInitialActiveOption(),this._emit("open",{}),this._config.callbacks.onOpen?.(),this._announce("Options expanded"),this._config.scrollToSelected.enabled)){const e=this._keyboardActiveChangeGeneration,t=()=>this._state.isOpen&&this._keyboardActiveChangeGeneration===e;this._requestLifecycleFrame(()=>{t()&&this._requestLifecycleFrame(()=>{t()&&this._scrollToSelected()})})}}_handleClose(e="programmatic"){const t=this._engine.dispatch({type:"CLOSE_REQUEST",reason:e});t.some(e=>"POPUP_CLOSED"===e.type)&&(this.removeAttribute("data-open"),this._restoreLiftedAncestors(),this._dropdown.style.display="none",this._dropdown.setAttribute("data-placement",this._resolvedDropdownPlacement),this._updateArrowRotation(),this._runEngineEffects(t),this._emit("close",{}),this._config.callbacks.onClose?.(),this._announce("Options collapsed"))}_updateDropdownVisibility(){this._state.isOpen?(this.setAttribute("data-open","true"),this._liftStackingAncestors(),this._dropdown.style.display="block",this._syncDropdownPlacement()):(this.removeAttribute("data-open"),this._restoreLiftedAncestors(),this._dropdown.style.display="none"),this._syncComboboxAccessibility()}_liftStackingAncestors(){this._restoreLiftedAncestors();let e=this.parentElement;for(;e&&e!==document.body;){if(this._createsStackingContext(e)){const t=e.hasAttribute("data-smilodon-open-ancestor");this._liftedAncestors.push({element:e,position:e.style.position,zIndex:e.style.zIndex,hadMarker:t}),"static"===getComputedStyle(e).position&&(e.style.position="relative"),e.style.zIndex="var(--select-ancestor-open-z-index, var(--select-host-open-z-index, var(--select-dropdown-z-index, 1000)))",e.setAttribute("data-smilodon-open-ancestor","true")}e=e.parentElement}}_restoreLiftedAncestors(){for(const e of this._liftedAncestors)e.element.style.position=e.position,e.element.style.zIndex=e.zIndex,e.hadMarker||e.element.removeAttribute("data-smilodon-open-ancestor");this._liftedAncestors=[]}_createsStackingContext(e){const t=getComputedStyle(e);return"fixed"===t.position||"sticky"===t.position||("auto"!==t.zIndex&&"static"!==t.position||("1"!==t.opacity||("none"!==t.transform||("none"!==t.filter||(!(!t.backdropFilter||"none"===t.backdropFilter)||("none"!==t.perspective||("normal"!==t.mixBlendMode||("isolate"===t.isolation||(!(!t.contain.includes("paint")&&!t.contain.includes("layout"))||!!(t.willChange.includes("transform")||t.willChange.includes("opacity")||t.willChange.includes("filter")))))))))))}_updateArrowRotation(){if(this._arrowContainer){const e=this._arrowContainer.querySelector(".dropdown-arrow");e&&(this._state.isOpen?e.classList.add("open"):e.classList.remove("open"))}}_isPerfEnabled(){return"undefined"!=typeof globalThis&&!0===globalThis.__SMILODON_DEV__&&"undefined"!=typeof performance&&"function"==typeof performance.mark&&"function"==typeof performance.measure}_perfMark(e){this._isPerfEnabled()&&performance.mark(e)}_perfMeasure(e,t,i){this._isPerfEnabled()&&(performance.measure(e,t,i),performance.clearMarks(t),performance.clearMarks(i),performance.clearMeasures(e))}_markOpenStart(){this._isPerfEnabled()&&(this._pendingFirstRenderMark=!0,this._perfMark("smilodon-dropdown-open-start"))}_finalizePerfMarks(){if(!this._isPerfEnabled())return this._pendingFirstRenderMark=!1,void(this._pendingSearchRenderMark=!1);this._pendingFirstRenderMark&&(this._pendingFirstRenderMark=!1,this._perfMark("smilodon-first-render-complete"),this._perfMeasure("smilodon-dropdown-to-first-render","smilodon-dropdown-open-start","smilodon-first-render-complete")),this._pendingSearchRenderMark&&(this._pendingSearchRenderMark=!1,this._perfMark("smilodon-search-render-complete"),this._perfMeasure("smilodon-search-to-render","smilodon-search-input-last","smilodon-search-render-complete"))}_filterItemsByQuery(e,t){if(!t?.trim())return e;const i=t.toLowerCase().trim(),n=this._config.serverSide.getLabelFromItem??(e=>e?.label??e?.text??String(e)),o=[],s=e.length;for(let t=0;t<s;t++){const s=e[t];if(null!=s)try{const e=n(s);if(null==e)continue;String(e).toLowerCase().includes(i)&&o.push(s)}catch(e){continue}}return o}_handleSearch(e){if(this._dataRequestCoordinator&&(this._acknowledgedProjectionPending||this._acknowledgedProjectionSettling))return this._acknowledgedPendingSearchQuery=e,this._input.value=e,void this._syncClearControlState();if("acknowledged"===this._dataLoadingConfig.protocol&&("remote"===this._dataLoadingConfig.searchMode||"hybrid"===this._dataLoadingConfig.searchMode)){if(this._state.searchQuery=e,this._syncClearControlState(),this._state.lastNotifiedQuery=e,this._state.lastNotifiedResultCount=0,this._dataRequestCoordinator){const t=this._dataRequestCoordinator.setQuery(e);this._acknowledgedReady?this._dispatchAcknowledgedActions(t):this._renderOptions()}else this._state.isOpen?this._renderOptions():this._handleOpen();return}this._state.searchQuery=e,this._syncClearControlState(),"acknowledged"===this._dataLoadingConfig.protocol&&this._dataRequestCoordinator&&this._dispatchAcknowledgedActions(this._dataRequestCoordinator.setQuery(e)),e.length>0?(this._perfMark("smilodon-search-input-last"),this._pendingSearchRenderMark=!0):this._pendingSearchRenderMark=!1,this._searchTimeout&&clearTimeout(this._searchTimeout),this._state.isSearching=!1,this._state.isOpen?this._renderOptions():this._handleOpen();const t=this._filterItemsByQuery(this._state.loadedItems,e),i=t.length;e.trim()&&this._announce(`${i} result${1!==i?"s":""} found for "${e}"`),e===this._state.lastNotifiedQuery&&i===this._state.lastNotifiedResultCount||(this._state.lastNotifiedQuery=e,this._state.lastNotifiedResultCount=i,this._setLifecycleTimeout(()=>{this._emit("search",{query:e,results:t,count:i}),this._config.callbacks.onSearch?.(e)},0))}_handleKeydown(e){if(this._config.enabled)switch(e.key){case"ArrowDown":e.preventDefault(),this._state.isOpen?this._moveActive(1,{shiftKey:e.shiftKey,toggleKey:e.ctrlKey||e.metaKey}):this._handleOpen();break;case"ArrowUp":e.preventDefault(),this._state.isOpen?this._moveActive(-1,{shiftKey:e.shiftKey,toggleKey:e.ctrlKey||e.metaKey}):this._handleOpen();break;case"Home":if(e.preventDefault(),this._state.isOpen){const t=this._getSelectableOptionIndices()[0];if(void 0===t)break;this._setActive(t),"multi"===this._config.selection.mode&&e.shiftKey&&this._selectRange(this._rangeAnchorIndex??t,t,{clear:!(e.ctrlKey||e.metaKey)})}break;case"End":if(e.preventDefault(),this._state.isOpen){const t=this._getSelectableOptionIndices(),i=t[t.length-1];if(void 0===i)break;this._setActive(i),"multi"===this._config.selection.mode&&e.shiftKey&&this._selectRange(this._rangeAnchorIndex??i,i,{clear:!(e.ctrlKey||e.metaKey)})}break;case"PageDown":e.preventDefault(),this._state.isOpen&&this._moveActive(10,{shiftKey:e.shiftKey,toggleKey:e.ctrlKey||e.metaKey});break;case"PageUp":e.preventDefault(),this._state.isOpen&&this._moveActive(-10,{shiftKey:e.shiftKey,toggleKey:e.ctrlKey||e.metaKey});break;case"Enter":case" ":if(e.preventDefault(),this._state.isOpen){const t=this._engine.state.activeKey,i=null===t?-1:this._itemRegistry.keyToIndex.get(t)??-1;i>=0&&this._selectOption(i,{shiftKey:e.shiftKey,toggleKey:e.ctrlKey||e.metaKey,reason:"keyboard"})}else this._handleOpen();break;case"Escape":e.preventDefault(),this._handleClose("escape");break;case"Tab":this._state.isOpen&&this._handleClose();break;case"a":case"A":(e.ctrlKey||e.metaKey)&&"multi"===this._config.selection.mode&&(e.preventDefault(),this._selectAll());break;default:1!==e.key.length||e.ctrlKey||e.altKey||e.metaKey||this._handleTypeAhead(e.key)}}_moveActive(e,t){const i=this._getSelectableOptionIndices();if(0===i.length)return;const n=this._engine.state.activeKey,o=null===n?-1:this._itemRegistry.keyToIndex.get(n)??-1,s=i.indexOf(o),r=s>=0?s:e>=0?-1:i.length,a=i[Math.max(0,Math.min(i.length-1,r+e))];if(this._setActive(a),"multi"===this._config.selection.mode&&t?.shiftKey){const e=this._rangeAnchorIndex??o,i=e>=0?e:a;null===this._rangeAnchorIndex&&(this._rangeAnchorIndex=i),this._selectRange(i,a,{clear:!t?.toggleKey})}}_setActive(e,t="keyboard"){this._ensureRegistryCurrent();const i=this._getRecordByIndex(e);let n=this._getOptionElementByIndex(e);if(!n&&i&&this._guardedVirtualizer&&(this._materializeGuardedVirtualKey(i.key),n=this._getOptionElementByIndex(e)),!i||i.disabled||!n||"true"===n.getAttribute("aria-disabled"))return;"keyboard"===t&&(this._keyboardActiveChangeGeneration+=1);const o=this._state.activeIndex;if(this._dispatchActiveKey(i.key,t,"set active"),this._state.activeIndex===e){if(o>=0&&o!==e){const e=this._getOptionElementByIndex(o);e&&("setActive"in e&&"function"==typeof e.setActive?e.setActive(!1):this._syncCustomOptionActiveClasses(e,!1))}if(n){"setActive"in n&&"function"==typeof n.setActive?n.setActive(!0):this._syncCustomOptionActiveClasses(n,!0),"function"==typeof n.scrollIntoView&&n.scrollIntoView({block:"nearest",behavior:"smooth"});const t=this._state.loadedItems.length;this._announce(`Item ${e+1} of ${t}`),this._syncLegacyActiveAria()}}}_getOptionElementByIndex(e){return this._optionsContainer.querySelector(`[data-index="${e}"]`)}_getSelectableOptions(){return Array.from(this._optionsContainer.children).filter(e=>(e.hasAttribute("data-index")||e.hasAttribute("data-sm-selectable"))&&"true"!==e.getAttribute("aria-disabled"))}_getSelectableOptionIndices(){return this._guardedVirtualizer?this._renderPlan.filteredKeys.flatMap(e=>{const t=this._itemRegistry.keyToRecord.get(e);return t&&!t.disabled?[t.index]:[]}):this._getSelectableOptions().map(e=>Number(e.getAttribute("data-sm-index")??e.getAttribute("data-index"))).filter(e=>Number.isFinite(e))}_buildRendererHelpers(){return{onSelect:(e,t)=>this._selectOption(t),getIndex:e=>{const t=e?.closest?.("[data-selectable]");if(!t)return null;const i=Number(t.dataset.index);return Number.isFinite(i)?i:null},keyboardFocus:e=>{this._setActive(e);const t=this._getOptionElementByIndex(e);this._applyFocusIntent("active-option","renderer-keyboard-focus",t)}}}_handleTypeAhead(e){this._typeTimeout&&clearTimeout(this._typeTimeout),this._typeBuffer+=e.toLowerCase(),this._typeTimeout=window.setTimeout(()=>{this._typeBuffer=""},500);const t=this._config.serverSide.getLabelFromItem||(e=>e?.label??String(e)),i=this._state.loadedItems.findIndex(e=>t(e).toLowerCase().startsWith(this._typeBuffer));i>=0&&this._setActive(i,"search")}_selectAll(){if("multi"!==this._config.selection.mode)return;this._ensureRegistryCurrent();const e=this._getSelectableOptions(),t=this._getSelectedEntries();e.forEach(e=>{const i=Number(e.getAttribute("data-sm-index")??e.getAttribute("data-index"));if(!Number.isFinite(i))return;const n=this._getRecordByIndex(i);n&&!this._isOptionSelectionBlocked(n.item)&&t.push(n)}),this._requestSelectionReplacement(t,"keyboard","select all"),this._renderOptions(),this._updateInputDisplay(),this._emitChange(),this._announce(`Selected all ${e.length} items`)}_selectRange(e,t,i){if("multi"!==this._config.selection.mode)return;this._ensureRegistryCurrent();const[n,o]=e<t?[e,t]:[t,e],s=this._getSelectedEntries(),r=i?.clear?s.filter(e=>!this._itemRegistry.keyToRecord.has(e.key)):s;for(let e=n;e<=o;e+=1){const t=this._getRecordByIndex(e),i=this._getOptionElementByIndex(e);("true"!==i?.getAttribute("aria-disabled")||i.classList.contains("smilodon-option--disabled-selectable"))&&(t&&!this._isOptionSelectionBlocked(t.item)&&r.push(t))}this._requestSelectionReplacement(r,i?.reason??"keyboard","select range"),this._renderOptions(),this._updateInputDisplay();const a=this._getRecordByIndex(t),l=a?this._getSelectEventDetail(a):null;l&&this._emit("select",l),this._emitChange(),this._announce(`${this._state.selectedIndices.size} items selected`),l&&this._config.callbacks.onSelect?.(l)}_getSelectEventDetail(e){const t=this._config.serverSide.getValueFromItem||(e=>e?.value??e),i=this._config.serverSide.getLabelFromItem||(e=>e?.label??String(e));return{item:e.item,index:e.index,value:t(e.item),label:i(e.item),selected:this._engine.state.selectedKeys.has(e.key),multi:"multi"===this._config.selection.mode}}_setInitialActiveOption(){const e=this._getSelectableOptionIndices(),t=Array.from(this._state.selectedIndices).sort((e,t)=>e-t);if(0===e.length||0===t.length)return void this._dispatchActiveKey(null,"open","initial active option");const i=t.find(t=>e.includes(t))??e[0];this._setActive(i,"open")}_announce(e){applyAccessibilityEffects(computeAccessibilityEffects(deriveAccessibilityState(this._engine.state),{optionKeys:[],announcements:[{politeness:"polite",message:e}]}).filter(e=>"ANNOUNCE"===e.type),{liveRegion:this._liveRegion}),this._liveRegion&&this._setLifecycleTimeout(()=>{applyAccessibilityEffects(computeAccessibilityEffects(deriveAccessibilityState(this._engine.state),{optionKeys:[],announcements:[{politeness:"polite",message:""}]}).filter(e=>"ANNOUNCE"===e.type),{liveRegion:this._liveRegion})},1e3)}_selectOption(e,t){this._ensureRegistryCurrent();const i=this._getRecordByIndex(e);if(!i)return;e=i.index;const n=i.item;if(this._isOptionSelectionBlocked(n))return;const o=this._engine.state.selectedKeys.has(i.key),s=t?.reason??"pointer";if(i.disabled||this._dispatchActiveKey(i.key,"keyboard"===s?"keyboard":"pointer","option selection"),"single"===this._config.selection.mode)this._dispatchSelection({type:o&&this._config.selection.allowDeselect?"TOGGLE_KEY_REQUEST":"SELECT_KEY_REQUEST",key:i.key,reason:s},"single option selection"),this._renderOptions(),this._config.selection.closeOnSelect&&this._handleClose("selection");else{const n=Boolean(t?.toggleKey);if(Boolean(t?.shiftKey)){const t=this._rangeAnchorIndex??e;return this._selectRange(t,e,{clear:!n,reason:s}),void(this._rangeAnchorIndex=t)}const r=this._config.selection.maxSelections||0;if(!o&&r>0&&this._engine.state.selectedKeys.size>=r)return this._announce(`Maximum ${r} selections allowed`),void this._renderOptions();this._dispatchSelection({type:"TOGGLE_KEY_REQUEST",key:i.key,reason:s},"multi option selection"),this._renderOptions()}this._rangeAnchorIndex=e,this._updateInputDisplay();const r=this._getSelectEventDetail(i);this._emit("select",r),this._emitChange();const a=r.label;if("single"===this._config.selection.mode)this._announce(`Selected ${a}`);else{const e=this._state.selectedIndices.size,t=o?"Deselected":"Selected";this._announce(`${t} ${a}. ${e} selected`)}this._config.callbacks.onSelect?.(r)}_handleOptionRemove(e,t){this._ensureRegistryCurrent();const i=this._getSelectedEntries().find(i=>void 0===t?i.index===e:i.key===t);if(!i)return;const n=i.item,o=this._shadow.activeElement,s=o instanceof HTMLButtonElement&&"chip-remove"===o.getAttribute("part")?o.closest(".selection-badge"):null,r=null!==s,a=s?Array.from(this._inputContent.querySelectorAll(".selection-badge")).indexOf(s):-1,l=this._itemRegistry.keyToRecord.has(i.key)?this._getOptionElementByIndex(i.index):null;if(this._dispatchSelection({type:"DESELECT_KEY_REQUEST",key:i.key,reason:"pointer"},"remove selected item"),l&&"setSelected"in l&&"function"==typeof l.setSelected)l.setSelected(!1);else if(l){l.classList.remove("selected","sm-selected","smilodon-option--selected");const e=(l.dataset.smState||"").split(" ").map(e=>e.trim()).filter(e=>e&&"selected"!==e);e.length>0?l.dataset.smState=e.join(" "):delete l.dataset.smState}if(this._updateInputDisplay(),this._renderOptions(),this._emitChange(),r&&this.isConnected){const e=this._inputContent.querySelectorAll('[part="chip-remove"]');if(e.length>0){e[Math.min(Math.max(a,0),e.length-1)].focus()}else this._applyFocusIntent("input","selected-chip-removed")}const c=l&&"getConfig"in l&&"function"==typeof l.getConfig?l.getConfig():void 0;this._emit("remove",{item:c?.item??n,index:i.index})}_updateInputDisplay(){const e=this._getSelectedEntries(),t=e.map(({item:e})=>e),i=this._config.serverSide.getLabelFromItem||(e=>e?.label??String(e));if(0===t.length){this._input.value="",this._input.placeholder=this._config.placeholder||"Select an option...";this._inputContent.querySelectorAll(".selection-badge").forEach(e=>e.remove())}else if("single"===this._config.selection.mode)this._input.value=i(t[0]);else{this._input.value="",this._input.placeholder="";this._inputContent.querySelectorAll(".selection-badge").forEach(e=>e.remove()),e.forEach(({key:e,index:t,item:n})=>{const o=document.createElement("span");o.className="selection-badge",this._config.styles.classNames?.badge&&o.classList.add(...this._config.styles.classNames.badge.split(" ").filter(Boolean)),o.setAttribute("part","chip");const s=document.createElement("span");if(s.className="selection-badge-label",this._config.styles.classNames?.badgeLabel&&s.classList.add(...this._config.styles.classNames.badgeLabel.split(" ").filter(Boolean)),s.setAttribute("part","chip-label"),s.textContent=i(n),o.appendChild(s),!1!==this._config.selection.showRemoveButton){const s=document.createElement("button");s.type="button",s.className="badge-remove",this._config.styles.classNames?.removeButton&&s.classList.add(...this._config.styles.classNames.removeButton.split(" ").filter(Boolean)),this._config.styles.classNames?.badgeRemove&&s.classList.add(...this._config.styles.classNames.badgeRemove.split(" ").filter(Boolean)),s.setAttribute("part","chip-remove"),s.setAttribute("aria-label",`Remove ${i(n)}`);const r=document.createElement("span");r.className="badge-remove-icon",this._config.styles.classNames?.badgeRemoveIcon&&r.classList.add(...this._config.styles.classNames.badgeRemoveIcon.split(" ").filter(Boolean)),r.setAttribute("part","chip-remove-icon"),this._setIconContent(r,this._config.selection.removeButtonIcon,"×"),s.appendChild(r),s.addEventListener("pointerdown",e=>{e.stopPropagation(),e.preventDefault()}),s.addEventListener("click",i=>{i.stopPropagation(),i.preventDefault(),this._handleOptionRemove(t,e)}),o.appendChild(s)}this._inputContent.insertBefore(o,this._input)})}null!==this._acknowledgedPendingSearchQuery&&(this._input.value=this._acknowledgedPendingSearchQuery),this._syncClearControlState()}_isActivelyEditingSearchInput(){return!0===this._config.searchable&&this._state.isOpen&&this._shadow.activeElement===this._input}_renderOptionsWithAnimation(){this._optionsContainer.style.opacity="0",this._optionsContainer.style.transition="opacity 0.15s ease-out",this._setLifecycleTimeout(()=>{this._renderOptions(),this._optionsContainer.style.opacity="1",this._optionsContainer.style.transition="opacity 0.2s ease-in"},150)}_scrollToSelected(){if(0===this._state.selectedIndices.size)return;const e=this._config.scrollToSelected.multiSelectTarget,t=Array.from(this._state.selectedIndices).filter(e=>e>=0).sort((e,t)=>e-t);if(0===t.length)return;let i;if("multi"===this._config.selection.mode&&t.length>1){const e=this._dropdown.getBoundingClientRect(),n=this._dropdown.scrollTop+e.height/2;let o=t[0],s=1/0;for(const e of t){const t=this._getOptionElementByIndex(e);if(t){const i=t.offsetTop,r=Math.abs(i-n);r<s&&(s=r,o=e)}}i=o}else i="first"===e?t[0]:t[t.length-1];let n=this._getOptionElementByIndex(i);if(!n&&this._guardedVirtualizer){const e=this._itemRegistry.indexToKey.get(i);void 0!==e&&(this._materializeGuardedVirtualKey(e),n=this._getOptionElementByIndex(i))}n&&("function"==typeof n.scrollIntoView&&n.scrollIntoView({block:this._config.scrollToSelected.block||"center",behavior:"smooth"}),this._setActive(i,"programmatic"))}async _loadMoreItems(e="manual"){if("acknowledged"===this._dataLoadingConfig.protocol){if(!this._dataRequestCoordinator||!this._acknowledgedReady||this._acknowledgedProjectionPending||this._acknowledgedProjectionSettling)return;const t=this._dataRequestCoordinator.requestLoadMore(e);return void this._dispatchAcknowledgedActions(t)}if(this._dataRequestCoordinator){if(!this._acknowledgedReady||this._acknowledgedProjectionPending||this._acknowledgedProjectionSettling)return;const t=this._dataRequestCoordinator.requestLoadMore(e);return void this._dispatchAcknowledgedActions(t)}if(!this._state.isBusy){this._setBusy(!0),this._dropdown&&(this._state.lastScrollPosition=this._dropdown.scrollTop,this._state.preserveScrollPosition=!0,this._renderOptions(),this._dropdown.scrollTop=this._state.lastScrollPosition);try{this._state.currentPage++,this._emit("loadMore",{page:this._state.currentPage,items:[]}),this._config.callbacks.onLoadMore?.(this._state.currentPage)}catch(e){this._handleError(e),this._setBusy(!1)}}}_setBusy(e){this._state.isBusy=e,this._syncListboxAccessibility(),this._renderOptions()}_handleError(e){this._emit("error",{message:e.message,cause:e}),this._config.callbacks.onError?.(e)}_emit(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0})),"diagnostic"!==e&&this._track("event",String(e),t)}_track(e,t,i){const n=this._config.tracking;if(!n?.enabled)return;if("event"===e&&!n.events)return;if("style"===e&&!n.styling)return;if("limitation"===e&&!n.limitations)return;const o={timestamp:Date.now(),source:e,name:t,detail:i},s="event"===e?this._tracking.events:"style"===e?this._tracking.styles:this._tracking.limitations;s.push(o);const r=Math.max(10,n.maxEntries||200);s.length>r&&s.splice(0,s.length-r),n.emitDiagnostics&&this.dispatchEvent(new CustomEvent("diagnostic",{detail:o,bubbles:!0,composed:!0}))}_getKnownLimitationDefinitions(){return[{id:"variableItemHeight",title:"Variable item height",description:"Virtualization assumes fixed or estimated item heights; fully dynamic heights are not yet supported.",workaround:"Use consistent item heights or set estimatedItemHeight to your dominant row size."},{id:"builtInFetchPaginationApi",title:"Built-in fetch/pagination API",description:"Core does not include a built-in fetchUrl/searchUrl pagination transport.",workaround:"Use onSearch/onLoadMore callbacks and update data via setItems()."},{id:"virtualizationOverheadSmallLists",title:"Virtualization overhead for small lists",description:"Virtualization can add slight overhead on very small lists.",workaround:"Disable virtualization for tiny datasets when micro-latency is critical."},{id:"runtimeModeSwitching",title:"Runtime single/multi mode switching",description:"Switching between single and multi mode can require state reset for consistency.",workaround:"Enable autoMitigateRuntimeModeSwitch or recreate/reset component state when toggling modes."},{id:"legacyBrowserSupport",title:"Legacy browser support",description:"Official support targets modern evergreen browsers."},{id:"webkitArchLinux",title:"Playwright WebKit on Arch-based Linux",description:"Native WebKit Playwright bundle depends on unavailable legacy system libraries on Arch-based distros.",workaround:"Run WebKit E2E tests via Playwright Docker image."}]}_evaluateLimitationStatus(e){return"suppress"===(this._config.limitations?.policies?.[e]?.mode??"default")?"suppressed":"runtimeModeSwitching"===e&&this._config.limitations?.autoMitigateRuntimeModeSwitch?"mitigated":"active"}getKnownLimitations(){return this._getKnownLimitationDefinitions().map(e=>{const t=this._config.limitations?.policies?.[e.id]?.mode??"default";return{...e,mode:t,status:this._evaluateLimitationStatus(e.id)}})}setLimitationPolicies(e){const t={...this._config.limitations?.policies||{},...e};this.updateConfig({limitations:{...this._config.limitations||{autoMitigateRuntimeModeSwitch:!0,policies:{}},policies:t}}),this._track("limitation","policiesUpdated",{policies:t})}getTrackingSnapshot(){return{events:[...this._tracking.events],styles:[...this._tracking.styles],limitations:[...this._tracking.limitations]}}clearTracking(e){if(!e||"all"===e)return this._tracking.events=[],this._tracking.styles=[],void(this._tracking.limitations=[]);"event"===e&&(this._tracking.events=[]),"style"===e&&(this._tracking.styles=[]),"limitation"===e&&(this._tracking.limitations=[])}getCapabilities(){return{styling:{classMap:!0,optionRenderer:!0,groupHeaderRenderer:!0,cssCustomProperties:!0,shadowParts:!0,globalStyleMirroring:!0},events:{emitted:["select","open","close","search","change","loadMore","remove","clear","error","diagnostic"],diagnosticEvent:!0},functionality:{multiSelect:!0,searchable:!0,infiniteScroll:!0,loadMore:!0,clearControl:!0,groupedItems:!0,serverSideSelection:!0,runtimeModeSwitchMitigation:Boolean(this._config.limitations?.autoMitigateRuntimeModeSwitch)},limitations:this.getKnownLimitations()}}_emitChange(){const e=this._getSelectedEntries(),t=e.map(({item:e})=>e),i=this._config.serverSide.getValueFromItem||(e=>e?.value??e),n=t.map(i),o=e.map(({index:e})=>e).filter(e=>e>=0);this._emit("change",{selectedItems:t,selectedValues:n,selectedIndices:o}),this._config.callbacks.onChange?.(t,n)}get optionRenderer(){return this._optionRenderer}set optionRenderer(e){this._optionRenderer!==e&&(this._invalidateGuardedMeasurements(),this._optionRenderer=e,this._setGlobalStylesMirroring(Boolean(e||this._classMap||this._groupHeaderRenderer)),this._track("style","optionRendererChanged",{enabled:Boolean(e)}),this._renderOptions())}setItems(e){this._invalidateGuardedMeasurements();const t=this._state.loadedItems.length;this._rebuildItemRegistry(e),this._state.groupedItems=this._groupItemsByProperty(e),this._state.searchQuery||this._isActivelyEditingSearchInput()||this._updateInputDisplay();const i=this._state.loadedItems.length;if(this._dataRequestCoordinator){const e=this._dataRequestCoordinator.getSnapshot().busy||this._acknowledgedProjectionPending;if(this._state.isSearching=!1,this._state.isBusy=e,this._state.preserveScrollPosition&&this._dropdown){const t=this._state.lastScrollPosition;this._renderOptions(),this._optionsContainer.scrollTop=t,this._requestLifecycleFrame(()=>{this._optionsContainer&&(this._optionsContainer.scrollTop=t)}),e||(this._state.preserveScrollPosition=!1)}else this._renderOptions();return}if(this._state.preserveScrollPosition&&this._dropdown){const e=this._state.lastScrollPosition;i>t&&(this._state.isBusy=!1),this._renderOptions(),this._dropdown.scrollTop=e,this._requestLifecycleFrame(()=>{this._dropdown&&(this._dropdown.scrollTop=e)}),i>t&&(this._state.preserveScrollPosition=!1)}else this._state.isBusy=!1,this._renderOptions()}_groupItemsByProperty(e){if(!e.some((e,t)=>null!==this._itemAdapter.getGroupKey?.(e,t)))return[];const t=new Map;return e.forEach((e,i)=>{const n=this._itemAdapter.getGroupKey?.(e,i),o=null==n?"Ungrouped":String(n),s=t.get(o);s?s.push(e):t.set(o,[e])}),Array.from(t.entries()).map(([e,t])=>({label:e,options:t}))}setGroupedItems(e){this._destroyGuardedVirtualizer(),this._rebuildItemRegistry(e.flatMap(e=>e.options)),this._state.groupedItems=e,this._renderOptions(),this._state.searchQuery||this._isActivelyEditingSearchInput()||this._updateInputDisplay()}getSelectedItems(){return this._ensureRegistryCurrent(),this._getSelectedEntries().map(e=>e.item)}get loadedItems(){return this._state.loadedItems}getSelectedValues(){return this.getSelectedItems().map(e=>this._getItemValue(e))}async setSelectedValues(e){if(this._config.serverSide.enabled&&this._config.serverSide.fetchSelectedItems)await this._loadSelectedItemsByValues(e);else{this._ensureRegistryCurrent();const t=this._itemRegistry.records.filter(t=>arrayIncludesValue(e,t.value)&&!this._isOptionSelectionBlocked(t.item));this._requestSelectionReplacement(t,"external-value-sync","setSelectedValues"),this._renderOptions(),this._updateInputDisplay(),this._emitChange()}}async _loadSelectedItemsByValues(e){if(!this._config.serverSide.fetchSelectedItems)return;this._setBusy(!0);const t=++this._asyncGeneration;try{const i=await this._config.serverSide.fetchSelectedItems(e);if(t!==this._asyncGeneration||!this.isConnected)return;const n=createItemRegistry(i,this._itemAdapter,{duplicateKeyPolicy:this._getDuplicateKeyPolicy()});this._requestSelectionReplacement(n.records,"external-value-sync","fetched selected items"),this._renderOptions(),this._updateInputDisplay(),this._emitChange(),this._config.scrollToSelected.enabled&&this._scrollToSelected()}catch(e){if(t!==this._asyncGeneration||!this.isConnected)return;this._handleError(e)}finally{t===this._asyncGeneration&&this.isConnected&&this._setBusy(!1)}}clear(){this._ensureRegistryCurrent(),this._dispatchSelection({type:"CLEAR_SELECTION_REQUEST",reason:"programmatic"},"clear"),this._renderOptions(),this._updateInputDisplay(),this._emitChange(),this._syncClearControlState()}clearSearch(){this._state.searchQuery="",this._config.searchable&&(this._input.value="",this._state.selectedIndices.size>0&&this._updateInputDisplay()),this._renderOptions(),this._syncClearControlState()}open(){this._handleOpen()}close(){this._handleClose()}updateConfig(e){this._invalidateGuardedMeasurements();const t=this._config.selection.mode,i=this._config.enabled,n=this._dataLoadingConfig,{dataLoading:o,callbacks:s,...r}=e,a={...r};let l;if(null!=s){const e=s;Object.prototype.hasOwnProperty.call(e,"onDataLoadingConfigError")&&(this._dataLoadingConfigErrorCallback=e.onDataLoadingConfigError),Object.prototype.hasOwnProperty.call(e,"onDataRequestCancel")&&(this._dataRequestCancelCallback=e.onDataRequestCancel),Object.prototype.hasOwnProperty.call(e,"onDataProjection")&&(this._dataProjectionCallback=e.onDataProjection);const t={...e};delete t.onDataLoadingConfigError,delete t.onDataRequestCancel,delete t.onDataProjection,a.callbacks=t}if(this._config=this._mergeConfig(this._config,a),void 0!==o){const e=null!==o&&"object"==typeof o?Object.getPrototypeOf(o):void 0,t=e===Object.prototype||null===e?{...this._dataLoadingConfig,...o}:o,i=validateDataLoadingConfig(t);if(i.valid)this._dataLoadingConfig=i.value,this._hasLastInvalidDataLoadingCandidate=!1,this._lastInvalidDataLoadingCandidate=void 0;else{const e=createInvalidDataLoadingCandidateSignature(t,i.issues);this._hasLastInvalidDataLoadingCandidate&&this._lastInvalidDataLoadingCandidate&&invalidDataLoadingSignaturesEqual(this._lastInvalidDataLoadingCandidate,e)||(this._hasLastInvalidDataLoadingCandidate=!0,this._lastInvalidDataLoadingCandidate=e,l={issues:i.issues})}}this._rebuildItemRegistry(),i!==this._config.enabled&&(this._input.disabled=!this._config.enabled,!this._config.enabled&&this._state.isOpen&&this._handleClose("disabled"),this._runEngineEffects(this._engine.dispatch({type:"DISABLED_CHANGED",disabled:!this._config.enabled}))),t!==this._config.selection.mode&&this._config.limitations?.autoMitigateRuntimeModeSwitch?(this.clear(),this._track("limitation","runtimeModeSwitchMitigated",{from:t,to:this._config.selection.mode})):t!==this._config.selection.mode&&this._track("limitation","runtimeModeSwitchDetected",{from:t,to:this._config.selection.mode}),this._input&&(this._input.readOnly=!this._config.searchable,this._syncComboboxAccessibility(),0===this._state.selectedIndices.size&&(this._input.placeholder=this._config.placeholder||"Select an option...")),this._clearControl&&this._clearControl.setAttribute("aria-label",this._config.clearControl.ariaLabel||"Clear selection and search"),this._clearControlIcon&&(this._config.clearControl.icon?this._clearControlIcon.textContent=this._config.clearControl.icon:this._clearControlIcon.innerHTML='<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 4L4 12M4 4L12 12" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>'),this._syncStyleConfigVariables(),this._syncListboxAccessibility(),this.isConnected?(this._syncDirectionConfig(),this._syncInputContainerMode(),this._syncMultiSelectDisplayConfig(),this._syncDropdownPlacement(),this._initializeObservers(),this._syncClearControlState(),this._isActivelyEditingSearchInput()||this._updateInputDisplay(),this._renderOptions()):(this._syncInputContainerMode(),this._syncMultiSelectDisplayConfig(),this._syncClearControlState(),this._isActivelyEditingSearchInput()||this._updateInputDisplay()),this._acknowledgedSearchMode=this._dataLoadingConfig.searchMode,"legacy"===this._dataLoadingConfig.protocol&&(this._acknowledgedDeferredStart=!1);const c=this._dataRequestCoordinator,d="acknowledged"===n.protocol&&"legacy"===this._dataLoadingConfig.protocol,h=n.protocol!==this._dataLoadingConfig.protocol||n.searchMode!==this._dataLoadingConfig.searchMode||n.paginationMode!==this._dataLoadingConfig.paginationMode;if(c&&d){if(this._acknowledgedReady&&!this._acknowledgedProjectionPending&&!this._acknowledgedProjectionSettling){const e=c.updateConfig(this._createCoordinatorConfig());"accepted"===e.status&&this._dispatchAcknowledgedActions(e.actions)}this._acknowledgedReady=!1,this._dispatchAcknowledgedActions(c.disconnect()),this._acknowledgedProjectionPending||this._acknowledgedProjectionSettling?this._clearAcknowledgedCoordinatorAfterProjection=!0:(this._dataRequestCoordinator=null,this._acknowledgedSearchMode=null,this._state.isBusy=!1,this._state.isSearching=!1,this._syncListboxAccessibility(),this._renderOptions())}else if(c&&"acknowledged"===this._dataLoadingConfig.protocol)if(this._clearAcknowledgedCoordinatorAfterProjection=!1,this._acknowledgedProjectionPending||this._acknowledgedProjectionSettling)this._acknowledgedConfigUpdatePending=!0,this._acknowledgedDeferredModeChange||(this._acknowledgedDeferredModeChange=h);else if(this._acknowledgedReady){const e=c.updateConfig(this._createCoordinatorConfig());if("accepted"===e.status){this._dispatchAcknowledgedActions(e.actions);const t=c.getSnapshot();this._state.isBusy=t.busy,this._state.isSearching="search"===t.activeRequest?.kind,this._syncListboxAccessibility(),e.actions.every(e=>"request"!==e.type)&&this._renderOptions()}}if(l){this._emit("dataLoadingConfigError",l);try{this._dataLoadingConfigErrorCallback?.(l)}catch(e){this._handleError(e)}}}startDataLoading(){const e=Boolean(this._dataRequestCoordinator&&this._acknowledgedProjectionPending);if("acknowledged"!==this._dataLoadingConfig.protocol&&!e)return;if("acknowledged"===this._dataLoadingConfig.protocol&&!this._ensureDataRequestCoordinator())return;if(!this.isConnected)return void(this._hasEverConnected||(this._acknowledgedDeferredStart=!0));if(this._acknowledgedReady)return;if(this._acknowledgedStartTask)return void(this._acknowledgedDeferredStart=!0);const t=this._startAcknowledgedDataLoading();this._acknowledgedStartTask=t,t.finally(()=>{this._acknowledgedStartTask===t&&(this._acknowledgedStartTask=null,this._acknowledgedDeferredStart&&this.isConnected&&(this._acknowledgedDeferredStart=!1,this.startDataLoading()))}).catch(e=>this._handleError(e))}getDataLoadingState(){const e=this._dataRequestCoordinator;if(!e){const e="remote"===this._dataLoadingConfig.searchMode||"hybrid"===this._dataLoadingConfig.searchMode,t="cursor"===this._dataLoadingConfig.paginationMode?{mode:"cursor",ordinal:1}:{mode:"page",page:e?this._dataLoadingConfig.firstPage:(this._config.infiniteScroll.initialPage??1)+1};return{status:"idle",connected:this.isConnected,busy:!1,projectionPending:!1,queryGeneration:0,activeRequest:null,hasMore:"acknowledged"===this._dataLoadingConfig.protocol&&!e&&(this._config.infiniteScroll.enabled||this._config.loadMore.enabled),nextEligiblePosition:t,error:null,resourceLimit:null}}const t=e.getSnapshot(),i=t.activeRequest?{...t.activeRequest,position:{...t.activeRequest.position}}:null;return{status:t.status,connected:t.connected,busy:t.busy||this._acknowledgedProjectionPending,projectionPending:this._acknowledgedProjectionPending,queryGeneration:t.queryGeneration,activeRequest:i,hasMore:t.hasMore,nextEligiblePosition:{...t.nextEligiblePosition},error:t.error?{...t.error}:null,resourceLimit:t.resourceLimit?{...t.resourceLimit}:null}}completeDataRequest(e){const t=this._dataRequestCoordinator;if(!t){const t=e;return null!==t&&"object"==typeof t&&"requestId"in t&&"string"==typeof t.requestId&&0!==t.requestId.length&&"queryGeneration"in t&&Number.isSafeInteger(t.queryGeneration)&&!(t.queryGeneration<0)&&"status"in t&&"string"==typeof t.status&&["succeeded","empty","exhausted","failed","cancelled"].includes(t.status)?"unknown-request":"invalid"}const i=e&&"object"==typeof e?e:null,n=t.getSnapshot().activeRequest,o=n&&i?.requestId===n.requestId&&i?.queryGeneration===n.queryGeneration?n:null,s=i?.status,r="succeeded"===s||"exhausted"===s||"empty"===s&&"next"===i?.advance,a=t.completeDataRequest(e);if("accepted"===a&&o)this._acknowledgedLastRequest=o,this._acknowledgedProjectionRequest=o,this._acknowledgedProjectionAttempt=0,this._acknowledgedProjectionCommitsPosition=r,this._projectAcknowledgedSnapshot(t.getSnapshot(),o,r);else if("resource-limit"===a){const e=t.getSnapshot().resourceLimit;this._emit("diagnostic",{timestamp:Date.now(),source:"event",name:"acknowledgedDataLoadingResourceLimit",detail:e})}return a}_createCoordinatorConfig(){return{dataLoading:{...this._dataLoadingConfig},infiniteScroll:{pageSize:this._config.infiniteScroll.pageSize,initialPage:this._config.infiniteScroll.initialPage}}}_ensureDataRequestCoordinator(){if(!this._dataRequestCoordinator){const e="remote"===this._dataLoadingConfig.searchMode||"hybrid"===this._dataLoadingConfig.searchMode;try{this._dataRequestCoordinator=new DataRequestCoordinator({config:this._createCoordinatorConfig(),initialQuery:this._state.searchQuery,initialItems:this._state.loadedItems,hasMore:!e&&(this._config.infiniteScroll.enabled||this._config.loadMore.enabled)})}catch(e){const t={issues:[{path:"dataLoading",code:"invalid-value",message:`Acknowledged data loading could not start: ${e instanceof Error?e.message:String(e)}`}]};this._emit("dataLoadingConfigError",t);try{this._dataLoadingConfigErrorCallback?.(t)}catch(e){this._handleError(e)}return null}}return this._acknowledgedSearchMode=this._dataLoadingConfig.searchMode,this._dataRequestCoordinator}async _startAcknowledgedDataLoading(){const e=this._dataRequestCoordinator,t=Boolean(e&&this._acknowledgedProjectionPending);if(!e||"acknowledged"!==this._dataLoadingConfig.protocol&&!t||!this.isConnected)return;if(this._acknowledgedReady)return;if(this._acknowledgedProjectionPending){const e=this._acknowledgedProjectionTask;if(e&&await e,!this.isConnected)return;if(this._acknowledgedProjectionPending&&await this._retryAcknowledgedProjection(),!this.isConnected||this._acknowledgedProjectionPending)return}if("acknowledged"!==this._dataLoadingConfig.protocol||!this._dataRequestCoordinator)return;null!==this._acknowledgedPendingSearchQuery&&(this._state.searchQuery=this._acknowledgedPendingSearchQuery,this._input.value=this._acknowledgedPendingSearchQuery,this._acknowledgedPendingSearchQuery=null);const i=e.updateConfig(this._createCoordinatorConfig());if("accepted"!==i.status)return void(this._acknowledgedReady=!1);this._acknowledgedConfigUpdatePending=!1,this._acknowledgedDeferredModeChange=!1,this._clearAcknowledgedCoordinatorAfterProjection=!1,this._acknowledgedReady=!0,this._initializeObservers();const n=i.actions;this._dispatchAcknowledgedActions(n);const o=e.connect(this._state.searchQuery);this._dispatchAcknowledgedActions(o),0===n.length&&0===o.length&&this._renderOptions();const s=this._renderCycleId;if(!await this._waitForRenderCycle(s))throw this._acknowledgedReady=!1,new Error("Acknowledged readiness render was superseded before completion")}_mergeConfig(e,t){const i={...e},n=Object.keys(t);for(let e=0;e<n.length;e++){const o=n[e];if(!Object.prototype.hasOwnProperty.call(t,o))continue;const s=t[o];if(void 0===s)continue;const r=i[o];void 0!==s&&(s&&"object"==typeof s&&!Array.isArray(s)?i[o]=this._mergeConfig(r&&"object"==typeof r?r:{},s):i[o]=s)}return i}_handleClearControlClick(){const e=!1!==this._config.clearControl.clearSelection,t=!1!==this._config.clearControl.clearSearch,i=this._state.selectedIndices.size>0,n=this._state.searchQuery.length>0;e&&i&&this.clear(),t&&n&&this.clearSearch(),this._emit("clear",{clearedSelection:e&&i,clearedSearch:t&&n}),this._config.callbacks.onClear?.({clearedSelection:e&&i,clearedSearch:t&&n}),this._applyFocusIntent("input","clear-control-complete")}_syncClearControlState(){if(!this._clearControl||!this._inputContainer||!this._arrowContainer)return;const e=!0===this._config.clearControl.enabled,t=this._state.selectedIndices.size>0,i=(this._acknowledgedPendingSearchQuery??this._state.searchQuery).length>0,n=!1!==this._config.clearControl.clearSelection,o=!1!==this._config.clearControl.clearSearch,s=n&&t||o&&i,r=!1!==this._config.clearControl.hideWhenEmpty,a=e&&(!r||s);this._inputContainer.classList.toggle("has-clear-control",a),this._arrowContainer.classList.toggle("with-clear-control",a),this._clearControl.hidden=!a,this._clearControl.disabled=!s,this._clearControl.setAttribute("aria-hidden",String(!a))}setError(e){this._hasError=!0,this._errorMessage=e,this._errorDescription&&(this._errorDescription.textContent=e),this._syncComboboxAccessibility(),this._announce(`Error: ${e}`)}clearError(){this._hasError=!1,this._errorMessage="",this._errorDescription&&(this._errorDescription.textContent=""),this._syncComboboxAccessibility()}setRequired(e){e?this._input.setAttribute("required",""):this._input.removeAttribute("required"),this._syncEngineSelectionConfig(),this._syncComboboxAccessibility()}validate(){return this._input.hasAttribute("required")&&0===this._state.selectedIndices.size?(this.setError("Selection is required"),!1):(this.clearError(),!0)}_deriveVirtualizationScope(e){const t=e.map(e=>this._itemRegistry.indexToKey.get(e)).filter(e=>void 0!==e);return{dataKeys:this._itemRegistry.records.map(e=>e.key),filteredKeys:t,registeredKeys:Array.from(this._engine.state.registeredKeys),windowKeys:this._renderPlan.intendedRenderKeys.slice(),mountedKeys:this._getMountedVirtualizationKeys(this._optionsContainer.children),selectedKeys:new Set(this._engine.state.selectedKeys),activeKey:this._engine.state.activeKey}}_getMountedVirtualizationKeys(e){return Array.from(e).filter(e=>e instanceof HTMLElement&&(e.hasAttribute("data-sm-selectable")||e.hasAttribute("data-selectable"))).map(e=>Number(e.getAttribute("data-sm-index")??e.getAttribute("data-index"))).filter(Number.isInteger).map(e=>this._itemRegistry.indexToKey.get(e)).filter(e=>void 0!==e)}_refreshMountedVirtualizationScope(){this._virtualizationScope={...this._virtualizationScope,mountedKeys:this._getMountedVirtualizationKeys(this._optionsContainer.children),registeredKeys:Array.from(this._engine.state.registeredKeys),selectedKeys:new Set(this._engine.state.selectedKeys),activeKey:this._engine.state.activeKey}}_appendMountedVirtualizationTargets(e){const t=this._getMountedVirtualizationKeys(e);this._virtualizationScope={...this._virtualizationScope,mountedKeys:[...new Set([...this._virtualizationScope.mountedKeys,...t])],registeredKeys:Array.from(this._engine.state.registeredKeys),selectedKeys:new Set(this._engine.state.selectedKeys),activeKey:this._engine.state.activeKey}}_createLegacyRenderPlan(e){const t=[...e],i=t.map(e=>this._itemRegistry.indexToKey.get(e)).filter(e=>void 0!==e),n=new Map;return i.forEach((e,t)=>n.set(e,t)),{mode:"legacy-full",filteredIndices:t,filteredKeys:i,intendedRenderKeys:i.slice(),filteredIndexByKey:n}}_createVirtualRenderPlan(e,t){const i=this._renderPlan.filteredKeys.slice(),n=computeWindowKeys(i,e,t);return{mode:"virtual-window",filteredIndices:n.map(e=>this._itemRegistry.keyToIndex.get(e)).filter(e=>void 0!==e),filteredKeys:i,intendedRenderKeys:n,filteredIndexByKey:new Map(this._renderPlan.filteredIndexByKey)}}_ensureGuardedVirtualizer(e){return null!==this._guardedVirtualizer&&(e.length!==this._guardedVirtualizerKeys.length||e.some((e,t)=>!Object.is(e,this._guardedVirtualizerKeys[t])))&&this._destroyGuardedVirtualizer(!0),this._guardedVirtualizer||(this._guardedVirtualizer=new Virtualizer(document.createElement("div"),e.length,e=>this._renderPlan.filteredKeys[e],{estimatedItemHeight:this._resolveGuardedEstimatedItemHeight(),buffer:0,measurementThreshold:0}),this._guardedVirtualScrollTop=this._optionsContainer.scrollTop,this._guardedVirtualViewportHeight=this._resolveGuardedViewportHeight(),this._optionsContainer.addEventListener("scroll",this._onGuardedVirtualScroll,{passive:!0}),this._guardedScrollListenerAttached=!0),this._guardedVirtualizerKeys=[...e],this._guardedVirtualizer}_resolveGuardedEstimatedItemHeight(){const e=this._config.estimatedItemHeight;if("number"==typeof e&&Number.isFinite(e)&&e>0)return e;const t=this._optionsContainer.querySelector('[part="option"]'),i=t?.getBoundingClientRect().height||t?.offsetHeight;return"number"==typeof i&&Number.isFinite(i)&&i>0?i:48}_resolveGuardedViewportHeight(){return[this._optionsContainer.clientHeight,this._optionsContainer.getBoundingClientRect().height].find(e=>Number.isFinite(e)&&e>0)??0}_clampGuardedScrollPosition(e,t){if(!this._guardedVirtualizer)return 0;const i=this._guardedVirtualizer.cumulativeOffset(e),n=Math.max(0,i-t),o=Math.min(Math.max(0,this._guardedVirtualScrollTop),n);return this._guardedVirtualScrollTop=o,this._optionsContainer.scrollTop!==o&&(this._optionsContainer.scrollTop=o),o}_createGuardedSpacer(e,t){const i=document.createElement("div");return i.setAttribute("data-virtual-spacer",e),i.setAttribute("aria-hidden","true"),i.setAttribute("role","presentation"),i.style.height=`${Number.isFinite(t)?Math.max(0,t):0}px`,i.style.minHeight="0",i.style.flex="0 0 auto",i.style.pointerEvents="none",i}_appendGuardedTopSpacer(){const e=this._guardedVirtualizer,t=this._guardedVirtualWindow;e&&t&&this._optionsContainer.appendChild(this._createGuardedSpacer("top",e.cumulativeOffset(t.startIndex)))}_appendGuardedBottomSpacer(){const e=this._guardedVirtualizer,t=this._guardedVirtualWindow;if(!e||!t)return;const i=e.cumulativeOffset(this._renderPlan.filteredKeys.length),n=e.cumulativeOffset(t.endIndex);this._optionsContainer.appendChild(this._createGuardedSpacer("bottom",Math.max(0,i-n)))}_resolveGuardedOverscan(){return 2}_applyGuardedWindowUpdate(e,t=0){if(!this._guardedVirtualizer)return!1;this._guardedVirtualScrollTop=e.scrollTop,this._guardedVirtualViewportHeight=e.viewportHeight;const i=this._renderPlan.filteredKeys.length,n={startIndex:Math.max(0,e.window.startIndex-t),endIndex:Math.min(i,e.window.endIndex+1+t)},o=this._guardedVirtualWindow?.startIndex!==n.startIndex||this._guardedVirtualWindow?.endIndex!==n.endIndex;return this._guardedVirtualWindow=n,o}_scheduleGuardedVirtualWindowUpdate(){this._guardedVirtualizer&&null===this._guardedVirtualWindowRafId&&(this._guardedVirtualWindowRafId=this._requestLifecycleFrame(()=>{this._guardedVirtualWindowRafId=null;const e=this._guardedVirtualizer;if(!e)return;const t=e.updateWindow(this._optionsContainer.scrollTop,this._resolveGuardedViewportHeight());this._guardedVirtualOverscan=this._resolveGuardedOverscan(),t&&this._applyGuardedWindowUpdate(t,this._guardedVirtualOverscan)&&this._renderOptions()}))}_cancelGuardedVirtualWindowUpdate(){null!==this._guardedVirtualWindowRafId&&(cancelAnimationFrame(this._guardedVirtualWindowRafId),this._lifecycleRafs.delete(this._guardedVirtualWindowRafId),this._guardedVirtualWindowRafId=null)}_applyGuardedScrollResult(e){if(!e||!this._guardedVirtualizer)return!1;this._guardedVirtualScrollTop=e.scrollTop,this._optionsContainer.scrollTop=e.scrollTop;const t=this._guardedVirtualizer.updateWindow(this._guardedVirtualScrollTop,this._guardedVirtualViewportHeight);return!!t&&(this._guardedVirtualWindow={startIndex:t.window.startIndex,endIndex:t.window.endIndex+1},this._guardedVirtualOverscan=0,!0)}_enableAcknowledgedDataLoadingForTest(e,t={}){if(this._dataRequestCoordinator)throw new Error("Acknowledged data loading is already enabled for this test instance");const i=e.dataLoading;this._dataLoadingConfig={protocol:i?.protocol??"acknowledged",searchMode:i?.searchMode??"local",paginationMode:i?.paginationMode??"page",firstPage:i?.firstPage??1,...void 0===i?.fetchLimit?{}:{fetchLimit:i.fetchLimit}},this._acknowledgedSearchMode=e.dataLoading?.searchMode??"local",this._dataRequestCoordinator=new DataRequestCoordinator({config:e,initialQuery:this._state.searchQuery,initialItems:this._state.loadedItems,hasMore:t.hasMore}),this._acknowledgedReady=!1,this.isConnected&&this._initializeObservers()}async _setAcknowledgedDataLoadingReadyForTest(){if(!this._dataRequestCoordinator)throw new Error("Enable acknowledged data loading before readiness");if(!this.isConnected)throw new Error("Acknowledged readiness requires a connected test element");if(this._acknowledgedReady)return;if(this._acknowledgedProjectionPending){const e=this._acknowledgedProjectionTask;if(e&&await e,this._acknowledgedProjectionPending&&await this._retryAcknowledgedProjectionForTest(),this._acknowledgedProjectionPending)throw new Error("Acknowledged readiness cannot open while snapshot projection is pending")}null!==this._acknowledgedPendingSearchQuery&&(this._state.searchQuery=this._acknowledgedPendingSearchQuery,this._input.value=this._acknowledgedPendingSearchQuery,this._acknowledgedPendingSearchQuery=null),this._acknowledgedReady=!0,this._initializeObservers();const e=this._dataRequestCoordinator.connect(this._state.searchQuery);this._dispatchAcknowledgedActions(e),0===e.length&&this._renderOptions();const t=this._renderCycleId;if(!await this._waitForRenderCycle(t))throw this._acknowledgedReady=!1,new Error("Acknowledged readiness render was superseded before completion")}_dispatchAcknowledgedActions(e){for(const t of e){if("cancel"===t.type){this._dispatchAcknowledgedEvent("dataRequestCancel",t.notification);try{this._dataRequestCancelCallback?.(t.notification)}catch(e){this._handleError(e)}continue}const e=t.request,i=this._dataRequestCoordinator;if(i&&this._acknowledgedReady&&("loadMore"===e.kind?(this._state.lastScrollPosition=this._optionsContainer.scrollTop,this._acknowledgedProjectionScrollTop=this._state.lastScrollPosition,this._state.preserveScrollPosition=!0,this._state.isSearching=!1):(this._acknowledgedProjectionScrollTop=0,this._state.preserveScrollPosition=!1,this._state.isSearching=!0),this._state.isBusy=!0,this._acknowledgedLastRequest=e,this._syncListboxAccessibility(),this._renderOptions(),"loadMore"===e.kind&&(this._optionsContainer.scrollTop=this._state.lastScrollPosition),i.markNotificationsDispatched(e.requestId)))if("search"===e.kind){const t={query:e.query,results:[],count:0,request:e};this._dispatchAcknowledgedEvent("search",t);try{const t=this._config.callbacks.onSearch;t?.(e.query,e)}catch(e){this._handleError(e)}}else{const t="page"===e.position.mode?e.position.page:e.position.ordinal,i={page:t,items:[],request:e};this._dispatchAcknowledgedEvent("loadMore",i);try{const i=this._config.callbacks.onLoadMore;i?.(t,e)}catch(e){this._handleError(e)}}}}_dispatchAcknowledgedEvent(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0})),this._track("event",e,t)}async _completeDataRequestForTest(e){const t=this.completeDataRequest(e);return"accepted"!==t||await this._acknowledgedProjectionTask,t}_failNextAcknowledgedProjectionForTest(e="before-publish"){this._acknowledgedProjectionFailureStageForTest=e}_retryAcknowledgedProjectionForTest(){return this._retryAcknowledgedProjection()}_retryAcknowledgedProjection(){return this._dataRequestCoordinator&&this._acknowledgedProjectionPending?this._projectAcknowledgedSnapshot(this._dataRequestCoordinator.getSnapshot(),this._acknowledgedProjectionRequest??this._acknowledgedLastRequest,this._acknowledgedProjectionCommitsPosition):Promise.resolve()}_projectAcknowledgedSnapshot(e,t,i){if(this._acknowledgedProjectionRunning)return this._acknowledgedProjectionTask??Promise.resolve();this._acknowledgedProjectionRequest=t??this._acknowledgedProjectionRequest,this._acknowledgedProjectionAttempt+=1,this._acknowledgedProjectionPending=!0;const n=Array.from(e.items);let o,s;try{if(o=createItemRegistry(n,this._itemAdapter,{duplicateKeyPolicy:this._getDuplicateKeyPolicy()}),s=this._groupItemsByProperty(n),"before-publish"===this._acknowledgedProjectionFailureStageForTest)throw this._acknowledgedProjectionFailureStageForTest=null,new Error("Injected acknowledged projection failure before publication")}catch(i){return this._syncListboxAccessibility(),this._recordAcknowledgedProjectionFailure(e,t,i),Promise.resolve()}this._acknowledgedProjectionRunning=!0;const r=this._applyAcknowledgedSnapshot(e,t,i,n,o,s).finally(()=>{this._acknowledgedProjectionTask===r&&(this._acknowledgedProjectionRunning=!1,this._acknowledgedProjectionTask=null)});return this._acknowledgedProjectionTask=r,r}async _applyAcknowledgedSnapshot(e,t,i,n,o,s){let r=!1;try{if(this._rebuildItemRegistry(n,o),this._state.groupedItems=s,i&&t&&(this._state.currentPage=e.lastCommittedPage??("page"===t.position.mode?t.position.page:t.position.ordinal)),this._state.isSearching=!1,this._state.isBusy=!0,this._state.lastScrollPosition=this._acknowledgedProjectionScrollTop,this._state.preserveScrollPosition="loadMore"===t?.kind,r=!0,"after-publish"===this._acknowledgedProjectionFailureStageForTest)throw this._acknowledgedProjectionFailureStageForTest=null,new Error("Injected acknowledged projection failure after publication");this._state.searchQuery||null!==this._acknowledgedPendingSearchQuery||this._isActivelyEditingSearchInput()||this._updateInputDisplay(),this._syncListboxAccessibility(),this._renderOptions();const a=this._renderCycleId;if(!await this._waitForRenderCycle(a))throw new Error("Acknowledged snapshot render was superseded before completion");this._state.isBusy=e.busy,e.busy||(this._optionsContainer.querySelector(".busy-bucket")?.remove(),this._shouldRenderLoadMoreTrigger()&&this._addLoadMoreTrigger()),this._optionsContainer.scrollTop=this._acknowledgedProjectionScrollTop,this._syncListboxAccessibility(),this._syncRenderedOptionAccessibility(),this._syncLegacyActiveAria(),this._state.preserveScrollPosition=!1,this._acknowledgedProjectionPending=!1,this._acknowledgedProjectionDiagnostic=null,this._acknowledgedProjectionSettling=!0;try{this._dispatchDataProjectionNotification({requestId:this._acknowledgedProjectionRequest?.requestId??t?.requestId??"unknown",queryGeneration:this._acknowledgedProjectionRequest?.queryGeneration??e.queryGeneration,attempt:this._acknowledgedProjectionAttempt,status:"complete"})}finally{this._acknowledgedProjectionSettling=!1}this._clearAcknowledgedCoordinatorAfterProjection?(this._dataRequestCoordinator=null,this._acknowledgedSearchMode=null,this._clearAcknowledgedCoordinatorAfterProjection=!1,this._acknowledgedProjectionRequest=null):this._acknowledgedProjectionRequest=null,this._finishAcknowledgedProjectionSettlement()}catch(i){r&&(this.isConnected&&(this._state.isBusy=!0),this._state.isSearching=!1,this._syncListboxAccessibility()),this._acknowledgedProjectionPending=!0,this._recordAcknowledgedProjectionFailure(e,t,i)}}_recordAcknowledgedProjectionFailure(e,t,i){const n=i instanceof Error?i.message:String(i),o={requestId:this._acknowledgedProjectionRequest?.requestId??t?.requestId??"unknown",queryGeneration:this._acknowledgedProjectionRequest?.queryGeneration??e.queryGeneration,message:n};this._acknowledgedProjectionDiagnostic=o,this._emit("diagnostic",{timestamp:Date.now(),source:"event",name:"acknowledgedProjectionFailed",detail:o}),"unknown"!==o.requestId&&this._dispatchDataProjectionNotification({requestId:o.requestId,queryGeneration:o.queryGeneration,attempt:this._acknowledgedProjectionAttempt,status:"failed",error:{message:n}})}_dispatchDataProjectionNotification(e){this._dispatchAcknowledgedEvent("dataProjection",e);try{this._dataProjectionCallback?.(e)}catch(e){this._handleError(e)}}_dispatchPendingAcknowledgedSearchIntent(){const e=this._acknowledgedPendingSearchQuery;null!==e&&this._acknowledgedReady&&this.isConnected&&(this._acknowledgedPendingSearchQuery=null,this._handleSearch(e))}_finishAcknowledgedProjectionSettlement(){const e=this._dataRequestCoordinator,t=this._acknowledgedPendingSearchQuery;if("acknowledged"!==this._dataLoadingConfig.protocol||!e)return this._acknowledgedConfigUpdatePending=!1,this._acknowledgedDeferredModeChange=!1,void("legacy"===this._dataLoadingConfig.protocol&&null!==t&&this.isConnected?(this._acknowledgedPendingSearchQuery=null,this._handleSearch(t)):this._dispatchPendingAcknowledgedSearchIntent());if(this.isConnected&&this._acknowledgedReady){if(this._acknowledgedConfigUpdatePending){const i=this._acknowledgedDeferredModeChange&&null!==t;i&&this._dispatchAcknowledgedActions(e.disconnect());const n=e.updateConfig(this._createCoordinatorConfig());if("accepted"!==n.status)return void(this._acknowledgedReady=!1);if(this._acknowledgedConfigUpdatePending=!1,this._acknowledgedDeferredModeChange=!1,i&&null!==t)return this._acknowledgedPendingSearchQuery=null,this._state.searchQuery=t,this._input.value=t,this._dispatchAcknowledgedActions(e.setQuery(t)),this._dispatchAcknowledgedActions(e.connect(t)),this._syncListboxAccessibility(),void this._handleSearch(t);this._dispatchAcknowledgedActions(n.actions);const o=e.getSnapshot();this._state.isBusy=o.busy,this._state.isSearching="search"===o.activeRequest?.kind,this._syncListboxAccessibility()}this._dispatchPendingAcknowledgedSearchIntent()}}_updateGuardedVirtualWindow(e,t){this._guardedVirtualizationRequested=!0;const i=this._ensureGuardedVirtualizer(this._renderPlan.filteredKeys);this._guardedVirtualScrollTop=e,this._guardedVirtualViewportHeight=t;const n=i.updateWindow(e,t);return!!n&&(this._guardedVirtualOverscan=0,this._applyGuardedWindowUpdate(n,this._guardedVirtualOverscan),this._optionsContainer.scrollTop=n.scrollTop,!0)}_destroyGuardedVirtualizer(e=!1){this._cancelGuardedVirtualWindowUpdate(),this._guardedMeasurementGeneration+=1,this._guardedScrollListenerAttached&&(this._optionsContainer.removeEventListener("scroll",this._onGuardedVirtualScroll),this._guardedScrollListenerAttached=!1),this._guardedVirtualizer?.destroy(),this._guardedVirtualizer=null,this._teardownGuardedOptionResizeObserver(),e||(this._guardedVirtualizationRequested=!1),this._guardedVirtualizerKeys=[],this._guardedVirtualWindow=null,this._guardedVirtualScrollTop=0,this._guardedVirtualViewportHeight=0,this._guardedVirtualOverscan=0}_invalidateGuardedMeasurements(){this._guardedVirtualizer&&this._destroyGuardedVirtualizer(!0)}_createGuardedOptionResizeObserver(e){"undefined"!=typeof ResizeObserver&&(this._guardedOptionResizeObserver=new ResizeObserver(t=>{if(e!==this._guardedMeasurementGeneration||!this._guardedVirtualizer||!this._guardedVirtualizationRequested||!this.isConnected)return;const i=this._guardedVirtualizer,n=this._optionsContainer.scrollTop,o=this._resolveGuardedViewportHeight(),s=this._captureGuardedScrollAnchor(i,n,o);let r=!1;for(const n of t){const t=n.target;if(!(t instanceof HTMLElement&&this._guardedObservedOptions.has(t)))continue;if(!t.isConnected||!this._optionsContainer.contains(t))continue;const o=this._guardedOptionMeasurements.get(t);if(!o||o.generation!==e)continue;const s=Number(t.getAttribute("data-index"));if(!Number.isInteger(s)||!Object.is(this._itemRegistry.indexToKey.get(s),o.key))continue;const a=this._renderPlan.filteredIndexByKey.get(o.key);if(void 0===a||a!==o.index)continue;const l=n.borderBoxSize?.[0]?.blockSize,c="number"==typeof l?l:n.contentRect.height;!Number.isFinite(c)||c<=0||(r=i.measureItem(o.index,c)||r)}if(!r)return;if(s){const e=this._renderPlan.filteredIndexByKey.get(s.key);if(void 0!==e){const t=Math.max(0,i.cumulativeOffset(e)+s.offset);this._guardedVirtualScrollTop=t,this._optionsContainer.scrollTop=t}}const a=i.updateWindow(this._optionsContainer.scrollTop,o);a&&this._applyGuardedWindowUpdate(a,this._guardedVirtualOverscan),this._renderOptions()}))}_captureGuardedScrollAnchor(e,t,i){const n=this._optionsContainer.getBoundingClientRect().top+this._optionsContainer.clientTop,o=n+i,s=Array.from(this._guardedObservedOptions).map(e=>({option:e,rect:e.getBoundingClientRect()})).filter(({rect:e})=>e.height>0&&e.bottom>n&&e.top<o).sort((e,t)=>e.rect.top-t.rect.top)[0],r=s?this._guardedOptionMeasurements.get(s.option):void 0;if(r&&r.generation===this._guardedMeasurementGeneration)return{key:r.key,offset:t-e.cumulativeOffset(r.index)};if(0===this._renderPlan.filteredKeys.length)return null;const a=e.computeWindow(t,0).startIndex,l=this._renderPlan.filteredKeys[a];return void 0===l?null:{key:l,offset:t-e.cumulativeOffset(a)}}_syncGuardedOptionResizeTargets(){if(!this._guardedVirtualizer||!this._guardedVirtualizationRequested||!this.isConnected)return;const e=[];for(const t of Array.from(this._optionsContainer.children)){if(!(t instanceof HTMLElement&&t.hasAttribute("data-index")))continue;const i=Number(t.getAttribute("data-index"));if(!Number.isInteger(i))continue;const n=this._itemRegistry.indexToKey.get(i),o=void 0===n?void 0:this._renderPlan.filteredIndexByKey.get(n);void 0!==n&&void 0!==o&&e.push({option:t,key:n,index:o})}e.some(({option:e})=>this._guardedObserverSeenOptions.has(e))&&this._guardedOptionResizeObserver&&(this._guardedMeasurementGeneration+=1,this._teardownGuardedOptionResizeObserver()),this._guardedOptionResizeObserver||this._createGuardedOptionResizeObserver(this._guardedMeasurementGeneration);const t=this._guardedOptionResizeObserver;if(!t)return;const i=new Set;for(const{option:n,key:o,index:s}of e)i.add(n),this._guardedOptionMeasurements.set(n,{key:o,index:s,generation:this._guardedMeasurementGeneration}),this._guardedObservedOptions.has(n)||(t.observe(n),this._guardedObserverSeenOptions.add(n));for(const e of this._guardedObservedOptions)i.has(e)||t.unobserve(e);this._guardedObservedOptions=i}_teardownGuardedOptionResizeObserver(){for(const e of this._guardedObservedOptions)this._guardedOptionResizeObserver?.unobserve(e);this._guardedObservedOptions.clear(),this._guardedObserverSeenOptions=new WeakSet,this._guardedOptionResizeObserver?.disconnect(),this._guardedOptionResizeObserver=null,this._guardedOptionMeasurements=new WeakMap}_materializeGuardedVirtualKey(e){if(!this._guardedVirtualizer)return!1;if(void 0===this._renderPlan.filteredIndexByKey.get(e))return!1;this._ensureGuardedVirtualizer(this._renderPlan.filteredKeys);const t=this._guardedVirtualizer.scrollToKey(e,e=>this._renderPlan.filteredIndexByKey.get(e));return!!this._applyGuardedScrollResult(t)&&(this._renderOptions(),!0)}_refreshVirtualizationScope(e){this._virtualizationScope=this._deriveVirtualizationScope(e)}_renderOptions(){this._ensureRegistryCurrent();const e=this._optionsContainer.scrollTop;this._renderCycleId+=1;const t=this._renderCycleId;this._resolvePendingRenderCycles(!1,t),this._guardedVirtualizer&&(this._guardedVirtualScrollTop=this._optionsContainer.scrollTop),this._loadMoreTrigger&&this._intersectionObserver&&this._intersectionObserver.unobserve(this._loadMoreTrigger),this._dataRequestCoordinator&&(this._loadMoreTrigger=void 0),this._unobserveGuardedOptionResizeTargets(),this._optionsContainer.innerHTML="";let i=[],n=null;if(Array.from(this._dropdown.children).forEach(e=>{e!==this._optionsContainer&&this._dropdown.removeChild(e)}),this._state.isOpen&&"none"===this._dropdown.style.display&&(this._dropdown.style.display="block"),this._state.isSearching){this._registerShadowItems([]),this._renderPlan=this._createLegacyRenderPlan([]),this._refreshVirtualizationScope(i),this._syncLegacyActiveAria();const e=document.createElement("div");return e.className="searching-state",e.setAttribute("part","loading"),e.textContent="Searching...",this._optionsContainer.appendChild(e),void this._resolveRenderCycle(t,!0)}const o=this._config.serverSide.getValueFromItem||(e=>e?.value??e),s=this._config.serverSide.getLabelFromItem||(e=>e?.label??String(e)),r="remote"===this._acknowledgedSearchMode?"":this._state.searchQuery.toLowerCase();if(null!==this._guardedMeasurementQuery&&this._guardedMeasurementQuery!==r&&this._invalidateGuardedMeasurements(),this._guardedMeasurementQuery=r,this._state.groupedItems.length>0&&!r)this._destroyGuardedVirtualizer(),this._renderPlan=this._createLegacyRenderPlan(this._itemRegistry.records.map(e=>e.index)),i=this._renderPlan.filteredIndices,this._registerShadowItems(i),this._refreshVirtualizationScope(i),this._state.groupedItems.forEach((e,t)=>{let i;this.groupHeaderRenderer?(i=this.groupHeaderRenderer(e,t),i instanceof HTMLElement||(i=document.createElement("div"),i.textContent=String(e.label))):(i=document.createElement("div"),i.textContent=e.label),i.classList.add("group-header"),this._config.styles.classNames?.groupHeader&&i.classList.add(...this._config.styles.classNames.groupHeader.split(" ").filter(Boolean)),i.hasAttribute("role")||i.setAttribute("role","presentation"),i.setAttribute("part","group-header"),this._optionsContainer.appendChild(i),e.options.forEach(e=>{const t=this._state.loadedItems.indexOf(e);-1!==t&&this._renderSingleOption(e,t,o,s)})});else{const a=[];if(this._state.loadedItems.forEach((e,t)=>{if(r)try{if(!String(s(e)).toLowerCase().includes(r))return}catch(e){return}a.push(t)}),this._renderPlan=this._createLegacyRenderPlan(a),i=this._renderPlan.filteredIndices,this._registerShadowItems(i),this._guardedVirtualizationRequested&&!this._guardedVirtualizer&&(this._ensureGuardedVirtualizer(this._renderPlan.filteredKeys),this._guardedVirtualViewportHeight=this._resolveGuardedViewportHeight(),this._guardedVirtualScrollTop=e),this._guardedVirtualizer){const e=this._ensureGuardedVirtualizer(this._renderPlan.filteredKeys),t=this._resolveGuardedViewportHeight();t>0&&(this._guardedVirtualViewportHeight=t);const i=this._clampGuardedScrollPosition(this._renderPlan.filteredKeys.length,this._guardedVirtualViewportHeight);n=i;const o=e.updateWindow(i,this._guardedVirtualViewportHeight);o?this._applyGuardedWindowUpdate(o,this._guardedVirtualOverscan):this._guardedVirtualWindow=null}this._guardedVirtualWindow&&(this._renderPlan=this._createVirtualRenderPlan(this._guardedVirtualWindow.startIndex,this._guardedVirtualWindow.endIndex));const l=this._renderPlan.filteredIndices;if(this._refreshVirtualizationScope(i),this._appendGuardedTopSpacer(),0!==l.length||this._state.isBusy){if(!this._guardedVirtualizer&&!1!==this._config.virtualize&&0===this._state.groupedItems.length&&l.length>300){const e=80;let i=0,n=0;if(this._state.selectedIndices.size>0&&this._config.scrollToSelected.enabled){const e=Array.from(this._state.selectedIndices).filter(e=>e>=0).sort((e,t)=>e-t),t="first"===this._config.scrollToSelected.multiSelectTarget?e[0]:e[e.length-1],i=l.indexOf(t);-1!==i&&(n=i+20)}const r=()=>{if(t!==this._renderCycleId)return void this._resolveRenderCycle(t,!1);const a=document.createDocumentFragment(),c=Math.min(Math.max(i+e,n),l.length);for(n=0;i<c;i+=1){const e=l[i],t=this._state.loadedItems[e];this._renderSingleOption(t,e,o,s,a)}const d=Array.from(a.children);if(this._optionsContainer.appendChild(a),this._appendMountedVirtualizationTargets(d),this._syncRenderedOptionAccessibility(),this._syncLegacyActiveAria(),i<l.length)this._requestLifecycleFrame(r);else{if(t!==this._renderCycleId)return void this._resolveRenderCycle(t,!1);!this._state.isBusy&&this._shouldRenderLoadMoreTrigger()&&this._addLoadMoreTrigger(),this._finalizePerfMarks(),this._resolveRenderCycle(t,!0)}};return void r()}l.forEach(e=>{const t=this._state.loadedItems[e];this._renderSingleOption(t,e,o,s)})}else{const e=document.createElement("div");e.setAttribute("part","no-results"),e.className="empty-state",e.textContent=r?`No results found for "${this._state.searchQuery}"`:"No options available",this._optionsContainer.appendChild(e)}this._appendGuardedBottomSpacer()}if(this._refreshMountedVirtualizationScope(),this._state.isBusy&&this._config.busyBucket.enabled){const e=document.createElement("div");if(e.setAttribute("part","loading"),e.className="busy-bucket",this._config.busyBucket.showSpinner){const t=document.createElement("div");t.className="spinner",e.appendChild(t)}if(this._config.busyBucket.message){const t=document.createElement("div");t.textContent=this._config.busyBucket.message,e.appendChild(t)}this._optionsContainer.appendChild(e)}else this._dataRequestCoordinator&&this._state.isBusy||!this._shouldRenderLoadMoreTrigger()||this._addLoadMoreTrigger();null!==n&&(this._optionsContainer.scrollTop=n),this._syncRenderedOptionAccessibility(),this._syncLegacyActiveAria(),this._syncGuardedOptionResizeTargets(),this._finalizePerfMarks(),this._resolveRenderCycle(t,!0)}_waitForRenderCycle(e){return e<this._renderCycleId?Promise.resolve(!1):e<=this._completedRenderCycleId?Promise.resolve(!0):new Promise(t=>{this._renderCycleWaiters.set(e,t);const i=window.setTimeout(()=>this._resolveRenderCycle(e,!1),12e4);this._renderCycleWaiterTimeouts.set(e,i)})}_resolveRenderCycle(e,t){t&&(this._completedRenderCycleId=Math.max(this._completedRenderCycleId,e));const i=this._renderCycleWaiters.get(e),n=this._renderCycleWaiterTimeouts.get(e);void 0!==n&&window.clearTimeout(n),this._renderCycleWaiterTimeouts.delete(e),i&&(this._renderCycleWaiters.delete(e),i(t))}_resolvePendingRenderCycles(e,t=Number.POSITIVE_INFINITY){for(const[i,n]of this._renderCycleWaiters){if(i>=t)continue;const o=this._renderCycleWaiterTimeouts.get(i);void 0!==o&&window.clearTimeout(o),this._renderCycleWaiterTimeouts.delete(i),this._renderCycleWaiters.delete(i),n(e)}}_unobserveGuardedOptionResizeTargets(){for(const e of this._guardedObservedOptions)this._guardedOptionResizeObserver?.unobserve(e);this._guardedObservedOptions.clear()}_renderSingleOption(e,t,i,n,o=this._optionsContainer){const s=this._state.selectedIndices.has(t),r=Boolean(e?.disabled),a=this._getDisabledOptionBehavior(),l=`${this._uniqueId}-option-${t}`;if(this._optionRenderer){const c=this._optionRenderer(e,t,this._rendererHelpers),d=this._normalizeCustomOptionElement(c,{index:t,value:i(e),label:n(e),selected:s,active:this._state.activeIndex===t,disabled:r,disabledBehavior:a,id:l});return d.setAttribute("dir",this._config.direction??"ltr"),void o.appendChild(d)}const c=new SelectOption({item:e,index:t,id:l,selected:s,disabled:r,disabledBehavior:a,active:this._state.activeIndex===t,getValue:i,getLabel:n,showRemoveButton:"multi"===this._config.selection.mode&&this._config.selection.showRemoveButton,removeButtonIcon:this._config.selection.removeButtonIcon,classMap:this.classMap,className:this._config.styles?.classNames?.option});this._config.styles?.classNames?.option&&c.classList.add(...this._config.styles.classNames.option.split(" ").filter(Boolean)),c.setAttribute("dir",this._config.direction??"ltr"),s&&this._config.styles?.classNames?.selectedOption&&c.classList.add(...this._config.styles.classNames.selectedOption.split(" ").filter(Boolean)),this._state.activeIndex===t&&this._config.styles?.classNames?.activeOption&&c.classList.add(...this._config.styles.classNames.activeOption.split(" ").filter(Boolean)),r&&this._config.styles.classNames?.disabledOption&&c.classList.add(...this._config.styles.classNames.disabledOption.split(" ").filter(Boolean)),c.setAttribute("part","option"),c.dataset.index=String(t),c.dataset.value=String(i(e)),c.dataset.smIndex=String(t),c.hasAttribute("data-sm-selectable")||c.toggleAttribute("data-sm-selectable",!0);const d=i(e);null!=d&&(c.dataset.smValue=String(d)),c.id=c.id||l,c.addEventListener("optionRemove",e=>{const i=e.detail,n=i?.index??t;this._handleOptionRemove(n)}),o.appendChild(c),c instanceof SelectOption&&c.ensureRendered()}_syncCustomOptionActiveClasses(e,t){const i=(this.classMap?.active??"active sm-active").split(/\s+/).filter(Boolean),n=(this._config.styles.classNames?.activeOption??"").split(/\s+/).filter(Boolean),o=[...new Set([...i,...n,"smilodon-option--active"])],s=this._customOptionManagedActiveClasses.get(e)??[];e.classList.remove(...new Set([...s,...o,"active","sm-active","smilodon-option--active"])),t&&e.classList.add(...o),this._customOptionManagedActiveClasses.set(e,o);const r=new Set((e.dataset.smState??"").split(/\s+/).filter(Boolean));t?r.add("active"):r.delete("active"),r.size?e.dataset.smState=[...r].join(" "):delete e.dataset.smState}_normalizeCustomOptionElement(e,t){const i=e instanceof HTMLElement?e:document.createElement("div");i.hasAttribute("part")||i.setAttribute("part","option"),i.classList.add("smilodon-option","option"),this._config.styles.classNames?.option&&i.classList.add(...this._config.styles.classNames.option.split(" ").filter(Boolean));const n=t.selected,o=t.active,s=t.disabled,r=s&&t.disabledBehavior.selectable,a=s&&t.disabledBehavior.hoverable,l=s&&t.disabledBehavior.focusable,c=s&&(r||a),d=(this.classMap?.selected??"selected sm-selected").split(" ").filter(Boolean),h=(this.classMap?.disabled??"disabled sm-disabled").split(" ").filter(Boolean);n?(i.classList.add(...d),i.classList.add("smilodon-option--selected"),this._config.styles.classNames?.selectedOption&&i.classList.add(...this._config.styles.classNames.selectedOption.split(" ").filter(Boolean))):(i.classList.remove(...d),i.classList.remove("smilodon-option--selected"),this._config.styles.classNames?.selectedOption&&i.classList.remove(...this._config.styles.classNames.selectedOption.split(" ").filter(Boolean))),this._syncCustomOptionActiveClasses(i,o),s?(i.classList.add(...h),i.classList.add("smilodon-option--disabled"),this._config.styles.classNames?.disabledOption&&i.classList.add(...this._config.styles.classNames.disabledOption.split(" ").filter(Boolean))):(i.classList.remove(...h),i.classList.remove("smilodon-option--disabled"),this._config.styles.classNames?.disabledOption&&i.classList.remove(...this._config.styles.classNames.disabledOption.split(" ").filter(Boolean))),i.classList.toggle("smilodon-option--disabled-interactive",c),i.classList.toggle("smilodon-option--disabled-hoverable",a),i.classList.toggle("smilodon-option--disabled-focusable",l),i.classList.toggle("smilodon-option--disabled-selectable",r);const u=[];n&&u.push("selected"),o&&u.push("active"),u.length?i.dataset.smState=u.join(" "):delete i.dataset.smState,i.hasAttribute("data-selectable")||i.setAttribute("data-selectable",""),i.hasAttribute("data-sm-selectable")||i.setAttribute("data-sm-selectable",""),i.dataset.index=String(t.index),i.dataset.value=String(t.value),i.dataset.smIndex=String(t.index),null!=t.value?i.dataset.smValue=String(t.value):delete i.dataset.smValue;const p=this._customOptionNormalizedIds.get(i);return!i.id||void 0!==p&&i.id===p?(i.id=t.id,this._customOptionNormalizedIds.set(i,t.id)):this._customOptionNormalizedIds.delete(i),i.hasAttribute("tabindex")||(i.tabIndex=-1),this._customOptionBoundElements.has(i)||this._customOptionBoundElements.add(i),this._normalizeCustomOptionAccessibility(i,{label:t.label,disabled:t.disabled}),i}_addLoadMoreTrigger(){const e=document.createElement("div");if(e.className="load-more-container",this._dataRequestCoordinator){let t;if(this._config.infiniteScroll.enabled&&Boolean(this._intersectionObserver)&&this._acknowledgedReady&&(t=this._acknowledgedSentinel??document.createElement("div"),t.className="infinite-scroll-sentinel",t.style.height="10px",t.style.width="100%",t.style.opacity="0",this._acknowledgedSentinel=t,this._loadMoreTrigger=t,e.appendChild(t)),this._config.loadMore.enabled||this._config.infiniteScroll.enabled){const i=document.createElement("button");i.className="load-more-button",i.textContent=`Load ${this._config.loadMore.itemsPerLoad} more`,i.addEventListener("click",()=>this._loadMoreItems("manual")),e.appendChild(i),t||(this._loadMoreTrigger=i)}if(this._optionsContainer.appendChild(e),t&&this._intersectionObserver)try{this._intersectionObserver.observe(t)}catch(i){this._intersectionObserver.disconnect(),this._intersectionObserver=void 0,t.remove(),this._loadMoreTrigger=e.querySelector(".load-more-button")??void 0}return}if(this._config.infiniteScroll.enabled){const t=document.createElement("div");t.className="infinite-scroll-sentinel",t.style.height="10px",t.style.width="100%",t.style.opacity="0",this._loadMoreTrigger=t,e.appendChild(t)}else{const t=document.createElement("button");t.className="load-more-button",t.textContent=`Load ${this._config.loadMore.itemsPerLoad} more`,t.addEventListener("click",()=>this._loadMoreItems()),this._loadMoreTrigger=t,e.appendChild(t)}this._optionsContainer.appendChild(e),this._intersectionObserver&&this._loadMoreTrigger&&this._intersectionObserver.observe(this._loadMoreTrigger)}_shouldRenderLoadMoreTrigger(){if(!this._config.loadMore.enabled&&!this._config.infiniteScroll.enabled)return!1;if(!("acknowledged"!==this._dataLoadingConfig.protocol||this._dataRequestCoordinator&&this._acknowledgedReady))return!1;if(!this._dataRequestCoordinator)return this._state.loadedItems.length>0;const e=this._dataRequestCoordinator.getSnapshot();return"resource-limited"!==e.status&&(e.hasMore||null!==e.error||"empty"===e.status||"failed"===e.status||"cancelled"===e.status)}}EnhancedSelect._instances=new Set,EnhancedSelect._MIRRORED_STYLES_SCOPE_CLASS="smilodon-mirrored-styles-scope",EnhancedSelect._MIRRORED_STYLESHEET_CACHE_LIMIT=32,EnhancedSelect._mirroredStylesheetTextCache=new Map,customElements.get("enhanced-select")||customElements.define("enhanced-select",EnhancedSelect);class WorkerManager{constructor(){this.worker=null,this.pending=new Map,this.supportsWorkers=!1,this.supportsSharedArrayBuffer=!1,this.nextId=0,this._fallbackOperations={transform:e=>{const{items:t,transformer:i}=e,n=new Function("item","index",`return (${i})(item, index)`);return t.map((e,t)=>n(e,t))},search:e=>{const{items:t,query:i,fuzzy:n}=e,o=i.toLowerCase(),s=[];for(let e=0;e<t.length;e++){const i=t[e],r=i,a=String(r?.label??r?.value??i).toLowerCase();if(n){let t=0;for(let e=0;e<a.length&&t<o.length;e++)a[e]===o[t]&&t++;t===o.length&&s.push({item:i,index:e})}else a.includes(o)&&s.push({item:i,index:e})}return s},filter:e=>{const{items:t,predicate:i}=e,n=new Function("item","index",`return (${i})(item, index)`);return t.filter((e,t)=>n(e,t))},sort:e=>{const{items:t,comparator:i}=e,n=new Function("a","b",`return (${i})(a, b)`);return[...t].sort(n)}},this.detectFeatures(),this.initWorker()}detectFeatures(){this.supportsWorkers="undefined"!=typeof Worker,this.supportsSharedArrayBuffer="undefined"!=typeof SharedArrayBuffer}initWorker(){if(this.supportsWorkers)try{const e=this.generateWorkerCode(),t=new Blob([e],{type:"application/javascript"}),i=URL.createObjectURL(t);this.worker=new Worker(i),this.worker.onmessage=this.handleMessage.bind(this),this.worker.onerror=this.handleError.bind(this),URL.revokeObjectURL(i)}catch(e){console.warn("Worker initialization failed, falling back to main thread",e),this.worker=null}}generateWorkerCode(){return"\n // Worker code\n self.onmessage = function(e) {\n const start = performance.now();\n const { id, type, payload } = e.data;\n \n // Lookup object for O(1) operation dispatch\n const operations = {\n 'transform': handleTransform,\n 'search': handleSearch,\n 'filter': handleFilter,\n 'sort': handleSort,\n };\n \n try {\n const handler = operations[type];\n if (!handler) {\n throw new Error('Unknown operation: ' + type);\n }\n \n const result = handler(payload);\n const duration = performance.now() - start;\n \n self.postMessage({\n id,\n success: true,\n data: result,\n duration,\n });\n } catch (error) {\n self.postMessage({\n id,\n success: false,\n error: error.message,\n });\n }\n };\n \n function handleTransform({ items, transformer }) {\n const fn = new Function('item', 'index', 'return (' + transformer + ')(item, index)');\n return items.map((item, i) => fn(item, i));\n }\n \n function handleSearch({ items, query, fuzzy, maxResults }) {\n const lowerQuery = query.toLowerCase();\n const results = [];\n \n for (let i = 0; i < items.length; i++) {\n const item = items[i];\n const text = String(item).toLowerCase();\n \n if (fuzzy) {\n if (fuzzyMatch(text, lowerQuery)) {\n results.push({ item, index: i, score: fuzzyScore(text, lowerQuery) });\n }\n } else {\n if (text.includes(lowerQuery)) {\n results.push({ item, index: i });\n }\n }\n \n if (maxResults && results.length >= maxResults) break;\n }\n \n if (fuzzy) {\n results.sort((a, b) => b.score - a.score);\n }\n \n return results;\n }\n \n function handleFilter({ items, predicate }) {\n const fn = new Function('item', 'index', 'return (' + predicate + ')(item, index)');\n return items.filter((item, i) => fn(item, i));\n }\n \n function handleSort({ items, comparator }) {\n const fn = new Function('a', 'b', 'return (' + comparator + ')(a, b)');\n return [...items].sort(fn);\n }\n \n // Simple fuzzy matching (Levenshtein-inspired)\n function fuzzyMatch(text, query) {\n let qi = 0;\n for (let ti = 0; ti < text.length && qi < query.length; ti++) {\n if (text[ti] === query[qi]) qi++;\n }\n return qi === query.length;\n }\n \n function fuzzyScore(text, query) {\n let score = 0;\n let qi = 0;\n for (let ti = 0; ti < text.length && qi < query.length; ti++) {\n if (text[ti] === query[qi]) {\n score += 100 - ti; // Earlier matches score higher\n qi++;\n }\n }\n return score;\n }\n "}handleMessage(e){const{id:t,success:i,data:n,error:o}=e.data,s=this.pending.get(t);s&&(clearTimeout(s.timeout),this.pending.delete(t),i?s.resolve(n):s.reject(new Error(o||"Worker error")))}handleError(e){console.error("Worker error:",e);for(const[e,t]of this.pending)clearTimeout(t.timeout),t.reject(new Error("Worker crashed"));this.pending.clear()}async execute(e,t,i=5e3){if(!this.worker)return this.executeFallback(e,t);const n="req_"+this.nextId++;return new Promise((o,s)=>{const r=setTimeout(()=>{this.pending.delete(n),s(new Error("Worker timeout"))},i);this.pending.set(n,{resolve:o,reject:s,timeout:r}),this.worker.postMessage({id:n,type:e,payload:t})})}async executeFallback(e,t){const i=this._fallbackOperations[e];if(!i)throw new Error(`Unknown operation: ${e}`);return i(t)}async transform(e,t){return this.execute("transform",{items:e,transformer:t.toString()})}async search(e,t,i=!1){return this.execute("search",{items:e,query:t,fuzzy:i})}async filter(e,t){return this.execute("filter",{items:e,predicate:t.toString()})}async sort(e,t){return this.execute("sort",{items:e,comparator:t.toString()})}get hasWorkerSupport(){return this.supportsWorkers&&null!==this.worker}get hasSharedArrayBuffer(){return this.supportsSharedArrayBuffer}destroy(){if(this.worker){for(const[e,t]of this.pending)clearTimeout(t.timeout),t.reject(new Error("Worker terminated"));this.pending.clear(),this.worker.terminate(),this.worker=null}}}let workerManager=null;function getWorkerManager(){return workerManager||(workerManager=new WorkerManager),workerManager}class PerformanceTelemetry{constructor(){this.frameTimes=[],this.longTasks=0,this.lastFrameTime=0,this.rafId=0,this.measuring=!1,this.observer=null,this.workTotal=0,this.workCount=0,this.measureFrame=()=>{if(!this.measuring)return;const e=performance.now(),t=e-this.lastFrameTime;this.frameTimes.push(t),this.frameTimes.length>60&&this.frameTimes.shift(),this.lastFrameTime=e,this.rafId=requestAnimationFrame(this.measureFrame)}}setupObserver(){if("undefined"!=typeof PerformanceObserver)try{this.observer=new PerformanceObserver(e=>{if(this.measuring)for(const t of e.getEntries())"longtask"===t.entryType&&t.duration>50&&this.longTasks++,"measure"===t.entryType&&(this.workTotal+=t.duration,this.workCount+=1)});try{this.observer.observe({entryTypes:["longtask","measure"]})}catch{this.observer.observe({entryTypes:["measure"]})}}catch(e){console.warn("PerformanceObserver not available",e)}}start(){this.measuring||(this.measuring=!0,this.frameTimes=[],this.workTotal=0,this.workCount=0,this.longTasks=0,this.lastFrameTime=performance.now(),this.setupObserver(),this.measureFrame())}stop(){this.measuring=!1,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=0),this.observer&&(this.observer.disconnect(),this.observer=null)}markStart(e){performance.mark(`${e}-start`)}markEnd(e){const t=`${e}-start`,i=`${e}-end`;performance.mark(i);const n=performance.measure(e,t,i),o=n?n.duration:0;return performance.clearMarks(t),performance.clearMarks(i),performance.clearMeasures(e),o}getMetrics(){const e=this.frameTimes.length>0?this.frameTimes.reduce((e,t)=>e+t,0)/this.frameTimes.length:0,t={frames:{frameTime:e,fps:e>0?1e3/e:0,longTasks:this.frameTimes.filter(e=>e>16.67).length,droppedFrames:this.frameTimes.filter(e=>e>33.33).length},mainThreadWork:this.workCount>0?this.workTotal/this.workCount:0,longTaskCount:this.longTasks};if("memory"in performance&&performance.memory){const e=performance.memory;t.memory={usedJSHeapSize:e.usedJSHeapSize,totalJSHeapSize:e.totalJSHeapSize,jsHeapSizeLimit:e.jsHeapSizeLimit}}return t}isPerformanceGood(){const e=this.getMetrics();return e.frames.fps>=55&&e.mainThreadWork<8&&e.frames.longTasks<3}getReport(){const e=this.getMetrics();let t="=== Performance Report ===\n";if(t+=`FPS: ${e.frames.fps.toFixed(2)}\n`,t+=`Avg Frame Time: ${e.frames.frameTime.toFixed(2)}ms\n`,t+=`Long Frames (>16.67ms): ${e.frames.longTasks}\n`,t+=`Dropped Frames (>33ms): ${e.frames.droppedFrames}\n`,t+=`Avg Main Thread Work: ${e.mainThreadWork.toFixed(2)}ms\n`,t+=`Long Tasks (>50ms): ${e.longTaskCount}\n`,e.memory){t+=`Memory: ${(e.memory.usedJSHeapSize/1024/1024).toFixed(2)}MB / ${(e.memory.jsHeapSizeLimit/1024/1024).toFixed(2)}MB\n`}return t+=`Status: ${this.isPerformanceGood()?"✓ GOOD":"✗ POOR"}\n`,t}reset(){this.frameTimes=[],this.workTotal=0,this.workCount=0,this.longTasks=0}destroy(){this.stop(),this.observer&&(this.observer.disconnect(),this.observer=null)}}let telemetry=null;function getTelemetry(){return telemetry||(telemetry=new PerformanceTelemetry),telemetry}async function measureAsync(e,t){const i=performance.now();return{result:await t(),duration:performance.now()-i}}function measureSync(e,t){const i=performance.now();return{result:t(),duration:performance.now()-i}}class NoOpSanitizer{sanitize(e){return e}}let globalSanitizer=new NoOpSanitizer;function setHTMLSanitizer(e){globalSanitizer=e}function getHTMLSanitizer(){return globalSanitizer}function sanitizeHTML(e){return globalSanitizer.sanitize(e)}function createTextNode(e){return document.createTextNode(e)}function setTextContent(e,t){e.textContent=t}function createElement(e,t,i){const n=document.createElement(e);if(t)for(const[e,i]of Object.entries(t))e.startsWith("on")||"style"===e?console.warn(`[NativeSelect Security] Blocked attribute: ${e}`):n.setAttribute(e,i);return void 0!==i&&(n.textContent=i),n}function setCSSProperties(e,t){for(const[i,n]of Object.entries(t))i.startsWith("--")?e.style.setProperty(i,n):console.warn(`[NativeSelect Security] CSS property must start with --: ${i}`)}const CSPFeatures={hasInlineScripts(){try{return new Function("return true"),!0}catch{return!1}},hasEval(){try{return eval("true"),!0}catch{return!1}},hasSharedArrayBuffer:()=>"undefined"!=typeof SharedArrayBuffer,hasWorkers(){try{return"undefined"!=typeof Worker}catch{return!1}},isSandboxed(){try{return window!==window.parent&&!window.parent}catch{return!0}},getCSPDirectives(){const e=document.querySelectorAll('meta[http-equiv="Content-Security-Policy"]'),t=[];return e.forEach(e=>{const i=e.getAttribute("content");i&&t.push(i)}),t}};function detectEnvironment(){return{canUseWorkers:CSPFeatures.hasWorkers(),canUseSharedArrayBuffer:CSPFeatures.hasSharedArrayBuffer(),canUseInlineScripts:CSPFeatures.hasInlineScripts(),canUseEval:CSPFeatures.hasEval(),isSandboxed:CSPFeatures.isSandboxed(),cspDirectives:CSPFeatures.getCSPDirectives()}}function validateTemplate(e,t){return globalSanitizer instanceof NoOpSanitizer&&console.warn(`[NativeSelect Security] Template from "${t}" contains HTML but no sanitizer is configured. This may be unsafe if the content is untrusted. Call setHTMLSanitizer() with a sanitizer like DOMPurify.`),sanitizeHTML(e)}function containsSuspiciousPatterns(e){return[/<script/i,/javascript:/i,/on\w+\s*=/i,/eval\s*\(/i,/Function\s*\(/i,/setTimeout\s*\(/i,/setInterval\s*\(/i].some(t=>t.test(e))}function escapeHTML(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}function escapeAttribute(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function applyClasses(e,t){e.className=t.filter(Boolean).join(" ")}function toggleClass(e,t,i){e.classList.toggle(t,i)}function setCustomProperties(e,t){for(const[i,n]of Object.entries(t))i.startsWith("--")?e.style.setProperty(i,n):"production"!==process.env.NODE_ENV&&console.warn(`[NativeSelect CSP] Custom property must start with --: "${i}". Skipping.`)}function getCustomProperty(e,t){return getComputedStyle(e).getPropertyValue(t).trim()}function removeCustomProperty(e,t){e.style.removeProperty(t)}const defaultTheme={"--ns-item-height":"40px","--ns-item-padding":"8px 12px","--ns-item-bg":"transparent","--ns-item-hover-bg":"rgba(0, 0, 0, 0.05)","--ns-item-selected-bg":"rgba(0, 102, 204, 0.1)","--ns-item-active-bg":"rgba(0, 102, 204, 0.2)","--ns-item-color":"inherit","--ns-item-selected-color":"#0066cc","--ns-border-color":"#ccc","--ns-border-radius":"4px","--ns-focus-outline":"2px solid #0066cc","--ns-font-size":"14px","--ns-font-family":"system-ui, -apple-system, sans-serif"};function applyDefaultTheme(e){setCustomProperties(e,defaultTheme)}const shadowDOMStyles='\n:host {\n display: block;\n box-sizing: border-box;\n font-family: var(--ns-font-family, system-ui, -apple-system, sans-serif);\n font-size: var(--ns-font-size, 14px);\n}\n\n* {\n box-sizing: border-box;\n}\n\n.ns-list {\n position: relative;\n overflow: auto;\n max-height: var(--ns-max-height, 300px);\n border: 1px solid var(--ns-border-color, #ccc);\n border-radius: var(--ns-border-radius, 4px);\n background: var(--ns-bg, white);\n outline: none;\n}\n\n.ns-list:focus {\n outline: var(--ns-focus-outline, 2px solid #0066cc);\n outline-offset: -2px;\n}\n\n.ns-item {\n padding: var(--ns-item-padding, 8px 12px);\n min-height: var(--ns-item-height, 40px);\n color: var(--ns-item-color, inherit);\n background: var(--ns-item-bg, transparent);\n cursor: pointer;\n user-select: none;\n display: flex;\n align-items: center;\n transition: background-color 0.15s ease;\n}\n\n.ns-item:hover {\n background: var(--ns-item-hover-bg, rgba(0, 0, 0, 0.05));\n}\n\n.ns-item[aria-selected="true"] {\n background: var(--ns-item-selected-bg, rgba(0, 102, 204, 0.1));\n color: var(--ns-item-selected-color, #0066cc);\n}\n\n.ns-item[data-active="true"]:not([aria-selected="true"]) {\n background: var(--ns-item-active-bg, rgba(0, 102, 204, 0.2));\n}\n\n.ns-item[aria-selected="true"][data-active="true"] {\n background: var(--ns-item-selected-active-bg, var(--ns-item-selected-bg, rgba(0, 102, 204, 0.1)));\n color: var(--ns-item-selected-active-color, var(--ns-item-selected-color, #0066cc));\n outline: var(--ns-item-selected-active-outline, 2px solid #0066cc);\n outline-offset: -2px;\n}\n\n.ns-item[aria-disabled="true"] {\n opacity: 0.5;\n cursor: not-allowed;\n}\n\n.ns-viewport {\n position: relative;\n overflow: auto;\n -webkit-overflow-scrolling: touch;\n}\n\n.ns-spacer {\n position: absolute;\n top: 0;\n left: 0;\n width: 1px;\n pointer-events: none;\n}\n\n/* Screen reader only */\n.ns-sr-only {\n position: absolute;\n left: -9999px;\n width: 1px;\n height: 1px;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n}\n\n/* Portal mode (teleported outside shadow DOM) */\n.ns-portal {\n position: fixed;\n z-index: var(--ns-portal-z-index, 9999);\n}\n\n/* CSP warning banner (only shown in development) */\n.ns-csp-warning {\n padding: 8px;\n background: #fff3cd;\n border: 1px solid #ffc107;\n border-radius: 4px;\n color: #856404;\n font-size: 12px;\n margin-bottom: 8px;\n}\n';function injectShadowStyles(e){const t=document.createElement("style");t.textContent=shadowDOMStyles,e.appendChild(t)}function hasOverflowHiddenAncestor(e){let t=e.parentElement;for(;t&&t!==document.body;){const e=getComputedStyle(t).overflow;if("hidden"===e||"clip"===e)return!0;t=t.parentElement}return!1}function warnCSPViolation(e,t){"production"!==process.env.NODE_ENV&&console.warn(`[NativeSelect CSP] Feature "${e}" blocked by Content Security Policy. Falling back to "${t}".`)}export{CSPFeatures,CustomOptionPool,DOMPool,DefaultSelectEffectRunner,EnhancedSelect,FenwickTree,NativeSelectElement,OptionRenderer,PerformanceTelemetry,SelectEngineBridge,SelectOption,Virtualizer,WorkerManager,applyClasses,applyDefaultTheme,applySelectionRequest,arrayIncludesValue,arraysEqualByValue,configureSelect,containsSuspiciousPatterns,createDefaultItemAdapter,createElement,createInitialSelectState,createItemRegistry,createRendererHelpers,createTextNode,defaultTheme,detectEnvironment,escapeAttribute,escapeHTML,getActiveKey,getCustomProperty,getDefaultDuplicateKeyPolicy,getHTMLSanitizer,getSelectedKeys,getTelemetry,getWorkerManager,hasOverflowHiddenAncestor,hasSelection,injectShadowStyles,isDisabled,isFocused,isOpen,isRegisteredKey,isSelected,measureAsync,measureSync,removeCustomProperty,renderTemplate,resetSelectConfig,sanitizeHTML,selectConfig,setCSSProperties,setCustomProperties,setHTMLSanitizer,setTextContent,shadowDOMStyles,toggleClass,transition,validateDataLoadingConfig,validateTemplate,valuesEqual,warnCSPViolation};
1
+ const createRendererHelpers=e=>({onSelect:e,getIndex:e=>{const t=e?.closest?.("[data-selectable]");if(!t)return null;const i=Number(t.dataset.index);return Number.isFinite(i)?i:null},keyboardFocus:e=>{const t=document.querySelector(`[data-selectable][data-index="${e}"]`);t?.focus?.()}});function renderTemplate(e,t,i){const n=document.createDocumentFragment();for(let e=0;e<t.length;e++){const o=t[e],s=document.createElement("div");s.innerHTML=i(o,e);let r=s.firstElementChild;if(!r){const t=document.createElement("div");for(t.setAttribute("data-selectable",""),t.setAttribute("data-index",String(e));s.firstChild;)t.appendChild(s.firstChild);n.appendChild(t);continue}r.hasAttribute("data-smilodon-handled")||(r.setAttribute("data-selectable",""),r.setAttribute("data-index",String(e))),n.appendChild(r)}e.replaceChildren(n)}const objectKeyCache=new WeakMap;let generatedObjectKeyId=0;function isObjectRecord(e){return null!==e&&("object"==typeof e||"function"==typeof e)}function readField(e,t){if(t&&isObjectRecord(e))return e[t]}function toSelectKey(e){return"string"==typeof e||"number"==typeof e?e:"boolean"==typeof e||"bigint"==typeof e||"symbol"==typeof e?String(e):null}function objectIdentityKey(e){const t=objectKeyCache.get(e);if(t)return t;generatedObjectKeyId+=1;const i=`__smilodon-object-${generatedObjectKeyId}`;return objectKeyCache.set(e,i),i}function indexFallbackKey(e,t){const i=globalThis.process?.env?.NODE_ENV;if("production"!==i){const e="[Smilodon Phase2] Using index as key is unstable under filtering/sorting. Provide getKey/valueField for stable selection.";t?t(e):console.warn(e)}return`__smilodon-index-${e}`}function createDefaultItemAdapter(e={}){return{getKey(t,i){if(e.getKey)return e.getKey(t,i);if(isObjectRecord(t)){const n=toSelectKey(t.id)??toSelectKey(t.key)??toSelectKey(t.value)??toSelectKey(readField(t,e.valueField));if(null!==n)return n;if(e.getValue){const n=toSelectKey(e.getValue(t,i));if(null!==n)return n}return"index"===e.keyFallback?indexFallbackKey(i,e.onIndexFallback):objectIdentityKey(t)}return String(t)},getValue(t,i){if(e.getValue)return e.getValue(t,i);const n=readField(t,e.valueField);return void 0!==n?n:isObjectRecord(t)&&void 0!==t.value?t.value:t},getLabel(t,i){if(e.getLabel)return e.getLabel(t,i);const n=readField(t,e.labelField);return void 0!==n?String(n):isObjectRecord(t)&&void 0!==t.label?String(t.label):isObjectRecord(t)&&void 0!==t.text?String(t.text):String(t)},isDisabled:(t,i)=>e.isDisabled?e.isDisabled(t,i):Boolean(isObjectRecord(t)&&t.disabled),getGroupKey:(t,i)=>e.getGroupKey?e.getGroupKey(t,i):isObjectRecord(t)&&void 0!==t.group?null==t.group?null:String(t.group):null}}function getDefaultDuplicateKeyPolicy(){const e=globalThis.process?.env?.NODE_ENV;return"production"===e?"warn":"throw"}function createItemRegistry(e,t,i={}){const n=i.duplicateKeyPolicy??getDefaultDuplicateKeyPolicy(),o=[],s=new Map,r=new Map,a=new Map,l=new Map,c=[];return e.forEach((e,d)=>{const h=t.getKey(e,d),u=l.get(h),p={key:h,item:e,index:d,label:t.getLabel(e,d),value:t.getValue(e,d),disabled:!0===t.isDisabled?.(e,d),groupKey:t.getGroupKey?.(e,d)??null};if(o.push(p),r.set(d,h),void 0!==u){const e={key:h,firstIndex:u,duplicateIndex:d};if(c.push(e),"throw"===n)throw new Error(duplicateKeyMessage(e));if("warn"===n)return void(i.onDuplicateKey?i.onDuplicateKey(e):console.warn(duplicateKeyMessage(e)));if("first-wins"===n)return}else l.set(h,d);s.set(h,p),a.set(h,d)}),{records:o,keyToRecord:s,indexToKey:r,keyToIndex:a,duplicateKeys:c}}function duplicateKeyMessage(e){return`[Smilodon Phase2] Duplicate item key "${String(e.key)}" at indexes ${e.firstIndex} and ${e.duplicateIndex}. Provide stable unique keys for selection.`}function applySelectionRequest(e,t,i){let n;switch(t.type){case"select":n=selectKey(e,t.key,i);break;case"deselect":n=deselectKey(e,t.key,i);break;case"toggle":n=e.has(t.key)?i.multiple||i.allowDeselect?deselectKey(e,t.key,i):e:selectKey(e,t.key,i);break;case"clear":n=i.required&&e.size>0?e:new Set;break;case"replace":n=replaceKeys(e,t.keys,i)}return n.size===e.size&&[...n].every(t=>e.has(t))?e:n}function selectKey(e,t,i){if(i.disabledKeys.has(t))return e;if(!i.multiple)return new Set([t]);if(e.has(t))return e;const n=i.maxSelections??0;return n>0&&e.size>=n?e:new Set([...e,t])}function deselectKey(e,t,i){if(!e.has(t)||i.disabledKeys.has(t))return e;if(i.required&&e.size<=1)return e;const n=new Set(e);return n.delete(t),n}function replaceKeys(e,t,i){const n=normalizeKeys(t,i);return i.required&&0===n.size&&e.size>0?normalizeKeys(e,i):n}function normalizeKeys(e,t){const i=new Set,n=t.maxSelections??0;for(const o of e)if(!t.disabledKeys.has(o)&&!i.has(o)&&(i.add(o),!t.multiple||n>0&&i.size>=n))break;return i}function transition(e,t){switch(t.type){case"CONNECT":return{state:{...e,lifecycle:"connected"},effects:[]};case"DISCONNECT":{const t="open"===e.popup?[{type:"POPUP_CLOSED",reason:"disconnect"},{type:"SYNC_ARIA"}]:[];return{state:{...e,lifecycle:"disconnected",popup:"closed",focused:!1},effects:t}}case"OPEN_REQUEST":return"connected"!==e.lifecycle||e.disabled||"open"===e.popup?{state:enforceInvariants(e),effects:[]}:{state:{...e,popup:"open"},effects:[{type:"POPUP_OPENED"},{type:"FOCUS_TRIGGER"},{type:"SYNC_ARIA"}]};case"CLOSE_REQUEST":return"closed"===e.popup?{state:e,effects:[]}:{state:{...e,popup:"closed"},effects:[{type:"POPUP_CLOSED",reason:t.reason},{type:"SYNC_ARIA"}]};case"TOGGLE_REQUEST":return transition(e,"open"===e.popup?{type:"CLOSE_REQUEST",reason:"programmatic"}:{type:"OPEN_REQUEST"});case"FOCUS_GAINED":return e.focused?{state:e,effects:[]}:{state:{...e,focused:!0},effects:[{type:"SYNC_ARIA"}]};case"FOCUS_LOST":return e.focused?{state:{...e,focused:!1},effects:[{type:"SYNC_ARIA"}]}:{state:e,effects:[]};case"DISABLED_CHANGED":{if(e.disabled===t.disabled)return{state:enforceInvariants(e),effects:[]};const i=enforceInvariants({...e,disabled:t.disabled}),n=[];return t.disabled&&"open"===e.popup&&n.push({type:"POPUP_CLOSED",reason:"disabled"}),n.push({type:"SYNC_ARIA"}),{state:i,effects:n}}case"ITEMS_REGISTERED":{const i=new Set(t.keys),n=new Set(t.disabledKeys??[]),o={...e.selection,disabledKeys:n},s=resolveActiveKey(e.activeKey,i,n),r=applySelectionRequest(e.selectedKeys,{type:"replace",keys:Array.from(e.selectedKeys)},o),a={...e,activeKey:s,selectedKeys:r,registeredKeys:i,selection:o},l=[];return keysEqual(s,e.activeKey)||l.push({type:"ACTIVE_KEY_CHANGED",activeKey:s,reason:"programmatic"}),setsEqual(r,e.selectedKeys)||l.push({type:"SELECTION_CHANGED",selectedKeys:Array.from(r),reason:"programmatic"}),l.length>0&&l.push({type:"SYNC_ARIA"}),{state:a,effects:l}}case"SELECTION_CONFIG_CHANGED":{const i={...e.selection,multiple:t.multiple??e.selection.multiple,required:t.required??e.selection.required,allowDeselect:t.allowDeselect??e.selection.allowDeselect,maxSelections:t.maxSelections??e.selection.maxSelections,disabledKeys:t.disabledKeys?new Set(t.disabledKeys):e.selection.disabledKeys},n=applySelectionRequest(e.selectedKeys,{type:"replace",keys:Array.from(e.selectedKeys)},i),o=resolveActiveKey(e.activeKey,e.registeredKeys,i.disabledKeys),s={...e,selection:i,selectedKeys:n,activeKey:o},r=[];return keysEqual(o,e.activeKey)||r.push({type:"ACTIVE_KEY_CHANGED",activeKey:o,reason:"programmatic"}),setsEqual(n,e.selectedKeys)||r.push({type:"SELECTION_CHANGED",selectedKeys:Array.from(n),reason:"programmatic"}),r.length>0&&r.push({type:"SYNC_ARIA"}),{state:s,effects:r}}case"ACTIVE_KEY_CHANGED":return null===t.key||e.registeredKeys.has(t.key)&&!e.selection.disabledKeys.has(t.key)?keysEqual(e.activeKey,t.key)?{state:e,effects:[]}:{state:{...e,activeKey:t.key},effects:[{type:"ACTIVE_KEY_CHANGED",activeKey:t.key,reason:t.reason},{type:"SYNC_ARIA"}]}:{state:e,effects:[]};case"SELECT_KEY_REQUEST":case"DESELECT_KEY_REQUEST":case"TOGGLE_KEY_REQUEST":case"CLEAR_SELECTION_REQUEST":case"REPLACE_SELECTION_REQUEST":{const i=applySelectionRequest(e.selectedKeys,selectionRequestFromEvent(t),e.selection);return setsEqual(i,e.selectedKeys)?{state:e,effects:[]}:{state:{...e,selectedKeys:i},effects:[{type:"SELECTION_CHANGED",selectedKeys:Array.from(i),reason:t.reason},{type:"SYNC_ARIA"}]}}default:return{state:e,effects:[]}}}function selectionRequestFromEvent(e){switch(e.type){case"SELECT_KEY_REQUEST":return{type:"select",key:e.key,reason:e.reason};case"DESELECT_KEY_REQUEST":return{type:"deselect",key:e.key,reason:e.reason};case"TOGGLE_KEY_REQUEST":return{type:"toggle",key:e.key,reason:e.reason};case"CLEAR_SELECTION_REQUEST":return{type:"clear",reason:e.reason};case"REPLACE_SELECTION_REQUEST":return{type:"replace",keys:e.keys,reason:e.reason}}}function enforceInvariants(e){return"disconnected"===e.lifecycle||e.disabled?"closed"===e.popup?e:{...e,popup:"closed"}:e}function resolveActiveKey(e,t,i){return null!==e&&t.has(e)&&!i.has(e)?e:null}function setsEqual(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function keysEqual(e,t){return e===t||Object.is(e,t)}function createInitialSelectState(){return{lifecycle:"disconnected",popup:"closed",disabled:!1,focused:!1,query:"",activeKey:null,selectedKeys:new Set,registeredKeys:new Set,selection:{multiple:!1,required:!1,allowDeselect:!1,disabledKeys:new Set,maxSelections:0},dataStatus:"idle"}}function isOpen(e){return"open"===e.popup}function isDisabled(e){return e.disabled}function isFocused(e){return e.focused}function hasSelection(e){return e.selectedKeys.size>0}function isSelected(e,t){return e.selectedKeys.has(t)}function getSelectedKeys(e){return Array.from(e.selectedKeys)}function getActiveKey(e){return e.activeKey}function isRegisteredKey(e,t){return e.registeredKeys.has(t)}class SelectEngineBridge{constructor(e=createInitialSelectState()){this._state=e}get state(){return this._state}dispatch(e){const t=transition(this._state,e);return this._state=t.state,t.effects}}class DefaultSelectEffectRunner{run(e,t){for(const i of e)switch(i.type){case"FOCUS_TRIGGER":t.focusTrigger?.();break;case"SYNC_ARIA":t.syncAria?.();break;case"POPUP_OPENED":t.onPopupOpened?.();break;case"POPUP_CLOSED":t.onPopupClosed?.(i.reason)}}}class FenwickTree{constructor(e){this.size=e,this.tree=new Float64Array(e+1)}add(e,t){let i=e+1;for(;i<=this.size;)this.tree[i]+=t,i+=i&-i}sum(e){if(e<0)return 0;let t=e+1,i=0;for(;t>0;)i+=this.tree[t],t-=t&-t;return i}rangeSum(e,t){return e>t?0:this.sum(t)-(e>0?this.sum(e-1):0)}update(e,t,i){this.add(e,i-t)}lowerBound(e){if(e<=0)return 0;let t=0,i=0,n=1<<Math.floor(Math.log2(this.size));for(;n>0;){if(t+n<=this.size){const o=i+this.tree[t+n];o<e&&(t+=n,i=o)}n>>=1}return t}reset(){this.tree.fill(0)}resize(e){if(e===this.size)return;const t=this.tree,i=this.size;this.size=e,this.tree=new Float64Array(e+1);const n=Math.min(i,e);for(let e=1;e<=n;e++)this.tree[e]=t[e]}getSize(){return this.size}exportState(){return{size:this.size,tree:Array.from(this.tree)}}static fromState(e){const t=new FenwickTree(e.size);return t.tree=new Float64Array(e.tree),t}}class DOMPool{constructor(e){this.pool=[],this.hits=0,this.misses=0,this.evictions=0,this.factory=e.factory,this.reset=e.reset||this.defaultReset.bind(this),this.maxSize=e.maxSize||64,this.telemetry=e.telemetry||!1}acquire(){const e=performance.now();for(let t=0;t<this.pool.length;t++){const i=this.pool[t];if(!i.inUse)return i.inUse=!0,i.lastUsed=e,this.reset(i.node),this.telemetry&&this.hits++,i.node}const t=this.factory();return this.pool.push({node:t,lastUsed:e,inUse:!0}),this.telemetry&&this.misses++,this.pool.length>this.maxSize&&this.evictLRU(),t}release(e){const t=this.pool.find(t=>t.node===e);if(t){if(t.inUse=!1,t.lastUsed=performance.now(),this.pool.length>this.maxSize)return void this.removePoolNode(t);this.reset(t.node)}}evictLRU(){let e=-1,t=1/0;for(let i=0;i<this.pool.length;i++){const n=this.pool[i];!n.inUse&&n.lastUsed<t&&(e=i,t=n.lastUsed)}return e>=0&&(this.removePoolNode(this.pool[e]),this.telemetry&&this.evictions++,!0)}removePoolNode(e){const t=this.pool.indexOf(e);if(t<0)return;const[i]=this.pool.splice(t,1);this.deepCleanup(i.node)}defaultReset(e){e.textContent="",e.removeAttribute("style");const t=Array.from(e.attributes);for(const i of t)i.name.startsWith("data-")&&"data-index"!==i.name&&"data-selectable"!==i.name&&e.removeAttribute(i.name);["aria-selected","aria-checked","aria-disabled"].forEach(t=>e.removeAttribute(t))}deepCleanup(e){const t=e.cloneNode(!0);e.parentNode?.replaceChild(t,e),e.textContent=""}clear(){for(const e of this.pool)this.deepCleanup(e.node);this.pool=[],this.resetTelemetry()}setMaxSize(e){for(this.maxSize=e;this.pool.length>this.maxSize&&this.evictLRU(););}getStats(){const e=this.pool.filter(e=>!e.inUse).length,t=this.hits+this.misses>0?this.hits/(this.hits+this.misses):0;return{total:this.pool.length,available:e,inUse:this.pool.length-e,maxSize:this.maxSize,hits:this.hits,misses:this.misses,evictions:this.evictions,hitRate:t}}resetTelemetry(){this.hits=0,this.misses=0,this.evictions=0}}class Virtualizer{constructor(e,t,i,n){this.measuredHeights=new Map,this.measuredHeightTotal=0,this.activeNodes=new Map,this.destroyed=!1,this.recycleRafId=0,this.intendedScrollTop=0,this.currentWindow=null,this.container=e,this.itemsLength=t,this.itemGetter=i,this.options=n,this.estimatedItemHeight=n.estimatedItemHeight,this.averageHeight=n.estimatedItemHeight;const o=Math.ceil(1.5*(2*n.buffer+10))+(n.maxPoolExtra??32);this.pool=new DOMPool({maxSize:o,factory:()=>{const e=document.createElement("div");return e.setAttribute("data-selectable",""),e},reset:e=>{e.textContent="",e.removeAttribute("style"),e.removeAttribute("aria-selected"),e.removeAttribute("aria-checked")},telemetry:n.enableTelemetry||!1}),this.fenwick=this.createFenwickTree(t),this.container.style.willChange="transform"}computeWindow(e,t){const{buffer:i}=this.options,n=this.indexAtOffset(e),o=n-i,s=this.itemsLength>0?Math.max(0,Math.min(this.itemsLength-1,o)):0,r=Math.max(0,e+t);let a=this.indexAtOffset(r);t>0&&a>n&&this.cumulativeOffset(a)===r&&(a-=1);const l=Math.max(n,a)+i,c=this.itemsLength>0?Math.max(0,Math.min(this.itemsLength-1,l)):-1,d=Math.max(0,c-s+1),h=d+(this.options.maxPoolExtra??32);return this.pool.setMaxSize(h),{startIndex:s,endIndex:c,windowSize:d}}updateWindow(e,t){if(this.destroyed)return null;const i=Number.isFinite(e)?Math.max(0,e):0,n=Number.isFinite(t)&&t>=0?t:0,o=this.computeWindow(i,n),s=null===this.currentWindow||this.currentWindow.startIndex!==o.startIndex||this.currentWindow.endIndex!==o.endIndex||this.currentWindow.windowSize!==o.windowSize;return this.currentWindow={...o},{window:{...o},changed:s,scrollTop:i,viewportHeight:n}}getCurrentWindow(){return this.currentWindow?{...this.currentWindow}:null}indexAtOffset(e){if(this.itemsLength<=0)return 0;const t=Math.max(0,e);let i=Math.max(0,Math.min(this.itemsLength-1,this.fenwick.lowerBound(t)));for(;i<this.itemsLength-1&&this.cumulativeOffset(i+1)<=t;)i+=1;return i}cumulativeOffset(e){if(!Number.isFinite(e))return e===Number.POSITIVE_INFINITY&&this.itemsLength>0?this.fenwick.sum(this.itemsLength-1):0;const t=Math.max(0,Math.min(this.itemsLength,Math.trunc(e)));return 0===t?0:this.fenwick.sum(t-1)}scrollToIndex(e){if(this.destroyed||this.itemsLength<=0)return null;const t=Number.isFinite(e)?Math.trunc(e):0,i=Math.max(0,Math.min(this.itemsLength-1,t)),n=this.cumulativeOffset(i);return this.intendedScrollTop=n,{index:i,offset:n,scrollTop:n}}scrollToKey(e,t){if(this.destroyed||this.itemsLength<=0)return null;const i=t(e);return"number"!=typeof i||!Number.isInteger(i)||i<0||i>=this.itemsLength?null:this.scrollToIndex(i)}getIntendedScrollTop(){return this.intendedScrollTop}acquireNode(e){const t=this.activeNodes.get(e);if(t)return t;const i=this.pool.acquire();return i.setAttribute("data-index",String(e)),this.activeNodes.set(e,i),i}releaseNode(e){const t=this.activeNodes.get(e);t&&(this.pool.release(t),this.activeNodes.delete(e))}releaseExcess(e){for(const[t,i]of this.activeNodes)e.has(t)||(this.pool.release(i),this.activeNodes.delete(t))}render(e,t,i){if(this.destroyed)return;const n=document.createDocumentFragment(),o=new Set;for(let s=e;s<=t;s++){const e=this.acquireNode(s);i(e,this.itemGetter(s),s),n.appendChild(e),o.add(s),queueMicrotask(()=>{this.destroyed||this.measureOnAppear(e,s)})}const s=this.cumulativeOffset(e);this.container.style.transform=`translate3d(0, ${Math.round(100*s)/100}px, 0)`,this.container.replaceChildren(n),this.recycleRafId&&cancelAnimationFrame(this.recycleRafId),this.recycleRafId=requestAnimationFrame(()=>{this.recycleRafId=0,this.destroyed||this.releaseExcess(o)})}measureOnAppear(e,t){this.measureItem(t,e.offsetHeight)}measureItem(e,t){if(this.destroyed||!Number.isInteger(e)||e<0||e>=this.itemsLength||!Number.isFinite(t)||t<=0)return!1;const i=this.measuredHeights.get(e),n=this.options.measurementThreshold??5;if(void 0===i||Math.abs(i-t)>n){const n=i??this.estimatedItemHeight;return this.measuredHeights.set(e,t),this.measuredHeightTotal+=t-(i??0),this.fenwick.update(e,n,t),this.updateAverageHeight(),!0}return!1}getPoolStats(){return this.pool.getStats()}setItemsLength(e){const t=this.itemsLength;this.itemsLength=e,e!==t&&(this.currentWindow=null);let i=!1;for(const[t,n]of this.measuredHeights)t>=e&&(this.measuredHeightTotal-=n,this.measuredHeights.delete(t),i=!0);i&&this.updateAverageHeight();for(const t of Array.from(this.activeNodes.keys()))t>=e&&this.releaseNode(t);e!==t&&(this.fenwick=this.createFenwickTree(e))}destroy(){this.destroyed=!0,this.recycleRafId&&(cancelAnimationFrame(this.recycleRafId),this.recycleRafId=0),this.pool.clear(),this.activeNodes.clear(),this.measuredHeights.clear(),this.measuredHeightTotal=0,this.averageHeight=this.estimatedItemHeight,this.currentWindow=null,this.fenwick.reset()}updateAverageHeight(){const e=this.measuredHeights.size;this.averageHeight=e>0?Math.round(this.measuredHeightTotal/e*100)/100:this.estimatedItemHeight}createFenwickTree(e){const t=new FenwickTree(e);for(let i=0;i<e;i++)t.add(i,this.estimatedItemHeight);for(const[i,n]of this.measuredHeights)i<e&&t.update(i,this.estimatedItemHeight,n);return t}}class CustomOptionPool{constructor(e=50){this._pool=new Map,this._activeComponents=new Map,this._maxPoolSize=e}acquire(e,t,i,n,o){this.release(i);const s=this._findAvailableComponent(e);let r;if(s)r=s.instance;else try{r=e(t,i)}catch(e){throw console.error("[CustomOptionPool] Failed to create component:",e),e}try{r.mountOption(o,n),s?(s.inUse=!0,s.lastUsedIndex=i):this._addToPool(e,r,i),this._activeComponents.set(i,r)}catch(e){s&&(s.inUse=!1);try{r.unmountOption()}catch{}throw console.error(`[CustomOptionPool] Failed to mount component at index ${i}:`,e),e}return r}release(e){const t=this._activeComponents.get(e);if(t){try{t.unmountOption()}catch(t){console.error(`[CustomOptionPool] Failed to unmount component at index ${e}:`,t)}this._activeComponents.delete(e);for(const e of this._pool.values()){const i=e.find(e=>e.instance===t);if(i){i.inUse=!1;break}}}}releaseAll(){Array.from(this._activeComponents.keys()).forEach(e=>this.release(e))}updateSelection(e,t){const i=this._activeComponents.get(e);i&&i.updateSelected(t)}updateFocused(e,t){const i=this._activeComponents.get(e);i&&i.updateFocused&&i.updateFocused(t)}getComponent(e){return this._activeComponents.get(e)}clear(){this.releaseAll(),this._pool.clear()}getStats(){let e=0,t=0;for(const i of this._pool.values())e+=i.length,t+=i.filter(e=>!e.inUse).length;return{totalPooled:e,activeComponents:this._activeComponents.size,availableComponents:t}}_findAvailableComponent(e){const t=this._pool.get(e);if(t)return t.find(e=>!e.inUse)}_addToPool(e,t,i){for(;this._getTotalPooled()>=this._maxPoolSize;)if(!this._evictAvailableComponent())return;const n=this._pool.get(e)||[];n.push({instance:t,inUse:!0,lastUsedIndex:i}),this._pool.set(e,n)}_evictAvailableComponent(){for(const[e,t]of this._pool.entries()){const i=t.findIndex(e=>!e.inUse);if(!(i<0))return t.splice(i,1),0===t.length&&this._pool.delete(e),!0}return!1}_getTotalPooled(){let e=0;for(const t of this._pool.values())e+=t.length;return e}}class OptionRenderer{constructor(e){this._mountedElements=new Map,this._config=e,this._pool=new CustomOptionPool(e.maxPoolSize)}render(e,t,i,n,o){const s=e,r=this._config.getValue(e),a=this._config.getLabel(e),l=!!this._config.getDisabled&&this._config.getDisabled(e);this.unmount(t);return s.optionComponent&&"function"==typeof s.optionComponent?this._renderCustomComponent(e,t,r,a,i,n,l,o,s.optionComponent):this._renderLightweightOption(e,t,r,a,i,n,l,o)}updateSelection(e,t){const i=this._mountedElements.get(e);if(!i)return;const n=this._pool.getComponent(e);n?n.updateSelected(t):t?(i.classList.add("selected"),i.setAttribute("aria-selected","true")):(i.classList.remove("selected"),i.setAttribute("aria-selected","false"))}updateFocused(e,t){const i=this._mountedElements.get(e);if(!i)return;const n=this._pool.getComponent(e);n?(n.updateFocused&&n.updateFocused(t),i.classList.toggle("focused",t)):i.classList.toggle("focused",t)}unmount(e){this._pool.release(e),this._mountedElements.delete(e)}unmountAll(){this._pool.releaseAll(),this._mountedElements.clear()}getStats(){return this._pool.getStats()}_renderLightweightOption(e,t,i,n,o,s,r,a){const l=document.createElement("div");return l.className="option",o&&l.classList.add("selected"),s&&l.classList.add("focused"),r&&l.classList.add("disabled"),l.id=`${a}-option-${t}`,l.textContent=n,l.dataset.value=String(i),l.dataset.index=String(t),l.dataset.mode="lightweight",l.setAttribute("role","option"),l.setAttribute("aria-selected",String(o)),r&&l.setAttribute("aria-disabled","true"),r||l.addEventListener("click",()=>{this._config.onSelect(t)}),this._mountedElements.set(t,l),l}_renderCustomComponent(e,t,i,n,o,s,r,a,l){const c=document.createElement("div");c.className="option option-custom",o&&c.classList.add("selected"),s&&c.classList.add("focused"),r&&c.classList.add("disabled"),c.id=`${a}-option-${t}`,c.dataset.value=String(i),c.dataset.index=String(t),c.dataset.mode="component",c.setAttribute("role","option"),c.setAttribute("aria-selected",String(o)),c.setAttribute("aria-label",n),r&&c.setAttribute("aria-disabled","true");const d={item:e,index:t,value:i,label:n,isSelected:o,isFocused:s,isDisabled:r,onSelect:e=>{r||this._config.onSelect(e)},onCustomEvent:(e,i)=>{this._config.onCustomEvent&&this._config.onCustomEvent(t,e,i)}};try{this._pool.acquire(l,e,t,d,c).getElement();r||c.addEventListener("click",e=>{c.contains(e.target)&&this._config.onSelect(t)})}catch(e){console.error(`[OptionRenderer] Failed to render custom component at index ${t}:`,e),c.innerHTML="",c.textContent=n,c.classList.add("component-error"),this._config.onError&&this._config.onError(t,e)}return this._mountedElements.set(t,c),c}}class NativeSelectElement extends HTMLElement{static get observedAttributes(){return["placement","strategy","portal"]}constructor(){super(),this._options={},this._items=[],this._selectedSet=new Set,this._selectedItems=new Map,this._activeIndex=-1,this._multi=!1,this._typeBuffer="",this._shadow=this.attachShadow({mode:"open"}),this._listRoot=document.createElement("div"),this._listRoot.setAttribute("role","listbox"),this._listRoot.setAttribute("tabindex","0"),this._shadow.appendChild(this._listRoot),this._liveRegion=document.createElement("div"),this._liveRegion.setAttribute("role","status"),this._liveRegion.setAttribute("aria-live","polite"),this._liveRegion.style.cssText="position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden;",this._shadow.appendChild(this._liveRegion),this._helpers=createRendererHelpers((e,t)=>this._onSelect(e,t)),this._listRoot.addEventListener("click",e=>{const t=e.target.closest("[data-selectable]");if(!t)return;const i=Number(t.dataset.index),n=this._items[i];this._onSelect(n,i)}),this._listRoot.addEventListener("keydown",e=>this._onKeydown(e))}connectedCallback(){this._listRoot.setAttribute("role","listbox"),this._listRoot.setAttribute("aria-label","Options list"),this._multi&&this._listRoot.setAttribute("aria-multiselectable","true"),this._initializeOptionRenderer(),this._emit("open",{})}disconnectedCallback(){this._emit("close",{}),this._unifiedRenderer&&this._unifiedRenderer.unmountAll(),this._virtualizer?.destroy(),this._virtualizer=void 0,this._typeTimeout&&window.clearTimeout(this._typeTimeout),this._announceTimeout&&window.clearTimeout(this._announceTimeout)}_initializeOptionRenderer(){this._unifiedRenderer?.unmountAll();const e={enableRecycling:!0,maxPoolSize:100,getValue:e=>e?.value??e,getLabel:e=>e?.label??String(e),getDisabled:e=>e?.disabled??!1,onSelect:e=>{const t=this._items[e];this._onSelect(t,e)},onCustomEvent:(e,t,i)=>{this.dispatchEvent(new CustomEvent("option:custom-event",{detail:{index:e,eventName:t,data:i},bubbles:!0,composed:!0}))},onError:(e,t)=>{console.error(`[NativeSelect] Error in option ${e}:`,t),this.dispatchEvent(new CustomEvent("option:mount-error",{detail:{index:e,error:t},bubbles:!0,composed:!0}))}};this._unifiedRenderer=new OptionRenderer(e)}attributeChangedCallback(e,t,i){switch(e){case"placement":this._options.placement=i??void 0;break;case"strategy":this._options.strategy=i??void 0;break;case"portal":this._options.portal="true"===i||"false"!==i&&void 0}}set items(e){this._items=e??[],this._virtualizer?.destroy(),this._virtualizer=new Virtualizer(this._listRoot,this._items.length,e=>this._items[e],{estimatedItemHeight:48,buffer:5}),this.render()}get items(){return this._items}set multi(e){this._multi=e,e?this._listRoot.setAttribute("aria-multiselectable","true"):this._listRoot.removeAttribute("aria-multiselectable")}get multi(){return this._multi}get selectedIndices(){return Array.from(this._selectedSet)}get selectedItems(){return Array.from(this._selectedItems.values())}set optionTemplate(e){this._options.optionTemplate=e,this.render()}set optionRenderer(e){this._options.optionRenderer=e,this.render()}setItems(e){this.items=e??[]}setValue(e){if(null==e||""===e)return this._selectedSet.clear(),this._selectedItems.clear(),this._activeIndex=-1,void this.render();const t=this._items.findIndex(t=>"object"==typeof t&&null!==t&&"value"in t?t.value===e:t===e);if(t>=0){const e=this._items[t];this._multi||(this._selectedSet.clear(),this._selectedItems.clear()),this._selectedSet.add(t),this._selectedItems.set(t,e),this._activeIndex=t,this.render()}}getValue(){const e=[];for(const t of this._selectedItems.values())"object"==typeof t&&null!==t&&"value"in t?e.push(t.value):e.push(t);return this._multi?e:e[0]??null}render(){const{optionTemplate:e,optionRenderer:t}=this._options,i=this.getBoundingClientRect().height||300,n=this.scrollTop||0;this._activeIndex>=0?this._listRoot.setAttribute("aria-activedescendant",`option-${this._activeIndex}`):this._listRoot.removeAttribute("aria-activedescendant");if(this._items.some(e=>"object"==typeof e&&null!==e&&Object.prototype.hasOwnProperty.call(e,"optionComponent")&&"function"==typeof e.optionComponent)&&this._unifiedRenderer){this._listRoot.replaceChildren();const e=document.createDocumentFragment();for(let t=0;t<this._items.length;t++){const i=this._items[t],n=this._selectedSet.has(t),o=this._activeIndex===t,s=this._unifiedRenderer.render(i,t,n,o,`native-${this.getAttribute("id")||"default"}`);e.appendChild(s)}return void this._listRoot.appendChild(e)}if(this._virtualizer){const{startIndex:o,endIndex:s}=this._virtualizer.computeWindow(n,i);return void this._virtualizer.render(o,s,(i,n,o)=>{if(this._applyOptionAttrs(i,o),t){const e=t(n,o,this._helpers);i.replaceChildren(e)}else if(e){const t=document.createElement("div");t.innerHTML=e(n,o);const s=t.firstElementChild;i.replaceChildren(s??document.createTextNode(String(n)))}else{const e=String("object"==typeof n&&null!==n&&"label"in n?n.label:n);i.textContent=e}})}const o=document.createDocumentFragment();for(let i=0;i<this._items.length;i++){const n=this._items[i];if(t){const e=t(n,i,this._helpers);e.hasAttribute("data-selectable")||(e.setAttribute("data-selectable",""),e.setAttribute("data-index",String(i))),this._applyOptionAttrs(e,i),o.appendChild(e)}else{if(e)return renderTemplate(this._listRoot,this._items,e),void this._applyAriaToAll();{const e=document.createElement("div"),t=String("object"==typeof n&&null!==n&&"label"in n?n.label:n);e.textContent=t,e.setAttribute("data-selectable",""),e.setAttribute("data-index",String(i)),this._applyOptionAttrs(e,i),o.appendChild(e)}}}this._listRoot.replaceChildren(o)}_applyOptionAttrs(e,t){e.setAttribute("role","option"),e.id=`option-${t}`,this._selectedSet.has(t)?e.setAttribute("aria-selected","true"):e.setAttribute("aria-selected","false")}_applyAriaToAll(){const e=Array.from(this._listRoot.children);for(const t of e){const e=Number(t.dataset.index);Number.isFinite(e)&&this._applyOptionAttrs(t,e)}}_emit(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0}))}_onSelect(e,t){this._multi?this._selectedSet.has(t)?(this._selectedSet.delete(t),this._selectedItems.delete(t)):(this._selectedSet.add(t),this._selectedItems.set(t,e)):(this._selectedSet.clear(),this._selectedItems.clear(),this._selectedSet.add(t),this._selectedItems.set(t,e)),this._activeIndex=t,this.render();const i=this._selectedSet.has(t),n=e?.value??e,o=e?.label??String(e);this._emit("select",{item:e,index:t,value:n,label:o,selected:i,multi:this._multi});const s=[],r=[];for(const e of this._selectedItems.values())s.push(e),r.push(e?.value??e);this._emit("change",{selectedItems:s,selectedValues:r,selectedIndices:Array.from(this._selectedSet)}),this._announce(`Selected ${o}`)}_onKeydown(e){switch(e.key){case"ArrowDown":e.preventDefault(),this._moveActive(1);break;case"ArrowUp":e.preventDefault(),this._moveActive(-1);break;case"Home":e.preventDefault(),this._setActive(0);break;case"End":e.preventDefault(),this._setActive(this._items.length-1);break;case"PageDown":e.preventDefault(),this._moveActive(10);break;case"PageUp":e.preventDefault(),this._moveActive(-10);break;case"Enter":case" ":if(e.preventDefault(),this._activeIndex>=0){const e=this._items[this._activeIndex];this._onSelect(e,this._activeIndex)}break;case"Escape":e.preventDefault(),this._emit("close",{});break;default:1!==e.key.length||e.ctrlKey||e.altKey||e.metaKey||this._onType(e.key)}}_moveActive(e){const t=Math.max(0,Math.min(this._items.length-1,this._activeIndex+e));this._setActive(t)}_setActive(e){this._activeIndex=e,this.render(),this._scrollToActive(),this._announce(`Navigated to ${String(this._items[e])}`)}_scrollToActive(){const e=this._shadow.getElementById(`option-${this._activeIndex}`);e?.scrollIntoView({block:"nearest",inline:"nearest"})}_onType(e){this._typeTimeout&&window.clearTimeout(this._typeTimeout),this._typeBuffer+=e.toLowerCase(),this._typeTimeout=window.setTimeout(()=>{this._typeBuffer=""},400);const t=this._items.findIndex(e=>String(e).toLowerCase().startsWith(this._typeBuffer));t>=0&&this._setActive(t)}_announce(e){this._liveRegion&&(this._liveRegion.textContent=e,this._announceTimeout&&window.clearTimeout(this._announceTimeout),this._announceTimeout=window.setTimeout(()=>{this._announceTimeout=void 0,this._liveRegion&&(this._liveRegion.textContent="")},1e3))}focus(){this._listRoot.focus()}}customElements.get("smilodon-select")||customElements.define("smilodon-select",NativeSelectElement);const defaultConfig={selection:{mode:"single",allowDeselect:!1,disabledOptionBehavior:{selectable:!1,hoverable:!1,focusable:!1},maxSelections:0,showRemoveButton:!0,showSelectedIndicator:!0,removeButtonIcon:"×",closeOnSelect:!0,toggleOnTriggerClick:!0},direction:"ltr",dropdownPlacement:{mode:"bottom"},multiSelectDisplay:{mode:"wrap",maxHeight:"160px",overflowX:"hidden",overflowY:"auto",dragScroll:!0},scrollToSelected:{enabled:!0,multiSelectTarget:"first",behavior:"smooth",block:"nearest"},loadMore:{enabled:!1,itemsPerLoad:3,threshold:100,showLoader:!0},busyBucket:{enabled:!0,showSpinner:!0,showMessage:!0,message:"Loading...",minDisplayTime:200,contentMode:"append"},styles:{classNames:{}},serverSide:{enabled:!1,getValueFromItem:e=>e?.value??e,getLabelFromItem:e=>e?.label??String(e)},infiniteScroll:{enabled:!1,pageSize:20,initialPage:1,cachePages:!0,maxCachedPages:10,preloadAdjacent:!0,scrollRestoration:"auto"},expandable:{enabled:!1,collapsedHeight:"300px",expandedHeight:"500px",expandLabel:"Show more",collapseLabel:"Show less"},clearControl:{enabled:!1,clearSelection:!0,clearSearch:!0,hideWhenEmpty:!0,ariaLabel:"Clear selection and search",icon:"×"},callbacks:{},tracking:{enabled:!1,events:!0,styling:!0,limitations:!0,emitDiagnostics:!1,maxEntries:200},limitations:{policies:{},autoMitigateRuntimeModeSwitch:!0},enabled:!0,searchable:!1,placeholder:"Select an option...",virtualize:!0,estimatedItemHeight:48};class SelectConfigManager{constructor(){this.config=this.deepClone(defaultConfig)}getConfig(){return this.config}updateConfig(e){this.config=this.deepMerge(this.config,e)}resetConfig(){this.config=this.deepClone(defaultConfig)}mergeWithComponentConfig(e){return this.deepMerge(this.deepClone(this.config),e)}deepClone(e){return JSON.parse(JSON.stringify(e))}deepMerge(e,t){const i={...e},n=Object.keys(t);for(let e=0;e<n.length;e++){const o=n[e];if(Object.prototype.hasOwnProperty.call(t,o)){const e=t[o],n=i[o];e&&"object"==typeof e&&!Array.isArray(e)?i[o]=this.deepMerge(n&&"object"==typeof n?n:{},e):i[o]=e}}return i}}const selectConfig=new SelectConfigManager;function configureSelect(e){selectConfig.updateConfig(e)}function resetSelectConfig(){selectConfig.resetConfig()}const DEFAULT_CONFIG={protocol:"legacy",searchMode:"local",paginationMode:"page",firstPage:1},ALLOWED_FIELDS=new Set(["protocol","searchMode","paginationMode","firstPage","fetchLimit"]);function issue(e,t,i){return{path:e,code:t,message:i}}function isRecord$1(e){if(null===e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function validatePositiveSafeInteger(e,t,i){const n=e[t];void 0!==n&&("number"==typeof n?(!Number.isSafeInteger(n)||n<=0)&&i.push(issue(t,"invalid-positive-integer",`${t} must be a positive safe integer.`)):i.push(issue(t,"invalid-type",`${t} must be a number.`)))}function validateDataLoadingConfig(e){if(!isRecord$1(e))return{valid:!1,issues:[issue("dataLoading","invalid-type","dataLoading must be a plain object.")]};const t=[];for(const i of Object.keys(e).filter(e=>!ALLOWED_FIELDS.has(e)).sort())t.push(issue(i,"unknown-field",`Unknown dataLoading field: ${i}.`));const i=e.protocol,n=void 0===i?DEFAULT_CONFIG.protocol:i;"string"!=typeof n?t.push(issue("protocol","invalid-type","protocol must be a string.")):"legacy"!==n&&"acknowledged"!==n&&t.push(issue("protocol","invalid-value","protocol must be legacy or acknowledged."));const o=e.searchMode,s=void 0===o?DEFAULT_CONFIG.searchMode:o;"string"!=typeof s?t.push(issue("searchMode","invalid-type","searchMode must be a string.")):"local"!==s&&"remote"!==s&&"hybrid"!==s&&t.push(issue("searchMode","invalid-value","searchMode must be local, remote, or hybrid."));const r=e.paginationMode,a=void 0===r?DEFAULT_CONFIG.paginationMode:r;if("string"!=typeof a?t.push(issue("paginationMode","invalid-type","paginationMode must be a string.")):"page"!==a&&"cursor"!==a&&t.push(issue("paginationMode","invalid-value","paginationMode must be page or cursor.")),validatePositiveSafeInteger(e,"firstPage",t),validatePositiveSafeInteger(e,"fetchLimit",t),"legacy"!==n||"remote"!==s&&"hybrid"!==s||t.push(issue("searchMode","requires-acknowledged-protocol","Remote and hybrid search require the acknowledged protocol.")),"legacy"===n&&"cursor"===a&&t.push(issue("paginationMode","requires-acknowledged-protocol","Cursor pagination requires the acknowledged protocol.")),t.length>0)return{valid:!1,issues:t};return{valid:!0,value:{protocol:n,searchMode:s,paginationMode:a,firstPage:void 0===e.firstPage?DEFAULT_CONFIG.firstPage:e.firstPage,...void 0===e.fetchLimit?{}:{fetchLimit:e.fetchLimit}}}}function computeWindowKeys(e,t,i){const n=Math.max(0,Math.min(e.length,Math.trunc(t))),o=Math.max(n,Math.min(e.length,Math.trunc(i)));return e.slice(n,o)}function deriveAccessibilityState(e,t={}){const i=e.selection.required,n=t.invalid??!1;return{expanded:"open"===e.popup,disabled:e.disabled,readonly:t.readonly??!1,searchable:t.searchable??!1,multiple:e.selection.multiple,required:i,invalid:n,busy:"loading"===e.dataStatus,activeKey:e.activeKey,selectedKeys:e.selectedKeys,disabledKeys:e.selection.disabledKeys,popupRole:"listbox",label:t.label??{},validation:{required:i,invalid:n,errorMessage:t.errorMessage??null,errorDescriptionId:t.errorDescriptionId??null}}}function uniqueIds(e){return[...new Set(e.filter(e=>Boolean(e)))]}function getLabelledBy(e){return uniqueIds([e.labelId,...e.labelledBy??[]])}function getDescribedBy(e){return uniqueIds([...e.label.describedBy??[],e.validation.errorDescriptionId])}function computeComboboxAccessibility(e,t=null){return{role:"combobox",expanded:e.expanded,disabled:e.disabled,readonly:e.readonly,autocomplete:e.searchable?"list":"none",multiple:e.multiple,required:e.required,invalid:e.invalid,activeKey:e.activeKey,controlsId:t,labelledBy:getLabelledBy(e.label),describedBy:getDescribedBy(e),ariaLabel:e.label.ariaLabel??null,ariaDescription:e.label.ariaDescription??null}}function computeListboxAccessibility(e){return{role:e.popupRole,multiple:e.multiple,busy:e.busy,labelledBy:getLabelledBy(e.label),ariaLabel:e.label.ariaLabel??null}}function computeOptionAccessibility(e,t){const i=e.disabled||e.disabledKeys.has(t);return{key:t,selected:e.selectedKeys.has(t),disabled:i,active:!i&&e.activeKey===t}}function computeAccessibilityEffects(e,t){return[{type:"SYNC_COMBOBOX_ARIA",...computeComboboxAccessibility(e,t.controlsId??null)},{type:"SYNC_LISTBOX_ARIA",...computeListboxAccessibility(e)},...t.optionKeys.map(t=>({type:"SYNC_OPTION_ARIA",...computeOptionAccessibility(e,t)})),...(t.announcements??[]).map(e=>({type:"ANNOUNCE",...e})),...(t.focusIntents??[]).map(e=>({type:"FOCUS_INTENT",...e}))]}function setBooleanAttribute(e,t,i){e.setAttribute(t,String(i))}function setOptionalAttribute(e,t,i){i?e.setAttribute(t,i):e.removeAttribute(t)}function setIdListAttribute(e,t,i){setOptionalAttribute(e,t,i.length>0?i.join(" "):null)}function applyCombobox(e,t){const i=t.combobox;if(!i)return;i.setAttribute("role",e.role),setBooleanAttribute(i,"aria-expanded",e.expanded),setBooleanAttribute(i,"aria-disabled",e.disabled),setBooleanAttribute(i,"aria-readonly",e.readonly),setBooleanAttribute(i,"aria-required",e.required),setBooleanAttribute(i,"aria-invalid",e.invalid),i.setAttribute("aria-autocomplete",e.autocomplete),setOptionalAttribute(i,"aria-controls",e.controlsId),setIdListAttribute(i,"aria-labelledby",e.labelledBy),setIdListAttribute(i,"aria-describedby",e.describedBy),setOptionalAttribute(i,"aria-label",e.ariaLabel),setOptionalAttribute(i,"aria-description",e.ariaDescription);const n=null==e.activeKey?null:t.getOptionByKey?.(e.activeKey)??null;setOptionalAttribute(i,"aria-activedescendant",n?.id||null)}function applyListbox(e,t){const i=t.listbox;i&&(i.setAttribute("role",e.role),e.multiple?i.setAttribute("aria-multiselectable","true"):i.removeAttribute("aria-multiselectable"),e.busy?i.setAttribute("aria-busy","true"):i.removeAttribute("aria-busy"),setIdListAttribute(i,"aria-labelledby",e.labelledBy),setOptionalAttribute(i,"aria-label",e.ariaLabel))}function applyOption(e,t){const i=t.getOptionByKey?.(e.key);i&&(i.setAttribute("role","option"),setBooleanAttribute(i,"aria-selected",e.selected),e.disabled?i.setAttribute("aria-disabled","true"):i.removeAttribute("aria-disabled"))}function applyFocusIntent(e,t,i){if(!i.applyFocus||"none"===e)return;const n="input"===e?t.focusTargets?.input:"clear-button"===e?t.focusTargets?.clearButton:t.focusTargets?.getActiveOption?.();n?.focus()}function applyAccessibilityEffects(e,t,i={}){for(const n of e)switch(n.type){case"SYNC_COMBOBOX_ARIA":applyCombobox(n,t);break;case"SYNC_LISTBOX_ARIA":applyListbox(n,t);break;case"SYNC_OPTION_ARIA":applyOption(n,t);break;case"ANNOUNCE":t.liveRegion&&(t.liveRegion.setAttribute("aria-live",n.politeness),t.liveRegion.setAttribute("aria-atomic","true"),t.liveRegion.textContent=n.message);break;case"FOCUS_INTENT":applyFocusIntent(n.target,t,i)}}class SelectOption extends HTMLElement{constructor(e){super(),this._hasRendered=!1,this._config=e,this._shadow=this.attachShadow({mode:"open"}),this._container=document.createElement("div"),this._container.className="option-container",this._initializeStyles(),this._attachEventListeners(),this._shadow.appendChild(this._container)}connectedCallback(){this._ensureRendered()}_ensureRendered(){this._hasRendered||(this._render(),this._hasRendered=!0)}ensureRendered(){this._ensureRendered()}_initializeStyles(){const e=document.createElement("style");e.textContent='\n :host {\n display: block;\n position: relative;\n font: inherit;\n color: var(--select-option-color, var(--select-text-color, #1f2937));\n background: var(--select-option-bg, var(--select-dropdown-bg, var(--select-bg, white)));\n border: var(--select-option-border, none);\n border-bottom: var(--select-option-border-bottom, none);\n border-radius: var(--select-option-border-radius, var(--select-radius-sm, 6px));\n box-shadow: var(--select-option-shadow, none);\n transform: var(--select-option-transform, none);\n transition: var(--select-option-transition, background-color 0.2s ease);\n }\n\n :host(:hover:not(.smilodon-option--disabled):not([aria-disabled="true"])),\n :host(.smilodon-option--disabled-hoverable:hover) {\n background: var(--select-option-hover-bg, #f0f0f0);\n color: var(--select-option-hover-color, var(--select-option-color, var(--select-text-color, #1f2937)));\n outline: var(--select-option-hover-border, none);\n outline-offset: -1px;\n box-shadow: var(--select-option-hover-shadow, var(--select-option-shadow, none));\n }\n\n /* Keep the visual surface on the host so external utility classes applied\n through classMap can override selected/active/disabled styles in both\n light and dark themes. */\n :host([aria-selected="true"]),\n :host(.smilodon-option--selected) {\n background: var(--select-option-selected-bg, #e3f2fd);\n color: var(--select-option-selected-color, #1976d2);\n border: var(--select-option-selected-border, var(--select-option-border, none));\n border-bottom: var(--select-option-selected-border-bottom, var(--select-option-border-bottom, none));\n border-radius: var(--select-option-selected-border-radius, var(--select-option-border-radius, 0));\n box-shadow: var(--select-option-selected-shadow, var(--select-option-shadow, none));\n transform: var(--select-option-selected-transform, var(--select-option-transform, none));\n }\n\n :host([aria-selected="true"]:hover),\n :host(.smilodon-option--selected:hover) {\n background: var(--select-option-selected-hover-bg, var(--select-option-selected-bg, #e3f2fd));\n color: var(--select-option-selected-hover-color, var(--select-option-selected-color, #1976d2));\n outline: var(--select-option-selected-hover-border, var(--select-option-hover-border, none));\n outline-offset: -1px;\n box-shadow: var(--select-option-selected-hover-shadow, var(--select-option-selected-shadow, var(--select-option-shadow, none)));\n }\n\n :host(.smilodon-option--active):not(.smilodon-option--disabled):not([aria-disabled="true"]),\n :host(.smilodon-option--active.smilodon-option--disabled-focusable) {\n background: var(--select-option-active-bg, var(--select-option-hover-bg, #f0f0f0));\n color: var(--select-option-active-color, var(--select-option-hover-color, var(--select-option-color, var(--select-text-color, #1f2937))));\n border: var(--select-option-active-border, var(--select-option-hover-border, var(--select-option-border, none)));\n box-shadow: var(--select-option-active-shadow, var(--select-option-shadow, none));\n transform: var(--select-option-active-transform, var(--select-option-transform, none));\n outline: var(--select-option-active-outline, none);\n outline-offset: var(--select-option-active-outline-offset, -2px);\n }\n\n :host(.smilodon-option--disabled),\n :host([aria-disabled="true"]) {\n background: var(--select-option-disabled-bg, var(--select-option-bg, var(--select-dropdown-bg, var(--select-bg, white))));\n color: var(--select-option-disabled-color, var(--select-option-color, var(--select-text-color, #1f2937)));\n border: var(--select-option-disabled-border, var(--select-option-border, none));\n border-bottom: var(--select-option-disabled-border-bottom, var(--select-option-border-bottom, none));\n opacity: var(--select-option-disabled-opacity, 0.5);\n cursor: var(--select-option-disabled-cursor, not-allowed);\n pointer-events: none;\n }\n\n :host(.smilodon-option--disabled-interactive) {\n pointer-events: auto;\n }\n \n .option-container {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: var(--select-option-padding, 10px 14px);\n cursor: pointer;\n user-select: none;\n color: inherit;\n background: inherit;\n transition: inherit;\n border: inherit;\n border-bottom: inherit;\n border-radius: inherit;\n box-shadow: inherit;\n transform: inherit;\n font: inherit;\n }\n \n .option-container:hover {\n background: inherit;\n color: inherit;\n border: inherit;\n border-bottom: inherit;\n box-shadow: inherit;\n transform: inherit;\n }\n \n .option-container.selected {\n background: inherit;\n color: inherit;\n border: inherit;\n border-bottom: inherit;\n border-radius: inherit;\n box-shadow: inherit;\n transform: inherit;\n }\n\n .option-container.selected:hover {\n background: inherit;\n color: inherit;\n border: inherit;\n border-bottom: inherit;\n box-shadow: inherit;\n transform: inherit;\n }\n \n .option-container.active:not(.disabled) {\n background: inherit;\n color: inherit;\n border: inherit;\n box-shadow: inherit;\n transform: inherit;\n outline: none;\n outline-offset: 0;\n }\n \n .option-container.disabled {\n background: inherit;\n color: inherit;\n border: inherit;\n border-bottom: inherit;\n opacity: inherit;\n cursor: inherit;\n pointer-events: none;\n }\n \n .option-content {\n flex: 1;\n overflow: var(--select-option-content-overflow, hidden);\n text-overflow: var(--select-option-content-text-overflow, ellipsis);\n white-space: var(--select-option-content-white-space, nowrap);\n }\n\n .checkmark-icon {\n display: none;\n margin-left: var(--select-checkmark-margin-left, 8px);\n color: var(--select-checkmark-color, currentColor);\n }\n\n :host([dir="rtl"]) .checkmark-icon,\n :host-context([dir="rtl"]) .checkmark-icon {\n margin-left: 0;\n margin-right: var(--select-checkmark-margin-left, 8px);\n }\n\n :host([aria-selected="true"]) .checkmark-icon,\n .option-container.selected .checkmark-icon {\n display: inline-flex;\n }\n \n .remove-button {\n margin-left: 8px;\n width: var(--select-badge-remove-size, 18px);\n height: var(--select-badge-remove-size, 18px);\n min-width: var(--select-badge-remove-min-width, var(--select-badge-remove-size, 18px));\n min-height: var(--select-badge-remove-min-height, var(--select-badge-remove-size, 18px));\n padding: 0;\n border: none;\n background-color: var(--select-badge-remove-bg, rgba(255, 255, 255, 0.2));\n color: var(--select-badge-remove-color, currentColor);\n cursor: pointer;\n border-radius: var(--select-badge-remove-radius, 50%);\n font-size: var(--select-badge-remove-font-size, 0.7333em);\n font-weight: var(--select-badge-remove-font-weight, 600);\n line-height: 1;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n transition: all 0.2s ease;\n }\n\n :host([dir="rtl"]) .remove-button,\n :host-context([dir="rtl"]) .remove-button {\n margin-left: 0;\n margin-right: 8px;\n }\n\n .remove-button-icon {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: var(--select-badge-remove-icon-size, 10px);\n height: var(--select-badge-remove-icon-size, 10px);\n color: var(--select-badge-remove-icon-color, currentColor);\n font-size: var(--select-badge-remove-icon-font-size, inherit);\n line-height: var(--select-badge-remove-icon-line-height, 1);\n transform: var(--select-badge-remove-icon-transform, none);\n opacity: var(--select-badge-remove-icon-opacity, 1);\n pointer-events: none;\n }\n\n .remove-button-icon svg {\n width: 100%;\n height: 100%;\n display: block;\n }\n \n .remove-button:hover {\n background-color: var(--select-badge-remove-hover-bg, #ffebee);\n color: var(--select-badge-remove-hover-color, #c62828);\n }\n \n .remove-button:focus {\n outline: 2px solid var(--select-remove-btn-focus-outline, #1976d2);\n outline-offset: 2px;\n }\n ',this._shadow.appendChild(e)}_getDisabledBehavior(){const e=this._config.disabledBehavior??{};return{selectable:!0===e.selectable,hoverable:!0===e.hoverable,focusable:!0===e.focusable}}_isDisabledSelectionBlocked(){return Boolean(this._config.disabled)&&!this._getDisabledBehavior().selectable}_render(){const{item:e,index:t,selected:i,disabled:n,active:o,render:s,showRemoveButton:r,classMap:a}=this._config,l=this._getDisabledBehavior();this._container.innerHTML="",this._container.setAttribute("part","option"),this._container.classList.add("smilodon-option");const c=(a?.selected??"selected sm-selected").split(" ").filter(Boolean),d=(a?.active??"active sm-active").split(" ").filter(Boolean),h=(a?.disabled??"disabled sm-disabled").split(" ").filter(Boolean),u=(e,t,i)=>{i?e.classList.add(...t):e.classList.remove(...t)};i?(u(this._container,[...c,"smilodon-option--selected"],!0),u(this,[...c,"smilodon-option--selected"],!0)):(u(this._container,[...c,"smilodon-option--selected"],!1),u(this,[...c,"smilodon-option--selected"],!1)),!o||n&&!l.focusable?(u(this._container,[...d,"smilodon-option--active"],!1),u(this,[...d,"smilodon-option--active"],!1)):(u(this._container,[...d,"smilodon-option--active"],!0),u(this,[...d,"smilodon-option--active"],!0)),n?(u(this._container,[...h,"smilodon-option--disabled"],!0),u(this,[...h,"smilodon-option--disabled"],!0)):(u(this._container,[...h,"smilodon-option--disabled"],!1),u(this,[...h,"smilodon-option--disabled"],!1));const p=(e,t)=>{u(this._container,[e],t),u(this,[e],t)};if(p("smilodon-option--disabled-interactive",Boolean(n&&(l.hoverable||l.selectable))),p("smilodon-option--disabled-hoverable",Boolean(n&&l.hoverable)),p("smilodon-option--disabled-focusable",Boolean(n&&l.focusable)),p("smilodon-option--disabled-selectable",Boolean(n&&l.selectable)),this._config.className){const e=this._config.className.split(" ").filter(Boolean);this._container.classList.add(...e)}this._config.style&&Object.assign(this._container.style,this._config.style);const g=document.createElement("div");if(g.className="option-content",s){const i=s(e,t);"string"==typeof i?g.innerHTML=i:i instanceof HTMLElement&&g.appendChild(i)}else{const e=this._getLabel();g.textContent=e}if(this._container.appendChild(g),r&&i){this._removeButton=document.createElement("button"),this._removeButton.className="remove-button",this._removeButton.setAttribute("part","chip-remove"),this._removeButton.setAttribute("aria-label","Remove option"),this._removeButton.setAttribute("type","button");const e=document.createElement("span");e.className="remove-button-icon",e.setAttribute("part","chip-remove-icon");const t=this._config.removeButtonIcon&&this._config.removeButtonIcon.trim()?this._config.removeButtonIcon:"×";t.trim().startsWith("<")?e.innerHTML=t:e.textContent=t,this._removeButton.appendChild(e),this._container.appendChild(this._removeButton)}if(this.setAttribute("role","option"),this.setAttribute("aria-selected",String(i)),n&&!l.selectable?this.setAttribute("aria-disabled","true"):this.removeAttribute("aria-disabled"),this.id=this._config.id||`select-option-${t}`,!r){const e=document.createElement("div");e.setAttribute("part","checkmark"),e.className="checkmark-icon",e.innerHTML='\n <svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" style="width:1em;height:1em;">\n <path d="M4 8.5L6.5 11L12 5.5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n ',this._container.appendChild(e)}const m=[];i&&m.push("selected"),!o||n&&!l.focusable||m.push("active"),m.length?this.dataset.smState=m.join(" "):delete this.dataset.smState,this.dataset.smIndex=String(t),this.hasAttribute("data-sm-selectable")||this.toggleAttribute("data-sm-selectable",!0)}_attachEventListeners(){this._container.addEventListener("click",e=>{e.target!==this._removeButton&&(this._isDisabledSelectionBlocked()||this._handleSelect())}),this._removeButton&&this._removeButton.addEventListener("click",e=>{e.stopPropagation(),this._handleRemove()}),this.addEventListener("keydown",e=>{this._isDisabledSelectionBlocked()||("Enter"===e.key||" "===e.key?(e.preventDefault(),this._handleSelect()):"Delete"!==e.key&&"Backspace"!==e.key||this._config.selected&&this._config.showRemoveButton&&(e.preventDefault(),this._handleRemove()))})}_handleSelect(){const e={item:this._config.item,index:this._config.index,value:this._getValue(),label:this._getLabel(),selected:!this._config.selected};this.dispatchEvent(new CustomEvent("optionSelect",{detail:e,bubbles:!0,composed:!0}))}_handleRemove(){const e={item:this._config.item,index:this._config.index,value:this._getValue(),label:this._getLabel(),selected:!1};this.dispatchEvent(new CustomEvent("optionRemove",{detail:e,bubbles:!0,composed:!0}))}_getValue(){return this._config.getValue?this._config.getValue(this._config.item):this._config.item?.value??this._config.item}_getLabel(){return this._config.getLabel?this._config.getLabel(this._config.item):this._config.item?.label??String(this._config.item)}updateConfig(e){this._config={...this._config,...e},this._render(),this._attachEventListeners()}getConfig(){return this._config}getValue(){return this._getValue()}getLabel(){return this._getLabel()}setSelected(e){this._config.selected=e,this._hasRendered&&this._render()}setActive(e){this._config.active=e&&(!this._config.disabled||this._getDisabledBehavior().focusable),this._hasRendered&&this._render()}setDisabled(e){this._config.disabled=e,this._hasRendered&&this._render()}}function valuesEqual(e,t){return!!Object.is(e,t)||null!=e&&null!=t&&("string"==typeof e&&"number"==typeof t?e===String(t):"number"==typeof e&&"string"==typeof t&&String(e)===t)}function arrayIncludesValue(e,t){for(let i=0;i<e.length;i+=1)if(valuesEqual(e[i],t))return!0;return!1}function arraysEqualByValue(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i+=1)if(!valuesEqual(e[i],t[i]))return!1;return!0}customElements.get("select-option")||customElements.define("select-option",SelectOption);const DEFAULT_MAX_CURSOR_PAGES=256,HARD_MAX_CURSOR_PAGES=4096,DEFAULT_MAX_CURSOR_TOKEN_BYTES=1024,HARD_MAX_CURSOR_TOKEN_BYTES=4096;let coordinatorInstanceSequence=0;function isRecord(e){if(null===e||"object"!=typeof e||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function isPositiveSafeInteger(e){return Number.isSafeInteger(e)&&e>0}function isNonNegativeSafeInteger(e){return Number.isSafeInteger(e)&&e>=0}function isCursor(e){return"string"==typeof e||"number"==typeof e&&Number.isFinite(e)}function cursorTokenByteLength(e){const t=String(e);let i=0;for(const e of t){const t=e.codePointAt(0);i+=t<=127?1:t<=2047?2:t<=65535?3:4}return i}function parseRequestId(e){const t=/^data-(\d+)-generation-(\d+)-request-(\d+)-([a-z0-9]+)$/.exec(e);if(!t)return null;const[,i,n,o,s]=t,r=Number(i),a=Number(n),l=Number(o);return!Number.isSafeInteger(r)||r<1||!Number.isSafeInteger(a)||a<0||!Number.isSafeInteger(l)||l<1?null:Object.freeze({instanceId:r,queryGeneration:a,sequence:l,check:s})}function requestIdCheck(e,t,i,n){let o=14695981039346656037n;const s=(1n<<64n)-1n,r=`${e}:${t}:${i}:${n}`;for(let e=0;e<r.length;e+=1)o^=BigInt(r.charCodeAt(e)),o=1099511628211n*o&s;return o.toString(36)}function isQueryMode(e){return"local"===e||"remote"===e||"hybrid"===e}function isPaginationMode(e){return"page"===e||"cursor"===e}function frozenPosition(e){return Object.freeze({...e})}function exactKeys(e,t){return Object.keys(e).every(e=>t.includes(e))}function asFrozenItems(e){return Object.freeze(Array.from(e))}function immutableActions(e){return Object.freeze(e.slice())}function configInput(e={}){const t=isRecord(e)?e:{},i=isRecord(t.dataLoading)?t.dataLoading:{},n=isRecord(t.infiniteScroll)?t.infiniteScroll:{};return{protocol:void 0===i.protocol?"legacy":i.protocol,searchMode:void 0===i.searchMode?"local":i.searchMode,paginationMode:void 0===i.paginationMode?"page":i.paginationMode,firstPage:void 0===i.firstPage?1:i.firstPage,initialPage:void 0===n.initialPage?1:n.initialPage,fetchLimit:i.fetchLimit,maxCursorPages:void 0===i.maxCursorPages?DEFAULT_MAX_CURSOR_PAGES:i.maxCursorPages,maxCursorTokenBytes:void 0===i.maxCursorTokenBytes?DEFAULT_MAX_CURSOR_TOKEN_BYTES:i.maxCursorTokenBytes,pageSize:n.pageSize}}function validateDataCoordinatorConfig(e={}){const t=configInput(e),i=[],n=(e,t)=>i.push(Object.freeze({field:e,message:t})),o=e;isRecord(o)?(void 0===o.dataLoading||isRecord(o.dataLoading)||n("dataLoading","must be a plain object when supplied"),void 0===o.infiniteScroll||isRecord(o.infiniteScroll)||n("infiniteScroll","must be a plain object when supplied")):n("config","must be a plain object"),"legacy"!==t.protocol&&"acknowledged"!==t.protocol&&n("dataLoading.protocol","must be legacy or acknowledged"),isQueryMode(t.searchMode)||n("dataLoading.searchMode","must be local, remote, or hybrid"),isPaginationMode(t.paginationMode)||n("dataLoading.paginationMode","must be page or cursor"),isPositiveSafeInteger(t.firstPage)||n("dataLoading.firstPage","must be a positive safe integer"),isPositiveSafeInteger(t.initialPage)||n("infiniteScroll.initialPage","must be a positive safe integer"),"acknowledged"===t.protocol&&"local"===t.searchMode&&"page"===t.paginationMode&&t.initialPage===Number.MAX_SAFE_INTEGER&&n("infiniteScroll.initialPage","must leave room for the next acknowledged page number"),void 0===t.fetchLimit||isPositiveSafeInteger(t.fetchLimit)||n("dataLoading.fetchLimit","must be a positive safe integer when supplied"),(!isPositiveSafeInteger(t.maxCursorPages)||t.maxCursorPages>HARD_MAX_CURSOR_PAGES)&&n("dataLoading.maxCursorPages",`must be a positive safe integer no greater than ${HARD_MAX_CURSOR_PAGES}`),(!isPositiveSafeInteger(t.maxCursorTokenBytes)||t.maxCursorTokenBytes>HARD_MAX_CURSOR_TOKEN_BYTES)&&n("dataLoading.maxCursorTokenBytes",`must be a positive safe integer no greater than ${HARD_MAX_CURSOR_TOKEN_BYTES}`),void 0===t.pageSize||isPositiveSafeInteger(t.pageSize)||n("infiniteScroll.pageSize","must be a positive safe integer when supplied"),"legacy"!==t.protocol||"remote"!==t.searchMode&&"hybrid"!==t.searchMode&&"cursor"!==t.paginationMode||n("dataLoading.protocol","remote/hybrid search and cursor pagination require acknowledged protocol");const s="number"==typeof t.fetchLimit?t.fetchLimit:"number"==typeof t.pageSize?t.pageSize:void 0;return"acknowledged"===t.protocol&&void 0===s&&n("dataLoading.fetchLimit","acknowledged requests require fetchLimit or an effective infiniteScroll.pageSize"),i.length>0?Object.freeze({valid:!1,errors:Object.freeze(i)}):Object.freeze({valid:!0,value:Object.freeze({protocol:t.protocol,searchMode:t.searchMode,paginationMode:t.paginationMode,firstPage:t.firstPage,initialPage:t.initialPage,fetchLimit:s,maxCursorPages:t.maxCursorPages,maxCursorTokenBytes:t.maxCursorTokenBytes})})}function copyCoordinatorConfig(e={}){return{dataLoading:e.dataLoading?{...e.dataLoading}:{},infiniteScroll:e.infiniteScroll?{...e.infiniteScroll}:{}}}function mergeCoordinatorConfig(e,t){return{dataLoading:{...e.dataLoading??{},...t.dataLoading??{}},infiniteScroll:{...e.infiniteScroll??{},...t.infiniteScroll??{}}}}class DataRequestCoordinator{constructor(e={}){this.instanceId=++coordinatorInstanceSequence,this.requestIdSecret=Math.random().toString(36).slice(2)||"0",this.requestSequence=0,this.connected=!1,this.hasConnected=!1,this.queryGeneration=0,this.active=null,this.status="idle",this.committedCursors=new Set,this.generationHasAcceptedResult=!1,this.retryAvailable=!1,this.error=null,this.resourceLimit=null,this.sentinelBlocked=!1,this.sentinelIntersecting=!1;const t=void 0===e.config?{}:e.config,i=validateDataCoordinatorConfig(t);if(!i.valid)throw new TypeError(i.errors.map(({field:e,message:t})=>`${e}: ${t}`).join("; "));this.rawConfig=copyCoordinatorConfig(t),this.config=i.value,this.query=e.initialQuery??"",this.items=asFrozenItems(e.initialItems??[]);const n=this.isRemoteMode();this.hasMore=!n&&(e.hasMore??!1),this.nextEligiblePosition=this.initialPosition(),this.lastCommittedPage="page"!==this.config.paginationMode||n?void 0:this.config.initialPage,this.needsInitialRemoteSearch=n}getSnapshot(){const e=this.active?.request??null,t=frozenPosition(this.nextEligiblePosition);return Object.freeze({status:this.status,connected:this.connected,busy:null!==this.active,query:this.query,normalizedQuery:this.query.trim(),queryGeneration:this.queryGeneration,items:asFrozenItems(this.items),hasMore:this.hasMore,activeRequest:e,lastCommittedPage:this.lastCommittedPage,nextEligiblePosition:t,error:this.error?Object.freeze({...this.error}):null,resourceLimit:this.resourceLimit,sentinelBlocked:this.sentinelBlocked,sentinelIntersecting:this.sentinelIntersecting})}connect(e=this.query){if(this.connected)return immutableActions([]);const t=[];if(e!==this.query&&t.push(...this.setQuery(e)),this.hasConnected&&(this.queryGeneration+=1),this.connected=!0,this.hasConnected=!0,this.isRemoteMode()&&this.needsInitialRemoteSearch){this.resetPaginationForRemoteQuery(!0);const e=this.createSearchRequest();e&&t.push(Object.freeze({type:"request",request:e}))}return immutableActions(t)}markNotificationsDispatched(e){return!(!this.active||this.active.request.requestId!==e||"requested"!==this.active.phase)&&(this.active.phase="loading",this.status="loading",!0)}setQuery(e){if("string"!=typeof e||e===this.query)return immutableActions([]);const t=[],i=this.invalidateActive("query-changed");if(i&&t.push(i),this.query=e,this.queryGeneration+=1,this.error=null,this.status="idle",this.generationHasAcceptedResult=!1,this.retryAvailable=!1,this.retryPosition=void 0,this.retryKind=void 0,this.committedCursors.clear(),this.resourceLimit=null,this.sentinelBlocked=!1,this.isRemoteMode()){if(this.resetPaginationForRemoteQuery(!0),this.needsInitialRemoteSearch=!0,this.connected){const e=this.createSearchRequest();e&&t.push(Object.freeze({type:"request",request:e}))}}else this.lastCommittedPage="page"===this.config.paginationMode?this.config.initialPage:void 0,this.nextEligiblePosition=this.initialPosition(),this.needsInitialRemoteSearch=!1;return immutableActions(t)}updateConfig(e){const t=e;if(!isRecord(t)||void 0!==t.dataLoading&&!isRecord(t.dataLoading)||void 0!==t.infiniteScroll&&!isRecord(t.infiniteScroll))return Object.freeze({status:"invalid",errors:Object.freeze([Object.freeze({field:"config",message:"update and nested config groups must be plain objects"})])});const i=mergeCoordinatorConfig(this.rawConfig,e),n=validateDataCoordinatorConfig(i);if(!n.valid)return Object.freeze({status:"invalid",errors:n.errors});const o=this.config,s=n.value,r=o.protocol!==s.protocol||o.searchMode!==s.searchMode||o.paginationMode!==s.paginationMode;if(this.rawConfig=copyCoordinatorConfig(i),this.config=s,!r)return this.refreshCursorDepthLimit(),Object.freeze({status:"accepted",actions:immutableActions([])});const a=[],l=this.invalidateActive("config-changed");if(l&&a.push(l),this.queryGeneration+=1,this.error=null,this.status="idle",this.generationHasAcceptedResult=!1,this.retryAvailable=!1,this.retryPosition=void 0,this.retryKind=void 0,this.committedCursors.clear(),this.resourceLimit=null,this.sentinelBlocked=!1,this.hasMore=!this.isRemoteMode()&&this.hasMore,this.lastCommittedPage="page"!==this.config.paginationMode||this.isRemoteMode()?void 0:this.config.initialPage,this.nextEligiblePosition=this.initialPosition(),this.needsInitialRemoteSearch=this.isRemoteMode(),this.connected&&this.isRemoteMode()){const e=this.createSearchRequest();e&&a.push(Object.freeze({type:"request",request:e}))}return Object.freeze({status:"accepted",actions:immutableActions(a)})}requestLoadMore(e="manual"){if("acknowledged"!==this.config.protocol||!this.connected||this.active)return immutableActions([]);if("sentinel"===e&&this.sentinelBlocked)return immutableActions([]);if(!this.hasMore&&!this.retryAvailable)return immutableActions([]);const t=this.retryAvailable&&this.retryPosition?this.retryPosition:this.nextEligiblePosition;if("cursor"===this.config.paginationMode&&"cursor"===t.mode&&t.ordinal>this.config.maxCursorPages)return this.resourceLimit=Object.freeze({reason:"cursor-depth",maxCursorPages:this.config.maxCursorPages}),this.status="resource-limited",this.sentinelBlocked=!0,immutableActions([]);"manual"===e&&(this.sentinelBlocked=!1);const i=this.retryAvailable?this.retryKind:void 0;this.retryAvailable=!1,this.retryPosition=void 0,this.retryKind=void 0;const n="search"===i&&this.isRemoteMode()?this.createSearchRequest(t):this.createLoadMoreRequest(t);return immutableActions(n?[Object.freeze({type:"request",request:n})]:[])}setSentinelIntersecting(e){return e?this.sentinelIntersecting?immutableActions([]):(this.sentinelIntersecting=!0,this.requestLoadMore("sentinel")):(this.sentinelIntersecting=!1,this.sentinelBlocked=!1,immutableActions([]))}disconnect(){if(!this.connected)return immutableActions([]);const e=this.active?.request,t=[];if(e){"search"!==e.kind||this.generationHasAcceptedResult||(this.needsInitialRemoteSearch=!0);const i=this.invalidateActive("disconnected");i&&t.push(i),this.resourceLimit=null,this.status="cancelled",this.sentinelBlocked=!0,this.queryGeneration+=1}return this.sentinelIntersecting=!1,this.connected=!1,immutableActions(t)}completeDataRequest(e){if(!isRecord(e)||!this.hasValidCompletionEnvelope(e))return"invalid";const t=e.requestId,i=e.queryGeneration;if(this.active?.request.requestId!==t)return this.classifyInactiveRequest(t,i);if(i!==this.active.request.queryGeneration||"loading"!==this.active.phase)return"invalid";const n=this.validateCompletionPayload(e,this.active.request);if(!n.valid){if("cursor-token-size"===n.resourceLimit){const i=cursorTokenByteLength(e.nextCursor);return this.resourceLimit=Object.freeze({reason:"cursor-token-size",maxCursorTokenBytes:this.config.maxCursorTokenBytes,actualCursorTokenBytes:i,requestId:t}),"resource-limit"}return"invalid"}const o=this.active.request,s=e.status,r="succeeded"===s||"exhausted"===s?asFrozenItems(e.items):this.items;let a,l,c,d=this.nextEligiblePosition,h=this.lastCommittedPage,u=this.hasMore,p=!1,g=null,m=!1,f=null;if("succeeded"===s){const t=this.advanceFrom(o,e);d=t.position,h=t.lastCommittedPage,c=t.cursorToCommit,u=!0}else if("exhausted"===s)h="page"===o.position.mode?o.position.page:this.lastCommittedPage,u=!1;else if("empty"===s)if(u=!0,m=!0,"next"===e.advance){const t=this.advanceFrom(o,e);d=t.position,h=t.lastCommittedPage,c=t.cursorToCommit}else p=!0,a=o.position,l=o.kind;else"failed"===s?(p=!0,a=o.position,l=o.kind,g=Object.freeze({...e.error}),m=!0):"cancelled"===s&&(p=!0,a=o.position,l=o.kind,m=!0);return"cursor"===this.config.paginationMode&&u&&"cursor"===d.mode&&d.ordinal>this.config.maxCursorPages&&(f=Object.freeze({reason:"cursor-depth",maxCursorPages:this.config.maxCursorPages,requestId:t}),m=!0),this.items=r,this.nextEligiblePosition=d,this.lastCommittedPage=h,this.hasMore=u,this.retryAvailable=p,this.retryPosition=a,this.retryKind=l,this.error=g,this.resourceLimit=f,this.sentinelBlocked=m,void 0!==c&&this.committedCursors.add(c),"succeeded"!==s&&"exhausted"!==s||(this.generationHasAcceptedResult=!0),this.active=null,this.status=f?"resource-limited":s,"accepted"}isRemoteMode(){return"remote"===this.config.searchMode||"hybrid"===this.config.searchMode}initialPosition(){if("cursor"===this.config.paginationMode)return Object.freeze({mode:"cursor",ordinal:1});const e=this.isRemoteMode()?this.config.firstPage:this.config.initialPage+1;return Object.freeze({mode:"page",page:e})}resetPaginationForRemoteQuery(e){this.hasMore=!1,this.lastCommittedPage=void 0,this.nextEligiblePosition=this.initialPosition(),this.committedCursors.clear(),this.retryAvailable=!1,this.retryPosition=void 0,this.retryKind=void 0,this.resourceLimit=null,this.sentinelBlocked=!1,this.error=null,e&&(this.items=asFrozenItems([]))}refreshCursorDepthLimit(){if("acknowledged"!==this.config.protocol||"cursor"!==this.config.paginationMode)return;const e=this.retryAvailable&&this.retryPosition?this.retryPosition:this.nextEligiblePosition;if((this.hasMore||this.retryAvailable)&&"cursor"===e.mode&&e.ordinal>this.config.maxCursorPages)return this.resourceLimit=Object.freeze({reason:"cursor-depth",maxCursorPages:this.config.maxCursorPages}),this.active||(this.status="resource-limited"),void(this.sentinelBlocked=!0);"cursor-depth"===this.resourceLimit?.reason&&(this.resourceLimit=null,this.active||"resource-limited"!==this.status||(this.status="idle"))}createSearchRequest(e=this.nextEligiblePosition){if(!this.connected||!this.isRemoteMode()||"acknowledged"!==this.config.protocol)return null;const t=this.createRequest({kind:"search",mode:this.config.searchMode},e);return t&&(this.needsInitialRemoteSearch=!1,this.status="requested"),t}createLoadMoreRequest(e){if(!this.connected||"acknowledged"!==this.config.protocol)return null;const t=this.createRequest({kind:"loadMore"},e);return t&&(this.status="requested"),t}createRequest(e,t){const i=this.config.fetchLimit;if(void 0===i||this.active)return null;this.requestSequence+=1;const n=requestIdCheck(this.requestIdSecret,this.instanceId,this.queryGeneration,this.requestSequence),o=`data-${this.instanceId}-generation-${this.queryGeneration}-request-${this.requestSequence}-${n}`,s=Object.freeze({requestId:o,queryGeneration:this.queryGeneration,query:this.query,normalizedQuery:this.query.trim(),fetchLimit:i,position:frozenPosition(t)}),r="search"===e.kind?Object.freeze({...s,kind:"search",mode:e.mode}):Object.freeze({...s,kind:"loadMore"});return this.active={request:r,phase:"requested"},this.status="requested",this.error=null,r}invalidateActive(e){if(!this.active)return null;const{request:t}=this.active;this.active=null,this.status="cancelled";const i=Object.freeze({requestId:t.requestId,queryGeneration:t.queryGeneration,reason:e});return Object.freeze({type:"cancel",notification:i})}classifyInactiveRequest(e,t){const i=parseRequestId(e);return!i||i.instanceId!==this.instanceId||i.check!==requestIdCheck(this.requestIdSecret,i.instanceId,i.queryGeneration,i.sequence)||i.sequence>this.requestSequence?"unknown-request":i.queryGeneration!==t?"invalid":i.queryGeneration<this.queryGeneration?"stale":"unknown-request"}hasValidCompletionEnvelope(e){return"string"==typeof e.requestId&&e.requestId.length>0&&isNonNegativeSafeInteger(e.queryGeneration)&&"string"==typeof e.status&&["succeeded","empty","exhausted","failed","cancelled"].includes(e.status)}validateCompletionPayload(e,t){const i=["requestId","queryGeneration","status"];switch(e.status){case"succeeded":{const n=[...i,"items","hasMore"];if("cursor"===t.position.mode&&n.push("nextCursor"),!exactKeys(e,n)||!Array.isArray(e.items)||!0!==e.hasMore)return{valid:!1};if("cursor"===t.position.mode){if(t.position.ordinal>=Number.MAX_SAFE_INTEGER||!isCursor(e.nextCursor))return{valid:!1};if(cursorTokenByteLength(e.nextCursor)>this.config.maxCursorTokenBytes)return{valid:!1,resourceLimit:"cursor-token-size"};if(this.hasCommittedCursor(e.nextCursor))return{valid:!1}}else{if("nextCursor"in e)return{valid:!1};if(t.position.page>=Number.MAX_SAFE_INTEGER)return{valid:!1}}return{valid:!0}}case"empty":{const n=[...i,"hasMore","advance"];if("cursor"===t.position.mode&&"next"===e.advance&&n.push("nextCursor"),!exactKeys(e,n)||!0!==e.hasMore)return{valid:!1};if("next"!==e.advance&&"retry"!==e.advance)return{valid:!1};if("cursor"===t.position.mode){if("next"===e.advance){if(t.position.ordinal>=Number.MAX_SAFE_INTEGER||!isCursor(e.nextCursor))return{valid:!1};if(cursorTokenByteLength(e.nextCursor)>this.config.maxCursorTokenBytes)return{valid:!1,resourceLimit:"cursor-token-size"};if(this.hasCommittedCursor(e.nextCursor))return{valid:!1}}else if("nextCursor"in e)return{valid:!1}}else{if("nextCursor"in e)return{valid:!1};if("next"===e.advance&&t.position.page>=Number.MAX_SAFE_INTEGER)return{valid:!1}}return{valid:!0}}case"exhausted":return exactKeys(e,[...i,"items","hasMore"])&&Array.isArray(e.items)&&!1===e.hasMore?{valid:!0}:{valid:!1};case"failed":{if(!exactKeys(e,[...i,"error"])||!isRecord(e.error))return{valid:!1};const t=e.error;return!exactKeys(t,["message","code","retryable"])||"string"!=typeof t.message||0===t.message.trim().length||void 0!==t.code&&"string"!=typeof t.code||void 0!==t.retryable&&"boolean"!=typeof t.retryable?{valid:!1}:{valid:!0}}case"cancelled":{const t="reason"in e;return!exactKeys(e,t?[...i,"reason"]:i)||t&&void 0!==e.reason&&"host-cancelled"!==e.reason?{valid:!1}:{valid:!0}}default:return{valid:!1}}}hasCommittedCursor(e){return this.committedCursors.has(e)||"cursor"===this.nextEligiblePosition.mode&&this.nextEligiblePosition.cursor===e}advanceFrom(e,t){if("page"===e.position.mode){const t=e.position.page;return{position:Object.freeze({mode:"page",page:t+1}),lastCommittedPage:t}}const i=t.nextCursor;return{position:Object.freeze({mode:"cursor",cursor:i,ordinal:e.position.ordinal+1}),lastCommittedPage:this.lastCommittedPage,cursorToCommit:i}}}const LEGACY_DATA_LOADING_CONFIG={protocol:"legacy",searchMode:"local",paginationMode:"page",firstPage:1},DATA_LOADING_CONFIG_FIELDS=["protocol","searchMode","paginationMode","firstPage","fetchLimit"],INVALID_OBJECT_VALUE=Object.freeze({kind:"object"}),INVALID_ARRAY_VALUE=Object.freeze({kind:"array"}),INVALID_FUNCTION_VALUE=Object.freeze({kind:"function"});function invalidConfigValueSignature(e){return null===e||"object"!=typeof e&&"function"!=typeof e?e:"function"==typeof e?INVALID_FUNCTION_VALUE:Array.isArray(e)?INVALID_ARRAY_VALUE:INVALID_OBJECT_VALUE}function createInvalidDataLoadingCandidateSignature(e,t){const i=null!==e&&"object"==typeof e?Object.getPrototypeOf(e):void 0,n=null!==e&&"object"==typeof e&&!Array.isArray(e)&&(i===Object.prototype||null===i),o=n?e:void 0;return{rootKind:n?"record":null===e?"null":Array.isArray(e)?"array":typeof e,rootValue:null===e||"object"!=typeof e?e:void 0,fieldValues:o?DATA_LOADING_CONFIG_FIELDS.map(e=>invalidConfigValueSignature(o[e])):[],issues:t.map(({path:e,code:t,message:i})=>[e,t,i])}}function invalidDataLoadingSignaturesEqual(e,t){if(e.rootKind!==t.rootKind||!Object.is(e.rootValue,t.rootValue))return!1;if(e.fieldValues.length!==t.fieldValues.length||e.issues.length!==t.issues.length)return!1;for(let i=0;i<e.fieldValues.length;i+=1)if(!Object.is(e.fieldValues[i],t.fieldValues[i]))return!1;for(let i=0;i<e.issues.length;i+=1){const n=e.issues[i],o=t.issues[i];if(n[0]!==o[0]||n[1]!==o[1]||n[2]!==o[2])return!1}return!0}class EnhancedSelect extends HTMLElement{static get observedAttributes(){return["aria-label","aria-description","aria-busy"]}get classMap(){return this._classMap}set classMap(e){this._areClassMapsEqual(this._classMap,e)||(this._invalidateGuardedMeasurements(),this._classMap=e,this._setGlobalStylesMirroring(Boolean(this._optionRenderer||e||this._groupHeaderRenderer)),this._track("style","classMapChanged",{hasClassMap:Boolean(e),keys:e?Object.keys(e):[]}),this.isConnected&&this._renderOptions())}get groupHeaderRenderer(){return this._groupHeaderRenderer}set groupHeaderRenderer(e){this._groupHeaderRenderer!==e&&(this._groupHeaderRenderer=e,this._setGlobalStylesMirroring(Boolean(this._optionRenderer||this._classMap||e)),this._track("style","groupHeaderRendererChanged",{enabled:Boolean(e)}),this.isConnected&&this._renderOptions())}constructor(){super(),this._dataLoadingConfig={...LEGACY_DATA_LOADING_CONFIG},this._hasLastInvalidDataLoadingCandidate=!1,this._busyPresentationVisible=!1,this._busyPresentationStartedAt=null,this._busyPresentationGeneration=0,this._busyPresentationHideTimer=null,this._engine=new SelectEngineBridge,this._virtualizationScope={dataKeys:[],filteredKeys:[],registeredKeys:[],windowKeys:[],mountedKeys:[],selectedKeys:new Set,activeKey:null},this._renderPlan={mode:"legacy-full",filteredIndices:[],filteredKeys:[],intendedRenderKeys:[],filteredIndexByKey:new Map},this._guardedVirtualWindow=null,this._guardedVirtualizer=null,this._guardedVirtualizationRequested=!1,this._guardedVirtualizerKeys=[],this._guardedMeasurementQuery=null,this._guardedOptionResizeObserver=null,this._guardedObservedOptions=new Set,this._guardedObserverSeenOptions=new WeakSet,this._guardedOptionMeasurements=new WeakMap,this._guardedMeasurementGeneration=0,this._guardedVirtualScrollTop=0,this._guardedVirtualViewportHeight=0,this._guardedVirtualOverscan=0,this._guardedVirtualWindowRafId=null,this._guardedScrollListenerAttached=!1,this._onGuardedVirtualScroll=()=>this._scheduleGuardedVirtualWindowUpdate(),this._effectRunner=new DefaultSelectEffectRunner,this._itemAdapter=this._createEngineItemAdapter(),this._itemRegistry=createItemRegistry([],this._itemAdapter),this._selectedRecordsByKey=new Map,this._registryItemsRef=[],this._pageCache={},this._dataRequestCoordinator=null,this._acknowledgedSearchMode=null,this._acknowledgedReady=!1,this._acknowledgedDeferredStart=!1,this._hasEverConnected=!1,this._acknowledgedStartTask=null,this._clearAcknowledgedCoordinatorAfterProjection=!1,this._acknowledgedConfigUpdatePending=!1,this._acknowledgedDeferredModeChange=!1,this._acknowledgedProjectionPending=!1,this._acknowledgedProjectionSettling=!1,this._acknowledgedPendingSearchQuery=null,this._acknowledgedProjectionFailureStageForTest=null,this._acknowledgedProjectionRunning=!1,this._acknowledgedProjectionTask=null,this._acknowledgedProjectionScrollTop=0,this._acknowledgedLastRequest=null,this._acknowledgedProjectionCommitsPosition=!1,this._acknowledgedProjectionRequest=null,this._acknowledgedProjectionAttempt=0,this._acknowledgedProjectionDiagnostic=null,this._typeBuffer="",this._hasError=!1,this._errorMessage="",this._boundArrowClick=null,this._pendingFirstRenderMark=!1,this._pendingSearchRenderMark=!1,this._rangeAnchorIndex=null,this._customOptionBoundElements=new WeakSet,this._customOptionManagedActiveClasses=new WeakMap,this._customOptionNormalizedIds=new WeakMap,this._customOptionNormalizedLabels=new WeakMap,this._mirrorGlobalStylesForCustomOptions=!1,this._globalStylesObserver=null,this._globalStylesContainer=null,this._themeContextObserver=null,this._globalStylesSyncToken=0,this._asyncGeneration=0,this._lifecycleTimers=new Set,this._lifecycleRafs=new Set,this._keyboardActiveChangeGeneration=0,this._tracking={events:[],styles:[],limitations:[]},this._suppressBlurClose=!1,this._renderCycleId=0,this._completedRenderCycleId=0,this._renderCycleWaiters=new Map,this._renderCycleWaiterTimeouts=new Map,this._suppressNextOpenClick=!1,this._resolvedDropdownPlacement="bottom",this._dropdownExitTimer=null,this._onDropdownExitAnimationEnd=e=>{if(e.target!==this._dropdown||this._state.isOpen)return;if("closing"!==this._dropdown.getAttribute("data-motion"))return;const t=getComputedStyle(this._dropdown).animationName.split(",").map(e=>e.trim()).filter(e=>e&&"none"!==e);t.length>1||e.animationName&&t[0]&&e.animationName!==t[0]||this._finishDropdownExit()},this._multiScrollDrag={active:!1,moved:!1,pointerId:-1,startX:0,startScrollLeft:0},this._liftedAncestors=[],this._onDocumentPointerDown=e=>{const t=e.composedPath&&e.composedPath()||[];let i=!1;for(const e of t){if(e===this||e===this._container){i=!0;break}if(e instanceof Node)try{if(this._shadow&&this._shadow.contains(e)){i=!0;break}}catch(e){}if(e instanceof Element)try{if(e.matches("[data-sm-selectable], [data-selectable], [data-sm-state], .input-container, .select-container, .dropdown-arrow-container, .clear-control-button")){i=!0;break}}catch(e){}}i||this._handleClose("outside-pointer")},this._shadow=this.attachShadow({mode:"open"}),this._uniqueId=`enhanced-select-${Math.random().toString(36).substr(2,9)}`,this._rendererHelpers=this._buildRendererHelpers(),this._config=selectConfig.getConfig(),this._engine.dispatch({type:"DISABLED_CHANGED",disabled:!this._config.enabled}),this._syncEngineSelectionConfig();const e=this;this._state={get isOpen(){return"open"===e._engine.state.popup},isBusy:!1,isSearching:!1,currentPage:this._config.infiniteScroll.initialPage||1,totalPages:1,selectedIndices:new Set,selectedItems:new Map,activeIndex:-1,searchQuery:"",loadedItems:[],groupedItems:[],preserveScrollPosition:!1,lastScrollPosition:0,lastNotifiedQuery:null,lastNotifiedResultCount:0,isExpanded:!1},this._container=this._createContainer(),this._inputContainer=this._createInputContainer(),this._inputContent=this._createInputContent(),this._input=this._createInput(),this._arrowContainer=this._createArrowContainer(),this._clearControl=this._createClearControl(),this._dropdown=this._createDropdown(),this._optionsContainer=this._createOptionsContainer(),this._liveRegion=this._createLiveRegion(),this._errorDescription=this._createErrorDescription(),this._initializeStyles(),this._syncStyleConfigVariables(),this._assembleDOM(),this._attachEventListeners(),this._initializeObservers(),this._syncComboboxAccessibility(),this._syncListboxAccessibility()}connectedCallback(){this._hasEverConnected=!0,EnhancedSelect._instances.add(this),this._runEngineEffects(this._engine.dispatch({type:"CONNECT"})),this._runEngineEffects(this._engine.dispatch({type:"DISABLED_CHANGED",disabled:!this._config.enabled})),this._connectionController?.abort(),this._connectionController=new AbortController,document.addEventListener("pointerdown",this._onDocumentPointerDown,{signal:this._connectionController.signal}),this.style.display="block",this._syncDirectionConfig(),this._syncComboboxAccessibility(),(this._dataRequestCoordinator||"acknowledged"===this._dataLoadingConfig.protocol)&&this._initializeObservers(),(this._optionRenderer||this._classMap||this._groupHeaderRenderer)&&this._setGlobalStylesMirroring(!0),this._config.serverSide.enabled&&this._config.serverSide.initialSelectedValues&&this._loadInitialSelectedItems(),(this._state.loadedItems.length>0||this._state.groupedItems.length>0)&&(this._renderOptions(),this._updateInputDisplay()),this._config.callbacks.onOpen&&this._config.callbacks.onOpen(),this._acknowledgedDeferredStart&&(this._acknowledgedDeferredStart=!1,this.startDataLoading())}attributeChangedCallback(e,t,i){t!==i&&("aria-busy"!==e?"aria-label"!==e&&"aria-description"!==e||(this._syncComboboxAccessibility(),"aria-label"===e&&this._syncListboxAccessibility()):this._syncListboxAccessibility())}disconnectedCallback(){if(this._cancelBusyPresentation(),this._dataRequestCoordinator){const e=this._dataRequestCoordinator.disconnect();this._acknowledgedReady=!1,this._dispatchAcknowledgedActions(e),this._state.isBusy=!1,this._state.isSearching=!1,this._state.preserveScrollPosition=!1}this._cancelDropdownExit(),this._dropdown.style.display="none",this._dropdown.setAttribute("inert",""),this._dropdown.setAttribute("aria-hidden","true"),EnhancedSelect._instances.delete(this),this._state.isOpen&&this._handleClose("disconnect"),this._runEngineEffects(this._engine.dispatch({type:"DISCONNECT"})),this._connectionController?.abort(),this._connectionController=void 0,this._asyncGeneration+=1,this._cancelGuardedVirtualWindowUpdate(),this._clearLifecycleTasks(),this._destroyGuardedVirtualizer(!0),this._virtualizationScope={...this._virtualizationScope,mountedKeys:[]},Array.from(this._optionsContainer.children).filter(e=>e.hasAttribute("data-index")||e.hasAttribute("data-virtual-spacer")).forEach(e=>e.remove()),this._resizeObserver?.disconnect(),this._intersectionObserver?.disconnect(),this._busyTimeout&&clearTimeout(this._busyTimeout),this._typeTimeout&&clearTimeout(this._typeTimeout),this._searchTimeout&&clearTimeout(this._searchTimeout),this._endMultiScrollDrag(),this._boundArrowClick&&this._arrowContainer&&this._arrowContainer.removeEventListener("click",this._boundArrowClick),this._renderCycleId+=1,this._resolvePendingRenderCycles(!1),this._teardownGlobalStylesMirroring()}_setGlobalStylesMirroring(e){this._mirrorGlobalStylesForCustomOptions!==e?(this._mirrorGlobalStylesForCustomOptions=e,this._track("style","globalStylesMirroringChanged",{enabled:e}),e?this._setupGlobalStylesMirroring():this._teardownGlobalStylesMirroring()):e&&this.isConnected&&!this._globalStylesObserver&&this._setupGlobalStylesMirroring()}_setLifecycleTimeout(e,t=0){const i=window.setTimeout(()=>{this._lifecycleTimers.delete(i),this.isConnected&&e()},t);return this._lifecycleTimers.add(i),i}_requestLifecycleFrame(e){const t=requestAnimationFrame(()=>{this._lifecycleRafs.delete(t),this.isConnected&&e()});return this._lifecycleRafs.add(t),t}_clearLifecycleTasks(){for(const e of this._lifecycleTimers)clearTimeout(e);this._lifecycleTimers.clear();for(const e of this._lifecycleRafs)cancelAnimationFrame(e);this._lifecycleRafs.clear()}_setupGlobalStylesMirroring(){"undefined"!=typeof document&&this._mirrorGlobalStylesForCustomOptions&&(this._setupThemeContextMirroring(),this._mirrorDocumentStylesIntoShadow(),this._globalStylesObserver||(this._globalStylesObserver=new MutationObserver(()=>{this._mirrorDocumentStylesIntoShadow()}),this._globalStylesObserver.observe(document.head,{childList:!0,subtree:!0,attributes:!0,characterData:!0})))}_teardownGlobalStylesMirroring(){this._globalStylesObserver&&(this._globalStylesObserver.disconnect(),this._globalStylesObserver=null),this._themeContextObserver&&(this._themeContextObserver.disconnect(),this._themeContextObserver=null),this._globalStylesContainer&&(this._globalStylesContainer.remove(),this._globalStylesContainer=null)}_mirrorDocumentStylesIntoShadow(){if("undefined"==typeof document)return;if(!this._mirrorGlobalStylesForCustomOptions)return;this._globalStylesContainer||(this._globalStylesContainer=document.createElement("div"),this._globalStylesContainer.setAttribute("data-smilodon-global-styles",""),this._shadow.appendChild(this._globalStylesContainer));const e=this._globalStylesContainer,t=++this._globalStylesSyncToken,i=Array.from(document.querySelectorAll('style,link[rel="stylesheet"]'));Promise.all(i.map((e,t)=>this._createScopedGlobalStyleNode(e,t))).then(i=>{this._globalStylesContainer&&t===this._globalStylesSyncToken&&(e.replaceChildren(...i.filter(e=>Boolean(e))),this._syncMirroredThemeContext())})}_setupThemeContextMirroring(){if("undefined"==typeof document)return;if(this._syncMirroredThemeContext(),this._themeContextObserver)return;this._themeContextObserver=new MutationObserver(()=>{this._syncMirroredThemeContext()});const e=new Set([this,document.documentElement]);document.body&&e.add(document.body);let t=this.parentElement;for(;t;)e.add(t),t=t.parentElement;e.forEach(e=>{this._themeContextObserver?.observe(e,{attributes:!0,attributeFilter:["class","dark-mode","darkmode","data-theme","theme"]})})}_syncMirroredThemeContext(){const e=this._optionsContainer;if(!e)return;const t=[".dark-mode",".dark","[dark-mode]","[darkmode]",'[data-theme="dark"]','[theme="dark"]'].some(e=>this.matches(e)||Boolean(this.closest(e)))||document.documentElement.matches('.dark-mode, .dark, [dark-mode], [darkmode], [data-theme="dark"], [theme="dark"]')||Boolean(document.body?.matches('.dark-mode, .dark, [dark-mode], [darkmode], [data-theme="dark"], [theme="dark"]'));e.classList.toggle("dark",t),e.classList.toggle("dark-mode",t),t?(e.setAttribute("dark-mode",""),e.setAttribute("data-theme","dark"),e.setAttribute("theme","dark")):(e.removeAttribute("dark-mode"),e.removeAttribute("data-theme"),e.removeAttribute("theme"))}async _createScopedGlobalStyleNode(e,t){if(e instanceof HTMLStyleElement)return this._buildScopedStyleElement(e.textContent||"",String(t));if(e instanceof HTMLLinkElement&&e.href){const i="use-credentials"===e.crossOrigin?"include":"same-origin",n=`${e.href}|${i}`;let o=EnhancedSelect._mirroredStylesheetTextCache.get(n);o?o.lastUsed=Date.now():(o={promise:fetch(e.href,{credentials:i,mode:"cors"}).then(e=>e.ok?e.text():null).catch(()=>null),lastUsed:Date.now()},EnhancedSelect._mirroredStylesheetTextCache.set(n,o),EnhancedSelect._pruneMirroredStylesheetTextCache());const s=await o.promise;return null===s?(EnhancedSelect._mirroredStylesheetTextCache.delete(n),null):this._buildScopedStyleElement(s,String(t))}return null}static _pruneMirroredStylesheetTextCache(){for(;EnhancedSelect._mirroredStylesheetTextCache.size>EnhancedSelect._MIRRORED_STYLESHEET_CACHE_LIMIT;){let e,t=1/0;for(const[i,n]of EnhancedSelect._mirroredStylesheetTextCache.entries())n.lastUsed<t&&(t=n.lastUsed,e=i);if(!e)return;EnhancedSelect._mirroredStylesheetTextCache.delete(e)}}_areClassMapsEqual(e,t){if(e===t)return!0;if(!e||!t)return!1;const i=Object.keys(e),n=Object.keys(t);return i.length===n.length&&i.every(i=>e[i]===t[i])}_buildScopedStyleElement(e,t){const i=this._scopeMirroredCssText(e);if(!i.trim())return null;const n=document.createElement("style");return n.setAttribute("data-smilodon-global-style",t),n.textContent=i,n}_scopeMirroredCssText(e){if(!e.trim())return"";try{if("undefined"!=typeof CSSStyleSheet&&"replaceSync"in CSSStyleSheet.prototype){const t=new CSSStyleSheet;return t.replaceSync(e),this._serializeScopedCssRules(Array.from(t.cssRules))}}catch(t){return this._scopeMirroredCssTextFallback(e)}return this._scopeMirroredCssTextFallback(e)}_scopeMirroredCssTextFallback(e){if(!e.trim())return"";const t=[],i=/([^{}]+)\{([^{}]+)\}/g;let n;for(;null!==(n=i.exec(e));){const e=n[1].trim(),i=n[2].trim();if(e.startsWith("@"))continue;const o=this._splitSelectorList(e).map(e=>this._scopeMirroredSelector(e)).filter(Boolean);o.length>0&&t.push(`${o.join(", ")} { ${i} }`)}return t.join("\n")}_serializeScopedCssRules(e){return e.map(e=>this._serializeScopedCssRule(e)).filter(Boolean).join("\n")}_serializeScopedCssRule(e){if(e instanceof CSSStyleRule){const t=this._splitSelectorList(e.selectorText).map(e=>this._scopeMirroredSelector(e)).filter(Boolean);return 0===t.length?"":`${t.join(", ")} { ${e.style.cssText} }`}if(e instanceof CSSMediaRule){const t=this._serializeScopedCssRules(Array.from(e.cssRules));return t?`@media ${e.conditionText} { ${t} }`:""}if("undefined"!=typeof CSSSupportsRule&&e instanceof CSSSupportsRule){const t=this._serializeScopedCssRules(Array.from(e.cssRules));return t?`@supports ${e.conditionText} { ${t} }`:""}if(e instanceof CSSFontFaceRule||e instanceof CSSKeyframesRule)return e.cssText;const t=e;if(t.cssRules){const e=this._serializeScopedCssRules(Array.from(t.cssRules));if(!e)return"";const i=t.constructor?.name??"";if(i.includes("Layer"))return`@layer ${t.name??""} { ${e} }`;if(i.includes("Container"))return`@container ${t.conditionText??""} { ${e} }`}return""}_splitSelectorList(e){const t=[];let i="",n=0,o=0;for(const s of e)"("===s&&(n+=1),")"===s&&(n=Math.max(0,n-1)),"["===s&&(o+=1),"]"===s&&(o=Math.max(0,o-1)),","!==s||0!==n||0!==o?i+=s:(i.trim()&&t.push(i.trim()),i="");return i.trim()&&t.push(i.trim()),t}_scopeMirroredSelector(e){const t=`.${EnhancedSelect._MIRRORED_STYLES_SCOPE_CLASS}`;let i=e.replace(/(^|\s|>|\+|~)(:root|html|body)(?=\b|\s|[.#[:>+~]|$)/g,`$1${t}`);let n=!1;return[/\.dark-mode(?![\w-]|\\:)/g,/\.dark(?![\w-]|\\:)/g,/\[dark-mode\]/g,/\[darkmode\]/g,/\[data-theme=(?:"dark"|'dark'|dark)\]/g,/\[theme=(?:"dark"|'dark'|dark)\]/g].forEach(e=>{i=i.replace(e,e=>(n=!0,`${e}${t}`))}),i.includes(EnhancedSelect._MIRRORED_STYLES_SCOPE_CLASS)||n||(i=`${t} ${i}`),i}_normalizeCustomOptionAccessibility(e,t){const i=this._customOptionNormalizedLabels.get(e),n=e.getAttribute("aria-label"),o=void 0!==i&&n===i;e.hasAttribute("aria-labelledby")||n&&!o?this._customOptionNormalizedLabels.delete(e):(e.setAttribute("aria-label",t.label),this._customOptionNormalizedLabels.set(e,t.label));const s=["a[href]","button","input","select","textarea","summary","[tabindex]",'[contenteditable=""]','[contenteditable="true"]','[role="button"]','[role="link"]','[role="checkbox"]','[role="switch"]','[role="radio"]','[role="textbox"]'].join(", ");e.querySelectorAll(s).forEach(i=>{i!==e&&(i.tabIndex=-1,i.hasAttribute("data-smilodon-keep-role")||i.setAttribute("role","presentation"),!t.disabled&&!i.matches("button, input, select, textarea, summary, a[href]")||i.hasAttribute("data-smilodon-keep-aria")||i.setAttribute("aria-hidden","true"))})}_createContainer(){const e=document.createElement("div");return e.className="select-container",this._config.styles.classNames?.container&&(e.className+=" "+this._config.styles.classNames.container),this._config.styles.container&&Object.assign(e.style,this._config.styles.container),e}_createInputContainer(){const e=document.createElement("div");e.className="input-container",e.setAttribute("part","button");const t=this._config.styles.input;if(t&&!this._config.styles.container){const i=["background","backgroundColor","border","borderColor","borderStyle","borderWidth","borderRadius","boxShadow","padding","height","minHeight","maxHeight"];for(const n of i){const i=t[n];null!=i&&""!==i&&(e.style[n]=i)}}return e}_createInputContent(){const e=document.createElement("div");return e.className="input-content",e}_setCssVariable(e,t){null!=t&&""!==t?this.style.setProperty(e,String(t)):this.style.removeProperty(e)}_applyStyleVariableMap(e,t){Object.entries(t).forEach(([t,i])=>{this._setCssVariable(i,e?.[t])})}_getDisabledOptionBehavior(){const e=this._config.selection.disabledOptionBehavior??{};return{selectable:!0===e.selectable,hoverable:!0===e.hoverable,focusable:!0===e.focusable}}_isDisabledOptionSelectable(e){return Boolean(e?.disabled)&&this._getDisabledOptionBehavior().selectable}_isOptionSelectionBlocked(e){return Boolean(e?.disabled)&&!this._isDisabledOptionSelectable(e)}_isPhase2DevRuntime(){const e=globalThis.process?.env?.NODE_ENV;return"production"!==e}_getDuplicateKeyPolicy(){return this._isPhase2DevRuntime()?"throw":"warn"}_warnPhase2(e){this._isPhase2DevRuntime()&&"undefined"!=typeof console&&console.warn(e)}_getItemValue(e){return this._config.serverSide.getValueFromItem?.(e)??e?.value??e}_getItemLabel(e){return this._config.serverSide.getLabelFromItem?.(e)??e?.label??String(e)}_createEngineItemAdapter(){return createDefaultItemAdapter({getValue:e=>this._getItemValue(e),getLabel:e=>this._getItemLabel(e),isDisabled:e=>Boolean(e?.disabled),getGroupKey:e=>{const t=e?.group;return null==t?null:String(t)},onIndexFallback:e=>this._warnPhase2(e)})}_getBlockedDisabledKeys(){const e=this._itemRegistry.records.filter(e=>e.disabled&&this._isOptionSelectionBlocked(e.item)).map(e=>e.key);for(const t of this._getSelectedEntries())this._isOptionSelectionBlocked(t.item)&&e.push(t.key);return e}_syncEngineSelectionConfig(){const e=Boolean(this._input?.hasAttribute("required")),t=this._getBlockedDisabledKeys();this._engine.dispatch({type:"SELECTION_CONFIG_CHANGED",multiple:"multi"===this._config.selection.mode,required:e,allowDeselect:!0===this._config.selection.allowDeselect,maxSelections:this._config.selection.maxSelections??0,disabledKeys:t}),this._state&&(this._syncLegacySelectionFromEngine(),this._syncLegacyActiveFromEngine(),this._assertSelectionProjection("selection config"),this._assertActiveProjection("selection config"))}_rebuildItemRegistry(e=this._state.loadedItems,t){const i=t??createItemRegistry(e,this._itemAdapter,{duplicateKeyPolicy:this._getDuplicateKeyPolicy()}),n=this._engine.state.activeKey,o=null===this._rangeAnchorIndex?void 0:this._itemRegistry.indexToKey.get(this._rangeAnchorIndex);this._itemRegistry=i,this._state.loadedItems=e,this._registryItemsRef=e;const s=this._getBlockedDisabledKeys();this._rangeAnchorIndex=void 0===o?null:i.keyToIndex.get(o)??null,this._engine.dispatch({type:"ITEMS_REGISTERED",keys:i.records.map(e=>e.key),disabledKeys:s}),null!==n&&i.keyToRecord.get(n)?.disabled?this._dispatchActiveKey(null,"programmatic","items registered with disabled active key"):this._syncLegacyActiveFromEngine(),this._syncLegacySelectionFromEngine(),this._syncEngineSelectionConfig(),this._assertSelectionProjection("items registered")}_ensureRegistryCurrent(){this._registryItemsRef!==this._state.loadedItems||this._itemRegistry.records.length!==this._state.loadedItems.length||this._itemRegistry.records.some((e,t)=>e.item!==this._state.loadedItems[t])?this._rebuildItemRegistry():(this._syncLegacySelectionFromEngine(),this._syncLegacyActiveFromEngine(),this._assertSelectionProjection("registry read"),this._assertActiveProjection("registry read"))}_getRecordByIndex(e){const t=this._itemRegistry.indexToKey.get(e);return void 0===t?null:this._itemRegistry.keyToRecord.get(t)??null}_getSelectedEntries(){const e=[];if(!this._state)return e;for(const t of this._engine.state.selectedKeys){const i=this._itemRegistry.keyToRecord.get(t)??this._selectedRecordsByKey.get(t);i&&e.push({key:t,index:i.index,item:i.item})}return e}_syncLegacySelectionFromEngine(){const e=new Set,t=new Map,i=this._engine.state.selectedKeys;for(const e of[...this._selectedRecordsByKey.keys()])i.has(e)||this._selectedRecordsByKey.delete(e);for(const n of i){const i=this._itemRegistry.keyToRecord.get(n);i&&this._selectedRecordsByKey.set(n,i),i&&(e.add(i.index),t.set(i.index,i.item))}this._state.selectedIndices=e,this._state.selectedItems=t}_projectedSelectedKeysSnapshot(){return new Set([...this._state.selectedIndices].map(e=>this._itemRegistry.indexToKey.get(e)).filter(e=>void 0!==e))}_assertSelectionProjection(e){if(!this._isPhase2DevRuntime())return;const t=this._projectedSelectedKeysSnapshot(),i=this._engine.state.selectedKeys;if(this._state.selectedItems.size!==this._state.selectedIndices.size||[...this._state.selectedIndices].some(e=>!this._state.selectedItems.has(e))||[...i].some(e=>this._itemRegistry.keyToRecord.has(e)&&!t.has(e))||[...t].some(e=>!i.has(e)))throw new Error(`[Smilodon Phase2] Selection projection failed in ${e}: compatibility=${JSON.stringify([...t])}, engine=${JSON.stringify([...i])}`)}_projectedActiveKeySnapshot(){return this._state.activeIndex<0?null:this._itemRegistry.indexToKey.get(this._state.activeIndex)??null}_syncLegacyActiveFromEngine(){const e=this._engine.state.activeKey;this._state.activeIndex=null===e?-1:this._itemRegistry.keyToIndex.get(e)??-1,this._syncLegacyActiveAria()}_assertActiveProjection(e){if(!this._isPhase2DevRuntime())return;const t=this._projectedActiveKeySnapshot(),i=this._engine.state.activeKey;if(t!==i&&!Object.is(t,i))throw new Error(`[Smilodon Phase2] Active projection failed in ${e}: compatibility=${String(t)}, engine=${String(i)}`)}_dispatchActiveKey(e,t,i){const n=this._engine.dispatch({type:"ACTIVE_KEY_CHANGED",key:e,reason:t});this._runEngineEffects(n),this._syncLegacyActiveFromEngine(),this._assertActiveProjection(i)}_clearDisabledEngineActive(e){const t=this._engine.state.activeKey;null!==t&&this._itemRegistry.keyToRecord.get(t)?.disabled?this._dispatchActiveKey(null,"programmatic",e):(this._syncLegacyActiveFromEngine(),this._assertActiveProjection(e))}_mirrorLegacyActive(e,t){this._dispatchActiveKey(this._projectedActiveKeySnapshot(),e,t)}_dispatchSelection(e,t){this._engine.dispatch(e),this._syncLegacySelectionFromEngine(),this._assertSelectionProjection(t)}_mirrorLegacySelection(e,t){this._dispatchSelection(e,t)}_requestSelectionReplacement(e,t,i){for(const t of e){const e=this._itemRegistry.keyToRecord.get(t.key)??this._selectedRecordsByKey.get(t.key);this._selectedRecordsByKey.set(t.key,e??{key:t.key,item:t.item,index:t.index,label:this._getItemLabel(t.item),value:this._getItemValue(t.item),disabled:Boolean(t.item?.disabled),groupKey:null==t.item?.group?null:String(t.item.group)})}this._dispatchSelection({type:"REPLACE_SELECTION_REQUEST",keys:e.map(({key:e})=>e),reason:t},i)}_registerShadowItems(e){const t=e.map(e=>this._itemRegistry.indexToKey.get(e)).filter(e=>void 0!==e);this._engine.dispatch({type:"ITEMS_REGISTERED",keys:t,disabledKeys:this._getBlockedDisabledKeys()}),this._clearDisabledEngineActive("visible items"),this._assertSelectionProjection("visible items")}_syncLegacyActiveAria(){this._syncComboboxAccessibility()}_syncStyleConfigVariables(){const e=this._config.styles;e&&(this._applyStyleVariableMap(e.option,{background:"--select-option-bg",backgroundColor:"--select-option-bg",color:"--select-option-color",border:"--select-option-border",borderBottom:"--select-option-border-bottom",borderRadius:"--select-option-border-radius",boxShadow:"--select-option-shadow",transform:"--select-option-transform",padding:"--select-option-padding",margin:"--select-option-margin",fontSize:"--select-option-font-size",fontWeight:"--select-option-font-weight",lineHeight:"--select-option-line-height",textAlign:"--select-option-text-align"}),this._applyStyleVariableMap(e.selectedOption,{background:"--select-option-selected-bg",backgroundColor:"--select-option-selected-bg",color:"--select-option-selected-color",border:"--select-option-selected-border",borderBottom:"--select-option-selected-border-bottom",borderRadius:"--select-option-selected-border-radius",boxShadow:"--select-option-selected-shadow",transform:"--select-option-selected-transform",fontWeight:"--select-option-selected-weight"}),this._applyStyleVariableMap(e.hoverOption,{background:"--select-option-hover-bg",backgroundColor:"--select-option-hover-bg",color:"--select-option-hover-color",border:"--select-option-hover-border",borderBottom:"--select-option-hover-border-bottom",boxShadow:"--select-option-hover-shadow",transform:"--select-option-hover-transform"}),this._applyStyleVariableMap(e.activeOption,{background:"--select-option-active-bg",backgroundColor:"--select-option-active-bg",color:"--select-option-active-color",border:"--select-option-active-border",outline:"--select-option-active-outline",outlineOffset:"--select-option-active-outline-offset",boxShadow:"--select-option-active-shadow",transform:"--select-option-active-transform"}),this._applyStyleVariableMap(e.disabledOption,{background:"--select-option-disabled-bg",backgroundColor:"--select-option-disabled-bg",color:"--select-option-disabled-color",border:"--select-option-disabled-border",borderBottom:"--select-option-disabled-border-bottom",opacity:"--select-option-disabled-opacity",cursor:"--select-option-disabled-cursor"}),this._applyStyleVariableMap(e.selectedIndicator,{width:"--select-option-selected-indicator-width",height:"--select-option-selected-indicator-height",background:"--select-option-selected-indicator-bg",backgroundColor:"--select-option-selected-indicator-bg",borderRadius:"--select-option-selected-indicator-radius",left:"--select-option-selected-indicator-left",right:"--select-option-selected-indicator-right",top:"--select-option-selected-indicator-top",transform:"--select-option-selected-indicator-transform",animation:"--select-option-selected-indicator-animation"}),this._setCssVariable("--select-option-selected-indicator-display",!1===this._config.selection.showSelectedIndicator?"none":e.selectedIndicator?.display),this._applyStyleVariableMap(e.badge,{width:"--select-badge-width",minWidth:"--select-badge-min-width",maxWidth:"--select-badge-max-width",height:"--select-badge-height",minHeight:"--select-badge-min-height",padding:"--select-badge-padding",margin:"--select-badge-margin",gap:"--select-badge-gap",background:"--select-badge-bg",backgroundColor:"--select-badge-bg",color:"--select-badge-color",border:"--select-badge-border",borderRadius:"--select-badge-border-radius",boxShadow:"--select-badge-shadow",fontSize:"--select-badge-font-size",fontWeight:"--select-badge-font-weight",lineHeight:"--select-badge-line-height",letterSpacing:"--select-badge-letter-spacing"}),this._applyStyleVariableMap(e.badgeHover,{background:"--select-badge-hover-bg",backgroundColor:"--select-badge-hover-bg",color:"--select-badge-hover-color",border:"--select-badge-hover-border",boxShadow:"--select-badge-hover-shadow",transform:"--select-badge-hover-transform"}),this._applyStyleVariableMap(e.badgeActive,{background:"--select-badge-active-bg",backgroundColor:"--select-badge-active-bg",color:"--select-badge-active-color",border:"--select-badge-active-border",boxShadow:"--select-badge-active-shadow",transform:"--select-badge-active-transform"}),this._applyStyleVariableMap(e.badgeLabel,{color:"--select-badge-label-color",fontSize:"--select-badge-label-font-size",fontWeight:"--select-badge-label-font-weight",lineHeight:"--select-badge-label-line-height",letterSpacing:"--select-badge-label-letter-spacing",textAlign:"--select-badge-label-text-align"}),this._applyStyleVariableMap(e.badgeRemove,{width:"--select-badge-remove-size",height:"--select-badge-remove-size",minWidth:"--select-badge-remove-min-width",minHeight:"--select-badge-remove-min-height",marginLeft:"--select-badge-remove-margin-left",background:"--select-badge-remove-bg",backgroundColor:"--select-badge-remove-bg",border:"--select-badge-remove-border",borderRadius:"--select-badge-remove-radius",color:"--select-badge-remove-color",fontSize:"--select-badge-remove-font-size",fontWeight:"--select-badge-remove-font-weight"}),this._applyStyleVariableMap(e.badgeRemoveIcon,{width:"--select-badge-remove-icon-size",height:"--select-badge-remove-icon-size",color:"--select-badge-remove-icon-color",fontSize:"--select-badge-remove-icon-font-size",lineHeight:"--select-badge-remove-icon-line-height",transform:"--select-badge-remove-icon-transform",opacity:"--select-badge-remove-icon-opacity"}),this._applyStyleVariableMap(e.badgeRemoveHover,{background:"--select-badge-remove-hover-bg",backgroundColor:"--select-badge-remove-hover-bg",color:"--select-badge-remove-hover-color",border:"--select-badge-remove-hover-border",boxShadow:"--select-badge-remove-hover-shadow",transform:"--select-badge-remove-hover-transform"}),this._applyStyleVariableMap(e.badgeRemoveActive,{background:"--select-badge-remove-active-bg",backgroundColor:"--select-badge-remove-active-bg",color:"--select-badge-remove-active-color",border:"--select-badge-remove-active-border",boxShadow:"--select-badge-remove-active-shadow",transform:"--select-badge-remove-active-transform"}),this._applyStyleVariableMap(e.groupHeader,{padding:"--select-group-header-padding",margin:"--select-group-header-margin",color:"--select-group-header-color",background:"--select-group-header-bg",backgroundColor:"--select-group-header-bg",border:"--select-group-header-border",borderBottom:"--select-group-header-border-bottom",borderRadius:"--select-group-header-border-radius",boxShadow:"--select-group-header-shadow",textAlign:"--select-group-header-text-align",fontSize:"--select-group-header-font-size",fontWeight:"--select-group-header-weight",textTransform:"--select-group-header-text-transform",letterSpacing:"--select-group-header-letter-spacing"}))}_resolveDropdownPlacement(){const e=this._config.dropdownPlacement?.mode??"bottom";if("bottom"===e||"top"===e)return e;const t=this._container.getBoundingClientRect(),i=window.innerHeight-t.bottom,n=window.getComputedStyle(this._dropdown),o=Number.parseFloat(n.maxHeight||"0");return i>=(Number.isFinite(o)&&o>0?Math.min(this._dropdown.scrollHeight,o):this._dropdown.scrollHeight)?"bottom":"top"}_syncDropdownPlacement(){this._dropdown&&(this._resolvedDropdownPlacement=this._resolveDropdownPlacement(),this._dropdown.setAttribute("data-placement",this._resolvedDropdownPlacement))}_syncDirectionConfig(){this.isConnected&&this.setAttribute("dir",this._config.direction??"ltr")}_setIconContent(e,t,i){const n=t&&t.trim()?t:i;e.innerHTML="",n.trim().startsWith("<")?e.innerHTML=n:e.textContent=n}_syncInputContainerMode(){if(!this._inputContainer||!this._input)return;const e="multi"===this._config.selection.mode;this._inputContainer.classList.toggle("input-container--multi",e),this._inputContainer.classList.toggle("input-container--single",!e),e?(this._input.style.flex="1 0 var(--select-multi-input-min-width, 96px)",this._input.style.width="auto",this._input.style.minWidth="var(--select-multi-input-min-width, 96px)"):(this._input.style.flex="1 1 auto",this._input.style.width="100%",this._input.style.minWidth="0"),this._syncMultiSelectDisplayConfig()}_syncMultiSelectDisplayConfig(){if(!this._inputContainer||!this._input)return;const e="multi"===this._config.selection.mode,t=this._config.multiSelectDisplay?.mode??"wrap",i=!1!==this._config.multiSelectDisplay?.dragScroll;if(!e)return this._inputContainer.removeAttribute("data-multi-scroll-mode"),this._inputContainer.removeAttribute("data-drag-scroll"),this._inputContainer.classList.remove("is-dragging-scroll"),this._inputContainer.style.removeProperty("--select-multi-input-max-height-config"),this._inputContainer.style.removeProperty("--select-multi-input-overflow-x-config"),this._inputContainer.style.removeProperty("--select-multi-input-overflow-y-config"),this._inputContainer.style.removeProperty("--select-multi-input-flex-wrap-config"),void this._inputContainer.style.removeProperty("--select-multi-input-align-content-config");const n=this._config.multiSelectDisplay?.maxHeight,o="160px";let s=n??"none",r=this._config.multiSelectDisplay?.overflowX??"hidden",a=this._config.multiSelectDisplay?.overflowY??"hidden",l="wrap",c="flex-start";"vertical"===t?(s=n??o,a=this._config.multiSelectDisplay?.overflowY??"auto"):"horizontal"===t&&(s=n??o,r=this._config.multiSelectDisplay?.overflowX??"auto",a=this._config.multiSelectDisplay?.overflowY??"hidden",l="nowrap",c="center"),this._inputContainer.setAttribute("data-multi-scroll-mode",t),this._inputContainer.setAttribute("data-drag-scroll",String(i&&"horizontal"===t)),this._inputContainer.style.setProperty("--select-multi-input-max-height-config",s),this._inputContainer.style.setProperty("--select-multi-input-overflow-x-config",r),this._inputContainer.style.setProperty("--select-multi-input-overflow-y-config",a),this._inputContainer.style.setProperty("--select-multi-input-flex-wrap-config",l),this._inputContainer.style.setProperty("--select-multi-input-align-content-config",c)}_canUseHorizontalMultiScroll(e){return"multi"===this._config.selection.mode&&("horizontal"===(this._config.multiSelectDisplay?.mode??"wrap")&&(!1!==this._config.multiSelectDisplay?.dragScroll&&(!e||!e.closest(".dropdown-arrow-container, .clear-control-button, .badge-remove")&&!e.matches(".select-input"))))}_isScrollableMultiSelectMode(){if("multi"!==this._config.selection.mode)return!1;const e=this._config.multiSelectDisplay?.mode??"wrap";return"vertical"===e||"horizontal"===e}_isPointerOnInputScrollbar(e){if(!this._isScrollableMultiSelectMode())return!1;const t=this._inputContent.getBoundingClientRect(),i=this._inputContent.offsetWidth-this._inputContent.clientWidth,n=this._inputContent.offsetHeight-this._inputContent.clientHeight;return i>0&&e.clientX>=t.right-i&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom||n>0&&e.clientY>=t.bottom-n&&e.clientY<=t.bottom&&e.clientX>=t.left&&e.clientX<=t.right}_beginMultiScrollDrag(e){const t=this._inputContent;this._multiScrollDrag.active=!0,this._multiScrollDrag.moved=!1,this._multiScrollDrag.pointerId=e.pointerId,this._multiScrollDrag.startX=e.clientX,this._multiScrollDrag.startScrollLeft=t.scrollLeft,this._inputContainer.classList.add("is-dragging-scroll");try{t.setPointerCapture(e.pointerId)}catch(e){}}_updateMultiScrollDrag(e){if(!this._multiScrollDrag.active||this._multiScrollDrag.pointerId!==e.pointerId)return;const t=e.clientX-this._multiScrollDrag.startX;Math.abs(t)>3&&(this._multiScrollDrag.moved=!0),this._inputContent.scrollLeft=this._multiScrollDrag.startScrollLeft-t}_endMultiScrollDrag(e){if(this._multiScrollDrag.active&&(null==e||this._multiScrollDrag.pointerId===e)){try{this._multiScrollDrag.pointerId>=0&&this._inputContent.releasePointerCapture(this._multiScrollDrag.pointerId)}catch(e){}this._multiScrollDrag.active=!1,this._multiScrollDrag.pointerId=-1,this._inputContainer.classList.remove("is-dragging-scroll")}}_createInput(){const e=document.createElement("input");if(e.setAttribute("part","input"),e.type="text",e.className="select-input",e.id=`${this._uniqueId}-input`,e.placeholder=this._config.placeholder||"Select an option...",e.disabled=!this._config.enabled,e.readOnly=!this._config.searchable,e.style.all="unset",e.style.display="block",e.style.flex="1 1 auto",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.minInlineSize="0",e.style.minHeight="0",e.style.padding="0",e.style.margin="0",e.style.border="0",e.style.background="transparent",e.style.boxSizing="border-box",e.style.outline="none",e.style.font="inherit",e.style.fontFamily="inherit",e.style.lineHeight="inherit",e.style.color="inherit",e.style.alignSelf="center",e.style.appearance="none",e.style.webkitAppearance="none",e.style.boxShadow="none",e.style.borderRadius="0",e.style.overflow="hidden",e.style.textOverflow="ellipsis",e.style.whiteSpace="nowrap",e.style.cursor=this._config.searchable?"text":"default",e.addEventListener("focus",()=>{this._config.searchable&&(e.readOnly=!1)}),this._config.styles.classNames?.input&&(e.className+=" "+this._config.styles.classNames.input),this._config.styles.input){const t={...this._config.styles.input};delete t.background,delete t.backgroundColor,delete t.border,delete t.borderColor,delete t.borderStyle,delete t.borderWidth,delete t.borderRadius,delete t.boxShadow,delete t.padding,delete t.height,delete t.minHeight,delete t.maxHeight,Object.assign(e.style,t)}return e.setAttribute("aria-haspopup","listbox"),e}_createDropdown(){const e=document.createElement("div");return e.className="select-dropdown",e.setAttribute("part","listbox"),e.style.display="none",this._config.styles.classNames?.dropdown&&(e.className+=" "+this._config.styles.classNames.dropdown),this._config.styles.dropdown&&Object.assign(e.style,this._config.styles.dropdown),e}_createOptionsContainer(){const e=document.createElement("div");return e.className=`options-container ${EnhancedSelect._MIRRORED_STYLES_SCOPE_CLASS}`,e}_createLiveRegion(){const e=document.createElement("div");return e.setAttribute("role","status"),e.setAttribute("aria-live","polite"),e.setAttribute("aria-atomic","true"),e.style.cssText="position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0;",e}_createErrorDescription(){const e=document.createElement("div");return e.id=`${this._uniqueId}-error`,e.style.cssText="position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0;",e}_createArrowContainer(){const e=document.createElement("div");e.className="dropdown-arrow-container",e.innerHTML='\n <slot name="arrow">\n <svg class="dropdown-arrow" part="arrow" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">\n <path d="M4 6L8 10L12 6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n </slot>\n ';const t=e.querySelector('slot[name="arrow"]');return t?.addEventListener("slotchange",()=>{t.assignedElements({flatten:!0}).length>0?this.setAttribute("data-custom-arrow","true"):this.removeAttribute("data-custom-arrow")}),e}_createClearControl(){const e=document.createElement("button");e.type="button",e.className="clear-control-button",e.setAttribute("part","clear-button");const t=document.createElement("span");return t.className="clear-control-icon",t.setAttribute("part","clear-icon"),this._config.clearControl.icon?t.textContent=this._config.clearControl.icon:t.innerHTML='<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 4L4 12M4 4L12 12" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',e.setAttribute("aria-label",this._config.clearControl.ariaLabel||"Clear selection and search"),e.appendChild(t),this._clearControlIcon=t,e}_assembleDOM(){this._inputContent.appendChild(this._input),this._inputContainer.appendChild(this._inputContent),this._clearControl&&this._inputContainer.appendChild(this._clearControl),this._arrowContainer&&this._inputContainer.appendChild(this._arrowContainer),this._container.appendChild(this._inputContainer),this._dropdown.appendChild(this._optionsContainer),this._container.appendChild(this._dropdown),this._shadow.appendChild(this._container),this._liveRegion&&this._shadow.appendChild(this._liveRegion),this._errorDescription&&this._shadow.appendChild(this._errorDescription);const e=`${this._uniqueId}-listbox`;this._dropdown.id=e,this._input.setAttribute("aria-owns",e),this._syncInputContainerMode(),this._syncClearControlState()}_initializeStyles(){const e=document.createElement("style");e.textContent='\n /* ═══════════════════════════════════════════════════════════════════════════\n ELEGANT SELECT COMPONENT — Refined Design System\n Formal aesthetics with sophisticated microinteractions\n ═══════════════════════════════════════════════════════════════════════════ */\n \n :host {\n --select-primary: #1a1a2e;\n --select-primary-light: #16213e;\n --select-accent: #0f3460;\n --select-accent-hover: #e94560;\n --select-surface: #ffffff;\n --select-surface-elevated: rgba(0, 0, 0, 0.04);\n --select-border: #e1e5eb;\n --select-border-focus: #0f3460;\n --select-text: #1a1a2e;\n --select-text-muted: #6b7280;\n --select-text-placeholder: #9ca3af;\n --select-shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.04);\n --select-shadow-md: 0 4px 12px rgba(0, 0, 0, 0.08);\n --select-shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.12);\n --select-shadow-focus: 0 0 0 3px rgba(15, 52, 96, 0.12);\n --select-radius-sm: 6px;\n --select-radius-md: 10px;\n --select-radius-lg: 14px;\n --select-transition-fast: 150ms cubic-bezier(0.4, 0, 0.2, 1);\n --select-transition-smooth: 250ms cubic-bezier(0.4, 0, 0.2, 1);\n --select-transition-bounce: 350ms cubic-bezier(0.34, 1.56, 0.64, 1);\n --select-badge-animation: badgeEnter 300ms cubic-bezier(0.34, 1.56, 0.64, 1) forwards;\n --select-badge-enter-from-opacity: 0;\n --select-badge-enter-from-transform: scale(0.8) translateY(-4px);\n --select-badge-enter-to-opacity: 1;\n --select-badge-enter-to-transform: scale(1) translateY(0);\n --select-badge-active-transform: scale(0.98);\n --select-badge-hover-transform: scale(1.02);\n --select-badge-letter-spacing: 0.01em;\n --select-badge-hover-shadow: var(--select-shadow-md), inset 0 1px 0 rgba(255, 255, 255, 0.15);\n --select-badge-remove-icon-size: 10px;\n --select-badge-remove-icon-color: currentColor;\n --select-badge-remove-icon-font-size: inherit;\n --select-badge-remove-icon-line-height: 1;\n --select-badge-remove-icon-transform: none;\n --select-badge-remove-icon-opacity: 1;\n --select-badge-remove-focus-outline: 2px solid rgba(255, 255, 255, 0.5);\n --select-badge-remove-focus-offset: 1px;\n --select-badge-remove-hover-transform: scale(1.15) rotate(90deg);\n --select-badge-remove-active-transform: scale(0.95) rotate(90deg);\n --select-input-hover-border: var(--select-border-focus);\n --select-input-hover-shadow: var(--select-shadow-sm), 0 0 0 1px rgba(15, 52, 96, 0.05);\n --select-input-font-weight: 450;\n --select-input-letter-spacing: 0.01em;\n --select-input-disabled-opacity: 0.6;\n --select-input-overflow-x: hidden;\n --select-input-align-items: center;\n --select-input-align-content: center;\n --select-input-align-self: center;\n --select-multi-input-max-height: 160px;\n --select-multi-input-overflow-x: hidden;\n --select-multi-input-overflow-y: auto;\n --select-multi-input-flex-wrap: wrap;\n --select-multi-input-align-content: flex-start;\n --select-multi-input-horizontal-height: var(--select-input-min-height, 48px);\n --select-multi-input-horizontal-input-flex: 0 0 var(--select-multi-input-min-width, 96px);\n --select-multi-input-horizontal-cursor: grab;\n --select-multi-input-horizontal-active-cursor: grabbing;\n --select-multi-input-end-gap: 12px;\n --select-multi-separator-inset-block: 10px;\n --select-multi-separator-height: auto;\n --select-multi-action-surface-bg: var(--select-input-bg, var(--select-surface));\n --select-multi-action-divider: 1px solid var(--select-border);\n --select-separator-width: 1px;\n --select-separator-inset-block: 10px;\n --select-separator-height: auto;\n --select-separator-display: block;\n --select-separator-opacity: 0.6;\n --select-separator-active-opacity: 1;\n --select-separator-position: var(--select-arrow-width, 42px);\n --select-separator-position-with-clear: calc(var(--select-arrow-right-with-clear, 34px) + var(--select-arrow-width, 42px));\n --select-separator-dark-bg: linear-gradient(\n to bottom,\n transparent 0%,\n var(--select-border) 20%,\n var(--select-border) 80%,\n transparent 100%\n );\n --select-arrow-open-transform: rotate(180deg);\n --select-clear-button-hover-transform: translateY(-50%) scale(1.1);\n --select-clear-button-active-transform: translateY(-50%) scale(0.95);\n --select-clear-button-focus-offset: 2px;\n --select-clear-icon-size: 14px;\n --select-dropdown-top: calc(100% + 6px);\n --select-dropdown-bottom: calc(100% + 6px);\n --select-dropdown-animation: dropdownEnter 200ms cubic-bezier(0.4, 0, 0.2, 1) forwards;\n --select-dropdown-exit-animation: dropdownExit 160ms cubic-bezier(0.4, 0, 1, 1) forwards;\n --select-dropdown-exit-from-opacity: 1;\n --select-dropdown-exit-from-transform: translateY(0) scale(1);\n --select-dropdown-exit-to-opacity: 0;\n --select-dropdown-exit-to-transform: translateY(-8px) scale(0.98);\n --select-dropdown-top-exit-to-transform: translateY(8px) scale(0.98);\n --select-dropdown-enter-from-opacity: 0;\n --select-dropdown-enter-from-transform: translateY(-8px) scale(0.98);\n --select-dropdown-enter-to-opacity: 1;\n --select-dropdown-enter-to-transform: translateY(0) scale(1);\n --select-dropdown-top-transform-origin: bottom center;\n --select-dropdown-top-enter-from-transform: translateY(8px) scale(0.98);\n --select-dropdown-padding: 6px;\n --select-dropdown-scroll-behavior: smooth;\n --select-dropdown-transform-origin: top center;\n --select-scrollbar-width: 6px;\n --select-scrollbar-thumb-radius: 3px;\n --select-option-hover-enabled: 1;\n --select-option-hover-transform: none;\n --select-option-font-weight: 450;\n --select-option-margin: 2px 0;\n --select-input-font-size: inherit;\n --select-input-font-weight: 400;\n --select-multi-container-padding: 6px;\n --select-input-font-size: inherit;\n --select-input-font-weight: 400;\n --select-multi-container-padding: 6px;\n --select-option-disabled-opacity: 0.5;\n --select-option-disabled-cursor: not-allowed;\n --select-option-active-outline: none;\n --select-option-active-outline-offset: -2px;\n --select-option-selected-active-bg: var(--select-option-selected-hover-bg, var(--select-option-selected-bg, linear-gradient(135deg, rgba(15, 52, 96, 0.12) 0%, rgba(15, 52, 96, 0.06) 100%)));\n --select-option-selected-active-color: var(--select-option-selected-hover-color, var(--select-option-selected-color, var(--select-accent)));\n --select-option-selected-active-border: var(--select-option-selected-hover-border, var(--select-option-selected-border, var(--select-option-border, none)));\n --select-option-selected-active-shadow: var(--select-option-active-shadow, none);\n --select-option-selected-active-transform: var(--select-option-active-transform, none);\n --select-option-selected-active-outline: none;\n --select-option-selected-active-outline-offset: -2px;\n --select-option-selected-indicator-display: block;\n --select-option-selected-indicator-width: 3px;\n --select-option-selected-indicator-height: 60%;\n --select-option-selected-indicator-bg: var(--select-accent);\n --select-option-selected-indicator-radius: 0 2px 2px 0;\n --select-option-selected-indicator-left: 0;\n --select-option-selected-indicator-top: 50%;\n --select-option-selected-indicator-transform: translateY(-50%);\n --select-option-selected-indicator-animation: selectedIndicator 200ms cubic-bezier(0.34, 1.56, 0.64, 1) forwards;\n --select-option-selected-indicator-from-height: 0;\n --select-option-selected-indicator-to-height: 60%;\n --select-option-selected-indicator-from-opacity: 0;\n --select-option-selected-indicator-to-opacity: 1;\n --select-option-pressed-transform: none;\n --select-option-selected-pressed-transform: none;\n --select-button-hover-transform: translateY(-1px);\n --select-button-active-transform: translateY(0) scale(0.98);\n --select-button-font-weight: 550;\n --select-button-letter-spacing: 0.02em;\n --select-spinner-animation: spin 0.8s cubic-bezier(0.4, 0, 0.2, 1) infinite;\n --select-searching-spinner-active-color: var(--select-accent);\n --select-badge-remove-margin-left: 2px;\n --select-badge-remove-radius: 50%;\n --select-badge-remove-font-weight: 600;\n --select-empty-gap: 8px;\n --select-searching-gap: 8px;\n --select-searching-spinner-size: 24px;\n --select-searching-spinner-border: 2px solid var(--select-border);\n --select-searching-spinner-animation: var(--select-spinner-animation);\n --select-group-header-separator-margin-top: 0;\n --select-group-header-separator-padding-top: 0;\n --select-group-header-separator-border-top: none;\n --select-reduced-motion-duration: 0.01ms;\n --select-reduced-motion-iteration-count: 1;\n --select-high-contrast-border-width: 2px;\n --select-high-contrast-indicator-width: 4px;\n --select-high-contrast-focus-outline-width: 3px;\n --select-high-contrast-focus-outline-color: Highlight;\n --select-touch-target-min-height: 44px;\n --select-badge-dark-bg: linear-gradient(135deg, var(--select-accent) 0%, #4f46e5 100%);\n --select-host-z-index: auto;\n --select-host-open-z-index: var(--select-dropdown-z-index, 1000);\n --select-ancestor-open-z-index: var(--select-host-open-z-index, var(--select-dropdown-z-index, 1000));\n \n display: block;\n position: relative;\n z-index: var(--select-host-z-index, auto);\n width: var(--select-width, 100%);\n height: var(--select-height, auto);\n font-family: var(--select-font-family, inherit);\n font-size: var(--select-font-size, inherit);\n line-height: var(--select-line-height, inherit);\n color: var(--select-color, inherit);\n }\n\n :host([data-open="true"]) {\n z-index: var(--select-host-open-z-index, var(--select-dropdown-z-index, 1000));\n }\n\n :host([dir="ltr"]) {\n direction: ltr;\n }\n\n :host([dir="rtl"]) {\n direction: rtl;\n }\n\n /* ─────────────────────────────────────────────────────────────────────────\n Selection Badges — Refined pill design with elegant interactions\n ───────────────────────────────────────────────────────────────────────── */\n \n .selection-badge {\n display: inline-flex;\n align-items: center;\n gap: var(--select-badge-gap, 6px);\n flex: 0 1 auto;\n width: var(--select-badge-width, auto);\n min-width: var(--select-badge-min-width, 0);\n height: var(--select-badge-height, auto);\n min-height: var(--select-badge-min-height, 26px);\n padding: var(--select-badge-padding, 4px 10px 4px 12px);\n margin: var(--select-badge-margin, 3px);\n background: var(--select-badge-bg, linear-gradient(135deg, var(--select-accent) 0%, var(--select-primary-light) 100%));\n color: var(--select-badge-color, #ffffff);\n border: var(--select-badge-border, none);\n border-radius: var(--select-badge-border-radius, 999px);\n box-shadow: var(--select-badge-shadow, var(--select-shadow-sm), inset 0 1px 0 rgba(255, 255, 255, 0.1));\n box-sizing: border-box;\n font-size: var(--select-badge-font-size, 0.8667em);\n font-weight: var(--select-badge-font-weight, 500);\n line-height: var(--select-badge-line-height, 1.2);\n letter-spacing: var(--select-badge-letter-spacing);\n max-width: var(--select-badge-max-width, 100%);\n overflow: hidden;\n transform: scale(1);\n transition: \n transform var(--select-transition-bounce),\n box-shadow var(--select-transition-fast),\n background var(--select-transition-fast);\n animation: var(--select-badge-animation);\n }\n \n @keyframes badgeEnter {\n 0% {\n opacity: var(--select-badge-enter-from-opacity);\n transform: var(--select-badge-enter-from-transform);\n }\n 100% {\n opacity: var(--select-badge-enter-to-opacity);\n transform: var(--select-badge-enter-to-transform);\n }\n }\n \n .selection-badge:hover {\n background: var(--select-badge-hover-bg, var(--select-badge-bg, linear-gradient(135deg, var(--select-accent) 0%, var(--select-primary-light) 100%)));\n color: var(--select-badge-hover-color, var(--select-badge-color, #ffffff));\n border: var(--select-badge-hover-border, var(--select-badge-border, none));\n box-shadow: var(--select-badge-hover-shadow);\n transform: var(--select-badge-hover-transform);\n }\n\n .selection-badge:active {\n background: var(--select-badge-active-bg, var(--select-badge-hover-bg, var(--select-badge-bg, linear-gradient(135deg, var(--select-accent) 0%, var(--select-primary-light) 100%))));\n color: var(--select-badge-active-color, var(--select-badge-hover-color, var(--select-badge-color, #ffffff)));\n border: var(--select-badge-active-border, var(--select-badge-hover-border, var(--select-badge-border, none)));\n box-shadow: var(--select-badge-active-shadow, var(--select-badge-hover-shadow));\n transform: var(--select-badge-active-transform);\n }\n\n .selection-badge-label {\n display: block;\n min-width: 0;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n color: var(--select-badge-label-color, inherit);\n font-size: var(--select-badge-label-font-size, inherit);\n font-weight: var(--select-badge-label-font-weight, inherit);\n line-height: var(--select-badge-label-line-height, var(--select-badge-line-height, 1.2));\n letter-spacing: var(--select-badge-label-letter-spacing, inherit);\n text-align: var(--select-badge-label-text-align, start);\n }\n\n .badge-remove {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: var(--select-badge-remove-size, 18px);\n height: var(--select-badge-remove-size, 18px);\n min-width: var(--select-badge-remove-min-width, var(--select-badge-remove-size, 18px));\n min-height: var(--select-badge-remove-min-height, var(--select-badge-remove-size, 18px));\n padding: 0;\n margin-left: var(--select-badge-remove-margin-left);\n background: var(--select-badge-remove-bg, rgba(255, 255, 255, 0.2));\n border: var(--select-badge-remove-border, none);\n border-radius: var(--select-badge-remove-radius);\n color: var(--select-badge-remove-color, #ffffff);\n font-size: var(--select-badge-remove-font-size, 0.7333em);\n font-weight: var(--select-badge-remove-font-weight);\n line-height: 1;\n cursor: pointer;\n flex: 0 0 auto;\n transition: \n background var(--select-transition-fast),\n color var(--select-transition-fast),\n border-color var(--select-transition-fast),\n box-shadow var(--select-transition-fast),\n transform var(--select-transition-bounce);\n }\n\n .badge-remove-icon {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: var(--select-badge-remove-icon-size, 10px);\n height: var(--select-badge-remove-icon-size, 10px);\n color: var(--select-badge-remove-icon-color, currentColor);\n font-size: var(--select-badge-remove-icon-font-size, inherit);\n line-height: var(--select-badge-remove-icon-line-height, 1);\n transform: var(--select-badge-remove-icon-transform, none);\n opacity: var(--select-badge-remove-icon-opacity, 1);\n pointer-events: none;\n }\n\n .badge-remove-icon svg {\n width: 100%;\n height: 100%;\n display: block;\n }\n \n .badge-remove:hover {\n background: var(--select-badge-remove-hover-bg, rgba(233, 69, 96, 0.9));\n color: var(--select-badge-remove-hover-color, var(--select-badge-remove-color, #ffffff));\n border: var(--select-badge-remove-hover-border, var(--select-badge-remove-border, none));\n box-shadow: var(--select-badge-remove-hover-shadow, none);\n transform: var(--select-badge-remove-hover-transform);\n }\n\n .badge-remove:focus-visible {\n outline: var(--select-badge-remove-focus-outline);\n outline-offset: var(--select-badge-remove-focus-offset);\n }\n \n .badge-remove:active {\n background: var(--select-badge-remove-active-bg, var(--select-badge-remove-hover-bg, rgba(233, 69, 96, 0.9)));\n color: var(--select-badge-remove-active-color, var(--select-badge-remove-hover-color, var(--select-badge-remove-color, #ffffff)));\n border: var(--select-badge-remove-active-border, var(--select-badge-remove-hover-border, var(--select-badge-remove-border, none)));\n box-shadow: var(--select-badge-remove-active-shadow, var(--select-badge-remove-hover-shadow, none));\n transform: var(--select-badge-remove-active-transform);\n }\n\n :host([dir="rtl"]) .badge-remove {\n margin-left: 0;\n margin-right: var(--select-badge-remove-margin-left);\n }\n \n /* ─────────────────────────────────────────────────────────────────────────\n Input Container — Sophisticated control shell\n ───────────��───────────────────────────────────────────────────────────── */\n \n .select-container {\n position: relative;\n width: 100%;\n }\n \n .input-container {\n position: relative;\n width: 100%;\n display: flex;\n align-items: var(--select-input-align-items, center);\n flex-wrap: nowrap;\n justify-content: var(--select-input-justify-content, flex-start);\n gap: var(--select-input-gap, 6px);\n padding: var(--select-input-padding, 10px 52px 10px 14px);\n height: var(--select-input-height, auto);\n min-height: var(--select-input-min-height, 48px);\n max-height: var(--select-input-max-height, 160px);\n overflow: hidden;\n padding: var(--select-multi-container-padding, 6px);\n align-content: var(--select-input-align-content, center);\n text-align: var(--select-input-text-align, start);\n background: var(--select-input-bg, var(--select-surface));\n font-size: var(--select-input-font-size, inherit);\n font-weight: var(--select-input-font-weight, 400);\n font-weight: var(--select-input-font-weight, 400);\n border: var(--select-input-border, 1.5px solid var(--select-border));\n border-radius: var(--select-input-border-radius, var(--select-radius-md));\n box-shadow: var(--select-shadow-sm);\n box-sizing: border-box;\n transition: \n border-color var(--select-transition-fast),\n box-shadow var(--select-transition-smooth),\n transform var(--select-transition-fast);\n }\n\n .input-content {\n position: relative;\n display: flex;\n flex: 1 1 auto;\n width: 100%;\n min-width: 0;\n min-height: 0;\n align-self: stretch;\n align-items: var(--select-input-align-items, center);\n align-content: var(--select-input-align-content, center);\n justify-content: var(--select-input-justify-content, flex-start);\n flex-wrap: nowrap;\n gap: var(--select-input-gap, 6px);\n overflow-x: var(--select-input-overflow-x, hidden);\n overflow-y: var(--select-input-overflow-y, hidden);\n scrollbar-width: thin;\n box-sizing: border-box;\n }\n \n .input-container:hover {\n border-color: var(--select-input-hover-border);\n box-shadow: var(--select-input-hover-shadow);\n }\n\n .input-container.input-container--single {\n flex-wrap: nowrap;\n align-content: center;\n }\n\n .input-container.input-container--multi {\n max-height: var(--select-multi-input-max-height, var(--select-multi-input-max-height-config, var(--select-input-max-height, 160px)));\n --select-multi-action-area-width: var(--select-arrow-width, 42px);\n }\n\n .input-container.input-container--multi .input-content {\n flex: 1 1 calc(100% - var(--select-multi-action-area-width, var(--select-arrow-width, 42px)));\n width: calc(100% - var(--select-multi-action-area-width, var(--select-arrow-width, 42px)));\n max-width: calc(100% - var(--select-multi-action-area-width, var(--select-arrow-width, 42px)));\n flex-wrap: var(--select-multi-input-flex-wrap, var(--select-multi-input-flex-wrap-config, wrap));\n align-content: var(--select-multi-input-align-content, var(--select-multi-input-align-content-config, flex-start));\n overflow-x: var(--select-multi-input-overflow-x, var(--select-multi-input-overflow-x-config, hidden));\n overflow-y: var(--select-multi-input-overflow-y, var(--select-multi-input-overflow-y-config, auto));\n padding-inline-end: var(--select-multi-input-end-gap, 12px);\n }\n\n .input-container.input-container--multi .input-content .selection-badge {\n flex: 0 0 auto;\n }\n\n .input-container.input-container--multi.has-clear-control .input-content {\n --select-multi-action-area-width: calc(var(--select-arrow-right-with-clear, 34px) + var(--select-arrow-width, 42px));\n }\n\n .input-container.input-container--multi::after {\n top: var(--select-multi-separator-inset-block, var(--select-separator-inset-block, 10px));\n bottom: var(--select-multi-separator-inset-block, var(--select-separator-inset-block, 10px));\n height: var(--select-multi-separator-height, auto);\n }\n\n .input-container.input-container--multi[data-multi-scroll-mode="horizontal"] {\n align-items: stretch;\n height: var(--select-multi-input-horizontal-height, var(--select-input-min-height, 48px));\n min-height: var(--select-multi-input-horizontal-height, var(--select-input-min-height, 48px));\n max-height: var(--select-multi-input-horizontal-height, var(--select-input-min-height, 48px));\n overflow: hidden;\n }\n\n .input-container.input-container--multi[data-multi-scroll-mode="horizontal"] .input-content {\n flex: 1 1 100%;\n width: 100%;\n max-width: 100%;\n min-height: 0;\n height: 100%;\n cursor: var(--select-multi-input-horizontal-cursor, grab);\n align-items: center;\n align-content: center;\n flex-wrap: nowrap;\n overflow-y: hidden;\n overscroll-behavior-x: contain;\n overscroll-behavior-y: none;\n padding-inline-end: 0;\n scroll-padding-inline-end: var(--select-multi-action-area-width, var(--select-arrow-width, 42px));\n }\n\n .input-container.input-container--multi[data-multi-scroll-mode="horizontal"].has-clear-control .input-content {\n --select-multi-action-area-width: calc(var(--select-arrow-right-with-clear, 34px) + var(--select-arrow-width, 42px));\n }\n\n .input-container.input-container--multi[data-multi-scroll-mode="horizontal"]::after {\n display: none;\n }\n\n .input-container.input-container--multi[data-multi-scroll-mode="horizontal"].is-dragging-scroll .input-content {\n cursor: var(--select-multi-input-horizontal-active-cursor, grabbing);\n user-select: none;\n }\n\n .input-container.input-container--multi[data-multi-scroll-mode="horizontal"] .selection-badge {\n flex: 0 0 auto;\n margin-top: 0;\n margin-bottom: 0;\n }\n\n .input-container.input-container--multi[data-multi-scroll-mode="horizontal"] .input-content > .select-input,\n .input-container.input-container--multi[data-multi-scroll-mode="horizontal"] .input-content > input.select-input,\n .input-container.input-container--multi[data-multi-scroll-mode="horizontal"] .input-content > .select-input[type="text"] {\n flex: var(--select-multi-input-horizontal-input-flex, 0 0 var(--select-multi-input-min-width, 96px));\n }\n\n .input-container.input-container--multi[data-multi-scroll-mode="horizontal"] .dropdown-arrow-container {\n background: var(--select-multi-action-surface-bg, var(--select-input-bg, var(--select-surface)));\n border-left: var(--select-multi-action-divider, 1px solid var(--select-border));\n z-index: 4;\n }\n\n .input-container.input-container--multi[data-multi-scroll-mode="horizontal"] .dropdown-arrow-container.with-clear-control {\n right: var(--select-arrow-right-with-clear, 34px);\n }\n\n :host([dir="rtl"]) .input-container.input-container--multi[data-multi-scroll-mode="horizontal"] .dropdown-arrow-container {\n border-left: none;\n border-right: var(--select-multi-action-divider, 1px solid var(--select-border));\n }\n\n :host([dir="rtl"]) .input-container.input-container--multi[data-multi-scroll-mode="horizontal"] .dropdown-arrow-container.with-clear-control {\n right: auto;\n left: var(--select-arrow-right-with-clear, 34px);\n }\n\n .input-container.input-container--multi[data-multi-scroll-mode="horizontal"] .clear-control-button {\n background: var(--select-multi-action-surface-bg, var(--select-input-bg, var(--select-surface)));\n z-index: 4;\n }\n \n .input-container:focus-within {\n border-color: var(--select-input-focus-border, var(--select-border-focus));\n box-shadow: var(--select-shadow-focus), var(--select-shadow-sm);\n }\n \n /* Elegant separator line before arrow */\n .input-container::after {\n content: \'\';\n display: var(--select-separator-display, block);\n position: absolute;\n top: var(--select-separator-inset-block, 10px);\n bottom: var(--select-separator-inset-block, 10px);\n right: var(--select-separator-position, var(--select-arrow-width, 42px));\n width: var(--select-separator-width, 1px);\n height: var(--select-separator-height, auto);\n background: var(--select-separator-bg, linear-gradient(\n to bottom,\n transparent 0%,\n var(--select-border) 20%,\n var(--select-border) 80%,\n transparent 100%\n ));\n pointer-events: none;\n z-index: 1;\n opacity: var(--select-separator-opacity);\n transition: opacity var(--select-transition-fast);\n }\n \n .input-container:hover::after,\n .input-container:focus-within::after {\n opacity: var(--select-separator-active-opacity);\n }\n\n :host([dir="rtl"]) .input-container::after {\n right: auto;\n left: var(--select-separator-position, var(--select-arrow-width, 42px));\n }\n \n /* ─────────────────────────────────────────────────────────────────────────\n Dropdown Arrow — Smooth rotation with refined styling\n ───────────────────────────────────────────────────────────────────────── */\n \n .dropdown-arrow-container {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n width: var(--select-arrow-width, var(--select-arrow-size, 42px));\n height: var(--select-arrow-height, var(--select-arrow-size, auto));\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n border-radius: var(--select-arrow-border-radius, 0 var(--select-radius-md) var(--select-radius-md) 0);\n z-index: 2;\n transition: background-color var(--select-transition-fast);\n }\n\n .input-container.has-clear-control {\n padding: var(--select-input-padding-with-clear, 10px 84px 10px 14px);\n }\n\n .input-container.has-clear-control::after {\n right: var(--select-separator-position-with-clear, calc(var(--select-arrow-right-with-clear, 34px) + var(--select-arrow-width, 42px)));\n }\n\n .dropdown-arrow-container.with-clear-control {\n right: var(--select-arrow-right-with-clear, 34px);\n }\n\n :host([dir="rtl"]) .dropdown-arrow-container {\n right: auto;\n left: 0;\n border-radius: var(--select-arrow-border-radius-rtl, var(--select-radius-md) 0 0 var(--select-radius-md));\n }\n\n :host([dir="rtl"]) .input-container.has-clear-control::after {\n right: auto;\n left: var(--select-separator-position-with-clear, calc(var(--select-arrow-right-with-clear, 34px) + var(--select-arrow-width, 42px)));\n }\n\n :host([dir="rtl"]) .dropdown-arrow-container.with-clear-control {\n right: auto;\n left: var(--select-arrow-right-with-clear, 34px);\n }\n\n /* ─────────────────────────────────────────────────────────────────────────\n Clear Control — Minimal and elegant dismiss button\n ───────────────────────────────────────────────────────────────────────── */\n\n .clear-control-button {\n position: absolute;\n top: 50%;\n right: var(--select-clear-button-right, 8px);\n transform: translateY(-50%);\n width: var(--select-clear-button-size, 26px);\n height: var(--select-clear-button-size, 26px);\n border: var(--select-clear-button-border, none);\n border-radius: var(--select-clear-button-radius, 50%);\n background: var(--select-clear-button-bg, transparent);\n color: var(--select-clear-button-color, var(--select-text-muted));\n display: inline-flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n z-index: 3;\n transition: \n background var(--select-transition-fast),\n color var(--select-transition-fast),\n transform var(--select-transition-bounce);\n }\n\n .clear-control-button:hover {\n background: var(--select-clear-button-hover-bg, rgba(233, 69, 96, 0.1));\n color: var(--select-clear-button-hover-color, var(--select-accent-hover));\n transform: var(--select-clear-button-hover-transform);\n }\n \n .clear-control-button:active {\n transform: var(--select-clear-button-active-transform);\n }\n\n .clear-control-button:focus-visible {\n outline: var(--select-clear-button-focus-outline, 2px solid var(--select-border-focus));\n outline-offset: var(--select-clear-button-focus-offset);\n }\n\n .clear-control-button[hidden] {\n display: none;\n }\n\n :host([dir="rtl"]) .clear-control-button {\n right: auto;\n left: var(--select-clear-button-right, 8px);\n }\n\n .clear-control-icon {\n width: var(--select-clear-icon-size);\n height: var(--select-clear-icon-size);\n pointer-events: none;\n }\n \n .clear-control-icon svg {\n width: 100%;\n height: 100%;\n }\n \n .dropdown-arrow-container:hover {\n background-color: var(--select-arrow-hover-bg, rgba(15, 52, 96, 0.05));\n }\n\n :host([data-custom-arrow="true"]) .dropdown-arrow-container:hover {\n background-color: transparent;\n }\n \n .dropdown-arrow {\n width: var(--select-arrow-width, var(--select-arrow-size, 16px));\n height: var(--select-arrow-height, var(--select-arrow-size, 16px));\n color: var(--select-arrow-color, var(--select-text-muted));\n transition: \n transform var(--select-transition-smooth),\n color var(--select-transition-fast);\n transform-origin: center;\n }\n \n .dropdown-arrow path {\n stroke-width: var(--select-arrow-stroke-width, 1.5);\n }\n \n .dropdown-arrow-container:hover .dropdown-arrow {\n color: var(--select-arrow-hover, var(--select-arrow-hover-color, #667eea));\n }\n \n .dropdown-arrow.open {\n transform: var(--select-arrow-open-transform);\n }\n \n /* ─────────────────────────────────────────────────────────────────────────\n Input Field — Clean text entry\n ───────────────────────────────────────────────────────────────────────── */\n \n .input-container > .select-input,\n input.select-input,\n .select-input[type="text"] {\n display: block;\n flex: 1 1 auto;\n width: var(--select-input-width, 100%);\n max-width: 100%;\n min-width: var(--select-input-min-width, 0);\n min-inline-size: 0;\n min-height: 0;\n padding: var(--select-input-field-padding, 0) !important;\n margin: 0 !important;\n border: 0 !important;\n font-size: var(--select-input-font-size, inherit);\n line-height: var(--select-input-line-height, 1.5);\n color: var(--select-input-color, var(--select-text));\n background: transparent !important;\n box-sizing: border-box;\n outline: none !important;\n font-weight: var(--select-input-font-weight);\n letter-spacing: var(--select-input-letter-spacing);\n font-family: var(--select-input-font-family, inherit);\n font-style: var(--select-input-font-style, normal);\n align-self: var(--select-input-align-self, center);\n appearance: none !important;\n -webkit-appearance: none !important;\n box-shadow: none !important;\n border-radius: 0 !important;\n overflow: hidden;\n text-overflow: ellipsis;\n text-align: var(--select-input-text-align, inherit);\n white-space: nowrap;\n }\n \n .select-input::placeholder {\n color: var(--select-input-placeholder-color, var(--select-text-placeholder));\n font-weight: 400;\n }\n\n :host([dir="rtl"]) .input-container {\n padding: var(--select-input-padding-rtl, 10px 14px 10px 52px);\n }\n\n :host([dir="rtl"]) .input-container.has-clear-control {\n padding: var(--select-input-padding-with-clear-rtl, 10px 14px 10px 84px);\n }\n\n .input-container.input-container--multi > .select-input,\n .input-container.input-container--multi > input.select-input,\n .input-container.input-container--multi > .select-input[type="text"] {\n width: auto;\n min-width: var(--select-multi-input-min-width, 96px);\n flex: 1 0 var(--select-multi-input-min-width, 96px);\n }\n\n .input-container.input-container--single > .select-input,\n .input-container.input-container--single > input.select-input,\n .input-container.input-container--single > .select-input[type="text"] {\n width: var(--select-input-width, 100%);\n min-width: 0;\n flex: 1 1 auto;\n }\n \n .select-input:disabled {\n background-color: var(--select-disabled-bg, #f5f5f5);\n cursor: not-allowed;\n opacity: var(--select-input-disabled-opacity);\n }\n \n /* ─────────────────────────────────────────────────────────────────────────\n Dropdown Panel — Elegant floating container\n ───────────────────────────────────────────────────────────────────────── */\n \n .select-dropdown {\n position: absolute;\n scroll-behavior: var(--select-dropdown-scroll-behavior);\n top: var(--select-dropdown-top);\n bottom: auto;\n left: 0;\n right: 0;\n max-height: var(--select-dropdown-max-height, 320px);\n overflow: hidden;\n box-sizing: border-box;\n background: var(--select-dropdown-bg, var(--select-surface));\n border: 1px solid var(--select-dropdown-border, var(--select-border));\n border-radius: var(--select-dropdown-border-radius, var(--select-radius-lg));\n box-shadow: var(--select-dropdown-shadow, var(--select-shadow-lg));\n z-index: var(--select-dropdown-z-index, 1000);\n transform-origin: var(--select-dropdown-transform-origin);\n animation: var(--select-dropdown-animation);\n }\n\n .select-dropdown[data-placement="top"] {\n top: auto;\n bottom: var(--select-dropdown-bottom, calc(100% + 6px));\n transform-origin: var(--select-dropdown-top-transform-origin, bottom center);\n }\n\n .select-dropdown[data-placement="top"] {\n --select-dropdown-enter-from-transform: var(--select-dropdown-top-enter-from-transform, translateY(8px) scale(0.98));\n --select-dropdown-exit-to-transform: var(--select-dropdown-top-exit-to-transform, translateY(8px) scale(0.98));\n }\n\n /* A closed popup stays visually mounted for exit, but cannot be interacted with. */\n .select-dropdown[data-motion="closing"] {\n animation: var(--select-dropdown-exit-animation);\n pointer-events: none;\n }\n\n @keyframes dropdownExit {\n from {\n opacity: var(--select-dropdown-exit-from-opacity);\n transform: var(--select-dropdown-exit-from-transform);\n }\n to {\n opacity: var(--select-dropdown-exit-to-opacity);\n transform: var(--select-dropdown-exit-to-transform);\n }\n }\n\n @keyframes dropdownEnter {\n 0% {\n opacity: var(--select-dropdown-enter-from-opacity);\n transform: var(--select-dropdown-enter-from-transform);\n }\n 100% {\n opacity: var(--select-dropdown-enter-to-opacity);\n transform: var(--select-dropdown-enter-to-transform);\n }\n }\n \n .options-container {\n position: relative;\n max-height: var(--select-options-max-height, 320px);\n overflow: auto;\n box-sizing: border-box;\n padding: var(--select-options-padding, var(--select-dropdown-padding, 6px));\n background: var(--select-options-bg, var(--select-dropdown-bg, var(--select-surface)));\n \n /* Custom scrollbar styling */\n scrollbar-width: thin;\n scrollbar-color: var(--select-border) transparent;\n }\n \n .options-container::-webkit-scrollbar {\n width: var(--select-scrollbar-width);\n }\n \n .options-container::-webkit-scrollbar-track {\n background: transparent;\n }\n \n .options-container::-webkit-scrollbar-thumb {\n background: var(--select-border);\n border-radius: var(--select-scrollbar-thumb-radius);\n }\n \n .options-container::-webkit-scrollbar-thumb:hover {\n background: var(--select-text-muted);\n }\n\n /* ─────────────────────────────────────────────────────────────────────────\n Group Headers — Refined section dividers\n ───────────────────────────────────────────────────────────────────────── */\n\n .group-header {\n padding: var(--select-group-header-padding, 10px 12px 8px 12px);\n margin: var(--select-group-header-margin, 0 calc(var(--select-options-padding, 6px) * -1));\n font-weight: var(--select-group-header-weight, 600);\n color: var(--select-group-header-color, var(--select-text-muted));\n background: var(--select-group-header-bg, #f3f4f6);\n text-align: var(--select-group-header-text-align, left);\n font-size: var(--select-group-header-font-size, 0.7333em);\n text-transform: var(--select-group-header-text-transform, uppercase);\n letter-spacing: var(--select-group-header-letter-spacing, 0.08em);\n position: sticky;\n top: calc(var(--select-options-padding, 6px) * -1);\n left: 0;\n right: 0;\n z-index: 100;\n border: var(--select-group-header-border, none);\n border-bottom: var(--select-group-header-border-bottom, 1px solid rgba(0, 0, 0, 0.08));\n border-radius: var(--select-group-header-border-radius, 0);\n box-shadow: var(--select-group-header-shadow, 0 1px 2px rgba(0, 0, 0, 0.04));\n /* Force solid background to prevent option bleed-through */\n isolation: isolate;\n }\n \n .group-header:not(:first-child) {\n margin-top: calc(\n var(--select-group-header-separator-margin-top, 0px) +\n var(--select-group-header-separator-padding-top, 0px)\n );\n border-top: var(--select-group-header-separator-border-top);\n }\n\n /* ─────────────────────────────────────────────────────────────────────────\n Options — Elegant hover and selection states\n ───────────────────────────────────────────────────────────────────────── */\n\n .option {\n position: relative;\n padding: var(--select-option-padding, 10px 14px);\n cursor: pointer;\n color: var(--select-option-color, var(--select-text));\n background: var(--select-option-bg, transparent);\n border: var(--select-option-border, none);\n box-sizing: border-box;\n text-align: var(--select-option-text-align, start);\n transition: var(--select-option-transition, \n background var(--select-transition-fast),\n color var(--select-transition-fast),\n outline-color var(--select-transition-fast),\n box-shadow var(--select-transition-fast)\n );\n user-select: none;\n font-size: var(--select-option-font-size, inherit);\n font-weight: var(--select-option-font-weight);\n line-height: var(--select-option-line-height, 1.5);\n border-radius: var(--select-option-border-radius, var(--select-radius-sm));\n margin: var(--select-option-margin);\n }\n\n .option:hover:not(.disabled):not(.smilodon-option--disabled),\n .option.smilodon-option--disabled-hoverable:hover {\n background: var(--select-option-hover-bg, var(--select-surface-elevated));\n /* Hover decoration must not resize or translate the pointer hit target. */\n outline: var(--select-option-hover-border, none);\n outline-offset: -1px;\n color: var(--select-option-hover-color, var(--select-text));\n }\n\n .option.selected {\n background: var(--select-option-selected-bg, linear-gradient(135deg, rgba(15, 52, 96, 0.08) 0%, rgba(15, 52, 96, 0.04) 100%));\n border: var(--select-option-selected-border, var(--select-option-border, none));\n color: var(--select-option-selected-color, var(--select-accent));\n font-weight: var(--select-option-selected-weight, 550);\n }\n \n .option.selected::before {\n content: var(--select-option-selected-indicator-content, \'\');\n display: var(--select-option-selected-indicator-display, block);\n position: absolute;\n left: var(--select-option-selected-indicator-left);\n top: var(--select-option-selected-indicator-top);\n transform: var(--select-option-selected-indicator-transform);\n width: var(--select-option-selected-indicator-width);\n height: var(--select-option-selected-indicator-height);\n background: var(--select-option-selected-indicator-bg);\n border-radius: var(--select-option-selected-indicator-radius);\n animation: var(--select-option-selected-indicator-animation);\n }\n\n :host([dir="rtl"]) .option.selected::before {\n left: auto;\n right: var(--select-option-selected-indicator-right, var(--select-option-selected-indicator-left));\n border-radius: var(--select-option-selected-indicator-radius-rtl, 2px 0 0 2px);\n }\n \n @keyframes selectedIndicator {\n 0% {\n height: var(--select-option-selected-indicator-from-height);\n opacity: var(--select-option-selected-indicator-from-opacity);\n }\n 100% {\n height: var(--select-option-selected-indicator-to-height);\n opacity: var(--select-option-selected-indicator-to-opacity);\n }\n }\n\n .option.selected:hover {\n background: var(--select-option-selected-hover-bg, var(--select-option-selected-bg, linear-gradient(135deg, rgba(15, 52, 96, 0.12) 0%, rgba(15, 52, 96, 0.06) 100%)));\n outline: var(--select-option-selected-hover-border, var(--select-option-hover-border, none));\n outline-offset: -1px;\n color: var(--select-option-selected-hover-color, var(--select-option-selected-color, var(--select-accent)));\n }\n\n .option.active:not(.selected):not(.disabled):not(.smilodon-option--disabled),\n .option.active.smilodon-option--disabled-focusable:not(.selected) {\n background: var(--select-option-active-bg, var(--select-surface-elevated));\n color: var(--select-option-active-color, var(--select-option-hover-color, var(--select-option-color, var(--select-text))));\n border: var(--select-option-active-border, var(--select-option-hover-border, var(--select-option-border, none)));\n outline: var(--select-option-active-outline, none);\n outline-offset: var(--select-option-active-outline-offset);\n box-shadow: var(--select-option-active-shadow, none);\n transform: var(--select-option-active-transform, none);\n }\n\n .option.selected.active:not(.disabled):not(.smilodon-option--disabled),\n .option.selected.active.smilodon-option--disabled-focusable {\n background: var(--select-option-selected-active-bg, var(--select-option-selected-hover-bg, var(--select-option-selected-bg, linear-gradient(135deg, rgba(15, 52, 96, 0.12) 0%, rgba(15, 52, 96, 0.06) 100%))));\n color: var(--select-option-selected-active-color, var(--select-option-selected-hover-color, var(--select-option-selected-color, var(--select-accent))));\n border: var(--select-option-selected-active-border, var(--select-option-selected-hover-border, var(--select-option-selected-border, var(--select-option-border, none))));\n outline: var(--select-option-selected-active-outline, var(--select-option-active-outline, none));\n outline-offset: var(--select-option-selected-active-outline-offset);\n box-shadow: var(--select-option-selected-active-shadow, var(--select-option-active-shadow, none));\n transform: var(--select-option-selected-active-transform, var(--select-option-active-transform, none));\n }\n\n .option.disabled,\n .option.smilodon-option--disabled {\n background: var(--select-option-disabled-bg, var(--select-option-bg, transparent));\n color: var(--select-option-disabled-color, var(--select-text-muted));\n border: var(--select-option-disabled-border, var(--select-option-border, none));\n opacity: var(--select-option-disabled-opacity, 0.5);\n cursor: var(--select-option-disabled-cursor, not-allowed);\n pointer-events: var(--select-option-disabled-pointer-events, none);\n }\n\n .option.smilodon-option--disabled-interactive {\n pointer-events: auto;\n }\n\n .option:active:not(.selected):not(.disabled):not(.smilodon-option--disabled),\n .option.smilodon-option--disabled-selectable:active:not(.selected) {\n background: var(--select-option-pressed-bg, rgba(15, 52, 96, 0.08));\n transform: var(--select-option-pressed-transform);\n }\n\n .option.selected:active:not(.disabled):not(.smilodon-option--disabled),\n .option.selected.smilodon-option--disabled-selectable:active {\n transform: var(--select-option-selected-pressed-transform);\n }\n \n /* ─────────────────────────────────────────────────────────────────────────\n Load More & Busy States — Refined feedback indicators\n ───────────────────────────────────────────────────────────────────────── */\n \n .load-more-container {\n padding: var(--select-load-more-padding, 12px);\n text-align: center;\n }\n \n .load-more-button {\n padding: var(--select-button-padding, 10px 20px);\n border: var(--select-button-border, 1.5px solid var(--select-border));\n background: var(--select-button-bg, transparent);\n color: var(--select-button-color, var(--select-accent));\n border-radius: var(--select-button-border-radius, var(--select-radius-md));\n cursor: pointer;\n font-size: var(--select-button-font-size, 0.8667em);\n font-weight: var(--select-button-font-weight);\n letter-spacing: var(--select-button-letter-spacing);\n transition: \n background var(--select-transition-fast),\n border-color var(--select-transition-fast),\n color var(--select-transition-fast),\n transform var(--select-transition-bounce);\n }\n \n .load-more-button:hover {\n background: var(--select-button-hover-bg, var(--select-accent));\n border-color: var(--select-accent);\n color: var(--select-button-hover-color, white);\n transform: var(--select-button-hover-transform);\n }\n \n .load-more-button:active {\n transform: var(--select-button-active-transform);\n }\n \n .load-more-button:disabled {\n opacity: var(--select-button-disabled-opacity, 0.5);\n cursor: not-allowed;\n transform: none;\n }\n \n .busy-bucket {\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: var(--select-busy-gap, 8px);\n padding: var(--select-busy-padding, 20px);\n text-align: center;\n color: var(--select-busy-color, var(--select-text-muted));\n background: var(--select-busy-bg, transparent);\n font-size: var(--select-busy-font-size, 0.8667em);\n }\n\n .busy-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n }\n\n .busy-icon[hidden] {\n display: none;\n }\n\n .busy-message {\n text-align: center;\n }\n\n .busy-content[hidden] {\n display: none;\n }\n\n .busy-bucket--replace .busy-icon,\n .busy-bucket--replace .busy-message {\n display: none;\n }\n \n .spinner {\n display: inline-block;\n width: var(--select-spinner-size, 22px);\n height: var(--select-spinner-size, 22px);\n border: var(--select-spinner-border, 2px solid var(--select-border));\n border-top-color: var(--select-spinner-active-color, var(--select-accent));\n border-radius: 50%;\n animation: var(--select-spinner-animation);\n }\n \n @keyframes spin {\n to { transform: rotate(360deg); }\n }\n \n .empty-state {\n padding: var(--select-empty-padding, 32px 24px);\n text-align: center;\n color: var(--select-empty-color, var(--select-text-muted));\n font-size: var(--select-empty-font-size, 0.9333em);\n background: var(--select-empty-bg, transparent);\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: var(--select-empty-gap);\n }\n \n .searching-state {\n padding: var(--select-searching-padding, 32px 24px);\n text-align: center;\n color: var(--select-searching-color, var(--select-accent));\n font-size: var(--select-searching-font-size, 0.9333em);\n background: var(--select-searching-bg, transparent);\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: var(--select-searching-gap);\n }\n \n .searching-state::before {\n content: \'\';\n width: var(--select-searching-spinner-size);\n height: var(--select-searching-spinner-size);\n border: var(--select-searching-spinner-border);\n border-top-color: var(--select-searching-spinner-active-color);\n border-radius: 50%;\n animation: var(--select-searching-spinner-animation);\n }\n \n /* ─────────────────────────────────────────────────────────────────────────\n Error States — Clear visual feedback\n ───────────────────────────────────────────────────────────────────────── */\n \n .select-input[aria-invalid="true"] {\n border-color: var(--select-error-border, #e94560);\n }\n \n .select-input[aria-invalid="true"]:focus {\n border-color: var(--select-error-border, #e94560);\n box-shadow: 0 0 0 3px var(--select-error-shadow, rgba(233, 69, 96, 0.15));\n }\n \n /* ──────────────────────────────────────────────────��──────────────────────\n Accessibility — Reduced motion & High contrast\n ───────────────────────────────────────────────────────────────────────── */\n \n @media (prefers-reduced-motion: reduce) {\n *,\n *::before,\n *::after {\n animation-duration: var(--select-reduced-motion-duration) !important;\n animation-iteration-count: var(--select-reduced-motion-iteration-count) !important;\n transition-duration: var(--select-reduced-motion-duration) !important;\n }\n \n .dropdown-arrow.open {\n transform: var(--select-arrow-open-transform);\n }\n }\n \n @media (prefers-contrast: high) {\n .select-input:focus {\n outline-width: var(--select-high-contrast-focus-outline-width);\n outline-color: var(--select-high-contrast-focus-outline-color);\n }\n \n .input-container {\n border-width: var(--select-high-contrast-border-width);\n }\n \n .option.selected::before {\n width: var(--select-high-contrast-indicator-width);\n }\n }\n \n /* Touch targets (WCAG 2.5.5) */\n .load-more-button,\n select-option {\n min-height: var(--select-touch-target-min-height);\n }\n \n /* ─────────────────────────────────────────────────────────────────────────\n Dark Mode — Elegant dark theme\n ───────────────────────────────────────────────────────────────────────── */\n \n :host(.dark-mode),\n :host([dark-mode]),\n :host([darkmode]),\n :host([data-theme="dark"]),\n :host([theme="dark"]),\n :host-context(.dark-mode),\n :host-context(.dark),\n :host-context([dark-mode]),\n :host-context([darkmode]),\n :host-context([data-theme="dark"]),\n :host-context([theme="dark"]) {\n --select-primary: #e5e5e5;\n --select-primary-light: #2a2a3e;\n --select-accent: #6366f1;\n --select-accent-hover: #f43f5e;\n --select-surface: var(--select-dark-bg, #1a1a2e);\n --select-surface-elevated: #252540;\n --select-border: var(--select-dark-border, #3f3f5a);\n --select-border-focus: #6366f1;\n --select-text: var(--select-dark-text, #f5f5f5);\n --select-text-muted: #9ca3af;\n --select-text-placeholder: #6b7280;\n --select-shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.2);\n --select-shadow-md: 0 4px 12px rgba(0, 0, 0, 0.3);\n --select-shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.4);\n --select-shadow-focus: 0 0 0 3px rgba(99, 102, 241, 0.25);\n\n --select-dropdown-bg: var(--select-dark-dropdown-bg, var(--select-surface));\n \n --select-arrow-color: var(--select-dark-arrow-color, #9ca3af);\n --select-arrow-hover-color: var(--select-dark-arrow-hover-color, #f5f5f5);\n --select-arrow-bg: var(--select-dark-arrow-bg, transparent);\n --select-arrow-hover-bg: var(--select-dark-arrow-hover-bg, rgba(156, 163, 175, 0.15));\n \n --select-separator-bg: var(--select-dark-separator-bg, var(--select-separator-dark-bg));\n --select-separator-width: var(--select-dark-separator-width, 1px);\n \n --select-badge-bg: var(--select-dark-badge-bg, rgba(99, 102, 241, 0.2));\n --select-badge-color: var(--select-dark-badge-color, #e0e7ff);\n --select-badge-border: var(--select-dark-badge-border, var(--select-badge-border, none));\n --select-badge-hover-border: var(--select-dark-badge-hover-border, var(--select-badge-hover-border, var(--select-badge-border, none)));\n --select-badge-active-border: var(--select-dark-badge-active-border, var(--select-badge-active-border, var(--select-badge-hover-border, var(--select-badge-border, none))));\n \n --select-group-header-bg: var(--select-group-header-dark-bg, #1a1a2e);\n --select-group-header-color: var(--select-group-header-dark-color, #9ca3af);\n \n --select-empty-color: var(--select-dark-empty-color, #9ca3af);\n \n --select-option-bg: var(--select-dark-option-bg, transparent);\n --select-option-color: var(--select-dark-option-color, var(--select-text));\n --select-option-border: var(--select-dark-option-border, none);\n --select-option-hover-bg: var(--select-dark-option-hover-bg, var(--select-surface-elevated));\n --select-option-hover-color: var(--select-dark-option-hover-color, var(--select-text));\n --select-option-hover-border: var(--select-dark-option-hover-border, var(--select-option-border, none));\n --select-option-selected-bg: var(--select-dark-option-selected-bg, linear-gradient(135deg, rgba(99, 102, 241, 0.15) 0%, rgba(99, 102, 241, 0.08) 100%));\n --select-option-selected-color: var(--select-dark-option-selected-color, #a5b4fc);\n --select-option-selected-border: var(--select-dark-option-selected-border, var(--select-option-border, none));\n --select-option-selected-hover-bg: var(--select-dark-option-selected-hover-bg, var(--select-option-selected-bg));\n --select-option-selected-hover-color: var(--select-dark-option-selected-hover-color, var(--select-option-selected-color));\n --select-option-selected-hover-border: var(--select-dark-option-selected-hover-border, var(--select-option-selected-border, var(--select-option-hover-border, var(--select-option-border, none))));\n }\n\n :host(.dark-mode) .input-container,\n :host([dark-mode]) .input-container,\n :host([darkmode]) .input-container,\n :host([data-theme="dark"]) .input-container,\n :host([theme="dark"]) .input-container,\n :host-context(.dark-mode) .input-container,\n :host-context(.dark) .input-container,\n :host-context([dark-mode]) .input-container,\n :host-context([darkmode]) .input-container,\n :host-context([data-theme="dark"]) .input-container,\n :host-context([theme="dark"]) .input-container {\n background: var(--select-surface);\n border-color: var(--select-border);\n }\n\n :host(.dark-mode) .input-container:hover,\n :host([dark-mode]) .input-container:hover,\n :host([darkmode]) .input-container:hover,\n :host([data-theme="dark"]) .input-container:hover,\n :host([theme="dark"]) .input-container:hover,\n :host-context(.dark-mode) .input-container:hover,\n :host-context(.dark) .input-container:hover,\n :host-context([dark-mode]) .input-container:hover,\n :host-context([darkmode]) .input-container:hover,\n :host-context([data-theme="dark"]) .input-container:hover,\n :host-context([theme="dark"]) .input-container:hover {\n border-color: var(--select-dark-input-hover-border, var(--select-input-hover-border, var(--select-dark-border-focus, var(--select-border-focus, #6366f1))));\n box-shadow: var(--select-dark-input-hover-shadow, var(--select-input-hover-shadow, var(--select-shadow-sm), 0 0 0 1px rgba(99, 102, 241, 0.12)));\n }\n\n :host(.dark-mode) .input-container:focus-within,\n :host([dark-mode]) .input-container:focus-within,\n :host([darkmode]) .input-container:focus-within,\n :host([data-theme="dark"]) .input-container:focus-within,\n :host([theme="dark"]) .input-container:focus-within,\n :host-context(.dark-mode) .input-container:focus-within,\n :host-context(.dark) .input-container:focus-within,\n :host-context([dark-mode]) .input-container:focus-within,\n :host-context([darkmode]) .input-container:focus-within,\n :host-context([data-theme="dark"]) .input-container:focus-within,\n :host-context([theme="dark"]) .input-container:focus-within {\n border-color: var(--select-dark-border-focus, var(--select-border-focus, #6366f1));\n box-shadow: var(--select-dark-shadow-focus, var(--select-shadow-focus, 0 0 0 3px rgba(99, 102, 241, 0.25))), var(--select-shadow-sm);\n }\n\n :host(.dark-mode) .input-container::after,\n :host([dark-mode]) .input-container::after,\n :host([darkmode]) .input-container::after,\n :host([data-theme="dark"]) .input-container::after,\n :host([theme="dark"]) .input-container::after,\n :host-context(.dark-mode) .input-container::after,\n :host-context(.dark) .input-container::after,\n :host-context([dark-mode]) .input-container::after,\n :host-context([darkmode]) .input-container::after,\n :host-context([data-theme="dark"]) .input-container::after,\n :host-context([theme="dark"]) .input-container::after {\n background: var(--select-separator-dark-bg);\n }\n\n :host(.dark-mode) .select-dropdown,\n :host([dark-mode]) .select-dropdown,\n :host([darkmode]) .select-dropdown,\n :host([data-theme="dark"]) .select-dropdown,\n :host([theme="dark"]) .select-dropdown,\n :host-context(.dark-mode) .select-dropdown,\n :host-context(.dark) .select-dropdown,\n :host-context([dark-mode]) .select-dropdown,\n :host-context([darkmode]) .select-dropdown,\n :host-context([data-theme="dark"]) .select-dropdown,\n :host-context([theme="dark"]) .select-dropdown {\n background: var(--select-dropdown-bg, var(--select-surface));\n border-color: var(--select-border);\n }\n\n :host(.dark-mode) .options-container,\n :host([dark-mode]) .options-container,\n :host([darkmode]) .options-container,\n :host([data-theme="dark"]) .options-container,\n :host([theme="dark"]) .options-container,\n :host-context(.dark-mode) .options-container,\n :host-context(.dark) .options-container,\n :host-context([dark-mode]) .options-container,\n :host-context([darkmode]) .options-container,\n :host-context([data-theme="dark"]) .options-container,\n :host-context([theme="dark"]) .options-container {\n background: var(--select-dropdown-bg, var(--select-surface));\n scrollbar-color: var(--select-border) transparent;\n }\n\n :host(.dark-mode) .selection-badge,\n :host([dark-mode]) .selection-badge,\n :host([darkmode]) .selection-badge,\n :host([data-theme="dark"]) .selection-badge,\n :host([theme="dark"]) .selection-badge,\n :host-context(.dark-mode) .selection-badge,\n :host-context(.dark) .selection-badge,\n :host-context([dark-mode]) .selection-badge,\n :host-context([darkmode]) .selection-badge,\n :host-context([data-theme="dark"]) .selection-badge,\n :host-context([theme="dark"]) .selection-badge {\n background: var(--select-dark-badge-bg, var(--select-badge-bg, var(--select-badge-dark-bg)));\n color: var(--select-dark-badge-color, var(--select-badge-color, #e0e7ff));\n }\n\n :host(.dark-mode) .group-header:not(:first-child),\n :host([dark-mode]) .group-header:not(:first-child),\n :host([darkmode]) .group-header:not(:first-child),\n :host([data-theme="dark"]) .group-header:not(:first-child),\n :host([theme="dark"]) .group-header:not(:first-child),\n :host-context(.dark-mode) .group-header:not(:first-child),\n :host-context(.dark) .group-header:not(:first-child),\n :host-context([dark-mode]) .group-header:not(:first-child),\n :host-context([darkmode]) .group-header:not(:first-child),\n :host-context([data-theme="dark"]) .group-header:not(:first-child),\n :host-context([theme="dark"]) .group-header:not(:first-child) {\n border-top-color: var(--select-border);\n }\n\n :host(.dark-mode) .group-header,\n :host([dark-mode]) .group-header,\n :host([darkmode]) .group-header,\n :host([data-theme="dark"]) .group-header,\n :host([theme="dark"]) .group-header,\n :host-context(.dark-mode) .group-header,\n :host-context(.dark) .group-header,\n :host-context([dark-mode]) .group-header,\n :host-context([darkmode]) .group-header,\n :host-context([data-theme="dark"]) .group-header,\n :host-context([theme="dark"]) .group-header {\n color: var(--select-dark-group-header-color, var(--select-group-header-color, inherit));\n background: var(--select-dark-group-header-bg, var(--select-group-header-bg, #1a1a2e));\n border-bottom: var(--select-group-header-border-bottom, 1px solid rgba(255, 255, 255, 0.08));\n box-shadow: var(--select-group-header-shadow, 0 1px 2px rgba(0, 0, 0, 0.3));\n }\n\n :host(.dark-mode) .group-header,\n :host([dark-mode]) .group-header,\n :host([darkmode]) .group-header,\n :host([data-theme="dark"]) .group-header,\n :host([theme="dark"]) .group-header {\n color: var(--select-dark-group-header-color, var(--select-group-header-dark-color, #9ca3af));\n background: var(--select-dark-group-header-bg, var(--select-group-header-dark-bg, #1a1a2e));\n border-bottom: var(--select-group-header-border-bottom, 1px solid rgba(255, 255, 255, 0.08));\n box-shadow: var(--select-group-header-shadow, 0 1px 2px rgba(0, 0, 0, 0.3));\n }\n\n :host(.dark-mode) .group-header:not(:first-child),\n :host([dark-mode]) .group-header:not(:first-child),\n :host([darkmode]) .group-header:not(:first-child),\n :host([data-theme="dark"]) .group-header:not(:first-child),\n :host([theme="dark"]) .group-header:not(:first-child) {\n border-top-color: var(--select-border);\n }\n\n :host(.dark-mode) .option.selected::before,\n :host([dark-mode]) .option.selected::before,\n :host([darkmode]) .option.selected::before,\n :host([data-theme="dark"]) .option.selected::before,\n :host([theme="dark"]) .option.selected::before,\n :host-context(.dark-mode) .option.selected::before,\n :host-context(.dark) .option.selected::before,\n :host-context([dark-mode]) .option.selected::before,\n :host-context([darkmode]) .option.selected::before,\n :host-context([data-theme="dark"]) .option.selected::before,\n :host-context([theme="dark"]) .option.selected::before {\n background: var(--select-accent);\n }\n ',this._shadow.firstChild?this._shadow.insertBefore(e,this._shadow.firstChild):this._shadow.appendChild(e)}_attachEventListeners(){this._arrowContainer&&(this._boundArrowClick=e=>{e.stopPropagation(),e.preventDefault(),this._state.isOpen&&!1!==this._config.selection.toggleOnTriggerClick?this._handleClose():this._state.isOpen||this._handleOpen()},this._arrowContainer.addEventListener("click",this._boundArrowClick)),this._clearControl&&(this._clearControl.addEventListener("pointerdown",e=>{e.stopPropagation(),e.preventDefault()}),this._clearControl.addEventListener("click",e=>{e.stopPropagation(),e.preventDefault(),this._handleClearControlClick()})),this._inputContainer.addEventListener("pointerdown",e=>{const t=e.target;if(!this._config.enabled)return;if(t&&t.closest(".dropdown-arrow-container"))return;if(t&&t.closest(".clear-control-button"))return;if(this._isPointerOnInputScrollbar(e))return void(this._suppressNextOpenClick=!0);const i="multi"===this._config.selection.mode&&"horizontal"===(this._config.multiSelectDisplay?.mode??"wrap"),n=this._canUseHorizontalMultiScroll(t);if(n&&0===e.button)return this._beginMultiScrollDrag(e),this._suppressNextOpenClick=!1,void e.preventDefault();t&&!t.matches(".select-input")&&e.preventDefault();const o=Boolean(t&&t.matches(".select-input"));if(this._state.isOpen&&!1!==this._config.selection.toggleOnTriggerClick&&!i&&!n&&(!o||!this._config.searchable))return void this._handleClose();const s=!this._state.isOpen;if(s&&this._handleOpen(),this._applyFocusIntent("input","input-container-trigger"),s&&this._optionsContainer&&"number"==typeof e.pointerId)try{this._optionsContainer.setPointerCapture(e.pointerId)}catch(e){}}),this._inputContainer.addEventListener("click",e=>{const t=e.target,i="multi"===this._config.selection.mode&&"horizontal"===(this._config.multiSelectDisplay?.mode??"wrap");return this._config.enabled&&i?t&&t.closest(".dropdown-arrow-container, .clear-control-button")||this._suppressNextOpenClick||this._multiScrollDrag.moved||this._isPointerOnInputScrollbar(e)?(this._suppressNextOpenClick=!1,void(this._multiScrollDrag.moved=!1)):(this._suppressNextOpenClick=!1,this._multiScrollDrag.moved=!1,this._state.isOpen||this._handleOpen(),void this._applyFocusIntent("input","input-container-activation")):(this._suppressNextOpenClick=!1,void(this._multiScrollDrag.moved=!1))}),this._inputContent.addEventListener("pointermove",e=>{this._updateMultiScrollDrag(e)}),this._inputContent.addEventListener("pointerup",e=>{this._endMultiScrollDrag(e.pointerId)}),this._inputContent.addEventListener("pointercancel",e=>{this._endMultiScrollDrag(e.pointerId)}),this._inputContent.addEventListener("wheel",e=>{if("multi"===this._config.selection.mode&&"horizontal"===(this._config.multiSelectDisplay?.mode??"wrap")){const t=Math.abs(e.deltaX)>Math.abs(e.deltaY)?e.deltaX:e.deltaY;0!==t&&(this._inputContent.scrollLeft+=t),e.preventDefault()}},{passive:!1}),this._container.addEventListener("click",e=>{e.stopPropagation()}),this._input.addEventListener("focus",()=>{this._runEngineEffects(this._engine.dispatch({type:"FOCUS_GAINED"})),this._handleOpen()}),this._input.addEventListener("blur",e=>{this._runEngineEffects(this._engine.dispatch({type:"FOCUS_LOST"}));const t=e.relatedTarget;t&&(this._shadow.contains(t)||this._container.contains(t))||this._setLifecycleTimeout(()=>{if(this._suppressBlurClose)return;const e=document.activeElement;e&&(this._shadow.contains(e)||this._container.contains(e))||this._handleClose("blur")},150)}),this._input.addEventListener("input",e=>{if(!this._config.searchable)return;const t=e.target.value;this._handleSearch(t)}),this._optionsContainer.addEventListener("pointerdown",()=>{this._suppressBlurClose=!0,this._setLifecycleTimeout(()=>{this._suppressBlurClose=!1},150)});this._optionsContainer.addEventListener("click",e=>{const t=e.composedPath&&e.composedPath()||[e.target];let i=null;for(const e of t)if(e instanceof Element)try{if(e.matches("[data-sm-selectable], [data-selectable], [data-sm-state]")){i=e;break}}catch(e){continue}if(i&&(!i.hasAttribute("aria-disabled")||i.classList.contains("smilodon-option--disabled-selectable"))){const t=i.getAttribute("data-sm-index")??i.getAttribute("data-index"),n=Number(t);Number.isNaN(n)||this._selectOption(n,{shiftKey:e.shiftKey,toggleKey:e.ctrlKey||e.metaKey})}}),this._input.addEventListener("keydown",e=>this._handleKeydown(e))}_initializeObservers(){if(this._intersectionObserver&&(this._intersectionObserver.disconnect(),this._intersectionObserver=void 0),("acknowledged"!==this._dataLoadingConfig.protocol||this._dataRequestCoordinator&&this._acknowledgedReady)&&this._config.infiniteScroll.enabled){const e=Boolean(this._dataRequestCoordinator&&"acknowledged"===this._dataLoadingConfig.protocol);if(e&&"undefined"==typeof IntersectionObserver)return;let t;try{t=new IntersectionObserver(i=>{this._intersectionObserver===t&&i.forEach(t=>{if(e){if(!this._acknowledgedReady||!this.isConnected||t.target!==this._loadMoreTrigger)return;if(!t.isIntersecting)return void this._dataRequestCoordinator?.setSentinelIntersecting(!1);if(this._acknowledgedProjectionPending||this._acknowledgedProjectionSettling)return;const e=this._dataRequestCoordinator?.setSentinelIntersecting(!0)??[];return void this._dispatchAcknowledgedActions(e)}t.isIntersecting&&!this._state.isBusy&&this._loadMoreItems()})},e?{root:this._optionsContainer,threshold:.1}:{threshold:.1}),this._intersectionObserver=t}catch(t){if(this._intersectionObserver=void 0,!e)throw t}}}async _loadInitialSelectedItems(){if(!this._config.serverSide.fetchSelectedItems||!this._config.serverSide.initialSelectedValues)return;this._setBusy(!0);const e=++this._asyncGeneration;try{const t=await this._config.serverSide.fetchSelectedItems(this._config.serverSide.initialSelectedValues);if(e!==this._asyncGeneration||!this.isConnected)return;const i=createItemRegistry(t,this._itemAdapter,{duplicateKeyPolicy:this._getDuplicateKeyPolicy()});this._requestSelectionReplacement(i.records,"external-value-sync","initial selected items"),this._updateInputDisplay()}catch(t){if(e!==this._asyncGeneration||!this.isConnected)return;this._handleError(t)}finally{e===this._asyncGeneration&&this.isConnected&&this._setBusy(!1)}}_runEngineEffects(e){this._effectRunner.run(e,{focusTrigger:()=>{this._applyFocusIntent("input","engine-focus-trigger")},syncAria:()=>{this._syncPopupAria()}})}_syncPopupAria(){this._input&&this._syncComboboxAccessibility()}_syncComboboxAccessibility(){if(!this._input||!this._engine||!this._state)return;applyAccessibilityEffects(computeAccessibilityEffects(deriveAccessibilityState(this._engine.state,{searchable:this._config.searchable,readonly:!this._config.searchable,invalid:this._hasError,label:{ariaLabel:this.getAttribute("aria-label")?.trim()||null,ariaDescription:this.getAttribute("aria-description")?.trim()||null},errorMessage:this._errorMessage,errorDescriptionId:this._hasError&&this._errorMessage?this._errorDescription?.id??null:null}),{controlsId:this._dropdown?.id||null,optionKeys:[]}).filter(e=>"SYNC_COMBOBOX_ARIA"===e.type),{combobox:this._input,getOptionByKey:e=>{if(!this._state.isOpen)return null;const t=this._itemRegistry.keyToIndex.get(e);return void 0===t?null:this._getOptionElementByIndex(t)}})}_syncListboxAccessibility(){if(!this._dropdown||!this._engine||!this._state)return;applyAccessibilityEffects(computeAccessibilityEffects({...deriveAccessibilityState(this._engine.state,{label:{ariaLabel:this.getAttribute("aria-label")?.trim()||null}}),busy:this._state.isBusy||"acknowledged"===this._dataLoadingConfig.protocol&&"true"===this.getAttribute("aria-busy")},{controlsId:this._dropdown.id||null,optionKeys:[]}).filter(e=>"SYNC_LISTBOX_ARIA"===e.type),{listbox:this._dropdown})}_syncRenderedOptionAccessibility(){if(!this._optionsContainer||!this._engine||!this._state)return;const e=new Map;if(this._optionsContainer.querySelectorAll("[data-index]").forEach(t=>{const i=Number(t.getAttribute("data-index"));if(!Number.isFinite(i))return;const n=this._itemRegistry.indexToKey.get(i);void 0!==n&&e.set(n,t)}),0===e.size)return;applyAccessibilityEffects(computeAccessibilityEffects(deriveAccessibilityState(this._engine.state),{controlsId:this._dropdown?.id||null,optionKeys:[...e.keys()]}).filter(e=>"SYNC_OPTION_ARIA"===e.type),{getOptionByKey:t=>e.get(t)??null})}_applyFocusIntent(e,t,i){applyAccessibilityEffects(computeAccessibilityEffects(deriveAccessibilityState(this._engine.state),{optionKeys:[],focusIntents:[{target:e,reason:t}]}).filter(e=>"FOCUS_INTENT"===e.type),{focusTargets:{input:"input"===e?this._input:null,clearButton:"clear-button"===e?this._clearControl:null,getActiveOption:()=>"active-option"===e?i??null:null}},{applyFocus:!0})}_handleOpen(){if(!this._config.enabled)return void this._runEngineEffects(this._engine.dispatch({type:"DISABLED_CHANGED",disabled:!0}));if(this._state.isOpen)return;EnhancedSelect._instances.forEach(e=>{e!==this&&e._handleClose()});const e=this._engine.dispatch({type:"OPEN_REQUEST"});if(e.some(e=>"POPUP_OPENED"===e.type)&&(this._runEngineEffects(e),this._cancelDropdownExit(),this._dropdown.removeAttribute("inert"),this._dropdown.removeAttribute("aria-hidden"),this._markOpenStart(),this.setAttribute("data-open","true"),this._liftStackingAncestors(),this._dropdown.style.display="block",this._updateArrowRotation(),this._renderOptions(),this._syncDropdownPlacement(),this._setInitialActiveOption(),this._emit("open",{}),this._config.callbacks.onOpen?.(),this._announce("Options expanded"),this._config.scrollToSelected.enabled)){const e=this._keyboardActiveChangeGeneration,t=()=>this._state.isOpen&&this._keyboardActiveChangeGeneration===e;this._requestLifecycleFrame(()=>{t()&&this._requestLifecycleFrame(()=>{t()&&this._scrollToSelected()})})}}_handleClose(e="programmatic"){const t=this._engine.dispatch({type:"CLOSE_REQUEST",reason:e});t.some(e=>"POPUP_CLOSED"===e.type)&&(this.removeAttribute("data-open"),this._restoreLiftedAncestors(),this._dropdown.setAttribute("data-placement",this._resolvedDropdownPlacement),this._updateArrowRotation(),this._runEngineEffects(t),this._beginDropdownExit("disconnect"===e||!this.isConnected),this._emit("close",{}),this._config.callbacks.onClose?.(),this._announce("Options collapsed"))}_cancelDropdownExit(){null!==this._dropdownExitTimer&&(window.clearTimeout(this._dropdownExitTimer),this._dropdownExitTimer=null),this._dropdown.removeEventListener("animationend",this._onDropdownExitAnimationEnd),this._dropdown.removeAttribute("data-motion")}_finishDropdownExit(){this._state.isOpen||"closing"!==this._dropdown.getAttribute("data-motion")||(this._cancelDropdownExit(),this._dropdown.style.display="none")}_beginDropdownExit(e){if(this._cancelDropdownExit(),this._dropdown.setAttribute("inert",""),this._dropdown.setAttribute("aria-hidden","true"),e||"none"===this._dropdown.style.display)return void(this._dropdown.style.display="none");this._dropdown.setAttribute("data-motion","closing");const t=this._getDropdownExitDurationMs();t<=0?this._finishDropdownExit():(this._dropdown.addEventListener("animationend",this._onDropdownExitAnimationEnd),this._dropdownExitTimer=window.setTimeout(()=>this._finishDropdownExit(),t+34))}_getDropdownExitDurationMs(){if(window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return 0;const e=getComputedStyle(this._dropdown),t=e.animationName.split(",").map(e=>e.trim());if(!t.length||t.every(e=>!e||"none"===e))return 0;const i=e=>{const t=e.trim(),i=Number.parseFloat(t);return Number.isFinite(i)?t.endsWith("ms")?i:t.endsWith("s")?1e3*i:0:0},n=e.animationDuration.split(","),o=e.animationDelay.split(","),s=e.animationIterationCount.split(","),r=t.reduce((e,t,r)=>{if(!t||"none"===t)return e;const a=i(n[r%n.length]??"0s"),l=i(o[r%o.length]??"0s"),c=Number.parseFloat(s[r%s.length]??"1"),d=Number.isFinite(c)?Math.max(0,c):1;return Math.max(e,Math.max(0,a*d+l))},0);return Math.min(r,1e4)}_updateDropdownVisibility(){this._state.isOpen?(this.setAttribute("data-open","true"),this._liftStackingAncestors(),this._dropdown.style.display="block",this._syncDropdownPlacement()):(this.removeAttribute("data-open"),this._restoreLiftedAncestors(),this._dropdown.style.display="none"),this._syncComboboxAccessibility()}_liftStackingAncestors(){this._restoreLiftedAncestors();let e=this.parentElement;for(;e&&e!==document.body;){if(this._createsStackingContext(e)){const t=e.hasAttribute("data-smilodon-open-ancestor");this._liftedAncestors.push({element:e,position:e.style.position,zIndex:e.style.zIndex,hadMarker:t}),"static"===getComputedStyle(e).position&&(e.style.position="relative"),e.style.zIndex="var(--select-ancestor-open-z-index, var(--select-host-open-z-index, var(--select-dropdown-z-index, 1000)))",e.setAttribute("data-smilodon-open-ancestor","true")}e=e.parentElement}}_restoreLiftedAncestors(){for(const e of this._liftedAncestors)e.element.style.position=e.position,e.element.style.zIndex=e.zIndex,e.hadMarker||e.element.removeAttribute("data-smilodon-open-ancestor");this._liftedAncestors=[]}_createsStackingContext(e){const t=getComputedStyle(e);return"fixed"===t.position||"sticky"===t.position||("auto"!==t.zIndex&&"static"!==t.position||("1"!==t.opacity||("none"!==t.transform||("none"!==t.filter||(!(!t.backdropFilter||"none"===t.backdropFilter)||("none"!==t.perspective||("normal"!==t.mixBlendMode||("isolate"===t.isolation||(!(!t.contain.includes("paint")&&!t.contain.includes("layout"))||!!(t.willChange.includes("transform")||t.willChange.includes("opacity")||t.willChange.includes("filter")))))))))))}_updateArrowRotation(){if(this._arrowContainer){const e=this._arrowContainer.querySelector(".dropdown-arrow");e&&(this._state.isOpen?e.classList.add("open"):e.classList.remove("open"))}}_isPerfEnabled(){return"undefined"!=typeof globalThis&&!0===globalThis.__SMILODON_DEV__&&"undefined"!=typeof performance&&"function"==typeof performance.mark&&"function"==typeof performance.measure}_perfMark(e){this._isPerfEnabled()&&performance.mark(e)}_perfMeasure(e,t,i){this._isPerfEnabled()&&(performance.measure(e,t,i),performance.clearMarks(t),performance.clearMarks(i),performance.clearMeasures(e))}_markOpenStart(){this._isPerfEnabled()&&(this._pendingFirstRenderMark=!0,this._perfMark("smilodon-dropdown-open-start"))}_finalizePerfMarks(){if(!this._isPerfEnabled())return this._pendingFirstRenderMark=!1,void(this._pendingSearchRenderMark=!1);this._pendingFirstRenderMark&&(this._pendingFirstRenderMark=!1,this._perfMark("smilodon-first-render-complete"),this._perfMeasure("smilodon-dropdown-to-first-render","smilodon-dropdown-open-start","smilodon-first-render-complete")),this._pendingSearchRenderMark&&(this._pendingSearchRenderMark=!1,this._perfMark("smilodon-search-render-complete"),this._perfMeasure("smilodon-search-to-render","smilodon-search-input-last","smilodon-search-render-complete"))}_filterItemsByQuery(e,t){if(!t?.trim())return e;const i=t.toLowerCase().trim(),n=this._config.serverSide.getLabelFromItem??(e=>e?.label??e?.text??String(e)),o=[],s=e.length;for(let t=0;t<s;t++){const s=e[t];if(null!=s)try{const e=n(s);if(null==e)continue;String(e).toLowerCase().includes(i)&&o.push(s)}catch(e){continue}}return o}_handleSearch(e){if(this._dataRequestCoordinator&&(this._acknowledgedProjectionPending||this._acknowledgedProjectionSettling))return this._acknowledgedPendingSearchQuery=e,this._input.value=e,void this._syncClearControlState();if("acknowledged"===this._dataLoadingConfig.protocol&&("remote"===this._dataLoadingConfig.searchMode||"hybrid"===this._dataLoadingConfig.searchMode)){if(this._state.searchQuery=e,this._syncClearControlState(),this._state.lastNotifiedQuery=e,this._state.lastNotifiedResultCount=0,this._dataRequestCoordinator){const t=this._dataRequestCoordinator.setQuery(e);this._acknowledgedReady?this._dispatchAcknowledgedActions(t):this._renderOptions()}else this._state.isOpen?this._renderOptions():this._handleOpen();return}this._state.searchQuery=e,this._syncClearControlState(),"acknowledged"===this._dataLoadingConfig.protocol&&this._dataRequestCoordinator&&this._dispatchAcknowledgedActions(this._dataRequestCoordinator.setQuery(e)),e.length>0?(this._perfMark("smilodon-search-input-last"),this._pendingSearchRenderMark=!0):this._pendingSearchRenderMark=!1,this._searchTimeout&&clearTimeout(this._searchTimeout),this._state.isSearching=!1,this._state.isOpen?this._renderOptions():this._handleOpen();const t=this._filterItemsByQuery(this._state.loadedItems,e),i=t.length;e.trim()&&this._announce(`${i} result${1!==i?"s":""} found for "${e}"`),e===this._state.lastNotifiedQuery&&i===this._state.lastNotifiedResultCount||(this._state.lastNotifiedQuery=e,this._state.lastNotifiedResultCount=i,this._setLifecycleTimeout(()=>{this._emit("search",{query:e,results:t,count:i}),this._config.callbacks.onSearch?.(e)},0))}_handleKeydown(e){if(this._config.enabled)switch(e.key){case"ArrowDown":e.preventDefault(),this._state.isOpen?this._moveActive(1,{shiftKey:e.shiftKey,toggleKey:e.ctrlKey||e.metaKey}):this._handleOpen();break;case"ArrowUp":e.preventDefault(),this._state.isOpen?this._moveActive(-1,{shiftKey:e.shiftKey,toggleKey:e.ctrlKey||e.metaKey}):this._handleOpen();break;case"Home":if(e.preventDefault(),this._state.isOpen){const t=this._getSelectableOptionIndices()[0];if(void 0===t)break;this._setActive(t),"multi"===this._config.selection.mode&&e.shiftKey&&this._selectRange(this._rangeAnchorIndex??t,t,{clear:!(e.ctrlKey||e.metaKey)})}break;case"End":if(e.preventDefault(),this._state.isOpen){const t=this._getSelectableOptionIndices(),i=t[t.length-1];if(void 0===i)break;this._setActive(i),"multi"===this._config.selection.mode&&e.shiftKey&&this._selectRange(this._rangeAnchorIndex??i,i,{clear:!(e.ctrlKey||e.metaKey)})}break;case"PageDown":e.preventDefault(),this._state.isOpen&&this._moveActive(10,{shiftKey:e.shiftKey,toggleKey:e.ctrlKey||e.metaKey});break;case"PageUp":e.preventDefault(),this._state.isOpen&&this._moveActive(-10,{shiftKey:e.shiftKey,toggleKey:e.ctrlKey||e.metaKey});break;case"Enter":case" ":if(e.preventDefault(),this._state.isOpen){const t=this._engine.state.activeKey,i=null===t?-1:this._itemRegistry.keyToIndex.get(t)??-1;i>=0&&this._selectOption(i,{shiftKey:e.shiftKey,toggleKey:e.ctrlKey||e.metaKey,reason:"keyboard"})}else this._handleOpen();break;case"Escape":e.preventDefault(),this._handleClose("escape");break;case"Tab":this._state.isOpen&&this._handleClose();break;case"a":case"A":(e.ctrlKey||e.metaKey)&&"multi"===this._config.selection.mode&&(e.preventDefault(),this._selectAll());break;default:1!==e.key.length||e.ctrlKey||e.altKey||e.metaKey||this._handleTypeAhead(e.key)}}_moveActive(e,t){const i=this._getSelectableOptionIndices();if(0===i.length)return;const n=this._engine.state.activeKey,o=null===n?-1:this._itemRegistry.keyToIndex.get(n)??-1,s=i.indexOf(o),r=s>=0?s:e>=0?-1:i.length,a=i[Math.max(0,Math.min(i.length-1,r+e))];if(this._setActive(a),"multi"===this._config.selection.mode&&t?.shiftKey){const e=this._rangeAnchorIndex??o,i=e>=0?e:a;null===this._rangeAnchorIndex&&(this._rangeAnchorIndex=i),this._selectRange(i,a,{clear:!t?.toggleKey})}}_setActive(e,t="keyboard"){this._ensureRegistryCurrent();const i=this._getRecordByIndex(e);let n=this._getOptionElementByIndex(e);if(!n&&i&&this._guardedVirtualizer&&(this._materializeGuardedVirtualKey(i.key),n=this._getOptionElementByIndex(e)),!i||i.disabled||!n||"true"===n.getAttribute("aria-disabled"))return;"keyboard"===t&&(this._keyboardActiveChangeGeneration+=1);const o=this._state.activeIndex;if(this._dispatchActiveKey(i.key,t,"set active"),this._state.activeIndex===e){if(o>=0&&o!==e){const e=this._getOptionElementByIndex(o);e&&("setActive"in e&&"function"==typeof e.setActive?e.setActive(!1):this._syncCustomOptionActiveClasses(e,!1))}if(n){"setActive"in n&&"function"==typeof n.setActive?n.setActive(!0):this._syncCustomOptionActiveClasses(n,!0),"function"==typeof n.scrollIntoView&&n.scrollIntoView({block:"nearest",behavior:"smooth"});const t=this._state.loadedItems.length;this._announce(`Item ${e+1} of ${t}`),this._syncLegacyActiveAria()}}}_getOptionElementByIndex(e){return this._optionsContainer.querySelector(`[data-index="${e}"]`)}_getSelectableOptions(){return Array.from(this._optionsContainer.children).filter(e=>(e.hasAttribute("data-index")||e.hasAttribute("data-sm-selectable"))&&"true"!==e.getAttribute("aria-disabled"))}_getSelectableOptionIndices(){return this._guardedVirtualizer?this._renderPlan.filteredKeys.flatMap(e=>{const t=this._itemRegistry.keyToRecord.get(e);return t&&!t.disabled?[t.index]:[]}):this._getSelectableOptions().map(e=>Number(e.getAttribute("data-sm-index")??e.getAttribute("data-index"))).filter(e=>Number.isFinite(e))}_buildRendererHelpers(){return{onSelect:(e,t)=>this._selectOption(t),getIndex:e=>{const t=e?.closest?.("[data-selectable]");if(!t)return null;const i=Number(t.dataset.index);return Number.isFinite(i)?i:null},keyboardFocus:e=>{this._setActive(e);const t=this._getOptionElementByIndex(e);this._applyFocusIntent("active-option","renderer-keyboard-focus",t)}}}_handleTypeAhead(e){this._typeTimeout&&clearTimeout(this._typeTimeout),this._typeBuffer+=e.toLowerCase(),this._typeTimeout=window.setTimeout(()=>{this._typeBuffer=""},500);const t=this._config.serverSide.getLabelFromItem||(e=>e?.label??String(e)),i=this._state.loadedItems.findIndex(e=>t(e).toLowerCase().startsWith(this._typeBuffer));i>=0&&this._setActive(i,"search")}_selectAll(){if("multi"!==this._config.selection.mode)return;this._ensureRegistryCurrent();const e=this._getSelectableOptions(),t=this._getSelectedEntries();e.forEach(e=>{const i=Number(e.getAttribute("data-sm-index")??e.getAttribute("data-index"));if(!Number.isFinite(i))return;const n=this._getRecordByIndex(i);n&&!this._isOptionSelectionBlocked(n.item)&&t.push(n)}),this._requestSelectionReplacement(t,"keyboard","select all"),this._renderOptions(),this._updateInputDisplay(),this._emitChange(),this._announce(`Selected all ${e.length} items`)}_selectRange(e,t,i){if("multi"!==this._config.selection.mode)return;this._ensureRegistryCurrent();const[n,o]=e<t?[e,t]:[t,e],s=this._getSelectedEntries(),r=i?.clear?s.filter(e=>!this._itemRegistry.keyToRecord.has(e.key)):s;for(let e=n;e<=o;e+=1){const t=this._getRecordByIndex(e),i=this._getOptionElementByIndex(e);("true"!==i?.getAttribute("aria-disabled")||i.classList.contains("smilodon-option--disabled-selectable"))&&(t&&!this._isOptionSelectionBlocked(t.item)&&r.push(t))}this._requestSelectionReplacement(r,i?.reason??"keyboard","select range"),this._renderOptions(),this._updateInputDisplay();const a=this._getRecordByIndex(t),l=a?this._getSelectEventDetail(a):null;l&&this._emit("select",l),this._emitChange(),this._announce(`${this._state.selectedIndices.size} items selected`),l&&this._config.callbacks.onSelect?.(l)}_getSelectEventDetail(e){const t=this._config.serverSide.getValueFromItem||(e=>e?.value??e),i=this._config.serverSide.getLabelFromItem||(e=>e?.label??String(e));return{item:e.item,index:e.index,value:t(e.item),label:i(e.item),selected:this._engine.state.selectedKeys.has(e.key),multi:"multi"===this._config.selection.mode}}_setInitialActiveOption(){const e=this._getSelectableOptionIndices(),t=Array.from(this._state.selectedIndices).sort((e,t)=>e-t);if(0===e.length||0===t.length)return void this._dispatchActiveKey(null,"open","initial active option");const i=t.find(t=>e.includes(t))??e[0];this._setActive(i,"open")}_announce(e){applyAccessibilityEffects(computeAccessibilityEffects(deriveAccessibilityState(this._engine.state),{optionKeys:[],announcements:[{politeness:"polite",message:e}]}).filter(e=>"ANNOUNCE"===e.type),{liveRegion:this._liveRegion}),this._liveRegion&&this._setLifecycleTimeout(()=>{applyAccessibilityEffects(computeAccessibilityEffects(deriveAccessibilityState(this._engine.state),{optionKeys:[],announcements:[{politeness:"polite",message:""}]}).filter(e=>"ANNOUNCE"===e.type),{liveRegion:this._liveRegion})},1e3)}_selectOption(e,t){this._ensureRegistryCurrent();const i=this._getRecordByIndex(e);if(!i)return;e=i.index;const n=i.item;if(this._isOptionSelectionBlocked(n))return;const o=this._engine.state.selectedKeys.has(i.key),s=t?.reason??"pointer";if(i.disabled||this._dispatchActiveKey(i.key,"keyboard"===s?"keyboard":"pointer","option selection"),"single"===this._config.selection.mode)this._dispatchSelection({type:o&&this._config.selection.allowDeselect?"TOGGLE_KEY_REQUEST":"SELECT_KEY_REQUEST",key:i.key,reason:s},"single option selection"),this._renderOptions(),this._config.selection.closeOnSelect&&this._handleClose("selection");else{const n=Boolean(t?.toggleKey);if(Boolean(t?.shiftKey)){const t=this._rangeAnchorIndex??e;return this._selectRange(t,e,{clear:!n,reason:s}),void(this._rangeAnchorIndex=t)}const r=this._config.selection.maxSelections||0;if(!o&&r>0&&this._engine.state.selectedKeys.size>=r)return this._announce(`Maximum ${r} selections allowed`),void this._renderOptions();this._dispatchSelection({type:"TOGGLE_KEY_REQUEST",key:i.key,reason:s},"multi option selection"),this._renderOptions()}this._rangeAnchorIndex=e,this._updateInputDisplay();const r=this._getSelectEventDetail(i);this._emit("select",r),this._emitChange();const a=r.label;if("single"===this._config.selection.mode)this._announce(`Selected ${a}`);else{const e=this._state.selectedIndices.size,t=o?"Deselected":"Selected";this._announce(`${t} ${a}. ${e} selected`)}this._config.callbacks.onSelect?.(r)}_handleOptionRemove(e,t){this._ensureRegistryCurrent();const i=this._getSelectedEntries().find(i=>void 0===t?i.index===e:i.key===t);if(!i)return;const n=i.item,o=this._shadow.activeElement,s=o instanceof HTMLButtonElement&&"chip-remove"===o.getAttribute("part")?o.closest(".selection-badge"):null,r=null!==s,a=s?Array.from(this._inputContent.querySelectorAll(".selection-badge")).indexOf(s):-1,l=this._itemRegistry.keyToRecord.has(i.key)?this._getOptionElementByIndex(i.index):null;if(this._dispatchSelection({type:"DESELECT_KEY_REQUEST",key:i.key,reason:"pointer"},"remove selected item"),l&&"setSelected"in l&&"function"==typeof l.setSelected)l.setSelected(!1);else if(l){l.classList.remove("selected","sm-selected","smilodon-option--selected");const e=(l.dataset.smState||"").split(" ").map(e=>e.trim()).filter(e=>e&&"selected"!==e);e.length>0?l.dataset.smState=e.join(" "):delete l.dataset.smState}if(this._updateInputDisplay(),this._renderOptions(),this._emitChange(),r&&this.isConnected){const e=this._inputContent.querySelectorAll('[part="chip-remove"]');if(e.length>0){e[Math.min(Math.max(a,0),e.length-1)].focus()}else this._applyFocusIntent("input","selected-chip-removed")}const c=l&&"getConfig"in l&&"function"==typeof l.getConfig?l.getConfig():void 0;this._emit("remove",{item:c?.item??n,index:i.index})}_updateInputDisplay(){const e=this._getSelectedEntries(),t=e.map(({item:e})=>e),i=this._config.serverSide.getLabelFromItem||(e=>e?.label??String(e));if(0===t.length){this._input.value="",this._input.placeholder=this._config.placeholder||"Select an option...";this._inputContent.querySelectorAll(".selection-badge").forEach(e=>e.remove())}else if("single"===this._config.selection.mode)this._input.value=i(t[0]);else{this._input.value="",this._input.placeholder="";this._inputContent.querySelectorAll(".selection-badge").forEach(e=>e.remove()),e.forEach(({key:e,index:t,item:n})=>{const o=document.createElement("span");o.className="selection-badge",this._config.styles.classNames?.badge&&o.classList.add(...this._config.styles.classNames.badge.split(" ").filter(Boolean)),o.setAttribute("part","chip");const s=document.createElement("span");if(s.className="selection-badge-label",this._config.styles.classNames?.badgeLabel&&s.classList.add(...this._config.styles.classNames.badgeLabel.split(" ").filter(Boolean)),s.setAttribute("part","chip-label"),s.textContent=i(n),o.appendChild(s),!1!==this._config.selection.showRemoveButton){const s=document.createElement("button");s.type="button",s.className="badge-remove",this._config.styles.classNames?.removeButton&&s.classList.add(...this._config.styles.classNames.removeButton.split(" ").filter(Boolean)),this._config.styles.classNames?.badgeRemove&&s.classList.add(...this._config.styles.classNames.badgeRemove.split(" ").filter(Boolean)),s.setAttribute("part","chip-remove"),s.setAttribute("aria-label",`Remove ${i(n)}`);const r=document.createElement("span");r.className="badge-remove-icon",this._config.styles.classNames?.badgeRemoveIcon&&r.classList.add(...this._config.styles.classNames.badgeRemoveIcon.split(" ").filter(Boolean)),r.setAttribute("part","chip-remove-icon"),this._setIconContent(r,this._config.selection.removeButtonIcon,"×"),s.appendChild(r),s.addEventListener("pointerdown",e=>{e.stopPropagation(),e.preventDefault()}),s.addEventListener("click",i=>{i.stopPropagation(),i.preventDefault(),this._handleOptionRemove(t,e)}),o.appendChild(s)}this._inputContent.insertBefore(o,this._input)})}null!==this._acknowledgedPendingSearchQuery&&(this._input.value=this._acknowledgedPendingSearchQuery),this._syncClearControlState()}_isActivelyEditingSearchInput(){return!0===this._config.searchable&&this._state.isOpen&&this._shadow.activeElement===this._input}_renderOptionsWithAnimation(){this._optionsContainer.style.opacity="0",this._optionsContainer.style.transition="opacity 0.15s ease-out",this._setLifecycleTimeout(()=>{this._renderOptions(),this._optionsContainer.style.opacity="1",this._optionsContainer.style.transition="opacity 0.2s ease-in"},150)}_scrollToSelected(){if(0===this._state.selectedIndices.size)return;const e=this._config.scrollToSelected.multiSelectTarget,t=Array.from(this._state.selectedIndices).filter(e=>e>=0).sort((e,t)=>e-t);if(0===t.length)return;let i;if("multi"===this._config.selection.mode&&t.length>1){const e=this._dropdown.getBoundingClientRect(),n=this._dropdown.scrollTop+e.height/2;let o=t[0],s=1/0;for(const e of t){const t=this._getOptionElementByIndex(e);if(t){const i=t.offsetTop,r=Math.abs(i-n);r<s&&(s=r,o=e)}}i=o}else i="first"===e?t[0]:t[t.length-1];let n=this._getOptionElementByIndex(i);if(!n&&this._guardedVirtualizer){const e=this._itemRegistry.indexToKey.get(i);void 0!==e&&(this._materializeGuardedVirtualKey(e),n=this._getOptionElementByIndex(i))}n&&("function"==typeof n.scrollIntoView&&n.scrollIntoView({block:this._config.scrollToSelected.block||"center",behavior:"smooth"}),this._setActive(i,"programmatic"))}async _loadMoreItems(e="manual"){if("acknowledged"===this._dataLoadingConfig.protocol){if(!this._dataRequestCoordinator||!this._acknowledgedReady||this._acknowledgedProjectionPending||this._acknowledgedProjectionSettling)return;const t=this._dataRequestCoordinator.requestLoadMore(e);return void this._dispatchAcknowledgedActions(t)}if(this._dataRequestCoordinator){if(!this._acknowledgedReady||this._acknowledgedProjectionPending||this._acknowledgedProjectionSettling)return;const t=this._dataRequestCoordinator.requestLoadMore(e);return void this._dispatchAcknowledgedActions(t)}if(!this._state.isBusy){this._setBusy(!0),this._dropdown&&(this._state.lastScrollPosition=this._dropdown.scrollTop,this._state.preserveScrollPosition=!0,this._renderOptions(),this._dropdown.scrollTop=this._state.lastScrollPosition);try{this._state.currentPage++,this._emit("loadMore",{page:this._state.currentPage,items:[]}),this._config.callbacks.onLoadMore?.(this._state.currentPage)}catch(e){this._handleError(e),this._setBusy(!1)}}}_setBusy(e){e&&this._beginBusyPresentation(),this._state.isBusy=e,this._syncListboxAccessibility(),this._renderOptions()}_handleError(e){this._emit("error",{message:e.message,cause:e}),this._config.callbacks.onError?.(e)}_emit(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0})),"diagnostic"!==e&&this._track("event",String(e),t)}_track(e,t,i){const n=this._config.tracking;if(!n?.enabled)return;if("event"===e&&!n.events)return;if("style"===e&&!n.styling)return;if("limitation"===e&&!n.limitations)return;const o={timestamp:Date.now(),source:e,name:t,detail:i},s="event"===e?this._tracking.events:"style"===e?this._tracking.styles:this._tracking.limitations;s.push(o);const r=Math.max(10,n.maxEntries||200);s.length>r&&s.splice(0,s.length-r),n.emitDiagnostics&&this.dispatchEvent(new CustomEvent("diagnostic",{detail:o,bubbles:!0,composed:!0}))}_getKnownLimitationDefinitions(){return[{id:"variableItemHeight",title:"Variable item height",description:"Virtualization assumes fixed or estimated item heights; fully dynamic heights are not yet supported.",workaround:"Use consistent item heights or set estimatedItemHeight to your dominant row size."},{id:"builtInFetchPaginationApi",title:"Built-in fetch/pagination API",description:"Core does not include a built-in fetchUrl/searchUrl pagination transport.",workaround:"Use onSearch/onLoadMore callbacks and update data via setItems()."},{id:"virtualizationOverheadSmallLists",title:"Virtualization overhead for small lists",description:"Virtualization can add slight overhead on very small lists.",workaround:"Disable virtualization for tiny datasets when micro-latency is critical."},{id:"runtimeModeSwitching",title:"Runtime single/multi mode switching",description:"Switching between single and multi mode can require state reset for consistency.",workaround:"Enable autoMitigateRuntimeModeSwitch or recreate/reset component state when toggling modes."},{id:"legacyBrowserSupport",title:"Legacy browser support",description:"Official support targets modern evergreen browsers."},{id:"webkitArchLinux",title:"Playwright WebKit on Arch-based Linux",description:"Native WebKit Playwright bundle depends on unavailable legacy system libraries on Arch-based distros.",workaround:"Run WebKit E2E tests via Playwright Docker image."}]}_evaluateLimitationStatus(e){return"suppress"===(this._config.limitations?.policies?.[e]?.mode??"default")?"suppressed":"runtimeModeSwitching"===e&&this._config.limitations?.autoMitigateRuntimeModeSwitch?"mitigated":"active"}getKnownLimitations(){return this._getKnownLimitationDefinitions().map(e=>{const t=this._config.limitations?.policies?.[e.id]?.mode??"default";return{...e,mode:t,status:this._evaluateLimitationStatus(e.id)}})}setLimitationPolicies(e){const t={...this._config.limitations?.policies||{},...e};this.updateConfig({limitations:{...this._config.limitations||{autoMitigateRuntimeModeSwitch:!0,policies:{}},policies:t}}),this._track("limitation","policiesUpdated",{policies:t})}getTrackingSnapshot(){return{events:[...this._tracking.events],styles:[...this._tracking.styles],limitations:[...this._tracking.limitations]}}clearTracking(e){if(!e||"all"===e)return this._tracking.events=[],this._tracking.styles=[],void(this._tracking.limitations=[]);"event"===e&&(this._tracking.events=[]),"style"===e&&(this._tracking.styles=[]),"limitation"===e&&(this._tracking.limitations=[])}getCapabilities(){return{styling:{classMap:!0,optionRenderer:!0,groupHeaderRenderer:!0,cssCustomProperties:!0,shadowParts:!0,globalStyleMirroring:!0},events:{emitted:["select","open","close","search","change","loadMore","remove","clear","error","diagnostic"],diagnosticEvent:!0},functionality:{multiSelect:!0,searchable:!0,infiniteScroll:!0,loadMore:!0,clearControl:!0,groupedItems:!0,serverSideSelection:!0,runtimeModeSwitchMitigation:Boolean(this._config.limitations?.autoMitigateRuntimeModeSwitch)},limitations:this.getKnownLimitations()}}_emitChange(){const e=this._getSelectedEntries(),t=e.map(({item:e})=>e),i=this._config.serverSide.getValueFromItem||(e=>e?.value??e),n=t.map(i),o=e.map(({index:e})=>e).filter(e=>e>=0);this._emit("change",{selectedItems:t,selectedValues:n,selectedIndices:o}),this._config.callbacks.onChange?.(t,n)}get optionRenderer(){return this._optionRenderer}set optionRenderer(e){this._optionRenderer!==e&&(this._invalidateGuardedMeasurements(),this._optionRenderer=e,this._setGlobalStylesMirroring(Boolean(e||this._classMap||this._groupHeaderRenderer)),this._track("style","optionRendererChanged",{enabled:Boolean(e)}),this._renderOptions())}setItems(e){this._invalidateGuardedMeasurements();const t=this._state.loadedItems.length;this._rebuildItemRegistry(e),this._state.groupedItems=this._groupItemsByProperty(e),this._state.searchQuery||this._isActivelyEditingSearchInput()||this._updateInputDisplay();const i=this._state.loadedItems.length;if(this._dataRequestCoordinator){const e=this._dataRequestCoordinator.getSnapshot().busy||this._acknowledgedProjectionPending;if(this._state.isSearching=!1,this._state.isBusy=e,this._state.preserveScrollPosition&&this._dropdown){const t=this._state.lastScrollPosition;this._renderOptions(),this._optionsContainer.scrollTop=t,this._requestLifecycleFrame(()=>{this._optionsContainer&&(this._optionsContainer.scrollTop=t)}),e||(this._state.preserveScrollPosition=!1)}else this._renderOptions();return}if(this._state.preserveScrollPosition&&this._dropdown){const e=this._state.lastScrollPosition;i>t&&(this._state.isBusy=!1),this._renderOptions(),this._dropdown.scrollTop=e,this._requestLifecycleFrame(()=>{this._dropdown&&(this._dropdown.scrollTop=e)}),i>t&&(this._state.preserveScrollPosition=!1)}else this._state.isBusy=!1,this._renderOptions()}_groupItemsByProperty(e){if(!e.some((e,t)=>null!==this._itemAdapter.getGroupKey?.(e,t)))return[];const t=new Map;return e.forEach((e,i)=>{const n=this._itemAdapter.getGroupKey?.(e,i),o=null==n?"Ungrouped":String(n),s=t.get(o);s?s.push(e):t.set(o,[e])}),Array.from(t.entries()).map(([e,t])=>({label:e,options:t}))}setGroupedItems(e){this._destroyGuardedVirtualizer(),this._rebuildItemRegistry(e.flatMap(e=>e.options)),this._state.groupedItems=e,this._renderOptions(),this._state.searchQuery||this._isActivelyEditingSearchInput()||this._updateInputDisplay()}getSelectedItems(){return this._ensureRegistryCurrent(),this._getSelectedEntries().map(e=>e.item)}get loadedItems(){return this._state.loadedItems}getSelectedValues(){return this.getSelectedItems().map(e=>this._getItemValue(e))}async setSelectedValues(e){if(this._config.serverSide.enabled&&this._config.serverSide.fetchSelectedItems)await this._loadSelectedItemsByValues(e);else{this._ensureRegistryCurrent();const t=this._itemRegistry.records.filter(t=>arrayIncludesValue(e,t.value)&&!this._isOptionSelectionBlocked(t.item));this._requestSelectionReplacement(t,"external-value-sync","setSelectedValues"),this._renderOptions(),this._updateInputDisplay(),this._emitChange()}}async _loadSelectedItemsByValues(e){if(!this._config.serverSide.fetchSelectedItems)return;this._setBusy(!0);const t=++this._asyncGeneration;try{const i=await this._config.serverSide.fetchSelectedItems(e);if(t!==this._asyncGeneration||!this.isConnected)return;const n=createItemRegistry(i,this._itemAdapter,{duplicateKeyPolicy:this._getDuplicateKeyPolicy()});this._requestSelectionReplacement(n.records,"external-value-sync","fetched selected items"),this._renderOptions(),this._updateInputDisplay(),this._emitChange(),this._config.scrollToSelected.enabled&&this._scrollToSelected()}catch(e){if(t!==this._asyncGeneration||!this.isConnected)return;this._handleError(e)}finally{t===this._asyncGeneration&&this.isConnected&&this._setBusy(!1)}}clear(){this._ensureRegistryCurrent(),this._dispatchSelection({type:"CLEAR_SELECTION_REQUEST",reason:"programmatic"},"clear"),this._renderOptions(),this._updateInputDisplay(),this._emitChange(),this._syncClearControlState()}clearSearch(){this._state.searchQuery="",this._config.searchable&&(this._input.value="",this._state.selectedIndices.size>0&&this._updateInputDisplay()),this._renderOptions(),this._syncClearControlState()}open(){this._handleOpen()}close(){this._handleClose()}updateConfig(e){this._invalidateGuardedMeasurements();const t=this._config.selection.mode,i=this._config.enabled,n=this._dataLoadingConfig,{dataLoading:o,callbacks:s,...r}=e,a={...r};let l;if(null!=s){const e=s;Object.prototype.hasOwnProperty.call(e,"onDataLoadingConfigError")&&(this._dataLoadingConfigErrorCallback=e.onDataLoadingConfigError),Object.prototype.hasOwnProperty.call(e,"onDataRequestCancel")&&(this._dataRequestCancelCallback=e.onDataRequestCancel),Object.prototype.hasOwnProperty.call(e,"onDataProjection")&&(this._dataProjectionCallback=e.onDataProjection);const t={...e};delete t.onDataLoadingConfigError,delete t.onDataRequestCancel,delete t.onDataProjection,a.callbacks=t}if(this._config=this._mergeConfig(this._config,a),void 0!==o){const e=null!==o&&"object"==typeof o?Object.getPrototypeOf(o):void 0,t=e===Object.prototype||null===e?{...this._dataLoadingConfig,...o}:o,i=validateDataLoadingConfig(t);if(i.valid)this._dataLoadingConfig=i.value,this._hasLastInvalidDataLoadingCandidate=!1,this._lastInvalidDataLoadingCandidate=void 0;else{const e=createInvalidDataLoadingCandidateSignature(t,i.issues);this._hasLastInvalidDataLoadingCandidate&&this._lastInvalidDataLoadingCandidate&&invalidDataLoadingSignaturesEqual(this._lastInvalidDataLoadingCandidate,e)||(this._hasLastInvalidDataLoadingCandidate=!0,this._lastInvalidDataLoadingCandidate=e,l={issues:i.issues})}}this._rebuildItemRegistry(),i!==this._config.enabled&&(this._input.disabled=!this._config.enabled,!this._config.enabled&&this._state.isOpen&&this._handleClose("disabled"),this._runEngineEffects(this._engine.dispatch({type:"DISABLED_CHANGED",disabled:!this._config.enabled}))),t!==this._config.selection.mode&&this._config.limitations?.autoMitigateRuntimeModeSwitch?(this.clear(),this._track("limitation","runtimeModeSwitchMitigated",{from:t,to:this._config.selection.mode})):t!==this._config.selection.mode&&this._track("limitation","runtimeModeSwitchDetected",{from:t,to:this._config.selection.mode}),this._input&&(this._input.readOnly=!this._config.searchable,this._syncComboboxAccessibility(),0===this._state.selectedIndices.size&&(this._input.placeholder=this._config.placeholder||"Select an option...")),this._clearControl&&this._clearControl.setAttribute("aria-label",this._config.clearControl.ariaLabel||"Clear selection and search"),this._clearControlIcon&&(this._config.clearControl.icon?this._clearControlIcon.textContent=this._config.clearControl.icon:this._clearControlIcon.innerHTML='<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 4L4 12M4 4L12 12" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>'),this._syncStyleConfigVariables(),this._syncListboxAccessibility(),this.isConnected?(this._syncDirectionConfig(),this._syncInputContainerMode(),this._syncMultiSelectDisplayConfig(),this._syncDropdownPlacement(),this._initializeObservers(),this._syncClearControlState(),this._isActivelyEditingSearchInput()||this._updateInputDisplay(),this._renderOptions()):(this._syncInputContainerMode(),this._syncMultiSelectDisplayConfig(),this._syncClearControlState(),this._isActivelyEditingSearchInput()||this._updateInputDisplay()),this._acknowledgedSearchMode=this._dataLoadingConfig.searchMode,"legacy"===this._dataLoadingConfig.protocol&&(this._acknowledgedDeferredStart=!1);const c=this._dataRequestCoordinator,d="acknowledged"===n.protocol&&"legacy"===this._dataLoadingConfig.protocol,h=n.protocol!==this._dataLoadingConfig.protocol||n.searchMode!==this._dataLoadingConfig.searchMode||n.paginationMode!==this._dataLoadingConfig.paginationMode;if(c&&d){if(this._acknowledgedReady&&!this._acknowledgedProjectionPending&&!this._acknowledgedProjectionSettling){const e=c.updateConfig(this._createCoordinatorConfig());"accepted"===e.status&&this._dispatchAcknowledgedActions(e.actions)}this._acknowledgedReady=!1,this._dispatchAcknowledgedActions(c.disconnect()),this._acknowledgedProjectionPending||this._acknowledgedProjectionSettling?this._clearAcknowledgedCoordinatorAfterProjection=!0:(this._dataRequestCoordinator=null,this._acknowledgedSearchMode=null,this._state.isBusy=!1,this._state.isSearching=!1,this._syncListboxAccessibility(),this._renderOptions())}else if(c&&"acknowledged"===this._dataLoadingConfig.protocol)if(this._clearAcknowledgedCoordinatorAfterProjection=!1,this._acknowledgedProjectionPending||this._acknowledgedProjectionSettling)this._acknowledgedConfigUpdatePending=!0,this._acknowledgedDeferredModeChange||(this._acknowledgedDeferredModeChange=h);else if(this._acknowledgedReady){const e=c.updateConfig(this._createCoordinatorConfig());if("accepted"===e.status){this._dispatchAcknowledgedActions(e.actions);const t=c.getSnapshot();this._state.isBusy=t.busy,this._state.isSearching="search"===t.activeRequest?.kind,this._syncListboxAccessibility(),e.actions.every(e=>"request"!==e.type)&&this._renderOptions()}}if(l){this._emit("dataLoadingConfigError",l);try{this._dataLoadingConfigErrorCallback?.(l)}catch(e){this._handleError(e)}}}startDataLoading(){const e=Boolean(this._dataRequestCoordinator&&this._acknowledgedProjectionPending);if("acknowledged"!==this._dataLoadingConfig.protocol&&!e)return;if("acknowledged"===this._dataLoadingConfig.protocol&&!this._ensureDataRequestCoordinator())return;if(!this.isConnected)return void(this._hasEverConnected||(this._acknowledgedDeferredStart=!0));if(this._acknowledgedReady)return;if(this._acknowledgedStartTask)return void(this._acknowledgedDeferredStart=!0);const t=this._startAcknowledgedDataLoading();this._acknowledgedStartTask=t,t.finally(()=>{this._acknowledgedStartTask===t&&(this._acknowledgedStartTask=null,this._acknowledgedDeferredStart&&this.isConnected&&(this._acknowledgedDeferredStart=!1,this.startDataLoading()))}).catch(e=>this._handleError(e))}getDataLoadingState(){const e=this._dataRequestCoordinator;if(!e){const e="remote"===this._dataLoadingConfig.searchMode||"hybrid"===this._dataLoadingConfig.searchMode,t="cursor"===this._dataLoadingConfig.paginationMode?{mode:"cursor",ordinal:1}:{mode:"page",page:e?this._dataLoadingConfig.firstPage:(this._config.infiniteScroll.initialPage??1)+1};return{status:"idle",connected:this.isConnected,busy:!1,projectionPending:!1,queryGeneration:0,activeRequest:null,hasMore:"acknowledged"===this._dataLoadingConfig.protocol&&!e&&(this._config.infiniteScroll.enabled||this._config.loadMore.enabled),nextEligiblePosition:t,error:null,resourceLimit:null}}const t=e.getSnapshot(),i=t.activeRequest?{...t.activeRequest,position:{...t.activeRequest.position}}:null;return{status:t.status,connected:t.connected,busy:t.busy||this._acknowledgedProjectionPending,projectionPending:this._acknowledgedProjectionPending,queryGeneration:t.queryGeneration,activeRequest:i,hasMore:t.hasMore,nextEligiblePosition:{...t.nextEligiblePosition},error:t.error?{...t.error}:null,resourceLimit:t.resourceLimit?{...t.resourceLimit}:null}}completeDataRequest(e){const t=this._dataRequestCoordinator;if(!t){const t=e;return null!==t&&"object"==typeof t&&"requestId"in t&&"string"==typeof t.requestId&&0!==t.requestId.length&&"queryGeneration"in t&&Number.isSafeInteger(t.queryGeneration)&&!(t.queryGeneration<0)&&"status"in t&&"string"==typeof t.status&&["succeeded","empty","exhausted","failed","cancelled"].includes(t.status)?"unknown-request":"invalid"}const i=e&&"object"==typeof e?e:null,n=t.getSnapshot().activeRequest,o=n&&i?.requestId===n.requestId&&i?.queryGeneration===n.queryGeneration?n:null,s=i?.status,r="succeeded"===s||"exhausted"===s||"empty"===s&&"next"===i?.advance,a=t.completeDataRequest(e);if("accepted"===a&&o)this._acknowledgedLastRequest=o,this._acknowledgedProjectionRequest=o,this._acknowledgedProjectionAttempt=0,this._acknowledgedProjectionCommitsPosition=r,this._projectAcknowledgedSnapshot(t.getSnapshot(),o,r);else if("resource-limit"===a){const e=t.getSnapshot().resourceLimit;this._emit("diagnostic",{timestamp:Date.now(),source:"event",name:"acknowledgedDataLoadingResourceLimit",detail:e})}return a}_createCoordinatorConfig(){return{dataLoading:{...this._dataLoadingConfig},infiniteScroll:{pageSize:this._config.infiniteScroll.pageSize,initialPage:this._config.infiniteScroll.initialPage}}}_ensureDataRequestCoordinator(){if(!this._dataRequestCoordinator){const e="remote"===this._dataLoadingConfig.searchMode||"hybrid"===this._dataLoadingConfig.searchMode;try{this._dataRequestCoordinator=new DataRequestCoordinator({config:this._createCoordinatorConfig(),initialQuery:this._state.searchQuery,initialItems:this._state.loadedItems,hasMore:!e&&(this._config.infiniteScroll.enabled||this._config.loadMore.enabled)})}catch(e){const t={issues:[{path:"dataLoading",code:"invalid-value",message:`Acknowledged data loading could not start: ${e instanceof Error?e.message:String(e)}`}]};this._emit("dataLoadingConfigError",t);try{this._dataLoadingConfigErrorCallback?.(t)}catch(e){this._handleError(e)}return null}}return this._acknowledgedSearchMode=this._dataLoadingConfig.searchMode,this._dataRequestCoordinator}async _startAcknowledgedDataLoading(){const e=this._dataRequestCoordinator,t=Boolean(e&&this._acknowledgedProjectionPending);if(!e||"acknowledged"!==this._dataLoadingConfig.protocol&&!t||!this.isConnected)return;if(this._acknowledgedReady)return;if(this._acknowledgedProjectionPending){const e=this._acknowledgedProjectionTask;if(e&&await e,!this.isConnected)return;if(this._acknowledgedProjectionPending&&await this._retryAcknowledgedProjection(),!this.isConnected||this._acknowledgedProjectionPending)return}if("acknowledged"!==this._dataLoadingConfig.protocol||!this._dataRequestCoordinator)return;null!==this._acknowledgedPendingSearchQuery&&(this._state.searchQuery=this._acknowledgedPendingSearchQuery,this._input.value=this._acknowledgedPendingSearchQuery,this._acknowledgedPendingSearchQuery=null);const i=e.updateConfig(this._createCoordinatorConfig());if("accepted"!==i.status)return void(this._acknowledgedReady=!1);this._acknowledgedConfigUpdatePending=!1,this._acknowledgedDeferredModeChange=!1,this._clearAcknowledgedCoordinatorAfterProjection=!1,this._acknowledgedReady=!0,this._initializeObservers();const n=i.actions;this._dispatchAcknowledgedActions(n);const o=e.connect(this._state.searchQuery);this._dispatchAcknowledgedActions(o),0===n.length&&0===o.length&&this._renderOptions();const s=this._renderCycleId;if(!await this._waitForRenderCycle(s))throw this._acknowledgedReady=!1,new Error("Acknowledged readiness render was superseded before completion")}_mergeConfig(e,t){const i={...e},n=Object.keys(t);for(let e=0;e<n.length;e++){const o=n[e];if(!Object.prototype.hasOwnProperty.call(t,o))continue;const s=t[o];if(void 0===s)continue;const r=i[o];void 0!==s&&(s&&"object"==typeof s&&!Array.isArray(s)?i[o]=this._mergeConfig(r&&"object"==typeof r?r:{},s):i[o]=s)}return i}_handleClearControlClick(){const e=!1!==this._config.clearControl.clearSelection,t=!1!==this._config.clearControl.clearSearch,i=this._state.selectedIndices.size>0,n=this._state.searchQuery.length>0;e&&i&&this.clear(),t&&n&&this.clearSearch(),this._emit("clear",{clearedSelection:e&&i,clearedSearch:t&&n}),this._config.callbacks.onClear?.({clearedSelection:e&&i,clearedSearch:t&&n}),this._applyFocusIntent("input","clear-control-complete")}_syncClearControlState(){if(!this._clearControl||!this._inputContainer||!this._arrowContainer)return;const e=!0===this._config.clearControl.enabled,t=this._state.selectedIndices.size>0,i=(this._acknowledgedPendingSearchQuery??this._state.searchQuery).length>0,n=!1!==this._config.clearControl.clearSelection,o=!1!==this._config.clearControl.clearSearch,s=n&&t||o&&i,r=!1!==this._config.clearControl.hideWhenEmpty,a=e&&(!r||s);this._inputContainer.classList.toggle("has-clear-control",a),this._arrowContainer.classList.toggle("with-clear-control",a),this._clearControl.hidden=!a,this._clearControl.disabled=!s,this._clearControl.setAttribute("aria-hidden",String(!a))}setError(e){this._hasError=!0,this._errorMessage=e,this._errorDescription&&(this._errorDescription.textContent=e),this._syncComboboxAccessibility(),this._announce(`Error: ${e}`)}clearError(){this._hasError=!1,this._errorMessage="",this._errorDescription&&(this._errorDescription.textContent=""),this._syncComboboxAccessibility()}setRequired(e){e?this._input.setAttribute("required",""):this._input.removeAttribute("required"),this._syncEngineSelectionConfig(),this._syncComboboxAccessibility()}validate(){return this._input.hasAttribute("required")&&0===this._state.selectedIndices.size?(this.setError("Selection is required"),!1):(this.clearError(),!0)}_deriveVirtualizationScope(e){const t=e.map(e=>this._itemRegistry.indexToKey.get(e)).filter(e=>void 0!==e);return{dataKeys:this._itemRegistry.records.map(e=>e.key),filteredKeys:t,registeredKeys:Array.from(this._engine.state.registeredKeys),windowKeys:this._renderPlan.intendedRenderKeys.slice(),mountedKeys:this._getMountedVirtualizationKeys(this._optionsContainer.children),selectedKeys:new Set(this._engine.state.selectedKeys),activeKey:this._engine.state.activeKey}}_getMountedVirtualizationKeys(e){return Array.from(e).filter(e=>e instanceof HTMLElement&&(e.hasAttribute("data-sm-selectable")||e.hasAttribute("data-selectable"))).map(e=>Number(e.getAttribute("data-sm-index")??e.getAttribute("data-index"))).filter(Number.isInteger).map(e=>this._itemRegistry.indexToKey.get(e)).filter(e=>void 0!==e)}_refreshMountedVirtualizationScope(){this._virtualizationScope={...this._virtualizationScope,mountedKeys:this._getMountedVirtualizationKeys(this._optionsContainer.children),registeredKeys:Array.from(this._engine.state.registeredKeys),selectedKeys:new Set(this._engine.state.selectedKeys),activeKey:this._engine.state.activeKey}}_appendMountedVirtualizationTargets(e){const t=this._getMountedVirtualizationKeys(e);this._virtualizationScope={...this._virtualizationScope,mountedKeys:[...new Set([...this._virtualizationScope.mountedKeys,...t])],registeredKeys:Array.from(this._engine.state.registeredKeys),selectedKeys:new Set(this._engine.state.selectedKeys),activeKey:this._engine.state.activeKey}}_createLegacyRenderPlan(e){const t=[...e],i=t.map(e=>this._itemRegistry.indexToKey.get(e)).filter(e=>void 0!==e),n=new Map;return i.forEach((e,t)=>n.set(e,t)),{mode:"legacy-full",filteredIndices:t,filteredKeys:i,intendedRenderKeys:i.slice(),filteredIndexByKey:n}}_createVirtualRenderPlan(e,t){const i=this._renderPlan.filteredKeys.slice(),n=computeWindowKeys(i,e,t);return{mode:"virtual-window",filteredIndices:n.map(e=>this._itemRegistry.keyToIndex.get(e)).filter(e=>void 0!==e),filteredKeys:i,intendedRenderKeys:n,filteredIndexByKey:new Map(this._renderPlan.filteredIndexByKey)}}_ensureGuardedVirtualizer(e){return null!==this._guardedVirtualizer&&(e.length!==this._guardedVirtualizerKeys.length||e.some((e,t)=>!Object.is(e,this._guardedVirtualizerKeys[t])))&&this._destroyGuardedVirtualizer(!0),this._guardedVirtualizer||(this._guardedVirtualizer=new Virtualizer(document.createElement("div"),e.length,e=>this._renderPlan.filteredKeys[e],{estimatedItemHeight:this._resolveGuardedEstimatedItemHeight(),buffer:0,measurementThreshold:0}),this._guardedVirtualScrollTop=this._optionsContainer.scrollTop,this._guardedVirtualViewportHeight=this._resolveGuardedViewportHeight(),this._optionsContainer.addEventListener("scroll",this._onGuardedVirtualScroll,{passive:!0}),this._guardedScrollListenerAttached=!0),this._guardedVirtualizerKeys=[...e],this._guardedVirtualizer}_resolveGuardedEstimatedItemHeight(){const e=this._config.estimatedItemHeight;if("number"==typeof e&&Number.isFinite(e)&&e>0)return e;const t=this._optionsContainer.querySelector('[part="option"]'),i=t?.getBoundingClientRect().height||t?.offsetHeight;return"number"==typeof i&&Number.isFinite(i)&&i>0?i:48}_resolveGuardedViewportHeight(){return[this._optionsContainer.clientHeight,this._optionsContainer.getBoundingClientRect().height].find(e=>Number.isFinite(e)&&e>0)??0}_clampGuardedScrollPosition(e,t){if(!this._guardedVirtualizer)return 0;const i=this._guardedVirtualizer.cumulativeOffset(e),n=Math.max(0,i-t),o=Math.min(Math.max(0,this._guardedVirtualScrollTop),n);return this._guardedVirtualScrollTop=o,this._optionsContainer.scrollTop!==o&&(this._optionsContainer.scrollTop=o),o}_createGuardedSpacer(e,t){const i=document.createElement("div");return i.setAttribute("data-virtual-spacer",e),i.setAttribute("aria-hidden","true"),i.setAttribute("role","presentation"),i.style.height=`${Number.isFinite(t)?Math.max(0,t):0}px`,i.style.minHeight="0",i.style.flex="0 0 auto",i.style.pointerEvents="none",i}_appendGuardedTopSpacer(){const e=this._guardedVirtualizer,t=this._guardedVirtualWindow;e&&t&&this._optionsContainer.appendChild(this._createGuardedSpacer("top",e.cumulativeOffset(t.startIndex)))}_appendGuardedBottomSpacer(){const e=this._guardedVirtualizer,t=this._guardedVirtualWindow;if(!e||!t)return;const i=e.cumulativeOffset(this._renderPlan.filteredKeys.length),n=e.cumulativeOffset(t.endIndex);this._optionsContainer.appendChild(this._createGuardedSpacer("bottom",Math.max(0,i-n)))}_resolveGuardedOverscan(){return 2}_applyGuardedWindowUpdate(e,t=0){if(!this._guardedVirtualizer)return!1;this._guardedVirtualScrollTop=e.scrollTop,this._guardedVirtualViewportHeight=e.viewportHeight;const i=this._renderPlan.filteredKeys.length,n={startIndex:Math.max(0,e.window.startIndex-t),endIndex:Math.min(i,e.window.endIndex+1+t)},o=this._guardedVirtualWindow?.startIndex!==n.startIndex||this._guardedVirtualWindow?.endIndex!==n.endIndex;return this._guardedVirtualWindow=n,o}_scheduleGuardedVirtualWindowUpdate(){this._guardedVirtualizer&&null===this._guardedVirtualWindowRafId&&(this._guardedVirtualWindowRafId=this._requestLifecycleFrame(()=>{this._guardedVirtualWindowRafId=null;const e=this._guardedVirtualizer;if(!e)return;const t=e.updateWindow(this._optionsContainer.scrollTop,this._resolveGuardedViewportHeight());this._guardedVirtualOverscan=this._resolveGuardedOverscan(),t&&this._applyGuardedWindowUpdate(t,this._guardedVirtualOverscan)&&this._renderOptions()}))}_cancelGuardedVirtualWindowUpdate(){null!==this._guardedVirtualWindowRafId&&(cancelAnimationFrame(this._guardedVirtualWindowRafId),this._lifecycleRafs.delete(this._guardedVirtualWindowRafId),this._guardedVirtualWindowRafId=null)}_applyGuardedScrollResult(e){if(!e||!this._guardedVirtualizer)return!1;this._guardedVirtualScrollTop=e.scrollTop,this._optionsContainer.scrollTop=e.scrollTop;const t=this._guardedVirtualizer.updateWindow(this._guardedVirtualScrollTop,this._guardedVirtualViewportHeight);return!!t&&(this._guardedVirtualWindow={startIndex:t.window.startIndex,endIndex:t.window.endIndex+1},this._guardedVirtualOverscan=0,!0)}_enableAcknowledgedDataLoadingForTest(e,t={}){if(this._dataRequestCoordinator)throw new Error("Acknowledged data loading is already enabled for this test instance");const i=e.dataLoading;this._dataLoadingConfig={protocol:i?.protocol??"acknowledged",searchMode:i?.searchMode??"local",paginationMode:i?.paginationMode??"page",firstPage:i?.firstPage??1,...void 0===i?.fetchLimit?{}:{fetchLimit:i.fetchLimit}},this._acknowledgedSearchMode=e.dataLoading?.searchMode??"local",this._dataRequestCoordinator=new DataRequestCoordinator({config:e,initialQuery:this._state.searchQuery,initialItems:this._state.loadedItems,hasMore:t.hasMore}),this._acknowledgedReady=!1,this.isConnected&&this._initializeObservers()}async _setAcknowledgedDataLoadingReadyForTest(){if(!this._dataRequestCoordinator)throw new Error("Enable acknowledged data loading before readiness");if(!this.isConnected)throw new Error("Acknowledged readiness requires a connected test element");if(this._acknowledgedReady)return;if(this._acknowledgedProjectionPending){const e=this._acknowledgedProjectionTask;if(e&&await e,this._acknowledgedProjectionPending&&await this._retryAcknowledgedProjectionForTest(),this._acknowledgedProjectionPending)throw new Error("Acknowledged readiness cannot open while snapshot projection is pending")}null!==this._acknowledgedPendingSearchQuery&&(this._state.searchQuery=this._acknowledgedPendingSearchQuery,this._input.value=this._acknowledgedPendingSearchQuery,this._acknowledgedPendingSearchQuery=null),this._acknowledgedReady=!0,this._initializeObservers();const e=this._dataRequestCoordinator.connect(this._state.searchQuery);this._dispatchAcknowledgedActions(e),0===e.length&&this._renderOptions();const t=this._renderCycleId;if(!await this._waitForRenderCycle(t))throw this._acknowledgedReady=!1,new Error("Acknowledged readiness render was superseded before completion")}_dispatchAcknowledgedActions(e){for(const t of e){if("cancel"===t.type){this._cancelBusyPresentation(),this._dispatchAcknowledgedEvent("dataRequestCancel",t.notification);try{this._dataRequestCancelCallback?.(t.notification)}catch(e){this._handleError(e)}continue}const e=t.request,i=this._dataRequestCoordinator;if(i&&this._acknowledgedReady&&("loadMore"===e.kind?(this._state.lastScrollPosition=this._optionsContainer.scrollTop,this._acknowledgedProjectionScrollTop=this._state.lastScrollPosition,this._state.preserveScrollPosition=!0,this._state.isSearching=!1):(this._acknowledgedProjectionScrollTop=0,this._state.preserveScrollPosition=!1,this._state.isSearching=!0),this._beginBusyPresentation(),this._state.isBusy=!0,this._acknowledgedLastRequest=e,this._syncListboxAccessibility(),this._renderOptions(),"loadMore"===e.kind&&(this._optionsContainer.scrollTop=this._state.lastScrollPosition),i.markNotificationsDispatched(e.requestId)))if("search"===e.kind){const t={query:e.query,results:[],count:0,request:e};this._dispatchAcknowledgedEvent("search",t);try{const t=this._config.callbacks.onSearch;t?.(e.query,e)}catch(e){this._handleError(e)}}else{const t="page"===e.position.mode?e.position.page:e.position.ordinal,i={page:t,items:[],request:e};this._dispatchAcknowledgedEvent("loadMore",i);try{const i=this._config.callbacks.onLoadMore;i?.(t,e)}catch(e){this._handleError(e)}}}}_dispatchAcknowledgedEvent(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0})),this._track("event",e,t)}async _completeDataRequestForTest(e){const t=this.completeDataRequest(e);return"accepted"!==t||await this._acknowledgedProjectionTask,t}_failNextAcknowledgedProjectionForTest(e="before-publish"){this._acknowledgedProjectionFailureStageForTest=e}_retryAcknowledgedProjectionForTest(){return this._retryAcknowledgedProjection()}_retryAcknowledgedProjection(){return this._dataRequestCoordinator&&this._acknowledgedProjectionPending?this._projectAcknowledgedSnapshot(this._dataRequestCoordinator.getSnapshot(),this._acknowledgedProjectionRequest??this._acknowledgedLastRequest,this._acknowledgedProjectionCommitsPosition):Promise.resolve()}_projectAcknowledgedSnapshot(e,t,i){if(this._acknowledgedProjectionRunning)return this._acknowledgedProjectionTask??Promise.resolve();this._acknowledgedProjectionRequest=t??this._acknowledgedProjectionRequest,this._acknowledgedProjectionAttempt+=1,this._acknowledgedProjectionPending=!0;const n=Array.from(e.items);let o,s;try{if(o=createItemRegistry(n,this._itemAdapter,{duplicateKeyPolicy:this._getDuplicateKeyPolicy()}),s=this._groupItemsByProperty(n),"before-publish"===this._acknowledgedProjectionFailureStageForTest)throw this._acknowledgedProjectionFailureStageForTest=null,new Error("Injected acknowledged projection failure before publication")}catch(i){return this._syncListboxAccessibility(),this._recordAcknowledgedProjectionFailure(e,t,i),Promise.resolve()}this._acknowledgedProjectionRunning=!0;const r=this._applyAcknowledgedSnapshot(e,t,i,n,o,s).finally(()=>{this._acknowledgedProjectionTask===r&&(this._acknowledgedProjectionRunning=!1,this._acknowledgedProjectionTask=null)});return this._acknowledgedProjectionTask=r,r}async _applyAcknowledgedSnapshot(e,t,i,n,o,s){let r=!1;try{if(this._rebuildItemRegistry(n,o),this._state.groupedItems=s,i&&t&&(this._state.currentPage=e.lastCommittedPage??("page"===t.position.mode?t.position.page:t.position.ordinal)),this._state.isSearching=!1,this._state.isBusy=!0,this._state.lastScrollPosition=this._acknowledgedProjectionScrollTop,this._state.preserveScrollPosition="loadMore"===t?.kind,r=!0,"after-publish"===this._acknowledgedProjectionFailureStageForTest)throw this._acknowledgedProjectionFailureStageForTest=null,new Error("Injected acknowledged projection failure after publication");this._state.searchQuery||null!==this._acknowledgedPendingSearchQuery||this._isActivelyEditingSearchInput()||this._updateInputDisplay(),this._syncListboxAccessibility(),this._renderOptions();const a=this._renderCycleId;if(!await this._waitForRenderCycle(a))throw new Error("Acknowledged snapshot render was superseded before completion");this._state.isBusy=e.busy,e.busy||(this._syncBusyPresentation(),this._busyPresentationVisible||this._optionsContainer.querySelector(".busy-bucket")?.remove(),this._shouldRenderLoadMoreTrigger()&&this._addLoadMoreTrigger()),this._optionsContainer.scrollTop=this._acknowledgedProjectionScrollTop,this._syncListboxAccessibility(),this._syncRenderedOptionAccessibility(),this._syncLegacyActiveAria(),this._state.preserveScrollPosition=!1,this._acknowledgedProjectionPending=!1,this._acknowledgedProjectionDiagnostic=null,this._acknowledgedProjectionSettling=!0;try{this._dispatchDataProjectionNotification({requestId:this._acknowledgedProjectionRequest?.requestId??t?.requestId??"unknown",queryGeneration:this._acknowledgedProjectionRequest?.queryGeneration??e.queryGeneration,attempt:this._acknowledgedProjectionAttempt,status:"complete"})}finally{this._acknowledgedProjectionSettling=!1}this._clearAcknowledgedCoordinatorAfterProjection?(this._dataRequestCoordinator=null,this._acknowledgedSearchMode=null,this._clearAcknowledgedCoordinatorAfterProjection=!1,this._acknowledgedProjectionRequest=null):this._acknowledgedProjectionRequest=null,this._finishAcknowledgedProjectionSettlement()}catch(i){r&&(this.isConnected&&(this._state.isBusy=!0),this._state.isSearching=!1,this._syncListboxAccessibility()),this._acknowledgedProjectionPending=!0,this._recordAcknowledgedProjectionFailure(e,t,i)}}_recordAcknowledgedProjectionFailure(e,t,i){const n=i instanceof Error?i.message:String(i),o={requestId:this._acknowledgedProjectionRequest?.requestId??t?.requestId??"unknown",queryGeneration:this._acknowledgedProjectionRequest?.queryGeneration??e.queryGeneration,message:n};this._acknowledgedProjectionDiagnostic=o,this._emit("diagnostic",{timestamp:Date.now(),source:"event",name:"acknowledgedProjectionFailed",detail:o}),"unknown"!==o.requestId&&this._dispatchDataProjectionNotification({requestId:o.requestId,queryGeneration:o.queryGeneration,attempt:this._acknowledgedProjectionAttempt,status:"failed",error:{message:n}})}_dispatchDataProjectionNotification(e){this._dispatchAcknowledgedEvent("dataProjection",e);try{this._dataProjectionCallback?.(e)}catch(e){this._handleError(e)}}_dispatchPendingAcknowledgedSearchIntent(){const e=this._acknowledgedPendingSearchQuery;null!==e&&this._acknowledgedReady&&this.isConnected&&(this._acknowledgedPendingSearchQuery=null,this._handleSearch(e))}_finishAcknowledgedProjectionSettlement(){const e=this._dataRequestCoordinator,t=this._acknowledgedPendingSearchQuery;if("acknowledged"!==this._dataLoadingConfig.protocol||!e)return this._acknowledgedConfigUpdatePending=!1,this._acknowledgedDeferredModeChange=!1,void("legacy"===this._dataLoadingConfig.protocol&&null!==t&&this.isConnected?(this._acknowledgedPendingSearchQuery=null,this._handleSearch(t)):this._dispatchPendingAcknowledgedSearchIntent());if(this.isConnected&&this._acknowledgedReady){if(this._acknowledgedConfigUpdatePending){const i=this._acknowledgedDeferredModeChange&&null!==t;i&&this._dispatchAcknowledgedActions(e.disconnect());const n=e.updateConfig(this._createCoordinatorConfig());if("accepted"!==n.status)return void(this._acknowledgedReady=!1);if(this._acknowledgedConfigUpdatePending=!1,this._acknowledgedDeferredModeChange=!1,i&&null!==t)return this._acknowledgedPendingSearchQuery=null,this._state.searchQuery=t,this._input.value=t,this._dispatchAcknowledgedActions(e.setQuery(t)),this._dispatchAcknowledgedActions(e.connect(t)),this._syncListboxAccessibility(),void this._handleSearch(t);this._dispatchAcknowledgedActions(n.actions);const o=e.getSnapshot();this._state.isBusy=o.busy,this._state.isSearching="search"===o.activeRequest?.kind,this._syncListboxAccessibility()}this._dispatchPendingAcknowledgedSearchIntent()}}_updateGuardedVirtualWindow(e,t){this._guardedVirtualizationRequested=!0;const i=this._ensureGuardedVirtualizer(this._renderPlan.filteredKeys);this._guardedVirtualScrollTop=e,this._guardedVirtualViewportHeight=t;const n=i.updateWindow(e,t);return!!n&&(this._guardedVirtualOverscan=0,this._applyGuardedWindowUpdate(n,this._guardedVirtualOverscan),this._optionsContainer.scrollTop=n.scrollTop,!0)}_destroyGuardedVirtualizer(e=!1){this._cancelGuardedVirtualWindowUpdate(),this._guardedMeasurementGeneration+=1,this._guardedScrollListenerAttached&&(this._optionsContainer.removeEventListener("scroll",this._onGuardedVirtualScroll),this._guardedScrollListenerAttached=!1),this._guardedVirtualizer?.destroy(),this._guardedVirtualizer=null,this._teardownGuardedOptionResizeObserver(),e||(this._guardedVirtualizationRequested=!1),this._guardedVirtualizerKeys=[],this._guardedVirtualWindow=null,this._guardedVirtualScrollTop=0,this._guardedVirtualViewportHeight=0,this._guardedVirtualOverscan=0}_invalidateGuardedMeasurements(){this._guardedVirtualizer&&this._destroyGuardedVirtualizer(!0)}_createGuardedOptionResizeObserver(e){"undefined"!=typeof ResizeObserver&&(this._guardedOptionResizeObserver=new ResizeObserver(t=>{if(e!==this._guardedMeasurementGeneration||!this._guardedVirtualizer||!this._guardedVirtualizationRequested||!this.isConnected)return;const i=this._guardedVirtualizer,n=this._optionsContainer.scrollTop,o=this._resolveGuardedViewportHeight(),s=this._captureGuardedScrollAnchor(i,n,o);let r=!1;for(const n of t){const t=n.target;if(!(t instanceof HTMLElement&&this._guardedObservedOptions.has(t)))continue;if(!t.isConnected||!this._optionsContainer.contains(t))continue;const o=this._guardedOptionMeasurements.get(t);if(!o||o.generation!==e)continue;const s=Number(t.getAttribute("data-index"));if(!Number.isInteger(s)||!Object.is(this._itemRegistry.indexToKey.get(s),o.key))continue;const a=this._renderPlan.filteredIndexByKey.get(o.key);if(void 0===a||a!==o.index)continue;const l=n.borderBoxSize?.[0]?.blockSize,c="number"==typeof l?l:n.contentRect.height;!Number.isFinite(c)||c<=0||(r=i.measureItem(o.index,c)||r)}if(!r)return;if(s){const e=this._renderPlan.filteredIndexByKey.get(s.key);if(void 0!==e){const t=Math.max(0,i.cumulativeOffset(e)+s.offset);this._guardedVirtualScrollTop=t,this._optionsContainer.scrollTop=t}}const a=i.updateWindow(this._optionsContainer.scrollTop,o);a&&this._applyGuardedWindowUpdate(a,this._guardedVirtualOverscan),this._renderOptions()}))}_captureGuardedScrollAnchor(e,t,i){const n=this._optionsContainer.getBoundingClientRect().top+this._optionsContainer.clientTop,o=n+i,s=Array.from(this._guardedObservedOptions).map(e=>({option:e,rect:e.getBoundingClientRect()})).filter(({rect:e})=>e.height>0&&e.bottom>n&&e.top<o).sort((e,t)=>e.rect.top-t.rect.top)[0],r=s?this._guardedOptionMeasurements.get(s.option):void 0;if(r&&r.generation===this._guardedMeasurementGeneration)return{key:r.key,offset:t-e.cumulativeOffset(r.index)};if(0===this._renderPlan.filteredKeys.length)return null;const a=e.computeWindow(t,0).startIndex,l=this._renderPlan.filteredKeys[a];return void 0===l?null:{key:l,offset:t-e.cumulativeOffset(a)}}_syncGuardedOptionResizeTargets(){if(!this._guardedVirtualizer||!this._guardedVirtualizationRequested||!this.isConnected)return;const e=[];for(const t of Array.from(this._optionsContainer.children)){if(!(t instanceof HTMLElement&&t.hasAttribute("data-index")))continue;const i=Number(t.getAttribute("data-index"));if(!Number.isInteger(i))continue;const n=this._itemRegistry.indexToKey.get(i),o=void 0===n?void 0:this._renderPlan.filteredIndexByKey.get(n);void 0!==n&&void 0!==o&&e.push({option:t,key:n,index:o})}e.some(({option:e})=>this._guardedObserverSeenOptions.has(e))&&this._guardedOptionResizeObserver&&(this._guardedMeasurementGeneration+=1,this._teardownGuardedOptionResizeObserver()),this._guardedOptionResizeObserver||this._createGuardedOptionResizeObserver(this._guardedMeasurementGeneration);const t=this._guardedOptionResizeObserver;if(!t)return;const i=new Set;for(const{option:n,key:o,index:s}of e)i.add(n),this._guardedOptionMeasurements.set(n,{key:o,index:s,generation:this._guardedMeasurementGeneration}),this._guardedObservedOptions.has(n)||(t.observe(n),this._guardedObserverSeenOptions.add(n));for(const e of this._guardedObservedOptions)i.has(e)||t.unobserve(e);this._guardedObservedOptions=i}_teardownGuardedOptionResizeObserver(){for(const e of this._guardedObservedOptions)this._guardedOptionResizeObserver?.unobserve(e);this._guardedObservedOptions.clear(),this._guardedObserverSeenOptions=new WeakSet,this._guardedOptionResizeObserver?.disconnect(),this._guardedOptionResizeObserver=null,this._guardedOptionMeasurements=new WeakMap}_materializeGuardedVirtualKey(e){if(!this._guardedVirtualizer)return!1;if(void 0===this._renderPlan.filteredIndexByKey.get(e))return!1;this._ensureGuardedVirtualizer(this._renderPlan.filteredKeys);const t=this._guardedVirtualizer.scrollToKey(e,e=>this._renderPlan.filteredIndexByKey.get(e));return!!this._applyGuardedScrollResult(t)&&(this._renderOptions(),!0)}_refreshVirtualizationScope(e){this._virtualizationScope=this._deriveVirtualizationScope(e)}_clearBusyPresentationHideTimer(){null!==this._busyPresentationHideTimer&&(window.clearTimeout(this._busyPresentationHideTimer),this._lifecycleTimers.delete(this._busyPresentationHideTimer),this._busyPresentationHideTimer=null)}_beginBusyPresentation(){this._busyPresentationGeneration+=1,this._clearBusyPresentationHideTimer(),this._busyPresentationVisible=this._config.busyBucket.enabled,this._busyPresentationStartedAt=this._busyBucket?.isConnected?Date.now():null}_syncBusyPresentation(){if(!this._config.busyBucket.enabled)return void this._cancelBusyPresentation();if(this._state.isBusy)return void(this._busyPresentationVisible&&null===this._busyPresentationHideTimer||this._beginBusyPresentation());if(!this._busyPresentationVisible||null!==this._busyPresentationHideTimer)return;const e=Number(this._config.busyBucket.minDisplayTime??0),t=Number.isFinite(e)?Math.max(0,e):0;null===this._busyPresentationStartedAt&&(this._busyPresentationStartedAt=Date.now());const i=this._busyPresentationStartedAt,n=t-Math.max(0,Date.now()-i);if(n<=0)return this._busyPresentationGeneration+=1,this._busyPresentationVisible=!1,void(this._busyPresentationStartedAt=null);const o=this._busyPresentationGeneration;this._busyPresentationHideTimer=this._setLifecycleTimeout(()=>{o!==this._busyPresentationGeneration||this._state.isBusy||(this._busyPresentationHideTimer=null,this._busyPresentationVisible=!1,this._busyPresentationStartedAt=null,this._busyBucket=void 0,this._clearBusyBucketContentObserver(),this._renderOptions())},n)}_clearBusyBucketContentObserver(){this._busyBucketContentObserver?.disconnect(),this._busyBucketContentObserver=void 0}_cancelBusyPresentation(){this._busyPresentationGeneration+=1,this._clearBusyPresentationHideTimer(),this._busyPresentationVisible=!1,this._busyPresentationStartedAt=null,this._clearBusyBucketContentObserver(),this._busyBucket=void 0,this._optionsContainer?.querySelector(".busy-bucket")?.remove()}_hasAccessibleBusyContent(e){return e.some(e=>e.nodeType===Node.TEXT_NODE?Boolean(e.textContent?.trim()):e instanceof Element&&(!e.hasAttribute("hidden")&&!e.hasAttribute("inert")&&"true"!==e.getAttribute("aria-hidden")?.toLowerCase()&&(!!["aria-label","aria-labelledby","alt","title"].some(t=>Boolean(e.getAttribute(t)?.trim()))||this._hasAccessibleBusyContent(Array.from(e.childNodes)))))}_syncBusyBucketContent(e){if(e!==this._busyBucket)return;const t=e.querySelector('slot[name="loading-content"]'),i=e.querySelector('slot[name="loading-icon"]');if(!t||!i)return;const n=t.assignedNodes({flatten:!0}),o=i.assignedNodes({flatten:!0}),s=n.length>0,r=this._hasAccessibleBusyContent(n),a=e.querySelector(".busy-icon");a?.toggleAttribute("hidden",!1===this._config.busyBucket.showSpinner&&0===o.length);const l=e.querySelector(".busy-content");l?.toggleAttribute("hidden",!s),e.classList.toggle("busy-bucket--replace","replace"===this._config.busyBucket.contentMode&&r);const c=e.querySelector(".busy-message");if(c){const e="replace"===this._config.busyBucket.contentMode&&!r;c.toggleAttribute("hidden",!1===this._config.busyBucket.showMessage&&!e),e&&!c.textContent?.trim()&&(c.textContent=this._config.busyBucket.message||"Loading...")}}_createBusyBucket(){const e=document.createElement("div");e.setAttribute("part","loading"),e.className="busy-bucket",this._busyBucket=e;const t=document.createElement("div");t.className="busy-icon",t.setAttribute("part","loading-icon"),t.setAttribute("aria-hidden","true");const i=document.createElement("slot");if(i.name="loading-icon",!1!==this._config.busyBucket.showSpinner){const e=document.createElement("div");e.className="spinner",e.setAttribute("part","loading-spinner"),e.setAttribute("aria-hidden","true"),i.appendChild(e)}t.appendChild(i),e.appendChild(t);const n=document.createElement("div");n.className="busy-message",n.setAttribute("part","loading-message"),n.textContent=this._config.busyBucket.message??"Loading...",n.toggleAttribute("hidden",!1===this._config.busyBucket.showMessage),e.appendChild(n);const o=document.createElement("div");o.className="busy-content",o.setAttribute("part","loading-content");const s=document.createElement("slot");s.name="loading-content",o.appendChild(s),e.appendChild(o);const r=()=>this._syncBusyBucketContent(e);return s.addEventListener("slotchange",r),i.addEventListener("slotchange",r),r(),"undefined"!=typeof MutationObserver&&(this._clearBusyBucketContentObserver(),this._busyBucketContentObserver=new MutationObserver(r),this._busyBucketContentObserver.observe(this,{childList:!0,subtree:!0,characterData:!0})),e}_appendBusyBucket(){const e=this._createBusyBucket();return this._optionsContainer.appendChild(e),null===this._busyPresentationStartedAt&&(this._busyPresentationStartedAt=Date.now()),this._syncBusyBucketContent(e),e}_renderOptions(){this._syncBusyPresentation(),this._clearBusyBucketContentObserver(),this._busyBucket=void 0,this._ensureRegistryCurrent();const e=this._optionsContainer.scrollTop;this._renderCycleId+=1;const t=this._renderCycleId;this._resolvePendingRenderCycles(!1,t),this._guardedVirtualizer&&(this._guardedVirtualScrollTop=this._optionsContainer.scrollTop),this._loadMoreTrigger&&this._intersectionObserver&&this._intersectionObserver.unobserve(this._loadMoreTrigger),this._dataRequestCoordinator&&(this._loadMoreTrigger=void 0),this._unobserveGuardedOptionResizeTargets(),this._optionsContainer.innerHTML="";let i=[],n=null;if(Array.from(this._dropdown.children).forEach(e=>{e!==this._optionsContainer&&this._dropdown.removeChild(e)}),this._state.isOpen&&"none"===this._dropdown.style.display&&(this._dropdown.style.display="block"),this._state.isSearching){this._registerShadowItems([]),this._renderPlan=this._createLegacyRenderPlan([]),this._refreshVirtualizationScope(i),this._syncLegacyActiveAria();const e=document.createElement("div");return e.className="searching-state",e.setAttribute("part","loading"),e.textContent="Searching...",this._optionsContainer.appendChild(e),void this._resolveRenderCycle(t,!0)}const o=this._config.serverSide.getValueFromItem||(e=>e?.value??e),s=this._config.serverSide.getLabelFromItem||(e=>e?.label??String(e)),r="remote"===this._acknowledgedSearchMode?"":this._state.searchQuery.toLowerCase();if(null!==this._guardedMeasurementQuery&&this._guardedMeasurementQuery!==r&&this._invalidateGuardedMeasurements(),this._guardedMeasurementQuery=r,this._state.groupedItems.length>0&&!r)this._destroyGuardedVirtualizer(),this._renderPlan=this._createLegacyRenderPlan(this._itemRegistry.records.map(e=>e.index)),i=this._renderPlan.filteredIndices,this._registerShadowItems(i),this._refreshVirtualizationScope(i),this._state.groupedItems.forEach((e,t)=>{let i;this.groupHeaderRenderer?(i=this.groupHeaderRenderer(e,t),i instanceof HTMLElement||(i=document.createElement("div"),i.textContent=String(e.label))):(i=document.createElement("div"),i.textContent=e.label),i.classList.add("group-header"),this._config.styles.classNames?.groupHeader&&i.classList.add(...this._config.styles.classNames.groupHeader.split(" ").filter(Boolean)),i.hasAttribute("role")||i.setAttribute("role","presentation"),i.setAttribute("part","group-header"),this._optionsContainer.appendChild(i),e.options.forEach(e=>{const t=this._state.loadedItems.indexOf(e);-1!==t&&this._renderSingleOption(e,t,o,s)})});else{const a=[];if(this._state.loadedItems.forEach((e,t)=>{if(r)try{if(!String(s(e)).toLowerCase().includes(r))return}catch(e){return}a.push(t)}),this._renderPlan=this._createLegacyRenderPlan(a),i=this._renderPlan.filteredIndices,this._registerShadowItems(i),this._guardedVirtualizationRequested&&!this._guardedVirtualizer&&(this._ensureGuardedVirtualizer(this._renderPlan.filteredKeys),this._guardedVirtualViewportHeight=this._resolveGuardedViewportHeight(),this._guardedVirtualScrollTop=e),this._guardedVirtualizer){const e=this._ensureGuardedVirtualizer(this._renderPlan.filteredKeys),t=this._resolveGuardedViewportHeight();t>0&&(this._guardedVirtualViewportHeight=t);const i=this._clampGuardedScrollPosition(this._renderPlan.filteredKeys.length,this._guardedVirtualViewportHeight);n=i;const o=e.updateWindow(i,this._guardedVirtualViewportHeight);o?this._applyGuardedWindowUpdate(o,this._guardedVirtualOverscan):this._guardedVirtualWindow=null}this._guardedVirtualWindow&&(this._renderPlan=this._createVirtualRenderPlan(this._guardedVirtualWindow.startIndex,this._guardedVirtualWindow.endIndex));const l=this._renderPlan.filteredIndices;if(this._refreshVirtualizationScope(i),this._appendGuardedTopSpacer(),0!==l.length||this._state.isBusy){if(!this._guardedVirtualizer&&!1!==this._config.virtualize&&0===this._state.groupedItems.length&&l.length>300){const e=80;let i=0,n=0;if(this._state.selectedIndices.size>0&&this._config.scrollToSelected.enabled){const e=Array.from(this._state.selectedIndices).filter(e=>e>=0).sort((e,t)=>e-t),t="first"===this._config.scrollToSelected.multiSelectTarget?e[0]:e[e.length-1],i=l.indexOf(t);-1!==i&&(n=i+20)}const r=()=>{if(t!==this._renderCycleId)return void this._resolveRenderCycle(t,!1);const a=document.createDocumentFragment(),c=Math.min(Math.max(i+e,n),l.length);for(n=0;i<c;i+=1){const e=l[i],t=this._state.loadedItems[e];this._renderSingleOption(t,e,o,s,a)}const d=Array.from(a.children),h=this._optionsContainer.querySelector(".busy-bucket");if(h?this._optionsContainer.insertBefore(a,h):this._optionsContainer.appendChild(a),this._appendMountedVirtualizationTargets(d),this._syncRenderedOptionAccessibility(),this._syncLegacyActiveAria(),i<l.length)this._busyPresentationVisible&&this._config.busyBucket.enabled&&!this._optionsContainer.querySelector(".busy-bucket")&&this._appendBusyBucket(),this._requestLifecycleFrame(r);else{if(t!==this._renderCycleId)return void this._resolveRenderCycle(t,!1);!this._state.isBusy&&this._shouldRenderLoadMoreTrigger()&&this._addLoadMoreTrigger(),this._finalizePerfMarks(),this._resolveRenderCycle(t,!0)}};return void r()}l.forEach(e=>{const t=this._state.loadedItems[e];this._renderSingleOption(t,e,o,s)})}else{const e=document.createElement("div");e.setAttribute("part","no-results"),e.className="empty-state",e.textContent=r?`No results found for "${this._state.searchQuery}"`:"No options available",this._optionsContainer.appendChild(e)}this._appendGuardedBottomSpacer()}this._refreshMountedVirtualizationScope(),this._busyPresentationVisible&&this._config.busyBucket.enabled&&this._appendBusyBucket(),this._dataRequestCoordinator&&this._state.isBusy||!this._shouldRenderLoadMoreTrigger()||this._addLoadMoreTrigger(),null!==n&&(this._optionsContainer.scrollTop=n),this._syncRenderedOptionAccessibility(),this._syncLegacyActiveAria(),this._syncGuardedOptionResizeTargets(),this._finalizePerfMarks(),this._resolveRenderCycle(t,!0)}_waitForRenderCycle(e){return e<this._renderCycleId?Promise.resolve(!1):e<=this._completedRenderCycleId?Promise.resolve(!0):new Promise(t=>{this._renderCycleWaiters.set(e,t);const i=window.setTimeout(()=>this._resolveRenderCycle(e,!1),12e4);this._renderCycleWaiterTimeouts.set(e,i)})}_resolveRenderCycle(e,t){t&&(this._completedRenderCycleId=Math.max(this._completedRenderCycleId,e));const i=this._renderCycleWaiters.get(e),n=this._renderCycleWaiterTimeouts.get(e);void 0!==n&&window.clearTimeout(n),this._renderCycleWaiterTimeouts.delete(e),i&&(this._renderCycleWaiters.delete(e),i(t))}_resolvePendingRenderCycles(e,t=Number.POSITIVE_INFINITY){for(const[i,n]of this._renderCycleWaiters){if(i>=t)continue;const o=this._renderCycleWaiterTimeouts.get(i);void 0!==o&&window.clearTimeout(o),this._renderCycleWaiterTimeouts.delete(i),this._renderCycleWaiters.delete(i),n(e)}}_unobserveGuardedOptionResizeTargets(){for(const e of this._guardedObservedOptions)this._guardedOptionResizeObserver?.unobserve(e);this._guardedObservedOptions.clear()}_renderSingleOption(e,t,i,n,o=this._optionsContainer){const s=this._state.selectedIndices.has(t),r=Boolean(e?.disabled),a=this._getDisabledOptionBehavior(),l=`${this._uniqueId}-option-${t}`;if(this._optionRenderer){const c=this._optionRenderer(e,t,this._rendererHelpers),d=this._normalizeCustomOptionElement(c,{index:t,value:i(e),label:n(e),selected:s,active:this._state.activeIndex===t,disabled:r,disabledBehavior:a,id:l});return d.setAttribute("dir",this._config.direction??"ltr"),void o.appendChild(d)}const c=new SelectOption({item:e,index:t,id:l,selected:s,disabled:r,disabledBehavior:a,active:this._state.activeIndex===t,getValue:i,getLabel:n,showRemoveButton:"multi"===this._config.selection.mode&&this._config.selection.showRemoveButton,removeButtonIcon:this._config.selection.removeButtonIcon,classMap:this.classMap,className:this._config.styles?.classNames?.option});this._config.styles?.classNames?.option&&c.classList.add(...this._config.styles.classNames.option.split(" ").filter(Boolean)),c.setAttribute("dir",this._config.direction??"ltr"),s&&this._config.styles?.classNames?.selectedOption&&c.classList.add(...this._config.styles.classNames.selectedOption.split(" ").filter(Boolean)),this._state.activeIndex===t&&this._config.styles?.classNames?.activeOption&&c.classList.add(...this._config.styles.classNames.activeOption.split(" ").filter(Boolean)),r&&this._config.styles.classNames?.disabledOption&&c.classList.add(...this._config.styles.classNames.disabledOption.split(" ").filter(Boolean)),c.setAttribute("part","option"),c.dataset.index=String(t),c.dataset.value=String(i(e)),c.dataset.smIndex=String(t),c.hasAttribute("data-sm-selectable")||c.toggleAttribute("data-sm-selectable",!0);const d=i(e);null!=d&&(c.dataset.smValue=String(d)),c.id=c.id||l,c.addEventListener("optionRemove",e=>{const i=e.detail,n=i?.index??t;this._handleOptionRemove(n)}),o.appendChild(c),c instanceof SelectOption&&c.ensureRendered()}_syncCustomOptionActiveClasses(e,t){const i=(this.classMap?.active??"active sm-active").split(/\s+/).filter(Boolean),n=(this._config.styles.classNames?.activeOption??"").split(/\s+/).filter(Boolean),o=[...new Set([...i,...n,"smilodon-option--active"])],s=this._customOptionManagedActiveClasses.get(e)??[];e.classList.remove(...new Set([...s,...o,"active","sm-active","smilodon-option--active"])),t&&e.classList.add(...o),this._customOptionManagedActiveClasses.set(e,o);const r=new Set((e.dataset.smState??"").split(/\s+/).filter(Boolean));t?r.add("active"):r.delete("active"),r.size?e.dataset.smState=[...r].join(" "):delete e.dataset.smState}_normalizeCustomOptionElement(e,t){const i=e instanceof HTMLElement?e:document.createElement("div");i.hasAttribute("part")||i.setAttribute("part","option"),i.classList.add("smilodon-option","option"),this._config.styles.classNames?.option&&i.classList.add(...this._config.styles.classNames.option.split(" ").filter(Boolean));const n=t.selected,o=t.active,s=t.disabled,r=s&&t.disabledBehavior.selectable,a=s&&t.disabledBehavior.hoverable,l=s&&t.disabledBehavior.focusable,c=s&&(r||a),d=(this.classMap?.selected??"selected sm-selected").split(" ").filter(Boolean),h=(this.classMap?.disabled??"disabled sm-disabled").split(" ").filter(Boolean);n?(i.classList.add(...d),i.classList.add("smilodon-option--selected"),this._config.styles.classNames?.selectedOption&&i.classList.add(...this._config.styles.classNames.selectedOption.split(" ").filter(Boolean))):(i.classList.remove(...d),i.classList.remove("smilodon-option--selected"),this._config.styles.classNames?.selectedOption&&i.classList.remove(...this._config.styles.classNames.selectedOption.split(" ").filter(Boolean))),this._syncCustomOptionActiveClasses(i,o),s?(i.classList.add(...h),i.classList.add("smilodon-option--disabled"),this._config.styles.classNames?.disabledOption&&i.classList.add(...this._config.styles.classNames.disabledOption.split(" ").filter(Boolean))):(i.classList.remove(...h),i.classList.remove("smilodon-option--disabled"),this._config.styles.classNames?.disabledOption&&i.classList.remove(...this._config.styles.classNames.disabledOption.split(" ").filter(Boolean))),i.classList.toggle("smilodon-option--disabled-interactive",c),i.classList.toggle("smilodon-option--disabled-hoverable",a),i.classList.toggle("smilodon-option--disabled-focusable",l),i.classList.toggle("smilodon-option--disabled-selectable",r);const u=[];n&&u.push("selected"),o&&u.push("active"),u.length?i.dataset.smState=u.join(" "):delete i.dataset.smState,i.hasAttribute("data-selectable")||i.setAttribute("data-selectable",""),i.hasAttribute("data-sm-selectable")||i.setAttribute("data-sm-selectable",""),i.dataset.index=String(t.index),i.dataset.value=String(t.value),i.dataset.smIndex=String(t.index),null!=t.value?i.dataset.smValue=String(t.value):delete i.dataset.smValue;const p=this._customOptionNormalizedIds.get(i);return!i.id||void 0!==p&&i.id===p?(i.id=t.id,this._customOptionNormalizedIds.set(i,t.id)):this._customOptionNormalizedIds.delete(i),i.hasAttribute("tabindex")||(i.tabIndex=-1),this._customOptionBoundElements.has(i)||this._customOptionBoundElements.add(i),this._normalizeCustomOptionAccessibility(i,{label:t.label,disabled:t.disabled}),i}_addLoadMoreTrigger(){const e=document.createElement("div");if(e.className="load-more-container",this._dataRequestCoordinator){let t;if(this._config.infiniteScroll.enabled&&Boolean(this._intersectionObserver)&&this._acknowledgedReady&&(t=this._acknowledgedSentinel??document.createElement("div"),t.className="infinite-scroll-sentinel",t.style.height="10px",t.style.width="100%",t.style.opacity="0",this._acknowledgedSentinel=t,this._loadMoreTrigger=t,e.appendChild(t)),this._config.loadMore.enabled||this._config.infiniteScroll.enabled){const i=document.createElement("button");i.className="load-more-button",i.textContent=`Load ${this._config.loadMore.itemsPerLoad} more`,i.addEventListener("click",()=>this._loadMoreItems("manual")),e.appendChild(i),t||(this._loadMoreTrigger=i)}if(this._optionsContainer.appendChild(e),t&&this._intersectionObserver)try{this._intersectionObserver.observe(t)}catch(i){this._intersectionObserver.disconnect(),this._intersectionObserver=void 0,t.remove(),this._loadMoreTrigger=e.querySelector(".load-more-button")??void 0}return}if(this._config.infiniteScroll.enabled){const t=document.createElement("div");t.className="infinite-scroll-sentinel",t.style.height="10px",t.style.width="100%",t.style.opacity="0",this._loadMoreTrigger=t,e.appendChild(t)}else{const t=document.createElement("button");t.className="load-more-button",t.textContent=`Load ${this._config.loadMore.itemsPerLoad} more`,t.addEventListener("click",()=>this._loadMoreItems()),this._loadMoreTrigger=t,e.appendChild(t)}this._optionsContainer.appendChild(e),this._intersectionObserver&&this._loadMoreTrigger&&this._intersectionObserver.observe(this._loadMoreTrigger)}_shouldRenderLoadMoreTrigger(){if(!this._config.loadMore.enabled&&!this._config.infiniteScroll.enabled)return!1;if(!("acknowledged"!==this._dataLoadingConfig.protocol||this._dataRequestCoordinator&&this._acknowledgedReady))return!1;if(!this._dataRequestCoordinator)return this._state.loadedItems.length>0;const e=this._dataRequestCoordinator.getSnapshot();return"resource-limited"!==e.status&&(e.hasMore||null!==e.error||"empty"===e.status||"failed"===e.status||"cancelled"===e.status)}}EnhancedSelect._instances=new Set,EnhancedSelect._MIRRORED_STYLES_SCOPE_CLASS="smilodon-mirrored-styles-scope",EnhancedSelect._MIRRORED_STYLESHEET_CACHE_LIMIT=32,EnhancedSelect._mirroredStylesheetTextCache=new Map,customElements.get("enhanced-select")||customElements.define("enhanced-select",EnhancedSelect);class WorkerManager{constructor(){this.worker=null,this.pending=new Map,this.supportsWorkers=!1,this.supportsSharedArrayBuffer=!1,this.nextId=0,this._fallbackOperations={transform:e=>{const{items:t,transformer:i}=e,n=new Function("item","index",`return (${i})(item, index)`);return t.map((e,t)=>n(e,t))},search:e=>{const{items:t,query:i,fuzzy:n}=e,o=i.toLowerCase(),s=[];for(let e=0;e<t.length;e++){const i=t[e],r=i,a=String(r?.label??r?.value??i).toLowerCase();if(n){let t=0;for(let e=0;e<a.length&&t<o.length;e++)a[e]===o[t]&&t++;t===o.length&&s.push({item:i,index:e})}else a.includes(o)&&s.push({item:i,index:e})}return s},filter:e=>{const{items:t,predicate:i}=e,n=new Function("item","index",`return (${i})(item, index)`);return t.filter((e,t)=>n(e,t))},sort:e=>{const{items:t,comparator:i}=e,n=new Function("a","b",`return (${i})(a, b)`);return[...t].sort(n)}},this.detectFeatures(),this.initWorker()}detectFeatures(){this.supportsWorkers="undefined"!=typeof Worker,this.supportsSharedArrayBuffer="undefined"!=typeof SharedArrayBuffer}initWorker(){if(this.supportsWorkers)try{const e=this.generateWorkerCode(),t=new Blob([e],{type:"application/javascript"}),i=URL.createObjectURL(t);this.worker=new Worker(i),this.worker.onmessage=this.handleMessage.bind(this),this.worker.onerror=this.handleError.bind(this),URL.revokeObjectURL(i)}catch(e){console.warn("Worker initialization failed, falling back to main thread",e),this.worker=null}}generateWorkerCode(){return"\n // Worker code\n self.onmessage = function(e) {\n const start = performance.now();\n const { id, type, payload } = e.data;\n \n // Lookup object for O(1) operation dispatch\n const operations = {\n 'transform': handleTransform,\n 'search': handleSearch,\n 'filter': handleFilter,\n 'sort': handleSort,\n };\n \n try {\n const handler = operations[type];\n if (!handler) {\n throw new Error('Unknown operation: ' + type);\n }\n \n const result = handler(payload);\n const duration = performance.now() - start;\n \n self.postMessage({\n id,\n success: true,\n data: result,\n duration,\n });\n } catch (error) {\n self.postMessage({\n id,\n success: false,\n error: error.message,\n });\n }\n };\n \n function handleTransform({ items, transformer }) {\n const fn = new Function('item', 'index', 'return (' + transformer + ')(item, index)');\n return items.map((item, i) => fn(item, i));\n }\n \n function handleSearch({ items, query, fuzzy, maxResults }) {\n const lowerQuery = query.toLowerCase();\n const results = [];\n \n for (let i = 0; i < items.length; i++) {\n const item = items[i];\n const text = String(item).toLowerCase();\n \n if (fuzzy) {\n if (fuzzyMatch(text, lowerQuery)) {\n results.push({ item, index: i, score: fuzzyScore(text, lowerQuery) });\n }\n } else {\n if (text.includes(lowerQuery)) {\n results.push({ item, index: i });\n }\n }\n \n if (maxResults && results.length >= maxResults) break;\n }\n \n if (fuzzy) {\n results.sort((a, b) => b.score - a.score);\n }\n \n return results;\n }\n \n function handleFilter({ items, predicate }) {\n const fn = new Function('item', 'index', 'return (' + predicate + ')(item, index)');\n return items.filter((item, i) => fn(item, i));\n }\n \n function handleSort({ items, comparator }) {\n const fn = new Function('a', 'b', 'return (' + comparator + ')(a, b)');\n return [...items].sort(fn);\n }\n \n // Simple fuzzy matching (Levenshtein-inspired)\n function fuzzyMatch(text, query) {\n let qi = 0;\n for (let ti = 0; ti < text.length && qi < query.length; ti++) {\n if (text[ti] === query[qi]) qi++;\n }\n return qi === query.length;\n }\n \n function fuzzyScore(text, query) {\n let score = 0;\n let qi = 0;\n for (let ti = 0; ti < text.length && qi < query.length; ti++) {\n if (text[ti] === query[qi]) {\n score += 100 - ti; // Earlier matches score higher\n qi++;\n }\n }\n return score;\n }\n "}handleMessage(e){const{id:t,success:i,data:n,error:o}=e.data,s=this.pending.get(t);s&&(clearTimeout(s.timeout),this.pending.delete(t),i?s.resolve(n):s.reject(new Error(o||"Worker error")))}handleError(e){console.error("Worker error:",e);for(const[e,t]of this.pending)clearTimeout(t.timeout),t.reject(new Error("Worker crashed"));this.pending.clear()}async execute(e,t,i=5e3){if(!this.worker)return this.executeFallback(e,t);const n="req_"+this.nextId++;return new Promise((o,s)=>{const r=setTimeout(()=>{this.pending.delete(n),s(new Error("Worker timeout"))},i);this.pending.set(n,{resolve:o,reject:s,timeout:r}),this.worker.postMessage({id:n,type:e,payload:t})})}async executeFallback(e,t){const i=this._fallbackOperations[e];if(!i)throw new Error(`Unknown operation: ${e}`);return i(t)}async transform(e,t){return this.execute("transform",{items:e,transformer:t.toString()})}async search(e,t,i=!1){return this.execute("search",{items:e,query:t,fuzzy:i})}async filter(e,t){return this.execute("filter",{items:e,predicate:t.toString()})}async sort(e,t){return this.execute("sort",{items:e,comparator:t.toString()})}get hasWorkerSupport(){return this.supportsWorkers&&null!==this.worker}get hasSharedArrayBuffer(){return this.supportsSharedArrayBuffer}destroy(){if(this.worker){for(const[e,t]of this.pending)clearTimeout(t.timeout),t.reject(new Error("Worker terminated"));this.pending.clear(),this.worker.terminate(),this.worker=null}}}let workerManager=null;function getWorkerManager(){return workerManager||(workerManager=new WorkerManager),workerManager}class PerformanceTelemetry{constructor(){this.frameTimes=[],this.longTasks=0,this.lastFrameTime=0,this.rafId=0,this.measuring=!1,this.observer=null,this.workTotal=0,this.workCount=0,this.measureFrame=()=>{if(!this.measuring)return;const e=performance.now(),t=e-this.lastFrameTime;this.frameTimes.push(t),this.frameTimes.length>60&&this.frameTimes.shift(),this.lastFrameTime=e,this.rafId=requestAnimationFrame(this.measureFrame)}}setupObserver(){if("undefined"!=typeof PerformanceObserver)try{this.observer=new PerformanceObserver(e=>{if(this.measuring)for(const t of e.getEntries())"longtask"===t.entryType&&t.duration>50&&this.longTasks++,"measure"===t.entryType&&(this.workTotal+=t.duration,this.workCount+=1)});try{this.observer.observe({entryTypes:["longtask","measure"]})}catch{this.observer.observe({entryTypes:["measure"]})}}catch(e){console.warn("PerformanceObserver not available",e)}}start(){this.measuring||(this.measuring=!0,this.frameTimes=[],this.workTotal=0,this.workCount=0,this.longTasks=0,this.lastFrameTime=performance.now(),this.setupObserver(),this.measureFrame())}stop(){this.measuring=!1,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=0),this.observer&&(this.observer.disconnect(),this.observer=null)}markStart(e){performance.mark(`${e}-start`)}markEnd(e){const t=`${e}-start`,i=`${e}-end`;performance.mark(i);const n=performance.measure(e,t,i),o=n?n.duration:0;return performance.clearMarks(t),performance.clearMarks(i),performance.clearMeasures(e),o}getMetrics(){const e=this.frameTimes.length>0?this.frameTimes.reduce((e,t)=>e+t,0)/this.frameTimes.length:0,t={frames:{frameTime:e,fps:e>0?1e3/e:0,longTasks:this.frameTimes.filter(e=>e>16.67).length,droppedFrames:this.frameTimes.filter(e=>e>33.33).length},mainThreadWork:this.workCount>0?this.workTotal/this.workCount:0,longTaskCount:this.longTasks};if("memory"in performance&&performance.memory){const e=performance.memory;t.memory={usedJSHeapSize:e.usedJSHeapSize,totalJSHeapSize:e.totalJSHeapSize,jsHeapSizeLimit:e.jsHeapSizeLimit}}return t}isPerformanceGood(){const e=this.getMetrics();return e.frames.fps>=55&&e.mainThreadWork<8&&e.frames.longTasks<3}getReport(){const e=this.getMetrics();let t="=== Performance Report ===\n";if(t+=`FPS: ${e.frames.fps.toFixed(2)}\n`,t+=`Avg Frame Time: ${e.frames.frameTime.toFixed(2)}ms\n`,t+=`Long Frames (>16.67ms): ${e.frames.longTasks}\n`,t+=`Dropped Frames (>33ms): ${e.frames.droppedFrames}\n`,t+=`Avg Main Thread Work: ${e.mainThreadWork.toFixed(2)}ms\n`,t+=`Long Tasks (>50ms): ${e.longTaskCount}\n`,e.memory){t+=`Memory: ${(e.memory.usedJSHeapSize/1024/1024).toFixed(2)}MB / ${(e.memory.jsHeapSizeLimit/1024/1024).toFixed(2)}MB\n`}return t+=`Status: ${this.isPerformanceGood()?"✓ GOOD":"✗ POOR"}\n`,t}reset(){this.frameTimes=[],this.workTotal=0,this.workCount=0,this.longTasks=0}destroy(){this.stop(),this.observer&&(this.observer.disconnect(),this.observer=null)}}let telemetry=null;function getTelemetry(){return telemetry||(telemetry=new PerformanceTelemetry),telemetry}async function measureAsync(e,t){const i=performance.now();return{result:await t(),duration:performance.now()-i}}function measureSync(e,t){const i=performance.now();return{result:t(),duration:performance.now()-i}}class NoOpSanitizer{sanitize(e){return e}}let globalSanitizer=new NoOpSanitizer;function setHTMLSanitizer(e){globalSanitizer=e}function getHTMLSanitizer(){return globalSanitizer}function sanitizeHTML(e){return globalSanitizer.sanitize(e)}function createTextNode(e){return document.createTextNode(e)}function setTextContent(e,t){e.textContent=t}function createElement(e,t,i){const n=document.createElement(e);if(t)for(const[e,i]of Object.entries(t))e.startsWith("on")||"style"===e?console.warn(`[NativeSelect Security] Blocked attribute: ${e}`):n.setAttribute(e,i);return void 0!==i&&(n.textContent=i),n}function setCSSProperties(e,t){for(const[i,n]of Object.entries(t))i.startsWith("--")?e.style.setProperty(i,n):console.warn(`[NativeSelect Security] CSS property must start with --: ${i}`)}const CSPFeatures={hasInlineScripts(){try{return new Function("return true"),!0}catch{return!1}},hasEval(){try{return eval("true"),!0}catch{return!1}},hasSharedArrayBuffer:()=>"undefined"!=typeof SharedArrayBuffer,hasWorkers(){try{return"undefined"!=typeof Worker}catch{return!1}},isSandboxed(){try{return window!==window.parent&&!window.parent}catch{return!0}},getCSPDirectives(){const e=document.querySelectorAll('meta[http-equiv="Content-Security-Policy"]'),t=[];return e.forEach(e=>{const i=e.getAttribute("content");i&&t.push(i)}),t}};function detectEnvironment(){return{canUseWorkers:CSPFeatures.hasWorkers(),canUseSharedArrayBuffer:CSPFeatures.hasSharedArrayBuffer(),canUseInlineScripts:CSPFeatures.hasInlineScripts(),canUseEval:CSPFeatures.hasEval(),isSandboxed:CSPFeatures.isSandboxed(),cspDirectives:CSPFeatures.getCSPDirectives()}}function validateTemplate(e,t){return globalSanitizer instanceof NoOpSanitizer&&console.warn(`[NativeSelect Security] Template from "${t}" contains HTML but no sanitizer is configured. This may be unsafe if the content is untrusted. Call setHTMLSanitizer() with a sanitizer like DOMPurify.`),sanitizeHTML(e)}function containsSuspiciousPatterns(e){return[/<script/i,/javascript:/i,/on\w+\s*=/i,/eval\s*\(/i,/Function\s*\(/i,/setTimeout\s*\(/i,/setInterval\s*\(/i].some(t=>t.test(e))}function escapeHTML(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}function escapeAttribute(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function applyClasses(e,t){e.className=t.filter(Boolean).join(" ")}function toggleClass(e,t,i){e.classList.toggle(t,i)}function setCustomProperties(e,t){for(const[i,n]of Object.entries(t))i.startsWith("--")?e.style.setProperty(i,n):"production"!==process.env.NODE_ENV&&console.warn(`[NativeSelect CSP] Custom property must start with --: "${i}". Skipping.`)}function getCustomProperty(e,t){return getComputedStyle(e).getPropertyValue(t).trim()}function removeCustomProperty(e,t){e.style.removeProperty(t)}const defaultTheme={"--ns-item-height":"40px","--ns-item-padding":"8px 12px","--ns-item-bg":"transparent","--ns-item-hover-bg":"rgba(0, 0, 0, 0.05)","--ns-item-selected-bg":"rgba(0, 102, 204, 0.1)","--ns-item-active-bg":"rgba(0, 102, 204, 0.2)","--ns-item-color":"inherit","--ns-item-selected-color":"#0066cc","--ns-border-color":"#ccc","--ns-border-radius":"4px","--ns-focus-outline":"2px solid #0066cc","--ns-font-size":"14px","--ns-font-family":"system-ui, -apple-system, sans-serif"};function applyDefaultTheme(e){setCustomProperties(e,defaultTheme)}const shadowDOMStyles='\n:host {\n display: block;\n box-sizing: border-box;\n font-family: var(--ns-font-family, system-ui, -apple-system, sans-serif);\n font-size: var(--ns-font-size, 14px);\n}\n\n* {\n box-sizing: border-box;\n}\n\n.ns-list {\n position: relative;\n overflow: auto;\n max-height: var(--ns-max-height, 300px);\n border: 1px solid var(--ns-border-color, #ccc);\n border-radius: var(--ns-border-radius, 4px);\n background: var(--ns-bg, white);\n outline: none;\n}\n\n.ns-list:focus {\n outline: var(--ns-focus-outline, 2px solid #0066cc);\n outline-offset: -2px;\n}\n\n.ns-item {\n padding: var(--ns-item-padding, 8px 12px);\n min-height: var(--ns-item-height, 40px);\n color: var(--ns-item-color, inherit);\n background: var(--ns-item-bg, transparent);\n cursor: pointer;\n user-select: none;\n display: flex;\n align-items: center;\n transition: background-color 0.15s ease;\n}\n\n.ns-item:hover {\n background: var(--ns-item-hover-bg, rgba(0, 0, 0, 0.05));\n}\n\n.ns-item[aria-selected="true"] {\n background: var(--ns-item-selected-bg, rgba(0, 102, 204, 0.1));\n color: var(--ns-item-selected-color, #0066cc);\n}\n\n.ns-item[data-active="true"]:not([aria-selected="true"]) {\n background: var(--ns-item-active-bg, rgba(0, 102, 204, 0.2));\n}\n\n.ns-item[aria-selected="true"][data-active="true"] {\n background: var(--ns-item-selected-active-bg, var(--ns-item-selected-bg, rgba(0, 102, 204, 0.1)));\n color: var(--ns-item-selected-active-color, var(--ns-item-selected-color, #0066cc));\n outline: var(--ns-item-selected-active-outline, 2px solid #0066cc);\n outline-offset: -2px;\n}\n\n.ns-item[aria-disabled="true"] {\n opacity: 0.5;\n cursor: not-allowed;\n}\n\n.ns-viewport {\n position: relative;\n overflow: auto;\n -webkit-overflow-scrolling: touch;\n}\n\n.ns-spacer {\n position: absolute;\n top: 0;\n left: 0;\n width: 1px;\n pointer-events: none;\n}\n\n/* Screen reader only */\n.ns-sr-only {\n position: absolute;\n left: -9999px;\n width: 1px;\n height: 1px;\n overflow: hidden;\n clip: rect(0, 0, 0, 0);\n white-space: nowrap;\n}\n\n/* Portal mode (teleported outside shadow DOM) */\n.ns-portal {\n position: fixed;\n z-index: var(--ns-portal-z-index, 9999);\n}\n\n/* CSP warning banner (only shown in development) */\n.ns-csp-warning {\n padding: 8px;\n background: #fff3cd;\n border: 1px solid #ffc107;\n border-radius: 4px;\n color: #856404;\n font-size: 12px;\n margin-bottom: 8px;\n}\n';function injectShadowStyles(e){const t=document.createElement("style");t.textContent=shadowDOMStyles,e.appendChild(t)}function hasOverflowHiddenAncestor(e){let t=e.parentElement;for(;t&&t!==document.body;){const e=getComputedStyle(t).overflow;if("hidden"===e||"clip"===e)return!0;t=t.parentElement}return!1}function warnCSPViolation(e,t){"production"!==process.env.NODE_ENV&&console.warn(`[NativeSelect CSP] Feature "${e}" blocked by Content Security Policy. Falling back to "${t}".`)}export{CSPFeatures,CustomOptionPool,DOMPool,DefaultSelectEffectRunner,EnhancedSelect,FenwickTree,NativeSelectElement,OptionRenderer,PerformanceTelemetry,SelectEngineBridge,SelectOption,Virtualizer,WorkerManager,applyClasses,applyDefaultTheme,applySelectionRequest,arrayIncludesValue,arraysEqualByValue,configureSelect,containsSuspiciousPatterns,createDefaultItemAdapter,createElement,createInitialSelectState,createItemRegistry,createRendererHelpers,createTextNode,defaultTheme,detectEnvironment,escapeAttribute,escapeHTML,getActiveKey,getCustomProperty,getDefaultDuplicateKeyPolicy,getHTMLSanitizer,getSelectedKeys,getTelemetry,getWorkerManager,hasOverflowHiddenAncestor,hasSelection,injectShadowStyles,isDisabled,isFocused,isOpen,isRegisteredKey,isSelected,measureAsync,measureSync,removeCustomProperty,renderTemplate,resetSelectConfig,sanitizeHTML,selectConfig,setCSSProperties,setCustomProperties,setHTMLSanitizer,setTextContent,shadowDOMStyles,toggleClass,transition,validateDataLoadingConfig,validateTemplate,valuesEqual,warnCSPViolation};
2
2
  //# sourceMappingURL=index.min.js.map