'use client';

import { useEffect, type ReactNode } from 'react';
import { useReducedMotion } from 'motion/react';

/**
 * Adds subtle scroll activity state for themed scrollbar feedback.
 * Native scrollbars are styled in CSS; this toggles [data-scrolling]
 * so the thumb can brighten while the user is scrolling.
 */
export function ScrollbarProvider({ children }: { children: ReactNode }) {
  const reduceMotion = useReducedMotion();

  useEffect(() => {
    if (reduceMotion) return;

    const root = document.documentElement;
    let idleTimer: ReturnType<typeof setTimeout> | null = null;

    const markScrolling = () => {
      root.dataset.scrolling = 'true';
      if (idleTimer) clearTimeout(idleTimer);
      idleTimer = setTimeout(() => {
        delete root.dataset.scrolling;
      }, 700);
    };

    // Capture scrolls from window and nested overflow containers
    window.addEventListener('scroll', markScrolling, { capture: true, passive: true });
    window.addEventListener('wheel', markScrolling, { capture: true, passive: true });
    window.addEventListener('touchmove', markScrolling, { capture: true, passive: true });

    return () => {
      window.removeEventListener('scroll', markScrolling, true);
      window.removeEventListener('wheel', markScrolling, true);
      window.removeEventListener('touchmove', markScrolling, true);
      if (idleTimer) clearTimeout(idleTimer);
      delete root.dataset.scrolling;
    };
  }, [reduceMotion]);

  return <>{children}</>;
}
