"use client";

import type { ReactNode } from "react";
import { useEffect } from "react";
import i18n, { ensureAdminI18nReady, normalizeAdminLanguage } from "@/i18n";

import { Toaster } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip";
import { hydrateAdminUiLocale } from "@/lib/admin-locale";
import { useAdminSessionStore } from "@/stores/admin-session";

type ProvidersProps = {
  children: ReactNode;
};

function AdminSessionHydrator() {
  useEffect(() => {
    void (async () => {
      await ensureAdminI18nReady();

      const locale = hydrateAdminUiLocale();
      const current = normalizeAdminLanguage(i18n.resolvedLanguage ?? i18n.language);
      if (locale && locale !== current) {
        await i18n.changeLanguage(locale);
      }

      useAdminSessionStore.getState().rehydrate();
    })();
  }, []);

  return null;
}

export function Providers({ children }: ProvidersProps) {
  return (
    <TooltipProvider>
      <AdminSessionHydrator />
      {children}
      <Toaster />
    </TooltipProvider>
  );
}
