"use client";

import { useEffect } from "react";
import { usePathname, useRouter } from "next/navigation";
import { Navbar } from "@/components/layout/navbar";
import { DashboardSidebar } from "@/components/layout/dashboard-sidebar";
import { useAuthStore } from "@/lib/store/auth-store";

/**
 * Every route in the (dashboard) group requires a login. AuthHydrator has
 * already restored the session from localStorage by the time this renders,
 * so isAuthenticated is reliable here — guests are sent to /auth before
 * they ever see a protected page (the API still enforces access on its own).
 */
export default function DashboardLayout({ children }: { children: React.ReactNode }) {
  const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
  const router = useRouter();
  const pathname = usePathname();

  useEffect(() => {
    if (!isAuthenticated) {
      router.replace(`/auth?next=${encodeURIComponent(pathname || "/")}`);
    }
  }, [isAuthenticated, router, pathname]);

  if (!isAuthenticated) return null;

  return (
    <>
      <Navbar />
      <div className="flex min-h-[calc(100vh-64px)]">
        <DashboardSidebar />
        <main className="flex-1 p-6 bg-gray-50/50">{children}</main>
      </div>
    </>
  );
}
