import create from 'zustand';

// Keeps current responsive breakpoints status in a store, updated (debounced) at resize

import { breakpoints, isBreakpointDown, isBreakpointUp } from '../constants/breakpoints';

const computeState = () => {
    const breakpointsStatus = Object.keys(breakpoints).reduce((all, currentKey) => (
        {
            ...all,
            [`${currentKey}Up`]: isBreakpointUp(breakpoints[currentKey]),
            [`${currentKey}Down`]: isBreakpointDown(breakpoints[currentKey])
        }
    ), {});

    return { breakpoints: breakpointsStatus };
};

export const [responsiveStore] = create(set => {
    let hasListener;
    let timeout;
    const handleResize = () => {
        clearTimeout(timeout);
        set(computeState());
    };
    const debounceResize = () => {
        if (timeout) { clearTimeout(timeout); }
        timeout = setTimeout(handleResize, 250);
    };

    return {
        computeResponsive: () => {
            if (hasListener) {
                return;
            }
            set(computeState());
            hasListener = true;
            window.addEventListener('resize', debounceResize);
        }
    };
});
