// Use relative URL - works everywhere (localhost and production) const API_BASE = '/api'; // Location for sunrise/sunset calculation const LATITUDE = 40.197; const LONGITUDE = -105.07661; let charts = {}; let previousTemp = null; let weatherEffectsActive = { rain: false, snow: false, lightning: false }; // Theme Management function initThemeSwitcher() { const savedTheme = localStorage.getItem('weather-theme') || 'static'; applyTheme(savedTheme); document.querySelectorAll('.theme-btn').forEach(btn => { btn.addEventListener('click', () => { const theme = btn.dataset.theme; applyTheme(theme); localStorage.setItem('weather-theme', theme); }); }); } function applyTheme(theme) { document.body.dataset.theme = theme; document.querySelectorAll('.theme-btn').forEach(btn => { btn.classList.toggle('active', btn.dataset.theme === theme); }); // Update sun times immediately to reflect new theme colors if (typeof updateSunTimes === 'function') { updateSunTimes(); } } // Weather Effects function createRain() { const container = document.getElementById('rain-container'); container.innerHTML = ''; for (let i = 0; i < 100; i++) { const drop = document.createElement('div'); drop.className = 'raindrop'; drop.style.left = Math.random() * 100 + '%'; drop.style.animationDuration = (Math.random() * 0.5 + 0.5) + 's'; drop.style.animationDelay = Math.random() * 2 + 's'; container.appendChild(drop); } container.classList.add('active'); weatherEffectsActive.rain = true; } function createSnow() { const container = document.getElementById('snow-container'); container.innerHTML = ''; for (let i = 0; i < 50; i++) { const flake = document.createElement('div'); flake.className = 'snowflake'; flake.style.left = Math.random() * 100 + '%'; flake.style.animationDuration = (Math.random() * 3 + 2) + 's'; flake.style.animationDelay = Math.random() * 5 + 's'; const swayDuration = (Math.random() * 2 + 2) + 's'; flake.style.setProperty('--sway-duration', swayDuration); container.appendChild(flake); } container.classList.add('active'); weatherEffectsActive.snow = true; } function triggerLightning() { const flash = document.getElementById('lightning-flash'); flash.classList.add('active'); setTimeout(() => flash.classList.remove('active'), 100); // Random second flash if (Math.random() > 0.5) { setTimeout(() => { flash.classList.add('active'); setTimeout(() => flash.classList.remove('active'), 50); }, 200); } } function clearWeatherEffects() { document.getElementById('rain-container').classList.remove('active'); document.getElementById('snow-container').classList.remove('active'); weatherEffectsActive.rain = false; weatherEffectsActive.snow = false; } function updateWeatherEffects(data) { clearWeatherEffects(); const temp = data.temperature; const precip = data.precipitation_24h; // Rain effect if (precip > 0.05 && temp > 35) { createRain(); } // Snow effect if (precip > 0.05 && temp <= 35) { createSnow(); } // Lightning (if we have strike data) if (data.lightning_strikes && data.lightning_strikes > 0) { setInterval(() => { if (Math.random() > 0.7) { triggerLightning(); } }, 5000); } } // Dynamic weather theming function updateWeatherTheme(data) { const hour = new Date().getHours(); const body = document.body; // Remove all theme classes body.classList.remove('clear-day', 'clear-night', 'cloudy', 'rain', 'sunrise', 'sunset'); // Check for precipitation if (data.precipitation_24h > 0.1) { body.classList.add('rain'); return; } // Check for sunrise/sunset (6-8am and 5-7pm) if ((hour >= 6 && hour < 8) || (hour >= 17 && hour < 19)) { body.classList.add('sunrise'); return; } // Day vs night if (hour >= 7 && hour < 19) { // Daytime - check if cloudy based on solar radiation if (data.solar_radiation < 200) { body.classList.add('cloudy'); } else { body.classList.add('clear-day'); } } else { // Nighttime body.classList.add('clear-night'); } } function getWeatherEmoji(data) { const hour = new Date().getHours(); const precip = data.precipitation_24h || 0; const temp = data.temperature || 70; if (precip > 0.1) { if (temp < 35) return '🌨️'; if (precip > 0.5) return '⛈️'; return '🌧️'; } if (hour >= 6 && hour < 8 || hour >= 17 && hour < 19) { return '🌅'; } if (hour >= 7 && hour < 19) { if (data.solar_radiation < 200) return '⛅'; return '☀️'; } return '🌙'; } function formatValue(value, precision = 1) { if (value === null || value === undefined) return '--'; return typeof value === 'number' ? value.toFixed(precision) : value; } function formatUptime(seconds) { if (!seconds) return '--'; const days = Math.floor(seconds / 86400); const hours = Math.floor((seconds % 86400) / 3600); const minutes = Math.floor((seconds % 3600) / 60); if (days > 0) { return `${days}d ${hours}h`; } else if (hours > 0) { return `${hours}h ${minutes}m`; } else { return `${minutes}m`; } } function formatTimestamp(isoString) { if (!isoString) return '--'; const date = new Date(isoString); const now = new Date(); const diffSeconds = Math.floor((now - date) / 1000); // Handle clock skew (server time ahead of client) if (diffSeconds < 0) return 'just now'; if (diffSeconds < 60) return `${diffSeconds}s ago`; if (diffSeconds < 3600) return `${Math.floor(diffSeconds / 60)}m ago`; if (diffSeconds < 86400) return `${Math.floor(diffSeconds / 3600)}h ago`; // For very old timestamps, show days const days = Math.floor(diffSeconds / 86400); if (days === 1) return 'yesterday'; if (days < 7) return `${days} days ago`; return date.toLocaleString(); } // Calculate feels-like temperature (wind chill or heat index) function calculateFeelsLike(temp, humidity, windSpeed) { if (temp < 50 && windSpeed > 3) { // Wind chill formula const windChill = 35.74 + (0.6215 * temp) - (35.75 * Math.pow(windSpeed, 0.16)) + (0.4275 * temp * Math.pow(windSpeed, 0.16)); return Math.round(windChill); } else if (temp > 80) { // Heat index formula const heatIndex = -42.379 + (2.04901523 * temp) + (10.14333127 * humidity) - (0.22475541 * temp * humidity) - (0.00683783 * temp * temp) - (0.05481717 * humidity * humidity) + (0.00122874 * temp * temp * humidity) + (0.00085282 * temp * humidity * humidity) - (0.00000199 * temp * temp * humidity * humidity); return Math.round(heatIndex); } return Math.round(temp); } // Update wind compass function updateWindCompass(direction, speed) { const arrow = document.getElementById('wind-arrow'); const directionText = document.getElementById('wind-direction-text'); if (direction !== null && direction !== undefined) { arrow.style.transform = `translate(-50%, -50%) rotate(${direction}deg)`; // Convert degrees to cardinal direction const cardinals = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW']; const index = Math.round(direction / 22.5) % 16; directionText.textContent = cardinals[index]; // Adjust cloud speed based on wind adjustCloudSpeed(speed); } } // Dynamically adjust cloud animation speed based on wind function adjustCloudSpeed(windSpeed) { const clouds = document.querySelectorAll('.cloud'); const baseSpeed = 60; // base duration in seconds const speedMultiplier = Math.max(0.3, 1 - (windSpeed / 50)); // Faster clouds with more wind clouds.forEach((cloud, index) => { const duration = (baseSpeed + (index * 10)) * speedMultiplier; cloud.style.animationDuration = `${duration}s`; }); } // Update UV index bar function updateUVIndex(uvValue) { const bar = document.getElementById('uv-bar-fill'); const levelText = document.getElementById('uv-level'); const percentage = Math.min((uvValue / 11) * 100, 100); bar.style.width = `${percentage}%`; // Color based on UV level let color, level; if (uvValue < 3) { color = '#4ade80'; // green level = 'Low'; } else if (uvValue < 6) { color = '#facc15'; // yellow level = 'Moderate'; } else if (uvValue < 8) { color = '#fb923c'; // orange level = 'High'; } else if (uvValue < 11) { color = '#f87171'; // red level = 'Very High'; } else { color = '#c084fc'; // purple level = 'Extreme'; } bar.style.background = color; bar.style.boxShadow = `0 0 10px ${color}`; levelText.textContent = level; } // Calculate sunrise/sunset times using astronomical formulas function calculateSunTimes(date, lat, lng) { const toRad = deg => deg * Math.PI / 180; const toDeg = rad => rad * 180 / Math.PI; // Work with UTC date const year = date.getUTCFullYear(); const month = date.getUTCMonth() + 1; const day = date.getUTCDate(); // Julian day calculation const a = Math.floor((14 - month) / 12); const y = year + 4800 - a; const m = month + 12 * a - 3; const jdn = day + Math.floor((153 * m + 2) / 5) + 365 * y + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400) - 32045; const n = jdn - 2451545; // Mean solar time const J = n - lng / 360; // Solar mean anomaly const M = (357.5291 + 0.98560028 * J) % 360; // Equation of center const C = 1.9148 * Math.sin(toRad(M)) + 0.02 * Math.sin(toRad(2 * M)) + 0.0003 * Math.sin(toRad(3 * M)); // Ecliptic longitude const lambda = (M + C + 180 + 102.9372) % 360; // Solar transit const Jtransit = 2451545 + J + 0.0053 * Math.sin(toRad(M)) - 0.0069 * Math.sin(toRad(2 * lambda)); // Declination of the sun const delta = toDeg(Math.asin(Math.sin(toRad(lambda)) * Math.sin(toRad(23.44)))); // Hour angle const cosOmega = (Math.sin(toRad(-0.83)) - Math.sin(toRad(lat)) * Math.sin(toRad(delta))) / (Math.cos(toRad(lat)) * Math.cos(toRad(delta))); // Handle polar day/night if (cosOmega > 1) return { sunrise: null, sunset: null }; if (cosOmega < -1) return { sunrise: null, sunset: null }; const omega = toDeg(Math.acos(cosOmega)); // Sunrise and sunset as Julian dates const Jrise = Jtransit - omega / 360; const Jset = Jtransit + omega / 360; // Convert to UTC hours const riseHours = ((Jrise - jdn + 0.5) * 24 + 24) % 24; const setHours = ((Jset - jdn + 0.5) * 24 + 24) % 24; // Create UTC dates, then convert to local const sunrise = new Date(Date.UTC(year, month - 1, day, Math.floor(riseHours), Math.round((riseHours % 1) * 60), 0)); const sunset = new Date(Date.UTC(year, month - 1, day, Math.floor(setHours), Math.round((setHours % 1) * 60), 0)); return { sunrise, sunset }; } // Calculate and display sunrise/sunset function updateSunTimes() { const now = new Date(); const today = calculateSunTimes(now, LATITUDE, LONGITUDE); // Also get tomorrow's sunrise for nighttime calculation const tomorrow = new Date(now); tomorrow.setDate(tomorrow.getDate() + 1); const tomorrowSun = calculateSunTimes(tomorrow, LATITUDE, LONGITUDE); if (today.sunrise && today.sunset) { const progressBar = document.getElementById('sun-progress'); // Check if it's nighttime (after sunset or before sunrise) const isNight = now > today.sunset || now < today.sunrise; // Get current theme const isStatic = document.body.dataset.theme === 'static'; if (isNight) { // Nighttime: flip labels - left is sunset, right is sunrise document.getElementById('left-icon').textContent = '🌇'; document.getElementById('left-label').textContent = 'Sunset'; document.getElementById('left-time').textContent = today.sunset.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); let nextSunrise; if (now > today.sunset) { nextSunrise = tomorrowSun.sunrise; } else { nextSunrise = today.sunrise; } document.getElementById('right-icon').textContent = '🌅'; document.getElementById('right-label').textContent = 'Sunrise'; document.getElementById('right-time').textContent = nextSunrise.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); // Calculate night progress let nightStart; if (now > today.sunset) { nightStart = today.sunset; } else { const yesterday = new Date(now); yesterday.setDate(yesterday.getDate() - 1); const yesterdaySun = calculateSunTimes(yesterday, LATITUDE, LONGITUDE); nightStart = yesterdaySun.sunset; } const totalNightMinutes = (nextSunrise - nightStart) / 1000 / 60; const currentNightMinutes = (now - nightStart) / 1000 / 60; const progress = Math.max(0, Math.min(100, (currentNightMinutes / totalNightMinutes) * 100)); progressBar.style.width = `${progress}%`; // Theme-aware colors for nighttime if (isStatic) { progressBar.style.background = '#fff'; } else { // Use theme colors for nighttime const skyDark = getComputedStyle(document.body).getPropertyValue('--sky-dark').trim(); const skyPrimary = getComputedStyle(document.body).getPropertyValue('--sky-primary').trim(); progressBar.style.background = `linear-gradient(90deg, ${skyDark}, ${skyPrimary})`; } } else { // Daytime: normal labels - left is sunrise, right is sunset document.getElementById('left-icon').textContent = '🌅'; document.getElementById('left-label').textContent = 'Sunrise'; document.getElementById('left-time').textContent = today.sunrise.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); document.getElementById('right-icon').textContent = '🌇'; document.getElementById('right-label').textContent = 'Sunset'; document.getElementById('right-time').textContent = today.sunset.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); // Calculate day progress const totalDayMinutes = (today.sunset - today.sunrise) / 1000 / 60; const currentMinutes = (now - today.sunrise) / 1000 / 60; const progress = Math.max(0, Math.min(100, (currentMinutes / totalDayMinutes) * 100)); progressBar.style.width = `${progress}%`; // Theme-aware colors for daytime if (isStatic) { progressBar.style.background = '#fff'; } else { // Use theme colors for daytime const accentWarm = getComputedStyle(document.body).getPropertyValue('--accent-warm').trim(); const accentCool = getComputedStyle(document.body).getPropertyValue('--accent-cool').trim(); progressBar.style.background = `linear-gradient(90deg, ${accentWarm}, ${accentCool})`; } } } else { // Fallback for polar regions document.getElementById('left-time').textContent = '--'; document.getElementById('right-time').textContent = '--'; document.getElementById('sun-progress').style.width = '0%'; } } // Temperature trend function updateTemperatureTrend(currentTemp) { const trendEl = document.getElementById('temp-trend'); if (previousTemp !== null) { const diff = currentTemp - previousTemp; if (diff > 0.5) { trendEl.textContent = '↗️'; trendEl.title = `+${diff.toFixed(1)}°F from last update`; } else if (diff < -0.5) { trendEl.textContent = '↘️'; trendEl.title = `${diff.toFixed(1)}°F from last update`; } else { trendEl.textContent = '→'; trendEl.title = 'Steady'; } } previousTemp = currentTemp; } async function fetchWeatherStats() { try { const response = await fetch(`${API_BASE}/weather/stats`); const result = await response.json(); const data = result.data || result; // Handle both new and old format // Basic stats document.getElementById('temperature').textContent = formatValue(data.temperature, 1); document.getElementById('humidity').textContent = formatValue(data.humidity, 0); document.getElementById('pressure').textContent = formatValue(data.pressure, 1); document.getElementById('wind_speed').textContent = formatValue(data.wind_speed, 1); document.getElementById('wind_gust').textContent = formatValue(data.wind_gust_24h, 1); document.getElementById('wind_gust_max').textContent = formatValue(data.wind_gust_max, 1); document.getElementById('solar_radiation').textContent = formatValue(data.solar_radiation, 0); document.getElementById('uv').textContent = formatValue(data.uv, 1); document.getElementById('precipitation').textContent = formatValue(data.precipitation_24h, 2); // Update last updated timestamp const lastUpdatedEl = document.getElementById('last-updated'); if (lastUpdatedEl && result.updated_at) { lastUpdatedEl.textContent = formatTimestamp(result.updated_at); } // Enhanced features const feelsLike = calculateFeelsLike(data.temperature, data.humidity, data.wind_speed); document.getElementById('feels-like').textContent = `Feels like: ${feelsLike}°F`; updateTemperatureTrend(data.temperature); updateWindCompass(data.wind_direction, data.wind_speed); updateUVIndex(data.uv); updateSunTimes(); // Update weather emoji const emoji = getWeatherEmoji(data); document.getElementById('weather-emoji').textContent = emoji; // Weather theme and effects updateWeatherTheme(data); updateWeatherEffects(data); } catch (error) { console.error('Error fetching weather stats:', error); } } async function fetchWeatherHistory(field, hours = 24) { try { const response = await fetch(`${API_BASE}/weather/history/${field}?hours=${hours}`); return await response.json(); } catch (error) { console.error(`Error fetching ${field} history:`, error); return []; } } function createChart(canvasId, label, data, color, unit = '') { const ctx = document.getElementById(canvasId).getContext('2d'); if (charts[canvasId]) { charts[canvasId].destroy(); } // Check if static theme is active const isStatic = document.body.dataset.theme === 'static'; charts[canvasId] = new Chart(ctx, { type: 'line', data: { labels: data.map(d => new Date(d.time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })), datasets: [{ label: label, data: data.map(d => d.value), borderColor: isStatic ? '#fff' : color, backgroundColor: isStatic ? 'rgba(255, 255, 255, 0.1)' : color + '40', tension: 0.4, fill: true, pointRadius: 0, pointHoverRadius: isStatic ? 0 : 6, pointBackgroundColor: isStatic ? '#fff' : color, pointHoverBackgroundColor: isStatic ? '#fff' : color, pointBorderColor: isStatic ? '#fff' : '#fff', pointHoverBorderColor: isStatic ? '#fff' : '#fff', pointBorderWidth: 2, pointHoverBorderWidth: 2, borderWidth: 2 }] }, options: { responsive: true, maintainAspectRatio: true, aspectRatio: 2.5, animation: isStatic ? false : undefined, hover: { mode: isStatic ? null : 'nearest', intersect: true, animationDuration: 0 }, plugins: { legend: { display: false }, tooltip: { enabled: !isStatic, callbacks: { label: (context) => `${context.parsed.y.toFixed(1)} ${unit}` } } }, scales: { x: { display: true, grid: { display: false }, ticks: { maxTicksLimit: 8, color: isStatic ? '#fff' : undefined } }, y: { display: true, grid: { color: isStatic ? '#333' : '#f0f0f0' }, ticks: { color: isStatic ? '#fff' : undefined } } } } }); } async function updateCharts() { const [tempData, humidityData, windData, pressureData] = await Promise.all([ fetchWeatherHistory('temperature', 24), fetchWeatherHistory('humidity', 24), fetchWeatherHistory('wind', 24), fetchWeatherHistory('pressure', 24) ]); createChart('tempChart', 'Temperature', tempData, '#f5576c', '°F'); createChart('humidityChart', 'Humidity', humidityData, '#4facfe', '%'); createChart('windChart', 'Wind Speed', windData, '#43e97b', 'mph'); createChart('pressureChart', 'Pressure', pressureData, '#fa709a', 'mbar'); } async function init() { // Initialize theme switcher initThemeSwitcher(); // Initial data fetch await fetchWeatherStats(); await updateCharts(); // Update sun times every minute setInterval(updateSunTimes, 60000); // Update stats every 30 seconds setInterval(fetchWeatherStats, 30000); // Update charts every 5 minutes setInterval(updateCharts, 300000); } init();