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 ezTagInputCss = ":host{--ez-tag-input--background-color:var(--color--gray-70, #FFFFFF);--ez-tag-input--border-color-default:var(--color--gray-200, #D2D2D3);--ez-tag-input--border-color-focused:var(--color--gray-300, #A4A5A7);--ez-tag-input--border-color-error:var(--color--red-600, #BD0025);--ez-tag-input--border-color-success:var(--color--green-600, #157A00);--ez-tag-input--border-color-warning:var(--color--yellow-600, #EFB103);--ez-tag-input--border-radius:var(--border--radius-8, 8px);--ez-tag-input--padding:var(--space--12, 12px);--ez-tag-input--gap:var(--space--8, 8px);--ez-tag-input--label-color:var(--color--petroleum-900, #141B27);--ez-tag-input--label-font-weight:var(--font-weight--regular, 400);--ez-tag-input--input-color:var(--color--petroleum-900, #141B27);--ez-tag-input--input-font-size:var(--font-size--default, 14px);--ez-tag-input--placeholder-color:var(--color--gray-400, #77777A);--ez-tag-input--background-color-disabled:var(--color--gray-90, #EAEAEA);--ez-tag-input--helptext-color:var(--color--ocean-green-1000, #00281D);display:flex;flex-direction:column;align-items:flex-start;box-sizing:border-box;font-family:var(--font--pattern, 'Roboto', Arial, sans-serif);font-size:var(--font-size--default, 14px);color:var(--color--ocean-green-1000, #00281D);width:100%;border:none;padding:0}label{display:block;width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;line-height:var(--line-height--20, 20px);color:var(--ez-tag-input--label-color);font-weight:var(--ez-tag-input--label-font-weight)}.tag-input__container{display:flex;flex-wrap:wrap;align-items:center;width:100%;box-sizing:border-box;gap:var(--ez-tag-input--gap);padding:var(--ez-tag-input--padding);margin:var(--space--4, 4px) 0;background-color:var(--ez-tag-input--background-color);border-radius:var(--ez-tag-input--border-radius);transition:box-shadow 0.2s cubic-bezier(0.4, 0, 0.2, 1)}.tag-input__container,.tag-input__container[data-state=\"default\"]{box-shadow:0 0 0 1px var(--ez-tag-input--border-color-default)}.tag-input__container[data-state=\"error\"]{box-shadow:0 0 0 var(--space--2, 2px) var(--ez-tag-input--border-color-error)}.tag-input__container[data-state=\"success\"]{box-shadow:0 0 0 var(--space--2, 2px) var(--ez-tag-input--border-color-success)}.tag-input__container[data-state=\"warning\"]{box-shadow:0 0 0 var(--space--2, 2px) var(--ez-tag-input--border-color-warning)}.tag-input__container:focus-within{box-shadow:0 0 0 var(--space--2, 2px) var(--ez-tag-input--border-color-focused)}input{flex:1;height:var(--space--24, 24px);background:transparent;border:none;outline:none;color:var(--ez-tag-input--input-color);font-family:var(--font--pattern, 'Roboto');font-size:var(--ez-tag-input--input-font-size);font-weight:var(--font-weight--regular, 400);line-height:var(--line-height--20, 20px)}input::placeholder{color:var(--ez-tag-input--placeholder-color)}.tag-input__container[data-disabled=\"true\"]{cursor:not-allowed;background:var(--ez-tag-input--background-color-disabled);box-shadow:0 0 0 1px var(--ez-tag-input--border-color-default)}.tag-input__container[data-disabled=\"true\"]>*{cursor:not-allowed}input:read-only .tag-input__container>*{cursor:default}@keyframes ez-helptext-fadein{from{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:translateY(0)}}span{font-size:var(--font-size--xsmall, 10px);line-height:var(--line-height--16, 16px);overflow:hidden;text-overflow:ellipsis;animation:ez-helptext-fadein 0.3s ease;color:var(--ez-tag-input--helptext-color)}";

const EzTagInput = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.ezChange = createEvent(this, "ezChange", 7);
    this.ezTagAdded = createEvent(this, "ezTagAdded", 7);
    this.ezTagRemoved = createEvent(this, "ezTagRemoved", 7);
    this.ezFocus = createEvent(this, "ezFocus", 7);
    this.ezBlur = createEvent(this, "ezBlur", 7);
    this.ezValidationError = createEvent(this, "ezValidationError", 7);
    this.ezType = createEvent(this, "ezType", 7);
    this.handleInputChange = (event) => {
      const target = event.target;
      this._inputElement.value = target.value;
      this.ezType.emit(this._inputElement.value);
    };
    this.handleInputKeyDown = (event) => {
      if (event.key === 'Backspace' && this._inputElement.value === '' && this.tags.length > 0 && !this.suppressBackspaceToRemove) {
        this.handleRemoveTag(this.tags[this.tags.length - 1]);
      }
    };
    this.handleInputFocus = () => {
      this.ezFocus.emit(this.tags);
    };
    this.handleInputBlur = () => {
      this.ezBlur.emit(this.tags);
    };
    this.handleTagClick = (tag, index) => {
      if (this.enabled && !this.readonly) {
        this.handleRemoveTag(tag);
        this.updateTagFocus(index);
      }
    };
    this.handleClearInput = () => {
      this._inputElement.value = '';
    };
    this.label = '';
    this.placeholder = '';
    this.helpText = undefined;
    this.enabled = true;
    this.readonly = false;
    this.name = undefined;
    this.tags = [];
    this.maxTagLength = undefined;
    this.maxTags = undefined;
    this.allowDuplicates = false;
    this.state = "default";
    this.validator = undefined;
    this.suppressTagsKeyboardNavigation = false;
    this.suppressBackspaceToRemove = false;
  }
  /** Aplica o foco no campo */
  async setFocus(option) {
    if (option === null || option === void 0 ? void 0 : option.selectText) {
      this._inputElement.select();
    }
    if (!(option === null || option === void 0 ? void 0 : option.preventScroll)) {
      this._inputElement.scrollIntoView({ behavior: "smooth", block: "center" });
    }
    this._inputElement.focus({ preventScroll: true });
  }
  /** Remove o foco do campo */
  async setBlur() {
    this._inputElement.blur();
  }
  /** Adiciona uma tag programaticamente */
  async addTag(tag) {
    return this.handleAddTag(tag);
  }
  /** Remove uma tag programaticamente */
  async removeTag(tag) {
    return this.handleRemoveTag(tag);
  }
  /** Limpa todas as tags */
  async clearTags() {
    this.tags = [];
    this.ezChange.emit([...this.tags]);
  }
  addInfoId() {
    if (this._element) {
      ElementIDUtils.addIDInfo(this._element);
    }
    if (this._inputElement) {
      const dataInfo = { id: 'embedded' };
      ElementIDUtils.addIDInfo(this._inputElement, 'tag-input', dataInfo);
    }
  }
  initializeKeyboardManager() {
    this._keyboardManager = new KeyboardManager({
      propagate: true,
      element: this._element,
    })
      .bind("Enter", () => this.handleAddCurrentTag())
      .bind("Tab", () => this.handleAddCurrentTag())
      .bind("Escape", () => this.handleClearInput())
      .bind("ArrowLeft", () => this.handlePreviousTagFocus())
      .bind("ArrowRight", () => this.handleNextTagFocus());
  }
  handleAddCurrentTag() {
    if (this._inputElement.value.trim()) {
      const success = this.handleAddTag(this._inputElement.value);
      if (success) {
        this._inputElement.value = '';
      }
      return success;
    }
    return false;
  }
  handleAddTag(tag) {
    const parsedTag = tag.trim();
    if (!this.enabled || this.readonly) {
      return false;
    }
    if (!parsedTag || parsedTag.length === 0) {
      return false;
    }
    if (this.maxTagLength && parsedTag.length > this.maxTagLength) {
      return false;
    }
    if (this.maxTags && this.tags.length >= this.maxTags) {
      return false;
    }
    if (!this.allowDuplicates && this.tags.includes(parsedTag)) {
      return false;
    }
    if (this.validator) {
      const validationResult = this.validator(parsedTag, [...this.tags]);
      if (validationResult === false) {
        this.ezValidationError.emit({ tag: parsedTag, error: undefined });
        return false;
      }
      if (typeof validationResult === 'string') {
        this.ezValidationError.emit({ tag: parsedTag, error: validationResult });
        return false;
      }
    }
    this.tags = [...this.tags, parsedTag];
    this.ezChange.emit([...this.tags]);
    this.ezTagAdded.emit(parsedTag);
    return true;
  }
  async updateTagFocus(lastIndex) {
    var _a;
    if (!((_a = this.tags) === null || _a === void 0 ? void 0 : _a.length) || this.suppressTagsKeyboardNavigation) {
      await this.setFocus();
      return;
    }
    if (!lastIndex) {
      return;
    }
    const nextIndex = lastIndex - 1;
    const tagElement = this._element.shadowRoot.querySelector(`#tag-${nextIndex}`);
    if (tagElement) {
      await tagElement.setFocus();
    }
  }
  getCurrentActiveTagIndex() {
    var _a;
    const currentActiveTag = this._element.shadowRoot.activeElement;
    if (!((_a = this.tags) === null || _a === void 0 ? void 0 : _a.length) || currentActiveTag.tagName.toLowerCase() !== 'ez-chip') {
      return null;
    }
    const currentIndex = parseInt(currentActiveTag.id.split('-')[1], 10);
    if (Number.isNaN(currentIndex) || currentIndex < 0 || currentIndex >= this.tags.length) {
      return null;
    }
    return currentIndex;
  }
  async setTagFocus(tagIndex) {
    const tagElement = this._element.shadowRoot.querySelector(`#tag-${tagIndex}`);
    if (tagElement) {
      await tagElement.setFocus();
    }
  }
  async handlePreviousTagFocus() {
    if (this.suppressTagsKeyboardNavigation || !this.enabled || this.readonly) {
      return;
    }
    if (this._element.shadowRoot.activeElement === this._inputElement) {
      await this.setTagFocus(this.tags.length - 1);
      return;
    }
    const currentIndex = this.getCurrentActiveTagIndex();
    if (currentIndex === null) {
      await this.setFocus();
      return;
    }
    if (currentIndex === 0) {
      return;
    }
    await this.setTagFocus(currentIndex - 1);
  }
  async handleNextTagFocus() {
    if (this.suppressTagsKeyboardNavigation || !this.enabled || this.readonly) {
      return;
    }
    const currentIndex = this.getCurrentActiveTagIndex();
    if (currentIndex === null || currentIndex >= this.tags.length - 1) {
      await this.setFocus();
      return;
    }
    await this.setTagFocus(currentIndex + 1);
  }
  handleRemoveTag(tagToRemove) {
    if (!this.enabled || this.readonly) {
      return false;
    }
    const tagIndex = this.tags.indexOf(tagToRemove);
    if (tagIndex === -1) {
      return false;
    }
    this.tags = this.tags.filter(tag => tag !== tagToRemove);
    this.ezChange.emit([...this.tags]);
    this.ezTagRemoved.emit(tagToRemove);
    return true;
  }
  async componentWillLoad() {
    if (!this.tags) {
      this.tags = [];
    }
  }
  componentDidLoad() {
    this.addInfoId();
    this.initializeKeyboardManager();
  }
  disconnectedCallback() {
    var _a;
    (_a = this._keyboardManager) === null || _a === void 0 ? void 0 : _a.unbindAllShortcutKeys();
  }
  render() {
    return (h(Host, null, h("label", { htmlFor: this.name }, this.label), h("div", { class: "tag-input__container", "data-state": this.state, "data-disabled": (!this.enabled).toString(), onClick: () => this.setFocus({ preventScroll: true }) }, this.tags.map((tag, index) => (h("ez-chip", { key: `tag-${index}`, id: `tag-${index}`, label: tag, enabled: this.enabled && !this.readonly, removePosition: this.enabled && !this.readonly ? "right" : undefined, mode: "label", onRemoveChip: () => this.handleTagClick(tag, index), tabIndex: (this.suppressTagsKeyboardNavigation || !this.enabled || this.readonly) ? -1 : 0, disableAutoUpdateValue: true, removeWithKeyboard: true }))), h("input", { ref: (el) => this._inputElement = el, id: this.name, type: "text", placeholder: this.placeholder, disabled: !this.enabled, readonly: this.readonly, maxlength: this.maxTagLength, onInput: this.handleInputChange, onKeyDown: this.handleInputKeyDown, onFocus: this.handleInputFocus, onBlur: this.handleInputBlur })), this.helpText && (h("span", { title: this.helpText }, this.helpText))));
  }
  get _element() { return getElement(this); }
};
EzTagInput.style = ezTagInputCss;

export { EzTagInput as ez_tag_input };
