"use client";

import { QueryClient, QueryClientProvider, MutationCache } 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";
import { notify, getErrorMessage } from "@/lib/notify";

/** Generic, locale-aware fallback for mutations that don't handle their own error. */
function globalMutationErrorFallback(): string {
  const lang = typeof document !== "undefined" ? document.documentElement.lang : "fa";
  return lang === "en" ? "Something went wrong" : lang === "ar" ? "حدث خطأ ما" : "خطایی رخ داد";
}

export function Providers({ children }: { children: React.ReactNode }) {
  const [queryClient] = useState(
    () =>
      new QueryClient({
        // Safety net: surface a toast for any mutation that doesn't define its own
        // onError (skips ones that already handle it, so no double toasts).
        mutationCache: new MutationCache({
          onError: (error, _vars, _ctx, mutation) => {
            if (mutation.options.onError) return;
            notify.error(getErrorMessage(error, globalMutationErrorFallback()));
          },
        }),
        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>
  );
}
