import { attachedRoot } from "@veno-ui/utils";
function defaultConditional() {
  return true;
}
function checkEvent(e, el, binding) {
  if (!e || checkIsActive(e, binding) === false)
    return false;
  const root = attachedRoot(el);
  if (root instanceof ShadowRoot && root.host === e.target)
    return false;
  const elements = (typeof binding.value === "object" && binding.value.include || (() => []))();
  elements.push(el);
  return !elements.some((el2) => el2?.contains(e.target));
}
function checkIsActive(e, binding) {
  const isActive = typeof binding.value === "object" && binding.value.closeConditional || defaultConditional;
  return isActive(e);
}
function directive(e, el, binding) {
  const handler = typeof binding.value === "function" ? binding.value : binding.value.handler;
  el._clickOutside.lastMousedownWasOutside && checkEvent(e, el, binding) && setTimeout(() => {
    checkIsActive(e, binding) && handler && handler(e);
  }, 0);
}
function handleShadow(el, callback) {
  const root = attachedRoot(el);
  callback(document.body);
  if (root instanceof ShadowRoot) {
    callback(root);
  }
}
const ClickOutside = {
  // [data-app] may not be found
  // if using bind, inserted makes
  // sure that the root element is
  // available, iOS does not support
  // clicks on body
  mounted(el, binding) {
    const onClick = (e) => directive(e, el, binding);
    const onMousedown = (e) => {
      el._clickOutside.lastMousedownWasOutside = checkEvent(e, el, binding);
    };
    handleShadow(el, (app) => {
      app.addEventListener("click", onClick, true);
      app.addEventListener("mousedown", onMousedown, true);
    });
    el._clickOutside = {
      lastMousedownWasOutside: true,
      onClick,
      onMousedown
    };
  },
  unmounted(el) {
    if (!el._clickOutside)
      return;
    handleShadow(el, (app) => {
      if (!app || !el._clickOutside)
        return;
      app.removeEventListener("click", el._clickOutside.onClick, true);
      app.removeEventListener("mousedown", el._clickOutside.onMousedown, true);
    });
    delete el._clickOutside;
  }
};
var click_outside_default = ClickOutside;
export {
  ClickOutside,
  click_outside_default as default
};
//# sourceMappingURL=index.mjs.map
