"use client";

import { useEffect } from "react";

export function IdleSessionGuard({ minutes }: { minutes: number }) {
  useEffect(() => {
    const timeout = Math.max(5, minutes) * 60 * 1000;
    let timer = window.setTimeout(signOut, timeout);

    function reset() {
      window.clearTimeout(timer);
      timer = window.setTimeout(signOut, timeout);
    }

    async function signOut() {
      await fetch("/api/auth/logout", { method: "POST" }).catch(() => undefined);
      window.location.assign("/login?error=idle");
    }

    const events = ["pointerdown", "keydown", "scroll", "touchstart"] as const;
    events.forEach((event) => window.addEventListener(event, reset, { passive: true }));
    return () => {
      window.clearTimeout(timer);
      events.forEach((event) => window.removeEventListener(event, reset));
    };
  }, [minutes]);

  return null;
}
