// CommercialUnderwritingPanel — Pro Commercial 129$/mo (Vague 4 PR 4.7)
//
// Panneau dedie modelisation 10 ans + IRR multi-annee + tornado chart + export Excel.
// Visible UNIQUEMENT pour les abonnes pro_commercial.
//
// Convention : IIFE, React global, hooks aliases useS/useM/useE.
// Expose window.CommercialUnderwritingPanel.

(function () {
  'use strict';

  const useS = React.useState;
  const useM = React.useMemo;
  const useE = React.useEffect;

  // ---------- Helpers format ----------
  function fmtMoney(v) {
    if (v == null || !Number.isFinite(Number(v))) return '—';
    var n = Math.round(Number(v));
    var sign = n < 0 ? '-' : '';
    var abs = Math.abs(n).toLocaleString('fr-CA');
    return sign + abs + ' $';
  }
  function fmtPct(v, digits) {
    if (v == null || !Number.isFinite(Number(v))) return '—';
    return (Number(v) * 100).toFixed(digits == null ? 2 : digits) + ' %';
  }
  function fmtMult(v) {
    if (v == null || !Number.isFinite(Number(v))) return '—';
    return Number(v).toFixed(2) + 'x';
  }

  // ---------- KPI Card ----------
  function KpiCard({ label, value, sub, tip }) {
    const TT = window.TermTooltip;
    const labelEl = (tip && TT)
      ? React.createElement(TT, { term: tip, badge: false }, label)
      : label;
    return (
      <div style={{
        background: '#fff', border: '1px solid #e5e7eb', borderRadius: 8,
        padding: '12px 14px', minWidth: 130, flex: 1,
      }}>
        <div style={{ fontSize: 11, color: '#64748b', textTransform: 'uppercase', letterSpacing: 0.5 }}>
          {labelEl}
        </div>
        <div style={{ fontSize: 20, fontWeight: 700, color: '#1e293b', marginTop: 4 }}>{value}</div>
        {sub && <div style={{ fontSize: 11, color: '#94a3b8', marginTop: 2 }}>{sub}</div>}
      </div>
    );
  }

  // ---------- Tornado Chart (SVG inline) ----------
  function TornadoChart({ data }) {
    if (!data || data.length === 0) {
      return <div style={{ color: '#94a3b8', fontStyle: 'italic' }}>Pas de donnees de sensibilite.</div>;
    }
    var maxMag = Math.max.apply(null, data.map(function (d) {
      return Math.max(Math.abs(d.impact_low_pp), Math.abs(d.impact_high_pp));
    }));
    maxMag = Math.max(maxMag, 1); // floor 1pp pour l'echelle
    var width = 520;
    var rowH = 28;
    var labelW = 170;
    var barW = width - labelW - 80;
    var centerX = labelW + barW / 2;
    var totalH = data.length * rowH + 20;
    return (
      <svg width={width} height={totalH} style={{ display: 'block', maxWidth: '100%' }}>
        {/* Ligne centrale */}
        <line x1={centerX} y1={5} x2={centerX} y2={totalH - 5} stroke="#cbd5e1" strokeWidth={1} />
        {data.map(function (d, i) {
          var y = i * rowH + 14;
          var lowW = (Math.abs(d.impact_low_pp) / maxMag) * (barW / 2);
          var highW = (Math.abs(d.impact_high_pp) / maxMag) * (barW / 2);
          // impact_low (parametre baisse) — bar a gauche si negatif sur IRR
          var lowDir = d.impact_low_pp < 0 ? -1 : 1;
          var highDir = d.impact_high_pp < 0 ? -1 : 1;
          return (
            <g key={d.parameter}>
              <text x={labelW - 8} y={y + 5} textAnchor="end" fontSize="11" fill="#475569">
                {d.label}
              </text>
              {/* Bar gauche (param -delta) */}
              <rect
                x={lowDir < 0 ? centerX - lowW : centerX}
                y={y - 8}
                width={lowW}
                height={16}
                fill="#fb923c"
                opacity={0.8}
              />
              {/* Bar droite (param +delta) */}
              <rect
                x={highDir < 0 ? centerX - highW : centerX}
                y={y - 8}
                width={highW}
                height={16}
                fill="#3b82f6"
                opacity={0.8}
              />
              <text x={width - 6} y={y + 5} textAnchor="end" fontSize="10" fill="#64748b">
                +/- {d.magnitude_pp.toFixed(1)} pp
              </text>
            </g>
          );
        })}
      </svg>
    );
  }

  // ---------- Panel principal ----------
  function CommercialUnderwritingPanel({ listing, userPlan, lang }) {
    var FR = (lang || 'fr') === 'fr';
    var TT = window.TermTooltip;

    // Verification tier
    if (userPlan !== 'pro_commercial' && userPlan !== 'agent_commercial') {
      return null;
    }
    if (!listing || !listing.id) return null;

    var [hyp, setHyp] = useS({
      growth_rent: 0.025,
      growth_opex: 0.025,
      exit_cap: 0.060,
      exit_year: 10,
      down_payment_pct: 0.25,
      interest_rate: 0.055,
      amortization_years: 25,
    });
    var [loading, setLoading] = useS(false);
    var [error, setError] = useS(null);
    var [result, setResult] = useS(null);
    var [excelLoading, setExcelLoading] = useS(false);

    function getToken() {
      if (window.vestora && window.vestora.auth && typeof window.vestora.auth.getToken === 'function') {
        return window.vestora.auth.getToken();
      }
      return Promise.resolve(null);
    }

    async function runUnderwriting() {
      setLoading(true);
      setError(null);
      try {
        var apiBase = (window.VESTORA_CONFIG && window.VESTORA_CONFIG.apiBase) || '';
        var token = await getToken();
        var headers = { 'Content-Type': 'application/json' };
        if (token) headers['Authorization'] = 'Bearer ' + token;
        var resp = await fetch(apiBase + '/api/v1/analysis/commercial_underwriting', {
          method: 'POST',
          headers: headers,
          body: JSON.stringify({
            listing_id: listing.id,
            hypotheses: hyp,
            years: 10,
            include_excel_url: false,
          }),
        });
        if (!resp.ok) {
          var txt = await resp.text();
          throw new Error('HTTP ' + resp.status + ' — ' + txt.slice(0, 200));
        }
        var data = await resp.json();
        setResult(data);
      } catch (e) {
        setError(e.message || String(e));
      } finally {
        setLoading(false);
      }
    }

    async function downloadExcel() {
      setExcelLoading(true);
      try {
        var apiBase = (window.VESTORA_CONFIG && window.VESTORA_CONFIG.apiBase) || '';
        var token = await getToken();
        var headers = { 'Content-Type': 'application/json' };
        if (token) headers['Authorization'] = 'Bearer ' + token;
        var resp = await fetch(apiBase + '/api/v1/analysis/commercial_underwriting/xlsx', {
          method: 'POST',
          headers: headers,
          body: JSON.stringify({
            listing_id: listing.id,
            hypotheses: hyp,
            years: 10,
          }),
        });
        if (!resp.ok) {
          var txt = await resp.text();
          throw new Error('HTTP ' + resp.status + ' — ' + txt.slice(0, 200));
        }
        var blob = await resp.blob();
        var url = URL.createObjectURL(blob);
        var a = document.createElement('a');
        a.href = url;
        a.download = 'vestora-proforma-' + listing.id + '.xlsx';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
      } catch (e) {
        setError('Excel: ' + (e.message || String(e)));
      } finally {
        setExcelLoading(false);
      }
    }

    // Run automatique au mount
    useE(function () {
      runUnderwriting();
      // eslint-disable-next-line
    }, [listing && listing.id]);

    function HypField({ label, value, onChange, min, max, step, suffix, tip }) {
      var labelEl = (tip && TT)
        ? React.createElement(TT, { term: tip, badge: false }, label)
        : label;
      return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4, minWidth: 130 }}>
          <label style={{ fontSize: 11, color: '#475569', fontWeight: 500 }}>{labelEl}</label>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <input
              type="number"
              value={value}
              min={min}
              max={max}
              step={step}
              onChange={function (e) { onChange(parseFloat(e.target.value)); }}
              style={{
                width: 70, padding: '4px 6px', border: '1px solid #cbd5e1',
                borderRadius: 4, fontSize: 13,
              }}
            />
            <span style={{ fontSize: 11, color: '#64748b' }}>{suffix}</span>
          </div>
        </div>
      );
    }

    var headerStyle = {
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      marginBottom: 14, paddingBottom: 10, borderBottom: '2px solid #1F3A5F',
    };

    return (
      <div style={{
        marginTop: 28, padding: 18, background: '#f8fafc',
        border: '1px solid #cbd5e1', borderRadius: 10,
      }}>
        <div style={headerStyle}>
          <div>
            <div style={{
              fontSize: 11, fontWeight: 700, color: '#1F3A5F', textTransform: 'uppercase',
              letterSpacing: 1, marginBottom: 2,
            }}>
              Pro Commercial 129$/mo
            </div>
            <h3 style={{ margin: 0, fontSize: 18, color: '#0f172a' }}>
              {FR ? 'Modelisation 10 ans + IRR + sensibilite' : '10-year model + IRR + sensitivity'}
            </h3>
          </div>
          <button
            onClick={downloadExcel}
            disabled={excelLoading || !result}
            style={{
              padding: '8px 16px', background: '#1F3A5F', color: '#fff',
              border: 'none', borderRadius: 6, fontWeight: 600, fontSize: 13,
              cursor: excelLoading ? 'wait' : 'pointer', opacity: excelLoading || !result ? 0.6 : 1,
            }}
          >
            {excelLoading ? (FR ? 'Generation…' : 'Generating…') : (FR ? 'Exporter Excel' : 'Export Excel')}
          </button>
        </div>

        {/* Form hypotheses */}
        <div style={{
          display: 'flex', flexWrap: 'wrap', gap: 14, marginBottom: 16,
          padding: 12, background: '#fff', borderRadius: 8, border: '1px solid #e5e7eb',
        }}>
          <HypField
            label={FR ? 'Croissance loyers' : 'Rent growth'}
            value={(hyp.growth_rent * 100).toFixed(1)}
            onChange={function (v) { setHyp({ ...hyp, growth_rent: v / 100 }); }}
            min={0} max={5} step={0.1} suffix="%/an"
          />
          <HypField
            label={FR ? 'Croissance OpEx' : 'OpEx growth'}
            value={(hyp.growth_opex * 100).toFixed(1)}
            onChange={function (v) { setHyp({ ...hyp, growth_opex: v / 100 }); }}
            min={0} max={5} step={0.1} suffix="%/an"
          />
          <HypField
            label={FR ? 'Cap rate sortie' : 'Exit cap'}
            value={(hyp.exit_cap * 100).toFixed(2)}
            onChange={function (v) { setHyp({ ...hyp, exit_cap: v / 100 }); }}
            min={3} max={9} step={0.05} suffix="%"
            tip="cap_rate"
          />
          <HypField
            label={FR ? 'Annee de sortie' : 'Exit year'}
            value={hyp.exit_year}
            onChange={function (v) { setHyp({ ...hyp, exit_year: parseInt(v, 10) }); }}
            min={5} max={10} step={1} suffix={FR ? 'ans' : 'yrs'}
          />
          <HypField
            label={FR ? 'Taux interet' : 'Interest rate'}
            value={(hyp.interest_rate * 100).toFixed(2)}
            onChange={function (v) { setHyp({ ...hyp, interest_rate: v / 100 }); }}
            min={3} max={10} step={0.05} suffix="%"
          />
          <button
            onClick={runUnderwriting}
            disabled={loading}
            style={{
              padding: '6px 14px', background: '#0ea5e9', color: '#fff',
              border: 'none', borderRadius: 6, fontWeight: 600, fontSize: 13,
              cursor: loading ? 'wait' : 'pointer', alignSelf: 'flex-end', height: 32,
            }}
          >
            {loading ? (FR ? 'Calcul…' : 'Computing…') : (FR ? 'Recalculer' : 'Recalculate')}
          </button>
        </div>

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

        {loading && !result && (
          <div style={{ padding: 20, textAlign: 'center', color: '#64748b' }}>
            {FR ? 'Calcul du pro forma…' : 'Computing pro forma…'}
          </div>
        )}

        {result && (
          <>
            {/* KPIs */}
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, marginBottom: 16 }}>
              <KpiCard
                label={TT ? 'NOI Y1' : 'NOI Y1'}
                value={fmtMoney(result.noi_y1)}
                tip="noi"
              />
              <KpiCard
                label="DSCR Y1"
                value={result.dscr_y1 ? result.dscr_y1.toFixed(2) : '—'}
              />
              <KpiCard
                label="IRR"
                value={fmtPct(result.irr)}
                sub={'Annee ' + result.exit_year}
                tip="irr"
              />
              <KpiCard label="TRI 5 ans" value={fmtPct(result.tri_5y)} tip="irr" />
              <KpiCard label="TRI 10 ans" value={fmtPct(result.tri_10y)} tip="irr" />
              <KpiCard
                label="Equity Multiple"
                value={fmtMult(result.equity_multiple)}
                sub={fmtMoney(result.exit_equity) + ' sortie'}
              />
            </div>

            {/* NOI split si mixte */}
            {result.noi_split && result.noi_split.is_mixed && (
              <div style={{
                padding: 12, background: '#fff', border: '1px solid #e5e7eb',
                borderRadius: 8, marginBottom: 16,
              }}>
                <div style={{ fontWeight: 600, fontSize: 13, marginBottom: 8, color: '#1e293b' }}>
                  {FR ? 'NOI separe residentiel / commercial' : 'NOI split residential / commercial'}
                </div>
                <div style={{ display: 'flex', gap: 24, fontSize: 13 }}>
                  <div>
                    <span style={{ color: '#64748b' }}>{FR ? 'NOI residentiel' : 'NOI residential'}</span>
                    <strong style={{ marginLeft: 8 }}>{fmtMoney(result.noi_split.noi_res)}</strong>
                    <span style={{ marginLeft: 6, color: '#94a3b8', fontSize: 11 }}>
                      ({(result.noi_split.share_res * 100).toFixed(0)}%)
                    </span>
                  </div>
                  <div>
                    <span style={{ color: '#64748b' }}>{FR ? 'NOI commercial' : 'NOI commercial'}</span>
                    <strong style={{ marginLeft: 8 }}>{fmtMoney(result.noi_split.noi_comm)}</strong>
                    <span style={{ marginLeft: 6, color: '#94a3b8', fontSize: 11 }}>
                      ({(result.noi_split.share_comm * 100).toFixed(0)}%)
                    </span>
                  </div>
                </div>
              </div>
            )}

            {/* Pro forma annuelle */}
            <div style={{ marginBottom: 18 }}>
              <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 8, color: '#1e293b' }}>
                {TT
                  ? React.createElement(TT, { term: 'pro_forma_normalisee', badge: false }, FR ? 'Pro forma annuelle' : 'Yearly pro forma')
                  : (FR ? 'Pro forma annuelle' : 'Yearly pro forma')
                }
              </div>
              <div style={{ overflowX: 'auto', background: '#fff', borderRadius: 8, border: '1px solid #e5e7eb' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
                  <thead style={{ background: '#f1f5f9' }}>
                    <tr>
                      <th style={{ padding: '8px 6px', textAlign: 'left' }}>Annee</th>
                      <th style={{ padding: '8px 6px', textAlign: 'right' }}>Revenu brut</th>
                      <th style={{ padding: '8px 6px', textAlign: 'right' }}>Vacance</th>
                      <th style={{ padding: '8px 6px', textAlign: 'right' }}>EGI</th>
                      <th style={{ padding: '8px 6px', textAlign: 'right' }}>OpEx</th>
                      <th style={{ padding: '8px 6px', textAlign: 'right' }}>NOI</th>
                      <th style={{ padding: '8px 6px', textAlign: 'right' }}>Service dette</th>
                      <th style={{ padding: '8px 6px', textAlign: 'right' }}>
                        {TT ? React.createElement(TT, { term: 'capex', badge: false }, 'Capex') : 'Capex'}
                      </th>
                      <th style={{ padding: '8px 6px', textAlign: 'right' }}>Cash flow</th>
                      <th style={{ padding: '8px 6px', textAlign: 'right' }}>Valeur</th>
                      <th style={{ padding: '8px 6px', textAlign: 'right' }}>Equity</th>
                    </tr>
                  </thead>
                  <tbody>
                    {result.yearly_proforma.map(function (y) {
                      var isExit = y.year === result.exit_year;
                      return (
                        <tr key={y.year} style={isExit ? { background: '#fffbeb', fontWeight: 600 } : {}}>
                          <td style={{ padding: '6px', borderTop: '1px solid #e5e7eb' }}>{y.year}</td>
                          <td style={{ padding: '6px', textAlign: 'right', borderTop: '1px solid #e5e7eb' }}>{fmtMoney(y.gross_income)}</td>
                          <td style={{ padding: '6px', textAlign: 'right', borderTop: '1px solid #e5e7eb', color: '#dc2626' }}>-{fmtMoney(y.vacancy)}</td>
                          <td style={{ padding: '6px', textAlign: 'right', borderTop: '1px solid #e5e7eb' }}>{fmtMoney(y.egi)}</td>
                          <td style={{ padding: '6px', textAlign: 'right', borderTop: '1px solid #e5e7eb', color: '#dc2626' }}>-{fmtMoney(y.opex)}</td>
                          <td style={{ padding: '6px', textAlign: 'right', borderTop: '1px solid #e5e7eb' }}>{fmtMoney(y.noi)}</td>
                          <td style={{ padding: '6px', textAlign: 'right', borderTop: '1px solid #e5e7eb', color: '#dc2626' }}>-{fmtMoney(y.debt_service)}</td>
                          <td style={{ padding: '6px', textAlign: 'right', borderTop: '1px solid #e5e7eb', color: '#dc2626' }}>-{fmtMoney(y.capex_reserve)}</td>
                          <td style={{ padding: '6px', textAlign: 'right', borderTop: '1px solid #e5e7eb', color: y.cash_flow >= 0 ? '#059669' : '#dc2626' }}>{fmtMoney(y.cash_flow)}</td>
                          <td style={{ padding: '6px', textAlign: 'right', borderTop: '1px solid #e5e7eb' }}>{fmtMoney(y.estimated_value)}</td>
                          <td style={{ padding: '6px', textAlign: 'right', borderTop: '1px solid #e5e7eb' }}>{fmtMoney(y.equity)}</td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>

            {/* Tornado */}
            <div>
              <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 8, color: '#1e293b' }}>
                {TT
                  ? React.createElement(TT, { term: 'tornado_chart', badge: false }, FR ? 'Analyse de sensibilite' : 'Sensitivity analysis')
                  : (FR ? 'Analyse de sensibilite' : 'Sensitivity analysis')
                }
              </div>
              <div style={{ background: '#fff', border: '1px solid #e5e7eb', borderRadius: 8, padding: 14 }}>
                <TornadoChart data={result.sensitivity} />
                <div style={{ fontSize: 11, color: '#64748b', marginTop: 8 }}>
                  {FR
                    ? 'Variations +/- du parametre par rapport a la base. Bleu = parametre augmente, orange = parametre baisse.'
                    : 'Parameter variation around base. Blue = parameter up, orange = parameter down.'}
                </div>
              </div>
            </div>
          </>
        )}
      </div>
    );
  }

  window.CommercialUnderwritingPanel = CommercialUnderwritingPanel;
})();
