/**
 * Copyright Aquera Inc 2023
 *
 * This source code is licensed under the BSD-3-Clause license found in the
 * LICENSE file in the root directory of this source tree.
 */
import { __decorate } from "tslib";
import { html, nothing } from 'lit';
import { customElement, state, property } from 'lit/decorators.js';
import { styles } from './nile-calendar.css';
import { classMap } from 'lit/directives/class-map.js';
import { watch } from '../internal/watch';
import NileElement from '../internal/nile-element';
import { ClearMode } from './nile-calendar.enum';
/**
 * Nile icon component.
 *
 * @tag nile-calendar
 *
 */
let NileCalendar = class NileCalendar extends NileElement {
    constructor() {
        super(...arguments);
        this.valueAttribute = null;
        this.allowedDates = JSON.stringify({});
        this.range = false;
        this.hideTypes = false;
        this.doubleClickUnselect = false;
        this.allowClear = false;
        this.type = 'absolute';
        this.hideDurationFields = [];
        this.showManualInputs = false;
        this.showMonthDropdown = false;
        this.showYearDropdown = false;
        this.dateFormat = 'MM/DD/YYYY';
        this.startDate = null;
        this.endDate = null;
        this.isSelectingStart = true;
        this.hideInput = false;
        this.currentMonth = new Date().getMonth();
        this.currentYear = new Date().getFullYear();
        this.allowedDatesLocal = null;
        this.disabled = false;
    }
    /**
     * The styles for NileCalendar
     * @remarks If you are extending this class you can extend the base styles with super. Eg `return [super(), myCustomStyles]`
     */
    static get styles() {
        return [styles];
    }
    connectedCallback() {
        super.connectedCallback();
        this.initializeValue();
        this.emit('nile-init');
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        this.emit('nile-destroy');
    }
    updated(changedProperties) {
        super.updated(changedProperties);
        if (changedProperties.has('valueAttribute')) {
            if (!this.valueAttribute) {
                this.value = null;
                this.startDate = null;
                this.endDate = null;
                this.isSelectingStart = true;
            }
            const date = new Date(this.valueAttribute || '');
            if (!isNaN(date.getTime())) {
                const offset = date.getTimezoneOffset();
                this.value = new Date(date.getTime() - offset * 60 * 1000);
                this.currentMonth = this.value.getMonth();
                this.currentYear = this.value.getFullYear();
            }
            this.initializeValue();
        }
    }
    get monthNames() {
        return Array.from({ length: 12 }, (_, i) => new Date(0, i).toLocaleString('default', { month: 'long' }));
    }
    get yearOptions() {
        const fallbackStart = 2000;
        const fallbackEnd = 2050;
        const start = this.startYear ?? fallbackStart;
        const end = this.endYear ?? fallbackEnd;
        if (start > end)
            return [];
        return Array.from({ length: end - start + 1 }, (_, i) => start + i);
    }
    onMonthSelected(monthIndex) {
        this.currentMonth = monthIndex;
        this.emit('nile-month-change', { month: monthIndex });
    }
    onYearSelected(year) {
        this.currentYear = year;
        this.emit('nile-year-change', { year });
    }
    checkValidAllowedDate() {
        let newDateRange;
        try {
            newDateRange = JSON.parse(this.allowedDates);
        }
        catch (error) {
            newDateRange = null;
        }
        if (!newDateRange || Object.keys(newDateRange).length == 0) {
            this.allowedDatesLocal = null;
            return;
        }
        this.hideInput = true;
        const startDate = this.getUTCDate(newDateRange.startDate);
        const endDate = this.getUTCDate(newDateRange.endDate);
        if (startDate > endDate) {
            console.error('StartDate must be greater than endDate');
        }
        else {
            this.allowedDatesLocal = newDateRange;
        }
    }
    isPrevDisabled() {
        return (this.currentMonth === 0 &&
            this.startYear !== undefined &&
            this.currentYear <= this.startYear);
    }
    isNextDisabled() {
        return (this.currentMonth === 11 &&
            this.endYear !== undefined &&
            this.currentYear >= this.endYear);
    }
    formatDate(date) {
        if (!date)
            return '';
        const yyyy = date.getFullYear();
        const mm = String(date.getMonth() + 1).padStart(2, '0');
        const dd = String(date.getDate()).padStart(2, '0');
        let formatted = this.dateFormat;
        formatted = formatted.replace(/YYYY/g, String(yyyy));
        formatted = formatted.replace(/MM/g, mm);
        formatted = formatted.replace(/DD/g, dd);
        formatted = formatted.replace(/YY/g, String(yyyy).slice(-2));
        return formatted;
    }
    parseDate(input, existingDate) {
        if (!input || !this.dateFormat)
            return null;
        const formatPattern = this.dateFormat
            .replace(/YYYY/, '(?<year>\\d{4})')
            .replace(/YY/, '(?<year>\\d{2})')
            .replace(/MM/, '(?<month>\\d{1,2})')
            .replace(/DD/, '(?<day>\\d{1,2})');
        const regex = new RegExp(`^${formatPattern}$`);
        const match = input.match(regex);
        if (!match || !match.groups)
            return null;
        const year = match.groups.year.length === 2 ? Number(`20${match.groups.year}`) : Number(match.groups.year);
        const month = Number(match.groups.month) - 1;
        const day = Number(match.groups.day);
        const date = new Date(year, month, day);
        if (existingDate) {
            date.setHours(existingDate.getHours(), existingDate.getMinutes(), existingDate.getSeconds());
        }
        else {
            date.setHours(0, 0, 0);
        }
        return date;
    }
    handleStartDateInput(event) {
        event.stopPropagation();
        const newDate = this.parseDate(event.detail.value, this.startDate);
        if (newDate) {
            newDate.setHours(0, 0, 0);
            this.startDate = newDate;
            this.currentMonth = newDate.getMonth();
            this.currentYear = newDate.getFullYear();
            this.requestUpdate();
        }
    }
    handleEndDateInput(event) {
        event.stopPropagation();
        const newDate = this.parseDate(event.detail.value, this.endDate);
        if (newDate) {
            newDate.setHours(23, 59, 59);
            this.endDate = newDate;
            this.currentMonth = newDate.getMonth();
            this.currentYear = newDate.getFullYear();
            this.requestUpdate();
        }
    }
    /**
     * Render method
     */
    render() {
        return html `
      <div
        class=${classMap({
            base: true,
            base__range: this.range,
        })}
        part="calendar-container"
      >
        <div class=${classMap({
            "calendar-config": true,
            "hidden": !this.range || (this.range && this.hideTypes)
        })}>
          <div class="calendar-switcher" part="calendar-switcher">
            <nile-tab-group centered @nile-tab-show="${this.onTypeChange}" value="${this.type}">
              <nile-tab slot="nav" panel="absolute" tabindex="${this.disabled ? '-1' : '0'}">Absolute</nile-tab>
              <nile-tab slot="nav" panel="relative" tabindex="${this.disabled ? '-1' : '0'}">Relative</nile-tab>
            </nile-tab-group>
          </div>
        </div>
 
        ${this.type == 'relative' ? this.renderRelativeCalendar() : ''}
        ${this.type == 'absolute' ? this.renderAbsoluteCalendar() : ''}

        ${!this.range ? '' : html `
        <div class="button-container" part="button-container">
          ${this.allowClear ?
            html `
            <nile-button 
            class="clear-button"
            variant="secondary"
            role="button"
            ?disabled="${!this.startDate || !this.endDate || this.disabled}"
            @keydown="${(e) => { if (e.key === 'Enter' || e.key === ' ')
                this.clearDate(); }}"
            @click="${this.clearDate}"

            > Reset</nile-button>` : nothing}
          <nile-button 
          class="apply-button"  
          ?disabled="${!this.startDate || !this.endDate || this.disabled}"  
          @click="${this.confimRange}"
          @keydown="${(e) => { if (e.key === 'Enter' || e.key === ' ')
            this.confimRange(); }}"
          > Apply</nile-button>
        </div>
        `}
      </div>
    `;
    }
    /**
     * @returns HTML content for absolute calendar
     */
    renderAbsoluteCalendar() {
        return html `
    <div class="calendar-wrapper" part="calendar-wrapper">
      <div class="calendar-container" >
        ${this.renderMonth(this.currentYear, this.currentMonth, this.getDaysArray(this.currentYear, this.currentMonth))}
      </div>
    </div>
    ${this.range ? html `
    <div class="calender-input ${this.showManualInputs ? '' : 'hidden'}" >
     <div class="from">
  <div class="from-date">
    <nile-input
      ?disabled="${this.disabled}"
      label="From"
      class="manual-input date-input"
      placeholder="${this.dateFormat}"
      value="${this.formatDate(this.startDate)}"
      @nile-change="${this.handleStartDateInput}"
    ></nile-input>
  </div>

  <div class="from-time">
    <nile-input
      ?disabled="${this.disabled}"
      class="manual-input time-input"
      placeholder="HH:MM:SS"
      value="${this.formatTime(this.startDate)}"
      @nile-change="${this.handleStartTimeInput}"
    ></nile-input>
  </div>
</div>


    <div class="from">
        <div class="from-date">
      <nile-input
      ?disabled="${this.disabled}"
        label="To"
        class="manual-input date-input"
        placeholder="${this.dateFormat}"
        value="${this.formatDate(this.endDate)}"
        @nile-change="${this.handleEndDateInput}"
      ></nile-input>
    </div>
      <div class="from-time">
      <nile-input
      ?disabled="${this.disabled}"
        class="manual-input time-input"
        placeholder="HH:MM:SS"
        value="${this.formatTime(this.endDate)}"
        @nile-change="${this.handleEndTimeInput}"
      ></nile-input>
    </div>
    </div>
    </div>
    ` : ''}
    `;
    }
    /**
     * @returns HTML content for relative calendar
     */
    renderRelativeCalendar() {
        return html `
      <div class="units-wrapper">
        <div class="unit-container">
  
          ${this.hideDurationFields?.includes('minutes') ? '' : html `
          <div class="unit-group">
            <div class="duration-name">Minutes</div>
            <div class="duration-units">
              ${this.renderTimeValues('minutes', [1, 5, 15, 30, 45])}
            </div>
          </div>
          `}
  
          ${this.hideDurationFields?.includes('hours') ? '' : html `
          <div class="unit-group">
            <div class="duration-name">Hours</div>
            <div class="duration-units">
              ${this.renderTimeValues('hours', [1, 2, 3, 6, 8, 12])}
            </div>
          </div>
          `}
  
          ${this.hideDurationFields?.includes('days') ? '' : html `
          <div class="unit-group">
            <div class="duration-name">Days</div>
            <div class="duration-units">
              ${this.renderTimeValues('days', [1, 2, 3, 4, 5, 6])}
            </div>
          </div>
          `}
  
          ${this.hideDurationFields?.includes('weeks') ? '' : html `
          <div class="unit-group">
            <div class="duration-name">Weeks</div>
            <div class="duration-units">
              ${this.renderTimeValues('weeks', [1, 2, 4, 6])}
            </div>
          </div>
          `}
  
          ${this.hideDurationFields?.includes('months') ? '' : html `
          <div class="unit-group">
            <div class="duration-name">Months</div>
            <div class="duration-units">
              ${this.renderTimeValues('months', [3, 6, 12, 15])}
            </div>
          </div>
          `}
        </div>
      </div>
  
      ${this.range ? html `
      <div>
        <div class="unit-input-container">
          <nile-input 
            class="manual-input duration-input" 
            ?disabled="${this.disabled}"
            label="Duration"
            inputmode="numeric"
            type="number"
            value="${this.selectedValue}" 
            @nile-change="${this.handleDurationChange}"
            placeholder="Enter Value"
          ></nile-input>
  
          <nile-select 
            class="manual-input time-input"  
            ?disabled="${this.disabled}"
            label="Unit of time" 
            value="${this.selectedUnit}"
            @nile-change="${this.handleUnitChange}"
          >
            <nile-option value="minutes" class="${this.hideDurationFields?.includes('minutes') ? 'hidden' : ''}">Minutes</nile-option>
            <nile-option value="hours" class="${this.hideDurationFields?.includes('hours') ? 'hidden' : ''}">Hours</nile-option>
            <nile-option value="days" class="${this.hideDurationFields?.includes('days') ? 'hidden' : ''}">Days</nile-option>
            <nile-option value="weeks" class="${this.hideDurationFields?.includes('weeks') ? 'hidden' : ''}">Weeks</nile-option>
            <nile-option value="months" class="${this.hideDurationFields?.includes('months') ? 'hidden' : ''}">Months</nile-option>
          </nile-select>
        </div>
      </div>
      ` : ''}
    `;
    }
    /**
     *
     * @param unit
     * @param values
     * @returns html for the option
     */
    renderTimeValues(unit, values) {
        return values.map(value => html `
          <div
            class="duration__value ${this.selectedUnit === unit && this.selectedValue === value ? 'duration__value--selected' : ''}"
            @click=${(e) => this.handleTimeValueClick(unit, value, e)}
            @keydown="${(e) => { if (e.key === 'Enter' || e.key === ' ')
            this.handleTimeValueClick(unit, value, e); }}"
          >${value}
          </div>`);
    }
    /**
     *
     * @param year
     * @param month
     * @param daysArray
     * @returns HTML for rendered month
     */
    renderMonth(year, month, daysArray) {
        const firstDay = new Date(year, month, 1).getDay();
        const lastDay = new Date(year, month + 1, 0).getDay();
        const prevMonthDays = this.getDaysArray(month === 0 ? year - 1 : year, month === 0 ? 11 : month - 1);
        const nextMonthDays = this.getDaysArray(month === 11 ? year + 1 : year, month === 11 ? 0 : month + 1);
        const fillerDaysBefore = prevMonthDays.slice(prevMonthDays.length - firstDay);
        const fillerDaysAfter = nextMonthDays.slice(0, 6 - lastDay);
        const allDays = [...fillerDaysBefore, ...daysArray, ...fillerDaysAfter];
        const isSelectedDate = (day, month, year, isCurrentMonth) => {
            if (!isCurrentMonth)
                return '';
            if (!this.range && this.value) {
                const isSelected = day === this.value.getDate() &&
                    month === this.value.getMonth() &&
                    year === this.value.getFullYear();
                if (isSelected)
                    return 'selected-date';
            }
            const isStartDate = this.startDate &&
                day === this.startDate.getDate() &&
                month === this.startDate.getMonth() &&
                year === this.startDate.getFullYear();
            const isEndDate = this.endDate &&
                day === this.endDate.getDate() &&
                month === this.endDate.getMonth() &&
                year === this.endDate.getFullYear();
            return isStartDate ? 'range-start' : isEndDate ? 'range-end' : '';
        };
        const isInRange = (day, month, year, isCurrentMonth) => {
            if (!isCurrentMonth)
                return false;
            if (this.startDate && this.endDate) {
                const date = new Date(year, month, day);
                return date >= this.startDate && date <= this.endDate;
            }
            return false;
        };
        const isCurrentDate = (day, month, year) => {
            const today = new Date();
            return (day === today.getDate() &&
                month + 1 === today.getMonth() + 1 &&
                year === today.getFullYear());
        };
        const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
        return html `
      <div class="calendar">
        <div class="calendar-header">
          <nile-icon
            class="calendar-header__month-navigation"
            name="var(--nile-icon-arrow-left, var(--ng-icon-chevron-left))"
            method="var(--nile-svg-method-fill, var(--ng-svg-method-stroke))"
            color=${this.disabled ? 'var(--nile-colors-dark-500, var(--ng-colors-fg-disabled))' : 'black'}
            role="button"
            tabindex="${this.disabled || this.isPrevDisabled() ? '-1' : '0'}"
            @keydown="${(e) => { if (e.key === 'Enter' || e.key === ' ')
            this.prevMonth(); }}"
            @click="${this.prevMonth}"
          >
          </nile-icon>
          <div class="calendar-header__center">

${this.showMonthDropdown || this.showYearDropdown ? html `
  ${this.showMonthDropdown ? html `
    <nile-dropdown ?disabled="${this.disabled}" class="month-dropdown">
      <span
        slot="trigger"
        class="calendar-header__trigger month-trigger"
        role="button"
        part="trigger"
      >
        ${new Date(year, month).toLocaleString('default', { month: 'long' })}
        <nile-icon name="arrowdropdown" color=${this.disabled ? 'var(--nile-colors-dark-500, var(--ng-colors-fg-disabled))' : 'black'} class="calendar-header__caret"></nile-icon>
      </span>
      <nile-menu>
        <div class="month-scroll-wrapper">
          ${this.monthNames.map((m, idx) => html `
            <nile-menu-item
              class="month-menu-item"
              ?selected="${idx === month}"
              @click="${() => this.onMonthSelected(idx)}"
            >
              ${m}
            </nile-menu-item>
          `)}
        </div>
      </nile-menu>
    </nile-dropdown>
  ` : html `
    <span
      >${new Date(year, month).toLocaleString('default', { month: 'long' })}</span
    >
  `}
  ${this.showYearDropdown ? html `
    <nile-dropdown ?disabled="${this.disabled}" class="year-dropdown">
      <span
        slot="trigger"
        class="calendar-header__trigger"
        role="button"
        part="trigger"
      >
        ${year}
        <nile-icon name="arrowdropdown" color=${this.disabled ? 'var(--nile-colors-dark-500, var(--ng-colors-fg-disabled))' : 'black'} class="calendar-header__caret"></nile-icon>
      </span>
      <nile-menu>
        <div class="year-scroll-wrapper">
          ${this.yearOptions.map(y => html `
              <nile-menu-item
                class="year-menu-item"
                ?selected="${y === year}"
                @click="${() => this.onYearSelected(y)}"
              >
                ${y}
              </nile-menu-item>
            `)}
        </div>
      </nile-menu>
    </nile-dropdown>
  ` : html `
    <span>${year}</span>
  `}
` : html `
  <span
    >${new Date(year, month).toLocaleString('default', {
            month: 'long',
        })}
    ${year}</span
  >
`}
</div>

          <nile-icon
            class="calendar-header__month-navigation"
            name="var(--nile-icon-arrow-right, var(--ng-icon-chevron-right))"
            method="var(--nile-svg-method-fill, var(--ng-svg-method-stroke))"
            color=${this.disabled ? 'var(--nile-colors-dark-500, var(--ng-colors-fg-disabled))' : 'black'}
            role="button"
            tabindex="${this.disabled || this.isNextDisabled() ? '-1' : '0'}"
            @keydown="${(e) => { if (e.key === 'Enter' || e.key === ' ')
            this.nextMonth(); }}"
            @click="${this.nextMonth}"
            
          >
          </nile-icon>
        </div>
   
        <div class="days_container">
        ${dayNames.map(day => html `<div class="day_name">${day}</div>`)}
          ${allDays.map((day, index) => {
            const isCurrentMonth = index >= fillerDaysBefore.length &&
                index < fillerDaysBefore.length + daysArray.length;
            const datePlacement = isSelectedDate(day, month, year, isCurrentMonth);
            const classMapObj = {
                'day_date': true,
                'not-allowed': !this.isAllowedDate(day, month, year),
                'in-range': isInRange(day, month, year, isCurrentMonth),
                'filler': !isCurrentMonth,
            };
            if (datePlacement)
                classMapObj[datePlacement] = true;
            return html ` 
            <div
              part="calendar-day-${day}"
              class=${classMap(classMapObj)}
             tabindex="${isCurrentMonth && this.isAllowedDate(day, month, year) && !this.disabled ? '0' : '-1'}"
              @keydown="${(e) => { if (e.key === 'Enter' || e.key === ' ')
                this.selectDate(day, month, year); }}"
              @click="${() => { if (isCurrentMonth)
                this.selectDate(day, month, year); }}"
            >
              <span style="position:relative;">
                ${day}
                ${isCurrentDate(day, month, year) && isCurrentMonth ? html `<div class="current__date__dot" part="current-date-dot"></div>` : nothing}
              </span>
            </div>`;
        })}
        </div>
      </div>
    `;
    }
    /**
     * Function to validate if date is not in allowedDates range
     * @param day
     * @param month
     * @param year
     * @returns
     */
    isAllowedDate(day, month, year) {
        if (!this.allowedDatesLocal) {
            return true;
        }
        const dateToCheck = new Date(Date.UTC(year, month, day));
        const startDate = this.getUTCDate(this.allowedDatesLocal.startDate);
        const endDate = this.getUTCDate(this.allowedDatesLocal.endDate);
        endDate.setUTCHours(23, 59, 59, 999);
        const isWithinRange = dateToCheck >= startDate && dateToCheck <= endDate;
        return isWithinRange;
    }
    clearDate(mode) {
        const clearType = mode ??
            (this.range
                ? this.type === 'relative'
                    ? ClearMode.Relative
                    : ClearMode.Range
                : ClearMode.Single);
        if (clearType === ClearMode.Single) {
            this.value = null;
        }
        else {
            this.valueAttribute = '';
            this.startDate = null;
            this.endDate = null;
            this.selectedUnit = undefined;
            this.selectedValue = undefined;
        }
        this.requestUpdate();
        this.emit('nile-clear');
    }
    /**
     * @function handle_date-click/select
     * @param day
     * @param month
     * @param year
     */
    selectDate(day, month, year) {
        if (this.disabled)
            return;
        const selectedDate = new Date(year, month, day);
        if (this.range) {
            if (this.startDate && this.endDate) {
                this.startDate = null;
                this.endDate = null;
            }
            if (this.isSelectingStart) {
                this.startDate = selectedDate;
                if (this.endDate && selectedDate > this.endDate) {
                    this.endDate = null;
                }
                this.isSelectingStart = false;
            }
            else {
                this.isSelectingStart = true;
                if (this.startDate && selectedDate < this.startDate) {
                    this.startDate = selectedDate;
                    this.endDate = null;
                    this.isSelectingStart = false;
                }
                else {
                    const endDate = selectedDate;
                    endDate.setHours(23, 59, 59, 999);
                    this.endDate = endDate;
                }
            }
        }
        else {
            if (String(this.value) == String(selectedDate) && this.doubleClickUnselect) {
                this.clearDate();
                return;
            }
            this.value = selectedDate;
            this.emitChangedData({ value: this.value });
        }
    }
    /**
     * Function to be called on initialization to set all other properties
     */
    initializeValue() {
        if (this.range) {
            try {
                const rangeValue = JSON.parse(this.valueAttribute || '');
                this.startDate = new Date(rangeValue.startDate);
                this.endDate = new Date(rangeValue.endDate);
                // Convert to local time
                this.startDate = new Date(this.startDate.getTime());
                this.endDate = new Date(this.endDate.getTime());
                this.value = null;
            }
            catch (e) {
                // console.error('Invalid range value');
            }
        }
        else {
            if (this.valueAttribute) {
                let date = new Date(this.valueAttribute);
                date = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
                if (!isNaN(date.getTime())) {
                    this.value = date;
                    this.currentMonth = this.value.getMonth();
                    this.currentYear = this.value.getFullYear();
                }
            }
        }
    }
    /**
     * Function to handle relative date selection
     */
    handleDurationChange(event) {
        event.stopPropagation();
        event.detail.value = event.detail.value.replace(/e/gi, "");
        const duration = Number(event.detail.value);
        if (!duration) {
            return;
        }
        ;
        this.selectedValue = duration;
        if (this.selectedUnit && this.selectedValue) {
            this.handleTimeValueClick(this.selectedUnit, this.selectedValue, event);
        }
    }
    handleUnitChange(event) {
        event.stopPropagation();
        this.selectedUnit = event.detail.value;
        if (this.selectedUnit && this.selectedValue) {
            this.handleTimeValueClick(this.selectedUnit, this.selectedValue, event);
        }
    }
    handleTimeValueClick(unit, value, event) {
        this.createRelativePeriod(unit, value);
        this.selectedUnit = unit;
        this.selectedValue = value;
    }
    createRelativePeriod(unit, value) {
        const endTime = new Date();
        const startTime = new Date();
        switch (unit) {
            case 'minutes':
                startTime.setMinutes(startTime.getMinutes() - value);
                break;
            case 'hours':
                startTime.setHours(startTime.getHours() - value);
                break;
            case 'days':
                startTime.setDate(startTime.getDate() - value);
                break;
            case 'weeks':
                startTime.setDate(startTime.getDate() - 7 * value); // Subtract weeks as days
                break;
            case 'months':
                startTime.setMonth(startTime.getMonth() - value);
                break;
        }
        this.startDate = new Date(startTime.getTime());
        this.endDate = new Date(endTime.getTime());
        return {
            startDate: this.startDate,
            endDate: this.endDate,
        };
    }
    /**
     * Function to handle start time selecion
     */
    handleStartTimeInput(event) {
        event.stopPropagation();
        if (!this.startDate) {
            this.startDate = null;
            return;
        }
        const time = this.parseTime(event.detail.value, this.startDate);
        if (time) {
            this.startDate = time;
        }
        else {
            this.startDate.setHours(0, 0, 0);
        }
        this.requestUpdate();
    }
    /**
     * Function to handle end time selecion
     */
    handleEndTimeInput(event) {
        event.stopPropagation();
        if (!this.endDate) {
            this.endDate = null;
            return;
        }
        const time = this.parseTime(event.detail.value, this.endDate);
        if (time) {
            this.endDate = time;
        }
        else {
            this.endDate.setHours(0, 0, 0);
        }
        this.requestUpdate();
    }
    // Parse time string to a Date object
    parseTime(input, date) {
        if (!this.isValidTimeInput(input)) {
            return null;
        }
        const [hour, minute, second] = input.split(':').map(Number);
        const newDate = new Date(date.getTime());
        newDate.setHours(hour, minute, second);
        return newDate;
    }
    // Validate time in HH:MM:SS format
    isValidTimeInput(input) {
        const regex = /^([0-1]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/;
        return regex.test(input);
    }
    formatTime(date) {
        if (!date)
            return '';
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${hours}:${minutes}:${seconds}`;
    }
    nextMonth() {
        if (this.disabled)
            return;
        if (this.currentMonth === 11) {
            const newYear = this.currentYear + 1;
            if (this.endYear !== undefined && newYear > this.endYear)
                return;
            this.currentMonth = 0;
            this.currentYear = newYear;
        }
        else {
            this.currentMonth++;
        }
    }
    prevMonth() {
        if (this.disabled)
            return;
        if (this.currentMonth === 0) {
            const newYear = this.currentYear - 1;
            if (this.startYear !== undefined && newYear < this.startYear)
                return;
            this.currentMonth = 11;
            this.currentYear = newYear;
        }
        else {
            this.currentMonth--;
        }
    }
    confimRange() {
        if (!(this.startDate && this.endDate))
            return;
        this.emitChangedData({
            startDate: this.startDate,
            endDate: this.endDate,
        });
    }
    onTypeChange(event) {
        if (this.disabled)
            return;
        this.type = event.detail.value;
        this.emit('nile-type-change', { value: this.type });
    }
    getUTCDate(dateStr) {
        return new Date(Date.UTC(dateStr.slice(0, 4), dateStr.slice(5, 7) - 1, dateStr.slice(8, 10)));
    }
    emitChangedData(data) {
        this.emit('nile-changed', data); // deprecated. Use nile-change instead
        this.emit('nile-change', data);
    }
    getDaysArray(year, month) {
        const daysInMonth = new Date(year, month + 1, 0).getDate();
        return Array.from({ length: daysInMonth }, (_, i) => i + 1);
    }
};
__decorate([
    property({ type: String, attribute: 'value' })
], NileCalendar.prototype, "valueAttribute", void 0);
__decorate([
    property({ type: String, attribute: true, reflect: true })
], NileCalendar.prototype, "allowedDates", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], NileCalendar.prototype, "range", void 0);
__decorate([
    property({ type: Boolean, attribute: true, reflect: true })
], NileCalendar.prototype, "hideTypes", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], NileCalendar.prototype, "doubleClickUnselect", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], NileCalendar.prototype, "allowClear", void 0);
__decorate([
    property({ type: String, reflect: true })
], NileCalendar.prototype, "type", void 0);
__decorate([
    property({ type: String })
], NileCalendar.prototype, "selectedUnit", void 0);
__decorate([
    property({ type: Number })
], NileCalendar.prototype, "selectedValue", void 0);
__decorate([
    property({ type: Array, attribute: 'hide-duration-fields' })
], NileCalendar.prototype, "hideDurationFields", void 0);
__decorate([
    property({ type: Boolean })
], NileCalendar.prototype, "showManualInputs", void 0);
__decorate([
    property({ type: Number, attribute: true, reflect: true })
], NileCalendar.prototype, "startYear", void 0);
__decorate([
    property({ type: Number, attribute: true, reflect: true })
], NileCalendar.prototype, "endYear", void 0);
__decorate([
    property({ type: Boolean, attribute: true, reflect: true })
], NileCalendar.prototype, "showMonthDropdown", void 0);
__decorate([
    property({ type: Boolean, attribute: true, reflect: true })
], NileCalendar.prototype, "showYearDropdown", void 0);
__decorate([
    property({ type: String, reflect: true, attribute: true })
], NileCalendar.prototype, "dateFormat", void 0);
__decorate([
    state()
], NileCalendar.prototype, "startDate", void 0);
__decorate([
    state()
], NileCalendar.prototype, "endDate", void 0);
__decorate([
    state()
], NileCalendar.prototype, "isSelectingStart", void 0);
__decorate([
    state()
], NileCalendar.prototype, "hideInput", void 0);
__decorate([
    state()
], NileCalendar.prototype, "value", void 0);
__decorate([
    state()
], NileCalendar.prototype, "currentMonth", void 0);
__decorate([
    state()
], NileCalendar.prototype, "currentYear", void 0);
__decorate([
    state()
], NileCalendar.prototype, "allowedDatesLocal", void 0);
__decorate([
    property({ type: Boolean, attribute: true, reflect: true })
], NileCalendar.prototype, "disabled", void 0);
__decorate([
    watch('allowedDates')
], NileCalendar.prototype, "checkValidAllowedDate", null);
NileCalendar = __decorate([
    customElement('nile-calendar')
], NileCalendar);
export { NileCalendar };
export default NileCalendar;
//# sourceMappingURL=nile-calendar.js.map