import * as React from "react";
import { useNavigate } from "react-router-dom";
import { useAuth, AuthPage } from "../react-auth";

export function RequireAuth({ children }: { children: React.ReactNode }) {
  const { currentUser, loading, error, login, register } = useAuth();
  const navigate = useNavigate();
  const [mode, setMode] = React.useState<"login" | "register">("login");

  if (currentUser) {
    return <>{children}</>;
  }

  return (
    <AuthPage
      mode={mode}
      onBack={() => navigate("/")}
      onSwitchMode={() => setMode(mode === "login" ? "register" : "login")}
      login={login}
      register={register}
      loading={loading}
      error={error}
      currentUser={currentUser}
    />
  );
}
