import _ from "./icon.js";
import I from "./resize-observer.js";
import { n as h, C as P } from "../chunks/lib-cortex-element.CVMmyPMC.js";
import { c as C } from "../chunks/component.styles.CRO4Odto.js";
import { c as O } from "../chunks/animate.El-MpOws.js";
import { c as w } from "../chunks/custom-element.L4WJXn1j.js";
import { L as E } from "../chunks/i18n.BABe9hN4.js";
import { c as b } from "../chunks/math.DqTA6ya4.js";
import { w as m } from "../chunks/watch.BCJD77bD.js";
import { c as x } from "../chunks/dom.0RpWet6y.js";
import { i as z, x as g } from "../chunks/lit-element.jLBm65_O.js";
import { r as v } from "../chunks/state.CSDxrqLd.js";
import { t as L } from "../chunks/event-options.CYHYGOd8.js";
import { e as S } from "../chunks/query.BBf1UFkC.js";
import { e as u } from "../chunks/class-map.BiVq-cVR.js";
import { c as M } from "../chunks/repeat.DbF2p5ae.js";
import { o as k } from "../chunks/style-map.llVFPd__.js";
import { n as $ } from "../chunks/when.Dr1es41R.js";
import T from "./tooltip.js";
import { C as A } from "../chunks/typography.DJC_UXgs.js";
import { H as R } from "../chunks/slot.j5oheLJC.js";
const N = (e, t) => {
  let i = 0;
  return function(...s) {
    window.clearTimeout(i), i = window.setTimeout(() => {
      e.call(this, ...s);
    }, t);
  };
}, y = (e, t, i) => {
  const s = e[t];
  e[t] = function(...o) {
    s.call(this, ...o), i.call(this, s, ...o);
  };
}, U = "onscrollend" in window;
if (!U) {
  const e = /* @__PURE__ */ new Set(), t = /* @__PURE__ */ new WeakMap(), i = (o) => {
    for (const n of o.changedTouches)
      e.add(n.identifier);
  }, s = (o) => {
    for (const n of o.changedTouches)
      e.delete(n.identifier);
  };
  document.addEventListener("touchstart", i, !0), document.addEventListener("touchend", s, !0), document.addEventListener("touchcancel", s, !0), y(
    EventTarget.prototype,
    "addEventListener",
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    function(o, n) {
      if (n !== "scrollend")
        return;
      const r = N(() => {
        e.size ? r() : this.dispatchEvent(new Event("scrollend"));
      }, 100);
      o.call(this, "scroll", r, { passive: !0 }), t.set(this, r);
    }
  ), y(
    EventTarget.prototype,
    "removeEventListener",
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    function(o, n) {
      if (n !== "scrollend")
        return;
      const r = t.get(this);
      r && o.call(this, "scroll", r, {
        passive: !0
      });
    }
  );
}
const D = z`:host{display:block}.share-option-list-item{cursor:pointer;align-items:center;gap:var(--cx-spacing-3x-small);flex-direction:column;justify-content:center;display:flex}.share-option-list-item--disabled{cursor:not-allowed;pointer-events:none;opacity:.5}.share-option-list-item__icon{border-radius:var(--cx-border-radius-medium);border:1px solid var(--cx-color-neutral-200);height:var(--item-size,3.5rem);width:var(--item-size,3.5rem);justify-content:center;align-items:center;display:flex}.share-option-list-item--selected .share-option-list-item__icon{border-color:var(--cx-color-primary)}.share-option-list-item__icon cx-icon{--font-size:var(--item-font-size,2rem)}.share-option-list-item--selected .share-option-list-item__label{--color:var(--cx-color-primary);--font-weight:var(--cx-font-weight-semibold)}`;
var B = Object.defineProperty, j = Object.getOwnPropertyDescriptor, p = (e, t, i, s) => {
  for (var o = s > 1 ? void 0 : s ? j(t, i) : t, n = e.length - 1, r; n >= 0; n--)
    (r = e[n]) && (o = (s ? r(t, i, o) : r(o)) || o);
  return s && o && B(t, i, o), o;
};
let d = class extends P {
  constructor() {
    super(...arguments), this.hasSlotController = new R(this, "[default]"), this.disabled = !1, this.icon = "", this.tooltip = "", this.selected = !1, this.value = "", this.processedIcon = "";
  }
  get isSVG() {
    return this.icon.startsWith("<svg");
  }
  handleIconChange() {
    if (this.isSVG) {
      const e = encodeURIComponent(this.icon).replace(/'/g, "%27").replace(/"/g, "%22");
      this.processedIcon = `data:image/svg+xml;charset=utf-8,${e}`;
    }
  }
  handleClick() {
    this.emit("cx-share-option-list-item-selected", {
      detail: {
        value: this.value
      }
    });
  }
  render() {
    const e = this.hasSlotController.test("[default]");
    return g`<div part="base" class=${u({
      "share-option-list-item": !0,
      "share-option-list-item--disabled": this.disabled,
      "share-option-list-item--selected": this.selected
    })} @click=${this.handleClick}><cx-tooltip content=${this.tooltip} ?disabled=${this.disabled || !e}><div class="share-option-list-item__icon">${$(
      this.isSVG,
      () => g`<cx-icon src=${this.processedIcon}></cx-icon>`,
      () => g`<cx-icon name=${this.icon}></cx-icon>`
    )}</div><cx-typography class="share-option-list-item__label" variant="small"><slot></slot></cx-typography></cx-tooltip></div>`;
  }
};
d.styles = [C, D];
d.dependencies = {
  "cx-icon": _,
  "cx-tooltip": T,
  "cx-typography": A
};
p([
  h({ reflect: !0, type: Boolean })
], d.prototype, "disabled", 2);
p([
  h({ reflect: !0, type: String })
], d.prototype, "icon", 2);
p([
  h({ reflect: !0, type: String })
], d.prototype, "tooltip", 2);
p([
  h({ reflect: !0, type: Boolean })
], d.prototype, "selected", 2);
p([
  h({ reflect: !0, type: String })
], d.prototype, "value", 2);
p([
  v()
], d.prototype, "processedIcon", 2);
p([
  m("icon")
], d.prototype, "handleIconChange", 1);
d = p([
  w("cx-share-option-list-item")
], d);
const V = z`:host{--border:none;--border-radius:var(--cx-border-radius-small);--height:100%;--item-size:3.5rem;--item-font-size:2rem;--scroll-hint:0px;--slide-gap:var(--cx-spacing-medium,1rem);height:var(--height);width:100%;display:flex}.share-option-list{gap:var(--cx-spacing-medium);align-items:center;min-width:100%;min-height:100%;display:grid;position:relative}.share-option-list--horizontal{grid-template-columns:minmax(2rem,max-content) 1fr minmax(2rem,max-content);grid-template-areas:".slides."}.share-option-list--vertical{grid-template-rows:minmax(2rem,max-content) 1fr minmax(2rem,max-content);grid-template-areas:".""slides""."}.share-option-list__placeholder{opacity:0;pointer-events:none;z-index:-1;grid-area:slides;width:100%;height:100%;position:absolute;top:0;left:0}.share-option-list__slides{height:100%;width:min(100%, var(--width));overscroll-behavior-x:contain;scrollbar-width:none;border-radius:var(--cx-border-radius-small);--slide-size:calc((100% - (var(--slides-per-page) - 1) * var(--slide-gap)) / var(--slides-per-page));grid-area:slides;justify-self:start;align-items:center;display:grid;overflow:auto}.share-option-list__slides--horizontal{grid-auto-flow:column;grid-auto-columns:var(--slide-size);column-gap:var(--slide-gap);scroll-snap-type:x mandatory;scroll-padding-inline:var(--scroll-hint);padding-inline:var(--scroll-hint);grid-auto-rows:100%;overflow-y:hidden}.share-option-list__slides--vertical{grid-auto-columns:100%;grid-auto-flow:row;grid-auto-rows:var(--slide-size);row-gap:var(--slide-gap);scroll-snap-type:y mandatory;scroll-padding-block:var(--scroll-hint);padding-block:var(--scroll-hint);overflow-x:hidden}.share-option-list__navigation{--font-size:var(--cx-font-size-x-large);font-size:var(--font-size);z-index:1;justify-content:space-between;align-items:center;display:flex;position:absolute}.share-option-list__navigation--horizontal{width:100%;height:0;padding:0 var(--cx-spacing-small);left:0;transform:translateY(-50%)}.share-option-list__navigation--vertical{width:0;height:100%;padding:var(--cx-spacing-small) 0;flex-direction:column;top:0;left:50%;transform:translate(-50%)}.share-option-list__navigation-button{border-radius:var(--cx-border-radius-circle);font-size:inherit;color:var(--cx-color-neutral-600);cursor:pointer;transition:var(--cx-transition-medium) color;appearance:none;background:0 0;border:none;flex:none;align-items:center;padding:0;display:flex}.share-option-list__navigation-button--disabled{opacity:.5;cursor:default}.share-option-list__navigation-button--disabled::part(base){pointer-events:none}.share-option-list__navigation-button--hidden{opacity:0;pointer-events:none}.share-option-list__navigation-button--previous{grid-area:1/1}.share-option-list__navigation-button--next{grid-area:1/3}.share-option-list__slides:focus-visible,.share-option-list__navigation-button:focus-visible{outline:var(--cx-focus-ring);outline-offset:var(--cx-focus-ring-offset)}`;
var G = Object.defineProperty, H = Object.getOwnPropertyDescriptor, a = (e, t, i, s) => {
  for (var o = s > 1 ? void 0 : s ? H(t, i) : t, n = e.length - 1, r; n >= 0; n--)
    (r = e[n]) && (o = (s ? r(t, i, o) : r(o)) || o);
  return s && o && G(t, i, o), o;
};
let l = class extends P {
  constructor() {
    super(...arguments), this.data = [], this.navigation = void 0, this.orientation = "horizontal", this.slidesPerPage = 1, this.slidesPerMove = 1, this.selectedItem = "", this.currentSlide = 0, this.activeSlide = 0, this.scrolling = !1, this.calculatedSlidesPerPage = 0, this.localize = new E(this), this.pendingSlideChange = !1, this.slideObserver = null, this.slidesCache = null, this.handleSlotChange = (e) => {
      this.invalidateSlidesCache(), e.some(
        (i) => [...i.addedNodes, ...i.removedNodes].some(
          (s) => this.isShareOptionListItem(s)
        )
      ) && this.initializeSlides(), this.requestUpdate();
    };
  }
  runConnectedCallback() {
    this.setAttribute("role", "region"), this.setAttribute("aria-label", this.localize.term("share"));
  }
  connectedUpdatedCallback() {
    this.initializeSlides(this.currentSlide), this.mutationObserver = new MutationObserver(this.handleSlotChange), this.mutationObserver.observe(this.scrollContainer, {
      childList: !0,
      subtree: !0
    });
  }
  disconnectedCallback() {
    super.disconnectedCallback(), this.mutationObserver?.disconnect();
  }
  willUpdate(e) {
    (e.has("slidesPerMove") || e.has("slidesPerPage")) && (this.slidesPerMove = Math.min(this.slidesPerMove, this.slidesPerPage));
  }
  async calculateSlidesPerPage() {
    await this.updateComplete;
    const e = x(
      getComputedStyle(this).getPropertyValue("--item-size")
    );
    if (!this.placeholderEl || !this.data.length || !e) {
      this.calculatedSlidesPerPage = this.slidesPerPage;
      return;
    }
    const t = x(
      getComputedStyle(this).getPropertyValue("--slide-gap")
    ), i = this.placeholderEl.getBoundingClientRect().width, s = Math.max(
      1,
      Math.floor((i + t) / (e + t))
    );
    this.calculatedSlidesPerPage = Math.min(
      this.slidesPerPage,
      s,
      this.data.length
    );
  }
  getPageCount() {
    const e = this.getSlides().length, { calculatedSlidesPerPage: t, slidesPerMove: i } = this, s = (e - t) / i + 1;
    return Math.ceil(s);
  }
  getCurrentPage() {
    return Math.ceil(this.activeSlide / this.slidesPerMove);
  }
  canScrollNext() {
    return this.getCurrentPage() < this.getPageCount() - 1;
  }
  canScrollPrev() {
    return this.getCurrentPage() > 0;
  }
  /**
   * @internal Gets all share option list items.
   */
  getSlides() {
    if (this.slidesCache === null) {
      if (!this.scrollContainer)
        return [];
      this.slidesCache = [...this.scrollContainer.children].filter(
        (e) => this.isShareOptionListItem(e)
      );
    }
    return this.slidesCache;
  }
  invalidateSlidesCache() {
    this.slidesCache = null;
  }
  handleKeyDown(e) {
    if ([
      "ArrowLeft",
      "ArrowRight",
      "ArrowUp",
      "ArrowDown",
      "Home",
      "End"
    ].includes(e.key)) {
      const t = this.localize.dir() === "rtl", i = e.key === "ArrowDown" || !t && e.key === "ArrowRight" || t && e.key === "ArrowLeft", s = e.key === "ArrowUp" || !t && e.key === "ArrowLeft" || t && e.key === "ArrowRight";
      e.preventDefault(), s && this.previous(), i && this.next(), e.key === "Home" && this.goToSlide(0), e.key === "End" && this.goToSlide(this.getSlides().length - 1);
    }
  }
  handleScroll() {
    this.scrolling = !0, this.pendingSlideChange || this.synchronizeSlides();
  }
  /** @internal Synchronizes the slides with the IntersectionObserver API. */
  synchronizeSlides() {
    this.slideObserver?.disconnect(), this.slideObserver = new IntersectionObserver(
      (e) => {
        this.slideObserver?.disconnect(), this.slideObserver = null;
        for (const c of e) {
          const f = c.target;
          f.toggleAttribute("inert", !c.isIntersecting), f.classList.toggle("--in-view", c.isIntersecting), f.setAttribute(
            "aria-hidden",
            c.isIntersecting ? "false" : "true"
          );
        }
        const t = e.find((c) => c.isIntersecting);
        if (!t)
          return;
        const i = this.getSlides(), s = this.getSlides().length, n = i.indexOf(
          t.target
        ), r = (Math.ceil(n / this.slidesPerMove) * this.slidesPerMove + s) % s;
        this.activeSlide = r, this.currentSlide = r;
      },
      {
        root: this.scrollContainer,
        threshold: 0.6
      }
    ), this.getSlides().forEach((e) => {
      this.slideObserver?.observe(e);
    });
  }
  handleScrollEnd() {
    this.scrolling && (this.scrolling = !1, this.pendingSlideChange = !1, this.synchronizeSlides());
  }
  isShareOptionListItem(e) {
    return e instanceof Element && e.tagName.toLowerCase() === "cx-share-option-list-item";
  }
  attributeChangedCallback(e, t, i) {
    super.attributeChangedCallback(e, t, i), e === "current-slide" && i !== String(this.activeSlide) && this.initializeSlides(Number(i));
  }
  async initializeSlides(e) {
    this.getSlides().forEach((t, i) => {
      t.classList.remove("--in-view"), t.classList.remove("--is-active"), t.setAttribute("role", "group"), t.setAttribute(
        "aria-label",
        this.localize.term("slideNum", i + 1)
      );
    }), this.updateSlidesSnap(), this.goToSlide(e ?? this.activeSlide, "auto"), this.requestUpdate();
  }
  async handleSlidesPerPageChange() {
    this.initializeSlides();
  }
  handleSlideChange() {
    const e = this.getSlides();
    e.forEach((t, i) => {
      t.classList.toggle("--is-active", i === this.activeSlide);
    }), this.hasUpdated && this.emit("cx-slide-change", {
      detail: {
        index: this.activeSlide,
        slide: e[this.activeSlide]
      }
    });
  }
  updateSlidesSnap() {
    const e = this.getSlides(), t = this.slidesPerMove;
    e.forEach((i, s) => {
      (s + t) % t === 0 ? i.style.removeProperty("scroll-snap-align") : i.style.setProperty("scroll-snap-align", "none");
    });
  }
  /**
   * Move the share option list backward by `slides-per-move` slides.
   *
   * @param behavior - The behavior used for scrolling.
   */
  previous(e = "smooth") {
    this.goToSlide(this.activeSlide - this.slidesPerMove, e);
  }
  /**
   * Move the share option list forward by `slides-per-move` slides.
   *
   * @param behavior - The behavior used for scrolling.
   */
  next(e = "smooth") {
    this.goToSlide(this.activeSlide + this.slidesPerMove, e);
  }
  /**
   * Scrolls the share option list to the slide specified by `index`.
   *
   * @param index - The slide index.
   * @param behavior - The behavior used for scrolling.
   */
  goToSlide(e, t = "smooth") {
    const { calculatedSlidesPerPage: i } = this, s = this.getSlides();
    if (!s.length)
      return;
    const o = b(
      e,
      0,
      s.length - i
    );
    this.activeSlide = Math.max(0, o), this.currentSlide = o;
    const n = this.localize.dir() === "rtl", r = b(
      e + (n ? i - 1 : 0),
      0,
      s.length - 1
    ), c = s[r];
    this.scrollToSlide(c, O() ? "auto" : t);
  }
  /**
   * Scrolls to the given slide, allowing an optional duration (in ms) for the scroll animation.
   * If duration is provided and behavior is 'smooth', a custom smooth scroll is performed.
   *
   * @param slide - The target slide HTMLElement.
   * @param behavior - The scroll behavior ('auto' | 'smooth').
   * @param duration - Optional duration in milliseconds for the scroll animation.
   */
  scrollToSlide(e, t = "smooth") {
    this.scrollContainer && (this.pendingSlideChange = !0, window.requestAnimationFrame(() => {
      const i = this.scrollContainer, s = i.getBoundingClientRect(), o = e.getBoundingClientRect(), n = o.left - s.left, r = o.top - s.top;
      n || r ? (this.pendingSlideChange = !0, i.scrollTo({
        behavior: t,
        left: n + i.scrollLeft,
        top: r + i.scrollTop
      })) : this.pendingSlideChange = !1;
    }));
  }
  handleNextButtonClick() {
    this.next();
  }
  handlePreviousButtonClick() {
    this.previous();
  }
  handleShareOptionListItemSelected(e) {
    this.selectedItem = e.detail.value;
  }
  render() {
    const { scrolling: e } = this, t = this.canScrollPrev(), i = this.canScrollNext(), s = this.localize.dir() === "ltr", o = getComputedStyle(this).getPropertyValue("--item-size"), n = getComputedStyle(this).getPropertyValue("--slide-gap");
    return g`<cx-resize-observer @cx-resize=${this.calculateSlidesPerPage}><div part="base" class=${u({
      "share-option-list": !0,
      "share-option-list--empty": this.data.length === 0,
      "share-option-list--horizontal": this.orientation === "horizontal",
      "share-option-list--vertical": this.orientation === "vertical"
    })} @cx-share-option-list-item-selected=${this.handleShareOptionListItemSelected}><div class="share-option-list__placeholder"></div><div id="scroll-container" part="scroll-container" class=${u({
      "share-option-list__slides": !0,
      "share-option-list__slides--horizontal": this.orientation === "horizontal",
      "share-option-list__slides--vertical": this.orientation === "vertical"
    })} style=${k({
      "--slides-per-page": this.calculatedSlidesPerPage,
      "--width": `calc(${this.calculatedSlidesPerPage} * ${o} + (${this.calculatedSlidesPerPage - 1} * ${n}))`
    })} aria-busy=${e ? "true" : "false"} aria-atomic="true" tabindex="0" @keydown=${this.handleKeyDown} @scroll=${this.handleScroll} @scrollend=${this.handleScrollEnd}>${M(
      this.data,
      (r) => r.id,
      (r, c) => g`<cx-share-option-list-item data-index=${c} value=${r.id} icon=${r.icon} tooltip=${r.tooltip} ?disabled=${r.disabled} ?selected=${r.id === this.selectedItem}>${r.name}</cx-share-option-list-item>`
    )}</div><slot hidden></slot>${$(
      this.navigation === "arrows" || this.navigation === "both",
      () => {
        let r = s ? "chevron_left" : "chevron_right", c = s ? "chevron_right" : "chevron_left";
        return this.orientation === "vertical" && (r = "expand_less", c = "expand_more"), g`<div part="navigation" class=${u({
          "share-option-list__navigation": !0,
          "share-option-list__navigation--horizontal": this.orientation === "horizontal",
          "share-option-list__navigation--vertical": this.orientation === "vertical"
        })}><button part="navigation-button navigation-button--previous" class=${u({
          "share-option-list__navigation-button": !0,
          "share-option-list__navigation-button--disabled": !t,
          "share-option-list__navigation-button--hidden": !t,
          "share-option-list__navigation-button--previous": !0
        })} aria-label=${this.localize.term("previousSlide")} aria-controls="scroll-container" aria-disabled=${String(!t)} @click=${t ? this.handlePreviousButtonClick : null}><slot name="previous-icon"><cx-icon name=${r}></cx-icon></slot></button><button part="navigation-button navigation-button--next" class=${u({
          "share-option-list__navigation-button": !0,
          "share-option-list__navigation-button--disabled": !i,
          "share-option-list__navigation-button--hidden": !i,
          "share-option-list__navigation-button--next": !0
        })} aria-label=${this.localize.term("nextSlide")} aria-controls="scroll-container" aria-disabled=${String(!i)} @click=${i ? this.handleNextButtonClick : null}><slot name="next-icon"><cx-icon name=${c}></cx-icon></slot></button></div>`;
      }
    )}</div></cx-resize-observer>`;
  }
};
l.styles = [C, V];
l.dependencies = {
  "cx-icon": _,
  "cx-resize-observer": I,
  "cx-share-option-list-item": d
};
a([
  S("slot")
], l.prototype, "slotElement", 2);
a([
  S(".share-option-list__slides")
], l.prototype, "scrollContainer", 2);
a([
  S(".share-option-list__placeholder")
], l.prototype, "placeholderEl", 2);
a([
  h({ reflect: !0, type: Array })
], l.prototype, "data", 2);
a([
  h({ reflect: !0, type: String })
], l.prototype, "navigation", 2);
a([
  h({ reflect: !0, type: String })
], l.prototype, "orientation", 2);
a([
  h({ attribute: "slides-per-page", reflect: !0, type: Number })
], l.prototype, "slidesPerPage", 2);
a([
  h({ attribute: "slides-per-move", reflect: !0, type: Number })
], l.prototype, "slidesPerMove", 2);
a([
  h({ attribute: "selected-item", reflect: !0, type: String })
], l.prototype, "selectedItem", 2);
a([
  h({ attribute: "current-slide", reflect: !0, type: Number })
], l.prototype, "currentSlide", 2);
a([
  v()
], l.prototype, "activeSlide", 2);
a([
  v()
], l.prototype, "scrolling", 2);
a([
  v()
], l.prototype, "calculatedSlidesPerPage", 2);
a([
  m("slidesPerPage"),
  m("data", { waitUntilFirstUpdate: !0 })
], l.prototype, "calculateSlidesPerPage", 1);
a([
  L({ passive: !0 })
], l.prototype, "handleScroll", 1);
a([
  m("calculatedSlidesPerPage", { waitUntilFirstUpdate: !0 })
], l.prototype, "handleSlidesPerPageChange", 1);
a([
  m("activeSlide")
], l.prototype, "handleSlideChange", 1);
a([
  m("slidesPerMove")
], l.prototype, "updateSlidesSnap", 1);
l = a([
  w("cx-share-option-list")
], l);
export {
  l as default
};
