"use client"; import { useState, useEffect, useRef } from 'react'; import { EventCardProps } from '@/types/space'; import { useRouter } from 'next/navigation'; import { Sparkles } from 'lucide-react'; export default function EventCard({ id, title, targetDate, endDate, icon }: EventCardProps) { const [isLive, setIsLive] = useState(false); const router = useRouter(); const [timeLeft, setTimeLeft] = useState({ d: "00", h: "00", m: "00", s: "00" }); const lastRefreshedRef = useRef(null); useEffect(() => { const updateTimer = () => { if (!targetDate || !endDate) return; const now = new Date(); const timeToStart = targetDate.getTime() - now.getTime(); const timeToEnd = endDate.getTime() - now.getTime(); if (timeToStart <= 0 && timeToEnd > 0) { if (!isLive) setIsLive(true); return; } if (timeToEnd <= 0) { if (isLive) setIsLive(false); const passId = endDate.toISOString(); if (lastRefreshedRef.current !== passId) { const isStaleDataFromServer = endDate.getTime() < (new Date().getTime() - 5000); if (!isStaleDataFromServer) { console.log("🛰️ Pass complete. Syncing with Mission Control..."); lastRefreshedRef.current = passId; router.refresh(); } else { console.warn("⚠️ Server returned stale ISS data. Standing by for worker update..."); lastRefreshedRef.current = passId; } } return; } const distance = timeToStart; const d = Math.floor(distance / (1000 * 60 * 60 * 24)); const h = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); const m = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); const s = Math.floor((distance % (1000 * 60)) / 1000); setTimeLeft({ d: d.toString().padStart(2, '0'), h: h.toString().padStart(2, '0'), m: m.toString().padStart(2, '0'), s: s.toString().padStart(2, '0') }); }; const interval = setInterval(updateTimer, 1000); updateTimer(); return () => clearInterval(interval); }, [targetDate, endDate, isLive, router]); if (!targetDate) { return (
{icon}

{title}

Waiting for orbital telemetry...

); } return (
{isLive ? (

{id === 'iss' ? 'Look Up!' : 'Event in Progress'}

{id === 'iss' ? 'The ISS is directly above. Give them a wave! 👋' : `The ${title} is occurring right now.`}

) : ( <>
{icon}

{title}

{parseInt(timeLeft.d) >= 2 ? ( /* Case 1: More than 2 days - Keep it super simple */ <> {timeLeft.d} Days ) : parseInt(timeLeft.d) === 1 ? ( /* Case 2: Between 24 and 48 hours - Show Day + Hours */ <> 01d : {timeLeft.h}h ) : ( /* Case 3: Under 24 hours - The full high-precision clock */ <> {timeLeft.h} : {timeLeft.m} : {timeLeft.s} )}

{parseInt(timeLeft.d) > 0 ? "Until event" : "T-Minus to Horizon"}

)}
); }