import { useCallback, useLayoutEffect, useMemo, useRef } from 'react';
import { useViewportType } from '../../../../useViewportType';
import { dataGridClassnames } from '../../../constants';
import { useRowHover } from '../../../hooks/useRowHover';
import { getColumnSections } from '../../utils/getColumnSections';
import { syncRowsHeight } from '../../utils/syncRowsHeight';
export const usePinnedColumns = ({ isLoading, columns, }) => {
    const containerRef = useRef(null);
    const { isMobile } = useViewportType();
    const hasPinnedColumns = useMemo(() => columns.some((column) => column.pinned), [columns]);
    const isRowHoverSyncEnabled = hasPinnedColumns && !isMobile;
    const { rowsMapRef, ...rowHoverProps } = useRowHover({
        hasPinnedColumns: isRowHoverSyncEnabled,
    });
    const isScrollStateSupported = CSS.supports('container-type', 'scroll-state');
    const checkOverflow = useCallback((element) => {
        if (element) {
            return element.scrollWidth > element.clientWidth;
        }
        return false;
    }, []);
    const { sections } = useMemo(() => getColumnSections(columns), [columns]);
    useLayoutEffect(() => {
        if (isLoading ||
            !hasPinnedColumns ||
            isMobile ||
            typeof window === 'undefined') {
            return;
        }
        const resizeObserver = new ResizeObserver(() => {
            syncRowsHeight(rowsMapRef.current);
            if (isScrollStateSupported) {
                return;
            }
            if (checkOverflow(containerRef.current)) {
                containerRef.current?.classList.add(dataGridClassnames.overflowed);
            }
            else {
                containerRef.current?.classList.remove(dataGridClassnames.overflowed);
            }
        });
        if (!containerRef.current) {
            return;
        }
        resizeObserver.observe(containerRef.current);
        return () => {
            resizeObserver.disconnect();
        };
    }, [hasPinnedColumns, isLoading, isMobile]);
    return { containerRef, rowHoverProps, sections, hasPinnedColumns };
};
