// app/redux/ReduxProvider.tsx
"use client";

import React, { useEffect, useRef } from "react";
import { Provider } from "react-redux";
import { makeStore } from "./store";
import { initializeAuth } from "./auth/authSlice";

export default function ReduxProvider({
  children,
}: {
  children: React.ReactNode;
}) {
  // Create a store instance for this client-side session
  const storeRef = useRef<ReturnType<typeof makeStore>>(makeStore());

  useEffect(() => {
    // Dispatch initializeAuth when the ReduxProvider component mounts on the client.
    // This ensures your Redux isLoggedIn state is synced with localStorage after a page refresh.
    if (storeRef.current) {
      storeRef.current.dispatch(initializeAuth() as any);
    }
  }, []);

  return <Provider store={storeRef.current}>{children}</Provider>;
}
