import { buildTab, buildTabManager } from "@coveo/headless";
import { LitElement, html } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import "../../common/atomic-tab-button/atomic-tab-button.js";
import { booleanConverter } from "../../../converters/boolean-converter.js";
import { bindStateToController } from "../../../decorators/bind-state.js";
import { bindingGuard } from "../../../decorators/binding-guard.js";
import { bindings } from "../../../decorators/bindings.js";
import { errorGuard } from "../../../decorators/error-guard.js";
import { withTailwindStyles } from "../../../decorators/with-tailwind-styles.js";
import atomic_tab_manager_tw_css from "./atomic-tab-manager.tw.css.js";
import "../../common/atomic-tab-bar/atomic-tab-bar.js";
function _ts_decorate(decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
    else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function _ts_metadata(k, v) {
    if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
}
class AtomicTabManager extends LitElement {
    initialize() {
        this.tabManager = buildTabManager(this.bindings.engine);
        const tabElements = Array.from(this.querySelectorAll('atomic-tab'));
        if (0 === tabElements.length) {
            this.error = new Error('The "atomic-tab-manager" element requires at least one "atomic-tab" child.');
            return;
        }
        tabElements.forEach((tabElement)=>{
            const name = tabElement.getAttribute('name') || '';
            const expression = tabElement.getAttribute('expression') ?? '';
            const label = tabElement.getAttribute('label') || '';
            if (!name) {
                this.error = new Error('The "name" attribute must be defined on all "atomic-tab" children.');
                return;
            }
            const tabController = buildTab(this.bindings.engine, {
                options: {
                    expression,
                    id: name,
                    clearFiltersOnTabChange: this.clearFiltersOnTabChange
                }
            });
            this.tabs.push({
                label,
                name,
                tabController
            });
        });
    }
    render() {
        return html`
      <atomic-tab-bar
        exportparts="popover-button, value-label, arrow-icon, backdrop, overflow-tabs, popover-tab"
      >
        <div
          role="tablist"
          aria-label="tab-area"
          part="tab-area"
          class="border-neutral mb-2 flex w-full flex-row border-b"
          @keydown=${this.handleTablistKeydown}
        >
          ${this.tabs.map((tab)=>{
            const isActive = this.tabManagerState.activeTab === tab.name;
            return html`<atomic-tab-button
              .label=${this.bindings.i18n.t(tab.label, {
                defaultValue: tab.label
            })}
              .active=${isActive}
              .select=${()=>{
                if (!tab.tabController.state.isActive) tab.tabController.select();
            }}
            ></atomic-tab-button>`;
        })}
        </div>
      </atomic-tab-bar>
    `;
    }
    handleTablistKeydown(event) {
        const tabs = Array.from(event.currentTarget.querySelectorAll('[role="tab"]'));
        const currentIndex = tabs.indexOf(event.target);
        if (-1 === currentIndex) return;
        let nextIndex = null;
        if ('ArrowRight' === event.key) nextIndex = (currentIndex + 1) % tabs.length;
        else if ('ArrowLeft' === event.key) nextIndex = (currentIndex - 1 + tabs.length) % tabs.length;
        else if ('Home' === event.key) nextIndex = 0;
        else if ('End' === event.key) nextIndex = tabs.length - 1;
        if (null !== nextIndex) {
            event.preventDefault();
            tabs[nextIndex].focus();
        }
    }
    constructor(...args){
        super(...args), this.tabs = [], this.clearFiltersOnTabChange = false;
    }
}
AtomicTabManager.styles = atomic_tab_manager_tw_css;
_ts_decorate([
    bindStateToController('tabManager'),
    state(),
    _ts_metadata("design:type", "u" < typeof TabManagerState ? Object : TabManagerState)
], AtomicTabManager.prototype, "tabManagerState", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicTabManager.prototype, "error", void 0);
_ts_decorate([
    property({
        type: Boolean,
        converter: booleanConverter,
        attribute: 'clear-filters-on-tab-change'
    })
], AtomicTabManager.prototype, "clearFiltersOnTabChange", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicTabManager.prototype, "render", null);
AtomicTabManager = _ts_decorate([
    customElement('atomic-tab-manager'),
    bindings(),
    withTailwindStyles
], AtomicTabManager);
export { AtomicTabManager };
