'use client';

// Fires `cb` whenever <html> class changes (typical light/dark toggle convention)
// or the user's color-scheme media preference flips. Used to repaint canvases
// after a theme switch — see ADR-003.

import { useEffect } from 'react';

export function useThemeWatcher(cb: () => void): void {
  useEffect(() => {
    const root = document.documentElement;
    const obs = new MutationObserver(cb);
    obs.observe(root, { attributes: true, attributeFilter: ['class', 'data-theme'] });
    const mq = window.matchMedia?.('(prefers-color-scheme: dark)');
    const onMq = () => cb();
    mq?.addEventListener?.('change', onMq);
    return () => {
      obs.disconnect();
      mq?.removeEventListener?.('change', onMq);
    };
  }, [cb]);
}
