← Demos
Web Pages · Demos

Beyond the Blue

Beyond the Blue helps students turn their current finances into a clear, practical savings plan. Users answer simple questions about their income, spending, savings, debt, and goals, then receive a personalized overview showing what they can set aside and how to move forward. This was made to solve the issue of Kentucky students not being fully informed of what budgeting looks like and the opportunities that can arise from investing wisely.

by Andrew Escamilla Nov 21, 2026 14 views 90.5 KB
Sandbox · beyond-the-blue · no access to your account
View source — the whole page is this one file
<!-- Copyright (c) 2026 Andrew Escamilla. Released under the MIT License. -->
<!doctype html>
<html lang="en">
<!-- For University of Kentucky students. Educational use only. This tool does not provide financial or investment advice. -->
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <meta name="description" content="Beyond the Blue helps University of Kentucky students budget for the semester, set a savings goal, and explore investing with small amounts.">
  <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; connect-src 'none'; base-uri 'none'; form-action 'none'">
  <title>Beyond the Blue</title>
  <style>
:root {
  color-scheme: light;
  --navy: #112b43;
  --deep: #0a1f33;
  --ink: #172f43;
  --muted: #516374;
  --line: #d5dde1;
  --paper: #f5f7f7;
  --white: #fff;
  --orange: #ffb074;
  --rust: #934515;
  --sans: "Aptos", "Segoe UI", system-ui, sans-serif;
  --body: var(--sans);
  --display: "Iowan Old Style", "Palatino Linotype", Palatino, Georgia, serif;
}
* { box-sizing: border-box; }
[hidden] { display: none !important; }
body { margin: 0; min-height: 100vh; min-height: 100svh; display: flex; flex-direction: column; font: 1rem/1.55 var(--body); color: var(--ink); background: var(--paper); }
main { flex: 1; }
body[data-screen="home"] main { display: flex; flex-direction: column; background: var(--deep); }
button, input, select, output { font: inherit; }
button, summary, select, input[type="radio"], input[type="checkbox"], input[type="range"] { cursor: pointer; }
button { color: inherit; }
a { color: #194e74; text-underline-offset: .2em; }
:focus-visible { outline: 3px solid #126fa2; outline-offset: 3px; }
#welcome :focus-visible, .hero-actions button:focus-visible { outline-color: var(--orange); }
h1:focus, #main:focus { outline: none; }
h1, h2, h3, p, figure, fieldset { margin: 0; }
fieldset { padding: 0; border: 0; min-width: 0; }
legend { padding: 0; }
.frame { width: min(1100px, calc(100% - 64px)); margin-inline: auto; }
.sr, .week-options input, .rate-options input { position: absolute; width: 1px; height: 1px; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
.skip { position: absolute; top: -100px; left: 12px; z-index: 20; background: white; padding: .6rem 1rem; }
.skip:focus { top: 8px; }
.mast { background: #fbfcfb; border-bottom: 1px solid var(--line); }
.mast-inner { min-height: 76px; display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
.wordmark { display: inline-flex; align-items: baseline; gap: .18em; white-space: nowrap; padding: 8px 0; border: 0; background: transparent; font: 600 1.45rem/1 var(--display); letter-spacing: -.045em; }
.wordmark em { font-weight: 400; color: var(--rust); }
.book-mark { position: relative; align-self: center; display: inline-block; width: 22px; height: 18px; margin-right: 7px; }
.book-mark::before, .book-mark::after { content: ""; position: absolute; inset: 1px 55% 2px 0; background: var(--navy); clip-path: polygon(0 0,100% 20%,100% 100%,0 78%); }
.book-mark::after { inset: 1px 0 2px 50%; transform: scaleX(-1); background: #ad5926; }
.tools, .hero-actions, .form-nav, .dialog-actions, .report-actions { display: flex; align-items: center; gap: 10px; }
.tools { gap: .25rem; }
.tools button, .tools summary { min-height: 42px; padding: .6rem .78rem; border: 0; background: transparent; color: var(--navy); border-radius: 5px; font-size: .9rem; font-weight: 600; }
.tools button:hover, .tools summary:hover { background: #e8eef1; }
.tools summary { display: flex; align-items: center; gap: 7px; }
.tools summary::after, .disclosure > summary::after, .footer summary::after {
  content: ""; width: .4em; height: .4em; border: solid currentColor; border-width: 0 1.6px 1.6px 0; transform: translateY(-.13em) rotate(45deg); flex-shrink: 0;
}
details[open].disclosure > summary::after, .footer details[open] > summary::after, .tools details[open] summary::after { transform: translateY(.12em) rotate(225deg); }
summary { list-style: none; }
summary::-webkit-details-marker { display: none; }
.tools details { position: relative; border-left: 1px solid var(--line); margin-left: .35rem; padding-left: .35rem; }
.popover { position: absolute; z-index: 5; inset: calc(100% + 5px) 0 auto auto; min-width: 180px; background: white; border: 1px solid var(--line); border-radius: 8px; padding: 14px; box-shadow: 0 12px 26px #132c4319; }
#noticeWrap { background: white; border-left: 3px solid #347390; margin-block: 14px 0; padding: 10px 15px; font-size: .92rem; }
#noticeWrap[data-error="true"] { border-color: #ac391c; }
#welcome { background: var(--deep); color: #fff; flex: 1; display: grid; align-items: center; }
.hero { max-width: 1100px; display: grid; grid-template-columns: 1.06fr .94fr; align-items: center; gap: clamp(38px,7vw,104px); padding-block: clamp(60px,10vh,120px); }
.eyeline { display: inline-flex; align-items: center; gap: 10px; font-size: .9rem; font-weight: 600; color: #c5d4df; }
.eyeline::before { content: ""; width: 22px; height: 2px; background: var(--orange); }
.hero h1 { font: 400 clamp(4.4rem,7.3vw,7.3rem)/.98 var(--display); letter-spacing: -.045em; margin: .22em 0 .25em; }
.hero h1 em { display: block; color: var(--orange); font-weight: 400; }
.intro { max-width: 36ch; color: #dce5eb; font-size: clamp(1.04rem,1.6vw,1.24rem); line-height: 1.55; }
.hero-actions { margin-top: 28px; flex-wrap: wrap; }
.primary, .secondary, .hero-secondary { display: inline-flex; align-items: center; justify-content: center; min-height: 46px; border: 1px solid transparent; padding: .64rem 1.22rem; border-radius: 7px; font-weight: 650; }
.primary { background: var(--navy); color: #fff; }
.primary:hover { background: #224663; }
.hero .primary { background: var(--orange); color: #142a3b; }
.hero .primary:hover { background: #ffc59b; }
.secondary { background: white; color: var(--ink); border-color: #b6c3cb; }
.secondary:hover { background: #f0f3f5; }
.hero-secondary { background: transparent; color: #fff; border-color: #63788a; }
.hero-secondary:hover { background: #203d56; }
.privacy { color: #b8c8d4; font-size: .85rem; margin-top: 17px; }
.week-card { background: #15334b; border: 1px solid #395268; border-radius: 12px; padding: clamp(24px,3.1vw,40px); min-width: 0; }
.week-card figcaption { font-size: 1.1rem; font-weight: 600; }
.week-options, .rate-options { display: flex; gap: 7px; margin-top: 13px; }
.week-options label, .rate-options label { cursor: pointer; }
.week-options span, .rate-options span { display: block; min-width: 54px; text-align: center; border: 1px solid #6e8393; color: #e4eef5; padding: .48rem .75rem; border-radius: 5px; font-size: .94rem; font-weight: 600; }
.week-options :checked + span { background: var(--orange); color: var(--deep); border-color: var(--orange); }
.week-options :focus-visible + span, .rate-options :focus-visible + span { outline: 3px solid #70bded; outline-offset: 3px; }
.week-result { display: flex; gap: 12px; align-items: baseline; flex-wrap: wrap; margin: 24px 0 15px; }
.week-result output { color: var(--white); font: 400 clamp(2.8rem,4.7vw,4.2rem)/1.1 var(--display); letter-spacing: -.05em; font-variant-numeric: tabular-nums; }
.week-result span, .axis, .chart-caption { color: #c5d6e0; }
#weekChart { display: block; width: 100%; height: 85px; }
.chart-grid { stroke: #557082; stroke-dasharray: 3 5; fill: none; stroke-width: .8; }
.chart-area { fill: #ffb07418; }
.chart-line { fill: none; stroke: var(--orange); stroke-width: 2.3; vector-effect: non-scaling-stroke; }
.axis { display: flex; justify-content: space-between; margin-top: 5px; font-size: .8125rem; }
.chart-caption { margin-top: 17px; font-size: .83rem; }
.wizard { display: grid; grid-template-columns: minmax(155px,215px) minmax(0,660px); gap: clamp(28px,6vw,84px); justify-content: center; padding-block: clamp(30px,6vw,70px); align-items: start; }
.step-rail { padding-top: 10px; }
.step-rail h2 { font: 400 1.65rem var(--display); letter-spacing: -.04em; }
.step-rail ol { list-style: none; padding: 0; margin: 22px 0 0; }
.step-rail li { color: #596c7b; border-left: 2px solid #d9e1e5; padding: 10px 0 10px 16px; font-size: .94rem; }
.step-rail li[aria-current] { color: var(--navy); border-color: #a9521b; font-weight: 700; }
.form-sheet, .paper-card, .fold { min-width: 0; padding: clamp(23px,3.2vw,40px); background: white; border: 1px solid var(--line); border-radius: 10px; }
.step-meta { display: flex; justify-content: space-between; gap: 12px; color: var(--muted); font-size: .9rem; }
.step-meta span:first-child { color: var(--rust); font-weight: 650; }
progress { display: block; width: 100%; appearance: none; border: 0; height: 4px; border-radius: 2px; background: #e5ebed; color: #a85220; margin: 10px 0 25px; }
progress::-webkit-progress-bar { background: #e5ebed; border-radius: 2px; }
progress::-webkit-progress-value { background: #a85220; border-radius: 2px; }
progress::-moz-progress-bar { background: #a85220; border-radius: 2px; }
.form-sheet h1, .overview h1 { font: 400 clamp(2rem,3.4vw,2.95rem)/1.12 var(--display); letter-spacing: -.045em; }
.question-hint { color: var(--muted); margin: 9px 0 22px; }
.fields { display: grid; gap: 16px; }
.field label, .popover label, .lab-label, .choices legend { display: block; font-weight: 600; font-size: .94rem; margin-bottom: 6px; }
.field-hint, .subtle, .fold p, .help-content p { color: var(--muted); }
.field-hint { display: block; font-size: .85rem; margin-top: 4px; }
.pair { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 14px; align-items: start; }
.input-wrap { position: relative; }
.currency-symbol { position: absolute; left: .82rem; top: 50%; transform: translateY(-50%); color: var(--muted); pointer-events: none; }
input[type="number"], select { display: block; width: 100%; min-width: 0; min-height: 46px; border: 1px solid #9aabb7; background: #fff; color: var(--ink); padding: .57rem .8rem; border-radius: 6px; }
input.money-input { padding-left: 1.7rem; }
select { appearance: none; padding-right: 2.1rem; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'%3E%3Cpath d='m4 6 4 4 4-4' fill='none' stroke='%23465e70' stroke-width='1.6'/%3E%3C/svg%3E"); background-position: right .75rem center; background-repeat: no-repeat; }
input, progress, .amount { font-variant-numeric: tabular-nums; }
input[type="checkbox"], input[type="radio"], input[type="range"] { accent-color: #244d6b; }
.check { display: flex; align-items: center; gap: .65rem; min-height: 34px; }
.check input, .choice input { width: 1.1rem; height: 1.1rem; margin: 0; flex: 0 0 auto; }
.choices { display: grid; gap: 8px; }
.choice { display: flex; align-items: center; gap: .7rem; min-height: 48px; padding: .65rem .85rem; border: 1px solid #b9c6cd; border-radius: 6px; cursor: pointer; }
.choice:hover { border-color: #627b8c; }
.choice:has(:checked) { background: #edf4f7; border-color: #3f647e; }
.choice-main { flex: 1; }
.choice-main strong, .choice-main small { display: block; }
.choice-main small { color: var(--muted); font-size: .85rem; }
.choice .amount { color: var(--navy); font-weight: 700; }
.form-nav { justify-content: space-between; border-top: 1px solid var(--line); padding-top: 20px; margin-top: 24px; }
.error { border-left: 3px solid #a93e27; background: #fff3ee; color: #8b301c; margin-top: 16px; padding: 9px 12px; }
.quick-result { background: #edf3f5; border-radius: 6px; padding: .75rem .9rem; display: flex; justify-content: space-between; gap: 12px; align-items: baseline; }
.quick-result strong { font-variant-numeric: tabular-nums; }
.disclosure > summary, .footer summary { display: flex; align-items: center; justify-content: space-between; gap: 15px; font-size: .94rem; font-weight: 600; min-height: 44px; }
.disclosure:not(.fold) { border-top: 1px solid var(--line); }
.disclosure:not(.fold) > summary { color: #285771; }
.help-content { display: grid; gap: 10px; padding: 4px 0 7px; font-size: .94rem; }
.overview { padding-block: 38px 48px; max-width: 964px; }
.report-head { display: flex; justify-content: space-between; align-items: center; gap: 16px; flex-wrap: wrap; margin-bottom: 18px; }
.report-head p { color: var(--muted); margin-top: 2px; font-size: .94rem; }
.report-actions { gap: 8px; flex-wrap: wrap; }
.report-actions button { font-size: .9rem; }
.action-card { padding: clamp(23px,3.5vw,38px); border-radius: 9px; background: var(--navy); color: #fff; }
.action-card .caption { color: #ffc59b; font-weight: 650; font-size: .93rem; }
.action-card h2 { font: 400 clamp(1.8rem,3.4vw,2.8rem)/1.18 var(--display); letter-spacing: -.035em; margin: 5px 0 8px; }
.action-card p { color: #dee8ed; max-width: 67ch; }
.action-card a { color: #ffbd8d; }
.allocation { list-style: none; display: flex; flex-wrap: wrap; padding: 0; margin: 17px 0 0; gap: 6px 22px; border-top: 1px solid #4d657a; padding-top: 13px; }
.allocation li { color: #dce8ef; font-size: .94rem; }
.allocation strong { color: white; }
.report-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; margin: 14px 0; }
.paper-card { padding: clamp(19px,2.4vw,27px); }
.paper-card h2, .fold > summary { font-size: 1.14rem; line-height: 1.35; font-weight: 650; }
.paper-card p, .fold p { font-size: .94rem; }
.paper-card .subtle { margin-top: 12px; }
.goal-block + .goal-block { border-top: 1px solid var(--line); padding-top: 12px; margin-top: 14px; }
.goal-block h3 { margin: 10px 0 3px; font-size: .98rem; }
.meter { margin: 12px 0; }
.meter-label, .fact { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; font-size: .94rem; }
.meter-label strong, .fact strong { font-variant-numeric: tabular-nums; }
.track { height: 7px; background: #e5ecee; border-radius: 5px; overflow: hidden; margin-top: 6px; }
.track i { display: block; height: 100%; background: #335a74; }
.track i.warm { background: #ad5725; }
.fact { padding: 8px 0; border-bottom: 1px solid #e5eaed; }
.fact:last-child { border: 0; }
.fold { padding: 0 clamp(18px,2.4vw,27px); margin-top: 10px; }
.fold > summary { min-height: 57px; }
.fold-body { padding: 3px 0 22px; display: grid; gap: 13px; }
.edit-links { display: flex; flex-wrap: wrap; gap: 8px; }
.edit-links button { font-size: .92rem; min-height: 40px; }
.rate-options { margin: 6px 0 0; }
.rate-options span { color: var(--ink); border-color: #a4b5c1; }
.rate-options :checked + span { background: var(--navy); color: white; border-color: var(--navy); }
.lab-label { margin-bottom: 0; }
input[type="range"] { width: 100%; min-height: 28px; margin: 2px 0; }
.lab-grid { display: grid; grid-template-columns: 1fr 1fr; align-items: start; gap: 2.3rem; }
.lab-controls { display: grid; gap: 12px; }
.lab-value { display: block; color: var(--navy); font: 400 2.2rem/1.1 var(--display); margin: 3px 0 7px; }
.footer { border-top: 1px solid var(--line); background: #fbfcfb; }
.footer-inner { display: grid; grid-template-columns: minmax(230px,.85fr) minmax(250px,1.15fr); gap: 24px; padding-block: 22px; align-items: start; }
.credit { font-size: .87rem; }
.credit span, .credit p { color: var(--muted); }
.credit p { font-size: .8rem; margin-top: 3px; }
.footer summary { margin-left: auto; width: fit-content; min-height: 32px; }
.footer-content { display: grid; gap: 20px; grid-template-columns: 1fr 1fr; margin: 13px 0; }
.footer-content h2, .footer-content p, .footer-content ul, .license p { font-size: .88rem; }
.footer-content h2:not(:first-child) { margin-top: 12px; }
.footer-content ul { padding-left: 18px; margin: 5px 0 0; }
.footer-content li { margin: 5px 0; }
.footer-content p, .license p { color: var(--muted); margin-top: 5px; }
dialog { width: min(440px,calc(100% - 30px)); border: 1px solid var(--line); border-radius: 9px; color: var(--ink); padding: 24px; }
dialog h2 { font-size: 1.4rem; }
dialog p { margin: 10px 0 20px; }
dialog::backdrop { background: #081e30a6; }
.dialog-actions { justify-content: end; flex-wrap: wrap; }
@media (max-width: 780px) {
  .frame { width: calc(100% - 40px); }
  .hero { grid-template-columns: 1fr 1fr; gap: 24px; }
  .hero h1 { font-size: clamp(3.2rem,8vw,4.4rem); }
  .wizard { grid-template-columns: minmax(0,640px); }
  .step-rail { display: none; }
  .footer-content { grid-template-columns: 1fr; }
}
@media (max-width: 620px) {
  .mast-inner { min-height: 62px; gap: 3px; }
  .wordmark { font-size: 1.18rem; }
  .book-mark { width: 16px; height: 14px; margin-right: 4px; }
  .tools { gap: 0; }
  .tools button, .tools summary { padding: .46rem; font-size: .83rem; }
  .tools details { padding-left: .1rem; margin-left: .1rem; }
  .hero { grid-template-columns: 1fr; padding-block: 39px 30px; gap: 29px; }
  .hero h1 { font-size: clamp(2.85rem,13vw,4.5rem); }
  .hero h1 em { display: inline; }
  .intro { max-width: 39ch; }
  .hero-actions { margin-top: 20px; }
  .week-card { padding: 19px 20px; }
  .week-result { margin: 13px 0 9px; }
  #weekChart { height: 61px; }
  .report-grid, .lab-grid, .footer-inner { grid-template-columns: 1fr; }
  .footer-inner { gap: 6px; padding-block: 18px; }
  .footer summary { margin-left: 0; }
  .lab-grid { gap: 15px; }
  .wizard { padding-block: 20px; }
  .overview { padding-block: 25px; }
}
@media (max-width: 390px) {
  .frame { width: calc(100% - 28px); }
  .pair { grid-template-columns: 1fr; }
  .form-sheet { padding: 17px; }
  .tools button, .tools summary { font-size: .8rem; padding-inline: .35rem; }
  .hero-actions { gap: 7px; }
  .hero-actions button { padding-inline: .86rem; }
}
@media print {
  body { display: block; background: #fff; color: #111; }
  .frame { width: 100%; }
  .mast, #noticeWrap, #welcome, #wizard, .report-actions, .footer details, dialog, .edit-block, #labDetails, #mathDetails { display: none !important; }
  .overview { padding: 0; }
  .action-card, .paper-card { break-inside: avoid; border: 1px solid #666; background: white; color: #111; box-shadow: none; }
  .action-card p, .action-card a, .action-card .caption, .allocation li, .allocation strong { color: #111; }
  .track, .track i { print-color-adjust: exact; }
  .footer-inner { display: block; }
  .report-grid { display: grid; grid-template-columns: 1fr 1fr; }
  @page { margin: 16mm; }
}

.sample-house { display:inline-block; margin-top:8px; padding:6px 0; border:0; background:transparent; color:#ffbf91; font-weight:650; text-decoration:underline; text-underline-offset:4px; }
.goal-studio { margin:14px 0; border-top:3px solid var(--navy); }
.goal-studio h2 { font-size:1.5rem; letter-spacing:-.035em; }
.studio-switch { display:flex; gap:6px; margin:15px 0 12px; flex-wrap:wrap; }
.studio-switch label { position:relative; cursor:pointer; }
.studio-switch input { position:absolute; opacity:0; }
.studio-switch span { display:block; padding:.55rem .85rem; border:1px solid #a4b4bd; border-radius:6px; font-size:.94rem; }
.studio-switch :checked + span { background:var(--navy); color:white; border-color:var(--navy); }
.studio-switch :focus-visible + span { outline:3px solid #126fa2; outline-offset:2px; }
.studio-intro { color:var(--muted); max-width:75ch; }
.studio-grid { display:grid; grid-template-columns:minmax(0,.8fr) minmax(0,1.2fr); gap:24px; align-items:start; margin:18px 0; }
.studio-controls,.studio-settings { display:grid; gap:12px; }
.studio-controls .check { align-items:flex-start; }
.studio-field label { display:flex; flex-wrap:wrap; justify-content:space-between; gap:3px 8px; font-size:.92rem; }
.studio-field strong,.studio-table td { font-variant-numeric:tabular-nums; }
.studio-results { background:#f2f6f7; padding:16px; border-radius:8px; min-width:0; }
.studio-total { display:grid; }
.studio-total strong { font-size:clamp(1.6rem,3vw,2.4rem); letter-spacing:-.05em; line-height:1.2; }
.studio-total small,.studio-table small { color:var(--muted); }
.studio-chart { width:100%; height:auto; display:block; margin-top:12px; }
.studio-chart text { font:16px var(--sans); fill:#425a6b; }
.studio-table { width:100%; border-collapse:collapse; font-size:.88rem; margin-block:10px 14px; }
.studio-table th,.studio-table td { text-align:right; border-bottom:1px solid var(--line); padding:6px 2px; overflow-wrap:anywhere; }
.studio-table th:first-child { text-align:left; }
.studio-table th small { display:inline-block; font-weight:400; }
.asset-key { display:inline-block; width:13px; margin-right:4px; vertical-align:middle; border-top-width:3px; }
.studio-note { border-left:2px solid #a95725; padding-left:10px; margin-top:12px; }
.account-explain { display:grid; gap:8px; margin-top:12px; }
@media(max-width:760px){.studio-grid{grid-template-columns:minmax(0,1fr);gap:16px}.studio-results{padding:12px}.studio-table{font-size:.85rem}}
@media print{.goal-studio{display:none}}

.intro, .question-hint { font-family: var(--display); }
.question-hint { font-size: 1.08rem; }

.answer-review { margin-top: 14px; }
.answer-review > h2 { font: 400 clamp(1.6rem, 3vw, 2rem)/1.2 var(--display); }
.answer-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 18px 36px; margin: 18px 0; }
.answer-grid > section { min-width: 0; border-top: 1px solid var(--line); padding-top: 8px; }
.answer-heading { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
.answer-grid h3 { margin: 0; font-size: 1rem; }
.answer-jump, .answer-edit { color: var(--navy); text-decoration: underline; text-underline-offset: .2em; }
.answer-edit { border: 0; background: transparent; padding: 7px 4px; font-size: .88rem; }
.answer-list { margin: 4px 0 0; font-size: .93rem; }
.answer-list > div { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 12px; align-items: baseline; padding: 5px 0; }
.answer-list dt, .unanswered { color: var(--muted); }
.answer-list dd { margin: 0; text-align: right; font-weight: 600; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
.unanswered { font-weight: 400; }
.calculator-review > p { color: var(--muted); }
@media (max-width: 720px) { .answer-grid { grid-template-columns: 1fr; } }
@media print {
  .answer-review { break-inside: auto; }
  .answer-grid > section { break-inside: avoid; }
  .answer-edit, .calculator-review:not([open]) { display: none; }
}
</style>
</head>
<body>
  <a class="skip" href="#main">Skip to content</a>
  <header class="mast">
    <div class="frame mast-inner">
      <button id="homeButton" class="wordmark" type="button" aria-label="Beyond the Blue home"><i class="book-mark" aria-hidden="true"></i>Beyond the <em>Blue</em></button>
      <nav class="tools" aria-label="Plan tools">
        <button id="openPlan" type="button">Open plan</button>
        <button id="savePlan" type="button" hidden>Save progress</button>
      </nav>
      <input id="planFile" type="file" accept=".json,application/json" hidden>
    </div>
  </header>
  <main id="main" tabindex="-1">
    <div id="noticeWrap" class="frame" hidden><div id="notice" role="status" aria-live="polite"></div></div>
    <section id="welcome" aria-labelledby="welcomeTitle">
      <div class="frame hero">
        <div class="hero-copy">
          <p class="eyeline">For University of Kentucky students</p>
          <h1 id="welcomeTitle" tabindex="-1">Beyond the <em>Blue</em></h1>
          <p class="intro">See what’s left after bills, plan for a goal, and explore what a few dollars could do over time.</p>
          <div class="hero-actions">
            <button type="button" class="primary" id="start">Build my plan</button>
            <button type="button" class="hero-secondary" id="sample">Show me an example</button>
          </div>
          <p class="privacy">For education only. Not financial or investment advice.<br>Your numbers stay on this device.</p>
        </div>
        <figure class="week-card" aria-labelledby="week-title">
          <figcaption id="week-title">What if you saved a little each week?</figcaption>
          <fieldset class="week-options">
            <legend class="sr">Weekly amount</legend>
            <label><input type="radio" name="weekly" value="5" checked><span>$5</span></label>
            <label><input type="radio" name="weekly" value="10"><span>$10</span></label>
            <label><input type="radio" name="weekly" value="25"><span>$25</span></label>
          </fieldset>
          <div class="week-result"><output id="weeklyTotal" aria-live="polite">$260</output><span>after one year</span></div>
          <svg id="weekChart" viewBox="0 0 360 83" preserveAspectRatio="none" aria-hidden="true" focusable="false">
            <path class="chart-grid" d="M0 8H360 M0 42H360 M0 76H360"/>
            <path id="weekArea" class="chart-area"></path><path id="weekLine" class="chart-line"></path>
          </svg>
          <div class="axis"><span>Today</span><span>26 weeks</span><span>52 weeks</span></div>
          <p class="chart-caption">52 weekly deposits. Interest excluded.</p>
          <button type="button" class="sample-house" id="houseExample">Try a sample down payment</button>
        </figure>
      </div>
    </section>
    <section id="wizard" class="frame wizard" hidden aria-labelledby="questionTitle">
      <aside class="step-rail" aria-label="Plan sections">
        <h2>Your plan</h2>
        <ol id="sections"><li>Your month</li><li>Savings &amp; debt</li><li>Your goals</li><li>Saving pace</li></ol>
      </aside>
      <div class="form-sheet">
        <div class="step-meta"><span id="groupLabel"></span><span id="stepCount"></span></div>
        <progress id="progress" value="1" max="7" aria-label="Plan progress"></progress>
        <form id="stepForm" novalidate>
          <h1 id="questionTitle" tabindex="-1"></h1><p id="questionHint" class="question-hint"></p>
          <div id="fields"></div>
          <p id="formError" class="error" role="alert" hidden></p>
          <div class="form-nav"><button type="button" class="secondary" id="back">Back</button><button type="submit" class="primary" id="next">Continue</button></div>
        </form>
      </div>
    </section>
    <section id="overview" class="frame overview" hidden aria-labelledby="planTitle"></section>
    <noscript><p class="frame">Enable JavaScript in your browser to use the planner.</p></noscript>
  </main>
  <footer class="footer">
    <div class="frame footer-inner">
      <div class="credit"><strong>Beyond the Blue</strong> <span>by Andrew Escamilla</span><p>For education only. Not financial or investment advice.</p></div>
      <details id="info"><summary>Resources &amp; credits</summary>
        <div class="footer-content">
          <section><h2>Kentucky resources</h2>
            <ul><li><a href="https://studentsuccess.uky.edu/financial-wellness/services/financial-wellness-coaching-moneycats" target="_blank" rel="noopener noreferrer">UK MoneyCATS peer coaching</a></li>
            <li><a href="https://studentsuccess.uky.edu/financial-wellness/basic-needs" target="_blank" rel="noopener noreferrer">UK Basic Needs support</a></li></ul>
            <h2>Saving and investing</h2>
            <ul><li><a href="https://www.consumerfinance.gov/an-essential-guide-to-building-an-emergency-fund/" target="_blank" rel="noopener noreferrer">CFPB guide to emergency savings</a></li>
            <li><a href="https://www.investor.gov/introduction-investing/investing-basics/save-and-invest/gauge-your-risk-tolerance" target="_blank" rel="noopener noreferrer">Investor.gov guide to time and risk</a></li>
            <li><a href="https://www.investor.gov/introduction-investing/investing-basics/glossary/compound-interest" target="_blank" rel="noopener noreferrer">Investor.gov on compounding</a></li></ul>
          </section>
          <section><h2>Your data</h2><p>This page works offline. Your answers live in this tab. Save progress downloads a plain-text plan file you can reopen here. Anyone with that file can read it. Resource links open separately when you choose them.</p>
            <h2>Credits</h2><p>An independent student project by Andrew Escamilla, built with assistance from ChatGPT. The navy and orange palette draws on Globefin. All code and charts are part of this file. This project is independent of the University of Kentucky.</p></section>
        </div>
        <details class="license"><summary>MIT License</summary>
          <p>Copyright (c) 2026 Andrew Escamilla</p>
          <p>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:</p>
          <p>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.</p>
          <p>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.</p>
          <p>For published copies or adaptations, credit the original author on the page: “Based on Beyond the Blue by Andrew Escamilla.”</p>
        </details>
      </details>
    </div>
  </footer>
  <dialog id="replaceDialog" aria-labelledby="replaceTitle" aria-describedby="replaceText">
    <h2 id="replaceTitle">Replace your current plan?</h2>
    <p id="replaceText">You have unsaved changes. Keep editing to save them first.</p>
    <div class="dialog-actions"><button id="keepDraft" type="button" class="secondary" autofocus>Keep editing</button><button id="replaceDraft" type="button" class="primary">Replace plan</button></div>
  </dialog>
  <script>
'use strict';

const $ = id => document.getElementById(id);
const currency = new Intl.NumberFormat('en-US', {style: 'currency', currency: 'USD', minimumFractionDigits: 0, maximumFractionDigits: 2});
const money = value => currency.format(value || 0);
const cents = value => Math.round((value || 0) * 100);
const dollars = value => money(value / 100);
const escapeText = value => String(value).replace(/[&<>"']/g, ch => ({'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'}[ch]));
const paceRates = {Conservative: 25, Moderate: 50, Aggressive: 75};
const options = {
  year: ['First year', 'Sophomore', 'Junior', 'Senior', 'Graduate / returning student'],
  home: ['On campus', 'Renting off campus', 'Living with family'],
  work: ['Working while studying', 'Looking for work', 'Focused on school for now'],
  stable: ['Steady', 'Changes month to month'],
  debt: ['No expensive debt', 'Yes, I carry a balance', 'Not sure'],
  short: ['A cash cushion', 'Graduation or a move', 'A trip or experience', 'A car or big purchase', 'Less money stress', 'Extra cash savings'],
  long: ['A future home', 'Retirement', 'Financial freedom', 'I’m figuring it out'],
  loss: ['I need this money to stay steady', 'I could accept some ups and downs', 'I’m comfortable with large swings'],
  pace: Object.keys(paceRates),
  knowledge: ['Brand new', 'Know a little', 'Already investing']
};
const shortLabels = {
  'A cash cushion': 'My emergency cushion', 'Graduation or a move': 'Moving after graduation',
  'A trip or experience': 'A trip or experience', 'A car or big purchase': 'A car or a large purchase',
  'Less money stress': 'A little more flexibility', 'Extra cash savings': 'Extra cash savings'
};
// [label, default, minimum, maximum, step]. All assumptions are editable examples.
const studioFields = {
  homePrice: ['Home price at purchase', 250000, 50000, 1000000, 5000],
  downPct: ['Down payment', 10, 1, 100, 1],
  buyYears: ['Years until purchase', 8, 1, 40, 1],
  collegeDeposit: ['Monthly deposit in college', 25, 0, 1000, 5],
  laterDeposit: ['Monthly deposit after college', 250, 0, 3000, 5],
  semesters: ['Semesters until graduation', 4, 0, 12, 1],
  startCash: ['Already saved toward this goal', 0, 0, 200000, 100],
  cashRate: ['Cash savings annual rate', 2, 0, 10, 1],
  bondRate: ['Bond annual total return', 4, -10, 15, 1],
  stockRate: ['Stock annual total return', 7, -10, 15, 1],
  payBudget: ['Monthly pre-tax pay set aside', 100, 0, 500, 5],
  retireYears: ['Years until retirement', 40, 1, 50, 1],
  taxNow: ['Marginal tax rate today', 12, 0, 45, 1],
  taxLater: ['Marginal rate at withdrawal', 22, 0, 45, 1],
  marketDrop: ['Drop at purchase', 0, 0, 1, 1],
  studioView: ['Goal', 0, 0, 1, 1],
  holding: ['Investment held in both IRAs', 2, 0, 2, 1]
};
const studioDefaults = Object.fromEntries(Object.entries(studioFields).map(([key, field]) => [key, field[1]]));
const assets = [
  {name: 'Cash savings', rate: 'cashRate', shock: 0, color: '#276f69', dash: '2 4'},
  {name: 'Bond portfolio', rate: 'bondRate', shock: .06, color: '#9b4614', dash: '8 4'},
  {name: 'Stock portfolio', rate: 'stockRate', shock: .25, color: '#284d81', dash: 'none'}
];

const defaultValues = {
  ...studioDefaults, weekly: 5,
  year: '', home: '', work: '', stable: '', income: null, support: null, essentials: null,
  flex: null, minimum: null, cash: null, reserved: null, cushion: 500, debt: '', balance: null,
  short: '', target: null, months: 12, long: '', years: null, loss: '', pace: '', knowledge: '',
  labMonthly: 5, labYears: 10, labRate: 5
};
const sampleValues = {
  ...defaultValues, year: 'Junior', home: 'Renting off campus', work: 'Working while studying',
  stable: 'Changes month to month', income: 1350, support: 200, essentials: 1000, flex: 150,
  minimum: 0, cash: 600, reserved: 200, cushion: 500, debt: 'No expensive debt',
  short: 'Graduation or a move', target: 1000, months: 12, long: 'Financial freedom',
  years: 20, loss: 'I could accept some ups and downs', pace: 'Moderate'
};
const numberLimits = {
  cushion: [0.01, 1000000000], months: [1, 120, 1], years: [1, 50, 1],
  balance: [0.01, 1000000000], labMonthly: [0, 100, 1], labYears: [1, 40, 1]
};
const defaultLimits = [0, 1000000000];
let values = {...defaultValues};
let step = 0, started = false, dirty = false, example = false, editing = false, screen = 'home';
let pendingReplacement = null, openRequest = 0, editBackup = null;

function help(title, html) {
  return '<details class="disclosure"><summary>' + title + '</summary><div class="help-content">' + html + '</div></details>';
}
function numberField(key, label, hint = '', unit = '$', required = false) {
  const [min, max, grid = .01] = numberLimits[key] || defaultLimits;
  const hasHint = hint ? ' aria-describedby="' + key + 'Hint"' : '';
  const prefix = unit === '$' ? '<span class="currency-symbol" aria-hidden="true">$</span>' : '';
  return '<div class="field"><label for="' + key + '">' + label + '</label><div class="input-wrap">' + prefix +
    '<input type="number" id="' + key + '" data-key="' + key + '" class="' + (prefix ? 'money-input' : '') +
    '" inputmode="' + (grid === 1 ? 'numeric' : 'decimal') + '" min="' + min + '" max="' + max +
    '" step="' + grid + '" value="' + (values[key] ?? '') + '"' + (required ? ' required' : '') + hasHint + '></div>' +
    (hint ? '<span class="field-hint" id="' + key + 'Hint">' + hint + '</span>' : '') + '</div>';
}
function selectField(key, label, placeholder = 'Choose one', labels = {}, required = false) {
  const choices = key === 'short' && values.short !== 'Extra cash savings'
    ? options.short.filter(value => value !== 'Extra cash savings') : options[key];
  const items = choices.map(value => '<option value="' + escapeText(value) + '"' +
    (value === values[key] ? ' selected' : '') + '>' + escapeText(labels[value] || value) + '</option>').join('');
  return '<div class="field"><label for="' + key + '">' + label + '</label><select id="' + key +
    '" data-key="' + key + '"' + (required ? ' required' : '') + '><option value="">' + placeholder + '</option>' + items + '</select></div>';
}
function radioChoices(key, legend, labels = {}, descriptions = {}, amounts = {}) {
  return '<fieldset class="choices" id="' + key + '" tabindex="-1"><legend class="sr">' + legend + '</legend>' +
    options[key].map((value, i) => '<label class="choice"><input type="radio" name="' + key + '" id="' + key + i +
      '" data-key="' + key + '" value="' + escapeText(value) + '"' + (values[key] === value ? ' checked' : '') +
      '><span class="choice-main"><strong>' + escapeText(labels[value] || value) + '</strong>' +
      (descriptions[value] ? '<small>' + escapeText(descriptions[value]) + '</small>' : '') + '</span>' +
      (amounts[value] ? '<span class="amount">' + escapeText(amounts[value]) + '</span>' : '') + '</label>').join('') + '</fieldset>';
}
function incomeFields() {
  return numberField('income', 'Take-home pay per month', 'Enter 0 if you aren’t receiving a paycheck.', '$', true) +
    numberField('support', 'Other regular support per month (optional)', 'Include money you receive regularly for living costs.') +
    '<label class="check"><input type="checkbox" data-key="stable" id="stable"' + (values.stable === options.stable[1] ? ' checked' : '') +
    '>My income changes month to month</label><p id="variableTip" class="subtle"' +
    (values.stable === options.stable[1] ? '' : ' hidden') + '>Use what you can count on in a quieter month.</p>' +
    help('About your semester (optional)', selectField('year', 'Year in school', 'Select year') +
      selectField('home', 'Living situation', 'Select housing') + selectField('work', 'Work situation', 'Select situation')) +
    help('How do I count financial aid?', '<p>If you already received aid for the term, include it in your cash balance on the savings screen. Reserve unspent loan money and grants committed to bills so those dollars stay out of your savings goal.</p>');
}
function spendingFields() {
  const housing = {'On campus': 'Include campus or meal-plan bills you still pay yourself.', 'Renting off campus': 'Include your share of rent, utilities and groceries.', 'Living with family': 'Count only the share of household costs you pay.'}[values.home] || 'Count rent, groceries, transportation and school costs you pay yourself.';
  return numberField('essentials', 'Monthly essentials', housing + ' Enter 0 if these are covered.', '$', true) +
    numberField('flex', 'Flexible spending (optional)', 'Eating out, subscriptions and other everyday choices.') +
    numberField('minimum', 'Required debt payments (optional)', 'Include only the minimums due this month.') +
    '<div class="quick-result"><span id="cashFlowLabel">Left after bills</span><strong id="cashFlowValue"></strong></div>' +
    help('What about a semester bill?', '<p>If cash is already set aside for tuition or rent, reserve it on the next screen. Count only the part you still need to cover from monthly income here.</p>');
}
function savingsFields() {
  return numberField('cash', 'Total in checking and savings', '', '$', true) +
    numberField('reserved', 'Cash already committed (optional)', 'Include money for upcoming bills and unspent student loan funds. Count each dollar once.') +
    numberField('cushion', 'Emergency cushion target', '$500 is an example. Choose an amount that could cover a surprise expense.', '$', true) +
    help('Which dollars count?', '<p>Start with cash you can access. Subtract the part committed to bills. The rest counts toward your cushion first, then toward your next goal.</p>');
}
function debtFields() {
  return radioChoices('debt', 'Do you carry high-interest debt?', {'No expensive debt': 'No', 'Yes, I carry a balance': 'Yes', 'Not sure': 'I’m not sure'}) +
    '<div id="debtExtra"' + (values.debt === options.debt[1] ? '' : ' hidden') + '>' +
    numberField('balance', 'Balance left after this month’s minimums (optional)', 'Use the amount still owed on high-interest debt. Leave blank if you need to check.') + '</div>' +
    help('What counts as high-interest debt?', '<p>A credit card balance that carries over and accrues interest is a common example. Paying a statement in full each month is different. Your statement shows the interest rate and balance.</p>');
}
function shortFields() {
  return selectField('short', 'Short-term goal', 'Choose a goal', shortLabels, true) +
    '<div id="targetRow"' + (values.short && values.short !== options.short[0] ? '' : ' hidden') + '>' +
    numberField('target', 'Goal amount', 'Separate from your cushion. Enter 0 if you’re still pricing it.') + '</div>' +
    '<p class="quick-result" id="onlyCushion"' + (values.short === options.short[0] ? '' : ' hidden') +
    '><span>Cushion target you chose</span><strong>' + money(values.cushion) + '</strong></p>' +
    numberField('months', 'How many months from now?', '', '', true);
}
function longFields() {
  return selectField('long', 'Long-term goal', 'Choose a goal', {}, true) +
    numberField('years', 'How many years away? (optional)', 'An estimate is fine.', '') +
    help('How do you feel about investment risk? (optional)', selectField('loss', 'If this money fell in value', 'Choose a response') +
      '<p>Your response is a reminder of your comfort with risk. You decide how to use your money.</p>');
}
function paceFields() {
  const remainder = planMath().net;
  const amounts = {}, descriptions = {};
  for (const [pace, percent] of Object.entries(paceRates)) {
    amounts[pace] = dollars(Math.round(Math.max(0, remainder) * percent / 100));
    descriptions[pace] = percent + '% of what’s left';
  }
  return '<div class="quick-result"><span>' + (remainder < 0 ? 'Monthly gap' : 'Left after bills') + '</span><strong>' + dollars(Math.abs(remainder)) + '</strong></div>' +
    (remainder <= 0 ? '<p class="subtle">This month’s amount is $0. Your pace can apply when you have money left over.</p>' : '') +
    radioChoices('pace', 'Saving pace', {}, descriptions, amounts) +
    help('What does the pace change?', '<p>Only the money left after your spending is split. The rest stays flexible. These percentages are examples you can compare, and they do not set your investment risk.</p>');
}
const groups = ['Your month', 'Savings & debt', 'Your goals', 'Saving pace'];
const steps = [
  {group: 0, title: 'What comes in each month?', hint: 'Use after-tax amounts. Estimates are fine.', body: incomeFields},
  {group: 0, title: 'What goes out each month?', hint: 'Enter the costs you cover from monthly income.', body: spendingFields},
  {group: 1, title: 'How much cash can you use?', hint: 'Separate money for bills from money you can keep.', body: savingsFields},
  {group: 1, title: 'Do you carry high-interest debt?', hint: 'Think about balances that charge you interest from month to month.', body: debtFields},
  {group: 2, title: 'What are you saving for first?', hint: 'Choose a goal you’d like to cover in the next few months or years.', body: shortFields},
  {group: 2, title: 'What would you like money to do later?', hint: 'Think beyond this semester. It’s fine if you’re still deciding.', body: longFields},
  {group: 3, title: 'Which saving pace fits you?', hint: 'Choose how much of your monthly remainder to set aside for priorities.', body: paceFields}
];
const editLabels = ['Income', 'Spending', 'Cash & cushion', 'Debt', 'Short-term goal', 'Long-term goal', 'Saving pace'];

function planMath(s = values) {
  // All budget operations use integer cents. Only the selected share needs rounding.
  const income = cents(s.income) + cents(s.support);
  const spending = cents(s.essentials) + cents(s.flex) + cents(s.minimum);
  const net = income - spending;
  const budget = Math.round(Math.max(0, net) * (paceRates[s.pace] || 0) / 100);
  const cash = Math.max(0, cents(s.cash) - cents(s.reserved));
  const cushionTarget = cents(s.cushion), cushionSaved = Math.min(cash, cushionTarget);
  const cushionGap = cushionTarget - cushionSaved;
  const target = s.short === options.short[0] ? 0 : cents(s.target);
  const goalSaved = Math.min(target, Math.max(0, cash - cushionSaved));
  const goalGap = target - goalSaved;
  const toCushion = Math.min(budget, cushionGap);
  let left = budget - toCushion;
  const debtKnown = s.debt === options.debt[1] && s.balance > 0;
  const debtReview = s.debt === 'Not sure' || (s.debt === options.debt[1] && !debtKnown);
  const toDebt = debtReview ? left : debtKnown ? Math.min(left, cents(s.balance)) : 0;
  left -= toDebt;
  const toGoal = Math.min(left, goalGap);
  return {income, spending, net, budget, cash, cushionTarget, cushionSaved, cushionGap, target, goalSaved, goalGap,
    debtKnown, debtReview, toCushion, toDebt, toGoal, unassigned: left - toGoal, flexible: Math.max(0, net) - budget};
}
function futureValue(monthly, years, rate) {
  const months = years * 12;
  if (!rate) return monthly * months;
  // Annual effective rate, equal monthly periods, end-of-month deposits.
  const logMonthly = Math.log1p(rate / 100) / 12;
  return monthly * Math.expm1(months * logMonthly) / Math.expm1(logMonthly);
}
function validateNumber(key, value) {
  if (value === null) return true;
  if (typeof value !== 'number' || !Number.isFinite(value)) return false;
  if (key === 'labRate') return [-5, 0, 5].includes(value);
  const [min, max, grid = .01] = numberLimits[key] || defaultLimits;
  return value >= min && value <= max && (grid === 1 ? Number.isInteger(value) : Math.abs(value - Math.round(value * 100) / 100) < 0.0000001);
}
function stepIssue(index, s = values, partial = false) {
  const required = [['income'], ['essentials'], ['cash', 'cushion'], ['debt'], ['short', 'months'], ['long'], ['pace']];
  if (!partial) {
    if (index === 4 && s.short && s.short !== options.short[0]) required[4].push('target');
    const key = required[index].find(key => s[key] === '' || s[key] === null);
    if (key) return {key, message: key in options ? 'Choose an option to continue.' : 'Enter an amount or time to continue.'};
  }
  if (index === 2 && s.cash !== null && s.reserved > s.cash) {
    return {key: 'reserved', message: 'The amount set aside for bills can’t exceed your total cash.'};
  }
  return null;
}
function notify(message = '', isError = false) {
  $('noticeWrap').hidden = !message;
  $('noticeWrap').dataset.error = String(isError);
  $('notice').textContent = message;
  if (message && isError) $('noticeWrap').scrollIntoView({block: 'nearest'});
}
function showScreen(name) {
  screen = name;
  document.body.dataset.screen = name;
  $('welcome').hidden = name !== 'home';
  $('wizard').hidden = name !== 'wizard';
  $('overview').hidden = name !== 'plan';
  $('savePlan').hidden = !started && !dirty && values.weekly === 5;
  $('savePlan').textContent = name === 'plan' ? 'Save plan' : 'Save progress';
  $('houseExample').hidden = started;
  $('info').open = false;
}
function focusHeading(id) {
  $(id).focus({preventScroll: true});
  window.scrollTo(0, 0);
}
function showHome(moveFocus = true) {
  showScreen('home');
  $('start').textContent = started ? (step === steps.length ? 'Return to plan' : 'Continue my plan') : 'Build my plan';
  $('sample').textContent = started ? 'Start a new plan' : 'Show me an example';
  if (moveFocus) focusHeading('welcomeTitle');
}
function showStep(index, returnToPlan = false) {
  if (returnToPlan && !editing) editBackup = {values: {...values}, dirty};
  if (!returnToPlan) editBackup = null;
  started = true; step = index; editing = returnToPlan;
  showScreen('wizard'); notify();
  const question = steps[index];
  $('questionTitle').textContent = question.title;
  $('questionHint').textContent = question.hint;
  $('groupLabel').textContent = (example ? 'Sample · ' : '') + groups[question.group];
  $('stepCount').textContent = 'Step ' + (index + 1) + ' of ' + steps.length;
  $('progress').value = index + 1;
  [...$('sections').children].forEach((item, i) => {
    if (i === question.group) item.setAttribute('aria-current', 'step'); else item.removeAttribute('aria-current');
  });
  $('fields').className = 'fields';
  $('fields').innerHTML = question.body();
  $('formError').hidden = true;
  $('back').textContent = editing ? 'Cancel edit' : 'Back';
  $('next').textContent = editing ? 'Update my plan' : index === steps.length - 1 ? 'See my plan' : 'Continue';
  refreshFields();
  focusHeading('questionTitle');
}
function refreshFields() {
  if (step === 1 && $('cashFlowValue')) {
    const net = planMath().net;
    $('cashFlowLabel').textContent = net < 0 ? 'Monthly gap' : 'Left after bills';
    $('cashFlowValue').textContent = values.essentials === null ? '—' : dollars(Math.abs(net));
  }
  if ($('variableTip')) $('variableTip').hidden = values.stable !== options.stable[1];
  if ($('debtExtra')) {
    $('debtExtra').hidden = values.debt !== options.debt[1];
    $('balance').disabled = $('debtExtra').hidden;
  }
  if ($('targetRow')) {
    $('targetRow').hidden = !values.short || values.short === options.short[0];
    $('target').disabled = $('targetRow').hidden;
    $('target').required = !$('targetRow').hidden;
    $('onlyCushion').hidden = values.short !== options.short[0];
  }
}
function showIssue(issue) {
  $('formError').textContent = issue.message;
  $('formError').hidden = false;
  const el = $(issue.key);
  if (!el) return;
  for (let p = el.parentElement; p; p = p.parentElement) if (p.tagName === 'DETAILS') p.open = true;
  (el.querySelector('input') || el).focus();
}
function currentValid(partial = false) {
  if (screen !== 'wizard') return true;
  for (const input of $('fields').querySelectorAll('input[type=number]:not(:disabled)')) {
    if (input.validity.badInput || (!input.validity.valueMissing && !input.validity.valid)) {
      showIssue({key: input.id, message: input.validationMessage});
      return false;
    }
  }
  const issue = stepIssue(step, values, partial);
  if (issue) { showIssue(issue); return false; }
  return true;
}
function firstIncomplete(s = values) { return steps.findIndex((_, i) => stepIssue(i, s)); }
function updateAnswer(event) {
  const input = event.target, key = input.dataset.key;
  if (!key || input.disabled || (input.type === 'radio' && !input.checked)) return;
  let value = input.value;
  if (input.type === 'checkbox') value = input.checked ? options.stable[1] : 'Steady';
  if (input.type === 'number' || input.type === 'range') value = input.value === '' ? null : input.valueAsNumber;
  values[key] = value;
  if (key === 'long' && (value === 'Retirement' || value === 'A future home')) values.studioView = Number(value === 'Retirement');
  dirty = true; notify();
  $('formError').hidden = true;
  if (key === 'debt' && value !== options.debt[1]) { values.balance = null; if ($('balance')) $('balance').value = ''; }
  if (key === 'short' && value === options.short[0]) { values.target = null; if ($('target')) $('target').value = ''; }
  refreshFields();
}
$('fields').addEventListener('input', updateAnswer);
$('stepForm').addEventListener('submit', event => {
  event.preventDefault();
  if (!currentValid()) return;
  dirty = true;
  if (!editing && step < steps.length - 1) { showStep(step + 1); return; }
  const missing = firstIncomplete();
  if (missing >= 0) { showStep(missing); return; }
  showPlan();
});
$('back').addEventListener('click', () => {
  if (editing) {
    if (editBackup) { values = editBackup.values; dirty = editBackup.dirty; }
    showPlan(); return;
  }
  if (!currentValid(true)) return;
  if (step > 0) { dirty = true; showStep(step - 1); } else showHome();
});

function meter(label, amount, scale, warm = false, suffix = '') {
  const percent = scale > 0 ? Math.max(0, Math.min(100, amount * 100 / scale)) : 0;
  return '<div class="meter"><div class="meter-label"><span>' + escapeText(label) + '</span><strong>' +
    dollars(amount) + suffix + '</strong></div><div class="track" aria-hidden="true"><i' +
    (warm ? ' class="warm"' : '') + ' style="width:' + percent + '%"></i></div></div>';
}
function monthText(n) { return n + (n === 1 ? ' month' : ' months'); }
function actionCard(m) {
  let headline, text;
  if (m.net < 0) {
    headline = 'Your monthly gap is ' + dollars(-m.net) + '.';
    text = 'Check which costs are due before your next paycheck. If rent or groceries are hard to cover, ' +
      '<a href="https://studentsuccess.uky.edu/financial-wellness/basic-needs" target="_blank" rel="noopener noreferrer">UK Basic Needs can help you find support</a>.';
  } else if (!m.budget) {
    headline = 'There’s ' + dollars(m.net) + ' left after bills.';
    text = m.net === 0 ? 'Your plan sets aside $0 this month. Check one upcoming bill or pay date, then revisit your numbers.' :
      'At this pace, the amount to set aside rounds to $0 this month.';
  } else if (m.unassigned === m.budget) {
    const unpriced = !m.target && values.short !== options.short[0];
    headline = unpriced ? 'Put a price on your next goal.' : 'Your current savings targets are covered.';
    text = unpriced ? 'Your cushion is covered. You have ' + dollars(m.budget) + ' available at this pace once you know what the goal costs.' :
      'Your pace leaves ' + dollars(m.budget) + ' available this month. You can choose another goal or keep that money flexible.';
  } else {
    headline = 'Set aside ' + dollars(m.budget) + ' this month.';
    if (m.toCushion > 0) text = 'Put the first ' + dollars(m.toCushion) + ' toward your emergency cushion.';
    else if (m.toDebt > 0) text = m.debtReview ? 'Hold this money until you check your balance and interest rate.' : 'Use ' + dollars(m.toDebt) + ' for an extra debt payment after your required minimums.';
    else text = 'Put ' + dollars(m.toGoal) + ' toward your short-term goal.';
    text += ' Your ' + values.pace.toLowerCase() + ' pace leaves ' + dollars(m.flexible) + ' flexible after bills.';
  }
  const rows = [['Emergency cushion', m.toCushion], [m.debtReview ? 'Hold for debt review' : 'Extra debt payment', m.toDebt],
    ['Short-term goal', m.toGoal], ['Unassigned', m.unassigned]].filter(row => row[1] > 0);
  return '<section class="action-card"><p class="caption">This month</p><h2>' + headline +
    '</h2><p>' + text + '</p>' + (rows.length > 1 ? '<ul class="allocation">' + rows.map(([label, value]) =>
      '<li>' + label + ' <strong>' + dollars(value) + '</strong></li>').join('') + '</ul>' : '') + '</section>';
}
function goalTiming(m) {
  const cushionOnly = values.short === options.short[0];
  const gap = cushionOnly ? m.cushionGap : m.goalGap;
  if (!cushionOnly && m.target === 0) return 'Your target is $0. Add an amount when you know the cost.';
  if (gap === 0) return 'Covered by the cash you have today.';
  if (m.budget <= 0) return 'No monthly savings are available at this pace. Revisit the date when your budget changes.';
  if (!cushionOnly && m.goalGap > m.toGoal && (m.debtReview || m.debtKnown)) return 'Check your debt balance and interest before estimating a finish date.';
  const months = cushionOnly ? Math.ceil(m.cushionGap / m.budget) :
    m.toGoal >= m.goalGap ? 1 : Math.ceil((m.cushionGap + m.goalGap) / m.budget);
  return 'About ' + monthText(months) + ' at this pace' + (months > values.months ?
    ', past your ' + values.months + '-month target.' : ', within your ' + values.months + '-month target.');
}
function goalCard(m) {
  const cushionOnly = values.short === options.short[0];
  const title = shortLabels[values.short];
  const current = cushionOnly ? m.cushionSaved : m.goalSaved;
  const target = cushionOnly ? m.cushionTarget : m.target;
  const longGoal = values.long === 'I’m figuring it out' ? 'Still exploring' : values.long;
  const horizon = values.years ? ' · ' + values.years + (values.years === 1 ? ' year' : ' years') : '';
  const nextLong = {'A future home': 'Price a down payment and choose a date to work toward.',
    Retirement: 'When you start a job, check whether its retirement plan offers a match.',
    'Financial freedom': 'Price one future choice, such as taking a month between jobs.',
    'I’m figuring it out': 'Pick one future expense to explore when you revisit your plan.'}[values.long];
  return '<section class="paper-card"><h2>Your goals</h2><div class="goal-block">' +
    (cushionOnly ? '' : meter('Emergency cushion', m.cushionSaved, m.cushionTarget, false, ' of ' + dollars(m.cushionTarget))) +
    meter(title, current, target, true, ' of ' + dollars(target)) + '<p>' + goalTiming(m) +
    '</p></div><div class="goal-block"><h3>Longer term · ' + escapeText(longGoal + horizon) + '</h3><p>' + nextLong + '</p></div></section>';
}
function cashCard(m) {
  const scale = Math.max(m.income, m.spending);
  return '<section class="paper-card"><h2>Your monthly budget</h2>' + meter('Money in', m.income, scale) +
    meter('Money out', m.spending, scale, true) + '<div class="fact"><span>' + (m.net < 0 ? 'Monthly gap' : 'Left after bills') +
    '</span><strong>' + dollars(Math.abs(m.net)) + '</strong></div>' +
    '<p class="subtle">' + (values.stable === options.stable[1] ? 'With changing income, check these numbers after a quieter month.' :
      'Includes the expenses and required payments you entered.') + '</p></section>';
}
function mathDetails(m) {
  const lines = [
    ['Income less spending', dollars(m.income) + ' − ' + dollars(m.spending) + ' = ' + dollars(m.net)],
    [values.pace + ' saving pace', paceRates[values.pace] + '% × ' + dollars(Math.max(0, m.net)) + ' = ' + dollars(m.budget)],
    ['Cash after reserved bills', money(values.cash) + ' − ' + money(values.reserved) + ' = ' + dollars(m.cash)],
    ['Emergency cushion today', dollars(m.cushionSaved) + ' of ' + dollars(m.cushionTarget)]
  ];
  if (m.target) lines.push(['Additional goal today', dollars(m.goalSaved) + ' of ' + dollars(m.target)]);
  const freeCash = m.cash - m.cushionSaved - m.goalSaved;
  if (freeCash > 0) lines.push(['Cash above both targets', dollars(freeCash)]);
  let note = 'Monthly amounts round to the nearest cent. The plan fills your cushion first, then covers extra debt payments or a debt review, then your short-term goal. Any remainder is yours to assign. Cash is counted once. Goal dates assume unchanged monthly amounts and no interest.';
  if (m.net < 0 && m.cash) note += ' Using cash to cover a monthly gap reduces what is available for your goals.';
  if (m.debtKnown) note += ' The extra payment is capped at the ' + money(values.balance) + ' you entered after required minimums. Verify the current balance on your statement.';
  if (values.loss) note += ' Your response about risk was “' + values.loss + '.”';
  return '<details class="disclosure fold" id="mathDetails"><summary>How the numbers work</summary><div class="fold-body"><div>' +
    lines.map(([label, value]) => '<div class="fact"><span>' + escapeText(label) + '</span><strong>' + escapeText(value) + '</strong></div>').join('') +
    '</div><p>' + escapeText(note) + '</p></div></details>';
}
function studioUnit(key, value) {
  if (['downPct','cashRate','bondRate','stockRate','taxNow','taxLater'].includes(key)) return value + '%';
  if (['retireYears','buyYears'].includes(key)) return value + (value === 1 ? ' year' : ' years');
  if (key === 'semesters') return value + (value === 1 ? ' semester' : ' semesters');
  return money(value);
}
function studioSlider(key) {
  const [label,, min, max, stride] = studioFields[key], v = values[key];
  return '<div class="studio-field"><label for="s-' + key + '">' + label + '<strong id="out-' + key + '">' + studioUnit(key,v) +
    '</strong></label><input id="s-' + key + '" data-studio="' + key + '" type="range" min="' + min + '" max="' + max +
    '" step="' + stride + '" value="' + v + '" aria-valuetext="' + studioUnit(key,v) + '"></div>';
}
function studioSettings(keys) { return '<div class="studio-settings">' + keys.map(studioSlider).join('') + '</div>'; }
function housingProjection(s) {
  const months = s.buyYears * 12, school = Math.min(months, s.semesters * 6);
  const target = s.homePrice * s.downPct / 100;
  const deposits = s.startCash + school * s.collegeDeposit + (months - school) * s.laterDeposit;
  const paths = assets.map(asset => {
    const factor = Math.pow(1 + s[asset.rate] / 100, 1 / 12);
    let balance = s.startCash, delayed = s.startCash;
    const points = [[0,balance]];
    for (let m = 1; m <= months; m++) {
      balance = balance * factor + (m <= school ? s.collegeDeposit : s.laterDeposit);
      delayed = delayed * factor + (m <= school ? 0 : s.laterDeposit);
      if (m % 12 === 0 || m === school) points.push([m,balance]);
    }
    if (s.marketDrop) {
      balance *= 1 - asset.shock; delayed *= 1 - asset.shock;
      points.push([months,balance]);
    }
    return {asset, points, balance, delayed};
  });
  return {months,school,target,deposits,paths};
}
function houseChart(model) {
  const top = Math.max(1, ...model.paths.flatMap(p => p.points.map(point => point[1])));
  const x = m => 68 + 466 * m / model.months, y = v => 145 - 117 * v / top;
  const tick = new Intl.NumberFormat('en-US',{style:'currency',currency:'USD',notation:'compact',maximumFractionDigits:1});
  const grid = [0, .5, 1].map(r => '<line x1="68" x2="534" y1="'+y(r*top)+'" y2="'+y(r*top)+'" stroke="#d6dee3"/><text x="59" y="'+(y(r*top)+4)+'" text-anchor="end">'+tick.format(top*r)+'</text>').join('');
  const lines = model.paths.map(({asset,points}) => '<polyline fill="none" stroke="'+asset.color+'" stroke-width="3" stroke-dasharray="'+asset.dash+'" points="'+
    points.map(([m,v])=>x(m).toFixed(1)+','+y(v).toFixed(1)).join(' ')+'"/>').join('');
  const grad = model.school > 0 && model.school < model.months ? '<line x1="'+x(model.school)+'" x2="'+x(model.school)+'" y1="23" y2="145" stroke="#657a86" stroke-dasharray="3 4"/><text x="'+Math.min(455,Math.max(110,x(model.school)))+'" y="15" text-anchor="middle">Graduation</text>' : '';
  return '<svg class="studio-chart" viewBox="0 0 552 173" role="img" aria-label="Projected balance from today to purchase. Ending balances and gaps are listed below.">'+grid+grad+lines+
    '<text x="68" y="166">Today</text><text x="534" y="166" text-anchor="end">Year '+model.months/12+'</text></svg>';
}
function houseResults(s) {
  const m = housingProjection(s);
  const rows = m.paths.map(({asset,balance}) => {
    const gap = (cents(m.target) - cents(balance)) / 100;
    return '<tr><th scope="row"><span class="asset-key" style="border-color:'+asset.color+';border-top-style:'+
      (asset.dash==='2 4'?'dotted':asset.dash==='8 4'?'dashed':'solid')+'"></span>'+asset.name+' <small>'+s[asset.rate]+'%</small></th><td>'+money(balance)+'</td><td>'+
      (gap===0?'On target':money(Math.abs(gap))+(gap>0?' short':' over'))+'</td></tr>';
  }).join('');
  const remainingCents = Math.max(0, cents(m.target) - cents(s.startCash) - m.school * cents(s.collegeDeposit));
  const monthlyCents = m.months > m.school ? Math.ceil(remainingCents / (m.months - m.school)) : 0;
  const finish = m.months > m.school ? 'Keeping the college deposits, the monthly amount needed after graduation with zero growth is <strong>'+dollars(monthlyCents)+'</strong>.' :
    'Your purchase date falls within the college phase. The after-college deposit starts after this goal date.';
  const early = m.school > 0 && s.collegeDeposit > 0 ? '<p class="studio-note"><strong>Start now or wait?</strong> During college you put in '+money(m.school*s.collegeDeposit)+
    '. In the stock example, starting those deposits now adds '+money(m.paths[2].balance-m.paths[2].delayed)+' at purchase compared with waiting until graduation. Both paths keep the same starting cash.</p>' : '';
  const earlyChart = early ? help('Compare the two start dates', meter('Start in college', cents(m.paths[2].balance), cents(m.paths[2].balance)) +
    meter('Wait until graduation', cents(m.paths[2].delayed), cents(m.paths[2].balance), true) +
    '<p>Both use the stock example and your selected purchase date. The only difference is whether deposits begin during college.</p>') : '';
  return '<div class="studio-total"><span>Down payment target</span><strong>'+money(m.target)+'</strong><small>'+s.downPct+'% of '+money(s.homePrice)+' · hypothetical returns</small></div>'+
    houseChart(m)+'<table class="studio-table"><caption class="sr">Balance and distance from your down payment after '+s.buyYears+' years</caption><thead><tr><th>Example</th><th>Before tax at purchase</th><th>vs. target</th></tr></thead><tbody>'+rows+'</tbody></table>'+
    '<p>Your starting cash and deposits total <strong>'+money(m.deposits)+'</strong>. '+finish+'</p>'+ (s.buyYears<=5 && !s.marketDrop ? '<p class="studio-note">A purchase within five years leaves little time to recover from a loss. Try the market drop to see the balance on closing day.</p>' : '') +early+earlyChart;
}
function iraProjection(s) {
  const rate = s[assets[s.holding].rate], rothDeposit = s.payBudget*(1-s.taxNow/100);
  const beforeTax = futureValue(s.payBudget,s.retireYears,rate);
  return {rothDeposit, roth:futureValue(rothDeposit,s.retireYears,rate), beforeTax, traditional:beforeTax*(1-s.taxLater/100)};
}
function retirementResults(s) {
  const p = iraProjection(s), scale = Math.max(cents(p.roth),cents(p.traditional),1);
  const difference = Math.abs(cents(p.roth)-cents(p.traditional));
  const compare = difference ? (p.roth > p.traditional ? 'Roth' : 'Traditional')+' finishes '+dollars(difference)+' higher under these tax assumptions.' : 'Both accounts finish with the same spendable amount under these assumptions.';
  return '<div class="studio-total"><span>At retirement</span><strong>'+s.retireYears+' years</strong><small>Same '+money(s.payBudget)+' of pre-tax pay per month · '+s[assets[s.holding].rate]+'% assumed annual return</small></div>'+
    meter('Roth IRA · after tax',cents(p.roth),scale)+meter('Traditional IRA · after tax',cents(p.traditional),scale,true)+
    '<p><strong>'+compare+'</strong></p><div class="account-explain"><p><b>Roth IRA</b> · Pay '+money(s.payBudget-p.rothDeposit)+' in tax each month and deposit '+money(p.rothDeposit)+'. The example assumes a qualified tax-free withdrawal.</p>'+
    '<p><b>Traditional IRA</b> · Deposit the full '+money(s.payBudget)+' with a full deduction. At withdrawal, '+money(p.beforeTax)+' before tax becomes '+money(p.traditional)+' after tax.</p></div>'+
    '<p class="studio-note">Try matching the two tax rates. With the same holding, fees and tax rates, the results match when you start with equal pre-tax pay.</p>';
}
function studioPanel() {
  const house = !values.studioView;
  const inputs = house ? studioSettings(['collegeDeposit','laterDeposit','buyYears'])+
    help('House price, down payment and graduation',studioSettings(['homePrice','downPct','semesters','startCash']))+
    '<label class="check"><input type="checkbox" data-studio="marketDrop" '+(values.marketDrop?'checked':'')+'>Test a market drop just before buying</label><small class="field-hint">One sudden drop at purchase: stocks −25%, bonds −6%, cash unchanged. This is a stress test.</small>' :
    studioSettings(['payBudget','retireYears'])+'<div class="field"><label for="s-holding">Holding inside both accounts</label><select id="s-holding" data-studio="holding">'+assets.map((a,i)=>'<option value="'+i+'" '+(values.holding===i?'selected':'')+'>'+a.name+'</option>').join('')+'</select></div>'+
    help('Change the tax rates',studioSettings(['taxNow','taxLater']));
  const rates = house ? assets.map(a=>a.rate) : [assets[values.holding].rate];
  return '<p class="studio-intro">'+(house?'Try a small deposit while you’re at UK and a different amount after graduation. Compare the same dollars in three places.':
    'Roth and traditional IRAs are retirement accounts. Either can hold investments such as stocks or bonds. Compare the same investment with two ways of paying tax.')+
    '</p><div class="studio-grid"><div class="studio-controls">'+inputs+help('Change assumed returns',studioSettings(rates))+'</div><div id="studioResults" class="studio-results">'+
    (house?houseResults(values):retirementResults(values))+'</div></div>'+
    help(house?'How to read the three paths':'Account rules and assumptions',house?
    '<p><b>Cash savings.</b> Interest can change. Accessible cash can cover a purchase on a fixed date.</p><p><b>Fixed income.</b> Bonds are loans that can pay interest. Bond prices can fall when rates rise, and issuers can default. The bond example reinvests income.</p><p><b>Stocks.</b> A diversified stock portfolio represents ownership across companies. Its value can fall sharply, even near a purchase date. For a goal five years away or sooner, a loss may leave little time to recover.</p><p>Rates are illustrative annual assumptions. Actual returns vary each year and can be negative. Each semester is six months. Deposits arrive at month-end. The model uses effective annual returns and a fixed purchase price. Closing costs, taxes, fees and inflation are excluded.</p><p><a href="https://www.investor.gov/introduction-investing/investing-basics/save-and-invest/gauge-your-risk-tolerance" target="_blank" rel="noopener noreferrer">Investor.gov · Time horizon and risk</a></p>':
    '<p>This example assumes eligible contributions, equal pre-tax earnings, a fully deductible traditional contribution, a flat marginal income tax on the entire traditional withdrawal, and a qualified Roth withdrawal. It excludes fees, penalties, inflation and other taxes. Both paths use monthly deposits at month-end. The time slider sets the example’s length. A short horizon alone does not make a Roth withdrawal qualified.</p><p>IRA contributions generally require taxable compensation earned by you or, on a joint return, your spouse. An annual limit applies across traditional and Roth IRAs combined. Roth contributions also have income limits. Workplace plan coverage and income can limit a traditional IRA deduction. Early withdrawals can have different tax consequences. The home example uses a separate, nonretirement pool of money.</p><p><a href="https://www.irs.gov/retirement-plans/traditional-and-roth-iras" target="_blank" rel="noopener noreferrer">IRS · Traditional and Roth IRAs</a></p>');
}
function goalStudio() {
  return '<section class="paper-card goal-studio" aria-labelledby="studioTitle"><h2 id="studioTitle" tabindex="-1">Explore a future goal</h2><p class="field-hint">Illustrative amounts. Change them freely without changing your budget.</p>'+
    '<fieldset class="studio-switch"><legend class="sr">Choose a goal to explore</legend>'+['Home down payment','Retirement accounts'].map((label,i)=>
      '<label><input type="radio" name="futureGoal" data-studio="studioView" value="'+i+'" '+(values.studioView===i?'checked':'')+'><span>'+label+'</span></label>').join('')+
    '</fieldset><div id="studioPanel">'+studioPanel()+'</div><div class="sr" id="studioStatus" role="status"></div></section>';
}
function changeStudio(input) {
  const key = input.dataset.studio;
  const v = input.type==='checkbox' ? Number(input.checked) : Number(input.value);
  if (!studioValid(key,v)) return;
  values[key]=v; dirty=true; notify();
  $('setting-' + key).textContent = calculatorSetting(key);
  if (key==='studioView' || key==='holding') {
    $('studioPanel').innerHTML=studioPanel();
    if (key==='holding') $('s-holding').focus();
  } else {
    const label=$('out-'+key);
    if(label){label.textContent=studioUnit(key,v);input.setAttribute('aria-valuetext',label.textContent);}
    const compareOpen = $('studioResults').querySelector('details')?.open;
    $('studioResults').innerHTML=values.studioView?retirementResults(values):houseResults(values);
    const comparison = $('studioResults').querySelector('details');
    if (comparison && compareOpen) comparison.open=true;
  }
}
function studioValid(key,v) {
  if (!Object.hasOwn(studioFields,key)) return false;
  const [,,min,max,stepSize]=studioFields[key];
  return Number.isInteger(v) && v>=min && v<=max && (v-min)%stepSize===0;
}

function investingLab() {
  const rates = [-5, 0, 5].map(rate => '<label><input type="radio" name="exampleRate" value="' + rate + '"' +
    (values.labRate === rate ? ' checked' : '') + '><span>' + rate + '%</span></label>').join('');
  return '<details class="disclosure fold" id="labDetails"><summary>Explore a small investing example</summary><div class="fold-body">' +
    '<p>Change the numbers to compare deposits with a hypothetical investment. This example is separate from your monthly plan.</p>' +
    '<div class="lab-grid"><div class="lab-controls">' +
    '<div><label class="lab-label" for="labMonthly">Monthly deposit · <span id="monthlyLabel"></span></label><input id="labMonthly" type="range" min="0" max="100" value="' + values.labMonthly + '"></div>' +
    '<div><label class="lab-label" for="labYears">Time · <span id="yearsLabel"></span></label><input id="labYears" type="range" min="1" max="40" value="' + values.labYears + '"></div>' +
    '<fieldset><legend class="lab-label">Hypothetical annual return</legend><div class="rate-options">' + rates + '</div></fieldset></div>' +
    '<div id="labResult" aria-live="polite"></div></div>' +
    '<p>Returns can be negative. Each example assumes a constant annual return, monthly compounding and deposits at month-end. It excludes fees, taxes and inflation.</p>' +
    help('Saving, investing and compounding', '<p>Saving keeps money accessible for a bill or a goal coming up soon. Investing puts money into assets that can gain or lose value. A near-term deadline leaves less time to recover from losses.</p><p>Compounding means later gains or losses also apply to earlier ones. Try the same deposit at 0% and 5%, then change the number of years.</p><p>A stock is ownership in a company. A bond is a loan. A fund can hold many investments. Spreading money across investments can reduce concentration risk, although losses are still possible.</p>') + '</div></details>';
}
function drawLab() {
  $('monthlyLabel').textContent = money(values.labMonthly);
  $('yearsLabel').textContent = values.labYears + (values.labYears === 1 ? ' year' : ' years');
  const paid = values.labMonthly * values.labYears * 12;
  const result = futureValue(values.labMonthly, values.labYears, values.labRate);
  const max = Math.max(cents(result), cents(paid));
  $('labResult').innerHTML = '<span class="subtle">Hypothetical ending value</span><strong class="lab-value">' + money(result) +
    '</strong>' + meter('Your deposits', cents(paid), max) + meter('Ending value', cents(result), max, true);
  $('labMonthly').setAttribute('aria-valuetext', money(values.labMonthly) + ' per month');
  $('labYears').setAttribute('aria-valuetext', $('yearsLabel').textContent);
}
function answerRows(rows) {
  return '<dl class="answer-list">' + rows.map(([label, value, id]) =>
    '<div><dt>' + escapeText(label) + '</dt><dd' + (id ? ' id="setting-' + id + '"' : '') + '>' +
    (value === null || value === '' ? '<span class="unanswered">Not entered</span>' : escapeText(value)) +
    '</dd></div>').join('') + '</dl>';
}
function calculatorSetting(key) {
  const v = values[key];
  switch (key) {
    case 'weekly': return money(v) + ' per week';
    case 'labMonthly': return money(v);
    case 'labYears': return v + (v === 1 ? ' year' : ' years');
    case 'labRate': return v + '%';
    case 'studioView': return v ? 'Retirement accounts' : 'Home down payment';
    case 'marketDrop': return v ? 'On' : 'Off';
    case 'holding': return assets[v].name;
    default: return studioUnit(key, v);
  }
}
function calculatorReview() {
  const labels = {weekly: 'Weekly savings example', labMonthly: 'Monthly deposit', labYears: 'Time invested',
    labRate: 'Assumed annual return', studioView: 'Selected future goal'};
  const sections = [
    ['Examples', ['weekly', 'studioView']],
    ['Small investing example', ['labMonthly', 'labYears', 'labRate']],
    ['Home down payment', ['homePrice', 'downPct', 'buyYears', 'collegeDeposit', 'laterDeposit', 'semesters', 'startCash', 'marketDrop']],
    ['Retirement accounts', ['payBudget', 'retireYears', 'holding', 'taxNow', 'taxLater']],
    ['Assumed annual returns', ['cashRate', 'bondRate', 'stockRate']]
  ];
  return '<details class="disclosure calculator-review"><summary>Calculator settings</summary><p>These examples include the starting settings for any controls you haven’t changed.</p><div class="answer-grid">' +
    sections.map(([title, keys]) => '<section><h3>' + title + '</h3>' +
      answerRows(keys.map(key => [labels[key] || studioFields[key][0], calculatorSetting(key), key])) + '</section>').join('') +
    '</div></details>';
}
function answerReview() {
  const v = values;
  const amount = key => v[key] == null ? null : money(v[key]);
  const duration = (key, unit) => v[key] == null ? null : v[key] + ' ' + unit + (v[key] === 1 ? '' : 's');
  const sections = [
    [['Monthly take-home pay', amount('income')], ['Other monthly support', amount('support')],
      ['Income changes month to month', v.stable === options.stable[1] ? 'Yes' : v.stable ? 'No' : 'Not marked'],
      ['Year in school', v.year], ['Living situation', v.home], ['Work situation', v.work]],
    [['Monthly essentials', amount('essentials')], ['Monthly flexible spending', amount('flex')],
      ['Monthly required debt payments', amount('minimum')]],
    [['Checking and savings', amount('cash')], ['Cash already committed', amount('reserved')],
      ['Emergency cushion target', amount('cushion')]],
    [['Carry high-interest debt?', ['No', 'Yes', 'I’m not sure'][options.debt.indexOf(v.debt)]],
      ['Balance after minimums', v.debt === options.debt[1] ? amount('balance') : 'Not applicable']],
    [['Goal', shortLabels[v.short]], ['Goal amount', v.short === options.short[0] ? amount('cushion') + ' (cushion target)' : amount('target')],
      ['Time until goal', duration('months', 'month')]],
    [['Goal', v.long], ['Time until goal', duration('years', 'year')], ['Comfort with investment risk', v.loss]],
    [['Saving pace', v.pace], ['Share of money left after bills', paceRates[v.pace] + '%']]
  ];
  if (v.knowledge) sections[5].push(['Investing experience', v.knowledge]);
  return '<section class="paper-card answer-review" aria-labelledby="answersTitle"><h2 id="answersTitle" tabindex="-1">' +
    (example ? 'Example answers' : 'Your answers') + '</h2><div class="answer-grid">' +
    sections.map((rows, i) => '<section><div class="answer-heading"><h3>' + escapeText(editLabels[i]) +
      '</h3><button type="button" class="answer-edit" data-edit="' + i + '" aria-label="Edit ' +
      escapeText(editLabels[i]) + '">Edit</button></div>' + answerRows(rows) + '</section>').join('') +
    '</div>' + calculatorReview() + '</section>';
}
function showPlan(openLab = false) {
  const missing = firstIncomplete();
  if (missing >= 0) { showStep(missing); return; }
  step = steps.length; started = true; editing = false; editBackup = null; showScreen('plan'); notify();
  const m = planMath();
  const profile = [values.year, values.home, values.work].filter(Boolean).join(' · ');
  $('overview').innerHTML = '<div class="report-head"><div><h1 id="planTitle" tabindex="-1">' +
    (example ? 'Sample plan' : 'Your plan') + '</h1>' + (example ? '<p>Fictional UK student · editable amounts</p>' :
      profile ? '<p>' + escapeText(profile) + '</p>' : '') + '</div><div class="report-actions">' +
    (example ? '<button class="primary" data-action="startOwn" type="button">Build my own plan</button>' : '') +
    '<a class="answer-jump" href="#answersTitle">Review answers</a>' +
    '<button class="secondary" data-action="print" type="button">Print plan</button></div></div>' +
    actionCard(m) + '<div class="report-grid">' + cashCard(m) + goalCard(m) + '</div>' +
    goalStudio() + investingLab() + mathDetails(m) + answerReview();
  drawLab();
  $('labDetails').open = openLab;
  focusHeading('planTitle');
}
$('overview').addEventListener('input', event => {
  const input = event.target;
  if (input.dataset && input.dataset.studio) { changeStudio(input); return; }
  if (input.name === 'exampleRate') values.labRate = Number(input.value);
  else if (input.id === 'labMonthly' || input.id === 'labYears') values[input.id] = input.valueAsNumber;
  else return;
  const key = input.name === 'exampleRate' ? 'labRate' : input.id;
  $('setting-' + key).textContent = calculatorSetting(key);
  dirty = true; notify(); drawLab();
});
$('overview').addEventListener('click', event => {
  const button = event.target.closest('button');
  if (!button) return;
  if (button.dataset.edit !== undefined) showStep(Number(button.dataset.edit), true);
  if (button.dataset.action === 'startOwn') replaceAfterCheck(() => startPlan(false));
  if (button.dataset.action === 'print') window.print();
});

function startPlan(sample) {
  const weekly = values.weekly;
  values = {...(sample ? sampleValues : defaultValues), weekly}; example = sample;
  dirty = !started && dirty; started = true; editing = false; notify();
  if (sample) showPlan(); else showStep(0);
}
function replaceAfterCheck(action) {
  if (!dirty) { action(); return; }
  pendingReplacement = action;
  $('replaceDialog').showModal();
}
$('keepDraft').addEventListener('click', () => $('replaceDialog').close());
$('replaceDraft').addEventListener('click', () => {
  const action = pendingReplacement; pendingReplacement = null; $('replaceDialog').close(); if (action) action();
});
$('replaceDialog').addEventListener('close', () => { pendingReplacement = null; });
$('homeButton').addEventListener('click', () => { if (currentValid(true)) { notify(); showHome(); } });
$('start').addEventListener('click', () => {
  if (!started) startPlan(false); else if (step === steps.length) showPlan(); else showStep(step, editing);
});
$('sample').addEventListener('click', () => {
  if (!started) startPlan(true);
  else replaceAfterCheck(() => startPlan(false));
});
$('houseExample').addEventListener('click', () => {
  startPlan(true);
  $('studioTitle').focus({preventScroll:true});
  $('studioTitle').scrollIntoView({block:'start'});
});
$('overview').addEventListener('change', event => {
  if (!event.target.dataset.studio) return;
  if (values.studioView) {
    const p=iraProjection(values);
    $('studioStatus').textContent='After tax: Roth '+money(p.roth)+', traditional '+money(p.traditional)+'.';
  } else {
    const m=housingProjection(values);
    $('studioStatus').textContent='Target '+money(m.target)+'. '+m.paths.map(p=>p.asset.name+' '+money(p.balance)).join(', ')+'.';
  }
});
function drawWeekly(amount) {
  for (const radio of document.querySelector('.week-options').querySelectorAll('input')) radio.checked = Number(radio.value) === amount;
  $('weeklyTotal').textContent = money(amount * 52);
  // Week zero is the starting balance. Each vertical step is one end-of-week deposit.
  let line = 'M1 76';
  for (let week = 1; week <= 52; week++) {
    const x = 1 + 358 * week / 52, y = 76 - 68 * week / 52;
    line += 'H' + x.toFixed(2) + 'V' + y.toFixed(2);
  }
  $('weekLine').setAttribute('d', line);
  $('weekArea').setAttribute('d', line + 'V76Z');
}
document.querySelector('.week-options').addEventListener('change', event => {
  values.weekly = Number(event.target.value);
  drawWeekly(values.weekly);
  dirty = true;
  $('savePlan').hidden = false;
});

function invalidFile(message = 'Choose a valid Beyond the Blue plan file.') { throw new Error(message); }
function readLegacyBudget(data) {
  const s = data.values;
  const moneyKeys = ['cash', 'income', 'support', 'housing', 'food', 'transport', 'other', 'payment', 'debt', 'oneoff',
    'job', 'living', 'postpay', 'moving', 'extraCost', 'target', 'saved', 'contribution', 'initial', 'monthly'];
  if (data.version === 2) moneyKeys.push('retIncome', 'retCosts');
  function within(k, min, max, integer = false) {
    return typeof s[k] === 'number' && Number.isFinite(s[k]) && s[k] >= min && s[k] <= max && (!integer || Number.isInteger(s[k]));
  }
  if (moneyKeys.some(k => !within(k, 0, 100000000)) || !within('delay', 0, 24, true) || !within('extraDelay', 0, 24, true) ||
      !within('years', 1, 50, true) || !within('rate', -50, 30) || !within('inflation', 0, 20)) invalidFile();
  for (const k of ['start', 'grad']) {
    if (typeof s[k] !== 'string' || !/^\d{4}-(0[1-9]|1[0-2])$/.test(s[k]) || s[k] < '2020-01' || s[k] > '2100-12') invalidFile();
  }
  const round = value => Math.round(value * 100) / 100;
  return {
    state: {...defaultValues, cash: round(s.cash), income: round(s.income), support: round(s.support),
      essentials: round(s.housing + s.food + s.transport + s.other), minimum: round(s.payment), target: round(s.target)},
    step: 0, example: false, message: 'Older plan imported. Review the questions. Your cash, monthly totals and goal amount carried over.'
  };
}
function readPlan(data) {
  if (!data || data.app !== 'beyond-the-blue' || !data.values || typeof data.values !== 'object' || Array.isArray(data.values)) invalidFile();
  if (data.welcomeOnly !== undefined && (typeof data.welcomeOnly !== 'boolean' || (data.welcomeOnly && (data.version !== 4 || data.step !== 0 || data.example !== false)))) invalidFile();
  if (data.version === 1 || data.version === 2) return readLegacyBudget(data);
  const old = data.version === 3;
  if ((!old && data.version !== 4) || data.journey !== 'uk-student') invalidFile('This plan version is not supported.');
  if (!Number.isInteger(data.step) || data.step < 0 || data.step > (old ? 11 : steps.length)) invalidFile('The saved step is invalid.');
  if (!old && typeof data.example !== 'boolean') invalidFile();
  const result = {};
  for (const key of Object.keys(defaultValues)) {
    const v = data.values[key];
    if (key === 'weekly') {
      if (v !== undefined && ![5,10,25].includes(v)) invalidFile('Invalid weekly savings amount.');
      result.weekly = v ?? 5;
      continue;
    }
    if (Object.hasOwn(studioDefaults,key)) {
      if (v === undefined || old) result[key] = studioDefaults[key];
      else if (studioValid(key,v)) result[key] = v;
      else invalidFile('A future-goal setting is invalid.');
      continue;
    }
    if (key in options) {
      if (v !== '' && !options[key].includes(v)) invalidFile('The plan contains an invalid choice.');
      if (old && key === 'short' && v === 'Extra cash savings') invalidFile();
      result[key] = v;
    } else {
      if (old && (typeof v !== 'number' || !Number.isFinite(v) || (key !== 'labRate' && v < 0) || v > 1000000)) invalidFile();
      if (old && (key === 'cushion' && v < 1 || ['months','years','labMonthly','labYears'].includes(key) && !Number.isInteger(v))) invalidFile();
      let n = old && key === 'balance' && v === 0 ? null : v;
      if (old && typeof n === 'number') n = Math.round(n * 100) / 100;
      if (!validateNumber(key, n) || (['labMonthly', 'labYears', 'labRate'].includes(key) && n === null)) invalidFile('The plan contains an invalid number.');
      result[key] = n;
    }
  }
  if (old && result.debt !== options.debt[1]) result.balance = null;
  if (old && result.short === options.short[0] && result.target > 0) result.short = 'Extra cash savings';
  if (result.short === options.short[0]) result.target = null;
  if (stepIssue(2, result, true)) invalidFile('The reserved amount is larger than the cash balance.');
  if (old) {
    const required = [['year', 'home', 'work'], ['stable'], [], [], ['debt'], ['short'], ['long', 'loss'], ['pace'], ['knowledge'], [], []];
    for (let i = 0; i < data.step; i++) if (required[i].some(key => !result[key])) invalidFile('The saved plan is missing an earlier answer.');
  } else if (result.debt !== options.debt[1] && result.balance !== null) invalidFile();
  const next = old ? [0, 0, 1, 2, 3, 4, 5, 6, 7, 7, 7, 7][data.step] : data.step;
  for (let i = 0; i < next; i++) if (stepIssue(i, result)) invalidFile('The saved plan is missing an earlier answer.');
  if (old && next >= 3 && result.debt === options.debt[1] && result.balance > 0 && result.minimum > 0) {
    return {state: result, step: 3, example: false, message: 'Earlier plan opened. Check that your debt balance is the amount left after this month’s minimums. Your other answers are filled in.'};
  }
  return {state: result, step: next, example: old ? false : data.example, welcomeOnly: data.welcomeOnly === true, lab: old && data.step === 9,
    message: old ? 'Earlier plan opened in the updated guide.' : 'Saved plan opened.'};
}
function save() {
  if (!currentValid(true)) return;
  const data = {app: 'beyond-the-blue', version: 4, journey: 'uk-student', example, step, values};
  if (!started) data.welcomeOnly = true;
  // The same reader that reopens a draft validates the exact download payload.
  try { readPlan(data); } catch (error) { notify('Review your entries before saving. ' + error.message, true); return; }
  const file = new Blob([JSON.stringify(data, null, 2)], {type: 'application/json'});
  const url = URL.createObjectURL(file);
  const link = document.createElement('a');
  link.href = url; link.download = 'Beyond-the-Blue-student-plan.json';
  document.body.append(link); link.click(); link.remove();
  setTimeout(() => URL.revokeObjectURL(url), 30000);
  dirty = false;
  if (editing && editBackup) editBackup.dirty = true;
  notify('Plan download requested. Use Open plan to return to it.');
}
async function loadFile(event) {
  const file = event.target.files[0];
  if (!file) return;
  const request = ++openRequest;
  event.target.value = '';
  try {
    if (file.size > 150000) invalidFile('This file is too large to be a plan.');
    let parsed;
    const text = await file.text();
    try { parsed = JSON.parse(text); } catch { invalidFile('Choose a plan saved as a .json file.'); }
    const incoming = readPlan(parsed);
    if (request !== openRequest) return;
    // No live values are changed until the whole file is validated and the user agrees.
    replaceAfterCheck(() => {
      values = incoming.state; dirty = false; started = true; example = incoming.example;
      drawWeekly(values.weekly);
      if (incoming.welcomeOnly) { started = false; step = 0; editing = false; editBackup = null; showHome(); }
      else if (incoming.step === steps.length) showPlan(incoming.lab); else showStep(incoming.step);
      notify(incoming.message);
    });
  } catch (error) {
    if (request === openRequest) notify('Couldn’t open this file. ' + error.message + ' Your current plan is intact.', true);
  }
}
$('savePlan').addEventListener('click', save);
$('openPlan').addEventListener('click', () => $('planFile').click());
$('planFile').addEventListener('change', loadFile);
document.addEventListener('keydown', event => {
  if ((started || dirty) && (event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') { event.preventDefault(); save(); }
});
window.addEventListener('beforeunload', event => {
  if (dirty) { event.preventDefault(); event.returnValue = true; }
});
drawWeekly(5);
showHome(false);
</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
  • studentsuccess.uky.edu
  • www.consumerfinance.gov
  • www.investor.gov
  • www.irs.gov

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 Andrew Escamilla. 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.