/**
 * @file useHasVerticalScrollbar.ts - A React hook that detects whether the page has a vertical scrollbar.
 */

import { useEffect, useState } from 'react';

/**
 * Detects whether the page has a vertical scrollbar.
 * Useful for adjusting UI elements that may be affected by scrollbar presence, such as fixed-position tooltips or modals that need to account for the scrollbar width.
 *
 * The hook monitors:
 * - Window resize events
 * - DOM mutations that might change content height
 *
 * @returns `true` if the document height exceeds the viewport height (scrollbar visible)
 *
 * @example
 * ```tsx
 * const hasScrollbar = useHasVerticalScrollbar();
 *
 * return (
 *  <Tooltip className={hasScrollbar ? undefined : 'position-fixed'}>
 *    ...
 *  </Tooltip>
 * );
 * ```
 */
export function useHasVerticalScrollbar() {
  const [hasVerticalScrollbar, setHasVerticalScrollbar] = useState(false);

  useEffect(() => {
    /**
     * Checks if the document content exceeds the viewport height.
     * When content is taller than the window, browsers display a vertical scrollbar.
     */
    const checkScrollbar = () => {
      setHasVerticalScrollbar(
        document.documentElement.scrollHeight > window.innerHeight
      );
    };

    // Perform initial check on mount
    checkScrollbar();

    // Re-check when window is resized
    window.addEventListener('resize', checkScrollbar);

    // Re-check when DOM content changes (which might affect page height)
    const observer = new MutationObserver(checkScrollbar);
    observer.observe(document.body, { childList: true, subtree: true });

    // Cleanup listeners on unmount
    return () => {
      window.removeEventListener('resize', checkScrollbar);
      observer.disconnect();
    };
  }, []);

  return hasVerticalScrollbar;
}
