/**
 * LicencePage.tsx
 *
 * React component replacing settings-parts/settings-licence.php.
 *
 * PHP still wraps the section in the settings <form>, so form inputs
 * rendered here are naturally submitted with the existing form flow.
 *
 * Data injected by PHP via wp_add_inline_script('pdfib-licence-page', '...', 'before')
 * into window.pdfibLicenceData.
 *
 * window.pdfBuilderLicense (existing localisation) is still available for nonces.
 */

import React, { useState, useRef, useCallback, useEffect } from 'react';

// ─── Types ────────────────────────────────────────────────────────────────────

export interface LicenceData {
  isPremium: boolean;
  isActive: boolean;
  badgeClass: 'badge-premium' | 'badge-free';
  badgeText: string;
  maskedKey: string;
  displayKey: string;
  licenseStatus: string;
  licenseCustomer: string;
  licenseEmail: string;
  licenseActivations: number | null;
  expiresLabel: string;
  daysLeftLabel: string;
  daysLeftClass: string;
  expired: boolean;
  expiringSoon: boolean;
  isLifetime: boolean;
  activateButtonText: string;
  activateTitle: string;
  activateHelp: string;
  inputPlaceholder: string;
  purchaseUrl: string;
  supportUrl: string;
  docsUrl: string;
  renewalUrl: string;
  unsubscribeUrl: string;
  emailRemindersEnabled: boolean;
  reminderEmail: string;
  adminEmail: string;
  siteUrl: string;
  licenseType?: string;
  siteCount?: number;
  activationLimit?: number | string;
}

declare global {
  interface Window {
    pdfibLicenceData?: LicenceData;
    pdfBuilderLicense?: {
      ajaxNonce: string;
      deactivateNonce: string;
      ajaxUrl: string;
      btnText: string;
    };
  }
}

// ─── EDD key regex ────────────────────────────────────────────────────────────

const EDD_REGEX = /^[a-f0-9]{32}$/i;

type NoticeType = 'error' | 'success' | 'loading' | 'idle';

// ─── Deactivation modal ───────────────────────────────────────────────────────

interface DeactivateModalProps {
  onClose: () => void;
  onConfirm: () => void;
}

const DeactivateModal: React.FC<DeactivateModalProps> = ({ onClose, onConfirm }) => (
  <div
    id="deactivate-modal-overlay"
    className="pdfb-canvas-modal-overlay"
    style={{ display: 'flex', zIndex: 10002 }}
    onClick={(e) => {
      if ((e.target as HTMLElement).id === 'deactivate-modal-overlay') onClose();
    }}
  >
    <div className="pdfb-canvas-modal-container" style={{ maxWidth: 450 }}>
      <div className="pdfb-canvas-modal-header">
        <h3>⚠️ Confirmer la désactivation</h3>
        <button type="button" className="pdfb-canvas-modal-close" onClick={onClose}>
          &times;
        </button>
      </div>
      <div className="pdfb-canvas-modal-body" style={{ textAlign: 'center', padding: 30 }}>
        <div style={{ fontSize: 48, marginBottom: 20 }}>⚠️</div>
        <h4 style={{ marginBottom: 15, color: '#23282d' }}>
          Êtes-vous sûr de vouloir désactiver la licence ?
        </h4>
        <p style={{ marginBottom: 20, color: '#666', lineHeight: 1.5 }}>Cette action va :</p>
        <ul style={{ textAlign: 'left', color: '#666', margin: '0 0 25px 0', paddingLeft: 20 }}>
          <li>Supprimer votre clé de licence</li>
          <li>Repasser en mode gratuit</li>
          <li>Perdre l&apos;accès aux options PRO</li>
        </ul>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'center' }}>
          <button
            type="button"
            className="button button-secondary"
            onClick={onClose}
            style={{ padding: '10px 20px' }}
          >
            Annuler
          </button>
          <button
            type="button"
            className="button button-danger"
            onClick={onConfirm}
            style={{ padding: '10px 20px', background: '#dc3545', borderColor: '#dc3545' }}
          >
            Désactiver
          </button>
        </div>
      </div>
    </div>
  </div>
);

// ─── Feature comparison data ───────────────────────────────────────────────────
// [label, free, premium, alwaysVisible]
// Source vérifiée : canvas, hooks premium et renderer de comparaison partagé.
const FEATURE_ROWS: Array<[string, string, string, boolean]> = [
  ['Éditeur visuel drag & drop',               '✓',                               '✓',                               true],
  ['Génération PDF',                           'PDF',                             'PDF',                             true],
  ['Éléments standards',                       'Texte, image, ligne, rectangle',  'Texte, image, ligne, rectangle',  true],
  ['Types de document',                        'Facture, devis',                  'Facture, devis, bon de commande, avoir, relevé, contrat', true],
  ['Modèles de texte dynamique',               '3 modèles',                       '36 modèles',                      true],
  ['Modèles de mentions',                      '3 modèles',                       '21 modèles',                      true],
  ['Intégration WooCommerce',                  '✓',                               '✓',                               true],
  ['Qualité d\'export max',                   '150 DPI',                         '300 & 600 DPI',                   false],
  ['Formats d\'export',                       'PDF',                             'PDF, PNG, JPG',                   false],
  ['Formats de page',                         'A4 portrait',                     'A3, Letter, Legal + paysage',     false],
  ['Galerie de modèles avancés',              '—',                               '✓',                               false],
  ['Navigation grille, snap & guides',        '—',                               '✓',                               false],
  ['Sélection multiple & mode groupe',        '—',                               '✓',                               false],
  ['Raccourcis clavier',                      '—',                               '✓',                               false],
  ['Couleurs canvas avancées',                '—',                               '✓',                               false],
  ['Thèmes prédéfinis de l’éditeur',          '—',                               '✓',                               false],
];

// ─── Main component ───────────────────────────────────────────────────────────

const LicencePage: React.FC = () => {
  const d = window.pdfibLicenceData!;
  const lic = window.pdfBuilderLicense;

  // ── Local state ──────────────────────────────────────────────────────────

  const [keyInput, setKeyInput] = useState('');
  const [noticeMsg, setNoticeMsg] = useState('');
  const [noticeType, setNoticeType] = useState<NoticeType>('idle');
  const [activating, setActivating] = useState(false);
  const [showDeactivateModal, setShowDeactivateModal] = useState(false);
  const [copyLabel, setCopyLabel] = useState('Copier');
  const [detailsOpen, setDetailsOpen] = useState(false);
  const [compareOpen, setCompareOpen] = useState(false);
  const [globalNotice, setGlobalNotice] = useState<{ type: 'success' | 'error'; msg: string } | null>(null);

  const inputRef = useRef<HTMLInputElement>(null);

  // ── Key validation ───────────────────────────────────────────────────────

  const keyValid = EDD_REGEX.test(keyInput.trim());
  const keyTouched = keyInput.trim().length > 0;

  // ── Activate ─────────────────────────────────────────────────────────────

  const handleActivate = useCallback(async () => {
    const key = keyInput.trim();
    if (!key) {
      setNoticeMsg('⚠ Veuillez saisir votre clé de licence.');
      setNoticeType('error');
      inputRef.current?.focus();
      return;
    }
    if (!EDD_REGEX.test(key)) {
      setNoticeMsg('⚠ Format invalide — une clé EDD comporte 32 caractères hexadécimaux (0-9, a-f).');
      setNoticeType('error');
      inputRef.current?.focus();
      return;
    }

    setActivating(true);
    setNoticeMsg('⏳ Vérification auprès du serveur de licences…');
    setNoticeType('loading');

    const formData = new FormData();
    formData.append('action', 'pdfib_activate_license');
    formData.append('nonce', lic?.ajaxNonce ?? '');
    formData.append('license_key', key);

    try {
      const res = await fetch(lic?.ajaxUrl ?? '/wp-admin/admin-ajax.php', {
        method: 'POST',
        body: formData,
      });
      const data = await res.json();
      if (data.success) {
        setNoticeMsg('✓ ' + data.data.message);
        setNoticeType('success');
        setTimeout(() => window.location.reload(), 1500);
      } else {
        setNoticeMsg('✗ ' + (data.data?.message ?? 'Erreur inconnue'));
        setNoticeType('error');
        setActivating(false);
      }
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : String(err);
      setNoticeMsg('✗ Erreur réseau : ' + msg);
      setNoticeType('error');
      setActivating(false);
    }
  }, [keyInput, lic]);

  // ── Deactivate ────────────────────────────────────────────────────────────

  const handleConfirmDeactivate = useCallback(async () => {
    setShowDeactivateModal(false);

    const body = 'action=pdfib_deactivate_license&nonce=' +
      encodeURIComponent(lic?.deactivateNonce ?? '');

    try {
      const xhr = new XMLHttpRequest();
      xhr.open('POST', lic?.ajaxUrl ?? '/wp-admin/admin-ajax.php', true);
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      xhr.onload = () => {
        if (xhr.status !== 200) {
          setGlobalNotice({ type: 'error', msg: '✗ Erreur serveur (statut: ' + xhr.status + ')' });
          return;
        }
        try {
          const resp = JSON.parse(xhr.responseText);
          if (resp.success) {
            setGlobalNotice({ type: 'success', msg: '✓ Licence désactivée avec succès. Rafraîchissement…' });
            setTimeout(() => window.location.reload(), 1500);
          } else {
            setGlobalNotice({ type: 'error', msg: '✗ ' + (resp.message ?? 'Erreur lors de la désactivation') });
          }
        } catch {
          setGlobalNotice({ type: 'error', msg: '✗ Réponse invalide du serveur.' });
        }
      };
      xhr.onerror = () => setGlobalNotice({ type: 'error', msg: '✗ Erreur de connexion' });
      xhr.send(body);
    } catch {
      setGlobalNotice({ type: 'error', msg: '✗ Erreur inattendue.' });
    }
  }, [lic]);

  // ── Copy key ──────────────────────────────────────────────────────────────

  const handleCopyKey = useCallback(() => {
    if (!navigator.clipboard || !d.displayKey) {
      setCopyLabel('Copie impossible');
      return;
    }
    navigator.clipboard.writeText(d.displayKey)
      .then(() => {
        setCopyLabel('Clé copiée');
        setTimeout(() => setCopyLabel('Copier'), 2000);
      })
      .catch(() => setCopyLabel('Copie impossible'));
  }, [d.displayKey]);

  // ── Focus input ───────────────────────────────────────────────────────────

  const handleFocusInput = useCallback(() => {
    document.getElementById('activate-section')?.scrollIntoView({ behavior: 'smooth', block: 'start' });
    setTimeout(() => inputRef.current?.focus(), 250);
  }, []);

  // ── Animation CSS injection ───────────────────────────────────────────────

  useEffect(() => {
    const id = 'pdfib-licence-anim';
    if (document.getElementById(id)) return;
    const s = document.createElement('style');
    s.id = id;
    s.textContent = [
      '@keyframes pdfib-shimmer{0%{background-position:-200% center}100%{background-position:200% center}}',
      '@keyframes pdfib-glow{0%,100%{box-shadow:0 0 8px rgba(246,178,14,.35),0 2px 15px rgba(0,0,0,.08)}50%{box-shadow:0 0 22px rgba(246,178,14,.7),0 2px 15px rgba(0,0,0,.08)}}',
      '@keyframes pdfib-glow-orange{0%,100%{box-shadow:0 0 8px rgba(255,107,0,.25),0 2px 15px rgba(0,0,0,.06)}50%{box-shadow:0 0 20px rgba(255,107,0,.55),0 2px 15px rgba(0,0,0,.06)}}',
      '@keyframes pdfib-pulse{0%,100%{opacity:1}50%{opacity:.82}}',
    ].join('');
    document.head.appendChild(s);
    return () => { document.getElementById(id)?.remove(); };
  }, []);

  // ── Notice colour ─────────────────────────────────────────────────────────

  const noticeColor =
    noticeType === 'error' ? '#cc1818' :
    noticeType === 'success' ? '#1a7e2e' : '#888';

  // ─── Render ───────────────────────────────────────────────────────────────

  return (
    <section id="licence" aria-label="Gestion de la licence">

      {/* Global notice (deactivation result) */}
      {globalNotice && (
        <div className={`notice ${globalNotice.type === 'success' ? 'notice-success' : 'notice-error'} inline`}>
          <p>{globalNotice.msg}</p>
        </div>
      )}

      {/* Header */}
      <div className="pdfb-license-header">
        <div className="pdfb-license-header-content">
          <div className="pdfb-license-header-top">
            <h2 className="license-main-title">Gestion de la licence</h2>
            <span className={`pdfb-license-status-badge ${d.badgeClass}`}>{d.badgeText}</span>
          </div>
          <p className="pdfb-license-subtitle">
            Activez votre clé, consultez son état et gérez les rappels avant expiration.
          </p>
        </div>

        <div className="pdfb-license-quick-actions">
          {!d.isActive ? (
            <button
              type="button"
              id="pdfib-focus-license-key"
              className="pdfb-license-btn-primary-large"
              onClick={handleFocusInput}
            >
              Entrer ma clé de licence
            </button>
          ) : (
            <button
              type="button"
              id="deactivate-license-btn"
              className="pdfb-license-btn-secondary-large"
              onClick={() => setShowDeactivateModal(true)}
            >
              Désactiver la licence
            </button>
          )}
        </div>
      </div>

      {/* Expiry notices */}
      {d.expired && (
        <div className="notice notice-error inline">
          <p><strong>Licence expirée.</strong> {d.daysLeftLabel}.</p>
        </div>
      )}
      {d.expiringSoon && !d.isLifetime && !d.expired && (
        <div className="notice notice-warning inline">
          <p><strong>Expiration imminente.</strong> {d.daysLeftLabel}.</p>
        </div>
      )}

      {/* Actions section */}
      <div className="pdfb-license-actions-section">

        {/* Activate card */}
        <div id="activate-section" className="pdfb-license-action-card">
          <div className="pdfb-license-action-card-header">
            <h3>{d.activateTitle}</h3>
            <p>{d.activateHelp}</p>
          </div>

          <div className="pdfb-license-action-card-content">

            {/* Steps — uniquement si pas premium */}
            {!d.isPremium && (
              <div style={{
                display: 'grid', gridTemplateColumns: '1fr 1fr 1fr',
                gap: 8, marginBottom: 18,
              }}>
                {[
                  { n: '1', label: 'Choisissez votre formule', desc: 'Mensuel · Annuel · À vie' },
                  { n: '2', label: 'Obtenez votre clé',   desc: '32 caractères — reçue par email' },
                  { n: '3', label: 'Activez votre clé',       desc: 'Accès à toutes les options PRO' },
                ].map(({ n, label, desc }) => (
                  <div key={n} style={{
                    background: 'linear-gradient(160deg,#f8f5ff,#fff)',
                    border: '1px solid #e0d6f7', borderRadius: 8,
                    padding: '10px 12px', textAlign: 'center',
                  }}>
                    <div style={{
                      width: 26, height: 26, borderRadius: '50%',
                      background: 'linear-gradient(135deg,#667eea,#764ba2)',
                      color: '#fff', fontSize: 12, fontWeight: 800,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      margin: '0 auto 6px',
                    }}>{n}</div>
                    <div style={{ fontSize: 11.5, fontWeight: 700, color: '#3b2f7a', marginBottom: 2, lineHeight: 1.3 }}>{label}</div>
                    <div style={{ fontSize: 10.5, color: '#888', lineHeight: 1.3 }}>{desc}</div>
                  </div>
                ))}
              </div>
            )}

            <div className="pdfb-license-input-group">
              <label htmlFor="license_key_input">Clé de licence</label>
              <div className="pdfb-license-input-with-button">
                <input
                  ref={inputRef}
                  type="text"
                  id="license_key_input"
                  aria-label="Clé de licence"
                  placeholder={d.inputPlaceholder}
                  className="pdfb-license-input"
                  value={keyInput}
                  onChange={(e) => setKeyInput(e.target.value)}
                />
                <button
                  type="button"
                  className="pdfb-license-btn-primary"
                  id="activate-license-btn"
                  disabled={activating || (keyTouched && !keyValid)}
                  onClick={handleActivate}
                >
                  <span className="pdfb-license-btn-text">
                    {activating ? 'Activation…' : d.activateButtonText}
                  </span>
                  <span className="pdfb-license-btn-icon">✓</span>
                </button>
              </div>

              {/* Inline validation notice */}
              {keyTouched && (
                <p
                  id="license-key-notice"
                  style={{
                    margin: '6px 0 0',
                    fontSize: 13,
                    color: keyValid ? '#1a7e2e' : '#cc1818',
                    fontWeight: 600,
                  }}
                >
                  {keyValid
                    ? '✓ Format valide.'
                    : '⚠ Format invalide — une clé EDD comporte 32 caractères hexadécimaux (0-9, a-f).'}
                </p>
              )}

              {/* AJAX notice */}
              {noticeType !== 'idle' && (
                <p style={{ margin: '6px 0 0', fontSize: 13, color: noticeColor, fontWeight: noticeType === 'loading' ? 'normal' : 600 }}>
                  {noticeMsg}
                </p>
              )}

              <p className="pdfb-license-input-help">
                {!d.isPremium ? (
                  <>
                    Vous n&apos;avez pas encore de clé ?{' '}
                    <a href={d.purchaseUrl} target="_blank" rel="noopener noreferrer">
                      Découvrir l&apos;extension PRO
                    </a>
                  </>
                ) : (
                  'Une nouvelle clé remplacera la licence actuellement active.'
                )}
              </p>

              {d.isPremium && d.displayKey && (
                <p className="description">
                  <a href={d.renewalUrl} target="_blank" rel="noopener noreferrer">
                    Renouveler la licence
                  </a>
                  {' | '}
                  <a href={d.unsubscribeUrl} target="_blank" rel="noopener noreferrer">
                    Gérer le renouvellement
                  </a>
                </p>
              )}
            </div>

            {/* Infos licence active — uniquement si premium */}
            {d.isPremium && (
              <div style={{ marginTop: 16 }}>

                {/* Statut détaillé */}
                <div style={{
                  display: 'grid', gridTemplateColumns: '1fr 1fr',
                  gap: 8, marginBottom: 12,
                }}>
                  {[
                    { icon: '🔑', label: 'Type de licence', value: d.licenseType || 'PRO' },
                    { icon: '📍', label: 'Site activé', value: d.siteCount ? `${d.siteCount} / ${d.activationLimit || '∞'}` : '1 site' },
                    { icon: '📅', label: 'Expiration', value: d.expiresLabel || 'À vie' },
                    { icon: '⚡', label: 'Statut', value: d.badgeText || 'Actif' },
                  ].map(({ icon, label, value }) => (
                    <div key={label} style={{
                      background: 'linear-gradient(160deg,#fffbeb,#fff)',
                      border: '1px solid rgba(198,168,0,.25)',
                      borderRadius: 8, padding: '10px 12px',
                    }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginBottom: 3 }}>
                        <span style={{ fontSize: 13 }}>{icon}</span>
                        <span style={{ fontSize: 10.5, fontWeight: 700, color: '#92660a', textTransform: 'uppercase', letterSpacing: '0.4px' }}>{label}</span>
                      </div>
                      <div style={{ fontSize: 13, fontWeight: 600, color: '#5a3e00' }}>{value}</div>
                    </div>
                  ))}
                </div>

                {/* Note sécurité */}
                <div style={{
                  display: 'flex', alignItems: 'flex-start', gap: 8,
                  padding: '10px 14px',
                  background: 'rgba(198,168,0,.06)',
                  borderRadius: 8,
                  border: '1px solid rgba(198,168,0,.2)',
                  fontSize: 12, color: '#7a5800',
                }}>
                  <span style={{ fontSize: 14, flexShrink: 0 }}>⚠️</span>
                  <span>Ne remplacez votre clé que si vous avez reçu une <strong>nouvelle clé valide</strong>. L&apos;ancienne sera désactivée sur ce site.</span>
                </div>
              </div>
            )}

            {/* Garanties — uniquement si pas premium */}
            {!d.isPremium && (
              <div style={{
                marginTop: 16,
                display: 'flex', gap: 12, flexWrap: 'wrap',
                padding: '10px 14px',
                background: 'rgba(102,126,234,.05)',
                borderRadius: 8,
                border: '1px solid rgba(102,126,234,.15)',
              }}>
                {[
                  { icon: '🔒', text: 'Achat séparé' },
                  { icon: '⚡', text: 'Activation par clé' },
                  { icon: '💬', text: 'Support du vendeur' },
                  { icon: '♾️', text: 'Licences à vie disponibles' },
                ].map(({ icon, text }) => (
                  <div key={text} style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 12, color: '#555' }}>
                    <span style={{ fontSize: 13 }}>{icon}</span>
                    <span style={{ fontWeight: 600 }}>{text}</span>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* Support / upgrade card — conditional style free vs premium */}
        {d.isActive ? (
          /* ── Premium: carte or avec ruban animé ────────────────────── */
          <div
            className="pdfb-license-action-card"
            style={{
              border: '2px solid #c6a800',
              background: 'linear-gradient(160deg,#fffbeb 0%,#fff 70%)',
              position: 'relative',
              overflow: 'hidden',
              animation: 'pdfib-glow 2.5s ease-in-out infinite',
            }}
          >
            {/* Ruban animé en haut */}
            <div style={{
              position: 'absolute', top: 0, left: 0, right: 0, height: 3,
              background: 'linear-gradient(90deg,#c6a800,#ffd700,#e8b800,#ffd700,#c6a800)',
              backgroundSize: '200% auto',
              animation: 'pdfib-shimmer 2.5s linear infinite',
            }} />
            {/* Badge Premium actif */}
            <div style={{
              position: 'absolute', top: 0, right: 16,
              background: 'linear-gradient(135deg,#f6c90e,#d4a800)',
              color: '#5a3e00', fontSize: 10, fontWeight: 700, letterSpacing: 1,
              padding: '4px 14px', borderRadius: '0 0 8px 8px',
              textTransform: 'uppercase',
            }}>★ PRO actif</div>

            <div className="pdfb-license-action-card-header" style={{ paddingTop: 28, paddingBottom: 8 }}>
              <h3 style={{ color: '#92660a', marginBottom: 4 }}>🏆 Options PRO actives</h3>
              <p style={{ fontSize: 13, color: '#7a5800', margin: 0 }}>
                Toutes les options PRO sont actives sur votre installation.
              </p>
            </div>

            <div className="pdfb-license-action-card-content" style={{ paddingTop: 10 }}>

              {/* Avantages liste */}
              <div style={{ marginBottom: 16 }}>
                {[
                  { icon: '⚡', text: 'Génération PDF, PNG & JPG' },
                  { icon: '🖨️', text: 'Export 300 & 600 DPI' },
                  { icon: '🖼️', text: 'Formats de page étendus' },
                  { icon: '🗂️', text: 'Galerie de modèles avancés' },
                  { icon: '🧲', text: 'Grille, guides & aimantation' },
                  { icon: '⌨️', text: 'Sélection multiple et raccourcis clavier' },
                ].map(({ icon, text }) => (
                  <div key={text} style={{
                    display: 'flex', alignItems: 'flex-start', gap: 8,
                    padding: '5px 0', borderBottom: '1px solid rgba(198,168,0,.15)',
                    fontSize: 12.5, color: '#5a3e00',
                  }}>
                    <span style={{ fontSize: 14, flexShrink: 0, marginTop: 1 }}>{icon}</span>
                    <span style={{ fontWeight: 500, lineHeight: 1.4 }}>{text}</span>
                  </div>
                ))}
              </div>

              {/* Ressources */}
              <div style={{ fontSize: 11.5, fontWeight: 700, color: '#92660a', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '0.5px' }}>
                Ressources &amp; gestion
              </div>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                <a href={d.supportUrl} target="_blank" rel="noopener noreferrer" className="button"
                  style={{ background: 'linear-gradient(135deg,#f6c90e,#d4a800)', border: '1px solid #b8940a', color: '#5a3e00', fontWeight: 700, fontSize: 12, padding: '7px 12px' }}>
                  🎯 Support
                </a>
                <a href={d.docsUrl} target="_blank" rel="noopener noreferrer" className="button button-secondary"
                  style={{ fontSize: 12, padding: '7px 12px' }}>
                  📖 Docs
                </a>
                <a href={d.renewalUrl} target="_blank" rel="noopener noreferrer" className="button button-secondary"
                  style={{ fontSize: 12, padding: '7px 12px' }}>
                  🔄 Renouveler
                </a>
              </div>
            </div>
          </div>
        ) : (
          /* ── No active license card ─────────────────────────── */
          <div className="pdfb-license-action-card">
            <div className="pdfb-license-action-card-header">
              <h3>Aucune licence active</h3>
              <p style={{ fontSize: 13, color: '#555', margin: 0 }}>
                Saisissez votre clé de licence ci-dessus pour activer les fonctionnalités avancées.
              </p>
            </div>
          </div>
        )}
      </div>

      {/* Details section */}
      <div className="pdfb-license-details-section">
        <button
          type="button"
          className="pdfb-expand-toggle"
          aria-expanded={detailsOpen}
          aria-controls="pdfb-details-body"
          onClick={() => setDetailsOpen((v) => !v)}
        >
          <span>Informations détaillées</span>
          <span
            className="pdfb-chevron"
            style={{ transform: detailsOpen ? 'rotate(180deg)' : '' }}
          >
            &#9660;
          </span>
        </button>

        {detailsOpen && (
          <div id="pdfb-details-body" style={{ marginTop: '0.75rem' }}>
            <div className="pdfb-license-details-grid">
              <div className="pdfb-license-detail-card">
                <h4>Statut</h4>
                <p className="pdfb-license-detail-value">{d.badgeText}</p>
              </div>
              <div className="pdfb-license-detail-card">
                <h4>État distant</h4>
                <p className="pdfb-license-detail-value">
                  {d.licenseStatus || 'Inconnu'}
                </p>
              </div>
              <div className="pdfb-license-detail-card">
                <h4>Site actuel</h4>
                <p className="pdfb-license-detail-value">{d.siteUrl}</p>
              </div>

              {d.maskedKey && (
                <div className="pdfb-license-detail-card">
                  <h4>Clé active</h4>
                  <p className="pdfb-license-detail-value">
                    <code>{d.maskedKey}</code>
                    {d.displayKey && (
                      <button
                        type="button"
                        className="button-link"
                        id="pdfib-copy-license-key"
                        onClick={handleCopyKey}
                      >
                        {copyLabel}
                      </button>
                    )}
                  </p>
                </div>
              )}

              {d.isActive && (
                <>
                  <div className="pdfb-license-detail-card">
                    <h4>Expiration</h4>
                    <p className="pdfb-license-detail-value">{d.expiresLabel}</p>
                  </div>
                  <div className="pdfb-license-detail-card">
                    <h4>Délai restant</h4>
                    <p className={`pdfb-license-detail-value ${d.daysLeftClass}`}>{d.daysLeftLabel}</p>
                  </div>
                </>
              )}

              {d.licenseCustomer && (
                <div className="pdfb-license-detail-card">
                  <h4>Titulaire</h4>
                  <p className="pdfb-license-detail-value">{d.licenseCustomer}</p>
                </div>
              )}

              {d.licenseEmail && (
                <div className="pdfb-license-detail-card">
                  <h4>Email</h4>
                  <p className="pdfb-license-detail-value">{d.licenseEmail}</p>
                </div>
              )}

              {d.licenseActivations !== null && (
                <div className="pdfb-license-detail-card">
                  <h4>Activations restantes</h4>
                  <p className="pdfb-license-detail-value">
                    {Math.abs(d.licenseActivations)}
                  </p>
                </div>
              )}
            </div>
          </div>
        )}
      </div>

      {/* Free vs Premium comparison */}
      <div className="premium-features-section">
        <h3 className="pdfb-section-title">Gratuit vs PRO</h3>
        <table className="widefat" style={{ borderCollapse: 'collapse', borderRadius: '4px 4px 0 0', overflow: 'hidden', marginBottom: 0 }}>
          <thead>
            <tr>
              <th style={{ width: '50%', padding: '10px 12px', background: '#f6f7f7', borderBottom: '2px solid #ddd', fontWeight: 700, color: '#23282d' }}>
                Fonctionnalité
              </th>
              <th style={{ width: '25%', padding: '10px 12px', background: '#f6f7f7', borderBottom: '2px solid #ddd', textAlign: 'center', color: '#666', fontWeight: 700 }}>
                Gratuit
              </th>
              <th style={{ width: '25%', padding: '10px 12px', background: '#fffbeb', borderBottom: '2px solid #c6a800', textAlign: 'center', color: '#92660a', fontWeight: 700 }}>
                ★ PRO
              </th>
            </tr>
          </thead>
          <tbody>
            {FEATURE_ROWS.filter((row) => row[3] || compareOpen).map(([label, free, premium]) => {
              const isFreeCheck = free === '✓';
              const isFreeMinus = free === '—';
              const isPremGreen = premium.startsWith('✓');
              const isPremMinus = premium === '—';
              return (
                <tr key={label} style={{ borderBottom: '1px solid #f0f0f0' }}>
                  <td style={{ padding: '8px 12px', fontSize: 13, color: '#23282d' }}>{label}</td>
                  <td style={{
                    padding: '8px 12px', textAlign: 'center', fontSize: 13,
                    color: isFreeMinus ? '#ccc' : isFreeCheck ? '#1a7e2e' : '#555',
                    fontWeight: isFreeCheck ? 700 : 400,
                  }}>{free}</td>
                  <td style={{
                    padding: '8px 12px', textAlign: 'center', fontSize: 13,
                    background: 'rgba(246,201,14,.06)',
                    color: isPremMinus ? '#ccc' : isPremGreen ? '#1a7e2e' : '#92660a',
                    fontWeight: 700,
                  }}>{premium}</td>
                </tr>
              );
            })}
          </tbody>
        </table>

        <button
          type="button"
          id="pdfb-compare-btn"
          aria-expanded={compareOpen}
          onClick={() => setCompareOpen((v) => !v)}
          style={{
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            width: '100%', padding: '10px 16px', margin: 0,
            background: '#f6f7f7', border: '1px solid #ddd', borderTop: 'none',
            cursor: 'pointer', color: '#555', fontSize: 13, fontWeight: 600,
            borderRadius: '0 0 4px 4px', boxSizing: 'border-box',
          }}
        >
          <span>{compareOpen ? 'Voir moins' : 'Voir plus de fonctionnalités'}</span>
          <span
            className="pdfb-chevron"
            style={{ transition: 'transform 0.2s', transform: compareOpen ? 'rotate(180deg)' : 'rotate(0deg)' }}
          >
            &#9660;
          </span>
        </button>
      </div>

      {/* Email reminders — fields stay in the PHP form for native form submission */}
      <div id="email-reminders" className="pdfb-license-action-card" style={{ marginTop: '1.5rem' }}>
        <div className="pdfb-license-action-card-header">
          <h3>Rappels par email</h3>
          <p>Recevez une alerte avant l&apos;expiration pour éviter une coupure de service.</p>
        </div>
        <div className="pdfb-license-action-card-content">
          <p>
            <label htmlFor="license_email_reminders">
              <input
                type="checkbox"
                id="license_email_reminders"
                name="pdfib_settings[pdfib_license_email_reminders]"
                value="1"
                defaultChecked={d.emailRemindersEnabled}
              />
              {' '}Activer les rappels par email
            </label>
          </p>
          <p>
            <label htmlFor="license_reminder_email">
              Adresse email de rappel
            </label>
            <input
              type="email"
              id="license_reminder_email"
              name="pdfib_settings[pdfib_license_reminder_email]"
              defaultValue={d.reminderEmail}
              placeholder={d.adminEmail}
              className="regular-text"
            />
          </p>
          <p className="description">Laissez vide pour réutiliser l&apos;email administrateur du site.</p>
          <p className="description">Cette adresse est utilisée uniquement pour les rappels de licence.</p>
        </div>
      </div>

      {/* Deactivation confirmation modal */}
      {showDeactivateModal && (
        <DeactivateModal
          onClose={() => setShowDeactivateModal(false)}
          onConfirm={handleConfirmDeactivate}
        />
      )}
    </section>
  );
};

export default LicencePage;
