"use client";

import { useEffect } from "react";
import { useLocale } from "next-intl";
import { useRouter } from "@/i18n/routing";
import { Sidebar } from "@/components/layout/sidebar";
import { Topbar } from "@/components/layout/topbar";
import { RouteGuard } from "@/components/auth/route-guard";
import { CafeThemeProvider } from "@/components/theme/cafe-theme-provider";
import { useAuthStore } from "@/lib/stores/auth.store";
import { useOfflineSync } from "@/lib/offline/use-offline-sync";

export default function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const locale = useLocale();
  const router = useRouter();
  const user = useAuthStore((s) => s.user);
  const hasHydrated = useAuthStore((s) => s._hasHydrated);
  useOfflineSync(); // register online/offline listeners + load queue count

  useEffect(() => {
    // Wait for Zustand to finish reading localStorage before deciding to redirect.
    // Without this guard, the effect fires while user is still null on first render,
    // causing a spurious redirect to /login even when the token exists in storage.
    if (hasHydrated && !user?.accessToken) {
      router.replace("/login");
    }
  }, [user, hasHydrated, router]);

  const isRtl = locale !== "en";

  const mainColumn = (
    <div className="flex min-h-0 min-w-0 flex-1 flex-col">
      <Topbar />
      <main className="min-h-0 flex-1 overflow-auto p-6 bg-background">
        <RouteGuard>{children}</RouteGuard>
      </main>
    </div>
  );

  return (
    <CafeThemeProvider>
      <div
        className="flex h-screen min-h-0 overflow-hidden bg-background"
        dir={isRtl ? "rtl" : "ltr"}
      >
        {isRtl ? (
          <>
            <Sidebar side="right" />
            {mainColumn}
          </>
        ) : (
          <>
            <Sidebar side="left" />
            {mainColumn}
          </>
        )}
      </div>
    </CafeThemeProvider>
  );
}
