import { Host, h } from "@stencil/core";
import { downSmall, upSmall } from "@pine-ds/icons/icons";
import { isScrolledFromInlineStart } from "../../../utils/scroll";
export class PdsTableHeadCell {
    constructor() {
        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" }))));
    }
    static get is() { return "pds-table-head-cell"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["pds-table-head-cell.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["pds-table-head-cell.css"]
        };
    }
    static get properties() {
        return {
            "cellAlign": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "'start' | 'center' | 'end' | 'justify'",
                    "resolved": "\"center\" | \"end\" | \"justify\" | \"start\"",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Sets the text alignment within the head cell."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "cell-align"
            },
            "sortable": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Determines whether the table column is sortable when set to `true`."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "sortable"
            }
        };
    }
    static get states() {
        return {
            "sortingDirection": {},
            "tableScrolling": {},
            "isSelected": {},
            "hasHeadBorder": {},
            "hasHeadBackground": {},
            "isActive": {}
        };
    }
    static get events() {
        return [{
                "method": "pdsTableSort",
                "name": "pdsTableSort",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event emitted to signal that a table column header has been sorted, providing information about the sorted column's name and sorting direction."
                },
                "complexType": {
                    "original": "{ column: string; direction: string }",
                    "resolved": "{ column: string; direction: string; }",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "setActiveSort": {
                "complexType": {
                    "signature": "(direction: \"asc\" | \"desc\") => Promise<void>",
                    "parameters": [{
                            "name": "direction",
                            "type": "\"desc\" | \"asc\"",
                            "docs": "- The sort direction to apply ('asc' or 'desc')"
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "Programmatically sets this column as the active sort column with the specified direction.\nUsed by pds-table to apply a default sort on initial load.",
                    "tags": [{
                            "name": "param",
                            "text": "direction - The sort direction to apply ('asc' or 'desc')"
                        }]
                }
            },
            "clearActiveSort": {
                "complexType": {
                    "signature": "() => Promise<void>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "Clears the active sort state from this column.\nUsed internally when another column becomes active.",
                    "tags": []
                }
            }
        };
    }
    static get elementRef() { return "hostElement"; }
}
//# sourceMappingURL=pds-table-head-cell.js.map
