import { Navigate } from "react-router";
import Error from "~/components/error";
import HomePage from "~/components/home";
import Loader from "~/components/loader";
import UserDropdown from "~/components/user-dropdown";
import { MainLayout } from "~/layout";
import { AUTH_ERROR, useUser } from "~/lib/api";
import { forceReload } from "~/lib/utils";

export default function Home() {
  const { user, isLoading, error } = useUser();
  
  if (isLoading) {
    return <Loader />;
  }
  if (error?.message === AUTH_ERROR) {
    return <Navigate to="/login" replace />;
  }
  if (error) {
    return <Error message={error.message} />;
  }

  return (
    <MainLayout page={<HomePage user={user} />}>
      <h1 className="text-2xl font-bold" onClick={forceReload}>
        Khollis&eacute; - {user.className} ⚔️
      </h1>
      <UserDropdown user={user} />
    </MainLayout>
  );
}
