// app/AuthBootstrap.tsx
"use client";

import { useEffect, useRef } from "react";
import { useDispatch } from "react-redux";
import { AppDispatch } from "@/app/redux/types";
import { validateAuth } from "./redux/auth/authSlice";

export function AuthBootstrap() {
  const dispatch = useDispatch<AppDispatch>();
  const startedRef = useRef(false);
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);

  useEffect(() => {
    // Guard against React StrictMode double-invoke in dev
    if (startedRef.current) return;
    startedRef.current = true;

    // Initial validate on mount
    dispatch(validateAuth());

    // Refresh on window focus (nice UX)
    const onFocus = () => dispatch(validateAuth());
    window.addEventListener("focus", onFocus);

    // Optional: periodic validation every 5 min
    intervalRef.current = setInterval(
      () => {
        dispatch(validateAuth());
      },
      5 * 60 * 1000
    );

    return () => {
      window.removeEventListener("focus", onFocus);
      if (intervalRef.current) clearInterval(intervalRef.current);
    };
  }, [dispatch]);

  return null;
}
