import { useEffect } from "react";

import { getScrollParent } from "../utils/getScrollParent.js";

import type { MutableRefObject } from "react";

function useScrollToBottomAction(container: MutableRefObject<HTMLElement>, callback: () => void, offset = 0) {
    useEffect(() => {
        if (!container) {
            return undefined;
        }

        const scrollContainer = getScrollParent(container.current);

        if (!scrollContainer) {
            return undefined;
        }

        const handleScroll = () => {
            if (scrollContainer.scrollTop + scrollContainer.clientHeight >= scrollContainer.scrollHeight - offset) {
                callback();
            }
        };

        scrollContainer.addEventListener("scroll", handleScroll);

        return () => {
            scrollContainer.removeEventListener("scroll", handleScroll);
        };
    }, [container, offset]);
}

export { useScrollToBottomAction };
