"use client";

import { useEffect } from "react";
import { useLocale } from "next-intl";
import { Loader2 } from "lucide-react";
import { useRouter } from "@/i18n/routing";
import { useAuthStore } from "@/lib/stores/auth.store";
import { RouteGuard } from "@/components/auth/route-guard";

/** Full-viewport routes (POS, queue TV display) — auth only, no dashboard chrome. */
export default function FullscreenLayout({ children }: { children: React.ReactNode }) {
  const locale = useLocale();
  const router = useRouter();
  const user = useAuthStore((s) => s.user);
  const hasHydrated = useAuthStore((s) => s._hasHydrated);
  const dir = locale === "en" ? "ltr" : "rtl";

  useEffect(() => {
    // Only redirect AFTER the persisted auth has rehydrated from localStorage —
    // otherwise a page refresh sees the empty initial state and bounces an
    // already-authenticated user to /login before their session loads back in.
    if (hasHydrated && !user?.accessToken) {
      router.replace("/login");
    }
  }, [hasHydrated, user, router]);

  // While rehydrating, show a loader instead of redirecting or flashing content.
  if (!hasHydrated) {
    return (
      <div className="flex min-h-svh items-center justify-center" dir={dir}>
        <Loader2 className="size-6 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <div className="min-h-svh" dir={dir}>
      <RouteGuard>{children}</RouteGuard>
    </div>
  );
}
