// #region Imports
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var TableCellElement_1;
import { HTMLElementEventEmitter } from '@breadstone/mosaik-elements';
import { DomServiceLocator } from '../../../../Dom/Dom';
import { Emit } from '../../../../events/Decorators/EmitDecorator';
import { Disableable } from '../../../Behaviors/Disableable';
import { Selectable } from '../../../Behaviors/Selectable';
import { TextFormattable } from '../../../Behaviors/TextFormattable';
import { TextOverflowable } from '../../../Behaviors/TextOverflowable';
import { Themeable } from '../../../Behaviors/Themeable';
import { addInheritanceConsumerController } from '../../../Controllers/InheritanceConsumerController';
import { Attribute } from '../../../Decorators/AttributeDecorator';
import { Component } from '../../../Decorators/ComponentDecorator';
import { Watch } from '../../../Decorators/WatchDecorator';
import { TableSelectionMode } from '../../../Types/TableSelectionMode';
import { TableSelectionType } from '../../../Types/TableSelectionType';
import { CustomElement } from '../../Abstracts/CustomElement';
import { IconElement } from '../../Media/Icon/IconElement';
import { TextElement } from '../../Primitives/Text/TextElement';
import { TableBodyElement } from './TableBodyElement';
import { tableCellElementTemplate } from './TableCellElementTemplate';
import { TableElement } from './TableElement';
import { TABLE_INHERITANCE_CONTEXT } from './TableInheritanceContext';
import { tableCellElementCosmopolitanStyle } from './Themes/TableCellElement.Cosmopolitan';
import { tableCellElementJoyStyle } from './Themes/TableCellElement.Joy';
import { tableCellElementMemphisStyle } from './Themes/TableCellElement.Memphis';
// #endregion
/**
 * Table Cell - A single unit within a table's row and column layout.
 *
 * @element mosaik-table-cell
 *
 * @slot  - The default slot.
 *
 * @csspart icon - The icon part.
 *
 * @cssprop {String} --table-cell-background-color - The cell background color CSS custom property.
 * @cssprop {String} --table-cell-border-color - The cell border color CSS custom property.
 * @cssprop {String} --table-cell-border-radius - The cell border radius CSS custom property.
 * @cssprop {String} --table-cell-border-width - The cell border width CSS custom property.
 * @cssprop {String} --table-cell-font-family - The cell font family CSS custom property.
 * @cssprop {String} --table-cell-font-letter-spacing - The cell font letter spacing CSS custom property.
 * @cssprop {String} --table-cell-font-line-height - The cell font line height CSS custom property.
 * @cssprop {String} --table-cell-font-size - The cell font size CSS custom property.
 * @cssprop {String} --table-cell-font-text-decoration - The cell font text decoration CSS custom property.
 * @cssprop {String} --table-cell-font-text-transform - The cell font text transform CSS custom property.
 * @cssprop {String} --table-cell-font-weight - The cell font weight CSS custom property.
 * @cssprop {String} --table-cell-foreground-color - The cell foreground color CSS custom property.
 * @cssprop {String} --table-cell-gap - The cell gap CSS custom property.
 * @cssprop {String} --table-cell-padding-bottom - The cell padding bottom CSS custom property.
 * @cssprop {String} --table-cell-padding-left - The cell padding left CSS custom property.
 * @cssprop {String} --table-cell-padding-right - The cell padding right CSS custom property.
 * @cssprop {String} --table-cell-padding-top - The cell padding top CSS custom property.
 * @cssprop {String} --table-cell-shadow - The cell shadow CSS custom property.
 * @cssprop {String} --table-cell-shadow-blur - The cell shadow blur CSS custom property.
 * @cssprop {String} --table-cell-shadow-color - The cell shadow color CSS custom property.
 * @cssprop {String} --table-cell-shadow-offset-x - The cell shadow offset x CSS custom property.
 * @cssprop {String} --table-cell-shadow-offset-y - The cell shadow offset y CSS custom property.
 * @cssprop {String} --table-cell-shadow-spread - The cell shadow spread CSS custom property.
 * @cssprop {String} --table-cell-transition-duration - The cell transition duration CSS custom property.
 * @cssprop {String} --table-cell-transition-mode - The cell transition mode CSS custom property.
 * @cssprop {String} --table-cell-transition-property - The cell transition property CSS custom property.
 * @cssprop {String} --table-cell-translate - The cell translate CSS custom property.
 *
 * @fires tableSortChanged {TableSortChangedEvent} - Fired when the sort direction of the cell has changed.
 * @fires selected {SelectedEvent} - Fired when the cell is selected.
 * @fires deselected {DeselectedEvent} - Fired when the cell is deselected.
 *
 * @dependency mosaik-icon - The Icon element.
 * @dependency mosaik-text - The Text element.
 *
 * @example
 * Basic table cell with text:
 * ```html
 * <mosaik-table-cell text="Alice"></mosaik-table-cell>
 * ```
 *
 * @example
 * Sortable header cell:
 * ```html
 * <mosaik-table-cell text="Name" key="name" sortable></mosaik-table-cell>
 * ```
 *
 * @public
 */
let TableCellElement = TableCellElement_1 = class TableCellElement extends Themeable(Selectable(Disableable(TextFormattable(TextOverflowable(CustomElement))))) {
    // #region Fields
    _inheritance = addInheritanceConsumerController(this, {
        context: TABLE_INHERITANCE_CONTEXT
    });
    _tableSortChanged;
    _key;
    _sorted;
    _sortable;
    _sortDirection;
    _text;
    _clickSubscription;
    _selectionClickSubscription;
    _table;
    // #endregion
    // #region Ctor
    /**
     * @public
     */
    constructor() {
        super();
        this._key = '';
        this._sorted = false;
        this._sortable = false;
        this._sortDirection = 'none';
        this._text = '';
        this._clickSubscription = null;
        this._selectionClickSubscription = null;
        this._table = null;
        this._tableSortChanged = new HTMLElementEventEmitter(this, 'tableSortChanged');
    }
    // #endregion
    // #region Properties
    /**
     * Returns the `is` property.
     *
     * @public
     * @static
     * @readonly
    */
    static get is() {
        return 'mosaik-table-cell';
    }
    /**
     * Gets or sets the `key` property.
     *
     * @public
     * @attr
     */
    get key() {
        return this._key;
    }
    set key(value) {
        if (this._key !== value) {
            this._key = value;
            this.requestUpdate('key');
        }
    }
    /**
     * Gets or sets the `sortable` property.
     *
     * @public
     * @attr
     */
    get sortable() {
        return this._sortable;
    }
    set sortable(value) {
        if (this._sortable !== value) {
            this._sortable = value;
            this.requestUpdate('sortable');
        }
    }
    /**
     * Gets or sets the `text` property.
     *
     * @public
     * @attr
     */
    get text() {
        return this._text;
    }
    set text(value) {
        if (this._text !== value) {
            this._text = value;
            this.requestUpdate('text');
        }
    }
    /**
     * Gets or sets the `sortDirection` property.
     *
     * @public
     * @attr
     */
    get sortDirection() {
        return this._sortDirection;
    }
    set sortDirection(value) {
        if (this._sortDirection !== value) {
            this._sortDirection = value;
            this.requestUpdate('sortDirection');
        }
    }
    /**
     * Called when the sort direction changes.
     * Provides reference to `ITableSortChangedEventDetail` as event argument.
     *
     * @public
     * @readonly
     * @eventProperty
     * @type IEventEmitter<ITableSortChangedEventDetail>
     */
    get tableSortChanged() {
        return this._tableSortChanged;
    }
    // #endregion
    // #region Methods
    /**
     * Sorts the cell in the specified direction.
     *
     * @public
     */
    sort(direction) {
        this.sortDirection = direction;
        this._sorted = this.sortDirection !== 'none';
        this.requestUpdate('sortDirection');
        this._tableSortChanged.emit({
            sortKey: this._key,
            sortDirection: this._sortDirection
        });
    }
    /**
     * Unsorts the cell.
     *
     * @public
     */
    unsort() {
        this.sortDirection = 'none';
        this._sorted = false;
        this.requestUpdate('sortDirection');
        this._tableSortChanged.emit({
            sortKey: this._key,
            sortDirection: this._sortDirection
        });
    }
    /**
     * @public
     * @override
     */
    attributeChangedCallback(name, oldValue, newValue) {
        super.attributeChangedCallback(name, oldValue, newValue);
        if (name === 'sortable') {
            if (this._sortable) {
                this._clickSubscription = this.on('click', () => this.handleSort());
            }
            else {
                this._clickSubscription?.dispose();
            }
        }
    }
    /**
     * @public
     * @override
     */
    disconnectedCallback() {
        super.disconnectedCallback();
        this._clickSubscription?.dispose();
        this._selectionClickSubscription?.dispose();
    }
    /**
     * @protected
     * @override
     */
    onApplyTemplate() {
        const table = DomServiceLocator.current.findAncestor(this, TableElement);
        if (table) {
            this._table = table;
            this.updateSelectionClickHandler();
        }
    }
    /**
     * @protected
     */
    onSelectionModePropertyChanged(_prev, _next) {
        this.updateSelectionClickHandler();
    }
    /**
     * @protected
     */
    onSelectionTypePropertyChanged(_prev, _next) {
        this.updateSelectionClickHandler();
    }
    /**
     * Sets up or tears down the click handler based on the inherited selection config.
     *
     * @private
     */
    updateSelectionClickHandler() {
        this._selectionClickSubscription?.dispose();
        this._selectionClickSubscription = null;
        const selectionMode = this._inheritance.get('selectionMode', TableSelectionMode.None);
        const selectionType = this._inheritance.get('selectionType', TableSelectionType.Row);
        // Only attach click handler if selection is cell-based and not disabled
        if (selectionMode !== TableSelectionMode.None && selectionType === TableSelectionType.Cell) {
            // Only attach if this cell is in a table body (not header/footer)
            const isInBody = DomServiceLocator.current.findAncestor(this, TableBodyElement) !== null;
            if (isInBody && this._table) {
                this._selectionClickSubscription = this.on('click', () => this.handleCellClick());
            }
        }
    }
    /**
     * Handles click events for cell selection.
     *
     * @private
     */
    handleCellClick() {
        if (this.disabled || !this._table) {
            return;
        }
        this._table.handleCellSelect(this);
    }
    /**
     * Handles click events for row selection.
     *
     * @private
     */
    handleSort() {
        let nextSortDirection = 'none';
        switch (this._sortDirection) {
            case 'asc':
                nextSortDirection = 'desc';
                break;
            case 'desc':
                nextSortDirection = 'none';
                break;
            case 'none':
                nextSortDirection = 'asc';
                break;
            default:
                nextSortDirection = 'none';
                break;
        }
        this.sort(nextSortDirection);
        if (!this._sorted) {
            // unsort other heads otherwise
            const cells = this.parentElement
                ? DomServiceLocator.current.findDescendants(this.parentElement, TableCellElement_1)
                : null;
            cells?.forEach((x) => x.unsort());
            this.sort(this._sortDirection);
        }
    }
};
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], TableCellElement.prototype, "key", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], TableCellElement.prototype, "sortable", null);
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], TableCellElement.prototype, "text", null);
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], TableCellElement.prototype, "sortDirection", null);
__decorate([
    Emit({ eventName: 'tableSortChanged' }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [])
], TableCellElement.prototype, "tableSortChanged", null);
__decorate([
    Watch('selectionMode', { waitUntilFirstUpdate: true }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String]),
    __metadata("design:returntype", void 0)
], TableCellElement.prototype, "onSelectionModePropertyChanged", null);
__decorate([
    Watch('selectionType', { waitUntilFirstUpdate: true }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String]),
    __metadata("design:returntype", void 0)
], TableCellElement.prototype, "onSelectionTypePropertyChanged", null);
TableCellElement = TableCellElement_1 = __decorate([
    Component({
        selector: 'mosaik-table-cell',
        template: tableCellElementTemplate,
        themes: {
            joy: tableCellElementJoyStyle,
            memphis: tableCellElementMemphisStyle,
            cosmopolitan: tableCellElementCosmopolitanStyle
        },
        imports: [
            TextElement,
            IconElement
        ]
    }),
    __metadata("design:paramtypes", [])
], TableCellElement);
export { TableCellElement };
//# sourceMappingURL=TableCellElement.js.map