"use client";

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

export default function ReduxProvider({
  children,
}: {
  children: React.ReactNode;
}) {
  const intervalRef = useRef<NodeJS.Timeout | null>(null);
  const initialCheckRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    // Check authentication status when the ReduxProvider component mounts on the client.
    // This ensures your Redux auth state is synced with the server-side token.
    store.dispatch(validateAuth());

    // Do an additional check after 2 seconds to ensure we have the latest token info
    initialCheckRef.current = setTimeout(() => {
      store.dispatch(validateAuth());
    }, 2000);

    // Set up periodic token validation every 5 minutes
    intervalRef.current = setInterval(
      () => {
        store.dispatch(validateAuth());
      },
      5 * 60 * 1000
    ); // 5 minutes

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
      if (initialCheckRef.current) {
        clearTimeout(initialCheckRef.current);
      }
    };
  }, []); // Empty dependency array ensures it runs only once on mount

  return <Provider store={store}>{children}</Provider>;
}
