import { useEffect, useState } from "react";

// Taken and adapted from:
// https://www.joshwcomeau.com/snippets/react-hooks/use-prefers-reduced-motion/

const query = "(prefers-reduced-motion: no-preference)";
const isRenderingOnServer = typeof window === "undefined";
const getInitialState = () => {
	// For our initial server render, we won't know if the user
	// prefers reduced motion, but it doesn't matter. This value
	// will be overwritten on the client, before any animations
	// occur.
	return isRenderingOnServer ? true : !window.matchMedia(query).matches;
};

export default function usePrefersReducedMotion() {
	const [prefersReducedMotion, setPrefersReducedMotion] =
		useState(getInitialState);
	useEffect(() => {
		const mediaQueryList = window.matchMedia(query);
		if (!mediaQueryList.addEventListener) {
			return;
		}

		const listener = (event: MediaQueryListEvent) =>
			setPrefersReducedMotion(!event.matches);
		mediaQueryList.addEventListener("change", listener, { passive: true });
		return () => mediaQueryList.removeEventListener("change", listener);
	}, []);
	return prefersReducedMotion;
}
