"use client";

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

interface CountdownProps {
  /** 截止时间 */
  endTime: Date | string | number;
  /** 紧凑模式（横向小尺寸） */
  compact?: boolean;
  className?: string;
}

interface TimeLeft {
  days: number;
  hours: number;
  minutes: number;
  seconds: number;
  finished: boolean;
}

function computeTimeLeft(end: number): TimeLeft {
  const diff = Math.max(0, end - Date.now());
  const days = Math.floor(diff / 86_400_000);
  const hours = Math.floor((diff % 86_400_000) / 3_600_000);
  const minutes = Math.floor((diff % 3_600_000) / 60_000);
  const seconds = Math.floor((diff % 60_000) / 1_000);
  return { days, hours, minutes, seconds, finished: diff <= 0 };
}

const UNIT_LABELS = [
  ["days", "Days"],
  ["hours", "Hours"],
  ["minutes", "Min"],
  ["seconds", "Sec"],
] as const;

export default function Countdown({
  endTime,
  compact = false,
  className,
}: CountdownProps) {
  const end = new Date(endTime).getTime();
  const [time, setTime] = useState<TimeLeft | null>(null);

  // 客户端首次渲染后再启动 tick，避免 SSR 与客户端时间不一致
  useEffect(() => {
    setTime(computeTimeLeft(end));
    const id = setInterval(() => setTime(computeTimeLeft(end)), 1000);
    return () => clearInterval(id);
  }, [end]);

  if (!time) {
    // 占位高度避免布局抖动
    return (
      <div
        className={cn(
          "flex items-center gap-3",
          compact ? "h-9" : "h-20",
          className,
        )}
        aria-hidden
      />
    );
  }

  if (time.finished) {
    return (
      <div
        className={cn(
          "font-display tracking-widest text-pink-400 uppercase",
          className,
        )}
      >
        Activity Ended
      </div>
    );
  }

  const values = [time.days, time.hours, time.minutes, time.seconds];

  if (compact) {
    return (
      <div
        className={cn(
          "inline-flex items-center gap-2 px-4 py-1.5 rounded-full",
          "bg-[rgba(13,10,36,0.55)] backdrop-blur-md",
          "border border-purple-300/40",
          className,
        )}
      >
        <span className="text-white/85 text-xs">距离投票结束</span>
        <span className="font-display text-xs text-purple-300 tabular-nums tracking-wider">
          {time.days}天 {String(time.hours).padStart(2, "0")}:
          {String(time.minutes).padStart(2, "0")}:
          {String(time.seconds).padStart(2, "0")}
        </span>
      </div>
    );
  }

  return (
    <div className={cn("flex items-center gap-3", className)}>
      {values.map((v, i) => (
        <div key={UNIT_LABELS[i]![0]} className="flex items-center gap-3">
          <div className="bg-surface border border-[var(--border-purple)] rounded-lg px-4 sm:px-5 py-3 text-center shadow-[0_0_16px_rgba(139,92,246,0.15)] min-w-[64px]">
            <div className="font-display text-2xl sm:text-3xl text-purple-300 glow-text-purple tabular-nums leading-none tracking-wider">
              {String(v).padStart(2, "0")}
            </div>
            <div className="font-label text-[10px] tracking-[0.2em] uppercase text-white/40 mt-1.5">
              {UNIT_LABELS[i]![1]}
            </div>
          </div>
          {i < 3 && (
            <span className="text-2xl text-white/30 font-light pb-3.5">:</span>
          )}
        </div>
      ))}
    </div>
  );
}
