// Calculateur DSCR — outil public gratuit, SEO + acquisition
// Route : #/calculateurs/dscr
// Pas de login requis. CTA vers / (Vestora).

const { useState: useDSCRS, useEffect: useDSCRE, useMemo: useDSCRM } = React;

function DscrCalcPage({ lang, onBack }) {
  const FR = lang !== 'en';

  useDSCRE(() => {
    window.scrollTo(0, 0);
    // SEO: title + meta
    const prevTitle = document.title;
    const prevMeta = document.querySelector('meta[name="description"]');
    const prevDesc = prevMeta ? prevMeta.getAttribute('content') : '';
    document.title = FR
      ? 'Calculateur DSCR immobilier Québec — Vestora'
      : 'Real Estate DSCR Calculator Quebec — Vestora';
    if (prevMeta) {
      prevMeta.setAttribute('content', FR
        ? 'Calculez le ratio DSCR de votre plex ou immeuble locatif en quelques secondes. Comprendre le seuil banquier, seuils canadiens, interprétation experte. Gratuit, sans inscription.'
        : 'Calculate the DSCR ratio for your rental property in seconds. Canadian lender thresholds, expert interpretation. Free, no login required.');
    }
    return () => {
      document.title = prevTitle;
      if (prevMeta) prevMeta.setAttribute('content', prevDesc);
    };
  }, [FR]);

  // Mode : simple (NOI + dette) ou détaillé (décomposé)
  const [mode, setMode] = useDSCRS('detailed');

  // Mode simple
  const [noi, setNoi] = useDSCRS('');
  const [debtService, setDebtService] = useDSCRS('');

  // Mode détaillé
  const [price, setPrice] = useDSCRS('');
  const [downPct, setDownPct] = useDSCRS('20');
  const [rate, setRate] = useDSCRS('5.5');
  const [amort, setAmort] = useDSCRS('25');
  const [grossRentMonthly, setGrossRentMonthly] = useDSCRS('');
  const [expensePct, setExpensePct] = useDSCRS('35');

  const fmt = (n) => n == null ? '—' : n.toLocaleString('fr-CA', { maximumFractionDigits: 0 });
  const fmtPct = (n) => n == null ? '—' : n.toFixed(2);

  const result = useDSCRM(() => {
    if (mode === 'simple') {
      const n = parseFloat(noi);
      const d = parseFloat(debtService);
      if (!n || !d || d === 0) return null;
      return { dscr: n / d, noi: n, debtService: d };
    }

    // Détaillé
    const p = parseFloat(price);
    const dpPct = parseFloat(downPct) / 100;
    const r = parseFloat(rate) / 100;
    const am = parseFloat(amort);
    const rent = parseFloat(grossRentMonthly);
    const expPct = parseFloat(expensePct) / 100;

    if (!p || !rent || !r || !am) return null;

    const dp = p * dpPct;
    const principal = p - dp;

    // Paiement mensuel hypothécaire canadien (composition semi-annuelle)
    let monthlyPayment;
    if (window.underwriting) {
      monthlyPayment = window.underwriting.mortgagePayment(principal, r, am);
    } else {
      // Fallback: composition semi-annuelle canadienne
      const mr = Math.pow(1 + r / 2, 1 / 6) - 1;
      const n = am * 12;
      monthlyPayment = mr === 0 ? principal / n : (principal * (mr * Math.pow(1 + mr, n))) / (Math.pow(1 + mr, n) - 1);
    }

    const annualDebt = monthlyPayment * 12;
    const grossRentAnnual = rent * 12;
    const noi_calc = grossRentAnnual * (1 - expPct);
    const dscr = annualDebt > 0 ? noi_calc / annualDebt : null;

    return {
      dscr,
      noi: noi_calc,
      debtService: annualDebt,
      grossRentAnnual,
      monthlyPayment,
      principal,
      downPayment: dp,
    };
  }, [mode, noi, debtService, price, downPct, rate, amort, grossRentMonthly, expensePct]);

  const dscrValue = result ? result.dscr : null;

  // Couleur et interprétation
  const gaugeColor = dscrValue == null ? '#ccc'
    : dscrValue >= 1.2 ? '#22c55e'
    : dscrValue >= 1.0 ? '#f59e0b'
    : '#ef4444';

  const gaugeLabel = dscrValue == null ? (FR ? 'Entrez vos données' : 'Enter your data')
    : dscrValue >= 1.25 ? (FR ? 'Excellent — prêt approuvable' : 'Excellent — approvable loan')
    : dscrValue >= 1.2  ? (FR ? 'Bon — acceptable par la plupart des prêteurs' : 'Good — acceptable by most lenders')
    : dscrValue >= 1.0  ? (FR ? 'Limite — possible avec certains prêteurs' : 'Borderline — possible with some lenders')
    : (FR ? 'Insuffisant — refusé par la plupart des prêteurs' : 'Insufficient — rejected by most lenders');

  // Jauge arc SVG
  const gaugeAngle = dscrValue == null ? 0 : Math.min(180, Math.max(0, (Math.min(dscrValue, 2) / 2) * 180));
  const r_ = 70, cx = 100, cy = 90;
  const toRad = (deg) => (deg - 180) * Math.PI / 180;
  const arcX = cx + r_ * Math.cos(toRad(gaugeAngle));
  const arcY = cy + r_ * Math.sin(toRad(gaugeAngle));

  return (
    <div className="legal-page" style={{ maxWidth: 860 }}>
      {/* Header */}
      <div className="legal-header">
        <button className="btn btn-ghost" onClick={onBack}>
          {FR ? '← Retour' : '← Back'}
        </button>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
          <span style={{ fontSize: 13, color: '#666', fontFamily: 'var(--font-body)' }}>
            {FR ? 'Outil gratuit' : 'Free tool'}
          </span>
          <a
            href="#/"
            style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              background: '#1e6f5c', color: '#fff', borderRadius: 8,
              padding: '7px 14px', fontSize: 13, fontWeight: 600,
              textDecoration: 'none', fontFamily: 'var(--font-body)',
            }}
          >
            {FR ? 'Analyser un vrai plex →' : 'Analyze a real property →'}
          </a>
        </div>
      </div>

      <div className="legal-content" style={{ padding: '28px 32px' }}>
        <h1 style={{ fontFamily: 'var(--font-display, Fraunces, serif)', fontSize: 28, marginBottom: 6 }}>
          {FR ? 'Calculateur DSCR' : 'DSCR Calculator'}
        </h1>
        <p style={{ color: '#666', margin: '0 0 24px', fontSize: 14 }}>
          {FR
            ? 'Calculez le Debt Service Coverage Ratio de votre investissement locatif en temps réel.'
            : 'Calculate the Debt Service Coverage Ratio of your rental investment in real time.'}
        </p>

        {/* Mode toggle */}
        <div style={{ display: 'flex', gap: 8, marginBottom: 24 }}>
          <button
            onClick={() => setMode('detailed')}
            style={{
              padding: '7px 16px', borderRadius: 8, border: '1px solid',
              borderColor: mode === 'detailed' ? '#1e6f5c' : '#ddd',
              background: mode === 'detailed' ? '#1e6f5c' : '#fff',
              color: mode === 'detailed' ? '#fff' : '#444',
              fontSize: 13, fontWeight: 500, cursor: 'pointer', fontFamily: 'var(--font-body)',
            }}
          >
            {FR ? 'Mode détaillé' : 'Detailed mode'}
          </button>
          <button
            onClick={() => setMode('simple')}
            style={{
              padding: '7px 16px', borderRadius: 8, border: '1px solid',
              borderColor: mode === 'simple' ? '#1e6f5c' : '#ddd',
              background: mode === 'simple' ? '#1e6f5c' : '#fff',
              color: mode === 'simple' ? '#fff' : '#444',
              fontSize: 13, fontWeight: 500, cursor: 'pointer', fontFamily: 'var(--font-body)',
            }}
          >
            {FR ? 'NOI + dette directs' : 'Direct NOI + debt'}
          </button>
        </div>

        {/* Layout : form + gauge */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 32, alignItems: 'start' }}>
          {/* Formulaire */}
          <div>
            {mode === 'simple' ? (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                <DscrField
                  label={FR ? 'NOI annuel ($)' : 'Annual NOI ($)'}
                  hint={FR ? "Revenus bruts − dépenses d'exploitation (sans dette)" : 'Gross income − operating expenses (excl. debt)'}
                  value={noi} onChange={setNoi} placeholder="ex: 48 000"
                />
                <DscrField
                  label={FR ? 'Service de la dette annuel ($)' : 'Annual debt service ($)'}
                  hint={FR ? 'Total des paiements hypothécaires annuels (capital + intérêts)' : 'Total annual mortgage payments (principal + interest)'}
                  value={debtService} onChange={setDebtService} placeholder="ex: 38 400"
                />
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                  <DscrField
                    label={FR ? "Prix d'achat ($)" : 'Purchase price ($)'}
                    value={price} onChange={setPrice} placeholder="ex: 650 000"
                  />
                  <DscrField
                    label={FR ? 'Mise de fonds (%)' : 'Down payment (%)'}
                    value={downPct} onChange={setDownPct} placeholder="20"
                    min={5} max={100}
                  />
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                  <DscrField
                    label={FR ? 'Taux hypothécaire (%)' : 'Mortgage rate (%)'}
                    value={rate} onChange={setRate} placeholder="5.5"
                    min={0.1} max={25} step={0.1}
                  />
                  <DscrField
                    label={FR ? 'Amortissement (ans)' : 'Amortization (years)'}
                    value={amort} onChange={setAmort} placeholder="25"
                    min={5} max={30}
                  />
                </div>
                <DscrField
                  label={FR ? 'Loyer brut mensuel total ($)' : 'Total gross monthly rent ($)'}
                  hint={FR ? 'Somme de tous les loyers perçus par mois' : 'Sum of all rents collected per month'}
                  value={grossRentMonthly} onChange={setGrossRentMonthly} placeholder="ex: 4 200"
                />
                <DscrField
                  label={FR ? 'Ratio de dépenses (%)' : 'Expense ratio (%)'}
                  hint={FR ? 'Taxes, assurances, entretien, gestion — typiquement 30-45%' : 'Taxes, insurance, maintenance, management — typically 30-45%'}
                  value={expensePct} onChange={setExpensePct} placeholder="35"
                  min={0} max={80} step={1}
                />
              </div>
            )}

            {/* Résultats numériques */}
            {result && (
              <div style={{
                marginTop: 20, padding: '16px 18px', borderRadius: 10,
                background: '#f7f9f8', border: '1px solid #e0ebe6',
              }}>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                  <DscrStat label="NOI annuel" value={'$' + fmt(result.noi)} />
                  <DscrStat label={FR ? 'Service de la dette / an' : 'Annual debt service'} value={'$' + fmt(result.debtService)} />
                  {mode === 'detailed' && result.monthlyPayment && (
                    <>
                      <DscrStat label={FR ? 'Paiement mensuel' : 'Monthly payment'} value={'$' + fmt(result.monthlyPayment)} />
                      <DscrStat label={FR ? 'Mise de fonds' : 'Down payment'} value={'$' + fmt(result.downPayment)} />
                    </>
                  )}
                </div>
              </div>
            )}
          </div>

          {/* Jauge DSCR */}
          <div style={{ minWidth: 200, textAlign: 'center', paddingTop: 8 }}>
            <svg viewBox="0 0 200 110" width="200" height="110" style={{ display: 'block', margin: '0 auto' }}>
              {/* Arc fond */}
              <path d="M30 90 A70 70 0 0 1 170 90" fill="none" stroke="#f0f0ee" strokeWidth="14" strokeLinecap="round" />
              {/* Arc couleur */}
              {dscrValue != null && (
                <path
                  d={`M30 90 A70 70 0 ${gaugeAngle > 90 ? 1 : 0} 1 ${arcX} ${arcY}`}
                  fill="none" stroke={gaugeColor} strokeWidth="14" strokeLinecap="round"
                />
              )}
              {/* Seuils */}
              <text x="28" y="106" fontSize="9" fill="#bbb" textAnchor="middle">0</text>
              <text x="100" y="20" fontSize="9" fill="#bbb" textAnchor="middle">1.2</text>
              <text x="172" y="106" fontSize="9" fill="#bbb" textAnchor="middle">2+</text>
              {/* Valeur centrale */}
              <text x="100" y="78" textAnchor="middle" fontSize="22" fontWeight="700"
                fill={dscrValue == null ? '#ccc' : gaugeColor}
                fontFamily="var(--font-body, Inter, sans-serif)">
                {dscrValue != null ? fmtPct(dscrValue) : '—'}
              </text>
              <text x="100" y="94" textAnchor="middle" fontSize="10" fill="#888"
                fontFamily="var(--font-body, Inter, sans-serif)">DSCR</text>
            </svg>
            <div style={{
              marginTop: 8, padding: '8px 12px', borderRadius: 8,
              background: dscrValue == null ? '#f5f5f3' : (dscrValue >= 1.2 ? '#f0fdf4' : dscrValue >= 1.0 ? '#fffbeb' : '#fef2f2'),
              border: `1.5px solid ${gaugeColor}`,
              fontSize: 12, fontWeight: 600, color: gaugeColor,
              fontFamily: 'var(--font-body)',
              maxWidth: 200,
            }}>
              {gaugeLabel}
            </div>
          </div>
        </div>

        {/* CTA */}
        <div style={{
          marginTop: 28, padding: '18px 20px', borderRadius: 12,
          background: 'linear-gradient(135deg, #1e6f5c, #2c3e2d)',
          color: '#fff', display: 'flex', alignItems: 'center',
          justifyContent: 'space-between', flexWrap: 'wrap', gap: 12,
        }}>
          <div>
            <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 3 }}>
              {FR ? 'Prêt à analyser un vrai plex ?' : 'Ready to analyze a real property?'}
            </div>
            <div style={{ fontSize: 13, opacity: 0.85 }}>
              {FR
                ? 'Vestora calcule DSCR, cap rate, cash-flow et score sur 100 pour chaque annonce au Québec.'
                : 'Vestora calculates DSCR, cap rate, cash-flow and score out of 100 for every Quebec listing.'}
            </div>
          </div>
          <a href="#/" style={{
            background: '#fff', color: '#1e6f5c', borderRadius: 8,
            padding: '9px 18px', fontWeight: 700, fontSize: 14,
            textDecoration: 'none', whiteSpace: 'nowrap',
          }}>
            {FR ? 'Analyser avec Vestora →' : 'Analyze with Vestora →'}
          </a>
        </div>
      </div>

      {/* Bloc SEO / éducatif */}
      <div className="legal-content" style={{ marginTop: 20, padding: '28px 32px' }}>
        <h2 style={{ fontSize: 20, marginBottom: 12, fontFamily: 'var(--font-display, Fraunces, serif)' }}>
          {FR ? "Qu'est-ce que le DSCR ?" : 'What is the DSCR?'}
        </h2>
        <p>
          {FR
            ? "Le Debt Service Coverage Ratio (DSCR) mesure la capacité d'un immeuble à rembourser sa dette grâce à ses revenus locatifs. Il se calcule ainsi :"
            : 'The Debt Service Coverage Ratio (DSCR) measures a property\'s ability to service its debt from rental income. It is calculated as:'}
        </p>
        <div style={{
          background: '#f7f9f8', border: '1px solid #d0e8e0', borderRadius: 8,
          padding: '12px 16px', fontFamily: 'var(--font-mono, JetBrains Mono, monospace)',
          fontSize: 14, textAlign: 'center', margin: '12px 0',
        }}>
          DSCR = NOI annuel ÷ Service de la dette annuel
        </div>
        <p>
          {FR
            ? 'Un DSCR de 1.0 signifie que l'immeuble génère exactement assez de revenus pour couvrir ses paiements hypothécaires. En dessous de 1.0, le propriétaire doit combler le déficit de sa poche.'
            : 'A DSCR of 1.0 means the property generates exactly enough income to cover mortgage payments. Below 1.0, the owner must cover the shortfall out of pocket.'}
        </p>

        <h2 style={{ fontSize: 18, marginTop: 24, marginBottom: 10, fontFamily: 'var(--font-display, Fraunces, serif)' }}>
          {FR ? 'Seuils des prêteurs canadiens' : 'Canadian lender thresholds'}
        </h2>
        <table className="legal-table">
          <thead>
            <tr>
              <th>DSCR</th>
              <th>{FR ? 'Interprétation' : 'Interpretation'}</th>
              <th>{FR ? 'Position des prêteurs' : 'Lender position'}</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td style={{ fontWeight: 700, color: '#22c55e' }}>&ge; 1.25</td>
              <td>{FR ? 'Excellent' : 'Excellent'}</td>
              <td>{FR ? 'Financement facile, meilleures conditions' : 'Easy financing, best terms'}</td>
            </tr>
            <tr>
              <td style={{ fontWeight: 700, color: '#4ade80' }}>1.20 – 1.25</td>
              <td>{FR ? 'Bon' : 'Good'}</td>
              <td>{FR ? 'Acceptable par la grande majorité des prêteurs' : 'Acceptable by the vast majority of lenders'}</td>
            </tr>
            <tr>
              <td style={{ fontWeight: 700, color: '#f59e0b' }}>1.00 – 1.20</td>
              <td>{FR ? 'Limite' : 'Borderline'}</td>
              <td>{FR ? 'Certains prêteurs acceptent, souvent avec conditions' : 'Some lenders accept, often with conditions'}</td>
            </tr>
            <tr>
              <td style={{ fontWeight: 700, color: '#ef4444' }}>&lt; 1.00</td>
              <td>{FR ? 'Insuffisant' : 'Insufficient'}</td>
              <td>{FR ? 'Refusé par la plupart des prêteurs institutionnels' : 'Rejected by most institutional lenders'}</td>
            </tr>
          </tbody>
        </table>

        <h2 style={{ fontSize: 18, marginTop: 24, marginBottom: 10, fontFamily: 'var(--font-display, Fraunces, serif)' }}>
          {FR ? 'Comment améliorer son DSCR ?' : 'How to improve your DSCR?'}
        </h2>
        <ul>
          <li>{FR ? 'Augmenter les loyers : chaque dollar de NOI supplémentaire améliore directement le ratio.' : 'Increase rents: every additional dollar of NOI directly improves the ratio.'}</li>
          <li>{FR ? 'Réduire les dépenses : optimiser taxes, assurances et gestion diminue le dénominateur.' : 'Reduce expenses: optimize taxes, insurance and management to lower operating costs.'}</li>
          <li>{FR ? "Allonger l'amortissement : passer de 20 à 25 ans réduit le paiement mensuel." : 'Extend amortization: going from 20 to 25 years reduces the monthly payment.'}</li>
          <li>{FR ? 'Augmenter la mise de fonds : un emprunt plus petit = service de la dette plus bas.' : 'Increase down payment: smaller loan = lower debt service.'}</li>
          <li>{FR ? "Cibler des marchés à fort rendement locatif vs prix d'achat." : 'Target markets with high rent yield vs purchase price.'}</li>
        </ul>

        <p style={{ marginTop: 20, padding: '12px 16px', background: '#f7f9f8', borderRadius: 8, fontSize: 13, color: '#555' }}>
          {FR
            ? 'Note : ce calculateur utilise la composition semi-annuelle canadienne (Loi sur les intérêts, L.R.C. 1985) pour les paiements hypothécaires. Les résultats sont donnés à titre indicatif; consultez un courtier hypothécaire pour une analyse personnalisée.'
            : 'Note: this calculator uses Canadian semi-annual compounding (Interest Act, R.S.C. 1985) for mortgage payments. Results are indicative; consult a mortgage broker for a personalized analysis.'}
        </p>
      </div>

      {/* Footer minimal */}
      <div style={{ textAlign: 'center', padding: '20px 16px', fontSize: 12, color: '#999' }}>
        © {new Date().getFullYear()} Vestora
        {' · '}
        <a href="#/confidentialite" style={{ color: '#999' }}>{FR ? 'Confidentialité' : 'Privacy'}</a>
        {' · '}
        <a href="#/calculateurs/cca-cat1" style={{ color: '#1e6f5c', fontWeight: 600 }}>
          {FR ? 'Calculateur CCA cat. 1 →' : 'CCA cat. 1 Calculator →'}
        </a>
      </div>
    </div>
  );
}

function DscrField({ label, hint, value, onChange, placeholder, min, max, step }) {
  return (
    <div>
      <label style={{ display: 'block', fontSize: 13, fontWeight: 600, marginBottom: 4, color: '#2a2a2a', fontFamily: 'var(--font-body)' }}>
        {label}
      </label>
      {hint && <div style={{ fontSize: 11, color: '#888', marginBottom: 5 }}>{hint}</div>}
      <input
        type="number"
        min={min}
        max={max}
        step={step || 1}
        value={value}
        onChange={e => onChange(e.target.value)}
        placeholder={placeholder}
        style={{
          width: '100%', padding: '8px 10px', borderRadius: 7,
          border: '1.5px solid #ddd', fontSize: 14,
          fontFamily: 'var(--font-body)', background: '#fff',
          boxSizing: 'border-box',
          outline: 'none',
        }}
      />
    </div>
  );
}

function DscrStat({ label, value }) {
  return (
    <div>
      <div style={{ fontSize: 11, color: '#888', marginBottom: 2 }}>{label}</div>
      <div style={{ fontSize: 15, fontWeight: 700, color: '#1a1a1a', fontFamily: 'var(--font-body)' }}>{value}</div>
    </div>
  );
}

window.DscrCalcPage = DscrCalcPage;
