Code viewer for World: display
// for stling purposes
const container = document.createElement('div');
container.style.margin = '0';
container.style.overflow = 'hidden';
container.style.fontFamily = 'Arial, sans-serif';
container.style.color = '#fff';
container.style.textAlign = 'center';
container.style.backgroundSize = 'cover';
container.style.backgroundRepeat = 'no-repeat';
container.style.transition = 'background-image 1s ease-in-out';
container.style.display = 'flex';
container.style.alignItems = 'center';
container.style.justifyContent = 'center';
container.style.height = '100vh';


const apiKey = '798c86aa4939906b096b1a604d8b3e45';
let city = ''; // Default city is empty to allow for automatic detection
let units = 'metric'; // Default to metric units

// Function to get user's location using Geolocation API
function getUserLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(position => {
            const { latitude, longitude } = position.coords;
            fetchCityByCoordinates(latitude, longitude);
        }, error => {
            console.error('Error getting user location:', error);
            // set a default location if location cant be determined
            city = 'madrid';
            fetchDataAndDisplay();
        });
    } 
}

// Function to fetch city name with OpenWeatherMap
function fetchCityByCoordinates(latitude, longitude) {
    const reverseGeocodingUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${apiKey}`;
    fetch(reverseGeocodingUrl)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            city = data.name;
            fetchDataAndDisplay();
        })
        .catch(error => {
            console.error('Error fetching city name:', error);
            // Handle error or set a default location
            city = 'madrid';
            fetchDataAndDisplay();
        });
}


function setDynamicBackground() {
    const now = new Date();
    const hours = now.getHours();
    let backgroundImageUrl;

    if (hours >= 6 && hours < 18) {
        backgroundImageUrl = '/uploads/coynetn2/daytime.jpeg';
    } else {
        backgroundImageUrl = '/uploads/coynetn2/nightime.jpg';
    }

    container.style.backgroundImage = `url(${backgroundImageUrl})`;
}

function updateTemperatureUnit(temperature) {
    return units === 'metric' ? `${temperature}°C` : `${(temperature * 9/5) + 32}°F`;
}

function createWeatherDisplay(data) {
    const weatherCard = document.createElement('div');
    weatherCard.className = 'weather-card';

    const cardHeader = document.createElement('div');
    cardHeader.className = 'card-header';
    cardHeader.innerHTML = `<h1 style="font-size: 24px;">Weather in ${city}</h1>`;
    weatherCard.appendChild(cardHeader);

    const weatherIcon = document.createElement('div');
    weatherIcon.className = 'weather-icon';
    weatherIcon.innerHTML = `<img src="${data.iconUrl}" alt="Weather Icon">`;
    weatherCard.appendChild(weatherIcon);

    const temperatureParagraph = document.createElement('p');
    temperatureParagraph.className = 'temperature';
    temperatureParagraph.innerHTML = updateTemperatureUnit(data.temperature);
    weatherCard.appendChild(temperatureParagraph);

    const detailsParagraph = document.createElement('p');
    detailsParagraph.className = 'weather-details';
    detailsParagraph.innerHTML = `
        Description: ${data.description}<br>
        Humidity: ${data.humidity}%<br>
        Wind Speed: ${data.windSpeed} m/s<br>
        Pressure: ${data.pressure} hPa`;
    weatherCard.appendChild(detailsParagraph);

    container.appendChild(weatherCard);
}

function createWeatherDisplayForecast(forecastData) {
    const forecastContainer = document.createElement('div');
    forecastContainer.className = 'forecast-container';

    forecastContainer.style.marginLeft = '50px';
    
    const forecastHeading = document.createElement('h2');
    forecastHeading.innerText = 'Forecast:';
    forecastContainer.appendChild(forecastHeading);
    
    const dailyTemperatures = {};

    for (const forecast of forecastData.list) {
        const forecastTime = new Date(forecast.dt * 1000);
        const forecastDay = forecastTime.toLocaleDateString('en-US', { weekday: 'long' });

        if (!dailyTemperatures[forecastDay]) {
            dailyTemperatures[forecastDay] = [];
        }

        dailyTemperatures[forecastDay].push(forecast.main.temp);
    }

    for (const day in dailyTemperatures) {
        const averageTemperature = calculateAverage(dailyTemperatures[day]);

        const forecastCard = document.createElement('div');
        forecastCard.className = 'forecast-card';

        forecastCard.innerHTML = `
            <p class="forecast-day">${day}</p>
            <p class="forecast-temperature">${updateTemperatureUnit(averageTemperature.toFixed(0))}</p>
        `;

        forecastContainer.appendChild(forecastCard);
    }

    container.appendChild(forecastContainer);
}

function playWeatherSoundEffect(description) {
    
    // MH edit
    console.log ( "playing sound effect " + description );
    
    const soundEffects = {
        'clear sky': '/uploads/coynetn2/SpringBirdsChirpingSoundEffectFREEDOWNLOAD.mp3',
        'rain': '/uploads/coynetn2/RainSoundFor1minute.mp3',
        'scattered clouds': '/uploads/coynetn2/SpringBirdsChirpingSoundEffectFREEDOWNLOAD.mp3',
    };

    const soundUrl = soundEffects[description.toLowerCase()];
    
    if (soundUrl) {
        const sound = new Audio(soundUrl);
        sound.volume = 0.5;
        sound.play();
    }
}

function calculateAverage(numbers) {
    const sum = numbers.reduce((acc, num) => acc + num, 0);
    return sum / numbers.length;
}

function fetchDataAndDisplay() {
    const currentWeatherUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=${units}`;
    const forecastUrl = `https://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=${apiKey}&units=${units}`;

    fetch(currentWeatherUrl)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            const temperature = data.main.temp;
            const description = data.weather[0].description;
            const iconUrl = `http://openweathermap.org/img/w/${data.weather[0].icon}.png`;
            const humidity = data.main.humidity;
            const windSpeed = data.wind.speed;
            const pressure = data.main.pressure;

            setDynamicBackground();
            createWeatherDisplay({
                iconUrl,
                temperature: updateTemperatureUnit(temperature),
                description,
                humidity,
                windSpeed,
                pressure,
            });
            
            playWeatherSoundEffect(description);
            
            fetch(forecastUrl)
                .then(response => response.json())
                .then(forecastData => {
                    setDynamicBackground();
                    createWeatherDisplayForecast(forecastData);
                })
                .catch(error => console.error('Error fetching forecast data:', error));
        })
        .catch(error => console.error('Error fetching current weather data:', error));
}

// Call getUserLocation to start location detection when the page loads
getUserLocation();

// Append the container to the body of the document
document.body.appendChild(container);