import { useEffect, useCallback, useRef } from 'react';
import { useTableContext } from './Tablev2.component';
export default function useSyncedScroll() {
    const { syncScrollListener, setSyncScrollListener } = useTableContext();
    const headerRef = useCallback((element) => {
        if (element) {
            const callback = (event) => {
                if (element && event) {
                    element.scrollTo({
                        left: event.target.scrollLeft,
                        top: 0,
                    });
                }
            };
            if (!syncScrollListener) {
                setSyncScrollListener(() => {
                    return callback;
                });
            }
        }
    }, [syncScrollListener]);
    const bodyRef = useRef(null);
    useEffect(() => {
        if (bodyRef.current && syncScrollListener) {
            /*
            We intentionally use _outerRef prop here despite the fact that it is
            internal use only and not typed, as it is the only way for us to access to the scrollable element
            */
            //@ts-expect-error
            bodyRef.current._outerRef.addEventListener('scroll', syncScrollListener);
        }
        return () => {
            //@ts-expect-error
            if (bodyRef.current && bodyRef.current._outerRef) {
                //@ts-expect-error
                bodyRef.current._outerRef.removeEventListener('scroll', syncScrollListener);
            }
        };
    }, [bodyRef.current, syncScrollListener]);
    return { headerRef, bodyRef };
}
