/*!
 * Built by ShiftSoftware
 * Copyright (c)
 */
import { Host, h } from "@stencil/core";
import cn from "../../global/lib/cn";
import { getNestedValue } from "../../global/lib/get-nested-value";
import { FormInputLabel } from "./components/form-input-label";
import { FormErrorMessage } from "./components/form-error-message";
export class FormTimePicker {
    constructor() {
        this.minuteStep = 1;
        this.isOpen = false;
        this.selectedValue = '';
        this.openUpwards = false;
        this.handleOutsideClick = (event) => {
            if (!this.el.contains(event.target))
                this.isOpen = false;
        };
        this.handleKeyDown = (event) => {
            if (event.key === 'Escape' && this.isOpen)
                this.isOpen = false;
        };
        this.toggleDropdown = () => {
            if (this.isOpen) {
                this.isOpen = false;
                return;
            }
            this.adjustDropdownPosition();
        };
        this.selectHour = (hour) => {
            const currentMinute = this.getSelectedMinute();
            const minute = currentMinute >= 0 ? currentMinute : 0;
            this.selectedValue = this.formatTime(hour, minute);
        };
        this.selectMinute = (minute) => {
            const currentHour = this.getSelectedHour();
            const hour = currentHour >= 0 ? currentHour : 0;
            this.selectedValue = this.formatTime(hour, minute);
        };
    }
    async componentWillLoad() {
        this.form.subscribe(this.name, this);
        if (this.staticValue)
            this.defaultValue = this.staticValue;
        if (this.defaultValue)
            this.selectedValue = this.defaultValue;
    }
    async onStaticValueChange(newStaticValue) {
        if (newStaticValue)
            this.selectedValue = newStaticValue;
    }
    async componentDidLoad() {
        document.addEventListener('click', this.handleOutsideClick);
        document.addEventListener('keydown', this.handleKeyDown);
    }
    async disconnectedCallback() {
        this.form.unsubscribe(this.name);
        document.removeEventListener('click', this.handleOutsideClick);
        document.removeEventListener('keydown', this.handleKeyDown);
    }
    reset(newValue) {
        this.selectedValue = newValue || this.defaultValue || '';
    }
    adjustDropdownPosition() {
        requestAnimationFrame(() => {
            const input = this.el.querySelector('.form-input-style');
            if (!input)
                return;
            const rect = input.getBoundingClientRect();
            const spaceBelow = window.innerHeight - rect.bottom - 20;
            this.openUpwards = spaceBelow < 220;
            setTimeout(() => {
                this.isOpen = true;
                this.scrollToSelected();
            }, 10);
        });
    }
    scrollToSelected() {
        requestAnimationFrame(() => {
            const hourCol = this.el.querySelector('.form-time-picker-hours');
            const minuteCol = this.el.querySelector('.form-time-picker-minutes');
            const scrollTo = (container) => {
                const selected = container === null || container === void 0 ? void 0 : container.querySelector('.selected');
                if (selected)
                    selected.scrollIntoView({ block: 'center' });
            };
            scrollTo(hourCol);
            scrollTo(minuteCol);
        });
    }
    toTimeMinutes(time) {
        const [h, m] = time.split(':').map(Number);
        return h * 60 + m;
    }
    isHourDisabled(hour) {
        const step = this.minuteStep || 1;
        for (let m = 0; m < 60; m += step) {
            if (!this.isMinuteDisabled(hour, m))
                return false;
        }
        return true;
    }
    isMinuteDisabled(hour, minute) {
        const time = hour * 60 + minute;
        if (this.minTime && time < this.toTimeMinutes(this.minTime))
            return true;
        if (this.maxTime && time > this.toTimeMinutes(this.maxTime))
            return true;
        return false;
    }
    getSelectedHour() {
        if (!this.selectedValue)
            return -1;
        return parseInt(this.selectedValue.split(':')[0], 10);
    }
    getSelectedMinute() {
        if (!this.selectedValue)
            return -1;
        return parseInt(this.selectedValue.split(':')[1], 10);
    }
    formatTime(hour, minute) {
        return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`;
    }
    render() {
        const { disabled, isRequired, meta, isError, errorMessage } = this.form.getInputState(this.name);
        const [locale] = this.form.getFormLocale();
        const label = getNestedValue(locale, meta === null || meta === void 0 ? void 0 : meta.label) || (meta === null || meta === void 0 ? void 0 : meta.label);
        const placeholder = getNestedValue(locale, meta === null || meta === void 0 ? void 0 : meta.placeholder);
        const isDisabled = disabled || this.isLoading || !!this.staticValue || this.isDisabled;
        const selectedHour = this.getSelectedHour();
        const selectedMinute = this.getSelectedMinute();
        const step = this.minuteStep || 1;
        const hours = Array.from({ length: 24 }, (_, i) => i);
        const minutes = Array.from({ length: Math.ceil(60 / step) }, (_, i) => i * step);
        return (h(Host, { key: '6b3a4ea826ea0c84e04eed20a704e5c0e813337e', translate: "no" }, h("label", { key: '67478c3f4a8850b2f158c0f770f053c50133709e', part: this.name, id: this.wrapperId, class: cn('form-input-label-container', this.wrapperClass, { disabled: isDisabled }) }, h(FormInputLabel, { key: 'c2a3741a553e7118fe8e5fb9a30481548cc8045b', isRequired: isRequired, label: label }), h("form-shadow-input", { key: '5f1240804457073623742b5ae2893bfd536da938', name: this.name, form: this.form, value: this.selectedValue }), h("div", { key: '810e033f8d55d629d5db213a75768ebd2e4ba140', part: `${this.name}-container form-input-container`, class: cn('form-input-container', { open: this.isOpen }) }, h("input", { key: 'b6bb8e7ddb91bbb18a28b32567e91efebd91f811', type: "text", readOnly: true, disabled: isDisabled, value: this.selectedValue, onClick: this.toggleDropdown, part: `${this.name}-input form-input`, placeholder: placeholder || (meta === null || meta === void 0 ? void 0 : meta.placeholder), class: cn('form-input-style form-input-select', {
                'form-input-error-style': isError,
            }) }), h("span", { key: 'eda7df336d3c2b60bea46e8671c0fd14a437d68a', part: `${this.name}-icon form-time-picker-icon`, class: "form-input-icon form-input-icon-end" }, h("svg", { key: '873d52be7e89d0d2ef944eff7c210784fded869e', "aria-hidden": "true", xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", "stroke-linejoin": "round", class: "size-full" }, h("circle", { key: '68a33fbc9d8288752fb7b696c4d6ffb56e1153d3', cx: "12", cy: "12", r: "10" }), h("polyline", { key: 'f691539787b34df56c11f0b743fd30dcee957686', points: "12 6 12 12 16 14" }))), h("div", { key: 'f9f396e03a42d43b6f2548342108b2b8530f2518', part: `${this.name}-dropdown form-time-picker-dropdown`, class: cn('form-picker-dropdown', {
                upwards: this.openUpwards,
                downwards: !this.openUpwards,
            }) }, h("div", { key: '86ea6167273f4fed989bf5972831e21166728034', class: "form-time-picker-columns" }, h("div", { key: '7e14aa8e8c971986a11ed3013bff82e5d9523e35', class: "form-time-picker-column form-time-picker-hours" }, h("div", { key: '5d6e8fbb8f0a33f4a6b5b78c8deb9c3274d74886', class: "form-time-picker-column-header" }, "HH"), hours.map(hour => {
            const hourDisabled = this.isHourDisabled(hour);
            return (h("button", { type: "button", disabled: hourDisabled, onClick: () => this.selectHour(hour), part: cn('form-time-picker-option', { 'form-time-picker-option-selected': hour === selectedHour }), class: cn('form-time-picker-option', {
                    selected: hour === selectedHour,
                }) }, String(hour).padStart(2, '0')));
        })), h("div", { key: 'f99b2fcad347ba0c9ecc160d9f0bbd92f4d55e2c', class: "form-time-picker-column form-time-picker-minutes" }, h("div", { key: '74f10fe998a94e1c78cb9a53eed1fdcff525acdf', class: "form-time-picker-column-header" }, "MM"), minutes.map(minute => {
            const minuteDisabled = selectedHour >= 0 ? this.isMinuteDisabled(selectedHour, minute) : false;
            return (h("button", { type: "button", disabled: minuteDisabled, onClick: () => this.selectMinute(minute), part: cn('form-time-picker-option', { 'form-time-picker-option-selected': minute === selectedMinute }), class: cn('form-time-picker-option', {
                    selected: minute === selectedMinute,
                }) }, String(minute).padStart(2, '0')));
        }))))), h(FormErrorMessage, { key: 'f0ef64a81ca5bae6f994dda778c2afbe6b3d19ea', name: this.name, isError: isError, errorMessage: locale[errorMessage] || errorMessage }))));
    }
    static get is() { return "form-time-picker"; }
    static get originalStyleUrls() {
        return {
            "$": ["form-inputs.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["form-inputs.css"]
        };
    }
    static get properties() {
        return {
            "name": {
                "type": "string",
                "attribute": "name",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "wrapperId": {
                "type": "string",
                "attribute": "wrapper-id",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "isLoading": {
                "type": "boolean",
                "attribute": "is-loading",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "isDisabled": {
                "type": "boolean",
                "attribute": "is-disabled",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "form": {
                "type": "unknown",
                "attribute": "form",
                "mutable": false,
                "complexType": {
                    "original": "FormHook<any>",
                    "resolved": "FormHook<any>",
                    "references": {
                        "FormHook": {
                            "location": "import",
                            "path": "~features/form-hook/form-hook",
                            "id": "src/features/form-hook/form-hook.ts::FormHook"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "wrapperClass": {
                "type": "string",
                "attribute": "wrapper-class",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "staticValue": {
                "type": "string",
                "attribute": "static-value",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "defaultValue": {
                "type": "string",
                "attribute": "default-value",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "minTime": {
                "type": "string",
                "attribute": "min-time",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "maxTime": {
                "type": "string",
                "attribute": "max-time",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "minuteStep": {
                "type": "number",
                "attribute": "minute-step",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "1"
            }
        };
    }
    static get states() {
        return {
            "isOpen": {},
            "selectedValue": {},
            "openUpwards": {}
        };
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "staticValue",
                "methodName": "onStaticValueChange"
            }];
    }
}
