← Demos
Web Pages · Demos

KY Money Milestones

A Kentucky money guide that shows which accounts, programs, and credit unions fit each life milestone, from turning 18 to buying a home. It turns your next milestone into a savings plan with real Kentucky taxes, and it’s private: nothing leaves your computer.

by Truc Nguyen Nov 20, 2026 15 views 270.4 KB
Sandbox · ky-money-milestones · no access to your account
View source — the whole page is this one file
<!-- Copyright (c) 2026 Truc Nguyen. Released under the MIT License. -->
<!--
KY Money Milestones
An educational tool that helps young Kentuckians learn which money accounts and programs
matter at each life milestone, and plan the cost of their next one.

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.

Third-party code: none. Every line of this file was written for this project.
Privacy: this page makes no network requests. Nothing you type leaves your computer.
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>KY Money Milestones</title>
<style>
  /* Design: Kentucky highway mile markers. Milestones = markers along your money road. */
  :root{
    --road:#0e5a3c;        /* highway sign green */
    --road-deep:#0a4430;
    --sky:#eef3f0;         /* pale roadside sky */
    --paper:#ffffff;
    --ink:#15241d;
    --muted:#55665d;
    --line:#d6e0da;
    --gold:#e3a21a;        /* goldenrod, Kentucky's state flower */
    --gold-soft:#fdf3dc;
    --good:#0e5a3c; --good-soft:#e4f1ea;
    --bad:#a8321f;  --bad-soft:#fbe9e5;
    --info-soft:#e9f0f5; --info:#2f5f86;
    --sign: "Avenir Next Condensed","Roboto Condensed","Arial Narrow","Helvetica Neue",system-ui,sans-serif;
    --body: system-ui,-apple-system,"Segoe UI",Roboto,Arial,sans-serif;
  }
  *{box-sizing:border-box}
  html{scroll-behavior:smooth}
  body{margin:0;background:var(--sky);color:var(--ink);font:17px/1.6 var(--body);padding-bottom:64px}
  a{color:var(--road);text-underline-offset:3px}
  a:hover{color:var(--road-deep)}

  /* Header: a small road sign */
  header{background:var(--paper);border-bottom:1px solid var(--line);position:sticky;top:0;z-index:5}
  .bar{max-width:1060px;margin:0 auto;padding:10px 20px;display:flex;align-items:center;gap:12px;flex-wrap:wrap}
  .brand{margin-right:auto;display:flex;align-items:center;gap:12px;text-decoration:none;color:inherit}
  .brand .plate{background:var(--road);color:#fff;border-radius:8px;padding:4px;box-shadow:0 1px 0 var(--road-deep)}
  .brand .plate span{display:block;border:2px solid #fff;border-radius:5px;padding:2px 9px;font:700 15px/1.2 var(--sign);letter-spacing:.02em}
  .brand b{font:700 20px/1.1 var(--sign);display:block}
  .brand small{font-size:13px;color:var(--muted)}
  .status{font-size:14px;color:var(--muted);display:flex;align-items:center;gap:6px}
  .status::before{content:"";width:8px;height:8px;border-radius:50%;background:#9fb3a8}
  .status.dirty{color:#8a5a00;font-weight:600}
  .status.dirty::before{background:var(--gold)}
  .status.saved::before{background:var(--road)}

  button{font:inherit;font-size:15px;border:1.5px solid var(--line);background:var(--paper);color:var(--ink);padding:8px 15px;border-radius:8px;cursor:pointer;transition:background .15s,border-color .15s,transform .1s}
  button:hover{border-color:#9fb3a8}
  button:active{transform:translateY(1px)}
  button.primary{background:var(--road);border-color:var(--road);color:#fff;font-weight:600}
  button.primary:hover{background:var(--road-deep);border-color:var(--road-deep)}
  button.small{font-size:14px;padding:5px 11px}
  kbd{font:600 12px var(--body);background:rgba(255,255,255,.18);border:1px solid rgba(255,255,255,.35);border-radius:4px;padding:1px 5px;margin-left:6px}

  nav.tabs{max-width:1060px;margin:0 auto;padding:0 20px;display:flex;gap:2px;flex-wrap:wrap}
  nav.tabs button{border:none;border-radius:0;background:none;padding:10px 12px 12px;font-size:15px;color:var(--muted);border-bottom:3px solid transparent}
  nav.tabs button:hover{color:var(--ink)}
  nav.tabs button[aria-selected="true"]{color:var(--road);border-bottom-color:var(--gold);font-weight:650}
  nav.tabs{align-items:center}
  nav.tabs button{display:inline-flex;align-items:center;padding:10px 10px 12px}
  nav.tabs .grp{display:none;font-size:11px;font-weight:750;letter-spacing:.08em;text-transform:uppercase;color:#8a9a91;padding:0 4px 0 2px}
  nav.tabs .sep{width:1px;height:22px;background:var(--line);margin:0 8px}
  nav.tabs .dot{display:inline-grid;place-items:center;flex:none;width:20px;height:20px;border-radius:50%;border:1.5px solid currentColor;font:700 11px/1 var(--body);font-style:normal;margin-right:7px}
  nav.tabs button.done .dot{background:var(--road);border-color:var(--road);color:#fff;font-size:0}
  nav.tabs button.done .dot::after{content:"✓";font-size:12px}
  .hero-cta{display:flex;flex-wrap:wrap;gap:10px 14px;align-items:center;margin:4px 0 6px}
  .hero-cta button{font-size:16px;padding:10px 18px;border-radius:999px;font-weight:650}
  .hero-cta button.gold{background:var(--gold);border-color:var(--gold);color:#2a1d00;box-shadow:0 3px 0 #b07d0f}
  .hero-cta button.gold:hover{background:#efb43a}
  .hero-cta button.ghost{background:transparent;color:#fff;border-color:rgba(255,255,255,.7)}
  .hero-cta button.ghost:hover{background:rgba(255,255,255,.1)}
  .hero .hero-cta .private{font-size:14px;margin:0;opacity:.85}
  .summary{margin:0 0 6px}
  .hero.compact .hero-in{padding:18px 24px 10px}
  .hero.compact h1{font-size:clamp(26px,3.4vw,34px);max-width:none}
  .checks{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(330px,100%),1fr));gap:0 18px;margin-top:12px}
  .stats{display:grid;grid-template-columns:repeat(4,1fr);gap:10px}
  .stat{display:flex;flex-direction:column;align-items:flex-start;gap:2px;text-align:left;background:var(--paper);border:1.5px solid var(--line);border-radius:14px;padding:14px 16px;font-size:14px;color:var(--muted);line-height:1.3}
  button.stat{cursor:pointer;transition:transform .15s,box-shadow .15s,border-color .15s}
  button.stat:hover{transform:translateY(-2px);border-color:#9fb3a8;box-shadow:0 6px 16px rgba(14,90,60,.12)}
  .stat .big{font:800 30px/1.1 var(--sign);color:var(--road)}
  .qhead{display:flex;gap:10px;align-items:baseline;flex-wrap:wrap;margin-bottom:4px}
  .tiles.feat{grid-template-columns:repeat(auto-fit,minmax(200px,1fr))}

  main{max-width:1060px;margin:0 auto;padding:26px 20px}
  main.enter{animation:enter .28s ease-out}
  @keyframes enter{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}

  h1{font:700 clamp(30px,4.4vw,44px)/1.08 var(--sign);margin:0 0 10px;letter-spacing:-.01em}
  h2{font:700 25px/1.2 var(--sign);margin:34px 0 12px}
  h3{font:700 19px/1.25 var(--sign);margin:0 0 6px}
  p{max-width:72ch}
  p.lead{font-size:18.5px;color:var(--muted);margin:0 0 20px}

  /* Hero: the big green sign with the road underneath */
  .hero{background:var(--road);color:#fff;border-radius:16px;padding:10px;margin:0 0 26px;box-shadow:0 2px 0 var(--road-deep)}
  .hero-in{border:3px solid #fff;border-radius:10px;padding:26px 28px 18px}
  .hero h1{color:#fff;max-width:18ch}
  .hero p{color:#d8ebe1;font-size:18px;margin:0 0 14px;max-width:60ch}
  .hero .private{font-size:15px;color:#fff;opacity:.9}
  .road{display:block;width:100%;height:auto;margin-top:22px;overflow:visible}
  .hero-in{position:relative}
  .roadin{position:relative;cursor:grab;touch-action:pan-y}
  .roadin.dragging{cursor:grabbing}
  .road .pin{fill:#fff;stroke:var(--road-deep);stroke-width:2}
  .road .tick{fill:#bcd3c6;font:600 12px var(--body);text-anchor:middle}
  .road .tk{stroke:#bcd3c6;stroke-width:1.5}
  .ageslide{position:absolute;left:0;top:18%;height:58%;width:100%;margin:0;opacity:0;pointer-events:none;z-index:2;-webkit-appearance:none;appearance:none;background:transparent}
  .ageslide:active{cursor:grabbing}
  .ageslide::-webkit-slider-thumb{-webkit-appearance:none;width:34px;height:34px}
  .ageslide::-moz-range-thumb{width:34px;height:34px;border:0}
  .agemark{position:absolute;top:47.2%;transform:translate(-50%,-50%);z-index:1;pointer-events:none;display:flex;flex-direction:column;align-items:center;justify-content:center;width:40px;height:40px;border-radius:10px;background:var(--gold);color:#2a1d00;border:2.5px solid #fff;box-shadow:0 3px 10px rgba(0,0,0,.35);line-height:1}
  .agemark small{font:800 8px/1 var(--body);letter-spacing:.06em}
  .agemark b{font:800 16px/1.05 var(--sign)}
  .ageslide:focus-visible + .agemark{outline:3px solid #fff;outline-offset:3px}
  @media (prefers-reduced-motion:no-preference){ .agemark{animation:nudge 2.4s ease-in-out 1.2s 2} }
  @keyframes nudge{0%,100%{transform:translate(-50%,-50%)}25%{transform:translate(-30%,-50%)}75%{transform:translate(-70%,-50%)}}
  .hero .agehint{font-size:14px;margin:4px 0 0;opacity:.9}
  .agepop{position:absolute;z-index:4;width:290px;background:#fff;color:var(--ink);border-radius:12px;padding:12px 14px 10px;box-shadow:0 10px 28px rgba(0,0,0,.3);border-top:4px solid var(--gold);pointer-events:none}
  .agepop::after{content:"";position:absolute;bottom:-8px;left:var(--arrow,50%);transform:translateX(-50%);border:8px solid transparent;border-bottom:0;border-top-color:#fff}
  .agepop[hidden]{display:none}
  .agepop.below{border-top:0;border-bottom:4px solid var(--gold)}
  .agepop.below::after{bottom:auto;top:-8px;border-top:0;border-bottom:8px solid #fff}
  .ap-head{display:flex;flex-direction:column;margin-bottom:6px}
  .ap-head b{font:800 18px/1.2 var(--sign);color:var(--road)}
  .ap-head span{font-size:12.5px;color:var(--muted)}
  .ap-row{display:grid;grid-template-columns:1fr auto;gap:0 10px;font-size:14px;margin:5px 0 0}
  .ap-v{font-weight:750;font-variant-numeric:tabular-nums}
  .ap-bar{grid-column:1 / -1;height:6px;background:#eef3f0;border-radius:3px;overflow:hidden;margin-top:2px}
  .ap-bar i{display:block;height:100%;border-radius:3px;transition:width .25s}
  .ap-bar .c1{background:#7fb79a}.ap-bar .c2{background:var(--road)}.ap-bar .c3{background:var(--gold)}.ap-bar .c4{background:#b07d0f}
  .hero .agepop .ap-note{font-size:11.5px;line-height:1.4;color:var(--muted);margin:8px 0 0;max-width:none}
  .road .asphalt{fill:#2f3a35}
  .road .center{stroke:var(--gold);stroke-width:3;stroke-dasharray:14 12;fill:none}
  .road .post{stroke:#fff;stroke-width:2}
  .road .mm rect{fill:var(--road-deep);stroke:#fff;stroke-width:2}
  .road .mm text{fill:#fff;font:700 16px var(--sign);text-anchor:middle}
  .road .mm .lbl{font:600 11.5px var(--body);fill:#cfe5d9}
  @media (prefers-reduced-motion:no-preference){
    .road .center{animation:drive 1.1s ease-out both}
    .road .mm{animation:pop .45s cubic-bezier(.3,1.5,.6,1) both}
  }
  @keyframes drive{from{stroke-dashoffset:600}to{stroke-dashoffset:0}}
  @keyframes pop{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:none}}

  .card{background:var(--paper);border:1px solid var(--line);border-radius:12px;padding:20px;margin:0 0 14px}
  .grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(230px,1fr));gap:16px}
  label{display:block;font-weight:600;font-size:15px;margin:0 0 5px}
  .hint{font-weight:400;color:var(--muted);font-size:14px}
  input[type=text],input[type=number],input[type=date],input[type=url],select,textarea{font:inherit;font-size:16px;width:100%;padding:10px 12px;border:1.5px solid #c9d5ce;border-radius:8px;background:#fff;color:var(--ink);transition:border-color .15s}
  input:hover,select:hover,textarea:hover{border-color:#9fb3a8}
  textarea{min-height:110px}
  input:focus,select:focus,textarea:focus,button:focus-visible,summary:focus-visible,a:focus-visible{outline:3px solid var(--gold);outline-offset:2px}
  .check{display:flex;gap:10px;align-items:flex-start;font-weight:500;margin:7px 0;cursor:pointer}
  .check input{margin-top:4px;width:19px;height:19px;flex:none;accent-color:var(--road)}
  .pill{display:inline-block;font:600 13px var(--body);padding:2px 10px;border-radius:999px;background:var(--good-soft);color:var(--road);vertical-align:middle}

  .note{border-radius:8px;padding:11px 14px;margin:8px 0;font-size:16px}
  .note.heads{background:var(--gold-soft);border-left:5px solid var(--gold)}
  .note.good{background:var(--good-soft);border-left:5px solid var(--good)}
  .note.bad{background:var(--bad-soft);border-left:5px solid var(--bad)}
  .note.info{background:var(--info-soft);border-left:5px solid var(--info)}
  .big{font:700 30px/1.15 var(--sign)}
  .muted{color:var(--muted)}

  /* Milestone picker: chips that light up like reflective signs */
  .ms-pick{display:grid;grid-template-columns:repeat(auto-fit,minmax(215px,1fr));gap:8px}
  .ms-pick label{display:flex;gap:10px;align-items:center;background:var(--paper);border:1.5px solid var(--line);border-radius:9px;padding:11px 13px;font-weight:600;cursor:pointer;transition:background .15s,border-color .15s,color .15s}
  .ms-pick label:hover{border-color:#9fb3a8}
  .ms-pick label.on{border-color:var(--road);background:var(--road);color:#fff}
  .ms-pick input{width:18px;height:18px;flex:none;accent-color:var(--gold)}
  /* line-drawn icons and picture tiles */
  .ico{width:54px;height:54px;flex:none;color:var(--road);fill:none;stroke:currentColor;stroke-width:3;stroke-linecap:round;stroke-linejoin:round}
  .ico .f{fill:currentColor}
  .ico .g{fill:var(--gold);stroke:var(--gold)}
  .ico .gs{stroke:var(--gold)}
  .ico .t{fill:currentColor;stroke:none;font-family:inherit}
  .ico.sm{width:30px;height:30px;stroke-width:3.5}
  .ico.lg{width:72px;height:72px}
  .ico.inl{width:30px;height:30px;vertical-align:middle;margin-right:4px}
  .tiles{display:grid;grid-template-columns:repeat(auto-fill,minmax(138px,1fr));gap:10px;margin:6px 0}
  .tile{position:relative;display:flex;flex-direction:column;align-items:center;justify-content:flex-start;gap:6px;padding:16px 10px 13px;background:var(--paper);border:1.5px solid var(--line);border-radius:14px;color:var(--ink);font-weight:650;font-size:14.5px;line-height:1.25;text-align:center;cursor:pointer;transition:transform .15s,box-shadow .15s,border-color .15s,background .15s}
  .tile:hover{transform:translateY(-2px);border-color:#9fb3a8;box-shadow:0 6px 16px rgba(14,90,60,.12)}
  .tile:hover .ico{transform:scale(1.06)}
  .tile .ico{transition:transform .2s}
  .tile .sub{font-size:12.5px;font-weight:500;color:var(--muted)}
  .tile[aria-expanded="true"]{border-color:var(--road);background:var(--road);color:#fff;box-shadow:0 6px 18px rgba(14,90,60,.25)}
  .tile[aria-expanded="true"] .ico{color:#fff}
  .tile[aria-expanded="true"] .sub{color:#d9eadf}
  .tile .badge{position:absolute;top:7px;right:7px;max-width:calc(100% - 14px);background:var(--gold);color:#3b2a00;font-size:10.5px;font-weight:750;border-radius:999px;padding:2px 7px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
  .tile-panel{margin-top:12px}
  .tile-panel.pop{animation:panelin .28s ease-out}
  @keyframes panelin{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
  .tile-hint{text-align:center;padding:8px 0}
  .inshead{display:flex;gap:16px;align-items:flex-start}
  .inscols{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px;margin-top:14px}
  .inscol{border-radius:10px;padding:10px 14px;border:1px solid var(--line)}
  .inscol h4{margin:0 0 4px;font-size:15px}
  .inscol ul{margin:0;padding-left:18px}
  .inscol li{margin:4px 0}
  .inscol.ky{background:#f2f7f4}.inscol.save{background:#fdf6e6}.inscol.watch{background:#fbefec}
  .words{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:10px;margin-bottom:12px}
  .word{display:flex;flex-direction:column;align-items:center;text-align:center;gap:4px;background:var(--paper);border:1px solid var(--line);border-radius:12px;padding:12px}
  .word span{font-size:13.5px;color:var(--muted)}
  .split{display:flex;height:30px;border-radius:8px;overflow:hidden;background:#e9efeb;margin:6px 0}
  .split span{display:block;height:100%;transition:width .4s ease}
  .sd{background:var(--gold)} .sc{background:#f3cf7a} .sp{background:var(--road)}
  .legend{display:flex;flex-wrap:wrap;gap:6px 16px;font-size:13.5px;margin-bottom:6px}
  .legend i{display:inline-block;width:12px;height:12px;border-radius:3px;margin-right:5px;vertical-align:-1px}
  .ms-pick label .ico{color:var(--road)}
  .ms-pick label.on .ico{color:#fff}
  @media (max-width:560px){ .tiles{grid-template-columns:repeat(2,1fr)} .inshead{flex-direction:column} .ico.lg{width:56px;height:56px} }
  @media (prefers-reduced-motion: reduce){ .tile,.tile .ico,.split span{transition:none} .tile-panel.pop{animation:none} }
  @media print{ .tiles{display:none} }

  /* Timeline: a road running down the left with mile markers */
  .route{position:relative;padding-left:0}
  .route::before{content:"";position:absolute;left:33px;top:6px;bottom:6px;width:10px;background:#2f3a35;border-radius:5px}
  .route::after{content:"";position:absolute;left:37px;top:10px;bottom:10px;width:2px;background:repeating-linear-gradient(var(--gold) 0 12px,transparent 12px 22px)}
  details.ms{position:relative;margin:0 0 14px 88px;background:var(--paper);border:1px solid var(--line);border-radius:12px}
  details.ms > summary{list-style:none;cursor:pointer;padding:16px 20px;display:flex;gap:14px;align-items:center;border-radius:12px}
  details.ms > summary::-webkit-details-marker{display:none}
  details.ms > summary:hover{background:#f7faf8}
  .marker{position:absolute;left:-82px;top:10px;width:58px;background:var(--road);border-radius:7px;padding:3px;z-index:1;box-shadow:0 2px 0 var(--road-deep)}
  .marker span{display:block;border:2px solid #fff;border-radius:5px;color:#fff;text-align:center;padding:3px 0 4px;font:700 11px/1.1 var(--sign)}
  .marker span b{display:block;font-size:22px;line-height:1}
  details.ms.sit{margin-left:0;border-left:5px solid var(--gold)}
  details.ms > summary .t{font:700 20px/1.2 var(--sign)}
  .progress{display:flex;align-items:center;gap:8px;font-size:14px;color:var(--muted);margin-top:3px}
  .progress i{display:block;width:90px;height:6px;border-radius:3px;background:var(--line);overflow:hidden}
  .progress i em{display:block;height:100%;background:var(--gold);transition:width .35s ease}
  details.ms > summary .chev{margin-left:auto;color:var(--muted);transition:transform .2s;font-size:13px}
  details.ms[open] > summary .chev{transform:rotate(90deg)}
  details.ms[open] > summary{border-bottom:1px solid var(--line);border-radius:12px 12px 0 0}
  .ms-body{padding:16px 20px 20px}
  @media (prefers-reduced-motion:no-preference){ details.ms[open] .ms-body{animation:enter .25s ease-out} }
  .acct{border-left:4px solid var(--road);background:#f6faf8;border-radius:0 8px 8px 0;padding:11px 14px;margin:8px 0}
  .acct b{font:700 18px var(--sign)}
  .acct .like{color:var(--muted);font-style:italic}
  .acct .when{margin-top:6px;font-size:15.5px}
  .acct .pw{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:4px 18px;margin-top:6px;font-size:15.5px}
  .acct .pw ul{margin:2px 0 0;padding-left:20px}
  .acct .pros b{color:var(--good)}
  .acct .watch b{color:#8a5a00}
  .acct .learn{margin-top:8px;font-size:15px;line-height:1.7}
  details.acct{padding:0}
  details.acct > summary{list-style:none;cursor:pointer;display:grid;grid-template-columns:1fr auto;gap:2px 12px;padding:10px 14px;align-items:start}
  details.acct > summary::-webkit-details-marker{display:none}
  details.acct .an{font:700 17px/1.3 var(--sign)}
  details.acct .aw{grid-column:1;font-size:15px;color:var(--ink)}
  details.acct .amore{grid-column:2;grid-row:1 / span 2;align-self:center;font-size:13px;font-weight:650;color:var(--road);border:1.5px solid var(--line);border-radius:999px;padding:3px 10px;white-space:nowrap;background:#fff}
  details.acct[open] .amore{background:var(--road);color:#fff;border-color:var(--road)}
  details.acct .acct-more{padding:0 14px 12px}
  details.acct .acct-more b{font:700 15.5px/1.4 var(--body)}
  .secs{display:flex;flex-direction:column;gap:8px;margin-top:12px}
  details.sec{background:var(--paper);border:1.5px solid var(--line);border-radius:12px;overflow:hidden}
  details.sec > summary{list-style:none;cursor:pointer;display:flex;align-items:center;gap:10px;padding:10px 14px;font-weight:650}
  details.sec > summary::-webkit-details-marker{display:none}
  details.sec > summary:hover{background:#f6faf8}
  details.sec .st{flex:1}
  details.sec .chev{color:var(--muted);font-size:12px;transition:transform .2s}
  details.sec[open] > summary{border-bottom:1px solid var(--line);background:#f6faf8}
  details.sec[open] > summary .chev{transform:rotate(90deg)}
  details.sec .sec-body{padding:10px 14px 14px}
  details.sec .sec-body .tool{margin:0;border:0;padding:0;background:none}
  .ico.xs{width:26px;height:26px;stroke-width:3.5}
  @media (max-width:560px){ details.acct > summary{grid-template-columns:1fr} details.acct .amore{grid-column:1;grid-row:auto;justify-self:start} }

  .tool{background:var(--paper);border:1.5px dashed #b8c9bf;border-radius:12px;padding:16px;margin:16px 0}
  .tool .grid{grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px}
  .result{margin-top:12px}

  /* Comparison bars */
  .bars{margin:6px 0 10px}
  .barrow{display:grid;grid-template-columns:150px 1fr auto;gap:12px;align-items:center;margin:8px 0}
  .barrow .k{font-size:15px;color:var(--muted)}
  .barrow .track{display:block;height:26px;background:#edf2ef;border-radius:6px;overflow:hidden}
  .barrow .fill{display:block;width:0;height:100%;border-radius:6px;transition:width .6s cubic-bezier(.2,.8,.2,1)}
  .barrow .fill.g{background:var(--road)}
  .barrow .fill.r{background:var(--bad)}
  .barrow .fill.y{background:var(--gold)}
  .barrow .v{font:700 20px var(--sign);min-width:100px;text-align:right}
  .takeaway{font-size:17.5px;margin:8px 0 0}
  .takeaway b{background:linear-gradient(transparent 60%,var(--gold-soft) 60%)}

  table{width:100%;border-collapse:collapse;font-size:15.5px}
  th,td{text-align:left;padding:9px 6px;border-bottom:1px solid var(--line);vertical-align:middle}
  th{font-size:13.5px;color:var(--muted);font-weight:600}
  td input,td select{padding:7px 9px;font-size:15px}
  .num{text-align:right;white-space:nowrap;font-variant-numeric:tabular-nums}
  .cands{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px}
  details.paste > summary{cursor:pointer;font-weight:600;color:var(--road)}

  details.homecalc > summary{cursor:pointer;list-style:none}
  details.homecalc > summary::-webkit-details-marker{display:none}
  .plan-total{background:var(--road);color:#fff;border-radius:10px;padding:16px 18px;margin:10px 0}
  .plan-total .big{font-size:38px}
  .plan-total small{display:block;color:#d8ebe1;font-size:15px}

  .qa .opts{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px}
  .qa .opts button{min-width:90px}
  .qa .opts button.picked-right{background:var(--good);color:#fff;border-color:var(--good)}
  .qa .opts button.picked-wrong{background:var(--bad);color:#fff;border-color:var(--bad)}
  .quizbar{display:grid;grid-template-columns:auto 1fr auto;gap:14px;align-items:center;background:var(--paper);border:1.5px solid var(--line);border-radius:12px;padding:10px 14px;margin:0 0 14px}
  .qprog{height:10px;background:#e9efeb;border-radius:5px;overflow:hidden}
  .qprog i{display:block;height:100%;background:var(--road);border-radius:5px;transition:width .3s}
  .score{display:flex;gap:4px;margin:6px 0 16px}
  .score i{width:28px;height:8px;border-radius:4px;background:var(--line)}
  .score i.r{background:var(--road)} .score i.w{background:var(--bad)}

  footer.disclaimer{position:fixed;left:0;right:0;bottom:0;background:var(--ink);color:#e4ece7;font-size:13.5px;line-height:1.45;padding:8px 20px;z-index:6;border-top:3px solid var(--gold)}
  footer.disclaimer div{max-width:1060px;margin:0 auto}
  footer.disclaimer .dwrap{display:flex;gap:14px;align-items:flex-start;justify-content:space-between}
  footer.disclaimer summary{cursor:pointer;list-style:none}
  footer.disclaimer summary::-webkit-details-marker{display:none}
  footer.disclaimer .more{color:var(--gold);text-decoration:underline;text-underline-offset:3px;white-space:nowrap}
  footer.disclaimer details[open] .more{display:none}
  footer.disclaimer details p{margin:6px 0 2px;max-width:none;color:#cfdcd5}
  .linkbtn{background:none;border:none;padding:0;color:#e4ece7;font-size:13.5px;text-decoration:underline;text-underline-offset:3px;white-space:nowrap}
  .linkbtn:hover{color:var(--gold)}
  .toast{position:fixed;left:50%;transform:translateX(-50%);bottom:88px;background:var(--road);color:#fff;padding:11px 18px;border-radius:9px;font-size:15px;z-index:20;max-width:90vw;display:none;box-shadow:0 6px 20px rgba(14,90,60,.25)}
  .toast.err{background:var(--bad)}
  .toast.show{display:block;animation:enter .2s ease-out}
  .modal-bg{position:fixed;inset:0;background:rgba(21,36,29,.5);display:none;align-items:center;justify-content:center;z-index:30;padding:18px}
  .modal{background:#fff;border-radius:14px;padding:24px;max-width:440px;width:100%;border-top:6px solid var(--gold)}
  .modal .row{display:flex;gap:10px;justify-content:flex-end;margin-top:16px}

  @media (max-width:640px){
    body{font-size:16px;padding-bottom:84px}
    header{position:static}
    nav.tabs{flex-wrap:nowrap;overflow-x:auto}
    nav.tabs button{flex:none}
    footer.disclaimer{font-size:12px;padding:7px 12px}
    .stats{grid-template-columns:1fr 1fr}
    .quizbar{grid-template-columns:1fr}
    .stat .big{font-size:24px}
    nav.tabs .grp,nav.tabs .sep{display:none}
    .hero-in{padding:18px 16px 12px}
    .route::before{left:21px} .route::after{left:25px}
    details.ms{margin-left:62px}
    .marker{left:-60px;width:48px}
    .marker span b{font-size:18px}
    .barrow{grid-template-columns:1fr auto}
    .barrow .track{grid-column:1 / -1;grid-row:2}
    .hide-sm{display:none}
    td.num{white-space:normal}
    .tool{overflow-x:auto}
    .brand{flex-basis:100%}
    .status{flex-basis:100%}
    .bar button{padding:7px 12px}
    .roadwrap{overflow-x:auto;margin:0 -6px}
    .roadwrap{overflow:visible;margin:0}
    .roadin{min-width:0}
    .hero .road .mm,.hero .road .tick,.hero .road .tk{display:none}
    .agepop{width:250px}
  }
  @media (prefers-reduced-motion:reduce){
    *,*::before,*::after{animation:none!important;transition:none!important}
    html{scroll-behavior:auto}
  }
  @media print{
    header,nav,footer.disclaimer,.no-print,.hero .road{display:none!important}
    body{background:#fff;padding:0}
    details.ms{break-inside:avoid}
  }
</style>
</head>
<body>

<header>
  <div class="bar">
    <div class="brand"><span class="plate" aria-hidden="true"><span>KY</span></span><span><b>Money Milestones</b><small>Learn it. Plan it. Kentucky edition.</small></span></div>
    <span id="status" class="status" aria-live="polite">Nothing to save yet</span>
    <button id="btnNew" type="button" title="Start a new plan">New</button>
    <button id="btnOpen" type="button" title="Open a saved plan file">Open</button>
    <button id="btnSave" type="button" class="primary" title="Save your plan (Ctrl+S or Cmd+S)">Save plan<kbd class="hide-sm">Ctrl+S</kbd></button>
    <input id="fileInput" type="file" accept=".html,.htm,.json,text/html,application/json" hidden>
  </div>
  <nav class="tabs" role="tablist" aria-label="Sections">
    <span class="grp" aria-hidden="true">Your plan</span>
    <button type="button" role="tab" data-tab="about" data-step="1"><i class="dot">1</i>About you</button>
    <button type="button" role="tab" data-tab="timeline" data-step="2"><i class="dot">2</i>Milestones</button>
    <button type="button" role="tab" data-tab="plan" data-step="3"><i class="dot">3</i>Plan the next one</button>
    <button type="button" role="tab" data-tab="qualify" data-step="4"><i class="dot">4</i>You may qualify</button>
    <span class="sep" aria-hidden="true"></span>
    <span class="grp" aria-hidden="true">Learn</span>
    <button type="button" role="tab" data-tab="guide">Accounts</button>
    <button type="button" role="tab" data-tab="ins">Insurance</button>
    <button type="button" role="tab" data-tab="scams">Scams</button>
    <button type="button" role="tab" data-tab="quiz">Quiz</button>
  </nav>
</header>

<main id="main" tabindex="-1"></main>

<footer class="disclaimer" role="note">
  <div class="dwrap"><details id="discl"><summary><b>For learning only.</b> Not financial, investment, tax, or legal advice. Nothing you type leaves your computer. <span class="more">More</span></summary>
    <p>This page is an educational tool. It does not recommend any specific investment, insurance company, or financial product. Neither Globefin nor the University of Kentucky endorses its calculations or conclusions. Numbers are estimates, so check the official sources before you decide anything.</p></details>
    <button type="button" class="linkbtn" data-tab="sources">Sources</button></div>
</footer>

<div id="toast" class="toast" role="status" aria-live="assertive"></div>
<div id="modalBg" class="modal-bg" role="dialog" aria-modal="true" aria-labelledby="modalTitle">
  <div class="modal">
    <h3 id="modalTitle">Are you sure?</h3>
    <p id="modalText"></p>
    <div class="row">
      <button type="button" id="modalNo">Cancel</button>
      <button type="button" id="modalYes" class="primary">Continue</button>
    </div>
  </div>
</div>

<script>
"use strict";

/* =========================================================
   1. FACTS (checked Nov 3, 2026). Update these in one place.
   ========================================================= */
const FACTS = {
  checked: "November 3, 2026",
  kySalesTax: 0.06,          // KY sales tax, no local add-on
  kyCarTax: 0.06,            // KY motor vehicle usage tax
  kyCarFees: 30,             // title $9 + registration $21 (typical county clerk fees)
  kyIncomeTax: "3.5%",
  ira2026: 7500,
  k401_2026: 24500,
  hsa2026: 4400,
  hsaFamily2026: 8750,
  k401catch: 8000, k401super: 11250, iraCatch: 1100,
  pellMax: 7395,
  ctc: 2200, ctcRefund: 1700,
  homestead: 49100,
  kyPensionExcl: 31110,
  ableLimit: 20000,
  kyMinWage: 7.25
};

/* =========================================================
   2. OCCUPATION GROUPS (type-to-search with everyday words)
   ========================================================= */
const OCCUPATIONS = [
  {id:"teacher", label:"Teacher or school staff", words:["teacher","teach","educator","school","substitute","para","paraeducator","principal","counselor","librarian","coach","aide"]},
  {id:"public", label:"State, city, or county government", words:["state","government","gov","city","county","public","clerk","frankfort","lfucg","metro","agency","dmv"]},
  {id:"university", label:"University or college employee", words:["university","college","professor","faculty","uk employee","staff","researcher","lab"]},
  {id:"military", label:"Military, National Guard, or veteran", words:["military","army","navy","air force","marine","guard","national guard","veteran","vet","soldier","reserve","coast guard"]},
  {id:"healthcare", label:"Healthcare", words:["nurse","rn","lpn","cna","doctor","physician","medical","hospital","pharmacy","pharmacist","therapist","dental","dentist","healthcare","health","emt","tech"]},
  {id:"responder", label:"Police, fire, or EMS", words:["police","officer","sheriff","deputy","fire","firefighter","ems","paramedic","dispatcher","corrections","first responder"]},
  {id:"agriculture", label:"Farming, horses, or agriculture", words:["farm","farmer","agriculture","ag","horse","equine","groom","barn","tobacco","cattle","crop","stable"]},
  {id:"self", label:"Self-employed or small business", words:["self","self-employed","freelance","freelancer","owner","business","contractor","gig","uber","doordash","lyft","etsy","creator","1099","stylist","photographer"]},
  {id:"trades", label:"Skilled trades", words:["electrician","plumber","welder","hvac","carpenter","mechanic","trade","union","apprentice","construction","lineman","technician"]},
  {id:"hourly", label:"Hourly, retail, food, or service", words:["retail","cashier","server","waiter","waitress","barista","cook","restaurant","warehouse","hourly","store","sales associate","fast food","hotel","bartender","delivery"]},
  {id:"student", label:"Full-time student", words:["student","undergrad","grad student","freshman","sophomore","junior","senior","high school"]}
];

function matchOccupation(text){
  const t = (text||"").toLowerCase().trim();
  if(!t) return null;
  let best=null, bestScore=0;
  for(const o of OCCUPATIONS){
    let s=0;
    for(const w of o.words){
      const re = new RegExp("(^|[^a-z])"+w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"($|[^a-z])");
      if(re.test(t)) s += w.length;
    }
    if(s>bestScore){bestScore=s;best=o;}
  }
  return best;
}

/* =========================================================
   3. MILESTONES
   tool types: growth, card, loan, match, upfront, down, emergency, borrow
   ========================================================= */
const MILESTONES = [
  {id:"teenjob", title:"First job (teen)", age:16,
   why:"Your first paycheck is the first time taxes come out, and doing your taxes right from the start can mean money back. It's also your first chance to save on your own.",
   learn:[
     {name:"Form W-4", what:"The form you fill out on your first day that tells your employer how much federal income tax to take out of each paycheck.", like:"Setting the dial for how much tax comes out now."},
     {name:"Your pay stub", what:"Shows your gross pay (before taxes) and each thing taken out: federal income tax, Social Security and Medicare (7.65% together), Kentucky income tax, and often a local city or county tax.", like:"A receipt for your paycheck."},
     {name:"Filing your tax returns", what:"After the year ends, your employer sends a W-2. You use it to file a federal return and a Kentucky return. If too much was taken out, you get a refund.", like:"Settling up with the government once a year."},
     {name:"Tips and side gigs", what:"Tips are income. Gig and freelance pay (a 1099) usually has no tax taken out, so you set money aside and may owe self-employment tax.", like:"Money no one took tax out of yet."},
     {name:"Savings account (at a bank or credit union)", what:"A safe place to park money that earns a little interest.", like:"Like a piggy bank that pays you a tiny bit to keep your money there."},
     {name:"Custodial Roth IRA", what:"A retirement account an adult opens for a minor who has earned income from a job.", like:"A time capsule for money. What grows inside can come out tax-free in retirement."},
     {name:"Custodial investment account (UGMA/UTMA)", what:"An adult opens and runs an investment account for a minor. The money legally belongs to the child and becomes theirs as an adult.", like:"A gift that grows, with a grown-up holding the keys for now."}
   ],
   alerts:p=>["<b>File your taxes even if you think you don't have to.</b> Many teens with part-time jobs get some or all of their withheld federal tax back, but only if they file a return.",
     "Only write <b>\"Exempt\"</b> on your W-4 if you owed no federal income tax last year and expect to owe none this year. Otherwise you could owe money at tax time.",
     "If a parent claims you as a dependent, check that box when you file. Your parents and you shouldn't both claim you.",
     "Kentucky has its own return too (Form 740), and many Kentucky cities and counties take a local payroll tax that shows on your pay stub.",
     "File for free: IRS Free File and free VITA tax help sites are open to many students and young workers. Never pay someone who promises a \"bigger refund.\"",
     "You don't have to be 18 to save for retirement. A Roth IRA needs <b>earned income</b> (a real job), not a certain age. Under 18, an adult opens it for you as a custodial account."],
   tool:{type:"paycheck", wage:13, hours:20, local:2.25, label:"Where does your first paycheck go?"},
   questions:["What should I put on my W-4?","Will local occupational tax come out of my pay?","When will I get my W-2?","Do you have a savings account for teens with no monthly fee?"],
   checklist:["Fill out your W-4 carefully on your first day","Read your first pay stub and find each tax line","Save your W-2 and file your federal and Kentucky returns by the April deadline","Open a no-fee savings account"],
   bundle:[]},
  {id:"turn18", title:"Turning 18", age:18,
   why:"You can now open accounts in your own name. Starting early is the biggest money advantage you'll ever have.",
   learn:[
     {name:"Checking account", what:"For everyday spending and getting paid by direct deposit.", like:"Your money's home base."},
     {name:"High-yield savings account", what:"Savings that pays more interest than a regular account.", like:"Same safe piggy bank, better rewards."},
     {name:"Roth IRA", what:"A retirement account you fund with money you've already paid tax on. It grows tax-free.", like:"Plant a seed now, harvest it tax-free later."},
     {name:"Brokerage account", what:"An account for buying and selling investments like index funds, ETFs, and stocks. Unlike a retirement account, you can take money out anytime.", like:"A store for investments that's open whenever you need it."},
     {name:"Health insurance until 26", what:"You can usually stay on a parent's health plan until age 26, even if you move out, get married, or have a job with its own plan.", like:"A safety net you don't have to give up at 18."}
   ],
   alerts:p=>[`For 2026 you can put up to <b>$${FACTS.ira2026.toLocaleString()}</b> into an IRA, or your total job earnings for the year if that's less.`, "Credit unions are often open to students and family members. See the <b>You may qualify</b> tab."],
   tool:{type:"growth", monthly:50, rate:6, years:47, delay:10, label:"The cost of waiting 10 years"},
   questions:["Are there monthly fees, and how do I avoid them?","What's the interest rate on savings?","Do you offer a Roth IRA, and what does it cost to open one?"],
   checklist:["Open a checking account in your name","Set up a savings account","Learn how a Roth IRA works"],
   bundle:[]},
  {id:"card", title:"First credit card", age:19,
   why:"A credit card builds your credit score, which affects car loans, apartments, and mortgages. Used wrong, it gets expensive fast.",
   learn:[
     {name:"Secured or student credit card", what:"Starter cards with low limits. A secured card uses your own deposit as the limit.", like:"Training wheels for credit."},
     {name:"Your credit report", what:"A record of how you pay back money. You can get yours free at AnnualCreditReport.com.", like:"Your money report card."},
     {name:"Credit union starter card", what:"Many credit unions offer starter or secured cards to members, often with lower rates and fees than big banks.", like:"Learning to drive in a quiet neighborhood first."},
     {name:"Becoming an authorized user", what:"A parent or trusted adult adds you to their card. Their on-time payments can help build your credit history.", like:"Borrowing someone's good reputation while you build your own."},
     {name:"Credit-builder loan", what:"A small loan, often from a credit union, where the money is held in savings while you make payments. You get it back at the end, and your payments are reported.", like:"Paying yourself while proving you pay on time."},
     {name:"Pre-qualification check", what:"Many card issuers let you see if you're likely to be approved before you apply, usually with a soft credit check.", like:"Peeking at the answer before turning in the test."}
   ],
   alerts:p=>{const a=["Paying the full balance every month means you pay <b>$0 in interest</b>. Interest only kicks in when you carry a balance."]; if(p.age && +p.age<21) a.push("Under 21? Federal law says you need your own income or a cosigner to get a card."); a.push("No credit history yet? The easiest places to start are usually a <b>secured card</b>, a <b>student card</b>, a <b>credit union starter card</b>, or becoming an <b>authorized user</b>. Check <b>You may qualify</b> for credit unions you can join."); a.push("This page doesn't name specific card brands. Offers change all the time, so compare the APR, annual fee, and whether the card reports to all three credit bureaus."); return a;},
   tool:{type:"card", balance:1000, apr:24, payment:40, label:"What carrying a balance really costs"},
   questions:["What's the APR (interest rate)?","Is there an annual fee?","Can I set up autopay for the full balance?"],
   checklist:["Check your free credit report","Pick a card with no annual fee","Turn on autopay for the full balance"],
   bundle:[]},
  {id:"college", title:"Applying for college", age:17,
   why:"How you pay for school can follow you for 10+ years. Free money first, borrowed money last.",
   learn:[
     {name:"FAFSA", what:"The Free Application for Federal Student Aid. It's one free online form at StudentAid.gov that colleges, the federal government, and Kentucky all use to decide your grants (free money), work-study jobs, and federal loans. You fill it out every year you're in school, starting senior year of high school.", like:"The key that opens most of the financial aid doors."},
     {name:"Federal Pell Grant", what:`Free federal money for undergraduates with financial need, up to $${FACTS.pellMax.toLocaleString()} for 2026–27. The FAFSA decides if you qualify.`, like:"The biggest free-money grant, and you don't pay it back."},
     {name:"Work Ready Kentucky Scholarship", what:"Kentucky help with tuition for short certificate programs in high-demand fields. It's run by KHEAA.", like:"A fast track into a good-paying job."},
     {name:"Kentucky CAP Grant", what:"Kentucky's need-based grant for students with financial need. There's no separate application. Your FAFSA is your application.", like:"Free money that goes to the earliest FAFSAs first."},
     {name:"Kentucky Tuition Grant (KTG)", what:"A need-based grant for full-time students at eligible private Kentucky colleges. It also comes from your FAFSA.", like:"Help for private-college tuition, through the same form."},
     {name:"KEES scholarship", what:"Kentucky money you earn with your high school grades and ACT/SAT score. Run by KHEAA.", like:"Points you've been earning since 9th grade."},
     {name:"Federal vs. private student loans", what:"Federal loans have fixed rates and flexible payback options. Private loans usually don't.", like:"Always try the safer ladder before the riskier one."}
   ],
   alerts:p=>["<b>File the FAFSA as early as you can.</b> Kentucky gives out CAP and KTG grants first come, first served by the date you finish your FAFSA, and the money can run out. The 2027–28 FAFSA is already open.",
     "The FAFSA is <b>free</b>. Never pay a website or company to file it for you.",
     "You'll need a StudentAid.gov account (FSA ID). If you're a dependent student, a parent needs one too, to share their tax info.",
     "Check your KEES balance on KHEAA's website. You may have earned more than you think.",
     "Every dollar you borrow gets paid back <b>with interest</b>. Use the calculator below before you sign."],
   tool:{type:"borrow", amount:20000, rate:6.5, years:10, label:"What a student loan costs each month"},
   questions:["Did you get my FAFSA, and is anything missing?","What grants and scholarships am I eligible for?","How much of my aid is a loan vs. free money?","Is this a federal or private loan?"],
   checklist:["Create your StudentAid.gov account (FSA ID)","Submit the FAFSA as soon as it opens, and every year after","List your Kentucky schools on the FAFSA so KHEAA can match state aid","Check your KEES award on KHEAA","Compare the net price (cost minus free aid) of each school"],
   bundle:[{name:"Laptop",price:800,tax:"sales"},{name:"Application fees",price:150,tax:"none"},{name:"Dorm basics",price:300,tax:"sales"}]},
  {id:"turn21", title:"Turning 21", age:21,
   why:"A good time to build a safety net so a surprise bill doesn't turn into credit card debt.",
   learn:[
     {name:"Emergency fund", what:"Money set aside only for real emergencies, like car repairs or a lost job. Many people aim for 3 to 6 months of expenses.", like:"An airbag for your budget."},
     {name:"Renters and car insurance", what:"Covers you when something goes wrong. Shop around every year.", like:"Paying a little now so a disaster doesn't wipe you out."}
   ],
   alerts:p=>["Keep your emergency fund in a separate savings account so you're not tempted to spend it."],
   tool:{type:"emergency", expenses:1800, months:3, saveMonths:12, label:"How big should your safety net be?"},
   questions:["Can I get a discount for bundling renters and car insurance?","Does my savings account have any withdrawal limits?"],
   checklist:["Pick an emergency fund goal","Open a separate savings account for it","Set up an automatic transfer each payday"],
   bundle:[]},
  {id:"car", title:"Buying a car", age:20,
   why:"A car is usually your second-biggest purchase. The interest rate and the taxes can add thousands.",
   learn:[
     {name:"Auto loan", what:"A loan for a car. Credit unions often offer lower rates than dealers. Get pre-approved before you shop.", like:"Shopping with a coupon in your pocket."},
     {name:"Kentucky usage tax", what:"Kentucky charges a 6% motor vehicle usage tax on the price, plus title and registration fees.", like:"Kentucky's version of sales tax for cars."},
     {name:"Kentucky car insurance minimums", what:"Kentucky requires at least 25/50/25 liability ($25,000 per person and $50,000 per accident for injuries, $25,000 for property damage) plus $10,000 in personal injury protection (PIP). Kentucky is a \"choice no-fault\" state.", like:"The legal minimum, which is a floor, not a recommendation."}
   ],
   alerts:p=>[`Budget for <b>6% Kentucky usage tax</b> plus about $${FACTS.kyCarFees} in title and registration fees. On a $15,000 car, that's about $${(15000*FACTS.kyCarTax+FACTS.kyCarFees).toLocaleString()}.`,"Compare loan rates from at least 2 or 3 places. A small rate difference adds up.","Get an insurance quote <b>before</b> you buy. Insurance can cost as much as a car payment for young drivers, and lenders usually require full coverage on a financed car."],
   tool:{type:"loan", amount:20000, rateA:6.9, rateB:8.9, months:60, label:"How much the interest rate matters"},
   questions:["What's the APR and total interest over the loan?","Can I get pre-approved before I visit the dealer?","Is there a penalty for paying the loan off early?"],
   checklist:["Get pre-approved at a credit union or bank","Add 6% KY usage tax and fees to your budget","Compare the total cost, not just the monthly payment"],
   bundle:[{name:"Car",price:15000,tax:"car"},{name:"First 6 months of insurance",price:900,tax:"none"}]},
  {id:"moveout", title:"Moving out", age:20,
   why:"Moving out costs way more than the first month's rent. Planning ahead keeps it from landing on a credit card.",
   learn:[
     {name:"Moving-out fund", what:"Savings for the deposit, first month, utility setup, and furniture.", like:"A launch pad. You need fuel before liftoff."},
     {name:"Renters insurance", what:"Covers your stuff and liability. Usually cheap. Some landlords require it.", like:"A safety net for everything you own."},
     {name:"Your renter rights (security deposits)", what:"Louisville, Lexington, and other cities that adopted Kentucky's landlord-tenant act (URLTA) require landlords to return your deposit within about 30 days, with an itemized list of any deductions. Kentucky has no cap on how big a deposit can be.", like:"Rules that help you get your deposit back."}
   ],
   alerts:p=>["Many landlords want your income to be about <b>3 times the rent</b>.","Working in Lexington or Louisville? A local occupational tax (about 2.2% to 2.25%) comes out of your pay. Use your real take-home pay from your pay stub."],
   tool:{type:"upfront", rent:950, deposit:950, utilities:250, moving:300, furniture:800, label:"What it really costs to move out"},
   questions:["What's included in rent (water, trash, internet)?","How much is the deposit, and how do I get it back?","Do you require renters insurance?"],
   checklist:["Save the full move-out amount before you sign","Read the lease, especially the deposit rules","Get renters insurance"],
   bundle:[{name:"Security deposit",price:950,tax:"none"},{name:"First month's rent",price:950,tax:"none"},{name:"Utility setup and deposits",price:250,tax:"none"},{name:"Bed and mattress",price:600,tax:"sales"},{name:"Kitchen basics",price:200,tax:"sales"}]},
  {id:"salary", title:"First salaried job", age:22,
   why:"Your first job with benefits is where free money shows up: employer matches, health accounts, and more.",
   learn:[
     {name:"401(k) or 403(b)", what:`A retirement plan through work. Money comes out before taxes. The 2026 limit is $${FACTS.k401_2026.toLocaleString()}.`, like:"A paycheck to your future self, taken out before you can spend it."},
     {name:"Employer match", what:"Your employer adds money when you save. For example, they match up to 4% of your pay.", like:"A 100% bonus on the money you put in."},
     {name:"HSA (Health Savings Account)", what:`Only with a high-deductible health plan. Money goes in tax-free, grows tax-free, and comes out tax-free for medical bills. The 2026 limit for one person is $${FACTS.hsa2026.toLocaleString()}.`, like:"A triple-tax-free piggy bank for doctor bills."},
     {name:"Disability insurance", what:"Replaces part of your paycheck if illness or injury keeps you from working. Many jobs offer it cheap or free, so check your benefits.", like:"Insurance for your paycheck."},
     {name:"Index funds and ETFs", what:"Funds that hold a whole basket of investments by following a market index. You can hold them inside a 401(k), an IRA, or a brokerage account.", like:"Buying a slice of the whole pizza instead of betting on one topping."},
     {name:"Choosing a health plan", what:"Compare the premium (what you pay every paycheck), the deductible (what you pay before the plan starts paying), and the out-of-pocket max (the most you'd pay in a bad year).", like:"Picking between a low monthly bill and a low worst-case bill."},
     {name:"Public Service Loan Forgiveness (PSLF)", what:"If you work full-time for a government or nonprofit employer, your remaining federal Direct Loans can be forgiven after 120 qualifying monthly payments.", like:"Ten years of public service can erase what's left of your student loans."}
   ],
   alerts:p=>occAlerts(p,"salary"),
   tool:{type:"match", salary:45000, matchPct:4, yourPct:2, label:"Are you leaving free money on the table?"},
   questions:["Do you match retirement contributions, and how much?","When can I start, and when is the match mine to keep (vesting)?","Is there an HSA option?"],
   checklist:["Fill out your W-4 carefully","Sign up for the retirement plan","Contribute at least enough to get the full match","Choose beneficiaries on every account"],
   bundle:[{name:"Work clothes",price:300,tax:"sales"}]},
  {id:"married", title:"Getting married", age:27,
   why:"Two people means two sets of accounts, debts, and habits. Talking money early prevents fights later.",
   learn:[
     {name:"Joint or shared accounts", what:"Some couples combine everything, some keep separate accounts plus one shared one.", like:"Yours, mine, and ours."},
     {name:"Beneficiaries", what:"The person who gets an account if something happens to you. Update every account.", like:"Telling your money where to go."}
   ],
   alerts:p=>["Most employer health plans let you add a spouse after a wedding, but only within a short window, often 30 days. Ask HR right away.","Update your W-4 at work so the right amount of tax is withheld."],
   tool:{type:"emergency", expenses:3500, months:3, saveMonths:18, label:"A shared safety net"},
   questions:["Can I add my spouse to my health plan, and what's the deadline?","How do I update beneficiaries?"],
   checklist:["Share credit reports and debts with each other","Update beneficiaries","Update your W-4"],
   bundle:[{name:"Rings",price:1500,tax:"sales"},{name:"Wedding costs",price:6000,tax:"none"}]},
  {id:"home", title:"Buying a home or getting a mortgage", age:29,
   why:"The down payment is only part of it. Closing costs, your credit score, and the rate all matter.",
   learn:[
     {name:"Mortgage", what:"A long loan (often 30 years) to buy a home. Your credit score affects your rate.", like:"Renting the money to buy the house."},
     {name:"Property tax and homeowners insurance", what:"Your monthly cost is more than the loan. Property tax and homeowners insurance are usually added to your payment through an escrow account.", like:"The hidden half of a house payment."},
     {name:"Flood and earthquake insurance", what:"Regular homeowners insurance doesn't cover floods or earthquakes. Flood policies usually take 30 days to start, and western Kentucky sits near the New Madrid fault.", like:"The two disasters your main policy skips."},
     {name:"Kentucky Housing Corporation (KHC)", what:"Kentucky's housing agency. It offers home loans and down payment help through approved lenders.", like:"A state program that helps you get in the door."},
     {name:"CD (certificate of deposit)", what:"You lock money away for a set time, like 6 months to 5 years, in exchange for a fixed interest rate. Credit unions call them share certificates.", like:"A savings account with a lock on the door and a better rate."},
     {name:"KHC down payment assistance (DAP)", what:"A loan from Kentucky Housing Corporation that helps cover the down payment and closing costs. Recent sources list up to $12,500.", like:"A boost to get in the door, which you pay back over time."},
     {name:"KHC first-time buyer mortgage", what:"KHC's Mortgage Revenue Bond program offers fixed-rate 30-year mortgages for first-time buyers who meet income and price limits.", like:"A state-backed starter mortgage."},
     {name:"Local down payment help", what:"Some cities run their own programs. Louisville's is a 0% loan, and half is forgiven after 15 years in the home. Check your city's housing office.", like:"Help from your hometown, on top of the state."}
   ],
   alerts:p=>{const a=[];
     if(p.firstTime) a.push("<b>First-time buyer?</b> You may qualify for KHC's first-time buyer mortgage and down payment help. Ask a KHC-approved lender, and compare with an FHA loan"+((p.veteran||p.serving)?" and your <b>VA home loan</b>, which usually needs no down payment":"")+".");
     a.push("KHC down payment help is a <b>loan you pay back</b>, not free money. Check kyhousing.org for current amounts and income limits.","Plan for closing costs on top of the down payment.");
     return a.concat(occAlerts(p,"home"));},
   tool:{type:"down", price:225000, label:"How much cash do you need?"},
   questions:["What's the rate and APR, and what are the total closing costs?","Am I eligible for KHC programs?","How much is mortgage insurance, and when does it go away?"],
   checklist:["Check your credit score","Get pre-approved","Ask a KHC-approved lender about Kentucky programs"],
   bundle:[{name:"Down payment",price:7875,tax:"none"},{name:"Closing costs",price:6000,tax:"none"},{name:"Moving costs",price:800,tax:"none"}]},
  {id:"kid", title:"Having a kid", age:30,
   why:"Kids are expensive now and later. Small steps early make college savings much easier.",
   learn:[
     {name:"529 college savings plan", what:"Grows tax-free when spent on school. Kentucky's plan is KY Saves 529. You can use any state's plan.", like:"A college piggy bank where the growth isn't taxed."},
     {name:"Life insurance", what:"Pays your family if you die. Term life is usually the simplest and cheapest type.", like:"A promise your kids will be OK."},
     {name:"Dependent care FSA", what:"Some employers let you pay for daycare with pre-tax money.", like:"A discount on childcare through your paycheck."},
     {name:"Child Tax Credit", what:`Up to $${FACTS.ctc.toLocaleString()} per child under 17 for 2026, with up to $${FACTS.ctcRefund.toLocaleString()} refundable even if you owe little tax. Your child needs a Social Security number.`, like:"A thank-you from the IRS for raising a kid."},
     {name:"KCHIP", what:"Kentucky's low-cost or free health insurance for uninsured kids under 19 in families that earn too much for Medicaid. Apply anytime on kynect.", like:"A health plan just for kids."}
   ],
   alerts:p=>["Kentucky does <b>not</b> give a state tax deduction for 529 contributions, even though some websites say it does. The growth is still tax-free for school costs.","Add your baby to your health insurance quickly, since there's usually a short deadline."],
   tool:{type:"growth", monthly:100, rate:6, years:18, delay:5, label:"College savings: start at birth or wait 5 years?"},
   questions:["When is the deadline to add my baby to my health plan?","Do you offer a dependent care FSA?","How much life insurance does my family need?"],
   checklist:["Add your child to health insurance","Learn about 529 plans","Look into term life insurance"],
   bundle:[{name:"Crib",price:250,tax:"sales"},{name:"Car seat",price:200,tax:"sales"},{name:"Stroller",price:250,tax:"sales"}]},
  {id:"disability", title:"Family member with a disability", age:null, situation:true, active:p=>p.disability,
   why:"Saving too much can risk benefits like SSI and Medicaid. A special account solves that.",
   learn:[
     {name:"STABLE Kentucky (ABLE account)", what:`Starting January 1, 2026, open to people whose disability began before age 46 (it used to be 26). Anyone can contribute up to $${FACTS.ableLimit.toLocaleString()} a year total, and savings generally don't count against SSI and Medicaid limits.`, like:"A savings account designed not to cost you your benefits."},
     {name:"Kentucky homestead exemption", what:`Homeowners who are totally disabled (or 65 and older) can take $${FACTS.homestead.toLocaleString()} off their home's assessed value for 2025 and 2026 property taxes. There's no income limit. You apply through your county PVA office.`, like:"A discount on your property tax bill."},
     {name:"kynect", what:"Kentucky's one-stop site to apply for Medicaid, KCHIP for kids, and other benefits. Medicaid and KCHIP accept applications all year.", like:"Kentucky's front door for health coverage and benefits."}
   ],
   alerts:p=>["<b>New in 2026:</b> ABLE accounts now cover disabilities that began before age <b>46</b>, not just before 26. Many more Kentuckians can open a STABLE account now, at any age.","Before ABLE accounts, people on SSI could only keep about $2,000. ABLE money generally isn't counted, so you can save for housing, school, transportation, and more."],
   tool:null,
   questions:["Am I eligible for STABLE Kentucky?","Which expenses count as qualified disability expenses?"],
   checklist:["Read the STABLE Kentucky fact sheet","Ask a benefits counselor how saving affects benefits"],
   bundle:[]},
  {id:"relocate", title:"Moving to, from, or within Kentucky", age:null, situation:true, active:p=>!!p.move,
   get why(){ return RELOC[relocType()].why; },
   get learn(){ return RELOC[relocType()].learn; },
   alerts:p=>RELOC[relocType()].alerts(),
   get tool(){ const t=relocType(); if(t==="within") return null; return {type:"relocate", salary:45000, otherRate:noWageTax()?0:4, kyLocal:2.25, otherLocal:0, moveCost:1500, carValue:t==="coming"?12000:0, oldCarTax:5,
     label: t==="coming"?"What moving to Kentucky could cost": t==="leaving"?"Kentucky vs. your new state": "Comparing state taxes"}; },
   get questions(){ return RELOC[relocType()].questions; },
   get checklist(){ return RELOC[relocType()].checklist; },
   bundle:[{name:"Movers or truck rental",price:1200,tax:"none"},{name:"Deposits at the new place",price:1000,tax:"none"},{name:"Travel and first week of food",price:400,tax:"none"}]},
  {id:"military", title:"Military service and veteran benefits", age:null, situation:true, active:p=>p.veteran||p.serving||p.milFamily,
   get why(){ const p=state.profile; return p.veteran? "You earned benefits that can save you serious money on a home, school, taxes, and banking. Many veterans never use all of them." : p.serving? "Serving now unlocks retirement, housing, and legal money protections, plus benefits you'll keep as a veteran." : "Family members of veterans and service members can qualify for school, banking, and home benefits too."; },
   get learn(){ const p=state.profile, out=[];
     if(p.veteran||p.serving) out.push({name:"VA home loan", what:"A home loan from a private lender that the VA partly guarantees. It's a lifetime benefit you can use more than once.", like:"The VA co-signs with you, so lenders give you better terms."});
     if(p.veteran||p.serving) out.push({name:"GI Bill", what:"VA education benefits that can help pay for college, trade school, or training.", like:"School money you earned with your service."});
     if(p.serving) out.push({name:"Thrift Savings Plan (TSP)", what:"The military's retirement savings plan, like a 401(k). Under the Blended Retirement System, the government adds matching contributions.", like:"A 401(k) for service members, with a match."});
     if(p.serving) out.push({name:"Servicemembers Civil Relief Act (SCRA)", what:"Federal protections while on active duty, including a 6% cap on interest for many debts you had before you joined.", like:"A shield for your finances while you serve."});
     if(p.veteran) out.push({name:"Kentucky tax breaks for veterans", what:"Kentucky excludes up to $31,110 of military retirement pay from state income tax (all of it for service before 1998). VA disability pay is tax-free.", like:"Kentucky lets you keep more of what you earned."});
     if(p.veteran) out.push({name:"Kentucky homestead exemption (100% disabled)", what:"Veterans rated 100% disabled can get a property tax exemption on their home through the county PVA office.", like:"A discount on your home's property tax bill."});
     if(p.milFamily||p.veteran) out.push({name:"KDVA tuition waiver for family", what:"Spouses and children of Kentucky veterans who are 100% disabled or who died from service can get tuition waived at Kentucky public colleges.", like:"Free tuition earned by your family's service."});
     out.push({name:"Kentucky Department of Veterans Affairs (KDVA)", what:"Free benefits representatives help you file VA claims and find state benefits.", like:"A free guide through the paperwork."});
     return out; },
   alerts:p=>{ const a=[];
     if(p.veteran||p.serving) a.push("A VA home loan usually needs <b>no down payment</b> and <b>no mortgage insurance (PMI)</b>. You may pay a one-time funding fee, but many veterans with a service-connected disability don't have to.");
     if(p.veteran||p.serving) a.push("Navy Federal Credit Union is open to all veterans, service members, and their families. Abound Credit Union (formerly Fort Knox FCU) serves retired military. See the <b>You may qualify</b> tab.");
     if(p.veteran) a.push("Military retirement pay counts toward Kentucky's $31,110 pension exclusion, so it shares that cap with other retirement income.");
     if(p.milFamily) a.push("Family members can often join military credit unions like Navy Federal through a veteran or service member in the family.");
     a.push("Never pay someone to file a VA claim for you. KDVA benefits representatives help for free.");
     return a; },
   get tool(){ const p=state.profile; return (p.veteran||p.serving)? {type:"valoan", price:250000, rate:6.5, pmi:0.6, label:"VA loan vs. a 5% down conventional loan"} : null; },
   get questions(){ return ["How do I get my VA Certificate of Eligibility?","Am I exempt from the VA funding fee?","Which Kentucky benefits do I qualify for?"]; },
   get checklist(){ return ["Get your VA Certificate of Eligibility","Talk to a free KDVA benefits representative","Check your eligibility at a military-friendly credit union"]; },
   bundle:[]},
  {id:"retire", title:"Planning for retirement", age:40,
   why:"Retirement could last 25+ years. The earlier you know your plan, the easier it gets.",
   learn:[
     {name:"Your workplace plan + IRA", what:"Most people use a mix: a work plan, an IRA, and Social Security or a pension.", like:"A three-legged stool."},
     {name:"Social Security statement", what:"See your estimated benefit at ssa.gov. Check it every year or two.", like:"A preview of one leg of the stool."},
     {name:"Kentucky retirement tax breaks", what:`Kentucky doesn't tax Social Security and excludes up to $${FACTS.kyPensionExcl.toLocaleString()} of pension, 401(k), and IRA income per person.`, like:"Kentucky lets retirees keep more."}
   ],
   alerts:p=>occAlerts(p,"retire"),
   tool:{type:"growth", monthly:300, rate:6, years:25, delay:10, label:"Starting at 40 vs. 50"},
   questions:["What will my pension or Social Security pay?","Am I on track for my workplace plan?","Can I make catch-up contributions after 50?"],
   checklist:["Check your Social Security or pension estimate","Review your contribution rate every year","Update beneficiaries"],
   bundle:[]}
];

/* =========================================================
   3b. MOVING TO, FROM, OR WITHIN KENTUCKY
   Content changes with the move type picked in "About you".
   ========================================================= */
const MOVE_TYPES = [
  ["", "I'm not moving"],
  ["within", "Moving within Kentucky"],
  ["leaving", "Leaving Kentucky for another state"],
  ["coming", "Moving to Kentucky to stay"],
  ["short", "In Kentucky short-term (school, internship, temp job)"],
  ["border", "Living in one state, working in the other (KY and a neighbor)"]
];
const RECIP_STATES = ["illinois","indiana","michigan","ohio","virginia","west virginia","wisconsin","il","in","mi","oh","va","wv","wi"];
const NO_WAGE_TAX = ["alaska","florida","nevada","new hampshire","south dakota","tennessee","texas","washington","wyoming","ak","fl","nv","nh","sd","tn","tx","wa","wy"];
function noWageTax(){ return NO_WAGE_TAX.includes(otherState().toLowerCase().replace(/\./g,"")); }
function otherState(){ return (state.profile.moveState||"").trim(); }
function isRecip(){ return RECIP_STATES.includes(otherState().toLowerCase().replace(/\./g,"")); }
const RELOC = {
  within:{
    why:"Moving inside Kentucky can still change your taxes, your credit union options, and your bills.",
    learn:[
      {name:"Local occupational tax", what:"Many Kentucky cities and counties take a payroll tax based on where you work, not where you live. A new job location can change your take-home pay.", like:"A city fee that rides along with your paycheck."},
      {name:"Utility and rental deposits", what:"New places often want deposits for rent, power, water, and internet. Old deposits come back later, so plan for overlap.", like:"Paying the cover charge twice before you get the first one back."}
    ],
    alerts:()=>["Update your address on your Kentucky driver's license, your car registration, your bank, and your employer.","If you change counties, check the <b>You may qualify</b> tab again. Some credit unions are based on county."],
    questions:["Will my take-home pay change at my new work location?","When do I get my old deposit back?","Is my renters insurance moving with me?"],
    checklist:["Update your address with the post office, bank, and employer","Update your Kentucky license and vehicle registration","Budget for new deposits before the old ones come back"]
  },
  leaving:{
    why:"Leaving Kentucky means two states care about your taxes that year, and some Kentucky programs work differently once you're gone.",
    learn:[
      {name:"Part-year tax returns", what:"In the year you move, you usually file a Kentucky part-year return (Form 740-NP) plus a return in your new state.", like:"Splitting the bill when you leave the restaurant halfway through dinner."},
      {name:"Accounts that move with you", what:"Your 401(k), IRA, and KY Saves 529 stay yours. A 529 can pay for eligible schools in any state.", like:"Luggage you get to keep."},
      {name:"Kentucky public pensions", what:"If you're leaving a teaching or government job, TRS, KPPA, or KDC money has its own rules for vesting, refunds, and rollovers.", like:"Read the fine print before you pull the plug."}
    ],
    alerts:()=>{ const a=["Before you quit a Kentucky public job, ask TRS, KPPA, or KDC what happens to your money if you leave. Cashing out early can mean taxes and penalties, and you may lose credit toward a pension.","KEES can't follow you to just any college. It works at Kentucky schools, and out of state only for certain programs through the Academic Common Market.","Many credit unions let you stay a member after you move. Ask before you close your account."];
      if(otherState()) a.unshift(`Look up <b>${esc(otherState())}</b>'s income tax rate and rules. Kentucky's is a flat ${FACTS.kyIncomeTax} for 2026, plus local taxes in many cities.`);
      return a; },
    questions:["What happens to my retirement plan or pension if I leave?","Can I keep my credit union account after I move?","Which tax returns will I need to file this year?"],
    checklist:["Compare your take-home pay in both states","Ask HR or your pension system about leaving","File a Kentucky part-year return next tax season","Update your address with the IRS, post office, and banks"]
  },
  coming:{
    why:"Welcome to Kentucky! New residents have short deadlines for a license and car registration, and some costs surprise people.",
    learn:[
      {name:"Kentucky driver's license", what:"New residents must get a Kentucky license within 30 days of moving here.", like:"Your Kentucky membership card."},
      {name:"Vehicle title and usage tax", what:"You title and register your car at your county clerk within 15 days. Kentucky charges a 6% usage tax on the car's trade-in value, minus credit for tax you already paid in your old state.", like:"Kentucky's welcome fee for your car, with a discount for what you already paid."},
      {name:"Kentucky income tax", what:`A flat ${FACTS.kyIncomeTax} state rate for 2026, plus a local occupational tax in many cities based on where you work.`, like:"One simple state rate, with a city add-on."},
      {name:"kynect", what:"Kentucky's health insurance marketplace. Moving often lets you sign up outside of open enrollment.", like:"Kentucky's health insurance store."}
    ],
    alerts:()=>["You need <b>Kentucky car insurance</b> before you can title your car here, so set that up first.","Bring proof of the sales tax you paid when you bought the car. It lowers your Kentucky usage tax.","Planning to go to a Kentucky public college? Just living here doesn't make you in-state for tuition. Kentucky looks at your domicile, and many rules use a 12-month test."],
    questions:["How much will my car's usage tax be after the credit?","Which local occupational tax applies at my new job?","Am I eligible for a special enrollment period on kynect?"],
    checklist:["Get Kentucky car insurance","Title and register your car within 15 days","Get your Kentucky driver's license within 30 days","Register to vote and update your address everywhere"]
  },
  short:{
    why:"Here for school, an internship, or a short job? You may still count as a resident of your home state, which changes your taxes and tuition.",
    learn:[
      {name:"Nonresident tax return", what:"If you earn wages in Kentucky but your home is another state, you may need to file a Kentucky nonresident return (Form 740-NP). Your home state may give you credit for tax paid here.", like:"Paying the state where you worked, then telling your home state so you aren't taxed twice."},
      {name:"Tax reciprocity", what:"If your home state is Illinois, Indiana, Michigan, Ohio, Virginia, West Virginia, or Wisconsin, your Kentucky wages may be exempt from Kentucky income tax. Give your employer Form 42A809.", like:"A neighbor deal: you only pay your home state."},
      {name:"In-state tuition", what:"Attending school here doesn't make you a Kentucky resident for tuition. Kentucky decides under a state regulation (13 KAR 2:045).", like:"Being a guest doesn't make you the homeowner."}
    ],
    alerts:()=>{ const a=["Reciprocity doesn't apply if you live in Kentucky for <b>more than 183 days</b> in the tax year. A full school year can go past that, so check before you skip Kentucky withholding.","Local occupational taxes can still come out of your Kentucky paycheck even if state tax doesn't."];
      if(otherState()) a.unshift(isRecip()? `Good news: <b>${esc(otherState())}</b> has a tax reciprocity deal with Kentucky. Ask your employer about Form 42A809.` : `<b>${esc(otherState())}</b> isn't one of Kentucky's reciprocity states, so you may file in both states. Your home state may give a credit for Kentucky tax.`);
      return a; },
    questions:["Should Kentucky tax come out of my paycheck?","Will my home state give me credit for Kentucky tax?","Do I need to register my car in Kentucky?"],
    checklist:["Find out which state is your tax home","Ask your employer about Form 42A809 if you qualify","Keep your pay stubs for both states' tax returns"]
  },
  border:{
    why:"Lots of people live in Ohio, Indiana, or another neighbor and work in Kentucky, or the other way around. Reciprocity deals can save you from double state tax.",
    learn:[
      {name:"Tax reciprocity", what:"Kentucky has deals with Illinois, Indiana, Michigan, Ohio, Virginia, West Virginia, and Wisconsin. Wages are usually taxed only by the state you live in.", like:"A handshake between neighbor states."},
      {name:"Local taxes don't follow the deal", what:"City and county taxes, like Kentucky occupational taxes or a city earnings tax across the river, can still apply where you work.", like:"The state deal covers the big bill, not the city's."}
    ],
    alerts:()=>{ const a=["Not a Kentucky resident but working here? Give your employer <b>Form 42A809</b> so Kentucky income tax isn't taken out by mistake (if you qualify).","Reciprocity doesn't apply if you live in Kentucky for more than 183 days in the tax year."];
      if(otherState()) a.unshift(isRecip()? `<b>${esc(otherState())}</b> is a reciprocity state with Kentucky.` : `<b>${esc(otherState())}</b> isn't on Kentucky's reciprocity list, so you may owe tax in both states with a credit.`);
      return a; },
    questions:["Is the right state's tax coming out of my paycheck?","Which local taxes apply where I work?"],
    checklist:["Check which state's tax is withheld on your pay stub","File the reciprocity form with your employer if you qualify"]
  }
};
function relocType(){ return RELOC[state.profile.move] ? state.profile.move : "coming"; }


/* =========================================================
   3c. ACCOUNT GUIDE: when you can open it, pros, things to know,
   and trusted links (government and nonprofit sources only).
   ========================================================= */
const L = {
  fdic:["FDIC: deposit insurance","https://www.fdic.gov/resources/deposit-insurance"],
  ncua:["NCUA: credit union insurance","https://mycreditunion.gov/protect-your-money/share-insurance"],
  cfpbBank:["CFPB: bank accounts","https://www.consumerfinance.gov/consumer-tools/bank-accounts/"],
  roth:["IRS: Roth IRAs","https://www.irs.gov/retirement-plans/roth-iras"],
  p590:["IRS Publication 590-A: IRAs","https://www.irs.gov/publications/p590a"],
  kids:["FINRA: ways to invest for children","https://www.finra.org/investors/insights/investing-children"],
  custodial:["FINRA: custodial accounts","https://finra.org/investors/learn-to-invest/types-investments/saving-for-education/esa-and-custodial-accounts"],
  brokerage:["SEC: how to open a brokerage account","https://www.investor.gov/introduction-investing/general-resources/news-alerts/alerts-bulletins/investor-bulletins-43"],
  students:["SEC: investing tips for college students","https://www.investor.gov/introduction-investing/general-resources/news-alerts/alerts-bulletins/investor-bulletins/investor-bulletin-top-10-investment-tips-college-students"],
  brokercheck:["FINRA BrokerCheck: look up a firm","https://brokercheck.finra.org"],
  sipc:["SIPC: what it protects","https://www.sipc.org"],
  index:["SEC: index funds","https://www.investor.gov/introduction-investing/investing-basics/investment-products/mutual-funds-and-exchange-traded-4"],
  etf:["SEC: what is an ETF?","https://www.investor.gov/introduction-investing/investing-basics/glossary/exchange-traded-fund-etf"],
  compound:["SEC: compound interest calculator","https://www.investor.gov/financial-tools-calculators/calculators/compound-interest-calculator"],
  cd:["SEC: CDs and the fine print","https://www.investor.gov/additional-resources/general-resources/publications-research/info-sheets/high-yield-cds-protect-your"],
  k401:["IRS: 401(k) plans","https://www.irs.gov/retirement-plans/401k-plans"],
  k403:["IRS: 403(b) plans","https://www.irs.gov/retirement-plans/irc-403b-tax-sheltered-annuity-plans"],
  hsa:["IRS Publication 969: HSAs","https://www.irs.gov/publications/p969"],
  hsaGloss:["HealthCare.gov: what is an HSA?","https://www.healthcare.gov/glossary/health-savings-account-hsa/"],
  p503:["IRS Publication 503: child care costs","https://www.irs.gov/publications/p503"],
  q529:["IRS: 529 plans Q&A","https://www.irs.gov/newsroom/529-plans-questions-and-answers"],
  kysaves:["KY Saves 529","https://www.kysaves.com"],
  cards:["CFPB: credit cards","https://www.consumerfinance.gov/consumer-tools/credit-cards/"],
  credit:["CFPB: credit reports and scores","https://www.consumerfinance.gov/consumer-tools/credit-reports-and-scores/"],
  acr:["AnnualCreditReport.com (free reports)","https://www.annualcreditreport.com"],
  fafsa:["StudentAid.gov: the FAFSA","https://studentaid.gov/h/apply-for-aid/fafsa"],
  loans:["StudentAid.gov: types of loans","https://studentaid.gov/understand-aid/types/loans"],
  kheaa:["KHEAA: KEES","https://www.kheaa.com"],
  auto:["CFPB: auto loans","https://www.consumerfinance.gov/consumer-tools/auto-loans/"],
  usage:["KY Revenue: motor vehicle usage tax","https://revenue.ky.gov/Property/Motor-Vehicles/Pages/Motor-Vehicle-Usage-Tax.aspx"],
  ins:["Kentucky Department of Insurance","https://insurance.ky.gov"],
  home:["CFPB: buying a house","https://www.consumerfinance.gov/owning-a-home/"],
  khc:["Kentucky Housing Corporation","https://www.kyhousing.org"],
  stable:["STABLE Kentucky","https://stablekentucky.com"],
  ssa:["Social Security: my Social Security account","https://www.ssa.gov/myaccount/"],
  trs:["Teachers' Retirement System of KY","https://trs.ky.gov"],
  kdc:["Kentucky Deferred Compensation","https://kdc.ky.gov"],
  drive:["KY: New to Kentucky drivers","https://drive.ky.gov/Drivers/Pages/New-To-Kentucky.aspx"],
  rev:["Kentucky Department of Revenue","https://revenue.ky.gov"],
  kynect:["kynect","https://kynect.ky.gov"],
  tuition:["13 KAR 2:045 (tuition residency)","https://apps.legislature.ky.gov/law/kar/titles/013/002/045/"],
  acm:["KEES and the Academic Common Market","https://cpe.ky.gov/acm/acm-kees.html"],
  deposit:["Kentucky Equal Justice Center: security deposits","https://www.kyjustice.org/topics/evictions/security-deposits-only-places-passed-urlta-uniform-residential-landlord-tenant-act"],
  pslf:["StudentAid.gov: Public Service Loan Forgiveness","https://studentaid.gov/manage-loans/forgiveness-cancellation/public-service"],
  w4:["IRS: Form W-4","https://www.irs.gov/forms-pubs/about-form-w-4"],
  freefile:["IRS Free File","https://www.irs.gov/filing/irs-free-file-do-your-taxes-for-free"],
  vita:["IRS: free tax help (VITA)","https://www.irs.gov/individuals/free-tax-return-preparation-for-qualifying-taxpayers"],
  vaLoan:["VA: home loan purchase loans","https://www.va.gov/housing-assistance/home-loans/loan-types/purchase-loan/"],
  vaFee:["VA: who pays the funding fee","https://news.va.gov/147050/funding-fee-who-pays-who-is-exempt/"],
  gi:["VA: education and training (GI Bill)","https://www.va.gov/education/"],
  tsp:["Thrift Savings Plan","https://www.tsp.gov"],
  mos:["Military OneSource (free financial counseling)","https://www.militaryonesource.mil"],
  kdva:["Kentucky Department of Veterans Affairs","https://veterans.ky.gov"],
  kdvaEd:["KDVA: tuition waiver for dependents","https://veterans.ky.gov/Benefits/Pages/Education-for-Veterans-in-Kentucky.aspx"],
  homestead:["KY Revenue: homestead exemption","https://revenue.ky.gov/Property/Residential-Farm-Commercial-Property/Pages/Homestead-Exemption.aspx"]
};
const ACCT_INFO = {
  "Savings account (at a bank or credit union)":{cat:"Banking and saving", when:"Any age. Under 18 usually needs a parent or guardian on the account.",
    pros:["Safe: insured up to $250,000 at FDIC banks and NCUA credit unions","Easy to get your money anytime","Builds the saving habit early"],
    watch:["Interest is usually low","Watch for monthly fees and minimum balances"], links:[L.fdic,L.ncua]},
  "Checking account":{cat:"Banking and saving", when:"Age 18 on your own. Younger with a parent or guardian.",
    pros:["Direct deposit, debit card, and bill pay in one place","Federally insured at FDIC banks and NCUA credit unions"],
    watch:["Overdraft and monthly fees can add up, so ask how to avoid them"], links:[L.cfpbBank,L.fdic]},
  "High-yield savings account":{cat:"Banking and saving", when:"Age 18 on your own.",
    pros:["Pays more interest than a regular savings account","Still federally insured if the bank or credit union is insured","Great home for an emergency fund"],
    watch:["Rates can change at any time","Some are online-only, so check how fast transfers are"], links:[L.fdic,L.ncua]},
  "CD (certificate of deposit)":{cat:"Banking and saving", when:"Age 18 on your own.",
    pros:["Fixed rate, so you know exactly what you'll earn","Federally insured at insured banks and credit unions","Good for money you need on a set date, like a down payment"],
    watch:["Taking money out early usually means a penalty","Some 'high-yield' CDs have tricky fine print, so read it"], links:[L.cd,L.fdic]},
  "Emergency fund":{cat:"Banking and saving", when:"Anytime. It's a goal, not a special account.",
    pros:["Keeps surprise bills off your credit card","Less stress when things go wrong"],
    watch:["Keep it somewhere safe and easy to reach, not invested in the stock market"], links:[L.fdic]},
  "Moving-out fund":{cat:"Banking and saving", when:"Anytime.", pros:["Lets you move without starting in debt"], watch:["Plan for deposits that overlap"], links:[L.cfpbBank]},
  "Brokerage account":{cat:"Investing", when:"Age 18 on your own. Under 18, an adult can open a custodial account for you.",
    pros:["No yearly contribution limit","Take money out anytime with no early-withdrawal penalty","Use it for any goal, like a house or freedom fund","Can hold low-cost index funds and ETFs"],
    watch:["Investments go up and down, and you can lose money","Not FDIC insured. SIPC covers a failed brokerage firm, not market losses","You pay tax on dividends and gains","Some sign-up forms make a margin (borrowing) account the default, so pick a cash account"],
    links:[L.brokerage,L.students,L.brokercheck,L.sipc]},
  "Index funds and ETFs":{cat:"Investing", when:"Anytime you have an account that can hold them: a 401(k), IRA, or brokerage account.",
    pros:["Spreads your money across many companies at once","Usually lower fees than funds that try to beat the market","Less buying and selling, which can mean lower taxes"],
    watch:["They still fall when the market falls","Fees still matter, so compare expense ratios"], links:[L.index,L.etf,L.compound]},
  "Custodial investment account (UGMA/UTMA)":{cat:"Investing", when:"Any age. An adult opens it for the child.",
    pros:["No contribution limits","Money can be used for anything that benefits the child","Gives investments a long time to grow"],
    watch:["The gift can't be taken back","The child gets full control when they reach the age set by state law"], links:[L.kids,L.custodial]},
  "Roth IRA":{cat:"Retirement", when:"Any age, as long as you have earned income from a job.",
    pros:["Growth and qualified withdrawals in retirement are tax-free","You can take out your contributions (not the growth) anytime","You pick where you open it and what it holds"],
    watch:[`2026 limit: $${FACTS.ira2026.toLocaleString()} or your earnings, whichever is less`,"Taking out growth early can mean taxes and a penalty","Higher incomes can't contribute directly"], links:[L.roth,L.p590,L.compound]},
  "Custodial Roth IRA":{cat:"Retirement", when:"Any age with earned income. An adult opens and manages it until the child is an adult.",
    pros:["Decades of tax-free growth","Teaches investing early"],
    watch:["Contributions can't be more than the teen earned that year"], links:[L.roth,L.kids]},
  "401(k) or 403(b)":{cat:"Retirement", when:"Through your employer, once you meet the plan's rules.",
    pros:["Money comes out of your paycheck automatically","Often comes with an employer match","Much higher limit than an IRA"],
    watch:["Investment choices are limited to the plan's menu","Early withdrawals usually mean taxes and a penalty","Check your plan's fees"], links:[L.k401,L.k403]},
  "Employer match":{cat:"Retirement", when:"When you're in a workplace plan that offers one.",
    pros:["Free money added to your retirement","An instant return on what you put in"],
    watch:["You may have to stay a while before the match is fully yours (vesting)"], links:[L.k401]},
  "HSA (Health Savings Account)":{cat:"Health and family", when:"Only when you're covered by a high-deductible health plan and no one claims you as a dependent.",
    pros:["Triple tax break: in, growth, and out for medical costs","The money is yours to keep even if you change jobs","Unused money rolls over every year"],
    watch:["You need a high-deductible health plan to contribute","Using it for non-medical costs means taxes and possibly a penalty"], links:[L.hsa,L.hsaGloss]},
  "Dependent care FSA":{cat:"Health and family", when:"Through your employer, if offered.", pros:["Pay for daycare with pre-tax money"], watch:["Use it or lose it rules may apply"], links:[L.p503]},
  "Disability insurance":{cat:"Health and family", when:"Usually through a job with benefits, or buy your own if self-employed.", pros:["Protects your income, your biggest money tool","Group plans through work are often low-cost or free"], watch:["Most plans replace only part of your pay","Work coverage usually ends when you leave the job"], links:[["Social Security disability benefits","https://www.ssa.gov/disability"],L.ins]},
  "Flood and earthquake insurance":{cat:"Health and family", when:"Any homeowner or renter. Buy before you need it.", pros:["Covers disasters regular policies leave out","Renters can cover belongings too"], watch:["NFIP flood policies usually have a 30-day wait","Earthquake deductibles are often a percent of the home's value"], links:[["FloodSmart (National Flood Insurance Program)","https://www.floodsmart.gov"],L.ins]},
  "Life insurance":{cat:"Health and family", when:"Any adult. Most useful when others depend on your income.", pros:["Protects your family if you die","Term life is usually simple and low-cost"], watch:["Compare quotes and check that the company is licensed in Kentucky"], links:[L.ins]},
  "Renters insurance":{cat:"Health and family", when:"Anyone renting.", pros:["Usually low-cost","Covers your stuff and liability"], watch:["Check the deductible"], links:[L.ins]},
  "Renters and car insurance":{cat:"Health and family", when:"Anyone renting or driving.", pros:["Protects you from big, sudden costs"], watch:["Shop around every year"], links:[L.ins]},
  "529 college savings plan":{cat:"Education", when:"Anyone can open one for any student, any age.",
    pros:["Growth is tax-free when spent on qualified school costs","Can pay for schools in any state","You can switch the beneficiary to another family member"],
    watch:["Kentucky gives no state tax deduction for contributions","Non-school withdrawals mean taxes and a penalty on growth"], links:[L.q529,L.kysaves]},
  "FAFSA":{cat:"Education", when:"Every year you'll be in college or training, starting senior year of high school. File as soon as it opens.",
    pros:["Free to file","One form for federal aid (like Pell Grants) and Kentucky aid (CAP, KTG)","Colleges use it for their own scholarships too"],
    watch:["Kentucky's CAP and KTG grants are first come, first served, so file early","Dependent students need a parent's info","Never pay anyone to file it"], links:[L.fafsa,L.kheaa]},
  "Kentucky CAP Grant":{cat:"Education", when:"Kentucky residents with financial need who file the FAFSA.",
    pros:["Free money you don't pay back","No separate application"], watch:["First come, first served by FAFSA date","Need is decided from your FAFSA"], links:[L.kheaa,L.fafsa]},
  "Kentucky Tuition Grant (KTG)":{cat:"Education", when:"Full-time Kentucky residents with need at eligible private Kentucky colleges.",
    pros:["Free money for private-college tuition","Comes from your FAFSA"], watch:["First come, first served","Full-time enrollment required"], links:[L.kheaa]},
  "Form W-4":{cat:"Taxes and paychecks", when:"Your first day at any job, and anytime your life changes (a second job, marriage, a baby).",
    pros:["Controls how much federal tax comes out of each check","Getting it right avoids a surprise tax bill"], watch:["Only claim \"exempt\" if you truly owe no tax"], links:[L.w4]},
  "Your pay stub":{cat:"Taxes and paychecks", when:"Every payday.", pros:["Helps you catch payroll mistakes","Shows how much goes to taxes"], watch:["Check that the right state and local taxes are taken out"], links:[L.w4]},
  "Filing your tax returns":{cat:"Taxes and paychecks", when:"Each spring for the year before, usually by mid-April.",
    pros:["Often means a refund for part-time workers","Free options through IRS Free File and VITA"], watch:["File both federal and Kentucky returns","Keep your W-2s and 1099s"], links:[L.freefile,L.vita,L.rev]},
  "Tips and side gigs":{cat:"Taxes and paychecks", when:"Any time you earn tips or freelance or gig pay.", pros:["Extra income on your own schedule"], watch:["No tax is withheld from most gig pay","You may owe self-employment tax, so set some aside"], links:[L.freefile]},
  "KEES scholarship":{cat:"Education", when:"Earned in Kentucky high school, used in college.", pros:["Money you earn with your grades"], watch:["Only usable at Kentucky schools or through the Academic Common Market"], links:[L.kheaa,L.acm]},
  "Federal vs. private student loans":{cat:"Education", when:"When you've used up free aid.", pros:["Federal loans have fixed rates and flexible payback"], watch:["Every dollar borrowed comes back with interest"], links:[L.loans]},
  "Secured or student credit card":{cat:"Credit and borrowing", when:"Age 18. Under 21 needs your own income or a cosigner.", pros:["Builds your credit history","Pay in full and it costs $0 in interest"], watch:["Carrying a balance gets expensive fast"], links:[L.cards]},
  "Your credit report":{cat:"Credit and borrowing", when:"Anytime, free.", pros:["Catch mistakes and fraud early"], watch:["Only use the official free site"], links:[L.acr,L.credit]},
  "Auto loan":{cat:"Credit and borrowing", when:"Age 18, or younger with a cosigner.", pros:["Pre-approval gives you bargaining power"], watch:["Compare the total cost, not just the monthly payment"], links:[L.auto]},
  "Kentucky usage tax":{cat:"Kentucky programs and rules", when:"When you title a car in Kentucky.", pros:["No local add-on statewide"], watch:["6% of the price, due at the county clerk"], links:[L.usage]},
  "Mortgage":{cat:"Credit and borrowing", when:"Age 18 with enough income and credit.", pros:["Builds home equity over time"], watch:["Closing costs and mortgage insurance add up"], links:[L.home]},
  "Kentucky Housing Corporation (KHC)":{cat:"Kentucky programs and rules", when:"Kentucky homebuyers who meet income and price limits.", pros:["Help with the down payment and closing costs"], watch:["Down payment help is a loan you repay"], links:[L.khc]},
  "STABLE Kentucky (ABLE account)":{cat:"Kentucky programs and rules", when:"Any age, if the disability began before age 46 (the rule since Jan. 1, 2026).", pros:["Save without losing SSI or Medicaid in most cases","Growth is tax-free when spent on qualified disability expenses","Family and friends can contribute"], watch:[`$${FACTS.ableLimit.toLocaleString()} a year total from everyone (2026)`,"Medicaid may be paid back from what's left after death"], links:[L.stable]},
  "Kentucky homestead exemption":{cat:"Kentucky programs and rules", when:"Kentucky homeowners age 65+ or totally disabled.", pros:[`$${FACTS.homestead.toLocaleString()} off your assessed value (2025–2026)`,"No income limit"], watch:["Apply through your county PVA","It's for your main home only"], links:[L.homestead]},
  "Social Security statement":{cat:"Retirement", when:"Anytime, online.", pros:["See your estimated benefit"], watch:["Most Kentucky teachers won't get Social Security from teaching"], links:[L.ssa]},
  "Your workplace plan + IRA":{cat:"Retirement", when:"Anytime you're working.", pros:["Using both can raise how much you save with tax breaks"], watch:["Different rules for each account"], links:[L.k401,L.roth]},
  "Kentucky public pensions":{cat:"Kentucky programs and rules", when:"Kentucky public school and government jobs.", pros:["A lifetime pension if you qualify"], watch:["Leaving early has special rules"], links:[L.trs,L.kdc]},
  "Kentucky driver's license":{cat:"Kentucky programs and rules", when:"Within 30 days of moving here.", pros:[], watch:[], links:[L.drive]},
  "Vehicle title and usage tax":{cat:"Kentucky programs and rules", when:"Within 15 days of moving here.", pros:[], watch:[], links:[L.usage]},
  "kynect":{cat:"Health and family", when:"Medicaid and KCHIP any time. Private health plans during open enrollment, or after a life event like a move.", pros:["One application checks you for Medicaid, KCHIP, and plans with financial help"], watch:["Report income changes to keep the right help"], links:[L.kynect]},
  "Kentucky income tax":{cat:"Kentucky programs and rules", when:"", pros:[], watch:[], links:[L.rev]},
  "Part-year tax returns":{cat:"Kentucky programs and rules", when:"", pros:[], watch:[], links:[L.rev]},
  "Nonresident tax return":{cat:"Kentucky programs and rules", when:"", pros:[], watch:[], links:[L.rev]},
  "Tax reciprocity":{cat:"Kentucky programs and rules", when:"", pros:[], watch:[], links:[L.rev]},
  "In-state tuition":{cat:"Education", when:"", pros:[], watch:[], links:[L.tuition]},
  "KHC down payment assistance (DAP)":{cat:"Kentucky programs and rules", when:"Kentucky homebuyers using a KHC loan who meet income and price limits.",
    pros:["Covers down payment and closing costs so you can buy sooner","Available through KHC-approved lenders statewide"], watch:["It's a loan you repay, so your monthly cost goes up","Amounts and limits change, so check KHC's site"], links:[L.khc,L.home]},
  "KHC first-time buyer mortgage":{cat:"Kentucky programs and rules", when:"First-time buyers who meet KHC income and purchase price limits.",
    pros:["Fixed rate for 30 years","Can pair with KHC down payment help"], watch:["Income and price limits apply","You'll likely need a homebuyer education course"], links:[L.khc]},
  "Local down payment help":{cat:"Kentucky programs and rules", when:"Depends on your city's rules.",
    pros:["Can stack with state help","Louisville's program forgives half after 15 years"], watch:["Usually must be your main home","Selling early may mean paying it back"], links:[L.home]},
  "Credit union starter card":{cat:"Credit and borrowing", when:"Once you're a member, usually age 18 or older.",
    pros:["Often lower rates and fees","Local help if you have questions"], watch:["You have to be eligible to join the credit union first"], links:[L.cards,L.ncua]},
  "Becoming an authorized user":{cat:"Credit and borrowing", when:"Any age the card issuer allows.",
    pros:["No application or credit check for you","Can start your credit history early"], watch:["Their late payments can hurt you too","Only helps if the issuer reports authorized users"], links:[L.credit]},
  "Credit-builder loan":{cat:"Credit and borrowing", when:"Usually age 18, often at credit unions.",
    pros:["Builds a payment history and savings at the same time","Easier to get than a card for many beginners"], watch:["Missed payments hurt your credit","There may be interest or fees"], links:[L.credit]},
  "Pre-qualification check":{cat:"Credit and borrowing", when:"Anytime before you apply.",
    pros:["Usually a soft check that doesn't hurt your score","Helps you avoid applying for cards you won't get"], watch:["Pre-qualified isn't a guarantee of approval","The real application is a hard check"], links:[L.cards]},
  "Kentucky car insurance minimums":{cat:"Health and family", when:"Before you register or drive a car in Kentucky.", pros:["PIP pays medical bills no matter who caused the crash"], watch:["Minimum coverage may not cover a serious accident","Financed cars usually need full coverage"], links:[L.ins]},
  "Your renter rights (security deposits)":{cat:"Kentucky programs and rules", when:"Anytime you rent. The strongest rules apply in cities that adopted URLTA, like Louisville and Lexington.", pros:["Deposit back within about 30 days, with an itemized list","Small claims court if it isn't returned"], watch:["Rules differ outside URLTA cities","Take dated move-in and move-out photos"], links:[L.deposit]},
  "Federal Pell Grant":{cat:"Education", when:"Undergraduates with financial need, through the FAFSA.", pros:["Free money you don't pay back",`Up to $${FACTS.pellMax.toLocaleString()} for 2026–27`], watch:["Amount depends on need and enrollment"], links:[L.fafsa]},
  "Work Ready Kentucky Scholarship":{cat:"Education", when:"Kentucky residents in eligible certificate programs.", pros:["Short programs that lead to in-demand jobs"], watch:["Program and school rules apply, so check with KHEAA"], links:[L.kheaa]},
  "Health insurance until 26":{cat:"Health and family", when:"Until your 26th birthday, if a parent's plan offers dependent coverage.", pros:["Often cheaper than buying your own plan"], watch:["Coverage ends at 26, so plan ahead for your own"], links:[L.kynect]},
  "Choosing a health plan":{cat:"Health and family", when:"At a new job and during open enrollment each year.", pros:["The right plan can save thousands in a bad year"], watch:["The lowest premium isn't always the cheapest overall","High-deductible plans can pair with an HSA"], links:[L.hsaGloss]},
  "Public Service Loan Forgiveness (PSLF)":{cat:"Education", when:"Full-time government and nonprofit workers with federal Direct Loans.", pros:["Remaining balance forgiven tax-free after 120 qualifying payments","Payments don't have to be in a row"], watch:["Submit the employer certification form every year","Only federal Direct Loans count"], links:[L.pslf]},
  "Child Tax Credit":{cat:"Health and family", when:"Each tax year, for children under 17 with a Social Security number.", pros:[`Up to $${FACTS.ctc.toLocaleString()} per child (2026)`,`Up to $${FACTS.ctcRefund.toLocaleString()} can come back as a refund`], watch:["Phases out at higher incomes"], links:[L.freefile]},
  "KCHIP":{cat:"Health and family", when:"Uninsured kids under 19 whose family income is above the Medicaid limit, up to about 218% of the poverty level.", pros:["Low or no cost","Apply any time of year"], watch:["The child generally can't have other health insurance"], links:[L.kynect]},
  "Kentucky retirement tax breaks":{cat:"Retirement", when:"Kentucky residents with retirement income.", pros:["Social Security isn't taxed by Kentucky",`Up to $${FACTS.kyPensionExcl.toLocaleString()} of pension and retirement income excluded`], watch:["The exclusion is shared across all your pension income"], links:[L.rev]},
  "Property tax and homeowners insurance":{cat:"Credit and borrowing", when:"When you buy a home.", pros:["Escrow spreads big bills into monthly payments"], watch:["Both can rise over time","Shop homeowners insurance every year"], links:[L.home,L.ins]},
  "VA home loan":{cat:"Military and veterans", when:"Veterans, service members, Guard and Reserve members who meet service rules, and some surviving spouses.",
    pros:["Usually no down payment","No private mortgage insurance (PMI)","Competitive interest rates","No penalty for paying it off early","A lifetime benefit you can reuse"],
    watch:["A one-time funding fee unless you're exempt","Lenders can still set their own credit score rules","The home must be your main residence"], links:[L.vaLoan,L.vaFee]},
  "GI Bill":{cat:"Military and veterans", when:"Veterans and service members who meet service requirements. Some benefits can transfer to family.",
    pros:["Helps pay tuition and fees","Veterans using the GI Bill generally get in-state tuition at public colleges"], watch:["Benefits have time and service rules, so check your entitlement"], links:[L.gi]},
  "Thrift Savings Plan (TSP)":{cat:"Military and veterans", when:"Service members and federal employees.",
    pros:["Very low fees","Government matching contributions under the Blended Retirement System","Roth and traditional options"], watch:["Early withdrawals can mean taxes and penalties"], links:[L.tsp]},
  "Servicemembers Civil Relief Act (SCRA)":{cat:"Military and veterans", when:"While on active duty.",
    pros:["6% interest cap on many debts from before you joined","Protections on leases and some contracts"], watch:["You usually have to ask your lender for it in writing"], links:[L.mos]},
  "Kentucky tax breaks for veterans":{cat:"Military and veterans", when:"Kentucky residents with military retirement or VA disability pay.",
    pros:["Up to $31,110 of retirement pay excluded","All of it excluded for service before 1998","VA disability pay is tax-free"], watch:["The $31,110 cap is shared with other pension income"], links:[L.rev]},
  "Kentucky homestead exemption (100% disabled)":{cat:"Military and veterans", when:"Veterans rated 100% disabled who own their Kentucky home.",
    pros:["Lowers the taxable value of your home"], watch:["Apply through your county PVA office"], links:[L.homestead]},
  "KDVA tuition waiver for family":{cat:"Military and veterans", when:"Spouses and children of qualifying Kentucky veterans.",
    pros:["Waives tuition at Kentucky public colleges and technical schools","Can be combined with federal Chapter 35 benefits"], watch:["Covers tuition only, not fees, books, or housing","Private and out-of-state schools don't qualify"], links:[L.kdvaEd]},
  "Kentucky Department of Veterans Affairs (KDVA)":{cat:"Military and veterans", when:"Kentucky veterans and families.",
    pros:["Free help filing VA claims","One place for state benefits"], watch:[], links:[L.kdva,L.mos]},
  "Accounts that move with you":{cat:"Retirement", when:"", pros:[], watch:[], links:[L.q529,L.p590]}
};
function linkList(links){ return (links||[]).map(([t,u])=>`<a href="${esc(u)}" target="_blank" rel="noopener noreferrer">${esc(t)}</a>`).join(" &nbsp;|&nbsp; "); }
/* Collapsible section: closed until the user opens it. Open/closed is remembered while the page is open. */
const uiOpen = {};
function sec(key, icon, title, badge, body, openByDefault){
  const open = key in uiOpen ? uiOpen[key] : !!openByDefault;
  return `<details class="sec" data-k="${esc(key)}" ${open?"open":""}><summary>${ico(icon,"xs")}<span class="st">${title}</span>${badge!==""&&badge!=null?`<span class="pill">${badge}</span>`:""}<span class="chev" aria-hidden="true">▶</span></summary><div class="sec-body">${body}</div></details>`;
}
function acctHtml(l, full){
  const i = ACCT_INFO[l.name] || {};
  const pros = (i.pros||[]).length? `<div class="pros"><b>Why people use it</b><ul>${i.pros.map(x=>`<li>${esc(x)}</li>`).join("")}</ul></div>`:"";
  const watch = (i.watch||[]).length? `<div class="watch"><b>Good to know</b><ul>${i.watch.map(x=>`<li>${esc(x)}</li>`).join("")}</ul></div>`:"";
  const more = `${l.like?`<div class="like">Think of it like this: ${esc(l.like.charAt(0).toLowerCase()+l.like.slice(1))}</div>`:""}
    ${i.when?`<div class="when"><b>When you can open it:</b> ${esc(i.when)}</div>`:""}
    ${(pros||watch)?`<div class="pw">${pros}${watch}</div>`:""}
    ${(i.links||[]).length?`<div class="learn">Learn more: ${linkList(i.links)}</div>`:""}`;
  const hasMore = !!(l.like||i.when||pros||watch||(i.links||[]).length);
  if(!hasMore) return `<div class="acct"><b>${esc(l.name)}</b><div>${esc(l.what)}</div></div>`;
  return `<details class="acct"><summary><span class="an">${esc(l.name)}</span><span class="aw">${esc(l.what)}</span><span class="amore">Details</span></summary><div class="acct-more">${more}</div></details>`;
}

const MS_BY_ID = Object.fromEntries(MILESTONES.map(m=>[m.id,m]));

/* Occupation-specific heads-up notes */
function occAlerts(p, where){
  const g = matchOccupation(p.occupation);
  const id = g ? g.id : null;
  const out = [];
  if(where==="salary"){
    out.push("Contribute at least enough to get the <b>full employer match</b>. That's free money.");
    if(id==="teacher") out.push("<b>Kentucky teachers:</b> your main retirement is the Teachers' Retirement System (TRS) pension. Most KY teachers <b>don't pay into or get Social Security</b> from teaching. You can also save extra through Kentucky Deferred Compensation (KDC).");
    if(id==="public") out.push("<b>Kentucky public employees:</b> Kentucky Deferred Compensation (KDC) offers extra 401(k) and 457(b) plans. New state hires are automatically enrolled in the 401(k), so check your pay stub.");
    if(id==="university") out.push("<b>University employees:</b> ask HR about your retirement plan choices and Kentucky Deferred Compensation (KDC).");
    if(id==="healthcare") out.push("<b>Hospitals and nonprofits</b> often offer a 403(b), which works like a 401(k). Ask about the match.");
    if(id==="responder") out.push("<b>Police, fire, and EMS:</b> many Kentucky city and county jobs are in a public pension run by the Kentucky Public Pensions Authority (KPPA). Ask HR which plan covers you. KDC may be an extra option.");
    if(id==="military") out.push("<b>Military:</b> ask about the Thrift Savings Plan (TSP), the military's retirement savings plan, and whether you get matching contributions.");
    if(id==="self") out.push("<b>Self-employed:</b> no boss means no match, but you can look into a SEP IRA or Solo 401(k). Also set money aside for quarterly estimated taxes.");
    if(id==="trades") out.push("<b>Skilled trades:</b> many unions have their own pension or annuity plan. Ask your local how it works.");
    if(id==="hourly") out.push("<b>Hourly jobs:</b> some employers offer a 401(k) to part-time workers too. Ask when you become eligible.");
    if(id==="agriculture") out.push("<b>Farm and horse work:</b> if your job has no retirement plan, you can still open your own IRA. Starting your own operation? The Kentucky Agricultural Finance Corporation has a Beginning Farmer Loan Program through local lenders.");
    if(["teacher","public","university","healthcare","responder"].includes(id)) out.push("<b>Student loans?</b> Government and nonprofit jobs can qualify for Public Service Loan Forgiveness (PSLF). Submit the employment form on StudentAid.gov every year.");
    if(id==="teacher") out.push("<b>Teachers</b> at qualifying low-income schools may also get up to $17,500 forgiven after five years through Teacher Loan Forgiveness.");
    if(id==="healthcare") out.push("<b>Healthcare workers</b> in shortage areas can look into National Health Service Corps loan repayment.");
    if(id==="self") out.push("Self-employment tax is about <b>15.3%</b> on your profit (both halves of Social Security and Medicare), on top of income tax.");
  }
  if(where==="retire"){
    if(id==="teacher") out.push("<b>Kentucky teachers:</b> most don't get Social Security from teaching, so the TRS pension plus your own savings is your whole retirement. Check your TRS estimate.");
    else out.push("Check your Social Security estimate at ssa.gov to see what one leg of your plan looks like.");
    if(id==="public"||id==="responder") out.push("Kentucky public employees can check their pension estimate with KPPA or TRS, and save extra through KDC.");
    out.push(`Catch-up contributions for 2026: age 50+ can add <b>$${FACTS.k401catch.toLocaleString()}</b> to a 401(k), 403(b), or 457(b) (<b>$${FACTS.k401super.toLocaleString()}</b> at ages 60–63) and <b>$${FACTS.iraCatch.toLocaleString()}</b> to an IRA.`);
    out.push(`Kentucky doesn't tax Social Security, and lets you exclude up to <b>$${FACTS.kyPensionExcl.toLocaleString()}</b> of pension and retirement income from state tax.`);
    out.push(`At 65, Kentucky homeowners can get the homestead exemption: $${FACTS.homestead.toLocaleString()} off their home's assessed value (2025–2026).`);
  }
  if(where==="home"){
    if(id==="military") out.push("<b>Military and veterans:</b> ask about VA home loans, which may not require a down payment.");
    if(id==="agriculture") out.push("<b>Rural areas:</b> USDA home loans can help with homes in eligible rural areas. Buying farmland? Ask about the Kentucky Agricultural Finance Corporation's Beginning Farmer Loan Program.");
  }
  return out;
}

/* =========================================================
   4. WHERE YOU MAY QUALIFY
   ========================================================= */
const COMMONWEALTH_COUNTIES = ["anderson","bourbon","boyle","bullitt","clark","estill","fayette","franklin","garrard","harrison","henry","jefferson"];
const PLACES = [
  {name:"UK Credit Union (UK Federal Credit Union)", type:"Credit union", url:"https://www.ukcreditunion.org/forallyall",
   test:p=>{ const r=[]; if(["uk","eku","bctc","kctcs"].includes(p.school)) r.push("You're a current or former student at a school on its list (UK, EKU, BCTC, KCTCS, and more)."); if(p.worksUK) r.push("You work for the University of Kentucky."); return r; },
   maybe:"Also open to employees of 100+ Central Kentucky partner employers and family members of current members."},
  {name:"Commonwealth Credit Union", type:"Credit union", url:"https://www.ccuky.org",
   test:p=>{ const c=(p.county||"").toLowerCase().replace(/\s*county\s*$/,"").trim(); return COMMONWEALTH_COUNTIES.includes(c)? ["You live or work in "+cap(c)+" County, which is in its membership area."]:[]; },
   maybe:"Open to people who live, work, worship, or go to school in certain Central Kentucky counties, plus partner employers. Check the full county list on its site."},
  {name:"Kentucky Deferred Compensation (KDC)", type:"Retirement plans for public workers", url:"https://kdc.ky.gov",
   test:p=>{ const g=matchOccupation(p.occupation); return g && ["teacher","public","university","responder"].includes(g.id)? ["You work in a public job. KDC serves state, public school, university, and participating local government employees."]:[]; },
   maybe:"Only for Kentucky public employees."},
  {name:"Teachers' Retirement System of Kentucky (TRS)", type:"Teacher pension", url:"https://trs.ky.gov",
   test:p=>{ const g=matchOccupation(p.occupation); return g && g.id==="teacher"? ["You're a teacher or school staff member. Most Kentucky public school teachers are TRS members."]:[]; },
   maybe:"For Kentucky public school teachers and some education staff."},
  {name:"Kentucky Public Pensions Authority (KPPA)", type:"Public employee pension", url:"https://www.kyret.ky.gov",
   test:p=>{ const g=matchOccupation(p.occupation); return g && ["public","responder"].includes(g.id)? ["Many state and county workers, police, and firefighters are covered by KPPA systems."]:[]; },
   maybe:"For many state and local government employees."},
  {name:"Kentucky Housing Corporation (KHC)", type:"Homebuyer programs", url:"https://www.kyhousing.org",
   test:p=> p.firstTime? ["You'd be a first-time buyer. KHC has first-time buyer mortgages and down payment assistance through approved lenders."] : p.firstHome? ["You're planning to buy a home. KHC offers home loans and down payment help through approved lenders."]:[],
   maybe:"For Kentucky homebuyers who meet income and price limits. Down payment help is a repayable loan."},
  {name:"KY Saves 529", type:"College savings", url:"https://www.kysaves.com",
   test:p=> (p.kids? ["You have or plan to have kids. Anyone can open a 529 for a child."]:[]),
   maybe:"Open to anyone saving for someone's education. No Kentucky tax deduction for contributions."},
  {name:"STABLE Kentucky", type:"ABLE account for disabilities", url:"https://stablekentucky.com",
   test:p=> p.disability? ["Someone in your family has a disability that began before age 46, which is the rule since 2026."]:[],
   maybe:"For people whose disability began before age 46 (updated from 26 on Jan. 1, 2026)."},
  {name:"KHEAA (KEES scholarships and college aid)", type:"College aid", url:"https://www.kheaa.com",
   test:p=> (p.age && +p.age<=24)? ["You're at the age where KEES and Kentucky college aid can matter."]:[],
   maybe:"For Kentucky students heading to college or training."},
  {name:"Kentucky Driver Licensing (New to Kentucky)", type:"License and car", url:"https://drive.ky.gov/Drivers/Pages/New-To-Kentucky.aspx",
   test:p=> p.move==="coming"? ["You're moving to Kentucky. You have 30 days to get a Kentucky license, and your car needs a Kentucky title within 15 days."]:[],
   maybe:"For new residents getting a license and registering a car."},
  {name:"kynect (Kentucky's health insurance marketplace)", type:"Health insurance", url:"https://kynect.ky.gov",
   test:p=> (p.move==="coming"||p.move==="leaving")? ["Moving can let you sign up for health coverage outside open enrollment."]:[],
   maybe:"For Kentuckians shopping for health coverage or other benefits."},
  {name:"Kentucky Department of Revenue: reciprocity and nonresident returns", type:"State taxes", url:"https://revenue.ky.gov",
   test:p=> (p.move==="short"||p.move==="border"||p.move==="leaving")? [p.move==="leaving"?"You'll likely file a Kentucky part-year return (Form 740-NP) for the year you move.":"You work across a state line. Kentucky's reciprocity rules and Form 42A809 may apply to you."]:[],
   maybe:"Tax forms for part-year residents, nonresidents, and people who live in a neighboring state."},
  {name:"VA home loans and benefits", type:"Veteran benefits", url:"https://www.va.gov/housing-assistance/home-loans/loan-types/purchase-loan/",
   test:p=> (p.veteran||p.serving)? ["Your service may make you eligible for a VA home loan with no down payment and no PMI."]:[],
   maybe:"For veterans, service members, and some surviving spouses."},
  {name:"Kentucky Department of Veterans Affairs", type:"Veteran benefits", url:"https://veterans.ky.gov",
   test:p=> (p.veteran||p.milFamily)? [p.veteran?"Free help filing VA claims and finding Kentucky benefits.":"Family of qualifying veterans may get Kentucky tuition waivers."]:[],
   maybe:"Free benefits help for Kentucky veterans and families."},
  {name:"Kentucky Agricultural Finance Corporation", type:"Farm loans", url:"https://www.kyagr.com/agpolicy/Kentucky-Ag-Finance-Corporation.html",
   test:p=>{ const g=matchOccupation(p.occupation); return g&&g.id==="agriculture"? ["You work in farming. Kentucky's Beginning Farmer Loan Program helps finance livestock, equipment, facilities, and farmland through local lenders."]:[]; },
   maybe:"Beginning farmer and farm infrastructure loans through local lenders."},
  {name:"StudentAid.gov: Public Service Loan Forgiveness", type:"Student loans", url:"https://studentaid.gov/manage-loans/forgiveness-cancellation/public-service",
   test:p=>{ const g=matchOccupation(p.occupation); return g&&["teacher","public","university","healthcare","responder"].includes(g.id)? ["Your job may be with a government or nonprofit employer, which can qualify for PSLF."]:[]; },
   maybe:"For full-time government and nonprofit workers with federal student loans."},
  {name:"Find any credit union you can join", type:"Search tool (federal)", url:"https://mycreditunion.gov/about-credit-unions/credit-union-locator",
   test:p=>[],
   maybe:"Many credit unions are open based on where you live, work, or go to school. Use the federal locator to find more."}
];


/* Kentucky credit unions: membership paths (checked Nov 2026; always confirm on the credit union's site) */
const CU = [
  {name:"Members Heritage Credit Union", url:"https://www.membersheritage.org", counties:["anderson","bath","bourbon","boyle","clark","estill","fayette","franklin","garrard","harrison","jessamine","lincoln","woodford"],
   note:"Open to people who live, work, worship, go to school, or have family in 22 Bluegrass and Gateway counties, plus some employer groups."},
  {name:"Park Community Credit Union", url:"https://parkcommunity.com/eligibility/", counties:["anderson","bourbon","boyle","bullitt","casey","clark","estill","fayette","franklin","garrard","harrison","henry","jackson","jefferson","oldham","shelby","spencer","trimble"],
   note:"Open to people who live, work, worship, or go to school in its Louisville-area and Bluegrass counties, plus family and household members."},
  {name:"L&N Federal Credit Union", url:"https://lnfcu.com/become-a-member", counties:["bullitt","henry","jefferson","knox","laurel","oldham","pulaski","rockcastle","shelby","spencer","trimble","boone","campbell","kenton","gallatin","grant","pendleton"],
   note:"Open to people in the Louisville area and parts of southeastern and Northern Kentucky, plus family of members. Northern Kentucky eligibility covers certain areas only."},
  {name:"Abound Credit Union", url:"https://www.aboundcu.com/Learn/What-We-re-About/Membership", counties:["boyle","breckinridge","grayson","hart","larue","meade","nelson","taylor"],
   mil:true, note:"Open to people in several central Kentucky counties, active and retired military, Fort Knox civilians and contractors, and family of members. You may also qualify by joining a partner military support association."},
  {name:"Navy Federal Credit Union", url:"https://www.navyfederal.org/membership/eligibility.html", counties:[], milAll:true,
   note:"Open to all veterans, active duty, Guard and Reserve, Department of Defense civilians, and their immediate family and household members."}
];
function countyKey(p){ return (p.county||"").toLowerCase().replace(/\s*county\s*$/,"").trim(); }
CU.forEach(c=>PLACES.splice(PLACES.length-1,0,{name:c.name, type:"Credit union", url:c.url, maybe:c.note,
  test:p=>{ const r=[], k=countyKey(p);
    if(k && c.counties.includes(k)) r.push(`You live or work in ${cap(k)} County, which is in its membership area.`);
    if(c.milAll && (p.veteran||p.serving)) r.push(p.veteran?"You're a veteran. All veterans can join, no matter how long you served.":"You're serving now, so you can join.");
    if(c.milAll && p.milFamily && !(p.veteran||p.serving)) r.push("Your family member's service makes you eligible as immediate family.");
    if(c.mil && (p.serving || p.veteran)) r.push("It serves active and retired military. Check whether your service qualifies.");
    return r; }}));

/* =========================================================
   5. QUIZ
   ========================================================= */
const QUIZ = [
  {q:"Kentucky gives you a state tax deduction for putting money in a KY Saves 529 college plan.", a:false, why:"False. Kentucky gives no state tax deduction for 529 contributions, even though some websites say it does. The growth is still tax-free when used for school."},
  {q:"Most Kentucky public school teachers pay into and collect Social Security from their teaching jobs.", a:false, why:"False. Most Kentucky teachers are in the TRS pension instead of Social Security. That makes their own savings extra important."},
  {q:"Kentucky Housing Corporation down payment help is free money you never pay back.", a:false, why:"False. It's a loan you repay. It helps you get in the door, but it's still debt."},
  {q:"You have to be 18 to have a Roth IRA.", a:false, why:"False. You need earned income from a job, not a certain age. A parent or guardian can open a custodial Roth IRA for a teen with a job."},
  {q:"On a $15,000 car, Kentucky's 6% usage tax adds about $900.", a:true, why:"True. $15,000 × 6% = $900, plus title and registration fees."},
  {q:"Credit unions are only for people who work at one specific company.", a:false, why:"False. Many Kentucky credit unions let you join based on where you live, work, worship, or go to school, or through family members."},
  {q:"When you buy a home in Kentucky, you pay 6% sales tax on the price.", a:false, why:"False. There's no sales tax on a home. Kentucky's real estate transfer tax is $0.50 per $500 of value, and the seller usually pays it. Buyers plan for closing costs, property tax, and insurance instead."},
  {q:"In 2026, you can only open an ABLE account (like STABLE Kentucky) if your disability started before age 26.", a:false, why:"False. Starting January 1, 2026, the rule is a disability that began before age 46. Many more people now qualify."},
  {q:"If you only worked a part-time job and earned a little, there's no reason to file a tax return.", a:false, why:"False. Filing is often how part-time workers get back the federal tax taken out of their paychecks. You also may need to file a Kentucky return."},
  {q:"The FAFSA costs money to file, so you should only do it if you're sure you'll get aid.", a:false, why:"False. The FAFSA is free. In Kentucky, CAP and KTG grants go out first come, first served by FAFSA date, so filing early matters."},
  {q:"A real job might pay you to like videos or rate apps, as long as you pay a small deposit first to unlock your earnings.", a:false, why:"False. That's a \"task\" job scam. Real jobs don't make you pay to get paid, and the FTC says jobs that pay you to like or rate content are illegal."},
  {q:"If you have no credit history, your only option is to wait until someone gives you a regular credit card.", a:false, why:"False. Secured cards, student cards, credit union starter cards, credit-builder loans, and becoming an authorized user are all common ways to start building credit."},
  {q:"VA home loans usually require private mortgage insurance (PMI) if you put less than 20% down.", a:false, why:"False. VA home loans don't require PMI and usually don't need a down payment. Many borrowers pay a one-time funding fee instead, and many disabled veterans are exempt."},
  {q:"New Kentucky residents have 30 days to get a Kentucky driver's license.", a:true, why:"True. Kentucky law gives new residents 30 days. Your car needs a Kentucky title even sooner, within 15 days."},
  {q:"If you live in Ohio and work in Kentucky, Kentucky income tax is usually taken from your wages.", a:false, why:"False. Ohio is one of seven reciprocity states. Your wages are usually taxed only by Ohio, as long as you give your employer Form 42A809. Local job taxes can still apply."},
  {q:"If you pay your credit card balance in full every month, you pay no interest.", a:true, why:"True. Interest only kicks in when you carry a balance past the due date."}
  ,
  // ---- Banking and saving ----
  {q:"Money in an FDIC-insured bank is protected up to $250,000 per depositor, per bank, per ownership type.", a:true, why:"True. If an insured bank fails, the FDIC covers deposits up to that limit. It doesn't cover stocks, bonds, or mutual funds."},
  {q:"Credit union deposits aren't federally insured, so they're riskier than bank deposits.", a:false, why:"False. Federally insured credit unions are covered by the NCUA up to $250,000, the same limit as the FDIC."},
  {q:"FDIC insurance covers stocks and mutual funds you buy through your bank.", a:false, why:"False. FDIC insurance covers deposits like checking, savings, and CDs. Investments can lose value even if you bought them at a bank."},
  {q:"A common guideline is to build an emergency fund of 3 to 6 months of must-pay expenses.", a:true, why:"True. Start with a small goal, like $500 or one month, then build up. The calculator in Moving out can help."},
  {q:"Online banks and credit unions sometimes pay much more interest on savings than a standard savings account at a big bank.", a:true, why:"True. Rates differ a lot. Comparing a few places can earn you more on the same money."},
  {q:"Banks can charge overdraft fees on ATM withdrawals and one-time debit card purchases even if you never opted in.", a:false, why:"False. Under federal rules, banks need your permission (opt-in) before charging overdraft fees on those transactions."},
  {q:"Interest you earn in a savings account is usually taxable income.", a:true, why:"True. Banks send a Form 1099-INT if you earn $10 or more, and you report the interest on your tax return."},
  {q:"Teens under 18 can't have any kind of bank account.", a:false, why:"False. Many banks and credit unions offer teen or joint accounts with a parent or guardian."},
  {q:"A budget means you can never spend money on fun.", a:false, why:"False. A good budget plans for fun too. It just decides ahead of time how much."},
  {q:"The 50/30/20 rule splits take-home pay into needs, wants, and saving or paying down debt.", a:true, why:"True. It's a simple starting point: about 50% needs, 30% wants, 20% savings and debt. Adjust it to your life."},
  {q:"Rent-to-own furniture and electronics usually cost much more in total than buying the item outright.", a:true, why:"True. Weekly payments add up, and the total can be far more than the store price. Saving first usually costs less."},
  // ---- Credit ----
  {q:"Checking your own credit report lowers your credit score.", a:false, why:"False. Checking your own report is a soft inquiry and doesn't hurt your score."},
  {q:"You can get free credit reports from Equifax, Experian, and TransUnion at AnnualCreditReport.com.", a:true, why:"True. It's the official free site. Check for accounts you don't recognize."},
  {q:"Closing your oldest credit card always raises your credit score.", a:false, why:"False. It can lower your available credit and shorten your history, which may lower your score."},
  {q:"Using a smaller share of your credit limit usually helps your credit score.", a:true, why:"True. Keeping your balance low compared to your limit (your utilization) is good for your score."},
  {q:"Paying on time is one of the biggest parts of your credit score.", a:true, why:"True. Payment history is the largest factor in common scoring models. Autopay for at least the minimum helps."},
  {q:"Your income is part of your credit score.", a:false, why:"False. Credit scores don't include income. Lenders may ask about income separately."},
  {q:"Freezing your credit costs a fee at each credit bureau.", a:false, why:"False. Credit freezes and unfreezes are free by federal law."},
  {q:"Using a debit card builds your credit history.", a:false, why:"False. Debit cards take money from your bank account, so they don't show up on credit reports."},
  {q:"Paying only the minimum on a credit card can take years to pay off and cost a lot in interest.", a:true, why:"True. Most of a minimum payment can go to interest. Try the credit card calculator in First credit card."},
  {q:"A 0% intro APR on a credit card lasts as long as you keep the card.", a:false, why:"False. Intro rates end after a set time, then the regular APR applies to any balance left."},
  {q:"Common FICO credit scores range from 300 to 850.", a:true, why:"True. Higher is better. Different lenders may use different score versions."},
  {q:"A secured credit card usually needs a deposit that becomes your credit limit.", a:true, why:"True. Used well and paid on time, it can build credit, and many let you graduate to a regular card."},
  {q:"Opening several new credit cards at once can lower your score for a while.", a:true, why:"True. Each application can add a hard inquiry, and new accounts lower your average account age."},
  {q:"Being added as an authorized user on someone's card can help build your credit history.", a:true, why:"True, if the card is reported and the owner pays on time. Their late payments can hurt you too, so pick carefully."},
  {q:"Getting married combines your credit scores into one shared score.", a:false, why:"False. Everyone keeps their own credit report and score. Joint accounts do show up on both reports."},
  {q:"Buy now, pay later plans never charge fees.", a:false, why:"False. Many charge late fees, and missed payments can hurt your credit or lead to collections."},
  {q:"Payday loans can cost the same as an APR of several hundred percent.", a:true, why:"True. A fee that looks small for two weeks adds up to a very high yearly rate. A credit union small-dollar loan usually costs far less."},
  {q:"Student loans are easy to wipe out in bankruptcy.", a:false, why:"False. Student loans are very hard to discharge in bankruptcy. Federal loans offer other help, like income-driven repayment."},
  // ---- Paychecks and taxes ----
  {q:"Your gross pay is the amount that lands in your bank account.", a:false, why:"False. Gross pay is before taxes and deductions. Take-home (net) pay is what you actually get."},
  {q:"Social Security and Medicare taxes (FICA) come out of most paychecks.", a:true, why:"True. Employees usually pay 7.65% of wages, and employers pay a matching amount."},
  {q:"Your W-4 form tells your employer how much federal tax to take out of your paycheck.", a:true, why:"True. Update it after big changes like marriage, a second job, or a new baby."},
  {q:"A big tax refund means the government gave you free money.", a:false, why:"False. A refund is usually your own money you overpaid during the year, given back without interest."},
  {q:"Moving into a higher tax bracket means all of your income is taxed at the higher rate.", a:false, why:"False. Only the dollars above the bracket line are taxed at the higher rate. A raise never lowers your take-home pay because of brackets."},
  {q:"Gig and freelance workers usually have no taxes taken out, so they may need to pay estimated taxes during the year.", a:true, why:"True. Setting aside part of each payment for taxes helps avoid a big bill and penalties."},
  {q:"Self-employed workers pay 15.3% self-employment tax for Social Security and Medicare.", a:true, why:"True. They pay both the worker and employer parts. Half of it can be deducted on the tax return."},
  {q:"Kentucky has a flat state income tax rate.", a:true, why:"True. Kentucky uses one flat rate for everyone, 3.5% for 2026."},
  {q:"Kentucky charges its 6% sales tax on regular groceries.", a:false, why:"False. Most food bought to eat at home is exempt from Kentucky sales tax. Prepared food and many other items are taxed."},
  {q:"Kentucky taxes Social Security benefits.", a:false, why:"False. Kentucky doesn't tax Social Security, and it excludes up to $31,110 of pension income."},
  {q:"Some Kentucky cities and counties charge their own job (occupational) tax on top of state income tax.", a:true, why:"True. Where you work can add a local tax. Check your pay stub."},
  {q:"The IRS VITA program offers free tax help to many people with low to moderate incomes.", a:true, why:"True. VITA sites are often at libraries, schools, and community centers."},
  {q:"The Child Tax Credit can lower your federal taxes if you have qualifying children.", a:true, why:"True. Part of it can even be refunded if you owe little tax. See Having a kid."},
  // ---- Saving for retirement and investing ----
  {q:"An employer 401(k) match is extra money your employer adds when you save.", a:true, why:"True. Not saving enough to get the full match leaves free money on the table."},
  {q:"For 2026, people under 50 can put up to $24,500 into a 401(k).", a:true, why:"True. That's the IRS limit for 2026. People 50 and older can add catch-up contributions."},
  {q:"For 2026, the IRA contribution limit for people under 50 is $7,500.", a:true, why:"True. It's $7,500, plus a $1,100 catch-up for people 50 and older."},
  {q:"You can generally take out your Roth IRA contributions (not the earnings) anytime without tax or penalty.", a:true, why:"True. Earnings have more rules, but your own contributions can come out. It's still best to leave them growing."},
  {q:"Starting to save 10 years earlier can make a big difference, even with small amounts.", a:true, why:"True. Growth builds on growth over time. Try the growth calculator in Turning 18."},
  {q:"A diversified index fund can't lose money.", a:false, why:"False. Spreading money across many investments lowers some risk, but the whole market can still go down."},
  {q:"An investment that did great last year is guaranteed to do great this year.", a:false, why:"False. Past results don't guarantee future results."},
  {q:"SIPC protects you if your brokerage firm fails, not if your investments lose value.", a:true, why:"True. SIPC helps return missing cash and securities from a failed firm. Market losses aren't covered."},
  {q:"You can look up a broker's background and complaints for free on FINRA BrokerCheck.", a:true, why:"True. Always check before you hand anyone money to invest."},
  {q:"Promises of high returns with little or no risk are a common sign of investment fraud.", a:true, why:"True. Real investments with higher returns come with higher risk. Be very careful with \"guaranteed\" profits."},
  {q:"Social Security retirement checks are smaller if you start them before your full retirement age.", a:true, why:"True. Starting early permanently lowers the monthly amount. Waiting past full retirement age raises it."},
  {q:"For people born in 1960 or later, full retirement age for Social Security is 67.", a:true, why:"True. You can start as early as 62 with smaller checks."},
  {q:"Kentucky gives a tax break on pension and retirement income.", a:true, why:"True. Kentucky excludes up to $31,110 of pension and retirement income, and Social Security isn't taxed."},
  // ---- Health and insurance ----
  {q:"To put money in an HSA, you need a qualifying high-deductible health plan.", a:true, why:"True. For 2026, the limit is $4,400 for self-only coverage and $8,750 for family coverage."},
  {q:"Money left in an HSA disappears at the end of the year.", a:false, why:"False. HSA money rolls over and stays yours, even if you change jobs. That's different from many FSAs."},
  {q:"Money in a flexible spending account (FSA) may be lost if you don't use it by the plan's deadline.", a:true, why:"True. Many FSAs are \"use it or lose it,\" though some allow a small carryover or grace period."},
  {q:"You can usually stay on a parent's health plan until age 26.", a:true, why:"True. It doesn't matter if you're married, in school, or living on your own."},
  {q:"Losing your job's health coverage lets you sign up for a kynect plan outside open enrollment.", a:true, why:"True. It opens a 60-day special enrollment window. Moving, marriage, and a new baby do too."},
  {q:"Kentucky Medicaid and KCHIP only take applications during open enrollment.", a:false, why:"False. You can apply for Medicaid and KCHIP any time of year through kynect."},
  {q:"Once you reach your health plan's out-of-pocket maximum, the plan pays 100% of covered in-network costs for the rest of the year.", a:true, why:"True. Your monthly premium still counts separately. Try the bill splitter on the Insurance tab."},
  {q:"A deductible is the amount you pay before insurance starts paying.", a:true, why:"True. A higher deductible usually means a lower monthly price, so have savings to cover it."},
  {q:"Kentucky requires at least $10,000 of personal injury protection (PIP) on car insurance.", a:true, why:"True. PIP pays medical bills no matter who caused the crash, along with 25/50/25 liability."},
  {q:"Kentucky's minimum car insurance is enough to fully cover any serious crash.", a:false, why:"False. The minimums are low. A serious crash can cost far more, and you could owe the rest."},
  {q:"Standard homeowners and renters policies cover flood damage.", a:false, why:"False. Flood needs separate coverage, such as through the National Flood Insurance Program."},
  {q:"New National Flood Insurance Program policies usually take 30 days to start.", a:true, why:"True. Buy before a storm is in the forecast."},
  {q:"Renters insurance can cover your stuff even though your landlord has insurance on the building.", a:true, why:"True. The landlord's policy covers the building, not your belongings."},
  {q:"Term life insurance builds cash value like a savings account.", a:false, why:"False. Term life only pays if you die during the term. That's why it usually costs much less than whole life."},
  {q:"Gap insurance can pay the difference if your car is totaled and you owe more than it's worth.", a:true, why:"True. It's most useful with a small down payment or a long loan."},
  {q:"Medicare starts automatically at 65 for everyone, even people not getting Social Security yet.", a:false, why:"False. If you aren't getting Social Security, you usually need to sign up. Late Part B sign-up can mean a lifelong penalty."},
  // ---- College ----
  {q:"Pell Grants usually don't have to be paid back.", a:true, why:"True. Pell Grants are need-based federal grants. The maximum for 2026–27 is $7,395."},
  {q:"You have to file the FAFSA every year you want federal student aid.", a:true, why:"True. Kentucky CAP and KTG grants are first come, first served, so file early each year."},
  {q:"Federal and private student loans have the same borrower protections.", a:false, why:"False. Federal loans offer income-driven repayment and forgiveness programs that private loans usually don't."},
  {q:"Kentucky's KEES scholarship money is earned through high school grades and ACT or SAT scores.", a:true, why:"True. Each year's GPA earns money, plus a bonus for your best ACT or SAT score."},
  {q:"Public Service Loan Forgiveness requires 120 qualifying payments while working for a qualifying employer.", a:true, why:"True. Government and nonprofit jobs often count. Track your payments at StudentAid.gov."},
  {q:"Federal Work-Study helps students earn money through part-time jobs.", a:true, why:"True. You check the box for it on the FAFSA, and your school sets it up."},
  {q:"Moving to Kentucky automatically makes you an in-state student for tuition.", a:false, why:"False. Kentucky looks at domicile, and many rules use a 12-month test. Check with the school."},
  {q:"529 plan money can be used tax-free for qualified college costs like tuition.", a:true, why:"True. Kentucky's KY Saves 529 doesn't give a state tax deduction, but the growth is still tax-free for school."},
  {q:"Paying a company to find scholarships is the best way to get free money for college.", a:false, why:"False. Scholarship searches and the FAFSA are free. Fee-based \"guaranteed\" scholarship services are a common scam."},
  // ---- Housing ----
  {q:"You need a 20% down payment to buy a home.", a:false, why:"False. Many loans allow much less, like 3.5% for FHA or 0% for VA. Under 20% usually means mortgage insurance."},
  {q:"Private mortgage insurance (PMI) protects the lender, not you.", a:true, why:"True. It's a cost to you that protects the lender if you stop paying. It can usually be removed once you build enough equity."},
  {q:"Your lender must give you a Closing Disclosure at least 3 business days before you close on a mortgage.", a:true, why:"True. Compare it to your Loan Estimate and ask about any changes."},
  {q:"Closing costs on a home are usually just a small flat fee.", a:false, why:"False. They often run a few percent of the price. Try the home calculator on Plan the next one."},
  {q:"Kentucky's homestead exemption lowers property taxes for homeowners 65 or older or totally disabled.", a:true, why:"True. It took $49,100 off the taxable value for 2025–2026. Apply at your county PVA office."},
  {q:"In Kentucky, the buyer usually pays the real estate transfer tax.", a:false, why:"False. The seller usually pays it. It's $0.50 per $500 of value."},
  {q:"Kentucky law caps how big a security deposit can be.", a:false, why:"False. Kentucky has no cap. Read your lease, and take photos when you move in and out."},
  // ---- Cars ----
  {q:"A longer car loan always saves money because the monthly payment is lower.", a:false, why:"False. A longer loan usually means paying more interest in total. Try the loan calculator in Buying a car."},
  {q:"Getting preapproved for a car loan before you visit a dealer can help you compare offers.", a:true, why:"True. You'll know your rate, and you can see if the dealer can beat it."},
  {q:"Kentucky's minimum car liability limits are 25/50/25.", a:true, why:"True. That's $25,000 per person and $50,000 per crash for injuries, plus $25,000 for property damage."},
  // ---- Work and jobs ----
  {q:"Kentucky's minimum wage is $7.25 an hour, the same as the federal minimum.", a:true, why:"True. Some jobs, like tipped jobs, have different rules."},
  {q:"Veterans have to pay a company to file a VA disability claim.", a:false, why:"False. Accredited representatives, including Kentucky Department of Veterans Affairs staff, help for free."},
  {q:"Kentucky offers a tuition waiver at state schools for some spouses and children of eligible veterans.", a:true, why:"True. The Kentucky Department of Veterans Affairs runs it. Check the eligibility rules."},
  {q:"An ABLE account can let someone with a disability save without losing SSI, as long as the balance stays at $100,000 or less.", a:true, why:"True. The first $100,000 in an ABLE account doesn't count toward SSI's resource limit."},
  // ---- Scams ----
  {q:"The IRS might call and demand you pay right away with gift cards.", a:false, why:"False. The IRS doesn't demand gift cards, wire transfers, or crypto. Hang up."},
  {q:"If someone asks you to read back a code that was texted to you, it's probably a scam.", a:true, why:"True. That code unlocks your account. Real companies won't ask for it."},
  {q:"You can forward scam texts to 7726 (SPAM) to report them to your phone carrier.", a:true, why:"True. Then delete the text, and don't click its links."},
  {q:"Your bank might ask you to move your money into a \"safe account\" to protect it from fraud.", a:false, why:"False. Banks never ask that. It's a common scam. Call the number on the back of your card."},
  {q:"It's safe to deposit a stranger's check and send part of it back once the money shows up in your account.", a:false, why:"False. Fake checks can bounce days later, and you'll owe the bank the full amount."},
  {q:"Caller ID can be faked to look like your bank, the police, or a government office.", a:true, why:"True. Hang up and call back using a number you look up yourself."},
  {q:"You can report scams to the Kentucky Attorney General.", a:true, why:"True. Report at ag.ky.gov/scams or (888) 432-9257, and at ReportFraud.ftc.gov."}
];

/* =========================================================
   6. STATE, SAVE, OPEN
   ========================================================= */
const APP_ID = "ky-money-milestones";
const VERSION = 1;
function defaults(){
  return {
    profile:{name:"", age:"", county:"", occupation:"", school:"", move:"", moveState:"", worksUK:false, firstHome:false, kids:false, disability:false, veteran:false, serving:false, milFamily:false, firstTime:false},
    pay:{amount:"", freq:"biweekly"},
    bills:[{name:"Phone",amount:""},{name:"Car insurance",amount:""}],
    picked:{},          // milestone id -> true
    msAge:{},           // milestone id -> age the user expects
    checks:{},          // "id:index" -> true
    tools:{},           // milestone id -> {inputs}
    next:{milestone:"", date:""},
    items:[],           // planned purchases
    swipe:{apr:24, payment:100},
    home:{price:225000, downPct:3.5, closingPct:3, rate:6.5, years:30, ptax:0.85, ins:1800},
    quiz:{}             // index -> true/false answer
  };
}
let state = defaults();
let dirty = false;
let everSaved = false;
let currentTab = "about";

function setDirty(v){
  dirty = v;
  const s = document.getElementById("status");
  if(v){ s.textContent = "Unsaved changes"; s.className="status dirty"; }
  else { s.textContent = everSaved ? "All changes saved" : "Nothing to save yet"; s.className="status"+(everSaved?" saved":""); }
}

/* Saving creates ONE file that does two jobs:
   1. Double-click it and it opens as a readable plan (your info, milestones, advice, and numbers).
   2. Load it back here with Open to keep editing. Your data rides along inside it as plain data, not code.
   The saved file contains no scripts. */
function savePlan(){
  const data = Object.assign({}, state); delete data._open; delete data._guideQ;
  const payload = {app:APP_ID, version:VERSION, savedAt:new Date().toISOString(), data};
  const json = JSON.stringify(payload).replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026");
  const doc = reportDoc(json);
  const blob = new Blob([doc], {type:"text/html"});
  const a = document.createElement("a");
  const nm = (state.profile.name||"my").replace(/[^a-z0-9]+/gi,"-").toLowerCase().replace(/^-|-$/g,"") || "my";
  a.href = URL.createObjectURL(blob);
  a.download = nm + "-money-milestones-plan.html";
  document.body.appendChild(a); a.click(); a.remove();
  setTimeout(()=>URL.revokeObjectURL(a.href), 2000);
  everSaved = true; setDirty(false);
  toast("Saved to your downloads. Double-click the file to read your plan, or click Open here to keep editing.");
}

/* Build the readable saved plan */
function reportDoc(json){
  const p = state.profile, g = matchOccupation(p.occupation);
  const who = p.name ? esc(p.name)+"'s" : "Your";
  const css = document.querySelector("style").textContent;
  const staticBars = h => h.replace(/data-w="([\d.]+)"/g, 'style="width:$1%"');
  const freqLabel = {weekly:"every week",biweekly:"every 2 weeks",semimonthly:"twice a month",monthly:"once a month"}[state.pay.freq];
  const schools = {uk:"University of Kentucky",eku:"Eastern Kentucky University",bctc:"Bluegrass Community & Technical College",kctcs:"A KCTCS college",othercollege:"Another college",hs:"High school"};
  const TYPE_ICON = {}; QUAL_GROUPS.forEach(gr=>(gr.types||[]).forEach(t=>TYPE_ICON[t]=gr.icon));

  // About you: picture chips instead of a table
  const chip=(icon,txt)=> txt? `<span class="rchip">${ico(icon,"xs")}${txt}</span>`:"";
  const about = `<div class="rchips">
    ${chip("n18", p.age? "Age "+esc(p.age):"")}${chip("pin", p.county? esc(p.county)+" County":"")}
    ${chip("briefcase", p.occupation? esc(p.occupation)+(g?` <span class="hint">(${esc(g.label)})</span>`:""):"")}
    ${chip("cap", esc(schools[p.school]||""))}
    ${chip("paycheck", n(state.pay.amount)>0? `${money(n(state.pay.amount))} ${freqLabel} <span class="hint">(~${money(monthlyTakeHome())}/mo)</span>`:"")}
    ${chip("soldier", p.veteran?"Veteran":p.serving?"Serving now":p.milFamily?"Military family":"")}
    ${chip("truck", p.move? "Moving":"")}${chip("access", p.disability? "Disability in the family":"")}
    ${chip("house", p.firstHome? "First-time homebuyer":"")}
  </div>`;

  // one milestone = one picture card: key accounts as chips, the calculator picture, checklist progress
  const msReport = (m, sit)=>{
    const age = msAgeOf(m), t = m.tool? toolVals(m.id):null;
    const done = m.checklist.filter((c,i)=>state.checks[m.id+":"+i]).length, pct = m.checklist.length? done/m.checklist.length*100:0;
    const alerts = m.alerts(p)||[];
    const accts = m.learn.map(l=>{ const i=ACCT_INFO[l.name]||{}; const link=(i.links||[])[0];
      return `<div class="racct"><b>${link?`<a href="${esc(link[1])}">${esc(l.name)}</a>`:esc(l.name)}</b><span>${esc(l.what)}</span></div>`; }).join("");
    return `<section class="rms${sit?" sit":""}">
      <div class="rms-head">${ico(MS_ICON[m.id]||"book","lg")}<div style="flex:1">
        <div class="rms-age">${sit?"Your situation":age===999?"":"Age "+esc(age)}</div>
        <h3>${esc(m.title)}</h3><p>${esc(m.why)}</p></div>
        <div class="rms-prog" title="${done} of ${m.checklist.length} steps done"><b>${done}/${m.checklist.length}</b><span>steps done</span><i><u style="width:${pct}%"></u></i></div></div>
      <h4>${ico("book","xs")} Accounts and programs to look into</h4><div class="racct-grid">${accts}</div>
      ${t? `<h4>${ico("chart","xs")} ${esc(t.label)}</h4><div class="rtool">${staticBars(toolResult(m.id))}</div>`:""}
      <div class="rcols">
        <div><h4>${ico("receipt","xs")} Your checklist</h4><ul class="rcheck">${m.checklist.map((c,i)=>`<li class="${state.checks[m.id+":"+i]?"y":""}">${esc(c)}</li>`).join("")}</ul></div>
        <div>${alerts.length?`<h4>${ico("pin","xs")} Kentucky heads-up</h4><ul class="rheads">${alerts.map(a=>`<li>${a}</li>`).join("")}</ul>`:""}
          <h4>${ico("phone","xs")} Questions to ask</h4><ul class="rq">${m.questions.map(q=>`<li>${esc(q)}</li>`).join("")}</ul></div>
      </div></section>`;
  };
  const msHtml = pickedList().map(m=>msReport(m)).join("") || `<p class="muted">No milestones picked yet.</p>`;

  // next goal: one big progress picture
  const nm = MS_BY_ID[state.next.milestone];
  const cost=state.items.reduce((s2,i)=>s2+itemTotal(i),0), saved=state.items.reduce((s2,i)=>s2+n(i.saved),0);
  const gp = cost>0? Math.min(100, saved/cost*100):0;
  const items = state.items.map(it=>`<tr><td>${esc(it.name)}${it.url?`<div class="hint"><a href="${esc(it.url)}">${esc(storeName(it.url)||"Link")}</a></div>`:""}</td>
    <td class="num">${money(n(it.price),true)}</td><td>${it.tax==="sales"?"+6% sales tax":it.tax==="car"?"+6% car tax + fees":"No tax"}</td>
    <td class="num">${money(itemTotal(it),true)}</td><td class="num">${money(n(it.saved),true)}</td></tr>`).join("");
  const plan = (nm||state.items.length)? `<section class="rgoal">
      <div class="rms-head">${ico(nm?(MS_ICON[nm.id]||"piggy"):"piggy","lg")}<div style="flex:1">
        <div class="rms-age">Next goal${state.next.date?` · by ${esc(new Date(state.next.date+"T12:00").toLocaleDateString("en-US",{month:"long",day:"numeric",year:"numeric"}))}`:""}</div>
        <h3>${nm?esc(nm.title):"Saving goal"}</h3></div></div>
      ${cost>0?`<div class="rbig"><span><b>${money(saved)}</b> saved</span><span><b>${money(cost)}</b> real cost with Kentucky tax</span></div>
      <div class="rbar"><u style="width:${gp.toFixed(1)}%"></u></div><p class="hint" style="margin:4px 0 12px">${Math.round(gp)}% of the way there</p>`:""}
      <div>${planSummaryHtml()}</div>
      ${items? `<div class="rtable"><table style="margin-top:12px"><thead><tr><th>Item</th><th class="num">Price</th><th>Tax</th><th class="num">Real cost</th><th class="num">Saved</th></tr></thead><tbody>${items}</tbody></table></div>`:""}
      ${state.next.milestone==="home"? `<h4>${ico("house","xs")} Kentucky home cost estimate</h4>${homeHtml()}`:""}
      ${state.items.length? `<h4>${ico("card","xs")} Save for it, or put it on a card?</h4>${staticBars(swipeHtml())}`:""}
    </section>` : "";

  // programs: picture tiles
  const matches = PLACES.map(pl=>({pl, r:pl.test(p)})).filter(x=>x.r.length);
  const qual = matches.length? `<h2>Where you may qualify</h2><div class="rprog-grid">${matches.map(x=>`<div class="rprog">${ico(TYPE_ICON[x.pl.type]||"pin")}<div><b><a href="${esc(x.pl.url)}">${esc(x.pl.name)}</a></b><span class="pill">${esc(x.pl.type)}</span><p>${esc(x.r[0])}</p></div></div>`).join("")}</div>`:"";

  const answered=Object.keys(state.quiz).length, right=Object.entries(state.quiz).filter(([k,v])=>QUIZ[+k]&&QUIZ[+k].a===v).length;
  const quiz = answered? `<h2>Myth-buster quiz</h2><section class="rgoal rquiz">${ico("book","lg")}<div style="flex:1"><div class="rbig"><span><b>${right} of ${answered}</b> right</span><span>${answered} of ${QUIZ.length} answered</span></div><div class="rbar"><u style="width:${(right/answered*100).toFixed(1)}%"></u></div></div></section>`:"";

  const savedOn = new Date().toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"});
  const rcss = `
  body{padding-bottom:90px} .reopen{font-size:14px;opacity:.85}
  .rchips{display:flex;flex-wrap:wrap;gap:8px}
  .rchip{display:inline-flex;align-items:center;gap:8px;background:var(--paper);border:1.5px solid var(--line);border-radius:999px;padding:6px 14px 6px 8px;font-size:15px}
  .rms,.rgoal{background:var(--paper);border:1.5px solid var(--line);border-left:6px solid var(--road);border-radius:16px;padding:18px 20px;margin:0 0 16px;break-inside:avoid}
  .rms.sit{border-left-color:var(--gold)}
  .rgoal{border-left-color:var(--gold);background:linear-gradient(180deg,#fffaf0,#fff)}
  .rms-head{display:flex;gap:16px;align-items:flex-start}
  .rms-head h3{margin:0 0 4px;font-size:22px}.rms-head p{margin:0;color:var(--muted)}
  .rms-age{font:800 12px/1 var(--body);letter-spacing:.08em;text-transform:uppercase;color:var(--gold-deep,#9a6b00);margin:4px 0 6px}
  .rms-prog{min-width:96px;text-align:center;display:flex;flex-direction:column;gap:2px}
  .rms-prog b{font:800 24px/1 var(--sign);color:var(--road)}.rms-prog span{font-size:12px;color:var(--muted)}
  .rms-prog i,.rbar{display:block;height:8px;background:#e6ede9;border-radius:4px;overflow:hidden;margin-top:4px}
  .rbar{height:14px;border-radius:7px}
  .rms-prog u,.rbar u{display:block;height:100%;background:linear-gradient(90deg,var(--road),#2f8a5f);text-decoration:none}
  .rms h4,.rgoal h4{display:flex;align-items:center;gap:8px;margin:16px 0 8px;font-size:16px}
  .racct-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:8px}
  .racct{background:#f4f8f6;border-radius:10px;padding:9px 12px;font-size:14px;line-height:1.4}
  .racct b{display:block;font-size:15px;margin-bottom:2px}.racct span{color:var(--muted)}
  .rtool{background:#f4f8f6;border-radius:12px;padding:12px 14px}
  .rcols{display:grid;grid-template-columns:1fr 1fr;gap:18px}
  .rcheck,.rq,.rheads{margin:0;padding:0;list-style:none;font-size:14.5px}
  .rcheck li{padding:4px 0 4px 28px;position:relative}
  .rcheck li::before{content:"";position:absolute;left:0;top:6px;width:16px;height:16px;border:2px solid #9fb3a8;border-radius:4px}
  .rcheck li.y{color:var(--muted);text-decoration:line-through}
  .rcheck li.y::before{background:var(--road);border-color:var(--road)}
  .rcheck li.y::after{content:"✓";position:absolute;left:4px;top:3px;color:#fff;font-size:13px;font-weight:800}
  .rq li,.rheads li{padding:4px 0 4px 18px;position:relative}
  .rq li::before{content:"?";position:absolute;left:0;font-weight:800;color:var(--road)}
  .rheads li::before{content:"";position:absolute;left:2px;top:12px;width:8px;height:8px;border-radius:50%;background:var(--gold)}
  .rbig{display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-top:14px;font-size:15px;color:var(--muted)}
  .rbig b{font:800 26px/1 var(--sign);color:var(--ink)}
  .rprog-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:10px;margin-bottom:16px}
  .rprog{display:flex;gap:12px;background:var(--paper);border:1.5px solid var(--line);border-radius:14px;padding:12px 14px;break-inside:avoid}
  .rprog .ico{width:44px;height:44px}.rprog b{display:block;margin-bottom:4px}.rprog p{margin:6px 0 0;font-size:14px;color:var(--muted)}
  .rquiz{display:flex;gap:16px;align-items:center}
  .rtable{overflow-x:auto}
  @media (max-width:640px){ .rcols{grid-template-columns:1fr} .rms-head{flex-wrap:wrap} }
  @media print{ .rms,.rgoal,.rprog{box-shadow:none} body{padding-bottom:0} footer.disclaimer{position:static} }`;
  return `<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>${who} money milestones plan</title><style>${css}${rcss}</style></head><body><main>
<section class="hero"><div class="hero-in">
  <h1>${who} money road</h1>
  <p>Saved ${esc(savedOn)} with KY Money Milestones.</p>
  <p class="private reopen">To change this plan, open the KY Money Milestones page, click <b>Open</b>, and pick this file.</p>
</div></section>
${summaryHtml(true)}
<h2>About you</h2>${about}
${plan? `<h2>Your next goal</h2>${plan}`:""}
${activeSituations().length?`<h2>Help for your situation</h2>${activeSituations().map(m=>msReport(m,true)).join("")}`:""}
<h2>Your milestones</h2>${msHtml}
${qual}${quiz}
<p class="hint">Facts last checked ${FACTS.checked}. Laws, limits, and program rules change, so check the official sources before you decide anything.</p>
</main>
<footer class="disclaimer" role="note"><div><b>For learning only.</b> This plan was made with an educational tool. It is not financial, investment, tax, or legal advice, and it does not recommend any specific investment. Neither Globefin nor the University of Kentucky endorses its calculations or conclusions.</div></footer>
<scr${""}ipt type="application/json" id="kymm-data">${json}<\/script>
</body></html>`.replace(/<details(?![^>]*\bopen\b)/g,"<details open");
}

/* Validate a loaded file. Returns a clean state or throws a friendly message. */
function cleanLoaded(obj){
  if(!obj || typeof obj!=="object") throw "That file isn't a plan file.";
  if(obj.app!==APP_ID) throw "That file wasn't made by KY Money Milestones.";
  if(typeof obj.version!=="number" || obj.version>VERSION) throw "That plan was made with a newer version of this page.";
  const d = obj.data;
  if(!d || typeof d!=="object" || !d.profile || typeof d.profile!=="object") throw "That plan file is damaged or incomplete.";
  const s = defaults();
  const str = v => (typeof v==="string" ? v.slice(0,500) : (typeof v==="number" && isFinite(v) ? String(v) : ""));
  const bool = v => v===true;
  const numOr = (v,f) => (typeof v==="number" && isFinite(v)) ? v : (typeof v==="string" && v.trim()!=="" && isFinite(+v) ? +v : f);
  for(const k of ["name","age","county","occupation","school","moveState"]) s.profile[k]=str(d.profile[k]);
  if(MOVE_TYPES.some(([v])=>v===d.profile.move)) s.profile.move=d.profile.move;
  for(const k of ["worksUK","firstHome","kids","disability","veteran","serving","milFamily","firstTime"]) s.profile[k]=bool(d.profile[k]);
  if(d.pay && typeof d.pay==="object"){ s.pay.amount=str(d.pay.amount); if(["weekly","biweekly","semimonthly","monthly"].includes(d.pay.freq)) s.pay.freq=d.pay.freq; }
  if(Array.isArray(d.bills)) s.bills = d.bills.slice(0,50).filter(b=>b&&typeof b==="object").map(b=>({name:str(b.name),amount:str(b.amount)}));
  if(d.picked && typeof d.picked==="object") for(const id in d.picked) if(MS_BY_ID[id] && !MS_BY_ID[id].situation && d.picked[id]===true) s.picked[id]=true;
  if(d.msAge && typeof d.msAge==="object") for(const id in d.msAge) if(MS_BY_ID[id]) s.msAge[id]=str(d.msAge[id]);
  if(d.checks && typeof d.checks==="object") for(const k in d.checks) if(/^[a-z0-9]+:\d+$/.test(k) && d.checks[k]===true) s.checks[k]=true;
  if(d.tools && typeof d.tools==="object") for(const id in d.tools){ if(!MS_BY_ID[id]||typeof d.tools[id]!=="object") continue; s.tools[id]={}; for(const k in d.tools[id]){ const v=numOr(d.tools[id][k],null); if(v!==null) s.tools[id][k]=v; } }
  if(d.next && typeof d.next==="object"){ if(MS_BY_ID[d.next.milestone]) s.next.milestone=d.next.milestone; if(typeof d.next.date==="string" && /^\d{4}-\d{2}-\d{2}$/.test(d.next.date)) s.next.date=d.next.date; }
  if(Array.isArray(d.items)) s.items = d.items.slice(0,100).filter(i=>i&&typeof i==="object").map(i=>({
    id: str(i.id)||uid(), name:str(i.name), url:safeUrl(str(i.url)), price:numOr(i.price,0), addedPrice:numOr(i.addedPrice,numOr(i.price,0)),
    addedOn: typeof i.addedOn==="string"? i.addedOn.slice(0,10):"", tax:["sales","car","none"].includes(i.tax)?i.tax:"sales", saved:numOr(i.saved,0)}));
  if(d.home && typeof d.home==="object") for(const k in s.home){ s.home[k]=numOr(d.home[k], s.home[k]); }
  if(d.swipe && typeof d.swipe==="object"){ s.swipe.apr=numOr(d.swipe.apr,24); s.swipe.payment=numOr(d.swipe.payment,100); }
  if(d.quiz && typeof d.quiz==="object") for(const k in d.quiz) if(QUIZ[+k] && typeof d.quiz[k]==="boolean") s.quiz[k]=d.quiz[k];
  return s;
}

function openFile(file){
  if(!file) return;
  if(file.size > 2*1024*1024){ toast("That file is too big to be a plan file. Your current plan wasn't changed.", true); return; }
  const r = new FileReader();
  r.onload = () => {
    let obj;
    try{
      let text = String(r.result).trim();
      if(text.charAt(0)!=="{"){   // a saved plan (.html): pull out the data block inside it
        const m = text.match(/<script type="application\/json" id="kymm-data">([\s\S]*?)<\/script>/);
        if(!m) throw 0;
        text = m[1];
      }
      obj = JSON.parse(text);
    }
    catch(e){ toast("We couldn't read that file. It isn't a valid plan file. Your current plan wasn't changed.", true); return; }
    try{
      const clean = cleanLoaded(obj);
      state = clean; everSaved = true; setDirty(false);
      render(); toast("Plan opened.");
    }catch(msg){
      toast((typeof msg==="string"?msg:"That file couldn't be opened.")+" Your current plan wasn't changed.", true);
    }
  };
  r.onerror = () => toast("We couldn't read that file. Your current plan wasn't changed.", true);
  r.readAsText(file);
}

/* =========================================================
   7. HELPERS
   ========================================================= */
function esc(s){ return String(s==null?"":s).replace(/[&<>"']/g,c=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[c])); }
function cap(s){ return s.replace(/\b\w/g,c=>c.toUpperCase()); }
function uid(){ return "i"+Math.random().toString(36).slice(2,9); }
function n(v){ const x = parseFloat(String(v).replace(/[$,]/g,"")); return isFinite(x)?x:0; }
function money(v, cents){ if(!isFinite(v)) return "too big to show"; return (v<0?"-":"")+"$"+Math.abs(v).toLocaleString("en-US",{minimumFractionDigits:cents?2:0,maximumFractionDigits:cents?2:0}); }
function safeUrl(u){ try{ const x=new URL(u); return (x.protocol==="https:"||x.protocol==="http:")? x.href : ""; }catch(e){ return ""; } }
function storeName(u){
  try{
    const h = new URL(u).hostname.replace(/^www\.|^m\.|^smile\./,"");
    const known = {"amazon.com":"Amazon","target.com":"Target","walmart.com":"Walmart","bestbuy.com":"Best Buy","ikea.com":"IKEA","wayfair.com":"Wayfair","costco.com":"Costco","homedepot.com":"Home Depot","lowes.com":"Lowe's","carmax.com":"CarMax","kroger.com":"Kroger","apple.com":"Apple","etsy.com":"Etsy","ebay.com":"eBay","samsclub.com":"Sam's Club","kohls.com":"Kohl's","macys.com":"Macy's","carvana.com":"Carvana","autotrader.com":"Autotrader","cars.com":"Cars.com","zillow.com":"Zillow","apartments.com":"Apartments.com"};
    return known[h] || cap(h.split(".").slice(-2,-1)[0]||h);
  }catch(e){ return ""; }
}
const PER_YEAR = {weekly:52, biweekly:26, semimonthly:24, monthly:12};
function monthlyTakeHome(){ return n(state.pay.amount) * PER_YEAR[state.pay.freq] / 12; }
function billsTotal(){ return state.bills.reduce((s,b)=>s+n(b.amount),0); }
function fv(monthly, ratePct, years){ const r=ratePct/100/12, k=Math.round(years*12); if(k<=0) return 0; return r===0? monthly*k : monthly*((Math.pow(1+r,k)-1)/r); }
function payment(P, ratePct, months){ const r=ratePct/100/12; if(months<=0) return 0; return r===0? P/months : P*r/(1-Math.pow(1+r,-months)); }
function payoff(balance, aprPct, pay){
  let b=balance, m=0, interest=0; const r=aprPct/100/12;
  if(b<=0) return {months:0, interest:0};
  if(pay <= b*r) return {months:Infinity, interest:Infinity};
  while(b>0.005 && m<1200){ const i=b*r; interest+=i; b=b+i-pay; m++; }
  return {months:m, interest:interest};
}
function itemTotal(it){ const p=n(it.price); if(it.tax==="sales") return p*(1+FACTS.kySalesTax); if(it.tax==="car") return p*(1+FACTS.kyCarTax)+FACTS.kyCarFees; return p; }
function paychecksUntil(dateStr){
  if(!dateStr) return 0;
  const end = new Date(dateStr+"T12:00:00"); const now = new Date();
  const days = (end-now)/86400000; if(days<=0) return 0;
  return Math.max(1, Math.floor(days/(365/PER_YEAR[state.pay.freq])));
}
/* Keep calculator inputs in a sensible range so odd entries can't break the math */
const CAPS = {years:80, delay:80, months:600, rate:100, rateA:100, rateB:100, apr:100, matchPct:100, yourPct:100, local:10, otherRate:20, otherLocal:10, oldCarTax:20, pmi:5, hours:168, wage:1000, saveMonths:600};
function clampTool(k, v){ v = isFinite(v) ? v : 0; if(v < 0) v = 0; const cap = CAPS[k] !== undefined ? CAPS[k] : 1e9; return Math.min(v, cap); }
function toolVals(id){ const m=MS_BY_ID[id]; const t=Object.assign({}, m.tool); const u=state.tools[id]||{}; for(const k in u) t[k]=clampTool(k, u[k]); return t; }
function activeSituations(){ return MILESTONES.filter(m=>m.situation && m.active(state.profile)); }
function pickedList(){ return MILESTONES.filter(m=>!m.situation && state.picked[m.id]).sort((a,b)=>msAgeOf(a)-msAgeOf(b)); }
function msAgeOf(m){ const v=state.msAge[m.id]; return v!==undefined && v!=="" ? n(v) : (m.age==null? 999 : m.age); }

let toastTimer=null;
function toast(msg, err){ const t=document.getElementById("toast"); t.textContent=msg; t.className="toast show"+(err?" err":""); clearTimeout(toastTimer); toastTimer=setTimeout(()=>t.className="toast", err?6500:3500); }

function ask(title, text){
  return new Promise(res=>{
    const bg=document.getElementById("modalBg");
    document.getElementById("modalTitle").textContent=title;
    document.getElementById("modalText").textContent=text;
    bg.style.display="flex";
    const yes=document.getElementById("modalYes"), no=document.getElementById("modalNo");
    const done=v=>{ bg.style.display="none"; yes.onclick=no.onclick=null; res(v); };
    yes.onclick=()=>done(true); no.onclick=()=>done(false); yes.focus();
  });
}


/* Road strip in the hero: your milestones as mile markers */
const SHORT = {teenjob:"First job",turn18:"Turn 18",card:"First card",college:"College",turn21:"Turn 21",car:"Car",moveout:"Move out",salary:"Salary job",married:"Married",home:"Home",kid:"Kid",disability:"ABLE",retire:"Retire plan",relocate:"Move",military:"Service"};
/* One age scale for the whole road, shared by the milestone signs and the gold AGE marker.
   Young ages get more room, since most milestones happen early: 18-25 fills about
   40% of the road, 25-35 about 20%, 35-50 about 15%, and 50-80 the rest. */
const ROAD_W=1000, ROAD_H=72, ROAD_Y=20;                 // asphalt from y=20 to 48
const ROAD_KNOTS=[[18,44],[25,420],[35,640],[50,800],[80,960]];
function ageToX(a){ a=Math.min(AGE_MAX,Math.max(AGE_MIN,a));
  for(let i=1;i<ROAD_KNOTS.length;i++){ const [a0,x0]=ROAD_KNOTS[i-1],[a1,x1]=ROAD_KNOTS[i]; if(a<=a1) return x0+(x1-x0)*(a-a0)/(a1-a0); }
  return ROAD_KNOTS[ROAD_KNOTS.length-1][1]; }
function xToAge(x){
  for(let i=1;i<ROAD_KNOTS.length;i++){ const [a0,x0]=ROAD_KNOTS[i-1],[a1,x1]=ROAD_KNOTS[i]; if(x<=x1) return Math.round(Math.max(AGE_MIN, a0+(a1-a0)*(x-x0)/(x1-x0))); }
  return AGE_MAX; }
function roadSvg(){
  const ticks=[18,20,25,30,35,40,50,60,70,80].map(a=>{ const x=Math.round(ageToX(a)); return `<line class="tk" x1="${x}" y1="${ROAD_Y+28}" x2="${x}" y2="${ROAD_Y+33}"/><text class="tick" x="${x}" y="${ROAD_Y+47}">${a}</text>`; }).join("");
  return `<div class="roadwrap"><div class="roadin"><svg class="road" viewBox="0 0 ${ROAD_W} ${ROAD_H}" role="img" aria-label="A road marked with ages from 18 to 80">
    <rect class="asphalt" x="0" y="${ROAD_Y}" width="${ROAD_W}" height="28" rx="4"/>
    <path class="center" d="M0 ${ROAD_Y+14} H${ROAD_W}"/>${ticks}</svg>${ageSlider()}</div></div>`;
}

/* Comparison bars + numbers that glide to their new value */
const lastVal = {};
function bars(key, rows){
  const max = Math.max(1, ...rows.map(r=>Math.abs(r.v)));
  return `<div class="bars">${rows.map((r,i)=>`<div class="barrow"><span class="k">${r.k}</span>
    <span class="track"><span class="fill ${r.c}" data-w="${(Math.abs(r.v)/max*100).toFixed(2)}" data-key="${key}-w${i}"></span></span>
    <span class="v" data-n="${r.v}" data-key="${key}-n${i}" data-suffix="${r.suffix||""}">${money(r.v)}${r.suffix||""}</span></div>`).join("")}</div>`;
}
const reduceMotion = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
function animateIn(root){
  root.querySelectorAll(".fill[data-w]").forEach(el=>{
    const k=el.dataset.key, to=+el.dataset.w, from = k in lastVal ? lastVal[k] : 0;
    el.style.width = from+"%"; lastVal[k]=to;
    if(reduceMotion){ el.style.width=to+"%"; return; }
    requestAnimationFrame(()=>requestAnimationFrame(()=>{ el.style.width=to+"%"; }));
  });
  root.querySelectorAll("[data-n]").forEach(el=>{
    const k=el.dataset.key, to=+el.dataset.n, from = k in lastVal ? lastVal[k] : 0, suf=el.dataset.suffix||"";
    lastVal[k]=to;
    if(reduceMotion || from===to){ el.textContent=money(to)+suf; return; }
    const t0=performance.now(), dur=550;
    const step=now=>{ const p=Math.min(1,(now-t0)/dur), e=1-Math.pow(1-p,3); el.textContent=money(from+(to-from)*e)+suf; if(p<1) requestAnimationFrame(step); };
    requestAnimationFrame(step);
  });
}

/* =========================================================
   ICONS AND PICTURE TILES. Original line drawings (no third-party art).
   Tap a picture to open its details, so each page shows less text at once.
   ========================================================= */
const ICONS = {
  soldier:`<path class="f" d="M17 29a15 15 0 0 1 30 0z"/><path d="M13 29h38"/><path d="M21 29v3a11 11 0 0 0 22 0v-3"/><path d="M11 59c2-10 10-15 21-15s19 5 21 15"/><path class="g" d="M32 46l2.2 4.6 5 .6-3.7 3.4 1 5-4.5-2.5-4.5 2.5 1-5-3.7-3.4 5-.6z"/>`,
  truck:`<rect x="5" y="18" width="34" height="24" rx="2"/><path d="M39 26h10l9 10v6H39z"/><path d="M12 30h12m-4-5 5 5-5 5"/><circle class="g" cx="17" cy="46" r="5"/><circle class="g" cx="48" cy="46" r="5"/>`,
  access:`<circle class="g" cx="32" cy="11" r="5"/><path d="M17 21l15 3 15-3"/><path d="M32 24v14"/><path d="M32 38l-8 18M32 38l8 18"/><circle cx="32" cy="32" r="28" stroke-dasharray="3 6"/>`,
  car:`<path d="M8 42v-9l7-13h34l7 13v9z"/><path d="M19 22l-4 10h34l-4-10z"/><circle class="g" cx="19" cy="44" r="6"/><circle class="g" cx="45" cy="44" r="6"/>`,
  house:`<path d="M7 32 32 10l25 22"/><path d="M14 27v28h36V27"/><rect class="g" x="27" y="38" width="10" height="17" rx="1"/><rect x="18" y="33" width="7" height="7"/>`,
  key:`<circle class="gs" cx="20" cy="32" r="11"/><circle cx="20" cy="32" r="4"/><path d="M31 32h26M49 32v9M56 32v7"/><path d="M8 54h48" stroke-dasharray="2 5"/>`,
  health:`<path d="M32 55S8 41 8 24a12 12 0 0 1 24-4 12 12 0 0 1 24 4c0 17-24 31-24 31z"/><path class="gs" stroke-width="5" d="M32 25v16M24 33h16"/>`,
  shield:`<path d="M32 6l22 8v16c0 14-10 24-22 28C20 54 10 44 10 30V14z"/><path class="g" d="M32 44s-11-6.5-11-14a5.5 5.5 0 0 1 11-2 5.5 5.5 0 0 1 11 2c0 7.5-11 14-11 14z"/>`,
  badge:`<path d="M32 6l22 8v16c0 14-10 24-22 28C20 54 10 44 10 30V14z"/><path class="g" d="M32 19l3.3 6.8 7.5 1-5.5 5.2 1.4 7.4L32 35.8l-6.7 3.6 1.4-7.4-5.5-5.2 7.5-1z"/>`,
  paycheck:`<rect x="6" y="16" width="52" height="32" rx="4"/><circle class="g" cx="32" cy="32" r="9"/><path d="M32 26v12M29 29h5a2 2 0 0 1 0 4h-4a2 2 0 0 0 0 4h5" stroke-width="2"/><path d="M50 52l6 6M56 52l-6 6" class="gs"/>`,
  water:`<path d="M5 44c6-6 11-6 17 0s11 6 17 0 11-6 17 0"/><path d="M5 54c6-6 11-6 17 0s11 6 17 0 11-6 17 0"/><path class="g" d="M32 6s-10 12-10 19a10 10 0 0 0 20 0c0-7-10-19-10-19z"/>`,
  medicare:`<rect x="8" y="14" width="48" height="36" rx="4"/><path d="M8 24h48"/><circle class="g" cx="22" cy="37" r="6"/><path d="M34 34h14M34 41h10"/>`,
  receipt:`<path d="M16 6h32v52l-5-4-5 4-6-4-6 4-5-4-5 4z"/><path d="M23 18h18M23 27h18M23 36h11"/><circle class="g" cx="41" cy="44" r="4"/>`,
  phone:`<rect x="18" y="5" width="28" height="54" rx="5"/><path d="M28 52h8"/><path class="g" d="M24 15h20a3 3 0 0 1 3 3v10a3 3 0 0 1-3 3H33l-6 5v-5h-3a3 3 0 0 1-3-3V18a3 3 0 0 1 3-3z"/>`,
  bank:`<path class="f" d="M7 24 32 9l25 15z"/><path d="M13 29v19M24 29v19M40 29v19M51 29v19"/><path d="M7 53h50"/><circle class="g" cx="32" cy="38" r="5"/>`,
  briefcase:`<rect x="7" y="20" width="50" height="34" rx="4"/><path d="M24 20v-6h16v6"/><path d="M7 34h50"/><rect class="g" x="28" y="30" width="8" height="8" rx="1"/>`,
  voice:`<circle cx="22" cy="24" r="10"/><path d="M6 56c2-11 8-16 16-16s14 5 16 16"/><path class="gs" d="M42 16a12 12 0 0 1 0 16M49 10a21 21 0 0 1 0 28"/>`,
  chart:`<path d="M9 55h46M9 55V9"/><path d="M15 46l11-12 8 8 15-19"/><path class="gs" d="M41 23h8v8"/>`,
  cap:`<path class="f" d="M4 25 32 13l28 12-28 12z"/><path d="M16 31v11c0 5 32 5 32 0V31"/><path class="gs" d="M56 27v14"/><circle class="g" cx="56" cy="44" r="3"/>`,
  cart:`<path d="M5 11h8l6 30h31l6-20H17"/><circle class="g" cx="24" cy="50" r="5"/><circle class="g" cx="45" cy="50" r="5"/>`,
  piggy:`<ellipse cx="30" cy="36" rx="21" ry="15"/><path d="M48 31h7v9h-6"/><path d="M19 22l-3-8 9 5"/><path d="M20 49v6M38 49v6"/><path d="M25 27h10"/><circle class="g" cx="30" cy="11" r="6"/>`,
  card:`<rect x="5" y="15" width="54" height="36" rx="4"/><path d="M5 25h54" stroke-width="5"/><rect class="g" x="12" y="33" width="11" height="8" rx="1.5"/><path d="M33 41h17"/>`,
  pin:`<path d="M32 59S13 38 13 25a19 19 0 0 1 38 0c0 13-19 34-19 34z"/><circle class="g" cx="32" cy="25" r="7"/>`,
  sun:`<path d="M6 46h52"/><path class="g" d="M17 46a15 15 0 0 1 30 0z"/><path d="M32 18v-7M14 28l-5-5M50 28l5-5M9 38H3M61 38h-6"/><path d="M14 54h36" stroke-dasharray="3 5"/>`,
  rings:`<circle cx="25" cy="36" r="14"/><circle class="gs" cx="39" cy="36" r="14"/><path class="g" d="M25 14l4-6h-8z"/>`,
  family:`<circle cx="21" cy="17" r="7"/><circle cx="43" cy="17" r="7"/><path d="M8 56c0-15 5-25 13-25s13 10 13 25"/><path d="M30 56c0-15 5-25 13-25s13 10 13 25"/><circle class="g" cx="32" cy="41" r="5"/>`,
  book:`<path d="M32 14C24 9 14 9 6 12v40c8-3 18-3 26 2 8-5 18-5 26-2V12c-8-3-18-3-26 2z"/><path d="M32 14v40"/><path class="gs" d="M13 22h12M13 30h12M39 22h12"/>`,
  n18:`<circle cx="32" cy="32" r="26"/><text x="32" y="41" text-anchor="middle" font-size="25" font-weight="800" class="t">18</text>`,
  n21:`<circle cx="32" cy="32" r="26"/><text x="32" y="41" text-anchor="middle" font-size="25" font-weight="800" class="t">21</text>`,
  apron:`<path d="M22 8h20v10l8 4v34H14V22l8-4z"/><rect class="g" x="24" y="34" width="16" height="10" rx="2"/><path d="M14 22h36"/>`
};
function ico(name, cls){ return `<svg viewBox="0 0 64 64" class="ico ${cls||""}" aria-hidden="true" focusable="false">${ICONS[name]||ICONS.book}</svg>`; }
const MS_ICON = {teenjob:"apron",turn18:"n18",card:"card",college:"cap",turn21:"n21",car:"car",moveout:"key",salary:"briefcase",married:"rings",home:"house",kid:"family",retire:"sun",disability:"access",relocate:"truck",military:"soldier"};

/* Which tile is open in each tile group. Not saved: it's just what's on screen. */
const uiTiles = {};
function tileGrid(group, items, openId){
  return `<div class="tiles" role="group">${items.map(x=>`<button type="button" class="tile${x.on?" on":""}" data-tile="${group}:${x.id}" aria-expanded="${openId===x.id}" aria-controls="panel-${group}">
    ${x.on?`<span class="badge">${esc(x.on===true?"For you":x.on)}</span>`:""}${ico(x.icon)}<span class="tl">${esc(x.label)}</span>${x.sub?`<span class="sub">${esc(x.sub)}</span>`:""}</button>`).join("")}</div>`;
}

/* =========================================================
   FIRST-MINUTE EXPERIENCE: example plan, summary, feature cards, nav steps
   ========================================================= */
function isEmptyPlan(){
  const p=state.profile;
  return !(p.name||p.age||p.county||p.occupation||p.school||p.move||p.veteran||p.serving||p.milFamily||p.disability||p.firstHome||p.kids||p.worksUK) && !Object.keys(state.picked).length && !state.items.length && !n(state.pay.amount);
}
function exampleState(){
  const s=defaults(), d=new Date(); d.setMonth(d.getMonth()+8);
  Object.assign(s.profile,{name:"Jordan", age:"22", county:"Fayette", occupation:"nurse", school:"uk", firstHome:true, firstTime:true});
  s.pay={amount:"1450", freq:"biweekly"};
  s.bills=[{name:"Rent",amount:"950"},{name:"Phone",amount:"65"},{name:"Car insurance",amount:"120"},{name:"Streaming",amount:"25"}];
  ["card","car","moveout","salary","home"].forEach(id=>s.picked[id]=true);
  s.checks={"card:0":true,"moveout:0":true};
  s.next={milestone:"car", date:d.toISOString().slice(0,10)};
  const today=new Date().toISOString().slice(0,10);
  s.items=[{id:uid(), name:"Used car", url:"", price:14500, addedPrice:14500, addedOn:today, tax:"car", saved:2500},
           {id:uid(), name:"First 6 months of car insurance", url:"", price:900, addedPrice:900, addedOn:today, tax:"none", saved:0}];
  return s;
}
function summaryStats(){
  const p=state.profile, picked=pickedList();
  const sits=activeSituations(), all=[...picked,...sits];
  const total=all.reduce((s,m)=>s+m.checklist.length,0), done=all.reduce((s,m)=>s+m.checklist.filter((c,i)=>state.checks[m.id+":"+i]).length,0);
  const matches=PLACES.filter(pl=>pl.test(p).length).length;
  const cost=state.items.reduce((s,i)=>s+itemTotal(i),0), saved=state.items.reduce((s,i)=>s+n(i.saved),0), left=Math.max(0,cost-saved);
  const checks=paychecksUntil(state.next.date);
  const per = (left>0 && state.next.date && checks>0)? left/checks : null;
  return {picked:picked.length, done, total, matches, per, left};
}
function summaryHtml(forReport){
  const s=summaryStats(), p=state.profile;
  const who = p.name? esc(p.name)+"'s" : "Your";
  const stat=(go,big,label)=> forReport? `<div class="stat"><span class="big">${big}</span><span>${label}</span></div>`
    : `<button type="button" class="stat" data-go="${go}"><span class="big">${big}</span><span>${label}</span></button>`;
  return `<section class="summary" aria-label="${who} money road at a glance">
    <div class="stats">
      ${stat("timeline", s.picked, s.picked===1?"milestone ahead":"milestones ahead")}
      ${stat("plan", s.per!=null? money(s.per) : "Set a goal", s.per!=null? "to save each paycheck" : "for your next milestone")}
      ${stat("qualify", s.matches, s.matches===1?"program you may qualify for":"programs you may qualify for")}
      ${stat("timeline", s.total? `${s.done}/${s.total}`:"0", "checklist steps done")}
    </div></section>`;
}
const FEATURES = [
  {go:"plan", icon:"cart", t:"Paste a product page", s:"We find the price and add Kentucky's 6% tax"},
  {go:"plan", icon:"house", t:"Home cost and tax", s:"Closing cash, transfer tax, true monthly cost"},
  {go:"ins", icon:"health", t:"Insurance bill splitter", s:"See who pays a medical bill"},
  {go:"scams", icon:"phone", t:"Is this a scam?", s:"A 10-second red-flag check"}
];
function featuresHtml(){
  return `<h2>What you can do here</h2><div class="tiles feat">${FEATURES.map(f=>`<button type="button" class="tile" data-go="${f.go}">${ico(f.icon)}<span class="tl">${esc(f.t)}</span><span class="sub">${esc(f.s)}</span></button>`).join("")}</div>`;
}
/* little ✓ on each numbered step once it has something in it */
function updateNav(){
  const p=state.profile, done={
    about: !!(p.age||p.county||p.occupation||n(state.pay.amount)),
    timeline: Object.keys(state.picked).length>0,
    plan: !!state.next.milestone || state.items.length>0,
    qualify: PLACES.some(pl=>pl.test(p).length)
  };
  document.querySelectorAll("nav.tabs button[data-step]").forEach(b=>b.classList.toggle("done", !!done[b.dataset.tab]));
}

/* You may qualify: grouped picture tiles */
const QUAL_GROUPS = [
  {id:"mine", icon:"badge", label:"Your matches", types:null},
  {id:"cu", icon:"bank", label:"Credit unions", types:["Credit union"]},
  {id:"college", icon:"cap", label:"College", types:["College aid","College savings","Student loans"]},
  {id:"home", icon:"house", label:"Buying a home", types:["Homebuyer programs"]},
  {id:"mil", icon:"soldier", label:"Military", types:["Veteran benefits"]},
  {id:"health", icon:"health", label:"Health and disability", types:["Health insurance","ABLE account for disabilities"]},
  {id:"work", icon:"briefcase", label:"Work and retirement", types:["Public employee pension","Retirement plans for public workers","Teacher pension"]},
  {id:"ky", icon:"pin", label:"More Kentucky help", types:null}
];
const QUAL_KNOWN = new Set(QUAL_GROUPS.flatMap(g=>g.types||[]));
function qualList(gid){
  const p=state.profile, g=QUAL_GROUPS.find(x=>x.id===gid);
  return PLACES.map(pl=>({pl, reasons:pl.test(p)})).filter(x=>{
    if(gid==="mine") return x.reasons.length>0;
    if(gid==="ky") return !QUAL_KNOWN.has(x.pl.type);
    return g.types.includes(x.pl.type);
  }).sort((a,b)=>b.reasons.length-a.reasons.length);
}
function qualOpenId(){ return uiTiles.qual!==undefined? uiTiles.qual : "mine"; }
function qualPanel(){
  const id=qualOpenId(); if(!id) return `<p class="hint tile-hint">Tap a picture to see programs.</p>`;
  const list=qualList(id);
  if(!list.length) return id==="mine"
    ? `<div class="card muted">Fill in <b>About you</b> (county, school, job, or military status) to see what you may qualify for. Or tap a picture above to browse.</div>`
    : `<div class="card muted">Nothing in this group yet.</div>`;
  return list.map(x=>`<div class="card qcard"><div class="qhead"><h3 style="margin:0">${esc(x.pl.name)}</h3><span class="pill">${esc(x.pl.type)}</span></div>
    ${x.reasons.length? x.reasons.map(r=>`<div class="note good">✅ ${esc(r)}</div>`).join("") : `<p style="margin:6px 0">${esc(x.pl.maybe)}</p>`}
    <a href="${esc(x.pl.url)}" target="_blank" rel="noopener noreferrer">Check the official site</a></div>`).join("");
}

/* =========================================================
   AGE COMPARE: drag the gold marker along the road to see typical
   balances for households headed by someone that age.
   ALL figures: Federal Reserve 2025 Survey of Consumer Finances (released
   Oct 9, 2026; 2025 dollars). The SCF is the newest official source and comes
   out every 3 years; the next survey is 2028. Checked Nov 16, 2026.
   - Net worth: Fed report, Table 2.
   - Retirement accounts: median among families that have one (Fed SCF 2025,
     as tabulated from the public data by several analysts; matches the Fed's
     published 35-44 figure of $61,200).
   - Checking and checking + savings: Boldin analysis of 2025 SCF public data.
   No state-by-age numbers exist for Kentucky, so these are U.S. medians.
   Kentucky income: Census CPS ASEC 2025 (KY $73,750 vs U.S. $87,460).
   ========================================================= */
const AGE_DATA_SOURCE = "Federal Reserve 2025 Survey of Consumer Finances (released Oct 2026)";
const AGE_DATA = [
  {lo:18, hi:34, label:"under 35",     chk:1900, bank:5000,  ret:21000,  nw:33000},
  {lo:35, hi:44, label:"35 to 44",     chk:2400, bank:6600,  ret:61200,  nw:155600},
  {lo:45, hi:54, label:"45 to 54",     chk:3700, bank:9400,  ret:133000, nw:253700},
  {lo:55, hi:64, label:"55 to 64",     chk:3400, bank:10000, ret:239000, nw:411900},
  {lo:65, hi:74, label:"65 to 74",     chk:4000, bank:10000, ret:257000, nw:431300},
  {lo:75, hi:85, label:"75 and older", chk:5000, bank:14000, ret:257000, nw:504900}
];
const AGE_MIN=18, AGE_MAX=80;
function ageRow(a){ return AGE_DATA.find(r=>a>=r.lo && a<=r.hi) || AGE_DATA[AGE_DATA.length-1]; }
function ageStart(){ const a=parseInt(state.profile.age,10); return (a>=AGE_MIN && a<=AGE_MAX)? a : 25; }
function ageSlider(){
  const v=ageStart(), pct=ageToX(v)/ROAD_W*100;
  return `<input type="range" class="ageslide" id="ageSlide" min="${AGE_MIN}" max="${AGE_MAX}" step="1" value="${v}" aria-label="Pick an age to see typical savings, checking, and investments for that age" aria-describedby="agePop">
    <span class="agemark" id="ageMark" style="left:${pct}%" aria-hidden="true"><small>AGE</small><b>${v}</b></span>`;
}
function agePopHtml(a){
  const r=ageRow(a), mine=parseInt(state.profile.age,10)===a;
  const max=Math.max(r.chk,r.bank,r.ret,r.nw);
  const line=(k,v,star,cls)=>`<div class="ap-row"><span class="ap-k">${k}${star?"*":""}</span><span class="ap-v">${money(v)}</span><span class="ap-bar"><i class="${cls}" style="width:${Math.max(2,v/max*100).toFixed(1)}%"></i></span></div>`;
  return `<div class="ap-head"><b>Age ${a}${mine?" (you)":""}</b><span>Typical U.S. household, ${r.label}</span></div>
    ${line("Checking",r.chk,false,"c1")}
    ${line("Checking + savings",r.bank,false,"c2")}
    ${line("Retirement accounts",r.ret,true,"c3")}
    ${line("Net worth (all you own minus debts)",r.nw,false,"c4")}
    <p class="ap-note">Medians from the ${AGE_DATA_SOURCE}, the newest official data. *Among households that have one. Kentucky isn't broken out by age; its median household income was about 16% below the U.S. in 2025 (Census).</p>`;
}
function agePlace(){
  const s=document.getElementById("ageSlide"), mk=document.getElementById("ageMark"), pop=document.getElementById("agePop"), hero=s&&s.closest(".hero-in");
  if(!s||!mk||!pop||!hero) return;
  const a=+s.value, pct=ageToX(a)/ROAD_W*100;
  mk.style.left=pct+"%"; mk.querySelector("b").textContent=a;
  s.setAttribute("aria-valuetext", `Age ${a}`);
  pop.innerHTML=agePopHtml(a);
  const hr=hero.getBoundingClientRect(), mr=mk.getBoundingClientRect(), w=pop.offsetWidth||280;
  const cx=mr.left+mr.width/2-hr.left, left=Math.max(8, Math.min(hr.width-w-8, cx-w/2));
  pop.style.left=left+"px"; pop.style.setProperty("--arrow", (cx-left)+"px");
  // open above the marker, or below it if the sticky header would cover the top
  const head=document.querySelector("header"), headB=head? head.getBoundingClientRect().bottom : 0, ph=pop.offsetHeight||240;
  const below = mr.top - ph - 14 < headB;
  pop.classList.toggle("below", below);
  if(below){ pop.style.bottom="auto"; pop.style.top=(mr.bottom-hr.top+10)+"px"; }
  else { pop.style.top="auto"; pop.style.bottom=(hr.bottom-mr.top+10)+"px"; }
}
function ageShow(on){ const pop=document.getElementById("agePop"); if(!pop) return; if(on){ pop.hidden=false; agePlace(); } else pop.hidden=true; }

/* =========================================================
   8. RENDER
   ========================================================= */
function render(anim){
  document.querySelectorAll("nav.tabs button").forEach(b=>b.setAttribute("aria-selected", b.dataset.tab===currentTab?"true":"false"));
  const main=document.getElementById("main");
  const views={about:viewAbout, timeline:viewTimeline, plan:viewPlan, qualify:viewQualify, quiz:viewQuiz, guide:viewGuide, ins:viewInsurance, scams:viewScams, sources:viewSources};
  main.innerHTML = views[currentTab]();
  main.classList.remove("enter"); if(anim){ void main.offsetWidth; main.classList.add("enter"); }
  updateNav();
  refreshLive();
}


const SIT_TILES = [
  {id:"military", icon:"soldier", label:"Military and veterans", sub:"VA loans, tuition, taxes"},
  {id:"relocate", icon:"truck", label:"Moving to, from, or in KY", sub:"License, title, taxes"},
  {id:"disability", icon:"access", label:"Disability in the family", sub:"ABLE, benefits, taxes"}
];
function situationOpenId(){
  if(uiTiles.sit!==undefined) return uiTiles.sit;
  const a=activeSituations(); return a.length? a[0].id : null;
}
function situationPanel(){
  const id=situationOpenId(); if(!id) return `<p class="hint tile-hint">Tap a picture to see help for that situation.</p>`;
  const m=MS_BY_ID[id];
  const off = !m.active(state.profile);
  return (off?`<div class="note info">You haven't checked this one in About you, so this is the general version. Check the matching box above to tailor it.</div>`:"") + msCard(m,true);
}
function situationHtml(){
  const act=new Set(activeSituations().map(m=>m.id));
  return `<p class="hint">Tap a picture. <b>For you</b> means it matches what you checked above.</p>
  ${tileGrid("sit", SIT_TILES.map(t=>Object.assign({},t,{on:act.has(t.id)})), situationOpenId())}
  <div id="panel-sit" class="tile-panel">${situationPanel()}</div>`;
}

function viewAbout(){
  const p=state.profile; const g=matchOccupation(p.occupation);
  return `
  <section class="hero${isEmptyPlan()?"":" compact"}"><div class="hero-in">
    ${isEmptyPlan()? `<h1>See what's coming up on your money road</h1>
    <p>Kentucky accounts, programs, and savings plans for every big money moment, from turning 18 to buying a home.</p>` : `<h1>${p.name? esc(p.name)+"'s":"Your"} money road</h1>`}
    <div class="hero-cta no-print">
      ${isEmptyPlan()? `<button type="button" class="gold" id="btnExample">▶ Try an example</button>`:""}
      <button type="button" class="ghost" data-jump="aboutForm">${isEmptyPlan()?"Start with you":"Edit about you"}</button>
      <span class="private">🔒 Private. Nothing leaves your computer.</span>
    </div>
    ${roadSvg()}
    <p class="agehint no-print">↔ Drag the gold <b>AGE</b> marker to compare typical checking, savings, retirement, and net worth at any age.</p>
    <div class="agepop" id="agePop" role="status" aria-live="polite" hidden></div>
  </div></section>
  <div id="intro">${isEmptyPlan()? featuresHtml() : summaryHtml()}</div>

  <h2 id="aboutForm">About you</h2>
  <div class="card"><div class="grid">
    <div><label for="p-name">First name <span class="hint">(optional)</span></label><input id="p-name" type="text" data-bind="profile.name" value="${esc(p.name)}" autocomplete="off"></div>
    <div><label for="p-age">Your age</label><input id="p-age" type="number" min="10" max="100" data-bind="profile.age" value="${esc(p.age)}"></div>
    <div><label for="p-county">Kentucky county you live or work in</label><input id="p-county" type="text" list="counties" data-bind="profile.county" value="${esc(p.county)}" placeholder="e.g. Fayette">
      <datalist id="counties">${["Fayette","Jefferson","Franklin","Scott","Madison","Jessamine","Woodford","Clark","Bourbon","Boyle","Kenton","Boone","Campbell","Warren","Daviess","Hardin","Pike","Laurel","Christian","McCracken"].map(c=>`<option value="${c}">`).join("")}</datalist></div>
    <div><label for="p-occ">Your job, or the job you want</label><input id="p-occ" type="text" data-bind="profile.occupation" value="${esc(p.occupation)}" placeholder="e.g. nurse, teacher, barista">
      <div class="hint" id="occMatch" style="margin-top:4px">${g?`We'll show tips for: <b>${esc(g.label)}</b>`:"Type your job in everyday words."}</div></div>
    <div><label for="p-school">School you go to or went to</label><select id="p-school" data-bind="profile.school">
      ${[["","None or other"],["uk","University of Kentucky"],["eku","Eastern Kentucky University"],["bctc","Bluegrass Community & Technical College"],["kctcs","Another KCTCS college"],["othercollege","Another college"],["hs","High school (current)"]].map(([v,l])=>`<option value="${v}" ${p.school===v?"selected":""}>${l}</option>`).join("")}
    </select></div>
    <div><label for="p-move">Are you moving?</label><select id="p-move" data-bind="profile.move">
      ${MOVE_TYPES.map(([v,l])=>`<option value="${v}" ${p.move===v?"selected":""}>${l}</option>`).join("")}
    </select></div>
    <div><label for="p-mstate">The other state <span class="hint">(where you're going, coming from, or live)</span></label><input id="p-mstate" type="text" list="states" data-bind="profile.moveState" value="${esc(p.moveState)}" placeholder="e.g. Ohio">
      <datalist id="states">${["Ohio","Indiana","Tennessee","West Virginia","Virginia","Illinois","Missouri","Michigan","Wisconsin","Georgia","Florida","Texas","North Carolina","New York","California"].map(c=>`<option value="${c}">`).join("")}</datalist></div>
  </div>
  <div class="checks">
    <label class="check"><input type="checkbox" data-bind="profile.veteran" ${p.veteran?"checked":""}> I'm a veteran</label>
    <label class="check"><input type="checkbox" data-bind="profile.serving" ${p.serving?"checked":""}> I'm serving now (active duty, National Guard, or Reserve)</label>
    <label class="check"><input type="checkbox" data-bind="profile.milFamily" ${p.milFamily?"checked":""}> My spouse or parent is a veteran or service member</label>
    <label class="check"><input type="checkbox" data-bind="profile.worksUK" ${p.worksUK?"checked":""}> I work for the University of Kentucky</label>
    <label class="check"><input type="checkbox" data-bind="profile.firstHome" ${p.firstHome?"checked":""}> I'm thinking about buying a home</label>
    <label class="check"><input type="checkbox" data-bind="profile.firstTime" ${p.firstTime?"checked":""}> It would be my first home</label>
    <label class="check"><input type="checkbox" data-bind="profile.kids" ${p.kids?"checked":""}> I have kids or plan to</label>
    <label class="check"><input type="checkbox" data-bind="profile.disability" ${p.disability?"checked":""}> I or someone in my family has a disability that started before age 46</label>
  </div></div>

  <h2>Help for your situation</h2>
  <div id="situation">${situationHtml()}</div>

  <h2>Your paycheck</h2>
  <div class="card"><div class="grid">
    <div><label for="pay-amt">Take-home pay per paycheck <span class="hint">(what actually hits your bank account)</span></label><input id="pay-amt" type="number" min="0" step="1" data-bind="pay.amount" value="${esc(state.pay.amount)}" placeholder="e.g. 1100"></div>
    <div><label for="pay-freq">How often you get paid</label><select id="pay-freq" data-bind="pay.freq">
      ${[["weekly","Every week"],["biweekly","Every 2 weeks"],["semimonthly","Twice a month"],["monthly","Once a month"]].map(([v,l])=>`<option value="${v}" ${state.pay.freq===v?"selected":""}>${l}</option>`).join("")}
    </select></div>
  </div>
  <p class="hint">Not working yet? Leave it blank. You can still explore everything.</p></div>

  <div class="no-print" style="margin-top:18px"><button type="button" class="primary" data-go="timeline">Next: pick your milestones</button></div>`;
}

function viewTimeline(){
  const list = pickedList();
  const picker = MILESTONES.filter(m=>!m.situation).map(m=>`<label class="${state.picked[m.id]?"on":""}"><input type="checkbox" data-pick="${m.id}" ${state.picked[m.id]?"checked":""}> ${ico(MS_ICON[m.id],"sm")}<span>${esc(m.title)}</span></label>`).join("");
  const cards = list.map(m=>msCard(m)).join("");
  return `
  <h1>Your milestones</h1>
  <p class="lead">Check the moments coming up. Each one opens into short sections you can tap to expand.</p>
  <div class="ms-pick no-print">${picker}</div>
  <h2>Your timeline ${list.length?`<span class="pill">${list.length} milestone${list.length>1?"s":""}</span>`:""}</h2>
  ${list.length? `<div class="route">${cards}</div>` : `<div class="card muted">Pick at least one milestone above to build your timeline.</div>`}
  ${list.length? `<div class="no-print" style="margin-top:14px;display:flex;gap:10px;flex-wrap:wrap"><button type="button" class="primary" data-go="plan">Next: plan your next milestone</button><button type="button" data-print="1">Print my plan</button></div>`:""}`;
}

function msCard(m, sit){
  const p=state.profile;
  const ageVal = state.msAge[m.id]!==undefined ? state.msAge[m.id] : (m.age==null?"":m.age);
  const alerts = (m.alerts(p)||[]).map(a=>`<div class="note heads">⚠️ ${a}</div>`).join("");
  const learn = m.learn.map(l=>acctHtml(l)).join("");
  const checks = m.checklist.map((c,i)=>`<label class="check"><input type="checkbox" data-check="${m.id}:${i}" ${state.checks[m.id+":"+i]?"checked":""}> ${esc(c)}</label>`).join("");
  const done = m.checklist.filter((c,i)=>state.checks[m.id+":"+i]).length;
  const isOpen = sit ? !(state._open && state._open[m.id]===false) : (state._open && state._open[m.id]);
  return `<details class="ms${sit?" sit":""}" ${isOpen?"open":""} data-ms="${m.id}">
    ${sit?"":`<span class="marker" aria-hidden="true">`}${sit?"":`<span>${ageVal===""?"ANY<b>&nbsp;</b>":"AGE<b>"+esc(ageVal)+"</b>"}</span></span>`}
    <summary><span><span class="t">${esc(m.title)}</span><span class="progress"><i><em style="width:${done/m.checklist.length*100}%"></em></i><span class="pc">${done} of ${m.checklist.length} steps done</span></span></span><span class="chev">▶</span></summary>
    <div class="ms-body">
      <p>${esc(m.why)}</p>
      ${m.age!=null?`<div style="max-width:220px;margin-bottom:8px"><label>About what age for you?</label><input type="number" min="10" max="100" data-msage="${m.id}" value="${esc(ageVal)}"></div>`:""}
      <div class="secs">
      ${sec(m.id+":learn","book", sit?"Benefits, accounts, and programs":"Accounts and programs to know", m.learn.length, `<p class="hint" style="margin:0 0 6px">Tap any one for the pros, what to watch for, and trusted links.</p>${learn}`)}
      ${alerts? sec(m.id+":ky","pin","Kentucky heads-up", (m.alerts(p)||[]).length, alerts):""}
      ${m.tool? sec(m.id+":calc","chart", esc(toolVals(m.id).label), "", toolHtml(m).replace(/<h3>[^<]*<\/h3>/,"")):""}
      ${sec(m.id+":q","phone","Questions to ask", m.questions.length, `<ul style="margin:0">${m.questions.map(q=>`<li>${esc(q)}</li>`).join("")}</ul>`)}
      ${sec(m.id+":check","receipt","Your checklist", `<span class="ckc">${done}/${m.checklist.length}</span>`, checks)}
      </div>
    </div></details>`;
}

const TOOL_FIELDS = {
  growth:[["monthly","Save each month ($)"],["rate","Example yearly growth (%)"],["years","For how many years"],["delay","What if you wait (years)"]],
  card:[["balance","Card balance ($)"],["apr","Interest rate, APR (%)"],["payment","You pay each month ($)"]],
  loan:[["amount","Loan amount ($)"],["rateA","Rate offer A (%)"],["rateB","Rate offer B (%)"],["months","Months to pay"]],
  match:[["salary","Yearly salary ($)"],["matchPct","Employer matches up to (%)"],["yourPct","You put in (%)"]],
  upfront:[["rent","Monthly rent ($)"],["deposit","Security deposit ($)"],["utilities","Utility setup ($)"],["moving","Moving costs ($)"],["furniture","Furniture and basics ($)"]],
  down:[["price","Home price ($)"]],
  emergency:[["expenses","Your monthly must-pay costs ($)"],["months","Months of cushion"],["saveMonths","Months to build it"]],
  borrow:[["amount","Amount borrowed ($)"],["rate","Interest rate (%)"],["years","Years to pay back"]],
  paycheck:[["wage","Hourly pay ($)"],["hours","Hours per week"],["local","Local job tax where you work (%)"]],
  valoan:[["price","Home price ($)"],["rate","Interest rate (%)"],["pmi","Yearly mortgage insurance on the other loan (%)"]],
  relocate:[["salary","Yearly pay ($)"],["kyLocal","KY local job tax (%)"],["otherRate","Other state's income tax (%)"],["otherLocal","Other state's local tax (%)"],["moveCost","Moving costs ($)"],["carValue","Car trade-in value ($)"],["oldCarTax","Sales tax you paid on it (%)"]]
};
function fieldsFor(t){ const f=TOOL_FIELDS[t.type]; return (t.type==="relocate" && relocType()!=="coming")? f.filter(([k])=>k!=="carValue"&&k!=="oldCarTax") : f; }
function toolHtml(m){
  const t=toolVals(m.id);
  const fields = fieldsFor(t).map(([k,l])=>`<div><label>${l}</label><input type="number" step="any" data-tool="${m.id}.${k}" value="${esc(t[k])}"></div>`).join("");
  return `<div class="tool" data-toolbox="${m.id}"><h3>${esc(t.label)}</h3><div class="grid">${fields}</div><div class="result" id="out-${m.id}"></div>
  ${t.type==="growth"?`<div class="hint" style="margin-top:6px">Growth rate is only an example so you can see how time works. Real investments go up and down, and nothing is guaranteed.</div>`:""}</div>`;
}

function toolResult(id){
  const t=toolVals(id);
  if(t.type==="growth"){
    const now=fv(n(t.monthly),n(t.rate),n(t.years));
    const late=fv(n(t.monthly),n(t.rate),Math.max(0,n(t.years)-n(t.delay)));
    const putNow=n(t.monthly)*12*n(t.years), putLate=n(t.monthly)*12*Math.max(0,n(t.years)-n(t.delay));
    return bars(id,[{k:"Start now",v:now,c:"g"},{k:`Wait ${n(t.delay)} years`,v:late,c:"r"}])+
      `<p class="hint" style="margin:0">You'd put in ${money(putNow)} if you start now, or ${money(putLate)} if you wait. The rest is growth.</p>
      <p class="takeaway"><b>Waiting costs about ${money(now-late)}.</b> Time does a lot of the work, so starting small and early beats starting big and late.</p>`;
  }
  if(t.type==="card"){
    const r=payoff(n(t.balance),n(t.apr),n(t.payment));
    if(r.months===Infinity) return `<div class="note bad"><b>At ${money(n(t.payment))} a month, this balance never gets paid off.</b> The interest is bigger than your payment.</div>`;
    return bars(id,[{k:"Pay in full monthly",v:n(t.balance),c:"g"},{k:`Pay ${money(n(t.payment))}/mo`,v:n(t.balance)+r.interest,c:"r"}])+
      `<p class="takeaway"><b>Carrying the balance costs ${money(r.interest)} in interest</b> and takes ${r.months} months to pay off. Paying in full each month costs $0 extra.</p>`;
  }
  if(t.type==="loan"){
    const pa=payment(n(t.amount),n(t.rateA),n(t.months)), pb=payment(n(t.amount),n(t.rateB),n(t.months));
    const ia=pa*n(t.months)-n(t.amount), ib=pb*n(t.months)-n(t.amount);
    const lo = ia<=ib;
    return bars(id,[{k:`Interest at ${n(t.rateA)}%`,v:ia,c:lo?"g":"r"},{k:`Interest at ${n(t.rateB)}%`,v:ib,c:lo?"r":"g"}])+
      `<p class="hint" style="margin:0">Monthly payment: ${money(pa)} at ${n(t.rateA)}% vs ${money(pb)} at ${n(t.rateB)}%.</p>
      <p class="takeaway"><b>The lower rate saves you about ${money(Math.abs(ib-ia))}.</b> That's why it's worth getting quotes from a few places.</p>`;
  }
  if(t.type==="match"){
    const full=n(t.salary)*n(t.matchPct)/100, got=n(t.salary)*Math.min(n(t.yourPct),n(t.matchPct))/100, missed=Math.max(0,full-got);
    return bars(id,[{k:"Free money you get",v:got,c:"g",suffix:"/yr"},{k:"Free money you skip",v:missed,c:"r",suffix:"/yr"}])+
      (missed>0? `<p class="takeaway"><b>You're leaving ${money(missed)} a year on the table.</b> Putting in ${n(t.matchPct)}% would get you the full ${money(full)} a year.</p>`
      : `<p class="takeaway"><b>You're getting the full match: ${money(full)} a year in free money.</b></p>`);
  }
  if(t.type==="upfront"){
    const total=n(t.rent)+n(t.deposit)+n(t.utilities)+n(t.moving)+n(t.furniture);
    const mth=monthlyTakeHome(); let extra="";
    if(mth>0){ const share=n(t.rent)/mth*100; extra=`<div class="note ${share>40?"bad":share>30?"heads":"good"}">Rent would be <b>${share.toFixed(0)}%</b> of your take-home pay. ${share>40?"That's a lot. It may be hard to cover other bills.":share>30?"That's on the high side.":"That's a manageable share."}</div>`; }
    return `<div class="note info">Cash you need before moving in: <span class="big">${money(total)}</span></div>${extra}<p class="hint">Want to save for it? Go to <b>Plan the next one</b> to see how much per paycheck.</p>`;
  }
  if(t.type==="down"){
    const p=n(t.price);
    return `<table><tr><th>Down payment</th><th class="num">Cash</th></tr>
      <tr><td>3.5% (FHA loan minimum)</td><td class="num">${money(p*0.035)}</td></tr>
      <tr><td>5%</td><td class="num">${money(p*0.05)}</td></tr>
      <tr><td>20% (usually no mortgage insurance)</td><td class="num">${money(p*0.2)}</td></tr>
      <tr><td>Closing costs, rough guess (2% to 5%)</td><td class="num">${money(p*0.02)} to ${money(p*0.05)}</td></tr></table>
      <p class="hint">Your lender will give you exact numbers. These are rough guesses to help you plan.</p>`;
  }
  if(t.type==="emergency"){
    const goal=n(t.expenses)*n(t.months); const months=Math.max(1,n(t.saveMonths));
    const perPay = goal/(months*PER_YEAR[state.pay.freq]/12);
    return `<div class="note info">Your safety net goal: <span class="big">${money(goal)}</span></div><p>To build it in ${months} months, save about <b>${money(perPay)} per paycheck</b> (${money(goal/months)} a month).</p>`;
  }
  if(t.type==="paycheck"){
    const gross=n(t.wage)*n(t.hours)*2, fica=gross*0.0765, ky=gross*0.035, loc=gross*n(t.local)/100, net=gross-fica-ky-loc;
    return `<table><tr><td>Gross pay (2 weeks)</td><td class="num"><b>${money(gross,true)}</b></td></tr>
      <tr><td>Social Security and Medicare (7.65%)</td><td class="num">−${money(fica,true)}</td></tr>
      <tr><td>Kentucky income tax (about 3.5%)</td><td class="num">−${money(ky,true)}</td></tr>
      <tr><td>Local job tax (${n(t.local)}%)</td><td class="num">−${money(loc,true)}</td></tr>
      <tr><td>Federal income tax</td><td class="num">Set by your W-4</td></tr>
      <tr><td><b>Take-home before federal tax</b></td><td class="num"><b>${money(net,true)}</b></td></tr></table>`+
      bars(id,[{k:"Gross pay",v:gross,c:"y"},{k:"Take-home (before federal)",v:net,c:"g"}])+
      `<p class="hint" style="margin:0">Rough estimate. Kentucky tax here skips the standard deduction, so the real amount is usually a little lower. Local rates differ by city and county, so check your pay stub. Lexington and Louisville are a little over 2%, and many rural counties are 0%. Kentucky's minimum wage is $${FACTS.kyMinWage.toFixed(2)} an hour.</p>`;
  }
  if(t.type==="valoan"){
    const price=n(t.price), down=price*0.05, conv=price-down, mo=payment(price,n(t.rate),360), moc=payment(conv,n(t.rate),360), pmiMo=conv*n(t.pmi)/100/12;
    return bars(id,[{k:"Cash down, VA loan",v:0,c:"g"},{k:"Cash down, 5% loan",v:down,c:"r"}])+
      `<p class="takeaway"><b>A VA loan could keep ${money(down)} in your pocket at closing</b> and skip about ${money(pmiMo)} a month in mortgage insurance.</p>
      <p class="hint" style="margin:0">Rough monthly principal and interest: ${money(mo)} (VA, nothing down) vs. ${money(moc)} + ${money(pmiMo)} mortgage insurance (5% down). Same rate assumed. Doesn't include the VA funding fee, taxes, or homeowners insurance. Your lender gives real numbers.</p>`;
  }
  if(t.type==="relocate"){
    const sal=n(t.salary), ky=sal*(3.5+n(t.kyLocal))/100, ot=sal*(n(t.otherRate)+n(t.otherLocal))/100;
    const st = otherState()||"Other state";
    const carTax = relocType()==="coming"? n(t.carValue)*Math.max(0,6-n(t.oldCarTax))/100 : 0;
    const diff = ot-ky;
    let out = bars(id,[{k:"Kentucky",v:ky,c:ky<=ot?"g":"r",suffix:"/yr"},{k:esc(st),v:ot,c:ot<ky?"g":"r",suffix:"/yr"}])+
      `<p class="takeaway"><b>${Math.abs(diff)<1?"About the same state and local tax either way.":(diff>0?`Kentucky is about ${money(diff)} a year lower`:`${esc(st)} is about ${money(-diff)} a year lower`)}</b>${Math.abs(diff)<1?"":" in state and local income tax"} on ${money(sal)} of pay.</p>
      <p class="hint" style="margin:4px 0 0">Rough estimate: rates times your pay, with no deductions. ${noWageTax()&&n(t.otherRate)===0?`${esc(st)} doesn't tax wages, so we used 0%.`:`The other state's rate is only an example until you type in the real one from its revenue website.`} Rent, groceries, sales tax, and property tax matter too.</p>`;
    if(relocType()==="coming") out += `<div class="note heads">Estimated Kentucky car usage tax: <b>${money(carTax)}</b> (6% of ${money(n(t.carValue))}, minus credit for the ${n(t.oldCarTax)}% you paid before). Due when you title it, within 15 days.</div>`;
    out += `<div class="note info">Cash to plan for the move: <b>${money(n(t.moveCost)+carTax)}</b>. Add it in <b>Plan the next one</b> to see it per paycheck.</div>`;
    return out;
  }
  if(t.type==="borrow"){
    const mths=n(t.years)*12, pm=payment(n(t.amount),n(t.rate),mths), tot=pm*mths;
    return bars(id,[{k:"You borrow",v:n(t.amount),c:"y"},{k:"You pay back",v:tot,c:"r"}])+`<p class="takeaway"><b>${money(pm)} a month for ${n(t.years)} years</b>, which is ${money(tot-n(t.amount))} in interest.</p>
      <p>Every $1,000 you <i>don't</i> borrow saves about ${money(n(t.amount)>0?(tot-n(t.amount))/n(t.amount)*1000:0)} in interest.</p>`;
  }
  return "";
}

function viewPlan(){
  const list=pickedList();
  const planList = (list.length?list:MILESTONES.filter(m=>!m.situation)).concat(activeSituations().filter(m=>m.bundle.length));
  const opts = planList.map(m=>`<option value="${m.id}" ${state.next.milestone===m.id?"selected":""}>${esc(m.title)}</option>`).join("");
  const ms = MS_BY_ID[state.next.milestone];
  const rows = state.items.map(it=>{
    const changed = n(it.addedPrice)>0 && Math.abs(n(it.price)-n(it.addedPrice))>=0.01;
    const diff = n(it.price)-n(it.addedPrice);
    return `<tr data-item="${it.id}">
      <td><input type="text" data-item-f="name" value="${esc(it.name)}" aria-label="Item name">${it.url?`<div class="hint">🔗 <a href="${esc(it.url)}" target="_blank" rel="noopener noreferrer">${esc(storeName(it.url)||"Link")}</a>${it.addedOn?`, added ${esc(it.addedOn)}`:""}</div>`:""}
        ${changed?`<div class="hint" style="color:${diff<0?"var(--good)":"var(--bad)"}">${diff<0?"⬇ Price dropped":"⬆ Price went up"} ${money(Math.abs(diff),true)} since you added it</div>`:""}</td>
      <td style="width:120px"><input type="number" step="0.01" min="0" data-item-f="price" value="${esc(it.price)}" aria-label="Price"></td>
      <td style="width:185px"><select data-item-f="tax" aria-label="Tax">
        <option value="sales" ${it.tax==="sales"?"selected":""}>+6% KY sales tax</option>
        <option value="car" ${it.tax==="car"?"selected":""}>+6% KY car tax + fees</option>
        <option value="none" ${it.tax==="none"?"selected":""}>No tax (rent, fees, home costs)</option></select></td>
      <td class="num" data-item-total>${money(itemTotal(it),true)}</td>
      <td style="width:110px"><input type="number" step="0.01" min="0" data-item-f="saved" value="${esc(it.saved)}" aria-label="Already saved"></td>
      <td><button type="button" class="small" data-remove="${it.id}" aria-label="Remove ${esc(it.name)}">✕</button></td></tr>`;}).join("");
  const billRows = state.bills.map((b,i)=>`<div style="display:flex;gap:8px;margin:6px 0"><input type="text" data-bill="${i}.name" value="${esc(b.name)}" placeholder="Bill name" aria-label="Bill name"><input type="number" min="0" data-bill="${i}.amount" value="${esc(b.amount)}" placeholder="$ per month" style="max-width:150px" aria-label="Monthly amount"><button type="button" class="small" data-billdel="${i}" aria-label="Remove bill">✕</button></div>`).join("");

  return `
  <h1>Plan your next milestone</h1>
  <p class="lead">Add what you'll need to buy, and we'll show the real Kentucky cost and how much to save each paycheck.</p>

  <div class="card"><div class="grid">
    <div><label for="next-ms">Your next milestone</label><select id="next-ms" data-bind="next.milestone"><option value="">Choose one</option>${opts}</select></div>
    <div><label for="next-date">Target date</label><input id="next-date" type="date" data-bind="next.date" value="${esc(state.next.date)}"></div>
  </div>
  ${ms && ms.bundle.length?`<p style="margin-bottom:0"><button type="button" data-bundle="${ms.id}">+ Add a starter list for “${esc(ms.title)}”</button> <span class="hint">Example prices you can change.</span></p>`:""}
  </div>

  <h2>Add something you'll need to buy</h2>
  <div class="card">
    <div class="grid">
      <div><label for="add-url">Product link <span class="hint">(optional)</span></label><input id="add-url" type="url" placeholder="https://..."></div>
      <div><label for="add-name">What is it?</label><input id="add-name" type="text" placeholder="e.g. Couch"></div>
      <div><label for="add-price">Price ($)</label><input id="add-price" type="number" min="0" step="0.01" placeholder="e.g. 650"></div>
      <div><label for="add-tax">Tax</label><select id="add-tax"><option value="sales">+6% KY sales tax</option><option value="car">+6% KY car tax + fees</option><option value="none">No tax (rent, fees, home costs)</option></select></div>
    </div>
    <details class="paste" style="margin-top:12px"><summary>Don't want to type it? Paste the product page and we'll find the price</summary>
      <p class="hint">On the product page, press <b>Ctrl+A</b> then <b>Ctrl+C</b> (on a Mac, Cmd+A then Cmd+C). Then paste below. This all happens on your computer. We never visit the site.</p>
      <textarea id="paste-text" placeholder="Paste the product page here"></textarea>
      <div style="margin-top:8px"><button type="button" id="btnFind">Find the price</button></div>
      <div id="cands"></div>
    </details>
    <div style="margin-top:12px"><button type="button" class="primary" id="btnAdd">Add to my plan</button></div>
  </div>

  <h2>Your shopping list</h2>
  <div class="card" style="overflow-x:auto">
    ${state.items.length? `<table><thead><tr><th>Item</th><th>Price</th><th>Tax</th><th class="num">Real cost</th><th>Saved so far</th><th></th></tr></thead><tbody>${rows}</tbody></table>`
      : `<p class="muted" style="margin:0">Nothing here yet. Add an item above${ms&&ms.bundle.length?" or use the starter list":""}.</p>`}
  </div>

  <details class="card homecalc" ${state.next.milestone==="home"?"open":""}>
    <summary><h2 style="display:inline;margin:0;font-size:22px">🏠 Buying a home? Kentucky cost and tax calculator</h2></summary>
    <p class="hint" style="margin-top:10px">Kentucky has no sales tax on a home purchase. The costs to plan for are closing costs, property tax, homeowners insurance, and the state transfer tax (usually paid by the seller).</p>
    <div class="grid">
      ${[["price","Home price ($)"],["downPct","Down payment (%)"],["closingPct","Closing costs, estimate (%)"],["rate","Mortgage rate (%)"],["years","Loan length (years)"],["ptax","Property tax rate per year (%)"],["ins","Homeowners insurance per year ($)"]].map(([k,l])=>`<div><label for="hc-${k}">${l}</label><input id="hc-${k}" type="number" step="any" data-home="${k}" value="${esc(state.home[k])}"></div>`).join("")}
    </div>
    <div id="homeOut" class="result"></div>
    <p style="margin-bottom:0"><button type="button" id="btnHomeAdd">+ Add down payment and closing costs to my shopping list</button></p>
  </details>

  <h2>Can you afford it?</h2>
  <div class="grid" style="align-items:start">
    <div class="card"><h3>Your monthly bills</h3><p class="hint">Rent, phone, insurance, subscriptions. Anything you pay every month.</p>${billRows}<button type="button" class="small" id="btnAddBill">+ Add a bill</button></div>
    <div class="card" id="planSummary"></div>
  </div>

  <div class="secs" style="margin-top:22px">${sec("plan:swipe","card","Save for it, or put it on a card?","Compare",`<div class="grid">
    <div><label for="sw-apr">Credit card interest rate, APR (%)</label><input id="sw-apr" type="number" step="0.1" data-bind="swipe.apr" value="${esc(state.swipe.apr)}"></div>
    <div><label for="sw-pay">You'd pay each month ($)</label><input id="sw-pay" type="number" step="1" data-bind="swipe.payment" value="${esc(state.swipe.payment)}"></div>
  </div><div id="swipeOut" class="result"></div>`)}</div>`;
}


function homeHtml(){
  const h=state.home, p=state.profile;
  const price=Math.max(0,n(h.price)), down=price*Math.max(0,n(h.downPct))/100, loan=Math.max(0,price-down), closing=price*Math.max(0,n(h.closingPct))/100;
  const months=Math.max(1,Math.round(n(h.years)*12)), pi=payment(loan,Math.max(0,n(h.rate)),months);
  const homesteadOK = (+p.age>=65) || p.disability;
  const taxable = Math.max(0, price - (homesteadOK? FACTS.homestead : 0));
  const ptaxYr = taxable*Math.max(0,n(h.ptax))/100, insYr=Math.max(0,n(h.ins));
  const pmiMo = (n(h.downPct)<20 && !(p.veteran||p.serving)) ? loan*0.006/12 : 0;
  const monthly = pi + ptaxYr/12 + insYr/12 + pmiMo;
  const transfer = Math.ceil(price/500)*0.5;
  const mth = monthlyTakeHome();
  return `<table>
    <tr><td><b>Cash to close</b> (down payment + closing costs)</td><td class="num"><b>${money(down+closing)}</b></td></tr>
    <tr><td style="padding-left:18px">Down payment</td><td class="num">${money(down)}</td></tr>
    <tr><td style="padding-left:18px">Closing costs (estimate)</td><td class="num">${money(closing)}</td></tr>
    <tr><td>Kentucky transfer tax ($0.50 per $500, <b>usually paid by the seller</b>)</td><td class="num">${money(transfer)}</td></tr>
    <tr><td><b>Estimated monthly payment</b></td><td class="num"><b>${money(monthly)}</b></td></tr>
    <tr><td style="padding-left:18px">Principal and interest</td><td class="num">${money(pi)}</td></tr>
    <tr><td style="padding-left:18px">Property tax${homesteadOK?` (after the $${FACTS.homestead.toLocaleString()} homestead exemption)`:""}</td><td class="num">${money(ptaxYr/12)}</td></tr>
    <tr><td style="padding-left:18px">Homeowners insurance</td><td class="num">${money(insYr/12)}</td></tr>
    ${pmiMo?`<tr><td style="padding-left:18px">Mortgage insurance, rough guess (under 20% down)</td><td class="num">${money(pmiMo)}</td></tr>`:""}
    <tr><td>Property tax per year</td><td class="num">${money(ptaxYr)}</td></tr>
  </table>
  ${mth>0?`<div class="note ${monthly/mth>0.36?"bad":monthly/mth>0.28?"heads":"good"}">This payment would be <b>${(monthly/mth*100).toFixed(0)}%</b> of your take-home pay. ${monthly/mth>0.36?"That's a stretch for most budgets.":monthly/mth>0.28?"That's on the high side.":"That's a comfortable share for many budgets."}</div>`:`<p class="hint">Add your take-home pay in <b>About you</b> to see how this fits your budget.</p>`}
  <p class="hint" style="margin:0">Estimates only. Property tax rates differ by county and city; check your county PVA and sheriff's tax bill. ${homesteadOK?"":`If you're 65+ or totally disabled, Kentucky's homestead exemption lowers your property tax. `}${(p.veteran||p.serving)?"A VA loan may need no down payment and no mortgage insurance. ":""}Your lender gives you official numbers on a Loan Estimate.</p>`;
}
function planSummaryHtml(){
  const total=state.items.reduce((s,i)=>s+itemTotal(i),0), saved=state.items.reduce((s,i)=>s+n(i.saved),0), left=Math.max(0,total-saved);
  const checks=paychecksUntil(state.next.date);
  const mth=monthlyTakeHome(), bills=billsTotal();
  let html=`<h3>Your plan</h3><table>
    <tr><td>Real cost with Kentucky tax</td><td class="num"><b>${money(total,true)}</b></td></tr>
    <tr><td>Already saved</td><td class="num">${money(saved,true)}</td></tr>
    <tr><td>Still need</td><td class="num"><b>${money(left,true)}</b></td></tr></table>`;
  if(!state.items.length){ return html+`<p class="muted">Add items to see your plan.</p>`; }
  if(left<=0) return html+`<div class="note good">🎉 You've saved enough for everything on your list!</div>`;
  if(!state.next.date) return html+`<div class="note info">Pick a <b>target date</b> above to see how much to save each paycheck.</div>`;
  if(checks===0) return html+`<div class="note heads">Your target date has passed or is today. Pick a later date.</div>`;
  const per=left/checks, perMonth=per*PER_YEAR[state.pay.freq]/12;
  html+=`<div class="plan-total"><small>Save this much each paycheck</small><span class="big">${money(per,true)}</span><small>for the next ${checks} paycheck${checks>1?"s":""}</small></div>`;
  if(mth>0){
    const free=mth-bills;
    const share = free>0? perMonth/free*100 : Infinity;
    html+=`<table><tr><td>Monthly take-home</td><td class="num">${money(mth)}</td></tr><tr><td>Monthly bills</td><td class="num">−${money(bills)}</td></tr><tr><td>Left over each month</td><td class="num"><b>${money(free)}</b></td></tr><tr><td>Needed for this goal each month</td><td class="num">${money(perMonth)}</td></tr></table>`;
    if(free<=0) html+=`<div class="note bad">Your bills already use all your take-home pay. Look for a bill to cut or a later date.</div>`;
    else if(share>100) html+=`<div class="note bad">This goal needs more than you have left each month. Try a later date or a cheaper option.</div>`;
    else if(share>50) html+=`<div class="note heads">Doable, but it uses <b>${share.toFixed(0)}%</b> of what's left after bills. Tight but possible.</div>`;
    else html+=`<div class="note good">This fits! It uses <b>${share.toFixed(0)}%</b> of what's left after bills.</div>`;
  } else html+=`<p class="hint">Add your take-home pay in <b>About you</b> to see if it fits your budget.</p>`;
  return html;
}

function swipeHtml(){
  const total=state.items.reduce((s,i)=>s+itemTotal(i),0), saved=state.items.reduce((s,i)=>s+n(i.saved),0), left=Math.max(0,total-saved);
  if(left<=0) return `<p class="muted">Add items to your list to compare.</p>`;
  const r=payoff(left,n(state.swipe.apr),n(state.swipe.payment));
  if(r.months===Infinity) return `<div class="note bad">At ${money(n(state.swipe.payment))} a month, a ${money(left)} card balance <b>never gets paid off</b>. The interest is bigger than the payment.</div>`;
  return bars("swipe",[{k:"Save first, then buy",v:left,c:"g"},{k:"Put it on the card",v:left+r.interest,c:"r"}])+
    `<p class="takeaway"><b>Saving first keeps ${money(r.interest)} in your pocket.</b> On the card, it takes ${r.months} months to pay off.</p>`;
}

function viewQualify(){
  const tiles=QUAL_GROUPS.map(g=>{ const m=qualList(g.id), hits=m.filter(x=>x.reasons.length).length;
    return {id:g.id, icon:g.icon, label:g.label, sub: g.id==="mine"? `${hits} found` : `${m.length} program${m.length===1?"":"s"}`, on: g.id!=="mine" && hits? `${hits} for you` : false}; });
  return `<h1>You may qualify</h1>
  <p class="lead">Credit unions and Kentucky programs matched to <b>About you</b>. Tap a picture to browse.</p>
  ${tileGrid("qual", tiles, qualOpenId())}
  <div id="panel-qual" class="tile-panel">${qualPanel()}</div>
  <p class="hint">Listings aren't endorsements, and we don't rank or show rates because they change weekly. Always confirm on the official site. Last checked ${FACTS.checked}.</p>`;
}

/* Quiz: a round of 5 random questions from the bank; "More questions" draws 5 new ones */
const QUIZ_ROUND=5;
let quizRound=null;
function drawQuizRound(){
  const left=QUIZ.map((x,i)=>i).filter(i=>typeof state.quiz[i]!=="boolean");
  for(let i=left.length-1;i>0;i--){ const j=Math.floor(Math.random()*(i+1)); [left[i],left[j]]=[left[j],left[i]]; }
  quizRound=left.slice(0,QUIZ_ROUND);
}
function viewQuiz(){
  if(!quizRound || quizRound.some(i=>!QUIZ[i])) drawQuizRound();
  const answered=Object.keys(state.quiz).length;
  const right=Object.entries(state.quiz).filter(([k,v])=>QUIZ[+k] && QUIZ[+k].a===v).length;
  const roundDone=quizRound.length>0 && quizRound.every(i=>typeof state.quiz[i]==="boolean");
  const left=QUIZ.length-answered;
  return `<h1>Kentucky money myth-busters</h1><p class="lead">True or false? ${QUIZ.length} questions, ${QUIZ_ROUND} at a time.</p>
  <div class="quizbar"><div><b>${right} of ${answered}</b> right so far</div><div class="qprog" aria-label="${answered} of ${QUIZ.length} answered"><i style="width:${(answered/QUIZ.length*100).toFixed(1)}%"></i></div><div class="hint">${answered} of ${QUIZ.length} answered</div></div>
  ${left===0 && answered?`<div class="note good"><b>🎉 You've answered all ${QUIZ.length} questions</b> and got ${right} right. Start over to try again.</div>`:""}
  ${quizRound.length? quizRound.map((i,n)=>{ const x=QUIZ[i], a=state.quiz[i]; const has=typeof a==="boolean";
    const cls=v=> has&&a===v ? (a===x.a?"picked-right":"picked-wrong") : "";
    return `<div class="card qa"><b>${n+1}. ${esc(x.q)}</b><div class="opts"><button type="button" class="${cls(true)}" data-quiz="${i}:1">True</button><button type="button" class="${cls(false)}" data-quiz="${i}:0">False</button></div>
    ${has?`<div class="note ${a===x.a?"good":"bad"}">${a===x.a?"✅ Right!":"❌ Not quite."} ${esc(x.why)}</div>`:""}</div>`;}).join("")
    : `<div class="card"><b>🎉 You've answered all ${QUIZ.length} questions.</b> You got ${right} right. Start over to try again.</div>`}
  <div class="no-print" style="display:flex;gap:10px;flex-wrap:wrap;margin-top:12px">
    ${left>0?`<button type="button" class="${roundDone?"primary":""}" id="btnQuizMore">↻ More questions${roundDone?"":" (skip these)"}</button>`:""}
    ${answered?`<button type="button" id="btnQuizReset">Start the quiz over</button>`:""}
  </div>`;
}


const GUIDE_CATS = [["Banking and saving","bank","Banking"],["Taxes and paychecks","receipt","Taxes and pay"],["Investing","chart","Investing"],["Retirement","sun","Retirement"],["Education","cap","School"],["Health and family","health","Health and family"],["Credit and borrowing","card","Credit and loans"],["Military and veterans","soldier","Military"],["Kentucky programs and rules","pin","Kentucky rules"]];
function guideItems(){
  const seen=new Set(), items=[];
  const saveP=state.profile; state.profile=Object.assign({},saveP,{veteran:true,serving:true,milFamily:true});
  const allLearn = MILESTONES.map(m=>m.learn); state.profile=saveP;
  allLearn.forEach(ls=>ls.forEach(l=>{ const i=ACCT_INFO[l.name]; if(i && (i.pros||[]).length && !seen.has(l.name)){ seen.add(l.name); items.push({l,i}); } }));
  return items;
}
function guideListHtml(){
  const items=guideItems(), q=(state._guideQ||"").toLowerCase().trim(), cat=uiTiles.guide;
  if(!q && !cat) return '<p class="hint tile-hint">Tap a picture above, or search, to see accounts.</p>';
  const sections = GUIDE_CATS.map(([c])=>{ if(!q && cat!=="all" && cat!==c) return "";
    const list=items.filter(x=>x.i.cat===c && (!q || (x.l.name+" "+x.l.what).toLowerCase().includes(q)));
    return list.length? `<h2>${esc(c)}</h2>${list.map(x=>`<div class="card">${acctHtml(x.l,true)}</div>`).join("")}`:""; }).join("");
  return sections||'<p class="muted">Nothing matches that search.</p>';
}
function viewGuide(){
  const items=guideItems();
  const tiles=[...GUIDE_CATS.map(([c,i,short])=>({id:c, icon:i, label:short, sub:`${items.filter(x=>x.i.cat===c).length} topics`})),{id:"all",icon:"book",label:"Show everything",sub:`${items.length} topics`}];
  return `<h1>Account guide</h1>
  <p class="lead">Every account and program in one place. Tap one for pros, cautions, and trusted links.</p>
  ${tileGrid("guide", tiles, uiTiles.guide)}
  <div class="no-print" style="max-width:420px;margin:14px 0"><label for="gq">Or search the guide</label><input id="gq" type="text" data-guideq="1" value="${esc(state._guideQ||"")}" placeholder="e.g. Roth, brokerage, HSA"></div>
  <div class="note info">This guide explains account <b>types</b>. It doesn't recommend specific funds, stocks, or companies. Before you open an investment account, look the firm up on <a href="https://brokercheck.finra.org" target="_blank" rel="noopener noreferrer">FINRA BrokerCheck</a>.</div>
  <div id="guideList" class="tile-panel" aria-live="polite">${guideListHtml()}</div>`;
}

/* =========================================================
   SCAM WATCH. Trends checked Nov 3, 2026 (FTC, FBI, Kentucky agencies).
   The page can't fetch live news (it sends nothing online), so the
   "Get live updates" links point to official pages that update daily.
   ========================================================= */
const SCAM_LINKS = {
  ftcAlerts:["FTC consumer alerts (updated often)","https://consumer.ftc.gov/consumer-alerts"],
  report:["Report fraud to the FTC","https://reportfraud.ftc.gov"],
  ic3:["FBI Internet Crime Complaint Center","https://www.ic3.gov"],
  kyag:["Kentucky Attorney General: scams","https://ag.ky.gov/scams"],
  idt:["IdentityTheft.gov recovery plan","https://www.identitytheft.gov"],
  sec:["SEC investor alerts","https://www.investor.gov/introduction-investing/general-resources/news-alerts/alerts-bulletins"],
  aid:["StudentAid.gov (free federal aid help)","https://studentaid.gov"]
};
const SCAMS = [
  {icon:"phone", t:"Fake toll and traffic ticket texts", tag:"Trending in Kentucky", who:()=>true,
   how:"A text says you owe a small toll or an unpaid traffic ticket and links to a payment page. The page steals your card number.",
   ky:"In March 2026 the Kentucky Transportation Cabinet warned of ongoing fake texts about unpaid traffic tickets. It says real messages don't call it the \"DMV\" or \"DOT.\"",
   do:"Don't click. Forward the text to 7726 (SPAM), then delete it. Check what you really owe on the official website you type in yourself."},
  {icon:"bank", t:"Fake bank fraud alerts", tag:"Costly", who:()=>true,
   how:"A text or call that looks like your bank says there's fraud on your account and asks you to \"verify\" a code or move money to a \"safe\" account.",
   ky:"", do:"Banks never ask you to move money to protect it. Hang up and call the number on the back of your card."},
  {icon:"badge", t:"Government imposters (IRS, Social Security, FTC, police)", tag:"Trending in Kentucky", who:()=>true,
   how:"Someone claims to be from a government agency or the police and says you'll be arrested or fined unless you pay right now, often with gift cards, wire transfers, or crypto.",
   ky:"Kentucky's Attorney General warned after a Frankfort-area senior lost $30,000 to callers pretending to be the FTC. Kentucky State Police also warned in 2026 about texts falsely claiming to be from KSP.",
   do:"Government agencies don't demand gift cards, crypto, or wire transfers. Hang up and look up the agency's real number yourself."},
  {icon:"briefcase", t:"Fake jobs and \"task\" jobs", tag:"Big for students", who:p=>!p.age||+p.age<35||p.school,
   how:"An unexpected text or social media message offers easy remote work. With \"task\" jobs you rate apps or like videos, then must deposit money to \"unlock\" your pay. Others send a fake check and ask you to send part back.",
   ky:"", do:"Real employers don't make you pay to get paid, and the FTC says a job that pays you to like or rate content is illegal. Look the company up yourself and never deposit a check for a stranger."},
  {icon:"voice", t:"AI voice clones of family", tag:"New tech", who:()=>true,
   how:"A call sounds exactly like a family member in trouble, often after an accident or arrest, who needs money fast and asks you not to tell anyone.",
   ky:"", do:"Hang up and call the person back on a number you know. Pick a family code word ahead of time."},
  {icon:"chart", t:"Investment and crypto scams", tag:"Biggest losses", who:()=>true,
   how:"A new online friend, a group chat \"professor,\" or a slick website promises big, guaranteed returns, usually in crypto. Your account shows gains, but you can never withdraw.",
   ky:"", do:"Guaranteed high returns are a red flag. Check the person or firm on FINRA BrokerCheck and Investor.gov before you invest anything."},
  {icon:"cap", t:"Scholarship and student loan scams", tag:"Big for students", who:p=>!p.age||+p.age<30||p.school,
   how:"Companies charge fees to \"find\" scholarships, fill out the FAFSA, or get your student loans forgiven.",
   ky:"Kentucky's Attorney General has warned about loan repayment companies charging for services that are free.",
   do:"The FAFSA is free. Federal loan repayment help is free at StudentAid.gov. Never pay for a scholarship."},
  {icon:"house", t:"Home closing wire fraud", tag:"Homebuyers", who:p=>p.firstHome||p.firstTime,
   how:"Right before closing, an email that looks like it's from your lender or title company says the wiring instructions changed.",
   ky:"", do:"Always call your title company at a number you already know before wiring money. Changed instructions by email are a huge red flag."},
  {icon:"soldier", t:"Veteran benefit scams", tag:"Veterans", who:p=>p.veteran||p.milFamily||p.serving,
   how:"Someone charges a fee to help with a VA claim or offers cash now for your future pension or benefits.",
   ky:"", do:"Kentucky Department of Veterans Affairs benefits representatives help for free. Never sign over future benefits."},
  {icon:"cart", t:"Fake online stores and marketplace overpayments", tag:"Shopping", who:()=>true,
   how:"Deals that seem too good to be true on social media ads, or a buyer who \"accidentally\" overpays you and asks for the difference back.",
   ky:"", do:"Use a credit card for online purchases (it's easier to dispute charges), research new stores, and never refund an overpayment until the money has fully cleared."}
];
const FLAGS = [
  ["It came out of nowhere (a text, call, email, or DM I didn't expect)",1],
  ["It says I have to act right now, or something bad happens",2],
  ["It wants payment by gift card, wire transfer, crypto, or a payment app",3],
  ["It asks for a code that was texted to me, or my password",3],
  ["It has a link or QR code to pay or \"verify\"",2],
  ["It promises easy money, a prize, or guaranteed returns",2],
  ["It tells me to keep it secret or not to tell my bank or family",3],
  ["It wants me to deposit a check and send some money back",3],
  ["The sender's address, number, or website looks slightly off",2],
  ["It claims to be the government, police, my bank, or a family member in trouble",2]
];
let scamChecks = {};
function scamMeter(){
  const score = Object.keys(scamChecks).reduce((s,i)=>s+FLAGS[+i][1],0);
  if(score===0) return `<div class="note info">Check any red flags you see in the message.</div>`;
  if(score<=2) return `<div class="note heads"><b>Be careful.</b> One warning sign doesn't prove it's a scam, but check it yourself using a phone number or website you already trust.</div>`;
  if(score<=5) return `<div class="note bad"><b>This looks like a scam.</b> Don't click, pay, or share codes. Contact the company or person directly on a number you already know.</div>`;
  return `<div class="note bad"><b>Very likely a scam.</b> Stop all contact. If you already paid or shared info, see "If it happened to you" below right away.</div>`;
}
function scamCard(x){ return `<div class="card"><div class="inshead">${ico(x.icon,"lg")}<div><div style="display:flex;gap:10px;align-items:baseline;flex-wrap:wrap"><h3 style="margin:0">${esc(x.t)}</h3><span class="pill">${esc(x.tag)}</span></div>
    <p style="margin:8px 0 0"><b>How it works:</b> ${esc(x.how)}</p></div></div>
    ${x.ky?`<div class="note heads">📍 ${esc(x.ky)}</div>`:""}
    <div class="note good"><b>What to do:</b> ${esc(x.do)}</div></div>`; }
function scamPanel(){ const x=SCAMS[+uiTiles.scam]; return (uiTiles.scam!=null && x)? scamCard(x) : `<p class="hint tile-hint">Tap a picture to see how the scam works and what to do.</p>`; }
function viewScams(){
  const p=state.profile;
  const forYou = SCAMS.filter(x=>x.who(p));
  return `<h1>Scams to watch for</h1>
  <p class="lead">Scammers target big moments like a first job, apartment, or car. Tap a picture to learn the trick.</p>
  <div class="grid" style="margin-bottom:8px">
    <div class="card"><div class="big">$15.9 billion</div><div class="muted">reported lost to fraud in 2025, a record (FTC)</div></div>
    <div class="card"><div class="big">#1</div><div class="muted">Imposter scams were the most reported scam for the 9th year in a row (FTC)</div></div>
    <div class="card"><div class="big">Text messages</div><div class="muted">were the top way scammers first reached people in 2025 (FTC)</div></div>
  </div>
  <h2>Is this a scam? Quick check</h2>
  <div class="card">
    <p style="margin-top:0">Got a message that feels off? Check every warning sign you see.</p>
    ${FLAGS.map((f,i)=>`<label class="check"><input type="checkbox" data-flag="${i}" ${scamChecks[i]?"checked":""}> ${esc(f[0])}</label>`).join("")}
    <div id="scamMeter" class="result">${scamMeter()}</div>
    <button type="button" class="small" id="btnFlagReset" style="margin-top:6px">Clear checks</button>
  </div>
  <h2>Trending scams to know ${forYou.length<SCAMS.length?`<span class="pill">matched to you</span>`:""}</h2>
  <p class="hint">Last checked ${FACTS.checked}. Based on FTC, FBI, and Kentucky agency warnings.</p>
  ${tileGrid("scam", forYou.map((x,i)=>({id:String(SCAMS.indexOf(x)), icon:x.icon, label:x.t, on:x.tag})), uiTiles.scam)}
  <div id="panel-scam" class="tile-panel">${scamPanel()}</div>
  <h2>Stay safe</h2>
  <div class="secs">
  ${sec("scam:protect","shield","Protect yourself before it happens","5 tips",`<ul style="margin:0">
    <li><b>Freeze your credit</b> at Equifax, Experian, and TransUnion. It's free, it stops new accounts in your name, and you can lift it when you apply for credit.</li>
    <li><b>Never share a one-time code.</b> No real bank or company will ask you to read one back.</li>
    <li><b>Turn on two-step login</b> and account alerts for your bank and email.</li>
    <li><b>Call back on a number you trust</b>, like the one on your card or the official website, not the number in the message.</li>
    <li><b>Slow down.</b> Pressure to act fast is the scammer's best tool.</li>
  </ul>`)}
  ${sec("scam:happened","phone","If it happened to you","5 steps",`<ol style="margin:0">
    <li><b>Call your bank or card company right away</b> to stop or reverse payments.</li>
    <li><b>Change passwords</b> on any account you shared, and turn on two-step login.</li>
    <li><b>Report it:</b> <a href="${SCAM_LINKS.report[1]}" target="_blank" rel="noopener noreferrer">ReportFraud.ftc.gov</a>, the <a href="${SCAM_LINKS.ic3[1]}" target="_blank" rel="noopener noreferrer">FBI's IC3</a> for online scams, and the Kentucky Attorney General at <a href="${SCAM_LINKS.kyag[1]}" target="_blank" rel="noopener noreferrer">ag.ky.gov/scams</a> or (888) 432-9257.</li>
    <li><b>If your identity was stolen,</b> get a step-by-step recovery plan at <a href="${SCAM_LINKS.idt[1]}" target="_blank" rel="noopener noreferrer">IdentityTheft.gov</a>.</li>
    <li><b>Watch out for "recovery" scams.</b> People who promise to get your money back for a fee are often scammers too.</li>
  </ol>`)}
  ${sec("scam:live","chart","Get live scam updates","",`<p style="margin-top:0">Scams change every week. These official pages post new warnings as they happen:</p>
    <div class="learn">${linkList([SCAM_LINKS.ftcAlerts,SCAM_LINKS.kyag,SCAM_LINKS.ic3,SCAM_LINKS.sec,SCAM_LINKS.aid])}</div>
    <p class="hint" style="margin-bottom:0">This page doesn't go online by itself, which keeps your information private. Tap a link to see the newest alerts.</p>`)}
  </div>`;
}
/* =========================================================
   INSURANCE. Checked Nov 3, 2026 (Kentucky DOI, KHBE/kynect, FEMA,
   SSA, Medicare, Kentucky SHIP). Explains coverage TYPES only.
   No companies are named or ranked.
   ========================================================= */
const INS_LINKS = {
  doi:["Kentucky Department of Insurance","https://insurance.ky.gov"],
  doiHelp:["File an insurance complaint (KY DOI)","https://insurance.ky.gov/ppc/new_default.aspx?divid=4"],
  kynect:["kynect (health coverage)","https://kynect.ky.gov"],
  khbe:["kynect open enrollment dates","https://khbe.ky.gov"],
  gloss:["HealthCare.gov glossary","https://www.healthcare.gov/glossary/"],
  flood:["FloodSmart (National Flood Insurance Program)","https://www.floodsmart.gov"],
  fmap:["FEMA flood maps","https://msc.fema.gov/portal/home"],
  mine:["Kentucky Mine Subsidence Insurance Fund","https://insurance.ky.gov/ppc/Documents/Revised%20Mine%20Subsidence%20Insurance%20Fund%20080124.pdf"],
  ssdi:["Social Security disability benefits","https://www.ssa.gov/disability"],
  medicare:["Medicare.gov: when to sign up","https://www.medicare.gov/basics/get-started-with-medicare"],
  ship:["Kentucky SHIP (free Medicare help)","https://www.chfs.ky.gov/agencies/dail/Pages/ship.aspx"],
  naic:["NAIC consumer insurance guides","https://content.naic.org/consumer"]
};
const INSURANCE = [
  {id:"health", icon:"health", label:"Health", sub:"Doctor and hospital bills",
   what:"Pays for doctor visits, prescriptions, and hospital stays. One emergency room trip can cost thousands without it.",
   who:"Everyone.",
   ky:["You can usually stay on a parent's plan until you turn 26.",
       "No job plan? Shop on kynect. Open enrollment for 2027 plans runs Nov 1, 2026 to Jan 15, 2027. Losing job coverage, moving, marrying, or having a baby opens a 60-day window to sign up.",
       "Medicaid and KCHIP (for kids) take applications all year. Starting Jan 1, 2027, some adults on Kentucky Medicaid will need to report work, school, or volunteer hours."],
   save:["Free, unbiased help picking a plan is available from a kynector (a kynect helper).","Stay in network. Out-of-network visits can cost much more.","A high-deductible plan can pair with an HSA, which saves money tax-free for health costs."],
   watch:["A low monthly price often means a high deductible. Use the bill splitter below to see what you'd really pay.","Short-term plans can refuse to pay for pre-existing conditions and may skip big benefits."],
   links:["kynect","khbe","gloss"], match:p=>true},
  {id:"car", icon:"car", label:"Car", sub:"Required to drive",
   what:"Pays for damage and injuries after a crash. Kentucky requires it on every registered car.",
   who:"Anyone who owns or regularly drives a car.",
   ky:["Kentucky's minimum is 25/50/25 liability ($25,000 per person and $50,000 per crash for injuries, $25,000 for property) plus $10,000 in personal injury protection (PIP).",
       "Kentucky is a \"choice no-fault\" state. PIP pays your medical bills no matter who caused the crash. You can reject no-fault in writing, but that changes your right to sue and be sued.",
       "You need Kentucky insurance before you can title a car here."],
   save:["Get quotes from at least 3 companies every year.","Ask about good-student, safe-driver, and bundling discounts.","A higher deductible lowers your price, as long as you have savings to cover it."],
   watch:["The minimum may not cover a serious crash. A hospital stay alone can pass $25,000.","Financed and leased cars usually need full coverage (collision and comprehensive).","Uninsured motorist coverage isn't required, but it protects you if the other driver has none."],
   links:["doi","naic"], match:p=>state.picked.car||(+p.age>=16&&+p.age<=25)},
  {id:"renters", icon:"key", label:"Renters", sub:"Your stuff and liability",
   what:"Covers your belongings if they're stolen or ruined by fire or a burst pipe, plus liability if someone gets hurt at your place.",
   who:"Anyone renting, including students living off campus.",
   ky:["Your landlord's insurance covers the building, not your things.","Some Kentucky leases require renters insurance, so read yours."],
   save:["It's often one of the cheapest policies you can buy.","Bundling with car insurance usually earns a discount.","Take a quick phone video of your things. It makes a claim much easier."],
   watch:["Flooding isn't covered. Renters can buy separate flood coverage for belongings.","\"Actual cash value\" pays what your used stuff is worth today. \"Replacement cost\" pays to buy it new."],
   links:["doi","naic"], match:p=>state.picked.moveout||!!p.move},
  {id:"home", icon:"house", label:"Homeowners", sub:"Your house and things",
   what:"Covers your house and belongings from fire, wind, hail, theft, and someone getting hurt on your property.",
   who:"Homeowners. Your lender will require it.",
   ky:["Tornado, wind, hail, and ice-storm damage are usually covered.","Flood and earthquake are not. Tap Flood and earthquake to learn more.",
       "Underground mine collapse isn't covered by a regular policy. In participating counties, coverage comes through the state's Mine Subsidence Insurance Fund."],
   save:["Shop your policy every year, since rates keep rising.","A higher deductible lowers your price.","Ask about discounts for a newer roof, alarms, or bundling with car insurance."],
   watch:["Some policies have a separate, higher wind and hail deductible.","Your monthly mortgage payment often includes insurance through escrow. Try the home calculator on Plan the next one."],
   links:["doi","mine"], match:p=>state.picked.home||p.firstHome},
  {id:"life", icon:"shield", label:"Life", sub:"Protects your family",
   what:"Pays money to the people you choose if you die, so they can keep up with rent, bills, and childcare.",
   who:"Anyone whose family depends on their income, especially parents.",
   ky:["Check that a company and agent are licensed with the Kentucky Department of Insurance before you buy."],
   save:["Term life (coverage for 10 to 30 years) usually costs far less than whole life.","Many jobs give a small amount free. It usually ends when you leave that job.","Prices are usually lower when you're younger and healthier."],
   watch:["Policies sold as investments can carry high fees. Understand the costs before you sign.","Name a beneficiary and update it after marriage, divorce, or a new baby."],
   links:["doi","naic"], match:p=>p.kids||state.picked.kid||state.picked.married},
  {id:"disability", icon:"paycheck", label:"Disability income", sub:"If you can't work",
   what:"Replaces part of your paycheck if illness or injury keeps you from working.",
   who:"Anyone who depends on a paycheck.",
   ky:["Social Security says more than 1 in 4 of today's 20-year-olds will become disabled before retirement age.","Social Security disability (SSDI) has strict rules and can take months to start."],
   save:["Check whether your job offers short-term and long-term disability. Group plans through work are often low-cost or free.","Self-employed? You'd need to buy your own policy."],
   watch:["Most plans replace only part of your pay, not all of it.","Coverage through work usually ends when you leave the job."],
   links:["ssdi","naic"], match:p=>state.picked.salary||matchOccupation(p.occupation)?.id==="self"||(+p.age>=22&&+p.age<62)},
  {id:"flood", icon:"water", label:"Flood and earthquake", sub:"Not in regular policies",
   what:"Separate coverage for disasters that regular home and renters policies leave out.",
   who:"Homeowners and renters, especially near rivers or in western Kentucky.",
   ky:["Regular home and renters policies don't cover flooding. Flood insurance comes from the National Flood Insurance Program or a private company. NFIP policies usually take 30 days to start.",
       "Western Kentucky sits near the New Madrid Seismic Zone. Earthquake coverage is an add-on you have to ask for."],
   save:["Look up your flood risk on FEMA's flood maps.","Many floods happen outside high-risk zones, where flood coverage often costs less."],
   watch:["Don't wait for the forecast. The 30-day wait means it's usually too late.","Earthquake coverage often has a high deductible, set as a percent of the home's value."],
   links:["flood","fmap","doi"], match:p=>state.picked.home||p.firstHome},
  {id:"medicare", icon:"medicare", label:"Medicare", sub:"Health coverage at 65",
   what:"Federal health insurance at 65, or earlier for some people with disabilities.",
   who:"People turning 65, and people who've received SSDI for a while.",
   ky:["Kentucky's SHIP gives free, unbiased Medicare counseling at (877) 293-7447."],
   save:["Your first chance to sign up is a 7-month window around your 65th birthday.","Compare drug and Advantage plans each fall during Medicare open enrollment (Oct 15 to Dec 7)."],
   watch:["Signing up late for Part B can mean a penalty that lasts for life, unless you have qualifying job coverage.","Never give your Medicare number to someone who calls you."],
   links:["medicare","ship"], match:p=>state.picked.retire||+p.age>=60}
];
const INS_BY_ID = Object.fromEntries(INSURANCE.map(x=>[x.id,x]));
let insCalc = {bill:8000, ded:2000, coins:20, oop:6000};

function insPanel(){
  const x=INS_BY_ID[uiTiles.ins]; if(!x) return `<p class="hint tile-hint">Tap a picture to see what it covers, Kentucky rules, ways to save, and what to watch out for.</p>`;
  const col=(icon,t,list,cls)=>`<div class="inscol ${cls}"><h4>${icon} ${t}</h4><ul>${list.map(s=>`<li>${esc(s)}</li>`).join("")}</ul></div>`;
  return `<div class="card inspanel">
    <div class="inshead">${ico(x.icon,"lg")}<div><h3 style="margin:0">${esc(x.label)} insurance</h3><p style="margin:4px 0 0">${esc(x.what)}</p><p class="hint" style="margin:4px 0 0"><b>Who needs it:</b> ${esc(x.who)}</p></div></div>
    <div class="inscols">${col("📍","Kentucky facts",x.ky,"ky")}${col("💡","Ways to save",x.save,"save")}${col("⚠️","Watch out",x.watch,"watch")}</div>
    <div class="learn" style="margin-top:8px">${linkList(x.links.map(k=>INS_LINKS[k]))}</div></div>`;
}
function insSplitHtml(){
  const bill=Math.max(0,insCalc.bill), ded=Math.max(0,insCalc.ded), co=Math.min(100,Math.max(0,insCalc.coins))/100, oop=Math.max(0,insCalc.oop);
  const dPart=Math.min(bill,ded);
  let you=dPart+Math.max(0,bill-ded)*co; const capped = oop>0 && you>oop; if(oop>0) you=Math.min(you,oop);
  const dShow=Math.min(dPart,you), cShow=Math.max(0,you-dShow), plan=Math.max(0,bill-you);
  const pc=v=> bill>0? (v/bill*100):0;
  return `<div class="split" role="img" aria-label="Of a ${money(bill)} bill, you pay ${money(you)} and the plan pays ${money(plan)}">
      <span class="sd" style="width:${pc(dShow)}%"></span><span class="sc" style="width:${pc(cShow)}%"></span><span class="sp" style="width:${pc(plan)}%"></span></div>
    <div class="legend"><span><i class="sd"></i>Your deductible ${money(dShow)}</span><span><i class="sc"></i>Your coinsurance share ${money(cShow)}</span><span><i class="sp"></i>Plan pays ${money(plan)}</span></div>
    <p class="takeaway"><b>You'd pay ${money(you)}</b> of this ${money(bill)} bill${capped?`. Your out-of-pocket max stopped it from going higher.`:"."} You'd also pay your monthly premium either way.</p>`;
}
function viewInsurance(){
  const p=state.profile;
  const tiles=INSURANCE.map(x=>({id:x.id, icon:x.icon, label:x.label, sub:x.sub, on:x.match(p)&&x.id!=="health"}));
  const words=[["receipt","Premium","What you pay every month just to have the plan."],["piggy","Deductible","What you pay first each year before the plan starts paying."],["chart","Coinsurance","Your share (like 20%) of costs after the deductible."],["shield","Out-of-pocket max","The most you'd pay in a year. After that, the plan pays 100%."]];
  return `<h1>Insurance</h1>
  <p class="lead">Insurance trades a small, steady cost for protection from a huge surprise bill. Tap a picture to learn the basics.</p>
  ${tileGrid("ins", tiles, uiTiles.ins)}
  <div id="panel-ins" class="tile-panel">${insPanel()}</div>

  <h2>Insurance words in one picture</h2>
  <div class="words">${words.map(([i,t,d])=>`<div class="word">${ico(i)}<b>${t}</b><span>${d}</span></div>`).join("")}</div>
  <div class="card">
    <h3 style="margin-top:0">Bill splitter: who pays a medical bill?</h3>
    <div class="grid">${[["bill","The bill ($)"],["ded","Your deductible ($)"],["coins","Your coinsurance (%)"],["oop","Out-of-pocket max ($)"]].map(([k,l])=>`<div><label for="ins-${k}">${l}</label><input id="ins-${k}" type="number" min="0" step="any" data-ins="${k}" value="${insCalc[k]}"></div>`).join("")}</div>
    <div id="insSplit" class="result">${insSplitHtml()}</div>
    <p class="hint" style="margin:0">Example numbers. Your plan's Summary of Benefits and Coverage lists your real ones. Copays and some free preventive care work differently.</p>
  </div>

  <h2>Trouble with an insurance company?</h2>
  <div class="card">${ico("phone","inl")} The <b>Kentucky Department of Insurance</b> takes complaints about health, car, home, and life insurance, and about agents. Call <b>(800) 595-6053</b> (in Kentucky) or file online.
    <div class="learn" style="margin-top:8px">${linkList([INS_LINKS.doiHelp,INS_LINKS.doi])}</div></div>
  <div class="note info">This page explains <b>types</b> of coverage. It doesn't name or rank insurance companies or tell you which policy to buy. Compare quotes and check a company's license with the Kentucky Department of Insurance.</div>`;
}

function viewSources(){
  const src=[
    ["Kentucky income tax rate (3.5% for 2026) and withholding","https://revenue.ky.gov"],
    ["Kentucky sales tax (6%)","https://revenue.ky.gov"],
    ["Kentucky motor vehicle usage tax (6%), KRS 138.460","https://law.justia.com/codes/kentucky/2012/chapter-138/138.460"],
    ["KY Saves 529 (no state tax deduction for contributions)","https://www.savingforcollege.com/529-plans/kentucky/ky-saves-529"],
    ["Teachers' Retirement System of Kentucky and Social Security","https://trs.ky.gov"],
    ["Kentucky Deferred Compensation","https://kdc.ky.gov"],
    ["Kentucky Housing Corporation","https://www.kyhousing.org"],
    ["STABLE Kentucky (ABLE accounts)","https://stablekentucky.com"],
    ["KHEAA and KEES scholarships","https://www.kheaa.com"],
    ["UK Credit Union membership","https://www.ukcreditunion.org/forallyall"],
    ["Commonwealth Credit Union","https://www.ccuky.org"],
    ["2026 retirement and HSA limits (IRS)","https://www.irs.gov/retirement-plans"],
    ["Free credit reports","https://www.annualcreditreport.com"],
    ["Credit union locator (NCUA)","https://mycreditunion.gov/about-credit-unions/credit-union-locator"],
    ["New to Kentucky: driver's license within 30 days","https://drive.ky.gov/Drivers/Pages/New-To-Kentucky.aspx"],
    ["Motor vehicle usage tax for new residents (credit for tax paid elsewhere)","https://revenue.ky.gov/Property/Motor-Vehicles/Pages/Motor-Vehicle-Usage-Tax.aspx"],
    ["Income tax reciprocity with neighboring states, 103 KAR 17:140","https://revenue.ky.gov"],
    ["Residency for in-state tuition, 13 KAR 2:045","https://apps.legislature.ky.gov/law/kar/titles/013/002/045/"],
    ["Using KEES out of state (Academic Common Market)","https://cpe.ky.gov/acm/acm-kees.html"],
    ["kynect","https://kynect.ky.gov"],
    ["ABLE accounts: disability onset before age 46 starting 2026, $20,000 limit","https://stablekentucky.com"],
    ["Kentucky homestead exemption: $49,100 for 2025–2026","https://revenue.ky.gov/Property/Residential-Farm-Commercial-Property/Pages/Homestead-Exemption.aspx"],
    ["2026–27 maximum Pell Grant: $7,395","https://fsapartners.ed.gov/knowledge-center/library/dear-colleague-letters/2026-01-30/2026-27-federal-pell-grant-maximum-and-minimum-award-amounts"],
    ["Public Service Loan Forgiveness","https://studentaid.gov/manage-loans/forgiveness-cancellation/public-service"],
    ["Kentucky security deposit rules (URLTA cities)","https://www.kyjustice.org/topics/evictions/security-deposits-only-places-passed-urlta-uniform-residential-landlord-tenant-act"],
    ["Age compare: Federal Reserve, Changes in U.S. Family Finances from 2022 to 2025 (net worth by age, Table 2; released Oct 9, 2026)","https://www.federalreserve.gov/publications/files/scf26.pdf"],
    ["Age compare: retirement account medians by age, 2025 SCF public data","https://binarydecimal.com/blogs/retirement-savings-by-age-2025"],
    ["Age compare: checking and checking + savings by age, 2025 SCF public data (Boldin)","https://www.boldin.com/retirement/average-household-savings-home-equity-and-other-balances/"],
    ["Kentucky real median household income 2025: $73,750 (Census via FRED)","https://fred.stlouisfed.org/series/MEHOINUSKYA672N"],
    ["U.S. real median household income 2025: $87,460 (Census, Income in the United States: 2025)","https://www.census.gov/library/stories/2026/09/median-household-income.html"],
    ["Kentucky Department of Insurance consumer protection, (800) 595-6053","https://insurance.ky.gov/ppc/new_default.aspx?divid=4"],
    ["kynect open enrollment for 2027 plans: Nov 1, 2026 to Jan 15, 2027 (KHBE)","https://khbe.ky.gov"],
    ["Kentucky Medicaid work requirements begin Jan 1, 2027 (kynector training guide)","https://khbe.ky.gov/TrainingGuides/Documents/kynector_2027_Refresher_Training_Guide.pdf"],
    ["Kentucky earthquake coverage rules (DOI Bulletin 98-2)","https://insurance.ky.gov/PPC/Documents/bul9802.pdf"],
    ["Kentucky Mine Subsidence Insurance Fund","https://insurance.ky.gov/ppc/Documents/Revised%20Mine%20Subsidence%20Insurance%20Fund%20080124.pdf"],
    ["National Flood Insurance Program","https://www.floodsmart.gov"],
    ["More than 1 in 4 20-year-olds will become disabled before retirement age (SSA)","https://www.ssa.gov/disabilityfacts/materials/pdf/poster-1.pdf"],
    ["Kentucky SHIP free Medicare counseling, (877) 293-7447","https://www.chfs.ky.gov/agencies/dail/Pages/ship.aspx"],
    ["Kentucky Agricultural Finance Corporation","https://www.kyagr.com/agpolicy/Kentucky-Ag-Finance-Corporation.html"],
    ["FTC: 2025 fraud data and consumer alerts","https://consumer.ftc.gov/consumer-alerts"],
    ["Kentucky Attorney General: scam reporting","https://ag.ky.gov/scams"],
    ["VA home loans: no down payment, no PMI, funding fee","https://www.va.gov/housing-assistance/home-loans/loan-types/purchase-loan/"],
    ["Kentucky Department of Veterans Affairs: tuition waiver, benefits","https://veterans.ky.gov"],
    ["Navy Federal Credit Union membership eligibility","https://www.navyfederal.org/membership/eligibility.html"],
    ["Abound Credit Union membership","https://www.aboundcu.com/Learn/What-We-re-About/Membership"],
    ["SEC Investor.gov: brokerage accounts, index funds, ETFs, CDs","https://www.investor.gov"],
    ["FINRA: investing for children and custodial accounts","https://www.finra.org/investors/insights/investing-children"],
    ["FDIC and NCUA: deposit and share insurance","https://www.fdic.gov/resources/deposit-insurance"],
    ["IRS: Roth IRAs, 401(k), 403(b), HSAs (Pub. 969), 529 plans","https://www.irs.gov"],
    ["CFPB: credit cards, credit reports, auto loans, buying a home","https://www.consumerfinance.gov"]
  ];
  return `<h1>Sources and how this page works</h1>
  <div class="card"><h3>What this page is</h3><p>KY Money Milestones is an educational tool for young Kentuckians. It explains which accounts and programs matter at each life stage and helps you plan the cost of your next one. It does not recommend any specific investment, fund, or company, and it can't tell you what's right for your situation.</p>
  <h3>Your privacy</h3><p>This page never sends your information anywhere. There are no accounts and no logins. Your plan only exists on this page and in the file you save.</p>
  <h3>Saving your work</h3><p>Click <b>Save plan</b> or press <b>Ctrl+S</b> (Cmd+S on a Mac) to download your plan. Double-click the saved file to read it, print it, or share it. To keep editing, click <b>Open</b> here (or drag the file onto this page). If you try to close the page with unsaved changes, your browser will warn you.</p>
  <h3>Credits</h3><p>Built with plain HTML, CSS, and JavaScript. No third-party code. Released under the MIT License.</p></div>
  <h2>Facts we used (checked ${FACTS.checked})</h2>
  <div class="card"><ul>${src.map(([t,u])=>`<li><a href="${u}" target="_blank" rel="noopener noreferrer">${esc(t)}</a></li>`).join("")}</ul>
  <p class="hint">Laws, limits, and program rules change. Always check the official source before making a decision.</p></div>`;
}

/* Recompute the live result areas without redrawing inputs (keeps your cursor in place) */
function refreshLive(){
  document.querySelectorAll("[data-toolbox]").forEach(b=>{ const id=b.dataset.toolbox; const o=document.getElementById("out-"+id); if(o) o.innerHTML=toolResult(id); });
  const ps=document.getElementById("planSummary"); if(ps) ps.innerHTML=planSummaryHtml();
  const intro=document.getElementById("intro"); if(intro){ const empty=isEmptyPlan(); if(intro.dataset.empty!==String(empty)||!empty){ intro.innerHTML = empty? featuresHtml() : summaryHtml(); intro.dataset.empty=String(empty); } }
  const sw=document.getElementById("swipeOut"); if(sw) sw.innerHTML=swipeHtml();
  const ho=document.getElementById("homeOut"); if(ho) ho.innerHTML=homeHtml();
  animateIn(document.getElementById("main"));
  document.querySelectorAll("[data-item]").forEach(tr=>{ const it=state.items.find(i=>i.id===tr.dataset.item); const td=tr.querySelector("[data-item-total]"); if(it&&td) td.textContent=money(itemTotal(it),true); });
}

/* =========================================================
   9. PRICE FINDER (works on pasted text only, no internet)
   ========================================================= */
function findPrices(text){
  const lines = text.split(/\r?\n/).map(s=>s.trim()).filter(Boolean);
  const re = /\$\s?(\d{1,3}(?:,\d{3})+(?:\.\d{2})?|\d+(?:\.\d{2})?)/g;
  const found = new Map();
  lines.forEach((line, idx)=>{
    let m; re.lastIndex=0;
    while((m=re.exec(line))){
      const v=parseFloat(m[1].replace(/,/g,"")); if(!(v>0) || v>2000000) continue;
      let score = found.has(v)? found.get(v).score : 0;
      score += 1;
      if(/price|now|sale|our price|buy|total|each|today/i.test(line)) score += 3;
      if(/was|list|save|shipping|delivery|off|coupon|reg\.|per month|\/mo|monthly/i.test(line)) score -= 2;
      if(idx < 80) score += 1;
      found.set(v,{value:v, score});
    }
  });
  const prices=[...found.values()].sort((a,b)=>b.score-a.score).slice(0,6);
  const name = lines.find(l=>l.length>=12 && l.length<=140 && !/\$|sign in|cart|menu|skip to|search|account|shop|deliver|ship|help/i.test(l) && /[a-z]/i.test(l) && l.split(" ").length>=2) || "";
  return {prices, name};
}

/* =========================================================
   10. EVENTS
   ========================================================= */
function setPath(path, value){
  const parts=path.split("."); let o=state;
  for(let i=0;i<parts.length-1;i++) o=o[parts[i]];
  o[parts[parts.length-1]]=value;
}

document.addEventListener("input", e=>{
  const el=e.target;
  if(el.id==="ageSlide"){ ageShow(true); return; }
  if(el.dataset.bind){
    setPath(el.dataset.bind, el.type==="checkbox"? el.checked : (el.dataset.bind.startsWith("swipe.") ? clampTool(el.dataset.bind==="swipe.apr"?"apr":"x", n(el.value)) : el.value));
    setDirty(true);
    if((el.dataset.bind==="profile.firstHome"||el.dataset.bind==="profile.firstTime") && el.checked) state.picked.home=true;
    if(["profile.veteran","profile.serving","profile.milFamily","profile.disability","profile.move","profile.moveState"].includes(el.dataset.bind)){ const sp=document.getElementById("situation"); if(sp){ sp.innerHTML=situationHtml(); } }
    if(el.dataset.bind==="profile.occupation"){ const g=matchOccupation(el.value); const o=document.getElementById("occMatch"); if(o) o.innerHTML = g?`We'll show tips for: <b>${esc(g.label)}</b>`:"Type your job in everyday words."; }
    updateNav(); refreshLive(); return;
  }
  if(el.dataset.flag!==undefined && el.type==="checkbox"){ if(el.checked) scamChecks[el.dataset.flag]=true; else delete scamChecks[el.dataset.flag]; document.getElementById("scamMeter").innerHTML=scamMeter(); return; }
  if(el.dataset.guideq){ state._guideQ=el.value; document.getElementById("guideList").innerHTML=guideListHtml(); return; }
  if(el.dataset.ins){ insCalc[el.dataset.ins]=Math.min(Math.max(n(el.value),0), el.dataset.ins==="coins"?100:1e8); document.getElementById("insSplit").innerHTML=insSplitHtml(); return; }
  if(el.dataset.home){ const hk=el.dataset.home; state.home[hk]=Math.min(Math.max(n(el.value),0), {downPct:100,closingPct:20,rate:30,years:50,ptax:10}[hk]||1e9); setDirty(true); refreshLive(); return; }
  if(el.dataset.tool){ const [id,k]=el.dataset.tool.split("."); state.tools[id]=state.tools[id]||{}; state.tools[id][k]=n(el.value); setDirty(true); refreshLive(); return; }
  if(el.dataset.msage){ state.msAge[el.dataset.msage]=el.value; setDirty(true); return; }
  if(el.dataset.bill){ const [i,k]=el.dataset.bill.split("."); state.bills[+i][k]=el.value; setDirty(true); refreshLive(); return; }
  if(el.dataset.itemF){ const tr=el.closest("[data-item]"); const it=state.items.find(i=>i.id===tr.dataset.item); if(!it) return;
    const f=el.dataset.itemF; it[f] = (f==="price"||f==="saved")? n(el.value) : el.value; setDirty(true); refreshLive(); return; }
});

document.addEventListener("change", e=>{
  const el=e.target;
  if(el.dataset.bind && el.type==="checkbox"){ return; }
  if(el.dataset.bind==="next.milestone"){ render(); return; }
  if(el.dataset.pick){ if(el.checked) state.picked[el.dataset.pick]=true; else delete state.picked[el.dataset.pick]; if(el.checked){ state._open=state._open||{}; state._open[el.dataset.pick]=true; } setDirty(true); render(); return; }
  if(el.dataset.check){ if(el.checked) state.checks[el.dataset.check]=true; else delete state.checks[el.dataset.check]; setDirty(true);
    const d=el.closest("details.ms"); if(d){ const m=MS_BY_ID[d.dataset.ms]; const done=m.checklist.filter((c,i)=>state.checks[m.id+":"+i]).length; const s=d.querySelector("summary .pc"); if(s) s.textContent=`${done} of ${m.checklist.length} steps done`; const ck=d.querySelector(".ckc"); if(ck) ck.textContent=`${done}/${m.checklist.length}`; const bar=d.querySelector("summary .progress em"); if(bar) bar.style.width=(done/m.checklist.length*100)+"%"; } return; }
  if(el.dataset.msage){ render(); return; }
  if(el.dataset.itemF==="price"){ render(); return; }
});

document.addEventListener("toggle", e=>{
  const d=e.target; if(d.matches && d.matches("details.ms")){ state._open=state._open||{}; state._open[d.dataset.ms]=d.open; }
  if(d.matches && d.matches("details.sec[data-k]")){ uiOpen[d.dataset.k]=d.open; if(d.open){ refreshLive(); } }
}, true);

document.addEventListener("click", async e=>{
  const b=e.target.closest("button"); if(!b) return;
  if(b.dataset.tab){ currentTab=b.dataset.tab; render(true); window.scrollTo(0,0); return; }
  if(b.dataset.jump){ const t=document.getElementById(b.dataset.jump); if(t){ t.scrollIntoView({behavior:reduceMotion?"auto":"smooth"}); const f=document.getElementById("p-name"); if(f) setTimeout(()=>f.focus({preventScroll:true}),reduceMotion?0:400); } return; }
  if(b.id==="btnExample"){
    if(dirty && !(await ask("Load the example?","You have unsaved changes. Loading the example will replace them. Save first if you want to keep them."))) return;
    state=exampleState(); quizRound=null; everSaved=false; setDirty(true); Object.keys(uiTiles).forEach(k=>delete uiTiles[k]); currentTab="about"; render(true); window.scrollTo(0,0);
    toast("Example loaded: Jordan, 22, a nurse in Fayette County. Click around, or press New to start your own."); return; }
  if(b.dataset.tile){ const i=b.dataset.tile.indexOf(":"), g=b.dataset.tile.slice(0,i), id=b.dataset.tile.slice(i+1);
    const cur = g==="sit"? situationOpenId() : g==="qual"? qualOpenId() : uiTiles[g];
    uiTiles[g] = cur===id? null : id;
    b.closest(".tiles").querySelectorAll(".tile").forEach(t=>t.setAttribute("aria-expanded", t===b && uiTiles[g]!==null ? "true":"false"));
    const panel = g==="guide"? document.getElementById("guideList") : document.getElementById("panel-"+g);
    panel.innerHTML = ({sit:situationPanel, ins:insPanel, scam:scamPanel, guide:guideListHtml, qual:qualPanel})[g]();
    panel.classList.remove("pop"); void panel.offsetWidth; panel.classList.add("pop");
    refreshLive();
    if(uiTiles[g] && panel.getBoundingClientRect().top > window.innerHeight*0.75) panel.scrollIntoView({behavior: matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth", block:"start"});
    return; }
  if(b.dataset.go){ currentTab=b.dataset.go; render(true); window.scrollTo(0,0); return; }
  if(b.dataset.print){ document.querySelectorAll("details").forEach(d=>d.open=true); window.print(); return; }
  if(b.dataset.quiz){ const [i,v]=b.dataset.quiz.split(":"); state.quiz[i]= v==="1"; setDirty(true); render(); return; }
  if(b.id==="btnHomeAdd"){ const h=state.home, price=Math.max(0,n(h.price)), today=new Date().toISOString().slice(0,10);
    const down=Math.round(price*Math.max(0,n(h.downPct))/100), closing=Math.round(price*Math.max(0,n(h.closingPct))/100);
    if(down>0) state.items.push({id:uid(), name:`Home down payment (${n(h.downPct)}%)`, url:"", price:down, addedPrice:down, addedOn:today, tax:"none", saved:0});
    if(closing>0) state.items.push({id:uid(), name:`Home closing costs (${n(h.closingPct)}%)`, url:"", price:closing, addedPrice:closing, addedOn:today, tax:"none", saved:0});
    setDirty(true); render(); toast("Added to your shopping list. There's no sales tax on these."); return; }
  if(b.id==="btnFlagReset"){ scamChecks={}; render(); return; }
  if(b.id==="btnQuizReset"){ state.quiz={}; quizRound=null; setDirty(true); render(); return; }
  if(b.id==="btnQuizMore"){ drawQuizRound(); render(true); window.scrollTo(0,0); return; }
  if(b.dataset.remove){ state.items=state.items.filter(i=>i.id!==b.dataset.remove); setDirty(true); render(); return; }
  if(b.dataset.billdel){ state.bills.splice(+b.dataset.billdel,1); setDirty(true); render(); return; }
  if(b.id==="btnAddBill"){ state.bills.push({name:"",amount:""}); setDirty(true); render(); return; }
  if(b.dataset.bundle){ const m=MS_BY_ID[b.dataset.bundle]; const today=new Date().toISOString().slice(0,10);
    m.bundle.forEach(x=>state.items.push({id:uid(), name:x.name, url:"", price:x.price, addedPrice:x.price, addedOn:today, tax:x.tax, saved:0}));
    setDirty(true); render(); toast("Starter list added. Change any price to match yours."); return; }
  if(b.id==="btnFind"){
    const txt=document.getElementById("paste-text").value; const out=document.getElementById("cands");
    if(!txt.trim()){ out.innerHTML=`<div class="note heads">Paste the product page into the box first.</div>`; return; }
    const r=findPrices(txt);
    if(r.name && !document.getElementById("add-name").value) document.getElementById("add-name").value=r.name.slice(0,120);
    out.innerHTML = r.prices.length? `<p style="margin:10px 0 4px"><b>Which one is the price?</b> <span class="hint">Most likely first.</span></p><div class="cands">${r.prices.map(p=>`<button type="button" class="small" data-pickprice="${p.value}">${money(p.value,true)}</button>`).join("")}</div>`
      : `<div class="note heads">We couldn't find a price in that text. Type it in the Price box instead.</div>`;
    return;
  }
  if(b.dataset.pickprice){ document.getElementById("add-price").value=b.dataset.pickprice; b.parentElement.querySelectorAll("button").forEach(x=>x.classList.remove("primary")); b.classList.add("primary"); return; }
  if(b.id==="btnAdd"){
    const url=document.getElementById("add-url").value.trim(), nameIn=document.getElementById("add-name").value.trim(), price=n(document.getElementById("add-price").value), tax=document.getElementById("add-tax").value;
    const su = url? safeUrl(url):"";
    if(url && !su){ toast("That link doesn't look right. It should start with https://", true); return; }
    if(!(price>0)){ toast("Add a price first. You can type it or use the paste helper.", true); return; }
    const name = nameIn || (su? storeName(su)+" item" : "Item");
    state.items.push({id:uid(), name, url:su, price, addedPrice:price, addedOn:new Date().toISOString().slice(0,10), tax, saved:0});
    setDirty(true); render(); toast("Added to your plan."); return;
  }
  if(b.id==="btnSave"){ savePlan(); return; }
  if(b.id==="btnOpen"){
    if(dirty && !(await ask("Open a different plan?","You have unsaved changes. If you open another plan, they'll be lost. Save first if you want to keep them."))) return;
    document.getElementById("fileInput").value=""; document.getElementById("fileInput").click(); return;
  }
  if(b.id==="btnNew"){
    if(dirty && !(await ask("Start a new plan?","You have unsaved changes. Starting over will clear them. Save first if you want to keep them."))) return;
    state=defaults(); quizRound=null; everSaved=false; setDirty(false); Object.keys(uiTiles).forEach(k=>delete uiTiles[k]); currentTab="about"; render(true); window.scrollTo(0,0); return;
  }
});

document.getElementById("fileInput").addEventListener("change", e=>openFile(e.target.files[0]));
document.addEventListener("dragover", e=>{ e.preventDefault(); });
document.addEventListener("drop", async e=>{
  e.preventDefault();
  const f = e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0]; if(!f) return;
  if(dirty && !(await ask("Open a different plan?","You have unsaved changes. If you open another plan, they'll be lost. Save first if you want to keep them."))) return;
  openFile(f);
});

document.addEventListener("keydown", e=>{
  if((e.ctrlKey||e.metaKey) && !e.shiftKey && !e.altKey && e.key.toLowerCase()==="s"){ e.preventDefault(); savePlan(); }
  if(e.key==="Escape" && document.getElementById("modalBg").style.display==="flex") document.getElementById("modalNo").click();
  if(e.key==="Escape" && document.activeElement?.id==="ageSlide"){ ageShow(false); }
});

function ageFromPointer(e, road){ const r=road.getBoundingClientRect(); const x=(e.clientX-r.left)/r.width*ROAD_W; const s=document.getElementById("ageSlide"); if(!s) return; s.value=xToAge(x); ageShow(true); }
document.addEventListener("pointerdown", e=>{ const road=e.target.closest&&e.target.closest(".roadin"); if(!road||e.button>0) return;
  const s=document.getElementById("ageSlide"); if(s) s.focus({preventScroll:true});
  road.classList.add("dragging"); try{ road.setPointerCapture(e.pointerId); }catch(_){}
  ageFromPointer(e, road); e.preventDefault(); });
document.addEventListener("pointermove", e=>{ const road=document.querySelector(".roadin.dragging"); if(road) ageFromPointer(e, road); });
document.addEventListener("pointerup", e=>{ const road=document.querySelector(".roadin.dragging"); if(road){ road.classList.remove("dragging"); try{ road.releasePointerCapture(e.pointerId); }catch(_){} } });
document.addEventListener("focusin", e=>{ if(e.target.id==="ageSlide") ageShow(true); });
document.addEventListener("focusout", e=>{ if(e.target.id==="ageSlide") ageShow(false); });
document.addEventListener("mouseover", e=>{ if(e.target.closest && e.target.closest(".roadin")) ageShow(true); });
document.addEventListener("mouseout", e=>{ const r=e.target.closest&&e.target.closest(".roadin"); if(r && !r.contains(e.relatedTarget) && document.activeElement?.id!=="ageSlide") ageShow(false); });
window.addEventListener("resize", ()=>{ const p=document.getElementById("agePop"); if(p && !p.hidden) agePlace(); });
window.addEventListener("beforeunload", e=>{ if(dirty){ e.preventDefault(); e.returnValue=""; return ""; } });

render();
</script>
</body>
</html>

Reaches out to

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

  • www.fdic.gov
  • mycreditunion.gov
  • www.consumerfinance.gov
  • www.irs.gov
  • www.finra.org
  • finra.org
  • www.investor.gov
  • brokercheck.finra.org
  • www.sipc.org
  • www.healthcare.gov
  • www.kysaves.com
  • www.annualcreditreport.com

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 Truc Nguyen. 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.