import { trpc } from "@/providers/trpc";
import { CheckCircle2 } from "lucide-react";

const FLAG_MAP: Record<string, string> = {
  "USA": "🇺🇸", "UK": "🇬🇧", "India": "🇮🇳", "Germany": "🇩🇪",
  "Australia": "🇦🇺", "Canada": "🇨🇦", "France": "🇫🇷", "Japan": "🇯🇵",
  "UAE": "🇦🇪", "Singapore": "🇸🇬", "Brazil": "🇧🇷", "Egypt": "🇪🇬",
  "Thailand": "🇹🇭", "South Korea": "🇰🇷", "Turkey": "🇹🇷",
  "Indonesia": "🇮🇩", "Hong Kong": "🇭🇰", "Sweden": "🇸🇪",
  "Netherlands": "🇳🇱", "Mexico": "🇲🇽",
};

function getFlag(location: string | null): string {
  if (!location) return "🌍";
  for (const [country, flag] of Object.entries(FLAG_MAP)) {
    if (location.includes(country)) return flag;
  }
  return "🌍";
}

export function ProductMarquee() {
  const { data: sales } = trpc.activity.getRecentSales.useQuery({ limit: 20 });

  const items = (sales || []).map((s) => ({
    name: s.customerName || "Customer",
    location: s.location || "Global",
    product: s.productName || "Premium Subscription",
  }));

  if (items.length === 0) return null;

  const doubled = [...items, ...items];

  return (
    <section className="py-10 overflow-hidden border-y border-white/5">
      <div className="relative">
        <div
          className="flex gap-8 animate-marquee whitespace-nowrap"
          style={{ width: "max-content" }}
        >
          {doubled.map((item, i) => (
            <div
              key={i}
              className="flex items-center gap-3 px-4 py-2 glass-card flex-shrink-0"
            >
              <CheckCircle2 className="w-4 h-4 text-green-400 flex-shrink-0" />
              <span className="text-sm">
                <span className="font-medium">{item.name}</span>
                <span className="text-slate-400"> from </span>
                <span>{getFlag(item.location)} {item.location}</span>
                <span className="text-slate-400"> purchased </span>
                <span className="text-[#f97316] font-medium">{item.product}</span>
              </span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}
