"use client";

import { useState, useEffect, useMemo } from "react";

interface FormattedDateProps {
  readonly date: Date | string;
  readonly locale: string;
  readonly options?: Intl.DateTimeFormatOptions;
}

/**
 * Client component to format dates safely without hydration mismatches
 * Accepts Date object or ISO date string to ensure consistency
 */
export function FormattedDate({ date, locale, options = { year: "numeric", month: "long", day: "numeric" } }: FormattedDateProps) {
  // Normalize date to ensure consistency - convert to Date object if string
  const dateObj = useMemo(() => {
    return typeof date === 'string' ? new Date(date) : date;
  }, [typeof date === 'string' ? date : date.getTime()]);

  // Create a stable initial date string that won't change between renders
  // Use only year, month, day to avoid timezone issues
  const initialDate = useMemo(() => {
    const year = dateObj.getFullYear();
    const month = dateObj.getMonth() + 1;
    const day = dateObj.getDate();
    return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  }, [dateObj.getFullYear(), dateObj.getMonth(), dateObj.getDate()]);

  const [displayDate, setDisplayDate] = useState<string>(initialDate);
  const [isMounted, setIsMounted] = useState(false);

  useEffect(() => {
    setIsMounted(true);
    // After mount, update to the properly formatted locale string
    try {
      const formatted = dateObj.toLocaleDateString(locale, options);
      setDisplayDate(formatted);
    } catch (error) {
      // Fallback to initial date if formatting fails
      setDisplayDate(initialDate);
    }
  }, [dateObj, locale, options, initialDate]);

  // Use suppressHydrationWarning because we intentionally change the format after mount
  return <span suppressHydrationWarning>{displayDate}</span>;
}

