"use client";

import { useEffect, useState } from "react";

// Extracted from EscortCard so the timestamp comparisons happen client-side.
// Earlier the server component called Date.now() at render time; on ISR pages
// the build/revalidate snapshot diverged from the client clock, producing
// hydration warnings and visible jank.

export function NewBadge({ createdAt }: { createdAt: Date | string | null | undefined }) {
  const [show, setShow] = useState(false);
  useEffect(() => {
    if (!createdAt) return;
    const ms = Date.now() - new Date(createdAt).getTime();
    if (ms < 14 * 24 * 60 * 60 * 1000) setShow(true);
  }, [createdAt]);
  if (!show) return null;
  return (
    <span className="absolute top-2 left-2 z-10 inline-flex items-center gap-1 rounded-full bg-emerald-500/90 px-2 py-0.5 text-[10px] font-bold uppercase text-white shadow-lg">
      New
    </span>
  );
}

export function OnlineDot({ lastOnlineAt }: { lastOnlineAt: Date | string | null | undefined }) {
  const [state, setState] = useState<"online" | "recent" | null>(null);
  useEffect(() => {
    if (!lastOnlineAt) return;
    const mins = (Date.now() - new Date(lastOnlineAt).getTime()) / 60000;
    if (mins > 30) return;
    // D.9: align thresholds with <LastSeen> — < 5 min = "Online now" (green
    // pulse), 5–30 min = "Recently active" (yellow). Earlier the card used
    // < 15 / 15–60 thresholds which contradicted the profile-page LastSeen
    // ("Online" badge there cuts off at 5 min). Now both surfaces tell
    // viewers the same story.
    setState(mins <= 5 ? "online" : "recent");
  }, [lastOnlineAt]);
  if (!state) return null;
  return (
    <span
      className={`absolute top-2.5 right-12 z-10 h-3 w-3 rounded-full ring-2 ring-surface ${
        state === "online" ? "bg-green-500 animate-pulse" : "bg-yellow-500"
      }`}
      aria-label={state === "online" ? "Online" : "Recently online"}
    />
  );
}
