import {
  __decorateClass,
  __privateAdd,
  __privateGet,
  __privateMethod,
  __privateSet
} from "../../chunks/chunk.QU3DSPNU.js";
var _cardRef, _arrowRef, _autoUpdateCleanupFn, _GdsCoachmark_instances, closeCoachMark_fn, findTarget_fn, checkBoundingRect_fn, checkOverlap_fn, isElementOutsideView_fn, computeTooltipPosition_fn, shouldTooltipBeVisible_fn, updateCoachmarks_fn;
import { property, state } from "lit/decorators.js";
import { createRef, ref } from "lit/directives/ref.js";
import { when } from "lit/directives/when.js";
import {
  arrow,
  autoUpdate,
  computePosition,
  detectOverflow,
  flip,
  hide,
  offset,
  shift
} from "@floating-ui/dom";
import { GdsElement } from "../../gds-element.js";
import { gdsCustomElement, html } from "../../scoping.js";
import CoachmarkStyles from "./coachmark.styles.js";
let GdsCoachmark = class extends GdsElement {
  constructor() {
    super(...arguments);
    __privateAdd(this, _GdsCoachmark_instances);
    this.placement = "bottom";
    this.overlappedBy = [];
    this.target = [];
    this.label = "Coachmark";
    this.computeVisibility = (_self, _target, computedVisibility) => computedVisibility;
    /**
     * The resolved targeted element (readonly)
     */
    this.targetElement = void 0;
    this._isVisible = false;
    this._preventClose = false;
    __privateAdd(this, _cardRef, createRef());
    __privateAdd(this, _arrowRef, createRef());
    __privateAdd(this, _autoUpdateCleanupFn);
  }
  connectedCallback() {
    super.connectedCallback();
    document.addEventListener("click", () => {
      setTimeout(() => {
        __privateMethod(this, _GdsCoachmark_instances, updateCoachmarks_fn).call(this);
        __privateMethod(this, _GdsCoachmark_instances, closeCoachMark_fn).call(this);
      }, 400);
    });
    document.addEventListener("keydown", (event) => {
      if (event.key === "Escape" && this._isVisible) {
        __privateMethod(this, _GdsCoachmark_instances, closeCoachMark_fn).call(this);
      }
    });
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    document.removeEventListener("click", __privateMethod(this, _GdsCoachmark_instances, closeCoachMark_fn));
    document.removeEventListener("keydown", (event) => {
      if (event.key === "Escape" && this._isVisible) {
        __privateMethod(this, _GdsCoachmark_instances, closeCoachMark_fn).call(this);
      }
    });
  }
  firstUpdated() {
    if (this.target.length > 0) {
      this.targetElement = __privateMethod(this, _GdsCoachmark_instances, findTarget_fn).call(this, this.target);
      __privateMethod(this, _GdsCoachmark_instances, updateCoachmarks_fn).call(this);
    }
  }
  setPreventClose(preventClose) {
    this._preventClose = preventClose;
  }
  render() {
    return html`${when(
      this.target.length > 0,
      () => html`
        <div
          role="dialog"
          id="body"
          aria-label=${this.label}
          ${ref(__privateGet(this, _cardRef))}
        >
          <slot></slot>
          <div id="arrow" ${ref(__privateGet(this, _arrowRef))}></div>
        </div>
      `,
      () => html``
    )}`;
  }
};
_cardRef = new WeakMap();
_arrowRef = new WeakMap();
_autoUpdateCleanupFn = new WeakMap();
_GdsCoachmark_instances = new WeakSet();
closeCoachMark_fn = function() {
  var _a;
  if (!this._isVisible) return;
  const shouldClose = this.dispatchCustomEvent("gds-ui-state", {
    detail: { open: this._isVisible, reason: "closed" },
    bubbles: false,
    composed: false,
    cancelable: true
  });
  if (!shouldClose) return;
  this._isVisible = false;
  __privateGet(this, _cardRef).value?.remove();
  (_a = __privateGet(this, _autoUpdateCleanupFn)) == null ? void 0 : _a.call(this);
};
findTarget_fn = function(selectors) {
  let shadow = false;
  let el = void 0;
  for (const selector of selectors) {
    if (selector === "shadowRoot") {
      shadow = true;
      continue;
    }
    if (!el) {
      el = document.querySelector(selector);
    } else if (shadow && el.shadowRoot) {
      el = el.shadowRoot.querySelector(selector);
      shadow = false;
    } else {
      el = el.querySelector(selector);
    }
  }
  return el;
};
checkBoundingRect_fn = function(element, overlappedElement) {
  if (element == overlappedElement) return;
  const elementRect = element.getBoundingClientRect();
  const overlappedElementRect = overlappedElement.getBoundingClientRect();
  return elementRect.top < overlappedElementRect.bottom && elementRect.bottom > overlappedElementRect.top && elementRect.left < overlappedElementRect.right && elementRect.right > overlappedElementRect.left;
};
checkOverlap_fn = function(selectors) {
  if (!selectors) return false;
  for (const selector of selectors) {
    const el = document.querySelector(selector);
    if (!el || getComputedStyle(el).visibility === "hidden") continue;
    if (__privateMethod(this, _GdsCoachmark_instances, checkBoundingRect_fn).call(this, this.targetElement, el)) {
      return true;
    }
  }
  return false;
};
isElementOutsideView_fn = function(element) {
  const elementRect = element.getBoundingClientRect();
  const windowHeight = window.innerHeight || document.documentElement.clientHeight;
  const windowWidth = window.innerWidth || document.documentElement.clientWidth;
  return elementRect.top + elementRect.height < 0 || elementRect.top > windowHeight || elementRect.left + elementRect.width < 0 || elementRect.left > windowWidth;
};
computeTooltipPosition_fn = async function(targetedEl, componentEl, arrowEl) {
  return computePosition(targetedEl, componentEl, {
    placement: this.placement,
    middleware: [
      offset(() => ({
        mainAxis: 16,
        alignmentAxis: 16
      })),
      {
        name: "detectOverflow",
        async fn(positionState) {
          const overflow = await detectOverflow(positionState, {
            boundary: document.body,
            rootBoundary: "document",
            altBoundary: true,
            padding: {
              top: 167,
              left: 20
            }
          });
          return {
            data: overflow
          };
        }
      },
      shift({ padding: 16 }),
      flip(),
      hide(),
      arrow({
        padding: 16,
        element: arrowEl
      })
    ]
  });
};
shouldTooltipBeVisible_fn = function() {
  if (!this.targetElement) return false;
  const isOutOfBound = __privateMethod(this, _GdsCoachmark_instances, isElementOutsideView_fn).call(this, this.targetElement);
  const targetIsVisible = this.targetElement.checkVisibility();
  const isOverlapping = this.overlappedBy.length === 0 ? false : __privateMethod(this, _GdsCoachmark_instances, checkOverlap_fn).call(this, this.overlappedBy);
  return this.computeVisibility(
    this,
    this.targetElement,
    !isOverlapping && !isOutOfBound && targetIsVisible
  );
};
updateCoachmarks_fn = async function() {
  const targetEl = this.targetElement;
  const componentEl = __privateGet(this, _cardRef).value;
  const arrowEl = __privateGet(this, _arrowRef).value;
  if (!targetEl || !componentEl || !arrowEl) return;
  try {
    __privateSet(this, _autoUpdateCleanupFn, autoUpdate(targetEl, componentEl, () => {
      __privateMethod(this, _GdsCoachmark_instances, computeTooltipPosition_fn).call(this, targetEl, componentEl, arrowEl).then(
        ({ x, y, middlewareData, placement }) => {
          if (__privateMethod(this, _GdsCoachmark_instances, shouldTooltipBeVisible_fn).call(this)) {
            this._isVisible = true;
            Object.assign(componentEl.style, {
              visibility: "visible",
              opacity: 1,
              left: `${x}px`,
              top: `${y}px`
            });
            if (middlewareData.arrow) {
              const { x: x2, y: y2 } = middlewareData.arrow;
              arrowEl.removeAttribute("class");
              arrowEl.classList.add("arrow-" + placement);
              Object.assign(arrowEl.style, {
                left: x2 != null ? `${x2}px` : "",
                top: y2 != null ? `${y2}px` : ""
              });
            }
          } else {
            this._isVisible = false;
            Object.assign(componentEl.style, {
              visibility: "hidden",
              opacity: 0
            });
          }
        }
      );
    }));
  } catch (error) {
    console.warn("failed to render tooltips");
  }
};
GdsCoachmark.styles = CoachmarkStyles;
__decorateClass([
  property()
], GdsCoachmark.prototype, "placement", 2);
__decorateClass([
  property({ attribute: false })
], GdsCoachmark.prototype, "overlappedBy", 2);
__decorateClass([
  property({ attribute: false })
], GdsCoachmark.prototype, "target", 2);
__decorateClass([
  property()
], GdsCoachmark.prototype, "label", 2);
__decorateClass([
  property({ attribute: false })
], GdsCoachmark.prototype, "computeVisibility", 2);
__decorateClass([
  state()
], GdsCoachmark.prototype, "_isVisible", 2);
__decorateClass([
  state()
], GdsCoachmark.prototype, "_preventClose", 2);
GdsCoachmark = __decorateClass([
  gdsCustomElement("gds-coachmark")
], GdsCoachmark);
export {
  GdsCoachmark
};
