"use client";

import { Badge } from "@/presentation/components/ui/badge";
import { cn } from "@/shared/lib/utils";

/**
 * Semantic color keys returned by the backend (same convention as
 * {@link AccessStatus}), mapped to Tailwind classes. The backend may instead
 * send a hex string (e.g. "#F7BC58"), which is rendered inline — so this badge
 * works regardless of which color convention the endpoint uses.
 */
const SEMANTIC: Record<string, string> = {
  success: "bg-emerald-100 text-emerald-800 border-emerald-200 dark:bg-emerald-950/40 dark:text-emerald-300",
  green: "bg-emerald-100 text-emerald-800 border-emerald-200 dark:bg-emerald-950/40 dark:text-emerald-300",
  warning: "bg-amber-100 text-amber-800 border-amber-200 dark:bg-amber-950/40 dark:text-amber-300",
  amber: "bg-amber-100 text-amber-800 border-amber-200 dark:bg-amber-950/40 dark:text-amber-300",
  failure: "bg-red-100 text-red-800 border-red-200 dark:bg-red-950/40 dark:text-red-300",
  danger: "bg-red-100 text-red-800 border-red-200 dark:bg-red-950/40 dark:text-red-300",
  red: "bg-red-100 text-red-800 border-red-200 dark:bg-red-950/40 dark:text-red-300",
  info: "bg-blue-100 text-blue-800 border-blue-200 dark:bg-blue-950/40 dark:text-blue-300",
  blue: "bg-blue-100 text-blue-800 border-blue-200 dark:bg-blue-950/40 dark:text-blue-300",
  indigo: "bg-indigo-100 text-indigo-800 border-indigo-200 dark:bg-indigo-950/40 dark:text-indigo-300",
  purple: "bg-purple-100 text-purple-800 border-purple-200 dark:bg-purple-950/40 dark:text-purple-300",
  neutral: "bg-gray-100 text-gray-700 border-gray-200 dark:bg-gray-800/40 dark:text-gray-300",
  gray: "bg-gray-100 text-gray-700 border-gray-200 dark:bg-gray-800/40 dark:text-gray-300",
};

const FALLBACK = "bg-gray-100 text-gray-700 border-gray-200 dark:bg-gray-800/40 dark:text-gray-300";

interface AntaiBadgeProps {
  label?: string | null;
  color?: string | null;
  icon?: React.ComponentType<{ className?: string }>;
  className?: string;
}

/** Label + color status pill. Tolerates a missing label (renders an em dash). */
export function AntaiBadge({ label, color, icon: Icon, className }: AntaiBadgeProps) {
  if (!label) {
    return <span className="text-muted-foreground text-xs">{"—"}</span>;
  }
  const isHex = typeof color === "string" && color.startsWith("#");
  const semantic = color ? SEMANTIC[color.toLowerCase()] : undefined;
  return (
    <Badge
      variant="outline"
      className={cn("text-xs font-medium gap-1", !isHex && (semantic ?? FALLBACK), className)}
      style={
        isHex
          ? { backgroundColor: `${color}1A`, color: color as string, borderColor: `${color}33` }
          : undefined
      }
    >
      {Icon && <Icon className="w-3 h-3 shrink-0" />}
      {label}
    </Badge>
  );
}
