import { h, proxyCustomElement, HTMLElement, createEvent, Host } from '@stencil/core/internal/client';
import { _ as __decorate, a as __metadata } from './tslib.es6.js';
import { B as BEM } from './bem.js';
import { b as waitAfterFramePaint } from './helpers.js';
import { L as Logger } from './log.js';
import { p as padStart } from './index3.js';
import { i as isNil } from './index2.js';
import { B as BalDate } from './date.js';
import { i as i18nBalDate } from './bal-date.i18n.js';
import { d as defineCustomElement$2 } from './bal-date-calendar-cell2.js';
import { d as defineCustomElement$1 } from './bal-icon2.js';
import { d as defaultConfig } from './config.default.js';
import { L as ListenToConfig } from './config.decorator.js';
import { L as ListenToSwipe } from './swipe.decorator.js';

// Function to get the number of days in a month
function getDaysInMonth(year, month) {
    if (month < 1 || year < 0) {
        return undefined;
    }
    return new Date(year, month, 0).getDate();
}
function isoDateOfDay(day, month, year) {
    return `${year}-${padStart(`${month}`, 2, '0')}-${padStart(`${day}`, 2, '0')}`;
}
function isoDateOfToday() {
    const today = new Date();
    return `${today.getFullYear()}-${padStart(`${today.getMonth() + 1}`, 2, '0')}-${padStart(`${today.getDate()}`, 2, '0')}`;
}
// Function to generate the calendar grid
function generateCalendarGrid(year, month, min, max, allowedDates) {
    // Create an empty grid array
    const grid = [];
    // Get the number of days in the month
    const numDays = getDaysInMonth(year, month);
    const firstDay = getFirstDayOfMonth(year, month);
    if (numDays !== undefined && firstDay) {
        // Create a new Date object for the first day of the month
        const isoToday = isoDateOfToday();
        const dateMin = BalDate.fromISO(min);
        const dateMax = BalDate.fromISO(max);
        const allowedDate = (isoDate) => {
            if (isNil(allowedDates)) {
                return false;
            }
            return !allowedDates(isoDate);
        };
        // Fill the grid with day numbers
        for (let day = 1; day <= numDays; day++) {
            const isoDate = isoDateOfDay(day, month, year);
            grid.push({
                day,
                month,
                year,
                isoDate,
                fullDate: BalDate.fromISO(isoDate).toFormat(),
                today: isoToday === isoDate,
                disabled: dateMin.isAfter(isoDate) || dateMax.isBefore(isoDate) || allowedDate(isoDate),
            });
        }
    }
    return grid;
}
// Function to get the first weekday of the month
function getFirstWeekdayOfMonth(year, month) {
    if (month < 1 || year < 0) {
        return 1;
    }
    // Create a new Date object with the given year and month
    const date = new Date(year, month - 1, 1);
    // Get the weekday of the first day of the month (0 - Sunday, 1 - Monday, ..., 6 - Saturday)
    const weekday = date.getDay();
    return weekday === 0 ? 7 : weekday;
}
function validateLanguage(language) {
    if (['en', 'de', 'fr', 'it', 'nl', 'es', 'pl', 'pt', 'sv', 'fi'].includes(language)) {
        return language;
    }
    return 'de';
}
// Function to generate the year list for the selection
function generateYears(currentYear, minYear, maxYear) {
    const list = [];
    const today = new Date();
    const todayYear = today.getFullYear();
    for (let year = minYear; year <= maxYear; year++) {
        list.push({
            value: year,
            label: `${year}`,
            disabled: false,
            today: todayYear === year,
            selected: currentYear === year,
        });
    }
    return list;
}
// Function to generate the month list for the selection
function generateMonths(language, currentYear, selectedDate, min, max) {
    const locale = validateLanguage(language);
    const months = BalDate.infoMonths({ format: 'long', locale });
    const selected = BalDate.fromISO(selectedDate);
    const today = new Date();
    const todayYear = today.getFullYear();
    const todayMonth = today.getMonth() + 1;
    let minMonth = 0;
    if (min && currentYear !== undefined) {
        const minDate = BalDate.fromISO(min);
        if (minDate.isValid) {
            if (currentYear > minDate.year) {
                minMonth = 0; // all months are allowed
            }
            else {
                minMonth = minDate.month || minMonth;
            }
        }
    }
    let maxMonth = 12;
    if (max && currentYear !== undefined) {
        const maxDate = BalDate.fromISO(max);
        if (maxDate.isValid) {
            if (currentYear < maxDate.year) {
                maxMonth = 12; // all months are allowed
            }
            else {
                maxMonth = maxDate.month || maxMonth;
            }
        }
    }
    return months.map((label, index) => {
        const value = index + 1;
        return {
            label,
            value,
            today: value === todayMonth && currentYear === todayYear,
            selected: value === selected.month && currentYear === selected.year,
            disabled: value < minMonth || value > maxMonth,
        };
    });
}
// Function to generate the weekday header row with the label and the content
function generateWeekDays(language) {
    const locale = validateLanguage(language);
    const weekdaysMin = BalDate.infoWeekdays({ format: 'short', locale });
    const weekdays = BalDate.infoWeekdays({ format: 'long', locale });
    return weekdaysMin.map((weekdayMin, index) => ({
        ariaLabel: weekdays[index],
        textContent: weekdayMin,
    }));
}
function getFirstDayOfMonth(year, month) {
    if (month < 1 || month > 12 || year < 0) {
        return undefined;
    }
    return new Date(year, month - 1, 1);
}

const CalendarGrid = ({ isVisible, ref, grid, weekdays, selectedDate, firstDayOfWeek, onSelectDay, }) => {
    const block = BEM.block('date-calendar');
    const blockBody = block.element('body');
    const blockBodyGrid = blockBody.element('grid');
    return (h("div", { role: "grid", class: Object.assign(Object.assign({}, blockBodyGrid.class()), blockBodyGrid.modifier('visible').class(isVisible)), "aria-hidden": isVisible ? 'false' : 'true', ref: el => ref(el) }, h("div", { role: "row", class: Object.assign({}, blockBodyGrid.element('head').class()) }, weekdays.map(weekday => (h("span", { key: weekday.textContent, role: "columnheader", "aria-label": weekday.ariaLabel, title: weekday.ariaLabel }, weekday.textContent)))), h("div", { role: "row", class: Object.assign({}, blockBodyGrid.element('body').class()), style: { '--bal-date-first-week-day': `${firstDayOfWeek}` } }, grid.map(cell => (h("bal-date-calendar-cell", Object.assign({ key: cell.isoDate }, cell, { selected: cell.isoDate === selectedDate, onBalSelectDay: ({ detail }) => onSelectDay(detail) })))))));
};

const CalendarList = ({ name, isVisible, girdHeight, list, onSelect, ref, }) => {
    const block = BEM.block('date-calendar');
    const blockBody = block.element('body');
    const blockBodyList = blockBody.element('list');
    return (h("ul", { class: Object.assign(Object.assign(Object.assign({}, blockBodyList.class()), blockBodyList.modifier(name).class()), blockBodyList.modifier('visible').class(isVisible)), "aria-hidden": isVisible ? 'false' : 'true', style: {
            height: `${girdHeight - 2 - 8 - 8}px`,
        }, ref: el => (ref ? ref(el) : undefined) }, list.map(item => (h("li", { key: item.value, id: `${name}-${item.value}` }, h("button", { class: Object.assign(Object.assign(Object.assign(Object.assign({}, blockBodyList.element('item').class()), blockBodyList.element('item').modifier('today').class(item.today)), blockBodyList.element('item').modifier('selected').class(item.selected)), blockBodyList.element('item').modifier('disabled').class(item.disabled)), disabled: item.disabled, tabIndex: -1, onClick: () => {
            if (!item.disabled) {
                onSelect(item);
            }
        } }, item.label))))));
};

const CalendarNav = ({ language, onClickSelectMonthAndYear, monthFullNames, month, year, isCalendarVisible, isListVisible, onClickPreviousMonth, onClickNextMonth, }) => {
    const block = BEM.block('date-calendar');
    const blockNav = block.element('nav');
    const nextMonthLabel = i18nBalDate[language].nextMonth;
    const previousMonthLabel = i18nBalDate[language].previousMonth;
    const selectMonthLabel = i18nBalDate[language].selectMonth;
    return (h("div", { class: Object.assign({}, blockNav.class()) }, h("div", { class: Object.assign({}, blockNav.modifier('start').class()) }, h("button", { title: selectMonthLabel, "aria-label": selectMonthLabel, tabIndex: -1, "data-testid": "change-year-month", onClick: onClickSelectMonthAndYear }, h("span", null, monthFullNames[month - 1], " ", year), h("bal-icon", { name: "caret-up", color: "primary", size: "small", turn: isCalendarVisible }))), h("div", { class: Object.assign({}, blockNav.modifier('end').class()), style: {
            display: isListVisible ? 'none' : 'flex',
        } }, h("button", { title: previousMonthLabel, "aria-label": previousMonthLabel, onClick: onClickPreviousMonth, tabIndex: -1, "data-testid": "previous-month" }, h("bal-icon", { name: "caret-left", color: "primary", size: "small" })), h("button", { title: nextMonthLabel, "aria-label": nextMonthLabel, onClick: onClickNextMonth, tabIndex: -1, "data-testid": "next-month" }, h("bal-icon", { name: "caret-right", color: "primary", size: "small" })))));
};

const balDateCalendarCss = ":host{--bal-date-first-week-day:0;--bal-date-calendar-button-background:transparent;--bal-date-calendar-button-background-hover:var(--bal-color-light-blue-1);--bal-date-calendar-button-background-active:var(--bal-color-light-blue-2);--bal-date-calendar-button-color:var(--bal-color-text-primary);--bal-date-calendar-button-today-color:var(--bal-color-light-blue-3);--bal-date-calendar-button-today-color-hover:var(--bal-color-text-primary);--bal-date-calendar-button-today-color-active:var(--bal-color-text-primary);--bal-date-calendar-button-selected-background:var(--bal-color-primary);--bal-date-calendar-button-selected-color:var(--bal-color-text-white)}:host{-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;display:inline-block;background:var(--bal-color-white);border-radius:var(--bal-radius-normal)}.bal-date-calendar__nav{display:-ms-flexbox;display:flex;width:calc(100% - 1rem);-ms-flex-pack:justify;justify-content:space-between;-ms-flex-align:center;align-items:center;padding:.5rem;gap:.5rem}.bal-date-calendar__nav--start>button{display:-ms-flexbox;display:flex;gap:.5rem}.bal-date-calendar__nav--end{display:-ms-flexbox;display:flex;gap:.5rem}.bal-date-calendar__nav button{display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;cursor:pointer;border-radius:var(--bal-radius-normal);font-family:var(--bal-font-family-text);font-weight:var(--bal-font-weight-regular);color:var(--bal-date-calendar-button-color);border:none;background:var(--bal-date-calendar-button-background);text-align:center;font-size:var(--bal-text-size-normal);line-height:var(--bal-line-height-normal);-webkit-hyphens:auto;-ms-hyphens:auto;hyphens:auto;outline:none;min-height:2rem;min-width:2rem;padding:.25rem;border-radius:var(--bal-button-radius);font-family:var(--bal-font-family-title);font-weight:var(--bal-font-weight-bold)}@media (hover: hover)and (pointer: fine){.bal-date-calendar__nav button:not(.bal-date-calendar__nav button--selected):not(.bal-date-calendar__nav button--disabled):hover{background:var(--bal-date-calendar-button-background-hover)}}.bal-date-calendar__nav button:not(.bal-date-calendar__nav button--selected):not(.bal-date-calendar__nav button--disabled):active{background:var(--bal-date-calendar-button-background-active)}.bal-date-calendar__nav button--today:not(.bal-date-calendar__nav button--selected):not(.bal-date-calendar__nav button--disabled){color:var(--bal-date-calendar-button-today-color);font-weight:var(--bal-font-weight-bold)}@media (hover: hover)and (pointer: fine){.bal-date-calendar__nav button--today:not(.bal-date-calendar__nav button--selected):not(.bal-date-calendar__nav button--disabled):hover{color:var(--bal-date-calendar-button-today-color-hover)}}.bal-date-calendar__nav button--today:not(.bal-date-calendar__nav button--selected):not(.bal-date-calendar__nav button--disabled):active{color:var(--bal-date-calendar-button-today-color-active)}.bal-date-calendar__nav button--selected{background:var(--bal-date-calendar-button-selected-background);color:var(--bal-date-calendar-button-selected-color);font-weight:var(--bal-font-weight-bold)}.bal-date-calendar__nav button--disabled{cursor:default;background:rgba(0,0,0,0);color:var(--bal-color-text-grey-light)}.bal-date-calendar__body{display:block}.bal-date-calendar__body__grid{width:-webkit-fit-content;width:-moz-fit-content;width:fit-content;padding:.5rem;height:0;padding-top:0;padding-bottom:0;visibility:hidden}.bal-date-calendar__body__grid--visible{height:auto;padding-top:.5rem;padding-bottom:.5rem;visibility:visible}.bal-date-calendar__body__grid__head{position:relative;display:grid;grid-template-columns:repeat(7, 1fr);-webkit-column-gap:.5rem;-moz-column-gap:.5rem;column-gap:.5rem;row-gap:.5rem;width:-webkit-fit-content;width:-moz-fit-content;width:fit-content}.bal-date-calendar__body__grid__head::after{position:absolute;content:\"\";height:2px;width:calc(100% + 1rem);bottom:0;left:-0.5rem;right:-0.5rem;background:var(--bal-color-border)}.bal-date-calendar__body__grid__head span{display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;height:2rem;width:2rem;font-family:var(--bal-font-family-title);font-weight:var(--bal-font-weight-bold);font-size:var(--bal-text-size-normal);line-height:var(--bal-line-height-normal);-webkit-hyphens:auto;-ms-hyphens:auto;hyphens:auto;text-wrap:nowrap}.bal-date-calendar__body__grid__body{display:grid;grid-template-columns:repeat(7, 1fr);-webkit-column-gap:.5rem;-moz-column-gap:.5rem;column-gap:.5rem;row-gap:.5rem;width:-webkit-fit-content;width:-moz-fit-content;width:fit-content;padding-top:.5rem}.bal-date-calendar__body__grid__body>.bal-date-calendar-cell{width:2rem;height:2rem;text-align:center;font-size:var(--bal-text-size-normal);line-height:var(--bal-line-height-normal);-webkit-hyphens:auto;-ms-hyphens:auto;hyphens:auto}.bal-date-calendar__body__grid__body>.bal-date-calendar-cell:first-child{grid-column:var(--bal-date-first-week-day)}.bal-date-calendar__body__list{display:none;list-style:none;margin:0;padding:0;-webkit-column-gap:.5rem;-moz-column-gap:.5rem;column-gap:.5rem;row-gap:.5rem;width:calc(100% - 1rem);overflow-y:auto;max-height:18rem;position:relative;padding:.5rem;border-top:2px solid var(--bal-color-border)}.bal-date-calendar__body__list .bal-date-calendar__body__list__item{display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;cursor:pointer;border-radius:var(--bal-radius-normal);font-family:var(--bal-font-family-text);font-weight:var(--bal-font-weight-regular);color:var(--bal-date-calendar-button-color);border:none;background:var(--bal-date-calendar-button-background);text-align:center;font-size:var(--bal-text-size-normal);line-height:var(--bal-line-height-normal);-webkit-hyphens:auto;-ms-hyphens:auto;hyphens:auto;outline:none;width:100%}@media (hover: hover)and (pointer: fine){.bal-date-calendar__body__list .bal-date-calendar__body__list__item:not(.bal-date-calendar__body__list .bal-date-calendar__body__list__item--selected):not(.bal-date-calendar__body__list .bal-date-calendar__body__list__item--disabled):hover{background:var(--bal-date-calendar-button-background-hover)}}.bal-date-calendar__body__list .bal-date-calendar__body__list__item:not(.bal-date-calendar__body__list .bal-date-calendar__body__list__item--selected):not(.bal-date-calendar__body__list .bal-date-calendar__body__list__item--disabled):active{background:var(--bal-date-calendar-button-background-active)}.bal-date-calendar__body__list .bal-date-calendar__body__list__item--today:not(.bal-date-calendar__body__list .bal-date-calendar__body__list__item--selected):not(.bal-date-calendar__body__list .bal-date-calendar__body__list__item--disabled){color:var(--bal-date-calendar-button-today-color);font-weight:var(--bal-font-weight-bold)}@media (hover: hover)and (pointer: fine){.bal-date-calendar__body__list .bal-date-calendar__body__list__item--today:not(.bal-date-calendar__body__list .bal-date-calendar__body__list__item--selected):not(.bal-date-calendar__body__list .bal-date-calendar__body__list__item--disabled):hover{color:var(--bal-date-calendar-button-today-color-hover)}}.bal-date-calendar__body__list .bal-date-calendar__body__list__item--today:not(.bal-date-calendar__body__list .bal-date-calendar__body__list__item--selected):not(.bal-date-calendar__body__list .bal-date-calendar__body__list__item--disabled):active{color:var(--bal-date-calendar-button-today-color-active)}.bal-date-calendar__body__list .bal-date-calendar__body__list__item--selected{background:var(--bal-date-calendar-button-selected-background);color:var(--bal-date-calendar-button-selected-color);font-weight:var(--bal-font-weight-bold)}.bal-date-calendar__body__list .bal-date-calendar__body__list__item--disabled{cursor:default;background:rgba(0,0,0,0);color:var(--bal-color-text-grey-light)}.bal-date-calendar__body__list--visible{display:grid}.bal-date-calendar__body__list--year{grid-template-columns:repeat(4, 1fr)}.bal-date-calendar__body__list--month{grid-template-columns:repeat(2, 1fr)}.bal-date-calendar-cell{display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;cursor:pointer;border-radius:var(--bal-radius-normal);font-family:var(--bal-font-family-text);font-weight:var(--bal-font-weight-regular);color:var(--bal-date-calendar-button-color);border:none;background:var(--bal-date-calendar-button-background);text-align:center;font-size:var(--bal-text-size-normal);line-height:var(--bal-line-height-normal);-webkit-hyphens:auto;-ms-hyphens:auto;hyphens:auto;outline:none;width:2rem;height:2rem}@media (hover: hover)and (pointer: fine){.bal-date-calendar-cell:not(.bal-date-calendar-cell--selected):not(.bal-date-calendar-cell--disabled):hover{background:var(--bal-date-calendar-button-background-hover)}}.bal-date-calendar-cell:not(.bal-date-calendar-cell--selected):not(.bal-date-calendar-cell--disabled):active{background:var(--bal-date-calendar-button-background-active)}.bal-date-calendar-cell--today:not(.bal-date-calendar-cell--selected):not(.bal-date-calendar-cell--disabled){color:var(--bal-date-calendar-button-today-color);font-weight:var(--bal-font-weight-bold)}@media (hover: hover)and (pointer: fine){.bal-date-calendar-cell--today:not(.bal-date-calendar-cell--selected):not(.bal-date-calendar-cell--disabled):hover{color:var(--bal-date-calendar-button-today-color-hover)}}.bal-date-calendar-cell--today:not(.bal-date-calendar-cell--selected):not(.bal-date-calendar-cell--disabled):active{color:var(--bal-date-calendar-button-today-color-active)}.bal-date-calendar-cell--selected{background:var(--bal-date-calendar-button-selected-background);color:var(--bal-date-calendar-button-selected-color);font-weight:var(--bal-font-weight-bold)}.bal-date-calendar-cell--disabled{cursor:default;background:rgba(0,0,0,0);color:var(--bal-color-text-grey-light)}";

const DateCalendar = /*@__PURE__*/ proxyCustomElement(class DateCalendar extends HTMLElement {
    constructor(registerHost) {
        super();
        if (registerHost !== false) {
            this.__registerHost();
        }
        this.__attachShadow();
        this.balChange = createEvent(this, "balChange", 7);
        this.oldMin = '';
        this.oldMax = '';
        this.selectedDate = '';
        this.monthFullNames = [];
        this.weekdays = [];
        this.months = [];
        this.years = [];
        this.calendarGrid = [];
        this.firstDayOfWeek = 0;
        this.month = 0;
        this.year = 0;
        this.language = defaultConfig.language;
        this.isCalendarVisible = true;
        this.isYearListVisible = false;
        this.isMonthListVisible = false;
        /**
         * Callback to determine which date in the datepicker should be selectable.
         */
        this.allowedDates = undefined;
        /**
         * EVENT BINDING
         * ------------------------------------------------------
         */
        this.onSelectDay = (isoDate) => {
            this.valueChanged(isoDate, this.selectedDate);
            this.balChange.emit(this.selectedDate);
        };
        this.onClickNextMonth = () => {
            let nextYear = this.year;
            let nextMonth = this.month + 1;
            if (nextMonth > 12) {
                nextMonth = 1;
                nextYear = nextYear + 1;
            }
            this.generateGridByMonthAndYear(nextMonth, nextYear);
        };
        this.onClickPreviousMonth = () => {
            let nextYear = this.year;
            let nextMonth = this.month - 1;
            if (nextMonth < 1) {
                nextMonth = 12;
                nextYear = nextYear - 1;
            }
            this.generateGridByMonthAndYear(nextMonth, nextYear);
        };
        this.onClickSelectMonthAndYear = async () => {
            this.updateSelections();
            if (this.isCalendarVisible === true) {
                this.isCalendarVisible = false;
                this.isYearListVisible = true;
                this.isMonthListVisible = false;
                await waitAfterFramePaint();
                if (this.yearListEl) {
                    const selectedYearEl = this.yearListEl.querySelector(`#year-${this.year}`);
                    if (selectedYearEl) {
                        const rowHeight = 26 + 8 + 4;
                        this.yearListEl.scrollTop = selectedYearEl.offsetTop - rowHeight * 2;
                    }
                    else {
                        this.yearListEl.scrollTop = 0;
                    }
                }
            }
            else {
                this.isCalendarVisible = true;
                this.isYearListVisible = false;
                this.isMonthListVisible = false;
            }
        };
        this.onClickYear = (newYear) => {
            this.isYearListVisible = false;
            this.isMonthListVisible = true;
            this.generateGridByMonthAndYear(this.month, newYear);
            this.months = generateMonths(this.language, newYear, this.selectedDate, this.min, this.max);
        };
        this.onClickMonth = (newMonth) => {
            this.isYearListVisible = false;
            this.isMonthListVisible = false;
            this.isCalendarVisible = true;
            this.generateGridByMonthAndYear(newMonth, this.year);
        };
    }
    createLogger(log) {
        this.log = log;
    }
    valueChanged(newValue, oldValue) {
        if (newValue !== oldValue) {
            const date = BalDate.fromISO(newValue);
            if (!date.isValid) {
                this.generateGridByDefaultDate();
                this.selectedDate = '';
            }
            else {
                this.generateGridByDate(date);
                this.selectedDate = date.toISODate();
            }
            this.updateSelections();
        }
    }
    rangePropChanged() {
        this.updateSelections();
        this.generateGrid();
    }
    yearRangePropChanged() {
        this.updateSelections();
    }
    /**
     * LIFECYCLE
     * ------------------------------------------------------
     */
    connectedCallback() {
        this.generateGridByDefaultDate();
        this.valueChanged(this.value, undefined);
    }
    /**
     * LISTENERS
     * ------------------------------------------------------
     */
    /**
     * @internal define config for the component
     */
    async configChanged(state) {
        this.language = state.language;
        this.monthFullNames = BalDate.infoMonths({ format: 'long', locale: this.language });
        this.weekdays = generateWeekDays(this.language);
        this.updateSelections();
    }
    swipeListener({ left, right }) {
        if (left) {
            this.onClickNextMonth();
        }
        else if (right) {
            this.onClickPreviousMonth();
        }
    }
    /**
     * GETTERS
     * ------------------------------------------------------
     */
    get minYear() {
        if (this.minYearProp === undefined) {
            const today = new Date();
            const year = today.getFullYear();
            const defaultMinYear = year - 100;
            if (this.min) {
                const date = BalDate.fromISO(this.min);
                return date.year || defaultMinYear;
            }
            else {
                return defaultMinYear;
            }
        }
        return this.minYearProp;
    }
    get maxYear() {
        if (this.maxYearProp === undefined) {
            const today = new Date();
            const year = today.getFullYear();
            const defaultMaxYear = year + 50;
            if (this.max) {
                const date = BalDate.fromISO(this.max);
                return date.year || defaultMaxYear;
            }
            else {
                return defaultMaxYear;
            }
        }
        return this.maxYearProp;
    }
    /**
     * PRIVATE METHODS
     * ------------------------------------------------------
     */
    updateSelections() {
        this.years = generateYears(this.year, this.minYear, this.maxYear);
        this.months = generateMonths(this.language, this.year, this.selectedDate, this.min, this.max);
    }
    generateGrid() {
        const date = BalDate.fromISO(this.value);
        if (date.isValid) {
            this.generateGridByDate(date);
        }
        else {
            this.generateGridByDefaultDate();
        }
    }
    generateGridByDate(date) {
        if (date.year !== undefined && date.month !== undefined) {
            this.generateGridByMonthAndYear(date.month, date.year);
        }
    }
    generateGridByDefaultDate() {
        const date = BalDate.fromISO(this.defaultDate);
        if (date.isValid) {
            this.generateGridByDate(date);
        }
        else {
            const today = new Date();
            this.month = today.getMonth() + 1;
            this.year = today.getFullYear();
            this.calendarGrid = generateCalendarGrid(this.year, this.month, this.min, this.max, this.allowedDates);
            this.firstDayOfWeek = getFirstWeekdayOfMonth(this.year, this.month);
        }
    }
    generateGridByMonthAndYear(month, year) {
        // Only generate when mont and year has changed
        if (this.month !== month || this.year !== year || this.oldMin !== this.min || this.oldMax !== this.max) {
            this.calendarGrid = generateCalendarGrid(year, month, this.min, this.max, this.allowedDates);
            this.firstDayOfWeek = getFirstWeekdayOfMonth(year, month);
        }
        this.month = month;
        this.year = year;
        this.oldMin = this.min;
        this.oldMax = this.max;
    }
    /**
     * RENDER
     * ------------------------------------------------------
     */
    render() {
        var _a;
        const girdHeight = ((_a = this.gridEl) === null || _a === void 0 ? void 0 : _a.clientHeight) || 0;
        const block = BEM.block('date-calendar');
        const blockBody = block.element('body');
        const blockFoot = block.element('foot');
        return (h(Host, { key: '34efddf3c88e5470dcefd22c5cab262873d07de8', class: Object.assign({}, block.class()) }, h(CalendarNav, { key: '9c8942a95ff9f1c8fdc8b1e153a29632145d1c2b', language: this.language, monthFullNames: this.monthFullNames, month: this.month, year: this.year, isCalendarVisible: this.isCalendarVisible, isListVisible: this.isMonthListVisible || this.isYearListVisible, onClickSelectMonthAndYear: this.onClickSelectMonthAndYear, onClickPreviousMonth: this.onClickPreviousMonth, onClickNextMonth: this.onClickNextMonth }), h("div", { key: '6a2cb7bba9c0568c1dc31d8b1c811b90c5845dce', class: Object.assign({}, blockBody.class()) }, h(CalendarGrid, { key: 'a687e1e1f80bc8ea21bdc7ad4709537829005843', isVisible: this.isCalendarVisible, grid: this.calendarGrid, weekdays: this.weekdays, firstDayOfWeek: this.firstDayOfWeek, selectedDate: this.selectedDate, ref: el => (this.gridEl = el), onSelectDay: isoDate => this.onSelectDay(isoDate) }), h(CalendarList, { key: 'cba1e282fb92f5edfa04e97eefcf9b38b57b8428', name: "year", isVisible: this.isYearListVisible, girdHeight: girdHeight, list: this.years, ref: el => (this.yearListEl = el), onSelect: item => this.onClickYear(item.value) }), h(CalendarList, { key: 'ae7cb47aaffec3d3a91d1aab96f1fbdde34b7e6f', name: "month", isVisible: this.isMonthListVisible, girdHeight: girdHeight, list: this.months, onSelect: item => this.onClickMonth(item.value) })), h("div", { key: '6e455964845a4e57abc793cb78916ed51fa0bdb3', class: Object.assign({}, blockFoot.class()) }, h("slot", { key: '277a09ef4cb10f6f051c84b1ba9f9ae79f0d3479' }))));
    }
    get el() { return this; }
    static get watchers() { return {
        "value": ["valueChanged"],
        "min": ["rangePropChanged"],
        "max": ["rangePropChanged"],
        "minYearProp": ["yearRangePropChanged"],
        "maxYearProp": ["yearRangePropChanged"]
    }; }
    static get style() { return balDateCalendarCss; }
}, [257, "bal-date-calendar", {
        "value": [1],
        "defaultDate": [1, "default-date"],
        "allowedDates": [16],
        "min": [1025],
        "max": [1025],
        "minYearProp": [2, "min-year"],
        "maxYearProp": [2, "max-year"],
        "selectedDate": [32],
        "monthFullNames": [32],
        "weekdays": [32],
        "months": [32],
        "years": [32],
        "calendarGrid": [32],
        "firstDayOfWeek": [32],
        "month": [32],
        "year": [32],
        "language": [32],
        "isCalendarVisible": [32],
        "isYearListVisible": [32],
        "isMonthListVisible": [32],
        "configChanged": [64]
    }, undefined, {
        "value": ["valueChanged"],
        "min": ["rangePropChanged"],
        "max": ["rangePropChanged"],
        "minYearProp": ["yearRangePropChanged"],
        "maxYearProp": ["yearRangePropChanged"]
    }]);
__decorate([
    Logger('bal-date-calendar'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Function]),
    __metadata("design:returntype", void 0)
], DateCalendar.prototype, "createLogger", null);
__decorate([
    ListenToConfig(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], DateCalendar.prototype, "configChanged", null);
__decorate([
    ListenToSwipe({ mobileOnly: true }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", void 0)
], DateCalendar.prototype, "swipeListener", null);
function defineCustomElement() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["bal-date-calendar", "bal-date-calendar-cell", "bal-icon"];
    components.forEach(tagName => { switch (tagName) {
        case "bal-date-calendar":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, DateCalendar);
            }
            break;
        case "bal-date-calendar-cell":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
        case "bal-icon":
            if (!customElements.get(tagName)) {
                defineCustomElement$1();
            }
            break;
    } });
}

export { DateCalendar as D, defineCustomElement as d };
