/**
 * UpgradeModals.tsx
 *
 * React component replacing partials/upgrade-modals.php.
 * Exposes showUpgradeModal / closeUpgradeModal as window globals so that
 * existing jQuery / vanilla-JS admin code keeps working without changes.
 *
 * Data injected by PHP via wp_localize_script('pdfib-upgrade-modals', 'pdfibUpgradeModalsData', {shopUrl}).
 */

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

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

export interface UpgradeModalsData {
  shopUrl: string;
}

declare global {
  interface Window {
    pdfibUpgradeModalsData?: UpgradeModalsData;
    showUpgradeModal?: (reason: string) => void;
    closeUpgradeModal?: (modalId: string) => void;
  }
}

type ModalReason = 'template' | 'gallery' | 'license_tab';

// ─── Feature list (same in all 3 modals) ─────────────────────────────────────

const FEATURES = [
  { icon: '📄', label: 'Templates supplémentaires', desc: 'selon la formule choisie' },
  { icon: '🖼️', label: 'Export PDF, PNG & JPG', desc: 'formats de sortie étendus' },
  { icon: '📤', label: 'Résolution élevée', desc: '300 & 600 DPI' },
  { icon: '🎯', label: 'Couleurs & fonds personnalisés', desc: 'pour le canvas' },
  { icon: '📐', label: 'Grille, guides & accrochage', desc: 'pour la mise en page' },
  { icon: '🔄', label: 'Mises à jour incluses', desc: 'selon votre licence' },
  { icon: '💬', label: 'Support du vendeur', desc: 'via le canal prévu' },
];

// ─── Modal config ─────────────────────────────────────────────────────────────

const MODAL_CONFIG: Record<ModalReason, { id: string; title: string; icon: string; heading: string; desc: string }> = {
  template: {
    id: 'upgrade-modal-template',
    title: 'Templates PRO',
    icon: '🎨',
    heading: 'Templates et personnalisation',
    desc: 'Ajoutez des templates supplémentaires et ajustez davantage le rendu.',
  },
  gallery: {
    id: 'upgrade-modal-gallery',
    title: 'Modèles PRO',
    icon: '🖼️',
    heading: 'Galerie de modèles',
    desc: 'Accédez aux modèles professionnels additionnels pour factures, devis et autres documents.',
  },
  license_tab: {
    id: 'upgrade-modal-license_tab',
    title: 'Licence PRO',
    icon: '💎',
    heading: 'Activation de la version PRO',
    desc: 'Associez votre licence séparée pour activer les options PRO sur cette installation.',
  },
};

// ─── Single modal ─────────────────────────────────────────────────────────────

interface UpgradeModalProps {
  reason: ModalReason;
  visible: boolean;
  onClose: () => void;
  shopUrl: string;
}

const UpgradeModal: React.FC<UpgradeModalProps> = ({ reason, visible, onClose, shopUrl }) => {
  const cfg = MODAL_CONFIG[reason];

  if (!visible) {
    return (
      <div
        id={cfg.id}
        className="pdfb-modal-overlay"
        style={{ display: 'none' }}
      />
    );
  }

  return (
    <div
      id={cfg.id}
      className="pdfb-modal-overlay"
      style={{
        display: 'flex',
        position: 'fixed',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        background: 'rgba(0,0,0,0.7)',
        zIndex: 99999,
        justifyContent: 'center',
        alignItems: 'center',
      }}
      onClick={(e) => {
        if ((e.target as HTMLElement).classList.contains('pdfb-modal-overlay')) {
          onClose();
        }
      }}
    >
      <div
        className="pdfb-modal-content"
        style={{
          background: 'white',
          borderRadius: 12,
          maxWidth: 500,
          width: '90%',
          maxHeight: '90vh',
          overflowY: 'auto',
          boxShadow: '0 10px 40px rgba(0,0,0,0.3)',
        }}
      >
        {/* Header */}
        <div
          className="pdfb-modal-header"
          style={{
            padding: '20px 30px',
            borderBottom: '1px solid #dee2e6',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}
        >
          <h3 style={{ margin: 0, color: '#23282d', fontSize: 20 }}>{cfg.title}</h3>
          <button
            className="pdfb-modal-close"
            onClick={onClose}
            style={{ background: 'none', border: 'none', fontSize: 24, cursor: 'pointer', color: '#6c757d' }}
          >
            &times;
          </button>
        </div>

        {/* Body */}
        <div className="pdfb-modal-body" style={{ padding: 30 }}>
          <div className="upgrade-feature" style={{ textAlign: 'center', marginBottom: 30 }}>
            <div className="pdfb-feature-icon" style={{ fontSize: 64, marginBottom: 20 }}>
              {cfg.icon}
            </div>
            <h4 style={{ color: '#23282d', fontSize: 20, marginBottom: 15 }}>{cfg.heading}</h4>
            <p style={{ color: '#666', marginBottom: 20, lineHeight: 1.6 }}>{cfg.desc}</p>

            <ul
              style={{
                textAlign: 'left',
                background: '#f8f9fa',
                padding: 20,
                borderRadius: 8,
                listStyle: 'none',
                margin: 0,
              }}
            >
              {FEATURES.map((f, i) => (
                <li key={i} style={{ margin: '8px 0', color: '#23282d' }}>
                  {f.icon} <strong>{f.label}</strong>
                  {f.desc ? ` — ${f.desc}` : ''}
                </li>
              ))}
            </ul>
          </div>

          {/* Pricing */}
          <div
            className="pricing"
            style={{
              textAlign: 'center',
              background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
              padding: 25,
              borderRadius: 8,
              color: 'white',
            }}
          >
            <div className="price" style={{ fontSize: 36, fontWeight: 'bold', marginBottom: 10 }}>
              69.99€ <span style={{ fontSize: 16, fontWeight: 'normal' }}>à vie</span>
            </div>
            <p style={{ margin: '10px 0 20px 0', opacity: 0.9 }}>
              Options de licence disponibles selon la formule choisie.
            </p>
            <a
              href={shopUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="button button-primary"
              style={{
                display: 'inline-flex',
                alignItems: 'center',
                gap: 5,
                padding: '12px 30px',
                fontSize: 18,
                fontWeight: 'bold',
                textDecoration: 'none',
                color: 'white',
              }}
            >
              <span className="dashicons dashicons-cart" style={{ marginRight: 5 }} />
              Voir les formules
            </a>
          </div>
        </div>
      </div>
    </div>
  );
};

// ─── Root component ───────────────────────────────────────────────────────────

const UpgradeModals: React.FC = () => {
  const shopUrl =
    window.pdfibUpgradeModalsData?.shopUrl ??
    'https://hub.threeaxe.fr/index.php/downloads/pdf-builder-pro/';

  const [visible, setVisible] = useState<ModalReason | null>(null);

  useEffect(() => {
    // Expose global helpers expected by legacy PHP/JS code.
    window.showUpgradeModal = (reason: string) => {
      if (reason in MODAL_CONFIG) {
        setVisible(reason as ModalReason);
      }
    };

    window.closeUpgradeModal = (modalId: string) => {
      const entry = Object.values(MODAL_CONFIG).find((c) => c.id === modalId);
      if (entry) {
        setVisible(null);
      }
    };

    return () => {
      delete window.showUpgradeModal;
      delete window.closeUpgradeModal;
    };
  }, []);

  return (
    <>
      {(Object.keys(MODAL_CONFIG) as ModalReason[]).map((reason) => (
        <UpgradeModal
          key={reason}
          reason={reason}
          visible={visible === reason}
          onClose={() => setVisible(null)}
          shopUrl={shopUrl}
        />
      ))}
    </>
  );
};

export default UpgradeModals;
