'use client'; import { CloudRain, Sun, Cloud, Thermometer } from 'lucide-react'; import { useState, useEffect } from 'react'; export function WeatherCard() { const [weather, setWeather] = useState(null); const [loading, setLoading] = useState(true); const [locationName, setLocationName] = useState('Detecting Location...'); useEffect(() => { async function fetchWeather(lat: number, lng: number) { try { // Fetch Weather const res = await fetch( `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lng}¤t=temperature_2m,relative_humidity_2m,weather_code&daily=temperature_2m_max,temperature_2m_min&temperature_unit=celsius&timezone=auto` ); const data = await res.json(); setWeather(data); // Simple Reverse Geocode (approximate or just use timezone) // Using a free reverse geocode API (limited, but fine for client side demo) try { const geoRes = await fetch(`https://api.bigdatacloud.net/data/reverse-geocode-client?latitude=${lat}&longitude=${lng}&localityLanguage=en`); const geoData = await geoRes.json(); if (geoData.city || geoData.locality) { setLocationName(`${geoData.city || geoData.locality}, ${geoData.countryCode}`); } else { setLocationName('Local Weather'); } } catch (e) { setLocationName('Local Weather'); } } catch (e) { console.error(e); } finally { setLoading(false); } } if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( (position) => { fetchWeather(position.coords.latitude, position.coords.longitude); }, (error) => { console.error("Geolocation error:", error); // Fallback to NY if denied fetchWeather(40.7128, -74.0060); setLocationName('New York, US (Default)'); } ); } else { fetchWeather(40.7128, -74.0060); setLocationName('New York, US (Default)'); } }, []); if (loading) { return (
); } if (!weather?.current) { // ... error state return (
Failed to load weather
); } const current = weather.current; const today = weather.daily; return (
Local Weather
{locationName}
{Math.round(current.temperature_2m)}°C
{getWeatherDescription(current.weather_code)}
H: {Math.round(today.temperature_2m_max[0])}° L: {Math.round(today.temperature_2m_min[0])}°
Humidity: {current.relative_humidity_2m}%
); } function getWeatherDescription(code: number) { if (code === 0) return 'Clear'; if (code <= 3) return 'Partly Cloudy'; if (code <= 48) return 'Foggy'; if (code <= 67) return 'Rainy'; if (code <= 77) return 'Snowy'; return 'Cloudy'; }