import { useState as k, useMemo as y, useEffect as D, useCallback as i } from "react";
import { FrankAuth as b } from "@frank-auth/sdk";
import { useAuth as x } from "./use-auth.js";
import { useConfig as C } from "../provider/config-provider.js";
const L = {
  // Default expiration time (15 minutes)
  DEFAULT_EXPIRES_IN: 15 * 60,
  // Minimum time between sends (60 seconds)
  RESEND_COOLDOWN: 60,
  // Email validation regex
  EMAIL_REGEX: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
  // Default templates
  TEMPLATES: {
    SIGN_IN: "magic-link-sign-in",
    SIGN_UP: "magic-link-sign-up",
    VERIFY_EMAIL: "magic-link-verify-email",
    PASSWORD_RESET: "magic-link-password-reset"
  },
  // URL parameter names
  URL_PARAMS: {
    TOKEN: "token",
    EMAIL: "email",
    TYPE: "type",
    REDIRECT: "redirect_to"
  }
};
function N() {
  const { activeOrganization: c, reload: t, userType: g } = x(), { apiUrl: l, publishableKey: w, features: a, linksPath: u, frontendUrl: d } = C(), [S, o] = k(!1), [f, s] = k(null), [E, M] = k(null), [n, O] = k(null), h = y(() => new b({
    publishableKey: w,
    apiUrl: l,
    userType: g ?? "end_user"
  }), [w, l]), I = y(() => a.magicLink, [a.magicLink]), m = y(() => n ? (Date.now() - n.getTime()) / 1e3 >= L.RESEND_COOLDOWN : !1, [n]), A = y(() => {
    if (!n || m) return 0;
    const e = (Date.now() - n.getTime()) / 1e3;
    return Math.max(0, L.RESEND_COOLDOWN - e);
  }, [n, m]);
  D(() => {
    if (!n || m) return;
    const e = setInterval(() => {
    }, 1e3);
    return () => clearInterval(e);
  }, [n, m]), i((e) => {
    const r = {
      code: e.code || "UNKNOWN_ERROR",
      message: e.message || "An unknown error occurred",
      details: e.details,
      field: e.field
    };
    throw s(r), r;
  }, []);
  const T = i((e) => L.EMAIL_REGEX.test(e), []), v = i((e) => {
    const r = e || window.location.href;
    try {
      return new URL(r).searchParams.get(L.URL_PARAMS.TOKEN);
    } catch {
      return null;
    }
  }, []), _ = i(async (e, r) => {
    if (!I) throw new Error("Magic links not available");
    if (!T(e)) throw new Error("Invalid email address");
    try {
      o(!0), s(null);
      const R = {
        email: e,
        redirectUrl: r?.redirectUrl || `${d ?? window.location.origin}${u?.magicLink}`,
        // organizationId: options?.organizationId || activeOrganization?.id,
        // customData: options?.customData,
        expiresIn: r?.expiresIn || L.DEFAULT_EXPIRES_IN
        // locale: options?.locale,
      }, U = await h.sendMagicLink(R);
      return M(e), O(/* @__PURE__ */ new Date()), {
        success: U.success,
        email: e,
        message: U.message,
        expiresAt: new Date(Date.now() + R.expiresIn * 1e3)
      };
    } catch (R) {
      return {
        success: !1,
        email: e,
        expiresAt: /* @__PURE__ */ new Date(),
        error: R.message || "Failed to send magic link"
      };
    } finally {
      o(!1);
    }
  }, [h, I, T, c]), p = i(async (e) => {
    if (!I) throw new Error("Magic links not available");
    if (!e) throw new Error("Verification token is required");
    try {
      o(!0), s(null);
      const r = await h.verifyMagicLink(e);
      return r.session ? (await t(), {
        success: !0,
        user: r.user,
        session: r.session,
        requiresAdditionalVerification: r.mfaRequired,
        mfaToken: r.mfaToken
      }) : {
        success: !1,
        error: r.error || "Magic link verification failed"
      };
    } catch (r) {
      return {
        success: !1,
        error: r.message || "Magic link verification failed"
      };
    } finally {
      o(!1);
    }
  }, [h, I, t]), P = i(async (e) => {
    const r = v(e);
    return r ? p(r) : {
      success: !1,
      error: "No verification token found in URL"
    };
  }, [v, p]), F = i(async () => {
    if (!E)
      throw new Error("No previous magic link to resend");
    if (!m)
      throw new Error(`Please wait ${Math.ceil(A)} seconds before resending`);
    return _(E);
  }, [E, m, A, _]), V = i(() => {
    s(null), M(null), O(null);
  }, []);
  return {
    // Magic link state
    isLoading: S,
    error: f,
    lastSentEmail: E,
    lastSentAt: n,
    canResend: m,
    timeUntilResend: A,
    // Magic link operations
    sendMagicLink: _,
    verifyMagicLink: p,
    resendMagicLink: F,
    // Magic link verification
    verifyFromUrl: P,
    extractTokenFromUrl: v,
    // Utility methods
    isValidEmail: T,
    clearState: V
  };
}
function $() {
  const {
    sendMagicLink: c,
    isLoading: t,
    error: g,
    lastSentEmail: l,
    canResend: w,
    resendMagicLink: a,
    isValidEmail: u,
    clearState: d
  } = N(), [S, o] = k("idle"), f = i(async (E, M) => {
    if (!u(E))
      throw new Error("Please enter a valid email address");
    try {
      const n = await c(E, {
        redirectUrl: M || "/dashboard",
        template: L.TEMPLATES.SIGN_IN
      });
      return n.success && o("email_sent"), n;
    } catch (n) {
      throw o("idle"), n;
    }
  }, [c, u]), s = i(() => {
    o("idle"), d();
  }, [d]);
  return {
    signIn: f,
    resend: a,
    reset: s,
    state: S,
    sentTo: l,
    canResend: w,
    isLoading: t,
    error: g,
    isValidEmail: u
  };
}
function X() {
  const {
    verifyFromUrl: c,
    verifyMagicLink: t,
    extractTokenFromUrl: g,
    isLoading: l,
    error: w
  } = N(), [a, u] = k("idle"), [d, S] = k(null);
  D(() => {
    const f = g();
    f && a === "idle" && o(f);
  }, [g, a]);
  const o = i(async (f) => {
    try {
      u("verifying");
      const s = f ? await t(f) : await c();
      return S(s), u(s.success ? "success" : "error"), s;
    } catch (s) {
      throw u("error"), S({
        success: !1,
        error: s.message
      }), s;
    }
  }, [t, c]);
  return {
    verify: o,
    state: a,
    result: d,
    isVerifying: a === "verifying" || l,
    isSuccess: a === "success",
    isError: a === "error",
    error: w || d?.error,
    requiresMFA: d?.requiresAdditionalVerification,
    mfaToken: d?.mfaToken
  };
}
function j() {
  const { sendMagicLink: c, isValidEmail: t } = N();
  return {
    sendResetLink: i(async (l) => {
      if (!t(l))
        throw new Error("Please enter a valid email address");
      return c(l, {
        template: L.TEMPLATES.PASSWORD_RESET,
        redirectUrl: `${window.location.origin}/auth/reset-password`
      });
    }, [c, t]),
    isValidEmail: t
  };
}
export {
  L as MAGIC_LINK_CONFIG,
  N as useMagicLink,
  j as useMagicLinkPasswordReset,
  $ as useMagicLinkSignIn,
  X as useMagicLinkVerification
};
//# sourceMappingURL=use-magic-link.js.map
