A free game where you live your whole financial life, from college to retirement, using your own numbers. Try Watch a sample life for a quick look, or play your own life with your real numbers.
<!-- Copyright (c) 2026 Will Frey. Released under the MIT License. -->
<!-- The Long Game: a money life-simulation for Kentucky college students and recent graduates who were never taught personal finance. For education only; not financial, investment, tax or legal advice. Uses no outside code libraries. Its only outside service is Google Fonts, which supplies the typefaces Bricolage Grotesque, Atkinson Hyperlegible and IBM Plex Mono (SIL Open Font License); nothing you enter leaves your device. -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>The Long Game</title>
<meta name="description" content="A free game where you live your whole financial life, from college to retirement, using your own numbers.">
<meta property="og:title" content="The Long Game">
<meta property="og:description" content="A free game where you live your whole financial life, from college to retirement, using your own numbers.">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,500;12..96,700;12..96,800&family=Atkinson+Hyperlegible:ital,wght@0,400;0,700;1,400&family=IBM+Plex+Mono:wght@500;600&display=swap" rel="stylesheet">
<style>
/* Layout: a game board. A path of life stages across the top, the current turn in the main column, a running balance sheet beside it. */
:root{
/* Type scale: every text size in the game uses one of these */
--fs-2xs:12.5px; --fs-xs:13.5px; --fs-sm:15.5px; --fs-base:17.5px; --fs-md:19.5px; --fs-lg:22px;
/* Green theme: forest-green hero, mint-gray surfaces */
--bg:#E9EFED; --surface:#FFFFFF; --sunk:#DCE5E2; --ink:#13262F; --muted:#56686D; --line:#C9D5D2;
--accent:#1D7556; --accent-ink:#FFFFFF; --accent-soft:#D3EADF;
--gold:#946F00; --gold-ink:#7A5B00; --gold-soft:#F5E8CA; --danger:#B13E2B; --danger-soft:#F7DED7;
--c-cash:#B38600; --c-k401:#1D8A5E; --c-ira:#A0522D; --c-roth:#2453C9; --c-brok:#C2418A; --c-home:#E0702A; --c-car:#6F7F94; --c-debt:#B13E2B; --c-529:#6A4FB8;
--hero1:#123B30; --hero2:#1D7556;
--pie-1:#2a78d6; --pie-2:#eb6834; --pie-3:#1baf7a; --pie-4:#eda100; --pie-5:#e87ba4; --pie-6:#008300; --pie-7:#6250d6; --pie-8:#e34948; --pie-other:#a3aeac;
--display:"Bricolage Grotesque","Avenir Next","Segoe UI",system-ui,sans-serif;
--body:"Atkinson Hyperlegible","Segoe UI",system-ui,sans-serif;
--mono:"IBM Plex Mono",ui-monospace,"SFMono-Regular",Menlo,monospace;
--r:14px;
}
@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){
--bg:#0D171B; --surface:#14222A; --sunk:#0A1317; --ink:#E3EDEA; --muted:#93A6A8; --line:#284049;
--accent:#49C095; --accent-ink:#06261A; --accent-soft:#153A2F;
--gold:#E6B44E; --gold-ink:#E6B44E; --gold-soft:#372C15; --danger:#EC8069; --danger-soft:#3B1F19;
--c-cash:#B38600; --c-k401:#2E9E6B; --c-ira:#C0703F; --c-roth:#4C7BEF; --c-brok:#D0559A; --c-home:#E0702A; --c-car:#9AA8BC; --c-debt:#EC8069; --c-529:#8F6FE0;
--hero1:#0F2E26; --hero2:#17583F; --pie-1:#3987e5; --pie-2:#d95926; --pie-3:#199e70; --pie-4:#c98500; --pie-5:#d55181; --pie-6:#008300; --pie-7:#9085e9; --pie-8:#e66767; --pie-other:#5f6f73; color-scheme:dark}}
:root[data-theme="dark"]{
--bg:#0D171B; --surface:#14222A; --sunk:#0A1317; --ink:#E3EDEA; --muted:#93A6A8; --line:#284049;
--accent:#49C095; --accent-ink:#06261A; --accent-soft:#153A2F;
--gold:#E6B44E; --gold-ink:#E6B44E; --gold-soft:#372C15; --danger:#EC8069; --danger-soft:#3B1F19;
--c-cash:#B38600; --c-k401:#2E9E6B; --c-ira:#C0703F; --c-roth:#4C7BEF; --c-brok:#D0559A; --c-home:#E0702A; --c-car:#9AA8BC; --c-debt:#EC8069; --c-529:#8F6FE0;
--hero1:#0F2E26; --hero2:#17583F; --pie-1:#3987e5; --pie-2:#d95926; --pie-3:#199e70; --pie-4:#c98500; --pie-5:#d55181; --pie-6:#008300; --pie-7:#9085e9; --pie-8:#e66767; --pie-other:#5f6f73; color-scheme:dark}
*{box-sizing:border-box}
[hidden]{display:none!important}
body{background:var(--bg);color:var(--ink);font-family:var(--body);font-size:var(--fs-base);line-height:1.55}
.wrap{max-width:1160px;margin:0 auto;padding-inline:18px;padding-block:22px 48px}
h1,h2,h3{font-family:var(--display);line-height:1.15;text-wrap:balance;margin:0}
h1{font-size:clamp(34px,6vw,56px);font-weight:800;letter-spacing:-.025em}
h2{font-size:clamp(22px,3vw,28px);font-weight:700;letter-spacing:-.01em}
h3{font-size:var(--fs-md);font-weight:700}
p{margin:0;max-width:68ch}
ul{margin:0;padding-left:20px}
li{margin:2px 0}
a{color:var(--accent)}
.money,.num{font-family:var(--mono);font-variant-numeric:tabular-nums}
.eyebrow{font-family:var(--mono);font-size:var(--fs-xs);letter-spacing:.08em;text-transform:uppercase;color:var(--muted)}
.muted{color:var(--muted)}
.neg{color:var(--danger)} .pos{color:var(--accent)}
.ic{width:22px;height:22px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round;flex:none}
.hero{position:relative;overflow:hidden;border-radius:20px;padding:28px 26px;margin-bottom:18px;color:#F3F8F5;
background:radial-gradient(70% 90% at 0% 100%,rgba(73,192,149,.28),transparent 70%),radial-gradient(120% 140% at 100% 0%,var(--hero2) 0%,var(--hero1) 60%)}
.hero p{color:#CFE3DA;font-size:var(--fs-md)}
.hero .eyebrow{color:#9FD3BC}
.hero-row{position:relative;display:flex;flex-wrap:wrap;gap:16px 28px;align-items:flex-end;justify-content:space-between}
.hero canvas{position:absolute;inset:0;width:100%;height:100%;opacity:.5;pointer-events:none}
.hero-ctl{display:flex;flex-wrap:wrap;gap:8px;align-items:center}
.homebtn{display:inline-flex;align-items:center;gap:6px;font:600 var(--fs-sm) var(--body);color:#F3F8F5;background:rgba(255,255,255,.1);border:1px solid rgba(255,255,255,.25);padding:8px 14px;border-radius:99px;cursor:pointer}
.homebtn:hover{background:rgba(255,255,255,.18)}.homebtn .ic{width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:2}
/* Home: one memorable element, the two-lives chart; everything else quiet */
.hhero{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1.15fr);gap:28px;align-items:center;padding:30px}
@media (max-width:820px){.hhero{grid-template-columns:minmax(0,1fr);padding:22px}}
.hh-copy{display:flex;flex-direction:column;gap:16px;min-width:0}
.hh-title{font-size:clamp(32px,4.2vw,44px);font-weight:800;letter-spacing:-.03em;line-height:1.02}
.hh-lede{margin:0;font-size:var(--fs-md);line-height:1.55;max-width:46ch}
.hh-cta{display:flex;flex-wrap:wrap;gap:10px}
.hh-more{display:flex;flex-wrap:wrap;gap:4px 18px}
.hh-cta a.btn{text-decoration:none}
.hlink{display:inline-flex;align-items:center;gap:7px;background:none;border:0;padding:6px 0;font:700 var(--fs-base) var(--body);color:var(--accent);cursor:pointer;text-underline-offset:3px}
.hlink:hover{text-decoration:underline}
.hlink .ic{width:18px;height:18px}
.hlink:focus-visible,.linkbtn:focus-visible{outline:2px solid var(--accent);outline-offset:3px;border-radius:4px}
.hh-chart{margin:0;min-width:0;display:flex;flex-direction:column;gap:8px}
.hh-chart figcaption{font-size:var(--fs-sm);color:var(--muted);line-height:1.45}
.lives{width:100%;height:auto;display:block;overflow:visible}
.lv-base{stroke:var(--line);stroke-width:1.5}
.lv-area{fill:var(--accent-soft);opacity:.7}
.lv-you{fill:none;stroke:var(--accent);stroke-width:3.5;stroke-linejoin:round;stroke-linecap:round}
.lv-twin{fill:none;stroke:var(--muted);stroke-width:2.5;stroke-dasharray:6 6;stroke-linecap:round}
.lv-ms line{stroke:var(--line);stroke-width:1;stroke-dasharray:2 4}
.lv-ms circle{fill:var(--surface);stroke:var(--gold);stroke-width:2.5}
.lv-ms text{font:700 var(--fs-sm) var(--body);fill:var(--ink)}
.lv-ms .lv-age{font:500 var(--fs-xs) var(--body);fill:var(--muted)}
.lv-axis{font:500 var(--fs-xs) var(--body);fill:var(--muted)}
.lv-big{font:800 28px var(--display);fill:var(--accent);letter-spacing:-.02em}
.lv-small{font:700 var(--fs-md) var(--display);fill:var(--muted)}
.lv-key{display:flex;flex-wrap:wrap;gap:6px 18px;font-size:var(--fs-sm)}
.lv-key span{display:inline-flex;align-items:flex-start;gap:8px}
.lv-key span::before{content:'';flex:none;width:22px;height:0;margin-top:.75em;border-top:3.5px solid var(--accent);border-radius:2px}
.lv-key .k-twin::before{border-top:2.5px dashed var(--muted)}
.lives.draw .lv-you{stroke-dasharray:1;stroke-dashoffset:1;animation:lvdraw 1.8s cubic-bezier(.6,.05,.3,1) .2s forwards}
.lives.draw .lv-area,.lives.draw .lv-ms,.lives.draw .lv-tag{opacity:0;animation:lvfade .6s ease 1.7s forwards}
.lives.draw .lv-area{animation-name:lvfadeA}
@keyframes lvdraw{to{stroke-dashoffset:0}}
@keyframes lvfade{to{opacity:1}}
@keyframes lvfadeA{to{opacity:.7}}
.why{display:flex;flex-direction:column;gap:14px;padding:6px 4px 0}
.why h3{font-size:var(--fs-lg)}
.whygrid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px;align-items:stretch}
.whygrid .whycard:last-child{grid-column:1/-1}
@media (max-width:900px){.whygrid{grid-template-columns:minmax(0,1fr)}}
.whycard{display:flex;flex-direction:column;gap:10px}
.whycard h4{margin:0;font:700 var(--fs-md)/1.3 var(--display)}
.whycard p{margin:0}
.whystats{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}
.whystats div{display:flex;flex-direction:column;gap:2px;padding:10px 12px;border-radius:10px;background:var(--sunk)}
.whystats b{font:800 var(--fs-lg)/1.1 var(--display)}
.whystats span{font-size:var(--fs-sm);color:var(--muted)}
.whysrc{font-size:var(--fs-xs);color:var(--muted)}
.whyvals{margin:0;padding-left:20px;display:grid;gap:6px}
.whyvals b{font-family:var(--display)}
.whytbl{width:100%;border-collapse:collapse;font-size:var(--fs-sm)}
.whytbl th,.whytbl td{padding:8px 10px;border-bottom:1px solid var(--line);text-align:center;vertical-align:middle}
.whytbl tbody th{text-align:left;font-weight:400}
.whytbl thead th{font-size:var(--fs-xs);color:var(--muted);font-weight:600}
.whytbl thead th:nth-child(2){color:var(--ink);font-weight:700}
.whytbl td:nth-child(2){background:var(--accent-soft)}
.ck{display:inline-flex;align-items:center;justify-content:center}
@media (max-width:640px){
.whytbl thead{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)}
.whytbl,.whytbl tbody,.whytbl tr{display:block}
.whytbl tr{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:4px;padding:10px 0;border-bottom:1px solid var(--line)}
.whytbl tbody th{grid-column:1/-1;padding:0 0 6px;border:0;font-weight:600}
.whytbl td{display:flex;flex-direction:column;align-items:center;gap:2px;padding:6px 2px;border:0;border-radius:8px}
.whytbl td::before{content:attr(data-l);font-size:12.5px;color:var(--muted);line-height:1.2;text-align:center}
}
@media (max-width:460px){.whytbl tr{grid-template-columns:repeat(3,minmax(0,1fr))}}
.hh-short{margin:10px 0 0;font-size:var(--fs-sm);color:var(--muted)}
.ck.yes .ic{width:18px;height:18px;color:var(--accent)}
.ck.no{color:var(--muted)}
.ck.part{font-size:var(--fs-xs);color:var(--muted)}
.hhow{display:flex;flex-direction:column;gap:14px;padding:6px 4px 0}
.hhow h3{font-size:var(--fs-lg)}
.hflow{list-style:none;margin:0;padding:0;display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:18px;position:relative}
.hflow::before{content:'';position:absolute;top:15px;left:16px;right:16px;height:2px;background:var(--line)}
.hflow li{position:relative;display:flex;flex-direction:column;gap:4px}
.hf-n{width:32px;height:32px;border-radius:50%;display:grid;place-items:center;background:var(--bg);border:2px solid var(--accent);color:var(--accent);font:800 var(--fs-base) var(--display);margin-bottom:6px;position:relative}
.hflow b{font-size:var(--fs-base);font-family:var(--display)}
.hflow p{margin:0;font-size:var(--fs-sm);color:var(--muted);line-height:1.45}
@media (max-width:820px){.hflow{grid-template-columns:minmax(0,1fr);gap:14px}.hflow::before{top:16px;bottom:16px;left:15px;right:auto;width:2px;height:auto}.hflow li{padding-left:46px}.hf-n{position:absolute;left:0;top:-4px;margin:0}}
.fan-wrap{position:relative}
.fan{width:100%;height:auto;display:block;touch-action:pan-y}
.fan .fg{stroke:var(--line);stroke-width:1}
.fan .fa{font:500 var(--fs-sm) var(--body);fill:var(--muted)}
.f-band{fill:var(--accent);opacity:.16}
.f-med{fill:none;stroke:var(--accent);stroke-width:2;stroke-linejoin:round}
.f-me{fill:none;stroke:var(--gold);stroke-width:3;stroke-linejoin:round;stroke-linecap:round}
.f-twin{fill:none;stroke:var(--muted);stroke-width:1.75;stroke-dasharray:6 5}
.f-x{stroke:var(--ink);stroke-width:1;opacity:.35}
.f-hit{fill:transparent;cursor:crosshair}
.fan-tip{position:absolute;top:8px;background:var(--surface);border:1px solid var(--line);border-radius:10px;padding:8px 10px;font-size:var(--fs-sm);display:flex;flex-direction:column;gap:2px;pointer-events:none;box-shadow:0 4px 14px rgba(0,0,0,.12);min-width:170px}
.fan-tip span{display:flex;align-items:center;gap:6px}.fan-tip i{width:10px;height:3px;border-radius:2px;background:var(--c)}.fan-tip .m{color:var(--muted);padding-left:16px}
.legend .lg-band::before{content:'';display:inline-block;width:14px;height:10px;background:var(--accent);opacity:.25;border-radius:2px;margin-right:6px;vertical-align:-1px}
.mc-stats{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}
.mc-stats div{background:var(--bg);border-radius:12px;padding:12px;display:flex;flex-direction:column;gap:2px}
.mc-stats .mid{background:var(--accent-soft)}
.mc-stats small{font-size:var(--fs-sm);color:var(--muted)}.mc-stats b{font:800 var(--fs-lg) var(--display);letter-spacing:-.02em}.mc-stats span{font-size:var(--fs-sm);color:var(--muted)}
@media (max-width:560px){.mc-stats{grid-template-columns:minmax(0,1fr)}.mc-stats div{flex-direction:row;flex-wrap:wrap;align-items:baseline;column-gap:8px}.mc-stats small{flex:1 0 100%}}
.luck{display:flex;flex-direction:column;gap:6px}
.luck-top{display:flex;flex-wrap:wrap;justify-content:space-between;gap:4px 12px;font-size:var(--fs-base)}.luck-top span{color:var(--muted);font-size:var(--fs-sm)}
.luck-bar{position:relative;height:12px;border-radius:6px;background:linear-gradient(90deg,var(--danger-soft),var(--bg) 50%,var(--accent-soft))}
.luck-bar i{position:absolute;top:-5px;width:6px;height:22px;margin-left:-3px;border-radius:3px;background:var(--gold);box-shadow:0 0 0 2px var(--surface)}
.luck-ends{display:flex;justify-content:space-between;font-size:var(--fs-xs);color:var(--muted)}
.mc-facts{margin:0;padding-left:20px;display:flex;flex-direction:column;gap:8px}
.modebar{display:flex;flex-wrap:wrap;gap:4px 12px;align-items:center;font-size:var(--fs-sm);color:var(--muted);margin-top:8px}
.chip.opt-chip{border-style:dashed}
.advhead{margin-bottom:6px}.advhead h3{font-size:var(--fs-md)}.advhead p{margin:4px 0 0}
.pick-adv{opacity:.85}
.lesson-card{border-left:5px solid var(--gold)}
.lesson-card h2{font-size:var(--fs-md);line-height:1.3}
.digdeep{gap:8px}
.fold{border:1px solid var(--line);border-radius:12px;background:var(--bg)}
.fold>summary{cursor:pointer;list-style:none;display:flex;flex-wrap:wrap;align-items:baseline;gap:2px 10px;padding:14px 16px;min-height:48px;font-weight:700}
.fold>summary::-webkit-details-marker{display:none}
@media (max-width:560px){.fold>summary{display:grid;grid-template-columns:18px minmax(0,1fr);column-gap:6px}.fold>summary .fs-s{grid-column:2}}
.fold>summary::before{content:'+';font:800 var(--fs-md) var(--display);color:var(--accent);width:16px}
.fold[open]>summary::before{content:'–'}
.fold>summary .fs-t{font-family:var(--display);font-size:var(--fs-base)}
.fold>summary .fs-s{font-weight:400;font-size:var(--fs-sm);color:var(--muted)}
.fold>summary:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:12px}
.fold>section{border:0;border-top:1px solid var(--line);border-radius:0 0 12px 12px}
.prevstage{margin:0 0 10px}.prevstage .linkbtn{font-weight:700;font-size:var(--fs-sm);text-decoration:none}.prevstage .linkbtn:hover{text-decoration:underline}
.tv-back{display:flex;flex-direction:column;gap:6px;border-top:1px solid var(--line);padding-top:14px;margin-top:4px}.tv-back .btn{align-self:flex-start}.tv-back .btn.warn{background:var(--danger);border-color:var(--danger)}.tv-back .muted{font-size:var(--fs-sm)}
.layout.solo{grid-template-columns:minmax(0,1fr);max-width:900px;margin:0 auto}
.home .lede{font-size:var(--fs-md)}
.hmenu{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,200px),1fr));gap:10px}
.hbtn{display:flex;align-items:center;gap:12px;text-align:left;padding:14px 16px;border-radius:14px;border:1px solid var(--line);background:var(--surface);color:var(--ink);cursor:pointer;font:inherit;min-height:64px}
.hbtn:hover{border-color:var(--accent)}
.hbtn .ic{flex:none;width:22px;height:22px;color:var(--accent)}
.hbtn span{display:flex;flex-direction:column;gap:2px}.hbtn small{color:var(--muted);font-size:var(--fs-sm)}
.hbtn.primary{background:var(--accent);border-color:var(--accent);color:var(--surface)}
.hbtn.primary .ic,.hbtn.primary small{color:var(--surface)}.hbtn.primary small{opacity:.85}
.hsteps{list-style:none;margin:0;padding:0;display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,190px),1fr));gap:12px}
.hsteps li{display:flex;gap:12px;background:var(--bg);border-radius:12px;padding:14px}
.hsteps p{margin:2px 0 0;font-size:var(--fs-sm);color:var(--muted)}
.hsteps li{padding:12px}
.hfoot{margin:0;font-size:var(--fs-sm);color:var(--muted)}
.hlife{display:flex;gap:0;overflow-x:auto;padding:8px 0 4px;position:relative}
.hstage{flex:1 0 110px;display:flex;flex-direction:column;align-items:center;text-align:center;gap:4px;position:relative;padding:0 4px}
.hstage::before{content:'';position:absolute;top:20px;left:-50%;right:50%;height:2px;background:var(--line);z-index:0}
.hstage:first-child::before{display:none}
.hstage .badge{position:relative;z-index:1}
.hstage b{font-size:var(--fs-sm)}.hstage small{font-size:var(--fs-xs);color:var(--muted)}
@media (max-width:600px){.hlife{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));row-gap:16px;overflow:visible}.hstage::before{display:none}.hstage{padding:0}}
.hchips{display:flex;flex-wrap:wrap;gap:8px}
.hchips button{background:var(--bg);border:1px solid var(--line);border-radius:99px;padding:6px 12px;font:inherit;font-size:var(--fs-sm);color:var(--ink);cursor:pointer}
.hchips button:hover{border-color:var(--accent);color:var(--accent)}
.hgsearch input{width:100%;font:inherit;font-size:var(--fs-base);padding:10px 14px;border-radius:12px;border:1px solid var(--line);background:var(--surface);color:var(--ink)}
.hgsearch input:focus{outline:2px solid var(--accent);outline-offset:1px}
.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
.hgletters{display:flex;flex-wrap:wrap;gap:4px}
.hgletters button{min-width:34px;height:34px;border-radius:8px;border:1px solid var(--line);background:var(--bg);color:var(--ink);font:600 var(--fs-sm) var(--mono);cursor:pointer}
.hgletters button:hover{border-color:var(--accent);color:var(--accent)}
.hglist{margin:0;display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,320px),1fr));gap:10px}
.hgitem{background:var(--bg);border-radius:12px;padding:12px 14px;scroll-margin:80px;transition:box-shadow .3s}
.hgitem dt{font-weight:700;font-size:var(--fs-base);margin-bottom:4px}
.hgitem dd{margin:0;font-size:var(--fs-sm);line-height:1.5}
.hgex{display:block;margin-top:6px;font-size:var(--fs-sm);color:var(--muted);border-left:3px solid var(--accent);padding-left:8px}
.hgitem.flash{animation:hgflash 1.6s ease}
@keyframes hgflash{0%,40%{box-shadow:0 0 0 3px var(--accent)}100%{box-shadow:0 0 0 0 transparent}}
.hky{margin:0;padding-left:20px;display:flex;flex-direction:column;gap:6px}
.linkbtn{background:none;border:0;padding:10px 0;margin:-10px 0;font:inherit;color:var(--accent);text-decoration:underline;cursor:pointer}
.toggle{display:inline-flex;align-items:center;gap:8px;font-size:var(--fs-sm);cursor:pointer;user-select:none;background:rgba(255,255,255,.1);padding:8px 12px;border-radius:99px}
.toggle input{accent-color:#49C095;width:18px;height:18px}
.realgrp{display:inline-flex;flex-wrap:wrap;align-items:center;gap:2px;background:rgba(255,255,255,.1);border:1px solid rgba(255,255,255,.22);border-radius:22px;padding:3px}
.realgrp .toggle{background:none}
.realinfo{display:inline-flex;align-items:center;gap:6px;font:600 var(--fs-sm) var(--body);color:#F3F8F5;background:rgba(255,255,255,.14);border:0;padding:7px 12px;border-radius:99px;cursor:pointer}
.realinfo:hover,.realinfo[aria-expanded=true]{background:rgba(255,255,255,.24)}
.realinfo .ic{width:17px;height:17px}
.snap-nw b{white-space:nowrap}
.snap-why{display:block;font-size:var(--fs-sm);color:var(--muted);margin-top:4px}
.realhelp{margin-top:12px;max-width:680px;background:rgba(255,255,255,.1);border:1px solid rgba(255,255,255,.22);border-radius:14px;padding:14px 16px;font-size:var(--fs-base);line-height:1.5}
.realhelp p{color:#E4F0EA;margin:0;font-size:var(--fs-base)}.realhelp p+p{margin-top:8px}.realhelp b{color:#fff}
.track{list-style:none;margin:0 0 20px;padding:6px 0 4px;display:flex;gap:0;position:relative;overflow-x:auto;scrollbar-width:thin}
.track li{position:relative;flex:1 0 64px;display:flex;flex-direction:column;align-items:center;gap:6px;text-align:center;font-size:var(--fs-sm);color:var(--muted);min-width:64px;padding:0 4px}
.track li.now .num{color:var(--ink);font-weight:700}
.track li::before{content:"";position:absolute;top:28px;left:-50%;width:100%;height:3px;background:var(--line);z-index:0}
.track li:first-child::before{display:none}
.track li.done::before,.track li.now::before{background:var(--accent)}
.node{position:relative;z-index:1;width:46px;height:46px;border-radius:50%;display:grid;place-items:center;background:var(--surface);border:2px solid var(--line);color:var(--muted)}
.track li.done .node{background:var(--accent-soft);border-color:var(--accent);color:var(--accent)}
.track li.now .node{background:var(--accent);border-color:var(--accent);color:var(--accent-ink);box-shadow:0 0 0 6px var(--accent-soft)}
.track b{font-family:var(--display);font-size:var(--fs-sm);color:var(--ink);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%}
@media (max-width:560px){.track b{font-size:var(--fs-2xs)}.track li span.num{font-size:var(--fs-2xs)}.node{width:36px;height:36px}.track li::before{top:17px}.node .ic{width:18px;height:18px}}
.layout{display:grid;grid-template-columns:minmax(0,1fr) 320px;gap:20px;align-items:start}
@media (max-width:900px){.layout{grid-template-columns:minmax(0,1fr)}}
main{display:flex;flex-direction:column;gap:18px;min-width:0}
.panel{background:var(--surface);border:1px solid var(--line);border-radius:var(--r);padding:22px;min-width:0}
.stack{display:flex;flex-direction:column;gap:14px}
.lede{font-size:var(--fs-md)}
@media (max-width:560px){.lede,.home .lede,.hh-lede,.hero p{font-size:var(--fs-base)}}
.start{display:flex;flex-wrap:wrap;gap:16px 24px;align-items:center;justify-content:space-between}
.sec{display:grid;grid-template-columns:minmax(0,.9fr) minmax(0,1.1fr);gap:22px}
@media (max-width:760px){.sec{grid-template-columns:minmax(0,1fr)}}
.sec-head{display:flex;align-items:center;gap:12px;grid-column:1/-1}
.badge{width:42px;height:42px;border-radius:12px;display:grid;place-items:center;background:var(--accent-soft);color:var(--accent);flex:none}
.learn{background:var(--bg);border-radius:12px;padding:16px;display:flex;flex-direction:column;gap:12px;min-width:0}
.learn p,.learn li{font-size:var(--fs-base)}
.learn h3{font-size:var(--fs-base)}
.tip{border-left:3px solid var(--gold);padding-left:12px;font-size:var(--fs-base)}
.fields{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px;align-content:start}
.field{display:flex;flex-direction:column;gap:4px;min-width:0}
.field label{font-weight:700;font-size:var(--fs-sm)}
.field small{color:var(--muted);font-size:var(--fs-sm)}
.inp{display:flex;align-items:center;border:1px solid var(--line);border-radius:9px;background:var(--surface);padding:0 10px}
.inp span{color:var(--muted);font-family:var(--mono);font-size:var(--fs-sm)}
.inp input{flex:1;min-width:0;border:0;background:transparent;color:var(--ink);font:500 var(--fs-base) var(--mono);padding:10px 6px;outline:none}
.inp:focus-within{border-color:var(--accent);box-shadow:0 0 0 3px var(--accent-soft)}
.example{display:inline-block;font-size:var(--fs-xs);font-family:var(--mono);background:var(--gold-soft);color:var(--ink);padding:3px 9px;border-radius:99px}
.bars{display:flex;flex-direction:column;gap:8px}
.bar-row{display:grid;grid-template-columns:110px minmax(0,1fr) auto;gap:10px;align-items:center;font-size:var(--fs-sm)}
.bar-row .track-b{height:14px;background:var(--sunk);border-radius:99px;overflow:hidden}
.bar-row .track-b i{display:block;height:100%;border-radius:99px;background:var(--c,var(--accent));transition:width .4s}
.bar-row .money{font-size:var(--fs-sm);text-align:right;white-space:normal}
@media (max-width:420px){.bar-row{grid-template-columns:80px minmax(0,1fr) auto}}
.stackbar{display:flex;height:22px;border-radius:7px;overflow:hidden;background:var(--sunk)}
.stackbar i{display:block;height:100%;background:var(--c);transition:flex-grow .4s}
.legend{display:flex;flex-wrap:wrap;gap:6px 16px;font-size:var(--fs-sm);color:var(--muted)}
.legend span::before{content:"";display:inline-block;width:11px;height:11px;border-radius:3px;margin-right:6px;vertical-align:-1px;background:var(--c)}
.gauge{position:relative;height:16px;border-radius:99px;background:linear-gradient(90deg,var(--accent) 0 30%,var(--gold) 30% 50%,var(--danger) 50% 100%);opacity:.9}
.gauge b{position:absolute;top:-5px;width:4px;height:26px;border-radius:2px;background:var(--ink);transform:translateX(-2px)}
.gauge-l{display:flex;justify-content:space-between;font-size:var(--fs-xs);color:var(--muted);font-family:var(--mono)}
.mkt{display:flex;align-items:center;gap:4px;height:70px;border-bottom:1px solid var(--line);position:relative}
.mkt div{flex:1;display:flex;flex-direction:column;justify-content:flex-end;height:100%;align-items:center;min-width:0}
.mkt-wrap{display:grid;grid-template-rows:70px 70px;}
.mkt-up{display:flex;align-items:flex-end;gap:4px}
.mkt-dn{display:flex;align-items:flex-start;gap:4px;border-top:1px solid var(--line)}
.mkt-up i,.mkt-dn i{flex:1;display:block;border-radius:3px;min-width:0}
.mkt-up i{background:var(--accent)} .mkt-dn i{background:var(--danger)}
.mkt-l{display:flex;gap:4px;font:var(--fs-2xs) var(--mono);color:var(--muted)}
.mkt-l span{flex:1;text-align:center;min-width:0;overflow:visible;white-space:nowrap}
@media (max-width:700px){.mkt-l.many{padding-bottom:16px}.mkt-l.many span:nth-child(even){transform:translateY(16px)}}
.q{display:flex;flex-direction:column;gap:10px;padding-top:18px;border-top:1px solid var(--line)}
.q:first-of-type{border-top:0;padding-top:0}
.q legend{font-family:var(--display);font-weight:700;font-size:var(--fs-md);padding:0}
fieldset{border:0;margin:0;padding:0;min-width:0}
.opts{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,200px),1fr));gap:8px}
@media (min-width:600px){.opts:has(>.opt:nth-child(4):last-child){grid-template-columns:repeat(2,minmax(0,1fr))}}
.opt{position:relative;display:flex;flex-direction:column;gap:4px;border:1.5px solid var(--line);border-radius:12px;padding:12px;cursor:pointer;background:var(--surface);transition:border-color .15s,background .15s}
.opt input{position:absolute;opacity:0;pointer-events:none}
.opt b{font-size:var(--fs-base)}
.opt .hint{font-size:var(--fs-sm);color:var(--muted)}
.otag{display:inline-block;vertical-align:2px;margin-left:4px;padding:1px 8px;border-radius:99px;border:1px solid var(--accent);background:var(--accent-soft);color:var(--ink);font:600 var(--fs-xs) var(--body);white-space:nowrap}
.otag.alt{background:var(--sunk);border-color:var(--line)}
.rsuggest{display:flex;gap:10px;align-items:flex-start;margin:0;padding:10px 12px;border-radius:10px;background:var(--accent-soft);font-size:var(--fs-sm)}
.rsuggest .ic{flex:none;width:18px;height:18px;margin-top:2px;color:var(--accent)}
.mixbar{display:flex;gap:2px;height:10px;margin-top:4px;border-radius:5px;overflow:hidden;background:var(--surface)}
.mixbar i{display:block;min-width:4px}
.mixkey{display:flex;flex-wrap:wrap;gap:2px 12px;font-size:var(--fs-xs);color:var(--muted)}
.mixkey span{display:inline-flex;align-items:center;gap:5px;white-space:nowrap}
.mixkey i{width:9px;height:9px;border-radius:2px;flex:none}
.rmix{margin:0 0 14px;padding:12px;border:1px solid var(--line);border-radius:12px}
.rmixrow{display:grid;grid-template-columns:96px minmax(0,1fr);column-gap:10px;align-items:center;margin-top:8px}
.rmixrow .mixbar{margin:0;height:14px}.rmixrow .mixkey{grid-column:2}
.rmixlab{font-weight:700;font-size:var(--fs-sm);grid-row:span 2}
.opt:hover{border-color:var(--accent)}
.opt:has(input:checked){border-color:var(--accent);background:var(--accent-soft)}
.opt:has(input:focus-visible){box-shadow:0 0 0 3px var(--accent-soft);border-color:var(--accent)}
.opt.off{opacity:.5;cursor:not-allowed}
.opt.off:hover{border-color:var(--line)}
.explain:empty{display:none}
.figmore{display:inline}.figmore summary{display:inline;padding:0;font-weight:600}.figmore[open]{display:block;margin-top:4px}.figmore[open] summary{display:block;margin-bottom:4px}
.exmore summary{padding:4px 0;font-size:var(--fs-sm)}
.exbody{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,220px),1fr));gap:10px;margin-top:6px}
.exbody>div{background:var(--bg);border-radius:10px;padding:12px 14px;font-size:var(--fs-sm)}
.explain .eyebrow{display:block;margin-bottom:4px}
.explain .cost .eyebrow{color:var(--gold-ink)}
.opt:has(input[type=checkbox]:checked){border-color:var(--gold);background:var(--gold-soft)}
.story{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:0}
.story li{display:grid;grid-template-columns:36px 44px minmax(0,1fr);gap:10px;align-items:center;padding:6px 0;position:relative}
.story li::before{content:"";position:absolute;left:17px;top:0;bottom:0;width:2px;background:var(--line)}
.story li:first-child::before{top:50%}.story li:last-child::before{bottom:50%}
.story .node{position:relative;z-index:1;width:36px;height:36px;border-radius:50%;display:grid;place-items:center;background:var(--surface);border:2px solid var(--line);color:var(--accent)}
.story .node .ic{width:18px;height:18px}
.story .num{font-weight:600;color:var(--muted)}
.goallist{display:flex;flex-direction:column;gap:6px;font-size:var(--fs-sm)}
.goallist div{display:flex;gap:8px;align-items:flex-start}
.goallist .ic{width:18px;height:18px}
.g-ok{color:var(--accent)}.g-no{color:var(--danger)}.g-wait{color:var(--muted)}
.term{font:inherit;color:inherit;background:none;border:0;padding:0;border-bottom:1.5px dotted var(--accent);cursor:help}
.term:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
.gloss{position:absolute;z-index:50;background:var(--surface);color:var(--ink);border:1px solid var(--line);border-radius:12px;padding:12px 14px;font-size:var(--fs-sm);box-shadow:0 8px 30px rgba(0,0,0,.18);max-width:300px}
.autobar{position:sticky;top:env(safe-area-inset-top,0px);z-index:20;display:flex;flex-wrap:wrap;gap:10px;align-items:center;justify-content:space-between;background:var(--gold-soft);border:1px solid var(--gold);border-radius:12px;padding:10px 14px;margin-bottom:12px;font-weight:700}
.autobar .btn{padding:8px 14px;font-size:var(--fs-sm)}
.fundcmp{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,200px),1fr));gap:10px;margin:4px 0 10px}
.fundcmp>div{background:var(--bg);border-radius:10px;padding:12px 14px;display:flex;flex-direction:column;gap:6px;min-width:0}
.learn .fundcmp>div{background:var(--surface);border:1px solid var(--line)}
.fundcmp h4{margin:0;font-family:var(--display);font-size:var(--fs-base)}
.fundcmp p{margin:0;font-size:var(--fs-sm)}
.fundcmp .fee{margin-top:auto;padding-top:6px;border-top:1px solid var(--line);font-weight:700;color:var(--gold-ink)}
.fundline{font-size:var(--fs-sm);margin:0}
.fundline+.fundline{margin-top:10px}
.acctcards .sw{display:inline-block;width:10px;height:10px;border-radius:3px;margin-right:7px;vertical-align:1px}
.acctcards .ex{margin-top:8px;padding-top:8px;border-top:1px solid var(--line);font-size:var(--fs-sm)}
.rchart{display:flex;flex-direction:column;gap:10px}
.rrow{display:grid;grid-template-columns:minmax(110px,150px) minmax(0,1fr) 64px;gap:10px;align-items:center}
.rrow.rhead{font-size:var(--fs-xs);color:var(--muted);font-family:var(--mono)}
.rlab{display:flex;flex-direction:column;font-size:var(--fs-sm);line-height:1.25}.rlab small{color:var(--muted);font-size:var(--fs-xs)}
.rbar{position:relative;height:38px}
.rbar i{position:absolute;display:block}
.rzero{top:0;bottom:12px;width:1px;background:var(--muted)}
.rrange{top:6px;height:12px;border-radius:6px;background:var(--c-k401,var(--accent));opacity:.35}
.ravg{top:2px;height:20px;width:3px;margin-left:-1px;background:var(--accent);border-radius:2px}
.rbar em{position:absolute;bottom:0;font-style:normal;font-size:var(--fs-2xs);color:var(--muted);font-family:var(--mono);transform:translateX(-10%);white-space:nowrap}
.rbar em.r{transform:translateX(-90%)}
.rend{font-family:var(--mono);font-size:var(--fs-sm);text-align:right}
.rquiz{background:var(--surface);border:1px solid var(--line);border-radius:12px;padding:12px 14px;display:flex;flex-direction:column;gap:10px}
.rquiz h4{margin:0;font-size:var(--fs-base)}
.rq{border:0;margin:0;padding:0;display:flex;flex-direction:column;gap:4px}
.rq legend{font-weight:700;font-size:var(--fs-sm);margin-bottom:4px;padding:0}
.rq label{display:flex;gap:8px;align-items:center;font-size:var(--fs-sm);cursor:pointer}
.rq input{accent-color:var(--accent)}
.rq-out{font-size:var(--fs-sm);display:flex;flex-wrap:wrap;gap:8px;align-items:center}
.rlab .rrng{display:none}
@media (max-width:520px){.rrow{grid-template-columns:100px minmax(0,1fr) 50px;gap:6px}.rlab small{display:none}.rlab small.rrng{display:block}.rbar em{display:none}.rbar{height:24px}.rbar-h{font-size:0}.rbar-h::after{content:'Bad year to great year';font-size:var(--fs-xs)}}
.nsteps{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:12px;counter-reset:none}
.nstep{background:var(--bg);border-radius:12px;padding:14px 16px;display:flex;flex-direction:column;gap:8px;border-left:4px solid var(--accent)}
.nstep.done{opacity:.6;border-left-color:var(--line)}
.nstep.done h3{text-decoration:line-through}
.nhead{display:flex;align-items:flex-start;gap:10px}
.nhead h3{flex:1;margin:0;font-size:var(--fs-md);line-height:1.3}
.nnum{flex:none;width:28px;height:28px;border-radius:50%;background:var(--accent);color:var(--surface);display:grid;place-items:center;font-weight:700;font-family:var(--mono);font-size:var(--fs-sm)}
.ndone{flex:none;display:flex;align-items:center;gap:6px;padding:8px 4px;margin:-8px -4px;font-size:var(--fs-sm);color:var(--muted);cursor:pointer;white-space:nowrap}
.ndone input{accent-color:var(--accent);width:18px;height:18px}
.ngame{margin:0;font-size:var(--fs-sm);color:var(--muted)}
.nstep ul{margin:0;padding-left:20px;display:flex;flex-direction:column;gap:4px}
.nstep ul li{font-size:var(--fs-base)}
.nlinks{display:flex;flex-wrap:wrap;gap:8px}
.nlinks a{display:inline-flex;align-items:center;gap:6px;font-weight:700;font-size:var(--fs-sm);color:var(--accent);text-decoration:none;border:1px solid var(--line);border-radius:999px;padding:6px 12px;background:var(--surface)}
.nlinks a .ic{width:14px;height:14px}
.nsrc{display:grid;gap:6px;margin-top:4px}
.nsrc-h{font-size:var(--fs-xs);font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:var(--muted)}
.nsrc .nlinks a{flex-direction:column;align-items:flex-start;gap:1px;padding:8px 14px}
.norg{font-weight:600;font-size:var(--fs-xs);color:var(--muted);letter-spacing:.02em}
.nlab{display:inline;font-weight:700}.nlab .ic{vertical-align:-2px;margin-left:2px}
.nsrc-note{font-size:var(--fs-sm)}
.carehide{display:none!important}
.payoff{display:flex;gap:12px;align-items:flex-start;padding:14px 16px;border-radius:14px;background:var(--accent-soft);border:1px solid var(--accent)}
.payoff>.ic{flex:none;width:24px;height:24px;color:var(--accent);margin-top:2px}
.payoff.ok{background:var(--sunk);border-color:var(--line)}
.payoff-k{display:block;font-size:var(--fs-xs);font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:var(--muted)}
.payoff-n{display:block;font:800 clamp(28px,5vw,36px)/1.1 var(--display);letter-spacing:-.02em;margin:2px 0 6px}
.payoff p{margin:0}
.stratlist{margin:0;padding-left:20px;display:grid;gap:6px}
.stratlist .sw{display:inline-block;width:10px;height:10px;border-radius:2px;margin-right:6px;vertical-align:0}
.riskpref{display:flex;flex-wrap:wrap;gap:8px;align-items:stretch}
.rp-h{flex-basis:100%;font-size:var(--fs-xs);font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:var(--muted)}
.rp{flex:1 1 150px;display:flex;flex-direction:column;align-items:flex-start;gap:2px;min-height:48px;padding:10px 12px;border:1.5px solid var(--line);border-radius:12px;background:var(--surface);color:var(--ink);font:700 var(--fs-sm) var(--body);cursor:pointer;text-align:left}
.rp small{font-weight:400;color:var(--muted);font-size:var(--fs-xs)}
.rp.on{border-color:var(--accent);background:var(--accent-soft)}
.rp:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
.tblwrap{overflow-x:auto}
.strattbl{width:100%;border-collapse:collapse;font-size:var(--fs-sm)}
.strattbl th,.strattbl td{padding:8px 10px;border-bottom:1px solid var(--line);text-align:right;white-space:nowrap}
.strattbl th:first-child{text-align:left}
.strattbl thead th{font-size:var(--fs-xs);color:var(--muted);font-weight:600;white-space:normal;vertical-align:bottom}
.strattbl tr.you th,.strattbl tr.you td{color:var(--muted)}
.strattbl .sw{display:inline-block;width:10px;height:10px;border-radius:2px;margin-right:8px;vertical-align:0}
#nextSteps{scroll-margin-top:96px}
b.money,span.money{white-space:nowrap}
@media (max-width:560px){
body.inner .hero{padding:18px 18px 16px}
body.inner .hero .hero-row>.stack>p{display:none}
body.inner .hero h1{font-size:30px}
.sm-hide{display:none}
.nhead{flex-wrap:wrap}
.nhead h3{flex:1 1 calc(100% - 44px)}
.ndone{margin-left:36px}
}
.nsrc .nlinks a{border-radius:12px;text-align:left;line-height:1.3}
.tosteps{align-self:flex-start;margin-top:4px}
.db-nw{display:flex;flex-wrap:wrap;align-items:baseline;gap:6px 12px;font-size:var(--fs-sm);color:var(--muted)}.db-nw b{color:var(--ink);font-size:var(--fs-md)}
.db-choices{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:8px}
.db-choices li{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:4px 14px;padding:10px 12px;border-radius:10px;background:var(--bg);border-left:4px solid var(--line);font-size:var(--fs-sm)}
.db-choices li.good{border-left-color:var(--accent)}.db-choices li.life{border-left-color:var(--c-roth)}.db-choices li.life .db-eff{color:var(--muted)}.db-choices li.bad{border-left-color:var(--danger)}
.db-choices .db-q{color:var(--muted)}.db-choices .db-a{font-weight:700}
.db-choices .db-eff{grid-column:1/-1;font-size:var(--fs-sm)}
.db-choices li.good .db-eff strong{color:var(--accent)}.db-choices li.bad .db-eff strong{color:var(--danger)}
.db-small li{padding:6px 10px;font-size:var(--fs-sm)}
@media (max-width:560px){.db-choices li{grid-template-columns:minmax(0,1fr)}}
@media (max-width:560px){.db-head .stats{grid-template-columns:repeat(2,minmax(0,1fr))}.db-head .stat .money{font-size:var(--fs-base)}}
.wi{grid-column:1/-1;display:flex;flex-direction:column;gap:8px;margin-top:2px}
.wi-btn{font-size:var(--fs-sm);font-weight:700;text-decoration:none;align-self:flex-start}.db-moment .wi-btn{color:var(--ink);text-decoration:underline;text-underline-offset:3px}.wi-btn:hover{text-decoration:underline}
.wi-opts{display:flex;flex-wrap:wrap;gap:6px;align-items:center;font-size:var(--fs-sm)}
.wi-opts .chip{flex:0 1 auto;max-width:100%;white-space:normal;text-align:left;line-height:1.3}
.whatif{display:flex;flex-direction:column;gap:8px;background:var(--surface);border:1px solid var(--line);border-radius:10px;padding:12px}
.whatif p{font-size:var(--fs-sm)}
.badge.warn{background:var(--danger-soft);color:var(--danger)}
.surprise .lede strong{color:var(--danger)}
.surprise .stats{grid-template-columns:repeat(3,minmax(0,1fr))}.surprise .stat{padding:10px}.surprise .stat .money{font-size:var(--fs-base)}.surprise .stat .money small{display:block;font-size:var(--fs-xs);color:var(--muted)}
.db-two{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,260px),1fr));gap:12px}
.db-col{border-radius:12px;padding:14px 16px;display:flex;flex-direction:column;gap:8px}
.db-col.good{background:var(--accent-soft)}.db-col.bad{background:var(--danger-soft)}
.db-col h3{font-size:var(--fs-base)}.db-col ol{margin:0;padding-left:20px;display:flex;flex-direction:column;gap:8px;font-size:var(--fs-sm)}
.db-col .db-q{font-weight:700}
.db-moments{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:12px}
.db-moment{display:flex;flex-direction:column;gap:6px;padding:14px 16px;border-radius:12px;border:1px solid var(--line);border-left-width:4px}
.db-moment.good{border-left-color:var(--accent);background:var(--accent-soft)}
.db-moment.bad{border-left-color:var(--danger);background:var(--danger-soft)}
.dbm-head{display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:10px;align-items:start}
.dbm-head h3{margin:0;font-size:var(--fs-md)}
.dbm-n{display:inline-grid;place-items:center;width:28px;height:28px;border-radius:50%;background:var(--surface);font:700 var(--fs-sm) var(--display)}
.dbm-amt{font:800 var(--fs-lg) var(--display);white-space:nowrap}
.db-moment.good .dbm-amt{color:var(--accent)}.db-moment.bad .dbm-amt{color:var(--danger)}
.dbm-q,.dbm-eff{margin:0}.dbm-q{font-size:var(--fs-sm)}
@media (max-width:480px){.dbm-head{grid-template-columns:auto minmax(0,1fr)}.dbm-amt{grid-column:2}}
.db-evs{display:flex;flex-direction:column;gap:6px}
.db-chips{display:flex;flex-wrap:wrap;gap:6px}
.db-chips span{font-size:var(--fs-sm);padding:4px 10px;border-radius:12px;border:1px solid var(--line);background:var(--surface)}
.db-chips span.good{border-color:var(--accent)}.db-chips span.bad{border-color:var(--danger)}
.agepick{margin-top:12px;max-width:520px}
.agepick label{display:flex;justify-content:space-between;gap:10px;font-size:var(--fs-base);margin-bottom:6px}
.agepick label b{font-family:var(--display);font-size:var(--fs-lg)}
.agepick input{width:100%;accent-color:var(--accent)}
.agepick .ticks{display:flex;justify-content:space-between;font-size:var(--fs-xs);color:var(--muted);font-family:var(--mono)}
.fundcmp.four{grid-template-columns:repeat(auto-fit,minmax(min(100%,260px),1fr))}
.isl .sugg{font-size:var(--fs-sm);color:var(--muted);margin:-2px 0 6px}
.insbox{background:var(--bg);border-radius:12px;padding:14px 16px;display:flex;flex-direction:column;gap:14px;margin-top:4px}
.isl label{display:flex;justify-content:space-between;gap:8px;flex-wrap:wrap;font-size:var(--fs-sm);margin-bottom:6px}
.isl input[type=range]{width:100%;accent-color:var(--accent)}
.isl .ticks{display:flex;justify-content:space-between;font-size:var(--fs-xs);color:var(--muted);font-family:var(--mono,monospace)}
.insout{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px}
.insout .big{font-size:var(--fs-lg)}
.insbars{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:8px;height:130px;margin-top:6px}
.insbars .ib{display:flex;flex-direction:column;justify-content:flex-end;align-items:center;gap:4px;min-width:0}
.insbars i{display:block;width:100%;max-width:44px;background:var(--line);border-radius:4px 4px 0 0}
.insbars .on i{background:var(--accent)}
.insbars .ibv{font-size:var(--fs-xs);color:var(--muted)}.insbars .on .ibv{color:var(--ink);font-weight:700}
.insbars .ibl{font-size:var(--fs-xs);color:var(--muted)}
.qlearn{margin:2px 0 8px}
.more summary{cursor:pointer;font-weight:700;color:var(--accent);padding:8px 0}
.tbtn{all:unset;display:flex;flex-direction:column;align-items:center;gap:6px;cursor:pointer;border-radius:12px;padding:0 4px}
.tbtn:hover .node{border-color:var(--accent);transform:scale(1.06)}
.tbtn:focus-visible{outline:3px solid var(--accent);outline-offset:2px}
.node{transition:transform .15s}
.turnview{position:fixed;inset:0;z-index:50;background:rgba(10,20,24,.55);display:flex;align-items:flex-start;justify-content:center;padding:calc(env(safe-area-inset-top,0px) + 24px) 16px 24px;overflow-y:auto}
.tv-card{width:min(720px,100%);box-shadow:0 20px 60px rgba(0,0,0,.25)}
.tv-head{display:flex;justify-content:space-between;align-items:flex-start;gap:12px}
.picks{display:grid;gap:6px}
.pick{display:grid;grid-template-columns:minmax(0,1.2fr) minmax(0,1fr);gap:12px;padding:8px 0;border-bottom:1px solid var(--line);font-size:var(--fs-sm)}
.pick span{color:var(--muted)}
@media (max-width:520px){.pick{grid-template-columns:1fr;gap:2px}}
.tv-ev{font-size:var(--fs-sm)}
.snap{padding:0;overflow:hidden}
#turn{scroll-margin-top:12px}
@media (max-width:900px){#turn{scroll-margin-top:64px}}
.snap-sum{list-style:none;display:flex;align-items:center;gap:16px;padding:18px 22px;cursor:pointer}
.snap-sum::-webkit-details-marker{display:none}
.snap-t{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}
.snap-k{display:flex;flex-wrap:wrap;gap:4px 18px;font-size:var(--fs-sm);color:var(--muted);margin-top:4px}
.snap-k b{color:var(--ink);font-weight:600}
.snap-k b.neg{color:var(--danger)}
.snap-k .snap-nw{display:flex;flex-wrap:wrap;align-items:baseline;gap:0 6px;flex-basis:100%;white-space:nowrap}
.snap-k .snap-nw b{font-family:var(--display);font-size:var(--fs-lg);font-weight:800;letter-spacing:-.02em}
.snap-more{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)}
.chev{display:grid;place-items:center;width:36px;height:36px;border-radius:50%;background:var(--sunk);transition:transform .2s}
.chev .ic{transform:rotate(90deg)}
.snap[open] .chev{transform:rotate(180deg)}
.snap-body{padding:0 22px 22px}
.snap .stats{grid-template-columns:repeat(auto-fit,minmax(128px,1fr))}
.snap .stat .money{font-size:var(--fs-md)!important}
.ring{position:relative;width:72px;height:72px;flex:none;display:grid;place-items:center}
.ring svg{position:absolute;inset:0;width:100%;height:100%}
.ring b{font:700 var(--fs-md) var(--display);line-height:1;margin-top:-6px}
.ring small{position:absolute;bottom:15px;font-size:var(--fs-2xs);font-family:var(--mono);text-transform:uppercase;letter-spacing:.02em;color:var(--muted)}
.stepper{display:flex;flex-direction:column;gap:10px;position:sticky;top:calc(env(safe-area-inset-top,0px));z-index:5;background:var(--surface);margin:0 -22px;padding:10px 22px;border-bottom:1px solid var(--line)}
.pbar{height:6px;border-radius:99px;background:var(--sunk);overflow:hidden}
.pbar i{display:block;height:100%;background:var(--accent);border-radius:99px;transition:width .3s}
.chips{display:flex;gap:6px;overflow-x:auto;scrollbar-width:none;padding-bottom:2px}
.chips::-webkit-scrollbar{display:none}
.chip{flex:none;font:600 var(--fs-sm) var(--body);border:1.5px solid var(--line);background:var(--surface);color:var(--muted);border-radius:99px;padding:6px 12px;cursor:pointer}
.chip.seen{color:var(--ink);border-color:var(--accent-soft);background:var(--accent-soft)}
.chip.on{background:var(--accent);border-color:var(--accent);color:var(--accent-ink)}
.chip:focus-visible{outline:3px solid var(--accent);outline-offset:2px}
.qn{display:inline-grid;place-items:center;width:28px;height:28px;border-radius:50%;background:var(--accent-soft);color:var(--accent-strong,var(--ink));font:700 var(--fs-sm) var(--display);margin-right:10px;vertical-align:2px}
.qstep .q{border-top:0;padding-top:4px}
.enter{animation:stepIn .28s ease-out}
@keyframes stepIn{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none}}
.actionbar{position:sticky;bottom:0;z-index:6;display:flex;align-items:center;gap:10px;justify-content:flex-end;padding:12px 0 calc(12px + env(safe-area-inset-bottom,0px));background:linear-gradient(to top,var(--bg) calc(100% - 14px),transparent);flex-wrap:wrap}
.actionbar .btn{white-space:nowrap}
@media (max-width:480px){.actionbar .btn{padding:12px 16px}}
.actionbar .stepcount{flex:1;text-align:center;font:600 var(--fs-sm) var(--mono);color:var(--muted)}
.actionbar .btn:first-child:disabled{opacity:.4;cursor:default}
.pick-b{all:unset;box-sizing:border-box;display:grid;grid-template-columns:minmax(0,1.2fr) minmax(0,1fr) auto;gap:12px;align-items:center;padding:10px 4px;border-bottom:1px solid var(--line);cursor:pointer;font-size:var(--fs-sm);width:100%}
.pick-b span{color:var(--muted)}
.pick-b em{font-style:normal;font-size:var(--fs-sm);color:var(--accent);font-weight:700}
.pick-b:hover{background:var(--bg)}
.pick-b:focus-visible{outline:3px solid var(--accent)}
@media (max-width:520px){.pick-b{grid-template-columns:1fr auto}.pick-b span{grid-column:1/-1}}
.opt{padding-right:40px}
.opt::after{content:"";position:absolute;top:12px;right:12px;width:18px;height:18px;border-radius:50%;border:2px solid var(--line);background:var(--surface);transition:all .15s}
.opt:has(input[type=checkbox])::after{border-radius:5px}
.opt:has(input:checked)::after{border-color:var(--accent);background:radial-gradient(circle,var(--accent-ink) 0 3px,var(--accent) 4px)}
.opt:has(input[type=checkbox]:checked)::after{background:var(--accent) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='3.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M5 12l5 5 9-10'/%3E%3C/svg%3E") center/12px no-repeat}
.opt.off::after{display:none}
.lesson-nav{display:flex;gap:6px;overflow-x:auto;scrollbar-width:none;scroll-margin-top:12px}
.lesson-nav::-webkit-scrollbar{display:none}
.ltab{flex:none;display:inline-flex;align-items:center;gap:8px;font:600 var(--fs-sm) var(--body);border:1.5px solid var(--line);background:var(--surface);color:var(--muted);border-radius:12px;padding:9px 14px;cursor:pointer}
.ltab .ic{width:18px;height:18px}
.ltab.on{border-color:var(--accent);color:var(--ink);background:var(--accent-soft)}
.ltab:focus-visible{outline:3px solid var(--accent);outline-offset:2px}
.lesson-foot{grid-column:1/-1;display:flex;justify-content:space-between;gap:10px;flex-wrap:wrap;border-top:1px solid var(--line);padding-top:16px}
.mstat{display:none}
@media (max-width:900px){.mstat:not([hidden]){display:flex;position:sticky;top:calc(env(safe-area-inset-top,0px));z-index:7;justify-content:space-between;gap:10px;background:var(--surface);border:1px solid var(--line);border-radius:12px;padding:8px 14px;margin-bottom:12px;font-size:var(--fs-sm);color:var(--muted);box-shadow:0 4px 14px rgba(0,0,0,.06)}
.mstat b{color:var(--ink)} .mstat .m-nw b{font-family:var(--display);font-size:var(--fs-md);font-weight:800} .mstat .m-nw b.neg{color:var(--danger)} .mstat:not([hidden]){align-items:center} .stepper{top:calc(env(safe-area-inset-top,0px) + 46px)}}
@media (prefers-reduced-motion:reduce){.enter{animation:none}}
#fileToast{position:fixed;left:50%;bottom:18px;transform:translate(-50%,20px);width:max-content;max-width:min(92vw,520px);padding:12px 16px;border-radius:12px;background:var(--ink);color:var(--bg);font-size:var(--fs-sm);line-height:1.4;box-shadow:0 8px 24px rgba(0,0,0,.25);opacity:0;pointer-events:none;transition:opacity .2s,transform .2s;z-index:60}
#fileToast.show{opacity:1;transform:translate(-50%,0)}
#fileToast.bad{border-left:4px solid var(--danger)}
.hero .hero-note{margin:0;font-size:var(--fs-xs);line-height:1.45;opacity:.85}
.resetbar{display:flex;flex-wrap:wrap;align-items:center;gap:8px 14px;margin-top:28px;padding-top:18px;border-top:1px solid var(--line);font-size:var(--fs-sm)}
.resetbar .btn.warn{border-color:var(--danger);color:var(--danger)}
.donut{display:flex;flex-wrap:wrap;align-items:center;gap:16px 28px}
.donut svg{width:min(210px,100%);height:auto;flex:none}
.donut .arc{transition:stroke-width .15s}
.donut .arc:hover{stroke-width:36}
.d-big{font:700 var(--fs-lg) var(--mono);fill:var(--ink)}
.d-sub{font:500 var(--fs-2xs) var(--body);fill:var(--muted)}
.d-legend{list-style:none;padding:0;margin:0;display:grid;gap:7px;flex:1 1 220px;min-width:0}
.d-legend li{display:grid;grid-template-columns:12px minmax(0,1fr) auto 42px;gap:10px;align-items:center;font-size:var(--fs-sm)}
.d-legend i{width:12px;height:12px;border-radius:3px;background:var(--c)}
.d-legend b{font-weight:600;text-align:right}
.d-legend em{font-style:normal;color:var(--muted);font:500 var(--fs-sm) var(--mono);text-align:right}
.oo{display:grid;grid-template-columns:1fr 1fr;gap:12px}
@media (max-width:640px){.oo{grid-template-columns:1fr}}
.oo-col{border-radius:12px;padding:14px;min-width:0}
.oo-col.own{background:var(--accent-soft)}
.oo-col.owe{background:var(--danger-soft)}
.oo-h{display:flex;justify-content:space-between;align-items:baseline;gap:8px;font:700 var(--fs-base) var(--display);padding-bottom:8px;border-bottom:1px solid var(--line)}
.oo-h b{font-size:var(--fs-md)}
.oo-col ul{list-style:none;margin:8px 0 0;padding:0;display:grid;gap:7px}
.oo-col li{display:grid;grid-template-columns:minmax(0,1fr) minmax(50px,.8fr) auto;gap:10px;align-items:center;font-size:var(--fs-sm)}
.oo-bar{height:8px;border-radius:99px;background:var(--surface);overflow:hidden}
.oo-bar i{display:block;height:100%;border-radius:99px}
.oo-col li b{font-weight:600;text-align:right}
.oo-eq{display:flex;flex-wrap:wrap;align-items:baseline;justify-content:center;gap:6px 12px;font-size:var(--fs-base);color:var(--muted);padding:10px;border:1px dashed var(--line);border-radius:12px}
.oo-eq b{color:var(--ink);font-size:var(--fs-md)}
.oo-eq b.neg{color:var(--danger)} .oo-eq b.pos{color:var(--accent)}
.gate.warnonly{background:var(--gold-soft)}
#live:disabled{opacity:.45;cursor:not-allowed;filter:none}
.gate{background:var(--danger-soft);border-radius:12px;padding:14px 16px;display:flex;flex-direction:column;gap:10px}
.gate .btns .btn{padding:8px 14px;font-size:var(--fs-sm)}
.noloans{grid-column:1/-1;max-width:460px}
.custom{background:var(--bg);border-radius:12px;padding:14px}
.spendq{display:flex;flex-direction:column;gap:10px}
.spendq input[type=range]{width:100%;accent-color:var(--accent)}
.spend-row{display:flex;flex-wrap:wrap;gap:10px 16px;align-items:center}
.note{font-size:var(--fs-sm);color:var(--muted);display:flex;gap:8px;align-items:flex-start}
.revisit{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,300px),1fr));gap:12px}
.rv{border:1px solid var(--line);border-radius:12px;padding:14px;display:flex;flex-direction:column;gap:10px;min-width:0}
.rv h3{font-size:var(--fs-base)}
.rv-row{grid-template-columns:minmax(0,1.3fr) minmax(0,1fr) auto}
.rv-row span:first-child{font-size:var(--fs-sm)}
.rv-row.mine span:first-child{font-weight:700}
.rv-row em{font-style:normal;font:600 var(--fs-2xs) var(--mono);text-transform:uppercase;letter-spacing:.06em;color:var(--accent);margin-left:4px}
.rv-v{font-size:var(--fs-sm)}
.rv-v.neg strong{color:var(--danger)}
.btns{display:flex;flex-wrap:wrap;gap:10px}
.btn{font:700 var(--fs-base) var(--body);border-radius:11px;padding:13px 22px;border:1.5px solid var(--accent);background:var(--accent);color:var(--accent-ink);cursor:pointer;display:inline-flex;align-items:center;gap:8px}
.btn:hover{filter:brightness(1.07)}
.btn{text-decoration:none}
.btn.ghost{background:transparent;color:var(--ink);border-color:var(--line)}
.btn.ghost:hover{border-color:var(--accent)}
.btn:focus-visible,.toggle input:focus-visible{outline:3px solid var(--accent);outline-offset:2px}
.ledger{display:grid;grid-template-columns:1fr auto;gap:5px 16px;font-size:var(--fs-base)}
.ledger .money{text-align:right}
.ledger .total{font-weight:700;border-top:1px solid var(--line);padding-top:6px;margin-top:2px}
.gap-foot{margin:0;font-size:var(--fs-sm)}
.leg-dash{color:var(--muted)}
.legend .leg-dash::before{display:none}
.imp{display:grid;gap:14px}
.imp-row{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:6px 16px;align-items:center}
.imp-q{display:flex;flex-direction:column;gap:2px;font-size:var(--fs-sm);min-width:0}
.imp-q span{color:var(--muted)}
.imp-viz{display:grid;grid-template-columns:minmax(0,1fr) 84px;gap:10px;align-items:center}
.imp-bar{position:relative;height:16px;border-radius:8px;background:var(--sunk)}
.imp-bar::after{content:"";position:absolute;left:50%;top:-3px;bottom:-3px;width:2px;margin-left:-1px;background:var(--line)}
.imp-bar i{position:absolute;top:0;bottom:0}
.imp-bar i.good{left:50%;background:var(--accent);border-radius:0 8px 8px 0}
.imp-bar i.bad{right:50%;background:var(--danger);border-radius:8px 0 0 8px}
.imp-bar i.flat{left:50%;width:8px;margin-left:-4px;border-radius:4px;background:var(--muted)}
.imp-amt{text-align:right;font-weight:700;font-size:var(--fs-sm);white-space:nowrap}
@media (max-width:560px){.imp-row{grid-template-columns:minmax(0,1fr)}}
.lcards{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,200px),1fr));gap:10px}
.lcard{display:flex;flex-direction:column;gap:6px;padding:14px;border-radius:12px;background:var(--sunk)}
.lc-n{font:800 var(--fs-lg)/1.1 var(--display);color:var(--ink)}
.lcard p{margin:0;font-size:var(--fs-sm)}
.lesson{display:grid;grid-template-columns:30px minmax(0,1fr);gap:10px;align-items:start}
.lesson .n{width:30px;height:30px;border-radius:50%;display:grid;place-items:center;background:var(--accent-soft);color:var(--accent-strong,var(--ink));font:700 var(--fs-sm) var(--display)}
.lesson p{font-size:var(--fs-base)}
.lesson strong{font-family:var(--display)}
.events{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,240px),1fr));gap:10px}
.ev{border-radius:12px;padding:14px;display:flex;flex-direction:column;gap:6px;border:1.5px solid var(--line);background:var(--surface)}
.ev.bad{border-color:var(--danger);background:var(--danger-soft)}
.ev.good{border-color:var(--accent);background:var(--accent-soft)}
.ev.star{border-color:var(--gold);background:var(--gold-soft)}
.ev.life{border-color:var(--c-roth)}
.ev-top{display:flex;gap:10px;align-items:center}
.ev-top .ic{color:var(--danger)}
.ev.good .ev-top .ic{color:var(--accent)}
.ev.star .ev-top .ic{color:var(--gold)}
.ev.life .ev-top .ic{color:var(--c-roth)}
.ev h3{font-size:var(--fs-base)}
.ev p{font-size:var(--fs-sm)}
.ev .eyebrow{font-size:var(--fs-2xs)}
.alert{background:var(--danger-soft);border-radius:12px;padding:14px 16px;font-size:var(--fs-base);display:flex;gap:10px;align-items:flex-start}
.alert .ic{color:var(--danger)}
.okay{background:var(--accent-soft);border-radius:12px;padding:14px 16px;font-size:var(--fs-base);display:flex;gap:10px;align-items:flex-start}
.okay .ic{color:var(--accent)}
.delta{display:flex;flex-wrap:wrap;gap:8px 32px;align-items:baseline}
.big{font-family:var(--mono);font-weight:600;font-size:clamp(28px,5vw,40px);letter-spacing:-.02em}
aside{position:sticky;top:calc(env(safe-area-inset-top,0px) + 12px)}
@media (max-width:900px){aside{position:static}}
.sheet{display:grid;grid-template-columns:auto 1fr auto;gap:4px 8px;font-size:var(--fs-sm);align-items:center}
.sheet .h{grid-column:1/-1;margin-top:8px}
.sheet .money{text-align:right}
.sheet .dot{width:10px;height:10px;border-radius:3px;background:var(--c)}
.nw{display:flex;flex-direction:column;gap:2px;border-top:2px solid var(--ink);margin-top:10px;padding-top:10px}
.nw b{font-family:var(--display);font-size:var(--fs-md)}
.nw .money{font-family:var(--display);font-size:48px;font-weight:800;letter-spacing:-.02em;line-height:1.1;font-variant-numeric:tabular-nums;color:var(--ink)}
.nw .money.neg{color:var(--danger)}
.nw .money.long{font-size:42px}.nw .money.xlong{font-size:36px}
@media (max-width:900px){.nw .money{font-size:52px}.nw .money.long{font-size:46px}.nw .money.xlong{font-size:40px}}
@media (max-width:420px){.nw .money{font-size:40px}.nw .money.long{font-size:32px}.nw .money.xlong{font-size:28px}}
svg.chart{width:100%;height:auto;display:block}
svg.chart text{font-family:var(--mono);font-size:var(--fs-2xs);fill:var(--muted)}
.goal{display:flex;flex-direction:column;gap:8px;padding:24px;border-radius:var(--r);background:radial-gradient(120% 140% at 100% 0%,var(--gold-soft),var(--surface));border:1px solid var(--gold)}
.goal .big{color:var(--gold-ink)}
.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:10px}
.stat{border:1px solid var(--line);border-radius:12px;padding:12px;display:flex;flex-direction:column;gap:4px}
.stat .ic{color:var(--accent)}
.stat .money{font-size:var(--fs-lg);font-weight:600}
.stat small{color:var(--muted);font-size:var(--fs-sm)}
footer{margin-top:28px;color:var(--muted);font-size:var(--fs-sm)}
footer details{max-width:85ch}
footer summary{cursor:pointer;font-weight:700;padding:12px 0}
footer ul{margin:8px 0}
@media (prefers-reduced-motion:reduce){*{transition:none!important}}
</style>
<div id="nojs" style="margin:16px auto;max-width:560px;padding:18px 20px;border-radius:14px;border:2px solid #1f6b4f;background:#eef6f1;color:#12332a;font:16px/1.5 system-ui,-apple-system,sans-serif">
<strong style="display:block;font-size:18px;margin-bottom:6px">This game needs to open in a web browser</strong>
It looks like this file opened in a preview, which can't run the game. On a computer, open the file with Chrome, Safari, Edge or Firefox. On a phone, open the game's published web page instead of the file.
</div>
<div class="wrap">
<header class="hero">
<canvas id="heroArt" aria-hidden="true"></canvas>
<div class="hero-row">
<div class="stack" style="gap:8px">
<span class="eyebrow">Kentucky edition · for college students and young adults new to money</span>
<h1>The Long Game</h1>
<p>Live your whole financial life before it happens. Make the big money decisions with your own numbers, and race a twin who never invests.</p>
<p class="hero-note">For education only. Not financial, investment, tax or legal advice. Nothing you enter leaves your device.</p>
</div>
<div class="hero-ctl"><button type="button" class="homebtn" id="goGloss"><svg class="ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 5a2 2 0 0 1 2-2h13v16H6a2 2 0 0 0-2 2zM4 21V5M8 7h7M8 11h7"/></svg> Glossary</button><button type="button" class="homebtn" id="goHome" hidden><svg class="ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M3 11l9-7 9 7v9a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z"/></svg> Home</button><span class="realgrp"><label class="toggle"><input type="checkbox" id="realToggle"> Show in today's dollars (recommended)</label><button type="button" class="realinfo" id="realInfo" aria-expanded="false" aria-controls="realHelp" aria-label="What does show in today's dollars mean?"><svg class="ic" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M9.5 9.2a2.6 2.6 0 0 1 5 .9c0 1.7-2.5 2.2-2.5 3.9M12 17.2v.1"/></svg><span id="realInfoT">What does this mean?</span></button></span></div>
<div class="realhelp" id="realHelp" hidden></div>
</div>
</header>
<div class="autobar" id="autobar" hidden><span>Sample life with preset choices. Read each screen, then press Continue.</span><span class="btns"><button class="btn" id="contAuto" type="button">Continue</button><button class="btn ghost" id="skipAuto" type="button">Skip to the end</button><button class="btn ghost" id="stopAuto" type="button">Stop and play myself</button></span></div>
<div class="mstat" id="mstat" hidden></div>
<ol class="track" id="track"></ol>
<p class="note" id="trackHint" hidden style="margin:-12px 0 16px">Tap any finished age above to see the choices you made.</p>
<div class="turnview" id="turnView" hidden><div class="tv-card panel stack" role="dialog" aria-modal="true" aria-label="Your choices for this turn"></div></div>
<div id="gloss" class="gloss" role="tooltip" hidden></div>
<div class="layout">
<main id="main"></main>
<aside id="side"></aside>
</div>
<div class="resetbar"><button type="button" class="btn ghost" id="saveFile">Save to a file</button><button type="button" class="btn ghost" id="openFile">Open a saved file</button><input type="file" id="fileIn" accept=".json,application/json" hidden><button type="button" class="btn ghost" id="resetAll">Start over</button><span class="muted" id="resetNote">Clears your game and numbers and goes back to the beginning.</span></div>
<footer>
<details>
<summary>How the math works, and sources</summary>
<ul>
<li>The game runs month by month from your age to 65. Investments follow random market years. You pick a risk level from conservative (40% stocks) to aggressive (100% stocks), and every mix gets safer after 50 and again after 65. All returns are before inflation. You pick the market assumption at setup: <b>historical</b> (the default) uses long-run US averages of about 10% a year for stocks and 5% for bonds, so the growth mix (80% stocks while young) earns about 9% a year before inflation, or about 6% after; <b>cautious</b> uses about 8% for stocks and 4% for bonds, so the growth mix earns about 7% before inflation, or about 4% after. Mixes earn less, with smaller swings, as they get safer with age. Every risk level faces the same random market years, scaled to its share of stocks. The typical level for your age follows a typical target-date fund (about 90% stocks until 40, about 50% at 65, 30% by 72); the US and international split shown inside each mix (about 60/40 of the stocks) is for illustration. Savings sit in a high-yield savings account earning 3.5% a year (online banks pay about 4% in late 2026; the national average savings account pays about 0.6%). Prices rise 3% a year and homes gain 3% a year.</li>
<li>Taxes use 2026 rules for a single filer, with brackets rising with inflation: federal brackets and the $16,100 standard deduction, Social Security and Medicare (7.65%), Kentucky's 3.5% income tax with its $3,360 standard deduction, and the local payroll tax where you work: 2.25% in Lexington, 2.2% for Louisville residents, about 1% in a typical smaller county.</li>
<li>401(k): your employer matches dollar for dollar up to 5% of pay. 2026 limits: $24,500 a year, plus $8,000 from age 50 ($11,250 at ages 60 to 63). Withdrawals in retirement are taxed at an estimated 12% federal rate, plus Kentucky's 3.5% only on withdrawals above $31,110 a year per person, since Kentucky excludes that much retirement income and doesn't tax Social Security.</li>
<li>Roth IRA: 2026 limit of $7,500 a year ($8,600 from age 50), shrinking for single filers earning $153,000 to $168,000. Brokerage: no limits; dividend taxes trim about 0.3% a year and gains are taxed at 15% when sold.</li>
<li>Student loans are treated as unsubsidized, with a 6-month grace period and a 10-year plan. Card minimums are interest plus 1% of the balance, at least $25. Cars are replaced every 12 years.</li>
<li>Starting salaries are about 80% of the Lexington-area median for each job (Bureau of Labor Statistics, May 2023) and grow about 4.5% a year to 35, 3.5% to 50, then 3%. Everyday costs start at $1,400 a month, and spending grows as income grows: 35 cents of every dollar of household pay above $50,000 goes to a bigger lifestyle. Credit card debt is capped at your limit or 30% of household income. A partner adds an income of about $52,000 and about $1,200 a month in shared costs (food, health care, a second car and more). Because household spending also rises with household income, a partner's total added spending is usually closer to $2,000 to $2,700 a month. That matches federal survey data: in 2024, two-person households spent about $32,000 a year more than one-person households (BLS Consumer Expenditure Survey). Each child costs about $1,200 a month until 18 for everything except childcare. Childcare until kindergarten is your choice: family help about $200 a month, home daycare about $650 or a daycare center about $850 per child (Kentucky averages from Child Care Aware), or a nanny about $2,700 a month for the family. Each child's four years of in-state public college cost about $55,000. All are rough estimates in today's dollars.</li>
<li>Lifespan: Kentuckians who reach 65 live to about 82 on average, among the lowest in the country (CDC). Smoking takes about 10 years and quitting before 40 wins back about 90% of them (New England Journal of Medicine, 2013). Regular exercise adds about 3 years and inactivity takes about 2, both rough estimates. A random health-luck factor adds or subtracts up to 4 years.</li><li>Retirement: work income stops at 65. You spend 80%, 100% or 120% of what you spent in your last working year, rising with inflation, and draw from savings, then brokerage, then your 401(k) (taxed about 15%), then your Roth. Social Security is estimated at 40% of your final salary at full retirement age 67, capped near the program's maximum, with 70% at 62, 86.7% at 65 and 124% at 70. The 4% rule is a rough guide to how much you can spend.</li>
<li>Long-term care: about half of people who reach 65 need paid long-term care. In the game, half of players do, in their last two years, at about $72,000 a year in today's dollars. Real costs vary widely; a private nursing home room often costs more.</li><li>This game teaches how money decisions add up. It is not personal financial advice.</li>
<li>Fonts: Bricolage Grotesque, Atkinson Hyperlegible and IBM Plex Mono, loaded from Google Fonts under the SIL Open Font License. Google Fonts is the only outside service this page uses, and nothing you enter is sent to it. Without an internet connection the game still works, using your device's built-in fonts. No outside code libraries are used.</li>
</ul>
<p>Sources: <a href="https://www.bls.gov/oes/2023/may/oes_30460.htm" target="_blank" rel="noopener">BLS wages, Lexington-Fayette area</a> · <a href="https://www.lexingtonky.gov/working/business-licensing-taxes/occupational-license-fee-rates-current-forms" target="_blank" rel="noopener">Lexington payroll tax</a> · <a href="https://louisvilleky.gov/sites/default/files/2024-12/ol-3d_instructions_2025.pdf" target="_blank" rel="noopener">Louisville payroll tax</a> · <a href="https://kaco.org/articles/data-brief-2026-county-occupational-taxes/" target="_blank" rel="noopener">Kentucky county payroll taxes</a> · <a href="https://investor.vanguard.com/investor-resources-education/iras/roth-ira-income-limits" target="_blank" rel="noopener">Roth IRA limits</a> · <a href="https://www.alliantcreditunion.org/money-mentor/contribution-limits-for-iras-and-401ks" target="_blank" rel="noopener">401(k) limits</a></p>
</details>
</footer>
</div>
<script>
(function(){var n=document.getElementById('nojs');if(n)n.remove()})();
// ENGINE START
const C={SELL:.06,INFL:.03,RET:.07,MKT_MEAN:.08,MKT_SD:.15,CASH:.035,HOME:.03,CARDEP:.15,DRAG:.003,LTCG:.15,RET_TAX:.13,
FED_SD:16100,KY_SD:3360,KY:.035,SS_CAP:184500,MATCH:.05,LIVING:1400,PARTNER_PAY:52000,PARTNER_COST:1200,KID_COST:1200,KID_BASE:1000,KID_COLLEGE:55000,K529:200,CAR_LIFE:144,CAR_PRICE:24000,BASE_LIFE:82,MIP:.0055,KY_RET_EXCL:31110,FED_RET:.12,LTC_COST:6000,PRE_MEDICARE:800,LTC_ODDS:.5,HSA_SELF:4400,HSA_FAM:8750,HSA_EMP:500,PPO_EXTRA:80,HDHP_ROUTINE:50,CREEP:.35,CREEP_FLOOR:50000,SMOKE_COST:230,GYM_COST:40,
K_LIMIT:24500,K_CU:8000,K_CU6063:11250,ROTH:7500,ROTH_CU:1100,ROTH_LO:153000,ROTH_HI:168000,P_EVENT:.042,
BRK:[[12400,.10],[50400,.12],[105700,.22],[201775,.24],[256225,.32],[640600,.35],[Infinity,.37]]};
const CITIES={lex:{label:'Lexington',rate:.0225,rent:1,pay:1},lou:{label:'Louisville',rate:.022,rent:1,pay:1.02},town:{label:'A smaller Kentucky town',rate:.01,rent:.75,pay:.9}};
const CAREERS=[
{id:'marketing',label:'Marketing specialist',median:58700},
{id:'accountant',label:'Accountant',median:66620},
{id:'nurse',label:'Registered nurse',median:80500},
{id:'analyst',label:'Management analyst',median:84885},
{id:'engineer',label:'Mechanical engineer',median:99530},
{id:'software',label:'Software developer',median:103290}].map(c=>({...c,salary:Math.round(c.median*0.8/100)*100}));
// How pay moves in each field: real raise above inflation early in a career, how much it swings, bonus odds and size, layoff risk
const PAY={
marketing:{real:.018,sd:.025,bonus:.30,size:.05,layoff:1.3,desc:'Raises vary a lot by employer. Bonuses are occasional, and layoffs are more common when budgets get cut.'},
accountant:{real:.02,sd:.015,bonus:.45,size:.06,layoff:.7,desc:'Steady raises, especially after earning a CPA. Bonuses are common at firms.'},
nurse:{real:.012,sd:.01,bonus:.15,size:.03,layoff:.4,desc:'Very steady raises and strong job security. Bonuses are rare, but extra shifts can add pay.'},
analyst:{real:.022,sd:.025,bonus:.50,size:.10,layoff:1,desc:'Raises and bonuses depend on performance, so they swing more year to year.'},
engineer:{real:.02,sd:.018,bonus:.40,size:.07,layoff:.8,desc:'Solid, fairly steady raises with regular bonuses.'},
software:{real:.028,sd:.035,bonus:.60,size:.12,layoff:1.4,desc:'Big raises and frequent bonuses, but pay swings more and layoffs come in waves.'},
steady:{real:.012,sd:.01,bonus:.15,size:.03,layoff:.5,desc:'Small, predictable raises, rare bonuses and good job security.'},
average:{real:.02,sd:.02,bonus:.35,size:.06,layoff:1,desc:'Typical raises with some ups and downs, and a bonus about every third year.'},
volatile:{real:.03,sd:.04,bonus:.55,size:.15,layoff:1.5,desc:'Big raises and big bonuses in good years, small ones in bad years, and higher layoff risk.'}};
const PAY_STYLE={steady:'Steady',average:'Average',volatile:'High risk, high reward'};
function payOf(s){return PAY[s.career==='custom'?s.payStyle:s.career]||PAY.average}
function careerLabel(s){return s.career==='custom'?s.careerTitle:(CAREERS.find(c=>c.id===s.career)||{label:''}).label}
const DECK=[
{id:'laptop',when:'school',w:2,cost:900,title:'Your laptop dies the week before finals',lesson:'Small emergencies are the most common kind. A $1,000 starter emergency fund handles most of them.'},
{med:true,id:'teeth',when:'school',w:1,cost:1600,title:'Your wisdom teeth have to come out',lesson:'Dental work is often only partly covered by insurance, even on a parent\'s plan.'},
{id:'parking',when:'school',w:1,cost:250,title:'A semester of parking tickets',lesson:'Fees and fines are easy to ignore until they add up.'},
{id:'scholar',when:'school',w:1,cost:-1500,title:'You win a department scholarship',lesson:'Many scholarships get few applicants. Applying every semester pays.'},
{id:'trans',when:'any',w:2,cost:2500,title:'Your car needs a new transmission',lesson:'Car repairs are among the most common surprise expenses. Older cars need a repair fund.'},
{id:'wreck',when:'any',w:2,cost:1000,title:'A fender bender. You owe the insurance deductible',lesson:'Your deductible is what you pay before insurance kicks in. A higher deductible lowers your premium, but you need cash ready to cover it.'},
{id:'phone',when:'any',w:2,cost:400,title:'Your phone screen shatters',lesson:'Small, frequent costs are why a buffer in checking matters.'},
{med:true,id:'er',when:'any',w:2,cost:1500,title:'A trip to the emergency room',lesson:'Even with insurance, you pay your deductible and copays first.'},
{med:true,id:'surgery',when:'grad',w:1,cost:5000,title:'You need surgery',lesson:'Health plans cap what you pay each year with an out-of-pocket maximum. Knowing yours tells you how big a medical cushion you need.'},
{med:true,id:'dental',when:'any',w:1,cost:1200,title:'You crack a tooth and need a crown',lesson:'Dental insurance often covers only part of major work.'},
{id:'wedding',when:'grad',w:1,cost:1500,title:'You\'re in a friend\'s destination wedding',lesson:'Not every surprise is bad news. Planned fun still needs room in the budget.'},
{id:'family',when:'grad',w:1,cost:3000,title:'A parent needs help with a medical bill',lesson:'Helping family is a real cost many people face. Savings let you help without going into debt.'},
{id:'vet',when:'any',w:1,cost:1100,title:'Your dog eats a sock. Emergency vet visit',lesson:'Pets bring surprise bills. A small pet fund smooths them out.'},
{id:'idtheft',when:'any',w:1,cost:600,title:'Someone steals your identity',lesson:'Freezing your credit with the three credit bureaus is free and blocks new accounts in your name.'},
{id:'ticket',when:'any',w:1,cost:450,title:'A speeding ticket raises your car insurance',lesson:'Tickets cost twice: the fine, then higher insurance premiums for years.'},
{id:'storm',when:'any',home:false,w:1,cost:2000,title:'A storm floods your apartment and ruins your things',lesson:'Your landlord\'s insurance covers the building, not your belongings. Renters insurance is inexpensive and covers your stuff.'},
{id:'tornado',when:'any',home:true,w:1,cost:2500,title:'A tornado damages your roof',lesson:'Homeowners insurance covers storm damage, but you pay the deductible first.'},
{id:'flood',when:'any',home:true,w:.6,cost:9000,title:'Flash flooding fills your basement',lesson:'Standard homeowners insurance does not cover floods. Flood insurance is a separate policy, and many eastern Kentucky families in the 2022 floods did not have it.'},
{id:'roof',when:'any',home:true,w:1,cost:12000,title:'Your roof needs replacing',lesson:'A common rule is to set aside 1% to 2% of your home\'s value each year for repairs.'},
{id:'hvac',when:'any',home:true,w:1,cost:7000,title:'Your furnace dies in January',lesson:'Furnaces and AC units last roughly 15 to 20 years. Homeowners should plan for replacing them.'},
{med:true,id:'braces',when:'grad',kids:true,w:1,cost:5500,title:'Your child needs braces',lesson:'Kids bring big surprise costs. Orthodontics is often only partly covered by dental insurance.'},
{id:'tip',when:'grad',w:1,gamble:{amt:2000,lose:.75,down:.7,up:1},title:'A coworker swears by a hot stock, so you buy $2,000 of it',lesson:'One company can crash while the market rises. Index funds spread your money across hundreds of companies so no single bet can sink you.'},
{id:'crypto',when:'any',w:.8,gamble:{amt:1500,lose:.6,down:.8,up:1.5},title:'A friend talks you into $1,500 of a new crypto coin',lesson:'Speculation is closer to gambling than investing. Only put in money you could lose completely.'},
{id:'bnpl',when:'any',w:1,cost:1350,title:'You use buy now, pay later for a new TV and miss a payment',lesson:'Splitting a purchase into payments makes it feel cheaper. Late fees and stacking several plans at once is how people get caught.'},
{id:'payday',when:'any',w:.7,broke:true,cost:600,title:'Short on rent, you take a $500 payday loan',lesson:'Kentucky lets payday lenders charge $15 for every $100 borrowed for about two weeks. Rolled over a few times, that works out to an interest rate near 400% a year.'},
{id:'refund',when:'any',w:2,cost:-700,title:'Your tax refund arrives',lesson:'A refund means you overpaid taxes during the year. Saving it beats spending it.'},
{id:'gig',when:'grad',w:1,cost:-2000,title:'A weekend side gig pays off',lesson:'Side income is taxed too, and self-employed earners pay both halves of Social Security and Medicare.'},
{id:'inherit',when:'grad',w:.4,cost:-10000,title:'A grandparent leaves you an inheritance',lesson:'Windfalls do the most good paying off high-interest debt or getting invested.'},
{id:'layoff',when:'work',w:1.5,layoff:true,title:'Your company cuts jobs, including yours',lesson:'Planners suggest saving 3 to 6 months of expenses for job loss. Unemployment benefits replace only part of your pay.'},
{id:'raise',when:'work',w:1.5,raise:.05,title:'You get an unexpected 5% raise',lesson:'If your spending stays the same, the whole raise becomes savings.'},
{id:'paycut',when:'work',w:.6,raise:-.05,title:'Business slows and your pay is cut 5%',lesson:'Income can go down too. Bills you can\'t shrink make cuts hurt more.'}];
function mulberry32(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296}}
function pmt(bal,rate,n){if(bal<=0)return 0;const r=rate/12;return r?bal*r/(1-Math.pow(1+r,-n)):bal/n}
function growthAt(age){return age<35?0.045:age<50?0.035:0.03}
function taxes(sal,k,f,local){
const taxable=Math.max(0,sal-k-C.FED_SD*f);let fed=0,prev=0;
for(const [cap,rate] of C.BRK){const c=cap*f;if(taxable>prev)fed+=(Math.min(taxable,c)-prev)*rate;prev=c}
const fica=Math.min(sal,C.SS_CAP*f)*0.062+sal*0.0145,ky=Math.max(0,sal-k-C.KY_SD*f)*C.KY,loc=sal*(local==null?.0225:local);
return {fed,fica,ky,local:loc,total:fed+fica+ky+loc};
}
function minPayoff(bal,apr){let m=0,int=0;while(bal>0.5&&m<720){const i=bal*apr/12;bal+=i;int+=i;bal-=Math.min(bal,Math.max(25,i+0.01*bal));m++}return {months:m,interest:int}}
function makeSchedule(seed,months){const r=mulberry32(seed),out=[];for(let m=0;m<months;m++){const a=r(),b=r(),c=r();if(a<C.P_EVENT)out.push({m,r:b,r2:c})}return out}
function normals(seed,n){const r=mulberry32(seed),o=[];for(let i=0;i<n;i++){const u=Math.max(1e-9,r()),v=r();o.push(Math.sqrt(-2*Math.log(u))*Math.cos(2*Math.PI*v))}return o}
function uniforms(seed,n){const r=mulberry32(seed),o=[];for(let i=0;i<n;i++)o.push(r());return o}
function makeMarket(seed,years){
const r=mulberry32(seed^0x5bd1e995),out=[];
for(let y=0;y<years;y++){const u=Math.max(1e-9,r()),v=r();out.push(Math.max(-2.6,Math.min(2.6,Math.sqrt(-2*Math.log(u))*Math.cos(2*Math.PI*v))))}
return out;
}
// Portfolio mix gets safer with age: mostly stocks until 50, more bonds after
// Four risk levels. Each gets safer after 50 and again after 65. Growth matches a typical target-date fund.
const RISK={cons:{label:'Conservative',w:[40,30,20],m:[[.06,.08,.057],[.055,.065,.053],[.05,.055,.048]]},
bal:{label:'Balanced',w:[60,45,30],m:[[.07,.11,.064],[.06,.09,.056],[.052,.065,.05]]},
growth:{label:'Growth',w:[80,60,40],m:[[.08,.15,.07],[.065,.11,.06],[.055,.08,.052]]},
aggr:{label:'Aggressive',w:[100,80,60],m:[[.095,.18,.079],[.08,.15,.07],[.065,.11,.06]]}};
// Return assumptions, all BEFORE inflation (prices rise 3% a year).
// 'hist': long-run US history, stocks about 10% and bonds about 5% a year. 'cautious': lower, closer to big firms' 10-year forecasts.
let RET_MODE='hist';
const RET_SB={hist:[.10,.05],cautious:[.079,.042]};
function mixAt(age,risk){const r=RISK[risk]||RISK.growth,i=age<50?0:age<65?1:2,m=r.m[i],w=r.w[i]/100;
if(RET_MODE==='hist'){const flat=RET_SB.hist[1]+(RET_SB.hist[0]-RET_SB.hist[1])*w;return {mean:flat+m[1]*m[1]/2,sd:m[1],flat,w}}
return {mean:m[0],sd:m[1],flat:m[2],w}}
function realR(r){return (1+r)/(1+C.INFL)-1}
function pct1(r){const v=Math.round(r*1000)/10;return (Number.isInteger(v)?v:v.toFixed(1))+'%'}
function retTxt(r){return `${pct1(r)} a year before inflation (about ${pct1(realR(r))} after)`}
// Typical target-date fund stock share by age (Vanguard-style glide path): ~90% to 40, ~50% at 65, 30% by 72
function tdfStock(a){return a<=40?90:a<=65?90-(a-40)*40/25:a<=72?50-(a-65)*20/7:30}
function riskSuggest(age){const t=Math.round(tdfStock(age)),g=Math.round(mixAt(age,'growth').w*100),k=age<72?'growth':'bal';
const alt=age<65&&t-g>=5?'aggr':null;return {k,alt,tdf:t}}
function mixParts(w){const st=Math.round(w*100),us=Math.round(st*.6),intl=st-us;return {us,intl,bd:100-st}}
function mixBar(w,key){const p=mixParts(w),seg=(v,c)=>v?`<i style="flex:${v} 0 0;background:var(${c})"></i>`:'';
return `<span class="mixbar" role="img" aria-label="US stocks ${p.us}%, international stocks ${p.intl}%, bonds ${p.bd}%">${seg(p.us,'--c-k401')}${seg(p.intl,'--c-roth')}${seg(p.bd,'--c-cash')}</span>${key===false?'':`<span class="mixkey"><span><i style="background:var(--c-k401)"></i>US ${p.us}%</span><span><i style="background:var(--c-roth)"></i>Intl ${p.intl}%</span><span><i style="background:var(--c-cash)"></i>Bonds ${p.bd}%</span></span>`}`}
function riskSuggestText(a){const sg=riskSuggest(a),pc=k=>Math.round(mixAt(a,k).w*100);
return `<b>Typical for age ${Math.floor(a)}: ${RISK[sg.k].label}.</b> Target-date funds hold about ${sg.tdf}% stocks at your age${sg.alt?`, between ${RISK[sg.k].label} (${pc(sg.k)}%) and ${RISK[sg.alt].label} (${pc(sg.alt)}%). ${RISK[sg.alt].label} also fits if you'd hold on through a crash.`:`, and ${RISK[sg.k].label} (${pc(sg.k)}%) is the closest mix.`} <span class="muted">A starting point, not personal advice.</span>`}
function riskRet(m,z){return Math.max(-.4,Math.min(.45,m.mean+m.sd*z))}
function mktReturn(s,yr){return riskRet(mixAt(s.startAge+yr,s.risk),s.market[yr])}
function boostRate(s,age,risk){const m=mixAt(age,risk);return m.flat+0.05*m.w/0.8}
function crashDrop(age,risk){return 0.25*mixAt(age,risk).w/0.8}
function invTotal(I){return (I.invest||0)+(I.k401Bal||0)+(I.iraBal||0)+(I.rothBal||0)}
function iraPart(s){return s.k401*(s.iraFrac||0)}
function newState(inp,seed){
return {seed,startAge:inp.age,age:inp.age,gradAge:inp.status==='grad'?inp.age:inp.age+inp.years,month:0,infl:1,flat:false,
cash:inp.checking+inp.savings,k401:(inp.k401Bal||0)+(inp.iraBal||0),iraFrac:(inp.k401Bal||0)+(inp.iraBal||0)>0?(inp.iraBal||0)/((inp.k401Bal||0)+(inp.iraBal||0)):0,roth:inp.rothBal||0,rothBasis:inp.rothBal||0,rothYTD:0,brok:inp.invest,brokBasis:inp.invest,k529:0,home:0,carValue:inp.carValue,carBought:-96,
student:{bal:inp.loans,rate:inp.loanRate/100,pay:0},card:{bal:inp.card,rate:inp.apr/100},
carLoan:{bal:0,rate:0,pay:0},mortgage:{bal:0,rate:0.065,pay:0},
grad:inp.status==='grad',inSchool:inp.status!=='grad',schoolIncome:inp.jobIncome+inp.family,tuitionNet:inp.status==='grad'||inp.tuitionPaid||inp.noLoans?0:Math.max(0,(inp.tuition||0)-(inp.kees||0)),schoolSpend:inp.spend,extraWork:0,extraLoan:0,spendCut:0,graceUntil:-1,
salary:0,career:null,city:'lex',localRate:.0225,rent:0,rentTier:null,carRun:250,carPlan:'keep',kPct:0,lastK:0,savePct:1,order:'smart',rothShare:1,
ltc:mulberry32(seed^0x7f4a7c15)()<C.LTC_ODDS,ltcShown:false,kWdYTD:0,ins:{type:'none'},lifestyle:null,credit:{score:inp.creditScore||680,hist:inp.status==='grad'?Math.min(300,Math.max(60,(inp.age-18)*12)):24,hit:0},fee:.0005,risk:'growth',health:null,hsaPlan:'none',hsa:0,story:[],track:{},limitBase:Math.max(inp.limit||2000,inp.card||0,1000),partner:false,partnerPay:0,kids:[],college:'none',smoke:'never',exercise:'some',luck:Math.round((mulberry32(seed^0x9e3779b9)()-0.5)*8),retired:false,ssClaim:65,spendStyle:1,retireSpend:0,ssMonthly:0,infl65:1,broke:null,
noIncome:0,soldUntil:-1,boostUntil:-1,
yrStart:invTotal(inp),yrContrib:0,yrSpend:0,lastYrSpend:0,ms:{},
totals:{cardInterest:0,studentInterest:0,carInterest:0,mortgageInterest:0,homeCosts:0,match:0,contrib:0,taxes:0,local:0,fun:0,shortfall:0,
rothIn:0,brokIn:0,rothOverflow:0,penalty:0,extraBorrowed:0,extraEarned:0,surprises:0,surpriseCost:0,surpriseToCard:0,windfalls:0,crashTax:0,kidCost:0,collegePaid:0,cars:0,bonus:0,premiums:0,fees:0,gambles:0,hsaIn:0,habits:0,ssPaid:0,unmet:0},
payZ:normals(seed^0x2545f491,90),bonusU:uniforms(seed^0x68e31da4,90),bonusV:uniforms(seed^0x1b873593,90),stageRaises:[],stageBonus:{n:0,amt:0},careerTitle:'',payStyle:'average',
schedule:makeSchedule(seed,(65-inp.age)*12),market:makeMarket(seed,90),sp:0,stageEvents:[],
history:[{age:inp.age,nw:0,f:1}],hit1M:null,hit1MReal:null,mcLog:[],mcI0:invTotal(inp),mcStart:invTotal(inp),mcU0:0,yrGrowth:0};
}
function invested(s){return s.k401+s.roth+s.brok+(s.hsa||0)}
function lifeParts(s){return {base:C.BASE_LIFE,exercise:{low:-2,some:0,high:3}[s.exercise],smoke:{never:0,quit:-1,smoker:-10}[s.smoke],luck:s.luck}}
function lifeExpect(s){const p=lifeParts(s);return p.base+p.exercise+p.smoke}
const SSF={62:.70,65:.867,67:1,70:1.24};
function ssPIA(s){const cap=4000*s.infl;return (Math.min(.4*s.salary/12,cap)+(s.partner?Math.min(.4*s.partnerPay/12,cap):0))}
function ssCompare(pia,death){return [62,65,67,70].map(a=>({age:a,monthly:pia*SSF[a],total:pia*SSF[a]*12*Math.max(0,death-a)}))}
function deathAge(s){return Math.min(99,Math.max(67,lifeExpect(s)+s.luck))}
function debts(s){return s.student.bal+s.card.bal+s.carLoan.bal+s.mortgage.bal}
function netWorth(s){return s.cash+invested(s)+s.k529+s.home+s.carValue+((s.ins&&s.ins.cv)||0)-debts(s)}
function insPayout(s){const i=s.ins;if(!i)return 0;if(i.type==='whole')return Math.max(0,i.face-i.cv);if(i.type==='term'&&s.month<i.start+(i.years||20)*12)return i.face;return 0}
function liquidAfterTax(s){return s.cash+(s.hsa||0)+s.roth+s.k401*(1-C.RET_TAX)+s.brok-C.LTCG*Math.max(0,s.brok-s.brokBasis)}
function afterTax(s){return liquidAfterTax(s)+s.k529+s.home+s.carValue-debts(s)}
function insQuote(s,type){const a=s.age,smk=s.smoke==='smoker';
if(type==='term')return (a<35?25:a<45?45:90)*(smk?3:1);
if(type==='whole')return (a<35?200:a<45?300:450)*(smk?2:1);return 0}
const TERM_YRS=[10,15,20,25,30],TERM_MULT={10:.7,15:.82,20:1,25:1.3,30:1.65};
function termQuote(s,years,face){const a=s.age,base=(a<35?25:a<45?45:a<55?90:190)*(s.smoke==='smoker'?3:1);return base*TERM_MULT[years]*(0.2+0.8*face/500000)}
function insRec(s){return Math.min(2000000,Math.max(250000,Math.round(s.salary/s.infl*10/50000)*50000))}
function insPremium(s){const i=s.ins;if(!i||i.type==='none')return 0;if(i.type==='term'&&s.month>=i.start+(i.years||20)*12)return 0;return i.prem*s.infl}
function buyInsurance(s,type,years,face){if(type==='none'){s.ins={type:'none'};return}
if(type==='term'){years=years||20;face=face||500000;s.ins={type,years,start:s.month,startAge:s.age,f0:s.infl,prem:termQuote(s,years,face),face:face*s.infl,cv:0};return}
s.ins={type,start:s.month,startAge:s.age,prem:insQuote(s,type),face:250000*s.infl,cv:0}}
function creditLabel(sc){return sc>=800?'Exceptional':sc>=740?'Very good':sc>=670?'Good':sc>=580?'Fair':'Poor'}
function mortRate(s){const c=s.credit.score;return c>=760?.061:c>=700?.065:c>=660?.07:c>=620?.076:.085}
function carRate(s,base){const c=s.credit.score;return base+(c>=720?0:c>=660?.025:c>=620?.06:.10)}
function creditStep(s){const cr=s.credit;cr.hist++;const lim=Math.max(1,cardLimit(s)),u=s.card.bal/lim;
const tgt=600+Math.min(90,cr.hist*.4)+(u<.1?80:u<.3?55:u<.5?20:-20)-cr.hit;cr.score=Math.max(300,Math.min(850,cr.score+(tgt-cr.score)*.04));cr.hit*=.99}
function story(s,text,icon){if(!s.flat)s.story.push({age:s.age,text,icon})}
function hsaLimit(s){return (s.partner||s.kids.length?C.HSA_FAM:C.HSA_SELF)*s.infl}
function lifeBase(s){return s.lifestyle!=null?s.lifestyle/12*s.infl:C.LIVING*s.infl+creep(s)}
function suggestLife(s){return Math.round((C.LIVING*s.infl+creep(s))*12/s.infl/500)*500}
function creep(s){if(s.inSchool||s.retired)return 0;return C.CREEP*Math.max(0,(s.salary+(s.partner?s.partnerPay:0))/12-C.CREEP_FLOOR*s.infl/12)}
function cardLimit(s){return Math.max(s.limitBase*s.infl,0.3*(s.salary+(s.partner?s.partnerPay:0)))}
function habitCost(s){return (s.smoke==='smoker'?C.SMOKE_COST:0)+(s.exercise==='high'?C.GYM_COST:0)}
const KID_TOTAL=[0,1.2,2,2.4,3,3.6];
function kidAgeF(age){return age<3?.92:age<6?.95:age<12?.98:age<15?1.05:1.12}
// Paid childcare until kindergarten (age 5), in today's dollars a month. Kentucky averages (Child Care Aware): center about $9,700 a year per infant, home daycare about $7,300; Lexington nanny about $2,735 a month.
const CARE={family:{label:'Family helps',cost:200},home:{label:'Home daycare',cost:650},center:{label:'Daycare center',cost:850},nanny:{label:'Nanny',cost:2700}};
function careCost(s,u5){if(!u5)return 0;const k=s.care||'center';return k==='nanny'?CARE.nanny.cost+300*(u5-1):CARE[k].cost*u5}
function kidCost(s){const live=s.kids.filter(b=>s.month>=b&&s.month<b+216),n=live.length;if(!n)return 0;const share=KID_TOTAL[Math.min(n,5)]/n,u5=live.filter(b=>s.month<b+60).length;return live.reduce((a,b)=>a+C.KID_BASE*share*kidAgeF((s.month-b)/12),0)+careCost(s,u5)}
function kidEst(n){return C.KID_BASE*KID_TOTAL[Math.max(0,Math.min(n,5))]}
function kidAgesText(s){const born=s.kids.filter(b=>s.month>=b).map(b=>Math.floor((s.month-b)/12)),plan=s.kids.length-born.length;if(!s.kids.length)return '';
const ages=born.length?(born.length===1?`1 kid, age ${born[0]}`:`${born.length} kids, ages ${born.slice(0,-1).join(', ')} and ${born[born.length-1]}`):'';
return ages+(born.length&&born.every(a=>a>=18)?' (all grown)':'')+(plan?`${ages?', plus ':''}${plan} more planned`:'')}
function ordinal(n){return ['first','second','third','fourth','fifth','sixth'][n-1]||n+'th'}
function kidsUnder18(s){return s.kids.filter(b=>s.month>=b&&s.month<b+216).length}
function housingCost(s){return s.home>0?s.home*0.02/12+(s.mortgage.bal>1?(s.mip||0):0):s.rent*s.infl}
function fixedNeeds(s){
if(s.inSchool)return Math.max(0,s.schoolSpend-s.spendCut)*s.infl;
return (s.carRun+(s.partner?C.PARTNER_COST:0)+kidCost(s)+habitCost(s)+(s.health==='ppo'?C.PPO_EXTRA*(s.partner||s.kids.length?2:1):0))*s.infl+housingCost(s)+lifeBase(s)+insPremium(s);
}
function efTarget(s){
if(s.inSchool)return 1000*s.infl;
const d=(s.student.bal>0?s.student.pay:0)+(s.carLoan.bal>0?s.carLoan.pay:0)+(s.mortgage.bal>0?s.mortgage.pay:0);
return 3*(fixedNeeds(s)+d);
}
function rothRoom(s){
const f=s.infl,lim=(C.ROTH+(s.age>=50?C.ROTH_CU:0))*f;let frac=1;
if(!s.inSchool){const magi=s.salary-s.lastK*12,lo=C.ROTH_LO*f,hi=C.ROTH_HI*f;frac=magi>=hi?0:magi<=lo?1:(hi-magi)/(hi-lo)}
return Math.max(0,lim*frac-s.rothYTD);
}
function investMoney(s,amt){
if(amt<=0)return;if(s.noInvest){s.cash+=amt;return}s.yrContrib+=amt;
if(s.rothShare>0){const want=amt*s.rothShare,x=Math.min(want,rothRoom(s));s.roth+=x;s.rothBasis+=x;s.rothYTD+=x;s.totals.rothIn+=x;amt-=x;if(want-x>0.01)s.totals.rothOverflow+=want-x}
if(amt>0){s.brok+=amt;s.brokBasis+=amt;s.totals.brokIn+=amt}
}
function payDown(L,amt){const p=Math.min(L.bal,amt);L.bal-=p;if(L.bal<0.005)L.bal=0;return p}
function chargeCard(s,amt){if(!(amt>0))return 0;const room=Math.max(0,cardLimit(s)-s.card.bal),put=Math.min(room,amt),rest=amt-put;s.card.bal+=put;
if(rest>0.5){s.totals.unmet+=rest;s.totals.unpaid=(s.totals.unpaid||0)+rest;s.credit.hit+=40}return put}
function payFrom(s,amt){
const fc=Math.min(s.cash,amt);s.cash-=fc;amt-=fc;
if(amt>0&&s.brok>0){const g=Math.min(s.brok,amt);s.brokBasis*=1-g/s.brok;s.brok-=g;s.yrContrib-=g;amt-=g}
if(amt>0)chargeCard(s,amt);
}
function withdraw(s,amt){
const fc=Math.min(s.cash,amt);s.cash-=fc;amt-=fc;
if(amt>0&&s.brok>0){const gf=Math.max(0,1-s.brokBasis/s.brok),net=1-C.LTCG*gf,g=Math.min(s.brok,amt/net);s.brokBasis*=1-g/s.brok;s.brok-=g;amt-=g*net}
if(amt>0&&s.k401>0){const excl=C.KY_RET_EXCL*(s.partner?2:1),rate=C.FED_RET+(s.kWdYTD>excl?C.KY:0),g=Math.min(s.k401,amt/(1-rate));s.k401-=g;s.kWdYTD=(s.kWdYTD||0)+g;s.totals.retTax=(s.totals.retTax||0)+g*rate;if(s.kWdYTD<=excl)s.totals.kyExcl=(s.totals.kyExcl||0)+g*C.KY;amt-=g*(1-rate)}
if(amt>0&&s.hsa>0){const g=Math.min(s.hsa,amt);s.hsa-=g;amt-=g}
if(amt>0&&s.roth>0){const g=Math.min(s.roth,amt);s.roth-=g;s.rothBasis=Math.min(s.rothBasis,s.roth);amt-=g}
if(amt>0&&s.k529>0){const g=Math.min(s.k529,amt);s.k529-=g;amt-=g}
return amt;
}
function allocate(s,amt){
if(amt<=0)return;const o=s.order;
if(o==='cash'){s.cash+=amt;return}
if(o==='invest'){investMoney(s,amt);return}
if(o==='smart'){let x=Math.min(amt,Math.max(0,efTarget(s)-s.cash));s.cash+=x;amt-=x;x=Math.min(amt,s.card.bal);s.card.bal-=x;amt-=x;investMoney(s,amt);return}
for(const d of [s.card,s.carLoan,s.student].filter(d=>d.bal>0).sort((a,b)=>b.rate-a.rate)){const x=Math.min(amt,d.bal);d.bal-=x;if(d.bal<0.005)d.bal=0;amt-=x;if(amt<=0)break}
investMoney(s,amt);
}
function eligible(s,c){
if(c.when==='school'&&!s.inSchool)return false;
if((c.when==='work'||c.when==='grad')&&s.inSchool)return false;
if(c.when==='work'&&s.noIncome>0)return false;
if(c.home===true&&!(s.home>0))return false;
if(c.home===false&&s.home>0)return false;
if(c.kids&&!kidsUnder18(s))return false;
if(c.broke&&s.cash>800)return false;
if(c.gamble&&s.cash+s.brok<c.gamble.amt*s.infl)return false;
return true;
}
function k401Draw(s,net){if(s.noInvest||!(s.k401>0)||!(net>0))return {net:0,gross:0};const keep=s.age<59.5?0.7:0.8,gross=Math.min(s.k401,net/keep);s.k401-=gross;s.totals.penalty+=gross*(1-keep);s.totals.k401Early=(s.totals.k401Early||0)+gross;return {net:gross*keep,gross}}
function payBig(s,amt,ev,resp){let rest=amt;ev.fromCash=0;ev.toCard=0;ev.k401Gross=0;ev.k401Lost=0;
if(resp==='card'){const tc=chargeCard(s,rest);ev.toCard+=tc;rest-=tc}
if(resp==='k401'){const d=k401Draw(s,rest);ev.k401Gross=d.gross;ev.k401Lost=d.gross-d.net;rest-=d.net}
if(rest>0){const fc=Math.min(Math.max(0,s.cash),rest);s.cash-=fc;ev.fromCash=fc;rest-=fc}
if(rest>0.005){const tc=chargeCard(s,rest);ev.toCard+=tc;rest-=tc}
ev.unpaid=Math.max(0,rest);if(resp==='cut')s.cut={until:s.month+6,amt:amt/6}}
function applyChance(s,c,r2){
const f=s.infl,resp=s.respond&&s.respond[s.month],ev={c,f,resp,age:s.age,amt:0,fromCash:0,toCard:0,months:0,shortBefore:s.totals.shortfall};
if(c.gamble){const g=c.gamble,amt=g.amt*f,win=r2>=g.lose,chg=win?amt*g.up:-amt*g.down;ev.gamble={amt,win,chg};if(chg<0){const fb=Math.min(s.brok,-chg);s.brok-=fb;s.brokBasis=Math.min(s.brokBasis,s.brok);const rest=-chg-fb,fc=Math.min(s.cash,rest);s.cash-=fc;s.card.bal+=rest-fc}else s.cash+=chg;s.totals.gambles+=chg;s.totals.surprises++;return ev}
if(c.med){const plan=s.health||'ppo',mult=plan==='ppo'?.5:1;ev.medPlan=plan;let amt=c.cost*f*mult;ev.full=c.cost*f;if(s.hsa>0){const h=Math.min(s.hsa,amt);s.hsa-=h;ev.fromHSA=h;amt-=h}
ev.amt=amt;payBig(s,amt,ev,resp);s.totals.surpriseCost+=amt+(ev.fromHSA||0);s.totals.surpriseToCard+=ev.toCard;s.totals.surprises++;return ev}
if(c.cost>0){ev.amt=c.cost*f;payBig(s,ev.amt,ev,resp);s.totals.surpriseCost+=ev.amt;s.totals.surpriseToCard+=ev.toCard}
else if(c.cost<0){ev.amt=-c.cost*f;s.cash+=ev.amt;s.totals.windfalls+=ev.amt}
if(c.layoff){ev.months=2+Math.floor(r2*5);s.noIncome=ev.months;ev.amt=s.salary/12*ev.months;if(resp==='cut')s.cut={until:s.month+ev.months,amt:0.35*lifeBase(s)};if(resp==='k401')s.k401Until=s.month+ev.months+1}
if(c.raise){s.salary*=1+c.raise;ev.amt=s.salary}
s.totals.surprises++;return ev;
}
function lifeEvent(s,title,body,lesson,kind='life'){s.stageEvents.push({life:true,kind,title,body,lesson,age:s.age})}
function replaceCar(s){
const f=s.infl,price=C.CAR_PRICE*f,need=Math.max(0,price-s.carValue),keep=Math.min(s.cash,efTarget(s)*0.5);let fromCash=Math.min(Math.max(0,s.cash-keep),need);
const ci=s.totals.cars;if((s.noInvest||s.strat)&&s.mirrorCars&&s.mirrorCars[ci]!=null)fromCash=Math.min(Math.max(0,s.cash),Math.max(0,need-s.mirrorCars[ci]));
const loan=need-fromCash;
s.cash-=fromCash;s.carValue=price;s.carBought=s.month;s.totals.cars++;
let cr=carRate(s,.075);if((s.noInvest||s.strat)&&s.mirrorCarRates&&s.mirrorCarRates[ci]!=null)cr=s.mirrorCarRates[ci];if(!s.flat&&!s.noInvest&&!s.strat){(s.carLog=s.carLog||{})[ci]=loan;(s.carRates=s.carRates||{})[ci]=cr}if(loan>0){s.carLoan={bal:loan,rate:cr,pay:pmt(loan,cr,60)}}
story(s,'Replaced a worn-out car','car');if(!s.flat)lifeEvent(s,'Your car finally gives out',`You replace it with a ${money(price,s.infl)} used car, paid with ${(l=>l.length>1?l.slice(0,-1).join(', ')+' and '+l[l.length-1]:l[0]||'your old car')([price-need>1?`${money(price-need,s.infl)} from your old car`:'',fromCash>=1?`${money(fromCash,s.infl)} of savings`:'',loan>0?`a ${money(loan,s.infl)} loan at ${(cr*100).toFixed(1)}%`:''].filter(Boolean))}.`,'Cars wear out. Setting aside a little each month in a car fund lets you buy the next one with cash instead of a loan.','bad');
}
function yearEnd(s){
s.kWdYTD=0;
const inv=invested(s),growth=inv-s.yrStart-s.yrContrib,yr=Math.floor(s.month/12)-1,mk=yr>=0?mktReturn(s,yr):null;
s.lastYrSpend=s.yrSpend;s.yrSpend=0;
if(!s.flat&&mk!=null&&inv>1000&&!(s.month-12<s.boostUntil)&&!(s.month-12<s.soldUntil)){if(!s.worstYr||mk<s.worstYr.r)s.worstYr={r:mk,age:s.age-1};if(!s.bestYr||mk>s.bestYr.r)s.bestYr={r:mk,age:s.age-1}}
if(!s.flat&&!s.retired){
const ms=s.ms,f=s.infl;
if(!ms.bad&&mk!=null&&mk<-0.1&&inv>1000&&!(s.month-12<s.boostUntil)){ms.bad=1;lifeEvent(s,`A bad year: the market fell ${Math.round(-mk*100)}%`,`Your investments lost value this year. You kept investing anyway.`,'Down years are normal. Since 1926 US stocks have fallen in roughly 1 of every 4 years, and long-term investors who held on still came out ahead.','bad')}
if(!ms.k100&&inv/f>=100000){ms.k100=1;lifeEvent(s,'You passed $100,000 invested',`Your investments are worth ${money(inv,f)}${real?'':` (${money(inv/f,0)} in today's dollars)`}.`,'The first $100,000 is the hardest. After it, growth does more of the work: 7% of $100,000 is $7,000 a year without lifting a finger.','star')}
if(!ms.beat&&s.yrContrib>500&&growth>s.yrContrib){ms.beat=1;lifeEvent(s,'Your money earned more than you put in',`This year you added ${money(s.yrContrib,f)}, and your investments earned ${money(growth,f)} on their own.`,'This is the crossover point. From here, your money is working harder than you are at building wealth.','star')}
const housing=12*(s.home>0?s.mortgage.pay+housingCost(s):s.rent*f);
if(!ms.house&&housing>0&&growth>housing){ms.house=1;lifeEvent(s,'Your investments paid your housing',`They earned ${money(growth,f)} this year, more than the ${money(housing,f)} you spent on housing.`,'Every dollar invested early becomes a worker that pays some of your bills later.','star')}
if(!ms.salary&&s.salary>0&&growth>s.salary){ms.salary=1;lifeEvent(s,'Your investments out-earned your job',`They earned ${money(growth,f)} this year, more than your ${money(s.salary,f)} salary.`,'When your money earns more than your paycheck, work becomes a choice. That is what financial independence means.','star')}
}
if(!s.flat&&s.mcLog){s.mcLog.push({age:s.age-1,flow:inv-(s.mcI0||0)-(s.yrGrowth||0),unmet:s.totals.unmet-(s.mcU0||0),ret:!!s.retired,nonInv:netWorth(s)-inv,nw:netWorth(s),f:s.infl,risk:s.risk||'growth'});s.mcI0=inv;s.mcU0=s.totals.unmet;s.yrGrowth=0}
s.yrStart=inv;s.yrContrib=0;
}
function syncRT(s){const T=s.totals,P=s._tp||(s._tp={}),Rt=s.rt||(s.rt={});for(const k in T){const v=T[k];if(typeof v!=='number')continue;const dd=v-(P[k]||0);if(dd){Rt[k]=(Rt[k]||0)+dd/s.infl;P[k]=v}}}
function realTot(s){syncRT(s);const o={};for(const k in s.totals)o[k]=typeof s.totals[k]==='number'?(s.rt[k]||0)*s.infl:s.totals[k];return o}
function step(s){
while(!s.flat&&s.sp<s.schedule.length&&s.schedule[s.sp].m<=s.month){
const e=s.schedule[s.sp++];if(e.m<s.month)continue;
const pool=DECK.filter(c=>eligible(s,c)),wt=c=>c.layoff&&s.career?c.w*payOf(s).layoff:c.w,tot=pool.reduce((a,c)=>a+wt(c),0);let x=e.r*tot,pick=pool[pool.length-1];
for(const p of pool){if(x<wt(p)){pick=p;break}x-=wt(p)}
if((s.noInvest||s.strat)&&s.mirror&&s.mirror[e.m]){const mp=DECK.find(c=>c.id===s.mirror[e.m]);if(mp)pick=mp}
else if(!s.noInvest&&!s.strat){(s.picks=s.picks||{})[e.m]=pick.id}
s.stageEvents.push(applyChance(s,pick,e.r2));
}
const f=s.infl,b={income:0,k401:0,match:0,tax:0,needs:0,debt:0,left:0,saved:0,fun:0,shortfall:0,k529:0};
const sold=s.month<s.soldUntil,boost=s.month<s.boostUntil;
if(s.month%12===0)s.rothYTD=0;
if(s.inSchool&&s.tuitionNet>0&&s.month%12===0&&s.month<(s.gradAge-s.startAge)*12-1e-6){const t=s.tuitionNet*s.infl;s.student.bal+=t;s.totals.tuitionLoans=(s.totals.tuitionLoans||0)+t}
if(!s.inSchool&&s.month===s.graceUntil)s.student.pay=pmt(s.student.bal,s.student.rate,120);
if(!s.inSchool&&!s.retired&&s.month-s.carBought>=C.CAR_LIFE&&s.carLoan.bal<1)replaceCar(s);
for(const born of s.kids){
if(s.month===born){const k=s.kids.filter(b=>b<=born).length;story(s,`Welcomed your ${ordinal(k)} child`,'heart');
if(s.home<=0&&(s.rentTier==='room'||s.rentTier==='solo'||s.rentTier==='home')){const ct=CITIES[s.city]||{rent:1};s.rentTier='family';s.rent=RENTS.family.rent*(ct.rent||1);story(s,'Moved to a 2-bedroom apartment to make room for the baby','home');s.movedForBaby=true}
if(!s.flat)lifeEvent(s,k>1?`Baby number ${k} arrives`:'A baby joins the family',`Congratulations! You're ${Math.floor(s.age)}, and your family now has ${kidAgesText(s).replace(/^1 kid, age 0$/,'a newborn')}. Kid costs now run about ${money(kidCost(s)*f,s.infl)} a month, including childcare, and they rise a little as kids get older.${s.movedForBaby&&k===1?` You also moved to a 2-bedroom apartment, about ${money(s.rent*f,s.infl)} a month.`:''}`,'Raising a child to 18 costs well over $200,000 in today\'s dollars. Many families save less for a while, then catch up.','life')}
if(s.month===born+216){
const cost=C.KID_COLLEGE*f;let from529=0;
if(s.college==='529'){const n=s.kids.filter(b=>s.month<=b+216).length||1;from529=Math.min(s.k529/n,cost);s.k529-=from529}
const rest=s.college==='none'?0:cost-from529;if(rest>0)payFrom(s,rest);s.totals.collegePaid+=from529+rest;
if(!s.flat)lifeEvent(s,'Your child heads to college',s.college==='none'?`They cover the ${money(cost,s.infl)} with loans, scholarships and work, like you did.`:`College costs about ${money(cost,s.infl)}: ${money(from529,s.infl)} from the 529${rest>0?` and ${money(rest,s.infl)} from your savings`:''}.`,s.college==='529'?'Money in a 529 grew tax-free for 18 years, so every dollar you saved covered more than a dollar of tuition.':s.college==='pay'?'Paying from savings works, but that money never got 18 years to grow.':'Your savings stayed intact. Your child starts adult life with student loans.','life');
}
}
if(s.inSchool){
b.income=(s.schoolIncome+s.extraWork)*f+s.extraLoan;
s.student.bal+=s.extraLoan;s.totals.extraBorrowed+=s.extraLoan;s.totals.extraEarned+=s.extraWork*f;
}else if(s.retired){
if(s.age>=s.ssClaim-1e-9){b.income=s.ssMonthly*s.infl/s.infl65;s.totals.ssPaid+=b.income}
if(s.ltc&&s.age>=deathAge(s)-2){b.ltc=C.LTC_COST*f;s.totals.ltc=(s.totals.ltc||0)+b.ltc;if(!s.ltcShown){s.ltcShown=true;story(s,'Needed long-term care','heart');lifeEvent(s,'You need long-term care',`Help at home and later a care facility cost about ${money(C.LTC_COST*12*f,f)} a year.`,'About half of people who reach 65 will need paid long-term care at some point. Medicare covers very little of it. Medicaid helps only after most of your savings are gone, which is why some people buy long-term care insurance in their 50s.','bad')}}
}else{
if(s.noIncome>0){s.noIncome--;s.lastK=0}
else{
const g=s.salary/12,cu=s.age>=60&&s.age<64?C.K_CU6063:s.age>=50?C.K_CU:0,lim=(C.K_LIMIT+cu)*f/12;
b.k401=Math.min(g*s.kPct,lim);b.match=Math.min(b.k401,g*C.MATCH);s.totals.missedMatch=(s.totals.missedMatch||0)+Math.max(0,g*C.MATCH-b.match);
b.hsa=s.hsaPlan==='max'?hsaLimit(s)/12-C.HSA_EMP*f/12:s.hsaPlan==='some'?150*f:0;if(b.hsa<0)b.hsa=0;
if(s.noInvest){b.kCash=b.k401;b.k401=0;b.match=0}
const t=taxes(s.salary,(b.k401+b.hsa)*12,f,s.localRate);b.tax=t.total/12;b.income=g-b.k401-b.hsa-b.tax-(b.kCash||0);
if(b.kCash){s.cash+=b.kCash;s.totals.kCash=(s.totals.kCash||0)+b.kCash}
if(s.hsaPlan!=='none'){const add=b.hsa+C.HSA_EMP*f/12;s.hsa+=add;s.yrContrib+=add;s.totals.hsaIn+=add}
{const ira=iraPart(s);s.k401+=b.k401+b.match;if(s.iraFrac)s.iraFrac=s.k401>0?ira/s.k401:0}s.yrContrib+=b.k401+b.match;s.lastK=b.k401;
s.totals.match+=b.match;s.totals.contrib+=b.k401;s.totals.taxes+=b.tax;s.totals.local+=t.local/12;
}
if(s.partner&&!s.retired){const t=taxes(s.partnerPay,0,f,s.localRate);b.income+=(s.partnerPay-t.total)/12;s.totals.taxes+=t.total/12}
}
b.needs=s.retired?s.spendStyle*s.retireSpend*s.infl/s.infl65+insPremium(s)+(b.ltc||0)+(s.age<65-1e-6?C.PRE_MEDICARE*f:0):fixedNeeds(s);
{const pr=insPremium(s);if(pr>0){s.totals.premiums+=pr;if(s.ins.type==='whole'&&s.month-s.ins.start>=12)s.ins.cv+=0.5*pr}}
if(s.ins.type==='whole')s.ins.cv*=Math.pow(1.025,1/12);
if(!s.inSchool)s.totals.habits+=habitCost(s)*f;
const kids=kidsUnder18(s),kc=kidCost(s)*f;s.totals.kidCost+=kc;
if(s.college==='529'&&kids){b.k529=kids*C.K529*f;s.k529+=b.k529;b.needs+=b.k529}
if(s.health==='hdhp'&&!s.inSchool){const rc=C.HDHP_ROUTINE*f*(s.partner||s.kids.length?2:1),h=Math.min(s.hsa,rc);s.hsa-=h;b.needs+=rc-h}
if(s.cut&&s.month<s.cut.until&&!s.retired){const x=Math.min(s.cut.amt,b.needs*0.5);b.needs-=x;b.cutBack=x;s.totals.cutBack=(s.totals.cutBack||0)+x}
if(s.home>0)s.totals.homeCosts+=housingCost(s);
const si=s.student.bal*s.student.rate/12;s.student.bal+=si;s.totals.studentInterest+=si;
if(!s.inSchool&&s.month>=s.graceUntil)b.debt+=payDown(s.student,s.student.pay);
if(s.card.bal>0.005){const ci=s.card.bal*s.card.rate/12;s.card.bal+=ci;s.totals.cardInterest+=ci;b.debt+=payDown(s.card,Math.max(25,ci+0.01*s.card.bal))}
if(s.carLoan.bal>0.005){const i=s.carLoan.bal*s.carLoan.rate/12;s.carLoan.bal+=i;s.totals.carInterest+=i;b.debt+=payDown(s.carLoan,s.carLoan.pay)}
if(s.mortgage.bal>0.005){const i=s.mortgage.bal*s.mortgage.rate/12;s.mortgage.bal+=i;s.totals.mortgageInterest+=i;b.debt+=payDown(s.mortgage,s.mortgage.pay)}
b.left=b.income-b.needs-b.debt;
if(s.inSchool&&s.coverGap&&b.left<0){const x=-b.left;s.student.bal+=x;s.totals.extraBorrowed+=x;b.income+=x;b.left=0}
if(s.retired&&b.left<0){const un=withdraw(s,-b.left);if(un>0.5){if(s.broke==null){s.broke=s.age;story(s,'Your savings ran out','bolt')}s.totals.unmet+=un}}
else if(s.retired){s.cash+=b.left}
else if(b.left<0){
const cr=s.lifestyle!=null?0:creep(s),cut=Math.min(cr,-b.left);b.needs-=cut;b.left+=cut;b.trim=cut;
if(b.left<0){const need=-b.left,fc=Math.min(s.cash,need);s.cash-=fc;let sh=need-fc;
if(sh>0&&s.k401Until>s.month){const d=k401Draw(s,sh);sh-=d.net;s.totals.k401Layoff=(s.totals.k401Layoff||0)+d.gross}
const lim=cardLimit(s),room=Math.max(0,lim-s.card.bal),onCard=Math.min(room,sh);s.card.bal+=onCard;b.shortfall=onCard;s.totals.shortfall+=onCard;sh-=onCard;
if(sh>0.5){s.totals.unmet+=sh;b.needs-=sh;if(!s.maxedThisStage)s.credit.hit+=90;if(!s.maxedThisStage)story(s,'Maxed out your credit card','bolt');if(!s.flat&&!s.maxedThisStage){s.maxedThisStage=true;lifeEvent(s,'You maxed out your credit card','Your card hit its limit, so you had to go without: skipped bills, borrowed from family, cut everything you could.','When debt payments eat your paycheck, every month gets harder. This is why a cushion and a budget matter before trouble hits.','bad')}}}
}
else{b.saved=b.left*s.savePct;b.fun=b.left-b.saved;s.totals.fun+=b.fun;s.totals.funR=(s.totals.funR||0)+b.fun/s.infl;allocate(s,b.saved)}
s.yrSpend+=b.needs-b.k529-kc+b.fun-insPremium(s);
const yr=Math.floor(s.month/12),mr=sold?C.CASH:boost?boostRate(s,s.age,s.risk):s.flat?mixAt(s.age,s.risk).flat:mktReturn(s,yr);
const g=Math.pow(1+mr,1/12);
const fm=Math.pow(1-s.fee,1/12);s.totals.fees+=(s.k401+s.roth+s.brok+s.hsa)*(1-fm);
if(!sold)s.totals.brokDrag=(s.totals.brokDrag||0)+s.brok*C.DRAG/12;
const mcI=s.flat?0:invested(s);
s.k401*=g*fm;s.roth*=g*fm;s.brok*=Math.pow(1+mr-(sold?0:C.DRAG),1/12)*fm;s.hsa*=s.noInvest?Math.pow(1+C.CASH,1/12):g*fm;s.k529*=Math.pow(1+(s.noInvest?C.CASH:s.flat?mixAt(s.age).flat:mktReturn(s,yr)),1/12);
if(!s.flat)s.yrGrowth=(s.yrGrowth||0)+invested(s)-mcI;
s.cash*=Math.pow(1+C.CASH,1/12);s.home*=Math.pow(1+C.HOME,1/12);s.carValue*=Math.pow(1-C.CARDEP,1/12);
syncRT(s);s.infl*=Math.pow(1+C.INFL,1/12);s.month++;s.age=s.startAge+s.month/12;
if(s.month%12===0){if(!s.inSchool&&!s.retired){yearPay(s);if(s.partner)s.partnerPay*=1+growthAt(s.age)}yearEnd(s)}
creditStep(s);
if(!s.flat){const tr=s.track;if(tr.credit800==null&&s.credit.score>=800)tr.credit800=s.age;if(tr.debtFree==null&&!s.inSchool&&s.student.bal+s.card.bal+s.carLoan.bal<1)tr.debtFree=s.age;if(tr.inv100==null&&invested(s)/s.infl>=100000)tr.inv100=s.age}
const nw=netWorth(s);s.history.push({age:s.age,nw,f:s.infl});
if(s.hit1M==null&&nw>=1e6)s.hit1M=s.age;
if(s.hit1MReal==null&&nw/s.infl>=1e6)s.hit1MReal=s.age;
return b;
}
function yearPay(s){
const p=payOf(s),yr=Math.floor(s.month/12),age=s.age,mult=age<35?1:age<50?.5:.15;
const raise=s.flat?C.INFL+p.real*mult:Math.max(0,C.INFL+p.real*mult+p.sd*mult*s.payZ[yr%90]);
if(s.noIncome===0){
let bonus=0;
if(s.flat)bonus=s.salary*p.bonus*p.size;
else if(s.bonusU[yr%90]<p.bonus)bonus=s.salary*p.size*(0.5+s.bonusV[yr%90]);
if(bonus>0){const net=bonus*(1-.32);s.totals.bonus+=net;if(!s.flat){s.stageBonus.n++;s.stageBonus.amt+=net}
const sv=net*s.savePct;s.totals.fun+=net-sv;allocate(s,sv)}
}
s.salary*=1+raise;if(!s.flat)s.stageRaises.push(raise);
}
function expMult(s){return s.grad?Math.min(1.45,1+0.025*Math.max(0,s.startAge-23)):1}
function graduate(s){s.inSchool=false;s.coverGap=false;s.extraLoan=0;s.extraWork=0;s.spendCut=0;s.graceUntil=s.grad?s.month:s.month+6;s.student.pay=pmt(s.student.bal,s.student.rate,120)}
function buyCar(s,price,rate,months,run){rate=carRate(s,rate);const p=price*s.infl,loan=Math.max(0,p-s.carValue);story(s,`Bought a ${money(p,s.infl)} car`,'car');s.carValue=p;s.carBought=s.month;s.carLoan={bal:loan,rate,pay:pmt(loan,rate,months)};s.carRun=run}
function downPaymentPlan(s,price,down=.10){
const P=price*s.infl,need=(down+.03)*P;let rem=need;
const fromCash=Math.min(s.cash,rem);rem-=fromCash;
const gainFrac=s.brok>0?Math.max(0,1-s.brokBasis/s.brok):0,netPer=1-C.LTCG*gainFrac;
const brokGross=Math.min(s.brok,rem/netPer);rem-=brokGross*netPer;
const fromRoth=Math.min(s.rothBasis,s.roth,rem);rem-=fromRoth;
const kGross=Math.min(s.k401,rem/0.7);rem-=kGross*0.7;
return {P,need,fromCash,brokGross,brokTax:brokGross*(1-netPer),fromRoth,kGross,kCost:kGross*0.3,ok:rem<=1,short:Math.max(0,rem)};
}
function buyHome(s,price,down=.10){
const d=downPaymentPlan(s,price,down);
s.cash-=d.fromCash;
if(d.brokGross>0){s.brokBasis*=1-d.brokGross/s.brok;s.brok-=d.brokGross}
if(d.fromRoth>0){s.roth-=d.fromRoth;s.rothBasis-=d.fromRoth}
if(d.kGross>0)s.k401-=d.kGross;
s.yrContrib-=d.brokGross+d.fromRoth+d.kGross;
s.totals.penalty+=d.brokTax+d.kCost;
const mr=mortRate(s),loan=(1-down)*d.P+(s.noInvest&&!d.ok?d.short:0);s.home=d.P;s.mortgage={bal:loan,rate:mr,pay:pmt(loan,mr,360)};s.mip=down<.1?loan*C.MIP/12:0;s.rent=0;if(s.track.home==null)s.track.home=s.age;story(s,`Bought a ${money(d.P,s.infl)} home at ${(mr*100).toFixed(1)}% with a ${creditLabel(s.credit.score).toLowerCase()} credit score`,'home');
d.f=s.infl;return d;
}
function salePlan(s){const gross=s.home,cost=gross*C.SELL,owed=s.mortgage.bal;return {gross,cost,owed,net:gross-cost-owed}}
function sellHome(s){const d=salePlan(s);s.cash+=d.net;s.totals.sellCosts=(s.totals.sellCosts||0)+d.cost;s.home=0;s.mortgage={bal:0,rate:s.mortgage.rate,pay:0};s.mip=0;return d}
function rentAfterSale(s){return (s.kids.length||s.partner?RENTS.nice.rent:RENTS.solo.rent)*CITIES[s.city].rent}
function moveDown(sale,P){return Math.max(.10,Math.min(.5,Math.floor((sale.net/P-.03)*100)/100))}
function movePlan(s,price){const c=structuredClone({...s,history:[],schedule:[],stageEvents:[],story:[]});c.flat=true;const sale=sellHome(c);
if(price==null)return {sale,ok:c.cash>=-1};
const P=price*c.infl,down=moveDown(sale,P),d=downPaymentPlan(c,price,down);return {sale,down,d,P,rate:mortRate(c),pay:pmt((1-down)*P,mortRate(c),360),ok:c.cash>=-1&&d.ok}}
function applyMove(s,ch){if(!ch.move||ch.move==='stay'||!(s.home>0))return;
const oldVal=s.home,sale=sellHome(s),f=s.infl;s.lastMove={kind:ch.move,sale,from:oldVal,f};
const t=MOVE_TIERS.find(t=>t.v===ch.move);
if(t){const P=t.p*f,down=moveDown(sale,P);if(downPaymentPlan(s,t.p,down).ok||s.noInvest){story(s,`Sold your ${money(oldVal,f)} home and paid ${money(sale.cost,f)} in selling costs`,'home');s.homeBuy=buyHome(s,t.p,down);s.lastMove.to=P;s.lastMove.down=down;return}}
s.rent=rentAfterSale(s);s.lastMove.kind='rent';story(s,`Sold your ${money(oldVal,f)} home and went back to renting`,'home')}
const MOVE_TIERS=[{v:'m190',p:190000},{v:'m260',p:260000},{v:'m360',p:360000},{v:'m500',p:500000}];
// ENGINE END
const RENTS={home:{rent:300,label:'Live at home with family'},room:{rent:700,label:'Split with roommates'},solo:{rent:1150,label:'Your own 1-bedroom'},family:{rent:1400,label:'A 2-bedroom apartment'},nice:{rent:1550,label:'New luxury apartment'}};
const $=id=>document.getElementById(id);
const ICON={check:'M5 12.5l4.5 4.5L19 7.5',
shield:'M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z',
pct:'M19 5L5 19 M7 9a2 2 0 1 0 0-4 2 2 0 0 0 0 4z M17 19a2 2 0 1 0 0-4 2 2 0 0 0 0 4z',
cap:'M2 9l10-5 10 5-10 5z M6 11v5c3 2 9 2 12 0v-5 M22 9v5',
brief:'M3 8h18v11H3z M8 8V5h8v3 M3 13h18',
trend:'M3 17l6-6 4 4 8-8 M15 7h6v6',
home:'M3 11l9-7 9 7 M5 10v10h14V10 M10 20v-5h4v5',
waves:'M2 8c3-3 5 3 8 0s5 3 8 0 3 0 4 0 M2 14c3-3 5 3 8 0s5 3 8 0 3 0 4 0',
flag:'M5 21V4 M5 4h11l-2 4 2 4H5',
wallet:'M3 7h15a3 3 0 0 1 3 3v7a2 2 0 0 1-2 2H3z M3 7l12-4v4 M16 13h2',
card:'M3 6h18v12H3z M3 10h18 M7 15h4',
car:'M4 16v-4l2-5h12l2 5v4z M4 16v2 M20 16v2 M7.5 13h.01 M16.5 13h.01',
doc:'M6 3h9l4 4v14H6z M14 3v5h5 M9 13h6 M9 17h6',
scale:'M12 4v16 M7 20h10 M4 7h16 M6 7l-3 7h6z M18 7l-3 7h6z',
bolt:'M13 2L4 14h7l-1 8 9-12h-7z',
plus:'M12 5v14 M5 12h14',
cal:'M4 5h16v15H4z M4 10h16 M9 3v4 M15 3v4',
star:'M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1L3.2 9.5l6.1-.9z',
heart:'M12 20s-7-4.4-7-10a4 4 0 0 1 7-2.6A4 4 0 0 1 19 10c0 5.6-7 10-7 10z',
ghost:'M6 20V10a6 6 0 0 1 12 0v10l-2-2-2 2-2-2-2 2-2-2z M10 10h.01 M14 10h.01',
sun:'M12 7a5 5 0 1 0 0 10 5 5 0 0 0 0-10z M12 1v3 M12 20v3 M4.2 4.2l2.1 2.1 M17.7 17.7l2.1 2.1 M1 12h3 M20 12h3',
play:'M7 4l13 8-13 8z',
arrow:'M5 12h14 M13 6l6 6-6 6'};
const ic=(n,cls='')=>`<svg class="ic ${cls}" viewBox="0 0 24 24" aria-hidden="true"><path d="${ICON[n]}"/></svg>`;
let real=true;
try{const v=localStorage.getItem('lg-real2');if(v!==null)real=v==='1'}catch(e){}
$('realToggle').checked=real;
$('realToggle').addEventListener('change',e=>{real=e.target.checked;try{localStorage.setItem('lg-real2',real?'1':'0')}catch(err){}render()});
let CUR_F=1;
function money(x,f,opts={}){
if(f===undefined)f=CUR_F;
const v=real&&f?x/f:x,neg=v<-0.5,a=Math.abs(v);let str;
if(opts.short&&a>=1e6)str='$'+(a/1e6).toFixed(a>=1e7?1:2)+'M';
else if(opts.short&&a>=1e4)str='$'+Math.round(a/1e3)+'K';
else str='$'+Math.round(a).toLocaleString('en-US');
return (neg?'−':'')+str;
}
const M=(x,f,o)=>`<span class="money">${money(x,f,o)}</span>`;
const esc=t=>String(t).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
const pct=x=>{const p=x*100;return (Math.abs(p-Math.round(p))<.05?Math.round(p):p.toFixed(1))+'%'};
// ---------- setup ----------
const GOALS=[
{id:'debt30',by:30,label:'Debt-free by 30',hint:'No student loan, card or car debt (a mortgage is fine)'},
{id:'home35',by:35,label:'Own a home by 35',hint:'Any home, bought by your 35th birthday'},
{id:'inv35',by:35,label:'$100,000 invested by 35',hint:'In today\'s dollars'},
{id:'credit',by:40,label:'800+ credit score by 40',hint:'Exceptional credit'},
{id:'mil55',by:55,label:'A millionaire by 55',hint:'Net worth of $1 million in today\'s dollars'},
{id:'never',label:'Never run out of money',hint:'Your savings last your whole life'},
{id:'leave',label:'Leave $500,000 to family',hint:'In today\'s dollars'},
{id:'live85',label:'Live to 85',hint:'Habits and luck both matter'}];
function goalStatus(s,id,final){const t=s.track,a=s.age;
const by=(age,lim)=>age!=null&&age<=lim+1e-6?{ok:true,txt:`Done at ${Math.floor(age)}`}:a>lim?{ok:false,txt:'Missed'}:{ok:null,txt:'In progress'};
if(id==='debt30')return by(t.debtFree,30);if(id==='home35')return by(t.home,35);if(id==='inv35')return by(t.inv100,35);if(id==='credit')return by(t.credit800,40);if(id==='mil55')return by(s.hit1MReal,55);
if(id==='never')return s.broke!=null?{ok:false,txt:`Ran out at ${Math.floor(s.broke)}`}:final?{ok:true,txt:'Your money lasted'}:{ok:null,txt:'So far, so good'};
if(id==='leave'){const e=(netWorth(s)+insPayout(s))/s.infl;return final?{ok:e>=500000,txt:`Left ${money(e,0)} in today\'s dollars`}:{ok:null,txt:'Revealed at the end'}}
if(id==='live85'){const d=deathAge(s);return final?{ok:d>=85,txt:`You lived to ${d}`}:{ok:null,txt:`Expected about ${lifeExpect(s)}`}}}
const DEFAULTS={returns:'hist',goals:[],status:'college',age:20,years:2,checking:600,savings:900,invest:0,k401Bal:0,iraBal:0,rothBal:0,loans:14000,loanRate:6.52,card:800,apr:24,limit:2000,carValue:5000,jobIncome:700,family:300,kees:1000,spend:950,tuition:7000,tuitionPaid:false};
const LIMITS={age:[18,40],years:[1,4],loanRate:[0,15],apr:[0,36],checking:[0,5e6],savings:[0,5e6],invest:[0,1e7],k401Bal:[0,1e7],iraBal:[0,1e7],rothBal:[0,1e7],loans:[0,5e5],card:[0,1e5],limit:[0,1e5],carValue:[0,2e5],jobIncome:[0,2e4],family:[0,2e4],kees:[0,5000],tuition:[0,80000],spend:[0,2e4],creditScore:[300,850]};
const F=(k,l,pre,suf,sm)=>({k,l,pre,suf,sm});
const SECTIONS=[
{id:'month',icon:'cal',title:'Your month',fields:[F('age','Your age',null,'years'),F('years','Years of college left',null,'years'),F('tuition','Tuition and fees per year','$',null,'After grants and scholarships. UK in-state is $14,177 a year before aid (2026–27). KEES comes off this for you.'),F('kees','KEES award per year','$',null,'Shown in your KHEAA account'),F('jobIncome','Job take-home pay per month','$'),F('family','Family help or aid refunds per month','$'),F('spend','What you spend per month','$',null,'Rent, food, gas, fun, everything')]},
{id:'cash',icon:'wallet',title:'Checking and savings',fields:[F('checking','Checking account','$'),F('savings','Savings account','$')]},
{id:'invest',icon:'trend',title:'Investing',fields:[F('k401Bal','401(k)','$',null,'Through a current or past job'),F('iraBal','Traditional IRA','$',null,'One you opened, or an old 401(k) you rolled over'),F('rothBal','Roth IRA','$',null,'Already-taxed money, tax-free later'),F('invest','Brokerage account','$',null,'A regular investing account, no tax break')]},
{id:'loans',icon:'doc',title:'Student loans',fields:[F('loans','Student loans so far','$'),F('loanRate','Interest rate',null,'%','Undergrad federal loans for 2026–27: 6.52%')]},
{id:'credit',icon:'card',title:'Credit cards and credit',fields:[F('card','Credit card balance','$',null,'What you owe right now'),F('apr','Card APR',null,'%','On your statement'),F('limit','Credit limit','$')]},
{id:'nw',icon:'scale',title:'Your net worth',fields:[F('carValue','What your car is worth','$',null,'Look it up on a used-car pricing site')]}];
function barRows(rows,max){
max=max||Math.max(1,...rows.map(r=>Math.abs(r.v)));
return `<div class="bars">${rows.map(r=>`<div class="bar-row"><span>${r.l}</span><span class="track-b"><i style="width:${Math.max(1.5,Math.abs(r.v)/max*100)}%;--c:${r.c||'var(--accent)'}"></i></span><span class="money">${r.t||money(r.v,r.f)}</span></div>`).join('')}</div>`;
}
function stackBar(parts){
const tot=parts.reduce((a,p)=>a+Math.max(0,p.v),0)||1;
return `<div class="stackbar">${parts.filter(p=>p.v>0).map(p=>`<i style="flex-grow:${p.v/tot};--c:${p.c}" title="${p.l}"></i>`).join('')}</div>
<div class="legend">${parts.filter(p=>p.v>0).map(p=>`<span style="--c:${p.c}">${p.l} ${money(p.v,p.f)}</span>`).join('')}</div>`;
}
function lineChart(series,x0,x1,opts={}){
const W=opts.w||520,H=opts.h||200,L=56,R=14,T=14,B=26;
let mx=opts.min1M?1.1e6:0,mn=0;for(const s of series)for(const p of s.pts){mx=Math.max(mx,p[1]*1.05);mn=Math.min(mn,p[1])}
const steps=[100,250,500,1000,2500,5000,10000,25000,50000,100000,250000,500000,1e6,2e6,5e6,1e7];const st=steps.find(v=>(mx-mn)/v<=5)||2e7;
mn=Math.floor(mn/st)*st;mx=Math.max(mx,mn+st);
const x=a=>L+(a-x0)/(x1-x0)*(W-L-R),y=v=>T+(1-(v-mn)/(mx-mn))*(H-T-B);
let g='';
for(let v=mn;v<=mx+1;v+=st)g+=`<line x1="${L}" x2="${W-R}" y1="${y(v)}" y2="${y(v)}" stroke="var(--line)"/><text x="${L-6}" y="${y(v)+4}" text-anchor="end">${Math.abs(v)<1?'$0':money(v,0,{short:true})}</text>`;
const span=x1-x0,xs=span>30?10:span>12?5:span>6?2:1;
for(let a=Math.ceil(x0/xs)*xs;a<=x1;a+=xs)g+=`<text x="${x(a)}" y="${H-7}" text-anchor="middle">${a}</text>`;
if(opts.min1M&&mx>=1e6)g+=`<line x1="${L}" x2="${W-R}" y1="${y(1e6)}" y2="${y(1e6)}" stroke="var(--gold)" stroke-width="1.5" stroke-dasharray="5 4"/><text x="${W-R}" y="${y(1e6)-6}" text-anchor="end" style="fill:var(--gold)">$1 million</text>`;
if(opts.vline){const vx=x(opts.vline.x);g+=`<line x1="${vx}" x2="${vx}" y1="${T}" y2="${H-B}" stroke="var(--danger)" stroke-width="1.5" stroke-dasharray="3 3"/><text x="${vx-4}" y="${T+10}" text-anchor="end" style="fill:var(--danger)">${opts.vline.label}</text>`}
for(const s of series){
const d=s.pts.map((p,i)=>(i?'L':'M')+x(p[0]).toFixed(1)+' '+y(p[1]).toFixed(1)).join('');
if(s.fill)g+=`<path d="${d}L${x(s.pts[s.pts.length-1][0]).toFixed(1)} ${y(Math.max(0,mn))}L${x(s.pts[0][0]).toFixed(1)} ${y(Math.max(0,mn))}Z" fill="${s.c}" opacity=".12"/>`;
g+=`<path d="${d}" fill="none" stroke="${s.c}" stroke-width="${s.dash?1.75:2.5}" ${s.dash?'stroke-dasharray="6 5"':''} stroke-linejoin="round"/>`;
const last=s.pts[s.pts.length-1];if(!s.dash)g+=`<circle cx="${x(last[0])}" cy="${y(last[1])}" r="4" fill="${s.c}"/>`;
}
return `<svg class="chart" viewBox="0 0 ${W} ${H}" role="img" aria-label="${opts.label||'Chart'}">${g}</svg>`;
}
function marketBars(rets,startAge){
const mx=Math.max(.2,...rets.map(Math.abs));
return `<div class="mkt-wrap"><div class="mkt-up">${rets.map(r=>`<i style="height:${r>0?r/mx*100:0}%"></i>`).join('')}</div><div class="mkt-dn">${rets.map(r=>`<i style="height:${r<0?-r/mx*100:0}%"></i>`).join('')}</div></div>
<div class="mkt-l${rets.length>6?' many':''}">${rets.map((r,i)=>`<span>${r>0?'+':''}${Math.round(r*100)}%</span>`).join('')}</div>`;
}
const SSC={62:'var(--c-car)',65:'var(--c-roth)',67:'var(--accent)',70:'var(--gold)'};
function ssUnit(){return real?"in today's dollars":'in dollars at age 65'}
function ssChart(pia,f,death){
const k=real&&f?1/f:1,end=Math.max(death||95,80),series=[62,65,67,70].map(a=>{const pts=[];for(let x=62;x<=end;x++)pts.push([x,pia*SSF[a]*12*Math.max(0,x-a)*k]);return {pts,c:SSC[a]}});
return lineChart(series,62,end,{w:560,h:220,label:'Total Social Security collected by age',vline:death?{x:death,label:'Your life ends'}:null})+
`<div class="legend">${[62,65,67,70].map(a=>`<span style="--c:${SSC[a]}">Claim at ${a}: ${money(pia*SSF[a],f)}/mo</span>`).join('')}</div><p class="muted" style="font-size:var(--fs-sm)">Amounts ${ssUnit()}. Real checks also rise with inflation every year.</p>`;
}
function lessonFor(id,I){
if(id==='month'&&I.status==='grad')return `<h3>You'll set your job and budget in the game</h3><p>Since you've graduated, the game starts at age ${I.age} with your career. You'll pick your job (or type in your own and its salary), where you live and how much you spend each year.</p><p class="tip">A common starting guideline is <strong>50/30/20</strong>: about half of take-home pay to needs, 30% to wants, and 20% to savings and paying down debt.</p>`;
if(id==='month'){
const inn=I.jobIncome+I.family,net=inn-I.spend,tn=I.tuitionPaid?0:Math.max(0,(I.tuition||0)-(I.kees||0)),yrs=I.years||1;
return `<h3>Cash flow is where every plan starts</h3>
<p>Money in minus money out. If it's positive, you have something to save. If it's negative, the gap comes from savings or a credit card.</p>
${barRows([{l:'Money in',v:inn,c:'var(--accent)'},{l:'Money out',v:I.spend,c:'var(--danger)'}])}
<p><strong>${net>=0?`You keep ${money(net)} a month.`:`You're short ${money(-net)} a month.`}</strong></p>
<p class="tip">A common starting guideline is <strong>50/30/20</strong>: about half of take-home pay to needs, 30% to wants, 20% to savings and paying down debt. On your ${money(inn)} that would be ${money(inn*.5)}, ${money(inn*.3)} and ${money(inn*.2)}.</p>
<p class="tip"><strong>Tuition:</strong> ${I.tuitionPaid?'already paid for, so you won\'t borrow anything more for school. That\'s a big head start.':tn>0?`${money(I.tuition)} a year${I.kees>0?` minus ${money(I.kees)} of KEES`:''} leaves <strong>${money(tn)} a year</strong> to borrow. Over ${yrs} more year${yrs>1?'s':''}, that's about <strong>${money(tn*yrs)}</strong> in new student loans, building interest from day one.`:'your KEES and aid cover it, so you won\'t borrow more for school.'}</p>
${I.kees>0?`<p class="tip"><strong>KEES</strong> money is earned in high school but has to be renewed each year in college by keeping your GPA up. Losing it would cost you ${money(I.kees)} a year.</p>`:''}`;
}
if(id==='cash'){
const tot=I.checking+I.savings,cush=Math.min(tot,1000),sugC=Math.min(I.spend,tot-cush),sugS=tot-sugC,ef=Math.min(1,I.savings/1000);
return `<h3>Checking is for spending. Savings is for later.</h3>
<ul><li><strong>Checking</strong> is where your paycheck lands and bills and your debit card draw from. It pays little or no interest.</li>
<li><strong>Savings</strong> holds your cushion. High-yield savings accounts at online banks often pay several times more interest than a typical bank's savings account. Both are FDIC-insured up to $250,000.</li></ul>
<p class="eyebrow">Your split</p>${stackBar([{l:'Checking',v:I.checking,c:'var(--c-roth)'},{l:'Savings',v:I.savings,c:'var(--c-cash)'}])}
<p class="eyebrow">A common split</p>${stackBar([{l:'Checking',v:sugC,c:'var(--c-roth)'},{l:'Savings',v:sugS,c:'var(--c-cash)'}])}
<p class="tip">Your first <strong>$1,000</strong> goes in savings as a starter emergency fund${ef<1?` (you're ${Math.round(ef*100)}% there)`:' (done)'}. Then keep about a month of spending in checking (${money(I.spend)} for you) so bills never bounce${sugC<I.spend?'. You\'re not there yet, so build checking up next':''}, and anything beyond that goes back to savings. After college, grow the cushion to 3 to 6 months of expenses.</p>`;
}
if(id==='invest'){
const yrs=65-I.age,a=[],b=[],c=[];let v1=0,v2=0,v3=0;const gr=mixAt(30,'growth').flat,mr=Math.pow(1+gr,1/12)-1,cr=Math.pow(1+C.CASH,1/12)-1;
for(let m=0;m<=yrs*12;m++){if(m%12===0){a.push([I.age+m/12,v1]);b.push([I.age+m/12,v2]);c.push([I.age+m/12,v3])}v1=(v1+100)*(1+mr);v3=(v3+100)*(1+cr);if(m>=120)v2=(v2+100)*(1+mr)}
const A=a[a.length-1][1],B=b[b.length-1][1],Cc=c[c.length-1][1];
return `<h3>Investing means owning things that grow</h3>
<ul><li><strong>Stocks</strong> are small pieces of companies. When companies grow and earn profits, their value rises.</li>
<li><strong>Bonds</strong> are loans to governments or companies that pay you interest. Steadier, but they grow slower.</li>
<li><strong>Index funds</strong> buy hundreds of companies at once, so one bad company can't sink you. Over the past century US stocks have averaged roughly 10% a year before inflation, about 7% after, with big drops along the way.</li></ul>
${retChoiceHTML()}
<p class="eyebrow">$100 a month from age ${I.age} to 65</p>
${lineChart([{pts:a,c:'var(--accent)',fill:true},{pts:b,c:'var(--c-brok)'},{pts:c,c:'var(--c-cash)'}],I.age,65,{label:'Compounding comparison'})}
${barRows([{l:`Invest at ${I.age}`,v:A,c:'var(--accent)'},{l:`Invest at ${I.age+10}`,v:B,c:'var(--c-brok)'},{l:'Savings account',v:Cc,c:'var(--c-cash)'},{l:'You put in',v:100*12*yrs,c:'var(--c-car)'}])}
<p class="tip">Same $100 a month, wildly different results. You put in ${money(100*12*yrs)}. Invested from ${I.age}, it grows to <strong>${money(A)}</strong>. Waiting 10 years costs about <strong>${money(A-B)}</strong>, and a high-yield savings account earning 3.5% barely beats 3% inflation. Invested here means the growth mix: ${retTxt(gr)}. That's <strong>compounding</strong>: your gains start earning gains, and time is the ingredient you can never get back.</p>
<details class="more qlearn"><summary>How a Roth IRA works</summary>${rothGuide()}</details>
<h3>Four places your invested money can live</h3>
<p>The account is the box; the funds inside it are what grow. The box decides <strong>when you pay tax</strong> and <strong>when you can take money out</strong>.</p>
${acctGuide()}
${invTotal(I)>0?`<p class="eyebrow">Your accounts today: ${money(invTotal(I))}</p>${stackBar([{l:'401(k)',v:I.k401Bal||0,c:'var(--c-k401)'},{l:'Traditional IRA',v:I.iraBal||0,c:'var(--c-ira)'},{l:'Roth IRA',v:I.rothBal||0,c:'var(--c-roth)'},{l:'Brokerage',v:I.invest||0,c:'var(--c-brok)'}])}`:''}
<p class="tip">In the game, new work savings go into your <strong>401(k)</strong>, and what you save on your own goes into a <strong>Roth IRA</strong> and a <strong>brokerage account</strong>. A Traditional IRA you already have keeps growing and is taxed like a 401(k) when you retire.</p>`;
}
if(id==='loans'&&(I.noLoans||!(I.loans>0)))return `<h3>No student loans: you're starting ahead</h3>
<p>The average borrower leaves college owing tens of thousands of dollars. Without loans, more of every paycheck is yours from day one.${I.status!=='grad'&&(I.noLoans||I.tuitionPaid)?' Your school is paid for, so the game won\'t add any tuition loans.':''}</p>
<ul><li>If you ever do borrow, <strong>federal loans</strong> come first: they have fixed rates, a 6-month grace period after graduation and income-driven repayment if money gets tight.</li>
<li><strong>Subsidized</strong> loans don't build interest while you're in school. <strong>Unsubsidized</strong> loans do, starting the day you borrow.</li>
<li>Private loans usually cost more and have fewer protections. Use them last.</li></ul>
<p class="tip">Use the money you would have spent on loan payments to build your emergency fund and start investing early. That head start compounds for decades.</p>`;
if(id==='loans'){
const r=I.loanRate/100,atGrad=I.status==='grad'?I.loans:I.loans*Math.pow(1+r/12,I.years*12+6),p10=pmt(atGrad,r,120),p20=pmt(atGrad,r,240);
return `<h3>Loans are cheap money now, expensive money later</h3>
<ul><li><strong>Subsidized</strong> federal loans don't build interest while you're in school. <strong>Unsubsidized</strong> loans do, starting the day you borrow.</li>
<li>Payments start 6 months after you graduate. The standard plan is 10 years. Longer plans lower your monthly payment but cost far more in total.</li></ul>
<p class="eyebrow">${I.status==='grad'?`Your ${money(I.loans)} from here`:`Your ${money(I.loans)} if unsubsidized`}</p>
${barRows([{l:'Borrowed',v:I.loans,c:'var(--c-roth)'},...(I.status==='grad'?[]:[{l:'Owed when payments start',v:atGrad,c:'var(--gold)'}]),{l:'Total paid, 10 years',v:p10*120,c:'var(--accent)',t:money(p10*120)+` · ${money(p10)}/mo`},{l:'Total paid, 20 years',v:p20*240,c:'var(--danger)',t:money(p20*240)+` · ${money(p20)}/mo`}])}
<p class="tip"><strong>If you stop paying:</strong> after 270 days of missed payments, federal loans go into default. The government can take part of your paycheck and your tax refunds, and your credit score drops for years. If money gets tight, ask your servicer about income-driven repayment before you miss a payment.</p>`;
}
if(id==='credit'){
const util=I.limit>0?I.card/I.limit:0,po=minPayoff(I.card,I.apr/100),g=(r,y)=>1000*Math.pow(1+r/12,12*y);
return `<h3>A credit card is a loan you repay every month</h3>
<ul><li>Every purchase is borrowed money. Each month you get a statement. <strong>Pay the full statement balance by the due date and you pay zero interest.</strong></li>
<li>Pay less than that and the rest gets charged your APR. Minimum payments are designed to keep you paying for years.</li></ul>
<p class="eyebrow">$1,000 left unpaid for 5 years</p>
${barRows([{l:`Student loan at ${pct(I.loanRate/100)}`,v:g(I.loanRate/100,5),c:'var(--c-roth)'},{l:`Credit card at ${pct(I.apr/100)}`,v:g(I.apr/100,5),c:'var(--danger)'}])}
${I.card>0?`<p>Paying only the minimum on your ${money(I.card)} balance takes about <strong>${(po.months/12).toFixed(1)} years</strong> and costs <strong>${money(po.interest)} in interest</strong>.</p>`:''}
<h3>Your credit score</h3>
<p>A credit score (300 to 850) tells lenders how risky you are. It affects loan rates, apartment applications and even insurance prices. FICO weighs five things:</p>
${barRows([{l:'Paying on time',v:35,t:'35%'},{l:'Amount owed',v:30,t:'30%'},{l:'History length',v:15,t:'15%'},{l:'New credit',v:10,t:'10%'},{l:'Credit mix',v:10,t:'10%'}],35)}
<p class="eyebrow">Your utilization: ${Math.round(util*100)}% of your limit</p>
<div class="gauge"><b style="left:${Math.min(100,util*100)}%"></b></div><div class="gauge-l"><span>0%</span><span>30%</span><span>50%</span><span>100%</span></div>
<p class="tip">Keep balances under 30% of your limit, never miss a payment, and keep your oldest card open. Those three habits build a strong score.</p>`;
}
if(id==='nw'){
const own=I.checking+I.savings+invTotal(I)+I.carValue,owe=I.loans+I.card,nw=own-owe;
return `<h3>Net worth = what you own − what you owe</h3>
<p>It's the one number that pulls every account together. ${I.status==='grad'?'Many people start out negative because of loans.':'Students usually start negative because of loans.'} What matters is the direction it moves.</p>
<p class="eyebrow">You own ${money(own)}</p>
${stackBar([{l:'Cash',v:I.checking+I.savings,c:'var(--c-cash)'},{l:'401(k)',v:I.k401Bal||0,c:'var(--c-k401)'},{l:'Traditional IRA',v:I.iraBal||0,c:'var(--c-ira)'},{l:'Roth IRA',v:I.rothBal||0,c:'var(--c-roth)'},{l:'Brokerage',v:I.invest||0,c:'var(--c-brok)'},{l:'Car',v:I.carValue,c:'var(--c-car)'}])}
<p class="eyebrow">You owe ${money(owe)}</p>
${stackBar([{l:'Student loans',v:I.loans,c:'var(--c-roth)'},{l:'Credit card',v:I.card,c:'var(--danger)'}])}
<div class="delta"><div><span class="eyebrow">Your net worth</span><div class="big ${nw<0?'neg':''}">${money(nw)}</div></div></div>
<p class="tip">${nw<0?'Negative is normal right now. Paying down debt and saving both push it up. The game tracks this number for the rest of your life.':(I.status==='grad'?'Positive is a good start. The game tracks this number for the rest of your life.':'Positive already puts you ahead of most college students.')}</p>`;
}
}
let G={simple:(()=>{try{return localStorage.getItem('lg-simple')!=='0'}catch(e){return true}})(),phase:'home',inp:{...DEFAULTS},s:null,twin:null,idx:0,runs:[],log:[],seed:Math.floor(Math.random()*1e9),result:null,enter:null,edited:false};
const AGE_NAMES=a=>a<20?'Late teens':a<25?'Early 20s':a<30?'Late 20s':a<35?'Early 30s':a<40?'Late 30s':a<45?'Early 40s':a<50?'Late 40s':a<55?'Early 50s':a<60?'Late 50s':a<65?'Early 60s':a<70?'Late 60s':a<75?'Early 70s':a<80?'Late 70s':a<85?'Early 80s':a<90?'Late 80s':'90s';
function nextBlock(s){
const a=Math.round(s.age*12)/12,n5=stageEnd(a),d=deathAge(s);
if(s.retired&&a>=d-1e-6)return null;
if(s.inSchool&&!s.grad&&a<s.gradAge-1e-6)return {key:'college',from:a,to:Math.min(s.gradAge,n5),name:'College',icon:'cap'};
const R=s.retireAge||65;
if(!s.career)return {key:'first',from:a,to:Math.min(R,n5),name:s.grad?'Your career':'First job',icon:'brief'};
if(a<R-1e-6){
if(!s.didCrash&&a>=38-1e-6&&a<=45+1e-6)return {key:'mid',from:a,to:Math.min(R,n5),name:stageName(a,n5)+': a market crash',icon:'waves'};
if(!s.didBuild&&a>=s.gradAge+2-1e-6)return {key:'build',from:a,to:Math.min(R,n5),name:stageName(a,n5)+': life gets bigger',icon:'heart'};
return {key:'check',from:a,to:Math.min(R,n5),name:stageName(a,Math.min(R,n5)),icon:a>=50?'flag':s.home>0||a<30?'trend':'home'};
}
return s.retired?{key:'retire2',from:a,to:d,name:'Your later years',icon:'sun'}:{key:'retire',from:a,to:Math.min(d,n5),name:'Retirement begins',icon:'sun'};
}
function stageEnd(a){return a>=30-1e-6&&a<60-1e-6?Math.floor(a/10+1e-9)*10+10:Math.floor(a/5+1e-9)*5+5}
function stageName(a,end){return end-a>=9.9&&a%10<1e-6?`Your ${Math.round(a)}s`:AGE_NAMES(a)}
function planAhead(s,from){const out=[];let a=from;while(a<65-1e-6){const n=Math.min(65,stageEnd(a));out.push({from:a,to:n,icon:a>=50?'flag':a<30?'trend':'home'});a=n}out.push({from:65,to:null,icon:'sun',name:'Retirement'});return out}
const SAVE_OPTS=()=>[
{v:0.1,label:'Save 10%',hint:'Spend the rest on going out, trips and upgrades'},
{v:0.25,label:'Save a quarter',hint:'Enjoy most of it, keep some'},
{v:0.5,label:'Save half',hint:'Live well below your means'}];
const ORDER_OPTS=[
{v:'smart',label:'Cushion, card, then invest',hint:'3-month emergency fund, clear the card, invest the rest'},
{v:'invest',label:'Invest all of it',hint:'Maximum growth, no cushion'},
{v:'debt',label:'Debt-free first',hint:'Pay off every loan, highest rate first'},
{v:'cash',label:'Keep it all in savings',hint:'Safe, earns about 3.5% before inflation'}];
const ACCT_OPTS=[
{v:1,label:'All Roth IRA',hint:'Up to the $7,500 yearly limit, extra to brokerage'},
{v:.75,label:'75% Roth, 25% brokerage',hint:'Mostly tax-free, a little flexible money'},
{v:.5,label:'50% Roth, 50% brokerage',hint:'An even split'},
{v:.25,label:'25% Roth, 75% brokerage',hint:'Mostly flexible money'},
{v:0,label:'No Roth IRA, all brokerage',hint:'Skip the Roth. No limits, but taxed along the way'}];
function kOpts(s,from,sal){
return [0,0.05,0.10,0.15,0.20].filter(v=>v>=from).slice(0,3).map(v=>({v,label:v===from&&from>0?'Keep at '+pct(v):v===0?'Nothing':pct(v)+' of pay',
hint:v===0?'You skip the free 5% match':sal?`You put in ${money(sal*v)}/yr; employer adds ${money(sal*Math.min(v,C.MATCH))}`:`Employer adds 5% of your pay free`}));
}
const LIFE_Q=(s,help)=>({id:'life',type:'money',q:'How much do you spend on everyday life each year?',help:help||'Food, clothes, phone, entertainment, trips and everything else except housing, your car and kids.',def:s.lifeCustom&&s.lifestyle!=null?s.lifestyle:suggestLife(s)});
function homeQ(s){const f=s.infl,sm=downPaymentPlan(s,190000,.035),a=downPaymentPlan(s,260000),b=downPaymentPlan(s,360000);
const hint=d=>{const extra=d.brokTax+d.kCost;return `${money(d.need)} down and closing${extra>1?`, ${money(extra)} lost to taxes and penalties`:d.fromCash>=d.need-1?', all from savings':''}`};
return {id:'home',q:'Buy a home or keep renting?',help:`Buying usually takes 10% down (as little as 3.5% with an FHA loan) plus about 3% in closing costs. With your ${creditLabel(s.credit.score).toLowerCase()} credit score (${Math.round(s.credit.score)}), your 30-year mortgage rate would be ${(mortRate(s)*100).toFixed(1)}%.`,def:'rent',options:[
{v:'rent',label:'Keep renting',hint:`${money(s.rent*f)} a month now`},
{v:'small',label:`Buy a ${money(190000*f,f,{short:true})} small home, 3.5% down`,hint:hint(sm)+' · FHA loan with mortgage insurance',off:!sm.ok,why:`Needs about ${money(sm.need)} saved`},
{v:'starter',label:`Buy a ${money(260000*f,f,{short:true})} starter home`,hint:hint(a),off:!a.ok,why:`Needs about ${money(a.need)} saved`},
{v:'bigger',label:`Buy a ${money(360000*f,f,{short:true})} home`,hint:hint(b),off:!b.ok,why:`Needs about ${money(b.need)} saved`}]}}
function moveQ(s){const f=s.infl,sale=salePlan(s),cur=s.home/f,nowPay=s.mortgage.bal>1?s.mortgage.pay:0;
const opts=[{v:'stay',label:'Stay in your home',hint:nowPay?`Keep your ${money(nowPay)} a month mortgage`:'It\'s paid off: no mortgage payment'}];
for(const t of MOVE_TIERS){if(Math.abs(t.p-cur)/cur<0.15)continue;const m=movePlan(s,t.p),up=t.p>cur;
opts.push({v:t.v,label:`Sell and ${up?'move up to':'downsize to'} a ${money(t.p*f,f,{short:true})} home`,hint:`New mortgage about ${money(m.pay)} a month${nowPay?` (now ${money(nowPay)})`:''}`,off:!m.ok,why:'Not enough equity and savings for the down payment'})}
const rp=movePlan(s,null);
opts.push({v:'rent',label:'Sell and rent instead',hint:`About ${money(rentAfterSale(s)*f)} a month in rent`,off:!rp.ok,why:'You owe more than the home would sell for'});
return {id:'move',q:'Stay in your home, or sell and move?',help:`Your home is worth about ${money(s.home)} and you owe ${money(s.mortgage.bal)}. Selling costs about 6% in agent fees and closing, so you'd walk away with about ${money(sale.net)}. Most people pay no tax on that profit: up to $250,000 of gain ($500,000 for married couples) is tax-free on a home you've lived in for 2 of the last 5 years.`,def:'stay',options:opts}}
function applyHome(s,ch){if(!ch.home||ch.home==='rent'||s.home>0)return;
if(ch.home==='small')s.homeBuy=buyHome(s,190000,.035);else if(ch.home==='starter')s.homeBuy=buyHome(s,260000);else if(ch.home==='bigger')s.homeBuy=buyHome(s,360000)}
function familyQs(s,first){const f=s.infl,qs=[],a=s.age;
if(!s.partner&&a<55)qs.push({id:'family',q:first?'Your life is changing. Who are you building it with?':'Any change at home?',def:'single',options:[
{v:'single',label:first?'Staying single for now':'Staying single',hint:'One income, lowest costs'},
{v:'partner',label:'Moving in with a partner',hint:`A second income of about ${money(C.PARTNER_PAY*f)} and shared costs`}]});
if(a<45){const have=s.kids.length;qs.push({id:'kids',q:have?`You have ${have} kid${have>1?'s':''}. Have more?`:'Do you want kids?',def:0,options:[0,1,2,3,4].filter(n=>have+n<=5&&n<=(a<39?4:a<41?3:a<43?2:1)).slice(0,have?4:5).map(n=>({v:n,label:n===0?(have?'No more kids':'No kids for now'):have?`${n} more`:`${n} kid${n>1?'s':''}`,hint:n===0?(have?`Kid costs stay about ${money(kidEst(have)*f)} a month`:'Your budget stays as is'):have?`About +${money((kidEst(have+n)-kidEst(have))*f)} a month (${money(kidEst(have+n)*f)} total for ${have+n})`:`About ${money(kidEst(n)*f)} a month while they're under 18`}))})}
{const u5=s.kids.filter(b=>b+60>s.month).length,planning=qs.some(q=>q.id==='kids');if(planning||u5){const f2=s.infl;qs.push({id:'care',q:u5?'Who watches your kids until they start kindergarten?':'If you have kids, who watches them until kindergarten?',help:'Childcare is often the biggest kid cost before school. It applies until each child turns 5.',def:s.care||'center',options:Object.entries(CARE).map(([k,c])=>({v:k,label:c.label,hint:`About ${money(c.cost*f2)} a month${k==='nanny'?' for the family':' per child'}${k==='family'?', with grandparents or a partner covering most hours':k==='home'?', care in a provider\'s home':k==='center'?', the Kentucky average for a licensed center':', care in your home'}`}))})}}
return qs}
function applyFamily(s,ch){
if(ch.care&&CARE[ch.care])s.care=ch.care;
if(ch.family==='partner'&&!s.partner){s.partner=true;s.partnerPay=C.PARTNER_PAY*s.infl;story(s,'Moved in with a partner','heart');if(s.rentTier==='home'&&!(s.home>0)){const ct=CITIES[s.city]||{rent:1};s.rentTier='solo';s.rent=RENTS.solo.rent*(ct.rent||1);story(s,'Moved out of your family\'s home into a 1-bedroom with your partner','home')}}
const n=+ch.kids||0;if(n>0){const r=mulberry32((s.seed^Math.imul(s.month+1,0x9E3779B1)^Math.imul(s.kids.length+1,0x85EBCA6B))>>>0),cap=Math.round((45.5-s.startAge)*12);let prev=s.kids.length?Math.max(...s.kids):null;
for(let i=0;i<n;i++){let m=prev!=null&&prev>=s.month-12?prev+18+Math.floor(r()*31):Math.max(s.month+12+Math.floor(r()*13),prev!=null?prev+15:0);
if(m>cap)m=Math.max(cap,(prev!=null?prev:s.month)+12,s.month+9);s.kids.push(m);prev=m}story(s,`Decided to have ${n} ${s.kids.length>n?'more ':''}kid${n>1?'s':''}`,'heart')}}
function retireQ(s){const f=s.infl,sal=s.salary;return {id:'retireAge',q:'When do you plan to stop working?',help:`Working longer means more years of pay and saving and fewer years living off savings. Retire before 65 and you pay for your own health insurance until Medicare starts, about ${money(C.PRE_MEDICARE*f)} a month.`,def:s.retireAge||65,options:[62,65,67,70].map(v=>({v,label:v===65?'At 65':`At ${v}`,hint:v===62?`Three fewer years of pay than at 65, plus about ${money(C.PRE_MEDICARE*f)} a month for health insurance until 65`:v===65?'When Medicare starts':`${v-65} more year${v-65>1?'s':''} of pay, about ${money(sal*(v-65),f,{short:true})} before taxes, and fewer years to fund`}))}}
const aOr=w=>(/^[aeiou]/i.test(w)?'an ':'a ')+w;
const jobPhrase=s=>s.career==='custom'?(s.careerTitle&&s.careerTitle!=='My job'?aOr(s.careerTitle):'your job'):aOr(careerLabel(s).toLowerCase());
function homeOK(s){return s.age<30-1e-6&&!s.partner&&!s.kids.length}
function rentOpts(s,f,stay){return Object.entries(RENTS).map(([k,r])=>k==='home'?{v:k,label:stay?'Stay at home a few more years':r.label,hint:`Chip in about ${money(r.rent*f)} a month for groceries and bills`,off:!homeOK(s)||(stay&&s.age>=28-1e-6),why:stay&&s.age>=28-1e-6?'Time to move out by 30':'Only before 30, without a partner or kids'}:{v:k,label:r.label,hint:`About ${money(r.rent*f)} a month in Lexington or Louisville`})}
function moveOutQ(s){return {id:'rent',q:'You\'ve been living at home. Time to move out?',help:'Living at home is the cheapest way to start, but most people move out by 30.',def:'room',options:rentOpts(s,s.infl,true)}}
function decisions(s,key){const qs=decisionsRaw(s,key);if(!Array.isArray(qs))return qs;
if(!s.retired&&!s.flat&&['check','build','mid'].includes(key)&&s.age>=59.5-1e-6&&s.age<65-1e-6&&!qs.some(q=>q.id==='retireAge'))qs.push(retireQ(s));const si=qs.findIndex(q=>q.id==='save'),ki=qs.findIndex(q=>q.id==='k401');if(si>=0&&ki>si){const [k]=qs.splice(ki,1);qs.splice(si,0,k)}return qs}
function decisionsRaw(s,key){
const f=s.infl;
if(key==='college'){
const qs=[];
if(s.card.bal>0){const pay=Math.min(s.cash,s.card.bal);
qs.push({id:'card',q:`What about your ${money(s.card.bal)} credit card balance?`,def:'min',options:[
{v:'min',label:'Keep paying the minimum',hint:`About ${money(s.card.bal*s.card.rate)} a year in interest`},
{v:'pay',label:pay>=s.card.bal?'Pay it off from savings':'Pay down what I can',hint:`Uses ${money(pay)} of your ${money(s.cash)} cash`,off:s.cash<1,why:'You have no savings to use'}]})}
qs.push({id:'cover',q:'How will you handle money for the rest of college?',def:'none',options:[
{v:'none',label:'Keep things as they are',hint:'Same income, same spending'},
{v:'borrow',label:'Borrow $5,000 more a year',hint:'More breathing room now, more debt later'},
{v:'work',label:'Work 10 more hours a week',hint:'About $470 more a month after taxes'},
{v:'cut',label:'Spend $200 less a month',hint:'Cook more, fewer nights out'},
...(s.schoolSpend>s.schoolIncome?[{v:'gap',label:'Borrow just enough to cover the gap',hint:`About ${money((s.schoolSpend-s.schoolIncome)*f)} a month more in student loans`}]:[])]});
return qs;
}
if(key==='first')return [
{id:'career',q:s.grad?'What job do you have?':'You graduate. What job do you take?',def:'accountant',custom:true,options:[...CAREERS.map(c=>({v:c.id,label:c.label,hint:`${s.grad&&expMult(s)>1.01?'Pays about':'Starts near'} ${money(c.salary*expMult(s)*f)} a year`})),{v:'custom',label:'My own job',hint:'Type your job and expected salary'}]},
{id:'city',q:'Where do you live and work?',def:'lex',options:[
{v:'lex',label:'Lexington',hint:'2.25% city payroll tax'},
{v:'lou',label:'Louisville',hint:'2.2% payroll tax for residents, slightly higher pay'},
{v:'town',label:'A smaller Kentucky town',hint:'Cheaper rent, about 1% payroll tax, lower pay'}]},
{id:'rent',q:'Where do you live?',def:'room',options:rentOpts(s,f,false)},
{id:'car',q:s.grad?'What about your car?':'Your old car still runs. Now what?',def:'keep',options:[
{v:'keep',label:'Keep driving it',hint:`Worth about ${money(s.carValue)}, no payment`},
{v:'used',label:'Buy a newer used car',hint:`${money(22000*f)}, ${money(pmt(Math.max(0,22000*f-s.carValue),0.075,60))}/mo for 5 years`},
{v:'new',label:'Buy a new SUV',hint:`${money(46000*f)}, ${money(pmt(Math.max(0,46000*f-s.carValue),0.07,72))}/mo for 6 years`}]},
...(!(s.home>0)?[homeQ(s)]:[]),
{id:'exercise',q:'How do you take care of your health?',def:'some',options:[
{v:'low',label:'Mostly on the couch',hint:'Free now, costly later'},
{v:'some',label:'Walks and pickup games',hint:'Free, a little activity most weeks'},
{v:'high',label:'Gym 3 or 4 times a week',hint:`${money(C.GYM_COST*f)} a month membership`}]},
{id:'smoke',q:'Do you smoke or vape nicotine?',def:'never',options:[
{v:'never',label:'No',hint:'Nothing to pay'},
{v:'smoker',label:'Yes, about a pack a day',hint:`${money(C.SMOKE_COST*f)} a month`}]},
LIFE_Q(s),
{id:'health',q:'Which health plan do you pick at work?',help:'Most employers offer a choice. A high-deductible plan costs less each month but you pay more when you need care, and it lets you open a health savings account (HSA).',def:'ppo',options:[
{v:'ppo',label:'Standard plan',hint:`About ${money(C.PPO_EXTRA*f)} more a month, smaller bills when you need care`},
{v:'hdhp',label:'High-deductible plan + HSA',hint:`Lower premiums, you put ${money(150*f)} a month in an HSA`},
{v:'hdhpmax',label:'High-deductible plan + max the HSA',hint:`Put the full ${money(C.HSA_SELF*f)} a year in your HSA`}]},
{id:'fund',q:'What do you invest in?',help:'This applies to your 401(k), IRA and brokerage money. Funds charge a yearly fee called an expense ratio.',learn:FUND_GUIDE,def:'index',options:[
{v:'index',label:'Low-cost index funds',hint:'About 0.05% a year in fees'},
{v:'target',label:'A target-date fund',hint:'About 0.12% a year, adjusts itself as you age'},
{v:'managed',label:'An advisor-managed account',hint:'About 1% a year in fees'}]},
riskQ(s,'first'),
{id:'k401',q:'How much of your pay goes into your 401(k)?',help:'Your employer matches dollar for dollar up to 5% of your pay.',def:0,options:kOpts(s,0,0)},
{id:'save',q:'After bills, how much of what is left do you save?',def:0.25,options:SAVE_OPTS()},
{id:'acct',q:'How do you split invested savings between a Roth IRA and a brokerage account?',help:'This is for savings beyond your 401(k).',learn:rothGuide(),def:1,options:ACCT_OPTS}];
if(key==='build')return [
...(s.rentTier==='home'&&!(s.home>0)?[moveOutQ(s)]:[]),
...(s.smoke==='smoker'?[{id:'quit',q:'You\'re still smoking. Quit now?',def:'keep',options:[
{v:'quit',label:'Quit now',hint:'Hard, but you\'re under 40'},
{v:'keep',label:'Keep smoking',hint:`${money(C.SMOKE_COST*f)} a month and counting`}]}]:[]),
...familyQs(s,true),
...(!(s.home>0)?[homeQ(s)]:[moveQ(s)]),
LIFE_Q(s,'A partner and kids change your budget. Kids cost about '+money(kidEst(1)*12*s.infl)+' a year for one or '+money(kidEst(2)*12*s.infl)+' for two on top of this, and a partner adds about '+money(C.PARTNER_COST*12*s.infl)+'.'),
{id:'ins',q:'Do you want life insurance?',help:'Life insurance pays your family if you die. It matters most when a partner or kids depend on your income. Prices are rough estimates for your age and habits.',learn:INS_GUIDE,extra:insBoxHTML(s),def:'none',options:[
{v:'none',label:'No life insurance',hint:'Nothing to pay'},
{v:'term',label:'Term life',hint:'Cheap coverage for 10 to 30 years. Pick the length and amount below'},
{v:'whole',label:'Whole life, $250,000',hint:`About ${money(insQuote(s,'whole')*f)} a month for life, builds cash value`}]},
{id:'save',q:'Your promotion means more money each month. How much of what is left do you save?',def:s.savePct,options:SAVE_OPTS()},
{id:'order',q:'In what order does your saved money get used?',def:'smart',options:ORDER_OPTS},
{id:'acct',q:'Change your Roth IRA and brokerage split?',learn:rothGuide(),def:s.rothShare,options:ACCT_OPTS},
{id:'k401',q:'Change your 401(k)?',def:s.kPct,options:kOpts(s,s.kPct,s.salary)}];
if(key==='check'){const qs=[];if(s.rentTier==='home'&&!(s.home>0))qs.push(moveOutQ(s));
if(!(s.home>0)){if(s.age<60)qs.push(homeQ(s))}else qs.push(moveQ(s));
qs.push(...familyQs(s,false));
if(s.kids.length&&!s.collegeSet)qs.push({id:'college',q:'How will you help with your kids\' college?',def:'none',options:[
{v:'none',label:'They pay their own way',hint:'Loans, scholarships and jobs, like you'},
{v:'pay',label:'Pay when they get there',hint:`About ${money(C.KID_COLLEGE*f)} each from savings at 18`},
{v:'529',label:'Save in a KY Saves 529',hint:`${money(C.K529*f)} a month per kid, grows tax-free`}]});
qs.push(LIFE_Q(s,s.age>=50?'Kids grown? Empty nesters often spend less, or more on travel. Everything except housing, your car and kids.':null));
qs.push({id:'save',q:'How much of what is left each month do you save?',def:s.savePct,options:SAVE_OPTS()});
qs.push({id:'k401',q:'Change your 401(k)?',help:s.age>=50?'From age 50 you can put an extra $8,000 a year into a 401(k), and $11,250 at ages 60 to 63.':null,def:s.kPct,options:kOpts(s,s.kPct,s.salary)});
qs.push({id:'acct',q:'Change your Roth IRA and brokerage split?',learn:rothGuide(),def:s.rothShare,options:ACCT_OPTS});
qs.push(riskQ(s,'check'));
return qs;
}
if(key==='mid')return [
{id:'crash',q:'What do you do with your investments?',def:'stay',options:[
{v:'stay',label:'Stay invested',hint:'Ride it out and keep contributing'},
{v:'sell',label:'Sell and wait in cash',hint:'Stop the bleeding, buy back in 3 years'}]},
...decisions(s,'check')];
if(key==='retire2'){const rs=s.retireSpend*s.infl/s.infl65;return [
{id:'spend',q:'Change how you live in retirement?',help:`Your savings: ${money(liquidAfterTax(s))} after taxes. Social Security pays about ${money(s.ssMonthly*s.infl/s.infl65)} a month${s.age<s.ssClaim?` starting at ${s.ssClaim}`:''}.`,def:s.spendStyle,options:[
{v:.8,label:'Simple and careful',hint:`About ${money(.8*rs)} a month`},
{v:1,label:'Same as when you retired',hint:`About ${money(rs)} a month`},
{v:1.2,label:'Travel and treat yourself',hint:`About ${money(1.2*rs)} a month`}]}]}
if(key==='retire'){const pia=s.pia,rs=s.retireSpend;
return [
{id:'ss',q:'When do you start Social Security?',help:'Your full retirement age is 67. Claiming earlier shrinks your check for life; waiting grows it.'+(s.partner?' Amounts include your partner\'s benefit, so they\'re for the two of you.':''),def:[62,65,67,70].find(v=>v>=Math.round(s.age)-1e-6)||70,options:[62,65,67,70].filter(v=>v>=Math.round(s.age)-1e-6).map((v,i)=>({v,label:i===0?`Start now, at ${v}`:`Wait until ${v}`,hint:`${money(pia*SSF[v],f)} a month, ${v===67?'your full benefit':v<67?Math.round((1-SSF[v])*100)+'% less than at 67':Math.round((SSF[v]-1)*100)+'% more than at 67'}`}))},
{id:'spend',q:'How do you want to live in retirement?',help:'Work costs like commuting stop, but health care costs rise. Many retirees end up spending about what they did before.',def:1,options:[
{v:.8,label:'Simple and careful',hint:`80% of what you spend now, about ${money(.8*rs,f)} a month`},
{v:1,label:'Keep living the same way',hint:`About ${money(rs,f)} a month`},
{v:1.2,label:'Travel and treat yourself',hint:`20% more than now, about ${money(1.2*rs,f)} a month`}]},
riskQ(s,'retire')];
}
}
function applyDecisions(s,key,ch){
if(key!=='first'&&ch.rent&&RENTS[ch.rent]&&s.rentTier==='home'&&!(s.home>0)&&ch.rent!=='home'){const ct=CITIES[s.city]||{rent:1};s.rentTier=ch.rent;s.rent=RENTS[ch.rent].rent*(ct.rent||1);if(!s.flat)story(s,`Moved out of your family's home: ${RENTS[ch.rent].label.toLowerCase()}`,'home')}
if(ch.retireAge&&!s.retired){const v=+ch.retireAge;if(v!==(s.retireAge||65)&&!s.flat)story(s,`Planned to retire at ${v}`,'sun');s.retireAge=v}
if(ch.risk&&RISK[ch.risk]&&key!=='college'){if(s.risk!==ch.risk&&!s.flat&&key!=='first')story(s,`Switched to ${aOr(RISK[ch.risk].label.toLowerCase())} investment mix`,'trend');s.risk=ch.risk}
if(ch.life!=null&&key!=='retire'&&key!=='retire2'&&key!=='college'){if(ch.lifeCustom){s.lifestyle=Math.max(3000,+ch.life);s.lifeCustom=true}else{s.lifestyle=null;s.lifeCustom=false}}
if(key==='college'){
if(ch.card==='pay'){const x=Math.min(s.cash,s.card.bal);s.cash-=x;s.card.bal-=x}
s.extraLoan=ch.cover==='borrow'?5000/12:0;s.coverGap=ch.cover==='gap';s.extraWork=ch.cover==='work'?470:0;s.spendCut=ch.cover==='cut'?200:0;
s.savePct=1;s.order=ch.cover==='borrow'?'cash':'smart';s.rothShare=1;
}
if(key==='first'){
if(!s.grad)story(s,'Graduated from college','cap');
graduate(s);const city=CITIES[ch.city];s.city=ch.city;s.localRate=city.rate;
if(ch.career==='custom'){s.career='custom';s.careerTitle=ch.customTitle||'My job';s.payStyle=ch.customStyle||'average';s.salary=(ch.customSalary||50000)*s.infl}
else{const c=CAREERS.find(c=>c.id===ch.career);s.career=c.id;s.salary=c.salary*expMult(s)*city.pay*s.infl}
s.rentTier=ch.rent;s.rent=RENTS[ch.rent].rent*city.rent;s.carPlan=ch.car;
if(ch.car==='used')buyCar(s,22000,0.075,60,270);else if(ch.car==='new')buyCar(s,46000,0.07,72,320);else s.carRun=250;
s.kPct=+ch.k401;s.savePct=+ch.save;s.order='smart';s.rothShare=+ch.acct;
if(ch.exercise)s.exercise=ch.exercise;if(ch.smoke)s.smoke=ch.smoke;
if(ch.health){s.health=ch.health==='ppo'?'ppo':'hdhp';s.hsaPlan=ch.health==='hdhpmax'?'max':ch.health==='hdhp'?'some':'none'}
if(ch.fund)s.fee={index:.0005,target:.0012,managed:.01}[ch.fund];
story(s,`${jobPhrase(s)==='your job'?'Started your job':`Started work as ${jobPhrase(s)}`} in ${CITIES[s.city].label==='A smaller Kentucky town'?'a smaller Kentucky town':CITIES[s.city].label}, earning ${money(s.salary,s.infl)}`,'brief');
if(s.smoke==='smoker')story(s,'Started smoking','bolt');
applyHome(s,ch);
}
if(key==='build'){
s.didBuild=true;if(ch.quit==='quit'){s.smoke='quit';story(s,'Quit smoking','heart')}
if(ch.ins){buyInsurance(s,ch.ins,ch.insYears,ch.insFace);if(ch.ins!=='none')story(s,ch.ins==='term'?`Bought a ${s.ins.years}-year, ${money(s.ins.face,s.infl)} term life policy`:'Bought a whole life policy','shield')}
}
if(key==='mid'){s.didCrash=true;story(s,ch.crash==='sell'?'Sold everything in the market crash':'Stayed invested through a market crash','waves');
if(ch.crash==='sell'){const tax=C.LTCG*Math.max(0,s.brok-s.brokBasis);s.brok-=tax;s.brokBasis=s.brok;s.totals.crashTax+=tax;s.soldUntil=s.month+36}
else s.boostUntil=s.month+36;
}
if(key!=='first'&&key!=='college'&&key!=='retire'&&key!=='retire2'){
if('save' in ch)s.savePct=+ch.save;if('order' in ch)s.order=ch.order;if('acct' in ch)s.rothShare=+ch.acct;if('k401' in ch)s.kPct=+ch.k401;
applyFamily(s,ch);applyHome(s,ch);applyMove(s,ch);
if(ch.college){s.college=ch.college;s.collegeSet=true;if(ch.college==='529')story(s,'Opened KY Saves 529 accounts for the kids','cap')}
}
if(key==='retire'){story(s,`Retired, with Social Security starting at ${ch.ss}`,'sun');s.ssClaim=+ch.ss;s.ssMonthly=s.pia*SSF[+ch.ss]*s.infl65/s.infl;s.spendStyle=+ch.spend}
if(key==='retire2'){s.spendStyle=+ch.spend}
}
function twinize(t,key,ch,s,cred0){
const c={...ch};if(c.college==='529')c.college='pay';
t.noInvest=true;if(cred0)t.credit=structuredClone(cred0);
if(s){t.respond={...(s.respond||{})};t.mirror={...(s.picks||{})};t.mirrorCars={...(s.carLog||{})};t.mirrorCarRates={...(s.carRates||{})}}
applyDecisions(t,key,c);
t.soldUntil=-1;t.boostUntil=-1;
}
function enterStage(s,key){
if(key==='build'){const old=s.salary;s.salary*=1.10;return {old,now:s.salary}}
if(key==='retire'){s.retired=true;s.retireAt=Math.round(s.age);s.infl65=s.infl;s.retireSpend=s.lastYrSpend/12;s.pia=ssPIA(s);s.kPct=0;s.noIncome=0;return {pia:s.pia,spend:s.retireSpend,nw:netWorth(s)}}
if(key==='mid'){const old=invested(s),d=crashDrop(s.age,s.risk);s.k401*=1-d;s.roth*=1-d;s.brok*=1-d;s.yrGrowth=(s.yrGrowth||0)+invested(s)-old;s.yrStart=invested(s);s.crashAge=s.age;s.crashDrop=d;return {old,now:invested(s),d,w:mixAt(s.age,s.risk).w}}
return null;
}
function stageTo(s,blk){return !s.retired&&!['retire','retire2','college'].includes(blk.key)&&s.retireAge&&blk.to>s.retireAge+1e-6?s.retireAge:blk.to}
function runStage(s,blk){
const key=blk.key,months=Math.max(1,Math.round((stageTo(s,blk)-s.age)*12));
syncRT(s);const rb={...s.rt};const credit0=s.credit.score,before={...s.totals},nw0=netWorth(s),car0=s.carValue,y0=Math.floor(s.month/12);s.stageEvents=[];s.maxedThisStage=false;s.stageRaises=[];s.stageBonus={n:0,amt:0};
for(let m=0;m<months;m++)step(s);
if(!s.flat&&s.stageBonus.n>0)lifeEvent(s,`${s.stageBonus.n} year-end bonus${s.stageBonus.n>1?'es':''}`,`Your bonuses added ${money(s.stageBonus.amt,s.infl)} after taxes. You saved ${Math.round(s.savePct*100)}% of it and spent the rest.`,'Bonuses are taxed as regular pay, often withheld at a flat 22% federal rate. Saving most of a bonus barely changes your lifestyle but can jump you ahead.','good');
const raises=[...s.stageRaises];
syncRT(s);const d={};for(const k in s.totals)d[k]=typeof s.totals[k]==='number'?((s.rt[k]||0)-(rb[k]||0))*s.infl:0;
const events=s.stageEvents.map(e=>({...e,shortAfter:s.totals.shortfall}));
const mkt=s.market.slice(y0,Math.floor(s.month/12)).map((z,i)=>{const r=mktReturn(s,y0+i);const mo=(y0+i)*12;return mo<s.soldUntil&&mo>=s.soldUntil-36?null:mo<s.boostUntil&&mo>=s.boostUntil-36?0.12:r}).filter(r=>r!=null);
return {key,months,nw0,nw1:netWorth(s),d,events,car0,mkt,raises,credit0,ageFrom:s.age-months/12,ageTo:s.age};
}
function project(s,blk,ch){
const c=structuredClone({...s,history:[],schedule:[],stageEvents:[]});c.sp=0;c.flat=true;
applyDecisions(c,blk.key,ch);runStage(c,blk);
let nb,guard=0,at65=null;const grab=()=>{if(!at65&&s.age<65-1e-6&&c.history.length&&c.history[c.history.length-1].age>=65-1e-6){const q=nwAt(c.history,65);at65={nw:q.nw,f:q.f}}};grab();
while((nb=nextBlock(c))&&guard++<40){enterStage(c,nb.key);const d={};for(const q of decisions(c,nb.key))if(q.def!==undefined)d[q.id]=q.def;applyDecisions(c,nb.key,d);runStage(c,nb);grab()}
return {nw:netWorth(c),f:c.infl,nw65:at65?at65.nw:null,f65:at65?at65.f:null};
}
function retirement(s){
const f=s.infl,port=liquidAfterTax(s),draw=port*0.04/12,ss=ssPIA(s);
const need=0.8*(s.lastYrSpend/12);return {port,draw,ss,need,ok:draw+ss>=need,f};
}
// ---------- explanations ----------
const FUND_GUIDE=`<div class="fundcmp">
<div><h4>Index fund</h4><p><b>What it is:</b> one fund that owns a slice of every company in a market index, like the S&P 500 (the 500 biggest US companies) or the whole stock market.</p><p><b>Who picks:</b> nobody. It just copies the index, which is why it's so cheap.</p><p><b>You do:</b> pick a stock fund and a bond fund, choose the mix, and shift it toward bonds as you age.</p><p class="fee">Fee: about 0.05% a year, or $5 per $10,000</p></div>
<div><h4>Target-date fund</h4><p><b>What it is:</b> a bundle of index funds named for the year you plan to retire, like "Target 2070." It holds mostly stocks while you're young and slowly moves to bonds as that year gets closer.</p><p><b>Who picks:</b> the fund company, on autopilot.</p><p><b>You do:</b> nothing but keep adding money. It's often the default in a 401(k).</p><p class="fee">Fee: about 0.12% a year, or $12 per $10,000</p></div>
<div><h4>Advisor-managed account</h4><p><b>What it is:</b> a financial advisor or managed service builds and runs your portfolio for you, often alongside planning help with taxes, insurance and goals.</p><p><b>Who picks:</b> the advisor, who is paid a percentage of your balance every year.</p><p><b>You do:</b> meet with them now and then. A good one can keep you from panic-selling in a crash.</p><p class="fee">Fee: about 1% a year, or $100 per $10,000</p></div>
</div>
<p class="fundline"><b>Why the fee matters:</b> $500 a month for 40 years at 7% a year (before fees and inflation) grows to about <b>$1.22 million</b> in index funds, <b>$1.20 million</b> in a target-date fund and <b>$954,000</b> with a 1% advisor. Same savings, same market, about <b>$266,000</b> less, all from fees. In this game all three earn the same market return and get safer with age; only the fee differs.</p>`;
const INS_GUIDE=`<div class="fundcmp four">
<div><h4>What it is</h4><p>You pay a monthly <b>premium</b>. If you die while covered, the insurer pays a lump sum, the <b>death benefit</b>, to the people you name (your <b>beneficiaries</b>). It's usually tax-free to them.</p></div>
<div><h4>Who needs it</h4><p>Anyone whose income other people rely on: a partner, kids, or someone who'd be stuck with a shared mortgage. If nobody depends on your paycheck, you may not need much yet.</p></div>
<div><h4>How much</h4><p>A common rule is <b>10 to 12 times your income</b>. Another way: add up your debts, your mortgage, a few years of income and your kids' college, then subtract what you've saved.</p></div>
<div><h4>Term vs. whole</h4><p><b>Term</b> covers a set number of years (10 to 30) and is cheap. <b>Whole life</b> lasts forever and builds cash value, but costs roughly 10 times more. Many planners say: buy term and invest the difference.</p></div>
</div>
<p class="fundline"><b>Tips:</b> buy while you're young and healthy, since the price is locked for the whole term. Match the length to the years people depend on you, like until your youngest finishes school or your mortgage is paid off. Coverage through work is often 1 to 2 times your salary and ends when you leave the job, so it's rarely enough on its own.</p>`;
function insBoxHTML(s){const rec=insRec(s);
return `<div class="insbox" id="insBox" hidden>
<div class="isl"><label for="ins-yrs">How long it covers you <b id="ins-yrs-v">20 years</b></label><input type="range" id="ins-yrs" min="0" max="4" step="1" value="2"><div class="ticks">${TERM_YRS.map(y=>`<span>${y}</span>`).join('')}</div></div>
<div class="isl"><label for="ins-face">How much your family gets <b id="ins-face-v"></b></label><p class="sugg">Rule of thumb: about ${money(rec*s.infl,s.infl)}, 10 times your income</p><input type="range" id="ins-face" min="100000" max="2000000" step="50000" value="${rec}"><div class="ticks"><span>${money(100000*s.infl,s.infl,{short:true})}</span><span>${money(2000000*s.infl,s.infl,{short:true})}</span></div></div>
<div class="insout"><div><span class="eyebrow">Monthly price</span><div class="big" id="ins-prem"></div></div><div><span class="eyebrow">Covered until</span><div class="big" id="ins-end"></div></div><div><span class="eyebrow">Total premiums</span><div class="big" id="ins-tot"></div></div></div>
<div><span class="eyebrow">Monthly price by length, for this amount</span><div class="insbars" id="ins-bars"></div></div>
</div>`}
function insBoxUpd(s,ch){const f=s.infl,y=ch.insYears||20,fc=ch.insFace||500000,p=termQuote(s,y,fc),mx=termQuote(s,30,fc);
$('ins-yrs-v').textContent=y+' years';$('ins-face-v').textContent=money(fc*f,f)+` · ${(fc/(s.salary/f)).toFixed(1)}x your income`;
$('ins-prem').textContent=money(p*f,f);$('ins-end').textContent='Age '+(Math.round(s.age)+y);$('ins-tot').textContent=money(p*12*y*f,f,{short:true});
$('ins-bars').innerHTML=TERM_YRS.map(t=>{const q=termQuote(s,t,fc);return `<div class="ib${t===y?' on':''}"><span class="ibv">${money(q*f,f)}</span><i style="height:${Math.max(6,q/mx*100)}%"></i><span class="ibl">${t} yrs</span></div>`}).join('')}
const pctr=x=>(x>=0?'+':'−')+Math.round(Math.abs(x)*100)+'%';
function retChoiceHTML(){const v=G.inp.returns||'hist',keep=RET_MODE,g=m=>{RET_MODE=m;const x=mixAt(30,'growth').flat;RET_MODE=keep;return x};
return `<fieldset class="q retq"><legend style="font-size:var(--fs-base)">How should markets behave in your game?</legend>
<p class="muted" style="font-size:var(--fs-sm);margin:0">Every return in the game is <b>before inflation</b>. Prices rise 3% a year, so subtract about 3 points to see real growth: 7% before inflation is about 4% after.</p>
<div class="opts"><label class="opt"><input type="radio" name="retmode" value="hist" ${v==='hist'?'checked':''}><b>Historical <span class="otag">Default</span></b><span class="hint">Long-run US averages: stocks about 10% a year, bonds about 5%. The growth mix earns ${retTxt(g('hist'))}.</span></label>
<label class="opt"><input type="radio" name="retmode" value="cautious" ${v==='cautious'?'checked':''}><b>Cautious</b><span class="hint">Lower returns, closer to big investment firms' forecasts for the next decade: stocks about 8%, bonds about 4%. The growth mix earns ${retTxt(g('cautious'))}.</span></label></div></fieldset>`}
function riskGrow(age,risk,monthly,lump){let v=lump||0;for(let a=age;a<65;a+=1/12){const r=mixAt(a,risk).flat;v=v*Math.pow((1+r)/(1+C.INFL),1/12)+(monthly||0)}return v}
function riskQ(s,when){const a=s.age,first=when==='first',ret=when==='retire';
return {id:'risk',q:first?'How much risk do you want to take with your investments?':ret?'How much risk do you take in retirement?':'Change how much investment risk you take?',
help:ret?'You\'ll now sell investments to live on. A big drop early in retirement hurts most, because you sell while prices are down. But too little risk lets inflation eat your savings.':'This sets your mix of stocks and bonds in your 401(k), IRA and brokerage account. Stocks grow more but swing harder. Bonds are steadier but grow less. Every mix gets safer as you age.',
suggest:riskSuggestText(a),learn:riskGuide(s),def:s.risk||'growth',options:Object.entries(RISK).map(([k,r])=>{const m=mixAt(a,k),sg=riskSuggest(a);return {v:k,label:`${r.label}: ${Math.round(m.w*100)}% stocks`,tag:k===sg.k?'Typical for your age':k===sg.alt?'Also typical for your age':'',hint:`Average year ${pctr(m.mean)} before inflation, a bad year ${pctr(m.mean-1.65*m.sd)}`,extra:mixBar(m.w)}})}}
function riskGuide(s){const a=s.age,lo=-.35,hi=.5,x=v=>((v-lo)/(hi-lo)*100).toFixed(1);
const rows=Object.entries(RISK).map(([k,r])=>{const m=mixAt(a,k),b=m.mean-1.65*m.sd,g=m.mean+1.65*m.sd;
const sg=riskSuggest(a);return `<div class="rrow"><span class="rlab"><b>${r.label}${k===sg.k?' <span class="otag">Typical</span>':''}</b><small>${Math.round(m.w*100)}% stocks / ${Math.round(100-m.w*100)}% bonds</small><small class="rrng">${pctr(b)} to ${pctr(g)}</small></span><span class="rbar" aria-label="${r.label}: bad year ${pctr(b)}, average ${pctr(m.mean)}, good year ${pctr(g)}"><i class="rzero" style="left:${x(0)}%"></i><i class="rrange" style="left:${x(b)}%;width:${(x(g)-x(b)).toFixed(1)}%"></i><i class="ravg" style="left:${x(m.mean)}%"></i><em style="left:${x(b)}%">${pctr(b)}</em><em class="r" style="left:${x(g)}%">${pctr(g)}</em></span>${a<64?`<span class="rend">${money(riskGrow(a,k,0,10000)*s.infl,s.infl,{short:true})}</span>`:''}</div>`}).join('');
const Q=(n,q,opts)=>`<fieldset class="rq"><legend>${q}</legend>${opts.map((o,i)=>`<label><input type="radio" name="rq${n}" value="${i}"> ${o}</label>`).join('')}</fieldset>`;
return `<p style="margin:0 0 8px"><b>Risk tolerance</b> is how much your investments can drop without you panicking or needing the money. It has two parts: <b>time</b> (money you won't touch for 20 years can ride out crashes) and <b>stomach</b> (a mix you'll stick with beats a bolder one you abandon in a crash).</p>
<div class="rchart"><div class="rrow rhead"><span class="rlab"></span><span class="rbar-h">A bad year (1 in 20) to a great year, with the average</span>${a<64?'<span class="rend">$10,000 at 65</span>':''}</div>${rows}</div>
<p class="muted" style="font-size:var(--fs-sm);margin:4px 0 12px">Ranges are for your age now. Dollar amounts are in today's dollars with average returns.</p>
<div class="rmix"><b>What's inside each mix</b> <span class="mixkey" style="display:inline-flex;margin-left:6px"><span><i style="background:var(--c-k401)"></i>US stocks</span><span><i style="background:var(--c-roth)"></i>International stocks</span><span><i style="background:var(--c-cash)"></i>Bonds</span></span><p class="muted" style="font-size:var(--fs-sm);margin:2px 0 8px">A typical way to build each mix at your age, like a target-date or all-in-one fund would. <b>US stocks</b> are shares of American companies. <b>International stocks</b> are companies in other countries, which spreads your risk. <b>Bonds</b> are loans to governments and companies that pay steady interest and usually fall less in a crash. The game tracks stocks and bonds; the US and international split is for illustration.</p>
${Object.entries(RISK).map(([k,r])=>`<div class="rmixrow"><span class="rmixlab">${r.label}</span>${mixBar(mixAt(a,k).w)}</div>`).join('')}
<p class="muted" style="font-size:var(--fs-sm);margin:8px 0 0">Every mix shifts toward bonds as you age: after 50, and again after 65.</p></div>
<div class="rquiz"><h4>Quick quiz: what's your risk tolerance?</h4>
${Q(1,'When will you need most of this money?',['Within 5 years','In 5 to 15 years','In 15 to 30 years','More than 30 years from now'])}
${Q(2,'Your investments drop 30% in a year. What do you do?',['Sell everything before it gets worse','Sell some to be safe','Do nothing and wait','Buy more while prices are low'])}
${Q(3,'Which would you rather have?',['A steady 4% a year, never a loss','About 6% a year, sometimes down 10%','About 7% a year, sometimes down 20%','About 8% a year, sometimes down 30%'])}
<div class="rq-out" id="rqOut" aria-live="polite">Answer all three to see your result.</div></div>`}
function riskQuiz(){const v=n=>{const e=document.querySelector(`input[name=rq${n}]:checked`);return e?+e.value:null},a=v(1),b=v(2),c=v(3),out=$('rqOut');if(!out)return;
if(a==null||b==null||c==null){out.textContent='Answer all three to see your result.';return}
let k=a+b+c,lvl=k<=2?'cons':k<=4?'bal':k<=7?'growth':'aggr',why='';
if(b===0&&(lvl==='growth'||lvl==='aggr')){lvl='bal';why=' You said you\'d sell in a crash, so a calmer mix you can stick with beats a bolder one you\'d abandon at the worst time.'}
if(a===0&&lvl!=='cons'){lvl='cons';why=' You need the money soon, and there may not be time to recover from a crash.'}
if(a===3&&b>=2&&lvl==='bal'){why=' With decades to go and a steady stomach, you could handle more risk if you wanted.'}
{const ag=G.s?G.s.age:G.inp.age,sg=riskSuggest(ag);if(lvl!==sg.k&&lvl!==sg.alt)why+=lvl==='cons'||lvl==='bal'?` For your age the suggestion is ${RISK[sg.k].label}. A calmer mix you'll stick with is fine, but it grows slower, so you may need to save a bit more.`:` For your age the suggestion is ${RISK[sg.k].label}. More risk can mean more growth, but only if you hold on in a crash.`;else why+=` That matches the suggestion for your age.`}
out.innerHTML=`<b>Your result: ${RISK[lvl].label}.</b>${why} <button type="button" class="btn ghost" id="rqUse">Use ${RISK[lvl].label}</button>`;
$('rqUse').onclick=()=>{const i=document.querySelector(`input[name="q-risk"][value="${lvl}"]`);if(i){i.checked=true;i.dispatchEvent(new Event('change',{bubbles:true}))}out.querySelector('button').textContent='Selected';}}
function acctGuide(){return `<div class="fundcmp four acctcards">
<div><b><i class="sw" style="background:var(--c-k401)"></i>401(k)</b><p>Through your job. Money comes out of your paycheck <strong>before income tax</strong>, and many employers <strong>match</strong> part of it. Taxed when you take it out in retirement. 2026 limit: $24,500.</p><p class="ex"><strong>Example:</strong> you earn $50,000 and put in 5% ($2,500). Your job matches another $2,500, so $5,000 goes in, and you owe about $390 less in income tax this year.</p></div>
<div><b><i class="sw" style="background:var(--c-ira)"></i>Traditional IRA</b><p>One you open yourself, with the same deal as a 401(k): a tax break now if your income qualifies, and <strong>taxed when you take it out</strong>. Shares the $7,500 IRA limit with a Roth.</p><p class="ex"><strong>Example:</strong> you leave your first job with $8,000 in its 401(k). You <strong>roll it over</strong> into a Traditional IRA: no tax, no penalty, and you pick the funds.</p></div>
<div><b><i class="sw" style="background:var(--c-roth)"></i>Roth IRA</b><p>You put in money you've <strong>already paid tax on</strong>. It grows tax-free and comes out <strong>tax-free</strong> after 59½. You can take out what you put in anytime. 2026 limit: $7,500.</p><p class="ex"><strong>Example:</strong> $3,000 from a summer job at 20, left alone at 7% a year before inflation, is about <strong>$63,000 at 65</strong>, and you owe $0 in tax on it.</p></div>
<div><b><i class="sw" style="background:var(--c-brok)"></i>Brokerage account</b><p>A regular investing account at a brokerage. <strong>No limits, no lock-up</strong>, but no tax break: you pay tax on dividends each year and on gains when you sell.</p><p class="ex"><strong>Example:</strong> you buy $1,000 of an index fund and sell it years later for $3,000. You owe tax on the $2,000 gain, usually 15%, so <strong>$300</strong>.</p></div></div>`}
function rothGuide(){const fv=7500*((Math.pow(1.07,43)-1)/.07),put=7500*43,gain=fv-put,tax=gain*.15,k=v=>'$'+(v>=1e6?(v/1e6).toFixed(2)+' million':Math.round(v/1000)+',000');
return `<div class="fundcmp four">
<div><h4>What it is</h4><p>A retirement account you fill with money you've <b>already paid tax on</b>. It grows tax-free, and in retirement you take it all out <b>tax-free</b>, forever.</p></div>
<div><h4>Why it's great when you're young</h4><p>Your tax rate is probably as low now as it will ever be. Paying a little tax today and <b>never on the growth</b> is usually one of the best deals in money.</p></div>
<div><h4>The rules for 2026</h4><p>Put in up to <b>$7,500 a year</b> ($8,600 at 50 or older). You need earned income, and a part-time or summer job counts. Single people earning $153,000 to $168,000 can put in less, and above that, none.</p></div>
<div><h4>Not as locked up as you'd think</h4><p>You can take out <b>what you put in</b> anytime with no tax or penalty. Only the growth waits until 59½ (and 5 years after opening), or it's taxed with a 10% penalty.</p></div>
</div>
<p class="fundline"><b>Roth IRA vs. the others:</b> a <b>401(k)</b> takes money before tax and taxes it when you retire, often with free matching money, so get the match first. A <b>brokerage account</b> has no limits and no lock-up, but you pay tax on dividends every year and on gains when you sell. A common order: 401(k) up to the match, then a Roth IRA, then more 401(k) or brokerage.</p>
<p class="fundline"><b>Example:</b> $7,500 a year from 22 to 65, growing 7% a year, becomes about <b>${k(fv)}</b> before inflation. In a Roth IRA every dollar is yours. In a regular brokerage account, the 15% tax on ${k(gain)} of gains would be about <b>${k(tax)}</b>, before counting the yearly dividend taxes.</p>
<p class="fundline"><b>Opening one:</b> pick a low-cost brokerage, open a Roth IRA, add money, then <b>buy a fund</b> (a target-date or total-market index fund). Money left in cash inside the account doesn't grow.</p>`}
function explain(s,qid,v,ch,b){
const f=s.infl;
const city=CITIES[ch.city||s.city]||CITIES.lex;
const salary=ch.career==='custom'?(ch.customSalary||50000)*f:ch.career?CAREERS.find(c=>c.id===ch.career).salary*city.pay*f:s.salary;
if(qid==='card'){const po=minPayoff(s.card.bal,s.card.rate);
if(v==='min')return [`Minimum payments start around ${money(Math.max(25,s.card.bal*s.card.rate/12+0.01*s.card.bal))} a month, and most of that is interest.`,`Paying only the minimum, this balance takes about ${(po.months/12).toFixed(1)} years to clear and costs ${money(po.interest)} in interest.`];
const x=Math.min(s.cash,s.card.bal);return [`Moves ${money(x)} from savings to the card, a guaranteed ${pct(s.card.rate)} return.`,`Your cash drops to ${money(s.cash-x)}. With a thinner cushion, the next surprise might land back on the card.`];}
if(qid==='cover'){const yrs=s.gradAge-s.age;
if(v==='none')return ['Your monthly money stays the same.','Nothing changes. If you spend more than you bring in, savings drain first and then the card fills.'];
if(v==='borrow'){const amt=5000*yrs;return [`Adds about $417 a month of spending money, borrowed at ${pct(s.student.rate)}.`,`That's ${money(amt)} more in loans, plus interest from day one. Repaying it adds about ${money(pmt(amt*1.08,s.student.rate,120))} a month for 10 years after graduation.`]}
if(v==='work')return ['About $470 more a month after taxes.','That\'s about 43 more hours a month. Less study time can cost you grades, and KEES and many scholarships depend on your GPA.'];
return [`Keeps $200 more each month, ${money(200*12*yrs)} over the rest of college.`,'Fewer meals and nights out. Learning to live on less now makes saving easier later.'];}
if(qid==='career'){
if(v==='custom'){const sal=(ch.customSalary||50000)*f,t=taxes(sal,0,f,city.rate),p=PAY[ch.customStyle||'average'];return [`${esc(ch.customTitle||'Your job')} starting at ${money(sal)} a year, about ${money((sal-t.total)/12)} a month after taxes where you live.`,`<strong>${PAY_STYLE[ch.customStyle||'average']} pay:</strong> ${p.desc} Not sure of your salary? The Bureau of Labor Statistics lists pay for hundreds of jobs in the Lexington area.`]}
const c=CAREERS.find(c=>c.id===v),xm=expMult(s),sal=c.salary*xm*f,t=taxes(sal,0,f,.0225),p=PAY[v];
return [`${xm>1.01?`With about ${Math.round(s.startAge-23)} years of experience, pays about`:'Starts near'} ${money(sal)} a year, about ${money((sal-t.total)/12)} a month after taxes in Lexington. The Lexington-area median for this job is ${money(c.median)}.`,`<strong>How pay moves:</strong> ${p.desc} Starting pay is the base every future raise builds on, but the job you can stick with matters too.`];}
if(qid==='city'){const T={lex:['Lexington takes 2.25% of every paycheck for its payroll tax, on top of state and federal taxes.','A big job market and rents in the middle of the range.'],
lou:['Louisville residents pay 2.2%: 1.25% to Metro government, 0.75% to schools and 0.2% to TARC transit. Pay runs a little higher.','The state\'s biggest job market, with rents similar to Lexington.'],
town:['Rent is about 25% cheaper and the local payroll tax is closer to 1%, the typical county rate.','Pay is about 10% lower and there are fewer jobs to move up into.']};return T[v];}
if(qid==='rent'){const r=RENTS[v].rent*city.rent*f,diff=(RENTS[v].rent-RENTS.room.rent)*city.rent*f;
if(v==='home')return [`You chip in about ${money(r)} a month for groceries and bills, ${money((RENTS.room.rent-RENTS.home.rent)*city.rent*f)} less than splitting a place with roommates.`,'The cheapest way to start: money you\'d spend on rent can pay down loans and build savings. The tradeoff is less independence, and most people move out by 30.'];
if(v==='room')return [`About ${money(r)} a month where you're living.`,'The cheapest place of your own. A few years with roommates is one of the fastest ways to build savings early. The tradeoff is less privacy.'];
return [`About ${money(r)} a month, ${money(diff)} more than with roommates.`,'More privacy and space. But every extra dollar on rent is a dollar that can\'t be saved or invested, month after month.'];}
if(qid==='car'){
if(v==='keep')return [`No payment. Your car is worth about ${money(s.carValue)} and keeps losing value slowly.`,'Nothing extra now. Older cars need more repairs, and you\'ll have to replace it eventually.'];
const price=(v==='new'?46000:22000)*f,rate=v==='new'?0.07:0.075,n=v==='new'?72:60,loan=Math.max(0,price-s.carValue),p=pmt(loan,rate,n);
return [`${money(price)} car minus your ${money(s.carValue)} trade-in. Loan of ${money(loan)} at ${pct(rate)}: ${money(p)} a month for ${n/12} years.`,`You'd pay ${money(p*n-loan)} in interest, and new cars lose about half their value in 4 or 5 years. A nicer ride comes at the price of a monthly payment.`];}
if(qid==='k401'){
const sal=salary||0;if(!sal)return ['',''];
const k=sal*v,match=sal*Math.min(v,C.MATCH),saved=taxes(sal,0,f,city.rate).total-taxes(sal,k,f,city.rate).total;
if(v===0)return ['Nothing goes in, so your paycheck is a bit bigger.',`You skip ${money(sal*C.MATCH)} a year of free money from your employer, and you pay income tax on all your pay.`];
return [`${pct(v)} of pay (${money(k)} a year) goes in before income tax. Your employer adds ${money(match)}. Because of the tax break, your take-home only drops about ${money(k-saved)} a year.`,'The money is locked up until age 59½. Taking it out early costs a 10% penalty plus income tax, and you pay income tax when you withdraw in retirement.'];}
if(qid==='save'){const left=Math.max(0,b?b.left:0);
if(left<1)return [`Right now nothing is left over after your bills${b&&b.trim>1?`, and your everyday spending already had to shrink by about ${money(b.trim)} a month to fit`:''}. So this choice saves $0 until your pay grows or your bills shrink.`,`To free up money, pick cheaper rent or a cheaper car${(ch&&ch.k401!=null?+ch.k401:s.kPct)>0.05?', put a little less in your 401(k) above the match':''}, or lower your everyday spending${G.simple?' under More (optional)':''}.`];
return [`Of about ${money(left)} left each month, you save ${money(left*v)} and spend ${money(left*(1-v))}.`,'Money spent is gone. Money saved keeps working and earning on its own. Enjoying life now matters too, so find a balance you can stick with.'];}
if(qid==='acct'){const sv=b&&b.saved>0?b.saved:0,rm=C.ROTH*f/12,r=Math.min(sv*v,rm);
const lead=sv>=1?`Of about ${money(sv)} a month you save, ${r<1?'all of it goes to brokerage':`roughly ${money(r)} goes to your Roth IRA and ${money(sv-r)} to brokerage`}${sv*v>rm?` (the Roth caps at ${money(C.ROTH*f)} a year, so the extra spills into brokerage)`:''}. Some of your savings may first go to your emergency fund or credit card.`:'';
if(v>0&&v<1)return [lead||`${Math.round(v*100)}% of invested savings go to a Roth IRA, the rest to a brokerage account.`,'The Roth grows tax-free but its growth is locked until retirement. Brokerage money is taxed along the way but stays available for a house, a car or an emergency. Splitting gives you some of both.'];
if(v===1)return [lead||'Invested savings go into a Roth IRA first, up to $7,500 a year, then into a brokerage account.','You pay tax on this money now, but it grows tax-free and comes out tax-free in retirement. You can take out what you put in (not the growth) anytime. High earners lose access above about $153,000 of income.'];
const yrs=Math.max(1,Math.round(65-s.age)),mo=Math.min(sv>0?sv:200*f,C.ROTH*f/12);let a=0,bk=0,bb=0;
for(let m=0;m<yrs*12;m++){const c=mo*Math.pow(1+C.INFL,m/12);a=a*Math.pow(1.07,1/12)+c;bk=bk*Math.pow(1.07-C.DRAG,1/12)+c;bb+=c}
const f65=f*Math.pow(1+C.INFL,yrs),lost=a-(bk-C.LTCG*Math.max(0,bk-bb));
return [`${lead||'Invested savings go into a regular brokerage account. '} For comparison, ${money(mo)} a month invested until 65 would grow to about ${money(a,f65)} in a Roth IRA. In a brokerage account, dividend taxes along the way and 15% tax on the gains leave about <strong>${money(a-lost,f65)}</strong>.`,`Skipping the Roth costs about <strong>${money(lost,f65)}</strong> in taxes by 65 on that money alone. Brokerage money is easier to reach, but a Roth isn't as locked up as people think: you can take out what you put in (not the growth) anytime with no tax or penalty. A Roth also has no required withdrawals and passes to heirs tax-free.`];}
if(qid==='order'){
const T={smart:['Builds a 3-month emergency fund, pays off credit card debt, then invests the rest.','Slower growth at first while the cushion fills. In return, surprises don\'t turn into 24% debt. This is the order most planners recommend.'],
invest:['Every saved dollar gets invested right away.','Faster growth, but no cushion. Any surprise or job loss lands on your credit card.'],
debt:['Pays off loans before investing, highest interest rate first.','Feels great, but paying off a 6% loan instead of investing, with no cushion, is a closer call than it looks.'],
cash:['Everything stays in a high-yield savings account.','Safe and easy to reach, but it earns about 3.5% while prices rise 3%, so it barely grows after inflation.']};return T[v];}
if(qid==='family'){const T={single:['Just you: one income and the lowest costs.','No backup income if you lose your job, and every bill is yours alone.'],
partner:[`A partner's income (about ${money(C.PARTNER_PAY*f)} a year) plus about ${money(C.PARTNER_COST*f)} a month in shared costs. Your everyday spending also tends to rise with the bigger household income, so the total added cost is often ${money(2000*f)} to ${money(2700*f)} a month.`,'Two incomes make saving easier and a layoff less scary. Shared money works best with shared goals, so talk about it early.'],
};return T[v];}
if(qid==='retireAge'){const ra=+v,yrs=ra-Math.round(s.age),f=s.infl;
const T={62:'More free years while you\'re healthy, but three fewer years of saving, three more years to fund, and you pay for health insurance until 65. Social Security is 30% smaller for life if you also claim at 62.',65:'The traditional choice: Medicare starts at 65, so there\'s no health insurance gap.',67:'Two more years of pay and saving, and two fewer years to fund. You can also wait to claim Social Security at 67 for your full benefit.',70:'The safest for your savings: more years of pay, the biggest Social Security check if you wait to claim, and fewer years to fund. The cost is less time retired.'};
return [`You keep working until ${ra}, about ${yrs} more year${yrs===1?'':'s'} from now${ra<65?`, then pay about ${money(C.PRE_MEDICARE*f)} a month for health insurance until Medicare at 65`:''}.`,T[ra]||T[65]]}
if(qid==='care'){const u=Math.max(1,s.kids.filter(b=>b+60>s.month).length||(+ch.kids||0)),c=CARE[v],mo=(v==='nanny'?c.cost+300*(u-1):c.cost*u)*s.infl;
const T={family:'Cheapest, but it depends on family nearby with time to give, or a partner working fewer hours, which can mean less income.',home:'Usually cheaper than a center and more flexible, with fewer kids per adult. Quality and licensing vary, so check that the provider is licensed.',center:'Licensed, reliable hours and backup staff. It costs about as much as a second rent payment, and it ends when kids start kindergarten.',nanny:'One-on-one care in your home and the most flexible hours, but it costs about as much as a full-time salary. It gets more reasonable per child with two or more kids.'};
return [`About ${money(mo)} a month${u>1?` for ${u} kids`:''} until each child turns 5, on top of other kid costs.`,T[v]]}
if(qid==='kids'){const n=+v;if(!n)return [s.kids.length?'Your family stays the size it is.':'No kids for now. You can decide again in a later turn, until about 45.','Fewer costs now. Many people wait until their finances feel steadier.'];
return [`${n} ${s.kids.length?'more ':''}kid${n>1?'s':''}, ${n>1?'the first in about 1 to 2 years, then 1½ to 4 years apart':'arriving in about 1 to 2 years'}. ${n>1?'They add':'That adds'} about ${money((kidEst(s.kids.length+n)-kidEst(s.kids.length))*f)} a month: food, clothes, child care, activities and health costs. Each extra kid costs a bit less than the first (shared rooms, hand-me-downs), and costs climb about 20% from baby to teen. Plus college.`,'Kids are one of life\'s biggest joys and one of its biggest expenses. Many families save less while kids are small, then catch up later. Life insurance matters more once kids depend on you.'];}
if(qid==='college'){const T={none:['Your kids cover college with loans, scholarships and jobs.','Your savings stay intact, but your kids start adult life with debt, like you did.'],
pay:[`You pay about ${money(C.KID_COLLEGE*f)} per kid from savings when each turns 18.`,'No planning now, but it\'s a big hit later, and money you never invested never grew.'],
'529':[`${money(C.K529*f)} a month per kid into KY Saves 529, Kentucky's college savings plan. Growth is tax-free when used for school.`,'Money leaves your budget today. If a child skips college, the earnings face taxes and a penalty when withdrawn for other uses.']};return T[v];}
if(qid==='home'){
if(v==='rent')return [`${money(s.rent*f)} a month, rising with inflation.`,'No down payment, no repair bills, easy to move. You build no home equity, but money not tied up in a house stays invested.'];
const price=v==='small'?190000:v==='starter'?260000:360000,dn=v==='small'?.035:.10,d=downPaymentPlan(s,price,dn),parts=[];
if(d.fromCash>1)parts.push(`${money(d.fromCash)} of savings`);if(d.brokGross>1)parts.push(`${money(d.brokGross)} of brokerage money${d.brokTax>=1?` (${money(d.brokTax)} in taxes)`:''}`);
if(d.fromRoth>1)parts.push(`${money(d.fromRoth)} of Roth contributions (no tax)`);if(d.kGross>1)parts.push(`${money(d.kGross)} of 401(k) money (${money(d.kCost)} lost to penalty and tax)`);
const mp=pmt((1-dn)*d.P,mortRate(s),360),mip=dn<.1?(1-dn)*d.P*C.MIP/12:0;
return [`Down payment and closing: ${money(d.need)}${parts.length?', paid with '+parts.join(', '):''}. Then ${money(mp)} a month for the mortgage${mip?`, ${money(mip)} a month for FHA mortgage insurance`:''} plus about ${money(d.P*0.02/12)} for taxes, insurance and upkeep.${dn<.1?' FHA loans let first-time buyers put as little as 3.5% down, at the cost of mortgage insurance and a bigger loan.':''}`,`Closing costs (${money(d.P*.03)}) are gone the day you buy. Owners also face big surprise repairs like roofs and furnaces. In return, you build equity and the home tends to rise in value.`];}
if(qid==='health'){if(v==='ppo')return [`About ${money(C.PPO_EXTRA*f)} a month more in premiums (more with a family). Doctor visits and big bills cost you roughly half what they would on a high-deductible plan.`,'Predictable and simple. The extra premiums add up every month whether you get sick or not, and there\'s no tax-free account.'];
const amt=v==='hdhpmax'?C.HSA_SELF*f:150*12*f;return [`Lower premiums. You put ${money(amt)} a year into a health savings account before taxes, and your employer adds ${money(C.HSA_EMP*f)}. Doctor visits (about ${money(C.HDHP_ROUTINE*f)} a month) and medical bills come out of the HSA first.`,'An HSA is triple tax-free: money goes in untaxed, grows untaxed and comes out untaxed for health costs. Unused money stays yours and can be invested for retirement. The catch is bigger bills when you get sick.']}
if(qid==='risk'){const m=mixAt(s.age,v),w=Math.round(m.w*100),ret=s.age>=64.5;
const mp=mixParts(m.w);
const does=`${w}% stocks and ${100-w}% bonds${ret?'':', shifting toward bonds after 50 and again after 65'}. A typical fund would hold about ${mp.us}% US stocks, ${mp.intl}% international stocks and ${mp.bd}% bonds. Over the long run it grows about ${retTxt(m.flat)}. About 1 year in 20 it loses ${pctr(m.mean-1.65*m.sd).slice(1)} or more.${ret?'':` $500 a month from now until 65 would grow to about ${money(riskGrow(s.age,v,500,0)*s.infl)} in today's dollars, if markets are average.`}`;
const T={cons:'A smooth ride, but slow growth. Over decades, too little risk is its own risk: after inflation your money barely grows, so you have to save a lot more to reach the same goal.',
bal:'A middle path. Smaller drops than an all-stock mix, so it\'s easier to stay calm in a crash, with less growth over the long run.',
growth:'Close to what target-date funds hold at your age, and it gets safer on the same schedule. Expect a few rough years. Over long stretches, stocks have more than made up for them.',
aggr:'The most growth over long periods, and the biggest drops. All-stock portfolios fell about half in 2008. Only pick this if you would truly hold on, because selling at the bottom turns a temporary drop into a permanent loss.'};
return [does,T[v]+(ret&&v==='aggr'?' In retirement, a crash in the first few years can force you to sell low just to pay bills.':ret&&v==='cons'?' A retirement can last 30 years, and prices roughly double over that time.':'')]}
if(qid==='fund'){const T={index:['Your money tracks the whole market at about 0.05% a year, or $5 for every $10,000.','The cheapest way to invest. You get the market\'s return, never more, and that beats most professional managers over time.'],
target:['One fund that holds stocks and bonds and gets safer as you approach retirement. About 0.12% a year.','Hands-off and still cheap. A great choice if you never want to think about it.'],
managed:['An advisor picks investments for you for about 1% of your balance every year, or $100 for every $10,000.','1% sounds small, but it comes out every year for decades. Over a working life it can eat roughly a quarter of what you would have had. Most managers don\'t beat the index after fees.']};return T[v]}
if(qid==='move'){const nowPay=s.mortgage.bal>1?s.mortgage.pay:0;
if(v==='stay')return [nowPay?`You keep your home and your ${money(nowPay)} a month mortgage, which keeps shrinking as you pay it down.`:'You keep your home, and it\'s paid off.','Staying put avoids about 6% in selling costs plus 3% in closing costs on the next home. Every move resets those costs, so frequent moves eat your equity.'];
if(v==='rent'){const m=movePlan(s,null);return [`You sell for ${money(m.sale.gross)}${m.sale.owed>1?`, pay ${money(m.sale.cost)} in selling costs and pay off the ${money(m.sale.owed)} mortgage`:` and pay ${money(m.sale.cost)} in selling costs`}, leaving about ${money(m.sale.net)} that goes to savings. Then you rent for about ${money(rentAfterSale(s)*f)} a month.`,'No more repairs, property taxes or mortgage, and your equity can be invested. But rent rises with prices every year and you stop building home equity.']}
const t=MOVE_TIERS.find(t=>t.v===v),m=movePlan(s,t.p),up=t.p*f>s.home;
return [`You sell for ${money(m.sale.gross)}${m.sale.owed>1?`, pay ${money(m.sale.cost)} in selling costs and pay off the ${money(m.sale.owed)} mortgage`:` and pay ${money(m.sale.cost)} in selling costs`}, leaving ${money(m.sale.net)}. You put ${pct(m.down)} down on a ${money(m.P)} home and take a new 30-year mortgage at ${(m.rate*100).toFixed(1)}%: about ${money(m.pay)} a month.`,
up?'More space, but a bigger mortgage, plus taxes, insurance and upkeep of about 2% of the home\'s value a year. You also restart a 30-year loan. Selling and buying together cost about 9% of the price.':'Downsizing frees up equity and lowers your bills. Many people downsize near retirement and invest the difference. Selling and buying still cost about 9% of the price together.']}
if(qid==='ins'){const nk=s.kids.length+(+ch.kids||0),deps=s.partner||ch.family==='partner'||nk>0;
if(v==='none')return ['No premiums.',deps?`If you died, your family would lose your income of about ${money(s.salary)} a year with nothing to replace it. ${s.partner||ch.family==='partner'?(nk?'With a partner and kids':'With a partner'):'With kids'} depending on you, that's a real risk.`:'If nobody depends on your income, you may not need life insurance yet. Buying while young and healthy locks in a low price, though.'];
if(v==='term'){const y=ch.insYears||20,fc=ch.insFace||500000,p=termQuote(s,y,fc),x=fc/(s.salary/s.infl),end=Math.round(s.age)+y;
return [`About ${money(p*f)} a month for ${y} years, ${money(p*12*y*f)} in total. If you die before age ${end}, your family gets ${money(fc*f)}, tax-free.`,`That's about ${x.toFixed(1)} times your income${x<8?', on the low side. Planners often suggest about 10 times':x>14?', more than most families need':', close to the 10 times planners often suggest'}. Cheap, because most people outlive the term and it never pays. That's the point: it covers the years your family depends on you most, ideally until your kids are grown and your mortgage is paid down.${s.smoke==='smoker'?' Smokers pay about 3 times as much.':''}`]}
return [`About ${money(insQuote(s,'whole')*f)} a month for the rest of your life. It pays $250,000 whenever you die and builds a small cash value you can borrow against.`,`It costs roughly ${Math.round(insQuote(s,'whole')/insQuote(s,'term'))} times more than term for half the coverage, and the cash value grows slowly. Many planners say to buy term and invest the difference. Whole life can make sense for estate planning or people who can't save on their own.`];}
if(qid==='life'){const typ=G.typLife||suggestLife(s),diff=v-typ,kids=s.kids.length+(+ch.kids||0);
const pt=s.partner||ch.family==='partner',house=(s.home>0?(s.mortgage.bal>1?s.mortgage.pay:0)+housingCost(s):(s.rent>0?(kids&&(s.rentTier==='room'||s.rentTier==='solo'||s.rentTier==='home')?RENTS.family.rent*((CITIES[s.city]||{rent:1}).rent||1):s.rent)*f:0))*12,car=(s.carRun*f+(s.carLoan.bal>1?s.carLoan.pay:0))*12,kc=kids?kidEst(kids)*12*f:0,pc=pt?C.PARTNER_COST*12*f:0,tot=v*f+house+car+kc+pc;
return [`${money(v*f)} a year, about ${money(v*f/12)} a month, on everyday life. <b>Your household total: about ${money(tot)} a year</b> (${money(tot/12)} a month)${pt||kids?` for you${pt&&kids?', a partner':pt?' and a partner':''}${kids?` and ${kids} kid${kids>1?'s':''}`:''}`:''}: everyday life ${money(v*f)}, housing ${money(house)}, car ${money(car)}${kids?`, kids ${money(kc)}${s.kids.some(b=>b+60>s.month)||+ch.kids?' plus childcare until each turns 5':''}`:''}${pt?`, partner's share ${money(pc)}`:''}. That's before taxes, debt payments and saving.`,
Math.abs(diff)<500?'Right around typical for your income. As pay rises, most people let spending creep up too. Holding it steady is one of the strongest ways to build wealth.':diff<0?`That's ${money(-diff*f)} a year below typical. Every dollar you don't spend is a dollar you can save, and living below your means is the habit most millionaires share.`:`That's ${money(diff*f)} a year above typical. Enjoying your money is fine, but spending more leaves less to save, and it raises how much you'll need in retirement too.`];}
if(qid==='exercise'){const T={low:['No cost and no time spent.','Inactive people tend to live a couple of years less and spend more on health care. In this game it takes about 2 years off your expected life.'],
some:['Free. A little activity most weeks.','A solid baseline. Your expected lifespan stays at the Kentucky average.'],
high:[`${money(C.GYM_COST*f)} a month for a gym, about ${money(C.GYM_COST*12*f)} a year.`,'Regular exercise is linked to roughly 3 extra years of life and fewer medical bills. In this game it adds about 3 years.']};return T[v];}
if(qid==='smoke'){if(v==='never')return ['No cost.','You keep the full Kentucky life expectancy, and Kentucky has one of the highest smoking rates in the country.'];
return [`About ${money(C.SMOKE_COST*f)} a month, ${money(C.SMOKE_COST*12*f)} a year, rising with prices.`,'Smokers lose more than 10 years of life on average. Quitting before 40 wins back about 90% of the lost years.'];}
if(qid==='quit'){if(v==='quit')return [`Saves about ${money(C.SMOKE_COST*f)} a month from now on.`,'Quitting before 40 wins back most of the years smoking takes. You keep about 1 year of lost life instead of 10.'];
return ['Same habit, same cost.','Every year you keep smoking, quitting gets harder and wins back less. Expect to lose about 10 years of life.'];}
if(qid==='ss'){const be={62:'Claiming at 62 gives you the smallest check for life, 30% less than at 67. It comes out ahead of waiting only if you die before about 78 to 80.',65:'Claiming at 65 instead of 70 comes out ahead only if you die before about 82.',67:'Waiting from 67 to 70 pays off if you live past about 82 or 83.',70:'Waiting to 70 beats claiming at 65 if you live past about 82.'};
return [`About ${money(s.pia*SSF[v],f)} a month for life, rising with inflation.${v>Math.round(s.age)?` Until ${v}, your savings cover everything: about ${v-Math.round(s.age)} year${v-Math.round(s.age)===1?'':'s'}.`:''}`,be[v]+' Nobody knows their exact lifespan, which is what makes this a real choice.'];}
if(qid==='spend'){const r=retirement(s);
return [`About ${money(v*s.retireSpend*(s.retired&&s.infl65?s.infl/s.infl65:1),f)} a month, rising with inflation.`,`A rule of thumb: you can spend about 4% of your investments a year${r.draw>=1?` (${money(r.draw,f)} a month)`:''} without running out for 30 years. Spend more than that plus Social Security and your savings shrink faster.`];}
if(qid==='crash'){const tax=C.LTCG*Math.max(0,s.brok-s.brokBasis);
if(v==='stay')return ['Keep everything invested and keep contributing at lower prices.','Watching your balance fall is painful. But you still own the shares when markets recover.'];
return [`Moves everything to cash.${tax>1?` Selling your brokerage investments costs ${money(tax)} in taxes on gains.`:''}`,'You avoid further drops, but you will likely miss the rebound. Timing when to get back in is very hard, even for professionals.'];}
return ['',''];
}
// ---------- rendering ----------
const SAVE_KEY='lg-game-v2';
function snapG(){return JSON.stringify({inp:G.inp,s:G.s,twin:G.twin,block:G.block,done:G.done,log:G.log,turns:G.turns,phase:G.phase,seed:G.seed,enter:G.enter,result:G.result,prevNW:G.prevNW})}
function syncMode(){RET_MODE=(G.inp&&G.inp.returns)||'cautious'}
function restoreG(o){Object.assign(G,o);syncMode()}
function saveGame(){if(G.auto||!G.s||G.phase==='setup'||G.phase==='final'||G.phase==='debrief'||G.phase==='surprise'||(G.phase==='home'||G.phase==='glossary'))return;try{localStorage.setItem(SAVE_KEY,snapG())}catch(e){}}
function hasSave(){try{return !!localStorage.getItem(SAVE_KEY)}catch(e){return false}}
function clearSave(){try{localStorage.removeItem(SAVE_KEY)}catch(e){}}
function loadGame(){try{const o=JSON.parse(localStorage.getItem(SAVE_KEY));if(!o||!o.s)return false;restoreG(o);G.undo=null;G.snaps=[];return true}catch(e){return false}}
const PRESET={first:{k401:0.05,fund:'index'}};
function startDemo(){const keep=G.inp.goals;G.inp={...DEFAULTS,goals:keep&&keep.length?keep:['debt30','inv35','never']};G.typed=false;startRun(Math.floor(Math.random()*1e9));G.auto=true;G.fast=false;render();presetDecide()}
function demoFix(s,st,ch,qs){if(!gateInfo(s,st,ch,qs).block)return ch;const pass=c=>{const r=scanTurn(s,st,c);return r.broke==null&&r.worst>=-1};
for(const q of qs){if(q.type==='money'){for(let k=.9;k>=.3;k-=.1){const c={...ch,life:q.def*k,lifeCustom:true};if(pass(c))return c}continue}
if(q.id==='risk')continue;for(const o of (q.options||[]).filter(o=>!o.off&&autoOK(q.id,o))){const c={...ch,[q.id]:o.v};if(pass(c))return c}}
const qs2=decisions(s,st.key);return {...ch,...bestFix(s,st,ch,qs2).ch}}
const FIX_ORDER=['rent','car','home','move','ins','health','k401','college','kids','cover','card','spend','order'];
function balanceFix(s,st,ch,qs){const pass=c=>{const r=scanTurn(s,st,c);return r.broke==null&&r.worst>=-1};const lq=qs.find(q=>q.type==='money');
const base=lq?(ch.lifeCustom?ch.life:lq.def):null;
if(lq)for(let k=.95;k>=.7-1e-9;k-=.05){const c={...ch,life:base*k,lifeCustom:true};if(pass(c))return c}
const opts=id=>{const q=qs.find(q=>q.id===id);return q&&q.options?q.options.filter(o=>!o.off&&autoOK(id,o)&&String(o.v)!==String(ch[id])):[]};
for(const lv of lq?[1,.85,.7]:[1])for(const id of FIX_ORDER)for(const o of opts(id)){const c={...ch,[id]:o.v};if(lq&&lv<1){c.life=base*lv;c.lifeCustom=true}if(pass(c))return c}
for(const a of FIX_ORDER)for(const oa of opts(a))for(const b of FIX_ORDER){if(b===a)continue;for(const ob of opts(b)){const c={...ch,[a]:oa.v,[b]:ob.v};if(lq){c.life=base*.8;c.lifeCustom=true}if(pass(c))return c}}
return demoFix(s,st,ch,qs)}
function presetChoices(){const qs=decisions(G.s,G.block.key),ch={};for(const q of qs)ch[q.id]=q.def;Object.assign(ch,PRESET[G.block.key]||{});return {qs,ch:demoFix(G.s,G.block,ch,qs)}}
function presetDecide(){if(!G.auto||G.phase!=='decide')return;const {ch}=presetChoices(),pre=PRESET[G.block.key]||{};
for(const [id,v] of Object.entries(pre)){const el=document.querySelector(`input[name="q-${id}"][value="${v}"]`);if(el&&!el.disabled){el.checked=true;el.dispatchEvent(new Event('change',{bubbles:true}))}}
const rv=document.querySelector('.chips .chip:last-child');if(rv)rv.click();window.scrollTo({top:0,behavior:'smooth'})}
function autoContinue(){if(!G.auto)return;
if(G.phase==='decide'){const {qs,ch}=presetChoices();doLive(qs,G.block,ch)}
else if(G.phase==='result'){doNext();presetDecide()}
if(G.phase==='final'){G.auto=false;render();window.scrollTo({top:0,behavior:'smooth'})}}
function autoStep(){if(!G.auto)return;let guard=0;
while(G.auto&&G.phase!=='final'&&guard++<60){if(G.phase==='decide'){const {qs,ch}=presetChoices();doLive(qs,G.block,ch)}else if(G.phase==='result')doNext()}
G.auto=false;G.fast=false;render();window.scrollTo({top:0,behavior:'smooth'})}
const GLOSS={'APR':'Annual percentage rate: the yearly interest rate a loan or credit card charges.','Roth IRA':'A retirement account you fund with after-tax money. It grows tax-free and comes out tax-free in retirement.','401(k)':'A retirement account through your employer. Money goes in before income tax, often with matching money from your employer.','brokerage':'A regular investment account with no limits or penalties for withdrawing. You pay tax on dividends and gains.','net worth':'Everything you own minus everything you owe.','compounding':'When your investment gains start earning gains of their own, so growth speeds up over time.','index fund':'A fund that buys every company in a market index, like the S&P 500, for a very low fee.','emergency fund':'Cash set aside for surprises like a car repair or a job loss, usually 3 to 6 months of expenses.','credit score':'A number from 300 to 850 that tells lenders how likely you are to repay. Higher scores get lower interest rates.','utilization':'How much of your credit card limit you are using. Under 30% helps your credit score.','premium':'What you pay each month to keep an insurance policy.','deductible':'What you pay out of pocket before insurance starts paying.','risk tolerance':'How much your investments can drop without you panicking or needing the money. It depends on how soon you need it and how you handle losses.','bonds':'Loans to governments or companies that pay interest. Steadier than stocks, but they grow less over time.','stocks':'Small pieces of ownership in companies. They grow the most over long periods and swing the most along the way.','term life':'Life insurance that covers you for a set number of years, usually at a low price.','death benefit':'The money a life insurance policy pays your beneficiaries when you die.','beneficiaries':'The people you name to receive money from your life insurance or retirement accounts when you die.','whole life':'Life insurance that lasts your whole life and builds cash value, at a much higher price.','Social Security':'Federal retirement income funded by payroll taxes. How much you get depends on your earnings and when you start.','inflation':'Prices rising over time, so each dollar buys a little less every year.','529':'A college savings account. Growth is tax-free when used for school costs.','HSA':'Health savings account: money goes in before taxes, grows tax-free and comes out tax-free for health costs.','target-date fund':'One fund named for your retirement year that holds stocks and bonds and gets safer on its own as that year gets closer.','expense ratio':'The yearly fee a fund charges, as a percentage of your balance.','home equity':'What your home is worth minus what you still owe on the mortgage.','mortgage':'A loan to buy a home, usually repaid over 15 or 30 years.','unsubsidized':'A student loan that builds interest from the day you borrow, even while you are in school.','grace period':'Time after graduation before student loan payments start, usually 6 months.','match':'Money your employer adds to your 401(k) when you contribute, often up to a set percent of pay.','capital gains':'The profit when you sell an investment for more than you paid.','4% rule':'A rule of thumb that you can spend about 4% of your investments a year in retirement without running out for 30 years.','diversification':'Spreading money across many investments so one bad one cannot sink you.','KEES':'Kentucky Educational Excellence Scholarship: money earned with your high school grades, renewed each year with your college GPA.','payroll tax':'A tax taken straight from wages. Kentucky cities and counties charge their own on top of state and federal taxes.'};
function glossify(root){if(!root)return;const terms=Object.keys(GLOSS).sort((a,b)=>b.length-a.length),used=new Set();
const esc=t=>t.replace(/[.*+?^${}()|[\]\\]/g,'\\$&'),re=new RegExp('\\b('+terms.map(esc).join('|')+')(?![\\w])','i');
const walker=document.createTreeWalker(root,NodeFilter.SHOW_TEXT,{acceptNode:n=>{const p=n.parentElement;if(!p||p.closest('a,.hgloss,summary,label,button,input,select,svg,.term,.money,.big,h1,h2,.eyebrow,legend,.legend,.bar-row,.ledger,.num'))return NodeFilter.FILTER_REJECT;return re.test(n.nodeValue)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});
const nodes=[];while(walker.nextNode())nodes.push(walker.currentNode);
for(const n of nodes){const m=n.nodeValue.match(re);if(!m)continue;const key=terms.find(t=>t.toLowerCase()===m[1].toLowerCase());if(!key||used.has(key))continue;used.add(key);
const i=m.index,after=n.splitText(i);after.nodeValue=after.nodeValue.slice(m[1].length);const b=document.createElement('button');b.type='button';b.className='term';b.textContent=m[1];b.dataset.t=key;n.parentNode.insertBefore(b,after)}
}
document.addEventListener('click',e=>{const t=e.target.closest&&e.target.closest('.term'),pop=$('gloss');if(!pop)return;
if(t){const r=t.getBoundingClientRect();pop.innerHTML=`<strong>${t.dataset.t}</strong><br>${GLOSS[t.dataset.t]}`;pop.hidden=false;const w=Math.min(300,window.innerWidth-24);pop.style.width=w+'px';pop.style.left=Math.max(12,Math.min(window.innerWidth-w-12,r.left+window.scrollX))+'px';pop.style.top=(r.bottom+window.scrollY+6)+'px';e.preventDefault();return}
if(!e.target.closest('#gloss'))pop.hidden=true});
document.addEventListener('keydown',e=>{if(e.key==='Escape'){if($('gloss'))$('gloss').hidden=true;if($('turnView')&&!$('turnView').hidden)closeTurn()}});
$('turnView').addEventListener('click',e=>{if(e.target.id==='turnView')closeTurn()});
function render(){syncMode();CUR_F=G.s&&G.phase!=='setup'&&!(G.phase==='home'||G.phase==='glossary')?G.s.infl:1;const home=(G.phase==='home'||G.phase==='glossary'),lay=document.querySelector('.layout');if(lay)lay.classList.toggle('solo',home);document.body.classList.toggle('inner',!home);{const rb=document.querySelector('.resetbar');if(rb)rb.hidden=home;const hb=$('goHome');if(hb)hb.hidden=G.phase==='home';const gb=$('goGloss');if(gb)gb.hidden=G.phase==='glossary'}renderTrack();renderSide();renderMain();glossify($('main'));saveGame();if($('gloss'))$('gloss').hidden=true}
function renderTrack(){
const el=$('track');let items=[];el.hidden=(G.phase==='home'||G.phase==='glossary');if((G.phase==='home'||G.phase==='glossary')){el.innerHTML='';const h=$('trackHint');if(h)h.hidden=true;return}
if(G.phase==='setup'||!G.s){const st=G.inp.status==='grad',a0=G.inp.age,g=st?a0:a0+G.inp.years;
if(!st){let a=a0;while(a<g){const n=Math.min(g,Math.floor(a/5)*5+5);items.push({from:a,to:n,icon:'cap',cls:''});a=n}}
items.push(...planAhead(null,g).map(x=>({...x,cls:''})));}
else{items=(G.done||[]).map(b=>({...b,cls:'done'}));
const cur=G.block,isEnd=G.phase==='final'||G.phase==='debrief';if(cur)items.push({...cur,cls:G.phase==='result'||isEnd?'done':'now'});
if(!isEnd&&cur&&cur.to<65)items.push(...planAhead(null,cur.to).map(x=>({...x,cls:''})));
else if(!isEnd&&cur&&cur.to>=65&&!G.s.retired&&cur.key!=='retire')items.push({from:65,to:null,icon:'sun',cls:''});}
el.style.gridTemplateColumns='';
const has=f=>(G.turns||[]).some(t=>Math.abs(t.from-f)<.01);
el.innerHTML=items.map(it=>{const inner=`<span class="node">${ic(it.icon||'trend')}</span><span class="num">${Math.round(it.from)}${it.to==null||(it.key==='retire2'&&G.phase==='decide')?'+':'–'+Math.round(it.to)}</span>`;
return `<li class="${it.cls}">${it.cls==='done'&&has(it.from)?`<button type="button" class="tbtn" data-from="${it.from}" aria-label="See your choices for ages ${Math.round(it.from)} to ${Math.round(it.to)}">${inner}</button>`:inner}</li>`}).join('');
el.querySelectorAll('.tbtn').forEach(b=>b.onclick=()=>openTurn(+b.dataset.from));
const hint=$('trackHint');if(hint)hint.hidden=!(G.turns&&G.turns.length);
const now=el.querySelector('.now');if(now&&now.scrollIntoView)try{el.scrollLeft=now.offsetLeft-el.clientWidth/2+now.clientWidth/2}catch(e){}
}
function goalsHTML(s,final){if(!G.inp.goals||!G.inp.goals.length)return '';
return `<div class="goallist"><span class="eyebrow">Your goals</span>${G.inp.goals.map(id=>{const g=GOALS.find(x=>x.id===id),st=goalStatus(s,id,final);return `<div><span class="${st.ok===true?'g-ok':st.ok===false?'g-no':'g-wait'}">${ic(st.ok===true?'star':st.ok===false?'bolt':'flag')}</span><span><strong>${g.label}</strong><br><span class="muted">${st.txt}</span></span></div>`}).join('')}</div>`}
function ownList(s){return [['Savings',s.cash,'var(--c-cash)'],['401(k)',s.k401-iraPart(s),'var(--c-k401)'],['Traditional IRA',iraPart(s),'var(--c-ira)'],['Roth IRA',s.roth,'var(--c-roth)'],['Brokerage',s.brok,'var(--c-brok)'],['HSA',s.hsa||0,'var(--c-529)'],['Kids\' 529',s.k529,'var(--c-529)'],['Insurance cash value',(s.ins&&s.ins.cv)||0,'var(--c-car)'],['Home',s.home,'var(--c-home)'],['Car',s.carValue,'var(--c-car)']].filter((x,i)=>i===0||x[1]>0.5)}
function oweList(s){return [['Student loans',s.student.bal],['Credit card',s.card.bal],['Car loan',s.carLoan.bal],['Mortgage',s.mortgage.bal]].filter(x=>x[1]>0.5)}
function ownOweHTML(s){const f=s.infl,own=ownList(s),owe=oweList(s),to=own.reduce((a,x)=>a+x[1],0),tw=owe.reduce((a,x)=>a+x[1],0),mx=Math.max(1,...own.map(x=>x[1]),...owe.map(x=>x[1])),nw=to-tw;
const li=(x,c)=>`<li><span>${x[0]}</span><span class="oo-bar"><i style="width:${Math.max(2,x[1]/mx*100)}%;background:${c}"></i></span><b class="money">${money(x[1],f)}</b></li>`;
return `<div class="oo"><div class="oo-col own"><div class="oo-h"><span>What you own</span><b class="money">${money(to,f)}</b></div><ul>${own.map(x=>li(x,x[2])).join('')}</ul></div>
<div class="oo-col owe"><div class="oo-h"><span>What you owe</span><b class="money">${money(tw,f)}</b></div>${owe.length?`<ul>${owe.map(x=>li(x,'var(--danger)')).join('')}</ul>`:'<p class="muted" style="font-size:var(--fs-sm);margin-top:6px">Nothing. You\'re debt-free.</p>'}</div></div>
<div class="oo-eq"><span>Own <b class="money">${money(to,f)}</b></span><span>−</span><span>Owe <b class="money">${money(tw,f)}</b></span><span>=</span><span>Net worth <b class="money ${nw<0?'neg':'pos'}">${money(nw,f)}</b></span></div>`}
function sheetFor(s){
const f=s.infl,row=(l,v,c,neg)=>`<span class="dot" style="--c:${c}"></span><span>${l}</span><span class="money ${neg?'neg':''}">${money(neg?-v:v,f)}</span>`;
const own=ownList(s),owe=oweList(s),to=own.reduce((a,x)=>a+x[1],0),tw=owe.reduce((a,x)=>a+x[1],0);
return `<div class="sheet"><span class="eyebrow h">You own</span>${own.map(x=>row(x[0],x[1],x[2])).join('')}<span></span><b>Total owned</b><b class="money" style="text-align:right">${money(to,f)}</b>
<span class="eyebrow h">You owe</span>${owe.length?owe.map(x=>row(x[0],x[1],'var(--c-debt)',true)).join('')+`<span></span><b>Total owed</b><b class="money neg" style="text-align:right">${money(-tw,f)}</b>`:'<span></span><span class="muted">Nothing</span><span></span>'}</div>
${(()=>{const t=money(netWorth(s),f);return `<div class="nw"><b>Net worth</b><span class="money ${netWorth(s)<0?'neg':''} ${t.length>11?'xlong':t.length>9?'long':''}">${t}</span></div>`})()}`;
}
const ptsOf=(h,n=3)=>h.filter((p,i)=>i%n===0||i===h.length-1).map(p=>[p.age,real?p.nw/p.f:p.nw]);
function renderMstat(){const m=$('mstat');if(!m)return;if(!G.s||G.phase==='setup'||(G.phase==='home'||G.phase==='glossary')){m.hidden=true;return}const s=G.s,nw=netWorth(s);m.hidden=false;
m.innerHTML=`<span>Age <b>${Math.floor(s.age)}</b></span><span class="m-nw">Net worth <b class="money ${nw<0?'neg':''}">${money(nw,s.infl)}</b></span><span>Credit <b class="money">${Math.round(s.credit.score)}</b></span>`}
function renderSide(){renderMstat();
const el=$('side');el.hidden=(G.phase==='home'||G.phase==='glossary');if((G.phase==='home'||G.phase==='glossary')){el.innerHTML='';return}
if(G.phase==='setup'){el.innerHTML=`<div class="panel stack"><span class="eyebrow">Age ${G.inp.age} · today</span>${sheetFor(newState(G.inp,0))}<p class="muted" style="font-size:var(--fs-sm)">This updates as you type.</p></div>`;return}
const s=G.s,t=G.twin;
const series=[{pts:ptsOf(s.history),c:'var(--accent)',fill:true}];if(t&&t.history.length>2)series.push({pts:ptsOf(t.history),c:'var(--muted)',dash:true});
el.innerHTML=`<div class="panel stack"><span class="eyebrow">Age ${Math.floor(s.age)} · ${s.retired?'retired':s.career?esc(careerLabel(s)):s.grad?'starting out':'student'}</span>${s.career?`<span class="note">${ic('heart')}<span>Expected lifespan with your habits: about <strong>${lifeExpect(s)}</strong></span></span>`:''}<span class="note">${ic('card')}<span>Credit score: <strong>${Math.round(s.credit.score)}</strong> (${creditLabel(s.credit.score)})</span></span>${s.kids.length?`<span class="note">${ic('heart')}<span>Kids: <strong>${kidAgesText(s)}</strong>${kidCost(s)>0?` · about ${money(kidCost(s)*s.infl,s.infl)}/mo`:''}</span></span>`:''}${sheetFor(s)}
${goalsHTML(s,false)}
${s.history.length>2?`${lineChart(series,s.startAge,Math.max(65,Math.ceil(s.age)),{w:300,h:170,label:'Net worth so far'})}<div class="legend"><span style="--c:var(--accent)">You</span><span style="--c:var(--muted)">Your twin who never invests: ${money(netWorth(t),t.infl,{short:true})}</span></div>`:''}</div>`;
}
function renderMain(){
const el=$('main');
const ab=$('autobar');if(ab){ab.hidden=!G.auto}
if(G.phase==='home')return renderHome(el);
if(G.phase==='glossary')return renderGlossary(el);
if(G.phase==='setup')return renderSetup(el);
if(G.phase==='decide')return renderDecide(el);
if(G.phase==='surprise')return renderSurprise(el);
if(G.phase==='result')return renderResult(el);
if(G.phase==='final')return renderFinal(el);
if(G.phase==='debrief')return renderDebrief(el);
}
function gradExample(age){const pts=[[22,0],[24,2000],[30,16000],[40,40000],[50,68000],[60,96000]];let k=0;for(let i=1;i<pts.length;i++){const [a0,v0]=pts[i-1],[a1,v1]=pts[i];if(age<=a1){k=v0+(v1-v0)*Math.max(0,age-a0)/(a1-a0);break}}if(age>60)k=96000;
const cash=Math.round((2000+Math.max(0,age-22)*400)/100)*100,left=Math.max(0,1-(age-22.5)/10);
return {checking:Math.round(cash/3/100)*100,savings:cash-Math.round(cash/3/100)*100,k401Bal:Math.round(k/500)*500,iraBal:0,rothBal:0,invest:0,loans:Math.round(14000*left/100)*100,noLoans:left<=0,card:age<25?800:1500,limit:age<25?2000:5000,carValue:age<25?5000:8000}}
function applyExample(){if(G.typed)return;if(G.inp.status==='grad')Object.assign(G.inp,gradExample(G.inp.age));else{for(const k of ['checking','savings','k401Bal','iraBal','rothBal','invest','loans','card','limit','carValue'])G.inp[k]=DEFAULTS[k];G.inp.noLoans=false}}
const GRAD_HIDE=['years','jobIncome','family','kees','spend','tuition'];
function secFields(sec){let fs=G.inp.status==='grad'?sec.fields.filter(f=>!GRAD_HIDE.includes(f.k)):sec.fields;if(G.inp.noLoans)fs=fs.filter(f=>f.k!=='loans'&&f.k!=='loanRate');if(G.inp.tuitionPaid)fs=fs.filter(f=>f.k!=='tuition');return fs}
function readInputs(){
for(const sec of SECTIONS)for(const fl of secFields(sec)){const el=$('f-'+fl.k);if(!el)continue;let v=parseFloat(el.value);if(!isFinite(v))v=0;v=Math.max(0,v);
if(LIMITS[fl.k]){const lim=fl.k==='age'?(G.inp.status==='grad'?[21,60]:[18,24]):LIMITS[fl.k];v=Math.min(lim[1],Math.max(lim[0],v))}if(fl.k==='age'||fl.k==='years')v=Math.round(v);G.inp[fl.k]=v}
if(G.inp.noLoans)G.inp.loans=0;if(G.inp.tuitionPaid)G.inp.tuition=0;
}
function goHome(){if(G.phase==='home')return;G.auto=false;G.fast=false;closeTurn();if(G.phase!=='glossary')G.backTo=G.phase;G.phase='home';render();window.scrollTo({top:0,behavior:'smooth'})}
function openGloss(id){if(G.phase!=='glossary'){G.glossFrom=G.phase;if(G.phase!=='home'){G.auto=false;G.fast=false;closeTurn();G.backTo=G.phase}}G.phase='glossary';render();window.scrollTo({top:0});if(id)setTimeout(()=>glossFlash(id),50)}
function glossFlash(id){const e=$('g-'+id);if(!e)return;const q=$('hgSearch');if(q&&q.value){q.value='';filterGloss('')}e.scrollIntoView({behavior:matchMedia('(prefers-reduced-motion: reduce)').matches?'auto':'smooth',block:'center'});e.classList.remove('flash');void e.offsetWidth;e.classList.add('flash')}
function twoLives(){const out={you:[],twin:[],out:null};let y=0,t=0,w=0;const keep=RET_MODE;RET_MODE='hist';const RI=a=>Math.pow((1+mixAt(a,'growth').flat)/(1+C.INFL),1/12)-1;RET_MODE=keep;const RIa={};for(let a=18;a<=85;a++){RET_MODE='hist';RIa[a]=RI(a);RET_MODE=keep}const rs=Math.pow((1+C.CASH)/(1+C.INFL),1/12)-1;
for(let age=18;age<=85;age++){
out.you.push([age,y]);out.twin.push([age,t]);
if(age===65)w=0.04*y/12;
for(let m=0;m<12;m++){const ri=RIa[age];if(age>=22&&age<65){y=y*(1+ri)+250;t=t*(1+rs)+250}else if(age>=65){y=Math.max(0,y*(1+ri)-w);const t0=t;t=Math.max(0,t*(1+rs)-w);if(t0>0&&t===0&&out.out==null)out.out=age}}
if(age===39)y*=.8}
out.w=w;return out}
function twoLivesSVG(animate){const d=twoLives(),sm=window.innerWidth<560,W=sm?380:600,H=sm?270:300,L=14,Rr=14,T=26,B=58,x=a=>L+(a-18)/(85-18)*(W-L-Rr),mx=Math.max(...d.you.map(p=>p[1])),yv=v=>H-B-(v/mx)*(H-T-B);
const path=pts=>pts.map((p,i)=>(i?'L':'M')+x(p[0]).toFixed(1)+' '+yv(p[1]).toFixed(1)).join(' ');
const yp=path(d.you),area=yp+` L${x(85)} ${H-B} L${x(18)} ${H-B} Z`,tp=path(d.twin);
const at=a=>d.you.find(p=>p[0]===a)[1],tw=a=>d.twin.find(p=>p[0]===a)[1];
const ms=[[22,'brief',sm?'Job':'First job'],[30,'heart',sm?'Kids':'Family'],[40,'waves','Crash'],[65,'sun','Retire']];
const k=v=>'$'+Math.round(v/1000)+'K';
return `<svg class="lives${animate?' draw':''}" viewBox="0 0 ${W} ${H}" role="img" aria-labelledby="livesT livesD">
<title id="livesT">You and your twin, same paycheck</title><desc id="livesD">You invest your savings and your twin keeps theirs in a savings account. By 65 yours grows to about ${k(at(65))} in today's dollars and your twin's to about ${k(tw(65))}.${d.out?` Spending the same amount in retirement, your twin runs out of money at ${d.out}.`:''}</desc>
<line class="lv-base" x1="${L}" x2="${W-Rr}" y1="${H-B}" y2="${H-B}"/><text class="lv-axis" x="${W-Rr}" y="${H-B+36}" text-anchor="end">85</text>
<path class="lv-area" d="${area}"/>
<path class="lv-twin" d="${tp}"/>
<path class="lv-you" d="${yp}" pathLength="1"/>
${ms.map(([a,i,l])=>`<g class="lv-ms" transform="translate(${x(a).toFixed(1)} 0)"><line y1="${yv(at(a)).toFixed(1)}" y2="${H-B}"/><circle cy="${yv(at(a)).toFixed(1)}" r="4.5"/><text y="${H-B+20}" text-anchor="${a===30?'start':'middle'}" x="${a===30?-6:a===40&&sm?8:0}">${l}</text><text class="lv-age" y="${H-B+36}" text-anchor="${a===30?'start':'middle'}" x="${a===30?-6:a===40&&sm?8:0}">${a}</text></g>`).join('')}
<g class="lv-tag" transform="translate(${x(65).toFixed(1)} ${(yv(at(65))-14).toFixed(1)})"><text text-anchor="middle" class="lv-big">${k(at(65))}</text></g>
<g transform="translate(${x(65).toFixed(1)} ${(yv(tw(65))-10).toFixed(1)})"><text text-anchor="middle" class="lv-small">${k(tw(65))}</text></g>
</svg>
<div class="lv-key"><span class="k-you">You: invested</span><span class="k-twin">Your twin: savings account${d.out?`, runs out at ${d.out}`:''}</span></div>`}
function renderHome(el){const mid=G.s&&G.backTo&&G.backTo!=='setup'&&G.backTo!=='home'&&G.backTo!=='glossary',saved=!mid&&hasSave();
const anim=!G.homeDrawn&&!matchMedia('(prefers-reduced-motion: reduce)').matches;G.homeDrawn=true;
const steps=[['Enter your numbers','Or use examples. Nothing leaves this page.'],['Choose, stage by stage','Job, rent, saving, investing, a home, a family.'],['Live with what happens','Raises, layoffs, repairs and crashes, at random.'],['See the whole picture','What each choice was worth, and your next real steps.']];
el.innerHTML=`<section class="panel hhero">
<div class="hh-copy">
<h2 class="hh-title">Same paycheck.<br>Same luck.<br>One invested.</h2>
<p class="hh-lede">You and your twin earn and save the same. You invest your savings. Your twin keeps theirs in a savings account. Watch what that one difference does.</p>
<div class="hh-cta">
${mid?`<button type="button" class="btn" id="hContinue">${ic('play')} Continue at age ${Math.floor(G.s.age)}</button>`:''}
${saved?`<button type="button" class="btn" id="hResume">${ic('play')} Continue your saved game</button>`:''}
<button type="button" class="btn ${mid||saved?'ghost':''}" id="hStart">${mid||saved?'Start a new life':'Start playing'}</button>
</div>
<div class="hh-more">
<button type="button" class="hlink" id="hLearn">${ic('doc')} Learn the basics first</button>
<button type="button" class="hlink" id="hDemo">${ic('sun')} Watch a sample life</button>
<button type="button" class="hlink" id="hOpen">${ic('doc')} Open a saved game file</button>
<button type="button" class="hlink" id="hGlossBtn">${ic('cap')} Money glossary</button>
</div>
<p class="hh-short"><b>Short on time?</b> Watch a sample life, then tap <b>Skip to the end</b>.</p>
</div>
<figure class="hh-chart">${twoLivesSVG(anim)}<figcaption>Example: you each save $250 a month from 22 to 65. Yours is invested; your twin's earns 3.5% in savings. <details class="more figmore"><summary>About this example</summary>Investments follow the game's default growth mix, about 9% a year before inflation while young and less as it gets safer, with a crash at 40. Shown in today's dollars after 3% inflation, before taxes and without a 401(k) match. From 65 you both spend the same amount each month.</details></figcaption></figure>
</section>
${whyHTML()}
<section class="hhow" aria-labelledby="hhowT">
<h3 id="hhowT">How it works</h3>
<ol class="hflow">${steps.map(([t,d],i)=>`<li><span class="hf-n">${i+1}</span><b>${t}</b></li>`).join('')}</ol>
<p class="hfoot">Built for Kentucky's taxes, KEES and wages. For learning only, not financial advice. Fonts: Bricolage Grotesque, Atkinson Hyperlegible and IBM Plex Mono from Google Fonts (SIL Open Font License), the only outside service this page uses. Nothing you enter is sent to it. <button type="button" class="linkbtn" id="hMath">How the math works</button></p>
</section>`;
const go=(after)=>{G.phase='setup';G.backTo=null;render();window.scrollTo({top:0});if(after)after()};
$('hStart').onclick=()=>{if(mid||saved){G.s=null;G.twin=null;G.lessonI=0}go()};
$('hLearn').onclick=()=>{if(mid||saved){G.s=null;G.twin=null}G.lessonI=0;go(()=>{const n=document.querySelector('.lesson-nav');if(n)n.scrollIntoView({behavior:'smooth',block:'start'})})};
$('hDemo').onclick=()=>{G.backTo=null;startDemo()};
$('hGlossBtn').onclick=()=>openGloss();
if($('hContinue'))$('hContinue').onclick=()=>{G.phase=G.backTo;G.backTo=null;render();window.scrollTo({top:0})};
if($('hOpen'))$('hOpen').onclick=()=>pickFile($('hOpen'));
if($('hResume'))$('hResume').onclick=()=>{if(loadGame()){G.backTo=null;render();window.scrollTo({top:0})}};
$('hMath').onclick=()=>{const d=document.querySelector('footer details');if(d){d.open=true;d.scrollIntoView({behavior:'smooth',block:'start'})}};
}
function whyHTML(){const keep=RET_MODE;RET_MODE='hist';const match=riskGrow(22,'growth',2500/12,0),extra=riskGrow(22,'growth',300,0),wait=riskGrow(22,'growth',200,0)-riskGrow(32,'growth',200,0);RET_MODE=keep;
const k=v=>'$'+(v>=1e6?(v/1e6).toFixed(1)+' million':Math.round(v/1000)+',000');
const Y='<span role="img" class="ck yes" aria-label="Yes">'+ic('check')+'</span>',N='<span role="img" class="ck no" aria-label="No">–</span>',P='<span role="img" class="ck part" aria-label="Partly">Partly</span>';
const rows=[['Uses your own real numbers',Y,Y,Y,Y,N],['Connects every choice in one life',Y,P,N,N,P],['Shows what a choice at 22 is worth at 65',Y,P,N,P,N],['Replays your life with one choice changed',Y,N,N,N,N],['Throws real surprises, like layoffs and crashes',Y,N,N,N,Y],['Uses Kentucky taxes, KEES and Lexington wages',Y,P,N,N,N],['Ends with real next steps',Y,N,P,N,N]];
return `<section class="why" aria-labelledby="whyT">
<h3 id="whyT">Why this game exists</h3>
<div class="whygrid">
<article class="panel whycard"><span class="eyebrow">Who it's for</span><h4>A UK student who was never taught personal finance</h4>
<p>Picture a UK sophomore who's never had a class on money. She'll graduate with about $33,000 in loans, then get a 401(k) form with her first job. Those choices shape the next 40 years, and she'll make them without seeing where they lead.</p>
<p><b>Already graduated?</b> Start at your age with your real salary, loans and savings.</p>
<p><b>The problem:</b> real life shows you the ending when it's too late to change it. This game shows it first.</p>
<div class="whystats"><div><b>$32,996</b><span>average debt for Kentucky public university graduates who borrow</span></div><div><b>38%</b><span>of basic personal finance questions Gen Z answers correctly, the lowest of any generation</span></div></div>
<p class="whysrc">Sources: <a href="https://cpe.ky.gov/data/reports/2025debtreport.pdf" target="_blank" rel="noopener noreferrer">Kentucky Council on Postsecondary Education, 2025</a> · <a href="https://gflec.org/wp-content/uploads/2025/05/2025_05_29_PFIN-Index-Release_FINAL.pdf" target="_blank" rel="noopener noreferrer">TIAA Institute–GFLEC P-Fin Index, 2025</a></p></article>
<article class="panel whycard"><span class="eyebrow">What it's worth</span><h4>Decisions worth hundreds of thousands of dollars, made before they cost anything</h4>
<p>With the game's historical returns, in today's dollars:</p>
<ul class="whyvals"><li><b>${k(match)}</b> by 65 from taking a 5% 401(k) match on a $50,000 salary, starting at 22</li><li><b>${k(extra)}</b> by 65 from investing $300 a month you'd otherwise spend on extras</li><li><b>${k(wait)}</b> lost by starting to invest $200 a month at 32 instead of 22</li></ul>
<p>After every stage, see what each choice was worth. At the end, get five real next steps.</p></article>
<article class="panel whycard"><span class="eyebrow">Why it's different</span><h4>Not another calculator</h4>
<p>Spreadsheets, bank apps and calculators each show one piece. Most money games use made-up numbers or cost money. This is your whole financial life, free, in about 20 minutes.</p>
<div class="tblwrap"><table class="whytbl"><thead><tr><th scope="col"></th><th scope="col">The Long Game</th><th scope="col">Spreadsheet</th><th scope="col">Bank app</th><th scope="col">Online calculator</th><th scope="col">Other money games</th></tr></thead>
<tbody>${rows.map(r=>`<tr><th scope="row">${r[0]}</th>${r.slice(1).map((c,i)=>`<td data-l="${['The Long Game','Spreadsheet','Bank app','Calculator','Other games'][i]}">${c}</td>`).join('')}</tr>`).join('')}</tbody></table></div>
<p class="whysrc">Other games compared: <a href="https://ngpf.org/blog/interactive/top-10-ngpf-interactives" target="_blank" rel="noopener noreferrer">Spent and Payback (NGPF's top interactives)</a> · <a href="https://www.bestmoney.com/financial-advisor/learn-more/best-financial-literacy-games" target="_blank" rel="noopener noreferrer">Financial Football, Budget Challenge and others (BestMoney's list)</a> · <a href="https://www.stocktrak.com/college-personal-finance-simulations/" target="_blank" rel="noopener noreferrer">StockTrak college simulation ($19.99 per student)</a></p></article>
</div></section>`}
function renderGlossary(el){const from=G.glossFrom||'home',back=from==='home'?'Back to home':from==='setup'?'Back to setup':'Back to your game';
const topics=[['Budgeting','budget'],['Credit scores','credit-score'],['Student loans','student-loans'],['Emergency funds','emergency-fund'],['Compounding','compounding'],['401(k) match','match'],['Roth IRA','roth-ira'],['Index funds','index-fund'],['Risk tolerance','risk-tolerance'],['Buying a home','mortgage'],['Life insurance','life-insurance'],['Social Security','social-security'],['Kentucky taxes','income-tax'],['Retirement','retirement-planning']];
el.innerHTML=`<div class="btns" style="margin-bottom:12px"><button type="button" class="btn ghost" id="gBack">${back}</button></div>
${homeGlossHTML(topics)}`;
$('gBack').onclick=()=>{const f=G.glossFrom||'home';G.glossFrom=null;if(f==='home'){G.phase='home'}else{G.phase=f;G.backTo=null}render();window.scrollTo({top:0})};
el.querySelectorAll('.hchips [data-g]').forEach(b=>b.onclick=()=>glossFlash(b.dataset.g));
$('hgSearch').addEventListener('input',e=>filterGloss(e.target.value));
el.querySelectorAll('.hgletters [data-l]').forEach(b=>b.onclick=()=>{const t=el.querySelector(`.hgitem[data-l="${b.dataset.l}"]`);if(t){const q=$('hgSearch');if(q.value){q.value='';filterGloss('')}t.scrollIntoView({behavior:'smooth',block:'center'})}});
}
const HOME_GLOSS=[
['401(k)','401k','A retirement account through your job. Money comes out of your paycheck before income tax, grows without being taxed, and is taxed when you take it out in retirement. Taking it out before age 59½ usually costs a 10% penalty plus tax.','The 2026 limit is $24,500 a year.'],
['Bonds','bonds','Loans you make to a government or a company in exchange for regular interest. Bonds are steadier than stocks but grow less over time.','A mix with more bonds drops less in a crash.'],
['Brokerage account','brokerage','A regular investment account. There\'s no limit on how much you put in and you can take money out anytime, but you pay tax on dividends each year and on your gains when you sell.','Good for goals before retirement, like a house.'],
['Budget','budget','A plan for where each dollar goes every month: needs like rent and food, wants like eating out, and savings. A budget isn\'t about spending less on everything. It\'s about spending on purpose.','A common starting point is 50/30/20: 50% needs, 30% wants, 20% savings.'],
['Compounding','compounding','When your investment earnings start earning money of their own, so growth speeds up the longer you wait. Time matters more than the amount you start with.','$1,000 growing 7% a year becomes about $1,967 in 10 years and $7,612 in 30.'],
['Credit card','credit-card','A card that lets you borrow up to a limit. Pay the full balance every month and you pay no interest. Carry a balance and you pay a high rate, often 20% to 30% a year.','Using less than 30% of your limit helps your credit score.'],
['Credit score','credit-score','A number from 300 to 850 that tells lenders how likely you are to pay them back. A higher score gets you lower interest rates on cars, homes and credit cards. Paying on time matters most.','Above about 740 is very good. Below 580 is poor.'],
['Down payment','down-payment','The cash you pay up front when you buy a home. The rest is your mortgage. Many first-time buyers put 3.5% to 20% down.','On a $260,000 home, 10% down is $26,000.'],
['Emergency fund','emergency-fund','Cash set aside for surprises like a car repair, a medical bill or losing your job. It keeps a bad week from turning into credit card debt.','Start with $1,000, then build to 3 to 6 months of expenses.'],
['Employer match','match','Free money your employer adds to your 401(k) when you put money in. Not getting the full match is like turning down part of your pay.','In the game, your employer matches dollar for dollar up to 5% of your pay. Earn $50,000, put in $2,500, and they add $2,500.'],
['Expense ratio','expense-ratio','The yearly fee a fund charges, as a percentage of your balance. It comes out automatically, so it\'s easy to miss.','0.05% costs $5 a year per $10,000. 1% costs $100.'],
['Home equity','home-equity','What your home is worth minus what you still owe on it. It grows as you pay down your mortgage and as the home rises in value.','A $300,000 home with a $200,000 mortgage has $100,000 of equity.'],
['Income tax','income-tax','Tax on the money you earn. The federal tax rate rises in steps as your income rises. Kentucky charges a flat 3.5% on income above its standard deduction.','The game uses 2026 federal and Kentucky rules.'],
['Index fund','index-fund','A fund that buys every company in a market index, like the S&P 500, instead of trying to pick winners. That spreads out your risk and keeps fees very low.','Over long periods, most professional stock pickers fail to beat the index after fees.'],
['Inflation','inflation','Prices rising over time, so each dollar buys a little less every year. "Today\'s dollars" adjusts future amounts so they feel like money now.','At 3% a year, prices roughly double in 24 years.'],
['International stocks','international-stocks','Shares of companies based outside the US, like Toyota or Nestlé. Owning them spreads your risk, because different countries\' markets have good and bad years at different times.','A typical target-date fund keeps about 40% of its stocks in international companies.'],
['Interest and APR','interest','Interest is what borrowing costs you, or what saving earns you. APR is the yearly interest rate on a loan or credit card.','$1,000 left on a card at 24% APR costs about $240 a year.'],
['KEES','kees','The Kentucky Educational Excellence Scholarship. Kentucky high school students earn it with their grades and test scores, and it helps pay for college in Kentucky. Your college GPA decides whether you keep it.','You can check your KEES balance in your KHEAA account.'],
['KHEAA','kheaa','The Kentucky Higher Education Assistance Authority, the state agency that runs KEES and other state student aid programs.','Its site is kheaa.com.'],
['KY Saves 529','ky-saves-529','Kentucky\'s 529 college savings plan. Money grows tax-free when it\'s used for school costs, and there\'s no minimum to start.','Even $25 a month from birth adds up by 18.'],
['Life expectancy','life-expectancy','How long people live on average. Kentuckians who reach 65 live to about 82, among the lowest in the country. Habits like smoking and exercise change it.','The longer you live, the longer your money has to last.'],
['Life insurance','life-insurance','A policy that pays the people you name if you die. Term life covers a set number of years and is cheap. Whole life lasts your whole life, builds cash value and costs much more.','It matters most when a partner or kids depend on your income.'],
['Local payroll tax','payroll-tax','A tax many Kentucky cities and counties take straight from your wages, on top of state and federal taxes. Social Security and Medicare also come out of every paycheck (7.65% together).','Lexington charges 2.25%. Louisville charges about 2.2% for residents.'],
['Market crash','market-crash','A sudden, steep drop in stock prices, like in 2008 or early 2020. The US stock market has always recovered so far, but it can take years. Selling during a crash locks in the loss.','In the game, stocks drop 25% around age 40.'],
['Mortgage','mortgage','A loan to buy a home, usually paid back over 15 or 30 years. The home backs the loan, so if you stop paying, the lender can take it.','Selling a home costs about 6% in agent fees and closing costs.'],
['Net worth','net-worth','Everything you own minus everything you owe. It\'s the clearest single number for your financial health.','$20,000 in savings and investments minus $15,000 in loans is a net worth of $5,000.'],
['Opportunity cost','opportunity-cost','What you give up when you choose one thing over another. Every dollar spent is a dollar that can\'t be saved or invested.','At the end of the game, you\'ll see what each choice you didn\'t make would have been worth.'],
['Quit Now Kentucky','quit-now','Kentucky\'s free program to help people quit smoking or vaping, with coaching by phone or online.','Call 1-800-QUIT-NOW (1-800-784-8669).'],
['Retirement planning','retirement-planning','Working out how much you\'ll need to stop working and how to get there: saving, investing, Social Security and how fast you spend. A common rule of thumb is that you can spend about 4% of your investments a year.','$1,000,000 invested supports about $40,000 a year by that rule.'],
['Risk tolerance','risk-tolerance','How much your investments can drop without you panicking or needing the money. It depends on how soon you need it and how you handle losses. More risk usually means more growth over decades, with bigger drops along the way.','In the game, you pick a mix from 40% stocks (conservative) to 100% stocks (aggressive).'],
['Roth IRA','roth-ira','A retirement account you fund with money you\'ve already paid tax on. It grows tax-free, and you take it out tax-free in retirement. You can take out what you put in (not the growth) anytime.','The 2026 limit is $7,500 a year.'],
['Social Security','social-security','Monthly income from the federal government in retirement, paid for by taxes on your paychecks. You can start between 62 and 70. Starting later gets you a bigger check for life.','Full retirement age is 67 for anyone born in 1960 or later.'],
['Stocks','stocks','Small pieces of ownership in companies. Over long periods they have grown more than almost any other investment, but they can drop sharply in a bad year.','US stocks have averaged roughly 10% a year over the past century, before inflation.'],
['Student loans','student-loans','Money borrowed to pay for school. Federal loans usually have fixed rates and flexible repayment plans. Unsubsidized loans build interest even while you\'re in school, and payments usually start 6 months after you leave.','You can see all your federal loans at StudentAid.gov.'],
['Target-date fund','target-date-fund','One fund that holds a full mix of US stocks, international stocks and bonds, picked for the year you plan to retire. It gets safer on its own as you age.','A typical one holds about 90% stocks until 40, about 50% at 65 and 30% by 72. The game\'s typical risk level for your age follows this path.'],
['Twin (in the game)','twin','A copy of you who makes every choice you do and lives through the same surprises, but never invests a dollar. Comparing yourself with your twin shows what investing alone was worth.','']];
function homeGlossHTML(topics){const L=[...new Set(HOME_GLOSS.map(g=>g[0][0].toUpperCase().replace(/[0-9]/,'#')))];
return `<section class="panel stack hgloss" id="hGloss"><div class="sec-head"><span class="badge">${ic('cap')}</span><div><span class="eyebrow">Money glossary</span><h2>Every term, in plain English</h2></div></div>
${topics?`<div class="stack" style="gap:6px"><span class="eyebrow">Jump to a topic</span><div class="hchips">${topics.map(([x,id])=>`<button type="button" data-g="${id}">${x}</button>`).join('')}</div></div>`:''}
<label class="hgsearch"><span class="sr">Search the glossary</span><input id="hgSearch" type="search" placeholder="Search terms, like "Roth" or "interest"" autocomplete="off"></label>
<div class="hgletters" aria-label="Jump to letter">${L.map(l=>`<button type="button" data-l="${l}">${l}</button>`).join('')}</div>
<dl class="hglist">${HOME_GLOSS.map(([t,id,d,ex])=>`<div class="hgitem" id="g-${id}" data-l="${t[0].toUpperCase().replace(/[0-9]/,'#')}" data-q="${esc((t+' '+d+' '+ex).toLowerCase())}"><dt>${t}</dt><dd>${d}${ex?`<span class="hgex">${ex}</span>`:''}</dd></div>`).join('')}</dl>
<p class="hgnone muted" id="hgNone" hidden>No terms match. Try a shorter word.</p></section>`}
function filterGloss(q){q=q.trim().toLowerCase();let n=0;document.querySelectorAll('.hgitem').forEach(e=>{const on=!q||e.dataset.q.includes(q);e.hidden=!on;if(on)n++});const no=$('hgNone');if(no)no.hidden=n>0}
function renderSetup(el){
el.innerHTML=`<section class="panel start"><div class="stack" style="gap:6px"><span class="eyebrow">Two ways to start</span><h2>Jump in, or learn first</h2>
<p class="muted">Play right away with example numbers, or work through six short lessons below using your own. Each takes about a minute. Your numbers never leave this page.</p></div>
<fieldset class="q" style="flex:1 1 100%"><legend style="font-size:var(--fs-base)">First, where are you in life?</legend><div class="opts">
<label class="opt"><input type="radio" name="status" value="college" ${G.inp.status!=='grad'?'checked':''}><b>I'm in college</b><span class="hint">Start the game in school</span></label>
<label class="opt"><input type="radio" name="status" value="grad" ${G.inp.status==='grad'?'checked':''}><b>I've already graduated</b><span class="hint">Skip college and start at any age from 21 to 60</span></label></div>
${G.inp.status==='grad'?`<div class="agepick"><label for="startAge">How old are you? The game starts here. <b id="startAgeV">${G.inp.age}</b></label><input type="range" id="startAge" min="21" max="60" step="1" value="${G.inp.age}" aria-describedby="startAgeH"><div class="ticks"><span>21</span><span>30</span><span>40</span><span>50</span><span>60</span></div><p class="muted" id="startAgeH" style="font-size:var(--fs-sm);margin:4px 0 0">Starting later means less time for investments to grow, and a job that pays more for your experience. ${G.typed?'Enter what you\'ve already saved in the lessons below.':`Example numbers below are for a typical ${G.inp.age}-year-old, with a 401(k) near the median for that age (Vanguard, How America Saves 2025). Change them to your own in the lessons.`}</p></div>`:''}</fieldset>
<fieldset class="q" style="flex:1 1 100%"><legend style="font-size:var(--fs-base)">Pick up to 3 life goals <span class="muted" style="font-weight:400;font-size:var(--fs-sm)">(optional, graded at the end)</span></legend><div class="opts goals">
${GOALS.map(g=>{const late=g.by&&G.inp.age>=g.by;return `<label class="opt ${late?'off':''}"><input type="checkbox" name="goal" value="${g.id}" ${late?'disabled':G.inp.goals.includes(g.id)?'checked':''}><b>${g.label}</b><span class="hint">${late?`You're already ${G.inp.age}`:g.hint}</span></label>`}).join('')}</div></fieldset>
<div class="btns">${hasSave()?`<button class="btn" id="resume">${ic('play')} Continue your saved game</button>`:''}<button class="btn ${hasSave()?'ghost':''}" id="quick">${ic('play')} Play now${G.inp.status==='grad'?' as a graduate':''}</button><button class="btn ghost" id="demo">Watch a sample life</button></div></section>
<div class="lesson-nav" role="tablist" aria-label="Lessons">${SECTIONS.map((sec,i)=>`<button type="button" role="tab" class="ltab" data-i="${i}">${ic(sec.icon)}<span>${sec.title}</span></button>`).join('')}</div>
${SECTIONS.map((sec,i)=>`<section class="panel sec lstep" data-i="${i}" id="sec-${sec.id}">
<div class="sec-head"><span class="badge">${ic(sec.icon)}</span><div><span class="eyebrow">Lesson ${i+1} of ${SECTIONS.length}${i===0&&!G.edited?' · <span class="example">Example numbers shown</span>':''}</span><h2>${sec.title}</h2></div></div>
${sec.id==='month'&&G.inp.status!=='grad'?`<label class="opt noloans"><input type="checkbox" id="tuitionPaid" ${G.inp.tuitionPaid?'checked':''}><b>My tuition is already paid for</b><span class="hint">${G.inp.noLoans?'Turned on because you said you have no student loans.':'Scholarships, family or savings cover it, so the game won\'t add tuition loans.'}</span></label>`:''}
${sec.id==='loans'?`<label class="opt noloans"><input type="checkbox" id="noLoans" ${G.inp.noLoans?'checked':''}><b>I don't have any student loans</b><span class="hint">${G.inp.status==='grad'?'Skip the loan numbers. You can still borrow later in the game.':'No loans now and none for school: your tuition counts as paid. You can still borrow later if money runs short.'}</span></label>`:''}
<div class="fields">${secFields(sec).map(fl=>`<div class="field"><label for="f-${fl.k}">${fl.l}</label><div class="inp">${fl.pre?`<span>${fl.pre}</span>`:''}<input id="f-${fl.k}" inputmode="decimal" value="${G.inp[fl.k]}">${fl.suf?`<span>${fl.suf}</span>`:''}</div>${fl.sm?`<small>${fl.sm}</small>`:''}</div>`).join('')}</div>
<div class="learn" id="learn-${sec.id}">${lessonFor(sec.id,G.inp)}</div>
<div class="lesson-foot">${i>0?`<button type="button" class="btn ghost lprev">Back</button>`:'<span></span>'}${i<SECTIONS.length-1?`<button type="button" class="btn lnext">Next lesson: ${SECTIONS[i+1].title} ${ic('arrow')}</button>`:`<button class="btn" id="go">Start the game with my numbers ${ic('arrow')}</button>`}</div></section>`).join('')}`;
{const sa=$('startAge');if(sa){sa.addEventListener('input',()=>{$('startAgeV').textContent=sa.value;const fa=$('f-age');if(fa)fa.value=sa.value});sa.addEventListener('change',()=>{readInputs();G.inp.age=+sa.value;applyExample();G.inp.goals=G.inp.goals.filter(id=>{const g=GOALS.find(x=>x.id===id);return !(g&&g.by&&G.inp.age>=g.by)});G.edited=true;render();const n=$('startAge');if(n)n.focus()})}}
el.querySelectorAll('input[name=status]').forEach(i=>i.addEventListener('change',()=>{readInputs();G.inp.status=i.value;if(i.value==='grad'&&G.inp.age<23)G.inp.age=25;if(i.value!=='grad'&&G.inp.age>24)G.inp.age=20;applyExample();render()}));
document.querySelectorAll('input[name=retmode]').forEach(i=>i.addEventListener('change',()=>{readInputs();G.inp.returns=i.value;syncMode();render()}));
const tp=$('tuitionPaid');if(tp)tp.addEventListener('change',()=>{readInputs();G.inp.tuitionPaid=tp.checked;if(tp.checked){G.inp.prevTuition=G.inp.tuition||G.inp.prevTuition;G.inp.tuition=0}else{G.inp.tuition=G.inp.prevTuition||DEFAULTS.tuition;if(G.inp.noLoans){G.inp.noLoans=false;G.inp.loans=0}}G.edited=true;render()});
const nl=$('noLoans');if(nl)nl.addEventListener('change',()=>{readInputs();G.inp.noLoans=nl.checked;const col=G.inp.status!=='grad';if(nl.checked){G.inp.prevLoans=G.inp.loans||G.inp.prevLoans;G.inp.loans=0;if(col){G.inp.tpBefore=!!G.inp.tuitionPaid;if(!G.inp.tuitionPaid){G.inp.prevTuition=G.inp.tuition||G.inp.prevTuition;G.inp.tuitionPaid=true;G.inp.tuition=0}}}else{G.inp.loans=G.inp.prevLoans||DEFAULTS.loans;if(col&&G.inp.tpBefore===false){G.inp.tuitionPaid=false;G.inp.tuition=G.inp.prevTuition||DEFAULTS.tuition}}G.edited=true;render()});
el.querySelectorAll('.fields input').forEach(i=>i.addEventListener('input',()=>{G.edited=true;G.typed=true;readInputs();for(const sec of SECTIONS)$('learn-'+sec.id).innerHTML=lessonFor(sec.id,G.inp);renderSide();renderTrack()}));
const showL=(i,scroll)=>{G.lessonI=i;el.querySelectorAll('.lstep').forEach(x=>{const on=+x.dataset.i===i;x.hidden=!on;if(on){x.classList.remove('enter');void x.offsetWidth;x.classList.add('enter')}});
el.querySelectorAll('.ltab').forEach(t=>{const on=+t.dataset.i===i;t.classList.toggle('on',on);t.setAttribute('aria-selected',on)});
if(scroll){const nav=el.querySelector('.lesson-nav');nav.scrollIntoView({behavior:matchMedia('(prefers-reduced-motion: reduce)').matches?'auto':'smooth',block:'start'})}};
el.querySelectorAll('.ltab').forEach(t=>t.onclick=()=>showL(+t.dataset.i,false));
el.querySelectorAll('.lnext').forEach(b=>b.onclick=()=>showL((G.lessonI||0)+1,true));
el.querySelectorAll('.lprev').forEach(b=>b.onclick=()=>showL((G.lessonI||0)-1,true));
showL(G.lessonI||0,false);
$('go').onclick=()=>{readInputs();startRun(G.seed)};
$('quick').onclick=()=>{readInputs();startRun(G.seed)};
el.querySelectorAll('input[name=goal]').forEach(i=>i.addEventListener('change',()=>{const on=[...el.querySelectorAll('input[name=goal]:checked')].map(x=>x.value);if(on.length>3){i.checked=false;return}G.inp.goals=on}));
if($('resume'))$('resume').onclick=()=>{if(loadGame())render()};
$('demo').onclick=()=>{readInputs();startDemo()};
}
function startRun(seed){syncMode();G.snaps=[];G.log=[];G.turns=[];G.prevNW=null;G.seed=seed;G.s=newState(G.inp,seed);G.twin=newState(G.inp,seed);G.twin.cash+=G.twin.brok+G.twin.k401+G.twin.roth;G.twin.brok=0;G.twin.brokBasis=0;G.twin.k401=0;G.twin.iraFrac=0;G.twin.roth=0;G.twin.rothBasis=0;G.twin.mcStart=0;G.twin.noInvest=true;G.done=[];G.block=nextBlock(G.s);G.phase='decide';G.enter=enterStage(G.s,G.block.key);enterStage(G.twin,G.block.key);render();window.scrollTo({top:0,behavior:'smooth'})}
function stageIntro(s,key,enter){
const f=s.infl;
if(key==='college')return `You're ${s.startAge} with ${s.gradAge-s.startAge} year${s.gradAge-s.startAge>1?'s':''} of school left: ${money(s.schoolIncome*f)} a month in, ${money(s.schoolSpend*f)} out.${s.tuitionNet>0?` Tuition after KEES and aid is ${money(s.tuitionNet*f)} a year, borrowed each fall.`:' Your tuition is covered.'} Your twin makes the same choices but never invests.`;
if(key==='first'&&s.grad)return `You're ${s.startAge}${s.student.bal>1?` and owe ${money(s.student.bal,f)} in student loans, about ${money(pmt(s.student.bal,s.student.rate,120),f)} a month for 10 years`:''}. Set up your working life. Your twin makes the same choices but never invests.`;
if(key==='first'&&!(s.student.bal>1))return `You graduate at ${s.gradAge} with no student loans, so more of every paycheck is yours. Time to set up your grown-up life.`;
if(key==='first')return `You graduate at ${s.gradAge} owing ${money(s.student.bal,f)} in student loans: about ${money(pmt(s.student.bal*Math.pow(1+s.student.rate/12,6),s.student.rate,120),f)} a month for 10 years after a 6-month grace period.`;
if(key==='build')return `You got promoted: your salary rose 10%, from ${money(enter.old,f)} to ${money(enter.now,f)}. What you do with raises shapes the next 30 years.`;
if(key==='check'){const a=Math.round(s.age);return `You're ${a}. ${Math.round(G.block&&G.block.to?G.block.to-a:5)} more years ahead. ${a>=60?'The finish line is in sight, and compounding does most of the heavy lifting now.':a>=50?'You can now make catch-up contributions to your 401(k).':!(s.home>0)?'You can buy a home now or keep renting.':'Check your budget and decide what should change.'}`}
if(key==='retire2')return `You're ${Math.round(s.age)} and retired. You have ${money(liquidAfterTax(s),f)} in savings after taxes${s.broke!=null?', and your savings have run out':''}. You can adjust how you live for the rest of your life.`;
if(key==='mid')return `The stock market just dropped 25%. With ${Math.round((enter.w||.8)*100)}% of your money in stocks, your investments fell ${Math.round((enter.d||.25)*100)}%, from ${money(enter.old,f)} to ${money(enter.now,f)}, in a few months. The news is full of panic.`;
if(key==='retire'){const le=lifeExpect(s);return `You retire at ${Math.round(s.age)} with ${money(enter.nw,f)}. With your habits, people like you live to about <strong>${le}</strong>, but many outlive the average, so planners say to make your money last to 95. Your paycheck stops now.`}
}
function lifeMult(){return real||!G.s?1:G.s.infl}
function moneyQ(q){const m=lifeMult(),v=Math.round(q.def*m/500)*500,mx=Math.max(Math.round(60000*m/1000)*1000,Math.round(v*2.5/1000)*1000),mn=Math.round(6000*m/500)*500;
return `<div class="spendq"><input type="range" id="rg-${q.id}" min="${mn}" max="${mx}" step="500" value="${v}" aria-label="Yearly spending"><div class="spend-row"><div class="inp" style="max-width:220px"><span>$</span><input id="nm-${q.id}" inputmode="decimal" value="${v}"><span>/year</span></div><span class="muted" id="typ-${q.id}"></span><button type="button" class="btn ghost" style="padding:8px 14px;font-size:var(--fs-sm)" id="rs-${q.id}">Use typical</button></div></div>`}
function currentChoices(qs){const ch={};if(qs.some(q=>q.type==='money'))ch.lifeCustom=G.lifeMode==='custom';for(const q of qs){if(q.type==='money'){const n=$('nm-'+q.id);let v=parseFloat(n&&n.value)/lifeMult();ch[q.id]=isFinite(v)?Math.min(500000,Math.max(3000,v)):q.def;continue}const el=document.querySelector(`input[name="q-${q.id}"]:checked`);ch[q.id]=el?(isNaN(+el.value)?el.value:+el.value):q.def}
{const iy=$('ins-yrs'),ifc=$('ins-face');if(iy&&ifc){ch.insYears=TERM_YRS[+iy.value]||20;ch.insFace=+ifc.value||500000}}
if(ch.career==='custom'){const t=$('cj-title'),sa=$('cj-salary'),st=$('cj-style');ch.customTitle=(t&&t.value.trim())||'My job';let v=parseFloat(sa&&sa.value);if(!isFinite(v))v=50000;ch.customSalary=Math.min(500000,Math.max(15000,v));ch.customStyle=(st&&st.value)||'average'}
return ch}
function snapshot(s){
const f=s.infl,yr=x=>x*12,o={rows:[],income:0,incomeLabel:'',expenses:0,taxes:0,toInv:0,debtPay:0};
if(s.inSchool){o.incomeLabel='Job, family help and KEES';o.income=yr((s.schoolIncome+s.extraWork)*f);
o.rows=[{l:'Everything you spend',v:yr(Math.max(0,s.schoolSpend-s.spendCut)*f),c:'var(--c-home)'}]}
else if(s.retired){o.incomeLabel='Paycheck stops now';o.income=0;o.rows=[{l:'What you spent last year',v:s.lastYrSpend,c:'var(--c-home)'}]}
else if(s.salary>0){
const g=s.salary,k=Math.min(g*s.kPct,(C.K_LIMIT+(s.age>=50?C.K_CU:0))*f),t=taxes(g,k,f,s.localRate).total+(s.partner?taxes(s.partnerPay,0,f,s.localRate).total:0);
o.incomeLabel=s.partner?'Household pay before taxes':'Your pay before taxes';o.income=g+(s.partner?s.partnerPay:0);o.taxes=t;o.toInv=k;
const kids=kidsUnder18(s),hd=s.home>0;
o.rows=[{l:hd?'Home upkeep, tax, insurance':'Rent',v:yr(housingCost(s)),c:'var(--c-home)'},{l:'Everyday life',v:yr(lifeBase(s)),c:'var(--c-cash)'},{l:'Car costs',v:yr(s.carRun*f),c:'var(--c-car)'}];
if(s.partner)o.rows.push({l:'Partner\'s share of costs',v:yr(C.PARTNER_COST*f),c:'var(--c-roth)'});
if(kids)o.rows.push({l:`Kids (${kids})`,v:yr(kidCost(s)*f),c:'var(--c-529)'});
if(habitCost(s))o.rows.push({l:'Habits',v:yr(habitCost(s)*f),c:'var(--danger)'});
if(insPremium(s))o.rows.push({l:'Life insurance',v:yr(insPremium(s)),c:'var(--c-brok)'});
}
const dp=(s.student.bal>1&&!s.inSchool&&s.month>=s.graceUntil?s.student.pay:0)+(s.card.bal>1?Math.max(25,s.card.bal*s.card.rate/12+0.01*s.card.bal):0)+(s.carLoan.bal>1?s.carLoan.pay:0)+(s.mortgage.bal>1?s.mortgage.pay:0);
if(dp>0)o.rows.push({l:'Loan and card payments',v:yr(dp),c:'var(--c-debt)'});
o.expenses=o.rows.reduce((a,r)=>a+r.v,0);o.left=o.income-o.taxes-o.toInv-o.expenses;
return o;
}
function healthScore(s){
const o=snapshot(s),mn=Math.max(1,o.expenses/12||fixedNeeds(s)),ef=Math.min(25,25*(s.cash/mn)/3);
const nonMort=s.student.bal+s.card.bal+s.carLoan.bal,inc=o.income||1;
const debt=s.inSchool?25*(1-Math.min(1,s.card.bal/Math.max(1,cardLimit(s))/0.5)):25*(1-Math.min(1,nonMort/inc/0.5));
const sr=o.income>0?(o.toInv+Math.max(0,o.left)*s.savePct)/o.income:0,sav=s.inSchool?(o.left>=0?20:8):25*Math.min(1,sr/0.15);
const cr=25*Math.max(0,Math.min(1,(s.credit.score-550)/250));
const total=Math.round(ef+debt+sav+cr);
return {total,parts:[{l:'Emergency cushion',v:ef,t:s.cash>=mn*3?'3+ months':`${(s.cash/mn).toFixed(1)} months`},{l:s.inSchool?'Card balance':'Debt load',v:debt},{l:s.inSchool?'Living within means':'Saving rate',v:sav,t:s.inSchool?null:`${Math.round(sr*100)}% of pay`},{l:'Credit',v:cr,t:String(Math.round(s.credit.score))}],
label:total>=80?'Strong':total>=60?'Solid':total>=40?'Shaky':'At risk'};
}
function ring(v,label){const r=22,c=2*Math.PI*r,col=v>=80?'var(--accent)':v>=60?'var(--accent)':v>=40?'var(--gold)':'var(--danger)';
return `<span class="ring" title="Financial health ${v} of 100"><svg viewBox="0 0 56 56" aria-hidden="true"><circle cx="28" cy="28" r="${r}" fill="none" stroke="var(--sunk)" stroke-width="6"/><circle cx="28" cy="28" r="${r}" fill="none" stroke="${col}" stroke-width="6" stroke-linecap="round" stroke-dasharray="${c*v/100} ${c}" transform="rotate(-90 28 28)"/></svg><b>${v}</b><small>${label}</small></span>`}
const PIE={tax:['Taxes',1],home:['Housing',2],left:['Left to save or spend',3],life:['Everyday life',4],family:['Partner and kids',5],k401:['Into your 401(k)',6],car:['Car',7],debt:['Loan and card payments',8],saved:['Saved',3],fun:['Fun money',4],bills:['Bills and living',2]};
function pieCat(label){const l=label.toLowerCase();return l.startsWith('rent')||l.startsWith('home')?'home':l.startsWith('everyday')||l.startsWith('everything')?'life':l.startsWith('car')?'car':l.startsWith('partner')||l.startsWith('kids')?'family':l.startsWith('loan')?'debt':'other'}
function donut(items,f,center,sub){
const agg={};for(const it of items){if(!(it.v>0))continue;agg[it.k]=(agg[it.k]||0)+it.v}
const order=['tax','k401','bills','home','life','car','family','debt','other','saved','fun','left'];
let parts=order.filter(k=>agg[k]>0).map(k=>({k,v:agg[k]}));const tot=parts.reduce((a,p)=>a+p.v,0)||1;
const small=parts.filter(p=>p.k!=='left'&&p.k!=='other'&&p.v/tot<.03);if(small.length){parts=parts.filter(p=>!small.includes(p));const o=parts.find(p=>p.k==='other');const sv=small.reduce((a,p)=>a+p.v,0);if(o)o.v+=sv;else parts.splice(parts.length-(parts.at(-1)&&parts.at(-1).k==='left'?1:0),0,{k:'other',v:sv})}
const nm=k=>k==='other'?'Other':PIE[k][0],col=k=>k==='other'?'var(--pie-other)':`var(--pie-${PIE[k][1]})`;
const R=74,W=30,C=2*Math.PI*R,gap=parts.length>1?2.5:0;let acc=0;
const arcs=parts.map(p=>{const len=p.v/tot*C,da=`${Math.max(.5,len-gap)} ${C}`,off=-acc;acc+=len;return `<circle class="arc" cx="100" cy="100" r="${R}" fill="none" stroke="${col(p.k)}" stroke-width="${W}" stroke-dasharray="${da}" stroke-dashoffset="${off}" transform="rotate(-90 100 100)"><title>${nm(p.k)}: ${money(p.v,f)} (${Math.round(p.v/tot*100)}%)</title></circle>`}).join('');
return `<div class="donut"><svg viewBox="0 0 200 200" role="img" aria-label="${esc(center)} ${esc(sub)}: ${parts.map(p=>nm(p.k)+' '+Math.round(p.v/tot*100)+'%').join(', ')}">${arcs}<text x="100" y="96" text-anchor="middle" class="d-big">${center}</text><text x="100" y="116" text-anchor="middle" class="d-sub">${sub}</text></svg>
<ul class="d-legend">${parts.map(p=>`<li><i style="--c:${col(p.k)}"></i><span>${nm(p.k)}</span><b class="money">${money(p.v,f)}</b><em>${Math.round(p.v/tot*100)}%</em></li>`).join('')}</ul></div>`;
}
function healthHTML(s){if(s.retired)return '';const h=healthScore(s);
return `<div class="stack" style="gap:8px"><span class="eyebrow">Financial health: ${h.total} out of 100 · ${h.label}</span>
${barRows(h.parts.map(p=>({l:p.l,v:Math.max(.4,p.v),c:p.v>=18?'var(--accent)':p.v>=10?'var(--gold)':'var(--danger)',t:`${Math.round(p.v)}/25${p.t?' · '+p.t:''}`})),25)}
<p class="muted" style="font-size:var(--fs-sm)">Each part is worth 25 points: a cushion of 3 months of expenses, little debt compared with your income, saving at least 15% of your pay, and a strong credit score.</p></div>`}
function snapshotHTML(s){
const f=s.infl,o=snapshot(s),nw=netWorth(s),prevNW=G.prevNW,chg=prevNW!=null?nw-prevNW.nw:null,inv=invested(s);
const tile=(label,val,sub,cls='')=>`<div class="stat"><span class="eyebrow">${label}</span><span class="money ${cls}" style="font-size:var(--fs-lg);font-weight:600">${val}</span><small>${sub}</small></div>`;
const hs=s.retired||(!s.career&&!s.inSchool)?null:healthScore(s),open=G.snapOpen!=null?G.snapOpen:!G.simple&&!(G.turns&&G.turns.length);
return `<details class="panel snap" id="snap" ${open?'open':''}><summary class="snap-sum">
${hs?ring(hs.total,hs.label):`<span class="badge">${ic('sun')}</span>`}
<div class="snap-t"><span class="eyebrow">Before you choose</span><h2>Where you stand at ${Math.floor(s.age)}</h2>
<span class="snap-k"><span class="snap-nw">Net worth <b class="money ${nw<0?'neg':''}">${money(nw,f)}</b></span><span>Invested <b class="money">${money(inv,f)}</b></span><span>Credit <b class="money">${Math.round(s.credit.score)}</b></span></span>${hs?(()=>{const w=[...hs.parts].sort((a,b)=>a.v-b.v)[0],tip={'Emergency cushion':'build savings toward 3 months of expenses','Debt load':'pay down loans and cards','Card balance':'keep your card balance low','Saving rate':'save 15% of your pay, counting your 401(k)','Living within means':'spend less than you bring in','Credit':'pay on time and keep card balances low'}[w.l];return w.v<20?`<span class="snap-why">Health score ${hs.total}/100. Weakest area: <b>${w.l}</b> (${Math.round(w.v)}/25). To raise it, ${tip}.</span>`:`<span class="snap-why">Health score ${hs.total}/100. Every area is in good shape.</span>`})():''}</div>
<span class="chev" aria-hidden="true">${ic('arrow')}</span><span class="snap-more">${open?'Hide details':'Show details'}</span></summary>
<div class="stack snap-body">
<div class="stats">
${tile('Net worth',money(nw,f),chg!=null?`${chg>=0?'+':'−'}${money(Math.abs(chg),real?f:0)} since age ${Math.floor(prevNW.age)}`:'Own minus owe',nw<0?'neg':'')}
${tile('Income per year',o.income>0?money(o.income,f):'—',o.income>0?o.incomeLabel:s.retired?'Social Security comes next':'You choose your job below')}
${tile('Invested',money(inv,f),inv>0?'401(k), Roth IRA and brokerage':'Nothing invested yet')}
${tile('Credit score',Math.round(s.credit.score),creditLabel(s.credit.score)+(s.card.bal>1?` · card ${Math.round(s.card.bal/Math.max(1,cardLimit(s))*100)}% used`:''),s.credit.score<620?'neg':'')}
${tile('Expenses per year',o.expenses>0?money(o.expenses,f):'—',o.expenses>0?'Before any changes this turn':'Set below')}
</div>
${healthHTML(s)}
<div class="stack" style="gap:8px">${ownOweHTML(s)}</div>
${o.income>0&&o.rows.length?`<div class="stack" style="gap:8px"><span class="eyebrow">Where a year of income goes right now</span>
${donut([{k:'tax',v:o.taxes},{k:'k401',v:o.toInv},...o.rows.map(r=>({k:pieCat(r.l),v:r.v})),{k:'left',v:Math.max(0,o.left)}],f,money(o.income,f,{short:true}),o.left<0?'income, overspent':'income a year')}
<p class="muted" style="font-size:var(--fs-sm)">${o.left>=0?`About ${money(o.left/12,f)} a month is left after bills. Your choices below decide how much of it you save.`:`You're spending about ${money(-o.left/12,f)} a month more than you bring in. That gap comes from savings, then credit cards.`}</p></div>`:''}
</div></details>`;
}
const ADV=new Set(['city','exercise','smoke','health','fund','risk','acct','life','order','ins','quit','college']);
function isAdv(q,key){if(key==='college'||key==='retire2')return false;if(key==='first'&&q.id==='home')return true;if(key==='first'&&q.id==='acct')return false;return ADV.has(q.id)}
function renderDecide(el){
const st=G.block,s=G.s,qs=decisions(s,st.key),to=Math.round(st.to);
if(G.pend){for(const q of qs){if(q.options&&G.pend[q.id]!==undefined&&q.options.some(o=>String(o.v)===String(G.pend[q.id])&&!o.off))q.def=G.pend[q.id];if(q.type==='money'&&G.pend.lifeCustom&&G.pend[q.id]!=null){q.def=G.pend[q.id];G.pendLifeCustom=true}}G.pend=null}
const simple=G.simple,core=[],adv=[];qs.forEach((q,i)=>(simple&&isAdv(q,st.key)?adv:core).push(i));
const kiQ=qs.findIndex(q=>q.id==='kids'),caQ=qs.findIndex(q=>q.id==='care');if(kiQ>=0&&caQ>=0&&core.includes(kiQ)&&core.includes(caQ))core.splice(core.indexOf(caQ),1);
const stepOf=qs.map(()=>0);core.forEach((qi,k)=>stepOf[qi]=k);adv.forEach(qi=>stepOf[qi]=core.length);if(kiQ>=0&&caQ>=0&&!core.includes(caQ)&&core.includes(kiQ))stepOf[caQ]=stepOf[kiQ];
const nSteps=core.length+(adv.length?1:0);
const prevSnap=!G.auto&&(G.snaps||[]).length?G.snaps[G.snaps.length-1]:null;
el.innerHTML=`${prevSnap?`<div class="prevstage"><button type="button" class="linkbtn" id="prevStage">← Back to ages ${Math.round(prevSnap.from)} to ${Math.round(prevSnap.to)} to change your choices</button></div>`:''}${snapshotHTML(s)}<section class="panel stack" id="turn">
<div class="sec-head"><span class="badge">${ic(st.icon)}</span><div><span class="eyebrow">${st.key==='retire2'?`Age ${Math.round(s.age)} until your story ends`:`Ages ${Math.round(s.age)}–${to}${st.key==='retire'?' or until your story ends':''}`}</span><h2>${st.name}</h2></div></div>
${st.key==='mid'?`<div class="alert">${ic('bolt')}<span>${stageIntro(s,st.key,G.enter)}</span></div>`:`<p class="lede">${stageIntro(s,st.key,G.enter)}</p>`}
${st.key==='retire'?`<div class="learn"><h3>How Social Security timing plays out</h3><p>Each line is the total you'd collect by each age. Starting early wins if you die young; waiting wins if you live long.</p>${ssChart(s.pia,s.infl,null)}<p class="tip">Claiming at 62 cuts your check 30% for life. Each year you wait past 67 adds 8%, up to 70.</p></div>`:''}
<div class="stepper"><div class="pbar"><i id="pbar"></i></div><div class="chips" id="chips">${core.map((qi,k)=>`<button type="button" class="chip" data-i="${k}">${SHORT[qs[qi].id]||'Question'}</button>`).join('')}${adv.length?`<button type="button" class="chip opt-chip" data-i="${core.length}">More (optional)</button>`:''}<button type="button" class="chip" data-i="${nSteps}">Review</button></div>
<div class="modebar"><span>${simple?`Simple mode: ${core.length} key choice${core.length===1?'':'s'}${adv.length?`, with ${adv.length} more set to smart defaults`:''}.`:'Showing every choice.'}</span><button type="button" class="linkbtn" id="modeToggle">${simple?'Show every choice':'Switch to simple mode'}</button></div></div>
<div class="steps">
${adv.length?`<div class="qstep advhead" data-i="${core.length}"><h3>More choices (optional)</h3><p class="muted">These are already set to sensible defaults, so you can skip straight to Review. Change any of them if you want more control.</p></div>`:''}
${qs.map((q,qi)=>`<div class="qstep" data-i="${stepOf[qi]}"><fieldset class="q"><legend><span class="qn">${simple&&isAdv(q,st.key)?'•':stepOf[qi]+1}</span>${q.q}</legend>${q.help?`<p class="muted" style="font-size:var(--fs-sm)">${q.help}</p>`:''}${q.suggest?`<p class="rsuggest">${ic('flag')}<span>${q.suggest}</span></p>`:''}${q.learn?`<details class="more qlearn"><summary>${q.id==='ins'?'How life insurance works':q.id==='risk'?'What\'s my risk tolerance? Take the quiz':q.id==='acct'?'How a Roth IRA works':'What\'s the difference?'}</summary>${q.learn}</details>`:''}
${q.type==='money'?moneyQ(q):''}
${q.options?`<div class="opts">${q.options.map(o=>`<label class="opt ${o.off?'off':''}"><input type="radio" name="q-${q.id}" value="${o.v}" ${o.off?'disabled':''} ${String(o.v)===String(q.def)?'checked':''}><b>${o.label}${o.tag?` <span class="otag${o.tag.startsWith('Also')?' alt':''}">${o.tag}</span>`:''}</b><span class="hint">${o.off?o.why:o.hint}</span>${o.extra||''}</label>`).join('')}</div>`:''}
${q.custom?`<div class="custom fields" id="customJob" hidden>
<div class="field"><label for="cj-title">Your job</label><div class="inp"><input id="cj-title" maxlength="40" placeholder="e.g. Physical therapist" style="font-family:var(--body)"></div></div>
<div class="field"><label for="cj-salary">Expected starting salary</label><div class="inp"><span>$</span><input id="cj-salary" inputmode="decimal" value="55000"></div><small>In today's dollars, per year</small></div>
<div class="field"><label for="cj-style">How pay grows in your field</label><div class="inp"><select id="cj-style" style="flex:1;border:0;background:transparent;color:var(--ink);font:500 var(--fs-base) var(--body);padding:10px 4px">${Object.entries(PAY_STYLE).map(([k,l])=>`<option value="${k}" ${k==='average'?'selected':''}>${l}</option>`).join('')}</select></div></div>
</div>`:''}
${q.extra||''}
<div class="explain" id="ex-${q.id}"></div></fieldset></div>`).join('')}
<div class="qstep" data-i="${nSteps}"><div class="stack"><h3>Review your choices</h3><div id="gate" class="gate" hidden></div><div class="picks" id="review"></div>
${st.key==='college'||st.key==='retire'?'':`<div class="stack" id="preview"></div>`}
<p class="note">${ic('flag')}<span>Choose carefully. After these years you'll see what each choice was worth.</span></p></div></div>
</div>
</section>
${st.key==='college'?`<div class="btns"><button class="btn ghost" id="skipCollege">Already graduated? Skip college</button></div>`:''}
<div class="actionbar"><button class="btn ghost" id="backq" type="button">Back</button><span class="stepcount" id="stepcount"></span><button class="btn" id="nextq" type="button">Next ${ic('arrow')}</button><button class="btn" id="live" type="button" hidden>${st.key==='retire2'?'Live out your later years':`Live ages ${Math.round(s.age)} to ${to}`} ${ic('arrow')}</button></div>`;
const upd=()=>{
const ch=currentChoices(qs);let b=null;const cj=$('customJob');if(cj)cj.hidden=ch.career!=='custom';
const ib=$('insBox');if(ib){ib.hidden=ch.ins!=='term';insBoxUpd(s,ch)}
if(qs.some(q=>q.type==='money')&&st.key!=='retire'){const c=structuredClone({...s,history:[],schedule:[],stageEvents:[]});c.flat=true;const c2={...ch};delete c2.life;c.lifestyle=null;applyDecisions(c,st.key,c2);if(st.key==='build')c.salary=s.salary;const typ=suggestLife(c);
$('typ-life').textContent=`Typical for your income: ${money(typ*s.infl,s.infl)} a year`;G.typLife=typ;
if(G.lifeMode==='typical'){const dv=Math.round(typ*lifeMult());$('nm-life').value=dv;$('rg-life').value=dv;ch.life=typ}
ch.lifeCustom=G.lifeMode==='custom';
$('rs-life').textContent=G.lifeMode==='custom'?'Use typical':'Following typical';
}
if(st.key!=='college'&&st.key!=='retire'){const c=structuredClone({...s,history:[],schedule:[],stageEvents:[]});c.flat=true;c.noIncome=0;applyDecisions(c,st.key,ch);if(c.graceUntil>c.month)c.month=c.graceUntil;b=step(c);$('preview').innerHTML=previewHTML(b,c)}
G.lastB=b;
for(const q of qs){const [does,cost]=explain(s,q.id,ch[q.id],ch,b),ex=$('ex-'+q.id),was=ex.querySelector('details'),op=was?was.open:false;
ex.innerHTML=does?`<details class="more exmore"${op?' open':''}><summary>What this choice does</summary><div class="exbody"><div><span class="eyebrow">What this does</span>${does}</div><div class="cost"><span class="eyebrow">The tradeoff</span>${cost}</div></div></details>`:''}
};
el.querySelectorAll('input[type=radio]').forEach(i=>i.addEventListener('change',upd));
el.querySelectorAll('.rquiz input').forEach(i=>i.addEventListener('change',riskQuiz));
{const cq=el.querySelector('input[name="q-care"]'),kq=el.querySelectorAll('input[name="q-kids"]');if(cq&&kq.length&&!G.s.kids.some(b=>b+60>G.s.month)){const fs=cq.closest('.qstep');const sync=()=>{const k=el.querySelector('input[name="q-kids"]:checked');fs.classList.toggle('carehide',!(k&&+k.value>0))};kq.forEach(i=>i.addEventListener('change',sync));sync()}}
el.querySelectorAll('#customJob input,#customJob select,#insBox input').forEach(i=>i.addEventListener('input',upd));
for(const q of qs.filter(q=>q.type==='money')){const rg=$('rg-'+q.id),nm=$('nm-'+q.id);
rg.addEventListener('input',()=>{nm.value=rg.value;G.lifeMode='custom';upd()});
nm.addEventListener('input',()=>{const v=parseFloat(nm.value);if(isFinite(v))rg.value=v;G.lifeMode='custom';upd()});
$('rs-'+q.id).onclick=()=>{G.lifeMode='typical';upd()}}
G.lifeMode=(s.lifeCustom||G.pendLifeCustom)?'custom':'typical';G.pendLifeCustom=false;upd();
if($('skipCollege'))$('skipCollege').onclick=()=>{G.inp.status='grad';G.inp.age=Math.max(21,G.inp.age);startRun(G.seed)};
const n=nSteps;let cur=0;
const show=(i,scroll)=>{cur=Math.max(0,Math.min(n,i));
el.querySelectorAll('.qstep').forEach(d=>{const on=+d.dataset.i===cur;d.hidden=!on;if(on){d.classList.remove('enter');void d.offsetWidth;d.classList.add('enter')}});
el.querySelectorAll('.chip').forEach(c=>{const k=+c.dataset.i;c.classList.toggle('on',k===cur);c.classList.toggle('seen',k<cur)});
$('pbar').style.width=(cur/n*100)+'%';$('stepcount').textContent=cur<n?`${cur+1} of ${n}`:'Ready';
$('backq').disabled=cur===0&&!prevSnap;$('backq').textContent=cur===0&&prevSnap?'← Last stage':'Back';$('nextq').hidden=cur===n;$('live').hidden=cur!==n;
if(cur===n){const ch=currentChoices(qs),f=s.infl,g=gateInfo(s,st,ch,qs);const gb=$('gate');gb.hidden=!g.msg;gb.className=g.block?'gate':'gate warnonly';
if(g.msg){gb.innerHTML=`<div class="alert" style="background:none;padding:0">${ic('bolt')}<span>${g.msg}</span></div>${g.block?`<div class="btns"><button type="button" class="btn" id="autoFix">Balance it for me</button></div><p class="muted" style="font-size:var(--fs-sm);margin:0">Or change something yourself:</p>`:''}${g.fix.length?`<div class="btns">${g.fix.map(x=>`<button type="button" class="btn ghost" data-go="${x.i}">${x.l}</button>`).join('')}</div>`:''}`;
const af=$('autoFix');if(af)af.onclick=()=>{const before=currentChoices(qs),fx=balanceFix(s,st,before,qs),chg=[];
for(const q of qs){const k=q.id;if(fx[k]===undefined)continue;
if(q.type==='money'){if(fx.lifeCustom&&Math.abs((fx.life||0)-(before.life||0))>1){const nm=$('nm-'+k);nm.value=String(Math.round(fx.life*lifeMult()));nm.dispatchEvent(new Event('input',{bubbles:true}));chg.push([q,before,{...before,life:fx.life,lifeCustom:true}])}continue}
if(String(fx[k])!==String(before[k])){const i=document.querySelector(`input[name="q-${k}"][value="${fx[k]}"]`);if(i&&!i.disabled){i.checked=true;i.dispatchEvent(new Event('change',{bubbles:true}));chg.push([q,before,fx])}}}
G.autoNote=chg.length?`To balance your budget, we changed: ${chg.map(([q,b,a])=>`<b>${SHORT[q.id]||q.q}</b> from ${pickLabel(q,b,s.infl)} to ${pickLabel(q,a,s.infl)}`).join('; ')}. You can change it back on any step.`:'';show(cur,false)};gb.querySelectorAll('[data-go]').forEach(x=>x.onclick=()=>show(stepOf[+x.dataset.go],true))}
if(G.autoNote&&!g.block){gb.hidden=false;gb.className='gate warnonly';gb.innerHTML=`<div class="okay">${ic('flag')}<span>${G.autoNote}</span></div>`;G.autoNote=''}
$('live').disabled=!!g.block;$('live').title=g.block?'Fix your budget first':'';$('review').innerHTML=[...core,...adv].map(i=>{const q=qs[i];return `<button type="button" class="pick pick-b${simple&&isAdv(q,st.key)?' pick-adv':''}" data-i="${i}"><span>${q.q}</span><b>${pickLabel(q,ch,f)}</b><em>Change</em></button>`}).join('');
$('review').querySelectorAll('.pick-b').forEach(b=>b.onclick=()=>show(stepOf[+b.dataset.i],true))}
const ac=el.querySelector('.chip.on');if(ac&&ac.scrollIntoView)try{ac.parentElement.scrollLeft=ac.offsetLeft-40}catch(e){}
if(scroll){const t=$('turn');if(t)t.scrollIntoView({behavior:matchMedia('(prefers-reduced-motion: reduce)').matches?'auto':'smooth',block:'start'})}};
el.querySelectorAll('.chip').forEach(c=>c.onclick=()=>show(+c.dataset.i,true));
$('nextq').onclick=()=>show(cur+1,true);$('backq').onclick=()=>{if(cur===0&&prevSnap)goBackTo(prevSnap.from);else show(cur-1,true)};
const sn=$('snap');if(sn)sn.querySelector('summary').addEventListener('click',()=>{G.snapOpen=!sn.open});
show(0,false);
$('live').onclick=()=>goLive(qs,st,currentChoices(qs));
if($('prevStage'))$('prevStage').onclick=()=>goBackTo(prevSnap.from);
$('modeToggle').onclick=()=>{G.pend=currentChoices(qs);G.simple=!G.simple;try{localStorage.setItem('lg-simple',G.simple?'1':'0')}catch(e){}render()};
}
const SHORT={care:'Childcare',retireAge:'Retirement',risk:'Risk',move:'Move',career:'Job',city:'City',rent:'Rent',kids:'Kids',car:'Car',exercise:'Health',smoke:'Smoking',life:'Spending',health:'Health plan',fund:'Funds',k401:'401(k)',save:'Saving',acct:'Roth split',family:'Family',ins:'Insurance',order:'Priorities',quit:'Quit smoking',home:'Home',college:'Kids\' college',crash:'Crash',ss:'Social Security',spend:'Lifestyle',card:'Credit card',cover:'Paying for school'};
function scanTurn(s,st,ch){const c=structuredClone({...s,history:[],schedule:[],stageEvents:[],story:[]});c.flat=true;c.noIncome=0;
applyDecisions(c,st.key,ch);c.risk='growth';const n=Math.max(1,Math.round((st.to-c.age)*12)),k0=kidsUnder18(c),b0=c.broke;let worst=Infinity,age=c.age,kids=false,first=null;
for(let i=0;i<n;i++){const a=c.age,b=step(c);if(first==null)first=b.left;if(c.retired){if(b0==null&&c.broke!=null)return {worst:-1e9,age:c.broke,broke:c.broke,kids:false};continue}
if(b.left<worst-0.01){worst=b.left;age=a;kids=kidsUnder18(c)>k0}}
return {worst:c.retired?0:worst,first:c.retired?0:first,age,kids,broke:null}}
function scanScore(r){return r.broke!=null?r.broke-1e6:r.worst}
const autoOK=(id,o)=>!(id==='rent'&&o.v==='home');
function bestFix(s,st,ch,qs){const c2={...ch};if(qs.some(q=>q.id==='life')){c2.life=6000;c2.lifeCustom=true}let best=scanTurn(s,st,c2);
for(const q of qs){const opts=(q.options||[]).filter(o=>!o.off&&(autoOK(q.id,o)||String(o.v)===String(c2[q.id])));if(opts.length<2||q.id==='risk')continue;let bv=c2[q.id];
for(const o of opts){if(String(o.v)===String(c2[q.id]))continue;const r=scanTurn(s,st,{...c2,[q.id]:o.v});if(scanScore(r)>scanScore(best)+0.01){best=r;bv=o.v}}
c2[q.id]=bv}
best.ch=c2;return best}
function gateInfo(s,st,ch,qs){const idx=id=>qs.findIndex(q=>q.id===id),fx=[];const add=(id,l)=>{const i=idx(id);if(i>=0)fx.push({i,l})};
const ok={block:false,msg:'',fix:[]};
if((st.key==='retire'||st.key==='retire2')&&s.broke!=null)return ok;
const r=scanTurn(s,st,ch);if(r.broke==null&&r.worst>=-1)return ok;
const fixed=bestFix(s,st,ch,qs),can=fixed.broke==null&&fixed.worst>=-1;
if(st.key==='retire'||st.key==='retire2'){
if(!can)return {block:false,msg:`Even at the lowest spending level here, your savings run out around age <strong>${Math.floor(fixed.broke!=null?fixed.broke:r.broke)}</strong>. After that you'll live on Social Security alone. Spending less still makes your money last longer.`,fix:[]};
add('spend','Spend less in retirement');add('ss','Social Security timing');
return {block:true,msg:`At this spending level, your savings would run out around age <strong>${Math.floor(r.broke)}</strong> and you couldn't cover your bills. Pick a plan your savings can support before moving on.`,fix:fx}}
const later=r.first>=-1&&r.age-s.age>=0.5,gap=money(later?-r.worst:-r.first,s.infl),when=later?`Around age <strong>${Math.floor(r.age)}</strong>${r.kids?', once your baby arrives,':','} your`:'Your';
if(st.key==='college'){add('cover','Change how you pay for school');add('card','Credit card');
if(!can)return {block:false,msg:`${when} spending runs about <strong>${gap} a month more</strong> than you bring in, even with the options here. The gap will come out of savings, then go on your credit card.`,fix:[]};
return {block:true,msg:`${when} spending runs <strong>${gap} a month more</strong> than you bring in. Cover every bill before moving on: work more, borrow, or spend less.`,fix:fx}}
add('life','Lower your spending');add('rent','Cheaper rent');add('home','Housing choice');add('move','Stay or move');add('car','Car choice');add('kids','Number of kids');add('family','Family');add('k401','401(k) amount');add('ins','Insurance');add('health','Health plan');add('college','Kids\' college');
if(!can)return {block:false,msg:`${when} bills run about <strong>${gap} a month more</strong> than your take-home pay, even with the cheapest choices here. The gap will come out of savings, then go on your credit card.`,fix:[]};
return {block:true,msg:`You can't afford this plan. ${when} bills and spending ${later?'will run':'are'} <strong>${gap} a month more</strong> than your take-home pay. Change something below so every expense is covered before you move on.`,fix:fx}}
function pickLabel(q,ch,f){const v=ch[q.id];if(v===undefined)return '';
if(q.type==='money')return `${money(v*f,f)} a year${ch.lifeCustom?'':' (typical for your income)'}`;
if(q.id==='ins'&&v==='term')return `${ch.insYears||20}-year term, ${money((ch.insFace||500000)*f,f)}`;
if(q.id==='career'&&v==='custom')return `${esc(ch.customTitle||'My job')}, starting at ${money((ch.customSalary||0)*f,f)}`;
const o=(q.options||[]).find(o=>String(o.v)===String(v));return o?o.label:String(v)}
function turnHTML(t){const ch=real?t.nw1/t.f1-t.nw0/t.f0:t.nw1-t.nw0;
return `<div class="tv-head"><div><span class="eyebrow">${esc(t.name)}</span><h2>Ages ${Math.round(t.from)} to ${Math.round(t.to)}</h2></div><button class="btn ghost" id="tvClose" type="button" aria-label="Close">Close</button></div>
<div class="delta"><div><span class="eyebrow">Net worth going in</span><div class="big" style="font-size:var(--fs-lg)">${money(t.nw0,t.f0)}</div></div><div><span class="eyebrow">Coming out</span><div class="big" style="font-size:var(--fs-lg)">${money(t.nw1,t.f1)}</div></div><div><span class="eyebrow">Change</span><div class="big ${ch<0?'neg':'pos'}" style="font-size:var(--fs-lg)">${ch>=0?'+':'−'}${money(Math.abs(ch),0)}</div></div></div>
<div class="stack" style="gap:6px"><span class="eyebrow">Your decisions</span>${t.picks.length?`<div class="picks">${t.picks.map(p=>`<div class="pick"><span>${p.q}</span><b>${p.a}</b></div>`).join('')}</div>`:'<p class="muted">No decisions this turn.</p>'}</div>
${t.events.length?`<div class="stack" style="gap:6px"><span class="eyebrow">What happened</span><ul class="tv-ev">${t.events.map(e=>`<li class="${e.good?'pos':'neg'}">${e.t}</li>`).join('')}</ul></div>`:''}
${t.lesson?`<div class="tip">${t.lesson}</div>`:''}`}
function openTurn(from){const t=(G.turns||[]).find(x=>Math.abs(x.from-from)<.01);if(!t)return;const v=$('turnView');
const later=(G.turns||[]).filter(x=>x.from>from+.01).length;
v.querySelector('.tv-card').innerHTML=turnHTML(t)+(canGoBack(from)?`<div class="tv-back"><button type="button" class="btn" id="tvBack">Go back and change these choices</button><span class="muted" id="tvBackNote">${later?`You'll replay ages ${Math.round(from)} onward with the same luck. The ${later} stage${later>1?'s':''} after it will be cleared.`:'You will replay these years with the same luck.'}</span></div>`:'');
v.hidden=false;$('tvClose').onclick=closeTurn;$('tvClose').focus();
const b=$('tvBack');if(b){let armed=false;b.onclick=()=>{if(later&&!armed){armed=true;b.textContent=`Tap again to go back to age ${Math.round(from)}`;b.classList.add('warn');setTimeout(()=>{armed=false;if(b.isConnected){b.textContent='Go back and change these choices';b.classList.remove('warn')}},5000);return}goBackTo(from)}}}
function closeTurn(){$('turnView').hidden=true}
function canGoBack(from){return !G.auto&&(G.snaps||[]).some(x=>Math.abs(x.from-from)<.01)}
function goBackTo(from){const L=G.snaps||[],i=L.findIndex(x=>Math.abs(x.from-from)<.01);if(i<0)return false;const e=L[i];
closeTurn();restoreG(JSON.parse(e.snap));G.snaps=L.slice(0,i);G.pend=e.ch;G.undo=null;G.phase='decide';G.fast=false;render();window.scrollTo({top:0,behavior:matchMedia('(prefers-reduced-motion: reduce)').matches?'auto':'smooth'});return true}
function doLive(qs,st,ch){
const s=G.s;let alt=null;
G.undo=snapG();(G.snaps=G.snaps||[]).push({key:st.key,from:st.from,to:st.to,name:st.name,snap:G.undo,ch:{...ch}});
for(const q of qs){const opts=(q.options||[]).filter(o=>!o.off);if(opts.length<2||q.id==='risk')continue;
G.log.push({turn:(G.turns||[]).length,id:q.id,stage:`Ages ${Math.round(st.from)}–${Math.round(st.to)}`,age:Math.round(s.age),q:q.q,chosen:String(ch[q.id]),opts:opts.map(o=>{const p=project(s,st,{...ch,[q.id]:o.v});return {v:String(o.v),label:o.label,nw:p.nw,f:p.f,nw65:p.nw65,f65:p.f65}})})}
if(st.key==='mid'){const c=structuredClone({...s,history:[],stageEvents:[]});applyDecisions(c,'mid',{...ch,crash:ch.crash==='stay'?'sell':'stay'});runStage(c,st);alt=netWorth(c)}
const f0=s.infl,picks=qs.map(q=>({q:q.q,a:pickLabel(q,ch,f0)})).filter(x=>x.a),cred0=structuredClone(s.credit);
applyDecisions(s,st.key,ch);st.to=stageTo(s,st);G.result=runStage(s,st);G.result.choices=ch;G.result.alt=alt;G.result.last=s.retired&&s.age>=deathAge(s)-1e-6;
(G.turns=G.turns||[]).push({from:st.from,to:s.age,name:st.name,icon:st.icon,picks,nw0:G.result.nw0,f0,nw1:G.result.nw1,f1:s.infl,
events:G.result.events.map(e=>({t:e.life?e.title:e.c.title,good:e.life?(e.kind==='star'||e.kind==='good'):(e.c.cost<0||e.c.raise>0||(e.gamble&&e.gamble.win))})),lesson:(lessonsFor(G.result,s)[0]||'')});
twinize(G.twin,st.key,ch,s,cred0);runStage(G.twin,st);G.twin.credit=structuredClone(s.credit);
G.phase='result';render();if(!G.fast)window.scrollTo({top:0,behavior:'smooth'});
}
function previewHTML(b,s){
const f=s.infl,line=(l,v,cls='')=>`<span>${l}</span><span class="money ${cls}">${money(v,f)}</span>`;
if(s.retired){const fromSav=Math.max(0,-b.left);return `<span class="eyebrow">A typical month in retirement</span>
<div class="ledger">${line(s.age<s.ssClaim?`Social Security (starts at ${s.ssClaim})`:'Social Security after taxes',b.income)}${line(s.kids.length?'Housing, car, kids and everyday costs':'Housing, car and everyday costs',-b.needs,'neg')}${b.debt?line('Loan and card payments',-b.debt,'neg'):''}
<span class="total">${fromSav>0?'Taken from your savings':'Left over'}</span><span class="money total">${money(fromSav>0?fromSav:b.left,f)}</span></div>
<p class="muted" style="font-size:var(--fs-sm);margin:0">${fromSav>0?'In retirement, your savings fill the gap between Social Security and what you spend. That\'s what they\'re for. The question is whether they last.':'Social Security covers everything, so your savings can keep growing.'}</p>`}
return `<span class="eyebrow">A typical month with these choices${b.debt>0?', once loan payments start':''}</span>
${b.income>0?donut([{k:'tax',v:b.tax},{k:'k401',v:b.k401},{k:'bills',v:b.needs},{k:'debt',v:b.debt},{k:'saved',v:b.saved},{k:'fun',v:b.fun}],f,money(b.tax+b.k401+b.income,f,{short:true}),'pay a month'):''}
<div class="ledger">${line(s.partner?'Household take-home pay after taxes and 401(k)':'Take-home pay after taxes and 401(k)',b.income)}${b.k401?line('Into your 401(k), plus employer match',b.k401+b.match,'pos'):''}
${line(s.kids.length?'Housing, car, kids and everyday costs':'Housing, car and everyday costs',-b.needs,'neg')}${b.debt?line('Loan and card payments',-b.debt,'neg'):''}
<span class="total">Left over</span><span class="money total ${b.left<0?'neg':''}">${money(b.left,f)}</span>
${b.left>0?`<span class="muted">You save ${pct(s.savePct)} of that</span><span class="money pos">${money(b.saved,f)}</span>`:''}</div>
${b.trim>1&&b.left<1?`<p class="muted" style="font-size:var(--fs-sm);margin:0">Your choices cost more than your paycheck, so your everyday spending is cut by about ${money(b.trim,f)} a month below what's typical for your income, and nothing is left to save.</p>`:''}
${b.left<0&&!s.retired?`<div class="alert">${ic('bolt')}<span>Your bills are bigger than your paycheck. The gap comes out of savings, then goes on your credit card.</span></div>`:''}`;
}
function lessonsFor(r,s){
const f=s.infl,d=r.d,c=r.choices,L=[];
if(r.key==='college'){
if(d.studentInterest>1)L.push(`Your student loans grew by <strong>${money(d.studentInterest,f)}</strong> from interest while you were in school. With unsubsidized loans, interest starts the day you borrow.`);
if(c.card==='min'&&d.cardInterest>1)L.push(`You paid <strong>${money(d.cardInterest,f)}</strong> in credit card interest. At ${pct(s.card.rate)} APR, every $100 carried for a year costs about $${Math.round(s.card.rate*100)}.`);
if(c.card==='pay')L.push(`Paying off the card was a guaranteed ${pct(s.card.rate)} return. No investment reliably pays that.`);
if(c.cover==='borrow')L.push(`Borrowing more added <strong>${money(d.extraBorrowed,f)}</strong> to your loans, and it all collects interest right away.`);
if(c.cover==='work')L.push(`The extra hours brought in <strong>${money(d.extraEarned,f)}</strong>. The real cost was time.`);
if(c.cover==='cut')L.push(`Spending $200 less a month kept about <strong>${money(200*r.months,f)}</strong> in your pocket.`);
if(s.roth>0)L.push(`Money beyond your $1,000 starter cushion went into a <strong>Roth IRA</strong>. Students with a job can open one, and decades of tax-free growth make early dollars especially powerful.`);
}
if(c.rent==='home'&&r.months>0){const ct=CITIES[s.city]||{rent:1},sv=(RENTS.room.rent-RENTS.home.rent)*(ct.rent||1)*r.months;L.unshift(`Living at home saved you about <strong>${money(sv,f)}</strong> compared with splitting a place with roommates. That head start is worth the most when it goes to debt and savings.`)}
if(r.key==='first'){
L.push(s.kPct>=C.MATCH?`Your employer added <strong>${money(d.match,f)}</strong> of free money through the 401(k) match, an instant 100% return.`:`You left about <strong>${money(s.salary*C.MATCH*r.months/12*0.93,f)}</strong> of free match money on the table. Contributing enough to get the full match is one of the easiest wins in personal finance.`);
if(d.rothIn>1)L.push(`You put <strong>${money(d.rothIn,f)}</strong> into your Roth IRA. Every dollar of its future growth comes out tax-free.${d.rothOverflow>1?` You hit the yearly limit, so ${money(d.rothOverflow,f)} went to your brokerage account.`:''}`);
if(s.carPlan!=='keep')L.push(`Your car lost <strong>${money(r.car0-s.carValue,f)}</strong> in value and you paid ${money(d.carInterest,f)} in loan interest.`);
{const sal=s.salary,k=sal*s.kPct,t=taxes(sal,k,f,s.localRate),taxable=Math.max(0,sal-k-C.FED_SD*f);const top=C.BRK.find(([cap])=>taxable<=cap*f)[1];
L.push(`Your top federal tax bracket is <strong>${Math.round(top*100)}%</strong>, but federal income tax takes only about <strong>${Math.round(t.fed/sal*100)}%</strong> of your pay. Each bracket applies only to the dollars inside it, so a raise can never lower your take-home pay.`)}
L.push(`${CITIES[s.city].label==='A smaller Kentucky town'?'Your county':CITIES[s.city].label}'s payroll tax took <strong>${money(d.local,f)}</strong> of your pay. Most people never hear about local payroll taxes until their first paycheck.`);
}
if(r.key==='build'){
const T={smart:'Your savings filled an emergency fund, cleared credit card debt, then got invested.',invest:'All savings went straight to investing. Any surprise landed on your credit card instead of a cushion.',cash:'Your savings sat in a savings account earning about 3.5% while prices rose 3%, so they barely grew after inflation.',debt:'You paid off loans before investing. Debt-free feels great; just know the growth you gave up.'};
L.push(T[s.order]);
const RT=realTot(s),put=RT.match+RT.contrib+RT.rothIn+RT.brokIn,inv=invested(s);
const st0=(G.inp.k401Bal||0)+(G.inp.iraBal||0)+(G.inp.rothBal||0)+(G.inp.invest||0);if(inv>0&&put>=1)L.push(`${st0>=1?`You started with <strong>${money(st0)}</strong> invested, and you and your employer have put in about <strong>${money(put,f)}</strong> more. Together they're`:`You and your employer have put about <strong>${money(put,f)}</strong> into investments, and they're`} now worth <strong>${money(inv,f)}</strong>. The difference is compounding, and it widens every year.`);
if(s.ins.type==='term')L.push(`Your ${s.ins.years||20}-year term policy costs about <strong>${money(s.ins.prem*f)}</strong> a month and protects your family with ${money(s.ins.face,f)} until age ${Math.round(s.ins.startAge+(s.ins.years||20))}.`);
if(s.ins.type==='whole')L.push(`Your whole life policy costs about <strong>${money(s.ins.prem*f)}</strong> a month. Its cash value is ${money(s.ins.cv,f)} so far, much less than you've paid in. That gap is the price of lifelong coverage.`);
if(s.ins.type==='none'&&s.partner)L.push('You have a partner but no life insurance. If you had died, they would have lost your income with no replacement. Term life is usually the cheapest way to cover that risk.');
if(s.kids.length)L.push(`${d.kidCost>1?`Raising kids cost about <strong>${money(d.kidCost,f)}</strong> over these years. `:''}Your family now: ${kidAgesText(s)}.${d.kidCost>1?' It\'s normal for savings to slow down while children are small.':''}`);
L.push(`You spent <strong>${money(d.fun,f)}</strong> on fun over these ${Math.round(r.months/12)} years. Spending isn't bad. Choosing it on purpose is the skill.`);
}
if(c.move&&c.move!=='stay'&&s.lastMove){const m=s.lastMove,fm=m.f||f;L.push(m.kind==='rent'?`You sold your home for ${money(m.sale.gross,fm)} and paid <strong>${money(m.sale.cost,fm)}</strong> in selling costs. About ${money(m.sale.net,fm)} went into your savings, and you went back to renting.`:`You sold your home for ${money(m.sale.gross,fm)}, paid <strong>${money(m.sale.cost,fm)}</strong> in selling costs and rolled your equity into a ${money(m.to,fm)} home. It's now worth <strong>${money(s.home,f)}</strong> and you owe ${money(s.mortgage.bal,f)}.`)}
if(c.home&&r.key!=='first'){
if(c.home==='rent'&&r.key==='check'&&s.age<36)L.push('Renting kept your money flexible. Renting isn\'t throwing money away when the down payment you didn\'t make stays invested.');
else if(!(s.home>0)){if(c.home==='rent')L.push(`You kept renting, now about <strong>${money(s.rent*f,f)} a month</strong>. Rent rises with prices, but money you didn't put into a house can stay invested.`)}
else{L.push(`Your home is worth <strong>${money(s.home,f)}</strong> and you owe ${money(s.mortgage.bal,f)}: <strong>${money(s.home-s.mortgage.bal,f)}</strong> in home equity. You paid ${money(d.mortgageInterest,f)} in mortgage interest and ${money(d.homeCosts,f)} in taxes, insurance and upkeep.`);
if(s.homeBuy&&s.homeBuy.brokTax+s.homeBuy.kCost>1)L.push(`Pulling the down payment from investments cost <strong>${money(s.homeBuy.brokTax+s.homeBuy.kCost,f)}</strong> in taxes and penalties. A separate house fund avoids that.`.replace(money(s.homeBuy.brokTax+s.homeBuy.kCost,f),money(s.homeBuy.brokTax+s.homeBuy.kCost,s.homeBuy.f||f)))}
if(s.k529>0)L.push(`Your kids' 529 holds <strong>${money(s.k529,f)}</strong>, growing tax-free for college.`);
}
if(r.key==='mid'){
L.push(c.crash==='stay'?`You stayed invested and rode the rebound. If you had sold, your net worth today would be about <strong>${money(r.nw1-r.alt,f)} lower</strong>.`:`Selling locked in the loss, and your money sat in cash during the rebound. Staying invested would have left you about <strong>${money(r.alt-r.nw1,f)} richer</strong>. Investors who sell in a crash usually miss the recovery.`);
L.push('This game assumes a strong 3-year rebound after the drop. Real recoveries have taken different amounts of time.');
}
if(r.key==='retire'||r.key==='retire2')L.push(s.broke!=null?`Your savings have run out. You're living on Social Security alone.`:`You spent about ${money(s.spendStyle*s.retireSpend*s.infl/s.infl65,f)} a month and your savings stand at ${money(liquidAfterTax(s),f)} after taxes.`);
if(r.last){const d=deathAge(s);
L.push(s.broke!=null?`Your savings ran out at <strong>${Math.floor(s.broke)}</strong>. You lived your last ${Math.round(d-s.broke)} years on Social Security alone, about ${money(s.ssMonthly*s.infl/s.infl65,f)} a month. Outliving your money is the biggest risk in retirement.`:`Your money lasted your whole life. You left <strong>${money(r.nw1,f)}</strong> behind.`);
const cmp=ssCompare(s.pia,d),best=cmp.filter(x=>x.age>=(s.retireAt||65)).sort((a,b)=>b.total-a.total)[0],mine=cmp.find(x=>x.age===s.ssClaim);
L.push(best.age===s.ssClaim?`Claiming Social Security at ${s.ssClaim} paid you the most for the life you lived: about <strong>${money(mine.total,s.infl65)}</strong> ${ssUnit()}.`:`Living to ${d}, claiming at ${best.age} would have paid about <strong>${money(best.total-mine.total,s.infl65)}</strong> more over your life than claiming at ${s.ssClaim} (${ssUnit()}).`);
if((s.totals.kyExcl||0)>1)L.push(`Kentucky doesn't tax the first $31,110 a year of retirement-account withdrawals${s.partner?' for each of you':''}, or Social Security at all. That saved you about <strong>${money(s.totals.kyExcl,f)}</strong> in state tax.`);
L.push('Kentucky has no estate tax, and its inheritance tax does not apply to spouses, children, parents, siblings or grandchildren. Retirement accounts go straight to the beneficiaries you name, so a will and up-to-date beneficiary forms decide who gets what.');
}
if(r.key==='check'&&s.age>=60)L.push('In these last working years your investments grow far more from compounding than from new contributions. The money you invested in your 20s does the most work.');
if(r.key==='check'&&s.age<60){const inv=invested(s),RT=realTot(s),put=RT.match+RT.contrib+RT.rothIn+RT.brokIn;const st0=(G.inp.k401Bal||0)+(G.inp.iraBal||0)+(G.inp.rothBal||0)+(G.inp.invest||0);if(inv>0&&put>=1)L.push(`${st0>=1?`You started with <strong>${money(st0)}</strong> invested, and you and your employer have put in about <strong>${money(put,f)}</strong> more. Together they're`:`You and your employer have put about <strong>${money(put,f)}</strong> into investments, and they're`} now worth <strong>${money(inv,f)}</strong>. The difference is compounding.`);L.push(`You spent <strong>${money(d.fun,f)}</strong> on fun over these ${Math.round(r.months/12)} years.`)}
if(r.key!=='college'&&r.credit0!=null){const c0=r.credit0,c1=s.credit.score,dc=c1-c0;if(Math.abs(dc)>=10)L.push(dc>0?`Your credit score rose from ${Math.round(c0)} to <strong>${Math.round(c1)}</strong> (${creditLabel(c1).toLowerCase()}). On-time payments, low card balances and a longer history did that, and it means lower rates on your next car or mortgage.`:`Your credit score fell from ${Math.round(c0)} to <strong>${Math.round(c1)}</strong>. High card balances and maxed-out cards drag it down, and lenders will now charge you more to borrow.`)}
if(r.key==='first'&&s.fee>=.01)L.push(`Your advisor-managed account charged <strong>${money(d.fees,f)}</strong> in fees these years. Small now, but it grows with your balance.`);
if(r.key==='first'&&s.hsaPlan!=='none')L.push(`Your HSA holds <strong>${money(s.hsa,f)}</strong>. Every dollar went in before taxes and can come out tax-free for health costs, now or in retirement.`);
if(r.raises&&r.raises.length){const a=r.raises,avg=a.reduce((x,y)=>x+y,0)/a.length;L.push(`Your raises averaged <strong>${pct(avg)}</strong> a year, ranging from ${pct(Math.min(...a))} to ${pct(Math.max(...a))}. About 3% of that just kept up with rising prices. ${payOf(s).desc}`)}
const t=G.twin;if(t&&r.key!=='college'&&!r.key.startsWith('retire')){const gap=netWorth(s)-netWorth(t);L.push(Math.abs(gap)<100*f?'You and your twin are even, because almost nothing you have is invested yet. Investing is the only difference between you.':gap>0?`Your twin made every choice you did but never invested. Right now you're <strong>${money(gap,f)} ahead</strong> of them, and the gap grows faster every year.`:`Your twin who never invests is currently ${money(-gap,f)} ahead, usually because your investments just took a hit. Over long periods, investing has always pulled ahead.`)}
return L;
}
const firstSent=t=>{t=String(t||'');const m=t.match(/^(.*?[.!?])(\s|$)/);return m?m[1]:t};
function eventCard(ev,s){
const f=ev.f||s.infl;
if(ev.life){const icon={star:'star',bad:'bolt',life:'heart',good:'plus'}[ev.kind]||'heart';
return `<div class="ev ${ev.kind==='bad'?'bad':ev.kind==='star'?'star':ev.kind==='good'?'good':'life'}"><div class="ev-top">${ic(icon)}<div><span class="eyebrow">Age ${Math.floor(ev.age)}${ev.kind==='star'?' · milestone':''}</span><h3>${ev.title}</h3></div></div><p>${ev.body}</p><p class="muted">${firstSent(ev.lesson)}</p></div>`}
const c=ev.c;let body='',cls='bad',icon='bolt';
if(ev.gamble){const g=ev.gamble;cls=g.win?'good':'bad';icon=g.win?'trend':'bolt';body=g.win?`It took off. Your ${money(g.amt,f)} became ${money(g.amt+g.chg,f)}. <strong>Lucky this time</strong>: most bets like this lose.`:`It crashed. You lost <strong>${money(-g.chg,f)}</strong> of your ${money(g.amt,f)}.`}
else if(c.med){const full=ev.full,paid=ev.amt+(ev.fromHSA||0);body=`The bill was ${money(full,f)}. ${ev.medPlan==='ppo'?`Your standard plan covered more, so you paid ${money(paid,f)}`:`On a high-deductible plan you paid ${money(paid,f)}`}${ev.fromHSA>1?(Math.abs(ev.fromHSA-paid)<1?', all of it tax-free from your HSA':`, ${money(ev.fromHSA,f)} of it tax-free from your HSA`):''}${ev.toCard>0.5?`, and <strong>${money(ev.toCard,f)} went on your credit card</strong>`:''}${ev.unpaid>0.5?`. Your card was maxed out, so <strong>${money(ev.unpaid,f)} went unpaid</strong> and hurt your credit score`:''}.`}
else if(c.cost>0)body=ev.unpaid>0.5?`Cost ${money(ev.amt,f)}. You only had ${money(ev.fromCash,f)} in savings${ev.toCard>0.5?` and room for ${money(ev.toCard,f)} on your card`:' and your card was maxed out'}, so <strong>${money(ev.unpaid,f)} went unpaid</strong> and hurt your credit score.`:ev.toCard>0.5?`Cost ${money(ev.amt,f)}. You only had ${money(ev.fromCash,f)} in savings, so <strong>${money(ev.toCard,f)} went on your credit card</strong>.`:`Cost ${money(ev.amt,f)}. <strong>Your savings covered it.</strong>`;
else if(c.cost<0){cls='good';icon='plus';body=`<strong>+${money(ev.amt,f)}</strong> to your savings.`}
else if(c.layoff){const sh=ev.shortAfter-ev.shortBefore;body=`${ev.months} months with no paycheck. ${sh>1?`Bills put up to <strong>${money(sh,f)}</strong> on your credit card.`:'<strong>Your savings carried you.</strong>'}`}
else if(c.raise>0){cls='good';icon='trend';body=`Your salary is now <strong>${money(ev.amt,f)}</strong>.`}
else body=`Your salary drops to <strong>${money(ev.amt,f)}</strong>.`;
if(ev.resp&&!ev.gamble){const r=ev.resp;
if(c.layoff)body+={cut:' You cut spending by about a third while you looked for work.',k401:' You used your 401(k) to pay bills once your savings ran low.'}[r]||'';
else if(c.cost>0&&(r==='card'||r==='k401')){const pre=c.med?body.replace(/, and <strong>.*$/,'.').replace(/\.$/,'.')+' ':`Cost ${money(ev.amt,f)}. `;
body=pre+(r==='card'?`You chose to put <strong>${money(ev.toCard,f)}</strong> on your credit card and keep your savings.`:`You chose to take <strong>${money(ev.k401Gross,f)}</strong> out of your 401(k) and lost <strong>${money(ev.k401Lost,f)}</strong> of it to the penalty and taxes.`)+(ev.fromCash>0.5?` ${money(ev.fromCash,f)} came from savings.`:'')+(r==='k401'&&ev.toCard>0.5?` ${money(ev.toCard,f)} went on your card.`:'')}
else if(c.cost>0&&r==='cut')body+=' Then you cut back for six months to rebuild your savings.'}
return `<div class="ev ${cls}"><div class="ev-top">${ic(icon)}<div><span class="eyebrow">Age ${Math.floor(ev.age)}</span><h3>${c.title}</h3></div></div><p>${body}</p><p class="muted">${firstSent(c.lesson)}</p></div>`;
}
function acctBar(s){const f=s.infl;return stackBar([{l:'Savings',v:s.cash,c:'var(--c-cash)',f},{l:'401(k)',v:s.k401-iraPart(s),c:'var(--c-k401)',f},{l:'Traditional IRA',v:iraPart(s),c:'var(--c-ira)',f},{l:'Roth IRA',v:s.roth,c:'var(--c-roth)',f},{l:'Brokerage',v:s.brok,c:'var(--c-brok)',f},{l:'Kids\' 529',v:s.k529,c:'var(--c-529)',f},{l:'Home equity',v:Math.max(0,s.home-s.mortgage.bal),c:'var(--c-home)',f}])}
function countUp(el){if(!el||matchMedia('(prefers-reduced-motion: reduce)').matches)return;const a=+el.dataset.a,b=+el.dataset.b,f=+el.dataset.f,t0=performance.now(),d=900;
const tick=t=>{const k=Math.min(1,(t-t0)/d),e=1-Math.pow(1-k,3);el.textContent=money(a+(b-a)*e,f);if(k<1)requestAnimationFrame(tick)};requestAnimationFrame(tick)}
function projectAhead(toAge){const r=G.result;if(r.proj!==undefined)return r.proj;
const s=G.s,t=G.twin;if(!t||s.retired||s.age>=toAge-0.5){r.proj=null;return null}
try{const c=structuredClone({...s,schedule:[],stageEvents:[]}),tc=structuredClone({...t,schedule:[],stageEvents:[]});c.flat=true;tc.flat=true;
let nb,g=0;while(c.age<toAge-1e-6&&(nb=nextBlock(c))&&g++<20){enterStage(c,nb.key);enterStage(tc,nb.key);const d={};for(const q of decisions(c,nb.key))if(q.def!==undefined)d[q.id]=q.def;
const cred0=structuredClone(c.credit);applyDecisions(c,nb.key,d);runStage(c,nb);twinize(tc,nb.key,d,c,cred0);runStage(tc,nb);tc.credit=structuredClone(c.credit);if(c.retired)break}
const cut=h=>h.filter(p=>p.age>=s.age-1e-6&&p.age<=toAge+1e-6);r.proj={you:cut(c.history),twin:cut(tc.history)}}catch(e){r.proj=null}
return r.proj}
function gapChartHTML(){const s=G.s,t=G.twin;if(!t||s.history.length<3||G.fast)return '';
const end=s.retired?Math.ceil(s.age):65,pr=projectAhead(65),x1=Math.max(65,Math.ceil(s.age)),f=s.infl;
const series=[{pts:ptsOf(t.history),c:'var(--muted)'},{pts:ptsOf(s.history),c:'var(--accent)',fill:true}];
let foot='';
if(pr&&pr.you.length>1){series.unshift({pts:ptsOf(pr.twin,1),c:'var(--muted)',dash:true});series.unshift({pts:ptsOf(pr.you,1),c:'var(--accent)',dash:true});
const y=pr.you[pr.you.length-1],w=pr.twin[pr.twin.length-1],yv=real?y.nw/y.f:y.nw,wv=real?w.nw/w.f:w.nw;
foot=`<p class="gap-foot">If you keep going like this, at 65: <b class="money">${money(yv,0,{short:true})}</b> for you, <b class="money">${money(wv,0,{short:true})}</b> for your twin.</p>`}
return `<div class="stack gapchart" style="gap:6px"><span class="eyebrow">You vs. your twin who never invests</span>${lineChart(series,s.startAge,x1,{w:innerWidth<600?340:560,h:innerWidth<600?240:220,label:'Your net worth and your twin\'s, with a dotted line for the years ahead'})}
<div class="legend"><span style="--c:var(--accent)">You</span><span style="--c:var(--muted)">Your twin</span>${pr?'<span class="leg-dash">Dotted: the years ahead, average markets</span>':''}</div>${foot}</div>`}
function impactHTML(){const ti=(G.turns||[]).length-1,items=(G.log||[]).filter(e=>e.turn===ti&&!DB_PERSONAL.includes(e.id)&&!(e.id==='care'&&!G.s.kids.length));if(!items.length)return '';
const late=items.some(e=>!at65Of(e)),rows=items.map(e=>{const vals=e.opts.map(o=>({...o,val:valOf(e,o)})),me=vals.find(o=>o.v===e.chosen)||vals[0],best=vals.reduce((a,b)=>b.val>a.val?b:a),worst=vals.reduce((a,b)=>b.val<a.val?b:a),cost=best.val-me.val,gain=me.val-worst.val;
return cost>1000?{e,me,cls:'bad',amt:cost,vs:best.label}:gain>1000?{e,me,cls:'good',amt:gain,vs:worst.label}:{e,me,cls:'flat',amt:0,vs:''}});
const mx=Math.max(1,...rows.map(r=>r.amt));
return `<section class="panel stack"><div class="sec-head"><span class="badge">${ic('trend')}</span><div><span class="eyebrow">What your choices did</span><h2>${late?'Each choice, by the end of your life':'Each choice, measured at 65'}</h2></div></div>
<div class="imp">${rows.map(r=>`<div class="imp-row"><div class="imp-q"><b>${SHORT[r.e.id]||'Choice'}: ${r.me.label}</b>${r.vs?`<span>vs. “${r.vs}”</span>`:''}</div>
<div class="imp-viz"><span class="imp-bar" aria-hidden="true">${r.cls==='flat'?'<i class="flat"></i>':`<i class="${r.cls}" style="width:${Math.max(3,r.amt/mx*50)}%"></i>`}</span><span class="imp-amt money ${r.cls==='bad'?'neg':r.cls==='good'?'pos':''}">${r.cls==='flat'?'About even':(r.cls==='good'?'+':'−')+money(r.amt,0,{short:true})}</span></div></div>`).join('')}</div>
<p class="muted" style="font-size:var(--fs-sm)">Compared with the other option, in today's dollars and average markets.</p></section>`}
function lessonCardsHTML(L){const tw=L.filter(t=>!/twin/i.test(t)),top=tw.slice(0,3),rest=tw.slice(3);if(!top.length)return '';
const first=t=>{const m=t.match(/^(.*?[.!?])(\s|$)/);return m?m[1]:t};
return `<section class="panel stack"><span class="eyebrow">What these years taught</span><div class="lcards">${top.map(t=>{const n=(t.match(/<strong>(.*?)<\/strong>/)||[])[1];return `<div class="lcard">${n?`<b class="lc-n">${n}</b>`:''}<p>${first(t).replace(/<\/?strong>/g,'')}</p></div>`}).join('')}</div>
${rest.length||top.some(t=>first(t)!==t)?`<details class="more"><summary>More from these years</summary><div class="stack" style="gap:10px;margin-top:10px">${tw.map((t,i)=>`<div class="lesson"><span class="n">${i+1}</span><p>${t}</p></div>`).join('')}</div></details>`:''}</section>`}
function renderResult(el){
const r=G.result,s=G.s,st=G.block,f=s.infl,ch=r.nw1-r.nw0,L=lessonsFor(r,s),last=r.last,nb=last?null:nextBlock(s);
const evs=[...r.events].sort((a,b)=>a.age-b.age);
el.innerHTML=`<section class="panel stack">
<div class="sec-head"><span class="badge">${ic(st.icon)}</span><div><span class="eyebrow">Ages ${Math.round(r.ageFrom)}–${Math.round(r.ageTo)} · ${st.name}</span><h2>${ch>=0?'Your net worth grew':'Your net worth fell'}</h2></div></div>
<div class="delta"><div><span class="eyebrow">Now</span><div class="big ${r.nw1<0?'neg':''}" id="nowBig" data-a="${r.nw0}" data-b="${r.nw1}" data-f="${f}">${money(r.nw1,f)}</div></div>
<div><span class="eyebrow">Change</span><div class="big ${ch<0?'neg':'pos'}" style="font-size:var(--fs-lg)">${ch>=0?'+':''}${money(ch,real?f:0)}</div></div>
<div><span class="eyebrow">Twin who never invests</span><div class="big muted" style="font-size:var(--fs-lg)">${money(netWorth(G.twin),G.twin.infl)}</div></div></div>
${gapChartHTML()}
<div class="stack" style="gap:8px"><span class="eyebrow">Where your money sits</span>${acctBar(s)}</div>
${invested(s)>100&&r.mkt.length>1?`<div class="stack" style="gap:8px"><span class="eyebrow">The stock market each year</span>${marketBars(r.mkt)}<p class="muted" style="font-size:var(--fs-sm)">Some years are great, some painful. Staying in collects the average.</p></div>`:''}
</section>
${impactHTML()}
<section class="panel stack"><div class="sec-head"><span class="badge">${ic('bolt')}</span><div><span class="eyebrow">What life threw at you</span><h2>${evs.length?evs.length+' moment'+(evs.length>1?'s':''):'A quiet stretch'}</h2></div></div>
${evs.length?`<div class="events">${evs.map(e=>eventCard(e,s)).join('')}</div>`:'<p class="muted">Nothing unexpected this time. Life is rarely this calm for long.</p>'}</section>
${lessonCardsHTML(L)}
<div class="actionbar"><button class="btn" id="next">${last?'See where you ended up':`Next: ages ${Math.round(nb.from)}–${Math.round(nb.to)}`} ${ic('arrow')}</button>${G.undo&&!G.auto?`<button class="btn ghost" id="undo">Redo<span class="sm-hide"> these years</span></button>`:''}</div><p class="muted" style="font-size:var(--fs-sm)">${G.undo&&!G.auto?'Redo goes back to the start of this turn with the same luck, so you can try different choices.':''}</p>`;
$('next').onclick=()=>doNext();
countUp($('nowBig'));
if($('undo'))$('undo').onclick=()=>{if(!goBackTo(G.block.from)&&G.undo){restoreG(JSON.parse(G.undo));G.phase='decide';render();window.scrollTo({top:0,behavior:'smooth'})}};
}
function doNext(){
const r=G.result,s=G.s,last=r.last,nb=last?null:nextBlock(s);
G.prevNW={nw:r.nw0,age:r.ageFrom};
if(last){G.phase='final';G.runs.unshift({h:G.s.history,s:G.s});G.runs=G.runs.slice(0,3);clearSave()}
else{G.done.push(G.block);G.block=nb;G.enter=enterStage(s,nb.key);enterStage(G.twin,nb.key);G.phase='decide'}
render();if(!G.fast)window.scrollTo({top:0,behavior:'smooth'});
if(G.auto&&!G.fast&&G.phase==='decide')presetDecide();
}
function revisitHTML(){
if(!G.log||!G.log.length)return '';
const items=G.log.map(e0=>{const e=at65E(e0);
const vals=e.opts.map(o=>real?o.nw/o.f:o.nw),mx=Math.max(...vals),mn=Math.min(...vals,0);
const mine=e.opts.find(o=>o.v===e.chosen)||e.opts[0],best=e.opts[vals.indexOf(mx)],gap=best.nw-mine.nw;
return {e,gap,f:mine.f,html:`<div class="rv"><div><span class="eyebrow">${e.stage} · age ${e.age}</span><h3>${e.q}</h3></div>
<div class="bars">${e.opts.map((o,i)=>`<div class="bar-row rv-row ${o.v===e.chosen?'mine':''}"><span>${o.label}${o.v===e.chosen?' <em>your pick</em>':''}</span><span class="track-b"><i style="width:${Math.max(3,(vals[i]-mn)/(mx-mn||1)*100)}%;--c:${o.v===e.chosen?'var(--accent)':o===best?'var(--gold)':'var(--c-car)'}"></i></span><span class="money">${money(o.nw,o.f,{short:true})}</span></div>`).join('')}</div>
<p class="rv-v ${gap>1000?'neg':'pos'}">${gap>1000?`Opportunity cost: about <strong>${money(gap,mine.f,{short:true})}</strong> ${e.when} compared with "${best.label}".`:`You picked the choice worth the most ${e.when}.`}</p></div>`};
});
const top=items.filter(x=>x.gap>1000).sort((a,b)=>b.gap-a.gap)[0];
return `<section class="panel stack"><div class="sec-head"><span class="badge">${ic('scale')}</span><div><span class="eyebrow">The reveal</span><h2>Your choices, revisited</h2></div></div>
<p class="muted">For each decision, here is what you'd have at 65 with each option (or at the end of your life, for choices made after 65), if everything after it followed typical choices and average markets. The gap is the opportunity cost of the path you didn't take. Money isn't everything: roommates, a cheaper car, a family or a different career all matter in ways that don't show up here.</p>
${top?`<div class="alert">${ic('bolt')}<span>Your most expensive choice was at age ${top.e.age}: "${top.e.q}" It cost about <strong>${money(top.gap,top.f,{short:true})}</strong> ${top.e.when}.</span></div>`:''}
${(()=>{const sorted=[...items].sort((a,b)=>b.gap-a.gap),top=sorted.slice(0,6),rest=sorted.slice(6);
return `<span class="eyebrow">Your ${top.length} most expensive choices</span><div class="revisit">${top.map(x=>x.html).join('')}</div>${rest.length?`<details class="more"><summary>See all ${items.length} decisions, in order</summary><div class="revisit" style="margin-top:12px">${items.map(x=>x.html).join('')}</div></details>`:''}`})()}</section>`;
}
function nextSteps(s,f,T){const I=G.inp,col=I.status!=='grad',L=[],raw=x=>money(x,0),gm=x=>money(x,f),cash=(I.checking||0)+(I.savings||0);
const add=(id,pri,title,game,todo,links)=>L.push({id,pri,title,game,todo,links:links||[]});
if(I.card>0)add('card',95,`Pay off your ${raw(I.card)} credit card balance`,`At ${I.apr}% interest, that balance costs you about ${raw(I.card*I.apr/100)} a year. In the game you paid ${gm(T.cardInterest)} in card interest over your life.`,
['Set up autopay for at least the minimum so you never miss a payment. One late payment can drop your score for years.','Put every extra dollar toward the card until it\'s gone. It\'s a guaranteed '+I.apr+'% return.',`From now on, pay the full statement balance each month and keep it under ${raw(.3*(I.limit||2000))}, 30% of your limit.`],[['CFPB','Credit card questions, answered','https://www.consumerfinance.gov/consumer-tools/credit-cards/answers/'],['CFPB','Why paying more than the minimum matters (PDF)','https://files.consumerfinance.gov/f/documents/cfpb_adult-fin-ed_paying-more-than-minimum_bookmark.pdf']]);
else if(T.cardInterest>500)add('card',40,'Keep paying your card in full',`In the game, carrying a balance cost you ${gm(T.cardInterest)} in interest.`,['Turn on autopay for the full statement balance.','Treat your card like a debit card: only charge what\'s already in checking.'],[['CFPB','Credit card questions, answered','https://www.consumerfinance.gov/consumer-tools/credit-cards/answers/']]);
if(cash<1000)add('ef',90,'Build a $1,000 starter emergency fund',`You have ${raw(cash)} in cash today. In the game, ${Math.round(s.totals.surprises||0)} surprise${Math.round(s.totals.surprises||0)===1?'':'s'} cost ${gm(T.surpriseCost)}${T.surpriseToCard>1?`, and ${gm(T.surpriseToCard)} of it landed on your credit card`:''}.`,
['Open a separate high-yield savings account. Many online banks pay far more than a regular checking account. Make sure it\'s FDIC-insured.','Set up an automatic transfer of $25 to $50 every payday so you don\'t have to think about it.','Only use it for true emergencies, like a car repair or a medical bill. Grow it to 3 to 6 months of expenses after college.'],[['FDIC','Is my bank account insured?','https://www.fdic.gov/resources/deposit-insurance/understanding-deposit-insurance'],['CFPB','A guide to building an emergency fund','https://www.consumerfinance.gov/an-essential-guide-to-building-an-emergency-fund/']]);
else if(T.surpriseToCard>500)add('ef',55,'Grow your emergency fund to 3 months of expenses',`In the game, ${gm(T.surpriseToCard)} of surprise costs landed on your credit card because your cushion ran out.`,['Keep 3 to 6 months of expenses in a high-yield savings account.','Refill it first after you use it.'],[['FDIC','Is my bank account insured?','https://www.fdic.gov/resources/deposit-insurance/understanding-deposit-insurance'],['CFPB','A guide to building an emergency fund','https://www.consumerfinance.gov/an-essential-guide-to-building-an-emergency-fund/']]);
if(I.loans>0&&!I.noLoans)add('loans',col?62:80,`Get to know your ${raw(I.loans)} in student loans`,`In the game you paid ${gm(T.studentInterest)} in student loan interest.`,
['Log in at StudentAid.gov to see each loan, its interest rate and who your servicer is.','When repayment starts, sign up for autopay with your servicer. Federal loans usually knock a little off your rate for it.','If payments ever get tight, ask about income-driven repayment before you miss a payment. Missed payments lead to default.',...(col?['If you can, pay the interest while you\'re in school so it doesn\'t pile up.']:[])],[['Federal Student Aid','Your loans and servicer','https://studentaid.gov'],['Federal Student Aid','Repayment Calculator: compare plans','https://studentaid.gov/repayment-calculator/']]);
const mm=T.missedMatch||0;
add('match',mm>1?(col?72:88):(col?50:30),col?'Sign up for your 401(k) match on day one of your first job':'Make sure you get your full 401(k) match',mm>1?`In the game you left ${gm(mm)} of free match money on the table.`:`In the game your employer added ${gm(T.match)} in free match money.`,
[col?'In your first week, log in to your benefits site and choose a contribution of at least the match, often 3% to 6% of pay.':'Log in to your benefits site and check that you put in at least enough to get the full match, often 3% to 6% of pay. If you\'re not sure what your match is, ask HR.','Pick a target-date or index fund with a fee (expense ratio) under 0.2%.','Every time you get a raise, bump your contribution up 1%.'],[['IRS','How 401(k) plans work','https://www.irs.gov/retirement-plans/401k-plans'],['SEC','What an expense ratio is','https://www.investor.gov/introduction-investing/investing-basics/glossary/expense-ratio']]);
add('roth',T.rothIn<1?76:58,'Open a Roth IRA and actually invest it',T.rothIn<1?`You never used a Roth in the game, and your brokerage paid about ${gm(T.brokDrag||0)} in taxes a Roth would have avoided.`:s.roth-s.rothBasis>=1?`In the game your Roth grew ${gm(s.roth-s.rothBasis)} tax-free.`:`In the game you put ${gm(T.rothIn)} into a Roth but used it along the way, so it had little time to grow tax-free.`,
[(col?'You need earned income, and a part-time or summer job counts. ':'You need earned income from a job. ')+'Open the account at a low-cost brokerage.','Start with what you can, even $25 to $50 a month on autopay. The 2026 limit is $7,500.','Opening an account isn\'t investing. Buy a fund (a target-date or total-market index fund) so your money isn\'t just sitting in cash.'],[['IRS','Roth IRA rules','https://www.irs.gov/retirement-plans/roth-iras'],['IRS','IRA contribution limits','https://www.irs.gov/retirement-plans/plan-participant-employee/retirement-topics-ira-contribution-limits']]);
if(s.soldUntil>0)add('crash',74,'Write down your crash plan now','In the game you sold during the market crash and missed the rebound. Most people who sell in a panic do the same.',['Write one sentence and keep it in your phone: "When the market drops, I keep investing."','Automate your contributions so you keep buying when prices are low.','Don\'t check your balance every day. Long-term money is for the long term.'],[['SEC','Asset allocation and diversification','https://www.investor.gov/introduction-investing/getting-started/asset-allocation'],['SEC','Beginners\' guide to asset allocation (PDF)','https://www.investor.gov/sites/investorgov/files/2019-02/Beginners-Guide-to-Asset-Allocation.pdf']]);
if(s.fee>=.01)add('fees',64,'Check the fees on your investments',`In the game, 1% fees cost you ${gm(T.fees)}.`,['Look up the expense ratio of every fund you own. Under 0.2% is good.','If you use an advisor, ask exactly how they\'re paid and what you pay each year in dollars.'],[['SEC','Mutual fund and ETF fees explained','https://www.investor.gov/introduction-investing/general-resources/news-alerts/alerts-bulletins/investor-bulletins/mutual-fund-and-etf-fees-and-expenses-investor-bulletin'],['FINRA','Fund Analyzer: compare fund costs','https://www.finra.org/investors/insights/research-and-compare-funds']]);
if(s.smoke==='smoker')add('quit',78,'If you smoke, get free help quitting',`In the game, smoking cost you about ${gm(T.habits)} and about 10 years of life.`,['Call Quit Now Kentucky at 1-800-QUIT-NOW (1-800-784-8669) for free coaching.','Ask a doctor or pharmacist about nicotine replacement, which many insurance plans cover.'],[['Kentucky CHFS','Quit Now Kentucky','https://chfs.ky.gov/agencies/dph/dpqi/cdpb/Pages/quit.aspx'],['NCI','Smokefree.gov quit plan','https://smokefree.gov']]);
if((s.partner||s.kids.length)&&s.ins.type==='none')add('ins',54,'Price out term life insurance before anyone depends on you',`In the game you had ${s.kids.length?'a family':'a partner'} and no life insurance.`,['Check what your job already includes, often 1 to 2 times your salary.','Get quotes for a 20 to 30 year term policy worth about 10 times your income. It\'s cheapest while you\'re young and healthy.'],[['NAIC','Life Insurance Buyer\'s Guide (PDF)','https://content.naic.org/sites/default/files/publication-lig-lp-consumer-life.pdf'],['Kentucky DOI','Insurance guide for young adults (PDF)','https://insurance.ky.gov/ppc/Documents/KDOI%20InsGuideYoungAdults061022mn.pdf']]);
if(col)add('kees',60,'Protect your KEES money and fill out the FAFSA',`In the game, KEES cut your tuition by ${raw((I.kees||0))} a year.`,['Log in to your KHEAA account to see your KEES balance and the GPA you need to keep it.','File the FAFSA every year, even if you think you won\'t qualify. Many grants and state aid require it.'],[['KHEAA','How KEES works and how to keep it','https://www.kheaa.com/web/scholarships-grants.faces#kees'],['Federal Student Aid','Fill out the FAFSA','https://studentaid.gov/h/apply-for-aid/fafsa']]);
if(T.unmet>1||T.shortfall>1000)add('budget',66,'Track one month of spending',`In the game you spent more than you earned at times${T.shortfall>1000?`, and ${gm(T.shortfall)} went on your credit card to cover it`:', and some bills went unpaid when your card was maxed out'}.`,['Write down every purchase for 30 days, or use your bank\'s app to sort them.','Split them into needs, wants and savings. 50/30/20 is a good starting point.','Pick one want to cap each month and move that money to savings.'],[['FTC','Making a budget, with a free worksheet','https://consumer.gov/your-money/making-budget'],['FTC','Free tools for planning your finances','https://consumer.ftc.gov/consumer-alerts/2026/02/planning-your-finances-year-come-here-are-some-tools-can-help']]);
add('credit',col?44:38,'Check your credit reports for free',`Your credit score ended the game at ${Math.round(s.credit.score)} (${creditLabel(s.credit.score).toLowerCase()}). Better credit got you lower rates on cars and homes.`,['Pull your reports from all three bureaus at AnnualCreditReport.com, the official free site.','Dispute anything that isn\'t yours.','Pay every bill on time. Payment history is the biggest part of your score.'],[['Official free site','AnnualCreditReport.com','https://www.annualcreditreport.com'],['CFPB','How to dispute an error on your report','https://www.consumerfinance.gov/ask-cfpb/how-do-i-dispute-an-error-on-my-credit-report-en-314/']]);
if(!col&&I.age>=30)add('ssa',36,'Open your “my Social Security” account',`In the game, Social Security paid you ${gm(T.ssPaid)}, and claiming at ${s.ssClaim} ${bestSSAge(s)===s.ssClaim?'was your best choice':`cost you compared with claiming at ${bestSSAge(s)}`}.`,['Create an account at ssa.gov/myaccount to check that your earnings are recorded correctly.','See your estimated benefit at 62, 67 and 70.'],[['SSA','my Social Security account','https://www.ssa.gov/myaccount/'],['SSA','Retirement benefits and when to start','https://www.ssa.gov/retirement']]);
if(s.kids.length&&s.college!=='529')add('529',30,'If you have kids, look at KY Saves 529',`In the game, college for your kids cost ${gm(T.collegePaid)} out of savings.`,['KY Saves 529 has no minimum contribution, and growth is tax-free for school costs.','Even $25 a month from birth adds up by 18.'],[['Kentucky','KY Saves 529 plan','https://www.kysaves.com']]);
add('calc',8,'Run your own numbers','See how your own savings could grow over time.',['Try the SEC\'s free compound interest calculator with what you can save each month.'],[['SEC','Compound interest calculator','https://www.investor.gov/financial-tools-calculators/calculators/compound-interest-calculator']]);
return L.sort((a,b)=>b.pri-a.pri).slice(0,5)}
function bestSSAge(s){const d=deathAge(s),c=ssCompare(s.pia,d).filter(x=>x.age>=(s.retireAt||65));return [...c].sort((a,b)=>b.total-a.total)[0].age}
function stepsHTML(s,f,T){const L=nextSteps(s,f,T),done=id=>{try{return localStorage.getItem('lg-step-'+id)==='1'}catch(e){return false}};
return `<section class="panel stack" id="nextSteps"><div class="sec-head"><span class="badge">${ic('flag')}</span><div><span class="eyebrow">Your real-life next steps</span><h2>${L.length} moves to make in real life</h2></div></div>
${payoffHTML()}
<p class="muted">Based on the numbers you entered and how you played. The game is practice; these are the real thing. Start with #1 this week.</p>
<ol class="nsteps">${L.map((x,i)=>`<li class="nstep${done(x.id)?' done':''}" data-id="${x.id}"><div class="nhead"><span class="nnum">${i+1}</span><h3>${x.title}</h3><label class="ndone"><input type="checkbox" ${done(x.id)?'checked':''}> Done</label></div>
<p class="ngame">${x.game}</p><ul>${x.todo.map(t=>`<li>${t}</li>`).join('')}</ul>${x.links.length?`<div class="nsrc"><span class="nsrc-h">Sources to look into</span><div class="nlinks">${x.links.map(([o,l,u])=>`<a href="${u}" target="_blank" rel="noopener noreferrer"><span class="norg">${o}</span><span class="nlab">${l} ${ic('arrow')}</span></a>`).join('')}</div></div>`:''}</li>`).join('')}</ol>
<p class="muted nsrc-note">Every source is a free government, state or nonprofit site, and the game isn't paid for any link. This is general education, not personal financial advice. Rates, limits and programs change, so check the official sites before you act.</p></section>`}
function riskSim(s,risk){const d=deathAge(s);let v=10000,worst=null;
for(let yr=0;s.startAge+yr<d;yr++){const age=s.startAge+yr;let r;
if(s.crashAge!=null&&age>=s.crashAge-1e-6&&age<s.crashAge+1-1e-6){r=-crashDrop(age,risk)}
else if(s.crashAge!=null&&age>=s.crashAge+1-1e-6&&age<s.crashAge+4-1e-6&&s.soldUntil<0){r=boostRate(s,age,risk)}
else r=riskRet(mixAt(age,risk),s.market[yr]);
v*=1+r;if(!worst||r<worst.r)worst={r,age}}
return {v:v/Math.pow(1+C.INFL,d-s.startAge),worst}}
function riskHTML(s){const rs=Object.keys(RISK).map(k=>({k,...riskSim(s,k)})),mine=rs.find(x=>x.k===(s.risk||'growth')),best=[...rs].sort((a,b)=>b.v-a.v)[0],cons=rs[0];
return `<section class="panel stack"><div class="sec-head"><span class="badge">${ic('waves')}</span><div><span class="eyebrow">Risk tolerance</span><h2>Same market, different mixes</h2></div></div>
<p>Here's what <strong>$10,000</strong> invested at ${s.startAge} would have become by ${deathAge(s)} in each mix, through the exact market years you lived${s.crashAge!=null?`, including the crash at ${Math.floor(s.crashAge)}`:''}. In today's dollars, before fees.</p>
${barRows(rs.map(x=>({l:`${RISK[x.k].label}${x.k===mine.k?' (you, at the end)':''}`,v:x.v,t:`${money(x.v,0)} · worst year ${pctr(x.worst.r)}`,c:x.k===mine.k?'var(--accent)':'var(--c-car)',f:0})))}
<p>${best.k===mine.k?`Your ${RISK[mine.k].label.toLowerCase()} mix came out ahead in your market.`:`In your market, ${RISK[best.k].label.toLowerCase()} came out ahead: ${money(best.v-mine.v,0)} more per $10,000 than your mix.`} The tradeoff is the bad years: the aggressive mix's worst year was ${pctr(rs[3].worst.r)}, versus ${pctr(cons.worst.r)} for conservative.${s.worstYr?` Your own worst year in the game was ${pctr(s.worstYr.r)} at age ${Math.floor(s.worstYr.age)}.`:''}</p>
<p class="tip">More risk usually means more money over decades, but only if you hold on through the drops. The best mix is the most growth you can live with without selling in a panic.${s.soldUntil>0?' You sold during the crash, which locked in the loss no matter which mix you had.':''}</p></section>`}
function monteCarlo(s,t,N){N=N||1000;const L=s.mcLog;if(!L||L.length<3)return null;
const rnd=mulberry32((s.seed^0x2545F491)>>>0),gauss=()=>{const u=Math.max(1e-9,rnd()),v=rnd();return Math.max(-2.6,Math.min(2.6,Math.sqrt(-2*Math.log(u))*Math.cos(2*Math.PI*v)))};
const Y=L.length,cols=L.map(()=>new Float64Array(N));let ranOut=0;const outAges=[];
for(let n=0;n<N;n++){let I=s.mcStart||0,out=false;
for(let y=0;y<Y;y++){const e=L[y],m=mixAt(e.age,e.risk);const r=riskRet(m,gauss()),fl=e.flow-(e.ret?e.unmet:0);I=I*(1+r)*(1-s.fee)+fl*(1+r/2);
if(I<0){if(e.ret&&!out&&I<-1){out=true;outAges.push(e.age)}I=0}
cols[y][n]=I+e.nonInv}
if(out)ranOut++}
const q=(a,p)=>a[Math.min(a.length-1,Math.max(0,Math.floor(p*(a.length-1))))];
const pct=cols.map(c=>{const a=Float64Array.from(c).sort();return {p10:q(a,.1),p50:q(a,.5),p90:q(a,.9)}});
const i65=L.findIndex(e=>e.age+1>=65),k=i65<0?Y-1:i65,a65=Float64Array.from(cols[k]).sort();
const mine=L[k].nw,rank=a65.findIndex(v=>v>=mine),luck=Math.round(100*(rank<0?1:rank/N));
const tw=t?nwAt(t.history,L[k].age+1).nw:0;let beat=0;for(let n=0;n<N;n++)if(cols[k][n]>tw)beat++;
outAges.sort((a,b)=>a-b);
return {N,L,pct,k,luck,beat,tw,lasted:N-ranOut,outMedian:outAges.length?outAges[Math.floor(outAges.length/2)]:null}}
function fanSVG(mc,s,t){const L=mc.L,dv=(v,f)=>real?v/f:v,sm=window.innerWidth<560,W=sm?380:640,H=sm?270:290,Lp=sm?50:62,Rp=sm?8:16,T=16,B=30,x0=s.startAge,x1=L[L.length-1].age+1;
const pts=L.map((e,i)=>({a:e.age+1,lo:dv(mc.pct[i].p10,e.f),md:dv(mc.pct[i].p50,e.f),hi:dv(mc.pct[i].p90,e.f),me:dv(e.nw,e.f),tw:t?dv(nwAt(t.history,e.age+1).nw,e.f):null}));
let mx=Math.max(...pts.map(p=>Math.max(p.hi,p.me,p.tw||0)))*1.05,mn=Math.min(0,...pts.map(p=>Math.min(p.lo,p.me)));
if(mn>-0.12*mx)mn=0;const steps=[1e3,2500,5e3,1e4,25e3,5e4,1e5,25e4,5e5,1e6,2e6,5e6,1e7,2e7];const st=steps.find(v=>(mx-mn)/v<=5)||5e7;mn=Math.floor(mn/st)*st;mx=Math.ceil(mx/st)*st;
const x=a=>Lp+(a-x0)/(x1-x0)*(W-Lp-Rp),y=v=>T+(1-(Math.max(mn,v)-mn)/(mx-mn))*(H-T-B),ln=k=>pts.map((p,i)=>(i?'L':'M')+x(p.a).toFixed(1)+' '+y(p[k]).toFixed(1)).join('');
let g='';for(let v=mn;v<=mx+1;v+=st)g+=`<line class="fg" x1="${Lp}" x2="${W-Rp}" y1="${y(v)}" y2="${y(v)}"/><text class="fa" x="${Lp-8}" y="${y(v)+4}" text-anchor="end">${Math.abs(v)<1?'$0':money(v,0,{short:true})}</text>`;
const span=x1-x0,xs=span>30?10:5;for(let a=Math.ceil(x0/xs)*xs;a<=x1;a+=xs)g+=`<text class="fa" x="${x(a)}" y="${H-8}" text-anchor="middle">${a}</text>`;
const band=pts.map((p,i)=>(i?'L':'M')+x(p.a).toFixed(1)+' '+y(p.hi).toFixed(1)).join('')+[...pts].reverse().map(p=>'L'+x(p.a).toFixed(1)+' '+y(p.lo).toFixed(1)).join('')+'Z';
g+=`<path class="f-band" d="${band}"/>${t?`<path class="f-twin" d="${ln('tw')}"/>`:''}<path class="f-med" d="${ln('md')}"/><path class="f-me" d="${ln('me')}"/>`;
g+=`<line class="f-x" id="fanX" y1="${T}" y2="${H-B}" x1="-10" x2="-10"/><rect class="f-hit" x="${Lp}" y="${T}" width="${W-Lp-Rp}" height="${H-T-B}"/>`;
return {svg:`<svg class="fan" viewBox="0 0 ${W} ${H}" role="img" aria-label="Your net worth by age across ${mc.N.toLocaleString()} possible markets">${g}</svg>`,pts,geo:{W,Lp,Rp,x0,x1}}}
function mcHTML(s,t){const mc=monteCarlo(s,t);if(!mc)return '';G.mc=mc;const fan=fanSVG(mc,s,t);G.fan=fan;
const e65=mc.L[mc.k],f65=e65.f,dv=v=>real?v/f65:v,p=mc.pct[mc.k],age65=Math.round(e65.age+1),flat=(p.p90-p.p10)/f65<5000;
const luckTxt=mc.luck>=80?'very lucky':mc.luck>=60?'luckier than average':mc.luck>=40?'about average':mc.luck>=20?'unluckier than average':'very unlucky';
return `<section class="panel stack" id="mcSec"><div class="sec-head"><span class="badge">${ic('waves')}</span><div><span class="eyebrow">Your life in ${mc.N.toLocaleString()} markets</span><h2>Was it your choices, or your luck?</h2></div></div>
<p>We replayed your exact choices, paychecks and surprises through ${mc.N.toLocaleString()} different stock markets. Only the market changes. The shaded band shows where 8 out of 10 of those lives landed.</p>
<div class="fan-wrap">${fan.svg}<div class="fan-tip" id="fanTip" hidden></div></div>
<div class="legend"><span style="--c:var(--gold)">Your actual life</span><span style="--c:var(--accent)">Typical market</span><span class="lg-band">8 in 10 markets</span>${t?'<span style="--c:var(--muted)">Your twin, never invested</span>':''}</div>
<div class="mc-stats">
<div><small>Bad luck, 1 in 10 markets</small><b>${money(dv(p.p10),0)}</b><span>at ${age65}</span></div>
<div class="mid"><small>Typical market</small><b>${money(dv(p.p50),0)}</b><span>at ${age65}</span></div>
<div><small>Good luck, 1 in 10 markets</small><b>${money(dv(p.p90),0)}</b><span>at ${age65}</span></div>
</div>
<div class="luck"><div class="luck-top"><b>Your market was ${luckTxt}.</b><span>Luckier than ${mc.luck} out of 100</span></div><div class="luck-bar" role="img" aria-label="Luck: ${mc.luck} out of 100"><i style="left:${Math.max(1,Math.min(99,mc.luck))}%"></i></div><div class="luck-ends"><span>Worst markets</span><span>Best markets</span></div></div>
<ul class="mc-facts">
${t?`<li><b>Investing beat your twin's savings account in ${mc.beat.toLocaleString()} of ${mc.N.toLocaleString()} markets.</b> ${mc.beat/mc.N>=.95?'Even in bad markets, decades of investing almost always win.':mc.beat/mc.N>=.6?'Investing usually won, but not every time.':'You invested too little, or too late, for markets to make much difference.'}</li>`:''}
<li><b>Your money lasted the rest of your life in ${mc.lasted.toLocaleString()} of ${mc.N.toLocaleString()} markets.</b> ${mc.lasted/mc.N>=.9?'Your plan holds up even when markets go badly.':mc.outMedian!=null?`When it didn't, the money usually ran out around ${Math.round(mc.outMedian)}. Saving a bit more or spending a bit less in retirement would widen your margin.`:''}</li>
${flat?'<li>You invested very little, so the market barely changed your outcome. That\'s the other side of risk: no market risk also means no market growth.</li>':''}
</ul>
<p class="tip">${mc.luck>=60?'Some of your result was good luck. ':mc.luck<=40?'Your result was held back by a rough market, not just your choices. ':''}To test your choices instead of your luck, use "Replay with the same luck" below: same markets and surprises, different decisions.</p>
<p class="muted" style="font-size:var(--fs-sm)">Markets here follow the same averages and swings as the rest of the game, with each year independent. Real markets have more extreme years, so treat this as a range of possibilities, not a forecast.</p></section>`}
function wireFan(){const svg=document.querySelector('.fan'),tip=$('fanTip'),xl=$('fanX'),F=G.fan;if(!svg||!tip||!F)return;const hit=svg.querySelector('.f-hit');
const move=ev=>{const r=svg.getBoundingClientRect(),cx=(ev.touches?ev.touches[0].clientX:ev.clientX)-r.left,vx=cx/r.width*F.geo.W,a=F.geo.x0+(vx-F.geo.Lp)/(F.geo.W-F.geo.Lp-F.geo.Rp)*(F.geo.x1-F.geo.x0);
let best=F.pts[0];for(const p of F.pts)if(Math.abs(p.a-a)<Math.abs(best.a-a))best=p;const px=F.geo.Lp+(best.a-F.geo.x0)/(F.geo.x1-F.geo.x0)*(F.geo.W-F.geo.Lp-F.geo.Rp);
xl.setAttribute('x1',px);xl.setAttribute('x2',px);
tip.innerHTML=`<b>Age ${Math.round(best.a)}</b><span><i style="--c:var(--gold)"></i>You: ${money(best.me,0)}</span><span><i style="--c:var(--accent)"></i>Typical: ${money(best.md,0)}</span><span class="m">8 in 10: ${money(best.lo,0,{short:true})} to ${money(best.hi,0,{short:true})}</span>${best.tw!=null?`<span><i style="--c:var(--muted)"></i>Twin: ${money(best.tw,0)}</span>`:''}`;
tip.hidden=false;const left=px/F.geo.W*r.width;tip.style.left=Math.max(0,Math.min(r.width-tip.offsetWidth,left+12-(left>r.width*.6?tip.offsetWidth+24:0)))+'px'};
const leave=()=>{tip.hidden=true;xl.setAttribute('x1',-10);xl.setAttribute('x2',-10)};
hit.addEventListener('mousemove',move);hit.addEventListener('touchstart',move,{passive:true});hit.addEventListener('touchmove',move,{passive:true});hit.addEventListener('mouseleave',leave)}
const LESSON_LINE={k401:'Always get the full 401(k) match. It\'s part of your pay, and skipping it means turning down free money.',save:'Saving a little more each month adds up to a lot over decades, because the earliest dollars grow the longest.',rent:'Housing is your biggest bill. Keeping it lower frees up money that can grow for decades.',car:'Cars lose value fast. A cheaper car leaves more money to invest.',fund:'Fees come out every year and compound against you. Low-cost index funds keep more of your money working.',acct:'A Roth IRA lets your growth come out tax-free. Fill it before a regular brokerage account.',crash:'Selling in a crash turns a temporary drop into a permanent loss. Staying invested is how you catch the recovery.',order:'Build a small cushion, clear high-interest debt, then invest the rest. The order matters.',kids:'Kids are worth far more than money, but they are expensive. Planning ahead keeps your savings on track.',home:'A home can build wealth, but buying costs a lot up front. Make sure the timing and price fit your budget.',move:'Every move costs about 9% of the home\'s price in selling and buying costs. Moving less keeps more of your equity.',life:'Spending a little less each year, especially early, has a huge effect by retirement.',career:'Your income is your biggest money tool. Higher pay early means more to save and invest for longer.',ins:'Insurance protects your family, but the cheapest coverage that does the job leaves more to invest.',health:'Picking the right health plan can save money every month, and an HSA grows tax-free.',ss:'When you start Social Security changes your check for life. Waiting pays more if you live long.',spend:'In retirement, how fast you spend decides whether your money lasts.',city:'Where you live changes your taxes and rent every single month.',cover:'Borrowing in college feels small now, but it grows with interest until you pay it back.',family:'Sharing a life can share costs, but it changes your budget. Talk about money early.'};
function lessonCard(){if(!G.log||!G.log.length)return '';
const items=G.log.map(e0=>{const e=at65E(e0);const vals=e.opts.map(o=>real?o.nw/o.f:o.nw),mx=Math.max(...vals),mine=e.opts.find(o=>o.v===e.chosen)||e.opts[0],best=e.opts[vals.indexOf(mx)];return {e,mine,best,gap:best.nw-mine.nw,f:mine.f}}).filter(x=>x.gap>1000&&!DB_PERSONAL.includes(x.e.id)).sort((a,b)=>b.gap-a.gap);
const top=items[0];
if(!top)return `<section class="panel stack lesson-card"><div class="sec-head"><span class="badge">${ic('star')}</span><div><span class="eyebrow">Your biggest lesson</span><h2>You made strong choices all the way through</h2></div></div><p>None of your decisions left much money on the table. The rest of your result came down to luck and the life you chose.</p></section>`;
const line=(top.e.id==='k401'&&+top.mine.v>=0.05?'Going past the match pays off too. Every extra percent you put in your 401(k) early grows for decades.':null)||LESSON_LINE[top.e.id]||'Small choices made early grow the most, because they have the longest time to compound.';
return `<section class="panel stack lesson-card"><div class="sec-head"><span class="badge">${ic('star')}</span><div><span class="eyebrow">Your biggest lesson</span><h2>${line}</h2></div></div>
<p>At ${top.e.age} you picked <b>"${top.mine.label}"</b> instead of <b>"${top.best.label}"</b>. That one choice cost you about <strong>${money(top.gap,top.f,{short:true})}</strong> ${top.e.when}.</p></section>`}
function foldFinal(el,s){const secs=[...el.children];const hero=secs.find(x=>x.classList.contains('goal')),ns=el.querySelector('#nextSteps'),twin=secs.find(x=>/Same life, no investing/.test(x.textContent)&&x.classList.contains('panel')),again=secs.find(x=>x.querySelector&&x.querySelector('#same'));
const keep=new Set([hero,ns,twin,again].filter(Boolean)),fold=secs.filter(x=>!keep.has(x)&&x.tagName==='SECTION');
const box=document.createElement('section');box.className='panel stack digdeep';box.innerHTML=`<div class="sec-head"><span class="badge">${ic('doc')}</span><div><span class="eyebrow">Dig deeper</span><h2>The full breakdown</h2></div></div><p class="muted">Open any section to see the details behind your result.</p>`;
for(const sec of fold){const d=document.createElement('details');d.className='fold';const ey=sec.querySelector('.eyebrow'),h=sec.querySelector('h2,h3');
d.innerHTML=`<summary><span class="fs-t">${h?h.textContent:'Details'}</span>${ey&&ey!==h?`<span class="fs-s">${ey.textContent}</span>`:''}</summary>`;d.appendChild(sec);box.appendChild(d)}
const lesson=document.createElement('div');lesson.innerHTML=lessonCard();const lc=lesson.firstElementChild;
const sb=secs.find(x=>x.id==='stratBox');
el.innerHTML='';[hero,lc,twin,sb,ns,fold.length?box:null,again].forEach(x=>{if(x)el.appendChild(x)})}
function rothHTML(s,f,T){const gain=Math.max(0,s.brok-s.brokBasis),owed=C.LTCG*gain,drag=T.brokDrag||0,taxes=drag+owed,rg=Math.max(0,s.roth-s.rothBasis);
if(T.rothIn<1&&!(drag>1))return '';
const head=T.rothIn<1?'You never had a Roth IRA':'Tax-free vs. taxable';
const body=T.rothIn<1?`You never put money in a Roth IRA, so everything you invested outside your 401(k) went into a taxable brokerage account. Along the way it paid about <strong>${money(drag,f)}</strong> in taxes on dividends${owed>1?`, and selling what's left would owe about <strong>${money(owed,f)}</strong> more on the gains. That's <strong>${money(taxes,f)}</strong> in total`:', plus 15% on the gains whenever you sold'}. Up to $7,500 a year of that could have grown in a Roth, tax-free forever.`
:s.rothBasis<1&&rg<1?`You used your Roth IRA money along the way, so little was left in it to grow tax-free.`:`Your Roth IRA grew by ${money(rg,f)} on top of the ${money(s.rothBasis,f)} you put in, and every dollar of it comes out tax-free.${s.brok>1?` Your brokerage account paid about ${money(drag,f)} in dividend taxes along the way and would owe about ${money(owed,f)} on its gains.`:''} Filling the Roth first each year is one of the simplest tax wins there is.`;
return `<section class="panel stack"><div class="sec-head"><span class="badge">${ic('trend')}</span><div><span class="eyebrow">Roth IRA</span><h2>${head}</h2></div></div>
${barRows([{l:'Roth IRA growth, tax-free',v:rg,c:'var(--c-roth)',f},{l:'Taxes on your brokerage',v:taxes,c:'var(--danger)',f}])}<p>${body}</p></section>`}
function insHTML(s,f,T){const i=s.ins;if(!i||i.type==='none')return s.partner?`<section class="panel stack"><div class="sec-head"><span class="badge">${ic('shield')}</span><div><span class="eyebrow">Life insurance</span><h2>You went without</h2></div></div><p>You never bought life insurance. You lived a long life, so it never mattered, but for years your ${s.kids.length?'partner and kids':'partner'} depended on your income with nothing to replace it if you had died. Term coverage would have cost about ${money(25*f)} a month at 30.</p></section>`:'';
const pay=insPayout(s);
return `<section class="panel stack"><div class="sec-head"><span class="badge">${ic('shield')}</span><div><span class="eyebrow">Life insurance</span><h2>${i.type==='term'?'Your term policy':'Your whole life policy'}</h2></div></div>
${i.type==='term'&&i.f0?(()=>{const g=i.f0,yrs=Math.min(i.years||20,(s.month-i.start)/12),paid=i.prem*12*yrs*g;return `${barRows([{l:'Premiums paid',v:paid,c:'var(--danger)',f:g},{l:pay>0?'Paid to your family':'Coverage while it lasted',v:i.face,c:'var(--accent)',f:g}])}<p class="muted" style="font-size:var(--fs-sm)">In dollars from when you bought it, at age ${Math.round(i.startAge)}.</p>`})():barRows([{l:'Premiums paid',v:T.premiums,c:'var(--danger)',f},{l:i.type==='term'?'Coverage while it lasted':'Paid to your family',v:i.type==='term'?i.face:Math.max(i.face,i.cv),c:'var(--accent)',f}])}
<p>${i.type==='term'?(pay>0?`You died while still covered, so your family received the ${money(i.face,i.f0||f)} death benefit tax-free on top of everything else you left.`:`You paid ${money(i.f0?i.prem*12*(i.years||20)*i.f0:T.premiums,i.f0||f)} for ${i.years||20} years of protection from age ${Math.round(i.startAge)} to ${Math.round(i.startAge+(i.years||20))}. You outlived it, so it never paid out, which is what happens for most people. It still did its job: if the worst had happened, your family would have received ${money(i.face,i.f0||f)}.`):`You paid ${money(T.premiums,f)} in premiums for life. At your death, your family received the ${money(Math.max(i.face,i.cv),f)} death benefit${i.cv>i.face?', which by then was mostly your own cash value':''}. Your cash value had grown to ${money(i.cv,f)} on ${money(T.premiums,f)} of premiums.${i.cv>i.face?'':` Inflation shrank that fixed payout: the ${money(i.face,0)} policy buys only about ${money(i.face/f,0)} worth of today's goods.`}`}</p></section>`;
}
function nwAt(h,age){let p=h[0];for(const q of h){if(q.age<=age+1e-6)p=q;else break}return p}
function renderFinal(el){
const s=G.s,t=G.twin,f=s.infl,T=realTot(s),d=deathAge(s),nw=netWorth(s),prev=G.runs[1],tw=netWorth(t);
const at65=nwAt(s.history,65),t65=nwAt(t.history,65),hit=real?s.hit1MReal:s.hit1M,lp=lifeParts(s);
const cmp=ssCompare(s.pia,d).filter(x=>x.age>=Math.min(s.retireAt||65,s.ssClaim||65)),bestSS=[...cmp].sort((a,b)=>b.total-a.total)[0],mySS=cmp.find(x=>x.age===s.ssClaim);
const series=[{pts:ptsOf(s.history,3),c:'var(--accent)',fill:true},{pts:ptsOf(t.history,3),c:'var(--muted)',dash:true}];if(prev)series.push({pts:ptsOf(prev.h,3),c:'var(--c-brok)',dash:true});
const RA=s.retireAt||65,yearsRet=d-RA,lasted=s.broke!=null?s.broke-RA:yearsRet,tLasted=t.broke!=null?t.broke-RA:yearsRet;
el.innerHTML=`<section class="goal">
<span class="eyebrow">Your story ends at ${d}</span>
<h2>${s.broke!=null?`Your money ran out at ${Math.floor(s.broke)}`:`You left ${money(nw+insPayout(s),f)} to your family`}</h2>
<p class="muted">${(()=>{const left=nw+insPayout(s);const lead=s.broke!=null?(left>1000?`You still left ${money(left,f)} to your family${s.home>0?', mostly the value of your home':''}. `:'You left almost nothing behind. '):'';return lead+(left>1000?(real?`That's in today's dollars. Because prices rise about ${f.toFixed(1)}x by then, the actual future amount reads ${money(left,0)}.`:`In today's dollars that's about ${money(left/f,0)}. Prices rise about ${f.toFixed(1)}x by then.`):'')})()}</p>
<div class="big">${money(at65.nw,at65.f)} <span style="font-size:.45em" class="muted">at 65</span></div>
<div class="btns"><button type="button" class="btn" id="toDebrief">${ic('doc')} See your debrief: the moments that helped and hurt most</button><a href="#nextSteps" id="toSteps" class="btn ghost tosteps">${ic('flag')} See your real-life next steps</a></div>
<p>${hit!=null?`You became a millionaire at ${Math.floor(hit)}${real?' in today\'s dollars':''}. `:''}You retired at 65 with ${money(at65.nw,at65.f)}${real?'':`, worth about ${money(at65.nw/at65.f,0)} in today's dollars`}, and lived ${yearsRet} more years. ${s.broke!=null?`For your last ${Math.round(d-s.broke)} years you lived on Social Security alone.`:`Your savings lasted the whole way.`}</p>
</section>
${mcHTML(s,t)}
<section class="panel stack"><div class="sec-head"><span class="badge">${ic('heart')}</span><div><span class="eyebrow">Health is wealth</span><h2>How your habits shaped your life</h2></div></div>
${barRows([{l:'Kentucky average at 65',v:lp.base,t:lp.base+' years',c:'var(--c-car)'},{l:'Exercise',v:Math.abs(lp.exercise)||.2,t:(lp.exercise>=0?'+':'−')+Math.abs(lp.exercise)+' years',c:lp.exercise>=0?'var(--accent)':'var(--danger)'},{l:'Smoking',v:Math.abs(lp.smoke)||.2,t:(lp.smoke>=0?'+':'−')+Math.abs(lp.smoke)+' years',c:lp.smoke>=0?'var(--accent)':'var(--danger)'},{l:'Health luck',v:Math.abs(lp.luck)||.2,t:(lp.luck>=0?'+':'−')+Math.abs(lp.luck)+' years',c:lp.luck>=0?'var(--accent)':'var(--danger)'},{l:'Your lifespan',v:d,t:d+' years',c:'var(--gold)'}],100)}
<p>${s.smoke==='smoker'?`Smoking cost you about 10 years of life and ${money(T.habits,f)} along the way.`:s.smoke==='quit'?'Quitting before 40 won back most of the years smoking would have taken.':'Not smoking kept your full life expectancy.'} ${s.exercise==='high'?'Staying active added about 3 years.':s.exercise==='low'?'An inactive lifestyle took about 2 years.':''} Luck played a part too, which is why planners suggest making money last to about 95.</p></section>
${G.inp.goals&&G.inp.goals.length?`<section class="panel stack"><div class="sec-head"><span class="badge">${ic('flag')}</span><div><span class="eyebrow">${G.inp.goals.filter(id=>goalStatus(s,id,true).ok).length} of ${G.inp.goals.length} reached</span><h2>Your goals</h2></div></div>${goalsHTML(s,true)}</section>`:''}
<section class="panel stack"><div class="sec-head"><span class="badge">${ic('doc')}</span><div><span class="eyebrow">Your life story</span><h2>How it all unfolded</h2></div></div>
<ol class="story">${[...s.story,{age:d,text:s.broke!=null?'Your story ends, with Social Security as your only income':`Your story ends. You leave ${money(nw+insPayout(s),f)} to your family`,icon:'sun'}].map(e=>`<li><span class="node">${ic(e.icon||'flag')}</span><span class="num">${Math.floor(e.age)}</span><span>${e.text}</span></li>`).join('')}</ol></section>
${insHTML(s,f,T)}
${riskHTML(s)}
${rothHTML(s,f,T)}
<section class="panel stack"><div class="sec-head"><span class="badge">${ic('sun')}</span><div><span class="eyebrow">Retirement</span><h2>Did your money outlast you?</h2></div></div>
${barRows([{l:`Years you lived after retiring at ${RA}`,v:yearsRet,t:yearsRet+' years',c:'var(--gold)'},{l:'Your savings lasted',v:Math.max(.2,lasted),t:(s.broke!=null?Math.floor(lasted)+' years':'All of them'),c:s.broke!=null?'var(--danger)':'var(--accent)'},{l:'Your twin\'s savings lasted',v:Math.max(.2,tLasted),t:(t.broke!=null?Math.floor(tLasted)+' years':'All of them'),c:'var(--c-car)'}],Math.max(yearsRet,1))}
<div class="${s.broke!=null?'alert':'okay'}">${ic(s.broke!=null?'bolt':'sun')}<span>${s.broke!=null?`You ran out at ${Math.floor(s.broke)} and lived the rest on about ${money(s.ssMonthly*s.infl/s.infl65,f)} a month from Social Security. Saving more earlier, spending less in retirement or claiming Social Security later would have stretched it.`:`You never ran out. ${s.spendStyle>1?'Even living large, your':'Your'} savings plus Social Security covered every year, and ${money(nw,f)} passes to your family.`}</span></div></section>
<section class="panel stack"><div class="sec-head"><span class="badge">${ic('cal')}</span><div><span class="eyebrow">Social Security, played out</span><h2>Was ${s.ssClaim} the right age to claim?</h2></div></div>
${ssChart(s.pia,s.infl65,d)}
${barRows(cmp.map(x=>({l:`Claim at ${x.age}${x.age===s.ssClaim?' (you)':''}`,v:x.total,c:SSC[x.age],f:s.infl65})))}
<p class="tip">Living to ${d}, ${bestSS.age===s.ssClaim?`claiming at ${s.ssClaim} was the best choice: about ${money(mySS.total,s.infl65)} over your life.`:`claiming at <strong>${bestSS.age}</strong> would have paid about <strong>${money(bestSS.total-mySS.total,s.infl65)}</strong> more than claiming at ${s.ssClaim}.`} ${bestSS.age>=70?'The longer you live, the more waiting pays.':d<82?'Because your life was shorter than average, claiming earlier came out ahead.':'Waiting longer pays off only if you live well past the average.'} Amounts are ${ssUnit()}.</p></section>
<section class="panel stack"><div class="sec-head"><span class="badge">${ic('ghost')}</span><div><span class="eyebrow">Same life, no investing</span><h2>You vs. your twin</h2></div></div>
<p>Your twin lived your exact life: the same job, pay, home, family, car and surprises, and they saved the same amount every month. The only difference: their savings sat in a high-yield savings account earning 3.5%, about 0.5% after inflation. No 401(k) match, no tax breaks, no market growth.</p>
${barRows([{l:'You at 65',v:at65.nw,c:'var(--accent)',f:at65.f},{l:'Your twin at 65',v:t65.nw,c:'var(--c-car)',f:t65.f}])}
<p class="tip">At 65, investing had made you <strong>${money(at65.nw-t65.nw,at65.f)}</strong> richer. ${t.broke!=null&&s.broke==null?`Your twin ran out of money at ${Math.floor(t.broke)}. You never did.`:t.broke!=null?`Your twin ran out at ${Math.floor(t.broke)}, ${s.broke!=null&&Math.floor(t.broke)<Math.floor(s.broke)?(Math.floor(s.broke)-Math.floor(t.broke))+' year'+(Math.floor(s.broke)-Math.floor(t.broke)===1?'':'s')+' before you':'too'}.`:''}</p></section>
<div id="stratBox">${stratHTML()}</div>
<section class="panel stack"><h3>Your net worth over your whole life</h3>
${lineChart(series,s.startAge,d,{w:640,h:280,min1M:true,label:'Net worth by age'})}
<div class="legend"><span style="--c:var(--accent)">You</span><span style="--c:var(--muted)">Your twin who never invested</span>${prev?`<span style="--c:var(--c-brok)">Your last run</span>`:''}<span style="--c:var(--gold)">$1 million</span></div></section>
${revisitHTML()}
<section class="panel stack"><h3>Where your money went</h3>
<div class="stats">
<div class="stat">${ic('plus')}${M(T.match,f)}<small>Free money from your 401(k) match</small></div>
<div class="stat">${ic('cal')}${M(T.ssPaid,f)}<small>Collected from Social Security</small></div>
<div class="stat">${ic('pct')}${M(T.fees,f)}<small>Investment fees at ${(s.fee*100).toFixed(2)}% a year</small></div>
${T.hsaIn>0?`<div class="stat">${ic('heart')}${M(T.hsaIn,f)}<small>Put into your HSA, tax-free</small></div>`:''}
${T.premiums>0?`<div class="stat">${ic('shield')}${M(T.premiums,f)}<small>Life insurance premiums</small></div>`:''}
<div class="stat">${ic('star')}${M(T.bonus,f)}<small>Bonuses after taxes${s.career==='custom'&&!(s.careerTitle&&s.careerTitle!=='My job')?'':' as '+esc(jobPhrase(s))}</small></div>
<div class="stat">${ic('bolt')}${M(T.surpriseCost,f)}<small>${Math.round(s.totals.surprises||0)} surprise${Math.round(s.totals.surprises||0)===1?'':'s'} cost you this${T.surpriseToCard>1?`; ${money(T.surpriseToCard,f)} went on the card`:''}</small></div>
<div class="stat">${ic('card')}${M(T.cardInterest,f)}<small>Paid in credit card interest</small></div>
<div class="stat">${ic('doc')}${M(T.studentInterest,f)}<small>Paid in student loan interest</small></div>
<div class="stat">${ic('scale')}${M(T.taxes,f)}<small>Income and payroll taxes while working, including ${money(T.local,f)} in local payroll tax</small></div>
<div class="stat">${ic('car')}${M(T.carInterest,f)}<small>Car loan interest, across ${Math.round(s.totals.cars||0)+1} car${Math.round(s.totals.cars||0)?'s':''}</small></div>
${T.habits>0?`<div class="stat">${ic('heart')}${M(T.habits,f)}<small>${s.smoke!=='never'?'Cigarettes':''}${s.smoke!=='never'&&s.exercise==='high'?' and ':''}${s.exercise==='high'?'Gym memberships':''}</small></div>`:''}
${T.kidCost>0?`<div class="stat">${ic('heart')}${M(T.kidCost+T.collegePaid,f)}<small>Raising kids, including college</small></div>`:''}
<div class="stat">${ic('wallet')}${M(T.fun,f)}<small>Spent on fun while working</small></div>
</div></section>
${stepsHTML(s,f,T)}
<section class="panel stack"><h3>Try it again</h3>
<p>Replay with the <strong>same surprises, market years and health luck</strong> but different choices, so any difference comes from your decisions alone. This run stays on the chart to compare.</p>
<div class="btns"><button class="btn ghost" id="toDebrief2">${ic('doc')} See your debrief</button><button class="btn" id="same">Replay with the same luck</button><button class="btn ghost" id="newluck">New luck</button><button class="btn ghost" id="edit">Back to the lessons</button></div></section>`;
el.querySelectorAll('.nstep input[type=checkbox]').forEach(cb=>cb.addEventListener('change',()=>{const li=cb.closest('.nstep');li.classList.toggle('done',cb.checked);try{localStorage.setItem('lg-step-'+li.dataset.id,cb.checked?'1':'0')}catch(e){}}));
{const j=$('toSteps');if(j)j.onclick=e=>{e.preventDefault();const t=$('nextSteps');if(t)t.scrollIntoView({behavior:matchMedia('(prefers-reduced-motion: reduce)').matches?'auto':'smooth',block:'start'})}}
foldFinal(el,s);
wireFan();
$('same').onclick=()=>startRun(G.seed);
{const sb=$('stratBox');if(sb)sb.addEventListener('click',e=>{const b=e.target.closest('.rp');if(!b)return;const y=sb.getBoundingClientRect().top;sb.innerHTML=stratHTML(b.dataset.rp);const nb=sb.querySelector(`.rp[data-rp="${b.dataset.rp}"]`);if(nb)nb.focus({preventScroll:true});window.scrollBy(0,sb.getBoundingClientRect().top-y)})}
['toDebrief','toDebrief2'].forEach(id=>{const b=$(id);if(b)b.onclick=()=>{G.phase='debrief';render();window.scrollTo({top:0,behavior:'smooth'})}});
$('newluck').onclick=()=>startRun(Math.floor(Math.random()*1e9));
$('edit').onclick=()=>{G.phase='setup';G.s=null;render();window.scrollTo({top:0})};
}
const DB_PERSONAL=['career','city','family','kids','smoke','exercise','ins','quit'];
const DB_LIFE={career:'Your job sets your pay for decades. The right job is about more than money, so this one isn\'t scored.',family:'A life choice. The game shows what it costs, but it isn\'t scored by money left behind.',kids:'A life choice. The game shows what kids cost, but it isn\'t scored by money left behind.',smoke:'Changes how long you\'re likely to live, so it isn\'t scored by money left behind.',quit:'Changes how long you\'re likely to live, so it isn\'t scored by money left behind.',exercise:'Changes how long you\'re likely to live, so it isn\'t scored by money left behind.',ins:'Insurance protects the people who depend on you. Its value isn\'t measured in money left behind.'};
const at65Of=e=>e.age<65&&e.id!=='retireAge'&&e.opts.every(o=>o.nw65!=null),valOf=(e,o)=>at65Of(e)?o.nw65/o.f65:o.nw/o.f,at65E=e=>at65Of(e)?{...e,when:'by 65',opts:e.opts.map(o=>({...o,nw:o.nw65,f:o.f65}))}:{...e,when:'by the end of your life'};
function dbEffect(e){if(DB_LIFE[e.id])return {cls:'life',amt:0,txt:DB_LIFE[e.id]};const vals=e.opts.map(o=>({...o,val:valOf(e,o)})),me=vals.find(o=>o.v===e.chosen)||vals[0],best=vals.reduce((a,b)=>b.val>a.val?b:a),worst=vals.reduce((a,b)=>b.val<a.val?b:a),cost=best.val-me.val,gain=me.val-worst.val,when=at65Of(e)?'by 65':'by the end of your life';
if(cost>1000)return {cls:'bad',amt:cost,txt:`Cost you about <strong>${money(cost,0,{short:true})}</strong> ${when} compared with “${best.label}.”`};
if(gain>1000)return {cls:'good',amt:gain,txt:`Your best option here. It left you about <strong>${money(gain,0,{short:true})}</strong> more ${when} than “${worst.label}.”`};
return {cls:'flat',amt:0,txt:'Made little difference to your money.'}}
function debriefData(){const turns=G.turns||[],log=G.log||[];
return turns.map((t,i)=>({t,i,si:(G.snaps||[]).findIndex(x=>Math.abs(x.from-t.from)<.01),choices:(t.picks||[]).map(p=>{const e=log.find(x=>(x.turn!=null?x.turn===i:x.stage===`Ages ${Math.round(t.from)}–${Math.round(t.to)}`)&&x.q===p.q);return {...p,e,eff:e?dbEffect(e):null}})}))}
function renderDebrief(el){
const s=G.s,t=G.twin,f=s.infl,d=deathAge(s),data=debriefData(),all=data.flatMap(x=>x.choices.map(c=>({...c,stage:x.t,si:x.si})));
const ranked=all.filter(c=>c.eff&&c.e&&!DB_PERSONAL.includes(c.e.id));
const top3=L=>{const seen=new Set(),out=[];for(const c of L.sort((a,b)=>b.eff.amt-a.eff.amt)){if(seen.has(c.e.id))continue;seen.add(c.e.id);out.push(c);if(out.length===3)break}return out};
const helped=top3(ranked.filter(c=>c.eff.cls==='good')),hurt=top3(ranked.filter(c=>c.eff.cls==='bad'));
const at65=nwAt(s.history,65),t65=nwAt(t.history,65),h0=(()=>{const t0=(G.turns||[])[0];return t0?{nw:t0.nw0,f:t0.f0}:{nw:0,f:1}})(),left=netWorth(s)+insPayout(s);
const ages=x=>`${Math.round(x.from)}–${Math.round(x.to)}`;
const moment=(c,i,kind)=>`<li class="db-moment ${kind}"><div class="dbm-head"><span class="dbm-n">${i+1}</span><div><span class="eyebrow">Age ${Math.round(c.stage.from)}${SHORT[c.e.id]?' · '+SHORT[c.e.id]:''}</span><h3>${c.a}</h3></div><span class="dbm-amt money">${kind==='good'?'+':'−'}${money(c.eff.amt,0,{short:true})}</span></div>
<p class="muted dbm-q">${c.q}</p><p class="dbm-eff">${c.eff.txt}</p>
${c.e&&c.si>=0&&c.e.opts.length>1?`<div class="wi"><button type="button" class="linkbtn wi-btn" aria-expanded="false">What if I'd chosen differently?</button><div class="wi-opts" hidden><span class="muted">Replay your life with:</span>${c.e.opts.filter(o=>o.v!==c.e.chosen).map(o=>`<button type="button" class="chip wi-pick" data-s="${c.si}" data-q="${c.e.id}" data-v="${esc(o.v)}" data-l="${esc(o.label)}">${o.label}</button>`).join('')}</div><div class="wi-out"></div></div>`:''}</li>`;
el.innerHTML=`<section class="panel stack db-head"><div class="sec-head"><span class="badge">${ic('doc')}</span><div><span class="eyebrow">Debrief · your story ended at ${d}</span><h2>The moments that mattered most</h2></div></div>
<p>You made ${all.length} choices over ${data.length} stages of life. Here are the ones that helped your money most and the ones that hurt it most, up to three each and one per kind of decision, so every moment is a different lesson.</p>
<div class="stats"><div class="stat"><small>You started with</small><span class="money">${money(h0.nw,h0.f)}</span></div><div class="stat"><small>At 65</small><span class="money">${money(at65.nw,at65.f)}</span></div><div class="stat"><small>Your twin at 65</small><span class="money">${money(t65.nw,t65.f)}</span></div><div class="stat"><small>${s.broke!=null?`Savings ran out at ${Math.floor(s.broke)}; you left`:'You left your family'}</small><span class="money">${money(Math.max(0,left),f)}</span></div></div></section>
<section class="panel stack db-sec good"><div class="sec-head"><span class="badge">${ic('trend')}</span><div><span class="eyebrow">Keep doing these</span><h2>${helped.length===1?'The moment that helped you most':`${helped.length||3} moments that helped you most`}</h2></div></div>
${helped.length?`<ol class="db-moments">${helped.map((c,i)=>moment(c,i,'good')).join('')}</ol>`:'<p class="muted">No single choice stood out as a big win. Your results came from many small decisions.</p>'}</section>
<section class="panel stack db-sec bad"><div class="sec-head"><span class="badge">${ic('bolt')}</span><div><span class="eyebrow">Do these differently</span><h2>${hurt.length===1?'The moment that hurt you most':`${hurt.length||3} moments that hurt you most`}</h2></div></div>
${hurt.length?`<ol class="db-moments">${hurt.map((c,i)=>moment(c,i,'bad')).join('')}</ol>`:'<p class="muted">None of your choices left much money on the table. Nicely played.</p>'}</section>
<p class="muted" style="font-size:var(--fs-sm)">Each amount compares your pick with the other options at that moment, measured at 65 (or by the end of your life for choices made after 65), if markets earned their average and later choices stayed typical. Amounts are in today's dollars. Personal choices like your job, family and health are part of the story but aren't ranked here. Tap “What if I'd chosen differently?” to replay your exact life, with the same luck, with one choice changed.</p>
<section class="panel stack"><h3>What next?</h3><p class="muted">Ready to try this for real? Your real-life next steps, each with free sources to look into, are on your results page.</p><div class="btns"><button class="btn" id="dbSteps">See my real-life next steps</button><button class="btn ghost" id="dbBack">← Back to your results</button><button class="btn ghost" id="dbSame">Replay with the same luck</button><button class="btn ghost" id="dbNew">New luck</button></div></section>`;
$('dbBack').onclick=()=>{G.phase='final';render();window.scrollTo({top:0})};
$('dbSteps').onclick=()=>{G.phase='final';render();const n=$('nextSteps');if(n)n.scrollIntoView({block:'start'});else window.scrollTo({top:0})};
el.querySelectorAll('.wi-btn').forEach(b=>b.onclick=()=>{const o=b.nextElementSibling,open=o.hidden;o.hidden=!open;b.setAttribute('aria-expanded',open)});
el.querySelectorAll('.wi-pick').forEach(b=>b.onclick=()=>{const out=b.closest('.wi').querySelector('.wi-out'),v=b.dataset.v,vv=v!==''&&!isNaN(+v)?+v:v;b.closest('.wi-opts').querySelectorAll('.wi-pick').forEach(x=>x.classList.toggle('on',x===b));out.innerHTML='<p class="muted">Replaying your life with the same luck…</p>';
setTimeout(()=>{let c=null;try{c=whatIf(+b.dataset.s,b.dataset.q,vv)}catch(err){console.error(err)}out.innerHTML=c?whatIfHTML(c,b.dataset.l):'<p class="muted">This one can\'t be replayed. Try another choice.</p>'},30)});
$('dbSame').onclick=()=>startRun(G.seed);
$('dbNew').onclick=()=>startRun(Math.floor(Math.random()*1e9));
}
// ---------- surprises you respond to ----------
function findSurprise(s,st,ch){if(s.retired||G.auto||G.fast||st.key==='retire'||st.key==='retire2')return null;
const c=structuredClone({...s,history:[],stageEvents:[],story:[]});c.respond={};applyDecisions(c,st.key,ch);c.stageEvents=[];
const months=Math.max(1,Math.round((st.to-c.age)*12));
for(let k=0;k<months;k++){const pre={cash:Math.max(0,c.cash),card:c.card.bal,lim:cardLimit(c),k401:c.k401,age:c.age,month:c.month,life:lifeBase(c),needs:fixedNeeds(c),f:c.infl,apr:c.card.rate};const n=c.stageEvents.length;step(c);
for(const ev of c.stageEvents.slice(n)){if(ev.life||!ev.c||ev.gamble||ev.c.id==='wedding')continue;const pay=ev.amt;if(ev.c.layoff||(ev.c.cost>0&&pay>=1500*pre.f))return {m:pre.month,ev,pre}}
if(c.retired)break}
return null}
function goLive(qs,st,ch){const sp=findSurprise(G.s,st,ch);if(!sp){doLive(qs,st,ch);return}
G.surprise={qs,st,ch,...sp};G.phase='surprise';render();window.scrollTo({top:0,behavior:matchMedia('(prefers-reduced-motion: reduce)').matches?'auto':'smooth'})}
function surpriseOptions(S){const ev=S.ev,c=ev.c,p=S.pre,f=p.f,yrs=Math.max(0,65-p.age),grow=v=>real?v/f*Math.pow(1.07/1.03,yrs):v*Math.pow(1.07,yrs),keep=p.age<59.5?0.7:0.8,k401ok=p.k401>100;
if(c.layoff){const cut=0.35*p.life,mos=p.needs>0?p.cash/p.needs:0;
return [{v:'save',label:'Live on your savings',hint:mos<0.1?'Your savings are nearly empty, so most of it lands on the credit card.':`They cover about ${mos.toFixed(1)} months of bills. After that, the credit card.`,why:'This is what an emergency fund is for. The bigger your cushion, the less a layoff hurts.'},
{v:'cut',label:'Cut spending by a third while you look',hint:`About ${money(cut,f)} less a month on everyday life`,why:'Fewer nights out and cheaper groceries make your savings last longer, so less ends up on the card.'},
{v:'k401',label:'Use your 401(k) to pay the bills',off:!k401ok,hint:k401ok?`You lose about ${Math.round((1-keep)*100)}% of what you take out to the penalty and taxes`:'You don\'t have 401(k) money to use yet',why:k401ok?'It keeps the card clean, but early withdrawals are expensive, and that money stops growing for retirement.':''}]}
const pay=ev.amt,po=minPayoff(pay,p.apr||0.24),room=Math.max(0,p.lim-p.card),gross=pay/keep;
return [{v:'save',label:'Pay from savings',hint:p.cash>=pay?`Uses ${money(pay,f)} of your ${money(p.cash,f)} savings`:p.cash<1?`No savings to use, so all ${money(pay,f)} goes on your card`:`Uses all ${money(p.cash,f)} of your savings, and the other ${money(pay-p.cash,f)} goes on your card`,why:'This is what an emergency fund is for. Your cushion is smaller until you rebuild it.'},
{v:'cut',label:'Pay from savings, then cut back to rebuild',hint:`Then spend about ${money(pay/6,f)} less a month for 6 months`,why:'Same as paying from savings, but you refill your cushion fast so you\'re ready for the next surprise.'},
{v:'card',label:'Put it on the credit card',hint:`At ${Math.round((p.apr||0.24)*100)}%, paying the minimum takes about ${(po.months/12).toFixed(1)} years and costs ${money(po.interest,f)} in interest`+(room<pay?(room<1?'. Your card is maxed out, so the rest would go unpaid and hurt your credit score':`. Your card only has ${money(room,f)} of room, so the rest would go unpaid`):''),why:'You keep your savings, but card interest is one of the most expensive ways to borrow.'},
{v:'k401',label:'Take it out of your 401(k)',off:!k401ok,hint:k401ok?`You'd take out about ${money(gross,f)} and lose ${money(gross-pay,f)} to the penalty and taxes`:'You don\'t have 401(k) money to use yet',why:k401ok?`That money would have grown to about ${money(grow(gross),real?1:0)} by 65${real?" in today's dollars":''}.`:''}]}
function renderSurprise(el){const S=G.surprise;if(!S){G.phase='decide';return renderDecide(el)}
const ev=S.ev,c=ev.c,p=S.pre,f=p.f,opts=surpriseOptions(S);
el.innerHTML=`<section class="panel stack surprise"><div class="sec-head"><span class="badge warn">${ic('bolt')}</span><div><span class="eyebrow">Age ${Math.floor(p.age)} · something just happened</span><h2>${c.title}</h2></div></div>
<p class="lede">${c.layoff?`You'll go about <strong>${ev.months} months</strong> without a paycheck while you look for a new job.`:`It costs <strong>${money(ev.amt,f)}</strong>${c.med?' after your health plan pays its part':''}, and it has to be paid now.`}</p>
<div class="stats"><div class="stat"><small>Savings</small><span class="money">${money(p.cash,f)}</span></div><div class="stat"><small>Credit card</small><span class="money">${money(p.card,f)} <small>of ${money(p.lim,f)}</small></span></div><div class="stat"><small>401(k)</small><span class="money">${money(p.k401,f)}</span></div></div>
<fieldset class="q"><legend>How do you handle it?</legend><div class="opts">${opts.map((o,k)=>`<label class="opt ${o.off?'off':''}"><input type="radio" name="sp" id="sp-${k}" value="${o.v}" ${o.off?'disabled':''}><b>${o.label}</b><span class="hint">${o.hint}</span></label>`).join('')}</div></fieldset>
<div id="spWhy" class="explain"><div class="muted">Pick one to see the tradeoff.</div></div>
<div class="btns"><button class="btn" id="spGo" disabled style="opacity:.5">Handle it and keep living ${ic('arrow')}</button><button class="btn ghost" id="spBack">Back to my choices</button></div>
<p class="muted" style="font-size:var(--fs-sm)">Real emergencies don't wait for a good time. How you pay for them matters as much as what they cost.</p></section>`;
el.querySelectorAll('input[name=sp]').forEach(i=>i.addEventListener('change',()=>{const o=opts.find(x=>x.v===i.value);$('spWhy').innerHTML=`<div class="cost"><span class="eyebrow">The tradeoff</span>${o.why||o.hint}</div>`;const g=$('spGo');g.disabled=false;g.style.opacity=''}));
$('spGo').onclick=()=>{const v=(el.querySelector('input[name=sp]:checked')||{}).value;if(!v)return;const s=G.s;(s.respond=s.respond||{})[S.m]=v;const {qs,st,ch}=S;G.surprise=null;doLive(qs,st,ch)};
$('spBack').onclick=()=>{G.pend=S.ch;G.surprise=null;G.phase='decide';render()};
}
// ---------- what if, from the debrief ----------
function whatIf(i,qid,v){const L=G.snaps||[],e=L[i];if(!e)return null;const o=JSON.parse(e.snap),c=o.s,blk=o.block;c.respond={...(G.s.respond||{})};
applyDecisions(c,blk.key,{...e.ch,[qid]:v});runStage(c,blk);
let nb,guard=0;while((nb=nextBlock(c))&&guard++<30){enterStage(c,nb.key);const later=L.find((x,k)=>k>i&&x.key===nb.key&&Math.abs(x.from-nb.from)<0.6);
const ch={};for(const q of decisions(c,nb.key))if(q.def!==undefined)ch[q.id]=q.def;if(later)Object.assign(ch,later.ch);
const HP={small:[190000,.035],starter:[260000,.10],bigger:[360000,.10]};if(HP[ch.home]&&!downPaymentPlan(c,HP[ch.home][0],HP[ch.home][1]).ok)ch.home='rent';
applyDecisions(c,nb.key,ch);runStage(c,nb)}
return c}
// ---------- three strategies: same life, same luck, different money habits ----------
const STRATS={invest:{label:'Investor',c:'var(--c-k401)',save:.25,k:.05},save:{label:'Saver',c:'var(--c-roth)',save:.25,k:.05},spend:{label:'Spender',c:'var(--c-brok)',save:.1,k:0}};
const RISKPREF={cons:'Risk averse',growth:'Risk neutral',aggr:'Risk loving'};
let STRAT_CACHE={key:null,map:{}};
function stratRun(mode,risk){const L=G.snaps||[];if(!L.length||!G.s)return null;
const ck=G.seed+'|'+L.length+'|'+G.turns.length+'|'+RET_MODE;if(STRAT_CACHE.key!==ck)STRAT_CACHE={key:ck,map:{}};const mk=mode+'|'+(risk||'');if(STRAT_CACHE.map[mk])return STRAT_CACHE.map[mk];
const o=JSON.parse(L[0].snap),P=G.s,cfg=STRATS[mode];let c=mode==='invest'?o.s:o.twin;if(!c)return null;
c.strat=mode;c.noInvest=mode!=='invest';c.respond={...(P.respond||{})};c.mirror={...(P.picks||{})};c.mirrorCars={...(P.carLog||{})};c.mirrorCarRates={...(P.carRates||{})};
const ov=(ch,key)=>{const qs=decisions(c,key).map(q=>q.id),x={...ch};
if(qs.includes('save'))x.save=cfg.save;if(qs.includes('k401'))x.k401=cfg.k;
if(mode==='invest'){if(qs.includes('risk'))x.risk=risk||'growth';if(qs.includes('fund'))x.fund='index';if(qs.includes('crash'))x.crash='stay';if(qs.includes('order'))x.order='smart'}
else{if(x.college==='529')x.college='pay';if(qs.includes('order'))x.order='cash'}
return x};
const fix=()=>{c.savePct=cfg.save;if(!c.retired)c.kPct=cfg.k;if(mode==='invest'){c.risk=risk||'growth';c.soldUntil=-1}else{c.order='cash'}};
let blk=o.block;const first={...(L[0].ch||{})};applyDecisions(c,blk.key,ov(first,blk.key));fix();runStage(c,blk);
let nb,guard=0;while((nb=nextBlock(c))&&guard++<30){enterStage(c,nb.key);const later=L.find((x,k)=>k>0&&x.key===nb.key&&Math.abs(x.from-nb.from)<0.6);
const ch={};for(const q of decisions(c,nb.key))if(q.def!==undefined)ch[q.id]=q.def;if(later)Object.assign(ch,later.ch);
const HP={small:[190000,.035],starter:[260000,.10],bigger:[360000,.10]};if(mode==='invest'&&HP[ch.home]&&!downPaymentPlan(c,HP[ch.home][0],HP[ch.home][1]).ok)ch.home='rent';
applyDecisions(c,nb.key,ov(ch,nb.key));fix();runStage(c,nb)}
STRAT_CACHE.map[mk]=c;return c}
function stratHTML(pref){const s=G.s;if(!G.snaps||!G.snaps.length)return '';
pref=pref||(RISKPREF[s.risk]?s.risk:'growth');
let R;try{R={invest:stratRun('invest',pref),save:stratRun('save'),spend:stratRun('spend')}}catch(e){return ''}
if(!R.invest||!R.save||!R.spend)return '';
const pts=h=>h.filter((p,k)=>k%12===0||k===h.length-1).map(p=>[p.age,real?p.nw/p.f:p.nw]);
const x1=Math.max(deathAge(s),...Object.values(R).map(deathAge));
const at=c=>nwAt(c.history,65),end=c=>Math.max(0,netWorth(c)+insPayout(c)),fun=c=>real?(c.totals.funR||0):(c.totals.fun||0);
const rows=Object.entries(R).map(([k,c])=>({k,c,a:at(c),fun:fun(c)}));
const inv=rows[0],sav=rows[1],spd=rows[2],f65=inv.a.f;
const extra=Math.max(0,spd.fun-inv.fun);
const row=x=>`<tr><th scope="row"><i class="sw" style="background:${STRATS[x.k].c}"></i>${STRATS[x.k].label}</th><td class="money">${money(x.a.nw,x.a.f,{short:true})}</td><td class="money">${money(x.fun,1,{short:true})}</td><td>${x.c.broke!=null?'At '+Math.floor(x.c.broke):'Never'}</td></tr>`;
return `<section class="panel stack" id="strats"><div class="sec-head"><span class="badge">${ic('trend')}</span><div><span class="eyebrow">Same life, three money habits</span><h2>Investor, Saver or Spender?</h2></div></div>
<p>Three people live your exact life: your job, pay, home, family, cars and surprises, with the same luck. Only what they do with money left after bills is different.</p>
<ul class="stratlist"><li><b><i class="sw" style="background:${STRATS.invest.c}"></i>Investor</b>: saves a quarter of what's left plus 5% of pay in the 401(k) for the full match, and invests it in a low-cost diversified mix. Stays invested in a crash.</li>
<li><b><i class="sw" style="background:${STRATS.save.c}"></i>Saver</b>: saves the same amount, but keeps all of it in a high-yield savings account at ${retTxt(C.CASH)}. No 401(k), so no match.</li>
<li><b><i class="sw" style="background:${STRATS.spend.c}"></i>Spender</b>: saves only 10% of what's left, keeps it in savings, and spends the rest on going out, trips and upgrades.</li></ul>
<div class="riskpref" role="group" aria-label="Investor's risk preference"><span class="rp-h">Investor's risk preference</span>${Object.entries(RISKPREF).map(([k,l])=>`<button type="button" class="rp${k===pref?' on':''}" data-rp="${k}" aria-pressed="${k===pref}">${l}<small>${RISK[k].label}, ${Math.round(mixAt(30,k).w*100)}% stocks</small></button>`).join('')}</div>
${lineChart([{pts:pts(R.invest.history),c:STRATS.invest.c},{pts:pts(R.save.history),c:STRATS.save.c},{pts:pts(R.spend.history),c:STRATS.spend.c},{pts:pts(s.history),c:'var(--muted)',dash:true}],s.startAge,x1,{w:640,h:280,label:'Net worth of the three strategies by age'})}
<div class="legend"><span style="--c:${STRATS.invest.c}">Investor</span><span style="--c:${STRATS.save.c}">Saver</span><span style="--c:${STRATS.spend.c}">Spender</span><span style="--c:var(--muted)">You</span></div>
<div class="tblwrap"><table class="strattbl"><thead><tr><th scope="col">Strategy</th><th scope="col">At 65</th><th scope="col">Extras spent</th><th scope="col">Ran out</th></tr></thead><tbody>${rows.map(row).join('')}<tr class="you"><th scope="row"><i class="sw" style="background:var(--muted)"></i>You</th><td class="money">${money(at(s).nw,at(s).f,{short:true})}</td><td class="money">${money(fun(s),1,{short:true})}</td><td>${s.broke!=null?'At '+Math.floor(s.broke):'Never'}</td></tr></tbody></table></div>
<p class="tip"><b>The opportunity cost:</b> the Spender enjoyed about <strong>${money(extra,1)}</strong> more on going out, trips and upgrades over their life, and had <strong>${money(Math.max(0,inv.a.nw-spd.a.nw),f65)}</strong> less than the Investor at 65. The Saver saved just as much as the Investor but ended <strong>${money(Math.max(0,inv.a.nw-sav.a.nw),f65)}</strong> behind, because savings barely beat inflation and there was no 401(k) match. ${R.spend.broke!=null?`The Spender ran out of money at ${Math.floor(R.spend.broke)}.`:''}</p>
<p class="muted" style="font-size:var(--fs-sm)">Switch the Investor's risk preference to see how a calmer or bolder mix changes the result with the same markets. Amounts at 65 are ${real?"in today's dollars":'in future dollars'}; returns use the ${RET_MODE==='hist'?'historical':'cautious'} market assumption you picked.</p></section>`}
function fixMoves(){const s=G.s,L=G.snaps||[];if(!s||!L.length)return [];const chs=L.map(x=>x.ch||{}),M=[];
if((s.totals.missedMatch||0)>1)M.push({id:'match',label:'take the full 401(k) match'});
if(chs.some(c=>c.fund==='managed')||(s.fee||0)>=.005)M.push({id:'fees',label:'use a low-cost index fund'});
if(chs.some(c=>c.crash==='sell'))M.push({id:'crash',label:'stay invested in the crash'});
if(chs.some(c=>c.order==='cash')||(s.totals.cardInterest||0)>1000)M.push({id:'order',label:'keep a cushion, clear the card, then invest the rest'});
if(chs.some(c=>c.risk==='cons')&&s.startAge<45)M.push({id:'risk',label:'pick the risk level typical for your age'});
return M}
function fixRun(M){const L=G.snaps||[];if(!L.length||!M.length)return null;const ck='fix|'+M.map(m=>m.id).join(',');
const key=G.seed+'|'+L.length+'|'+G.turns.length+'|'+RET_MODE;if(STRAT_CACHE.key!==key)STRAT_CACHE={key,map:{}};if(STRAT_CACHE.map[ck])return STRAT_CACHE.map[ck];
const o=JSON.parse(L[0].snap),P=G.s;let c=o.s;const has=id=>M.some(m=>m.id===id);
c.strat='fix';c.respond={...(P.respond||{})};c.mirror={...(P.picks||{})};c.mirrorCars={...(P.carLog||{})};c.mirrorCarRates={...(P.carRates||{})};
const ov=(ch,key)=>{const qs=decisions(c,key).map(q=>q.id),x={...ch};
if(has('match')&&qs.includes('k401'))x.k401=Math.max(+x.k401||0,C.MATCH);
if(has('fees')&&qs.includes('fund')&&x.fund==='managed')x.fund='index';
if(has('crash')&&qs.includes('crash'))x.crash='stay';
if(has('order')&&qs.includes('order')&&(x.order==='cash'||x.order==null))x.order='smart';
if(has('risk')&&qs.includes('risk')&&x.risk==='cons')x.risk=riskSuggest(c.age).k;
return x};
const fix=()=>{if(has('match')&&!c.retired&&c.career)c.kPct=Math.max(c.kPct||0,C.MATCH);if(has('order')&&c.order==='cash')c.order='smart';if(has('crash'))c.soldUntil=-1};
let blk=o.block;applyDecisions(c,blk.key,ov({...(L[0].ch||{})},blk.key));fix();runStage(c,blk);
let nb,guard=0;while((nb=nextBlock(c))&&guard++<30){enterStage(c,nb.key);const later=L.find((x,k)=>k>0&&x.key===nb.key&&Math.abs(x.from-nb.from)<0.6);
const ch={};for(const q of decisions(c,nb.key))if(q.def!==undefined)ch[q.id]=q.def;if(later)Object.assign(ch,later.ch);
const HP={small:[190000,.035],starter:[260000,.10],bigger:[360000,.10]};if(HP[ch.home]&&!downPaymentPlan(c,HP[ch.home][0],HP[ch.home][1]).ok)ch.home='rent';
applyDecisions(c,nb.key,ov(ch,nb.key));fix();runStage(c,nb)}
STRAT_CACHE.map[ck]=c;return c}
function payoffHTML(){const s=G.s;let M=[],c=null;try{M=fixMoves();c=fixRun(M)}catch(e){c=null}
const a=nwAt(s.history,65);
if(!M.length||!c)return `<div class="payoff ok">${ic('star')}<div><b>You already made the big moves.</b> You took the full match, kept fees low and stayed invested. The steps below are about keeping it that way in real life.</div></div>`;
const b=nwAt(c.history,65),gain=b.nw/b.f-a.nw/a.f,list=M.map(m=>m.label),txt=list.length>1?list.slice(0,-1).join(', ')+' and '+list[list.length-1]:list[0];
if(gain<1000)return `<div class="payoff ok">${ic('star')}<div><b>Your big moves were already close to right.</b> Fixing the rest (${txt}) would have changed your net worth at 65 by less than $1,000.</div></div>`;
return `<div class="payoff">${ic('trend')}<div><span class="payoff-k">What these moves are worth</span><b class="payoff-n money">${money(real?gain:gain*a.f,real?1:1)}</b><p>If you had made ${M.length===1?'this move':'these moves'} from the start (${txt}), the exact same life with the same luck would have left you about <strong>${money(real?gain:gain*a.f,1)}</strong> more at 65${real?", in today's dollars":''}. That's what the steps below are worth in the game. In real life, the same habits work the same way.</p></div></div>`}
function whatIfHTML(c,label){const s=G.s,pts=h=>h.filter((p,k)=>k%12===0||k===h.length-1).map(p=>[p.age,real?p.nw/p.f:p.nw]);
const a65=nwAt(s.history,65),b65=nwAt(c.history,65),endA=netWorth(s)+insPayout(s),endB=netWorth(c)+insPayout(c),dA=deathAge(s),dB=deathAge(c);
const x1=Math.max(dA,dB);
return `<div class="whatif"><p><strong>If you had picked “${label}”:</strong> ${Math.abs(b65.nw/b65.f-a65.nw/a65.f)<500?'you\'d have the same at 65':`at 65 you'd have <strong>${money(b65.nw,b65.f)}</strong> instead of ${money(a65.nw,a65.f)}`}${endA/s.infl<1000&&endB/c.infl<1000?`. Either way, your savings would run out before the end of your life${c.broke!=null&&s.broke!=null&&Math.floor(c.broke)!==Math.floor(s.broke)?`: at ${Math.floor(c.broke)} instead of ${Math.floor(s.broke)}`:''}.`:Math.abs(endB/c.infl-endA/s.infl)<500?`, and you'd leave about the same, ${money(Math.max(0,endA),s.infl)}.`:`, and you'd leave <strong>${money(Math.max(0,endB),c.infl)}</strong> instead of ${money(Math.max(0,endA),s.infl)}.${c.broke!=null&&s.broke==null?` Your savings would run out at ${Math.floor(c.broke)}.`:c.broke==null&&s.broke!=null?' Your savings would last your whole life.':''}`}${dB!==dA?` You'd live to about ${dB} instead of ${dA}.`:''}</p>
${lineChart([{pts:pts(s.history),c:'var(--accent)',fill:true},{pts:pts(c.history),c:'var(--gold)',dash:true}],s.startAge,x1,{label:'Your life compared with the what-if'})}
<div class="legend"><span style="--c:var(--accent)">Your life</span><span style="--c:var(--gold)">With “${label}”</span></div>
<p class="muted" style="font-size:var(--fs-sm)">Same luck: the same markets, surprises and health, with your later choices kept where they still apply. That's why it can differ from the average-market estimate above.</p></div>`}
function heroArt(){
const cv=$('heroArt');if(!cv||!cv.getContext)return;const r=cv.getBoundingClientRect(),dpr=window.devicePixelRatio||1;
cv.width=r.width*dpr;cv.height=r.height*dpr;const x=cv.getContext('2d');x.scale(dpr,dpr);const W=r.width,H=r.height;
for(let k=0;k<5;k++){x.beginPath();const base=H*(0.95-k*0.06),g=1.5+k*0.5;
for(let i=0;i<=60;i++){const t=i/60,y=base-Math.pow(t,g)*H*(0.55+k*0.06)+Math.sin(t*12+k)*4;i?x.lineTo(t*W,y):x.moveTo(0,y)}
x.strokeStyle=k===4?'rgba(230,180,78,.9)':'rgba(160,220,195,'+(0.18+k*0.1)+')';x.lineWidth=k===4?2.5:1.5;x.stroke()}
}
(function(){const b=$('resetAll'),n=$('resetNote');let armed=null;
b.onclick=()=>{if(!armed){b.textContent='Tap again to start over';b.classList.add('warn');n.textContent='This erases your saved game. Tap again within 5 seconds to confirm.';armed=setTimeout(()=>{armed=null;b.textContent='Start over';b.classList.remove('warn');n.textContent='Clears your game and numbers and goes back to the beginning.'},5000);return}
clearTimeout(armed);armed=null;b.textContent='Start over';b.classList.remove('warn');n.textContent='Clears your game and numbers and goes back to the beginning.';
G.auto=false;G.fast=false;clearSave();closeTurn();
Object.assign(G,{snaps:[],phase:'setup',inp:{...DEFAULTS,goals:[]},s:null,twin:null,block:null,done:[],log:[],turns:[],result:null,enter:null,prevNW:null,undo:null,edited:false,lessonI:0,snapOpen:null,seed:Math.floor(Math.random()*1e9)});
render();window.scrollTo({top:0,behavior:'smooth'})}})();
$('stopAuto').onclick=()=>{G.auto=false;render()};
$('goHome').onclick=goHome;
$('goGloss').onclick=()=>openGloss();
function realHelpHTML(){const s=G.s&&G.phase!=='setup'&&G.phase!=='home'&&G.phase!=='glossary'?G.s:null,on=$('realToggle').checked;
return `<p><b>Prices go up over time.</b> That's inflation, and the game assumes about 3% a year. So a dollar 40 years from now buys much less than a dollar today: something that costs $100 now will cost about $326 then.</p>
<p><b>Today's dollars (on)</b> shrinks every future amount back to what it would buy right now. $1 million at 65 means the same as $1 million today, so you can compare any two ages fairly. <b>Future dollars (off)</b> shows the actual numbers you'd see on a bank statement in that year: bigger, but each one buys less.</p>
${s&&s.infl>1.01?`<p><b>In your game:</b> you're ${Math.floor(s.age)}, and prices are ${s.infl.toFixed(2)} times what they were when you started. Your net worth is ${money(netWorth(s)/s.infl,0)} in today's dollars, or ${money(netWorth(s),0)} in future dollars.</p>`:''}
<p>Most people find today's dollars easier to understand, which is why it's on by default. It changes only how numbers are shown, never what you actually have.</p>`}
$('realInfo').onclick=()=>{const h=$('realHelp'),b=$('realInfo'),open=h.hidden;if(open)h.innerHTML=realHelpHTML();h.hidden=!open;b.setAttribute('aria-expanded',open);$('realInfoT').textContent=open?'Hide explanation':'What does this mean?'};
$('realToggle').addEventListener('change',()=>{const h=$('realHelp');if(!h.hidden)setTimeout(()=>{h.innerHTML=realHelpHTML()},0)});
$('skipAuto').onclick=()=>{G.fast=true;autoStep()};
$('contAuto').onclick=()=>autoContinue();
render();heroArt();window.addEventListener('resize',heroArt);
// ---------- save to a file, open a saved file, warn before closing ----------
let SAVE_DL=null;try{if(window.claude&&typeof window.claude.use==='function')window.claude.use('downloads').then(d=>{SAVE_DL=d||null},()=>{})}catch(e){}
const FILE_APP='the-long-game',FILE_PHASES=['setup','decide','result','final','debrief'];
function workSig(){try{return [G.phase==='glossary'?G.backTo:G.phase,(G.turns||[]).length,G.s?G.s.month:0,JSON.stringify(G.inp)].join('|')}catch(e){return ''}}
let SAVED_SIG=null;
function hasWork(){return !G.auto&&(!!G.s||!!G.edited)}
function unsaved(){return hasWork()&&workSig()!==SAVED_SIG}
function fileToast(msg,bad){let t=$('fileToast');if(!t){t=document.createElement('div');t.id='fileToast';t.setAttribute('role','status');t.setAttribute('aria-live','polite');document.body.appendChild(t)}
t.textContent=msg;t.className=bad?'bad show':'show';clearTimeout(t._h);t._h=setTimeout(()=>{t.className=''},bad?9000:6000)}
function saveToFile(){
if(G.auto){fileToast('The sample life can\'t be saved. Start your own life to save it.',true);return}
if(!hasWork()){fileToast('Nothing to save yet. Enter your numbers or start a life first.',true);return}
const mid=G.phase==='surprise',game=JSON.parse(snapG());if(mid)game.phase='decide';
const d=new Date(),pad=n=>String(n).padStart(2,'0'),data={app:FILE_APP,version:1,saved:d.toISOString(),game};
const name=`the-long-game-${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}.json`,text=JSON.stringify(data);
const done=()=>{SAVED_SIG=workSig();fileToast(mid?'Saved to a file. Because a surprise is still waiting for your answer, the file picks up at the start of these years.':'Saved to a file. Use "Open a saved file" later to pick up where you left off.')};
const viaLink=()=>{const a=document.createElement('a');a.textContent='Download saved game';a.setAttribute('aria-hidden','true');a.style.display='none';a.href=URL.createObjectURL(new Blob([text],{type:'application/json'}));a.download=name;document.body.appendChild(a);a.click();setTimeout(()=>{URL.revokeObjectURL(a.href);a.remove()},1500);done()};
if(SAVE_DL)SAVE_DL.save({filename:name,data:text}).then(done,e=>{if(e&&e.code==='declined')fileToast('The file wasn\'t saved. Tap "Save to a file" again whenever you\'re ready.',true);else if(e&&e.code==='rate_limited')fileToast('A save window is already open. Finish that one first.',true);else viaLink()});
else viaLink()}
function validSave(o){const g=o&&o.app===FILE_APP&&o.game;if(!g||typeof g!=='object')return false;
if(!g.inp||typeof g.inp!=='object'||typeof g.inp.age!=='number')return false;
if(!FILE_PHASES.includes(g.phase))return false;
if(g.phase!=='setup'){const s=g.s;if(!s||typeof s!=='object'||typeof s.age!=='number'||!Array.isArray(s.history)||!s.history.length||!Array.isArray(g.turns)||!g.twin||typeof g.twin!=='object'||!g.block)return false}
return true}
function openFromText(txt){let o=null;try{o=JSON.parse(txt)}catch(e){}
if(!validSave(o)){fileToast('That file isn\'t a saved game from The Long Game, so nothing changed. Your current game is still here.',true);return false}
const back={snap:snapG(),undo:G.undo,snaps:G.snaps,backTo:G.backTo,auto:G.auto,edited:G.edited};
try{restoreG(o.game);G.undo=null;G.snaps=[];G.backTo=null;G.auto=false;G.edited=true;render();window.scrollTo({top:0});SAVED_SIG=workSig();saveGame();fileToast('Saved game opened. Pick up where you left off.');return true}
catch(e){try{restoreG(JSON.parse(back.snap));G.undo=back.undo;G.snaps=back.snaps;G.backTo=back.backTo;G.auto=back.auto;G.edited=back.edited;render()}catch(e2){}
fileToast('That file couldn\'t be opened, so nothing changed. Your current game is still here.',true);return false}}
let PICK_ARMED=null;
function pickFile(btn){
if(unsaved()&&!PICK_ARMED){const old=btn.innerHTML;btn.textContent='Tap again to open a file';btn.classList.add('warn');
fileToast('You have changes you haven\'t saved to a file. Opening a file replaces your current game. Tap again to continue, or save first.',true);
PICK_ARMED=setTimeout(()=>{PICK_ARMED=null;btn.innerHTML=old;btn.classList.remove('warn')},6000);return}
if(PICK_ARMED){clearTimeout(PICK_ARMED);PICK_ARMED=null;btn.classList.remove('warn');btn.textContent=btn.id==='hOpen'?'Open a saved game file':'Open a saved file'}
const inp=$('fileIn');inp.value='';inp.click()}
$('fileIn').addEventListener('change',e=>{const f=e.target.files&&e.target.files[0];if(!f)return;
if(f.size>20*1024*1024){fileToast('That file is too big to be a saved game, so nothing changed. Your current game is still here.',true);return}
const r=new FileReader();r.onload=()=>openFromText(String(r.result||''));r.onerror=()=>fileToast('That file couldn\'t be read, so nothing changed. Your current game is still here.',true);r.readAsText(f)});
$('saveFile').onclick=saveToFile;
$('openFile').onclick=()=>pickFile($('openFile'));
window.addEventListener('beforeunload',e=>{if(unsaved()){e.preventDefault();e.returnValue='';return ''}});
SAVED_SIG=workSig();
</script>
</html>
Websites this page contacts when it runs — fonts, chart libraries, data. Found by reading its source.
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 Will Frey. Licensed under the MIT License. Published on Globefin.
Provided as is, without warranty. Any external libraries it loads keep their own licences. Terms →
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.