document.addEventListener('DOMContentLoaded', function () {
    const calendarGrid = document.getElementById('calendarGrid');
    const currentMonthDisplay = document.getElementById('currentMonthDisplay');
    const prevBtn = document.getElementById('prevMonth');
    const nextBtn = document.getElementById('nextMonth');
    const todayBtn = document.getElementById('todayBtn');
    const viewButtons = document.querySelectorAll('.view-toggle button');

    let currentDate = new Date();
    // Normalize time
    currentDate.setHours(0, 0, 0, 0);

    let currentView = 'month'; // month, week, day
    let events = [];

    const monthNames = ["January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"
    ];

    function fetchInterviews() {
        fetch('api/interviews.php')
            .then(response => response.json())
            .then(data => {
                if (Array.isArray(data)) {
                    events = data.map(item => {
                        const d = new Date(item.scheduled_at);
                        return {
                            date: d,
                            day: d.getDate(),
                            month: d.getMonth(),
                            year: d.getFullYear(),
                            hour: d.getHours(),
                            minute: d.getMinutes(),
                            title: `${formatTime(d)} - ${item.candidate_name}`,
                            type: 'interview',
                            status: item.status,
                            candidateId: item.candidate_id
                        };
                    });
                    render();
                }
            })
            .catch(err => console.error('Error fetching interviews:', err));
    }

    function formatTime(date) {
        return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    }

    // View Toggle Logic
    viewButtons.forEach(btn => {
        btn.addEventListener('click', () => {
            // Update UI
            viewButtons.forEach(b => b.classList.remove('active'));
            btn.classList.add('active');

            // Update State
            currentView = btn.textContent.toLowerCase().trim();
            render();
        });
    });

    // Navigation logic based on view
    prevBtn.addEventListener('click', () => {
        if (currentView === 'month') {
            currentDate.setMonth(currentDate.getMonth() - 1);
        } else if (currentView === 'week') {
            currentDate.setDate(currentDate.getDate() - 7);
        } else if (currentView === 'day') {
            currentDate.setDate(currentDate.getDate() - 1);
        }
        render();
    });

    nextBtn.addEventListener('click', () => {
        if (currentView === 'month') {
            currentDate.setMonth(currentDate.getMonth() + 1);
        } else if (currentView === 'week') {
            currentDate.setDate(currentDate.getDate() + 7);
        } else if (currentView === 'day') {
            currentDate.setDate(currentDate.getDate() + 1);
        }
        render();
    });

    todayBtn.addEventListener('click', () => {
        currentDate = new Date();
        currentDate.setHours(0, 0, 0, 0);
        render();
    });

    // Main Render Function
    function render() {
        if (currentView === 'month') {
            renderMonthView();
        } else if (currentView === 'week') {
            renderWeekView();
        } else if (currentView === 'day') {
            renderDayView();
        }
    }

    // --- MONTH VIEW ---
    function renderMonthView() {
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth();

        currentMonthDisplay.textContent = `${monthNames[month]} ${year}`;
        calendarGrid.className = 'calendar-grid'; // Reset class
        calendarGrid.innerHTML = "";

        // Headers
        const daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
        daysOfWeek.forEach(day => {
            const header = document.createElement('div');
            header.className = 'calendar-header';
            header.textContent = day;
            calendarGrid.appendChild(header);
        });

        const firstDay = new Date(year, month, 1).getDay();
        const daysInMonth = new Date(year, month + 1, 0).getDate();
        const prevMonthDays = new Date(year, month, 0).getDate();
        const today = new Date();

        // Previous month padding
        for (let i = firstDay - 1; i >= 0; i--) {
            const dayDiv = document.createElement('div');
            dayDiv.className = 'calendar-day opacity-50';
            dayDiv.innerHTML = `<span class="day-number">${prevMonthDays - i}</span>`;
            calendarGrid.appendChild(dayDiv);
        }

        // Current days
        for (let i = 1; i <= daysInMonth; i++) {
            const dayDiv = document.createElement('div');
            dayDiv.className = 'calendar-day';

            if (i === today.getDate() && month === today.getMonth() && year === today.getFullYear()) {
                dayDiv.classList.add('today');
            }

            let dayContent = `<span class="day-number">${i}</span>`;

            // Events
            const dayEvents = events.filter(e =>
                e.day === i && e.month === month && e.year === year
            );

            dayEvents.forEach(evt => {
                dayContent += createEventCard(evt);
            });

            dayDiv.innerHTML = dayContent;
            calendarGrid.appendChild(dayDiv);
        }

        // Next month padding logic omitted for brevity as grid usually handles itself, 
        // but ensuring strict 7x6 grid:
        const totalUsed = firstDay + daysInMonth;
        const remaining = 42 - totalUsed; // 6 rows * 7 cols
        for (let i = 1; i <= remaining; i++) {
            const dayDiv = document.createElement('div');
            dayDiv.className = 'calendar-day opacity-50';
            dayDiv.innerHTML = `<span class="day-number">${i}</span>`;
            calendarGrid.appendChild(dayDiv);
        }
    }

    // --- WEEK VIEW ---
    function renderWeekView() {
        // Find Sunday of current week
        const startOfWeek = new Date(currentDate);
        startOfWeek.setDate(currentDate.getDate() - currentDate.getDay());

        const endOfWeek = new Date(startOfWeek);
        endOfWeek.setDate(startOfWeek.getDate() + 6);

        // Display Range
        const startMonth = monthNames[startOfWeek.getMonth()];
        const endMonth = monthNames[endOfWeek.getMonth()];
        if (startMonth === endMonth) {
            currentMonthDisplay.textContent = `${startMonth} ${startOfWeek.getDate()} - ${endOfWeek.getDate()}, ${startOfWeek.getFullYear()}`;
        } else {
            currentMonthDisplay.textContent = `${startMonth} ${startOfWeek.getDate()} - ${endMonth} ${endOfWeek.getDate()}, ${endOfWeek.getFullYear()}`;
        }

        calendarGrid.innerHTML = "";
        // Use a flex layout or just force standard grid to look like columns
        // For simple week view, we can just use 7 columns.
        calendarGrid.style.display = 'grid';
        calendarGrid.style.gridTemplateColumns = 'repeat(7, 1fr)';
        calendarGrid.style.gap = '1px'; // border handling

        const daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

        // Headers
        daysOfWeek.forEach((day, index) => {
            const currentDayDate = new Date(startOfWeek);
            currentDayDate.setDate(startOfWeek.getDate() + index);

            const header = document.createElement('div');
            header.className = 'calendar-header';
            // Highlight today in header
            const today = new Date();
            if (isSameDay(currentDayDate, today)) {
                header.style.background = '#eef2ff';
                header.style.color = 'var(--primary-color)';
            }
            header.textContent = `${day} ${currentDayDate.getDate()}`;
            calendarGrid.appendChild(header);
        });

        // Days columns
        for (let i = 0; i < 7; i++) {
            const currentDayDate = new Date(startOfWeek);
            currentDayDate.setDate(startOfWeek.getDate() + i);

            const dayDiv = document.createElement('div');
            dayDiv.className = 'calendar-day';
            dayDiv.style.minHeight = '400px'; // Taller for week view

            // Filter events for this day
            const dayEvents = events.filter(e => isSameDay(e.date, currentDayDate));

            dayEvents.forEach(evt => {
                dayDiv.innerHTML += createEventCard(evt);
            });

            calendarGrid.appendChild(dayDiv);
        }
    }

    // --- DAY VIEW ---
    function renderDayView() {
        const dayName = currentDate.toLocaleDateString('en-US', { weekday: 'long' });
        currentMonthDisplay.textContent = `${dayName}, ${monthNames[currentDate.getMonth()]} ${currentDate.getDate()}, ${currentDate.getFullYear()}`;

        calendarGrid.innerHTML = "";
        calendarGrid.style.display = 'block'; // List view basically

        const todayEvents = events.filter(e => isSameDay(e.date, currentDate));

        if (todayEvents.length === 0) {
            calendarGrid.innerHTML = `
                <div style="padding: 3rem; text-align: center; color: #94a3b8;">
                    <i class="fa-regular fa-calendar-xmark" style="font-size: 2rem; margin-bottom: 1rem;"></i>
                    <p>No interviews scheduled for this day.</p>
                </div>
            `;
            return;
        }

        // Sort by time
        todayEvents.sort((a, b) => a.date - b.date);

        todayEvents.forEach(evt => {
            const card = document.createElement('div');
            card.className = 'event-card';
            card.style.cursor = 'pointer';
            card.style.marginBottom = '10px';
            card.style.padding = '15px';
            card.style.fontSize = '1em';

            card.innerHTML = `
                <div class="flex justify-between items-center">
                    <div class="font-bold text-lg">${formatTime(evt.date)}</div>
                    <span class="badge badge-info">${evt.status}</span>
                </div>
                <div class="mt-2 text-primary font-medium">${evt.title.split(' - ')[1]}</div>
            `;

            card.onclick = () => window.location.href = `candidate-detail.html?id=${evt.candidateId}`;
            calendarGrid.appendChild(card);
        });
    }

    // Helper
    function createEventCard(evt) {
        return `
            <div class="event-card" style="cursor: pointer;" title="${evt.title}" onclick="window.location.href='candidate-detail.html?id=${evt.candidateId}'">
                ${evt.title}
            </div>
        `;
    }

    function isSameDay(d1, d2) {
        return d1.getFullYear() === d2.getFullYear() &&
            d1.getMonth() === d2.getMonth() &&
            d1.getDate() === d2.getDate();
    }

    // Initial load
    fetchInterviews();
});
