"use client";

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { ConfirmProvider } from "@/components/providers/confirm-provider";
import { MeeziToaster } from "@/components/ui/meezi-toaster";
import { useAuthStore } from "@/lib/stores/auth.store";
import { restoreQueryCache, startPersisting } from "@/lib/offline/query-persister";

export function Providers({ children }: { children: React.ReactNode }) {
  const [queryClient] = useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            staleTime: 30_000,
            retry: 1,
            // Keep data in memory long enough to back offline reads; it is also
            // persisted to IndexedDB by the persister below.
            gcTime: 24 * 60 * 60 * 1000,
          },
        },
      })
  );

  // Persist the query cache to IndexedDB so the dashboard is viewable offline.
  // Scoped to the current café so a different tenant never hydrates this data.
  const cafeId = useAuthStore((s) => s.user?.cafeId);
  useEffect(() => {
    const scope = cafeId ?? "anon";
    let active = true;
    let stop: () => void = () => {};
    void (async () => {
      await restoreQueryCache(queryClient, scope);
      if (!active) return;
      stop = startPersisting(queryClient, scope);
    })();
    return () => {
      active = false;
      stop();
    };
  }, [queryClient, cafeId]);

  return (
    <QueryClientProvider client={queryClient}>
      <ConfirmProvider>
        {children}
        <MeeziToaster />
      </ConfirmProvider>
    </QueryClientProvider>
  );
}
