← Demos
Web Pages · Demos

Medical Bill Fighter KY

For Kentucky households with a medical bill they can’t pay. Try it: click “See a 1-minute example” on Start, then open Charity Care. A family of 3 earning $52,000 is at 190% of the poverty line, so their $8,400 UK HealthCare ER bill is likely free. Then check Letters (a ready-to-send aid application), Payments (the medical credit card interest trap) and Deadlines. Notice: real Kentucky hospital policies with sources, and nothing you type leaves the page.

by Liam Schilling Nov 20, 2026 13 views 95.2 KB
Sandbox · medical-bill-fighter-ky-2 · no access to your account
View source — the whole page is this one file
<!-- Copyright (c) 2026 Liam Joseph Schilling. Released under the MIT License. -->
<!--
Medical Bill Fighter KY

MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Third-party code: none. All code in this file was written for this project.
Educational use only. Not financial, legal, tax or medical advice.
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Medical Bill Fighter KY</title>
<meta name="description" content="Free, private tool for Kentucky households fighting medical bills: charity care check, ready-to-send letters, payment comparisons and federal deadlines.">
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Cpath d='M16 2 4 7v8c0 7.5 5.1 13.4 12 15 6.9-1.6 12-7.5 12-15V7L16 2z' fill='%230e7490'/%3E%3Cpath d='M14 10h4v4h4v4h-4v4h-4v-4h-4v-4h4z' fill='%23fff'/%3E%3C/svg%3E">
<style>
:root{
  --ink:#16243a; --ink2:#46566e; --muted:#6b7a90; --line:#d9e1ea; --bg:#f5f7fa; --card:#fff;
  --brand:#0f5f73; --brand2:#0b4a5a; --brandSoft:#e3f1f4;
  --good:#1d7a46; --goodSoft:#e4f4ea; --warn:#9a5b00; --warnSoft:#fdf1dc; --bad:#a3262a; --badSoft:#fbe6e6;
  --info:#2b5797; --infoSoft:#e7eefa; --hl:#fff3b0;
  --r:12px;
}
*{box-sizing:border-box}
[hidden]{display:none!important}
html,body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif}
a{color:var(--brand)}
h1,h2,h3{line-height:1.25;margin:0 0 .5em}
h1{font-size:1.6rem} h2{font-size:1.3rem} h3{font-size:1.05rem}
p{margin:.4em 0 .8em}
button,input,select,textarea{font:inherit;color:inherit}
.wrap{max-width:1040px;margin:0 auto;padding:0 16px}
header.top{background:var(--brand2);color:#fff}
header.top .wrap{display:flex;align-items:center;justify-content:space-between;gap:12px;padding-top:12px;padding-bottom:12px;flex-wrap:wrap}
.logo{display:flex;align-items:center;gap:10px;font-weight:700;font-size:1.15rem}
.logo svg{flex:none}
.filebar{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
.filebar .status{font-size:.85rem;opacity:.85}
.btn{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--line);background:#fff;color:var(--ink);border-radius:8px;padding:8px 14px;cursor:pointer;font-weight:600;font-size:.95rem}
.btn:hover{border-color:var(--brand)}
.btn:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible,[role=tab]:focus-visible{outline:3px solid #f2b705;outline-offset:2px}
.btn.primary{background:var(--brand);border-color:var(--brand);color:#fff}
.btn.primary:hover{background:var(--brand2)}
.btn.ghost{background:transparent;color:#fff;border-color:rgba(255,255,255,.5)}
.btn.small{padding:5px 10px;font-size:.85rem}
.btn.danger{color:var(--bad)}
nav.tabs{background:#fff;border-bottom:1px solid var(--line);position:sticky;top:0;z-index:5}
nav.tabs .wrap{display:flex;gap:2px;overflow-x:auto;scrollbar-width:thin}
[role=tab]{border:0;background:none;padding:12px 14px;cursor:pointer;color:var(--ink2);font-weight:600;white-space:nowrap;border-bottom:3px solid transparent}
[role=tab][aria-selected=true]{color:var(--brand2);border-bottom-color:var(--brand)}
[role=tab] .n{display:inline-block;width:20px;height:20px;border-radius:50%;background:var(--brandSoft);color:var(--brand2);font-size:.75rem;line-height:20px;text-align:center;margin-right:6px}
.summary{background:var(--brandSoft);border-bottom:1px solid #c7e2e8}
.summary .wrap{display:flex;gap:24px;flex-wrap:wrap;align-items:baseline;padding-top:10px;padding-bottom:10px}
.summary .big{font-size:1.25rem;font-weight:800}
.summary .lbl{font-size:.8rem;color:var(--ink2);text-transform:uppercase;letter-spacing:.04em}
main{padding:24px 0 48px}
.card{background:var(--card);border:1px solid var(--line);border-radius:var(--r);padding:20px;margin-bottom:16px}
.grid{display:grid;gap:16px}
.g2{grid-template-columns:repeat(2,minmax(0,1fr))}
.g3{grid-template-columns:repeat(3,minmax(0,1fr))}
.g4{grid-template-columns:repeat(4,minmax(0,1fr))}
@media (max-width:760px){.g2,.g3,.g4{grid-template-columns:1fr}}
label{display:block;font-weight:600;font-size:.92rem;margin-bottom:4px}
.hint{font-size:.85rem;color:var(--muted);font-weight:400}
input[type=text],input[type=number],input[type=date],input[type=password],select,textarea{width:100%;padding:9px 11px;border:1px solid #b9c6d4;border-radius:8px;background:#fff}
textarea{min-height:80px;resize:vertical}
.field{margin-bottom:12px}
.fact{border-left:4px solid var(--brand);padding:6px 0 6px 12px;margin:0}
.fact b{font-size:1.4rem;display:block;color:var(--brand2)}
.steps{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;counter-reset:s}
@media (max-width:760px){.steps{grid-template-columns:1fr}}
.step{background:var(--bg);border-radius:10px;padding:14px}
.step::before{counter-increment:s;content:counter(s);display:inline-block;width:28px;height:28px;border-radius:50%;background:var(--brand);color:#fff;text-align:center;line-height:28px;font-weight:700;margin-bottom:6px}
.notice{border-radius:10px;padding:12px 14px;margin:10px 0;font-size:.95rem}
.notice.good{background:var(--goodSoft);color:#124d2c}
.notice.warn{background:var(--warnSoft);color:#5f3a00}
.notice.bad{background:var(--badSoft);color:#6d1518}
.notice.info{background:var(--infoSoft);color:#1d3d6b}
.notice.muted{background:var(--bg);color:var(--ink2)}
.disclaimer{font-size:.85rem;color:var(--ink2);background:#fff;border:1px dashed #b9c6d4;border-radius:10px;padding:10px 12px}
table{width:100%;border-collapse:collapse;font-size:.93rem}
th,td{text-align:left;padding:9px 8px;border-bottom:1px solid var(--line);vertical-align:top}
th{font-size:.8rem;text-transform:uppercase;letter-spacing:.03em;color:var(--ink2)}
td.num,th.num{text-align:right;white-space:nowrap}
.tablewrap{overflow-x:auto}
.pill{display:inline-block;padding:2px 9px;border-radius:999px;font-size:.78rem;font-weight:700;white-space:nowrap}
.pill.good{background:var(--goodSoft);color:var(--good)}
.pill.warn{background:var(--warnSoft);color:var(--warn)}
.pill.info{background:var(--infoSoft);color:var(--info)}
.pill.muted{background:var(--bg);color:var(--ink2)}
.pill.bad{background:var(--badSoft);color:var(--bad)}
.bignum{font-size:3rem;font-weight:800;line-height:1;color:var(--brand2)}
.meter{height:14px;border-radius:7px;background:linear-gradient(90deg,#d6efe0 0%,#d6efe0 50%,#fdf1dc 50%,#fdf1dc 87.5%,#f3dede 87.5%);position:relative;margin:26px 0 30px}
.meter .mk{position:absolute;top:-6px;width:3px;height:26px;background:var(--ink)}
.meter .tick{position:absolute;top:18px;font-size:.72rem;color:var(--ink2);transform:translateX(-50%);white-space:nowrap}
.meter .you{position:absolute;top:-24px;font-size:.78rem;font-weight:700;transform:translateX(-50%);white-space:nowrap}
.check{display:flex;gap:10px;align-items:flex-start;padding:10px 0;border-bottom:1px solid var(--line)}
.check input{margin-top:4px;width:18px;height:18px;flex:none}
.check label{font-weight:600;margin:0}
.check .hint{display:block}
.letter{white-space:pre-wrap;font-family:Georgia,"Times New Roman",serif;background:#fff;border:1px solid var(--line);border-radius:8px;padding:22px;line-height:1.55;font-size:.98rem}
.letter mark{background:var(--hl);padding:0 2px;border-radius:3px}
.row{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
.right{margin-left:auto}
.timeline{list-style:none;padding:0;margin:0}
.timeline li{display:grid;grid-template-columns:120px 1fr;gap:12px;padding:10px 0;border-bottom:1px solid var(--line)}
.timeline li.past{color:var(--muted)}
.timeline .d{font-weight:700}
.tag{font-size:.75rem;font-weight:700;color:var(--muted)}
.srcs li{margin-bottom:6px;font-size:.92rem}
.muted{color:var(--muted)}
.small{font-size:.88rem}
.sr{position:absolute;left:-9999px}
.ai{border:1px solid #c9d6ea;background:#f8fbff}
.ai .out{white-space:pre-wrap;background:#fff;border:1px solid var(--line);border-radius:8px;padding:12px;min-height:48px}
footer{border-top:1px solid var(--line);background:#fff;padding:18px 0;font-size:.85rem;color:var(--ink2)}
.toast{position:fixed;left:50%;bottom:20px;transform:translateX(-50%);background:var(--ink);color:#fff;padding:10px 16px;border-radius:8px;font-size:.92rem;opacity:0;transition:opacity .2s;pointer-events:none;z-index:50;max-width:90vw}
.toast.show{opacity:1}
.chart text{font-size:12px;fill:var(--ink2)}
details summary{cursor:pointer;font-weight:600}
@media (max-width:760px){
  table.stack thead{display:none}
  table.stack tr{display:block;border-bottom:1px solid var(--line);padding:8px 0}
  table.stack td{display:block;border:0;padding:3px 0;text-align:left}
  table.stack td.num{text-align:left}
  table.stack td[data-label]::before{content:attr(data-label) ": ";font-weight:700;color:var(--ink2);font-size:.8rem;text-transform:uppercase}
}
@media print{
  header.top,nav.tabs,.summary,footer,.noprint,.btn{display:none!important}
  body{background:#fff}
  .card{border:0;padding:0}
  .letter{border:0;padding:0;font-size:12pt}
  .letter mark{background:none}
}

/* ===== Polish layer ===== */
:root{--brand:#0e7490;--brand2:#155e75;--brandSoft:#e6f6f9;--bg:#f3f6f8;--line:#e3e9ee;--ink:#0f1f33;--ink2:#4a5a70;--r:16px;
  --shadow:0 1px 2px rgba(15,31,51,.05),0 6px 20px rgba(15,31,51,.05)}
body{background:var(--bg);-webkit-font-smoothing:antialiased}
h1{font-size:1.55rem;letter-spacing:-.01em} h2{font-size:1.15rem;letter-spacing:-.005em}
header.top{background:linear-gradient(120deg,#0f3d4c 0%,#0e7490 100%)}
.btn{border-radius:10px;border-color:#d5dee6;box-shadow:0 1px 2px rgba(15,31,51,.04);transition:background .15s,border-color .15s,transform .05s}
.btn:active{transform:translateY(1px)}
.btn.primary{background:var(--brand);box-shadow:0 2px 6px rgba(14,116,144,.25)}
.btn.ghost{border-color:rgba(255,255,255,.35)}
nav.tabs{background:rgba(255,255,255,.92);backdrop-filter:saturate(1.4) blur(8px);border-bottom:1px solid var(--line)}
nav.tabs .wrap{padding-top:8px;padding-bottom:8px;gap:4px}
[role=tab]{border:0;border-radius:999px;padding:8px 14px;font-size:.93rem}
[role=tab]:hover{background:#f1f5f8}
[role=tab][aria-selected=true]{background:var(--brandSoft);color:var(--brand2);border:0}
[role=tab] .n{background:#fff;box-shadow:inset 0 0 0 1px #cfe3e8}
[role=tab][aria-selected=true] .n{background:var(--brand);color:#fff;box-shadow:none}
.summary{background:transparent;border:0}
.summary .wrap{padding-top:18px;padding-bottom:0;gap:12px;align-items:stretch}
.stat{background:#fff;border-radius:14px;padding:12px 16px;box-shadow:var(--shadow);min-width:140px;flex:1}
.stat.hero{background:linear-gradient(135deg,#0e7490,#0f5f73);color:#fff;flex:1.4}
.stat.hero .lbl{color:rgba(255,255,255,.8)}
.stat.hero .big{color:#fff;font-size:1.6rem}
.summary .lbl{font-size:.72rem;font-weight:700}
.summary .empty{background:#fff;border-radius:14px;padding:12px 16px;box-shadow:var(--shadow);color:var(--ink2);flex:1}
main{padding:18px 0 56px}
.card{border:0;box-shadow:var(--shadow);border-radius:var(--r);padding:24px}
.hero-card{background:linear-gradient(135deg,#e9f7fa 0%,#ffffff 60%);padding:32px 28px}
.hero-card h1{font-size:2rem;line-height:1.15;max-width:640px}
.hero-card p{font-size:1.05rem;color:var(--ink2);max-width:680px}
.fact{border:0;background:#f6f9fb;border-radius:12px;padding:14px 16px}
.fact b{font-size:1.6rem;letter-spacing:-.02em}
.step{background:#f6f9fb;border-radius:12px}
.notice{border-radius:12px}
.notice.good{border:1px solid #cbe9d6}.notice.info{border:1px solid #d3e0f5}.notice.warn{border:1px solid #f4dfb8}.notice.bad{border:1px solid #f1caca}
input[type=text],input[type=number],input[type=date],input[type=password],select,textarea{border:1px solid #d3dce5;border-radius:10px;padding:10px 12px;background:#fbfcfd;transition:border-color .15s,box-shadow .15s}
input:focus,select:focus,textarea:focus{outline:none;border-color:var(--brand);box-shadow:0 0 0 3px rgba(14,116,144,.15);background:#fff}
th{border-bottom:1px solid var(--line)} td{border-bottom:1px solid #eef2f5}
.letter{border-radius:12px;box-shadow:inset 0 0 0 1px var(--line);border:0;background:#fffefb}
.bignum{font-size:3.4rem;letter-spacing:-.03em}
.meter{height:12px;border-radius:6px}
details.more{margin:6px 0 14px}
details.more>summary,details.fold>summary{list-style:none;color:var(--brand2);font-weight:600;padding:6px 0}
details.more>summary::-webkit-details-marker,details.fold>summary::-webkit-details-marker{display:none}
details.more>summary::before,details.fold>summary::before{content:"+ ";font-weight:800}
details[open].more>summary::before,details[open].fold>summary::before{content:"– "}
details.fold>summary h2{display:inline;margin:0}
.nextbar{display:flex;justify-content:flex-end;margin-top:4px}
.nextbar .btn{padding:10px 18px}
.ai{background:#fff;border:0}
footer{background:transparent;border:0}
#view:focus{outline:none}
.check input:checked + div label{color:var(--muted);text-decoration:line-through}
footer .wrap{border-top:1px solid var(--line);padding-top:18px}
</style>
</head>
<body>

<header class="top">
  <div class="wrap">
    <div class="logo">
      <svg width="30" height="30" viewBox="0 0 32 32" aria-hidden="true"><path d="M16 2 4 7v8c0 7.5 5.1 13.4 12 15 6.9-1.6 12-7.5 12-15V7L16 2z" fill="#fff" opacity=".95"/><path d="M14 10h4v4h4v4h-4v4h-4v-4h-4v-4h4z" fill="#0b4a5a"/></svg>
      <span>Medical Bill Fighter <span style="opacity:.75">KY</span></span>
    </div>
    <div class="filebar">
      <span class="status" id="saveStatus" aria-live="polite">No unsaved changes</span>
      <button class="btn ghost small" id="btnOpen" type="button">Open file</button>
      <button class="btn small" id="btnSave" type="button">Save to file</button>
      <input type="file" id="fileInput" accept=".json,application/json" class="sr" aria-label="Open a saved Medical Bill Fighter file">
    </div>
  </div>
</header>

<nav class="tabs" aria-label="Sections">
  <div class="wrap" role="tablist" id="tablist"></div>
</nav>

<div class="summary" aria-live="polite">
  <div class="wrap" id="summaryBar"></div>
</div>

<main>
  <div class="wrap" id="view" role="tabpanel" tabindex="-1"></div>
</main>

<footer>
  <div class="wrap">
    <p><b>Educational use only.</b> Medical Bill Fighter KY is a learning tool. It is not financial, legal, tax or medical advice, and it does not recommend any investment. Hospital policies change; confirm every number with the hospital or a legal aid office before you rely on it.</p>
    <p><b>Your privacy:</b> everything you type stays on this page in your browser. Nothing is sent anywhere unless you turn on the optional AI helper, which sends only what it shows you first. Saving creates a file on your own device.</p>
    <p id="copyLine"></p>
  </div>
</footer>

<div class="toast" id="toast" role="status" aria-live="polite"></div>

<script>
"use strict";
/* ============================================================
   CONFIG
   ============================================================ */
const AUTHOR = "Liam Joseph Schilling";
const APP_ID = "medical-bill-fighter-ky";
const SCHEMA_VERSION = 1;
const LIMITS = { money: 10000000, text: 2000, bills: 200, household: 20 };

/* ============================================================
   DATA  (every entry has a source; checked 2026-11-17)
   ============================================================ */
const DATA = {
  checked: "2026-11-17",
  fpl: { year: 2026, base: 15960, add: 5680,
    src: "https://aspe.hhs.gov/topics/poverty-economic-mobility/poverty-guidelines" },
  medicaidAdultPct: 138,
  facts: [
    { big: "9th", text: "Kentucky's national rank for medical debt (end of 2025).",
      src: "https://spectrumlocalnews.com/louisville/news/2026/04/13/medical-debt-kentucky" },
    { big: "1 in 5", text: "Kentuckians estimated to have medical debt in collections.",
      src: "https://www.wuky.org/wuky-news/2025-08-14/kentucky-lags-behind-other-states-in-medical-debt-protections" },
    { big: "Up to half", text: "of the debt some Kentucky hospitals wrote off came from patients they believe qualified for charity care.",
      src: "https://www.lpm.org/news/2019-10-19/in-ky-and-nationwide-patients-are-racking-up-bad-hospital-debt-when-they-may-qualify-for-assistance" },
    { big: "0", text: "Kentucky laws requiring hospitals to offer charity care. Each hospital writes its own rules.",
      src: "https://lpm.org/investigate/2023-11-20/for-years-a-powerful-louisville-hospital-sued-people-for-unpaid-bills-experts-say-they-could-have-gotten-free-care" }
  ],
  /* kind: hospital | forprofit | provider ; freeTo/discTo in % of poverty line; null = not confirmed */
  hospitals: [
    { id: "ukhc", name: "UK HealthCare (Lexington)", kind: "hospital", nonprofit: true, freeTo: 200, discTo: 300, discPct: null,
      note: "UK's policy covers households up to 300% of the poverty line. The free-care cutoff of 200% comes from a third-party summary; confirm with UK.",
      phone: "", url: "https://ukhealthcare.uky.edu/patients-visitors/patients/payment-insurance/financial-assistance",
      src: "https://WWW.UKHEALTHCARE.UKY.EDU/sites/default/files/2024-01/A07-010-Financial-Assistance-Program-dec-2023.pdf" },
    { id: "norton", name: "Norton Healthcare / Norton Children's (Louisville)", kind: "hospital", nonprofit: true, freeTo: 350, discTo: null, discPct: null,
      note: "Free care up to 350% of the poverty line. Norton also checks assets.",
      phone: "(502) 479-6300", url: "https://nortonhealthcare.com/patient-resources/billing-information/financial-assistance/",
      src: "https://nortonhealthcare.com/patient-resources/billing-information/financial-assistance/" },
    { id: "uofl", name: "UofL Health (Louisville)", kind: "hospital", nonprofit: true, freeTo: 300, discTo: null, discPct: null,
      note: "UofL Health says households up to 300% of the poverty line may not have to pay.",
      phone: "", url: "https://uoflhealth.org/",
      src: "https://uoflhealth.org/wp-content/uploads/2022/10/Financial-Assistance-Program-SummaryULH062017.pdf" },
    { id: "baptist", name: "Baptist Health Kentucky", kind: "hospital", nonprofit: true, freeTo: 300, discTo: 400, discPct: 50,
      note: "Free up to 300%, 50% off from 301% to 400% (third-party summary of Baptist's policy; confirm with Baptist).",
      phone: "", url: "https://www.baptisthealth.com/",
      src: "https://www.careroute.ai/hospital-financial-assistance/baptist-health-kentucky" },
    { id: "stelizabeth", name: "St. Elizabeth Healthcare (Northern KY)", kind: "hospital", nonprofit: true, freeTo: 200, discTo: 400, discPct: null,
      note: "100% help at or under 200% of the poverty line; tiered discounts above that; case-by-case hardship help above 400%.",
      phone: "877-424-5750", url: "https://www.stelizabeth.com/",
      src: "https://www.stelizabeth.com/docs/default-source/pay-my-bill/documents/2023/2023-fap-plain-language-summary-pls---20230517.pdf" },
    { id: "arh", name: "Appalachian Regional Healthcare (ARH, Eastern KY)", kind: "hospital", nonprofit: true, freeTo: null, discTo: null, discPct: null,
      note: "ARH offers free and discounted care under its Financial Assistance Policy. Income cutoffs were not confirmed for this tool; ask ARH.",
      phone: "859-226-2440", url: "https://arh.org/financial-assistance", src: "https://arh.org/financial-assistance" },
    { id: "chi", name: "CHI Saint Joseph Health", kind: "hospital", nonprofit: null, freeTo: null, discTo: null, discPct: null,
      note: "Has a financial assistance program. Income cutoffs not confirmed for this tool; ask the hospital.",
      phone: "", url: "https://www.chisaintjosephhealth.org/body.cfm?id=3149", src: "https://www.chisaintjosephhealth.org/body.cfm?id=3149" },
    { id: "kdh", name: "King's Daughters (Ashland)", kind: "hospital", nonprofit: null, freeTo: null, discTo: null, discPct: null,
      note: "Has a written Financial Assistance Policy. Income cutoffs not confirmed for this tool; ask the hospital.",
      phone: "", url: "https://www.kingsdaughtershealth.com/patient-visitors/financial-services-resources/financial-assistance-policy",
      src: "https://www.kingsdaughtershealth.com/patient-visitors/financial-services-resources/financial-assistance-policy" },
    { id: "otherhosp", name: "Other nonprofit hospital", kind: "hospital", nonprofit: true, freeTo: null, discTo: null, discPct: null,
      note: "Every nonprofit hospital must publish a Financial Assistance Policy. Search the hospital's name plus \"financial assistance policy.\"",
      phone: "", url: "", src: "https://www.irs.gov/charities-non-profits/charitable-organizations/requirements-for-501c3-hospitals-under-the-affordable-care-act-section-501r" },
    { id: "forprofit", name: "For-profit hospital", kind: "forprofit", nonprofit: false, freeTo: null, discTo: null, discPct: null,
      note: "Federal nonprofit charity care rules don't apply. Many still offer self-pay discounts and plans if you ask.",
      phone: "", url: "", src: "https://www.irs.gov/charities-non-profits/charitable-organizations/requirements-for-501c3-hospitals-under-the-affordable-care-act-section-501r" },
    { id: "provider", name: "Doctor, lab, imaging or ambulance", kind: "provider", nonprofit: null, freeTo: null, discTo: null, discPct: null,
      note: "These bills often come separately from the hospital's. Ask whether they follow the hospital's financial assistance policy or have their own.",
      phone: "", url: "", src: "" }
  ],
  rights: {
    eca: 120, appWindow: 240, eca_notice: 30, nsaGap: 400, nsaDays: 120, validation: 30,
    src501r: "https://www.irs.gov/charities-non-profits/charitable-organizations/requirements-for-501c3-hospitals-under-the-affordable-care-act-section-501r",
    srcNSA: "https://www.cms.gov/medical-bill-rights",
    srcFDCPA: "https://www.consumerfinance.gov/ask-cfpb/what-information-does-a-debt-collector-have-to-give-me-about-a-debt-en-331/",
    srcSOL: "https://www.findlaw.com/state/kentucky-law/kentucky-civil-statute-of-limitations-laws.html",
    srcSOL2: "https://law.justia.com/codes/kentucky/chapter-413/section-413-160/",
    srcHomestead: "https://www.careroute.ai/states/kentucky-medical-bill-rights",
    srcCaps: "https://www.wuky.org/wuky-news/2025-08-14/kentucky-lags-behind-other-states-in-medical-debt-protections",
    srcMedicaid: "https://www.talktomira.com/coverage/medicaid/kentucky/"
  },
  directory: [
    { name: "kynect", what: "Apply for Kentucky Medicaid, KCHIP or marketplace coverage. Do this first if your income is low.", url: "https://kynect.ky.gov" },
    { name: "Kentucky Equal Justice Center", what: "Statewide advocacy on health care access and medical debt.", url: "https://www.kyequaljustice.org" },
    { name: "Legal Aid Society", what: "Free civil legal help, Louisville area.", url: "https://laslou.org" },
    { name: "Legal Aid of the Bluegrass", what: "Free civil legal help, central and northern Kentucky.", url: "https://lablaw.org" },
    { name: "AppalReD Legal Aid", what: "Free civil legal help, eastern Kentucky.", url: "https://ardfky.org" },
    { name: "Kentucky Legal Aid", what: "Free civil legal help, western and south-central Kentucky.", url: "https://klaid.org" },
    { name: "Kentucky Voices for Health", what: "Consumer health advocacy; has run medical debt relief drives.", url: "https://kyvoicesforhealth.org" },
    { name: "AnnualCreditReport.com", what: "Free credit reports from all three bureaus. Check for medical collections.", url: "https://www.annualcreditreport.com" }
  ],
  statuses: ["New", "Itemized requested", "Aid applied", "Disputed", "Payment plan", "Paid", "In collections"]
};

/* ============================================================
   STATE
   ============================================================ */
function blankState(){
  return {
    household: { size: 1, income: "", insured: "uninsured" },
    you: { name: "", address: "", phone: "" },
    bills: [],
    checklist: {},
    gfe: { estimate: "", billed: "" },
    pay: { balance: "", monthly: "", promo: 12, cardApr: 29.99, loanApr: 14 },
    letter: { type: "aid", billId: "", proposed: "", errors: "", collector: "" }
  };
}
let state = blankState();
let dirty = false;
let currentTab = "start";
let editingBillId = null;
const ai = { key: "", consent: false, model: "claude-haiku-5-5", busy: false };

/* ============================================================
   HELPERS
   ============================================================ */
const $ = (s, el = document) => el.querySelector(s);
const $$ = (s, el = document) => Array.from(el.querySelectorAll(s));
function esc(s){ return String(s == null ? "" : s).replace(/[&<>"']/g, c => ({ "&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;" }[c])); }
function num(v){ const n = parseFloat(v); return Number.isFinite(n) ? n : NaN; }
function money(n){ if (!Number.isFinite(n)) return "—"; return n.toLocaleString("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 }); }
function money2(n){ if (!Number.isFinite(n)) return "—"; return n.toLocaleString("en-US", { style: "currency", currency: "USD", minimumFractionDigits: 2, maximumFractionDigits: 2 }); }
function uid(){ return "b" + Math.random().toString(36).slice(2, 9) + Date.now().toString(36).slice(-4); }
function parseDate(s){ if (!/^\d{4}-\d{2}-\d{2}$/.test(s || "")) return null; const [y,m,d] = s.split("-").map(Number); const dt = new Date(y, m - 1, d); return (dt.getFullYear() === y && dt.getMonth() === m - 1 && dt.getDate() === d) ? dt : null; }
function addDays(dt, n){ const d = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate()); d.setDate(d.getDate() + n); return d; }
function fmtDate(dt){ return dt ? dt.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }) : ""; }
function today(){ const n = new Date(); return new Date(n.getFullYear(), n.getMonth(), n.getDate()); }
function toast(msg){ const t = $("#toast"); t.textContent = msg; t.classList.add("show"); clearTimeout(toast._t); toast._t = setTimeout(() => t.classList.remove("show"), 2600); }
function markDirty(){ dirty = true; $("#saveStatus").textContent = "Unsaved changes"; }
function markClean(){ dirty = false; $("#saveStatus").textContent = "All changes saved to file"; }

/* ============================================================
   CALCULATIONS (pure)
   ============================================================ */
function guideline(n){ n = Math.max(1, Math.floor(n)); return DATA.fpl.base + DATA.fpl.add * (n - 1); }
function fplPercent(income, size){
  const i = num(income), s = num(size);
  if (!Number.isFinite(i) || i < 0 || !Number.isFinite(s) || s < 1) return null;
  return i / guideline(s) * 100;
}
function hosp(id){ return DATA.hospitals.find(h => h.id === id) || DATA.hospitals.find(h => h.id === "otherhosp"); }
function billBalance(b){ return Math.max(0, (num(b.billed) || 0) - (num(b.insPaid) || 0)); }

function aidEstimate(b, fpl){
  const owed = billBalance(b);
  const h = hosp(b.provider);
  if (b.status === "Paid") return { min: 0, max: 0, owed: 0, tone: "muted", short: "Paid", label: "Marked as paid." };
  if (fpl == null) return { min: owed, max: owed, owed, tone: "muted", short: "Need income", label: "Enter your household size and income on the Charity Care tab to see an estimate." };
  if (h.kind === "forprofit") return { min: owed, max: owed, owed, tone: "warn", short: "Ask for discount",
    label: "For-profit hospital: federal charity care rules don't apply. Ask for a self-pay discount, a hardship reduction and an interest-free plan anyway." };
  if (h.kind === "provider") return { min: 0, max: owed, owed, tone: "info", short: "Ask provider",
    label: "Ask whether this provider follows the hospital's financial assistance policy or has its own. Many doctor groups do." };
  if (h.freeTo == null) return { min: 0, max: owed, owed, tone: "info", short: "Check policy",
    label: "This tool doesn't have this hospital's income cutoffs. Many Kentucky hospitals give free care to households between 200% and 350% of the poverty line, so apply." };
  if (fpl <= h.freeTo) return { min: 0, max: 0, owed, tone: "good", short: "Likely free",
    label: `Likely free. This hospital's policy covers households up to ${h.freeTo}% of the poverty line, and you're at ${Math.round(fpl)}%.` };
  if (h.discTo && fpl <= h.discTo){
    if (h.discPct){ const v = owed * (1 - h.discPct / 100);
      return { min: v, max: v, owed, tone: "good", short: `Likely ${h.discPct}% off`, label: `Likely ${h.discPct}% off under this hospital's policy (${h.freeTo + 1}%–${h.discTo}% of the poverty line).` }; }
    return { min: 0, max: owed, owed, tone: "good", short: "Likely discounted",
      label: `Likely discounted. This hospital gives partial help up to ${h.discTo}% of the poverty line; the hospital sets the amount.` };
  }
  const top = h.discTo || h.freeTo;
  return { min: owed, max: owed, owed, tone: "warn", short: "Over limit",
    label: `Over this hospital's ${top}% limit. Ask about an uninsured discount, hardship or catastrophic help, and an interest-free plan.` };
}

function totals(){
  const fpl = fplPercent(state.household.income, state.household.size);
  let billed = 0, owed = 0, min = 0, max = 0;
  state.bills.forEach(b => { const e = aidEstimate(b, fpl); billed += num(b.billed) || 0; owed += e.owed; min += e.min; max += e.max; });
  return { fpl, billed, owed, min, max, count: state.bills.length };
}

function deadlines(b){
  const out = [];
  const h = hosp(b.provider);
  const first = parseDate(b.firstBill);
  const R = DATA.rights;
  if (first && h.kind === "hospital" && h.nonprofit !== false){
    out.push({ date: addDays(first, R.eca), key: "eca",
      label: `Earliest date a nonprofit hospital may sue, report to credit bureaus or sell this debt, and only after ${R.eca_notice} days' written notice.` });
    out.push({ date: addDays(first, R.appWindow), key: "app",
      label: `Federal minimum window to apply for financial assistance ends. Applying stops collection actions while your application is reviewed.` });
  }
  if (first && state.household.insured === "uninsured"){
    out.push({ date: addDays(first, R.nsaDays), key: "nsa",
      label: `Only if this care was scheduled and you got a written Good Faith Estimate: last day to start a No Surprises Act dispute when the bill is $${R.nsaGap} or more above it. (Doesn't apply to emergency visits.)` });
  }
  const coll = parseDate(b.collectorDate);
  if (coll){
    out.push({ date: addDays(coll, R.validation), key: "val",
      label: `Ask the collector to validate the debt by this date (${R.validation} days after its first notice).` });
  }
  out.sort((a, c) => a.date - c.date);
  const t = today();
  out.forEach(d => d.past = d.date < t);
  return out;
}
function nextDeadline(b){ return deadlines(b).find(d => !d.past) || null; }

function payoffCompare(balance, monthly, promoMonths, cardApr, loanApr){
  const bal = num(balance), pay = num(monthly), promo = Math.max(0, Math.floor(num(promoMonths) || 0));
  if (!(bal > 0) || !(pay > 0)) return null;
  const MAX = 600;
  const plan = { months: Math.ceil(bal / pay - 1e-9), total: bal, interest: 0 };
  // Medical credit card with deferred interest
  const rc = (num(cardApr) || 0) / 1200;
  let b = bal, accrued = 0, paid = 0, m = 0, trap = 0, never = false;
  while (b > 0.005 && m < MAX){
    m++;
    if (m <= promo){
      accrued += b * rc;
      const p = Math.min(pay, b); b -= p; paid += p;
      if (b <= 0.005) break;
      if (m === promo){ b += accrued; trap = accrued; accrued = 0; }
    } else {
      const i = b * rc;
      if (pay <= i){ never = true; break; }
      b += i; const p = Math.min(pay, b); b -= p; paid += p;
    }
  }
  if (m >= MAX && b > 0.005) never = true;
  const card = never ? { never: true, trap } : { months: m, total: paid, interest: paid - bal, trap };
  // Personal loan, simple amortization at the same monthly payment
  const rl = (num(loanApr) || 0) / 1200;
  let lb = bal, lp = 0, lm = 0, lnever = false;
  while (lb > 0.005 && lm < MAX){
    lm++; const i = lb * rl;
    if (pay <= i){ lnever = true; break; }
    lb += i; const p = Math.min(pay, lb); lb -= p; lp += p;
  }
  if (lm >= MAX && lb > 0.005) lnever = true;
  const loan = lnever ? { never: true } : { months: lm, total: lp, interest: lp - bal };
  return { plan, card, loan };
}

/* ============================================================
   SAVE / OPEN with validation
   ============================================================ */
function exportObject(){ return { app: APP_ID, schemaVersion: SCHEMA_VERSION, savedAt: new Date().toISOString(), data: state }; }
function saveFile(){
  const blob = new Blob([JSON.stringify(exportObject(), null, 2)], { type: "application/json" });
  const a = document.createElement("a");
  a.href = URL.createObjectURL(blob);
  a.download = "medical-bill-fighter-ky.json";
  document.body.appendChild(a); a.click();
  setTimeout(() => { URL.revokeObjectURL(a.href); a.remove(); }, 500);
  markClean(); toast("Saved. Keep the file somewhere safe; it holds your bill details.");
}

function validateFile(obj){
  const errs = [];
  const isStr = (v, max = LIMITS.text) => typeof v === "string" && v.length <= max;
  const isMoneyStr = v => v === "" || (typeof v === "string" || typeof v === "number") && Number.isFinite(num(v)) && num(v) >= 0 && num(v) <= LIMITS.money;
  const isDate = v => v === "" || (typeof v === "string" && parseDate(v) !== null);
  if (!obj || typeof obj !== "object" || Array.isArray(obj)) return { ok: false, errs: ["The file isn't a Medical Bill Fighter save file."] };
  if (obj.app !== APP_ID) errs.push("This file wasn't made by Medical Bill Fighter KY.");
  if (obj.schemaVersion !== SCHEMA_VERSION) errs.push("This file is from an unsupported version.");
  const d = obj.data;
  if (!d || typeof d !== "object") { errs.push("The file has no data section."); return { ok: false, errs }; }
  const h = d.household || {};
  if (!Number.isInteger(h.size) || h.size < 1 || h.size > LIMITS.household) errs.push("Household size must be a whole number from 1 to 20.");
  if (!isMoneyStr(h.income)) errs.push("Household income is not a valid amount.");
  if (!["uninsured", "insured"].includes(h.insured)) errs.push("Insurance status is not valid.");
  const y = d.you || {};
  ["name", "address", "phone"].forEach(k => { if (!isStr(y[k] == null ? "" : y[k], 500)) errs.push(`Your ${k} is not valid text.`); });
  if (!Array.isArray(d.bills) || d.bills.length > LIMITS.bills) errs.push("The bills list is missing or too long.");
  else d.bills.forEach((b, i) => {
    const n = i + 1;
    if (!b || typeof b !== "object") { errs.push(`Bill ${n} is not valid.`); return; }
    if (!isStr(b.id, 40) || !b.id) errs.push(`Bill ${n} has no ID.`);
    if (!DATA.hospitals.some(x => x.id === b.provider)) errs.push(`Bill ${n} has an unknown provider.`);
    ["providerName", "account", "notes"].forEach(k => { if (!isStr(b[k] == null ? "" : b[k])) errs.push(`Bill ${n}: ${k} is not valid text.`); });
    ["billed", "insPaid"].forEach(k => { if (!isMoneyStr(b[k] == null ? "" : b[k])) errs.push(`Bill ${n}: ${k} is not a valid amount.`); });
    ["service", "firstBill", "collectorDate"].forEach(k => { if (!isDate(b[k] == null ? "" : b[k])) errs.push(`Bill ${n}: ${k} is not a valid date.`); });
    if (!DATA.statuses.includes(b.status)) errs.push(`Bill ${n} has an unknown status.`);
  });
  if (d.checklist && (typeof d.checklist !== "object" || Array.isArray(d.checklist))) errs.push("The checklist is not valid.");
  const g = d.gfe || {}; if (!isMoneyStr(g.estimate == null ? "" : g.estimate) || !isMoneyStr(g.billed == null ? "" : g.billed)) errs.push("Good Faith Estimate amounts are not valid.");
  const p = d.pay || {};
  ["balance", "monthly"].forEach(k => { if (!isMoneyStr(p[k] == null ? "" : p[k])) errs.push(`Payment ${k} is not valid.`); });
  ["promo", "cardApr", "loanApr"].forEach(k => { const v = num(p[k]); if (p[k] !== "" && p[k] != null && (!Number.isFinite(v) || v < 0 || v > 100)) errs.push(`Payment ${k} is out of range.`); });
  const l = d.letter || {};
  ["proposed", "errors", "collector", "billId"].forEach(k => { if (!isStr(l[k] == null ? "" : l[k])) errs.push(`Letter field ${k} is not valid.`); });
  if (l.type != null && !LETTERS.some(x => x.id === l.type)) errs.push("Letter type is not valid.");
  return { ok: errs.length === 0, errs };
}

function sanitize(d){
  const s = blankState();
  s.household = { size: d.household.size, income: String(d.household.income ?? ""), insured: d.household.insured };
  s.you = { name: String(d.you?.name ?? ""), address: String(d.you?.address ?? ""), phone: String(d.you?.phone ?? "") };
  s.bills = d.bills.map(b => ({
    id: b.id, provider: b.provider, providerName: String(b.providerName ?? ""), account: String(b.account ?? ""),
    service: b.service ?? "", firstBill: b.firstBill ?? "", collectorDate: b.collectorDate ?? "",
    billed: String(b.billed ?? ""), insPaid: String(b.insPaid ?? ""), status: b.status, notes: String(b.notes ?? "")
  }));
  s.checklist = {}; Object.keys(d.checklist || {}).slice(0, 50).forEach(k => { if (CHECKS.some(c => c.id === k)) s.checklist[k] = !!d.checklist[k]; });
  s.gfe = { estimate: String(d.gfe?.estimate ?? ""), billed: String(d.gfe?.billed ?? "") };
  s.pay = Object.assign(s.pay, { balance: String(d.pay?.balance ?? ""), monthly: String(d.pay?.monthly ?? ""),
    promo: d.pay?.promo ?? 12, cardApr: d.pay?.cardApr ?? 29.99, loanApr: d.pay?.loanApr ?? 14 });
  s.letter = Object.assign(s.letter, { type: d.letter?.type || "aid", billId: String(d.letter?.billId ?? ""), proposed: String(d.letter?.proposed ?? ""),
    errors: String(d.letter?.errors ?? ""), collector: String(d.letter?.collector ?? "") });
  return s;
}

function openFile(file){
  if (!file) return;
  if (file.size > 2 * 1024 * 1024) { showFileError(["That file is too large to be a Medical Bill Fighter save."]); return; }
  const reader = new FileReader();
  reader.onerror = () => showFileError(["The file couldn't be read."]);
  reader.onload = () => {
    let obj;
    try { obj = JSON.parse(reader.result); } catch (e) { showFileError(["The file isn't valid JSON. It may be damaged or not a Medical Bill Fighter save."]); return; }
    const v = validateFile(obj);
    if (!v.ok) { showFileError(v.errs.slice(0, 6)); return; }
    if (dirty && !confirm("You have unsaved changes. Replace them with this file?")) return;
    state = sanitize(obj.data);
    editingBillId = null;
    markClean(); $("#saveStatus").textContent = "Opened " + file.name;
    renderAll(); toast("File opened.");
  };
  reader.readAsText(file);
}
function showFileError(errs){
  toast("That file was not opened. Your current work is unchanged.");
  const box = document.createElement("div");
  box.className = "notice bad"; box.setAttribute("role", "alert");
  box.innerHTML = `<b>That file was not opened. Your current work is unchanged.</b><ul>${errs.map(e => `<li>${esc(e)}</li>`).join("")}</ul>`;
  const v = $("#view"); v.prepend(box);
  setTimeout(() => box.remove(), 12000);
}

/* ============================================================
   TABS
   ============================================================ */
const TABS = [
  { id: "start", label: "Start" },
  { id: "bills", label: "Bills" },
  { id: "aid", label: "Charity Care" },
  { id: "check", label: "Bill Check" },
  { id: "letters", label: "Letters" },
  { id: "pay", label: "Payments" },
  { id: "rights", label: "Deadlines" }
];
function renderTabs(){
  $("#tablist").innerHTML = TABS.map((t, i) =>
    `<button role="tab" id="tab-${t.id}" aria-selected="${t.id === currentTab}" aria-controls="view" tabindex="${t.id === currentTab ? 0 : -1}" data-tab="${t.id}"><span class="n">${i + 1}</span>${t.label}</button>`).join("");
}
function go(tab){ currentTab = tab; renderTabs(); renderView(); window.scrollTo({ top: 0 }); $("#view").focus({ preventScroll: true }); }

function renderSummary(){
  const t = totals();
  if (!t.count){ $("#summaryBar").innerHTML = `<div class="empty small">Add a bill to see how much you may really owe.</div>`; return; }
  const range = t.min === t.max ? money(t.min) : `${money(t.min)}–${money(t.max)}`;
  $("#summaryBar").innerHTML = `
    <div class="stat hero"><div class="lbl">You may owe</div><div class="big">${t.fpl == null ? "Add income" : range}</div></div>
    <div class="stat"><div class="lbl">Your balance</div><div class="big">${money(t.owed)}</div></div>
    <div class="stat"><div class="lbl">Of poverty line</div><div class="big">${t.fpl == null ? "—" : Math.round(t.fpl) + "%"}</div></div>
    <div class="stat"><div class="lbl">Bills</div><div class="big">${t.count}</div></div>`;
}

function renderView(){
  const v = $("#view");
  v.setAttribute("aria-labelledby", "tab-" + currentTab);
  v.innerHTML = VIEWS[currentTab]();
  if (AFTER[currentTab]) AFTER[currentTab]();
}
function renderAll(){ renderTabs(); renderSummary(); renderView(); }

function nextBtn(tab, text){ return `<div class="nextbar noprint"><button class="btn primary" type="button" data-go="${tab}">${text} →</button></div>`; }
/* ---------- 1. START ---------- */
function viewStart(){
  return `
  <div class="card hero-card">
    <h1>Got a medical bill you can't pay? You may not have to.</h1>
    <p>Many Kentuckians qualify for free or discounted hospital care and never apply. In a few minutes this tool shows what you may really owe, writes your letters, and tracks your deadlines. Nothing you type leaves this page.</p>
    <div class="row noprint">
      <button class="btn primary" data-go="bills" type="button">Start with your bill</button>
      <button class="btn" id="btnExample" type="button">See a 1-minute example</button>
    </div>
  </div>
  <div class="card">
    <h2>Why this matters in Kentucky</h2>
    <div class="grid g4">
      ${DATA.facts.map(f => `<p class="fact"><b>${esc(f.big)}</b>${esc(f.text)} <a href="${esc(f.src)}" target="_blank" rel="noopener" class="small">Source</a></p>`).join("")}
    </div>
  </div>
  <div class="card">
    <h2>How it works</h2>
    <div class="steps">
      <div class="step"><h3>Check</h3><p class="small">Add your bills and income. See if you likely qualify for free or discounted care, and check your bill for errors.</p></div>
      <div class="step"><h3>Apply</h3><p class="small">Get ready-to-send letters: financial assistance, itemized bill, dispute, debt validation, payment plan.</p></div>
      <div class="step"><h3>Resolve</h3><p class="small">Track federal deadlines for every bill and compare payment options before you sign anything.</p></div>
    </div>
  </div>
  <div class="card">
    <p class="disclaimer"><b>Educational use only.</b> A learning tool, not financial, legal, tax or medical advice. No account, no login, no bank connection. Use <b>Save to file</b> to keep your work on your own device. Hospital policies change, so confirm numbers with the hospital, and call legal aid if you've been sued.</p>
    <div class="row noprint" style="margin-top:10px"><button class="btn small danger" id="btnClear" type="button">Clear everything</button></div>
  </div>`;
}
const EXAMPLE = () => ({
  household: { size: 3, income: "52000", insured: "uninsured" },
  you: { name: "Dana Example", address: "100 Main St, Hazard, KY 41701", phone: "(606) 555-0100" },
  bills: [
    { id: uid(), provider: "ukhc", providerName: "", account: "UK-448812", service: isoDaysAgo(70), firstBill: isoDaysAgo(45), collectorDate: "",
      billed: "8400", insPaid: "0", status: "New", notes: "ER visit after a fall, uninsured after a job change." },
    { id: uid(), provider: "provider", providerName: "Eastern KY Imaging", account: "EKI-2291", service: isoDaysAgo(70), firstBill: isoDaysAgo(60), collectorDate: isoDaysAgo(10),
      billed: "1250", insPaid: "0", status: "In collections", notes: "Sent to a collection agency." }
  ],
  checklist: {},
  gfe: { estimate: "", billed: "" },
  pay: { balance: "1250", monthly: "100", promo: 12, cardApr: 29.99, loanApr: 14 },
  letter: { type: "aid", billId: "", proposed: "75", errors: "", collector: "Bluegrass Recovery Services" }
});
function isoDaysAgo(n){ const d = addDays(today(), -n); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; }

/* ---------- 2. BILLS ---------- */
function viewBills(){
  const fpl = fplPercent(state.household.income, state.household.size);
  const rows = state.bills.map(b => {
    const h = hosp(b.provider); const e = aidEstimate(b, fpl); const nd = nextDeadline(b);
    const range = e.min === e.max ? money(e.min) : `${money(e.min)}–${money(e.max)}`;
    return `<tr>
      <td><b>${esc(b.provider === "provider" || b.provider === "otherhosp" || b.provider === "forprofit" ? (b.providerName || h.name) : h.name)}</b><div class="small muted">${esc(b.account ? "Acct " + b.account : "")}${b.service ? " · Service " + fmtDate(parseDate(b.service)) : ""}</div></td>
      <td class="num">${money(billBalance(b))}</td>
      <td><span class="pill ${e.tone}">${esc(e.short)}</span><div class="small">${range}</div></td>
      <td>${esc(b.status)}</td>
      <td class="small">${nd ? `<b>${fmtDate(nd.date)}</b><br>${esc(nd.label.split(".")[0])}` : '<span class="muted">—</span>'}</td>
      <td class="noprint"><button class="btn small" data-edit="${esc(b.id)}" type="button" aria-label="Edit bill">Edit</button> <button class="btn small danger" data-del="${esc(b.id)}" type="button" aria-label="Delete bill">Delete</button></td>
    </tr>`;
  }).join("");
  return `
  <div class="card">
    <div class="row"><h1 style="margin:0">My bills</h1><button class="btn primary right noprint" id="btnAddBill" type="button">+ Add a bill</button></div>
    <p class="muted">Add every medical bill you're dealing with. Each one gets its own estimate and deadlines.</p>
    ${state.bills.length ? `<div class="tablewrap"><table class="stack">
      <thead><tr><th>Provider</th><th class="num">Balance</th><th>Estimate</th><th>Status</th><th>Next deadline</th><th class="noprint"><span class="sr">Actions</span></th></tr></thead>
      <tbody>${rows}</tbody></table></div>` : `<div class="notice muted">No bills yet. Click <b>Add a bill</b>, or load the example on the Start tab.</div>`}
    ${fpl == null && state.bills.length ? `<div class="notice info">Estimates need your household size and income. <a href="#" data-go="aid">Enter them on the Charity Care tab.</a></div>` : ""}
  </div>
  <div id="billEditor"></div>
  ${state.bills.length ? nextBtn("aid", "Next: see what you may owe") : ""}`;
}
function billEditorHTML(b){
  const opts = DATA.hospitals.map(h => `<option value="${h.id}" ${b.provider === h.id ? "selected" : ""}>${esc(h.name)}</option>`).join("");
  const st = DATA.statuses.map(s => `<option ${b.status === s ? "selected" : ""}>${esc(s)}</option>`).join("");
  const needsName = ["provider", "otherhosp", "forprofit"].includes(b.provider);
  return `<div class="card" id="editorCard">
    <h2>${state.bills.some(x => x.id === b.id) ? "Edit bill" : "Add a bill"}</h2>
    <form id="billForm" novalidate>
      <div class="grid g2">
        <div class="field"><label for="f_provider">Who sent the bill?</label><select id="f_provider" name="provider">${opts}</select></div>
        <div class="field" id="nameWrap" ${needsName ? "" : "hidden"}><label for="f_providerName">Provider name</label><input type="text" id="f_providerName" name="providerName" maxlength="200" value="${esc(b.providerName)}"></div>
        <div class="field"><label for="f_status">Status</label><select id="f_status" name="status">${st}</select></div>
        <div class="field"><label for="f_billed">Amount billed ($)</label><input type="number" id="f_billed" name="billed" min="0" step="0.01" inputmode="decimal" value="${esc(b.billed)}"></div>
        <div class="field"><label for="f_insPaid">Paid by insurance so far ($) <span class="hint">(0 if none)</span></label><input type="number" id="f_insPaid" name="insPaid" min="0" step="0.01" inputmode="decimal" value="${esc(b.insPaid)}"></div>
        <div class="field"><label for="f_service">Date of service</label><input type="date" id="f_service" name="service" value="${esc(b.service)}"></div>
        <div class="field"><label for="f_firstBill">Date of the first bill after you left <span class="hint">(starts federal deadlines)</span></label><input type="date" id="f_firstBill" name="firstBill" value="${esc(b.firstBill)}"></div>
      </div>
      <details class="more" ${b.account || b.collectorDate || b.notes ? "open" : ""}><summary>More details (optional)</summary>
        <div class="grid g2" style="margin-top:8px">
          <div class="field"><label for="f_account">Account number</label><input type="text" id="f_account" name="account" maxlength="60" value="${esc(b.account)}"></div>
          <div class="field"><label for="f_collectorDate">Collector's first notice date <span class="hint">(if it went to collections)</span></label><input type="date" id="f_collectorDate" name="collectorDate" value="${esc(b.collectorDate)}"></div>
          <div class="field"><label for="f_notes">Notes</label><input type="text" id="f_notes" name="notes" maxlength="500" value="${esc(b.notes)}"></div>
        </div>
      </details>
      <p class="small muted" id="provNote">${esc(hosp(b.provider).note)}</p>
      <div id="formErr"></div>
      <div class="row"><button class="btn primary" type="submit">Save bill</button><button class="btn" type="button" id="btnCancelBill">Cancel</button></div>
    </form></div>`;
}
function newBill(){ return { id: uid(), provider: "otherhosp", providerName: "", account: "", status: "New", billed: "", insPaid: "", service: "", firstBill: "", collectorDate: "", notes: "" }; }

/* ---------- 3. CHARITY CARE ---------- */
function viewAid(){
  const h = state.household;
  return `
  <div class="card">
    <h1>Charity care check</h1>
    <p>Nonprofit hospitals must offer free or discounted care to patients who qualify, based mostly on household income compared with the federal poverty line. Kentucky has no state rules, so each hospital sets its own cutoffs.</p>
    <div class="grid g3">
      <div class="field"><label for="hh_size">People in your household</label><input type="number" id="hh_size" min="1" max="20" step="1" value="${esc(h.size)}" data-bind="household.size"></div>
      <div class="field"><label for="hh_income">Household income per year, before taxes ($)</label><input type="number" id="hh_income" min="0" step="100" inputmode="decimal" value="${esc(h.income)}" data-bind="household.income"></div>
      <div class="field"><label for="hh_ins">Insurance</label><select id="hh_ins" data-bind="household.insured">
        <option value="uninsured" ${h.insured === "uninsured" ? "selected" : ""}>No insurance</option>
        <option value="insured" ${h.insured === "insured" ? "selected" : ""}>Have insurance (still owe a balance)</option></select></div>
    </div>
    <div id="aidOut"></div>
  </div>
  <div class="card"><h2>Your bills</h2><div id="aidBills"></div></div>
  ${state.bills.length ? nextBtn("letters", "Next: write your letter") : ""}
  <div class="card"><details class="fold"><summary><h2>Kentucky hospital policies in this tool</h2></summary><div style="margin-top:12px">
    <div class="tablewrap"><table class="stack"><thead><tr><th>Hospital</th><th class="num">Free up to</th><th class="num">Discount up to</th><th>Notes</th></tr></thead><tbody>
    ${DATA.hospitals.filter(x => x.kind === "hospital" && x.id !== "otherhosp").map(x => `<tr>
      <td><b>${esc(x.name)}</b>${x.phone ? `<div class="small">${esc(x.phone)}</div>` : ""}</td>
      <td class="num" data-label="Free up to">${x.freeTo ? x.freeTo + "%" : "Ask"}</td>
      <td class="num" data-label="Discount up to">${x.discTo ? x.discTo + "%" + (x.discPct ? ` (${x.discPct}% off)` : "") : (x.freeTo ? "—" : "Ask")}</td>
      <td class="small">${esc(x.note)} ${x.src ? `<a href="${esc(x.src)}" target="_blank" rel="noopener">Source</a>` : ""}</td></tr>`).join("")}
    </tbody></table></div>
    <p class="small muted">Percent of the ${DATA.fpl.year} federal poverty guidelines. Checked ${esc(DATA.checked)}. Policies also look at assets and other factors; only the hospital can decide.</p>
  </div></details></div>`;
}
function aidOutputs(){
  const fpl = fplPercent(state.household.income, state.household.size);
  const out = $("#aidOut"); if (!out) return;
  if (fpl == null){ out.innerHTML = `<div class="notice muted">Enter your household size and income to see where you stand.</div>`; }
  else {
    const g = guideline(state.household.size);
    const pos = Math.min(100, fpl / 400 * 100);
    const medicaid = fpl <= DATA.medicaidAdultPct;
    out.innerHTML = `
      <div class="grid g2" style="align-items:center">
        <div><div class="bignum">${Math.round(fpl)}%</div><div class="muted">of the ${DATA.fpl.year} poverty line (${money(g)} for ${state.household.size} ${state.household.size == 1 ? "person" : "people"})</div></div>
        <div>
          <div class="meter" role="img" aria-label="${Math.round(fpl)} percent of the poverty line on a scale to 400 percent">
            <span class="mk" style="left:calc(${pos}% - 1px)"></span><span class="you" style="left:${pos}%">You</span>
            ${[0, 138, 200, 300, 350, 400].map(v => `<span class="tick" style="left:${v / 4}%">${v}%</span>`).join("")}
          </div>
          <div class="small muted">Green: many Kentucky hospitals give free care here. Yellow: often discounted. Red: usually over the limit.</div>
        </div>
      </div>
      ${medicaid ? `<div class="notice good"><b>You may qualify for Kentucky Medicaid.</b> Adults with income up to ${DATA.medicaidAdultPct}% of the poverty line can usually get it. Apply at <a href="https://kynect.ky.gov" target="_blank" rel="noopener">kynect</a> first, and ask whether coverage can reach back to cover these bills. Hospitals often require a Medicaid application before charity care. <a href="${DATA.rights.srcMedicaid}" target="_blank" rel="noopener" class="small">Source</a></div>` : ""}
      ${state.household.insured === "insured" ? `<div class="notice info">Have insurance? Many policies still cover what you owe after insurance (deductibles and coinsurance). Ask the hospital whether its policy covers insured patients' balances.</div>` : ""}`;
  }
  const ab = $("#aidBills"); if (!ab) return;
  if (!state.bills.length){ ab.innerHTML = `<div class="notice muted">No bills yet. <a href="#" data-go="bills">Add one on My Bills.</a></div>`; return; }
  const t = totals();
  ab.innerHTML = state.bills.map(b => {
    const e = aidEstimate(b, fpl); const h = hosp(b.provider);
    const range = e.min === e.max ? money(e.min) : `${money(e.min)}–${money(e.max)}`;
    return `<div class="notice ${e.tone}"><div class="row"><b>${esc(b.providerName || h.name)}</b><span class="pill ${e.tone} right">${esc(e.short)}</span></div>
      <div>Balance ${money(e.owed)} → you may owe <b>${range}</b></div><div class="small">${esc(e.label)}</div>
      ${h.url ? `<div class="small"><a href="${esc(h.url)}" target="_blank" rel="noopener">Hospital's financial assistance page</a>${h.phone ? " · " + esc(h.phone) : ""}</div>` : ""}</div>`;
  }).join("") + (fpl != null ? (() => {
    const likely = t.owed - t.max, possible = t.owed - t.min;
    const line = likely === possible
      ? `About ${money(likely)} of your ${money(t.owed)} balance is likely forgivable.`
      : `About ${money(likely)} of your ${money(t.owed)} balance is likely forgivable, and up to ${money(possible)} if every application is approved.`;
    return `<p><b>${line}</b> <a href="#" data-go="letters">Write your application letter →</a></p>`;
  })() : "");
}

/* ---------- 4. BILL CHECK ---------- */
const CHECKS = [
  { id: "itemized", t: "Ask for an itemized bill", h: "A summary bill hides errors. You have a right to see every charge. The Letters tab writes this request." },
  { id: "eob", t: "Match it to your insurer's Explanation of Benefits", h: "If insured: the amount you owe on the bill should match \"patient responsibility\" on the EOB." },
  { id: "billed", t: "Make sure insurance (or Medicaid) was actually billed", h: "Call the billing office and ask which insurer they billed and when." },
  { id: "dupes", t: "Look for duplicate charges", h: "The same code or item listed twice on the same date." },
  { id: "notreceived", t: "Look for services you didn't receive", h: "Medicines, supplies or tests you don't remember. Ask what each code means." },
  { id: "dates", t: "Check dates and your name, birthday and insurance ID", h: "A wrong ID is one of the most common reasons a claim gets denied." },
  { id: "room", t: "Check room and time charges", h: "Count the days billed for a room, or the minutes billed for surgery or anesthesia." },
  { id: "hold", t: "Ask the billing office to hold the account while you review", h: "Write down the date, the person's name and what they said." }
];
function viewCheck(){
  return `
  <div class="card">
    <h1>Bill check</h1>
    <p>Billing errors are common. Go through this list before you pay anything. Your progress is saved with your file.</p>
    ${CHECKS.map(c => `<div class="check"><input type="checkbox" id="chk_${c.id}" data-check="${c.id}" ${state.checklist[c.id] ? "checked" : ""}><div><label for="chk_${c.id}">${esc(c.t)}</label><span class="hint">${esc(c.h)}</span></div></div>`).join("")}
    <p class="small" id="checkProg"></p>
  </div>
  <div class="card">
    <h2>No insurance? Compare your bill to your Good Faith Estimate</h2>
    <p>If you were uninsured or paid yourself and the care was scheduled at least 3 business days ahead, the provider had to give you a written Good Faith Estimate. If the bill is $${DATA.rights.nsaGap} or more above it, you can dispute it under the federal No Surprises Act, usually within ${DATA.rights.nsaDays} days of the bill. <a href="${DATA.rights.srcNSA}" target="_blank" rel="noopener">CMS medical bill rights</a></p>
    <div class="grid g2">
      <div class="field"><label for="gfe_e">Good Faith Estimate total ($)</label><input type="number" id="gfe_e" min="0" step="0.01" value="${esc(state.gfe.estimate)}" data-bind="gfe.estimate"></div>
      <div class="field"><label for="gfe_b">Billed total for the same provider ($)</label><input type="number" id="gfe_b" min="0" step="0.01" value="${esc(state.gfe.billed)}" data-bind="gfe.billed"></div>
    </div>
    <div id="gfeOut"></div>
  </div>
  ${nextBtn("letters", "Next: write your letters")}
  ${aiCard("explain")}`;
}
function checkOutputs(){
  const done = CHECKS.filter(c => state.checklist[c.id]).length;
  const p = $("#checkProg"); if (p) p.textContent = `${done} of ${CHECKS.length} done.`;
  const o = $("#gfeOut"); if (!o) return;
  const e = num(state.gfe.estimate), b = num(state.gfe.billed);
  if (!(e >= 0) || !(b >= 0) || state.gfe.estimate === "" || state.gfe.billed === ""){ o.innerHTML = ""; return; }
  const diff = b - e;
  o.innerHTML = diff >= DATA.rights.nsaGap
    ? `<div class="notice warn"><b>Your bill is ${money2(diff)} above the estimate.</b> That meets the $${DATA.rights.nsaGap} threshold for a federal dispute. Start it within ${DATA.rights.nsaDays} days of the bill through the CMS No Surprises help desk.</div>`
    : `<div class="notice muted">The bill is ${diff >= 0 ? money2(diff) + " above" : money2(-diff) + " below"} the estimate, under the $${DATA.rights.nsaGap} dispute threshold. You can still ask the provider to explain the difference.</div>`;
}

/* ---------- 5. LETTERS ---------- */
const LETTERS = [
  { id: "aid", name: "Financial assistance application cover letter", to: "provider" },
  { id: "itemized", name: "Itemized bill request", to: "provider" },
  { id: "dispute", name: "Billing error dispute", to: "provider" },
  { id: "validation", name: "Debt validation request (to a collector)", to: "collector" },
  { id: "plan", name: "Hardship payment plan request", to: "provider" }
];
function letterValues(b, placeholders){
  const fpl = fplPercent(state.household.income, state.household.size);
  const h = b ? hosp(b.provider) : null;
  const v = {
    NAME: state.you.name, ADDRESS: state.you.address, PHONE: state.you.phone,
    TODAY: fmtDate(today()),
    PROVIDER: b ? (b.providerName || h.name) : "",
    ACCOUNT: b ? b.account : "",
    SERVICE: b && b.service ? fmtDate(parseDate(b.service)) : "",
    BALANCE: b ? money2(billBalance(b)) : "",
    SIZE: String(state.household.size || ""),
    INCOME: state.household.income !== "" ? money(num(state.household.income)) : "",
    FPL: fpl == null ? "" : String(Math.round(fpl)),
    PROPOSED: state.letter.proposed !== "" && num(state.letter.proposed) > 0 ? money2(num(state.letter.proposed)) : "",
    ERRORS: state.letter.errors,
    COLLECTOR: state.letter.collector,
    NOTICE: b && b.collectorDate ? fmtDate(parseDate(b.collectorDate)) : ""
  };
  if (placeholders) Object.keys(v).forEach(k => { if (k !== "TODAY") v[k] = ""; });
  return { v, h };
}
function letterTemplate(type, h){
  const head = `{NAME}\n{ADDRESS}\n{PHONE}\n\n{TODAY}\n\n`;
  const toProv = `To: {PROVIDER}, Patient Financial Services\nRe: Account {ACCOUNT}, date of service {SERVICE}\n\n`;
  const sign = `\n\nSincerely,\n\n{NAME}`;
  const np = !h || h.nonprofit !== false;
  switch (type){
    case "aid": return head + toProv +
`To whom it may concern:

Please accept my enclosed application for financial assistance under your Financial Assistance Policy for the account above. The balance is {BALANCE}.

My household has {SIZE} people and an annual income of about {INCOME}, which is about {FPL}% of the 2026 federal poverty guidelines. Based on your published policy, I believe I may qualify for free or discounted care.
${np ? `
While my application is under review, please suspend all collection actions on this account, as federal rules require of nonprofit hospitals (26 C.F.R. § 1.501(r)-6). If any part of this account has been sent to a collection agency or reported to a credit bureau, please recall it.
` : `
While my application is under review, please place this account on hold and do not send it to collections.
`}
Please tell me in writing if you need more documents, and send me your decision in writing.` + sign;
    case "itemized": return head + toProv +
`To whom it may concern:

Please send me a complete itemized statement for the account above. For each charge, please include the date, a description, the billing code (CPT, HCPCS or revenue code), the quantity and the amount, along with all payments and adjustments.

Please place this account on hold while I review the statement, and do not send it to collections during that time. Please also send me a copy of your Financial Assistance Policy and application.` + sign;
    case "dispute": return head + toProv +
`To whom it may concern:

I am disputing charges on the account above. After reviewing my itemized statement, I believe the following charges are wrong:

{ERRORS}

Please review these charges, correct my bill, and send me an updated itemized statement. Please do not send this account to collections or report it to a credit bureau while this dispute is open.` + sign;
    case "validation": return head +
`To: {COLLECTOR}
Re: Account {ACCOUNT} (original creditor: {PROVIDER})

To whom it may concern:

I am writing in response to your notice dated {NOTICE}. I dispute this debt and request validation under the Fair Debt Collection Practices Act. Please send me:

1. The name of the original creditor and the account number with that creditor.
2. An itemized statement of the amount you say I owe, including any interest or fees.
3. Proof that you are authorized to collect this debt.
4. A copy of any agreement I signed to pay it.

Please stop collection activity until you send this information. I am also applying for financial assistance with the original provider. Please contact me in writing only.` + sign;
    case "plan": return head + toProv +
`To whom it may concern:

I want to resolve the account above, but my income does not allow me to pay {BALANCE} at once. I am requesting an interest-free monthly payment plan of {PROPOSED} per month.

Please also let me know whether I qualify for financial assistance, a self-pay or prompt-pay discount, or a hardship reduction. Please confirm any plan in writing, and keep the account out of collections while I make the agreed payments.` + sign;
  }
  return "";
}
function fillLetter(type, b, mode){
  // mode: "html" (marks missing), "text" (missing shown as [FIELD]), "placeholder" (all personal fields as [FIELD])
  const { v, h } = letterValues(b, mode === "placeholder");
  const t = letterTemplate(type, h);
  const parts = t.split(/(\{[A-Z]+\})/g);
  return parts.map(p => {
    const m = /^\{([A-Z]+)\}$/.exec(p);
    if (!m) return mode === "html" ? esc(p) : p;
    const val = v[m[1]];
    if (val) return mode === "html" ? esc(val) : val;
    return mode === "html" ? `<mark>[${m[1]}]</mark>` : `[${m[1]}]`;
  }).join("");
}
function viewLetters(){
  const L = state.letter;
  const billOpts = state.bills.map(b => `<option value="${esc(b.id)}" ${L.billId === b.id ? "selected" : ""}>${esc((b.providerName || hosp(b.provider).name) + " — " + money(billBalance(b)))}</option>`).join("");
  return `
  <div class="card noprint">
    <h1>Letter builder</h1>
    <p>Pick a letter and a bill. Your details fill in automatically. Anything highlighted in yellow is missing. Send letters by certified mail or the hospital's patient portal, and keep copies.</p>
    <div class="grid g2">
      <div class="field"><label for="l_type">Letter</label><select id="l_type" data-bind="letter.type">${LETTERS.map(x => `<option value="${x.id}" ${L.type === x.id ? "selected" : ""}>${esc(x.name)}</option>`).join("")}</select></div>
      <div class="field"><label for="l_bill">Bill</label><select id="l_bill" data-bind="letter.billId"><option value="">Choose a bill…</option>${billOpts}</select></div>
    </div>
    <details ${state.you.name ? "" : "open"}><summary>Your contact details (used in letters)</summary>
      <div class="grid g3" style="margin-top:10px">
        <div class="field"><label for="y_name">Your name</label><input type="text" id="y_name" maxlength="200" value="${esc(state.you.name)}" data-bind="you.name"></div>
        <div class="field"><label for="y_addr">Mailing address</label><input type="text" id="y_addr" maxlength="300" value="${esc(state.you.address)}" data-bind="you.address"></div>
        <div class="field"><label for="y_phone">Phone</label><input type="text" id="y_phone" maxlength="40" value="${esc(state.you.phone)}" data-bind="you.phone"></div>
      </div></details>
    <div id="letterExtras"></div>
  </div>
  <div class="card">
    <div class="row noprint"><h2 style="margin:0">Preview</h2>
      <div class="right row"><button class="btn small" id="btnCopy" type="button">Copy</button><button class="btn small" id="btnTxt" type="button">Download .txt</button><button class="btn small" id="btnPrint" type="button">Print</button></div></div>
    <div class="letter" id="letterOut" style="margin-top:12px"></div>
  </div>
  ${nextBtn("pay", "Next: compare payment options")}
  ${aiCard("polish")}`;
}
function letterOutputs(){
  const L = state.letter;
  if (L.type === "validation"){
    const cur = state.bills.find(x => x.id === L.billId);
    const coll = state.bills.find(x => x.collectorDate || x.status === "In collections");
    if (coll && (!cur || !(cur.collectorDate || cur.status === "In collections"))){ L.billId = coll.id; const sel = $("#l_bill"); if (sel) sel.value = coll.id; }
  }
  const ex = $("#letterExtras"); if (!ex) return;
  let extra = "";
  if (L.type === "plan") extra = `<div class="field"><label for="l_prop">Monthly payment you can afford ($)</label><input type="number" id="l_prop" min="1" step="1" value="${esc(L.proposed)}" data-bind="letter.proposed"></div>`;
  if (L.type === "dispute") extra = `<div class="field"><label for="l_err">Which charges are wrong? <span class="hint">(one per line: date, code, amount, why)</span></label><textarea id="l_err" maxlength="2000" data-bind="letter.errors">${esc(L.errors)}</textarea></div>`;
  if (L.type === "validation") extra = `<div class="field"><label for="l_coll">Collection agency name</label><input type="text" id="l_coll" maxlength="200" value="${esc(L.collector)}" data-bind="letter.collector"></div>`;
  if (ex.dataset.type !== L.type){ ex.innerHTML = extra; ex.dataset.type = L.type; bindInputs(ex); }
  const b = state.bills.find(x => x.id === L.billId) || null;
  $("#letterOut").innerHTML = fillLetter(L.type, b, "html");
}

/* ---------- 6. PAY IT SMART ---------- */
function viewPay(){
  const p = state.pay;
  return `
  <div class="card">
    <h1>Pay it smart</h1>
    <p>Apply for financial assistance first. If you still owe money, compare before you sign. Hospitals often offer interest-free plans. Medical credit cards often advertise "no interest" but use <b>deferred interest</b>: if the balance isn't paid in full by the end of the promo, all the interest from day one is added at once.</p>
    <div class="grid g3">
      <div class="field"><label for="p_bal">Amount to pay off ($)</label><input type="number" id="p_bal" min="0" step="1" value="${esc(p.balance)}" data-bind="pay.balance"></div>
      <div class="field"><label for="p_mon">Monthly payment you can afford ($)</label><input type="number" id="p_mon" min="1" step="1" value="${esc(p.monthly)}" data-bind="pay.monthly"></div>
      <div class="field"><label for="p_promo">Credit card promo length (months)</label><input type="number" id="p_promo" min="0" max="60" step="1" value="${esc(p.promo)}" data-bind="pay.promo"></div>
      <div class="field"><label for="p_capr">Credit card APR after promo (%) <span class="hint">check your card's terms</span></label><input type="number" id="p_capr" min="0" max="100" step="0.01" value="${esc(p.cardApr)}" data-bind="pay.cardApr"></div>
      <div class="field"><label for="p_lapr">Personal loan APR (%)</label><input type="number" id="p_lapr" min="0" max="100" step="0.01" value="${esc(p.loanApr)}" data-bind="pay.loanApr"></div>
      <div class="field"><label>&nbsp;</label><button class="btn small" id="btnUseTotal" type="button">Use my total balance</button></div>
    </div>
    <div id="payOut"></div>
  </div>
  ${nextBtn("rights", "Next: your deadlines")}`;
}
function payOutputs(){
  const o = $("#payOut"); if (!o) return;
  const p = state.pay;
  const r = payoffCompare(p.balance, p.monthly, p.promo, p.cardApr, p.loanApr);
  if (!r){ o.innerHTML = `<div class="notice muted">Enter an amount and a monthly payment to compare.</div>`; return; }
  const items = [
    { name: "Hospital interest-free plan", res: r.plan, color: "#1d7a46" },
    { name: "Medical credit card (deferred interest)", res: r.card, color: "#a3262a" },
    { name: "Personal loan", res: r.loan, color: "#2b5797" }
  ];
  const finite = items.filter(i => !i.res.never);
  const maxT = Math.max(...finite.map(i => i.res.total), 1);
  const W = 640, rowH = 54, H = items.length * rowH + 10, labelW = 0;
  const bars = items.map((it, i) => {
    const y = i * rowH + 6;
    if (it.res.never) return `<text x="0" y="${y + 14}" font-weight="700" fill="#16243a">${esc(it.name)}</text><text x="0" y="${y + 34}" fill="#a3262a">Never paid off at this payment: the interest is more than your payment.</text>`;
    const w = Math.max(4, (it.res.total / maxT) * (W - 170));
    return `<text x="0" y="${y + 14}" font-weight="700" fill="#16243a">${esc(it.name)}</text>
      <rect x="0" y="${y + 20}" width="${w}" height="20" rx="4" fill="${it.color}"></rect>
      <text x="${w + 8}" y="${y + 35}" fill="#16243a" font-weight="700">${money(it.res.total)}</text>
      <text x="${w + 8 + 70}" y="${y + 35}">${it.res.months} mo</text>`;
  }).join("");
  const best = finite.slice().sort((a, b) => a.res.total - b.res.total)[0];
  const card = r.card;
  const extra = card.never ? "" : (card.trap > 0
    ? `<div class="notice bad"><b>The deferred-interest trap:</b> at ${money(num(p.monthly))}/month you won't finish within ${p.promo} months, so ${money2(card.trap)} of back interest lands at once. The card costs ${money(card.total - r.plan.total)} more than the hospital plan.</div>`
    : `<div class="notice good">At this payment you'd pay off the card within the promo, so no interest. Miss one payment or fall short and the deferred interest could still hit.</div>`);
  const needed = Math.ceil(num(p.balance) / Math.max(1, Math.floor(num(p.promo) || 0)));
  o.innerHTML = `
    <svg class="chart" viewBox="0 0 ${W} ${H}" width="100%" role="img" aria-label="Total cost comparison">${bars}</svg>
    <div class="notice good"><b>Cheapest: ${esc(best.name)}</b>, ${money(best.res.total)} total over ${best.res.months} months.</div>
    ${extra}
    ${num(p.promo) > 0 ? `<p class="small muted">To beat the promo you'd need about ${money(needed)} a month for ${Math.floor(num(p.promo))} months.</p>` : ""}
    <p class="small muted">Estimates use monthly interest and equal payments. Real card and loan terms vary; read the agreement before signing. Not a recommendation of any lender or product.</p>`;
}

/* ---------- 7. RIGHTS & DEADLINES ---------- */
function viewRights(){
  const R = DATA.rights;
  const tl = state.bills.map(b => {
    const ds = deadlines(b); const h = hosp(b.provider);
    return `<h3 style="margin-top:14px">${esc(b.providerName || h.name)} <span class="tag">${money(billBalance(b))}</span></h3>
      ${ds.length ? `<ul class="timeline">${ds.map(d => `<li class="${d.past ? "past" : ""}"><span class="d">${fmtDate(d.date)}${d.past ? '<br><span class="tag">passed</span>' : ""}</span><span>${esc(d.label)}</span></li>`).join("")}</ul>`
      : `<p class="small muted">Add the date of the first bill${state.household.insured === "uninsured" ? "" : ""} to see deadlines.</p>`}`;
  }).join("");
  return `
  <div class="card">
    <h1>Rights & deadlines</h1>
    <p>Dates are counted from the first bill you got after leaving the hospital (and, for collectors, from their first notice). Write them on your calendar.</p>
    ${state.bills.length ? tl : `<div class="notice muted">No bills yet. <a href="#" data-go="bills">Add one</a> to build your timeline.</div>`}
  </div>
  <div class="grid g2">
    <div class="card">
      <h2>Federal protections</h2>
      <ul>
        <li><b>Nonprofit hospitals</b> must publish a Financial Assistance Policy, accept applications for at least ${R.appWindow} days after the first bill, wait ${R.eca} days before lawsuits, credit reporting or selling debt, and give ${R.eca_notice} days' written notice first. Applying pauses those actions. <a href="${R.src501r}" target="_blank" rel="noopener">IRS 501(r)</a></li>
        <li><b>No Surprises Act:</b> uninsured or self-pay patients can dispute a bill $${R.nsaGap}+ over the Good Faith Estimate. Insured patients are protected from most surprise out-of-network bills. <a href="${R.srcNSA}" target="_blank" rel="noopener">CMS</a></li>
        <li><b>Debt collectors</b> must tell you the amount and creditor, and if you dispute within ${R.validation} days of their notice they must pause and verify the debt. <a href="${R.srcFDCPA}" target="_blank" rel="noopener">CFPB</a></li>
        <li><b>Credit reports:</b> a 2025 court ruling struck down the federal rule that would have removed medical debt from credit reports. Check your reports for free and dispute errors. <a href="https://www.annualcreditreport.com" target="_blank" rel="noopener">AnnualCreditReport.com</a></li>
      </ul>
    </div>
    <div class="card">
      <h2>Kentucky specifics</h2>
      <ul>
        <li><b>No state charity care law.</b> Each hospital sets its own rules, so read its policy.</li>
        <li><b>No state cap on medical debt interest</b> and no state wage-garnishment limit beyond federal law; after a court judgment, federal law generally caps garnishment at 25% of disposable pay. <a href="${R.srcCaps}" target="_blank" rel="noopener">Source</a></li>
        <li><b>Homestead exemption is only $5,000</b>, among the lowest in the country, so a court judgment can reach home equity. If you're sued, contact legal aid right away. <a href="${R.srcHomestead}" target="_blank" rel="noopener">Source</a></li>
        <li><b>Time limit to sue:</b> generally 5 years on an unwritten account and 10 years if you signed a written agreement after July 15, 2014 (KRS 413.120, 413.160). A court judgment can be enforced for 15 years. Making a payment may restart the clock. <a href="${R.srcSOL}" target="_blank" rel="noopener">Source</a></li>
        <li><b>Never ignore court papers.</b> Missing your court date usually means the creditor wins automatically.</li>
      </ul>
    </div>
  </div>
  <div class="card">
    <h2>Kentucky help</h2>
    <div class="grid g2">${DATA.directory.map(d => `<div><b><a href="${esc(d.url)}" target="_blank" rel="noopener">${esc(d.name)}</a></b><div class="small">${esc(d.what)}</div></div>`).join("")}</div>
  </div>
  <div class="card"><details class="fold"><summary><h2>Sources</h2></summary>
    <p class="small muted" style="margin-top:10px">Every number in this tool, with where it came from. Checked ${esc(DATA.checked)}.</p>
    <ul class="srcs">
      <li>${DATA.fpl.year} federal poverty guidelines: ${money(DATA.fpl.base)} for 1 person, plus ${money(DATA.fpl.add)} per additional person. <a href="${DATA.fpl.src}" target="_blank" rel="noopener">HHS</a></li>
      <li>Kentucky adult Medicaid limit: ${DATA.medicaidAdultPct}% of the poverty line. <a href="${R.srcMedicaid}" target="_blank" rel="noopener">Source</a></li>
      ${DATA.facts.map(f => `<li>${esc(f.big)}: ${esc(f.text)} <a href="${esc(f.src)}" target="_blank" rel="noopener">Source</a></li>`).join("")}
      ${DATA.hospitals.filter(h => h.src && h.freeTo).map(h => `<li>${esc(h.name)}: free up to ${h.freeTo}%${h.discTo ? `, discount to ${h.discTo}%` : ""}. <a href="${esc(h.src)}" target="_blank" rel="noopener">Policy source</a></li>`).join("")}
      <li>Kentucky statute of limitations. <a href="${R.srcSOL}" target="_blank" rel="noopener">FindLaw</a> · <a href="${R.srcSOL2}" target="_blank" rel="noopener">KRS 413.160</a></li>
    </ul>
    <details class="noprint"><summary>Run built-in calculation checks</summary><div id="testOut" class="small" style="margin-top:8px"></div><button class="btn small" id="btnTests" type="button">Run checks</button></details>
  </details></div>`;
}

/* ============================================================
   OPTIONAL AI HELPER (user's own Anthropic key)
   ============================================================ */
function aiCard(kind){
  const title = kind === "explain" ? "Optional: explain a billing term or code" : "Optional: polish this letter's tone";
  const what = kind === "explain"
    ? "Only the term or code you type below (for example \"CPT 99285\" or \"facility fee\"). Never your name, amounts, income or bills."
    : "Only this letter's wording with every personal detail replaced by placeholders like [NAME] and [BALANCE]. Your details are filled back in here, on your device.";
  return `<div class="card ai noprint"><details class="fold"><summary><h2>${title}</h2></summary><div style="margin-top:12px">
    <p class="small">This uses <b>Claude, an AI service from Anthropic</b>, with <b>your own Anthropic API key</b>. Everything else on this page works without it.</p>
    <p class="small"><b>What gets sent to Anthropic:</b> ${what}</p>
    <div class="grid g2">
      <div class="field"><label for="ai_key_${kind}">Your Anthropic API key <span class="hint">(kept only in this tab's memory; never saved to your file)</span></label><input type="password" id="ai_key_${kind}" autocomplete="off" value="${esc(ai.key)}" data-ai="key"></div>
      <div class="field"><label for="ai_model_${kind}">Model</label><input type="text" id="ai_model_${kind}" value="${esc(ai.model)}" data-ai="model"></div>
    </div>
    <div class="check" style="border:0"><input type="checkbox" id="ai_ok_${kind}" data-ai="consent" ${ai.consent ? "checked" : ""}><div><label for="ai_ok_${kind}">I agree to send the text described above to Anthropic.</label></div></div>
    ${kind === "explain" ? `<div class="field"><label for="ai_term">Term or code</label><input type="text" id="ai_term" maxlength="120" placeholder="e.g. CPT 99285, facility fee, revenue code 0450"></div>
      <button class="btn primary" id="ai_go_explain" type="button">Explain</button>`
    : `<button class="btn primary" id="ai_go_polish" type="button">Polish tone</button> <button class="btn" id="ai_fill" type="button" hidden>Fill my details back in</button>`}
    <div class="out" id="ai_out_${kind}" aria-live="polite" style="margin-top:12px"><span class="muted">${ai.key ? "Ready." : "No key entered. The AI helper is off; the rest of the page works normally."}</span></div>
  </div></details></div>`;
}
async function callAI(system, userText){
  if (!ai.key) throw new Error("NOKEY");
  if (!ai.consent) throw new Error("NOCONSENT");
  if (!navigator.onLine) throw new Error("OFFLINE");
  const ctl = new AbortController(); const timer = setTimeout(() => ctl.abort(), 25000);
  try {
    const res = await fetch("https://api.anthropic.com/v1/messages", {
      method: "POST", signal: ctl.signal,
      headers: { "content-type": "application/json", "x-api-key": ai.key, "anthropic-version": "2023-06-01", "anthropic-dangerous-direct-browser-access": "true" },
      body: JSON.stringify({ model: ai.model || "claude-haiku-5-5", max_tokens: 700, system, messages: [{ role: "user", content: userText }] })
    });
    if (!res.ok){ const e = new Error("HTTP"); e.status = res.status; throw e; }
    const j = await res.json();
    return (j.content || []).filter(c => c.type === "text").map(c => c.text).join("\n").trim();
  } finally { clearTimeout(timer); }
}
function aiErrorText(e){
  if (e.message === "NOKEY") return "No API key entered. The AI helper is off; everything else still works.";
  if (e.message === "NOCONSENT") return "Please tick the box to agree before anything is sent.";
  if (e.message === "OFFLINE" || e.name === "TypeError") return "Couldn't reach Anthropic. You may be offline. Everything else on this page still works.";
  if (e.name === "AbortError") return "Anthropic took too long to answer. Try again later.";
  if (e.status === 401 || e.status === 403) return "Anthropic didn't accept that key. Check it and try again.";
  if (e.status === 404 || e.status === 400) return "Anthropic didn't accept the request. Check the model name.";
  if (e.status === 429) return "Too many requests or the key's limit was reached. Wait a minute and try again.";
  if (e.status >= 500) return "Anthropic's service is having trouble right now. Try again later.";
  return "The AI helper isn't available right now. Everything else still works.";
}
const AI_GUARD = "Never give legal, tax, investment or personalized financial advice, and never recommend any security, lender or financial product. ";
async function aiExplain(){
  const out = $("#ai_out_explain"); const term = ($("#ai_term").value || "").trim();
  if (!term){ out.textContent = "Type a term or code first."; return; }
  if (/[@$]/.test(term) || /\d{7,}/.test(term)){ out.textContent = "That looks like it may include personal details (an email, dollar amount or long number). Please type only the term or code."; return; }
  out.textContent = "Asking Claude…";
  try {
    const t = await callAI("You explain U.S. medical billing terms and codes in plain English at an 8th-grade reading level, in 120 words or less. If it's a code, say what kind of service it usually describes. " + AI_GUARD + "If the request is not about a medical billing term, say you can only explain billing terms.", "Explain this medical billing term or code: " + term);
    out.textContent = t || "No answer came back.";
  } catch (e){ out.textContent = aiErrorText(e); }
}
let polished = "";
async function aiPolish(){
  const out = $("#ai_out_polish");
  const b = state.bills.find(x => x.id === state.letter.billId) || null;
  const draft = fillLetter(state.letter.type, b, "placeholder");
  out.textContent = "Asking Claude…"; $("#ai_fill").hidden = true;
  try {
    const t = await callAI("You edit letters a patient will send to a hospital billing office or debt collector. Make the letter clear, polite and firm, at an 8th-grade reading level. Keep every bracketed placeholder such as [NAME] or [BALANCE] exactly as written. Do not add facts, dollar amounts, dates, laws or citations that are not already in the letter. " + AI_GUARD + "Return only the letter.", draft);
    polished = t || ""; out.textContent = polished || "No answer came back.";
    if (polished) $("#ai_fill").hidden = false;
  } catch (e){ out.textContent = aiErrorText(e); }
}
function fillPolished(){
  const b = state.bills.find(x => x.id === state.letter.billId) || null;
  const { v } = letterValues(b, false);
  const filled = polished.replace(/\[([A-Z]+)\]/g, (m, k) => v[k] ? v[k] : m);
  $("#ai_out_polish").textContent = filled;
  copyText(filled, "Polished letter copied with your details.");
}

/* ============================================================
   SELF-TESTS
   ============================================================ */
function runTests(){
  const T = []; const ok = (name, cond) => T.push({ name, pass: !!cond });
  ok("Poverty guideline, 1 person = $15,960", guideline(1) === 15960);
  ok("Poverty guideline, 4 people = $33,000", guideline(4) === 33000);
  ok("Poverty guideline, 9 people = $61,400", guideline(9) === 61400);
  ok("$51,908 for 3 people = 190%", Math.abs(fplPercent(51908, 3) - 190) < 1e-9);
  ok("Missing income gives no percent", fplPercent("", 3) === null);
  const bUK = { provider: "ukhc", billed: "8400", insPaid: "0", status: "New" };
  ok("UK at 190% is likely free", aidEstimate(bUK, 190).max === 0);
  ok("Norton at 351% is over the limit", aidEstimate({ provider: "norton", billed: "1000", insPaid: "0", status: "New" }, 351).min === 1000);
  ok("Baptist at 350% is 50% off", aidEstimate({ provider: "baptist", billed: "1000", insPaid: "0", status: "New" }, 350).min === 500);
  ok("Insurance payment reduces balance", billBalance({ billed: "1000", insPaid: "250" }) === 750);
  const r1 = payoffCompare(1200, 100, 12, 29.99, 14);
  ok("Card paid within promo costs no interest", r1 && Math.abs(r1.card.total - 1200) < 0.01 && r1.card.trap === 0);
  const r2 = payoffCompare(1300, 100, 12, 29.99, 14);
  ok("Card not paid within promo triggers back interest", r2 && r2.card.trap > 0 && r2.card.total > 1300);
  ok("Hospital plan: $1,300 at $100 = 13 months", r2 && r2.plan.months === 13);
  ok("Loan that can't cover interest never pays off", payoffCompare(10000, 10, 0, 29.99, 30).loan.never === true);
  const d = deadlines({ provider: "ukhc", firstBill: "2026-01-01", collectorDate: "" });
  ok("240-day window from Jan 1, 2026 = Aug 29, 2026", d.some(x => x.key === "app" && x.date.getTime() === new Date(2026, 7, 29).getTime()));
  ok("Invalid save file is rejected", validateFile({ app: "x" }).ok === false);
  ok("Current state passes validation", validateFile(exportObject()).ok === true);
  return T;
}

/* ============================================================
   BINDING & EVENTS
   ============================================================ */
function setPath(path, val){
  const [a, b] = path.split(".");
  if (path === "household.size"){ const n = Math.floor(num(val)); state.household.size = Number.isFinite(n) ? Math.min(LIMITS.household, Math.max(1, n)) : 1; return; }
  state[a][b] = val;
}
function bindInputs(root){
  $$("[data-bind]", root).forEach(el => {
    const ev = el.tagName === "SELECT" ? "change" : "input";
    el.addEventListener(ev, () => { setPath(el.dataset.bind, el.value); markDirty(); refreshOutputs(); });
  });
}
function refreshOutputs(){
  renderSummary();
  if (currentTab === "aid") aidOutputs();
  if (currentTab === "check") checkOutputs();
  if (currentTab === "letters") letterOutputs();
  if (currentTab === "pay") payOutputs();
}
function copyText(text, msg){
  const done = () => toast(msg || "Copied.");
  if (navigator.clipboard && window.isSecureContext) navigator.clipboard.writeText(text).then(done, fallback); else fallback();
  function fallback(){ const ta = document.createElement("textarea"); ta.value = text; ta.style.position = "fixed"; ta.style.opacity = "0"; document.body.appendChild(ta); ta.select(); try { document.execCommand("copy"); done(); } catch (e) { toast("Couldn't copy. Select the text and copy it manually."); } ta.remove(); }
}

const VIEWS = { start: viewStart, bills: viewBills, aid: viewAid, check: viewCheck, letters: viewLetters, pay: viewPay, rights: viewRights };
const AFTER = {
  start(){
    $("#btnExample").addEventListener("click", () => {
      if ((state.bills.length || dirty) && !confirm("Replace your current work with the example?")) return;
      state = EXAMPLE(); state.letter.billId = state.bills[0].id; markDirty(); renderAll(); go("bills"); toast("Example loaded: Dana, a family of 3 in Hazard.");
    });
    $("#btnClear").addEventListener("click", () => {
      if (!confirm("Clear everything on this page? Save first if you want to keep it.")) return;
      state = blankState(); editingBillId = null; dirty = false; $("#saveStatus").textContent = "No unsaved changes"; renderAll(); toast("Cleared.");
    });
  },
  bills(){
    $("#btnAddBill").addEventListener("click", () => { const b = newBill(); editingBillId = b.id; afterBillsNew(b); });
    afterBills();
  },
  aid(){ bindInputs($("#view")); aidOutputs(); },
  check(){
    bindInputs($("#view"));
    $$("[data-check]").forEach(el => el.addEventListener("change", () => { state.checklist[el.dataset.check] = el.checked; markDirty(); checkOutputs(); }));
    checkOutputs(); bindAI("explain");
  },
  letters(){
    if (!state.letter.billId && state.bills[0]) state.letter.billId = state.bills[0].id;
    $("#l_bill").value = state.letter.billId;
    bindInputs($("#view")); letterOutputs();
    $("#btnCopy").addEventListener("click", () => { const b = state.bills.find(x => x.id === state.letter.billId) || null; copyText(fillLetter(state.letter.type, b, "text"), "Letter copied."); });
    $("#btnTxt").addEventListener("click", () => {
      const b = state.bills.find(x => x.id === state.letter.billId) || null;
      const blob = new Blob([fillLetter(state.letter.type, b, "text")], { type: "text/plain" });
      const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = `letter-${state.letter.type}.txt`; document.body.appendChild(a); a.click(); setTimeout(() => { URL.revokeObjectURL(a.href); a.remove(); }, 500);
    });
    $("#btnPrint").addEventListener("click", () => window.print());
    bindAI("polish");
  },
  pay(){
    bindInputs($("#view")); payOutputs();
    $("#btnUseTotal").addEventListener("click", () => {
      const t = totals(); state.pay.balance = String(Math.round(t.max)); $("#p_bal").value = state.pay.balance; markDirty(); payOutputs();
      toast(t.count ? "Using the most you may owe." : "Add bills first.");
    });
  },
  rights(){
    $("#btnTests").addEventListener("click", () => {
      const T = runTests(); const passed = T.filter(t => t.pass).length;
      $("#testOut").innerHTML = `<p><b>${passed} of ${T.length} checks passed.</b></p><ul>${T.map(t => `<li>${t.pass ? "✓" : "✗"} ${esc(t.name)}</li>`).join("")}</ul>`;
    });
  }
};
function afterBillsNew(b){
  editingBillId = b.id;
  $("#billEditor").innerHTML = billEditorHTML(b);
  wireEditor(b);
}
function wireEditor(b){
  const f = $("#billForm");
  f.provider.addEventListener("change", () => {
    $("#nameWrap").hidden = !["provider", "otherhosp", "forprofit"].includes(f.provider.value);
    $("#provNote").textContent = hosp(f.provider.value).note;
  });
  f.addEventListener("submit", ev => {
    ev.preventDefault();
    const fd = Object.fromEntries(new FormData(f).entries());
    const errs = [];
    const billed = num(fd.billed), ins = fd.insPaid === "" ? 0 : num(fd.insPaid);
    if (!(billed > 0) || billed > LIMITS.money) errs.push("Enter the amount billed (more than $0).");
    if (!Number.isFinite(ins) || ins < 0 || ins > LIMITS.money) errs.push("Insurance paid must be $0 or more.");
    if (ins > billed) errs.push("Insurance paid can't be more than the amount billed.");
    ["service", "firstBill", "collectorDate"].forEach(k => { if (fd[k] && !parseDate(fd[k])) errs.push("One of the dates isn't valid."); });
    if (errs.length){ $("#formErr").innerHTML = `<div class="notice bad" role="alert">${errs.map(esc).join("<br>")}</div>`; return; }
    const rec = { id: b.id, provider: DATA.hospitals.some(h => h.id === fd.provider) ? fd.provider : "otherhosp", providerName: (fd.providerName || "").slice(0, 200), account: (fd.account || "").slice(0, 60),
      status: DATA.statuses.includes(fd.status) ? fd.status : "New", billed: String(billed), insPaid: String(ins),
      service: fd.service || "", firstBill: fd.firstBill || "", collectorDate: fd.collectorDate || "", notes: (fd.notes || "").slice(0, 500) };
    const i = state.bills.findIndex(x => x.id === b.id);
    if (i >= 0) state.bills[i] = rec; else state.bills.push(rec);
    if (!state.letter.billId) state.letter.billId = rec.id;
    editingBillId = null; markDirty(); renderSummary(); renderView(); toast("Bill saved.");
  });
  $("#btnCancelBill").addEventListener("click", () => { editingBillId = null; renderView(); });
  $("#f_provider").focus();
  $("#editorCard").scrollIntoView({ behavior: "smooth", block: "start" });
}
// single source of truth for the editor wiring
function afterBills(){
  if (!editingBillId) return;
  const b = state.bills.find(x => x.id === editingBillId);
  if (!b) return;
  $("#billEditor").innerHTML = billEditorHTML(b);
  wireEditor(b);
}
function bindAI(kind){
  $$("[data-ai]").forEach(el => {
    const ev = el.type === "checkbox" ? "change" : "input";
    el.addEventListener(ev, () => {
      const k = el.dataset.ai; ai[k] = el.type === "checkbox" ? el.checked : el.value.trim();
      const o = $(`#ai_out_${kind}`); if (o && !ai.busy) o.textContent = ai.key ? (ai.consent ? "Ready." : "Tick the box to agree before using the helper.") : "No key entered. The AI helper is off; the rest of the page works normally.";
    });
  });
  if (kind === "explain") $("#ai_go_explain").addEventListener("click", aiExplain);
  if (kind === "polish"){ $("#ai_go_polish").addEventListener("click", aiPolish); $("#ai_fill").addEventListener("click", fillPolished); }
}

document.addEventListener("click", ev => {
  const t = ev.target.closest("[data-tab],[data-go],[data-edit],[data-del]");
  if (!t) return;
  if (t.dataset.tab) go(t.dataset.tab);
  else if (t.dataset.go){ ev.preventDefault(); go(t.dataset.go); }
  else if (t.dataset.edit){ editingBillId = t.dataset.edit; renderView(); }
  else if (t.dataset.del){
    const b = state.bills.find(x => x.id === t.dataset.del);
    if (b && confirm(`Delete the bill from ${b.providerName || hosp(b.provider).name}?`)){
      state.bills = state.bills.filter(x => x.id !== b.id);
      if (state.letter.billId === b.id) state.letter.billId = "";
      markDirty(); renderSummary(); renderView(); toast("Bill deleted.");
    }
  }
});
$("#tablist").addEventListener("keydown", ev => {
  if (!["ArrowRight", "ArrowLeft", "Home", "End"].includes(ev.key)) return;
  ev.preventDefault();
  let i = TABS.findIndex(t => t.id === currentTab);
  if (ev.key === "ArrowRight") i = (i + 1) % TABS.length;
  if (ev.key === "ArrowLeft") i = (i - 1 + TABS.length) % TABS.length;
  if (ev.key === "Home") i = 0; if (ev.key === "End") i = TABS.length - 1;
  go(TABS[i].id); $(`#tab-${TABS[i].id}`).focus();
});
$("#btnSave").addEventListener("click", saveFile);
$("#btnOpen").addEventListener("click", () => $("#fileInput").click());
$("#fileInput").addEventListener("change", ev => { openFile(ev.target.files[0]); ev.target.value = ""; });
window.addEventListener("beforeunload", ev => { if (dirty){ ev.preventDefault(); ev.returnValue = ""; return ""; } });

$("#copyLine").textContent = `Copyright (c) 2026 ${AUTHOR}. Released under the MIT License. Hospital data checked ${DATA.checked}.`;
renderAll();
</script>
</body>
</html>

Reaches out to

Websites this page contacts when it runs — fonts, chart libraries, data. Found by reading its source.

  • www.w3.org
  • aspe.hhs.gov
  • spectrumlocalnews.com
  • www.wuky.org
  • www.lpm.org
  • lpm.org
  • ukhealthcare.uky.edu
  • www.ukhealthcare.uky.edu
  • nortonhealthcare.com
  • uoflhealth.org
  • www.baptisthealth.com
  • www.careroute.ai

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 Liam Schilling. 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.