import { useSyncExternalStore } from 'react';

const NARROW_BREAKPOINT = 640;

const mql =
    typeof window === 'undefined'
        ? undefined
        : window.matchMedia(`(max-width: ${NARROW_BREAKPOINT - 1}px)`);

function subscribe(callback: () => void) {
    if (!mql) {
        return () => {};
    }

    mql.addEventListener('change', callback);

    return () => {
        mql.removeEventListener('change', callback);
    };
}

function getSnapshot(): boolean {
    return mql?.matches ?? false;
}

function getServerSnapshot(): boolean {
    return false;
}

/** True below 640px, where dense grids have to give way to lists. */
export function useIsNarrow(): boolean {
    return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
}
