import { useEffect, useState } from 'react';

/**
 * AUD7: returns a counter that increments whenever the active theme changes.
 *
 * Themes are applied by swapping `document.documentElement.className`
 * (`lib/theme.ts`). ECharts reads its colors from CSS custom properties at
 * init time only, so a theme switch leaves charts stranded on the old palette.
 * Charts include this epoch in their render effect's dependency array; the
 * effect re-runs (dispose + re-init with a fresh theme) on every switch.
 */
export function useThemeEpoch(): number {
  const [epoch, setEpoch] = useState(0);

  useEffect(() => {
    const target = document.documentElement;
    let last = target.className;
    const observer = new MutationObserver(() => {
      if (target.className !== last) {
        last = target.className;
        setEpoch((n) => n + 1);
      }
    });
    observer.observe(target, { attributes: true, attributeFilter: ['class'] });
    return () => observer.disconnect();
  }, []);

  return epoch;
}
