← Demos
Web Pages · Demos

The $2,000 Line

For someone in Kentucky on SSI who has just received a lump sum, such as an inheritance. Type in the amount and the day it arrived, and the page shows how much has to leave the bank, and by what date, to stay under the $2,000 limit on the 1st, and what each of three paths costs: leaving it in the bank, spending it on things SSI does not count, or moving it to a STABLE Kentucky account. With a dated checklist and a one-page printout. Nothing you type is sent anywhere.

by Christian Smith Nov 19, 2026 11 views 194.5 KB
Sandbox · the-2-000-line · no access to your account
View source — the whole page is this one file
<!-- Copyright (c) 2026 Christian Smith and Liam Schilling. Released under the MIT License. -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>The $2,000 Line: a lump sum and an SSI check in Kentucky</title>
<style>
  :root {
    --paper: #ffffff;
    --card: #f5f6f4;
    --ink: #1f2a24;
    --muted: #4f5b54;
    --ridge: #2f5d50;
    --rust: #9a3f1c;
    --gold-ink: #7a5200;
    --gold-line: #a87408;      /* 3.8:1 on the paper colour: the $2,000 line has to stand out */
    --rule: #e1e4e1;
    --field-edge: #5d6a63;
    --note-bg: #fff6df;
    --warn-bg: #fdecea;
    --warn-ink: #8c1d18;
  }
  * { box-sizing: border-box; }
  [hidden] { display: none !important; }
  html { font-size: 100%; }
  body {
    margin: 0;
    background: var(--paper);
    color: var(--ink);
    font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
    line-height: 1.5;
  }
  main { max-width: 62rem; margin: 0 auto; padding: 1rem 1rem 2rem; }
  main > section { margin-top: 3.5rem; }
  h1, h2, h3 { line-height: 1.2; letter-spacing: -0.01em; }
  h1 { font-size: 2.1rem; font-weight: 750; margin: 0.75rem 0 0; }
  h2 { display: flex; align-items: center; gap: 0.6rem; font-size: 1.4rem; margin: 0 0 0.75rem; }
  .step { display: inline-flex; flex: none; align-items: center; justify-content: center; width: 1.8rem; height: 1.8rem; border-radius: 50%; background: var(--ridge); color: #ffffff; font: 700 0.95rem/1 system-ui, -apple-system, "Segoe UI", Roboto, Arial, sans-serif; }
  h3 { font-size: 1.05rem; margin: 0 0 0.5rem; }
  p, .headline, .outcomes, .notice, .ask { max-width: 46rem; }
  :focus-visible { outline: 3px solid var(--rust); outline-offset: 2px; }

  /* Top of the page: a picture, who it is for, and his question */
  .subtitle { margin: 0.25rem 0 0.75rem; color: var(--muted); font-size: 1.05rem; }
  .built-for { margin: 0.5rem 0; }
  .his-question { margin: 0.75rem 0 0; padding: 0 0 0 0.9rem; border-left: 3px solid var(--gold-line); color: var(--muted); font-style: italic; }

  /* The answer */
  .mode-row { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem 0.75rem; margin: 0 0 0.6rem; }
  .tag { margin: 0; padding: 0.2rem 0.75rem; border-radius: 1rem; background: var(--card); color: var(--muted); font-size: 0.85rem; font-weight: 600; }
  .headline { margin: 0; padding: 1.1rem 1.25rem; background: var(--card); border: 0; border-left: 5px solid var(--gold-line); border-radius: 6px; font-size: 1.35rem; line-height: 1.4; }
  .headline strong, .outcomes strong { font-variant-numeric: tabular-nums; }
  .headline .days { display: block; margin-top: 0.25rem; color: var(--rust); font-weight: 700; }
  .aside { color: var(--muted); font-size: 0.95rem; }
  .outcomes { margin: 0.75rem 0 0; padding: 0; list-style: none; }
  .outcomes li { margin: 0; padding: 0.6rem 0; border-bottom: 1px solid var(--rule); }
  .outcomes li:last-child { border-bottom: 0; }
  .notice { margin: 0.6rem 0; padding: 0.4rem 0.8rem; background: var(--note-bg); border-left: 3px solid var(--gold-line); border-radius: 0 4px 4px 0; }

  /* Buttons and questions asked in place */
  .btn { min-height: 44px; padding: 0.5rem 0.95rem; border: 1px solid #7d8782; border-radius: 8px; background: #ffffff; color: var(--ink); font: inherit; font-weight: 600; cursor: pointer; }
  .btn:hover { border-color: var(--ridge); color: var(--ridge); }
  .btn-solid, .btn-solid:hover { background: var(--ridge); border-color: var(--ridge); color: #ffffff; }
  .ask { margin: 0 0 0.75rem; padding: 0.75rem; background: var(--card); border: 2px solid var(--rust); border-radius: 6px; }
  .ask p { margin: 0 0 0.6rem; font-weight: 600; }
  .ask .btn { margin: 0 0.5rem 0.25rem 0; }

  /* The file bar: save, open, print, start over */
  .file-bar { margin: 0 0 1rem; padding: 0.25rem 0 0.6rem; border-bottom: 1px solid var(--rule); }
  .file-buttons { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; }
  .pill { display: inline-flex; align-items: center; gap: 0.4rem; margin: 0; padding: 0.25rem 0.75rem; border: 2px solid var(--ridge); border-radius: 1rem; color: var(--ridge); font-size: 0.9rem; font-weight: 600; }
  .pill[data-dirty="yes"] { border-color: var(--rust); color: var(--rust); background: var(--note-bg); }
  .pill-mark { font-weight: 700; }
  .file-note { margin: 0.5rem 0 0; padding: 0.5rem 0.8rem; background: var(--note-bg); border-left: 4px solid var(--gold-line); }
  .file-note:empty { display: none; }
  .file-error { margin: 0.5rem 0 0; padding: 0.6rem 0.8rem; background: var(--warn-bg); color: var(--warn-ink); border-left: 4px solid var(--warn-ink); font-weight: 600; }
  #file-ask .ask { margin: 0.6rem 0 0; }
  .file-more { margin-top: 0.3rem; }
  .file-more > summary { font-size: 0.9rem; font-weight: 600; }
  .file-more label { margin-top: 0.5rem; }
  textarea { display: block; width: 100%; margin: 0.4rem 0; padding: 0.4rem 0.6rem; border: 2px solid var(--field-edge); border-radius: 6px; background: #ffffff; color: var(--ink); font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 0.85rem; }
  @media (max-width: 30rem) {
    .file-bar { padding: 0.25rem 0 0.5rem; }
    .file-buttons { display: grid; grid-template-columns: 1fr 1fr; gap: 0.4rem; }
    .file-buttons .btn { padding: 0.3rem 0.45rem; font-size: 0.95rem; line-height: 1.2; }
    .pill { grid-column: 1 / -1; justify-self: start; }
    .file-more summary { padding: 0.2rem 0; font-size: 0.9rem; }
  }
  .print-sheet { display: none; }
  @media print {
    @page { margin: 12mm; }
    html, body { background: #ffffff; color: #000000; }
    body { font-size: 9pt; line-height: 1.3; }
    main { max-width: none; padding: 0; }
    main > *:not(.print-sheet) { display: none !important; }
    .print-sheet { display: block; margin: 0; }
    .print-sheet h2 { font-size: 15pt; margin: 0 0 3pt; }
    .print-sheet h3 { font-size: 10pt; margin: 7pt 0 2pt; }
    .print-sheet p { max-width: none; margin: 2.5pt 0; }
    .ps-headline { font-size: 11.5pt; font-weight: 700; border: 1.5pt solid #000000; padding: 4pt 6pt; }
    .ps-table { width: 100%; border-collapse: collapse; font-size: 8.5pt; font-variant-numeric: tabular-nums; }
    .ps-table th, .ps-table td { border: 0.75pt solid #555555; padding: 2pt 4pt; text-align: left; vertical-align: top; }
    .ps-cols { display: grid; grid-template-columns: 1fr 1fr; gap: 10pt; break-inside: avoid; }
    .ps-list { margin: 0; padding: 0; list-style: none; }
    .ps-list li { margin: 1.5pt 0; }
    .ps-small, .ps-notes { font-size: 7.5pt; }
    .ps-notes { font-size: 8pt; white-space: pre-line; }
    .ps-worked { margin: 0; padding-left: 14pt; font-size: 8.5pt; }
    .ps-worked li { margin: 1.5pt 0; }
  }

  /* The numbers */
  .fields { display: grid; gap: 1.4rem 2.5rem; grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr)); align-items: start; margin-top: 1rem; }
  .fields .field { margin: 0; }
  #numbers:not(.show-help) .hint { display: none; }
  .step-head { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 0.25rem 1rem; }
  .step-head h2 { margin: 0; }
  .link-btn { min-height: 44px; padding: 0 0.25rem; border: 0; background: none; color: var(--ridge); font: inherit; font-size: 0.9rem; font-weight: 600; text-decoration: underline; text-underline-offset: 3px; cursor: pointer; }
  .field { margin: 0 0 1.1rem; }
  .field:last-child { margin-bottom: 0; }
  fieldset.field { min-width: 0; padding: 0; border: 0; }
  label, legend, .label { display: block; padding: 0; margin: 0; font-weight: 600; }
  .hint { margin: 0.15rem 0 0.4rem; color: var(--muted); font-size: 0.9rem; }
  input[type="text"] { width: 100%; min-height: 44px; padding: 0.4rem 0.6rem; border: 2px solid var(--field-edge); border-radius: 6px; background: #ffffff; color: var(--ink); font: inherit; font-size: 1rem; font-variant-numeric: tabular-nums; }
  input[aria-invalid="true"] { border-color: var(--warn-ink); border-width: 3px; }
  .money { display: flex; align-items: center; gap: 0.4rem; max-width: 14rem; }
  .money span { font-weight: 600; }
  .short { max-width: 6rem; }
  .date-boxes { display: flex; gap: 0.6rem; }
  .date-boxes label { font-weight: 400; font-size: 0.9rem; }
  .date-boxes .part { width: 4rem; }
  .date-boxes .part-year { width: 5.5rem; }
  .choice { display: flex; align-items: center; gap: 0.5rem; min-height: 44px; font-weight: 400; cursor: pointer; }
  .choice input { width: 1.25rem; height: 1.25rem; margin: 0; accent-color: var(--ridge); }
  .echo { margin: 0.35rem 0 0; color: var(--ridge); font-weight: 600; }
  .field-error { margin: 0.35rem 0 0; color: var(--warn-ink); font-weight: 600; }
  details > summary { cursor: pointer; padding: 0.35rem 0; color: var(--ridge); font-weight: 600; }
  .sub-more { margin-top: 1.25rem; padding-top: 0.5rem; border-top: 1px solid var(--rule); }
  .more-label { margin: 3.5rem 0 0.25rem; color: var(--muted); font-size: 0.8rem; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; }
  .more { border-top: 1px solid var(--rule); }
  .more:last-of-type { border-bottom: 1px solid var(--rule); }
  .more > summary { display: block; list-style: none; padding: 0.9rem 0 0.9rem 1.6rem; position: relative; color: var(--ink); }
  .more > summary::-webkit-details-marker { display: none; }
  .more > summary::before { content: "+"; position: absolute; left: 0.2rem; top: 0.85rem; color: var(--ridge); font-weight: 700; font-size: 1.2rem; line-height: 1.2; }
  .more[open] > summary::before { content: "\2212"; }
  .more-title { display: inline; margin: 0; font-size: 1.15rem; }
  .more-hint { display: block; margin-top: 0.15rem; color: var(--muted); font-size: 0.9rem; font-weight: 400; }
  .more > section { padding: 0 0 1.5rem 1.6rem; }

  /* Three paths. Every card looks the same: the page does not rank them. */
  .cards { display: grid; gap: 1rem; grid-template-columns: repeat(auto-fit, minmax(17rem, 1fr)); align-items: start; }
  .card { padding: 1.1rem 1.15rem; background: var(--card); border: 0; border-radius: 10px; }
  .why { margin-top: 0.75rem; }
  .why > summary { font-size: 0.85rem; }
  .why p { color: var(--muted); font-size: 0.9rem; }
  .card h3 { margin: 0 0 0.35rem; }
  .card p { margin: 0 0 0.5rem; font-size: 0.95rem; }
  .card dl { margin: 0.75rem 0 0; }
  .card dt { margin-top: 0.7rem; color: var(--muted); font-size: 0.85rem; font-weight: 600; }
  .card dd { margin: 0; font-variant-numeric: tabular-nums; }
  .card .value { display: block; font-weight: 700; }
  .card .note { display: block; color: var(--muted); font-size: 0.9rem; }
  .card .cushion .value { font-size: 1.6rem; line-height: 1.25; }

  /* Three shelves */
  .shelf { margin: 1.1rem 0 0; }
  .shelf h3 { margin: 0; }
  .shelf-cap { margin: 0.15rem 0 0.4rem; color: var(--muted); font-size: 0.95rem; }
  .shelf-wrap { overflow-x: auto; }
  .shelf-wrap svg { display: block; overflow: visible; }
  .shelf-wrap text { font-family: inherit; font-size: 11px; }
  .blk { fill: var(--ridge); }
  .blk-over { stroke: var(--rust); stroke-width: 1; }
  .blk-stable { fill: var(--gold-line); }
  .blk-gap { stroke: var(--paper); stroke-width: 1.5; }
  .blk-break { fill: none; stroke: var(--paper); stroke-width: 3; }
  .hatch-bg { fill: var(--warn-bg); }
  .hatch-line { stroke: var(--rust); stroke-width: 2; }
  .shelf-line { stroke: var(--ink); stroke-width: 3; }
  .plank { stroke: var(--gold-ink); stroke-width: 3; }
  .gold { stroke: var(--gold-line); stroke-width: 3; }
  .gold-label { fill: var(--gold-ink); font-weight: 700; }
  .ax { fill: var(--muted); }
  .yr { stroke: var(--rule); stroke-width: 1; }
  .mk-paid { fill: var(--ridge); }
  .mk-notpayable { fill: none; stroke: var(--rust); stroke-width: 2.5; }
  .mk-repay { fill: none; stroke: var(--rust); stroke-width: 2; }
  .mk-closed { fill: none; stroke: var(--muted); stroke-width: 2; }
  .flag { fill: var(--rust); }
  .flag-pole { stroke: var(--ink); stroke-width: 1.5; }
  .flag-label { fill: var(--ink); font-weight: 600; }
  .shelf-legend { display: flex; flex-wrap: wrap; gap: 0.25rem 1.1rem; margin: 0.9rem 0 0.25rem; padding: 0; list-style: none; font-size: 0.9rem; }
  .shelf-legend li { display: flex; align-items: center; gap: 0.35rem; }
  .table-wrap { overflow-x: auto; }
  .months-table { border-collapse: collapse; margin: 0.4rem 0; font-size: 0.9rem; font-variant-numeric: tabular-nums; }
  .months-table caption { text-align: left; color: var(--muted); padding-bottom: 0.3rem; }
  .months-table th, .months-table td { padding: 0.3rem 0.55rem; border-bottom: 1px solid var(--rule); text-align: left; vertical-align: top; }
  .months-table thead th { border-bottom: 2px solid var(--ink); }

  /* The clock, the timing what-if, and when it does not all fit */
  .clock-lines { max-width: 46rem; padding-left: 1.2rem; }
  .clock-lines li { margin: 0.35rem 0; }
  .whatif { max-width: 46rem; }
  .bar-row { margin: 0.6rem 0; }
  .bar-label { margin: 0 0 0.25rem; font-variant-numeric: tabular-nums; }
  .bar-track { height: 1.1rem; background: var(--card); border: 1px solid var(--rule); border-radius: 4px; }
  .bar-fill { height: 100%; background: var(--ridge); border-radius: 3px 0 0 3px; }
  .bar-row + .bar-row .bar-fill { background: var(--gold-line); }
  .fit-choice { margin-top: 1rem; }
  .fit { margin-top: 2rem; }

  /* The Kentucky part, the checklist, how it's worked out, the rules */
  .age-ruler { margin: 0.25rem 0 1.25rem; }
  .age-ruler svg { display: block; overflow: visible; }
  .age-ruler text { font-family: inherit; font-size: 11px; }
  .ruler-axis { stroke: var(--ink); stroke-width: 2; }
  .ruler-tick { stroke: var(--muted); stroke-width: 1; }
  .ruler-old { stroke: var(--muted); stroke-width: 3; }
  .ruler-new { stroke: var(--ridge); stroke-width: 3; }
  .ruler-mark { stroke: var(--rust); stroke-width: 2.5; }
  .ruler-dot { fill: var(--rust); }
  .ruler-label { fill: var(--ink); font-weight: 600; paint-order: stroke; stroke: var(--paper); stroke-width: 4px; stroke-linejoin: round; }
  .checklist { padding: 0; list-style: none; max-width: 46rem; }
  .checklist .choice { align-items: flex-start; padding: 0.35rem 0; }
  .checklist .choice input { margin-top: 0.15rem; flex: none; }
  .notes { max-width: 46rem; font-family: inherit; font-size: 1rem; }
  .worked { max-width: 46rem; padding-left: 1.4rem; font-variant-numeric: tabular-nums; }
  .worked li { margin: 0.45rem 0; }
  .rules-table td { min-width: 9rem; }
  .limits { max-width: 46rem; }

  /* Built-in checks and footer */
  .checks-summary { font-weight: 600; }
  .checks-warning { padding: 0.75rem; background: var(--warn-bg); color: var(--warn-ink); border: 2px solid var(--warn-ink); border-radius: 6px; font-weight: 600; }
  .checks-list { padding-left: 1.4rem; }
  .checks-list li { margin: 0.5rem 0; }
  .checks-list ul { padding-left: 1.1rem; color: var(--muted); font-size: 0.9rem; font-variant-numeric: tabular-nums; }
  .mark-pass { color: var(--ridge); font-weight: 700; }
  .mark-fail { color: var(--warn-ink); font-weight: 700; }
  footer { margin-top: 2.5rem; padding-top: 1rem; border-top: 1px solid var(--rule); color: var(--muted); font-size: 0.9rem; }
  footer p { margin: 0.4rem 0; }
</style>
</head>
<body>
<main>
  <div class="file-bar" role="group" aria-label="Your plan, kept as a file on this device">
    <div class="file-buttons">
      <button type="button" id="btn-save" class="btn btn-solid" aria-keyshortcuts="Control+S Meta+S">Save my plan</button>
      <button type="button" id="btn-open" class="btn" aria-keyshortcuts="Control+O Meta+O">Open a saved plan</button>
      <button type="button" id="btn-print" class="btn">Print</button>
      <button type="button" id="btn-reset" class="btn">Start over</button>
      <p class="pill" id="save-pill" role="status" aria-live="polite"><span class="pill-mark" id="save-pill-mark" aria-hidden="true"></span><span id="save-pill-text"></span></p>
    </div>
    <input type="file" id="file-pick" aria-label="Choose a saved plan" hidden>
    <div id="file-ask"></div>
    <div id="file-alert" role="alert"></div>
    <p id="file-note" class="file-note" role="status" aria-live="polite"></p>
    <details id="save-text-box" class="file-more">
      <summary>Can’t download? Show my file as text, or paste a saved file</summary>
      <p class="hint">Ctrl+S saves and Ctrl+O opens (Cmd+S and Cmd+O on a Mac). You can also drag a saved file onto
        this page to open it. The file stays on this device.</p>
      <label for="save-text">Your plan as text</label>
      <p class="hint" id="save-text-hint">This is the whole file. Copy all of it and keep it, for example in a note or an
        email to yourself.</p>
      <textarea id="save-text" rows="6" readonly spellcheck="false" aria-describedby="save-text-hint"></textarea>
      <div id="paste-box">
        <label for="paste-text">Paste a saved file</label>
        <textarea id="paste-text" rows="4" spellcheck="false"></textarea>
        <button type="button" id="btn-paste-open" class="btn">Open the pasted plan</button>
      </div>
    </details>
  </div>

  <header>
    <h1>The $2,000 Line</h1>
    <p class="subtitle">Keeping a lump sum and an SSI check in Kentucky</p>
    <p class="built-for"><strong>Built for</strong> a 38-year-old in Jackson, Breathitt County, disabled in a wreck at 31
      and living on a $994 SSI check, whose grandmother has just left him $16,500. He is an invented example; anyone in
      Kentucky with the same problem can type in their own numbers.</p>
    <p class="his-question">&ldquo;Mamaw left me $16,500 and I&rsquo;m not allowed more than $2,000. Do I have to turn it
      down, or spend it all this month?&rdquo;</p>
  </header>

  <section id="answer" aria-labelledby="answer-title">
    <h2 id="answer-title"><span class="step" aria-hidden="true">1</span><span id="answer-title-text">What the rule means for him</span></h2>
    <div class="mode-row">
      <p id="mode-tag" class="tag"></p>
      <button type="button" id="btn-own" class="btn">Use my own numbers</button>
      <button type="button" id="btn-sample" class="btn" hidden>Show the example again</button>
    </div>
    <div id="mode-ask"></div>
    <div id="headline" class="headline" role="status" aria-live="polite"></div>
    <ul id="outcomes" class="outcomes"></ul>
    <p id="refusal-note" class="aside"></p>
    <div id="notices"></div>
    <details class="sub-more" id="answer-why">
      <summary>Why these numbers</summary>
      <p id="room-note" class="aside"></p>
      <p id="receipt-note" class="aside"></p>
    </details>
  </section>

  <section id="numbers" aria-labelledby="numbers-title">
    <div class="step-head">
      <h2 id="numbers-title" tabindex="-1"><span class="step" aria-hidden="true">2</span>The numbers</h2>
      <button type="button" id="btn-help" class="link-btn" aria-pressed="false" aria-controls="numbers">Show help for each box</button>
    </div>
    <p class="aside">Change any box and everything is worked out again. Nothing typed here leaves this page.</p>
    <div class="fields">
      <div class="field" role="radiogroup" aria-labelledby="f-kind-label" aria-describedby="f-kind-hint">
        <p class="label" id="f-kind-label">What kind of money is it?</p>
        <label class="choice" for="f-kind-inheritance"><input type="radio" name="kind" id="f-kind-inheritance" value="inheritance" checked> An inheritance</label>
        <label class="choice" for="f-kind-backpay"><input type="radio" name="kind" id="f-kind-backpay" value="backpay"> SSI back pay</label>
        <p class="hint" id="f-kind-hint">An inheritance counts as income in the month it arrives. SSI back pay does not, and
          it is not counted for <span data-figure="backpay-months"></span> months after that. Back pay paid in
          installments has a separate count for each one, and back pay from Social Security disability or retirement
          benefits follows other rules; this page works out neither.</p>
      </div>
      <div class="field">
        <label for="f-amount">The lump sum</label>
        <p class="hint" id="f-amount-hint">The amount that arrives, in dollars.</p>
        <div class="money"><span aria-hidden="true">$</span><input type="text" id="f-amount" inputmode="decimal" autocomplete="off" data-money="amountCents" aria-describedby="f-amount-hint f-amount-error"></div>
        <p class="field-error" id="f-amount-error" hidden></p>
      </div>
      <fieldset class="field" id="f-arrival">
        <legend>Day the money arrives</legend>
        <p class="hint" id="f-arrival-hint">Month, day and year in digits, like 11, 12 and 2026.</p>
        <div class="date-boxes">
          <div class="part"><label for="f-arrival-m">Month</label><input type="text" id="f-arrival-m" inputmode="numeric" autocomplete="off" maxlength="2" data-date="m" aria-describedby="f-arrival-hint f-arrival-echo f-arrival-error"></div>
          <div class="part"><label for="f-arrival-d">Day</label><input type="text" id="f-arrival-d" inputmode="numeric" autocomplete="off" maxlength="2" data-date="d" aria-describedby="f-arrival-hint f-arrival-echo f-arrival-error"></div>
          <div class="part part-year"><label for="f-arrival-y">Year</label><input type="text" id="f-arrival-y" inputmode="numeric" autocomplete="off" maxlength="4" data-date="y" aria-describedby="f-arrival-hint f-arrival-echo f-arrival-error"></div>
        </div>
        <p class="echo" id="f-arrival-echo"></p>
        <p class="field-error" id="f-arrival-error" hidden></p>
      </fieldset>
      <div class="field">
        <label for="f-other">Other money that counts, already on hand</label>
        <p class="hint" id="f-other-hint">Cash and bank balances. Blank means none.</p>
        <div class="money"><span aria-hidden="true">$</span><input type="text" id="f-other" inputmode="decimal" autocomplete="off" data-money="otherCents" aria-describedby="f-other-hint f-other-error"></div>
        <p class="field-error" id="f-other-error" hidden></p>
      </div>
      <div class="field">
        <label for="f-spend">Living costs each month with no check</label>
        <p class="hint" id="f-spend-hint">Used only where the money stays in the bank: what is spent from it in each month
          that no check comes. Blank means nothing is spent.</p>
        <div class="money"><span aria-hidden="true">$</span><input type="text" id="f-spend" inputmode="decimal" autocomplete="off" data-money="monthlySpendCents" aria-describedby="f-spend-hint f-spend-error"></div>
        <p class="field-error" id="f-spend-error" hidden></p>
      </div>
      <div class="field">
        <label for="f-onset">Age when the disability began</label>
        <p class="hint" id="f-onset-hint">An ABLE account, such as STABLE Kentucky, is open to a person whose disability began
          before the <span data-figure="onset"></span> birthday. Until the end of 2025 the rule said the
          <span data-figure="onset-old"></span>.</p>
        <input type="text" class="short" id="f-onset" inputmode="numeric" autocomplete="off" maxlength="3" data-whole="onsetAge" data-min="0" data-max="120" data-what="The age" aria-describedby="f-onset-hint f-onset-error">
        <p class="field-error" id="f-onset-error" hidden></p>
      </div>
    </div>
    <details class="sub-more" id="more-settings">
      <summary>More settings: the SSI amount, room under the line, ABLE deposits</summary>
      <div class="fields">
        <div class="field">
          <label for="f-ssi-2026">Monthly SSI check in 2026</label>
          <p class="hint" id="f-ssi-2026-hint">The full amount for one person is <span data-figure="ssi-2026"></span>. Type the
            full monthly amount, before anything is held back from it.</p>
          <div class="money"><span aria-hidden="true">$</span><input type="text" id="f-ssi-2026" inputmode="decimal" autocomplete="off" data-money="ssiCents" data-year="2026" aria-describedby="f-ssi-2026-hint f-ssi-2026-error"></div>
          <p class="field-error" id="f-ssi-2026-error" hidden></p>
        </div>
        <div class="field">
          <label for="f-ssi-2027">Monthly SSI check in 2027</label>
          <p class="hint" id="f-ssi-2027-hint">The full amount for one person is <span data-figure="ssi-2027"></span>. Later years
            are not published yet and reuse this box.</p>
          <div class="money"><span aria-hidden="true">$</span><input type="text" id="f-ssi-2027" inputmode="decimal" autocomplete="off" data-money="ssiCents" data-year="2027" aria-describedby="f-ssi-2027-hint f-ssi-2027-error"></div>
          <p class="field-error" id="f-ssi-2027-error" hidden></p>
        </div>
        <div class="field">
          <label for="f-buffer">Room to leave under the <span data-figure="line"></span> line</label>
          <p class="hint" id="f-buffer-hint">The plan aims this far under the line on the 1st, because interest or a small
            deposit can push a count over. Blank means none.</p>
          <div class="money"><span aria-hidden="true">$</span><input type="text" id="f-buffer" inputmode="decimal" autocomplete="off" data-money="bufferCents" aria-describedby="f-buffer-hint f-buffer-error"></div>
          <p class="field-error" id="f-buffer-error" hidden></p>
        </div>
        <div class="field">
          <label for="f-prior">Already paid into an ABLE account in <span id="prior-year">the year the money arrives</span></label>
          <p class="hint" id="f-prior-hint">Deposits from anyone during that calendar year. Blank means none.</p>
          <div class="money"><span aria-hidden="true">$</span><input type="text" id="f-prior" inputmode="decimal" autocomplete="off" data-money="priorStableCents" aria-describedby="f-prior-hint f-prior-error"></div>
          <p class="field-error" id="f-prior-error" hidden></p>
        </div>
        <div class="field">
          <label for="f-cap-2026">Most that can be paid in during 2026</label>
          <p class="hint" id="f-cap-2026-hint">Published figure: <span data-figure="cap-2026"></span>.</p>
          <div class="money"><span aria-hidden="true">$</span><input type="text" id="f-cap-2026" inputmode="decimal" autocomplete="off" data-money="capCents" data-year="2026" aria-describedby="f-cap-2026-hint f-cap-2026-error"></div>
          <p class="field-error" id="f-cap-2026-error" hidden></p>
        </div>
        <div class="field">
          <label for="f-cap-2027">Most that can be paid in during 2027</label>
          <p class="hint" id="f-cap-2027-hint">Published figure: <span data-figure="cap-2027"></span>, from one Internal Revenue
            Service notice. Change it if a newer figure is out.</p>
          <div class="money"><span aria-hidden="true">$</span><input type="text" id="f-cap-2027" inputmode="decimal" autocomplete="off" data-money="capCents" data-year="2027" aria-describedby="f-cap-2027-hint f-cap-2027-error"></div>
          <p class="field-error" id="f-cap-2027-error" hidden></p>
        </div>
      </div>
    </details>
  </section>

  <section id="paths" aria-labelledby="paths-title">
    <h2 id="paths-title"><span class="step" aria-hidden="true">3</span>Three paths, side by side</h2>
    <p class="aside">The same arithmetic three ways. This page does not rank them; which one fits is for the person whose
      money it is.</p>
    <div id="path-notes"></div>
    <div id="cards" class="cards"></div>
    <section id="fit-section" class="fit" aria-labelledby="fit-title" hidden>
      <h3 id="fit-title">If it does not all fit</h3>
      <p id="fit-intro"></p>
      <div class="cards">
        <article class="card" aria-labelledby="fit-spend-title"><h3 id="fit-spend-title">Spend that part before the 1st</h3><p id="fit-spend"></p></article>
        <article class="card" aria-labelledby="fit-wait-title"><h3 id="fit-wait-title">Hold that part until the next limit</h3><p id="fit-wait"></p></article>
      </div>
      <fieldset class="field fit-choice" id="f-leftover">
        <legend>The STABLE card and shelf above show that part</legend>
        <label class="choice" for="f-leftover-spend"><input type="radio" name="leftover" id="f-leftover-spend" value="spend" checked> spent before the 1st</label>
        <label class="choice" for="f-leftover-wait"><input type="radio" name="leftover" id="f-leftover-wait" value="wait"> held until the next limit</label>
      </fieldset>
      <div id="fit-lines"></div>
    </section>
  </section>

  <section id="shelves-section" aria-labelledby="shelves-title">
    <h2 id="shelves-title"><span class="step" aria-hidden="true">4</span>Month by month: what is counted on each 1st</h2>
    <p class="aside">Each column is the money counted on the 1st of a month, in blocks of <span id="shelf-block">$1,000</span>.
      Above the gold <span data-figure="line"></span> line the blocks are hatched; the mark under a column is that
      month&rsquo;s check.</p>
    <div id="shelves"></div>
    <ul class="shelf-legend" id="shelf-legend" aria-label="Key to the shelves">
      <li><svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true" focusable="false"><rect class="blk" x="2" y="2" width="12" height="12"/></svg>counted, within the line</li>
      <li><svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true" focusable="false"><defs><pattern id="hatch-key" width="6" height="6" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect class="hatch-bg" width="6" height="6"/><line class="hatch-line" x1="0" y1="0" x2="0" y2="6"/></pattern></defs><rect class="blk-over" fill="url(#hatch-key)" x="2" y="2" width="12" height="12"/></svg>counted, above the line</li>
      <li><svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true" focusable="false"><rect class="blk-stable" x="2" y="2" width="12" height="12"/></svg>in STABLE Kentucky, not counted</li>
      <li><svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true" focusable="false"><line class="gold" x1="1" y1="8" x2="15" y2="8"/></svg>the <span data-figure="line"></span> line</li>
      <li><svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true" focusable="false"><circle class="mk-paid" cx="8" cy="8" r="4"/></svg>check paid</li>
      <li><svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true" focusable="false"><path class="mk-notpayable" d="M4 4L12 12M12 4L4 12"/></svg>check not payable</li>
      <li><svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true" focusable="false"><rect class="mk-repay" x="4" y="4" width="8" height="8"/></svg>check has to be repaid</li>
      <li><svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true" focusable="false"><circle class="mk-closed" cx="8" cy="8" r="4"/></svg>case closed</li>
      <li><svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true" focusable="false"><line class="flag-pole" x1="4" y1="2" x2="4" y2="15"/><path class="flag" d="M4 2L13 6L4 10Z"/></svg>12th month in a row with no payable check</li>
    </ul>
    <details class="sub-more" id="shelves-others">
      <summary>Show the other two paths month by month</summary>
      <div id="shelves-more"></div>
      <p class="aside">Once a path is at or under the line, its later columns repeat that month; nothing more is assumed.</p>
    </details>
    <details id="shelves-table-box">
      <summary>Show these months as a table</summary>
      <div class="table-wrap" tabindex="0" role="region" aria-label="The months, as a table"><table class="months-table" id="shelves-table"></table></div>
    </details>
  </section>

  <section id="clock-section" aria-labelledby="clock-title">
    <h2 id="clock-title"><span class="step" aria-hidden="true">5</span>The clock</h2>
    <ul id="clock-lines" class="clock-lines"></ul>
    <details class="sub-more" id="allowance-box">
    <summary>Change how many banking days the move takes</summary>
    <div class="field">
      <label for="f-allowance">Banking days allowed for opening an account and moving the money</label>
      <p class="hint" id="f-allowance-hint">No official figure exists; <span data-figure="allowance"></span> is a starting figure.
        A whole number from 1 to 90.</p>
      <input type="text" class="short" id="f-allowance" inputmode="numeric" autocomplete="off" maxlength="2" data-whole="allowanceDays" data-min="1" data-max="90" data-what="The number of banking days" aria-describedby="f-allowance-hint f-allowance-error">
      <p class="field-error" id="f-allowance-error" hidden></p>
    </div>
    </details>

    <details class="sub-more" id="whatif-box">
      <summary>If the money arrived on another day</summary>
      <p class="aside">Social Security&rsquo;s manual counts an inheritance as income in the first month it has a value and
        can be used. This compares the arithmetic for two days; it is not a way to pick one.</p>
      <fieldset class="field" id="f-alt">
        <legend>Another day to compare</legend>
        <p class="hint" id="f-alt-hint">Month, day and year in digits. Leave the boxes blank to skip the comparison.</p>
        <div class="date-boxes">
          <div class="part"><label for="f-alt-m">Month</label><input type="text" id="f-alt-m" inputmode="numeric" autocomplete="off" maxlength="2" data-date="m" aria-describedby="f-alt-hint f-alt-echo f-alt-error"></div>
          <div class="part"><label for="f-alt-d">Day</label><input type="text" id="f-alt-d" inputmode="numeric" autocomplete="off" maxlength="2" data-date="d" aria-describedby="f-alt-hint f-alt-echo f-alt-error"></div>
          <div class="part part-year"><label for="f-alt-y">Year</label><input type="text" id="f-alt-y" inputmode="numeric" autocomplete="off" maxlength="4" data-date="y" aria-describedby="f-alt-hint f-alt-echo f-alt-error"></div>
        </div>
        <p class="echo" id="f-alt-echo"></p>
        <p class="field-error" id="f-alt-error" hidden></p>
      </fieldset>
      <div id="whatif" class="whatif"></div>
    </details>
  </section>



  <section id="checklist-section" aria-labelledby="checklist-title">
    <h2 id="checklist-title"><span class="step" aria-hidden="true">6</span>A dated checklist</h2>
    <p class="aside">Ticks and notes are saved in the plan file. Nothing here is sent anywhere.</p>
    <ul id="checklist" class="checklist"></ul>
    <details class="sub-more" id="questions-box">
      <summary>Questions to ask Social Security, and your notes</summary>
      <ul id="ssa-questions"></ul>
      <div class="field">
        <label for="f-notes">Notes</label>
        <p class="hint" id="f-notes-hint">Up to 5,000 characters, saved with the plan.</p>
        <textarea id="f-notes" class="notes" rows="5" maxlength="5000" aria-describedby="f-notes-hint"></textarea>
      </div>
    </details>
  </section>

  <p class="more-label">More detail</p>
  <details class="more" id="kentucky-more">
    <summary><h2 class="more-title" id="kentucky-title">The Kentucky part</h2><span class="more-hint">Who can open a STABLE Kentucky account, what state law protects, the medical card, inheritance tax, free help</span></summary>
    <section id="kentucky-section" aria-labelledby="kentucky-title">
      <h3>Who can open a STABLE Kentucky account</h3>
      <p id="age-words"></p>
      <div id="age-ruler" class="age-ruler"></div>
      <h3>What Kentucky law says about the account</h3>
      <p>Kentucky Revised Statutes, section 164A.260(3), says that money in an account, or taken out of it for a qualified
        expense, is (in summary):</p>
      <ul>
        <li>exempt from attachment, execution and garnishment;</li>
        <li>disregarded when eligibility for, or the amount of, any public assistance program is worked out, unless federal
          law requires otherwise;</li>
        <li>not subject to claims by the Cabinet for Health and Family Services, unless federal law requires otherwise;</li>
        <li>passed to the beneficiary&rsquo;s estate on the beneficiary&rsquo;s death, unless federal law prohibits it.</li>
      </ul>
      <p>Section 164A.260(2) also exempts the account from Kentucky taxation. STABLE Kentucky&rsquo;s materials list a
        <span data-figure="stable-min"></span> smallest first deposit. That, and any account fee, are left out of the
        arithmetic on this page; the program can give its current terms.</p>
      <h3>Taking money back out</h3>
      <p>Money taken out of the account for housing and still in the bank on the next 1st counts toward the
        <span data-figure="line"></span> line (Social Security&rsquo;s operations manual, section SI 01130.740). Other
        withdrawals have their own rules; Social Security can say how a planned withdrawal is treated.</p>
      <h3>If a check is not payable: the medical card</h3>
      <p>Kentucky Medicaid that comes with SSI can lapse in months when the SSI check is not payable, and getting it back
        can take a new application (Social Security&rsquo;s operations manual, section SI 01715.010). That is not a permanent
        loss: Kentucky Medicaid also covers adults with low incomes, with no savings test. Whether rules that start in 2027
        change that is a question for Kentucky&rsquo;s Department for Community Based Services.</p>
      <h3>Kentucky inheritance tax</h3>
      <p>A grandchild is a Class A beneficiary under Kentucky Revised Statutes, section 140.070 (as amended in 2026), and
        section 140.080 exempts Class A beneficiaries in full, so the Kentucky inheritance tax on a grandchild&rsquo;s share
        is $0. Other relatives and friends can owe the tax.</p>
      <h3>Free help</h3>
      <p>Free benefits counselling (the work incentives program) for Breathitt County is run by Goodwill Industries of
        Kentucky, according to the state Office of Vocational Rehabilitation&rsquo;s provider list of March 2026. Legal aid
        offices give free civil legal help to people with low incomes, and Social Security answers questions about a case.</p>
    </section>
  </details>
  <details class="more" id="worked-more">
    <summary><h2 class="more-title" id="worked-title">How it&rsquo;s worked out</h2><span class="more-hint">The arithmetic in a few sentences, with the numbers above</span></summary>
    <section id="worked-section" aria-labelledby="worked-title">
      <ol id="worked" class="worked"></ol>
      <p class="aside">The same arithmetic runs for any numbers typed in. The built-in checks below compare it with answers
        worked out by hand.</p>
    </section>
  </details>
  <details class="more" id="rules-more">
    <summary><h2 class="more-title" id="rules-title">Rules this page uses</h2><span class="more-hint">Every figure and where it comes from, and what this page does not do</span></summary>
    <section id="rules-section" aria-labelledby="rules-title">
      <p class="aside">Every figure in the arithmetic comes from this list. Sources are named in words, each with the day it
        was read. The SSI amounts, the yearly ABLE limits and the banking-day allowance can be changed on the page; the
        figures fixed in law are shown as they are.</p>
      <div class="table-wrap" tabindex="0" role="region" aria-label="The rules, as a table"><table class="months-table rules-table" id="rules-table"></table></div>
      <h3>What this page does not do</h3>
      <ul class="limits">
        <li>It works out one person&rsquo;s case. A couple has a different line.</li>
        <li>It counts cash and money in the bank, not an inherited house, car or other property.</li>
        <li>It takes SSI as the only income.</li>
        <li>It takes one ABLE account per person, and does not know what an account already holds.</li>
        <li>It names no investment option and shows no growth.</li>
        <li>It is not legal, tax, benefits or investment advice, and it does not know a real case. The man in the example
          is invented.</li>
        <li>It works from rules published for 2026 and 2027.</li>
      </ul>
    </section>
  </details>
  <details class="more" id="checks-more">
    <summary><h2 class="more-title" id="checks-title">Built-in checks</h2><span class="more-hint" id="checks-hint">Examples with known answers, run each time the page opens</span></summary>
    <section id="checks-section" aria-labelledby="checks-title">
      <p class="aside">Each time this page opens it works through examples with known answers and compares the results.</p>
      <div id="checks"></div>
    </section>
  </details>




  <section id="print-sheet" class="print-sheet" aria-label="The plan as one printed page">
    <h2 class="ps-title">The $2,000 Line: a plan to take along</h2>
    <p id="ps-who"></p>
    <p id="ps-tag"></p>
    <p id="ps-headline" class="ps-headline"></p>
    <p id="ps-numbers"></p>
    <h3>Three paths, side by side (the same arithmetic; not ranked)</h3>
    <div id="ps-paths"></div>
    <div class="ps-cols">
      <div><h3>Checklist</h3><ul id="ps-checklist" class="ps-list"></ul></div>
      <div><h3>Questions to ask Social Security</h3><ul id="ps-questions" class="ps-list"></ul></div>
    </div>
    <h3>How it&rsquo;s worked out</h3>
    <ol id="ps-worked" class="ps-worked"></ol>
    <p class="ps-small"><strong>For education only.</strong> This page shows arithmetic against published rules. It is not
      legal, tax, benefits or investment advice, and it does not know your case. Confirm every date and amount with
      Social Security before acting on it. Copyright (c) 2026 Christian Smith and Liam Schilling, MIT License.</p>
    <p id="ps-notes" class="ps-notes"></p>
    <p id="ps-sources" class="ps-small"></p>
  </section>

  <footer>
    <p><strong>For education only.</strong> This page shows arithmetic against published rules. It is not legal, tax,
      benefits or investment advice, and it does not know your case. Confirm every date and amount with Social Security
      before acting on it.</p>
    <p>Nothing you type leaves this page. No outside code was used.</p>
    <p>Copyright (c) 2026 Christian Smith and Liam Schilling. Released under the MIT License.</p>
  </footer>
</main>

<script>
"use strict";

/* ENGINE:START */

/* =====================================================================================
   1. RULES
   Every figure the arithmetic uses, with where it comes from. Sources are named in
   words. "applies" is the period the figure covers; "checked" is the day the source
   was read; "status" says how sure the figure is.
   ===================================================================================== */

const RULES = {
  // The most countable money one person on SSI may have at the first moment of a month.
  line: {
    cents: 200000,
    label: "Countable money one person on SSI may have at the first moment of a month",
    source: "Code of Federal Regulations, title 20, section 416.1205 (the amount) and section 416.1207 (counted as of the first moment of the month)",
    applies: "In force since January 1, 1989",
    checked: "November 17, 2026",
    status: "The amount was read from the regulation. Its table does not say what happens at exactly $2,000; this page treats exactly $2,000 as within the limit, a reading to confirm with Social Security. A couple has a different line and is outside this page."
  },
  // An inheritance is income in the month it arrives and countable money from the next 1st.
  inheritance: {
    label: "An inheritance is income in the month it is received, and countable money from the first moment of the next month if it is still held",
    source: "Social Security operations manual, sections SI 00830.550 and SI 01110.600",
    applies: "Current manual text",
    checked: "November 17, 2026",
    status: "Read from the manual. Social Security may treat the day the estate closes as the day of receipt."
  },
  // The first $20 of unearned income in a month is not counted.
  incomeExclusion: {
    cents: 2000,
    label: "Unearned income not counted each month",
    source: "Code of Federal Regulations, title 20, section 416.1124(c)(12)",
    applies: "Current regulation text",
    checked: "November 17, 2026",
    status: "Read from the regulation. Assumes no other unearned income in the month the money arrives."
  },
  // Which month's income sets which month's check.
  monthByMonth: {
    label: "A month's check is normally worked out from income two months earlier; in the first month back after a month with no check, that month's own income is used",
    source: "Code of Federal Regulations, title 20, section 416.420(a) and (b)",
    applies: "Current regulation text",
    checked: "November 17, 2026",
    status: "Read from the regulation. This is why a large lump sum costs only the check for the month it arrives, and a small one lowers the check two months later."
  },
  // The full monthly SSI payment for one person, by calendar year.
  ssi: {
    centsByYear: { 2026: 99400, 2027: 102900 },
    label: "Full monthly SSI payment for one person",
    source: "Social Security operations manual, section SI 02001.020",
    applies: "2026 and 2027; later years are not published",
    checked: "November 17, 2026",
    status: "Read from the manual. Years outside the table reuse the nearest figure and are marked as not published."
  },
  // The most that can be paid into one ABLE account in a calendar year.
  ableCap: {
    centsByYear: { 2026: 2000000, 2027: 2000000 },
    label: "Most that can be paid into one ABLE account in a calendar year",
    source: "Social Security operations manual, section SI 01130.740 (2026); Internal Revenue Service, Revenue Procedure 2026-35 (2027)",
    applies: "2026 and 2027",
    checked: "2026 figure: November 17, 2026. 2027 figure: the revenue procedure was not re-read",
    status: "The 2026 figure was read from the manual. The 2027 figure rests on the revenue procedure alone, taken from the research notes for this page; to be re-read before publishing."
  },
  // The part of an ABLE account balance that SSI does not count.
  ableBalance: {
    cents: 10000000,
    label: "ABLE account balance that SSI does not count",
    source: "Social Security operations manual, section SI 01130.740, effective February 26, 2026",
    applies: "Current manual text",
    checked: "November 17, 2026",
    status: "Read from the manual: up to and including $100,000."
  },
  // Not used in the arithmetic; named in the Kentucky panel.
  stableMinimum: {
    cents: 2500,
    label: "Smallest first deposit into a STABLE Kentucky account",
    source: "STABLE Kentucky program questions and answers, and a State Treasurer's presentation, read through search results",
    applies: "Program terms as of November 2026",
    checked: "November 17, 2026",
    status: "Not used in the arithmetic. Sources on a yearly account fee disagree, so no fee is used either."
  },
  // Who may open an ABLE account: the disability began before this birthday.
  onsetBefore: {
    age: 46,
    sinceYear: 2026,
    label: "An ABLE account is open to a person whose disability began before this birthday",
    source: "Social Security operations manual, section SI 01130.740",
    applies: "Since January 1, 2026",
    checked: "November 17, 2026",
    status: "Read from the manual."
  },
  // The rule that applied until the end of 2025, shown beside the new one.
  onsetBeforeOld: {
    age: 26,
    label: "The earlier rule: disability began before this birthday",
    source: "Social Security operations manual, section SI 01130.740",
    applies: "Until December 31, 2025",
    checked: "November 17, 2026",
    status: "Read from the manual. Many web pages still show this older rule."
  },
  // Months in a row with no payable check before the case is closed.
  closeAfter: {
    months: 12,
    label: "Months in a row with no payable check before the case is closed",
    source: "Code of Federal Regulations, title 20, section 416.1335",
    applies: "Current regulation text",
    checked: "November 17, 2026",
    status: "Read from the regulation. Counted from the first month not eligible; the case closes at the start of the 13th month."
  },
  // A change is reported by this day of the month after it happens.
  reportBy: {
    day: 10,
    label: "A change is reported to Social Security by this day of the following month",
    source: "Social Security operations manual, section SI 02301.005, part B.3; Code of Federal Regulations, title 20, section 416.714(a)",
    applies: "Manual text in effect since March 11, 2026",
    checked: "November 18, 2026",
    status: "Read from the manual and the regulation: a report is late if it is not made within 10 days after the end of the month in which the change happened. Both say to report as soon as the change happens. The 10th is not moved when it falls on a weekend."
  },
  // SSI back pay is not counted for this many months after the month it is received.
  backPay: {
    months: 9,
    label: "Months after the month received in which SSI back pay is not counted",
    source: "Social Security operations manual, section SI 01130.600, part B.1; Code of Federal Regulations, title 20, section 416.1233(a)",
    applies: "Payments received on or after March 2, 2004",
    checked: "November 18, 2026",
    status: "Read from the manual and the regulation: the unspent part is not counted for the 9 calendar months after the month it is received. This page treats back pay as not being income, which holds for SSI back pay only. Social Security back pay is counted as income in the month it arrives and is outside this page."
  },
  // Days when banks do not move money, used for the banking-day counts.
  bankHolidays: {
    label: "Bank holidays: New Year's Day, the third Monday of January, the third Monday of February, the last Monday of May, June 19, July 4, the first Monday of September, the second Monday of October, November 11, the fourth Thursday of November, December 25",
    source: "Board of Governors of the Federal Reserve System, statistical release K.8, Holidays Observed by the Federal Reserve System, 2026 to 2030",
    applies: "Printed for 2026 to 2030; the same pattern is applied to other years",
    checked: "November 18, 2026",
    status: "Read from the release: when a holiday falls on a Sunday the Reserve Banks are closed the following Monday; when it falls on a Saturday they are open the Friday before. One bank, or the STABLE program, may keep other hours."
  },
  // How long the move is assumed to take. The reader types their own figure.
  allowance: {
    days: 10,
    label: "Banking days allowed for opening an account and moving the money",
    source: "No official figure exists",
    applies: "A starting figure the reader can change",
    checked: "November 17, 2026",
    status: "An allowance, not a rule."
  },
  // How far ahead the month-by-month working looks.
  horizon: {
    months: 120,
    label: "Months this page looks ahead",
    source: "A limit of this page, not a rule",
    applies: "Always",
    checked: "November 17, 2026",
    status: "Ten years."
  },
  // After this day the figures above may be out of date and the page says so.
  validThrough: {
    date: { y: 2027, m: 12, d: 31 },
    label: "Last day covered by the published figures on this page",
    source: "The latest year in the tables above",
    applies: "2026 and 2027",
    checked: "November 17, 2026",
    status: "After this day the page shows a notice that its figures may be out of date."
  }
};

/* The worked example: $16,500 arriving on Thursday, November 12, 2026. He is invented. */
const SAMPLE = {
  kind: "inheritance",                       // "inheritance" or "backpay"
  amountCents: 1650000,                      // the lump sum
  arrival: { y: 2026, m: 11, d: 12 },        // the day it arrives
  otherCents: 50000,                         // other countable money already on hand
  ssiCents: { 2026: 99400, 2027: 102900 },   // his monthly check, by year
  bufferCents: 50000,                        // room he wants to leave under the line
  monthlySpendCents: 100000,                 // what he lives on each month with no check
  onsetAge: 31,                              // age when the disability began
  priorStableCents: 0,                       // already paid into an ABLE account this year
  capCents: { 2026: 2000000, 2027: 2000000 },// yearly ABLE limit, by year
  allowanceDays: 10                          // banking days allowed for the move
};
const SAMPLE_TODAY = { y: 2026, m: 11, d: 12 };

/* The largest amount the page accepts: $999,999,999.99. */
const MAX_CENTS = 99999999999;


/* =====================================================================================
   2. DATES
   A date is a plain { y, m, d } object. Nothing here reads the clock or a time zone:
   "today" is always handed in. Day counts go through Date.UTC so that a daylight
   saving change never adds or drops a day.
   ===================================================================================== */

const MONTH_LENGTHS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
const WEEKDAY_NAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const MONTH_NAMES = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"];

function isLeapYear(y) {
  return (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;
}

function daysInMonth(y, m) {
  return m === 2 && isLeapYear(y) ? 29 : MONTH_LENGTHS[m - 1];
}

function isValidDate(dt) {
  return !!dt &&
    Number.isInteger(dt.y) && Number.isInteger(dt.m) && Number.isInteger(dt.d) &&
    dt.y >= 2000 && dt.y <= 2100 &&
    dt.m >= 1 && dt.m <= 12 &&
    dt.d >= 1 && dt.d <= daysInMonth(dt.y, dt.m);
}

/* Days since January 1, 1970. Two serials subtract to a whole number of days. */
function serial(dt) {
  return Math.round(Date.UTC(dt.y, dt.m - 1, dt.d) / 86400000);
}

function fromSerial(n) {
  const t = new Date(n * 86400000);
  return { y: t.getUTCFullYear(), m: t.getUTCMonth() + 1, d: t.getUTCDate() };
}

function daysBetween(from, to) {
  return serial(to) - serial(from);
}

function addDays(dt, n) {
  return fromSerial(serial(dt) + n);
}

/* 0 is Sunday, 6 is Saturday. January 1, 1970 was a Thursday. */
function weekday(dt) {
  return ((serial(dt) % 7) + 11) % 7;
}

function firstOfNextMonth(dt) {
  return dt.m === 12 ? { y: dt.y + 1, m: 1, d: 1 } : { y: dt.y, m: dt.m + 1, d: 1 };
}

/* A month as one whole number, so months can be counted and compared. */
function monthIdx(dt) {
  return dt.y * 12 + (dt.m - 1);
}

/* The first day of the month with that number. */
function fromMonthIdx(mi) {
  return { y: Math.floor(mi / 12), m: (mi % 12) + 1, d: 1 };
}


/* =====================================================================================
   3. BANKING DAYS
   ===================================================================================== */

const FIXED_HOLIDAYS = [
  { m: 1, d: 1, name: "New Year's Day" },
  { m: 6, d: 19, name: "Juneteenth National Independence Day" },
  { m: 7, d: 4, name: "Independence Day" },
  { m: 11, d: 11, name: "Veterans Day" },
  { m: 12, d: 25, name: "Christmas Day" }
];

/* which = 1 for the first, 2 for the second, and so on; which = -1 for the last. */
const FLOATING_HOLIDAYS = [
  { m: 1, weekday: 1, which: 3, name: "Birthday of Martin Luther King, Jr." },
  { m: 2, weekday: 1, which: 3, name: "Washington's Birthday" },
  { m: 5, weekday: 1, which: -1, name: "Memorial Day" },
  { m: 9, weekday: 1, which: 1, name: "Labor Day" },
  { m: 10, weekday: 1, which: 2, name: "Columbus Day" },
  { m: 11, weekday: 4, which: 4, name: "Thanksgiving Day" }
];

/* The day of the month on which the n-th (or last) given weekday falls. */
function nthWeekdayOfMonth(y, m, wantedWeekday, which) {
  if (which === -1) {
    const last = daysInMonth(y, m);
    const lastWeekday = weekday({ y: y, m: m, d: last });
    return last - ((lastWeekday - wantedWeekday + 7) % 7);
  }
  const firstWeekday = weekday({ y: y, m: m, d: 1 });
  return 1 + ((wantedWeekday - firstWeekday + 7) % 7) + 7 * (which - 1);
}

function fixedHolidayName(dt) {
  for (const h of FIXED_HOLIDAYS) {
    if (h.m === dt.m && h.d === dt.d) return h.name;
  }
  return "";
}

/* The holiday's name, or "" on an ordinary day. */
function bankHolidayName(dt) {
  const fixed = fixedHolidayName(dt);
  if (fixed) return fixed;
  if (weekday(dt) === 1) {
    const sunday = fixedHolidayName(addDays(dt, -1));
    if (sunday) return sunday + " (observed)";
  }
  for (const h of FLOATING_HOLIDAYS) {
    if (h.m === dt.m && dt.d === nthWeekdayOfMonth(dt.y, dt.m, h.weekday, h.which)) return h.name;
  }
  return "";
}

function isBankHoliday(dt) {
  return bankHolidayName(dt) !== "";
}

function isBankingDay(dt) {
  const wd = weekday(dt);
  return wd !== 0 && wd !== 6 && !isBankHoliday(dt);
}

/* Banking days from "from" up to, but not including, the deadline. */
function bankingDays(from, deadline) {
  let count = 0;
  for (let s = serial(from); s < serial(deadline); s += 1) {
    if (isBankingDay(fromSerial(s))) count += 1;
  }
  return count;
}

/* Weekday holidays in the same window, with their names. */
function holidaysBetween(from, deadline) {
  const found = [];
  for (let s = serial(from); s < serial(deadline); s += 1) {
    const day = fromSerial(s);
    const wd = weekday(day);
    const name = bankHolidayName(day);
    if (name && wd !== 0 && wd !== 6) found.push({ date: day, name: name });
  }
  return found;
}

/* Step back from the deadline until n banking days have been counted. A move that
   takes n banking days and starts on the returned day has those n days before the 1st. */
function startBy(deadline, n) {
  const needed = Math.max(1, n);
  let day = addDays(deadline, -1);
  let counted = 0;
  for (let guard = 0; guard < 2000; guard += 1) {
    if (isBankingDay(day)) {
      counted += 1;
      if (counted >= needed) return day;
    }
    day = addDays(day, -1);
  }
  return day;
}


/* =====================================================================================
   4. MONEY
   Money is whole cents everywhere. Text is turned into cents from its digits, never
   through a decimal fraction.
   ===================================================================================== */

/* Returns { cents, error }. Blank text gives { cents: null, error: null }. */
function parseMoney(text) {
  const raw = String(text === null || text === undefined ? "" : text).trim();
  if (raw === "") return { cents: null, error: null };
  if (/^[-−(]/.test(raw)) {
    return { cents: null, error: "Amounts here are zero or more. Leave out the minus sign." };
  }
  const cleaned = raw.replace(/^\$/, "").replace(/[,\s]/g, "");
  const whole = /^(\d+)(?:\.(\d{0,2}))?$/.exec(cleaned);
  const fraction = /^\.(\d{1,2})$/.exec(cleaned);
  if (!whole && !fraction) {
    if (/^\d*\.\d{3,}$/.test(cleaned)) {
      return { cents: null, error: "Use dollars and cents, like 1,250.50." };
    }
    return { cents: null, error: "Type a dollar amount in digits, like 1,250.50." };
  }
  const dollarsText = (whole ? whole[1] : "0").replace(/^0+(?=\d)/, "");
  const centsText = ((whole ? whole[2] : fraction[1]) || "").padEnd(2, "0");
  if (dollarsText.length > 9) {
    return { cents: null, error: "That is more than this page can work with." };
  }
  return { cents: Number(dollarsText) * 100 + Number(centsText), error: null };
}

/* "$15,500" for whole dollars, "$993.99" otherwise. */
function formatMoney(cents) {
  if (!Number.isFinite(cents)) return "an unknown amount";
  const whole = Math.round(Math.abs(cents));
  const dollars = String(Math.floor(whole / 100)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  const rest = whole % 100;
  const sign = cents < 0 && whole > 0 ? "-" : "";
  return sign + "$" + dollars + (rest === 0 ? "" : "." + (rest < 10 ? "0" : "") + rest);
}

/* Money as text for an input box: "16,500" or "1,250.50"; "" when there is no value. */
function moneyText(cents) {
  return cents === null || cents === undefined ? "" : formatMoney(cents).replace("$", "");
}

/* A whole number typed as text, such as an age. Returns { value, error };
   blank text gives { value: null, error: null }. */
function parseWhole(text, min, max, what) {
  const raw = String(text === null || text === undefined ? "" : text).trim();
  if (raw === "") return { value: null, error: null };
  if (!/^\d{1,4}$/.test(raw)) {
    return { value: null, error: what + " has to be a whole number in digits." };
  }
  const n = Number(raw);
  if (n < min || n > max) {
    return { value: null, error: what + " has to be from " + min + " to " + max + "." };
  }
  return { value: n, error: null };
}

/* A date typed into three boxes: month, day, year. Returns { date, error };
   three blank boxes give { date: null, error: null }. A two-digit year means 20xx. */
function parseDateParts(monthText, dayText, yearText) {
  const parts = [monthText, dayText, yearText].map(function (t) {
    return String(t === null || t === undefined ? "" : t).trim();
  });
  if (parts.every(function (p) { return p === ""; })) return { date: null, error: null };
  if (parts.some(function (p) { return p === ""; })) {
    return { date: null, error: "Fill in the month, the day and the year." };
  }
  if (!parts.every(function (p) { return /^\d{1,4}$/.test(p); })) {
    return { date: null, error: "Use digits only, like 11, 12 and 2026." };
  }
  const dt = {
    y: Number(parts[2]) + (parts[2].length <= 2 ? 2000 : 0),
    m: Number(parts[0]),
    d: Number(parts[1])
  };
  if (dt.y < 2000 || dt.y > 2100) return { date: null, error: "Use a year from 2000 to 2100." };
  if (!isValidDate(dt)) {
    return { date: null, error: "That day is not on the calendar. Check the month and the day." };
  }
  return { date: dt, error: null };
}

/* style "short": Tue Dec 1, 2026 - "long": Tuesday, December 1, 2026 - "day": Tuesday, December 1
   "plain": December 1, 2026 - "monthday": December 1 */
function formatDate(dt, style) {
  const dayName = WEEKDAY_NAMES[weekday(dt)];
  const monthName = MONTH_NAMES[dt.m - 1];
  if (style === "short") return dayName.slice(0, 3) + " " + monthName.slice(0, 3) + " " + dt.d + ", " + dt.y;
  if (style === "day") return dayName + ", " + monthName + " " + dt.d;
  if (style === "plain") return monthName + " " + dt.d + ", " + dt.y;
  if (style === "monthday") return monthName + " " + dt.d;
  return dayName + ", " + monthName + " " + dt.d + ", " + dt.y;
}

/* style "short": Oct 2027 - otherwise: October 2027 */
function formatMonth(mi, style) {
  const dt = fromMonthIdx(mi);
  const monthName = MONTH_NAMES[dt.m - 1];
  return (style === "short" ? monthName.slice(0, 3) : monthName) + " " + dt.y;
}


/* =====================================================================================
   5. THE RULES AS SMALL FUNCTIONS
   "inp" is an input object shaped like SAMPLE above.
   ===================================================================================== */

/* A figure for a year: published if the year is in the table; otherwise the nearest
   earlier year's figure (or the earliest one), marked known: false. */
function lookupByYear(table, year) {
  if (Object.prototype.hasOwnProperty.call(table, year)) return { cents: table[year], known: true };
  const years = Object.keys(table).map(Number).sort(function (a, b) { return a - b; });
  let nearest = years[0];
  for (const y of years) {
    if (y <= year) nearest = y;
  }
  return { cents: table[nearest], known: false };
}

/* The monthly check in a given year. */
function checkFor(inp, year) {
  return lookupByYear(inp.ssiCents, year);
}

/* The yearly ABLE limit in a given year. */
function capFor(inp, year) {
  return lookupByYear(inp.capCents, year);
}

/* Who may open an ABLE account. "now" follows the rule in force in the given year
   (the current rule when no year is given); "old" is the rule that ended with 2025. */
function ableEligible(onsetAge, year) {
  const known = Number.isInteger(onsetAge) && onsetAge >= 0;
  const underOld = known && onsetAge < RULES.onsetBeforeOld.age;
  const underNew = known && onsetAge < RULES.onsetBefore.age;
  const newRuleInForce = year === undefined || year >= RULES.onsetBefore.sinceYear;
  return { known: known, now: newRuleInForce ? underNew : underOld, old: underOld };
}

/* What the lump sum does as income in the month it arrives.
   lost:    counted income is at least the check, so that month's check has to be repaid.
   reduced: the person stays eligible, and the check two months later is lower.
   none:    back pay is not income; nor is $20 or less. */
function incomeEffect(inp) {
  const r = monthIdx(inp.arrival);
  if (inp.kind === "backpay") return { kind: "none", cents: 0, month: null, known: true };
  const countedIncome = inp.amountCents - RULES.incomeExclusion.cents;
  if (countedIncome <= 0) return { kind: "none", cents: 0, month: null, known: true };
  const check = checkFor(inp, inp.arrival.y);
  if (countedIncome >= check.cents) {
    return { kind: "lost", cents: check.cents, month: r, known: check.known };
  }
  const later = checkFor(inp, fromMonthIdx(r + 2).y);
  return { kind: "reduced", cents: Math.min(countedIncome, later.cents), month: r + 2, known: later.known };
}

/* The first month in which the money is counted against the line: the month after it
   arrives, or the tenth month after for back pay. */
function firstTestMonth(inp) {
  const r = monthIdx(inp.arrival);
  return inp.kind === "backpay" ? r + RULES.backPay.months + 1 : r + 1;
}

/* What he aims to have counted on the 1st: the line less the room he wants to leave. */
function targetFor(inp) {
  return Math.max(0, RULES.line.cents - inp.bufferCents);
}

/* How much has to be out of the bank before the 1st. */
function needOut(inp) {
  return Math.max(0, inp.otherCents + inp.amountCents - targetFor(inp));
}

/* The month in which acting can begin: the month the money arrives, or today's month
   when that is later. */
function actingMonth(inp, today) {
  const r = monthIdx(inp.arrival);
  return today ? Math.max(r, monthIdx(today)) : r;
}

/* The month whose first moment is the next count that can still be met: the first
   test month, or the month after "now" once that test has gone by. */
function deadlineMonthFor(inp, nowMonth) {
  return Math.max(firstTestMonth(inp), nowMonth + 1);
}

/* Room in an ABLE account for deposits made in the months fromMonth up to, but not
   including, toMonth. Room is counted by the calendar year of each deposit, less what
   was already paid in during priorYear, and never past the balance SSI does not count. */
function ableRoom(inp, fromMonth, toMonth, priorYear) {
  const years = [];
  let room = 0;
  let known = true;
  for (let m = fromMonth; m < toMonth; m += 1) {
    const year = fromMonthIdx(m).y;
    if (years.indexOf(year) !== -1) continue;
    years.push(year);
    const cap = capFor(inp, year);
    if (!cap.known) known = false;
    room += Math.max(0, cap.cents - (year === priorYear ? inp.priorStableCents : 0));
  }
  room = Math.min(room, Math.max(0, RULES.ableBalance.cents - inp.priorStableCents));
  return { years: years, known: known, roomCents: room };
}

/* How much of what has to leave fits into an ABLE account before the next 1st.
   With no "now" given, acting begins in the month the money arrives. */
function capPlan(inp, nowMonth, needCents) {
  const now = nowMonth === undefined ? monthIdx(inp.arrival) : Math.max(monthIdx(inp.arrival), nowMonth);
  const space = ableRoom(inp, now, deadlineMonthFor(inp, now), fromMonthIdx(now).y);
  const need = needCents === undefined ? needOut(inp) : needCents;
  const toStable = Math.min(need, space.roomCents);
  const leftover = need - toStable;
  return {
    years: space.years,
    known: space.known,
    roomCents: space.roomCents,
    toStableCents: toStable,
    leftoverCents: leftover,
    fits: leftover === 0,
    // Held in the bank, does the leftover put him over the line on the 1st?
    leftoverOverLine: leftover > RULES.line.cents - targetFor(inp)
  };
}


/* =====================================================================================
   6. MONTH BY MONTH
   One path, walked a month at a time from the month the money arrives.

   "nowMonth" is the month in which acting can begin: the arrival month, or a later
   month when the page is opened later. Months before it have already gone by with
   the money still in the bank, and that is so on every path.

   path "leave":  the money stays in the bank; he lives on it in months with no check.
   path "spend":  everything above his target is spent before the 1st on things SSI
                  does not count.
   path "stable": everything above his target goes into an ABLE account, up to the
                  yearly room. A part that does not fit is either spent before the 1st
                  (leftoverMode "spend") or held until the next year's room opens
                  (leftoverMode "wait").

   Row status:  "repay"       the month the money arrives, when it counts as income
                              of at least the check: that check has to be repaid
                "notpayable"  counted money is over the line at the first moment
                "paid"        at or under the line
                "closed"      after twelve months in a row with no payable check
   ===================================================================================== */

function simulatePath(inp, path, leftoverMode, nowMonth) {
  const mode = leftoverMode === "wait" ? "wait" : "spend";
  const line = RULES.line.cents;
  const target = targetFor(inp);
  const r = monthIdx(inp.arrival);
  const first = firstTestMonth(inp);
  const now = nowMonth === undefined ? r : Math.max(r, nowMonth);   // acting can begin in this month
  const deadlineMonth = Math.max(first, now + 1);                   // the next 1st that can still be met
  const effect = incomeEffect(inp);

  let other = inp.otherCents;      // other countable money
  let wind = inp.amountCents;      // what is left of the lump sum in the bank
  let stable = 0;                  // moved into the ABLE account on this path
  let things = 0;                  // spent on things SSI does not count
  let livedOn = 0;                 // spent on living in months with no check
  let held = null;                 // in the bank at the start of the month acting begins
  const paidIn = {};               // ABLE deposits by calendar year
  paidIn[fromMonthIdx(now).y] = inp.priorStableCents;

  let run = 0;                     // months in a row with no payable check
  let twelfth = null;
  let closedFrom = null;
  let backUnder = null;
  let hitBalanceLimit = false;
  const lost = { count: 0, cents: 0, knownCount: 0, knownCents: 0 };
  const rows = [];
  const deposits = [];

  function takeOut(amount) {
    const fromWind = Math.min(wind, amount);
    wind -= fromWind;
    const fromOther = Math.min(other, amount - fromWind);
    other -= fromOther;
    return fromWind + fromOther;
  }
  function overTarget() {
    return Math.max(0, other + wind - target);
  }
  function moveToStable(m) {
    const year = fromMonthIdx(m).y;
    const already = paidIn[year] || 0;
    const yearRoom = Math.max(0, capFor(inp, year).cents - already);
    const balanceRoom = Math.max(0, RULES.ableBalance.cents - inp.priorStableCents - stable);
    if (overTarget() > 0 && balanceRoom < yearRoom && balanceRoom < overTarget()) hitBalanceLimit = true;
    const moved = takeOut(Math.min(overTarget(), yearRoom, balanceRoom));
    if (moved > 0) {
      stable += moved;
      paidIn[year] = already + moved;
      deposits.push({ month: m, cents: moved });
    }
  }

  for (let m = r; m <= r + RULES.horizon.months; m += 1) {
    // The first moment of month m.
    if (m === now) held = other + wind;
    const counted = other + (m >= first ? wind : 0);
    const check = checkFor(inp, fromMonthIdx(m).y);
    let status;
    if (closedFrom !== null && m >= closedFrom) status = "closed";
    else if (m === r && effect.kind === "lost") status = "repay";
    else if (counted > line) status = "notpayable";
    else status = "paid";

    if (status === "repay" || status === "notpayable") {
      run += 1;
      if (run === RULES.closeAfter.months) {
        twelfth = m;
        closedFrom = m + 1;
      }
    } else if (status === "paid") {
      run = 0;
    }

    if (status === "notpayable" || (status === "closed" && counted > line)) {
      lost.count += 1;
      lost.cents += check.cents;
      if (check.known) {
        lost.knownCount += 1;
        lost.knownCents += check.cents;
      }
    }

    rows.push({
      month: m,
      counted: counted,
      inBank: other + wind,
      inStable: stable,
      status: status,
      check: check.cents,
      known: check.known,
      run: run
    });

    if (m >= first && counted <= line) {
      backUnder = m;
      if (path === "stable" && mode === "wait" && m >= now) moveToStable(m);   // top up with any new room
      break;
    }

    // During month m, after its first moment.
    const noCheck = status === "notpayable" || status === "closed";
    if (path === "leave" || m < now) {
      // Nothing is done with the money: it is lived on in months with no check.
      // Months before "now" have already gone by, so this holds for every path.
      if (noCheck) livedOn += takeOut(inp.monthlySpendCents);
    } else if (path === "spend") {
      if (m === deadlineMonth - 1) things += takeOut(overTarget());
    } else if (path === "stable") {
      if (noCheck && m > now) livedOn += takeOut(inp.monthlySpendCents);
      if (m < deadlineMonth || mode === "wait") moveToStable(m);
      if (m === deadlineMonth - 1 && mode === "spend") things += takeOut(overTarget());
    }
  }
  if (held === null) held = other + wind;

  // A smaller sum lowers the check two months later only if no month in between is missed.
  const reduced = effect.kind === "reduced" && rows.length > 1 &&
    rows[0].status === "paid" && rows[1].status === "paid"
    ? { month: effect.month, cents: effect.cents }
    : null;

  let countedOnFirst = null;
  for (const row of rows) {
    if (row.month === first) countedOnFirst = row.counted;
  }

  return {
    rows: rows,
    summary: {
      path: path,
      leftoverMode: path === "stable" ? mode : null,
      firstTest: first,
      actingFrom: now,              // the month in which acting begins
      heldCents: held,              // in the bank at the start of that month
      countedOnFirstCents: countedOnFirst,
      receipt: effect,              // the receipt month's check; kept apart from "lost"
      reduced: reduced,
      lost: lost,                   // checks not payable after the receipt month
      backUnder: backUnder,         // null: not at or under the line within the months looked at
      twelfth: twelfth,
      closedFrom: closedFrom,
      cushionCents: other + wind + stable,
      inBankCents: other + wind,
      inStableCents: stable,
      onThingsCents: things,
      livedOnCents: livedOn,
      deposits: deposits,
      hitBalanceLimit: hitBalanceLimit
    }
  };
}

/* The paths side by side. "stable" is null when the onset age rules the account out;
   "stableWait" exists only when part of the money does not fit this year. */
function comparePaths(inp, nowMonth) {
  const now = nowMonth === undefined ? monthIdx(inp.arrival) : Math.max(monthIdx(inp.arrival), nowMonth);
  const spend = simulatePath(inp, "spend", null, now);
  const need = Math.max(0, spend.summary.heldCents - targetFor(inp));
  const cap = capPlan(inp, now, need);
  const eligible = ableEligible(inp.onsetAge, fromMonthIdx(now).y).now;
  return {
    leave: simulatePath(inp, "leave", null, now),
    spend: spend,
    stable: eligible ? simulatePath(inp, "stable", "spend", now) : null,
    stableWait: eligible && cap.leftoverCents > 0 ? simulatePath(inp, "stable", "wait", now) : null
  };
}


/* =====================================================================================
   7. THE CLOCK
   ===================================================================================== */

/* How long there is before the money is counted. If that 1st has already gone by, the
   countdown moves to the next first of the month. */
function clock(inp, today) {
  const testDate = fromMonthIdx(firstTestMonth(inp));
  const passed = serial(today) >= serial(testDate);
  const deadline = passed ? firstOfNextMonth(today) : testDate;
  const from = serial(today) > serial(inp.arrival) ? today : inp.arrival;
  const begin = startBy(deadline, inp.allowanceDays);
  const afterArrival = firstOfNextMonth(inp.arrival);
  const reportBy = { y: afterArrival.y, m: afterArrival.m, d: RULES.reportBy.day };
  return {
    testDate: testDate,                  // the 1st on which the money is first counted
    passed: passed,                      // true once that 1st has begun
    deadline: deadline,                  // the 1st the countdown runs to
    from: from,                          // the later of today and the arrival day
    daysLeft: daysBetween(from, deadline),
    bankingDaysLeft: bankingDays(from, deadline),
    holidays: holidaysBetween(from, deadline),
    allowanceDays: inp.allowanceDays,
    startBy: begin,
    startByBeforeArrival: serial(begin) < serial(inp.arrival),
    startByPassed: serial(begin) < serial(today),
    reportBy: reportBy,
    reportPassed: serial(today) > serial(reportBy),
    // The 1st is not a banking day, so that month's check is paid early and may
    // already be in the bank when the 1st begins.
    checkLandsEarly: !isBankingDay(deadline)
  };
}

/* The window that one arrival day gives, whatever today is. */
function arrivalWindow(inp, arrival) {
  const alt = Object.assign({}, inp, { arrival: arrival });
  const first = firstTestMonth(alt);
  const testDate = fromMonthIdx(first);
  // Deposits already made belong to the year of the real arrival. They use up room
  // in this window only if the window reaches that year.
  const space = ableRoom(alt, monthIdx(arrival), first, inp.arrival.y);
  return {
    arrival: arrival,
    testDate: testDate,
    windowDays: daysBetween(arrival, testDate),
    bankingDays: bankingDays(arrival, testDate),
    effect: incomeEffect(alt),
    capYears: space.years,
    roomCents: space.roomCents,
    checkLandsEarly: !isBankingDay(testDate)
  };
}

/* "What if it were paid on another day?" Compares the two windows. */
function timingWhatIf(inp, altArrival) {
  if (!isValidDate(altArrival)) return null;
  const read = readInput(inp);
  if (read.problems.length > 0) return null;
  const base = arrivalWindow(read.input, read.input.arrival);
  const alt = arrivalWindow(read.input, altArrival);
  return { base: base, alt: alt, daysGained: alt.windowDays - base.windowDays };
}


/* =====================================================================================
   8. THE WHOLE PLAN
   ===================================================================================== */

/* Checks an input object and fills blanks with plain defaults.
   Returns { input, problems }, each problem being { field, message }. */
function readInput(inp) {
  const src = inp || {};
  const problems = [];

  function moneyProblem(v) {
    if (Number.isInteger(v) && v > MAX_CENTS) return " is more than this page can work with.";
    if (!Number.isInteger(v) || v < 0) return " has to be a dollar amount of zero or more.";
    return "";
  }
  function money(key, label, fallback) {
    const v = src[key];
    if (v === null || v === undefined) return fallback;
    const problem = moneyProblem(v);
    if (problem) {
      problems.push({ field: key, message: label + problem });
      return fallback;
    }
    return v;
  }
  function yearTable(key, label, fallbackTable) {
    const out = {};
    let given = src[key];
    if (given === null || given === undefined) given = {};
    if (typeof given !== "object" || Array.isArray(given)) {
      problems.push({ field: key, message: label + " has to be given year by year." });
      given = {};
    }
    for (const year of Object.keys(fallbackTable)) {
      const v = Object.prototype.hasOwnProperty.call(given, year) ? given[year] : null;
      const blank = v === null || v === undefined;
      const problem = blank ? "" : moneyProblem(v);
      if (problem) problems.push({ field: key, message: label + " for " + year + problem });
      out[year] = blank || problem ? fallbackTable[year] : v;
    }
    return out;
  }

  const clean = {};
  clean.kind = src.kind === "backpay" ? "backpay" : "inheritance";
  if (src.kind !== undefined && src.kind !== null && src.kind !== "backpay" && src.kind !== "inheritance") {
    problems.push({ field: "kind", message: "The kind of money has to be an inheritance or back pay." });
  }

  const problemsBeforeAmount = problems.length;
  clean.amountCents = money("amountCents", "The amount", 0);
  if (clean.amountCents === 0 && problems.length === problemsBeforeAmount) {
    problems.push({ field: "amountCents", message: "Enter an amount to see a plan." });
  }

  clean.arrival = src.arrival;
  if (src.arrival === null || src.arrival === undefined) {
    problems.push({ field: "arrival", message: "Enter the day the money arrives." });
  } else if (!isValidDate(src.arrival)) {
    problems.push({ field: "arrival", message: "That arrival day is not on the calendar. Check the month and the day." });
  }

  clean.otherCents = money("otherCents", "Other money", 0);
  if (clean.otherCents > RULES.line.cents) {
    // The page starts from someone who is within the line before the money arrives.
    problems.push({ field: "otherCents", message: "Other money is already over the " + formatMoney(RULES.line.cents) +
      " line before this money arrives. This page starts from someone who is within the line; Social Security " +
      "can say where such a case stands." });
  }
  clean.bufferCents = money("bufferCents", "Room to leave under the line", 0);
  if (clean.bufferCents > RULES.line.cents) {
    problems.push({ field: "bufferCents", message: "Room to leave under the line can be at most " + formatMoney(RULES.line.cents) + "." });
    clean.bufferCents = 0;
  }
  clean.monthlySpendCents = money("monthlySpendCents", "Monthly spending", 0);
  clean.priorStableCents = money("priorStableCents", "The amount already paid in this year", 0);
  clean.ssiCents = yearTable("ssiCents", "The SSI amount", RULES.ssi.centsByYear);
  clean.capCents = yearTable("capCents", "The yearly limit", RULES.ableCap.centsByYear);

  clean.onsetAge = null;
  if (src.onsetAge !== null && src.onsetAge !== undefined) {
    if (Number.isInteger(src.onsetAge) && src.onsetAge >= 0 && src.onsetAge <= 120) {
      clean.onsetAge = src.onsetAge;
    } else {
      problems.push({ field: "onsetAge", message: "The age when the disability began has to be a whole number from 0 to 120." });
    }
  }

  clean.allowanceDays = RULES.allowance.days;
  if (src.allowanceDays !== null && src.allowanceDays !== undefined) {
    if (Number.isInteger(src.allowanceDays) && src.allowanceDays >= 1 && src.allowanceDays <= 90) {
      clean.allowanceDays = src.allowanceDays;
    } else {
      problems.push({ field: "allowanceDays", message: "The allowance has to be a whole number of banking days from 1 to 90." });
    }
  }

  return { input: clean, problems: problems };
}

/* Everything the page shows, from one input object and one "today".
   Returns { ok: false, field, message, problems } when there is nothing to work out. */
function buildPlan(inp, today) {
  const read = readInput(inp);
  if (!isValidDate(today)) {
    read.problems.push({ field: "today", message: "The date to count from is not on the calendar." });
  }
  if (read.problems.length > 0) {
    return { ok: false, field: read.problems[0].field, message: read.problems[0].message, problems: read.problems };
  }
  const input = read.input;
  const time = clock(input, today);
  const now = actingMonth(input, today);
  const paths = comparePaths(input, now);
  const held = paths.spend.summary.heldCents;
  const need = Math.max(0, held - targetFor(input));
  return {
    ok: true,
    input: input,
    today: today,
    lineCents: RULES.line.cents,
    targetCents: targetFor(input),
    actingFrom: now,                 // the month in which acting can begin
    heldCents: held,                 // in the bank at the start of that month
    needOutCents: need,              // what has to leave to reach the target on the next 1st
    overLineCents: Math.max(0, held - RULES.line.cents),   // the part the rule itself requires
    effect: incomeEffect(input),
    firstTest: firstTestMonth(input),
    cap: capPlan(input, now, need),
    eligible: ableEligible(input.onsetAge, fromMonthIdx(now).y),
    clock: time,
    paths: paths,
    // Are the check amounts for the arrival year and the test year published?
    ratePublished: checkFor(input, input.arrival.y).known && checkFor(input, time.testDate.y).known,
    // Has the calendar passed the last day the figures cover?
    stale: serial(today) > serial(RULES.validThrough.date)
  };
}

/* ENGINE:END */


/* =====================================================================================
   STATE
   Everything the reader can change lives in state.data. A saved file holds exactly
   state.data (see FILE below).
   ===================================================================================== */

/* STATE:START */

/* The keys the arithmetic reads, in a fixed order. */
const INPUT_KEYS = ["kind", "amountCents", "arrival", "otherCents", "ssiCents", "bufferCents",
  "monthlySpendCents", "onsetAge", "priorStableCents", "capCents", "allowanceDays"];

function copyOf(value) {
  return JSON.parse(JSON.stringify(value));
}

/* The worked example. Its "today" is pinned to the day the money arrived, so the
   example reads the same on whatever day the page is opened. */
function sampleData() {
  const data = copyOf(SAMPLE);
  data.mode = "sample";
  data.asOf = copyOf(SAMPLE_TODAY);
  data.leftoverChoice = "spend";
  data.altArrival = { y: 2026, m: 12, d: 2 };
  data.ticks = {};
  data.notes = "";
  return data;
}

/* A clean sheet for the reader's own numbers: personal boxes blank, published figures
   kept, and the device's calendar in place of the example's pinned day. */
function blankData() {
  return {
    kind: "inheritance",
    amountCents: null,
    arrival: null,
    otherCents: null,
    ssiCents: copyOf(RULES.ssi.centsByYear),
    bufferCents: null,
    monthlySpendCents: null,
    onsetAge: null,
    priorStableCents: null,
    capCents: copyOf(RULES.ableCap.centsByYear),
    allowanceDays: RULES.allowance.days,
    mode: "own",
    asOf: null,
    leftoverChoice: "spend",
    altArrival: null,
    ticks: {},
    notes: ""
  };
}

/* Just the part of the data that the arithmetic reads. */
function engineInput(data) {
  const inp = {};
  for (const key of INPUT_KEYS) inp[key] = data[key];
  return inp;
}

/* Has the reader edited the example? */
function isSampleChanged(data) {
  return data.mode === "sample" &&
    JSON.stringify(engineInput(data)) !== JSON.stringify(engineInput(sampleData()));
}

/* STATE:END */


/* =====================================================================================
   FILE
   Saving the plan to a file and reading a saved file back. These functions take and
   return plain values, so the test script can run them without a browser. A saved file
   is read in full and checked here before anything on the page is touched.
   ===================================================================================== */

/* FILE:START */

const APP_ID = "ky-the-2000-line";
const FILE_KIND = "plan";
const FILE_SCHEMA = 1;               // the newest file format this page reads
const APP_VERSION = "1.0.0";
const MAX_FILE_SIZE = 1000000;       // about 1 MB; a saved plan is about 1 KB
const MAX_NOTES_CHARS = 5000;
const MAX_TICKS = 200;
const MONEY_KEYS = ["amountCents", "otherCents", "bufferCents", "monthlySpendCents", "priorStableCents"];

function pad2(n) {
  return (n < 10 ? "0" : "") + String(n);
}

/* "the-2000-line-plan-2026-11-19.json", from a local { y, m, d }. */
function fileNameFor(day) {
  return "the-2000-line-plan-" + day.y + "-" + pad2(day.m) + "-" + pad2(day.d) + ".json";
}

/* "2026-11-19T20:14:05-05:00": a clock reading in local time with its offset, built
   from local parts so the date never jumps to tomorrow in the evening. */
function localStamp(t) {
  const offset = -t.getTimezoneOffset();
  const size = Math.abs(offset);
  return t.getFullYear() + "-" + pad2(t.getMonth() + 1) + "-" + pad2(t.getDate()) + "T" +
    pad2(t.getHours()) + ":" + pad2(t.getMinutes()) + ":" + pad2(t.getSeconds()) +
    (offset < 0 ? "-" : "+") + pad2(Math.floor(size / 60)) + ":" + pad2(size % 60);
}

/* "8:14 p.m." */
function clockWords(t) {
  const h = t.getHours();
  return ((h + 11) % 12 + 1) + ":" + pad2(t.getMinutes()) + (h < 12 ? " a.m." : " p.m.");
}

function buildEnvelope(data, savedAt) {
  return {
    app: APP_ID,
    kind: FILE_KIND,
    schema: FILE_SCHEMA,
    appVersion: APP_VERSION,
    savedAt: savedAt,
    data: copyOf(data)
  };
}

/* The whole file, indented so a person can read it. */
function envelopeText(data, savedAt) {
  return JSON.stringify(buildEnvelope(data, savedAt), null, 2) + "\n";
}

function refusal(field, reason) {
  return { ok: false, field: field, message: reason + " Nothing was changed." };
}

function isPlainObject(v) {
  return v !== null && typeof v === "object" && !Array.isArray(v);
}

/* Two plans hold the same entries, whatever order the entries are written in. Used to say so
   when an opened file matches the screen, since the page then looks unchanged. */
function samePlan(a, b) {
  function canonical(v) {
    if (Array.isArray(v)) return "[" + v.map(canonical).join(",") + "]";
    if (isPlainObject(v)) {
      return "{" + Object.keys(v).sort().map(function (k) {
        return JSON.stringify(k) + ":" + canonical(v[k]);
      }).join(",") + "}";
    }
    return String(JSON.stringify(v));
  }
  return canonical(a) === canonical(b);
}

function hasKey(obj, key) {
  return Object.prototype.hasOwnProperty.call(obj, key);
}

function copyDate(dt) {
  return { y: dt.y, m: dt.m, d: dt.d };
}

function noNegativeZero(v) {
  return v === 0 ? 0 : v;
}

function tooLarge() {
  return refusal("file", "That file is too large to be a saved plan (a saved plan is about 1 KB).");
}

/* Read the text of a saved file. Returns { ok: true, data }, a fresh copy built from
   known keys only, or { ok: false, field, message } naming what is wrong. */
function readSavedText(text) {
  if (typeof text !== "string") return refusal("file", "That file could not be read as text.");
  if (text.length > MAX_FILE_SIZE) return tooLarge();
  const body = text.replace(/^/, "").trim();
  if (body === "") return refusal("file", "That file is empty.");
  let parsed;
  try {
    parsed = JSON.parse(body);
  } catch (err) {
    return refusal("file", "That isn’t a plan saved by The $2,000 Line: its text is not in the saved format, " +
      "or the file was cut short.");
  }
  return readSavedFile(parsed);
}

/* Check the outer wrapper of a saved file, then its data. */
function readSavedFile(file) {
  const notOurs = "That isn’t a plan saved by The $2,000 Line: ";
  if (!isPlainObject(file)) return refusal("file", notOurs + "it holds no saved plan.");
  if (file.app !== APP_ID) return refusal("app", notOurs + "its “app” entry is missing or names another program.");
  if (file.kind !== FILE_KIND) {
    return refusal("kind", "That file is from The $2,000 Line but is not a saved plan: its “kind” entry is missing or different.");
  }
  if (!Number.isInteger(file.schema) || file.schema < 1) {
    return refusal("schema", "That file’s format number (its “schema” entry) is missing or not a whole number.");
  }
  if (file.schema > FILE_SCHEMA) {
    return refusal("schema", "That file was made by a newer version of this page (file format " + file.schema +
      "; this page reads format " + FILE_SCHEMA + ").");
  }
  if (!isPlainObject(file.data)) return refusal("data", "That file holds no saved numbers: its “data” entry is missing.");
  return readSavedData(file.data);
}

/* Build the candidate. Unknown keys are dropped; a missing key takes the clean-sheet value. */
function readSavedData(data) {
  function bad(key, words) {
    return refusal(key, "That file can’t be opened. " + words + " (In the file: “" + key + "”.)");
  }
  function given(key) {
    return hasKey(data, key) && data[key] !== undefined ? data[key] : null;
  }

  // The numbers the arithmetic reads go through the same reader the page itself uses.
  const src = {};
  for (const key of INPUT_KEYS) src[key] = given(key);
  const read = readInput(src);
  const problems = read.problems.filter(function (p) {
    // A sheet with no amount or no day yet is waiting to be filled in, not faulty.
    if (p.field === "amountCents") return !(src.amountCents === null || src.amountCents === 0);
    if (p.field === "arrival") return src.arrival !== null;
    return true;
  });
  if (problems.length > 0) return bad(problems[0].field, problems[0].message);

  const out = {};
  for (const key of INPUT_KEYS) {
    if (key === "arrival") {
      out.arrival = src.arrival === null ? null : copyDate(src.arrival);
    } else if (key === "ssiCents" || key === "capCents") {
      out[key] = {};
      for (const year of Object.keys(read.input[key])) out[key][year] = noNegativeZero(read.input[key][year]);
    } else if (MONEY_KEYS.indexOf(key) !== -1 || key === "onsetAge") {
      out[key] = src[key] === null ? null : noNegativeZero(src[key]);
    } else {
      out[key] = read.input[key];      // kind and allowanceDays, with their defaults
    }
  }

  const mode = given("mode");
  if (mode !== "sample" && mode !== "own") {
    return bad("mode", "Which numbers are shown has to be the example or your own numbers.");
  }
  out.mode = mode;

  const asOf = given("asOf");
  if (asOf !== null && !isValidDate(asOf)) return bad("asOf", "The day the plan is counted from is not on the calendar.");
  out.asOf = asOf === null ? null : copyDate(asOf);

  const choice = given("leftoverChoice");
  if (choice !== null && choice !== "spend" && choice !== "wait") {
    return bad("leftoverChoice", "What happens to money that does not fit has to be “spend” or “wait”.");
  }
  out.leftoverChoice = choice === null ? "spend" : choice;

  const alt = given("altArrival");
  if (alt !== null && !isValidDate(alt)) {
    return bad("altArrival", "The other arrival day, for the timing comparison, is not on the calendar.");
  }
  out.altArrival = alt === null ? null : copyDate(alt);

  const ticks = given("ticks");
  out.ticks = {};
  if (ticks !== null) {
    if (!isPlainObject(ticks)) return bad("ticks", "The checklist ticks have to be a list of named yes-or-no marks.");
    const names = Object.keys(ticks);
    if (names.length > MAX_TICKS) return bad("ticks", "There are more checklist ticks than this page has.");
    for (const name of names) {
      if (!/^[a-z0-9-]{1,40}$/.test(name) || typeof ticks[name] !== "boolean") {
        return bad("ticks", "A checklist tick is not in the saved form.");
      }
      out.ticks[name] = ticks[name];
    }
  }

  const notes = given("notes");
  if (notes !== null && typeof notes !== "string") return bad("notes", "The notes have to be text.");
  if (notes !== null && notes.length > MAX_NOTES_CHARS) {
    return bad("notes", "The notes are longer than " + MAX_NOTES_CHARS.toLocaleString("en-US") + " characters.");
  }
  out.notes = notes === null ? "" : notes;

  return { ok: true, data: out };
}

/* FILE:END */

const NO_CHANGES = "No changes yet";

const state = {
  data: sampleData(),
  errors: {},      // box id -> { label, message } for a box that needs fixing
  dirty: false,    // true once something has changed since the page opened, was saved or was opened
  savedNote: NO_CHANGES   // what the pill says while nothing is unsaved
};

/* Today's date from the device, built from local parts. */
function todayLocal() {
  const t = new Date();
  return { y: t.getFullYear(), m: t.getMonth() + 1, d: t.getDate() };
}

function currentToday() {
  return state.data.asOf || todayLocal();
}

/* The plan for what is on the page now. A box with a message beside it stops the plan,
   so the page never shows figures worked out from a number that is not on screen. */
function currentPlan() {
  // The comparison day feeds only the timing what-if, so a message there does not stop the plan.
  const ids = Object.keys(state.errors).filter(function (id) { return id !== "f-alt"; });
  if (ids.length > 0) {
    const first = state.errors[ids[0]];
    return {
      ok: false,
      unreadable: true,
      field: ids[0],
      message: "Check the box “" + first.label + "”. " + first.message,
      problems: []
    };
  }
  return planView(buildPlan(engineInput(state.data), currentToday()), state.data.leftoverChoice);
}


/* =====================================================================================
   WORDS
   Every sentence the page builds from the arithmetic. These functions take a plan and
   return plain text, so they can be read and tested without a browser.
   ===================================================================================== */

/* WORDS:START */

/* "he" in the example, "you" for the reader's own numbers. */
function voiceFor(mode) {
  return mode === "sample"
    ? { him: "him", lives: "he lives" }
    : { him: "you", lives: "you live" };
}

function plural(n, one, many) {
  return n + " " + (n === 1 ? one : many);
}

/* 46 -> "46th", 21 -> "21st". */
function ordinal(n) {
  const lastTwo = n % 100;
  const last = n % 10;
  if (lastTwo >= 11 && lastTwo <= 13) return n + "th";
  if (last === 1) return n + "st";
  if (last === 2) return n + "nd";
  if (last === 3) return n + "rd";
  return n + "th";
}

function monthNameOf(mi) {
  return MONTH_NAMES[fromMonthIdx(mi).m - 1];
}

/* A day with its weekday. The year is added when it is not this year. */
function dayWords(dt, today) {
  return formatDate(dt, dt.y === today.y ? "day" : "long");
}

/* A day without its weekday. The year is added when it is not this year. */
function dateWords(dt, today) {
  return formatDate(dt, dt.y === today.y ? "monthday" : "plain");
}

/* The label over the answer: which numbers these are and which day they count from. */
function tagWords(data, today) {
  if (data.mode !== "sample") return "Your numbers: counted from today, " + formatDate(today, "long");
  if (isSampleChanged(data)) return "Example, changed: shown as of " + formatDate(today, "long");
  return "Example: shown as of the day the money arrived, " + formatDate(today, "long");
}

/* The headline as pieces of text. Pieces marked strong are the figures.
   Returns { parts: [{ text, strong }], days } where days is "19 days." or "". */
function headlineParts(plan) {
  if (!plan.ok) return { parts: [{ text: plan.message }], days: "" };

  const time = plan.clock;
  const today = plan.today;
  const need = formatMoney(plan.needOutCents);
  const by = dayWords(time.deadline, today);
  // When the money has not arrived yet, the days run from the day it arrives.
  const days = plural(time.daysLeft, "day", "days") +
    (serial(today) < serial(plan.input.arrival) ? " from the day the money arrives." : ".");
  const held = plan.heldCents;
  const line = formatMoney(plan.lineCents);

  if (plan.needOutCents === 0) {
    return {
      parts: [
        { text: "Nothing has to leave the bank. The money counted on " },
        { text: by, strong: true },
        { text: " is " + formatMoney(held) + ", which is within the " + line + " line." }
      ],
      days: ""
    };
  }
  if (time.passed) {
    return {
      parts: [
        { text: formatDate(time.testDate, "plain") + " has begun, so this money has been counted once already. " +
          "If it is still in the bank, " },
        { text: need, strong: true },
        { text: " has to be out before " },
        { text: by, strong: true },
        { text: " for the " + monthNameOf(monthIdx(time.deadline)) + " check to be payable." }
      ],
      days: days
    };
  }
  if (held <= plan.lineCents) {
    // Only the room the reader chose makes anything move; the line itself is not crossed.
    return {
      parts: [
        { text: need, strong: true },
        { text: " has to be out of the bank before " },
        { text: by, strong: true },
        { text: " to keep " + formatMoney(plan.input.bufferCents) + " of room under the line. Left alone, the money " +
          "counted that day is " + formatMoney(held) + ", which is still within the " + line + " line." }
      ],
      days: days
    };
  }
  return {
    parts: [
      { text: need, strong: true },
      { text: " has to be out of the bank before " },
      { text: by, strong: true },
      { text: "." }
    ],
    days: days
  };
}

/* The headline figure includes the room the reader chose under the line. This
   sentence splits it into the part the rule requires and the part that is a choice. */
function roomNote(plan) {
  if (!plan.ok || plan.needOutCents === 0 || plan.overLineCents === 0 || plan.input.bufferCents === 0) return "";
  return "That is " + formatMoney(plan.overLineCents) + " over the " + formatMoney(plan.lineCents) +
    " line, plus the " + formatMoney(plan.input.bufferCents) + " of room chosen under it.";
}

/* "15 checks not payable ($15,400), case closed from November 2027" */
function lostWords(s) {
  let words;
  if (s.lost.count === 0) words = "no further checks lost";
  else if (s.backUnder === null) words = "no check payable in the ten years this page looks ahead";
  else words = plural(s.lost.count, "check", "checks") + " not payable (" + formatMoney(s.lost.cents) + ")";
  if (s.closedFrom !== null) words += ", case closed from " + formatMonth(s.closedFrom, "long");
  return words;
}

/* The three one-line outcomes under the headline, each led by the cushion kept.
   Returns [{ lead, text }]; an empty list when nothing has to move. */
function outcomeLines(plan) {
  if (!plan.ok || plan.needOutCents === 0) return [];
  const lines = [];
  function add(sim, words) {
    lines.push({ lead: formatMoney(sim.summary.cushionCents) + " kept", text: " " + words + ": " + lostWords(sim.summary) + "." });
  }
  add(plan.paths.leave, "if it stays in the bank");
  add(plan.paths.spend, "if the rest is spent before the 1st on things SSI does not count");
  if (plan.paths.stable) {
    add(plan.paths.stable, "if the rest is moved to a STABLE Kentucky account");
  } else if (!plan.eligible.known) {
    lines.push({ lead: "STABLE Kentucky", text: ": type the age when the disability began to see this path." });
  } else {
    lines.push({ lead: "STABLE Kentucky", text: ": not open when the disability began at age " +
      RULES.onsetBefore.age + " or later." });
  }
  return lines;
}

/* What the money does to the check for the month it arrives. */
function receiptNote(plan) {
  if (!plan.ok) return "";
  const ask = "Confirm the dates and amounts with Social Security.";
  const effect = plan.effect;
  if (plan.input.kind === "backpay") {
    return "SSI back pay is not income, so no check has to be repaid. It is not counted for " +
      RULES.backPay.months + " months after the month it arrives. " + ask;
  }
  if (effect.kind === "lost") {
    return "On every path the " + monthNameOf(effect.month) + " check (" + formatMoney(effect.cents) +
      ") has to be repaid, because the money counts as income in the month it arrives. The cushion figures " +
      "on this page are before that repayment. " + ask;
  }
  if (effect.kind === "reduced") {
    return "Where no month is missed, the " + monthNameOf(effect.month) + " check is lower by " +
      formatMoney(effect.cents) + ", because the money counts as income in the month it arrives. " + ask;
  }
  return ask;
}

/* His question was whether to turn the money down. */
function refusalNote(plan) {
  if (!plan.ok || plan.input.kind !== "inheritance" || plan.needOutCents === 0) return "";
  return "Turning an inheritance down is not a way around the rule: Social Security’s manual lists a refused " +
    "inheritance as giving a resource away.";
}

/* Cautions shown under the answer. */
function noticeWords(plan) {
  const notes = [];
  if (!plan.ok) return notes;
  if (plan.clock.passed && plan.paths.spend.summary.lost.count > 0) {
    notes.push("The first count, on " + formatDate(plan.clock.testDate, "plain") + ", has already happened. This page " +
      "takes the money as still in the bank today, less living costs in each month no check came. The checks " +
      "already not payable are counted on every path. Social Security can say where the case stands now.");
  }
  if (!plan.ratePublished) {
    const year = checkFor(plan.input, plan.input.arrival.y).known ? plan.clock.testDate.y : plan.input.arrival.y;
    notes.push("The SSI amount for " + year + " is not in this page’s table, so the nearest published amount is " +
      "used. The boxes under “The numbers” can be changed to the right amount.");
  }
  if (plan.stale) {
    notes.push("The figures on this page were published for 2026 and 2027, and today is after " +
      formatDate(RULES.validThrough.date, "plain") + ". Check the current SSI amount and the yearly ABLE limit " +
      "before using this arithmetic.");
  }
  return notes;
}

const PATH_TITLES = {
  leave: "Leave it in the bank",
  spend: "Spend it down before the 1st",
  stable: "Move it to STABLE Kentucky"
};

/* One path as a card: a title, a sentence about it, and six rows that are the same
   on every card. Returns { key, title, about, extra, unavailable, rows }. */
function cardFor(plan, key, voice) {
  const inp = plan.input;
  const target = formatMoney(plan.targetCents);
  const card = { key: key, title: PATH_TITLES[key], about: "", extra: "", unavailable: "", rows: [] };

  if (key === "leave") {
    card.about = inp.monthlySpendCents > 0
      ? "The money stays in the bank. In each month with no check, " + voice.lives + " on " +
        formatMoney(inp.monthlySpendCents) + " of it; nothing is taken in the month it arrives."
      : "The money stays in the bank and none of it is spent.";
  } else if (key === "spend") {
    card.about = "Everything above " + target + " is spent before the 1st on things SSI does not count. " +
      "Social Security’s manual lists, within limits, the home, an automobile, household goods and personal " +
      "effects, and burial spaces and funds.";
  } else {
    card.about = "Everything above " + target + " goes into a STABLE Kentucky account, Kentucky’s ABLE program. " +
      "SSI does not count the first " + formatMoney(RULES.ableBalance.cents) + " in an ABLE account (this page does " +
      "not know what an account already holds), and an ABLE account from any state is treated the same way.";
  }

  const sim = plan.paths[key];
  if (!sim) {
    card.unavailable = !plan.eligible.known
      ? "Type the age when the disability began, under “The numbers”, to see this path."
      : "This path is not open when the disability began at age " + RULES.onsetBefore.age + " or later (the age typed is " +
        inp.onsetAge + "). A trust is a question for an attorney.";
    return card;
  }

  const s = sim.summary;
  const rows = sim.rows;
  const today = plan.today;
  const r = rows[0].month;
  const firstDate = fromMonthIdx(s.firstTest);

  if (key === "stable" && plan.cap.leftoverCents > 0) {
    card.extra = formatMoney(plan.cap.leftoverCents) + " does not fit under the yearly limit (" +
      formatMoney(plan.cap.roomCents) + " of room). " + (s.leftoverMode === "wait"
        ? "This card counts that part as kept in the bank and moved when the next year’s limit opens."
        : "This card counts that part as spent before the 1st on things SSI does not count.") +
      " “If it does not all fit”, below, shows both ways.";
  }

  // 1. Cushion kept
  const after = [];
  if (s.livedOnCents > 0) after.push(formatMoney(s.livedOnCents) + " lived on while no check came");
  if (s.onThingsCents > 0) after.push(formatMoney(s.onThingsCents) + " spent on things SSI does not count");
  let cushionNote = s.inStableCents > 0
    ? formatMoney(s.inStableCents) + " in STABLE and " + formatMoney(s.inBankCents) + " in the bank"
    : "in the bank";
  if (after.length > 0) cushionNote += ", after " + after.join(" and ");
  card.rows.push({ label: "Cushion kept", value: formatMoney(s.cushionCents), note: cushionNote });

  // 2. The check for the month the money arrives
  let receiptValue;
  let receiptNoteText = "";
  if (rows[0].status === "repay") {
    receiptValue = "Has to be repaid";
    receiptNoteText = formatMoney(rows[0].check) + ": the money counts as " + monthNameOf(r) + " income";
  } else if (rows[0].status === "paid") {
    receiptValue = "Paid";
    if (inp.kind === "backpay") receiptNoteText = "Back pay is not income";
    else if (s.reduced) receiptNoteText = "The " + monthNameOf(s.reduced.month) + " check is lower by " + formatMoney(s.reduced.cents);
  } else {
    receiptValue = "Not payable";
    receiptNoteText = "Other money is already over the line";
  }
  card.rows.push({ label: monthNameOf(r) + " check", value: receiptValue, note: receiptNoteText });

  // 3. Counted on the 1st
  const counted = s.countedOnFirstCents;
  card.rows.push({
    label: "Counted on " + dateWords(firstDate, today),
    value: formatMoney(counted),
    note: counted > plan.lineCents ? "over the line by " + formatMoney(counted - plan.lineCents) : "within the line"
  });

  // 4. Checks not payable after the arrival month
  let lostValue;
  let lostNote = "";
  if (s.lost.count === 0) {
    lostValue = "None";
  } else if (s.backUnder === null) {
    lostValue = "Every month for ten years";
    lostNote = "Ten years is as far as this page looks";
  } else {
    lostValue = plural(s.lost.count, "check", "checks") + ": " + formatMoney(s.lost.cents);
    if (s.lost.knownCount < s.lost.count) {
      lostNote = formatMoney(s.lost.knownCents) + " of that (" + plural(s.lost.knownCount, "check", "checks") +
        ") is at published amounts; later years reuse the last published amount";
    }
  }
  card.rows.push({ label: "Checks not payable after that", value: lostValue, note: lostNote });

  // 5. Within the line again
  let backValue;
  if (s.backUnder === null) backValue = "Not within ten years";
  else if (s.backUnder === s.firstTest && s.lost.count === 0) backValue = "Not over it at any point";
  else backValue = formatDate(fromMonthIdx(s.backUnder), "plain");
  card.rows.push({
    label: "Within the line again",
    value: backValue,
    note: s.closedFrom !== null && s.backUnder !== null
      ? "The case is closed by then, so checks do not start again by themselves"
      : ""
  });

  // 6. Case status
  card.rows.push(s.closedFrom === null
    ? { label: "Case status", value: "Open", note: "" }
    : { label: "Case status", value: "Closed from " + formatMonth(s.closedFrom, "long"),
        note: "After " + RULES.closeAfter.months + " months in a row with no payable check; a new application is needed" });

  return card;
}

/* Figures quoted in the fixed text of the page, taken from RULES so each lives in one place. */
function ruleFigures() {
  return {
    "line": formatMoney(RULES.line.cents),
    "ssi-2026": formatMoney(RULES.ssi.centsByYear[2026]),
    "ssi-2027": formatMoney(RULES.ssi.centsByYear[2027]),
    "cap-2026": formatMoney(RULES.ableCap.centsByYear[2026]),
    "cap-2027": formatMoney(RULES.ableCap.centsByYear[2027]),
    "onset": ordinal(RULES.onsetBefore.age),
    "onset-old": ordinal(RULES.onsetBeforeOld.age),
    "backpay-months": String(RULES.backPay.months),
    "allowance": String(RULES.allowance.days),
    "stable-min": formatMoney(RULES.stableMinimum.cents),
    "balance": formatMoney(RULES.ableBalance.cents)
  };
}

/* ---------- The three shelves: the chart and its table, as plain values ---------- */

const SHELF_KEYS = ["leave", "spend", "stable"];
const SHELF_MAX_MONTHS = 25;      // the chart shows at most this many months
const SHELF_MAX_BLOCKS = 18;      // the tallest stack, in blocks
const MARK_WORDS = {
  paid: "check paid",
  repay: "check has to be repaid",
  notpayable: "check not payable",
  closed: "case closed"
};

/* What the chart marks under a month. A closed case still over the line is a check not
   payable; a closed case at or under the line is marked as closed. */
function markFor(row) {
  if (row.status === "closed") return row.counted > RULES.line.cents ? "notpayable" : "closed";
  return row.status;
}

/* Everything the chart and its table show. Every path starts in the month the money
   arrives; once a path is at or under the line its walk stops, and its later columns
   repeat that month ("held"), with nothing more assumed. null when there is nothing to draw. */
function shelfModel(plan) {
  if (!plan.ok || plan.needOutCents === 0) return null;
  const start = plan.paths.leave.rows[0].month;
  let end = start;
  for (const key of SHELF_KEYS) {
    const sim = plan.paths[key];
    if (sim) end = Math.max(end, sim.rows[sim.rows.length - 1].month);
  }
  const cut = end - start + 1 > SHELF_MAX_MONTHS;
  if (cut) end = start + SHELF_MAX_MONTHS - 1;
  const months = [];
  for (let m = start; m <= end; m += 1) months.push(m);

  let peak = RULES.line.cents;
  const strips = SHELF_KEYS.map(function (key) {
    const sim = plan.paths[key];
    if (!sim) return { key: key, title: PATH_TITLES[key], cells: null, summary: null, flagMonth: null };
    const cells = months.map(function (m, i) {
      const held = i >= sim.rows.length;
      const row = sim.rows[held ? sim.rows.length - 1 : i];
      peak = Math.max(peak, row.counted, row.inStable);
      return { month: m, counted: row.counted, inStable: row.inStable, mark: markFor(row), held: held };
    });
    const twelfth = sim.summary.twelfth;
    return { key: key, title: PATH_TITLES[key], cells: cells, summary: sim.summary,
      flagMonth: twelfth !== null && twelfth <= end ? twelfth : null };
  });

  // Blocks of $1,000, or of $2,000 when a stack would pass 18 blocks. The blocks never
  // grow past that, so the line keeps its height; a taller stack is cut short with a break.
  const blockCents = peak > 100000 * SHELF_MAX_BLOCKS ? 200000 : 100000;
  const tallCents = blockCents * SHELF_MAX_BLOCKS;
  return { start: start, end: end, months: months, cut: cut, strips: strips, blockCents: blockCents,
    tallCents: tallCents, cutTall: peak > tallCents, lineCents: RULES.line.cents };
}

function capitalFirst(text) {
  return text.charAt(0).toUpperCase() + text.slice(1);
}

/* The line under a strip's title. */
function shelfCaption(strip) {
  const s = strip.summary;
  const parts = [];
  if (s.livedOnCents > 0) parts.push(formatMoney(s.livedOnCents) + " lived on while no check came");
  parts.push(lostWords(s));
  if (s.inStableCents > 0) parts.push(formatMoney(s.inStableCents) + " in STABLE, not counted");
  return capitalFirst(parts.join("; ")) + ".";
}

/* What a screen reader hears for a strip. */
function shelfDescription(model, strip) {
  const s = strip.summary;
  const firstCell = strip.cells.filter(function (c) { return c.month === s.firstTest; })[0];
  const words = [];
  if (firstCell) {
    words.push(formatMoney(firstCell.counted) + " counted on " + formatDate(fromMonthIdx(s.firstTest), "plain") + ".");
  }
  if (s.backUnder !== null && s.backUnder !== s.firstTest) {
    words.push("At or under the line from " + formatDate(fromMonthIdx(s.backUnder), "plain") + ".");
  }
  words.push(shelfCaption(strip));
  if (strip.flagMonth !== null) {
    words.push("A flag marks " + formatMonth(strip.flagMonth, "long") + ", the " + ordinal(RULES.closeAfter.months) +
      " month in a row with no payable check.");
  }
  words.push("The table under the chart lists every month.");
  return words.join(" ");
}

function shelfCutNote(model) {
  const words = [];
  if (model.cutTall) {
    words.push("Stacks over " + formatMoney(model.tallCents) + " are cut short and marked with a break; the table lists " +
      "every amount.");
  }
  if (model.cut) {
    words.push("The shelves stop at " + formatMonth(model.end, "long") + ", " + SHELF_MAX_MONTHS + " months from the " +
      "month the money arrives. A path still over the line then goes on past it.");
  }
  return words.join(" ");
}

/* The same months as a table: a header row, then one row per month. */
function shelfTable(model) {
  const strips = model.strips.filter(function (s) { return s.cells; });
  const head = ["1st of the month"].concat(strips.map(function (s) { return s.title; }));
  const rows = model.months.map(function (m, i) {
    return [formatMonth(m, "short")].concat(strips.map(function (s) {
      const c = s.cells[i];
      let words = formatMoney(c.counted) + " counted";
      if (c.inStable > 0) words += ", " + formatMoney(c.inStable) + " in STABLE";
      words += "; " + MARK_WORDS[c.mark];
      if (s.flagMonth === c.month) words += "; " + ordinal(RULES.closeAfter.months) + " month in a row";
      return words;
    }));
  });
  return { head: head, rows: rows };
}

/* ---------- Which STABLE walk the page shows ---------- */

/* When part of the money does not fit under this year's limit, the reader picks how the
   STABLE path treats that part: spent before the 1st, or held until the next year's limit.
   The plan keeps both walks; the cards, outcomes and shelves read "stable". */
function planView(plan, choice) {
  if (!plan.ok) return plan;
  const wait = choice === "wait" && plan.paths.stableWait !== null;
  return Object.assign({}, plan, {
    leftoverChoice: wait ? "wait" : "spend",
    paths: Object.assign({}, plan.paths, { stable: wait ? plan.paths.stableWait : plan.paths.stable, stableSpend: plan.paths.stable })
  });
}

/* ---------- The clock ---------- */

/* The last banking day before a 1st: when the 1st is not a banking day, that month's
   check is normally paid then. */
function earlyPayDay(first) {
  return startBy(first, 1);
}

function earlyCheckWords(first, today) {
  return formatDate(first, "plain") + " is not a banking day, so the " + monthNameOf(monthIdx(first)) + " check is " +
    "normally paid early, on " + dayWords(earlyPayDay(first), today) + ", and may already be in the bank when " +
    formatDate(first, "monthday") + " begins. Whether that check counts toward the line that day is a question for " +
    "Social Security.";
}

/* The clock as sentences: the window, holidays, the start-by day, the report, the check. */
function clockLines(plan) {
  if (!plan.ok) return [];
  const c = plan.clock;
  const today = plan.today;
  const lines = [];
  const fromWords = serial(c.from) > serial(today)
    ? "the day the money arrives, " + dayWords(c.from, today)
    : "today, " + dayWords(c.from, today);
  const banking = c.bankingDaysLeft === 0 ? "none of them a banking day"
    : c.bankingDaysLeft === 1 ? "1 of them a banking day"
    : c.bankingDaysLeft + " of them banking days";
  lines.push("From " + fromWords + ", to " + dayWords(c.deadline, today) + ": " + plural(c.daysLeft, "day", "days") +
    ", " + banking + ".");
  lines.push(c.holidays.length === 0
    ? "No bank holiday falls on a weekday in between."
    : "Bank holidays in between: " + c.holidays.map(function (h) {
      return h.name + ", " + dayWords(h.date, today);
    }).join("; ") + ".");
  let start = "If moving the money takes " + plural(c.allowanceDays, "banking day", "banking days") +
    ", counting the day it starts, that means starting by " + dayWords(c.startBy, today) + ".";
  if (c.startByBeforeArrival) {
    start += " That day is before the money arrives, so that many banking days are not there: from the day it " +
      "arrives there " + (c.bankingDaysLeft === 1 ? "is 1 banking day" : "are " + c.bankingDaysLeft + " banking days") + ".";
  } else if (c.startByPassed) {
    start += " That day has gone by: " + (c.bankingDaysLeft === 1 ? "1 banking day is" : c.bankingDaysLeft + " banking days are") +
      " left, counting today.";
  }
  lines.push(start);
  lines.push("A report to Social Security is due within " + RULES.reportBy.day + " days after the end of the month the " +
    "money arrives: by " + dayWords(c.reportBy, today) + "." + (c.reportPassed ? " That day has gone by." : ""));
  lines.push(c.checkLandsEarly
    ? earlyCheckWords(c.deadline, today)
    : dayWords(c.deadline, today) + " is a banking day, so the " + monthNameOf(monthIdx(c.deadline)) + " check is paid " +
      "that day.");
  if (plan.eligible.now && plan.cap.years.length > 0) {
    lines.push("A deposit to STABLE Kentucky before then counts toward the " + plan.cap.years.join(" and ") +
      " yearly limit" + (plan.cap.years.length > 1 ? "s" : "") + ": " + formatMoney(plan.cap.roomCents) + " of room." +
      (plan.cap.known ? "" : " A limit for that year is not published yet, so the last published figure is used."));
  }
  return lines;
}

/* ---------- The timing what-if ---------- */

function effectWords(effect) {
  if (effect.kind === "lost") return "the " + monthNameOf(effect.month) + " check has to be repaid";
  if (effect.kind === "reduced") return "the " + monthNameOf(effect.month) + " check is lower by " + formatMoney(effect.cents);
  return "no check is repaid";
}

/* Two arrival days side by side: bars in days, then what changes. null without a day to compare. */
function whatIfParts(plan, altArrival) {
  if (!plan.ok || !altArrival) return null;
  const w = timingWhatIf(plan.input, altArrival);
  if (!w) return null;
  const today = plan.today;
  const longest = Math.max(w.base.windowDays, w.alt.windowDays, 1);
  const bars = [w.base, w.alt].map(function (win, i) {
    return {
      label: (i === 0 ? "Arrives " : "If it arrived ") + formatDate(win.arrival, "short") + ": " +
        plural(win.windowDays, "day", "days") + " (" + plural(win.bankingDays, "banking day", "banking days") +
        ") before " + formatDate(win.testDate, "short"),
      share: Math.max(0.02, win.windowDays / longest)
    };
  });
  const lines = [];
  const gained = w.daysGained;
  lines.push(gained === 0 ? "The same number of days either way."
    : Math.abs(gained) + (gained > 0 ? " more " : " fewer ") + (Math.abs(gained) === 1 ? "day" : "days") +
      " before the money is counted.");
  const baseEffect = effectWords(w.base.effect);
  const altEffect = effectWords(w.alt.effect);
  lines.push(capitalFirst(baseEffect === altEffect ? "either way, " + altEffect + "."
    : "with " + formatDate(w.alt.arrival, "monthday") + ", " + altEffect + "; with " +
      formatDate(w.base.arrival, "monthday") + ", " + baseEffect + "."));
  if (w.base.capYears.join() !== w.alt.capYears.join() && plan.eligible.now) {
    lines.push("A deposit before that 1st counts toward the " + w.alt.capYears.join(" and ") + " yearly ABLE limit" +
      (w.alt.capYears.length > 1 ? "s" : "") + " instead of " + w.base.capYears.join(" and ") + ".");
  }
  if (w.alt.checkLandsEarly) lines.push(earlyCheckWords(w.alt.testDate, today));
  return { bars: bars, lines: lines, gained: gained, altEffect: w.alt.effect, altEarly: w.alt.checkLandsEarly };
}

/* ---------- When it does not all fit ---------- */

function notPayableMonths(sim) {
  return sim.rows.filter(function (r) { return markFor(r) === "notpayable"; }).map(function (r) {
    return formatMonth(r.month, "long");
  });
}

function joinWords(list) {
  if (list.length <= 1) return list.join("");
  return list.slice(0, -1).join(", ") + " and " + list[list.length - 1];
}

/* The two ways to treat the part that does not fit, each with what it costs. null when
   everything fits or the STABLE path is not open. Neither way is ranked. */
function leftoverParts(plan) {
  if (!plan.ok || !plan.paths.stableSpend || !plan.paths.stableWait || plan.cap.leftoverCents === 0) return null;
  const today = plan.today;
  const deadline = plan.clock.deadline;
  function costOf(sim) {
    const s = sim.summary;
    const months = notPayableMonths(sim);
    const named = s.lost.count > 0 && s.backUnder !== null && s.closedFrom === null && months.length === s.lost.count;
    const lost = !named ? lostWords(s)
      : (months.length === 1 ? "the " + months[0] + " check not payable" : "checks not payable in " + joinWords(months)) +
        " (" + formatMoney(s.lost.cents) + ")";
    return formatMoney(s.cushionCents) + " kept (" + formatMoney(s.inStableCents) + " in STABLE, " +
      formatMoney(s.inBankCents) + " in the bank); " + lost + ".";
  }
  const wait = plan.paths.stableWait;
  const lines = [];
  // Holding crosses a January 1, which is always a bank holiday.
  for (const r of wait.rows) {
    const dt = fromMonthIdx(r.month);
    if (dt.m === 1 && r.month > wait.rows[0].month) {
      lines.push(earlyCheckWords(dt, today));
      break;
    }
  }
  lines.push("A trust is a question for an attorney.");
  return {
    intro: formatMoney(plan.cap.leftoverCents) + " of the " + formatMoney(plan.needOutCents) + " does not fit: the yearly " +
      "limit leaves " + formatMoney(plan.cap.roomCents) + " of room before " + dayWords(deadline, today) + ". Here is " +
      "the same arithmetic both ways; this page does not choose between them.",
    spend: "Spent before the 1st on things SSI does not count: " + costOf(plan.paths.stableSpend),
    wait: "Kept in the bank and moved when the next year’s limit opens: " + costOf(wait),
    lines: lines
  };
}

/* ---------- The Kentucky panel: the age rule ---------- */

/* Who an ABLE account is open to, by the age the disability began, under the old and new rules. */
function ageWords(onsetAge, voice) {
  const oldAge = RULES.onsetBeforeOld.age;
  const newAge = RULES.onsetBefore.age;
  const rules = "The rule until December 31, 2025 was a disability that began before age " + oldAge + "; since January 1, " +
    "2026 it is before age " + newAge + ".";
  const e = ableEligible(onsetAge);
  if (!e.known) return rules + " Type the age when the disability began, under “The numbers”, to see where it falls.";
  const who = voice.lives.split(" ")[0];
  const at = "With a disability that began at " + onsetAge + ", " + who;
  if (e.old) return rules + " " + at + " can open an account under both rules.";
  if (e.now) return rules + " " + at + " could not open one under the old rule and can under the new one.";
  return rules + " " + at + " cannot open one under either rule.";
}

/* ---------- The dated checklist and the questions for Social Security ---------- */

/* Items with fixed ids, so ticks saved in a file find their item again. */
function checklistItems(plan) {
  if (!plan.ok) return [];
  const c = plan.clock;
  const today = plan.today;
  const items = [];
  items.push({ id: "report", text: "Money reported to Social Security (due by " + dayWords(c.reportBy, today) + ")" });
  if (plan.needOutCents > 0) {
    items.push({ id: "move", text: formatMoney(plan.needOutCents) + " out of the bank before " + dayWords(c.deadline, today) +
      " (a move that takes " + plural(c.allowanceDays, "banking day", "banking days") + " starts by " + dayWords(c.startBy, today) + ")" });
    items.push({ id: "receipts", text: "Receipts kept for anything bought with the money" });
  }
  if (plan.paths.stable && plan.needOutCents > 0) {
    items.push({ id: "account", text: "STABLE Kentucky account opened, if that is the path taken" });
  }
  items.push({ id: "statement", text: "Bank statement kept that shows the balance on " + formatDate(c.deadline, "plain") });
  if (plan.effect.kind === "lost") {
    items.push({ id: "repay", text: "Asked Social Security how the " + monthNameOf(plan.effect.month) + " check (" +
      formatMoney(plan.effect.cents) + ") is repaid" });
  }
  items.push({ id: "counselling", text: "Free benefits counselling asked for" });
  return items;
}

function socialSecurityQuestions(plan) {
  const list = [
    "Which day counts as the day the money was received?",
    "Does a transfer still in progress on the 1st count as moved?"
  ];
  if (plan.ok && plan.effect.kind === "lost") list.push("How is the " + monthNameOf(plan.effect.month) + " check repaid?");
  list.push("Is a check paid early, before a 1st that is not a banking day, counted on that 1st?");
  return list;
}

/* ---------- How it's worked out ---------- */

/* "1 × $994 + 14 × $1,029 = $15,400" for the checks a walk marks not payable. */
function lostSum(sim) {
  const groups = [];
  let total = 0;
  for (const r of sim.rows) {
    if (markFor(r) !== "notpayable") continue;
    total += r.check;
    const g = groups.filter(function (x) { return x.cents === r.check; })[0];
    if (g) g.count += 1;
    else groups.push({ cents: r.check, count: 1 });
  }
  if (groups.length === 0) return "none";
  return groups.map(function (g) { return g.count + " × " + formatMoney(g.cents); }).join(" + ") + " = " + formatMoney(total);
}

/* The arithmetic in sentences, with the numbers on the page. */
function workedOut(plan) {
  if (!plan.ok) return [];
  const inp = plan.input;
  const c = plan.clock;
  const today = plan.today;
  const when = formatDate(c.deadline, "plain");
  const lines = [];
  const sum = inp.otherCents + inp.amountCents;
  lines.push(plan.heldCents === sum
    ? "Counted on " + when + " if nothing moves: " + formatMoney(inp.otherCents) + " already on hand + " +
      formatMoney(inp.amountCents) + " = " + formatMoney(sum) + "."
    : "In the bank at the start of " + formatMonth(plan.actingFrom, "long") + ", after the months already gone by: " +
      formatMoney(plan.heldCents) + ".");
  const target = inp.bufferCents > 0
    ? "The line is " + formatMoney(plan.lineCents) + "; with " + formatMoney(inp.bufferCents) + " of room chosen under it, " +
      "the target is " + formatMoney(plan.targetCents) + ". "
    : "The line is " + formatMoney(plan.lineCents) + ". ";
  lines.push(target + (plan.needOutCents > 0
    ? formatMoney(plan.heldCents) + " − " + formatMoney(plan.targetCents) + " = " + formatMoney(plan.needOutCents) + " has to leave."
    : formatMoney(plan.heldCents) + " is within that, so nothing has to leave."));
  const e = plan.effect;
  if (inp.kind === "backpay") {
    lines.push("SSI back pay is not income, and it is not counted until " + formatDate(fromMonthIdx(plan.firstTest), "plain") +
      ", the 1st after the " + RULES.backPay.months + " months that follow the month it arrives.");
  } else if (e.kind !== "none") {
    const counted = inp.amountCents - RULES.incomeExclusion.cents;
    lines.push("As income in " + formatMonth(monthIdx(inp.arrival), "long") + ": " + formatMoney(inp.amountCents) + " − " +
      formatMoney(RULES.incomeExclusion.cents) + " = " + formatMoney(counted) + (e.kind === "lost"
        ? ", at least that month’s " + formatMoney(e.cents) + " check, so that check has to be repaid."
        : ", less than that month’s check, so the " + formatMonth(e.month, "long") + " check is lower by " + formatMoney(e.cents) + "."));
  }
  if (plan.needOutCents === 0) return lines;

  const leave = plan.paths.leave.summary;
  let leaveWords = "Leaving it in the bank: " + formatMoney(leave.countedOnFirstCents) + " is counted on " +
    formatDate(fromMonthIdx(leave.firstTest), "plain");
  if (inp.monthlySpendCents > 0) leaveWords += ", and " + formatMoney(inp.monthlySpendCents) + " is lived on in each month with no check";
  leaveWords += leave.backUnder !== null
    ? "; it is at or under the line again on " + formatDate(fromMonthIdx(leave.backUnder), "plain") + "."
    : "; it stays over the line for the ten years this page looks ahead.";
  leaveWords += " Checks not payable: " + lostSum(plan.paths.leave) + ".";
  if (leave.closedFrom !== null) {
    leaveWords += " The " + ordinal(RULES.closeAfter.months) + " month in a row with no payable check is " +
      formatMonth(leave.twelfth, "long") + ", so the case is closed from " + formatMonth(leave.closedFrom, "long") + ".";
  }
  lines.push(leaveWords);

  const spend = plan.paths.spend.summary;
  lines.push("Spending it down: " + formatMoney(spend.onThingsCents) + " spent before " + when + " on things SSI does not " +
    "count leaves " + formatMoney(spend.countedOnFirstCents) + " counted; " + lostWords(spend) + ".");

  const sim = plan.paths.stable;
  if (sim) {
    const s = sim.summary;
    lines.push("Moving it to STABLE Kentucky: " + formatMoney(s.inStableCents) + " ends up in the account, which SSI does " +
      "not count up to " + formatMoney(RULES.ableBalance.cents) + "; " + formatMoney(s.inBankCents) + " stays in the bank. " +
      "Cushion: " + formatMoney(s.inBankCents) + " + " + formatMoney(s.inStableCents) + " = " + formatMoney(s.cushionCents) +
      "; " + lostWords(s) + ".");
  }
  return lines;
}

/* ---------- Rules this page uses ---------- */

const RULE_CHANGE_WHERE = {
  ssi: "Can be changed under “The numbers”.",
  ableCap: "Can be changed under “The numbers”.",
  allowance: "Can be changed under “The clock”."
};

function ruleFigureWords(rule) {
  if (rule.centsByYear) {
    return Object.keys(rule.centsByYear).map(function (y) { return y + ": " + formatMoney(rule.centsByYear[y]); }).join("; ");
  }
  if (rule.cents !== undefined) return formatMoney(rule.cents);
  if (rule.age !== undefined) return "Before age " + rule.age;
  if (rule.day !== undefined) return "The " + ordinal(rule.day);
  if (rule.days !== undefined) return rule.days + " banking days";
  if (rule.months !== undefined) return rule.months + " months";
  if (rule.date !== undefined) return formatDate(rule.date, "plain");
  return "A rule";
}

/* One row per entry in RULES: figure, what it is, source, period, day checked, how sure. */
function ruleRows() {
  return Object.keys(RULES).map(function (key) {
    const r = RULES[key];
    return {
      key: key,
      figure: ruleFigureWords(r),
      label: r.label,
      source: r.source,
      applies: r.applies,
      checked: r.checked,
      status: r.status + (RULE_CHANGE_WHERE[key] ? " " + RULE_CHANGE_WHERE[key] : "")
    };
  });
}

/* ---------- The printed sheet ---------- */

/* The numbers the plan was worked out from, on one line. */
function numbersLine(plan) {
  if (!plan.ok) return plan.message;
  const i = plan.input;
  const parts = [
    (i.kind === "backpay" ? "SSI back pay of " : "An inheritance of ") + formatMoney(i.amountCents) + " arriving " +
      formatDate(i.arrival, "long"),
    formatMoney(i.otherCents) + " other money on hand",
    formatMoney(i.bufferCents) + " of room chosen under the line",
    formatMoney(i.monthlySpendCents) + " lived on in a month with no check",
    i.onsetAge === null ? "age when the disability began not typed" : "disability began at " + i.onsetAge,
    "SSI check " + Object.keys(i.ssiCents).map(function (y) { return formatMoney(i.ssiCents[y]) + " (" + y + ")"; }).join(", ")
  ];
  if (i.priorStableCents > 0) parts.push(formatMoney(i.priorStableCents) + " already paid into an ABLE account this year");
  parts.push("counted as of " + formatDate(plan.today, "long"));
  return parts.join(" · ") + ".";
}

/* The three cards as one table: a row per card row, a column per path. null when there are no paths. */
function printPathRows(plan, voice) {
  if (!plan.ok || plan.needOutCents === 0) return null;
  const cards = SHELF_KEYS.map(function (k) { return cardFor(plan, k, voice); });
  const shown = cards.filter(function (c) { return c.rows.length > 0; })[0];
  return {
    head: [""].concat(cards.map(function (c) { return c.title; })),
    rows: shown.rows.map(function (r, n) {
      return [r.label].concat(cards.map(function (c) {
        if (c.rows.length > 0) return c.rows[n].value;
        if (n > 0) return "";
        return plan.eligible.known ? "Not open at this age" : "Age not typed";
      }));
    })
  };
}

const PRINT_SOURCES = ["line", "inheritance", "incomeExclusion", "monthByMonth", "ssi", "ableCap", "ableBalance",
  "onsetBefore", "closeAfter", "reportBy"];

/* The sources behind the main figures, each named once. */
function sourcesLine() {
  const seen = [];
  const keys = [];
  for (const k of PRINT_SOURCES) {
    for (const part of RULES[k].source.split("; ")) {
      // "section SI 01130.740 (2026)" and "section SI 01130.740, effective ..." name the same section.
      const key = part.replace(/ \(\d{4}\)$/, "").replace(/, effective .*$/, "");
      if (keys.indexOf(key) === -1) {
        keys.push(key);
        seen.push(part);
      }
    }
  }
  return "Sources: " + seen.join("; ") + ".";
}

/* WORDS:END */


/* =====================================================================================
   RENDER
   Puts the words on the page. Text reaches the page through textContent only.
   ===================================================================================== */

function byId(id) {
  return document.getElementById(id);
}

function el(tag, attrs, kids) {
  const node = document.createElement(tag);
  if (attrs) {
    for (const key of Object.keys(attrs)) {
      if (key === "text") node.textContent = attrs[key];
      else node.setAttribute(key, attrs[key]);
    }
  }
  if (kids) {
    for (const kid of kids) {
      node.appendChild(typeof kid === "string" ? document.createTextNode(kid) : kid);
    }
  }
  return node;
}

function clear(node) {
  while (node.firstChild) node.removeChild(node.firstChild);
}

function renderTag(voice) {
  byId("mode-tag").textContent = tagWords(state.data, currentToday());
  byId("answer-title-text").textContent = "What the rule means for " + voice.him;
  byId("btn-own").hidden = state.data.mode !== "sample";
  byId("btn-sample").hidden = state.data.mode === "sample";
}

function renderHeadline(plan) {
  const box = byId("headline");
  const words = headlineParts(plan);
  clear(box);
  for (const part of words.parts) {
    box.appendChild(part.strong ? el("strong", { text: part.text }) : document.createTextNode(part.text));
  }
  if (words.days) box.appendChild(el("span", { class: "days", text: words.days }));
}

function renderOutcomes(plan) {
  const list = byId("outcomes");
  clear(list);
  for (const line of outcomeLines(plan)) {
    list.appendChild(el("li", null, [el("strong", { text: line.lead }), line.text]));
  }
  byId("room-note").textContent = roomNote(plan);
  byId("receipt-note").textContent = receiptNote(plan);
  byId("answer-why").hidden = !roomNote(plan) && !receiptNote(plan);
  byId("refusal-note").textContent = refusalNote(plan);
  const notices = byId("notices");
  clear(notices);
  for (const text of noticeWords(plan)) {
    notices.appendChild(el("p", { class: "notice", text: text }));
  }
}

function cardNode(card) {
  const titleId = "card-" + card.key + "-title";
  const node = el("article", { class: "card", "aria-labelledby": titleId }, [el("h3", { id: titleId, text: card.title })]);
  const about = el("details", { class: "why" }, [el("summary", { text: "About this path" }), el("p", { text: card.about })]);
  if (card.unavailable) {
    node.appendChild(el("p", { text: card.unavailable }));
    node.appendChild(about);
    return node;
  }
  if (card.extra) node.appendChild(el("p", { text: card.extra }));
  const list = el("dl");
  card.rows.forEach(function (row, i) {
    list.appendChild(el("dt", { text: row.label }));
    const value = el("dd", i === 0 ? { class: "cushion" } : null, [el("span", { class: "value", text: row.value })]);
    if (row.note) value.appendChild(el("span", { class: "note", text: row.note }));
    list.appendChild(value);
  });
  node.appendChild(list);
  node.appendChild(about);
  return node;
}

function renderCards(plan, voice) {
  const box = byId("cards");
  const notes = byId("path-notes");
  clear(box);
  clear(notes);
  if (!plan.ok) {
    notes.appendChild(el("p", { class: "notice", text: "The three paths appear here once there is an amount and a day above." }));
    return;
  }
  if (plan.needOutCents === 0) {
    notes.appendChild(el("p", { class: "notice", text: "Nothing has to move, so there are no paths to set side by side." }));
    return;
  }
  for (const key of ["leave", "spend", "stable"]) {
    box.appendChild(cardNode(cardFor(plan, key, voice)));
  }
}

/* ---------- The three shelves, drawn at the width they have ---------- */

const BLOCK_PX = 9;             // height of one block
const SHELF_RIGHT_PX = 48;      // room at the right for the line's label
let shelfWidth = 0;             // the width the shelves were last drawn at

/* An SVG element. Its namespace is read from the key's own inline SVG, so no address
   string is needed in the file. */
function svgNode(tag, attrs, text) {
  const node = document.createElementNS(byId("shelf-legend").querySelector("svg").namespaceURI, tag);
  for (const key of Object.keys(attrs || {})) node.setAttribute(key, String(attrs[key]));
  if (text !== undefined) node.textContent = text;
  return node;
}

function tenth(v) {
  return Math.round(v * 10) / 10;
}

/* One stack of blocks standing on baseY. Above the line (when hatchId is given) the
   blocks are hatched. Thin gaps mark each block. */
function drawStack(svg, x, w, baseY, fullCents, model, cls, hatchId) {
  if (fullCents <= 0) return;
  const cents = Math.min(fullCents, model.tallCents);
  const px = function (c) { return c / model.blockCents * BLOCK_PX; };
  const within = hatchId ? Math.min(cents, model.lineCents) : cents;
  svg.appendChild(svgNode("rect", { x: tenth(x), y: tenth(baseY - px(within)), width: tenth(w), height: tenth(px(within)), class: cls }));
  if (hatchId && cents > model.lineCents) {
    svg.appendChild(svgNode("rect", { x: tenth(x), y: tenth(baseY - px(cents)), width: tenth(w),
      height: tenth(px(cents - model.lineCents)), fill: "url(#" + hatchId + ")", class: "blk-over" }));
  }
  for (let k = 1; k * model.blockCents < cents; k += 1) {
    const y = tenth(baseY - k * BLOCK_PX);
    svg.appendChild(svgNode("line", { x1: tenth(x), x2: tenth(x + w), y1: y, y2: y, class: "blk-gap" }));
  }
  if (fullCents > cents) {
    // A break across the top: this stack goes on past what is drawn.
    const y = baseY - px(cents) + 6;
    const step = w / 4;
    let d = "M" + tenth(x - 1) + " " + tenth(y);
    for (let k = 1; k <= 4; k += 1) d += "L" + tenth(x + k * step - step / 2) + " " + tenth(y + (k % 2 ? -3 : 3)) + "L" + tenth(x + k * step) + " " + tenth(y);
    svg.appendChild(svgNode("path", { d: d + "L" + tenth(x + w + 1) + " " + tenth(y), class: "blk-break" }));
  }
}

/* The mark under a month: a shape, with its words in the key and the table. */
function drawMark(svg, kind, cx, cy) {
  if (kind === "paid") {
    svg.appendChild(svgNode("circle", { cx: cx, cy: cy, r: 4, class: "mk-paid" }));
  } else if (kind === "notpayable") {
    svg.appendChild(svgNode("path", { d: "M" + (cx - 4) + " " + (cy - 4) + "L" + (cx + 4) + " " + (cy + 4) +
      "M" + (cx + 4) + " " + (cy - 4) + "L" + (cx - 4) + " " + (cy + 4), class: "mk-notpayable" }));
  } else if (kind === "repay") {
    svg.appendChild(svgNode("rect", { x: cx - 4, y: cy - 4, width: 8, height: 8, class: "mk-repay" }));
  } else {
    svg.appendChild(svgNode("circle", { cx: cx, cy: cy, r: 4, class: "mk-closed" }));
  }
}

function drawShelf(model, strip, width) {
  const n = model.months.length;
  const colW = Math.max(12, Math.min(40, Math.floor((width - SHELF_RIGHT_PX) / n)));
  const gap = Math.max(2, Math.round(colW * 0.2));
  const right = n * colW;
  const fullW = right + SHELF_RIGHT_PX;
  const px = function (c) { return c / model.blockCents * BLOCK_PX; };
  let maxCounted = model.lineCents * 1.3;
  let maxStable = 0;
  for (const c of strip.cells) {
    maxCounted = Math.max(maxCounted, Math.min(c.counted, model.tallCents));
    maxStable = Math.max(maxStable, Math.min(c.inStable, model.tallCents));
  }
  const top = strip.flagMonth === null ? 6 : 30;
  const shelfY = top + Math.ceil(px(maxCounted));
  const plankY = maxStable > 0 ? shelfY + 16 + Math.ceil(px(maxStable)) : shelfY;
  const markY = plankY + 14;
  const letterY = markY + 19;
  const yearY = letterY + 13;
  const height = yearY + 4;
  const titleId = "shelf-" + strip.key + "-t";
  const descId = "shelf-" + strip.key + "-d";
  const svg = svgNode("svg", { width: fullW, height: height, viewBox: "0 0 " + fullW + " " + height, role: "img",
    "aria-labelledby": titleId, "aria-describedby": descId });
  svg.appendChild(svgNode("title", { id: titleId }, strip.title));
  svg.appendChild(svgNode("desc", { id: descId }, shelfDescription(model, strip)));

  const hatchId = "hatch-" + strip.key;
  const pattern = svgNode("pattern", { id: hatchId, width: 6, height: 6, patternUnits: "userSpaceOnUse", patternTransform: "rotate(45)" });
  pattern.appendChild(svgNode("rect", { width: 6, height: 6, class: "hatch-bg" }));
  pattern.appendChild(svgNode("line", { x1: 0, y1: 0, x2: 0, y2: 6, class: "hatch-line" }));
  svg.appendChild(svgNode("defs")).appendChild(pattern);

  strip.cells.forEach(function (c, i) {
    const x0 = i * colW;
    const dt = fromMonthIdx(c.month);
    if (dt.m === 1 && i > 0) svg.appendChild(svgNode("line", { x1: x0, x2: x0, y1: top - 4, y2: yearY - 10, class: "yr" }));
    drawStack(svg, x0 + gap / 2, colW - gap, shelfY, c.counted, model, "blk", hatchId);
    if (maxStable > 0) drawStack(svg, x0 + gap / 2, colW - gap, plankY, c.inStable, model, "blk-stable", null);
    drawMark(svg, c.mark, tenth(x0 + colW / 2), markY);
    svg.appendChild(svgNode("text", { x: tenth(x0 + colW / 2), y: letterY, "text-anchor": "middle", class: "ax" },
      MONTH_NAMES[dt.m - 1].charAt(0)));
    // The year under each January, and under the first month when there is room before the next January.
    if (dt.m === 1 || (i === 0 && (13 - dt.m) * colW >= 30)) {
      svg.appendChild(svgNode("text", { x: x0 + 1, y: yearY, class: "ax" }, String(dt.y)));
    }
  });

  svg.appendChild(svgNode("line", { x1: 0, x2: right, y1: shelfY + 1.5, y2: shelfY + 1.5, class: "shelf-line" }));
  if (maxStable > 0) {
    svg.appendChild(svgNode("line", { x1: 0, x2: right, y1: plankY + 1.5, y2: plankY + 1.5, class: "plank" }));
    svg.appendChild(svgNode("text", { x: right + 5, y: plankY - 13, class: "ax" }, "not"));
    svg.appendChild(svgNode("text", { x: right + 5, y: plankY - 1, class: "ax" }, "counted"));
  }
  const lineY = tenth(shelfY - px(model.lineCents));
  svg.appendChild(svgNode("line", { x1: 0, x2: right + 3, y1: lineY, y2: lineY, class: "gold" }));
  svg.appendChild(svgNode("text", { x: right + 5, y: lineY + 4, class: "gold-label" }, formatMoney(model.lineCents)));

  if (strip.flagMonth !== null) {
    const i = strip.flagMonth - model.start;
    const cx = tenth(i * colW + colW / 2);
    const stackTop = shelfY - px(Math.min(strip.cells[i].counted, model.tallCents));
    svg.appendChild(svgNode("line", { x1: cx, x2: cx, y1: 3, y2: tenth(stackTop - 2), class: "flag-pole" }));
    svg.appendChild(svgNode("path", { d: "M" + cx + " 3L" + (cx + 11) + " 7.5L" + cx + " 12Z", class: "flag" }));
    // About 6 px a letter at this size: the label goes on whichever side has room.
    let label = ordinal(RULES.closeAfter.months) + " month in a row";
    if (cx + 14 + label.length * 6 > fullW && cx - 4 - label.length * 6 < 0) label = ordinal(RULES.closeAfter.months) + " month";
    const onRight = cx + 14 + label.length * 6 <= fullW;
    svg.appendChild(svgNode("text", { x: onRight ? cx + 14 : cx - 4, y: 12, "text-anchor": onRight ? "start" : "end",
      class: "flag-label" }, label));
  }
  return svg;
}

function renderShelves(plan, voice) {
  const box = byId("shelves");
  const more = byId("shelves-more");
  const table = byId("shelves-table");
  clear(box);
  clear(more);
  clear(table);
  const model = shelfModel(plan);
  byId("shelf-legend").hidden = !model;
  byId("shelves-table-box").hidden = !model;
  byId("shelves-others").hidden = !model;
  byId("shelf-block").textContent = formatMoney(model ? model.blockCents : 100000);
  if (!model) {
    box.appendChild(el("p", { class: "notice", text: plan.ok
      ? "Nothing has to move, so there are no shelves to draw."
      : "The shelves appear here once there is an amount and a day above." }));
    return;
  }
  shelfWidth = box.clientWidth || 640;
  for (const strip of model.strips) {
    const part = el("div", { class: "shelf" }, [el("h3", { text: strip.title })]);
    if (strip.cells) {
      part.appendChild(el("p", { class: "shelf-cap", text: shelfCaption(strip) }));
      const drawing = drawShelf(model, strip, shelfWidth);
      const wrap = el("div", { class: "shelf-wrap" }, [drawing]);
      // Too wide to fit: the strip scrolls sideways, so it has to take the keyboard too.
      if (Number(drawing.getAttribute("width")) > shelfWidth) {
        wrap.setAttribute("tabindex", "0");
        wrap.setAttribute("role", "region");
        wrap.setAttribute("aria-label", strip.title + ", scrolls sideways");
      }
      part.appendChild(wrap);
    } else {
      part.appendChild(el("p", { class: "shelf-cap", text: cardFor(plan, strip.key, voice).unavailable }));
    }
    // The first path is drawn in view; the other two open with one click.
    (strip.key === model.strips[0].key ? box : more).appendChild(part);
  }
  const cutNote = shelfCutNote(model);
  if (cutNote) box.appendChild(el("p", { class: "notice", text: cutNote }));

  const t = shelfTable(model);
  table.appendChild(el("caption", { text: "Counted on the 1st of each month, and what happens to that month’s check" }));
  table.appendChild(el("thead", null, [el("tr", null, t.head.map(function (h) { return el("th", { scope: "col", text: h }); }))]));
  table.appendChild(el("tbody", null, t.rows.map(function (r) {
    return el("tr", null, [el("th", { scope: "row", text: r[0] })].concat(r.slice(1).map(function (c) {
      return el("td", { text: c });
    })));
  })));
}

/* ---------- The Kentucky part, the checklist, how it's worked out, the rules ---------- */

/* The age ruler: the old and new age rules as brackets, and a mark at the age typed.
   Decorative: the sentence above it says the same thing. */
function drawAgeRuler(onsetAge, width) {
  const top = Math.max(60, Math.min(120, (onsetAge || 0) + 10));
  const pad = 8;
  const w = Math.max(240, Math.min(width, 640));
  const x = function (age) { return tenth(pad + age / top * (w - 2 * pad)); };
  const svg = svgNode("svg", { width: w, height: 96, viewBox: "0 0 " + w + " 96", "aria-hidden": "true", focusable: "false" });
  // The mark goes in first, so the bracket labels sit on top of it.
  if (Number.isInteger(onsetAge)) {
    svg.appendChild(svgNode("line", { x1: x(onsetAge), x2: x(onsetAge), y1: 4, y2: 60, class: "ruler-mark" }));
  }
  const bracket = function (age, y, cls, words) {
    svg.appendChild(svgNode("line", { x1: x(0), x2: x(age), y1: y, y2: y, class: cls }));
    svg.appendChild(svgNode("line", { x1: x(age), x2: x(age), y1: y - 5, y2: y + 5, class: cls }));
    svg.appendChild(svgNode("text", { x: x(0) + 2, y: y - 6, class: "ruler-label" }, words));
  };
  bracket(RULES.onsetBeforeOld.age, 18, "ruler-old", "Before " + RULES.onsetBeforeOld.age + ": the rule until 2025");
  bracket(RULES.onsetBefore.age, 42, "ruler-new", "Before " + RULES.onsetBefore.age + ": the rule since 2026");
  svg.appendChild(svgNode("line", { x1: x(0), x2: x(top), y1: 60, y2: 60, class: "ruler-axis" }));
  for (let a = 0; a <= top; a += 10) {
    svg.appendChild(svgNode("line", { x1: x(a), x2: x(a), y1: 60, y2: 65, class: "ruler-tick" }));
    svg.appendChild(svgNode("text", { x: x(a), y: 78, "text-anchor": "middle", class: "ax" }, String(a)));
  }
  if (Number.isInteger(onsetAge)) {
    svg.appendChild(svgNode("circle", { cx: x(onsetAge), cy: 60, r: 4.5, class: "ruler-dot" }));
    svg.appendChild(svgNode("text", { x: x(onsetAge), y: 93, "text-anchor": "middle", class: "ruler-label" },
      "Began at " + onsetAge));
  }
  return svg;
}

function renderKentucky(voice) {
  byId("age-words").textContent = ageWords(state.data.onsetAge, voice);
  const box = byId("age-ruler");
  clear(box);
  box.appendChild(drawAgeRuler(state.data.onsetAge, box.clientWidth || 640));
}

function renderChecklist(plan) {
  const list = byId("checklist");
  clear(list);
  const items = checklistItems(plan);
  if (items.length === 0) list.appendChild(el("li", { text: "The checklist appears once there is an amount and a day above." }));
  for (const item of items) {
    const id = "tick-" + item.id;
    const box = el("input", { type: "checkbox", id: id, name: "tick", "data-tick": item.id, "aria-labelledby": id + "-text" });
    box.checked = state.data.ticks[item.id] === true;
    list.appendChild(el("li", null, [el("label", { class: "choice", for: id }, [box, el("span", { id: id + "-text", text: item.text })])]));
  }
  const questions = byId("ssa-questions");
  clear(questions);
  for (const q of socialSecurityQuestions(plan)) questions.appendChild(el("li", { text: q }));
}

function renderWorked(plan) {
  const list = byId("worked");
  clear(list);
  const lines = workedOut(plan);
  if (lines.length === 0) lines.push("The arithmetic appears here once there is an amount and a day above.");
  for (const line of lines) list.appendChild(el("li", { text: line }));
}

/* The rules table does not change, so it is built once. */
function renderRules() {
  const table = byId("rules-table");
  const rows = ruleRows();
  table.appendChild(el("caption", { text: rows.length + " rules and figures, from the RULES list in this file" }));
  table.appendChild(el("thead", null, [el("tr", null, ["Figure", "What it is", "Source", "Applies", "Read on", "How sure"]
    .map(function (h) { return el("th", { scope: "col", text: h }); }))]));
  table.appendChild(el("tbody", null, rows.map(function (r) {
    return el("tr", null, [el("th", { scope: "row", text: r.figure })].concat([r.label, r.source, r.applies, r.checked, r.status]
      .map(function (t) { return el("td", { text: t }); })));
  })));
}

/* The printed sheet, filled from the same words as the page. Also refreshed just
   before printing, so ticks and notes are current. */
function renderPrintSheet(plan, voice) {
  byId("ps-who").textContent = state.data.mode === "sample"
    ? document.querySelector(".built-for").textContent.replace(/\s+/g, " ").trim()
    : "Worked out for the numbers typed into the page.";
  byId("ps-tag").textContent = tagWords(state.data, currentToday());
  const head = headlineParts(plan);
  byId("ps-headline").textContent = head.parts.map(function (p) { return p.text; }).join("") + (head.days ? " " + head.days : "");
  byId("ps-numbers").textContent = numbersLine(plan);
  const box = byId("ps-paths");
  clear(box);
  const t = printPathRows(plan, voice);
  if (t) {
    box.appendChild(el("table", { class: "ps-table" }, [
      el("thead", null, [el("tr", null, t.head.map(function (h) { return el("th", { scope: "col", text: h }); }))]),
      el("tbody", null, t.rows.map(function (r) {
        return el("tr", null, [el("th", { scope: "row", text: r[0] })].concat(r.slice(1).map(function (c) { return el("td", { text: c }); })));
      }))
    ]));
  } else {
    box.appendChild(el("p", { text: plan.ok ? "Nothing has to move, so there are no paths to set side by side." : plan.message }));
  }
  const list = byId("ps-checklist");
  clear(list);
  for (const item of checklistItems(plan)) {
    list.appendChild(el("li", { text: (state.data.ticks[item.id] ? "☑ " : "☐ ") + item.text }));
  }
  const questions = byId("ps-questions");
  clear(questions);
  for (const q of socialSecurityQuestions(plan)) questions.appendChild(el("li", { text: q }));
  const worked = byId("ps-worked");
  clear(worked);
  for (const line of workedOut(plan)) worked.appendChild(el("li", { text: line }));
  const notes = state.data.notes;
  byId("ps-notes").textContent = notes ? "Notes: " + (notes.length > 450 ? notes.slice(0, 450) + "… (the rest is in the saved file)" : notes) : "";
  byId("ps-sources").textContent = sourcesLine();
}

/* A change that needs no new arithmetic (a tick, the notes): the pill and the file
   follow it, and nothing is drawn again under the reader's keyboard. */
function lightEdit(change) {
  const before = JSON.stringify(state.data);
  change();
  if (JSON.stringify(state.data) !== before) {
    state.dirty = true;
    clearFileMessages();
  }
  renderFileState();
}

/* Small pieces of the input area that follow the numbers. */
function renderInputNotes() {
  const arrival = state.data.arrival;
  // Deposits count against the year in which a deposit can next be made.
  byId("prior-year").textContent = arrival
    ? String(fromMonthIdx(actingMonth({ arrival: arrival }, currentToday())).y)
    : "the year the money arrives";
  byId("f-arrival-echo").textContent = arrival && !state.errors["f-arrival"] ? formatDate(arrival, "long") : "";
  const alt = state.data.altArrival;
  byId("f-alt-echo").textContent = alt && !state.errors["f-alt"] ? formatDate(alt, "long") : "";
}

/* ---------- The clock, the timing what-if, and when it does not all fit ---------- */

function renderClock(plan) {
  const list = byId("clock-lines");
  clear(list);
  const lines = plan.ok ? clockLines(plan) : ["The clock starts once there is an amount and a day above."];
  for (const line of lines) list.appendChild(el("li", { text: line }));

  const box = byId("whatif");
  clear(box);
  const parts = state.errors["f-alt"] ? null : whatIfParts(plan, state.data.altArrival);
  if (!parts) return;
  for (const bar of parts.bars) {
    const fill = el("div", { class: "bar-fill" });
    fill.style.width = Math.round(bar.share * 1000) / 10 + "%";
    box.appendChild(el("div", { class: "bar-row" }, [
      el("p", { class: "bar-label", text: bar.label }),
      el("div", { class: "bar-track", "aria-hidden": "true" }, [fill])
    ]));
  }
  for (const line of parts.lines) box.appendChild(el("p", { text: line }));
}

function renderFit(plan) {
  const parts = leftoverParts(plan);
  byId("fit-section").hidden = !parts;
  if (!parts) return;
  byId("fit-intro").textContent = parts.intro;
  byId("fit-spend").textContent = parts.spend;
  byId("fit-wait").textContent = parts.wait;
  const lines = byId("fit-lines");
  clear(lines);
  for (const line of parts.lines) lines.appendChild(el("p", { class: "aside", text: line }));
  byId("f-leftover-spend").checked = plan.leftoverChoice !== "wait";
  byId("f-leftover-wait").checked = plan.leftoverChoice === "wait";
}

function onBeforeUnload(event) {
  event.preventDefault();
  event.returnValue = true;
}

let unloadWarningOn = false;

function setText(node, text) {
  if (node.textContent !== text) node.textContent = text;
}

/* The pill beside Save, and the browser's question on closing the page, follow state.dirty.
   The closing question is wired only while something is unsaved. */
function renderFileState() {
  const pill = byId("save-pill");
  pill.setAttribute("data-dirty", state.dirty ? "yes" : "no");
  setText(byId("save-pill-mark"), state.dirty ? "!" : "✓");
  setText(byId("save-pill-text"), state.dirty ? "Unsaved changes" : state.savedNote);
  if (state.dirty && !unloadWarningOn) {
    window.addEventListener("beforeunload", onBeforeUnload);
    unloadWarningOn = true;
  } else if (!state.dirty && unloadWarningOn) {
    window.removeEventListener("beforeunload", onBeforeUnload);
    unloadWarningOn = false;
  }
  if (byId("save-text-box").open) byId("save-text").value = envelopeText(state.data, localStamp(new Date()));
}

function render() {
  const plan = currentPlan();
  const voice = voiceFor(state.data.mode);
  renderTag(voice);
  renderHeadline(plan);
  renderOutcomes(plan);
  renderCards(plan, voice);
  renderShelves(plan, voice);
  renderClock(plan);
  renderFit(plan);
  renderKentucky(voice);
  renderChecklist(plan);
  renderWorked(plan);
  renderPrintSheet(plan, voice);
  renderInputNotes();
  renderFileState();
  // The headline may point at a box that needs fixing; make sure that box is in view.
  for (const id of Object.keys(state.errors)) {
    const fold = byId(id) && byId(id).closest("details");
    if (fold && !fold.open) fold.open = true;
  }
}

function showValue(v) {
  return typeof v === "string" ? v : String(v);
}

function renderChecks(results) {
  const box = byId("checks");
  clear(box);
  // The panel's own line shows the result; a failure opens the panel so the warning is seen.
  byId("checks-hint").textContent = results.allPassed
    ? results.passed + " of " + results.total + " passed"
    : "Warning: only " + results.passed + " of " + results.total + " passed";
  if (results.allPassed) {
    box.appendChild(el("p", { class: "checks-summary", text: results.passed + " of " + results.total + " built-in checks passed." }));
  } else {
    byId("checks-more").open = true;
    box.appendChild(el("p", { class: "checks-warning", role: "alert", text: "Warning: only " + results.passed + " of " +
      results.total + " built-in checks passed. The numbers on this page may be wrong. Do not rely on them." }));
  }
  const list = el("ol", { class: "checks-list" });
  for (const c of results.cases) {
    const item = el("li", null, [
      el("span", { class: c.pass ? "mark-pass" : "mark-fail", text: c.pass ? "Passed: " : "Failed: " }),
      c.name
    ]);
    const inner = el("ul");
    for (const k of c.checks) {
      inner.appendChild(el("li", { text: k.label + ": " + showValue(k.got) +
        (k.pass ? "" : " (expected " + showValue(k.want) + ")") }));
    }
    item.appendChild(inner);
    list.appendChild(item);
  }
  box.appendChild(list);
}


/* =====================================================================================
   INPUTS AND EVENTS
   A box is read when the reader leaves it or presses Enter. Text that cannot be read
   is left as typed, with a message beside the box.
   ===================================================================================== */

/* Each date is three boxes (month, day, year) in a fieldset, read together. */
const DATE_GROUPS = {
  "f-arrival": { key: "arrival", label: "Day the money arrives" },
  "f-alt": { key: "altArrival", label: "Another day to compare" }
};

/* The words of the label that belongs to a box. */
function labelOf(box) {
  for (const label of document.querySelectorAll("label")) {
    if (label.getAttribute("for") === box.id) return label.textContent.trim().replace(/\s+/g, " ");
  }
  return "This box";
}

/* Show or clear the message beside a box, and remember it so the plan waits for a fix. */
function setBoxError(boxes, errorId, key, label, message) {
  const line = byId(errorId);
  line.textContent = message || "";
  line.hidden = !message;
  for (const box of boxes) {
    if (message) box.setAttribute("aria-invalid", "true");
    else box.removeAttribute("aria-invalid");
  }
  if (message) state.errors[key] = { label: label, message: message };
  else delete state.errors[key];
  // A box that needs fixing is never left inside a closed fold-out.
  const fold = message && boxes[0].closest("details");
  if (fold && !fold.open) fold.open = true;
}

function readMoneyBox(box) {
  const key = box.getAttribute("data-money");
  const year = box.getAttribute("data-year");
  const read = parseMoney(box.value);
  let message = read.error;
  let cents = read.cents;
  if (!message && key === "bufferCents" && cents !== null && cents > RULES.line.cents) {
    message = "Room to leave can be at most " + formatMoney(RULES.line.cents) + ".";
  }
  if (!message && key === "otherCents" && cents !== null && cents > RULES.line.cents) {
    message = "This is already over the " + formatMoney(RULES.line.cents) + " line before the money arrives. This page " +
      "starts from someone who is within the line; Social Security can say where such a case stands.";
  }
  if (!message) {
    if (year) {
      // A blank year box goes back to the published figure.
      if (cents === null) cents = (key === "ssiCents" ? RULES.ssi.centsByYear : RULES.ableCap.centsByYear)[year];
      state.data[key][year] = cents;
    } else {
      state.data[key] = cents;
    }
    box.value = moneyText(cents);
  }
  setBoxError([box], box.id + "-error", box.id, labelOf(box), message);
}

function readWholeBox(box) {
  const key = box.getAttribute("data-whole");
  const read = parseWhole(box.value, Number(box.getAttribute("data-min")), Number(box.getAttribute("data-max")),
    box.getAttribute("data-what"));
  if (!read.error) {
    // A blank allowance goes back to the starting figure.
    const value = read.value === null && key === "allowanceDays" ? RULES.allowance.days : read.value;
    state.data[key] = value;
    box.value = value === null ? "" : String(value);
  }
  setBoxError([box], box.id + "-error", box.id, labelOf(box), read.error);
}

function dateBoxes(groupId) {
  return ["m", "d", "y"].map(function (part) { return byId(groupId + "-" + part); });
}

function readDateBoxes(groupId) {
  const boxes = dateBoxes(groupId);
  const read = parseDateParts(boxes[0].value, boxes[1].value, boxes[2].value);
  if (!read.error) state.data[DATE_GROUPS[groupId].key] = read.date;
  setBoxError(boxes, groupId + "-error", groupId, DATE_GROUPS[groupId].label, read.error);
}

function groupOf(box) {
  return box.closest("fieldset").id;
}

function readKind() {
  state.data.kind = byId("f-kind-backpay").checked ? "backpay" : "inheritance";
}

/* Run one change, note whether anything really changed, and draw the page again. */
function edit(change) {
  const before = JSON.stringify([state.data, state.errors]);
  change();
  if (JSON.stringify([state.data, state.errors]) !== before) {
    state.dirty = true;
    clearFileMessages();     // a note about the last save or open no longer fits
  }
  render();
}

/* Write the data into the boxes, for a fresh start or a change of mode. */
function fillInputs() {
  const d = state.data;
  state.errors = {};
  for (const box of document.querySelectorAll("[data-money]")) {
    const key = box.getAttribute("data-money");
    const year = box.getAttribute("data-year");
    box.value = moneyText(year ? d[key][year] : d[key]);
    setBoxError([box], box.id + "-error", box.id, "", null);
  }
  for (const box of document.querySelectorAll("[data-whole]")) {
    const v = d[box.getAttribute("data-whole")];
    box.value = v === null || v === undefined ? "" : String(v);
    setBoxError([box], box.id + "-error", box.id, "", null);
  }
  for (const groupId of Object.keys(DATE_GROUPS)) {
    const dt = d[DATE_GROUPS[groupId].key];
    const boxes = dateBoxes(groupId);
    boxes[0].value = dt ? String(dt.m) : "";
    boxes[1].value = dt ? String(dt.d) : "";
    boxes[2].value = dt ? String(dt.y) : "";
    setBoxError(boxes, groupId + "-error", groupId, "", null);
  }
  byId("f-kind-backpay").checked = d.kind === "backpay";
  byId("f-kind-inheritance").checked = d.kind !== "backpay";
  byId("f-notes").value = d.notes;
  byId("questions-box").open = d.notes !== "";
}

/* Fixed text that quotes a figure gets it from RULES. */
function fillFigures() {
  const figures = ruleFigures();
  for (const spot of document.querySelectorAll("[data-figure]")) {
    spot.textContent = figures[spot.getAttribute("data-figure")] || "";
  }
}

/* A yes-or-no question shown on the page itself, right where the reader is looking. */
function askInPlace(slot, question, yesLabel, noLabel, onYes, returnTo) {
  clear(slot);
  const yes = el("button", { type: "button", class: "btn btn-solid", text: yesLabel });
  const no = el("button", { type: "button", class: "btn", text: noLabel });
  const box = el("div", { class: "ask", role: "group", "aria-label": question }, [el("p", { text: question }), yes, no]);
  function close() {
    clear(slot);
  }
  yes.addEventListener("click", function () {
    close();
    onYes();
  });
  no.addEventListener("click", function () {
    close();
    if (returnTo) returnTo.focus();
  });
  box.addEventListener("keydown", function (event) {
    if (event.key === "Escape") no.click();
  });
  slot.appendChild(box);
  no.focus();
}

/* Put a whole new set of data on the page: the example, a clean sheet or an opened file. */
function replaceData(data, savedNote) {
  clear(byId("mode-ask"));
  clear(byId("file-ask"));
  clearFileMessages();
  state.data = data;
  state.dirty = false;
  state.savedNote = savedNote;
  fillInputs();
  render();
}

function useOwnNumbers() {
  replaceData(blankData(), NO_CHANGES);
  byId("f-amount").focus();
  byId("numbers").scrollIntoView();
}

function showExample() {
  replaceData(sampleData(), NO_CHANGES);
  byId("btn-own").focus();
}


/* =====================================================================================
   SAVE, OPEN, PRINT, START OVER
   The file bar at the top. Every question and message appears beside the buttons,
   never in a pop-up, so all of it works inside a strict frame.
   ===================================================================================== */

function clearFileMessages() {
  clear(byId("file-alert"));
  byId("file-note").textContent = "";
}

/* A refused file: shown beside Open, in a region read out at once. */
function showFileError(text) {
  const box = byId("file-alert");
  clear(box);
  box.appendChild(el("p", { class: "file-error", text: text }));
}

function showFileNote(text) {
  byId("file-note").textContent = text;
}

/* A box still being typed in is read first, so the file matches the screen. */
function readActiveBox() {
  const box = document.activeElement;
  if (isTextBox(box)) readBox(box, true);
}

function savePlan() {
  readActiveBox();
  clear(byId("file-ask"));
  clearFileMessages();
  const waiting = Object.keys(state.errors);
  if (waiting.length > 0) {
    showFileNote("Not saved yet: the box “" + state.errors[waiting[0]].label + "” has a message beside it. " +
      "Fix that box, then save, so the file holds what is on the screen.");
    return;
  }
  const now = new Date();
  const name = fileNameFor(todayLocal());
  const text = envelopeText(state.data, localStamp(now));
  const wasDirty = state.dirty;
  const wasNote = state.savedNote;
  // Marked as saved before the download starts, so a browser that checks for unsaved
  // work while the file is handed over does not ask about it.
  state.dirty = false;
  state.savedNote = "Saved " + clockWords(now);
  renderFileState();
  try {
    const link = URL.createObjectURL(new Blob([text], { type: "application/json" }));
    const a = el("a", { href: link, download: name, hidden: "" });
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    setTimeout(function () { URL.revokeObjectURL(link); }, 1000);
    showFileNote("Your browser was handed the file “" + name + "”. Most browsers put it in your Downloads " +
      "folder. To open it again, drag it onto this page, or use “Open a saved plan” and look in Downloads. " +
      "If no file appears, use “Can’t download?” below.");
  } catch (err) {
    state.dirty = wasDirty;
    state.savedNote = wasNote;
    byId("save-text-box").open = true;
    renderFileState();
    showFileNote("This view could not hand over a file. The whole file is shown as text below: copy all of it " +
      "and keep it.");
  }
}

function openPlan() {
  readActiveBox();
  clear(byId("file-ask"));
  clearFileMessages();
  const pick = byId("file-pick");
  pick.value = "";
  pick.click();
}

function onFilePicked() {
  const pick = byId("file-pick");
  const file = pick.files && pick.files[0];
  pick.value = "";                       // so the same file can be chosen again
  if (file) openChosenFile(file);
}

/* A file dropped anywhere on the page opens like one chosen with the button. Without this,
   the browser would leave the page to show the dropped file. */
function draggingFiles(event) {
  const types = event.dataTransfer && event.dataTransfer.types;
  return !!types && Array.prototype.indexOf.call(types, "Files") !== -1;
}

function onFileDragOver(event) {
  if (!draggingFiles(event)) return;
  event.preventDefault();
  event.dataTransfer.dropEffect = "copy";
}

function onFileDropped(event) {
  if (!draggingFiles(event)) return;
  event.preventDefault();
  const files = event.dataTransfer.files;
  if (!files || files.length === 0) return;
  openChosenFile(files[0]);
  byId("btn-open").scrollIntoView({ block: "nearest" });
}

/* Read a file chosen in the file window or dropped on the page. */
function openChosenFile(file) {
  clear(byId("file-ask"));
  clearFileMessages();
  const name = "“" + String(file.name).slice(0, 80) + "”";
  // Say which file was chosen, so picking a photo or another file by mistake is plain to see.
  function refuse(result) {
    const notAPlan = result.field === "file" || result.field === "app";
    showFileError("You chose " + name + ". " + result.message + (notAPlan
      ? " A saved plan has a name like “" + fileNameFor(todayLocal()) + "” and is usually in your Downloads folder."
      : ""));
  }
  if (file.size > MAX_FILE_SIZE) {
    refuse(tooLarge());
    return;
  }
  const reader = new FileReader();
  reader.onload = function () {
    const result = readSavedText(String(reader.result));
    if (result.ok) offerOpened(result, name);
    else refuse(result);
  };
  reader.onerror = function () {
    refuse(refusal("file", "That file could not be read."));
  };
  reader.readAsText(file);
}

function openPasted() {
  clear(byId("file-ask"));
  clearFileMessages();
  offerOpened(readSavedText(byId("paste-text").value), "the pasted text");
}

/* A file that passed every check replaces the page, after asking if work here is unsaved. */
function offerOpened(result, source) {
  if (!result.ok) {
    showFileError(result.message);
    return;
  }
  const same = samePlan(result.data, state.data);
  function apply() {
    replaceData(result.data, "Opened a saved plan");
    showFileNote("Opened the plan from " + source + "." + (same
      ? " It holds the same numbers that were already on the screen, so nothing on the page changed."
      : ""));
    byId("btn-open").focus();
  }
  if (!state.dirty || same) {
    apply();
    return;
  }
  askInPlace(byId("file-ask"), "Replace what is on the screen with the plan from " + source +
    "? Your changes here are not saved.", "Yes, open it", "Keep my work", apply, byId("btn-open"));
}

function startOver() {
  clearFileMessages();
  const question = state.dirty
    ? "Start over? Every box goes back to the example, and your changes, which are not saved, are cleared."
    : "Start over? Every box goes back to the example.";
  askInPlace(byId("file-ask"), question, "Yes, start over", "Keep my work", function () {
    replaceData(sampleData(), NO_CHANGES);
    showFileNote("The page is back to the example.");
    byId("btn-reset").focus();
  }, byId("btn-reset"));
}

/* A strict frame ignores window.print() without a word, and then "beforeprint" never
   fires. If it has not fired about half a second later, say so in place. */
let printStarted = false;

function printPlan() {
  readActiveBox();
  clear(byId("file-ask"));
  clearFileMessages();
  printStarted = false;
  try {
    window.print();
  } catch (err) {
    printStarted = false;
  }
  setTimeout(function () {
    if (!printStarted) {
      showFileNote("Printing is blocked in this view. Save your file, open the page from your computer, and print there.");
    }
  }, 500);
}

function wireFileBar() {
  byId("btn-save").addEventListener("click", savePlan);
  byId("btn-open").addEventListener("click", openPlan);
  byId("btn-print").addEventListener("click", printPlan);
  byId("btn-reset").addEventListener("click", startOver);
  byId("file-pick").addEventListener("change", onFilePicked);
  document.addEventListener("dragover", onFileDragOver);
  document.addEventListener("drop", onFileDropped);
  byId("btn-paste-open").addEventListener("click", openPasted);
  const textBox = byId("save-text-box");
  textBox.addEventListener("toggle", function () {
    if (textBox.open) renderFileState();
  });
  byId("save-text").addEventListener("focus", function () {
    byId("save-text").select();
  });
  window.addEventListener("beforeprint", function () {
    printStarted = true;
    renderPrintSheet(currentPlan(), voiceFor(state.data.mode));
  });
  // Ctrl+S and Ctrl+O, or Cmd on a Mac. They work while the page has the keyboard.
  document.addEventListener("keydown", function (event) {
    if (!(event.ctrlKey || event.metaKey) || event.altKey) return;
    const key = String(event.key || "").toLowerCase();
    if (key === "s") {
      event.preventDefault();
      savePlan();
    } else if (key === "o") {
      event.preventDefault();
      openPlan();
    }
  });
}

function isTextBox(node) {
  return !!node && node.tagName === "INPUT" && node.type === "text";
}

/* Read whichever box an event came from. */
function readBox(box, dateEvenIfUnfinished) {
  if (box.hasAttribute("data-money")) {
    edit(function () { readMoneyBox(box); });
  } else if (box.hasAttribute("data-whole")) {
    edit(function () { readWholeBox(box); });
  } else if (box.hasAttribute("data-date")) {
    const groupId = groupOf(box);
    const allTyped = dateBoxes(groupId).every(function (b) { return b.value.trim() !== ""; });
    if (allTyped || dateEvenIfUnfinished) edit(function () { readDateBoxes(groupId); });
  }
}

function wireEvents() {
  document.addEventListener("change", function (event) {
    const box = event.target;
    if (isTextBox(box)) readBox(box, false);
    else if (box && box.name === "kind") edit(readKind);
    else if (box && box.name === "leftover") edit(function () { state.data.leftoverChoice = box.value === "wait" ? "wait" : "spend"; });
    else if (box && box.name === "tick") {
      lightEdit(function () {
        const tick = box.getAttribute("data-tick");
        if (box.checked) state.data.ticks[tick] = true;
        else delete state.data.ticks[tick];
      });
    }
  });

  document.addEventListener("keydown", function (event) {
    if (event.key === "Enter" && isTextBox(event.target)) readBox(event.target, true);
  });

  // The three date boxes are read together once the reader leaves the group.
  // The three boxes of a date are read together once the reader leaves the group.
  for (const groupId of Object.keys(DATE_GROUPS)) {
    const group = byId(groupId);
    group.addEventListener("focusout", function (event) {
      if (!group.contains(event.relatedTarget)) edit(function () { readDateBoxes(groupId); });
    });
  }

  // The shelves are drawn at the width they have, so they are drawn again when it changes.
  let resizeQueued = false;
  window.addEventListener("resize", function () {
    if (resizeQueued) return;
    resizeQueued = true;
    requestAnimationFrame(function () {
      resizeQueued = false;
      if (byId("shelves").clientWidth !== shelfWidth) {
        renderShelves(currentPlan(), voiceFor(state.data.mode));
        renderKentucky(voiceFor(state.data.mode));
      }
    });
  });

  // Step 2 shows short labels; the longer help under each box appears on request.
  byId("btn-help").addEventListener("click", function () {
    const on = byId("numbers").classList.toggle("show-help");
    byId("btn-help").setAttribute("aria-pressed", on ? "true" : "false");
    byId("btn-help").textContent = on ? "Hide the help" : "Show help for each box";
  });

  // The age ruler is drawn at the width it has, which is known only once its panel is open.
  byId("kentucky-more").addEventListener("toggle", function () {
    if (byId("kentucky-more").open) renderKentucky(voiceFor(state.data.mode));
  });

  byId("f-notes").addEventListener("input", function () {
    lightEdit(function () { state.data.notes = byId("f-notes").value.slice(0, MAX_NOTES_CHARS); });
  });

  byId("btn-own").addEventListener("click", useOwnNumbers);
  byId("btn-sample").addEventListener("click", function () {
    if (!state.dirty) {
      showExample();
      return;
    }
    askInPlace(byId("mode-ask"), "Replace your numbers with the example? What you typed will be cleared.",
      "Yes, show the example", "Keep my numbers", showExample, byId("btn-sample"));
  });
}


/* =====================================================================================
   SELF_TESTS
   Known-answer examples, worked by hand first. The page runs them every time it opens
   and shows the result under "Built-in checks". Each check is [what, got, expected].
   ===================================================================================== */

/* CHECKS:START */

function sampleWith(changes) {
  return Object.assign({}, SAMPLE, changes);
}

function rowFor(sim, y, m) {
  const wanted = monthIdx({ y: y, m: m, d: 1 });
  for (const row of sim.rows) {
    if (row.month === wanted) return row;
  }
  return { status: "no such month", counted: -1, check: -1 };
}

/* True if any number inside the value is not a finite number. */
function hasBadNumber(value) {
  if (typeof value === "number") return !Number.isFinite(value);
  if (value && typeof value === "object") {
    for (const key of Object.keys(value)) {
      if (hasBadNumber(value[key])) return true;
    }
  }
  return false;
}

function monthOrNever(mi) {
  return mi === null ? "never" : formatMonth(mi, "short");
}

const SELF_TESTS = [
  { n: 1, name: "The example: $16,500 arrives on November 12, 2026", run: function () {
    const p = buildPlan(SAMPLE, SAMPLE_TODAY);
    return [
      ["Day the money is first counted", formatDate(p.clock.testDate, "short"), "Tue Dec 1, 2026"],
      ["Days left", p.clock.daysLeft, 19],
      ["Banking days left", p.clock.bankingDaysLeft, 12],
      ["Has to leave the bank", formatMoney(p.needOutCents), "$15,500"],
      ["Fits under this year's limit", p.cap.fits, true],
      ["November check", p.effect.kind + " " + formatMoney(p.effect.cents), "lost $994"],
      ["Report by", formatDate(p.clock.reportBy, "short"), "Thu Dec 10, 2026"],
      ["Start by, allowing 10 banking days", formatDate(p.clock.startBy, "short"), "Mon Nov 16, 2026"]
    ];
  } },
  { n: 2, name: "The example, money left in the bank", run: function () {
    const sim = simulatePath(SAMPLE, "leave");
    const s = sim.summary;
    return [
      ["Counted on December 1", formatMoney(s.countedOnFirstCents), "$17,000"],
      ["At or under the line again", monthOrNever(s.backUnder), "Mar 2028"],
      ["Counted on that day", formatMoney(rowFor(sim, 2028, 3).counted), "$2,000"],
      ["Checks not payable", s.lost.count + " = " + formatMoney(s.lost.cents), "15 = $15,400"],
      ["Of those, at published rates", s.lost.knownCount + " = " + formatMoney(s.lost.knownCents), "13 = $13,342"],
      ["Twelfth month in a row", monthOrNever(s.twelfth), "Oct 2027"],
      ["Case closed from", monthOrNever(s.closedFrom), "Nov 2027"],
      ["Cushion kept", formatMoney(s.cushionCents), "$2,000"]
    ];
  } },
  { n: 3, name: "The example, spent down or moved to STABLE", run: function () {
    const spend = simulatePath(SAMPLE, "spend").summary;
    const stable = simulatePath(SAMPLE, "stable", "spend").summary;
    return [
      ["Spend: further checks lost", spend.lost.count, 0],
      ["Spend: counted on December 1", formatMoney(spend.countedOnFirstCents), "$1,500"],
      ["Spend: cushion kept", formatMoney(spend.cushionCents), "$1,500"],
      ["STABLE: further checks lost", stable.lost.count, 0],
      ["STABLE: counted on December 1", formatMoney(stable.countedOnFirstCents), "$1,500"],
      ["STABLE: cushion kept", formatMoney(stable.cushionCents), "$17,000"]
    ];
  } },
  { n: 4, name: "$1,500 arrives with no room left: exactly $2,000 is still payable", run: function () {
    const inp = sampleWith({ amountCents: 150000, bufferCents: 0 });
    const sim = simulatePath(inp, "leave");
    return [
      ["Counted on December 1", formatMoney(sim.summary.countedOnFirstCents), "$2,000"],
      ["December check", rowFor(sim, 2026, 12).status, "paid"],
      ["Has to leave the bank", formatMoney(needOut(inp)), "$0"],
      ["November check", incomeEffect(inp).kind, "lost"]
    ];
  } },
  { n: 5, name: "$1,501 arrives with no room left: one dollar over", run: function () {
    const inp = sampleWith({ amountCents: 150100, bufferCents: 0 });
    const sim = simulatePath(inp, "leave");
    return [
      ["Has to leave the bank", formatMoney(needOut(inp)), "$1"],
      ["December check", rowFor(sim, 2026, 12).status, "notpayable"],
      ["January check", rowFor(sim, 2027, 1).status, "paid"]
    ];
  } },
  { n: 6, name: "Money arrives on November 30: one day", run: function () {
    const p = buildPlan(sampleWith({ arrival: { y: 2026, m: 11, d: 30 } }), SAMPLE_TODAY);
    return [
      ["Days left", p.clock.daysLeft, 1],
      ["Start-by day falls before the money arrives", p.clock.startByBeforeArrival, true]
    ];
  } },
  { n: 7, name: "Money arrives on December 1, 2026 and stays in the bank", run: function () {
    const inp = sampleWith({ arrival: { y: 2026, m: 12, d: 1 } });
    const p = buildPlan(inp, SAMPLE_TODAY);
    const s = p.paths.leave.summary;
    return [
      ["Day the money is first counted", formatDate(p.clock.testDate, "short"), "Fri Jan 1, 2027"],
      ["Days left", p.clock.daysLeft, 31],
      ["Check to repay", p.effect.kind + " " + monthOrNever(p.effect.month), "lost Dec 2026"],
      ["At or under the line again", monthOrNever(s.backUnder), "Apr 2028"],
      ["Case closed from", monthOrNever(s.closedFrom), "Dec 2027"],
      ["January check may already be in the bank", p.clock.checkLandsEarly, true]
    ];
  } },
  { n: 8, name: "Money arrives on December 31, 2026", run: function () {
    const p = buildPlan(sampleWith({ arrival: { y: 2026, m: 12, d: 31 } }), SAMPLE_TODAY);
    return [
      ["Days left", p.clock.daysLeft, 1],
      ["Year whose limit applies", p.cap.years.join(" and "), "2026"]
    ];
  } },
  { n: 9, name: "February 29 exists in 2028 and not in 2027", run: function () {
    const leap = buildPlan(sampleWith({ arrival: { y: 2028, m: 2, d: 29 } }), SAMPLE_TODAY);
    const none = buildPlan(sampleWith({ arrival: { y: 2027, m: 2, d: 29 } }), SAMPLE_TODAY);
    return [
      ["February 29, 2028 is accepted", leap.ok, true],
      ["Days left", leap.ok ? leap.clock.daysLeft : -1, 1],
      ["2028 check amount is published", leap.ok ? leap.ratePublished : true, false],
      ["February 29, 2027 is accepted", none.ok, false],
      ["Field named in the message", none.field, "arrival"]
    ];
  } },
  { n: 10, name: "Timing: paid on December 2 in place of November 12", run: function () {
    const w = timingWhatIf(SAMPLE, { y: 2026, m: 12, d: 2 });
    return [
      ["Days in the window", w.alt.windowDays, 30],
      ["Days gained", w.daysGained, 11],
      ["Check to repay", w.alt.effect.kind + " " + monthOrNever(w.alt.effect.month), "lost Dec 2026"],
      ["January check may already be in the bank", w.alt.checkLandsEarly, true]
    ];
  } },
  { n: 11, name: "$21,000: exactly the yearly limit has to move", run: function () {
    const inp = sampleWith({ amountCents: 2100000 });
    const cap = capPlan(inp);
    return [
      ["Has to leave the bank", formatMoney(needOut(inp)), "$20,000"],
      ["Fits under this year's limit", cap.fits, true],
      ["Cushion kept", formatMoney(simulatePath(inp, "stable", "spend").summary.cushionCents), "$21,500"]
    ];
  } },
  { n: 12, name: "$21,001: one dollar does not fit", run: function () {
    const inp = sampleWith({ amountCents: 2100100 });
    const sim = simulatePath(inp, "stable", "wait");
    return [
      ["Left over", formatMoney(capPlan(inp).leftoverCents), "$1"],
      ["December check if it is held", rowFor(sim, 2026, 12).status, "paid"],
      ["Checks lost", sim.summary.lost.count, 0]
    ];
  } },
  { n: 13, name: "$21,501: the leftover is held in the bank", run: function () {
    const sim = simulatePath(sampleWith({ amountCents: 2150100 }), "stable", "wait");
    return [
      ["December check", rowFor(sim, 2026, 12).status + " " + formatMoney(rowFor(sim, 2026, 12).check), "notpayable $994"],
      ["January check", rowFor(sim, 2027, 1).status, "paid"]
    ];
  } },
  { n: 14, name: "The example with $6,000 already paid in this year", run: function () {
    const inp = sampleWith({ priorStableCents: 600000 });
    const cap = capPlan(inp);
    const spend = simulatePath(inp, "stable", "spend").summary;
    const wait = simulatePath(inp, "stable", "wait");
    return [
      ["Room this year", formatMoney(cap.roomCents), "$14,000"],
      ["Left over", formatMoney(cap.leftoverCents), "$1,500"],
      ["Leftover spent: cushion kept", formatMoney(spend.cushionCents), "$15,500"],
      ["Leftover held: December check", rowFor(wait, 2026, 12).status, "notpayable"],
      ["Leftover held: checks lost", wait.summary.lost.count, 1],
      ["Leftover held: cushion kept", formatMoney(wait.summary.cushionCents), "$16,000"]
    ];
  } },
  { n: 15, name: "$30,000: more than one year's limit", run: function () {
    const inp = sampleWith({ amountCents: 3000000 });
    const spend = simulatePath(inp, "stable", "spend").summary;
    const wait = simulatePath(inp, "stable", "wait");
    return [
      ["Leftover spent: cushion kept", formatMoney(spend.cushionCents), "$21,500"],
      ["Leftover held: December check", rowFor(wait, 2026, 12).status, "notpayable"],
      ["Leftover held: January check", rowFor(wait, 2027, 1).status, "notpayable"],
      ["Leftover held: checks lost", wait.summary.lost.count + " = " + formatMoney(wait.summary.lost.cents), "2 = $2,023"],
      ["Leftover held: cushion kept", formatMoney(wait.summary.cushionCents), "$28,500"]
    ];
  } },
  { n: 16, name: "A blank amount or $0 gives no plan", run: function () {
    const blank = buildPlan(sampleWith({ amountCents: null }), SAMPLE_TODAY);
    const zero = buildPlan(sampleWith({ amountCents: 0 }), SAMPLE_TODAY);
    return [
      ["Blank: a plan is made", blank.ok, false],
      ["Blank: message", blank.message, "Enter an amount to see a plan."],
      ["$0: a plan is made", zero.ok, false],
      ["$0: message", zero.message, "Enter an amount to see a plan."],
      ["A number that is not a number anywhere", hasBadNumber(blank) || hasBadNumber(zero), false]
    ];
  } },
  { n: 17, name: "Small amounts lower a later check; $1,014 or more costs a whole check", run: function () {
    const a = incomeEffect(sampleWith({ amountCents: 80000 }));
    const b = incomeEffect(sampleWith({ amountCents: 101400 }));
    const c = incomeEffect(sampleWith({ amountCents: 101399 }));
    return [
      ["$800", a.kind + " by " + formatMoney(a.cents) + " in " + monthOrNever(a.month), "reduced by $780 in Jan 2027"],
      ["$1,014", b.kind, "lost"],
      ["$1,013.99", c.kind + " by " + formatMoney(c.cents), "reduced by $993.99"]
    ];
  } },
  { n: 18, name: "Age when the disability began: 25, 26, 45, 46", run: function () {
    function both(age) {
      const e = ableEligible(age);
      return (e.now ? "new rule yes" : "new rule no") + ", " + (e.old ? "old rule yes" : "old rule no");
    }
    return [
      ["25", both(25), "new rule yes, old rule yes"],
      ["26", both(26), "new rule yes, old rule no"],
      ["45", both(45), "new rule yes, old rule no"],
      ["46", both(46), "new rule no, old rule no"],
      ["46: a STABLE path is shown", comparePaths(sampleWith({ onsetAge: 46 })).stable !== null, false]
    ];
  } },
  { n: 19, name: "Living on $0, $3,000 or $700 a month with the money in the bank", run: function () {
    const none = simulatePath(sampleWith({ monthlySpendCents: 0 }), "leave").summary;
    const fast = simulatePath(sampleWith({ monthlySpendCents: 300000 }), "leave").summary;
    const slow = simulatePath(sampleWith({ monthlySpendCents: 70000 }), "leave").summary;
    return [
      ["$0: at or under the line again", monthOrNever(none.backUnder), "never"],
      ["$0: case closed from", monthOrNever(none.closedFrom), "Nov 2027"],
      ["$3,000: at or under the line again", monthOrNever(fast.backUnder), "May 2027"],
      ["$3,000: checks not payable", fast.lost.count + " = " + formatMoney(fast.lost.cents), "5 = $5,110"],
      ["$700: at or under the line again", monthOrNever(slow.backUnder), "Oct 2028"],
      ["$700: checks not payable", slow.lost.count, 22]
    ];
  } },
  { n: 20, name: "The same $16,500 as SSI back pay, left in the bank", run: function () {
    const inp = sampleWith({ kind: "backpay" });
    const sim = simulatePath(inp, "leave");
    return [
      ["Check to repay", incomeEffect(inp).kind, "none"],
      ["November check", rowFor(sim, 2026, 11).status, "paid"],
      ["First counted", formatDate(fromMonthIdx(firstTestMonth(inp)), "short"), "Wed Sep 1, 2027"],
      ["Counted on that day", formatMoney(sim.summary.countedOnFirstCents), "$17,000"]
    ];
  } },
  { n: 21, name: "Reading typed amounts", run: function () {
    return [
      ["$1,250.50", parseMoney("$1,250.50").cents, 125050],
      [".5", parseMoney(".5").cents, 50],
      ["blank is blank, not an error", parseMoney("").cents === null && parseMoney("").error === null, true],
      ["-5 is turned away", parseMoney("-5").error !== null, true],
      ["1e5 is turned away", parseMoney("1e5").error !== null, true],
      ["abc is turned away", parseMoney("abc").error !== null, true]
    ];
  } },
  { n: 22, name: "March 1 to March 31, 2027 across the daylight saving change", run: function () {
    return [
      ["Days", daysBetween({ y: 2027, m: 3, d: 1 }, { y: 2027, m: 3, d: 31 }), 30]
    ];
  } }
];

function runSelfTests() {
  const cases = SELF_TESTS.map(function (t) {
    let checks;
    try {
      checks = t.run().map(function (c) {
        return { label: c[0], got: c[1], want: c[2], pass: c[1] === c[2] };
      });
    } catch (err) {
      checks = [{ label: "Ran without an error", got: String(err && err.message ? err.message : err), want: "no error", pass: false }];
    }
    return { n: t.n, name: t.name, checks: checks, pass: checks.every(function (c) { return c.pass; }) };
  });
  const passed = cases.filter(function (c) { return c.pass; }).length;
  return { total: cases.length, passed: passed, allPassed: passed === cases.length, cases: cases };
}

/* CHECKS:END */


/* =====================================================================================
   START
   ===================================================================================== */

fillFigures();
renderRules();
fillInputs();
wireEvents();
wireFileBar();
render();
renderChecks(runSelfTests());
</script>
</body>
</html>

Reaches out to

Nothing. This page is entirely self-contained and contacts no other website when it runs.

Licence

Published on Globefin under the MIT License. You may copy, change, and reuse this page, including commercially — just keep the notice below with it.

Copyright © 2026 Christian Smith. Licensed under the MIT License. Published on Globefin.

Provided as is, without warranty. Any external libraries it loads keep their own licences. Terms →

Sandbox

Scripts run, but the demo has its own throwaway origin. It can't read your session or cookies, can't reach the page around it, and can't navigate your tab. Don't enter real passwords or personal data into any demo.