import { h, Host } from "@stencil/core";
import { ElementIDUtils, StringUtils } from "@sankhyalabs/core";
export class EzTabselector {
  constructor() {
    this.setFocusedParam = (ev) => {
      if (ev.key === "Enter") {
        const selectedTab = this._processedTabs[this._focusedIndex];
        this.handleTabClick(selectedTab);
        ev.preventDefault();
        this.setFocusedTab(selectedTab.index);
      }
      else if (ev.key === "ArrowLeft" || ev.key === "ArrowRight") {
        let operator = undefined;
        if (ev.key === "ArrowLeft") {
          operator = false;
        }
        else if (ev.key === "ArrowRight") {
          operator = true;
        }
        else {
          return;
        }
        if (this._focusedIndex === undefined) {
          if (operator === false) {
            this._focusedIndex = this.selectedIndex !== undefined ? this.selectedIndex - 1 : undefined;
          }
          else {
            this._focusedIndex = this.selectedIndex !== undefined ? this.selectedIndex + 1 : undefined;
          }
        }
        else {
          if (operator === false) {
            this._focusedIndex = this._focusedIndex - 1;
          }
          else {
            this._focusedIndex = this._focusedIndex + 1;
          }
        }
        if (this._focusedIndex < 0) {
          this._focusedIndex = 0;
        }
        else if (this._focusedIndex > this._processedTabs.length - 1) {
          this._focusedIndex = this._processedTabs.length - 1;
        }
        this.setFocusedBtn(true, this._focusedIndex);
        this.setFocusedTab(this._focusedIndex);
      }
      else if (ev.key === "Tab" || ev.key === "Escape") {
        const currentTab = this._processedTabs[this.selectedIndex];
        this._focusedIndex = undefined;
        this.handleTabClick(currentTab);
        ev.preventDefault();
        this.setFocusedTab(this.selectedIndex);
      }
    };
    this._processedTabs = undefined;
    this.selectedIndex = undefined;
    this.selectedTab = undefined;
    this.tabs = undefined;
  }
  observeTabs(newValue, oldValue) {
    if (newValue && typeof newValue !== "string") {
      this._processedTabs = newValue;
      return;
    }
    if (newValue !== oldValue) {
      this.processesTabs();
    }
  }
  async goToTab(tabIndex, silent = false) {
    const tab = this._processedTabs.find(tab => tab.index === tabIndex);
    this.handleTabClick(tab, !silent);
  }
  handleTabClick(tab, emitChange = true) {
    this.selectedIndex = tab.index;
    this._focusedIndex = undefined;
    this.selectedTab = tab.tabKey;
    if (emitChange) {
      this.ezChange.emit(tab);
    }
    this.setFocusedBtn(false, tab.index);
  }
  componentWillLoad() {
    this.processesTabs();
  }
  processesTabs() {
    if (this.tabs) {
      if (Array.isArray(this.tabs)) {
        this._processedTabs = [...this.tabs];
      }
      else {
        this._processedTabs = [];
        this.tabs.split(",").forEach((label) => {
          label = label.trim();
          this._processedTabs.push({ label, tabKey: label, index: this._processedTabs.length });
          this.buildElementIdTab(this._processedTabs);
        });
      }
    }
    this._hostElem.querySelectorAll("ez-tab").forEach((elem) => {
      const tabKey = elem.getAttribute("tabKey");
      const label = elem.getAttribute("label");
      const leftIcon = elem.getAttribute("leftIcon");
      const rightIcon = elem.getAttribute("rightIcon");
      const tab = { label, tabKey, leftIcon, rightIcon, index: this._processedTabs.length };
      const content = elem.firstChild;
      if (content) {
        content.setAttribute("slot", "tab" + tab.index);
        this._hostElem.appendChild(content);
      }
      this._processedTabs.push(tab);
      this.buildElementIdTab(this._processedTabs);
    });
  }
  componentDidRender() {
    this.updateScroll();
  }
  componentDidLoad() {
    ElementIDUtils.addIDInfo(this._hostElem, "itemsSelector");
    this._hostElem.shadowRoot.querySelectorAll('button[name="tab-button"]').forEach((elem) => {
      var _a;
      const label = (_a = elem.querySelector('span.tab-label')) === null || _a === void 0 ? void 0 : _a.innerText;
      const dataInfo = { id: `${StringUtils.toCamelCase(label)}` };
      ElementIDUtils.addIDInfo(elem, "itemSelector", dataInfo);
    });
  }
  handleSlotChange(ev) {
    const slot = ev.target;
    const content = slot.assignedElements()[0];
    if (content) {
      content.style.marginLeft = "6px";
    }
  }
  scrollBackward() {
    const container = this._scrollContainer;
    if (container) {
      container.scrollLeft -= container.clientWidth;
    }
  }
  scrollFoward() {
    const container = this._scrollContainer;
    if (container) {
      let lastTab = null;
      container.querySelectorAll(".tab").forEach((tab) => {
        if (tab.getBoundingClientRect().right < container.clientWidth) {
          lastTab = tab;
        }
      });
      container.scrollLeft = lastTab.offsetLeft + lastTab.offsetWidth;
    }
  }
  updateScroll() {
    const container = this._scrollContainer;
    if (container) {
      const { scrollWidth, clientWidth, scrollLeft } = container;
      const remainingScroll = scrollWidth - clientWidth - Math.ceil(scrollLeft);
      this._startHidden = container.scrollLeft > 0;
      this._endHidden = remainingScroll > 0;
      if (this._startHidden) {
        this._backwardButton.classList.remove("hidden");
      }
      else {
        this._backwardButton.classList.add("hidden");
      }
      if (this._endHidden) {
        this._forwardButton.classList.remove("hidden");
      }
      else {
        this._forwardButton.classList.add("hidden");
      }
      const classNames = ["", "startHidden", "endHidden", "middle"];
      const currentClass = classNames[Number(this._startHidden) | Number(this._endHidden) << 1];
      classNames.forEach((name) => {
        if (name !== currentClass && container.classList.contains(name)) {
          container.classList.remove(name);
        }
      });
      if (currentClass && !container.classList.contains(currentClass)) {
        container.classList.add(currentClass);
      }
    }
  }
  domScrollHandler() {
    window.clearTimeout(this._scrollCallBack);
    this._scrollCallBack = window.setTimeout(() => { this.updateScroll(); }, 200);
  }
  setFocusedTab(index) {
    window.clearTimeout(this._scrollCallBackTest);
    this._scrollCallBackTest = window.setTimeout(() => {
      const tabtoscroll = this._scrollContainer.querySelector(`#tab${index}`);
      tabtoscroll.scrollIntoView();
    }, 200);
  }
  setFocusedBtn(visible, parameter) {
    const tabsButtons = this._scrollContainer.querySelectorAll(".tab");
    tabsButtons.forEach((el) => {
      el.classList.remove("is-focused");
      if (el.id === "tab" + parameter && visible) {
        el.classList.add("is-focused");
      }
      ;
    });
  }
  buildElementIdTab(tabs) {
    tabs.forEach(tab => {
      if (!tab.hasOwnProperty(ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME)) {
        const elemIdTabSelector = this._hostElem.getAttribute(ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME);
        const dataElementID = `${elemIdTabSelector}_${StringUtils.toCamelCase(tab.tabKey)}`;
        tab[ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME] = dataElementID;
      }
    });
  }
  render() {
    return (h(Host, null, h("button", { class: "backward-button", ref: (el) => this._backwardButton = el, onClick: () => this.scrollBackward() }), h("div", { class: "scroll", ref: (el) => this._scrollContainer = el, onScroll: () => this.domScrollHandler(), onKeyDown: (ev) => this.setFocusedParam(ev) }, this._processedTabs.map((tab, index) => {
      const tabId = "tab" + index;
      const isSelected = index === this.selectedIndex || (this.selectedTab && tab.tabKey === this.selectedTab);
      if (isSelected) {
        this.selectedTab = tab.tabKey;
        this.selectedIndex = index;
      }
      return h("button", { id: tabId, name: "tab-button", class: `tab${isSelected ? " is-active" : ""}`, onClick: () => this.handleTabClick(tab) }, tab.leftIcon && h("ez-icon", { iconName: tab.leftIcon, class: "left-icon" }), h("span", { class: "tab-label", title: tab.label }, tab.label), tab.rightIcon && h("ez-icon", { iconName: tab.rightIcon, class: "right-icon" }), h("slot", { name: tabId, onSlotchange: (ev) => { this.handleSlotChange(ev); } }));
    })), h("button", { class: "forward-button", ref: (el) => this._forwardButton = el, onClick: () => this.scrollFoward() })));
  }
  static get is() { return "ez-tabselector"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() {
    return {
      "$": ["ez-tabselector.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["ez-tabselector.css"]
    };
  }
  static get properties() {
    return {
      "selectedIndex": {
        "type": "number",
        "mutable": true,
        "complexType": {
          "original": "number",
          "resolved": "number",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define o index da aba selecionada."
        },
        "attribute": "selected-index",
        "reflect": true
      },
      "selectedTab": {
        "type": "string",
        "mutable": true,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define a aba selecionada."
        },
        "attribute": "selected-tab",
        "reflect": true
      },
      "tabs": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string | Array<Tab>",
          "resolved": "Tab[] | string",
          "references": {
            "Array": {
              "location": "global"
            },
            "Tab": {
              "location": "local"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define o nome das abas do componente.\nPodendo serem separadas por v\u00EDrgula \",\" ou em um Array de configura\u00E7\u00E3o."
        },
        "attribute": "tabs",
        "reflect": false
      }
    };
  }
  static get states() {
    return {
      "_processedTabs": {}
    };
  }
  static get events() {
    return [{
        "method": "ezChange",
        "name": "ezChange",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Emitido quando acontece a altera\u00E7\u00E3o de valor do componente."
        },
        "complexType": {
          "original": "Tab",
          "resolved": "Tab",
          "references": {
            "Tab": {
              "location": "local"
            }
          }
        }
      }];
  }
  static get methods() {
    return {
      "goToTab": {
        "complexType": {
          "signature": "(tabIndex: number, silent?: boolean) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": []
        }
      }
    };
  }
  static get elementRef() { return "_hostElem"; }
  static get watchers() {
    return [{
        "propName": "tabs",
        "methodName": "observeTabs"
      }];
  }
}
