import { ref } from 'vue';

export default function (pageSelector: string, cb = async () => {}) {
    const isRunRequest = ref(false);
    const hasRequest = ref(false);

    const loadMoreList = async () => {
        const scrollY = window.scrollY;
        const innerHeight = window.innerHeight;
        const pageHeight = document.querySelector(pageSelector)?.clientHeight;

        if (scrollY + innerHeight === pageHeight && !isRunRequest.value) {
            if (hasRequest.value) {
                isRunRequest.value = true;

                await cb().finally(() => {
                    isRunRequest.value = false;
                });
            }
        }
    };

    const addListener = () => window.addEventListener('scroll', loadMoreList);
    const removeListener = () => window.removeEventListener('scroll', loadMoreList);

    return {
        hasRequest,
        addListener,
        removeListener,
    };
}
