// FicheBrandeeModal — Generation fiche PDF investisseur brandee courtier (PR 2.2 Vague 2)
//
// S'ouvre depuis :
//   - le drawer listing (bouton "Fiche brandee PDF" reserve aux courtiers Pro)
//   - BrokerTab_Clients (bouton sur chaque match opportunite)
//
// Champs override (avec valeurs par defaut du listing) :
//   price, gross_income, opex, rate, down_payment_pct, vacancy_pct
//
// Section "Apercu en direct" : recalcule cap rate / cash flow / DSCR cote
// client (reutilise window.underwriting si disponible — moteur underwriting.js).
//
// Bouton "Generer PDF" -> POST /api/v1/broker/fiche -> ouvre pdf_url dans
// un nouvel onglet.
//
// Convention : IIFE, React global, expose window.FicheBrandeeModal.

(function () {
  'use strict';

  const { useState, useEffect, useMemo } = React;

  // ---- helpers ------------------------------------------------------------

  function _toast(msg, type) {
    var el = document.createElement('div');
    el.textContent = msg;
    Object.assign(el.style, {
      position: 'fixed', bottom: '24px', left: '50%', transform: 'translateX(-50%)',
      background: type === 'error' ? 'oklch(0.35 0.12 25)' : 'oklch(0.18 0.012 85)',
      color: '#fff', padding: '12px 24px', borderRadius: '8px', zIndex: 10000,
      fontSize: '14px', fontFamily: 'Inter, sans-serif',
      boxShadow: '0 4px 16px rgba(0,0,0,0.25)',
    });
    document.body.appendChild(el);
    setTimeout(function () { el.remove(); }, 4000);
  }

  function _fmtMoney(v) {
    if (v == null || !Number.isFinite(Number(v))) return '—';
    return Number(v).toLocaleString('fr-CA', { maximumFractionDigits: 0 }) + ' $';
  }
  function _fmtPct(v, digits) {
    if (v == null || !Number.isFinite(Number(v))) return '—';
    return (Number(v) * 100).toFixed(digits == null ? 2 : digits) + ' %';
  }

  // Calcul KPIs cote client (preview live, identique a la logique backend) ----
  function _amortPayment(principal, rate, years) {
    if (principal <= 0 || rate <= 0 || years <= 0) return 0;
    var r = rate / 12;
    var n = years * 12;
    return principal * r / (1 - Math.pow(1 + r, -n));
  }

  function _resolveDefaults(listing) {
    var price = Number(listing?.price) || 0;
    var declared = Number(listing?.askingGrossIncome ?? listing?.asking_gross_income ?? listing?.grossIncome) || 0;
    var units = Number(listing?.totalUnits ?? listing?.total_units ?? listing?.units) || 0;
    var grossIncome = declared > 0 ? declared : (units > 0 ? units * 13200 : 0);

    var opexParts = [
      listing?.municipalTaxes ?? listing?.municipal_taxes,
      listing?.schoolTaxes ?? listing?.school_taxes,
      listing?.insurance,
      listing?.energyCost ?? listing?.energy_cost,
      listing?.maintenanceCost ?? listing?.maintenance_cost,
      listing?.snowRemoval ?? listing?.snow_removal,
      listing?.otherExpenses ?? listing?.other_expenses,
    ];
    var opexSum = opexParts.reduce(function (a, b) {
      var n = Number(b);
      return a + (Number.isFinite(n) ? n : 0);
    }, 0);
    var opex = opexSum > 0 ? opexSum : grossIncome * 0.40;

    return {
      price: price,
      grossIncome: grossIncome,
      opex: opex,
      rate: 0.0595,
      downPaymentPct: 0.25,
      vacancyPct: 0.04,
    };
  }

  function _computePreview(values) {
    var price = Number(values.price) || 0;
    var gross = Number(values.grossIncome) || 0;
    var opex = Number(values.opex) || 0;
    var rate = Number(values.rate) || 0;
    var dp = Number(values.downPaymentPct) || 0;
    var vac = Number(values.vacancyPct) || 0;

    var effectiveIncome = gross * Math.max(0, 1 - vac);
    var noi = Math.max(0, effectiveIncome - opex);
    var capRate = price > 0 ? noi / price : 0;
    var principal = price * (1 - dp);
    var monthly = _amortPayment(principal, rate, 25);
    var annualDebt = monthly * 12;
    var cashFlowYear = noi - annualDebt;
    var cashFlowMonth = cashFlowYear / 12;
    var dscr = annualDebt > 0 ? noi / annualDebt : 0;
    return {
      noi: noi,
      capRate: capRate,
      cashFlowYear: cashFlowYear,
      cashFlowMonth: cashFlowMonth,
      dscr: dscr,
      monthlyPayment: monthly,
    };
  }

  // ---- Composant ---------------------------------------------------------

  function FicheBrandeeModal({ open, onClose, listing, currentUser }) {
    var defaults = useMemo(function () { return _resolveDefaults(listing || {}); }, [listing]);

    const [values, setValues] = useState(defaults);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    // Options PDF (PR 3.3 Vague 3) : checkboxes "Inclure ..."
    const [pdfOptions, setPdfOptions] = useState({
      include_mli_compare: false,
    });

    useEffect(function () {
      if (open) {
        setValues(defaults);
        setError(null);
      }
    }, [open, defaults]);

    if (!open) return null;

    // Detection des overrides : champ != valeur par defaut
    var overridesDelta = {};
    Object.keys(values).forEach(function (k) {
      var d = Number(defaults[k]);
      var v = Number(values[k]);
      if (Number.isFinite(v) && (!Number.isFinite(d) || Math.abs(v - d) > 1e-9)) {
        overridesDelta[k] = v;
      }
    });
    var hasOverrides = Object.keys(overridesDelta).length > 0;

    var preview = _computePreview(values);

    var setNum = function (key) {
      return function (e) {
        var raw = e.target.value;
        setValues(function (prev) {
          var next = Object.assign({}, prev);
          next[key] = raw === '' ? '' : Number(raw);
          return next;
        });
      };
    };
    var setPct = function (key) {
      return function (e) {
        var raw = e.target.value;
        setValues(function (prev) {
          var next = Object.assign({}, prev);
          next[key] = raw === '' ? '' : Number(raw) / 100;
          return next;
        });
      };
    };

    async function handleSubmit() {
      if (!currentUser) {
        if (window.vestora && window.vestora.auth && typeof window.vestora.auth.openModal === 'function') {
          window.vestora.auth.openModal();
        }
        onClose();
        return;
      }
      setLoading(true);
      setError(null);
      try {
        var api = window.vestora && window.vestora.brokerApi;
        if (!api || typeof api.generateFiche !== 'function') {
          throw new Error('API broker indisponible.');
        }
        // Mapping camelCase -> snake_case backend
        var apiOverrides = {
          price: overridesDelta.price,
          gross_income: overridesDelta.grossIncome,
          opex: overridesDelta.opex,
          rate: overridesDelta.rate,
          down_payment_pct: overridesDelta.downPaymentPct,
          vacancy_pct: overridesDelta.vacancyPct,
        };
        var res = await api.generateFiche(String(listing.id), apiOverrides, pdfOptions);
        if (!res.ok) {
          var msg = (res.error && res.error.message) || 'Erreur generation PDF';
          if (res.error && res.error.status === 400) {
            setError('Configurez votre profil courtier d\'abord (Profil > Mon profil).');
          } else {
            setError(msg);
          }
          setLoading(false);
          return;
        }
        // Ouverture dans nouvel onglet
        if (res.data.pdfUrl) {
          window.open(res.data.pdfUrl, '_blank', 'noopener');
          _toast('Fiche PDF generee.', 'success');
          onClose();
        }
      } catch (e) {
        setError(String(e && e.message ? e.message : e));
      } finally {
        setLoading(false);
      }
    }

    // ---- Styles ---------------------------------------------------------
    var overlay = {
      position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.55)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      zIndex: 9999, padding: 16,
    };
    var card = {
      background: '#fff', borderRadius: 12, maxWidth: 720, width: '100%',
      maxHeight: '90vh', overflow: 'auto',
      boxShadow: '0 20px 60px rgba(15,23,42,0.30)',
      fontFamily: 'Inter, -apple-system, sans-serif',
    };
    var headerStyle = {
      padding: '18px 24px', borderBottom: '1px solid #e5e7eb',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    };
    var bodyStyle = { padding: '18px 24px' };
    var grid2 = {
      display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 14,
    };
    var label = { fontSize: 12, color: '#475569', marginBottom: 4, display: 'block', fontWeight: 500 };
    var input = {
      width: '100%', padding: '8px 10px', border: '1px solid #d1d5db',
      borderRadius: 6, fontSize: 14, fontFamily: 'inherit',
    };
    var preStyle = {
      background: '#faf7f2', border: '1px solid #e5e0d6', borderRadius: 8,
      padding: 14, marginTop: 16, marginBottom: 14,
    };
    var btnPrimary = {
      background: 'oklch(0.30 0.07 155)', color: '#fff', border: 'none',
      padding: '10px 20px', borderRadius: 6, fontWeight: 600, fontSize: 14,
      cursor: loading ? 'not-allowed' : 'pointer', opacity: loading ? 0.6 : 1,
    };
    var btnSecondary = {
      background: '#fff', color: '#475569', border: '1px solid #d1d5db',
      padding: '10px 20px', borderRadius: 6, fontWeight: 500, fontSize: 14,
      cursor: 'pointer', marginRight: 8,
    };

    return (
      <div style={overlay} onClick={function (e) { if (e.target === e.currentTarget) onClose(); }}>
        <div style={card}>
          <div style={headerStyle}>
            <div>
              <div style={{ fontSize: 18, fontWeight: 600, color: '#0F172A' }}>
                Fiche brandee PDF
              </div>
              <div style={{ fontSize: 12, color: '#64748b', marginTop: 2 }}>
                Genere une fiche investisseur a votre marque avec hypotheses personnalisees.
              </div>
            </div>
            <button onClick={onClose} aria-label="Fermer"
              style={{ background: 'transparent', border: 'none', fontSize: 22, cursor: 'pointer', color: '#64748b' }}>×</button>
          </div>

          <div style={bodyStyle}>
            <div style={{ fontSize: 13, color: '#0F172A', marginBottom: 10 }}>
              <strong>{listing?.address || listing?.address_full || 'Bien selectionne'}</strong>
            </div>

            <div style={grid2}>
              <div>
                <label style={label}>Prix d'achat ($)</label>
                <input type="number" min="0" step="1000" style={input}
                  value={values.price === '' ? '' : values.price}
                  onChange={setNum('price')} />
              </div>
              <div>
                <label style={label}>Revenus bruts annuels ($)</label>
                <input type="number" min="0" step="100" style={input}
                  value={values.grossIncome === '' ? '' : values.grossIncome}
                  onChange={setNum('grossIncome')} />
              </div>
              <div>
                <label style={label}>Depenses d'exploitation annuelles ($)</label>
                <input type="number" min="0" step="100" style={input}
                  value={values.opex === '' ? '' : values.opex}
                  onChange={setNum('opex')} />
              </div>
              <div>
                <label style={label}>Taux hypothecaire (%)</label>
                <input type="number" min="0" max="30" step="0.05" style={input}
                  value={values.rate === '' ? '' : (Number(values.rate) * 100).toFixed(2)}
                  onChange={setPct('rate')} />
              </div>
              <div>
                <label style={label}>Mise de fonds (%)</label>
                <input type="number" min="0" max="100" step="1" style={input}
                  value={values.downPaymentPct === '' ? '' : (Number(values.downPaymentPct) * 100).toFixed(0)}
                  onChange={setPct('downPaymentPct')} />
              </div>
              <div>
                <label style={label}>Vacance / mauvaises creances (%)</label>
                <input type="number" min="0" max="100" step="0.5" style={input}
                  value={values.vacancyPct === '' ? '' : (Number(values.vacancyPct) * 100).toFixed(1)}
                  onChange={setPct('vacancyPct')} />
              </div>
            </div>

            <div style={preStyle}>
              <div style={{ fontSize: 12, fontWeight: 600, color: '#0F172A', marginBottom: 8 }}>
                Apercu en direct {hasOverrides && <span style={{
                  background: '#fef3c7', color: '#92400e', padding: '1px 6px',
                  borderRadius: 3, fontSize: 10, marginLeft: 6,
                }}>HYPOTHESES MODIFIEES</span>}
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8, fontSize: 13 }}>
                <div><span style={{ color: '#64748b' }}>Cap rate :</span> <strong>{_fmtPct(preview.capRate)}</strong></div>
                <div><span style={{ color: '#64748b' }}>DSCR :</span> <strong>{preview.dscr.toFixed(2)}</strong></div>
                <div><span style={{ color: '#64748b' }}>Cash flow mensuel :</span> <strong>{_fmtMoney(preview.cashFlowMonth)}</strong></div>
                <div><span style={{ color: '#64748b' }}>NOI annuel :</span> <strong>{_fmtMoney(preview.noi)}</strong></div>
              </div>
            </div>

            {/* Options PDF (PR 3.3 Vague 3) */}
            <div style={{
              background: '#f8fafc', border: '1px solid #e2e8f0', borderRadius: 6,
              padding: '10px 12px', marginBottom: 12,
            }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: '#0F172A', marginBottom: 6 }}>
                Options PDF
              </div>
              <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: '#374151', cursor: 'pointer' }}>
                <input
                  type="checkbox"
                  checked={pdfOptions.include_mli_compare}
                  onChange={(e) => setPdfOptions(Object.assign({}, pdfOptions, { include_mli_compare: e.target.checked }))}
                />
                <span>Inclure le comparatif MLI-Select vs Conventionnel</span>
              </label>
              <div style={{ fontSize: 11, color: '#94a3b8', marginTop: 4, marginLeft: 24 }}>
                Pour immeubles 5 logements et plus (admissibles SCHL).
              </div>
            </div>

            {error && (
              <div style={{
                background: '#fef2f2', color: '#991b1b', border: '1px solid #fecaca',
                padding: '10px 12px', borderRadius: 6, fontSize: 13, marginBottom: 12,
              }}>{error}</div>
            )}

            <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 8 }}>
              <button style={btnSecondary} onClick={onClose} disabled={loading}>Annuler</button>
              <button style={btnPrimary} onClick={handleSubmit} disabled={loading}>
                {loading ? 'Generation en cours (3-6s)...' : 'Generer PDF'}
              </button>
            </div>

            <div style={{ fontSize: 11, color: '#94a3b8', marginTop: 12, lineHeight: 1.5 }}>
              A titre indicatif. Les chiffres sont des estimations basees sur les
              donnees publiques. Disclaimer OACIQ/AMF inclus automatiquement dans le PDF.
            </div>
          </div>
        </div>
      </div>
    );
  }

  window.FicheBrandeeModal = FicheBrandeeModal;
})();
