← Demos
Web Pages · Demos

School's Out

by Carter Overtoom Nov 19, 2026 8 views 301.1 KB
Sandbox · school-s-out · no access to your account
View source — the whole page is this one file
<!-- Copyright (c) 2026 Carter Overtoom. Released under the MIT License. -->
<!doctype html>
<!--
School's Out, version 1.0
Who it's for: Kentucky public school teachers and TRS-covered university faculty
planning when they can afford to retire.

For educational use only. These are estimates, not financial, investment, tax,
legal, or benefits advice. Only the Teachers' Retirement System of Kentucky (TRS)
can give official benefit figures.

MIT License

Copyright (c) 2026 Carter Overtoom

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

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

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>School's Out</title>
<meta name="description" content="For Kentucky teachers and TRS-covered university faculty: see when you can retire, what TRS, Social Security, and savings could pay, and how to close any gap.">
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='14' fill='%23272a74'/%3E%3Cpath d='M32 12c-10 0-15 8-15 18 0 8-3 12-6 15h42c-3-3-6-7-6-15 0-10-5-18-15-18z' fill='%23f4c430'/%3E%3Ccircle cx='32' cy='50' r='5' fill='%23f4c430'/%3E%3C/svg%3E">
<style>
:root{color-scheme:light dark;
 --bg:#faf8f4;--paper:#fff;--wash:#f3f0e8;--ink:#24242a;--soft:#5c5a55;--line:#d9d5ca;
 --board:#272a74;--on-board:#fff;--bus:#f4c430;--on-bus:#2a2100;--apple:#a92f27;--apple-wash:#f9e7e4;--leaf:#1f6b47;--leaf-wash:#e6f1ea;--blue:#2733a6;--chart:#272a74;
 --head:Arial,Helvetica,sans-serif;--body:Arial,Helvetica,sans-serif}
@media (prefers-color-scheme:dark){:root{--bg:#12131f;--paper:#1c1e30;--wash:#262942;--ink:#eceef8;--soft:#adb2c9;--line:#3b3f5e;--board:#1a1d5a;--on-board:#eceef8;--apple:#f39a90;--apple-wash:#3b211e;--leaf:#83d9a4;--leaf-wash:#17382a;--blue:#aab6ff;--chart:#8f95d0}}
*{box-sizing:border-box}
html{scroll-behavior:smooth;scroll-padding-top:70px}
body{margin:0;background:var(--bg);color:#22232b;font:17px/1.55 var(--body)}
@media (prefers-color-scheme:dark){body{color:var(--ink)}}
h1,h2,h3,.bigline{color:var(--ink)}
a{color:var(--blue)}
button,input,select{font:inherit;color:inherit}
:focus-visible{outline:3px solid var(--blue);outline-offset:2px}
[tabindex="-1"]:focus,[tabindex="-1"]:focus-visible{outline:none}
h1,h2,h3{font-family:var(--head);line-height:1.15}
h2{margin:0 0 6px;font-size:30px}
h3{margin:0 0 6px;font-size:20px}
.wrap{max-width:1280px;margin-inline:auto;padding-inline:20px}
body[data-screen=welcome] #wizard,body[data-screen=welcome] #resultsView,body[data-screen=welcome] .r-only{display:none!important}
body[data-screen=wizard] .hero,body[data-screen=wizard] .why,body[data-screen=wizard] #resultsView,body[data-screen=wizard] .r-only{display:none!important}
body[data-screen=results] .hero,body[data-screen=results] .why,body[data-screen=results] #wizard{display:none!important}
.big-btn{display:block;width:100%;min-height:52px;padding:0 18px;background:var(--bus);color:#1d1f4d;border:0;border-radius:3px;font-size:18px;font-weight:700;cursor:pointer}
.big-btn:hover{filter:brightness(.93)}
.link-btn[hidden]{display:none!important}
.link-btn{display:block;width:100%;min-height:44px;margin-top:6px;background:none;border:0;color:var(--blue);text-decoration:underline;font-weight:600;cursor:pointer}
.wizard{max-width:640px;padding-block:44px 80px}
.wizard h1{font-size:clamp(28px,4vw,38px);margin:4px 0 18px}
.wizard h1:focus{outline:0}
.progress{margin:0;color:var(--soft);font-weight:600}
.wp-bar{display:flex;gap:6px;margin:6px 0 6px}.wp-lab{display:flex;gap:6px;margin:0 0 16px}.wp-lab b{flex:1;font-size:13px;font-weight:400;color:var(--soft)}.wp-lab b.now{color:var(--ink);font-weight:700}
@media (max-width:600px){.wp-lab b:not(.now){visibility:hidden}}.wp-bar i{flex:1;height:8px;border-radius:4px;background:var(--line)}.wp-bar i.done{background:var(--board)}.wp-bar i.now{background:var(--bus)}
.wiz-fields{display:grid;gap:16px}
.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
.imp{margin:0 0 18px;padding:10px 0;border-top:1px solid var(--line);border-bottom:1px solid var(--line)}
.imp summary{cursor:pointer;font-weight:700;color:var(--blue)}
.imp p{margin:8px 0;font-size:15px}
.imp input[type=file]{display:block;margin:8px 0;max-width:100%}
.imp textarea{margin-top:4px}
.wiz-fields .f{font-size:16px}
.wiz-fields input[type=number],.wiz-fields input[type=text],.wiz-fields select{min-height:52px;font-size:18px}
.wiz-fields small{font-size:14px}
.radio-card{display:flex;gap:12px;align-items:flex-start;padding:14px;background:var(--paper);border:2px solid var(--line);border-radius:8px;cursor:pointer;font-weight:400}
.radio-card:has(input:checked){border-color:var(--chart);background:var(--wash)}
.radio-card input{flex:none;width:20px;height:20px;margin:2px 0 0;accent-color:var(--chart)}
.radio-card strong{display:block}
.err-text{min-height:24px;margin:10px 0 0;color:var(--apple);font-weight:600}
.wiz-fields select{min-height:52px;font-size:17px}
#wPre83Wrap[hidden]{display:none}
.fas-toggle{width:auto;margin:0;padding:0;text-align:left;font-size:15px}
#wFasArea[hidden],#wFasWrap[hidden],#wTypeWrap[hidden]{display:none}
#wTypeWrap .fas-toggle{margin-top:6px}
#wFasWrap{margin-top:12px}
.wiz-actions{display:grid;grid-template-columns:120px minmax(0,1fr);gap:10px;margin-top:10px}
.wiz-actions button:first-child{min-height:52px;background:var(--paper);border:1px solid var(--line);border-radius:8px;cursor:pointer}
body[data-ex="1"] #saveBtn{display:none!important}
#modeNote{margin-bottom:12px}
#modeNote:empty{display:none}
#modeNote>div{padding:12px 14px;background:var(--paper);border:1px solid var(--line)}
#modeNote button{min-height:40px;margin-left:6px;padding:0 12px;background:var(--bus);color:#1d1f4d;border:0;border-radius:3px;font-weight:700;cursor:pointer}
#modeNote button.inline-link{margin-left:10px;padding:0;background:none;color:var(--blue);text-decoration:underline;font-weight:600}
.skip{position:absolute;left:-999px;top:8px;z-index:40;padding:10px 14px;background:var(--bus);color:var(--on-bus);border-radius:6px}
.skip:focus{left:12px}
.bar{position:sticky;top:0;z-index:30;background:var(--board);color:var(--on-board)}
.bar-inner{display:flex;flex-wrap:wrap;align-items:center;gap:8px;padding-block:8px}
.brand{display:flex;align-items:center;gap:8px;margin-right:auto;font:700 22px var(--head);color:inherit;text-decoration:none}
.brand small{font:400 14px var(--body);opacity:.85}
.brand svg{width:30px;height:30px}
.bar button{min-height:40px;padding:0 13px;background:transparent;border:1px solid currentColor;border-radius:999px;cursor:pointer;font-size:14px}
.bar button:hover{background:rgba(255,255,255,.14)}
.bar .w-only{display:none}body[data-screen=welcome] .bar .w-only{display:inline-block}
.bar button.main{background:var(--bus);color:var(--on-bus);border-color:var(--bus);font-weight:700}
.bar :focus-visible{outline-color:var(--bus)}
.bar-inner{position:relative}
.more-menu{display:flex;flex-wrap:wrap;gap:8px}
.bar .more-btn{display:none}
body:not([data-screen=welcome]):not([data-screen=wizard]) .bar .more-btn{display:inline-flex;align-items:center;justify-content:center;min-width:44px;font-size:1.5rem;line-height:1;padding:7px 12px}
body:not([data-screen=welcome]):not([data-screen=wizard]) .more-menu{display:none;position:absolute;right:max(16px,env(safe-area-inset-right,0px));top:calc(100% - 4px);flex-direction:column;flex-wrap:nowrap;align-items:stretch;gap:6px;min-width:230px;padding:10px;background:var(--board);border:1px solid rgba(255,255,255,.18);border-radius:10px;box-shadow:0 14px 28px -10px rgba(0,0,0,.45);z-index:40}
body:not([data-screen=welcome]):not([data-screen=wizard]) .bar.open .more-menu{display:flex}
.more-menu button{text-align:left}
@media (max-width:1000px){.brand small{display:none}}
@media (max-width:700px){.bar .wide-only{display:none}.bar button{padding:0 12px}}
.hero{position:relative;background:var(--wash);overflow:hidden}
.hero-grid{position:relative;z-index:2;display:grid;grid-template-columns:minmax(0,1fr) minmax(0,340px);gap:56px;padding-block:44px 8px;align-items:start}
.hero{display:flex;flex-direction:column;min-height:calc(100vh - var(--barh,56px));min-height:calc(100svh - var(--barh,56px))}
.hero-grid{flex:none}
.hero-scene{flex:1 0 auto;height:max(120px,10vw);margin-top:20px;display:flex}
.hero-scene .lake-art{flex:1;height:auto}
@media (min-width:701px) and (max-height:800px){.hero-grid{padding-block:26px 4px}.hero h1.q{font-size:clamp(38px,4.6vw,56px);margin-bottom:10px}.hero-sub{margin-top:10px}.hero-actions{margin-top:12px}.ex-card{padding-block:12px 4px}}
@media (min-width:701px) and (max-height:720px){.hero h1.q{font-size:clamp(36px,4vw,48px)}.hero-grid{padding-top:14px}}
.inline-link{padding:0;background:none;border:0;color:var(--blue);text-decoration:underline;font:inherit;cursor:pointer}
.hero-free{margin:14px 0 0;font-weight:600;color:var(--ink)}
.hero-scene .lake-art{display:block;width:100%;height:100%}
.hero-sub{margin:18px 0 0;font-size:18px;color:var(--soft)}
.hero-actions{display:flex;flex-wrap:wrap;align-items:center;gap:8px 20px;margin-top:18px}
.hero-actions .big-btn{width:auto;padding:0 30px}
.hero-actions .link-btn{width:auto;margin:0;padding:0 4px}
.lake-art{display:block;width:100%;height:100%}
@media (prefers-color-scheme:dark){.lake-art{filter:brightness(.74) saturate(.9)}}
.hero h1{margin:0;font-size:clamp(46px,7vw,84px);font-weight:700;letter-spacing:-.015em}
.why{padding-block:26px}
.why-text{margin:10px 0 0;max-width:46em;font-size:18px}
.teacher-voices{margin-top:40px;padding:28px;background:#d3d5ea;border-radius:6px}
.teacher-voices h3{margin:0 0 18px;color:#24242a;font-size:22px}
.quote-track{display:grid;grid-template-columns:repeat(3,1fr);gap:16px}
.teacher-quote{margin:0;padding:24px;background:#fff;color:#24242a;border:1px solid #c2c5e2;border-radius:4px;display:flex;flex-direction:column;justify-content:space-between}
.teacher-quote blockquote{margin:0;padding:0;font-style:normal;font-size:17px;line-height:1.6;color:#24242a}
.teacher-quote figcaption{margin-top:22px;color:#555;font-size:14px;font-weight:600}
@media(max-width:800px){.teacher-voices{padding:22px 16px}.teacher-voices h3{font-size:20px;margin-bottom:14px}.quote-track{grid-template-columns:1fr;gap:12px}.teacher-quote{padding:20px}}
@media(prefers-reduced-motion:reduce){.quote-track{scroll-behavior:auto}}
.asks{margin-top:26px;max-width:820px}.asks h3{margin-bottom:8px}
.asks dl{margin:0;border-top:1px solid var(--line)}
.asks dl>div{display:grid;grid-template-columns:minmax(0,15em) 1fr;gap:4px 24px;align-items:baseline;padding:12px 14px;border-bottom:1px solid var(--line);background:var(--paper)}
.asks dt{font-size:15px;color:var(--soft)}
.asks dd{margin:0;font:600 19px/1.35 var(--head);color:var(--ink)}
.asks dd span{display:block;font:400 13.5px/1.4 var(--body);color:var(--soft)}
.asks .us{background:var(--leaf-wash)}.asks .us dt{color:var(--leaf);font-weight:700}.asks .us dd{font-size:21px}
@media (max-width:700px){.asks dl>div{grid-template-columns:1fr}}
#message{position:sticky;top:60px;z-index:20}
#message:empty{display:none}
#message>div{margin-block:8px;padding:10px 14px;border-radius:6px;background:var(--leaf-wash);border:1px solid var(--leaf);box-shadow:0 4px 12px -8px #000}
#message>.err{border-color:var(--apple);background:var(--apple-wash)}
#message button{min-height:36px;margin-left:8px;padding:0 10px;background:var(--paper);border:1px solid var(--line);border-radius:6px;cursor:pointer}
.layout{display:flex;flex-direction:column;gap:20px;max-width:940px;padding-block:18px 40px}
.step{padding:18px 0;border-bottom:1px solid var(--line)}
.step>p{margin:0 0 12px;font-size:14px;color:var(--soft)}
.full{grid-column:1/-1}
.f{display:flex;flex-direction:column;gap:4px;min-width:0;font-size:14px;font-weight:600}
.f small{font-weight:400;color:var(--soft);line-height:1.35}
input[type=number],input[type=text],input[type=search],select{width:100%;min-width:0;min-height:44px;padding:0 10px;background:var(--paper);border:1px solid var(--line);border-radius:6px;font-weight:400;font-size:16px}
.affix{display:flex;align-items:center;background:var(--paper);border:1px solid var(--line);border-radius:6px}
.affix:focus-within{outline:3px solid var(--blue);outline-offset:2px}
.affix input{border:0;background:transparent;outline:0}
.affix span{flex:none;padding:0 8px;color:var(--soft);font-weight:400;font-size:14px}
.affix .pre{padding-right:0;font-size:16px}
.check-line{display:flex;align-items:flex-start;gap:10px;min-height:40px;font-size:15px;font-weight:400;cursor:pointer}
.check-line input{flex:none;width:20px;height:20px;margin:2px 0 0;accent-color:var(--leaf)}
details.more{margin-top:12px}
details.more summary{min-height:36px;cursor:pointer;font-weight:600;color:var(--blue);font-size:15px}
.inline-f{display:flex;flex-wrap:wrap;gap:12px;margin-bottom:10px}.inline-f .f{width:220px}
textarea{width:100%;padding:10px;background:var(--paper);border:1px solid var(--line);border-radius:6px;font:inherit;font-weight:400;color:inherit}
.note{margin:10px 0 0;font-size:15px;color:var(--soft)}
#results{min-width:0}
.board h1{color:inherit}
.board{position:relative;padding:24px 26px 34px;background:#1f4a3f;color:#f5f8f4;border:10px solid #8a5a33;border-radius:4px;box-shadow:inset 0 0 40px rgba(0,0,0,.28)}
.answer{margin:0;font:700 clamp(28px,3.6vw,44px)/1.15 var(--head);max-width:22em}
.chart-wrap{position:relative}
.tip{position:absolute;z-index:5;max-width:280px;padding:8px 10px;background:var(--paper);color:var(--ink);border:1px solid var(--ink);font-size:14.5px;line-height:1.4;pointer-events:none;box-shadow:0 8px 18px -12px rgba(0,0,0,.6)}
.tip[hidden]{display:none}
svg .guide{stroke:var(--ink);stroke-width:1.5;stroke-dasharray:3 3}
.tray{position:absolute;left:0;right:0;bottom:0;height:12px;background:#8a5a33}
.tray i{position:absolute;bottom:10px;width:34px;height:7px;border-radius:2px;background:#f7f5ec;right:40px}
.tray i+i{right:86px;width:24px;background:#e9e6da}
.bigline{margin:0;font:700 30px/1.15 var(--head)}
ul.tight{margin:8px 0 0;padding-left:20px;max-width:46em}
ul.tight li{margin:4px 0}
@media screen{#resultsView[data-plan=closed] #results>:not(#modeNote):not(#answerBox){display:none}
#resultsView[data-plan=closed]{display:block;max-width:820px}}
.slide{margin-top:20px;padding-top:16px;border-top:2px dashed rgba(245,248,244,.45)}
.slide label{display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;font-weight:600;color:#f5f8f4}
.slide strong{color:#f5f8f4;font:700 22px/1.2 var(--head)}.slide strong.ok,.board .answer.ok{color:#8fd3a8}.board .answer.mid{color:#ffe07a}.board .answer.bad{color:#f2b8a8}.slide strong.ok{color:#8fd3a8}.slide strong.mid{color:#ffe07a}.slide strong.bad{color:#f2b8a8}
#tryRetire{display:block;width:100%;height:44px;margin:6px 0 0;accent-color:#f5f8f4;cursor:grab}
#tryRetire:focus-visible{outline:2px solid #f5f8f4;outline-offset:2px}
.slide-ends{font-size:14px;color:#f5f8f4}
.slide-zones{display:flex;gap:3px;margin:0 10px;font-size:13px}
.slide-zones span{min-width:0;padding-top:5px;border-top:5px solid;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.zone-btn{padding:12px 0;background:none;border:0;color:inherit;font:inherit;text-decoration:underline dotted;text-underline-offset:3px;cursor:pointer;white-space:nowrap}
.zone-btn:focus-visible{outline:2px solid #f5f8f4;outline-offset:2px}
.zone-help{margin-top:12px;padding:12px 14px;background:rgba(245,248,244,.08);border-radius:6px;font-size:14px;line-height:1.5;color:#e8f0ea}
.zone-help[hidden]{display:none}
.zone-help p{margin:0}
.zone-help p+p{margin-top:6px}
.slide .zone-help strong{color:#fff;font:inherit;font-weight:700}
.z-cut{border-color:#f2b8a8!important;color:#f2c6b9}
.z-full{border-color:#8fd3a8!important;color:#b7e3c6}
.z-wait{border-color:#aebfb6!important;color:#d6e4dc}
.z-tiny .zone-btn{display:block;width:100%;min-height:16px}
.slide-nums{display:flex;justify-content:space-between;margin-top:4px}
input[type=number]{appearance:textfield;-moz-appearance:textfield}
input[type=number]::-webkit-inner-spin-button,input[type=number]::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}
.report{position:relative;margin-top:40px;padding:22px 22px 18px 58px;background:var(--paper);border:1px solid var(--line);border-radius:4px;background-image:repeating-linear-gradient(transparent 0 31px,rgba(29,95,138,.16) 31px 32px),linear-gradient(90deg,transparent 40px,rgba(169,47,39,.45) 40px 42px,transparent 42px);background-position:0 29px,0 0}
.report[hidden]{display:none}
.rc-head{display:flex;justify-content:space-between;align-items:flex-start;gap:16px}
.rc-head h2{font-size:26px}
.rc-head p{margin:2px 0 0;color:var(--soft)}
.grade-how{margin-top:8px;font-size:14.5px}
.rc-mark{flex:none;display:grid;place-items:center;min-width:84px;height:84px;padding:0 10px;border:4px solid var(--apple);border-radius:50%;transform:rotate(-8deg);color:var(--apple);font:700 40px/1 var(--body)}
.report table{width:100%;margin-top:14px;border-collapse:collapse;background:transparent}
.report th,.report td{white-space:normal;min-width:0;padding:8px 6px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top}
.report thead th{font-size:14px;color:var(--soft);font-weight:600}
.report tbody th{font-weight:600;white-space:nowrap}
.report .rc-g{color:var(--apple);font:700 24px/1 var(--body);text-align:center;width:64px}
.report details{margin-top:12px}
/* Everything in the report card sits on the 32px ruled lines: one line of text per ruled line, gaps in whole lines. */
.report{padding-top:32px!important;padding-bottom:32px!important;line-height:32px}
.report .rc-head{display:block;padding-right:110px}.report .rc-mark{position:absolute;right:22px;top:20px}
.report .rc-head h2{font-size:26px;line-height:32px;margin:0}.report .rc-head p{margin:0;line-height:32px}
.report table{margin-top:32px}.report th,.report td{padding:0 6px;line-height:32px;border-bottom:0;height:32px}
.report thead th{line-height:32px}.report .rc-g{line-height:32px}
.report .extra{position:relative;isolation:isolate;margin-top:32px;padding:0 14px;background:none;line-height:32px}.report .extra::before{content:'';position:absolute;z-index:-1;left:0;right:0;top:-4px;bottom:4px;background:var(--leaf-wash);opacity:.75}.report .extra h3,.report .extra p{margin:0!important;line-height:32px}.report .extra ul{margin:0}
.report details{margin-top:0}.report details>summary{line-height:32px;min-height:32px}.report .grade-how{line-height:32px;margin:0}.report .grade-how th,.report .grade-how td{height:auto}
@media (max-width:600px){.report .rc-head{padding-right:76px}.report .rc-mark{right:12px;top:16px}.report table tr{gap:0 10px;padding:0;border-bottom:0}.report th,.report td{height:auto}.report .grade-how tr{display:block}.report .grade-how th,.report .grade-how td{display:block;padding:0}}
@media (max-width:600px){.report{padding:18px 14px 14px 40px;background-image:repeating-linear-gradient(transparent 0 31px,rgba(29,95,138,.16) 31px 32px),linear-gradient(90deg,transparent 26px,rgba(169,47,39,.45) 26px 28px,transparent 28px)}.report tbody th{white-space:normal}.rc-mark{min-width:64px;height:64px;font-size:30px}.report table,.report tbody,.report tr{display:block}.report thead{display:none}.report tr{display:grid;grid-template-columns:1fr auto;gap:2px 10px;padding:8px 0;border-bottom:1px solid var(--line)}.report th,.report td{border:0;padding:0}.report td:last-child{grid-column:1/-1}}
.extra{margin-top:14px;padding:12px 14px;background:var(--leaf-wash)}
.extra h3{margin:0 0 4px;font-size:18px}
.extra ul{margin:0;padding-left:20px}
.extra .up{font-weight:700;color:var(--leaf)}
.pass{max-width:720px;background:#fff;color:#000;font-size:14px;line-height:1.45}
.pass-top{display:flex;justify-content:space-between;align-items:baseline;gap:12px;flex-wrap:wrap;border-bottom:2px solid #000;padding-bottom:6px}
.pass-top strong{font:700 22px/1.2 var(--head)}.pass-sub{margin:6px 0 0;color:#333}
.pass dl{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1.3fr);margin:6px 0}
.pass dt,.pass dd{margin:0;padding:6px 4px;border-bottom:1px solid #bbb}
.pass dt{font-weight:600}
.pass .blank{display:inline-block;min-width:70%;border-bottom:1px solid #000}
.pass h3{margin:14px 0 4px;font-size:15px;color:#000}
.pass ol{margin:4px 0;padding-left:20px}
#printPass{display:none}
@media (max-width:700px){.pass dl{grid-template-columns:1fr}.pass dt{border-bottom:0;padding-bottom:0}}
.hero h1.q{font-size:clamp(40px,5.4vw,72px);line-height:1.12;max-width:16em;margin-bottom:16px}
.ex-card{position:relative;justify-self:end;width:min(370px,100%);padding:16px 18px 10px;background:var(--paper);border:1px solid var(--line)}
.ex-card p{margin:0}
.ex-who{font:700 19px/1.2 var(--head);color:var(--ink);text-wrap:balance}
.ex-sub{margin-top:2px!important;font-size:13px;color:var(--soft);line-height:1.4}
.ex-rows{margin:10px 0 0;padding:0;list-style:none;font-size:14.5px}
.ex-rows li{padding:8px 0 6px}
.exr-top{display:flex;justify-content:space-between;gap:10px;align-items:baseline}
.exr-top b{font-weight:700;white-space:nowrap}
.ex-no .exr-top b{color:var(--apple)}.ex-ok .exr-top b{color:var(--leaf)}
.exr-bar{position:relative;height:10px;margin:5px 0 3px}.exr-bar u{position:absolute;top:0;bottom:0;right:0;background:repeating-linear-gradient(90deg,var(--line) 0 4px,transparent 4px 7px)}
.exr-bar i,.ex-note .key i{position:absolute;top:0;bottom:0;background:var(--board)}
.exr-bar i.sav,.ex-note .key i.sav{background:var(--bus)}
@media (prefers-color-scheme:dark){.exr-bar i,.ex-note .key i{background:#8f95d0}.exr-bar i.sav,.ex-note .key i.sav{background:var(--bus)}}
.exr-bar .cut{position:absolute;top:-3px;bottom:-3px;width:3px;margin-left:-1px;background:var(--apple)}
.ex-rows small{display:block;font-size:12.5px;color:var(--soft)}
.exr-axis{position:relative;height:18px;padding:0!important;font-size:11.5px;color:var(--soft);border-top:1px solid var(--line)}.exr-axis span{position:absolute;top:2px;transform:translateX(-50%)}
.ex-note{margin-top:8px!important;font-size:12.5px;color:var(--soft);display:flex;flex-wrap:wrap;gap:4px 16px}.ex-note .key{display:inline-flex;align-items:center;gap:6px}.ex-note .key i{position:static;display:inline-block;width:14px;height:10px}
.ex-link{width:auto!important;min-height:40px!important;margin:2px 0 0!important;padding:0!important;text-align:left}
@media (max-width:700px){.ex-card{justify-self:stretch;width:auto;margin-top:6px}}
.bd-when{margin:8px 0 0;font-size:16px;color:rgba(245,248,244,.8)}
.bd-sum{margin:18px 0 0;display:flex;flex-wrap:wrap;align-items:baseline;gap:4px 16px}.bd-sum strong{font:700 clamp(24px,3.6vw,34px)/1.15 var(--head)}.bd-sum strong.ok{color:#8fd3a8}.bd-sum strong.mid{color:#ffe07a}.bd-sum strong.bad{color:#f2b8a8}.bd-sum span{color:rgba(245,248,244,.8);font-size:16px}
.bd-warn{margin:6px 0 0;font-size:17px;color:#ffe07a}
.bd-sub{margin:10px 0 0;font-size:17px;color:#f5f8f4}.bd-sub strong{color:#8fd3a8}
.bd-more{margin-top:16px}.bd-more>summary{min-height:44px;display:flex;align-items:center;cursor:pointer;font-weight:600;color:#f5f8f4;text-decoration:underline;text-underline-offset:3px}
.bd-more .lg-how{margin:6px 0 0}

.ledger{display:grid;gap:16px;margin-top:18px}
.lg-top{display:flex;justify-content:space-between;align-items:baseline;gap:12px;font-size:16px;color:#d6e4dc}
.lg-top strong{font:700 30px/1 var(--head);color:#f5f8f4}
.lg-bar{height:14px;margin-top:8px;background:rgba(245,248,244,.12);border-radius:7px;overflow:hidden}
.lg-bar i{display:block;height:100%;border-radius:7px}
.lg-verdict{margin:18px 0 0;padding:10px 14px;border-radius:6px;font:700 20px/1.3 var(--head)}
.lg-verdict.ok{background:#8fd3a8;color:#123124}
.lg-verdict.mid{background:#ffe07a;color:#2a2100}
.lg-verdict.bad{background:#f2b8a8;color:#4a140d}
.lg-later{margin:10px 0 0;font-size:15px;color:#d6e4dc}
.lg-math{margin:-4px 0 14px;font-size:13.5px;line-height:1.45;color:#d6e4dc}
.lg-math strong{color:#f5f8f4;font-weight:600}
.law-list li{margin-bottom:6px}
.law-list cite{font-style:normal;font-weight:600;white-space:nowrap}
.check-tbl td:last-child{font-variant-numeric:tabular-nums}
.wiz-save{margin:0;padding:0;border:0;display:grid;gap:14px}
.wiz-save legend{padding:0;margin-bottom:6px;font-weight:600;font-size:16px}
.opt-tag{font-weight:400;font-size:13px;color:var(--soft);margin-left:4px}
.lg-foot{margin:12px 0 0;font-size:13px;color:#c3d6cc}
.wiz-pair{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:16px}
.wiz-checks{margin:4px 0 0;padding:0;border:0;display:grid;gap:10px}
.wiz-checks legend{padding:0;margin-bottom:8px;font-weight:600;font-size:16px}
.wiz-sub{display:grid;gap:12px;padding:10px 0 4px}
.wiz-sub[hidden]{display:none}
.wiz-small{font-size:14px;color:var(--soft)}
.wiz-ot{display:grid;grid-template-columns:minmax(0,1.3fr) minmax(0,.8fr) minmax(0,1fr);gap:10px}
.sp-intro{margin:-8px 0 14px;color:var(--soft)}
.wiz-sec{margin:0;padding:18px 20px 20px;border:1px solid var(--line);border-radius:8px;background:var(--paper);display:grid;gap:16px;min-width:0}
.wiz-sec+.wiz-sec{margin-top:16px}
.wiz-sec>legend{float:left;width:100%;padding:0;margin:0 0 2px;font:700 18px/1.25 var(--head);color:var(--ink)}
.wiz-sec .wiz-sec{padding:0;border:0;background:none}
.wq-list{display:grid}
.wq{padding:14px 0;border-top:1px solid var(--line)}.wq:first-child{border-top:0;padding-top:4px}
.wq-row{margin:0;padding:0;border:0;display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;min-width:0}
.wq-t{float:left;padding:0;font-size:16px;font-weight:400;color:var(--ink);flex:1 1 260px;max-width:30em}
.wq .seg{flex:none;flex-wrap:nowrap}.wq .seg .radio-card{flex:0 0 78px;padding:8px 12px}
.wq .wiz-sub{padding-top:12px}
.wq-tax select{flex:0 1 240px;width:auto;min-width:200px}
@media (max-width:600px){.wiz-sec{padding:14px}}
.wiz-sec>legend+*{clear:both}
.wiz-row{display:flex;flex-wrap:wrap;gap:10px}.seg .radio-card{flex:0 0 140px;align-items:center;padding:12px 16px}.seg .radio-card input{margin:0}.wiz-row .radio-card{flex:1 1 180px}
.sav-toggle{width:auto;margin:0;padding:0;text-align:left;font-size:15px}
.back-btn{min-height:44px;padding:0 4px;background:none;border:0;color:var(--blue);font-weight:600;text-decoration:underline;cursor:pointer}
.steps{display:none;align-items:center;justify-content:space-between;gap:12px;padding-top:12px;padding-bottom:0}
body[data-has="1"]:not([data-screen=welcome]) .steps{display:flex}
.pg-arrow{display:grid;place-items:center;width:46px;height:46px;padding:0 0 4px;background:var(--paper);color:var(--ink);border:1px solid var(--line);border-radius:50%;font:400 34px/1 var(--head);cursor:pointer}
.pg-arrow:disabled{opacity:.3;cursor:default}
#pgName{font-size:14px;color:var(--soft)}
@media print{.steps{display:none!important}}
.risk-bars{display:grid;gap:10px;margin:8px 0 6px}
.rb{display:grid;grid-template-columns:minmax(0,1.3fr) minmax(0,1fr);gap:12px;align-items:center}.rb-o{display:grid;grid-template-columns:minmax(0,1fr) 84px;gap:12px;align-items:center}
.rb-l{display:grid;gap:2px}.rb-s{width:100%;max-width:260px;accent-color:var(--board);margin:2px 0 0}
.rb-l{font-size:15px}.rb.base .rb-l{font-weight:700}
.rb-t{height:14px;background:var(--wash);border-radius:7px;overflow:hidden}.rb-t i{display:block;height:100%;border-radius:7px}
.rb-t i.ok{background:var(--leaf)}.rb-t i.bad{background:var(--apple)}
.rb b{font-size:15px;text-align:right}.rb b.ok{color:var(--leaf)}.rb b.bad{color:var(--apple)}
.rb-axis{display:grid;grid-template-columns:minmax(0,1.3fr) minmax(0,1fr);gap:12px;font-size:12px;color:var(--soft)}.rb-ends{display:flex;justify-content:space-between;padding-right:96px}
.miles svg{margin:2px 0 10px}
@media (max-width:600px){.rb{grid-template-columns:minmax(0,1fr);row-gap:6px}.rb-o{grid-template-columns:minmax(0,1fr) 70px}.rb-axis{grid-template-columns:minmax(0,1fr)}.rb-axis>span:first-child{display:none}.rb-ends{padding-right:82px}.rb-s{max-width:none}}

.hero-who{margin:10px 0 0;font-size:14px;color:var(--soft);max-width:34em}
.wiz-who{margin:-6px 0 14px;font-size:14px;color:var(--soft)}
.ac-key{display:flex;flex-wrap:wrap;gap:6px 18px;margin:6px 0 4px;font-size:13px;color:var(--soft)}.ac-key span{display:inline-flex;align-items:center;gap:6px}.ac-key i{display:inline-block;width:14px;height:10px;border-radius:2px}
.ss-tiles{display:block;margin:12px 0;border-top:1px solid var(--line)}
.ss-t{display:grid;grid-template-columns:minmax(0,1fr) auto;column-gap:20px;align-items:baseline;padding:12px 0;border-bottom:1px solid var(--line)}
.ss-t small:first-child{grid-column:1;grid-row:1;font-size:16px;font-weight:700;color:var(--ink)}
.ss-t strong{grid-column:2;grid-row:1 / span 2;align-self:center;text-align:right;font-size:22px;line-height:1.2;color:var(--ink);white-space:nowrap}
.ss-t small:last-child{grid-column:1;grid-row:2;font-size:14px;color:var(--soft);margin-top:2px}
.ss-t.warn strong{color:#8a5a00}
@media (max-width:600px){.ss-t strong{font-size:18px;white-space:normal}}
.ss-table{margin-top:24px}.ss-pitch{margin:2px 0 10px}
.next3{margin:12px 0 18px;padding:0 0 0 22px;border-top:1px solid var(--line)}
.next3 li{padding:12px 0 12px 4px;border-bottom:1px solid var(--line)}.next3 li::marker{font-weight:700}
.next3 strong{display:block;font-size:16px}.next3 span{display:block;font-size:14px;color:var(--soft);margin-top:2px}.next3 .link-btn{display:block;width:auto;margin:4px 0 0;padding:0;text-align:left}
.mn-row{display:flex;align-items:center;justify-content:space-between;gap:10px 16px;flex-wrap:wrap}.mn-act{display:flex;align-items:center;gap:14px;margin-left:auto}
.ap{list-style:none;margin:0;padding:0;border-top:1px solid var(--line)}
.ap li{display:grid;grid-template-columns:96px 24px minmax(0,1fr);gap:10px;align-items:start;padding:10px 0;border-bottom:1px solid var(--line)}
.ap-when{font-weight:700}.ap input{margin:4px 0 0;width:18px;height:18px}.ap li .link-btn{display:inline!important;width:auto!important;min-height:0;padding:0!important;margin:0!important;font:inherit;text-align:left;vertical-align:baseline}.ap input{accent-color:var(--board)}
@media (max-width:600px){.ap li{grid-template-columns:24px minmax(0,1fr)}.ap-when{grid-column:1/-1}}
.miles{margin-top:22px}
.miles h3{margin:0 0 4px}
.miles>p{margin:0 0 10px;color:var(--soft)}
.miles ol{list-style:none;margin:0;padding:0;display:grid;gap:8px}
.miles li{display:grid;grid-template-columns:76px minmax(0,1fr);gap:10px;padding:8px 10px;border-top:1px solid var(--line)}
.miles li b{font-weight:700}
.miles li.done{color:var(--soft)}
.miles li.next{background:#fff6d6;color:#2a2100}
.miles em{font-style:normal;font-weight:600}
.be{display:block;margin-top:10px;padding:10px 14px;background:var(--leaf-wash)}
.req,.req-note{display:none}
.req-note{margin:0 0 4px;font-size:14px;color:var(--soft)}
.req-note .req{margin:0 2px 0 0}

.schedule{margin:18px 0 0;padding:12px 0;border-top:2px solid var(--ink);border-bottom:1px solid var(--line)}
.schedule h2{margin:0 0 6px;font-size:18px}
#periods{display:flex;flex-wrap:wrap;gap:6px}
#periods button{min-height:40px;padding:0 10px;background:var(--bg);border:1px solid var(--line);border-radius:6px;font-size:14px;cursor:pointer}
#periods button[aria-pressed=true]{background:var(--board);color:var(--on-board);border-color:var(--board);font-weight:700}
#periods b{margin-right:4px}
.period{margin-top:24px;padding:24px 28px 28px;background:var(--paper);border:1px solid var(--line);border-radius:6px}
@media (max-width:700px){.period{padding:18px 16px 20px;margin-top:18px}}
.sub{margin-top:22px}
.worth{margin-top:24px}.worth h3{margin:0 0 4px}
.worth .be:first-child{margin-top:0}
.lg-how{margin:-4px 0 14px}.lg-how summary{min-height:32px;cursor:pointer;font-size:14px;color:#d6e4dc;text-decoration:underline dotted;text-underline-offset:3px}.lg-how .lg-math{margin:4px 0 0}
.star{display:inline-block;margin-left:4px;padding:0 6px;background:var(--bus);color:var(--on-bus);border-radius:3px;font-size:12px;font-weight:700}
blockquote{margin:0;padding:0 0 0 1.2em;font-style:italic}
.gloss dt{font-weight:700;margin-top:8px}.gloss dd{margin:0}
.answer-sub{margin:10px 0 0;font-size:19px;max-width:36em}
.block{margin-top:44px}
.lead{margin:0 0 14px;max-width:46em;color:var(--soft)}
svg.chart{display:block;width:100%;height:auto}
.axis{fill:var(--soft);font-size:14px}
.gridline{stroke:var(--line)}
.try{margin-top:12px}
.try label{font-weight:600;font-size:14px}
input[type=range]{width:100%;min-height:36px;accent-color:var(--chart);margin:2px 0}
.two{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}
.panel{padding:14px 0 0;border-top:1px solid var(--line)}
.panel h3{margin-top:0}
.tbl-wrap{overflow-x:auto;background:var(--paper)}
table{width:100%;border-collapse:collapse;font-variant-numeric:tabular-nums}
th,td{padding:8px 12px;border-bottom:1px solid var(--line);text-align:right;white-space:nowrap}
th:first-child,td:first-child{text-align:left;white-space:normal;min-width:150px}
thead th{font-size:14px}
.flag{padding:10px 14px;background:var(--apple-wash);margin-top:10px}
.flag.good{background:var(--leaf-wash)}
.act{min-height:44px;padding:0 14px;margin-top:10px;background:var(--board);color:var(--on-board);border:0;border-radius:6px;font-weight:700;cursor:pointer}
details.section{border-top:1px solid var(--line);padding:12px 0}
details.section:last-of-type{border-bottom:1px solid var(--line)}
details.section>summary{min-height:32px;font:700 20px var(--head);cursor:pointer}
details.section ul{margin:8px 0;padding-left:20px;max-width:48em}
details.section li{margin:5px 0}
#s-how{font-size:15px;display:none}
body.fp-open #s-how{display:block}
body.fp-open #resultsView #results>#s-how{display:block!important}
body.fp-solo[data-screen] #resultsView{display:block!important}
body.fp-solo[data-screen] #wizard,body.fp-solo[data-screen] .hero,body.fp-solo[data-screen] .why{display:none!important}
body.fp-solo #resultsView *:not(#s-how):not(#s-how *):not(:has(#s-how)){display:none!important}
#s-how details.section{display:none;border:0}
#s-how details.section.fp-on{display:block}
#s-how details.section>summary{pointer-events:none;list-style:none}
#s-how details.section>summary::-webkit-details-marker{display:none}
#s-how details.section>summary{font-size:17px}
.foot-links{display:grid;grid-template-columns:repeat(4,minmax(0,max-content));gap:0 40px;margin:4px 0 22px;font-size:16px}
.foot-links a{display:block;padding:10px 0;color:var(--ink);text-decoration:none}
.foot-links a:hover{text-decoration:underline}
@media (max-width:700px){.foot-links{grid-template-columns:repeat(2,minmax(0,1fr));gap:0 20px}}
footer{padding-block:20px 56px;border-top:1px solid var(--line);font-size:14px;color:var(--soft)}
footer p{max-width:60em}
@media (max-width:1000px){
 .hero-grid{grid-template-columns:minmax(0,1fr);gap:28px;padding-block:28px 32px}
 .ex-card{justify-self:start;width:min(380px,100%)}
 .hero-actions .big-btn{width:100%}
 .hero-actions .link-btn{width:100%;text-align:center}
}
@media (max-width:700px){
 .hero .wrap.hero-grid{gap:20px;padding-top:24px}
 .hero h1.q{font-size:38px}
 .hero-sub{margin-top:14px;font-size:17px}
 .brand small{display:none}
}
@media (max-width:760px){
 .bar{position:static}
 #message{top:0}
 html{scroll-padding-top:8px}
 .two{grid-template-columns:minmax(0,1fr)}
 .board{padding:16px 16px 30px;border-width:7px}
}
@media (prefers-reduced-motion:reduce){html{scroll-behavior:auto}}
@media print{
 body[data-print=pass]>*:not(#printPass){display:none!important}
 body[data-print=pass] #printPass{display:block!important}
 #passPrint{display:none!important}
 :root{color-scheme:light;--bg:#fff;--paper:#fff;--wash:#f1f1f1;--ink:#000;--soft:#333;--line:#999;--board:#222;--on-board:#fff;--bus:#ddd;--on-bus:#000;--apple:#000;--leaf:#000;--blue:#000;--chart:#222}
 .bar,#message,.try,.schedule,#modeNote,.hero-scene,.why,.skip,.act,details:not([open]){display:none!important}
 .layout{display:block}
 .hero-grid{display:block;padding:0}
 .hero h1{font-size:30pt}
 .block{margin-top:16px}
 .panel,tr{break-inside:avoid}
 h2,h3{break-after:avoid}
 body{font-size:11pt}
 .slide{display:none!important}
 .board{background:#fff;color:#000;border:2px solid #000;box-shadow:none}.tray{display:none}
 svg.chart{max-height:3in}
}

/* Direct, accessible feedback link: opens the user's own email app; no data collected by School's Out. */
.bar-inner .feedback-link{white-space:nowrap}
.bar-inner .feedback-link:hover{text-decoration:underline}
.bar-inner .feedback-link:focus-visible{outline:3px solid #e5ac12;outline-offset:3px}

/* Feedback dialog is local-only; sending requires the visitor's email provider. */
.feedback-link{cursor:pointer;background:transparent}
.feedback-modal{border:1px solid #c8cad6;border-radius:16px;padding:1.3rem;width:min(94vw,480px);max-height:90vh;overflow:auto;color:#25253b;background:#fff;box-shadow:0 18px 65px #0004}
.feedback-modal::backdrop{background:#10132b99}
.feedback-modal h2{margin:.1rem 0 .5rem;font-size:1.35rem}
.feedback-modal label{display:block;font-weight:650;margin-top:1rem;margin-bottom:.35rem}
.feedback-modal select,.feedback-modal textarea{box-sizing:border-box;width:100%;font:inherit;border:1px solid #8589a3;border-radius:8px;padding:.65rem;background:#fff;color:#20223a}
.feedback-modal textarea{min-height:125px;resize:vertical}
.feedback-actions{display:flex;flex-wrap:wrap;justify-content:center;gap:.55rem;margin-top:1rem}
.feedback-actions button{font:inherit;border-radius:8px;border:1px solid #5e6285;padding:.65rem .85rem;cursor:pointer;background:#fff;color:#25253b}
.feedback-actions .feedback-primary{background:#272a74;color:#fff;border-color:#272a74}
.feedback-note{font-size:.86rem;color:#52546b;line-height:1.45}
.feedback-status{min-height:1.5em;font-size:.88rem;text-align:center}
#boardText h1:focus{outline:none}
@media print{#results button,#results input[type=range]{display:none!important}}
body[data-screen=results] footer .wrap{max-width:940px}
body[data-screen=wizard] footer .wrap{max-width:640px}
.bar .fb-narrow{display:none}
@media (max-width:480px){
 body[data-screen=results] .bar #feedbackOpen{display:none}
 body[data-screen=results] .bar .more-menu .fb-narrow{display:block}
 .brand{font-size:19px}
 .bar button{padding:0 11px}
}
html:not(.js) .ex-card,html:not(.js) .hero-actions,html:not(.js) .bar button,html:not(.js) .bar .more-menu{display:none!important}
/* Phones and tablets: the first screen is the headline, the Start button and the farm scene, ending at the bottom edge.
   The notes and the example card follow below it. fitHero() sets the spacing. */
@media (max-width:1000px){
 .hero{min-height:0;background:#f3f0e8}
 .hero-grid,.hero-text{display:contents}
 .hero h1.q,.hero-sub,.hero-actions,.hero-free,.hero-who,.hero .ex-card{margin-inline:20px}
 .hero h1.q{order:1;margin-top:var(--hero-top,28px)}
 .hero-sub{order:2}.hero-actions{order:3}.hero-free{order:4}
 .hero-scene{order:6;flex:none;margin-top:var(--scene-gap,20px);height:var(--scene-h,140px)}
 .hero-who{order:7;max-width:none}
 .hero-free+.hero-who{margin-top:24px}
 .hero .ex-card{order:8;margin-top:20px;margin-bottom:32px;justify-self:auto;width:auto;max-width:520px}
}
@media (max-width:400px){.brand{font-size:17px;gap:6px}.brand svg{width:26px;height:26px}.bar button{padding:0 9px;font-size:13px}.bar-inner{gap:6px}}
/* In restricted previews where scripts cannot run, show only the download notice. */
html:not(.js) body > :not(#nojs){display:none!important}
html:not(.js) body{background:#f3f0e8!important;min-height:100vh;margin:0;display:grid;place-items:center}
html:not(.js) #nojs{display:block!important;width:min(92vw,520px);margin:24px auto!important;padding:28px!important;border:1px solid #d9d5ca!important;border-radius:8px;background:#fff!important;color:#24242a!important;text-align:center;box-shadow:none}
html:not(.js) #nojs strong{display:block;font-size:23px;line-height:1.25;margin-bottom:12px}
html:not(.js) #nojs p{margin:8px 0;line-height:1.5}

/* Desktop: fit the complete farm illustration within the first viewport,
   without a few pixels of the next section peeking out. */
@media (min-width:1001px){
 body[data-screen="welcome"] .hero{
   height:calc(100svh - var(--barh,56px));
   min-height:0;
 }
 body[data-screen="welcome"] .hero-scene{
   flex:1 1 0;
   min-height:0;
   margin-top:12px;
   overflow:hidden;
 }
 body[data-screen="welcome"] .hero-scene .lake-art{
   min-height:0;
   width:100%;
   height:100%;
 }
}

/* Compact eligibility and rules disclosure. Native details works by tap, click and keyboard. */
.hero-info{position:relative;margin-top:8px;max-width:38em;color:var(--soft);font-size:14px}
.hero-info summary{display:inline-flex;align-items:center;gap:7px;cursor:pointer;color:var(--blue);font-weight:600;list-style:none;min-height:30px}
.hero-info summary::-webkit-details-marker{display:none}
.hero-info summary:hover{text-decoration:underline}
.hero-info-icon{display:inline-grid;place-items:center;width:17px;height:17px;border:1.5px solid currentColor;border-radius:50%;font:700 12px/1 Arial,sans-serif}
.hero-info-content{position:absolute;z-index:12;top:calc(100% + 5px);left:0;width:min(470px,calc(100vw - 40px));padding:13px 16px;background:#fff;color:#333;border:1px solid var(--line);border-radius:5px;box-shadow:0 7px 22px rgba(0,0,0,.13);font-size:14px;line-height:1.5}
.hero-info-content p{margin:0}.hero-info-content p+p{margin-top:10px}

@media (max-width:1000px){.hero-info{order:6;margin:8px 20px 0;max-width:none}.hero-info-content{position:relative;top:auto;margin-top:6px;box-shadow:none}}

/* Keep the beige homepage readable even when the host preview forces dark mode. */
@media (prefers-color-scheme:dark){
 :root{color-scheme:light;--bg:#faf8f4;--paper:#fff;--wash:#f3f0e8;--ink:#24242a;--soft:#5c5a55;--line:#d9d5ca;--board:#272a74;--on-board:#fff;--blue:#272a74;--chart:#272a74;--apple:#c84935;--apple-wash:#fff0eb;--leaf:#2e7753;--leaf-wash:#eaf6ef}
 .lake-art{filter:none}
}
.hero h1.q{color:#24242a}
.hero .hero-sub{color:#5c5a55}
.hero .hero-free{color:#24242a}
.hero-info-links .hero-info summary{color:#272a74}
/* Quiet, side-by-side secondary links below the primary call to action. */
.hero-info-links{display:flex;align-items:flex-start;flex-wrap:wrap;gap:4px 22px;margin-top:9px}
.hero-info-links .hero-info{margin:0;max-width:none;font-size:13px}
.hero-info-links .hero-info summary{font-size:13px;font-weight:400;min-height:30px;gap:6px}
.hero-info-links .hero-info-icon{width:15px;height:15px;font-size:10px}
@media (max-width:1000px){.hero-info-links{order:5;margin:8px 20px 0;gap:4px 18px}.hero-info-links .hero-info{margin:0}}
@media (max-width:400px) and (max-height:660px){.hero h1{font-size:34px;margin-bottom:10px}.hero .lede,.hero h1+p{font-size:16px;line-height:1.45}}
@media (max-width:400px){.hero-info-links{gap:0 14px;margin-top:4px}.hero-info-links .hero-info summary{font-size:12px;min-height:28px;gap:5px}}
</style>
</head>
<body data-screen="welcome">
<a class="skip" id="skipLink" href="#startBtn">Skip to the start button</a>
<div class="bar">
  <div class="wrap bar-inner">
    <a class="brand" href="#top"><svg viewBox="0 0 64 64" aria-hidden="true"><path d="M32 8c-11 0-17 9-17 20 0 9-3 14-7 18h48c-4-4-7-9-7-18 0-11-6-20-17-20z" fill="#f4c430"/><circle cx="32" cy="52" r="6" fill="#f4c430"/></svg>School's Out <small>Retirement planning for Kentucky teachers and faculty in TRS</small></a>
    <button type="button" id="openBtn2" class="w-only">Open<span class="wide-only"> a saved</span> plan</button>
    <button type="button" id="saveBtn" class="main r-only">Save Plan</button>
    <button type="button" id="pdfBtn" class="r-only">Export PDF</button>
    <button type="button" class="feedback-link" id="feedbackOpen" aria-haspopup="dialog">Feedback</button>
    <button type="button" id="moreBtn" class="more-btn" aria-expanded="false" aria-controls="moreMenu" aria-label="More options" title="More options">&#8943;</button>
    <div class="more-menu" id="moreMenu">
    <button type="button" id="openBtn" class="r-only">Open a saved plan</button>
    <input id="openFile" type="file" accept=".json,application/json" hidden aria-label="Saved plan to open">
    <button type="button" id="overBtn" class="r-only">Start over</button>
    <button type="button" id="feedbackOpen2" class="r-only fb-narrow">Feedback</button>
    </div>
  </div>
</div>
<div class="wrap"><div id="message" aria-live="polite"></div></div>

<div id="nojs" role="alert"><strong>Open School’s Out in your browser</strong><p>This preview can’t run the calculator. To use School’s Out, download the HTML file from the message or page where you received it—not from inside this preview.</p><p><strong style="font-size:inherit;display:inline;margin:0">On iPhone or iPad:</strong> Save the attached HTML file to Files, then open it in a browser that supports local HTML files. If your preview app does not offer a download option, open the original file link in Safari or another browser first.</p><p><strong style="font-size:inherit;display:inline;margin:0">On a computer:</strong> Download the HTML file, then double-click it to open it in Chrome, Edge, Firefox, or Safari.</p><p>Your information stays on your device. No account or installation is needed.</p></div>
<header class="hero" id="top">
  <div class="wrap hero-grid">
    <div class="hero-text">
      <h1 class="q">When can you afford to retire?</h1>
      <p class="hero-sub">Most pension calculators only show what TRS will pay you. School's Out adds your savings and bills to find the first year you can afford to retire.</p>
      <div class="hero-actions"><button type="button" class="big-btn" id="startBtn">Start my plan</button><button type="button" class="link-btn" id="newBtn" hidden>Start a new plan</button></div>
      <p class="hero-free">Free, no sign-up, and your information stays on your device.</p>
      <div class="hero-info-links">
      <details class="hero-info" id="heroInfo">
        <summary><span class="hero-info-icon" aria-hidden="true">i</span> Who can use School's Out?</summary>
        <div class="hero-info-content">
          <p>For Kentucky teachers, principals, counselors, librarians and other school or university staff in TRS. Bus drivers, custodians, cafeteria workers and aides are usually in a different pension, CERS, so this app won't fit them.</p>
        </div>
      </details>
      <details class="hero-info" id="heroRulesInfo">
        <summary><span class="hero-info-icon" aria-hidden="true">i</span> TRS rules and updates</summary>
        <div class="hero-info-content">
          <p>Uses Kentucky law and TRS rules as of July 2026, including the 2026 return-to-work changes and the 2025 federal law that ended Social Security cuts for people with a TRS pension.</p>
        </div>
      </details>
      </div>
    </div>
    <aside class="ex-card" aria-labelledby="exH">
        <p class="ex-who" id="exH"></p>
        <p class="ex-sub" id="exSub"></p>
        <ul class="ex-rows" id="exRows"></ul>
        <p class="ex-note" id="exNote"></p>
        <button type="button" class="link-btn ex-link" data-example="year26">See this teacher's plan</button>
      </aside>
  </div>
  <div class="hero-scene" aria-hidden="false"><svg class="lake-art lake-wide" viewBox="0 60 1200 240" preserveAspectRatio="xMidYMax meet" role="img" aria-label="A Kentucky horse farm in the morning: a horse grazing on rolling hills, a barn and silo, and a white plank fence">
 <circle cx="452" cy="116" r="34" fill="#f4c430" opacity=".18"/><circle cx="452" cy="116" r="23" fill="#f4c430"/>
 <path d="M-1200 150 C-800 140 -200 195 0 160 C200 125 450 150 700 135 C950 120 1050 120 1200 135 C1500 165 1900 120 2400 140 V300 H-1200Z" fill="#d3d5ea"/>
 <path d="M-1200 190 C-800 170 -260 240 0 200 C260 160 620 195 1200 165 C1780 135 2000 180 2400 170 V300 H-1200Z" fill="#a7abd3"/>
 <g fill="#272a74"><path d="M166 154.8l12 -20l30 -12l30 12l12 20Z"/><rect x="170" y="153.8" width="76" height="37"/><rect x="254" y="138.8" width="18" height="52" /><circle cx="263" cy="138.8" r="9"/></g><rect x="197" y="163.8" width="21" height="27" fill="#f4c430"/>
 <path d="M1010 178.9V144.9" stroke="#272a74" stroke-width="4.5"/><circle cx="1010" cy="131.7" r="22" fill="#3c4198"/><path d="M1062 177.1V153.1" stroke="#272a74" stroke-width="4.5"/><circle cx="1062" cy="144.1" r="15" fill="#3c4198"/><path d="M60 198.2V172.2" stroke="#272a74" stroke-width="4.5"/><circle cx="60" cy="162.0" r="17" fill="#3c4198"/><path d="M-330 217.0V187.0" stroke="#272a74" stroke-width="4.5"/><circle cx="-330" cy="175.0" r="20" fill="#3c4198"/><path d="M-700 201.5V177.5" stroke="#272a74" stroke-width="4.5"/><circle cx="-700" cy="168.5" r="15" fill="#3c4198"/><path d="M1480 161.4V133.4" stroke="#272a74" stroke-width="4.5"/><circle cx="1480" cy="122.6" r="18" fill="#3c4198"/><path d="M1540 160.7V140.7" stroke="#272a74" stroke-width="4.5"/><circle cx="1540" cy="132.9" r="13" fill="#3c4198"/><path d="M1950 169.1V139.1" stroke="#272a74" stroke-width="4.5"/><circle cx="1950" cy="127.1" r="20" fill="#3c4198"/>
 <g fill="#272a74" transform="translate(740 113.4) scale(.34)"><path d="M190 134L204 130L212 164L213 194C214 199 217 202 219 206L219 210L206 210L207 203L207 194L205 168Z"/><path d="M96 118L110 118L104 150L101 163L103 180L104 194C105 199 108 202 110 206L110 210L97 210L98 203L98 194L96 178L94 163L93 150Z"/><path d="M64 84C70 70 84 62 100 62C120 62 140 68 158 68C170 68 180 64 190 63C198 63 206 68 212 76C222 88 230 100 236 110C241 118 245 124 249 130L254 118C258 124 259 132 258 139C264 154 271 174 276 190C278 197 277 203 272 206C268 208 263 206 260 202C255 192 248 186 241 180C235 175 232 168 233 162C234 158 235 156 236 154C228 144 220 130 211 118C208 122 206 127 205 132C204 136 201 139 197 140L195 164C196 168 195 174 194 178L193 194C193 198 196 201 198 205L198 210L185 210L186 203C187 199 187 196 187 194L186 178C185 174 184 168 184 164L181 136C160 140 135 136 112 124C108 130 100 138 95 146C91 152 88 158 86 163C85 168 86 174 85 180L84 194C84 198 88 202 90 206L90 210L77 210L77 204C78 200 78 197 78 194L78 178C78 172 76 166 73 162C75 154 76 148 75 142C72 132 64 122 61 110C59 100 60 92 64 84Z"/><path d="M66 81C54 82 45 92 42 108C39 130 41 154 46 174C49 162 51 148 52 134C53 118 57 102 68 90Z"/></g>
 <path d="M-1200 240 C-800 225 -350 292 0 262 C350 232 800 250 1200 222 C1600 194 2000 230 2400 215 V300 H-1200Z" fill="#3c4198"/>
 <g stroke="#fff" fill="none"><g stroke-width="3.5"><path d="M-1200 235 C-800 220 -350 287 0 257 C350 227 800 245 1200 217 C1600 189 2000 225 2400 210"/><path d="M-1200 225 C-800 210 -350 277 0 247 C350 217 800 235 1200 207 C1600 179 2000 215 2400 200"/><path d="M-1200 215 C-800 200 -350 267 0 237 C350 207 800 225 1200 197 C1600 169 2000 205 2400 190"/></g><path stroke-width="5" d="M-1170 209.0v34M-1110 207.9v34M-1050 207.9v34M-990 208.6v34M-930 210.1v34M-870 212.2v34M-810 214.7v34M-750 217.6v34M-690 220.7v34M-630 224.0v34M-570 227.2v34M-510 230.4v34M-450 233.3v34M-390 235.8v34M-330 237.9v34M-270 239.3v34M-210 239.8v34M-150 239.3v34M-90 237.6v34M-30 234.3v34M30 229.6v34M90 225.4v34M150 222.1v34M210 219.4v34M270 217.3v34M330 215.6v34M390 214.3v34M450 213.2v34M510 212.2v34M570 211.4v34M630 210.6v34M690 209.8v34M750 208.8v34M810 207.7v34M870 206.4v34M930 204.8v34M990 202.8v34M1050 200.4v34M1110 197.5v34M1170 194.0v34M1230 190.0v34M1290 186.7v34M1350 184.3v34M1410 182.6v34M1470 181.5v34M1530 181.0v34M1590 181.0v34M1650 181.4v34M1710 182.2v34M1770 183.1v34M1830 184.2v34M1890 185.3v34M1950 186.4v34M2010 187.4v34M2070 188.2v34M2130 188.7v34M2190 188.8v34M2250 188.5v34M2310 187.6v34M2370 186.0v34"/></g>
</svg></div>
</header>

<main class="wrap why" aria-labelledby="h-why">
  <h2 id="h-why">Why Kentucky educators need School's Out</h2>
  <p class="why-text">Teaching in Kentucky doesn't earn Social Security, so your TRS pension and savings have to cover everything. Leave too early and TRS can cut your pension for life, and before 65 you may pay more for health insurance. School's Out shows how each extra year of teaching changes both, and the first year your money lasts.</p>
  <div class="asks">
    <h3>Why not use another tool?</h3>
    <dl>
      <div><dt>TRS's online benefit estimator</dt><dd>Shows your pension. <span>It doesn't show whether that covers your bills, health insurance and taxes.</span></dd></div>
      <div><dt>A typical retirement calculator</dt><dd>Shows if savings last. <span>It counts Social Security that teaching doesn't earn, and doesn't know TRS rules.</span></dd></div>
      <div><dt>Online TRS pension calculators</dt><dd>Shows your pension under TRS rules. <span>It doesn't add health insurance, taxes, savings or a spouse's income to show whether your money lasts.</span></dd></div>
      <div class="us"><dt>School's Out</dt><dd>Shows when you can afford to retire. <span>It uses TRS rules, your bills and your savings together.</span></dd></div>
    </dl>
  </div>
  <section class="teacher-voices" aria-labelledby="teacherVoicesTitle">
    <h3 id="teacherVoicesTitle">Real testimonials on School's Out</h3>
    <div class="quote-track">
    <figure class="teacher-quote">
      <blockquote>“I am six years away from retirement and not quite ready to make an appointment with TRS ... but would love to be able to play around with something like this to get an idea of what I'm looking at.”</blockquote>
      <figcaption>— Kristin C., High School Teacher</figcaption>
    </figure>
    <figure class="teacher-quote">
      <blockquote>“I love this app because it makes retirement planning easier, more accessible, and less overwhelming for educators. It's a tool every teacher should have.”</blockquote>
      <figcaption>— Bradley S., High School Teacher</figcaption>
    </figure>
    <figure class="teacher-quote">
      <blockquote>“The menu choices were intuitive and easy to use and really woke me up a bit about saving and working towards this goal.”</blockquote>
      <figcaption>— Sarah M., High School Teacher</figcaption>
    </figure>
    </div>
  </section>
</main>

<nav class="wrap steps" id="steps" aria-label="Pages">
  <button type="button" class="pg-arrow" id="pgPrev">&lsaquo;</button>
  <span id="pgName"></span>
  <button type="button" class="pg-arrow" id="pgNext">&rsaquo;</button>
</nav>
<main class="wrap wizard" id="wizard" aria-labelledby="wizQ">
  <div id="wizForm">
    <p class="progress" id="wizProgress"></p>
    <h1 id="wizQ" tabindex="-1"></h1>
    <div id="wizBody"></div>
    <p class="err-text" id="wizErr" role="alert"></p>
    <div class="wiz-actions"><button type="button" id="wizBack">Back</button><button type="button" class="big-btn" id="wizNext">Next</button></div>
  </div>
</main>

<main class="wrap layout" id="resultsView" data-plan="closed">

<div id="results" tabindex="-1">

  <div id="modeNote" role="status"></div>
  <div id="answerBox">
    <div class="board"><div id="boardText"></div>
      <div class="slide" id="slideWrap"><label for="tryRetire">Drag to try another age</label><input id="tryRetire" type="range" min="50" max="75" step="1"><div class="slide-ends" id="slideEnds"></div></div>
      <div class="tray" aria-hidden="true"><i></i><i></i></div></div>
    <p class="answer-sub" id="answerSub"></p>
    <div id="reportDetails"><section class="report" id="reportCard" aria-labelledby="rcH" hidden>
      <div class="rc-head">
        <div><h2 id="rcH">Your retirement report card</h2><p id="rcNote"></p></div>
        <div class="rc-mark" id="rcGrade"></div>
      </div>
      <table id="rcTable"><thead><tr><th scope="col">Subject</th><th scope="col">Grade</th><th scope="col">Teacher's comment</th></tr></thead><tbody id="rcRows"></tbody></table>
      <div class="extra" id="rcExtra" hidden></div>
      <details><summary>How grading works</summary><table class="grade-how"><tbody>
        <tr><th scope="row">Money that lasts</th><td>A+, A or A- if it lasts to 95 even with bills 30%, 20% or 10% higher. B+ if it just lasts. If it runs short, the grade follows the share of your costs to 95 it still covers, from B at 98% down to F below 70%.</td></tr>
        <tr><th scope="row">TRS pension</th><td>The share of your final average salary it replaces, from A at 60% or more down to F under 20%.</td></tr>
        <tr><th scope="row">Health coverage</th><td>The share TRS pays toward retiree coverage. A at 100%, F if you wouldn't qualify.</td></tr>
      </tbody></table><p class="grade-how">A grade describes this plan on these numbers. It isn't a grade on you, and it changes when the numbers do.</p></details>
    </section>
    </div>
  </div>

  <nav class="schedule" aria-label="Sections of your plan">
    <h2>Your full plan</h2>
    <div id="periods" role="group" aria-label="Choose a section"></div>
  </nav>

  <section class="block period" id="s-when" aria-labelledby="h-when">
    <h2 id="h-when">When could you retire?</h2>
    <div class="worth" id="worthWrap" hidden><h3>Worth knowing</h3><div id="worthOut"></div></div>
    <h3 class="sub">How long your money lasts, by the age you retire</h3>
    <div id="ageChart"></div>
    <div id="miles"></div>
  </section>

  <section class="block period" id="s-enough" aria-labelledby="h-enough">
    <h2 id="h-enough">Will your money last?</h2>
    <div id="enoughOut"></div>
    <h3 class="sub">What could go wrong</h3>
    <div id="retireStressOut"></div>
  </section>

  <section class="block period" id="s-health" aria-labelledby="h-health">
    <h2 id="h-health">Health coverage</h2>
    <div id="healthOut"></div>
  </section>

  <section class="block period" id="s-ss" aria-labelledby="h-ss">
    <h2 id="h-ss">Social Security</h2>
    <div id="ssOut"></div>
    <div id="sideWrap" class="ss-table"><h3 class="sub">Extra money on the table</h3><p class="ss-pitch">A summer or side job outside the school system pays into Social Security. Do it long enough and you get a monthly check for life, on top of your pension.</p>
    <div class="inline-f"><label class="f">If a summer job paid<span class="affix"><span class="pre">$</span><input id="sidePay" type="number" min="0" step="500"><span>a year</span></span></label></div>
    <div id="sideOut"></div></div>
    <div id="ssMore"></div>
  </section>
  <section class="block period" id="s-road" aria-labelledby="h-road">
    <h2 id="h-road">Refund or pension?</h2>
    <p class="lead">If you leave teaching, you can take your TRS money back as a one-time refund instead of a pension.</p>
    <div id="refundOut" aria-live="polite"></div>
  </section>

  <section class="block period" id="s-work" aria-labelledby="h-work">
    <h2 id="h-work">Can I work after I retire?</h2>
    <p class="lead">Yes. Many teachers go back to sub or teach part-time and keep their pension. There are a few rules.</p>
    <div id="workOut"></div>
  </section>

  <section class="block period" id="s-family" aria-labelledby="h-family">
    <h2 id="h-family">Your family</h2>
    <p class="lead">What your family would get if you died, and what to set up now.</p>
    <div id="familyOut"></div>
  </section>

  <section class="block period" id="s-plan" aria-labelledby="h-plan">
    <h2 id="h-plan">Your action plan</h2>
    <p class="note no-pdf" style="margin-top:2px">Your checks are saved with your plan.</p>
    <div id="next3"></div>
    <div class="panel you" style="margin-top:4px"><h3>For your situation</h3><div id="youOut"></div></div>
    <div id="s-pass" hidden><div id="passOut"></div><button type="button" id="passPrint" hidden>Print the checklist</button></div>
  </section>

  <section class="block" id="s-how" aria-labelledby="h-how">
    <button type="button" class="back-btn" id="fpClose">Back to your plan</button>
    <h2 id="h-how">The fine print</h2>
    <details class="section" id="fp-years"><summary>See the numbers year by year</summary>
      <div class="tbl-wrap" tabindex="0" role="region" aria-label="Year by year"><table id="yearTable"></table></div>
      <p class="note">The numbers behind the charts, for the retirement age you chose, per month and in today's dollars (constant purchasing power). Savings left is the full balance at the end of each year.</p>
    </details>
    <details class="section" id="fp-how"><summary>How the math works</summary><ul>
      <li>If you stop teaching before you can retire early, the plan starts your pension when it has no cut. TRS would also let you start it sooner, from 55 (57 for TRS 4), with a cut for life.</li>
      <li>TRS 4 (joined in 2022 or later) has two parts: the foundational pension, and a supplemental account that you and your district pay into. School's Out adds 2% of pay from each and grows it at 2.5% a year, a cautious stand-in for the rate TRS sets from 30-year Treasury yields. The account is counted with your savings when you retire.</li>
      <li>Health prices are TRS's 2026 prices for one person and change every year. A spouse, or children before 65, can join at full cost. If you or your spouse can get insurance through a state-administered employer, you may have to drop TRS coverage. Deductibles and copays aren't counted.</li>
      <li>Working after retirement follows KRS 161.605 as of July 2026. Districts short of teachers can sometimes hire retirees with no earnings limit.</li>
      <li>Savings are spent in this order: other savings, then a 457(b), then other pre-tax accounts, then Roth. Your best order may differ, so ask a tax professional.</li>
      <li>The assisted living test in "What could go wrong" uses Kentucky's 2025 median of $5,528 a month, from the CareScout survey.</li>
      <li>The "money lasts" check runs each year to age 95, spending your bills plus estimated health costs and taxes. Amounts are in today's dollars.</li>
      <li>The reasons for this page come from teachers' real concerns: pensions shrinking with inflation, confusion about Social Security, and <a href="https://www.nctq.org/wp-content/uploads/2025/03/Kentucky_Pensions_NCTQ.pdf" rel="noopener">statements that don't show how benefits build over time</a>.</li>
      <li>Account balances grow at the interest Kentucky law sets: 3% for TRS 1 and 2, and 2.5% for TRS 3. For TRS 4, the law ties the rate to Treasury bond yields, so 2.5% is an assumption.</li>
      <li>Some districts pay out up to 30% of your daily rate for unused sick days instead of buying service credit. For TRS 1 to 3, that payout raises your final year's salary. For TRS 4, it can go into your supplemental account. Ask your district which it offers.</li>
      <li>Kentucky limits how much raises in your last 3 years (5 for TRS 4) can count, unless they come with a new position. Out-of-state credit counts toward the 27-year path for TRS 1 to 3; the TRS 4 rules don't say it counts, so School's Out doesn't count it toward TRS 4 eligibility.</li>
      <li>Health estimates use TRS's 2026 single-coverage prices for the LivingWell PPO plan before 65, and the TRS Medicare plan plus the $202.90 Medicare Part B premium at 65. Before 65, that's the plan's $89.14 cost plus the amount TRS's rate chart sets for your years of service, which is $206.50 with full credit. It assumes no tobacco fee and a completed LivingWell Promise. Lower-cost plans exist, and prices change every year.</li>
      <li>Social Security uses the 2026 formula amounts, and later years may differ.</li>
      <li>Two tax limits aren't raised for inflation, so they matter more each year: Kentucky's $31,110 pension exclusion and the income levels where Social Security starts to be taxed. School's Out shrinks both in today's dollars. Retirement taxes use the standard deduction for your filing status, without the extra deductions for people 65 and older, so they may run a little high.</li>
      <li>School days until school's out use 185 contract days a year, the same count TRS uses for a year of sick leave credit.</li>
      <li>A pension earned before you leave stops growing with salary, so inflation reduces its value until it starts. After it starts, it gets a 1.5% yearly cost-of-living increase.</li>
      <li>Pension estimates use the basic single life annuity and assume your salary rose at your raise rate. Survivor options lower the amount, and TRS doesn't publish by how much. If you enter a survivor option on the Your spouse page, your own figures are used instead.</li>
      <li>One-time amounts are in today's dollars. Money coming in lands in your other savings, treated as already taxed. Money going out is paid from savings like any other bill, so taking it from a pre-tax account adds tax. A one-time cost shows in the savings chart and the year-by-year table, not in the monthly "going out" line.</li>
      <li>Regular healthcare expenses belong in monthly bills. Insurance premiums are estimated separately.</li>
      <li>TRS pensions start on the first day of a month, and you reach a new age for these rules on the first of the month after your birthday. School's Out works in whole years of age, so your real start date may be a few months later than the age shown.</li>
      <li>The law sets the early cut "for each year" you fall short. School's Out counts any part of a year as a full year, the cautious choice. Ask TRS how they count a partial year in your case.</li>
      <li>Part-time or substitute service, extra-duty pay, and leave paid out at retirement can change your numbers. If you were in another Kentucky public retirement system first, TRS may use that date to set your account type. Ask TRS.</li>
    </ul></details>
    <details class="section" id="fp-law"><summary>The Kentucky law behind these numbers</summary><ul class="law-list">
      <li><cite>KRS 161.620</cite>: how the pension is figured, including the rate per year of service, 2% for years before July 1, 1983, 3% for years over 30, the limit that a pension can't be more than your final average salary or last salary, and the 1.5% yearly increase.</li>
      <li><cite>KRS 161.600</cite>: when you can retire, and the early cut of 5% a year (6% if you joined July 2008 or later) for each year under 60 or under 27 years of service, whichever is fewer. For TRS 4, each year under 60 or under 30 years.</li>
      <li><cite>KRS 161.633</cite>: the rules for members who joined Jan. 1, 2022 or later (TRS 4).</li>
      <li><cite>KRS 161.220</cite>: definitions, including final average salary.</li>
      <li><cite>KRS 161.623</cite>: unused sick leave credit, 185 days to a year, capped at 300 days if you joined July 2008 or later.</li>
      <li><cite>KRS 161.675</cite>: health insurance for retirees.</li>
      <li><cite>Kentucky Schedule P</cite>: the $31,110 pension exclusion, and the part of a pension earned before 1998 that Kentucky doesn't tax.</li>
    </ul><p class="note">School's Out uses the average salary for the pension limit, which can be a little lower than what the law allows when your last salary is higher.</p></details>
    <details class="section" id="fp-math"><summary>Check our math</summary>
      <p>The same formulas run these sample teachers, each with a $64,000 final average salary. You can work them by hand.</p>
      <div class="tbl-wrap" tabindex="0" role="region" aria-label="Sample teachers"><table class="check-tbl"><thead><tr><th scope="col">Teacher</th><th scope="col">How it works</th><th scope="col">Yearly pension</th></tr></thead><tbody id="checkRows"></tbody></table></div>
    </details>
    <details class="section" id="fp-words"><summary>Words to know</summary><dl class="gloss">
      <dt>401(k), 403(b) and traditional IRA</dt><dd>Retirement savings accounts. You pay tax on the money when you take it out.</dd>
      <dt>457(b)</dt><dd>A savings plan many school districts offer. After you leave the job, you can take money out before 59½ without the 10% penalty.</dd>
      <dt>Account type (TRS 1 to 4)</dt><dd>Which set of TRS rules you&#39;re under, based on when you joined: TRS 1 before July 2002, TRS 2 to June 2008, TRS 3 to the end of 2021, and TRS 4 from 2022.</dd>
      <dt>Assisted living</dt><dd>Housing with daily help, like meals and medicine. One of the tests in What could go wrong.</dd>
      <dt>Beneficiary</dt><dd>The person you name to get your TRS money if you die.</dd>
      <dt>Break in service</dt><dd>How long you must wait after retiring before working for a TRS employer again: 3 months, or a year for a full-time job with the same district.</dd>
      <dt>Buying service credit</dt><dd>Paying TRS so years like out-of-state teaching or military service count toward your pension.</dd>
      <dt>CERS</dt><dd>The County Employees Retirement System. Bus drivers, custodians, cafeteria workers and other classified school staff are usually in CERS, not TRS.</dd>
      <dt>Cost-of-living increase</dt><dd>A yearly raise to your pension, 1.5% by law for most benefits. Prices usually rise faster, so it buys a little less each year.</dd>
      <dt>Critical shortage</dt><dd>When a district can&#39;t fill a job, it may hire retirees without the usual earnings limit.</dd>
      <dt>Early cut</dt><dd>A permanent reduction for retiring before you reach no-cut status: 5% a year short (6% if you joined in July 2008 or later), counting years under 60 or under 27 years of service, whichever is fewer. For TRS 4, years under 60 or under 30 years, up to 18%.</dd>
      <dt>Early-withdrawal penalty</dt><dd>A 10% tax on money taken from a 401(k), 403(b) or IRA before 59½, with some exceptions.</dd>
      <dt>Extra-duty pay</dt><dd>Pay for coaching, clubs and other work beyond your teaching contract.</dd>
      <dt>Final average salary</dt><dd>The average of your highest five salaries. TRS 1 to 3 members who are 55 with 27 years can use three.</dd>
      <dt>Head of household</dt><dd>A tax filing status for unmarried people who pay most of the costs of a home for a dependent.</dd>
      <dt>Inflation</dt><dd>How fast prices rise. School&#39;s Out shows amounts in today&#39;s dollars, so you can compare them with prices now.</dd>
      <dt>KEHP</dt><dd>The Kentucky Employees&#39; Health Plan. TRS retirees under 65 get health insurance through it.</dd>
      <dt>Medicare and Part B</dt><dd>Federal health insurance from 65. Part B covers doctor visits and has a monthly premium.</dd>
      <dt>Multiplier</dt><dd>The percent of your final average salary earned for each year of service.</dd>
      <dt>No cut (unreduced pension)</dt><dd>TRS pays the full pension your years and salary have earned, with nothing taken off for retiring early.</dd>
      <dt>Pathway</dt><dd>TRS&#39;s online account for members, where you can see your record and request an estimate.</dd>
      <dt>Payroll tax</dt><dd>The 7.65% Social Security and Medicare tax taken from pay at jobs outside Kentucky teaching.</dd>
      <dt>Premium</dt><dd>What you pay each month for insurance.</dd>
      <dt>Reciprocity</dt><dd>A way to combine service across Kentucky public retirement systems to qualify for retirement.</dd>
      <dt>Refund</dt><dd>Taking back your own TRS contributions, with interest, when you leave teaching, instead of a pension.</dd>
      <dt>Retiree health share</dt><dd>The part of your retiree health insurance TRS pays. It grows with your years of service.</dd>
      <dt>Rollover</dt><dd>Moving retirement money straight into an IRA or another plan, so you don&#39;t pay tax on it yet.</dd>
      <dt>Roth IRA and Roth 401(k)</dt><dd>Retirement accounts you pay tax on going in. Money taken out later is tax-free.</dd>
      <dt>Service credit</dt><dd>The years TRS counts toward your pension. Usually one for each school year you work full time.</dd>
      <dt>Sick leave credit</dt><dd>Unused sick days your district may turn into service: every 185 days adds a year.</dd>
      <dt>Social Security credits</dt><dd>Earned through work that pays into Social Security, up to 4 a year. It generally takes 40 to qualify on your own record.</dd>
      <dt>Spouse benefit</dt><dd>Social Security you can get based on your husband or wife&#39;s work record.</dd>
      <dt>Survivor option</dt><dd>A choice at retirement: a smaller pension that keeps paying your beneficiary for life after you die.</dd>
      <dt>Today's dollars</dt><dd>Future amounts shown as what they&#39;d buy now, so they&#39;re easy to compare.</dd>
      <dt>TRS</dt><dd>The Teachers&#39; Retirement System of the State of Kentucky, the pension for teachers and other certified school and university staff.</dd>
      <dt>Vested</dt><dd>You&#39;ve earned a right to a future pension, generally after 5 years of Kentucky service.</dd>
    </dl></details>
    <details class="section" id="fp-left"><summary>What this leaves out</summary><ul>
      <li>Raises, investment returns, health insurance prices, inflation and future tax rules can all change your results. The earliest age that works is a projection, not a guarantee.</li>
      <li>Reciprocal service with other Kentucky systems. Bought years, like out-of-state or military service, use the years and cost you enter, and TRS sets the real cost.</li>
      <li>Limits on late-career raises in the final average salary, and lump-sum leave payouts.</li>
      <li>Child tax credits and disability benefits. Survivor options are counted only if you enter one. If your spouse dies first, some TRS options raise your check again, and that isn't counted. A spouse's income, savings and Social Security are counted only if you say you're married and fill in the Your spouse page. Their pay is entered before taxes. A pension you type in is held level in today's dollars. A TRS pension that School's Out works out for them gets the 1.5% yearly increase. If you leave their Social Security blank, it's estimated from their current pay.</li>
      <li>Required withdrawals from pre-tax accounts, long-term care beyond the assisted living test, and exact taxes on other income.</li>
      <li>Job security, stress, schedule, and how much you love the work. Those can matter as much as the money.</li>
      <li>Future law changes. Retiree health terms can change, and Social Security's future isn't guaranteed.</li>
    </ul></details>
    <details class="section" id="fp-privacy"><summary>Privacy and outside services</summary><p>This page calls no outside services, uses no API key, sets no cookies, and keeps your plan only in this browser on this device until you choose Start over. It doesn't ask for your name, member ID, password, or bank login, and it never connects to Pathway. If you choose to read in your TRS statement, the page picks out your age, service, salaries and balance in this browser and keeps nothing else from it. Your numbers stay here unless you save them to a file on your own device. Source links open only if you click them. It works offline once opened.</p><p><strong>Accessibility.</strong> Every page works with a keyboard and a screen reader, sliders announce their values, charts have text descriptions, and the colours meet contrast guidelines in light and dark mode.</p></details>
    <details class="section" id="fp-sources"><summary>Sources, checked November 2026</summary><ul>
      <li><a href="https://apps.legislature.ky.gov/law/Statutes/statute.aspx?id=57279" rel="noopener">KRS 161.605, working after retirement</a> and <a href="https://trs.ky.gov/retired-members/returning-to-work/" rel="noopener">TRS: Returning to work</a> (used in "Can I work after I retire?")</li>
      <li><a href="https://trs.ky.gov/wp-content/uploads/2020/07/Service-Retirement-Information-Sheet-TRS123-FINAL-202303.pdf" rel="noopener">TRS 1, 2, and 3 service retirement</a> and <a href="https://trs.ky.gov/wp-content/uploads/2021/12/Service-Retirement-Information-Sheet-TRS4-FINAL-202303.pdf" rel="noopener">TRS 4 service retirement</a></li>
      <li><a href="https://trs.ky.gov/wp-content/uploads/2021/12/TRS-4-Summary-Plan-Description-202201.pdf" rel="noopener">TRS 4 Summary Plan Description</a> and <a href="https://trs.ky.gov/wp-content/uploads/2025/12/TRS-2025-ACFR-Final.pdf" rel="noopener">TRS 2025 annual report</a></li>
      <li><a href="https://trs.ky.gov/active-members/membership/pt-or-substitute-teaching/" rel="noopener">TRS contribution rates</a>, <a href="https://trs.ky.gov/active-members/events-affecting-pension/termination-of-employment/" rel="noopener">leaving and withdrawing</a>, and <a href="https://trs.ky.gov/active-members/retirement-planning/reciprocity/" rel="noopener">reciprocity</a></li>
      <li><a href="https://trs.ky.gov/wp-content/uploads/2020/07/Purchases-FINAL-May-2024.pdf" rel="noopener">TRS credit purchases</a> and <a href="https://apps.legislature.ky.gov/law/statutes/statute.aspx?id=51806" rel="noopener">KRS 161.515 on out-of-state service</a></li>
      <li><a href="https://trs.ky.gov/wp-content/uploads/2025/09/4a-4b-TRS-KEHP-Rate-Chart-2026-Final.pdf" rel="noopener">TRS 2026 health rates before 65</a> and <a href="https://trs.ky.gov/wp-content/uploads/2025/10/2026-Turning-65-Booklet-Web-Version.pdf" rel="noopener">TRS 2026 Turning 65 booklet</a></li>
      <li><a href="https://www.cms.gov/newsroom/fact-sheets/2026-medicare-parts-b-premiums-deductibles" rel="noopener">2026 Medicare Part B premium</a> and <a href="https://trs.ky.gov/ktrs-benefit-estimator-calculator/" rel="noopener">TRS's online benefit estimator</a></li>
      <li><a href="https://trs.ky.gov/wp-content/uploads/2022/02/Death-Survivor-FINAL-2022.pdf" rel="noopener">TRS death and survivor benefits</a>, and retirement options for <a href="https://trs.ky.gov/wp-content/uploads/2022/09/Retirement-Options-Information-Sheet-TRS-123.pdf" rel="noopener">TRS 1 to 3</a> and <a href="https://trs.ky.gov/wp-content/uploads/2021/12/Retirement-Options-Information-Sheet-TRS-4-FINAL.pdf" rel="noopener">TRS 4</a></li>
      <li><a href="https://apps.legislature.ky.gov/record/26rs/hb642.html" rel="noopener">House Bill 642 (2026)</a> on return to work and account type</li>
      <li>Kentucky statutes: <a href="https://apps.legislature.ky.gov/law/statutes/statute.aspx?id=56065" rel="noopener">KRS 161.600</a> (eligibility), <a href="https://apps.legislature.ky.gov/law/statutes/statute.aspx?id=57281" rel="noopener">KRS 161.620</a> (benefit formulas), <a href="https://apps.legislature.ky.gov/law/statutes/statute.aspx?id=56196" rel="noopener">KRS 161.220</a> (salary and interest), <a href="https://apps.legislature.ky.gov/law/statutes/statute.aspx?id=51823" rel="noopener">KRS 161.623</a> and <a href="https://apps.legislature.ky.gov/law/statutes/statute.aspx?id=56057" rel="noopener">KRS 161.155</a> (sick leave)</li>
      <li><a href="https://apps.legislature.ky.gov/recorddocuments/note/21RS/hb258/AA.pdf" rel="noopener">HB 258 actuarial note</a> (TRS 4 contribution split and interest assumption)</li>
      <li><a href="https://trs.ky.gov/how-your-trs-benefit-may-affect-your-social-security-benefit/" rel="noopener">TRS and Social Security</a>, <a href="https://www.ssa.gov/benefits/retirement/social-security-fairness-act.html" rel="noopener">Social Security Fairness Act</a>, and <a href="https://www.ssa.gov/OACT/COLA/piaformula.html" rel="noopener">2026 benefit formula</a></li>
      <li><a href="https://revenue.ky.gov/Forms/2026%20Withholding%20Formula.pdf" rel="noopener">Kentucky 2026 withholding formula</a>, <a href="https://www.aarp.org/states/kentucky/state-tax-guide/" rel="noopener">Kentucky retirement income exclusion</a>, and <a href="https://kaco.org/media/7051/2026-databrief-occupationaltaxes.pdf" rel="noopener">county job tax rates</a></li>
      <li><a href="https://www.currentfederaltaxdevelopments.com/blog/2025/10/9/2026-inflation-adjustments-for-tax-professionals-revenue-procedure-2025-32-analysis" rel="noopener">2026 federal tax figures</a></li>
      <li><a href="https://kentuckylantern.com/?p=12400" rel="noopener">Kentucky Lantern on the state's teacher shortage report</a> and <a href="https://kypolicy.org/kentucky-teacher-pensions-are-getting-smaller/" rel="noopener">Kentucky Center for Economic Policy on shrinking pensions</a></li>
      <li><a href="https://www.yahoo.com/news/kentucky-lawmakers-break-promise-teachers-094014223.html" rel="noopener">Coverage of the 2025 retiree health contribution law</a>, <a href="https://www.ssa.gov/OACT/COLA/QC.html" rel="noopener">2026 Social Security credit amount</a>, and <a href="https://www.ssa.gov/survivor/eligibility" rel="noopener">survivor benefit rules</a></li>
      <li><a href="https://www.businesswire.com/news/home/20260302615589/en/CareScout-Releases-2025-Cost-of-Care-Data-for-Kentucky" rel="noopener">CareScout 2025 Cost of Care data for Kentucky</a> (assisted living, used in "What could go wrong")</li>
    </ul><p>TRS offers official estimates through <a href="https://mss.trs.ky.gov/" rel="noopener">Pathway</a>, its member site, or by phone at 800-618-1687. Use School's Out to think through the decision, then use TRS for the real number.</p></details>
  </section>
</div>
</main>

<footer><div class="wrap">
  <nav class="foot-links" aria-label="Fine print"><a href="#fp-how" data-fp>How the math works</a><a href="#fp-words" data-fp>Words to know</a><a href="#fp-privacy" data-fp>Privacy</a><a href="#fp-sources" data-fp>Sources</a><a href="#fp-years" data-fp class="r-only">Year by year</a><a href="#fp-math" data-fp class="r-only">Check our math</a><a href="#fp-left" data-fp class="r-only">What this leaves out</a></nav>
  <p><strong>For educational use only.</strong> These are estimates, not financial, investment, tax, legal, or benefits advice. Only the Teachers' Retirement System of Kentucky (TRS) can give official numbers. School's Out isn't connected to or endorsed by TRS. It also doesn't recommend any investment. Rules change, and your results may differ, so get an official estimate from TRS before you decide.</p>
  <p>School's Out version 1.0, November 2026. &copy; 2026 Carter Overtoom. Released under the <a href="https://opensource.org/license/mit" rel="noopener">MIT License</a>. No third-party code is used. If you publish a copy or changed version, credit it on the page: "Based on School's Out by Carter Overtoom."</p>
</div></footer>
<div id="printPass"></div>
<dialog id="feedbackDialog" class="feedback-modal" aria-labelledby="feedbackTitle" aria-describedby="feedbackDesc">
  <h2 id="feedbackTitle">Feedback</h2>
  <p id="feedbackDesc" class="feedback-note">Have a question, an idea, or a problem to report? Write it here. Don't include personal information.</p>
  <label for="feedbackKind">What is this about?</label>
  <select id="feedbackKind"><option value="Question">Question</option><option value="Suggestion">Suggestion</option><option value="Problem report">Report a problem</option></select>
  <label for="feedbackText">Your message</label>
  <textarea id="feedbackText" placeholder="Tell me what's on your mind…" maxlength="4000"></textarea>
  <div class="feedback-actions"><button type="button" class="feedback-primary" id="feedbackEmail">Open my email app</button><button type="button" id="feedbackClose">Close</button></div>
  <p id="feedbackStatus" class="feedback-status" role="status" aria-live="polite"></p>
</dialog>
<script>
/* The page is running: drop the notice shown to viewers that don't run scripts. */
document.documentElement.classList.add('js'); (function () { var n = document.getElementById('nojs'); if (n) n.parentNode.removeChild(n); })();
'use strict';
/* ---------- Rules, checked November 7, 2026 ---------- */
var R = {
  contrib: { legacy: { school: .12855, univ: .08185 }, four: { school: .1475, univ: .09775 } },
  health: { school: .0375, univ: .02775 },
  fourSupp: .02, fourEmployer: .02, fourInterest: .025,
  std: { single: 16100, hoh: 24150, joint: 32200, mfs: 16100 },
  brackets: {
    mfs: [[12400, .10], [50400, .12], [105700, .22], [201775, .24], [256225, .32], [384350, .35], [Infinity, .37]],
    single: [[12400, .10], [50400, .12], [105700, .22], [201775, .24], [256225, .32], [640600, .35], [Infinity, .37]],
    hoh: [[17700, .10], [67450, .12], [105700, .22], [201750, .24], [256200, .32], [640600, .35], [Infinity, .37]],
    joint: [[24800, .10], [100800, .12], [211400, .22], [403550, .24], [512450, .32], [768700, .35], [Infinity, .37]]
  },
  kyRate: .035, kyStd: 3360, kyPension: 31110,
  ssBase: 184500, bend1: 1286, bend2: 7749, fra: 67, credit: 1890,
  subsidy: {
    '1': [[5, .25], [10, .5], [15, .75], [20, 1]],
    '2': [[5, .1], [10, .25], [15, .45], [20, .65], [25, .9], [26, .95], [27, 1]],
    '3': [[5, .1], [10, .25], [15, .45], [20, .65], [25, .9], [26, .95], [27, 1]],
    '4': [[5, .1], [10, .25], [15, .45], [20, .65], [25, .9], [26, .95], [27, 1]]
  },
  /* Kentucky median for assisted living, a month: CareScout Cost of Care Survey 2025. Used only in "What could go wrong". */
  ltcAssisted: 5528,
  kehpFull: 1016.40, kehpBasis: 809.90, kehpPlan: 89.14, kehpSpouse: 1113.54, mehpFull: 200, partB: 202.90
};

var JOB_TAX = {Adair:.5,Allen:1,Ballard:1.5,Bath:2,Boone:.8,Bourbon:1.25,Boyd:1,Boyle:1.25,Breathitt:2,Butler:1,Caldwell:1.5,Campbell:.9,Carroll:1.5,Carter:1,Clark:1.5,Clay:1,Clinton:1.25,Crittenden:1.5,Cumberland:1.25,Daviess:1,Elliott:1,Estill:2,Fayette:2.25,Franklin:1,Gallatin:1,Garrard:2,Grant:2.5,Graves:1,Grayson:.5,Hancock:1.6,Hardin:1,Harrison:1.5,Hart:.8,Henderson:1,Hickman:1,Hopkins:.5,Jackson:1.85,Jefferson:2.2,Jessamine:1,Johnson:.5,Kenton:.7,Knox:1,Laurel:1,Leslie:1,Lincoln:1,Livingston:1,Logan:.75,Madison:1,Magoffin:1,Marion:1,Marshall:1,Martin:2,Mason:1,McCracken:1,McCreary:1.5,McLean:1,Menifee:1.25,Mercer:1,Metcalfe:1,Monroe:1,Montgomery:2,Morgan:1.5,Nelson:.5,Nicholas:1,Ohio:1.25,Pendleton:1,Perry:1,Pike:1,Powell:1.75,Pulaski:1,Robertson:1.5,Rockcastle:1.5,Rowan:1.5,Russell:1,Scott:1,Shelby:1,Simpson:1.25,Spencer:.8,Taylor:1,Todd:1,Union:.5,Warren:1,Washington:.75,Wayne:.9,Whitley:1,Wolfe:1.25,Woodford:1.5};
var COUNTIES = 'Adair Allen Anderson Ballard Barren Bath Bell Boone Bourbon Boyd Boyle Bracken Breathitt Breckinridge Bullitt Butler Caldwell Calloway Campbell Carlisle Carroll Carter Casey Christian Clark Clay Clinton Crittenden Cumberland Daviess Edmonson Elliott Estill Fayette Fleming Floyd Franklin Fulton Gallatin Garrard Grant Graves Grayson Green Greenup Hancock Hardin Harlan Harrison Hart Henderson Henry Hickman Hopkins Jackson Jefferson Jessamine Johnson Kenton Knott Knox Larue Laurel Lawrence Lee Leslie Letcher Lewis Lincoln Livingston Logan Lyon Madison Magoffin Marion Marshall Martin Mason McCracken McCreary McLean Meade Menifee Mercer Metcalfe Monroe Montgomery Morgan Muhlenberg Nelson Nicholas Ohio Oldham Owen Owsley Pendleton Perry Pike Powell Pulaski Robertson Rockcastle Rowan Russell Scott Shelby Simpson Spencer Taylor Todd Trigg Trimble Union Warren Washington Wayne Webster Whitley Wolfe Woodford'.split(' ');

/* ---------- TRS rules ---------- */
/* Interest on member accounts, KRS 161.220(13): 3% for TRS 1 and 2, 2.5% for TRS 3.
   TRS 4 follows Treasury yields, so 2.5% is an assumption. */
function acctRate(type) { return type === '1' || type === '2' ? .03 : .025; }
/* Out-of-state credit counts toward the 27-year path for TRS 1 to 3 (KRS 161.600). TRS 4 rules don't say so. */
function eligBought(type, kyYears, wanted) { return type === '4' ? 0 : allowedOutOfState(kyYears, wanted); }
function multiplier(type, univ, years, age) {
  var y = years;
  if (type === '4') {
    var a = Math.max(0, Math.min(5, age - 60)) / 5 * .2;
    var base = (univ ? .7 : 1.7) + a;
    var career = y >= 30 ? .5 : y >= 20 ? .25 : 0;
    return base + career;
  }
  if (univ) {
    if (type === '3') return y <= 10 ? 1.5 : y <= 20 ? 1.7 : y < 27 ? 1.85 : 2;
    return 2;
  }
  if (type === '1') return 2.5;
  if (type === '2') return y < 10 ? 2 : 2.5;
  return y <= 10 ? 1.7 : y <= 20 ? 2 : y <= 26 ? 2.3 : 2.5;
}

/* Percent of final average salary, before any early reduction. */
/* TRS 1 years before July 1, 1983 earn 2% instead of 2.5% (KRS 161.620). */
function pre83Years(h) {
  if (h.type !== '1' || h.univ) return 0;
  if (typeof h.pre83 === 'number' && h.pre83 >= 0) return Math.min(h.years, h.pre83);
  if (!h.startYear || h.startYear >= 1983) return 0;
  return Math.max(0, Math.min(h.years, 1983 - h.startYear));
}
/* A pension can't be more than the final average salary (TRS allows up to the greater of that or the last salary; we use the average, the safer choice). */
function percentOfSalary(type, univ, years, age, pre83) { return Math.min(100, rawPercent(type, univ, years, age, pre83)); }
function rawPercent(type, univ, years, age, pre83) {
  var m = multiplier(type, univ, years, age);
  if (type === '1' && !univ && pre83 > 0) {
    var p = Math.min(pre83, years, 30);
    return p * 2 + (Math.min(years, 30) - p) * m + Math.max(0, years - 30) * 3;
  }
  if (type !== '4' && !univ && years > 30) return 30 * m + (years - 30) * 3;
  return years * m;
}

function isUnreduced(type, years, age) {
  if (type === '4') return (age >= 57 && years >= 30) || (age >= 60 && years >= 10) || (age >= 65 && years >= 5);
  return years >= 27 || (age >= 60 && years >= 5);
}

function reductionAt(type, years, age) {
  if (isUnreduced(type, years, age)) return 0;
  if (type === '4') {
    if (age >= 57 && years >= 10) return Math.min(18, 6 * Math.ceil(Math.min(60 - age, 30 - years) - 1e-9));
    return null;
  }
  var rate = type === '3' ? 6 : 5, need = type === '3' ? 10 : 5;
  if (age >= 55 && years >= need) return rate * Math.ceil(Math.min(60 - age, 27 - years) - 1e-9);
  return null;
}

function firstFullAge(type, years, fromAge) {
  if (years < 5) return null;
  var ages = type === '4'
    ? [years >= 30 ? 57 : null, years >= 10 ? 60 : null, 65]
    : [years >= 27 ? 0 : null, 60];
  var best = Infinity;
  ages.forEach(function (a) { if (a !== null) best = Math.min(best, a); });
  return Math.max(best, fromAge);
}

function subsidyShare(type, years) {
  var share = 0;
  R.subsidy[type].forEach(function (s) { if (years >= s[0]) share = s[1]; });
  return share;
}
function preMedicareCost(share) { return R.kehpPlan + Math.max(0, R.kehpFull - share * R.kehpBasis); }
function medicareCost(type, years) { return R.mehpFull * (1 - subsidyShare(type, years)) + R.partB; }
/* In the form: would stopping now leave this teacher without TRS retiree health insurance? */
function healthEligible(type, years) {
  if (type === '3' || type === '4') return years >= 15;
  return years >= 5;
}

/* ---------- Taxes (today's dollars) ---------- */
function incomeTax(taxable, status) {
  var tax = 0, low = 0;
  R.brackets[status].some(function (b) {
    var part = Math.min(taxable, b[0]) - low;
    if (part > 0) tax += part * b[1];
    low = b[0];
    return taxable <= b[0];
  });
  return tax;
}

function workTaxes(h, gross, pretaxRate, ficaRate, localRate) {
  var pretax = gross * pretaxRate;
  var fed = incomeTax(Math.max(0, gross - pretax - R.std[h.status]), h.status);
  var ky = Math.max(0, gross - pretax - R.kyStd) * R.kyRate;
  var fica = gross * ficaRate;
  var local = gross * localRate / 100;
  return { pretax: pretax, fed: fed, ky: ky, fica: fica, local: local, net: gross - pretax - fed - ky - fica - local };
}

function teachingPay(h, gross) {
  var set = h.type === '4' ? R.contrib.four : R.contrib.legacy;
  var rate = h.univ ? set.univ : set.school;
  return workTaxes(h, gross, rate, h.univ ? .0765 : .0145, h.localRate);
}
function jobPay(h, path, gross) {
  return workTaxes(h, gross, 0, path.covered ? .0765 : .0145, path.localRate);
}

/* Share of a TRS pension earned before Jan. 1, 1998, which Kentucky doesn't tax (Schedule P). */
function pre98Share(h, service) {
  var sy = h.startYear;
  if (!sy || sy >= 1998 || !(service > 0)) return 0;
  return Math.max(0, Math.min(1, (1998 - sy - 0.5) / service));
}
/* exempt: TRS pension earned before 1998. ahead: years from now, because Kentucky's $31,110 exclusion and the Social Security tax thresholds aren't raised for inflation. */
function retireTax(h, pension, ss, other, exempt, ahead, spPen) {
  exempt = exempt || 0; spPen = spPen || 0;
  var erode = Math.pow(1 + h.inflation / 100, Math.max(0, ahead || 0));
  var kyExcl = R.kyPension / erode;
  var joint = h.status === 'joint';
  /* The income levels where Social Security becomes taxable aren't raised for inflation either. */
  /* A married couple filing separately who live together has no tax-free threshold for Social Security. */
  var mfs = h.status === 'mfs', base1 = (joint ? 32000 : mfs ? 0 : 25000) / erode, base2 = (joint ? 44000 : mfs ? 0 : 34000) / erode;
  var provisional = pension + other + spPen + ss / 2;
  var taxableSs = 0;
  if (provisional > base2) taxableSs = Math.min(.85 * ss, .85 * (provisional - base2) + Math.min(.5 * ss, .5 * (base2 - base1)));
  else if (provisional > base1) taxableSs = Math.min(.5 * ss, .5 * (provisional - base1));
  var fed = incomeTax(Math.max(0, pension + other + spPen + taxableSs - R.std[h.status]), h.status);
  /* Kentucky's pension exclusion is per person, so a spouse's pension gets its own. */
  /* Someone who retires to another state doesn't pay Kentucky income tax. That state's own tax isn't modelled. */
  var ky = h.outKy ? 0 : Math.max(0, Math.max(0, pension - exempt - kyExcl) + Math.max(0, spPen - kyExcl) + other - R.kyStd) * R.kyRate;
  return fed + ky;
}

function ssMonthly(pia, claimAge) {
  var diff = (claimAge - R.fra) * 12;
  var f = diff >= 0 ? 1 + diff * (2 / 3) / 100
    : 1 - (Math.min(-diff, 36) * (5 / 9) + Math.max(-diff - 36, 0) * (5 / 12)) / 100;
  return pia * f;
}
function piaFromEarnings(list) {
  var top = list.slice().sort(function (a, b) { return b - a; }).slice(0, 35);
  var aime = top.reduce(function (s, v) { return s + Math.min(v, R.ssBase); }, 0) / 35 / 12;
  var pia = .9 * Math.min(aime, R.bend1) + .32 * Math.max(0, Math.min(aime, R.bend2) - R.bend1) + .15 * Math.max(0, aime - R.bend2);
  return Math.floor(pia * 10) / 10;
}

/* ---------- Simulation: everything in today's dollars ---------- */
function teachNominal(h, sw, k) {
  if (sw && k >= sw.at) return sw.salary * Math.pow(1 + h.inflation / 100, sw.at) * Math.pow(1 + h.raise / 100, k - sw.at);
  if (k < 0 && h.fasPast > 0) {
    /* The teacher's own average of their last 5 salaries (this year included), or of all of them if they have fewer, sets the past years. */
    var cnt = Math.max(2, Math.min(5, Math.ceil(h.years || 5)));
    var past = Math.max(0, (cnt * h.fasPast - h.salary) / (cnt - 1));
    return k >= -4 ? past : past * Math.pow(1 + h.raise / 100, k + 4);
  }
  return h.salary * Math.pow(1 + h.raise / 100, k);
}
function teachHistory(h, teachMore, sw) {
  var list = [], n = Math.max(1, Math.ceil(h.years + teachMore));
  var first = Math.max(0, Math.ceil(teachMore) - 1);
  for (var k = 0; k < n; k++) list.push(teachNominal(h, sw, first - k));
  return list;
}

function finalAverage(h, teachMore, years, age, sw) {
  var count = (h.type !== '4' && age >= 55 && years >= 27) ? 3 : 5;
  var list = teachHistory(h, teachMore, sw).sort(function (a, b) { return b - a; }).slice(0, count);
  return list.reduce(function (s, v) { return s + v; }, 0) / list.length;
}

function accountEstimate(h, teachMore) {
  var set = h.type === '4' ? R.contrib.four : R.contrib.legacy;
  var rate = (h.univ ? set.univ : set.school) - (h.univ ? R.health.univ : R.health.school);
  var hist = teachHistory(h, teachMore).reverse();
  var bal = 0;
  var r = 1 + acctRate(h.type);
  hist.forEach(function (s) { bal = bal * r + s * rate; });
  return bal;
}
function balanceAt(h, teachMore) {
  if (h.balance > 0) {
    var extra = 0;
    var set = h.type === '4' ? R.contrib.four : R.contrib.legacy;
    var rate = (h.univ ? set.univ : set.school) - (h.univ ? R.health.univ : R.health.school);
    var r = 1 + acctRate(h.type);
    for (var i = 0; i < Math.ceil(teachMore); i++) extra = extra * r + h.salary * Math.pow(1 + h.raise / 100, i) * rate;
    return h.balance * Math.pow(r, teachMore) + extra;
  }
  return accountEstimate(h, teachMore);
}
function supplementAt(h, teachMore, sw, includeMember) {
  if (h.type !== '4') return 0;
  var hist = teachHistory(h, teachMore, sw).reverse(), bal = 0;
  hist.forEach(function (s) { bal = bal * (1 + R.fourInterest) + s * ((includeMember ? R.fourSupp : 0) + R.fourEmployer); });
  return bal;
}

/* Out-of-state teaching: one year for every two Kentucky years, up to 10. */
function allowedOutOfState(kyYears, wanted) {
  var limit = kyYears < 2 ? 0 : kyYears >= 10 ? 10 : Math.floor(kyYears / 2);
  return Math.min(limit, wanted);
}

function simulate(h, path) {
  var i = h.inflation / 100, g = h.returnRate / 100;
  var dr = ((1 + g) / (1 + i) - 1);
  var a0 = h.age, stop = Math.max(a0, h.stopAge), end = 90;
  var sw = (!path.stay && path.trs) ? { at: path.more, salary: path.salary, localRate: path.localRate } : null;
  var teachMore = (path.stay || path.trs) ? stop - a0 : Math.min(path.more, Math.max(0, stop - a0));
  var serviceAtLeave = h.years + teachMore;
  var boughtNow = allowedOutOfState(serviceAtLeave, h.boughtYears || 0);
  var eligYears = serviceAtLeave + eligBought(h.type, serviceAtLeave, h.boughtYears || 0);
  var benefitYears = serviceAtLeave + boughtNow + h.sickYears;
  var leaveAge = a0 + teachMore;
  var vested = serviceAtLeave >= 5;
  var fasNominal = finalAverage(h, teachMore, serviceAtLeave, leaveAge, sw);
  var startAge = vested ? firstFullAge(h.type, eligYears, leaveAge) : null;
  var earlyCut = 0;
  if (vested && h.takeEarly && startAge > leaveAge) {
    var cutNow = reductionAt(h.type, eligYears, leaveAge);
    if (cutNow) { earlyCut = cutNow; startAge = leaveAge; }
  }
  var pensionAnnualNominal = 0;
  /* A survivor option trades a smaller check for payments that continue to a spouse. The cut is the teacher's own figure from TRS. */
  var survF = h.sp && h.sp.on && h.sp.survCut > 0 ? 1 - Math.min(50, h.sp.survCut) / 100 : 1;
  if (vested) pensionAnnualNominal = fasNominal * percentOfSalary(h.type, h.univ, benefitYears, startAge, pre83Years(h)) / 100 * (1 - earlyCut / 100) * survF;

  var refundCash = 0;
  if (!vested) refundCash = balanceAt(h, teachMore) / Math.pow(1 + i, teachMore);
  var suppReal = vested ? supplementAt(h, teachMore, sw, true) / Math.pow(1 + i, teachMore) : 0;

  var pensionRealAtStart = vested ? pensionAnnualNominal / Math.pow(1 + i, startAge - a0) : 0;
  var colaReal = (h.noCola ? 1 : 1.015) / (1 + i) - 1;

  /* Social Security */
  var coveredEarnings = [];
  for (var c = 0; c < h.ssYears; c++) coveredEarnings.push(h.ssAvg);
  var workYearsTotal = Math.max(0, stop - a0);
  for (var n0 = 0; n0 < workYearsTotal; n0++) {
    if (n0 < teachMore) { if (h.univ) coveredEarnings.push(teachNominal(h, sw, n0) / Math.pow(1 + i, n0)); }
    else if (path.covered) coveredEarnings.push(path.salary * Math.pow((1 + path.raise / 100) / (1 + i), n0 - teachMore));
  }
  var credits = Math.min(40, coveredEarnings.length * 4);
  var pia = credits >= 40 ? piaFromEarnings(coveredEarnings) : 0;
  var ssMonth = pia ? ssMonthly(pia, h.claimAge) : 0;

  /* Year by year */
  var value = 0, rows = [], parts = { pay: 0, match: 0, pension: 0, ss: 0, tax: 0, health: 0, lump: 0 };
  var share = subsidyShare(h.type, serviceAtLeave), hEligible = healthEligible(h.type, serviceAtLeave);
  for (var n = 0; a0 + n < end; n++) {
    var age = a0 + n, net = 0, match = 0, health = 0, pensionNow = 0, ssNow = 0, teaching = false, gross = 0;
    if (age < stop) {
      if (n < teachMore) {
        teaching = true;
        gross = teachNominal(h, sw, n) / Math.pow(1 + i, n);
        net = teachingPay(sw && n >= sw.at ? Object.assign({}, h, { localRate: sw.localRate }) : h, gross).net;
        health = h.teachHealth * 12;
      } else {
        gross = path.salary * Math.pow((1 + path.raise / 100) / (1 + i), n - teachMore);
        net = jobPay(h, path, gross).net;
        match = gross * path.match / 100;
        health = path.health * 12;
        if (path.gap && n - teachMore < path.gap) { gross = 0; net = 0; match = 0; health = h.marketHealth * 12; }
      }
    }
    if (vested && age >= startAge) pensionNow = pensionRealAtStart * Math.pow(1 + colaReal, age - startAge);
    if (age >= h.claimAge) ssNow = ssMonth * 12;
    if (age >= stop) {
      var trsRetired = vested && age >= startAge;
      if (age < 65) {
        health = (trsRetired && hEligible)
          ? preMedicareCost(share) * 12
          : h.marketHealth * 12;
      } else {
        health = (trsRetired && hEligible) ? medicareCost(h.type, serviceAtLeave) * 12 : h.medicareOther * 12;
      }
    }
    var retireTaxes = (pensionNow || ssNow) ? retireTax(h, pensionNow, ssNow, gross, pensionNow * pre98Share(h, serviceAtLeave), age - h.age) - retireTax(h, 0, 0, gross, 0, age - h.age) : 0;
    var cash = net + match * .85 + pensionNow + ssNow - retireTaxes - health;
    if (n === Math.floor(teachMore) && refundCash) cash += refundCash * .85;
    if (age === stop) cash += suppReal * .85;
    var df = Math.pow(1 + dr, n);
    value += cash / df;
    parts.pay += net / df; parts.match += match * .85 / df; parts.pension += pensionNow / df; parts.ss += ssNow / df; parts.tax -= retireTaxes / df; parts.health -= health / df;
    if (n === Math.floor(teachMore) && refundCash) parts.lump += refundCash * .85 / df;
    if (age === stop) parts.lump += suppReal * .85 / df;
    rows.push({ age: age, teaching: teaching, gross: gross, net: net, pension: pensionNow, ss: ssNow, health: health, match: match, tax: retireTaxes });
  }

  /* Savings grown only to the stopping age, then level to age 90 */
  var w = Math.max(0, h.savings + (h.rothBal || 0) + (h.otherBal || 0) + (h.b457Bal || 0) - (boughtNow > 0 ? (h.boughtCost || 0) : 0));
  rows.forEach(function (r) {
    if (r.age >= stop) return;
    var yrSave = r.teaching ? (h.saveMonthly + (h.rothMonthly || 0) + (h.otherMonthly || 0) + (h.b457Monthly || 0)) * 12 : r.gross * path.save / 100 + r.match;
    w = w * (1 + dr) + yrSave;
  });
  if (refundCash) w += refundCash * .85;
  w += suppReal;
  var yearsDraw = Math.max(1, end - stop);
  var drawAnnual = dr > 0 ? w * dr / (1 - Math.pow(1 + dr, -yearsDraw)) : w / yearsDraw;

  var at67 = rows.filter(function (r) { return r.age >= Math.max(67, stop); })[0] || rows[rows.length - 1];
  /* Social Security is read at the claiming age, so claiming at 68 to 70 isn't missed. */
  var atClaim = rows.filter(function (r) { return r.age >= Math.max(h.claimAge || 67, stop); })[0] || rows[rows.length - 1];

  return {
    replacePct: vested ? percentOfSalary(h.type, h.univ, benefitYears, startAge, pre83Years(h)) * (1 - earlyCut / 100) * survF : 0, survF: survF,
    otherPension: h.otherPension || 0, otherPensionAge: h.otherPensionAge || 65, boughtNow: boughtNow, pensionRealAtStart: pensionRealAtStart, colaReal: colaReal, path: path, parts: parts, value: value, earlyCut: earlyCut, teachMore: teachMore, service: serviceAtLeave, leaveAge: leaveAge, vested: vested, startAge: startAge,
    fasNominal: fasNominal, pensionNominal: pensionAnnualNominal, pensionMonthlyAtStart: pensionRealAtStart / 12,
    pensionMonthly67: at67.pension / 12, ssMonthly: atClaim.ss / 12, savingsMonthly: drawAnnual / 12, savingsAtStop: w,
    healthMonthlyPre65: (vested && hEligible) ? preMedicareCost(share) : h.marketHealth,
    share: share, healthEligible: hEligible, credits: credits, pia: pia, refundCash: refundCash, supplement: suppReal,
    totalMonthly67: at67.pension / 12 + atClaim.ss / 12 + drawAnnual / 12, rows: rows, stop: stop
  };
}

function refundView(h, path) {
  var more = path.stay ? 0 : path.more;
  var service = h.years + more;
  var age = h.age + more;
  var gross = balanceAt(h, more) + (h.type === '4' && service >= 5 ? supplementAt(h, more, null, false) : 0);
  /* No 10% penalty for someone who leaves the job in or after the year they turn 55 (IRC 72(t)(2)(A)(v)). */
  var penalty = age < 55 ? gross * .1 : 0;
  var income = path.salary || 0;
  var fed = incomeTax(Math.max(0, income + gross - R.std[h.status]), h.status) - incomeTax(Math.max(0, income - R.std[h.status]), h.status);
  var ky = Math.max(0, gross - R.kyPension) * R.kyRate;
  var after = gross - penalty - fed - ky;
  var sim = simulate(h, path);
  var months = sim.pensionMonthlyAtStart > 0 ? after / sim.pensionMonthlyAtStart : null;
  return { gross: gross, penalty: penalty, fed: fed, ky: ky, after: after, sim: sim, months: months, eligibleNow: service >= 5 && isEligibleToRetire(h.type, service, age) };
}

/* "an 18%", "a 25%" */
function aPct(n) { return (/^(8|11|18|8\d)$/.test(String(Math.round(n))) ? 'an ' : 'a ') + n; }
/* Retirement starts July 1 after the last school year. If this year's July 1 has passed, that's next July. */
function retireDate(yrsOut) { var now = new Date(), d = new Date(now.getFullYear() + Math.max(0, yrsOut), 6, 1); return d <= now ? new Date(now.getFullYear() + 1, 6, 1) : d; }
function isEligibleToRetire(type, years, age) { return reductionAt(type, years, age) !== null; }

/* Summer or side work that pays into Social Security while you keep teaching. */
function sideWork(h, stay, pay) {
  var needed = Math.max(0, 40 - stay.credits);
  var creditsPerYear = Math.min(4, Math.floor(pay / R.credit));
  if (creditsPerYear < 1) return { creditsPerYear: 0 };
  var years = Math.ceil(needed / creditsPerYear);
  var list = [];
  for (var c = 0; c < h.ssYears; c++) list.push(h.ssAvg);
  for (var y = 0; y < Math.max(years, 1); y++) list.push(pay);
  var monthly = ssMonthly(piaFromEarnings(list), h.claimAge);
  return { creditsPerYear: creditsPerYear, years: years, monthly: monthly, costYear: pay * .0765, needed: needed };
}

/* ---------- Retirement planning ---------- */
var STAY = { stay: true, more: 0, salary: 0, raise: 0, localRate: 0, match: 0, save: 0, health: 0, covered: false };
function retireAt(h, age) {
  return simulate(Object.assign({}, h, { stopAge: age, takeEarly: true }), Object.assign({}, STAY, { localRate: h.localRate }));
}
function incomeLater(s) { return s.pensionMonthlyAtStart + s.savingsMonthly + s.ssMonthly + (s.otherPension || 0); }
function firstFullRetireAge(h) {
  for (var a = h.age; a <= 75; a++) {
    var y = h.years + (a - h.age);
    if (y >= 5 && isUnreduced(h.type, y + eligBought(h.type, y, h.boughtYears || 0), a)) return a;
  }
  return null;
}
function firstAnyRetireAge(h) {
  for (var a = h.age; a <= 75; a++) {
    var y = h.years + (a - h.age);
    if (y >= 5 && reductionAt(h.type, y + eligBought(h.type, y, h.boughtYears || 0), a) !== null) return a;
  }
  return null;
}
function retireTable(h) {
  var start = firstAnyRetireAge(h);
  if (start === null) return [];
  var out = [], full = firstFullRetireAge(h), last = Math.min(75, Math.max(start + 12, 67));
  for (var a = start; a <= last; a++) {
    var s = retireAt(h, a);
    out.push({ age: a, service: s.service, pension: s.pensionMonthlyAtStart, cut: s.earlyCut, savings: s.savingsMonthly, ss: s.ssMonthly, total: incomeLater(s), full: a === full, health: s.healthMonthlyPre65, sim: s });
  }
  return out;
}
/* Bills can step to a new level at some age (a mortgage ends, a parent's care starts). Both levels are in today's dollars. */
function billsAt(h, a) { return h.goalLater > 0 && h.goalLaterAge > 0 && a >= h.goalLaterAge ? h.goalLater : h.goal; }
function scaleBills(h, f, add) { return Object.assign({}, h, { goal: Math.max(0, h.goal * f + (add || 0)), goalLater: h.goalLater > 0 ? Math.max(1, h.goalLater * f + (add || 0)) : 0 }); }
/* "What could go wrong": each test has a size the teacher can drag. riskOpts holds their choices for this visit only. */
var riskOpts = {};
function riskSpec(h) {
  var care = Math.max(85, h.stopAge + 1);
  return [
    { k: 'bills', min: 0, max: 50, step: 5, def: 10, lab: function (v) { return 'Your bills run ' + v + '% higher'; }, mod: function (hh, v) { return scaleBills(hh, 1 + v / 100); } },
    { k: 'ret', min: 0, max: Math.max(0, h.returnRate), step: 0.25, def: Math.min(h.returnRate, 3), lab: function (v) { return 'Your savings grow only ' + v + '%'; }, mod: function (hh, v) { return Object.assign({}, hh, { returnRate: v }); } },
    { k: 'infl', min: h.inflation, max: 6, step: 0.25, def: Math.max(h.inflation, 3.5), lab: function (v) { return 'Prices rise ' + v + '% a year'; }, mod: function (hh, v) { return Object.assign({}, hh, { inflation: v }); } },
    { k: 'fees', min: 0, max: 2, step: 0.25, def: 1, lab: function (v) { return 'You pay ' + v + '% a year more in fees'; }, mod: function (hh, v) { return Object.assign({}, hh, { returnRate: Math.max(0, hh.returnRate - v) }); } },
    { k: 'raise', min: 0, max: Math.max(0, h.raise), step: 0.25, def: Math.min(h.raise, 1), lab: function (v) { return 'Your raises are only ' + v + '%'; }, mod: function (hh, v) { return Object.assign({}, hh, { raise: v }); } },
    { k: 'crash', min: 0, max: 50, step: 5, def: 25, lab: function (v) { return 'Your savings fall ' + v + '% the year you retire'; }, mod: function (hh, v) { return Object.assign({}, hh, { crash: v / 100 }); } },
    { k: 'care', min: 0, max: 6, step: 1, def: 2, lab: function (v) { return (h.sp && h.sp.on ? 'One of you needs ' : 'You need ') + v + (v === 1 ? ' year' : ' years') + ' of assisted living at ' + care; }, mod: function (hh, v) { return v > 0 ? Object.assign({}, hh, { care: { age: care, years: v, monthly: R.ltcAssisted } }) : hh; } }
  ];
}
function retireStress(h, age) {
  var run = function (label, hh, spec) { var r = survive(hh, age), gap = 0, cost = 0; r.rows.forEach(function (w) { gap += w.short; cost += w.bills + w.health + w.tax + (w.once || 0); }); return { label: label, lasts: r.lasts, age: r.firstShort, monthly: r.shortMonthly, covered: cost > 0 ? Math.max(0, 1 - gap / cost) : 1, spec: spec }; };
  var out = [run('These assumptions', h)];
  riskSpec(h).forEach(function (sp) {
    var v = riskOpts[sp.k]; if (v === undefined || v < sp.min || v > sp.max) v = sp.def;
    sp.val = v; out.push(run(sp.lab(v), sp.mod(h, v), sp));
  });
  return out.concat(h.ssYears > 0 ? [run('You have no Social Security from earlier work', Object.assign({}, h, { ssYears: 0, ssAvg: 0 }))] : [])
   .concat(h.sp && h.sp.on ? [run('You die at ' + Math.max(80, age + 5) + (h.sp.survShare > 0 ? ', and your spouse keeps ' + h.sp.survShare + '% of your pension' : ', and your pension stops'), Object.assign({}, h, { meEnds: Math.max(80, age + 5) }))] : [])
   .concat(h.sp && h.sp.on ? [run('Your spouse dies at ' + Math.max(80, age + 5), Object.assign({}, h, { spEnds: Math.max(80, age + 5) }))] : []);
}

/* Health coverage for someone who teaches until retirement. */
function healthPlan(h, sim) {
  var eligible = sim.vested && sim.healthEligible;
  var pre = eligible ? preMedicareCost(sim.share) : h.marketHealth;
  var post = eligible ? medicareCost(h.type, sim.service) : h.medicareOther;
  var yearsPre = Math.max(0, 65 - Math.max(sim.stop, h.age));
  var preStarts = sim.vested ? Math.max(sim.stop, sim.startAge) : sim.stop;
  var gapYears = eligible ? Math.max(0, Math.min(65, preStarts) - sim.stop) : 0;
  var next = null;
  R.subsidy[h.type].forEach(function (st) {
    if (next === null && st[0] > sim.service && st[1] > sim.share && (h.type !== '3' && h.type !== '4' || st[0] >= 15)) next = { years: st[0], share: st[1], cost: preMedicareCost(st[1]) };
  });
  return { eligible: eligible, pre: pre, post: post, yearsPre: yearsPre, gapYears: gapYears, next: next, share: sim.share };
}

/* ---------- Will the money last? ---------- */
var LAST_AGE = 95;
/* Big one-time amounts the teacher expects: money in (a house sale, an inheritance) or out (a wedding, a roof). Today's dollars. */
function oneTimes(h) { return [1, 2, 3].map(function (n) { return { amt: h['ot' + n + 'Amt'] || 0, age: Math.round(h['ot' + n + 'Age'] || 0), out: !!h['ot' + n + 'Out'] }; }).filter(function (o) { return o.amt > 0 && o.age > 0; }); }
/* A spouse's benefit on the other's record: half their full amount, less if claimed before 67, never more for waiting. */
function spousalFactor(claim) { var m = Math.max(0, (R.fra - claim) * 12); return 1 - (Math.min(m, 36) * 25 / 36 + Math.max(0, m - 36) * 5 / 12) / 100; }
function survive(h, age, sim) {
  var s = sim || retireAt(h, age);
  var dr = ((1 + h.returnRate / 100) / (1 + h.inflation / 100) - 1);
  var work = Math.max(0, s.stop - h.age);
  var grow = function (bal, monthly) { var w = bal || 0; for (var y = 0; y < work; y++) w = w * (1 + dr) + (monthly || 0) * 12; return w; };
  var roth = grow(h.rothBal, h.rothMonthly), other = grow(h.otherBal, h.otherMonthly), f457 = grow(h.b457Bal, h.b457Monthly);
  var pre = Math.max(0, s.savingsAtStop - roth - other - f457);
  /* Spouse: pay until they stop, pension, Social Security, savings, and health coverage if it's through TRS. */
  var sp = h.sp && h.sp.on ? h.sp : null, ageGap = sp ? sp.age - h.age : 0, spSs = 0;
  if (sp) {
    var w2 = sp.savings || 0, spWork = Math.max(0, sp.stopAge - sp.age);
    for (var y2 = 0; y2 < work; y2++) w2 = w2 * (1 + dr) + (y2 < spWork ? (sp.saveMonthly || 0) * 12 : 0);
    pre += w2;
    spSs = sp.pia > 0 ? ssMonthly(sp.pia, sp.claimAge || 67) * 12 : 0;
  }
  /* One-time money before retirement goes into savings, or comes out of it, and grows or is missed until the stop age. */
  var ots = oneTimes(h);
  ots.forEach(function (o) {
    if (o.age >= s.stop) return;
    var v = o.amt * Math.pow(1 + dr, Math.max(0, s.stop - Math.max(o.age, h.age))), t;
    if (!o.out) { other += v; return; }
    t = Math.min(other, v); other -= t; v -= t; t = Math.min(f457, v); f457 -= t; v -= t; t = Math.min(pre, v); pre -= t; v -= t; roth = Math.max(0, roth - v);
  });
  /* A "what could go wrong" test: savings drop by this share the year you retire. */
  if (h.crash > 0) { roth *= 1 - h.crash; other *= 1 - h.crash; f457 *= 1 - h.crash; pre *= 1 - h.crash; }
  var hp = healthPlan(h, s), rows = [], firstShort = null, shortMonthly = 0, earlyPenaltyRisk = false;
  var otherIncome = (h.otherIncome || 0) * 12, p98 = pre98Share(h, s.service);
  for (var a = s.stop; a <= LAST_AGE; a++) {
    var pension = (s.vested && a >= s.startAge) ? s.pensionRealAtStart * Math.pow(1 + s.colaReal, a - s.startAge) : 0, trsOnly = pension;
    var ex98 = pension * p98;
    if (s.otherPension && a >= s.otherPensionAge) pension += s.otherPension * 12;
    var ssMine = a >= h.claimAge ? s.ssMonthly * 12 : 0, ssSp = 0;
    var spouse = 0, spPen = 0, spHealth = 0, spWage = 0, spSave = 0, widowed = !!(sp && h.spEnds && a >= h.spEnds), gone = !!(sp && h.meEnds && a >= h.meEnds);
    /* If the teacher dies first, the spouse keeps the survivor share, or nothing on the basic option. */
    if (gone) { var keepS = Math.min(100, sp.survShare || 0) / 100; pension = trsOnly * keepS; ex98 *= keepS; }
    if (sp) {
      var sa = a + ageGap, spClaim = sp.claimAge || 67;
      if (!widowed) {
        spPen = (sa >= (sp.pensionAge || 65) ? (sp.pension || 0) * 12 : 0) + (sp.trsPension && sa >= sp.trsAge ? sp.trsPension * 12 * Math.pow(1 + (sp.trsCola || 0), sa - sp.trsAge) : 0);
        spWage = sa < sp.stopAge ? (sp.pay || 0) * 12 : 0;
        /* What they put into savings comes out of their pay and goes into the savings pot, so it isn't spent twice. */
        spSave = sa < sp.stopAge ? Math.min(spWage, (sp.saveMonthly || 0) * 12) : 0;
        spouse = spWage - spSave + spPen;
        if (sa >= spClaim) {
          ssSp += spSs;
          /* Since 2025 a TRS pension no longer cuts spouse benefits, so either of you can be topped up to half the other's full amount. */
          if (a >= h.claimAge) { ssMine += Math.max(0, sp.pia / 2 - s.pia) * spousalFactor(h.claimAge) * 12; ssSp += Math.max(0, s.pia / 2 - sp.pia) * spousalFactor(spClaim) * 12; }
        }
        /* Spouse coverage starts no earlier than the teacher's retirement and the start of eligible retiree coverage. */
        if (sp.onTrs && hp.eligible && s.vested && a >= Math.max(s.stop, s.startAge)) spHealth = (sa < 65 ? R.kehpSpouse : R.mehpFull + R.partB) * 12;
        if (sp.trs && sp.hPre !== undefined && sa >= (sp.stopAge || sp.age)) spHealth += (sa < 65 ? sp.hPre : sp.hPost) * 12;
      } else if (a >= 60) ssMine = Math.max(ssMine, spSs * Math.min(1, .715 + (a - 60) / 7 * .285)); /* a widow or widower keeps the larger check */
    }
    /* If the teacher dies first on the basic option, the TRS pension ends. The spouse keeps the larger Social Security check. */
    if (gone) { ssMine = 0; var own = sa >= spClaim ? spSs : 0; ssSp = sa >= 60 ? Math.max(own, s.ssMonthly * 12) : own; }
    /* A spouse who teaches pays into TRS and Medicare, not Social Security. */
    var ss = ssMine + ssSp, fica = spWage * (sp && sp.trs ? .143 : .0765), ahead = a - h.age, oi = h.otherIncomeEnd > 0 && a >= h.otherIncomeEnd ? 0 : otherIncome;
    var hT = widowed || gone ? Object.assign({}, h, { status: 'single' }) : h, apart = sp && !widowed && !gone && h.status === 'mfs';
    var taxOf = function (draws) {
      if (apart) return retireTax(h, pension + draws, ssMine, oi, ex98, ahead, 0) + retireTax(h, spPen, ssSp, spWage - spSave, 0, ahead, 0) + fica;
      return retireTax(hT, pension + draws, ss, oi + spWage - spSave, ex98, ahead, spPen) + fica;
    };
    var healthCost = (gone ? 0 : (a < 65 ? hp.pre : hp.post) * 12) + spHealth + (h.oop || 0) * 12;
    /* One-time money this year: a cost is paid like any other bill, and a windfall lands in savings. */
    var once = 0;
    ots.forEach(function (o) { if (o.age !== a) return; if (o.out) once += o.amt; else other += o.amt; });
    if (h.care && a >= h.care.age && a < h.care.age + h.care.years) once += h.care.monthly * 12;
    var need = billsAt(h, a) * 12 + healthCost + once;
    var preDraw = 0, tax = 0, otherDraw = 0, rothDraw = 0, d457 = 0;
    /* Taking money out raises the tax, which means taking a little more out. Repeat until it settles. */
    for (var it = 0, was = -1; it < 60 && Math.abs(preDraw + d457 + otherDraw - was) > .5; it++) {
      was = preDraw + d457 + otherDraw;
      tax = taxOf(preDraw + d457);
      var gap = need + tax - pension - ss - oi - spouse;
      otherDraw = Math.min(other, Math.max(0, gap));
      var left = Math.max(0, gap - otherDraw);
      /* A 457(b) has no early-withdrawal penalty once you've left the job, so it's used before other pre-tax money. */
      d457 = Math.min(f457, left);
      preDraw = Math.min(pre, left - d457);
    }
    tax = taxOf(preDraw + d457);
    var remain = Math.max(0, need + tax - pension - ss - oi - spouse - otherDraw - d457 - preDraw);
    rothDraw = Math.min(roth, remain);
    remain -= rothDraw;
    if (preDraw > 0 && a < 60) earlyPenaltyRisk = true;
    if (remain > 12 && firstShort === null) { firstShort = a; shortMonthly = remain / 12; }
    other = (other - otherDraw) * (1 + dr); f457 = (f457 - d457) * (1 + dr); pre = (pre - preDraw + spSave) * (1 + dr); roth = (roth - rothDraw) * (1 + dr);
    rows.push({ age: a, once: once, pension: pension, ss: ss, otherIncome: oi, spouse: spouse, health: healthCost, bills: billsAt(h, a) * 12, tax: tax, draw: otherDraw + d457 + preDraw + rothDraw, balance: other + f457 + pre + roth, short: remain });
  }
  return { sim: s, rows: rows, firstShort: firstShort, shortMonthly: shortMonthly, lasts: firstShort === null, earlyPenaltyRisk: earlyPenaltyRisk, start: rows[0], hp: hp };
}
function firstSafeAge(h) {
  var start = firstAnyRetireAge(h);
  if (start === null) start = h.age;
  for (var a = Math.max(start, h.age); a <= 75; a++) if (survive(h, a).lasts) return a;
  return null;
}
function extraToLast(h, age) {
  if (survive(h, age).lasts) return 0;
  if (age <= h.age) return null;
  var lo = 0, hi = 10000;
  var test = function (x) { return survive(Object.assign({}, h, { saveMonthly: h.saveMonthly + x }), age).lasts; };
  if (!test(hi)) return null;
  for (var i = 0; i < 24; i++) { var mid = (lo + hi) / 2; if (test(mid)) hi = mid; else lo = mid; }
  return hi;
}

/* Is buying out-of-state service worth it? */
function purchaseView(h, age) {
  var withIt = retireAt(h, age), without = retireAt(Object.assign({}, h, { boughtYears: 0, boughtCost: 0 }), age);
  var gain = withIt.pensionMonthlyAtStart - without.pensionMonthlyAtStart;
  return { gain: gain, payback: (h.boughtCost > 0 && gain > 0) ? h.boughtCost / gain / 12 : null, used: withIt.boughtNow, earlier: without.startAge !== null && withIt.startAge !== null && withIt.startAge < without.startAge ? [without.startAge, withIt.startAge] : null };
}

/* ---------- Report card ---------- */
function stepGrade(v, steps) { for (var i = 0; i < steps.length; i++) if (v >= steps[i][0]) return steps[i][1]; return 'F'; }
function gradePlan(h, sim) {
  if (!sim.vested) return { overall: 'I', subjects: [] };
  var sv = survive(h, sim.stop, sim), money, moneyNote;
  if (sv.lasts) {
    var room = [30, 20, 10].filter(function (p) { return survive(scaleBills(h, 1 + p / 100), sim.stop, sim).lasts; })[0];
    money = room === 30 ? 'A+' : room === 20 ? 'A' : room === 10 ? 'A-' : 'B+';
    moneyNote = room ? 'Lasts past age ' + LAST_AGE + ', even if your bills ran ' + room + '% higher.' : 'Lasts past age ' + LAST_AGE + ', with little room to spare.';
  } else {
    var gap = 0, cost = 0;
    sv.rows.forEach(function (r) { gap += r.short; cost += r.bills + r.health + r.tax + (r.once || 0); });
    var covered = cost > 0 ? 1 - gap / cost : 1;
    money = stepGrade(covered, [[.98, 'B'], [.95, 'B-'], [.9, 'C+'], [.85, 'C'], [.8, 'C-'], [.7, 'D']]);
    var atAge = function () { return plain(sv.shortMonthly); };
    moneyNote = (sv.firstShort <= sim.stop ? 'Falls about ' + atAge(sim.stop) + ' a month short from the start.' : 'Could run short at age ' + sv.firstShort + ', by about ' + atAge(sv.firstShort) + ' a month at first.') + ' Covers about ' + Math.min(99, Math.round(covered * 100)) + '% of your costs to age ' + LAST_AGE + '.';
  }
  var cross = coverUntil(sv);
  if (sv.lasts && cross !== null) moneyNote += cross <= sim.stop ? ' Savings fill a gap from the start.' : ' Your income covers the bills until about ' + cross + ', then savings fill the gap.';
  var pct = sim.replacePct;
  var pension = stepGrade(pct, [[60, 'A'], [55, 'A-'], [50, 'B+'], [45, 'B'], [40, 'B-'], [35, 'C+'], [30, 'C'], [25, 'C-'], [20, 'D']]);
  var pensionNote = 'Replaces about ' + Math.round(pct) + '% of your final average salary' + (sim.earlyCut ? ', after ' + aPct(sim.earlyCut) + '% early cut for life' : sim.startAge > sim.stop ? '' : ', with no early cut') + '.' + (sim.startAge > sim.stop ? ' It starts at ' + sim.startAge + ', not ' + sim.stop + '.' : '');
  var health, healthNote;
  if (!sim.healthEligible) { health = 'F'; healthNote = 'You wouldn\'t qualify for TRS retiree coverage. You\'d need ' + (h.type === '3' || h.type === '4' ? 15 : 5) + ' years.'; }
  else {
    health = stepGrade(sim.share, [[1, 'A'], [.9, 'A-'], [.65, 'B'], [.45, 'C'], [.25, 'D']]);
    healthNote = (sim.stop < 65 ? 'TRS covers you before 65. ' : '') + 'TRS would pay ' + Math.round(sim.share * 100) + '% of its share toward your coverage.';
  }
  return { overall: money, subjects: [
    ['Money that lasts', money, moneyNote],
    ['TRS pension', pension, pensionNote],
    ['Health coverage', health, healthNote]
  ] };
}

/* ---------- State and examples ---------- */
function base(o) {
  return Object.assign({ age: 34, status: 'single', type: '3', years: 9, salary: 56000, county: 'Fayette', localRate: 2.25, univ: false, raise: 2, sickYears: 0, sickDays: 0, balance: 0, teachHealth: 60,
    sp: { on: false, age: 0, pay: 0, stopAge: 0, pension: 0, pensionAge: 65, pia: 0, claimAge: 67, savings: 0, saveMonthly: 0, onTrs: false },
    later: false, moved: false, boughtYears: 0, boughtCost: 0, otherPension: 0, otherPensionAge: 65, rothBal: 0, rothMonthly: 0, otherBal: 0, otherMonthly: 0, otherIncome: 0, sidePay: 8000, stopAge: 60, claimAge: 67, ssYears: 4, ssAvg: 16000, savings: 12000, saveMonthly: 100, goal: 2700, inflation: 2.5, returnRate: 5, marketHealth: 1000, medicareOther: 300, checks: {} }, o);
}
var EXAMPLES = {
  year26: base({ age: 50, years: 26, type: '1', startYear: 2000, salary: 70000, county: 'Madison', localRate: 1, stopAge: 53, ssYears: 0, ssAvg: 0, savings: 90000, saveMonthly: 300, goal: 3000 }),
  blank: base({ age: 35, years: 0, salary: 0, type: '4', county: 'Fayette', stopAge: 60, ssYears: 0, ssAvg: 0, savings: 0, saveMonthly: 0, goal: 0, teachHealth: 0, raise: 2 })
};
var state = JSON.parse(JSON.stringify(EXAMPLES.year26));
var dirty = false, isExample = false, screen = 'welcome';
function $(id) { return document.getElementById(id); }
function money(n) { var v = Math.round(Math.abs(n)); return (n <= -.5 ? '-$' : '$') + v.toLocaleString('en-US'); }
function plain(n) { return '$' + Math.round(Math.abs(n)).toLocaleString('en-US'); }
function esc(s) { var d = document.createElement('div'); d.textContent = String(s); return d.innerHTML.replace(/"/g, '&quot;'); }
function ready() { return state.salary > 0 && state.years > 0; }
function yearsText(n) { return n === 1 ? '1 year' : n + ' years'; }
function stayPath() { return { stay: true, more: 0, salary: 0, raise: 0, localRate: state.localRate, match: 0, save: 0, health: 0, covered: false, name: 'Stay in the classroom' }; }

/* ---------- Forms ---------- */
function fillForm() { $('sidePay').value = state.sidePay; }
function readNum(el) {
  var v = parseFloat(el.value);
  if (!isFinite(v) || v < 0) return 0;
  var max = el.max === '' ? Infinity : parseFloat(el.max);
  return Math.min(v, max);
}
function onChange(e) {
  var el = e.target;
  if (el.id === 'openFile' || !el.closest('#resultsView') || (el.dataset && el.dataset.risk)) return;
  /* Trying ages on a made-up teacher keeps it an example, so it is never saved as your plan. */
  if (el.id !== 'tryRetire') isExample = false;
  if (el.id === 'tryRetire') {
    state.stopAge = parseInt(el.value, 10);
  } else if (el.dataset && el.dataset.task) {
    state.checks[el.dataset.task] = el.checked; markDirty(); autoSave(); return;
  } else if (el.id === 'sidePay') {
    state.sidePay = readNum(el);
  } else { return; }
  markDirty();
  renderAll();
}
function markDirty() { dirty = true; }
function showMessage(text, kind) { $('message').innerHTML = '<div class="' + kind + '" role="' + (kind === 'err' ? 'alert' : 'status') + '">' + esc(text) + '</div>'; }

/* Age rules used by simulate need a safe, sane copy of the numbers. */
function safe() {
  var h = JSON.parse(JSON.stringify(state));
  h.age = Math.max(18, Math.min(80, h.age || 18));
  h.stopAge = Math.max(h.age, Math.min(85, h.stopAge || h.age));
  h.claimAge = Math.max(62, Math.min(70, h.claimAge || 67));
  if (h.sp && h.sp.on && h.status !== 'joint' && h.status !== 'mfs') h.status = 'joint';
  /* No Social Security amount for the spouse? Estimate it from their pay, as their SSA statement would. */
  if (h.sp && h.sp.on && !h.sp.trs && !(h.sp.pia > 0) && h.sp.pay > 0) {
    var spYrs = Math.min(45, (h.sp.ssYears > 0 ? h.sp.ssYears : Math.max(0, Math.min(40, h.sp.age - 22))) + Math.max(0, (h.sp.stopAge || h.sp.age) - h.sp.age));
    if (spYrs >= 10) { var e = []; for (var q = 0; q < Math.round(spYrs); q++) e.push(h.sp.pay * 12); h.sp.pia = piaFromEarnings(e); h.sp.piaEst = true; }
  }
  /* A spouse in TRS: their pension comes from the same formulas as yours, run on their numbers. */
  if (h.sp && h.sp.on && h.sp.trs && h.sp.start >= 1960 && h.sp.years > 0 && h.sp.salary > 0) {
    var sq = h.sp, sStop = sq.stopAge > sq.age ? sq.stopAge : sq.age;
    var hs = Object.assign({}, h, { age: sq.age, years: sq.years, startYear: sq.start, type: typeFromYear(sq.start), salary: sq.salary, raise: sq.raise >= 0 ? sq.raise : 2, univ: false, fasPast: 0, pre83: -1, sickDays: 0, sickYears: 0, balance: 0,
      savings: 0, saveMonthly: 0, rothBal: 0, rothMonthly: 0, otherBal: 0, otherMonthly: 0, b457Bal: 0, b457Monthly: 0, otherPension: 0, boughtYears: 0, boughtCost: 0, ssYears: 0, ssAvg: 0, wantAge: 0, sp: { on: false } });
    var st = retireAt(hs, Math.min(85, Math.max(sq.age, sStop)));
    if (st.vested && st.pensionRealAtStart > 0) { sq.trsPension = st.pensionRealAtStart / 12; sq.trsAge = st.startAge; sq.trsCola = st.colaReal || 0; }
    /* Their own retiree health plan, priced by the same rules as yours. Counted once they stop working. */
    var hpS = healthPlan(hs, st); sq.hPre = hpS.pre; sq.hPost = hpS.post;
  }
  if (h.sickDays > 0 && h.sickHow !== 'cash') h.sickYears = Math.min(h.sickDays, h.type === '3' || h.type === '4' ? 300 : h.sickDays) / 185;
  return h;
}

/* ---------- Results ---------- */
function renderAll() {
  var h = safe(), stay = simulate(h, stayPath());
  $('resultsView').dataset.mode = isExample ? 'example' : 'mine';
  window.__r = { h: h, stay: stay };
  renderMode();
  orderSections(h);
  renderRetire(h, stay);
  renderRoad(h);
  renderSs(h, stay);
  renderHealth(h);
  renderSide(h, stay);
  renderPlan(h, stay);
  autoSave();
  renderYears(h);
}

function renderMode() {
  var box = $('modeNote');
  document.body.dataset.ex = isExample ? '1' : '0';
  if (isExample) box.innerHTML = '<div class="mn-row"><span><strong>This is a made-up teacher.</strong></span><span class="mn-act">' + (exampleFrom ? '<button type="button" id="backMine">Back to my plan</button>' : '<button type="button" id="useMine">Use my numbers</button>') + ' <button type="button" class="inline-link" id="exHome">Back to home</button></span></div>';
  else box.innerHTML = '';
}

/* One line that shows how the TRS pension was figured, so a teacher can check it. */
function pensionMath(h, s, shownMonthly) {
  if (!s.vested || s.startAge !== s.stop || !(s.fasNominal > 0)) return '';
  var monthly = s.pensionNominal / 12;
  var tail = Math.abs(monthly - shownMonthly) > 2 ? ' a month in future-year dollars at age ' + s.stop + '. With prices rising ' + h.inflation + '% a year, that buys what <strong>' + plain(shownMonthly) + '</strong> buys today.' : ' a month.';
  var yrs = s.service + (s.boughtNow || 0) + (h.sickYears || 0), p83 = pre83Years(h);
  var pct = percentOfSalary(h.type, h.univ, yrs, s.startAge, p83), rate = multiplier(h.type, h.univ, yrs, s.startAge);
  var n = (h.type !== '4' && s.leaveAge >= 55 && s.service >= 27) ? 3 : 5;
  var r1 = function (x) { return (Math.round(x * 100) / 100).toString(); };
  var yTxt = (Math.round(yrs * 10) / 10) + ' years';
  var first = pct >= 100 ? yTxt + ' reach the 100% limit' : Math.abs(yrs * rate - pct) < .01 ? yTxt + ' &times; ' + r1(rate) + '% = ' + r1(pct) + '%' : yTxt + ' earn ' + r1(pct) + '%';
  var cut = (s.earlyCut ? ', minus ' + aPct(s.earlyCut) + '% early cut' : '') + (s.survF < 1 ? ', minus ' + r1((1 - s.survF) * 100) + '% for the survivor option' : '');
  return '<p class="lg-math"><strong>How we got ' + plain(shownMonthly) + ':</strong> ' + first + ' of your average salary' + cut + '. Your highest ' + n + ' salaries average about ' + plain(s.fasNominal) + ' in future-year dollars' + (h.fasPast > 0 && s.stop - h.age < n ? ', using the salary average you entered. ' : s.stop - h.age < n ? ', counting back from this year\'s salary at ' + h.raise + '% raises. ' : ' by then, if your pay rises ' + h.raise + '% a year. ') + plain(s.fasNominal) + ' &times; ' + r1(pct) + '%' + (s.earlyCut ? ' &times; ' + (100 - s.earlyCut) + '%' : '') + (s.survF < 1 ? ' &times; ' + r1(s.survF * 100) + '%' : '') + ' &divide; 12 = ' + plain(monthly) + tail + '</p>';
}
var zoneOpen = false, howOpen = false, moreOpen = false;
document.addEventListener('toggle', function (e) { if (e.target.classList && e.target.classList.contains('lg-how')) howOpen = e.target.open; if (e.target.classList && e.target.classList.contains('bd-more')) moreOpen = e.target.open; }, true);
function cutRule(t) {
  if (t === '4') return 'You can start at 57 with 10 years. The cut is 6% for each year you\'re under 60 or under 30 years of service, whichever is fewer, up to 18%.';
  if (t === '3') return 'You can start at 55 with 10 years. The cut is 6% for each year you\'re under 60 or under 27 years of service, whichever is fewer.';
  return 'You can start at 55 with 5 years. The cut is 5% for each year you\'re under 60 or under 27 years of service, whichever is fewer.';
}
document.addEventListener('click', function (e) {
  var b = e.target.closest && e.target.closest('[data-zonehelp]');
  if (!b) return;
  zoneOpen = !zoneOpen; $('zoneHelp').hidden = !zoneOpen;
  document.querySelectorAll('[data-zonehelp]').forEach(function (x) { x.setAttribute('aria-expanded', zoneOpen); });
});

/* The service milestones for each TRS account type, in plain words. */
function serviceMilestones(t) {
  var rate = { '2': [[10, 'Your rate rises from 2% to 2.5% a year, on all your years.']], '3': [[11, 'Your rate rises from 1.7% to 2.0% a year, on all your years.'], [21, 'Your rate rises to 2.3% a year, on all your years.'], [27, 'Your rate rises to 2.5% a year, on all your years.']] }[t] || [];
  var list;
  if (t === '1') list = [[5, 'You\'re vested: a pension for life is yours, even if you leave. TRS pays 25% of its health share.'], [10, 'TRS pays 50% of its health share.'], [15, 'TRS pays 75% of its health share.'], [20, 'TRS pays its full health share.'], [27, 'You can retire at any age with no early cut.']];
  else if (t === '4') list = [[5, 'You\'re vested: a pension for life is yours, even if you leave. No early cut from 65.'], [10, 'You can retire at 57 with an early cut, or at 60 with no cut.'], [15, 'You first qualify for TRS help with health insurance (45% of its share).'], [20, 'Your rate gets a 0.25% career bonus, on all your years. Health share rises to 65%.'], [27, 'TRS pays its full health share.'], [30, 'Your career bonus rises to 0.5%, and you can retire at 57 with no cut.']];
  else list = [[5, 'You\'re vested: a pension for life is yours, even if you leave. No early cut from 60.' + (t === '2' ? ' TRS pays 10% of its health share.' : '')], [10, t === '3' ? 'You can retire early, from 55, with a cut.' : 'TRS pays 25% of its health share.'], [15, t === '3' ? 'You first qualify for TRS help with health insurance (45% of its share).' : 'TRS pays 45% of its health share.'], [20, 'TRS pays 65% of its health share.'], [27, 'You can retire at any age with no early cut, and TRS pays its full health share.']];
  if (t !== '1') list.push([25, 'TRS pays 90% of its health share.'], [26, 'TRS pays 95% of its health share.']);
  if (t !== '4') list.push([31, 'Each year past 30 earns 3% instead of your usual rate.']);
  list = list.concat(rate).sort(function (a, b) { return a[0] - b[0]; });
  var merged = [];
  list.forEach(function (m) { var last = merged[merged.length - 1]; if (last && last[0] === m[0]) last[1] += ' ' + m[1]; else merged.push([m[0], m[1]]); });
  return merged;
}
function renderMilestones(h) {
  var ms = serviceMilestones(h.type), next = null;
  ms.forEach(function (m) { if (next === null && m[0] > h.years) next = m[0]; });
  var names = { '1': 'before July 2002', '2': 'from July 2002 to June 2008', '3': 'from July 2008 to 2021', '4': 'in 2022 or later' };
  return '<div class="miles"><h3>Why some years matter more</h3><p>For teachers who joined TRS ' + names[h.type] + ', like you:</p>' + milesStrip(h, ms) + '<ol>' + ms.map(function (m) {
    var cls = m[0] <= h.years ? 'done' : m[0] === next ? 'next' : '';
    return '<li class="' + cls + '"><b>Year ' + m[0] + '</b><span>' + m[1] + (cls === 'done' ? ' <em>Reached.</em>' : cls === 'next' ? ' <em>Your next one.</em>' : '') + '</span></li>';
  }).join('') + '</ol></div>';
}
/* Break-even: when waiting for no early cut catches up with retiring now. Pension only, in today's dollars. */
function breakEven(h, early, full) {
  if (full === null || full <= early) return null;
  var a = retireAt(h, early), b = retireAt(h, full);
  if (!a.vested || !b.vested) return null;
  var p = function (s, x) { return x >= s.startAge ? s.pensionRealAtStart * Math.pow(1 + s.colaReal, x - s.startAge) : 0; };
  var ca = 0, cb = 0;
  for (var x = early; x <= 100; x++) { ca += p(a, x); cb += p(b, x); if (x >= full && cb >= ca) return { age: x, more: (p(b, full) - p(a, full)) / 12 }; }
  return { age: null, more: (p(b, full) - p(a, full)) / 12 };
}
/* The first age when bills, health and taxes cost more than comes in. The pension's 1.5% raise trails inflation, so this often arrives years after retiring. */
function coverUntil(sv) {
  for (var i = 0; i < sv.rows.length; i++) { var r = sv.rows[i]; if (r.age < LAST_AGE - 1 && r.bills + r.health + r.tax > r.pension + r.ss + r.otherIncome + (r.spouse || 0) + 12) return r.age; }
  return null;
}
function selectedRetire(h) { return retireAt(h, h.stopAge); }
/* When one more year of teaching crosses a TRS milestone, say what it is worth. */
function oneMoreYear(h, s) {
  if (s.stop >= 75) return '';
  var n = retireAt(h, s.stop + 1), why = [];
  if (!n.vested) return '';
  var box = function (t) { return ' <span class="be"><strong>One more year counts here.</strong> ' + t + '</span>'; };
  var lead = 'Teaching until ' + n.stop + ' instead of ' + s.stop;
  if (!s.vested) return box(lead + ' gets you to 5 years of service, so you\'d be vested and keep a pension for life: about <strong>' + plain(n.pensionMonthlyAtStart) + ' a month</strong> from age ' + n.startAge + ', in today\'s dollars.');
  var yrs = function (x) { return x.service + (x.boughtNow || 0) + (h.sickYears || 0); }, r2 = function (x) { return (Math.round(x * 100) / 100).toString(); }, pc = function (x) { return Math.round(x * 100); };
  var m0 = multiplier(h.type, h.univ, yrs(s), s.startAge), m1 = multiplier(h.type, h.univ, yrs(n), n.startAge);
  var nowS = s.startAge <= s.stop, nowN = n.startAge <= n.stop;
  if (!nowS && nowN) why.push('your pension could start right away instead of waiting until age ' + s.startAge);
  if (m1 > m0 + .045) why.push('your rate rises from ' + r2(m0) + '% to ' + r2(m1) + '% on all your years');
  if (nowS && nowN && s.earlyCut && n.earlyCut < s.earlyCut) why.push(n.earlyCut ? 'your early cut drops from ' + s.earlyCut + '% to ' + n.earlyCut + '%' : 'your early cut ends');
  var health = '';
  if (n.healthEligible && (!s.healthEligible || n.share > s.share + .001)) {
    var h0 = healthPlan(h, s), h1 = healthPlan(h, n), less = n.stop < 65 ? h0.pre - h1.pre : h0.post - h1.post;
    health = 'TRS would pay ' + pc(n.share) + '% of its share of your health coverage' + (s.healthEligible ? ', up from ' + pc(s.share) + '%' : ', which you wouldn\'t qualify for a year earlier') + (less >= 1 ? '. That lowers your cost by about <strong>' + plain(less) + ' a month</strong>' + (n.stop < 65 ? ' before 65' : '') : '') + '.';
  }
  if (!why.length) return health ? box(lead + ' reaches a health milestone. ' + health) : '';
  var gain = n.pensionMonthlyAtStart - s.pensionMonthlyAtStart;
  var amt = nowS && nowN && gain >= 1 ? ' adds about <strong>' + plain(gain) + ' a month</strong> to your pension for life, in today\'s dollars'
    : !nowS && nowN ? ' means a pension of about <strong>' + plain(n.pensionMonthlyAtStart) + ' a month</strong>, in today\'s dollars' : ' matters';
  return box(lead + amt + ', because ' + (why.length > 1 ? why.slice(0, -1).join(', ') + ' and ' + why[why.length - 1] : why[0]) + '.' + (health ? ' ' + health : ''));
}
function renderRetire(h, stay) {
  if (!ready()) {
    $('boardText').innerHTML = '<h1 class="answer">When could you retire?</h1>'; $('answerSub').innerHTML = 'Choose Start my plan to enter your numbers.'; $('slideWrap').hidden = true;
    ['ageChart', 'enoughOut', 'retireStressOut', 'worthOut'].forEach(function (id) { $(id).innerHTML = ''; });
    return;
  }
  var s = selectedRetire(h);
  var full = firstFullRetireAge(h);
  var head, sv = null;
  var oth = h.otherIncome || 0;
  var ledger = '', verdictHtml = '';
  if (!s.vested) {
    head = 'At age ' + s.stop + ', you\'d have under 5 years of service, so no TRS pension yet.';
  } else {
    head = 'Retire at ' + s.stop + '?';
    var sv = survive(h, s.stop, s), r0 = sv.rows[0];
    var yrsOut = Math.max(0, s.stop - h.age), M = function (v) { return v / 12; };
    var inNow = M(r0.pension + r0.ss + r0.otherIncome + (r0.spouse || 0));
    var outNow = M(r0.bills + r0.health + r0.tax), gap = inNow - outNow;
    var inParts = [];
    if (r0.pension > 0) inParts.push('TRS pension ' + plain(M(r0.pension)));
    else if (s.startAge > s.stop) inParts.push('TRS pension starts at ' + s.startAge);
    var suppLine = s.supplement > 500 ? '<p class="lg-later"><strong>Your TRS 4 supplemental account:</strong> about ' + plain(Math.round(s.supplement / 1000) * 1000) + ' when you retire, counted with your savings.</p>' : '';
    if (r0.ss > 0) inParts.push('Social Security ' + plain(M(r0.ss)));
    if (r0.otherIncome > 0) inParts.push('other income ' + plain(M(r0.otherIncome)));
    if (r0.spouse > 0) inParts.push('your spouse\'s pay and pension ' + plain(M(r0.spouse)));
    var outParts = ['bills ' + plain(M(r0.bills)) + ' in today\'s dollars', 'health insurance' + (h.sp && h.sp.on && (h.sp.onTrs || h.sp.trs) && r0.health > (hpBoth = healthPlan(h, s)).pre * 12 + 1 ? ' for both of you ' : ' ') + plain(M(r0.health))], hpBoth;
    if (r0.tax >= 12) outParts.push((h.sp && h.sp.on ? 'taxes for both of you ' : 'taxes ') + plain(M(r0.tax)));
    var mathLine = pensionMath(h, s, M(r0.pension));
    var safeAge = firstSafeAge(h);
    var almost = !sv.lasts && ((sv.firstShort !== null && sv.firstShort >= 85) || (safeAge !== null && safeAge - s.stop === 1));
    head = sv.lasts ? 'Yes, you can retire at ' + s.stop + '.' : almost ? 'Almost: retiring at ' + s.stop + ' is close.' : 'Not yet at ' + s.stop + '.';
    var later = s.pensionMonthlyAtStart + s.ssMonthly + (s.otherPension || 0) + oth;
    var laterAge = Math.max(s.startAge || 0, s.ssMonthly > 0 ? h.claimAge : 0, s.otherPension > 0 ? s.otherPensionAge : 0);
    var dollarsNote = yrsOut >= 1 ? '<p class="lg-foot">In today\'s dollars.</p>' : '';
    var hpl = healthPlan(h, s);
    /* What changes later, and what's left at the end: the two things a first-year snapshot can't show. */
    var otLine = oneTimes(h).map(function (o) { return '<p class="lg-later">At ' + o.age + ', a one-time ' + plain(o.amt) + (o.out ? ' goes out. It comes from savings.' : ' comes in. It goes into savings.') + '</p>'; }).join('');
    var changeLine = '';
    if (h.goalLater > 0 && h.goalLaterAge > s.stop) changeLine += '<p class="lg-later">From ' + h.goalLaterAge + ', your bills change to ' + plain(h.goalLater) + ' a month.</p>';
    if (h.otherIncome > 0 && h.otherIncomeEnd > s.stop) changeLine += '<p class="lg-later">Your other income of ' + plain(h.otherIncome) + ' a month stops at ' + h.otherIncomeEnd + '.</p>';
    /* Bills check colours: green when income alone pays the bills (or only falls short after 85), yellow whenever savings have to fill a gap, red when the money runs short. */
    /* The quick read: one verdict and the monthly bottom line. Everything else folds away under "See the details". */
    var good = gap >= 0, yrs0 = Math.max(0, s.stop - h.age);
    var days = Math.round(yrs0 * 185 / 10) * 10;
    var whenLine = 'Around ' + retireDate(yrs0).getFullYear() + (yrs0 >= 1 ? ' &middot; about ' + days.toLocaleString('en-US') + ' school days to go' : ' &middot; at the end of this school year') + (sv.lasts && !h.wantAge && safeAge === s.stop ? ' &middot; the earliest age that works' : '');
    var cross = good ? coverUntil(sv) : null, lateCross = cross && sv.lasts && cross >= 85;
    /* One line instead of three boxes: the number that matters, then where it comes from. */
    var later = good && cross && !lateCross;
    var gcls = good ? 'ok' : (sv.lasts || (sv.firstShort > s.stop + 1 && r0.balance > 1)) ? 'mid' : 'bad';
    var big = good ? '+' + plain(gap) + ' a month left over' : gcls === 'mid' ? plain(-gap) + ' a month from savings' : plain(-gap) + ' a month short';
    var tiles = '<p class="bd-sum"><strong class="' + gcls + '">' + big + '</strong></p>' + (later ? '<p class="bd-warn">From about ' + cross + ', prices outgrow your pension and savings fill the gap.</p>' : '');
    var chk = [];
    var mark = function (c, t) { chk.push('<li class="' + c + '"><span aria-hidden="true">' + (c === 'ok' ? '&#10003;' : c === 'mid' ? '!' : '&#10007;') + '</span>' + t + '</li>'); };
    if (good && lateCross) mark('ok', 'Income covers your bills to about ' + cross + ', then savings cover the rest');
    else if (good && cross) mark('mid', 'Income covers your bills until about ' + cross + (sv.lasts ? ', then savings fill the gap' : ''));
    else if (good) mark(sv.lasts ? 'ok' : 'mid', sv.lasts ? 'Your income covers your bills' : 'Your income covers your bills at first');
    else if (sv.lasts) mark('mid', 'Savings cover the ' + plain(-gap) + ' a month gap');
    else if (sv.firstShort > s.stop + 1 && r0.balance > 1) mark('mid', 'Savings cover the gap until about ' + sv.firstShort);
    else mark('bad', 'Short ' + plain(-gap) + ' a month');
    if (!sv.lasts) mark('bad', 'Your money runs short at ' + sv.firstShort);
    if (s.earlyCut) mark('mid', 'Early cut: ' + s.earlyCut + '% less pension for life');
    else if (s.startAge > s.stop) mark('mid', 'Pension starts at ' + s.startAge + ', not ' + s.stop);
    else mark('ok', 'Full pension, no early cut');
    if (hpl.eligible) mark('ok', 'TRS health coverage' + (s.stop < 65 ? ' before 65' : ''));
    else mark('bad', 'No TRS health coverage: ' + plain(hpl.pre) + ' a month on your own');
    var detail = '<p class="lg-later"><strong>Coming in:</strong> ' + inParts.join(', ') + '.</p>' + (mathLine ? '<details class="lg-how in-pdf"' + (howOpen ? ' open' : '') + '><summary>How we got ' + plain(M(r0.pension)) + '</summary>' + mathLine + '</details>' : '') +
      '<p class="lg-later"><strong>Going out:</strong> ' + outParts.join(', ') + '.</p>' + suppLine + (laterAge > s.stop && later - inNow >= 1 ? '<p class="lg-later">Your income rises to about ' + plain(later) + ' a month at ' + laterAge + ', when ' + (s.ssMonthly > 0 && h.claimAge === laterAge ? 'Social Security' : s.startAge === laterAge ? 'your TRS pension' : 'your other pension') + ' starts.</p>' : '') + changeLine + otLine + dollarsNote;
    ledger = '<p class="bd-when">' + whenLine + '</p>' + tiles +
      '<details class="bd-more in-pdf"' + (moreOpen ? ' open' : '') + '><summary>See the details</summary>' + detail + '</details>';
    verdictHtml = '';
  }
  var sub = '', worth = '';
  if (s.vested && !sv.lasts) {
    var more = extraToLast(h, s.stop), safe = firstSafeAge(h);
    /* A catch-up amount bigger than a quarter of take-home-scale pay isn't a real option, so it isn't offered. */
    if (more && more > h.salary / 12 * .25) more = null;
    var saveTxt = more ? 'saving about <strong>' + plain(more) + ' more a month</strong> until ' + s.stop : '';
    if (safe !== null && safe > s.stop) sub = 'Retiring at <strong>' + safe + '</strong> would cover your costs through age ' + LAST_AGE + '.' + (more ? ' So would ' + saveTxt + '.' : '');
    else if (more) sub = saveTxt.replace(/^./, 'S') + ' could cover your costs through age ' + LAST_AGE + '.';
  }
  if (s.earlyCut) sub += ' This includes an early-retirement cut of about ' + s.earlyCut + '%.';
  if (s.vested && sv.earlyPenaltyRisk) worth += '<span class="be"><strong>Taking savings out before 59&frac12;.</strong> Money from a 401(k), 403(b) or IRA can carry a 10% penalty. A 457(b) doesn\'t, and neither does a 403(b) or 401(k) from a job you leave in or after the year you turn 55. Ask your plan which applies.</span>';
  if (s.earlyCut) {
    var be = breakEven(h, s.stop, full);
    if (be && be.more > 0) worth += '<span class="be"><strong>Retire now or wait?</strong> Waiting until ' + full + ', when the cut ends, pays about ' + plain(be.more) + ' more a month in today\'s dollars' + (be.age ? '. Counting the pension alone, waiting comes out ahead if you live past about <strong>' + be.age + '</strong>.' : ', but retiring now stays ahead through age 100.') + '</span>';
  }
  if (s.vested && h.sickDays > 0 && h.sickHow === 'unsure' && h.sickYears > 0) {
    var noSick = retireAt(Object.assign({}, h, { sickYears: 0 }), h.stopAge), sickGain = s.pensionMonthlyAtStart - noSick.pensionMonthlyAtStart;
    if (sickGain >= 1) worth += '<span class="be"><strong>Ask your district about your sick days.</strong> This plan counts your ' + h.sickDays + ' unused days as about ' + (Math.round(h.sickYears * 10) / 10) + ' years of service. If your district pays cash for them instead, your pension would be about <strong>' + plain(sickGain) + ' a month less</strong>.</span>';
  }
  worth += oneMoreYear(h, s);

  $('worthOut').innerHTML = worth; $('worthWrap').hidden = !worth; 
  $('boardText').innerHTML = '<h1 class="answer ' + (!s.vested ? 'bad' : sv.lasts ? 'ok' : almost ? 'mid' : 'bad') + '">' + head + '</h1>' + (sub ? ledger.replace('<details class="bd-more', '<p class="bd-sub">' + sub.trim() + '</p><details class="bd-more') : ledger) + verdictHtml;
  /* The way to make it work is written on the board, not under it. */
  $('answerSub').innerHTML = ''; $('answerSub').hidden = true;
  renderReportCard(h, s);

  /* Age table */
  var table = retireTable(h), range = $('tryRetire');
  $('slideWrap').hidden = !table.length;
  if (table.length) {
    range.min = Math.max(h.age, Math.min(table[0].age - 2, h.stopAge, h.wantAge || 99)); range.max = Math.max(table[table.length - 1].age, 75, h.stopAge); range.value = h.stopAge;
    var cutTxt = s.earlyCut ? ', ' + s.earlyCut + '% early cut' : s.vested && s.startAge > s.stop ? ', pension starts at ' + s.startAge : '';
    range.setAttribute('aria-valuetext', 'Retire at age ' + h.stopAge + cutTxt);
    var lo = +range.min, hi = +range.max, span = Math.max(1, hi - lo), waitSpan = Math.max(0, Math.min(span, table[0].age - lo)), cutSpan = Math.max(0, (full === null ? span : Math.max(0, Math.min(span, full - lo))) - waitSpan);
    var zb = function (cls, flex, txt) { var tiny = flex / span < .14 && cls !== 'z-full'; return '<span class="' + cls + (tiny ? ' z-tiny' : '') + '" style="flex:' + flex + '"><button type="button" class="zone-btn" data-zonehelp aria-expanded="' + zoneOpen + '" aria-controls="zoneHelp"' + (tiny ? ' aria-label="' + txt + '" title="' + txt + '"' : '') + '>' + (tiny ? '' : txt) + '</button></span>'; };
    $('slideEnds').innerHTML = '<div class="slide-zones">' + (waitSpan > 0 ? zb('z-wait', waitSpan, 'Wait') : '') + (cutSpan > 0 ? zb('z-cut', cutSpan, cutSpan / span < .25 ? 'Cut' : 'Early cut') : '') + (waitSpan + cutSpan < span ? zb('z-full', span - cutSpan - waitSpan, 'No cut' + (cutSpan + waitSpan > 0 && full !== null ? ' from ' + full : '')) : '') + '</div><div class="slide-nums"><span>' + lo + '</span><span>' + hi + '</span></div>' +
      '<div class="zone-help" id="zoneHelp"' + (zoneOpen ? '' : ' hidden') + '><p><strong>No cut</strong> means TRS pays the full pension your years and salary have earned. ' + (full !== null ? 'For you, that starts at ' + full + '.' : '') + '</p><p><strong>Early cut</strong> means you retire before then and your pension is smaller for life. ' + cutRule(h.type) + '</p>' + (waitSpan > 0 ? '<p><strong>Wait</strong> means you\'d stop teaching before you can draw a pension, so it would start later, at the age shown.</p>' : '') + '</div>';
    /* One row per age. "Now" is added when leaving today means waiting for the pension, so the cost of leaving early shows. */
    var rows = table.slice();
    /* Only when "now" sits close to the first real choice; a 20-year gap would squash every other bar. */
    if (h.age < table[0].age && table[0].age - h.age <= 5) { var s0 = retireAt(h, h.age); if (s0.vested) rows.unshift({ age: h.age, now: true, service: s0.service, pension: s0.pensionMonthlyAtStart, cut: s0.earlyCut, ss: s0.ssMonthly, full: false, sim: s0 }); }
    rows.forEach(function (r) { r.x = survive(h, r.age, r.sim); });
    $('ageChart').innerHTML = ageChart(h, rows);
  } else { $('ageChart').innerHTML = '<p class="note">You\'ll need at least 5 years of service before a pension is possible.</p>'; }

  /* Will it last */
  var sur = survive(h, s.stop, s), enough = '';
  var peak = sur.rows.reduce(function (m, r) { return r.balance > m.balance ? r : m; }, sur.rows[0]), endB = sur.rows[sur.rows.length - 1].balance, crossA = coverUntil(sur);
  var round = function (v) { return plain(Math.round(v / 1000) * 1000); };
  enough += '<p class="lead">' + (sur.lasts ? '<strong>Yes, past ' + LAST_AGE + '.</strong> ' : '<strong>It runs short at ' + sur.firstShort + '.</strong> ') + (crossA ? 'Your income covers your bills until about ' + crossA + '. After that, savings fill the gap' + (peak.age >= LAST_AGE - 1 && sur.lasts ? ', and they still grow, to about ' + round(endB) + ' at ' + LAST_AGE + '.' : (peak.balance > 1000 && peak.age > s.stop ? '. They peak around ' + round(peak.balance) + ' at ' + peak.age : '') + (sur.lasts ? ' and are about ' + round(endB) + ' at ' + LAST_AGE + '.' : '.')) : sur.lasts ? 'Your income covers your bills every year' + (endB > 1000 ? ', and savings grow to about ' + round(endB) + ' by ' + LAST_AGE : '') + '.' : '') + '</p>' + cashChart(h, sur) + (sur.rows.some(function (r) { return r.balance > 1 || r.draw > 1; }) ? '<h3 class="sub">Your savings, year by year</h3>' + balanceChart(sur) : '') ;
  var gapYears = s.vested ? Math.max(0, s.startAge - s.stop) : 0;
  if (gapYears) enough += '<p class="flag">Your pension wouldn\'t start for ' + yearsText(gapYears) + ' after you stop teaching. Plan how you\'d pay bills until then.</p>';
  $('enoughOut').innerHTML = enough;

  var risks = retireStress(h, s.stop);
  $('retireStressOut').innerHTML = '<p class="note no-pdf" style="margin:0 0 10px">Drag any test to make it milder or worse. Each bar shows how long your money lasts.</p>' + riskBars(risks, s.stop) + (h.sp && h.sp.on ? '<p class="note">If you die first, ' + (h.sp.survShare > 0 ? 'your spouse keeps ' + h.sp.survShare + '% of your pension,' : 'this plan\'s pension stops, and your spouse keeps') + ' their own income and the larger Social Security check. If they die first, their pay and pension stop, you keep the larger check, and bills stay the same.</p>' : '');
}

/* Bars for each retirement age, running from that age to where the money ends.
   Navy: income alone pays the bills. Gold: savings fill the gap. A red end: the money runs out before 95. */
function ageChart(h, rows) {
  var W = Math.max(340, Math.min(900, $('s-when').clientWidth || 900)), H = 250, L = 44, R2 = 10, T = 26, B = 40;
  var lo = rows[0].age, hi = LAST_AGE, n = rows.length, band = (W - L - R2) / n, bw = Math.max(6, Math.min(40, band * .7));
  var y = function (v) { return T + (1 - (v - lo) / (hi - lo)) * (H - T - B); };
  var g = '', step = hi - lo > 30 ? 10 : 5;
  for (var v = Math.ceil(lo / step) * step; v < hi; v += step) g += '<line class="gridline" x1="' + L + '" x2="' + (W - R2) + '" y1="' + y(v) + '" y2="' + y(v) + '"/><text class="axis" x="' + (L - 8) + '" y="' + (y(v) + 5) + '" text-anchor="end">' + v + '</text>';
  g += '<line x1="' + L + '" x2="' + (W - R2) + '" y1="' + y(hi) + '" y2="' + y(hi) + '" stroke="var(--ink)" stroke-width="1.5" stroke-dasharray="6 4"/><text x="' + (L - 8) + '" y="' + (y(hi) + 5) + '" text-anchor="end" font-size="13" font-weight="700" fill="var(--ink)">' + hi + '</text>';
  var every = Math.ceil(n / (W < 560 ? 7 : 14));
  var rect = function (x, y1, y2, fill) { return y2 - y1 < .5 ? '' : '<rect x="' + x.toFixed(1) + '" y="' + y1.toFixed(1) + '" width="' + bw.toFixed(1) + '" height="' + (y2 - y1).toFixed(1) + '" fill="' + fill + '"/>'; };
  /* Ages next to the highlighted one are skipped if their labels would touch it. */
  var pickI = rows.findIndex(function (r) { return r.age === h.stopAge; });
  rows.forEach(function (r, i) {
    var cx = L + band * (i + .5), x0 = cx - bw / 2, pick = r.age === h.stopAge;
    var end = r.x.lasts ? hi : Math.max(r.age, r.x.firstShort), cross = coverUntil(r.x);
    var mid = cross === null ? end : Math.min(end, Math.max(r.age, cross));
    r.cross = cross;
    g += '<g opacity="' + (pick ? 1 : .8) + '">' + rect(x0, y(mid), y(r.age), 'var(--chart)') + rect(x0, y(end), y(mid), 'var(--bus)') + (r.x.lasts ? '' : '<rect x="' + x0.toFixed(1) + '" y="' + (y(end) - 3).toFixed(1) + '" width="' + bw.toFixed(1) + '" height="5" fill="var(--apple)"/>') + '</g>';
    if (pick) g += '<rect x="' + (x0 - 2).toFixed(1) + '" y="' + (y(end) - 2).toFixed(1) + '" width="' + (bw + 4).toFixed(1) + '" height="' + (y(r.age) - y(end) + 4).toFixed(1) + '" fill="none" stroke="var(--ink)" stroke-width="2"/><text x="' + cx.toFixed(1) + '" y="' + (y(end) - 9).toFixed(1) + '" text-anchor="middle" font-size="13" font-weight="700" fill="var(--ink)" stroke="var(--paper)" stroke-width="4" paint-order="stroke">' + (r.x.lasts ? hi + '+' : 'To ' + r.x.firstShort) + '</text>';
    if (pick || (i % every === 0 && (pickI < 0 || Math.abs(i - pickI) * band >= 26))) g += '<text class="axis" x="' + cx.toFixed(1) + '" y="' + (H - B + 18) + '" text-anchor="middle"' + (pick ? ' font-weight="700" fill="var(--ink)"' : '') + '>' + r.age + '</text>';
  });
  var key = '<div class="ac-key" aria-hidden="true"><span><i style="background:var(--chart)"></i>Income alone pays the bills</span><span><i style="background:var(--bus)"></i>Savings fill the gap</span><span><i style="background:var(--apple);height:4px"></i>Money runs out</span></div>';
  var ok = rows.filter(function (r) { return r.x.lasts; }), alone = rows.filter(function (r) { return r.x.lasts && r.cross === null; });
  var lbl = 'Chart of retirement ages from ' + lo + ' to ' + rows[n - 1].age + '. ' + (ok.length ? 'From ' + ok[0].age + ' on, the money lasts past ' + LAST_AGE + '. ' : 'At none of these ages does it last to ' + LAST_AGE + '. ') + (alone.length ? 'From ' + alone[0].age + ' on, income alone pays the bills.' : 'At every age, savings are needed to fill a gap.');
  var tips = rows.map(function (r) {
    var how = !r.x.lasts ? (r.cross !== null && r.cross > r.age ? 'Income pays the bills to about ' + r.cross + ', then savings run out at ' + r.x.firstShort : 'Savings run out at ' + r.x.firstShort)
      : r.cross === null ? 'Income alone pays the bills' : r.cross <= r.age ? 'Savings fill a gap from the start' : 'Income pays the bills to about ' + r.cross + ', then savings fill the gap';
    return '<strong>Retire at ' + r.age + (r.now ? ' (now)' : '') + '</strong><br>Pension ' + plain(r.pension) + ' a month' + (r.sim.startAge > r.age ? ' from ' + r.sim.startAge : r.cut ? ' after ' + aPct(r.cut) + '% cut' : '') + '<br>' + how;
  });
  return '<p class="note no-pdf" style="margin-top:2px">Each bar runs from the age you retire. Point at a bar, or tap it, for the pension.</p>' + key + wrapChart('<svg class="chart" viewBox="0 0 ' + W + ' ' + H + '" role="img" aria-label="' + esc(lbl) + '">' + g + '<text class="axis" x="' + ((L + W - R2) / 2) + '" y="' + (H - 4) + '" text-anchor="middle">Age you retire</text>' + hovCols(rows.map(function (r, i) { return L + band * (i + .5); }), T, H - B, tips) + '</svg>');
}
/* Bars for "What could go wrong": each runs from the retirement age to 95, and stops where the money runs out. */
function riskBar(r, stop) {
  var pct = r.lasts ? 100 : Math.max(2, Math.min(100, (r.age - stop) / Math.max(1, LAST_AGE - stop) * 100));
  return '<span class="rb-t"><i class="' + (r.lasts ? 'ok' : 'bad') + '" style="width:' + pct.toFixed(1) + '%"></i></span><b class="' + (r.lasts ? 'ok' : 'bad') + '">' + (r.lasts ? 'Past ' + LAST_AGE : 'To ' + r.age) + '</b>';
}
function riskBars(list, stop) {
  return '<div class="risk-bars" role="list">' + list.map(function (r, i) {
    var sp = r.spec, sl = sp ? '<input type="range" class="rb-s" data-risk="' + sp.k + '" min="' + sp.min + '" max="' + sp.max + '" step="' + sp.step + '" value="' + sp.val + '" aria-label="' + esc(r.label) + '">' : '';
    return '<div class="rb' + (i ? '' : ' base') + '" role="listitem"><span class="rb-l"><span id="rbl-' + (sp ? sp.k : i) + '">' + esc(i ? r.label : 'Your plan as entered') + '</span>' + sl + '</span><span class="rb-o" id="rbo-' + (sp ? sp.k : i) + '">' + riskBar(r, stop) + '</span></div>';
  }).join('') + '<div class="rb-axis" aria-hidden="true"><span></span><span class="rb-ends"><span>Retire at ' + stop + '</span><span>Age ' + LAST_AGE + '</span></span></div></div>';
}
/* Dragging a test re-runs only that row, so the slider keeps its place. */
document.addEventListener('input', function (e) {
  var k = e.target.dataset && e.target.dataset.risk; if (!k || !ready()) return;
  riskOpts[k] = parseFloat(e.target.value);
  var h = safe(), list = retireStress(h, h.stopAge);
  list.forEach(function (r) { if (r.spec && r.spec.k === k) { $('rbl-' + k).textContent = r.label; e.target.setAttribute('aria-label', r.label); $('rbo-' + k).innerHTML = riskBar(r, h.stopAge); } });
});
/* A strip of the service years that matter, with where you are now. */
function milesStrip(h, ms) {
  var W = Math.max(340, Math.min(900, $('s-when').clientWidth || 900)), H = 78, L = 16, R2 = 16, ly = 46;
  var top = Math.max(ms[ms.length - 1][0], Math.ceil(h.years)) + 1, x = function (v) { return L + v / top * (W - L - R2); };
  var g = '<line x1="' + L + '" x2="' + (W - R2) + '" y1="' + ly + '" y2="' + ly + '" stroke="var(--line)" stroke-width="4" stroke-linecap="round"/><line x1="' + L + '" x2="' + x(Math.min(h.years, top)).toFixed(1) + '" y1="' + ly + '" y2="' + ly + '" stroke="var(--leaf)" stroke-width="4" stroke-linecap="round"/>';
  var lastX = -99, next = null;
  ms.forEach(function (m) { if (next === null && m[0] > h.years) next = m[0]; });
  ms.forEach(function (m) {
    var cx = x(m[0]), done = m[0] <= h.years, nx = m[0] === next;
    g += '<circle cx="' + cx.toFixed(1) + '" cy="' + ly + '" r="' + (nx ? 8 : 6) + '" fill="' + (done ? 'var(--leaf)' : nx ? 'var(--bus)' : 'var(--paper)') + '" stroke="' + (done ? 'var(--leaf)' : 'var(--ink)') + '" stroke-width="2"/>';
    if (cx - lastX >= 22 || nx) { g += '<text class="axis" x="' + cx.toFixed(1) + '" y="' + (ly + 26) + '" text-anchor="middle"' + (nx ? ' font-weight="700" fill="var(--ink)"' : '') + '>' + m[0] + '</text>'; lastX = cx; }
  });
  var yx = x(Math.min(h.years, top)), anchor = yx < 70 ? 'start' : yx > W - 70 ? 'end' : 'middle';
  g += '<path d="M' + (yx - 6).toFixed(1) + ' 24 L' + (yx + 6).toFixed(1) + ' 24 L' + yx.toFixed(1) + ' 33 Z" fill="var(--ink)"/><text x="' + yx.toFixed(1) + '" y="17" text-anchor="' + anchor + '" font-size="13" font-weight="700" fill="var(--ink)">You: ' + (Math.round(h.years * 10) / 10) + ' years</text>';
  return '<svg class="chart" viewBox="0 0 ' + W + ' ' + H + '" role="img" aria-label="' + esc('Timeline of service years. You have about ' + (Math.round(h.years * 10) / 10) + ' years' + (next !== null ? '; your next milestone is year ' + next : '') + '.') + '">' + g + '</svg>';
}
function cashChart(h, sur) {
  var rows = sur.rows, W = Math.max(340, Math.min(900, $('s-enough').clientWidth || 900)), H = 260, L = 70, R2 = 12, T = 30, B = 44;
  var inc = rows.map(function (r) { return (r.pension + r.ss + r.otherIncome + (r.spouse || 0)) / 12; }), out = rows.map(function (r) { return (r.bills + r.health + r.tax) / 12; });
  var max = Math.max.apply(null, inc.concat(out, [100])) * 1.1;
  var x = function (i) { return L + i / Math.max(1, rows.length - 1) * (W - L - R2); }, y = function (v) { return T + (1 - v / max) * (H - T - B); };
  var line = function (arr) { return arr.map(function (v, i) { return (i ? 'L' : 'M') + x(i).toFixed(1) + ' ' + y(v).toFixed(1); }).join(' '); };
  var gap = '';
  rows.forEach(function (r, i) { if (i && out[i] > inc[i] + .5) gap += '<path d="M' + x(i - 1).toFixed(1) + ' ' + y(inc[i - 1]).toFixed(1) + ' L' + x(i).toFixed(1) + ' ' + y(inc[i]).toFixed(1) + ' L' + x(i).toFixed(1) + ' ' + y(out[i]).toFixed(1) + ' L' + x(i - 1).toFixed(1) + ' ' + y(out[i - 1]).toFixed(1) + ' Z" fill="var(--apple)" opacity=".16"/>'; });
  var grid = '', tick = niceStep(max, 4);
  for (var v = 0; v <= max; v += tick) grid += '<line class="gridline" x1="' + L + '" x2="' + (W - R2) + '" y1="' + y(v) + '" y2="' + y(v) + '"/><text class="axis" x="' + (L - 8) + '" y="' + (y(v) + 5) + '" text-anchor="end">' + money(v) + '</text>';
  var every = Math.ceil(rows.length / (W < 560 ? 5 : 9));
  rows.forEach(function (r, i) { if (i % every === 0) grid += '<text class="axis" x="' + x(i) + '" y="' + (H - B + 20) + '" text-anchor="middle">' + r.age + '</text>'; });
  var key = '<text x="' + L + '" y="16" font-size="14" font-weight="700" fill="var(--chart)">— Coming in</text><text x="' + (L + 120) + '" y="16" font-size="14" font-weight="700" fill="var(--apple)">- - Going out</text>' + (gap && W >= 560 ? '<text x="' + (L + 240) + '" y="16" font-size="14" fill="var(--soft)">Shaded: paid from savings, or short</text>' : '');
  var lbl = 'Monthly income and costs by age. Income starts at ' + money(inc[0]) + ' and costs at ' + money(out[0]) + '; at ' + rows[rows.length - 1].age + ', income is ' + money(inc[inc.length - 1]) + ' and costs are ' + money(out[out.length - 1]) + '.';
  var tips = rows.map(function (r, i) {
    var parts = [['TRS pension', r.pension], ['Social Security', r.ss], ['your spouse', r.spouse || 0], ['other income', r.otherIncome]].filter(function (q) { return q[1] > 1; }).map(function (q) { return q[0] + ' ' + plain(q[1] / 12); });
    var net = inc[i] - out[i];
    return '<strong>Age ' + r.age + '</strong><br>Coming in ' + plain(inc[i]) + (parts.length > 1 ? ': ' + parts.join(', ') : '') + '<br>Going out ' + plain(out[i]) + ': bills ' + plain(r.bills / 12) + ', health ' + plain(r.health / 12) + ', taxes ' + plain(r.tax / 12) + '<br>' + (r.short > 12 ? '<strong>Short ' + plain(r.short / 12) + '</strong>' : net >= 0 ? plain(net) + ' to spare' : 'From savings ' + plain(r.draw / 12));
  });
  return '<h3 class="sub">What comes in and goes out each month</h3><p class="note no-pdf" style="margin-top:2px">Point at the chart, or tap it, to see any age.</p>' + wrapChart('<svg class="chart" viewBox="0 0 ' + W + ' ' + H + '" role="img" aria-label="' + esc(lbl) + '">' + grid + gap + key + '<path d="' + line(out) + '" fill="none" stroke="var(--apple)" stroke-width="3" stroke-dasharray="7 5"/><path d="' + line(inc) + '" fill="none" stroke="var(--chart)" stroke-width="3"/><text class="axis" x="' + ((L + W - R2) / 2) + '" y="' + (H - 6) + '" text-anchor="middle">Your age, in today\'s dollars</text>' + hovCols(rows.map(function (r, i) { return x(i); }), T, H - B, tips) + '</svg>');
}
function balanceChart(sur) {
  var rows = sur.rows, W = Math.max(340, Math.min(900, $('s-enough').clientWidth || $('results').clientWidth || 900)), H = 262, L = 76, R2 = 12, T = 30, B = 44;
  /* The top of the axis is rounded up to a labelled step, so the highest line always has a value. */
  var top = Math.max.apply(null, rows.map(function (r) { return r.balance; }).concat([1000])), step0 = niceStep(top, 3), max = Math.ceil(top / step0) * step0;
  var x = function (i) { return L + i / Math.max(1, rows.length - 1) * (W - L - R2); }, y = function (v) { return T + (1 - v / max) * (H - T - B); };
  var d = rows.map(function (r, i) { return (i ? 'L' : 'M') + x(i).toFixed(1) + ' ' + y(r.balance).toFixed(1); }).join(' ');
  var area = d + ' L' + x(rows.length - 1) + ' ' + (H - B) + ' L' + L + ' ' + (H - B) + ' Z';
  var grid = '', tick = niceStep(max, 3);
  for (var v = 0; v <= max; v += tick) grid += '<line class="gridline" x1="' + L + '" x2="' + (W - R2) + '" y1="' + y(v) + '" y2="' + y(v) + '"/><text class="axis" x="' + (L - 8) + '" y="' + (y(v) + 5) + '" text-anchor="end">' + money(v) + '</text>';
  var every = Math.ceil(rows.length / (W < 560 ? 5 : 9));
  rows.forEach(function (r, i) { if (i % every === 0) grid += '<text class="axis" x="' + x(i) + '" y="' + (H - B + 20) + '" text-anchor="middle">' + r.age + '</text>'; });
  var mark = '';
  if (sur.firstShort !== null) { var ix = rows.findIndex(function (r) { return r.age === sur.firstShort; }), mx = x(ix); mark = '<line x1="' + mx + '" x2="' + mx + '" y1="' + T + '" y2="' + (H - B) + '" stroke="var(--apple)" stroke-width="2" stroke-dasharray="4 4"/><text x="' + (mx > W - 170 ? mx - 8 : mx + 8) + '" y="' + (T - 10) + '" text-anchor="' + (mx > W - 170 ? 'end' : 'start') + '" font-size="15" font-weight="700" fill="var(--apple)">Runs short at ' + sur.firstShort + '</text>'; }
  var tips = rows.map(function (r) { return '<strong>Age ' + r.age + '</strong><br>Savings left ' + plain(r.balance) + (r.draw > 1 ? '<br>Taking out ' + plain(r.draw / 12) + ' a month' : '<br>Nothing taken out this year'); });
  return wrapChart('<svg class="chart" viewBox="0 0 ' + W + ' ' + H + '" role="img" aria-label="' + esc('Savings balance by age, starting at ' + money(rows[0].balance) + (sur.firstShort !== null ? ' and running short at age ' + sur.firstShort : ' and lasting past age ' + LAST_AGE)) + '">' + grid + '<path d="' + area + '" fill="var(--bus)" opacity=".45"/><path d="' + d + '" fill="none" stroke="var(--ink)" stroke-width="3"/>' + mark + '<text class="axis" x="' + ((L + W - R2) / 2) + '" y="' + (H - 6) + '" text-anchor="middle">Your age, with savings in today\'s dollars</text>' + hovCols(rows.map(function (r, i) { return x(i); }), T, H - B, tips) + '</svg>');
}

function talkText(h) {
  if (!ready()) return '';
  var s = retireAt(h, h.stopAge), f = survive(h, h.stopAge, s).rows[0], both = !!(h.sp && h.sp.on);
  var total = (f.pension + f.ss + f.otherIncome + (f.spouse || 0)) / 12;
  var line = 'I\'ve been looking at my retirement. If I teach until ' + s.stop + ', ' + (both ? 'we' : 'I') + ' could have about ' + plain(total) + ' a month coming in at first, in today\'s dollars';
  var bits = [];
  if (f.pension > 0) bits.push('about ' + plain(f.pension / 12) + ' from TRS');
  if (both && f.spouse > 0) bits.push('about ' + plain(f.spouse / 12) + ' from your pay and pension');
  if (bits.length === 1 && Math.abs(f.pension / 12 - total) < 1) line += ', all from TRS';
  else if (bits.length) line += ', including ' + bits.join(' and ');
  line += '. ';
  var surT = survive(h, h.stopAge, s);
  line += surT.lasts ? 'On those numbers, ' + (both ? 'our' : 'my') + ' money could last past ' + LAST_AGE + ' with ' + plain(h.goal) + ' a month in bills. ' : 'On those numbers, ' + (both ? 'our' : 'my') + ' money could run short at ' + surT.firstShort + ' with ' + plain(h.goal) + ' a month in bills. ';
  var hpT = healthPlan(h, s);
  line += 'Health coverage could cost about ' + plain(hpT.post) + ' a month from 65' + (hpT.yearsPre > 0 ? ', and about ' + plain(hpT.pre) + ' a month before then' : '') + '. ';
  line += 'These are estimates, and I still need official numbers from TRS. What would you want retirement to look like?';
  return line;
}

function niceStep(span, count) {
  var raw = span / count, mag = Math.pow(10, Math.floor(Math.log10(raw || 1))), n = raw / mag;
  return (n <= 1 ? 1 : n <= 2 ? 2 : n <= 5 ? 5 : 10) * mag;
}
function renderRoad(h) {
  if ($('miles')) $('miles').innerHTML = ready() ? renderMilestones(h) : '';
  if (!ready()) { $('refundOut').innerHTML = '<p>Enter your service years and salary to estimate a refund.</p>'; return; }
  var more = Math.max(0, Math.round(h.stopAge - h.age));
  var rv = refundView(h, { stay: false, more: more, salary: 0 });
  var dfl = Math.pow(1 + h.inflation / 100, more);
  var gross = rv.gross / dfl, after = rv.after / dfl;
  var service = h.years + more;
  var sp0 = retireAt(h, h.age + more), pen = sp0.vested ? sp0.pensionMonthlyAtStart : 0, payback = pen > 0 ? gross / (pen * 12) : null;
  var t = function (cls, label, val, sub) { return '<div class="ss-t' + (cls ? ' ' + cls : '') + '"><small>' + label + '</small><strong>' + val + '</strong><small>' + sub + '</small></div>'; };
  $('refundOut').innerHTML = gross > 0
    ? '<p class="note" style="margin-top:0">Leaving at ' + (h.age + more) + ' with about ' + (Math.round(service * 10) / 10) + ' years of service, in today\'s money:</p><div class="ss-tiles">' +
      t('', 'Refund, once', money(gross), 'About ' + money(after) + ' if taken as cash, after tax' + (rv.penalty > 0 ? ' and penalty' : '')) +
      (pen > 0 ? t('ok', 'Pension instead', plain(pen) + ' a month', 'For life' + (sp0.startAge > h.age + more ? ', from age ' + sp0.startAge : '')) +
        t(payback <= 10 ? 'ok' : '', 'The pension pays it back in', 'About ' + Math.max(1, Math.round(payback)) + (Math.round(payback) === 1 ? ' year' : ' years'), 'Every year after that is money the refund wouldn\'t give you')
        : t('', 'Pension instead', 'None yet', 'You need 5 years of service to keep a pension')) + '</div>' +
      '<p class="note">' + (pen > 0 ? 'Taking the refund gives up the pension for those years. ' : '') + 'Moving it straight into an IRA usually puts off the tax. This is an estimate: confirm the amount and taxes with TRS before deciding.</p>'
    : '<p>No refund could be estimated from your numbers.</p>';
}

function renderSide(h, stay) {
  var box = $('sideOut');
  $('sideWrap').hidden = h.univ || stay.credits >= 40;
  if (h.univ || stay.credits >= 40) { box.innerHTML = ''; return; }
  var r = sideWork(h, stay, h.sidePay);
  var over = Math.round(r.monthly * 12 * 20 / 1000) * 1000;
  box.innerHTML = r.creditsPerYear
    ? '<div class="ss-tiles"><div class="ss-t ok"><small>Extra each month</small><strong>+' + plain(r.monthly) + '</strong><small>From age ' + h.claimAge + ', for life</small></div><div class="ss-t ok"><small>Over 20 years</small><strong>' + plain(over) + '</strong><small>In today\'s money</small></div><div class="ss-t"><small>What it takes</small><strong>' + yearsText(r.years) + '</strong><small>About ' + plain(r.costYear) + ' a year in payroll tax</small></div></div>'
    : '<p class="flag">That\'s below the ' + plain(R.credit) + ' a year needed to earn one credit in 2026.</p>';
}

/* ---------- Checklist for contacting TRS ---------- */
function passQuestions(h, s) {
  var q = ['What would my pension be under each survivor option, using my beneficiary\'s birth date?', 'What would my retiree health coverage cost at my retirement date?', 'Does my extra-duty pay count toward my pension?', 'Will my district buy my unused sick leave as service credit, or pay it out?'];
  if (s.earlyCut) q.push('How is my ' + s.earlyCut + '% early-retirement cut figured for partial years?');
  if (h.moved) q.push('Can I buy credit for my out-of-state teaching, and what would it cost?');
  if (h.later) q.push('Does any of my earlier public work count through reciprocity?');
  return q;
}
function renderPass(h) {
  var s = retireAt(h, h.stopAge), year = retireDate(h.stopAge - h.age).getFullYear(), blank = '<span class="blank">&nbsp;</span>';
  var rows = [
    ['TRS member ID', blank + '<br><small>On your TRS statement or in Pathway</small>'],
    ['Current year contract salary', plain(h.salary)], ['Current year extra-duty salary', blank],
    ['Beneficiary\'s relationship and birth date', blank], ['Projected retirement date', 'Age ' + h.stopAge + ', around ' + year],
    ['Unused sick leave balance', h.sickDays > 0 ? h.sickDays + ' days' : blank], ['Projected raises', h.raise + '% a year']
  ];
  $('passOut').innerHTML = '<div class="pass"><div class="pass-top"><strong>Retirement estimate checklist</strong><span>Teachers\' Retirement System of the State of Kentucky</span></div>' +
    '<p class="pass-sub">Have this ready when you call TRS or request an estimate in Pathway. Prepared ' + new Date().toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' }) + '.</p>' +
    '<h3>Information TRS will ask for</h3><dl>' + rows.map(function (r) { return '<dt>' + r[0] + '</dt><dd>' + r[1] + '</dd>'; }).join('') + '</dl>' +
    '<h3>Questions to ask</h3><ol>' + passQuestions(h, s).map(function (x) { return '<li>' + esc(x) + '</li>'; }).join('') + '</ol>' +
    '<h3>How to reach TRS</h3><p style="margin:0">Phone 800-618-1687, the secure email form on the TRS Contact Us page (trs.ky.gov), or Pathway member self-service. Figures here are planning estimates from School\'s Out, not TRS.</p></div>';
}

function renderSs(h, stay) {
  var sp = h.sp && h.sp.on ? h.sp : null, html = '';
  var tile = function (label, val, sub, cls) { return '<div class="ss-t' + (cls ? ' ' + cls : '') + '"><small>' + label + '</small><strong>' + val + '</strong><small>' + sub + '</small></div>'; };
  if (h.univ) html += '<p class="lead">University staff pay into both TRS and Social Security, so you\'ll get both.</p>';
  else html += '<p class="lead">Teaching in a Kentucky school district doesn\'t pay into Social Security. Other jobs do, and a TRS pension no longer cuts what you earn from them.</p>';
  html += '<div class="ss-tiles">' + (stay.credits >= 40 ? tile('Your Social Security', plain(stay.ssMonthly) + ' a month', 'From age ' + h.claimAge + ', for life', 'ok')
    : tile('Your Social Security', '$0', stay.credits > 0 ? 'You have ' + stay.credits + ' of the 40 credits you need' : 'No other jobs entered yet')) + '</div>';
  if (sp) {
    var own = stay.pia || 0, top = Math.max(0, sp.pia / 2 - own) * spousalFactor(h.claimAge);
    html += '<p class="note">Your spouse\'s own Social Security, about ' + plain(ssMonthly(sp.pia, sp.claimAge || 67)) + ' a month from their age ' + (sp.claimAge || 67) + (sp.piaEst ? ' (estimated from their pay)' : '') + ', is counted in your plan.' +
      (top >= 1 ? ' You could also get about ' + plain(top) + ' a month on their record from your age ' + h.claimAge + '. That\'s counted too.' : '') + '</p>';
  }
  $('ssOut').innerHTML = html;
  $('ssMore').innerHTML = '<p class="note">See your real record at <a href="https://www.ssa.gov/myaccount/" rel="noopener">ssa.gov/myaccount</a>.</p>';
}

/* Health insurance before 65, by the age you stop teaching: shows where more years lower the cost. */
function healthChart(h, s) {
  if (h.age >= 64) return '';
  var list = [];
  for (var a = h.age; a <= 64; a++) { var sa = retireAt(h, a); list.push({ age: a, cost: healthPlan(h, sa).pre, ok: sa.vested && sa.healthEligible, svc: sa.service, share: sa.share }); }
  if (list.every(function (r) { return Math.abs(r.cost - list[0].cost) < 1; })) return '';
  var W = Math.max(340, Math.min(900, $('s-health').clientWidth || 900)), H = 230, L = 62, R2 = 12, T = 16, B = 44, step = (W - L - R2) / list.length;
  var max = Math.max.apply(null, list.map(function (r) { return r.cost; }).concat([100])) * 1.1, y = function (v) { return T + (1 - v / max) * (H - T - B); };
  var grid = '', tick = niceStep(max, 3), every = Math.max(1, Math.ceil(list.length / (W < 560 ? 6 : 12)));
  for (var v = 0; v <= max; v += tick) grid += '<line class="gridline" x1="' + L + '" x2="' + (W - R2) + '" y1="' + y(v) + '" y2="' + y(v) + '"/><text class="axis" x="' + (L - 8) + '" y="' + (y(v) + 5) + '" text-anchor="end">' + money(v) + '</text>';
  var pickH = list.findIndex(function (r) { return r.age === s.stop; });
  var bars = list.map(function (r, i) {
    var x = L + i * step, top = y(r.cost), pick = r.age === s.stop;
    return '<rect x="' + (x + 1) + '" y="' + top + '" width="' + Math.max(2, step - 3) + '" height="' + (H - B - top) + '" fill="' + (pick ? 'var(--bus)' : r.ok ? 'var(--chart)' : '#9aa0b8') + '"/><rect class="hov" x="' + x + '" y="' + T + '" width="' + step + '" height="' + (H - B - T) + '" fill="transparent" data-tip="' + esc('<strong>Stop at ' + r.age + ', with ' + Math.round(r.svc) + ' years</strong><br>' + plain(r.cost) + ' a month until 65<br>' + (r.ok ? 'TRS pays ' + Math.round(r.share * 100) + '% of its share' : 'No TRS coverage, so this is the stand-in price for a plan of your own')) + '"/>' + (pick || (i % every === 0 && (pickH < 0 || Math.abs(i - pickH) * step >= 26)) ? '<text class="axis" x="' + (x + step / 2) + '" y="' + (H - B + 20) + '" text-anchor="middle"' + (pick ? ' font-weight="700"' : '') + '>' + r.age + '</text>' : '');
  }).join('');
  var lbl = 'Monthly health insurance before 65 by the age you stop teaching, from ' + money(list[0].cost) + ' at ' + list[0].age + ' to ' + money(list[list.length - 1].cost) + ' at ' + list[list.length - 1].age + '.';
  return '<h3 class="sub">Your health insurance before 65, by the age you stop teaching</h3><p class="note" style="margin-top:2px">Each bar is what you\'d pay each month until Medicare. The cost drops at the years of service where TRS pays more. Your plan\'s age is in gold' + (list.some(function (r) { return !r.ok; }) ? '. Grey bars mean no TRS coverage, so they use your own plan\'s price, ' + plain(h.marketHealth) + ' a month' : '') + '.<span class="no-pdf"> Point at a bar for details.</span></p>' + wrapChart('<svg class="chart" viewBox="0 0 ' + W + ' ' + H + '" role="img" aria-label="' + esc(lbl) + '">' + grid + bars + '<text class="axis" x="' + ((L + W - R2) / 2) + '" y="' + (H - 6) + '" text-anchor="middle">Age you stop teaching</text></svg>');
}
/* What health insurance costs each month from retirement to 95: the step down at 65 is the point. */
function healthTimeline(h, s) {
  var rows = survive(h, s.stop, s).rows, W = Math.max(340, Math.min(900, $('s-health').clientWidth || 900)), H = 230, L = 62, R2 = 12, T = 34, B = 44;
  var v = rows.map(function (r) { return r.health / 12; }), n = rows.length, max = Math.max.apply(null, v.concat([100])) * 1.2;
  var bw = (W - L - R2) / n, x = function (i) { return L + i * bw; }, y = function (c) { return T + (1 - c / max) * (H - T - B); };
  var g = '', tick = niceStep(max, 3);
  for (var t = 0; t <= max; t += tick) g += '<line class="gridline" x1="' + L + '" x2="' + (W - R2) + '" y1="' + y(t) + '" y2="' + y(t) + '"/><text class="axis" x="' + (L - 8) + '" y="' + (y(t) + 5) + '" text-anchor="end">' + money(t) + '</text>';
  var d = 'M' + L + ' ' + (H - B);
  v.forEach(function (c, i) { d += ' L' + x(i).toFixed(1) + ' ' + y(c).toFixed(1) + ' L' + x(i + 1).toFixed(1) + ' ' + y(c).toFixed(1); });
  d += ' L' + x(n).toFixed(1) + ' ' + (H - B) + ' Z';
  /* Label each stretch where the cost holds steady: before Medicare, then Medicare. */
  var segs = [], st = 0;
  for (var i = 1; i <= n; i++) if (i === n || (rows[i].age === 65 && rows[i - 1].age === 64) || Math.abs(v[i] - v[st]) > Math.max(25, v[st] * .15)) { segs.push([st, i - 1]); st = i; }
  segs.forEach(function (sg) {
    var a = rows[sg[0]].age, b = rows[sg[1]].age, cx = (x(sg[0]) + x(sg[1] + 1)) / 2, avg = v.slice(sg[0], sg[1] + 1).reduce(function (p, q) { return p + q; }, 0) / (sg[1] - sg[0] + 1);
    if (x(sg[1] + 1) - x(sg[0]) < 70) return;
    var name = b < 65 ? 'Before Medicare' : a >= 65 ? 'With Medicare' : 'Age ' + a + ' to ' + b;
    g += '<text x="' + cx.toFixed(1) + '" y="' + (y(Math.max.apply(null, v.slice(sg[0], sg[1] + 1))) - 18).toFixed(1) + '" text-anchor="middle" font-size="13" fill="var(--soft)">' + name + '</text><text x="' + cx.toFixed(1) + '" y="' + (y(Math.max.apply(null, v.slice(sg[0], sg[1] + 1))) - 3).toFixed(1) + '" text-anchor="middle" font-size="15" font-weight="700" fill="var(--ink)">' + plain(avg) + ' a month</text>';
  });
  var i65 = rows.findIndex(function (r) { return r.age === 65; });
  var every = Math.ceil(n / (W < 560 ? 5 : 9));
  rows.forEach(function (r, i) { if ((i % every === 0 && (i65 < 0 || Math.abs(i - i65) * bw > 26)) || i === i65) g += '<text class="axis" x="' + (x(i) + bw / 2).toFixed(1) + '" y="' + (H - B + 20) + '" text-anchor="middle"' + (i === i65 ? ' font-weight="700" fill="var(--ink)"' : '') + '>' + r.age + '</text>'; });
  var tips = rows.map(function (r, i) { return '<strong>Age ' + r.age + '</strong><br>Health insurance ' + plain(v[i]) + ' a month' + (r.age >= 65 ? ', with Medicare' : ''); });
  var total = v.reduce(function (p, q) { return p + q * 12; }, 0);
  var lbl = 'Monthly health insurance cost by age, from ' + money(v[0]) + ' at ' + rows[0].age + (i65 > 0 ? ' to ' + money(v[i65]) + ' at 65, when Medicare starts' : '') + '.';
  return '<h3 class="sub">What you\'d pay for health insurance each month</h3><p class="note" style="margin-top:2px">From retiring at ' + s.stop + ' to ' + LAST_AGE + ', in today\'s dollars' + (h.sp && h.sp.on && rows[0].health / 12 > healthPlan(h, s).pre + 1 ? ', including your spouse' : '') + '. That\'s about ' + plain(Math.round(total / 1000) * 1000) + ' in premiums in all, before deductibles and copays.</p>' + wrapChart('<svg class="chart" viewBox="0 0 ' + W + ' ' + H + '" role="img" aria-label="' + esc(lbl) + '">' + g + '<path d="' + d + '" fill="var(--chart)" opacity=".75"/><text class="axis" x="' + ((L + W - R2) / 2) + '" y="' + (H - 6) + '" text-anchor="middle">Your age</text>' + hovCols(rows.map(function (r, i) { return x(i) + bw / 2; }), T, H - B, tips) + '</svg>');
}
function renderHealth(h) {
  if (!ready()) { $('healthOut').innerHTML = ''; return; }
  var s = retireAt(h, h.stopAge), hp = healthPlan(h, s);
  var steps = [];
  if (hp.yearsPre > 0) steps.push('<div class="panel"><h3>Age ' + s.stop + (s.stop < 64 ? ' to 64' : '') + '</h3><p class="bigline">' + plain(hp.pre) + ' a month</p><p>' + (hp.eligible ? 'TRS group coverage through the Kentucky Employees\' Health Plan, with ' + Math.round(hp.share * 100) + '% of the TRS contribution.' : 'Estimated cost of coverage outside TRS because you would not qualify for TRS coverage on this path.') + '</p></div>');
  steps.push('<div class="panel"><h3>Age 65 and up</h3><p class="bigline">' + plain(hp.post) + ' a month</p><p>' + (hp.eligible ? 'The TRS Medicare plan plus your Medicare Part B cost.' : 'Estimated Medicare and other coverage costs.') + '</p></div>');
  var html = '<div class="two">' + steps.join('') + '</div>' + healthTimeline(h, s);
  var noTrs = !hp.eligible && hp.yearsPre > 0;
  var canMissTrs = h.age < 65 && !healthPlan(h, retireAt(h, h.age)).eligible;
  if (noTrs) html += '<div class="panel" style="margin-top:14px"><h3>Leaving before TRS health coverage</h3>' +
    '<p>At age ' + s.stop + ', you would need insurance outside TRS until Medicare. School\'s Out includes an estimated ' + plain(h.marketHealth) + ' per month in your affordability calculations. This is a planning assumption, not a marketplace quote.</p>' +
    '<label class="f" for="resultOutsidePremium">Change your estimated monthly premium (optional)<span class="affix"><span class="pre">$</span><input id="resultOutsidePremium" type="number" min="0" max="10000" step="10" value="' + h.marketHealth + '"><span>a month</span></span></label>' +
    '<p class="note">Check actual prices at <a href="https://kynect.ky.gov/" target="_blank" rel="noopener">kynect.ky.gov</a> or through another insurer. Your eligibility and cost may vary.</p></div>';
  else if (canMissTrs) html += '<details style="margin-top:14px"><summary>What if you left before qualifying for TRS coverage?</summary><p>Leaving earlier could mean paying for coverage outside TRS until Medicare. The calculator uses ' + plain(h.marketHealth) + ' per month as a starting estimate for those years, not a quote.</p><label class="f" for="resultOutsidePremium">Estimated monthly premium<span class="affix"><span class="pre">$</span><input id="resultOutsidePremium" type="number" min="0" max="10000" step="10" value="' + h.marketHealth + '"><span>a month</span></span></label><p class="note">Compare actual plans at <a href="https://kynect.ky.gov/" target="_blank" rel="noopener">kynect.ky.gov</a>.</p></details>';
  html += healthChart(h, s);
  if (h.sp && h.sp.on && h.sp.onTrs && hp.eligible) html += '<p class="note">Your spouse on your TRS plan pays full price: about ' + plain(R.kehpSpouse) + ' a month until they turn 65, then ' + plain(R.mehpFull + R.partB) + ' with Medicare Part B. That\'s counted in Will your money last.</p>';
  if (h.sp && h.sp.on && h.sp.trs && h.sp.hPre !== undefined) html += '<p class="note">Your spouse\'s own TRS plan would cost about ' + plain(h.sp.hPre) + ' a month before they turn 65 and ' + plain(h.sp.hPost) + ' after, starting when they stop working. That\'s counted in Will your money last.</p>';

  if (!hp.eligible && (h.type === '3' || h.type === '4') && s.service < 15) html += '<p class="flag">You\'d need at least 15 years of service for TRS retiree coverage. You\'d reach that about ' + yearsText(Math.ceil(15 - s.service)) + ' after this date.</p>';
  if (hp.next && hp.yearsPre > 0) html += '<p class="flag good"><strong>Worth checking:</strong> at ' + hp.next.years + ' years of service, the TRS contribution rises to ' + Math.round(hp.next.share * 100) + '%, which could lower your cost before 65 to about ' + plain(hp.next.cost) + ' a month.</p>';
  if (hp.gapYears > 0) html += '<p class="flag">Your pension wouldn\'t start for ' + yearsText(hp.gapYears) + ' after you stop teaching. Ask TRS when your retiree coverage could start, and plan coverage for that gap.</p>';
  html += '<p class="note">TRS\'s 2026 prices for one person. <a href="#fp-how" data-fp>How the math works</a> has what isn\'t counted.</p>';
  $('healthOut').innerHTML = html;
}

/* ---------- Extra credit ---------- */
var GRADES = ['F', 'D', 'C-', 'C', 'C+', 'B-', 'B', 'B+', 'A-', 'A', 'A+'];
function extraCredit(h, s, now) {
  if (now === 'I' || now === 'A+') return [];
  var tries = [];
  if (s.stop < 75) tries.push(['Teach 1 more year and retire at ' + (s.stop + 1), Object.assign({}, h, { stopAge: s.stop + 1 })]);
  if (s.stop > h.age) tries.push(['Save $100 more a month until you retire', Object.assign({}, h, { saveMonthly: h.saveMonthly + 100 })]);
  if (h.goal > 600) tries.push(['Trim $200 a month from your retirement bills', scaleBills(h, 1, -200)]);
  if (s.ssMonthly > 0 && h.claimAge < 70) tries.push(['Start Social Security at 70 instead of ' + h.claimAge, Object.assign({}, h, { claimAge: 70 })]);
  var base = GRADES.indexOf(now);
  return tries.map(function (x) { var g = gradePlan(x[1], retireAt(x[1], x[1].stopAge)).overall; return [x[0], g]; })
    .filter(function (x) { return GRADES.indexOf(x[1]) > base; });
}

function gradeWord(g) { return g === 'I' ? 'Incomplete' : g.replace('+', ' plus').replace('-', ' minus'); }
function renderReportCard(h, s) {
  var g = gradePlan(h, s), box = $('reportCard');
  box.hidden = false;
  $('rcGrade').textContent = g.overall;
  $('rcGrade').setAttribute('aria-label', 'Overall grade: ' + gradeWord(g.overall));
  $('rcNote').textContent = g.overall === 'I' ? 'Incomplete: you\'d have under 5 years of service at age ' + s.stop + ', so there\'s no TRS pension to grade yet.' : 'Your overall grade is how long your money lasts if you retire at ' + s.stop + '.';
  $('rcRows').innerHTML = g.subjects.map(function (r) { return '<tr><th scope="row">' + r[0] + '</th><td class="rc-g" aria-label="' + gradeWord(r[1]) + '">' + r[1] + '</td><td>' + esc(r[2]) + '</td></tr>'; }).join('');
  $('rcTable').hidden = !g.subjects.length;
  var ec = extraCredit(h, s, g.overall), ex = $('rcExtra');
  ex.hidden = !ec.length;
  ex.innerHTML = ec.length ? '<h3>Extra credit</h3><p style="margin:0 0 6px">What-ifs that would raise this grade. They\'re ideas to test, not advice.</p><ul>' + ec.map(function (x) { return '<li>' + esc(x[0]) + ': <span class="up">' + esc(g.overall) + ' to ' + esc(x[1]) + '</span></li>'; }).join('') + '</ul>' : '';
}
function renderYou(h) {
  var tips = [], s = retireAt(h, h.stopAge), box = $('youOut');
  if (h.later) {
    if (s.service < 27 && h.type !== '4' && s.stop < 60) tips.push('You\'d have about ' + Math.round(s.service) + ' Kentucky years by ' + s.stop + '. Without 27 years, an unreduced pension generally waits until age 60.');
    if (h.type === '4' && s.stop < 65) tips.push('With TRS 4, an unreduced pension needs age 60 with 10 years or age 65 with 5, so it pays to know your date.');
    if (s.service < 15 && (h.type === '3' || h.type === '4')) tips.push('You\'d have under 15 years, so you wouldn\'t qualify for TRS retiree health coverage. Plan for your own coverage until Medicare.');
    tips.push(s.credits >= 40 ? 'Your earlier jobs and any work after teaching could give you ' + plain(s.ssMonthly) + ' a month from Social Security at ' + h.claimAge + '. Check your earnings record.' : 'You have ' + s.credits + ' of 40 Social Security credits. Part-time or summer work could get you there.');
    tips.push('List every old 401(k) and IRA. Consider asking a fee-only professional whether keeping or combining them makes sense.');
  }
  if (h.otherPension > 0 && h.boughtYears > 0) tips.push('You entered both a pension from another state and years to buy from TRS. TRS won\'t sell credit for years another pension counts, so make sure these are different years.');
  if (h.moved) {
    tips.push('Find out if you\'re still owed a pension or refund from your old state. Ask for its deadlines before you withdraw anything.');
    tips.push('Check whether your old job paid into Social Security. If it did, count it in your earlier work.');
    var allowed = allowedOutOfState(h.years, 10);
    tips.push('To buy out-of-state credit, TRS generally requires active membership and 2 Kentucky years, at least one after your out-of-state service. You can buy 1 year for every 2 Kentucky years, up to 10 once you reach 10 Kentucky years. Right now that could be up to ' + yearsText(allowed) + '.');
    tips.push('You can\'t buy service that you\'re using, or will use, for a pension from another state. Purchased service doesn\'t count toward the 5 Kentucky years needed for vesting.');
    if (h.boughtYears > 0) {
      var pv = purchaseView(h, h.stopAge);
      tips.push('Buying ' + yearsText(pv.used) + ' could add about ' + plain(pv.gain) + ' a month to your pension' + (pv.payback ? ', paying back your ' + plain(h.boughtCost) + ' cost in about ' + Math.ceil(pv.payback) + ' years of payments' : '') + (pv.earlier ? ', and could move your full pension from age ' + pv.earlier[0] + ' to ' + pv.earlier[1] : '') + '. TRS sets the final cost, and quotes can change.');
    }
  }
  box.parentNode.hidden = !tips.length;
  box.innerHTML = '<ul class="tight">' + tips.map(function (x) { return '<li>' + esc(x) + '</li>'; }).join('') + '</ul>';
}

/* Going back to work after retiring, under KRS 161.605 as amended July 15, 2026. */
function renderWork(h) {
  if (!ready()) { $('workOut').innerHTML = ''; return; }
  var s = retireAt(h, h.stopAge), more = Math.max(0, h.stopAge - h.age);
  var yrs = s.service + (s.boughtNow || 0) + (h.sickYears || 0), pct = yrs >= 30 ? 75 : 65;
  var last = h.salary * Math.pow((1 + h.raise / 100) / (1 + h.inflation / 100), more), cap = Math.round(last * pct / 100 / 1000) * 1000;
  var t = function (cls, label, val, sub) { return '<div class="ss-t' + (cls ? ' ' + cls : '') + '"><small>' + label + '</small><strong>' + val + '</strong><small>' + sub + '</small></div>'; };
  $('workOut').innerHTML = '<div class="ss-tiles">' +
    t('', 'Wait first', '3 months', 'After your retirement date, before any school job. A full-time job with the same district means waiting a year.') +
    t('ok', 'Then you can earn up to', plain(cap) + ' a year', pct + '% of your last salary' + (yrs >= 30 ? ', because you\'d have 30 years' : '') + ', and your pension keeps coming. Earn more and it\'s cut dollar for dollar.') +
    t('ok', 'Jobs outside schools', 'No TRS limit', 'Work that isn\'t covered by TRS doesn\'t touch your pension.') + '</div>' +
    '<p><strong>Don\'t line up the job before you retire.</strong> If TRS finds you agreed to come back before your retirement date, it cancels the retirement and you repay what you got, with interest.</p>' +
    '<p class="note">Ask TRS before you accept a job.</p>';
}
function renderFamily(h) {
  var life = h.type === '4' ? '$5,000' : '$2,000', s = retireAt(h, h.stopAge), mar = !!(h.sp && h.sp.on);
  var tile = function (cls, label, val, sub) { return '<div class="ss-t' + (cls ? ' ' + cls : '') + '"><small>' + label + '</small><strong>' + val + '</strong><small>' + sub + '</small></div>'; };
  /* After retiring: the standard pension stops at death. A survivor option, picked when you retire, keeps a check going to your husband or wife for life in exchange for a smaller one now. */
  var afterT = !s.vested ? tile('', 'If you die after you retire', '$0', 'No pension yet: you need 5 years')
    : s.survF < 1 ? tile('ok', 'If you die after you retire', plain(s.pensionMonthlyAtStart * h.sp.survShare / 100) + ' a month', 'To your husband or wife for life, from the survivor option you entered')
    : tile(mar ? 'warn' : '', 'If you die after you retire', '$0', mar ? 'Unless you pick a survivor option when you retire. Then they get a check for life, and yours is a bit smaller.' : 'Your checks stop');
  var todo = ['<strong>Make sure TRS has the right person listed</strong> to get your money. There are two forms, one for your pension and one for the ' + life + ' payment. Update both after a marriage, divorce or new baby.',
    s.survF < 1 ? '<strong>Check these amounts</strong> against the estimate TRS gives you.' : '<strong>Before you retire, ask TRS</strong> what each survivor option would pay, using ' + (mar ? 'your husband or wife\'s' : 'your beneficiary\'s') + ' birth date.' + (mar ? ' Then enter it on the Your spouse page to see what it does to your plan.' : ''),
    '<strong>If your family depends on your pay,</strong> look into life insurance. ' + life + ' won\'t replace it.'];
  $('familyOut').innerHTML = '<div class="ss-tiles">' + tile('ok', 'If you die while teaching', '$180 a month', (mar ? 'To your husband or wife' : 'To a husband or wife, if you have one') + ', for life' + (h.years >= 10 ? ', or a check based on your pension' : '') + '. $240 if they earn under $550 a month.') +
    tile('ok', 'Your children', '$200 a month', 'For one child, up to $440 for all, until 18 (23 in college)') + afterT + tile('', 'One-time payment', life, 'For funeral costs') + '</div>' +
    '<h3 class="sub">What to do</h3><ul class="tight">' + todo.map(function (x) { return '<li>' + x + '</li>'; }).join('') + '</ul>' +
    (mar && s.vested ? '<p class="note">"What could go wrong" shows what happens to your money if either of you dies first.</p>' : '') +
    '';
}

function renderPlan(h, stay) {
  /* Your last year, month by month, counted back from a July 1 retirement after your final school year.
     Deadlines and documents are from TRS's retirement application page (F-23). */
  if (!ready()) { $('next3').innerHTML = ''; } else {
    var now = new Date(), R = retireDate(h.stopAge - h.age);
    var at = function (m) { var d = new Date(R); d.setMonth(d.getMonth() - m); return d; };
    var mon = function (d) { return d.toLocaleDateString('en-US', { month: 'short', year: 'numeric' }); };
    var checks = state.checks || {};
    var items = [
      [12, 'est', 'Get an official TRS estimate.', 'Call TRS at 800-618-1687 or use Pathway. <button type="button" class="link-btn" data-print-pass>Print the checklist</button> of what they\'ll ask you and what to ask them.'],
      [10, 'stmt', 'Check your TRS statement.', 'Make sure your years of service and salaries are right.'],
      [9, 'sick', 'Ask about your sick days.', 'Ask your district how many unused days you\'ll have and what it does with them at retirement.'],
      [8, 'talk', 'Talk it over at home.', '<button type="button" class="link-btn" id="copyTalk">Copy a short summary</button> of your plan to share.'],
      [6, 'bene', 'Check your beneficiary.', 'There are two forms: one for your TRS account and one for TRS life insurance.'],
      [4, 'docs', 'Gather your documents.', 'A certified birth certificate (not the hospital one), your signed Social Security card, and a marriage certificate if it applies. For a survivor option, your beneficiary\'s too.'],
      [3, 'opts', 'Decide on health coverage' + (h.sp && h.sp.on ? ' and a survivor option.' : '.'), 'Ask TRS what each choice costs before you apply.'],
      [2, 'apply', 'Apply for retirement.', 'Fill out your part of the application (Form F-23) on Pathway or on paper, then ask your district to fill out its part.'],
      [1, null, 'Application due ' + R.toLocaleDateString('en-US', { month: 'long', day: 'numeric' }) .replace(/July 1/, 'June 1') + '.', 'TRS must have it a month before your retirement date.'],
      [0, null, 'School\'s out.', 'Your retirement starts ' + R.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' }) + '.']
    ];
    var row = function (it) {
      var d = at(it[0]), due = d <= now && it[0] > 0;
      return '<li><b class="ap-when">' + (due ? 'Now' : mon(d)) + '</b>' + (it[1] ? '<input type="checkbox" data-task="' + it[1] + '"' + (checks[it[1]] ? ' checked' : '') + ' aria-label="Done: ' + esc(it[2].replace(/\.$/, '')) + '">' : '<span class="ap-gap"></span>') + '<span><strong>' + it[2] + '</strong> ' + it[3] + '</span></li>';
    };
    var y0 = R.getFullYear() - 1;
    $('next3').innerHTML = '<h3 class="sub">Your last year</h3><p style="margin:2px 0 8px">The ' + y0 + '&ndash;' + String(R.getFullYear()).slice(2) + ' school year, if you retire ' + R.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' }) + '.</p><ul class="ap">' + items.map(row).join('') + '</ul>';
  }
  renderYou(h);
  renderWork(h);
  renderFamily(h);
  renderPass(h);

}
function renderYears(h) {
  if (!ready()) { $('yearTable').innerHTML = ''; return; }
  var v = survive(h, h.stopAge), sp = h.sp && h.sp.on, m = function (x) { return money(x / 12); }, anyOnce = v.rows.some(function (r) { return r.once > 0; });
  $('yearTable').innerHTML = '<thead><tr><th scope="col">Age</th><th scope="col">TRS pension</th><th scope="col">Social Security</th>' + (sp ? '<th scope="col">Your spouse</th>' : '') + '<th scope="col">Other income</th><th scope="col">Bills</th><th scope="col">Health</th><th scope="col">Taxes</th>' + (anyOnce ? '<th scope="col">One-time cost</th>' : '') + '<th scope="col">From savings</th><th scope="col">Savings left</th><th scope="col">Short</th></tr></thead><tbody>' +
    v.rows.map(function (r) { return '<tr><td>' + r.age + '</td><td>' + m(r.pension) + '</td><td>' + m(r.ss) + '</td>' + (sp ? '<td>' + m(r.spouse) + '</td>' : '') + '<td>' + m(r.otherIncome) + '</td><td>' + m(r.bills) + '</td><td>' + m(r.health) + '</td><td>' + m(r.tax) + '</td>' + (anyOnce ? '<td>' + (r.once ? money(r.once) : '') + '</td>' : '') + '<td>' + m(r.draw) + '</td><td>' + money(r.balance) + '</td><td>' + (r.short > 12 ? m(r.short) : '') + '</td></tr>'; }).join('') + '</tbody>';
}

/* ---------- Save, open, calendar ---------- */
function download(name, type, text) {
  var url = URL.createObjectURL(new Blob([text], { type: type }));
  var a = document.createElement('a');
  a.href = url; a.download = name;
  document.body.append(a); a.click(); a.remove();
  setTimeout(function () { URL.revokeObjectURL(url); }, 1000);
}
function saveFile() {
  download('schools-out-plan.json', 'application/json', JSON.stringify({ app: 'schools-out-kentucky', version: 1, saved: new Date().toISOString(), data: state }, null, 2));
  dirty = false;
  showMessage('Plan downloaded as a JSON file. Keep it private: it contains your pay and retirement details.', 'ok');
}
function n(v, max) { return typeof v === 'number' && isFinite(v) && v >= 0 && v <= max; }
function validate(d) {
  if (!d || typeof d !== 'object') return null;
  ['rothBal', 'rothMonthly', 'otherBal', 'otherMonthly', 'b457Bal', 'b457Monthly', 'otherIncome', 'boughtYears', 'boughtCost', 'otherPension', 'sickDays', 'sickYears', 'startYear', 'wantAge', 'fasPast', 'goalLater', 'goalLaterAge', 'otherIncomeEnd', 'oop', 'ot1Amt', 'ot1Age', 'ot1Out', 'ot2Amt', 'ot2Age', 'ot2Out', 'ot3Amt', 'ot3Age', 'ot3Out'].forEach(function (f) { if (d[f] === undefined) d[f] = 0; });
  if (d.otherPensionAge === undefined) d.otherPensionAge = 65;
  var lim = { oop: 10000, ot1Amt: 100000000, ot1Age: 100, ot1Out: 1, ot2Amt: 100000000, ot2Age: 100, ot2Out: 1, ot3Amt: 100000000, ot3Age: 100, ot3Out: 1, boughtYears: 10, boughtCost: 10000000, otherPension: 100000, otherPensionAge: 80, rothBal: 100000000, rothMonthly: 100000, b457Bal: 100000000, b457Monthly: 100000, otherBal: 100000000, otherMonthly: 100000, otherIncome: 100000, sidePay: 1000000, age: 80, years: 50, salary: 5000000, raise: 20, localRate: 5, sickYears: 5, sickDays: 2000, startYear: 3000, wantAge: 75, fasPast: 5000000, balance: 10000000, teachHealth: 10000, stopAge: 85, claimAge: 70, ssYears: 45, ssAvg: 1000000, savings: 100000000, saveMonthly: 100000, goal: 100000, goalLater: 100000, goalLaterAge: 100, otherIncomeEnd: 100, inflation: 10, returnRate: 12, marketHealth: 10000, medicareOther: 10000 };
  for (var k in lim) if (!n(d[k], lim[k])) return null;
  if (d.age < 18 || d.claimAge < 62) return null;
  if (['single', 'hoh', 'joint', 'mfs'].indexOf(d.status) < 0 || ['1', '2', '3', '4'].indexOf(d.type) < 0 || typeof d.univ !== 'boolean' || COUNTIES.indexOf(d.county) < 0) return null;
  var out = { later: d.later === true, moved: d.moved === true, fromWizard: d.fromWizard === true, status: d.status, type: d.type, univ: d.univ, county: d.county, checks: {} };
  for (k in lim) out[k] = d[k];
  out.outKy = d.outKy === true;
  out.sickHow = ['credit', 'cash', 'unsure'].indexOf(d.sickHow) >= 0 ? d.sickHow : 'credit';
  out.pre83 = typeof d.pre83 === 'number' && d.pre83 >= 0 && d.pre83 <= 50 ? d.pre83 : -1;
  if (d.checks && typeof d.checks === 'object') Object.keys(d.checks).forEach(function (c) { if (typeof d.checks[c] === 'boolean' && c.length < 20) out.checks[c] = d.checks[c]; });
  var q = d.sp, spLim = { survCut: 50, survShare: 100, start: 2100, years: 50, salary: 5000000, raise: 20, ssYears: 45, age: 95, pay: 100000, stopAge: 95, pension: 100000, pensionAge: 95, pia: 10000, claimAge: 70, savings: 100000000, saveMonthly: 100000 };
  out.sp = { on: false, age: 0, pay: 0, stopAge: 0, pension: 0, pensionAge: 65, pia: 0, claimAge: 67, savings: 0, saveMonthly: 0, onTrs: false };
  if (q && typeof q === 'object') {
    for (k in spLim) if (q[k] !== undefined) { if (!n(q[k], spLim[k])) return null; out.sp[k] = q[k]; }
    out.sp.on = q.on === true; out.sp.onTrs = q.onTrs === true; out.sp.trs = q.trs === true;
  }
  return out;
}
function openFile(file) {
  var bad = function () { showMessage('That file isn\'t a valid School\'s Out plan, so it wasn\'t opened. Your numbers on this page haven\'t changed.', 'err'); };
  var reader = new FileReader();
  reader.onerror = bad;
  reader.onload = function () {
    var p, clean;
    try { p = JSON.parse(reader.result); } catch (e) { return bad(); }
    if (!p || (p.app !== 'schools-out-kentucky') || p.version !== 1) return bad();
    clean = validate(p.data);
    if (!clean) return bad();
    state = clean; state.fromWizard = true; isExample = false;
    setScreen('results');
    fillForm(); renderAll(); showPeriod('when', false); dirty = false;
    showMessage('Your saved plan is open.', 'ok');
  };
  reader.readAsText(file);
}
/* Keep the plan on this device so it survives leaving and coming back. */
/* Each copy of this file keeps its own plan, so a new download starts fresh. */
var STORE = 'schools-out-plan:' + location.pathname;
function autoSave() {
  if (isExample || !state.fromWizard || screen !== 'results') return;
  try { localStorage.setItem(STORE, JSON.stringify({ v: 1, data: state, plan: $('resultsView').dataset.plan })); } catch (e) { /* storage may be blocked */ }
}
function clearSaved() { try { localStorage.removeItem(STORE); } catch (e) { /* ignore */ } }
function restoreSaved() {
  try {
    var raw = localStorage.getItem(STORE); if (!raw) return false;
    var p = JSON.parse(raw), d = p && p.v === 1 ? validate(JSON.parse(JSON.stringify(p.data))) : null;
    if (!d || !d.fromWizard) { clearSaved(); return false; }
    state = d; isExample = false; dirty = false;
    var plan = 'open';
    $('resultsView').dataset.plan = plan; document.body.dataset.plan = plan;
    fillForm(); renderAll(); showPeriod('when', false); setScreen('welcome');
    $('startBtn').textContent = 'Continue my plan'; $('newBtn').hidden = false;
    return true;
  } catch (e) { return false; }
}
var PAGES = [['wizard', 'Your numbers'], ['results', 'Your answer']];
function goHome() {
  setScreen('welcome');
  var has = state.fromWizard && !isExample;
  $('startBtn').textContent = has ? 'Continue my plan' : 'Start my plan'; $('newBtn').hidden = !has;
}
var wizFrom = 'welcome';
function setScreen(name) {
  if (name === 'wizard' && screen !== 'wizard') wizFrom = screen;
  screen = name;
  document.body.dataset.screen = name;
  var sk = $('skipLink'); if (sk) { sk.href = name === 'results' ? '#results' : name === 'wizard' ? '#wizQ' : '#startBtn'; sk.textContent = name === 'results' ? 'Skip to your answer' : name === 'wizard' ? 'Skip to the questions' : 'Skip to the start button'; }
  document.body.dataset.has = state.fromWizard && !isExample ? '1' : '0';
  var ix = PAGES.findIndex(function (p) { return p[0] === name; });
  if (ix >= 0) {
    $('pgName').textContent = PAGES[ix][1];
    $('pgPrev').disabled = false; $('pgNext').disabled = ix === PAGES.length - 1;
    $('pgPrev').setAttribute('aria-label', ix > 0 ? 'Back to ' + PAGES[ix - 1][1] : 'Back to the front page');
    $('pgNext').setAttribute('aria-label', ix < PAGES.length - 1 ? 'Next: ' + PAGES[ix + 1][1] : 'No later page');
  }
  window.scrollTo({ top: 0, left: 0, behavior: 'instant' });
  if (name !== 'wizard') navSync();
}
/* The browser's Back and Forward buttons move between School's Out's own pages and question pages, instead of leaving the app. */
var navPopping = false;
function navKey() { return screen + (screen === 'wizard' ? ':' + wiz.step : ''); }
function navSync() {
  if (navPopping || !window.history || !history.pushState) return;
  var k = navKey(), cur = history.state && history.state.so;
  try { if (!cur) history.replaceState({ so: k }, ''); else if (cur !== k) history.pushState({ so: k }, ''); } catch (e) { /* history may be unavailable */ }
}
window.addEventListener('popstate', function (e) {
  var k = e.state && e.state.so; if (!k) return;
  navPopping = true;
  try {
    var parts = k.split(':'), to = parts[0];
    if (to === 'wizard') {
      if (screen !== 'wizard') { if (!wiz.fresh) wizFromState(); setScreen('wizard'); } else wizardKeep();
      var st = wizSteps(), step = +parts[1];
      wiz.step = st.indexOf(step) >= 0 ? step : st[0];
      renderWizard();
    } else if (to === 'results' && (state.fromWizard || isExample)) { setScreen('results'); focusAnswer(); }
    else goHome();
  } finally { navPopping = false; }
  try { history.replaceState({ so: navKey() }, ''); } catch (e2) { /* ignore */ }
});
var exampleFrom = null;
function loadExample(name) {
  var previous = dirty ? JSON.stringify(state) : null, wasExample = isExample;
  state = JSON.parse(JSON.stringify(EXAMPLES[name]));
  isExample = name !== 'blank';
  setScreen('results');
  $('resultsView').dataset.plan = 'open'; document.body.dataset.plan = 'open';
  fillForm(); renderAll();
  dirty = false;
  $('message').innerHTML = '';
  /* Unsaved numbers are kept aside, and the example banner offers a way back to them instead of a separate message. */
  if (previous && !wasExample) exampleFrom = { state: previous, wasExample: false };
  if (exampleFrom) { dirty = true; renderMode(); }
}

var BASE_PERIODS = [['when', 'When can I retire?', ['s-when']], ['enough', 'Will my money last?', ['s-enough']], ['health', 'Health', ['s-health']], ['ss', 'Social Security', ['s-ss']], ['work', 'Work after retiring', ['s-work']], ['family', 'My family', ['s-family']], ['road', 'Refund or pension?', ['s-road']], ['plan', 'Your action plan', ['s-plan']]];
var PERIODS = BASE_PERIODS.slice();
/* Sections follow the questions a teacher asks in order. For someone early in their career, refund or pension is a real choice, so it moves up. */
function orderSections(h) {
  var s = ready() ? retireAt(h, h.stopAge) : null, early = !!s && (!s.vested || h.years < 10);
  PERIODS = BASE_PERIODS.filter(function (p) { return p[0] !== 'road'; });
  PERIODS.splice(early ? 2 : PERIODS.length - 1, 0, BASE_PERIODS[6]);
  PERIODS.forEach(function (p) { var el = $(p[2][0]); if (el && el.parentNode === $('results')) $('results').insertBefore(el, $('s-how')); });
  $('periods').innerHTML = PERIODS.map(function (p, i) { return '<button type="button" data-period="' + p[0] + '"><b>' + (i + 1) + '</b>' + p[1] + '</button>'; }).join('');
}
function showPeriod(id, focus) {
  /* The full plan is one long page, like a set of numbered sections. These buttons jump to a section. */
  var ix = PERIODS.findIndex(function (p) { return p[0] === id; });
  if (id === 'when') renderAll();
  if (focus) {
    var h2 = $(PERIODS[ix][2][0]).querySelector('h2');
    h2.setAttribute('tabindex', '-1');
    h2.focus({ preventScroll: true });
    $(PERIODS[ix][2][0]).scrollIntoView({ block: 'start' });
  }
}

/* ---------- The question pages ---------- */
function newWiz(fresh) { return { step: 0, start: '', years: '', age: '', type: '', salary: '', county: 'Fayette', goal: '', fresh: !!fresh }; }
var wiz = newWiz(false);
var THIS_YEAR = new Date().getFullYear();
/* Account type from the fall the first school year began. */
function defaultPre83(start, years) { var y = parseInt(start, 10); if (!(y >= 1960) || y >= 1983) return 0; return Math.max(0, Math.min(parseFloat(years) || 0, 1983 - y)); }
/* Service before July 1983 is only possible for someone who started before 1983. */
function pre83Show() { var sy = parseInt($('wStart') ? $('wStart').value : wiz.start, 10), t = ($('wType') && $('wType').value) || (sy >= 1960 ? typeFromYear(sy) : ''); return t === '1' && sy >= 1960 && sy < 1983; }
function pre83Sync() { if ($('wPre83Wrap')) $('wPre83Wrap').hidden = !pre83Show(); }
function typeFromYear(y) { return y <= 2001 ? '1' : y <= 2007 ? '2' : y <= 2021 ? '3' : '4'; }
function wizFromState() {
  wiz.step = 0;
  if (!state.fromWizard || isExample) return;
  var s = state, w = wiz;
  w.univ = !!s.univ; w.status = s.status || 'single'; w.start = s.startYear || ''; w.years = s.years; w.age = s.age; w.salary = s.salary; w.goal = s.goal; w.raise = s.raise; w.want = s.wantAge || ''; w.yearsTyped = true; w.type = s.type; w.pre83 = s.pre83 >= 0 ? s.pre83 : ''; w.fas = s.fasPast || '';
  w.sav = s.savings || ''; w.savM = s.saveMonthly || ''; w.b457 = s.b457Bal || ''; w.b457M = s.b457Monthly || ''; w.roth = s.rothBal || ''; w.rothM = s.rothMonthly || ''; w.oth = s.otherBal || ''; w.othM = s.otherMonthly || ''; w.inc = s.otherIncome || ''; w.incEnd = s.otherIncomeEnd || ''; w.goal2 = s.goalLater || ''; w.goal2Age = s.goalLater ? s.goalLaterAge : ''; w.mkt = s.marketHealth === 1000 && !s.fromWizard ? '' : s.marketHealth;
  w.split = !!(s.b457Bal || s.b457Monthly || s.rothBal || s.rothMonthly || s.otherBal || s.otherMonthly); w.tot = w.split ? '' : w.sav; w.totM = w.split ? '' : w.savM; w.unallocated = ''; w.unallocatedM = '';
  w.sick = s.sickDays || ''; w.sickHow = s.sickHow || 'unsure'; w.ssY = s.ssYears || ''; w.ssA = s.ssAvg || ''; w.op = s.otherPension || ''; w.opAge = s.otherPension ? s.otherPensionAge : '';
  var q = s.sp || {};
  w.spAge = q.age || ''; w.spStop = q.stopAge || ''; w.spSalary = q.salary || (q.pay ? Math.round(q.pay * 12) : ''); w.spStart = q.start || ''; w.spYears = q.years || ''; w.spPia = q.pia || ''; w.spClaimAge = q.claimAge >= 62 && q.claimAge <= 70 ? q.claimAge : 67; w.spPen = q.pension || ''; w.spPenAge = q.pension && q.pensionAge ? q.pensionAge : ''; w.spSav = q.savings || ''; w.survCut = q.survCut || ''; w.survShare = q.survShare || ''; w.spTrs = !!q.onTrs;
  w.spKind = !!q.trs;
[1, 2, 3].forEach(function (k) { w['ot' + k + 'A'] = s['ot' + k + 'Amt'] || ''; w['ot' + k + 'G'] = s['ot' + k + 'Amt'] ? s['ot' + k + 'Age'] : ''; w['ot' + k + 'D'] = s['ot' + k + 'Amt'] && !s['ot' + k + 'Out'] ? '0' : '1'; });
  w.chk = { tax: s.status === 'hoh' || s.status === 'mfs', inc: !!s.otherIncome, ot: !!(s.ot1Amt || s.ot2Amt || s.ot3Amt), sick: !!s.sickDays, ss: !!s.ssYears, op: !!s.otherPension, sp: !!q.on, bl: s.goalLater > 0, out: !!s.outKy, buy: s.boughtYears > 0 };
  w.buyY = s.boughtYears || ''; w.buyC = s.boughtCost || '';
}
function wfield(label, id, val, o) {
  o = o || {};
  return '<label class="f"><span>' + label + '</span><span class="affix">' + (o.money === false ? '' : '<span class="pre">$</span>') + '<input id="' + id + '" type="number" min="0"' + (o.max ? ' max="' + o.max + '"' : '') + ' step="' + (o.step || 1) + '" value="' + esc(val === undefined ? '' : val) + '">' + (o.per ? '<span>' + o.per + '</span>' : '') + '</span>' + (o.hint ? '<small>' + o.hint + '</small>' : '') + '</label>';
}
/* An optional extra asked as a plain question. "No" is picked unless the plan already has an answer. */
function wq(key, question, inner) {
  var on = !!(wiz.chk && wiz.chk[key]), nm = 'wq-' + key;
  return '<div class="wq"><fieldset class="wq-row"><legend class="wq-t">' + question + '</legend><div class="wiz-row seg">' +
    '<label class="radio-card"><input type="radio" name="' + nm + '" value="0" data-wno="' + key + '"' + (on ? '' : ' checked') + '><strong>No</strong></label>' +
    '<label class="radio-card"><input type="radio" name="' + nm + '" value="1" data-wchk="' + key + '"' + (on ? ' checked' : '') + '><strong>Yes</strong></label></div></fieldset>' +
    '<div class="wiz-sub" id="wsub-' + key + '"' + (on ? '' : ' hidden') + '>' + inner + '</div></div>';
}
/* The same guess safe() makes when a spouse's Social Security is left blank, shown while they type so it can be corrected. */
function spSsGuess() {
  var box = $('spSsGuess'); if (!box) return;
  var age = parseFloat($('wSpAge').value) || 0, stop = parseFloat($('wSpStop').value) || age, pay = parseFloat($('wSpSalary').value) || 0;
  if ($('wSpPia').value !== '' || !(age >= 18) || !(pay > 0)) { box.textContent = 'Leave blank to estimate it.'; return; }
  var yrs = Math.min(45, Math.max(0, Math.min(40, age - 22)) + Math.max(0, stop - age));
  if (yrs < 10) { box.textContent = 'Left blank, none is counted, because that\'s under 10 years of work.'; return; }
  var e = []; for (var q = 0; q < Math.round(yrs); q++) e.push(pay);
  box.textContent = 'Left blank, we\'ll guess about ' + plain(piaFromEarnings(e)) + ' a month, as if they\'d worked since 22 at today\'s pay.';
}
document.addEventListener('input', function (e) { if (['wSpAge', 'wSpStop', 'wSpSalary', 'wSpPia'].indexOf(e.target.id) >= 0) spSsGuess(); });
function updateSpouseTrsHelp() {
  var el = $('wSpTrsHelp'); if (!el) return;
  var spouseAge = parseFloat(($('wSpAge') || {}).value), teacherAge = parseFloat(wiz.age), retirementAge = parseFloat(wiz.want);
  var when = Number.isFinite(retirementAge) ? retirementAge : NaN;
  var ageAtRetirement = spouseAge + (when - teacherAge);
  var msg = 'Starts when you retire. ';
  if (Number.isFinite(ageAtRetirement)) msg += ageAtRetirement < 65 ? 'Before they turn 65 it\'s about $' + Math.round(R.kehpSpouse).toLocaleString() + ' a month, and less after. ' : 'They\'d be on the Medicare plan by then. ';
  el.textContent = msg + 'If they use another plan, add its cost to your bills.';
}
document.addEventListener('input', function (e) { if (e.target.id === 'wSpAge') updateSpouseTrsHelp(); });

function wizSteps() { return wiz.chk && wiz.chk.sp ? [0, 1, 2, 3] : [0, 1, 3]; }
var WIZ_TITLES = ['About you', 'Your teaching career', 'Your spouse', 'Your money'];
/* "Step 2 of 3" with a bar under it: done pages filled, this page in yellow, pages to come in gray. */
var STEP_NAMES = ['About you', 'Your career', 'Your spouse', 'Your money'];
function wizProg(at, n) {
  var st = wizSteps(), seg = '', lab = '';
  for (var i = 0; i < n; i++) { var c = i < at ? 'done' : i === at ? 'now' : ''; seg += '<i class="' + c + '"></i>'; lab += '<b class="' + c + '">' + (STEP_NAMES[st[i]] || '') + '</b>'; }
  $('wizProgress').innerHTML = '<span class="sr-only">Step ' + (at + 1) + ' of ' + n + '</span><span class="wp-bar" aria-hidden="true">' + seg + '</span><span class="wp-lab" aria-hidden="true">' + lab + '</span>';
}
function renderWizard() {
  var w = wiz;
  if (!w.chk) w.chk = {};
  if (w.step === 2 && !w.chk.sp) w.step = 3;
  var st = wizSteps(), at = st.indexOf(w.step), last = at === st.length - 1;
  $('wizProgress').hidden = false;
  wizProg(at, st.length);
  $('wizErr').textContent = '';
  $('wizBack').textContent = at === 0 ? 'Cancel' : 'Back';
  var editing = isEditing();
  $('wizNext').textContent = !last ? 'Next' : editing ? 'Update my answer' : 'Show my answer';
  $('wizQ').textContent = WIZ_TITLES[w.step];
  $('pgName').textContent = '';
  $('pgPrev').setAttribute('aria-label', at === 0 ? 'Leave the questions' : 'Back: ' + WIZ_TITLES[st[at - 1]]);
  $('pgNext').setAttribute('aria-label', last ? 'Show my answer' : 'Next: ' + WIZ_TITLES[st[at + 1]]);
  if (w.step === 0) {
    $('wizBody').innerHTML = '<p class="wiz-who">This is for staff in the Teachers\' Retirement System (TRS): jobs that need a teaching certificate or a four-year degree. If you\'re not sure which pension you\'re in, ask your district\'s payroll office.</p><div class="wiz-fields wiz-sec">' +
      '<div class="wiz-pair"><label class="f"><span>Your age<span class="req" aria-hidden="true">*</span></span><input id="wAge" required type="number" min="18" max="80" step="1" value="' + esc(w.age) + '"></label><label class="f"><span>Desired retirement age <span class="opt-tag">(optional)</span></span><input id="wWant" type="number" min="18" max="75" step="1" value="' + esc(w.want || '') + '"><small>Leave blank to find the earliest age you can afford to retire.</small></label></div>' +
      '<fieldset class="wiz-checks"><legend>Are you married?<span class="req" aria-hidden="true">*</span></legend><div class="wiz-row seg">' + [[false, 'No'], [true, 'Yes']].map(function (o) {
        return '<label class="radio-card"><input type="radio" name="wMarried" required value="' + (o[0] ? '1' : '0') + '"' + (w.chk.sp === o[0] ? ' checked' : '') + '><strong>' + o[1] + '</strong></label>';
      }).join('') + '</div><small class="wiz-small">If yes, you\'ll add your spouse on a later page.</small></fieldset></div>';
  } else if (w.step === 1) {
    var tp = w.type || (parseInt(w.start, 10) >= 1960 ? typeFromYear(parseInt(w.start, 10)) : '');
    var typeOpen = !!(w.typeOpen || (w.type && parseInt(w.start, 10) >= 1960 && w.type !== typeFromYear(parseInt(w.start, 10))));
    var p83 = w.pre83 !== undefined && w.pre83 !== '' ? w.pre83 : defaultPre83(w.start, w.years);
    $('wizBody').innerHTML =
      '<details class="imp" id="impBox"><summary>Fill this in from my TRS annual statement</summary>' +
      '<p>TRS sends this statement each fall, and it\'s in Pathway. Choose the PDF, or open it, select all the text, copy it, and paste it here. It\'s read on this device only. Nothing is uploaded, and the statement isn\'t saved.</p>' +
      '<input type="file" id="impFile" accept=".pdf,.txt,application/pdf,text/plain" aria-label="TRS annual statement file">' +
      '<textarea id="impText" rows="3" placeholder="Or paste the text of your statement here" aria-label="Statement text"></textarea>' +
      '<button type="button" class="act" id="impGo">Read the pasted text</button><div id="impOut" role="status"></div></details>' +
      '<p class="req-note"><span class="req" aria-hidden="true">*</span> Required</p><div class="wiz-fields"><fieldset class="wiz-sec"><legend>Your TRS service</legend>' +
      '<fieldset class="wiz-checks"><legend>Where you work</legend>' + [[false, 'A public school district', ''], [true, 'A state university, in TRS', 'EKU, Kentucky State, Morehead State, Murray State or WKU.']].map(function (o) {
        return '<label class="radio-card"><input type="radio" name="wUniv" value="' + (o[0] ? '1' : '0') + '"' + (!!w.univ === o[0] ? ' checked' : '') + '><span><strong>' + o[1] + '</strong>' + o[2] + '</span></label>';
      }).join('') + '</fieldset>' +
      '<div class="wiz-pair"><label class="f"><span>Year you started teaching in Kentucky<span class="req" aria-hidden="true">*</span></span><input id="wStart" required type="number" min="1960" max="' + THIS_YEAR + '" step="1" placeholder="For example, 2004" value="' + esc(w.start || '') + '"><small>Your first school year in a TRS job, like 2004 for 2004&ndash;05.</small><button type="button" class="link-btn fas-toggle" id="wTypeToggle"' + (typeOpen ? ' hidden' : '') + '>My TRS account type is different</button></label></div>' +
      '<div id="wTypeWrap"' + (typeOpen ? '' : ' hidden') + '><label class="f"><span>TRS account type</span><select id="wType"><option value=""' + (tp ? '' : ' selected') + '>Fills in from your start year</option><option value="1"' + (tp === '1' ? ' selected' : '') + '>TRS 1: before July 2002</option><option value="2"' + (tp === '2' ? ' selected' : '') + '>TRS 2: July 2002 to June 2008</option><option value="3"' + (tp === '3' ? ' selected' : '') + '>TRS 3: July 2008 to 2021</option><option value="4"' + (tp === '4' ? ' selected' : '') + '>TRS 4: 2022 or later</option></select><small>It\'s on your TRS statement.</small></label><button type="button" class="link-btn fas-toggle" id="wTypeBack">Use my start year instead</button></div>' +
      '<div class="wiz-pair"><label class="f"><span>Years of service so far<span class="req" aria-hidden="true">*</span></span><input id="wYears" required type="number" min="0" max="50" step="0.5" value="' + esc(w.years) + '"><small>Filled in from your start year. Change it for breaks or part-time years.</small></label><div id="wPre83Wrap"' + (tp === '1' && parseInt(w.start, 10) < 1983 ? '' : ' hidden') + '><label class="f"><span>Years of service before July 1, 1983</span><input id="wPre83" type="number" min="0" max="30" step="0.5" value="' + esc(p83) + '"><small>These earn 2%, not 2.5%. Most have none.</small></label></div></div></fieldset>' +
      '<fieldset class="wiz-sec"><legend>Your pay</legend>' +
      '<div class="wiz-pair"><label class="f"><span>Salary this year, before taxes<span class="req" aria-hidden="true">*</span></span><span class="affix"><span class="pre">$</span><input id="wSalary" required type="number" min="1" step="500" value="' + esc(w.salary) + '"></span><small>Include extra-duty pay, like coaching or club sponsor stipends.</small></label>' +
      '<label class="f"><span>Yearly raise<span class="req" aria-hidden="true">*</span></span><span class="affix"><input id="wRaise" required type="number" min="0" max="10" step="any" value="' + esc(isFinite(parseFloat(w.raise)) ? w.raise : 2) + '"><span>% a year</span></span><small>2% is an average. Actual amounts vary by district.</small></label></div>' +
      '<div id="wFasArea"' + (parseFloat(w.years) >= 1 ? '' : ' hidden') + '><button type="button" class="link-btn fas-toggle" id="wFasToggle" aria-expanded="' + (w.fas ? 'true' : 'false') + '" aria-controls="wFasWrap">My pay jumped recently</button><div id="wFasWrap"' + (w.fas ? '' : ' hidden') + '>' +
      '<label class="f"><span>Average of your last 5 salaries <span class="opt-tag">(optional)</span></span><small style="margin:-2px 0 6px">Including this year. If you\'ve taught less than 5 years, average all of them.</small><span class="affix"><span class="pre">$</span><input id="wFas" type="number" min="0" step="500" value="' + esc(w.fas || '') + '"></span><small>Your TRS statement shows your salary history.</small></label></div></div></fieldset></div>';
  } else if (w.step === 2) {
    /* Just enough about your spouse to see what they add to the household. A spouse in TRS gets their pension worked out like yours. */
    var two = function (ss, trs) { return '<span class="sp-ss"' + (w.spKind ? ' hidden' : '') + '>' + ss + '</span><span class="sp-trs"' + (w.spKind ? '' : ' hidden') + '>' + trs + '</span>'; };
    $('wizBody').innerHTML = '' +
      '<p class="req-note"><span class="req" aria-hidden="true">*</span> Required</p><div class="wiz-fields"><fieldset class="wiz-sec"><legend>About them</legend>' +
      '<div class="wiz-pair">' + wfield('Their age<span class="req" aria-hidden="true">*</span>', 'wSpAge', w.spAge, { money: false, max: 95 }) + wfield('Age they\'ll stop working', 'wSpStop', w.spStop, { money: false, max: 95, hint: 'Leave blank only if they\'ve already stopped.' }) + '</div>' +
      '<div class="wiz-pair">' + wfield('Their pay, before taxes', 'wSpSalary', w.spSalary, { step: 500, per: 'a year' }) + wfield('Their savings, added up', 'wSpSav', w.spSav, { step: 500, hint: 'Accounts in their name only. Joint accounts go on your page, once.' }) + '</div>' +
      '</fieldset><fieldset class="wiz-sec"><legend>Work and pension</legend><fieldset class="wiz-checks"><legend>Are they also a Kentucky teacher in TRS?</legend><div class="wiz-row seg">' + [[false, 'No'], [true, 'Yes']].map(function (o) {
        return '<label class="radio-card"><input type="radio" name="wSpKind" value="' + (o[0] ? '1' : '0') + '"' + (!!w.spKind === o[0] ? ' checked' : '') + '><strong>' + o[1] + '</strong></label>';
      }).join('') + '</div></fieldset>' +
      '<div class="sp-trs"' + (w.spKind ? '' : ' hidden') + '><div class="wiz-pair">' +
        '<label class="f"><span>Year they started in TRS</span><input id="wSpStart" type="number" min="1960" max="' + THIS_YEAR + '" step="1" placeholder="For example, 2004" value="' + esc(w.spStart || '') + '"></label>' +
        '<label class="f"><span>Their years of service</span><input id="wSpYears" type="number" min="0" max="50" step="0.5" value="' + esc(w.spYears || '') + '"><small>Filled in from their start year.</small></label></div>' +
        '<small class="wiz-small">Their TRS pension is worked out from these and their pay. Already retired? Skip these and enter what TRS pays them under Their pension.</small></div>' +
      '<div class="wiz-pair">' + wfield('Their Social Security', 'wSpPia', w.spPia, { step: 10, per: 'a month', hint: two('At 67, from ssa.gov. <span id="spSsGuess">Leave blank to estimate it.</span>', 'Only from jobs outside teaching.') }) +
        wfield(two('Their pension', 'Their other pension'), 'wSpPen', w.spPen, { step: 10, per: 'a month', hint: two('Before taxes. Leave blank if none.', 'Leave their TRS pension out. It\'s worked out above. If they\'ve already retired, enter what TRS pays them.') }) + '</div>' +
      '</fieldset><fieldset class="wiz-sec"><legend>Social Security and health</legend><div class="wiz-pair">' + wfield('Age your spouse will start Social Security', 'wSpClaimAge', w.spClaimAge === undefined || w.spClaimAge === '' ? 67 : w.spClaimAge, { money: false, max: 70, hint: 'Choose 62 to 70. This can be later than when they stop working.' }) + '</div>' +
      '<div class="sp-ss"' + (w.spKind ? ' hidden' : '') + '><label class="check-line"><input type="checkbox" id="wSpTrs"' + (w.spTrs ? ' checked' : '') + '> Put them on my TRS health plan when I retire</label><small class="wiz-small" id="wSpTrsHelp">Starts when you retire. If they use another plan, add its cost to your bills.</small></div>' +
      '</fieldset><fieldset class="wiz-sec"><legend>If you die first <span class="opt-tag">(optional)</span></legend>' +
      '<div class="wiz-pair">' + wfield('Pension cut for a survivor option', 'wSurvCut', w.survCut, { money: false, max: 50, step: 'any', per: '%', hint: 'From your TRS estimate. Leave blank for no survivor option: the biggest check, which stops when you die.' }) + wfield('Share your spouse keeps', 'wSurvShare', w.survShare, { money: false, max: 100, step: 'any', per: '%', hint: 'From the same estimate.' }) + '</div></fieldset>' +
      '<small class="wiz-small sp-trs"' + (w.spKind ? '' : ' hidden') + '>Their TRS health plan is added for you. If they\'re already retired, add what they pay for it to your bills.</small>' +
      '</fieldset></div>';
    updateSpouseTrsHelp();
  } else {
    $('wizBody').innerHTML = (w.chk.sp ? '<p class="sp-intro">Enter household totals. Count joint savings only once.</p>' : '') + '<div class="wiz-fields">' +
      '<fieldset class="wiz-sec"><legend>What you spend</legend><label class="f"><span>' + (w.chk.sp ? 'Your household\'s monthly bills today' : 'Your monthly bills today') + '<span class="req" aria-hidden="true">*</span></span><span class="affix"><span class="pre">$</span><input id="wGoal" required type="number" min="1" step="50" value="' + esc(w.goal || '') + '"><span>a month</span></span><small>Everything you spend' + (w.chk.sp ? ' for both of you' : '') + ', except health insurance. We add that.</small></label></fieldset>' +
      '<fieldset class="wiz-sec"><legend>What you\'ve saved</legend><fieldset class="wiz-save"><legend class="sr-only">Account balances and contributions</legend>' +
      (w.split ? '<div class="wiz-pair">' + wfield('403(b), 401(k), or traditional IRA', 'wSav', w.sav, { step: 500, hint: 'Taxed when you take it out.' }) + wfield('You add', 'wSavM', w.savM, { step: 10, per: 'a month' }) + '</div>' +
      '<div class="wiz-pair">' + wfield('457(b)', 'w457', w.b457, { step: 500, hint: 'Taxed on withdrawal; special early-withdrawal rules apply.' }) + wfield('You add', 'w457M', w.b457M, { step: 10, per: 'a month' }) + '</div>' +
      '<div class="wiz-pair">' + wfield('Roth IRA or Roth 401(k)', 'wRoth', w.roth, { step: 500, hint: 'Tax-free when you take it out.' }) + wfield('You add', 'wRothM', w.rothM, { step: 10, per: 'a month' }) + '</div>' +
      '<div class="wiz-pair">' + wfield('Other savings', 'wOth', w.oth, { step: 500, hint: 'Bank or brokerage accounts.' + (w.chk.sp ? ' Joint accounts go here, once.' : '') }) + wfield('You add', 'wOthM', w.othM, { step: 10, per: 'a month' }) + '</div>' +
      '<p class="sav-unallocated" id="wUnallocated" aria-live="polite"></p>' +
      '<button type="button" class="link-btn sav-toggle" id="wSplit">Enter one total instead</button>'
      : '<div class="wiz-pair">' + wfield('Total account balance', 'wTot', w.tot, { step: 500, hint: (w.chk.sp ? 'Yours plus joint accounts, once. ' : '') + 'Not your TRS pension.' }) + wfield('Monthly contributions', 'wTotM', w.totM, { step: 10, per: 'a month', hint: 'Until you stop teaching.' }) + '</div>' +
      '<button type="button" class="link-btn sav-toggle" id="wSplit">Split by account type</button>') + '</fieldset></fieldset>' +
      '<fieldset class="wiz-sec wiz-extras"><legend>A few more questions</legend><p class="wiz-small" style="margin:0">Each one makes your answer more exact. If none apply, leave them on No.</p><div class="wq-list">' +
      wq('bl', 'Will your bills go down later, like when your mortgage is paid off?', '<div class="wiz-pair">' + wfield('Monthly expenses after the change', 'wGoal2', w.goal2, { step: 50, per: 'a month', hint: 'In today\'s dollars. For example, subtract a mortgage payment once it is paid off, even if that happens before retirement.' }) + wfield('Your age when expenses change', 'wGoal2Age', w.goal2Age, { money: false, max: 100 }) + '</div>') +
      wq('ss', 'Have you worked jobs that paid into Social Security?', '<div class="wiz-pair">' + wfield('Years in those jobs, in any state', 'wSsY', w.ssY, { money: false, max: 45 }) + wfield('Average yearly pay in them', 'wSsA', w.ssA, { step: 500 }) + '</div><small class="wiz-small">Check your benefit at ssa.gov/myaccount.</small>') +
      wq('op', 'Will you get a pension from another job, the military or another state?', '<div class="wiz-pair">' + wfield('Monthly pension', 'wOp', w.op, { step: 10, per: 'a month' }) + wfield('It starts at age', 'wOpAge', w.opAge, { money: false, max: 80 }) + '</div><small class="wiz-small">Another state, the military, or a past job. Leave other states\' years out of your Kentucky years.</small>') +
      wq('ot', 'Do you expect a big one-time cost or payment, like a new roof or an inheritance?', '<small class="wiz-small">Like selling a house, an inheritance, a wedding or a new roof. In today\'s dollars. Use up to three rows.</small>' + [1, 2, 3].map(function (k) {
        return '<div class="wiz-ot"><label class="f"><span>Amount</span><span class="affix"><span class="pre">$</span><input id="wOt' + k + 'A" type="number" min="0" step="500" value="' + esc(w['ot' + k + 'A'] || '') + '"></span></label><label class="f"><span>At age</span><input id="wOt' + k + 'G" type="number" min="18" max="95" step="1" value="' + esc(w['ot' + k + 'G'] || '') + '"></label><label class="f"><span>It</span><select id="wOt' + k + 'D"><option value="1"' + (w['ot' + k + 'D'] === '0' ? '' : ' selected') + '>goes out</option><option value="0"' + (w['ot' + k + 'D'] === '0' ? ' selected' : '') + '>comes in</option></select></label></div>';
      }).join('')) +
      wq('sick', 'Will you have unused sick days when you retire?', wfield('Unused sick days at retirement', 'wSick', w.sick, { money: false, max: 2000, per: 'days', hint: 'Your balance at the end of your last school year.' }) +
        '<fieldset class="wiz-checks"><legend>What does your district do with unused sick days at retirement?</legend>' +
        [['credit', 'Buys service credit from TRS', 'Every 185 days adds a year to your pension.'], ['cash', 'Pays part of them in cash', 'No years are added. School\'s Out doesn\'t count the cash.'], ['unsure', 'I\'m not sure', 'Counted as credit, and you\'ll see what it\'s worth so you can ask.']].map(function (o) {
          return '<label class="radio-card"><input type="radio" name="wSickHow" value="' + o[0] + '"' + ((w.sickHow || 'unsure') === o[0] ? ' checked' : '') + '><span><strong>' + o[1] + '</strong>' + o[2] + '</span></label>';
        }).join('') + '<small class="wiz-small">Ask your district if unsure.</small></fieldset>') +
      wq('inc', 'Will you work part-time or have other income after you retire?', '<div class="wiz-pair">' + wfield('Other monthly income', 'wInc', w.inc, { step: 50, per: 'a month', hint: 'Before taxes. Like rent, part-time work or substitute teaching.' }) + wfield('It stops at age', 'wIncEnd', w.incEnd, { money: false, max: 100, hint: 'Leave blank if it lasts for life.' }) + '</div>') +
      wq('buy', 'Did you teach in another state or serve in the military, and plan to buy those years from TRS?', '<div class="wiz-pair">' + wfield('Years you\'d buy', 'wBuyY', w.buyY, { money: false, max: 10, hint: 'Up to 1 for every 2 Kentucky years, and 10 at most.' }) + wfield('What TRS quoted', 'wBuyC', w.buyC, { step: 500, hint: 'Paid from your savings. Leave blank if you don\'t have a quote yet.' }) + '</div>') +
      wq('out', 'Will you move out of Kentucky?', '<small class="wiz-small">School\'s Out will leave out Kentucky income tax. It doesn\'t add your new state\'s taxes, so check those yourself. Your TRS pension and health coverage go with you.</small>') +
      '<div class="wq wq-tax"><div class="wq-row"><label class="wq-t" for="wStatus">How will you file taxes?</label><select id="wStatus">' + (w.chk.sp ? [['joint', 'Married, filing jointly'], ['mfs', 'Married, filing separately']] : [['single', 'Single'], ['hoh', 'Head of household']]).map(function (o) { return '<option value="' + o[0] + '"' + (w.status === o[0] ? ' selected' : '') + '>' + o[1] + '</option>'; }).join('') + '</select></div></div>' +
      '</div></fieldset>' +
      '</div>';
  }
  spSsGuess();
  markOptional();
  $('wizQ').focus();
  navSync();
}
/* Most questions are required, so only the optional ones get a label. A field is optional when its label has no required star. */
function markOptional() {
  $('wizBody').querySelectorAll('label.f').forEach(function (l) {
    if (l.closest('.wiz-sub') || l.querySelector('.req') || /optional/i.test(l.textContent) || l.closest('legend')) return;
    var inp = l.querySelector('input:not([type=checkbox]):not([type=radio]),select');
    if (!inp || l.closest('.wiz-sec') && /optional/i.test(l.closest('.wiz-sec').querySelector('legend').textContent)) return;
    var head = l.querySelector('span'); if (head && !head.querySelector('.opt-tag')) head.insertAdjacentHTML('beforeend', ' <span class="opt-tag">(optional)</span>');
  });
}
function wizardKeep() {
  var w = wiz, k = function (prop, id) { if ($(id)) w[prop] = $(id).value; }, r = function (name) { return document.querySelector('input[name=' + name + ']:checked'); };
  if (!w.chk) w.chk = {};
  var wm = r('wMarried'); if (wm) w.chk.sp = wm.value === '1';
  var wu = r('wUniv'); if (wu) w.univ = wu.value === '1';
  [['age', 'wAge'], ['want', 'wWant'], ['start', 'wStart'], ['years', 'wYears'], ['salary', 'wSalary'], ['raise', 'wRaise'], ['type', 'wType'], ['pre83', 'wPre83'], ['fas', 'wFas'],
   ['spAge', 'wSpAge'], ['spStop', 'wSpStop'], ['spStart', 'wSpStart'], ['spYears', 'wSpYears'], ['spSalary', 'wSpSalary'], ['spPia', 'wSpPia'], ['spClaimAge', 'wSpClaimAge'], ['spPen', 'wSpPen'], ['spPenAge', 'wSpPenAge'], ['spSav', 'wSpSav'], ['survCut', 'wSurvCut'], ['survShare', 'wSurvShare'], ['ot1A', 'wOt1A'], ['ot1G', 'wOt1G'], ['ot1D', 'wOt1D'], ['ot2A', 'wOt2A'], ['ot2G', 'wOt2G'], ['ot2D', 'wOt2D'], ['ot3A', 'wOt3A'], ['ot3G', 'wOt3G'], ['ot3D', 'wOt3D'],
   ['goal', 'wGoal'], ['status', 'wStatus'], ['sav', 'wSav'], ['savM', 'wSavM'], ['b457', 'w457'], ['b457M', 'w457M'], ['roth', 'wRoth'], ['rothM', 'wRothM'], ['oth', 'wOth'], ['othM', 'wOthM'], ['tot', 'wTot'], ['totM', 'wTotM'],
   ['inc', 'wInc'], ['incEnd', 'wIncEnd'], ['goal2', 'wGoal2'], ['goal2Age', 'wGoal2Age'], ['mkt', 'wMkt'], ['sick', 'wSick'], ['ssY', 'wSsY'], ['ssA', 'wSsA'], ['op', 'wOp'], ['opAge', 'wOpAge'], ['buyY', 'wBuyY'], ['buyC', 'wBuyC']].forEach(function (x) { k(x[0], x[1]); });
  if ($('wPre83Wrap') && $('wPre83Wrap').hidden) w.pre83 = '';
  var sk = r('wSpKind'); if (sk) w.spKind = sk.value === '1';
  var sh = r('wSickHow'); if (sh) w.sickHow = sh.value;
  if ($('wSpTrs')) w.spTrs = $('wSpTrs').checked;
}
function wizardRead() {
  var w = wiz, bad = function (m) { $('wizErr').textContent = m; return false; }, v;
  wizardKeep();
  var req = Array.prototype.slice.call(document.querySelectorAll('#wizBody input[required], #wizBody select[required]'));
  req.forEach(function (el) { el.removeAttribute('aria-invalid'); });
  var empty = req.filter(function (el) { return el.value.trim() === ''; });
  /* A start year in the future would leave years blank, so say what's actually wrong first. */
  if (w.step === 1 && parseInt(w.start, 10) > THIS_YEAR) { $('wStart').focus(); return bad('The year you started can\'t be later than ' + THIS_YEAR + '.'); }
  if (empty.length) { empty.forEach(function (el) { el.setAttribute('aria-invalid', 'true'); }); empty[0].focus(); var NAMES = { wAge: 'your age', wStart: 'the year you started teaching in Kentucky', wYears: 'your years of service', wSalary: 'your salary', wRaise: 'your yearly raise', wGoal: 'your monthly bills' }; return bad('Enter ' + (NAMES[empty[0].id] || 'the boxes marked with a red *') + '.'); }
  var a = parseInt(w.age, 10);
  if (w.step === 0) {
    if (!(a >= 18 && a <= 80)) return bad('Enter your age, between 18 and 80.');
    if (w.want !== '' && w.want !== undefined) { var wa = parseInt(w.want, 10); if (!(wa >= a && wa <= 75)) return bad('Enter the age you\'d like to retire, between ' + a + ' and 75, or leave it blank.'); w.want = wa; } else w.want = '';
    if (w.chk.sp !== true && w.chk.sp !== false) { var mq = document.querySelector('input[name=wMarried]'); if (mq) mq.focus(); return bad('Choose whether you\'re married.'); }
    return true;
  }
  if (w.step === 1) {
    v = parseInt(w.start, 10);
    if (!(v >= 1960 && v <= THIS_YEAR)) return bad('Enter the year you started teaching in Kentucky, like 2004.');
    if (!(parseFloat(w.years) > 0) || parseFloat(w.years) > 50) return bad('Enter your years of service, between 0.5 and 50.');
    if (parseFloat(w.years) > THIS_YEAR - v + 1) return bad('Your years of service can\'t be more than the years since you started in ' + v + '.');
    if (a - (THIS_YEAR - v) < 18) return bad('Check your start year against your age on the first page. You\'d have started teaching before age 18.');
    if (!(parseFloat(w.salary) > 0)) return bad('Enter your salary before taxes.');
    if (parseFloat(w.salary) < 5000) { $('wSalary').focus(); return bad('Enter your yearly salary, like 52000.'); }
    var rz = isFinite(parseFloat(w.raise)) ? Math.round(parseFloat(w.raise) * 100) / 100 : 2;
    if (!(rz >= 0 && rz <= 10)) return bad('Enter a yearly raise between 0% and 10%.');
    w.raise = rz;
    w.type = w.type || typeFromYear(v);
    var pz = parseFloat(w.pre83), fz = parseFloat(w.fas);
    if (w.fas !== '' && w.fas !== undefined && !(fz > 0)) return bad('Enter your salary average, or leave it blank.');
    if (w.type === '1' && w.pre83 !== '' && w.pre83 !== undefined && !(pz >= 0 && pz <= Math.min(30, parseFloat(w.years)))) return bad('Years before July 1983 must be between 0 and your years of service.');
    return true;
  }
  if (w.step === 2) {
    var spA = parseInt(w.spAge, 10); if (!(spA >= 18 && spA <= 95)) { $('wSpAge').focus(); return bad('Enter your spouse\'s age, between 18 and 95.'); }
    if (w.spStop !== '' && w.spStop !== undefined && !(parseInt(w.spStop, 10) >= spA && parseInt(w.spStop, 10) <= 95)) { $('wSpStop').focus(); return bad('Enter the age they\'ll stop working, or leave it blank if they already have.'); }
    if (n(w.spPen) > 0 && w.spPenAge !== '' && w.spPenAge !== undefined && (!Number.isInteger(Number(w.spPenAge)) || Number(w.spPenAge) < 18 || Number(w.spPenAge) > 95)) { $('wSpPenAge').focus(); return bad('Enter a pension start age between 18 and 95, or leave it blank.'); }
    var claim = Number(w.spClaimAge);
    if (w.spClaimAge === '' || !Number.isInteger(claim) || claim < 62 || claim > 70) { $('wSpClaimAge').focus(); return bad('Enter the age your spouse will start Social Security, from 62 to 70.'); }
    var sc = parseFloat(w.survCut), ssh = parseFloat(w.survShare);
    if (w.survCut !== '' && w.survCut !== undefined && !(sc >= 0 && sc <= 50)) { $('wSurvCut').focus(); return bad('Enter the pension cut as a percent between 0 and 50, or leave it blank.'); }
    if (sc > 0 && !(ssh > 0 && ssh <= 100)) { $('wSurvShare').focus(); return bad('Enter the share your spouse keeps, between 1 and 100.'); }
    if (!(sc > 0) && ssh > 0) { $('wSurvCut').focus(); return bad('Enter the pension cut that goes with that survivor share, or clear both boxes.'); }
    if (parseFloat(w.spSalary) > 0 && (w.spStop === '' || w.spStop === undefined)) { $('wSpStop').focus(); return bad('You entered their pay, so enter the age they\'ll stop working.'); }
    if (w.spKind && (w.spStart || w.spYears)) {
      var ss0 = parseInt(w.spStart, 10), sy0 = parseFloat(w.spYears);
      if (!(ss0 >= 1960 && ss0 <= THIS_YEAR)) { $('wSpStart').focus(); return bad('Enter the year your spouse started in TRS, or leave it blank.'); }
      if (!(sy0 > 0 && sy0 <= 50)) { $('wSpYears').focus(); return bad('Enter your spouse\'s years of service.'); }
      if (sy0 > THIS_YEAR - ss0 + 1) { $('wSpYears').focus(); return bad('Their years of service can\'t be more than the years since they started in ' + ss0 + '.'); }
      if (!(parseFloat(w.spSalary) > 0)) { $('wSpSalary').focus(); return bad('Enter your spouse\'s pay, so their TRS pension can be worked out.'); }
    }
    return true;
  }
  if (!(parseFloat(w.goal) > 0)) return bad('Enter your monthly bills today.');
  /* Catch a yearly amount typed into a monthly box, but let it through if they meant it. */
  if (parseFloat(w.salary) > 0 && parseFloat(w.goal) > 2 * parseFloat(w.salary) / 12 && w.goalOk !== w.goal) { w.goalOk = w.goal; $('wGoal').setAttribute('aria-invalid', 'true'); $('wGoal').focus(); return bad('That\'s more than twice your monthly pay. Bills should be per month, not per year. If ' + plain(parseFloat(w.goal)) + ' a month is right, choose the button again.'); }
  if (w.chk.bl) { var g2 = parseFloat(w.goal2), g2a = parseInt(w.goal2Age, 10); if (!(g2 > 0)) return bad('Enter your monthly bills after the change, or pick No.'); if (!(g2a > parseInt(w.age, 10) && g2a <= 100)) return bad('Enter the age your bills change. It should be after your age now.'); }
  if (w.chk.inc && parseFloat(w.inc) > 0 && w.incEnd !== '' && w.incEnd !== undefined && !(parseInt(w.incEnd, 10) > parseInt(w.age, 10))) return bad('Enter the age your other income stops, or leave it blank if it lasts for life.');
  if (w.chk.sp && w.status !== 'joint' && w.status !== 'mfs') return bad('You added your spouse, so choose a married filing status under How you file taxes.');
  if (w.chk.ot) for (var ok = 1; ok <= 3; ok++) { if (parseFloat(w['ot' + ok + 'A']) > 0) { var og = parseInt(w['ot' + ok + 'G'], 10); if (!(og >= parseInt(w.age, 10) && og <= 95)) { if ($('wOt' + ok + 'G')) $('wOt' + ok + 'G').focus(); return bad('Enter the age for that one-time amount, from your age now to 95.'); } } }
  if (w.chk.buy && !(parseFloat(w.buyY) >= 1)) return bad('Enter how many years you\'d buy, or pick No.');
  if (w.chk.op && parseFloat(w.op) > 0) { var oa = parseInt(w.opAge, 10); if (!(oa >= 40 && oa <= 80)) return bad('Enter the age your other pension starts, between 40 and 80.'); }
  return true;
}
/* Apply the money step to a plan. */
function applyWizMoney(d) {
  var w = wiz, n = function (x) { return Math.max(0, parseFloat(x) || 0); };
  if (!w.split) { d.savings = n(w.tot); d.saveMonthly = n(w.totM); d.b457Bal = 0; d.b457Monthly = 0; d.rothBal = 0; d.rothMonthly = 0; d.otherBal = 0; d.otherMonthly = 0; }
  else { d.savings = n(w.sav); d.saveMonthly = n(w.savM); d.b457Bal = n(w.b457); d.b457Monthly = n(w.b457M); d.rothBal = n(w.roth); d.rothMonthly = n(w.rothM); d.otherBal = n(w.oth) + Math.max(0, n(w.unallocated) - n(w.sav) - n(w.b457) - n(w.roth) - n(w.oth)); d.otherMonthly = n(w.othM) + Math.max(0, n(w.unallocatedM) - n(w.savM) - n(w.b457M) - n(w.rothM) - n(w.othM)); }
  d.otherIncome = w.chk.inc ? n(w.inc) : 0; d.otherIncomeEnd = d.otherIncome > 0 ? Math.min(100, Math.round(n(w.incEnd))) : 0;
  d.goalLater = w.chk.bl ? Math.min(100000, Math.round(n(w.goal2))) : 0; d.goalLaterAge = d.goalLater > 0 ? Math.min(100, Math.round(n(w.goal2Age))) : 0;
  d.outKy = !!w.chk.out;
  d.boughtYears = w.chk.buy ? Math.min(10, Math.round(n(w.buyY))) : 0; d.boughtCost = d.boughtYears > 0 ? Math.min(10000000, n(w.buyC)) : 0;
  d.oop = 0; // Out-of-pocket healthcare spending is included in monthly bills.
  [1, 2, 3].forEach(function (k) { var on = w.chk.ot && n(w['ot' + k + 'A']) > 0; d['ot' + k + 'Amt'] = on ? Math.min(100000000, n(w['ot' + k + 'A'])) : 0; d['ot' + k + 'Age'] = on ? Math.round(n(w['ot' + k + 'G'])) : 0; d['ot' + k + 'Out'] = on && w['ot' + k + 'D'] === '0' ? 0 : on ? 1 : 0; });
  // Outside-coverage premiums are adjusted on the results page, not in the questionnaire.
  d.sickDays = w.chk.sick ? Math.min(2000, n(w.sick)) : 0;
  d.sickHow = w.chk.sick ? (w.sickHow || 'unsure') : 'credit';
  d.ssYears = w.chk.ss ? Math.min(45, n(w.ssY)) : 0; d.ssAvg = w.chk.ss ? n(w.ssA) : 0;
  d.otherPension = w.chk.op ? n(w.op) : 0; d.otherPensionAge = w.chk.op && n(w.opAge) ? n(w.opAge) : 65;
  d.later = d.ssYears > 0; d.moved = d.otherPension > 0;
  d.status = w.status || 'single';
  var mar = d.status === 'joint' || d.status === 'mfs';
  if (w.chk.sp && !mar) d.status = 'joint'; else if (!w.chk.sp && mar) d.status = 'single';
  var spTrsIn = w.spKind && n(w.spStart) >= 1960 && n(w.spYears) > 0;
  var was = d.sp && d.sp.on ? d.sp : {};
  d.sp = w.chk.sp ? { on: true, age: Math.round(n(w.spAge)), pay: n(w.spSalary) / 12, salary: n(w.spSalary), start: spTrsIn ? Math.round(n(w.spStart)) : 0, years: spTrsIn ? n(w.spYears) : 0, raise: 2, stopAge: Math.round(n(w.spStop)), pension: n(w.spPen), pensionAge: n(w.spPen) > 0 && n(w.spPenAge) ? Math.round(n(w.spPenAge)) : Math.max(Math.round(n(w.spAge)), Math.round(n(w.spStop))), pia: Math.min(10000, n(w.spPia)), ssYears: was.ssYears || 0, claimAge: Math.round(n(w.spClaimAge)), savings: n(w.spSav), saveMonthly: was.saveMonthly || 0, survCut: Math.min(50, n(w.survCut)), survShare: n(w.survCut) > 0 ? Math.min(100, n(w.survShare)) : 0, onTrs: !!w.spTrs && !w.spKind, trs: !!w.spKind }
    : { on: false, age: 0, pay: 0, stopAge: 0, pension: 0, pensionAge: 65, pia: 0, claimAge: 67, savings: 0, saveMonthly: 0, onTrs: false, trs: false };
}
function wizardFinish() {
  var w = wiz;
  if (wiz.fresh) { clearSaved(); wiz.fresh = false; }
  else if (state.fromWizard && !isExample) {
    state.startYear = parseInt(w.start, 10); state.years = parseFloat(w.years); state.age = parseInt(w.age, 10);
    state.salary = parseFloat(w.salary); state.goal = Math.round(parseFloat(w.goal)); state.type = w.type; state.raise = +w.raise;
    state.pre83 = w.type === '1' && w.pre83 !== '' ? parseFloat(w.pre83) : -1;
    state.fasPast = parseFloat(w.fas) > 0 ? parseFloat(w.fas) : 0;
    if (w.balance) state.balance = w.balance;
    state.univ = w.univ === true;
    var f2 = firstFullRetireAge(safe());
    state.wantAge = w.want || 0;
    if (w.want) state.stopAge = w.want;
    else if (state.stopAge < state.age) state.stopAge = f2 === null ? 67 : Math.max(f2, state.age);
    applyWizMoney(state);
    if (!w.want) { var sa2 = firstSafeAge(safe()); if (sa2 !== null) state.stopAge = sa2; }
    dirty = true; setScreen('results'); fillForm(); renderAll(); window.scrollTo({ top: 0, left: 0, behavior: 'instant' }); focusAnswer(); return;
  }
  var d = JSON.parse(JSON.stringify(EXAMPLES.blank));
  d.age = parseInt(w.age, 10); d.years = parseFloat(w.years); d.type = w.type; d.startYear = parseInt(w.start, 10); d.salary = parseFloat(w.salary); d.raise = +w.raise; d.pre83 = w.type === '1' && w.pre83 !== '' ? parseFloat(w.pre83) : -1; d.fasPast = parseFloat(w.fas) > 0 ? parseFloat(w.fas) : 0;
  d.univ = w.univ === true;
  if (w.balance) d.balance = w.balance;
  d.county = w.county; d.localRate = JOB_TAX[w.county] || 0; d.teachHealth = 60; d.saveMonthly = 0; d.goal = 0;
  var full = firstFullRetireAge(d);
  d.stopAge = w.want ? w.want : full === null ? 67 : Math.max(full, Math.min(55, d.age + 1));
  d.wantAge = w.want || 0;
  d.goal = Math.round(parseFloat(w.goal));
  d.savings = 0; d.saveMonthly = 0; d.rothBal = 0; d.rothMonthly = 0; d.otherBal = 0; d.otherMonthly = 0; d.otherIncome = 0; d.ssYears = 0; d.ssAvg = 0;
  d.later = false; d.moved = false; d.otherPension = 0; d.otherPensionAge = 65; d.boughtYears = 0; d.boughtCost = 0;
  applyWizMoney(d);
  d.fromWizard = true;
  state = d; isExample = false; dirty = true;
  if (!w.want) { var sa = firstSafeAge(safe()); if (sa !== null) state.stopAge = sa; }
  setScreen('results');
  $('resultsView').dataset.plan = 'open';
  document.body.dataset.plan = 'open';
  fillForm(); renderAll(); showPeriod('when', false);
  window.scrollTo({ top: 0, left: 0, behavior: 'instant' });
  focusAnswer();
}
/* After the last question, keyboard and screen reader users land on the answer. */
function focusAnswer() { var hd = document.querySelector('#boardText h1'); if (hd) { hd.tabIndex = -1; hd.focus({ preventScroll: true }); } }

/* ---------- Example on the front page ---------- */
function renderExampleCard() {
  /* Run the made-up teacher through the same math as a real plan, so the card always matches "See this teacher's plan".
     Each bar shows, year by year, whether the pension pays the bills, savings fill the gap, or neither does. */
  var keep = state; state = JSON.parse(JSON.stringify(EXAMPLES.year26));
  var h = safe(); state = keep;
  var lo = h.age, span = LAST_AGE + 1 - lo, pct = function (x) { return ((x - lo) / span * 100).toFixed(2); };
  var row = function (a) {
    var r = retireAt(h, a), s = survive(h, a), more = a - h.age, segs = [], cur = null;
    s.rows.forEach(function (y) {
      var k = y.short > 1 ? '' : y.draw > 1 ? 'sav' : 'pen';
      if (cur && cur.k === k) cur.to = y.age + 1; else segs.push(cur = { k: k, from: y.age, to: y.age + 1 });
    });
    /* A one-year blip between two runs of the same kind (like the year Medicare starts) is drawn as part of them, to keep the bar easy to read. */
    for (var q = 1; q < segs.length - 1; q++) if (segs[q].to - segs[q].from === 1 && segs[q - 1].k === segs[q + 1].k) { segs[q - 1].to = segs[q + 1].to; segs.splice(q, 2); q--; }
    var what = more === 0 ? 'Stop teaching now' : 'Teach ' + more + ' more year' + (more === 1 ? '' : 's');
    var sub = r.startAge > a ? 'No pension until ' + r.startAge : '';
    var out = s.lasts ? 'Covered past ' + LAST_AGE : 'Runs short at ' + s.firstShort;
    var bar = '<u style="left:' + pct(a) + '%"></u>' + segs.filter(function (g) { return g.k; }).map(function (g) { return '<i class="' + g.k + '" style="left:' + pct(g.from) + '%;width:' + (g.to - g.from) / span * 100 + '%"></i>'; }).join('') +
      (s.lasts ? '' : '<b class="cut" style="left:' + pct(s.firstShort) + '%"></b>');
    return { ok: s.lasts, html: '<div class="exr-top"><span>' + what + '</span><b>' + out + '</b></div><div class="exr-bar">' + bar + '</div>' + (sub ? '<small>' + sub + '</small>' : '') };
  };
  var rows = [row(h.age), row(h.age + 1)], a = h.age + 2;
  if (!rows[1].ok) { while (a < 70 && !survive(h, a).lasts) a++; rows.push(row(a)); }
  $('exH').textContent = 'Can the pension pay the bills?';
  $('exSub').textContent = 'A teacher, age ' + h.age + ', with ' + h.years + ' years of service and ' + plain(h.goal) + ' a month in bills';
  $('exRows').innerHTML = rows.map(function (r) { return '<li class="' + (r.ok ? 'ex-ok' : 'ex-no') + '">' + r.html + '</li>'; }).join('') +
    '<li class="exr-axis" aria-hidden="true">' + [lo, 65, 80, LAST_AGE].filter(function (x, i, arr) { return x >= lo && x <= LAST_AGE && (i === 0 || x - arr[i - 1] >= 8 || x === LAST_AGE); }).map(function (x) { return '<span style="left:' + (x === LAST_AGE ? 100 : pct(x)) + '%' + (x === lo ? ';transform:none' : x === LAST_AGE ? ';transform:translateX(-100%)' : '') + '">' + (x === lo ? 'Age ' : '') + x + '</span>'; }).join('') + '</li>';
  $('exNote').innerHTML = '<span class="key"><i class="pen"></i>Pension alone</span><span class="key"><i class="sav"></i>Savings needed too</span>';
}

/* ---------- PDF of the whole plan ----------
   Written straight to a PDF file with the two built-in Times fonts, so it needs no print dialog and no library. */
var PDFW = { r: '278,278,355,556,556,889,667,191,333,333,389,584,278,333,278,278,556,556,556,556,556,556,556,556,556,556,278,278,584,584,584,556,1015,667,667,722,722,667,611,778,722,278,500,667,556,833,722,778,667,778,722,667,611,722,667,944,667,667,611,278,278,278,469,556,333,556,556,500,556,556,278,556,556,222,222,500,222,833,556,556,556,556,333,500,278,556,500,722,500,500,500,334,260,334,584,556,556,556,222,556,333,1000,556,556,333,1000,667,333,1000,556,611,556,556,222,222,333,333,350,556,1000,333,1000,500,333,944,556,500,667,278,333,556,556,556,556,260,556,333,737,370,556,584,333,737,333,400,584,556,556,333,556,537,278,333,556,365,556,834,834,834,611,667,667,667,667,667,667,1000,722,667,667,667,667,278,278,278,278,722,722,778,778,778,778,778,584,778,722,722,722,722,667,667,611,556,556,556,556,556,556,889,500,556,556,556,556,278,278,278,278,556,556,556,556,556,556,556,584,611,556,556,556,556,500,556,500'.split(','), b: '278,333,474,556,556,889,722,238,333,333,389,584,278,333,278,278,556,556,556,556,556,556,556,556,556,556,333,333,584,584,584,611,975,722,722,722,722,667,611,778,722,278,556,722,611,833,722,778,667,778,722,667,611,722,667,944,667,667,611,333,278,333,584,556,333,556,611,556,611,556,333,611,611,278,278,556,278,889,611,611,611,611,389,556,333,611,556,778,556,556,500,389,280,389,584,556,556,556,278,556,500,1000,556,556,333,1000,667,333,1000,556,611,556,556,278,278,500,500,350,556,1000,333,1000,556,333,944,556,500,667,278,333,556,556,556,556,280,556,333,737,370,556,584,333,737,333,400,584,556,556,333,611,556,278,333,556,365,556,834,834,834,611,722,722,722,722,722,722,1000,722,667,667,667,667,278,278,278,278,722,722,778,778,778,778,778,584,778,722,722,722,722,667,667,611,556,556,556,556,556,556,889,556,556,556,556,556,278,278,278,278,611,611,611,611,611,611,611,584,611,611,611,611,611,556,611,556'.split(',') };
function pdfDoc() {
  var W = 612, H = 792, M = 54, pages = [], cur = [], y = H - M;
  var map = { '‘': 145, '’': 146, '“': 147, '”': 148, '•': 149, '–': 150, '—': 151, '−': 45, ' ': 32, '≥': 62, '≤': 60 };
  var codes = function (t) { var out = []; for (var i = 0; i < t.length; i++) { var c = map[t[i]] || t.charCodeAt(i); out.push(c > 255 || c < 32 ? 63 : c); } return out; };
  var width = function (t, bold, size) { var w = 0, tab = PDFW[bold ? 'b' : 'r']; codes(t).forEach(function (c) { w += +tab[c - 32] || 500; }); return w / 1000 * size; };
  var lit = function (t) { return '(' + codes(t).map(function (c) { return c === 40 || c === 41 || c === 92 ? '\\' + String.fromCharCode(c) : c > 126 ? '\\' + c.toString(8) : String.fromCharCode(c); }).join('') + ')'; };
  var put = function (x, yy, t, bold, size) { cur.push('BT /' + (bold ? 'F2' : 'F1') + ' ' + size + ' Tf ' + x.toFixed(1) + ' ' + yy.toFixed(1) + ' Td ' + lit(t) + ' Tj ET'); };
  var newPage = function () { pages.push(cur); cur = []; y = H - M; };
  var room = function (h) { if (y - h < M + 14) newPage(); };
  var wrap = function (t, bold, size, maxW) {
    var lines = [], line = '';
    String(t).split(/\s+/).forEach(function (word) {
      var tryLine = line ? line + ' ' + word : word;
      if (line && width(tryLine, bold, size) > maxW) { lines.push(line); line = word; } else line = tryLine;
    });
    if (line) lines.push(line);
    return lines;
  };
  var doc = {
    para: function (t, o) {
      o = o || {}; if (!t) return;
      var size = o.size || 10.5, lead = size * 1.36, x = M + (o.indent || 0);
      wrap(t, o.bold, size, W - M - x).forEach(function (l) { room(lead); y -= lead; put(x, y, l, o.bold, size); });
      y -= o.after === undefined ? 4 : o.after;
    },
    heading: function (t, level) {
      var size = level === 1 ? 21 : level === 2 ? 14.5 : 11.5;
      room(size * 3.2); y -= level === 1 ? 0 : level === 2 ? 12 : 6;
      doc.para(t, { bold: true, size: size, after: 2 });
      if (level < 3) { cur.push('0.7 w ' + M + ' ' + (y - 2).toFixed(1) + ' m ' + (W - M) + ' ' + (y - 2).toFixed(1) + ' l S'); y -= 7; }
    },
    table: function (rows, hasHead) {
      rows = rows.filter(function (r) { return r.length; }); if (!rows.length) return;
      var size = 9, lead = 11.6, pad = 5, n = Math.max.apply(null, rows.map(function (r) { return r.length; })), full = W - 2 * M, nat = [];
      for (var c = 0; c < n; c++) nat.push(Math.min(full * .62, Math.max.apply(null, rows.map(function (r, i) { return width(r[c] || '', hasHead && i === 0 || c === 0, size); })) + 2 * pad));
      var sum = nat.reduce(function (a, b) { return a + b; }, 0), cw = nat.map(function (w) { return sum > full ? w * full / sum : w; });
      rows.forEach(function (r, i) {
        var bold = hasHead && i === 0, cells = [], lines = 1;
        for (var c = 0; c < n; c++) { cells.push(wrap(r[c] || '', bold || c === 0 && n > 2, size, cw[c] - 2 * pad)); lines = Math.max(lines, cells[c].length); }
        var h = lines * lead + 5; room(h);
        var x = M;
        cells.forEach(function (ls, c) { ls.forEach(function (l, k) { put(x + pad, y - lead * (k + 1), l, bold || c === 0 && n > 2, size); }); x += cw[c]; });
        y -= h;
        cur.push((bold ? '0.7' : '0.3') + ' w ' + M + ' ' + (y + 1).toFixed(1) + ' m ' + (M + Math.min(full, sum)).toFixed(1) + ' ' + (y + 1).toFixed(1) + ' l S');
      });
      y -= 6;
    },
    finish: function () {
      pages.push(cur);
      var objs = ['<< /Type /Catalog /Pages 2 0 R >>', '', '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>', '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>'], kids = [];
      pages.forEach(function (ops, i) {
        var body = ops.concat(['BT /F1 8.5 Tf ' + M + ' 34 Td ' + lit('School\'s Out. Estimates for educational use, not advice. Page ' + (i + 1) + ' of ' + pages.length) + ' Tj ET']).join('\n');
        objs.push('<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ' + W + ' ' + H + '] /Resources << /Font << /F1 3 0 R /F2 4 0 R >> >> /Contents ' + (objs.length + 2) + ' 0 R >>');
        kids.push(objs.length + ' 0 R');
        objs.push('<< /Length ' + body.length + ' >>\nstream\n' + body + '\nendstream');
      });
      objs[1] = '<< /Type /Pages /Kids [' + kids.join(' ') + '] /Count ' + pages.length + ' >>';
      var out = '%PDF-1.4\n', offs = [];
      objs.forEach(function (o, i) { offs.push(out.length); out += (i + 1) + ' 0 obj\n' + o + '\nendobj\n'; });
      var xref = out.length;
      out += 'xref\n0 ' + (objs.length + 1) + '\n0000000000 65535 f \n' + offs.map(function (o) { return ('0000000000' + o).slice(-10) + ' 00000 n \n'; }).join('');
      return out + 'trailer\n<< /Size ' + (objs.length + 1) + ' /Root 1 0 R >>\nstartxref\n' + xref + '\n%%EOF\n';
    }
  };
  return doc;
}
/* Turn what's on the page into PDF text, so the PDF always matches the screen. */
function pdfClean(t) { return t.replace(/\s+/g, ' ').replace(/ ([.,;:%)])/g, '$1').replace(/\( /g, '(').replace(/\$ /g, '$').trim(); }
function pdfTxt(el) {
  var out = '';
  el.childNodes.forEach(function (nd) {
    if (nd.nodeType === 3) out += nd.nodeValue;
    else if (nd.nodeType === 1 && !nd.hidden && (nd.matches('.link-btn') || !nd.matches('button,input,select,textarea,script,style,svg'))) out += ' ' + pdfTxt(nd) + ' ';
  });
  return out;
}
var PDF_BLOCK = ['DIV', 'P', 'UL', 'OL', 'TABLE', 'H1', 'H2', 'H3', 'DL', 'SECTION', 'BLOCKQUOTE', 'svg', 'DETAILS'];
function pdfWalk(el, doc) {
  if (el.nodeType !== 1 || el.hidden || el.matches('button,input,select,textarea,script,style,summary,details:not(.in-pdf),label.f,.slide,.no-pdf,.ac-key,.rb-axis,.tray,.inline-f,.lg-bar,.try>label')) return;
  var tag = el.tagName;
  if (tag === 'svg') { var lab = el.getAttribute('aria-label'); if (lab) doc.para('Chart: ' + lab.replace(/\.+$/, '') + '.', { size: 9.5 }); return; }
  if (el.matches('.ss-t')) { var sm = el.querySelectorAll('small'); return doc.para(pdfClean(pdfTxt(sm[0])) + ': ' + pdfClean(pdfTxt(el.querySelector('strong'))) + (sm[1] && pdfTxt(sm[1]).trim() ? '. ' + pdfClean(pdfTxt(sm[1])) : ''), { after: 3 }); }
  if (el.matches('.rb')) return doc.para(pdfClean(pdfTxt(el.querySelector('.rb-l'))) + ': ' + pdfClean(pdfTxt(el.querySelector('.rb-o b'))).toLowerCase().replace(/^past/, 'lasts past').replace(/^to /, 'lasts to '), { after: 3 });
  if (el.id === 'rcGrade') return doc.para('Overall grade: ' + pdfClean(pdfTxt(el)), { bold: true, size: 12 });
  if (/^H[1-3]$/.test(tag)) return doc.heading(pdfClean(pdfTxt(el)).replace(/^\d\s+/, ''), tag === 'H3' ? 3 : 2);
  if (tag === 'TABLE') return doc.table([].map.call(el.rows, function (r) { return [].map.call(r.cells, function (c) { return pdfClean(pdfTxt(c)); }); }), !!el.tHead);
  if (tag === 'UL' || tag === 'OL') {
    [].forEach.call(el.children, function (li, i) {
      if (li.hidden) return;
      var cb = li.querySelector('input[type=checkbox]');
      doc.para((cb ? (cb.checked ? '[x] ' : '[  ] ') : tag === 'OL' && !el.closest('.miles') ? (i + 1) + '. ' : '• ') + pdfClean(pdfTxt(li)), { indent: 10, after: 2 });
    });
    return;
  }
  if (tag === 'DL') {
    [].forEach.call(el.children, function (c) {
      if (c.tagName === 'DT') doc.para(pdfClean(pdfTxt(c)), { bold: true, after: 0 });
      else doc.para((c.querySelector('.blank') ? '____________________ ' : '') + pdfClean(pdfTxt(c)), { indent: 10 });
    });
    return;
  }
  var hasBlock = [].some.call(el.children, function (c) { return PDF_BLOCK.indexOf(c.tagName) >= 0; });
  if (!hasBlock) {
    var t = pdfClean(pdfTxt(el));
    return doc.para(t, { bold: el.matches('.lg-verdict,.bigline,.lg-top'), size: el.matches('.lg-foot,.note,.lg-math') ? 9.5 : undefined });
  }
  var run = '';
  var flush = function () { var t = pdfClean(run); if (t) doc.para(t); run = ''; };
  el.childNodes.forEach(function (nd) {
    if (nd.nodeType === 3) run += nd.nodeValue;
    else if (nd.nodeType === 1 && PDF_BLOCK.indexOf(nd.tagName) >= 0) { flush(); pdfWalk(nd, doc); }
    else if (nd.nodeType === 1 && !nd.hidden && (nd.matches('.link-btn') || !nd.matches('button,input,select,textarea,script,style,summary,label.f'))) run += ' ' + pdfTxt(nd) + ' ';
  });
  flush();
}
function makePdf() {
  if (!ready()) return showMessage('Enter your numbers first, then download the PDF.', 'err');
  var st = state, doc = pdfDoc(), row = function (a, b) { return [a, b]; }, per = function (v) { return plain(v) + ' a month'; };
  doc.heading('School\'s Out: my retirement plan', 1);
  doc.para('Made ' + new Date().toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }) + (isExample ? '. This is a made-up teacher, not a real plan.' : '.') + ' These are estimates for educational use, not financial, tax, legal or benefits advice. Only the Teachers\' Retirement System of Kentucky can give official numbers.', { size: 9.5 });
  ['boardText', 'answerSub', 'reportCard'].concat(PERIODS.map(function (p) { return p[2][0]; })).forEach(function (id) { pdfWalk($(id), doc); });
  doc.heading('Questions to ask TRS', 2);
  passQuestions(st, retireAt(safe(), st.stopAge)).forEach(function (q, i) { doc.para((i + 1) + '. ' + q, { indent: 10, after: 2 }); });
  doc.heading('The numbers this plan uses', 2);
  var rows = [row('TRS account', 'TRS ' + st.type + (st.univ ? ', university' : '') + (st.startYear ? ', started teaching in ' + st.startYear : '')), row('Age now', String(st.age)), row('Years of service now', String(st.years)),
    row('Salary this year', plain(st.salary) + ', rising ' + st.raise + '% a year'), row('Retirement age in this plan', String(st.stopAge)), row('Monthly bills today', plain(st.goal) + ', before health insurance and taxes')];
  if (st.savings || st.saveMonthly) rows.push(row('403(b), 401(k) or traditional IRA', plain(st.savings) + ', adding ' + per(st.saveMonthly)));
  if (st.b457Bal || st.b457Monthly) rows.push(row('457(b)', plain(st.b457Bal || 0) + ', adding ' + per(st.b457Monthly || 0)));
  if (st.rothBal || st.rothMonthly) rows.push(row('Roth accounts', plain(st.rothBal) + ', adding ' + per(st.rothMonthly)));
  if (st.otherBal || st.otherMonthly) rows.push(row('Other savings', plain(st.otherBal) + ', adding ' + per(st.otherMonthly)));
  if (st.otherIncome) rows.push(row('Other income in retirement, before taxes', per(st.otherIncome) + (st.otherIncomeEnd ? ', until age ' + st.otherIncomeEnd : '')));
  if (st.goalLater > 0) rows.push(row('Monthly bills from age ' + st.goalLaterAge, plain(st.goalLater)));

  oneTimes(st).forEach(function (o) { rows.push(row('One-time money at age ' + o.age, plain(o.amt) + (o.out ? ' going out' : ' coming in'))); });
  if (st.sp && st.sp.on && st.sp.survCut > 0) rows.push(row('Survivor option', 'Pension cut ' + st.sp.survCut + '%, with ' + st.sp.survShare + '% continuing to your spouse'));
  if (st.outKy) rows.push(row('Where you\'ll live', 'Outside Kentucky, so no Kentucky income tax is counted'));
  if (st.sickDays) rows.push(row('Unused sick days', st.sickDays + ' days, ' + ({ credit: 'bought as service credit by the district', cash: 'paid in cash by the district, so not counted', unsure: 'counted as service credit, but the district\'s policy isn\'t known yet' })[st.sickHow || 'credit']));
  if (st.ssYears) rows.push(row('Jobs that paid Social Security', st.ssYears + ' years, averaging ' + plain(st.ssAvg) + ' a year'));
  if (st.otherPension) rows.push(row('Another pension', per(st.otherPension) + ' from age ' + st.otherPensionAge));
  if (st.sp && st.sp.on) {
    var q = st.sp;
    rows.push(row('Spouse', 'Age ' + q.age + (q.pay && q.stopAge ? ', pay before taxes ' + per(q.pay) + ' until age ' + q.stopAge : '') + (q.trs && q.start ? ', in TRS since ' + q.start + ' with ' + q.years + ' years' + (safe().sp.trsPension ? ', TRS pension worked out at about ' + per(safe().sp.trsPension) + ' from age ' + safe().sp.trsAge : '') : '') + (q.pension ? ', pension ' + per(q.pension) + ' from age ' + q.pensionAge : '') + (q.pia ? ', Social Security ' + per(q.pia) + ' at age ' + (q.claimAge || 67) : '') + (q.savings || q.saveMonthly ? ', savings ' + plain(q.savings) + ' adding ' + per(q.saveMonthly) : '') + (q.onTrs ? ', covered on the TRS health plan' : '')));
  }
  rows.push(row('Assumptions', 'Prices rise ' + st.inflation + '% a year, savings grow ' + st.returnRate + '% a year, Social Security starts at ' + st.claimAge + ', taxes for ' + ({ single: 'a single filer', hoh: 'a head of household', joint: 'a married couple filing jointly', mfs: 'married, filing separately' })[safe().status]));
  doc.table(rows, false);
  doc.heading('Before you rely on this', 2);
  [].forEach.call(document.querySelectorAll('footer p'), function (p2) { doc.para(pdfClean(pdfTxt(p2)), { size: 9.5 }); });
  download('schools-out-plan.pdf', 'application/pdf', doc.finish());
  showMessage('Your plan was saved as a PDF in your Downloads folder.', 'ok');
}

/* ---------- Read a TRS annual statement, as a PDF or as pasted text. It never leaves this device. ---------- */
function latin(bytes) { var out = ''; for (var i = 0; i < bytes.length; i += 8192) out += String.fromCharCode.apply(null, bytes.subarray(i, i + 8192)); return out; }
function inflate(bytes) {
  /* Reads whatever inflates cleanly, so a stray byte after the compressed data doesn't lose the page. */
  var ds = new DecompressionStream('deflate'), w = ds.writable.getWriter(), rd = ds.readable.getReader(), chunks = [], size = 0;
  w.write(bytes).catch(function () {}); w.close().catch(function () {});
  var done = function () {
    if (!size) throw new Error('empty');
    var out = new Uint8Array(size), at = 0;
    chunks.forEach(function (c) { out.set(c, at); at += c.length; });
    return out;
  };
  var pump = function () { return rd.read().then(function (r) { if (r.done) return done(); chunks.push(r.value); size += r.value.length; return pump(); }, done); };
  return pump();
}
function pdfCmap(text) {
  var map = { two: false, n: 0 }, hex = function (h) { var o = ''; for (var i = 0; i + 3 < h.length; i += 4) o += String.fromCharCode(parseInt(h.substr(i, 4), 16)); return o; }, m;
  var chars = /beginbfchar([\s\S]*?)endbfchar/g, ranges = /beginbfrange([\s\S]*?)endbfrange/g, pair = /<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>/g, rng = /<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*(?:<([0-9A-Fa-f]+)>|\[([^\]]*)\])/g, k;
  while ((m = chars.exec(text))) while ((k = pair.exec(m[1]))) { map[parseInt(k[1], 16)] = hex(k[2]); map.n++; if (k[1].length > 2) map.two = true; }
  while ((m = ranges.exec(text))) while ((k = rng.exec(m[1]))) {
    var lo = parseInt(k[1], 16), hi = Math.min(parseInt(k[2], 16), lo + 512), list = k[4] ? k[4].match(/[0-9A-Fa-f]+/g) || [] : null;
    for (var c = lo; c <= hi; c++) { map[c] = list ? hex(list[c - lo] || '') : hex(k[3]).slice(0, -1) + String.fromCharCode(hex(k[3]).slice(-1).charCodeAt(0) + c - lo); map.n++; }
    if (k[1].length > 2) map.two = true;
  }
  return map;
}
function pdfString(tok, map) {
  var bytes = [], i;
  if (tok[0] === '<') { var h = tok.replace(/[^0-9A-Fa-f]/g, ''); for (i = 0; i + 1 < h.length; i += 2) bytes.push(parseInt(h.substr(i, 2), 16)); }
  else {
    var s2 = tok.slice(1, -1);
    for (i = 0; i < s2.length; i++) {
      if (s2[i] !== '\\') { bytes.push(s2.charCodeAt(i) & 255); continue; }
      var nx = s2[++i], oct = /^[0-7]{1,3}/.exec(s2.slice(i));
      if (oct) { bytes.push(parseInt(oct[0], 8)); i += oct[0].length - 1; }
      else if (nx !== '\n' && nx !== '\r') bytes.push(({ n: 10, r: 13, t: 9, b: 8, f: 12 })[nx] || (nx || '').charCodeAt(0));
    }
  }
  var out = '';
  if (map && map.two) for (i = 0; i + 1 < bytes.length; i += 2) out += map[bytes[i] * 256 + bytes[i + 1]] || '';
  else for (i = 0; i < bytes.length; i++) out += map && map[bytes[i]] !== undefined ? map[bytes[i]] : String.fromCharCode(bytes[i]);
  return out;
}
function pdfText(buf) {
  var bytes = new Uint8Array(buf), raw = latin(bytes), jobs = [], re = /stream\r?\n/g, m;
  if (raw.slice(0, 5) !== '%PDF-') return Promise.reject(new Error('not a pdf'));
  while ((m = re.exec(raw))) {
    var start = m.index + m[0].length, end = raw.indexOf('endstream', start);
    if (end < 0) break;
    var head = raw.slice(Math.max(0, m.index - 900), m.index), hs = head.match(/\d+\s+\d+\s+obj\b/g) || [''], lastObj = hs[hs.length - 1], dict = head.slice(head.lastIndexOf(lastObj)), num = String(parseInt(lastObj, 10));
    (function (num, dict, start, end) {
      if (/FlateDecode/.test(dict) && !/ASCII85|LZW|DCT|JPX|CCITT/.test(dict)) jobs.push(inflate(bytes.subarray(start, end)).then(function (b) { return { num: num, text: latin(b) }; }, function () { return null; }));
      else if (!/\/Filter/.test(dict)) jobs.push(Promise.resolve({ num: num, text: raw.slice(start, end) }));
    })(num, dict, start, end);
    re.lastIndex = end + 9;
  }
  return Promise.all(jobs).then(function (list) {
    list = list.filter(Boolean);
    var cmaps = {}, merged = null, all = raw + list.map(function (x) { return x.text; }).join('\n'), fontCmap = {}, names = {}, k;
    list.forEach(function (x) { if (/beginbf(char|range)/.test(x.text)) { cmaps[x.num] = pdfCmap(x.text); merged = merged || { two: false, n: 0 }; for (var c in cmaps[x.num]) if (c !== 'two' && c !== 'n' && merged[c] === undefined) merged[c] = cmaps[x.num][c]; merged.two = merged.two || cmaps[x.num].two; } });
    var fonts = /(\d+)\s+0\s+obj\b((?:(?!endobj)[\s\S]){0,3000}?)\/ToUnicode\s+(\d+)\s+0\s+R/g, ref = /\/([A-Za-z0-9_.+-]+)\s+(\d+)\s+0\s+R/g;
    while ((k = fonts.exec(all))) if (cmaps[k[3]]) fontCmap[k[1]] = cmaps[k[3]];
    while ((k = ref.exec(all))) if (fontCmap[k[2]]) names[k[1]] = fontCmap[k[2]];
    var out = '', tok = /\/([^\s\/\[\]<>()]+)\s+(-?[\d.]+)\s+Tf|\[((?:\((?:\\[\s\S]|[^\\)])*\)|<[^>]*>|[^\]])*)\]\s*TJ|(\((?:\\[\s\S]|[^\\)])*\)|<[0-9A-Fa-f\s]*>)\s*(?:Tj|'|")|(-?[\d.]+)\s+(-?[\d.]+)\s+T[dD]\b|(?:-?[\d.]+\s+){4}(-?[\d.]+)\s+(-?[\d.]+)\s+Tm\b|T\*|\bET\b/g, part = /\((?:\\[\s\S]|[^\\)])*\)|<[^>]*>|-?[\d.]+/g;
    list.forEach(function (x) {
      if (!/\bBT\b/.test(x.text) || !/T[jJ]\b/.test(x.text)) return;
      var map = merged, lastY = null, size = 10, run = 0, t, p2;
      var show = function (str) { out += str; run += str.length; };
      tok.lastIndex = 0;
      while ((t = tok.exec(x.text))) {
        if (t[1]) { map = names[t[1]] || merged; size = Math.abs(+t[2]) || size; }
        else if (t[3] !== undefined) { run = 0; part.lastIndex = 0; while ((p2 = part.exec(t[3]))) { if (p2[0][0] === '(' || p2[0][0] === '<') show(pdfString(p2[0], map)); else if (+p2[0] < -180) show(' '); } }
        else if (t[4]) { run = 0; show(pdfString(t[4], map)); }
        else if (t[5] !== undefined) {
          /* A move along the same line is a space only when it jumps past the text just shown; otherwise it's kerning inside a word. */
          if (+t[6] !== 0) out += '\n'; else if (+t[5] - run * size * .75 > size * .3 || +t[5] < 0) out += ' ';
          run = 0;
        }
        else if (t[7] !== undefined) { out += lastY !== null && Math.abs(+t[8] - lastY) > 1 ? '\n' : ' '; lastY = +t[8]; run = 0; }
        else if (t[0] === 'T*') { out += '\n'; run = 0; }
      }
      out += '\n';
    });
    var good = (out.match(/[A-Za-z0-9 .,$\/:\n-]/g) || []).length;
    if (out.length < 80 || good / out.length < .85) throw new Error('unreadable');
    return out;
  });
}
/* Find the few numbers the plan needs. Anything not found is simply left for the teacher to type. */
function parseStatement(t) {
  var out = { found: [] }, m, num = function (x) { return parseFloat(String(x).replace(/[$,\s]/g, '')); }, now = new Date();
  t = t.replace(/ /g, ' ').replace(/[ \t]+/g, ' ');
  m = /(?:date of birth|birth ?date|\bd\.?o\.?b\b\.?)\D{0,25}(\d{1,2})[\/-](\d{1,2})[\/-]((?:19|20)\d\d)/i.exec(t);
  if (m) { var age = now.getFullYear() - +m[3] - (now.getMonth() + 1 < +m[1] || (now.getMonth() + 1 === +m[1] && now.getDate() < +m[2]) ? 1 : 0); if (age >= 18 && age <= 80) { out.age = age; out.found.push('Age ' + age); } }
  var rows = [];
  t.split(/\n/).forEach(function (line) {
    var y = /^\W{0,3}(?:FY\s*)?((?:19|20)\d\d)(?:\s?[-–\/]\s?((?:19|20)?\d\d))?(?=\s)/.exec(line);
    if (!y) return;
    var rest = line.slice(y[0].length), amts = (rest.match(/\$?\d{1,3}(?:,\d{3})+(?:\.\d\d)?|\$\d{4,7}(?:\.\d\d)?|\b\d{4,7}\.\d\d\b/g) || []).map(num).filter(function (v) { return v >= 1000 && v < 1000000; });
    var cr = /(?:^|\s)([01]\.\d{1,4})(?=\s|$)/.exec(rest.replace(/\$?\d{1,3}(?:,\d{3})+(?:\.\d\d)?/g, ' '));
    if (amts.length) rows.push({ year: +y[1], salary: Math.max.apply(null, amts), credit: cr ? +cr[1] : null });
  });
  rows = rows.filter(function (r) { return r.year >= 1960 && r.year <= now.getFullYear(); }).sort(function (a, b) { return a.year - b.year; });
  /* One stray line with a year and a dollar amount isn't a salary history. */
  if (rows.length === 1 && !/salary/i.test(t)) rows = [];
  rows = rows.filter(function (r) { return r.salary >= 5000; });
  if (rows.length) {
    var full = rows.filter(function (r) { return r.credit === null || r.credit >= .9; }), last = (full.length ? full : rows).slice(-1)[0];
    out.salary = Math.round(last.salary); out.found.push('Latest full-year salary ' + plain(out.salary));
    if (rows.length < 30) { out.start = rows[0].year; out.found.push('First year on the statement ' + rows[0].year); }
    if (full.length >= 5) { out.fas = Math.round(full.slice(-5).reduce(function (a, r) { return a + r.salary; }, 0) / 5); out.found.push('Average of your last 5 salaries ' + plain(out.fas)); }
    if (rows.every(function (r) { return r.credit !== null; })) out.years = Math.round(rows.reduce(function (a, r) { return a + r.credit; }, 0) * 100) / 100;
  }
  m = /total[^\n]{0,40}?service[^\n\d]{0,40}(\d{1,2}(?:\.\d{1,4})?)(?!\d|\/|,)/i.exec(t) || /service credit[^\n\d]{0,40}(\d{1,2}\.\d{1,4})(?!\d)/i.exec(t);
  if (m && +m[1] > 0 && +m[1] <= 50) out.years = +m[1];
  if (out.years) out.found.push(out.years + ' years of service');
  m = /(?:entry date|date of entry|membership date|member since|date of membership)\D{0,25}(\d{1,2})[\/-]\d{1,2}[\/-]((?:19|20)\d\d)/i.exec(t);
  if (m) { out.start = +m[2] - (+m[1] < 7 ? 1 : 0); out.type = +m[2] < 2002 || (+m[2] === 2002 && +m[1] < 7) ? '1' : +m[2] < 2008 || (+m[2] === 2008 && +m[1] < 7) ? '2' : +m[2] < 2022 ? '3' : '4'; out.found.push('Joined TRS in ' + m[2]); }
  m = /\bTRS ?([1-4])\b/.exec(t); if (m) { out.type = m[1]; out.found.push('Account type TRS ' + m[1]); }
  var bal = 0, br = /(?:account balance|total contributions and interest|total contributions (?:&|and) interest|ending balance|total account|balance as of)[^\n$\d]{0,70}(?:\d{1,2}\/\d{1,2}\/\d{2,4}\D{0,20})?\$?\s?(\d{1,3}(?:,\d{3})+\.\d\d|\d{4,7}\.\d\d)/ig;
  while ((m = br.exec(t))) bal = Math.max(bal, num(m[1]));
  if (bal) { out.balance = Math.round(bal); out.found.push('Account balance ' + plain(bal)); }
  return out;
}
function importApply(text) {
  var box = $('impOut'), r = parseStatement(text);
  if (r.age === undefined && r.years === undefined && r.salary === undefined) { box.innerHTML = '<p class="err-text">That didn\'t look like a TRS annual statement, so nothing was changed. You can type your numbers in below.</p>'; return; }
  var set = function (id, v) { if (v !== undefined && $(id)) { $(id).value = v; $(id).dispatchEvent(new Event('input', { bubbles: true })); } };
  if (r.start) set('wStart', r.start);
  if (r.type && $('wType')) { $('wType').value = r.type; wiz.typeTyped = true; wiz.typeOpen = true; $('wTypeWrap').hidden = false; if ($('wTypeToggle')) $('wTypeToggle').hidden = true; pre83Sync(); }
  if (r.age !== undefined && !wiz.age) wiz.age = r.age;
  if (r.years) { set('wYears', r.years); wiz.yearsTyped = true; } set('wSalary', r.salary);
  if (r.fas && $('wFasWrap')) { $('wFasArea').hidden = false; $('wFasWrap').hidden = false; $('wFasToggle').setAttribute('aria-expanded', 'true'); set('wFas', r.fas); }
  if (r.balance) wiz.balance = r.balance;
  var missing = [['years', 'years of service'], ['salary', 'salary'], ['start', 'the year you started']].filter(function (x) { return r[x[0]] === undefined; }).map(function (x) { return x[1]; });
  box.innerHTML = '<p class="note" style="color:inherit"><strong>Filled in from your statement.</strong> ' + r.found.map(esc).join('. ') + '.' + (missing.length ? ' Not found, so please type: ' + missing.join(', ') + '.' : '') + ' Check each box below against the statement before you go on. The statement itself wasn\'t saved.</p>';
  if ($('impText')) $('impText').value = '';
}
function importFile(file) {
  var box = $('impOut'), fail = function () { box.innerHTML = '<p class="err-text">That file couldn\'t be read here, and nothing was changed. Open your statement, select all the text, copy it, and paste it into the box.</p>'; };
  if (!file) return;
  if (file.size > 30 * 1024 * 1024) return fail();
  var rd = new FileReader();
  rd.onerror = fail;
  rd.onload = function () {
    var head = latin(new Uint8Array(rd.result).subarray(0, 5));
    if (head === '%PDF-') { if (typeof DecompressionStream === 'undefined') return fail(); pdfText(rd.result).then(importApply, fail); }
    else { try { importApply(new TextDecoder().decode(rd.result)); } catch (e) { fail(); } }
  };
  rd.readAsArrayBuffer(file);
}
document.addEventListener('change', function (e) { if (e.target.id === 'impFile') { importFile(e.target.files[0]); e.target.value = ''; } });
document.addEventListener('click', function (e) {
  var btn = e.target.closest ? e.target.closest('button') : null;
  if (btn && btn.id === 'pdfBtn') makePdf();
  if (e.target.id === 'impGo') { var v = $('impText').value; if (v.trim().length < 20) $('impOut').innerHTML = '<p class="err-text">Paste the text of your statement first, or choose the PDF.</p>'; else importApply(v); }
});

document.addEventListener('click', function (e) { if (e.target.closest && e.target.closest('[data-print-pass]')) $('passPrint').click(); });
document.addEventListener('click', function (e) {
  var a = e.target.closest && e.target.closest('[data-fp]');
  if (e.target.id === 'fpClose') {
    if (document.body.classList.contains('fp-solo')) { document.body.classList.remove('fp-open', 'fp-solo'); window.scrollTo({ top: 0, left: 0, behavior: 'instant' }); return; }
    document.body.classList.remove('fp-open'); $('answerBox').scrollIntoView(); return;
  }
  if (!a) return;
  e.preventDefault();
  var d = $(a.getAttribute('href').slice(1));
  if (!d) return;
  /* On the front page or the questions, the fine print opens on its own and Back returns there with nothing lost. */
  var solo = screen !== 'results';
  document.body.classList.toggle('fp-solo', solo);
  $('fpClose').textContent = solo ? (screen === 'wizard' ? 'Back to the questions' : 'Back') : 'Back to your plan';
  /* Sources and the Kentucky law list open together. */
  document.querySelectorAll('#s-how details.section').forEach(function (x) { x.classList.toggle('fp-on', x === d || (d.id === 'fp-sources' && x.id === 'fp-law')); if (x.id === 'fp-law' && d.id === 'fp-sources') x.open = true; });
  d.open = true;
  document.body.classList.add('fp-open');
  if (solo) window.scrollTo({ top: 0, left: 0, behavior: 'instant' }); else $('s-how').scrollIntoView({ block: 'start' });
  $('fpClose').focus({ preventScroll: true });
});
/* Point at a chart to read its numbers. Works by mouse, and by tap on a phone. */
function wrapChart(svg) { return '<div class="chart-wrap">' + svg + '<div class="tip" hidden aria-hidden="true"></div></div>'; }
function hovCols(xs, top, bottom, tips) {
  return xs.map(function (cx, i) {
    var l = i ? (xs[i - 1] + cx) / 2 : cx - (xs[1] - cx) / 2, r = i < xs.length - 1 ? (cx + xs[i + 1]) / 2 : cx + (cx - xs[i - 1]) / 2;
    return '<rect class="hov" x="' + l.toFixed(1) + '" y="' + top + '" width="' + Math.max(1, r - l).toFixed(1) + '" height="' + (bottom - top) + '" fill="transparent" data-gx="' + cx.toFixed(1) + '" data-tip="' + esc(tips[i]) + '"/>';
  }).join('') + '<line class="guide" x1="0" x2="0" y1="' + top + '" y2="' + bottom + '" visibility="hidden"/>';
}
var tipWrap = null;
function chartTip(e) {
  var wrap = e.target.closest ? e.target.closest('.chart-wrap') : null, t = wrap && e.target.closest('.hov');
  if (tipWrap && tipWrap !== wrap) { tipWrap.querySelector('.tip').hidden = true; var g0 = tipWrap.querySelector('.guide'); if (g0) g0.setAttribute('visibility', 'hidden'); tipWrap = null; }
  if (!wrap) return;
  var tip = wrap.querySelector('.tip'), guide = wrap.querySelector('.guide');
  if (!t) { tip.hidden = true; if (guide) guide.setAttribute('visibility', 'hidden'); return; }
  tipWrap = wrap; tip.innerHTML = t.getAttribute('data-tip'); tip.hidden = false;
  var wr = wrap.getBoundingClientRect(), r = t.getBoundingClientRect(), py = (e.clientY || r.top + r.height / 2) - wr.top;
  var left = Math.max(0, Math.min(wr.width - tip.offsetWidth, r.left + r.width / 2 - wr.left - tip.offsetWidth / 2)), top = py - tip.offsetHeight - 16;
  tip.style.left = left + 'px'; tip.style.top = (top < 0 ? py + 18 : top) + 'px';
  if (guide && t.dataset.gx) { guide.setAttribute('x1', t.dataset.gx); guide.setAttribute('x2', t.dataset.gx); guide.setAttribute('visibility', 'visible'); }
}
document.addEventListener('mousemove', chartTip);
document.addEventListener('click', function (e) { if (e.target.closest && e.target.closest('.chart-wrap')) chartTip(e); });
/* ---------- Wire up ---------- */
renderExampleCard();
fillForm();
document.addEventListener('input', onChange);
document.addEventListener('change', function (e) {
  if (e.target.id !== 'resultOutsidePremium') return;
  var val = Number(e.target.value);
  if (!Number.isFinite(val) || val < 0 || val > 10000) return;
  state.marketHealth = val;
  wiz.mkt = val;
  renderAll();
});
document.addEventListener('click', function (e) {
  var t = e.target.closest('button');
  if (!t) return;
  if (t.dataset.example) loadExample(t.dataset.example);
  if (t.id === 'passPrint') { $('printPass').innerHTML = $('passOut').innerHTML; document.body.dataset.print = 'pass'; window.print(); setTimeout(function () { delete document.body.dataset.print; }, 1000); }
  if (t.dataset.period) showPeriod(t.dataset.period, true);
  if (t.id === 'overBtn') { $('message').innerHTML = ''; wiz = newWiz(true); }
  if (t.id === 'startBtn' && state.fromWizard && !isExample && t.textContent === 'Continue my plan') { setScreen('results'); return; }
  if (t.id === 'newBtn') { wiz = newWiz(true); setScreen('wizard'); renderWizard(); return; }
  if (t.id === 'exHome') { exampleFrom = null; leaveExample(); window.scrollTo(0, 0); return; }
  if (t.id === 'backMine' && exampleFrom) { state = JSON.parse(exampleFrom.state); isExample = exampleFrom.wasExample; exampleFrom = null; fillForm(); renderAll(); dirty = true; window.scrollTo(0, 0); return; }
  if (t.id === 'startBtn' || t.id === 'useMine' || t.id === 'overBtn') { wiz.step = 0; if (!wiz.fresh) wizFromState(); setScreen('wizard'); renderWizard(); }
  if (t.id === 'pgPrev' || t.id === 'pgNext') {
    var at = PAGES.findIndex(function (p) { return p[0] === screen; }), to = PAGES[at + (t.id === 'pgNext' ? 1 : -1)];
    /* On the question pages the arrows act like Back and Next: no skipping ahead without answering each page. */
    if (screen === 'wizard') { if (t.id === 'pgNext') wizardStep(); else $('wizBack').click(); return; }
    if (!to && t.id === 'pgPrev') goHome();
    else if (to) { if (to[0] === 'wizard') { wizFromState(); wiz.step = wizSteps()[wizSteps().length - 1]; setScreen('wizard'); renderWizard(); } else setScreen(to[0]); }
  }
  if (t.id === 'wizBack') {
    if (wizSteps().indexOf(wiz.step) <= 0) { if (wizFrom === 'welcome' || !(state.fromWizard || isExample)) goHome(); else setScreen(wizFrom); }
    else { wizardKeep(); var st = wizSteps(), i = st.indexOf(wiz.step); wiz.step = st[Math.max(0, i - 1)]; renderWizard(); }
  }
  if (t.id === 'copyTalk') {
    var okay = function () { t.textContent = 'Copied'; }, fail = function () { t.textContent = 'Copy didn\'t work in this browser'; };
    try { navigator.clipboard.writeText(talkText(window.__r.h)).then(okay, fail); } catch (err) { fail(); }
  }
});
document.addEventListener('change', function (e) { if (e.target.tagName === 'SELECT') onChange(e); });
document.addEventListener('change', function (e) { if (e.target.name !== 'wMarried') return; wiz.chk.sp = e.target.value === '1'; if (!wiz.chk.tax) wiz.status = wiz.chk.sp ? 'joint' : 'single'; var st = wizSteps(); wizProg(st.indexOf(wiz.step), st.length); });
document.addEventListener('change', function (e) { if (e.target.name !== 'wSpKind') return; var t = e.target.value === '1'; document.querySelectorAll('#wizBody .sp-ss').forEach(function (x) { x.hidden = t; }); document.querySelectorAll('#wizBody .sp-trs').forEach(function (x) { x.hidden = !t; }); });
/* True when the questions are being used to change a plan that already exists. */
function isEditing() { return !!(state.fromWizard && !isExample && !wiz.fresh); }
/* Every page is answered in order, for a new plan and when editing a saved one. */
function wizardStep() {
  if (!wizardRead()) return;
  var st = wizSteps(), i = st.indexOf(wiz.step);
  if (i === st.length - 1) wizardFinish(); else { wiz.step = st[i + 1]; renderWizard(); }
}
$('wizNext').addEventListener('click', wizardStep);
$('wizForm').addEventListener('keydown', function (e) {
  if (e.key === 'Enter' && e.target.tagName === 'INPUT') { e.preventDefault(); wizardStep(); }
});
$('saveBtn').addEventListener('click', saveFile);
$('openBtn').addEventListener('click', function () { $('openFile').value = ''; $('openFile').click(); });
$('openBtn2').addEventListener('click', function () { $('openFile').value = ''; $('openFile').click(); });
$('openFile').addEventListener('change', function () { var f = $('openFile').files[0]; if (f) openFile(f); $('openFile').value = ''; });
function setMore(o) { var b = document.querySelector('.bar'); b.classList.toggle('open', o); $('moreBtn').setAttribute('aria-expanded', o ? 'true' : 'false'); $('moreBtn').innerHTML = '&#8943;'; $('moreBtn').setAttribute('aria-label', o ? 'Close options' : 'More options'); }
$('moreBtn').addEventListener('click', function (e) { e.stopPropagation(); setMore(!document.querySelector('.bar').classList.contains('open')); });
document.addEventListener('click', function (e) { if (!document.querySelector('.bar').classList.contains('open')) return; if (!e.target.closest('#moreMenu') || e.target.closest('button')) setMore(false); });
document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && document.querySelector('.bar').classList.contains('open')) { setMore(false); $('moreBtn').focus(); } });
var lastW = window.innerWidth;
window.addEventListener('resize', function () { if (window.innerWidth !== lastW) { lastW = window.innerWidth; renderAll(); } });
window.addEventListener('beforeunload', function (e) { if (dirty) { e.preventDefault(); e.returnValue = ''; } });
isExample = true;
renderAll();
showPeriod('when', false);
setScreen('welcome');
restoreSaved();

/* Clear a wizard error as soon as the person starts fixing it, and count typed answers as unsaved changes. */
document.addEventListener('input', function (e) {
  if (e.target.closest && e.target.closest('#wizBody')) { dirty = true; if ($('wizErr')) $('wizErr').textContent = ''; }
});

/* Numbers change only when typed: scrolling moves the page, and arrow keys do nothing. */
document.addEventListener('wheel', function (e) {
  if (e.target.matches && e.target.matches('input[type=number]') && e.target === document.activeElement) {
    e.preventDefault();
    window.scrollBy(0, e.deltaY);
  }
}, { passive: false });
document.addEventListener('keydown', function (e) {
  if ((e.key === 'ArrowUp' || e.key === 'ArrowDown') && e.target.matches && e.target.matches('input[type=number]')) e.preventDefault();
});

/* Keep original totals unassigned until the user identifies account types. */
function updateUnallocated() {
  var el = $('wUnallocated'); if (!el) return;
  var w = wiz, n = function(x) { return Math.max(0, parseFloat(x) || 0); };
  var bal = n(w.sav) + n(w.b457) + n(w.roth) + n(w.oth);
  var monthly = n(w.savM) + n(w.b457M) + n(w.rothM) + n(w.othM);
  var rem = Math.max(0, n(w.unallocated) - bal), remM = Math.max(0, n(w.unallocatedM) - monthly);
  el.textContent = (rem || remM) ? 'Not yet assigned: $' + rem.toLocaleString('en-US') + (remM ? ' and $' + remM.toLocaleString('en-US') + '/month' : '') + '. Assign these amounts to the correct account types for more accurate taxes.' : 'Account amounts are entered individually.';
}
document.addEventListener('input', function(e) {
  if (!/^w(Sav|457|Roth|Oth)(M)?$/.test(e.target.id)) return;
  wiz[e.target.id.replace(/^w/, '').replace(/^Sav/, 'sav').replace(/^Roth/, 'roth').replace(/^Oth/, 'oth').replace(/^457/, 'b457')] = e.target.value;
  updateUnallocated();
});
/* Savings: one total by default, or split by account type for more exact taxes. Amounts carry over either way. */
document.addEventListener('click', function (e) {
  if (e.target.id !== 'wSplit') return;
  var w = wiz, n = function (x) { return parseFloat(x) || 0; };
  wizardKeep();
  if (w.split) { var t = n(w.sav) + n(w.b457) + n(w.roth) + n(w.oth), tm = n(w.savM) + n(w.b457M) + n(w.rothM) + n(w.othM); w.tot = Math.max(t, n(w.unallocated)) || ''; w.totM = Math.max(tm, n(w.unallocatedM)) || ''; w.split = false; }
  else { w.unallocated = w.tot || ''; w.unallocatedM = w.totM || ''; w.split = true; }
  renderWizard();
  updateUnallocated();
  var f = $(w.split ? 'wSav' : 'wTot'); if (f) f.focus();
});
document.addEventListener('click', function (e) {
  if (e.target.id !== 'wTypeBack') return;
  wiz.typeOpen = false; wiz.typeTyped = false; wiz.type = '';
  $('wType').value = ''; $('wTypeWrap').hidden = true; $('wTypeToggle').hidden = false;
  pre83Sync();
  $('wTypeToggle').focus();
});
document.addEventListener('click', function (e) {
  if (e.target.id !== 'wTypeToggle') return;
  wiz.typeOpen = true; $('wTypeWrap').hidden = false; e.target.hidden = true; $('wType').focus();
});
document.addEventListener('click', function (e) {
  if (e.target.id !== 'wFasToggle') return;
  var open = $('wFasWrap').hidden; $('wFasWrap').hidden = !open; e.target.setAttribute('aria-expanded', open ? 'true' : 'false');
  if (open) $('wFas').focus(); else $('wFas').value = '';
});
document.addEventListener('change', function (e) {
  if (e.target.id === 'wType') { wiz.typeTyped = true; pre83Sync(); }
  var no = e.target.dataset && e.target.dataset.wno;
  if (no) { wiz.chk[no] = false; $('wsub-' + no).hidden = true; return; }
  var k = e.target.dataset && e.target.dataset.wchk;
  if (!k) return;
  wiz.chk[k] = e.target.checked; $('wsub-' + k).hidden = !e.target.checked;
  if (e.target.checked) { var f = $('wsub-' + k).querySelector('input'); if (f) f.focus(); }
});

document.addEventListener('input', function (e) {
  if (e.target.id === 'wSpYears') wiz.spYearsTyped = e.target.value !== '';
  if (e.target.id === 'wSpStart' && !wiz.spYearsTyped && $('wSpYears')) { var y = parseInt(e.target.value, 10); $('wSpYears').value = (y >= 1960 && y <= THIS_YEAR) ? Math.max(0.5, THIS_YEAR - y) : ''; }
});
/* Fill years of service from the start year, unless the person has typed their own. */
document.addEventListener('input', function (e) {
  if (e.target.id === 'wYears') wiz.yearsTyped = e.target.value !== '';
  if (e.target.id === 'wStart') {
    var sy = parseInt(e.target.value, 10);
    if (!wiz.typeTyped && $('wType') && sy >= 1960 && sy <= THIS_YEAR) { $('wType').value = typeFromYear(sy); }
    pre83Sync();
    if (!wiz.pre83Typed && $('wPre83')) $('wPre83').value = defaultPre83(sy, $('wYears').value || (THIS_YEAR - sy));
  }
  if (e.target.id === 'wPre83') wiz.pre83Typed = true;
  if ((e.target.id === 'wYears' || e.target.id === 'wStart') && $('wFasArea')) setTimeout(function () { $('wFasArea').hidden = !(parseFloat($('wYears').value) >= 1); }, 0);
  if (e.target.id === 'wStart' && !wiz.yearsTyped) {
    var y = parseInt(e.target.value, 10);
    $('wYears').value = (y >= 1960 && y <= THIS_YEAR) ? Math.max(0.5, THIS_YEAR - y) : '';
  }
});

/* The School's Out name in the header returns to the front page. */
/* Leaving the example brings back your own plan, if this copy has one saved. */
function leaveExample() { if (isExample && restoreSaved()) return; goHome(); }
document.querySelector('.bar .brand').addEventListener('click', function (e) { e.preventDefault(); if (isExample) leaveExample(); else goHome(); });

/* Sample teachers for "Check our math", run through the same formulas. */
(function () {
  var fas = 64000, cut = reductionAt('3', 24, 56), rows = [
    ['Joined before July 2002, 22 years', '22 &times; 2.5% = 55%', fas * percentOfSalary('1', false, 22, 60) / 100],
    ['Joined before July 2002, 32 years', '30 &times; 2.5% + 2 &times; 3% = 81%', fas * percentOfSalary('1', false, 32, 60) / 100],
    ['Joined 2002 to 2008, 9 years', '9 &times; 2.0% = 18%, because the 2.5% rate starts at 10 years', fas * percentOfSalary('2', false, 9, 60) / 100],
    ['Joined 2008 to 2021, 21 years', '21 &times; 2.3% = 48.3%', fas * percentOfSalary('3', false, 21, 60) / 100],
    ['Joined 2008 to 2021, age 56, 24 years', '24 &times; 2.3% = 55.2%, minus ' + aPct(cut) + '% early cut (3 years under 27 counts, since it\'s fewer than 4 under 60)', fas * percentOfSalary('3', false, 24, 56) / 100 * (1 - cut / 100)],
    ['Joined 2022 or later, age 62, 24 years', '24 &times; (1.78% + 0.25%) = 48.72%', fas * percentOfSalary('4', false, 24, 62) / 100]
  ];
  $('checkRows').innerHTML = rows.map(function (r) { return '<tr><td>' + r[0] + '</td><td>' + r[1] + '</td><td>' + plain(r[2]) + '</td></tr>'; }).join('');
})();

/* The front page fills the screen exactly, so the horse-farm scene ends at the bottom edge. */
function fitHero() {
  var b = document.querySelector('.bar'); if (b) document.documentElement.style.setProperty('--barh', b.offsetHeight + 'px');
  /* A wide, short space crops the drawing to fill it; a tall space keeps the drawing's size and shows more sky above. */
  var sc = document.querySelector('.hero-scene'), art = sc && sc.querySelector('.lake-art');
  var hero = document.getElementById('top'), free = document.querySelector('.hero-info-links') || document.querySelector('.hero-free'), root = hero && hero.style;
  if (root && sc && free) {
    if (window.innerWidth <= 1000) {
      /* Fit the headline, button and scene into exactly one screen (the small-viewport height, so it holds with the browser bars showing). */
      var probe = document.createElement('div'); probe.style.cssText = 'position:fixed;top:0;height:100vh;height:100svh;visibility:hidden';
      document.body.appendChild(probe); var H = probe.offsetHeight; document.body.removeChild(probe);
      root.setProperty('--hero-top', '28px'); root.setProperty('--scene-gap', '20px'); root.setProperty('--scene-h', '140px');
      var hr = hero.getBoundingClientRect(), above = free.getBoundingClientRect().bottom - hr.top, top = hr.top + window.scrollY;
      var room = H - top - above;
      var sceneH = Math.max(120, Math.min(240, room - 40)), spare = Math.max(0, room - sceneH - 20);
      root.setProperty('--scene-h', sceneH + 'px');
      /* On very short screens, borrow up to 24px from the top padding and gap so the scene still ends at the fold. */
      var cut = Math.min(24, Math.max(0, sceneH + 20 - room)), topCut = Math.min(16, cut), gapCut = cut - topCut;
      root.setProperty('--hero-top', (28 - topCut + Math.round(spare * .35)) + 'px');
      root.setProperty('--scene-gap', (20 - gapCut + spare - Math.round(spare * .35)) + 'px');
      root.setProperty('--fold', (above - topCut + Math.round(spare) + 20 - gapCut + sceneH) + 'px');
    } else { ['--hero-top', '--scene-gap', '--scene-h', '--fold'].forEach(function (k) { root.removeProperty(k); }); }
  }
  if (art && sc.clientHeight) { var vw = Math.min(3600, Math.max(1200, 240 * sc.clientWidth / sc.clientHeight)); art.setAttribute('viewBox', (600 - vw / 2) + ' 60 ' + vw + ' 240'); }
}
fitHero(); window.addEventListener('resize', fitHero);

/* Feedback control: compose locally and open user's email program. */
(function(){
  /* Fine-print section titles are headings, not toggles: they can't be clicked, so they can't be collapsed from the keyboard either. */
  document.querySelectorAll('#s-how details.section>summary').forEach(function (sm) { sm.tabIndex = -1; sm.addEventListener('click', function (e) { e.preventDefault(); }); });
  var open=document.getElementById('feedbackOpen'), dialog=document.getElementById('feedbackDialog');
  document.getElementById('feedbackOpen2').addEventListener('click', function () { var b = document.querySelector('.bar'); if (b) b.classList.remove('open'); open.click(); });
  if(!open || !dialog)return;
  var kind=document.getElementById('feedbackKind'), message=document.getElementById('feedbackText'), status=document.getElementById('feedbackStatus');
  var close=document.getElementById('feedbackClose');
  function draft(){return message.value.trim();}
  function valid(){if(!message.value.trim()){status.textContent='Please write your message first.';message.focus();return false;}return true;}
  open.addEventListener('click',function(){status.textContent='';if(typeof dialog.showModal==='function')dialog.showModal();else dialog.setAttribute('open','');message.focus();});
  close.addEventListener('click',function(){dialog.close?dialog.close():dialog.removeAttribute('open');open.focus();});
  dialog.addEventListener('click',function(e){if(e.target===dialog){dialog.close?dialog.close():dialog.removeAttribute('open');}});
  /* Only what the person typed is used, and nothing is sent until they press Send in their own email. */
  var TO='chov223@uky.edu';
  function subject(){return "School's Out: "+kind.value;}
  document.getElementById('feedbackEmail').addEventListener('click',function(){
    if(!valid())return;
    status.textContent='Opening your email app. Press Send there to submit.';
    window.location.href='mailto:'+TO+'?subject='+encodeURIComponent(subject())+'&body='+encodeURIComponent(draft());
  });
})();
</script>
<script>
/* Homepage info: hover to preview, click to pin, click outside or Esc to dismiss. */
(function(){
  const infos = Array.from(document.querySelectorAll('.hero-info-links details.hero-info'));
  if (!infos.length) return;
  let pinned = null;
  function closeAll(){ infos.forEach(info => { info.open = false; }); pinned = null; }
  infos.forEach(info => {
    const summary = info.querySelector('summary');
    info.addEventListener('pointerenter', event => {
      if (event.pointerType !== 'mouse' || pinned) return;
      infos.forEach(other => { if (other !== info) other.open = false; });
      info.open = true;
    });
    info.addEventListener('pointerleave', event => {
      if (event.pointerType === 'mouse' && pinned !== info) info.open = false;
    });
    summary.addEventListener('click', event => {
      event.preventDefault();
      if (pinned === info) { closeAll(); return; }
      infos.forEach(other => { other.open = other === info; });
      pinned = info;
    });
  });
  document.addEventListener('click', event => {
    if (!event.target.closest('.hero-info-links details.hero-info')) closeAll();
  });
  document.addEventListener('keydown', event => {
    if (event.key === 'Escape') closeAll();
  });
})();
</script>
</body>
</html>

Reaches out to

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

  • www.w3.org
  • www.nctq.org
  • apps.legislature.ky.gov
  • trs.ky.gov
  • www.cms.gov
  • www.ssa.gov
  • revenue.ky.gov
  • www.aarp.org
  • kaco.org
  • www.currentfederaltaxdevelopments.com
  • kentuckylantern.com
  • kypolicy.org

Licence

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

Copyright © 2026 Carter Overtoom. Licensed under the MIT License. Published on Globefin.

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

Sandbox

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