"use client";

/**
 * 倒计时组件（ai14）
 *
 * 基于服务器时间偏移计算剩余时间，防止客户端篡改
 * 最后 5 分钟变红色警告，最后 1 分钟闪烁
 * 倒计时归零时触发 onTimeUp 回调
 */

import { useState, useEffect, useRef } from "react";
import { cn } from "@/lib/exam-types";

export interface CountdownTimerProps {
  /** 考试截止时间（ISO 8601） */
  endTime: string;
  /** 倒计时归零回调 */
  onTimeUp: () => void;
  /** 服务器时间偏移（毫秒，serverTime - clientTime） */
  serverTimeOffset: number;
}

/** 格式化秒数为 HH:MM:SS */
function formatDuration(totalSeconds: number): string {
  const h = Math.floor(totalSeconds / 3600);
  const m = Math.floor((totalSeconds % 3600) / 60);
  const s = totalSeconds % 60;
  return [h, m, s].map((n) => String(n).padStart(2, "0")).join(":");
}

/** 计算剩余秒数 */
function calcRemaining(endTime: string, offset: number): number {
  const expiry = new Date(endTime).getTime();
  const correctedNow = Date.now() + offset;
  return Math.max(0, Math.floor((expiry - correctedNow) / 1000));
}

export function CountdownTimer({
  endTime,
  onTimeUp,
  serverTimeOffset,
}: CountdownTimerProps): JSX.Element {
  const [remaining, setRemaining] = useState(() =>
    calcRemaining(endTime, serverTimeOffset),
  );
  const onTimeUpRef = useRef(onTimeUp);
  onTimeUpRef.current = onTimeUp;

  useEffect(() => {
    const tick = (): void => {
      const r = calcRemaining(endTime, serverTimeOffset);
      setRemaining(r);
      if (r === 0) {
        onTimeUpRef.current();
      }
    };
    tick();
    const interval = setInterval(tick, 1000);
    return () => clearInterval(interval);
  }, [endTime, serverTimeOffset]);

  const formatted = formatDuration(remaining);
  const isUrgent = remaining <= 300 && remaining > 0; // 最后 5 分钟
  const isCritical = remaining <= 60 && remaining > 0; // 最后 1 分钟
  const isExpired = remaining === 0;

  return (
    <div
      className={cn(
        "font-mono text-2xl tabular-nums transition-colors",
        isExpired && "text-danger",
        isCritical && "text-danger animate-pulse",
        isUrgent && !isCritical && "text-warning",
        !isUrgent && !isCritical && !isExpired && "text-ink",
      )}
      role="timer"
      aria-live="polite"
      aria-label={`剩余时间 ${formatted}`}
    >
      {isExpired ? "时间到" : formatted}
    </div>
  );
}
