import { WithElement as q, OnDispose as W, WithBrowserCtx as z, Value as j, render as R, html as E, dataAttr as F, attr as f, computedOf as A, prop as U, aria as B, on as H, When as O, Use as _, Fragment as K, coalesce as S } from "@tempots/dom";
import { u as G } from "./use-animated-toggle-89fKlXxy.js";
import { g as J } from "./timer-Rd2sKnvH.js";
import { s as N } from "./session-id-3KiilioY.js";
import { B as P } from "./translations-BGblCUBj.js";
import { C as Q } from "./use-form-BSvvERhX.js";
import { B as D } from "./input-container-DhUiLmXE.js";
const X = [
  "a[href]",
  "button:not([disabled])",
  "input:not([disabled])",
  "select:not([disabled])",
  "textarea:not([disabled])",
  '[tabindex]:not([tabindex="-1"])',
  '[contenteditable="true"]',
  "audio[controls]",
  "video[controls]",
  "details > summary:first-of-type",
  "details[open]"
].join(", ");
function Y(c) {
  return Array.from(c.querySelectorAll(X)).filter(
    (e) => {
      const s = e;
      return s.offsetWidth > 0 && s.offsetHeight > 0 && !s.hasAttribute("inert") && window.getComputedStyle(s).visibility !== "hidden";
    }
  );
}
function $(c = {}) {
  const {
    active: e = !0,
    escapeDeactivates: s = !0,
    onEscape: t,
    initialFocus: n,
    returnFocus: r,
    clickOutsideDeactivates: l = !1,
    onClickOutside: u
  } = c;
  return q((g) => {
    let h = e, m = null, i = [], b = null, p = null, d = null;
    typeof document < "u" && (m = document.activeElement);
    const y = () => {
      i = Y(g);
    }, x = (a) => {
      if (h) {
        if (s && a.key === "Escape") {
          a.preventDefault(), t?.();
          return;
        }
        if (a.key === "Tab") {
          if (y(), i.length === 0) {
            a.preventDefault();
            return;
          }
          const o = i.indexOf(
            document.activeElement
          );
          a.shiftKey ? o <= 0 && (a.preventDefault(), i[i.length - 1]?.focus()) : o >= i.length - 1 && (a.preventDefault(), i[0]?.focus());
        }
      }
    }, v = (a) => {
      if (!h || !l) return;
      const o = a.target;
      g.contains(o) || u?.();
    }, k = () => {
      if (!h) return;
      y();
      let a = null;
      typeof n == "function" ? a = n() : n ? a = n : i.length > 0 && (a = i[0]), a && (p = setTimeout(() => {
        p = null, a?.focus();
      }, 50)), document.addEventListener("keydown", x, !0), l && document.addEventListener("click", v, !0);
    }, w = () => {
      h = !1, document.removeEventListener("keydown", x, !0), document.removeEventListener("click", v, !0);
      let a = null;
      typeof r == "function" ? a = r() : r ? a = r : m && (a = m), a && document.body.contains(a) && (d = setTimeout(() => {
        d = null, a?.focus();
      }, 0));
    };
    return b = setTimeout(() => {
      b = null, k();
    }, 0), W(() => {
      b != null && clearTimeout(b), p != null && clearTimeout(p), d != null && clearTimeout(d), w();
    });
  });
}
function de(c = {}) {
  return {
    activate: () => $({ ...c, active: !0 }),
    deactivate: () => $({ ...c, active: !1 })
  };
}
function Z(c) {
  return {
    "~standard": {
      version: 1,
      vendor: "beatui-custom",
      validate: (s) => {
        const t = c.validate(s);
        return t.success ? { value: t.data } : {
          issues: t.errors.map((n) => ({
            message: n.message,
            path: n.path
          }))
        };
      },
      types: void 0
    },
    safeParse: (s) => {
      const t = c.validate(s);
      return t.success ? { success: !0, data: t.data } : {
        success: !1,
        error: {
          errors: t.errors.map((n) => ({
            message: n.message,
            path: n.path?.map(
              (r) => typeof r == "object" && "key" in r ? r.key.toString() : r.toString()
            ) || []
          }))
        }
      };
    }
  };
}
class T {
  optional() {
    return new ee(this);
  }
  default(e) {
    return new te(this, e);
  }
  schema() {
    return Z(this);
  }
}
class C extends T {
  minLength;
  maxLength;
  pattern;
  customValidations = [];
  validate(e) {
    if (typeof e != "string")
      return { success: !1, errors: [{ message: "Expected string" }] };
    const s = [];
    this.minLength !== void 0 && e.length < this.minLength && s.push({ message: `Must be at least ${this.minLength} characters` }), this.maxLength !== void 0 && e.length > this.maxLength && s.push({ message: `Must be at most ${this.maxLength} characters` }), this.pattern && !this.pattern.test(e) && s.push({ message: "Invalid format" });
    for (const t of this.customValidations) {
      const n = t(e);
      n && s.push({ message: n });
    }
    return s.length > 0 ? { success: !1, errors: s } : { success: !0, data: e };
  }
  min(e, s) {
    const t = new C();
    return t.minLength = e, t.maxLength = this.maxLength, t.pattern = this.pattern, t.customValidations = [...this.customValidations], s && t.customValidations.push(
      (n) => n.length < e ? s : null
    ), t;
  }
  max(e, s) {
    const t = new C();
    return t.minLength = this.minLength, t.maxLength = e, t.pattern = this.pattern, t.customValidations = [...this.customValidations], s && t.customValidations.push(
      (n) => n.length > e ? s : null
    ), t;
  }
  regex(e, s) {
    const t = new C();
    return t.minLength = this.minLength, t.maxLength = this.maxLength, t.pattern = e, t.customValidations = [...this.customValidations], s && t.customValidations.push(
      (n) => e.test(n) ? null : s
    ), t;
  }
  email(e = "Please enter a valid email address") {
    const s = /^[^\s@]+@[^\s@]+\.[^\s@]+$/, t = new C();
    return t.minLength = this.minLength, t.maxLength = this.maxLength, t.pattern = this.pattern, t.customValidations = [
      ...this.customValidations,
      (n) => s.test(n) ? null : e
    ], t;
  }
  refine(e) {
    const s = new C();
    return s.minLength = this.minLength, s.maxLength = this.maxLength, s.pattern = this.pattern, s.customValidations = [...this.customValidations, e], s;
  }
}
class V extends T {
  mustBeTrue = !1;
  trueMessage;
  validate(e) {
    return typeof e != "boolean" ? { success: !1, errors: [{ message: "Expected boolean" }] } : this.mustBeTrue && e !== !0 ? {
      success: !1,
      errors: [{ message: this.trueMessage || "Must be true" }]
    } : { success: !0, data: e };
  }
  refine(e, s) {
    const t = new V();
    t.mustBeTrue = this.mustBeTrue, t.trueMessage = this.trueMessage;
    const n = t.validate.bind(t);
    return t.validate = (r) => {
      const l = n(r);
      return l.success ? e(l.data) ? l : { success: !1, errors: [{ message: s }] } : l;
    }, t;
  }
  literal(e, s) {
    const t = new V();
    return t.mustBeTrue = !0, t.trueMessage = s, t;
  }
}
class ee extends T {
  constructor(e) {
    super(), this.inner = e;
  }
  validate(e) {
    if (e === void 0)
      return { success: !0, data: void 0 };
    const s = this.inner.validate(e);
    return s.success ? { success: !0, data: s.data } : { success: !1, errors: s.errors };
  }
}
class te extends T {
  constructor(e, s) {
    super(), this.inner = e, this.defaultValue = s;
  }
  validate(e) {
    return e === void 0 ? { success: !0, data: this.defaultValue } : this.inner.validate(e);
  }
}
class I extends T {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  constructor(e) {
    super(), this.shape = e;
  }
  validate(e) {
    if (typeof e != "object" || e === null || Array.isArray(e))
      return { success: !1, errors: [{ message: "Expected object" }] };
    const s = e, t = {}, n = [];
    for (const [r, l] of Object.entries(this.shape)) {
      const u = l.validate(s[r]);
      if (u.success)
        t[r] = u.data;
      else
        for (const g of u.errors)
          n.push({
            message: g.message,
            path: [r, ...g.path || []]
          });
    }
    return n.length > 0 ? { success: !1, errors: n } : { success: !0, data: t };
  }
  refine(e, s) {
    const t = new I(this.shape), n = t.validate.bind(t);
    return t.validate = (r) => {
      const l = n(r);
      if (!l.success) return l;
      const u = e(l.data);
      return u ? {
        success: !1,
        errors: [
          {
            message: u,
            path: s?.path
          }
        ]
      } : { success: !0, data: l.data };
    }, t;
  }
}
const me = () => new C(), fe = () => new V(), he = (c) => new I(c);
function se(c) {
  return z((e) => {
    const s = [], t = () => s.forEach((r) => r());
    return c(({
      effect: r = "opaque",
      mode: l = "capturing",
      onClickOutside: u,
      onEscape: g,
      content: h,
      container: m = "body"
    }) => {
      m === "body" && (e = e.makePortal("body"));
      const i = G();
      i.listenOnClosed(t);
      let b = () => {
      }, p = () => {
      };
      const d = (a) => {
        a.key === "Escape" && (g?.(), i.close());
      }, y = () => {
        u?.(), i.close();
      }, x = (a) => {
        b(), p(), a === "capturing" ? (document.addEventListener("keydown", d), b = () => document.removeEventListener("keydown", d), e.element.addEventListener("mousedown", y), p = () => e.element.removeEventListener("mousedown", y)) : (b = () => {
        }, p = () => {
        });
      }, v = j.on(l, x);
      s.push(v), s.push(() => {
        i.dispose(), b(), p();
      });
      const w = R((() => {
        const a = /* @__PURE__ */ new Set();
        for (const o of e.element.querySelectorAll(
          ":scope > :not([data-overlay])"
        ))
          o.hasAttribute("inert") ? a.add(o) : o.setAttribute("inert", "");
        return s.push(() => {
          for (const o of e.element.querySelectorAll(
            ":scope > :not([data-overlay])"
          ))
            a.has(o) || o.removeAttribute("inert");
          a.clear();
        }), document.activeElement?.blur?.(), E.div(
          q((o) => i.setElement(o)),
          F.status(i.status.map(String)),
          F.overlay("true"),
          f.class(
            A(
              r ?? "opaque",
              l
            )(
              (o, L) => `bc-overlay bc-overlay--effect-${o} bc-overlay--mode-${L}`
            )
          ),
          h
        );
      })(), e.element, {
        disposeWithParent: !0,
        clear: !1,
        providers: e.providers
      });
      s.push(w), J(() => i.open());
    }, t);
  });
}
function ne(c, e) {
  const {
    size: s = "md",
    dismissable: t = !0,
    showCloseButton: n = !0,
    onClose: r,
    overlayEffect: l = "opaque",
    container: u = "body",
    position: g = "center"
  } = c;
  return se((h, m) => {
    let i = () => {
    };
    return e((d) => {
      i = m;
      const y = U("capturing");
      j.on(t, (o) => {
        y.set(o ? "capturing" : "non-capturing");
      });
      const x = A(
        d.header != null,
        n
      )((o, L) => o || L), v = N("modal"), k = `${v}-header`, w = `${v}-body`, a = E.div(
        f.class(
          A(
            s,
            g
          )(
            (o, L) => `bc-modal bc-modal--size-${o} bc-modal--container-${u} bc-modal--position-${L}`
          )
        ),
        // Essential ARIA attributes for modal dialog
        f.role("dialog"),
        B.modal(!0),
        ...d.header ? [B.labelledby(k)] : [],
        B.describedby(w),
        f.tabindex(-1),
        // Make modal focusable for initial focus
        f.id(v),
        F.focusTrap("true"),
        // Mark as focus trap container
        H.mousedown((o) => o.stopPropagation()),
        // Prevent overlay click-outside when clicking modal content
        // Focus trap implementation
        $({
          escapeDeactivates: !1,
          // Let Overlay handle escape key
          initialFocus: () => {
            const o = document.getElementById(v);
            if (!o) return null;
            const L = o.querySelector(
              '[aria-label="Close modal"]'
            );
            if (L) return L;
            const M = o.querySelector(
              'button, input, select, textarea, [tabindex]:not([tabindex="-1"])'
            );
            return M || o;
          }
        }),
        // Modal content container
        E.div(
          f.class("bc-modal__content"),
          // Header section
          O(
            x,
            () => E.div(
              f.class("bc-modal__header"),
              E.div(
                f.class("bc-modal__title"),
                ...d.header ? [f.id(k)] : [],
                d.header
              ),
              O(
                n,
                () => _(
                  P,
                  (o) => Q({
                    size: "sm",
                    label: o.$.closeModal,
                    onClick: () => {
                      i(), m();
                    }
                  })
                )
              )
            )
          ),
          // Body section
          E.div(f.class("bc-modal__body"), f.id(w), d.body),
          // Footer section
          d.footer && E.div(f.class("bc-modal__footer"), d.footer)
        )
      );
      h({
        mode: y,
        effect: l ?? "opaque",
        container: u,
        content: a,
        onClickOutside: () => {
          r?.(), m();
        },
        onEscape: () => {
          r?.(), m();
        }
      });
    }, () => {
      i(), m();
    });
  });
}
function pe(c, e) {
  const { confirmText: s, cancelText: t, onConfirm: n, onCancel: r, ...l } = c;
  return _(
    P,
    (u) => ne({ showCloseButton: !1, ...l }, (g, h) => {
      const m = () => {
        n?.(), h();
      }, i = () => {
        r?.(), h();
      };
      return e((p) => {
        g({
          body: p,
          footer: K(
            f.class("bc-modal__actions"),
            D(
              {
                variant: "outline",
                onClick: i
              },
              S(t, u.$.cancel)
            ),
            D(
              {
                color: "primary",
                variant: "filled",
                onClick: m
              },
              S(s, u.$.confirm)
            )
          )
        });
      }, h);
    })
  );
}
export {
  V as B,
  pe as C,
  $ as F,
  ne as M,
  se as O,
  C as S,
  I as a,
  fe as b,
  Z as c,
  he as o,
  me as s,
  de as u
};
