// Simple Auth Context
const AuthContext = React.createContext(null);

function AuthProvider({ children }) {
  const [user, setUser] = React.useState(null);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    window.AuthAPI.me()
      .then(setUser)
      .catch(() => setUser(null))
      .finally(() => setLoading(false));
  }, []);

  async function login(email, password) {
    const res = await window.AuthAPI.login(email, password);
    setUser(res.user);
    return res.user;
  }

  async function logout() {
    await window.AuthAPI.logout();
    setUser(null);
  }

  const value = { user, setUser, login, logout, loading };
  return React.createElement(AuthContext.Provider, { value }, children);
}

function useAuth() {
  return React.useContext(AuthContext);
}

window.AuthContext = { AuthProvider, useAuth };
