"use client";

import { useEffect, useState } from "react";
import { cn } from "@/lib/cn";

interface LiveBadgeProps {
  /** 最后更新时间 */
  updatedAt: Date | null;
  /** 是否处于加载 / 暂停态 */
  paused?: boolean;
  className?: string;
}

/**
 * 实时排名状态徽章。
 * 显示 "LIVE · 5s ago" 并带一个心跳呼吸点。
 */
export default function LiveBadge({
  updatedAt,
  paused = false,
  className,
}: LiveBadgeProps) {
  const [, force] = useState(0);

  // 每秒刷新一次相对时间显示
  useEffect(() => {
    const id = setInterval(() => force((x) => x + 1), 1000);
    return () => clearInterval(id);
  }, []);

  const rel = updatedAt ? formatRelative(updatedAt) : "正在连接…";

  return (
    <span
      className={cn(
        "inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-white/[0.04] border border-white/10 text-[10px] tracking-widest font-label uppercase",
        paused ? "text-white/45" : "text-purple-300",
        className,
      )}
    >
      <span
        className={cn(
          "w-1.5 h-1.5 rounded-full",
          paused
            ? "bg-white/40"
            : "bg-purple-400 animate-pulse-glow shadow-[0_0_6px_rgba(167,139,250,0.8)]",
        )}
      />
      {paused ? "Paused" : "Live"}
      <span className="text-white/35 normal-case tracking-normal">·</span>
      <span className="text-white/55 normal-case tracking-normal">{rel}</span>
    </span>
  );
}

function formatRelative(d: Date): string {
  const sec = Math.floor((Date.now() - d.getTime()) / 1000);
  if (sec < 5) return "just now";
  if (sec < 60) return `${sec}s ago`;
  if (sec < 3600) return `${Math.floor(sec / 60)}m ago`;
  return d.toLocaleTimeString();
}
