import React, { useEffect, useCallback, useRef, forwardRef, useMemo, } from 'react';
import { OverlayScrollbars } from 'overlayscrollbars';
import { st, classes } from './useOverlayScrollbar.st.css.js';
import { forkRef } from '../../utils/forkRef';
const DEFAULT_OPTIONS = {
    scrollbars: { autoHide: 'leave', autoHideDelay: 0 },
};
/**
 * @param params Parameters for customization.
 * @returns A tuple with two values:
 * The first value is the overlay scrollbar host component.
 * The second value is the overlay scrollbar content component.
 */
export const useOverlayScrollbar = (params) => {
    const options = useRef(params?.options || DEFAULT_OPTIONS);
    const scrollableContainerRef = useRef(null);
    const contentRef = useRef(null);
    const instanceRef = useRef(null);
    const initialize = useCallback((target) => {
        // if already initialized do nothing
        if (OverlayScrollbars.valid(instanceRef.current)) {
            return;
        }
        /**
         * If the environment is test or window is undefined,
         * do not initialize the OverlayScrollbars.
         */
        if (process.env.NODE_ENV === 'test' || typeof window === 'undefined') {
            return;
        }
        instanceRef.current = OverlayScrollbars({
            target,
            elements: {
                content: contentRef.current,
                viewport: contentRef.current,
            },
        }, options.current);
    }, [options]);
    useEffect(() => {
        if (scrollableContainerRef.current) {
            initialize(scrollableContainerRef.current);
        }
        return () => instanceRef.current?.destroy();
    }, [initialize]);
    const OverlayScrollbarHost = useCallback(({ children, className, ...rest }) => {
        return (React.createElement("div", { "data-overlayscrollbars-initialize": "", className: st(classes.root, className), ref: scrollableContainerRef, ...rest }, children));
    }, []);
    // this is required in order to use forwardRef together with memoization
    const OverlayScrollbarContent = useMemo(() => forwardOverlayScrollbarContent(contentRef), [contentRef]);
    return [OverlayScrollbarHost, OverlayScrollbarContent];
};
const forwardOverlayScrollbarContent = (contentRef) => forwardRef(({ children, ...rest }, ref) => {
    return (React.createElement("div", { "data-overlayscrollbars-contents": true, ref: forkRef(ref, contentRef), ...rest }, children));
});
//# sourceMappingURL=useOverlayScrollbar.js.map