import { AuthOptions } from "@/app/api/auth/[...nextauth]/authOptions";
import { getServerSession } from "next-auth";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import PortfolioHome from "../components/home/PortfolioHome";

const Home = async (props: {
  searchParams: Promise<{ folder?: string; view?: string }>;
}) => {
  const user = await getServerSession(AuthOptions);

  if (!user?.user) {
    redirect("/");
  }

  // Device-level display preference travels as a cookie so the server renders
  // the chosen view on first paint (no client-side flicker).
  const cookieStore = await cookies();
  const initialDisplay =
    cookieStore.get("home-display")?.value === "list" ? "list" : "grid";

  // The selected rail view survives refresh via the URL; an unknown folder id
  // falls back to All client-side once data loads.
  const searchParams = await props.searchParams;
  const initialView =
    searchParams.view === "starred"
      ? ("starred" as const)
      : /^\d+$/.test(searchParams.folder ?? "")
        ? { folderId: searchParams.folder! }
        : ("all" as const);

  return (
    <PortfolioHome initialDisplay={initialDisplay} initialView={initialView} />
  );
};
export default Home;
