// Update intervals (in milliseconds)
const INTERVALS = {
    TIME: 1000,              // 1 second
    WEATHER: 900000,         // 15 minutes
    CALENDAR: 300000,        // 5 minutes
    BACKGROUND: 300000,      // 5 minutes
    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
        const { current, forecast } = data;

        document.getElementById('current-temp').textContent = `${current.temp}°`;
        document.getElementById('weather-icon').textContent = WEATHER_ICONS[current.icon] || '🌤️';
        document.getElementById('weather-description').textContent = current.description;
        document.getElementById('feels-like').textContent = `${current.feels_like}°`;
        document.getElementById('humidity').textContent = `${current.humidity}%`;
        document.getElementById('wind-speed').textContent = `${current.wind_speed} km/h`;

        // Update forecast
        const forecastContainer = document.getElementById('forecast-container');
        forecastContainer.innerHTML = '';

        forecast.forEach(day => {
            const dayElement = document.createElement('div');
            dayElement.className = 'forecast-day';
            dayElement.innerHTML = `
                <div class="forecast-day-name">${day.date}</div>
                <div class="forecast-description">${day.description}</div>
                <div class="forecast-temp">
                    <span class="high">${day.temp_max}°</span>
                    <span class="low">${day.temp_min}°</span>
                </div>
            `;
            forecastContainer.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;
        }

        eventsContainer.innerHTML = '';

        events.forEach(event => {
            const eventElement = document.createElement('div');
            eventElement.className = 'event';

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

            // Format time
            const timeOptions = { hour: '2-digit', minute: '2-digit', weekday: 'short', day: 'numeric', month: 'short' };
            const timeString = startTime.toLocaleDateString('en-NZ', timeOptions);

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

            eventsContainer.appendChild(eventElement);
        });

    } 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);
    }
}
