"use client";

import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { BrapiSidebar, BrapiTopbar } from "@/components/brapi/BrapiShell";
import { useMenuStore, useAuthStore } from "@/stores";

export default function AppLayout({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const fetchMenus = useMenuStore((state) => state.fetchMenus);
  const token = useAuthStore((state) => state.token);
  const hydrated = useAuthStore((state) => state.hydrated);

  useEffect(() => {
    if (!hydrated) {
      return;
    }
    if (!token) {
      router.replace("/login");
      return;
    }
    void fetchMenus();
  }, [fetchMenus, hydrated, router, token]);

  if (!hydrated || !token) {
    return null;
  }

  return (
    <div className="flex h-screen overflow-hidden bg-slate-50 text-slate-900 dark:bg-slate-950 dark:text-slate-50">
      <BrapiSidebar />
      <div className="flex min-w-0 flex-1 flex-col overflow-hidden">
        <BrapiTopbar />
        <main className="min-h-0 min-w-0 flex-1 overflow-y-auto p-4 md:p-6">{children}</main>
      </div>
    </div>
  );
}
