"use client";

import { cn } from "@/lib/utils";
import { useTranslation } from "react-i18next";

/** Optional fixed px size; default follows parent text (1em). */
export const VERIFICATION_BADGE_SIZE = 14;

export const VERIFICATION_COLORS = {
  gray: "#636360",
  blue: "#002FC6",
  green: "#06CC00",
  gold: "#EDCB00",
} as const;

export type VerifyBadgeTier = "none" | "gray" | "blue" | "green" | "gold";

type VerificationBadgeProps = {
  verifyBadge?: VerifyBadgeTier | string | null;
  className?: string;
  size?: number;
};

export function resolveVerificationStatus(
  verifyBadge?: string | null
): VerifyBadgeTier | null {
  if (
    !verifyBadge ||
    verifyBadge === "none" ||
    !(verifyBadge in VERIFICATION_COLORS)
  ) {
    return null;
  }
  return verifyBadge as VerifyBadgeTier;
}

const VERIFICATION_ICON_SRC: Record<Exclude<VerifyBadgeTier, "none">, string> = {
  gray: "/images/icons/verify-gray.svg",
  blue: "/images/icons/verify-blue.svg",
  green: "/images/icons/verify-green.svg",
  gold: "/images/icons/verify-gold.svg",
};

export function getVerificationIcon(
  verifyBadge?: string | null,
  labels?: {
    grayAlt: string;
    blueAlt: string;
    greenAlt: string;
    goldAlt: string;
  }
): { src: string; alt: string } | null {
  const status = resolveVerificationStatus(verifyBadge);
  if (!status || status === "none") return null;

  const altByTier: Record<Exclude<VerifyBadgeTier, "none">, string> = {
    gray: labels?.grayAlt ?? "Pending verification",
    blue: labels?.blueAlt ?? "Verified badge",
    green: labels?.greenAlt ?? "License badge",
    gold: labels?.goldAlt ?? "Gold badge",
  };

  return { src: VERIFICATION_ICON_SRC[status], alt: altByTier[status] };
}

function VerificationBadge({
  verifyBadge,
  className,
  size,
}: VerificationBadgeProps) {
  const { t } = useTranslation("common");
  const icon = getVerificationIcon(verifyBadge, {
    grayAlt: t("verificationBadge.pendingAlt"),
    blueAlt: t("verificationBadge.verifiedAlt"),
    greenAlt: t("verificationBadge.licenseAlt"),
    goldAlt: t("verificationBadge.goldAlt", "Gold badge"),
  });
  if (!icon) return null;

  return (
    // eslint-disable-next-line @next/next/no-img-element
    <img
      src={icon.src}
      alt={icon.alt}
      title={icon.alt}
      className={cn(
        "inline-block shrink-0 object-contain align-middle",
        size == null && "h-[1em] w-[1em]",
        className
      )}
      style={size != null ? { width: size, height: size } : undefined}
    />
  );
}

export default VerificationBadge;
