/* ============ Financial calculators ============ */
const { useState: uS } = React;

function CRow({ label, sub, children }) {
  return <div className="fs-row"><label>{label}{sub ? <small>{sub}</small> : null}</label>{children}</div>;
}
function ResultPanel({ label, big, bigColor, rows, kpis }) {
  return (
    <div>
      <div className="fin-result">
        <div className="big-lbl">{label}</div>
        <div className="big-num" style={bigColor ? { color: bigColor } : null}>{big}</div>
        {rows ? (
          <div className="fin-breakdown">
            {rows.map((r, i) => <div className={'fb' + (r.total ? ' total' : '')} key={i}><span className="fl">{r.l}</span><span className="fv">{r.v}</span></div>)}
          </div>
        ) : null}
      </div>
      {kpis ? (
        <div className="kpi-strip" style={{ gridTemplateColumns: 'repeat(' + Math.min(kpis.length, 3) + ', 1fr)' }}>
          {kpis.map((k, i) => <div className={'kpi' + (k.accent ? ' accent' : '')} key={i}><div className="l">{k.l}</div><div className={'v' + (k.neg ? ' neg' : '')}>{k.v}</div>{k.hint ? <div className="hint">{k.hint}</div> : null}</div>)}
        </div>
      ) : null}
    </div>
  );
}
function CalcShell({ title, desc, children }) {
  return (
    <div className="card">
      <div className="card-head"><h3>{title}</h3></div>
      <div className="card-body">
        {desc ? <div style={{ fontSize: 12.5, color: 'var(--muted)', lineHeight: 1.5, marginBottom: 10 }}>{desc}</div> : null}
        <div className="field-stack">{children}</div>
      </div>
    </div>
  );
}

/* 1. BRRRR */
function BRRRR({ deal, calc }) {
  const [s, set] = uS({ purchase: deal.terms.acceptedPrice, rehab: calc.rehabTotal, arv: deal.terms.sellingPrice, ltv: 75, rate: 7.5, term: 30, rent: deal.capRate.monthlyRent, opex: 35, closing: Math.round(deal.terms.acceptedPrice * 0.03) });
  const u = (k, v) => set((p) => ({ ...p, [k]: v }));
  const allIn = s.purchase + s.rehab + s.closing;
  const refiLoan = s.arv * s.ltv / 100;
  const pay = monthlyPayment(refiLoan, s.rate, s.term);
  const cashLeft = allIn - refiLoan;
  const cashFlow = s.rent - s.rent * s.opex / 100 - pay;
  const coc = cashLeft > 0 ? (cashFlow * 12 / cashLeft) * 100 : Infinity;
  const equity = s.arv - refiLoan;
  return (
    <React.Fragment>
      <CalcShell title="BRRRR Inputs" desc="Buy, Rehab, Rent, Refinance, Repeat — how much capital you recover and the cash flow that remains.">
        <CRow label="Purchase price"><MoneyInput value={s.purchase} onChange={(v) => u('purchase', v)} /></CRow>
        <CRow label="Rehab budget"><MoneyInput value={s.rehab} onChange={(v) => u('rehab', v)} /></CRow>
        <CRow label="Buy closing costs"><MoneyInput value={s.closing} onChange={(v) => u('closing', v)} /></CRow>
        <CRow label="After repair value"><MoneyInput value={s.arv} onChange={(v) => u('arv', v)} /></CRow>
        <CRow label="Refinance LTV"><NumInput value={s.ltv} onChange={(v) => u('ltv', v || 0)} suffix="%" /></CRow>
        <CRow label="Refi rate"><NumInput value={s.rate} onChange={(v) => u('rate', v || 0)} suffix="%" /></CRow>
        <CRow label="Refi term"><NumInput value={s.term} onChange={(v) => u('term', v || 0)} suffix="yr" /></CRow>
        <CRow label="Monthly rent"><MoneyInput value={s.rent} onChange={(v) => u('rent', v)} /></CRow>
        <CRow label="Operating expenses"><NumInput value={s.opex} onChange={(v) => u('opex', v || 0)} suffix="% rent" /></CRow>
      </CalcShell>
      <ResultPanel label="Monthly Cash Flow After Refi" big={fmtMoney(cashFlow)} bigColor={cashFlow < 0 ? 'var(--coral-soft)' : null}
        rows={[
          { l: 'Total invested (all-in)', v: fmtMoney(allIn) },
          { l: 'Refinance loan (' + s.ltv + '% ARV)', v: fmtMoney(refiLoan) },
          { l: 'New monthly payment', v: fmtMoney(pay) },
          { l: cashLeft >= 0 ? 'Cash left in deal' : 'Cash pulled out', v: fmtMoney(Math.abs(cashLeft)), total: true },
        ]}
        kpis={[
          { l: 'Cash Left In', v: cashLeft <= 0 ? '$0 ✓' : fmtMoney(cashLeft), accent: true, hint: cashLeft <= 0 ? 'Full BRRRR — capital recovered' : 'Capital still tied up' },
          { l: 'Cash-on-Cash', v: isFinite(coc) ? fmtPct(coc) : '∞', hint: 'Annual CF ÷ cash left', neg: coc < 0 },
          { l: 'Equity Captured', v: fmtMoney(equity), hint: 'ARV − refi loan' },
        ]} />
    </React.Fragment>
  );
}

/* 2. Wholesale */
function Wholesale({ deal, calc }) {
  const [s, set] = uS({ arv: deal.terms.sellingPrice, rehab: calc.rehabTotal, contract: deal.terms.acceptedPrice, fee: 12000 });
  const u = (k, v) => set((p) => ({ ...p, [k]: v }));
  const buyerMao = s.arv * 0.7 - s.rehab;
  const buyerPays = s.contract + s.fee;
  const buyerAllIn = buyerPays + s.rehab;
  const buyerMargin = s.arv - buyerAllIn;
  const buyerUnder = buyerPays <= buyerMao;
  return (
    <React.Fragment>
      <CalcShell title="Wholesale / Assignment" desc="Lock a contract, assign it to an end buyer for a fee. Check the buyer still has room under the 70% rule.">
        <CRow label="After repair value"><MoneyInput value={s.arv} onChange={(v) => u('arv', v)} /></CRow>
        <CRow label="Estimated rehab"><MoneyInput value={s.rehab} onChange={(v) => u('rehab', v)} /></CRow>
        <CRow label="Your contract price"><MoneyInput value={s.contract} onChange={(v) => u('contract', v)} /></CRow>
        <CRow label="Assignment fee"><MoneyInput value={s.fee} onChange={(v) => u('fee', v)} /></CRow>
      </CalcShell>
      <ResultPanel label="Your Assignment Fee" big={fmtMoney(s.fee)} bigColor="var(--sage)"
        rows={[
          { l: 'Buyer pays (contract + fee)', v: fmtMoney(buyerPays) },
          { l: "Buyer's all-in (+ rehab)", v: fmtMoney(buyerAllIn) },
          { l: "Buyer's projected margin", v: fmtMoney(buyerMargin) },
          { l: '70% rule max for buyer', v: fmtMoney(buyerMao), total: true },
        ]}
        kpis={[
          { l: 'Buyer Under 70%?', v: buyerUnder ? 'Yes ✓' : 'No', accent: buyerUnder, neg: !buyerUnder, hint: buyerUnder ? 'Attractive to buyers' : 'Lower contract or fee' },
          { l: 'Spread to Buyer MAO', v: fmtMoney(buyerMao - buyerPays), hint: 'Room above your price', neg: (buyerMao - buyerPays) < 0 },
          { l: "Buyer Margin", v: fmtPct(s.arv ? buyerMargin / s.arv * 100 : 0), hint: 'Of ARV' },
        ]} />
    </React.Fragment>
  );
}

/* 3. Subject-To */
function SubjectTo({ deal, calc }) {
  const [s, set] = uS({ price: deal.terms.acceptedPrice, balance: Math.round(deal.terms.acceptedPrice * 0.8), rate: 4.5, payment: 1850, cashToSeller: 10000, closing: 3000, arv: deal.terms.sellingPrice });
  const u = (k, v) => set((p) => ({ ...p, [k]: v }));
  const entry = s.cashToSeller + s.closing;
  const equity = s.arv - s.balance;
  return (
    <React.Fragment>
      <CalcShell title="Subject-To" desc="Take title subject to the seller's existing mortgage staying in place. Your entry cost is mostly cash to seller + closing.">
        <CRow label="Purchase price"><MoneyInput value={s.price} onChange={(v) => u('price', v)} /></CRow>
        <CRow label="Existing loan balance"><MoneyInput value={s.balance} onChange={(v) => u('balance', v)} /></CRow>
        <CRow label="Existing rate"><NumInput value={s.rate} onChange={(v) => u('rate', v || 0)} suffix="%" /></CRow>
        <CRow label="Existing monthly payment"><MoneyInput value={s.payment} onChange={(v) => u('payment', v)} /></CRow>
        <CRow label="Cash to seller"><MoneyInput value={s.cashToSeller} onChange={(v) => u('cashToSeller', v)} /></CRow>
        <CRow label="Closing costs"><MoneyInput value={s.closing} onChange={(v) => u('closing', v)} /></CRow>
        <CRow label="After repair value"><MoneyInput value={s.arv} onChange={(v) => u('arv', v)} /></CRow>
      </CalcShell>
      <ResultPanel label="Cash to Control Property" big={fmtMoney(entry)}
        rows={[
          { l: 'Loan assumed (subject-to)', v: fmtMoney(s.balance) },
          { l: 'Existing payment (taken over)', v: fmtMoney(s.payment) + '/mo' },
          { l: 'Cash to seller + closing', v: fmtMoney(entry) },
          { l: 'Equity captured (ARV − loan)', v: fmtMoney(equity), total: true },
        ]}
        kpis={[
          { l: 'Entry Cost', v: fmtMoney(entry), accent: true, hint: 'Vs full down payment' },
          { l: 'Instant Equity', v: fmtMoney(equity), hint: 'ARV − assumed loan', neg: equity < 0 },
          { l: 'Rate Assumed', v: fmtPct(s.rate), hint: 'Often below market' },
        ]} />
    </React.Fragment>
  );
}

/* 4. Private Money */
function PrivateMoney({ deal }) {
  const [s, set] = uS({ loan: deal.terms.acceptedPrice, rate: 10, term: 12, points: 2, structure: 'Interest-only' });
  const u = (k, v) => set((p) => ({ ...p, [k]: v }));
  const monthlyInterest = s.loan * s.rate / 100 / 12;
  const pointsCost = s.loan * s.points / 100;
  const totalInterest = monthlyInterest * s.term;
  const totalCost = pointsCost + totalInterest;
  const payoff = s.loan + (s.structure === 'Accrued' ? totalInterest : 0);
  return (
    <React.Fragment>
      <CalcShell title="Private Money" desc="Model a private/relationship loan — points up front plus interest over the term.">
        <CRow label="Loan amount"><MoneyInput value={s.loan} onChange={(v) => u('loan', v)} /></CRow>
        <CRow label="Interest rate"><NumInput value={s.rate} onChange={(v) => u('rate', v || 0)} suffix="%" /></CRow>
        <CRow label="Term"><NumInput value={s.term} onChange={(v) => u('term', v || 0)} suffix="mo" /></CRow>
        <CRow label="Points"><NumInput value={s.points} onChange={(v) => u('points', v || 0)} suffix="pts" /></CRow>
        <CRow label="Structure">
          <select className="in" style={{ width: 150 }} value={s.structure} onChange={(e) => u('structure', e.target.value)}><option>Interest-only</option><option>Accrued</option></select>
        </CRow>
      </CalcShell>
      <ResultPanel label="Total Cost of Capital" big={fmtMoney(totalCost)} bigColor="var(--coral-soft)"
        rows={[
          { l: 'Points (' + s.points + ')', v: fmtMoney(pointsCost) },
          { l: 'Monthly interest', v: fmtMoney(monthlyInterest) },
          { l: 'Total interest (' + s.term + ' mo)', v: fmtMoney(totalInterest) },
          { l: 'Payoff at term', v: fmtMoney(payoff), total: true },
        ]}
        kpis={[
          { l: 'Monthly Payment', v: s.structure === 'Interest-only' ? fmtMoney(monthlyInterest) : '$0', accent: true, hint: s.structure === 'Interest-only' ? 'Interest-only' : 'Accrues to payoff' },
          { l: 'Effective Cost', v: fmtPct(s.loan ? totalCost / s.loan * 100 : 0), hint: 'Total cost ÷ loan' },
          { l: 'Points Cost', v: fmtMoney(pointsCost), hint: 'Due at closing' },
        ]} />
    </React.Fragment>
  );
}

/* 5. Profit Split (JV) */
function ProfitSplit({ deal, calc }) {
  const [s, set] = uS({ netProfit: Math.round(calc.netProfit), partnerCapital: Math.round(calc.allInCost), prefRate: 8, holdMonths: deal.terms.holdingMonths, splitPartner: 50 });
  const u = (k, v) => set((p) => ({ ...p, [k]: v }));
  const pref = s.partnerCapital * s.prefRate / 100 * (s.holdMonths / 12);
  const remaining = s.netProfit - pref;
  const partnerSplit = remaining > 0 ? remaining * s.splitPartner / 100 : remaining;
  const partnerTotal = pref + partnerSplit;
  const yourTotal = s.netProfit - partnerTotal;
  return (
    <React.Fragment>
      <CalcShell title="JV Profit Split" desc="Split deal profit with a capital partner — preferred return first, then a split of the remainder.">
        <CRow label="Net profit"><MoneyInput value={s.netProfit} onChange={(v) => u('netProfit', v)} /></CRow>
        <CRow label="Partner capital"><MoneyInput value={s.partnerCapital} onChange={(v) => u('partnerCapital', v)} /></CRow>
        <CRow label="Preferred return" sub="Annualized on capital"><NumInput value={s.prefRate} onChange={(v) => u('prefRate', v || 0)} suffix="%" /></CRow>
        <CRow label="Hold period"><NumInput value={s.holdMonths} onChange={(v) => u('holdMonths', v || 0)} suffix="mo" /></CRow>
        <CRow label="Split to partner" sub="After pref"><NumInput value={s.splitPartner} onChange={(v) => u('splitPartner', v || 0)} suffix="%" /></CRow>
      </CalcShell>
      <ResultPanel label="Your Share" big={fmtMoney(yourTotal)} bigColor={yourTotal < 0 ? 'var(--coral-soft)' : 'var(--sage)'}
        rows={[
          { l: 'Preferred return to partner', v: fmtMoney(pref) },
          { l: 'Remaining profit', v: fmtMoney(remaining) },
          { l: 'Partner split (' + s.splitPartner + '%)', v: fmtMoney(partnerSplit) },
          { l: 'Partner total', v: fmtMoney(partnerTotal), total: true },
        ]}
        kpis={[
          { l: 'Your Take', v: fmtMoney(yourTotal), accent: true, hint: fmtPct(s.netProfit ? yourTotal / s.netProfit * 100 : 0) + ' of profit' },
          { l: 'Partner Take', v: fmtMoney(partnerTotal), hint: fmtPct(s.netProfit ? partnerTotal / s.netProfit * 100 : 0) + ' of profit' },
          { l: 'Partner Return', v: fmtPct(s.partnerCapital ? partnerTotal / s.partnerCapital * 100 : 0), hint: 'On their capital' },
        ]} />
    </React.Fragment>
  );
}

/* 6. IRR / NPV */
function IRRNPV({ deal, calc }) {
  const [s, set] = uS({ initial: Math.round(calc.allInCost), exit: Math.round(calc.netSalePrice), months: deal.terms.holdingMonths, discount: 10 });
  const u = (k, v) => set((p) => ({ ...p, [k]: v }));
  const n = Math.max(1, Math.round(s.months));
  const flows = [-s.initial, ...Array(n - 1).fill(0), s.exit];
  const mIrr = irr(flows);
  const annualIrr = isFinite(mIrr) ? (Math.pow(1 + mIrr, 12) - 1) * 100 : NaN;
  const mDisc = s.discount / 100 / 12;
  const npvVal = npv(mDisc, flows);
  const profit = s.exit - s.initial;
  const equityMult = s.initial ? s.exit / s.initial : 0;
  return (
    <React.Fragment>
      <CalcShell title="IRR / NPV" desc="Time-value return on a flip: cash out now, proceeds at sale. IRR is annualized.">
        <CRow label="Initial investment" sub="All-in cash"><MoneyInput value={s.initial} onChange={(v) => u('initial', v)} /></CRow>
        <CRow label="Exit proceeds" sub="Net sale price"><MoneyInput value={s.exit} onChange={(v) => u('exit', v)} /></CRow>
        <CRow label="Hold period"><NumInput value={s.months} onChange={(v) => u('months', v || 1)} suffix="mo" /></CRow>
        <CRow label="Discount rate" sub="For NPV"><NumInput value={s.discount} onChange={(v) => u('discount', v || 0)} suffix="%" /></CRow>
      </CalcShell>
      <ResultPanel label="Annualized IRR" big={isFinite(annualIrr) ? fmtPct(annualIrr) : '—'} bigColor={annualIrr < 0 ? 'var(--coral-soft)' : 'var(--sage)'}
        rows={[
          { l: 'Profit', v: fmtMoney(profit) },
          { l: 'Equity multiple', v: equityMult.toFixed(2) + '×' },
          { l: 'NPV @ ' + s.discount + '%', v: fmtMoney(npvVal) },
          { l: 'Hold', v: n + ' months', total: true },
        ]}
        kpis={[
          { l: 'Annual IRR', v: isFinite(annualIrr) ? fmtPct(annualIrr) : '—', accent: true, neg: annualIrr < 0, hint: 'Time-weighted return' },
          { l: 'NPV', v: fmtMoney(npvVal), neg: npvVal < 0, hint: npvVal >= 0 ? 'Beats discount rate' : 'Below hurdle' },
          { l: 'Equity Multiple', v: equityMult.toFixed(2) + '×', hint: 'Exit ÷ invested' },
        ]} />
    </React.Fragment>
  );
}

/* 7. 1031 Exchange */
function Exchange1031({ deal, calc }) {
  const [s, set] = uS({ sale: deal.terms.sellingPrice, basis: Math.round(deal.terms.acceptedPrice + calc.rehabTotal), costs: Math.round(calc.sellingFeesSum), fed: 20, state: 5, recapture: 0 });
  const u = (k, v) => set((p) => ({ ...p, [k]: v }));
  const gain = Math.max(0, s.sale - s.costs - s.basis);
  const fedTax = gain * s.fed / 100;
  const stateTax = gain * s.state / 100;
  const recaptureTax = s.recapture * 0.25;
  const deferred = fedTax + stateTax + recaptureTax;
  const reinvest = s.sale - s.costs;
  return (
    <React.Fragment>
      <CalcShell title="1031 Exchange" desc="Estimate the tax you defer by exchanging into a like-kind property instead of cashing out.">
        <CRow label="Sale price"><MoneyInput value={s.sale} onChange={(v) => u('sale', v)} /></CRow>
        <CRow label="Adjusted basis" sub="Purchase + improvements"><MoneyInput value={s.basis} onChange={(v) => u('basis', v)} /></CRow>
        <CRow label="Selling costs"><MoneyInput value={s.costs} onChange={(v) => u('costs', v)} /></CRow>
        <CRow label="Federal cap-gains rate"><NumInput value={s.fed} onChange={(v) => u('fed', v || 0)} suffix="%" /></CRow>
        <CRow label="State tax rate"><NumInput value={s.state} onChange={(v) => u('state', v || 0)} suffix="%" /></CRow>
        <CRow label="Depreciation to recapture"><MoneyInput value={s.recapture} onChange={(v) => u('recapture', v)} /></CRow>
      </CalcShell>
      <ResultPanel label="Tax Deferred" big={fmtMoney(deferred)} bigColor="var(--sage)"
        rows={[
          { l: 'Capital gain', v: fmtMoney(gain) },
          { l: 'Federal tax (' + s.fed + '%)', v: fmtMoney(fedTax) },
          { l: 'State tax (' + s.state + '%)', v: fmtMoney(stateTax) },
          { l: 'Depreciation recapture (25%)', v: fmtMoney(recaptureTax) },
        ]}
        kpis={[
          { l: 'Total Deferred', v: fmtMoney(deferred), accent: true, hint: 'Kept working for you' },
          { l: 'Min Reinvestment', v: fmtMoney(reinvest), hint: 'To fully defer' },
          { l: 'Capital Gain', v: fmtMoney(gain), hint: 'Sale − basis − costs' },
        ]} />
    </React.Fragment>
  );
}

/* 8. Depreciation / tax benefit */
function Depreciation({ deal }) {
  const [s, set] = uS({ value: deal.terms.acceptedPrice, landPct: 20, life: 27.5, taxRate: 24 });
  const u = (k, v) => set((p) => ({ ...p, [k]: v }));
  const building = s.value * (1 - s.landPct / 100);
  const annualDep = s.life ? building / s.life : 0;
  const annualSavings = annualDep * s.taxRate / 100;
  return (
    <React.Fragment>
      <CalcShell title="Depreciation Tax Benefit" desc="Annual paper loss that shelters rental income (buy-&-hold). Residential = 27.5 yr, commercial = 39 yr.">
        <CRow label="Property value"><MoneyInput value={s.value} onChange={(v) => u('value', v)} /></CRow>
        <CRow label="Land portion" sub="Not depreciable"><NumInput value={s.landPct} onChange={(v) => u('landPct', v || 0)} suffix="%" /></CRow>
        <CRow label="Useful life"><NumInput value={s.life} onChange={(v) => u('life', v || 1)} suffix="yr" /></CRow>
        <CRow label="Marginal tax rate"><NumInput value={s.taxRate} onChange={(v) => u('taxRate', v || 0)} suffix="%" /></CRow>
      </CalcShell>
      <ResultPanel label="Annual Tax Savings" big={fmtMoney(annualSavings)} bigColor="var(--sage)"
        rows={[
          { l: 'Depreciable building basis', v: fmtMoney(building) },
          { l: 'Annual depreciation', v: fmtMoney(annualDep) },
          { l: 'Monthly tax savings', v: fmtMoney(annualSavings / 12) },
          { l: 'Savings over ' + Math.round(s.life) + ' yr', v: fmtMoney(annualSavings * s.life), total: true },
        ]}
        kpis={[
          { l: 'Annual Savings', v: fmtMoney(annualSavings), accent: true, hint: 'At ' + s.taxRate + '% bracket' },
          { l: 'Annual Depreciation', v: fmtMoney(annualDep), hint: 'Paper expense' },
          { l: 'Total Shelter', v: fmtMoney(annualSavings * s.life), hint: 'Full schedule' },
        ]} />
    </React.Fragment>
  );
}

/* 9. Equity tracker (hold scenario) */
function EquityTracker({ deal }) {
  const [s, set] = uS({ value: deal.terms.sellingPrice, loan: Math.round(deal.terms.acceptedPrice * 0.8), rate: deal.mortgage.rate, term: 30, apprec: 3, years: 10 });
  const u = (k, v) => set((p) => ({ ...p, [k]: v }));
  const sched = amortize(s.loan, s.rate, s.term);
  const yearly = groupByYear(sched.rows);
  const balAt = (y) => y === 0 ? s.loan : (yearly[y - 1] ? yearly[y - 1].bal : 0);
  const rows = [1, 3, 5, 10, 15, 20, 30].filter((y) => y <= s.term);
  const projValue = (y) => s.value * Math.pow(1 + s.apprec / 100, y);
  const equityAt = (y) => projValue(y) - balAt(y);
  return (
    <React.Fragment>
        <div className="card">
          <div className="card-head"><h3>Equity Tracker</h3></div>
          <div className="card-body">
            <div style={{ fontSize: 12.5, color: 'var(--muted)', lineHeight: 1.5, marginBottom: 10 }}>If you hold instead of flip: equity grows from appreciation plus loan paydown.</div>
            <div className="field-stack">
              <CRow label="Current value"><MoneyInput value={s.value} onChange={(v) => u('value', v)} /></CRow>
              <CRow label="Loan balance"><MoneyInput value={s.loan} onChange={(v) => u('loan', v)} /></CRow>
              <CRow label="Mortgage rate"><NumInput value={s.rate} onChange={(v) => u('rate', v || 0)} suffix="%" /></CRow>
              <CRow label="Loan term"><NumInput value={s.term} onChange={(v) => u('term', v || 0)} suffix="yr" /></CRow>
              <CRow label="Appreciation"><NumInput value={s.apprec} onChange={(v) => u('apprec', v || 0)} suffix="%/yr" /></CRow>
              <CRow label="Hold horizon"><NumInput value={s.years} onChange={(v) => u('years', v || 0)} suffix="yr" /></CRow>
            </div>
          </div>
        </div>
        <div>
          <ResultPanel label={'Projected Equity in ' + s.years + ' yr'} big={fmtMoney(equityAt(s.years))} bigColor="var(--sage)"
            rows={[
              { l: 'Projected value', v: fmtMoney(projValue(s.years)) },
              { l: 'Loan balance', v: fmtMoney(balAt(s.years)) },
              { l: 'Equity gain vs today', v: fmtMoney(equityAt(s.years) - (s.value - s.loan)), total: true },
            ]} />
          <div className="card" style={{ marginTop: 14 }}>
            <div className="card-body" style={{ padding: 0 }}>
              <table className="cmp-tbl"><thead><tr><th>Year</th><th>Value</th><th>Balance</th><th>Equity</th></tr></thead>
                <tbody>{rows.map((y) => <tr key={y}><td>Year {y}</td><td>{fmtMoney(projValue(y))}</td><td>{fmtMoney(balAt(y))}</td><td className="good-c">{fmtMoney(equityAt(y))}</td></tr>)}</tbody>
              </table>
            </div>
          </div>
        </div>
    </React.Fragment>
  );
}

const CALCS = [
  { id: 'brrrr', label: 'BRRRR', C: BRRRR },
  { id: 'wholesale', label: 'Wholesale', C: Wholesale },
  { id: 'subto', label: 'Subject-To', C: SubjectTo },
  { id: 'private', label: 'Private Money', C: PrivateMoney },
  { id: 'split', label: 'Profit Split', C: ProfitSplit },
  { id: 'irr', label: 'IRR / NPV', C: IRRNPV },
  { id: '1031', label: '1031 Exchange', C: Exchange1031 },
  { id: 'depr', label: 'Depreciation', C: Depreciation },
  { id: 'equity', label: 'Equity Tracker', C: EquityTracker },
];

function CalculatorsTab({ deal, calc, update }) {
  const [sub, setSub] = uS('brrrr');
  const Active = (CALCS.find((c) => c.id === sub) || CALCS[0]).C;
  return (
    <div>
      <div className="comps-head" style={{ marginBottom: 12 }}>
        <div>
          <h2 className="tab-title">Investment Calculators</h2>
          <div className="tab-desc">Strategy tools seeded from your current deal — adjust freely without changing the deal.</div>
        </div>
      </div>
      <div className="calc-nav">
        {CALCS.map((c) => <button key={c.id} className={'calc-pill' + (sub === c.id ? ' on' : '')} onClick={() => setSub(c.id)}>{c.label}</button>)}
      </div>
      <div className="fin-wrap"><Active deal={deal} calc={calc} update={update} /></div>
    </div>
  );
}

window.CalculatorsTab = CalculatorsTab;
