// SaisonImpotsPage — Calculateur Saison d'impôts T776/TP-128 (Vague 3 PR 3B)
// Route : #/saison-impots
// Saisie manuelle d'UN bien locatif + calcul du revenu net imposable
// fédéral et québécois, CCA optionnelle (catégorie 1, règle demi-année),
// recommandation IA simple "appliquer la CCA ou non" + export PDF
// formaté T776 (fédéral) + TP-128 (QC).
//
// Gating :
//   - decouverte (free) : CTA Investisseur Pro
//   - investisseur (24$): aperçu sections A+B+C, CTA upgrade pour D+E+PDF
//   - pro / pro_plus / pro_commercial / entreprise : tout déverrouillé
//
// Important : composant front 100% autonome, ne touche PAS au backend
// portfolio (réservé PR 3A).

const { useState: useSI, useEffect: useSIE, useMemo: useSIM } = React;

const TT_SI = window.TermTooltip || (({ children }) => children);

// ── Helpers fiscalité simplifiés ─────────────────────────────────────────────

function fmt$(n) {
  if (n == null || isNaN(n)) return '—';
  return new Intl.NumberFormat('fr-CA', { style: 'currency', currency: 'CAD', maximumFractionDigits: 0 }).format(n);
}
function fmtNum(n) {
  if (n == null || isNaN(n)) return '—';
  return new Intl.NumberFormat('fr-CA', { maximumFractionDigits: 0 }).format(n);
}
function parseNum(v) {
  if (v === '' || v == null) return 0;
  const x = parseFloat(String(v).replace(/\s/g, '').replace(',', '.'));
  return isNaN(x) ? 0 : x;
}

// CCA catégorie 1 — taux 4% dégressif, règle demi-année an 1 si acquis
function computeCCA({ fnaccOuverture, coutBatiment, acquisAnnee, applyCCA }) {
  if (!applyCCA) return { ccaAnnuel: 0, fnaccFermeture: fnaccOuverture };
  const TAUX = 0.04;
  if (acquisAnnee) {
    // règle demi-année : base = coût bâtiment, 50% seulement
    const cca = Math.round(coutBatiment * TAUX * 0.5);
    return { ccaAnnuel: cca, fnaccFermeture: Math.max(0, coutBatiment - cca) };
  }
  const cca = Math.round(fnaccOuverture * TAUX);
  return { ccaAnnuel: cca, fnaccFermeture: Math.max(0, fnaccOuverture - cca) };
}

// ── Composant principal ─────────────────────────────────────────────────────

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

  // SEO
  useSIE(() => {
    window.scrollTo(0, 0);
    const prevTitle = document.title;
    const prevMeta = document.querySelector('meta[name="description"]');
    const prevDesc = prevMeta ? prevMeta.getAttribute('content') : '';
    document.title = FR
      ? "Saison d'impôts immobilier QC — Calculateur T776/TP-128 — Vestora"
      : 'Tax Season Rental QC — T776/TP-128 Calculator — Vestora';
    if (prevMeta) {
      prevMeta.setAttribute('content', FR
        ? "Calculez votre revenu net locatif T776 (fédéral) et TP-128 (Québec) : revenus, dépenses déductibles, CCA optionnelle, économie d'impôt. PDF prêt pour la déclaration."
        : 'Calculate your T776 (federal) and TP-128 (Quebec) net rental income: rents, deductions, optional CCA, tax savings. PDF ready for filing.');
    }
    return () => {
      document.title = prevTitle;
      if (prevMeta) prevMeta.setAttribute('content', prevDesc);
    };
  }, [FR]);

  // ── Tier / gating ─────────────────────────────────────────────────────────
  const [tier, setTier] = useSI('decouverte');
  useSIE(() => {
    const tg = window.vestora && window.vestora.tierGate;
    if (!tg) return;
    tg.getCurrentTier().then(t => setTier(t)).catch(() => setTier('decouverte'));
  }, []);

  // Rank simplifié sans dépendre de l'export tierRank ESM
  const tierRankLocal = (t) => {
    switch (t) {
      case 'decouverte': return 0;
      case 'investisseur': return 1;
      case 'pro':
      case 'pro_plus':
      case 'investisseur_pro': return 2;
      case 'pro_commercial': return 3;
      case 'entreprise': return 4;
      default: return 0;
    }
  };
  const tierR = tierRankLocal(tier);
  const isFree = tierR === 0;
  const isInvestisseur = tierR === 1;
  const isUnlocked = tierR >= 2;

  // ── State des sections ────────────────────────────────────────────────────
  // Section A — Identification
  const [addressInput, setAddressInput] = useSI('');
  const [typeBien, setTypeBien] = useSI('plex');
  const [partBatimentPct, setPartBatimentPct] = useSI('80'); // % du prix attribué au bâtiment
  const [prixAchat, setPrixAchat] = useSI('');

  // Section B — Revenus
  const [loyersBruts, setLoyersBruts] = useSI('');
  const [autresRevenus, setAutresRevenus] = useSI('');
  const [pertesLocatives, setPertesLocatives] = useSI(''); // ex: logement vacant

  // Section C — Dépenses
  const [taxesMun, setTaxesMun] = useSI('');
  const [taxesScol, setTaxesScol] = useSI('');
  const [assurance, setAssurance] = useSI('');
  const [energie, setEnergie] = useSI('');
  const [interetsHypo, setInteretsHypo] = useSI('');
  const [fraisAdmin, setFraisAdmin] = useSI('');
  const [entretien, setEntretien] = useSI('');
  const [fraisJuridiques, setFraisJuridiques] = useSI('');
  const [fraisProf, setFraisProf] = useSI('');
  const [autresDep, setAutresDep] = useSI('');

  // Section D — CCA
  const [fnaccOuverture, setFnaccOuverture] = useSI(''); // si vide, on déduit du coût bâtiment
  const [acquisAnnee, setAcquisAnnee] = useSI(false);
  const [applyCCA, setApplyCCA] = useSI(true);

  // Section E — Taux marginal
  const [tauxMarginal, setTauxMarginal] = useSI('47'); // combiné fed+QC par défaut

  // ── Calculs dérivés ───────────────────────────────────────────────────────
  const calcs = useSIM(() => {
    const prix = parseNum(prixAchat);
    const partB = Math.max(0, Math.min(100, parseNum(partBatimentPct))) / 100;
    const coutBatiment = prix * partB;
    const coutTerrain = prix * (1 - partB);

    const revenus = parseNum(loyersBruts) + parseNum(autresRevenus) - parseNum(pertesLocatives);

    const depenses =
      parseNum(taxesMun) +
      parseNum(taxesScol) +
      parseNum(assurance) +
      parseNum(energie) +
      parseNum(interetsHypo) +
      parseNum(fraisAdmin) +
      parseNum(entretien) +
      parseNum(fraisJuridiques) +
      parseNum(fraisProf) +
      parseNum(autresDep);

    const revenuAvantCCA = revenus - depenses;

    const fnaccOuvNum = fnaccOuverture === ''
      ? coutBatiment // 1ère année par défaut = coût du bâtiment
      : parseNum(fnaccOuverture);

    const { ccaAnnuel, fnaccFermeture } = computeCCA({
      fnaccOuverture: fnaccOuvNum,
      coutBatiment,
      acquisAnnee,
      applyCCA,
    });

    // Règle ARC : la CCA ne peut pas créer de perte locative nette
    const ccaPlafonnee = revenuAvantCCA > 0
      ? Math.min(ccaAnnuel, revenuAvantCCA)
      : 0;

    const revenuNet = revenuAvantCCA - ccaPlafonnee;
    const taux = parseNum(tauxMarginal) / 100;
    const impotEstime = Math.max(0, revenuNet) * taux;
    const economieGraceCCA = ccaPlafonnee * taux;

    // Recommandation simple : appliquer CCA si revenuAvantCCA > 0 ET pas de plan de revente <3 ans
    const recoApplyCCA = revenuAvantCCA > 0;

    return {
      prix, partB, coutBatiment, coutTerrain,
      revenus, depenses, revenuAvantCCA,
      fnaccOuvNum, ccaAnnuel, ccaPlafonnee, fnaccFermeture,
      revenuNet, taux, impotEstime, economieGraceCCA,
      recoApplyCCA,
    };
  }, [
    prixAchat, partBatimentPct, loyersBruts, autresRevenus, pertesLocatives,
    taxesMun, taxesScol, assurance, energie, interetsHypo, fraisAdmin,
    entretien, fraisJuridiques, fraisProf, autresDep,
    fnaccOuverture, acquisAnnee, applyCCA, tauxMarginal,
  ]);

  // ── Export PDF ────────────────────────────────────────────────────────────
  const handleExportPdf = () => {
    const jsPDFClass = (window.jspdf && window.jspdf.jsPDF) || window.jsPDF;
    if (!jsPDFClass) {
      alert(FR ? 'jsPDF non chargé. Vérifiez la connexion internet.' : 'jsPDF not loaded.');
      return;
    }
    const doc = new jsPDFClass({ orientation: 'portrait', unit: 'mm', format: 'a4' });
    const PAGE_W = 210, PAGE_H = 297, MARGIN = 14;

    // Header
    doc.setFillColor(44, 62, 45);
    doc.rect(0, 0, PAGE_W, 26, 'F');
    doc.setFont('helvetica', 'bold');
    doc.setFontSize(16);
    doc.setTextColor(255, 255, 255);
    doc.text('VESTORA', MARGIN, 11);
    doc.setFont('helvetica', 'normal');
    doc.setFontSize(8);
    doc.setTextColor(139, 195, 74);
    doc.text(FR ? "Saison d'impôts — T776 (fédéral) + TP-128 (Québec)" : 'Tax Season — T776 + TP-128', MARGIN, 17);
    doc.setFontSize(8);
    doc.setTextColor(200, 220, 200);
    const dateStr = new Date().toISOString().slice(0, 10);
    doc.text(dateStr, PAGE_W - MARGIN, 11, { align: 'right' });

    let y = 34;

    // Section title helper
    const drawTitle = (label) => {
      doc.setFillColor(44, 62, 45);
      doc.rect(MARGIN, y, PAGE_W - MARGIN * 2, 6, 'F');
      doc.setFont('helvetica', 'bold');
      doc.setFontSize(8.5);
      doc.setTextColor(255, 255, 255);
      doc.text(label, MARGIN + 3, y + 4.2);
      y += 9;
    };

    const drawRow = (label, val, bold) => {
      doc.setFont('helvetica', bold ? 'bold' : 'normal');
      doc.setFontSize(9);
      doc.setTextColor(30, 40, 30);
      doc.text(label, MARGIN + 2, y);
      doc.text(val, PAGE_W - MARGIN - 2, y, { align: 'right' });
      y += 5.5;
    };

    // A — Identification
    drawTitle(FR ? 'A — IDENTIFICATION DU BIEN' : 'A — PROPERTY IDENTIFICATION');
    drawRow(FR ? 'Adresse' : 'Address', addressInput || '—');
    drawRow(FR ? 'Type' : 'Type', typeBien);
    drawRow(FR ? "Prix d'achat" : 'Purchase price', fmt$(calcs.prix));
    drawRow(FR ? 'Part bâtiment' : 'Building portion', (calcs.partB * 100).toFixed(0) + ' %');
    drawRow(FR ? 'Coût du bâtiment' : 'Building cost', fmt$(calcs.coutBatiment), true);
    drawRow(FR ? 'Coût du terrain' : 'Land cost', fmt$(calcs.coutTerrain));
    y += 3;

    // B — Revenus (T776 lignes 8141-8230 ; TP-128 lignes 10-25)
    drawTitle(FR ? 'B — REVENUS DE LOCATION (T776 lignes 8141+ / TP-128 lignes 10+)' : 'B — RENTAL INCOME (T776 8141+ / TP-128 10+)');
    drawRow(FR ? 'Loyers bruts encaissés' : 'Gross rents collected', fmt$(parseNum(loyersBruts)));
    drawRow(FR ? 'Autres revenus (parking, buanderie)' : 'Other income (parking, laundry)', fmt$(parseNum(autresRevenus)));
    drawRow(FR ? 'Moins : pertes locatives' : 'Less: rental losses', '-' + fmt$(parseNum(pertesLocatives)));
    drawRow(FR ? 'Revenus totaux' : 'Total income', fmt$(calcs.revenus), true);
    y += 3;

    // C — Dépenses (T776 lignes 8521-9281)
    drawTitle(FR ? 'C — DÉPENSES DÉDUCTIBLES (T776 lignes 8521+ / TP-128 lignes 30+)' : 'C — DEDUCTIBLE EXPENSES (T776 8521+ / TP-128 30+)');
    drawRow(FR ? 'Taxes municipales' : 'Municipal taxes', fmt$(parseNum(taxesMun)));
    drawRow(FR ? 'Taxes scolaires' : 'School taxes', fmt$(parseNum(taxesScol)));
    drawRow(FR ? 'Assurance' : 'Insurance', fmt$(parseNum(assurance)));
    drawRow(FR ? 'Énergie (chauffage, élec.)' : 'Utilities', fmt$(parseNum(energie)));
    drawRow(FR ? 'Intérêts hypothécaires' : 'Mortgage interest', fmt$(parseNum(interetsHypo)));
    drawRow(FR ? 'Frais administratifs' : 'Administrative fees', fmt$(parseNum(fraisAdmin)));
    drawRow(FR ? 'Entretien & réparations' : 'Maintenance & repairs', fmt$(parseNum(entretien)));
    drawRow(FR ? 'Frais juridiques' : 'Legal fees', fmt$(parseNum(fraisJuridiques)));
    drawRow(FR ? 'Frais professionnels (comptable)' : 'Professional fees', fmt$(parseNum(fraisProf)));
    drawRow(FR ? 'Autres dépenses' : 'Other expenses', fmt$(parseNum(autresDep)));
    drawRow(FR ? 'Dépenses totales' : 'Total expenses', fmt$(calcs.depenses), true);
    drawRow(FR ? 'Revenu avant CCA' : 'Income before CCA', fmt$(calcs.revenuAvantCCA), true);
    y += 3;

    // Pagination check
    if (y > PAGE_H - 70) { doc.addPage(); y = MARGIN; }

    // D — CCA (T776 Annexe — Catégorie 1)
    drawTitle(FR ? 'D — CCA CATÉGORIE 1 (T776 annexe / TP-128 partie 4)' : 'D — CCA CLASS 1');
    drawRow(FR ? 'FNACC ouverture' : 'Opening UCC', fmt$(calcs.fnaccOuvNum));
    drawRow(FR ? 'Règle demi-année (an 1)' : 'Half-year rule (Y1)', acquisAnnee ? (FR ? 'Oui' : 'Yes') : (FR ? 'Non' : 'No'));
    drawRow(FR ? 'Taux catégorie 1' : 'Class 1 rate', '4 %');
    drawRow(FR ? 'CCA calculée' : 'Computed CCA', fmt$(calcs.ccaAnnuel));
    drawRow(FR ? 'CCA appliquée (plafonnée)' : 'Applied CCA (capped)', fmt$(calcs.ccaPlafonnee), true);
    drawRow(FR ? 'FNACC fermeture' : 'Closing UCC', fmt$(calcs.fnaccFermeture));
    y += 3;

    // E — Résultat
    drawTitle(FR ? 'E — RÉSULTAT' : 'E — RESULT');
    drawRow(FR ? 'Revenu net imposable' : 'Net taxable income', fmt$(calcs.revenuNet), true);
    drawRow(FR ? "Taux marginal d'impôt" : 'Marginal tax rate', (calcs.taux * 100).toFixed(1) + ' %');
    drawRow(FR ? 'Impôt estimé (fed + QC combiné)' : 'Estimated tax (fed + QC)', fmt$(calcs.impotEstime), true);
    drawRow(FR ? "Économie d'impôt grâce à la CCA" : 'Tax savings from CCA', fmt$(calcs.economieGraceCCA));

    // Footer
    doc.setFillColor(44, 62, 45);
    doc.rect(0, PAGE_H - 10, PAGE_W, 10, 'F');
    doc.setFont('helvetica', 'normal');
    doc.setFontSize(6.5);
    doc.setTextColor(200, 220, 200);
    doc.text(
      FR
        ? "Vestora · Outil pédagogique. Vérifiez avec un comptable/fiscaliste avant de produire votre déclaration."
        : 'Vestora · Educational tool. Verify with a CPA before filing.',
      MARGIN, PAGE_H - 4
    );
    doc.text(dateStr, PAGE_W - MARGIN, PAGE_H - 4, { align: 'right' });

    const slug = (addressInput || 'mon-bien').toLowerCase().normalize('NFD').replace(/[^a-z0-9]+/g, '-').slice(0, 40);
    doc.save('vestora-saison-impots-' + slug + '-' + dateStr + '.pdf');
  };

  // ── Rendu Free : CTA Investisseur Pro ─────────────────────────────────────
  if (isFree) {
    return (
      <div className="legal-page" style={{ maxWidth: 920 }}>
        <div className="legal-header">
          <button className="btn btn-ghost" onClick={onBack}>{FR ? '← Retour' : '← Back'}</button>
        </div>
        <div className="legal-content" style={{ padding: '28px 32px' }}>
          <h1 style={{ fontFamily: 'var(--font-display, Fraunces, serif)', fontSize: 28, marginBottom: 8 }}>
            {FR ? "Saison d'impôts — Revenu locatif QC" : 'Tax Season — QC Rental Income'}
          </h1>
          <p style={{ color: '#666', marginBottom: 20 }}>
            {FR
              ? "Calculateur T776 (fédéral) + TP-128 (Québec) avec CCA optionnelle et export PDF prêt pour la déclaration. Réservé Investisseur Pro 49 $/mo."
              : 'T776 (federal) + TP-128 (Quebec) calculator with optional CCA and PDF export. Investor Pro 49$/mo.'}
          </p>
          <div style={{
            padding: '22px 24px', borderRadius: 14,
            background: 'linear-gradient(135deg, #1e3a5f, #1e6f5c)',
            color: '#fff', marginBottom: 18,
          }}>
            <div style={{ fontWeight: 700, fontSize: 17, marginBottom: 6 }}>
              {FR ? 'Débloquez Saison d\'impôts' : 'Unlock Tax Season'}
            </div>
            <ul style={{ fontSize: 13.5, lineHeight: 1.7, opacity: 0.92, paddingLeft: 18, margin: 0 }}>
              <li>{FR ? 'Sections T776 + TP-128 complètes (revenus, dépenses, CCA)' : 'Full T776 + TP-128 (income, expenses, CCA)'}</li>
              <li>{FR ? 'Calcul de la CCA cat. 1 avec règle demi-année' : 'Class 1 CCA with half-year rule'}</li>
              <li>{FR ? "Recommandation auto « appliquer la CCA ou non »" : 'Auto recommendation "apply CCA or not"'}</li>
              <li>{FR ? "Export PDF formaté prêt à donner au comptable" : 'Formatted PDF for your CPA'}</li>
            </ul>
            <a href="#/tarifs" style={{
              display: 'inline-block', marginTop: 14,
              background: '#fff', color: '#1e3a5f', borderRadius: 8,
              padding: '10px 20px', fontWeight: 700, fontSize: 14,
              textDecoration: 'none',
            }}>
              {FR ? 'Voir Investisseur Pro 49 $ →' : 'See Investor Pro 49$ →'}
            </a>
          </div>
          <p style={{ fontSize: 12, color: '#888' }}>
            {FR
              ? "Outil éducatif. Ne remplace pas un comptable agréé."
              : 'Educational tool. Does not replace a chartered accountant.'}
          </p>
        </div>
      </div>
    );
  }

  // ── Rendu principal (Investisseur preview + Pro+ full) ────────────────────
  return (
    <div className="legal-page" style={{ maxWidth: 1000 }}>
      <div className="legal-header">
        <button className="btn btn-ghost" onClick={onBack}>{FR ? '← Retour' : '← Back'}</button>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          {isInvestisseur && (
            <span style={{
              fontSize: 11, padding: '4px 10px', borderRadius: 12,
              background: '#fef3c7', color: '#92400e', fontWeight: 600,
            }}>
              {FR ? 'Aperçu — upgrade Pro pour calcul + PDF' : 'Preview — upgrade Pro for calc + PDF'}
            </span>
          )}
          {isUnlocked && (
            <button
              onClick={handleExportPdf}
              style={{
                background: '#1e6f5c', color: '#fff', border: 'none',
                borderRadius: 8, padding: '8px 16px', fontWeight: 600,
                fontSize: 13, cursor: 'pointer',
              }}
            >
              {FR ? '📄 Exporter PDF' : '📄 Export PDF'}
            </button>
          )}
        </div>
      </div>

      <div className="legal-content" style={{ padding: '24px 32px' }}>
        <h1 style={{ fontFamily: 'var(--font-display, Fraunces, serif)', fontSize: 26, marginBottom: 4 }}>
          {FR ? "Saison d'impôts — Revenu locatif QC" : 'Tax Season — QC Rental Income'}
        </h1>
        <p style={{ color: '#666', margin: '0 0 24px', fontSize: 14 }}>
          {FR
            ? "Remplissez les sections du formulaire T776 (fédéral) + TP-128 (Québec). Le calcul de la CCA et l'impôt estimé sont automatiques."
            : 'Fill in T776 (federal) + TP-128 (Quebec) sections. CCA and estimated tax are computed automatically.'}
        </p>

        {/* Section A */}
        <SectionTitle n="A" label={FR ? 'Identification du bien' : 'Property identification'} />
        <Grid>
          <Field label={FR ? 'Adresse' : 'Address'} value={addressInput} onChange={setAddressInput} type="text" placeholder="123 rue Principale, Montréal" />
          <Field label={FR ? 'Type' : 'Type'} value={typeBien} onChange={setTypeBien} type="select"
                 options={[
                   { value: 'plex', label: FR ? 'Plex (2-5 logements)' : 'Plex (2-5 units)' },
                   { value: 'multilogement', label: FR ? 'Multilogement (6+)' : 'Multi-residential (6+)' },
                   { value: 'condo', label: FR ? 'Condo locatif' : 'Rental condo' },
                   { value: 'maison', label: FR ? 'Maison locative' : 'Rental house' },
                 ]} />
          <Field label={FR ? "Prix d'achat ($)" : 'Purchase price ($)'} value={prixAchat} onChange={setPrixAchat} placeholder="650 000" />
          <Field label={<TT_SI term="part_batiment">{FR ? 'Part bâtiment (%)' : 'Building portion (%)'}</TT_SI>}
                 hint={FR ? `Terrain = ${(100 - parseNum(partBatimentPct)).toFixed(0)} %` : `Land = ${(100 - parseNum(partBatimentPct)).toFixed(0)} %`}
                 value={partBatimentPct} onChange={setPartBatimentPct} placeholder="80" />
        </Grid>
        <DerivedRow label={FR ? 'Coût du bâtiment (amortissable)' : 'Building cost (depreciable)'} value={fmt$(calcs.coutBatiment)} />
        <DerivedRow label={FR ? 'Coût du terrain (non amortissable)' : 'Land cost (non-depreciable)'} value={fmt$(calcs.coutTerrain)} />

        {/* Section B */}
        <SectionTitle n="B" label={FR ? 'Revenus de location (T776 8141+ / TP-128 10+)' : 'Rental income'} />
        <Grid>
          <Field label={FR ? 'Loyers bruts encaissés' : 'Gross rents collected'} value={loyersBruts} onChange={setLoyersBruts} placeholder="48 000" />
          <Field label={FR ? 'Autres revenus (parking, buanderie)' : 'Other income (parking, laundry)'} value={autresRevenus} onChange={setAutresRevenus} placeholder="1 200" />
          <Field label={FR ? 'Pertes locatives (vacance)' : 'Rental losses (vacancy)'} value={pertesLocatives} onChange={setPertesLocatives} placeholder="0" />
        </Grid>
        <DerivedRow label={FR ? 'Revenus totaux' : 'Total income'} value={fmt$(calcs.revenus)} bold />

        {/* Section C */}
        <SectionTitle n="C" label={FR ? 'Dépenses déductibles (T776 8521+ / TP-128 30+)' : 'Deductible expenses'} />
        <Grid>
          <Field label={FR ? 'Taxes municipales' : 'Municipal taxes'} value={taxesMun} onChange={setTaxesMun} placeholder="4 800" />
          <Field label={FR ? 'Taxes scolaires' : 'School taxes'} value={taxesScol} onChange={setTaxesScol} placeholder="600" />
          <Field label={FR ? 'Assurance' : 'Insurance'} value={assurance} onChange={setAssurance} placeholder="2 400" />
          <Field label={FR ? 'Énergie (chauffage, élec.)' : 'Utilities'} value={energie} onChange={setEnergie} placeholder="1 200" />
          <Field label={FR ? 'Intérêts hypothécaires' : 'Mortgage interest'} value={interetsHypo} onChange={setInteretsHypo} placeholder="18 000" />
          <Field label={FR ? 'Frais administratifs' : 'Administrative fees'} value={fraisAdmin} onChange={setFraisAdmin} placeholder="0" />
          <Field label={FR ? 'Entretien & réparations' : 'Maintenance & repairs'} value={entretien} onChange={setEntretien} placeholder="3 000" />
          <Field label={FR ? 'Frais juridiques' : 'Legal fees'} value={fraisJuridiques} onChange={setFraisJuridiques} placeholder="0" />
          <Field label={FR ? 'Frais professionnels (comptable)' : 'Professional fees'} value={fraisProf} onChange={setFraisProf} placeholder="500" />
          <Field label={FR ? 'Autres dépenses' : 'Other expenses'} value={autresDep} onChange={setAutresDep} placeholder="0" />
        </Grid>
        <DerivedRow label={FR ? 'Dépenses totales' : 'Total expenses'} value={fmt$(calcs.depenses)} bold />
        <DerivedRow label={FR ? 'Revenu avant CCA' : 'Income before CCA'} value={fmt$(calcs.revenuAvantCCA)} bold />

        {/* Section D — gated pour Investisseur (preview only) */}
        {!isUnlocked && (
          <div style={{
            marginTop: 28, padding: 20, borderRadius: 12,
            background: '#fef3c7', border: '1px solid #fbbf24',
          }}>
            <div style={{ fontWeight: 700, marginBottom: 6 }}>
              {FR ? '🔒 Sections D + E + PDF — Investisseur Pro 49 $' : '🔒 Sections D + E + PDF — Investor Pro 49$'}
            </div>
            <p style={{ fontSize: 13, color: '#555', margin: '0 0 12px' }}>
              {FR
                ? "Pour calculer la CCA cat. 1, l'impôt estimé et exporter le PDF prêt-à-donner-au-comptable, passez à Investisseur Pro."
                : 'To compute CCA Class 1, estimated tax and export the PDF, upgrade to Investor Pro.'}
            </p>
            <a href="#/tarifs" style={{
              background: '#1e3a5f', color: '#fff', borderRadius: 8,
              padding: '8px 16px', fontWeight: 700, fontSize: 13,
              textDecoration: 'none', display: 'inline-block',
            }}>
              {FR ? 'Voir les forfaits →' : 'View plans →'}
            </a>
          </div>
        )}

        {isUnlocked && (
          <>
            <SectionTitle n="D" label={<><TT_SI term="amortissement">CCA</TT_SI> — {FR ? 'Catégorie 1 (optionnelle)' : 'Class 1 (optional)'}</>} />
            <Grid>
              <Field
                label={<TT_SI term="fnacc">{FR ? "FNACC d'ouverture" : 'Opening UCC'}</TT_SI>}
                hint={FR ? `Vide = coût du bâtiment (${fmt$(calcs.coutBatiment)})` : `Empty = building cost (${fmt$(calcs.coutBatiment)})`}
                value={fnaccOuverture} onChange={setFnaccOuverture}
                placeholder={fmtNum(calcs.coutBatiment)}
              />
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 18 }}>
                <input
                  type="checkbox"
                  id="acquisAnnee"
                  checked={acquisAnnee}
                  onChange={e => setAcquisAnnee(e.target.checked)}
                  style={{ width: 18, height: 18 }}
                />
                <label htmlFor="acquisAnnee" style={{ fontSize: 13 }}>
                  {FR ? "Bien acquis cette année (règle demi-année)" : 'Acquired this year (half-year rule)'}
                </label>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 18 }}>
                <input
                  type="checkbox"
                  id="applyCCA"
                  checked={applyCCA}
                  onChange={e => setApplyCCA(e.target.checked)}
                  style={{ width: 18, height: 18 }}
                />
                <label htmlFor="applyCCA" style={{ fontSize: 13 }}>
                  {FR ? 'Appliquer la CCA cette année' : 'Apply CCA this year'}
                </label>
              </div>
            </Grid>

            {/* Recommandation */}
            <div style={{
              marginTop: 12, padding: '12px 16px', borderRadius: 10,
              background: calcs.recoApplyCCA ? '#ecfdf5' : '#fef3c7',
              border: '1px solid ' + (calcs.recoApplyCCA ? '#10b981' : '#fbbf24'),
              fontSize: 13, color: '#333',
            }}>
              <strong>{FR ? '💡 Recommandation :' : '💡 Recommendation:'}</strong>{' '}
              {calcs.recoApplyCCA
                ? (FR
                    ? "Appliquer la CCA — votre revenu locatif est positif, la CCA réduira votre impôt. ⚠️ Attention à la récupération d'amortissement à la revente (revenu ordinaire imposé à 100%)."
                    : 'Apply CCA — positive rental income, CCA reduces tax. ⚠️ Beware recapture at sale (ordinary income, 100% taxed).')
                : (FR
                    ? "Ne pas appliquer la CCA cette année — votre revenu locatif est ≤ 0, la CCA ne peut pas créer de perte (règle ARC). Reportez-la aux années suivantes."
                    : 'Skip CCA this year — rental income ≤ 0, CCA cannot create a loss (CRA rule). Carry forward.')}
            </div>
            <DerivedRow label={FR ? 'CCA calculée' : 'Computed CCA'} value={fmt$(calcs.ccaAnnuel)} />
            <DerivedRow label={FR ? 'CCA appliquée (plafonnée)' : 'Applied CCA (capped)'} value={fmt$(calcs.ccaPlafonnee)} bold />
            <DerivedRow label={FR ? 'FNACC fermeture' : 'Closing UCC'} value={fmt$(calcs.fnaccFermeture)} />

            {/* Section E */}
            <SectionTitle n="E" label={FR ? 'Résultat' : 'Result'} />
            <Grid>
              <Field
                label={<TT_SI term="taux_marginal">{FR ? "Taux marginal d'impôt (%)" : 'Marginal tax rate (%)'}</TT_SI>}
                hint={FR ? 'Combiné fédéral + Québec, ex: 47 %' : 'Combined federal + QC, e.g. 47%'}
                value={tauxMarginal} onChange={setTauxMarginal}
                placeholder="47"
              />
            </Grid>
            <div style={{
              marginTop: 16, padding: '18px 20px', borderRadius: 12,
              background: '#f7f9f8', border: '1.5px solid #d0e8e0',
            }}>
              <ResultRow label={FR ? 'Revenu net imposable' : 'Net taxable income'} value={fmt$(calcs.revenuNet)} color="#1e3a5f" big />
              <ResultRow label={FR ? "Impôt estimé (fed + QC combiné)" : 'Estimated tax (fed + QC)'} value={fmt$(calcs.impotEstime)} color="#dc2626" big />
              <ResultRow label={FR ? "Économie d'impôt grâce à la CCA" : 'Tax savings from CCA'} value={fmt$(calcs.economieGraceCCA)} color="#1e6f5c" />
            </div>

            {/* Disclaimer */}
            <p style={{ marginTop: 16, padding: '12px 16px', background: '#fefce8', borderRadius: 8, fontSize: 12, color: '#666', border: '1px solid #fde68a' }}>
              <strong>{FR ? 'Avertissement :' : 'Disclaimer:'}</strong>{' '}
              {FR
                ? "Calcul simplifié à titre éducatif. Le taux marginal combiné réel dépend de votre revenu total (échelle progressive ARC + Revenu QC). Confiez votre déclaration à un comptable agréé."
                : 'Simplified calculation for educational purposes. Actual marginal rate depends on total income (CRA + Revenu QC brackets). Consult a chartered accountant.'}
            </p>
          </>
        )}
      </div>

      {/* Bloc SEO / éducatif (visible pour tous les tiers payants) */}
      <div className="legal-content" style={{ marginTop: 20, padding: '28px 32px' }}>
        <h2 style={{ fontSize: 20, marginBottom: 12, fontFamily: 'var(--font-display, Fraunces, serif)' }}>
          {FR ? "Saison d'impôts locatif au Québec — repères" : 'Quebec rental tax season — key facts'}
        </h2>
        <h3 style={{ fontSize: 15, color: '#1e6f5c', marginTop: 16 }}>{FR ? 'T776 vs TP-128 : deux formulaires, un même calcul' : 'T776 vs TP-128'}</h3>
        <p>
          {FR
            ? "Au Québec, vous déclarez votre revenu locatif deux fois : T776 (État des loyers de biens immeubles) au fédéral, TP-128 (Revenus et dépenses afférents à un bien locatif) au provincial. Les lignes se correspondent ; la CCA peut être appliquée différemment des deux paliers."
            : 'In Quebec you file twice: T776 (federal) and TP-128 (provincial). Line items match; CCA can be elected differently at each level.'}
        </p>
        <h3 style={{ fontSize: 15, color: '#1e6f5c', marginTop: 16 }}>
          {FR ? <TT_SI term="amortissement">{`La CCA — une déduction optionnelle`}</TT_SI> : 'CCA — an optional deduction'}
        </h3>
        <p>
          {FR
            ? "La CCA catégorie 1 (4 % dégressif) est facultative chaque année. Elle réduit l'impôt courant mais déclenche une récupération d'amortissement à la revente. À éviter si vous prévoyez revendre dans les 3-5 ans."
            : 'Class 1 CCA (4% declining) is optional each year. It cuts current tax but triggers recapture at sale.'}
        </p>
        <h3 style={{ fontSize: 15, color: '#1e6f5c', marginTop: 16 }}>{FR ? 'Plafond : pas de perte créée par la CCA' : 'Cap: CCA cannot create a loss'}</h3>
        <p>
          {FR
            ? "Règle ARC : la CCA ne peut pas créer de perte locative nette. Si votre revenu avant CCA est ≤ 0, la CCA appliquée est plafonnée à 0 et reportée."
            : 'CRA rule: CCA cannot create a net rental loss. Capped at zero and carried forward.'}
        </p>
      </div>

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

// ── Sous-composants UI ─────────────────────────────────────────────────────

function SectionTitle({ n, label }) {
  return (
    <h2 style={{
      marginTop: 26, marginBottom: 12, fontSize: 16, fontWeight: 700,
      color: '#1e3a5f', borderBottom: '2px solid #d0e8e0', paddingBottom: 6,
      fontFamily: 'var(--font-body)',
    }}>
      <span style={{
        display: 'inline-block', background: '#1e6f5c', color: '#fff',
        borderRadius: 6, padding: '2px 8px', fontSize: 12, fontWeight: 700,
        marginRight: 8, verticalAlign: 1,
      }}>{n}</span>
      {label}
    </h2>
  );
}

function Grid({ children }) {
  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))',
      gap: 14, marginBottom: 10,
    }}>{children}</div>
  );
}

function Field({ label, hint, value, onChange, placeholder, type, options }) {
  return (
    <div>
      <label style={{ display: 'block', fontSize: 12.5, fontWeight: 600, marginBottom: 3, color: '#2a2a2a' }}>
        {label}
      </label>
      {hint && <div style={{ fontSize: 10.5, color: '#888', marginBottom: 4 }}>{hint}</div>}
      {type === 'select' ? (
        <select
          value={value}
          onChange={e => onChange(e.target.value)}
          style={inputStyle}
        >
          {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
        </select>
      ) : (
        <input
          type={type === 'text' ? 'text' : 'number'}
          value={value}
          onChange={e => onChange(e.target.value)}
          placeholder={placeholder}
          style={inputStyle}
        />
      )}
    </div>
  );
}

const inputStyle = {
  width: '100%', padding: '8px 10px', borderRadius: 7,
  border: '1.5px solid #ddd', fontSize: 13.5,
  fontFamily: 'var(--font-body)', background: '#fff',
  boxSizing: 'border-box', outline: 'none',
};

function DerivedRow({ label, value, bold }) {
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between',
      padding: '6px 10px', fontSize: 13,
      fontWeight: bold ? 700 : 500,
      color: bold ? '#1e3a5f' : '#444',
      borderBottom: '1px dashed #e4ece8',
    }}>
      <span>{label}</span>
      <span style={{ fontFamily: 'var(--font-mono, monospace)' }}>{value}</span>
    </div>
  );
}

function ResultRow({ label, value, color, big }) {
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
      padding: '8px 0', borderBottom: '1px dashed #d0e8e0',
    }}>
      <span style={{ fontSize: big ? 14 : 13, color: '#555' }}>{label}</span>
      <span style={{
        fontFamily: 'var(--font-mono, monospace)',
        fontSize: big ? 22 : 16, fontWeight: 700, color: color || '#1e3a5f',
      }}>{value}</span>
    </div>
  );
}

window.SaisonImpotsPage = SaisonImpotsPage;
