import { proxyCustomElement, HTMLElement, createEvent, h, Host } from '@stencil/core/internal/client';
import { u as upSmall, d as downSmall } from './index2.js';
import { i as isScrolledFromInlineStart } from './scroll.js';
import { d as defineCustomElement$1 } from './pds-icon2.js';

const pdsTableHeadCellCss = ":host{--border-head-cell-default:var(--pine-border-width-thin) solid var(--pine-color-border-subtle);--box-shadow-default:3px 3px 6px -2px rgba(0, 0, 0, 0.1);-webkit-border-after:var(--border-head-cell-default);border-block-end:var(--border-head-cell-default);color:var(--pine-color-text);display:table-cell;font-family:var(--pine-font-family-body);font-size:var(--pine-font-size);font-weight:var(--pine-font-weight-regular);letter-spacing:var(--pine-letter-spacing);line-height:var(--pine-line-height-body);padding:var(--pine-dimension-sm);position:relative;text-align:start;vertical-align:inherit}:host(.is-compact){padding-block:var(--pine-dimension-2xs)}:host(.is-fixed){background:var(--pine-color-background-container);inset-inline-start:var(--pine-dimension-none);position:-webkit-sticky;position:sticky;z-index:var(--pine-z-index-raised)}:host(.is-fixed.has-head-background){background-color:var(--pine-color-background-subtle)}:host(.has-head-border){-webkit-border-before:var(--border-head-cell-default);border-block-start:var(--border-head-cell-default)}:host-context([dir=rtl]){--box-shadow-default:-3px 3px 6px -2px rgba(0, 0, 0, 0.1)}:host(.has-scrolled.is-fixed){-webkit-box-shadow:var(--box-shadow-default);box-shadow:var(--box-shadow-default)}:host(.is-sortable){cursor:pointer}:host(.is-sortable) pds-icon{-webkit-margin-start:var(--pine-dimension-2xs);margin-inline-start:var(--pine-dimension-2xs);-webkit-padding-before:2px;padding-block-start:2px;position:absolute}:host(.is-sortable:hover),:host(.is-active){color:var(--pine-color-text-strong)}:host(.pds-table-head-cell--align-start){text-align:start}:host(.pds-table-head-cell--align-center){text-align:center}:host(.pds-table-head-cell--align-end){text-align:end}:host(.pds-table-head-cell--align-justify){text-align:justify}";

const PdsTableHeadCell = /*@__PURE__*/ proxyCustomElement(class PdsTableHeadCell extends HTMLElement {
    constructor(registerHost) {
        super();
        if (registerHost !== false) {
            this.__registerHost();
        }
        this.__attachShadow();
        this.pdsTableSort = createEvent(this, "pdsTableSort", 7);
        this.scrollContainer = null;
        this.setupRetries = 0;
        /**
         * The direction of sorting.
         */
        this.sortingDirection = 'asc';
        /**
         * Determines if the table is currently scrolling.
         * @defaultValue false
         */
        this.tableScrolling = false;
        /**
         * Determines if the table row is currently selected.
         * @defaultValue false
         */
        this.isSelected = false;
        /**
         * Determines if the parent table-head has the border attribute.
         * @defaultValue false
         */
        this.hasHeadBorder = false;
        /**
         * Determines if the parent table-head has the background attribute.
         * @defaultValue false
         */
        this.hasHeadBackground = false;
        /**
         * Determines if this column is the currently active sorted column.
         * @defaultValue false
         */
        this.isActive = false;
        /**
         * Handles scroll events to update fixed column shadow state.
         * Updates the tableScrolling state to control CSS classes for fixed column shadows.
         * @private
         */
        this.handleScroll = () => {
            if (!this.scrollContainer) {
                return;
            }
            try {
                this.tableScrolling = isScrolledFromInlineStart(this.scrollContainer);
            }
            catch (error) {
                console.warn('Scroll handler error:', error);
            }
        };
        this.toggleSort = () => {
            if (this.sortable) {
                // Guard: return early if tableRef is not available
                if (!this.tableRef) {
                    return;
                }
                const column = this.hostElement.innerText.trim();
                // Always toggle the direction (preserves original behavior)
                this.sortingDirection = this.sortingDirection === 'asc' ? 'desc' : 'asc';
                // Reset all OTHER head cells to inactive state (skip the current one)
                this.tableRef.querySelectorAll('pds-table-head-cell').forEach(async (headCell) => {
                    // Skip clearing the current cell
                    if (headCell !== this.hostElement) {
                        const headCellComponent = headCell;
                        await headCellComponent.clearActiveSort();
                    }
                });
                // Mark this column as active
                this.isActive = true;
                this.hostElement.classList.add('is-active');
                // Emit the sort event with the current direction
                this.pdsTableSort.emit({ column, direction: this.sortingDirection });
            }
        };
    }
    /**
     * Programmatically sets this column as the active sort column with the specified direction.
     * Used by pds-table to apply a default sort on initial load.
     * @param direction - The sort direction to apply ('asc' or 'desc')
     */
    async setActiveSort(direction) {
        if (!this.sortable)
            return;
        this.sortingDirection = direction;
        this.isActive = true;
        this.hostElement.classList.add('is-active');
    }
    /**
     * Clears the active sort state from this column.
     * Used internally when another column becomes active.
     */
    async clearActiveSort() {
        this.isActive = false;
        this.hostElement.classList.remove('is-active');
    }
    componentWillLoad() {
        // Set initial references and state before first render
        this.tableRef = this.hostElement.closest('pds-table');
        const tableHead = this.hostElement.closest('pds-table-head');
        if (tableHead) {
            this.hasHeadBorder = tableHead.hasAttribute('border');
            this.hasHeadBackground = tableHead.hasAttribute('background');
        }
    }
    componentDidLoad() {
        if (this.tableRef && this.tableRef.responsive && this.tableRef.fixedColumn) {
            // For responsive tables with fixed columns, set up scroll detection
            // This enables the first column header to show a shadow when the table is scrolled horizontally
            this.setupScrollListener();
        }
        // Watch for changes to the parent table-head's border and background attributes
        const tableHead = this.hostElement.closest('pds-table-head');
        if (tableHead && typeof MutationObserver !== 'undefined') {
            // Defensive guard: disconnect existing observer before creating a new one
            if (this.headObserver) {
                this.headObserver.disconnect();
            }
            this.headObserver = new MutationObserver(() => {
                // Update state when border or background attributes change
                this.hasHeadBorder = tableHead.hasAttribute('border');
                this.hasHeadBackground = tableHead.hasAttribute('background');
            });
            this.headObserver.observe(tableHead, {
                attributes: true,
                attributeFilter: ['border', 'background']
            });
        }
    }
    disconnectedCallback() {
        this.cleanupScrollListener();
        if (this.headObserver) {
            this.headObserver.disconnect();
        }
    }
    setupScrollListener() {
        var _a;
        if (!this.tableRef)
            return;
        // Query shadowRoot once and cache the container
        const container = (_a = this.tableRef.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector('.pds-table-responsive-container');
        if (container) {
            // Container available immediately
            this.scrollContainer = container;
            this.scrollContainer.addEventListener('scroll', this.handleScroll, { passive: true });
            this.handleScroll(); // Initial check
            this.setupRetries = 0; // Reset counter on success
        }
        else {
            // Container not ready, set up timer for retry with bounds
            this.setupTimer = window.setTimeout(() => {
                if (this.scrollContainer)
                    return; // Already found
                this.setupRetries = (this.setupRetries || 0) + 1;
                if (this.setupRetries <= 50) {
                    this.setupScrollListener();
                }
                else {
                    console.warn('Failed to find responsive container after 50 attempts');
                }
            }, 100);
        }
    }
    cleanupScrollListener() {
        if (this.scrollContainer) {
            this.scrollContainer.removeEventListener('scroll', this.handleScroll);
            this.scrollContainer = null;
        }
        if (this.setupTimer !== undefined) {
            window.clearTimeout(this.setupTimer);
            this.setupTimer = undefined;
        }
        this.setupRetries = 0; // Reset retry counter
    }
    classNames() {
        const classNames = [];
        if (this.tableRef && this.tableRef.compact) {
            classNames.push('is-compact');
        }
        if (this.cellAlign) {
            classNames.push(`pds-table-head-cell--align-${this.cellAlign}`);
        }
        if (this.sortable) {
            classNames.push('is-sortable');
        }
        if (this.sortable && this.sortingDirection !== null) {
            classNames.push('sort-' + this.sortingDirection);
        }
        if (this.tableRef && this.tableRef.fixedColumn && this.tableScrolling) {
            classNames.push('has-scrolled');
        }
        if (this.hasHeadBackground) {
            classNames.push('has-head-background');
        }
        if (this.hasHeadBorder) {
            classNames.push('has-head-border');
        }
        return classNames.join(' ');
    }
    render() {
        return (h(Host, { key: 'e0a30c326b81e0cc3fa8c0392b61f2a6625aad71', class: this.classNames(), role: "columnheader", onClick: this.toggleSort, part: "head-cell", style: this.tableRef &&
                this.tableRef.fixedColumn &&
                this.tableRef.selectable
                ? { '--fixed-cell-position': '40px' }
                : {} }, h("slot", { key: '3d0012983b2b552e4e61a3d84717afb9de8e572f' }), this.sortable && this.isActive && (h("pds-icon", { key: '326607f90b12ecc26a731dc696d0a3b8ebb0960c', icon: this.sortingDirection === 'asc' ? upSmall : downSmall, part: "sort-icon" }))));
    }
    get hostElement() { return this; }
    static get style() { return pdsTableHeadCellCss; }
}, [257, "pds-table-head-cell", {
        "cellAlign": [1, "cell-align"],
        "sortable": [4],
        "sortingDirection": [32],
        "tableScrolling": [32],
        "isSelected": [32],
        "hasHeadBorder": [32],
        "hasHeadBackground": [32],
        "isActive": [32],
        "setActiveSort": [64],
        "clearActiveSort": [64]
    }]);
function defineCustomElement() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["pds-table-head-cell", "pds-icon"];
    components.forEach(tagName => { switch (tagName) {
        case "pds-table-head-cell":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, PdsTableHeadCell);
            }
            break;
        case "pds-icon":
            if (!customElements.get(tagName)) {
                defineCustomElement$1();
            }
            break;
    } });
}

export { PdsTableHeadCell as P, defineCustomElement as d };
//# sourceMappingURL=pds-table-head-cell2.js.map

//# sourceMappingURL=pds-table-head-cell2.js.map