"use client";
import { jsx } from "react/jsx-runtime";
import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useRef,
  useState
} from "react";
import { apiCall } from "../backend/utils/apiCall.js";
const PortalCtx = createContext(null);
function usePortalContext() {
  const ctx = useContext(PortalCtx);
  if (!ctx) throw new Error("usePortalContext must be used inside <PortalProvider>");
  return ctx;
}
function PortalProvider({ orgSlug, children, initialAuth, initialTenant }) {
  const hasServerData = initialAuth !== void 0;
  const [authState, setAuthState] = useState(() => {
    if (hasServerData && initialAuth) {
      return {
        user: {
          id: initialAuth.sub,
          email: initialAuth.email,
          displayName: initialAuth.displayName,
          emailVerified: false,
          customerEntityId: initialAuth.customerEntityId ?? null,
          personEntityId: initialAuth.personEntityId ?? null,
          isActive: true,
          lastLoginAt: null,
          createdAt: ""
        },
        roles: [],
        resolvedFeatures: initialAuth.resolvedFeatures,
        isPortalAdmin: initialAuth.resolvedFeatures.some((f) => f === "portal.*"),
        loading: false,
        error: null
      };
    }
    if (hasServerData && !initialAuth) {
      return { user: null, roles: [], resolvedFeatures: [], isPortalAdmin: false, loading: false, error: null };
    }
    return { user: null, roles: [], resolvedFeatures: [], isPortalAdmin: false, loading: true, error: null };
  });
  const profileEnrichedRef = useRef(false);
  useEffect(() => {
    if (hasServerData && !initialAuth) return;
    if (profileEnrichedRef.current) return;
    let cancelled = false;
    async function fetchProfile() {
      try {
        const { ok, status, result: data } = await apiCall("/api/customer_accounts/portal/profile");
        if (cancelled) return;
        if (status === 401) {
          setAuthState((prev) => ({ ...prev, loading: false, user: prev.user }));
          return;
        }
        if (!ok || !data?.ok) {
          setAuthState((prev) => ({ ...prev, loading: false }));
          return;
        }
        profileEnrichedRef.current = true;
        setAuthState({
          user: data.user,
          roles: data.roles || [],
          resolvedFeatures: data.resolvedFeatures || [],
          isPortalAdmin: data.isPortalAdmin || false,
          loading: false,
          error: null
        });
      } catch {
        if (!cancelled) {
          setAuthState((prev) => ({ ...prev, loading: false }));
        }
      }
    }
    fetchProfile();
    return () => {
      cancelled = true;
    };
  }, [hasServerData, initialAuth]);
  const logout = useCallback(async () => {
    try {
      await apiCall("/api/customer_accounts/portal/logout", { method: "POST" });
    } catch {
    }
    profileEnrichedRef.current = false;
    setAuthState({ user: null, roles: [], resolvedFeatures: [], isPortalAdmin: false, loading: false, error: null });
    window.location.assign(`/${orgSlug}/portal/login`);
  }, [orgSlug]);
  const [tenantState] = useState(() => {
    if (initialTenant) {
      return {
        tenantId: initialTenant.tenantId,
        organizationId: initialTenant.organizationId,
        organizationName: initialTenant.organizationName,
        loading: false,
        error: null
      };
    }
    return { tenantId: void 0, organizationId: void 0, organizationName: void 0, loading: true, error: null };
  });
  useEffect(() => {
    if (initialTenant) return;
  }, [initialTenant]);
  const value = {
    auth: { ...authState, logout },
    tenant: tenantState,
    orgSlug
  };
  return /* @__PURE__ */ jsx(PortalCtx.Provider, { value, children });
}
export {
  PortalProvider,
  usePortalContext
};
//# sourceMappingURL=PortalContext.js.map
