/*!
 * 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 FormDatePicker {
    constructor() {
        this.language = 'en';
        this.firstDayOfWeek = 0; // 0=Sun, 1=Mon, 6=Sat
        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.selectDate = (year, month, day) => {
            this.selectedValue = this.toDateString(year, month, day);
            this.isOpen = false;
        };
        this.prevMonth = () => {
            if (!this.canGoPrev())
                return;
            if (this.viewMonth === 0) {
                this.viewMonth = 11;
                this.viewYear--;
            }
            else {
                this.viewMonth--;
            }
        };
        this.nextMonth = () => {
            if (!this.canGoNext())
                return;
            if (this.viewMonth === 11) {
                this.viewMonth = 0;
                this.viewYear++;
            }
            else {
                this.viewMonth++;
            }
        };
    }
    async componentWillLoad() {
        this.form.subscribe(this.name, this);
        if (this.staticValue)
            this.defaultValue = this.staticValue;
        if (this.defaultValue)
            this.selectedValue = this.defaultValue;
        const initDate = this.selectedValue ? new Date(this.selectedValue + 'T00:00:00') : new Date();
        this.viewYear = initDate.getFullYear();
        this.viewMonth = initDate.getMonth();
    }
    async onStaticValueChange(newStaticValue) {
        if (newStaticValue) {
            this.selectedValue = newStaticValue;
            const date = new Date(newStaticValue + 'T00:00:00');
            this.viewYear = date.getFullYear();
            this.viewMonth = date.getMonth();
        }
    }
    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 || '';
        if (this.selectedValue) {
            const date = new Date(this.selectedValue + 'T00:00:00');
            this.viewYear = date.getFullYear();
            this.viewMonth = date.getMonth();
        }
    }
    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 < 320;
            setTimeout(() => {
                this.isOpen = true;
            }, 10);
        });
    }
    // Date utilities
    toDateString(year, month, day) {
        return `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
    }
    isDateDisabled(year, month, day) {
        const dateStr = this.toDateString(year, month, day);
        if (this.minDate && dateStr < this.minDate)
            return true;
        if (this.maxDate && dateStr > this.maxDate)
            return true;
        if (this.disabledDates)
            return this.disabledDates(new Date(year, month, day));
        return false;
    }
    getCalendarDays() {
        const year = this.viewYear;
        const month = this.viewMonth;
        const firstDayOfMonth = new Date(year, month, 1).getDay();
        const daysInMonth = new Date(year, month + 1, 0).getDate();
        const daysInPrevMonth = new Date(year, month, 0).getDate();
        const leadingDays = (firstDayOfMonth - this.firstDayOfWeek + 7) % 7;
        const days = [];
        for (let i = leadingDays - 1; i >= 0; i--) {
            const prevMonth = month === 0 ? 11 : month - 1;
            const prevYear = month === 0 ? year - 1 : year;
            days.push({ day: daysInPrevMonth - i, month: prevMonth, year: prevYear, isCurrentMonth: false });
        }
        for (let i = 1; i <= daysInMonth; i++) {
            days.push({ day: i, month, year, isCurrentMonth: true });
        }
        const remaining = 42 - days.length;
        for (let i = 1; i <= remaining; i++) {
            const nextMonth = month === 11 ? 0 : month + 1;
            const nextYear = month === 11 ? year + 1 : year;
            days.push({ day: i, month: nextMonth, year: nextYear, isCurrentMonth: false });
        }
        return days;
    }
    getWeekDayNames() {
        const names = [];
        const baseDate = new Date(2024, 0, 7); // known Sunday
        for (let i = 0; i < 7; i++) {
            const d = new Date(baseDate);
            d.setDate(d.getDate() + ((this.firstDayOfWeek + i) % 7));
            names.push(new Intl.DateTimeFormat(this.language, { weekday: 'short' }).format(d));
        }
        return names;
    }
    getMonthYearTitle() {
        return new Intl.DateTimeFormat(this.language, { month: 'long', year: 'numeric' }).format(new Date(this.viewYear, this.viewMonth));
    }
    formatDisplayValue() {
        if (!this.selectedValue)
            return '';
        try {
            return new Intl.DateTimeFormat(this.language, { year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date(this.selectedValue + 'T00:00:00'));
        }
        catch (_a) {
            return this.selectedValue;
        }
    }
    canGoPrev() {
        if (!this.minDate)
            return true;
        const [minYear, minMonth] = this.minDate.split('-').map(Number);
        return this.viewYear > minYear || (this.viewYear === minYear && this.viewMonth > minMonth - 1);
    }
    canGoNext() {
        if (!this.maxDate)
            return true;
        const [maxYear, maxMonth] = this.maxDate.split('-').map(Number);
        return this.viewYear < maxYear || (this.viewYear === maxYear && this.viewMonth < maxMonth - 1);
    }
    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 displayValue = this.formatDisplayValue();
        const weekDays = this.getWeekDayNames();
        const days = this.getCalendarDays();
        const monthTitle = this.getMonthYearTitle();
        const now = new Date();
        const todayStr = this.toDateString(now.getFullYear(), now.getMonth(), now.getDate());
        return (h(Host, { key: 'e811e634de3eed62d2698801155e35ba1931da08', translate: "no" }, h("label", { key: 'b86713c4df81667f88491d0d75fdcaf7678a54b7', part: this.name, id: this.wrapperId, class: cn('form-input-label-container', this.wrapperClass, { disabled: isDisabled }) }, h(FormInputLabel, { key: '390f67f93ea40bf8a7a93f7cf145a9a3c3cb2779', isRequired: isRequired, label: label }), h("form-shadow-input", { key: '2a553cf2afb044343a5e09110dd3ed51d1d60c76', name: this.name, form: this.form, value: this.selectedValue }), h("div", { key: '03e0a20db6467054a7780e20ed5600621b2d7835', part: `${this.name}-container form-input-container`, class: cn('form-input-container', { open: this.isOpen }) }, h("input", { key: 'f4680aea436783cd8ca208f33e83cd66ef876108', type: "text", readOnly: true, disabled: isDisabled, value: displayValue, 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: 'fe42f5122bd86b3078f7945524875e3115416eb5', part: `${this.name}-icon form-date-picker-icon`, class: "form-input-icon form-input-icon-end" }, h("svg", { key: 'c1ecd094c0219b9c3305d87406e5a1272165043a', "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("path", { key: 'c84a008419ea45e635ad23f5701cf1008199c923', d: "M8 2v4" }), h("path", { key: '31e1f6bd24e782c102cef9a8a525c86e6152bc0d', d: "M16 2v4" }), h("rect", { key: 'd0bd1360ac7a9a8af7343a07f3c56accd8ab64bd', width: "18", height: "18", x: "3", y: "4", rx: "2" }), h("path", { key: 'ed5b60fd32306df4f68d3016e4bf682f6dc5e7c6', d: "M3 10h18" }))), h("div", { key: '533fba9778259abfc4d23d008376e2481ed3ef67', part: `${this.name}-dropdown form-date-picker-dropdown`, class: cn('form-picker-dropdown', {
                upwards: this.openUpwards,
                downwards: !this.openUpwards,
            }) }, h("div", { key: '67a4662f4fbe34a7cebc69ba0e17b91ab9296141', class: "form-date-picker-header" }, h("button", { key: 'e513d634e51e7f55af19fd6669d4c8f66f72a2b7', type: "button", disabled: !this.canGoPrev(), part: `${this.name}-prev form-date-picker-nav`, onClick: this.prevMonth, class: "form-date-picker-nav" }, h("svg", { key: '92a25d2edb944f5db7c70ca74f3ca1c32f7fcde7', "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-4 rtl:rotate-180" }, h("path", { key: '49d65ef06356aa43af0d12333f615a4026a4bf88', d: "m15 18-6-6 6-6" }))), h("span", { key: '0f1abc512ffc2e7da3b484829be7c8dac677110e', part: `${this.name}-title form-date-picker-title`, class: "form-date-picker-title" }, monthTitle), h("button", { key: 'e79e405e94f2d5ac1706beb47475ac440c8811ac', type: "button", disabled: !this.canGoNext(), part: `${this.name}-next form-date-picker-nav`, onClick: this.nextMonth, class: "form-date-picker-nav" }, h("svg", { key: '0fc7a03e8aca1cbffbf7eed81442ceb747a04a1d', "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-4 rtl:rotate-180" }, h("path", { key: 'a70b240cb7ccc6906e324e95aa5c1ca8ebe53fd4', d: "m9 18 6-6-6-6" })))), h("div", { key: '2db84e741c4dd519dd914e17c1b5176a46d092f0', class: "form-date-picker-grid" }, weekDays.map(day => (h("div", { class: "form-date-picker-weekday" }, day))), days.map(cell => {
            const dateStr = this.toDateString(cell.year, cell.month, cell.day);
            const isSelected = dateStr === this.selectedValue;
            const isToday = dateStr === todayStr;
            const dateDisabled = !cell.isCurrentMonth || this.isDateDisabled(cell.year, cell.month, cell.day);
            return (h("button", { type: "button", disabled: dateDisabled, onClick: () => this.selectDate(cell.year, cell.month, cell.day), part: cn('form-date-picker-day', { 'form-date-picker-day-selected': isSelected, 'form-date-picker-day-today': isToday }), class: cn('form-date-picker-day', {
                    selected: isSelected,
                    today: isToday && !isSelected,
                    outside: !cell.isCurrentMonth,
                }) }, cell.day));
        })))), h(FormErrorMessage, { key: '99223f511804a9316e2662b1a656105f73d27ec4', name: this.name, isError: isError, errorMessage: locale[errorMessage] || errorMessage }))));
    }
    static get is() { return "form-date-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
            },
            "language": {
                "type": "string",
                "attribute": "language",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "'en'"
            },
            "minDate": {
                "type": "string",
                "attribute": "min-date",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "maxDate": {
                "type": "string",
                "attribute": "max-date",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "disabledDates": {
                "type": "unknown",
                "attribute": "disabled-dates",
                "mutable": false,
                "complexType": {
                    "original": "(date: Date) => boolean",
                    "resolved": "(date: Date) => boolean",
                    "references": {
                        "Date": {
                            "location": "global",
                            "id": "global::Date"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "firstDayOfWeek": {
                "type": "number",
                "attribute": "first-day-of-week",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "0"
            }
        };
    }
    static get states() {
        return {
            "isOpen": {},
            "selectedValue": {},
            "viewYear": {},
            "viewMonth": {},
            "openUpwards": {}
        };
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "staticValue",
                "methodName": "onStaticValueChange"
            }];
    }
}
