import { prop as b, computedOf as B, makeProviderMark as U, When as y, Unless as C, Use as S, html as r, attr as l, Ensure as g, OneOfValue as D, Fragment as E, NotEmpty as O, ForEach as R, on as L } from "@tempots/dom";
import { A as M, a as T } from "../auth-divider-BIefTDoO.js";
import { m as N } from "../translations-BGblCUBj.js";
import { N as v, P as V, E as x } from "../notice-BmkckDsD.js";
import { S as P } from "../stack-BJgsPJ9A.js";
import { B as k } from "../input-container-DhUiLmXE.js";
import { T as I } from "../text-input-BZmAB3_o.js";
function F(t, e) {
  return t.error ? (e.onError?.({
    message: t.error.message,
    status: t.error.status
  }), t.error.message) : null;
}
function z(t, e, a) {
  return async (n) => {
    const u = await t.signIn.email({
      email: n.email,
      password: n.password,
      callbackURL: e.callbackURL
    }), o = F(u, e);
    return o || (await a(), null);
  };
}
function q(t, e, a) {
  return async (n) => {
    const u = await t.signUp.email({
      name: n.name,
      email: n.email,
      password: n.password,
      callbackURL: e.callbackURL
    }), o = F(u, e);
    return o || (await a(), null);
  };
}
function j(t, e) {
  return async (a) => {
    const n = await t.requestPasswordReset({
      email: a.email,
      redirectTo: e.callbackURL
    });
    return F(n, e);
  };
}
function H(t, e) {
  return async (a) => {
    const n = await t.signIn.social({
      provider: a,
      callbackURL: e.callbackURL,
      errorCallbackURL: e.errorCallbackURL
    });
    F(n, e);
  };
}
function W(t, e = {}) {
  const a = b(null), n = b(!0), u = B(a)(
    (w) => w?.user ?? null
  ), o = B(a)((w) => w != null);
  let d;
  async function m() {
    try {
      const w = await t.getSession();
      w.error || !w.data ? a.set(null) : a.set({
        user: w.data.user,
        session: w.data.session
      });
    } catch {
      a.set(null);
    } finally {
      n.set(!1);
    }
  }
  e.onSessionChange && a.on(e.onSessionChange), m(), e.refreshInterval && e.refreshInterval > 0 && (d = setInterval(m, e.refreshInterval));
  function f() {
    d != null && (clearInterval(d), d = void 0), a.dispose(), n.dispose(), u.dispose(), o.dispose();
  }
  return { session: a, isPending: n, user: u, isAuthenticated: o, refresh: m, dispose: f };
}
function Y(t) {
  return t.map((e) => ({
    provider: e
  }));
}
function G(t, e = {}) {
  const a = W(t, {
    refreshInterval: e.refreshInterval,
    onSessionChange: e.onSessionChange
  }), n = () => a.refresh(), u = z(t, e, n), o = q(t, e, n), d = j(t, e), m = H(t, e), f = e.socialProviders ? Y(e.socialProviders) : [], w = {
    onSignIn: u,
    passwordRules: e.passwordRules,
    showRememberMe: e.showRememberMe,
    labels: e.labels ? {
      emailLabel: e.labels.emailLabel,
      passwordLabel: e.labels.passwordLabel,
      rememberMeLabel: e.labels.rememberMeLabel,
      signInButton: e.labels.signInButton,
      forgotPasswordLink: e.labels.forgotPasswordLink,
      noAccountLink: e.labels.noAccountLink
    } : void 0
  }, c = {
    onSignUp: o,
    passwordRules: e.passwordRules,
    showPasswordStrength: e.showPasswordStrength,
    showNameField: e.showNameField,
    showConfirmPassword: e.showConfirmPassword,
    labels: e.labels ? {
      nameLabel: e.labels.nameLabel,
      emailLabel: e.labels.emailLabel,
      passwordLabel: e.labels.passwordLabel,
      confirmPasswordLabel: e.labels.confirmPasswordLabel,
      acceptTermsLabel: e.labels.acceptTermsLabel,
      signUpButton: e.labels.signUpButton,
      hasAccountLink: e.labels.hasAccountLink
    } : void 0
  }, p = {
    onResetPassword: d,
    labels: e.labels ? {
      resetPasswordButton: e.labels.resetPasswordButton,
      resetPasswordDescription: e.labels.resetPasswordDescription,
      emailLabel: e.labels.emailLabel,
      backToSignInLink: e.labels.backToSignInLink
    } : void 0
  }, i = {
    onSignIn: u,
    onSignUp: o,
    onResetPassword: d,
    onSocialLogin: m,
    socialProviders: f.length > 0 ? f : void 0,
    showSocialDivider: f.length > 0,
    passwordRules: e.passwordRules,
    showRememberMe: e.showRememberMe,
    showPasswordStrength: e.showPasswordStrength,
    showNameField: e.showNameField,
    showConfirmPassword: e.showConfirmPassword,
    labels: e.labels
  };
  async function s() {
    await t.signOut(), await n();
  }
  function h() {
    a.dispose();
  }
  return {
    session: a.session,
    isPending: a.isPending,
    user: a.user,
    isAuthenticated: a.isAuthenticated,
    containerOptions: i,
    signInOptions: w,
    signUpOptions: c,
    resetOptions: p,
    socialProviders: f,
    signOut: s,
    refreshSession: n,
    dispose: h
  };
}
const ne = {
  mark: U("BetterAuth"),
  create: (t) => {
    if (!t)
      throw new Error("BetterAuth provider requires a client option");
    const e = G(t.client, t);
    return {
      value: e,
      dispose: () => e.dispose()
    };
  }
};
function re(t, e, ...a) {
  return M({ ...t.containerOptions, ...e }, ...a);
}
function oe(t, e) {
  return T(
    (a) => e((n) => a({ ...t.containerOptions, ...n }))
  );
}
function ie(t, e) {
  return y(t.isAuthenticated, e);
}
function ce(t, e) {
  return C(t.isAuthenticated, e);
}
const J = {
  // Two-Factor Authentication
  twoFactorSetupDescription: "Enter your password to enable two-factor authentication.",
  twoFactorEnableButton: "Enable 2FA",
  twoFactorVerifyButton: "Verify",
  twoFactorScanDescription: "Scan the code below with your authenticator app, then enter the verification code.",
  twoFactorBackupCodesDescription: "Save these backup codes in a safe place. You can use them to sign in if you lose access to your authenticator.",
  twoFactorCodePlaceholder: "Enter 6-digit code",
  twoFactorBackupCodePlaceholder: "Enter backup code",
  twoFactorEnabled: "Two-factor authentication has been enabled.",
  twoFactorTotpDescription: "Enter the code from your authenticator app.",
  twoFactorOtpDescription: "Enter the one-time code sent to you.",
  twoFactorBackupDescription: "Enter one of your backup codes.",
  twoFactorSendOtpButton: "Send Code",
  twoFactorMethodLabel: (t) => {
    switch (t) {
      case "totp":
        return "Authenticator";
      case "otp":
        return "Email/SMS";
      case "backup":
        return "Backup Code";
      default:
        return t;
    }
  },
  passwordPlaceholder: "Enter your password",
  // Magic Link
  magicLinkDescription: "Enter your email to receive a sign-in link.",
  magicLinkSendButton: "Send Magic Link",
  magicLinkSent: "A sign-in link has been sent to your email.",
  // Passkey
  passkeySignInButton: "Sign in with Passkey",
  passkeyAddButton: "Add Passkey",
  passkeyDeleteButton: "Delete",
  passkeyRenameButton: "Rename",
  passkeySaveButton: "Save",
  passkeyCancelButton: "Cancel",
  passkeyNamePlaceholder: "Passkey name (optional)",
  passkeyUnnamed: "Unnamed passkey"
}, $ = J, A = "en", K = /* @__PURE__ */ Object.assign({}), _ = N({
  defaultLocale: A,
  defaultMessages: $,
  localeLoader: async (t) => {
    if (t === A) return $;
    const e = K[`./locales/${t}.ts`];
    return e ? await e() : $;
  },
  providerName: "BetterAuthI18n"
});
function le({
  twoFactor: t,
  issuer: e,
  onComplete: a
}) {
  const n = b(""), u = b(null), o = b([]), d = b(""), m = b(null), f = b(!1), w = b("password");
  async function c(i) {
    i.preventDefault(), f.set(!0), m.set(null);
    const s = await t.enable({
      password: n.value,
      issuer: e
    });
    if (f.set(!1), s.error) {
      m.set(s.error.message);
      return;
    }
    s.data && (u.set(s.data.totpURI), o.set(s.data.backupCodes), w.set("verify"));
  }
  async function p(i) {
    i.preventDefault(), f.set(!0), m.set(null);
    const s = await t.verifyTotp({ code: d.value });
    if (f.set(!1), s.error) {
      m.set(s.error.message);
      return;
    }
    w.set("complete"), a?.();
  }
  return S(
    _,
    (i) => r.div(
      l.class("bc-two-factor"),
      g(
        m,
        (s) => v(
          { variant: "danger", tone: "prominent", role: "alert" },
          r.div(s)
        )
      ),
      D(w, {
        password: () => r.form(
          l.class("bc-two-factor__form"),
          L.submit(c),
          P(
            r.p(
              l.class("bc-auth-form__description"),
              i.$.twoFactorSetupDescription
            ),
            V({
              value: n,
              onChange: (s) => n.set(s),
              placeholder: i.$.passwordPlaceholder
            }),
            k(
              {
                type: "submit",
                variant: "filled",
                color: "primary",
                loading: f
              },
              l.class("bc-auth-form__submit"),
              i.$.twoFactorEnableButton
            )
          )
        ),
        verify: () => E(
          g(
            u,
            (s) => r.div(
              l.class("bc-two-factor__totp-uri"),
              r.p(i.$.twoFactorScanDescription),
              r.code(l.class("bc-two-factor__code-display"), s)
            )
          ),
          O(
            o,
            () => r.div(
              l.class("bc-two-factor__backup-codes"),
              r.p(i.$.twoFactorBackupCodesDescription),
              r.ul(R(o, (s) => r.li(s)))
            )
          ),
          r.form(
            l.class("bc-two-factor__form"),
            L.submit(p),
            P(
              I({
                value: d,
                onChange: (s) => d.set(s),
                placeholder: i.$.twoFactorCodePlaceholder
              }),
              k(
                {
                  type: "submit",
                  variant: "filled",
                  color: "primary",
                  loading: f
                },
                l.class("bc-auth-form__submit"),
                i.$.twoFactorVerifyButton
              )
            )
          )
        ),
        complete: () => r.div(
          l.class("bc-two-factor__complete"),
          v(
            { variant: "success", tone: "prominent" },
            r.div(i.$.twoFactorEnabled)
          )
        )
      })
    )
  );
}
function ue({
  twoFactor: t,
  methods: e = ["totp", "backup"],
  trustDevice: a,
  onVerified: n
}) {
  const u = b(""), o = b(null), d = b(!1), m = b(e[0] ?? "totp");
  async function f(c) {
    c.preventDefault(), d.set(!0), o.set(null);
    const p = m.value;
    let i;
    if (p === "totp")
      i = await t.verifyTotp({
        code: u.value,
        trustDevice: a
      });
    else if (p === "otp" && t.verifyOtp)
      i = await t.verifyOtp({
        code: u.value,
        trustDevice: a
      });
    else if (p === "backup")
      i = await t.verifyBackupCode({ code: u.value });
    else {
      o.set("Unsupported verification method"), d.set(!1);
      return;
    }
    if (d.set(!1), i.error) {
      o.set(i.error.message);
      return;
    }
    n?.();
  }
  async function w() {
    if (!t.sendOtp) return;
    d.set(!0), o.set(null);
    const c = await t.sendOtp({ trustDevice: a });
    d.set(!1), c.error && o.set(c.error.message);
  }
  return S(_, (c) => {
    const p = B(
      m,
      c
    )((s, h) => s === "totp" ? h.twoFactorTotpDescription : s === "otp" ? h.twoFactorOtpDescription : h.twoFactorBackupDescription), i = B(
      m,
      c
    )((s, h) => s === "backup" ? h.twoFactorBackupCodePlaceholder : h.twoFactorCodePlaceholder);
    return r.div(
      l.class("bc-two-factor"),
      g(
        o,
        (s) => v(
          { variant: "danger", tone: "prominent", role: "alert" },
          r.div(s)
        )
      ),
      // Method selector (only if more than one method)
      y(
        e.length > 1,
        () => r.div(
          l.class("bc-two-factor__methods"),
          ...e.map(
            (s) => r.button(
              l.type("button"),
              l.class("bc-two-factor__method-button"),
              l.class(
                m.map(
                  (h) => h === s ? "bc-two-factor__method-button--active" : ""
                )
              ),
              L.click(() => {
                m.set(s), u.set(""), o.set(null);
              }),
              c.$.twoFactorMethodLabel.map((h) => h(s))
            )
          )
        )
      ),
      r.form(
        l.class("bc-two-factor__form"),
        L.submit(f),
        P(
          r.p(l.class("bc-auth-form__description"), p),
          // Send OTP button (only for OTP method)
          y(
            m.map((s) => s === "otp" && t.sendOtp != null),
            () => k(
              {
                type: "button",
                variant: "outline",
                color: "primary",
                onClick: w,
                loading: d
              },
              c.$.twoFactorSendOtpButton
            )
          ),
          I({
            value: u,
            onChange: (s) => u.set(s),
            placeholder: i
          }),
          k(
            {
              type: "submit",
              variant: "filled",
              color: "primary",
              loading: d
            },
            l.class("bc-auth-form__submit"),
            c.$.twoFactorVerifyButton
          )
        )
      )
    );
  });
}
function de({
  client: t,
  callbackURL: e
}) {
  const a = b(""), n = b(null), u = b(!1), o = b(!1);
  async function d(m) {
    if (m.preventDefault(), !t.signIn.magicLink) {
      n.set("Magic link sign-in is not configured");
      return;
    }
    u.set(!0), n.set(null);
    const f = await t.signIn.magicLink({
      email: a.value,
      callbackURL: e
    });
    if (u.set(!1), f.error) {
      n.set(f.error.message);
      return;
    }
    o.set(!0);
  }
  return S(
    _,
    (m) => r.div(
      l.class("bc-auth-form"),
      g(
        n,
        (f) => v(
          { variant: "danger", tone: "prominent", role: "alert" },
          r.div(f)
        )
      ),
      C(
        o,
        () => r.form(
          l.class("bc-auth-form__form"),
          L.submit(d),
          P(
            l.class("bc-auth-form__fields"),
            r.p(
              l.class("bc-auth-form__description"),
              m.$.magicLinkDescription
            ),
            x({
              value: a,
              onChange: (f) => a.set(f)
            }),
            k(
              {
                type: "submit",
                variant: "filled",
                color: "primary",
                loading: u
              },
              l.class("bc-auth-form__submit"),
              m.$.magicLinkSendButton
            )
          )
        )
      ),
      y(
        o,
        () => v(
          { variant: "success", tone: "prominent" },
          r.div(m.$.magicLinkSent)
        )
      )
    )
  );
}
function me({
  client: t,
  autoFill: e,
  onSuccess: a,
  onError: n
}) {
  const u = b(!1);
  async function o() {
    if (!t.signIn.passkey) return;
    u.set(!0);
    const d = await t.signIn.passkey({ autoFill: e });
    if (u.set(!1), d.error) {
      n?.({ message: d.error.message, status: d.error.status });
      return;
    }
    a?.();
  }
  return S(
    _,
    (d) => k(
      {
        type: "button",
        variant: "outline",
        color: "primary",
        onClick: o,
        loading: u
      },
      l.class("bc-passkey-signin"),
      d.$.passkeySignInButton
    )
  );
}
function fe({
  passkey: t
}) {
  const e = b([]), a = b(null), n = b(!1), u = b("");
  async function o(c, p) {
    n.set(!0), a.set(null);
    const i = await c();
    if (n.set(!1), i.error) {
      a.set(i.error.message);
      return;
    }
    await p?.(i.data);
  }
  async function d() {
    await o(
      () => t.listUserPasskeys(),
      (c) => e.set(c ?? [])
    );
  }
  async function m() {
    const c = u.value || void 0;
    await o(
      () => t.addPasskey({ name: c }),
      async () => {
        u.set(""), await d();
      }
    );
  }
  async function f(c) {
    await o(
      () => t.deletePasskey({ id: c }),
      () => d()
    );
  }
  async function w(c, p) {
    await o(
      () => t.updatePasskey({ id: c, name: p }),
      () => d()
    );
  }
  return d(), S(
    _,
    (c) => r.div(
      l.class("bc-passkey-management"),
      g(
        a,
        (p) => v(
          { variant: "danger", tone: "prominent", role: "alert" },
          r.div(p)
        )
      ),
      // Passkey list
      r.div(
        l.class("bc-passkey-list"),
        R(e, (p) => {
          const i = b(!1), s = b(p.$.name?.value ?? "");
          return r.div(
            l.class("bc-passkey-item"),
            C(
              i,
              () => r.div(
                l.class("bc-passkey-item__info"),
                r.span(
                  l.class("bc-passkey-item__name"),
                  p.$.name?.map((h) => h ?? c.$.passkeyUnnamed.value) ?? c.$.passkeyUnnamed
                ),
                r.span(l.class("bc-passkey-item__date"), p.$.createdAt)
              )
            ),
            y(
              i,
              () => r.div(
                l.class("bc-passkey-item__edit"),
                I({
                  value: s,
                  onChange: (h) => s.set(h)
                })
              )
            ),
            r.div(
              l.class("bc-passkey-item__actions"),
              C(
                i,
                () => r.div(
                  k(
                    {
                      type: "button",
                      variant: "text",
                      size: "sm",
                      onClick: () => {
                        s.set(p.$.name?.value ?? ""), i.set(!0);
                      }
                    },
                    c.$.passkeyRenameButton
                  ),
                  k(
                    {
                      type: "button",
                      variant: "text",
                      size: "sm",
                      color: "danger",
                      onClick: () => f(p.$.id.value)
                    },
                    c.$.passkeyDeleteButton
                  )
                )
              ),
              y(
                i,
                () => r.div(
                  k(
                    {
                      type: "button",
                      variant: "text",
                      size: "sm",
                      onClick: async () => {
                        await w(p.$.id.value, s.value), i.set(!1);
                      }
                    },
                    c.$.passkeySaveButton
                  ),
                  k(
                    {
                      type: "button",
                      variant: "text",
                      size: "sm",
                      onClick: () => i.set(!1)
                    },
                    c.$.passkeyCancelButton
                  )
                )
              )
            )
          );
        })
      ),
      // Add passkey
      r.div(
        l.class("bc-passkey-add"),
        P(
          I({
            value: u,
            onChange: (p) => u.set(p),
            placeholder: c.$.passkeyNamePlaceholder
          }),
          k(
            {
              type: "button",
              variant: "filled",
              color: "primary",
              onClick: m,
              loading: n
            },
            c.$.passkeyAddButton
          )
        )
      )
    )
  );
}
export {
  ie as Authenticated,
  ne as BetterAuth,
  re as BetterAuthContainer,
  _ as BetterAuthI18n,
  oe as BetterAuthModal,
  de as MagicLinkForm,
  fe as PasskeyManagement,
  me as PasskeySignIn,
  le as TwoFactorSetup,
  ue as TwoFactorVerify,
  ce as Unauthenticated,
  G as createBetterAuthBridge,
  W as createSessionManager,
  Y as mapSocialProviders
};
