import { LitElement, css, html } from "lit";
import { customElement, state } from "lit/decorators.js";
import { renderButton } from "../button.js";
import { errorGuard } from "../../../decorators/error-guard.js";
import { withTailwindStyles } from "../../../decorators/with-tailwind-styles.js";
import "../atomic-tab-popover/atomic-tab-popover.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 AtomicTabBar extends LitElement {
    get tabsFromSlot() {
        const isTab = (tagName)=>/atomic-.+-tab$/i.test(tagName) || /tab-button$/i.test(tagName);
        return Array.from(this.querySelectorAll('*')).filter((element)=>isTab(element.tagName));
    }
    get selectedTab() {
        return this.tabsFromSlot.find((tab)=>tab.active);
    }
    get slotContentWidth() {
        return this.tabsFromSlot.reduce((total, el)=>total + parseFloat(window.getComputedStyle(el).getPropertyValue('width')), 0);
    }
    get containerWidth() {
        return parseFloat(window.getComputedStyle(this).getPropertyValue('width'));
    }
    get isOverflow() {
        return this.slotContentWidth > this.containerWidth;
    }
    get tabPopover() {
        return this.shadowRoot?.querySelector('atomic-tab-popover');
    }
    get popoverWidth() {
        return this.tabPopover ? this.getElementWidth(this.tabPopover) : 0;
    }
    get overflowingTabs() {
        const containerRelativeRightPosition = this.getBoundingClientRect().right;
        const selectedTabRelativeRightPosition = this.selectedTab?.getBoundingClientRect().right;
        return this.tabsFromSlot.filter((element)=>{
            const isBeforeSelectedTab = selectedTabRelativeRightPosition ? selectedTabRelativeRightPosition > element.getBoundingClientRect().right : false;
            const minimumWidthNeeded = isBeforeSelectedTab ? this.popoverWidth + this.getElementWidth(this.selectedTab) : this.popoverWidth;
            const rightPositionLimit = this.isOverflow ? containerRelativeRightPosition - minimumWidthNeeded : containerRelativeRightPosition;
            return element.getBoundingClientRect().right > rightPositionLimit && !element.active;
        });
    }
    get displayedTabs() {
        return this.tabsFromSlot.filter((el)=>!this.overflowingTabs.includes(el));
    }
    get lastDisplayedTab() {
        const displayedTabs = this.displayedTabs;
        return displayedTabs[displayedTabs.length - 1];
    }
    get lastDisplayedTabRightPosition() {
        return this.lastDisplayedTab.getBoundingClientRect().right - this.getBoundingClientRect().left;
    }
    connectedCallback() {
        super.connectedCallback();
        this.addEventListener('atomic/tabRendered', this.handleTabRendered);
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        this.resizeObserver?.disconnect();
        this.removeEventListener('atomic/tabRendered', this.handleTabRendered);
    }
    firstUpdated() {
        this.resizeObserver = new ResizeObserver(()=>{
            this.updateTabsDisplay();
        });
        this.resizeObserver.observe(this);
    }
    willUpdate() {
        this.updateTabsDisplay();
    }
    render() {
        return html`
      <slot></slot>
      <atomic-tab-popover
        exportparts="popover-button, value-label, arrow-icon, backdrop overflow-tabs"
      >
        ${this.popoverTabs}
      </atomic-tab-popover>
    `;
    }
    updatePopoverPosition() {
        this.tabPopover?.style.setProperty('left', `${this.displayedTabs.length ? this.lastDisplayedTabRightPosition : 0}px`);
    }
    constructor(...args){
        super(...args), this.popoverTabs = [], this.handleTabRendered = (event)=>{
            event.stopPropagation();
            this.updatePopoverTabs();
        }, this.getElementWidth = (element)=>element ? parseFloat(window.getComputedStyle(element).getPropertyValue('width')) : 0, this.hideElement = (el)=>{
            el.style.visibility = 'hidden';
            el.ariaHidden = 'true';
        }, this.showElement = (el)=>{
            el.style.visibility = 'visible';
            el.ariaHidden = 'false';
        }, this.updateTabVisibility = (tabs, isVisible)=>{
            const tabCount = this.tabsFromSlot.length;
            tabs.forEach((tab, index)=>{
                tab.style.setProperty('order', String(isVisible ? index + 1 : tabCount - tabs.length + index + 1));
                if (isVisible) this.showElement(tab);
                else this.hideElement(tab);
            });
        }, this.updatePopoverTabs = ()=>{
            this.popoverTabs = this.overflowingTabs.map((tab)=>html`
        <li>
          ${renderButton({
                    props: {
                        part: 'popover-tab',
                        style: 'text-transparent',
                        class: 'w-full truncate rounded px-4 py-2 text-left font-semibold',
                        ariaLabel: tab.label,
                        title: tab.label,
                        onClick: ()=>{
                            tab.select();
                            this.updatePopoverTabs();
                            this.tabPopover?.toggle();
                        }
                    }
                })(html`${tab.label}`)}
        </li>
      `);
        }, this.setTabButtonMaxWidth = ()=>{
            this.displayedTabs.forEach((tab)=>{
                tab.style.setProperty('max-width', `calc(100% - ${this.popoverWidth}px)`);
            });
        }, this.updateTabsDisplay = ()=>{
            this.updateTabVisibility(this.overflowingTabs, false);
            this.updateTabVisibility(this.displayedTabs, true);
            this.setTabButtonMaxWidth();
            this.updatePopoverPosition();
            this.updatePopoverTabs();
            this.tabPopover?.setButtonVisibility(!!this.overflowingTabs.length);
        };
    }
}
AtomicTabBar.styles = css`/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */:host{display:flex;overflow-x:visible;position:relative;white-space:nowrap;width:100%}`;
_ts_decorate([
    state(),
    _ts_metadata("design:type", Array)
], AtomicTabBar.prototype, "popoverTabs", void 0);
_ts_decorate([
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicTabBar.prototype, "render", null);
AtomicTabBar = _ts_decorate([
    customElement('atomic-tab-bar'),
    withTailwindStyles
], AtomicTabBar);
export { AtomicTabBar };
