import { useLayoutEffect, useState } from "react";

import { matchesMedia } from "../utils/matchesMedia.js";

function useMatchesMedia(queries: string[], once?: boolean): boolean[] {
    const mediaQueryLists = queries.map((q) => matchesMedia(q));
    const getValue = () => mediaQueryLists.map(([mql]) => mql.matches);
    const [value, setValue] = useState(getValue);

    useLayoutEffect(() => {
        if (once) {
            return () => {
                // Silence is golden.
            };
        }

        const handler = () => setValue(getValue);
        mediaQueryLists.forEach(([, addListener]) => addListener(handler));
        return () => mediaQueryLists.forEach(([, , removeListener]) => removeListener(handler));
    }, [once]);

    return value;
}

export { useMatchesMedia };
