"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useGridCache = useGridCache;
const react_1 = require("react");
const hooks_1 = require("../../../utils/hooks");
const table_grid_nav_1 = require("../helpers/table-grid-nav");
/**
 * Manages the table grid cache and observes DOM changes that require grid rebuilding.
 * Watches for structural changes (rows/cells added/removed) and attribute changes
 * (colspan, rowspan, hidden, style) that affect grid layout and focusability.
 */
function useGridCache(tableRef, enabled) {
    const gridCacheRef = (0, react_1.useRef)({
        grid: null,
        dirty: true,
    });
    const [activeCell, setActiveCell] = (0, react_1.useState)(null);
    const activeCellRef = (0, hooks_1.useValueAsRef)(activeCell);
    const observerRef = (0, react_1.useRef)(null);
    (0, react_1.useEffect)(() => {
        if (!tableRef || !enabled) {
            return;
        }
        observerRef.current = new MutationObserver(() => {
            gridCacheRef.current.dirty = true;
            if (activeCellRef.current && !activeCellRef.current.isConnected) {
                setActiveCell(null);
            }
        });
        observerRef.current.observe(tableRef, {
            subtree: true,
            childList: true,
            attributes: true,
            attributeFilter: ["colspan", "rowspan", "hidden", "style"],
        });
        return () => {
            if (observerRef.current) {
                observerRef.current.disconnect();
                observerRef.current = null;
            }
        };
    }, [tableRef, enabled, activeCellRef]);
    /**
     * If keyboard-nav is re-enabled, mark grid as dirty since
     * the table might have changed while it was disabled.
     */
    (0, react_1.useEffect)(() => {
        if (enabled) {
            gridCacheRef.current.dirty = true;
        }
    }, [enabled]);
    const getTableGrid = (0, react_1.useCallback)((_tableRef) => {
        if (gridCacheRef.current.dirty || !gridCacheRef.current.grid) {
            gridCacheRef.current.grid = (0, table_grid_nav_1.buildTableGridMap)(_tableRef);
            gridCacheRef.current.dirty = false;
        }
        return gridCacheRef.current.grid;
    }, []);
    return {
        getTableGrid,
        activeCell,
        setActiveCell,
    };
}
//# sourceMappingURL=useGridCache.js.map