'use client'; import React, { useState, useEffect, createContext, useContext } from 'react'; interface ClientTimeContextType { mounted: boolean; currentTime: Date; } const ClientTimeContext = createContext({ mounted: false, currentTime: new Date(0) }); export function ClientTimeProvider({ children }: { children: React.ReactNode }) { const [mounted, setMounted] = useState(false); const [currentTime, setCurrentTime] = useState(new Date(0)); useEffect(() => { setMounted(true); // Don't update time immediately to prevent hydration mismatch // Wait a bit before starting the interval const timeout = setTimeout(() => { setCurrentTime(new Date()); // Update time every second to keep it fresh const interval = setInterval(() => { setCurrentTime(new Date()); }, 1000); return () => clearInterval(interval); }, 100); // Small delay to ensure hydration is complete return () => clearTimeout(timeout); }, []); return ( {children} ); } export function useClientTime() { return useContext(ClientTimeContext); } // Universal client-safe timestamp component export function SafeTimestamp({ timestamp, format = 'time', fallback = '--:--:--' }: { timestamp: Date | string; format?: 'time' | 'datetime' | 'date'; fallback?: string; }) { const { mounted } = useClientTime(); if (!mounted) { return {fallback}; } const date = typeof timestamp === 'string' ? new Date(timestamp) : timestamp; switch (format) { case 'time': return {date.toLocaleTimeString()}; case 'datetime': return {date.toLocaleString()}; case 'date': return {date.toLocaleDateString()}; default: return {date.toLocaleTimeString()}; } } // Current time display that's always client-safe export function CurrentTime({ format = 'time', fallback = '--:--:--' }: { format?: 'time' | 'datetime' | 'date'; fallback?: string; }) { const { mounted, currentTime } = useClientTime(); if (!mounted || currentTime.getTime() === 0) { return {fallback}; } switch (format) { case 'time': return {currentTime.toLocaleTimeString()}; case 'datetime': return {currentTime.toLocaleString()}; case 'date': return {currentTime.toLocaleDateString()}; default: return {currentTime.toLocaleTimeString()}; } } export default ClientTimeProvider;