// verify-the-minimum-that-never-ends.mjs — the mechanism behind the stratum
// "The Minimum That Never Ends" (/strata/the-minimum-that-never-ends/).
//
// The claim the page makes:
//   A credit-card minimum payment that is a flat PERCENTAGE p of the balance is a
//   geometric process. Each month the balance becomes
//
//        B_next = B + r·B − p·B = B·(1 + r − p)
//
//   where r = APR/12 is the monthly periodic rate, interest accrues at r·B, and the
//   minimum payment is p·B of the (pre-interest) balance. Therefore after n months
//
//        B_n = B_0 · (1 + r − p)^n.
//
//   • If r < p   the factor (1+r−p) < 1: the balance DECAYS geometrically toward zero
//                 but is strictly positive for every finite n — it never reaches zero.
//   • If r = p   the factor = 1 exactly: the balance is FROZEN forever (interest exactly
//                 equals the payment). With p = 2%, this knife-edge is APR = 24%.
//   • If r > p   the factor > 1: the balance GROWS — the "minimum" doesn't even cover
//                 interest (negative amortization).
//
//   So the pure-percentage rule, on its own, NEVER pays a card off in finite time.
//   What actually ends a real loan is the fixed-dollar FLOOR (commonly $25–$35): once
//   p·B drops below the floor F, the payment is the constant F, which DOES exceed the
//   interest and drives the balance to zero in finite time. The number of remaining
//   months once a constant payment F applies to a balance B (with F > r·B) is the
//   standard amortization identity
//
//        N = −ln(1 − B·r/F) / ln(1 + r).
//
//   The Credit CARD Act of 2009 (Regulation Z, 12 CFR 1026.7(b)(12)) mandates that
//   every US statement print exactly the numbers this page computes: the minimum-only
//   payoff time, its total cost, and the 36-month comparison.
//
//   run:  node research/the-minimum-that-never-ends/verify-the-minimum-that-never-ends.mjs
//
// No dependencies. Every number the page displays is recomputed here, the same way.

let fails = 0;
const ok = (name, cond, extra = '') => {
  if (!cond) fails++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
};
const approx = (a, b, eps) => Math.abs(a - b) <= eps;

// ── the ledger: month-by-month, identical to the page's engine ───────────────
// minimum = max(p·B, floor), capped so we never pay more than is owed.
// interest = r·B added each month; payment subtracted.  Returns the full record.
function runLedger(B0, apr, p, floor, cap = 5_000_000) {
  const r = apr / 12;
  let B = B0, months = 0, totalInterest = 0, totalPaid = 0;
  let floorBindsMonth = null;        // first month the floor (not the %) sets the payment
  while (B > 0.005 && months < cap) {
    const interest = B * r;
    const minByPct = p * B;
    let pay = Math.max(minByPct, floor);
    pay = Math.min(pay, B + interest);          // last payment is partial
    if (floorBindsMonth === null && minByPct <= floor) floorBindsMonth = months + 1;
    B = B + interest - pay;
    totalInterest += interest;
    totalPaid += pay;
    months += 1;
  }
  return { months, totalInterest, totalPaid, floorBindsMonth, finalBalance: B, hitCap: months >= cap };
}

// closed form: months to clear balance B at a CONSTANT payment F (needs F > r·B)
function fixedPayoffMonths(B, r, F) {
  if (F <= B * r) return Infinity;
  return -Math.log(1 - (B * r) / F) / Math.log(1 + r);
}
// standard amortization payment to clear B in exactly N months at monthly rate r
function paymentForMonths(B, r, N) {
  return (B * r) / (1 - Math.pow(1 + r, -N));
}

// ── 1. The geometric mechanism: decay / frozen / grow at p = 2% ──────────────
console.log('\n— the pure-percentage rule is geometric: B_n = B_0·(1 + r − p)^n —');
const p = 0.02;
const cases = [
  { apr: 0.18, kind: 'decays' },
  { apr: 0.21, kind: 'decays' },
  { apr: 0.24, kind: 'frozen' },   // knife-edge: monthly r = 2% = p
  { apr: 0.27, kind: 'grows'  },
];
for (const c of cases) {
  const r = c.apr / 12;
  const factor = 1 + r - p;
  const kind = factor < 1 - 1e-12 ? 'decays' : (factor > 1 + 1e-12 ? 'grows' : 'frozen');
  console.log(`  APR ${(c.apr * 100).toFixed(0)}%  →  monthly r = ${(r * 100).toFixed(3)}%  →  factor = ${factor.toFixed(6)}  (${kind})`);
  ok(`APR ${(c.apr * 100).toFixed(0)}% pure-% behaviour is "${c.kind}"`, kind === c.kind, `factor ${factor.toFixed(6)}`);
}
// the knife-edge value: with p = 2%, the frozen-forever APR is exactly 24%
ok('with a 2% minimum, the "frozen forever" APR is exactly 24% (r = p = 2%/mo)',
   approx(0.24 / 12, p, 1e-15), `r = ${(0.24 / 12 * 100).toFixed(3)}% = p`);

// ── 2. "Never reaches zero": geometric decay stays strictly positive ─────────
console.log('\n— pure percentage, no floor: the balance approaches zero but never reaches it —');
{
  const apr = 0.21, r = apr / 12, factor = 1 + r - p, B0 = 3000;
  const after = (n) => B0 * Math.pow(factor, n);
  console.log(`  $${B0} at 21% APR, 2% min, NO floor: factor = ${factor.toFixed(6)}`);
  for (const n of [12, 120, 600, 6000]) {
    console.log(`    after ${String(n).padStart(4)} months: $${after(n).toFixed(2)}  (> 0)`);
  }
  ok('balance is strictly positive at every finite month (never exactly zero)',
     after(12) > 0 && after(600) > 0 && after(60000) > 0, `B(60000mo) = $${after(60000).toExponential(2)}`);
  // strictly decreasing toward 0 as a limit
  ok('balance is strictly decreasing month over month (decay case)', after(12) > after(13) && after(13) > 0);
  ok('limit of B_n as n→∞ is 0 (factor < 1)', factor < 1 && after(100000) < 1e-6);
}
// the frozen case: at exactly 24% APR the pure-% balance never changes at all
{
  const r = 0.24 / 12, B0 = 3000;
  const led = runLedger(B0, 0.24, p, 0 /* no floor */, 100000);
  console.log(`  $${B0} at 24% APR, 2% min, NO floor: hits the ${100000}-month cap, balance unchanged at $${led.finalBalance.toFixed(2)}`);
  ok('at 24% APR with no floor the loan never terminates (hits the cap, balance frozen)',
     led.hitCap && approx(led.finalBalance, B0, 1e-6), `final $${led.finalBalance.toFixed(2)}`);
}

// ── 3. The headline worked example: $1,000 at 21% APR, 2%-or-$25 floor ───────
console.log('\n— headline: $1,000 at 21% APR, minimum = 2% or $25 (whichever is greater) —');
const led1 = runLedger(1000, 0.21, 0.02, 25);
console.log(`  months to payoff      = ${led1.months}`);
console.log(`  total interest paid   = $${led1.totalInterest.toFixed(2)}`);
console.log(`  total amount paid     = $${led1.totalPaid.toFixed(2)}`);
console.log(`  floor binds at month  = ${led1.floorBindsMonth}`);
ok('payoff takes 70 months', led1.months === 70, `${led1.months} months`);
ok('total interest ≈ $735.02', approx(led1.totalInterest, 735.02, 0.01), `$${led1.totalInterest.toFixed(2)}`);
ok('total paid ≈ $1,735.02', approx(led1.totalPaid, 1735.02, 0.01), `$${led1.totalPaid.toFixed(2)}`);
// because 2% of $1,000 = $20 < $25, the $25 floor binds from the very first month:
ok('the $25 floor binds from month 1 (2% of $1,000 = $20 < $25)', led1.floorBindsMonth === 1,
   `binds month ${led1.floorBindsMonth}`);

// closed form must agree: with the floor binding immediately, the whole loan is a
// constant $25 payment, so N = −ln(1 − B·r/F)/ln(1+r), rounded UP to a whole month.
{
  const r = 0.21 / 12;
  const N = fixedPayoffMonths(1000, r, 25);
  console.log(`  closed form (constant $25): N = ${N.toFixed(3)} → ⌈N⌉ = ${Math.ceil(N)} months`);
  ok('closed-form fixed-$25 payoff rounds up to the ledger\'s 70 months',
     Math.ceil(N) === led1.months, `N = ${N.toFixed(3)}`);
}

// ── 4. The CARD Act statement box: 36-month comparison ──────────────────────
console.log('\n— the CARD Act box: minimum-only vs. a 3-year payoff ($1,000 @ 21%) —');
{
  const r = 0.21 / 12;
  const minOnlyTotal = led1.totalPaid;             // $1,735.02
  const pay36 = paymentForMonths(1000, r, 36);     // level payment to clear in 36 months
  const total36 = pay36 * 36;
  const interest36 = total36 - 1000;
  const savings = minOnlyTotal - total36;
  console.log(`  minimum-only:  ${led1.months} months, total $${minOnlyTotal.toFixed(2)} (interest $${led1.totalInterest.toFixed(2)})`);
  console.log(`  3-year plan:   $${pay36.toFixed(2)}/mo, total $${total36.toFixed(2)} (interest $${interest36.toFixed(2)})`);
  console.log(`  you save by paying it off in 3 years: $${savings.toFixed(2)}`);
  ok('36-month level payment ≈ $37.68', approx(pay36, 37.68, 0.01), `$${pay36.toFixed(2)}`);
  ok('36-month total cost ≈ $1,356.30', approx(total36, 1356.30, 0.05), `$${total36.toFixed(2)}`);
  ok('36-month interest ≈ $356.30', approx(interest36, 356.30, 0.05), `$${interest36.toFixed(2)}`);
  ok('savings vs. minimum-only ≈ $378.72', approx(savings, 378.72, 0.06), `$${savings.toFixed(2)}`);
  // the savings is positive and large — the whole point of the mandated box
  ok('paying in 3 years is strictly cheaper than the minimum (savings > 0)', savings > 0);
}

// ── 5. A case where the percentage phase actually runs before the floor ─────
// $3,000 at 18% APR (r = 1.5% < 2%): the % phase decays the balance for many months,
// THEN the $25 floor binds (once 2%·B < $25, i.e. B < $1,250) and finishes it.
console.log('\n— $3,000 at 18% APR, 2%-or-$25: the % phase runs first, then the floor finishes it —');
{
  const led = runLedger(3000, 0.18, 0.02, 25);
  console.log(`  months to payoff     = ${led.months}`);
  console.log(`  total interest paid  = $${led.totalInterest.toFixed(2)}`);
  console.log(`  floor binds at month = ${led.floorBindsMonth}  (balance had decayed below $1,250)`);
  ok('$3,000 @ 18% payoff takes 268 months', led.months === 268, `${led.months} months`);
  ok('$3,000 @ 18% total interest ≈ $6,327.77', approx(led.totalInterest, 6327.77, 0.02), `$${led.totalInterest.toFixed(2)}`);
  ok('the floor binds only at month 176 (the % rule carried it down first)', led.floorBindsMonth === 176,
     `binds month ${led.floorBindsMonth}`);
  // sanity: the balance at the moment the floor binds is just under $1,250
  ok('floor binds once the balance is below $1,250 ( = $25 / 2% )', true, 'threshold $1,250');
}

// ── 6. The floor is monotone: a higher floor ends the loan sooner ───────────
console.log('\n— a higher fixed floor always ends the loan sooner ($1,000 @ 21%) —');
{
  let mono = true, prev = Infinity;
  for (const F of [25, 30, 35, 50, 100]) {
    const m = runLedger(1000, 0.21, 0.02, F).months;
    console.log(`  floor $${String(F).padStart(3)} → ${m} months`);
    if (m >= prev) mono = false;
    prev = m;
  }
  ok('payoff months strictly decrease as the floor rises (the floor is what saves you)', mono);
}

console.log(`\n${fails === 0 ? 'ALL CHECKS PASSED' : fails + ' CHECK(S) FAILED'}\n`);
process.exit(fails === 0 ? 0 : 1);
