import { useState as I, useMemo as s, useCallback as c, useEffect as Y } from "react";
import { FrankOrganization as nn } from "@frank-auth/sdk";
import { useAuth as tn } from "./use-auth.js";
import { useAuth as en } from "../provider/auth-provider.js";
import { useConfig as an } from "../provider/config-provider.js";
function E() {
  const {
    organization: l,
    organizationMemberships: g,
    activeOrganization: i,
    switchOrganization: z,
    session: v,
    reload: u
  } = tn(), { frankOrg: f } = en(), { apiUrl: h, publishableKey: m, userType: O } = an(), [y, p] = I([]), [M, rn] = I([]), [A, a] = I(!1), [U, d] = I(null), e = s(() => (console.log(
    "Initializing Frank Organization SDK",
    v,
    h,
    m,
    O
  ), new nn(
    {
      publishableKey: m,
      apiUrl: h,
      userType: O ?? "end_user"
    },
    v?.accessToken
  )), [m, h, v?.accessToken]), r = c((n) => {
    const t = {
      code: n.code || "UNKNOWN_ERROR",
      message: n.message || "An unknown error occurred",
      details: n.details,
      field: n.field
    };
    throw d(t), t;
  }, []), o = c(async () => {
    if (e)
      try {
        a(!0), d(null);
        const n = await e.listOrganizations({
          fields: []
        });
        p(n.data ?? []);
      } catch (n) {
        console.error("Failed to load organizations:", n), d({
          code: "ORGANIZATIONS_LOAD_FAILED",
          message: "Failed to load organizations"
        });
      } finally {
        a(!1);
      }
  }, [e]);
  Y(() => {
    o();
  }, [o]);
  const R = c(
    async (n) => {
      if (!e)
        throw new Error("Organization service not available");
      try {
        a(!0), d(null);
        const t = {
          name: n.name,
          slug: n.slug,
          // description: params.description,
          logoUrl: n.logoUrl,
          websiteUrl: n.websiteUrl,
          settings: n.settings,
          plan: n.planId ?? "free"
          // createTrialPeriod: true,
          // enableAuthService: true,
          // endUserLimit: 10000000,
          // externalUserLimit: 0,
          // orgType: "platform",
          // plan: "",
        }, w = await e.createOrganization(t);
        return await o(), await u(), w;
      } catch (t) {
        return r(t);
      } finally {
        a(!1);
      }
    },
    [e, o, u, r]
  ), S = c(
    async (n, t) => {
      if (!e)
        throw new Error("Organization service not available");
      try {
        a(!0), d(null);
        const w = {
          name: t.name,
          slug: t.slug,
          description: t.description,
          logoUrl: t.logoUrl,
          websiteUrl: t.websiteUrl,
          settings: t.settings
        }, X = await e.updateOrganization(
          n,
          w
        );
        return await o(), await u(), X;
      } catch (w) {
        return r(w);
      } finally {
        a(!1);
      }
    },
    [e, o, u, r]
  ), k = c(
    async (n) => {
      if (!e)
        throw new Error("Organization service not available");
      try {
        a(!0), d(null), await e.deleteOrganization(n, {
          notifyMembers: !0,
          confirm: !0,
          dataRetention: 0
        }), await o(), await u();
      } catch (t) {
        r(t);
      } finally {
        a(!1);
      }
    },
    [e, o, u, r]
  ), L = c(
    async (n) => {
      await z(n), await o();
    },
    [z, o]
  ), C = c(
    async (n) => {
      if (!e || !i)
        throw new Error("Organization service not available");
      try {
        a(!0), d(null);
        const t = {
          emailAddress: n.emailAddress,
          role: n.role,
          redirectUrl: n.redirectUrl,
          publicMetadata: n.publicMetadata,
          privateMetadata: n.privateMetadata
        };
        await e.addMember(i.id, t), await o();
      } catch (t) {
        r(t);
      } finally {
        a(!1);
      }
    },
    [e, i, o, r]
  ), N = c(
    async (n) => {
      if (!e || !i)
        throw new Error("Organization service not available");
      try {
        a(!0), d(null), await e.removeMember(i.id, n, {
          notifyUser: !0
        }), await o();
      } catch (t) {
        r(t);
      } finally {
        a(!1);
      }
    },
    [e, i, o, r]
  ), T = c(
    async (n, t) => {
      if (!e || !i)
        throw new Error("Organization service not available");
      try {
        a(!0), d(null), await e.updateMemberRole(
          i.id,
          n,
          {
            roleId: t
          }
        ), await o();
      } catch (w) {
        r(w);
      } finally {
        a(!1);
      }
    },
    [e, i, o, r]
  ), q = c(async () => {
    if (!e || !i)
      throw new Error("Organization service not available");
    try {
      return ((await e.listMembers(i.id)).data ?? []).map(
        (t) => ({
          id: t.userId,
          userId: t.userId,
          organizationId: t.organizationId,
          role: t.role,
          status: t.status,
          joinedAt: t.joinedAt,
          invitedBy: t.invitedBy
        })
      );
    } catch (n) {
      return r(n), [];
    }
  }, [e, i, r]), F = c(
    async (n, t) => {
      if (!e)
        throw new Error("Organization service not available");
      try {
        a(!0), d(null);
        const w = {
          ...t ?? {},
          token: n,
          acceptTerms: !0
        };
        await e.acceptInvitation(w), await o(), await u();
      } catch (w) {
        r(w);
      } finally {
        a(!1);
      }
    },
    [e, o, u, r]
  ), j = c(
    async (n) => {
      if (!e)
        throw new Error("Organization service not available");
      try {
        a(!0), d(null);
        const t = {
          token: n
        };
        await e.declineInvitation(t), await o();
      } catch (t) {
        r(t);
      } finally {
        a(!1);
      }
    },
    [e, o, r]
  ), x = c(
    async (n) => {
      if (!e)
        throw new Error("Organization service not available");
      try {
        a(!0), d(null), await e.cancelInvitation(n), await o();
      } catch (t) {
        r(t);
      } finally {
        a(!1);
      }
    },
    [e, o, r]
  ), D = c(
    async (n) => {
      if (!e)
        throw new Error("Organization service not available");
      try {
        a(!0), d(null), await e.resendInvitation(n);
      } catch (t) {
        r(t);
      } finally {
        a(!1);
      }
    },
    [e, r]
  ), _ = c(
    async (n) => {
      if (!e || !i)
        throw new Error("Organization service not available");
      try {
        a(!0), d(null);
        const t = await e.updateOrganizationSettings(
          i.id,
          n
        );
        return await o(), await u(), t;
      } catch (t) {
        return r(t);
      } finally {
        a(!1);
      }
    },
    [
      e,
      i,
      o,
      u,
      r
    ]
  ), K = s(
    () => i?.id || null,
    [i]
  ), B = s(
    () => i?.name || null,
    [i]
  ), G = s(
    () => i?.slug || null,
    [i]
  ), b = s(() => i ? g.find(
    (n) => n.organization.id === i.id
  ) : null, [i, g]), W = s(
    () => b?.role === "owner",
    [b]
  ), Z = s(
    () => ["owner", "admin"].includes(b?.role || ""),
    [b]
  ), $ = s(() => !!b, [b]), H = s(
    () => i?.memberCount || 0,
    [i]
  ), J = s(
    () => M.filter((n) => n.status === "pending").length,
    [M]
  ), P = s(
    () => y.length > 0,
    [y]
  ), Q = s(() => O === "internal" ? !0 : O === "external" ? g.some((n) => n.role === "owner") : !1, [O, g]), V = s(
    () => y.length > 1,
    [y]
  );
  return {
    // Organization state
    organization: l,
    organizations: y,
    activeOrganization: i,
    memberships: g,
    invitations: M,
    isLoaded: !!e,
    isLoading: A,
    error: U,
    // Organization management
    createOrganization: R,
    updateOrganization: S,
    deleteOrganization: k,
    switchOrganization: L,
    // Member management
    inviteMember: C,
    removeMember: N,
    updateMemberRole: T,
    getMembers: q,
    // Invitation management
    acceptInvitation: F,
    declineInvitation: j,
    cancelInvitation: x,
    resendInvitation: D,
    // Settings management
    updateSettings: _,
    // Convenience properties
    organizationId: K,
    organizationName: B,
    organizationSlug: G,
    isOwner: W,
    isAdmin: Z,
    isMember: $,
    memberCount: H,
    pendingInvitations: J,
    // Multi-tenant helpers
    hasOrganizations: P,
    canCreateOrganization: Q,
    canSwitchOrganization: V
  };
}
function dn() {
  const {
    activeOrganization: l,
    memberships: g,
    isOwner: i,
    isAdmin: z,
    isMember: v,
    memberCount: u
  } = E(), f = s(() => l ? g.find((h) => h.organization.id === l.id) : null, [l, g]);
  return {
    organization: l,
    membership: f,
    role: f?.role || null,
    isOwner: i,
    isAdmin: z,
    isMember: v,
    memberCount: u,
    joinedAt: f?.joinedAt || null,
    status: f?.status || null
  };
}
function gn() {
  const {
    invitations: l,
    acceptInvitation: g,
    declineInvitation: i,
    cancelInvitation: z,
    resendInvitation: v,
    inviteMember: u,
    isAdmin: f,
    isLoading: h,
    error: m
  } = E(), O = s(
    () => l.filter((p) => p.status === "pending"),
    [l]
  ), y = s(
    () => l.filter((p) => p.status === "expired"),
    [l]
  );
  return {
    invitations: l,
    pendingInvitations: O,
    expiredInvitations: y,
    acceptInvitation: g,
    declineInvitation: i,
    cancelInvitation: f ? z : void 0,
    resendInvitation: f ? v : void 0,
    inviteMember: f ? u : void 0,
    canManageInvitations: f,
    isLoading: h,
    error: m
  };
}
function wn() {
  const {
    organizations: l,
    activeOrganization: g,
    switchOrganization: i,
    canSwitchOrganization: z,
    isLoading: v
  } = E();
  return {
    organizations: l,
    activeOrganization: g,
    switchOrganization: i,
    canSwitchOrganization: z,
    isLoading: v,
    hasMultipleOrganizations: l.length > 1
  };
}
export {
  E as useOrganization,
  gn as useOrganizationInvitations,
  dn as useOrganizationMembership,
  wn as useOrganizationSwitcher
};
//# sourceMappingURL=use-organization.js.map
