/**
 * Reduced Motion Store
 *
 * Tracks the user's `prefers-reduced-motion` OS setting.
 * When enabled, animations (inertia, layout transitions, edge fades)
 * should be skipped or set to instant.
 */

import { atom } from 'jotai';

/**
 * Whether the user prefers reduced motion.
 * Initialized from `matchMedia` and updated on changes.
 *
 * Components/hooks should read this atom to skip animations:
 * - Pan/zoom inertia → stop immediately
 * - Layout transitions → apply positions instantly
 * - Edge fade animations → duration = 0
 */
export const prefersReducedMotionAtom = atom(
	typeof window !== 'undefined' &&
	typeof window.matchMedia === 'function'
		? window.matchMedia('(prefers-reduced-motion: reduce)').matches
		: false,
);

/**
 * Effect atom: subscribes to matchMedia changes.
 * Mount this once in CanvasProvider via useAtom.
 */
export const watchReducedMotionAtom = atom(null, (_get, set) => {
	if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return;

	const mql = window.matchMedia('(prefers-reduced-motion: reduce)');
	const handler = (e: MediaQueryListEvent) => {
		set(prefersReducedMotionAtom, e.matches);
	};

	// Sync initial state
	set(prefersReducedMotionAtom, mql.matches);

	mql.addEventListener('change', handler);
	return () => mql.removeEventListener('change', handler);
});
