/*!
 * Custom elements for Nanopore-Digital Web applications
 */
import { Fragment } from "@stencil/core";
import { h } from "../../utils/renderer";
import { CSSNAMESPACE } from "./table.constants";
import { colheadFootRender, headerPinClasses, mergeProperties, } from "./table.utils";
export const TableColHead = ({ column, onColumnSortClick, defaults, }) => {
    if (column.hidden) {
        return h(Fragment, null);
    }
    // Sort handling
    function handleColumnSortClick(e) {
        let order;
        switch (column.order) {
            case 'asc':
                order = 'desc';
                break;
            case 'desc':
                order = null;
                break;
            default:
                order = 'asc';
        }
        onColumnSortClick(order, column.prop, e.target.closest('th'));
    }
    function isSortable() {
        return ((!!defaults.sortable && column.sortable !== false) ||
            (!defaults.sortable && column.sortable === true));
    }
    let extraProps = {};
    if (column.columnProperties) {
        extraProps = column.columnProperties(column) || extraProps;
    }
    const baseProps = {
        class: {
            ...headerPinClasses('th', column.pinned),
            [`${CSSNAMESPACE}__pin--start`]: column.pinned === 'start',
            [`${CSSNAMESPACE}__pin--end`]: column.pinned === 'end',
            [`${CSSNAMESPACE}__ordered`]: !!column.order,
            [`${CSSNAMESPACE}__filtered`]: column.filter !== undefined && column.filter !== null,
        },
    };
    let props = extraProps ? mergeProperties(baseProps, extraProps) : baseProps;
    const content = colheadFootRender(column);
    if (!content)
        return h(Fragment, null);
    props =
        Number(props.colSpan) > 1
            ? { ...props, scope: 'colgroup' }
            : { ...props, scope: 'col' };
    if (isSortable()) {
        const sort = column.order
            ? column.order === 'asc'
                ? 'ascending'
                : 'descending'
            : 'none';
        props = { ...props, 'aria-sort': sort };
    }
    return (h("th", { ...props, key: column.prop }, isSortable() ? (h("button", { class: {
            [`${CSSNAMESPACE}__order-btn`]: true,
            [`${CSSNAMESPACE}__cell-content`]: true,
        }, onClick: handleColumnSortClick }, colheadFootRender(column), column.filter !== undefined && column.filter !== null && (h("nano-icon", { name: "light/filter" })), !!column.order &&
        (column.order === 'desc' ? (h("nano-icon", { name: "solid/arrow-down-long" })) : (h("nano-icon", { name: "solid/arrow-up-long" }))), h("div", { class: `${CSSNAMESPACE}__status-icons` }, h("nano-icon", { name: "light/chevron-down" })))) : (h("div", { class: `${CSSNAMESPACE}__cell-content` }, colheadFootRender(column), column.filter !== undefined && column.filter !== null && (h("nano-icon", { name: "light/bars-filter" }))))));
};
