// PricingPage — Route #/tarifs
// Sprint 1 PR3 — 3 cartes tarifaires + toggle annuel/mensuel + tableau comparatif + FAQ
// Stub gracieux si window.vestora.auth ou .billing absents (PRs #1/#2 pas encore mergées)

(function () {
  const { useState, useEffect } = React;

  // ---- Helpers stubs gracieux ----
  function showToast(msg) {
    const el = document.createElement('div');
    el.textContent = msg;
    Object.assign(el.style, {
      position: 'fixed', bottom: '24px', left: '50%', transform: 'translateX(-50%)',
      background: 'oklch(0.18 0.012 85)', color: '#fff',
      padding: '12px 24px', borderRadius: '8px', zIndex: 9999,
      fontSize: '14px', fontFamily: 'Inter, sans-serif',
      boxShadow: '0 4px 16px rgba(0,0,0,0.25)',
      animation: 'fadeIn 0.2s ease',
    });
    document.body.appendChild(el);
    setTimeout(() => el.remove(), 3500);
  }

  function openLoginModal() {
    if (window.vestora && window.vestora.auth && typeof window.vestora.auth.openModal === 'function') {
      window.vestora.auth.openModal();
    } else {
      showToast('Connexion bientôt disponible — fonctionnalité en cours de déploiement.');
    }
  }

  function startCheckout(planKey) {
    if (window.vestora && window.vestora.billing && typeof window.vestora.billing.startCheckout === 'function') {
      window.vestora.billing.startCheckout(planKey);
    } else {
      showToast('Paiement bientôt disponible — en cours de déploiement (Stripe).');
    }
  }

  function isLoggedIn() {
    return !!(window.vestora && window.vestora.auth && window.vestora.auth.getUser());
  }

  async function handleStartTrial(setPendingTrial, setTrialLoading) {
    if (!isLoggedIn()) {
      setPendingTrial(true);
      openLoginModal();
      return;
    }
    setTrialLoading(true);
    try {
      const billing = window.vestora && window.vestora.billing;
      if (!billing || typeof billing.startTrial !== 'function') {
        showToast('Fonctionnalité bientôt disponible.');
        return;
      }
      const data = await billing.startTrial();
      showToast('🎁 Trial Pro 7j activé ! Profitez de toutes les fonctionnalités Pro.');
      setTimeout(() => window.location.reload(), 1800);
    } catch (e) {
      showToast(e.message || 'Erreur lors de l\'activation du trial.');
    } finally {
      setTrialLoading(false);
    }
  }

  // ---- Data ----
  const PLANS = [
    {
      id: 'decouverte',
      name: 'Découverte',
      badge: null,
      anchor: false,
      monthlyPrice: 0,
      annualPrice: 0,
      annualPerMonth: 0,
      ctaLabel: 'Commencer gratuitement',
      ctaSecondary: null,
      note: 'Pas de carte requise',
      color: 'var(--ink-3)',
      features: [
        { label: 'Recherche + filtres basiques (Type, Prix, Unités, Score)', included: true },
        { label: 'Carte avec pins + scores', included: true },
        { label: '1 zone watchée (ville ou quartier sauvegardé)', included: true },
        { label: 'Drawer avec 3 KPIs (capRate, DSCR, cashFlow)', included: true, note: '5 ouvertures/mois' },
        { label: 'Score + verdict + 1 tag profil', included: true },
        { label: '6 profils investisseur', included: true },
        { label: 'Onboarding wizard', included: true },
        { label: 'Multi-zones illimitées', included: false },
        { label: '12+ filtres avancés', included: false },
        { label: 'HypothesesStrip live recalc', included: false },
        { label: 'Comparateur 4 biens', included: false },
        { label: 'Market position complète + percentile', included: false },
        { label: 'Stress test 3 taux', included: false },
        { label: 'Expert analysis complète', included: false },
        { label: 'AnalyzePage 10 ans + IRR', included: false },
        { label: 'Module fiscalité QC (CCA, gain en capital)', included: false },
        { label: 'PDF export', included: false },
        { label: 'Alertes multi-critères', included: false },
      ],
    },
    {
      id: 'investisseur',
      name: 'Investisseur',
      badge: '⭐ Plus populaire',
      anchor: false,
      monthlyPrice: 24,
      annualPrice: 228,
      annualPerMonth: 19,
      ctaLabel: 'Essayer 7 jours gratuit',
      ctaSecondary: 'Sans carte requise',
      note: 'Annule en 1 clic',
      color: 'var(--accent)',
      features: [
        { label: 'Tout de Découverte', included: true },
        { label: 'Multi-zones illimitées sauvegardées', included: true },
        { label: '12+ filtres complets (yearBuilt, bedrooms, area, DSCR, cashFlow…)', included: true },
        { label: 'Drawer complet (cashOnCash, NOI, expenseRatio, GRM, pricePerUnit)', included: true },
        { label: 'HypothesesStrip live recalc (mise de fonds, taux, amort)', included: true },
        { label: 'Comparateur 4 biens côte-à-côte', included: true },
        { label: 'Market position complète (percentile + médiane ville)', included: true },
        { label: 'Stress test 3 taux (5%/6%/7%)', included: true },
        { label: 'Expert analysis complète (strengths/weaknesses/risks)', included: true },
        { label: 'Analyses détaillées illimitées (sans quota)', included: true },
        { label: 'Favoris + historique cloud (sync multi-devices)', included: true },
        { label: '1 alerte par jour (nouveau listing dans ma zone)', included: true },
        { label: 'Profil utilisateur cloud-saved', included: true },
        { label: 'AnalyzePage 10 ans + IRR', included: false },
        { label: 'Module fiscalité QC (CCA, gain en capital)', included: false },
        { label: 'PDF export', included: false },
        { label: 'Alertes multi-critères illimitées', included: false },
        { label: 'Scénarios sauvegardés + custom stress test', included: false },
      ],
    },
    {
      id: 'pro',
      name: 'Pro',
      badge: null,
      anchor: true,
      monthlyPrice: 59,
      annualPrice: 564,
      annualPerMonth: 47,
      ctaLabel: 'Essayer 7 jours gratuit',
      ctaSecondary: 'Sans carte requise',
      note: 'Annule en 1 clic',
      color: 'oklch(0.36 0.07 155)',
      features: [
        { label: 'Tout de Investisseur', included: true },
        { label: 'AnalyzePage full (3 scénarios A/B/C + projection 10 ans + IRR exact)', included: true },
        { label: 'Tornado sensitivity (6 variables ±10%) + export CSV', included: true },
        { label: 'Module fiscalité QC (CCA cat.1, gain en capital, économie d\'impôt)', included: true },
        { label: 'PDF export signé "Vestora Pro" (partage banquier/comptable)', included: true },
        { label: 'Alertes multi-critères illimitées (cap rate, score, rayon km)', included: true },
        { label: 'Scénarios sauvegardés (10 par listing)', included: true },
        { label: 'Custom stress test (n\'importe quel taux)', included: true },
        { label: 'API webhook personnel (email + Slack/Discord)', included: true },
      ],
    },
  ];

  const COMPARE_FEATURES = [
    { label: 'Filtres basiques (Type, Prix, Unités, Score)', decouverte: true, investisseur: true, pro: true },
    { label: 'Carte + pins scores', decouverte: true, investisseur: true, pro: true },
    { label: '6 profils investisseur', decouverte: true, investisseur: true, pro: true },
    { label: 'Drawer (3 KPIs)', decouverte: '5/mois', investisseur: 'Illimité', pro: 'Illimité' },
    { label: 'Zones sauvegardées', decouverte: '1 zone', investisseur: 'Illimité', pro: 'Illimité' },
    { label: '12+ filtres avancés', decouverte: false, investisseur: true, pro: true },
    { label: 'Drawer complet (8 KPIs)', decouverte: false, investisseur: true, pro: true },
    { label: 'HypothesesStrip live', decouverte: false, investisseur: true, pro: true },
    { label: 'Comparateur 4 biens', decouverte: false, investisseur: true, pro: true },
    { label: 'Market position + percentile', decouverte: false, investisseur: true, pro: true },
    { label: 'Stress test 3 taux', decouverte: false, investisseur: true, pro: true },
    { label: 'Expert analysis complète', decouverte: false, investisseur: true, pro: true },
    { label: 'Historique cloud + favoris', decouverte: false, investisseur: true, pro: true },
    { label: 'Alertes basiques (1/jour)', decouverte: false, investisseur: true, pro: true },
    { label: 'AnalyzePage 10 ans + IRR', decouverte: false, investisseur: false, pro: true },
    { label: 'Fiscalité QC (CCA + gain capital)', decouverte: false, investisseur: false, pro: true },
    { label: 'PDF export pro', decouverte: false, investisseur: false, pro: true },
    { label: 'Alertes multi-critères illimitées', decouverte: false, investisseur: false, pro: true },
    { label: 'Scénarios sauvegardés', decouverte: false, investisseur: false, pro: true },
    { label: 'API webhook personnel', decouverte: false, investisseur: false, pro: true },
  ];

  const FAQ = [
    {
      q: 'Est-ce que je peux annuler à tout moment ?',
      a: 'Oui. Vous pouvez annuler votre abonnement en 1 clic depuis votre espace compte. Aucun engagement, aucun frais de résiliation. L\'accès reste actif jusqu\'à la fin de la période payée.',
    },
    {
      q: 'La TVQ est-elle incluse dans les prix affichés ?',
      a: 'Les prix affichés sont hors taxes. La TVQ (9,975%) et la TPS (5%) s\'appliquent pour les résidents du Québec, conformément à la réglementation canadienne.',
    },
    {
      q: 'Mes données sont-elles sécurisées ?',
      a: 'Oui. Vos données sont hébergées sur Supabase (région Canada) avec chiffrement en transit (TLS) et au repos. Nous ne vendons jamais vos données à des tiers.',
    },
    {
      q: 'Que se passe-t-il après le trial Pro de 7 jours ?',
      a: 'À la fin des 7 jours, votre compte revient automatiquement en mode Découverte (gratuit). Aucun débit n\'est effectué. Vous pouvez à tout moment passer à Investisseur ou Pro.',
    },
    {
      q: 'Puis-je changer de plan en cours de route ?',
      a: 'Oui. Vous pouvez monter ou descendre de plan à tout moment. En montée, la différence est calculée au prorata. En descente, le crédit est conservé pour la prochaine période.',
    },
    {
      q: 'Les données des propriétés sont-elles à jour ?',
      a: 'Notre base de données est mise à jour régulièrement depuis les sources publiques et partenaires. Les métriques financières (cap rate, DSCR, cashFlow) sont calculées en temps réel selon vos hypothèses personnelles.',
    },
    {
      q: 'Vestora remplace-t-il un comptable ou un courtier ?',
      a: 'Non. Vestora est un outil d\'aide à la décision. Les analyses fiscales et financières sont à valider avec votre comptable et courtier hypothécaire avant tout investissement.',
    },
  ];

  const TESTIMONIALS = [
    {
      initials: 'MG',
      name: 'Marc-André Girard',
      role: 'Investisseur immobilier, Québec',
      quote: 'En 20 minutes j\'avais comparé 4 plex et calculé mon vrai rendement après impôt. Vestora m\'a évité une erreur de 30 000 $.',
      accent: 'var(--accent)',
    },
    {
      initials: 'SF',
      name: 'Sophie Fortier',
      role: 'Courtière immobilière, RE/MAX',
      quote: 'Je montre les analyses Vestora Pro à mes clients investisseurs lors des visites. Ça accélère les décisions et renforce ma crédibilité.',
      accent: 'oklch(0.36 0.07 155)',
    },
    {
      initials: 'JB',
      name: 'Jean-François Beaulieu',
      role: 'Gestionnaire de patrimoine, Montréal',
      quote: 'Le module fiscalité QC avec CCA et gain en capital est exactement ce qui manquait. Mes clients voient enfin le rendement net réel.',
      accent: 'oklch(0.45 0.08 250)',
    },
  ];

  // ---- Sub-components ----
  function CheckIcon() {
    return (
      <svg width="16" height="16" viewBox="0 0 16 16" fill="none" style={{ flexShrink: 0 }}>
        <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>
    );
  }

  function LockIcon() {
    return (
      <svg width="14" height="14" viewBox="0 0 14 14" fill="none" style={{ flexShrink: 0, opacity: 0.45 }}>
        <rect x="2.5" y="6" width="9" height="7" rx="1.5" stroke="currentColor" strokeWidth="1.3"/>
        <path d="M4.5 6V4.5a2.5 2.5 0 115 0V6" stroke="currentColor" strokeWidth="1.3"/>
      </svg>
    );
  }

  function CellValue({ val }) {
    if (val === true) return <span style={{ color: 'oklch(0.42 0.13 150)', fontSize: 16, lineHeight: 1 }}>✓</span>;
    if (val === false) return <span style={{ color: 'var(--ink-4)', fontSize: 14 }}>—</span>;
    return <span style={{ fontSize: 12, color: 'var(--ink-2)', fontWeight: 500 }}>{val}</span>;
  }

  function FAQItem({ q, a }) {
    const [open, setOpen] = useState(false);
    return (
      <div style={{
        borderBottom: '1px solid var(--line)',
        padding: '0',
      }}>
        <button
          onClick={() => setOpen(o => !o)}
          style={{
            width: '100%', textAlign: 'left', background: 'none', border: 'none',
            padding: '16px 0', display: 'flex', justifyContent: 'space-between',
            alignItems: 'center', gap: 12, cursor: 'pointer',
            fontSize: 14, fontWeight: 500, color: 'var(--ink-1)',
            fontFamily: 'inherit',
          }}
        >
          <span>{q}</span>
          <span style={{
            fontSize: 18, color: 'var(--ink-3)', flexShrink: 0,
            transform: open ? 'rotate(45deg)' : 'none', transition: 'transform 0.2s',
          }}>+</span>
        </button>
        {open && (
          <div style={{
            fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.65,
            paddingBottom: 16,
          }}>
            {a}
          </div>
        )}
      </div>
    );
  }

  function TestimonialCard({ initials, name, role, quote, accent }) {
    return (
      <div style={{
        background: 'var(--bg-elev)',
        border: '1px solid var(--line)',
        borderRadius: 'var(--radius-lg)',
        padding: '24px',
        display: 'flex', flexDirection: 'column', gap: 16,
      }}>
        <p style={{
          fontSize: 14, lineHeight: 1.7, color: 'var(--ink-1)',
          margin: 0, fontStyle: 'italic',
        }}>
          « {quote} »
        </p>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 'auto' }}>
          <div style={{
            width: 40, height: 40, borderRadius: '50%',
            background: accent, display: 'flex', alignItems: 'center', justifyContent: 'center',
            flexShrink: 0,
          }}>
            <span style={{ color: '#fff', fontWeight: 700, fontSize: 14, fontFamily: 'var(--mono)' }}>
              {initials}
            </span>
          </div>
          <div>
            <div style={{ fontWeight: 600, fontSize: 13, color: 'var(--ink-1)' }}>{name}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{role}</div>
          </div>
        </div>
      </div>
    );
  }

  // ---- Main Component ----
  function PricingPage({ lang, onBack, currentUser }) {
    const [annual, setAnnual] = useState(true);
    const [pendingPlanKey, setPendingPlanKey] = useState(null);
    const [pendingTrial, setPendingTrial] = useState(false);
    const [trialLoading, setTrialLoading] = useState(false);

    // Quand currentUser passe de null → user, on lance le Checkout ou le trial en attente.
    useEffect(() => {
      if (currentUser && pendingPlanKey) {
        const key = pendingPlanKey;
        setPendingPlanKey(null);
        startCheckout(key);
      }
      if (currentUser && pendingTrial) {
        setPendingTrial(false);
        handleStartTrial(setPendingTrial, setTrialLoading);
      }
    }, [currentUser, pendingPlanKey, pendingTrial]);

    const handleCTA = (plan) => {
      if (plan.id === 'decouverte') {
        if (currentUser) {
          window.navigateTo('#/');
        } else {
          openLoginModal();
        }
        return;
      }

      const cycle = annual ? 'annual' : 'monthly';
      const planKey = `${plan.id}_${cycle}`;

      // Lead event — clic sur un CTA payant
      if (window.vestora && window.vestora.analytics) {
        window.vestora.analytics.track('Lead', { plan: plan.id, cycle });
      }

      if (!currentUser) {
        setPendingPlanKey(planKey);
        openLoginModal();
      } else {
        startCheckout(planKey);
      }
    };

    return (
      <div style={{
        height: '100vh',
        background: 'var(--bg)',
        overflowY: 'auto',
        fontFamily: 'var(--sans)',
      }}>
        {/* Back nav */}
        <div style={{
          position: 'sticky', top: 0, zIndex: 40,
          borderBottom: '1px solid var(--line)',
          background: 'var(--bg-elev)',
          padding: '0 24px',
          height: 56,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <button
            onClick={onBack || (() => window.navigateTo('#/'))}
            style={{
              display: 'flex', alignItems: 'center', gap: 6,
              background: 'none', border: 'none', cursor: 'pointer',
              color: 'var(--ink-2)', fontSize: 14, fontFamily: 'inherit',
              padding: '4px 0',
            }}
          >
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
              <path d="M10 3L5 8l5 5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
            Retour
          </button>
          <a href="#/" style={{ textDecoration: 'none', color: 'var(--ink-1)', fontWeight: 600, fontSize: 15, letterSpacing: '-0.01em' }}>
            Vestora
          </a>
          <div style={{ width: 60 }} />
        </div>

        {/* Hero */}
        <div style={{
          textAlign: 'center',
          padding: '64px 24px 40px',
          maxWidth: 720, margin: '0 auto',
        }}>
          <div style={{
            display: 'inline-block',
            background: 'var(--accent-soft)',
            color: 'var(--accent-ink)',
            borderRadius: 20, padding: '4px 14px',
            fontSize: 12, fontWeight: 600, letterSpacing: '0.04em',
            marginBottom: 20, textTransform: 'uppercase',
          }}>
            Tarifs
          </div>
          <h1 style={{
            fontFamily: 'var(--serif)', fontSize: 'clamp(28px, 5vw, 44px)',
            fontWeight: 500, margin: '0 0 16px', color: 'var(--ink-1)',
            lineHeight: 1.15, letterSpacing: '-0.02em',
          }}>
            Analysez votre prochain investissement.<br />
            <em style={{ fontStyle: 'italic', color: 'var(--accent-ink)' }}>En toute clarté.</em>
          </h1>
          <p style={{
            fontSize: 16, color: 'var(--ink-2)', margin: '0 0 36px',
            lineHeight: 1.6, maxWidth: 520, marginLeft: 'auto', marginRight: 'auto',
          }}>
            Le seul moteur d'analyse multi-logement Canada-native avec fiscalité QC, profils investisseur et hypothèses personnalisables.
          </p>

          {/* Toggle annuel/mensuel */}
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 12,
            background: 'var(--bg-warm)', borderRadius: 40,
            padding: '4px', border: '1px solid var(--line)',
          }}>
            <button
              onClick={() => setAnnual(false)}
              style={{
                padding: '8px 20px', borderRadius: 36, border: 'none',
                background: !annual ? 'var(--bg-elev)' : 'transparent',
                color: !annual ? 'var(--ink-1)' : 'var(--ink-3)',
                fontWeight: !annual ? 600 : 400, fontSize: 14,
                cursor: 'pointer', fontFamily: 'inherit',
                boxShadow: !annual ? 'var(--shadow-sm)' : 'none',
                transition: 'all 0.2s',
              }}
            >
              Mensuel
            </button>
            <button
              onClick={() => setAnnual(true)}
              style={{
                padding: '8px 20px', borderRadius: 36, border: 'none',
                background: annual ? 'var(--accent)' : 'transparent',
                color: annual ? 'var(--accent-fg)' : 'var(--ink-3)',
                fontWeight: annual ? 600 : 400, fontSize: 14,
                cursor: 'pointer', fontFamily: 'inherit',
                boxShadow: annual ? 'var(--shadow-sm)' : 'none',
                transition: 'all 0.2s',
                display: 'flex', alignItems: 'center', gap: 6,
              }}
            >
              Annuel
              <span style={{
                background: annual ? 'rgba(255,255,255,0.2)' : 'var(--accent-soft)',
                color: annual ? 'var(--accent-fg)' : 'var(--accent-ink)',
                fontSize: 11, fontWeight: 700, borderRadius: 10,
                padding: '2px 7px',
              }}>
                −20%
              </span>
            </button>
          </div>
        </div>

        {/* Cards */}
        <div style={{
          maxWidth: 1100, margin: '0 auto', padding: '0 24px 64px',
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',
          gap: 24, alignItems: 'start',
        }}>
          {PLANS.map((plan) => {
            const isAnchor = plan.anchor;
            const price = annual
              ? (plan.annualPerMonth === 0 ? 0 : plan.annualPerMonth)
              : plan.monthlyPrice;
            const priceLabel = price === 0 ? 'Gratuit' : `${price}$/mo`;
            const annualNote = annual && plan.annualPerMonth > 0
              ? `Facturé ${plan.annualPrice}$/an`
              : plan.monthlyPrice > 0 ? 'Facturé mensuellement' : null;

            return (
              <div
                key={plan.id}
                style={{
                  background: 'var(--bg-elev)',
                  border: plan.badge
                    ? '2px solid var(--accent)'
                    : isAnchor
                    ? '1.5px solid var(--line)'
                    : '1px solid var(--line)',
                  borderRadius: 'var(--radius-lg)',
                  padding: '28px 24px 24px',
                  position: 'relative',
                  boxShadow: plan.badge ? 'var(--shadow-lg)' : isAnchor ? 'var(--shadow-md)' : 'var(--shadow-sm)',
                  transform: isAnchor ? 'scale(1.03)' : 'none',
                  transformOrigin: 'top center',
                  transition: 'box-shadow 0.2s, transform 0.2s',
                }}
                onMouseEnter={e => { e.currentTarget.style.boxShadow = 'var(--shadow-lg)'; }}
                onMouseLeave={e => {
                  e.currentTarget.style.boxShadow = plan.badge
                    ? 'var(--shadow-lg)'
                    : isAnchor ? 'var(--shadow-md)' : 'var(--shadow-sm)';
                }}
              >
                {/* Badge populaire */}
                {plan.badge && (
                  <div style={{
                    position: 'absolute', top: -14, left: '50%', transform: 'translateX(-50%)',
                    background: 'var(--accent)', color: 'var(--accent-fg)',
                    borderRadius: 20, padding: '4px 14px',
                    fontSize: 12, fontWeight: 700, whiteSpace: 'nowrap',
                    boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
                  }}>
                    {plan.badge}
                  </div>
                )}

                {/* Anchor label */}
                {isAnchor && (
                  <div style={{
                    position: 'absolute', top: -13, right: 20,
                    background: 'var(--ink-1)', color: 'var(--bg)',
                    borderRadius: 20, padding: '3px 12px',
                    fontSize: 11, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase',
                  }}>
                    Référence pro
                  </div>
                )}

                {/* Plan name */}
                <div style={{ marginBottom: 8 }}>
                  <span style={{
                    fontFamily: 'var(--serif)', fontSize: 20, fontWeight: 500,
                    color: 'var(--ink-1)', letterSpacing: '-0.01em',
                  }}>
                    {plan.name}
                  </span>
                </div>

                {/* Price */}
                <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, marginBottom: 4 }}>
                  <span style={{
                    fontFamily: 'var(--mono)', fontSize: isAnchor ? 42 : 36,
                    fontWeight: 700, color: plan.badge ? 'var(--accent-ink)' : 'var(--ink-1)',
                    lineHeight: 1,
                  }}>
                    {priceLabel}
                  </span>
                </div>
                {annualNote && (
                  <div style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 4 }}>
                    {annualNote}
                  </div>
                )}
                {annual && plan.monthlyPrice > 0 && (
                  <div style={{ fontSize: 12, color: 'oklch(0.42 0.13 150)', marginBottom: 16, fontWeight: 500 }}>
                    Au lieu de {plan.monthlyPrice}$/mo — 2 mois offerts
                  </div>
                )}
                {!annual && plan.monthlyPrice === 0 && <div style={{ height: 8 }} />}
                {!annual && plan.monthlyPrice > 0 && <div style={{ height: 24 }} />}

                {/* Divider */}
                <div style={{ borderTop: '1px solid var(--line)', margin: '12px 0 20px' }} />

                {/* CTA trial gratuit — uniquement pour la carte Pro (anchor) */}
                {isAnchor && (
                  <button
                    onClick={() => handleStartTrial(setPendingTrial, setTrialLoading)}
                    disabled={trialLoading}
                    style={{
                      width: '100%', padding: '12px 16px',
                      borderRadius: 'var(--radius)',
                      border: '2px solid var(--ink-1)',
                      background: 'transparent',
                      color: 'var(--ink-1)',
                      fontWeight: 700, fontSize: 14, cursor: trialLoading ? 'not-allowed' : 'pointer',
                      fontFamily: 'inherit',
                      transition: 'opacity 0.15s, transform 0.15s',
                      marginBottom: 8,
                      opacity: trialLoading ? 0.65 : 1,
                    }}
                    onMouseEnter={e => { if (!trialLoading) { e.currentTarget.style.background = 'var(--ink-1)'; e.currentTarget.style.color = 'var(--bg)'; } }}
                    onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--ink-1)'; }}
                  >
                    {trialLoading ? '…' : '🎁 Essai gratuit 7 jours'}
                  </button>
                )}

                {/* CTA standard */}
                <button
                  onClick={() => handleCTA(plan)}
                  style={{
                    width: '100%', padding: '12px 16px',
                    borderRadius: 'var(--radius)',
                    border: plan.badge || isAnchor ? 'none' : '1.5px solid var(--line)',
                    background: plan.badge
                      ? 'var(--accent)'
                      : isAnchor
                      ? 'var(--ink-1)'
                      : 'var(--bg-warm)',
                    color: plan.badge
                      ? 'var(--accent-fg)'
                      : isAnchor
                      ? 'var(--bg)'
                      : 'var(--ink-1)',
                    fontWeight: 600, fontSize: 14, cursor: 'pointer',
                    fontFamily: 'inherit',
                    transition: 'opacity 0.15s, transform 0.15s',
                    marginBottom: 8,
                  }}
                  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)'; }}
                >
                  {plan.ctaLabel}
                </button>

                {/* Note sous CTA */}
                <div style={{
                  textAlign: 'center', fontSize: 12, color: 'var(--ink-3)',
                  marginBottom: 20,
                }}>
                  {plan.note}
                  {plan.ctaSecondary && ` · ${plan.ctaSecondary}`}
                </div>

                {/* Features list */}
                <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
                  {plan.features.map((f, i) => (
                    <li key={i} style={{
                      display: 'flex', alignItems: 'flex-start', gap: 10,
                      fontSize: 13, color: f.included ? 'var(--ink-1)' : 'var(--ink-4)',
                    }}>
                      {f.included ? <CheckIcon /> : <LockIcon />}
                      <span style={{ lineHeight: 1.4 }}>
                        {f.label}
                        {f.note && (
                          <span style={{ display: 'block', fontSize: 11, color: 'var(--ink-3)', marginTop: 1 }}>
                            {f.note}
                          </span>
                        )}
                      </span>
                    </li>
                  ))}
                </ul>
              </div>
            );
          })}
        </div>

        {/* Entreprise CTA */}
        <div style={{
          maxWidth: 700, margin: '0 auto 64px', padding: '28px 32px',
          background: 'var(--bg-warm)',
          border: '1px solid var(--line)', borderRadius: 'var(--radius-lg)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          gap: 24, flexWrap: 'wrap',
        }}>
          <div>
            <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 4 }}>
              🏢 Entreprise — Courtiers, fonds, family offices
            </div>
            <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.5 }}>
              Multi-sièges, white-label, API REST, client matchmaking engine, SLA, onboarding 1-on-1.
              À partir de 149$/siège/mois.
            </div>
          </div>
          <a
            href="mailto:contact@vestora.ca?subject=Vestora Entreprise — demande d'information"
            style={{
              display: 'inline-block', padding: '11px 22px',
              background: 'var(--ink-1)', color: 'var(--bg)',
              borderRadius: 'var(--radius)', textDecoration: 'none',
              fontSize: 14, fontWeight: 600, whiteSpace: 'nowrap',
              flexShrink: 0,
            }}
          >
            Nous contacter
          </a>
        </div>

        {/* Tableau de comparaison */}
        <div style={{ maxWidth: 900, margin: '0 auto 80px', padding: '0 24px' }}>
          <h2 style={{
            fontFamily: 'var(--serif)', fontSize: 26, fontWeight: 500,
            textAlign: 'center', marginBottom: 32, color: 'var(--ink-1)',
            letterSpacing: '-0.01em',
          }}>
            Comparaison détaillée
          </h2>
          <div style={{ overflowX: 'auto' }}>
            <table style={{
              width: '100%', borderCollapse: 'collapse',
              fontSize: 13, color: 'var(--ink-1)',
            }}>
              <thead>
                <tr style={{ borderBottom: '2px solid var(--line)' }}>
                  <th style={{ textAlign: 'left', padding: '10px 12px', fontWeight: 600, width: '42%' }}>
                    Fonctionnalité
                  </th>
                  {PLANS.map(p => (
                    <th key={p.id} style={{
                      textAlign: 'center', padding: '10px 12px', fontWeight: 700,
                      color: p.badge ? 'var(--accent-ink)' : 'var(--ink-1)',
                      fontFamily: 'var(--serif)',
                    }}>
                      {p.name}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {COMPARE_FEATURES.map((row, i) => (
                  <tr key={i} style={{
                    borderBottom: '1px solid var(--line-soft)',
                    background: i % 2 === 0 ? 'transparent' : 'var(--bg-warm)',
                  }}>
                    <td style={{ padding: '9px 12px', color: 'var(--ink-2)', lineHeight: 1.4 }}>
                      {row.label}
                    </td>
                    <td style={{ textAlign: 'center', padding: '9px 12px' }}>
                      <CellValue val={row.decouverte} />
                    </td>
                    <td style={{
                      textAlign: 'center', padding: '9px 12px',
                      background: 'oklch(0.36 0.07 155 / 0.04)',
                    }}>
                      <CellValue val={row.investisseur} />
                    </td>
                    <td style={{ textAlign: 'center', padding: '9px 12px' }}>
                      <CellValue val={row.pro} />
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {/* FAQ */}
        <div style={{ maxWidth: 680, margin: '0 auto 80px', padding: '0 24px' }}>
          <h2 style={{
            fontFamily: 'var(--serif)', fontSize: 26, fontWeight: 500,
            textAlign: 'center', marginBottom: 32, color: 'var(--ink-1)',
            letterSpacing: '-0.01em',
          }}>
            Questions fréquentes
          </h2>
          {FAQ.map((item, i) => (
            <FAQItem key={i} q={item.q} a={item.a} />
          ))}
        </div>

        {/* Témoignages */}
        <div style={{ maxWidth: 960, margin: '0 auto 80px', padding: '0 24px' }}>
          <h2 style={{
            fontFamily: 'var(--serif)', fontSize: 26, fontWeight: 500,
            textAlign: 'center', marginBottom: 12, color: 'var(--ink-1)',
            letterSpacing: '-0.01em',
          }}>
            Ils analysent avec Vestora
          </h2>
          <p style={{
            textAlign: 'center', fontSize: 14, color: 'var(--ink-3)',
            marginBottom: 36, lineHeight: 1.6,
          }}>
            Des investisseurs et professionnels de l'immobilier au Québec
          </p>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))',
            gap: 20,
          }}>
            {TESTIMONIALS.map((t, i) => (
              <TestimonialCard key={i} {...t} />
            ))}
          </div>
        </div>

        {/* Footer note */}
        <div style={{
          textAlign: 'center', padding: '24px 24px 48px',
          borderTop: '1px solid var(--line)',
          fontSize: 13, color: 'var(--ink-3)', lineHeight: 1.7,
        }}>
          <p style={{ margin: '0 0 8px' }}>
            Pas de carte requise pour Découverte · Annule en 1 clic · Support par email
          </p>
          <p style={{ margin: 0 }}>
            Questions ? <a href="mailto:contact@vestora.ca" style={{ color: 'var(--accent-ink)', textDecoration: 'none' }}>contact@vestora.ca</a>
          </p>
        </div>
      </div>
    );
  }

  window.PricingPage = PricingPage;
})();
