'use client';

import { useEffect, useState } from 'react';
import { useLanguage } from '@/lib/i18n/LanguageContext';

interface LocalTimeProps {
  date: string | Date; // 接收 UTC 时间
  className?: string;
  options?: Intl.DateTimeFormatOptions;
}

export default function LocalTime({ date, className, options }: LocalTimeProps) {
  const { lang } = useLanguage();
  const [localTimeString, setLocalTimeString] = useState<string>('');

  useEffect(() => {
    if (!date) return;
    
    let dateObj: Date;

    // === 核心修复逻辑 ===
    if (typeof date === 'string') {
      // 1. 兼容 "YYYY-MM-DD HH:mm:ss" 格式，将空格替换为 T
      let normalizedDate = date.replace(' ', 'T');

      // 2. 如果字符串末尾没有 'Z' 且没有时区偏移（如 +08:00），强制追加 'Z'
      // 这告诉浏览器：“这个时间字符串是 UTC 时间”
      if (!normalizedDate.endsWith('Z') && !normalizedDate.includes('+')) {
        normalizedDate += 'Z';
      }
      
      dateObj = new Date(normalizedDate);
    } else {
      dateObj = date;
    }

    // 检查日期是否有效
    if (isNaN(dateObj.getTime())) {
      setLocalTimeString('Invalid Date');
      return;
    }

    const locale = lang === 'zh' ? 'zh-CN' : 'en-US';
    
    const defaultOptions: Intl.DateTimeFormatOptions = {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false,
    };

    const finalOptions = { ...defaultOptions, ...options };
    
    // 使用浏览器的 Intl API 进行本地化格式化 (会自动转换为用户时区)
    const formatter = new Intl.DateTimeFormat(locale, finalOptions);

    setLocalTimeString(formatter.format(dateObj));
  }, [date, lang, options]);

  if (!localTimeString) {
    return <span className={`opacity-0 ${className}`}>--:--</span>;
  }

  return <span className={className}>{localTimeString}</span>;
}