"use client";
import { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { apiCall } from "../../backend/utils/apiCall.js";
function useCustomerAuth(orgSlug) {
  const router = useRouter();
  const [state, setState] = useState({
    user: null,
    roles: [],
    resolvedFeatures: [],
    isPortalAdmin: false,
    loading: true,
    error: null
  });
  useEffect(() => {
    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) {
          setState((prev) => ({ ...prev, loading: false, user: null }));
          return;
        }
        if (!ok || !data?.ok) {
          setState((prev) => ({ ...prev, loading: false, error: data?.error || `HTTP ${status}` }));
          return;
        }
        setState({
          user: data.user,
          roles: data.roles || [],
          resolvedFeatures: data.resolvedFeatures || [],
          isPortalAdmin: data.isPortalAdmin || false,
          loading: false,
          error: null
        });
      } catch {
        if (!cancelled) {
          setState((prev) => ({ ...prev, loading: false, error: "Network error" }));
        }
      }
    }
    fetchProfile();
    return () => {
      cancelled = true;
    };
  }, []);
  const loginPath = orgSlug ? `/${orgSlug}/portal/login` : "/portal/login";
  const logout = useCallback(async () => {
    try {
      await apiCall("/api/customer_accounts/portal/logout", { method: "POST" });
    } catch {
    }
    setState({
      user: null,
      roles: [],
      resolvedFeatures: [],
      isPortalAdmin: false,
      loading: false,
      error: null
    });
    router.push(loginPath);
  }, [router, loginPath]);
  return { ...state, logout };
}
export {
  useCustomerAuth
};
//# sourceMappingURL=useCustomerAuth.js.map
