"use client";

import { useState, useEffect, useRef } from "react";
import { 
  Sparkles, 
  Save, 
  Send, 
  MessageCircle, 
  Flame, 
  Bell, 
  Crown, 
  Globe, 
  Upload, 
  Image as ImageIcon, 
  Trash2, 
  ExternalLink, 
  Eye, 
  RefreshCw,
  CheckCircle2,
  Sliders
} from "lucide-react";
import { toast } from "@/components/ui/Toaster";
import { HeroCardConfig } from "@/components/PromoHeroCards";

// Official Discord Logo SVG
function DiscordLogo({ className = "w-4 h-4" }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 127.14 96.36" fill="currentColor">
      <path d="M107.7,8.07A105.15,105.15,0,0,0,81.47,0a72.06,72.06,0,0,0-3.36,6.83A97.68,97.68,0,0,0,49,6.83,72.37,72.37,0,0,0,45.64,0,105.89,105.89,0,0,0,19.39,8.09C2.79,32.65-1.71,56.6.54,80.21h0A105.73,105.73,0,0,0,32.71,96.36,77.7,77.7,0,0,0,39.6,85.25a68.42,68.42,0,0,1-10.85-5.18c.91-.66,1.8-1.34,2.66-2a75.57,75.57,0,0,0,64.32,0c.87.71,1.76,1.39,2.66,2a68.68,68.68,0,0,1-10.87,5.19,77,77,0,0,0,6.89,11.1,105.25,105.25,0,0,0,32.19-16.14c2.64-27.38-4.51-51.11-18.91-72.15ZM42.45,65.69C36.18,65.69,31,60,31,53s5-12.74,11.43-12.74S54,45.92,53.87,53,48.74,65.69,42.45,65.69Zm42.24,0C78.41,65.69,73.25,60,73.25,53s5-12.74,11.44-12.74S96.23,45.92,96.1,53,91,65.69,84.69,65.69Z"/>
    </svg>
  );
}

const COLOR_PRESETS = [
  { id: "crimson", name: "Rouge MTBR", hex: "#e05a68", bg: "bg-[#e05a68]/20", border: "border-[#e05a68]/50", text: "text-[#f08592]" },
  { id: "blue", name: "Bleu Telegram", hex: "#2AABEE", bg: "bg-[#2AABEE]/20", border: "border-[#2AABEE]/50", text: "text-[#7dd3fc]" },
  { id: "pink", name: "Rose Bonbon", hex: "#ec4899", bg: "bg-pink-500/20", border: "border-pink-500/50", text: "text-pink-300" },
  { id: "discord", name: "Violet Discord", hex: "#5865F2", bg: "bg-[#5865F2]/20", border: "border-[#5865F2]/50", text: "text-[#a5b4fc]" },
  { id: "green", name: "Vert Émeraude", hex: "#10b981", bg: "bg-emerald-500/20", border: "border-emerald-500/50", text: "text-emerald-300" },
  { id: "amber", name: "Or / Ambre", hex: "#f59e0b", bg: "bg-amber-500/20", border: "border-amber-500/50", text: "text-amber-300" }
];

const ICON_PRESETS = [
  { id: "telegram", name: "Telegram", icon: Send },
  { id: "discord", name: "Discord", icon: DiscordLogo },
  { id: "chat", name: "Chat / Message", icon: MessageCircle },
  { id: "fire", name: "Flamme", icon: Flame },
  { id: "star", name: "Étoile", icon: Sparkles },
  { id: "bell", name: "Cloche", icon: Bell },
  { id: "crown", name: "Couronne", icon: Crown },
  { id: "globe", name: "Globe", icon: Globe }
];

interface HeroCardsEditorProps {
  themeColor?: string;
  onSaved?: () => void;
}

export function HeroCardsEditor({ themeColor = "#e05a68", onSaved }: HeroCardsEditorProps) {
  const [cards, setCards] = useState<HeroCardConfig[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [activeTab, setActiveTab] = useState<number>(0);
  const [uploadingIdx, setUploadingIdx] = useState<number | null>(null);
  const fileInputRefs = useRef<(HTMLInputElement | null)[]>([]);

  const fetchCards = async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/admin/hero-cards");
      const data = await res.json();
      if (data?.cards && Array.isArray(data.cards)) {
        setCards(data.cards);
      }
    } catch {
      toast("Erreur de chargement des pancartes", "error");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchCards();
  }, []);

  const updateCard = (index: number, field: keyof HeroCardConfig, value: any) => {
    setCards(prev => {
      const next = [...prev];
      if (next[index]) {
        next[index] = { ...next[index], [field]: value };
      }
      return next;
    });
  };

  const handleFileUpload = async (index: number, file: File) => {
    if (!file) return;
    setUploadingIdx(index);
    try {
      const formData = new FormData();
      formData.append("file", file);
      formData.append("type", "image");

      let res = await fetch("/api/upload", {
        method: "POST",
        body: formData
      });
      if (!res.ok) {
        res = await fetch("/api/admin/infeed-ads/upload", {
          method: "POST",
          body: formData
        });
      }
      const data = await res.json();
      if (res.ok && data?.url) {
        updateCard(index, "imageUrl", data.url);
        toast("Image de fond uploadée avec succès !", "success");
      } else {
        toast(data?.error || "Erreur lors de l'upload", "error");
      }
    } catch (e: any) {
      toast("Erreur d'upload: " + e.message, "error");
    } finally {
      setUploadingIdx(null);
    }
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      const res = await fetch("/api/admin/hero-cards", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ cards })
      });
      const data = await res.json();
      if (res.ok && data?.success) {
        toast("Les 3 pancartes d'accueil ont été enregistrées avec succès !", "success");
        if (onSaved) onSaved();
      } else {
        toast(data?.error || "Erreur lors de la sauvegarde", "error");
      }
    } catch (e: any) {
      toast("Erreur réseau: " + e.message, "error");
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="p-8 text-center text-white/50 flex items-center justify-center gap-2">
        <RefreshCw className="animate-spin" size={18} />
        <span>Chargement des 3 pancartes...</span>
      </div>
    );
  }

  const currentCard = cards[activeTab] || cards[0];

  return (
    <div className="bg-[#12080b] border border-[#2e1217] rounded-3xl p-6 md:p-8 shadow-2xl space-y-6">
      
      {/* 📌 Header */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 pb-6 border-b border-white/10">
        <div>
          <div className="flex items-center gap-2 mb-1">
            <Sparkles style={{ color: themeColor }} size={22} />
            <h2 className="text-xl sm:text-2xl font-black text-white">
              Les 3 Pancartes d'Accueil MTBR (100% Modifiables)
            </h2>
          </div>
          <p className="text-xs sm:text-sm text-white/70">
            Personnalisez librement les 3 bannières en haut du flux : textes, badges, icônes, liens, images de fond et styles.
          </p>
        </div>

        <button
          type="button"
          onClick={handleSave}
          disabled={saving}
          style={{
            backgroundColor: themeColor,
            boxShadow: `0 0 25px ${themeColor}66`
          }}
          className="flex items-center justify-center gap-2 px-6 py-3.5 rounded-2xl text-white font-black text-xs sm:text-sm hover:scale-105 active:scale-95 transition-all cursor-pointer disabled:opacity-50 self-start md:self-auto shrink-0"
        >
          {saving ? <RefreshCw size={18} className="animate-spin" /> : <Save size={18} />}
          <span>{saving ? "Enregistrement..." : "💾 Sauvegarder les 3 Pancartes"}</span>
        </button>
      </div>

      {/* 📌 Tabs: Pancarte #1, Pancarte #2, Pancarte #3 */}
      <div className="flex flex-wrap gap-2.5 p-1.5 bg-[#070406] rounded-2xl border border-white/10">
        {cards.map((c, i) => (
          <button
            key={c.id || i}
            type="button"
            onClick={() => setActiveTab(i)}
            className={`flex-1 min-w-[120px] py-2.5 px-4 rounded-xl text-xs sm:text-sm font-black transition-all flex items-center justify-center gap-2 cursor-pointer ${
              activeTab === i
                ? "bg-[#e05a68] text-white shadow-lg scale-[1.02]"
                : "text-white/60 hover:text-white hover:bg-white/5"
            }`}
          >
            <span>Pancarte #{i + 1}</span>
            <span className="text-[10px] opacity-75 truncate max-w-[100px]">({c.badge || "Hero"})</span>
            {c.enabled !== false ? (
              <span className="w-2 h-2 rounded-full bg-emerald-500 shrink-0" title="Visible" />
            ) : (
              <span className="w-2 h-2 rounded-full bg-red-500 shrink-0" title="Masquée" />
            )}
          </button>
        ))}
      </div>

      {/* 📌 Live Preview de la carte active */}
      {currentCard && (
        <div className="space-y-3">
          <div className="flex items-center justify-between text-xs font-bold text-white/60">
            <span className="flex items-center gap-1.5">
              <Eye size={14} />
              <span>Aperçu en Direct sur MTBR (Pancarte #{activeTab + 1})</span>
            </span>
            <span className="text-[11px] font-mono text-white/40">Mise à jour instantanée</span>
          </div>

          <div className="p-3 bg-black/60 rounded-2xl border border-white/5 max-w-xl">
            <div
              style={{
                minHeight: currentCard.height === "compact" ? "125px" : currentCard.height === "large" ? "180px" : currentCard.height === "xlarge" ? "220px" : "150px",
                borderRadius: "16px"
              }}
              className="relative overflow-hidden bg-[#181126] border border-[#2e1217] p-4 flex flex-col justify-between shadow-xl"
            >
              {/* Background Image */}
              {currentCard.imageUrl && (
                <>
                  <img
                    src={currentCard.imageUrl}
                    alt={currentCard.title}
                    className="absolute inset-0 w-full h-full object-cover opacity-40"
                  />
                  <div className="absolute inset-0 bg-gradient-to-t from-black/90 via-black/40 to-black/20" />
                </>
              )}

              {/* Top Row: Badge + Flag */}
              <div className="flex items-center justify-between z-10">
                <span
                  style={{
                    backgroundColor: currentCard.badgeColor?.startsWith("#") ? `${currentCard.badgeColor}33` : undefined,
                    borderColor: currentCard.badgeColor?.startsWith("#") ? `${currentCard.badgeColor}88` : undefined,
                    color: currentCard.badgeColor?.startsWith("#") ? currentCard.badgeColor : undefined
                  }}
                  className={`text-[10px] font-black uppercase tracking-wider px-2.5 py-0.5 rounded-full border ${
                    !currentCard.badgeColor?.startsWith("#")
                      ? COLOR_PRESETS.find(p => p.id === currentCard.badgeColor)?.bg || "bg-[#e05a68]/20"
                      : ""
                  } ${
                    !currentCard.badgeColor?.startsWith("#")
                      ? COLOR_PRESETS.find(p => p.id === currentCard.badgeColor)?.border || "border-[#e05a68]/50"
                      : ""
                  } ${
                    !currentCard.badgeColor?.startsWith("#")
                      ? COLOR_PRESETS.find(p => p.id === currentCard.badgeColor)?.text || "text-[#f08592]"
                      : ""
                  }`}
                >
                  {currentCard.badge || "PROMO"}
                </span>
                <span className="text-xs">{currentCard.flag || "🇫🇷"}</span>
              </div>

              {/* Middle Row: Icon + Title + Subtitle */}
              <div className="z-10 my-2">
                <div className="flex items-center gap-2.5 mb-1">
                  <div
                    style={{
                      backgroundColor: currentCard.badgeColor?.startsWith("#") ? currentCard.badgeColor : undefined
                    }}
                    className={`w-6 h-6 rounded-full flex items-center justify-center shrink-0 ${
                      !currentCard.badgeColor?.startsWith("#")
                        ? currentCard.badgeColor === "blue"
                          ? "bg-[#2AABEE] text-black"
                          : currentCard.badgeColor === "pink"
                          ? "bg-pink-500 text-white"
                          : currentCard.badgeColor === "discord"
                          ? "bg-[#5865F2] text-white"
                          : currentCard.badgeColor === "green"
                          ? "bg-emerald-500 text-black"
                          : currentCard.badgeColor === "amber"
                          ? "bg-amber-500 text-black"
                          : "bg-[#e05a68] text-white"
                        : "text-white"
                    }`}
                  >
                    {currentCard.type === "telegram" && <Send size={12} />}
                    {currentCard.type === "discord" && <DiscordLogo className="w-3.5 h-3.5" />}
                    {currentCard.type === "chat" && <MessageCircle size={12} />}
                    {currentCard.type === "fire" && <Flame size={12} />}
                    {currentCard.type === "bell" && <Bell size={12} />}
                    {currentCard.type === "crown" && <Crown size={12} />}
                    {currentCard.type === "globe" && <Globe size={12} />}
                    {(!currentCard.type || currentCard.type === "custom" || currentCard.type === "star") && <Sparkles size={12} />}
                  </div>
                  <h3 className="font-black text-white truncate text-sm">
                    {currentCard.title || "Titre de la pancarte"}
                  </h3>
                </div>
                <p className="text-white/75 font-medium line-clamp-1 text-xs">
                  {currentCard.subtitle || "Sous-titre et description de la pancarte..."}
                </p>
              </div>

              {/* Bottom Row: CTA Button */}
              <div
                style={{
                  color: currentCard.badgeColor?.startsWith("#") ? currentCard.badgeColor : undefined
                }}
                className={`z-10 flex items-center justify-between text-[11px] font-black pt-1.5 border-t border-white/10 ${
                  !currentCard.badgeColor?.startsWith("#")
                    ? currentCard.badgeColor === "blue"
                      ? "text-[#2AABEE]"
                      : currentCard.badgeColor === "pink"
                      ? "text-pink-400"
                      : currentCard.badgeColor === "discord"
                      ? "text-[#818cf8]"
                      : currentCard.badgeColor === "green"
                      ? "text-emerald-400"
                      : currentCard.badgeColor === "amber"
                      ? "text-amber-400"
                      : "text-[#e05a68]"
                    : ""
                }`}
              >
                <span>{currentCard.ctaText || "En savoir plus"}</span>
                <span>➔</span>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 📌 Formulaire d'édition complet de la pancarte sélectionnée */}
      {currentCard && (
        <div className="bg-[#180a0e] border border-[#3b171f] rounded-2xl p-5 md:p-6 space-y-5">
          
          {/* Ligne 1 : Statut activé + Hauteur */}
          <div className="flex flex-wrap items-center justify-between gap-4 pb-4 border-b border-white/10">
            <label className="flex items-center gap-3 cursor-pointer select-none">
              <input
                type="checkbox"
                checked={currentCard.enabled !== false}
                onChange={(e) => updateCard(activeTab, "enabled", e.target.checked)}
                className="w-5 h-5 accent-[#e05a68] rounded cursor-pointer"
              />
              <span className="font-black text-sm text-white">
                {currentCard.enabled !== false ? "✅ Pancarte Activée (Visible sur l'accueil)" : "❌ Pancarte Masquée (Désactivée)"}
              </span>
            </label>

            <div className="flex items-center gap-2">
              <span className="text-xs font-bold text-white/60">Hauteur :</span>
              <select
                value={currentCard.height || "normal"}
                onChange={(e) => updateCard(activeTab, "height", e.target.value)}
                className="bg-[#0b0813] border border-white/10 rounded-xl px-3 py-1.5 text-xs text-white outline-none cursor-pointer"
              >
                <option value="compact">Compacte (125px)</option>
                <option value="normal">Normale (155px)</option>
                <option value="large">Grande (190px)</option>
                <option value="xlarge">Très Grande (230px)</option>
              </select>
            </div>
          </div>

          {/* Ligne 2 : Badge, Couleur, Icône, Drapeau */}
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            
            {/* Badge Text */}
            <div>
              <label className="block text-xs font-bold text-white/70 mb-1.5">
                Texte du Badge (Haut Gauche)
              </label>
              <input
                type="text"
                value={currentCard.badge || ""}
                onChange={(e) => updateCard(activeTab, "badge", e.target.value)}
                placeholder="ex: CANAL OFFICIEL"
                className="w-full bg-[#0b0813] border border-white/10 rounded-xl px-3.5 py-2 text-xs text-white font-bold outline-none focus:border-[#e05a68]"
              />
            </div>

            {/* Couleur du Badge */}
            <div>
              <label className="block text-xs font-bold text-white/70 mb-1.5">
                Couleur du Thème / Badge
              </label>
              <select
                value={COLOR_PRESETS.some(p => p.id === currentCard.badgeColor) ? currentCard.badgeColor : "custom"}
                onChange={(e) => {
                  if (e.target.value !== "custom") {
                    updateCard(activeTab, "badgeColor", e.target.value);
                  }
                }}
                className="w-full bg-[#0b0813] border border-white/10 rounded-xl px-3.5 py-2 text-xs text-white outline-none cursor-pointer focus:border-[#e05a68]"
              >
                {COLOR_PRESETS.map(p => (
                  <option key={p.id} value={p.id}>{p.name}</option>
                ))}
                <option value="custom">Code Hex Personnalisé (#...)</option>
              </select>
              {(!COLOR_PRESETS.some(p => p.id === currentCard.badgeColor) || currentCard.badgeColor?.startsWith("#")) && (
                <div className="mt-2 flex items-center gap-2">
                  <input
                    type="color"
                    value={currentCard.badgeColor?.startsWith("#") ? currentCard.badgeColor : "#e05a68"}
                    onChange={(e) => updateCard(activeTab, "badgeColor", e.target.value)}
                    className="w-8 h-8 rounded-lg border-0 cursor-pointer bg-transparent"
                  />
                  <input
                    type="text"
                    value={currentCard.badgeColor || ""}
                    onChange={(e) => updateCard(activeTab, "badgeColor", e.target.value)}
                    placeholder="#e05a68"
                    className="flex-1 bg-[#0b0813] border border-white/10 rounded-lg px-2.5 py-1 text-xs text-white font-mono"
                  />
                </div>
              )}
            </div>

            {/* Type d'Icône */}
            <div>
              <label className="block text-xs font-bold text-white/70 mb-1.5">
                Icône Affichée
              </label>
              <select
                value={currentCard.type || "telegram"}
                onChange={(e) => updateCard(activeTab, "type", e.target.value)}
                className="w-full bg-[#0b0813] border border-white/10 rounded-xl px-3.5 py-2 text-xs text-white outline-none cursor-pointer focus:border-[#e05a68]"
              >
                {ICON_PRESETS.map(ic => (
                  <option key={ic.id} value={ic.id}>{ic.name}</option>
                ))}
              </select>
            </div>

            {/* Drapeau / Émoji */}
            <div>
              <label className="block text-xs font-bold text-white/70 mb-1.5">
                Drapeau ou Émoji (Haut Droite)
              </label>
              <input
                type="text"
                value={currentCard.flag || ""}
                onChange={(e) => updateCard(activeTab, "flag", e.target.value)}
                placeholder="🇫🇷, 🔥, 👑, etc."
                className="w-full bg-[#0b0813] border border-white/10 rounded-xl px-3.5 py-2 text-xs text-white text-center outline-none focus:border-[#e05a68]"
              />
            </div>
          </div>

          {/* Ligne 3 : Titre et Sous-titre */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-bold text-white/70 mb-1.5">
                Titre Principal de la Pancarte
              </label>
              <input
                type="text"
                value={currentCard.title || ""}
                onChange={(e) => updateCard(activeTab, "title", e.target.value)}
                placeholder="ex: MTBR CANAL TELEGRAM OFFICIEL"
                className="w-full bg-[#0b0813] border border-white/10 rounded-xl px-3.5 py-2.5 text-xs text-white font-black outline-none focus:border-[#e05a68]"
              />
            </div>

            <div>
              <label className="block text-xs font-bold text-white/70 mb-1.5">
                Sous-titre / Description Courte
              </label>
              <input
                type="text"
                value={currentCard.subtitle || ""}
                onChange={(e) => updateCard(activeTab, "subtitle", e.target.value)}
                placeholder="ex: Toutes les actualités et sorties exclusives"
                className="w-full bg-[#0b0813] border border-white/10 rounded-xl px-3.5 py-2.5 text-xs text-white outline-none focus:border-[#e05a68]"
              />
            </div>
          </div>

          {/* Ligne 4 : Bouton CTA et Lien URL de Clic */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-bold text-white/70 mb-1.5">
                Texte du Bouton d'Action (CTA)
              </label>
              <input
                type="text"
                value={currentCard.ctaText || ""}
                onChange={(e) => updateCard(activeTab, "ctaText", e.target.value)}
                placeholder="ex: Rejoins sur Telegram, Rejoindre le Discord..."
                className="w-full bg-[#0b0813] border border-white/10 rounded-xl px-3.5 py-2.5 text-xs text-white font-bold outline-none focus:border-[#e05a68]"
              />
            </div>

            <div>
              <label className="block text-xs font-bold text-white/70 mb-1.5">
                Lien de Destination (URL après Clic)
              </label>
              <div className="relative flex items-center">
                <input
                  type="text"
                  value={currentCard.url || ""}
                  onChange={(e) => updateCard(activeTab, "url", e.target.value)}
                  placeholder="https://t.me/... ou https://discord.gg/..."
                  className="w-full bg-[#0b0813] border border-white/10 rounded-xl pl-3.5 pr-9 py-2.5 text-xs text-white font-mono outline-none focus:border-[#e05a68]"
                />
                {currentCard.url && (
                  <a
                    href={currentCard.url}
                    target="_blank"
                    rel="noreferrer"
                    className="absolute right-3 text-white/40 hover:text-white"
                    title="Tester le lien"
                  >
                    <ExternalLink size={14} />
                  </a>
                )}
              </div>
            </div>
          </div>

          {/* Ligne 5 : Image de Fond (Upload direct ou URL) */}
          <div>
            <label className="block text-xs font-bold text-white/70 mb-1.5">
              Image d'Arrière-Plan de la Pancarte (Optionnelle)
            </label>
            <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3">
              <input
                type="text"
                value={currentCard.imageUrl || ""}
                onChange={(e) => updateCard(activeTab, "imageUrl", e.target.value)}
                placeholder="https://... ou téléchargez une image ci-contre"
                className="flex-1 bg-[#0b0813] border border-white/10 rounded-xl px-3.5 py-2.5 text-xs text-white font-mono outline-none focus:border-[#e05a68]"
              />

              <input
                type="file"
                ref={(el) => { fileInputRefs.current[activeTab] = el; }}
                accept="image/*"
                className="hidden"
                onChange={(e) => {
                  const file = e.target.files?.[0];
                  if (file) handleFileUpload(activeTab, file);
                }}
              />

              <button
                type="button"
                onClick={() => fileInputRefs.current[activeTab]?.click()}
                disabled={uploadingIdx === activeTab}
                className="px-4 py-2.5 rounded-xl bg-white/10 hover:bg-white/15 text-white font-bold text-xs flex items-center justify-center gap-2 transition-all cursor-pointer border border-white/10 shrink-0 disabled:opacity-50"
              >
                {uploadingIdx === activeTab ? (
                  <RefreshCw size={14} className="animate-spin" />
                ) : (
                  <Upload size={14} />
                )}
                <span>{uploadingIdx === activeTab ? "Upload..." : "Télécharger une Image"}</span>
              </button>

              {currentCard.imageUrl && (
                <button
                  type="button"
                  onClick={() => updateCard(activeTab, "imageUrl", "")}
                  className="px-3 py-2.5 rounded-xl bg-red-500/10 hover:bg-red-500/20 text-red-400 font-bold text-xs flex items-center justify-center gap-1.5 transition-all cursor-pointer border border-red-500/20 shrink-0"
                  title="Supprimer l'image"
                >
                  <Trash2 size={14} />
                  <span>Retirer</span>
                </button>
              )}
            </div>

            {currentCard.imageUrl && (
              <div className="mt-2.5 flex items-center gap-3 p-2 bg-black/40 rounded-xl border border-white/5 w-fit">
                <img
                  src={currentCard.imageUrl}
                  alt="Aperçu miniature"
                  className="w-16 h-10 object-cover rounded-lg border border-white/10"
                />
                <span className="text-[11px] font-mono text-white/50 truncate max-w-xs">
                  {currentCard.imageUrl}
                </span>
              </div>
            )}
          </div>

        </div>
      )}

      {/* 💾 Bouton Enregistrer du bas */}
      <div className="flex justify-end pt-2">
        <button
          type="button"
          onClick={handleSave}
          disabled={saving}
          style={{
            backgroundColor: themeColor,
            boxShadow: `0 0 25px ${themeColor}66`
          }}
          className="flex items-center gap-2 px-8 py-3.5 rounded-2xl text-white font-black text-sm hover:scale-105 active:scale-95 transition-all cursor-pointer disabled:opacity-50 shadow-xl"
        >
          {saving ? <RefreshCw size={18} className="animate-spin" /> : <Save size={18} />}
          <span>{saving ? "Enregistrement en cours..." : "💾 Enregistrer les 3 Pancartes"}</span>
        </button>
      </div>

    </div>
  );
}
