/**
 * A wrapper around `window.matchMedia` that allows to attach a callback to the `change` event.
 * It is useful to react to changes in the viewport size or check if the current viewport matches a media query
 * without reflow / layout trash.
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia#javascript
 * @see https://gist.github.com/paulirish/5d52fb081b3570c81e3a?permalink_comment_id=4665975#gistcomment-4665975
 * @see https://stackoverflow.com/a/60000747/5506547
 */
function matchesMedia(media: string) {
    const mediaQueryList = window.matchMedia(media);

    return [
        mediaQueryList,
        (callback: (e: MediaQueryListEvent) => void) => {
            try {
                // Chrome & Firefox
                mediaQueryList.addEventListener("change", callback);
            } catch (e1) {
                try {
                    // Safari
                    mediaQueryList.addListener(callback);
                } catch (e2) {
                    // Silence is golden.
                }
            }
        },
        (callback: (e: MediaQueryListEvent) => void) => {
            try {
                mediaQueryList.removeEventListener("change", callback);
            } catch (e1) {
                try {
                    // Safari
                    mediaQueryList.removeListener(callback);
                } catch (e2) {
                    // Silence is golden.
                }
            }
        },
    ] as const;
}

export { matchesMedia };
