import React, { useMemo, useState, useRef, useEffect } from "react"; import { Search, Calendar, CloudRain, Thermometer, Wind, Database, Info, ChevronDown, XCircle } from "lucide-react"; import { countryMatches } from "@/utils/country"; interface Station { id: string; name: string; country: string; longitude: number; latitude: number; elevation: number | null; available_params: string; } interface SidebarProps { stations: Station[]; selectedCountry: string; setSelectedCountry: (country: string) => void; selectedStation: string; setSelectedStation: (stationId: string) => void; startDate: string; setStartDate: (date: string) => void; endDate: string; setEndDate: (date: string) => void; parameter: string; setParameter: (param: string) => void; selectedHour: number; observations?: Record; } const FilterLabel = ({ id, label, help, }: { id: string; label: string; help: string; }) => { const [isOpen, setIsOpen] = useState(false); const wrapperRef = useRef(null); useEffect(() => { if (!isOpen) return; const handlePointerDown = (event: MouseEvent | TouchEvent) => { if (wrapperRef.current && !wrapperRef.current.contains(event.target as Node)) { setIsOpen(false); } }; const handleKeyDown = (event: KeyboardEvent) => { if (event.key === "Escape") { setIsOpen(false); } }; document.addEventListener("mousedown", handlePointerDown); document.addEventListener("touchstart", handlePointerDown); document.addEventListener("keydown", handleKeyDown); return () => { document.removeEventListener("mousedown", handlePointerDown); document.removeEventListener("touchstart", handlePointerDown); document.removeEventListener("keydown", handleKeyDown); }; }, [isOpen]); const handleBlur = (event: React.FocusEvent) => { if (!event.currentTarget.contains(event.relatedTarget as Node | null)) { setIsOpen(false); } }; return (
setIsOpen(true)} onMouseLeave={() => setIsOpen(false)} onFocus={() => setIsOpen(true)} onBlur={handleBlur} className="relative w-full text-sm font-semibold text-slate-400 lg:text-slate-500 tracking-wider uppercase flex items-center gap-1.5" > {label} {isOpen && ( )}
); }; // Custom Searchable Dropdown for Stations const SearchableStationSelect = ({ stations, selectedStation, setSelectedStation }: { stations: Station[], selectedStation: string, setSelectedStation: (id: string) => void }) => { const [isOpen, setIsOpen] = useState(false); const [search, setSearch] = useState(""); const dropdownRef = useRef(null); // Close when clicking outside or pressing Escape useEffect(() => { const handleClickOutside = (e: MouseEvent) => { if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) { setIsOpen(false); } }; const handleKeyDown = (e: KeyboardEvent) => { if (e.key === "Escape" && isOpen) { setIsOpen(false); } }; document.addEventListener("mousedown", handleClickOutside); document.addEventListener("keydown", handleKeyDown); return () => { document.removeEventListener("mousedown", handleClickOutside); document.removeEventListener("keydown", handleKeyDown); }; }, [isOpen]); const selected = stations.find(s => s.id === selectedStation); const filtered = useMemo(() => { if (!search) return stations; const lower = search.toLowerCase(); return stations.filter(s => s.name.toLowerCase().includes(lower) || s.id.toLowerCase().includes(lower) || s.country.toLowerCase().includes(lower) ); }, [stations, search]); return (
{isOpen && (
setSearch(e.target.value)} className="w-full pl-8 pr-3 py-1.5 text-base md:text-sm bg-white/10 border border-white/20 text-white placeholder:text-slate-500 lg:bg-slate-50 lg:border-slate-200 lg:text-slate-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all" />
{selectedStation && ( )} {filtered.length === 0 ? (
No stations found
) : ( <> {!selectedStation && ( )} {filtered.map(st => ( ))} )}
)}
); }; export const Sidebar: React.FC = ({ stations, selectedCountry, setSelectedCountry, selectedStation, setSelectedStation, startDate, setStartDate, endDate, setEndDate, parameter, setParameter, selectedHour, observations }) => { // Extract unique countries sorted alphabetically const countries = useMemo(() => { const unique = new Set(stations.map(st => st.country).filter(Boolean)); return Array.from(unique).sort(); }, [stations]); // Filter stations based on selected country for the station dropdown const filteredStations = useMemo(() => { if (!selectedCountry) return stations; return stations.filter(st => countryMatches(st.country, selectedCountry)); }, [stations, selectedCountry]); // Count stations that have actual valid observations for the selected hour const activeCount = useMemo(() => { if (!observations || Object.keys(observations).length === 0) { return filteredStations.length; } let count = 0; filteredStations.forEach((st) => { const val = observations[st.id]?.[selectedHour]; if (val !== undefined && val !== null && !isNaN(val)) { count++; } }); return count; }, [filteredStations, observations, selectedHour]); const hoursAgo = useMemo(() => { const selectedDateStr = `${endDate}T${selectedHour.toString().padStart(2, "0")}:00:00Z`; const selectedTime = new Date(selectedDateStr).getTime(); const now = new Date().getTime(); const diff = now - selectedTime; return Math.max(0, Math.floor(diff / (1000 * 60 * 60))); }, [endDate, selectedHour]); // Date range constraints (max 31 days) const handleStartDateChange = (newStart: string) => { setStartDate(newStart); const startObj = new Date(newStart); const endObj = new Date(endDate); // Auto-adjust end date if range exceeds 31 days if (endObj.getTime() - startObj.getTime() > 31 * 24 * 60 * 60 * 1000) { const newEnd = new Date(startObj.getTime() + 31 * 24 * 60 * 60 * 1000); // Ensure we don't set future dates const maxDate = new Date(); if (newEnd > maxDate) { setEndDate(maxDate.toISOString().split("T")[0]); } else { setEndDate(newEnd.toISOString().split("T")[0]); } } else if (startObj > endObj) { setEndDate(newStart); } }; const handleEndDateChange = (newEnd: string) => { setEndDate(newEnd); const startObj = new Date(startDate); const endObj = new Date(newEnd); // Auto-adjust start date if range exceeds 31 days if (endObj.getTime() - startObj.getTime() > 31 * 24 * 60 * 60 * 1000) { const newStart = new Date(endObj.getTime() - 31 * 24 * 60 * 60 * 1000); setStartDate(newStart.toISOString().split("T")[0]); } else if (startObj > endObj) { setStartDate(newEnd); } }; return ( ); };