import { jsx as _jsx } from "react/jsx-runtime";
import { createContext, useContext, useEffect, useMemo, useReducer, useRef } from 'react';
import { tableReducer } from './table-reducer.js';
import { createPublicTableApi } from '../../logic/public-table-api.js';
import { TableApi } from '../../logic/table-api.js';
const TableContext = createContext(null);
const TableProvider = ({ children, config, tableRef }) => {
    const [state, dispatch] = useReducer((tableReducer), {
        columns: config.columns,
        defaultData: [...config.data],
        data: config.data,
        allowRowSelection: config.allowRowSelection ?? true,
        showRowNumbers: config.showRowNumbers ?? true,
        selectedRowIndexes: [],
        lastSelectedRowIndex: null,
        selectedCellIndex: null,
        isCellEditMode: false,
        sortState: null,
    });
    useEffect(() => {
        dispatch({ type: 'SET_DISPATCH', payload: dispatch });
    }, [dispatch]);
    const stateRef = useRef(state);
    const configRef = useRef(config);
    useEffect(() => {
        stateRef.current = state;
        configRef.current = config;
    }, [state, config]);
    const [api, publicApi] = useMemo(() => {
        const internalApi = new TableApi(tableRef, configRef, stateRef);
        const publicApi = createPublicTableApi(internalApi);
        if (config.apiRef) {
            config.apiRef.current = publicApi;
        }
        return [internalApi, publicApi];
    }, [config.apiRef, tableRef]);
    return (_jsx(TableContext.Provider, { value: {
            config,
            state,
            api,
            publicApi,
        }, children: children }));
};
const useInternalTableState = () => {
    const context = useContext(TableContext);
    if (!context) {
        throw new Error('useTable must be used within a TableProvider');
    }
    return context;
};
export { TableProvider, useInternalTableState };
//# sourceMappingURL=table-provider.js.map