// calendar.js — Calendar day/week/month views (CalendarState)
// Extracted from dashboard.html (lines 5157-5328)

// Calendar
// ============================================================
// CalendarState.view / .events / .accounts (namespaced above)

function switchCalendarView(view) {
    CalendarState.view = view;
    document.querySelectorAll('.cal-view-bar .mp-tab').forEach(t => t.classList.remove('active'));
    const tab = document.getElementById('cal-tab-' + view);
    if (tab) tab.classList.add('active');
    loadCalendar(view);
}

async function loadCalendar(view) {
    view = view || CalendarState.view;
    CalendarState.view = view;
    const daysMap = {day: 1, week: 7, month: 42};
    const days = daysMap[view] || 7;
    const container = document.getElementById('cal-content');
    container.innerHTML = '<div class="loading"><div class="spinner"></div></div>';

    try {
        const res = await apiFetch(API + '/api/calendar/events?days=' + days + '&view=' + view);
        const data = await res.json();
        CalendarState.events = data.events || [];
        CalendarState.accounts = data.accounts || [];
        _renderCalSources();
        if (view === 'day') _renderCalDay();
        else if (view === 'month') _renderCalMonth();
        else _renderCalWeek();
    } catch (e) {
        container.innerHTML = '<p class="cal-no-events">Failed to load calendar events.</p>';
    }
}

function _renderCalSources() {
    const el = document.getElementById('cal-sources');
    if (!CalendarState.accounts.length) { el.style.display = 'none'; return; }
    const icons = {google: 'fab fa-google', caldav: 'fas fa-cloud'};
    el.innerHTML = '<span>Sources:</span> ' + CalendarState.accounts.map(a => {
        const ic = icons[a.type] || 'fas fa-calendar';
        const label = a.label || a.type;
        return '<span class="cal-source-tag cal-' + escapeHtml(a.type) + '"><i class="' + ic + '"></i> ' + escapeHtml(label) + '</span>';
    }).join('');
    el.style.display = 'flex';
}

// _calFormatTime removed — use formatDate(str, 'time')

function _calEventChip(ev) {
    const allDay = ev.all_day;
    const cls = allDay ? 'cal-event cal-allday' : 'cal-event';
    const timeStr = allDay ? 'All day' : formatDate(ev.start, 'time');
    const title = escapeHtml(ev.summary || '(No title)');
    let tooltip = title;
    if (ev.location) tooltip += '\\n' + escapeHtml(ev.location);
    return '<div class="' + cls + '" title="' + tooltip + '">'
        + '<span class="cal-event-time">' + escapeHtml(timeStr) + '</span>'
        + title + '</div>';
}

function _renderCalDay() {
    const container = document.getElementById('cal-content');
    const today = new Date();
    today.setHours(0,0,0,0);

    let html = '<div class="cal-day-grid">';
    for (let h = 7; h <= 22; h++) {
        const label = (h < 10 ? '0' : '') + h + ':00';
        const hourEvents = CalendarState.events.filter(ev => {
            if (ev.all_day) return h === 7;
            try {
                const d = new Date(ev.start);
                return d.getHours() === h && _sameDay(d, today);
            } catch(e) { return false; }
        });
        html += '<div class="cal-hour-row">';
        html += '<div class="cal-hour-label">' + label + '</div>';
        html += '<div class="cal-hour-slot">' + hourEvents.map(_calEventChip).join('') + '</div>';
        html += '</div>';
    }
    html += '</div>';
    if (!CalendarState.events.length) html = '<p class="cal-no-events">No events today.</p>';
    container.innerHTML = html;
}

function _sameDay(a, b) {
    return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
}

function _renderCalWeek() {
    const container = document.getElementById('cal-content');
    const today = new Date();
    today.setHours(0,0,0,0);
    // Start from Monday of current week
    const dayOfWeek = today.getDay();
    const monday = new Date(today);
    monday.setDate(today.getDate() - ((dayOfWeek + 6) % 7));

    const dayNames = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
    let html = '<div class="cal-week-grid">';
    for (let i = 0; i < 7; i++) {
        const d = new Date(monday);
        d.setDate(monday.getDate() + i);
        const isToday = _sameDay(d, today);
        const hdrCls = isToday ? 'cal-week-header cal-today' : 'cal-week-header';
        const dateLabel = dayNames[i] + ' ' + d.getDate() + '/' + (d.getMonth()+1);
        const dayEvents = CalendarState.events.filter(ev => {
            try {
                const s = new Date(ev.start);
                return _sameDay(s, d);
            } catch(e) { return false; }
        });
        html += '<div class="cal-week-col">';
        html += '<div class="' + hdrCls + '">' + dateLabel + '</div>';
        html += '<div class="cal-week-events">';
        if (dayEvents.length) {
            dayEvents.sort((a,b) => {
                if (a.all_day && !b.all_day) return -1;
                if (!a.all_day && b.all_day) return 1;
                return String(a.start).localeCompare(String(b.start));
            });
            html += dayEvents.map(_calEventChip).join('');
        }
        html += '</div></div>';
    }
    html += '</div>';
    if (!CalendarState.events.length) html = '<p class="cal-no-events">No events this week.</p>';
    container.innerHTML = html;
}

function _renderCalMonth() {
    const container = document.getElementById('cal-content');
    const today = new Date();
    today.setHours(0,0,0,0);
    const year = today.getFullYear();
    const month = today.getMonth();

    // First day of month and grid start (Monday-based)
    const firstOfMonth = new Date(year, month, 1);
    const startDay = (firstOfMonth.getDay() + 6) % 7; // 0=Mon
    const gridStart = new Date(firstOfMonth);
    gridStart.setDate(gridStart.getDate() - startDay);

    const dayNames = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
    let html = '<div class="cal-month-grid">';
    // Header row
    dayNames.forEach(n => { html += '<div class="cal-month-header">' + n + '</div>'; });
    // 6 weeks
    for (let i = 0; i < 42; i++) {
        const d = new Date(gridStart);
        d.setDate(gridStart.getDate() + i);
        const isOther = d.getMonth() !== month;
        const isToday = _sameDay(d, today);
        const cellCls = isOther ? 'cal-month-cell cal-other-month' : 'cal-month-cell';
        const numCls = isToday ? 'cal-month-day-num cal-today' : 'cal-month-day-num';
        const dayEvents = CalendarState.events.filter(ev => {
            try { return _sameDay(new Date(ev.start), d); } catch(e) { return false; }
        });
        html += '<div class="' + cellCls + '">';
        html += '<div class="' + numCls + '">' + d.getDate() + '</div>';
        // Show up to 3 events, then +N more
        const show = dayEvents.slice(0, 3);
        show.forEach(ev => { html += _calEventChip(ev); });
        if (dayEvents.length > 3) {
            html += '<div style="font-size:0.7rem;color:var(--text-dim);">+' + (dayEvents.length - 3) + ' more</div>';
        }
        html += '</div>';
    }
    html += '</div>';
    container.innerHTML = html;
}

