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