// authcontext.js
import React, { createContext, useState, useEffect, useContext } from "react";
import { isAuthenticated, login, logout } from "./auth"; // Import helper functions

export const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
  const [auth, setAuth] = useState(null);
  const [loading, setLoading] = useState(true);

  const handleLogin = async (email, password) => {
    const userData = await login(email, password);
    if (userData) {
      setAuth(userData);
      localStorage.setItem("user", JSON.stringify(userData));
      return userData;  // <-- returns full user object
    }
    return null;
  };

  const handleLogout = () => {
    logout();
    setAuth(null);
    localStorage.removeItem("user");
  };

  useEffect(() => {
    const initializeAuth = async () => {
      const userData = await isAuthenticated();
      if (userData) {
        setAuth(userData);
      } else {
        setAuth(null);
      }
      setLoading(false);
    };

    initializeAuth();
  }, []);

  //if (loading) return <div>Loading...</div>;

  const contextValue = {
    auth,
    setAuth,
    login: handleLogin,
    logout: handleLogout,
  };
  

  return (
    <AuthContext.Provider value={contextValue}>
      {children}
    </AuthContext.Provider>
  );
};



