import { useState as O, useMemo as P, useCallback as o, useEffect as K } from "react";
import { FrankAuth as V } from "@frank-auth/sdk";
import { useAuth as x } from "./use-auth.js";
import { useConfig as N } from "../provider/config-provider.js";
const h = {
  google: {
    name: "Google",
    displayName: "Google",
    icon: "🔴",
    color: "#4285f4",
    defaultScopes: ["openid", "profile", "email"]
  },
  microsoft: {
    name: "Microsoft",
    displayName: "Microsoft",
    icon: "🟦",
    color: "#00a1f1",
    defaultScopes: ["openid", "profile", "email"]
  },
  github: {
    name: "GitHub",
    displayName: "GitHub",
    icon: "⚫",
    color: "#333333",
    defaultScopes: ["user:email"]
  },
  apple: {
    name: "Apple",
    displayName: "Apple",
    icon: "🍎",
    color: "#000000",
    defaultScopes: ["name", "email"]
  },
  facebook: {
    name: "Facebook",
    displayName: "Facebook",
    icon: "🔵",
    color: "#1877f2",
    defaultScopes: ["email", "public_profile"]
  },
  twitter: {
    name: "Twitter",
    displayName: "Twitter",
    icon: "🐦",
    color: "#1da1f2",
    defaultScopes: ["users.read", "tweet.read"]
  },
  linkedin: {
    name: "LinkedIn",
    displayName: "LinkedIn",
    icon: "🔵",
    color: "#0077b5",
    defaultScopes: ["r_liteprofile", "r_emailaddress"]
  },
  discord: {
    name: "Discord",
    displayName: "Discord",
    icon: "🎮",
    color: "#5865f2",
    defaultScopes: ["identify", "email"]
  }
};
function R() {
  const { user: t, activeOrganization: d, reload: l, userType: m } = x(), { apiUrl: f, publishableKey: k, features: y } = N(), [w, b] = O([]), [p, a] = O(!1), [S, u] = O(null), c = P(() => new V({
    publishableKey: k,
    apiUrl: f,
    userType: m ?? "end_user"
  }), [k, f]), s = P(() => y.oauth, [y.oauth]), g = o((e) => {
    const r = {
      code: e.code || "UNKNOWN_ERROR",
      message: e.message || "An unknown error occurred",
      details: e.details,
      field: e.field
    };
    throw u(r), r;
  }, []), I = o(async () => {
    if (s)
      try {
        a(!0), u(null);
        const e = await c.listOAuthProviders();
        b(e);
      } catch (e) {
        console.error("Failed to load OAuth providers:", e), u({
          code: "OAUTH_PROVIDERS_LOAD_FAILED",
          message: "Failed to load OAuth providers"
        });
      } finally {
        a(!1);
      }
  }, [c, s]);
  K(() => {
    I();
  }, [I]);
  const A = o(async (e, r) => {
    if (!s) throw new Error("OAuth not available");
    try {
      const i = {
        provider: e,
        redirectUrl: r?.redirectUrl || `${window.location.origin}/auth/callback`,
        scopes: r?.scopes,
        state: r?.state,
        prompt: r?.prompt,
        organizationId: r?.organizationId || d?.id,
        connection: r?.connection
      };
      return (await c.initiateSSOLogin(i)).authUrl;
    } catch (i) {
      return g(i), "";
    }
  }, [c, s, d, g]), n = o(async (e, r) => {
    if (!s) throw new Error("OAuth not available");
    try {
      a(!0), u(null);
      const i = await A(e, r);
      window.location.href = i;
    } catch (i) {
      g(i);
    } finally {
      a(!1);
    }
  }, [A, s, g]), U = o(async (e, r, i) => {
    if (!s) throw new Error("OAuth not available");
    try {
      a(!0), u(null);
      const v = {
        provider: e,
        code: r || new URLSearchParams(window.location.search).get("code") || "",
        state: i || new URLSearchParams(window.location.search).get("state") || ""
      }, E = await c.handleSSOCallback(v);
      return E.success ? (await l(), {
        success: !0,
        user: E.user,
        session: E.session
      }) : {
        success: !1,
        error: E.error || "OAuth authentication failed"
      };
    } catch (v) {
      return {
        success: !1,
        error: v.message || "OAuth callback failed"
      };
    } finally {
      a(!1);
    }
  }, [c, s, l]), C = o(async (e, r) => {
    if (!t) throw new Error("User not authenticated");
    if (!s) throw new Error("OAuth not available");
    try {
      a(!0), u(null);
      const i = await A(e, {
        ...r,
        state: `connect:${e}:${t.id}`
      });
      window.location.href = i;
    } catch (i) {
      g(i);
    } finally {
      a(!1);
    }
  }, [t, A, s, g]), L = o(async (e) => {
    if (!t) throw new Error("User not authenticated");
    if (!s) throw new Error("OAuth not available");
    try {
      a(!0), u(null), await c.disconnectOAuthProvider(e), await l();
    } catch (r) {
      g(r);
    } finally {
      a(!1);
    }
  }, [c, t, s, l, g]), W = o((e) => t?.connectedAccounts ? t.connectedAccounts.some((r) => r.provider === e) : !1, [t]), _ = o((e) => w.find((r) => r.name === e) || null, [w]), D = o((e) => n("google", {
    scopes: h.google.defaultScopes,
    ...e
  }), [n]), F = o((e) => n("microsoft", {
    scopes: h.microsoft.defaultScopes,
    ...e
  }), [n]), T = o((e) => n("github", {
    scopes: h.github.defaultScopes,
    ...e
  }), [n]), G = o((e) => n("apple", {
    scopes: h.apple.defaultScopes,
    ...e
  }), [n]), H = o((e) => n("facebook", {
    scopes: h.facebook.defaultScopes,
    ...e
  }), [n]), z = o((e) => n("twitter", {
    scopes: h.twitter.defaultScopes,
    ...e
  }), [n]), M = o((e) => n("linkedin", {
    scopes: h.linkedin.defaultScopes,
    ...e
  }), [n]), $ = o((e) => n("discord", {
    scopes: h.discord.defaultScopes,
    ...e
  }), [n]), q = o(async () => {
    await I();
  }, [I]);
  return {
    // OAuth state
    providers: w,
    isLoading: p,
    error: S,
    // OAuth authentication
    signInWithProvider: n,
    handleCallback: U,
    // Provider management
    connectProvider: C,
    disconnectProvider: L,
    // Provider information
    isProviderConnected: W,
    getProviderInfo: _,
    // Common providers
    signInWithGoogle: D,
    signInWithMicrosoft: F,
    signInWithGitHub: T,
    signInWithApple: G,
    signInWithFacebook: H,
    signInWithTwitter: z,
    signInWithLinkedIn: M,
    signInWithDiscord: $,
    // Utility methods
    refreshProviders: q,
    getAuthUrl: A
  };
}
function X(t) {
  const {
    signInWithProvider: d,
    connectProvider: l,
    disconnectProvider: m,
    isProviderConnected: f,
    getProviderInfo: k,
    isLoading: y,
    error: w
  } = R(), b = P(() => h[t], [t]), p = P(() => k(t), [k, t]), a = P(() => f(t), [f, t]), S = o((s) => d(t, {
    scopes: b.defaultScopes,
    ...s
  }), [d, t, b.defaultScopes]), u = o((s) => l(t, s), [l, t]), c = o(() => m(t), [m, t]);
  return {
    provider: b,
    providerInfo: p,
    isConnected: a,
    signIn: S,
    connect: u,
    disconnect: c,
    isLoading: y,
    error: w,
    isEnabled: !!p?.enabled
  };
}
function Y() {
  const { handleCallback: t } = R(), [d, l] = O("idle"), [m, f] = O(null);
  return {
    processCallback: o(async (y, w, b) => {
      const p = new URLSearchParams(window.location.search), a = y || p.get("provider") || "google", S = w || p.get("code") || "", u = b || p.get("state") || "";
      if (!S) {
        l("error"), f({
          success: !1,
          error: "No authorization code received"
        });
        return;
      }
      try {
        l("processing");
        const c = await t(a, S, u);
        return f(c), l(c.success ? "success" : "error"), c;
      } catch (c) {
        const s = {
          success: !1,
          error: c.message || "OAuth callback failed"
        };
        return f(s), l("error"), s;
      }
    }, [t]),
    state: d,
    result: m,
    isProcessing: d === "processing",
    isSuccess: d === "success",
    isError: d === "error"
  };
}
export {
  h as OAUTH_PROVIDERS,
  R as useOAuth,
  Y as useOAuthCallback,
  X as useOAuthProvider
};
//# sourceMappingURL=use-oauth.js.map
