import { Host, h } from "@stencil/core";
import { closest } from "../../../utils/closest";
export class PdsTableRow {
    constructor() {
        this.observer = null;
        this.bodyObserver = null;
        /**
         * Determines if the row should have a divider border.
         * @defaultValue false
         */
        this.hasDivider = false;
        /**
         * Determines if this is the last row in the table body.
         * @defaultValue false
         */
        this.isLastRow = false;
        this.handleCheckboxChange = (event) => {
            this.isSelected = event.detail.checked;
            this.handleSelect(this.isSelected);
        };
        this.handleSelect = (isSelected) => {
            this.indeterminate = false;
            if (!closest('pds-table-head', this.hostElement)) {
                const rowIndex = Array.from(this.hostElement.parentNode.children).indexOf(this.hostElement);
                this.pdsTableRowSelected.emit({
                    rowIndex,
                    isSelected,
                });
            }
        };
        this.generateUniqueId = () => {
            const randomString = Math.random().toString(36).substring(2, 8);
            const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
            const uniqueId = `${randomString}-${timestamp}`;
            return uniqueId;
        };
    }
    classNames() {
        const classNames = [];
        if (this.isSelected) {
            classNames.push("is-selected");
        }
        if (this.hasDivider) {
            classNames.push("has-divider");
        }
        if (this.isLastRow) {
            classNames.push("is-last-row");
        }
        return classNames.join(' ');
    }
    componentWillRender() {
        // Always refresh tableRef to get latest prop values
        // This ensures we pick up changes to parent table props
        this.tableRef = this.hostElement.closest('pds-table');
        if (this.tableRef && this.tableRef.fixedColumn) {
            const tableCell = this.hostElement.querySelector('pds-table-cell');
            tableCell === null || tableCell === void 0 ? void 0 : tableCell.classList.add("is-fixed");
        }
    }
    componentWillLoad() {
        // Handle initial selection state
        if (this.isSelected) {
            this.handleSelect(this.isSelected);
        }
        // Note: tableRef, observers, and divider state are set up in connectedCallback
        // which runs before componentWillLoad and also handles row re-attachment after sorting
    }
    connectedCallback() {
        // When a row is re-attached to the DOM (e.g., after sorting),
        // we need to re-setup the observers since disconnectedCallback cleared them
        // Note: componentDidLoad only fires once, but connectedCallback fires every time
        // the element is attached to the DOM (including after being moved)
        this.tableRef = this.hostElement.closest('pds-table');
        this.setupObservers();
        this.updateDividerState();
    }
    disconnectedCallback() {
        this.cleanupObservers();
    }
    cleanupObservers() {
        if (this.observer) {
            this.observer.disconnect();
            this.observer = null;
        }
        if (this.bodyObserver) {
            this.bodyObserver.disconnect();
            this.bodyObserver = null;
        }
    }
    setupObservers() {
        // Clean up any existing observers first
        this.cleanupObservers();
        // Watch for changes to the parent table's row-dividers attribute
        if (this.tableRef && typeof MutationObserver !== 'undefined') {
            this.observer = new MutationObserver(() => {
                this.updateDividerState();
            });
            this.observer.observe(this.tableRef, {
                attributes: true,
                attributeFilter: ['row-dividers']
            });
        }
        // Watch for child list changes in table body (e.g., when rows are reordered during sorting)
        const tableBody = this.hostElement.closest('pds-table-body');
        if (tableBody && typeof MutationObserver !== 'undefined') {
            this.bodyObserver = new MutationObserver(() => {
                this.updateLastRowState();
            });
            this.bodyObserver.observe(tableBody, {
                childList: true
            });
        }
    }
    shouldHaveDivider() {
        if (!this.tableRef) {
            this.tableRef = this.hostElement.closest('pds-table');
        }
        // Reads the parent pds-table component's rowDividers property value directly
        return !!(this.tableRef && this.tableRef.rowDividers);
    }
    updateDividerState() {
        this.hasDivider = this.shouldHaveDivider();
        this.updateLastRowState();
    }
    updateLastRowState() {
        if (!this.hasDivider) {
            this.isLastRow = false;
            return;
        }
        const tableBody = this.hostElement.closest('pds-table-body');
        if (tableBody) {
            const rows = Array.from(tableBody.querySelectorAll('pds-table-row'));
            this.isLastRow = rows[rows.length - 1] === this.hostElement;
        }
        else {
            this.isLastRow = false;
        }
    }
    render() {
        return (h(Host, { key: '6bbd8bb7cd1f90de0e418748bf8d3b9240ab0cb8', class: this.classNames(), role: "row", part: "row" }, this.tableRef && this.tableRef.selectable && (h("pds-table-cell", { key: '9a92396654e7cdf819536335ebe95169d4d4c26d', part: this.tableRef.fixedColumn ? 'checkbox-cell' : 'checkbox-cell', class: this.tableRef.selectable ? 'has-checkbox' : '' }, h("pds-checkbox", { key: 'bf61a00da4d3c19280aae90d8eaff9515a716c52', componentId: this.generateUniqueId(), onPdsCheckboxChange: this.handleCheckboxChange, indeterminate: this.indeterminate, label: "Select Row", hideLabel: true, checked: this.isSelected, part: "row-checkbox" }))), h("slot", { key: 'f77887e878913bea5e0ca0a281a639285a65f1c1' })));
    }
    static get is() { return "pds-table-row"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["pds-table-row.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["pds-table-row.css"]
        };
    }
    static get properties() {
        return {
            "indeterminate": {
                "type": "boolean",
                "mutable": true,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Determines if the row selected is in an indeterminate state."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "indeterminate"
            },
            "isSelected": {
                "type": "boolean",
                "mutable": true,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Determines if the table row is currently selected."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "is-selected"
            }
        };
    }
    static get states() {
        return {
            "hasDivider": {},
            "isLastRow": {}
        };
    }
    static get events() {
        return [{
                "method": "pdsTableRowSelected",
                "name": "pdsTableRowSelected",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Event that is emitted when the checkbox is clicked, carrying the selected value."
                },
                "complexType": {
                    "original": "{ rowIndex: number; isSelected: boolean; }",
                    "resolved": "{ rowIndex: number; isSelected: boolean; }",
                    "references": {}
                }
            }];
    }
    static get elementRef() { return "hostElement"; }
}
//# sourceMappingURL=pds-table-row.js.map
