import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import Box from '../box';
import { styled, useStyleConfig, vui } from '../core';
import { cs, useCallbackRef } from '../utils';
import { useTableContext } from './context';
import TableSortIcon from './tableSortIcon';
export const ThBase = styled.thBox `
  font-weight: demi;
  text-align: left;
  transition-duration: fast;
`;
/** Displays Table heading with support for sort. */
export const Th = vui((props, ref) => {
    const { children, className, disabled, field, isInteractive: isInteractiveProp, isSortable, onClick: onClickProp, title, ...rest } = props;
    // Always call hooks unconditionally
    const tableContext = useTableContext();
    const styles = useStyleConfig('Table', tableContext);
    // Extract values after hook calls
    const { onSortChange, sort } = tableContext || {};
    const handleClick = useCallbackRef((e) => {
        onClickProp?.(e);
        if (isSortable && field && onSortChange) {
            onSortChange(field);
        }
    });
    const onClick = onClickProp || isSortable ? handleClick : undefined;
    const isActive = !disabled && sort?.key === field;
    const sortOrder = isActive ? sort.order : undefined;
    const isInteractive = isInteractiveProp ?? onClick !== undefined;
    const activeProps = isActive ? { bg: 'skyBlue.active' } : {};
    const disabledProps = disabled ? { bg: 'disabled.bg', color: 'disabled.color', cursor: 'not-allowed' } : {};
    const hoverBg = isSortable ? 'skyBlue.hover' : undefined;
    const interactiveProps = !disabled && isInteractive
        ? {
            cursor: 'pointer',
            onClick,
            tabIndex: 0,
            userSelect: 'none',
        }
        : {};
    return (_jsx(ThBase, { className: cs('vui-th', className), "data-active": isActive, "data-disabled": disabled, hoverBg: hoverBg, px: 2, ref: ref, ...styles.th, ...activeProps, ...disabledProps, ...interactiveProps, ...rest, children: children ?? (_jsxs(Box, { centerV: true, display: "inline-flex", children: [title, isSortable && _jsx(TableSortIcon, { ml: 1, my: 0.5, order: sortOrder })] })) }));
});
Th.displayName = 'Th';
export default Th;
//# sourceMappingURL=th.js.map