const App = () => {
            const urlParams = new URLSearchParams(window.location.search);
            
            const [date, setDate] = useState(() => {
                const dParam = urlParams.get('date');
                if (dParam) return new Date(parseInt(dParam, 10));
                const saved = localStorage.getItem('np_date');
                if (saved) {
                    const parsed = new Date(parseInt(saved, 10));
                    if (!isNaN(parsed.getTime())) return parsed;
                }
                const d = new Date();
                d.setHours(12, 0, 0, 0);
                return d;
            });
            const dateStrKey = date.toISOString().split('T')[0];
            
            const [camPos, setCamPos] = useState(() => { 
                const lat = urlParams.get('cLat'); const lng = urlParams.get('cLng');
                if (lat && lng) return { lat: parseFloat(lat), lng: parseFloat(lng) };
                const saved = localStorage.getItem('np_camPos');
                if (saved) return JSON.parse(saved);
                return { lat: 55.6090, lng: -1.7120 };
            }); 
            const [targetPos, setTargetPos] = useState(() => { 
                const lat = urlParams.get('tLat'); const lng = urlParams.get('tLng');
                if (lat && lng) return { lat: parseFloat(lat), lng: parseFloat(lng) };
                const saved = localStorage.getItem('np_targetPos');
                if (saved) return JSON.parse(saved);
                return { lat: 55.6105, lng: -1.7090 };
            });
            
            const [targetHeight, setTargetHeight] = useState(() => parseInt(localStorage.getItem('np_targetHeight')) || 15);
            const [targetWidth, setTargetWidth] = useState(() => parseInt(localStorage.getItem('np_targetWidth')) || 15);
            const [focalLength, setFocalLength] = useState(() => parseFloat(localStorage.getItem('np_focalLength')) || 50);
            const [sensor, setSensor] = useState(() => localStorage.getItem('np_sensor') || 'FF');
            const [aperture, setAperture] = useState(() => parseFloat(localStorage.getItem('np_aperture')) || 8.0);
            
            const [sunData, setSunData] = useState(null);
            const [moonData, setMoonData] = useState(null);
            const [mwData, setMwData] = useState(null);
            const [alignment, setAlignment] = useState(null);
            const [terrainData, setTerrainData] = useState(null);
            const [horizonWeather, setHorizonWeather] = useState({ sunRise: null, sunSet: null, moonRise: null, moonSet: null });
            const [localAtmos, setLocalAtmos] = useState({ temp: 10, pressure_msl: 1010 });
            const [corridorData, setCorridorData] = useState(null);
            
            const [showInfo, setShowInfo] = useState(false);
            const [isPlaying, setIsPlaying] = useState(false);
            const [mobileTab, setMobileTab] = useState('map'); 
            const [showViewfinder, setShowViewfinder] = useState(false);
            const [isLocating, setIsLocating] = useState(false);
            const [layerMode, setLayerMode] = useState('standard');
            const [showMWOverlay, setShowMWOverlay] = useState(false); 
            const [tgtPixelPos, setTgtPixelPos] = useState({x: -1000, y: -1000}); 
            const [toastMsg, setToastMsg] = useState(null);
            const [searchQuery, setSearchQuery] = useState('');
            const [searchType, setSearchType] = useState('camera');
            const [cloudData, setCloudData] = useState(null);
            const [isSearchingTime, setIsSearchingTime] = useState(false);
            const [panoMode, setPanoMode] = useState(false);
            const [showTimeline, setShowTimeline] = useState(true);

            // Desktop panel collapsing state (auto-collapse on smaller laptops/iPads)
            const [leftPanelExpanded, setLeftPanelExpanded] = useState(() => typeof window !== 'undefined' ? window.innerWidth > 1024 : true);
            const [rightPanelExpanded, setRightPanelExpanded] = useState(() => typeof window !== 'undefined' ? window.innerWidth > 1024 : true);

            const [savedPlans, setSavedPlans] = useState(() => JSON.parse(localStorage.getItem('np_saved_plans')) || []);
            const [showPlans, setShowPlans] = useState(false);
            
            const showToast = useCallback((msg) => {
                setToastMsg(msg);
                setTimeout(() => setToastMsg(null), 4000);
            }, []);

            useEffect(() => {
                localStorage.setItem('np_date', date.getTime().toString());
                localStorage.setItem('np_camPos', JSON.stringify(camPos));
                localStorage.setItem('np_targetPos', JSON.stringify(targetPos));
                localStorage.setItem('np_targetHeight', targetHeight.toString());
                localStorage.setItem('np_targetWidth', targetWidth.toString());
                localStorage.setItem('np_focalLength', focalLength.toString());
                localStorage.setItem('np_sensor', sensor);
                localStorage.setItem('np_aperture', aperture.toString());
            }, [date, camPos, targetPos, targetHeight, targetWidth, focalLength, sensor, aperture]);

            useEffect(() => {
                localStorage.setItem('np_saved_plans', JSON.stringify(savedPlans));
            }, [savedPlans]);

            const sDims = getSensorDims(sensor);
            const fl = parseFloat(focalLength) || 50;
            const fovAzimuth = 2 * Math.atan(sDims.w / (2 * fl)) * (180 / Math.PI);
            const fovAltitude = 2 * Math.atan(sDims.h / (2 * fl)) * (180 / Math.PI);

            const astroStats = useMemo(() => {
                const fl = parseFloat(focalLength);
                const ap = parseFloat(aperture);
                if (!fl || !ap) return { npf: 0, rule500: 0 };
                let crop = 1.0; let pixelPitch = 5.5; 
                switch(sensor) {
                    case 'APSC-N': crop = 1.5; pixelPitch = 4.0; break;
                    case 'APSC-C': crop = 1.6; pixelPitch = 3.8; break;
                    case 'M43': crop = 2.0; pixelPitch = 3.3; break;
                    case 'FF': default: crop = 1.0; pixelPitch = 5.5; break;
                }
                const rule500 = 500 / (fl * crop);
                const npf = (35 * ap + 30 * pixelPitch) / fl;
                return { npf: npf.toFixed(1), rule500: rule500.toFixed(1) };
            }, [focalLength, aperture, sensor]);

            const hyperfocal = useMemo(() => {
                const fl = parseFloat(focalLength);
                const ap = parseFloat(aperture);
                if (!fl || !ap) return 0;
                return ((fl * fl) / (getCoC(sensor) * ap)) / 1000; 
            }, [focalLength, aperture, sensor]);

            const shadowLength = useMemo(() => {
                if (!sunData || sunData.altitude <= 0) return 'No shadow';
                const len = targetHeight / Math.tan(sunData.altitude * Math.PI / 180);
                return len > 1000 ? '> 1km' : `${len.toFixed(1)}m`;
            }, [targetHeight, sunData]);

            const mapContainerRef = useRef(null);
            const mapInstanceRef = useRef(null);
            const camMarkerRef = useRef(null);
            const tgtMarkerRef = useRef(null);
            const lightLayerRef = useRef(null);
            const topoLayerRef = useRef(null);
            
            const linesRef = useRef({
                sunRise: null, sunSet: null, sunCurrent: null,
                moonRise: null, moonSet: null, moonCurrent: null,
                sightLine: null, fovWedge: null,
                sunWedge: null, moonWedge: null, targetShadow: null,
                corridorGroup: null
            });

            const updateOverlayPos = useCallback(() => {
                if (mapInstanceRef.current && showMWOverlay) {
                    const pt = mapInstanceRef.current.latLngToContainerPoint([targetPos.lat, targetPos.lng]);
                    setTgtPixelPos({ x: pt.x, y: pt.y });
                }
            }, [targetPos, showMWOverlay]);

            useEffect(() => {
                if (!mapInstanceRef.current) return;
                mapInstanceRef.current.on('move', updateOverlayPos);
                mapInstanceRef.current.on('zoom', updateOverlayPos);
                updateOverlayPos();
                return () => {
                    mapInstanceRef.current.off('move', updateOverlayPos);
                    mapInstanceRef.current.off('zoom', updateOverlayPos);
                }
            }, [updateOverlayPos]);

            // BASE EPHEMERIS
            useEffect(() => {
                if (!window.SunCalc) return;
                const sPos = SunCalc.getPosition(date, camPos.lat, camPos.lng);
                const mPos = SunCalc.getMoonPosition(date, camPos.lat, camPos.lng);
                const mIllum = SunCalc.getMoonIllumination(date);
                const sunAltDeg = sPos.altitude * 180 / Math.PI;

                const searchDate = new Date(date);
                searchDate.setHours(12, 0, 0, 0);
                const sTimes = SunCalc.getTimes(searchDate, camPos.lat, camPos.lng);
                const mTimes = SunCalc.getMoonTimes(searchDate, camPos.lat, camPos.lng);

                setSunData(prev => ({
                    ...(prev || {}),
                    azimuth: toCompassBearing(sPos.azimuth),
                    altitude: sunAltDeg,
                    riseTime: prev?.riseTime || sTimes.sunrise,
                    setTime: prev?.setTime || sTimes.sunset,
                    goldenHour: sTimes.goldenHour,
                    night: sTimes.night,
                    nightEnd: sTimes.nightEnd,
                    nauticalDawn: sTimes.nauticalDawn,
                    nauticalDusk: sTimes.nauticalDusk,
                    dawn: sTimes.dawn,
                    dusk: sTimes.dusk,
                    riseAzimuth: prev?.riseAzimuth || (sTimes.sunrise ? toCompassBearing(SunCalc.getPosition(sTimes.sunrise, camPos.lat, camPos.lng).azimuth) : null),
                    setAzimuth: prev?.setAzimuth || (sTimes.sunset ? toCompassBearing(SunCalc.getPosition(sTimes.sunset, camPos.lat, camPos.lng).azimuth) : null)
                }));

                setMoonData(prev => ({
                    ...(prev || {}),
                    azimuth: toCompassBearing(mPos.azimuth),
                    altitude: mPos.altitude * 180 / Math.PI,
                    fraction: Math.round(mIllum.fraction * 100),
                    phase: mIllum.phase,
                    riseTime: prev?.riseTime || mTimes.rise,
                    setTime: prev?.setTime || mTimes.set,
                    riseAzimuth: prev?.riseAzimuth || (mTimes.rise ? toCompassBearing(SunCalc.getMoonPosition(mTimes.rise, camPos.lat, camPos.lng).azimuth) : null),
                    setAzimuth: prev?.setAzimuth || (mTimes.set ? toCompassBearing(SunCalc.getMoonPosition(mTimes.set, camPos.lat, camPos.lng).azimuth) : null)
                }));

                const lst = getLST(date, targetPos.lng);
                const gc = getAltAz(GC_RA, GC_DEC, targetPos.lat, lst);
                setMwData({ az: gc.az, alt: gc.alt, visible: sunAltDeg < -12 && gc.alt > 0 });
                updateOverlayPos();

                const distM = calculateDistance(camPos.lat, camPos.lng, targetPos.lat, targetPos.lng);
                const bearing = calculateBearing(camPos.lat, camPos.lng, targetPos.lat, targetPos.lng);
                setAlignment({ distance: distM, bearing: bearing });

                let isMounted = true;
                const getUltraPrecise = async () => {
                    try {
                        const elevs = await fetchElevationData([camPos.lat], [camPos.lng]);
                        const elevation = elevs[0] || 0;
                        let finalSunRise, finalSunSet, finalMoonRise, finalMoonSet;

                        if (window.Astronomy) {
                            const observer = new window.Astronomy.Observer(camPos.lat, camPos.lng, elevation);
                            const startOfDay = new Date(date);
                            startOfDay.setHours(0, 0, 0, 0);

                            const aSunRise = window.Astronomy.SearchRiseSet('Sun', observer, +1, startOfDay, 1);
                            const aSunSet = window.Astronomy.SearchRiseSet('Sun', observer, -1, startOfDay, 1);
                            const aMoonRise = window.Astronomy.SearchRiseSet('Moon', observer, +1, startOfDay, 1);
                            const aMoonSet = window.Astronomy.SearchRiseSet('Moon', observer, -1, startOfDay, 1);

                            if (aSunRise) finalSunRise = aSunRise.date;
                            if (aSunSet) finalSunSet = aSunSet.date;
                            if (aMoonRise) finalMoonRise = aMoonRise.date;
                            if (aMoonSet) finalMoonSet = aMoonSet.date;

                            if (isMounted) {
                                setSunData(prev => ({
                                    ...prev,
                                    riseTime: finalSunRise || prev.riseTime, setTime: finalSunSet || prev.setTime,
                                    riseAzimuth: finalSunRise ? getAstroAzimuth('Sun', finalSunRise, observer) : prev.riseAzimuth,
                                    setAzimuth: finalSunSet ? getAstroAzimuth('Sun', finalSunSet, observer) : prev.setAzimuth
                                }));
                                setMoonData(prev => ({
                                    ...prev,
                                    riseTime: finalMoonRise || prev.riseTime, setTime: finalMoonSet || prev.setTime,
                                    riseAzimuth: finalMoonRise ? getAstroAzimuth('Moon', finalMoonRise, observer) : prev.riseAzimuth,
                                    setAzimuth: finalMoonSet ? getAstroAzimuth('Moon', finalMoonSet, observer) : prev.setAzimuth
                                }));
                            }
                        }
                    } catch (e) { console.warn("High-precision engine fetch failed", e); }
                };
                const timer = setTimeout(getUltraPrecise, 800);
                return () => { isMounted = false; clearTimeout(timer); };
            }, [date, camPos, targetPos, updateOverlayPos]);


            // HORIZON WEATHER 5-TIER FALLBACK (50km, 100km, 200km)
            useEffect(() => {
                let isMounted = true;
                const fetchHorizonWeatherRobust = async () => {
                    if (!window.SunCalc) return;
                    const sTimes = SunCalc.getTimes(date, camPos.lat, camPos.lng);
                    const mTimes = SunCalc.getMoonTimes(date, camPos.lat, camPos.lng);

                    const reqs = [
                        { time: sTimes.sunrise, az: sTimes.sunrise ? toCompassBearing(SunCalc.getPosition(sTimes.sunrise, camPos.lat, camPos.lng).azimuth) : null, key: 'sunRise' },
                        { time: sTimes.sunset, az: sTimes.sunset ? toCompassBearing(SunCalc.getPosition(sTimes.sunset, camPos.lat, camPos.lng).azimuth) : null, key: 'sunSet' },
                        { time: mTimes.rise, az: mTimes.rise ? toCompassBearing(SunCalc.getMoonPosition(mTimes.rise, camPos.lat, camPos.lng).azimuth) : null, key: 'moonRise' },
                        { time: mTimes.set, az: mTimes.set ? toCompassBearing(SunCalc.getMoonPosition(mTimes.set, camPos.lat, camPos.lng).azimuth) : null, key: 'moonSet' }
                    ].filter(r => r.time && r.az !== null);

                    if (reqs.length === 0) return;

                    const nextDay = new Date(date); nextDay.setDate(nextDay.getDate() + 1);
                    const nextDayStr = nextDay.toISOString().split('T')[0];
                    const newWeather = { sunRise: null, sunSet: null, moonRise: null, moonSet: null };
                    
                    await Promise.all(reqs.map(async (r) => {
                        const ptLow = computeDestinationPoint(camPos.lat, camPos.lng, 50, r.az);
                        const ptMid = computeDestinationPoint(camPos.lat, camPos.lng, 100, r.az);
                        const ptHigh = computeDestinationPoint(camPos.lat, camPos.lng, 200, r.az);
                        
                        const lats = [ptLow[0].toFixed(4), ptMid[0].toFixed(4), ptHigh[0].toFixed(4)];
                        const lngs = [ptLow[1].toFixed(4), ptMid[1].toFixed(4), ptHigh[1].toFixed(4)];
                        
                        const cacheKey = `horizon_${lats.join(',')}_${dateStrKey}`;
                        if (DataCache.horizon.has(cacheKey)) {
                            newWeather[r.key] = DataCache.horizon.get(cacheKey);
                            return;
                        }

                        try {
                            const url = `https://api.open-meteo.com/v1/forecast?latitude=${lats.join(',')}&longitude=${lngs.join(',')}&hourly=cloudcover_low,cloudcover_mid,cloudcover_high&timezone=auto&start_date=${dateStrKey}&end_date=${nextDayStr}`;
                            const res = await fetchWithTimeout(url, {}, 6000);
                            if (res.ok) {
                                const data = await res.json();
                                const results = Array.isArray(data) ? data : [data];
                                const hrStr = `${r.time.getFullYear()}-${String(r.time.getMonth()+1).padStart(2,'0')}-${String(r.time.getDate()).padStart(2,'0')}T${String(r.time.getHours()).padStart(2,'0')}:00`;
                                
                                const hourIdx = results[0]?.hourly?.time?.indexOf(hrStr);
                                if (hourIdx !== undefined && hourIdx !== -1) {
                                    const parsed = {
                                        low: results[0]?.hourly?.cloudcover_low?.[hourIdx] ?? null,
                                        mid: results[1]?.hourly?.cloudcover_mid?.[hourIdx] ?? null,
                                        high: results[2]?.hourly?.cloudcover_high?.[hourIdx] ?? null
                                    };
                                    newWeather[r.key] = parsed;
                                    DataCache.horizon.set(cacheKey, parsed);
                                    return;
                                }
                            }
                        } catch(e) {}

                        try {
                            const fetchMet = async (pt) => {
                                const res = await fetchWithTimeout(`https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=${pt[0]}&lon=${pt[1]}`, {headers: {'User-Agent':'NorthernPixlPlanner/1.0'}}, 5000);
                                if(!res.ok) return null;
                                const data = await res.json();
                                const targetHr = new Date(r.time); targetHr.setMinutes(0,0,0);
                                const ts = data.properties.timeseries.find(ts => new Date(ts.time).getTime() === targetHr.getTime());
                                return ts ? ts.data.instant.details.cloud_area_fraction : null;
                            };
                            const [low, mid, high] = await Promise.all([fetchMet(lats[0], lngs[0]), fetchMet(lats[1], lngs[1]), fetchMet(lats[2], lngs[2])]);
                            if (low !== null || mid !== null || high !== null) {
                                const parsed = { low, mid, high };
                                newWeather[r.key] = parsed;
                                DataCache.horizon.set(cacheKey, parsed);
                                return;
                            }
                        } catch(e) {}
                    }));

                    if (isMounted) setHorizonWeather(newWeather);
                };

                const timer = setTimeout(fetchHorizonWeatherRobust, 1200);
                return () => { isMounted = false; clearTimeout(timer); };
            }, [camPos.lat, camPos.lng, dateStrKey, date]);

            // ELEVATION PROFILE & LOCAL WEATHER
            useEffect(() => {
                let isMounted = true;
                
                // Reset terrain if distance is completely unworkable
                if (!alignment || alignment.distance < 10) {
                    setTerrainData(null);
                }

                const fetchTopography = async () => {
                    if (!alignment || alignment.distance < 10) return;
                    const pts = 50; 
                    const distStep = alignment.distance / (pts - 1);
                    const lats = []; const lngs = [];
                    for(let i=0; i<pts; i++) {
                        const p = computeDestinationPoint(camPos.lat, camPos.lng, (distStep * i)/1000, alignment.bearing);
                        lats.push(p[0].toFixed(5)); lngs.push(p[1].toFixed(5));
                    }
                    
                    const elevs = await fetchElevationData(lats, lngs);
                    if (isMounted && elevs && elevs.length === pts) {
                        const camElev = elevs[0] || 0;
                        const tgtElev = elevs[pts - 1] || 0;
                        let blocked = false;
                        const camH = camElev + 1.5; 
                        const tgtH = tgtElev + targetHeight; 
                        
                        const profile = elevs.map((e, i) => { return { dist: (i / (pts - 1)) * alignment.distance, elev: e || 0 }; });
                        
                        // Ultra-precise curvature & LOS check
                        for(let i=1; i<pts-1; i++) {
                            const distIKm = (distStep * i) / 1000;
                            const distTgtKm = alignment.distance / 1000;
                            
                            const curvDropI = 0.0785 * (distIKm * distIKm);
                            const curvDropTgt = 0.0785 * (distTgtKm * distTgtKm);
                            
                            const apparentTgtH = tgtH - curvDropTgt;
                            const apparentElevI = (profile[i].elev) - curvDropI;
                            
                            const rayH = camH + ((apparentTgtH - camH) * (i / (pts - 1)));
                            
                            if (apparentElevI > rayH) blocked = true;
                        }
                        setTerrainData({ camElev, tgtElev, profile, blocked });
                    }
                };

                const fetchLocalMeteo = async () => {
                    const hourIdx = date.getHours();
                    const wData = await fetchLocalWeatherData(camPos.lat, camPos.lng, dateStrKey);
                    
                    if (isMounted && wData) {
                        setCloudData(wData.clouds);
                        setLocalAtmos({
                            temp: wData.temps[hourIdx] ?? 10,
                            pressure_msl: wData.pressures[hourIdx] ?? 1010
                        });
                    }
                };
                
                const timer = setTimeout(() => {
                    fetchTopography();
                    fetchLocalMeteo();
                }, 800); 
                return () => { isMounted = false; clearTimeout(timer); };
            }, [camPos, targetPos, targetHeight, alignment, dateStrKey, date]);

            // Map Initialization
            useEffect(() => {
                if (mapContainerRef.current && !mapInstanceRef.current) {
                    const map = L.map(mapContainerRef.current, { zoomControl: false, attributionControl: false, scrollWheelZoom: false, smoothWheelZoom: true }).setView([camPos.lat, camPos.lng], 15);
                    lightLayerRef.current = L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', { attribution: '&copy; OpenStreetMap &copy; CARTO' }).addTo(map);
                    topoLayerRef.current = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', { maxZoom: 17, attribution: 'Map data: &copy; OpenStreetMap contributors, SRTM | Map style: &copy; OpenTopoMap (CC-BY-SA)' });
                    L.control.attribution({ position: 'bottomleft' }).addTo(map);
                    L.control.zoom({ position: 'bottomright' }).addTo(map);
                    mapInstanceRef.current = map;

                    const camSvg = `<svg width="32" height="42" viewBox="0 0 32 42" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M16 0C7.163 0 0 7.163 0 16C0 26.5 16 42 16 42C16 42 32 26.5 32 16C32 7.163 24.837 0 16 0Z" fill="#0ea5e9"/><path d="M20 11H16.5L15 9H11L9.5 11H6C4.9 11 4 13V22C4 23.1 4.9 24 6 24H20C21.1 24 22 23.1 22 22V13C22 11.9 21.1 11 20 11ZM13 21C10.8 21 9 19.2 9 17C9 14.8 10.8 13 13 13C15.2 13 17 14.8 17 17C17 19.2 15.2 21 13 21Z" fill="white" transform="translate(3, -1) scale(0.8)"/><circle cx="13" cy="17" r="2.5" fill="white" transform="translate(3, -1) scale(0.8)"/></svg>`;
                    camMarkerRef.current = L.marker([camPos.lat, camPos.lng], { draggable: true, icon: L.divIcon({ className: 'camera-marker', html: camSvg, iconSize: [32, 42], iconAnchor: [16, 42] }) }).addTo(map);

                    const tgtSvg = `<svg width="32" height="42" viewBox="0 0 32 42" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M16 0C7.163 0 0 7.163 0 16C0 26.5 16 42 16 42C16 42 32 26.5 32 16C32 7.163 24.837 0 16 0Z" fill="#ef4444"/><circle cx="16" cy="16" r="7" stroke="white" stroke-width="2"/><circle cx="16" cy="16" r="3" stroke="white" stroke-width="2"/><circle cx="16" cy="16" r="1" fill="white"/></svg>`;
                    tgtMarkerRef.current = L.marker([targetPos.lat, targetPos.lng], { draggable: true, icon: L.divIcon({ className: 'target-marker', html: tgtSvg, iconSize: [32, 42], iconAnchor: [16, 42] }) }).addTo(map);

                    const lineStyle = { weight: 2, opacity: 0.8 };
                    linesRef.current.fovWedge = L.polygon([], { color: '#0ea5e9', weight: 1, fillColor: '#0ea5e9', fillOpacity: 0.1, dashArray: '4, 4' }).addTo(map);
                    linesRef.current.sunWedge = L.polygon([], { color: '#f59e0b', weight: 0, fillColor: '#fcd34d', fillOpacity: 0.15 }).addTo(map);
                    linesRef.current.moonWedge = L.polygon([], { color: '#60a5fa', weight: 0, fillColor: '#bfdbfe', fillOpacity: 0.15 }).addTo(map);
                    linesRef.current.targetShadow = L.polygon([], { color: '#000', weight: 0, fillColor: '#020617', fillOpacity: 0.5 }).addTo(map);
                    linesRef.current.sunRise = L.polyline([], { ...lineStyle, color: '#f59e0b', weight: 4 }).addTo(map);
                    linesRef.current.sunSet = L.polyline([], { ...lineStyle, color: '#ea580c', weight: 4 }).addTo(map);
                    linesRef.current.sunCurrent = L.polyline([], { ...lineStyle, color: '#eab308', dashArray: '5, 5' }).addTo(map);
                    linesRef.current.moonRise = L.polyline([], { ...lineStyle, color: '#60a5fa', weight: 4 }).addTo(map);
                    linesRef.current.moonSet = L.polyline([], { ...lineStyle, color: '#3b82f6', weight: 4 }).addTo(map);
                    linesRef.current.moonCurrent = L.polyline([], { ...lineStyle, color: '#8b5cf6', dashArray: '5, 5' }).addTo(map);
                    linesRef.current.sightLine = L.polyline([], { weight: 3, color: '#1e293b', dashArray: '4, 8' }).addTo(map);
                    linesRef.current.corridorGroup = L.layerGroup().addTo(map);

                    camMarkerRef.current.on('drag', (e) => {
                        const newLatlng = e.target.getLatLng();
                        const tgtLatlng = tgtMarkerRef.current.getLatLng();
                        linesRef.current.sightLine.setLatLngs([newLatlng, tgtLatlng]);
                    });
                    camMarkerRef.current.on('dragend', (e) => setCamPos(e.target.getLatLng()));

                    tgtMarkerRef.current.on('drag', (e) => {
                        const newLatlng = e.target.getLatLng();
                        const camLatlng = camMarkerRef.current.getLatLng();
                        linesRef.current.sightLine.setLatLngs([camLatlng, newLatlng]);
                        setCorridorData(null); 
                    });
                    tgtMarkerRef.current.on('dragend', (e) => setTargetPos(e.target.getLatLng()));

                    setTimeout(() => { if (mapInstanceRef.current) mapInstanceRef.current.invalidateSize(); }, 300);
                }
            }, []);

            useEffect(() => {
                if (!mapInstanceRef.current || !linesRef.current.corridorGroup) return;
                linesRef.current.corridorGroup.clearLayers();
                if (corridorData) {
                    corridorData.forEach(seg => {
                        const color = seg.valid ? '#22c55e' : '#ef4444'; 
                        const dashArray = seg.valid ? null : '4, 8';
                        const weight = seg.valid ? 6 : 4;
                        const opacity = seg.valid ? 0.9 : 0.6;
                        L.polyline([seg.start, seg.end], { color, weight, opacity, dashArray }).addTo(linesRef.current.corridorGroup);
                    });
                }
            }, [corridorData]);

            useEffect(() => {
                if (!mapInstanceRef.current) return;
                const map = mapInstanceRef.current;
                if (layerMode === 'topo') {
                    if (lightLayerRef.current) map.removeLayer(lightLayerRef.current);
                    if (topoLayerRef.current && !map.hasLayer(topoLayerRef.current)) topoLayerRef.current.addTo(map);
                } else {
                    if (topoLayerRef.current) map.removeLayer(topoLayerRef.current);
                    if (lightLayerRef.current && !map.hasLayer(lightLayerRef.current)) lightLayerRef.current.addTo(map);
                }
            }, [layerMode]);

            useEffect(() => {
                if (!mapInstanceRef.current || !sunData || !moonData) return;
                const lineLengthKm = 100; const cLat = camPos.lat; const cLng = camPos.lng;

                const drawLine = (ref, azimuth) => {
                    if (azimuth !== null && !isNaN(azimuth)) {
                        const end = computeDestinationPoint(cLat, cLng, lineLengthKm, azimuth);
                        ref.setLatLngs([[cLat, cLng], end]);
                    } else { ref.setLatLngs([]); }
                };

                drawLine(linesRef.current.sunRise, sunData.riseAzimuth);
                drawLine(linesRef.current.sunSet, sunData.setAzimuth);
                drawLine(linesRef.current.sunCurrent, sunData.altitude > -18 ? sunData.azimuth : null); 
                drawLine(linesRef.current.moonRise, moonData.riseAzimuth);
                drawLine(linesRef.current.moonSet, moonData.setAzimuth);
                drawLine(linesRef.current.moonCurrent, moonData.altitude > -5 ? moonData.azimuth : null); 
                linesRef.current.sightLine.setLatLngs([[cLat, cLng], [targetPos.lat, targetPos.lng]]);
                
                if (alignment && fovAzimuth) {
                    const startAz = (alignment.bearing - (fovAzimuth / 2) + 360) % 360;
                    const distKm = Math.max((alignment.distance * 1.2) / 1000, 3);
                    const pts = [[cLat, cLng]];
                    for (let i = 0; i <= 10; i++) {
                        const az = (startAz + (i * fovAzimuth / 10)) % 360;
                        pts.push(computeDestinationPoint(cLat, cLng, distKm, az));
                    }
                    linesRef.current.fovWedge.setLatLngs(pts);
                } else if (linesRef.current.fovWedge) {
                    linesRef.current.fovWedge.setLatLngs([]);
                }

                const drawWedge = (ref, riseAz, setAz, originLat, originLng) => {
                    if (riseAz !== null && setAz !== null) {
                        let start = riseAz; let end = setAz;
                        if (end < start) end += 360;
                        const pts = [[originLat, originLng]];
                        for (let a = start; a <= end; a += 5) pts.push(computeDestinationPoint(originLat, originLng, lineLengthKm, a % 360));
                        pts.push(computeDestinationPoint(originLat, originLng, lineLengthKm, setAz));
                        ref.setLatLngs(pts);
                    } else { ref.setLatLngs([]); }
                };
                
                drawWedge(linesRef.current.sunWedge, sunData.riseAzimuth, sunData.setAzimuth, cLat, cLng);
                drawWedge(linesRef.current.moonWedge, moonData.riseAzimuth, moonData.setAzimuth, cLat, cLng);

                if (sunData.altitude > 0 && sunData.altitude < 89) {
                    const shadowLenKm = Math.min((targetHeight / Math.tan(sunData.altitude * Math.PI / 180)) / 1000, 10);
                    const shadowAz = (sunData.azimuth + 180) % 360;
                    const wKm = targetWidth / 1000;
                    const baseAz1 = (sunData.azimuth + 90) % 360;
                    const baseAz2 = (sunData.azimuth - 90 + 360) % 360;
                    const p1 = computeDestinationPoint(targetPos.lat, targetPos.lng, wKm/2, baseAz1);
                    const p2 = computeDestinationPoint(targetPos.lat, targetPos.lng, wKm/2, baseAz2);
                    const p3 = computeDestinationPoint(p2[0], p2[1], shadowLenKm, shadowAz);
                    const p4 = computeDestinationPoint(p1[0], p1[1], shadowLenKm, shadowAz);
                    linesRef.current.targetShadow.setLatLngs([p1, p2, p3, p4]);
                } else {
                    linesRef.current.targetShadow.setLatLngs([]);
                }

                if (camMarkerRef.current) camMarkerRef.current.setLatLng([cLat, cLng]);
                if (tgtMarkerRef.current) tgtMarkerRef.current.setLatLng([targetPos.lat, targetPos.lng]);

            }, [sunData, moonData, camPos, targetPos, targetHeight, targetWidth, fovAzimuth, alignment]);

            useEffect(() => {
                let interval;
                if (isPlaying && !showViewfinder) { 
                    interval = setInterval(() => {
                        setDate(prev => new Date(prev.getTime() + 15 * 1000)); 
                    }, 50);
                }
                return () => clearInterval(interval);
            }, [isPlaying, showViewfinder]);

            const handleTimeChange = (e) => {
                const secs = parseInt(e.target.value, 10);
                const newDate = new Date(date);
                newDate.setHours(Math.floor(secs / 3600), Math.floor((secs % 3600) / 60), secs % 60, 0);
                setDate(newDate);
            };

            const handleDateChange = (e) => {
                const parts = e.target.value.split('-');
                if (parts.length === 3) {
                    const newDate = new Date(date);
                    newDate.setFullYear(parts[0], parts[1] - 1, parts[2]);
                    setDate(newDate);
                }
            };

            const handleAutoAlignCamera = (newLat, newLng) => {
                setCamPos({ lat: newLat, lng: newLng });
                if (mapInstanceRef.current) mapInstanceRef.current.panTo([newLat, newLng], { animate: true, duration: 1.0 });
            };

            const handleSearch = async (e) => {
                e.preventDefault();
                if (!searchQuery) return;
                try {
                    const res = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(searchQuery)}`);
                    const data = await res.json();
                    if (data && data.length > 0) {
                        const lat = parseFloat(data[0].lat); const lng = parseFloat(data[0].lon);
                        if (searchType === 'camera') {
                            setCamPos({ lat, lng });
                            if (mapInstanceRef.current) mapInstanceRef.current.panTo([lat, lng], {animate: true});
                            showToast("Camera location found!");
                        } else {
                            setTargetPos({ lat, lng });
                            if (mapInstanceRef.current) mapInstanceRef.current.panTo([lat, lng], {animate: true});
                            showToast("Target location found!");
                        }
                        setSearchQuery('');
                    } else { alert("Location not found."); }
                } catch (err) { console.error("Search error", err); }
            };

            const handleLocateMe = () => {
                if (!mapInstanceRef.current || isLocating) return;
                setIsLocating(true);
                mapInstanceRef.current.locate({ setView: true, maxZoom: 15 });
                mapInstanceRef.current.once('locationfound', (e) => {
                    setIsLocating(false);
                    const { lat, lng } = e.latlng;
                    setCamPos({ lat, lng });
                    if (camMarkerRef.current) camMarkerRef.current.setLatLng([lat, lng]);
                    if (linesRef.current.sightLine && tgtMarkerRef.current) {
                        const tgtLatlng = tgtMarkerRef.current.getLatLng();
                        linesRef.current.sightLine.setLatLngs([[lat, lng], tgtLatlng]);
                    }
                    mapInstanceRef.current.panTo([lat, lng], { animate: true });
                });
                mapInstanceRef.current.once('locationerror', () => {
                    setIsLocating(false);
                    alert("Unable to access your location. Please check your browser permissions.");
                });
            };

            const handleStreetView = () => {
                const bearing = alignment ? Math.round(alignment.bearing) : 0;
                window.open(`https://www.google.com/maps/@?api=1&map_action=pano&viewpoint=${camPos.lat},${camPos.lng}&heading=${bearing}&pitch=0`, '_blank');
            };

            const handleTimeMachine = (type) => {
                if (isSearchingTime || !alignment) return;
                setIsSearchingTime(true);
                showToast(`Searching for next ${type} alignment...`);

                setTimeout(() => {
                    let apparentAlt = 0;
                    if (terrainData && terrainData.tgtElev) {
                        const heightDiff = (terrainData.tgtElev + targetHeight) - (terrainData.camElev + 1.5);
                        apparentAlt = Math.atan2(heightDiff, alignment.distance) * (180 / Math.PI);
                    }
                    const idealTrueAltitude = Math.max(0.5, apparentAlt + 0.265); 
                    
                    const searchDate = new Date(date);
                    let found = false;
                    
                    for (let days = 1; days <= 365; days++) {
                        searchDate.setDate(searchDate.getDate() + 1);
                        const startOfDay = new Date(searchDate); startOfDay.setHours(0,0,0,0);
                        
                        let prevAz = null;
                        for (let min = 0; min < 1440; min += 5) {
                            const testTime = new Date(startOfDay.getTime() + min * 60000);
                            const pos = type === 'sun' ? SunCalc.getPosition(testTime, camPos.lat, camPos.lng) : SunCalc.getMoonPosition(testTime, camPos.lat, camPos.lng);
                            const az = toCompassBearing(pos.azimuth);
                            const alt = pos.altitude * 180 / Math.PI;

                            if (prevAz !== null) {
                                if ((prevAz < alignment.bearing && az >= alignment.bearing) || (prevAz > alignment.bearing && az <= alignment.bearing && Math.abs(prevAz - az) < 180)) {
                                    if (Math.abs(alt - idealTrueAltitude) < 1.5) { 
                                        setDate(testTime);
                                        showToast(`Found! Next ${type} alignment on ${testTime.toLocaleDateString()}`);
                                        found = true;
                                        break;
                                    }
                                }
                            }
                            prevAz = az;
                        }
                        if (found) break;
                    }
                    
                    if (!found) alert(`Could not find a precise ${type} alignment crossing this target within the next year.`);
                    setIsSearchingTime(false);
                }, 100);
            };

            const handleSavePlan = () => {
                const url = new URL(window.location.href);
                url.searchParams.set('cLat', camPos.lat.toFixed(5)); url.searchParams.set('cLng', camPos.lng.toFixed(5));
                url.searchParams.set('tLat', targetPos.lat.toFixed(5)); url.searchParams.set('tLng', targetPos.lng.toFixed(5));
                url.searchParams.set('date', date.getTime());
                
                const text = url.toString();
                const textArea = document.createElement("textarea");
                textArea.value = text;
                textArea.style.position = "fixed"; textArea.style.left = "-999999px"; textArea.style.top = "-999999px";
                document.body.appendChild(textArea);
                textArea.focus(); textArea.select();
                
                try {
                    document.execCommand('copy');
                    showToast("Plan URL copied to clipboard!");
                } catch (err) { showToast("Failed to copy Plan URL."); }
                document.body.removeChild(textArea);
            };

            const handleCopyGPS = (type) => {
                const pos = type === 'camera' ? camPos : targetPos;
                const text = `${pos.lat.toFixed(6)}, ${pos.lng.toFixed(6)}`;
                const textArea = document.createElement("textarea");
                textArea.value = text;
                textArea.style.position = "fixed"; textArea.style.left = "-999999px"; textArea.style.top = "-999999px";
                document.body.appendChild(textArea);
                textArea.focus(); textArea.select();
                
                try {
                    document.execCommand('copy');
                    showToast(`${type === 'camera' ? 'Camera' : 'Target'} GPS Copied!`);
                } catch (err) { showToast('Failed to copy GPS'); }
                document.body.removeChild(textArea);
            };

            const handleNavigateToCamera = () => {
                window.open(`https://www.google.com/maps/dir/?api=1&destination=${camPos.lat},${camPos.lng}`, '_blank');
            };

            const handleSaveToLibrary = (name) => {
                if(!name) return;
                const newPlan = { id: Date.now(), name, date: date.getTime(), camPos, targetPos, targetHeight, targetWidth, focalLength, sensor, aperture };
                setSavedPlans(prev => [...prev, newPlan]);
                showToast("Plan saved to library!");
            };

            const handleLoadPlan = (plan) => {
                setDate(new Date(plan.date)); setCamPos(plan.camPos); setTargetPos(plan.targetPos);
                if(plan.targetHeight) setTargetHeight(plan.targetHeight);
                if(plan.targetWidth) setTargetWidth(plan.targetWidth);
                if(plan.focalLength) setFocalLength(plan.focalLength);
                if(plan.sensor) setSensor(plan.sensor);
                if(plan.aperture) setAperture(plan.aperture);
                
                if (mapInstanceRef.current) {
                    const bounds = L.latLngBounds([plan.camPos, plan.targetPos]);
                    mapInstanceRef.current.fitBounds(bounds, { padding: [50, 50], maxZoom: 16 });
                }
                setShowPlans(false);
                showToast("Plan loaded!");
            };

            const handleDeletePlan = (id) => setSavedPlans(prev => prev.filter(p => p.id !== id));

            const handleExportPlan = () => {
                if (!alignment || !sunData || !moonData) {
                    alert("Please wait for ephemeris data to load before exporting.");
                    return;
                }
                const printWindow = window.open('', '_blank');
                const sunDelta = getDelta(sunData.azimuth, alignment.bearing);
                const moonDelta = getDelta(moonData.azimuth, alignment.bearing);
                
                const html = `<!DOCTYPE html>
                    <html lang="en">
                    <head><meta charset="UTF-8"><title>Shoot Plan: ${date.toLocaleDateString('en-GB')}</title>
                        <style>
                            body { font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; color: #1e293b; padding: 30px; line-height: 1.5; max-width: 800px; margin: 0 auto; background: white;}
                            h1 { color: #0f172a; border-bottom: 2px solid #cbd5e1; padding-bottom: 10px; margin-bottom: 30px; font-size: 28px; text-transform: uppercase; letter-spacing: 1px;}
                            h2 { color: #0ea5e9; font-size: 16px; text-transform: uppercase; letter-spacing: 1.5px; border-bottom: 1px solid #e2e8f0; padding-bottom: 5px; margin-top: 30px;}
                            .grid { display: flex; flex-wrap: wrap; gap: 30px; } .col { flex: 1; min-width: 300px; }
                            .data-row { display: flex; justify-content: space-between; margin-bottom: 8px; border-bottom: 1px dashed #f1f5f9; padding-bottom: 4px;}
                            .label { font-weight: bold; color: #64748b; font-size: 13px; } .val { font-family: 'Courier New', Courier, monospace; font-weight: 700; font-size: 14px; color: #0f172a;}
                            .badge { padding: 3px 6px; border-radius: 4px; font-size: 11px; font-weight: bold; font-family: sans-serif; text-transform: uppercase;}
                            .badge.green { background: #dcfce7; color: #065f46; border: 1px solid #bbf7d0; } .badge.red { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }
                            .footer { margin-top: 50px; font-size: 11px; color: #94a3b8; text-align: center; border-top: 1px solid #f1f5f9; padding-top: 20px;}
                            @media print { body { padding: 0; } }
                        </style>
                    </head>
                    <body>
                        <h1>NorthernPixl Shoot Plan</h1>
                        <div class="grid">
                            <div class="col">
                                <h2>Location & Target</h2>
                                <div class="data-row"><span class="label">Date & Time:</span><span class="val">${date.toLocaleDateString('en-GB')} at ${date.toLocaleTimeString('en-GB', {hour:'2-digit', minute:'2-digit', second:'2-digit'})}</span></div>
                                <div class="data-row"><span class="label">Camera Coordinates:</span><span class="val">${camPos.lat.toFixed(6)}, ${camPos.lng.toFixed(6)}</span></div>
                                <div class="data-row"><span class="label">Target Coordinates:</span><span class="val">${targetPos.lat.toFixed(6)}, ${targetPos.lng.toFixed(6)}</span></div>
                                <div class="data-row"><span class="label">Bearing to Target:</span><span class="val">${formatDeg(alignment.bearing)}</span></div>
                                <div class="data-row"><span class="label">Distance to Target:</span><span class="val">${(alignment.distance/1000).toFixed(3)} km</span></div>
                                <div class="data-row"><span class="label">Target Dimensions:</span><span class="val">${targetHeight}m H &times; ${targetWidth}m W</span></div>
                            </div>
                            <div class="col">
                                <h2>Terrain & Optics</h2>
                                <div class="data-row"><span class="label">Camera Elevation:</span><span class="val">${terrainData ? Math.round(terrainData.camElev) + 'm' : 'Loading...'}</span></div>
                                <div class="data-row"><span class="label">Target Elevation:</span><span class="val">${terrainData ? Math.round(terrainData.tgtElev) + 'm' : 'Loading...'}</span></div>
                                <div class="data-row"><span class="label">Line of Sight Check:</span><span class="val">${terrainData ? (terrainData.blocked ? '<span class="badge red">BLOCKED</span>' : '<span class="badge green">CLEAR</span>') : '...'}</span></div>
                                <div class="data-row"><span class="label">Lens Setup:</span><span class="val">${focalLength}mm f/${aperture} (${sensor})</span></div>
                                <div class="data-row"><span class="label">Camera FOV:</span><span class="val">${fovAzimuth.toFixed(1)}&deg; &times; ${fovAltitude.toFixed(1)}&deg;</span></div>
                                <div class="data-row"><span class="label">Hyperfocal Distance:</span><span class="val">${hyperfocal.toFixed(2)}m</span></div>
                            </div>
                        </div>
                        <div class="grid">
                            <div class="col">
                                <h2>Sun Status</h2>
                                <div class="data-row"><span class="label">Sun Azimuth / Altitude:</span><span class="val">${formatDeg(sunData.azimuth)} / ${sunData.altitude.toFixed(2)}&deg;</span></div>
                                <div class="data-row"><span class="label">Alignment Delta:</span><span class="val">${sunDelta !== null ? sunDelta.toFixed(2) + '&deg;' : 'N/A'}</span></div>
                                <div class="data-row"><span class="label">Sunrise / Sunset:</span><span class="val">${formatTimeStr(sunData.riseTime)} / ${formatTimeStr(sunData.setTime)}</span></div>
                                <div class="data-row"><span class="label">Golden Hour:</span><span class="val">${formatTimeStr(sunData.goldenHour)}</span></div>
                                <div class="data-row"><span class="label">Astro Dark Window:</span><span class="val">${formatTimeStr(sunData.night)} &rarr; ${formatTimeStr(sunData.nightEnd)}</span></div>
                            </div>
                            <div class="col">
                                <h2>Moon & Stars</h2>
                                <div class="data-row"><span class="label">Moon Azimuth / Altitude:</span><span class="val">${formatDeg(moonData.azimuth)} / ${moonData.altitude.toFixed(2)}&deg;</span></div>
                                <div class="data-row"><span class="label">Alignment Delta:</span><span class="val">${moonDelta !== null ? moonDelta.toFixed(2) + '&deg;' : 'N/A'}</span></div>
                                <div class="data-row"><span class="label">Moonrise / Moonset:</span><span class="val">${formatTimeStr(moonData.riseTime)} / ${formatTimeStr(moonData.setTime)}</span></div>
                                <div class="data-row"><span class="label">Lunar Phase:</span><span class="val">${moonData.fraction}% (${getPhaseName(moonData.phase)})</span></div>
                                <div class="data-row"><span class="label">Spot Stars Limit (NPF/500):</span><span class="val">${astroStats.npf}s / ${astroStats.rule500}s</span></div>
                            </div>
                        </div>
                        <div class="footer">Generated by NorthernPixl Advanced Shoot Planner using NASA JPL DE431 Ephemeris and WGS-84 Ellipsoidal Projection.</div>
                    </body></html>`;
                printWindow.document.write(html);
                printWindow.document.close();
                setTimeout(() => { printWindow.print(); }, 250);
            };

            const secondsOfDay = date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds();
            const sunDelta = sunData && alignment ? getDelta(sunData.azimuth, alignment.bearing) : null;
            const moonDelta = moonData && alignment ? getDelta(moonData.azimuth, alignment.bearing) : null;

            return (
                <div className="w-full h-[100dvh] flex flex-col relative transition-all duration-300 overflow-hidden">
                    <Navbar />
                    
                    <main className="relative w-full h-[calc(100dvh-4rem)] mt-16">
                        <div className="absolute inset-0 z-0">
                            <div ref={mapContainerRef} className="w-full h-full"></div>
                            
                            {showMWOverlay && mwData && (
                                <div className="absolute inset-0 z-[100] pointer-events-none overflow-hidden">
                                    <div className="absolute inset-0 bg-slate-900/50 mix-blend-multiply"></div>
                                    <svg className="w-full h-full absolute inset-0">
                                        <circle cx={tgtPixelPos.x} cy={tgtPixelPos.y} r={40} fill="none" stroke="rgba(255,255,255,0.2)" strokeWidth="1" strokeDasharray="4 4" />
                                        <circle cx={tgtPixelPos.x} cy={tgtPixelPos.y} r={80} fill="none" stroke="rgba(255,255,255,0.2)" strokeWidth="1" strokeDasharray="4 4" />
                                        <circle cx={tgtPixelPos.x} cy={tgtPixelPos.y} r={120} fill="none" stroke="rgba(255,255,255,0.4)" strokeWidth="1.5" />
                                        
                                        <line x1={tgtPixelPos.x} y1={tgtPixelPos.y - 125} x2={tgtPixelPos.x} y2={tgtPixelPos.y + 125} stroke="rgba(255,255,255,0.1)" strokeWidth="1" />
                                        <line x1={tgtPixelPos.x - 125} y1={tgtPixelPos.y} x2={tgtPixelPos.x + 125} y2={tgtPixelPos.y} stroke="rgba(255,255,255,0.1)" strokeWidth="1" />
                                        <text x={tgtPixelPos.x} y={tgtPixelPos.y - 130} fill="rgba(255,255,255,0.6)" fontSize="10" textAnchor="middle">N</text>
                                        <text x={tgtPixelPos.x + 130} y={tgtPixelPos.y} fill="rgba(255,255,255,0.6)" fontSize="10" alignmentBaseline="middle">E</text>

                                        {GALACTIC_EQUATOR.map((pt, i) => {
                                            const lst = getLST(date, targetPos.lng);
                                            const { alt, az } = getAltAz(pt.ra, pt.dec, targetPos.lat, lst);
                                            const r = 120 * ((90 - alt) / 90);
                                            if (r > 600) return null; 
                                            const px = tgtPixelPos.x + r * Math.sin(az * Math.PI/180);
                                            const py = tgtPixelPos.y - r * Math.cos(az * Math.PI/180);
                                            const isVisible = alt > 0;
                                            return <circle key={i} cx={px} cy={py} r={3} fill={isVisible ? "#f8fafc" : "rgba(255,255,255,0.15)"} className="drop-shadow-md" />;
                                        })}

                                        {(() => {
                                            const r = 120 * ((90 - mwData.alt) / 90);
                                            if (r > 600) return null;
                                            const px = tgtPixelPos.x + r * Math.sin(mwData.az * Math.PI/180);
                                            const py = tgtPixelPos.y - r * Math.cos(mwData.az * Math.PI/180);
                                            return (
                                                <g>
                                                    <line x1={tgtPixelPos.x} y1={tgtPixelPos.y} x2={px} y2={py} stroke="rgba(217, 70, 239, 0.5)" strokeWidth="1.5" strokeDasharray="4 2" />
                                                    <circle cx={px} cy={py} r={14} fill="rgba(217, 70, 239, 0.2)" />
                                                    <circle cx={px} cy={py} r={6} fill="#d946ef" stroke="#fff" strokeWidth="1.5" className="drop-shadow-lg" />
                                                </g>
                                            );
                                        })()}
                                    </svg>
                                </div>
                            )}
                        </div>
                        
                        <div className={`absolute top-6 left-1/2 -translate-x-1/2 z-[3000] transition-all duration-300 pointer-events-none ${toastMsg ? 'opacity-100 translate-y-0' : 'opacity-0 -translate-y-4'}`}>
                            <div className="bg-slate-900 text-white px-5 py-3 rounded-full shadow-xl flex items-center gap-2">
                                <Icon name="check" size={16} className="text-emerald-400" />
                                <span className="text-[11px] md:text-xs font-bold uppercase tracking-widest">{toastMsg}</span>
                            </div>
                        </div>

                        {/* Search Bar - Slides inline with Left Panel */}
                        <div className="absolute top-16 md:top-6 left-1/2 -translate-x-1/2 md:left-[24.5rem] lg:left-[25.5rem] xl:left-[26.5rem] md:transform-none z-[400] bg-white/95 backdrop-blur-md rounded-full shadow-md border border-slate-200 flex items-center px-4 py-2 w-72 md:w-80 lg:w-96 hidden md:flex transition-all duration-300">
                            <select value={searchType} onChange={(e) => setSearchType(e.target.value)} className="bg-transparent text-slate-500 text-[10px] md:text-xs font-bold uppercase tracking-widest outline-none border-r border-slate-200 pr-2 mr-2 cursor-pointer">
                                <option value="camera">Camera</option>
                                <option value="target">Target</option>
                            </select>
                            <Icon name="search" size={16} className="text-slate-400 mr-2 shrink-0" />
                            <form onSubmit={handleSearch} className="w-full">
                                <input type="text" placeholder={searchType === 'camera' ? "Search camera location..." : "Search target landmark..."} value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} className="bg-transparent border-none outline-none text-[11px] md:text-xs font-bold text-slate-700 w-full" />
                            </form>
                        </div>

                        <div className="absolute top-3 left-2 right-2 z-[1010] flex md:hidden bg-white/95 backdrop-blur-md rounded-xl p-1 shadow-sm border border-slate-200">
                            <button onClick={() => setMobileTab('map')} className={`flex-1 py-2 text-[10px] font-black uppercase tracking-widest rounded-lg transition-all ${mobileTab === 'map' ? 'bg-slate-900 text-white shadow-md' : 'text-slate-500 hover:bg-slate-100'}`}><Icon name="map" size={14} className="inline mr-1" /> Map</button>
                            <button onClick={() => setMobileTab('alignment')} className={`flex-1 py-2 text-[10px] font-black uppercase tracking-widest rounded-lg transition-all ${mobileTab === 'alignment' ? 'bg-slate-900 text-white shadow-md' : 'text-slate-500 hover:bg-slate-100'}`}>Alignment</button>
                            <button onClick={() => setMobileTab('ephemeris')} className={`flex-1 py-2 text-[10px] font-black uppercase tracking-widest rounded-lg transition-all ${mobileTab === 'ephemeris' ? 'bg-sky-500 text-white shadow-md' : 'text-slate-500 hover:bg-slate-100'}`}>Sun/Moon</button>
                        </div>

                        {/* Map Layers - Stacks below Search Bar on MD/LG, snaps right on XL */}
                        <div className={`absolute top-[4.2rem] md:top-20 xl:top-6 left-4 md:left-[24.5rem] lg:left-[25.5rem] xl:left-auto xl:right-[24.5rem] lg:right-[25.5rem] xl:right-[26.5rem] z-[400] bg-white/95 backdrop-blur-md rounded-lg shadow-md border border-slate-200 ${mobileTab !== 'map' ? 'hidden md:flex' : 'flex'} transition-all duration-300`}>
                            <button onClick={() => setLayerMode('standard')} className={`px-3 py-2 text-[10px] font-black uppercase tracking-widest rounded-l-lg transition-all ${layerMode === 'standard' ? 'bg-slate-900 text-white' : 'text-slate-500 hover:bg-slate-100'}`}>Standard</button>
                            <button onClick={() => setLayerMode('topo')} className={`px-3 py-2 text-[10px] font-black uppercase tracking-widest transition-all ${layerMode === 'topo' ? 'bg-emerald-600 text-white' : 'text-slate-500 hover:bg-slate-100'}`}>Topo Map</button>
                            <button onClick={() => setShowMWOverlay(!showMWOverlay)} className={`px-3 py-2 text-[10px] font-black uppercase tracking-widest rounded-r-lg border-l border-slate-200 transition-all ${showMWOverlay ? 'bg-fuchsia-600 text-white shadow-inner' : 'text-slate-500 hover:bg-slate-100'}`}>Milky Way 2D</button>
                        </div>

                        {/* Left Panel - Alignment & Camera */}
                        <div className={`absolute top-[8rem] md:top-6 left-2 md:left-[5.5rem] lg:left-[6.5rem] right-2 md:right-auto z-[1005] md:z-[400] bg-white/95 backdrop-blur-md rounded-xl md:rounded-2xl shadow-xl border border-slate-200 flex-col ${mobileTab === 'alignment' ? 'flex' : 'hidden md:flex'} w-auto md:w-72 lg:w-80 animate-in transition-all duration-300`}>
                            <div className="flex justify-between items-center p-3 md:p-4 border-b border-slate-100 cursor-default">
                                <h3 className="font-black text-[10px] md:text-xs uppercase tracking-widest text-slate-700 flex items-center gap-2"><Icon name="target" size={14} className="text-rose-500"/> Setup & Alignment</h3>
                                <button 
                                    onClick={() => setLeftPanelExpanded(!leftPanelExpanded)} 
                                    className="hidden md:flex items-center justify-center bg-slate-100 hover:bg-slate-200 text-slate-500 rounded-lg p-1.5 transition-colors"
                                    title={leftPanelExpanded ? "Minimise Panel" : "Maximise Panel"}
                                >
                                    <Icon name="chevronDown" size={14} className={`transition-transform duration-300 ${leftPanelExpanded ? 'rotate-180' : ''}`} />
                                </button>
                            </div>

                            <div className={`px-3 md:px-5 pb-3 md:pb-5 pt-3 overflow-y-auto max-h-[65dvh] md:max-h-[calc(100dvh-12rem)] custom-scrollbar ${leftPanelExpanded ? 'block' : 'block md:hidden'}`}>
                                {alignment && (
                                    <>
                                        <div className="flex justify-between items-center bg-slate-50 border border-slate-100 rounded-lg p-2.5 mb-3">
                                            <div className="text-center w-1/2 border-r border-slate-200">
                                                <span className="block text-[8px] md:text-[9px] font-black uppercase tracking-widest text-slate-400 mb-0.5">Bearing</span>
                                                <span className="font-bold text-base md:text-xl text-slate-900 leading-none">{formatDeg(alignment.bearing)}</span>
                                            </div>
                                            <div className="text-center w-1/2">
                                                <span className="block text-[8px] md:text-[9px] font-black uppercase tracking-widest text-slate-400 mb-0.5">Distance</span>
                                                <span className="font-bold text-base md:text-xl text-slate-900 leading-none">{(alignment.distance / 1000).toFixed(2)}<span className="text-[10px] ml-0.5 text-slate-500 font-normal">km</span></span>
                                            </div>
                                        </div>
                                        
                                        {/* Fix: Bulletproof SVG baseline mapping for 100% flat locations */}
                                        {terrainData && terrainData.profile && (() => {
                                            const minElev = Math.min(...terrainData.profile.map(p => p.elev));
                                            const maxElev = Math.max(...terrainData.profile.map(p => p.elev));
                                            const range = Math.max(1, maxElev - minElev);
                                            
                                            const pointsStr = `0,100 ${terrainData.profile.map((p, i) => {
                                                const x = (i / (terrainData.profile.length - 1 || 1)) * 100;
                                                // Leaves a permanent 10% minimum height for the baseline so shapes are never rendered invisible
                                                const y = 90 - (((p.elev - minElev) / range) * 80);
                                                return `${x.toFixed(2)},${y.toFixed(2)}`;
                                            }).join(' ')} 100,100`;

                                            return (
                                                <div className="mb-3 bg-slate-100 rounded-lg relative h-10 w-full overflow-hidden flex items-end">
                                                    <svg viewBox="0 0 100 100" preserveAspectRatio="none" className="absolute inset-0 w-full h-full opacity-60">
                                                        <polygon points={pointsStr} fill="#94a3b8" />
                                                    </svg>
                                                    <div className="relative w-full flex justify-between items-center text-[8px] font-bold text-slate-600 px-2 pb-1 drop-shadow-md">
                                                        <span>Cam {Math.round(terrainData.camElev)}m</span>
                                                        <Icon name="mountain" size={10} className="opacity-50" />
                                                        <span>Tgt {Math.round(terrainData.tgtElev)}m</span>
                                                    </div>
                                                </div>
                                            );
                                        })()}
                                        
                                        {terrainData && terrainData.blocked && (
                                            <div className="flex items-center text-red-600 text-[9px] font-black uppercase tracking-widest mb-3 gap-1.5 bg-red-50 p-2 rounded-lg border border-red-100 shadow-sm">
                                                <Icon name="alertTriangle" size={12} className="shrink-0" /> Line of Sight Blocked
                                            </div>
                                        )}

                                        {corridorData && (
                                            <div className="mb-3 bg-slate-50 border border-slate-200 rounded-lg p-2.5 shadow-inner">
                                                <span className="block text-[8px] font-black uppercase tracking-widest text-slate-500 mb-1.5 flex items-center gap-1"><Icon name="map" size={10}/> 15km Alignment Corridor</span>
                                                <div className="flex flex-col gap-1">
                                                    <div className="flex items-center gap-2 text-[9px] text-slate-600 font-bold"><span className="w-4 h-1.5 rounded-full bg-emerald-500"></span> Valid Viewpoint</div>
                                                    <div className="flex items-center gap-2 text-[9px] text-slate-600 font-bold"><span className="w-4 h-1.5 rounded-full bg-red-500 opacity-60"></span> Blocked / Water</div>
                                                </div>
                                            </div>
                                        )}

                                        <div className="flex gap-2 mb-3">
                                            <button onClick={() => handleCopyGPS('camera')} className="flex-1 bg-slate-100 hover:bg-slate-200 text-slate-600 py-1.5 rounded-lg flex items-center justify-center gap-1.5 transition-colors border border-slate-200 shadow-sm">
                                                <Icon name="copy" size={10} />
                                                <span className="text-[8px] md:text-[9px] font-bold uppercase tracking-widest">Copy Cam GPS</span>
                                            </button>
                                            <button onClick={handleNavigateToCamera} className="flex-1 bg-sky-100 hover:bg-sky-200 text-sky-700 py-1.5 rounded-lg flex items-center justify-center gap-1.5 transition-colors border border-sky-200 shadow-sm">
                                                <Icon name="navigation" size={10} />
                                                <span className="text-[8px] md:text-[9px] font-bold uppercase tracking-widest">Navigate</span>
                                            </button>
                                        </div>
                                        
                                        <div className="space-y-1.5">
                                            {sunData && sunDelta !== null && (
                                                <div className="flex justify-between items-center bg-amber-50/50 border border-amber-100/50 p-2 rounded-lg">
                                                    <span className="text-amber-600 flex items-center gap-1.5 text-[9px] font-black uppercase tracking-widest"><Icon name="sun" size={12}/> Azimuth</span>
                                                    <span className="text-xs font-bold text-amber-900">{formatDeg(sunData.azimuth)}</span>
                                                    <span className={`px-1.5 py-0.5 rounded text-[9px] font-bold shadow-sm border ${sunDelta < 2 ? 'bg-emerald-500 text-white border-emerald-600' : 'bg-white border-amber-200 text-amber-700'}`}>
                                                        Δ {sunDelta.toFixed(1)}°
                                                    </span>
                                                </div>
                                            )}
                                            {moonData && moonDelta !== null && (
                                                <div className="flex justify-between items-center bg-indigo-50/50 border border-indigo-100/50 p-2 rounded-lg">
                                                    <span className="text-indigo-600 flex items-center gap-1.5 text-[9px] font-black uppercase tracking-widest"><Icon name="moon" size={12}/> Azimuth</span>
                                                    <span className="text-xs font-bold text-indigo-900">{formatDeg(moonData.azimuth)}</span>
                                                    <span className={`px-1.5 py-0.5 rounded text-[9px] font-bold shadow-sm border ${moonDelta < 2 ? 'bg-emerald-500 text-white border-emerald-600' : 'bg-white border-indigo-200 text-indigo-700'}`}>
                                                        Δ {moonDelta.toFixed(1)}°
                                                    </span>
                                                </div>
                                            )}
                                        </div>

                                        <div className="flex gap-2 mt-2">
                                            <button onClick={() => handleTimeMachine('sun')} disabled={isSearchingTime} className="flex-1 bg-amber-100 hover:bg-amber-200 text-amber-700 py-1.5 rounded-lg flex items-center justify-center gap-1 transition-colors shadow-sm disabled:opacity-50">
                                                <Icon name="clockArrow" size={12} />
                                                <span className="text-[8px] md:text-[9px] font-black uppercase tracking-widest">Next Sun</span>
                                            </button>
                                            <button onClick={() => handleTimeMachine('moon')} disabled={isSearchingTime} className="flex-1 bg-indigo-100 hover:bg-indigo-200 text-indigo-700 py-1.5 rounded-lg flex items-center justify-center gap-1 transition-colors shadow-sm disabled:opacity-50">
                                                <Icon name="clockArrow" size={12} />
                                                <span className="text-[8px] md:text-[9px] font-black uppercase tracking-widest">Next Moon</span>
                                            </button>
                                        </div>

                                        <button onClick={() => setShowViewfinder(true)} className="w-full mt-3 bg-slate-900 hover:bg-slate-800 text-white py-2.5 rounded-lg flex items-center justify-center gap-1.5 transition-colors shadow-md group">
                                            <Icon name="viewfinder" size={14} className="text-sky-400 group-hover:scale-110 transition-transform" />
                                            <span className="text-[9px] md:text-[10px] font-black uppercase tracking-widest">Virtual Viewfinder</span>
                                        </button>
                                    </>
                                )}
                                
                                <div className="mt-4 pt-3 border-t border-slate-100">
                                    <label className="flex items-center gap-1.5 text-[9px] font-black text-slate-400 uppercase tracking-widest mb-2">
                                        <Icon name="aperture" size={12} /> Camera & Lens (FOV)
                                    </label>
                                    <div className="flex gap-2">
                                        <select value={sensor} onChange={(e) => setSensor(e.target.value)} className="bg-slate-50 border border-slate-200 text-slate-700 text-[10px] font-bold rounded p-1.5 flex-1 outline-none">
                                            <option value="FF">Full Frame</option>
                                            <option value="APSC-N">APS-C (1.5x)</option>
                                            <option value="APSC-C">APS-C (1.6x)</option>
                                            <option value="M43">Micro 4/3</option>
                                        </select>
                                        <div className="relative flex-1 bg-slate-50 border border-slate-200 rounded flex items-center p-1.5">
                                            <input type="number" value={focalLength} onChange={(e) => setFocalLength(e.target.value)} className="bg-transparent border-none text-slate-700 text-[10px] font-bold w-full outline-none text-right" min="10" max="2000" />
                                            <span className="text-[9px] text-slate-400 font-bold ml-1">mm</span>
                                        </div>
                                    </div>
                                    <div className="flex justify-between items-center text-[9px] mt-2 bg-slate-50 border border-slate-200 p-1.5 rounded">
                                         <span className="text-slate-500 font-bold" title="Max Shutter Speed to avoid star trailing">Spot Stars:</span>
                                         <span className="text-slate-800 font-black">{astroStats.npf}s <span className="text-slate-400 font-normal">(NPF)</span> | {astroStats.rule500}s <span className="text-slate-400 font-normal">(500)</span></span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        {/* Right Panel - Ephemeris */}
                        <div className={`absolute top-14 md:top-6 right-2 md:right-[5.5rem] lg:right-[6.5rem] left-2 md:left-auto z-[1005] md:z-[400] bg-white/95 backdrop-blur-md rounded-xl md:rounded-2xl shadow-xl border border-slate-200 flex-col ${mobileTab === 'ephemeris' ? 'flex' : 'hidden md:flex'} w-auto md:w-72 lg:w-80 animate-in transition-all duration-300`}>
                            <div className="flex justify-between items-center p-3 md:p-4 border-b border-slate-100 cursor-default">
                                <h3 className="font-black text-[10px] md:text-xs uppercase tracking-widest text-slate-700 flex items-center gap-2"><Icon name="sun" size={14} className="text-amber-500"/> Celestial Ephemeris</h3>
                                <button 
                                    onClick={() => setRightPanelExpanded(!rightPanelExpanded)} 
                                    className="hidden md:flex items-center justify-center bg-slate-100 hover:bg-slate-200 text-slate-500 rounded-lg p-1.5 transition-colors"
                                    title={rightPanelExpanded ? "Minimise Panel" : "Maximise Panel"}
                                >
                                    <Icon name="chevronDown" size={14} className={`transition-transform duration-300 ${rightPanelExpanded ? 'rotate-180' : ''}`} />
                                </button>
                            </div>

                            <div className={`px-3 md:px-5 pb-3 md:pb-5 pt-3 overflow-y-auto max-h-[65dvh] md:max-h-[calc(100dvh-12rem)] custom-scrollbar ${rightPanelExpanded ? 'block' : 'block md:hidden'}`}>
                                {sunData && moonData && (
                                    <div className="flex flex-col gap-3">
                                        <div className="bg-amber-50/50 rounded-lg p-3 border border-amber-100/50">
                                            <div className="flex items-center justify-between mb-3">
                                                <div className="flex items-center gap-2">
                                                    <Icon name="sun" size={14} className="text-amber-500" />
                                                    <span className="font-black uppercase tracking-widest text-[11px] text-amber-700">Solar Ephemeris</span>
                                                </div>
                                                <span className={`text-[10px] font-bold px-2 py-0.5 rounded-md ${sunData.altitude > 0 ? 'bg-amber-100 text-amber-700' : 'bg-slate-200 text-slate-600'}`}>{sunData.altitude.toFixed(1)}°</span>
                                            </div>
                                            <div className="grid grid-cols-2 gap-x-4 gap-y-2">
                                                <div className="flex justify-between items-center text-[10px] border-b border-amber-100 pb-1 col-span-2">
                                                    <span className="font-bold text-slate-500 uppercase tracking-wider">Astro Dark</span>
                                                    <span className="font-bold text-slate-800">{formatTimeStr(sunData.night)} - {formatTimeStr(sunData.nightEnd)}</span>
                                                </div>
                                                <div className="flex justify-between items-center text-[10px] border-b border-amber-100 pb-1 col-span-2">
                                                    <span className="font-bold text-slate-500 uppercase tracking-wider">Blue Hour (Civil)</span>
                                                    <span className="font-bold text-sky-700">{formatTimeStr(sunData.dawn)} - {formatTimeStr(sunData.dusk)}</span>
                                                </div>
                                                <div className="flex justify-between items-center text-[10px] col-span-2">
                                                    <span className="font-bold text-orange-500 uppercase tracking-wider">Gold Hr</span>
                                                    <span className="font-bold text-slate-800">{formatTimeStr(sunData.goldenHour)}</span>
                                                </div>
                                                <div className="flex justify-between items-center text-[10px] col-span-2">
                                                    <span className="font-bold text-slate-500 uppercase tracking-wider">Rise</span>
                                                    <span className="font-bold text-slate-800 flex items-center">{formatTimeStr(sunData.riseTime)} <HorizonBadge coverObj={horizonWeather.sunRise} /></span>
                                                </div>
                                                <div className="flex justify-between items-center text-[10px] col-span-2">
                                                    <span className="font-bold text-slate-500 uppercase tracking-wider">Set</span>
                                                    <span className="font-bold text-slate-800 flex items-center">{formatTimeStr(sunData.setTime)} <HorizonBadge coverObj={horizonWeather.sunSet} /></span>
                                                </div>
                                            </div>
                                        </div>

                                        <div className="bg-indigo-50/50 rounded-lg p-3 border border-indigo-100/50">
                                            <div className="flex items-center justify-between mb-3">
                                                <div className="flex items-center gap-2">
                                                    <Icon name="moon" size={14} className="text-indigo-500" />
                                                    <span className="font-black uppercase tracking-widest text-[11px] text-indigo-700">Lunar Ephemeris</span>
                                                </div>
                                                <span className="text-[10px] font-black uppercase bg-indigo-100 text-indigo-700 px-2 py-0.5 rounded shadow-sm border border-indigo-200">{moonData.fraction}%</span>
                                            </div>
                                            <div className="grid grid-cols-2 gap-x-4 gap-y-2">
                                                <div className="flex justify-between items-center text-[10px] col-span-2 border-b border-indigo-100 pb-1">
                                                    <span className="font-bold text-slate-500 uppercase tracking-wider">Phase</span>
                                                    <span className="font-bold text-indigo-900 text-right">{getPhaseName(moonData.phase)}</span>
                                                </div>
                                                <div className="flex justify-between items-center text-[10px] col-span-2 border-b border-indigo-100 pb-1">
                                                    <span className="font-bold text-slate-500 uppercase tracking-wider">Altitude</span>
                                                    <span className={`font-bold ${moonData.altitude > 0 ? 'text-indigo-600' : 'text-slate-400'}`}>{moonData.altitude.toFixed(1)}°</span>
                                                </div>
                                                <div className="flex justify-between items-center text-[10px] col-span-2">
                                                    <span className="font-bold text-slate-500 uppercase tracking-wider">Rise</span>
                                                    <span className="font-bold text-slate-800 flex items-center">{formatTimeStr(moonData.riseTime)} <HorizonBadge coverObj={horizonWeather.moonRise} /></span>
                                                </div>
                                                <div className="flex justify-between items-center text-[10px] col-span-2">
                                                    <span className="font-bold text-slate-500 uppercase tracking-wider">Set</span>
                                                    <span className="font-bold text-slate-800 flex items-center">{formatTimeStr(moonData.setTime)} <HorizonBadge coverObj={horizonWeather.moonSet} /></span>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        {mwData && (
                                            <div className="bg-slate-900 rounded-lg p-3 shadow-inner">
                                                <div className="flex items-center justify-between mb-3">
                                                    <div className="flex items-center gap-2">
                                                        <Icon name="stars" size={14} className="text-fuchsia-400" />
                                                        <span className="font-black uppercase tracking-widest text-[11px] text-fuchsia-300">Milky Way Core</span>
                                                    </div>
                                                    <span className={`text-[9px] font-bold px-2 py-0.5 rounded uppercase tracking-widest ${mwData.visible ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-700 text-slate-400'}`}>
                                                        {mwData.visible ? 'Visible' : 'Invisible'}
                                                    </span>
                                                </div>
                                                <div className="grid grid-cols-2 gap-x-4 gap-y-2">
                                                    <div className="flex justify-between items-center text-[10px] col-span-2 border-b border-slate-700 pb-1">
                                                        <span className="font-bold text-slate-400 uppercase tracking-wider">Altitude</span>
                                                        <span className={`font-bold ${mwData.alt > 0 ? 'text-fuchsia-400' : 'text-slate-500'}`}>{mwData.alt.toFixed(1)}°</span>
                                                    </div>
                                                    <div className="flex justify-between items-center text-[10px] col-span-2 border-b border-slate-700 pb-1">
                                                        <span className="font-bold text-slate-400 uppercase tracking-wider">Azimuth</span>
                                                        <span className="font-bold text-slate-300">{formatDeg(mwData.az)}</span>
                                                    </div>
                                                </div>
                                            </div>
                                        )}
                                    </div>
                                )}
                            </div>
                        </div>

                        {/* Right Cluster Toolbar */}
                        <div className={`absolute right-3 md:right-4 lg:right-5 z-[400] flex flex-col gap-3 transition-all duration-300 ${showTimeline ? 'bottom-[120px] md:bottom-[130px]' : 'bottom-6 md:bottom-6'} ${mobileTab !== 'map' ? 'hidden md:flex' : ''}`}>
                            <button onClick={handleExportPlan} className="w-[38px] md:w-[42px] h-[38px] md:h-[42px] bg-sky-50 backdrop-blur-md rounded-full shadow-md border border-sky-200 flex items-center justify-center text-sky-600 hover:bg-sky-500 hover:text-white transition-colors" title="Download/Print Shoot Plan">
                                <Icon name="download" size={18} />
                            </button>
                            <button onClick={handleStreetView} className="w-[38px] md:w-[42px] h-[38px] md:h-[42px] bg-white/90 backdrop-blur-md rounded-full shadow-md border border-slate-200 flex items-center justify-center text-slate-500 hover:text-amber-500 transition-colors" title="Open in Google Street View">
                                <Icon name="streetView" size={18} />
                            </button>
                            <button onClick={handleSavePlan} className="w-[38px] md:w-[42px] h-[38px] md:h-[42px] bg-white/90 backdrop-blur-md rounded-full shadow-md border border-slate-200 flex items-center justify-center text-slate-500 hover:text-sky-500 transition-colors" title="Copy Plan URL to Clipboard">
                                <Icon name="link" size={18} />
                            </button>
                            <button onClick={handleLocateMe} disabled={isLocating} className={`w-[38px] md:w-[42px] h-[38px] md:h-[42px] bg-white/90 backdrop-blur-md rounded-full shadow-md border border-slate-200 flex items-center justify-center transition-colors ${isLocating ? 'text-sky-500 animate-pulse' : 'text-slate-500 hover:text-sky-500'}`} title="Move Camera to My Location">
                                <Icon name="locate" size={18} />
                            </button>
                        </div>

                        {/* Left Cluster Toolbar */}
                        <div className={`absolute left-3 md:left-4 lg:left-5 z-[400] flex flex-col gap-3 transition-all duration-300 ${showTimeline ? 'bottom-[120px] md:bottom-[130px]' : 'bottom-6 md:bottom-6'} ${mobileTab !== 'map' ? 'hidden md:flex' : ''}`}>
                            <button onClick={() => setShowTimeline(!showTimeline)} className="w-[38px] md:w-[42px] h-[38px] md:h-[42px] bg-slate-900/90 backdrop-blur-md rounded-full shadow-md border border-slate-700 flex items-center justify-center text-white hover:bg-slate-800 transition-colors" title="Toggle Timeline">
                                <Icon name={showTimeline ? "eyeOff" : "calendar"} size={18} />
                            </button>
                            <button onClick={() => setShowPlans(true)} className="w-[38px] md:w-[42px] h-[38px] md:h-[42px] bg-white/90 backdrop-blur-md rounded-full shadow-md border border-slate-200 flex items-center justify-center text-slate-500 hover:text-sky-500 transition-colors" title="Saved Plans Library">
                                <Icon name="bookmark" size={18} />
                            </button>
                            <button onClick={() => setShowInfo(true)} className="w-[38px] md:w-[42px] h-[38px] md:h-[42px] bg-white/90 backdrop-blur-md rounded-full shadow-md border border-slate-200 flex items-center justify-center text-slate-500 hover:text-sky-500 transition-colors" title="Methodology & Sources">
                                <Icon name="info" size={18} />
                            </button>
                        </div>

                        {/* Timeline */}
                        <div className={`absolute bottom-4 md:bottom-6 left-2 right-2 md:left-1/2 md:-translate-x-1/2 md:w-[600px] z-[400] bg-white/95 backdrop-blur-xl rounded-2xl shadow-2xl border border-slate-200 p-3 md:p-5 transition-all duration-300 ${showTimeline ? 'translate-y-0 opacity-100' : 'translate-y-8 opacity-0 pointer-events-none'}`}>
                            <div className="flex justify-between items-center mb-2 md:mb-3">
                                <div className="flex flex-wrap items-center gap-1.5 md:gap-3">
                                    <input type="date" value={dateStrKey} onChange={handleDateChange} className="bg-slate-100 border border-slate-200 text-slate-700 font-bold text-[10px] md:text-sm rounded-lg px-2 py-1 md:px-3 md:py-1.5 focus:outline-none focus:ring-2 focus:ring-sky-500 cursor-pointer shrink-0"/>
                                    {cloudData && (
                                        <div className="flex items-center gap-1.5 sm:gap-2 text-[7px] sm:text-[9px] font-bold uppercase tracking-widest text-slate-500 bg-slate-100/50 border border-slate-200 px-1.5 py-1 sm:px-2 sm:py-1.5 rounded-lg shrink-0" title="Hourly Cloud Cover Forecast">
                                            <span className="flex items-center gap-0.5 sm:gap-1"><span className="w-1.5 h-1.5 sm:w-2 sm:h-2 rounded-full bg-[#22c55e] opacity-80"></span> Clear</span>
                                            <span className="flex items-center gap-0.5 sm:gap-1"><span className="w-1.5 h-1.5 sm:w-2 sm:h-2 rounded-full bg-[#eab308] opacity-80"></span> Mixed</span>
                                            <span className="flex items-center gap-0.5 sm:gap-1"><span className="w-1.5 h-1.5 sm:w-2 sm:h-2 rounded-full bg-[#ef4444] opacity-80"></span> Cloudy</span>
                                        </div>
                                    )}
                                </div>
                                <div className="text-xl md:text-3xl font-black font-mono tracking-tighter text-slate-900 shrink-0">
                                    {date.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', second: '2-digit' })}
                                </div>
                            </div>

                            <div className="flex items-center gap-2 md:gap-3">
                                <button onClick={() => setIsPlaying(!isPlaying)} className={`p-2 md:p-3 rounded-full flex-shrink-0 transition-colors shadow-sm ${isPlaying ? 'bg-rose-50 text-rose-500 hover:bg-rose-100' : 'bg-sky-50 text-sky-600 hover:bg-sky-100'}`}>
                                    <Icon name={isPlaying ? "pause" : "play"} size={14} />
                                </button>
                                
                                <div className="flex-grow relative pt-2 pb-1 rounded-lg overflow-hidden bg-slate-100/50">
                                    {cloudData && (
                                        <div className="absolute top-0 left-0 w-full h-full flex opacity-30 pointer-events-none">
                                            {cloudData.map((cover, i) => (
                                                <div key={i} className="h-full flex-1" style={{ backgroundColor: (cover === null || cover === undefined) ? '#cbd5e1' : (cover > 50 ? '#ef4444' : (cover > 15 ? '#eab308' : '#22c55e')) }} title={`Cloud Cover: ${cover ?? '?'}%`}></div>
                                            ))}
                                        </div>
                                    )}

                                    <div className="absolute w-full h-full top-0 left-0 pointer-events-none flex items-center">
                                        {sunData && sunData.riseTime && (
                                            <div className="absolute w-1 md:w-1.5 h-2 md:h-3 bg-amber-400 rounded-full" style={{ left: `${((sunData.riseTime.getHours()*3600 + sunData.riseTime.getMinutes()*60 + sunData.riseTime.getSeconds()) / 86400) * 100}%` }}></div>
                                        )}
                                        {sunData && sunData.setTime && (
                                            <div className="absolute w-1 md:w-1.5 h-2 md:h-3 bg-orange-500 rounded-full" style={{ left: `${((sunData.setTime.getHours()*3600 + sunData.setTime.getMinutes()*60 + sunData.setTime.getSeconds()) / 86400) * 100}%` }}></div>
                                        )}
                                    </div>
                                    <input type="range" min="0" max="86399" value={secondsOfDay} onChange={handleTimeChange} className="w-full relative z-10"/>
                                </div>
                            </div>
                        </div>

                        {showViewfinder && (
                            <VirtualViewfinder
                                camPos={camPos}
                                setCamPos={setCamPos}
                                targetPos={targetPos}
                                date={date}
                                setDate={setDate}
                                alignment={alignment}
                                onClose={() => setShowViewfinder(false)}
                                handleTimeChange={handleTimeChange}
                                sunData={sunData}
                                moonData={moonData}
                                targetHeight={targetHeight}
                                setTargetHeight={setTargetHeight}
                                targetWidth={targetWidth}
                                setTargetWidth={setTargetWidth}
                                onAutoAlign={handleAutoAlignCamera}
                                fovAzimuth={fovAzimuth}
                                fovAltitude={fovAltitude}
                                sDims={sDims}
                                focalLength={focalLength}
                                setFocalLength={setFocalLength}
                                sensor={sensor}
                                setSensor={setSensor}
                                aperture={aperture}
                                setAperture={setAperture}
                                showToast={showToast}
                                terrainData={terrainData}
                                panoMode={panoMode}
                                setPanoMode={setPanoMode}
                                localAtmos={localAtmos}
                                setCorridorData={setCorridorData}
                                hyperfocal={hyperfocal}
                                shadowLength={shadowLength}
                                astroStats={astroStats}
                            />
                        )}

                        {showPlans && (
                            <div className="fixed inset-0 z-[2000] bg-slate-900/80 backdrop-blur-sm flex items-center justify-center p-4 animate-in fade-in" onClick={() => setShowPlans(false)}>
                                <div className="bg-white rounded-3xl shadow-2xl overflow-hidden w-full max-w-lg flex flex-col" onClick={e => e.stopPropagation()}>
                                    <div className="flex items-center justify-between p-4 md:p-5 border-b border-slate-100 bg-slate-50">
                                        <div className="flex items-center gap-3">
                                            <div className="bg-sky-500 text-white p-2.5 rounded-xl shadow-sm">
                                                <Icon name="bookmark" size={18} />
                                            </div>
                                            <h3 className="font-black text-base md:text-lg text-slate-800">Saved Plans Library</h3>
                                        </div>
                                        <button onClick={() => setShowPlans(false)} className="p-2 hover:bg-slate-200 rounded-full transition-colors text-slate-500">
                                            <Icon name="x" size={18} />
                                        </button>
                                    </div>
                                    <div className="p-5 md:p-6 overflow-y-auto max-h-[60vh] custom-scrollbar bg-slate-50">
                                        <div className="mb-6 bg-white p-4 rounded-2xl shadow-sm border border-slate-200">
                                            <h4 className="text-[10px] font-black uppercase tracking-widest text-slate-400 mb-3">Save Current Setup</h4>
                                            <div className="flex gap-2">
                                                <input type="text" id="newPlanName" placeholder="e.g. Bamburgh Sunrise" className="flex-1 bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 text-sm font-bold text-slate-700 outline-none focus:border-sky-500" />
                                                <button onClick={() => {
                                                    const input = document.getElementById('newPlanName');
                                                    if(input.value) { handleSaveToLibrary(input.value); input.value = ''; }
                                                }} className="bg-slate-900 hover:bg-slate-800 text-white px-4 py-2 rounded-lg text-[10px] font-black uppercase tracking-widest transition-colors shadow-md">
                                                    Save
                                                </button>
                                            </div>
                                        </div>

                                        <h4 className="text-[10px] font-black uppercase tracking-widest text-slate-400 mb-3">My Library</h4>
                                        {savedPlans.length === 0 ? (
                                            <p className="text-sm text-slate-500 text-center py-6 italic">No plans saved yet.</p>
                                        ) : (
                                            <div className="space-y-3">
                                                {savedPlans.map(plan => (
                                                    <div key={plan.id} className="bg-white p-4 rounded-xl shadow-sm border border-slate-200 flex justify-between items-center group">
                                                        <div>
                                                            <h5 className="font-bold text-slate-800">{plan.name}</h5>
                                                            <p className="text-[10px] text-slate-500 font-mono mt-1">{new Date(plan.date).toLocaleDateString('en-GB')} • {plan.focalLength}mm</p>
                                                        </div>
                                                        <div className="flex gap-2">
                                                            <button onClick={() => handleLoadPlan(plan)} className="bg-sky-50 hover:bg-sky-100 text-sky-600 p-2 rounded-lg transition-colors border border-sky-200" title="Load Plan">
                                                                <Icon name="play" size={14} />
                                                            </button>
                                                            <button onClick={() => handleDeletePlan(plan.id)} className="bg-rose-50 hover:bg-rose-100 text-rose-600 p-2 rounded-lg transition-colors border border-rose-200 opacity-0 group-hover:opacity-100 lg:opacity-100" title="Delete Plan">
                                                                <Icon name="x" size={14} />
                                                            </button>
                                                        </div>
                                                    </div>
                                                ))}
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </div>
                        )}

                        {showInfo && (
                            <div className="fixed inset-0 z-[2000] bg-slate-900/80 backdrop-blur-sm flex items-center justify-center p-4 animate-in fade-in" onClick={() => setShowInfo(false)}>
                                <div className="bg-white rounded-3xl shadow-2xl overflow-hidden w-full max-w-4xl flex flex-col" onClick={e => e.stopPropagation()}>
                                    <div className="flex items-center justify-between p-4 md:p-5 border-b border-slate-100 bg-slate-50">
                                        <div className="flex items-center gap-3">
                                            <div className="bg-slate-900 text-white p-2.5 rounded-xl shadow-sm">
                                                <Icon name="info" size={18} />
                                            </div>
                                            <h3 className="font-black text-base md:text-lg text-slate-800">Guide & Masterclass</h3>
                                        </div>
                                        <button onClick={() => setShowInfo(false)} className="p-2 hover:bg-slate-200 rounded-full transition-colors text-slate-500">
                                            <Icon name="x" size={18} />
                                        </button>
                                    </div>
                                    <div className="p-5 md:p-6 overflow-y-auto max-h-[70dvh] custom-scrollbar space-y-8">

                                        <div className="bg-sky-50 p-5 rounded-2xl border border-sky-100 shadow-sm">
                                            <h4 className="font-black text-sky-800 text-sm md:text-base uppercase tracking-widest mb-5 flex items-center gap-2">
                                                <Icon name="target" size={20} className="text-sky-600"/> Masterclass: Planning a Perfect Alignment
                                            </h4>
                                            <div className="space-y-5">
                                                <div className="flex gap-4">
                                                    <div className="w-6 h-6 rounded-full bg-sky-200 text-sky-700 flex items-center justify-center font-black shrink-0 text-xs mt-0.5 shadow-inner">1</div>
                                                    <div>
                                                        <strong className="text-slate-900 text-xs md:text-sm block mb-1">Set Your Target & Initial Camera Position</strong>
                                                        <p className="text-[11px] md:text-xs text-slate-600 leading-relaxed">Start by dropping the <b className="text-rose-500">Red Marker</b> on your subject (e.g., a lighthouse, castle, or tree). Drop the <b className="text-sky-500">Blue Marker</b> roughly where you want to shoot from. The dashed line connects them, showing your current shooting bearing and distance.</p>
                                                    </div>
                                                </div>
                                                <div className="flex gap-4">
                                                    <div className="w-6 h-6 rounded-full bg-sky-200 text-sky-700 flex items-center justify-center font-black shrink-0 text-xs mt-0.5 shadow-inner">2</div>
                                                    <div>
                                                        <strong className="text-slate-900 text-xs md:text-sm block mb-1">Use the Time Machine</strong>
                                                        <p className="text-[11px] md:text-xs text-slate-600 leading-relaxed">Open the <b>Alignment</b> tab (left side) and click <b>Next Sun</b> or <b>Next Moon</b>. The app will rapidly scan up to 365 days ahead to find the exact date and time the celestial body crosses directly behind your target from your chosen angle.</p>
                                                    </div>
                                                </div>
                                                <div className="flex gap-4">
                                                    <div className="w-6 h-6 rounded-full bg-sky-200 text-sky-700 flex items-center justify-center font-black shrink-0 text-xs mt-0.5 shadow-inner">3</div>
                                                    <div>
                                                        <strong className="text-slate-900 text-xs md:text-sm block mb-1">Check the Terrain & Line of Sight</strong>
                                                        <p className="text-[11px] md:text-xs text-slate-600 leading-relaxed">Review the 3D elevation profile in the Alignment tab. If it shows <span className="text-red-600 font-bold bg-red-100 px-1 rounded">BLOCKED</span>, a hill or obstacle is in the way! Look at the map for the <b>15km Corridor Overlay</b> (green lines are safe, red are blocked) to safely drag your Camera pin to a clear viewpoint along the alignment path.</p>
                                                    </div>
                                                </div>
                                                <div className="flex gap-4">
                                                    <div className="w-6 h-6 rounded-full bg-sky-200 text-sky-700 flex items-center justify-center font-black shrink-0 text-xs mt-0.5 shadow-inner">4</div>
                                                    <div>
                                                        <strong className="text-slate-900 text-xs md:text-sm block mb-1">Perfect the Framing in the Virtual Viewfinder</strong>
                                                        <p className="text-[11px] md:text-xs text-slate-600 leading-relaxed">Input your target's estimated height/width and your lens focal length (e.g., 400mm). Open the <b>Virtual Viewfinder</b>. Click <b>Align Rise</b> or <b>Align Set</b>. The app will calculate the precise distance required to make the sun/moon look massive behind your subject, automatically jumping your camera pin to the optimal coordinate.</p>
                                                    </div>
                                                </div>
                                                <div className="flex gap-4">
                                                    <div className="w-6 h-6 rounded-full bg-sky-200 text-sky-700 flex items-center justify-center font-black shrink-0 text-xs mt-0.5 shadow-inner">5</div>
                                                    <div>
                                                        <strong className="text-slate-900 text-xs md:text-sm block mb-1">Verify Weather & Save</strong>
                                                        <p className="text-[11px] md:text-xs text-slate-600 leading-relaxed">Check the <b>Sun/Moon</b> tab for the Horizon Cloud badges (50km, 100km, 200km) to ensure the distant horizon is clear of thick clouds. Once verified, click the <b>Bookmark</b> icon to save the plan to your library, or the <b>Download</b> icon to print your PDF cheat sheet!</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div>
                                            <p className="text-xs md:text-sm text-slate-500 font-bold uppercase tracking-widest mb-3 flex items-center gap-2"><Icon name="map" size={16} className="text-slate-400"/> Map & Interface Features</p>
                                            <div className="grid grid-cols-1 md:grid-cols-2 gap-3 md:gap-4">
                                                <div className="bg-slate-50 p-4 rounded-xl border border-slate-100 shadow-sm">
                                                    <strong className="text-slate-900 flex items-center gap-2 text-xs md:text-sm mb-1.5"><Icon name="locate" size={16} className="text-rose-500"/> Markers & Search</strong>
                                                    <p className="text-[11px] md:text-xs text-slate-600 leading-relaxed">Drag the <b>Blue</b> (Camera) and <b>Red</b> (Target) markers to set up your shot. Use the top search bar to quickly jump to specific locations or landmarks.</p>
                                                </div>
                                                <div className="bg-slate-50 p-4 rounded-xl border border-slate-100 shadow-sm">
                                                    <strong className="text-slate-900 flex items-center gap-2 text-xs md:text-sm mb-1.5"><Icon name="eye" size={16} className="text-sky-500"/> Map Lines & Wedges</strong>
                                                    <p className="text-[11px] md:text-xs text-slate-600 leading-relaxed">The dashed line is your line-of-sight. Yellow/Blue lines show Sun/Moon paths. The dashed blue wedge represents your camera's Field of View based on your lens setup.</p>
                                                </div>
                                                <div className="bg-slate-50 p-4 rounded-xl border border-slate-100 shadow-sm">
                                                    <strong className="text-slate-900 flex items-center gap-2 text-xs md:text-sm mb-1.5"><Icon name="streetView" size={16} className="text-emerald-500"/> Map Layers</strong>
                                                    <p className="text-[11px] md:text-xs text-slate-600 leading-relaxed">Toggle between Standard and Topographic maps using the buttons in the top right. You can also enable a 2D Milky Way track overlay for night sky planning.</p>
                                                </div>
                                                <div className="bg-slate-50 p-4 rounded-xl border border-slate-100 shadow-sm">
                                                    <strong className="text-slate-900 flex items-center gap-2 text-xs md:text-sm mb-1.5"><Icon name="navigation" size={16} className="text-indigo-500"/> Quick Tools (Right Edge)</strong>
                                                    <p className="text-[11px] md:text-xs text-slate-600 leading-relaxed">Export a PDF cheat-sheet plan, jump into Google Street View at the camera's location, copy a shareable link, or snap the camera marker to your current GPS location.</p>
                                                </div>
                                            </div>
                                        </div>

                                        <div>
                                            <p className="text-xs md:text-sm text-slate-500 font-bold uppercase tracking-widest mb-3 flex items-center gap-2"><Icon name="target" size={16} className="text-slate-400"/> Alignment & Camera (Left Panel)</p>
                                            <div className="grid grid-cols-1 md:grid-cols-2 gap-3 md:gap-4">
                                                <div className="bg-slate-50 p-4 rounded-xl border border-slate-100 shadow-sm">
                                                    <strong className="text-slate-900 flex items-center gap-2 text-xs md:text-sm mb-1.5"><Icon name="mountain" size={16} className="text-amber-600"/> Terrain & Line of Sight</strong>
                                                    <p className="text-[11px] md:text-xs text-slate-600 leading-relaxed">View a 3D elevation profile between your camera and target. It automatically warns you if hills block your view and generates a 15km color-coded "safe corridor" map overlay.</p>
                                                </div>
                                                <div className="bg-slate-50 p-4 rounded-xl border border-slate-100 shadow-sm">
                                                    <strong className="text-slate-900 flex items-center gap-2 text-xs md:text-sm mb-1.5"><Icon name="clockArrow" size={16} className="text-rose-500"/> Time Machine</strong>
                                                    <p className="text-[11px] md:text-xs text-slate-600 leading-relaxed">Click "Next Sun" or "Next Moon" to automatically scan up to 365 days ahead to find the exact date and time a perfect alignment occurs over your target.</p>
                                                </div>
                                                <div className="bg-slate-50 p-4 rounded-xl border border-slate-100 shadow-sm">
                                                    <strong className="text-slate-900 flex items-center gap-2 text-xs md:text-sm mb-1.5"><Icon name="aperture" size={16} className="text-slate-700"/> Camera Settings</strong>
                                                    <p className="text-[11px] md:text-xs text-slate-600 leading-relaxed">Input your sensor size and focal length to accurately size the map FOV wedge and Virtual Viewfinder. It also calculates true Hyperfocal distance.</p>
                                                </div>
                                                <div className="bg-slate-50 p-4 rounded-xl border border-slate-100 shadow-sm">
                                                    <strong className="text-slate-900 flex items-center gap-2 text-xs md:text-sm mb-1.5"><Icon name="stars" size={16} className="text-purple-500"/> Spot Stars Limit</strong>
                                                    <p className="text-[11px] md:text-xs text-slate-600 leading-relaxed">Based on your lens and sensor, this calculates your maximum exposure times (using NPF and 500 rules) to prevent star trailing during astrophotography.</p>
                                                </div>
                                            </div>
                                        </div>

                                        <div>
                                            <p className="text-xs md:text-sm text-slate-500 font-bold uppercase tracking-widest mb-3 flex items-center gap-2"><Icon name="sun" size={16} className="text-slate-400"/> Ephemeris & Timeline</p>
                                            <div className="grid grid-cols-1 md:grid-cols-2 gap-3 md:gap-4">
                                                <div className="bg-slate-50 p-4 rounded-xl border border-slate-100 shadow-sm">
                                                    <strong className="text-slate-900 flex items-center gap-2 text-xs md:text-sm mb-1.5"><Icon name="sun" size={16} className="text-orange-500"/> Sun, Moon & Milky Way</strong>
                                                    <p className="text-[11px] md:text-xs text-slate-600 leading-relaxed">The right panel shows exact altitudes, azimuths, moon phase, and key times (Golden Hour, Astro Dark) for celestial bodies calculated using high-precision NASA algorithms.</p>
                                                </div>
                                                <div className="bg-slate-50 p-4 rounded-xl border border-slate-100 shadow-sm">
                                                    <strong className="text-slate-900 flex items-center gap-2 text-xs md:text-sm mb-1.5"><Icon name="cloud" size={16} className="text-teal-500"/> Multi-Tier Horizon Clouds</strong>
                                                    <p className="text-[11px] md:text-xs text-slate-600 leading-relaxed">Look for the L/M/H badges next to rise/set times. They predict cloud cover at 50km, 100km, and 200km over the horizon exactly at the sun/moon's bearing.</p>
                                                </div>
                                                <div className="bg-slate-50 p-4 rounded-xl border border-slate-100 shadow-sm">
                                                    <strong className="text-slate-900 flex items-center gap-2 text-xs md:text-sm mb-1.5"><Icon name="calendar" size={16} className="text-sky-600"/> Timeline & Playback</strong>
                                                    <p className="text-[11px] md:text-xs text-slate-600 leading-relaxed">Use the bottom panel to select a date and scrub through time. Press Play to animate the movement of celestial bodies and shadows on the map.</p>
                                                </div>
                                                <div className="bg-slate-50 p-4 rounded-xl border border-slate-100 shadow-sm">
                                                    <strong className="text-slate-900 flex items-center gap-2 text-xs md:text-sm mb-1.5"><Icon name="cloud" size={16} className="text-slate-400"/> Hourly Weather Bar</strong>
                                                    <p className="text-[11px] md:text-xs text-slate-600 leading-relaxed">The transparent colored bar sitting directly behind the bottom timeline slider shows local hourly cloud cover (Green=Clear, Yellow=Mixed, Red=Cloudy).</p>
                                                </div>
                                            </div>
                                        </div>

                                        <div>
                                            <p className="text-xs md:text-sm text-slate-500 font-bold uppercase tracking-widest mb-3 flex items-center gap-2"><Icon name="viewfinder" size={16} className="text-slate-400"/> Virtual Viewfinder (Modal)</p>
                                            <div className="grid grid-cols-1 md:grid-cols-2 gap-3 md:gap-4">
                                                <div className="bg-slate-50 p-4 rounded-xl border border-slate-100 shadow-sm">
                                                    <strong className="text-slate-900 flex items-center gap-2 text-xs md:text-sm mb-1.5"><Icon name="viewfinder" size={16} className="text-fuchsia-500"/> 3D Simulation</strong>
                                                    <p className="text-[11px] md:text-xs text-slate-600 leading-relaxed">A visual preview of your shot accounting for target dimensions, lens FOV, atmospheric refraction, and true apparent size of the sun/moon relative to the subject.</p>
                                                </div>
                                                <div className="bg-slate-50 p-4 rounded-xl border border-slate-100 shadow-sm">
                                                    <strong className="text-slate-900 flex items-center gap-2 text-xs md:text-sm mb-1.5"><Icon name="target" size={16} className="text-emerald-600"/> Smart Auto-Align</strong>
                                                    <p className="text-[11px] md:text-xs text-slate-600 leading-relaxed">Inside the Viewfinder, click "Align Rise" or "Set". It automatically calculates the exact required distance and time to frame the body perfectly behind your target.</p>
                                                </div>
                                                <div className="bg-slate-50 p-4 rounded-xl border border-slate-100 shadow-sm">
                                                    <strong className="text-slate-900 flex items-center gap-2 text-xs md:text-sm mb-1.5"><Icon name="smartphone" size={16} className="text-indigo-400"/> AR Mode & Context Zoom</strong>
                                                    <p className="text-[11px] md:text-xs text-slate-600 leading-relaxed">Toggle AR mode to use your device's gyro/compass to pan around the sky. Use Context Zoom to zoom out beyond your lens's FOV to see what's happening out-of-frame.</p>
                                                </div>
                                                <div className="bg-slate-50 p-4 rounded-xl border border-slate-100 shadow-sm">
                                                    <strong className="text-slate-900 flex items-center gap-2 text-xs md:text-sm mb-1.5"><Icon name="grid" size={16} className="text-amber-500"/> Pano Grid Mode</strong>
                                                    <p className="text-[11px] md:text-xs text-slate-600 leading-relaxed">Toggle the Panorama Grid inside the Viewfinder to overlay a 3x2 shooting grid with a 30% overlap guide for planning multi-shot panoramas.</p>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div>
                                            <p className="text-xs md:text-sm text-slate-500 font-bold uppercase tracking-widest mb-3 flex items-center gap-2"><Icon name="bookmark" size={16} className="text-slate-400"/> Library</p>
                                            <div className="bg-slate-50 p-4 rounded-xl border border-slate-100 shadow-sm">
                                                 <strong className="text-slate-900 flex items-center gap-2 text-xs md:text-sm mb-1.5"><Icon name="bookmark" size={16} className="text-sky-500"/> Saved Plans Library</strong>
                                                 <p className="text-[11px] md:text-xs text-slate-600 leading-relaxed">Click the Bookmark icon (bottom left) to open your library. Save your current locations, date, target size, and camera settings locally to reload them at any time without losing your work.</p>
                                            </div>
                                        </div>

                                    </div>
                                </div>
                            </div>
                        )}
                    </main>
                </div>
            );
        };

        const root = ReactDOM.createRoot(document.getElementById('root'));
        root.render(<App />);
