"use client";

import { useEffect, useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import type { ReactNode } from "react";
import DashboardShell from "@/components/layout/DashboardShell";
import { useAuthStore } from "@/store/authStore";
import { useTenantStore } from "@/store/tenantStore";

export default function DashboardLayout({ children }: { children: ReactNode }) {
  const router = useRouter();
  const pathname = usePathname();
  const token = useAuthStore((s) => s.accessToken);
  const hydrateAuth = useAuthStore((s) => s.hydrate);
  const hydrateTenant = useTenantStore((s) => s.hydrate);
  const [ready, setReady] = useState(false);

  useEffect(() => {
    hydrateAuth();
    hydrateTenant();
    setReady(true);
  }, [hydrateAuth, hydrateTenant]);

  useEffect(() => {
    if (!ready) return;
    if (!token && !pathname.startsWith("/login")) {
      router.replace("/login");
    }
  }, [token, pathname, ready, router]);

  return <DashboardShell>{children}</DashboardShell>;
}
