'use client';

import React, { createContext, useContext, useEffect, useState } from 'react';

import { isUserSuperAdmin } from '@/services/auth';

interface AuthContextType {
  isSuperAdmin: boolean;
  isLoading: boolean;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [isSuperAdmin, setIsSuperAdmin] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    isUserSuperAdmin()
      .then(setIsSuperAdmin)
      .finally(() => setIsLoading(false));
  }, []);

  return (
    <AuthContext.Provider value={{ isSuperAdmin, isLoading }}>{children}</AuthContext.Provider>
  );
}

export function useAuth() {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
}
