/**
 * @file useModalObserver.ts - Observes Bootstrap modal open/close events via a MutationObserver on `document.body` and exposes the current count of active (`.modal.show`) modals.
 * Other hooks and components can use this count to coordinate behavior when one or more modals are visible.
 */

import { useEffect, useState } from 'react';

/**
 * Observes the number of shown Bootstrap modals on the page and returns the active count.
 * Uses a MutationObserver on `document.body` to detect when modals are added or removed.
 *
 * @returns Active modal count
 */
export function useModalObserver() {
  const [activeCount, setActiveCount] = useState(0);

  useEffect(() => {
    // Counts DOM elements matching Bootstrap's open-modal selector
    const update = () => {
      const openModals = document.querySelectorAll('.modal.show');
      setActiveCount(openModals.length);
    };

    // Run once at mount to capture any already-open modals
    update();

    // Watch for direct children added/removed from body (Bootstrap appends modals there)
    const observer = new MutationObserver(update);
    observer.observe(document.body, {
      childList: true,
    });

    return () => observer.disconnect();
  }, []);

  return activeCount;
}
