import { r as registerInstance, c as createEvent, h, H as Host, g as getElement } from './index-baa5e267.js';
import { ElementIDUtils, KeyboardManager } from '@sankhyalabs/core';

const ezClassicComboBoxCss = ":host{display:block;box-sizing:border-box;font-family:var(--font--pattern, 'Roboto', Arial, sans-serif);font-size:var(--font-size--default, 14px);color:var(--color--gray-500, #494A4E);--ez-classic-combo-box-highlighted-bg-color:var(--color--gray-90, #EAEAEA);--ez-classic-combo-box-max-height:180px;--ez-classic-combo-box-list-bg-color:var(--color--gray-70, #FFFFFF);--ez-classic-combo-box-item-hover-bg-color:var(--color--gray-100, #DEDEDE);--ez-classic-combo-box-selected-bg-color:var(--color--ocean-green-90, #E6F3EF);--ez-classic-combo-box-selected-text-color:var(--color--ocean-green-600, #008561);--ez-classic-combo-box-selected-font-weight:var(--font-weight--medium, 500);--ez-classic-combo-box-item-padding:var(--space--8, 8px) var(--space--4, 4px);--ez-classic-combo-box-item-border-radius:var(--border--radius-8, 8px);--ez-classic-combo-box-list-margin:var(--space--6, 6px);--ez-classic-combo-box-transition-duration:150ms;--ez-classic-combo-box-scrollbar-color:var(--color--gray-300, #C4C4C4);--ez-classic-combo-box-no-results-margin:var(--space--52, 52px) 0;--ez-classic-combo-box-item-text-color:inherit;--ez-classic-combo-box-item-min-height:auto}ul{list-style:none;padding:0;margin:var(--ez-classic-combo-box-list-margin);display:flex;flex-direction:column;overflow-y:auto;scrollbar-width:thin;scrollbar-color:var(--ez-classic-combo-box-scrollbar-color) transparent;max-height:var(--ez-classic-combo-box-max-height);scroll-behavior:smooth;background-color:var(--ez-classic-combo-box-list-bg-color)}li{cursor:pointer;border-radius:var(--ez-classic-combo-box-item-border-radius);padding:var(--ez-classic-combo-box-item-padding);transition:var(--ez-classic-combo-box-transition-duration) background-color linear;color:var(--ez-classic-combo-box-item-text-color);min-height:var(--ez-classic-combo-box-item-min-height)}li:hover{background-color:var(--ez-classic-combo-box-item-hover-bg-color)}li.highlighted{background-color:var(--ez-classic-combo-box-highlighted-bg-color)}li.selected{background-color:var(--ez-classic-combo-box-selected-bg-color);color:var(--ez-classic-combo-box-selected-text-color);font-weight:var(--ez-classic-combo-box-selected-font-weight)}span.no-results{margin:var(--ez-classic-combo-box-no-results-margin);cursor:default;text-align:center;display:flex;align-items:center;justify-content:center}";

const EzClassicComboBox = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.ezChange = createEvent(this, "ezChange", 7);
    this.ezBlur = createEvent(this, "ezBlur", 7);
    this.iconClick = createEvent(this, "iconClick", 7);
    this.ezVisibilityChange = createEvent(this, "ezVisibilityChange", 7);
    this.ezType = createEvent(this, "ezType", 7);
    this._keyboardManager = undefined;
    this._boundHandleDocumentClick = this.handleDocumentClick.bind(this);
    this.popoverVisible = false;
    this.hasSlotContent = false;
    this.highlightedIndex = 0;
    this.filteredOptions = [];
    this.inputValue = '';
    this.value = null;
    this.label = undefined;
    this.placeholder = undefined;
    this.enabled = true;
    this.readonly = false;
    this.name = undefined;
    this.state = "default";
    this.helpText = undefined;
    this.iconName = undefined;
    this.titleIcon = undefined;
    this.iconClickable = false;
    this.suppressSearch = false;
    this.options = undefined;
    this.textEmptyOption = undefined;
    this.suppressEmptyOption = false;
  }
  /**
   * Aplica o foco no campo.
   */
  async setFocus(option) {
    var _a;
    await ((_a = this._inputElem) === null || _a === void 0 ? void 0 : _a.setFocus(option));
  }
  /**
   * Remove o foco do campo.
   */
  async setBlur() {
    var _a;
    await ((_a = this._inputElem) === null || _a === void 0 ? void 0 : _a.setBlur());
    await this.hidePopover();
  }
  /**
   * Exibe o popover abaixo do input.
   */
  async showPopover() {
    var _a, _b, _c;
    if (!this._popoverElem || !this._inputElem || this.popoverVisible) {
      return;
    }
    this.popoverVisible = true;
    const inputContainer = (_b = (_a = this._inputElem) === null || _a === void 0 ? void 0 : _a.shadowRoot) === null || _b === void 0 ? void 0 : _b.querySelector('.input-container');
    await ((_c = this._popoverElem) === null || _c === void 0 ? void 0 : _c.showUnder(inputContainer !== null && inputContainer !== void 0 ? inputContainer : this._inputElem));
  }
  /**
   * Oculta o popover.
   */
  async hidePopover() {
    var _a;
    this.popoverVisible = false;
    await ((_a = this._popoverElem) === null || _a === void 0 ? void 0 : _a.hide());
  }
  compareOptionValues(option1, option2) {
    var _a, _b;
    return JSON.stringify((_a = option1 === null || option1 === void 0 ? void 0 : option1.value) !== null && _a !== void 0 ? _a : null) === JSON.stringify((_b = option2 === null || option2 === void 0 ? void 0 : option2.value) !== null && _b !== void 0 ? _b : null);
  }
  setEmptyValue() {
    this.value = null;
    this.inputValue = '';
  }
  async setValue(option) {
    if (!option || !this.options) {
      this.setEmptyValue();
      await this.hidePopover();
      return;
    }
    if (this.compareOptionValues(this.value, option)) {
      await this.hidePopover();
      return;
    }
    if (!option.value) {
      this.setEmptyValue();
    }
    else {
      this.value = option;
      this.inputValue = option.label;
    }
    this.ezChange.emit(this.value);
    await this.hidePopover();
  }
  async optionsChanged() {
    this.filterOptions('');
  }
  async valueChanged(newValue) {
    if (newValue) {
      this.inputValue = newValue.label;
      this.setHighlightedIndexToValue();
    }
    else {
      this.inputValue = '';
      this.highlightedIndex = 0;
    }
  }
  async handleIconClick(event) {
    event.stopPropagation();
    event.preventDefault();
    if (event.detail.icon === 'right') {
      if (!this.popoverVisible) {
        await this.showPopover();
      }
      else {
        await this.hidePopover();
      }
    }
    else {
      this.iconClick.emit();
    }
  }
  async handleEzChange(event) {
    event.stopPropagation();
    this.inputValue = event.detail;
    if (!this.popoverVisible && this.inputValue.length > 0) {
      await this.showPopover();
    }
    this.ezType.emit(this.inputValue);
    this.highlightedIndex = 0;
    this.filterOptions(this.inputValue);
  }
  async handleEzBlur(event) {
    var _a, _b;
    event.stopPropagation();
    if (((_a = this.value) === null || _a === void 0 ? void 0 : _a.label) !== this.inputValue) {
      this.inputValue = ((_b = this.value) === null || _b === void 0 ? void 0 : _b.label) || '';
    }
    this.ezBlur.emit(this.value);
  }
  filterOptions(searchTerm) {
    if (!this.options) {
      this.filteredOptions = [];
      return;
    }
    let currentOptions = [];
    if (!searchTerm || searchTerm.trim() === '') {
      currentOptions = currentOptions.concat([...this.options]);
    }
    else {
      const term = searchTerm.toLowerCase().trim();
      currentOptions = currentOptions.concat(this.options.filter(option => option.label.toLowerCase().includes(term) ||
        option.value.toLowerCase().includes(term)));
    }
    if (!this.suppressEmptyOption && currentOptions.length > 0) {
      currentOptions = [
        {
          value: null,
          label: this.textEmptyOption || "Selecione um item"
        },
        ...currentOptions
      ];
    }
    this.filteredOptions = currentOptions;
    this.setHighlightedIndexToValue();
    this.scrollToHighlightedOption();
  }
  scrollToHighlightedOption() {
    if (this.highlightedIndex < 0 || !this._listElem) {
      return;
    }
    const highlightedOption = this._listElem.children[this.highlightedIndex];
    if (highlightedOption) {
      highlightedOption.scrollIntoView({
        behavior: 'smooth',
        block: 'nearest',
        inline: 'start'
      });
    }
  }
  async selectOption(option) {
    if (!option || this.readonly || !this.enabled) {
      return;
    }
    await this.setValue(option);
  }
  async handleArrowUp() {
    var _a;
    if (!this.popoverVisible) {
      await this.showPopover();
      return;
    }
    const optionsLength = ((_a = this.filteredOptions) === null || _a === void 0 ? void 0 : _a.length) || 0;
    if (optionsLength <= 0 || this.highlightedIndex <= 0) {
      return;
    }
    this.highlightedIndex = Math.max(0, this.highlightedIndex - 1);
    this.scrollToHighlightedOption();
  }
  handleArrowDown() {
    var _a;
    if (!this.popoverVisible) {
      this.showPopover();
      return;
    }
    const optionsLength = ((_a = this.filteredOptions) === null || _a === void 0 ? void 0 : _a.length) || 0;
    if (optionsLength <= 0) {
      return;
    }
    this.highlightedIndex = Math.min(optionsLength - 1, this.highlightedIndex + 1);
    this.scrollToHighlightedOption();
  }
  async selectCurrentItem() {
    if (!this.popoverVisible || this.highlightedIndex < 0) {
      return;
    }
    if (this.hasSlotContent || this.filteredOptions.length === 0 || this.readonly || !this.enabled) {
      await this.hidePopover();
      return;
    }
    if (this.filteredOptions && this.filteredOptions[this.highlightedIndex]) {
      this.selectOption(this.filteredOptions[this.highlightedIndex]);
    }
  }
  handleVisibilityChange(event) {
    this.popoverVisible = event.detail;
    this.ezVisibilityChange.emit(this.popoverVisible);
  }
  checkSlotContent() {
    const slot = this._element.querySelector('slot') || this._element;
    if (slot instanceof HTMLSlotElement) {
      this.hasSlotContent = slot.assignedNodes().length > 0;
    }
    else {
      this.hasSlotContent = slot.children.length > 0;
    }
  }
  setHighlightedIndexToValue() {
    if (this.value && this.filteredOptions) {
      const index = this.filteredOptions.findIndex(opt => opt.value === this.value.value);
      if (index >= 0) {
        this.highlightedIndex = index;
        return;
      }
      this.highlightedIndex = 0;
    }
  }
  async handleDocumentClick(event) {
    const target = event.target;
    if (!this._element.contains(target) && !this._popoverElem.contains(target)) {
      await this.hidePopover();
    }
  }
  addInfoId() {
    const dataInfo = { id: 'embedded' };
    if (this._element) {
      ElementIDUtils.addIDInfo(this._element);
    }
    if (this._inputElem) {
      ElementIDUtils.addIDInfo(this._inputElem, 'classic-combo-box-input', dataInfo);
    }
    if (this._popoverElem) {
      ElementIDUtils.addIDInfo(this._popoverElem, 'classic-combo-box-popover', dataInfo);
    }
  }
  async initKeyboardManager() {
    this._keyboardManager = new KeyboardManager({ element: this._element, propagate: true });
    this._keyboardManager
      .bind("ArrowUp", () => this.handleArrowUp(), { propagate: false })
      .bind("ArrowDown", () => this.handleArrowDown(), { propagate: false })
      .bind("Enter", () => this.selectCurrentItem(), { propagate: false })
      .bind("Tab", () => this.selectCurrentItem())
      .bind("shift+Tab", () => this.selectCurrentItem())
      .bind("Escape", () => this.hidePopover());
  }
  async connectedCallback() {
    await this.initKeyboardManager();
    document.addEventListener('mouseup', this._boundHandleDocumentClick);
  }
  disconnectedCallback() {
    this._keyboardManager.unbindAllShortcutKeys();
    document.removeEventListener('mouseup', this._boundHandleDocumentClick);
  }
  componentWillLoad() {
    this.filterOptions('');
  }
  componentDidLoad() {
    this.addInfoId();
    this.checkSlotContent();
    if (this.value) {
      this.inputValue = this.value.label;
      this.setHighlightedIndexToValue();
    }
  }
  render() {
    var _a;
    return (h(Host, null, h("ez-classic-input", { ref: ref => this._inputElem = ref, name: this.name, label: this.label, placeholder: this.placeholder, value: this.inputValue, state: this.state, enabled: this.enabled, readonly: this.readonly || this.suppressSearch, leftIconName: this.iconName, leftIconTooltip: this.titleIcon, leftIconClickable: this.iconClickable, rightIconClickable: true, helpText: this.helpText, rightIconName: this.popoverVisible ? 'chevron-up' : 'chevron-down', onIconClick: this.handleIconClick.bind(this), onEzChange: this.handleEzChange.bind(this), onEzFocus: this.showPopover.bind(this), onEzBlur: this.handleEzBlur.bind(this) }), h("ez-popover-core", { ref: ref => this._popoverElem = ref, useAnchorSize: true, onEzVisibilityChange: this.handleVisibilityChange.bind(this), overlayType: "none", options: { verticalGap: 2, horizontalGap: 0 }, autoClose: false }, h("slot", { onSlotchange: this.checkSlotContent.bind(this) }), !this.hasSlotContent && (((_a = this.filteredOptions) === null || _a === void 0 ? void 0 : _a.length) > 0 ? (h("ul", { ref: ref => this._listElem = ref, tabIndex: -1 }, this.filteredOptions.map((option, index) => {
      var _a, _b;
      return (h("li", { key: (_a = option.value) !== null && _a !== void 0 ? _a : '__empty__', value: option.value, class: {
          'highlighted': this.highlightedIndex === index,
          'selected': ((_b = this.value) === null || _b === void 0 ? void 0 : _b.value) === option.value
        }, onMouseDown: () => this.selectOption(option) }, option.label));
    }))) : (h("span", { class: "no-results" }, "Nenhum resultado encontrado"))))));
  }
  get _element() { return getElement(this); }
  static get watchers() { return {
    "options": ["optionsChanged"],
    "value": ["valueChanged"]
  }; }
};
EzClassicComboBox.style = ezClassicComboBoxCss;

export { EzClassicComboBox as ez_classic_combo_box };
