import React, { useEffect, useState } from "https://esm.sh/react";
import { createRoot } from "https://esm.sh/react-dom/client";
function calculateDensityAltitude(elevation, temperature, pressure) {
const tempC = (temperature - 32) * 5 / 9;
const pressureHpa = pressure * 33.86389;
const densityAltitude = elevation + (145366.45 * (1 - Math.pow(pressureHpa / 1013.25, 0.190284)));
return Math.round(densityAltitude);
}
function App() {
const [weatherData, setWeatherData] = useState(null);
const [error, setError] = useState(null);
const [lastChecked, setLastChecked] = useState(new Date());
const [consecutiveErrors, setConsecutiveErrors] = useState(0);
useEffect(() => {
const fetchWeather = () => {
setLastChecked(new Date());
fetch("/api/weather" + window.location.search)
.then(response => response.json())
.then(data => {
setWeatherData(data);
setConsecutiveErrors(0);
})
.catch(err => {
setError(err.message);
setConsecutiveErrors(prev => prev + 1);
});
};
fetchWeather();
const intervalId = setInterval(() => {
if (consecutiveErrors < 5) {
fetchWeather();
} else {
setError("Too many errors occurred. Updates paused. Please refresh the page to try again.");
}
}, 60000);
return () => clearInterval(intervalId);
}, [consecutiveErrors]);
if (error) return <div className="error">Error: {error}</div>;
if (!weatherData) return <div>Loading...</div>;
const densityAltitude = calculateDensityAltitude(
weatherData.elevation,
weatherData.temperature,
weatherData.pressure,
);
return (
<div className="weather-display">
<h1>Current Weather - {weatherData.stationName}</h1>
<div className="weather-tiles">
<div className="tile">
<h2>Conditions</h2>
<div className="tile-content">
<span>Temperature:</span>
<span>{weatherData.temperature}</span>
<span>°F</span>
<span>Humidity:</span>
<span>{weatherData.humidity}</span>
<span>%</span>
<span>Dewpoint:</span>
<span>{weatherData.dewpoint}</span>
<span>°F</span>
<span>Pressure:</span>
<span>{weatherData.pressure}</span>
<span>inHg</span>
</div>
</div>
<div className="tile">
<h2>Wind</h2>
<div className="tile-content">
<span>Wind Speed:</span>
<span>{weatherData.windSpeed}</span>
<span>mph</span>
<span>Direction:</span>
<span>{weatherData.windDirection}</span>
<span>°</span>
<span>Wind Gust:</span>
<span>{weatherData.windGust}</span>
<span>mph</span>
</div>
</div>