"use client";

import { useState } from "react";
import { Sparkles, ExternalLink, BadgeCheck, Send, Megaphone } from "lucide-react";
import { motion } from "framer-motion";

export interface InFeedAd {
  id: string;
  name: string;             // Nom interne de la campagne
  title: string;            // Titre affiché sous la vignette
  description?: string;     // Description / sous-titre
  sponsorBadge?: string;    // Badge en haut à gauche (ex: "Sponsorisé", "Partenaire", "Exclusif")
  badgeColor?: string;      // "purple" | "blue" | "crimson" | "pink" | "green" | "amber"
  imageUrl: string;         // Bannière 16:9 (URL ou uploadée)
  linkUrl: string;          // Lien de destination
  ctaText?: string;         // Texte du bouton d'action (ex: "Rejoindre", "Découvrir")
  position: number;         // Numéro du slot dans la grille (1-indexed, ex: 5 = Ligne 2, Vidéo 2)
  row?: number;             // Numéro de ligne (aide au calcul)
  col?: number;             // Numéro de colonne (aide au calcul)
  active: boolean;          // Afficher ou masquer
  openInNewTab?: boolean;   // Ouvrir dans un nouvel onglet
}

const BADGE_COLORS: Record<string, { gradient: string; text: string; shadow: string }> = {
  purple: {
    gradient: "from-[#7b2cbf] to-[#9d4edd]",
    text: "text-white",
    shadow: "rgba(123,44,191,0.5)"
  },
  blue: {
    gradient: "from-[#0284c7] to-[#38bdf8]",
    text: "text-white",
    shadow: "rgba(2,132,199,0.5)"
  },
  crimson: {
    gradient: "from-[#be123c] to-[#f43f5e]",
    text: "text-white",
    shadow: "rgba(190,18,60,0.5)"
  },
  pink: {
    gradient: "from-[#db2777] to-[#f472b6]",
    text: "text-white",
    shadow: "rgba(219,39,119,0.5)"
  },
  green: {
    gradient: "from-[#059669] to-[#34d399]",
    text: "text-white",
    shadow: "rgba(5,150,105,0.5)"
  },
  amber: {
    gradient: "from-[#d97706] to-[#fbbf24]",
    text: "text-black font-black",
    shadow: "rgba(217,119,6,0.5)"
  }
};

interface CustomInFeedAdCardProps {
  ad: InFeedAd;
}

export function CustomInFeedAdCard({ ad }: CustomInFeedAdCardProps) {
  const [imgError, setImgError] = useState(false);
  const colorConf = BADGE_COLORS[ad.badgeColor || "purple"] || BADGE_COLORS.purple;

  const isTelegram = ad.linkUrl?.toLowerCase().includes("t.me") || 
                     ad.title?.toLowerCase().includes("telegram") ||
                     ad.name?.toLowerCase().includes("telegram");

  return (
    <motion.div
      className="relative w-full group select-none"
      whileHover={{ scale: 1.02 }}
      transition={{ duration: 0.2, ease: "easeOut" }}
    >
      <a
        href={ad.linkUrl || "#"}
        target={ad.openInNewTab !== false ? "_blank" : "_self"}
        rel="noopener noreferrer"
        className="block relative cursor-pointer"
      >
        {/* 📌 Format Vignette 16:9 identique aux VideoCards */}
        <div
          style={{ borderRadius: "var(--custom-video-radius, 18px)" }}
          className="relative aspect-video overflow-hidden mb-2.5 border border-white/10 group-hover:border-[#7b2cbf] transition-all duration-300 shadow-lg bg-[#0d0915] flex items-center justify-center group-hover:shadow-[0_0_25px_rgba(123,44,191,0.3)]"
        >
          {/* Image Bannière */}
          {!imgError && ad.imageUrl ? (
            <img
              src={ad.imageUrl}
              alt={ad.title || ad.name}
              onError={() => setImgError(true)}
              className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500 ease-out"
              draggable={false}
            />
          ) : (
            <div className="w-full h-full bg-gradient-to-br from-[#1a0f2e] via-[#241344] to-[#0c0617] flex flex-col items-center justify-center p-4 text-center">
              <Megaphone size={36} className="text-[#b57bee] mb-2 opacity-80" />
              <p className="text-xs font-black text-white/90 line-clamp-2">{ad.title || ad.name}</p>
            </div>
          )}

          {/* Calque d'assombrissement doux au survol */}
          <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/20 to-transparent opacity-60 group-hover:opacity-80 transition-opacity duration-300" />

          {/* Badge Sponsorisé en haut à gauche */}
          <div
            className={`absolute top-2.5 left-2.5 z-20 bg-gradient-to-r ${colorConf.gradient} ${colorConf.text} text-[9px] font-black uppercase px-2 py-0.5 rounded-md shadow`}
            style={{ boxShadow: `0 0 10px ${colorConf.shadow}` }}
          >
            {ad.sponsorBadge || "Sponsorisé"}
          </div>

          {/* Badge AD en haut à droite */}
          <div className="absolute top-2.5 right-2.5 z-20 bg-black/80 backdrop-blur-md border border-white/15 text-amber-300 text-[10px] font-black px-1.5 py-0.5 rounded flex items-center gap-1 shadow">
            <Sparkles size={10} className="text-amber-400" />
            <span>AD</span>
          </div>

          {/* Bouton CTA centré avec animation hover */}
          <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all duration-300 transform scale-95 group-hover:scale-100">
            <div
              className="px-4 py-2 rounded-full font-black text-xs text-white flex items-center gap-1.5 shadow-2xl transition-all"
              style={{
                background: "linear-gradient(135deg, #7b2cbf 0%, #9d4edd 100%)",
                boxShadow: "0 0 20px rgba(123,44,191,0.8), 0 0 40px rgba(157,78,221,0.4)"
              }}
            >
              {isTelegram ? <Send size={13} className="text-white" /> : <ExternalLink size={13} className="text-white" />}
              <span>{ad.ctaText || "Rejoindre"}</span>
            </div>
          </div>
        </div>

        {/* 📌 Métadonnées sous la vignette (Identique au layout VideoCard) */}
        <div className="flex gap-2.5 px-0.5 items-start">
          {/* Avatar / Icône sponsor */}
          <div className="relative flex-shrink-0 mt-0.5">
            <div
              className="w-8 h-8 rounded-full border border-[#7b2cbf]/50 group-hover:border-[#9d4edd] group-hover:shadow-[0_0_10px_rgba(123,44,191,0.6)] transition-all duration-300 overflow-hidden flex items-center justify-center"
              style={{ background: isTelegram ? "linear-gradient(135deg, #0088cc, #229ed9)" : "linear-gradient(135deg, #3c096c, #7b2cbf)" }}
            >
              {isTelegram ? (
                <Send size={15} className="text-white ml-0.5" />
              ) : (
                <Sparkles size={15} className="text-amber-300" />
              )}
            </div>
          </div>

          {/* Titre & Description */}
          <div className="flex-1 min-w-0">
            <h3
              style={{ fontSize: "var(--custom-video-title-size, 13px)" }}
              className="font-extrabold leading-snug line-clamp-1 text-white group-hover:text-[#b57bee] transition-colors duration-200"
            >
              {ad.title || ad.name}
            </h3>

            <div
              style={{ fontSize: "var(--custom-video-meta-size, 11px)" }}
              className="flex items-center gap-1.5 font-bold mt-0.5 leading-none"
            >
              <span className="text-[#d4b09a] truncate max-w-[130px] group-hover:text-[#b57bee] transition-colors">
                {ad.name || "Partenaire Officiel"}
              </span>
              <BadgeCheck size={12} className="text-[#9d4edd] flex-shrink-0" />
              <span className="text-[#5f5f7a]">·</span>
              <span className="text-[#8a6a55] truncate max-w-[150px]">
                {ad.description || "Recommandé"}
              </span>
            </div>
          </div>

          {/* Icône externe à droite */}
          <div className="flex-shrink-0 text-[#8a6a55] group-hover:text-[#b57bee] p-1 transition-colors duration-200">
            <ExternalLink size={15} />
          </div>
        </div>
      </a>
    </motion.div>
  );
}
