import { Host, h } from "@stencil/core";
import { isScrolledFromInlineStart } from "../../../utils/scroll";
import { setupTruncationTooltip } from "../../../utils/truncation-tooltip";
export class PdsTableCell {
    constructor() {
        this.scrollContainer = null;
        this.setupRetries = 0;
        this.truncationCleanup = null;
        /**
         * Determines if the table is currently scrolling.
         * @defaultValue false
         */
        this.tableScrolling = 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);
            }
        };
    }
    componentWillRender() {
        this.tableRef = this.hostElement.closest('pds-table');
    }
    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 to show a shadow when the table is scrolled horizontally
            this.setupScrollListener();
        }
        if (this.truncate) {
            this.initTruncationTooltip();
        }
    }
    disconnectedCallback() {
        this.cleanupScrollListener();
        this.destroyTruncationTooltip();
    }
    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
    }
    handleTruncateChange(newValue) {
        if (newValue) {
            this.initTruncationTooltip();
        }
        else {
            this.destroyTruncationTooltip();
        }
    }
    initTruncationTooltip() {
        this.destroyTruncationTooltip();
        this.truncationCleanup = setupTruncationTooltip({
            hostEl: this.hostElement,
            contentEl: this.hostElement,
            getTooltipText: () => this.hostElement.textContent || '',
        });
    }
    destroyTruncationTooltip() {
        if (this.truncationCleanup) {
            this.truncationCleanup();
            this.truncationCleanup = null;
        }
    }
    classNames() {
        const classNames = [];
        if (this.tableRef && this.tableRef.compact) {
            classNames.push('is-compact');
        }
        if (this.cellAlign) {
            classNames.push(`pds-table-cell--align-${this.cellAlign}`);
        }
        if (this.truncate) {
            classNames.push('is-truncated');
        }
        if (this.tableRef && this.tableRef.fixedColumn && this.tableScrolling) {
            classNames.push('has-scrolled');
        }
        return classNames.join(' ');
    }
    render() {
        return (h(Host, { key: 'b108b0fce3ff0d5c503922a6c936ffd6ca52523f', class: this.classNames(), role: "gridcell", part: "cell", tabIndex: this.truncate ? 0 : undefined, style: this.tableRef &&
                this.tableRef.fixedColumn &&
                this.tableRef.selectable
                ? { '--fixed-cell-position': '40px' }
                : {} }, h("slot", { key: 'ebc1709ef52029bc6afec2fa89a90d47620892cb' })));
    }
    static get is() { return "pds-table-cell"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["pds-table-cell.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["pds-table-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 cell."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "cell-align"
            },
            "truncate": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Truncates content to a max width and adds an ellipsis.\nWhen text overflows, a tooltip showing the full text will appear on hover/focus.\nNote: When truncate is enabled, the element automatically receives tabindex=\"0\" for keyboard accessibility."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "truncate"
            }
        };
    }
    static get states() {
        return {
            "tableScrolling": {}
        };
    }
    static get elementRef() { return "hostElement"; }
    static get watchers() {
        return [{
                "propName": "truncate",
                "methodName": "handleTruncateChange"
            }];
    }
}
//# sourceMappingURL=pds-table-cell.js.map
