import { __decorate, __metadata } from "tslib";
import { LitElement, html, css } from 'lit';
import { customElement, state, property } from 'lit/decorators.js';
import moment from 'moment';
let EaasCalendar = class EaasCalendar extends LitElement {
    constructor() {
        super(...arguments);
        this.showCalendar = false;
        this.currentYear = new Date().getFullYear();
        this.currentMonth = new Date().getMonth();
        this.selectedDate = '';
        this.type = 'daily';
        this.title = '';
        this.hostStyle = '';
        this.displayFormat = '';
        // 외부 클릭 감지를 위해, 달력이 열려 있을 때 컴포넌트 외부 클릭 시 달력을 닫음
        this._handleOutsideClick = (e) => {
            const path = e.composedPath();
            // path 배열 중 'calendar-popup' 클래스를 가진 요소가 있는지 확인
            const isCalendarClick = path.some(el => el.classList?.contains('calendar-popup'));
            if (this.showCalendar && !isCalendarClick) {
                this.showCalendar = false;
            }
        };
    }
    static { this.styles = css `
    :host {
      position: relative;

      .calendar-container {
        display: flex;
        gap: var(--padding-narrow);
        position: relative;
        align-items: center;
      }

      label.title {
        align-content: center;
        color: var(--md-sys-color-surface-tint);
        font-size: 0.9em;
        white-space: nowrap;
      }

      /* 인풋 스타일 */
      .date-input {
        flex: 1;
        padding: var(--padding-default) var(--padding-wide);
        border-radius: 5px;
        border: none;
        background-color: rgba(0, 0, 0, 0.5);
        color: var(--md-sys-color-on-secondary);
        font-size: 1em;
        cursor: pointer;
        width: 100%;
      }
      .date-input:focus {
        outline: none;
      }
      md-icon {
        position: absolute;
        right: var(--padding-narrow);
        --md-icon-size: 20px;
        opacity: 0.7;
        margin-bottom: 2px;
      }

      /* 달력 팝업 - 기본 위치를 오른쪽(right)으로 설정 */
      .calendar-popup {
        position: absolute;
        top: 30px;
        right: 0;
        width: 300px;
        border: 2px solid var(--md-sys-color-tertiary);
        background-color: #111;
        color: var(--md-sys-color-on-secondary);
        border-radius: 10px;
        padding: var(--padding-wide);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
        z-index: 999;
      }

      .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: var(--margin-wide);
      }

      .month-year {
        font-weight: bold;
      }

      button {
        background: none;
        border: none;
        color: var(--md-sys-color-surface-tint);
        cursor: pointer;
        font-size: 1.2em;
      }
      button:hover {
        color: var(--md-sys-color-on-secondary);
      }
      .day-names,
      .dates {
        display: grid;
        grid-template-columns: repeat(7, 1fr);
        gap: var(--padding-narrow);
        text-align: center;
      }

      .day-names div {
        font-size: 0.9em;
        color: var(--md-sys-color-surface-tint);
      }

      .dates div {
        padding: var(--padding-narrow);
        border-radius: 5px;
        cursor: pointer;
        font-size: 0.9em;
      }
      .dates div:hover {
        background-color: #2a3258;
        font-weight: bold;
      }
      .selected {
        background-color: var(--md-sys-color-tertiary);
        font-weight: bold;
        font-size: 1em;
      }
      .inactive {
        color: #646a7f;
        cursor: default;
      }
      .inactive:hover {
        background-color: transparent;
      }
    }
    :host([type='month']) .dates {
      grid-template-columns: repeat(6, 1fr);
    }
  `; }
    connectedCallback() {
        super.connectedCallback();
    }
    disconnectedCallback() {
        document.removeEventListener('click', this._handleOutsideClick, { capture: true });
        super.disconnectedCallback();
    }
    updated(changedProperties) {
        if (changedProperties.has('showCalendar')) {
            if (this.showCalendar) {
                document.addEventListener('click', this._handleOutsideClick, { capture: true });
            }
            else {
                document.removeEventListener('click', this._handleOutsideClick, { capture: true });
            }
        }
        // selectedDate가 변경될 때 currentYear, currentMonth 동기화
        if (changedProperties.has('selectedDate')) {
            if (this.selectedDate) {
                const parts = this.selectedDate.split('-');
                if (parts.length >= 2) {
                    this.currentYear = parseInt(parts[0], 10);
                    this.currentMonth = parseInt(parts[1], 10) - 1;
                }
            }
            this.dispatchEvent(new CustomEvent('change', { detail: { value: this.selectedDate } }));
        }
        if (changedProperties.has('hostStyle')) {
            this.style.cssText = this.hostStyle;
        }
    }
    // 달력 계산 메서드
    getFirstDayOfMonth(year, month) {
        return new Date(year, month, 1).getDay(); // 0(일) ~ 6(토)
    }
    getDaysInMonth(year, month) {
        return new Date(year, month + 1, 0).getDate();
    }
    // 이전 달 / 다음 달 이동
    prevMonth() {
        if (this.currentMonth === 0) {
            this.currentMonth = 11;
            this.currentYear -= 1;
        }
        else {
            this.currentMonth -= 1;
        }
    }
    nextMonth() {
        if (this.currentMonth === 11) {
            this.currentMonth = 0;
            this.currentYear += 1;
        }
        else {
            this.currentMonth += 1;
        }
    }
    // 인풋 클릭 시 달력 토글 (이벤트 전파 차단 제거)
    toggleCalendar() {
        this.showCalendar = !this.showCalendar;
    }
    // 날짜 선택 시 값 업데이트 및 달력 닫기
    onSelectDate(day) {
        const month = this.currentMonth + 1; // 1~12
        const dayStr = String(day).padStart(2, '0');
        const monthStr = String(month).padStart(2, '0');
        this.selectedDate = `${this.currentYear}-${monthStr}-${dayStr}`;
        this.dispatchEvent(new CustomEvent('date-selected', { detail: { date: this.selectedDate } }));
        this.showCalendar = false;
    }
    onSelectMonth(month) {
        const monthStr = String(month + 1).padStart(2, '0');
        this.selectedDate = `${this.currentYear}-${monthStr}`;
        this.dispatchEvent(new CustomEvent('month-selected', { detail: { date: this.selectedDate } }));
        this.showCalendar = false;
    }
    prevYear() {
        this.currentYear -= 1;
    }
    nextYear() {
        this.currentYear += 1;
    }
    onSelectYear(year) {
        this.selectedDate = `${year}`;
        this.dispatchEvent(new CustomEvent('year-selected', { detail: { date: this.selectedDate } }));
        this.showCalendar = false;
    }
    render() {
        let displayValue = this.selectedDate;
        if (this.selectedDate && this.displayFormat) {
            displayValue = moment(this.selectedDate, this._getMomentParseFormat()).format(this.displayFormat);
        }
        return html `
      <div class="calendar-container" @click=${this.toggleCalendar}>
        ${this.title ? html `<label class="title">${this.title}</label>` : ''}
        <input class="date-input" type="text" .value=${displayValue} placeholder="날짜를 선택하세요" readonly />
        <md-icon>calendar_month</md-icon>
      </div>
      ${this.showCalendar ? this.renderCalendar() : ''}
    `;
    }
    renderCalendar() {
        if (this.type === 'monthly') {
            return this.drawMonthCalendar();
        }
        else if (this.type === 'yearly') {
            return this.drawYearCalendar();
        }
        else {
            return this.drawDateCalendar();
        }
    }
    drawDateCalendar() {
        const firstDay = this.getFirstDayOfMonth(this.currentYear, this.currentMonth);
        const daysInMonth = this.getDaysInMonth(this.currentYear, this.currentMonth);
        // 선택된 날짜 파싱 (형식: YYYY-MM-DD)
        let selectedYear = null;
        let selectedMonth = null;
        let selectedDay = null;
        if (this.selectedDate) {
            const parts = this.selectedDate.split('-');
            selectedYear = parseInt(parts[0], 10);
            selectedMonth = parseInt(parts[1], 10) - 1;
            selectedDay = parseInt(parts[2], 10);
        }
        const isSelected = (year, month, day) => selectedYear !== null &&
            selectedMonth !== null &&
            selectedDay !== null &&
            year === selectedYear &&
            month === selectedMonth &&
            day === selectedDay;
        // 달력에 표시할 날짜 배열 (빈 칸 포함)
        const days = [];
        for (let i = 0; i < firstDay; i++) {
            days.push({ dayNum: null });
        }
        for (let i = 1; i <= daysInMonth; i++) {
            days.push({ dayNum: i });
        }
        return html `
      <div class="calendar-popup">
        <div class="header">
          <button @click=${this.prevMonth}>«</button>
          <div class="month-year">${this.currentYear}년 ${String(this.currentMonth + 1).padStart(2, '0')}월</div>
          <button @click=${this.nextMonth}>»</button>
        </div>
        <div class="day-names">
          <div>일</div>
          <div>월</div>
          <div>화</div>
          <div>수</div>
          <div>목</div>
          <div>금</div>
          <div>토</div>
        </div>
        <div class="dates">
          ${days.map(item => {
            if (!item.dayNum) {
                return html `<div class="inactive"></div>`;
            }
            else {
                const classes = isSelected(this.currentYear, this.currentMonth, item.dayNum) ? 'selected' : '';
                return html `<div class="${classes}" @click=${() => this.onSelectDate(item.dayNum)}>${item.dayNum}</div>`;
            }
        })}
        </div>
      </div>
    `;
    }
    drawMonthCalendar() {
        let selectedYear = null;
        let selectedMonth = null;
        if (this.selectedDate) {
            const parts = this.selectedDate.split('-');
            if (parts.length >= 2) {
                selectedYear = parseInt(parts[0], 10);
                selectedMonth = parseInt(parts[1], 10);
            }
        }
        return html `
      <div class="calendar-popup">
        <div class="header">
          <button @click=${this.prevYear}>«</button>
          <div class="month-year">${this.currentYear}년</div>
          <button @click=${this.nextYear}>»</button>
        </div>
        <div class="dates">
          ${Array.from({ length: 12 }, (_, i) => {
            const monthValue = i + 1;
            const classes = selectedYear === this.currentYear && selectedMonth === monthValue ? 'selected' : '';
            return html `<div class="${classes}" @click=${() => this.onSelectMonth(i)}>${monthValue}월</div>`;
        })}
        </div>
      </div>
    `;
    }
    drawYearCalendar() {
        let selectedYear = null;
        if (this.selectedDate) {
            const parts = this.selectedDate.split('-');
            if (parts.length >= 1) {
                selectedYear = parseInt(parts[0], 10);
            }
        }
        // 현재 연도 기준으로 앞뒤 5년씩 표시
        const startYear = this.currentYear - 5;
        const years = Array.from({ length: 11 }, (_, i) => startYear + i);
        return html `
      <div class="calendar-popup">
        <div class="header">
          <button @click=${() => (this.currentYear -= 11)}>«</button>
          <div class="month-year">연도 선택</div>
          <button @click=${() => (this.currentYear += 11)}>»</button>
        </div>
        <div class="dates">
          ${years.map(year => {
            const classes = selectedYear === year ? 'selected' : '';
            return html `<div class="${classes}" @click=${() => this.onSelectYear(year)}>${year}년</div>`;
        })}
        </div>
      </div>
    `;
    }
    // moment 파싱 포맷 자동 결정 함수 추가
    _getMomentParseFormat() {
        if (this.type === 'monthly')
            return 'YYYY-MM';
        if (this.type === 'yearly')
            return 'YYYY';
        return 'YYYY-MM-DD';
    }
    // 외부에서 강제로 렌더링을 트리거할 수 있는 메소드
    renderCalendarInput(value) {
        const input = this.renderRoot?.querySelector('.date-input');
        if (input) {
            let displayValue = value;
            if (value && this.displayFormat) {
                displayValue = moment(value, this._getMomentParseFormat()).format(this.displayFormat);
            }
            input.value = displayValue;
        }
        this.requestUpdate();
    }
};
__decorate([
    state(),
    __metadata("design:type", Object)
], EaasCalendar.prototype, "showCalendar", void 0);
__decorate([
    state(),
    __metadata("design:type", Number)
], EaasCalendar.prototype, "currentYear", void 0);
__decorate([
    state(),
    __metadata("design:type", Number)
], EaasCalendar.prototype, "currentMonth", void 0);
__decorate([
    property({ type: String }),
    __metadata("design:type", String)
], EaasCalendar.prototype, "selectedDate", void 0);
__decorate([
    property({ type: String }),
    __metadata("design:type", String)
], EaasCalendar.prototype, "type", void 0);
__decorate([
    property({ type: String }),
    __metadata("design:type", String)
], EaasCalendar.prototype, "title", void 0);
__decorate([
    property({ type: String }),
    __metadata("design:type", String)
], EaasCalendar.prototype, "hostStyle", void 0);
__decorate([
    property({ type: String }),
    __metadata("design:type", String)
], EaasCalendar.prototype, "displayFormat", void 0);
EaasCalendar = __decorate([
    customElement('eaas-calendar')
], EaasCalendar);
export { EaasCalendar };
//# sourceMappingURL=eaas-calendar.js.map