import {
  getDeepActiveElement,
  getTabbableBoundary
} from "./chunk.UMIKFOMI.js";
import {
  scrollIntoView
} from "./chunk.WDWV53JP.js";
import {
  getAnimation,
  setDefaultAnimation
} from "./chunk.N4LHE3QK.js";
import {
  waitForEvent
} from "./chunk.B4BZKR24.js";
import {
  LocalizeController
} from "./chunk.X3FE7OHE.js";
import {
  watch
} from "./chunk.X2OQMWGY.js";
import {
  SolidElement,
  customElement
} from "./chunk.H53WQBDK.js";
import {
  animateTo,
  stopAnimations
} from "./chunk.HQWAKJBV.js";
import {
  __decorateClass
} from "./chunk.S3NI7NKU.js";

// src/components/dropdown/dropdown.ts
import { css, html } from "lit";

// src/internal/deep-closest-element.ts
function deepClosestElement(element, selector) {
  let current = element;
  while (current) {
    if (current.matches(selector)) {
      return current;
    }
    if (current.parentElement) {
      current = current.parentElement;
    } else if (current.parentNode instanceof ShadowRoot) {
      current = current.parentNode.host;
    } else {
      break;
    }
  }
  return null;
}

// src/components/dropdown/dropdown.ts
import { property, query } from "lit/decorators.js";
import cx from "classix";
var SdDropdown = class extends SolidElement {
  constructor() {
    super(...arguments);
    this.localize = new LocalizeController(this);
    this.open = false;
    this.rounded = false;
    this.placement = "bottom-start";
    this.disabled = false;
    this.stayOpenOnSelect = false;
    this.distance = 0;
    this.skidding = 0;
    this.noAutoSize = false;
    this.noFlip = false;
    this.hoist = false;
  }
  connectedCallback() {
    super.connectedCallback();
    this.handleMenuItemActivate = this.handleMenuItemActivate.bind(this);
    this.handlePanelSelect = this.handlePanelSelect.bind(this);
    this.handleKeyDown = this.handleKeyDown.bind(this);
    this.handleDocumentKeyDown = this.handleDocumentKeyDown.bind(this);
    this.handleDocumentMouseDown = this.handleDocumentMouseDown.bind(this);
    if (!this.containingElement) {
      this.containingElement = this;
    }
  }
  firstUpdated() {
    this.panel.hidden = !this.open;
    if (this.open) {
      this.addOpenListeners();
      this.popup.active = true;
    }
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    this.removeOpenListeners();
    this.hide();
  }
  /**
   * Slotted triggers can be arbitrary content. The accessible trigger is the tabbable element
   * within the slotted trigger. This could be the slotted element itself, a child of the slotted element,
   * or an element within the slotted elements shadow root.
   *
   * e.g. the accessible trigger of an <sd-6-22-0-button> is a <button> located inside its shadow root.
   *
   * To determine this, we assume the first tabbable element in the trigger slot is the "accessible trigger."
   * */
  getAccessibleTrigger() {
    const assignedElements = this.trigger.assignedElements({ flatten: true });
    const accessibleTrigger = assignedElements.find((el) => getTabbableBoundary(el).start);
    let target = null;
    if (accessibleTrigger) {
      switch (accessibleTrigger.tagName.toLowerCase()) {
        // Solid buttons have to update the internal button so it's announced correctly by screen readers
        case "sd-6-22-0-button":
        case "sd-6-22-0-icon-button":
          target = accessibleTrigger.button;
          break;
        case "sd-6-22-0-navigation-item":
          target = accessibleTrigger.button;
          break;
        default:
          target = accessibleTrigger;
      }
    }
    return target;
  }
  // Slotted triggers can be arbitrary content, but we need to connect them to the dropdown panel with `aria-haspopup` and
  // `aria-expanded`. These must be applied to the `accessible trigger`.
  updateAccessibleTrigger() {
    const target = this.getAccessibleTrigger();
    if (!target) return;
    target.setAttribute("aria-haspopup", "true");
    target.setAttribute("aria-expanded", this.open ? "true" : "false");
  }
  focusOnTrigger() {
    const trigger = this.getAccessibleTrigger();
    if (typeof (trigger == null ? void 0 : trigger.focus) === "function") {
      trigger.focus();
    }
  }
  getMenu() {
    return this.panel.assignedElements({ flatten: true }).find((el) => el.tagName.toLowerCase() === "sd-6-22-0-menu");
  }
  handleKeyDown(event) {
    if (this.open && event.key === "Escape") {
      event.stopPropagation();
      this.hide();
      this.focusOnTrigger();
    }
  }
  handleDocumentKeyDown(event) {
    var _a;
    if (event.key === "Tab") {
      if (this.open && ((_a = document.activeElement) == null ? void 0 : _a.tagName.toLowerCase()) === "sd-6-22-0-menu-item") {
        event.preventDefault();
        this.hide();
        this.focusOnTrigger();
        return;
      }
      setTimeout(() => {
        const activeElement = getDeepActiveElement();
        if (!activeElement || !this.containingElement || deepClosestElement(activeElement, this.containingElement.tagName.toLowerCase()) !== this.containingElement) {
          this.hide();
        }
      });
    }
  }
  handleDocumentMouseDown(event) {
    const path = event.composedPath();
    if (this.containingElement && !path.includes(this.containingElement)) {
      this.hide();
    }
  }
  handleMenuItemActivate(event) {
    const item = event.target;
    scrollIntoView(item, this.panel);
  }
  handlePanelSelect(event) {
    const target = event.target;
    if (!this.stayOpenOnSelect && target.tagName.toLowerCase() === "sd-6-22-0-menu") {
      this.hide();
      this.focusOnTrigger();
    }
  }
  handleTriggerClick() {
    if (this.open) {
      const menu = this.getMenu();
      if (menu) {
        const current = menu.getCurrentItem();
        current == null ? void 0 : current.classList.remove("menu-item-focus");
      }
      this.hide();
    } else {
      this.show();
    }
  }
  handleTriggerKeyDown(event) {
    if (event.key === "Escape" && this.open) {
      event.stopPropagation();
      this.focusOnTrigger();
      this.handleTriggerClick();
      return;
    }
    if ([" ", "Enter"].includes(event.key)) {
      event.preventDefault();
      this.handleTriggerClick();
      return;
    }
    const menu = this.getMenu();
    if (menu) {
      const menuItems = menu.defaultSlot.assignedElements({ flatten: true });
      const firstMenuItem = menuItems.find((item) => !item.disabled) || menuItems[0];
      const lastMenuItem = menuItems[menuItems.length - 1];
      if (["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) {
        event.preventDefault();
        if (!this.open) {
          this.show();
        }
        if (menuItems.length > 0) {
          requestAnimationFrame(() => {
            if (event.key === "ArrowDown" || event.key === "Home") {
              menu.setCurrentItem(firstMenuItem);
              firstMenuItem.focus();
              firstMenuItem.classList.add("menu-item-focus");
            }
            if (event.key === "ArrowUp" || event.key === "End") {
              menu.setCurrentItem(lastMenuItem);
              lastMenuItem.focus();
              lastMenuItem.classList.add("menu-item-focus");
            }
          });
        }
      }
    }
  }
  handleTriggerKeyUp(event) {
    if (event.key === " ") {
      event.preventDefault();
    }
  }
  handleTriggerSlotChange() {
    this.updateAccessibleTrigger();
  }
  /** Shows the dropdown panel. */
  async show() {
    if (this.open) {
      return void 0;
    }
    this.open = true;
    return waitForEvent(this, "sd-after-show");
  }
  /** Hides the dropdown panel */
  async hide() {
    if (!this.open) {
      return void 0;
    }
    this.open = false;
    return waitForEvent(this, "sd-after-hide");
  }
  /**
   * Instructs the dropdown menu to reposition. Useful when the position or size of the trigger changes when the menu
   * is activated.
   */
  reposition() {
    this.popup.reposition();
  }
  addOpenListeners() {
    this.panel.addEventListener("sd-activate", this.handleMenuItemActivate);
    this.panel.addEventListener("sd-6-22-0-select", this.handlePanelSelect);
    this.panel.addEventListener("keydown", this.handleKeyDown);
    document.addEventListener("keydown", this.handleDocumentKeyDown);
    document.addEventListener("mousedown", this.handleDocumentMouseDown);
  }
  removeOpenListeners() {
    if (this.panel) {
      this.panel.removeEventListener("sd-activate", this.handleMenuItemActivate);
      this.panel.removeEventListener("sd-6-22-0-select", this.handlePanelSelect);
      this.panel.removeEventListener("keydown", this.handleKeyDown);
    }
    document.removeEventListener("keydown", this.handleDocumentKeyDown);
    document.removeEventListener("mousedown", this.handleDocumentMouseDown);
  }
  async handleOpenChange() {
    if (this.disabled) {
      this.open = false;
      return;
    }
    this.updateAccessibleTrigger();
    if (this.open) {
      this.emit("sd-show");
      this.addOpenListeners();
      await stopAnimations(this);
      this.panel.hidden = false;
      this.popup.active = true;
      const { keyframes, options } = getAnimation(this, "dropdown.show", { dir: this.localize.dir() });
      await animateTo(this.popup.popup, keyframes, options);
      this.emit("sd-after-show");
    } else {
      this.emit("sd-hide");
      this.removeOpenListeners();
      await stopAnimations(this);
      const { keyframes, options } = getAnimation(this, "dropdown.hide", { dir: this.localize.dir() });
      await animateTo(this.popup.popup, keyframes, options);
      this.panel.hidden = true;
      this.popup.active = false;
      this.emit("sd-after-hide");
    }
  }
  render() {
    return html`<sd-6-22-0-popup part="base" id="dropdown" exportparts="
          popup:base__popup,
        " placement="${this.placement}" distance="${this.rounded && this.distance < 1 ? 1 : this.distance}" skidding="${this.skidding}" strategy="${this.hoist ? "fixed" : "absolute"}" ?flip="${!this.noFlip}" shift auto-size="vertical" auto-size-padding="10"><slot name="trigger" slot="anchor" part="trigger" class="block" @click="${this.handleTriggerClick}" @keydown="${this.handleTriggerKeyDown}" @keyup="${this.handleTriggerKeyUp}" @slotchange="${this.handleTriggerSlotChange}"></slot><slot part="panel" class="${cx(
      "panel-color-border border shadow sd-6-22-0-dropdown-color-background block",
      this.open ? "pointer-events-auto" : "pointer-events-none",
      this.rounded && "rounded-md"
    )}" aria-hidden="${this.open ? "false" : "true"}" aria-labelledby="dropdown"></slot></sd-6-22-0-popup>`;
  }
};
SdDropdown.styles = [
  ...SolidElement.styles,
  css`/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */@layer theme,base,components,utilities;
:host{display:inline-block}#dropdown::part(popup){z-index:var(--sd-z-index-dropdown,900)}#dropdown[data-current-placement^=top]::part(popup){transform-origin:bottom}#dropdown[data-current-placement^=bottom]::part(popup){transform-origin:top}#dropdown[data-current-placement^=left]::part(popup){transform-origin:100%}#dropdown[data-current-placement^=right]::part(popup){transform-origin:0}:host(:not([no-auto-size])) ::slotted(:not([slot=trigger])){overflow:auto;max-width:var(--auto-size-available-width)!important;max-height:var(--auto-size-available-height)!important}`
];
__decorateClass([
  query("#dropdown")
], SdDropdown.prototype, "popup", 2);
__decorateClass([
  query("[part=trigger]")
], SdDropdown.prototype, "trigger", 2);
__decorateClass([
  query("[part=panel]")
], SdDropdown.prototype, "panel", 2);
__decorateClass([
  property({ type: Boolean, reflect: true })
], SdDropdown.prototype, "open", 2);
__decorateClass([
  property({ type: Boolean, reflect: true })
], SdDropdown.prototype, "rounded", 2);
__decorateClass([
  property({ type: String, reflect: true })
], SdDropdown.prototype, "placement", 2);
__decorateClass([
  property({ type: Boolean, reflect: true })
], SdDropdown.prototype, "disabled", 2);
__decorateClass([
  property({ attribute: "stay-open-on-select", type: Boolean, reflect: true })
], SdDropdown.prototype, "stayOpenOnSelect", 2);
__decorateClass([
  property({ type: Object })
], SdDropdown.prototype, "containingElement", 2);
__decorateClass([
  property({ type: Number, reflect: true })
], SdDropdown.prototype, "distance", 2);
__decorateClass([
  property({ type: Number, reflect: true })
], SdDropdown.prototype, "skidding", 2);
__decorateClass([
  property({ type: Boolean, reflect: true, attribute: "no-auto-size" })
], SdDropdown.prototype, "noAutoSize", 2);
__decorateClass([
  property({ type: Boolean, reflect: true, attribute: "no-flip" })
], SdDropdown.prototype, "noFlip", 2);
__decorateClass([
  property({ type: Boolean, reflect: true })
], SdDropdown.prototype, "hoist", 2);
__decorateClass([
  watch("open", { waitUntilFirstUpdate: true })
], SdDropdown.prototype, "handleOpenChange", 1);
SdDropdown = __decorateClass([
  customElement("sd-6-22-0-dropdown")
], SdDropdown);
setDefaultAnimation("dropdown.show", {
  keyframes: [{ opacity: 0 }, { opacity: 1 }],
  options: { duration: "var(--sd-duration-medium, 300)", easing: "ease-in-out" }
});
setDefaultAnimation("dropdown.hide", {
  keyframes: [{ opacity: 1 }, { opacity: 0 }],
  options: { duration: "var(--sd-duration-fast, 150)", easing: "ease-in-out" }
});

export {
  SdDropdown
};
