import { useState, useEffect } from "react";

export function useAdminAuth() {
  const [isAdminAuthenticated, setIsAdminAuthenticated] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const checkAuth = () => {
      const authenticated = localStorage.getItem("admin_authenticated") === "true";
      setIsAdminAuthenticated(authenticated);
      setIsLoading(false);
    };

    checkAuth();

    // Listen for storage changes across tabs
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === "admin_authenticated") {
        checkAuth();
      }
    };

    window.addEventListener("storage", handleStorageChange);
    
    return () => {
      window.removeEventListener("storage", handleStorageChange);
    };
  }, []);

  const login = (userData: any) => {
    localStorage.setItem("admin_authenticated", "true");
    localStorage.setItem("admin_user", JSON.stringify(userData));
    setIsAdminAuthenticated(true);
  };

  const logout = () => {
    localStorage.removeItem("admin_authenticated");
    localStorage.removeItem("admin_user");
    setIsAdminAuthenticated(false);
  };

  const getAdminUser = () => {
    const userData = localStorage.getItem("admin_user");
    return userData ? JSON.parse(userData) : null;
  };

  return {
    isAdminAuthenticated,
    isLoading,
    login,
    logout,
    getAdminUser,
  };
}