// #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 TimeBoxElement_1;
import { DomServiceLocator } from '../../../../Dom/Dom';
import { Appearanceable } from '../../../Behaviors/Appearanceable';
import { Clearable } from '../../../Behaviors/Clearable';
import { Disableable } from '../../../Behaviors/Disableable';
import { DropDownable } from '../../../Behaviors/DropDownable';
import { Invalidable } from '../../../Behaviors/Invalidable';
import { Labelable } from '../../../Behaviors/Labelable';
import { Localeable } from '../../../Behaviors/Localeable';
import { Slottable } from '../../../Behaviors/Slottable';
import { Valueable } from '../../../Behaviors/Valueable';
import { Variantable } from '../../../Behaviors/Variantable';
import { ClickOutsideController } from '../../../Controllers/ClickOutsideController';
import { Attribute } from '../../../Decorators/AttributeDecorator';
import { Component } from '../../../Decorators/ComponentDecorator';
import { Property } from '../../../Decorators/PropertyDecorator';
import { Watch } from '../../../Decorators/WatchDecorator';
import { ITimeSpan } from '../../../Types/TimeSpan';
import { FloatingElement } from '../../Primitives/Floating/FloatingElement';
import { FocusRingElement } from '../../Primitives/FocusRing/FocusRingElement';
import { MenuElement } from '../../Selectors/Menu/MenuElement';
import { MenuItemElement } from '../../Selectors/Menu/MenuItemElement';
import { InputBaseElement } from '../Abstracts/InputBase';
import { timeBoxElementTemplate } from './TimeBoxElementTemplate';
import { timeBoxElementJoyStyle } from './Themes/TimeBoxElement.Joy';
import { timeBoxElementRetroStyle } from './Themes/TimeBoxElement.Retro';
import { timeBoxElementCosmopolitanStyle } from './Themes/TimeBoxElement.Cosmopolitan';
import { Themeable } from '../../../Behaviors/Themeable';
import { TextAlignment } from '../../../Types/TextAlignment';
import { PortalElement } from '../../Primitives/Portal/PortalElement';
import { Key, KeyName } from '../../../../Controls/Types/Key';
import { KeyboardController } from '../../../Controllers/KeyboardController';
import { ButtonElement } from '../../Buttons/Button/ButtonElement';
import { ProjectionController } from '../../Primitives/Portal/ProjectionController';
// #endregion
/**
 * Time Box - A sophisticated time input control with dropdown time selection and flexible time formatting.
 *
 * @description
 * The Time Box component provides an intuitive interface for selecting and inputting time values with support
 * for various time formats, locales, and input methods. It features a text input field combined with a dropdown
 * time picker that displays selectable time slots. The component handles time parsing and validation, supports
 * 12/24-hour formats, customizable time intervals, minimum and maximum time constraints, and keyboard navigation.
 * Features include internationalization support, custom time markers, flexible formatting options, and comprehensive
 * accessibility features. Ideal for scheduling applications, appointment booking, form inputs, and any interface
 * requiring precise time selection.
 *
 * @name Time Box
 * @element mosaik-timebox
 * @category Inputs
 *
 * @slot prefix - Content placed before the input field.
 * @slot suffix - Content placed after the input field.
 *
 * @csspart focusRing - The focus ring indicator.
 * @csspart prefix - The prefix content container.
 * @csspart inner - The inner container wrapper.
 * @csspart label - The floating label element.
 * @csspart input - The time input field.
 * @csspart suffix - The suffix content container.
 * @csspart timeButton - The time dropdown toggle button.
 * @csspart portal - The portal container for the dropdown.
 * @csspart popup - The floating time picker container.
 * @csspart menu - The time selection menu.
 * @csspart timeSlot - Individual time slot items in the dropdown.
 *
 * @cssprop {String} --time-box-background-color - The background color.
 * @cssprop {String} --time-box-border-color - The border color.
 * @cssprop {String} --time-box-border-radius - The border radius.
 * @cssprop {String} --time-box-border-style - The border style.
 * @cssprop {String} --time-box-border-width - The border width.
 * @cssprop {String} --time-box-font-family - The font family.
 * @cssprop {String} --time-box-font-size - The font size.
 * @cssprop {String} --time-box-font-weight - The font weight.
 * @cssprop {String} --time-box-foreground-color - The foreground color.
 * @cssprop {String} --time-box-gap - The gap between elements.
 * @cssprop {String} --time-box-height - The height.
 * @cssprop {String} --time-box-padding-bottom - The padding bottom.
 * @cssprop {String} --time-box-padding-left - The padding left.
 * @cssprop {String} --time-box-padding-right - The padding right.
 * @cssprop {String} --time-box-padding-top - The padding top.
 * @cssprop {String} --time-box-shadow - The shadow.
 * @cssprop {String} --time-box-transition-duration - The transition duration.
 * @cssprop {String} --time-box-width - The width.
 *
 * @dependency mosaik-focus-ring - Used for focus indication.
 * @dependency mosaik-button - Used for the time dropdown button.
 * @dependency mosaik-portal - Used for dropdown positioning.
 * @dependency mosaik-floating - Used for dropdown positioning.
 * @dependency mosaik-menu - Used for time selection interface.
 * @dependency mosaik-menu-item - Used for individual time slots.
 *
 * @fires cleared - Fired when the value is cleared.
 *
 * @keyhandle UpArrow - Selects the previous time unit.
 * @keyhandle DownArrow - Selects the next time unit.
 *
 * @example
 * ```html
 * <mosaik-timebox
 *   label="Meeting Time"
 *   placeholder="Select time"
 *   min="09:00"
 *   max="17:00"
 *   step="15">
 * </mosaik-timebox>
 * ```
 *
 * @public
 */
let TimeBoxElement = TimeBoxElement_1 = class TimeBoxElement extends Themeable(Slottable(Clearable(Localeable(Disableable(Invalidable(Valueable(Variantable(Appearanceable(DropDownable(Labelable(InputBaseElement))))))))))) {
    // #region Fields
    _clickOutsideController;
    _keyboardController;
    _projectionController;
    _inputElement;
    _floatingElement;
    _interval;
    _value;
    _readonly;
    _required;
    _autofocus;
    _name;
    _placeholder;
    _autocomplete;
    _isEditable;
    _blackoutTimes;
    _specialTimes;
    _minTime;
    _maxTime;
    _markerHandler;
    _textAlign;
    // #endregion
    // #region Ctor
    /**
     * Constructs a new instance of the `TimeBoxElement` class.
     *
     * @public
     */
    constructor() {
        super();
        this._interval = 60;
        this._value = null;
        this._readonly = false;
        this._required = false;
        this._autofocus = false;
        this._name = '';
        this._placeholder = '';
        this._autocomplete = false;
        this._isEditable = false;
        this._blackoutTimes = [];
        this._specialTimes = [];
        this._minTime = null;
        this._maxTime = null;
        this._textAlign = TextAlignment.Left;
        this._markerHandler = (_item) => [];
        this._clickOutsideController = new ClickOutsideController(this, {
            ignored: () => [this._floatingElement],
            skipInitial: true,
            callback: () => this.close()
        });
        this._keyboardController = new KeyboardController(this, {});
        this._projectionController = new ProjectionController(this, {
            slotName: '',
            targetSelector: '[part="projection"]',
            projecting: (element) => {
                element.setAttribute(`${TimeBoxElement_1.is}-projection`, '');
            }
        });
    }
    // #endregion
    // #region Properties
    /**
     * Returns the `{@link is}` property.
     * The `{@link is}` property represents natural name of this element.
     *
     * @public
     * @static
     * @readonly
     */
    static get is() {
        return 'mosaik-timebox';
    }
    /**
     * Gets or sets the `value` property.
     *
     * @public
     * @override
     */
    get value() {
        return this._value;
    }
    set value(value) {
        if (!isValidValue(value)) {
            value = null;
        }
        if (this._value !== value) {
            this._value = value;
            this.requestUpdate('value');
        }
    }
    /**
     * Gets or sets the `readonly` property.
     *
     * @public
     * @attr
     */
    get readonly() {
        return this._readonly;
    }
    set readonly(value) {
        if (this._readonly !== value) {
            this._readonly = value;
            this.requestUpdate('readonly');
        }
    }
    /**
     * Gets or sets the `required` property.
     *
     * @public
     * @attr
     */
    get required() {
        return this._required;
    }
    set required(value) {
        if (this._required !== value) {
            this._required = value;
            this.requestUpdate('required');
        }
    }
    /**
     * Gets or sets the `autofocus` property.
     *
     * @public
     * @override
     */
    get autofocus() {
        return this._autofocus;
    }
    set autofocus(value) {
        if (this._autofocus !== value) {
            this._autofocus = value;
            this.requestUpdate('autofocus');
        }
    }
    /**
     * Gets or sets the `name` property.
     *
     * @public
     * @attr
     */
    get name() {
        return this._name;
    }
    set name(value) {
        if (this._name !== value) {
            this._name = value;
            this.requestUpdate('name');
        }
    }
    /**
     * Gets or sets the `placeholder` property.
     *
     * @public
     * @attr
     */
    get placeholder() {
        return this._placeholder;
    }
    set placeholder(value) {
        if (this._placeholder !== value) {
            this._placeholder = value;
            this.requestUpdate('placeholder');
        }
    }
    /**
     * Gets or sets the `autocomplete` property.
     *
     * @public
     * @attr
     */
    get autocomplete() {
        return this._autocomplete;
    }
    set autocomplete(value) {
        if (this._autocomplete !== value) {
            this._autocomplete = value;
            this.requestUpdate('autocomplete');
        }
    }
    /**
     * Gets or sets the `isEditable` property.
     *
     * @public
     * @attr
     */
    get isEditable() {
        return this._isEditable;
    }
    set isEditable(value) {
        if (this._isEditable !== value) {
            this._isEditable = value;
            this.requestUpdate('isEditable');
        }
    }
    /**
     * Gets or sets the `interval` property.
     *
     * @public
     * @attr
     */
    get interval() {
        return this._interval;
    }
    set interval(value) {
        if (this._interval !== value) {
            this._interval = value;
            this.requestUpdate('interval');
        }
    }
    /**
     * Gets or sets the `blackoutTimes` property.
     *
     * @public
     * @attr
     */
    get blackoutTimes() {
        return this._blackoutTimes;
    }
    set blackoutTimes(value) {
        if (this._blackoutTimes !== value) {
            this._blackoutTimes = value;
            this.requestUpdate('blackoutTimes');
        }
    }
    /**
     * Gets or sets the `specialTimes` property.
     *
     * @public
     * @attr
     */
    get specialTimes() {
        return this._specialTimes;
    }
    set specialTimes(value) {
        if (this._specialTimes !== value) {
            this._specialTimes = value;
            this.requestUpdate('specialTimes');
        }
    }
    /**
     * Gets or sets the `minTime` property.
     *
     * @public
     * @attr
     */
    get minTime() {
        return this._minTime;
    }
    set minTime(value) {
        if (this._minTime !== value) {
            this._minTime = value;
            this.requestUpdate('minTime');
        }
    }
    /**
     * Gets or sets the `maxTime` property.
     *
     * @public
     * @attr
     */
    get maxTime() {
        return this._maxTime;
    }
    set maxTime(value) {
        if (this._maxTime !== value) {
            this._maxTime = value;
            this.requestUpdate('maxTime');
        }
    }
    /**
     * Determines the text alignment of the component.
     *
     * @public
     * @attr
     */
    get textAlign() {
        return this._textAlign;
    }
    set textAlign(value) {
        if (this._textAlign !== value) {
            this._textAlign = value;
            this.requestUpdate('textAlign');
        }
    }
    /**
     * A handler that gets date and returns null or a tuple with circled marker data. See {@link TimeMarkerData}.
     *
     * @public
     * @attr
     */
    get markerHandler() {
        return this._markerHandler;
    }
    set markerHandler(value) {
        if (this._markerHandler !== value) {
            this._markerHandler = value;
            this.requestUpdate('markerHandler');
        }
    }
    /**
     * Determines whether the element has a prefix or not.
     * The Prefix is a slot that is displayed before the input.
     *
     * @private
     * @readonly
     * @attr
     */
    get hasPrefix() {
        return this.hasSlotContent('prefix');
    }
    /**
     * Determines whether the element has a suffix or not.
     * The Suffix is a slot that is displayed after the input.
     *
     * @private
     * @readonly
     * @attr
     */
    get hasSuffix() {
        return this.hasSlotContent('suffix');
    }
    // #endregion
    // #region Methods
    /**
     * @public
     * @override
     */
    connectedCallback() {
        super.connectedCallback();
        this.on('click', () => this.focus());
        this._keyboardController
            .add([Key.UpArrow], () => this.selectPrevious(), undefined, { preventDefault: true })
            .add([Key.DownArrow], () => this.selectNext(), undefined, { preventDefault: true })
            .add([Key.Space, Key.Enter], () => this.toggle(), undefined, { preventDefault: true })
            .add([Key.Escape], () => {
            if (this.isDropDownOpen) {
                this.close();
            }
            else {
                this.clear();
            }
        }, undefined, { preventDefault: true })
            .add([Key.Tab], () => this.close());
    }
    /**
     * Selects the next time span in the list.
     *
     * @public
     */
    selectNext() {
        const allItems = DomServiceLocator.current.findDescendants(this._floatingElement, MenuItemElement.is) ?? [];
        const currentIndex = allItems.findIndex((item) => ITimeSpan.equals(this.value, item.value));
        let nextValue = null;
        // if the current index is -1, it means that the value is not in the list
        // in this case, we select the first item
        if (currentIndex === -1) {
            nextValue = allItems.at(0)?.value;
        }
        else {
            nextValue = allItems.at(currentIndex + 1)?.value ?? allItems.at(0)?.value;
        }
        if (nextValue) {
            this.setTimeSpan(nextValue);
        }
    }
    /**
     * Selects the previous time span in the list.
     *
     * @public
     */
    selectPrevious() {
        const allItems = DomServiceLocator.current.findDescendants(this._floatingElement, MenuItemElement.is) ?? [];
        const currentIndex = allItems.findIndex((item) => ITimeSpan.equals(this.value, item.value));
        let nextValue = null;
        // if the current index is -1, it means that the value is not in the list
        // in this case, we select the first item
        if (currentIndex === -1) {
            nextValue = allItems.at(0)?.value;
        }
        else {
            nextValue = allItems.at(currentIndex - 1)?.value;
        }
        if (nextValue) {
            this.setTimeSpan(nextValue);
        }
    }
    /**
     * Sets focus on the input.
     *
     * @public
     * @override
     */
    focus() {
        if (this.shadowRoot) {
            DomServiceLocator.current.findDescendant(this.shadowRoot, 'input')?.focus();
        }
    }
    /**
     * Removes keyboard focus from the input.
     *
     * @public
     * @override
     */
    blur() {
        if (this.shadowRoot) {
            DomServiceLocator.current.findDescendant(this.shadowRoot, 'input')?.blur();
        }
    }
    /**
     * Clears the value of the element but not the validation.
     *
     * @public
     * @override
     */
    clear(force) {
        const isCleared = super.clear(force);
        if (isCleared) {
            this.emit('input', {
                bubbles: true,
                composed: true
            });
            this.emit('change', {
                bubbles: true,
                composed: true
            });
        }
        return isCleared;
    }
    /**
     * Resets the value, all kinds of validation and errors.
     *
     * @public
     * @override
     */
    reset() {
        super.reset();
        this.clear();
        this.invalid = false;
    }
    /**
     * Checks the validity of the element and returns `true` if it is valid; otherwise, `false`.
     *
     * @public
     * @override
     */
    checkValidity() {
        return this.shadowRoot
            ? this._inputElement.checkValidity()
            : true;
    }
    /**
     * @protected
     * @template
     */
    onChange(event) {
        this.value = ITimeSpan.parse(event.target.value, this.locale);
        this.emit('change', { detail: this.value });
    }
    /**
     * @protected
     * @template
     * @override
     */
    onInput(event) {
        super.onInput(event);
        this.value = ITimeSpan.parse(event.target.value, this.locale);
        this.emit('input', { detail: this.value });
    }
    /**
     * @protected
     * @template
     * @override
     */
    onFocus(event) {
        super.onFocus(event);
        this.emit('focus', { detail: event });
    }
    /**
     * @protected
     * @template
     * @override
     */
    onBlur(event) {
        super.onBlur(event);
        this.emit('blur', { detail: event });
    }
    /**
     * @protected
     * @template
     */
    onKeyDown(event) {
        // we need to override the default behavior of the HTMLInputElement
        if (event.key === KeyName.ArrowUp || event.key === KeyName.ArrowDown) {
            event.preventDefault();
            // delegate to the keyboard controller
            this._keyboardController.handle(event);
        }
    }
    /**
     * @private
     * @template
     */
    setTimeSpan(value) {
        this.value = value;
        this.emit('change', { detail: this.value });
        this.close();
    }
    /**
     * @protected
     * @override
     */
    onApplyTemplate() {
        super.onApplyTemplate();
        this._inputElement = this.getTemplatePart('input');
        this._floatingElement = this.getTemplatePart('popup');
    }
    /**
     * @protected
     */
    onIsDropDownOpenPropertyChanged(_prev, next) {
        if (next) {
            this._clickOutsideController.observe();
        }
        else {
            this._clickOutsideController.unobserve();
        }
    }
};
__decorate([
    Attribute({ type: Object }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [Object])
], TimeBoxElement.prototype, "value", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], TimeBoxElement.prototype, "readonly", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], TimeBoxElement.prototype, "required", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], TimeBoxElement.prototype, "autofocus", null);
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], TimeBoxElement.prototype, "name", null);
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], TimeBoxElement.prototype, "placeholder", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], TimeBoxElement.prototype, "autocomplete", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], TimeBoxElement.prototype, "isEditable", null);
__decorate([
    Attribute({ type: Number }),
    __metadata("design:type", Number),
    __metadata("design:paramtypes", [Number])
], TimeBoxElement.prototype, "interval", null);
__decorate([
    Attribute({ type: (Array) }),
    __metadata("design:type", Array),
    __metadata("design:paramtypes", [Array])
], TimeBoxElement.prototype, "blackoutTimes", null);
__decorate([
    Attribute({ type: (Array) }),
    __metadata("design:type", Array),
    __metadata("design:paramtypes", [Array])
], TimeBoxElement.prototype, "specialTimes", null);
__decorate([
    Attribute({ type: ITimeSpan }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [Object])
], TimeBoxElement.prototype, "minTime", null);
__decorate([
    Attribute({ type: ITimeSpan }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [Object])
], TimeBoxElement.prototype, "maxTime", null);
__decorate([
    Attribute({ type: TextAlignment }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], TimeBoxElement.prototype, "textAlign", null);
__decorate([
    Property({ type: Function }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Function])
], TimeBoxElement.prototype, "markerHandler", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [])
], TimeBoxElement.prototype, "hasPrefix", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [])
], TimeBoxElement.prototype, "hasSuffix", null);
__decorate([
    Watch('isDropDownOpen', { waitUntilFirstUpdate: true }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Boolean, Boolean]),
    __metadata("design:returntype", void 0)
], TimeBoxElement.prototype, "onIsDropDownOpenPropertyChanged", null);
TimeBoxElement = TimeBoxElement_1 = __decorate([
    Component({
        selector: 'mosaik-timebox',
        template: timeBoxElementTemplate,
        themes: {
            joy: timeBoxElementJoyStyle,
            retro: timeBoxElementRetroStyle,
            cosmopolitan: timeBoxElementCosmopolitanStyle
        },
        host: {
            tabIndex: '0'
        },
        options: {
            mode: 'open',
            delegatesFocus: true
        },
        imports: [
            ButtonElement,
            FocusRingElement,
            FloatingElement,
            MenuElement,
            MenuItemElement,
            PortalElement
        ]
    }),
    __metadata("design:paramtypes", [])
], TimeBoxElement);
export { TimeBoxElement };
/**
 * Checks if the provided value is valid for a input.
 * A valid value can be a ITimeSpan or null
 *
 * @private
 * @param value - The value to check.
 */
function isValidValue(value) {
    return ITimeSpan.isTimeSpan(value) || value === null;
}
//# sourceMappingURL=TimeBoxElement.js.map