// MliCompareTable — comparatif MLI-Select 40 ans vs Conventionnel 25 ans
// (Vague 3 PR 3.3 — Pro Courtier)
//
// Affiche cote a cote les deux scenarios de financement (mise de fonds,
// prime SCHL, paiement mensuel, cash flow, DSCR, ROE 5 ans, economie
// d'interets 5 ans) avec une ligne synthese "Recommendation" motivee.
//
// Gating Pro : feature 'mli_compare' (cf. data/site/src/lib/tier-gate.js).
//   - decouverte / investisseur : preview brouillee + bouton "Debloquer Pro"
//   - pro / entreprise : table active
//
// Eligibilite : si listing < 5 unites residentielles, on n'affiche pas la
// table mais un message clair indiquant la raison.
//
// Conventions : IIFE, React global, expose window.MliCompareTable.

(function () {
  'use strict';

  const { useState, useMemo, useEffect } = React;

  // ── Helpers format ──────────────────────────────────────────────────────
  function fmtMoney(v) {
    if (v == null || !Number.isFinite(Number(v))) return '—';
    return Math.round(Number(v)).toLocaleString('fr-CA') + ' $';
  }
  function fmtMoneySigned(v) {
    if (v == null || !Number.isFinite(Number(v))) return '—';
    const n = Math.round(Number(v));
    return (n >= 0 ? '+' : '−') + Math.abs(n).toLocaleString('fr-CA') + ' $';
  }
  function fmtPct(v, d) {
    if (v == null || !Number.isFinite(Number(v))) return '—';
    return (Number(v) * 100).toFixed(d == null ? 2 : d) + ' %';
  }
  function fmtRatio(v) {
    if (v == null || !Number.isFinite(Number(v))) return '—';
    return Number(v).toFixed(2);
  }

  function TT(props) {
    const Comp = window.TermTooltip;
    if (!Comp) return React.createElement('span', null, props.children);
    return React.createElement(Comp, { term: props.term, badge: props.badge !== false }, props.children);
  }

  // ── Composant principal ─────────────────────────────────────────────────
  function MliCompareTable(props) {
    const listing = props.listing || {};
    const lang = props.lang || 'fr';
    const FR = lang === 'fr';

    // Gating
    const [userTier, setUserTier] = useState('decouverte');
    const [paywallOpen, setPaywallOpen] = useState(false);
    const [showAssumptions, setShowAssumptions] = useState(false);

    useEffect(function () {
      const tg = window.vestora && window.vestora.tierGate;
      if (tg && typeof tg.getCurrentTier === 'function') {
        tg.getCurrentTier()
          .then(function (t) { setUserTier(t); })
          .catch(function () { setUserTier('decouverte'); });
      }
    }, []);

    // Calcul comparatif (memo)
    const result = useMemo(function () {
      if (!window.underwriting || typeof window.underwriting.compareMliVsConventional !== 'function') {
        return null;
      }
      if (!listing || !Number(listing.price)) return null;
      try {
        return window.underwriting.compareMliVsConventional(listing, {});
      } catch (e) {
        if (window.console) console.warn('MliCompareTable compute error', e);
        return null;
      }
    }, [listing]);

    if (!result) return null;

    // Eligibilite : si non eligible → message court, pas de table.
    if (result.mli && result.mli.eligible === false) {
      return React.createElement(
        'section',
        { id: 'section-mli-compare', style: { marginTop: 16 } },
        React.createElement(
          'h3',
          { className: 'section-title' },
          React.createElement(TT, { term: 'mli_select' }, FR ? 'MLI-Select vs Conventionnel' : 'MLI-Select vs Conventional')
        ),
        React.createElement(
          'div',
          {
            style: {
              padding: '12px 14px',
              background: '#f8fafc',
              border: '1px solid #e2e8f0',
              borderRadius: 8,
              fontSize: 13,
              color: '#475569',
              lineHeight: 1.5,
            },
          },
          FR
            ? 'Cet immeuble n\'est pas éligible MLI-Select.'
            : 'This building is not eligible for MLI-Select.',
          React.createElement('br'),
          React.createElement(
            'small',
            { style: { color: '#64748b', fontSize: 12 } },
            FR ? 'Raison : ' : 'Reason: ',
            result.mli.reason_if_not || (FR ? 'critères SCHL non remplis.' : 'CMHC criteria not met.')
          )
        )
      );
    }

    // Tier gating Pro
    const tg = window.vestora && window.vestora.tierGate;
    const isLocked = !!(tg && tg.canAccess && !tg.canAccess('mli_compare', userTier));

    // ── Render table ─────────────────────────────────────────────────────
    const mli = result.mli || {};
    const conv = result.conv || {};
    const delta = result.delta || {};
    const reco = result.recommendation || {};

    const styles = {
      section: { marginTop: 16 },
      tableWrap: {
        border: '1px solid var(--line, #e2e8f0)',
        borderRadius: 8,
        overflow: 'hidden',
        background: 'var(--bg-elev, #fff)',
      },
      table: { width: '100%', borderCollapse: 'collapse', fontSize: 13 },
      th: {
        padding: '10px 12px',
        background: 'var(--bg-soft, #faf7f2)',
        textAlign: 'left',
        fontWeight: 600,
        fontSize: 12,
        color: 'var(--ink-2, #475569)',
        borderBottom: '1px solid var(--line, #e2e8f0)',
      },
      thNum: { textAlign: 'right' },
      td: {
        padding: '8px 12px',
        borderBottom: '1px solid var(--line, #f1f5f9)',
        fontSize: 13,
        color: 'var(--ink, #0f172a)',
      },
      tdNum: { textAlign: 'right', fontVariantNumeric: 'tabular-nums' },
      tdLabel: { color: 'var(--ink-2, #475569)', fontSize: 12 },
      recoRow: {
        background: reco.winner === 'mli' ? '#ecfdf5'
          : reco.winner === 'conv' ? '#eff6ff'
          : '#fef3c7',
      },
      recoLabel: {
        fontWeight: 600,
        color: reco.winner === 'mli' ? '#065f46'
          : reco.winner === 'conv' ? '#1e3a8a'
          : '#78350f',
      },
      btnLink: {
        background: 'transparent', border: 'none',
        color: 'var(--ink-2, #475569)', textDecoration: 'underline',
        fontSize: 12, cursor: 'pointer', padding: '4px 0',
      },
      blurOverlay: {
        position: 'relative',
      },
      blurContent: {
        filter: 'blur(5px)', pointerEvents: 'none', userSelect: 'none', opacity: 0.5,
      },
      unlockOverlay: {
        position: 'absolute', inset: 0,
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        gap: 10, zIndex: 5, padding: 20,
      },
      unlockBtn: {
        padding: '8px 16px', borderRadius: 6,
        background: 'var(--brand, #2c3e2d)', color: '#fff',
        border: 'none', cursor: 'pointer', fontWeight: 600, fontSize: 13,
      },
    };

    function recoText() {
      if (reco.winner === 'mli') return FR ? 'MLI-Select recommandé' : 'MLI-Select recommended';
      if (reco.winner === 'conv') return FR ? 'Conventionnel recommandé' : 'Conventional recommended';
      return FR ? 'Choix neutre' : 'Neutral choice';
    }

    const rows = [
      {
        label: React.createElement(TT, { term: 'mise_de_fonds' }, FR ? 'Mise de fonds' : 'Down payment'),
        conv: fmtMoney(conv.mef_required),
        mli: fmtMoney(mli.mef_required),
        delta: delta.mef_delta != null ? fmtMoneySigned(delta.mef_delta) : '—',
      },
      {
        label: React.createElement(TT, { term: 'prime_schl' }, FR ? 'Prime SCHL' : 'CMHC premium'),
        conv: FR ? 's/o' : 'n/a',
        mli: fmtMoney(mli.prime_schl),
        delta: '—',
      },
      {
        label: FR ? 'Paiement mensuel' : 'Monthly payment',
        conv: fmtMoney(conv.monthly_payment),
        mli: fmtMoney(mli.monthly_payment),
        delta: '—',
      },
      {
        label: FR ? 'Cash-flow mensuel' : 'Monthly cash flow',
        conv: fmtMoneySigned(conv.monthly_cashflow),
        mli: fmtMoneySigned(mli.monthly_cashflow),
        delta: delta.cashflow_delta_monthly != null
          ? fmtMoneySigned(delta.cashflow_delta_monthly) : '—',
      },
      {
        label: React.createElement(TT, { term: 'rcd' }, 'DSCR'),
        conv: fmtRatio(conv.dscr),
        mli: fmtRatio(mli.dscr),
        delta: '—',
      },
      {
        label: React.createElement(TT, { term: 'roi' }, FR ? 'ROE 5 ans' : '5-yr ROE'),
        conv: fmtPct(conv.roe_5y, 1),
        mli: fmtPct(mli.roe_5y, 1),
        delta: delta.roe_delta != null ? (delta.roe_delta >= 0 ? '+' : '−') +
          Math.abs(delta.roe_delta * 100).toFixed(1) + ' pt' : '—',
      },
      {
        label: FR ? 'Intérêts cumulés 5 ans' : 'Total interest 5 yrs',
        conv: fmtMoney(conv.total_interest_5y),
        mli: fmtMoney(mli.total_interest_5y),
        delta: delta.interest_savings_5y != null
          ? fmtMoneySigned(delta.interest_savings_5y) : '—',
      },
    ];

    const tableEl = React.createElement(
      'div',
      { style: styles.tableWrap },
      React.createElement(
        'table',
        { style: styles.table },
        React.createElement(
          'thead',
          null,
          React.createElement(
            'tr',
            null,
            React.createElement('th', { style: styles.th }, FR ? 'Critère' : 'Criterion'),
            React.createElement('th', { style: Object.assign({}, styles.th, styles.thNum) },
              FR ? 'Conv. 25 ans' : 'Conv. 25 yrs'),
            React.createElement('th', { style: Object.assign({}, styles.th, styles.thNum) },
              FR ? 'MLI-Select 40 ans' : 'MLI-Select 40 yrs'),
            React.createElement('th', { style: Object.assign({}, styles.th, styles.thNum) },
              FR ? 'Δ MLI − Conv.' : 'Δ MLI − Conv.')
          )
        ),
        React.createElement(
          'tbody',
          null,
          rows.map(function (r, i) {
            return React.createElement(
              'tr',
              { key: i },
              React.createElement('td', { style: Object.assign({}, styles.td, styles.tdLabel) }, r.label),
              React.createElement('td', { style: Object.assign({}, styles.td, styles.tdNum) }, r.conv),
              React.createElement('td', { style: Object.assign({}, styles.td, styles.tdNum) }, r.mli),
              React.createElement('td', { style: Object.assign({}, styles.td, styles.tdNum) }, r.delta)
            );
          }),
          React.createElement(
            'tr',
            { style: styles.recoRow },
            React.createElement(
              'td',
              { style: Object.assign({}, styles.td, { fontWeight: 600 }), colSpan: 1 },
              FR ? 'Recommandation' : 'Recommendation'
            ),
            React.createElement(
              'td',
              { style: Object.assign({}, styles.td, { colSpan: 3 }), colSpan: 3 },
              React.createElement(
                'div',
                { style: styles.recoLabel },
                recoText()
              ),
              React.createElement(
                'div',
                { style: { fontSize: 12, color: 'var(--ink-2, #475569)', marginTop: 4, lineHeight: 1.5 } },
                reco.rationale || ''
              )
            )
          )
        )
      ),
      React.createElement(
        'div',
        { style: { padding: '8px 12px', borderTop: '1px solid var(--line, #e2e8f0)' } },
        React.createElement(
          'button',
          {
            type: 'button',
            style: styles.btnLink,
            onClick: function () { setShowAssumptions(true); },
          },
          FR ? 'Voir les hypothèses' : 'View assumptions'
        )
      )
    );

    // Si bloque par tier : preview floutee + CTA paywall
    let body;
    if (isLocked) {
      body = React.createElement(
        'div',
        { style: styles.blurOverlay },
        React.createElement('div', { style: styles.blurContent }, tableEl),
        React.createElement(
          'div',
          { style: styles.unlockOverlay },
          React.createElement('div', { style: { fontSize: 24 } }, '🔒'),
          React.createElement(
            'p',
            {
              style: {
                textAlign: 'center', maxWidth: 360, margin: 0,
                color: 'var(--ink-2, #475569)', fontSize: 13, lineHeight: 1.5,
              },
            },
            FR
              ? 'Le comparatif MLI-Select vs Conventionnel est réservé au plan Pro courtier.'
              : 'MLI-Select vs Conventional comparison requires the Pro broker plan.'
          ),
          React.createElement(
            'button',
            {
              type: 'button',
              style: styles.unlockBtn,
              onClick: function () { setPaywallOpen(true); },
            },
            FR ? 'Débloquer avec Pro' : 'Unlock with Pro'
          )
        )
      );
    } else {
      body = tableEl;
    }

    // Modal hypotheses
    let assumptionsModal = null;
    if (showAssumptions && mli && mli.eligible) {
      const overlayStyle = {
        position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.55)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        zIndex: 10000, padding: 16,
      };
      const cardStyle = {
        background: '#fff', borderRadius: 12, maxWidth: 520, width: '100%',
        padding: 20, fontSize: 13, lineHeight: 1.6,
        boxShadow: '0 20px 60px rgba(15,23,42,0.30)',
      };
      assumptionsModal = React.createElement(
        'div',
        {
          style: overlayStyle,
          onClick: function (e) { if (e.target === e.currentTarget) setShowAssumptions(false); },
        },
        React.createElement(
          'div',
          { style: cardStyle },
          React.createElement(
            'div',
            { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 } },
            React.createElement('h4', { style: { margin: 0, fontSize: 15 } },
              FR ? 'Hypothèses appliquées' : 'Assumptions used'),
            React.createElement(
              'button',
              {
                type: 'button',
                style: { background: 'transparent', border: 'none', fontSize: 20, cursor: 'pointer', color: '#64748b' },
                onClick: function () { setShowAssumptions(false); },
                'aria-label': FR ? 'Fermer' : 'Close',
              },
              '×'
            )
          ),
          React.createElement(
            'div',
            { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 } },
            React.createElement(
              'div',
              null,
              React.createElement('div', { style: { fontWeight: 600, marginBottom: 4 } },
                FR ? 'Conventionnel 25 ans' : 'Conventional 25 yrs'),
              React.createElement('div', null, (FR ? 'Mise de fonds : ' : 'Down payment: ') + fmtPct(conv.down_payment_pct, 0)),
              React.createElement('div', null, (FR ? 'Taux : ' : 'Rate: ') + fmtPct(conv.rate, 2)),
              React.createElement('div', null, (FR ? 'Amortissement : ' : 'Amortization: ') + conv.amort_years + (FR ? ' ans' : ' yrs')),
              React.createElement('div', null, (FR ? 'Prêt : ' : 'Loan: ') + fmtMoney(conv.loan_amount))
            ),
            React.createElement(
              'div',
              null,
              React.createElement('div', { style: { fontWeight: 600, marginBottom: 4 } },
                FR ? 'MLI-Select 40 ans' : 'MLI-Select 40 yrs'),
              React.createElement('div', null, (FR ? 'Mise de fonds : ' : 'Down payment: ') + fmtPct(mli.down_payment_pct, 0)),
              React.createElement('div', null, (FR ? 'Taux : ' : 'Rate: ') + fmtPct(mli.rate, 2)),
              React.createElement('div', null, (FR ? 'Amortissement : ' : 'Amortization: ') + mli.amort_years + (FR ? ' ans' : ' yrs')),
              React.createElement('div', null, (FR ? 'Prêt total (incl. prime) : ' : 'Total loan (incl. premium): ') + fmtMoney(mli.loan_amount))
            )
          ),
          React.createElement(
            'div',
            { style: { marginTop: 14, fontSize: 11, color: '#64748b', lineHeight: 1.5 } },
            FR
              ? 'Éligibilité MLI-Select non garantie (axes accessibilité/abordabilité/efficacité énergétique non vérifiables depuis Centris). Validez avec un courtier SCHL avant offre.'
              : 'MLI-Select eligibility not guaranteed (accessibility/affordability/energy axes not verifiable from Centris). Confirm with a CMHC broker before offer.'
          )
        )
      );
    }

    // PaywallModal optionnelle
    let paywallEl = null;
    if (paywallOpen && window.PaywallModal) {
      paywallEl = React.createElement(window.PaywallModal, {
        open: paywallOpen,
        onClose: function () { setPaywallOpen(false); },
        feature: 'mli_compare',
        featureLabel: FR ? 'Comparatif MLI-Select vs Conventionnel' : 'MLI-Select vs Conventional',
        requiredTier: 'pro',
        currentTier: userTier,
        reason: 'tier_too_low',
      });
    }

    return React.createElement(
      'section',
      { id: 'section-mli-compare', style: styles.section },
      React.createElement(
        'h3',
        { className: 'section-title' },
        React.createElement(TT, { term: 'mli_select' }, FR ? 'MLI-Select 40 ans vs Conventionnel 25 ans' : 'MLI-Select 40 yrs vs Conventional 25 yrs'),
        React.createElement(
          'small',
          { style: { display: 'block', color: 'var(--ink-3, #94a3b8)', fontSize: 11, marginTop: 2, fontWeight: 400 } },
          FR
            ? 'Comparatif côte à côte des deux financements admissibles aux immeubles 5 logements+.'
            : 'Side-by-side comparison of both financing options for 5+ unit buildings.'
        )
      ),
      body,
      assumptionsModal,
      paywallEl
    );
  }

  window.MliCompareTable = MliCompareTable;
})();
