// AnalyzePage — Étape 3 : analyse complète, 3 scénarios A/B/C
// Accessible via hash routing #/analyze/:id

const {
  useState: useAP,
  useMemo: useMAP,
  useEffect: useEAP,
  useCallback: useCBAP,
} = React;

// ── Calculs financiers détaillés ─────────────────────────────────────────────

function droitsMutation(price) {
  // Barème Québec 2024
  let tax = 0;
  const brackets = [
    [51700, 0.005],
    [258600 - 51700, 0.01],
    [517100 - 258600, 0.015],
    [1034200 - 517100, 0.02],
    [2000000 - 1034200, 0.025],
  ];
  let rem = price;
  for (const [limit, rate] of brackets) {
    const chunk = Math.min(rem, limit);
    tax += chunk * rate;
    rem -= chunk;
    if (rem <= 0) break;
  }
  if (rem > 0) tax += rem * 0.03;
  return Math.round(tax);
}

function schhlPremium(price, downPct) {
  if (downPct >= 0.20) return 0;
  const ltv = 1 - downPct;
  let rate = ltv <= 0.65 ? 0.006 : ltv <= 0.75 ? 0.017 : ltv <= 0.80 ? 0.024 : ltv <= 0.85 ? 0.028 : ltv <= 0.90 ? 0.031 : 0.04;
  return Math.round(price * ltv * rate);
}

function monthlyPaymentCalc(loan, rate, years) {
  const r = rate / 12;
  const n = years * 12;
  if (r <= 0) return loan / n;
  return loan * (r * Math.pow(1 + r, n)) / (Math.pow(1 + r, n) - 1);
}

function computeScenario(s) {
  const price = s.price;
  const downAmt = price * s.downPaymentPct;
  const droits = droitsMutation(price);
  const notaire = 1800;
  const fraisPreteur = s.isSCHL ? 900 : 500;
  const evaluateur = s.evaluateur ?? 500;
  const inspecteur = s.inspecteur ?? 600;
  const renos = s.renosAchat ?? 0;
  const totalFrais = droits + notaire + fraisPreteur + evaluateur + inspecteur + renos;
  const schhl = s.isSCHL ? schhlPremium(price, s.downPaymentPct) : 0;
  const argent = downAmt + totalFrais;
  const loan = price - downAmt + schhl;

  const grossIncome = s.grossIncome;
  const addRevenue = s.addRevenue ?? 0;
  const grossEffective = (grossIncome + addRevenue) * (1 - s.vacancyPct);

  // Dépenses
  const taxesMun = s.taxesMun ?? Math.round(price * 0.012);
  const taxesScol = s.taxesScol ?? Math.round(price * 0.002);
  const assurance = s.assurance ?? Math.round(price * 0.004);
  const electricite = s.electricite ?? 0;
  const energie = s.energie ?? 0;
  const deneigement = s.deneigement ?? 0;
  const gestion = s.gestionOverride != null
    ? s.gestionOverride
    : Math.round(grossEffective * s.managementPct);
  const yearBuilt = s.yearBuilt ?? 1975;
  const age = Math.max(0, new Date().getFullYear() - yearBuilt);
  const capexRate = age < 10 ? 0.005 : age < 25 ? 0.01 : 0.015;
  const capex = s.capexOverride != null
    ? s.capexOverride
    : Math.round(price * capexRate);

  const totalOpex = taxesMun + taxesScol + assurance + electricite + energie + deneigement + gestion;
  const totalCharges = totalOpex + capex;

  const noi = grossEffective - totalOpex;
  const noiAjuste = grossEffective - totalCharges;

  // Financement
  const mp = monthlyPaymentCalc(loan, s.mortgageRate, s.amortizationYears);
  const annualDebt = mp * 12;
  const dscr = noi > 0 && annualDebt > 0 ? noi / annualDebt : 0;
  const dscrMin = s.isSCHL ? 1.25 : 1.20;
  const cashflowBrut = noi - annualDebt;
  const cashflowAjuste = noiAjuste - annualDebt;
  const cocBrut = argent > 0 ? cashflowBrut / argent : 0;
  const cocAjuste = argent > 0 ? cashflowAjuste / argent : 0;

  const capRateBrut = price > 0 ? noi / price : 0;
  const capRateAjuste = price > 0 ? noiAjuste / price : 0;

  const tga = s.tga ?? 0.055;
  const valMarchande = tga > 0 ? noi / tga : price;
  const valEconomique = dscrMin > 0 ? noi / (dscrMin * annualDebt / loan * loan) : price;
  const prixRetenu = Math.min(price, valMarchande);

  const units = s.units ?? 1;
  const revParPorte = units > 0 ? grossEffective / units / 12 : 0;
  const cfParPorte = units > 0 ? cashflowAjuste / units / 12 : 0;
  const grm = grossIncome > 0 ? price / grossIncome : 0;
  const mrn = noiAjuste > 0 ? price / noiAjuste : 0;
  const cashBreakeven = grossEffective > 0 ? (totalCharges + annualDebt) / grossEffective : 0;

  // Capitalisation 1ère année
  const r = s.mortgageRate / 12;
  const n = s.amortizationYears * 12;
  const cap1 = Array.from({ length: 12 }).reduce(({ bal, tot }, _, i) => {
    const interest = bal * r;
    const principal = mp - interest;
    return { bal: bal - principal, tot: tot + principal };
  }, { bal: loan, tot: 0 }).tot;

  const roiTotal = argent > 0
    ? (cashflowAjuste + cap1 + price * s.appreciationRate) / argent
    : 0;

  return {
    price, downAmt, droits, notaire, fraisPreteur, evaluateur, inspecteur, renos, totalFrais, schhl, argent,
    grossIncome, addRevenue, grossEffective,
    taxesMun, taxesScol, assurance, electricite, energie, deneigement, gestion, capex,
    totalOpex, totalCharges, noi, noiAjuste,
    loan, mp, annualDebt, dscr, dscrMin, cashflowBrut, cashflowAjuste, cocBrut, cocAjuste,
    capRateBrut, capRateAjuste, valMarchande, valEconomique, prixRetenu,
    units, revParPorte, cfParPorte, grm, mrn, cashBreakeven, roiTotal, capexRate, cap1,
  };
}

function computeProjection(s, c, years = 10) {
  const rows = [];
  let loan = c.loan;
  let loyer = c.grossEffective;
  let opex = c.totalOpex;
  let valeur = s.price;
  const mp = c.mp;
  const r = s.mortgageRate / 12;

  for (let yr = 1; yr <= years; yr++) {
    loyer *= 1 + (s.rentGrowthRate ?? 0.03);
    opex  *= 1.02;
    valeur *= 1 + (s.appreciationRate ?? 0.03);
    const rno = loyer - opex;
    const annualDebt = mp * 12;
    const cf = rno - annualDebt;

    // Capital remboursé cette année
    let capRembYear = 0;
    let bal = loan;
    for (let m = 0; m < 12; m++) {
      const interest = bal * r;
      const principal = mp - interest;
      capRembYear += principal;
      bal -= principal;
    }
    loan = bal;
    const equite = valeur - loan;

    rows.push({
      yr, loyer: Math.round(loyer), opex: Math.round(opex), rno: Math.round(rno),
      annualDebt: Math.round(annualDebt), cf: Math.round(cf),
      capRemb: Math.round(capRembYear), valeur: Math.round(valeur), equite: Math.round(equite)
    });
  }
  return rows;
}

function computeTornado(s, c) {
  const base = c.cashflowAjuste;
  const vars = [
    { key: 'taux', label: 'Taux hypothécaire', delta: () => {
      const up = computeScenario({ ...s, mortgageRate: s.mortgageRate * 1.1 }).cashflowAjuste;
      const dn = computeScenario({ ...s, mortgageRate: s.mortgageRate * 0.9 }).cashflowAjuste;
      return { up: up - base, dn: dn - base };
    }},
    { key: 'vacance', label: 'Vacance', delta: () => {
      const up = computeScenario({ ...s, vacancyPct: s.vacancyPct * 1.1 }).cashflowAjuste;
      const dn = computeScenario({ ...s, vacancyPct: s.vacancyPct * 0.9 }).cashflowAjuste;
      return { up: up - base, dn: dn - base };
    }},
    { key: 'loyers', label: 'Revenus bruts', delta: () => {
      const up = computeScenario({ ...s, grossIncome: s.grossIncome * 1.1 }).cashflowAjuste;
      const dn = computeScenario({ ...s, grossIncome: s.grossIncome * 0.9 }).cashflowAjuste;
      return { up: up - base, dn: dn - base };
    }},
    { key: 'gestion', label: 'Frais de gestion', delta: () => {
      const up = computeScenario({ ...s, managementPct: s.managementPct * 1.1 }).cashflowAjuste;
      const dn = computeScenario({ ...s, managementPct: s.managementPct * 0.9 }).cashflowAjuste;
      return { up: up - base, dn: dn - base };
    }},
    { key: 'capex', label: 'Capex', delta: () => {
      const upC = { ...s, capexOverride: (s.capexOverride ?? Math.round(s.price * (s.capexRate ?? 0.01))) * 1.1 };
      const dnC = { ...s, capexOverride: (s.capexOverride ?? Math.round(s.price * (s.capexRate ?? 0.01))) * 0.9 };
      const up = computeScenario(upC).cashflowAjuste;
      const dn = computeScenario(dnC).cashflowAjuste;
      return { up: up - base, dn: dn - base };
    }},
  ];
  return vars.map(v => ({ ...v, ...v.delta() }))
    .sort((a, b) => (Math.abs(b.up) + Math.abs(b.dn)) - (Math.abs(a.up) + Math.abs(a.dn)));
}

function verdict(c) {
  const score = (
    (c.capRateAjuste >= 0.06 ? 3 : c.capRateAjuste >= 0.04 ? 1 : 0) +
    (c.dscr >= 1.25 ? 3 : c.dscr >= 1.10 ? 1 : 0) +
    (c.cashflowAjuste > 0 ? 2 : 0) +
    (c.cocAjuste >= 0.06 ? 2 : 0)
  );
  if (score >= 8) return 'excellent';
  if (score >= 5) return 'good';
  if (score >= 2) return 'fair';
  return 'avoid';
}

function strengths(c, FR) {
  const pts = [];
  if (c.capRateAjuste >= 0.06) pts.push(FR ? `Cap rate ajusté solide (${(c.capRateAjuste*100).toFixed(1)} %)` : `Strong adj. cap rate (${(c.capRateAjuste*100).toFixed(1)}%)`);
  if (c.dscr >= 1.25) pts.push(FR ? `DSCR confortable (${c.dscr.toFixed(2)})` : `Comfortable DSCR (${c.dscr.toFixed(2)})`);
  if (c.cashflowAjuste > 0) pts.push(FR ? `Cashflow positif (${window.fmt.moneyShort(c.cashflowAjuste)}/an)` : `Positive cash flow (${window.fmt.moneyShort(c.cashflowAjuste)}/yr)`);
  if (c.cocAjuste >= 0.06) pts.push(FR ? `Cash-on-cash attractif (${(c.cocAjuste*100).toFixed(1)} %)` : `Attractive CoC (${(c.cocAjuste*100).toFixed(1)}%)`);
  if (c.cashBreakeven <= 0.80) pts.push(FR ? 'Point d\'équilibre confortable (≤ 80 %)' : 'Comfortable break-even (≤ 80%)');
  return pts.slice(0, 3);
}

function weaknesses(c, FR) {
  const pts = [];
  if (c.capRateAjuste < 0.04) pts.push(FR ? `Cap rate faible (${(c.capRateAjuste*100).toFixed(1)} %)` : `Low cap rate (${(c.capRateAjuste*100).toFixed(1)}%)`);
  if (c.dscr < 1.10) pts.push(FR ? `DSCR sous le seuil bancaire (${c.dscr.toFixed(2)})` : `DSCR below bank threshold (${c.dscr.toFixed(2)})`);
  if (c.cashflowAjuste < 0) pts.push(FR ? `Cashflow négatif (${window.fmt.moneyShort(c.cashflowAjuste)}/an)` : `Negative cash flow (${window.fmt.moneyShort(c.cashflowAjuste)}/yr)`);
  if (c.cashBreakeven > 0.95) pts.push(FR ? `Point d\'équilibre critique (${(c.cashBreakeven*100).toFixed(0)} %)` : `Critical break-even (${(c.cashBreakeven*100).toFixed(0)}%)`);
  if (c.grm > 18) pts.push(FR ? `GRM élevé (${c.grm.toFixed(1)}×)` : `High GRM (${c.grm.toFixed(1)}×)`);
  return pts.slice(0, 3);
}

// ── Badge coloré ─────────────────────────────────────────────────────────────
function Badge({ value, thresholds, format, label }) {
  // thresholds: { green: fn(v), yellow: fn(v) }
  const cls = thresholds.green(value) ? 'badge-green'
    : thresholds.yellow(value) ? 'badge-yellow'
    : 'badge-red';
  return (
    <span className={`ap-badge ${cls}`}>
      {format ? format(value) : value}
    </span>
  );
}

function kpiTone(key, value) {
  if (key === 'capRate') return value >= 0.06 ? 'pos' : value < 0.04 ? 'neg' : '';
  if (key === 'dscr') return value >= 1.25 ? 'pos' : value < 1.10 ? 'neg' : '';
  if (key === 'cashflow') return value > 0 ? 'pos' : value < 0 ? 'neg' : '';
  if (key === 'coc') return value >= 0.06 ? 'pos' : value < 0 ? 'neg' : '';
  if (key === 'breakeven') return value <= 0.80 ? 'pos' : value > 0.95 ? 'neg' : '';
  return '';
}

// ── Input numérique inline ───────────────────────────────────────────────────
function NumInput({ value, onChange, min, max, step, fmt, prefix, suffix, className }) {
  const [editing, setEditing] = useAP(false);
  const [raw, setRaw] = useAP('');

  const startEdit = () => { setEditing(true); setRaw(String(value)); };
  const commit = () => {
    setEditing(false);
    const v = parseFloat(raw.replace(',', '.'));
    if (!isNaN(v)) {
      if (min != null && v < min) onChange(min);
      else if (max != null && v > max) onChange(max);
      else onChange(v);
    }
  };

  if (editing) {
    return (
      <input
        className={`ap-inline-input ${className || ''}`}
        type="number" value={raw} min={min} max={max} step={step}
        onChange={e => setRaw(e.target.value)}
        onBlur={commit}
        onKeyDown={e => { if (e.key === 'Enter') commit(); if (e.key === 'Escape') setEditing(false); }}
        autoFocus
      />
    );
  }

  return (
    <span className={`ap-editable ${className || ''}`} onClick={startEdit} title="Cliquer pour modifier">
      {prefix && <span className="ap-prefix">{prefix}</span>}
      {fmt ? fmt(value) : value}
      {suffix && <span className="ap-suffix"> {suffix}</span>}
      <span className="ap-edit-icon">✎</span>
    </span>
  );
}

// ── Section 1 : Coût d'acquisition ──────────────────────────────────────────
function Section1({ scenarios, calcs, setScenario, FR }) {
  const f = window.fmt;
  const rows = [
    { key: 'price', label: FR ? 'Prix offert' : 'Offered price', editable: true,
      val: s => s.price, set: (idx, v) => setScenario(idx, 'price', v),
      fmt: v => f.money(v), min: 10000, max: 5000000, step: 1000 },
    { key: 'droits', label: FR ? 'Droits de mutation' : 'Transfer tax', val: (s, c) => c.droits, fmt: v => f.money(v) },
    { key: 'notaire', label: FR ? 'Notaire' : 'Notary', val: (s, c) => c.notaire, fmt: v => f.money(v) },
    { key: 'fraisPreteur', label: FR ? 'Frais prêteur' : 'Lender fees', val: (s, c) => c.fraisPreteur, fmt: v => f.money(v) },
    { key: 'evaluateur', label: FR ? 'Évaluateur' : 'Appraiser', editable: true,
      val: s => s.evaluateur ?? 500, set: (idx, v) => setScenario(idx, 'evaluateur', v),
      fmt: v => f.money(v), min: 0, max: 5000, step: 50 },
    { key: 'inspecteur', label: FR ? 'Inspecteur' : 'Inspector', editable: true,
      val: s => s.inspecteur ?? 600, set: (idx, v) => setScenario(idx, 'inspecteur', v),
      fmt: v => f.money(v), min: 0, max: 5000, step: 50 },
    { key: 'renos', label: FR ? 'Rénos à l\'achat' : 'Initial renos', editable: true,
      val: s => s.renosAchat ?? 0, set: (idx, v) => setScenario(idx, 'renosAchat', v),
      fmt: v => f.money(v), min: 0, max: 500000, step: 1000 },
    { key: 'totalFrais', label: FR ? 'Total frais d\'acquisition' : 'Total acquisition costs',
      val: (s, c) => c.totalFrais, fmt: v => f.money(v), bold: true },
    { key: 'downAmt', label: FR ? 'Mise de fonds' : 'Down payment', val: (s, c) => c.downAmt, fmt: v => f.money(v) },
    { key: 'schhl', label: 'Prime SCHL', val: (s, c) => c.schhl, fmt: v => f.money(v),
      hide: (s, c) => c.schhl === 0 },
    { key: 'argent', label: FR ? 'Argent requis au départ' : 'Total cash required',
      val: (s, c) => c.argent, fmt: v => f.money(v), bold: true, highlight: true },
  ];

  return (
    <section className="ap-section" id="ap-section-1">
      <h3 className="section-title">{FR ? '1. Coût d\'acquisition' : '1. Acquisition costs'}</h3>
      <div className="ap-table-wrap">
        <table className="ap-table">
          <thead>
            <tr>
              <th className="ap-th-label">{FR ? 'Poste' : 'Item'}</th>
              {scenarios.map((s, i) => <th key={i} className={`ap-th-col ap-col-${i}`}>{s.label}</th>)}
            </tr>
          </thead>
          <tbody>
            {rows.map(row => {
              const anyVisible = scenarios.some((s, i) => !(row.hide && row.hide(s, calcs[i])));
              if (!anyVisible) return null;
              return (
                <tr key={row.key} className={`ap-row ${row.bold ? 'ap-row-bold' : ''} ${row.highlight ? 'ap-row-highlight' : ''}`}>
                  <td className="ap-td-label">{row.label}</td>
                  {scenarios.map((s, i) => {
                    const c = calcs[i];
                    if (row.hide && row.hide(s, c)) return <td key={i} className={`ap-td ap-col-${i}`}>—</td>;
                    const rawVal = row.val(s, c);
                    return (
                      <td key={i} className={`ap-td ap-col-${i}`}>
                        {row.editable
                          ? <NumInput value={rawVal} onChange={v => row.set(i, v)}
                              min={row.min} max={row.max} step={row.step} fmt={row.fmt}/>
                          : row.fmt(rawVal)
                        }
                      </td>
                    );
                  })}
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </section>
  );
}

// ── Section 2 : Revenus ──────────────────────────────────────────────────────
function Section2({ scenarios, calcs, setScenario, FR }) {
  const f = window.fmt;
  const rows = [
    { key: 'grossIncome', label: FR ? 'Revenu brut annuel' : 'Annual gross income', editable: true,
      val: s => s.grossIncome, set: (idx, v) => setScenario(idx, 'grossIncome', v), fmt: v => f.money(v), min: 0, max: 500000, step: 500 },
    { key: 'addRevenue', label: FR ? 'Revenus additionnels (stationnement, buanderie…)' : 'Additional revenue', editable: true,
      val: s => s.addRevenue ?? 0, set: (idx, v) => setScenario(idx, 'addRevenue', v), fmt: v => f.money(v), min: 0, max: 50000, step: 100 },
    { key: 'vacancyPct', label: FR ? 'Vacance %' : 'Vacancy %', editable: true,
      val: s => s.vacancyPct, set: (idx, v) => setScenario(idx, 'vacancyPct', v / 100),
      fmt: v => `${(v * 100).toFixed(0)} %`, min: 0, max: 50, step: 1 },
    { key: 'grossEffective', label: FR ? 'Revenu brut effectif' : 'Effective gross income',
      val: (s, c) => c.grossEffective, fmt: v => f.money(v), bold: true, highlight: true },
  ];

  return (
    <section className="ap-section" id="ap-section-2">
      <h3 className="section-title">{FR ? '2. Revenus & vacance' : '2. Revenue & vacancy'}</h3>
      <div className="ap-table-wrap">
        <table className="ap-table">
          <thead>
            <tr>
              <th className="ap-th-label">{FR ? 'Poste' : 'Item'}</th>
              {scenarios.map((s, i) => <th key={i} className={`ap-th-col ap-col-${i}`}>{s.label}</th>)}
            </tr>
          </thead>
          <tbody>
            {rows.map(row => (
              <tr key={row.key} className={`ap-row ${row.bold ? 'ap-row-bold' : ''} ${row.highlight ? 'ap-row-highlight' : ''}`}>
                <td className="ap-td-label">{row.label}</td>
                {scenarios.map((s, i) => {
                  const rawVal = row.val(s, calcs[i]);
                  const displayVal = row.key === 'vacancyPct' ? s.vacancyPct : rawVal;
                  return (
                    <td key={i} className={`ap-td ap-col-${i}`}>
                      {row.editable
                        ? <NumInput
                            value={row.key === 'vacancyPct' ? +(s.vacancyPct * 100).toFixed(0) : rawVal}
                            onChange={v => row.set(i, v)}
                            min={row.min} max={row.max} step={row.step} fmt={row.fmt}/>
                        : row.fmt(rawVal)
                      }
                    </td>
                  );
                })}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </section>
  );
}

// ── Section 3 : Dépenses ─────────────────────────────────────────────────────
function Section3({ scenarios, calcs, setScenario, FR }) {
  const f = window.fmt;

  function pctRBE(val, gross) {
    if (!gross) return '';
    return `${((val / gross) * 100).toFixed(0)} % RBE`;
  }

  function ExpRow({ rowKey, label, block, vals, editable, setVals, min, max, step, noteKey }) {
    return (
      <tr className="ap-row">
        <td className="ap-td-label ap-td-indent">
          <span className="ap-block-dot" data-block={block}/>
          {label}
        </td>
        {scenarios.map((s, i) => {
          const val = vals[i];
          const gr = calcs[i].grossEffective;
          return (
            <td key={i} className={`ap-td ap-col-${i}`}>
              <div className="ap-td-inner">
                {editable
                  ? <NumInput value={val} onChange={v => setVals(i, v)} min={min} max={max} step={step} fmt={v => f.money(v)}/>
                  : f.money(val)
                }
                <span className="ap-pct-badge">{pctRBE(val, gr)}</span>
              </div>
            </td>
          );
        })}
      </tr>
    );
  }

  return (
    <section className="ap-section" id="ap-section-3">
      <h3 className="section-title">{FR ? '3. Dépenses' : '3. Expenses'}</h3>
      <div className="ap-expense-legend">
        <span className="ap-block-dot" data-block="A"/> {FR ? 'Fixes' : 'Fixed'}
        <span className="ap-block-dot" data-block="B"/> {FR ? 'Variables' : 'Variable'}
        <span className="ap-block-dot" data-block="C"/> {FR ? 'Gestion' : 'Management'}
        <span className="ap-block-dot" data-block="D"/> {FR ? 'Capex' : 'Capex'}
      </div>
      <div className="ap-table-wrap">
        <table className="ap-table">
          <thead>
            <tr>
              <th className="ap-th-label">{FR ? 'Poste' : 'Item'}</th>
              {scenarios.map((s, i) => <th key={i} className={`ap-th-col ap-col-${i}`}>{s.label}</th>)}
            </tr>
          </thead>
          <tbody>
            <tr className="ap-row-group-header"><td colSpan={scenarios.length + 1} className="ap-block-header" data-block="A">{FR ? 'Bloc A — Fixes' : 'Block A — Fixed'}</td></tr>
            <ExpRow rowKey="taxesMun" label={FR ? 'Taxes municipales' : 'Municipal taxes'} block="A"
              vals={scenarios.map((s, i) => s.taxesMun ?? calcs[i].taxesMun)} editable
              setVals={(idx, v) => setScenario(idx, 'taxesMun', v)} min={0} max={100000} step={100}/>
            <ExpRow rowKey="taxesScol" label={FR ? 'Taxes scolaires' : 'School taxes'} block="A"
              vals={scenarios.map((s, i) => s.taxesScol ?? calcs[i].taxesScol)} editable
              setVals={(idx, v) => setScenario(idx, 'taxesScol', v)} min={0} max={20000} step={50}/>
            <ExpRow rowKey="assurance" label={FR ? 'Assurance' : 'Insurance'} block="A"
              vals={scenarios.map((s, i) => s.assurance ?? calcs[i].assurance)} editable
              setVals={(idx, v) => setScenario(idx, 'assurance', v)} min={0} max={20000} step={50}/>

            <tr className="ap-row-group-header"><td colSpan={scenarios.length + 1} className="ap-block-header" data-block="B">{FR ? 'Bloc B — Variables' : 'Block B — Variable'}</td></tr>
            <ExpRow rowKey="electricite" label={FR ? 'Électricité (si commun)' : 'Electricity (common)'} block="B"
              vals={scenarios.map(s => s.electricite ?? 0)} editable
              setVals={(idx, v) => setScenario(idx, 'electricite', v)} min={0} max={30000} step={100}/>
            <ExpRow rowKey="energie" label={FR ? 'Chauffage / énergie' : 'Heating / energy'} block="B"
              vals={scenarios.map(s => s.energie ?? 0)} editable
              setVals={(idx, v) => setScenario(idx, 'energie', v)} min={0} max={20000} step={100}/>
            <ExpRow rowKey="deneigement" label={FR ? 'Déneigement / entretien' : 'Snow removal / maintenance'} block="B"
              vals={scenarios.map(s => s.deneigement ?? 0)} editable
              setVals={(idx, v) => setScenario(idx, 'deneigement', v)} min={0} max={10000} step={100}/>

            <tr className="ap-row-group-header"><td colSpan={scenarios.length + 1} className="ap-block-header" data-block="C">{FR ? 'Bloc C — Gestion' : 'Block C — Management'}</td></tr>
            <ExpRow rowKey="gestion" label={FR ? `Gestion (${(scenarios[0].managementPct*100).toFixed(0)} % RBE)` : `Management (${(scenarios[0].managementPct*100).toFixed(0)}% EGI)`} block="C"
              vals={scenarios.map((s, i) => s.gestionOverride ?? calcs[i].gestion)} editable
              setVals={(idx, v) => setScenario(idx, 'gestionOverride', v)} min={0} max={50000} step={100}/>

            <tr className="ap-row-group-header"><td colSpan={scenarios.length + 1} className="ap-block-header" data-block="D">{FR ? 'Bloc D — Capex' : 'Block D — Capex'}</td></tr>
            <tr className="ap-row">
              <td className="ap-td-label ap-td-indent">
                <span className="ap-block-dot" data-block="D"/>
                {FR ? 'Réserve capex' : 'Capex reserve'}
                {' '}
                <span className="ap-badge badge-yellow" style={{ fontSize: 10 }}>
                  {FR ? `${(calcs[0].capexRate * 100).toFixed(1)} % valeur` : `${(calcs[0].capexRate * 100).toFixed(1)}% of value`}
                </span>
              </td>
              {scenarios.map((s, i) => {
                const val = s.capexOverride ?? calcs[i].capex;
                const gr = calcs[i].grossEffective;
                return (
                  <td key={i} className={`ap-td ap-col-${i}`}>
                    <div className="ap-td-inner">
                      <NumInput value={val} onChange={v => setScenario(i, 'capexOverride', v)}
                        min={0} max={100000} step={100} fmt={v => f.money(v)}/>
                      <span className="ap-pct-badge">{pctRBE(val, gr)}</span>
                    </div>
                  </td>
                );
              })}
            </tr>

            <tr className="ap-row ap-row-bold">
              <td className="ap-td-label">{FR ? 'Sous-total OpEx (hors Capex)' : 'OpEx subtotal (excl. Capex)'}</td>
              {calcs.map((c, i) => <td key={i} className={`ap-td ap-col-${i}`}>{f.money(c.totalOpex)}</td>)}
            </tr>
            <tr className="ap-row ap-row-bold ap-row-highlight">
              <td className="ap-td-label">{FR ? 'Total charges (OpEx + Capex)' : 'Total expenses (OpEx + Capex)'}</td>
              {calcs.map((c, i) => <td key={i} className={`ap-td ap-col-${i}`}>{f.money(c.totalCharges)}</td>)}
            </tr>
          </tbody>
        </table>
      </div>
    </section>
  );
}

// ── Section 4 : Financement ──────────────────────────────────────────────────
function Section4({ scenarios, calcs, setScenario, FR }) {
  const f = window.fmt;

  function dscrBadge(dscr, dscrMin) {
    const cls = dscr >= dscrMin ? 'badge-green' : dscr >= dscrMin * 0.9 ? 'badge-yellow' : 'badge-red';
    return <span className={`ap-badge ${cls}`}>{dscr.toFixed(2)}</span>;
  }

  return (
    <section className="ap-section" id="ap-section-4">
      <h3 className="section-title">{FR ? '4. Financement' : '4. Financing'}</h3>

      {/* Inputs */}
      <div className="ap-financing-inputs">
        {scenarios.map((s, i) => (
          <div key={i} className={`ap-fin-col ap-col-${i}`}>
            <div className="ap-fin-col-head">{s.label}</div>
            <div className="ap-fin-row">
              <span className="ap-fin-label">{FR ? 'Mise de fonds' : 'Down %'}</span>
              <NumInput value={+(s.downPaymentPct * 100).toFixed(0)}
                onChange={v => setScenario(i, 'downPaymentPct', v / 100)}
                min={5} max={50} step={1} fmt={v => `${v} %`}/>
            </div>
            <div className="ap-fin-row">
              <span className="ap-fin-label">{FR ? 'Taux' : 'Rate'}</span>
              <NumInput value={+(s.mortgageRate * 100).toFixed(2)}
                onChange={v => setScenario(i, 'mortgageRate', v / 100)}
                min={2} max={12} step={0.05} fmt={v => `${v.toFixed(2)} %`}/>
            </div>
            <div className="ap-fin-row">
              <span className="ap-fin-label">{FR ? 'Amor.' : 'Amort.'}</span>
              <NumInput value={s.amortizationYears}
                onChange={v => setScenario(i, 'amortizationYears', v)}
                min={5} max={30} step={1} fmt={v => `${v} ${FR ? 'ans' : 'yr'}`}/>
            </div>
          </div>
        ))}
      </div>

      {/* Résultats */}
      <div className="ap-table-wrap" style={{ marginTop: 16 }}>
        <table className="ap-table">
          <thead>
            <tr>
              <th className="ap-th-label">{FR ? 'Indicateur' : 'Indicator'}</th>
              {scenarios.map((s, i) => <th key={i} className={`ap-th-col ap-col-${i}`}>{s.label}</th>)}
            </tr>
          </thead>
          <tbody>
            <tr className="ap-row">
              <td className="ap-td-label">{FR ? 'RCD min requis' : 'Min DSCR required'}</td>
              {calcs.map((c, i) => <td key={i} className={`ap-td ap-col-${i}`}>{c.dscrMin.toFixed(2)}</td>)}
            </tr>
            <tr className="ap-row ap-row-bold">
              <td className="ap-td-label">{FR ? 'RCD réel' : 'Actual DSCR'}</td>
              {calcs.map((c, i) => <td key={i} className={`ap-td ap-col-${i}`}>{dscrBadge(c.dscr, c.dscrMin)}</td>)}
            </tr>
            <tr className="ap-row">
              <td className="ap-td-label">{FR ? 'Valeur marchande (TGA)' : 'Market value (TGA)'}</td>
              {calcs.map((c, i) => <td key={i} className={`ap-td ap-col-${i}`}>{f.money(c.valMarchande)}</td>)}
            </tr>
            <tr className="ap-row">
              <td className="ap-td-label">{FR ? 'Valeur économique (RCD)' : 'Economic value (DSCR)'}</td>
              {calcs.map((c, i) => <td key={i} className={`ap-td ap-col-${i}`}>{f.money(c.valEconomique)}</td>)}
            </tr>
            <tr className="ap-row ap-row-bold ap-row-highlight">
              <td className="ap-td-label">{FR ? 'Prix retenu pour financement' : 'Financing reference price'}</td>
              {calcs.map((c, i) => <td key={i} className={`ap-td ap-col-${i}`}>{f.money(c.prixRetenu)}</td>)}
            </tr>
            <tr className="ap-row">
              <td className="ap-td-label">{FR ? 'Paiement mensuel' : 'Monthly payment'}</td>
              {calcs.map((c, i) => <td key={i} className={`ap-td ap-col-${i}`}>{f.money(c.mp)}</td>)}
            </tr>
            <tr className="ap-row">
              <td className="ap-td-label">{FR ? 'Service de la dette / an' : 'Annual debt service'}</td>
              {calcs.map((c, i) => <td key={i} className={`ap-td ap-col-${i}`}>{f.money(c.annualDebt)}</td>)}
            </tr>
          </tbody>
        </table>
      </div>
    </section>
  );
}

// ── Section 5 : KPI ──────────────────────────────────────────────────────────
function Section5({ scenarios, calcs, FR }) {
  const f = window.fmt;

  function KpiCol({ c, idx }) {
    const kpis = [
      { key: 'capRate', label: FR ? 'Cap rate brut' : 'Gross cap rate', val: c.capRateBrut, fmt: f.pct },
      { key: 'capRate', label: FR ? 'Cap rate ajusté capex' : 'Adj. cap rate', val: c.capRateAjuste, fmt: f.pct },
      { key: 'dscr', label: 'DSCR / RCD', val: c.dscr, fmt: v => v.toFixed(2) },
      { key: 'breakeven', label: FR ? 'Cash/Break-even' : 'Break-even', val: c.cashBreakeven, fmt: v => `${(v*100).toFixed(0)} %` },
      { key: 'cashflow', label: FR ? 'CF avant capex' : 'CF before capex', val: c.cashflowBrut, fmt: f.moneyShort },
      { key: 'cashflow', label: FR ? 'CF ajusté capex' : 'Adj. CF', val: c.cashflowAjuste, fmt: f.moneyShort },
      { key: 'coc', label: 'Cash-on-cash', val: c.cocAjuste, fmt: f.pct },
      { key: 'coc', label: FR ? 'ROI total' : 'Total ROI', val: c.roiTotal, fmt: f.pct },
      { key: null, label: 'MRB / GRM', val: c.grm, fmt: v => `${v.toFixed(1)}×` },
      { key: null, label: 'MRN / NRM', val: c.mrn, fmt: v => `${v.toFixed(1)}×` },
      { key: null, label: FR ? 'Revenu/porte/mois' : 'Rev./unit/mo', val: c.revParPorte, fmt: f.moneyShort },
      { key: 'cashflow', label: FR ? 'CF/porte/mois' : 'CF/unit/mo', val: c.cfParPorte, fmt: f.moneyShort },
    ];

    return (
      <div className={`ap-kpi-col ap-col-${idx}`}>
        <div className="ap-kpi-col-head">{scenarios[idx].label}</div>
        <div className="ap-kpi-grid">
          {kpis.map((kpi, ki) => (
            <div key={ki} className="ap-kpi-card">
              <div className="ap-kpi-label">{kpi.label}</div>
              <div className={`ap-kpi-value ${kpi.key ? kpiTone(kpi.key, kpi.val) : ''}`}>
                {kpi.fmt(kpi.val)}
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  return (
    <section className="ap-section" id="ap-section-5">
      <h3 className="section-title">{FR ? '5. Indicateurs clés' : '5. Key metrics'}</h3>
      <div className="ap-kpi-cols">
        {calcs.map((c, i) => <KpiCol key={i} c={c} idx={i}/>)}
      </div>
    </section>
  );
}

// ── Section 6 : Projection 10 ans ────────────────────────────────────────────
function Section6({ scenarios, calcs, FR }) {
  const [selIdx, setSelIdx] = useAP(0);
  const f = window.fmt;
  const proj = useMAP(() => computeProjection(scenarios[selIdx], calcs[selIdx]), [selIdx, scenarios, calcs]);

  return (
    <section className="ap-section" id="ap-section-6">
      <h3 className="section-title">
        {FR ? '6. Projection 10 ans' : '6. 10-year projection'}
        <div className="ap-proj-selector">
          {scenarios.map((s, i) => (
            <button key={i}
              className={`ap-proj-tab ${i === selIdx ? 'active' : ''} ap-col-${i}`}
              onClick={() => setSelIdx(i)}
            >{s.label}</button>
          ))}
        </div>
      </h3>
      <div className="ap-table-wrap">
        <table className="ap-table ap-projection-table">
          <thead>
            <tr>
              <th>{FR ? 'Année' : 'Year'}</th>
              <th>{FR ? 'Loyer eff.' : 'Eff. rent'}</th>
              <th>OpEx</th>
              <th>RNO / NOI</th>
              <th>{FR ? 'Serv. dette' : 'Debt svc'}</th>
              <th>CF</th>
              <th>{FR ? 'Cap. remb.' : 'Principal'}</th>
              <th>{FR ? 'Valeur' : 'Value'}</th>
              <th>{FR ? 'Équité' : 'Equity'}</th>
            </tr>
          </thead>
          <tbody>
            {proj.map(row => (
              <tr key={row.yr} className={row.yr % 2 === 0 ? 'ap-row-alt' : ''}>
                <td className="ap-td-year">{row.yr}</td>
                <td>{f.moneyShort(row.loyer)}</td>
                <td>{f.moneyShort(row.opex)}</td>
                <td>{f.moneyShort(row.rno)}</td>
                <td>{f.moneyShort(row.annualDebt)}</td>
                <td className={row.cf > 0 ? 'ap-pos' : 'ap-neg'}>{f.moneyShort(row.cf)}</td>
                <td>{f.moneyShort(row.capRemb)}</td>
                <td>{f.moneyShort(row.valeur)}</td>
                <td>{f.moneyShort(row.equite)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </section>
  );
}

// ── Section 7 : Sensibilité (tornado) ────────────────────────────────────────
function Section7({ scenarios, calcs, FR }) {
  const [selIdx, setSelIdx] = useAP(0);
  const tornado = useMAP(() => computeTornado(scenarios[selIdx], calcs[selIdx]), [selIdx, scenarios, calcs]);
  const maxAbs = Math.max(1, ...tornado.flatMap(t => [Math.abs(t.up), Math.abs(t.dn)]));
  const f = window.fmt;

  return (
    <section className="ap-section" id="ap-section-7">
      <h3 className="section-title">
        {FR ? '7. Analyse de sensibilité ±10 %' : '7. Sensitivity ±10%'}
        <div className="ap-proj-selector">
          {scenarios.map((s, i) => (
            <button key={i}
              className={`ap-proj-tab ${i === selIdx ? 'active' : ''} ap-col-${i}`}
              onClick={() => setSelIdx(i)}
            >{s.label}</button>
          ))}
        </div>
      </h3>
      <div className="ap-tornado-note">{FR ? 'Impact sur le cash-flow annuel ajusté' : 'Impact on annual adjusted cash flow'}</div>
      <div className="ap-tornado-wrap">
        {tornado.map(t => {
          const upW = Math.abs(t.up) / maxAbs * 45;
          const dnW = Math.abs(t.dn) / maxAbs * 45;
          return (
            <div key={t.key} className="ap-tornado-row">
              <div className="ap-tornado-label">{t.label}</div>
              <div className="ap-tornado-bars">
                <div className="ap-tornado-neg-zone">
                  <div className="ap-tornado-bar neg" style={{ width: `${dnW}%` }}>
                    <span className="ap-tornado-val">{t.dn > 0 ? '+' : ''}{f.moneyShort(t.dn)}</span>
                  </div>
                </div>
                <div className="ap-tornado-center"/>
                <div className="ap-tornado-pos-zone">
                  <div className="ap-tornado-bar pos" style={{ width: `${upW}%` }}>
                    <span className="ap-tornado-val">{t.up > 0 ? '+' : ''}{f.moneyShort(t.up)}</span>
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </section>
  );
}

// ── Section 9 : Fiscalité (CCA + gain en capital) ───────────────────────────

// Part bâtiment par défaut : 80% du prix d'achat (modifiable via UI ultérieurement)
const PART_BATIMENT_DEFAULT = 0.80;
// Taux marginal combiné fédéral + Qc par défaut (tranche ~100k$)
const TAUX_MARGINAL_DEFAULT = 0.47;
// Frais de vente estimés (courtage + notaire) en % du prix
const FRAIS_VENTE_PCT = 0.05;

function Section9({ scenarios, calcs, listing, FR }) {
  const f = window.fmt;
  const fisc = window.fiscalite;
  if (!fisc) return null;

  // Sélecteur de scénario (comme Section 6)
  const [selIdx, setSelIdx] = useAP(0);

  const s = scenarios[selIdx];

  // Part bâtiment : fallback 80% (pas de ratio terrain/bâtiment dans municipalAssessment)
  const coutBatiment = Math.round(s.price * PART_BATIMENT_DEFAULT);

  // CCA année 1 et années 5 / 10
  const cca1  = fisc.ccaCategorie1(coutBatiment, 1);
  const res5  = fisc.ccaCumule(coutBatiment, 5);
  const res10 = fisc.ccaCumule(coutBatiment, 10);
  const cca5  = res5.annees[4].ccaAnnuel;   // CCA de l'année 5
  const cca10 = res10.annees[9].ccaAnnuel;  // CCA de l'année 10

  // Économies d'impôt annuelles
  const eco1  = fisc.economieFiscaleCCA(cca1.ccaAnnuel, TAUX_MARGINAL_DEFAULT);
  const eco5  = fisc.economieFiscaleCCA(cca5, TAUX_MARGINAL_DEFAULT);
  const eco10 = fisc.economieFiscaleCCA(cca10, TAUX_MARGINAL_DEFAULT);

  // Scénario de revente après 5 ans et 10 ans
  function reventeCalc(nbAnnees) {
    const res = fisc.ccaCumule(coutBatiment, nbAnnees);
    const prixVente = Math.round(s.price * Math.pow(1 + (s.appreciationRate ?? 0.03), nbAnnees));
    const fraisVente = Math.round(prixVente * FRAIS_VENTE_PCT);
    const gain = fisc.gainEnCapital(prixVente, s.price, fraisVente, res.ccaCumule);
    const impot = fisc.impotSurGain(gain.totalImposable, TAUX_MARGINAL_DEFAULT);
    return { prixVente, fraisVente, ccaCumule: res.ccaCumule, ...gain, impot };
  }

  const rev5  = reventeCalc(5);
  const rev10 = reventeCalc(10);

  return (
    <section className="ap-section" id="ap-section-9">
      <h3 className="section-title">
        {FR ? '9. Fiscalité — CCA & gain en capital' : '9. Tax — CCA & capital gain'}
        <div className="ap-proj-selector">
          {scenarios.map((sc, i) => (
            <button key={i}
              className={`ap-proj-tab ${i === selIdx ? 'active' : ''} ap-col-${i}`}
              onClick={() => setSelIdx(i)}
            >{sc.label}</button>
          ))}
        </div>
      </h3>

      <div className="ap-fisc-note">
        {FR
          ? `Hypothèses : part bâtiment ${(PART_BATIMENT_DEFAULT * 100).toFixed(0)} % du prix d'achat · taux marginal ${(TAUX_MARGINAL_DEFAULT * 100).toFixed(0)} % · frais de vente ${(FRAIS_VENTE_PCT * 100).toFixed(0)} % · CCA cat. 1 à ${(fisc.CCA_RATE_BATIMENT * 100).toFixed(0)} % dégressif.`
          : `Assumptions: building portion ${(PART_BATIMENT_DEFAULT * 100).toFixed(0)}% of purchase price · marginal rate ${(TAUX_MARGINAL_DEFAULT * 100).toFixed(0)}% · selling costs ${(FRAIS_VENTE_PCT * 100).toFixed(0)}% · CCA class 1 at ${(fisc.CCA_RATE_BATIMENT * 100).toFixed(0)}% declining balance.`
        }
      </div>

      {/* CCA annuelle */}
      <div className="ap-fisc-subtitle">{FR ? 'Déduction pour amortissement (CCA)' : 'Capital Cost Allowance (CCA)'}</div>
      <div className="ap-table-wrap">
        <table className="ap-table">
          <thead>
            <tr>
              <th className="ap-th-label">{FR ? 'Année' : 'Year'}</th>
              <th className="ap-th-col">{FR ? 'CCA déduite' : 'CCA deducted'}</th>
              <th className="ap-th-col">{FR ? 'Économie d\'impôt' : 'Tax saving'}</th>
              <th className="ap-th-col">{FR ? 'FNACC (solde)' : 'UCC (balance)'}</th>
            </tr>
          </thead>
          <tbody>
            {[
              { yr: FR ? 'Année 1' : 'Year 1', cca: cca1.ccaAnnuel, eco: eco1, solde: cca1.soldeFermeture },
              { yr: FR ? 'Année 5' : 'Year 5', cca: cca5, eco: eco5, solde: res5.solde },
              { yr: FR ? 'Année 10' : 'Year 10', cca: cca10, eco: eco10, solde: res10.solde },
            ].map(row => (
              <tr key={row.yr} className="ap-row">
                <td className="ap-td-label">{row.yr}</td>
                <td className="ap-td ap-col-0">{f.money(row.cca)}</td>
                <td className="ap-td ap-col-0 ap-pos">{f.money(row.eco)}</td>
                <td className="ap-td ap-col-0">{f.money(row.solde)}</td>
              </tr>
            ))}
            <tr className="ap-row ap-row-bold">
              <td className="ap-td-label">{FR ? 'CCA cumulée 10 ans' : 'Cumul. CCA 10 yr'}</td>
              <td className="ap-td ap-col-0">{f.money(res10.ccaCumule)}</td>
              <td className="ap-td ap-col-0 ap-pos">{f.money(fisc.economieFiscaleCCA(res10.ccaCumule, TAUX_MARGINAL_DEFAULT))}</td>
              <td className="ap-td ap-col-0">—</td>
            </tr>
          </tbody>
        </table>
      </div>

      {/* Revente */}
      <div className="ap-fisc-subtitle" style={{ marginTop: 20 }}>
        {FR ? 'Fiscalité à la revente (gain en capital + récupération)' : 'Tax on sale (capital gain + recapture)'}
      </div>
      <div className="ap-table-wrap">
        <table className="ap-table">
          <thead>
            <tr>
              <th className="ap-th-label">{FR ? 'Poste' : 'Item'}</th>
              <th className="ap-th-col">{FR ? 'Revente 5 ans' : 'Sale yr 5'}</th>
              <th className="ap-th-col">{FR ? 'Revente 10 ans' : 'Sale yr 10'}</th>
            </tr>
          </thead>
          <tbody>
            {[
              { key: 'prixVente',                label: FR ? 'Prix de vente estimé'    : 'Estimated sale price',       fmt: f.money },
              { key: 'fraisVente',               label: FR ? 'Frais de vente'          : 'Selling costs',              fmt: f.money },
              { key: 'gainBrut',                 label: FR ? 'Gain brut'               : 'Gross gain',                 fmt: f.money },
              { key: 'ccaCumule',                label: FR ? 'CCA cumulée déduite'     : 'Cumul. CCA claimed',         fmt: f.money },
              { key: 'recuperationAmortissement',label: FR ? 'Récupération amortissement (100 % imposable)' : 'Recapture (100% taxable)', fmt: f.money },
              { key: 'gainCapital',              label: FR ? 'Gain en capital'         : 'Capital gain',               fmt: f.money },
              { key: 'gainImposable50',          label: FR ? 'Portion imposable (50 %)': 'Taxable portion (50%)',      fmt: f.money },
              { key: 'totalImposable',           label: FR ? 'Total imposable'         : 'Total taxable',              fmt: f.money, bold: true },
              { key: 'impot',                    label: FR ? `Impôt estimé (${(TAUX_MARGINAL_DEFAULT*100).toFixed(0)} %)` : `Est. tax (${(TAUX_MARGINAL_DEFAULT*100).toFixed(0)}%)`, fmt: f.money, bold: true, neg: true },
            ].map(row => (
              <tr key={row.key} className={`ap-row ${row.bold ? 'ap-row-bold' : ''}`}>
                <td className="ap-td-label">{row.label}</td>
                <td className={`ap-td ap-col-0 ${row.neg ? 'ap-neg' : ''}`}>{row.fmt(rev5[row.key])}</td>
                <td className={`ap-td ap-col-1 ${row.neg ? 'ap-neg' : ''}`}>{row.fmt(rev10[row.key])}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="ap-fisc-disclaimer">
        {FR
          ? 'Estimation indicative uniquement. Consultez un comptable ou fiscaliste pour votre situation personnelle. La récupération d\'amortissement s\'applique si des déductions CCA ont été réclamées.'
          : 'Indicative estimate only. Consult a tax professional for your personal situation. Recapture applies only if CCA deductions were previously claimed.'
        }
      </div>
    </section>
  );
}

// ── Section 8 : Verdict ──────────────────────────────────────────────────────
function Section8({ scenarios, calcs, FR }) {
  const f = window.fmt;
  const t = window.I18N[FR ? 'fr' : 'en'];
  const ALTS = [
    { label: 'S&P 500', rate: 0.10 },
    { label: 'CELI / TFSA', rate: 0.045 },
    { label: FR ? 'Indice Qc' : 'QC RE index', rate: 0.08 },
  ];

  return (
    <section className="ap-section" id="ap-section-8">
      <h3 className="section-title">{FR ? '8. Verdict & recommandation' : '8. Verdict & recommendation'}</h3>
      <div className="ap-verdict-cols">
        {scenarios.map((s, idx) => {
          const c = calcs[idx];
          const v = verdict(c);
          const pts = strengths(c, FR);
          const wk = weaknesses(c, FR);
          const bancable = c.dscr >= c.dscrMin;
          const coc = c.cocAjuste;

          return (
            <div key={idx} className={`ap-verdict-col ap-col-${idx}`}>
              <div className="ap-verdict-col-head">
                <span className="ap-verdict-label">{s.label}</span>
                <span className={`ap-verdict-badge verdict-${v}`}>{t[v]}</span>
              </div>

              {pts.length > 0 && (
                <div className="ap-verdict-section">
                  <div className="ap-verdict-section-title ap-pos">{FR ? 'Points forts' : 'Strengths'}</div>
                  {pts.map((p, i) => <div key={i} className="ap-verdict-item ap-pos">✓ {p}</div>)}
                </div>
              )}

              {wk.length > 0 && (
                <div className="ap-verdict-section">
                  <div className="ap-verdict-section-title ap-neg">{FR ? 'Points faibles' : 'Weaknesses'}</div>
                  {wk.map((p, i) => <div key={i} className="ap-verdict-item ap-neg">~ {p}</div>)}
                </div>
              )}

              <div className="ap-verdict-section">
                <div className="ap-verdict-section-title">{FR ? 'Finançabilité' : 'Bankability'}</div>
                <div className={`ap-finançable ${bancable ? 'ap-pos' : 'ap-neg'}`}>
                  <span className="ap-feu">{bancable ? '🟢' : '🔴'}</span>
                  {bancable
                    ? (FR ? 'Finançable (DSCR ≥ ' + c.dscrMin.toFixed(2) + ')' : 'Financeable (DSCR ≥ ' + c.dscrMin.toFixed(2) + ')')
                    : (FR ? `DSCR insuffisant (${c.dscr.toFixed(2)} < ${c.dscrMin.toFixed(2)})` : `DSCR insufficient (${c.dscr.toFixed(2)} < ${c.dscrMin.toFixed(2)})`)
                  }
                </div>
              </div>

              <div className="ap-verdict-section">
                <div className="ap-verdict-section-title">{FR ? 'Comparaison alternatives' : 'vs. alternatives'}</div>
                {ALTS.map(alt => (
                  <div key={alt.label} className="ap-alt-row">
                    <span className="ap-alt-label">{alt.label}</span>
                    <span className="ap-alt-rate">{(alt.rate * 100).toFixed(1)} %</span>
                    <span className={coc > alt.rate ? 'ap-pos' : 'ap-neg'}>
                      {coc > alt.rate ? '↑ +' : '↓ '}
                      {f.pct(Math.abs(coc - alt.rate))}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          );
        })}
      </div>
    </section>
  );
}

// ── Composant principal AnalyzePage ──────────────────────────────────────────
function AnalyzePage({ listing, profile: initProfile, onBack, lang }) {
  const FR = lang !== 'en';
  const t = window.I18N[lang] || window.I18N.fr;
  const f = window.fmt;

  const profile = initProfile || window.userProfile || window.DEFAULT_USER_PROFILE || {};

  const makeScenario = (label, overrides = {}) => ({
    label,
    price: listing.price,
    grossIncome: listing.metrics?.potentialGrossIncome ?? listing.metrics?.grossIncome ?? 0,
    units: listing.units ?? 1,
    yearBuilt: listing.yearBuilt ?? 1975,
    downPaymentPct: profile.downPaymentPct ?? 0.20,
    mortgageRate: profile.mortgageRate ?? 0.055,
    amortizationYears: profile.amortizationYears ?? 25,
    isSCHL: profile.isSCHL ?? false,
    vacancyPct: profile.vacancyPct ?? 0.05,
    managementPct: profile.managementPct ?? 0.08,
    appreciationRate: profile.appreciationRate ?? 0.03,
    rentGrowthRate: profile.rentGrowthRate ?? 0.03,
    tga: profile.tga ?? 0.055,
    ...overrides,
  });

  const [scenarios, setScenarios] = useAP(() => [
    makeScenario(FR ? 'Réaliste' : 'Realistic'),
    makeScenario(FR ? 'Optimiste' : 'Optimistic', {
      price: listing.price * 0.95,
      mortgageRate: (profile.mortgageRate ?? 0.055) - 0.005,
      grossIncome: (listing.metrics?.potentialGrossIncome ?? listing.metrics?.grossIncome ?? 0) * 1.05,
    }),
    makeScenario(FR ? 'Pessimiste' : 'Pessimistic', {
      vacancyPct: (profile.vacancyPct ?? 0.05) * 2,
      mortgageRate: (profile.mortgageRate ?? 0.055) + 0.01,
      grossIncome: (listing.metrics?.potentialGrossIncome ?? listing.metrics?.grossIncome ?? 0) * 0.95,
    }),
  ]);

  const [profileModalOpen, setProfileModalOpen] = useAP(false);
  const [pdfLoading, setPdfLoading] = useAP(false);

  // Gating tier — PDF + fiscalité réservés au plan Pro+ (Sprint 2 PR5)
  const [userTier, setUserTier] = useAP('decouverte');
  const [pdfPaywallOpen, setPdfPaywallOpen] = useAP(false);
  const [fiscPaywallOpen, setFiscPaywallOpen] = useAP(false);

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

  const pdfLocked = window.vestora?.tierGate
    ? !window.vestora?.tierGate.canAccess('pdf_export', userTier)
    : false;
  const fiscLocked = window.vestora?.tierGate
    ? !window.vestora?.tierGate.canAccess('tax_qc', userTier)
    : false;

  const handleExportPdf = async () => {
    if (pdfLocked) { setPdfPaywallOpen(true); return; }
    if (pdfLoading) return;
    setPdfLoading(true);
    try {
      if (window.vestoraPdf?.exportAnalysis) {
        await window.vestoraPdf.exportAnalysis(listing, { scenarios, calcs, lang });
      } else {
        window.print();
      }
    } catch (e) {
      console.error('PDF export failed', e);
      alert(FR ? 'Erreur lors de l\'export PDF. Réessayez.' : 'PDF export failed. Try again.');
    } finally {
      setPdfLoading(false);
    }
  };

  // Libère body/app-root du overflow:hidden pendant toute la durée de la page analyse
  useEAP(() => {
    document.body.classList.add('analyze-active');
    return () => document.body.classList.remove('analyze-active');
  }, []);

  const setScenario = (idx, key, val) => {
    setScenarios(prev => prev.map((s, i) => i === idx ? { ...s, [key]: val } : s));
  };

  const copyScenario = (from, to) => {
    setScenarios(prev => prev.map((s, i) => i === to ? { ...prev[from], label: s.label } : s));
  };

  const calcs = useMAP(() => scenarios.map(s => computeScenario(s)), [scenarios]);

  const address = [listing.address, listing.neighborhood, listing.city].filter(Boolean).join(', ');

  return (
    <div className="ap-root">
      {/* Header */}
      <div className="ap-header">
        <button className="ap-back-btn" onClick={onBack}>
          <svg width="14" height="14" viewBox="0 0 14 14" stroke="currentColor" strokeWidth="1.5" fill="none">
            <path d="M9 2L3 7l6 5"/>
          </svg>
          {FR ? 'Retour' : 'Back'}
        </button>
        <div className="ap-header-title">
          <div className="ap-header-address">{address}</div>
          <div className="ap-header-meta">
            <span className="ap-header-price">{f.money(listing.price)}</span>
            <span className="ap-header-type">{listing.type}</span>
            <span className="ap-header-units">{listing.units} {FR ? 'unités' : 'units'}</span>
          </div>
        </div>
        <div className="ap-header-actions">
          <button className="btn btn-ghost ap-btn-sm" onClick={() => setProfileModalOpen(true)}>
            {FR ? 'Mon profil' : 'My profile'}
          </button>
          <button
            className="btn ap-btn-sm ap-print-btn"
            onClick={handleExportPdf}
            disabled={pdfLoading}
            title={pdfLocked ? 'Plan Pro requis' : ''}
            style={pdfLocked ? { opacity: 0.65, cursor: 'pointer' } : {}}
          >
            {pdfLocked ? '🔒 ' : ''}
            {pdfLoading ? (FR ? '⏳ Génération…' : '⏳ Generating…') : (FR ? 'Exporter PDF' : 'Export PDF')}
          </button>
        </div>
      </div>

      {/* Boutons copier scénarios */}
      <div className="ap-copy-bar">
        <span className="ap-copy-label">{FR ? 'Copier :' : 'Copy:'}</span>
        {[['A→B', 0, 1], ['A→C', 0, 2], ['B→C', 1, 2], ['B→A', 1, 0], ['C→A', 2, 0], ['C→B', 2, 1]].map(([lbl, from, to]) => (
          <button key={lbl} className="ap-copy-btn" onClick={() => copyScenario(from, to)}>{lbl}</button>
        ))}
      </div>

      {/* Colonnes scénarios (labels + couleurs) */}
      <div className="ap-scenario-header">
        {scenarios.map((s, i) => (
          <div key={i} className={`ap-scenario-col-head ap-col-${i}`}>
            <input
              className="ap-scenario-label-input"
              value={s.label}
              onChange={e => setScenario(i, 'label', e.target.value)}
            />
          </div>
        ))}
      </div>

      {/* Sections */}
      <div className="ap-content">
        <Section1 scenarios={scenarios} calcs={calcs} setScenario={setScenario} FR={FR}/>
        <Section2 scenarios={scenarios} calcs={calcs} setScenario={setScenario} FR={FR}/>
        <Section3 scenarios={scenarios} calcs={calcs} setScenario={setScenario} FR={FR}/>
        <Section4 scenarios={scenarios} calcs={calcs} setScenario={setScenario} FR={FR}/>
        <Section5 scenarios={scenarios} calcs={calcs} FR={FR}/>
        <Section6 scenarios={scenarios} calcs={calcs} FR={FR}/>
        <Section7 scenarios={scenarios} calcs={calcs} FR={FR}/>
        <Section8 scenarios={scenarios} calcs={calcs} FR={FR}/>
        {/* Section 9 — Fiscalité QC : gated Pro+ (Sprint 2 PR5) */}
        {fiscLocked ? (
          <section className="ap-section" id="ap-section-9" style={{ position: 'relative' }}>
            {/* Preview floutée */}
            <div style={{ filter: 'blur(5px)', pointerEvents: 'none', userSelect: 'none', opacity: 0.4 }}>
              <h3 className="section-title">
                {FR ? '9. Fiscalité — CCA & gain en capital' : '9. Tax — CCA & capital gain'}
              </h3>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 16, padding: '0 0 16px' }}>
                {[1,2,3].map(i => <div key={i} style={{ height: 80, background: 'var(--surface-2, #f5f5f0)', borderRadius: 8 }}/>)}
              </div>
              <div style={{ height: 120, background: 'var(--surface-2, #f5f5f0)', borderRadius: 8, marginBottom: 16 }}/>
            </div>
            {/* Overlay cadenas + CTA */}
            <div style={{
              position: 'absolute', inset: 0,
              display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
              gap: 12, zIndex: 10, padding: 24,
            }}>
              <div style={{ fontSize: 28 }}>🔒</div>
              <p style={{
                textAlign: 'center', maxWidth: 360,
                color: 'var(--ink-2)', fontSize: 14, margin: 0, lineHeight: 1.5,
              }}>
                {FR
                  ? 'Le module Fiscalité QC (CCA + gain en capital) est réservé au plan Pro.'
                  : 'The QC Tax module (CCA + capital gains) requires a Pro plan.'}
              </p>
              <button
                onClick={() => setFiscPaywallOpen(true)}
                style={{
                  padding: '9px 20px', borderRadius: 8,
                  background: 'var(--brand, #2c3e2d)', color: '#fff',
                  border: 'none', cursor: 'pointer', fontWeight: 600, fontSize: 13,
                }}
              >
                {FR ? 'Débloquer avec Pro' : 'Unlock with Pro'}
              </button>
            </div>
            {window.PaywallModal && (
              <window.PaywallModal
                open={fiscPaywallOpen}
                onClose={() => setFiscPaywallOpen(false)}
                feature="tax_qc"
                featureLabel="Fiscalité QC — CCA & gain en capital"
                requiredTier="pro"
                currentTier={userTier}
                reason="tier_too_low"
              />
            )}
          </section>
        ) : (
          <Section9 scenarios={scenarios} calcs={calcs} listing={listing} FR={FR}/>
        )}

        {/* Export */}
        <div className="ap-export-bar">
          <button
            className="btn ap-print-btn-lg"
            onClick={handleExportPdf}
            disabled={pdfLoading}
            title={pdfLocked ? 'Plan Pro requis pour exporter en PDF' : ''}
            style={pdfLocked ? { opacity: 0.65, cursor: 'pointer' } : {}}
          >
            {pdfLocked
              ? React.createElement('svg', { width: 16, height: 16, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.5, strokeLinecap: 'round', strokeLinejoin: 'round', style: { display: 'inline-block', verticalAlign: 'middle', marginRight: 6 } },
                React.createElement('rect', { x: 3, y: 11, width: 18, height: 11, rx: 2 }),
                React.createElement('path', { d: 'M7 11V7a5 5 0 0110 0v4' })
              )
              : React.createElement('svg', { width: 16, height: 16, viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor', strokeWidth: 1.5 },
                React.createElement('path', { d: 'M4 6V1h8v5M4 11H2a1 1 0 01-1-1V6a1 1 0 011-1h12a1 1 0 011 1v4a1 1 0 01-1 1h-2M4 9h8v6H4V9z' })
              )
            }
            {pdfLoading ? (FR ? '⏳ Génération du PDF…' : '⏳ Generating PDF…') : (FR ? 'Exporter ce rapport (PDF)' : 'Export this report (PDF)')}
            {pdfLocked && <span style={{ fontSize: 11, marginLeft: 6, opacity: 0.8 }}>{FR ? '— Plan Pro' : '— Pro plan'}</span>}
          </button>
        </div>

        <div className="ap-methodology">
          <strong>{FR ? 'Méthodologie' : 'Methodology'} —</strong>{' '}
          {FR
            ? 'Calculs basés sur les hypothèses du profil investisseur. Droits de mutation selon barème Québec 2024. Les projections sont indicatives et ne constituent pas un conseil financier.'
            : 'Calculations based on investor profile assumptions. Transfer taxes per Quebec 2024 schedule. Projections are indicative and do not constitute financial advice.'
          }
        </div>
      </div>

      {/* Modal profil */}
      <window.UserProfileModal open={profileModalOpen} onClose={() => setProfileModalOpen(false)} lang={lang}/>

      {/* PaywallModal — PDF export (Sprint 2 PR5) */}
      {window.PaywallModal && (
        <window.PaywallModal
          open={pdfPaywallOpen}
          onClose={() => setPdfPaywallOpen(false)}
          feature="pdf_export"
          featureLabel="Export PDF signé Vestora Pro"
          requiredTier="pro"
          currentTier={userTier}
          reason="tier_too_low"
        />
      )}
    </div>
  );
}

Object.assign(window, { AnalyzePage });
