"use client"

import { useEffect, useState, useCallback, useRef } from "react"
import { useParams, useRouter } from "next/navigation"
import { useLocale, useTranslations } from "next-intl"
import {
  ArrowLeft, Building2, Pencil, Loader2, AlertTriangle,
  Users, Trash2, Shield, Globe, MapPin, Mail, Phone,
  CreditCard, Clock, UserPlus, Ban, UserCheck, RefreshCw,
  Key, Download, CheckCircle2, XCircle, CalendarClock,
  Infinity as InfinityIcon, FileArchive, ImageDown, Award,
} from "lucide-react"

import {
  getTenant, getTenantLicense, saveTenantLicense, deleteTenantLicense,
  exportTenantData,
  type Tenant, type TenantLicense, type LicensePlan,
} from "@/src/lib/api/tenants"
import {
  listMembershipsByTenant, deleteMembership, updateMembership,
  listRoles, type Membership, type Role,
} from "@/src/lib/api/memberships"
import { listUsers, type User } from "@/src/lib/api/users"
import { COUNTRIES } from "@/src/lib/constants/countries"

// ── Palette ────────────────────────────────────────────────────────────────
const NAVY  = "#1a3578"
const NAVY2 = "#2655b0"
const TEAL  = "#4dba96"
const TEAL2 = "#2d9073"
const RED   = "#dc2626"
const GREEN = "#059669"

// ── Helpers ────────────────────────────────────────────────────────────────
function displayName(u?: User) {
  if (!u) return "—"
  return [u.first_name, u.last_name].filter(Boolean).join(" ") || u.username
}
function resolveUserId(m: Membership): number {
  return typeof m.user === "object" ? (m.user as any).id : (m.user as number)
}
function fmtDate(iso: string | null | undefined, locale: string) {
  if (!iso) return "—"
  try {
    return new Date(iso).toLocaleDateString(locale === "fr" ? "fr-FR" : "en-GB", {
      day: "2-digit", month: "long", year: "numeric",
    })
  } catch { return iso }
}
function fmtDateShort(iso: string | null | undefined, locale: string) {
  if (!iso) return "—"
  try {
    return new Date(iso).toLocaleDateString(locale === "fr" ? "fr-FR" : "en-GB", {
      day: "2-digit", month: "short", year: "numeric",
    })
  } catch { return iso }
}
function addOneYear(dateStr: string): string {
  const d = new Date(dateStr)
  d.setFullYear(d.getFullYear() + 1)
  return d.toISOString().slice(0, 10)
}
function today(): string {
  return new Date().toISOString().slice(0, 10)
}
function certNumber(lic: TenantLicense): string {
  const year = new Date(lic.starts_at).getFullYear()
  return `ACX-LIC-${year}-${String(lic.id).padStart(6, "0")}`
}

// ── Badges ─────────────────────────────────────────────────────────────────
function MemberBadge({ status }: { status: string }) {
  const map: Record<string, [string, string, string, string]> = {
    active:    [GREEN,    "rgba(5,150,105,0.09)",   "rgba(5,150,105,0.25)",   "Actif"],
    invited:   [NAVY2,   `${NAVY2}12`,              `${NAVY2}30`,             "Invité"],
    suspended: ["#94a3b8","rgba(148,163,184,0.09)", "rgba(148,163,184,0.25)", "Suspendu"],
  }
  const [color, bg, border, label] = map[status] ?? map.suspended
  return (
    <span className="inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-[11px] font-semibold ring-1"
      style={{ color, background: bg, borderColor: border }}>
      <span className="h-1.5 w-1.5 rounded-full" style={{ backgroundColor: color }} />
      {label}
    </span>
  )
}
function UserAvatar({ name }: { name: string }) {
  return (
    <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl text-[11px] font-bold text-white"
      style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}>
      {name.slice(0, 2).toUpperCase()}
    </div>
  )
}
function InfoRow({ icon: Icon, label, value }: { icon: any; label: string; value?: string | null }) {
  if (!value) return null
  return (
    <div className="flex items-start gap-3 border-b border-slate-50 py-2.5 last:border-0">
      <div className="mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-lg" style={{ background: `${NAVY}0a` }}>
        <Icon className="h-3 w-3" style={{ color: NAVY }} />
      </div>
      <div>
        <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400">{label}</p>
        <p className="mt-0.5 text-sm text-slate-700">{value}</p>
      </div>
    </div>
  )
}
function LicenseBadge({ lic }: { lic: TenantLicense | null }) {
  const tL = useTranslations("admin.license")
  if (!lic) return (
    <span className="inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-semibold ring-1"
      style={{ color: "#94a3b8", background: "rgba(148,163,184,0.08)", borderColor: "rgba(148,163,184,0.25)" }}>
      <span className="h-1.5 w-1.5 rounded-full bg-slate-300" />
      {tL("no_license")}
    </span>
  )
  if (!lic.is_active) return (
    <span className="inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-semibold ring-1"
      style={{ color: "#94a3b8", background: "rgba(148,163,184,0.08)", borderColor: "rgba(148,163,184,0.25)" }}>
      <span className="h-1.5 w-1.5 rounded-full bg-slate-400" />
      {tL("status_inactive")}
    </span>
  )
  if (lic.is_expired) return (
    <span className="inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-semibold ring-1"
      style={{ color: RED, background: "rgba(220,38,38,0.08)", borderColor: "rgba(220,38,38,0.25)" }}>
      <XCircle className="h-3.5 w-3.5" />
      {tL("status_expired")}
    </span>
  )
  return (
    <span className="inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-semibold ring-1"
      style={{ color: GREEN, background: "rgba(5,150,105,0.08)", borderColor: "rgba(5,150,105,0.25)" }}>
      <CheckCircle2 className="h-3.5 w-3.5" />
      {tL("status_active")}
    </span>
  )
}

// ── Certificate Modal ──────────────────────────────────────────────────────
function LicenseCertificateModal({
  tenant,
  license,
  locale,
  onClose,
}: {
  tenant: Tenant
  license: TenantLicense
  locale: string
  onClose: () => void
}) {
  const isFr      = locale === "fr"
  const isLifetime = license.plan === "lifetime"
  const num        = certNumber(license)
  const isValid    = license.is_active && !license.is_expired

  const CERT_NAVY = "#0f2a5e"
  const GOLD      = "#b8860b"
  const CREAM     = "#fffdf5"

  const txt = isFr ? {
    platform:   "Plateforme de Recouvrement de Créances",
    docTitle:   "Certificat de Licence",
    docSub:     "Logiciel ACX",
    certNoLbl:  "N° de certificat",
    attests:    "Ce certificat atteste que",
    beneficiary:"le titulaire ci-après désigné bénéficie d'une licence d'utilisation",
    planLbl:    isLifetime ? "À vie (Lifetime)" : "Annuelle",
    planDesc:   "de la plateforme logicielle ACX — outil de gestion et de suivi du recouvrement de créances.",
    planCol:    "Formule",
    statusCol:  "Statut",
    issuedCol:  "Date d'émission",
    expiryCol:  isLifetime ? "Validité" : "Date d'expiration",
    unlimited:  "Illimitée ∞",
    valid:      "✓ Actif",
    invalid:    "✗ Inactif",
    sealLine1:  "CERTIFIÉ",
    sealLine2:  "CONFORME",
    signedBy:   "Administrateur Système",
    signedOrg:  "Plateforme ACX",
    legal:      `Ce document électronique certifie la validité de la licence à la date d'émission ci-dessus.
Il est généré automatiquement et a valeur de preuve d'accès à la plateforme ACX.
Document émis le ${new Date().toLocaleDateString("fr-FR", { day:"2-digit", month:"long", year:"numeric" })}.`,
    downloadBtn: "Télécharger PNG",
    downloading: "Génération…",
    closeBtn:   "Fermer",
  } : {
    platform:   "Debt Recovery Platform",
    docTitle:   "License Certificate",
    docSub:     "ACX Software",
    certNoLbl:  "Certificate No.",
    attests:    "This certifies that",
    beneficiary:"the holder named hereafter is granted a",
    planLbl:    isLifetime ? "Lifetime" : "Annual",
    planDesc:   "license to use the ACX software platform — a debt management and recovery tracking tool.",
    planCol:    "Plan",
    statusCol:  "Status",
    issuedCol:  "Issue date",
    expiryCol:  isLifetime ? "Validity" : "Expiry date",
    unlimited:  "Unlimited ∞",
    valid:      "✓ Active",
    invalid:    "✗ Inactive",
    sealLine1:  "CERTIFIED",
    sealLine2:  "GENUINE",
    signedBy:   "System Administrator",
    signedOrg:  "ACX Platform",
    legal:      `This electronic document certifies the validity of the licence as of the issue date above.
It is automatically generated and serves as proof of access to the ACX platform.
Document issued on ${new Date().toLocaleDateString("en-GB", { day:"2-digit", month:"long", year:"numeric" })}.`,
    downloadBtn: "Download PNG",
    downloading: "Generating…",
    closeBtn:   "Close",
  }

  const certRef = useRef<HTMLDivElement>(null)
  const [downloading, setDownloading] = useState(false)

  async function handleDownload() {
    if (!certRef.current) return
    setDownloading(true)
    try {
      const { toPng } = await import("html-to-image")
      const slug = (tenant as any).slug ?? tenant.name.toLowerCase().replace(/\s+/g, "_")
      const dataUrl = await toPng(certRef.current, {
        quality: 1,
        pixelRatio: 3,
        backgroundColor: CREAM,
      })
      const a = document.createElement("a")
      a.href = dataUrl
      a.download = `certificat_acx_${slug}_${new Date().getFullYear()}.png`
      a.click()
    } catch (err) {
      console.error("Certificate download error", err)
    } finally {
      setDownloading(false)
    }
  }

  return (
    <>
      {/* Overlay */}
      <div
        className="fixed inset-0 z-[9000] flex flex-col items-center justify-start overflow-y-auto py-8 px-4"
        style={{ background: "rgba(10,14,40,0.92)", backdropFilter: "blur(10px)" }}
      >
        {/* Barre d'actions */}
        <div className="mb-6 flex items-center gap-3">
          <button
            onClick={handleDownload}
            disabled={downloading}
            className="flex items-center gap-2 rounded-xl px-5 py-2.5 text-sm font-bold text-white shadow-xl transition hover:opacity-90 active:scale-95 disabled:opacity-60"
            style={{ background: `linear-gradient(135deg, ${CERT_NAVY} 0%, #1e40af 100%)` }}
          >
            {downloading
              ? <><span className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" /> {txt.downloading}</>
              : <><ImageDown className="h-4 w-4" /> {txt.downloadBtn}</>
            }
          </button>
          <button
            onClick={onClose}
            className="flex items-center gap-2 rounded-xl border border-white/20 bg-white/10 px-5 py-2.5 text-sm font-semibold text-white backdrop-blur transition hover:bg-white/20"
          >
            <XCircle className="h-4 w-4" />
            {txt.closeBtn}
          </button>
        </div>

        {/* Zone certificat */}
        <div className="flex w-full items-center justify-center">

          {/* Papier certificat A4 */}
          <div
            ref={certRef}
            className="relative w-full max-w-2xl shadow-2xl"
            style={{ background: CREAM, fontFamily: "'Georgia', 'Times New Roman', serif" }}
          >
            {/* Bordure dorée externe */}
            <div className="pointer-events-none absolute inset-3 z-10" style={{ border: `2px solid ${GOLD}` }} />
            {/* Bordure fine interne */}
            <div className="pointer-events-none absolute inset-[18px] z-10" style={{ border: `0.5px solid ${GOLD}55` }} />

            {/* Coins ornementaux */}
            {(["top-[6px] left-[6px]", "top-[6px] right-[6px]", "bottom-[6px] left-[6px]", "bottom-[6px] right-[6px]"] as const).map((cls) => (
              <div key={cls} className={`pointer-events-none absolute ${cls} z-20 flex h-7 w-7 items-center justify-center select-none`}
                style={{ color: GOLD, fontSize: 20, lineHeight: 1 }}>
                ✦
              </div>
            ))}

            {/* Filigrane diagonal VALIDE / VALID */}
            {isValid && (
              <div className="pointer-events-none absolute inset-0 z-0 flex items-center justify-center select-none overflow-hidden">
                <span style={{
                  fontSize: 110,
                  fontWeight: 900,
                  color: `${CERT_NAVY}05`,
                  transform: "rotate(-35deg)",
                  letterSpacing: "0.4em",
                  whiteSpace: "nowrap",
                }}>
                  {isFr ? "VALIDE" : "VALID"}
                </span>
              </div>
            )}

            {/* Contenu */}
            <div className="relative z-10 px-12 py-10 space-y-5">

              {/* ── En-tête ── */}
              <div className="flex items-start justify-between gap-4">
                {/* Logo ACX */}
                <div className="flex flex-col items-center gap-1">
                  <div
                    className="flex h-16 w-16 items-center justify-center rounded-2xl text-xl font-black text-white shadow-lg"
                    style={{ background: `linear-gradient(135deg, ${CERT_NAVY} 0%, #1e40af 100%)` }}
                  >
                    ACX
                  </div>
                  <p className="text-[8px] tracking-wider uppercase" style={{ color: GOLD }}>Official</p>
                </div>

                {/* Titre central */}
                <div className="flex-1 text-center">
                  <p className="text-[9px] uppercase tracking-[0.35em]" style={{ color: GOLD }}>
                    {txt.platform}
                  </p>
                  <h1 className="mt-1.5 text-[22px] font-black uppercase tracking-widest" style={{ color: CERT_NAVY }}>
                    {txt.docTitle}
                  </h1>
                  <p className="mt-0.5 text-[11px] italic" style={{ color: "#64748b" }}>{txt.docSub}</p>
                  {/* Ligne dorée */}
                  <div
                    className="mx-auto mt-2.5 h-[2px] w-40 rounded-full"
                    style={{ background: `linear-gradient(90deg, transparent, ${GOLD}, transparent)` }}
                  />
                </div>

                {/* Numéro de certificat */}
                <div
                  className="rounded-xl px-3 py-2 text-right"
                  style={{ background: `${CERT_NAVY}07`, border: `1px solid ${CERT_NAVY}18` }}
                >
                  <p className="text-[8px] uppercase tracking-widest" style={{ color: GOLD }}>{txt.certNoLbl}</p>
                  <p className="mt-0.5 font-mono text-[11px] font-black" style={{ color: CERT_NAVY }}>{num}</p>
                  <p className="mt-0.5 text-[8px]" style={{ color: "#94a3b8" }}>
                    {isValid
                      ? (isFr ? "En vigueur" : "In force")
                      : (isFr ? "Expiré" : "Expired")}
                  </p>
                </div>
              </div>

              {/* ── Séparateur ── */}
              <div className="flex items-center gap-2">
                <div className="h-px flex-1" style={{ background: `${GOLD}40` }} />
                <span style={{ color: GOLD, fontSize: 12 }}>✦</span>
                <div className="h-px flex-1" style={{ background: `${GOLD}40` }} />
              </div>

              {/* ── Corps central ── */}
              <div className="space-y-3 text-center">
                <p className="text-sm italic" style={{ color: "#64748b" }}>{txt.attests}</p>

                {/* Nom du tenant — vedette */}
                <div
                  className="rounded-xl px-8 py-4"
                  style={{ background: `${CERT_NAVY}07`, border: `1.5px solid ${CERT_NAVY}15` }}
                >
                  <p className="text-[28px] font-black leading-tight" style={{ color: CERT_NAVY }}>
                    {tenant.name}
                  </p>
                  {(tenant.city || tenant.country) && (
                    <p className="mt-1 text-[12px]" style={{ color: "#64748b" }}>
                      {[tenant.city, tenant.country].filter(Boolean).join("  ·  ")}
                    </p>
                  )}
                </div>

                <p className="text-[13px] leading-relaxed" style={{ color: "#374151" }}>
                  {txt.beneficiary}{" "}
                  <strong style={{ color: CERT_NAVY, fontVariant: "small-caps" }}>
                    {txt.planLbl}
                  </strong>{" "}
                  {txt.planDesc}
                </p>
              </div>

              {/* ── Tableau des détails ── */}
              <div
                className="overflow-hidden rounded-xl"
                style={{ border: `1px solid ${GOLD}40` }}
              >
                <div className="grid grid-cols-2">
                  {[
                    { label: txt.planCol,    value: isLifetime ? (isFr ? "Licence à vie" : "Lifetime License") : (isFr ? "Licence annuelle" : "Annual License"), color: CERT_NAVY },
                    { label: txt.statusCol,  value: isValid ? txt.valid : txt.invalid,   color: isValid ? GREEN : RED },
                    { label: txt.issuedCol,  value: fmtDate(license.starts_at, locale),  color: "#374151" },
                    { label: txt.expiryCol,  value: isLifetime ? txt.unlimited : fmtDate(license.expires_at, locale),
                      color: isLifetime ? GREEN : license.is_expired ? RED : CERT_NAVY },
                  ].map(({ label, value, color }, i) => (
                    <div
                      key={i}
                      className="px-5 py-3"
                      style={{
                        background: i % 2 === 0 ? `${CERT_NAVY}04` : `${GOLD}06`,
                        borderRight: i % 2 === 0 ? `1px solid ${GOLD}30` : "none",
                        borderBottom: i < 2 ? `1px solid ${GOLD}30` : "none",
                      }}
                    >
                      <p className="text-[8px] uppercase tracking-widest" style={{ color: "#94a3b8" }}>{label}</p>
                      <p className="mt-0.5 text-[13px] font-bold" style={{ color }}>{value}</p>
                    </div>
                  ))}
                </div>
              </div>

              {/* ── Séparateur bas ── */}
              <div className="flex items-center gap-2">
                <div className="h-px flex-1" style={{ background: `${GOLD}40` }} />
                <span style={{ color: GOLD, fontSize: 12 }}>✦</span>
                <div className="h-px flex-1" style={{ background: `${GOLD}40` }} />
              </div>

              {/* ── Bas de page : sceau + légal + signature ── */}
              <div className="flex items-end justify-between gap-4">

                {/* Sceau officiel */}
                <div className="relative flex-shrink-0">
                  <div
                    className="relative flex h-24 w-24 flex-col items-center justify-center rounded-full"
                    style={{
                      border: `2.5px solid ${CERT_NAVY}`,
                      background: `radial-gradient(circle, ${CERT_NAVY}0a 0%, ${CERT_NAVY}04 100%)`,
                    }}
                  >
                    <div
                      className="pointer-events-none absolute inset-[5px] rounded-full"
                      style={{ border: `1px dashed ${GOLD}80` }}
                    />
                    <Shield className="h-5 w-5 mb-0.5" style={{ color: CERT_NAVY }} />
                    <p className="text-[7px] font-black uppercase tracking-[0.15em] leading-tight text-center px-2"
                      style={{ color: CERT_NAVY }}>
                      {txt.sealLine1}<br />{txt.sealLine2}
                    </p>
                  </div>
                </div>

                {/* Note légale */}
                <p className="flex-1 text-[9px] leading-relaxed italic" style={{ color: "#94a3b8" }}>
                  {txt.legal}
                </p>

                {/* Zone signature */}
                <div className="flex-shrink-0 text-right">
                  {/* Signature réelle — PNG fond transparent */}
                  <img
                    src="/images/signature.png"
                    alt="Signature"
                    style={{
                      height: "58px",
                      width: "auto",
                      maxWidth: "170px",
                      objectFit: "contain",
                      marginLeft: "auto",
                      marginBottom: "2px",
                    }}
                  />
                  <div className="h-[1px] w-36 ml-auto" style={{ background: `${CERT_NAVY}50` }} />
                  <p className="mt-1 text-[10px] font-bold" style={{ color: CERT_NAVY }}>{txt.signedBy}</p>
                  <p className="text-[9px]" style={{ color: GOLD }}>{txt.signedOrg}</p>
                </div>
              </div>

            </div>
          </div>
        </div>
      </div>
    </>
  )
}

// ══════════════════════════════════════════════════════════════════════════
export default function TenantDetailPage() {
  const { id } = useParams<{ id: string }>()
  const tenantId = Number(id)
  const locale   = useLocale()
  const router   = useRouter()
  const tL = useTranslations("admin.license")
  const tE = useTranslations("admin.export")

  const [tenant,   setTenant]   = useState<Tenant | null>(null)
  const [members,  setMembers]  = useState<Membership[]>([])
  const [allUsers, setAllUsers] = useState<User[]>([])
  const [roles,    setRoles]    = useState<Role[]>([])
  const [license,  setLicense]  = useState<TenantLicense | null>(null)

  const [loadingT, setLoadingT] = useState(true)
  const [loadingM, setLoadingM] = useState(true)
  const [loadingL, setLoadingL] = useState(true)
  const [errorT,   setErrorT]   = useState<string | null>(null)
  const [errorM,   setErrorM]   = useState<string | null>(null)

  const [tab,      setTab]      = useState<"users" | "info" | "license">("users")
  const [toggling, setToggling] = useState<number | null>(null)
  const [removing, setRemoving] = useState<number | null>(null)
  const [showCert, setShowCert] = useState(false)

  // ── licence form ─────────────────────────────────────────────────────────
  const [licForm, setLicForm] = useState({
    plan:       "annual" as LicensePlan,
    starts_at:  today(),
    expires_at: addOneYear(today()),
    is_active:  true,
    notes:      "",
  })
  const [licSaving,   setLicSaving]   = useState(false)
  const [licMsg,      setLicMsg]      = useState<{ ok: boolean; text: string } | null>(null)
  const [licDeleting, setLicDeleting] = useState(false)

  // ── export ────────────────────────────────────────────────────────────────
  const [exporting, setExporting] = useState(false)
  const [exportMsg, setExportMsg] = useState<{ ok: boolean; text: string } | null>(null)

  // ── load ──────────────────────────────────────────────────────────────────
  const loadTenant = useCallback(async () => {
    setLoadingT(true); setErrorT(null)
    try { setTenant(await getTenant(tenantId)) }
    catch (e: any) { setErrorT(e?.message ?? "Erreur") }
    finally { setLoadingT(false) }
  }, [tenantId])

  const loadMembers = useCallback(async () => {
    setLoadingM(true); setErrorM(null)
    try { setMembers(await listMembershipsByTenant(tenantId)) }
    catch (e: any) { setErrorM(e?.message ?? "Erreur") }
    finally { setLoadingM(false) }
  }, [tenantId])

  const loadLicense = useCallback(async () => {
    setLoadingL(true)
    try {
      const lic = await getTenantLicense(tenantId)
      setLicense(lic)
      if (lic) {
        setLicForm({
          plan:       lic.plan,
          starts_at:  lic.starts_at,
          expires_at: lic.expires_at ?? "",
          is_active:  lic.is_active,
          notes:      lic.notes,
        })
      }
    } catch {}
    finally { setLoadingL(false) }
  }, [tenantId])

  useEffect(() => {
    loadTenant()
    loadMembers()
    loadLicense()
    listUsers().then(setAllUsers).catch(() => {})
    listRoles().then(setRoles).catch(() => {})
  }, [loadTenant, loadMembers, loadLicense])

  useEffect(() => {
    if (licForm.plan === "annual" && licForm.starts_at) {
      setLicForm(f => ({ ...f, expires_at: addOneYear(f.starts_at) }))
    }
    if (licForm.plan === "lifetime") {
      setLicForm(f => ({ ...f, expires_at: "" }))
    }
  }, [licForm.plan, licForm.starts_at])

  // ── helpers ───────────────────────────────────────────────────────────────
  const getUser = useCallback((m: Membership): User | undefined => {
    const uid = resolveUserId(m)
    const fromAllUsers = allUsers.find((u) => u.id === uid)
    if (fromAllUsers) return fromAllUsers
    if (typeof m.user === "object" && m.user !== null) return m.user as unknown as User
    return undefined
  }, [allUsers])

  const countryName = (code?: string | null) => {
    if (!code) return null
    const c = COUNTRIES.find((x) => x.code === code)
    return c ? (locale === "fr" ? c.fr : c.en) : code
  }

  // ── actions membres ───────────────────────────────────────────────────────
  async function onToggle(m: Membership) {
    setToggling(m.id)
    try {
      await updateMembership(m.id, { status: m.status === "active" ? "suspended" : "active" })
      await loadMembers()
    } catch (e: any) { setErrorM(e?.message ?? "Erreur") }
    finally { setToggling(null) }
  }
  async function onRemove(m: Membership) {
    const u = getUser(m)
    if (!confirm(`Retirer ${displayName(u)} de ce tenant ?`)) return
    setRemoving(m.id)
    try { await deleteMembership(m.id); await loadMembers() }
    catch (e: any) { setErrorM(e?.message ?? "Erreur") }
    finally { setRemoving(null) }
  }

  // ── actions licence ───────────────────────────────────────────────────────
  async function onSaveLicense() {
    setLicSaving(true); setLicMsg(null)
    try {
      const payload = {
        plan:       licForm.plan,
        starts_at:  licForm.starts_at,
        expires_at: licForm.plan === "lifetime" ? null : licForm.expires_at || null,
        is_active:  licForm.is_active,
        notes:      licForm.notes,
      }
      const saved = await saveTenantLicense(tenantId, payload)
      setLicense(saved)
      setLicMsg({ ok: true, text: tL("saved") })
    } catch (e: any) {
      setLicMsg({ ok: false, text: e?.message ?? "Erreur" })
    } finally { setLicSaving(false) }
  }

  async function onDeleteLicense() {
    if (!confirm(tL("confirm_delete"))) return
    setLicDeleting(true)
    try {
      await deleteTenantLicense(tenantId)
      setLicense(null)
      setLicMsg({ ok: true, text: tL("deleted") })
    } catch (e: any) {
      setLicMsg({ ok: false, text: e?.message ?? "Erreur" })
    } finally { setLicDeleting(false) }
  }

  // ── export ────────────────────────────────────────────────────────────────
  async function onExport() {
    if (!tenant) return
    setExporting(true); setExportMsg(null)
    try {
      await exportTenantData(tenantId, tenant.slug)
      setExportMsg({ ok: true, text: tE("success") })
    } catch (e: any) {
      setExportMsg({ ok: false, text: e?.message ?? tE("error") })
    } finally { setExporting(false) }
  }

  // ── loading / error ───────────────────────────────────────────────────────
  if (loadingT) return (
    <div className="flex items-center justify-center gap-2 py-24 text-sm text-slate-400">
      <Loader2 className="h-5 w-5 animate-spin" /> Chargement…
    </div>
  )
  if (errorT || !tenant) return (
    <div className="flex items-start gap-3 rounded-2xl border border-red-100 bg-red-50 px-5 py-4 text-sm text-red-700">
      <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
      {errorT ?? "Tenant introuvable"}
    </div>
  )

  const inputCls = "w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-700 outline-none focus:border-teal-400 focus:ring-2 focus:ring-teal-400/20 transition"

  return (
    <>
      {/* Certificat (modal plein écran) */}
      {showCert && license && tenant && (
        <LicenseCertificateModal
          tenant={tenant}
          license={license}
          locale={locale}
          onClose={() => setShowCert(false)}
        />
      )}

      <div className="space-y-5">

        {/* Retour */}
        <button onClick={() => router.push(`/${locale}/admin/tenants`)}
          className="flex items-center gap-1.5 text-sm text-slate-400 transition hover:text-slate-700">
          <ArrowLeft className="h-4 w-4" /> Retour à la liste
        </button>

        {/* Carte tenant */}
        <div className="flex flex-col gap-4 rounded-2xl border bg-white p-5 shadow-sm sm:flex-row sm:items-center sm:justify-between">
          <div className="flex items-center gap-4">
            <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl text-base font-bold text-white shadow-sm"
              style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}>
              {tenant.name.slice(0, 2).toUpperCase()}
            </div>
            <div>
              <h1 className="text-xl font-bold text-slate-900">{tenant.name}</h1>
              <div className="mt-1 flex flex-wrap items-center gap-2">
                {tenant.plan && (
                  <span className="rounded-full px-2.5 py-0.5 text-[11px] font-semibold ring-1"
                    style={{ color: NAVY, background: `${NAVY}10`, borderColor: `${NAVY}25` }}>
                    {tenant.plan}
                  </span>
                )}
                <span className="flex items-center gap-1 text-[12px] font-medium"
                  style={{ color: tenant.status === "active" ? GREEN : "#94a3b8" }}>
                  <span className="h-1.5 w-1.5 rounded-full"
                    style={{ backgroundColor: tenant.status === "active" ? GREEN : "#94a3b8" }} />
                  {tenant.status === "active" ? "Actif" : "Suspendu"}
                </span>
                {!loadingL && <LicenseBadge lic={license} />}
                {tenant.city && (
                  <span className="text-[12px] text-slate-400">
                    · {tenant.city}{tenant.country ? `, ${countryName(tenant.country)}` : ""}
                  </span>
                )}
              </div>
            </div>
          </div>
          <button onClick={() => router.push(`/${locale}/admin/tenants/${tenant.id}/edit`)}
            className="flex items-center gap-2 rounded-xl border bg-white px-4 py-2 text-sm font-medium text-slate-700 shadow-sm transition hover:bg-slate-50 active:scale-95">
            <Pencil className="h-3.5 w-3.5" /> Modifier
          </button>
        </div>

        {/* Onglets */}
        <div className="flex gap-1 rounded-xl border bg-white p-1 shadow-sm w-fit flex-wrap">
          {([
            { id: "users",   label: "Utilisateurs", icon: Users,    badge: members.length as number | undefined },
            { id: "info",    label: "Informations",  icon: Building2, badge: undefined as number | undefined },
            { id: "license", label: tL("tab"),        icon: Key,     badge: undefined as number | undefined },
          ] as const).map(({ id: tid, label, icon: Icon, badge }) => (
            <button key={tid} onClick={() => setTab(tid)}
              className="flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium transition-all"
              style={tab === tid ? { backgroundColor: NAVY, color: "#fff" } : { color: "#64748b" }}>
              <Icon className="h-4 w-4" />
              {label}
              {badge !== undefined && (
                <span className="rounded-full px-1.5 py-0.5 text-[10px] font-bold"
                  style={tab === tid
                    ? { background: "rgba(255,255,255,0.2)", color: "#fff" }
                    : { background: `${NAVY}12`, color: NAVY }}>
                  {badge}
                </span>
              )}
            </button>
          ))}
        </div>

        {/* ── ONGLET UTILISATEURS ────────────────────────────────────────── */}
        {tab === "users" && (
          <div className="rounded-2xl border bg-white shadow-sm overflow-hidden">
            <div className="flex items-center justify-between gap-3 border-b px-5 py-4">
              <div>
                <p className="font-semibold text-slate-800">Membres du tenant</p>
                <p className="text-xs text-slate-400 mt-0.5">
                  {members.length} utilisateur{members.length > 1 ? "s" : ""} rattaché{members.length > 1 ? "s" : ""}
                </p>
              </div>
              <div className="flex items-center gap-2">
                <button onClick={loadMembers}
                  className="flex h-9 w-9 items-center justify-center rounded-xl border bg-white text-slate-500 shadow-sm transition hover:bg-slate-50">
                  <RefreshCw className="h-3.5 w-3.5" />
                </button>
                <button
                  onClick={() => router.push(`/${locale}/admin/tenants/${tenantId}/users/new`)}
                  className="flex items-center gap-2 rounded-xl px-4 py-2.5 text-sm font-semibold text-white shadow-sm transition active:scale-95 hover:opacity-90"
                  style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}>
                  <UserPlus className="h-4 w-4" /> Ajouter un utilisateur
                </button>
              </div>
            </div>
            {errorM && (
              <div className="mx-5 mt-4 flex items-start gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700">
                <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />{errorM}
              </div>
            )}
            {loadingM ? (
              <div className="flex items-center justify-center gap-2 py-16 text-sm text-slate-400">
                <Loader2 className="h-4 w-4 animate-spin" /> Chargement…
              </div>
            ) : members.length === 0 ? (
              <div className="flex flex-col items-center justify-center gap-3 py-16">
                <Users className="h-10 w-10 text-slate-200" />
                <p className="text-sm text-slate-400">Aucun utilisateur dans ce tenant</p>
                <button
                  onClick={() => router.push(`/${locale}/admin/tenants/${tenantId}/users/new`)}
                  className="mt-1 flex items-center gap-2 rounded-xl px-4 py-2.5 text-sm font-semibold text-white"
                  style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}>
                  <UserPlus className="h-4 w-4" /> Ajouter le premier utilisateur
                </button>
              </div>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b bg-slate-50/60">
                      {["Utilisateur", "Email / Login", "Rôle", "Statut", "Actions"].map((h) => (
                        <th key={h} className="px-5 py-3 text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400 last:text-right">{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-50">
                    {members.map((m) => {
                      const u = getUser(m)
                      const name = displayName(u)
                      const roleNames = roles.filter((r) => (m.roles ?? []).includes(r.id)).map((r) => r.label)
                      return (
                        <tr key={m.id} className="transition-colors hover:bg-slate-50/60">
                          <td className="px-5 py-4">
                            <div className="flex items-center gap-3">
                              <UserAvatar name={name} />
                              <div>
                                <p className="font-semibold text-slate-800">{name}</p>
                                {m.is_owner && (
                                  <span className="inline-flex items-center gap-1 text-[10px] font-semibold" style={{ color: TEAL2 }}>
                                    <Shield className="h-2.5 w-2.5" /> Propriétaire
                                  </span>
                                )}
                              </div>
                            </div>
                          </td>
                          <td className="px-5 py-4">
                            <div className="space-y-0.5">
                              {u?.email && <p className="flex items-center gap-1.5 text-[12px] text-slate-600"><Mail className="h-3 w-3 shrink-0 text-slate-400" />{u.email}</p>}
                              {u?.username && <p className="font-mono text-[11px] text-slate-400">@{u.username}</p>}
                              {!u?.email && !u?.username && <span className="text-slate-400">—</span>}
                            </div>
                          </td>
                          <td className="px-5 py-4">
                            {roleNames.length > 0
                              ? roleNames.map((r) => (
                                  <span key={r} className="mr-1 inline-flex rounded-full px-2 py-0.5 text-[11px] font-semibold ring-1"
                                    style={{ color: NAVY, background: `${NAVY}0c`, borderColor: `${NAVY}20` }}>{r}</span>
                                ))
                              : <span className="text-[12px] text-slate-400">—</span>}
                          </td>
                          <td className="px-5 py-4"><MemberBadge status={m.status} /></td>
                          <td className="px-5 py-4">
                            <div className="flex items-center justify-end gap-2">
                              <button onClick={() => router.push(`/${locale}/admin/tenants/${tenantId}/users/${resolveUserId(m)}/edit?mid=${m.id}`)}
                                className="flex items-center gap-1.5 rounded-lg border bg-white px-3 py-1.5 text-xs font-semibold text-slate-600 shadow-sm transition hover:bg-slate-50 active:scale-95">
                                <Pencil className="h-3 w-3" /> Modifier
                              </button>
                              <button onClick={() => onToggle(m)} disabled={toggling === m.id}
                                className="flex h-8 w-8 items-center justify-center rounded-lg border bg-white text-slate-500 shadow-sm transition hover:text-slate-800 active:scale-95 disabled:opacity-50">
                                {toggling === m.id ? <Loader2 className="h-3.5 w-3.5 animate-spin" />
                                  : m.status === "active" ? <Ban className="h-3.5 w-3.5" />
                                  : <UserCheck className="h-3.5 w-3.5 text-emerald-500" />}
                              </button>
                              <button onClick={() => onRemove(m)} disabled={removing === m.id}
                                className="flex h-8 w-8 items-center justify-center rounded-lg border border-red-100 bg-red-50 text-red-500 shadow-sm transition hover:bg-red-100 active:scale-95 disabled:opacity-50">
                                {removing === m.id ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Trash2 className="h-3.5 w-3.5" />}
                              </button>
                            </div>
                          </td>
                        </tr>
                      )
                    })}
                  </tbody>
                </table>
              </div>
            )}
            {!loadingM && members.length > 0 && (
              <div className="border-t px-5 py-3 text-[11px] text-slate-400">
                {members.length} membre{members.length > 1 ? "s" : ""}
              </div>
            )}
          </div>
        )}

        {/* ── ONGLET INFORMATIONS ────────────────────────────────────────── */}
        {tab === "info" && (
          <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
            <div className="rounded-2xl border bg-white p-6 shadow-sm">
              <p className="mb-3 text-[10px] font-bold uppercase tracking-widest text-slate-400">Identité</p>
              <InfoRow icon={Building2}  label="Nom"     value={tenant.name} />
              <InfoRow icon={CreditCard} label="Plan"    value={tenant.plan} />
              <InfoRow icon={CreditCard} label="Devise"  value={tenant.currency} />
              <InfoRow icon={Clock}      label="Créé le" value={fmtDate(tenant.created_at, locale)} />
            </div>
            <div className="rounded-2xl border bg-white p-6 shadow-sm">
              <p className="mb-3 text-[10px] font-bold uppercase tracking-widest text-slate-400">Localisation</p>
              <InfoRow icon={Globe}  label="Pays"        value={countryName(tenant.country)} />
              <InfoRow icon={MapPin} label="Ville"       value={tenant.city} />
              <InfoRow icon={MapPin} label="Adresse"     value={[tenant.address_line1, tenant.address_line2].filter(Boolean).join(", ")} />
              <InfoRow icon={MapPin} label="Code postal" value={tenant.postal_code} />
              <InfoRow icon={Clock}  label="Fuseau"      value={tenant.timezone} />
            </div>
            <div className="rounded-2xl border bg-white p-6 shadow-sm lg:col-span-2">
              <p className="mb-3 text-[10px] font-bold uppercase tracking-widest text-slate-400">Contact</p>
              <div className="grid sm:grid-cols-3 gap-2">
                <InfoRow icon={Mail}  label="Email"   value={tenant.email} />
                <InfoRow icon={Phone} label="Tél."    value={tenant.phone} />
                <InfoRow icon={Globe} label="Website" value={tenant.website} />
              </div>
              {!tenant.email && !tenant.phone && !tenant.website && (
                <p className="text-sm text-slate-400">Aucune information de contact renseignée.</p>
              )}
            </div>
          </div>
        )}

        {/* ── ONGLET LICENCE ─────────────────────────────────────────────── */}
        {tab === "license" && (
          <div className="space-y-4">

            {/* ── Carte statut actuel ── */}
            {loadingL ? (
              <div className="flex items-center gap-2 rounded-2xl border bg-white px-5 py-4 text-sm text-slate-400 shadow-sm">
                <Loader2 className="h-4 w-4 animate-spin" /> Chargement de la licence…
              </div>
            ) : license ? (
              /* Licence existante */
              <div
                className="rounded-2xl border bg-white shadow-sm overflow-hidden"
                style={{ borderColor: license.is_active && !license.is_expired ? `${GREEN}30` : `${RED}25` }}
              >
                {/* Bande colorée en haut */}
                <div
                  className="h-1 w-full"
                  style={{
                    background: license.is_active && !license.is_expired
                      ? `linear-gradient(90deg, ${GREEN}, #34d399)`
                      : `linear-gradient(90deg, ${RED}, #f87171)`,
                  }}
                />
                <div className="px-5 py-4 flex flex-wrap items-center gap-4">

                  {/* Icône + statut */}
                  <div className="flex items-center gap-3">
                    <div
                      className="flex h-10 w-10 items-center justify-center rounded-xl"
                      style={{
                        background: license.is_active && !license.is_expired
                          ? "rgba(5,150,105,0.1)" : "rgba(220,38,38,0.08)",
                      }}
                    >
                      <Key className="h-5 w-5" style={{
                        color: license.is_active && !license.is_expired ? GREEN : RED,
                      }} />
                    </div>
                    <div>
                      <LicenseBadge lic={license} />
                      <p className="mt-0.5 text-[11px] text-slate-500">
                        {license.plan === "annual" ? tL("plan_annual") : tL("plan_lifetime")}
                        {" · "}
                        <span className="font-mono">{certNumber(license)}</span>
                      </p>
                    </div>
                  </div>

                  {/* Dates */}
                  <div className="flex flex-wrap items-center gap-4 text-sm flex-1 min-w-0">
                    <div className="flex items-center gap-1.5">
                      <CalendarClock className="h-3.5 w-3.5 text-slate-400" />
                      <span className="text-slate-500 text-xs">{tL("starts_at")} :</span>
                      <span className="font-medium text-slate-700">{fmtDateShort(license.starts_at, locale)}</span>
                    </div>
                    {license.plan !== "lifetime" && (
                      <>
                        <span className="text-slate-300">→</span>
                        <div className="flex items-center gap-1.5">
                          <CalendarClock className="h-3.5 w-3.5" style={{ color: license.is_expired ? RED : NAVY }} />
                          <span className="text-slate-500 text-xs">{tL("expires_at")} :</span>
                          <span className="font-medium" style={{ color: license.is_expired ? RED : NAVY }}>
                            {fmtDateShort(license.expires_at, locale)}
                          </span>
                          {(license.days_remaining ?? 0) > 0 && (
                            <span className="rounded-full bg-slate-100 px-2 py-0.5 text-[10px] font-semibold text-slate-500">
                              {tL("days_left", { n: license.days_remaining ?? 0 })}
                            </span>
                          )}
                        </div>
                      </>
                    )}
                    {license.plan === "lifetime" && (
                      <div className="flex items-center gap-1.5 text-teal-600">
                        <InfinityIcon className="h-4 w-4" />
                        <span className="text-xs font-semibold">{tL("plan_lifetime")}</span>
                      </div>
                    )}
                  </div>

                  {/* Actions rapides */}
                  <div className="flex items-center gap-2 flex-shrink-0">
                    <button
                      onClick={() => setShowCert(true)}
                      className="flex items-center gap-1.5 rounded-xl border px-3 py-1.5 text-xs font-semibold transition hover:bg-slate-50 active:scale-95"
                      style={{ borderColor: `${NAVY}25`, color: NAVY }}
                    >
                      <Award className="h-3.5 w-3.5" />
                      Certificat
                    </button>
                    <button
                      onClick={onDeleteLicense}
                      disabled={licDeleting}
                      className="flex h-8 w-8 items-center justify-center rounded-xl border border-red-100 bg-red-50 text-red-400 shadow-sm transition hover:bg-red-100 active:scale-95 disabled:opacity-50"
                    >
                      {licDeleting ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Trash2 className="h-3.5 w-3.5" />}
                    </button>
                  </div>
                </div>
              </div>
            ) : (
              /* Aucune licence */
              <div className="flex items-center gap-3 rounded-2xl border border-dashed border-slate-200 bg-slate-50 px-5 py-4">
                <div className="flex h-9 w-9 items-center justify-center rounded-xl bg-slate-200">
                  <Key className="h-4 w-4 text-slate-400" />
                </div>
                <div>
                  <p className="text-sm font-semibold text-slate-700">{tL("no_license")}</p>
                  <p className="text-xs text-slate-400">{tL("no_license_hint")}</p>
                </div>
              </div>
            )}

            {/* ── Formulaire licence ── */}
            <div className="rounded-2xl border bg-white shadow-sm overflow-hidden">
              {/* En-tête formulaire */}
              <div className="flex items-center gap-2 border-b px-5 py-3"
                style={{ background: `${NAVY}04` }}>
                <Key className="h-4 w-4" style={{ color: NAVY }} />
                <p className="text-sm font-semibold text-slate-700">
                  {license ? tL("form_title_edit") : tL("form_title_create")}
                </p>
              </div>

              <div className="p-5 space-y-4">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">

                  {/* Formule */}
                  <div>
                    <label className="block text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1.5">
                      {tL("plan_label")} *
                    </label>
                    <div className="flex gap-2">
                      {(["annual", "lifetime"] as const).map((p) => (
                        <button
                          key={p}
                          onClick={() => setLicForm(f => ({ ...f, plan: p }))}
                          className="flex-1 flex items-center justify-center gap-1.5 rounded-xl border py-2 text-xs font-bold transition"
                          style={licForm.plan === p
                            ? { background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)`, color: "#fff", borderColor: NAVY }
                            : { borderColor: "#e2e8f0", color: "#64748b", background: "#f8fafc" }}
                        >
                          {p === "annual" ? <CalendarClock className="h-3.5 w-3.5" /> : <InfinityIcon className="h-3.5 w-3.5" />}
                          {p === "annual" ? tL("plan_annual") : tL("plan_lifetime")}
                        </button>
                      ))}
                    </div>
                  </div>

                  {/* Statut */}
                  <div>
                    <label className="block text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1.5">
                      Statut
                    </label>
                    <div className="flex gap-2">
                      {([true, false] as const).map((v) => (
                        <button
                          key={String(v)}
                          onClick={() => setLicForm(f => ({ ...f, is_active: v }))}
                          className="flex-1 flex items-center justify-center gap-1.5 rounded-xl border py-2 text-xs font-bold transition"
                          style={licForm.is_active === v
                            ? { background: v ? "rgba(5,150,105,0.1)" : "rgba(220,38,38,0.08)", color: v ? GREEN : RED, borderColor: v ? GREEN : RED }
                            : { borderColor: "#e2e8f0", color: "#64748b", background: "#f8fafc" }}
                        >
                          {v ? <CheckCircle2 className="h-3.5 w-3.5" /> : <XCircle className="h-3.5 w-3.5" />}
                          {v ? tL("status_active") : tL("status_inactive")}
                        </button>
                      ))}
                    </div>
                  </div>

                  {/* Date début */}
                  <div>
                    <label className="block text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1.5">
                      {tL("starts_at")} *
                    </label>
                    <input
                      type="date"
                      className={inputCls}
                      value={licForm.starts_at}
                      onChange={(e) => setLicForm(f => ({ ...f, starts_at: e.target.value }))}
                    />
                  </div>

                  {/* Date expiration (masquée si lifetime) */}
                  {licForm.plan === "annual" ? (
                    <div>
                      <label className="block text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1.5">
                        {tL("expires_at")} *
                      </label>
                      <input
                        type="date"
                        className={inputCls}
                        value={licForm.expires_at}
                        onChange={(e) => setLicForm(f => ({ ...f, expires_at: e.target.value }))}
                      />
                    </div>
                  ) : (
                    <div className="flex items-center justify-center rounded-xl border border-dashed border-teal-200 bg-teal-50 py-2">
                      <span className="flex items-center gap-1.5 text-xs font-semibold text-teal-700">
                        <InfinityIcon className="h-4 w-4" /> Pas d'expiration
                      </span>
                    </div>
                  )}

                  {/* Notes */}
                  <div className="sm:col-span-2">
                    <label className="block text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1.5">
                      {tL("notes_label")}
                    </label>
                    <textarea
                      className={inputCls + " resize-none"}
                      rows={2}
                      placeholder={locale === "fr" ? "Notes internes (optionnel)…" : "Internal notes (optional)…"}
                      value={licForm.notes}
                      onChange={(e) => setLicForm(f => ({ ...f, notes: e.target.value }))}
                    />
                  </div>
                </div>

                {/* Retour */}
                {licMsg && (
                  <p className={`text-sm font-medium ${licMsg.ok ? "text-emerald-600" : "text-red-600"}`}>
                    {licMsg.ok ? "✓" : "✗"} {licMsg.text}
                  </p>
                )}

                {/* Bouton Enregistrer */}
                <div className="flex justify-end">
                  <button
                    onClick={onSaveLicense}
                    disabled={licSaving}
                    className="flex items-center gap-2 rounded-xl px-5 py-2 text-sm font-bold text-white shadow-sm transition hover:opacity-90 disabled:opacity-50 active:scale-95"
                    style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}
                  >
                    {licSaving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Key className="h-4 w-4" />}
                    {licSaving ? tL("saving") : tL("save")}
                  </button>
                </div>
              </div>
            </div>

            {/* ── Export données ── */}
            <div className="rounded-2xl border bg-white shadow-sm">
              <div className="flex items-center justify-between gap-4 px-5 py-4 flex-wrap">
                <div className="flex items-center gap-3">
                  <div className="flex h-9 w-9 items-center justify-center rounded-xl"
                    style={{ background: `${TEAL}15` }}>
                    <FileArchive className="h-4 w-4" style={{ color: TEAL2 }} />
                  </div>
                  <div>
                    <p className="text-sm font-semibold text-slate-800">{tE("title")}</p>
                    <p className="text-xs text-slate-400">{tE("subtitle")}</p>
                    {exportMsg && (
                      <p className={`mt-1 text-xs font-medium ${exportMsg.ok ? "text-emerald-600" : "text-red-600"}`}>
                        {exportMsg.ok ? "✓" : "✗"} {exportMsg.text}
                      </p>
                    )}
                  </div>
                </div>
                <button
                  onClick={onExport}
                  disabled={exporting}
                  className="flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-bold text-white shadow-sm transition hover:opacity-90 disabled:opacity-50 active:scale-95"
                  style={{ background: `linear-gradient(135deg, ${TEAL} 0%, ${TEAL2} 100%)` }}
                >
                  {exporting
                    ? <><Loader2 className="h-4 w-4 animate-spin" /> {tE("exporting")}</>
                    : <><Download className="h-4 w-4" /> {tE("btn")}</>
                  }
                </button>
              </div>
            </div>

          </div>
        )}
      </div>
    </>
  )
}
