#!/usr/bin/env node
// Offline verifier for /strata/no-interest-if-paid-in-full-deferred-interest/
//
// Recomputes EVERY number shown on the page from first principles and cross-checks
// each one two independent ways where possible. Exits 0 iff all checks pass.
//
// The model (identical to the page's inline simulate()):
//   Deferred interest = monthly periodic rate (APR/12) applied to the balance carried
//   at the START of each promo month, summed over the promo, and CHARGED only if any
//   balance remains at the deadline (waived entirely if paid in full). Payments reduce
//   the balance after each month's accrual.
//
// Sources (see README.md):
//   - CFPB Ask-CFPB en-40 (reviewed Jan 22, 2024): interest "calculated based on the
//     balance you owed in each month," "back to the original date of the charge";
//     >60 days late can void the deferred-interest period.
//   - CFPB blog "How to understand special promotional financing offers": the "if" tell;
//     0% intro APR charges interest only on the remainder, forward only.
//   - Canonical worked example (computed here from the CFPB-described mechanism, NOT quoted
//     from any single cited source): $3,000 @ 20%, $250/mo, one month $240 short ($10 left)
//     -> ~$325 retroactive interest.
//   - The ~50%-of-purchase magnitude for long, high-APR promos is a property of the mechanism
//     computed here (see check 6), not a figure quoted from a cited source.
//   - NerdWallet, "Deferred Interest vs. 0% APR": remainder on a true 0% card costs < $1.

let PASS = 0, FAIL = 0;
function check(name, got, want, tol = 0.005) {
  const ok = Math.abs(got - want) <= tol;
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${name}: got ${round(got)} want ${round(want)} (tol ${tol})`);
  ok ? PASS++ : FAIL++;
  return ok;
}
function assert(name, cond, detail = '') {
  console.log(`${cond ? 'PASS' : 'FAIL'}  ${name}${detail ? ': ' + detail : ''}`);
  cond ? PASS++ : FAIL++;
  return cond;
}
function round(x) { return Math.round(x * 1e4) / 1e4; }

// ── the model ────────────────────────────────────────────────────────────────
function simulate(P, apr, N, M) {
  const mpr = apr / 12;
  let bal = P, accrued = 0;
  const bals = [];
  for (let i = 0; i < N; i++) {
    bals.push(bal);
    accrued += bal * mpr;
    bal = Math.max(0, bal - M);
  }
  const leftover = bal;
  const charged = leftover > 1e-9 ? accrued : 0;
  return { leftover, accrued, charged, bals, mpr };
}

console.log('=== Deferred interest vs 0% APR — offline recompute ===\n');

// ── 1) Canonical anchor: clean $250/mo, $3,000 @ 20%, 12 mo -> exactly $325.00 ──
// Method A: month-by-month simulate() with a payment that clears (so we read accrued).
const clean = simulate(3000, 0.20, 12, 250);
check('canonical clean schedule accrued (month-by-month)', clean.accrued, 325.00);
// Method B: arithmetic series. Beginning balances are 3000,2750,...,250 = 250*(12..1).
// Sum = 250 * (1+2+...+12) = 250 * 78 = 19,500. Interest = 19,500 * 0.20/12.
const seriesSum = 250 * (12 * 13 / 2);            // = 19,500
check('canonical series Σ balances', seriesSum, 19500, 0.5);
check('canonical series interest (independent)', seriesSum * (0.20 / 12), 325.00);
// The two methods must agree exactly.
assert('canonical: month-by-month == series', Math.abs(clean.accrued - seriesSum * 0.20 / 12) < 1e-9);
// clean schedule clears to $0 (12 * $250 = $3,000)
check('canonical clean schedule leftover', clean.leftover, 0, 1e-9);

// ── 2) $10-short scenario (one month pays $240) -> "~$325" (325..327) ──────────
function shortScenario(shortMonth) {
  const mpr = 0.20 / 12;
  let bal = 3000, accrued = 0;
  for (let i = 1; i <= 12; i++) {
    accrued += bal * mpr;
    bal -= (i === shortMonth ? 240 : 250);
  }
  return { leftover: bal, accrued };
}
for (const m of [1, 6, 11]) {
  const s = shortScenario(m);
  check(`$10-short (month ${m}) leftover`, s.leftover, 10, 1e-6);
  assert(`$10-short (month ${m}) charged ~ $325 (325..327)`, s.accrued > 325 && s.accrued < 327,
         `$${round(s.accrued)}`);
}

// ── 3) The "scary ceiling": flat 20% × $3,000 == pay-nothing accrual == $600 ───
const payNothing = simulate(3000, 0.20, 12, 0);
check('pay-nothing accrual', payNothing.accrued, 600.00);
check('flat 20% × $3,000 (simple, 12mo)', 3000 * 0.20 * (12 / 12), 600.00);
assert('ceiling: pay-nothing accrual == flat sticker interest',
       Math.abs(payNothing.accrued - 3000 * 0.20) < 1e-9);
// And the real (paid-down) charge is strictly LESS than the ceiling — the whole point.
assert('real charge ($325) < flat ceiling ($600)', clean.accrued < payNothing.accrued,
       `$${round(clean.accrued)} < $${round(payNothing.accrued)}`);

// ── 4) The cliff: $0 left -> $0 charged; a cent left -> full accrual charged ───
const exactPay = simulate(3000, 0.20, 12, 3000 / 12);         // leaves exactly $0
const centShort = simulate(3000, 0.20, 12, 3000 / 12 - 0.01 / 12); // leaves ~1 cent
assert('cliff: paid in full -> $0 charged', exactPay.charged === 0);
assert('cliff: a cent left -> full accrued charged',
       centShort.charged > 300 && Math.abs(centShort.charged - centShort.accrued) < 1e-9,
       `$${round(centShort.charged)}`);

// ── 5) True 0% APR control on the $10 remainder -> < $1 (~$0.17) ──────────────
const zeroRemainder = 10 * (0.20 / 12);
check('true-0% APR: 1 month forward on $10 @ 20%', zeroRemainder, 0.1667, 0.001);
assert('true-0% remainder is under $1 (NerdWallet)', zeroRemainder < 1.0, `$${round(zeroRemainder)}`);

// ── 6) CFPB "~50% of purchase" for a long 25-35 month promo is plausible ──────
// Not the CFPB's exact population figure (that's their reported data) — we only assert
// our mechanism CAN reach ~half the purchase for a long promo at a high go-to APR with a
// balance carried a long time (e.g., minimum-ish paydown). Here: $2,000, 29.99%, 30 mo,
// paying just $30/mo (a plausible small minimum) leaves a large balance most of the term.
const longPromo = simulate(2000, 0.2999, 30, 30);
const pct = longPromo.charged / 2000;
assert('long-promo retro interest can reach ~50% of purchase',
       pct > 0.45 && pct < 0.75, `${round(pct * 100)}% of $2,000`);

// ── 7) Default page settings sanity ($3,000 @ 20%, 12mo, $250/mo) ─────────────
const dflt = simulate(3000, 0.20, 12, 250);
assert('default schedule clears -> endings show $0 / $0 / (n/a)', dflt.leftover <= 1e-9);
// with a genuinely short default (e.g. $245/mo) the deferred charge appears
const shortDefault = simulate(3000, 0.20, 12, 245);
assert('default @ $245/mo leaves a balance -> nonzero charge',
       shortDefault.leftover > 0 && shortDefault.charged > 300,
       `leftover $${round(shortDefault.leftover)}, charged $${round(shortDefault.charged)}`);

console.log(`\n=== ${PASS} passed, ${FAIL} failed ===`);
process.exit(FAIL === 0 ? 0 : 1);
