import { _ as _applyDecoratedDescriptor, a as _initializerDefineProperty, b as _defineProperty } from '../_rollupPluginBabelHelpers-9wjJaosZ.js';
import { setComponentTemplate } from '@ember/component';
import { precompileTemplate } from '@ember/template-compilation';
import { macroCondition, dependencySatisfies, importSync } from '@embroider/macros';
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { isArray } from '@ember/array';
import { action } from '@ember/object';
import { inject } from '@ember/service';
import { isEqual } from '@ember/utils';
import optional from 'ember-composable-helpers/helpers/optional';
import pipe from 'ember-composable-helpers/helpers/pipe';
import queue from 'ember-composable-helpers/helpers/queue';
import PowerSelectMultiple from 'ember-power-select/components/power-select-multiple';
import { emberPowerSelectIsGroup } from 'ember-power-select/helpers/ember-power-select-is-group';
import { and, not } from 'ember-truth-helpers';
import argOrDefault from '../helpers/arg-or-default.js';
import classNames from '../helpers/class-names.js';
import EuiAccordionAccordionComponent from './eui-combo-box/create-option.js';
import EuiComboBoxGroup from './eui-combo-box/group.js';
import NoMatchesMessageComponent from './eui-combo-box/no-matches-message.js';
import EuiComboBoxOptionsComponent from './eui-combo-box/options.js';
import SearchMessageComponent from './eui-combo-box/search-message.js';
import EuiComboBoxTriggerComponent from './eui-combo-box/trigger.js';

var _class, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5;
let cached = macroCondition(dependencySatisfies('ember-source', '>= 4.1.0-alpha.0')) ? importSync('@glimmer/tracking').cached : importSync('ember-cached-decorator-polyfill').cached;
const isSliceable = coll => {
  return isArray(coll);
};
const toPlainArray = collection => {
  if (isSliceable(collection)) {
    return collection.slice();
  } else {
    return collection;
  }
};
let EuiComboBoxComponent = setComponentTemplate(precompileTemplate(`
    {{! @glint-nocheck: not typesafe yet }}
    <PowerSelectMultiple
      ...attributes
      @onChange={{pipe this.onChange @onChange}}
      @onFocus={{@onFocus}}
      @onBlur={{@onBlur}}
      @onOpen={{@onOpen}}
      @onClose={{@onClose}}
      @placeholderComponent={{@placeholderComponent}}
      @searchMessage={{this.searchMessage}}
      @searchMessageComponent={{if
        @searchMessageComponent
        @searchMessageComponent
        EuiComboBoxSearchMessage
      }}
      @noMatchesMessage={{this.noMatchesMessage}}
      @matchTriggerWidth={{@matchTriggerWidth}}
      @options={{this.options}}
      @selected={{@selectedOptions}}
      @closeOnSelect={{@closeOnSelect}}
      @defaultHighlighted={{@defaultHighlighted}}
      @searchField={{@searchField}}
      @searchEnabled={{argOrDefault @searchEnabled true}}
      @tabindex={{@tabindex}}
      @initiallyOpened={{and (not @isDisabled) @autoFocus}}
      @triggerComponent={{component
        EuiComboBoxTrigger
        fullWidth=@fullWidth
        compressed=@compressed
        isInvalid=@isInvalid
        singleSelection=@singleSelection
        onClose=@removeTag
        onCreateOption=(if @onCreateOption this.onCreateOption)
        isLoading=@isLoading
        autoFocus=(and (not @isDisabled) @autoFocus)
        icon=@triggerIcon
      }}
      @matcher={{@matcher}}
      @initiallyOpen={{@initiallyOpen}}
      @typeAheadOptionMatcher={{@typeAheadOptionMatcher}}
      @buildSelection={{this.buildSelection}}
      @search={{@search}}
      @onInput={{@onInput}}
      @onKeydown={{@onKeydown}}
      @scrollTo={{this.scrollTo}}
      @registerAPI={{queue this.registerAPI (optional @registerApi)}}
      @horizontalPosition={{@horizontalPosition}}
      @destination={{@destination}}
      @preventScroll={{@preventScroll}}
      @renderInPlace={{@renderInPlace}}
      @verticalPosition={{@verticalPosition}}
      @disabled={{@isDisabled}}
      @calculatePosition={{@calculatePosition}}
      @eventType={{@eventType}}
      @ariaLabel={{@ariaLabel}}
      @ariaLabelledBy={{@ariaLabelledBy}}
      @required={{@required}}
      @triggerRole={{@triggerRole}}
      @title={{@title}}
      @triggerId={{@triggerId}}
      @allowClear={{and (argOrDefault @isClearable true) (not @isDisabled)}}
      @loadingMessage={{this.loadingMessage}}
      @selectedItemComponent={{@selectedItemComponent}}
      @beforeOptionsComponent={{@beforeOptionsComponent}}
      @afterOptionsComponent={{@afterOptionsComponent}}
      @placeholder={{@placeholder}}
      @searchPlaceholder={{@searchPlaceholder}}
      @optionsComponent={{component
        EuiComboBoxOptions
        rowHeight=@rowHeight
        class=@optionsClass
      }}
      @extra={{@extra}}
      @groupComponent={{component EuiComboBoxGroup}}
      @triggerClass={{classNames
        "euiComboBox"
        (if @compressed "euiComboBox--compressed")
        (if @fullWidth "euiComboBox--fullWidth")
        (if @isDisabled "euiComboBox-isDisabled")
        (if @isInvalid "euiComboBox-isInvalid")
        (if this.select.isOpen "euiComboBox-isOpen")
      }}
      @noMatchesMessageComponent={{if
        @onCreateOption
        (component
          EuiComboBoxCreateOption
          customOptionText=@customOptionText
          onCreateOption=this.onCreateOption
          select=this.select
        )
        (component EuiComboBoxNoMatchesMessage)
      }}
      @dropdownClass="euiComboBoxOptionsList euiPanel euiPanel--borderRadiusMedium euiPanel--noShadow euiPanel--plain euiPopover__panel-isAttached euiPopover__panel euiPopover__panel-noArrow euiPopover__panel--bottom euiPopover__panel-isOpen euiComboBoxOptionsList__rowWrap {{@dropdownClass}}"
      as |option i|
    >
      {{yield option i}}
    </PowerSelectMultiple>
  `, {
  strictMode: true,
  scope: () => ({
    PowerSelectMultiple,
    pipe,
    EuiComboBoxSearchMessage: SearchMessageComponent,
    argOrDefault,
    and,
    not,
    EuiComboBoxTrigger: EuiComboBoxTriggerComponent,
    queue,
    optional,
    EuiComboBoxOptions: EuiComboBoxOptionsComponent,
    EuiComboBoxGroup,
    classNames,
    EuiComboBoxCreateOption: EuiAccordionAccordionComponent,
    EuiComboBoxNoMatchesMessage: NoMatchesMessageComponent
  })
}), (_class = class EuiComboBoxComponent extends Component {
  constructor(...args) {
    super(...args);
    _initializerDefineProperty(this, "euiI18n", _descriptor, this);
    _initializerDefineProperty(this, "select", _descriptor2, this);
    _initializerDefineProperty(this, "_resolvedOptions", _descriptor3, this);
    _initializerDefineProperty(this, "searchText", _descriptor4, this);
    _initializerDefineProperty(this, "_searchResult", _descriptor5, this);
    _defineProperty(this, "_filterResultsCache", {
      results: [],
      options: [],
      searchText: this.searchText
    });
  }
  get loadingMessage() {
    return this.args.loadingMessage || this.euiI18n.lookupToken('euiComboBox.loadingMessage', 'Loading options...');
  }
  get noMatchesMessage() {
    return this.args.noMatchesMessage || this.euiI18n.lookupToken('euiComboBox.noMatchesMessage', 'No results found');
  }
  get searchMessage() {
    return this.args.searchMessage || this.euiI18n.lookupToken('euiComboBox.searchMessage', 'Type to search');
  }
  //This is to allow scrolling between virtualized groups
  get opts() {
    return this.results.reduce((acc, curr) => {
      if (emberPowerSelectIsGroup([curr])) {
        acc.push(curr, ...curr.options);
      } else {
        acc.push(curr);
      }
      return acc;
    }, []);
  }
  get options() {
    if (this._resolvedOptions) return toPlainArray(this._resolvedOptions);
    if (this.args.options) {
      return toPlainArray(this.args.options);
    } else {
      return [];
    }
  }
  get results() {
    if (this.searchText.length > 0) {
      if (this.args.search) {
        return toPlainArray(this._searchResult || this.options);
      } else {
        if (this._filterResultsCache.options === this.options && this._filterResultsCache.searchText === this.searchText) {
          // This is an optimization to avoid filtering several times, which may be a bit expensive
          // if there are many options, if neither the options nor the searchtext have changed
          return this._filterResultsCache.results;
        }

        //@ts-ignore
        let results = this._filter(this.options, this.searchText);
        //eslint-disable-next-line
        this._filterResultsCache = {
          results,
          options: this.options,
          searchText: this.searchText
        };
        return results;
      }
    } else {
      return this.options;
    }
  }
  scrollTo(option, select) {
    let optionsList = document.querySelector(`[aria-controls="ember-power-select-trigger-${select.uniqueId}"]`);
    if (!optionsList) {
      return;
    }
    let index = this.opts.indexOf(option);
    if (index === -1) {
      return;
    }
    let optionElement = optionsList.querySelector(`[data-option-index="${index}"]`);
    if (!optionElement) {
      return;
    }
    let optionTopScroll = optionElement.offsetTop;
    let optionBottomScroll = optionTopScroll + optionElement.offsetHeight;
    if (optionBottomScroll > optionsList.offsetHeight + optionsList.scrollTop) {
      optionsList.scrollTop = optionBottomScroll - optionsList.offsetHeight;
    } else if (optionTopScroll < optionsList.scrollTop) {
      optionsList.scrollTop = optionTopScroll;
    }
  }
  registerAPI(select) {
    this.select = select;
  }
  onChange(selected) {
    if (this.args.singleSelection) {
      return selected.length > 0 ? [selected[selected.length - 1]] : [];
    }
    return selected;
  }
  onCreateOption() {
    let option;
    if (this.args.onCreateOption && typeof this.args.onCreateOption === 'function') {
      // The `onCreateOption` function can be used to sanitize the input or explicitly return `false` to reject the input
      option = this.args.onCreateOption(this.select.searchText);
      if (option === false) {
        return;
      }
    }
    let search = option || this.select.searchText;
    this.select.actions.search('');
    this.select.actions.close();
    return search;
  }
  buildSelection(option, select) {
    let newSelection = (select.selected || []).slice(0);
    let idx = -1;
    for (let i = 0; i < newSelection.length; i++) {
      if (isEqual(newSelection[i], option)) {
        idx = i;
        break;
      }
    }
    if (idx > -1) {
      newSelection.splice(idx, 1);
    } else {
      newSelection.push(option);
    }
    if (this.args.singleSelection && newSelection.length === 0) {
      select.actions.search('');
    }
    if (select?.selected?.length < newSelection.length) {
      select.actions.search('');
    }
    return newSelection;
  }
}, (_descriptor = _applyDecoratedDescriptor(_class.prototype, "euiI18n", [inject], {
  configurable: true,
  enumerable: true,
  writable: true,
  initializer: null
}), _descriptor2 = _applyDecoratedDescriptor(_class.prototype, "select", [tracked], {
  configurable: true,
  enumerable: true,
  writable: true,
  initializer: function () {
    return null;
  }
}), _descriptor3 = _applyDecoratedDescriptor(_class.prototype, "_resolvedOptions", [tracked], {
  configurable: true,
  enumerable: true,
  writable: true,
  initializer: null
}), _descriptor4 = _applyDecoratedDescriptor(_class.prototype, "searchText", [tracked], {
  configurable: true,
  enumerable: true,
  writable: true,
  initializer: function () {
    return '';
  }
}), _descriptor5 = _applyDecoratedDescriptor(_class.prototype, "_searchResult", [tracked], {
  configurable: true,
  enumerable: true,
  writable: true,
  initializer: null
}), _applyDecoratedDescriptor(_class.prototype, "opts", [cached], Object.getOwnPropertyDescriptor(_class.prototype, "opts"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "options", [cached], Object.getOwnPropertyDescriptor(_class.prototype, "options"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "results", [cached], Object.getOwnPropertyDescriptor(_class.prototype, "results"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "scrollTo", [action], Object.getOwnPropertyDescriptor(_class.prototype, "scrollTo"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "registerAPI", [action], Object.getOwnPropertyDescriptor(_class.prototype, "registerAPI"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "onChange", [action], Object.getOwnPropertyDescriptor(_class.prototype, "onChange"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "onCreateOption", [action], Object.getOwnPropertyDescriptor(_class.prototype, "onCreateOption"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "buildSelection", [action], Object.getOwnPropertyDescriptor(_class.prototype, "buildSelection"), _class.prototype)), _class));

export { EuiComboBoxComponent as default, toPlainArray };
//# sourceMappingURL=eui-combo-box.js.map
