import Link from "next/link";
import { avatarUrl } from "@/lib/media";
import MediaImage from "./media-image";
import VerifiedBadge from "./verified-badge";
import AvailabilityPill from "./availability-pill";
import { CompareAddButton } from "./compare-button";
import { NewBadge, OnlineDot } from "./escort-card-time-bits";
import { HeartFavoriteButton } from "./heart-favorite-button";

// Maps common country names to flag emojis
function countryFlag(name?: string | null): string {
  if (!name) return "";
  const flags: Record<string, string> = {
    "united kingdom": "\u{1F1EC}\u{1F1E7}", "uk": "\u{1F1EC}\u{1F1E7}", "england": "\u{1F1EC}\u{1F1E7}",
    "thailand": "\u{1F1F9}\u{1F1ED}", "germany": "\u{1F1E9}\u{1F1EA}", "spain": "\u{1F1EA}\u{1F1F8}",
    "france": "\u{1F1EB}\u{1F1F7}", "italy": "\u{1F1EE}\u{1F1F9}", "netherlands": "\u{1F1F3}\u{1F1F1}",
    "belgium": "\u{1F1E7}\u{1F1EA}", "switzerland": "\u{1F1E8}\u{1F1ED}", "austria": "\u{1F1E6}\u{1F1F9}",
    "portugal": "\u{1F1F5}\u{1F1F9}", "greece": "\u{1F1EC}\u{1F1F7}", "turkey": "\u{1F1F9}\u{1F1F7}",
    "united states": "\u{1F1FA}\u{1F1F8}", "usa": "\u{1F1FA}\u{1F1F8}", "canada": "\u{1F1E8}\u{1F1E6}",
    "australia": "\u{1F1E6}\u{1F1FA}", "brazil": "\u{1F1E7}\u{1F1F7}", "colombia": "\u{1F1E8}\u{1F1F4}",
    "mexico": "\u{1F1F2}\u{1F1FD}", "argentina": "\u{1F1E6}\u{1F1F7}", "czech republic": "\u{1F1E8}\u{1F1FF}",
    "czechia": "\u{1F1E8}\u{1F1FF}", "poland": "\u{1F1F5}\u{1F1F1}", "romania": "\u{1F1F7}\u{1F1F4}",
    "hungary": "\u{1F1ED}\u{1F1FA}", "sweden": "\u{1F1F8}\u{1F1EA}", "norway": "\u{1F1F3}\u{1F1F4}",
    "denmark": "\u{1F1E9}\u{1F1F0}", "finland": "\u{1F1EB}\u{1F1EE}", "ireland": "\u{1F1EE}\u{1F1EA}",
    "japan": "\u{1F1EF}\u{1F1F5}", "south korea": "\u{1F1F0}\u{1F1F7}", "philippines": "\u{1F1F5}\u{1F1ED}",
    "india": "\u{1F1EE}\u{1F1F3}", "russia": "\u{1F1F7}\u{1F1FA}", "ukraine": "\u{1F1FA}\u{1F1E6}",
    "south africa": "\u{1F1FF}\u{1F1E6}", "nigeria": "\u{1F1F3}\u{1F1EC}", "kenya": "\u{1F1F0}\u{1F1EA}",
    "uae": "\u{1F1E6}\u{1F1EA}", "united arab emirates": "\u{1F1E6}\u{1F1EA}", "dubai": "\u{1F1E6}\u{1F1EA}",
    "singapore": "\u{1F1F8}\u{1F1EC}", "malaysia": "\u{1F1F2}\u{1F1FE}", "indonesia": "\u{1F1EE}\u{1F1E9}",
    "new zealand": "\u{1F1F3}\u{1F1FF}", "china": "\u{1F1E8}\u{1F1F3}", "croatia": "\u{1F1ED}\u{1F1F7}",
    "bulgaria": "\u{1F1E7}\u{1F1EC}", "slovakia": "\u{1F1F8}\u{1F1F0}", "latvia": "\u{1F1F1}\u{1F1FB}",
    "lithuania": "\u{1F1F1}\u{1F1F9}", "estonia": "\u{1F1EA}\u{1F1EA}", "cyprus": "\u{1F1E8}\u{1F1FE}",
    "malta": "\u{1F1F2}\u{1F1F9}", "luxembourg": "\u{1F1F1}\u{1F1FA}", "scotland": "\u{1F3F4}\u{E0067}\u{E0062}\u{E0073}\u{E0063}\u{E0074}\u{E007F}",
  };
  return flags[name.toLowerCase()] ?? "";
}

interface EscortCardProps {
  escort: {
    id: number;
    id_aw: string | null;
    username: string | null;
    profile_photo: string | null;
    is_verified: boolean;
    is_vip: boolean;
    status: string | null;
    lastonline_at: Date | null;
    is_agency?: boolean | null;
    country?: { name: string } | null;
    city?: { name: string } | null;
    photo_count?: number;
    _count?: { photos?: number };
    created_at?: Date | null;
    rateUsers?: { in_call?: string | null; out_call?: string | null }[] | null;
    avatarMediaUrls?: string[];
  };
}

export default function EscortCard({ escort }: EscortCardProps) {
  const href = `/view/${escort.id_aw ?? escort.id}`;
  const isAvailable = escort.status === "available";
  const photoCount = escort.photo_count ?? escort._count?.photos ?? 0;

  // "From" price: find minimum rate
  const minRate = (() => {
    if (!escort.rateUsers || escort.rateUsers.length === 0) return null;
    let min = Infinity;
    for (const ru of escort.rateUsers) {
      for (const val of [ru.in_call, ru.out_call]) {
        if (!val) continue;
        const num = parseFloat(val.replace(/[^0-9.]/g, ""));
        if (!isNaN(num) && num > 0 && num < min) min = num;
      }
    }
    return min === Infinity ? null : min;
  })();

  const flag = countryFlag(escort.country?.name);
  const avatarCandidates = escort.avatarMediaUrls?.length
    ? escort.avatarMediaUrls
    : escort.profile_photo
      ? [avatarUrl(escort.profile_photo, escort.id_aw)]
      : [];

  return (
    <Link
      href={href}
      className="group relative block overflow-hidden rounded-xl bg-surface shadow-md transition-all duration-300 hover:shadow-xl hover:shadow-primary/10 hover:-translate-y-1"
    >
      {/* Photo */}
      <div className={`aspect-[3/4] relative overflow-hidden bg-surface-light ${isAvailable ? "ring-2 ring-green-400 ring-offset-1 ring-offset-surface rounded-xl animate-[pulse-glow_2s_ease-in-out_infinite]" : ""}`}>
        {/* C.2: next/image gives WebP/AVIF + responsive srcset on the most-
            loaded image in the entire app. The card aspect-[3/4] wrapper is
            already `relative`; `fill` + `sizes` lets Next pick the right
            resolution per breakpoint (cuts payload ~60% on listing pages).
            MediaImage falls through to the next candidate URL on 404 —
            R2 conversions aren't guaranteed to exist even when Spatie's
            metadata claims they were generated. */}
        <MediaImage
          srcs={avatarCandidates}
          alt={`${escort.username ?? "Escort"}${escort.city?.name ? ` in ${escort.city.name}` : ""} profile photo`}
          fill
          sizes="(max-width:640px) 50vw, (max-width:1024px) 33vw, 25vw"
          loading="lazy"
          className="object-cover transition-transform duration-500 group-hover:scale-105"
          fallback={
            <div className="flex h-full w-full items-center justify-center text-text-muted">
              <svg
                className="h-16 w-16 opacity-30"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={1.5}
                  d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
                />
              </svg>
            </div>
          }
        />

        {/* Gradient overlay */}
        <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-transparent" />

        {/* Photo count badge — bottom-left of photo */}
        {photoCount > 0 && (
          <span className="absolute bottom-12 left-2.5 z-10 inline-flex items-center gap-1 bg-black/50 backdrop-blur-sm text-white/90 text-[10px] font-medium px-1.5 py-0.5 rounded-md">
            <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" />
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 13a3 3 0 11-6 0 3 3 0 016 0z" />
            </svg>
            {photoCount}
          </span>
        )}

        {/* Online status indicator — client-side check; server snapshot would
            drift on ISR pages. */}
        <OnlineDot lastOnlineAt={escort.lastonline_at} />

        {/* Heart + Compare buttons. The heart is now an interactive button
            (was an inert <span> with no aria-label) that calls the favorites
            API and stops link propagation so the click doesn't also navigate
            to the profile. */}
        {/* On hover-capable devices (desktop), buttons fade in on group-hover.
            On touch devices (no hover), they stay visible — earlier the
            md:opacity-0 + md:group-hover:opacity-100 made the heart and
            compare button unreachable on iPad and other touch tablets. */}
        <div className="absolute top-2.5 right-2.5 flex flex-col gap-1.5 opacity-100 [@media(hover:hover)]:md:opacity-0 [@media(hover:hover)]:md:group-hover:opacity-100 transition-opacity duration-200">
          <HeartFavoriteButton userId={escort.id} />
          <CompareAddButton escort={{ id: escort.id, id_aw: escort.id_aw, username: escort.username }} />
        </div>

        {/* Badges top-left — NewBadge is client-side; static badges stay SSR. */}
        <div className="absolute top-2.5 left-2.5 flex items-center gap-1">
          <VerifiedBadge verified={escort.is_verified} vip={escort.is_vip} size="sm" />
        </div>
        <NewBadge createdAt={escort.created_at} />

        {/* Bottom info overlay */}
        <div className="absolute bottom-0 left-0 right-0 p-3 space-y-1">
          <div className="flex items-center gap-1.5">
            <h3 className="text-sm font-semibold text-white truncate">
              {escort.username ?? "Anonymous"}
            </h3>
            <VerifiedBadge verified={escort.is_verified} vip={false} size="sm" />
          </div>
          {(escort.city || escort.country) && (
            <p className="text-xs text-white/70 truncate">
              {flag && <span className="mr-0.5">{flag}</span>}
              {escort.city?.name}
              {escort.city && escort.country ? ", " : ""}
              {escort.country?.name}
            </p>
          )}
          <div className="flex items-center gap-1.5 flex-wrap">
            <AvailabilityPill
              available={isAvailable}
              lastOnline={escort.lastonline_at}
            />
            <span className={`inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px] font-medium ${
              escort.is_agency
                ? "bg-blue-500/20 text-blue-300"
                : "bg-emerald-500/20 text-emerald-300"
            }`}>
              {escort.is_agency ? "Agency" : "Independent"}
            </span>
          </div>
          {isAvailable && (
            <span className="inline-flex items-center gap-1 mt-1 px-2 py-0.5 rounded-full bg-green-500/20 border border-green-400/30 text-green-400 text-[10px] font-semibold uppercase tracking-wide">
              <span className="w-1.5 h-1.5 rounded-full bg-green-400 animate-pulse" />
              Available Now
            </span>
          )}
          {minRate !== null && (
            <p className="text-[10px] text-white/60 font-medium mt-0.5">
              From &euro;{Math.round(minRate)}/hr
            </p>
          )}
        </div>
      </div>
    </Link>
  );
}
