'use strict';

var index = require('./index-BEF5cZxd.js');
var props = require('./props-CPENhBnM.js');
var constants = require('./constants-Dmmp9FHy.js');
var template = require('./template-Cj6PcLmR.js');
var helpers_types = require('./helpers.types-vap8QfRH.js');
var helpers = require('./helpers-DmI-ZOAH.js');
var attribute = require('./attribute-CH1-zDDl.js');
var accessibility = require('./accessibility-BQJmIVWV.js');
require('./gov.log-C5EH15b_.js');
require('./utils-NnC78QR3.js');
require('./sizes-D5zsw2g5.js');
require('./colors-DgrrxjsX.js');

const GovTabs = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.govChange = index.createEvent(this, "gov-change");
        this.triggerRefs = {};
        /**
         * Tabs type
         */
        this.type = "text";
        /**
         * Tabs size.
         */
        this.size = 'm';
        /**
         * Style variation of the tab chips.
         */
        this.color = "primary";
        /**
         * Tabs orientation
         */
        this.orientation = "horizontal";
        /**
         * Icon and description display direction
         */
        this.direction = 'row';
        this.controllers = [];
        this.focusIndex = 0;
        this.inheritedAttributes = {};
        this.h = template.govHost(this.host);
    }
    validateType(newValue) {
        props.validateProp(constants.TabTypes, newValue, constants.TabsClass.root);
    }
    validateColor(newValue) {
        props.validateProp(constants.TabColors, newValue, constants.TabsClass.root);
    }
    validateSize(newValue) {
        props.validateProp(constants.TabSizes, newValue, constants.TabsClass.root);
    }
    componentDidLoad() {
        this.attributeObserver = new attribute.AttributeObserver(this.host, (attributeName, newValue) => {
            this.onAriaAttributeChange(attributeName, newValue);
        });
        this.attributeObserver.startObserving(attribute.ariaAttributes);
    }
    componentWillLoad() {
        this.prepareControllers();
        this.validateSize(this.size);
        this.inheritedAttributes = accessibility.inheritAriaAttributes(this.host);
    }
    disconnectedCallback() {
        var _a;
        (_a = this.attributeObserver) === null || _a === void 0 ? void 0 : _a.stopObserving();
    }
    onAriaAttributeChange(attributeName, newValue) {
        this.host.removeAttribute(attributeName);
        this.inheritedAttributes = Object.assign(Object.assign({}, this.inheritedAttributes), { [attributeName]: newValue });
    }
    prepareControllers(skipDefault = false) {
        this.controllers = [];
        const promises = [];
        this.host.querySelectorAll(':scope > ' + constants.TabsItemClass.root).forEach((tab) => {
            const controlItem = Promise.all([
                tab.getIdentifier(),
                tab.getTriggerIdentifier(),
                tab.getDisableState()
            ]).then(([identifier, triggerIdentifier, disabled]) => {
                const isDefault = typeof tab.getAttribute("default") === "string";
                const iconStart = helpers.prepareIconFormat(tab.getAttribute('icon-start'));
                const iconEnd = helpers.prepareIconFormat(tab.getAttribute('icon-end'));
                return {
                    label: tab.getAttribute("label"),
                    direction: tab.getAttribute("direction"),
                    contentIdentifier: identifier,
                    disabled: disabled,
                    triggerIdentifier: triggerIdentifier,
                    element: tab,
                    active: false,
                    default: isDefault,
                    iconStart,
                    iconEnd
                };
            });
            promises.push(controlItem);
        });
        Promise.all(promises).then(controllers => {
            if (skipDefault === false) {
                let defaultTabIndex = controllers.findIndex(controller => controller.default);
                if (defaultTabIndex === -1)
                    defaultTabIndex = 0;
                this.focusIndex = defaultTabIndex;
                controllers[defaultTabIndex].active = true;
            }
            else if (this.focusIndex > -1 && helpers_types.hasOwnProperty(controllers, this.focusIndex)) {
                controllers[this.focusIndex].active = true;
            }
            const isWrongCombination = controllers.findIndex((controller) => controller.active && controller.disabled);
            if (isWrongCombination > -1) {
                controllers[isWrongCombination].active = false;
                const firstGoodTab = controllers.findIndex((controller) => !controller.disabled);
                if (firstGoodTab > -1) {
                    controllers[firstGoodTab].active = true;
                    this.focusIndex = firstGoodTab;
                }
            }
            this.controllers = [...controllers];
            this.reRender();
        });
    }
    setActiveByIdentifier(identifier) {
        const temp = [];
        this.controllers.map(item => {
            item.active = identifier === item.triggerIdentifier || identifier === item.contentIdentifier;
            temp.push(item);
        });
        this.controllers = [...temp];
    }
    reRender() {
        this.controllers.map(control => {
            control.element.setActiveStatus(control.active).catch();
        });
    }
    render() {
        return (index.h(index.Host, { key: '0b339dda9cd002b5548650f0f996d349842f4c8b', class: this.h.classes(constants.TabsClass.root), size: this.size, color: this.color, type: this.type, direction: this.direction, onKeyDown: this.onKeydownHandler.bind(this) }, index.h("div", Object.assign({ key: '683da4323be50ee97c0f2b666423308b2feb6ff3', class: constants.TabsClass.tabs, role: "tablist" }, this.inheritedAttributes), index.h("ul", { key: '0a255d6a8a57744c0636a41e567661775d450dee', class: constants.TabsClass.list }, this.controllers.map(control => (index.h("li", { class: constants.TabsClass.item }, this.type == "text" ? (index.h("button", { class: constants.TabsClass.btn, id: control.triggerIdentifier, role: "tab", type: "button", onClick: () => this.onSelectHandler(control), disabled: control.disabled, "aria-disabled": template.toBoolAttr(control.disabled), "aria-selected": template.toBoolAttr(control.active), "aria-controls": control.contentIdentifier, tabindex: control.active && !control.disabled ? 0 : -1, ref: el => (this.triggerRefs[control.triggerIdentifier] = el) }, control.iconStart ? (index.h("gov-icon", { name: control.iconStart.name, type: control.iconStart.type })) : null, control.label, control.iconEnd ? (index.h("gov-icon", { name: control.iconEnd.name, type: control.iconEnd.type })) : null)) : (index.h("gov-chip", { role: "tab", tag: 'button', identifier: control.triggerIdentifier, "aria-selected": template.booleanString(control.active), "aria-controls": control.contentIdentifier, focusable: control.active, disabled: control.disabled, color: this.color, size: this.size === "xs" ? "xs" : (this.size === "s" ? "s" : "m"), type: control.active ? "solid" : "outlined", ref: el => (this.triggerRefs[control.triggerIdentifier] = el), "on-gov-click": () => this.onSelectHandler(control) }, control.iconStart ? (index.h("gov-icon", { name: control.iconStart.name, type: control.iconStart.type, slot: "icon-start" })) : null, control.label, control.iconEnd ? (index.h("gov-icon", { name: control.iconEnd.name, type: control.iconEnd.type, slot: "icon-end" })) : null))))))), index.h("slot", { key: '367950fe8ebba21bbe73c51a0d4c33efbb33e093' })));
    }
    getCurrentTab() {
        return this.controllers.find(control => control.active) || null;
    }
    onSelectHandler(control) {
        const index = this.controllers.findIndex(t => t.triggerIdentifier === control.triggerIdentifier);
        this.focusIndex = index;
        this.setActiveByIdentifier(control.triggerIdentifier);
        this.reRender();
        this.govChange.emit(this.getCurrentTab().element);
    }
    onKeydownHandler(e) {
        const keyCode = e.keyCode;
        e.stopPropagation();
        this.goToPrevNext(keyCode);
    }
    goToPrevNext(keyCode) {
        if ([37, 38, 39, 40].includes(keyCode)) {
            if (false === (this.focusIndex >= 0 && this.focusIndex <= this.controllers.length - 1)) {
                return;
            }
            this.controllers[this.focusIndex].active = false;
            if (keyCode === 39 || keyCode === 40) {
                this.focusIndex++;
                if (this.focusIndex >= this.controllers.length) {
                    this.focusIndex = 0;
                }
                if (this.controllers[this.focusIndex].disabled) {
                    this.goToPrevNext(40);
                }
            }
            else if (keyCode === 37 || keyCode === 38) {
                this.focusIndex--;
                if (this.focusIndex < 0) {
                    this.focusIndex = this.controllers.length - 1;
                }
                if (this.controllers[this.focusIndex].disabled) {
                    this.goToPrevNext(38);
                }
            }
            if (this.focusIndex >= 0 && this.focusIndex <= this.controllers.length - 1) {
                const current = this.controllers[this.focusIndex];
                current.active = true;
                const trigger = this.triggerRefs[current.triggerIdentifier];
                if (trigger.nodeName.toLowerCase() === 'gov-chip') {
                    this.triggerRefs[current.triggerIdentifier].setFocus();
                }
                else {
                    this.triggerRefs[current.triggerIdentifier].focus();
                }
                this.controllers = [...this.controllers];
                this.reRender();
                this.govChange.emit(this.getCurrentTab().element);
            }
        }
    }
    /**
     * Regenerate tabs controllers
     */
    async refresh() {
        this.prepareControllers();
    }
    /**
     * Returns the currently selected tabs-item
     */
    async currentTab() {
        return this.getCurrentTab().element || null;
    }
    /**
     * Regenerate tabs controllers
     */
    async setActiveTab(identifier) {
        this.setActiveByIdentifier(identifier);
        this.reRender();
    }
    /**
     * Regenerate tabs controllers
     */
    async rerender() {
        this.prepareControllers(true);
    }
    get host() { return index.getElement(this); }
    static get watchers() { return {
        "type": ["validateType"],
        "color": ["validateColor"],
        "size": ["validateSize"]
    }; }
};

exports.gov_tabs = GovTabs;
//# sourceMappingURL=gov-tabs.entry.cjs.js.map

//# sourceMappingURL=gov-tabs.cjs.entry.js.map