// PaywallModal — modal paywall réutilisable (Sprint 2 PR2)
// Fondation UI pour le gating de toutes les features premium.
// Props pures : ne dépend PAS de tier-gate.js (PR1 Sprint 2 en parallèle).
//
// Usage :
//   <PaywallModal
//     open={true}
//     onClose={() => setOpen(false)}
//     feature="compare_page"
//     featureLabel="Comparateur de 4 biens"
//     requiredTier="investisseur"
//     currentTier="decouverte"
//     reason="tier_too_low"
//   />

(function () {
  const { useEffect: usePWE } = React;

  // ---- Données bénéfices par tier ----
  const TIER_BENEFITS = {
    investisseur: [
      'Multi-zones illimitées + tous les filtres avancés (12+)',
      'Drawer complet — 8 KPIs, market position, stress test 3 taux',
      'HypothesesStrip live recalc (mise de fonds, taux, amortissement)',
      'Comparateur 4 biens côte-à-côte',
    ],
    pro: [
      'AnalyzePage full : 3 scénarios A/B/C sur 10 ans + IRR exact',
      'Module fiscalité QC (CCA catégorie 1 + gain en capital)',
      'PDF export signé "Vestora Pro" (partage banquier/comptable)',
      'Alertes multi-critères illimitées + scénarios sauvegardés',
    ],
    entreprise: [
      'Multi-utilisateurs avec rôles et permissions',
      'White-label, API REST, bulk export',
      'Client matchmaking engine + SLA garanti',
      'Onboarding dédié 1-on-1 + support prioritaire',
    ],
  };

  const TIER_LABELS = {
    decouverte: 'Découverte',
    investisseur: 'Investisseur',
    pro: 'Pro',
    entreprise: 'Entreprise',
  };

  const TIER_PRICES = {
    investisseur: '24$/mo',
    pro: '59$/mo',
    entreprise: 'Sur devis',
  };

  // ---- Icônes SVG inline ----
  function LockIcon() {
    return (
      <svg
        width="28" height="28" viewBox="0 0 24 24" fill="none"
        stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"
        style={{ display: 'block' }}
        aria-hidden="true"
      >
        <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
        <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
      </svg>
    );
  }

  function CloseIcon() {
    return (
      <svg width="14" height="14" viewBox="0 0 14 14" stroke="currentColor" strokeWidth="1.5" fill="none" aria-hidden="true">
        <path d="M2 2l10 10M12 2L2 12"/>
      </svg>
    );
  }

  function CheckBullet() {
    return (
      <svg
        width="16" height="16" viewBox="0 0 16 16" fill="none"
        style={{ flexShrink: 0, marginTop: 1 }}
        aria-hidden="true"
      >
        <circle cx="8" cy="8" r="7.5" fill="oklch(0.52 0.13 150 / 0.12)"/>
        <path d="M5 8l2.2 2.2L11 5.5" stroke="oklch(0.42 0.13 150)" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    );
  }

  // ---- Composant principal ----
  function PaywallModal({
    open,
    onClose,
    feature,
    featureLabel,
    requiredTier,
    currentTier,
    reason = 'tier_too_low',
    quotaInfo,         // { used, limit, resetsOn } — si reason === 'quota_exceeded'
    onUpgrade,
  }) {
    // Fermeture par Echap
    usePWE(() => {
      if (!open) return;
      const handleKey = (e) => {
        if (e.key === 'Escape') onClose();
      };
      document.addEventListener('keydown', handleKey);
      return () => document.removeEventListener('keydown', handleKey);
    }, [open, onClose]);

    // Bloquer scroll body
    usePWE(() => {
      if (open) {
        document.body.style.overflow = 'hidden';
      } else {
        document.body.style.overflow = '';
      }
      return () => { document.body.style.overflow = ''; };
    }, [open]);

    // Tracking
    usePWE(() => {
      if (open) {
        console.log('[paywall]', { feature, requiredTier, reason });
      }
    }, [open, feature, requiredTier, reason]);

    if (!open) return null;

    const handleUpgrade = () => {
      if (typeof onUpgrade === 'function') {
        onUpgrade();
      } else {
        window.location.hash = '#/tarifs';
      }
    };

    const tierLabel = TIER_LABELS[requiredTier] || requiredTier;
    const tierPrice = TIER_PRICES[requiredTier] || '';
    const benefits = TIER_BENEFITS[requiredTier] || [];

    // Titre contextuel
    let titleText;
    if (reason === 'quota_exceeded' && quotaInfo) {
      const resetsLabel = quotaInfo.resetsOn
        ? new Date(quotaInfo.resetsOn).toLocaleDateString('fr-CA', { day: 'numeric', month: 'long' })
        : '—';
      titleText = `Quota mensuel atteint (${quotaInfo.used}/${quotaInfo.limit} analyses détaillées). Réinitialisation le ${resetsLabel}.`;
    } else {
      titleText = `${featureLabel || 'Cette fonctionnalité'} est réservée au plan ${tierLabel}`;
    }

    return (
      <div
        className="pw-backdrop"
        style={{
          position: 'fixed', inset: 0, zIndex: 10000,
          background: 'rgba(0, 0, 0, 0.55)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          padding: '16px',
          backdropFilter: 'blur(2px)',
          WebkitBackdropFilter: 'blur(2px)',
          animation: 'pwFadeIn 0.15s ease',
        }}
        onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
        role="dialog"
        aria-modal="true"
        aria-label={titleText}
      >
        <div
          className="pw-panel"
          style={{
            background: 'var(--bg-elev, #fff)',
            borderRadius: 'var(--radius-lg, 14px)',
            boxShadow: 'var(--shadow-lg, 0 20px 60px rgba(0,0,0,0.22))',
            width: '100%',
            maxWidth: 460,
            overflow: 'hidden',
            animation: 'pwSlideUp 0.2s ease',
            fontFamily: 'var(--sans, Inter, sans-serif)',
            color: 'var(--ink-1, #1a1a1a)',
          }}
          onClick={(e) => e.stopPropagation()}
        >
          {/* ---- Header ---- */}
          <div style={{
            display: 'flex', alignItems: 'flex-start', gap: 14,
            padding: '24px 24px 0',
          }}>
            {/* Icône cadenas */}
            <div style={{
              flexShrink: 0,
              width: 48, height: 48, borderRadius: 12,
              background: 'var(--accent-soft, oklch(0.95 0.04 155))',
              color: 'var(--accent-ink, oklch(0.36 0.07 155))',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              marginTop: 2,
            }}>
              <LockIcon />
            </div>

            {/* Titre + sous-titre */}
            <div style={{ flex: 1, minWidth: 0 }}>
              <h2 style={{
                margin: '0 0 4px',
                fontFamily: 'var(--serif, Fraunces, serif)',
                fontSize: 17, fontWeight: 500,
                letterSpacing: '-0.01em',
                lineHeight: 1.3,
                color: 'var(--ink-1, #1a1a1a)',
              }}>
                {titleText}
              </h2>
              {tierPrice && (
                <div style={{
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                  background: 'var(--accent-soft, oklch(0.95 0.04 155))',
                  color: 'var(--accent-ink, oklch(0.36 0.07 155))',
                  borderRadius: 20, padding: '2px 10px',
                  fontSize: 12, fontWeight: 600,
                  marginTop: 4,
                }}>
                  Plan {tierLabel} — {tierPrice}
                </div>
              )}
            </div>

            {/* Bouton fermer */}
            <button
              onClick={onClose}
              aria-label="Fermer"
              style={{
                flexShrink: 0,
                background: 'none', border: 'none', cursor: 'pointer',
                color: 'var(--ink-3, #999)',
                width: 28, height: 28, borderRadius: 6,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                padding: 0, marginTop: -2,
                transition: 'background 0.1s, color 0.1s',
              }}
              onMouseEnter={e => {
                e.currentTarget.style.background = 'var(--bg-warm, #f5f5f0)';
                e.currentTarget.style.color = 'var(--ink-1, #1a1a1a)';
              }}
              onMouseLeave={e => {
                e.currentTarget.style.background = 'none';
                e.currentTarget.style.color = 'var(--ink-3, #999)';
              }}
            >
              <CloseIcon />
            </button>
          </div>

          {/* ---- Corps — bénéfices du tier ---- */}
          {benefits.length > 0 && (
            <div style={{ padding: '20px 24px 0' }}>
              <div style={{
                fontSize: 12, fontWeight: 600, letterSpacing: '0.05em',
                textTransform: 'uppercase', color: 'var(--ink-3, #888)',
                marginBottom: 10,
              }}>
                Inclus dans le plan {tierLabel}
              </div>
              <ul style={{
                listStyle: 'none', padding: 0, margin: 0,
                display: 'flex', flexDirection: 'column', gap: 8,
              }}>
                {benefits.map((b, i) => (
                  <li key={i} style={{
                    display: 'flex', alignItems: 'flex-start', gap: 10,
                    fontSize: 13.5, color: 'var(--ink-1, #1a1a1a)', lineHeight: 1.4,
                  }}>
                    <CheckBullet />
                    {b}
                  </li>
                ))}
              </ul>
            </div>
          )}

          {/* ---- Contexte utilisateur (tier actuel) ---- */}
          {currentTier && reason === 'tier_too_low' && (
            <div style={{
              margin: '16px 24px 0',
              padding: '10px 14px',
              background: 'var(--bg-warm, #f9f9f6)',
              borderRadius: 8,
              border: '1px solid var(--line, #e8e8e0)',
              fontSize: 12.5, color: 'var(--ink-2, #555)', lineHeight: 1.5,
            }}>
              Votre plan actuel : <strong>{TIER_LABELS[currentTier] || currentTier}</strong>.
              Passez à <strong>{tierLabel}</strong> pour débloquer cette fonctionnalité.
            </div>
          )}

          {/* ---- Actions ---- */}
          <div style={{ padding: '20px 24px 24px', display: 'flex', flexDirection: 'column', gap: 10 }}>
            <button
              onClick={handleUpgrade}
              style={{
                width: '100%', padding: '13px 16px',
                borderRadius: 'var(--radius, 8px)', border: 'none',
                background: 'var(--accent, oklch(0.36 0.07 155))',
                color: 'var(--accent-fg, #fff)',
                fontWeight: 600, fontSize: 14.5,
                cursor: 'pointer', fontFamily: 'inherit',
                transition: 'opacity 0.15s, transform 0.15s',
                letterSpacing: '-0.01em',
              }}
              onMouseEnter={e => {
                e.currentTarget.style.opacity = '0.88';
                e.currentTarget.style.transform = 'translateY(-1px)';
              }}
              onMouseLeave={e => {
                e.currentTarget.style.opacity = '1';
                e.currentTarget.style.transform = 'translateY(0)';
              }}
            >
              Voir les plans
            </button>
            <button
              onClick={onClose}
              style={{
                width: '100%', padding: '11px 16px',
                borderRadius: 'var(--radius, 8px)',
                border: '1.5px solid var(--line, #e8e8e0)',
                background: 'transparent',
                color: 'var(--ink-2, #555)',
                fontWeight: 500, fontSize: 14,
                cursor: 'pointer', fontFamily: 'inherit',
                transition: 'background 0.1s',
              }}
              onMouseEnter={e => { e.currentTarget.style.background = 'var(--bg-warm, #f5f5f0)'; }}
              onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; }}
            >
              Plus tard
            </button>
          </div>
        </div>

        {/* ---- Animations inline ---- */}
        <style>{`
          @keyframes pwFadeIn {
            from { opacity: 0; }
            to   { opacity: 1; }
          }
          @keyframes pwSlideUp {
            from { transform: translateY(10px); opacity: 0; }
            to   { transform: translateY(0);    opacity: 1; }
          }
        `}</style>
      </div>
    );
  }

  // Export global
  window.PaywallModal = PaywallModal;
})();
