'use client';

import { Provider as ReduxProvider } from 'react-redux';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { useState, useEffect } from 'react';
import { store } from '@/store';
import { Toaster } from '@/components/ui/toaster';
import { useSidebar } from '@/store/zustand/use-sidebar';
import { initializeAuth } from '@/store/slices/auth.slice';

function HydrationHandler() {
  useEffect(() => {
    // 客户端初始化 zustand 持久化状态
    useSidebar.persist.rehydrate();
    // 客户端初始化 auth token
    store.dispatch(initializeAuth());
  }, []);
  return null;
}

export function Providers({ children }: { children: React.ReactNode }) {
  const [queryClient] = useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            staleTime: 60 * 1000,
            refetchOnWindowFocus: false,
          },
        },
      })
  );

  return (
    <ReduxProvider store={store}>
      <QueryClientProvider client={queryClient}>
        <HydrationHandler />
        {children}
        <Toaster />
      </QueryClientProvider>
    </ReduxProvider>
  );
}
