import { type JSX, useEffect, useState, createContext } from "react"


type AuthContextType = {
  token: string | null;
  setToken: (token: string | null) => void;
  loading: boolean;
};


const AuthContext = createContext<AuthContextType>({
  token: null,
  setToken: () => {},
  loading: true,
});


export const AuthProvider = ({ children }: { children: JSX.Element }) => {
  const [token, setTokenState] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const savedToken = localStorage.getItem("token");
    if (savedToken) {
      setTokenState(savedToken);
    }
    setLoading(false)
  }, []);

  const setToken = (newToken: string | null) => {
    setTokenState(newToken);
    if (newToken) {
      localStorage.setItem("token", newToken);
    } else {
      localStorage.removeItem("token");
    }
  };

  return (
    <AuthContext.Provider value={{ token, setToken, loading }}>
      {children}
    </AuthContext.Provider>
  );
};

export default AuthContext;
