// #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);
};
import { HTMLElementEventEmitter, on } from '@breadstone/mosaik-elements';
import { Emit } from '../../../../events/Decorators/EmitDecorator';
import { Busyable } from '../../../Behaviors/Busyable';
import { ContentAlignable } from '../../../Behaviors/ContentAlignable';
import { Fitable } from '../../../Behaviors/Fitable';
import { Iconable } from '../../../Behaviors/Iconable';
import { Labelable } from '../../../Behaviors/Labelable';
import { Orientable } from '../../../Behaviors/Orientable';
import { Reversible } from '../../../Behaviors/Reversible';
import { Themeable } from '../../../Behaviors/Themeable';
import { Attribute } from '../../../Decorators/AttributeDecorator';
import { Component } from '../../../Decorators/ComponentDecorator';
import { RippleElement } from '../../Effects/Ripple/RippleElement';
import { StackElement } from '../../Layouts/Stack/StackElement';
import { IconElement } from '../../Media/Icon/IconElement';
import { FocusRingElement } from '../../Primitives/FocusRing/FocusRingElement';
import { TextElement } from '../../Primitives/Text/TextElement';
import { ProgressRingElement } from '../../Ranges/ProgressRing/ProgressRingElement';
import { ButtonBaseElement } from '../Abstracts/ButtonBaseElement';
import { pressButtonElementTemplate } from './PressButtonElementTemplate';
import { pressButtonElementCosmopolitanStyle } from './Themes/PressButtonElement.Cosmopolitan';
import { pressButtonElementJoyStyle } from './Themes/PressButtonElement.Joy';
import { pressButtonElementMemphisStyle } from './Themes/PressButtonElement.Memphis';
// #endregion
/**
 * Press Button - An interactive button that requires holding for a configurable duration before triggering its action.
 *
 * @description
 * The Press Button is a safety-focused button designed for destructive or high-impact actions
 * such as deleting resources. Unlike a standard button, it requires the user to press and hold
 * for a configurable countdown duration before the action fires. While held, a progress bar fills
 * the button background from left to right, providing visual feedback. If the user releases before
 * the countdown completes, the action is cancelled and the progress resets. This prevents accidental
 * triggering of critical operations.
 *
 * @name Press Button
 * @element mosaik-press-button
 * @category Buttons
 *
 * @slot icon - The icon slot for placing an icon inside the button.
 * @slot label - The label slot for text or labels inside the button.
 * @slot overlay - The overlay slot (useful for badges or additional visual elements).
 *
 * @csspart button - The button part of the Press Button.
 * @csspart focusRing - The focus ring part of the Press Button.
 * @csspart icon - The icon part of the Press Button.
 * @csspart innerStack - The innerStack part.
 * @csspart label - The label part of the Press Button.
 * @csspart progressFill - The progress bar fill that animates from left to right during press.
 * @csspart progressRing - The progress ring part of the Press Button.
 * @csspart ripple - The ripple effect part of the Press Button.
 *
 * @cssprop {Color} --press-button-background-color - The background color of the Press Button.
 * @cssprop {Color} --press-button-border-color - The border color of the Press Button.
 * @cssprop {String} --press-button-border-radius - The border radius of the Press Button.
 * @cssprop {String} --press-button-border-style - The border style of the Press Button.
 * @cssprop {String} --press-button-border-width - The border width of the Press Button.
 * @cssprop {String} --press-button-focus-ring-active-width - The button focus ring active width CSS custom property.
 * @cssprop {String} --press-button-focus-ring-color - The button focus ring color CSS custom property.
 * @cssprop {String} --press-button-focus-ring-inward-offset - The button focus ring inward offset CSS custom property.
 * @cssprop {String} --press-button-focus-ring-outward-offset - The button focus ring outward offset CSS custom property.
 * @cssprop {String} --press-button-font-family - The font family of the Press Button.
 * @cssprop {String} --press-button-font-letter-spacing - The font letter spacing of the Press Button.
 * @cssprop {String} --press-button-font-line-height - The font line height of the Press Button.
 * @cssprop {String} --press-button-font-size - The font size of the Press Button.
 * @cssprop {String} --press-button-font-text-decoration - The font text decoration of the Press Button.
 * @cssprop {String} --press-button-font-text-transform - The font text transform of the Press Button.
 * @cssprop {String} --press-button-font-weight - The font weight of the Press Button.
 * @cssprop {Color} --press-button-foreground-color - The foreground color of the Press Button.
 * @cssprop {String} --press-button-gap - The gap between elements of the Press Button.
 * @cssprop {String} --press-button-height - The button height CSS custom property.
 * @cssprop {String} --press-button-icon-min-height - The button icon min height CSS custom property.
 * @cssprop {String} --press-button-icon-min-width - The button icon min width CSS custom property.
 * @cssprop {String} --press-button-line-height - The line height of the Press Button text.
 * @cssprop {String} --press-button-min-height - The button min height CSS custom property.
 * @cssprop {String} --press-button-min-width - The button min width CSS custom property.
 * @cssprop {String} --press-button-padding-bottom - The padding bottom of the Press Button.
 * @cssprop {String} --press-button-padding-left - The padding left of the Press Button.
 * @cssprop {String} --press-button-padding-right - The padding right of the Press Button.
 * @cssprop {String} --press-button-padding-top - The padding top of the Press Button.
 * @cssprop {Color} --press-button-progress-fill-color - The progress fill background color during press.
 * @cssprop {String} --press-button-progress-ring-width - The button progress ring width CSS custom property.
 * @cssprop {String} --press-button-progress-thickness - The button progress thickness CSS custom property.
 * @cssprop {Color} --press-button-ripple-color - The button ripple color CSS custom property.
 * @cssprop {String} --press-button-ripple-duration - The button ripple duration CSS custom property.
 * @cssprop {String} --press-button-shadow - The shadow of the Press Button.
 * @cssprop {String} --press-button-shadow-blur - The button shadow blur CSS custom property.
 * @cssprop {String} --press-button-shadow-color - The button shadow color CSS custom property.
 * @cssprop {String} --press-button-shadow-offset-x - The button shadow offset x CSS custom property.
 * @cssprop {String} --press-button-shadow-offset-y - The button shadow offset y CSS custom property.
 * @cssprop {String} --press-button-shadow-spread - The button shadow spread CSS custom property.
 * @cssprop {String} --press-button-transition-duration - The transition duration for the Press Button.
 * @cssprop {String} --press-button-transition-mode - The transition mode for the Press Button.
 * @cssprop {String} --press-button-transition-property - The transition property for the Press Button.
 * @cssprop {String} --press-button-translate - The button translate CSS custom property.
 * @cssprop {String} --press-button-width - The button width CSS custom property.
 *
 * @fires pressed {PressedEvent} - Called when the press duration countdown has completed.
 *
 * @dependency {FocusRingElement} mosaik-focus-ring - The Focus Ring component, used for focus indication.
 * @dependency {IconElement} mosaik-icon - The Icon component, used for displaying the icon.
 * @dependency {ProgressRingElement} mosaik-progress-ring - The Progress Ring component, used for progress indication.
 * @dependency {RippleElement} mosaik-ripple - The Ripple component, used for the ripple effect.
 * @dependency {StackElement} mosaik-stack - The Stack component, used for layout management.
 * @dependency {TextElement} mosaik-text - The Text component, used for displaying the label text.
 *
 * @example
 * Destructive action requiring user confirmation by holding:
 * ```html
 * <mosaik-press-button label="Delete" variant="danger" duration="3000"></mosaik-press-button>
 * ```
 *
 * @example
 * Press button with custom countdown duration for critical infrastructure operations:
 * ```html
 * <mosaik-press-button label="Shut Down Server" variant="warning" duration="5000"></mosaik-press-button>
 * ```
 *
 * @public
 */
let PressButtonElement = class PressButtonElement extends Themeable(Reversible(Orientable(ContentAlignable(Fitable(Busyable(Labelable(Iconable(ButtonBaseElement)))))))) {
    // #region Fields
    _duration;
    _isPressing;
    _isMouseKeydown;
    _progress;
    _animationFrameId;
    _lastTimestamp;
    _fillElement;
    _pointerDownSubscription;
    _pointerUpSubscription;
    _pointerCancelSubscription;
    _pressed;
    // #endregion
    // #region Ctor
    /**
     * @public
     */
    constructor() {
        super();
        this._duration = 3000;
        this._isPressing = false;
        this._isMouseKeydown = false;
        this._progress = 0;
        this._animationFrameId = null;
        this._lastTimestamp = 0;
        this._fillElement = null;
        this._pointerDownSubscription = null;
        this._pointerUpSubscription = null;
        this._pointerCancelSubscription = null;
        this._pressed = new HTMLElementEventEmitter(this, 'pressed');
    }
    // #endregion
    // #region Properties
    /**
     * Returns the `is` property.
     * The `is` property represents natural name of this element.
     *
     * @public
     * @static
     * @readonly
     */
    static get is() {
        return 'mosaik-press-button';
    }
    /**
     * Gets or sets the `duration` property.
     * The duration in milliseconds that the button must be held before the `pressed` event fires.
     *
     * @public
     * @attr duration
     */
    get duration() {
        return this._duration;
    }
    set duration(value) {
        if (this._duration !== value) {
            this._duration = value;
            this.requestUpdate('duration');
        }
    }
    /**
     * Gets or sets the `isPressing` property.
     * Indicates whether the button is currently being pressed and the countdown is active.
     *
     * @public
     * @readonly
     * @attr is-pressing
     */
    get isPressing() {
        return this._isPressing;
    }
    /**
     * @private
     */
    set isPressing(value) {
        if (this._isPressing !== value) {
            this._isPressing = value;
            this.requestUpdate('isPressing');
        }
    }
    /**
     * Called when the press countdown has completed.
     * Provides reference to `IPressedEventDetail` as event detail.
     *
     * @public
     * @readonly
     * @eventProperty
     */
    get pressed() {
        return this._pressed;
    }
    // #endregion
    // #region Methods
    /**
     * @public
     * @override
     */
    disconnectedCallback() {
        super.disconnectedCallback();
        this._pointerDownSubscription?.dispose();
        this._pointerUpSubscription?.dispose();
        this._pointerCancelSubscription?.dispose();
        this.cancelAnimation();
        this._progress = 0;
        this._isMouseKeydown = false;
        this.isPressing = false;
    }
    /**
     * @protected
     * @override
     */
    onApplyTemplate() {
        super.onApplyTemplate();
        const buttonElement = this.getTemplatePart('button');
        this._fillElement = this.getTemplatePart('progressFill');
        this._pointerDownSubscription = on(buttonElement, 'pointerdown', (event) => this.onPointerDown(event));
    }
    /**
     * Emits the `pressed` event.
     *
     * @protected
     */
    onPressed(args) {
        this._pressed.emit(args);
    }
    /**
     * @private
     */
    onPointerDown(event) {
        // Only handle primary button (left mouse / touch)
        if (event.button !== 0 || this._isMouseKeydown) {
            return;
        }
        this._isMouseKeydown = true;
        this.isPressing = true;
        // Cancel any ongoing drain animation and resume from current progress
        this.cancelAnimation();
        // Register global listeners to catch pointer release anywhere
        this._pointerUpSubscription?.dispose();
        this._pointerCancelSubscription?.dispose();
        this._pointerUpSubscription = on(document, 'pointerup', () => this.release());
        this._pointerCancelSubscription = on(document, 'pointercancel', () => this.release());
        // Start fill animation from current progress
        this._lastTimestamp = performance.now();
        this._animationFrameId = requestAnimationFrame((t) => this.fillTick(t));
    }
    /**
     * Advances the progress fill on each animation frame while the button is held.
     *
     * @private
     */
    fillTick(timestamp) {
        const delta = timestamp - this._lastTimestamp;
        this._lastTimestamp = timestamp;
        this._progress = Math.min(1, this._progress + delta / this._duration);
        this.updateFillStyle();
        if (this._progress >= 1) {
            this.onCompleted();
            return;
        }
        this._animationFrameId = requestAnimationFrame((t) => this.fillTick(t));
    }
    /**
     * Drains the progress fill at 2x speed on each animation frame after the button is released.
     *
     * @private
     */
    drainTick(timestamp) {
        const delta = timestamp - this._lastTimestamp;
        this._lastTimestamp = timestamp;
        // Drain at 2x fill speed
        this._progress = Math.max(0, this._progress - (delta / this._duration) * 2);
        this.updateFillStyle();
        if (this._progress <= 0) {
            this._progress = 0;
            return;
        }
        this._animationFrameId = requestAnimationFrame((t) => this.drainTick(t));
    }
    /**
     * Called when the progress reaches 100%. Fires the pressed event and fades out the progress fill.
     *
     * @private
     */
    onCompleted() {
        this._isMouseKeydown = false;
        this.isPressing = false;
        this.cancelAnimation();
        this.releaseListeners();
        this.onPressed({});
        // Fade out the fill using CSS transition on opacity, then reset
        if (this._fillElement) {
            this._fillElement.style.opacity = '0';
            this._fillElement.addEventListener('transitionend', () => {
                this._progress = 0;
                if (this._fillElement) {
                    this._fillElement.style.width = '0%';
                    this._fillElement.style.opacity = '';
                }
            }, { once: true });
        }
    }
    /**
     * @private
     */
    release() {
        if (!this._isMouseKeydown) {
            return;
        }
        this._isMouseKeydown = false;
        this.isPressing = false;
        this.cancelAnimation();
        this.releaseListeners();
        // Start drain animation at 2x speed if there is progress to drain
        if (this._progress > 0) {
            this._lastTimestamp = performance.now();
            this._animationFrameId = requestAnimationFrame((t) => this.drainTick(t));
        }
    }
    /**
     * Cancels any running requestAnimationFrame loop.
     *
     * @private
     */
    cancelAnimation() {
        if (this._animationFrameId !== null) {
            cancelAnimationFrame(this._animationFrameId);
            this._animationFrameId = null;
        }
    }
    /**
     * Updates the progress fill element width to reflect the current progress.
     *
     * @private
     */
    updateFillStyle() {
        if (this._fillElement) {
            this._fillElement.style.width = `${this._progress * 100}%`;
        }
    }
    /**
     * Disposes the global pointer event listeners.
     *
     * @private
     */
    releaseListeners() {
        this._pointerUpSubscription?.dispose();
        this._pointerCancelSubscription?.dispose();
        this._pointerUpSubscription = null;
        this._pointerCancelSubscription = null;
    }
};
__decorate([
    Attribute({ type: Number }),
    __metadata("design:type", Number),
    __metadata("design:paramtypes", [Number])
], PressButtonElement.prototype, "duration", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], PressButtonElement.prototype, "isPressing", null);
__decorate([
    Emit({ eventName: 'pressed' }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [])
], PressButtonElement.prototype, "pressed", null);
PressButtonElement = __decorate([
    Component({
        selector: 'mosaik-press-button',
        template: pressButtonElementTemplate,
        themes: {
            joy: pressButtonElementJoyStyle,
            memphis: pressButtonElementMemphisStyle,
            cosmopolitan: pressButtonElementCosmopolitanStyle
        },
        options: {
            mode: 'open',
            delegatesFocus: true
        },
        imports: [
            StackElement,
            IconElement,
            RippleElement,
            FocusRingElement,
            TextElement,
            ProgressRingElement
        ]
    }),
    __metadata("design:paramtypes", [])
], PressButtonElement);
export { PressButtonElement };
//# sourceMappingURL=PressButtonElement.js.map