import { useEffect, useLayoutEffect, useState } from "react";

const useWindowSize = (): number[] => {
	const [size, setSize] = useState([0, 0]);
	useLayoutEffect(() => {
		const updateSize = () => {
			setSize([window.innerWidth, window.innerHeight]);
		};
		window.addEventListener("resize", updateSize);
		updateSize();
		return () => window.removeEventListener("resize", updateSize);
	}, []);
	return size;
};

/**
 * Firefox auto-scrolls the window when typing in form fields if a scrollable
 * element (e.g. Froala .fr-wrapper with overflow:auto) is present in the page.
 * This hook blocks any window scroll not initiated by the user (wheel/touch)
 * while a field inside the given container has focus.
 *
 * @see https://bugzilla.mozilla.org/show_bug.cgi?id=1422524
 * @see https://bugzilla.mozilla.org/show_bug.cgi?id=1660932
 */
const useFirefoxScrollLock = (containerRef: React.RefObject<HTMLElement | null>) => {
	useEffect(() => {
		if (!navigator.userAgent.includes("Firefox")) {
			return;
		}

		let savedScrollY = window.scrollY;
		let userScrolling = false;
		let scrollTimer: ReturnType<typeof setTimeout>;

		const markUserScroll = () => {
			userScrolling = true;
			clearTimeout(scrollTimer);
			scrollTimer = setTimeout(() => {
				userScrolling = false;
			}, 150);
		};

		const onScroll = () => {
			if (!userScrolling && containerRef.current?.contains(document.activeElement)) {
				window.scrollTo(0, savedScrollY);
			} else {
				savedScrollY = window.scrollY;
			}
		};

		window.addEventListener("wheel", markUserScroll, { passive: true });
		window.addEventListener("touchmove", markUserScroll, { passive: true });
		window.addEventListener("scroll", onScroll);

		return () => {
			window.removeEventListener("wheel", markUserScroll);
			window.removeEventListener("touchmove", markUserScroll);
			window.removeEventListener("scroll", onScroll);
			clearTimeout(scrollTimer);
		};
	}, [containerRef]);
};

export { useFirefoxScrollLock, useWindowSize };
