import {
  debounce
} from "./chunk.UVI5HHLF.js";
import {
  scrollIntoView
} from "./chunk.WDWV53JP.js";
import {
  LocalizeController
} from "./chunk.X3FE7OHE.js";
import {
  SolidElement,
  customElement
} from "./chunk.H53WQBDK.js";
import {
  __decorateClass,
  __spreadValues
} from "./chunk.S3NI7NKU.js";

// src/components/tab-group/tab-group.ts
import { css, html } from "lit";
import { ifDefined } from "lit/directives/if-defined.js";
import { property, query, state } from "lit/decorators.js";
import cx from "classix";
var SdTabGroup = class extends SolidElement {
  constructor() {
    super(...arguments);
    this.localize = new LocalizeController(this);
    this.tabs = [];
    this.panels = [];
    this.hasScrollControls = false;
    this.variant = "default";
    this.canScroll = {
      left: false,
      right: false
    };
    this.activation = "auto";
  }
  connectedCallback() {
    const whenAllDefined = Promise.all([
      customElements.whenDefined("sd-tab"),
      customElements.whenDefined("sd-tab-panel")
    ]);
    super.connectedCallback();
    this.resizeObserver = new ResizeObserver(() => {
      this.updateScrollControls();
      this.repositionIndicator();
    });
    this.mutationObserver = new MutationObserver((mutations) => {
      if (mutations.some((m) => !["aria-labelledby", "aria-controls"].includes(m.attributeName))) {
        setTimeout(() => this.setAriaLabels());
      }
      if (mutations.some((m) => m.attributeName === "disabled")) {
        this.syncTabsAndPanels();
      }
    });
    this.updateComplete.then(() => {
      this.syncTabsAndPanels();
      this.mutationObserver.observe(this, { attributes: true, childList: true, subtree: true });
      this.resizeObserver.observe(this.nav);
      this.nav.addEventListener("scroll", () => this.handleScroll());
      whenAllDefined.then(() => {
        const intersectionObserver = new IntersectionObserver((entries, observer) => {
          var _a;
          if (entries[0].intersectionRatio > 0) {
            this.setAriaLabels();
            this.setActiveTab((_a = this.activeTab) != null ? _a : this.tabs[0], { emitEvents: false });
            observer.unobserve(entries[0].target);
          }
        });
        intersectionObserver.observe(this.tabGroup);
      });
    });
  }
  updated(changedProperties) {
    const oldValue = changedProperties.get("canScroll");
    if (!oldValue && this.canScroll) {
      this.handleScroll();
    }
  }
  disconnectedCallback() {
    var _a;
    this.mutationObserver.disconnect();
    if (this.nav) {
      (_a = this.resizeObserver) == null ? void 0 : _a.unobserve(this.nav);
    }
  }
  getAllTabs(options = { includeDisabled: true }) {
    const slot = this.shadowRoot.querySelector('slot[name="nav"]');
    return Array.from(slot.assignedElements()).map((el) => el.tagName.toLocaleLowerCase() === "sd-tab" ? el : el.querySelector("sd-tab")).filter((el) => {
      return el && options.includeDisabled ? el.tagName.toLowerCase() === "sd-tab" : el.tagName.toLowerCase() === "sd-tab" && !el.disabled;
    });
  }
  getAllPanels() {
    return [...this.body.assignedElements()].filter((el) => el.tagName.toLowerCase() === "sd-tab-panel");
  }
  getActiveTab() {
    return this.tabs.find((t) => t.matches(":focus"));
  }
  handleClick(event) {
    const target = event.target;
    const tab = target.closest("sd-tab");
    const tabGroup = tab == null ? void 0 : tab.closest("sd-tab-group");
    if (tabGroup !== this) {
      return;
    }
    if (tab !== null) {
      this.setActiveTab(tab, { scrollBehavior: "smooth" });
    }
  }
  handleKeyDown(event) {
    const target = event.target;
    const tab = target.closest("sd-tab");
    const tabGroup = tab == null ? void 0 : tab.closest("sd-tab-group");
    if (tabGroup !== this) {
      return;
    }
    if (["Enter", " "].includes(event.key)) {
      if (tab !== null) {
        this.setActiveTab(tab, { scrollBehavior: "smooth" });
        event.preventDefault();
      }
    }
    if (["Tab"].includes(event.key)) {
      const index = this.tabs.indexOf(this.getActiveTab());
      const nextTab = this.tabs[index + 1];
      if (tab !== null && nextTab) {
        scrollIntoView(nextTab, this.nav, "horizontal");
      }
    }
    if (["Shift", "Tab"].includes(event.key)) {
      const index = this.tabs.indexOf(this.getActiveTab());
      const previousTab = this.tabs[index - 1];
      if (tab !== null && previousTab) {
        scrollIntoView(previousTab, this.nav, "horizontal");
      }
    }
    if (["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End"].includes(event.key)) {
      const activeEl = this.tabs.find((t) => t.matches(":focus"));
      const isRtl = this.localize.dir() === "rtl";
      if ((activeEl == null ? void 0 : activeEl.tagName.toLowerCase()) === "sd-tab") {
        let index = this.tabs.indexOf(activeEl);
        if (event.key === "Home") {
          index = 0;
        } else if (event.key === "End") {
          index = this.tabs.length - 1;
        } else if (event.key === (isRtl ? "ArrowRight" : "ArrowLeft") || event.key === "ArrowUp") {
          index--;
        } else if (event.key === (isRtl ? "ArrowLeft" : "ArrowRight") || event.key === "ArrowDown") {
          index++;
        }
        if (index < 0) {
          index = this.tabs.length - 1;
        }
        if (index > this.tabs.length - 1) {
          index = 0;
        }
        this.tabs[index].focus({ preventScroll: true });
        if (this.activation === "auto") {
          this.setActiveTab(this.tabs[index], { scrollBehavior: "smooth" });
        }
        scrollIntoView(this.tabs[index], this.nav, "horizontal");
        event.preventDefault();
      }
    }
  }
  handleScroll() {
    this.canScroll = {
      left: this.nav.scrollLeft > 0,
      right: this.nav.scrollLeft + this.nav.clientWidth < this.nav.scrollWidth - 1
    };
  }
  handleScrollToStart() {
    this.nav.scroll({
      left: this.localize.dir() === "rtl" ? this.nav.scrollLeft + this.nav.clientWidth : this.nav.scrollLeft - this.nav.clientWidth,
      behavior: "smooth"
    });
  }
  handleScrollToEnd() {
    this.nav.scroll({
      left: this.localize.dir() === "rtl" ? this.nav.scrollLeft - this.nav.clientWidth : this.nav.scrollLeft + this.nav.clientWidth,
      behavior: "smooth"
    });
  }
  /** Sets the active tab and panel. */
  setActiveTab(tab, options) {
    options = __spreadValues({
      emitEvents: true,
      scrollBehavior: "auto"
    }, options);
    if (tab !== this.activeTab && !tab.disabled && !tab.visuallyDisabled) {
      const previousTab = this.activeTab;
      this.activeTab = tab;
      this.tabs.map((el) => el.active = el === this.activeTab);
      this.panels.map((el) => {
        var _a;
        return el.active = el.name === ((_a = this.activeTab) == null ? void 0 : _a.panel);
      });
      this.repositionIndicator();
      scrollIntoView(this.activeTab, this.nav, "horizontal", options.scrollBehavior);
      if (options.emitEvents) {
        if (previousTab) {
          this.emit("sd-tab-hide", { detail: { name: previousTab.panel } });
        }
        this.emit("sd-tab-show", { detail: { name: this.activeTab.panel } });
      }
    }
  }
  setAriaLabels() {
    this.tabs.forEach((tab) => {
      const panel = this.panels.find((el) => el.name === tab.panel);
      if (panel) {
        tab.setAttribute("aria-controls", panel.getAttribute("id"));
      }
    });
  }
  // This stores tabs and panels so we can refer to a cache instead of calling querySelectorAll() multiple times.
  syncTabsAndPanels() {
    this.tabs = this.getAllTabs({ includeDisabled: false });
    this.panels = this.getAllPanels();
    this.repositionIndicator();
    this.panels.forEach((panel) => {
      panel.tabIndex = 0;
    });
    this.updateComplete.then(() => this.updateScrollControls());
    if (this.tabs.length !== 0 && this.tabs[0].variant === "container") {
      this.variant = "container";
    }
  }
  updateScrollControls() {
    this.hasScrollControls = this.nav.scrollWidth > this.nav.clientWidth;
  }
  async repositionIndicator() {
    await this.updateComplete;
    const currentTab = this.activeTab;
    const indicator = this.indicator;
    const tabsContainer = this.tabsContainer;
    if (!currentTab || !indicator || !tabsContainer || currentTab.variant === "container") return;
    const tabRect = currentTab.getBoundingClientRect();
    const containerRect = tabsContainer.getBoundingClientRect();
    const isCentered = getComputedStyle(tabsContainer).justifyContent === "center";
    const containerCenter = containerRect.left + containerRect.width / 2;
    const tabCenter = tabRect.left + tabRect.width / 2;
    const width = currentTab.offsetWidth;
    const offsetX = isCentered ? tabCenter - containerCenter : tabRect.left - containerRect.left;
    indicator.style.width = `${width}px`;
    indicator.style.transform = `translateX(${offsetX}px)`;
  }
  /** Shows the specified tab panel. */
  show(panel) {
    const tab = this.tabs.find((el) => el.panel === panel);
    if (tab) {
      this.setActiveTab(tab, { scrollBehavior: "smooth" });
    }
  }
  render() {
    var _a;
    const isRtl = this.localize.dir() === "rtl";
    return html`<div part="base" class="${cx("flex flex-col rounded-none")}" @click="${this.handleClick}" @keydown="${this.handleKeyDown}"><div part="nav" class="${cx(this.hasScrollControls && "relative py-0 px-12")}">${this.hasScrollControls ? html`<button part="scroll-button--start" exportparts="base:scroll-button__base" tabindex="-1" aria-hidden="true" disabled="${ifDefined(!this.canScroll.left || void 0)}" class="${cx(
      "sd-interactive flex items-center justify-center absolute top-0 bottom-0 left-0 !outline-offset-0 border-b border-neutral-400 z-10",
      this.localize.dir() === "rtl" && "left-auto right-0"
    )}" @click="${this.handleScrollToStart}"><sd-icon library="_internal" name="${isRtl ? "chevron-up" : "chevron-down"}" label="previous" class="${cx("h-6 w-12 rotate-90 grid place-items-center")}"></sd-icon></button>` : ""}<div part="scroll-container" class="flex overflow-x-auto focus-visible:focus-outline !outline-offset-0"><div part="tabs" class="${cx("flex flex-auto relative flex-row")}" role="tablist">${((_a = this.activeTab) == null ? void 0 : _a.variant) !== "container" ? html`<div part="active-tab-indicator" id="indicator" class="absolute h-1 bg-accent bottom-0 transition-[transform,width] duration-medium ease-in-out z-30 navigable__current-indicator-height navigable__current-indicator-border-radius"></div>` : ""}<div part="separation" class="border-neutral-400 absolute w-full h-0.25 bottom-0 border-b z-10"></div><slot name="nav" @slotchange="${this.syncTabsAndPanels}"></slot></div></div>${this.hasScrollControls ? html`<button part="scroll-button--end" exportparts="base:scroll-button__base" tabindex="-1" aria-hidden="true" disabled="${ifDefined(!this.canScroll.right || void 0)}" class="${cx(
      "sd-interactive flex items-center justify-center absolute top-0 bottom-0 right-0 !outline-offset-0 border-b border-neutral-400 z-10",
      this.localize.dir() === "rtl" && "right-auto left-0"
    )}" @click="${this.handleScrollToEnd}"><sd-icon library="_internal" name="${isRtl ? "chevron-down" : "chevron-up"}" label="next" class="${cx("h-6 w-12 rotate-90 grid place-items-center")}"></sd-icon></button>` : ""}</div><slot part="body" class="${cx("block auto py-8 px-6", this.variant === "container" && "border border-neutral-400 border-t-0")}" @slotchange="${this.syncTabsAndPanels}"></slot></div>`;
  }
};
SdTabGroup.styles = [
  ...SolidElement.styles,
  css`/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */@layer theme,base,components,utilities;
:host{box-sizing:border-box;display:block}[part=scroll-container]{scrollbar-width:none}[part=scroll-container]::-webkit-scrollbar{height:calc(var(--sd-spacing-1) * 0);width:calc(var(--sd-spacing-1) * 0)}::slotted(sd-tab-panel){--padding:1rem 0}::slotted(sd-tab-panel:focus-visible){outline-style:solid;outline-offset:2px;outline-width:2px;outline-color:var(--outline-color-primary)}`
];
__decorateClass([
  query("[part=base]")
], SdTabGroup.prototype, "tabGroup", 2);
__decorateClass([
  query("[part=body]")
], SdTabGroup.prototype, "body", 2);
__decorateClass([
  query("[part=scroll-container]")
], SdTabGroup.prototype, "nav", 2);
__decorateClass([
  query("[part=active-tab-indicator]")
], SdTabGroup.prototype, "indicator", 2);
__decorateClass([
  query('[part="tabs"]')
], SdTabGroup.prototype, "tabsContainer", 2);
__decorateClass([
  state()
], SdTabGroup.prototype, "hasScrollControls", 2);
__decorateClass([
  state()
], SdTabGroup.prototype, "variant", 2);
__decorateClass([
  state()
], SdTabGroup.prototype, "canScroll", 2);
__decorateClass([
  property({ type: String, reflect: true })
], SdTabGroup.prototype, "activation", 2);
__decorateClass([
  debounce(20)
], SdTabGroup.prototype, "handleScroll", 1);
SdTabGroup = __decorateClass([
  customElement("sd-tab-group")
], SdTabGroup);

export {
  SdTabGroup
};
