"use client";
import { useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { subscribeAgentEvents } from '../agents/agent-events-bus.js';

// /approvals is read from audit_logs + approval_requests, neither of which
// publishes a live event today (writes go through appendAudit() directly).
// So we trigger a server refresh on three signals:
//
//   1. Any agent tool start/result on the SSE bus — gated PP calls funnel
//      through this path right before they raise an approval row.
//   2. Tab focus / visibility change — the operator approves in another tab
//      and flips back, page should already reflect the new state.
//   3. A slow safety poll (every 12s while visible) — covers the case where
//      a daemon (cron / heartbeat worker) raises a request with no SSE event.
//
// All refreshes are coalesced through one debounced router.refresh() call so
// a strict-mode burst (8 events in one second) yields one render, not eight.
const REFRESH_DEBOUNCE_MS = 500;
const POLL_INTERVAL_MS = 12_000;

export default function ApprovalsLiveRefresh() {
  const router = useRouter();
  const timerRef = useRef(null);

  useEffect(() => {
    let cancelled = false;

    function scheduleRefresh() {
      if (cancelled) return;
      if (timerRef.current) return;
      timerRef.current = setTimeout(() => {
        timerRef.current = null;
        if (!cancelled) router.refresh();
      }, REFRESH_DEBOUNCE_MS);
    }

    const unsubscribe = subscribeAgentEvents((event) => {
      if (!event) return;
      // Any tool start/result is a reasonable approximation of "something
      // gateable just happened" — it's cheap to refresh and corrects state
      // within half a second.
      if (event.type === 'agent_run_start' || event.type === 'agent_run_complete') {
        scheduleRefresh();
      }
    });

    function onVisibility() {
      if (document.visibilityState === 'visible') scheduleRefresh();
    }
    document.addEventListener('visibilitychange', onVisibility);
    window.addEventListener('focus', scheduleRefresh);

    const pollId = setInterval(() => {
      if (document.visibilityState === 'visible') scheduleRefresh();
    }, POLL_INTERVAL_MS);

    return () => {
      cancelled = true;
      unsubscribe();
      document.removeEventListener('visibilitychange', onVisibility);
      window.removeEventListener('focus', scheduleRefresh);
      clearInterval(pollId);
      if (timerRef.current) {
        clearTimeout(timerRef.current);
        timerRef.current = null;
      }
    };
  }, [router]);

  return null;
}
