import { ref, onMounted, onBeforeUnmount } from 'vue'
export function useAdaptation(sizes, handleChange) {
    const mediaQueryLists = sizes.map(size => window.matchMedia(`(max-width: ${size.maxWidth})`));
    const currentDevice = ref(getCurrentDevice())
    function getCurrentDevice() {
        for (let i = 0; i < mediaQueryLists.length; i++) {
            if (mediaQueryLists[i].matches) {
                return sizes[i].maxWidth;
            }
        }
        return sizes[sizes.length - 1].maxWidth
    }

    const changeHandler = (newValue) => {
        if (typeof handleChange === 'function') {
            handleChange(newValue);
        }
    };

    const mediaQueryChangeHandler = () => {
        const newDevice = getCurrentDevice();
        if (currentDevice.value !== newDevice) {
            currentDevice.value = newDevice;
            changeHandler(newDevice);
        }
    };

    let cleanupHandlers = [];

    onMounted(() => {
        mediaQueryLists.forEach(query => {
            query.addEventListener('change', mediaQueryChangeHandler);
            cleanupHandlers.push(() => query.removeEventListener('change', mediaQueryChangeHandler));
        });
        // Ensure the initial value is correct and trigger the changeHandler with the initial value
        const initialDevice = getCurrentDevice();
        currentDevice.value = initialDevice;
        changeHandler(initialDevice);
    });

    onBeforeUnmount(() => {
        cleanupHandlers.forEach(cleanup => cleanup());
    });

    return { maxWidth: currentDevice };
}