// Update intervals (in milliseconds)
const INTERVALS = {
    TIME: 1000,              // 1 second
    WEATHER: 900000,         // 15 minutes
    CALENDAR: 300000,        // 5 minutes
    BACKGROUND: 60000,       // 1 minute
    JOKE: 3600000           // 1 hour
};

// Weather icon mapping (OpenWeatherMap icons to emoji or text)
const WEATHER_ICONS = {
    '01d': '☀️', '01n': '🌙',
    '02d': '⛅', '02n': '☁️',
    '03d': '☁️', '03n': '☁️',
    '04d': '☁️', '04n': '☁️',
    '09d': '🌧️', '09n': '🌧️',
    '10d': '🌦️', '10n': '🌧️',
    '11d': '⛈️', '11n': '⛈️',
    '13d': '❄️', '13n': '❄️',
    '50d': '🌫️', '50n': '🌫️'
};

// Initialize the application
document.addEventListener('DOMContentLoaded', () => {
    // Start all update functions
    updateTime();
    updateWeather();
    updateCalendar();
    updateBackground();
    updateJoke();

    // Set up intervals
    setInterval(updateTime, INTERVALS.TIME);
    setInterval(updateWeather, INTERVALS.WEATHER);
    setInterval(updateCalendar, INTERVALS.CALENDAR);
    setInterval(updateBackground, INTERVALS.BACKGROUND);
    setInterval(updateJoke, INTERVALS.JOKE);
});

// Update time and date
function updateTime() {
    const now = new Date();

    // Format time (HH:MM)
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    document.getElementById('time').textContent = `${hours}:${minutes}`;

    // Format date (Day, Month Date)
    const options = { weekday: 'long', month: 'long', day: 'numeric' };
    const dateString = now.toLocaleDateString('en-NZ', options);
    document.getElementById('date').textContent = dateString;
}

// Fetch and update weather
async function updateWeather() {
    try {
        const response = await fetch('/api/weather');
        if (!response.ok) throw new Error('Weather fetch failed');

        const data = await response.json();

        if (data.error) {
            console.error('Weather error:', data.error);
            return;
        }

        // Update current weather in header
        const { current, forecast } = data;

        document.getElementById('current-temp').textContent = `${current.temp}°`;
        document.getElementById('weather-icon').textContent = WEATHER_ICONS[current.icon] || '🌤️';

        // Update 3-day forecast in header
        const headerForecast = document.getElementById('header-forecast');
        headerForecast.innerHTML = '';

        forecast.forEach(day => {
            const dayElement = document.createElement('div');
            dayElement.className = 'forecast-item';
            dayElement.innerHTML = `
                <div class="weather-label">${day.date}</div>
                <div class="forecast-icon">${WEATHER_ICONS[day.icon] || '🌤️'}</div>
                <div class="forecast-temps">
                    <span class="high">${day.temp_max}°</span>
                    <span class="low">${day.temp_min}°</span>
                </div>
            `;
            headerForecast.appendChild(dayElement);
        });

    } catch (error) {
        console.error('Error updating weather:', error);
    }
}

// Fetch and update calendar events
async function updateCalendar() {
    try {
        const response = await fetch('/api/calendar');
        if (!response.ok) throw new Error('Calendar fetch failed');

        const events = await response.json();

        if (events.error) {
            console.error('Calendar error:', events.error);
            return;
        }

        const eventsContainer = document.getElementById('calendar-events');

        if (!events || events.length === 0) {
            eventsContainer.innerHTML = '<div class="event-placeholder">No upcoming events</div>';
            return;
        }

        // Group events by day
        const eventsByDay = {};
        const today = new Date();
        today.setHours(0, 0, 0, 0);

        // Create 5 days (today + 4 more)
        for (let i = 0; i < 5; i++) {
            const date = new Date(today);
            date.setDate(today.getDate() + i);
            const dateKey = date.toISOString().split('T')[0];
            eventsByDay[dateKey] = {
                date: date,
                events: []
            };
        }

        // Group events by their date (including multi-day events)
        events.forEach(event => {
            const eventStart = new Date(event.start);
            const eventEnd = new Date(event.end);
            eventStart.setHours(0, 0, 0, 0);
            eventEnd.setHours(0, 0, 0, 0);

            // Check each day in our 5-day view
            Object.keys(eventsByDay).forEach(dateKey => {
                const dayDate = new Date(eventsByDay[dateKey].date);
                dayDate.setHours(0, 0, 0, 0);

                // Include event if this day falls within the event's duration
                if (dayDate >= eventStart && dayDate <= eventEnd) {
                    eventsByDay[dateKey].events.push(event);
                }
            });
        });

        // Render events grouped by day
        eventsContainer.innerHTML = '';

        Object.keys(eventsByDay).sort().forEach(dateKey => {
            const dayData = eventsByDay[dateKey];
            const dayElement = document.createElement('div');
            dayElement.className = 'day-group';

            // Format day header
            const dayDate = dayData.date;
            const isToday = dayDate.toDateString() === new Date().toDateString();
            const dayName = isToday ? 'Today' : dayDate.toLocaleDateString('en-NZ', { weekday: 'long' });
            const dateStr = dayDate.toLocaleDateString('en-NZ', { day: 'numeric', month: 'short' });

            dayElement.innerHTML = `
                <div class="day-header">
                    <span class="day-name">${dayName}</span>
                    <span class="day-date">${dateStr}</span>
                </div>
                <div class="day-events"></div>
            `;

            const dayEventsContainer = dayElement.querySelector('.day-events');

            if (dayData.events.length === 0) {
                dayEventsContainer.innerHTML = '<div class="no-events">No events</div>';
            } else {
                dayData.events.forEach(event => {
                    const eventElement = document.createElement('div');
                    eventElement.className = 'event';

                    const startTime = new Date(event.start);
                    const endTime = new Date(event.end);

                    // Check if it's an all-day event (time is 00:00)
                    const isAllDay = startTime.getHours() === 0 && startTime.getMinutes() === 0
                                   && endTime.getHours() === 0 && endTime.getMinutes() === 0;

                    let timeString;
                    if (isAllDay) {
                        timeString = 'All day';
                    } else {
                        timeString = startTime.toLocaleTimeString('en-NZ', { hour: '2-digit', minute: '2-digit' });
                    }

                    eventElement.innerHTML = `
                        <div class="event-time">${timeString}</div>
                        <div class="event-title">${event.title}</div>
                        ${event.location ? `<div class="event-location">📍 ${event.location}</div>` : ''}
                    `;

                    dayEventsContainer.appendChild(eventElement);
                });
            }

            eventsContainer.appendChild(dayElement);
        });

    } catch (error) {
        console.error('Error updating calendar:', error);
    }
}

// Update background image
async function updateBackground() {
    try {
        const response = await fetch('/api/background');
        if (!response.ok) throw new Error('Background fetch failed');

        const data = await response.json();
        const backgroundElement = document.getElementById('background');

        if (data.image) {
            // Preload image to avoid flicker
            const img = new Image();
            img.onload = () => {
                backgroundElement.style.backgroundImage = `url('${data.image}')`;
            };
            img.src = data.image;
        } else if (data.color) {
            backgroundElement.style.backgroundColor = data.color;
            backgroundElement.style.backgroundImage = 'none';
        }

    } catch (error) {
        console.error('Error updating background:', error);
    }
}

// Fetch and update dad joke
async function updateJoke() {
    try {
        const response = await fetch('/api/joke');
        if (!response.ok) throw new Error('Joke fetch failed');

        const data = await response.json();

        if (data.joke) {
            document.getElementById('joke').textContent = data.joke;
        }

    } catch (error) {
        console.error('Error updating joke:', error);
    }
}
