// Calculateur CCA catégorie 1 — outil public gratuit, SEO + acquisition
// Route : #/calculateurs/cca-cat1
// Pas de login requis. CTA vers AnalyzePage Pro.

const { useState: useCCAS, useEffect: useCCAE, useMemo: useCCAM } = React;

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

  useCCAE(() => {
    window.scrollTo(0, 0);
    const prevTitle = document.title;
    const prevMeta = document.querySelector('meta[name="description"]');
    const prevDesc = prevMeta ? prevMeta.getAttribute('content') : '';
    document.title = FR
      ? 'Calculateur CCA catégorie 1 immobilier Québec — Vestora'
      : 'CCA Class 1 Real Estate Calculator Quebec — Vestora';
    if (prevMeta) {
      prevMeta.setAttribute('content', FR
        ? 'Calculez la déduction pour amortissement (CCA) catégorie 1 de votre immeuble locatif au Québec : tableau annuel, règle de la demi-année, économie d\'impôt. Gratuit, sans inscription.'
        : 'Calculate Class 1 Capital Cost Allowance (CCA) for your Quebec rental property: annual table, half-year rule, tax savings. Free, no login required.');
    }
    return () => {
      document.title = prevTitle;
      if (prevMeta) prevMeta.setAttribute('content', prevDesc);
    };
  }, [FR]);

  const [buildingCost, setBuildingCost] = useCCAS('');
  const [years, setYears] = useCCAS('10');
  const [taxRate, setTaxRate] = useCCAS('47');

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

  const tableData = useCCAM(() => {
    const cost = parseFloat(buildingCost);
    const nbYears = parseInt(years, 10);
    const taux = parseFloat(taxRate) / 100;

    if (!cost || cost <= 0 || !nbYears || nbYears < 1) return null;

    const rows = [];
    let solde = cost;
    let cumulCCA = 0;
    let cumulEconomie = 0;

    for (let y = 1; y <= Math.min(nbYears, 50); y++) {
      let ccaAnnuel;
      let soldeFermeture;

      if (window.fiscalite) {
        const res = window.fiscalite.ccaCategorie1(cost, y, y === 1 ? undefined : solde);
        ccaAnnuel = res.ccaAnnuel;
        soldeFermeture = res.soldeFermeture;
      } else {
        // Fallback local — identique à fiscalite-qc.js
        const CCA_RATE = 0.04;
        if (y === 1) {
          ccaAnnuel = Math.round(cost * CCA_RATE * 0.5);
          soldeFermeture = Math.max(0, cost - ccaAnnuel);
        } else {
          ccaAnnuel = Math.round(solde * CCA_RATE);
          soldeFermeture = Math.max(0, solde - ccaAnnuel);
        }
      }

      const economie = taux > 0 ? Math.round(ccaAnnuel * taux) : 0;
      cumulCCA += ccaAnnuel;
      cumulEconomie += economie;

      rows.push({
        annee: y,
        soldeOuverture: solde,
        ccaAnnuel,
        soldeFermeture,
        economieImpot: economie,
        cumulCCA,
        cumulEconomie,
      });

      solde = soldeFermeture;
    }

    return rows;
  }, [buildingCost, years, taxRate]);

  const totalCCA = tableData ? tableData[tableData.length - 1].cumulCCA : 0;
  const totalEconomie = tableData ? tableData[tableData.length - 1].cumulEconomie : 0;
  const soldeResiduel = tableData ? tableData[tableData.length - 1].soldeFermeture : 0;

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

      <div className="legal-content" style={{ padding: '28px 32px' }}>
        <h1 style={{ fontFamily: 'var(--font-display, Fraunces, serif)', fontSize: 28, marginBottom: 6 }}>
          {FR ? 'Calculateur CCA — Catégorie 1' : 'CCA Calculator — Class 1'}
        </h1>
        <p style={{ color: '#666', margin: '0 0 24px', fontSize: 14 }}>
          {FR
            ? 'Simulez la Déduction pour Amortissement (DPA/CCA) de votre bâtiment résidentiel locatif — catégorie 1, taux 4% dégressif.'
            : 'Simulate the Capital Cost Allowance (CCA) for your residential rental building — Class 1, 4% declining balance.'}
        </p>

        {/* Inputs */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 16, marginBottom: 24 }}>
          <CcaField
            label={FR ? 'Coût du bâtiment ($)' : 'Building cost ($)'}
            hint={FR ? 'Valeur amortissable — excluant le terrain' : 'Depreciable value — excluding land'}
            value={buildingCost} onChange={setBuildingCost} placeholder="ex: 480 000"
          />
          <CcaField
            label={FR ? "Nombre d'années" : 'Number of years'}
            hint={FR ? 'Projection (max 50)' : 'Projection (max 50)'}
            value={years} onChange={setYears} placeholder="10"
            min={1} max={50}
          />
          <CcaField
            label={FR ? "Taux marginal d'impôt (%)" : 'Marginal tax rate (%)'}
            hint={FR ? 'Taux combiné fédéral + Québec, ex: 47%' : 'Combined federal + Quebec rate, e.g. 47%'}
            value={taxRate} onChange={setTaxRate} placeholder="47"
            min={0} max={60} step={0.5}
          />
        </div>

        {/* Résumé */}
        {tableData && (
          <>
            <div style={{
              display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))',
              gap: 12, marginBottom: 20,
            }}>
              <CcaSummaryCard
                label={FR ? `CCA totale sur ${years} ans` : `Total CCA over ${years} years`}
                value={'$' + fmt(totalCCA)}
                color="#1e6f5c"
              />
              <CcaSummaryCard
                label={FR ? "Économie d'impôt totale" : 'Total tax savings'}
                value={'$' + fmt(totalEconomie)}
                color="#2563eb"
              />
              <CcaSummaryCard
                label={FR ? 'Valeur résiduelle (FNACC)' : 'Residual value (UCC)'}
                value={'$' + fmt(soldeResiduel)}
                color="#7c3aed"
              />
            </div>

            {/* Tableau */}
            <div style={{ overflowX: 'auto', borderRadius: 8, border: '1px solid #e0ebe6' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
                <thead>
                  <tr style={{ background: '#f0f7f4' }}>
                    <th style={thStyle}>{FR ? 'Année' : 'Year'}</th>
                    <th style={thStyle}>{FR ? 'FNACC ouverture' : 'Opening UCC'}</th>
                    <th style={thStyle}>{FR ? 'CCA annuelle' : 'Annual CCA'}</th>
                    <th style={thStyle}>{FR ? 'FNACC fermeture' : 'Closing UCC'}</th>
                    <th style={thStyle}>{FR ? "Économie d'impôt" : 'Tax savings'}</th>
                    <th style={thStyle}>{FR ? 'CCA cumulée' : 'Cumul. CCA'}</th>
                  </tr>
                </thead>
                <tbody>
                  {tableData.map((row, i) => (
                    <tr key={row.annee} style={{ background: i % 2 === 0 ? '#fff' : '#fafaf8' }}>
                      <td style={{ ...tdStyle, fontWeight: 600 }}>
                        {row.annee}
                        {row.annee === 1 && (
                          <span style={{ marginLeft: 4, fontSize: 10, color: '#f59e0b', fontWeight: 500 }}>
                            {FR ? '½ an' : '½ yr'}
                          </span>
                        )}
                      </td>
                      <td style={tdStyle}>${fmt(row.soldeOuverture)}</td>
                      <td style={{ ...tdStyle, color: '#1e6f5c', fontWeight: 600 }}>${fmt(row.ccaAnnuel)}</td>
                      <td style={tdStyle}>${fmt(row.soldeFermeture)}</td>
                      <td style={{ ...tdStyle, color: '#2563eb', fontWeight: 500 }}>${fmt(row.economieImpot)}</td>
                      <td style={{ ...tdStyle, color: '#555' }}>${fmt(row.cumulCCA)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </>
        )}

        {/* CTA Pro */}
        <div style={{
          marginTop: 28, padding: '18px 20px', borderRadius: 12,
          background: 'linear-gradient(135deg, #1e3a5f, #1e6f5c)',
          color: '#fff', display: 'flex', alignItems: 'center',
          justifyContent: 'space-between', flexWrap: 'wrap', gap: 12,
        }}>
          <div>
            <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 3 }}>
              {FR ? 'Analyse fiscale complète avec Vestora Pro' : 'Full tax analysis with Vestora Pro'}
            </div>
            <div style={{ fontSize: 13, opacity: 0.85 }}>
              {FR
                ? "CCA intégrée dans l'analyse d'un plex : gain en capital, récupération d'amortissement, IRR, 3 scénarios."
                : 'CCA integrated in a plex analysis: capital gain, recapture, IRR, 3 scenarios.'}
            </div>
          </div>
          <a href="#/tarifs" style={{
            background: '#fff', color: '#1e3a5f', borderRadius: 8,
            padding: '9px 18px', fontWeight: 700, fontSize: 14,
            textDecoration: 'none', whiteSpace: 'nowrap',
          }}>
            {FR ? 'Voir les forfaits →' : 'View plans →'}
          </a>
        </div>
      </div>

      {/* Bloc SEO / éducatif */}
      <div className="legal-content" style={{ marginTop: 20, padding: '28px 32px' }}>
        <h2 style={{ fontSize: 20, marginBottom: 12, fontFamily: 'var(--font-display, Fraunces, serif)' }}>
          {FR ? "CCA catégorie 1 : l'essentiel" : 'CCA Class 1: the essentials'}
        </h2>

        <h3 style={{ fontSize: 15, marginBottom: 8, color: '#1e6f5c' }}>
          {FR ? "Qu'est-ce que la CCA (DPA) ?" : 'What is CCA (Capital Cost Allowance)?'}
        </h3>
        <p>
          {FR
            ? 'La Déduction pour Amortissement (DPA) — Capital Cost Allowance (CCA) en anglais — est une déduction fiscale qui permet aux propriétaires d\'immeubles locatifs de réduire leur revenu imposable chaque année, en tenant compte de la dépréciation économique du bâtiment.'
            : 'Capital Cost Allowance (CCA) is a tax deduction that allows rental property owners to reduce their taxable income each year, accounting for the economic depreciation of the building.'}
        </p>

        <h3 style={{ fontSize: 15, marginBottom: 8, marginTop: 20, color: '#1e6f5c' }}>
          {FR ? 'Catégorie 1 — taux 4% dégressif' : 'Class 1 — 4% declining balance'}
        </h3>
        <p>
          {FR
            ? 'Les bâtiments résidentiels à revenus (4 logements et plus, acquis après 1987) sont généralement en catégorie 1 avec un taux de 4% selon la méthode dégressive. Cela signifie que chaque année, la déduction est calculée sur le solde résiduel (FNACC), et non sur le coût original.'
            : 'Residential rental buildings (4 or more units, acquired after 1987) are generally in Class 1 at a 4% declining balance rate. This means each year, the deduction is calculated on the residual balance (UCC), not on the original cost.'}
        </p>

        <div style={{
          background: '#f7f9f8', border: '1px solid #d0e8e0', borderRadius: 8,
          padding: '12px 16px', fontFamily: 'var(--font-mono, JetBrains Mono, monospace)',
          fontSize: 13, margin: '12px 0',
        }}>
          <div>{FR ? 'Année 1 (règle demi-année) :' : 'Year 1 (half-year rule):'}</div>
          <div style={{ paddingLeft: 16 }}>CCA = Coût × 4% × 50%</div>
          <div style={{ marginTop: 8 }}>{FR ? 'Années suivantes :' : 'Following years:'}</div>
          <div style={{ paddingLeft: 16 }}>CCA = FNACC × 4%</div>
        </div>

        <h3 style={{ fontSize: 15, marginBottom: 8, marginTop: 20, color: '#1e6f5c' }}>
          {FR ? 'Règle de la demi-année' : 'Half-year rule'}
        </h3>
        <p>
          {FR
            ? 'L\'ARC impose la règle de la demi-année (Rule of 50%) la première année : peu importe quand vous avez acquis l\'immeuble, vous ne pouvez déduire que 50% de la CCA normale. Cette règle s\'applique à la catégorie 1.'
            : 'The CRA imposes the half-year rule in the first year: regardless of when you acquired the property, you can only deduct 50% of the normal CCA. This rule applies to Class 1.'}
        </p>

        <h3 style={{ fontSize: 15, marginBottom: 8, marginTop: 20, color: '#1e6f5c' }}>
          {FR ? 'Récupération d\'amortissement à la revente' : 'Recapture at disposition'}
        </h3>
        <p>
          {FR
            ? 'Attention : lors de la revente, si le prix de vente dépasse la FNACC résiduelle, la différence (jusqu\'à concurrence du coût original) est imposée à 100% comme récupération d\'amortissement. C\'est un revenu ordinaire, pas un gain en capital. Planifiez-le !'
            : 'Important: at disposition, if the sale price exceeds the residual UCC, the difference (up to the original cost) is taxed at 100% as recapture. This is ordinary income, not a capital gain. Plan accordingly!'}
        </p>

        <h3 style={{ fontSize: 15, marginBottom: 8, marginTop: 20, color: '#1e6f5c' }}>
          {FR ? 'Plafond de la catégorie 1' : 'Class 1 ceiling'}
        </h3>
        <p>
          {FR
            ? 'La CCA ne peut pas créer une perte locative nette (en vertu des règles sur les biens de location de l\'ARC). Elle peut seulement réduire votre revenu de location à zéro. Les déductions excédentaires sont reportées aux années suivantes.'
            : 'CCA cannot create a net rental loss (under CRA rental property rules). It can only reduce your rental income to zero. Excess deductions are carried forward to future years.'}
        </p>

        <p style={{ marginTop: 20, padding: '12px 16px', background: '#fefce8', borderRadius: 8, fontSize: 13, color: '#555', border: '1px solid #fde68a' }}>
          <strong>{FR ? 'Avertissement fiscal :' : 'Tax disclaimer:'}</strong>{' '}
          {FR
            ? 'Ce calculateur est fourni à titre éducatif uniquement. Les règles fiscales peuvent évoluer. Consultez un comptable (CPA) ou fiscaliste avant de prendre des décisions basées sur ces calculs.'
            : 'This calculator is provided for educational purposes only. Tax rules may change. Consult a CPA or tax specialist before making decisions based on these calculations.'}
        </p>
      </div>

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

const thStyle = {
  padding: '10px 12px', textAlign: 'right', fontWeight: 600, fontSize: 12,
  color: '#444', borderBottom: '1px solid #d0e8e0', whiteSpace: 'nowrap',
};
const tdStyle = {
  padding: '8px 12px', textAlign: 'right', borderBottom: '1px solid #f0f0ee',
  fontFamily: 'var(--font-mono, JetBrains Mono, monospace)', fontSize: 13,
};

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

function CcaSummaryCard({ label, value, color }) {
  return (
    <div style={{
      padding: '14px 16px', borderRadius: 10,
      background: '#f7f9f8', border: `1.5px solid ${color}22`,
    }}>
      <div style={{ fontSize: 11, color: '#888', marginBottom: 4 }}>{label}</div>
      <div style={{ fontSize: 20, fontWeight: 700, color, fontFamily: 'var(--font-body)' }}>{value}</div>
    </div>
  );
}

window.CcaCalcPage = CcaCalcPage;
