"use client";

import type { ReactNode } from "react";
import { useEffect } from "react";
import i18n 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 applyStoredAdminLanguage() {
  const locale = hydrateAdminUiLocale();
  if (!locale) {
    return;
  }
  const current = i18n.resolvedLanguage ?? i18n.language;
  if (locale !== current) {
    void i18n.changeLanguage(locale);
  }
}

function AdminSessionHydrator() {
  useEffect(() => {
    if (i18n.isInitialized) {
      applyStoredAdminLanguage();
    } else {
      i18n.on("initialized", applyStoredAdminLanguage);
    }
    useAdminSessionStore.getState().rehydrate();

    return () => {
      i18n.off("initialized", applyStoredAdminLanguage);
    };
  }, []);

  return null;
}

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