"use client";

import { useState, useEffect } from "react";
import { motion } from "framer-motion";
import Link from "next/link";
import { Flame, ChevronRight } from "lucide-react";
import { fetchGamesClient, type GameItem } from "@/lib/api";

// Developer/publisher mapping for popular games
const PUBLISHERS: Record<string, string> = {
  "Mobile Legends B": "Moonton",
  "Mobile Legends A": "Moonton",
  "Mobile Legends (Global)": "Moonton",
  "Free Fire": "Garena",
  "Free Fire Max": "Garena",
  "Genshin Impact": "HoYoverse",
  "Honkai Star Rail": "HoYoverse",
  "Honkai: Star Rail": "HoYoverse",
  "Honkai Impact 3": "HoYoverse",
  "Zenless Zone Zero": "HoYoverse",
  "Valorant": "Riot Games",
  "League of Legends": "Riot Games",
  "Honor of Kings Global": "TiMi Studio",
  "PUBG Mobile (ID)": "Tencent Games",
  "PUBGM INDO A": "Tencent Games",
  "PUBG Mobile (GLOBAL)": "Tencent Games",
  "Call of Duty Mobile": "Activision",
  "One Punch Man": "FingerFun",
  "Roblox Via Login": "Roblox Corp",
  "Tower of Fantasy": "Hotta Studio",
  "Marvel Rivals": "NetEase",
  "Blood Strike": "NetEase",
  "Point Blank (ID)": "Zepetto",
  "Voucher PSN": "Sony",
  "Steam Wallet Code": "Valve",
  "Revelation Infinite Journey": "NetEase",
};

export default function TrendingSection() {
  const [games, setGames] = useState<GameItem[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchGamesClient()
      .then((data) => {
        const sorted = data.sort((a, b) => b.product_count - a.product_count).slice(0, 9);
        setGames(sorted);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  return (
    <section className="mt-10 md:mt-14">
      <div className="flex items-center justify-between mb-5">
        <div className="flex items-center gap-2.5">
          <div className="w-8 h-8 rounded-lg bg-red-500/20 flex items-center justify-center">
            <Flame className="text-red-500" size={18} />
          </div>
          <div>
            <h2 className="font-heading text-lg md:text-xl font-bold text-white uppercase tracking-wide">Trending</h2>
            <p className="text-[11px] text-muted">Berikut adalah beberapa produk yang paling populer saat ini.</p>
          </div>
        </div>
        <Link href="#products" className="text-xs text-primary hover:text-primary-hover font-medium flex items-center gap-1 transition-colors">
          Lihat Semua <ChevronRight size={14} />
        </Link>
      </div>

      {loading ? (
        <div className="grid grid-cols-2 md:grid-cols-3 gap-2 sm:gap-3">
          {Array.from({ length: 10 }).map((_, i) => (
            <div key={i} className="flex items-center gap-2 sm:gap-3 p-2 sm:p-3 rounded-xl bg-dark-surface border border-dark-border animate-pulse">
              <div className="w-10 h-10 sm:w-14 sm:h-14 rounded-lg sm:rounded-xl bg-dark-surface2 shrink-0" />
              <div className="space-y-1.5 sm:space-y-2 flex-1 min-w-0">
                <div className="h-2.5 sm:h-3 bg-dark-surface2 rounded w-3/4" />
                <div className="h-1.5 sm:h-2 bg-dark-surface2 rounded w-1/2" />
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="grid grid-cols-2 md:grid-cols-3 gap-2 sm:gap-3">
          {games.map((game, i) => (
            <motion.div
              key={game.slug}
              initial={{ opacity: 0, y: 15 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: i * 0.05, duration: 0.3 }}
            >
              <Link
                href={`/${game.slug}`}
                className="group flex items-center gap-2 sm:gap-3 p-2 sm:p-3 rounded-xl bg-dark-surface border border-dark-border hover:border-primary/40 transition-all duration-300 hover:shadow-glow-sm relative overflow-hidden"
              >
                {/* Dot pattern bg */}
                <div className="absolute inset-0 bg-[radial-gradient(circle_at_1px_1px,rgba(255,255,255,0.03)_1px,transparent_0)] bg-[length:16px_16px] pointer-events-none" />

                {/* Game Icon */}
                <div className="relative w-10 h-10 sm:w-14 sm:h-14 rounded-lg sm:rounded-xl overflow-hidden bg-dark-surface2 shrink-0 ring-1 ring-white/5 group-hover:ring-primary/30 transition-all">
                  <img
                    src={game.icon}
                    alt={game.name}
                    className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500"
                    loading="lazy"
                    onError={(e) => { (e.target as HTMLImageElement).style.display = "none"; }}
                  />
                </div>

                {/* Info */}
                <div className="flex-1 min-w-0 relative z-10">
                  <h3 className="text-[10px] sm:text-sm font-bold text-white truncate group-hover:text-primary transition-colors">
                    {game.name}
                  </h3>
                  <p className="text-[8px] sm:text-[11px] text-muted truncate mt-0.5 sm:mt-0">
                    {PUBLISHERS[game.name] || "Publisher"}
                  </p>
                </div>
              </Link>
            </motion.div>
          ))}
        </div>
      )}
    </section>
  );
}
