        const { useState, useEffect, useRef, useMemo, useCallback } = React;

        // --- FETCH UTILITY WITH STRICT TIMEOUT (EXTENDED TO 8 SECONDS) ---
        const fetchWithTimeout = async (url, options = {}, timeoutMs = 8000) => {
            const controller = new AbortController();
            const id = setTimeout(() => controller.abort(), timeoutMs);
            try {
                const response = await fetch(url, { ...options, signal: controller.signal });
                clearTimeout(id);
                return response;
            } catch (error) {
                clearTimeout(id);
                throw error;
            }
        };

        // --- IN-MEMORY CACHE FOR API RESPONSES ---
        const DataCache = {
            elevation: new Map(),
            weather: new Map(),
            horizon: new Map()
        };

        // --- 10-POINT ROBUST ELEVATION API FALLBACK ENGINE ---
        const fetchElevationData = async (lats, lngs) => {
            const cacheKey = `${lats[0]},${lngs[0]}_${lats[lats.length-1]},${lngs[lngs.length-1]}_${lats.length}`;
            if (DataCache.elevation.has(cacheKey)) return DataCache.elevation.get(cacheKey);

            // Pre-process coordinate formats for various APIs
            const valhallaShape = lats.map((lat, i) => ({lat: parseFloat(lat), lon: parseFloat(lngs[i])}));
            const otdFormat = lats.map((lat, i) => `${lat},${lngs[i]}`).join('|');
            const oeLocations = lats.map((lat, i) => ({latitude: parseFloat(lat), longitude: parseFloat(lngs[i])}));
            
            const apis = [
                // API 1: Open-Meteo (Highly reliable, fast, global 90m)
                async () => {
                    const res = await fetchWithTimeout(`https://api.open-meteo.com/v1/elevation?latitude=${lats.join(',')}&longitude=${lngs.join(',')}`, {}, 6000);
                    if (!res.ok) throw new Error("Open-Meteo Failed");
                    const data = await res.json();
                    if (data.elevation && data.elevation.length === lats.length) return data.elevation;
                    throw new Error("OM Format Invalid");
                },
                // API 2: Valhalla OSM public server (Extremely robust routing engine)
                async () => {
                    const res = await fetchWithTimeout(`https://valhalla1.openstreetmap.de/height`, {
                        method: 'POST', headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ shape: valhallaShape, range: false })
                    }, 6000);
                    if (!res.ok) throw new Error("Valhalla Failed");
                    const data = await res.json();
                    if (data.height && data.height.length === lats.length) return data.height;
                    throw new Error("Valhalla Format Invalid");
                },
                // API 3: OpenTopoData Mapzen (Global 30m, high precision)
                async () => {
                    const res = await fetchWithTimeout(`https://api.opentopodata.org/v1/mapzen`, {
                        method: 'POST', headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ locations: otdFormat })
                    }, 6000);
                    if (!res.ok) throw new Error("OTD Mapzen Failed");
                    const data = await res.json();
                    if (data.results) return data.results.map(r => r.elevation);
                    throw new Error("OTD Mapzen Format Invalid");
                },
                // API 4: OpenTopoData SRTM90m (Standard global 90m)
                async () => {
                    const res = await fetchWithTimeout(`https://api.opentopodata.org/v1/srtm90m`, {
                        method: 'POST', headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ locations: otdFormat })
                    }, 6000);
                    if (!res.ok) throw new Error("OTD SRTM Failed");
                    const data = await res.json();
                    if (data.results) return data.results.map(r => r.elevation);
                    throw new Error("OTD SRTM Format Invalid");
                },
                // API 5: Racemap Elevation API (Very fast array processing)
                async () => {
                    const rmPath = lats.map((lat, i) => [parseFloat(lngs[i]), parseFloat(lat)]);
                    const res = await fetchWithTimeout(`https://elevation.racemap.com/api`, {
                        method: 'POST', headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(rmPath)
                    }, 6000);
                    if (!res.ok) throw new Error("Racemap Failed");
                    const data = await res.json();
                    if (Array.isArray(data) && data.length === lats.length) return data;
                    throw new Error("Racemap Format Invalid");
                },
                // API 6: GPXZ OTD Compat (Commercial robust fallback)
                async () => {
                    const res = await fetchWithTimeout(`https://api.gpxz.io/v1/elevation/otd-compat`, {
                        method: 'POST', headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ locations: otdFormat })
                    }, 6000);
                    if (!res.ok) throw new Error("GPXZ Failed");
                    const data = await res.json();
                    if (data.results) return data.results.map(r => r.elevation);
                    throw new Error("GPXZ Format Invalid");
                },
                // API 7: Elevation-API.io public endpoint
                async () => {
                    const url = `https://elevation-api.io/api/elevation?points=${lats.map((l,i)=>`(${l},${lngs[i]})`).join(',')}`;
                    const res = await fetchWithTimeout(url, {}, 6000);
                    if (!res.ok) throw new Error("Elevation-API Failed");
                    const data = await res.json();
                    if (data.elevations && data.elevations.length === lats.length) return data.elevations.map(r => r.elevation);
                    throw new Error("Elevation-API Format Invalid");
                },
                // API 8: Open-Elevation (Classic open API, fallback)
                async () => {
                    const res = await fetchWithTimeout(`https://api.open-elevation.com/api/v1/lookup`, {
                        method: 'POST', headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ locations: oeLocations })
                    }, 8000);
                    if (!res.ok) throw new Error("OE Failed");
                    const data = await res.json();
                    if (data.results) return data.results.map(r => r.elevation);
                    throw new Error("OE Format Invalid");
                },
                // API 9: OpenTopoData ASTER30m
                async () => {
                    const res = await fetchWithTimeout(`https://api.opentopodata.org/v1/aster30m`, {
                        method: 'POST', headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ locations: otdFormat })
                    }, 6000);
                    if (!res.ok) throw new Error("OTD ASTER Failed");
                    const data = await res.json();
                    if (data.results) return data.results.map(r => r.elevation);
                    throw new Error("OTD ASTER Format Invalid");
                }
            ];

            for (let i = 0; i < apis.length; i++) {
                try {
                    const elevs = await apis[i]();
                    if (elevs && elevs.length === lats.length) {
                        // Strict parsing to prevent SVG NaNs
                        const cleanElevs = elevs.map(e => {
                            const parsed = parseFloat(e);
                            return isNaN(parsed) ? 0 : parsed;
                        });
                        DataCache.elevation.set(cacheKey, cleanElevs);
                        return cleanElevs;
                    }
                } catch (e) {
                    console.warn(`Elevation API ${i+1} failed:`, e.message);
                }
            }

            // Absolute Fallback
            console.warn("All Elevation APIs failed. Using fallback 0m baseline.");
            const fallback = lats.map(() => 0);
            DataCache.elevation.set(cacheKey, fallback);
            return fallback;
        };


        // --- 5-POINT ROBUST LOCAL WEATHER API FALLBACK ENGINE ---
        const fetchLocalWeatherData = async (lat, lng, dateStr) => {
            const cacheKey = `${dateStr}_${lat.toFixed(2)}_${lng.toFixed(2)}`;
            if (DataCache.weather.has(cacheKey)) return DataCache.weather.get(cacheKey);

            // API 1: Open-Meteo ECMWF (Highly Accurate Primary)
            try {
                const res = await fetchWithTimeout(`https://api.open-meteo.com/v1/ecmwf?latitude=${lat}&longitude=${lng}&hourly=cloudcover,cloudcover_low,cloudcover_mid,cloudcover_high,temperature_2m,pressure_msl&timezone=auto&start_date=${dateStr}&end_date=${dateStr}`, {}, 6000);
                if (res.ok) {
                    const data = await res.json();
                    if (data.hourly && data.hourly.cloudcover) {
                        const strictCloudCover = data.hourly.cloudcover.map((total, i) => Math.max(total, data.hourly.cloudcover_low[i] || 0, data.hourly.cloudcover_mid[i] || 0, data.hourly.cloudcover_high[i] || 0));
                        const result = { clouds: strictCloudCover, temps: data.hourly.temperature_2m, pressures: data.hourly.pressure_msl };
                        DataCache.weather.set(cacheKey, result);
                        return result;
                    }
                }
            } catch(e) { console.warn("API 1 (Open-Meteo ECMWF) failed", e); }

            // API 2: NOAA / NWS API (US Target Override)
            if (lat > 24 && lat < 50 && lng > -125 && lng < -66) {
                try {
                    const ptRes = await fetchWithTimeout(`https://api.weather.gov/points/${lat},${lng}`);
                    if (ptRes.ok) {
                        const ptData = await ptRes.json();
                        const forecastRes = await fetchWithTimeout(ptData.properties.forecastHourly);
                        if (forecastRes.ok) {
                            const forecastData = await forecastRes.json();
                            const clouds = new Array(24).fill(0); const temps = new Array(24).fill(10); const pressures = new Array(24).fill(1010);
                            forecastData.properties.periods.forEach(p => {
                                const d = new Date(p.startTime);
                                if (d.toISOString().split('T')[0] === dateStr) {
                                    const h = d.getHours();
                                    clouds[h] = p.relativeHumidity?.value || 0; 
                                    temps[h] = p.temperature || 10;
                                }
                            });
                            const result = { clouds, temps, pressures };
                            DataCache.weather.set(cacheKey, result);
                            return result;
                        }
                    }
                } catch(e) { console.warn("API 2 (NOAA NWS) failed", e); }
            }

            // API 3: MET Norway
            try {
                const res = await fetchWithTimeout(`https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=${lat.toFixed(4)}&lon=${lng.toFixed(4)}`, {
                    headers: { 'User-Agent': 'NorthernPixlPlanner/1.0' }
                }, 6000);
                if (res.ok) {
                    const data = await res.json();
                    const clouds = new Array(24).fill(0); const temps = new Array(24).fill(10); const pressures = new Array(24).fill(1010);
                    data.properties.timeseries.forEach(ts => {
                        const tsDate = new Date(ts.time);
                        if (tsDate.toISOString().split('T')[0] === dateStr) {
                            const h = tsDate.getHours();
                            clouds[h] = ts.data.instant.details.cloud_area_fraction;
                            temps[h] = ts.data.instant.details.air_temperature;
                            pressures[h] = ts.data.instant.details.air_pressure_at_sea_level;
                        }
                    });
                    const result = { clouds, temps, pressures };
                    DataCache.weather.set(cacheKey, result);
                    return result;
                }
            } catch(e) { console.warn("API 3 (MET Norway) failed", e); }

            // API 4: Wttr.in
            try {
                const res = await fetchWithTimeout(`https://wttr.in/${lat},${lng}?format=j1`, {}, 6000);
                if (res.ok) {
                    const data = await res.json();
                    const clouds = new Array(24).fill(0); const temps = new Array(24).fill(10); const pressures = new Array(24).fill(1010);
                    const dayData = data.weather.find(w => w.date === dateStr);
                    if (dayData && dayData.hourly) {
                        dayData.hourly.forEach(h => {
                            const hour = parseInt(h.time) / 100;
                            if (hour >= 0 && hour < 24) {
                                clouds[hour] = parseInt(h.cloudcover); temps[hour] = parseInt(h.tempC); pressures[hour] = parseInt(h.pressure);
                            }
                        });
                        for(let i=1; i<24; i++) { if (clouds[i] === 0) { clouds[i] = clouds[i-1]; temps[i] = temps[i-1]; pressures[i] = pressures[i-1]; } }
                        const result = { clouds, temps, pressures };
                        DataCache.weather.set(cacheKey, result);
                        return result;
                    }
                }
            } catch(e) { console.warn("API 4 (Wttr.in) failed", e); }

            // API 5: Fallback defaults
            console.warn("All Weather APIs failed. Proceeding with null data to prevent crash.");
            return { clouds: new Array(24).fill(null), temps: new Array(24).fill(10), pressures: new Array(24).fill(1010) };
        };


