import { jsx as _jsx } from "react/jsx-runtime";
// (C) 2019-2026 GoodData Corporation
import { forwardRef, useCallback, useImperativeHandle, useMemo, useRef, } from "react";
import { handleOnScrollEvent } from "../utils/scroll.js";
import { ScrollContext } from "./ScrollContext.js";
const DEFAULT_BOTTOM_MARGIN = 5;
const scrollToVisibleDefault = (element, container, bottomMargin) => {
    container.scrollTop = element.offsetTop - container.offsetTop - bottomMargin;
};
const isElementInvisibleCheckDefault = (element, container) => {
    if (element && container) {
        const offset = element.offsetTop - container.offsetTop;
        const itemHeight = element.clientHeight;
        const parentHeight = container.clientHeight;
        return parentHeight < offset + itemHeight;
    }
    return false;
};
/**
 * @internal
 */
export const ScrollablePanel = forwardRef(function ScrollablePanel(props, ref) {
    const { tagName: TagName = "div", scrollToVisible = scrollToVisibleDefault, children, ...divProps } = props;
    const containerRef = useRef(null);
    useImperativeHandle(ref, () => containerRef.current ?? undefined);
    const memoizeContext = useMemo(() => {
        return {
            scrollIntoView: (element, bottomMargin = DEFAULT_BOTTOM_MARGIN, isElementInvisibleCheck = isElementInvisibleCheckDefault) => {
                if (containerRef.current) {
                    const container = containerRef.current;
                    if (isElementInvisibleCheck(element, container)) {
                        scrollToVisible(element, container, bottomMargin);
                    }
                }
            },
        };
    }, [scrollToVisible, containerRef]);
    const onPanelScroll = useCallback(() => {
        if (containerRef?.current) {
            handleOnScrollEvent(containerRef.current);
        }
    }, []);
    return (_jsx(ScrollContext.Provider, { value: memoizeContext, children: _jsx(TagName, { ...divProps, ref: containerRef, onScroll: onPanelScroll, children: children }) }));
});
