import { Component, Event, h, State, Element, Prop, Listen, } from '@stencil/core';
import { TabNavigationTypes } from '../../types/TabNavigation';
export class TeliaTab {
  constructor() {
    /** State scroll used for toggling horizontal scroll shadow */
    this.scrollClasses = {};
    /** Array of slotted children */
    this.children = [];
    /** sets background on content */
    this.background = false;
    /** variant */
    this.variant = 'default';
    /** Controls wether the tabs should fill the entire available width */
    this.fullWidth = false;
    /** Tracking id is used to identify and count Component usage */
    this.dataTrackingId = 'telia-tab';
    this.componentClass = 'telia-tab';
    this.activeIndex = 0;
    this.isKeyPress = true;
    this.sideScrollAdjustmentSize = 200;
    this.onIntersection = (entries) => {
      const allEntriesVisible = entries.every(entry => entry.isIntersecting) &&
        entries.length === this.tabItems.length;
      if (allEntriesVisible) {
        this.scrollClasses = {};
        return;
      }
      entries.forEach(entry => {
        const entryIndex = Number(entry.target.children[0].getAttribute('data-index'));
        const isStartEntry = entryIndex === 0;
        const isLastEntry = entryIndex === this.tabItems.length - 1;
        this.scrollClasses = Object.assign(Object.assign(Object.assign({ 'telia-tab__wrapper--scroll-start': true }, this.scrollClasses), (isStartEntry && {
          'telia-tab__wrapper--scroll-end': !entry.isIntersecting,
        })), (isLastEntry && {
          'telia-tab__wrapper--scroll-start': !entry.isIntersecting,
        }));
      });
    };
  }
  handleInternalUpdate(e) {
    e.stopPropagation();
    this.createChildren();
  }
  handleTabNavigation(e) {
    const { location, key } = e.detail.value;
    const currentIndex = this.activeIndex;
    let nextIndex;
    this.isKeyPress = true;
    if (location > -1) {
      nextIndex = location;
      this.isKeyPress = false;
    }
    switch (key) {
      case TabNavigationTypes.ArrowLeft:
        if (currentIndex > 0) {
          nextIndex = currentIndex - 1;
        }
        else {
          nextIndex = this.children.length - 1;
        }
        break;
      case TabNavigationTypes.ArrowRight:
        if (currentIndex < this.children.length - 1) {
          nextIndex = currentIndex + 1;
        }
        else {
          nextIndex = 0;
        }
        break;
      case TabNavigationTypes.Home:
        nextIndex = 0;
        break;
      case TabNavigationTypes.End:
        nextIndex = this.children.length - 1;
        break;
    }
    this.activeIndex = nextIndex;
    this.children.forEach((child, index) => {
      child.active = index === nextIndex;
    });
    this.vocaTabChange.emit({ value: this.children[this.activeIndex].tabId });
    this.createChildren();
  }
  handleResize() {
    this.scrollToTarget(this.getActiveTabListItem());
  }
  componentWillLoad() {
    this.createChildren();
    this.findPreSelectedTab();
  }
  componentDidLoad() {
    this.tabItems = this.host.shadowRoot.querySelectorAll('telia-tab-header');
    const tablist = this.host.shadowRoot.querySelector('.telia-tab__list');
    this.observer = new IntersectionObserver(this.onIntersection, {
      threshold: [0.99],
      root: tablist,
    });
    this.tabItems.forEach(el => this.observer.observe(el));
    this.scrollToTarget(this.getActiveTabListItem());
  }
  disconnectedCallback() {
    var _a, _b;
    // if we have an intersection observer, disconnect it
    (_b = (_a = this.observer) === null || _a === void 0 ? void 0 : _a.disconnect) === null || _b === void 0 ? void 0 : _b.call(_a);
  }
  /**
   * Check if there is a pre-selected tab,
   * else set first tab as pre-selected
   * @private
   */
  findPreSelectedTab() {
    if (this.children.length === 0)
      return;
    /**
     * flag to indicate that an active tab
     * was found on render
     */
    let activePreSet = false;
    this.children.forEach((child, index) => {
      if (activePreSet) {
        /**
         * since flag is true
         * all other tabs should
         * be set to not active
         */
        child.active = false;
      }
      if (child.active) {
        activePreSet = true;
        this.activeIndex = index;
      }
    });
    if (this.activeIndex === 0) {
      this.children[this.activeIndex].active = true;
    }
  }
  /**
   * Will scroll tab list to keyboard focused tab header
   * @param target
   * @private
   */
  scrollToTarget(target) {
    var _a, _b;
    /**
     * scroll may not be available in test runner, so check existence before
     * proceeding. We can't use scrollIntoView() because Safari doesn't support
     * it fully.
     */
    if (typeof (target === null || target === void 0 ? void 0 : target.getBoundingClientRect) !== 'function' ||
      typeof ((_a = this.tabList) === null || _a === void 0 ? void 0 : _a.scroll) !== 'function') {
      return;
    }
    const targetRect = target.getBoundingClientRect();
    const wrapperRect = this.tabList.getBoundingClientRect();
    const wrapperWidth = this.tabList.clientWidth;
    const wrapperOffset = parseInt((_b = getComputedStyle(this.tabList)['border-width-left']) === null || _b === void 0 ? void 0 : _b.split('px')[0], 10);
    let offset = wrapperRect.left + (isNaN(wrapperOffset) ? 0 : wrapperOffset);
    let left;
    //Handle forward navigation
    if (targetRect.right > wrapperRect.right) {
      left = targetRect.left + this.tabList.scrollLeft;
      left = left + targetRect.width - wrapperWidth + wrapperWidth * 0.1;
      left = left - offset;
    }
    //Handle backwards navigation
    if (targetRect.left < wrapperRect.left) {
      left = targetRect.left + this.tabList.scrollLeft;
      left = left - wrapperWidth * 0.1;
      left = left - offset;
    }
    if (left !== undefined) {
      this.tabList.scroll({ left: left, behavior: 'smooth' });
    }
  }
  /**
   * Create child array
   * @private
   */
  createChildren() {
    this.children = [];
    let slotted = this.host.querySelectorAll('telia-tab-content');
    slotted.forEach(node => {
      if (node.nodeName.indexOf('TELIA-TAB') > -1) {
        this.children.push(node);
      }
    });
  }
  getActiveTabListItem() {
    var _a;
    return (_a = this.tabList) === null || _a === void 0 ? void 0 : _a.querySelector('telia-tab-header[active]');
  }
  handleScrollButtonClick(side) {
    const { scrollLeft } = this.tabList;
    const modifier = side === 'left'
      ? -this.sideScrollAdjustmentSize
      : this.sideScrollAdjustmentSize;
    this.tabList.scroll({ left: scrollLeft + modifier, behavior: 'smooth' });
  }
  renderScrollButton(side) {
    return (h("button", { class: `${this.componentClass}__scroll-button ${this.componentClass}__scroll-button--${side}`, onClick: () => this.handleScrollButtonClick(side) },
      h("telia-icon", { size: "md", name: `chevron-${side}` })));
  }
  render() {
    const classNames = {
      'telia-tab': true,
      [`telia-tab--${this.variant}`]: !!this.variant,
      [`telia-tab--full-width`]: this.fullWidth,
    };
    return (h("div", { class: classNames },
      h("telia-vst", { dataTrackingId: this.dataTrackingId }),
      h("div", { class: "telia-tab__container" },
        h("div", { class: Object.assign({ 'telia-tab__wrapper': true }, this.scrollClasses) },
          h("div", { ref: el => {
              this.tabList = el;
            }, class: "telia-tab__list", role: "tablist" }, this.children.map((child, index) => {
            return (h("telia-tab-header", { onFocusin: e => {
                this.scrollToTarget(e.target);
              }, tabId: child.tabId, icon: child.icon, name: child.name, active: child.active, "data-testid": child.dataTestid, "data-index": index, "is-key-press": this.isKeyPress, variant: this.variant }, child.name));
          })),
          this.renderScrollButton('left'),
          this.renderScrollButton('right'))),
      h("div", { class: {
          'telia-tab__content': true,
          'telia-tab__content--light-background': this.background,
        }, role: "presentation" },
        h("div", { class: "telia-tab__container", role: "presentation" },
          h("slot", null)))));
  }
  static get is() { return "telia-tab"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() { return {
    "$": ["telia-tab.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["telia-tab.css"]
  }; }
  static get properties() { return {
    "background": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "sets background on content"
      },
      "attribute": "background",
      "reflect": false,
      "defaultValue": "false"
    },
    "variant": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "TabVariant",
        "resolved": "\"contained\" | \"contained-on-negative\" | \"default\" | \"inline\" | \"light\" | \"light-wide\" | \"wide\"",
        "references": {
          "TabVariant": {
            "location": "import",
            "path": "../../types/TabVariants"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "variant"
      },
      "attribute": "variant",
      "reflect": false,
      "defaultValue": "'default'"
    },
    "fullWidth": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Controls wether the tabs should fill the entire available width"
      },
      "attribute": "full-width",
      "reflect": false,
      "defaultValue": "false"
    }
  }; }
  static get states() { return {
    "scrollClasses": {},
    "children": {}
  }; }
  static get events() { return [{
      "method": "vocaTabChange",
      "name": "vocaTabChange",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "Emitted when tab has changed. Value is id of active telia-tab-content"
      },
      "complexType": {
        "original": "TabChangeDetail",
        "resolved": "{ value: string; }",
        "references": {
          "TabChangeDetail": {
            "location": "local"
          }
        }
      }
    }]; }
  static get elementRef() { return "host"; }
  static get listeners() { return [{
      "name": "vocaTabContentNameChange",
      "method": "handleInternalUpdate",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "vocaInternalTabNavigation",
      "method": "handleTabNavigation",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "resize",
      "method": "handleResize",
      "target": "window",
      "capture": false,
      "passive": true
    }]; }
}
