"use client";

import { useEffect, useRef } from "react";
import { useTopLoader } from "nextjs-toploader";

interface LoadingOverlayProps {
  isLoading: boolean;
  message?: string;
}

/**
 * Per-screen loading signal.
 *
 * This no longer renders anything. It used to paint a full-screen scrim with a
 * spinner card over the page, which blocked interaction with content that was
 * already on screen and stacked on top of the identical app-wide overlay the
 * fetch wrapper was showing at the same time.
 *
 * It now drives the shared top progress bar. The component and its props are
 * kept so all 18 call sites stay unchanged, and `message` is still announced to
 * screen readers — the visual noise is what went away, not the feedback.
 */
export function LoadingOverlay({ isLoading, message = "Loading data…" }: LoadingOverlayProps) {
  const loader = useTopLoader();
  const active = useRef(false);

  useEffect(() => {
    if (isLoading && !active.current) {
      active.current = true;
      loader.start();
    } else if (!isLoading && active.current) {
      active.current = false;
      loader.done();
    }
  }, [isLoading, loader]);

  useEffect(
    () => () => {
      if (active.current) loader.done(true);
    },
    [loader]
  );

  if (!isLoading) return null;

  return (
    <span role="status" aria-live="polite" className="sr-only">
      {message}
    </span>
  );
}
