// --- VIRTUAL VIEWFINDER COMPONENT ---
        const VirtualViewfinder = ({ camPos, setCamPos, targetPos, date, setDate, alignment, onClose, handleTimeChange, sunData, moonData, targetHeight, setTargetHeight, targetWidth, setTargetWidth, onAutoAlign, fovAzimuth, fovAltitude, sDims, focalLength, setFocalLength, sensor, setSensor, aperture, setAperture, showToast, terrainData, panoMode, setPanoMode, localAtmos, setCorridorData, hyperfocal, shadowLength, astroStats }) => {
            const [isPlaying, setIsPlaying] = useState(false);
            const [contextMultiplier, setContextMultiplier] = useState(2); 
            const [arMode, setArMode] = useState(false);
            const [deviceOrientation, setDeviceOrientation] = useState({ heading: alignment.bearing, pitch: 0 });
            
            const aspect = sDims.w / sDims.h;
            const SVG_HEIGHT = 600;
            const SVG_WIDTH = SVG_HEIGHT * aspect;

            const safeDistance = Math.max(1, alignment.distance);

            const camElev = terrainData?.camElev || 0;
            const tgtElev = terrainData?.tgtElev || 0;
            const pitchToTargetBase = Math.atan2((tgtElev - (camElev + 1.5)), safeDistance) * (180 / Math.PI);
            const pitchToTargetTop = Math.atan2(((tgtElev + targetHeight) - (camElev + 1.5)), safeDistance) * (180 / Math.PI);
            const apparentAlt = Math.max(0.1, pitchToTargetTop - pitchToTargetBase);

            const displayFovAzimuth = fovAzimuth * contextMultiplier;
            const displayFovAltitude = fovAltitude * contextMultiplier;

            // Restored the accidentally removed currentCenterAz variable!
            const currentCenterAz = arMode ? deviceOrientation.heading : alignment.bearing;
            
            // Shift camera pitch up by 20% of the displayed FOV to compose with exactly 70% sky / 30% ground
            const currentCenterAlt = arMode ? deviceOrientation.pitch : (pitchToTargetBase + apparentAlt / 2) + (0.2 * displayFovAltitude);

            const mapAzToX = (az) => {
                const relAz = getRelativeAz(az, currentCenterAz);
                return ((relAz + (displayFovAzimuth / 2)) / displayFovAzimuth) * SVG_WIDTH;
            };

            const MIN_ALTITUDE = currentCenterAlt - (displayFovAltitude / 2);
            const MAX_ALTITUDE = currentCenterAlt + (displayFovAltitude / 2);

            const mapAltToY = (alt) => SVG_HEIGHT - (((alt - MIN_ALTITUDE) / displayFovAltitude) * SVG_HEIGHT);

            const targetBaseY = mapAltToY(pitchToTargetBase);
            const targetTopY = mapAltToY(pitchToTargetTop);
            
            const sunRadiusDeg = getBodyRadiusDeg('sun', date, camPos.lat, camPos.lng, camElev);
            const moonRadiusDeg = getBodyRadiusDeg('moon', date, camPos.lat, camPos.lng, camElev);
            const sunRadius = (sunRadiusDeg / displayFovAzimuth) * SVG_WIDTH;
            const moonRadius = (moonRadiusDeg / displayFovAzimuth) * SVG_WIDTH;
            
            const targetWidthDeg = Math.atan(targetWidth / safeDistance) * (180 / Math.PI);
            const targetHalfW = (targetWidthDeg / 2 / displayFovAzimuth) * SVG_WIDTH;
            
            const sunWidthDeg = sunRadiusDeg * 2;
            const moonWidthDeg = moonRadiusDeg * 2;
            const sunSizeRatio = targetWidthDeg > 0 ? sunWidthDeg / targetWidthDeg : 0;
            const moonSizeRatio = targetWidthDeg > 0 ? moonWidthDeg / targetWidthDeg : 0;
            const sunRatioText = sunSizeRatio >= 1 ? `${sunSizeRatio.toFixed(1)}x wider` : `${(1/sunSizeRatio).toFixed(1)}x narrower`;
            const moonRatioText = moonSizeRatio >= 1 ? `${moonSizeRatio.toFixed(1)}x wider` : `${(1/moonSizeRatio).toFixed(1)}x narrower`;

            const frameW = SVG_WIDTH / contextMultiplier;
            const frameH = SVG_HEIGHT / contextMultiplier;
            const frameX = (SVG_WIDTH - frameW) / 2;
            const frameY = (SVG_HEIGHT - frameH) / 2;

            const generatePath = (type) => {
                const points = [];
                let hasEntered = false;
                for (let m = 0; m < 1440; m += 10) {
                    const d = new Date(date);
                    d.setHours(0, m, 0, 0);
                    const { alt, az } = getAccurateAltAz(type, d, camPos.lat, camPos.lng, camElev, localAtmos);
                    const relAz = getRelativeAz(az, currentCenterAz);
                    if (relAz >= -(displayFovAzimuth/2 + 5) && relAz <= (displayFovAzimuth/2 + 5)) {
                        points.push({ x: mapAzToX(az), y: mapAltToY(alt), time: d });
                        hasEntered = true;
                    } else if (hasEntered) {
                        points.push({ break: true });
                        hasEntered = false;
                    }
                }
                return points;
            };

            const sunPath = generatePath('sun');
            const moonPath = generatePath('moon');

            const renderPathString = (points) => {
                let d = "";
                let isFirst = true;
                points.forEach(p => {
                    if (p.break) { isFirst = true; return; }
                    if (isNaN(p.x) || isNaN(p.y)) return;
                    if (isFirst) { d += `M ${p.x.toFixed(2)} ${p.y.toFixed(2)} `; isFirst = false; }
                    else { d += `L ${p.x.toFixed(2)} ${p.y.toFixed(2)} `; }
                });
                return d;
            };

            const stepAz = displayFovAzimuth <= 5 ? 1 : (displayFovAzimuth <= 20 ? 5 : (displayFovAzimuth <= 60 ? 10 : 20));
            const startAz = currentCenterAz - (displayFovAzimuth / 2);
            const endAz = currentCenterAz + (displayFovAzimuth / 2);
            const gridBearings = [];
            for (let az = Math.floor(startAz/stepAz)*stepAz; az <= endAz; az += stepAz) {
                gridBearings.push((az + 360) % 360);
            }

            const stepAlt = displayFovAltitude <= 5 ? 1 : (displayFovAltitude <= 20 ? 5 : (displayFovAltitude <= 60 ? 10 : 20));
            const gridAltitudes = [];
            for (let alt = Math.floor(MIN_ALTITUDE/stepAlt)*stepAlt; alt <= MAX_ALTITUDE; alt += stepAlt) {
                gridAltitudes.push(alt);
            }

            const timeInterval = displayFovAzimuth <= 5 ? 1 : (displayFovAzimuth <= 20 ? 3 : 6); 

            useEffect(() => {
                let interval;
                if (isPlaying) {
                    interval = setInterval(() => {
                        const secs = date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds() + 15;
                        const evt = { target: { value: secs >= 86400 ? 0 : secs } };
                        handleTimeChange(evt);
                    }, 50);
                }
                return () => clearInterval(interval);
            }, [isPlaying, date, handleTimeChange]);

            const handleOrientation = (e) => {
                let heading = 0;
                if (e.webkitCompassHeading) heading = e.webkitCompassHeading;
                else if (e.alpha !== null) heading = 360 - e.alpha; 
                let pitch = 0;
                if (e.beta !== null) pitch = e.beta - 90;
                setDeviceOrientation({ heading, pitch: -pitch }); 
            };

            const toggleAR = async () => {
                if (!arMode) {
                    if (typeof DeviceOrientationEvent !== 'undefined' && typeof DeviceOrientationEvent.requestPermission === 'function') {
                        try {
                            const permission = await DeviceOrientationEvent.requestPermission();
                            if (permission === 'granted') {
                                window.addEventListener('deviceorientation', handleOrientation);
                                setArMode(true);
                                showToast("AR Sensors Activated");
                            } else {
                                alert("Permission to access device orientation was denied.");
                            }
                        } catch (e) {
                            alert("Device Orientation not supported or requires HTTPS.");
                        }
                    } else if ('ondeviceorientationabsolute' in window || 'ondeviceorientation' in window) {
                        const evt = 'ondeviceorientationabsolute' in window ? 'deviceorientationabsolute' : 'deviceorientation';
                        window.addEventListener(evt, handleOrientation);
                        setArMode(true);
                        showToast("AR Sensors Activated");
                    } else {
                        alert("AR Mode is not supported on this device/browser.");
                    }
                } else {
                    window.removeEventListener('deviceorientation', handleOrientation);
                    window.removeEventListener('deviceorientationabsolute', handleOrientation);
                    setArMode(false);
                    setDeviceOrientation({ heading: alignment.bearing, pitch: 0 });
                }
            };

            useEffect(() => {
                return () => {
                    window.removeEventListener('deviceorientation', handleOrientation);
                    window.removeEventListener('deviceorientationabsolute', handleOrientation);
                };
            }, []);

            const secondsOfDay = date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds();

            const handleSmartAlign = async (type, phase) => {
                const bodyData = type === 'sun' ? sunData : moonData;
                if (!bodyData) return;

                showToast("Calculating exact terrain framing & 15km corridor...");

                let idealTargetApparentSize = fovAltitude * 0.4;
                idealTargetApparentSize = Math.min(idealTargetApparentSize, 8); 
                idealTargetApparentSize = Math.max(idealTargetApparentSize, 0.5); 

                const reqDistMeters = Math.max(1, targetHeight) / Math.tan(idealTargetApparentSize * Math.PI / 180);
                const reqDistKm = reqDistMeters / 1000;

                if (reqDistKm > 100 || reqDistKm <= 0) {
                    alert("The required distance to frame this shot is over 100km! Try a shorter focal length or taller target.");
                    return;
                }

                const startOfDay = new Date(date);
                startOfDay.setHours(0,0,0,0);
                const startSearch = new Date(startOfDay.getTime() - 12 * 3600000); 
                
                let roughTime = null;
                let roughAz = null;
                let prevAlt = null;

                for (let i = 0; i < 2880; i+=2) { 
                    let testDate = new Date(startSearch.getTime() + i * 60000);
                    let { alt, az } = getAccurateAltAz(type, testDate, targetPos.lat, targetPos.lng, 0, localAtmos);
                    let tempRadius = getBodyRadiusDeg(type, testDate, targetPos.lat, targetPos.lng, 0);

                    if (prevAlt !== null) {
                        if (phase === 'rise' && prevAlt < tempRadius && alt >= tempRadius) {
                            if (!roughTime || Math.abs(testDate - date) < Math.abs(roughTime - date)) {
                                roughTime = testDate; roughAz = az;
                            }
                        } else if (phase === 'set' && prevAlt > tempRadius && alt <= tempRadius) {
                            if (!roughTime || Math.abs(testDate - date) < Math.abs(roughTime - date)) {
                                roughTime = testDate; roughAz = az;
                            }
                        }
                    }
                    prevAlt = alt;
                }

                if (!roughTime) {
                    alert(`Could not find a suitable ${phase} time for the ${type}. It may not rise/set around this date.`);
                    return;
                }

                const newBearing = (roughAz + 180) % 360;
                const newPos = computeDestinationPoint(targetPos.lat, targetPos.lng, reqDistKm, newBearing);

                let cElev = 0, tElev = 0;
                try {
                    const lats = [newPos[0], targetPos.lat];
                    const lngs = [newPos[1], targetPos.lng];
                    const elevs = await fetchElevationData(lats, lngs);
                    cElev = elevs[0] || 0;
                    tElev = elevs[1] || 0;
                } catch(e) {
                    console.warn("Could not fetch elevation, assuming flat.");
                }

                const heightDiff = (tElev + targetHeight) - (cElev + 1.5); 
                const newPitchToTargetTop = Math.atan2(heightDiff, reqDistMeters) * (180 / Math.PI);
                
                let targetTime = null;
                let targetAzimuth = null;
                prevAlt = null;

                const exactSearchStart = new Date(roughTime.getTime() - 60 * 60000); // +/- 1 hr window
                const finalCamPosLat = newPos[0];
                const finalCamPosLng = newPos[1];

                for (let i = 0; i < 120; i++) { 
                    let testDate = new Date(exactSearchStart.getTime() + i * 60000);
                    let { alt, az } = getAccurateAltAz(type, testDate, finalCamPosLat, finalCamPosLng, cElev, localAtmos);
                    let exactBodyRadius = getBodyRadiusDeg(type, testDate, finalCamPosLat, finalCamPosLng, cElev);
                    
                    let idealTrueAltitude = newPitchToTargetTop + exactBodyRadius;

                    if (prevAlt !== null) {
                        if (phase === 'rise' && prevAlt < idealTrueAltitude && alt >= idealTrueAltitude) {
                            if (!targetTime || Math.abs(testDate - date) < Math.abs(targetTime - date)) {
                                targetTime = testDate; targetAzimuth = az;
                            }
                        } else if (phase === 'set' && prevAlt > idealTrueAltitude && alt <= idealTrueAltitude) {
                            if (!targetTime || Math.abs(testDate - date) < Math.abs(targetTime - date)) {
                                targetTime = testDate; targetAzimuth = az;
                            }
                        }
                    }
                    prevAlt = alt;
                }

                if (targetTime) {
                    setDate(targetTime); 
                    const finalBearing = (targetAzimuth + 180) % 360;
                    const finalIdealPos = computeDestinationPoint(targetPos.lat, targetPos.lng, reqDistKm, finalBearing);
                    onAutoAlign(finalIdealPos[0], finalIdealPos[1]);
                    
                    try {
                        const corridorPts = 50; 
                        const maxDistKm = 15;
                        const distStepKm = maxDistKm / (corridorPts - 1);
                        const corridorLats = [];
                        const corridorLngs = [];
                        
                        for(let i=0; i<corridorPts; i++) {
                            const p = computeDestinationPoint(targetPos.lat, targetPos.lng, distStepKm * i, finalBearing);
                            corridorLats.push(p[0].toFixed(5));
                            corridorLngs.push(p[1].toFixed(5));
                        }
                        
                        const elevs = await fetchElevationData(corridorLats, corridorLngs);
                        
                        if (elevs && elevs.length === corridorPts) {
                            const segments = [];
                            const tgtTopElev = (elevs[0] || 0) + targetHeight;
                            
                            for(let i=1; i<corridorPts; i++) {
                                const distIKm = distStepKm * i;
                                const camElev = (elevs[i] || 0) + 1.5;
                                let blocked = false;
                                const onLand = (elevs[i] || 0) > 0.5;
                                
                                for(let j=1; j<i; j++) {
                                    const distJKm = distStepKm * j;
                                    const distCamToJKm = distIKm - distJKm;
                                    const curvDropJ = 0.0785 * (distCamToJKm * distCamToJKm);
                                    const curvDropTgt = 0.0785 * (distIKm * distIKm);
                                    
                                    const apparentTgtElev = tgtTopElev - curvDropTgt;
                                    const apparentJElev = (elevs[j] || 0) - curvDropJ;

                                    const rayElevAtJ = camElev + ((apparentTgtElev - camElev) * (distCamToJKm / distIKm));
                                    
                                    if (apparentJElev > rayElevAtJ) {
                                        blocked = true;
                                        break;
                                    }
                                }
                                
                                segments.push({
                                    start: [parseFloat(corridorLats[i-1]), parseFloat(corridorLngs[i-1])],
                                    end: [parseFloat(corridorLats[i]), parseFloat(corridorLngs[i])],
                                    valid: onLand && !blocked,
                                    dist: distIKm * 1000
                                });
                            }
                            setCorridorData(segments);
                        }
                    } catch (err) {
                        console.warn("Corridor generation failed", err);
                    }

                    setContextMultiplier(1.5);
                    setArMode(false);
                    showToast(`Aligned for ${focalLength}mm lens. 15km line-of-sight corridor drawn on map.`);
                } else {
                    alert(`Terrain is too high! The ${type} does not reach the required altitude to clear the structure from this distance.`);
                }
            };

            const getSkyColor = (sunAlt) => {
                if (!sunAlt) return '#0f172a';
                if (sunAlt > 6) return '#1e3a8a'; 
                if (sunAlt > 0) return '#713f12'; 
                if (sunAlt > -6) return '#4c1d95'; 
                if (sunAlt > -12) return '#312e81'; 
                if (sunAlt > -18) return '#1e1b4b'; 
                return '#0f172a'; 
            };

            const skyColor = sunData ? getSkyColor(sunData.altitude) : '#0f172a';
            const currentSunPos = getAccurateAltAz('sun', date, camPos.lat, camPos.lng, camElev, localAtmos);
            const currentMoonPos = getAccurateAltAz('moon', date, camPos.lat, camPos.lng, camElev, localAtmos);

            return (
                <div className="fixed inset-0 bg-slate-900 flex flex-col animate-in" style={{ zIndex: 99999 }}>
                    <div className="flex items-center justify-between p-3 md:p-5 border-b border-slate-800 shrink-0 bg-slate-900/95 backdrop-blur-md z-20">
                        <div className="flex items-center gap-3">
                            <div className="bg-sky-500 text-white p-2 md:p-2.5 rounded-lg md:rounded-xl shadow-lg shadow-sky-500/20">
                                <Icon name="viewfinder" size={18} />
                            </div>
                            <div>
                                <h3 className="font-black text-base md:text-lg text-white leading-tight">Virtual Viewfinder</h3>
                                <p className="text-slate-400 text-[10px] md:text-xs">Bearing: <strong className="text-white">{formatDeg(alignment.bearing)}</strong> • Distance: <strong className="text-white">{(safeDistance / 1000).toFixed(2)}km</strong></p>
                            </div>
                        </div>
                        <button onClick={onClose} className="flex items-center gap-1.5 px-3 py-2 bg-slate-800 hover:bg-rose-900/80 border border-slate-700 hover:border-rose-800 rounded-lg transition-colors text-slate-300 hover:text-white shrink-0 shadow-sm">
                            <Icon name="x" size={16} />
                            <span className="text-[10px] md:text-xs font-black uppercase tracking-widest">Close</span>
                        </button>
                    </div>

                    <div className="flex-1 min-h-0 w-full overflow-y-auto md:overflow-hidden flex flex-col md:flex-row relative custom-scrollbar">
                        <div className="shrink-0 md:flex-1 relative w-full h-[45dvh] md:h-auto md:self-stretch bg-slate-900 border-b border-slate-800 md:border-b-0 transition-colors duration-500" style={{ backgroundColor: skyColor }}>
                            
                            <div className="absolute top-2 md:top-8 right-2 md:right-8 bg-slate-900/80 backdrop-blur-md border border-slate-700 p-3 rounded-xl z-30 shadow-lg flex flex-col gap-2">
                                <label className="text-[10px] font-black text-sky-400 uppercase tracking-widest flex items-center justify-between gap-1.5 w-full">
                                    <span><Icon name="eye" size={12} className="inline mr-1"/> Context Zoom</span>
                                    <div className="flex gap-2 ml-4">
                                        <button onClick={() => setPanoMode(!panoMode)} className={`px-2 py-1 rounded border text-[9px] transition-colors ${panoMode ? 'bg-amber-500 border-amber-400 text-white' : 'border-slate-600 text-slate-400 hover:text-white hover:border-slate-500'}`} title="Panorama Planner (3x2 Grid)">
                                            <Icon name="grid" size={10} className="inline mr-1" /> Pano
                                        </button>
                                        <button onClick={toggleAR} className={`px-2 py-1 rounded border text-[9px] transition-colors ${arMode ? 'bg-sky-500 border-sky-400 text-white' : 'border-slate-600 text-slate-400 hover:text-white hover:border-slate-500'}`} title="Use Device Gyro/Compass">
                                            <Icon name="smartphone" size={10} className="inline mr-1" /> AR Mode
                                        </button>
                                    </div>
                                </label>
                                <div className="flex items-center gap-2 mt-1">
                                    <span className="text-[10px] text-slate-400 font-bold">1x</span>
                                    <input type="range" min="1" max="10" step="0.5" value={contextMultiplier} onChange={(e) => setContextMultiplier(parseFloat(e.target.value))} className="w-24 md:w-32 ar-scrubber"/>
                                    <span className="text-[10px] text-slate-400 font-bold">10x</span>
                                </div>
                            </div>

                            <div className="absolute inset-0 md:inset-6 md:rounded-2xl overflow-hidden bg-slate-900/20 shadow-[inset_0_0_40px_rgba(0,0,0,0.5)]">
                                <svg viewBox={`0 0 ${SVG_WIDTH} ${SVG_HEIGHT}`} preserveAspectRatio="xMidYMid slice" className="absolute inset-0 w-full h-full">
                                    {gridAltitudes.map(alt => (
                                        <g key={`alt-${alt}`}>
                                            <line x1="0" y1={mapAltToY(alt)} x2={SVG_WIDTH} y2={mapAltToY(alt)} stroke={alt === 0 ? "#cbd5e1" : "#e2e8f0"} strokeWidth={alt === 0 ? "2" : "1"} strokeDasharray={alt === 0 ? "none" : "5,5"} opacity="0.4"/>
                                            <text x="10" y={mapAltToY(alt) - 5} fill={alt === 0 ? "#f8fafc" : "#f1f5f9"} fontSize="12" fontWeight="bold" opacity="0.8">{alt}°</text>
                                        </g>
                                    ))}

                                    {gridBearings.map((bearing, i) => {
                                        const x = mapAzToX(bearing);
                                        const isCenter = Math.abs(getDelta(bearing, currentCenterAz)) < (stepAz / 2);
                                        return (
                                            <g key={`brg-${bearing}`}>
                                                <line x1={x} y1="0" x2={x} y2={SVG_HEIGHT} stroke={isCenter ? "#cbd5e1" : "#e2e8f0"} strokeWidth={isCenter ? "2" : "1"} strokeDasharray={isCenter ? "none" : "5,5"} opacity="0.4"/>
                                                <text x={x} y={SVG_HEIGHT - 10} fill={isCenter ? "#f8fafc" : "#f1f5f9"} fontSize="12" fontWeight="bold" textAnchor="middle" opacity="0.8">{formatDeg(bearing)}</text>
                                            </g>
                                        );
                                    })}

                                    {BRIGHT_STARS.map((star, i) => {
                                        const lst = getLST(date, targetPos.lng);
                                        const { alt, az } = getAltAz(star.ra, star.dec, targetPos.lat, lst);
                                        const relAz = getRelativeAz(az, currentCenterAz);
                                        if (relAz >= -(displayFovAzimuth/2 + 5) && relAz <= (displayFovAzimuth/2 + 5) && alt >= MIN_ALTITUDE - 5 && alt <= MAX_ALTITUDE + 5) {
                                            const sx = mapAzToX(az);
                                            const sy = mapAltToY(alt);
                                            const r = Math.max(0.5, 3 - star.mag);
                                            return (
                                                <g key={`star-${i}`}>
                                                    <circle cx={sx} cy={sy} r={r} fill="#fff" opacity={0.8 + (Math.random() * 0.2)} />
                                                    {star.mag < 1.5 && <text x={sx + 4} y={sy + 3} fill="rgba(255,255,255,0.5)" fontSize="8">{star.name}</text>}
                                                </g>
                                            );
                                        }
                                        return null;
                                    })}

                                    {ASTERISMS.map((ast, i) => {
                                        const lst = getLST(date, targetPos.lng);
                                        let pointsStr = "";
                                        let visible = false;
                                        ast.lines.forEach((pt) => {
                                            const { alt, az } = getAltAz(pt[0], pt[1], targetPos.lat, lst);
                                            const relAz = getRelativeAz(az, currentCenterAz);
                                            if (relAz >= -(displayFovAzimuth/2 + 15) && relAz <= (displayFovAzimuth/2 + 15) && alt >= MIN_ALTITUDE - 15 && alt <= MAX_ALTITUDE + 15) visible = true;
                                            pointsStr += `${mapAzToX(az).toFixed(2)},${mapAltToY(alt).toFixed(2)} `;
                                        });
                                        if (visible) {
                                            const { alt: textAlt, az: textAz } = getAltAz(ast.lines[0][0], ast.lines[0][1], targetPos.lat, lst);
                                            return (
                                                <g key={`ast-${i}`}>
                                                    <polyline points={pointsStr} fill="none" stroke="rgba(255,255,255,0.2)" strokeWidth="1" strokeDasharray="3,3" />
                                                    <text x={mapAzToX(textAz)} y={mapAltToY(textAlt) - 10} fill="rgba(255,255,255,0.4)" fontSize="10">{ast.name}</text>
                                                </g>
                                            );
                                        }
                                        return null;
                                    })}

                                    <path d={renderPathString(sunPath)} fill="none" stroke="#fcd34d" strokeWidth="3" opacity="0.6"/>
                                    <path d={renderPathString(moonPath)} fill="none" stroke="#bfdbfe" strokeWidth="3" opacity="0.6"/>

                                    {sunPath.filter((p, i) => i % timeInterval === 0 && !p.break).map((p, i) => (
                                        <text key={`st-${i}`} x={p.x} y={p.y - 10} fill="#fcd34d" fontSize="10" fontWeight="bold" textAnchor="middle" opacity="0.8" className="drop-shadow-md">{formatTimeStr(p.time)}</text>
                                    ))}
                                    {moonPath.filter((p, i) => i % timeInterval === 0 && !p.break).map((p, i) => (
                                        <text key={`mt-${i}`} x={p.x} y={p.y - 10} fill="#bfdbfe" fontSize="10" fontWeight="bold" textAnchor="middle" opacity="0.8" className="drop-shadow-md">{formatTimeStr(p.time)}</text>
                                    ))}

                                    {getRelativeAz(currentSunPos.az, currentCenterAz) >= -(displayFovAzimuth/2) && getRelativeAz(currentSunPos.az, currentCenterAz) <= (displayFovAzimuth/2) && (
                                        <g transform={`translate(${mapAzToX(currentSunPos.az).toFixed(2)}, ${mapAltToY(currentSunPos.alt).toFixed(2)})`}>
                                            <circle cx="0" cy="0" r={sunRadius + 20} fill="rgba(252, 211, 77, 0.3)"/>
                                            <circle cx="0" cy="0" r={sunRadius} fill="#fcd34d" fillOpacity="0.9" stroke="#f59e0b" strokeWidth="2"/>
                                            <line x1="-12" y1="0" x2="12" y2="0" stroke="#b45309" strokeWidth="1.5" opacity="0.7"/>
                                            <line x1="0" y1="-12" x2="0" y2="12" stroke="#b45309" strokeWidth="1.5" opacity="0.7"/>
                                        </g>
                                    )}

                                    {getRelativeAz(currentMoonPos.az, currentCenterAz) >= -(displayFovAzimuth/2) && getRelativeAz(currentMoonPos.az, currentCenterAz) <= (displayFovAzimuth/2) && (
                                        <g transform={`translate(${mapAzToX(currentMoonPos.az).toFixed(2)}, ${mapAltToY(currentMoonPos.alt).toFixed(2)})`}>
                                            <circle cx="0" cy="0" r={moonRadius + 20} fill="rgba(191, 219, 254, 0.3)"/>
                                            <circle cx="0" cy="0" r={moonRadius} fill="#e0f2fe" fillOpacity="0.9" stroke="#93c5fd" strokeWidth="2"/>
                                            <line x1="-12" y1="0" x2="12" y2="0" stroke="#1e3a8a" strokeWidth="1.5" opacity="0.7"/>
                                            <line x1="0" y1="-12" x2="0" y2="12" stroke="#1e3a8a" strokeWidth="1.5" opacity="0.7"/>
                                        </g>
                                    )}

                                    {targetBaseY < SVG_HEIGHT && (
                                        <rect x="0" y={targetBaseY} width={SVG_WIDTH} height={Math.max(0, SVG_HEIGHT - targetBaseY)} fill="#020617" opacity="0.9" />
                                    )}

                                    <g transform={`translate(${mapAzToX(alignment.bearing).toFixed(2)}, 0)`}>
                                        <path d={`M ${-targetHalfW} ${targetBaseY} L ${-(targetHalfW*0.6)} ${targetTopY} L ${targetHalfW*0.6} ${targetTopY} L ${targetHalfW} ${targetBaseY} Z`} fill="#0f172a" stroke="#1e293b" strokeWidth="2" opacity="1"/>
                                        <line x1="0" y1={targetBaseY} x2="0" y2={targetTopY} stroke="#ef4444" strokeWidth="2" strokeDasharray="4,2" opacity="0.6"/>
                                        <circle cx="0" cy={targetTopY} r="4" fill="#ef4444"/>
                                        <text x="0" y={targetTopY - 15} fill="#f8fafc" fontSize="12" fontWeight="bold" textAnchor="middle" className="drop-shadow-md">Target Top ({pitchToTargetTop > 0 ? '+' : ''}{pitchToTargetTop.toFixed(2)}°)</text>
                                    </g>

                                    {contextMultiplier > 1 && !panoMode && (
                                        <g>
                                            <rect x={frameX} y={frameY} width={frameW} height={frameH} fill="none" stroke="rgba(56, 189, 248, 0.8)" strokeWidth="3" strokeDasharray="12,8" />
                                            <text x={frameX + 10} y={frameY + 20} fill="rgba(56, 189, 248, 0.9)" fontSize="14" fontWeight="bold" className="drop-shadow-md">Camera Frame ({focalLength}mm)</text>
                                        </g>
                                    )}

                                    {contextMultiplier > 1 && panoMode && (
                                        <g>
                                            {[-1, 0, 1].map(col => (
                                                [-0.5, 0.5].map(row => {
                                                    const px = frameX + (col * frameW * 0.7); 
                                                    const py = frameY + (row * frameH * 0.7);
                                                    return <rect key={`pano-${col}-${row}`} x={px} y={py} width={frameW} height={frameH} fill="none" stroke="rgba(245, 158, 11, 0.6)" strokeWidth="2" strokeDasharray="6,4" />;
                                                })
                                            ))}
                                            <rect x={frameX - frameW * 0.7} y={frameY - frameH * 0.35} width={frameW * 2.4} height={frameH * 1.7} fill="none" stroke="rgba(245, 158, 11, 0.9)" strokeWidth="2" />
                                            <text x={frameX - frameW * 0.7 + 10} y={frameY - frameH * 0.35 + 20} fill="rgba(245, 158, 11, 0.9)" fontSize="14" fontWeight="bold" className="drop-shadow-md">Panorama Grid (3x2, 30% overlap)</text>
                                        </g>
                                    )}
                                    
                                    {arMode && (
                                        <g>
                                            <line x1={SVG_WIDTH/2 - 20} y1={SVG_HEIGHT/2} x2={SVG_WIDTH/2 + 20} y2={SVG_HEIGHT/2} stroke="white" strokeWidth="2" opacity="0.5" />
                                            <line x1={SVG_WIDTH/2} y1={SVG_HEIGHT/2 - 20} x2={SVG_WIDTH/2} y2={SVG_HEIGHT/2 + 20} stroke="white" strokeWidth="2" opacity="0.5" />
                                        </g>
                                    )}
                                </svg>
                                
                                <div className="absolute top-4 left-4 text-white text-xs md:text-sm font-mono opacity-70 bg-slate-900/50 px-2 py-1 rounded flex items-center gap-2">
                                    {arMode ? 'Live AR Sensor Data' : 'Azimuth vs Altitude Grid'}
                                    {terrainData?.blocked && !arMode && (
                                        <span className="text-red-500 font-bold ml-2 bg-red-900/50 px-2 py-0.5 rounded flex items-center gap-1"><Icon name="alertTriangle" size={12}/> BLOCKED</span>
                                    )}
                                </div>
                            </div>
                        </div>

                        <div className="w-full md:w-80 lg:w-96 shrink-0 bg-slate-800 md:border-l border-slate-700 flex flex-col md:h-auto md:self-stretch">
                            <div className="flex-1 overflow-y-auto p-5 md:p-6 custom-scrollbar">
                                <div className="mb-6">
                                    <div className="flex items-center gap-2 mb-4">
                                        <Icon name="aperture" size={18} className="text-sky-400" />
                                        <h4 className="font-black text-white uppercase tracking-widest text-[10px] md:text-xs">Camera FOV Setup</h4>
                                    </div>
                                    <div className="flex gap-2 mb-2">
                                        <select value={sensor} onChange={(e) => setSensor(e.target.value)} className="bg-slate-700 border-none text-white text-[10px] md:text-xs font-bold rounded p-2 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-700 rounded flex items-center p-2">
                                            <input type="number" value={focalLength} onChange={(e) => setFocalLength(e.target.value)} className="bg-transparent border-none text-white text-[10px] md:text-xs font-bold w-full outline-none text-right" min="10" max="2000" />
                                            <span className="text-[10px] text-slate-400 font-bold ml-1">mm</span>
                                        </div>
                                    </div>
                                    <div className="flex gap-2">
                                        <div className="relative flex-1 bg-slate-700 rounded flex items-center p-2">
                                            <span className="text-[10px] text-slate-400 font-bold mr-2">f/</span>
                                            <input type="number" value={aperture} onChange={(e) => setAperture(e.target.value)} className="bg-transparent border-none text-white text-[10px] md:text-xs font-bold w-full outline-none" min="1.0" max="32" step="0.1" />
                                        </div>
                                    </div>
                                    
                                    <div className="flex flex-col gap-1 mt-3 bg-slate-900/50 p-2 rounded">
                                        <div className="flex items-center justify-between text-[10px] text-slate-400">
                                            <span>Field of View:</span>
                                            <strong className="text-white">{fovAzimuth.toFixed(1)}° <span className="font-normal mx-0.5 text-slate-500">x</span> {fovAltitude.toFixed(1)}°</strong>
                                        </div>
                                        <div className="flex items-center justify-between text-[10px] text-slate-400">
                                            <span title="The closest distance you can focus while keeping infinity sharp">Hyperfocal Dist:</span>
                                            <strong className="text-emerald-400">{hyperfocal.toFixed(2)}m</strong>
                                        </div>
                                        <div className="flex items-center justify-between text-[10px] text-slate-400 mt-1">
                                            <span title="Max shutter speed to avoid star trails">Spot Stars (NPF / 500):</span>
                                            <strong className="text-sky-400">{astroStats.npf}s / {astroStats.rule500}s</strong>
                                        </div>
                                    </div>
                                </div>

                                <div className="border-t border-slate-700 my-4"></div>

                                <div className="flex items-center gap-2 mb-4">
                                    <Icon name="target" size={18} className="text-rose-400" />
                                    <h4 className="font-black text-white uppercase tracking-widest text-[10px] md:text-xs">Target Details</h4>
                                </div>

                                <div className="grid grid-cols-2 gap-4 mb-4">
                                    <div>
                                        <label className="flex justify-between items-center text-[9px] font-bold text-slate-300 uppercase tracking-widest mb-2">
                                            <span>Height</span>
                                            <span className="text-white bg-slate-700 px-1.5 py-0.5 rounded">{targetHeight}m</span>
                                        </label>
                                        <input type="range" min="1" max="200" value={targetHeight} onChange={(e) => setTargetHeight(parseInt(e.target.value, 10))} className="w-full ar-scrubber"/>
                                    </div>
                                    <div>
                                        <label className="flex justify-between items-center text-[9px] font-bold text-slate-300 uppercase tracking-widest mb-2">
                                            <span>Width</span>
                                            <span className="text-white bg-slate-700 px-1.5 py-0.5 rounded">{targetWidth}m</span>
                                        </label>
                                        <input type="range" min="1" max="200" value={targetWidth} onChange={(e) => setTargetWidth(parseInt(e.target.value, 10))} className="w-full ar-scrubber"/>
                                    </div>
                                </div>
                                
                                <div className="flex flex-col gap-1 mb-2">
                                    <p className="text-[10px] text-slate-400 leading-snug flex justify-between">Apparent altitude: <strong className="text-white ml-1">{apparentAlt.toFixed(2)}°</strong></p>
                                    <p className="text-[10px] text-slate-400 leading-snug flex justify-between" title="Calculated using exact ephemeris angular diameters">Apparent Size: <strong className="text-fuchsia-400 ml-1">Sun {sunRatioText} / Moon {moonRatioText}</strong></p>
                                    <p className="text-[10px] text-slate-400 leading-snug flex justify-between">Current shadow length: <strong className="text-amber-400 ml-1">{shadowLength}</strong></p>
                                </div>
                                
                            </div>

                            <div className="shrink-0 bg-slate-900/60 border-t border-slate-700 p-5 md:p-6 shadow-[0_-10px_20px_-5px_rgba(0,0,0,0.3)]">
                                <div className="flex items-center gap-2 mb-2">
                                    <Icon name="target" size={16} className="text-emerald-400" />
                                    <h4 className="font-black text-white uppercase tracking-widest text-[10px] md:text-xs">Smart Auto-Align</h4>
                                </div>
                                <p className="text-[9px] text-slate-400 mb-4 leading-relaxed">Calculate exact distance and time to perfectly frame the body behind the target.</p>
                                
                                <div className="space-y-3">
                                    <div className="bg-gradient-to-br from-amber-900/40 to-slate-800/80 border border-amber-700/40 rounded-xl p-3 shadow-inner relative overflow-hidden">
                                        <div className="absolute top-0 left-0 w-1 h-full bg-amber-500/50"></div>
                                        <div className="flex justify-between items-center mb-2.5 pl-2">
                                            <span className="text-[10px] font-bold text-amber-400 flex items-center gap-1.5 uppercase tracking-widest"><Icon name="sun" size={14}/> Sun Alt</span>
                                            <span className="text-amber-100 font-mono text-[10px] bg-amber-900/60 px-1.5 py-0.5 rounded border border-amber-800">{sunData?.altitude.toFixed(1)}°</span>
                                        </div>
                                        <div className="flex gap-2 pl-2">
                                            <button onClick={() => handleSmartAlign('sun', 'rise')} disabled={!sunData} className="w-full bg-amber-600/90 hover:bg-amber-500 disabled:bg-slate-700 disabled:text-slate-500 text-white py-2 rounded-lg text-[9px] md:text-[10px] font-black uppercase tracking-widest transition-colors shadow-md">Align Rise</button>
                                            <button onClick={() => handleSmartAlign('sun', 'set')} disabled={!sunData} className="w-full bg-amber-700/90 hover:bg-amber-600 disabled:bg-slate-700 disabled:text-slate-500 text-white py-2 rounded-lg text-[9px] md:text-[10px] font-black uppercase tracking-widest transition-colors shadow-md">Align Set</button>
                                        </div>
                                    </div>

                                    <div className="bg-gradient-to-br from-indigo-900/40 to-slate-800/80 border border-indigo-700/40 rounded-xl p-3 shadow-inner relative overflow-hidden">
                                        <div className="absolute top-0 left-0 w-1 h-full bg-indigo-500/50"></div>
                                        <div className="flex justify-between items-center mb-2.5 pl-2">
                                            <span className="text-[10px] font-bold text-indigo-400 flex items-center gap-1.5 uppercase tracking-widest"><Icon name="moon" size={14}/> Moon Alt</span>
                                            <span className="text-indigo-100 font-mono text-[10px] bg-indigo-900/60 px-1.5 py-0.5 rounded border border-indigo-800">{moonData?.altitude.toFixed(1)}°</span>
                                        </div>
                                        <div className="flex gap-2 pl-2">
                                            <button onClick={() => handleSmartAlign('moon', 'rise')} disabled={!moonData} className="w-full bg-indigo-600/90 hover:bg-indigo-500 disabled:bg-slate-700 disabled:text-slate-500 text-white py-2 rounded-lg text-[9px] md:text-[10px] font-black uppercase tracking-widest transition-colors shadow-md">Align Rise</button>
                                            <button onClick={() => handleSmartAlign('moon', 'set')} disabled={!moonData} className="w-full bg-indigo-700/90 hover:bg-indigo-600 disabled:bg-slate-700 disabled:text-slate-500 text-white py-2 rounded-lg text-[9px] md:text-[10px] font-black uppercase tracking-widest transition-colors shadow-md">Align Set</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div className="bg-slate-900 p-3 md:p-5 border-t border-slate-800 flex flex-row items-center justify-between gap-3 md:gap-4 shrink-0 z-20">
                        <div className="text-xl md:text-2xl font-black font-mono tracking-tighter text-white shrink-0">
                            {date.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', second: '2-digit' })}
                        </div>
                        <div className="flex items-center gap-2 md:gap-4 w-full">
                            <button onClick={() => setIsPlaying(!isPlaying)} className={`p-2.5 md:p-3 rounded-full flex-shrink-0 transition-colors shadow-sm ${isPlaying ? 'bg-sky-500 text-white' : 'bg-slate-700 text-sky-400 hover:bg-slate-600'}`}>
                                <Icon name={isPlaying ? "pause" : "play"} size={14} />
                            </button>
                            <input type="range" min="0" max="86399" value={secondsOfDay} onChange={handleTimeChange} className="w-full ar-scrubber"/>
                        </div>
                    </div>
                </div>
            );
        };
