/* calendar.js - 日历插件核心 */
(function(global) {
    class CalendarPlugin {
        constructor(options) {
            this.options = Object.assign({
                trigger: null,        // 触发按钮（必填）
                onSelect: null,       // 选中回调
                initialDate: null,    // 初始日期
                zIndex: 9999
            }, options);
            
            this.triggerEl = null;
            this.popupEl = null;
            this.isOpen = false;
            this.currentYear = 2026;
            this.currentMonth = 3;
            this.selectedDate = null;
            
            this.init();
        }
        
        init() {
            if (!this.options.trigger) {
                console.error('[CalendarPlugin] 缺少 trigger 参数');
                return;
            }
            
            this.triggerEl = typeof this.options.trigger === 'string' 
                ? document.querySelector(this.options.trigger)
                : this.options.trigger;
            
            if (!this.triggerEl) return;
            
            this.createPopup();
            this.bindEvents();
            this.handleInitialDate();
            
            // 窗口变化重新定位
            window.addEventListener('resize', () => this.isOpen && this.positionPopup());
            window.addEventListener('scroll', () => this.isOpen && this.positionPopup(), true);
        }
        
        handleInitialDate() {
            if (this.options.initialDate) {
                const parsed = this.parseDate(this.options.initialDate);
                if (parsed) {
                    this.selectedDate = parsed;
                    this.currentYear = parsed.year;
                    this.currentMonth = parsed.month;
                }
            }
            this.renderCalendar();
        }
        
        createPopup() {
            this.popupEl = document.createElement('div');
            this.popupEl.className = 'calendar-plugin-popup';
            this.popupEl.style.position = 'absolute';
            this.popupEl.style.zIndex = this.options.zIndex;
            this.popupEl.innerHTML = `
                <div class="calendar-plugin-inner">
                    <div class="calendar-nav-header">
                        <div class="nav-icon-btn lashen" data-action="prevMonth"><</div>
                        <span class="date-num" id="calYear">2026</span>
                        <span class="date-text">年</span>
                        <span class="date-num" id="calMonth">四</span>
                        <span class="date-text">月</span>
                        <div class="nav-icon-btn lashen" data-action="nextMonth">></div>
                    </div>
                    
                    <div class="week-row">
                        <div>日</div><div>一</div><div>二</div><div>三</div><div>四</div><div>五</div><div>六</div>
                    </div>
                    <div class="days-grid" id="calDaysGrid"></div>
                    <div class="nav-group">
                        <div class="flex">
                            <div type="button" class="nav-icon-btn lashen" data-action="prevYear" title="上一年"><<</div>
                            <div type="button" class="nav-icon-btn lashen" data-action="prevMonth" title="上一月"><</div>
                        </div>
                        <button type="button" class="nav-icon-btn today" data-action="today" title="今天">今天</button>
                        <div class="flex">
                            <div type="button" class="nav-icon-btn lashen" data-action="nextMonth" title="下一月">></div>
                            <div type="button" class="nav-icon-btn lashen" data-action="nextYear" title="下一年">>></div>
                        </div>
                    </div>
                    <button class="action-btn" data-action="clear">清空</button>
                </div>
            `;
            document.body.appendChild(this.popupEl);
        }
        
        bindEvents() {
            // 触发按钮点击
            this.triggerEl.addEventListener('click', (e) => {
                e.stopPropagation();
                this.toggle();
            });
            
            // 全局点击关闭
            document.addEventListener('click', (e) => {
                if (this.isOpen && this.popupEl && 
                    !this.popupEl.contains(e.target) && 
                    e.target !== this.triggerEl) {
                    this.close();
                }
            });
            
            // 按钮事件
            this.popupEl.querySelectorAll('[data-action]').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    e.stopPropagation();
                    this.handleAction(btn.dataset.action);
                });
            });
            
            // 日期点击委托
            this.popupEl.querySelector('#calDaysGrid').addEventListener('click', (e) => {
                const cell = e.target.closest('.day-cell');
                if (cell && cell.dataset.year) {
                    this.selectDate(
                        parseInt(cell.dataset.year),
                        parseInt(cell.dataset.month),
                        parseInt(cell.dataset.day)
                    );
                }
            });
        }
        
        handleAction(action) {
            switch(action) {
                case 'prevYear': this.currentYear--; break;
                case 'nextYear': this.currentYear++; break;
                case 'prevMonth':
                    this.currentMonth--;
                    if (this.currentMonth < 0) {
                        this.currentMonth = 11;
                        this.currentYear--;
                    }
                    break;
                case 'nextMonth':
                    this.currentMonth++;
                    if (this.currentMonth > 11) {
                        this.currentMonth = 0;
                        this.currentYear++;
                    }
                    break;
                case 'today':
                    const today = new Date();
                    this.selectDate(today.getFullYear(), today.getMonth(), today.getDate());
                    return;
                case 'clear':
                    this.selectedDate = null;
                    this.renderCalendar();
                    if (this.options.onSelect) this.options.onSelect('');
                    this.close();
                    return;
            }
            this.renderCalendar();
        }
        
        selectDate(year, month, day) {
            this.selectedDate = { year, month, day };
            this.renderCalendar();
            const dateStr = `${year}-${String(month+1).padStart(2,'0')}-${String(day).padStart(2,'0')}`;
            if (this.options.onSelect) this.options.onSelect(dateStr);
            this.close();
        }
        
        renderCalendar() {
            const year = this.currentYear;
            const month = this.currentMonth;
            const monthNames = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'];
            
            // 更新标题
            const titleEl = this.popupEl.querySelector('#calYearMonth');
            const calYear = this.popupEl.querySelector('#calYear');
            const calMonth = this.popupEl.querySelector('#calMonth');
            if (titleEl) titleEl.innerText = `${year}年 ${monthNames[month]}月`;
            if (calYear) calYear.innerText = year;
            if (calMonth) calMonth.innerText = monthNames[month];

            // 计算日期数组
            const firstDay = new Date(year, month, 1);
            const startWeekday = firstDay.getDay();
            const lastDate = new Date(year, month + 1, 0).getDate();
            const prevLastDate = new Date(year, month, 0).getDate();
            
            let days = [];
            
            // 上月
            for (let i = 0; i < startWeekday; i++) {
                let prevY = month === 0 ? year - 1 : year;
                let prevM = month === 0 ? 11 : month - 1;
                days.push({ year: prevY, month: prevM, day: prevLastDate - startWeekday + i + 1, isCurrent: false });
            }
            // 当月
            for (let i = 1; i <= lastDate; i++) {
                days.push({ year, month, day: i, isCurrent: true });
            }
            // 下月
            const remaining = 42 - days.length;
            for (let i = 1; i <= remaining; i++) {
                let nextY = month === 11 ? year + 1 : year;
                let nextM = month === 11 ? 0 : month + 1;
                days.push({ year: nextY, month: nextM, day: i, isCurrent: false });
            }
            
            // 渲染网格
            const grid = this.popupEl.querySelector('#calDaysGrid');
            grid.innerHTML = '';
            const today = new Date();
            
            days.forEach(d => {
                const cell = document.createElement('div');
                cell.className = 'day-cell';
                if (!d.isCurrent) cell.classList.add('other-month');
                if (this.selectedDate && this.selectedDate.year === d.year && 
                    this.selectedDate.month === d.month && this.selectedDate.day === d.day) {
                    cell.classList.add('selected');
                }
                cell.innerText = d.day;
                cell.dataset.year = d.year;
                cell.dataset.month = d.month;
                cell.dataset.day = d.day;
                grid.appendChild(cell);
            });
        }
        
        positionPopup() {
            const trigRect = this.triggerEl.getBoundingClientRect();
            const popRect = this.popupEl.getBoundingClientRect();
            let top = trigRect.bottom + window.scrollY + 6;
            let left = trigRect.left + window.scrollX;
            
            if (top + popRect.height > window.scrollY + window.innerHeight - 10) {
                top = trigRect.top + window.scrollY - popRect.height - 6;
                this.popupEl.classList.add('popup-arrow-bottom');
            } else {
                this.popupEl.classList.remove('popup-arrow-bottom');
            }
            
            if (left + popRect.width > window.scrollX + window.innerWidth - 8) {
                left = trigRect.right + window.scrollX - popRect.width;
            }
            
            this.popupEl.style.top = `${top}px`;
            this.popupEl.style.left = `${Math.max(left, window.scrollX + 4)}px`;
        }
        
        parseDate(dateStr) {
            const parts = dateStr.split('-');
            if (parts.length === 3) {
                return {
                    year: parseInt(parts[0]),
                    month: parseInt(parts[1]) - 1,
                    day: parseInt(parts[2])
                };
            }
            return null;
        }
        
        open() {
            if (this.isOpen) return;
            this.renderCalendar();
            this.positionPopup();
            this.popupEl.classList.add('open');
            this.isOpen = true;
        }
        
        close() {
            if (!this.isOpen) return;
            this.popupEl.classList.remove('open');
            this.isOpen = false;
        }
        
        toggle() {
            this.isOpen ? this.close() : this.open();
        }
        
        destroy() {
            if (this.popupEl) this.popupEl.remove();
        }
    }
    
    // 暴露到全局
    global.CalendarPlugin = CalendarPlugin;
})(window);