import { buildTab } from "@coveo/headless/insight";
import { LitElement, css, html } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { when } from "lit/directives/when.js";
import { createAppLoadedListener } from "../../common/interface/store.js";
import { dispatchTabLoaded } from "../../common/tabs/tab-common.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 { randomID } from "../../../utils/utils.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 AtomicInsightTab extends LitElement {
    connectedCallback() {
        super.connectedCallback();
        this.addEventListener('click', this.handleClick);
        this.addEventListener('keydown', this.handleKeydown);
        this.updateHostAttributes();
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        this.removeEventListener('click', this.handleClick);
        this.removeEventListener('keydown', this.handleKeydown);
    }
    initialize() {
        this.tab = buildTab(this.bindings.engine, {
            options: {
                expression: this.expression,
                id: this.tabId
            },
            initialState: {
                isActive: this.active
            }
        });
        createAppLoadedListener(this.bindings.store, (isAppLoaded)=>{
            this.isAppLoaded = isAppLoaded;
        });
    }
    select() {
        this.tab?.select();
    }
    updated() {
        if (this.tabState) {
            this.active = this.tabState.isActive;
            this.updateHostAttributes();
        }
        dispatchTabLoaded(this);
    }
    updateHostAttributes() {
        this.setAttribute('role', 'tab');
        this.setAttribute('aria-selected', this.active ? 'true' : 'false');
        this.tabIndex = this.active ? 0 : -1;
    }
    render() {
        return html`<span part="tab" title=${this.label}
      >${when(this.isAppLoaded, ()=>this.label)}</span
    >`;
    }
    constructor(...args){
        super(...args), this.label = 'no-label', this.active = false, this.isAppLoaded = false, this.tabId = randomID('insight-tab'), this.handleClick = ()=>{
            this.tab?.select();
        }, this.handleKeydown = (event)=>{
            if ('Enter' === event.key || ' ' === event.key) {
                event.preventDefault();
                this.tab?.select();
                return;
            }
            const tablist = this.closest('[role="tablist"]');
            if (!tablist) return;
            const tabs = Array.from(tablist.querySelectorAll('[role="tab"]'));
            const currentIndex = tabs.indexOf(this);
            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.forEach((tab, index)=>{
                    tab.tabIndex = index === nextIndex ? 0 : -1;
                });
                tabs[nextIndex].focus();
            }
        };
    }
}
AtomicInsightTab.styles = css`/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,::backdrop,:after,:before{--tw-font-weight:initial}}}:host{cursor:pointer;display:flex}:host:focus-visible{--tw-outline-style:none;outline-style:none}[part=tab]{margin-right:calc(var(--spacing,.25rem)*6);margin-top:calc(var(--spacing,.25rem)*1);padding-bottom:calc(var(--spacing,.25rem)*3);--tw-font-weight:var(--font-weight-semibold,600);color:var(--atomic-on-background);font-weight:var(--font-weight-semibold,600);max-width:150px;overflow:hidden;position:relative;text-overflow:ellipsis}:host(:focus-visible) [part=tab],:host(:hover) [part=tab]{color:var(--atomic-primary)}:host([active]) [part=tab]:after{background-color:var(--atomic-primary);border-radius:var(--atomic-border-radius);bottom:calc(var(--spacing,.25rem)*0);content:"";display:block;height:calc(var(--spacing,.25rem)*1);position:absolute;width:100%}@property --tw-font-weight{syntax:"*";inherits:false}`;
_ts_decorate([
    property({
        type: String,
        reflect: true
    })
], AtomicInsightTab.prototype, "label", void 0);
_ts_decorate([
    property({
        type: Boolean,
        reflect: true,
        attribute: 'active'
    })
], AtomicInsightTab.prototype, "active", void 0);
_ts_decorate([
    property({
        type: String
    }),
    _ts_metadata("design:type", String)
], AtomicInsightTab.prototype, "expression", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof InsightBindings ? Object : InsightBindings)
], AtomicInsightTab.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicInsightTab.prototype, "error", void 0);
_ts_decorate([
    bindStateToController('tab'),
    state(),
    _ts_metadata("design:type", "u" < typeof InsightTabState ? Object : InsightTabState)
], AtomicInsightTab.prototype, "tabState", void 0);
_ts_decorate([
    state()
], AtomicInsightTab.prototype, "isAppLoaded", void 0);
_ts_decorate([
    errorGuard(),
    bindingGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicInsightTab.prototype, "render", null);
AtomicInsightTab = _ts_decorate([
    customElement('atomic-insight-tab'),
    bindings(),
    withTailwindStyles
], AtomicInsightTab);
export { AtomicInsightTab };
