/**
 * Interactive Single Calendar Date Range Picker for FlashSale
 */
class RangeCalendar {
    constructor(containerId, options = {}) {
        this.container = document.getElementById(containerId);
        if (!this.container) return;

        this.onSelect = options.onSelect || function() {};
        this.currentMonth = new Date();
        this.currentMonth.setDate(1);

        this.startDate = options.initialStart ? new Date(options.initialStart + 'T00:00:00') : null;
        this.endDate = options.initialEnd ? new Date(options.initialEnd + 'T00:00:00') : null;

        this.render();
    }

    formatDate(date) {
        if (!date) return '';
        const y = date.getFullYear();
        const m = String(date.getMonth() + 1).padStart(2, '0');
        const d = String(date.getDate()).padStart(2, '0');
        return `${y}-${m}-${d}`;
    }

    formatReadable(date) {
        if (!date) return '';
        return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
    }

    render() {
        const year = this.currentMonth.getFullYear();
        const month = this.currentMonth.getMonth();

        const monthName = this.currentMonth.toLocaleDateString('en-US', { month: 'long', year: 'numeric' });
        const firstDayIndex = new Date(year, month, 1).getDay();
        const daysInMonth = new Date(year, month + 1, 0).getDate();

        const today = new Date();
        today.setHours(0, 0, 0, 0);

        let html = `
            <div class="calendar-picker">
                <div class="calendar-header">
                    <button type="button" class="calendar-nav-btn" id="calPrev">&larr;</button>
                    <div class="calendar-title">${monthName}</div>
                    <button type="button" class="calendar-nav-btn" id="calNext">&rarr;</button>
                </div>
                <div class="calendar-weekdays">
                    <div>Sun</div><div>Mon</div><div>Tue</div><div>Wed</div><div>Thu</div><div>Fri</div><div>Sat</div>
                </div>
                <div class="calendar-days">
        `;

        for (let i = 0; i < firstDayIndex; i++) {
            html += `<div class="calendar-day is-disabled" style="opacity:0;"></div>`;
        }

        for (let d = 1; d <= daysInMonth; d++) {
            const dateObj = new Date(year, month, d);
            dateObj.setHours(0, 0, 0, 0);
            const dateIso = this.formatDate(dateObj);
            const isDisabled = dateObj < today;

            let classes = ['calendar-day'];
            if (isDisabled) classes.push('is-disabled');

            if (this.startDate && dateIso === this.formatDate(this.startDate)) {
                classes.push('is-start-date');
            }
            if (this.endDate && dateIso === this.formatDate(this.endDate)) {
                classes.push('is-end-date');
            }
            if (this.startDate && this.endDate && dateObj > this.startDate && dateObj < this.endDate) {
                classes.push('is-in-range');
            }

            html += `<div class="${classes.join(' ')}" data-date="${dateIso}">${d}</div>`;
        }

        html += `
                </div>
                <div class="range-display">
                    <div class="text-sm">
                        <span class="text-muted">Selected Window:</span>
                        <strong style="color:var(--color-primary);margin-left:6px;" id="calRangeText">
                            ${this.startDate ? this.formatReadable(this.startDate) : 'Tap a Start Date'}
                            ${this.endDate ? ' &rarr; ' + this.formatReadable(this.endDate) : ''}
                        </strong>
                    </div>
                    ${this.startDate ? `<button type="button" class="btn btn--ghost btn--sm" id="calClear" style="color:var(--color-error);padding:0 8px;">Reset</button>` : ''}
                </div>
            </div>
        `;

        this.container.innerHTML = html;
        this.bindEvents();
    }

    bindEvents() {
        const prevBtn = this.container.querySelector('#calPrev');
        const nextBtn = this.container.querySelector('#calNext');
        const clearBtn = this.container.querySelector('#calClear');

        if (prevBtn) {
            prevBtn.onclick = () => {
                this.currentMonth.setMonth(this.currentMonth.getMonth() - 1);
                this.render();
            };
        }
        if (nextBtn) {
            nextBtn.onclick = () => {
                this.currentMonth.setMonth(this.currentMonth.getMonth() + 1);
                this.render();
            };
        }
        if (clearBtn) {
            clearBtn.onclick = () => {
                this.startDate = null;
                this.endDate = null;
                this.render();
                this.onSelect(null, null);
            };
        }

        const dayEls = this.container.querySelectorAll('.calendar-day:not(.is-disabled)');
        dayEls.forEach(el => {
            el.onclick = () => {
                const clickedStr = el.getAttribute('data-date');
                if (!clickedStr) return;
                const clickedDate = new Date(clickedStr + 'T00:00:00');

                if (!this.startDate || (this.startDate && this.endDate)) {
                    this.startDate = clickedDate;
                    this.endDate = null;
                } else if (clickedDate < this.startDate) {
                    this.startDate = clickedDate;
                    this.endDate = null;
                } else {
                    this.endDate = clickedDate;
                }

                this.render();
                this.onSelect(
                    this.formatDate(this.startDate),
                    this.formatDate(this.endDate || this.startDate)
                );
            };
        });
    }
}
