import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { createContext, useState, useRef, useEffect, useMemo } from 'react';
import { tableTheme } from './Table.theme.js';
import { cn } from '../../../utils/cn.js';
import { TableHeader } from './TableHeader.js';
import { TableBody } from './TableBody.js';
import { TableSelectionHeader } from './TableSelectionHeader.js';
import { TableColumnManager } from './TableColumnManager.js';
import { TableFilter } from './TableFilter.js';
import { useTableColumns } from './hooks/useTableColumns.js';
import { useTableSelection } from './hooks/useTableSelection.js';
import { useTablePagination } from './hooks/useTablePagination.js';
import { useTableFilter } from './hooks/useTableFilter.js';

/**
 * Context for sharing table state across all table components
 * Provides theme, configuration, and callback functions to child components
 */
const TableContext = createContext({
    theme: tableTheme,
    variant: "default",
    freezeHeader: false,
    freezeFirstColumn: false,
    freezeLastColumn: false,
});
/**
 * Enhanced Table component with dual API support (declarative and data-driven)
 *
 * Features:
 * - Dual API: Use with data/columns props OR declarative Table.Header/Body/Row/Cell components
 * - Stable row identification using rowKey prop for consistent React reconciliation
 * - Column management with visibility controls
 * - Sorting, filtering, row selection, and expansion
 * - Frozen columns and headers
 * - Pagination support
 * - Full accessibility compliance (WCAG 2.1 AA)
 * - Theme customization with className overrides
 */
function TableComponent(props) {
    var _a;
    const { data, columns, rowKey, variant = "default", theme: themeOverrides, className = "", freezeHeader = false, freezeFirstColumn = false, freezeLastColumn = false, sortable = false, sortConfig = [], onSortChange, filterable = false, filterConfig = [], onFilterChange, filterLogic: controlledFilterLogic, enableBuiltInFilter = false, expandable = false, expandedRowRender, expandedRows = [], onExpandedRowsChange, selectable = false, selectionType = "checkbox", selectedRows = [], onSelectionChange, bulkActions = [], showColumnManager = false, visibleColumns: initialVisibleColumns, onVisibleColumnsChange, onColumnReorder, pagination, children, } = props;
    // Column management hook
    const { visibleColumns, columnOrder, visibleColumnsList, handleToggleColumn, handleColumnReorder, handleResetToDefault, } = useTableColumns({
        columns,
        initialVisibleColumns,
        onVisibleColumnsChange,
        onColumnReorder,
    });
    // Filter logic state
    const [internalFilterLogic, setInternalFilterLogic] = useState('and');
    const filterLogic = controlledFilterLogic !== null && controlledFilterLogic !== void 0 ? controlledFilterLogic : internalFilterLogic;
    const handleFilterLogicChange = (logic) => {
        setInternalFilterLogic(logic);
    };
    // Built-in filter hook
    const { filteredData: builtInFilteredData } = useTableFilter({
        filterConfig,
        onFilterChange,
        filterLogic,
        data,
        columns,
        enableBuiltInFilter,
    });
    // Use filtered data when built-in filter is enabled, otherwise use raw data
    const effectiveData = enableBuiltInFilter ? builtInFilteredData : data;
    // Pagination hook
    const { paginatedData } = useTablePagination({
        data: effectiveData,
        pagination,
    });
    // Selection hook (for clear selection in header)
    const { handleClearSelection } = useTableSelection({
        data: paginatedData,
        rowKey,
        selectionType,
        selectedRows,
        onSelectionChange,
    });
    // Determine which API is being used (declarative vs data-driven)
    const isDeclarativeAPI = !!children;
    // Detect horizontal overflow to conditionally apply frozen column backdrop styles
    const scrollContainerRef = useRef(null);
    const [isOverflowing, setIsOverflowing] = useState(false);
    useEffect(() => {
        const container = scrollContainerRef.current;
        if (!container)
            return;
        const checkOverflow = () => {
            setIsOverflowing(container.scrollWidth > container.clientWidth);
        };
        checkOverflow();
        const observer = new ResizeObserver(checkOverflow);
        observer.observe(container);
        return () => observer.disconnect();
    }, []);
    // Merge global theme with component-specific overrides
    // When the table overflows, add backdrop-blur + shadow to frozen columns
    const theme = useMemo(() => {
        const merged = {
            ...tableTheme,
            ...(themeOverrides || {}),
        };
        if (isOverflowing) {
            const overflowBg = "backdrop-blur-sm bg-black/5 dark:bg-white/5";
            merged.frozenColumnStyle = cn(merged.frozenColumnStyle, overflowBg, "shadow-l-xl");
            merged.lastFrozenColumnStyle = cn(merged.lastFrozenColumnStyle, overflowBg, "shadow-r-xl");
        }
        return merged;
    }, [themeOverrides, isOverflowing]);
    // Get base classes from theme
    const baseClasses = theme.baseStyle || "";
    const variantClasses = ((_a = theme.variants) === null || _a === void 0 ? void 0 : _a[variant]) || "";
    // Memoize context value to prevent unnecessary re-renders in consumers
    const contextValue = useMemo(() => ({
        theme,
        variant,
        freezeHeader,
        freezeFirstColumn,
        freezeLastColumn,
        sortable,
        sortConfig,
        onSortChange,
        filterable,
        filterConfig,
        onFilterChange,
        filterLogic,
        expandable,
        expandedRows,
        onExpandedRowsChange,
        selectable,
        selectionType,
        selectedRows,
        onSelectionChange,
    }), [
        theme,
        variant,
        freezeHeader,
        freezeFirstColumn,
        freezeLastColumn,
        sortable,
        sortConfig,
        onSortChange,
        filterable,
        filterConfig,
        onFilterChange,
        filterLogic,
        expandable,
        expandedRows,
        onExpandedRowsChange,
        selectable,
        selectionType,
        selectedRows,
        onSelectionChange,
    ]);
    return (jsx(TableContext.Provider, { value: contextValue, children: jsxs("div", { className: "relative", children: [!isDeclarativeAPI && columns && ((filterable && onFilterChange) || showColumnManager) && (jsxs("div", { className: theme.columnManagerContainer, children: [filterable && onFilterChange && (jsx(TableFilter, { columns: columns, filterConfig: filterConfig, onFilterChange: onFilterChange, filterLogic: filterLogic, onFilterLogicChange: handleFilterLogicChange, data: data })), showColumnManager && (jsx(TableColumnManager, { columns: columns, visibleColumns: visibleColumns, columnOrder: columnOrder, onToggleColumn: handleToggleColumn, onResetToDefault: handleResetToDefault, onColumnReorder: onColumnReorder ? handleColumnReorder : undefined }))] })), !isDeclarativeAPI && selectable && selectedRows.length > 0 && (jsx(TableSelectionHeader, { selectedCount: selectedRows.length, totalCount: paginatedData.length, selectedRows: selectedRows, bulkActions: bulkActions, onClearSelection: handleClearSelection })), jsx("div", { className: "overflow-x-auto", ref: scrollContainerRef, children: jsx("table", { className: cn(baseClasses, variantClasses, className), role: "table", "aria-label": isDeclarativeAPI ? "Data table" : `Data table with ${paginatedData.length} rows`, "aria-rowcount": pagination ? pagination.totalItems : data === null || data === void 0 ? void 0 : data.length, "aria-colcount": visibleColumnsList.length, children: isDeclarativeAPI ? (children) : (jsxs(Fragment, { children: [jsx(TableHeader, { columns: visibleColumnsList, sortConfig: sortConfig, onSortChange: onSortChange, filterConfig: filterConfig, onFilterChange: onFilterChange, freezeHeader: freezeHeader, freezeFirstColumn: freezeFirstColumn, freezeLastColumn: freezeLastColumn, expandable: expandable, expandedRowRender: expandedRowRender, selectable: selectable, selectionType: selectionType, selectedRows: selectedRows, onSelectionChange: onSelectionChange, totalRowCount: paginatedData.length, theme: theme, data: paginatedData, rowKey: rowKey }), jsx(TableBody, { data: paginatedData, columns: visibleColumnsList, rowKey: rowKey, expandedRowRender: expandedRowRender, expandedRows: expandedRows, onExpandedRowsChange: onExpandedRowsChange, selectable: selectable, selectionType: selectionType, selectedRows: selectedRows, onSelectionChange: onSelectionChange, freezeFirstColumn: freezeFirstColumn, freezeLastColumn: freezeLastColumn, theme: theme })] })) }) })] }) }));
}
TableComponent.displayName = "Table";
const Table = TableComponent;

export { Table, TableContext };
