"use client";

import { ReactNode, useRef } from "react";
import { Provider } from "react-redux";
import { AppStore, makeStore } from "./store";
import { User } from "../store/authSlice";


type InitialUserPayload = { user: User };
interface Props {
  children: ReactNode;
  initialUser: InitialUserPayload | null;
}

export const ReduxProvider = ({ children, initialUser }: Props) => {
  const storeRef = useRef<AppStore | null>(null);
  if (!storeRef.current) {
    storeRef.current = makeStore({
      auth: {
        user: initialUser ?? null,
        status: initialUser ? "authenticated" : "unauthenticated",
      },
    } as any);
  }

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