"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Dashboard from "./pages/dashboard/Dashboard";

export default function Home() {
  const router = useRouter();
  const [isClient, setIsClient] = useState(false);

  useEffect(() => {
    setIsClient(true);
    // Verify auth via API + cookies
    fetch("/api/documents", { credentials: "include" })
      .then((res) => {
        if (res.status === 401) {
          // Not authenticated - redirect to login
          router.push("/pages/login");
        }
      })
      .catch(() => {
        // Network error - try to load anyway
      });
  }, [router]);

  if (!isClient) {
    return null; // Avoid hydration mismatch
  }

  return (
    <Dashboard
      onLogout={() => {
        // Clear cookies via logout endpoint
        fetch("/auth/logout", { method: "POST", credentials: "include" }).then(
          () => {
            router.push("/pages/login");
          }
        );
      }}
    />
  );
}
