"use client";

import { useState, useEffect, useMemo } from "react";
import {
  Megaphone,
  Loader2,
  Send,
  FlaskConical,
  History,
  AlertCircle,
  CheckCircle2,
  Eye,
  Sparkles,
  Tag,
  Ban,
  Link2,
  Trash2,
} from "lucide-react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useNotification } from "@/components/ui/notification";
import { useTranslationStore } from "@/lib/store";
import { API_BASE } from "@/lib/config";
import { useI18n } from "@/lib/i18n";
import { LLM_CHANNEL_OPTIONS } from "../constants";
import type {
  MarketingAudiencesResponse,
  MarketingEmailGenerateRequest,
  MarketingEmailGenerateResponse,
  MarketingEmailHistoryEntry,
  MarketingEmailSendResponse,
  PromoCode,
  PromoListResponse,
} from "../types";

const getToken = () => useTranslationStore.getState().settings.adminToken ?? "";

/** Clés i18n par identifiant d'audience (l'identifiant part en base/historique). */
const AUDIENCE_LABEL_KEYS: Record<string, string> = {
  waitlist: "admin.marketing.audienceWaitlist",
  inactive_30: "admin.marketing.audienceInactive",
  "plan:pro": "admin.marketing.audiencePlanPro",
  "plan:starter": "admin.marketing.audiencePlanStarter",
  "plan:business": "admin.marketing.audiencePlanBusiness",
  "plan:enterprise": "admin.marketing.audiencePlanEnterprise",
  "plan:free": "admin.marketing.audiencePlanFree",
  all_users: "admin.marketing.audienceAllUsers",
};

/** Langues proposées pour l'email généré. */
const EMAIL_LANGUAGES: { id: string; labelKey: string }[] = [
  { id: "Français", labelKey: "admin.marketing.langFr" },
  { id: "English", labelKey: "admin.marketing.langEn" },
  { id: "Deutsch", labelKey: "admin.marketing.langDe" },
  { id: "Español", labelKey: "admin.marketing.langEs" },
  { id: "Italiano", labelKey: "admin.marketing.langIt" },
  { id: "Português", labelKey: "admin.marketing.langPt" },
  { id: "Nederlands", labelKey: "admin.marketing.langNl" },
  { id: "العربية", labelKey: "admin.marketing.langAr" },
  { id: "فارسی", labelKey: "admin.marketing.langFa" },
  { id: "日本語", labelKey: "admin.marketing.langJa" },
  { id: "한국어", labelKey: "admin.marketing.langKo" },
  { id: "Русский", labelKey: "admin.marketing.langRu" },
  { id: "中文", labelKey: "admin.marketing.langZh" },
];

const TONES: { id: string; labelKey: string }[] = [
  { id: "friendly", labelKey: "admin.marketing.toneFriendly" },
  { id: "professional", labelKey: "admin.marketing.toneProfessional" },
  { id: "urgent", labelKey: "admin.marketing.toneUrgent" },
  { id: "festive", labelKey: "admin.marketing.toneFestive" },
];

/** Forfaits éligibles à un code promo (le forfait gratuit n'est pas éligible). */
const PROMO_PLANS = ["all", "starter", "pro", "business", "enterprise"];

export default function AdminMarketingPage() {
  const { t } = useI18n();
  const { success, error } = useNotification();
  const [audiences, setAudiences] = useState<Record<string, number>>({});
  const [unsubscribedCount, setUnsubscribedCount] = useState(0);
  const [audience, setAudience] = useState("waitlist");
  const [subject, setSubject] = useState("");
  const [html, setHtml] = useState("");
  const [testEmail, setTestEmail] = useState("");
  const [showPreview, setShowPreview] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [isSendingTest, setIsSendingTest] = useState(false);
  const [isSending, setIsSending] = useState(false);
  const [history, setHistory] = useState<MarketingEmailHistoryEntry[]>([]);
  /** Empreinte SHA-256 du contenu courant (même calcul que le backend). */
  const [contentHash, setContentHash] = useState<string | null>(null);
  /** false si le navigateur n'expose pas crypto.subtle (indicateur absent,
   * l'envoi reste possible : le serveur valide l'envoi test). */
  const [hashSupported, setHashSupported] = useState(true);

  // ── Génération par IA ──
  const [genProvider, setGenProvider] = useState("openrouter");
  const [genModel, setGenModel] = useState("");
  const [brief, setBrief] = useState("");
  const [genLanguage, setGenLanguage] = useState("Français");
  const [genTone, setGenTone] = useState("friendly");
  const [genPromoCode, setGenPromoCode] = useState("");
  const [isGenerating, setIsGenerating] = useState(false);

  // ── Réductions ──
  const [promos, setPromos] = useState<PromoCode[]>([]);
  const [promoCode, setPromoCode] = useState("");
  const [promoType, setPromoType] = useState<"percent" | "amount">("percent");
  const [promoValue, setPromoValue] = useState("10");
  const [promoPlans, setPromoPlans] = useState<string[]>(["all"]);
  const [promoMaxRedemptions, setPromoMaxRedemptions] = useState("");
  const [promoExpiresAt, setPromoExpiresAt] = useState("");
  const [isCreatingPromo, setIsCreatingPromo] = useState(false);
  const [deactivatingCode, setDeactivatingCode] = useState<string | null>(null);
  const [deletingCode, setDeletingCode] = useState<string | null>(null);
  const [linkingCode, setLinkingCode] = useState<string | null>(null);

  useEffect(() => {
    if (!crypto?.subtle) {
      setHashSupported(false);
      setContentHash(null);
      return;
    }
    let cancelled = false;
    const data = new TextEncoder().encode(`${subject.trim()}\n${html.trim()}`);
    crypto.subtle
      .digest("SHA-256", data)
      .then((buf) => {
        if (cancelled) return;
        const hex = Array.from(new Uint8Array(buf))
          .map((b) => b.toString(16).padStart(2, "0"))
          .join("");
        setContentHash(hex);
      })
      .catch(() => setContentHash(null));
    return () => {
      cancelled = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [subject, html]);

  const loadAudiences = async () => {
    const response = await fetch(`${API_BASE}/api/v1/admin/marketing/audiences`, {
      headers: { Authorization: `Bearer ${getToken()}` },
    });
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    const json: MarketingAudiencesResponse = await response.json();
    setAudiences(json.data.audiences);
    setUnsubscribedCount(json.data.unsubscribed_count);
  };

  const loadHistory = async () => {
    const response = await fetch(`${API_BASE}/api/v1/admin/marketing/email/history`, {
      headers: { Authorization: `Bearer ${getToken()}` },
    });
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    const json = await response.json();
    setHistory(json.data ?? []);
  };

  const loadPromos = async () => {
    const response = await fetch(`${API_BASE}/api/v1/admin/marketing/promos`, {
      headers: { Authorization: `Bearer ${getToken()}` },
    });
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    const json: PromoListResponse = await response.json();
    setPromos(json.data.promos ?? []);
  };

  useEffect(() => {
    setIsLoading(true);
    Promise.all([loadAudiences(), loadHistory(), loadPromos()])
      .catch((e) =>
        error({ title: t("admin.marketing.loadErrorTitle"), description: String(e.message ?? e) })
      )
      .finally(() => setIsLoading(false));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const audienceLabel = (key: string): string => {
    const labelKey = AUDIENCE_LABEL_KEYS[key];
    return labelKey ? t(labelKey) : key;
  };

  const channelLabel = (id: string): string => {
    const entry = LLM_CHANNEL_OPTIONS.find((c) => c.id === id);
    return entry ? t(entry.labelKey) : id;
  };

  const recipientCount = audiences[audience] ?? 0;

  /** Simple indicateur (non bloquant) : un test réussi de ce contenu exact
   * apparaît dans l'historique chargé. La décision d'autoriser l'envoi réel
   * appartient au serveur (l'historique affiché est tronqué à 100 entrées). */
  const testSeenInHistory =
    !!contentHash &&
    history.some(
      (h) => h.test_mode && h.sent_count > 0 && h.content_hash === contentHash
    );

  // ── Génération IA : remplit sujet + HTML, n'envoie RIEN ──
  const generateEmail = async () => {
    if (!brief.trim()) {
      error({ title: t("admin.marketing.generateFailedTitle"), description: t("admin.marketing.briefRequired") });
      return;
    }
    setIsGenerating(true);
    try {
      const payload: MarketingEmailGenerateRequest = {
        provider: genProvider,
        model: genModel.trim() || undefined,
        brief: brief.trim(),
        language: genLanguage,
        tone: genTone || undefined,
        promo_code: genPromoCode || undefined,
      };
      const response = await fetch(`${API_BASE}/api/v1/admin/marketing/email/generate`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${getToken()}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify(payload),
      });
      const json = await response.json().catch(() => null);
      const d = json?.data as MarketingEmailGenerateResponse["data"] | undefined;
      if (response.ok && d?.subject && d?.html) {
        setSubject(d.subject);
        setHtml(d.html);
        success({ title: t("admin.marketing.generatedTitle"), description: t("admin.marketing.generatedDesc", { provider: channelLabel(d.provider) }) });
      } else if (response.ok) {
        // 200 sans contenu exploitable : message d'erreur, jamais d'exception.
        error({ title: t("admin.marketing.generateFailedTitle"), description: t("admin.marketing.generateEmpty") });
      } else {
        error({
          title: t("admin.marketing.generateFailedTitle"),
          description: json?.message || `HTTP ${response.status}`,
        });
      }
    } catch {
      error({ title: t("admin.marketing.generateFailedTitle"), description: t("admin.marketing.networkDesc") });
    } finally {
      setIsGenerating(false);
    }
  };

  const sendTest = async () => {
    if (!subject.trim() || !html.trim()) {
      error({ title: t("admin.marketing.incompleteTitle"), description: t("admin.marketing.incompleteDesc") });
      return;
    }
    setIsSendingTest(true);
    try {
      const response = await fetch(`${API_BASE}/api/v1/admin/marketing/email/send`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${getToken()}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          audience,
          subject: subject.trim(),
          html: html.trim(),
          test_mode: true,
          test_email: testEmail.trim() || null,
        }),
      });
      const json = await response.json().catch(() => ({}));
      if (response.ok) {
        const d: MarketingEmailSendResponse["data"] = json.data;
        success({
          title: t("admin.marketing.testDoneTitle"),
          description: t("admin.marketing.testDoneDesc", { email: d.recipient ?? "" }),
        });
        await loadHistory();
      } else {
        error({
          title: t("admin.marketing.testFailedTitle"),
          description: json.message || `HTTP ${response.status}`,
        });
        await loadHistory();
      }
    } catch {
      error({ title: t("admin.marketing.loadErrorTitle"), description: t("admin.marketing.networkDesc") });
    } finally {
      setIsSendingTest(false);
    }
  };

  const sendReal = async () => {
    if (!subject.trim() || !html.trim()) {
      error({ title: t("admin.marketing.incompleteTitle"), description: t("admin.marketing.incompleteDesc") });
      return;
    }
    if (
      !window.confirm(
        t("admin.marketing.confirmSend", { count: recipientCount, audience: audienceLabel(audience) })
      )
    ) {
      return;
    }
    setIsSending(true);
    try {
      const response = await fetch(`${API_BASE}/api/v1/admin/marketing/email/send`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${getToken()}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          audience,
          subject: subject.trim(),
          html: html.trim(),
          test_mode: false,
        }),
      });
      const json = await response.json().catch(() => ({}));
      if (response.ok) {
        const d: MarketingEmailSendResponse["data"] = json.data;
        success({
          title: t("admin.marketing.sendingTitle"),
          description: t("admin.marketing.sendingDesc", { count: d.queued ?? 0 }),
        });
        setTimeout(() => {
          loadHistory().catch(() => {});
        }, 3000);
      } else {
        error({
          title: t("admin.marketing.sendRefusedTitle"),
          description: json.message || `HTTP ${response.status}`,
        });
      }
    } catch {
      error({ title: t("admin.marketing.loadErrorTitle"), description: t("admin.marketing.networkDesc") });
    } finally {
      setIsSending(false);
    }
  };

  // ── Réductions ──
  const createPromo = async () => {
    const code = promoCode.trim().toUpperCase();
    const value = parseFloat(promoValue);
    if (!code || !Number.isFinite(value)) {
      error({ title: t("admin.marketing.promoCreateFailedTitle"), description: t("admin.marketing.promoInvalidInput") });
      return;
    }
    setIsCreatingPromo(true);
    try {
      const body: Record<string, unknown> = {
        code,
        type: promoType,
        value,
        plans: promoPlans.length ? promoPlans : ["all"],
      };
      if (promoMaxRedemptions.trim()) body.max_redemptions = parseInt(promoMaxRedemptions, 10);
      if (promoExpiresAt.trim()) {
        // « jusqu'au 10 » = valable tout le 10 : 23:59:59 UTC du jour choisi.
        body.expires_at = new Date(`${promoExpiresAt.trim()}T23:59:59Z`).toISOString();
      }
      const response = await fetch(`${API_BASE}/api/v1/admin/marketing/promos`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${getToken()}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify(body),
      });
      const json = await response.json().catch(() => ({}));
      if (response.ok) {
        success({ title: t("admin.marketing.promoCreatedTitle"), description: t("admin.marketing.promoCreatedDesc", { code }) });
        setPromoCode("");
        setPromoMaxRedemptions("");
        setPromoExpiresAt("");
        await loadPromos();
      } else {
        error({
          title: t("admin.marketing.promoCreateFailedTitle"),
          description: json.message || `HTTP ${response.status}`,
        });
      }
    } catch {
      error({ title: t("admin.marketing.promoCreateFailedTitle"), description: t("admin.marketing.networkDesc") });
    } finally {
      setIsCreatingPromo(false);
    }
  };

  const deactivatePromo = async (code: string) => {
    setDeactivatingCode(code);
    try {
      const response = await fetch(
        `${API_BASE}/api/v1/admin/marketing/promos/${encodeURIComponent(code)}/deactivate`,
        {
          method: "POST",
          headers: { Authorization: `Bearer ${getToken()}` },
        }
      );
      const json = await response.json().catch(() => ({}));
      if (response.ok) {
        success({ title: t("admin.marketing.promoDeactivatedTitle"), description: t("admin.marketing.promoDeactivatedDesc", { code }) });
        await loadPromos();
      } else {
        error({
          title: t("admin.marketing.promoDeactivateFailedTitle"),
          description: json.message || `HTTP ${response.status}`,
        });
      }
    } catch {
      error({ title: t("admin.marketing.promoDeactivateFailedTitle"), description: t("admin.marketing.networkDesc") });
    } finally {
      setDeactivatingCode(null);
    }
  };

  const deletePromo = async (code: string) => {
    if (!window.confirm(t("admin.marketing.promoDeleteConfirm", { code }))) return;
    setDeletingCode(code);
    try {
      const response = await fetch(
        `${API_BASE}/api/v1/admin/marketing/promos/${encodeURIComponent(code)}`,
        {
          method: "DELETE",
          headers: { Authorization: `Bearer ${getToken()}` },
        }
      );
      const json = await response.json().catch(() => ({}));
      if (response.ok) {
        success({ title: t("admin.marketing.promoDeletedTitle"), description: t("admin.marketing.promoDeletedDesc", { code }) });
        await loadPromos();
      } else {
        error({
          title: t("admin.marketing.promoDeleteFailedTitle"),
          description: json.message || `HTTP ${response.status}`,
        });
      }
    } catch {
      error({ title: t("admin.marketing.promoDeleteFailedTitle"), description: t("admin.marketing.networkDesc") });
    } finally {
      setDeletingCode(null);
    }
  };

  const linkPromoToStripe = async (code: string) => {
    setLinkingCode(code);
    try {
      const response = await fetch(
        `${API_BASE}/api/v1/admin/marketing/promos/${encodeURIComponent(code)}/link-stripe`,
        {
          method: "POST",
          headers: { Authorization: `Bearer ${getToken()}` },
        }
      );
      const json = await response.json().catch(() => ({}));
      if (response.ok) {
        success({ title: t("admin.marketing.promoLinkedTitle"), description: t("admin.marketing.promoLinkedDesc", { code }) });
        await loadPromos();
      } else {
        error({
          title: t("admin.marketing.promoLinkFailedTitle"),
          description: json.message || `HTTP ${response.status}`,
        });
      }
    } catch {
      error({ title: t("admin.marketing.promoLinkFailedTitle"), description: t("admin.marketing.networkDesc") });
    } finally {
      setLinkingCode(null);
    }
  };

  const togglePromoPlan = (plan: string) => {
    setPromoPlans((prev) => {
      if (plan === "all") return prev.includes("all") ? [] : ["all"];
      const next = prev.filter((p) => p !== "all");
      return next.includes(plan) ? next.filter((p) => p !== plan) : [...next, plan];
    });
  };

  const activePromos = useMemo(() => promos.filter((p) => p.active), [promos]);

  const promoLabel = (p: PromoCode): string => {
    const value =
      p.type === "percent" ? `-${p.value} %` : `-${p.value} €`;
    return `${p.code} (${value})`;
  };

  const previewDoc = useMemo(
    () =>
      html.trim() ||
      `<html><body style='font-family:sans-serif;color:#94a3b8;padding:32px;text-align:center;'>${t(
        "admin.marketing.previewEmpty"
      )}</body></html>`,
    [html, t]
  );

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-3">
        <div className="w-10 h-10 bg-purple-600/20 rounded-lg flex items-center justify-center">
          <Megaphone className="w-5 h-5 text-purple-400" />
        </div>
        <div>
          <h1 className="text-xl font-semibold text-foreground">{t("admin.marketing.title")}</h1>
          <p className="text-sm text-muted-foreground">{t("admin.marketing.subtitle")}</p>
        </div>
      </div>

      {isLoading ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="size-8 animate-spin text-muted-foreground" />
        </div>
      ) : (
        <>
          <div className="grid gap-6 lg:grid-cols-3">
            {/* ── Composition ── */}
            <Card className="lg:col-span-2 overflow-visible">
              <CardHeader>
                <CardTitle className="text-base">{t("admin.marketing.newCampaign")}</CardTitle>
                <CardDescription>
                  {t("admin.marketing.unsubscribedNote", { count: unsubscribedCount })}
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                {/* ── Générer avec l'IA ── */}
                <div className="rounded-lg border border-border/60 bg-muted/30 p-4 space-y-3">
                  <div className="flex items-center gap-2">
                    <Sparkles className="size-4 text-accent" />
                    <span className="text-sm font-semibold">{t("admin.marketing.generateTitle")}</span>
                  </div>
                  <p className="text-xs text-muted-foreground">{t("admin.marketing.generateDesc")}</p>
                  <div className="grid gap-3 sm:grid-cols-3">
                    <div className="space-y-1.5">
                      <Label htmlFor="gen-provider">{t("admin.marketing.channel")}</Label>
                      <Select value={genProvider} onValueChange={setGenProvider}>
                        <SelectTrigger id="gen-provider">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          {LLM_CHANNEL_OPTIONS.map((c) => (
                            <SelectItem key={c.id} value={c.id}>
                              {t(c.labelKey)}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="space-y-1.5">
                      <Label htmlFor="gen-model">{t("admin.marketing.model")}</Label>
                      <Input
                        id="gen-model"
                        placeholder={t("admin.marketing.modelPlaceholder")}
                        value={genModel}
                        onChange={(e) => setGenModel(e.target.value)}
                      />
                    </div>
                    <div className="space-y-1.5">
                      <Label htmlFor="gen-promo">{t("admin.marketing.promoOptional")}</Label>
                      <Select value={genPromoCode || "none"} onValueChange={(v) => setGenPromoCode(v === "none" ? "" : v)}>
                        <SelectTrigger id="gen-promo">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="none">{t("admin.marketing.promoNone")}</SelectItem>
                          {activePromos.map((p) => (
                            <SelectItem key={p.code} value={p.code}>
                              {promoLabel(p)}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                  <div className="space-y-1.5">
                    <Label htmlFor="gen-brief">{t("admin.marketing.brief")}</Label>
                    <Textarea
                      id="gen-brief"
                      className="min-h-20"
                      placeholder={t("admin.marketing.briefPlaceholder")}
                      value={brief}
                      onChange={(e) => setBrief(e.target.value)}
                      maxLength={4000}
                    />
                  </div>
                  <div className="grid gap-3 sm:grid-cols-3">
                    <div className="space-y-1.5">
                      <Label htmlFor="gen-language">{t("admin.marketing.language")}</Label>
                      <Select value={genLanguage} onValueChange={setGenLanguage}>
                        <SelectTrigger id="gen-language">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          {EMAIL_LANGUAGES.map((l) => (
                            <SelectItem key={l.id} value={l.id}>
                              {t(l.labelKey)}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="space-y-1.5">
                      <Label htmlFor="gen-tone">{t("admin.marketing.tone")}</Label>
                      <Select value={genTone || "none"} onValueChange={(v) => setGenTone(v === "none" ? "" : v)}>
                        <SelectTrigger id="gen-tone">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="none">{t("admin.marketing.toneNone")}</SelectItem>
                          {TONES.map((tone) => (
                            <SelectItem key={tone.id} value={tone.id}>
                              {t(tone.labelKey)}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="flex items-end">
                      <Button
                        variant="outline"
                        onClick={generateEmail}
                        disabled={isGenerating || !brief.trim()}
                        className="gap-2 w-full"
                      >
                        {isGenerating ? (
                          <Loader2 className="size-4 animate-spin" />
                        ) : (
                          <Sparkles className="size-4" />
                        )}
                        {isGenerating ? t("admin.marketing.generating") : t("admin.marketing.generateBtn")}
                      </Button>
                    </div>
                  </div>
                </div>

                <div className="grid gap-4 sm:grid-cols-2">
                  <div className="space-y-2">
                    <Label>{t("admin.marketing.audience")}</Label>
                    <Select value={audience} onValueChange={setAudience}>
                      <SelectTrigger>
                        <SelectValue placeholder={t("admin.marketing.audiencePlaceholder")} />
                      </SelectTrigger>
                      <SelectContent>
                        {Object.keys(audiences)
                          .sort((a, b) => (audiences[b] ?? 0) - (audiences[a] ?? 0))
                          .map((key) => (
                            <SelectItem key={key} value={key}>
                              {audienceLabel(key)} ({audiences[key]})
                            </SelectItem>
                          ))}
                      </SelectContent>
                    </Select>
                    <p className="text-xs text-muted-foreground">
                      {t("admin.marketing.recipientsAvailable", { count: recipientCount })}
                    </p>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="marketing-test-email">{t("admin.marketing.testEmail")}</Label>
                    <Input
                      id="marketing-test-email"
                      type="email"
                      placeholder={t("admin.marketing.testEmailPlaceholder")}
                      value={testEmail}
                      onChange={(e) => setTestEmail(e.target.value)}
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="marketing-subject">{t("admin.marketing.subject")}</Label>
                  <Input
                    id="marketing-subject"
                    placeholder={t("admin.marketing.subjectPlaceholder")}
                    value={subject}
                    onChange={(e) => setSubject(e.target.value)}
                    maxLength={200}
                  />
                </div>

                <div className="space-y-2">
                  <div className="flex items-center justify-between">
                    <Label htmlFor="marketing-html">{t("admin.marketing.html")}</Label>
                    <Button
                      variant="ghost"
                      size="sm"
                      className="h-7 gap-1.5 text-xs"
                      onClick={() => setShowPreview((v) => !v)}
                    >
                      <Eye className="size-3" />
                      {showPreview ? t("admin.marketing.hidePreview") : t("admin.marketing.preview")}
                    </Button>
                  </div>
                  <Textarea
                    id="marketing-html"
                    className="min-h-48 font-mono text-xs"
                    placeholder={t("admin.marketing.htmlPlaceholder")}
                    value={html}
                    onChange={(e) => setHtml(e.target.value)}
                  />
                  <p className="text-xs text-muted-foreground">{t("admin.marketing.footerNote")}</p>
                  {showPreview && (
                    <iframe
                      title={t("admin.marketing.previewTitle")}
                      srcDoc={previewDoc}
                      className="h-72 w-full rounded-lg border border-border bg-white"
                      sandbox=""
                    />
                  )}
                </div>

                <div className="flex flex-wrap items-center gap-3 border-t border-border/60 pt-4">
                  <Button variant="outline" onClick={sendTest} disabled={isSendingTest} className="gap-2">
                    {isSendingTest ? (
                      <Loader2 className="size-4 animate-spin" />
                    ) : (
                      <FlaskConical className="size-4" />
                    )}
                    {t("admin.marketing.sendTest")}
                  </Button>
                  <Button
                    onClick={sendReal}
                    disabled={isSending || recipientCount === 0}
                    className="gap-2"
                  >
                    {isSending ? (
                      <Loader2 className="size-4 animate-spin" />
                    ) : (
                      <Send className="size-4" />
                    )}
                    {t("admin.marketing.sendReal", { count: recipientCount })}
                  </Button>
                  {!hashSupported && (
                    <span className="flex items-center gap-1.5 text-xs text-muted-foreground">
                      <AlertCircle className="size-3.5" />
                      {t("admin.marketing.localCheckUnavailable")}
                    </span>
                  )}
                  {hashSupported && testSeenInHistory && (
                    <span className="flex items-center gap-1.5 text-xs text-green-500">
                      <CheckCircle2 className="size-3.5" />
                      {t("admin.marketing.testValidated")}
                    </span>
                  )}
                  {hashSupported && !testSeenInHistory && (
                    <span className="flex items-center gap-1.5 text-xs text-amber-500">
                      <AlertCircle className="size-3.5" />
                      {t("admin.marketing.testRequiredHint")}
                    </span>
                  )}
                </div>
              </CardContent>
            </Card>

            {/* ── Historique ── */}
            <Card>
              <CardHeader className="flex flex-row items-center gap-2 pb-3">
                <History className="size-4 text-muted-foreground" />
                <CardTitle className="text-base">{t("admin.marketing.history")}</CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                {history.length === 0 && (
                  <p className="text-sm text-muted-foreground">{t("admin.marketing.noHistory")}</p>
                )}
                {history.map((h) => (
                  <div key={h.id} className="rounded-lg border border-border/60 p-3 text-xs">
                    <div className="mb-1 flex flex-wrap items-center gap-2">
                      {h.test_mode ? (
                        <Badge variant="outline" className="text-[10px]">
                          {t("admin.marketing.badgeTest")}
                        </Badge>
                      ) : (
                        <Badge className="bg-accent/10 text-accent border-accent/30 text-[10px]">
                          {t("admin.marketing.badgeReal")}
                        </Badge>
                      )}
                      <span className="text-muted-foreground">
                        {new Date(h.sent_at).toLocaleString("fr-FR")}
                      </span>
                    </div>
                    <p className="mb-1 font-medium text-foreground">{h.subject}</p>
                    <p className="text-muted-foreground">
                      {audienceLabel(h.audience)} —{" "}
                      {t("admin.marketing.historySent", {
                        sent: h.sent_count,
                        total: h.recipients_total,
                      })}
                      {h.failed_count > 0
                        ? t("admin.marketing.historyFailedSuffix", { count: h.failed_count })
                        : ""}
                    </p>
                  </div>
                ))}
              </CardContent>
            </Card>
          </div>

          {/* ── Réductions (codes promo) ── */}
          <div className="grid gap-6 lg:grid-cols-3">
            <Card className="lg:col-span-2">
              <CardHeader className="flex flex-row items-center gap-2 pb-3">
                <Tag className="size-4 text-muted-foreground" />
                <div>
                  <CardTitle className="text-base">{t("admin.marketing.promoTitle")}</CardTitle>
                  <CardDescription>{t("admin.marketing.promoDesc")}</CardDescription>
                </div>
              </CardHeader>
              <CardContent className="space-y-3">
                {promos.length === 0 && (
                  <p className="text-sm text-muted-foreground">{t("admin.marketing.promoEmpty")}</p>
                )}
                {promos.map((p) => (
                  <div key={p.code} className="rounded-lg border border-border/60 p-3 text-xs">
                    <div className="mb-1 flex flex-wrap items-center gap-2">
                      <span className="font-mono font-semibold text-foreground">{p.code}</span>
                      <Badge variant="secondary" className="text-[10px]">
                        {p.type === "percent" ? `-${p.value} %` : `-${p.value} €`}
                      </Badge>
                      {p.active ? (
                        <Badge className="bg-green-500/10 text-green-600 border-green-500/30 text-[10px]">
                          {t("admin.marketing.promoActive")}
                        </Badge>
                      ) : (
                        <Badge variant="outline" className="text-[10px]">
                          {t("admin.marketing.promoInactive")}
                        </Badge>
                      )}
                      {p.stripe_mode === "local_only" && (
                        <Badge variant="outline" className="text-[10px] text-amber-500 border-amber-500/40">
                          {t("admin.marketing.promoLocalOnly")}
                        </Badge>
                      )}
                      {p.active && p.stripe_mode === "local_only" && (
                        <Button
                          variant="ghost"
                          size="sm"
                          className="ms-auto h-6 gap-1 px-2 text-[11px] text-blue-500"
                          onClick={() => linkPromoToStripe(p.code)}
                          disabled={linkingCode === p.code}
                        >
                          {linkingCode === p.code ? (
                            <Loader2 className="size-3 animate-spin" />
                          ) : (
                            <Link2 className="size-3" />
                          )}
                          {t("admin.marketing.promoLinkStripe")}
                        </Button>
                      )}
                      {p.active && (
                        <Button
                          variant="ghost"
                          size="sm"
                          className={"h-6 gap-1 px-2 text-[11px] text-red-500 " + (p.stripe_mode === "local_only" ? "" : "ms-auto")}
                          onClick={() => deactivatePromo(p.code)}
                          disabled={deactivatingCode === p.code}
                        >
                          {deactivatingCode === p.code ? (
                            <Loader2 className="size-3 animate-spin" />
                          ) : (
                            <Ban className="size-3" />
                          )}
                          {t("admin.marketing.promoDeactivate")}
                        </Button>
                      )}
                      <Button
                        variant="ghost"
                        size="sm"
                        className="h-6 w-6 p-0 text-red-500"
                        onClick={() => deletePromo(p.code)}
                        disabled={deletingCode === p.code}
                        aria-label={t("admin.marketing.promoDelete")}
                      >
                        {deletingCode === p.code ? (
                          <Loader2 className="size-3 animate-spin" />
                        ) : (
                          <Trash2 className="size-3" />
                        )}
                      </Button>
                    </div>
                    <p className="text-muted-foreground">
                      {t("admin.marketing.promoUsage", {
                        used: p.times_used,
                        max: p.max_redemptions ?? "∞",
                      })}
                      {" · "}
                      {t("admin.marketing.promoPlansLabel")}{" "}
                      {(p.plans ?? []).map((plan) =>
                        plan === "all" ? t("admin.marketing.promoAllPlans") : plan
                      ).join(", ")}
                      {" · "}
                      {p.expires_at
                        ? t("admin.marketing.promoExpiresOn", {
                            date: new Date(p.expires_at).toLocaleDateString("fr-FR"),
                          })
                        : t("admin.marketing.promoNeverExpires")}
                    </p>
                  </div>
                ))}
              </CardContent>
            </Card>

            <Card className="overflow-visible">
              <CardHeader className="pb-3">
                <CardTitle className="text-base">{t("admin.marketing.promoCreateTitle")}</CardTitle>
                <CardDescription>{t("admin.marketing.promoCreateDesc")}</CardDescription>
              </CardHeader>
              <CardContent className="space-y-3">
                <div className="space-y-1.5">
                  <Label htmlFor="promo-code">{t("admin.marketing.promoCode")}</Label>
                  <Input
                    id="promo-code"
                    placeholder="LANCEMENT10"
                    value={promoCode}
                    onChange={(e) => setPromoCode(e.target.value.toUpperCase())}
                    maxLength={24}
                  />
                </div>
                <div className="grid grid-cols-2 gap-2">
                  <div className="space-y-1.5">
                    <Label htmlFor="promo-type">{t("admin.marketing.promoType")}</Label>
                    <Select value={promoType} onValueChange={(v) => setPromoType(v as "percent" | "amount")}>
                      <SelectTrigger id="promo-type">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="percent">{t("admin.marketing.promoTypePercent")}</SelectItem>
                        <SelectItem value="amount">{t("admin.marketing.promoTypeAmount")}</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="space-y-1.5">
                    <Label htmlFor="promo-value">{t("admin.marketing.promoValue")}</Label>
                    <Input
                      id="promo-value"
                      type="number"
                      min={promoType === "percent" ? 1 : 0.01}
                      max={promoType === "percent" ? 100 : 10000}
                      value={promoValue}
                      onChange={(e) => setPromoValue(e.target.value)}
                    />
                  </div>
                </div>
                <div className="space-y-1.5">
                  <Label>{t("admin.marketing.promoPlans")}</Label>
                  <div className="flex flex-wrap gap-1.5">
                    {PROMO_PLANS.map((plan) => (
                      <button
                        key={plan}
                        type="button"
                        onClick={() => togglePromoPlan(plan)}
                        className={
                          "rounded-full border px-2.5 py-1 text-[11px] transition-colors " +
                          (promoPlans.includes(plan)
                            ? "border-accent bg-accent/10 text-accent"
                            : "border-border text-muted-foreground hover:text-foreground")
                        }
                      >
                        {plan === "all" ? t("admin.marketing.promoAllPlans") : plan}
                      </button>
                    ))}
                  </div>
                </div>
                <div className="grid grid-cols-2 gap-2">
                  <div className="space-y-1.5">
                    <Label htmlFor="promo-max">{t("admin.marketing.promoMaxRedemptions")}</Label>
                    <Input
                      id="promo-max"
                      type="number"
                      min={1}
                      placeholder={t("admin.marketing.promoMaxPlaceholder")}
                      value={promoMaxRedemptions}
                      onChange={(e) => setPromoMaxRedemptions(e.target.value)}
                    />
                  </div>
                  <div className="space-y-1.5">
                    <Label htmlFor="promo-expires">{t("admin.marketing.promoExpires")}</Label>
                    <Input
                      id="promo-expires"
                      type="date"
                      value={promoExpiresAt}
                      onChange={(e) => setPromoExpiresAt(e.target.value)}
                    />
                    <p className="text-[11px] text-muted-foreground">
                      {t("admin.marketing.promoExpiryHint")}
                    </p>
                  </div>
                </div>
                <Button onClick={createPromo} disabled={isCreatingPromo || !promoCode.trim()} className="w-full gap-2">
                  {isCreatingPromo ? (
                    <Loader2 className="size-4 animate-spin" />
                  ) : (
                    <Tag className="size-4" />
                  )}
                  {isCreatingPromo ? t("admin.marketing.promoCreating") : t("admin.marketing.promoCreate")}
                </Button>
              </CardContent>
            </Card>
          </div>
        </>
      )}
    </div>
  );
}
