"use client"; import React from 'react'; import { useState, useEffect, useRef } from 'react'; import { EventCardProps } from '@/types/space'; import { useRouter } from 'next/navigation'; import { motion, AnimatePresence } from 'framer-motion'; import { LucideProps } 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 && ( )}
{isLive ? (
{React.isValidElement(icon) ? React.cloneElement(icon as React.ReactElement, { size: 35 }) : icon}

{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 ? ( <> {timeLeft.d} Days ) : (
{timeLeft.h}: {timeLeft.m}:
{timeLeft.s}
)}

{id === 'iss' ? "T-Minus to Horizon" : id === 'launch' ? "T-Minus to Ignition" : id === 'moon' ? "Until Lunar Phase" : "Days to Peak Phase"}

)}
); }