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;
};
import { MelodicComponent } from '@melodicdev/core';
import { computePosition, autoUpdate, offset, flip, shift } from '../../../utils/positioning/index.js';
import { datePickerTemplate } from './date-picker.template.js';
import { datePickerStyles } from './date-picker.styles.js';
/**
 * ml-date-picker - Date input with calendar dropdown
 *
 * Users can type a date directly into the input or pick from the calendar popover.
 *
 * @example
 * ```html
 * <ml-date-picker label="Start date" value="2026-02-08"></ml-date-picker>
 * <ml-date-picker placeholder="Select date" min="2026-01-01" max="2026-12-31"></ml-date-picker>
 * ```
 *
 * @fires ml:change - Emitted when a date is selected. Detail: { value: string }
 */
let DatePickerComponent = class DatePickerComponent {
    constructor() {
        /** Selected date in ISO format (YYYY-MM-DD) */
        this.value = '';
        /** Placeholder text */
        this.placeholder = 'Select date';
        /** Field label */
        this.label = '';
        /** Hint text */
        this.hint = '';
        /** Error message */
        this.error = '';
        /** Input size */
        this.size = 'md';
        /** Disabled state */
        this.disabled = false;
        /** Required state */
        this.required = false;
        /** Minimum selectable date (YYYY-MM-DD) */
        this.min = '';
        /** Maximum selectable date (YYYY-MM-DD) */
        this.max = '';
        /** Whether the calendar popover is open */
        this.isOpen = false;
        this._cleanupAutoUpdate = null;
        this.toggleCalendar = () => {
            if (this.disabled)
                return;
            const popoverEl = this.getPopoverEl();
            if (popoverEl) {
                popoverEl.togglePopover();
            }
        };
        /** Called when the user types a date into the input */
        this.handleInput = (event) => {
            const input = event.target;
            this.commitValue(input.value);
        };
        /** Clicking the input opens the calendar */
        this.handleInputClick = () => {
            if (!this.isOpen) {
                this.toggleCalendar();
            }
        };
        /** Called when a day is clicked in the calendar - selects immediately and closes */
        this.handleDateSelect = (event) => {
            event.stopPropagation();
            const detail = event.detail;
            this.commitValue(detail.value);
            this.closePopover();
        };
        this.handleKeyDown = (event) => {
            if (event.key === 'Escape' && this.isOpen) {
                event.preventDefault();
                this.closePopover();
            }
            // Prevent Space from triggering the native date picker
            if (event.key === ' ') {
                event.preventDefault();
                if (!this.isOpen) {
                    this.toggleCalendar();
                }
            }
            // Prevent F4 / Alt+Down from triggering the native picker in some browsers
            if (event.key === 'F4' || (event.altKey && event.key === 'ArrowDown')) {
                event.preventDefault();
                if (!this.isOpen) {
                    this.toggleCalendar();
                }
            }
        };
        this._handleToggle = (event) => {
            const toggleEvent = event;
            if (toggleEvent.newState === 'open') {
                this.isOpen = true;
                this.startPositioning();
            }
            else {
                this.isOpen = false;
                this._cleanupAutoUpdate?.();
                this._cleanupAutoUpdate = null;
                this.returnFocus();
            }
        };
    }
    onCreate() {
        const popoverEl = this.getPopoverEl();
        if (popoverEl) {
            popoverEl.addEventListener('toggle', this._handleToggle);
        }
    }
    onDestroy() {
        this._cleanupAutoUpdate?.();
        const popoverEl = this.getPopoverEl();
        if (popoverEl) {
            popoverEl.removeEventListener('toggle', this._handleToggle);
        }
    }
    commitValue(iso) {
        this.value = iso;
        this.elementRef.dispatchEvent(new CustomEvent('ml:change', {
            bubbles: true,
            composed: true,
            detail: { value: iso }
        }));
    }
    closePopover() {
        const popoverEl = this.getPopoverEl();
        if (popoverEl && this.isOpen) {
            popoverEl.hidePopover();
        }
    }
    startPositioning() {
        const triggerEl = this.getTriggerEl();
        const popoverEl = this.getPopoverEl();
        if (!triggerEl || !popoverEl)
            return;
        const update = () => this.updatePosition(triggerEl, popoverEl);
        this._cleanupAutoUpdate?.();
        this._cleanupAutoUpdate = autoUpdate(triggerEl, popoverEl, update);
    }
    updatePosition(triggerEl, popoverEl) {
        const middleware = [offset(4), flip(), shift({ padding: 8 })];
        const { x, y } = computePosition(triggerEl, popoverEl, {
            placement: 'bottom-start',
            middleware
        });
        popoverEl.style.left = `${x}px`;
        popoverEl.style.top = `${y}px`;
    }
    returnFocus() {
        const inputEl = this.getInputEl();
        if (inputEl) {
            inputEl.focus();
        }
    }
    getInputEl() {
        return this.elementRef.shadowRoot?.querySelector('.ml-date-picker__input');
    }
    getTriggerEl() {
        return this.elementRef.shadowRoot?.querySelector('.ml-date-picker__trigger');
    }
    getPopoverEl() {
        return this.elementRef.shadowRoot?.querySelector('.ml-date-picker__popover');
    }
};
DatePickerComponent = __decorate([
    MelodicComponent({
        selector: 'ml-date-picker',
        template: datePickerTemplate,
        styles: datePickerStyles,
        attributes: ['value', 'placeholder', 'label', 'hint', 'error', 'size', 'disabled', 'required', 'min', 'max']
    })
], DatePickerComponent);
export { DatePickerComponent };
