import {
  parseSponsorshipSignals,
  SPONSORSHIP_GREEN_FLAG_IDS,
  SPONSORSHIP_RED_FLAG_IDS,
  SPONSORSHIP_SIGNAL_META,
  SPONSORSHIP_YELLOW_FLAG_IDS,
  type SponsorshipFlagTier,
} from "@shared/sponsorship-signals";
import type React from "react";
import { Badge } from "@/components/ui/badge";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";

const flagTierClass: Record<SponsorshipFlagTier, string> = {
  green: "border-emerald-500/30 bg-emerald-500/10 text-emerald-200",
  yellow: "border-amber-500/40 bg-amber-500/10 text-amber-200",
  red: "border-rose-500/40 bg-rose-500/10 text-rose-200",
};

interface SponsorshipSignalsPillsProps {
  sponsorshipSignals: string | null | undefined;
  className?: string;
  size?: "xs" | "sm";
}

export const SponsorshipSignalsPills: React.FC<
  SponsorshipSignalsPillsProps
> = ({ sponsorshipSignals, className, size = "sm" }) => {
  const signals = parseSponsorshipSignals(sponsorshipSignals);
  if (signals.length === 0) return null;

  const ordered = [
    ...SPONSORSHIP_RED_FLAG_IDS.filter((id) => signals.includes(id)),
    ...SPONSORSHIP_YELLOW_FLAG_IDS.filter((id) => signals.includes(id)),
    ...SPONSORSHIP_GREEN_FLAG_IDS.filter((id) => signals.includes(id)),
  ];

  return (
    <TooltipProvider>
      <div className={cn("flex flex-wrap items-center gap-1", className)}>
        {ordered.map((signal) => {
          const meta = SPONSORSHIP_SIGNAL_META[signal];
          return (
            <Tooltip key={signal} delayDuration={0}>
              <TooltipTrigger asChild>
                <Badge
                  variant="outline"
                  className={cn(
                    "font-medium",
                    size === "xs" ? "px-1 py-0 text-[10px]" : "text-xs",
                    flagTierClass[meta.flagTier],
                  )}
                >
                  {meta.shortLabel}
                </Badge>
              </TooltipTrigger>
              <TooltipContent side="top" className="max-w-xs">
                <p className="text-xs font-medium">{meta.label}</p>
                <p className="text-xs text-muted-foreground">
                  {meta.description}
                </p>
              </TooltipContent>
            </Tooltip>
          );
        })}
      </div>
    </TooltipProvider>
  );
};
